diff --git "a/4370.jsonl" "b/4370.jsonl" new file mode 100644--- /dev/null +++ "b/4370.jsonl" @@ -0,0 +1,279 @@ +{"seq_id":"39383518401","text":"\nimport json\nimport logging\nfrom datetime import datetime\nfrom json import JSONDecodeError\nfrom typing import Dict, Optional\n\nimport requests\n\nfrom .dumper import Dumper\nfrom .exceptions import SolarLogError\n\nlog = logging.getLogger('slmon.solarlogclient')\n\n\nclass SolarLogClient:\n '''\n Represents the Solar-Log™ device. Provides a abstraction of the device and provides session handling.\n\n :param username: The username to log in (e.g. `user`)\n :param password: The password to log in\n :param host: The host to connect to\n :param login: Whether to log in and try to maintain a session.\n :param dumper: Optional dumper that, when set, dumps the retrieved data as soon as possible.\n '''\n\n _username: Optional[str]\n _password: Optional[str]\n _host: str\n _schema: str\n\n _s: requests.Session\n _logged_in: bool\n #: Session token\n _token: str\n _dumper: Optional[Dumper]\n\n _login_url: str\n _getjp_url: str\n\n # data obtained from the device\n\n _sl_revision: Optional[int]\n\n # logcheck\n _sl_logcheck_logged_in: int\n _sl_logcheck_login_level: int\n _sl_logcheck_access_level: int\n\n _timeout = (5, 5)\n\n # pylint: disable=too-many-arguments\n def __init__(self, host: str, login: bool, username: Optional[str] = None, password: Optional[str] = None,\n dumper: Optional[Dumper] = None) -> None:\n self._username = username\n self._password = password\n self._host = host\n self._login = login\n self._token = ''\n self._dumper = dumper\n self._sl_revision = None\n\n self._s = requests.Session()\n\n self._schema = 'http'\n self._login_url = f'{self._schema}://{self._host}/login'\n self._getjp_url = f'{self._schema}://{self._host}/getjp'\n\n self.init_session()\n\n def dump(self, filename: str, data: str) -> None:\n '''\n If the dumper is available, hands of the data to be dumped.\n\n :param filename: The name of the file to dump into. The dumper adds a timestamp and the json extension on it\n own.\n :param data: The data to dump.\n '''\n if self._dumper:\n self._dumper.dump(filename, data)\n\n @property\n def sl_revision(self) -> int:\n '''\n Returns the Solar-Log™ revision. If the revision has not been queried before, performs a query.\n\n :raises SolarLogError: If the query for the revision failed.\n '''\n if not self._sl_revision:\n return self.get_revision()\n return self._sl_revision\n\n def set_login(self, login: bool) -> None:\n '''\n Controls whether the client tries to log in before the next request if it detects that it is not logged in.\n This can be set to `False` before accessing the Solar-Log™ with a webbrowser as it does not allow more than one\n active session and the client would kick the user out of the session each time it is called.\n '''\n self._login = login\n\n @property\n def login(self) -> bool:\n '''\n Returns whether the client performs a login if it detects that its session has ended.\n '''\n return self._login\n\n @property\n def logged_in(self) -> bool:\n '''\n Returns whether the client thinks that its session is valid. This value is updated on querying the data logger.\n '''\n return self._logged_in\n\n def init_session(self) -> None:\n '''\n Initializes the requests session\n '''\n self._logged_in = False\n self._s.cookies.set('banner_hidden', 'false')\n\n def init_data(self) -> None:\n '''\n Initializes internal data structures, should be called after a reconnect.\n '''\n self._sl_revision = None\n self._sl_logcheck_logged_in = 0\n self._sl_logcheck_login_level = 0\n self._sl_logcheck_access_level = 0\n\n def do_login(self) -> bool:\n '''\n Performs the login action. Updates the internal `_logged_in` value and returns whether it was successful.\n\n :return: Whether it was successful.\n '''\n log.debug(f'do_login _login: {self._login} _logged_in: {self._logged_in}')\n if self._username is None or self._password is None:\n log.error('Can\\'t log in, username and/or password not set')\n elif self._login:\n if self._logged_in:\n self.handle_logout()\n\n log.info(f'Performing login as user \"{self._username}\"')\n login_resp = self._s.post(self._login_url, data={'u': self._username, 'p': self._password},\n timeout=self._timeout)\n if login_resp.status_code != 200:\n log.warning(f'Login failed: {login_resp.status_code} \"{login_resp.text}\"')\n elif 'SUCCESS' in login_resp.text:\n log.debug(f'do_login resp: {login_resp.text} cookies: {login_resp.cookies}')\n try:\n self._token = login_resp.cookies['SolarLog']\n except KeyError:\n log.error('Could not find \"SolarLog\" cookie')\n else:\n log.info(f'Logged in to the solarlog at {self._host}')\n self._logged_in = True\n elif 'FAILED' in login_resp.text:\n if '(password)' in login_resp.text:\n log.warning('Logging in failed: password')\n else:\n log.warning(f'Logging in failed: \"{login_resp.text}\"')\n log.info(f'do_login: logged_in = {self._logged_in}')\n return self._logged_in\n\n def handle_logout(self) -> None:\n '''\n Performs the neccessary steps to return to a clean, not logged-in state. This is used when the client detects\n that the server does not consider its session valid anymore.\n '''\n log.info('Handling logout')\n self._logged_in = False\n self._token = ''\n\n def getjp(self, data: str) -> requests.Response:\n '''\n Low-level function to access the ``getjp`` endpoint of the Solar-Log™ device. If the JSON response contains the\n words ``ACCESS DENIED``, then the logout handler is triggered.\n\n :param data: The query string. If logged in, the token will automatically be prepended.\n :return: The response object.\n '''\n headers = {\n 'Content-Type': 'application/json',\n }\n log.debug(f'token: {self._token}')\n\n if not self._logged_in:\n log.debug('getjp: not logged in')\n if self._login:\n log.debug('getjp: logging in')\n self.do_login()\n resp = self._s.post(self._getjp_url, data=f'token={self._token};{data}', headers=headers,\n timeout=self._timeout)\n else:\n resp = self._s.post(self._getjp_url, data=data, headers=headers, timeout=self._timeout)\n else:\n resp = self._s.post(self._getjp_url, data=f'token={self._token};{data}', headers=headers,\n timeout=self._timeout)\n self.dump('getjp', resp.text)\n if '\"ACCESS DENIED\"' in resp.text:\n self.handle_logout()\n resp.raise_for_status()\n return resp\n\n def get_revision(self) -> int:\n '''\n Queries the device for the current revision number.\n '''\n resp = self._s.get(f'{self._schema}://{self._host}/revision.html',\n params={'_': int(datetime.now().timestamp() * 1000)})\n if resp.status_code == 200:\n try:\n rev = int(resp.text)\n except ValueError as exc:\n msg = 'Revision: not a valid integer'\n log.error(msg)\n raise SolarLogError(msg) from exc\n\n if rev < 1000:\n msg = f'Revision: sanity check failed, not a valid revision: {rev}'\n log.error(msg)\n raise SolarLogError(msg)\n self._sl_revision = rev\n else:\n raise SolarLogError(f'Failed to get content: {resp.status_code} {resp.text}')\n return self._sl_revision\n\n def get_open_json(self) -> Dict:\n '''\n Requests the \"Open JSON\" output. This does not require a login. The keys are converted to integers on the fly.\n '''\n resp = self.getjp('{\"801\":{\"100\":null,\"170\":null}}')\n if resp.status_code != 200:\n raise SolarLogError(f'OpenJSON: Unexpected status code {resp.status_code}')\n log.debug(resp.text)\n return json.loads(resp.text, object_hook=lambda d: {\n int(k): [int(i) for i in v] if isinstance(v, list) else v for k, v in d.items()})\n\n def get_lcd(self) -> Dict:\n '''\n Queries for the current set of LCD data and returns the result as a dict. This function works without valid\n login.\n '''\n lcd_resp = self.getjp('{\"701\":null,\"794\":{\"0\":null}}')\n if lcd_resp.status_code != 200:\n raise SolarLogError(f'LCD: Unexpected status code {lcd_resp.status_code}')\n try:\n return lcd_resp.json()\n except JSONDecodeError as exc:\n raise SolarLogError(f'Could not parse json response: {str(exc)}') from exc\n\n def do_logcheck(self) -> None:\n '''\n Checks the login and access state. The data is stored internally.\n\n :raises SolarLogError: If querying failed or the data is not parseable.\n '''\n logcheck_resp = self._s.get(f'{self._schema}://{self._host}/logcheck',\n params={'_': int(datetime.now().timestamp() * 1000)})\n if logcheck_resp.status_code == 200:\n data = logcheck_resp.text.split(';')\n if len(data) != 3:\n raise SolarLogError(f'logcheck: got invalid data: {logcheck_resp.text}')\n self._sl_logcheck_logged_in = int(data[0])\n self._sl_logcheck_login_level = int(data[1])\n self._sl_logcheck_access_level = int(data[2])\n else:\n raise SolarLogError(f'logcheck: got unexpected status code {logcheck_resp.status_code}')\n","repo_name":"svalouch/slmon","sub_path":"src/slmon/solarlogclient.py","file_name":"solarlogclient.py","file_ext":"py","file_size_in_byte":10174,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"18168733778","text":"import csv\nimport sys\nimport os\nfrom fpdf import FPDF\n\ndef download_csv(user, fields, rows, tipo):\n if tipo == 1:\n filename = \"historial_visitas_{0}.csv\".format(user)\n with open(filename, 'w') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(fields)\n csvwriter.writerows(rows)\n\ndef download_pdf(user, fields, rows, tipo):\n pdf = FPDF(orientation = 'L')\n pdf.add_page()\n pdf.set_font('Arial', 'B', 12)\n header = \"| \"\n for x in fields:\n header = header + x + ' | '\n pdf.cell(0, 10, txt = header, ln = 1, align = 'C')\n pdf.set_font(\"Arial\", size = 12)\n for l in rows:\n r = \"| \"\n for x in l:\n r = r + str(x) + ' | '\n pdf.cell(0, 10, txt = r, ln = 1, align = 'C')\n if tipo == 1:\n filename = \"historial_visitas_{0}.pdf\".format(user)\n pdf.output(filename)\n","repo_name":"suribe06/Software_Testing_Project","sub_path":"download_files.py","file_name":"download_files.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"8684735369","text":"\"\"\"\r\nSTATUS: Code is working. ✅\r\n\"\"\"\r\n\r\n\"\"\"\r\nGNU General Public License v3.0\r\n\r\nCopyright (C) 2022, SOME-1HING [https://github.com/SOME-1HING]\r\n\r\nCredits:-\r\n I don't know who originally wrote this code. If you originally wrote this code, please reach out to me. \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, either version 3 of the License, or\r\n(at your option) any later version.\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\n\r\nimport speedtest\r\nfrom Shikimori import DEV_USERS, dispatcher\r\nfrom Shikimori.modules.disable import DisableAbleCommandHandler\r\nfrom Shikimori.modules.helper_funcs.chat_status import dev_plus\r\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, Update\r\nfrom telegram.ext import CallbackContext, CallbackQueryHandler\r\n\r\n\r\ndef convert(speed):\r\n return round(int(speed) / 1048576, 2)\r\n\r\n\r\n@dev_plus\r\ndef speedtestxyz(update: Update, context: CallbackContext):\r\n buttons = [\r\n [\r\n InlineKeyboardButton(\"Image\", callback_data=\"speedtest_image\"),\r\n InlineKeyboardButton(\"Text\", callback_data=\"speedtest_text\"),\r\n ],\r\n ]\r\n update.effective_message.reply_text(\r\n \"Select SpeedTest Mode\",\r\n reply_markup=InlineKeyboardMarkup(buttons),\r\n )\r\n\r\n\r\ndef speedtestxyz_callback(update: Update, context: CallbackContext):\r\n query = update.callback_query\r\n\r\n if query.from_user.id in DEV_USERS:\r\n msg = update.effective_message.edit_text(\"Running a speedtest....\")\r\n speed = speedtest.Speedtest()\r\n speed.get_best_server()\r\n speed.download()\r\n speed.upload()\r\n replymsg = \"SpeedTest Results:\"\r\n\r\n if query.data == \"speedtest_image\":\r\n speedtest_image = speed.results.share()\r\n update.effective_message.reply_photo(\r\n photo=speedtest_image,\r\n caption=replymsg,\r\n )\r\n msg.delete()\r\n\r\n elif query.data == \"speedtest_text\":\r\n result = speed.results.dict()\r\n replymsg += f\"\\nDownload: `{convert(result['download'])}Mb/s`\\nUpload: `{convert(result['upload'])}Mb/s`\\nPing: `{result['ping']}`\"\r\n update.effective_message.edit_text(replymsg, parse_mode=ParseMode.MARKDOWN)\r\n else:\r\n query.answer(\"You are required to join Kingdom Of Science to use this command.\")\r\n\r\n\r\nSPEED_TEST_HANDLER = DisableAbleCommandHandler(\r\n \"speedtest\", speedtestxyz, run_async=True\r\n)\r\nSPEED_TEST_CALLBACKHANDLER = CallbackQueryHandler(\r\n speedtestxyz_callback, pattern=\"speedtest_.*\", run_async=True\r\n)\r\n\r\ndispatcher.add_handler(SPEED_TEST_HANDLER)\r\ndispatcher.add_handler(SPEED_TEST_CALLBACKHANDLER)\r\n\r\n__mod_name__ = \"SpeedTest\"\r\n__command_list__ = [\"speedtest\"]\r\n__handlers__ = [SPEED_TEST_HANDLER, SPEED_TEST_CALLBACKHANDLER]\r\n","repo_name":"SOME-1HING/ShikimoriBot","sub_path":"Shikimori/modules/speed_test.py","file_name":"speed_test.py","file_ext":"py","file_size_in_byte":3260,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"24"} +{"seq_id":"16205700995","text":"# Author: Hasan Öztürk\n# Usage: python perturb.py --flair_model_dirpath --conll_dataset_dirpath \n# Example: python perturb.py python perturb.py --flair_model_dirpath /opt/kanarya/resources/flair_models/bertcustom_2020-01-09_02 --conll_dataset_dirpath /home/hasan.ozturk/kanarya-github/kanarya/data/de-da-te-ta.10E-4percent.conll.84max.dev\n# Note that we only take the last word w/ the de/da suffix into account.\n\nimport numpy as np\nfrom flair.models import SequenceTagger\nfrom flair.data import Sentence\nimport flair, torch\nimport sys\nimport argparse\nimport copy\nimport json\n\n#deda_pos = 0\n\nbert_vocab_tokens = set()\nbert_vocab_subtokens = set()\n\ndelta_p_dict = {}\n\nsentence_count = 0\n\n\n\n\ndef get_labels(to_tagged_string):\n\n\t\tlabels = []\n\t\ttokens = to_tagged_string.split()\n\t\tfor token in tokens:\n\t\t\tif token == \"\":\n\t\t\t\t# Remove the last \"O\" label !! I assumed that a prediction cannot start with a tag\n\t\t\t\tdel labels[-1]\n\t\t\t\t# Add tag\n\t\t\t\tlabels.append(\"B-ERR\")\n\t\t\telse:\n\t\t\t\tlabels.append(\"O\")\n\n\t\t# Add \"O\" label for dot\n\t\tlabels.append(\"O\")\n\t\treturn labels\n\n\ndef does_contain_deda(word):\n\tsuffixes = ['de','da','te','ta']\n\tif word[-2:] in suffixes:\n\t\treturn True\n\telse:\n\t\treturn False\n\n# This will be a more convinient but costly operation, let us not it for now.\ndef get_deda_pos(sentence):\n\tdeda_pos = 0\n\tfor idx, token in enumerate(sentence.tokens):\n\t\tif does_contain_deda(token.text):\n\t\t\tdeda_pos = idx\n\treturn deda_pos\n\n\ndef populate_vocab(params):\n\n\tbert_vocab_dirpath = params[\"bert_vocab_dirpath\"]\n\tglobal bert_vocab\n\n\tf = open(bert_vocab_dirpath, \"r\")\n\tfor line in f:\n\t\tline = line.strip() # Eliminate space chars\n\t\tif line[:2] == \"##\":\n\t\t\tbert_vocab_subtokens.add(line[2:])\n\t\t\t##print(\"Subtoken: \" + line[2:] + \" - \" + str(len(line[2:])))\n\t\telse:\n\t\t\tbert_vocab_tokens.add(line)\n\t\t\t##print(\"Token: \" + line + \" - \" + str(len(line)))\n\n\n\n\ndef div_dict(my_dict, dividend):\n\tfor i in my_dict:\n\t\tmy_dict[i] = my_dict[i] / dividend;\n\n# Should take an object of Sentence class, not string as an argument\ndef get_prob(sentence, pos):\n\n\tdeda_token = sentence.tokens[pos]\n\t##print(\"Token: \" + str(deda_token))\n\tlabel = deda_token.get_tag('ner') # Be careful, it returns \n\n\tvalue = label.value\n\n\tif value == 'B-ERR':\n\t\tscore = label.score\n\telse:\n\t\tscore = 1 - label.score\n\n\t##print(str(deda_token) + \": \" + str(label))\n\treturn score # float\n\n\n# Delete the last character of the preceding word\ndef perturb1(sentence, pos):\n\n\t# Preceding word\n\tperturbed_token_pos = max(0, pos-1)\n\tperturbed_sentence = copy.deepcopy(sentence)\n\ttoken = perturbed_sentence.tokens[perturbed_token_pos]\n\tif len(token.text) != 1:\n\t\ttoken.text = token.text[:-1]\n\t##print(\"Perturb 1: \" + str(perturbed_sentence))\n\treturn perturbed_sentence\n\n\n# Delete the first character of the preceding word\ndef perturb2(sentence, pos):\n\n\t# Preceding word\n\tperturbed_token_pos = max(0, pos-1)\n\tperturbed_sentence = copy.deepcopy(sentence)\n\ttoken = perturbed_sentence.tokens[perturbed_token_pos]\n\tif len(token.text) != 1:\n\t\ttoken.text = token.text[1:]\n\t##print(\"Perturb 2: \" + str(perturbed_sentence))\n\treturn perturbed_sentence\n\n# Capitalize the first character of the preceding word\ndef perturb3(sentence, pos):\n\n\t# Preceding word\n\tperturbed_token_pos = max(0, pos-1)\n\tperturbed_sentence = copy.deepcopy(sentence)\n\ttoken = perturbed_sentence.tokens[perturbed_token_pos]\n\ttoken.text = token.text.capitalize()\n\t##print(\"Perturb 3: \" + str(perturbed_sentence))\n\treturn perturbed_sentence\n\n# !!! If there is no word in the position where a word will be deleted, then we return delta_pi = 0, which might cause problems.\n\n# Remove the preceding word, if any\ndef perturb4(sentence, pos):\n\t\n\t# If there is a preceding word, then remove it. If not, do not perturb\n\tif pos > 0:\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\tdel perturbed_sentence.tokens[pos - 1]\n\t\t##print(\"Perturb 4: \" + str(perturbed_sentence))\n\t\treturn perturbed_sentence\n\telse:\n\t\t##print(\"Perturb 4: \" + str(sentence))\n\t\treturn sentence\n\n# Remove the two previous word, if any\ndef perturb5(sentence, pos):\n\t\n\t# If there is a word two before the deda_word, then remove it. If not, do not perturb\n\tif pos > 1:\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\tdel perturbed_sentence.tokens[pos - 2]\n\t\t##print(\"Perturb 5: \" + str(perturbed_sentence))\n\t\treturn perturbed_sentence\n\telse:\n\t\t##print(\"Perturb 5: \" + str(sentence))\n\t\treturn sentence\n\n\n\n# Remove the three previous word, if any\ndef perturb6(sentence, pos):\n\t\n\t# If there is a word three before the deda_word, then remove it. If not, do not perturb\n\tif pos > 2:\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\tdel perturbed_sentence.tokens[pos - 3]\n\t\t##print(\"Perturb 6: \" + str(perturbed_sentence))\n\t\treturn perturbed_sentence\n\telse:\n\t\t##print(\"Perturb 6: \" + str(sentence))\n\t\treturn sentence\n\n# Remove the following word, if any\ndef perturb7(sentence, pos):\n\t\n\t# If there is a following word, then remove it. If not, do not perturb\n\tif pos < (len(sentence.tokens) - 1):\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\tdel perturbed_sentence.tokens[pos + 1]\n\t\t##print(\"Perturb 7: \" + str(perturbed_sentence))\n\t\treturn perturbed_sentence\n\telse:\n\t\t##print(\"Perturb 7: \" + str(sentence))\n\t\treturn sentence\n\n# Remove the two following word, if any\ndef perturb8(sentence, pos):\n\t\n\t# If there is a word after 2 positions of deda_word, then remove it. If not, do not perturb\n\tif pos < (len(sentence.tokens) - 2):\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\tdel perturbed_sentence.tokens[pos + 2]\n\t\t##print(\"Perturb 8: \" + str(perturbed_sentence))\n\t\treturn perturbed_sentence\n\telse:\n\t\t##print(\"Perturb 8: \" + str(sentence))\n\t\treturn sentence\n\n# Remove the three following word, if any\ndef perturb9(sentence, pos):\n\t\n\t# If there is a word after 3 positions of deda_word, then remove it. If not, do not perturb\n\tif pos < (len(sentence.tokens) - 3):\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\tdel perturbed_sentence.tokens[pos + 3]\n\t\t##print(\"Perturb 9: \" + str(perturbed_sentence))\n\t\treturn perturbed_sentence\n\telse:\n\t\t##print(\"Perturb 9: \" + str(sentence))\n\t\treturn sentence\n\n# Remove the first and shortest common pattern (##subtoken) in the preceding word using BERT vocab\ndef perturb10(sentence, pos):\n\n\t# If there is a preceding word, then remove it. If not, do not perturb\n\tif pos > 0:\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\t\n\t\ttoken = perturbed_sentence.tokens[pos - 1]\n\t\tperturbed_token = perturb10_helper(token.text)\n\n\t\ttoken.text = perturbed_token\n\t\t\n\t\t\n\t\t#print(\"Perturb 10: \" + str(perturbed_sentence)+ \"\\n\")\n\t\treturn perturbed_sentence\n\telse:\n\t\t#print(\"Perturb 10: \" + str(sentence)+ \"\\n\")\n\t\treturn sentence\n\n\ndef perturb10_helper(word):\n\n\t# Careful w/ single chars\n\n\tfor idx in range(len(word)):\n\n\t\t# For now ignore single chars, since it seems like there is a problem in bert vocab\n\t\tif idx > 1:\n\t\t\tif word[:idx+1] in bert_vocab_subtokens:\n\t\t\t\tif len(word[idx+1:]) > 0:\n\t\t\t\t\t#print(\"Perturb 10: Word: \" + word + \" - \" + \"Found: \" + word[:idx+1] + \" - \" + \"Return: \" + word[idx+1:])\n\t\t\t\t\treturn word[idx+1:]\n\t#print(\"Could not find a pattern, returning the original word: \" + word)\n\treturn word\n\n\n# Keep the first and shortest common pattern (##subtoken) in the preceding word using BERT vocab and remove the rest\ndef perturb11(sentence, pos):\n\n\t# If there is a preceding word, then remove it. If not, do not perturb\n\tif pos > 0:\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\t\n\t\ttoken = perturbed_sentence.tokens[pos - 1]\n\t\tperturbed_token = perturb11_helper(token.text)\n\n\t\ttoken.text = perturbed_token\n\t\t\n\t\t\n\t\t#print(\"Perturb 11: \" + str(perturbed_sentence)+ \"\\n\")\n\t\treturn perturbed_sentence\n\telse:\n\t\t#print(\"Perturb 11: \" + str(sentence)+ \"\\n\")\n\t\treturn sentence\n\n\ndef perturb11_helper(word):\n\n\t# Careful w/ single chars\n\n\tfor idx in range(len(word)):\n\n\t\t# For now ignore single chars, since it seems like there is a problem in bert vocab\n\t\tif idx > 1:\n\t\t\tif word[:idx+1] in bert_vocab_subtokens:\n\t\t\t\tif len(word[idx+1:]) > 0:\n\t\t\t\t\t#print(\"Perturb 11: Word: \" + word + \" - \" + \"Found: \" + word[:idx+1] + \" - \" + \"Return: \" + word[:idx+1])\n\t\t\t\t\treturn word[:idx+1]\n\t#print(\"Could not find a pattern, returning the original word: \" + word)\n\treturn word\n\n\n# Remove the last and shortest common pattern (##subtoken) in the preceding word using BERT vocab\ndef perturb12(sentence, pos):\n\n\t# If there is a preceding word, then remove it. If not, do not perturb\n\tif pos > 0:\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\t\n\t\ttoken = perturbed_sentence.tokens[pos - 1]\n\t\tperturbed_token = perturb12_helper(token.text)\n\n\t\ttoken.text = perturbed_token\n\t\t\n\t\t\n\t\t#print(\"Perturb 12: \" + str(perturbed_sentence)+ \"\\n\")\n\t\treturn perturbed_sentence\n\telse:\n\t\t#print(\"Perturb 12: \" + str(sentence)+ \"\\n\")\n\t\treturn sentence\n\n\ndef perturb12_helper(word):\n\n\t# Careful w/ single chars\n\n\tfor idx in range(len(word)):\n\n\t\t# For now ignore single chars, since it seems like there is a problem in bert vocab\n\t\tif idx > 1:\n\t\t\t##print(word[-idx:])\n\t\t\tif word[-(idx+1):] in bert_vocab_subtokens:\n\t\t\t\tif len(word[idx+1:]) > 0:\n\t\t\t\t\t#print(\"Perturb 12: Word: \" + word + \" - \" + \"Found: \" + word[-(idx+1):] + \" - \" + \"Return: \" + word[:-(idx+1)] )\n\t\t\t\t\treturn word[:-(idx+1):]\n\n\t#print(\"Could not find a pattern, returning the original word: \" + word)\n\treturn word\n\n# Keep the last and shortest common pattern (##subtoken) in the preceding word using BERT vocab\ndef perturb13(sentence, pos):\n\n\t# If there is a preceding word, then remove it. If not, do not perturb\n\tif pos > 0:\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\t\n\t\ttoken = perturbed_sentence.tokens[pos - 1]\n\t\tperturbed_token = perturb13_helper(token.text)\n\n\t\ttoken.text = perturbed_token\n\t\t\n\t\t\n\t\t#print(\"Perturb 13: \" + str(perturbed_sentence)+ \"\\n\")\n\t\treturn perturbed_sentence\n\telse:\n\t\t#print(\"Perturb 13: \" + str(sentence)+ \"\\n\")\n\t\treturn sentence\n\n\ndef perturb13_helper(word):\n\n\t# Careful w/ single chars\n\n\tfor idx in range(len(word)):\n\n\t\t# For now ignore single chars, since it seems like there is a problem in bert vocab\n\t\tif idx > 1:\n\t\t\t##print(word[-idx:])\n\t\t\tif word[-(idx+1):] in bert_vocab_subtokens:\n\t\t\t\tif len(word[idx+1:]) > 0:\n\t\t\t\t\t#print(\"Perturb 13: Word: \" + word + \" - \" + \"Found: \" + word[-(idx+1):] + \" - \" + \"Return: \" + word[-(idx+1):] )\n\t\t\t\t\treturn word[-(idx+1):]\n\t\t\t\t\t\n\t#print(\"Could not find a pattern, returning the original word: \" + word)\n\treturn word\n\n\n# Remove the first and shortest common pattern (##subtoken) in the following word using BERT vocab\ndef perturb14(sentence, pos):\n\n\t# If there is a preceding word, then remove it. If not, do not perturb\n\tif pos < (len(sentence.tokens) - 1):\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\t\n\t\ttoken = perturbed_sentence.tokens[pos + 1]\n\t\tperturbed_token = perturb14_helper(token.text)\n\n\t\ttoken.text = perturbed_token\n\t\t\n\t\t\n\t\t#print(\"Perturb 14: \" + str(perturbed_sentence)+ \"\\n\")\n\t\treturn perturbed_sentence\n\telse:\n\t\t#print(\"Perturb 14: \" + str(sentence)+ \"\\n\")\n\t\treturn sentence\n\n\ndef perturb14_helper(word):\n\n\t# Careful w/ single chars\n\n\tfor idx in range(len(word)):\n\n\t\t# For now ignore single chars, since it seems like there is a problem in bert vocab\n\t\tif idx > 1:\n\t\t\tif word[:idx+1] in bert_vocab_subtokens:\n\t\t\t\tif len(word[idx+1:]) > 0:\n\t\t\t\t\t#print(\"Perturb 14: Word: \" + word + \" - \" + \"Found: \" + word[:idx+1] + \" - \" + \"Return: \" + word[idx+1:] )\n\t\t\t\t\treturn word[idx+1:]\n\t#print(\"Could not find a pattern, returning the original word: \" + word)\n\treturn word\n\n# Keep the first and shortest common pattern (##subtoken) in the following word using BERT vocab\ndef perturb15(sentence, pos):\n\n\t# If there is a preceding word, then remove it. If not, do not perturb\n\tif pos < (len(sentence.tokens) - 1):\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\t\n\t\ttoken = perturbed_sentence.tokens[pos + 1]\n\t\tperturbed_token = perturb15_helper(token.text)\n\n\t\ttoken.text = perturbed_token\n\t\t\n\t\t\n\t\t#print(\"Perturb 15: \" + str(perturbed_sentence)+ \"\\n\")\n\t\treturn perturbed_sentence\n\telse:\n\t\t#print(\"Perturb 15: \" + str(sentence)+ \"\\n\")\n\t\treturn sentence\n\n\ndef perturb15_helper(word):\n\n\t# Careful w/ single chars\n\n\tfor idx in range(len(word)):\n\n\t\t# For now ignore single chars, since it seems like there is a problem in bert vocab\n\t\tif idx > 1:\n\t\t\tif word[:idx+1] in bert_vocab_subtokens:\n\t\t\t\tif len(word[idx+1:]) > 0:\n\t\t\t\t\t#print(\"Perturb 15: Word: \" + word + \" - \" + \"Found: \" + word[:idx+1] + \" - \" + \"Return: \" + word[:idx+1])\n\t\t\t\t\treturn word[:idx+1]\n\t#print(\"Could not find a pattern, returning the original word: \" + word)\n\treturn word\n\n# Remove the last and shortest common pattern (##subtoken) in the following word using BERT vocab\ndef perturb16(sentence, pos):\n\n\t# If there is a preceding word, then remove it. If not, do not perturb\n\tif pos < (len(sentence.tokens) - 1):\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\t\n\t\ttoken = perturbed_sentence.tokens[pos + 1]\n\t\tperturbed_token = perturb16_helper(token.text)\n\n\t\ttoken.text = perturbed_token\n\t\t\n\t\t\n\t\t#print(\"Perturb 16: \" + str(perturbed_sentence)+ \"\\n\")\n\t\treturn perturbed_sentence\n\telse:\n\t\t#print(\"Perturb 16: \" + str(sentence)+ \"\\n\")\n\t\treturn sentence\n\n\ndef perturb16_helper(word):\n\n\t# Careful w/ single chars\n\n\tfor idx in range(len(word)):\n\n\t\t# For now ignore single chars, since it seems like there is a problem in bert vocab\n\t\tif idx > 1:\n\t\t\tif word[-(idx+1):] in bert_vocab_subtokens:\n\t\t\t\tif len(word[idx+1:]) > 0:\n\t\t\t\t\t#print(\"Perturb 16: Word: \" + word + \" - \" + \"Found: \" + word[-(idx+1):] + \" - \" + \"Return: \" + word[:-(idx+1)] )\n\t\t\t\t\treturn word[:-(idx+1):]\n\t#print(\"Could not find a pattern, returning the original word: \" + word)\n\treturn word\n\n# Keep the last and shortest common pattern (##subtoken) in the following word using BERT vocab\ndef perturb17(sentence, pos):\n\n\t# If there is a preceding word, then remove it. If not, do not perturb\n\tif pos < (len(sentence.tokens) - 1):\n\t\tperturbed_sentence = copy.deepcopy(sentence)\n\t\t\n\t\ttoken = perturbed_sentence.tokens[pos + 1]\n\t\tperturbed_token = perturb17_helper(token.text)\n\n\t\ttoken.text = perturbed_token\n\t\t\n\t\t\n\t\t#print(\"Perturb 17: \" + str(perturbed_sentence)+ \"\\n\")\n\t\treturn perturbed_sentence\n\telse:\n\t\t#print(\"Perturb 17: \" + str(sentence)+ \"\\n\")\n\t\treturn sentence\n\n\ndef perturb17_helper(word):\n\n\t# Careful w/ single chars\n\n\tfor idx in range(len(word)):\n\n\t\t# For now ignore single chars, since it seems like there is a problem in bert vocab\n\t\tif idx > 1:\n\t\t\tif word[-(idx+1):] in bert_vocab_subtokens:\n\t\t\t\tif len(word[idx+1:]) > 0:\n\t\t\t\t\t#print(\"Perturb 17: Word: \" + word + \" - \" + \"Found: \" + word[-(idx+1):] + \" - \" + \"Return: \" + word[-(idx+1):] )\n\t\t\t\t\treturn word[-(idx+1):]\n\t#print(\"Could not find a pattern, returning the original word: \" + word)\n\treturn word\n\n\n\n\nperturbation_functions = [perturb1, perturb2, perturb4, perturb5, perturb6, perturb7, perturb8, perturb9, perturb10, perturb11, perturb12, perturb13, perturb14, perturb15, perturb16, perturb17]\n\n\ndef create_dict():\n\t'''\n\tfor func in perturbation_functions:\n\t\tdelta_p_dict[str(func)] = 0\n\t'''\n\n\tfor func in perturbation_functions:\n\t\tdelta_p_dict[str(func)] = []\n\n\n\n# !!! OMIT ZEROS\n\ndef runner(params):\n\n\tflair.device = torch.device('cpu')\n\n\t#classifier_model = sys.argv[1]\n\tclassifier_model = params[\"flair_model_dirpath\"]\n\tconll_data = params[\"conll_dataset_dirpath\"]\n\n\tclassifier = SequenceTagger.load_from_file(classifier_model + '/best-model.pt')\n\n\ttrue_labels = []\n\tf = open(conll_data, \"r\")\n\n\tsentence = \"\"\n\tword_idx = 0 # 0 indexing\n\t#deda_pos = 0\n\tglobal deda_pos\n\tfor line in f:\n\t\ttokens = line.split()\n\t\tif(len(tokens) == 2):\n\n\t\t\t# Current word and label pair\n\t\t\tcurrent_word = tokens[0] \n\t\t\tcurrent_label = tokens[1]\n\n\t\t\t'''\n\t\t\t# Currently we only take the last word which contains de/da in a sentence !!\n\t\t\tif does_contain_deda(current_word):\n\t\t\t\tdeda_pos = word_idx\n\n\n\t\t\tword_idx += 1\n\n\t\t\t'''\n\t\t\ttrue_labels.append(current_label)\n\n\t\t\t# Check if it is the end of a sentence\n\t\t\tif(current_word == \".\"):\n\t\t\t\n\t\t\t\t# Construct the sentence\n\t\t\t\tsentence = sentence + current_word \n\n\t\t\t\t# Make a prediction\n\t\t\t\tsentence = Sentence(sentence)\n\t\t\t\tclassifier.predict(sentence)\n\n\t\t\t\t# Get the tagged string (does not include \"O\"s)\n\t\t\t\ttagged_string = sentence.to_tagged_string()\n\n\t\t\t\t# Get the labels for the sentence (does include \"O\"s)\n\t\t\t\tpredicted_labels = get_labels(tagged_string)\n\n\t\t\t\tdeda_pos = get_deda_pos(sentence)\n\t\t\t\tp0 = get_prob(sentence, deda_pos) \n\n\t\t\t\t##print(sentence)\n\t\t\t\tfor func in perturbation_functions:\n\t\t\t\t\tperturbed_sentence = func(sentence, deda_pos)\n\n\t\t\t\t\tclassifier.predict(perturbed_sentence)\n\n\t\t\t\t\tdeda_pos = get_deda_pos(sentence)\n\t\t\t\t\tpi = get_prob(perturbed_sentence, deda_pos)\n\n\t\t\t\t\tdelta_p = pi - p0\n\n\t\t\t\t\t##print(\"Delta_p for \" + str(func) + \": \" + str(delta_p))\n\t\t\t\t\t#delta_p_dict[str(func)] += delta_p\n\t\t\t\t\tdelta_p_dict[str(func)].append(delta_p)\n\n\t\t\t\t##print(\"=================================\")\n\t\t\t\t\n\n\t\t\t\tsentence = \"\"\n\t\t\t\tword_idx = 0\n\t\t\t\tglobal sentence_count\n\t\t\t\tsentence_count += 1\n\t\t\telse:\n\t\t\t\t# Construct the sentence\n\t\t\t\t# Careful: Sentence begins with a space !\n\t\t\t\tsentence = sentence + \" \" + current_word\n\n\ndef report():\n\n\t#global delta_p_dict\n\n print(\"Sentence Count: \" + str(sentence_count) + \"\\n\")\n\n print('{:<50s}{:<30s}{:<30s}{:<30s}'.format(\"Function\",\"Absolute Mean\", \"Direction\", \"Variance\"))\n for func in perturbation_functions:\n \t# Eliminate zeros (?)\n \tdelta_p_dict[str(func)] = [i for i in delta_p_dict[str(func)] if i != 0.0]\n\n \tmean = np.mean(delta_p_dict[str(func)])\n \tvar = np.var(delta_p_dict[str(func)])\n \tdirection = \"+\" if mean > 0 else \"-\"\n\n \ts = '{:<50s}{:<30s}{:<30s}{:<30s}'.format(str(func),str(abs(mean)), direction, str(var))\n \tprint(s)\n\n\n\ndef main():\n\n parser = argparse.ArgumentParser()\n\n # Default parameter values\n best_bert_model = '/opt/kanarya/resources/flair_models/bertcustom_2020-01-09_02'\n test_set = '/home/hasan.ozturk/kanarya-github/kanarya/data/de-da-te-ta.10E-4percent.conll.84max.test'\n bert_vocab_dirpath = '/opt/kanarya/resources/vocabs/vocab_whole_corpus_28996.txt'\n\n parser.add_argument(\"--conll_dataset_dirpath\", default=test_set)\n parser.add_argument(\"--flair_model_dirpath\", default=best_bert_model)\n parser.add_argument(\"--bert_vocab_dirpath\", default=bert_vocab_dirpath)\n\n args = parser.parse_args()\n\n conll_dataset_dirpath = args.conll_dataset_dirpath\n flair_model_dirpath = args.flair_model_dirpath\n\n params = {\n \t\"conll_dataset_dirpath\": conll_dataset_dirpath,\n \t\"flair_model_dirpath\": flair_model_dirpath,\n \t\"bert_vocab_dirpath\": bert_vocab_dirpath\n }\n\n populate_vocab(params)\n\n create_dict()\n runner(params)\n\n report()\n\n '''\n global delta_p_dict\n\n #print(\"Sentence Count: \" + str(sentence_count))\n\n div_dict(delta_p_dict, sentence_count)\n # Pretty #print\n #print (json.dumps(delta_p_dict, indent=4))\n '''\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"derlem/kanarya","sub_path":"perturbation/perturb.py","file_name":"perturb.py","file_ext":"py","file_size_in_byte":18867,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"24"} +{"seq_id":"39965486355","text":"import calendar as cal\nimport pandas as pd\n\nfrom hidrocomp.series.exceptions import StationError\nfrom hidrocomp.statistic.pearson3 import Pearson3\nfrom hidrocomp.series.series_build import SeriesBuild\nfrom hidrocomp.series.partial import Partial\nfrom hidrocomp.series.maximum import MaximumFlow\nfrom hidrocomp.series.minimum import MinimumFlow\nfrom hidrocomp.series.monthly_average import MonthlyAverageFlow\nfrom hidrocomp.eflow import IHA\nfrom hidrocomp.graphics import RatingCurve, HydrogramYear, HydrogramClean\n\n\nclass Flow(SeriesBuild):\n\n type_data = 'FLUVIOMÉTRICO'\n data_type = 'flow'\n\n def __init__(self, data=None, path_file=None, station=None, source=None, *args, **kwargs):\n super().__init__(data=data, path=path_file, station=station, source=source, data_type=self.type_data, *args,\n **kwargs)\n self.__month_num_flood = None\n self.__month_abr_flood = None\n self.__month_num_drought = None\n self.__month_abr_drought = None\n\n def _month_start_year_hydrologic(self):\n if self.__month_num_flood is None:\n if self.station is None:\n raise TypeError(\"Define a station!\")\n else:\n data = pd.DataFrame(self.data[self.station])\n mean_month = pd.DataFrame([data.loc[data.index.month == i].mean() for i in range(1, 13)])\n month_start_year_hydrologic = 1 + mean_month.idxmin().values[0]\n month_start_year_hydrologic_abr_flood = cal.month_abbr[month_start_year_hydrologic].upper()\n\n self.__month_num_flood = month_start_year_hydrologic\n self.__month_abr_flood = 'AS-%s' % month_start_year_hydrologic_abr_flood\n\n self.__month_num_drought = month_start_year_hydrologic - 6\n self.__month_abr_drought = 'AS-%s' % cal.month_abbr[self.__month_num_drought].upper()\n else:\n if self.__month_num_flood > 6:\n self.__month_num_drought = self.__month_num_flood - 6\n else:\n self.__month_num_drought = self.__month_num_flood + 6\n\n self.__month_abr_flood = 'AS-%s' % cal.month_abbr[self.__month_num_flood].upper()\n self.__month_abr_drought = 'AS-%s' % cal.month_abbr[self.__month_num_drought].upper()\n\n return self.__month_num_flood, self.__month_abr_flood, self.__month_num_drought, self.__month_abr_drought\n\n @property\n def month_num_flood(self) -> int:\n return self._month_start_year_hydrologic()[0]\n\n @month_num_flood.setter\n def month_num_flood(self, month: int):\n self.__month_num_flood = month\n\n @property\n def month_abr_flood(self) -> str:\n return self._month_start_year_hydrologic()[1]\n\n @property\n def month_num_drought(self) -> int:\n return self._month_start_year_hydrologic()[2]\n\n @property\n def month_abr_drought(self) -> str:\n return self._month_start_year_hydrologic()[3]\n\n def minimum(self) -> MinimumFlow:\n minimum = MinimumFlow(obj=self, station=self.station)\n\n return minimum\n\n def maximum(self) -> MaximumFlow:\n maximum = MaximumFlow(obj=self, station=self.station)\n\n return maximum\n\n def partial(self, threshold_type: str, events_type: str, criterion_type: str, threshold_value: float,\n **kwargs) -> Partial:\n partial = Partial(station=self.station, obj=self, type_threshold=threshold_type, type_event=events_type,\n type_criterion=criterion_type, value_threshold=threshold_value, **kwargs)\n\n return partial\n\n def simulation_withdraw(self, criterion, rate, months=None, value=None):\n if type(months) is not list and months is not None:\n raise TypeError\n\n if criterion == 'q90':\n data = self.data.copy()\n if value is None:\n withdraw = (self.quantile(percentile=0.1) * (rate / 100)).values[0]\n else:\n withdraw = (value * (rate / 100)).values[0]\n\n if months is None:\n name = \"withdraw_{}_{}_{}\".format(rate, criterion, 'all')\n data.rename(columns={self.station: name}, inplace=True)\n data = data - withdraw\n data.loc[data[name] < 0, name] = 0\n return data\n else:\n name = \"withdraw_{}_{}_{}\".format(rate, criterion, 'months')\n data.rename(columns={self.station: name}, inplace=True)\n for i in self.data[self.station].index:\n if i.month in months:\n data.at[i, name] = self.data[self.station][i] - withdraw\n data.loc[data[name] < 0, name] = 0\n return data\n else:\n return None\n\n def iha(self, status=None, date_start: str = None, date_end: str = None, statistic=\"no-parametric\",\n central_metric=\"mean\", month_water: int = None, variation_metric: str = \"std\", type_threshold=\"stationary\",\n type_criterion: str = None, threshold_high: float = None, threshold_low: float = None,\n aspects: list = None, magnitude: list = None, magnitude_and_duration: list = None, timing: list = None,\n frequency_and_duration: list = None, rate_and_frequency: list = None, **kwargs) -> IHA:\n \"\"\"\n @param rate_and_frequency:\n @param frequency_and_duration:\n @param timing:\n @param magnitude_and_duration:\n @param magnitude:\n @param aspects:\n @param status:\n @param date_start:\n @param date_end:\n @param statistic:\n @param central_metric:\n @param month_water:\n @param variation_metric:\n @param type_threshold:\n @param type_criterion:\n @param threshold_high:\n @param threshold_low:\n @return:\n \"\"\"\n iha = IHA(flow=self, month_water=month_water, status=status, date_start=date_start, date_end=date_end,\n statistic=statistic, central_metric=central_metric, variation_metric=variation_metric,\n type_threshold=type_threshold, type_criterion=type_criterion, threshold_high=threshold_high,\n threshold_low=threshold_low, aspects=aspects, magnitude=magnitude, timing=timing,\n frequency_and_duration=frequency_and_duration, rate_and_frequency=rate_and_frequency,\n magnitude_and_duration=magnitude_and_duration, **kwargs)\n return iha\n\n def power_energy(self, efficiency: int, gravity: float, hydraulic_head: float, station: str = None) -> pd.Series:\n if len(self.columns) > 1:\n if station is None:\n raise AttributeError(\"Station is None\")\n else:\n data = self.data[station]\n else:\n data = self.data\n const = efficiency * gravity * hydraulic_head\n pot = data.multiply(const)\n return pot\n\n def hydrogram(self, title, threshold=None, save=False, width=None, height=None, size_text=16, color=None):\n if self.station is None:\n hydrogram = HydrogramClean(data=self.data, threshold=threshold, width=width, height=height,\n size_text=size_text, title=title, color=color, data_type=self.data_type)\n fig, data = hydrogram.plot()\n else:\n hydrogram = HydrogramClean(data=self.data[self.station], threshold=threshold, width=width, height=height,\n size_text=size_text, title=title, color=color, data_type=self.data_type)\n fig, data = hydrogram.plot()\n return fig, data\n\n def hydrogram_year(self, title=\"\", threshold=None, width: int = None, height: int = None, size_text: int = 16,\n showlegend: bool = False, language: str = 'pt'):\n idx = [i for i in self.data.index if i.month == 2 and i.day == 29]\n data = self.data.drop(index=idx)\n data = data.groupby(pd.Grouper(freq=self.month_abr_flood))\n hydrogram = HydrogramYear(data=data, threshold=threshold, width=width, height=height, size_text=size_text,\n title=title, language=language, showlegend=showlegend, data_type=self.data_type)\n fig, data = hydrogram.plot()\n return fig, data\n\n def rating_curve(self, title=None, width=None, height=None, size_text=16):\n if self.station is None:\n raise StationError\n permanence = RatingCurve(self.data[self.station], width=width, height=height, size_text=size_text,\n title=title)\n fig, data = permanence.plot()\n return fig, data\n\n def get_month_name(self):\n months = {1: 'Janeiro', 2: 'Fevereiro', 3: 'Março', 4: 'Abril', 5: 'Maio', 6: 'Junho', 7: 'Julho', 8: 'Agosto',\n 9: 'Setembro', 10: 'Outubro', 11: 'Novembro', 12: 'Dezembro'}\n return months[self.month_num_flood]\n\n def flow_min(self, method: str = \"q95\"):\n\n if method == 'q7,10':\n qmin = self.data.rolling(7).mean().groupby(pd.Grouper(freq='AS-JAN')).min()\n prop = 1 / 10\n dist = Pearson3(qmin[self.station].values)\n dist.mml()\n return dist.values(prop)\n else:\n percent = int(method.split(\"q\")[1])\n return self.quantile((100-percent)/100)\n\n def base_flow(self, method: str = \"q90/q50\"):\n if method == \"q90/q50\":\n q50 = self.flow_min(method=\"q50\")[0]\n q90 = self.flow_min(method=\"q90\")[0]\n return round(q90/q50, 4)\n else:\n raise NameError(\"Method invalid!\")\n\n def monthly_average(self):\n monthly_average_flow = MonthlyAverageFlow(flow=self, station=self.station)\n return monthly_average_flow\n","repo_name":"clebsonpy/HidroComp","sub_path":"hidrocomp/series/flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":9802,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"24"} +{"seq_id":"42113039784","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 ('accounting', '0010_auto_20140921_2127'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='saving',\n name='user',\n ),\n migrations.DeleteModel(\n name='Saving',\n ),\n migrations.AddField(\n model_name='dailyexpenses',\n name='category',\n field=models.CharField(max_length=200, null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='monthlyexpenses',\n name='category',\n field=models.CharField(max_length=200, null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='monthlyincome',\n name='type',\n field=models.CharField(max_length=200, null=True, blank=True),\n preserve_default=True,\n ),\n ]\n","repo_name":"JohannaMW/accounts","sub_path":"accounting/migrations/0011_auto_20140921_2228.py","file_name":"0011_auto_20140921_2228.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"35019361835","text":"from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport sys\nsys.path.append(\".\")\nimport os\nimport time\n\nfrom PIL import Image\nfrom torch.autograd import Variable\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nfrom tqdm import tqdm\nimport math\nimport torch.nn.functional as F\n\nfrom copy import deepcopy\n\nfrom SparseImgRepresenter import ScaleSpaceAffinePatchExtractor\nfrom LAF import normalizeLAFs, denormalizeLAFs, LAFs2ell, abc2A, convertLAFs_to_A23format\nfrom Utils import line_prepender, batched_forward\nfrom architectures import AffNetFast\nfrom HardNet import HardNet\nfrom library import opt\n\n# USE_CUDA = False\nUSE_CUDA = torch.cuda.is_available()\nWRITE_IMGS_DEBUG = False\n\nAffNetPix = AffNetFast(PS = 32)\nweightd_fname = opt.bindir+'hesaffnet/pretrained/AffNet.pth'\nif USE_CUDA:\n checkpoint = torch.load(weightd_fname, map_location='cuda:0')\nelse:\n checkpoint = torch.load(weightd_fname, map_location='cpu')\nAffNetPix.load_state_dict(checkpoint['state_dict'])\nAffNetPix.eval()\n\n\nHardNetDescriptor = HardNet()\nmodel_weights = opt.bindir+'hesaffnet/pretrained/HardNet++.pth'\nif USE_CUDA:\n hncheckpoint = torch.load(model_weights, map_location='cuda:0')\nelse:\n hncheckpoint = torch.load(model_weights, map_location='cpu')\nHardNetDescriptor.load_state_dict(hncheckpoint['state_dict'])\nHardNetDescriptor.eval()\n\nif USE_CUDA:\n AffNetPix = AffNetPix.cuda()\n HardNetDescriptor = HardNetDescriptor.cuda()\n\n\nfrom library import *\nimport cv2\n\ndef getAffmaps_from_Affnet(patches_np):\n sp1, sp2 = np.shape(patches_np[0])\n subpatches = torch.autograd.Variable( torch.zeros([len(patches_np), 1, 32, 32], dtype=torch.float32), volatile = True).view(len(patches_np), 1, 32, 32)\n for k in range(0,len(patches_np)):\n subpatch = patches_np[k][int(sp1/2)-16:int(sp2/2)+16, int(sp1/2)-16:int(sp2/2)+16].reshape(1,1,32,32)\n subpatches[k,:,:,:] = torch.from_numpy(subpatch.astype(np.float32)) #=subpatch\n\n x, y = subpatches.shape[3]/2.0 + 2, subpatches.shape[2]/2.0 + 2 \n LAFs = normalizeLAFs( torch.tensor([[AffNetPix.PS/2, 0, x], [0, AffNetPix.PS/2, y]]).reshape(1,2,3), subpatches.shape[3], subpatches.shape[2] ) \n baseLAFs = torch.zeros([subpatches.shape[0], 2, 3], dtype=torch.float32) \n for m in range(subpatches.shape[0]):\n baseLAFs[m,:,:] = LAFs\n \n if USE_CUDA:\n # or ---> A = AffNetPix(subpatches.cuda()).cpu()\n with torch.no_grad():\n A = batched_forward(AffNetPix, subpatches.cuda(), 256).cpu()\n else:\n with torch.no_grad():\n A = AffNetPix(subpatches)\n LAFs = torch.cat([torch.bmm(A,baseLAFs[:,:,0:2]), baseLAFs[:,:,2:] ], dim =2)\n dLAFs = denormalizeLAFs(LAFs, subpatches.shape[3], subpatches.shape[2])\n Alist = convertLAFs_to_A23format( dLAFs.detach().cpu().numpy().astype(np.float32) )\n return Alist\n\n\ndef AffNetHardNet_describe(patches):\n descriptors = np.zeros( shape = [patches.shape[0], 128], dtype=np.float32)\n HessianAffine = []\n subpatches = torch.autograd.Variable( torch.zeros([len(patches), 1, 32, 32], dtype=torch.float32), volatile = True).view(len(patches), 1, 32, 32)\n baseLAFs = torch.zeros([len(patches), 2, 3], dtype=torch.float32) \n for m in range(patches.shape[0]):\n patch_np = patches[m,:,:,0].reshape(np.shape(patches)[1:3])\n HessianAffine.append( ScaleSpaceAffinePatchExtractor( mrSize = 5.192, num_features = 0, border = 0, num_Baum_iters = 0) )\n with torch.no_grad():\n var_image = torch.autograd.Variable(torch.from_numpy(patch_np.astype(np.float32)), volatile = True)\n patch = var_image.view(1, 1, var_image.size(0),var_image.size(1))\n with torch.no_grad(): \n HessianAffine[m].createScaleSpace(patch) # to generate scale pyramids and stuff\n x, y = patch.size(3)/2.0 + 2, patch.size(2)/2.0 + 2 \n LAFs = normalizeLAFs( torch.tensor([[AffNetPix.PS/2, 0, x], [0, AffNetPix.PS/2, y]]).reshape(1,2,3), patch.size(3), patch.size(2) ) \n baseLAFs[m,:,:] = LAFs\n with torch.no_grad():\n subpatch = HessianAffine[m].extract_patches_from_pyr(denormalizeLAFs(LAFs, patch.size(3), patch.size(2)), PS = AffNetPix.PS)\n if WRITE_IMGS_DEBUG:\n SaveImageWithKeys(subpatch.detach().cpu().numpy().reshape([32,32]), [], 'p1/'+str(n)+'.png' )\n # This subpatch has been blured by extract_patches _from_pyr... \n # let't us crop it manually to obtain fair results agains other methods\n subpatch = patch_np[16:48,16:48].reshape(1,1,32,32)\n #var_image = torch.autograd.Variable(torch.from_numpy(subpatch.astype(np.float32)), volatile = True)\n #subpatch = var_image.view(1, 1, 32,32)\n subpatches[m,:,:,:] = torch.from_numpy(subpatch.astype(np.float32)) #=subpatch\n if WRITE_IMGS_DEBUG:\n SaveImageWithKeys(subpatch.detach().cpu().numpy().reshape([32,32]), [], 'p2/'+str(n)+'.png' )\n if USE_CUDA:\n # or ---> A = AffNetPix(subpatches.cuda()).cpu()\n with torch.no_grad():\n A = batched_forward(AffNetPix, subpatches.cuda(), 256).cpu()\n else:\n with torch.no_grad():\n A = AffNetPix(subpatches)\n LAFs = torch.cat([torch.bmm(A,baseLAFs[:,:,0:2]), baseLAFs[:,:,2:] ], dim =2)\n dLAFs = denormalizeLAFs(LAFs, patch.size(3), patch.size(2))\n Alist = convertLAFs_to_A23format( dLAFs.detach().cpu().numpy().astype(np.float32) )\n for m in range(patches.shape[0]):\n with torch.no_grad():\n patchaff = HessianAffine[m].extract_patches_from_pyr(dLAFs[m,:,:].reshape(1,2,3), PS = 32)\n if WRITE_IMGS_DEBUG:\n SaveImageWithKeys(patchaff.detach().cpu().numpy().reshape([32,32]), [], 'im1/'+str(n)+'.png' )\n SaveImageWithKeys(patch_np, [], 'im2/'+str(n)+'.png' )\n subpatches[m,:,:,:] = patchaff\n if USE_CUDA:\n with torch.no_grad():\n # descriptors = HardNetDescriptor(subpatches.cuda()).detach().cpu().numpy().astype(np.float32)\n descriptors = batched_forward(HardNetDescriptor, subpatches.cuda(), 256).cpu().numpy().astype(np.float32)\n else:\n with torch.no_grad():\n descriptors = HardNetDescriptor(subpatches).detach().cpu().numpy().astype(np.float32)\n return descriptors, Alist\n\ndef AffNetHardNet_describeFromKeys(img_np, KPlist):\n img = torch.autograd.Variable(torch.from_numpy(img_np.astype(np.float32)), volatile = True)\n img = img.view(1, 1, img.size(0),img.size(1))\n HessianAffine = ScaleSpaceAffinePatchExtractor( mrSize = 5.192, num_features = 0, border = 0, num_Baum_iters = 0)\n if USE_CUDA:\n HessianAffine = HessianAffine.cuda()\n img = img.cuda()\n with torch.no_grad():\n HessianAffine.createScaleSpace(img) # to generate scale pyramids and stuff\n descriptors = []\n Alist = []\n n=0\n # for patch_np in patches:\n for kp in KPlist: \n x, y = np.float32(kp.pt)\n LAFs = normalizeLAFs( torch.tensor([[AffNetPix.PS/2, 0, x], [0, AffNetPix.PS/2, y]]).reshape(1,2,3), img.size(3), img.size(2) )\n with torch.no_grad():\n patch = HessianAffine.extract_patches_from_pyr(denormalizeLAFs(LAFs, img.size(3), img.size(2)), PS = AffNetPix.PS)\n if WRITE_IMGS_DEBUG:\n SaveImageWithKeys(patch.detach().cpu().numpy().reshape([32,32]), [], 'p2/'+str(n)+'.png' )\n if USE_CUDA:\n # or ---> A = AffNetPix(subpatches.cuda()).cpu()\n with torch.no_grad():\n A = batched_forward(AffNetPix, patch.cuda(), 256).cpu()\n else:\n with torch.no_grad():\n A = AffNetPix(patch)\n new_LAFs = torch.cat([torch.bmm(A,LAFs[:,:,0:2]), LAFs[:,:,2:] ], dim =2)\n dLAFs = denormalizeLAFs(new_LAFs, img.size(3), img.size(2))\n with torch.no_grad():\n patchaff = HessianAffine.extract_patches_from_pyr(dLAFs, PS = 32)\n if WRITE_IMGS_DEBUG:\n SaveImageWithKeys(patchaff.detach().cpu().numpy().reshape([32,32]), [], 'p1/'+str(n)+'.png' )\n SaveImageWithKeys(img_np, [kp], 'im1/'+str(n)+'.png' )\n descriptors.append( HardNetDescriptor(patchaff).cpu().numpy().astype(np.float32) )\n Alist.append( convertLAFs_to_A23format( LAFs.detach().cpu().numpy().astype(np.float32) ) )\n n=n+1\n return descriptors, Alist\n\n\ndef HessAffNetHardNet_Detect(img, Nfeatures=500):\n var_image = torch.autograd.Variable(torch.from_numpy(img.astype(np.float32)), volatile = True)\n var_image_reshape = var_image.view(1, 1, var_image.size(0),var_image.size(1))\n HessianAffine = ScaleSpaceAffinePatchExtractor( mrSize = 5.192, num_features = Nfeatures, border = 5, num_Baum_iters = 1, AffNet = AffNetPix)\n if USE_CUDA:\n HessianAffine = HessianAffine.cuda()\n var_image_reshape = var_image_reshape.cuda()\n \n with torch.no_grad():\n LAFs, responses = HessianAffine(var_image_reshape, do_ori = True)\n\n # these are my affine maps to work with\n Alist = convertLAFs_to_A23format(LAFs).cpu().numpy().astype(np.float32)\n KPlist = [cv2.KeyPoint(x=A[0,2], y=A[1,2], _size=10, _angle=0.0,\n _response=1, _octave=packSIFTOctave(0,0),_class_id=1)\n for A in Alist]\n return KPlist, Alist, responses\n\n\ndef HessAffNetHardNet_DetectAndDescribe(img, Nfeatures=500):\n var_image = torch.autograd.Variable(torch.from_numpy(img.astype(np.float32)), volatile = True)\n var_image_reshape = var_image.view(1, 1, var_image.size(0),var_image.size(1))\n HessianAffine = ScaleSpaceAffinePatchExtractor( mrSize = 5.192, num_features = Nfeatures, border = 5, num_Baum_iters = 1, AffNet = AffNetPix)\n if USE_CUDA:\n HessianAffine = HessianAffine.cuda()\n var_image_reshape = var_image_reshape.cuda()\n \n with torch.no_grad():\n LAFs, responses = HessianAffine(var_image_reshape, do_ori = True)\n patches = HessianAffine.extract_patches_from_pyr(LAFs, PS = 32)\n descriptors = HardNetDescriptor(patches)\n\n # these are my affine maps to work with\n Alist = convertLAFs_to_A23format(LAFs).cpu().numpy().astype(np.float32)\n KPlist = [cv2.KeyPoint(x=A[0,2], y=A[1,2], _size=10, _angle=0.0,\n _response=1, _octave=packSIFTOctave(0,0),_class_id=1)\n for A in Alist]\n return KPlist, patches, descriptors, Alist, responses\n\ndef HessAff_Detect(img, PatchSize=60, Nfeatures=500):\n var_image = torch.autograd.Variable(torch.from_numpy(img.astype(np.float32)), volatile = True)\n var_image_reshape = var_image.view(1, 1, var_image.size(0),var_image.size(1))\n HessianAffine = ScaleSpaceAffinePatchExtractor( mrSize = 5.192, num_features = Nfeatures, border = PatchSize/2, num_Baum_iters = 1)\n # if USE_CUDA:\n # HessianAffine = HessianAffine.cuda()\n # var_image_reshape = var_image_reshape.cuda()\n \n with torch.no_grad():\n LAFs, responses = HessianAffine(var_image_reshape, do_ori = True)\n patches = HessianAffine.extract_patches_from_pyr(LAFs, PS = PatchSize).cpu()\n\n # these are my affine maps to work with\n Alist = convertLAFs_to_A23format(LAFs).cpu().numpy().astype(np.float32)\n KPlist = [cv2.KeyPoint(x=A[0,2], y=A[1,2], _size=10, _angle=0.0,\n _response=1, _octave=packSIFTOctave(0,0),_class_id=1)\n for A in Alist]\n return KPlist, np.array(patches), Alist, responses.cpu()\n\nfrom Losses import distance_matrix_vector\ndef BruteForce4HardNet(descriptors1, descriptors2, SNN_threshold = 0.8):\n if type(descriptors1)!=torch.Tensor:\n descriptors1 = torch.from_numpy(descriptors1.astype(np.float32))\n descriptors2 = torch.from_numpy(descriptors2.astype(np.float32))\n # if USE_CUDA:\n # descriptors1 = descriptors1.cuda()\n # descriptors2 = descriptors2.cuda()\n #Bruteforce matching with SNN threshold \n dist_matrix = distance_matrix_vector(descriptors1, descriptors2)\n min_dist, idxs_in_2 = torch.min(dist_matrix,1)\n dist_matrix[:,idxs_in_2] = 100000;# mask out nearest neighbour to find second nearest\n min_2nd_dist, idxs_2nd_in_2 = torch.min(dist_matrix,1)\n mask = (min_dist / (min_2nd_dist + 1e-8)) <= SNN_threshold\n\n tent_matches_in_1 = indxs_in1 = torch.autograd.Variable(torch.arange(0, idxs_in_2.size(0)), requires_grad = False)[mask]\n tent_matches_in_2 = idxs_in_2[mask]\n\n tent_matches_in_1 = tent_matches_in_1.data.cpu().long()\n tent_matches_in_2 = tent_matches_in_2.data.cpu().long()\n return tent_matches_in_1, tent_matches_in_2\n","repo_name":"rdguez-mariano/fast_imas_IPOL","sub_path":"adaptiveIMAS/hesaffnet/hesaffnet.py","file_name":"hesaffnet.py","file_ext":"py","file_size_in_byte":12666,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"24"} +{"seq_id":"3393545806","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn import preprocessing\n\n\ncsv = pd.read_csv(\"~/Documents/ml/ccpp.csv\")\nX_train = np.array(csv.iloc[:,:4])\n#one = np.ones(Xn.shape[0])\n#X = np.column_stack((Xn,one))\ny_train = np.array(csv.iloc[:,4])\n\nmin_max_scaler = preprocessing.MinMaxScaler()\nX_train_minmax = min_max_scaler.fit_transform(X_train)\nrate = 0.00001\ny_train=y_train.reshape(-1,1)\n\nX = tf.placeholder(\"float\",[None,4])\ny = tf.placeholder(\"float\",[None,1])\n\nw=tf.Variable(tf.zeros([4,1]))\nb = tf.Variable(tf.zeros([1]))\n\nprint(X_train)\npred = tf.matmul(X,w)+b\nloss= tf.reduce_mean(tf.reduce_mean(pred-y))\noptimizer = tf.train.GradientDescentOptimizer(rate).minimize(loss)\n\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init)\n\n\nfor i in range(10000):\n sess.run(optimizer,{X:X_train,y:y_train})\n#sess.run(loss,{pX:X,py:y})\nwr = [sess.run(w[0]),sess.run(w[1]),sess.run(w[2]),sess.run(w[3])]\n#wr = sess.run(w)\nb=sess.run(b)\n\nprint(\"------------------\")\nprint(min_max_scaler.scale_)\nprint(wr)\n\nprint(b)\n","repo_name":"model1235/linearRegression","sub_path":"linearTensorflow.py","file_name":"linearTensorflow.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"73177021181","text":"'''\r\nPrerequisite: Install pandas respective to your OS.\r\nDESC: This program reads the XML files and extracted Error,Message,Rule object from it and load it into ELSX file into it's respective sheets. This program also generate Log file for testing purposes.\r\nStep1: Ask user input for Directory of XML files\r\nStep2: Once the user enter the Directory the program will traverse through each of an XML file and processed it only if it meets all the condition and pass through all the flags. \r\nCondition to extract the objects from XML:\r\n 1) XML file should be in the directory\r\n 2) The root of the XML file should be Data \r\n 3) It should match the path in order to fetch the data \r\n Errors=> Data/Nuula/Errors/Error \r\n Message=> Data/DataExtract900jer/Messages/Message\r\n Rules=> Data/DataExtract900jer/Rules/Rule\r\nTo run this program the above condition should be meet. If not, an appropriate error will generate on Log as well as Terminal.\r\nIn the program I declared 5 lists:\r\n A[] = Has the information of the Error object.\r\n B[] = Has the information of the Message object.\r\n C[] = Has the information of the Rules object.\r\n D[] = Used as a flag, to check the count. This tells when their is XML file present in the provided directory.\r\n\r\nLogic behind this: Extracted the data in the form of Dictionary from XML and put it into lists because I'm using Pandas DF and it take 2 dimensional objects. Once retrieved I used that List of Dictionaries of store the data into Excel. Once we get the data into their respective List then this program makes an Excel sheet with respective the information extracted.\r\n'''\r\nimport os # For user input\r\nimport xml.etree.cElementTree as ET\r\nfrom numpy import correlate # To access the XML\r\nimport pandas as pd # To put the extracted data into XLSX file\r\nimport logging # To make a log file\r\n\r\n# Initializing and creatign object for logging to use in the program\r\nlogging.basicConfig(filename=\"Nuula.log\",\r\n format='%(asctime)s, %(levelname)-8s [%(filename)s] %(message)s')\r\nlogger = logging.getLogger() # Creating an object\r\nlogger.setLevel(logging.INFO) # Setting the threshold of logger\r\n# Made a list to store values and raise flag on conditions\r\nA, B, C, D, procFiles = [], [], [], [], []\r\nincorrectPath, rootNotData = 0, 0\r\ncorrectFiles = []\r\ndir = input(\"Please enter home directory:\")\r\nfor filename in os.listdir(dir):\r\n if not filename.endswith('.xml'):\r\n continue\r\n fullname = os.path.join(dir, filename)\r\n D.append(fullname)\r\n tree1 = ET.parse(fullname)\r\n root1 = tree1.getroot()\r\n if root1.tag == 'Data':\r\n for error in root1.findall(\"./Nuula/Errors/Error\"):\r\n A.append(error.attrib)\r\n for message in root1.findall(\"./DataExtract900jer/Messages/Message\"):\r\n B.append(message.attrib)\r\n for rule in root1.findall(\"./DataExtract900jer/Rules/Rule\"):\r\n C.append(rule.attrib)\r\n if len(D) > 0 and len(A) == 0 and len(B) == 0 and len(C) == 0:\r\n incorrectPath += 1\r\n print(\"Incorrect path of file\" + filename)\r\n logging.info(\"Incorrect path\" + filename)\r\n else:\r\n correctFiles.append(filename)\r\n else:\r\n rootNotData += 1\r\n print(\"Root of an XML file \" + filename + \" is not Data\")\r\n logging.info(\"Root of an XML file \" + filename + \" is not Data\")\r\nif len(D) == 0 and len(A) == 0 and len(B) == 0 and len(C) == 0:\r\n print(\"No XML file found\")\r\n logging.info(\"No XML file found\")\r\nif len(D) > 0 and len(A) > 0 or len(B) > 0 or len(C) > 0:\r\n numProcessed = len(D)-(incorrectPath+rootNotData)\r\n dfError = pd.DataFrame(A)\r\n dfMessage = pd.DataFrame(B)\r\n dfRule = pd.DataFrame(C)\r\n writer = pd.ExcelWriter('Nuula.xlsx', engine='xlsxwriter')\r\n if len(A) > 0:\r\n dfError.to_excel(writer, sheet_name='Error')\r\n if len(B) > 0:\r\n dfMessage.to_excel(writer, sheet_name='Message')\r\n if len(C) > 0:\r\n dfRule.to_excel(writer, sheet_name='Rules')\r\n writer.save()\r\n print(\"Number of XML files in the directory are:\", len(D)) # correct\r\n print(\"Number of XMLs failed:\", (incorrectPath+rootNotData))\r\n logging.info(\"Number of XML failed: \" + str(incorrectPath+rootNotData))\r\n print(\"Number of XMLs processed:\", numProcessed)\r\n logging.info(\"Number of files processed: \" + str(numProcessed))\r\n for x in correctFiles:\r\n print(\"Processed files are:\", x)\r\n print(\"Excel file created\")\r\n logging.info('ELSX file created')\r\nelse:\r\n print(\"Number of XML files in the directory are:\", len(D))\r\n print(\"Number of XMLs failed:\", len(D))\r\n print(\"Number of XMLs processed: 0\")\r\n","repo_name":"DecodeRav/XML-XLSX","sub_path":"nulla.py","file_name":"nulla.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"26221439948","text":"from collections import deque\n\ndef solution(progresses, speeds):\n answer = []\n q = deque()\n for i in range(len(progresses)):\n left = 100 - progresses[i]\n if left % speeds[i] != 0:\n q.append(left // speeds[i] + 1)\n else:\n q.append(left // speeds[i])\n cnt = 1\n now = q.popleft()\n while q:\n if q[0] <= now:\n cnt += 1\n q.popleft()\n else:\n answer.append(cnt)\n cnt = 1\n now = q.popleft()\n else:\n if cnt != 0:\n answer.append(cnt)\n\n return answer\n","repo_name":"junho100/algorithm_for_test","sub_path":"algorithm/pmx_기능개발.py","file_name":"pmx_기능개발.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"72810922622","text":"# coding: utf-8\n\n\"\"\"\n OOXML Automation\n\n This API helps users convert Excel and Powerpoint documents into rich, live dashboards and stories. # noqa: E501\n\n The version of the OpenAPI document: 0.1.0-no-tags\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass TableCells(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'row_id': 'str',\n 'column_id': 'str',\n 'row_span': 'int',\n 'column_span': 'int',\n 'is_merged_vertical': 'bool',\n 'is_merged_horozontal': 'bool',\n 'id': 'str'\n }\n\n attribute_map = {\n 'row_id': 'rowId',\n 'column_id': 'columnId',\n 'row_span': 'rowSpan',\n 'column_span': 'columnSpan',\n 'is_merged_vertical': 'isMergedVertical',\n 'is_merged_horozontal': 'isMergedHorozontal',\n 'id': 'id'\n }\n\n def __init__(self, row_id=None, column_id=None, row_span=None, column_span=None, is_merged_vertical=None, is_merged_horozontal=None, id=None): # noqa: E501\n \"\"\"TableCells - a model defined in OpenAPI\"\"\" # noqa: E501\n\n self._row_id = None\n self._column_id = None\n self._row_span = None\n self._column_span = None\n self._is_merged_vertical = None\n self._is_merged_horozontal = None\n self._id = None\n self.discriminator = None\n\n self.row_id = row_id\n self.column_id = column_id\n if row_span is not None:\n self.row_span = row_span\n if column_span is not None:\n self.column_span = column_span\n if is_merged_vertical is not None:\n self.is_merged_vertical = is_merged_vertical\n if is_merged_horozontal is not None:\n self.is_merged_horozontal = is_merged_horozontal\n if id is not None:\n self.id = id\n\n @property\n def row_id(self):\n \"\"\"Gets the row_id of this TableCells. # noqa: E501\n\n\n :return: The row_id of this TableCells. # noqa: E501\n :rtype: str\n \"\"\"\n return self._row_id\n\n @row_id.setter\n def row_id(self, row_id):\n \"\"\"Sets the row_id of this TableCells.\n\n\n :param row_id: The row_id of this TableCells. # noqa: E501\n :type: str\n \"\"\"\n\n self._row_id = row_id\n\n @property\n def column_id(self):\n \"\"\"Gets the column_id of this TableCells. # noqa: E501\n\n\n :return: The column_id of this TableCells. # noqa: E501\n :rtype: str\n \"\"\"\n return self._column_id\n\n @column_id.setter\n def column_id(self, column_id):\n \"\"\"Sets the column_id of this TableCells.\n\n\n :param column_id: The column_id of this TableCells. # noqa: E501\n :type: str\n \"\"\"\n\n self._column_id = column_id\n\n @property\n def row_span(self):\n \"\"\"Gets the row_span of this TableCells. # noqa: E501\n\n\n :return: The row_span of this TableCells. # noqa: E501\n :rtype: int\n \"\"\"\n return self._row_span\n\n @row_span.setter\n def row_span(self, row_span):\n \"\"\"Sets the row_span of this TableCells.\n\n\n :param row_span: The row_span of this TableCells. # noqa: E501\n :type: int\n \"\"\"\n\n self._row_span = row_span\n\n @property\n def column_span(self):\n \"\"\"Gets the column_span of this TableCells. # noqa: E501\n\n\n :return: The column_span of this TableCells. # noqa: E501\n :rtype: int\n \"\"\"\n return self._column_span\n\n @column_span.setter\n def column_span(self, column_span):\n \"\"\"Sets the column_span of this TableCells.\n\n\n :param column_span: The column_span of this TableCells. # noqa: E501\n :type: int\n \"\"\"\n\n self._column_span = column_span\n\n @property\n def is_merged_vertical(self):\n \"\"\"Gets the is_merged_vertical of this TableCells. # noqa: E501\n\n\n :return: The is_merged_vertical of this TableCells. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._is_merged_vertical\n\n @is_merged_vertical.setter\n def is_merged_vertical(self, is_merged_vertical):\n \"\"\"Sets the is_merged_vertical of this TableCells.\n\n\n :param is_merged_vertical: The is_merged_vertical of this TableCells. # noqa: E501\n :type: bool\n \"\"\"\n\n self._is_merged_vertical = is_merged_vertical\n\n @property\n def is_merged_horozontal(self):\n \"\"\"Gets the is_merged_horozontal of this TableCells. # noqa: E501\n\n\n :return: The is_merged_horozontal of this TableCells. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._is_merged_horozontal\n\n @is_merged_horozontal.setter\n def is_merged_horozontal(self, is_merged_horozontal):\n \"\"\"Sets the is_merged_horozontal of this TableCells.\n\n\n :param is_merged_horozontal: The is_merged_horozontal of this TableCells. # noqa: E501\n :type: bool\n \"\"\"\n\n self._is_merged_horozontal = is_merged_horozontal\n\n @property\n def id(self):\n \"\"\"Gets the id of this TableCells. # noqa: E501\n\n\n :return: The id of this TableCells. # noqa: E501\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this TableCells.\n\n\n :param id: The id of this TableCells. # noqa: E501\n :type: str\n \"\"\"\n\n self._id = id\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, TableCells):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","repo_name":"presalytics/python-client","sub_path":"presalytics/client/presalytics_ooxml_automation/models/table_cells.py","file_name":"table_cells.py","file_ext":"py","file_size_in_byte":7167,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"24"} +{"seq_id":"29886610499","text":"def getscore(a, b):\n return a / b\n\ndef main():\n file = open(\"edges.txt\")\n info = file.readline().split(\" \")\n nodes = int(info[0])\n edges = int(info[1])\n\n graph = []\n allVertices = set() # set\n \n for line in file:\n info = line.split(\" \")\n v1 = int(info[0])\n if v1 not in allVertices:\n allVertices.add(v1)\n v2 = int (info[1])\n if v2 not in allVertices:\n allVertices.add(v2)\n l = int (info[2])\n graph.append((l, v1, v2))\n\n g = sorted(graph)\n \n\n X = set({graph[0][1]}) # Just intialization\n T = []\n \n while X != allVertices:\n allEdges = [edge for edge in g if ((edge[1] in X and edge[2] not in X) or (edge[2] in X and edge[1] not in X))]\n sortedEdges = sorted(allEdges)\n e = sortedEdges[0]\n\n T.append(e[0]) # add span to T\n X.add(e[1] if e[1] not in X else e[2]) # Add a vertex to X\n\n print (sum(T))\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"ArsalanKhairani/Algorithms","sub_path":"PrimMST.py","file_name":"PrimMST.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"21668297344","text":"# 7311 Coding Assignment 2\r\n\r\n# write code for the following functions.\r\n# note: these functions use the non-binding type hints feature new in Python 3.5\r\n# It's good to get in the habit of writing your code this way\r\n\r\n# All these functions return None so that the code compiles.\r\n# Your job is to write code that returns a correct implementation of the function.\r\nimport pytest\r\nimport re\r\n\r\ndef get_longest_word(instring: str) -> str:\r\n '''\r\n do: Return the longest word in the instring.\r\n A word is a colelction of alphanumeric characters separated by one or more spoces.\r\n\r\n example: get_longest_word(\"jump holler have a fabulous time\" ) -> \"fabulous\"\r\n :param instring: string with space delimited words\r\n :return: the longest wrord string\r\n '''\r\n words = instring.split()\r\n longest_word = ''\r\n for word in words:\r\n if len(word) > len(longest_word):\r\n longest_word = word\r\n return longest_word\r\n\r\ndef count_char_frequency(instr : str) -> dict:\r\n '''\r\n do: extract each character in instr and use a dict to keep track of the number of occurrences\r\n of each character\r\n example: \"abba\" -> {'a':2, 'b':2}\r\n :param instr: string of characters\r\n :return: dictionary\r\n '''\r\n char_count = {}\r\n for char in instr:\r\n if char in char_count:\r\n char_count[char] += 1\r\n else:\r\n char_count[char] = 1\r\n return char_count\r\n\r\nclass MyVehicleClass:\r\n '''Add attributes number_wheels and weight.\r\n Add a method weight_per_wheel that returns weight/number_wheels\r\n '''\r\n\r\n def __init__(self, number_wheels, weight):\r\n self.number_wheels = number_wheels\r\n self.weight = weight\r\n\r\n def weight_per_wheel(self):\r\n return self.weight / self.number_wheels\r\n\r\n@pytest.fixture\r\ndef some_vehicle():\r\n '''\r\n Fixture to create an instance of MyVehicleClass for testing.\r\n '''\r\n return MyVehicleClass(18, 500000)\r\n\r\ndef test_vehicle_class (some_vehicle: MyVehicleClass) -> float:\r\n '''\r\n :param some_vehicle: an instance of the MyVehicleClass\r\n :return: the value returned by the weight_per_wheel method\r\n '''\r\n return some_vehicle.weight_per_wheel()\r\n\r\n\r\ndef regex_test(instring: str) -> list:\r\n '''\r\n do: write a regex string as a local variable to find\r\n floating point numbers that have at least one digit preceding the decimal\r\n and at least two numbers following the decimal\r\n\r\n example: regex_test (\"abc 2.987 44.8 999.99\") -> ['2.987', '999.99']\r\n suggest: use the website http://regexpal.com to test out regexes\r\n\r\n :param instring: string to search for matches to regex\r\n :return: list of matches\r\n '''\r\n\r\n regex_pattern = r'\\d+\\.\\d{2,}'\r\n return re.findall(regex_pattern, instring)\r\n\r\nprint (f\"get_long_word('bob found ridiculous book on shelf'):{get_longest_word('bob found ridiculous book on shelf')}\")\r\n\r\nprint (f\"count_char_frequency('abxgttyavb') : {count_char_frequency('abxgttyavb') }\")\r\n\r\n# OOP: create an instance of MyVehicleClass called my_truck\r\n# with number_wheels = 18 and weight = 500000\r\n# pass my_truck to the test_vehicle_class function\r\n\r\nmy_truck = MyVehicleClass(18, 500000)\r\n\r\nprint(f\"test_vehicle_class(my_truck): {test_vehicle_class(my_truck)}\")\r\n\r\nprint (f\"regex_test ('abc 2.987 44.8 999.99') : {regex_test ('abc 2.987 44.8 999.99')}\")","repo_name":"CharlesBryanJr/Python_Repo","sub_path":"CS_7311/a3_coding2.py","file_name":"a3_coding2.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"11905910744","text":"\"\"\"\nSerial version of NEB method based on machine learning PES with first\nprinciples correction.\n\nAvailable functions\n-------------------\nrun_aineb:\n Performs NEB calculation with first principles corrections.\n\"\"\"\n\nfrom ase.io import read, write\nfrom ase.neb import NEB\nfrom ase.optimize import BFGS, FIRE\n\nfrom amp import Amp\nfrom amp.utilities import Annealer\n\nfrom ..common.utilities import echo\nfrom .common import initialize_mep, validate_mep, cluster_data\n\n\ndef run_aineb(gen_args, gen_calc_amp, gen_calc_ref):\n \"\"\"\n Performs NEB calculation with first principles corrections.\n\n Parameters\n ----------\n gen_args: function object\n Function that generates controlling arguments adaptively.\n gen_calc_amp: function object\n Function that instantiates an Amp calculator.\n gen_calc_ref: function object\n Function that instantiates a reference (first principles) calculator.\n\n Returns\n -------\n None\n\n CAUTION\n -------\n Amp calculators cannot be shared by more than one NEB images. So we have to\n train it and then load it from disk for each of the images. In this case,\n Amp calculators must be trained with 'overwrite=True' argument.\n \"\"\"\n # Generate the initial controlling arguments\n mep_args, control_args, dataset_args, convergence, neb_args = gen_args()\n\n # Load the initial and final images and training dataset\n initial_image = read(mep_args[\"initial_file\"], index=-1, parallel=False)\n final_image = read(mep_args[\"final_file\"], index=-1, parallel=False)\n full_set = read(dataset_args[\"train_file\"], index=\":\", parallel=False)\n train_set = cluster_data(full_set, dataset_args)\n\n # Main loop\n echo(\"Serial AI-NEB running on 1 process.\")\n is_converged = False\n for iteration in range(convergence[\"max_iteration\"]):\n echo(\"\\nIteration # %d\" % (iteration+1))\n\n # Train the Amp calculator\n if ((iteration == 0 and control_args[\"restart_with_calc\"] is False) or\n (iteration != 0 and control_args[\"reuse_calc\"] is False)):\n echo(\"Initial Amp calculator built from scratch.\")\n reload = False\n else:\n echo(\"Initial Amp calculator loaded from previous training.\")\n reload = True\n calc_amp = gen_calc_amp(reload=reload)\n echo(\"Training the Amp calculator...\")\n if control_args[\"annealing\"] is True:\n Annealer(calc=calc_amp, images=train_set)\n calc_amp.train(images=train_set, overwrite=True)\n label = calc_amp.label\n\n # Build the initial MEP\n if ((iteration == 0 and control_args[\"restart_with_mep\"] is False) or\n (iteration != 0 and control_args[\"reuse_mep\"] is False)):\n echo(\"Initial MEP built from scratch.\")\n mep = initialize_mep(initial_image, final_image,\n mep_args[\"num_inter_images\"], neb_args)\n else:\n echo(\"Initial MEP loaded from mep.traj.\")\n mep = read(\"mep.traj\", index=\":\")\n for image in mep[1:-1]:\n calc_amp = Amp.load(label + \".amp\", cores=1, label=label,\n logging=False)\n image.set_calculator(calc_amp)\n\n # Calculate the MEP from initial guess\n echo(\"Running NEB using the Amp calculator...\")\n assert (len(neb_args[\"climb\"]) ==\n len(neb_args[\"opt_algorithm\"]) ==\n len(neb_args[\"fmax\"]) ==\n len(neb_args[\"steps\"]))\n for stage in range(len(neb_args[\"climb\"])):\n if neb_args[\"climb\"][stage] is False:\n echo(\"Climbing image switched off.\")\n else:\n echo(\"Climbing image switched on.\")\n neb_runner = NEB(mep,\n k=neb_args[\"k\"],\n climb=neb_args[\"climb\"][stage],\n remove_rotation_and_translation=\n neb_args[\"rm_rot_trans\"],\n method=neb_args[\"method\"])\n # NOTE: interpolation is done in initialize_mep.\n if neb_args[\"opt_algorithm\"][stage] == \"FIRE\":\n opt_algorithm = FIRE\n else:\n opt_algorithm = BFGS\n opt_runner = opt_algorithm(neb_runner)\n opt_runner.run(fmax=neb_args[\"fmax\"][stage],\n steps=neb_args[\"steps\"][stage])\n\n # The validation of MEP is very time-consuming. Here we save MEP without\n # energies and forces for inspection.\n write(\"chk_%d.traj\" % (iteration+1), mep, parallel=False)\n\n # Validate the MEP against the reference calculator\n # Note that for serial version of run_aineb we have to pass mep[1:-1]\n # to validate_mep instead of the whole mep.\n echo(\"Validating the MEP using reference calculator...\")\n accuracy, ref_images = validate_mep(mep[1:-1], calc_amp, gen_calc_ref)\n converge_status = []\n for key, value in accuracy.items():\n echo(\"%16s = %13.4e (%13.4e)\" % (key, value, convergence[key]))\n converge_status.append(value <= convergence[key])\n\n # Save the MEP\n # Note that this piece of code MUST be placed here. Otherwise the\n # energies in mep.traj will be lost.\n mep_save = [initial_image]\n mep_save.extend(ref_images)\n mep_save.append(final_image)\n write(\"mep_%d.traj\" % (iteration+1), mep_save, parallel=False)\n\n # Update training dataset\n full_set.extend(ref_images)\n train_set = cluster_data(full_set, dataset_args)\n echo(\"Size of training dataset after clustering: %d.\" % len(train_set))\n write(\"train.traj\", full_set, parallel=False)\n\n # Update controlling arguments\n (mep_args, control_args, dataset_args,\n convergence, neb_args) = gen_args(iteration+1, accuracy)\n\n # Check if convergence has been reached\n if converge_status == [True, True, True, True]:\n is_converged = True\n break\n\n # Summary\n if is_converged:\n echo(\"\\nAI-NEB calculation converged.\"\n \"\\nThe MEP is saved in mep_%d.traj.\" % (iteration+1))\n else:\n echo(\"\\nMaximum iteration number reached.\"\n \"\\nAI-NEB calculation not converged.\")\n","repo_name":"Senppoa/aipes","sub_path":"aipes/neb/serial.py","file_name":"serial.py","file_ext":"py","file_size_in_byte":6308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"22561232087","text":"# vim: set fileencoding=utf-8 sw=2 ts=2 et :\nfrom __future__ import absolute_import\n\ndef oct_to_int(octa):\n \"\"\"\n Convert an octal string to an integer.\n \"\"\"\n\n if not isinstance(octa, str):\n raise TypeError\n return int(octa, 8)\n\ndef int_to_oct(intgr):\n \"\"\"\n Convert an integer to a 0-started octal string.\n\n Not using the oct builtin because its output changed in python 3.0.\n \"\"\"\n\n if not isinstance(intgr, int):\n raise TypeError(intgr, int)\n if intgr < 0:\n raise ValueError(intgr)\n octa = ''\n while intgr > 0:\n intgr, mod = divmod(intgr, 8)\n octa = str(mod) + octa\n return '0' + octa\n\n\n","repo_name":"g2p/systems","sub_path":"lib/systems/util/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"11134997197","text":"\"\"\"\nLabel printing models\n\"\"\"\n\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport sys\nimport os\nimport logging\nimport datetime\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.core.validators import FileExtensionValidator, MinValueValidator\nfrom django.core.exceptions import ValidationError, FieldError\n\nfrom django.template import Template, Context\nfrom django.template.loader import render_to_string\n\nfrom django.utils.translation import gettext_lazy as _\n\nfrom InvenTree.helpers import validateFilterString, normalize\n\nimport common.models\nimport stock.models\nimport part.models\n\n\ntry:\n from django_weasyprint import WeasyTemplateResponseMixin\nexcept OSError as err: # pragma: no cover\n print(\"OSError: {e}\".format(e=err))\n print(\"You may require some further system packages to be installed.\")\n sys.exit(1)\n\n\nlogger = logging.getLogger(\"inventree\")\n\n\ndef rename_label(instance, filename):\n \"\"\" Place the label file into the correct subdirectory \"\"\"\n\n filename = os.path.basename(filename)\n\n return os.path.join('label', 'template', instance.SUBDIR, filename)\n\n\ndef validate_stock_item_filters(filters):\n\n filters = validateFilterString(filters, model=stock.models.StockItem)\n\n return filters\n\n\ndef validate_stock_location_filters(filters):\n\n filters = validateFilterString(filters, model=stock.models.StockLocation)\n\n return filters\n\n\ndef validate_part_filters(filters):\n\n filters = validateFilterString(filters, model=part.models.Part)\n\n return filters\n\n\nclass WeasyprintLabelMixin(WeasyTemplateResponseMixin):\n \"\"\"\n Class for rendering a label to a PDF\n \"\"\"\n\n pdf_filename = 'label.pdf'\n pdf_attachment = True\n\n def __init__(self, request, template, **kwargs):\n\n self.request = request\n self.template_name = template\n self.pdf_filename = kwargs.get('filename', 'label.pdf')\n\n\nclass LabelTemplate(models.Model):\n \"\"\"\n Base class for generic, filterable labels.\n \"\"\"\n\n class Meta:\n abstract = True\n\n # Each class of label files will be stored in a separate subdirectory\n SUBDIR = \"label\"\n\n # Object we will be printing against (will be filled out later)\n object_to_print = None\n\n @property\n def template(self):\n return self.label.path\n\n def __str__(self):\n return \"{n} - {d}\".format(\n n=self.name,\n d=self.description\n )\n\n name = models.CharField(\n blank=False, max_length=100,\n verbose_name=_('Name'),\n help_text=_('Label name'),\n )\n\n description = models.CharField(\n max_length=250,\n blank=True, null=True,\n verbose_name=_('Description'),\n help_text=_('Label description'),\n )\n\n label = models.FileField(\n upload_to=rename_label,\n unique=True,\n blank=False, null=False,\n verbose_name=_('Label'),\n help_text=_('Label template file'),\n validators=[FileExtensionValidator(allowed_extensions=['html'])],\n )\n\n enabled = models.BooleanField(\n default=True,\n verbose_name=_('Enabled'),\n help_text=_('Label template is enabled'),\n )\n\n width = models.FloatField(\n default=50,\n verbose_name=_('Width [mm]'),\n help_text=_('Label width, specified in mm'),\n validators=[MinValueValidator(2)]\n )\n\n height = models.FloatField(\n default=20,\n verbose_name=_('Height [mm]'),\n help_text=_('Label height, specified in mm'),\n validators=[MinValueValidator(2)]\n )\n\n filename_pattern = models.CharField(\n default=\"label.pdf\",\n verbose_name=_('Filename Pattern'),\n help_text=_('Pattern for generating label filenames'),\n max_length=100,\n )\n\n @property\n def template_name(self):\n \"\"\"\n Returns the file system path to the template file.\n Required for passing the file to an external process\n \"\"\"\n\n template = self.label.name\n template = template.replace('/', os.path.sep)\n template = template.replace('\\\\', os.path.sep)\n\n template = os.path.join(settings.MEDIA_ROOT, template)\n\n return template\n\n def get_context_data(self, request):\n \"\"\"\n Supply custom context data to the template for rendering.\n\n Note: Override this in any subclass\n \"\"\"\n\n return {}\n\n def generate_filename(self, request, **kwargs):\n \"\"\"\n Generate a filename for this label\n \"\"\"\n\n template_string = Template(self.filename_pattern)\n\n ctx = self.context(request)\n\n context = Context(ctx)\n\n return template_string.render(context)\n\n def context(self, request):\n \"\"\"\n Provides context data to the template.\n \"\"\"\n\n context = self.get_context_data(request)\n\n # Add \"basic\" context data which gets passed to every label\n context['base_url'] = common.models.InvenTreeSetting.get_setting('INVENTREE_BASE_URL')\n context['date'] = datetime.datetime.now().date()\n context['datetime'] = datetime.datetime.now()\n context['request'] = request\n context['user'] = request.user\n context['width'] = self.width\n context['height'] = self.height\n\n return context\n\n def render_as_string(self, request, **kwargs):\n \"\"\"\n Render the label to a HTML string\n\n Useful for debug mode (viewing generated code)\n \"\"\"\n\n return render_to_string(self.template_name, self.context(request), request)\n\n def render(self, request, **kwargs):\n \"\"\"\n Render the label template to a PDF file\n\n Uses django-weasyprint plugin to render HTML template\n \"\"\"\n\n wp = WeasyprintLabelMixin(\n request,\n self.template_name,\n base_url=request.build_absolute_uri(\"/\"),\n presentational_hints=True,\n filename=self.generate_filename(request),\n **kwargs\n )\n\n return wp.render_to_response(\n self.context(request),\n **kwargs\n )\n\n\nclass StockItemLabel(LabelTemplate):\n \"\"\"\n Template for printing StockItem labels\n \"\"\"\n\n @staticmethod\n def get_api_url():\n return reverse('api-stockitem-label-list')\n\n SUBDIR = \"stockitem\"\n\n filters = models.CharField(\n blank=True, max_length=250,\n help_text=_('Query filters (comma-separated list of key=value pairs),'),\n verbose_name=_('Filters'),\n validators=[\n validate_stock_item_filters\n ]\n )\n\n def matches_stock_item(self, item):\n \"\"\"\n Test if this label template matches a given StockItem object\n \"\"\"\n\n try:\n filters = validateFilterString(self.filters)\n items = stock.models.StockItem.objects.filter(**filters)\n except (ValidationError, FieldError):\n # If an error exists with the \"filters\" field, return False\n return False\n\n items = items.filter(pk=item.pk)\n\n return items.exists()\n\n def get_context_data(self, request):\n \"\"\"\n Generate context data for each provided StockItem\n \"\"\"\n\n stock_item = self.object_to_print\n\n return {\n 'item': stock_item,\n 'part': stock_item.part,\n 'name': stock_item.part.full_name,\n 'ipn': stock_item.part.IPN,\n 'revision': stock_item.part.revision,\n 'quantity': normalize(stock_item.quantity),\n 'serial': stock_item.serial,\n 'uid': stock_item.uid,\n 'qr_data': stock_item.format_barcode(brief=True),\n 'qr_url': stock_item.format_barcode(url=True, request=request),\n 'tests': stock_item.testResultMap(),\n 'parameters': stock_item.part.parameters_map(),\n\n }\n\n\nclass StockLocationLabel(LabelTemplate):\n \"\"\"\n Template for printing StockLocation labels\n \"\"\"\n\n @staticmethod\n def get_api_url():\n return reverse('api-stocklocation-label-list')\n\n SUBDIR = \"stocklocation\"\n\n filters = models.CharField(\n blank=True, max_length=250,\n help_text=_('Query filters (comma-separated list of key=value pairs'),\n verbose_name=_('Filters'),\n validators=[\n validate_stock_location_filters]\n )\n\n def matches_stock_location(self, location):\n \"\"\"\n Test if this label template matches a given StockLocation object\n \"\"\"\n\n try:\n filters = validateFilterString(self.filters)\n locs = stock.models.StockLocation.objects.filter(**filters)\n except (ValidationError, FieldError):\n return False\n\n locs = locs.filter(pk=location.pk)\n\n return locs.exists()\n\n def get_context_data(self, request):\n \"\"\"\n Generate context data for each provided StockLocation\n \"\"\"\n\n location = self.object_to_print\n\n return {\n 'location': location,\n 'qr_data': location.format_barcode(brief=True),\n }\n\n\nclass PartLabel(LabelTemplate):\n \"\"\"\n Template for printing Part labels\n \"\"\"\n\n @staticmethod\n def get_api_url():\n return reverse('api-part-label-list')\n\n SUBDIR = 'part'\n\n filters = models.CharField(\n blank=True, max_length=250,\n help_text=_('Part query filters (comma-separated value of key=value pairs)'),\n verbose_name=_('Filters'),\n validators=[\n validate_part_filters\n ]\n )\n\n def matches_part(self, part):\n \"\"\"\n Test if this label template matches a given Part object\n \"\"\"\n\n try:\n filters = validateFilterString(self.filters)\n parts = part.models.Part.objects.filter(**filters)\n except (ValidationError, FieldError):\n return False\n\n parts = parts.filter(pk=part.pk)\n\n return parts.exists()\n\n def get_context_data(self, request):\n \"\"\"\n Generate context data for each provided Part object\n \"\"\"\n\n part = self.object_to_print\n\n return {\n 'part': part,\n 'category': part.category,\n 'name': part.name,\n 'description': part.description,\n 'IPN': part.IPN,\n 'revision': part.revision,\n 'qr_data': part.format_barcode(brief=True),\n 'qr_url': part.format_barcode(url=True, request=request),\n 'parameters': part.parameters_map(),\n }\n","repo_name":"connexuscu/food_pantry_inventory","sub_path":"InvenTree/label/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10528,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"14716334076","text":"\"\"\"\nAdd attribute to code blocks\n\"\"\"\n\nimport panflute as pf\n\ndef action(elem, doc):\n if isinstance(elem, pf.CodeBlock) or isinstance(elem, pf.Code):\n # Check whether emtpy\n if elem.classes: \n config = doc.get_metadata('code-attribute')\n\n # Check config\n if config == True or (type(config) == list and elem.classes[0] in config):\n # Assign the class name to style attribute\n elem.attributes['style'] = elem.classes[0]\n\ndef main(doc=None):\n return pf.run_filter(action, doc=doc) \n\nif __name__ == '__main__':\n main()\n\n","repo_name":"DCsunset/pandoc-code-attribute","sub_path":"pandoc_code_attribute.py","file_name":"pandoc_code_attribute.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"39196818859","text":"import matplotlib.pyplot as plt\nimport pandas as pd\n\ndef plot_data(data):\n \"\"\" fig = plt.figure(figsize = (18,6))\n ax1 = fig.add_subplot(2,2,1) \n ax1.set_title('Who survived with respect to the gender?') \n ax2 = fig.add_subplot(2,2,2) \n data.Pclass[data.Survived == 1].value_counts().plot(kind='barh')\n ax2.set_title('Survived by Class')\n ax2.set_xlabel('Class')\n ax3 = fig.add_subplot(2,2,3) \n data.Pclass.value_counts().plot(kind='bar',title='Distribution of Classes')\n ax3.set_xlabel('Class')\n ax4 = fig.add_subplot(2,2,4) \n data.Age[data.Survived == 1].value_counts().plot(kind='kde')\n data.Age[data.Survived == 0].value_counts().plot(kind='kde') \n ax4.set_title('Survived by Age')\n ax4.set_xlabel('Age')\n ax4.legend(('Survived', 'Dead'), loc='best')\n death_count = pd.crosstab([data.Pclass, data.Sex],data.Survived.astype(bool))\n death_count.plot(kind='bar',stacked=True,color=['red','yellow'], grid=False, title='Class&Sex by Survivorship')\n death_count = pd.crosstab([data.Sex],data.Survived.astype(bool))\n death_count.plot(kind='bar',stacked=True,color=['red','yellow'], grid=False, title='Sex by Survivorship') \"\"\"\n fig = plt.figure(figsize = (18,6))\n ax1 = fig.add_subplot(2,2,1) \n data.Survived[(data.Sex == 'female') & (data.Pclass == 3)].value_counts().plot(kind='bar', color = 'red', title = 'Who Survived respect to gender and class?', label ='Female Low CLass', legend=True)\n ax1.set_xticklabels(['Survived','Dead'],rotation=0)\n ax1.set_ylim(0,data[data.Sex == 'female'].shape[0])\n# ax1.set_xlim(-1, data.shape[0])\n ax2 = fig.add_subplot(2,2,2) \n data.Survived[(data.Sex == 'male') & (data.Pclass == 3)].value_counts().plot(kind='bar', color = 'gold', title = 'Who Survived respect to gender and class?', label ='Male Low Class', legend=True)\n ax2.set_xticklabels(['Survived','Dead'], rotation=0)\n ax2.set_ylim(0,data[data.Sex == 'male'].shape[0])\n ax3 = fig.add_subplot(2,2,3) \n data.Survived[(data.Sex == 'female') & data.Pclass.isin([1,2])].value_counts().plot(kind='bar', color = 'red', title = 'Who Survived respect to gender and class?', label ='Female High Class', legend=True)\n ax3.set_xticklabels(['Survived','Dead'],rotation=0)\n ax3.set_ylim(0,data[data.Sex == 'female'].shape[0])\n ax4 = fig.add_subplot(2,2,4) \n data.Survived[(data.Sex == 'male') & data.Pclass.isin([1,2])].value_counts().plot(kind='bar', color = 'red', title = 'Who Survived respect to gender and class?', label ='Male High Class', legend=True)\n ax4.set_xticklabels(['Survived','Dead'],rotation=0)\n ax4.set_ylim(0,data[data.Sex == 'male'].shape[0])","repo_name":"StevenLOL/Kaggle-3","sub_path":"Titanic/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"24"} +{"seq_id":"29957731586","text":"from ete3 import NCBITaxa\nncbi = NCBITaxa()\nncbi.update_taxonomy_database()\nbuilt = False\n\n#format=1 aparecer nomes dos nodes interiores\ninfile2 = open(\"colunasfinal\", 'r')\nfor lines in infile2:\n\tidtaxa = lines.strip().split(\",\")\n\tidtaxa = list(map(int,idtaxa))\n\ninfile2.close()\n\nwhile not built:\n\ttry:\n\t\tt = ncbi.get_topology(idtaxa, intermediate_nodes=True)\n\n\t\ttreefinal = t.get_ascii(attributes=[\"rank\", \"sci_name\"])\n\t\tbuilt= True\n\texcept KeyError as e:\n\t\ttaxid_not_found = int(e.args[0])\n\t\tidtaxa.remove(taxid_not_found)\n\t\tprint(\"the following IDs were not found in NCBI taxonomy database:\" + str(taxid_not_found))\n\t\tpass\n\n\t\t\nwith open(\"ete3tree\", 'w') as tree:\n\tprint(treefinal, file = tree)\n","repo_name":"labBioinfo/workflow","sub_path":"Taxonomy/ete3tree.py","file_name":"ete3tree.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"24"} +{"seq_id":"35080225780","text":"import pygame\r\nimport torch\r\nimport torch.nn as nn\r\nimport numpy as np\r\nimport cv2\r\nfrom torch.optim import Adam\r\nfrom collections import deque\r\nimport random\r\nimport copy\r\nimport pickle\r\nimport time\r\n# Local imports\r\nimport environment\r\nimport supportFunctions as sF\r\n\r\n\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Some global configs\r\ntorch.autograd.set_detect_anomaly(True)\r\n\r\n\r\nREPLAY_MEMORY_SIZE = 500000 # Constants\r\nDISCOUNT = 0.99\r\nEPOCHS = 10000\r\nMIN_REPLAY_MEMORY_SIZE = 200000 # fit after testing < 10000\r\nMINIBATCH_SIZE = 32 # maybe 32 \r\nUPDATE_TARGET_EVERY = 10\r\nEPSILON_DECAY = 0.99975\r\nMIN_EPSILON = 0.001\r\n\r\nRENDER = False\r\nIMPORT_REPLAY_MEMORY = False\r\nIMPORTED_EPSILON = 0.6\r\n\r\nMANUAL = False\r\n\r\n\r\nclass ConvNet(nn.Module):\r\n def __init__(self):\r\n super(ConvNet, self).__init__()\r\n self.conv1 = nn.Sequential(\r\n nn.Conv2d(1, 32, kernel_size=8, stride=1),\r\n #nn.BatchNorm2d(32),\r\n nn.ReLU())\r\n #nn.MaxPool2d(kernel_size=2, stride=2))\r\n self.conv2 = nn.Sequential(\r\n nn.Conv2d(32, 16, kernel_size=5, stride=1),\r\n #nn.BatchNorm2d(32),\r\n nn.ReLU())\r\n #nn.MaxPool2d(kernel_size=2, stride=2))\r\n self.conv3 = nn.Sequential(\r\n nn.Conv2d(16, 8, kernel_size=3, stride=1),\r\n #nn.BatchNorm2d(32),\r\n nn.ReLU())\r\n #nn.MaxPool2d(kernel_size=2, stride=2))\r\n #self.drop = nn.Dropout(p=0.2)\r\n self.fc1 = nn.Linear(in_features=12168, out_features=500)\r\n self.fc2 = nn.Linear(in_features=self.fc1.out_features, out_features=4)\r\n self.optimizer = Adam(self.parameters(), lr=0.001)\r\n self.loss = nn.L1Loss()\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = self.conv2(x)\r\n x = self.conv3(x)\r\n x = x.view(x.size(0), -1) # Flatten\r\n #x = self.drop(x)\r\n x = self.fc1(x)\r\n out = self.fc2(x) # replace in_features with size of oReshape\r\n return out\r\n\r\nclass Agent:\r\n def __init__(self):\r\n self.model = ConvNet() # To do: move model parameters to other class\r\n self.target_model = ConvNet()\r\n self.model_fit_count = 0\r\n self.first_train_step = True\r\n self.loss_tracker = []\r\n # Move models to GPU\r\n if device != 'cpu':\r\n self.model = self.model.cuda()\r\n self.model.loss = self.model.loss.cuda()\r\n self.target_model = self.target_model.cuda()\r\n self.target_model.loss = self.target_model.loss.cuda()\r\n # init both with same weights # target model is what we predict against every step\r\n self.target_model.load_state_dict(self.model.state_dict()) # target model weights will be updated every few steps to keep sanity because of large epsilon\r\n \r\n self.replay_memory = deque(maxlen=REPLAY_MEMORY_SIZE)\r\n\r\n if IMPORT_REPLAY_MEMORY == True:\r\n with open(f\"replaymemory.pickle\", 'rb') as handle:\r\n self.replay_memory = pickle.load(handle)\r\n\r\n self.target_update_counter = 0\r\n self.traincount = 0\r\n\r\n def update_replay_memory(self, transition):\r\n self.replay_memory.append(transition)\r\n\r\n def get_qs(self, state, step):\r\n return self.model(state)\r\n def sample_replay_memory(self):\r\n minibatch = random.sample(self.replay_memory, MINIBATCH_SIZE)\r\n for (current_states, action, reward, new_current_state, done) in minibatch:\r\n current_states = current_states.to(device=device)\r\n new_current_state = new_current_state.to(device=device)\r\n return minibatch\r\n\r\n def train(self, terminal_state, step): # realy call every step? \r\n if len(self.replay_memory) < MIN_REPLAY_MEMORY_SIZE:\r\n return\r\n \r\n if self.traincount == 0:\r\n # Save replay memory at first training step\r\n with open(f\"replaymemory.pickle\", 'wb') as handle:\r\n pickle.dump(self.replay_memory, handle)\r\n self.first_train_step = False\r\n self.traincount += 1\r\n if self.traincount % 100 == 0:\r\n torch.save(self.model, f'models/model_{time.time_ns()}.model')\r\n\r\n # get random sample of replay memory \r\n self.minibatch = random.sample(self.replay_memory, MINIBATCH_SIZE)\r\n #self.minibatch = self.sample_replay_memory()\r\n \r\n for index, (self.current_states, self.action, self.reward, self.new_current_state, self.done) in enumerate(self.minibatch):\r\n self.current_states = self.current_states.to(device=device)\r\n self.new_current_state = self.new_current_state.to(device=device)\r\n\r\n # Get q of current action with max q\r\n current_qs = self.model(self.current_states)\r\n chos_action = torch.argmax(current_qs).item()\r\n #self.current_q = torch.max(current_qs)\r\n # if not game over get q from target model else new_q = reward\r\n new_qs = self.target_model(self.new_current_state)\r\n new_current_qs = current_qs.detach().clone() # insert self.new_q here \r\n if not self.done:\r\n self.max_future_q = torch.max(new_qs).item()\r\n self.new_q = self.reward + DISCOUNT * self.max_future_q\r\n else:\r\n self.new_q = self.reward\r\n\r\n new_current_qs.data[0,chos_action] = self.new_q\r\n\r\n # Calc loss and backprop\r\n self.l = self.model.loss(current_qs, new_current_qs)\r\n self.loss_tracker.append(self.l.item())\r\n self.l.backward()\r\n\r\n if terminal_state: # To Do: check if this is the right criteria, probably not\r\n self.model.optimizer.step()\r\n self.model.optimizer.zero_grad()\r\n if self.model_fit_count %50 == 0:\r\n print(\"Model fitted \" + str(self.model_fit_count) + \" times\")\r\n print(\"current_q: \" + str(current_qs))\r\n print(\"new_q: \" + str(new_current_qs))\r\n self.model_fit_count += 1 \r\n else:\r\n self.target_update_counter += 1\r\n \r\n if self.target_update_counter > UPDATE_TARGET_EVERY:\r\n self.target_model.load_state_dict(self.model.state_dict())\r\n self.target_update_counter = 0\r\n self.current_state = self.current_state.cpu()\r\n self.new_current_state = self.new_current_state.cpu()\r\n \r\n def run_game(self):\r\n\r\n list_earned_rewards = list ()\r\n\r\n epsilon = 1\r\n if IMPORT_REPLAY_MEMORY == True:\r\n epsilon = IMPORTED_EPSILON\r\n epscount = 0\r\n stepcountlist = list()\r\n for self.epoch in range(EPOCHS):\r\n self.episode_reward = 0\r\n self.game = environment.Game(RENDER) # later threadable\r\n if self.epoch % 10 == 0:\r\n print(f\"Gamecount:{self.epoch}\")\r\n print(f\"Replaymemory Size: {len(self.replay_memory)}\")\r\n \r\n \r\n\r\n stepcount = 0\r\n while self.game.reward != -1:\r\n stepcount +=1\r\n self.done = False\r\n ### interesting Variables ####\r\n # game.food_pos #\r\n # game.snake_pos #\r\n # game.snake_body #\r\n # game.reward #\r\n ##############################\r\n\r\n # set manual True if you want to manual control the snake\r\n \r\n if MANUAL == True: \r\n # Input 0, 1, 2, 3\r\n self.keypressed = input()\r\n # Call to step ingame, all variables acessible through self.game\r\n if self.keypressed != '':\r\n self.keypressed = int(self.keypressed)\r\n self.game.step(self.keypressed)\r\n print(self.game.snake_pos)\r\n\r\n else:\r\n ####### Training #######\r\n self.current_state = sF.getStateAsVec(self.game.game_window, self.game.frame_size_x)\r\n if np.random.random_sample() > epsilon:\r\n \r\n # predict q and select action\r\n self.current_state = self.current_state.to(device=device)\r\n with torch.no_grad():\r\n self.q_values = self.model(self.current_state)\r\n self.current_state = self.current_state.detach().cpu()\r\n self.action = torch.max(self.q_values)\r\n else:\r\n self.action = np.random.randint(0, 4)\r\n\r\n # Exec next step\r\n if type(self.action) == torch.tensor:\r\n self.game.step(self.action.item())\r\n else:\r\n self.game.step(self.action)\r\n\r\n # Get reward from environment\r\n self.reward = self.game.reward\r\n\r\n # Check if game over\r\n if self.reward == -1:\r\n self.done = True\r\n self.episode_reward += self.reward\r\n\r\n self.new_state = sF.getStateAsVec(self.game.game_window, self.game.frame_size_x)\r\n self.update_replay_memory((self.current_state, self.action, self.reward, self.new_state, self.done))\r\n self.train(self.done, 0)\r\n\r\n \r\n ###### /Training ###### \r\n\r\n # On Game Over:; \r\n if self.game.reward == -1:\r\n # Count steps taken per game\r\n stepcountlist.append(stepcount)\r\n if len(stepcountlist) % 10 == 0:\r\n with open(f\"steplist.pickle\", 'wb') as handle:\r\n pickle.dump(stepcountlist, handle)\r\n with open(f\"losslist.pickle\", 'wb') as handle:\r\n pickle.dump(self.loss_tracker, handle)\r\n \r\n \r\n # Count rewards earned per game\r\n print(f\"Reward of episode: {self.episode_reward}\")\r\n list_earned_rewards.append(self.episode_reward)\r\n if len(list_earned_rewards) % 10 == 0:\r\n with open(f\"rewardslist.pickle\", 'wb') as handle:\r\n pickle.dump(list_earned_rewards, handle)\r\n\r\n \r\n # Decay epsilon\r\n if epsilon > MIN_EPSILON:\r\n epsilon *= EPSILON_DECAY\r\n epsilon = max(MIN_EPSILON, epsilon)\r\n \r\n if epscount % 10 == 0:\r\n print(\"Current Epsilon: \" + str(epsilon))\r\n epscount+=1\r\n self.game.quit()\r\n\r\n\r\n#sF.seed_everything(1) \r\nagent = Agent()\r\n\r\nagent.run_game()","repo_name":"Miles345/snake_cnn","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":11287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"31276834956","text":"\n\nclass Room:\n\n # pts : dict (x,y) -> matrix[y][x]\n # matrix : int[][] 1 is black 0 is all other pixels\n\n THRESHOLD = 1\n\n def __init__(self, pts, matrix) -> None:\n self.pts = pts\n self.matrix = matrix\n\n def _findRooms(self, x: int, y: int, room: list):\n # print(\"at top\", x, y, end=\" | \")\n\n if (x, y) in self.visited:\n # print(\"been visited\", end=\" | \")\n return\n\n if self.pts[(x, y)] == 1:\n # print(\"is black\")\n return\n\n # print(f'x:{x} y:{y} room:{room}')\n\n self.visited.add((x, y))\n room.append((x, y))\n # up\n if y < len(self.matrix)-1:\n # print(\"went up\")\n self._findRooms(x, y+1, room)\n # down\n if y > 1:\n # print(\"went down\")\n self._findRooms(x, y-1, room)\n # left\n if x > 1:\n # print(\"went left\")\n self._findRooms(x-1, y, room)\n # right\n if x < len(self.matrix[0])-1:\n # print(\"went right\")\n self._findRooms(x+1, y, room)\n\n return\n\n def findRooms(self) -> None:\n self.visited = set() # tuples (x,y)\n self.rooms = list()\n\n for y in range(len(self.matrix)):\n for x in range(len(self.matrix[0])):\n room = list()\n self._findRooms(x, y, room)\n # print(room)\n if room != []:\n # print(room)\n self.rooms.append(room)\n\n # for room in self.rooms:\n # print(room)\n\n def threshold(self):\n threshold = list()\n for col in range(len(self.matrix[0])):\n count = 0\n onBlack = False\n for row in self.matrix:\n if (row[col] == 1):\n onBlack = True\n if onBlack:\n count += 1\n if (row[col] == 0 and onBlack):\n onBlack = False\n count = 0\n threshold.append(count)\n","repo_name":"ACEinfinity7/floorPlan","sub_path":"oldCode/Room_Old.py","file_name":"Room_Old.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"21286349627","text":"#!/usr/bin/env python\nimport json\nimport numpy as np\nimport pickle\nimport pdb\n\ndef convert_bbox(bb):\n return np.array([max(0,bb['x']),max(0,bb['y']),bb['x']+bb['w'],bb['y']+bb['h']],dtype=np.uint16)\n\n#load dataset annotations\nwith open(\"sg_test_annotations_clean.json\") as f: data_in = json.load(f)\n\n#extract gt for each object\ndata_out = []\nfor d in data_in:\n image_reg = {}\n image_reg['filename'] = d['filename']\n image_reg['objects'] = []\n for o in d['objects']:\n single_reg = {}\n single_reg['object'] = o['names'][0]\n single_reg['bbox'] = convert_bbox(o['bbox'])\n image_reg['objects'].append(single_reg)\n data_out.append(image_reg)\n\n#store object annotations\nwith open(\"sg_test_obj_bbox.pkl\",'w') as f: pickle.dump(data_out,f)\n\npdb.set_trace()\n","repo_name":"guyrose3/gen_scene_graph","sub_path":"gen_obj_boxes.py","file_name":"gen_obj_boxes.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"22791974909","text":"#index errors will be raised when you try to access an index which is not present in the list or tuple or array\n\nX=[1,2,3,4,5]\nprint(X[41])\n\n#in case of dictionaries it will be KeyError\nPerson={\n 'Name': 'Vivek',\n 'Company' : 'Bellatrix'\n}\nprint(Person['Name']) #it will work\nprint(Person['Age']) #it will throw KeyError","repo_name":"mvinovivek/BA_Python","sub_path":"Class_3/1_7_IndexError.py","file_name":"1_7_IndexError.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"26735541990","text":"from Game import Game\r\nimport pygame\r\nimport time\r\nimport datetime\r\n\r\nuseGraphics = True\r\n\r\npygame.init()\r\n\r\nscreen = pygame.display.set_mode((800, 800))\r\n\r\nGame = Game(screen, 800, 800)\r\nstart = datetime.datetime.now()\r\nfor i in range(10000):\r\n for event in pygame.event.get():\r\n pass\r\n Game.tick()\r\n if useGraphics:\r\n screen.fill((0, 0, 0))\r\n Game.draw()\r\n screen.blit(pygame.transform.flip(screen, False, True), (0,0))\r\n pygame.display.flip()\r\n time.sleep(.01)\r\nend = datetime.datetime.now()\r\n\r\nprint(\"elapsed time\", end-start)","repo_name":"mPelland42/MLProject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"72695765183","text":"import math\r\ndef yousuck():\r\n\r\n #< [A] Construct User Point in d-dimension space\r\n user_coord = [] #Binary Content list\r\n user_cw = 5 #code-wise rating [1,10]\r\n user_tw = 7 #think-wise rating [1,10]\r\n user_weight = 5 #inversly proportional to noobness of user ; use in k-mean clustering ; [1,10]\r\n user_solved_pid = []\r\n\r\n #<: change to livesubm.uid==current_uid in place of [.lang==\"CPP\"]\r\n for r1 in row1:\r\n\r\n user_solved_hard_cw.append(r1.problems.code)\r\n user_solved_hard_tw.append(r1.problems.think)\r\n user_solved_pid.append(r1.problems.id)\r\n\r\n #Below 15 is the constant for parameters , current parameters are features (dp,graph,etc)\r\n param=15\r\n\r\n for i in range(param): #Initialize each coloumn with 0\r\n user_solved_prblm[i][pc]=0\r\n\r\n if r1.problems.dp==True:\r\n user_solved_prblm[0][pc]=1\r\n\r\n if r1.problems.graph==True:\r\n user_solved_prblm[1][pc]=1\r\n\r\n if r1.problems.computational_geometry==True:\r\n user_solved_prblm[2][pc]=1\r\n\r\n if r1.problems.greedy==True:\r\n user_solved_prblm[3][pc]=1\r\n\r\n if r1.problems.search==True:\r\n user_solved_prblm[4][pc]=1\r\n\r\n if r1.problems.network_flow==True:\r\n user_solved_prblm[5][pc]=1\r\n\r\n if r1.problems.maths==True:\r\n user_solved_prblm[6][pc]=1\r\n\r\n if r1.problems.heuristic==True:\r\n user_solved_prblm[7][pc]=1\r\n\r\n if r1.problems.string==True:\r\n user_solved_prblm[8][pc]=1\r\n\r\n if r1.problems.adhoc==True:\r\n user_solved_prblm[9][pc]=1\r\n\r\n if r1.problems.ds==True:\r\n user_solved_prblm[10][pc]=1\r\n\r\n pc+=1\r\n\r\n #<<\r\n\r\n user_coord.append(cur)\r\n #>>>\r\n\r\n #>>\r\n\r\n #>\r\n\r\n #< [B] Construct Problem points\r\n\r\n prblm_coord = [[0 for x in range(50)] for y in range(20)] #Refer doc\r\n prblm_hard_cw=[]\r\n prblm_hard_tw=[]\r\n ppc=0 #populated problem count\r\n\r\n row2=db(db.problems.id>0).select() #Select all problems initially\r\n\r\n for r2 in row2:\r\n ju=1\r\n for x in user_solved_pid: #Don't construct points off problems already solved\r\n if r2.id==x:\r\n ju=0\r\n break\r\n\r\n if ju==0: #Skip populating space with problems already solved\r\n continue\r\n\r\n for i in range(17):\r\n prblm_coord[i][ppc]=0\r\n\r\n fact=r2.think+r2.code #\r\n\r\n if r2.dp==True:\r\n prblm_coord[0][ppc]=fact\r\n\r\n if r2.dp==True:\r\n prblm_coord[0][ppc]=fact\r\n\r\n if r2.graph==True:\r\n prblm_coord[1][ppc]=fact\r\n\r\n if r2.computational_geometry==True:\r\n prblm_coord[2][ppc]=fact\r\n\r\n if r2.greedy==True:\r\n prblm_coord[3][ppc]=fact\r\n\r\n if r2.search==True:\r\n prblm_coord[4][ppc]=fact\r\n\r\n if r2.network_flow==True:\r\n prblm_coord[5][ppc]=fact\r\n\r\n if r2.maths==True:\r\n prblm_coord[6][ppc]=fact\r\n\r\n if r2.heuristic==True:\r\n prblm_coord[7][ppc]=fact\r\n\r\n if r2.string==True:\r\n prblm_coord[8][ppc]=fact\r\n\r\n if r2.adhoc==True:\r\n prblm_coord[9][ppc]=fact\r\n\r\n if r2.ds==True:\r\n prblm_coord[10][ppc]=fact\r\n\r\n ppc+=1\r\n\r\n #>\r\n\r\n #< [C] Create first 2 PRs , for mantaining ladder structure\r\n\r\n cur_prblm_coord = []\r\n #:Get currently displayed problem's coordinate\r\n selected=2\r\n for i in range(15):\r\n cur_prblm_coord.append(prblm_coord[i][selected])\r\n #\r\n\r\n res1,res2=1,2\r\n fin1_ham_dist,fin1_euc_dist=999999999999,999999999999\r\n fin2_ham_dist,fin2_euc_dist=999999999999,999999999999\r\n\r\n for i in range(ppc):\r\n if i==selected: #\r\n continue\r\n\r\n cur_ham_dist,cur_euc_dist=0,0\r\n\r\n for j in range(15):\r\n if cur_prblm_coord[j]*prblm_coord[j][i]==0:\r\n cur_ham_dist+=1\r\n\r\n dif=(cur_prblm_coord[j]-prblm_coord[j][i])*(cur_prblm_coord[j]-prblm_coord[j][i])\r\n cur_euc_dist+=dif\r\n\r\n cur_euc_dist=math.sqrt(cur_euc_dist)\r\n\r\n if ((fin2_ham_dist>cur_ham_dist) or (fin2_ham_dist==cur_ham_dist and fin2_euc_dist>cur_euc_dist)):\r\n fin2_ham_dist=cur_ham_dist\r\n fin2_euc_dist=cur_euc_dist\r\n r2=i\r\n\r\n if ((fin1_ham_dist>fin2_ham_dist) or (fin1_ham_dist==fin2_ham_dist and fin1_euc_dist>fin2_euc_dist)):\r\n fin1_ham_dist,fin2_ham_dist=fin2_ham_dist,fin1_ham_dist\r\n fin1_euc_dist,fin2_euc_dist=fin2_euc_dist,fin1_euc_dist\r\n r1,r2=r2,r1\r\n\r\n\r\n ''' print ('\r\n print (':/ans>') '''\r\n\r\n #>\r\n\r\n #< [D] Modified K-mean Clustering for last 3 PRs\r\n\r\n km1=[1,0,4,1,5,9,0,2,4,8,1,0,4,8,0] #Initial Clusters , k=3\r\n km2=[0,8,2,0,1,7,9,8,1,3,3,7,0,4,1]\r\n km3=[4,2,8,4,2,0,1,5,2,0,4,3,2,0,0]\r\n\r\n color = [1 for i in range(ppc+5)] #Store ith point falls under which cluster's Voronoi Region\r\n\r\n for iterations in range(1000): #Max iterations untill assuming distrubtion weightage function converges\r\n td1 = [0 for xx in range(15)]\r\n td2 = [0 for xx in range(15)]\r\n td3 = [0 for xx in range(15)]\r\n\r\n for i in range(ppc):\r\n ed1,hd1=0,0 #Eucledian Distance,Hamming Distance wrt km1\r\n ed2,hd2=0,0\r\n ed3,hd3=0,0\r\n\r\n for j in range(15):\r\n if prblm_coord[j][i]*km1[j]==0:\r\n hd1+=1\r\n\r\n if prblm_coord[j][i]*km2[j]==0:\r\n hd2+=1\r\n\r\n if prblm_coord[j][i]*km3[j]==0:\r\n hd3+=1\r\n\r\n ed1=ed1+((prblm_coord[j][i]-km1[j])*(prblm_coord[j][i]-km1[j]))\r\n ed2=ed2+((prblm_coord[j][i]-km2[j])*(prblm_coord[j][i]-km2[j]))\r\n ed3=ed3+((prblm_coord[j][i]-km3[j])*(prblm_coord[j][i]-km3[j]))\r\n\r\n ed1=math.sqrt(ed1)\r\n ed2=math.sqrt(ed2)\r\n ed3=math.sqrt(ed3)\r\n\r\n c1 = ed1 # = (30-hd1)+ed1 #70% ED + 30% Inverse HD composition\r\n c2 = ed2\r\n c3 = ed3\r\n\r\n if c1<=c2 and c1<=c3:\r\n color[i]=1\r\n\r\n for j in range(15):\r\n td1[j]+=(prblm_coord[j][i])\r\n\r\n if c2<=c3 and c2<=c1:\r\n color[i]=2\r\n\r\n for j in range(15):\r\n td2[j]+=(prblm_coord[j][i])\r\n\r\n if c3<=c1 and c3<=c2:\r\n color[i]=3\r\n\r\n for j in range(15):\r\n td3[j]+=(prblm_coord[j][i])\r\n\r\n for xy in range(15):\r\n km1[xy]=td1[xy]/ppc\r\n km2[xy]=td2[xy]/ppc\r\n km3[xy]=td3[xy]/ppc\r\n\r\n ans1,d1=1,99999999999\r\n ans2,d2=2,99999999999\r\n ans3,d3=3,99999999999\r\n tmp1=0\r\n tmp2=0\r\n tmp3=0\r\n\r\n for bc in range(ppc):\r\n if r1==bc:\r\n continue\r\n\r\n if r2==bc:\r\n continue\r\n\r\n tmp1=0\r\n tmp2=0\r\n tmp3=0\r\n\r\n for j in range(15):\r\n tmp1+=((prblm_coord[j][bc]-km1[j])*(prblm_coord[j][bc]-km1[j]))\r\n tmp2+=((prblm_coord[j][bc]-km2[j])*(prblm_coord[j][bc]-km2[j]))\r\n tmp3+=((prblm_coord[j][bc]-km3[j])*(prblm_coord[j][bc]-km3[j]))\r\n\r\n tmp1=math.sqrt(tmp1)\r\n tmp2=math.sqrt(tmp2)\r\n tmp3=math.sqrt(tmp3)\r\n\r\n if tmp1\r\n #return locals()\r\n #return dict(user_solved_prblm=user_solved_prblm,prblm_coord=prblm_coord,user_coord=user_coord)\r\n\r\n return dict(rpl=rpl,rpl2=rpl2)\r\n","repo_name":"articuno12/OJ","sub_path":"models/pr.py","file_name":"pr.py","file_ext":"py","file_size_in_byte":8744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"4259004705","text":"from timeout_decorator import *\nfrom subprocess import call\nimport random\nimport sys\nimport os\n\n@timeout(10)\ndef questions():\n for i in range(50):\n a=random.randint(1,999999999)\n b=random.randint(1,999999999)\n print(\"Question\",i,\":\",a,\"+\",b)\n print(\"Your answer:\")\n sys.stdout.flush()\n c=input()\n try:\n c=int(c)\n except:\n print(\"Hey! Numbers only! The teacher is not amused.\")\n sys.stdout.flush()\n exit()\n if(c!=a+b):\n print(\"Wrong! Go back to grade school and learn your addition!\")\n sys.stdout.flush()\n exit()\n\nprint(\"John just noticed his homework is due in 10 seconds!\")\nprint(\"Help him finish his homework, which contains 50 additions.\")\ntry:\n questions()\n print(\"You did it! John would like to reward you with a shell.\")\n print(\"Find the flag there!\")\n sys.stdout.flush()\n call(\"/bin/bash\")\nexcept TimeoutError:\n print(\"You took too much time! The homework was collected and John is now a very sad kid.\")\n\n","repo_name":"rkevin-arch/ECS189M","sub_path":"challenges/linux_misc/addition/dist/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"24"} +{"seq_id":"35775814048","text":"from PySide2 import QtWidgets, QtGui\n\nfrom ui.binary_interaction_parameters_ui import Ui_FormBinaryParameters\n\n\nclass EditBinaryInteractionParametersView(QtWidgets.QWidget, Ui_FormBinaryParameters):\n def __init__(self, controller, parent=None):\n super().__init__(parent)\n self.setupUi(self)\n\n icon = QtGui.QIcon()\n icon.addPixmap(\n QtGui.QPixmap(\":/images/main_logo.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off\n )\n self.setWindowIcon(icon)\n\n from Controllers.EditBinaryInteractionParametersController import (\n EditBinaryInteractionParametersController,\n )\n\n self.controller: EditBinaryInteractionParametersController = controller\n\n self.btn_ok.clicked.connect(self.clicked_ok)\n self.btn_cancel.clicked.connect(self.clicked_cancel)\n self.btn_setZero.clicked.connect(self.clicked_setZero)\n self.btn_setSymmetric.clicked.connect(self.clicked_setSymmetric)\n # self.btn_fitToExp.clicked.connect(self.clicked_fitToExp)\n\n def clicked_ok(self):\n self.controller.okClicked()\n\n def clicked_cancel(self):\n self.controller.cancelClicked()\n\n def clicked_setZero(self):\n self.controller.setZeroClicked()\n\n def clicked_setSymmetric(self):\n self.controller.setSymmetricClicked()\n\n # def clicked_fitToExp(self):\n # self.controller.fitToExpClicked()\n","repo_name":"marcusbfs/Sindri","sub_path":"Sindri/Views/EditBinaryInteractionParametersView.py","file_name":"EditBinaryInteractionParametersView.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"24"} +{"seq_id":"9884975713","text":"#!/usr/bin/python\nimport serial # for UART\nimport smbus # for I2C \nimport threading # for periodic sensor check\n\n# define I2C address for arduino\naddress = 0x00\n\n# define UART port name and baudrate\nuartPortName = \"/dev/tty-ACM0\" \nbaudRate = 115200\n\n# initialize variable to store fuel sensor reading\nsensorValue = 0\n\n# define function to check fuel sensor periodically \ndef checkSensor(): \n\n i2c.write_byte(address, arduinoCommands[\"AT+SENS=?\"]) # command Arduino to get sensor's value\n arduinoRsp = i2c.read_i2c_block_data(address, 0,2) # Arduino sends sensor value in two bytes but as int digits\n sensorValue = arduinoRsp[0]*100+arduinoRsp[1] # combine to obtain the reading\n threading.Timer(1, checkSensor).start() # check every second\n\n \n# define functions to carry out the UART terminal commands \ndef setRelay(command): \n\n i2c.write_byte(address, arduinoCommands[command]) # command Arduino to control the relays \n return \"^OK\\r\\n\" # return the response\n\ndef readSensor(command):\n return \"^OK\\r\\n\" + str(sensorValue) + \"\\r\\n\" # return the response with last fuel sensor read value \n\n \n# map the UART terminal commands to the respective functions\nuartCommands = {\n \"AT+RLYON=1\" : setRelay,\n \"AT+RLYON=2\" : setRelay,\n \"AT+RLYOFF=1\" : setRelay,\n \"AT+RLYOFF=2\" : setRelay,\n \"AT+SENS=?\" : readSensor,\n }\n\n# values to be send to Arduino for each command, Arduino operates according to the value it receives\narduinoCommands = {\n \"AT+RLYON=1\" : 1,\n \"AT+RLYON=2\" : 2,\n \"AT+RLYOFF=1\" : 3,\n \"AT+RLYOFF=2\" : 4,\n \"AT+SENS=?\" : 5,\n }\n \n# define a function to read a line from UART terminal \ndef readLine(port):\n receivedLine = \"\"\n while True:\n receivedChar = port.read() \n receivedLine += receivedChar\n if receivedChar=='\\r' or receivedChar=='':\n return receivedLine\n\n# initialize the I2C bus\ni2c = smbus.SMBus(0)\n\n# initialize the UART terminal\nuartPort = serial.Serial(uartPortName, baudRate)\n\n# send reset response to UART terminal as script starts\nuartPort.write(\"^RESET\\r\\n\")\n\n# start periodic sensor check\ncheckSensor()\n \nwhile True:\n receivedCommand = readLine(uartPort) # read the UART terminal command\n \n if receivedCommand in uartCommands: # check if the received UART terminal command is valid \n rpiRSP = uartCommands[receivedCommand](receivedCommand) # process the command \n uartPort.write(rpiRSP) # send the response to UART terminal\n else: \n uartPort.write(\"Invalid command\\r\\n\")\n\n \n \n","repo_name":"kadiraktass/Smove","sub_path":"firmware/rpi_master.py","file_name":"rpi_master.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"40229924210","text":"#!/usr/bin/env python\nimport numpy as np\nimport rospy\nimport roslib\nimport tf\nimport math\nfrom tf.transformations import euler_from_quaternion\nimport copy\nimport time\nimport matplotlib.pyplot as plt\nimport sys, select, os\nif os.name == 'nt':\n import msvcrt\nelse:\n import tty, termios\nfrom geometry_msgs.msg import PoseStamped, Twist, Pose, PoseWithCovariance\nfrom nav_msgs.msg import Odometry\nfrom sensor_msgs.msg import Imu, LaserScan\nfrom tf.transformations import euler_from_quaternion\nfrom pathplanningmqp.msg import transform\n\nclass lqr_controller:\n def __init__(self):\n print(\"Creating LQR Controller Node\")\n print(\"............................\")\n rospy.init_node('LQR_Controller')\n self.listener = tf.TransformListener()\n\n self.vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size = 2)\n self.odom_sub = rospy.Subscriber('/odom', Odometry, callback=self.odom_callback)\n self.imu_sub = rospy.Subscriber('/imu', Imu, callback=self.imu_callback)\n self.scan_sub = rospy.Subscriber('/scan', LaserScan, callback=self.scan_callback)\n self.trans_sub = rospy.Subscriber('/linear_trans', transform, callback=self.trans_callback)\n self.odom_msg = Odometry()\n self.pose_msg = Pose()\n self.vel_msg = Twist()\n self.imu_msg = Imu()\n self.scan_msg = LaserScan()\n self.trans_msg = transform()\n self.odom_updated = False\n self.imu_updated = False\n self.scan_updated = False\n self.trans_updated = False\n\n def odom_callback(self, msg):\n self.odom_msg = msg\n self.odom_updated = True\n\n def imu_callback(self, msg):\n self.imu_msg = msg\n self.imu_updated = True\n\n def scan_callback(self, msg):\n self.scan_msg = msg\n self.scan_updated = True\n def trans_callback(self, msg):\n self.trans_msg = msg\n self.trans_updated = True\n\nif __name__ == \"__main__\":\n if os.name != 'nt':\n settings = termios.tcgetattr(sys.stdin)\n try:\n start_time = time.time()\n Robot = lqr_controller()\n for i in range(0,20):\n Robot.vel_msg.linear.x = 0\n Robot.vel_msg.angular.z = 0\n Robot.vel_pub.publish(Robot.vel_msg)\n print(\"STOPPING\")\n rospy.sleep(1)\n rospy.spin()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"hoangminh2408/PathPlanningMQP2019","sub_path":"unused/emstop.py","file_name":"emstop.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"24"} +{"seq_id":"10969301264","text":"import turtle\np = turtle.Pen()\np.color('red','yellow')\np.begin_fill()\np.speed(0)\nwhile True:\n p.forward(200)\n p.left(170)\n if abs(p.pos()) < 1:\n break\np.end_fill()\nturtle.exitonclick()\n","repo_name":"sachinyadav3496/DataScienceWorkshop","sub_path":"notebooks/Code/turtle1.py","file_name":"turtle1.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"22474563073","text":"import random\nimport sys\nimport time\nimport pygame as pg\nimport sounds\nfrom time import sleep\nfrom alien import Alien\nfrom bullet import Bullet, SpecialBullet\nfrom item import Item\n\nclock = pg.time.Clock()\nFPS = 120\nreset = 0\n\ngameOverButtons = [\"retry\", \"menu\", \"quit\"]\npauseButtons = [\"play\", \"menu\", \"quit\"]\n\n\ndef checkEvents(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets, charged_bullets):\n \"\"\"Respond to keypresses and mouse events.\"\"\"\n for event in pg.event.get():\n # Check for quit event\n if event.type == pg.QUIT:\n sys.exit()\n\n # Check for key down has been pressed\n elif event.type == pg.KEYDOWN:\n checkKeydownEvents(event, setting, screen, stats, sb, ship, aliens, bullets, eBullets)\n if (stats.gameActive):\n continue\n if event.key == pg.K_UP:\n sounds.control_menu.play()\n bMenu.up()\n elif event.key == pg.K_DOWN:\n sounds.control_menu.play()\n bMenu.down()\n elif event.key == pg.K_RETURN:\n sounds.select_menu.play()\n selectedName, selectedBtn = bMenu.getSelectedButton()\n if selectedBtn:\n buttonAction(stats, selectedName, setting, screen, ship, aliens, bullets, eBullets)\n elif event.type == pg.KEYUP:\n checkKeyupEvents(event, setting, screen, stats, ship, bullets, charged_bullets)\n\n elif event.type == pg.MOUSEMOTION:\n if not stats.gameActive:\n mouseBtnName, mouseBtn = bMenu.mouseCheck(event.pos[0], event.pos[1])\n if mouseBtn is not None:\n selectedName, selectedBtn = bMenu.getSelectedButton()\n if mouseBtn is not selectedBtn:\n sounds.control_menu.play()\n bMenu.selectByName(mouseBtnName)\n\n elif event.type == pg.MOUSEBUTTONDOWN:\n if not stats.gameActive:\n pressed = pg.mouse.get_pressed()\n if (pressed[0]):\n pos = pg.mouse.get_pos()\n mouseBtnName, mouseBtn = bMenu.mouseCheck(pos[0], pos[1])\n if mouseBtn is not None:\n sounds.select_menu.play()\n buttonAction(stats, mouseBtnName, setting, screen, ship, aliens, bullets, eBullets)\n\n\ndef buttonAction(stats, selectedName, setting, screen, ship, aliens, bullets, eBullets):\n if selectedName in ('play', 'retry'):\n checkPlayBtn(setting, screen, stats, ship, aliens, bullets, eBullets)\n elif selectedName == 'menu':\n stats.setGameLoop('mainMenu')\n stats.resetStats()\n elif selectedName == 'quit':\n pg.time.delay(300)\n sys.exit()\n\n\ndef checkKeydownEvents(event, setting, screen, stats, sb, ship, aliens, bullets, eBullets):\n \"\"\"Response to kepresses\"\"\"\n if event.key == pg.K_RIGHT:\n # Move the ship right\n ship.movingRight = True\n elif event.key == pg.K_LEFT:\n # Move the ship left\n ship.movingLeft = True\n elif event.key == pg.K_UP:\n # Move the ship up\n ship.movingUp = True\n elif event.key == pg.K_DOWN:\n # Move the ship down\n ship.movingDown = True\n elif event.key == pg.K_TAB:\n # Change the style of trajectory of bullet\n if (ship.trajectory < 4):\n ship.trajectory += 1\n else:\n ship.trajectory = 0\n elif event.key == pg.K_SPACE:\n if not stats.paused:\n if ship.checkReadyToShoot() and (len(bullets) < 10):\n sounds.attack.play()\n newBullet = Bullet(setting, screen, ship, ship.trajectory)\n bullets.add(newBullet)\n ship.setNextShootTime()\n ship.chargeGaugeStartTime = pg.time.get_ticks()\n ship.shoot = True\n\n elif event.key == pg.K_x or event.key == 167:\n # Ultimate key\n useUltimate(setting, screen, stats, bullets, stats.ultimatePattern)\n # Check for pause key\n elif event.key == pg.K_p or event.key == 181:\n sounds.paused.play()\n pause(stats)\n # Add speed control key\n elif event.key == pg.K_q or event.key == 172:\n setting.halfspeed()\n elif event.key == pg.K_w or event.key == 173:\n setting.doublespeed()\n elif event.key == pg.K_c or event.key == 168:\n # interception Key\n setting.checkBtnPressed += 1\n if setting.checkBtnPressed % 2 != 0:\n setting.interception = True\n else:\n setting.interception = False\n elif event.key == pg.K_F12:\n # Reset Game\n sounds.button_click_sound.play()\n resetGame()\n elif event.key == pg.K_ESCAPE:\n # Quit game\n sounds.button_click_sound.play()\n pg.time.delay(300)\n sys.exit()\n\n\ndef checkKeyupEvents(event, setting, screen, stats, ship, bullets, charged_bullets):\n \"\"\"Response to keyrealeses\"\"\"\n global gauge\n if event.key == pg.K_RIGHT:\n ship.movingRight = False\n elif event.key == pg.K_LEFT:\n ship.movingLeft = False\n elif event.key == pg.K_UP:\n ship.movingUp = False\n elif event.key == pg.K_DOWN:\n ship.movingDown = False\n elif event.key == pg.K_SPACE:\n if not stats.paused:\n if (ship.chargeGauge == 100):\n sounds.charge_shot.play()\n newBullet = Bullet(setting, screen, ship, ship.trajectory, 2, 5)\n bullets.add(newBullet)\n ship.chargeGauge = 0\n elif (50 <= ship.chargeGauge):\n sounds.charge_shot.play()\n newBullet = Bullet(setting, screen, ship, ship.trajectory, 3)\n charged_bullets.add(newBullet)\n ship.shoot = False\n\n\ndef pause(stats):\n \"\"\"Pause the game when the pause button is pressed\"\"\"\n stats.gameActive = False\n stats.paused = True\n\n\ndef resetGame():\n global reset\n reset = 1\n stats.highScore = 0\n stats.saveHighScore()\n\n\ndef checkPlayBtn(setting, screen, stats, ship, aliens, bullets, eBullets):\n \"\"\"Start new game if playbutton is pressed\"\"\"\n if not stats.gameActive and not stats.paused:\n setting.initDynamicSettings()\n stats.resetStats()\n stats.gameActive = True\n\n # Reset the alien and the bullets\n aliens.empty()\n bullets.empty()\n eBullets.empty()\n\n # Create a new fleet and center the ship\n createFleet(setting, stats, screen, ship, aliens)\n ship.centerShip()\n\n elif not stats.gameActive and stats.paused:\n # IF the game is not running and game is paused unpause the game\n stats.gameActive = True\n stats.paused = False\n\n\ndef getNumberAliens(setting, alienWidth):\n \"\"\"Determine the number of aliens that fit in a row\"\"\"\n availableSpaceX = setting.screenWidth - 2 * alienWidth\n numberAliensX = int(availableSpaceX / (2 * alienWidth))\n return numberAliensX\n\n\ndef getNumberRows(setting, shipHeight, alienHeight):\n \"\"\"Determine the number of rows of aliens that fit on the screen\"\"\"\n availableSpaceY = (setting.screenHeight - (3 * alienHeight) - shipHeight)\n numberRows = int(availableSpaceY / (3 * alienHeight))\n return numberRows\n\n\ndef createAlien(setting, stats, screen, aliens, alienNumber, rowNumber):\n sounds.stage_clear.play()\n alien = Alien(setting, screen, stats.level*3)\n alienWidth = alien.rect.width\n screenRect = alien.screen.get_rect()\n alien.x = alienWidth + 2 * alienWidth * alienNumber\n \"\"\" random position of enemy will be created in game window\"\"\"\n alien.rect.x = random.randrange(0, setting.screenWidth - alien.x / 2)\n alien.rect.y = (alien.rect.height + random.randrange(0, setting.screenHeight - alien.rect.height * 2)) / 1.5\n aliens.add(alien)\n\ndef createItem(setting, screen, posx, posy, type, items):\n \"\"\"add item func\"\"\"\n item = Item(setting, screen, type, posx, posy)\n screenRect = item.screen.get_rect()\n items.add(item)\n\n\ndef createFleet(setting, stats, screen, ship, aliens):\n \"\"\"Create a fleet of aliens\"\"\"\n alien = Alien(setting, screen, stats.level*3)\n numberAliensX = getNumberAliens(setting, alien.rect.width)\n numberRows = getNumberRows(setting, ship.rect.height, alien.rect.height)\n\n # create the first row of aliens\n for rowNumber in range(numberRows):\n for alienNumber in range(numberAliensX):\n createAlien(setting, stats, screen, aliens, alienNumber, rowNumber)\n\n\ndef checkFleetEdges(setting, aliens):\n \"\"\"Respond if any aliens have reached an edge\"\"\"\n for alien in aliens.sprites():\n if alien.checkEdges():\n changeFleetDir(setting, aliens)\n break\n\n\ndef checkFleetBottom(setting, stats, sb, screen, ship, aliens, bullets, eBullets):\n \"\"\"Respond if any aliens have reached an bottom of screen\"\"\"\n for alien in aliens.sprites():\n if alien.checkBottom():\n shipHit(setting, stats, sb, screen, ship, aliens, bullets, eBullets)\n\n\ndef changeFleetDir(setting, aliens):\n \"\"\"Change the direction of aliens\"\"\"\n for alien in aliens.sprites():\n alien.rect.y += setting.fleetDropSpeed\n setting.fleetDir *= -1\n\n\ndef shipHit(setting, stats, sb, screen, ship, aliens, bullets, eBullets):\n \"\"\"Respond to ship being hit\"\"\"\n if stats.shipsLeft > 0:\n sounds.explosion_sound.play()\n stats.shipsLeft -= 1\n stats.ultimateGauge = 0\n ship.centerShip()\n setting.newStartTime = pg.time.get_ticks()\n else:\n stats.gameActive = False\n checkHighScore(stats, sb)\n\n\ndef updateAliens(setting, stats, sb, screen, ship, aliens, bullets, eBullets):\n \"\"\"Update the aliens\"\"\"\n checkFleetEdges(setting, aliens)\n checkFleetBottom(setting, stats, sb, screen, ship, aliens, bullets, eBullets)\n aliens.update(setting, screen, ship, aliens, eBullets)\n\n #look for alien-ship collision\n if pg.sprite.spritecollideany(ship, aliens):\n #74\n shipHit(setting, stats, sb, screen, ship, aliens, bullets, eBullets)\n #sb.prepShips()\n\n\ndef updateBullets(setting, screen, stats, sb, ship, aliens, bullets, eBullets, charged_bullets, items):\n \"\"\"update the position of the bullets\"\"\"\n #check if we are colliding\n bullets.update()\n eBullets.update()\n charged_bullets.update()\n checkBulletAlienCol(setting, screen, stats, sb, ship, aliens, bullets, eBullets, charged_bullets, items)\n checkEBulletShipCol(setting, stats, sb, screen, ship, aliens, bullets, eBullets)\n\n #if bullet goes off screen delete it\n for bullet in eBullets.copy():\n screenRect = screen.get_rect()\n if bullet.rect.top >= screenRect.bottom:\n eBullets.remove(bullet)\n for bullet in bullets.copy():\n if bullet.rect.bottom <= 0:\n bullets.remove(bullet)\n\n if setting.interception:\n pg.sprite.groupcollide(bullets, eBullets, bullets, eBullets)\n\n\ndef updateItems(setting, screen, stats, sb, ship, aliens, bullets, eBullets, items):\n \"\"\"update the position of the bullets\"\"\"\n #check if we are colliding\n items.update()\n #if bullet goes off screen delete it\n for item in items.sprites():\n screenRect = screen.get_rect()\n if item.rect.top >= screenRect.bottom:\n items.remove(item)\n for item in items.sprites():\n if item.rect.bottom <= 0:\n items.remove(item)\n for item in items.sprites():\n if item.rect.centerx -30 < ship.rect.x < item.rect.x +30 and item.rect.centery -20 < ship.rect.centery < item.rect.centery +20:\n if item.type == 1:\n stats.shipsLeft += 1\n items.empty()\n\n\ndef checkBulletAlienCol(setting, screen, stats, sb, ship, aliens, bullets, eBullets, charged_bullets, items):\n \"\"\"Detect collisions between alien and bullets\"\"\"\n collisions = pg.sprite.groupcollide(aliens, bullets, False, False)\n collisions.update(pg.sprite.groupcollide(aliens, charged_bullets, False, True))\n if collisions:\n sounds.enemy_explosion_sound.play()\n\n\n for c in collisions:\n setting.explosions.add(c.rect.x, c.rect.y)\n i = random.randrange(100)\n if i<=10:\n createItem(setting, screen, c.rect.x, c.rect.y, 1, items)\n\n\n for alien in collisions :\n for bullet in collisions[alien] :\n alien.hitPoint -= bullet.damage\n bullets.remove(bullet)\n if alien.hitPoint <= 0 :\n setting.explosions.add(alien.rect.x, alien.rect.y)\n sounds.enemy_explosion_sound.play()\n aliens.remove(alien)\n\n # Increase the ultimate gauge, upto 100\n stats.ultimateGauge += setting.ultimateGaugeIncrement\n if stats.ultimateGauge > 100:\n stats.ultimateGauge = 100\n for aliens in collisions.values():\n stats.score += setting.alienPoints * len(aliens)\n checkHighScore(stats, sb)\n #alien drop item by random probability\n\n\n sb.prepScore()\n #Check if there are no more aliens\n if len(aliens) == 0:\n # Destroy exsiting bullets and create new fleet\n sounds.stage_clear.play()\n # bullets.empty()\n eBullets.empty()\n setting.increaseSpeed() #Speed up game\n stats.level += 1\n setting.setIncreaseScoreSpeed(stats.level)\n sb.prepLevel()\n\n createFleet(setting, stats, screen, ship, aliens)\n # Invincibility during 2 sec\n setting.newStartTime = pg.time.get_ticks()\n\n\ndef checkEBulletShipCol(setting, stats, sb, screen, ship, aliens, bullets, eBullets):\n \"\"\"Check for collisions using collision mask between ship and enemy bullets\"\"\"\n for ebullet in eBullets.sprites():\n if pg.sprite.collide_mask(ship, ebullet):\n shipHit(setting, stats, sb, screen, ship, aliens, bullets, eBullets)\n #sb.prepShips()\n eBullets.empty()\n\n\ndef checkHighScore(stats, sb):\n \"\"\"Check to see if high score has been broken\"\"\"\n if stats.score > stats.highScore:\n stats.highScore = stats.score\n stats.saveHighScore()\n\n\ndef updateUltimateGauge(setting, screen, stats, sb):\n \"\"\"Draw a bar that indicates the ultimate gauge\"\"\"\n x = sb.levelRect.left - 130\n y = sb.levelRect.top + 4\n gauge = stats.ultimateGauge\n ultimateImg = pg.font.Font('Fonts/Square.ttf', 10).render(\"POWER SHOT(X)\", True, (255, 255, 255),\n (255, 100, 0))\n ultimateRect = ultimateImg.get_rect()\n ultimateRect.x = x + 5\n ultimateRect.y = y\n if gauge == 100:\n pg.draw.rect(screen, (255, 255, 255), (x, y, 100, 12), 0)\n pg.draw.rect(screen, (255, 100, 0), (x, y, gauge, 12), 0)\n screen.blit(ultimateImg, ultimateRect)\n else:\n pg.draw.rect(screen, (255, 255, 255), (x, y, 100, 12), 0)\n pg.draw.rect(screen, (0, 255, 255), (x, y, gauge, 12), 0)\n\n\ndef UltimateDiamondShape(setting, screen, stats, sbullets):\n xpos = 10\n yCenter = setting.screenHeight + (setting.screenWidth / 50) * 20\n yGap = 0\n # Make a diamond pattern\n while xpos <= setting.screenWidth:\n if yGap == 0:\n sBullet = SpecialBullet(setting, screen, (xpos, yCenter))\n sbullets.add(sBullet)\n else:\n upBullet = SpecialBullet(setting, screen, (xpos, yCenter + yGap))\n downBullet = SpecialBullet(setting, screen, (xpos, yCenter - yGap))\n sbullets.add(upBullet)\n sbullets.add(downBullet)\n if xpos <= setting.screenWidth / 2:\n yGap += 20\n else:\n yGap -= 20\n xpos += setting.screenWidth / 30\n\n\ndef useUltimate(setting, screen, stats, sbullets, pattern):\n if stats.ultimateGauge != 100:\n return\n if pattern == 1:\n sounds.ult_attack.play()\n UltimateDiamondShape(setting, screen, stats, sbullets)\n # elif pattern == 2:\n #\t\tmake other pattern\n stats.ultimateGauge = 0\n\n\ndef updateChargeGauge(ship):\n gauge = 0\n if ship.shoot == True:\n gauge = 100 * ((pg.time.get_ticks() - ship.chargeGaugeStartTime) / ship.fullChargeTime)\n if (100 < gauge):\n gauge = 100\n ship.chargeGauge = gauge\n\n\ndef drawChargeGauge(setting, screen, ship, sb):\n x = sb.levelRect.left - 240\n y = sb.levelRect.top + 4\n color = (50, 50, 50)\n if (ship.chargeGauge == 100):\n color = (255, 0, 0)\n elif (50 <= ship.chargeGauge):\n color = (255, 120, 0)\n\n pg.draw.rect(screen, (255, 255, 255), (x, y, 100, 10), 0)\n pg.draw.rect(screen, color, (x, y, ship.chargeGauge, 10), 0)\n\n\ndef updateScreen(setting, screen, stats, sb, ship, aliens, bullets, eBullets, charged_bullets, bMenu, bgManager, items):\n \"\"\"Update images on the screen and flip to the new screen\"\"\"\n # Redraw the screen during each pass through the loop\n # Fill the screen with background color\n # Readjust the quit menu btn position\n global clock, FPS, gameOverButtons, pauseButtons\n bMenu.drawMenu()\n bgManager.update()\n bgManager.draw()\n\n # draw \"Dodged!\" text if ship is invincibile\n if pg.time.get_ticks() - setting.newStartTime < 1500:\n text1 = pg.font.Font('Fonts/Square.ttf', 20).render(\"Dodged!\", True, (255, 255, 255), )\n screen.blit(text1, (ship.rect.x + 40, ship.rect.y))\n\n # draw all the bullets\n for bullet in bullets.sprites():\n bullet.drawBullet()\n\n # draw all the enemy bullets\n for ebull in eBullets.sprites():\n ebull.drawBullet()\n\n for charged_bullet in charged_bullets.sprites():\n charged_bullet.drawBullet()\n\n ship.blitme()\n aliens.draw(screen)\n\n for i in items:\n i.update()\n i.drawitem()\n\n # Update Ultimate Gauge\n updateUltimateGauge(setting, screen, stats, sb)\n\n # Update and draw Charge Gauge\n updateChargeGauge(ship)\n drawChargeGauge(setting, screen, ship, sb)\n\n # Draw the scoreboard\n sb.prepScore()\n sb.prepHighScore()\n sb.prepLevel()\n sb.showScore()\n\n # Draw the play button if the game is inActive\n if not stats.gameActive:\n if (stats.shipsLeft < 1):\n bMenu.setMenuButtons(gameOverButtons)\n scoreImg = pg.font.Font('Fonts/Square.ttf', 50).render(\"Score: \" + str(stats.score), True, (0, 0, 0),\n (255, 255, 255))\n screen.fill((0, 0, 0))\n screen.blit(scoreImg, ((setting.screenWidth - scoreImg.get_width()) / 2, 120))\n screen.blit(setting.gameOverImage, (20, 30))\n else:\n bMenu.setMenuButtons(pauseButtons)\n bMenu.drawMenu()\n setting.explosions.draw(screen)\n # Make the most recently drawn screen visable.\n pg.display.update()\n clock.tick(FPS)\n","repo_name":"anjinsung/Galtron","sub_path":"gameFunctions.py","file_name":"gameFunctions.py","file_ext":"py","file_size_in_byte":18809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"24"} +{"seq_id":"11018106019","text":"from django.core import validators\nfrom django.db import models\nfrom django.contrib.auth import models as auth_models\n\nfrom cosplay_project.core.validators import validate_only_letters, validate_only_letters_and_spaces\n\n\nclass AppUser(auth_models.AbstractUser):\n MIN_LENGTH_FIRST_NAME = 5\n MAX_LENGTH_FIRST_NAME = 25\n MIN_LENGTH_USERNAME = 5\n MAX_LENGTH_USERNAME = 20\n MIN_LENGTH_LAST_NAME = 5\n MAX_LENGTH_LAST_NAME = 25\n MAX_LENGTH_DESCRIPTION = 100\n\n email = models.EmailField(\n unique=True,\n null=False,\n blank=False,\n )\n\n first_name = models.CharField(\n max_length=MAX_LENGTH_FIRST_NAME,\n validators=(\n validators.MinLengthValidator(MIN_LENGTH_FIRST_NAME, 'First Name must have at least 5 letters!'),\n validate_only_letters,\n ),\n null=False,\n blank=False,\n )\n\n last_name = models.CharField(\n max_length=MAX_LENGTH_LAST_NAME,\n validators=(\n validators.MinLengthValidator(MIN_LENGTH_LAST_NAME, 'Last Name must have at least 5 letters!'),\n validate_only_letters,\n ),\n null=False,\n blank=False,\n )\n\n username = models.CharField(\n 'Username',\n unique=True,\n max_length=MAX_LENGTH_USERNAME,\n validators=(\n validators.MinLengthValidator(MIN_LENGTH_USERNAME, 'Username must have at least 5 letters!'),\n validate_only_letters,\n )\n )\n\n description = models.TextField(\n max_length=MAX_LENGTH_DESCRIPTION,\n null=False,\n blank=False,\n )\n\n age = models.PositiveIntegerField(\n null=False,\n blank=False,\n )\n\n\nclass Event(models.Model):\n TITLE_MIN_LENGTH = 5\n TITLE_MAX_LENGTH = 50\n URL_MIN_LENGTH = 5\n URL_MAX_LENGTH = 200\n\n title = models.CharField(\n max_length=TITLE_MAX_LENGTH,\n validators=(\n validators.MinLengthValidator(TITLE_MIN_LENGTH, f'Please add at least {TITLE_MIN_LENGTH} letters'),\n validate_only_letters_and_spaces,\n )\n )\n\n date_of_event = models.DateField()\n url = models.URLField(\n max_length=URL_MAX_LENGTH,\n validators=(\n validators.MinLengthValidator(URL_MIN_LENGTH, f'Please add at least {URL_MIN_LENGTH} letters'),\n )\n )\n\n def __str__(self):\n return f'{self.title} is added with date {self.date_of_event}'\n","repo_name":"VladimirStoqnov/My-Project","sub_path":"cosplay_project/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"36894498968","text":"#!/usr/bin/python\n\nimport random\n\nclass Node(object):\n def __init__(self, value):\n self.value = value\n self.next = None\n\nclass LinkedList(object):\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert_node(self, value):\n if self.head == None:\n self.head = Node(value)\n self.tail = self.head\n else:\n self.tail.next = Node(value)\n\ndef merge_linked_lists(node1, node2):\n if node1 == None:\n return node2\n if node2 == None:\n return node1\n if node1.value <= node2.value:\n node1.next = merge_linked_lists(node1.next, node2)\n return node1\n else:\n node2.next = merge_linked_lists(node2.next, node1)\n return node2\n\ndef main():\n linked_list_one = LinkedList()\n linked_list_two = LinkedList()\n for ii in range(1, 10):\n linked_list_one.insert_node(random.randint(1, 1000))\n linked_list_two.insert_node(random.randint(1, 1000))\n node_one = merge_linked_lists(linked_list_one.head, linked_list_two.head)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mihirkelkar/languageprojects","sub_path":"python/Merge_Linked_List/merge_linked_list.py","file_name":"merge_linked_list.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"43408907115","text":"# © 2008-2022 Deltatech\n# Dorin Hongu This information is password protected.'\n '

Please log in with proper credentials.

', 401,\n {'WWW-Authenticate': 'Basic realm=\"Login Required\"'})\n\ndef requires_auth_admin(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n auth = request.authorization\n if not auth or not check_auth_admin(auth.username, auth.password):\n return authenticate()\n return f(*args, **kwargs)\n return decorated\n\n\n\n#%%\n@lessons.route('/addLesson/////', methods=['GET', 'POST'])\n@login_required\ndef addLesson(classid, courseid, dow, per,lessonid):\n cat='0'\n classid = courseid[0:5]\n \n form = AddLessonForm()\n form.title = \"Plan Lesson for \" + courseid\n schedid = dow+per\n form.scheduleid.data = schedid\n form.periodid.data = schedid[2:]\n form.start_time.data = Period.query.filter_by(periodid=schedid[2:]).first().start_time\n form.end_time.data = Period.query.filter_by(periodid=schedid[2:]).first().end_time\n form.subject.data = courseid[6:]\n form.room.data = Group.query.filter_by(classid=classid).first().room\n form.grade.data = courseid[0:1]\n form.classid.data = courseid[0:5]\n form.courseid.data = courseid\n form.total.data = Group.query.filter_by(classid=classid).first().amount\n form.content.data = ''\n \n if lessonid == 'a':\n form.title = \"Add Lesson for \" + courseid\n cat='Add'\n else:\n cat=\"Plan\"\n return render_template(\"addLesson.html\", form = form, cat=cat, lessonid=lessonid, teacher=current_user.username, value=\"add_lesson\") \n\n@lessons.route('/update_lessons/', methods=['GET', 'POST'])\n@login_required\ndef udpate_lessons(lessonid):\n date = request.form['date']\n scheduleid = request.form['scheduleid']\n periodid = request.form['scheduleid'][2:]\n start_time = request.form['start_time']\n end_time = request.form['end_time']\n subject = request.form['courseid'][6:]\n room = request.form['room']\n grade = request.form['courseid'][0:1]\n classid = request.form['courseid'][0:5]\n courseid = request.form['courseid']\n total = request.form['total']\n content = request.form['content']\n topic = \"lesson\"\n teacher = current_user.username\n \n if lessonid == 'a':\n df = pd.DataFrame(columns = ['lessondate','scheduleid', 'periodid', 'start_time', 'end_time', 'subject', 'room', 'grade', 'classid', 'courseid', 'total', 'content', 'teacher'])\n entry = pd.Series([date, scheduleid, periodid, start_time, end_time, subject, room, grade, classid, courseid, total, content, teacher], index=df.columns)\n df = df.append(entry, ignore_index=True)\n df = df.set_index('periodid')\n df.fillna('', inplace=True)\n print(df) \n df.to_sql('lessons', engine, if_exists=\"append\")\n\n else:\n topic = \"plan for \" + courseid\n query = \"UPDATE lessons set plan = '\" + content + \"' WHERE lessonid = '\" + lessonid + \"' and teacher = '\" + teacher +\"';\"\n with engine.begin() as conn: # TRANSACTION\n conn.execute(query)\n return render_template(\"confirmation.html\" , topic=topic, value=\"edit_lesson\", teacher = current_user.username)\n\n\n#%%\n@lessons.route('/lessons/')\n@login_required\n@requires_auth_admin\ndef display_lessons(day):\n if current_user.username != 'rfriedman':\n return render_template('denied.html')\n else:\n global current_week\n current_week = Week.query.first().today\n return_all = 0\n title = \"My Lessons\"\n if day=='all':\n return_all=1\n lessons = Lessons.query.filter_by(teacher=current_user.username).order_by(Lessons.lessondate.desc(),Lessons.periodid).all()\n else:\n lessons = Lessons.query.filter_by(courseid=day, teacher=current_user.username).order_by(Lessons.lessondate.desc(),Lessons.periodid).all()\n return render_template('lessons.html', title = title, lessons = lessons, return_all=return_all, current_week=current_week) \n\n#%%\n@lessons.route('/edit_lesson//')\n@login_required\ndef edit_lesson(lessonid, content):\n teacher=current_user.username\n #sql_df = pd.read_sql_query(\"Select * from period\" , engine, index_col='periodid')\n\n return render_template('edit.html', lessonid=lessonid, content=content,teacher=teacher)\n\n#%%\n@lessons.route('/update_lesson//')\n@login_required\ndef update_lesson(lessonid, newcontent):\n teacher = current_user.username\n query = \"UPDATE lessons set content = '\" + newcontent + \"' WHERE lessonid = '\" + lessonid + \"' and teacher ='\" +teacher +\"';\"\n with engine.begin() as conn: # TRANSACTION\n conn.execute(query)\n return render_template(\"confirmation.html\", topic=\"updated lesson\", value=\"update_lesson\", teacher = current_user.username)\n\n\n@lessons.route('/delete_lesson/')\ndef delete_lesson(lessonid):\n topic = \"delete lesson\"\n print(lessonid)\n query = \"DELETE FROM lessons WHERE lessonid = \" + lessonid + \";\"\n #df = pd.read_sql_query(query, engine)\n with engine.begin() as conn: # TRANSACTION\n conn.execute(query)\n print('lesson has been deleted')\n return render_template('confirmation.html', topic=topic, value=\"delete_lesson\", teacher = current_user.username)\n\n\n","repo_name":"rachelf21/school_scheduling_app","sub_path":"app/lessons/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"44196321050","text":"import numpy as np\nimport itertools\nimport time\nfrom PIL import Image\n\nhardware = \"CPU\"\n\nN = 2048\nnSteps = 2048\nnRule = 102\nstart = \"random\"\n\ncolorAlive = \"#E06863\"\ncolorDead = \"#71FFA6\"\n\nfileFormat = \"png\"\n\nif hardware == 'CPU':\n from numpy.lib.stride_tricks import as_strided \n lib = np\n\nif hardware == 'GPU': \n import cupy as cp\n from cupy.lib.stride_tricks import as_strided\n lib = cp\n from cupy.lib.stride_tricks import as_strided\n\nmapToArray = lambda f, xs: np.array(list(map(f, xs)))\n\nformatPattern = lambda p: 2*mapToArray(int,p)-1\n\ndef getRules(): \n\n patterns = mapToArray(''.join, list(itertools.product(\"01\", repeat = 3)))[::-1]\n \n binary = np.binary_repr(nRule)\n binary = np.array([*('0'*((1<<3)-len(binary)) + binary)])\n \n zeros = np.where(binary == '0')[0]\n ones = np.where(binary == '1')[0]\n \n ruleToDead = mapToArray(formatPattern, patterns[zeros])\n ruleToAlive = mapToArray(formatPattern, patterns[ones] )\n \n return lib.array(ruleToDead ),\\\n lib.array(ruleToAlive)\n\ndef init():\n\n allCells = lib.empty((nSteps + 1, N), dtype = lib.int8)\n \n if start == 'random': allCells[0] = 2*lib.random.randint(0, 2, N) - 1\n else: allCells[0] = -lib.ones(N)\n if start == 'middle': allCells[0][N//2] = 1\n if start == 'left' : allCells[0][0] = 1\n if start == 'right' : allCells[0][N-1] = 1\n \n return allCells\n\ndef step(cells):\n \n # Creates sliding windows without additional memory\n # For numpy implementation can use sliding_window_view\n windows = lib.lib.stride_tricks.as_strided(cells, (cells.shape[0] - 2, 3), (1, 1))\n \n # Cells are -1 for Dead and 1 for Alive\n # Which means convolution with the fitting rule gives 3\n # One pass is actually enough, but the performance doesn't drop\n toDead = lib.where((lib.einsum('ij,kj->ik', windows, rules[0]) == 3).any(1))[0] + 1\n toAlive = lib.where((lib.einsum('ij,kj->ik', windows, rules[1]) == 3).any(1))[0] + 1\n \n cells[toAlive] = 1\n cells[toDead] = -1 \n return cells\n\ndef save():\n hex2rgb = lambda c: [int(c[i:i+2], 16) for i in (1, 2, 4)]\n \n colorAliveRGB = hex2rgb(colorAlive)\n colorDeadRGB = hex2rgb(colorDead)\n \n if hardware == 'GPU': image = allCells.get()\n if hardware == 'CPU': image = allCells\n \n image = image.repeat(3).reshape(nSteps + 1, N, 3).astype(np.int16)\n for i in range(3):\n image[:,:,i][image[:,:,i] == 1] = colorAliveRGB[i]\n image[:,:,i][image[:,:,i] == -1] = colorDeadRGB[i]\n \n image = Image.fromarray(image.astype(np.uint8))\n image.save(f\"run_{N}_{nSteps}_rule{nRule}_{start}_{hardware}.{fileFormat}\")\n\n \nrules = getRules()\n\nstartTime = time.time()\n\nallCells = init()\n\nfor i in range(1, nSteps + 1):\n allCells[i] = step(allCells[i-1].copy())\n\nendTime = time.time()\n\nsave()\n\nprint(f\"Runtime: {endTime - startTime :.2f} s\")\n","repo_name":"Dima-aka-dima/fast-automata-with-python","sub_path":"1d/main1d.py","file_name":"main1d.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"70409596543","text":"#write by kratos\n#about dict\n\n#dict:key-value的数据类型\n\ninfo = {\n 'stu001':\"kratos\",\n 'stu002':\"yang\",\n 'stu003':\"lincj\"\n}\n\nprint(info)\n#查\n#print(info[\"stu002\"])\nprint(info.get(\"stu004\")) #安全的获取方法,直接print不存在会报错。\n\n#增改 存在修改,不存在就增加\ninfo[\"stu002\"]=\"ming\"\ninfo[\"stu004\"]=\"uzi\"\n\n#删\ninfo.pop(\"stu002\")\n#del info[\"stu004\"]\n\n\n#多级字典嵌套及操作;key 最好用英文\n\ninfo1 = {\n \"RNG\":{\"xiaohu\":[21,\"gay\"]},\n \"EDG\":{\n \"clearlove\":[\"123\",\"4396\"]\n }\n}\n\nprint(info1[\"EDG\"][\"clearlove\"][0])\n\n\n#其他姿势\n\n#列出所有value\nprint(info.values())\n\n#列出所有keys\nprint(info.keys())\n\n#参数1如果不存在就创建它,value值为参数2\ninfo.setdefault(\"stu006\",\"124356\")\n\n#更新合并:update 相同key的更新value值,没有相同的添加进info\nb={\"stu001\":666,\"stu008\":32423}\ninfo.update(b)\n\n#初始化一个新的字典,value都为test,每个value指向的是同一个内存地址,所以在多层字典的时候,修改一个会修改所有的value\nc = dict.fromkeys([4,3,9],\"test\")\n\n#字典的循环\nfor i in info:\n print(i,info[i])\n\n\n\n\n","repo_name":"lin790292154/python_note","sub_path":"day2/dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"13890574018","text":"\"\"\"\r\nPurpose:\r\nCollect functions for generating grid points (evaluation points).\r\n1. grid_exp1\r\n2. grid_exp2\r\n3. grid_exp3\r\n4. grid_mmv\r\n@author: Tomoaki Yamada\r\n\"\"\"\r\n\r\n\r\ndef grid_exp1(xmin, xmax, num_grid):\r\n \"\"\"\r\n Exponential grid: For details, see Carroll (2012).\r\n params: xmin: minimum gridpoint.\r\n params: xmax: maximum gridpoint.\r\n params: num_grid: the number of gridpoints\r\n return: grid: evaluation points.\r\n \"\"\"\r\n\r\n import numpy as np\r\n\r\n dmax = np.log(xmax + 1.0)\r\n mesh = np.linspace(xmin, dmax, num_grid)\r\n grid = np.exp(mesh) - 1.0\r\n\r\n return grid\r\n\r\n\r\ndef grid_exp2(xmin, xmax, num_grid):\r\n \"\"\"\r\n double exponential grid: For details, see Carroll (2012).\r\n params: xmin: minimum gridpoint.\r\n params: xmax: maximum gridpoint.\r\n params: num_grid: the number of gridpoints\r\n return: grid: evaluation points.\r\n \"\"\"\r\n\r\n import numpy as np\r\n\r\n dmax = np.log(np.log(xmax + 1.0) + 1.0)\r\n mesh = np.linspace(xmin, dmax, num_grid)\r\n grid = np.exp(np.exp(mesh) - 1.0) - 1.0\r\n\r\n return grid\r\n\r\n\r\ndef grid_exp3(xmin, xmax, num_grid):\r\n \"\"\"\r\n triple exponential grid: For details, see Carroll (2012).\r\n params: xmin: minimum gridpoint.\r\n params: xmax: maximum gridpoint.\r\n params: num_grid: the number of gridpoints\r\n return: grid: evaluation points.\r\n \"\"\"\r\n\r\n import numpy as np\r\n\r\n dmax = np.log(np.log(np.log(xmax + 1.0) + 1.0) + 1.0)\r\n mesh = np.linspace(xmin, dmax, num_grid)\r\n grid = np.exp(np.exp(np.exp(mesh) - 1.0) - 1.0) - 1.0\r\n\r\n return grid\r\n\r\n\r\ndef grid_mmv(xmin, xmax, theta, num_grid):\r\n \"\"\"\r\n Generate grids proposed in Maliar, Maliar and Valli (2010,JEDC).\r\n params: xmin: minimum gridpoint.\r\n params: xmax: maximum gridpoint.\r\n params: theta: coefficient for concentration of gridpoint.\r\n params: num_grid: the number of gridpoints\r\n return: grid: evaluation points.\r\n \"\"\"\r\n\r\n import numpy as np\r\n\r\n # Equation (7) in Maliar et al. (2010,JEDC)\r\n tmp = np.empty(num_grid)\r\n for i in range(num_grid):\r\n tmp[i] = (float(i)/float(num_grid-1))**theta * xmax\r\n\r\n # adjust to [xmin,xmax]\r\n grid = np.empty(num_grid)\r\n grid[0] = xmin\r\n for i in range(1, num_grid, 1):\r\n grid[i] = grid[i-1] + (tmp[i]-tmp[i-1]) / xmax*(xmax-xmin)\r\n\r\n return grid\r\n","repo_name":"Boxcat96/practice_olg1","sub_path":"generate_grid.py","file_name":"generate_grid.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"37488095982","text":"\"\"\"\n-*- coding: utf-8 -*-\n@Author : Link\n@Time : 2022/12/23 16:59\n@Site : \n@File : mixin.py\n@Software: PyCharm\n@Remark : \n\"\"\"\n\nfrom dataclasses import dataclass\nfrom enum import Enum\n\nimport numpy as np\nfrom pyqtgraph import PlotWidget, InfiniteLine\n\nfrom common.li import Li\nfrom ui_component.ui_app_variable import UiGlobalVariable\n\n\nclass ChartType(Enum):\n BinMap = 0x10\n BinPareto = 0x11\n TransBar = 0x20\n TransScatter = 0x30\n VisualMap = 0x40\n\n\n@dataclass\nclass RangeData:\n x_min: int = 0\n x_max: int = 0\n y_min: int = 0\n y_max: int = 0\n\n\ndef GraphRangeSignal(func):\n \"\"\"\n 这个是为了防止信号误触发\n :param func:\n :return:\n \"\"\"\n\n def wrapper(ctx, *args, **kwargs):\n try:\n ctx.pw.sigRangeChanged.disconnect()\n except RuntimeError:\n pass\n if ctx.p_range is None:\n ctx.p_range = RangeData()\n res = func(ctx, *args, **kwargs)\n ctx.p_range.x_min, ctx.p_range.x_max = ctx.bottom_axis.range\n ctx.p_range.y_min, ctx.p_range.y_max = ctx.left_axis.range\n ctx.pw.sigRangeChanged.connect(ctx.set_range_data_to_chart)\n return res\n\n return wrapper\n\n\nclass BasePlot:\n \"\"\"\n TODO: rota: 0b000000\n 0bX_____ -> select x 选取后筛选X轴的数据\n 0b_X____ -> select y 选取后筛选Y轴的数据\n 0b__X___ -> lint x H_L_Limit/AVG 放在X轴 -> 主要数据分布在X上\n 0b___X__ -> lint y H_L_Limit/AVG 放在Y轴 -> 主要数据分布在Y上\n 0b____X_ -> zoom x X轴放大缩小\n 0b_____X -> zoom y Y轴放大缩小\n \"\"\"\n pw: PlotWidget = None\n rota: int = None\n li: Li = None\n p_range: RangeData = None\n line_init: bool = False\n\n key: int = None # 显示的测试项目\n lines: dict = None\n unit: str = ''\n\n sig: int = 0 # 方向\n change: bool = False # 是否已经绘图了\n\n def set_data(self, key: int):\n \"\"\"\n :param key: TEST_ID\n :return:\n \"\"\"\n if self.li is None:\n raise Exception(\"first set li\")\n row = self.li.capability_key_dict.get(key, None)\n if row is None:\n return\n self.key = key\n title = str(row[\"TEST_NUM\"]) + \":\" + row[\"TEST_TXT\"]\n self.set_title(title)\n if self.p_range is None:\n self.p_range = RangeData()\n\n def set_title(self, title: str = \"PlotItem with CustomAxisItem, CustomViewBox\"):\n self.pw.plotItem.setTitle(title)\n\n def resize(self, w, h):\n self.pw.resize(w, h)\n\n def widget(self, width: int):\n self.pw.setMaximumWidth(width)\n return self.pw\n\n @GraphRangeSignal\n def pw_show(self):\n \"\"\"\n graph_range_signal的意义在于不要触发因为坐标改变导致的信号循环\n :return:\n \"\"\"\n self.pw.show()\n\n def set_lines(self, **kwargs):\n \"\"\"\n line可以缓存\n \"\"\"\n if self.lines is None:\n self.lines = {}\n for key, item in kwargs.items():\n if key in self.lines:\n inf = self.lines[key] # type:InfiniteLine\n inf.setPos(item)\n else:\n ang = 0 if self.sig else 90\n inf = InfiniteLine(\n movable=False, angle=ang, pen=(255, 0, 0), hoverPen=(0, 200, 0),\n label=key + '={value:0.9f}' + self.unit,\n labelOpts={'color': (255, 0, 0), 'movable': True, 'fill': (0, 0, 200, 100), 'position': 0.1, }\n )\n inf.setPos(item)\n self.pw.addItem(inf)\n\n def set_range_data_to_chart(self, a, ax) -> bool:\n if self.li is None:\n return False\n if self.sig == 1: # 0 是 X, 1 是Y 的变化\n data_min, data_max = self.p_range.y_min, self.p_range.y_max\n else:\n data_min, data_max = self.p_range.x_min, self.p_range.x_max\n percent = (ax[self.sig][1] - ax[self.sig][0]) / (data_max - data_min)\n if 0.85 < percent < 1.15:\n \"\"\" 性能会好些,体验会差点 \"\"\"\n return False\n self.set_p_range(ax[self.sig][0], ax[self.sig][1])\n return True\n\n def set_line_self(self):\n row = self.li.capability_key_dict.get(self.key, None)\n if row is None: return\n self.unit = row[\"UNITS\"] if not isinstance(row[\"UNITS\"], float) else \"\"\n if UiGlobalVariable.GraphScreen == 0:\n l_limit = row[\"LO_LIMIT\"]\n if isinstance(row[\"LO_LIMIT_TYPE\"], float):\n l_limit = row[\"MIN\"]\n h_limit = row[\"HI_LIMIT\"]\n if isinstance(row[\"HI_LIMIT_TYPE\"], float):\n h_limit = row[\"MAX\"]\n self.set_lines(\n HI_LIMIT=h_limit,\n LO_LIMIT=l_limit,\n AVG=row[\"AVG\"],\n )\n return\n if UiGlobalVariable.GraphScreen == 1:\n l_limit = row[\"MIN\"]\n h_limit = row[\"MAX\"]\n self.set_lines(\n VAILD_MAX=h_limit,\n VAILD_MIN=l_limit,\n AVG=row[\"AVG\"],\n )\n return\n if UiGlobalVariable.GraphScreen == 2:\n l_limit = row[\"ALL_DATA_MIN\"]\n h_limit = row[\"ALL_DATA_MAX\"]\n self.set_lines(\n DATA_MIN=h_limit,\n DATA_MAX=l_limit,\n AVG=row[\"AVG\"],\n )\n return\n if UiGlobalVariable.GraphScreen == 3:\n if row[\"STD\"] == 0 or np.isnan(row[\"STD\"]):\n l_limit, h_limit = -0.1, 1.1\n else:\n rig_x = row[\"STD\"] * UiGlobalVariable.GraphMeanAddSubSigma\n l_limit = row[\"AVG\"] - rig_x\n h_limit = row[\"AVG\"] + rig_x\n self.set_lines(\n SIGMA_MIN=h_limit,\n SIGMA_MAX=l_limit,\n AVG=row[\"AVG\"],\n )\n return\n\n # @GraphRangeSignal\n def set_range_self(self):\n \"\"\"\n 显示\n :return:\n \"\"\"\n row = self.li.capability_key_dict.get(self.key, None)\n if row is None: return\n if UiGlobalVariable.GraphScreen == 0:\n l_limit = row[\"LO_LIMIT\"]\n if isinstance(row[\"LO_LIMIT_TYPE\"], float):\n l_limit = row[\"MIN\"]\n h_limit = row[\"HI_LIMIT\"]\n if isinstance(row[\"HI_LIMIT_TYPE\"], float):\n h_limit = row[\"MAX\"]\n step = row[\"STD\"] * 2\n self.set_p_range(l_limit - step, h_limit + step)\n return\n if UiGlobalVariable.GraphScreen == 1:\n self.set_p_range(row[\"MIN\"], row[\"MAX\"])\n return\n if UiGlobalVariable.GraphScreen == 2:\n low = self.li.to_chart_csv_data.df[self.key].min()\n high = self.li.to_chart_csv_data.df[self.key].max()\n self.set_p_range(low, high)\n return\n if UiGlobalVariable.GraphScreen == 3:\n if row[\"STD\"] == 0 or np.isnan(row[\"STD\"]):\n l_limit, h_limit = -0.1, 1.1\n else:\n step = row[\"STD\"] * self.li.rig\n l_limit, h_limit = row[\"AVG\"] - step, row[\"AVG\"] + step\n self.set_p_range(l_limit, h_limit)\n return\n\n def set_p_range(self, p_min, p_max):\n if self.sig == 1:\n self.p_range.y_min, self.p_range.y_max = p_min, p_max\n else:\n self.p_range.x_min, self.p_range.x_max = p_min, p_max\n\n def set_front_chart(self):\n pass\n\n def __del__(self):\n print(\"chart delete\")\n try:\n self.li.QChartSelect.disconnect(self.set_front_chart)\n except RuntimeError:\n pass\n try:\n self.li.QChartRefresh.disconnect(self.set_front_chart)\n except RuntimeError:\n pass\n","repo_name":"Crazytommy90/ATE_STDF_ANALYSIS","sub_path":"chart_core/chart_pyqtgraph/core/mixin.py","file_name":"mixin.py","file_ext":"py","file_size_in_byte":7870,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"24"} +{"seq_id":"8259085818","text":"import os\nimport sys\nimport psutil\nimport argparse\nimport time\n\n#delta penalty\nDelta = 30\n\n# alpha penalty\nAlpha = {}\nAlpha[\"A\"] = {\"A\": 0, \"C\": 110, \"G\": 48, \"T\": 94}\nAlpha[\"C\"] = {\"A\": 110, \"C\": 0, \"G\": 118, \"T\": 48}\nAlpha[\"G\"] = {\"A\": 48, \"C\": 118, \"G\": 0, \"T\": 110}\nAlpha[\"T\"] = {\"A\": 94, \"C\": 48, \"G\": 110, \"T\": 0}\n\ndef parse_input(file_name):\n with open(file_name) as f:\n cont = f.read().splitlines()\n for i in range(1, len(cont)):\n if not cont[i].isdigit():\n split_index = i\n return cont[0], [int(idx) for idx in cont[1:split_index]], cont[split_index], [int(index) for index in cont[1 + split_index:]]\n\ndef parse_base(base_string, ls_indices):\n base = base_string\n for i in ls_indices:\n base = base[: i + 1] + base + base[i + 1:]\n assert len(base) == (2 ** len(ls_indices)) * len(base_string)\n return base\n\ndef string_alignment(s1, s2):\n col_size = len(s1) + 1\n row_size = len(s2) + 1\n dp = [[0] * row_size for i in range(col_size)]\n \n #set base case\n for i in range(col_size):\n dp[i][0] = i * Delta\n for i in range(row_size):\n dp[0][i] = i * Delta\n\n #general dp process\n for i in range(1, col_size):\n for j in range(1, row_size):\n mismatch = dp[i - 1][j - 1] + Alpha[s1[i - 1]][s2[j - 1]]\n gap_top = dp[i - 1][j] + Delta\n gap_left = dp[i][j - 1] + Delta\n dp[i][j] = min(mismatch, gap_top, gap_left)\n \n #find minimum cost alignment\n s1_align = ''\n s2_align = ''\n ls1 = len(s1)\n ls2 = len(s2)\n while ls1 != 0 and ls2 != 0:\n if dp[ls1][ls2] == dp[ls1 - 1][ls2 - 1] + Alpha[s1[ls1 - 1]][s2[ls2 - 1]]:\n s1_align = s1[ls1 - 1] + s1_align\n s2_align = s2[ls2 - 1] + s2_align\n ls1 = ls1 - 1\n ls2 = ls2 - 1\n elif dp[ls1][ls2] == dp[ls1 - 1][ls2] + Delta:\n s1_align = s1[ls1 - 1] + s1_align\n s2_align = '_' + s2_align\n ls1 = ls1 - 1\n else:\n s1_align = '_' + s1_align\n s2_align = s2[ls2 - 1] + s2_align\n ls2 = ls2 - 1\n\n #assign gap for the rest\n if ls1 != 0:\n for i in range(ls1, 0, -1):\n s1_align = s1[i - 1] + s1_align\n s2_align = '_' + s2_align\n elif ls2 != 0:\n for i in range(ls2, 0, -1):\n s1_align = '_' + s1_align\n s2_align = s2[i - 1] + s2_align\n\n return dp[len(s1)][len(s2)], s1_align, s2_align\n\ndef output_file(s1, s2, cost, time_cost, memory_cost, out_file = 'b_output_11t.txt'):\n with open(out_file, \"w\") as f:\n f.write(f\"{cost}\")\n f.write(\"\\n\")\n f.write(f\"{s1}\")\n f.write(\"\\n\")\n f.write(f\"{s2}\")\n f.write(\"\\n\")\n f.write(f\"{time_cost}\")\n f.write(\"\\n\")\n f.write(f\"{memory_cost}\")\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('file_name', type=str)\n args = parser.parse_args()\n base1, lst1, base2, lst2 = parse_input(args.file_name)\n\n sequence_one = parse_base(base1, lst1)\n sequence_two = parse_base(base2, lst2)\n\n start_at = time.time()\n cost, s1_align, s2_align = string_alignment(sequence_one, sequence_two)\n \n memory_info = psutil.Process().memory_info()\n memory_cost = float(memory_info.rss/1024)\n \n time_cost = (time.time() - start_at) * 1000\n output_file(s1_align, s2_align, cost, time_cost, memory_cost)\n","repo_name":"sgsshane1998/sequence-alignment","sub_path":"sequence alignment/basic_3.py","file_name":"basic_3.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"40727014595","text":"import random\r\nimport numpy as np\r\n\r\n\r\nclass Perceptron:\r\n\r\n def __init__(self, point_arr):\r\n self.point_arr = point_arr\r\n self.weights = (np.random.rand(2) - 0.5)\r\n self.learning_rate = 0.1\r\n self.correct_count = 0\r\n self.incorrect_count = 0\r\n\r\n @staticmethod\r\n def sum_weighted_inputs(inputs, weights):\r\n weighted_input = 0\r\n\r\n for index in range(len(weights)):\r\n weighted_input += inputs[index] * weights[index]\r\n return weighted_input\r\n\r\n @staticmethod\r\n def activation(weighted_inputs_sum):\r\n if weighted_inputs_sum >= 0:\r\n return 1\r\n else:\r\n return -1\r\n\r\n def guess(self, inputs):\r\n weighted_inputs_sum = self.sum_weighted_inputs(inputs, self.weights)\r\n return self.activation(weighted_inputs_sum)\r\n\r\n def train(self):\r\n for curr_point in self.point_arr:\r\n inputs = [curr_point.x, curr_point.y]\r\n result = self.guess(inputs)\r\n curr_error = curr_point.label - result\r\n self.adjust_weights(curr_error, inputs)\r\n self.print_curr_result()\r\n\r\n def adjust_weights(self, curr_error, inputs):\r\n\r\n for index in range(len(self.weights)):\r\n self.weights[index] += curr_error * inputs[index] * self.learning_rate\r\n\r\n def print_curr_result(self):\r\n for point in self.point_arr:\r\n inputs = [point.x, point.y]\r\n result = self.guess(inputs)\r\n\r\n if result == point.label:\r\n self.correct_count += 1\r\n\r\n else:\r\n self.incorrect_count += 1\r\n\r\n print('correct count = %d' % self.correct_count)\r\n print('incorrect count = %d\\n\\n\\n' % self.incorrect_count)\r\n self.correct_count = 0\r\n self.incorrect_count = 0\r\n","repo_name":"jacksnett/neural_network","sub_path":"Perpetron.py","file_name":"Perpetron.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"40829845406","text":"'''\r\nGiven the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.\r\n\r\nA root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.\r\n'''\r\nfrom typing import Optional, List\r\nfrom TreeNode import TreeNode, deserialize\r\n\r\n\r\nclass Solution:\r\n def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:\r\n paths = []\r\n\r\n if root is None:\r\n return []\r\n\r\n if root.val == targetSum and root.left is None and root.right is None:\r\n return [[root.val]]\r\n\r\n left_paths = self.pathSum(root.left, targetSum - root.val)\r\n right_paths = self.pathSum(root.right, targetSum - root.val)\r\n child_paths = left_paths + right_paths\r\n for path in child_paths:\r\n paths.append([root.val] + path)\r\n\r\n return paths\r\n\r\n\r\nsolution = Solution()\r\nassert solution.pathSum(deserialize([5,4,8,11,None,13,4,7,2,None,None,5,1]), 22) == [[5, 4, 11, 2], [5, 8, 4, 5]]\r\nassert solution.pathSum(deserialize([1, 2, 3]), 5) == []\r\nassert solution.pathSum(deserialize([1, 2]), 0) == []\r\n","repo_name":"TessFerrandez/algorithms","sub_path":"binary-trees/lc-m-113-path-sum-ii.py","file_name":"lc-m-113-path-sum-ii.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"24"} +{"seq_id":"22765575244","text":"# Project: Classification with Use of Neural Networks in the Keras Environment\n# Application: Experimental application for neural network comparison with use of Keras\n# Author: Michal Pyšík\n# File: main.py\n\nimport tkinter as tk\nimport utils as ut\nimport view\n\n\n# Main function that runs the main loop of the application\nif __name__ == \"__main__\":\n root = tk.Tk()\n view = view.View(root)\n view.setup()\n\n root.option_add(\"*Dialog.msg.width\", 34)\n root.option_add(\"*Dialog.msg.wrapLength\", \"6i\")\n root.geometry(\"%sx%s\" % (ut.window_width, ut.window_height))\n root.title(\"Neural network comparison with Keras\")\n root.mainloop()\n","repo_name":"MichalPysik/IBT","sub_path":"app/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"15268946151","text":"# Refactored file for longitude.\r\n\r\nimport csv\r\n\r\nfilename = 'hurrmatthew.csv'\r\nwith open(filename) as f:\r\n\treader = csv.reader(f)\r\n\theader_row = next(reader)\r\n\t\t\r\n\tlongitudes = []\r\n\tfor column in reader:\r\n\t\tlongitude = int(float(column[6]))\r\n\t\tlongitudes.append(longitude)\r\n\t\t\r\n\r\n\t\t\r\n\r\n","repo_name":"zorroartico/Hurricane-Matthew-Path-Map","sub_path":"longitude.py","file_name":"longitude.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"70912988862","text":"#  coding: utf-8\nimport json\nimport typing\nfrom aiohttp import web\nfrom aiohttp.web_app import Application\nfrom aiohttp.web_request import Request\nfrom aiohttp.web_response import Response\nimport aiohttp_jinja2\nfrom hapic.data import HapicData\nfrom json import JSONDecodeError\n\nfrom guilang.description import Description\nfrom guilang.description import Part\nfrom guilang.description import Type\nfrom rolling.kernel import Kernel\nfrom rolling.model.character import (\n ConversationsQueryModel,\n GetConversationQueryModel,\n PostConversationBodyModel,\n PostSetupConversationQueryModel,\n)\nfrom rolling.model.character import GetCharacterPathModel\nfrom rolling.model.character import GetConversationPathModel\nfrom rolling.server.controller.base import BaseController\nfrom rolling.server.document.character import CharacterDocument\nfrom rolling.server.document.message import MessageDocument\nfrom rolling.server.extension import hapic\nfrom rolling.util import ORIGINAL_AVATAR_PATTERN, ZONE_THUMB_AVATAR_PATTERN\n\n\nclass ConversationController(BaseController):\n def __init__(self, kernel: Kernel) -> None:\n self._kernel = kernel\n\n @hapic.with_api_doc()\n @hapic.input_path(GetCharacterPathModel)\n @hapic.input_query(ConversationsQueryModel)\n @hapic.output_body(Description)\n async def main_page(self, request: Request, hapic_data: HapicData) -> Description:\n # messages = self._kernel.message_lib.get_conversation_first_messages(\n # hapic_data.path.character_id,\n # hapic_data.query.with_character_id, # FIXME BS NOW: test it\n # )\n # conversation_parts = []\n # for message in messages:\n # unread = \"\"\n # if (\n # self._kernel.server_db_session.query(MessageDocument.id)\n # .filter(\n # MessageDocument.first_message == message.first_message,\n # MessageDocument.read == False,\n # MessageDocument.character_id == hapic_data.path.character_id,\n # )\n # .count()\n # ):\n # unread = \"*\"\n # conversation_parts.append(\n # Part(\n # is_link=True,\n # form_action=f\"/conversation/{hapic_data.path.character_id}/read/{message.first_message}\",\n # label=f\"{unread}{message.subject}\",\n # align=\"left\",\n # )\n # )\n\n return Description(\n title=\"Conversations\",\n items=[\n # Part(\n # text=(\n # \"Les conversations sont les échanges de paroles\"\n # \" tenus avec d'autres personnages\"\n # )\n # ),\n # Part(\n # is_link=True,\n # label=\"Démarrer une nouvelle conversation\",\n # form_action=f\"/conversation/{hapic_data.path.character_id}/start\",\n # ),\n # Part(text=\"Ci-dessous les conversations précédentes ou en cours\"),\n # ]\n # + conversation_parts,*\n Part(\n is_link=True,\n label=\"Afficher les conversations (web)\",\n form_action=f\"{self._kernel.server_config.base_url}/conversation/{hapic_data.path.character_id}/web\",\n is_web_browser_link=True,\n )\n ],\n can_be_back_url=True,\n )\n\n @hapic.with_api_doc()\n @aiohttp_jinja2.template(\"discussions.html\")\n @hapic.input_path(GetCharacterPathModel)\n @hapic.input_query(GetConversationQueryModel)\n @hapic.input_body(PostConversationBodyModel)\n async def main_page_web(self, request: Request, hapic_data: HapicData) -> dict:\n character_id: str = hapic_data.path.character_id\n character_doc = self._kernel.character_lib.get_document(character_id)\n conversation_id: typing.Optional[int] = hapic_data.query.conversation_id\n current_zone: bool = bool(hapic_data.query.current_zone)\n posted_message: typing.Optional[str] = hapic_data.body.message\n\n conversation: typing.Optional[MessageDocument] = None\n conversation_messages: typing.List[MessageDocument] = []\n zone_characters: typing.List[CharacterDocument] = []\n\n if character_id != request[\"account_character_id\"]:\n raise web.HTTPForbidden()\n\n if conversation_id and current_zone:\n raise web.HTTPBadRequest()\n\n if conversation_id is not None:\n conversation_messages = self._kernel.message_lib.get_conversation_messages(\n character_id,\n conversation_id=conversation_id,\n order=MessageDocument.datetime.asc(),\n )\n conversation = conversation_messages[0]\n\n if current_zone:\n conversation_messages = (\n self._kernel.message_lib.get_character_zone_messages(\n character_id,\n order=MessageDocument.datetime.asc(),\n )\n )\n zone_characters = self._kernel.character_lib.get_zone_characters(\n row_i=character_doc.world_row_i, col_i=character_doc.world_col_i\n )\n\n if posted_message and conversation_id:\n await self._kernel.message_lib.add_conversation_message(\n character_id,\n subject=conversation.subject,\n message=posted_message,\n concerned=conversation.concerned,\n conversation_id=conversation_id,\n filter_by_same_zone_than_author=True,\n )\n # Reload messages (because just added one)\n conversation_messages = self._kernel.message_lib.get_conversation_messages(\n character_id,\n conversation_id=conversation_id,\n order=MessageDocument.datetime.asc(),\n )\n\n if posted_message and current_zone:\n await self._kernel.message_lib.add_zone_message(\n character_id,\n message=posted_message,\n zone_row_i=character_doc.world_row_i,\n zone_col_i=character_doc.world_col_i,\n )\n # Reload messages (because just added one)\n conversation_messages = (\n self._kernel.message_lib.get_character_zone_messages(\n character_id,\n order=MessageDocument.datetime.asc(),\n )\n )\n\n duo_topics = self._kernel.message_lib.get_conversation_first_messages(\n character_id\n )\n\n all_character_ids = list(\n set().union(\n [c.id for c in zone_characters],\n *[message.concerned for message in duo_topics],\n )\n )\n characters_by_ids = {\n character_id: self._kernel.character_lib.get_document(\n character_id, dead=None\n )\n for character_id in all_character_ids\n }\n\n # Avatar thumbs\n character_avatar_thumbs_by_ids = {}\n for character in characters_by_ids.values():\n if character.avatar_uuid and character.avatar_is_validated:\n character_avatar_thumbs_by_ids[\n character.id\n ] = ZONE_THUMB_AVATAR_PATTERN.format(avatar_uuid=character.avatar_uuid)\n else:\n character_avatar_thumbs_by_ids[\n character.id\n ] = ZONE_THUMB_AVATAR_PATTERN.format(avatar_uuid=\"0000\")\n\n # Avatars\n character_avatars_by_ids = {}\n for character in characters_by_ids.values():\n if character.avatar_uuid and character.avatar_is_validated:\n character_avatars_by_ids[character.id] = ORIGINAL_AVATAR_PATTERN.format(\n avatar_uuid=character.avatar_uuid\n )\n else:\n character_avatars_by_ids[character.id] = ORIGINAL_AVATAR_PATTERN.format(\n avatar_uuid=\"0000\"\n )\n\n return {\n \"characters_by_ids\": characters_by_ids,\n \"duo_topics\": duo_topics,\n \"character_id\": character_id,\n \"conversation\": conversation,\n \"conversation_messages\": conversation_messages,\n \"character_avatar_thumbs_by_ids\": character_avatar_thumbs_by_ids,\n \"character_avatars_by_ids\": character_avatars_by_ids,\n \"current_zone\": current_zone,\n \"zone_characters\": zone_characters,\n }\n\n @hapic.with_api_doc()\n @aiohttp_jinja2.template(\"discussions.html\")\n @hapic.input_path(GetCharacterPathModel)\n @hapic.input_query(PostSetupConversationQueryModel, as_list=[\"character_id\"])\n async def setup_web(self, request: Request, hapic_data: HapicData) -> Response:\n character_id: str = hapic_data.path.character_id\n if character_id != request[\"account_character_id\"]:\n raise web.HTTPForbidden()\n concerned: typing.List[str] = list(\n set(hapic_data.query.character_id + [character_id])\n )\n concerned_character_docs = {\n character_id_: self._kernel.character_lib.get_document(character_id_)\n for character_id_ in concerned\n }\n\n if not concerned:\n raise web.HTTPBadRequest(body=\"Aucun personnage n'a été sélectionné\")\n\n existing_topic_id: typing.Optional[\n int\n ] = self._kernel.message_lib.search_conversation_first_message_for_concerned(\n character_id, concerned=list(set(concerned + [character_id]))\n )\n\n if existing_topic_id is not None:\n return web.HTTPFound(\n f\"/conversation/{character_id}/web?conversation_id={existing_topic_id}\"\n )\n\n new_topic_id = await self._kernel.message_lib.add_conversation_message(\n author_id=character_id,\n subject=\", \".join(\n [\n concerned_character_docs[character_id_].name\n for character_id_ in concerned\n ]\n ),\n is_first_message=True,\n message=\"\",\n concerned=concerned,\n )\n\n return web.HTTPFound(\n f\"/conversation/{character_id}/web?conversation_id={new_topic_id}\"\n )\n\n @hapic.with_api_doc()\n @hapic.input_path(GetCharacterPathModel)\n @hapic.input_query(ConversationsQueryModel)\n @hapic.output_body(Description)\n async def start(self, request: Request, hapic_data: HapicData) -> Description:\n character_doc = self._kernel.character_lib.get_document(\n hapic_data.path.character_id\n )\n zone_characters = self._kernel.character_lib.get_zone_characters(\n row_i=character_doc.world_row_i,\n col_i=character_doc.world_col_i,\n exclude_ids=[hapic_data.path.character_id],\n )\n\n try:\n data = await request.json()\n if data.get(\"message\"):\n selected_character_ids = [\n c.id for c in zone_characters if data.get(c.id) == \"on\"\n ]\n if not selected_character_ids:\n return Description(\n title=\"Démarrer une nouvelle conversation\",\n items=[Part(text=\"Vous devez choisir au moins un personnage\")],\n )\n\n conversation_id = (\n await self._kernel.message_lib.add_conversation_message(\n author_id=hapic_data.path.character_id,\n subject=data.get(\"subject\", \"Une conversation\"),\n message=data[\"message\"],\n concerned=selected_character_ids,\n is_first_message=True,\n )\n )\n return Description(\n redirect=f\"/conversation/{hapic_data.path.character_id}/read/{conversation_id}\"\n )\n\n except JSONDecodeError:\n pass # no json (i guess)\n\n if not zone_characters:\n return Description(\n title=\"Démarrer une nouvelle conversation\",\n items=[\n Part(text=\"Il n'y a personne ici avec qui converser\"),\n Part(\n is_link=True,\n label=\"Retourner aux conversations\",\n form_action=f\"/conversation/{hapic_data.path.character_id}\",\n ),\n ],\n )\n\n character_parts = []\n for zone_character in zone_characters:\n character_parts.append(\n Part(\n label=zone_character.name,\n value=\"on\",\n is_checkbox=True,\n name=zone_character.id,\n # FIXME BS NOW: test it\n checked=zone_character.id == hapic_data.query.with_character_id,\n )\n )\n\n return Description(\n title=\"Démarrer une nouvelle conversation\",\n items=[\n Part(\n text=\"Vous devez choisir les personnages avec qui entretenir cette conversation\"\n ),\n Part(\n is_form=True,\n form_action=f\"/conversation/{hapic_data.path.character_id}/start\",\n items=character_parts\n + [\n Part(\n label=\"Choisissez un titre\",\n type_=Type.STRING,\n name=\"subject\",\n ),\n Part(\n label=\"Saisissez votre élocuction\",\n type_=Type.STRING,\n name=\"message\",\n ),\n ],\n ),\n ],\n footer_links=[\n Part(\n is_link=True,\n label=\"Retourner aux conversations\",\n form_action=f\"/conversation/{hapic_data.path.character_id}\",\n )\n ],\n )\n\n @hapic.with_api_doc()\n @hapic.input_path(GetConversationPathModel)\n @hapic.output_body(Description)\n async def read(self, request: Request, hapic_data: HapicData) -> Description:\n messages = self._kernel.message_lib.get_conversation_messages(\n character_id=hapic_data.path.character_id,\n conversation_id=hapic_data.path.conversation_id,\n )\n concerned_ids = set()\n for message in messages:\n concerned_ids |= set(message.concerned)\n concerned_names = [\n r[0]\n for r in self._kernel.server_db_session.query(CharacterDocument.name)\n .filter(CharacterDocument.id.in_(concerned_ids))\n .all()\n ]\n\n message_parts = []\n for message in messages:\n text = (\n f\"{message.author_name}: {message.text}\"\n if not message.is_outzone_message\n else message.text\n )\n message_parts.append(Part(text=text))\n\n self._kernel.message_lib.mark_character_conversation_messages_as_read(\n character_id=hapic_data.path.character_id,\n conversation_id=hapic_data.path.conversation_id,\n )\n self._kernel.server_db_session.commit()\n return Description(\n title=messages[-1].subject,\n items=[\n Part(text=\"Cette conversation concerne les personnages suivants\"),\n Part(text=\", \".join(concerned_names)),\n Part(\n is_form=True,\n form_action=f\"/conversation/{hapic_data.path.character_id}/add/{hapic_data.path.conversation_id}\",\n items=[\n Part(\n label=\"Ajouter un message\",\n type_=Type.STRING,\n name=\"message\",\n )\n ],\n ),\n Part(text=\"Conversation (message le plus récente en haut):\"),\n ]\n + message_parts,\n footer_links=[\n Part(\n is_link=True,\n label=\"Retourner aux conversations\",\n form_action=f\"/conversation/{hapic_data.path.character_id}\",\n classes=[\"primary\"],\n )\n ],\n can_be_back_url=True,\n )\n\n @hapic.with_api_doc()\n @hapic.input_path(GetConversationPathModel)\n @hapic.output_body(Description)\n async def add(self, request: Request, hapic_data: HapicData) -> Description:\n data = await request.json()\n add_message = data[\"message\"]\n last_message = self._kernel.message_lib.get_last_conversation_message(\n hapic_data.path.conversation_id\n )\n await self._kernel.message_lib.add_conversation_message(\n author_id=hapic_data.path.character_id,\n conversation_id=hapic_data.path.conversation_id,\n subject=last_message.subject,\n concerned=last_message.concerned,\n message=add_message,\n )\n\n return Description(\n redirect=f\"/conversation/{hapic_data.path.character_id}/read/{hapic_data.path.conversation_id}\"\n )\n\n # @hapic.with_api_doc()\n # @hapic.input_path(GetConversationPathModel)\n # @hapic.output_body(Description)\n # async def edit_concerned(self, request: Request, hapic_data: HapicData) -> Description:\n # character_doc = self._kernel.character_lib.get_document(hapic_data.path.character_id)\n # message = (\n # self._kernel.server_db_session.query(MessageDocument)\n # .filter(MessageDocument.id == hapic_data.path.conversation_id)\n # .one()\n # )\n # first_message = (\n # self._kernel.server_db_session.query(MessageDocument)\n # .filter(MessageDocument.id == message.first_message)\n # .one()\n # )\n # last_message = (\n # self._kernel.server_db_session.query(MessageDocument)\n # .filter(MessageDocument.first_message == message.first_message)\n # .order_by(MessageDocument.datetime.desc())\n # .limit(1)\n # .one()\n # )\n # zone_characters = self._kernel.character_lib.get_zone_characters(\n # row_i=character_doc.world_row_i,\n # col_i=character_doc.world_col_i,\n # exclude_ids=[hapic_data.path.character_id],\n # )\n #\n # character_parts = []\n # for zone_character in zone_characters:\n # character_parts.append(\n # Part(\n # label=zone_character.name,\n # value=\"on\",\n # is_checkbox=True,\n # name=zone_character.id,\n # checked=zone_character.id in last_message.concerned,\n # )\n # )\n #\n # return Description(\n # title=first_message.subject,\n # items=[\n # Part(\n # text=\"Vous pouvez ajouter les personnages ci-dessous à la conversation\",\n # is_form=True,\n # form_action=f\"/conversation/{hapic_data.path.character_id}/edit-concerned/{hapic_data.path.conversation_id}\",\n # items=character_parts,\n # )\n # ],\n # footer_links=[\n #\n # Part(\n # is_link=True,\n # label=\"Retourner aux conversations\",\n # form_action=f\"/conversation/{hapic_data.path.character_id}\",\n # ),\n # Part(\n # is_link=True,\n # label=\"Voir la conversation\",\n # form_action=f\"/conversation/{hapic_data.path.character_id}/read/{hapic_data.path.conversation_id}\",\n # classes=[\"primary\"],\n # ),\n # ],\n # )\n\n def bind(self, app: Application) -> None:\n app.add_routes(\n [\n web.post(\"/conversation/{character_id}\", self.main_page),\n web.get(\"/conversation/{character_id}/web\", self.main_page_web),\n web.post(\"/conversation/{character_id}/web\", self.main_page_web),\n web.get(\"/conversation/{character_id}/web/setup\", self.setup_web),\n web.post(\"/conversation/{character_id}/start\", self.start),\n web.post(\n \"/conversation/{character_id}/read/{conversation_id}\", self.read\n ),\n web.post(\n \"/conversation/{character_id}/add/{conversation_id}\", self.add\n ),\n ]\n )\n","repo_name":"buxx/rolling","sub_path":"rolling/server/controller/conversation.py","file_name":"conversation.py","file_ext":"py","file_size_in_byte":21120,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"24"} +{"seq_id":"72982441981","text":"import sys, re, glob\nimport numpy as np\n\nfrom cctk import GaussianFile, Molecule\nfrom cctk import parse_gaussian as parse\n\nfilenames = sys.argv[1]\ninfo = []\n\nfor filename in sorted(glob.glob(filenames, recursive=True)):\n try:\n output_file, lines = GaussianFile.read_file(filename, return_lines=True)\n except:\n continue\n\n success = \"NO\"\n if output_file.success:\n success = output_file.success\n else:\n continue\n\n energy = output_file.energies[-1]\n iters = len(output_file.energies)\n mol = output_file.get_molecule()\n\n cation_anion_dist = 0\n mul_q = 0\n hir_q = 0\n if 29 in mol.atomic_numbers:\n mul_q = float(parse.find_parameter(lines, \" 52 Cu\", 4, 2)[-1])\n hir_q = float(parse.find_parameter(lines, \" 52 Cu\", 8, 2)[-1])\n\n if 16 in mol.atomic_numbers:\n cation_anion_dist = mol.get_distance(52, 54)\n elif 51 in mol.atomic_numbers:\n cation_anion_dist = mol.get_distance(52, 53)\n\n imaginaries = \"--\"\n try:\n if output_file.num_imaginaries() > 0:\n if output_file.num_imaginaries() > 1:\n imaginaries = \", \".join(output_file.imaginaries())\n else:\n imaginaries = output_file.imaginaries()[0]\n except:\n #### Will raise ValueError if job is not of type \"FREQ\"\n pass\n\n info.append([filename, energy, energy * 627.509, iters, mul_q, hir_q, success, imaginaries, cation_anion_dist])\n\n\nif len(info) > 0:\n min_energy = np.min([x[2] for x in info])\n def adjust_energy(row):\n if row[2] < 0:\n row[2] = row[2] - min_energy\n return row\n\n info = list(map(adjust_energy, info))\n\n print(\"{0},{1},{2},{3},{4},{5},{6},{7},{8}\".format(\n \"File\", \"Energy (Hartree)\", \"Rel Energy (kcal)\", \"Iterations\", \"Mulliken Q\", \"Hirshfeld Q\", \"Success?\", \"Imaginaries?\",\"X-Cu Distance\"\n ))\n\n for row in info:\n print(\"{0},{1:.4f},{2:.2f},{3},{4:.4f},{5:.4f},{6},{7:},{8:.2f}\".format(*row))\n\n","repo_name":"ekwan/cctk","sub_path":"tutorial/tutorial_07/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"24"} +{"seq_id":"7489073321","text":"def triangle():\r\n a = float(input(\"Основание: \"))\r\n h = float(input(\"Высота: \"))\r\n s = round(0.5 * a * h, 2)\r\n print(\"Площадь треугольника: \", s)\r\n\r\ndef square():\r\n a = float(input(\"Длина стороны: \"))\r\n s = round(a ** 2, 2)\r\n print(\"Площадь квадрата: \", s)\r\n\r\nfigure = input(\"\"\"Для площади треугольника нажмите 1\r\nДля площади квадрата нажмите 2: \"\"\")\r\nif figure == '1':\r\n triangle()\r\nelif figure == '2':\r\n square()","repo_name":"Daalin80/Lesson5","sub_path":"ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"8954792546","text":"import torch\nfrom torchvision import transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(28, 64, (5,5), padding = 2)\n self.conv1_bn = nn.BatchNorm2d(64)\n self.conv2 = nn.Conv2d(64, 128, 2, padding = 2)\n self.fc1 = nn.Linear(2048, 1024)\n self.dropout = nn.Dropout(0.3)\n self.fc2 = nn.Linear(1024, 512)\n self.bn = nn.BatchNorm1d(1)\n self.fc3 = nn.Linear(512, 128)\n self.fc4 = nn.Linear(128,47)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.max_pool2d(x, 2, 2)\n x = self.conv1_bn(x)\n x = F.relu(self.conv2(x))\n x = F.max_pool2d(x, 2, 2)\n x = x.view(-1, 2048)\n x = F.relu(self.fc1(x))\n x = self.dropout(x)\n x = self.fc2(x)\n x = x.view(-1, 1, 512)\n x = self.bn(x)\n x = x.view(-1, 512)\n x = self.fc3(x)\n x = self.fc4(x)\n\n return x\n","repo_name":"imadelh/ML-web-app","sub_path":"app/ml_model/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":267,"dataset":"github-code","pt":"24"} +{"seq_id":"36009131297","text":"import os\nimport sys\nimport logging\nimport json\nfrom flask import Flask\n\n_log = logging.getLogger(__name__)\n\nfolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\"))\nsys.path.insert(0, folder)\nfrom voto.data.db_session import initialise_database\n\n# Store credentials in a external file that is never added to git or shared over insecure channels\nwith open(folder + \"/mongo_secrets.json\") as json_file:\n secrets = json.load(json_file)\n\napp = Flask(__name__)\n\n\ndef main():\n configure()\n app.run(debug=True, port=5006)\n\n\ndef configure():\n _log.info(\"Configuring Flask app:\")\n\n register_blueprints()\n _log.info(\"Registered blueprints\")\n if \"mongo_user\" not in secrets.keys():\n initialise_database(user=None, password=None)\n else:\n initialise_database(\n user=secrets[\"mongo_user\"],\n password=secrets[\"mongo_password\"],\n port=int(secrets[\"mongo_port\"]),\n server=secrets[\"mongo_server\"],\n db=secrets[\"mongo_db\"],\n )\n _log.info(\"DB setup completed.\")\n\n\ndef register_blueprints():\n from voto.views import home_views, mission_views, platform_views\n\n app.register_blueprint(home_views.blueprint)\n app.register_blueprint(mission_views.blueprint)\n app.register_blueprint(platform_views.blueprint)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(\n filename=f\"{secrets['log_dir']}/voto.log\",\n filemode=\"a\",\n format=\"%(asctime)s %(levelname)-8s %(message)s\",\n level=logging.INFO,\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n )\n main()\nelse:\n configure()\n","repo_name":"voto-ocean-knowledge/voto-web","sub_path":"voto/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"35790496249","text":"# ! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"liuluyang\"\n# Datetime: 2019/11/28 13:17\n\n\n\nimport uuid\nimport time\n\nuid_set = set()\nfor i in range(100):\n uid = str(uuid.uuid1())\n print(time.time())\n print(uid)\n uid_set.add(uid.split('-')[3])\n\nprint(len(uid_set), uid_set)","repo_name":"liuluyang/mk","sub_path":"py3-study/面向对象课上代码/1902/11-28/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"40039854189","text":"from pyspark.sql.types import StructType, StructField, IntegerType, LongType\nfrom pyspark.sql import functions as func\nimport codecs\n\nfrom core.session_manager import SessionManager\n\n\ndef load_movie_names():\n movie_names = {}\n with codecs.open(\"./ml-100k/u.item\", \"r\", encoding=\"ISO-8859-1\", errors=\"ignore\") as file:\n for line in file:\n fields = line.split('|')\n movie_names[int(fields[0])] = fields[1]\n return movie_names\n\n\ndef get_look_up_name_func(names):\n def look_up_name(movie_id):\n return names.value[movie_id]\n\n return look_up_name\n\n\ndef main():\n with SessionManager(\"PopularMoviesWithBroadcast\") as spark:\n schema = StructType([\n StructField(\"user_id\", IntegerType(), True),\n StructField(\"movie_id\", IntegerType(), True),\n StructField(\"rating\", IntegerType(), True),\n StructField(\"timestamp\", LongType(), True),\n ])\n names = spark.sparkContext.broadcast(load_movie_names())\n\n ratings = spark.read.option(\"sep\", \"\\t\").schema(schema).csv(\"./ml-100k/u.data\")\n counts = ratings.groupBy(\"movie_id\").count().sort(\"count\", ascending=False)\n look_up_name_udf = func.udf(get_look_up_name_func(names))\n\n results = counts.withColumn(\"movie_title\", look_up_name_udf(func.col(\"movie_id\")))\\\n .select(\"movie_title\", \"count\").sort(\"count\", ascending=False)\n\n results.show(10)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Gekol/spark-practice","sub_path":"13_popular_movies_with_broadcast.py","file_name":"13_popular_movies_with_broadcast.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"27716318595","text":"\"\"\"\nFetch scalar and table variables\n++++++++++++++++++++++++++++++++\n\nSend a series of SNMP GETBULK requests with the following options:\n\n* with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols\n* over IPv4/UDP\n* to an Agent at 104.236.166.95:161\n* with values non-repeaters = 1, max-repetitions = 25\n* for two OIDs in tuple form (first OID is non-repeating)\n* stop on end-of-mib condition for both OIDs\n\nThis script performs similar to the following Net-SNMP command:\n\n| $ snmpbulkwalk -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -C n1 -C r25 -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1\n\n\"\"\"#\nfrom pysnmp.entity import engine, config\nfrom pysnmp.entity.rfc3413 import cmdgen\nfrom pysnmp.carrier.asyncore.dgram import udp\n\n# Create SNMP engine instance\nsnmpEngine = engine.SnmpEngine()\n\n#\n# SNMPv3/USM setup\n#\n\n# user: usr-md5-des, auth: MD5, priv DES\nconfig.addV3User(\n snmpEngine, 'usr-md5-des',\n config.USM_AUTH_HMAC96_MD5, 'authkey1',\n config.USM_PRIV_CBC56_DES, 'privkey1'\n)\nconfig.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-des', 'authPriv')\n\n#\n# Setup transport endpoint and bind it with security settings yielding\n# a target name\n#\n\n# UDP/IPv4\nconfig.addTransport(\n snmpEngine,\n udp.DOMAIN_NAME,\n udp.UdpSocketTransport().openClientMode()\n)\n\nconfig.addTargetAddr(\n snmpEngine, 'my-router',\n udp.DOMAIN_NAME, ('104.236.166.95', 161),\n 'my-creds'\n)\n\n\n# Error/response receiver\n# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal\ndef cbFun(snmpEngine, sendRequesthandle, errorIndication,\n errorStatus, errorIndex, varBindTable, cbCtx):\n if errorIndication:\n print(errorIndication)\n return # stop on error\n\n if errorStatus:\n print('%s at %s' % (errorStatus.prettyPrint(),\n errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))\n return # stop on error\n\n for varBindRow in varBindTable:\n for oid, val in varBindRow:\n print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))\n\n return True # signal dispatcher to continue walking\n\n\n# Prepare initial request to be sent\ncmdgen.BulkCommandGenerator().sendVarBinds(\n snmpEngine,\n 'my-router',\n None, '', # contextEngineId, contextName\n 0, 25, # non-repeaters, max-repetitions\n (((1, 3, 6, 1, 2, 1, 1), None),\n ((1, 3, 6, 1, 4, 1, 1), None)),\n cbFun\n)\n\n# Run I/O dispatcher which would send pending queries and process responses\nsnmpEngine.transportDispatcher.runDispatcher()\n","repo_name":"etingof/pysnmp","sub_path":"examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py","file_name":"getbulk-fetch-scalar-and-table-variables.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","stars":544,"dataset":"github-code","pt":"24"} +{"seq_id":"6361947275","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# how many genes of each genome belong to each category \n\nfrom collections import defaultdict\nimport sys\n\nf1 = open('genome_unique_gene_annotation.txt', 'r')\nf2 = open('unique_gene_subsystems.tsv', 'r')\nf3 = open('category_subcat_count_result.txt', 'w')\nf4 = open('category_count_result.txt', 'w')\n\ngenelist = f1.readlines()\nsubsyslist = f2.readlines()\n\n#generate gene annotation dict\nmydict1=defaultdict(dict)\na = 0\nfor lines in genelist:\n\ta += 1\n\tif a >1:\n\t\tlines=lines.strip('\\n')\n\t\tgenome, feaid = lines.split('\\t')[0:2]\n\t\thypo = lines.split('\\t')[7]\n\t\tif genome.startswith('gi'):\n\t\t\tg=genome.split('|')[3][0:6]\n\t\telse:\n\t\t\tg=genome.split('_')[0]\n\n\t\tif mydict1.get(g):\n\t\t\tmydict1[g].append('\\t\\t'.join([feaid,hypo]))\n\t\telse:\n\t\t\tmydict1[g]=[]\n\t\t\tmydict1[g].append('\\t\\t'.join([feaid,hypo]))\n\n\n#generate subsystem dict\nmydict2=defaultdict(dict)\nb = 0\nfor rows in subsyslist:\n\tb += 1\n\tif b > 1:\n\t\tcategory,subcate = rows.split('\\t')[0:2]\n\t\tfeature = rows.split('\\t')[4].strip('\\n')\n\t\tif mydict2[category].get(subcate):\n\t\t\tmydict2[category][subcate].append(feature)\n\t\telse:\n\t\t\tmydict2[category][subcate]=[]\n\t\t\tmydict2[category][subcate].append(feature)\n\n\n\n#output category and subcategory and sum file\nf3.write('\\t\\t')\nfor g in mydict1:\n\tf3.write(g+'\\t')\nf3.write('\\n')\n\nfor category in mydict2:\n\tf3.write(category+'\\t')\n\tfor subcate in mydict2[category]:\n\t\tf3.write(subcate+'\\t')\n\t\tfor g in mydict1:\n\t\t\ti = 0\n\t\t\tfor features in mydict2[category][subcate]:\n\t\t\t\tfeature = features.split(', ')\n\t\t\t\tfor feat in feature:\n\t\t\t\t\tfor items in mydict1[g]:\n\t\t\t\t\t\tfeaid, hypo = items.split('\\t\\t')[0:2]\n\t\t\t\t\t\tif feaid == feat:\n\t\t\t\t\t\t\ti += 1\n\t\t\tf3.write(str(i)+'\\t')\n\t\tf3.write('\\n')\n\t\tf3.write('\\t')\n\tf3.write('\\n')\n\nf3.write('Hypothetical protein'+'\\t\\t')\nfor g in mydict1:\n\tnum = 0\n\tfor items in mydict1[g]:\n\t\tfeaid,hypo = items.split('\\t\\t')[0:2]\n\t\tif \"hypothetical protein\" in hypo:\n\t\t\tnum += 1\n\tf3.write(str(num)+'\\t')\nf3.write('\\n')\n\nf3.write('No hit'+'\\t'+'592'+'\\n')\n\n\n\n#output category and sum file\nfor g in mydict1:\n\tf4.write('\\t'+g)\nf4.write('\\n')\n\nfor category in mydict2:\n\tf4.write(category+'\\t')\n\tfor g in mydict1:\n\t\ti = 0\n\t\tfor subcate in mydict2[category]:\n\t\t\tfor features in mydict2[category][subcate]:\n\t\t\t\tfeature = features.split(', ')\n\t\t\t\tfor feat in feature:\n\t\t\t\t\tfor items in mydict1[g]:\n\t\t\t\t\t\tfeaid, hypo = items.split('\\t')[0:2]\n\t\t\t\t\t\tif feaid == feat:\n\t\t\t\t\t\t\ti += 1\n\t\tf4.write(str(i)+'\\t')\n\tf4.write('\\n')\n\nf4.write('Hypothetical protein'+'\\t')\nfor g in mydict1:\n\tnum = 0\n\tfor items in mydict1[g]:\n\t\tfeaid, hypo = items.split('\\t\\t')[0:2]\n\t\tif \"hypothetical protein\" in hypo:\n\t\t\tnum += 1\n\tf4.write(str(num)+'\\t')\nf4.write('\\n')\n\nf4.write('No hit'+'\\t'+'592'+'\\n')\n\n\nf1.close()\nf2.close()\nf3.close()\nf4.close()","repo_name":"zhongjiew/Master-thesis","sub_path":"count_category.py","file_name":"count_category.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"30815341160","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nN = int(input())\r\narr = [list(map(int, input().split())) for _ in range(N)]\r\ndp = [0] * (N+1)\r\nfor day in range(N):\r\n for i in range(day, N):\r\n if i + arr[i][0] <= N:\r\n dp[i + arr[i][0]] = max(dp[i + arr[i][0]], dp[day] + arr[i][1])\r\nprint(max(dp))","repo_name":"byungKHee/ps_study","sub_path":"백준/Silver/14501. 퇴사/퇴사.py","file_name":"퇴사.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"16582467662","text":"n, k = map(int,input().split())\n\narr = list(range(2,n+1))\nch = [0]*(n+1)\ncnt = 0\n\nfor i in range(2, n+1):\n for j in range(i, n+1, i):\n if ch[j] == 0 :\n ch[j] = 1\n cnt += 1\n if cnt == k:\n print(j)\n break","repo_name":"gumsu/BOJ","sub_path":"2960_에라토스테네스의_체.py","file_name":"2960_에라토스테네스의_체.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70355527096","text":"def occupied_adjacent_seats(model, row, col):\n ''' returns the number of occupied adjacent seats for a given seat '''\n # constraints\n max_row = len(model)\n max_col = len(model[0])\n \n seats = 0\n # check NW\n if row - 1 >= 0 and col - 1 >= 0 and model[row - 1][col - 1] == '#':\n seats += 1\n # check N\n if row - 1 >= 0 and model[row - 1][col] == '#':\n seats += 1\n # check NE\n if row - 1 >= 0 and col + 1 < max_col and model[row - 1][col + 1] == '#':\n seats += 1\n # check E\n if col + 1 < max_col and model[row][col + 1] == '#':\n seats += 1\n # check SE\n if row + 1 < max_row and col + 1 < max_col and model[row + 1][col + 1] == '#':\n seats += 1\n # check S\n if row + 1 < max_row and model[row + 1][col] == '#':\n seats += 1\n # check SW\n if row + 1 < max_row and col - 1 >= 0 and model[row + 1][col - 1] == '#':\n seats += 1\n # check W\n if col - 1 >= 0 and model[row][col - 1] == '#':\n seats += 1\n\n return seats\n\n\ndef total_occupied_seats(model):\n ''' returns the number of occupied seats in a model '''\n occupied = 0\n for row in model:\n for space in row:\n if space == '#':\n occupied += 1\n return occupied\n\n\nif __name__ == '__main__':\n # extract input from file\n with open('input.txt', 'r') as f:\n model = [list(x.rstrip()) for x in f.readlines()]\n \n max_row = len(model)\n max_col = len(model[0])\n while True:\n # copy model - normal model.copy() still contains references to original model rows\n new_model = list(map(list, model))\n num_changes = 0\n for row in range(max_row):\n for col in range(max_col):\n seat = model[row][col]\n if seat == 'L' and occupied_adjacent_seats(model, row, col) == 0:\n # update seat in new model\n new_model[row][col] = '#'\n num_changes += 1\n elif seat == '#' and occupied_adjacent_seats(model, row, col) >= 4:\n # update seat in new model\n new_model[row][col] = 'L'\n num_changes += 1\n # update model\n model = new_model\n # no changes made during iteration\n if num_changes == 0:\n print(total_occupied_seats(model))\n break\n","repo_name":"axieax/advent-of-code","sub_path":"2020/day11/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"20834610015","text":"import numpy as np\n\nfrom AccraABM import rcParams\n\nif rcParams['model.use_psyco'] == True:\n import psyco\n psyco.full()\n\nprobability_time_units = rcParams['probability.time_units']\n\nclass UnitsError(Exception):\n pass\n\ndeath_probabilities_female = rcParams['probability.death.female']\n\ndef __probability_index__(t):\n \"\"\"\n Matches units of time in model to those the probability is expressed in. For \n instance: if probabilities are specified for decades, whereas the model runs in \n months, __probability_index__, when provided with an age in months, will convert \n it to decades, rounding down. NOTE: all probabilities must be expressed with the \n same time units.\n \"\"\"\n if probability_time_units == 'months':\n return t\n elif probability_time_units == 'years':\n return int(round(t / 12.))\n elif probability_time_units == 'decades':\n return int(round(t / 120.))\n else:\n raise UnitsError(\"unhandled probability_time_units\")\n\ndef calc_probability_death(person):\n \"Calculates the probability of death for an agent.\"\n age = person.get_age_months()\n probability_index = __probability_index__(age)\n try:\n return death_probabilities_female[probability_index]\n except IndexError:\n raise IndexError(\"error calculating death probability (index %s)\"%(probability_index))\n\ndef draw_from_prob_dist(prob_dist):\n \"\"\"\n Draws a random number from a manually specified probability distribution,\n where the probability distribution is a tuple specified as:\n ([a, b, c, d], [1, 2, 3])\n where a, b, c, and d are bin limits, and 1, 2, and 3 are the probabilities \n assigned to each bin. Notice one more bin limit must be specifed than the \n number of probabilities given (to close the interval).\n \"\"\"\n # First randomly choose the bin, with the bins chosen according to their \n # probability.\n binlims, probs = prob_dist\n num = np.random.rand() * np.sum(probs)\n n = 0\n probcumsums = np.cumsum(probs)\n for upprob in probcumsums[1:]:\n if num < upprob:\n break\n n += 1\n upbinlim = binlims[n+1]\n lowbinlim = binlims[n]\n # Now we know the bin lims, so draw a random number evenly distributed \n # between those two limits.\n return np.random.uniform(lowbinlim, upbinlim)\n\ndef calculate_cover_fraction_NBH(person_ids, egocentric_nbhs, value, na_value):\n # note that areas are expressed in pixels.\n # in below line, np.invert is use for bitwise not (to select values that \n # are not nan\n total_area = np.sum(np.sum(egocentric_nbhs != na_value, 1), 0)\n # convert total area to float or else it will be an integer/integer for the \n # later division\n total_area = np.array(total_area, dtype=\"float\")\n cover_area = np.sum(np.sum((egocentric_nbhs == value) & \n (egocentric_nbhs != na_value), 1), 0)\n cover_fractions = (cover_area / total_area)\n cover_fractions_dict = {}\n for cover_fraction, person_id in zip(cover_fractions, person_ids):\n cover_fractions_dict[person_id] = cover_fraction\n return cover_fractions_dict\n\ndef calculate_cover_fraction_world(lulc, value, na_value):\n # note that areas are expressed in pixels.\n # in below line, np.invert is use for bitwise not (to select values that \n # are not nan\n total_area = np.sum(np.sum(lulc != na_value, 1), 0)\n # convert total area to float or else it will be an integer/integer for the \n # later division\n total_area = float(total_area)\n cover_area = np.sum(np.sum((lulc == value) & (lulc != na_value), 1), 0)\n cover_fraction = (cover_area / total_area)\n return cover_fraction\n\ndef predict_physical_functioning(person):\n \"\"\"\n Calculates the physical functioning score of an agent, using the results of \n a spatial autoregressive lag model.\n \"\"\"\n if rcParams['NBH_effects_type'] == \"egocentric\":\n prefix = 'reg.pf.Ego'\n elif rcParams['NBH_effects_type'] == \"vernacular\":\n prefix = 'reg.pf.FMV'\n elif rcParams['NBH_effects_type'] == \"none\":\n prefix = 'reg.pf.NoVegEffect'\n else:\n raise StatisticsError('No coefficients specified for neighborhoods effects type \"%s\"'%rcParams['NBH_effects_type'])\n\n ##################################\n # Neighborhood characteristics\n ##################################\n # Note that in the regression model the coefficient for veg fraction is \n # calculated on the log of the (percentage veg in NBH + 1)\n if rcParams['NBH_effects_type'] in [\"egocentric\", \"vernacular\"]:\n xb_sum = rcParams[prefix + '.coef.log_veg_fraction'] * np.log(person._veg_fraction*100 + 1)\n else:\n xb_sum = 0\n\n ##################################\n # Individual-level characteristics\n ##################################\n xb_sum += rcParams[prefix + '.coef.age'] * person.get_age_years()\n\n xb_sum += rcParams[prefix + '.coef.age_squared'] * (person.get_age_years()**2)\n\n if person.get_ethnicity() == 1:\n xb_sum += rcParams[prefix + '.coef.major_ethnic_1']\n elif person.get_ethnicity() == 2:\n xb_sum += rcParams[prefix + '.coef.major_ethnic_2']\n elif person.get_ethnicity() == 3:\n xb_sum += rcParams[prefix + '.coef.major_ethnic_3']\n elif person.get_ethnicity() == 4:\n xb_sum += rcParams[prefix + '.coef.major_ethnic_4']\n else:\n raise StatisticsError(\"Ethnicity %s does not have a specified coefficient\"%person.get_ethnicity())\n\n if person._education == 0:\n xb_sum += rcParams[prefix + '.coef.education_0']\n elif person._education == 1:\n xb_sum += rcParams[prefix + '.coef.education_1']\n elif person._education == 2:\n xb_sum += rcParams[prefix + '.coef.education_2']\n elif person._education == 3:\n xb_sum += rcParams[prefix + '.coef.education_3']\n elif person._education == 4:\n xb_sum += rcParams[prefix + '.coef.education_4']\n else:\n raise StatisticsError(\"Education %s does not have a specified coefficient\"%person._education)\n\n xb_sum += rcParams[prefix + '.coef.charcoal'] * person._charcoal\n\n xb_sum += rcParams[prefix + '.coef.own_toilet'] * person._own_toilet\n\n if person._yrs_in_house_cat == \"5\":\n xb_sum += rcParams[prefix + '.coef.yrs_in_house_cat_0']\n elif person._yrs_in_house_cat == \"15\":\n xb_sum += rcParams[prefix + '.coef.yrs_in_house_cat_5']\n elif person._yrs_in_house_cat == \"30\":\n xb_sum += rcParams[prefix + '.coef.yrs_in_house_cat_15']\n elif person._yrs_in_house_cat == \">30\":\n xb_sum += rcParams[prefix + '.coef.yrs_in_house_cat_gt30']\n else:\n raise StatisticsError(\"Yrs_In_House_Cat %s does not have a specified coefficient\"%person._yrs_in_house_cat)\n\n # Intercept\n xb_sum += rcParams[prefix + '.coef.intercept']\n\n xb_sum += np.random.randn()*rcParams[prefix + '.residvariance']\n\n return xb_sum\n","repo_name":"azvoleff/accraabm","sub_path":"statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":6881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"33269425357","text":"import numpy as np\nimport time\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation, Dropout\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.datasets import mnist\n\n\ndef get_mlp_model(input_size, hidden_layer_size, dropout_factor, output_size):\n model = Sequential()\n model.add(Dense(hidden_layer_size, input_dim=input_size))\n model.add(Activation('relu'))\n model.add(Dropout(dropout_factor))\n model.add(Dense(hidden_layer_size))\n model.add(Activation('relu'))\n model.add(Dropout(dropout_factor))\n model.add(Dense(output_size))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n return model\n\n\ndef get_cnn_model(input_shape, filters, kernel_size, pool_size, dropout_factor, output_size):\n model = Sequential()\n model.add(Conv2D(filters=filters,\n kernel_size=kernel_size,\n activation='relu',\n input_shape=input_shape))\n model.add(MaxPooling2D(pool_size))\n model.add(Conv2D(filters=filters,\n kernel_size=kernel_size,\n activation='relu'))\n model.add(MaxPooling2D(pool_size))\n model.add(Conv2D(filters=filters,\n kernel_size=kernel_size,\n activation='relu'))\n model.add(Flatten())\n model.add(Dropout(dropout_factor))\n model.add(Dense(output_size))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n return model\n\n\ndef run_comparison():\n # load data from mnist dataset\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n # count unique labels. In case of MNIST, ten elements, labels from 0 to 9\n output_size = len(np.unique(y_train))\n\n # convert to one-hot vector\n y_train = to_categorical(y_train)\n y_test = to_categorical(y_test)\n\n image_size = x_train.shape[1]\n\n # normalize pixel values to range 0.0 .. 1.0\n x_train = x_train.astype('float32') / 255\n x_test = x_test.astype('float32') / 255\n\n print(\"==== Multilayer perceptron ====\")\n # MLP hyperparameters\n batch_size_mlp = 128\n input_size_mlp = image_size * image_size\n hidden_layer_size_mlp = 256\n dropout_factor_mlp = 0.45\n\n # resize input to single dimensional vector\n x_train = np.reshape(x_train, [-1, input_size_mlp])\n x_test = np.reshape(x_test, [-1, input_size_mlp])\n\n # get and train MLP\n model_mlp = get_mlp_model(input_size_mlp, hidden_layer_size_mlp, dropout_factor_mlp, output_size)\n start_mlp = time.time()\n model_mlp.fit(x_train, y_train, epochs=20, batch_size=batch_size_mlp)\n end_mlp = time.time()\n training_time_mlp = end_mlp - start_mlp\n\n # evaluate MLP on test data\n _, accuracy_mlp = model_mlp.evaluate(x_test, y_test, batch_size=batch_size_mlp, verbose=0)\n\n print(\"==== Convolution Neural Network ====\")\n # CNN hyperparameters\n batch_size_cnn = 128\n input_shape = (image_size, image_size, 1)\n kernel_size_cnn = 3\n pool_size_cnn = 2\n filters_cnn = 64\n dropout_factor_cnn = 0.2\n\n # resize input to two dimensional image with one channel\n x_train = np.reshape(x_train, [-1, image_size, image_size, 1])\n x_test = np.reshape(x_test, [-1, image_size, image_size, 1])\n\n # get and train CNN\n model_cnn = get_cnn_model(input_shape, filters_cnn, kernel_size_cnn, pool_size_cnn, dropout_factor_cnn, output_size)\n start_cnn = time.time()\n model_cnn.fit(x_train, y_train, epochs=10, batch_size=batch_size_cnn)\n end_cnn = time.time()\n training_time_cnn = end_cnn - start_cnn\n\n # evaluate cnn on test data\n _, accuracy_cnn = model_cnn.evaluate(x_test, y_test, batch_size=batch_size_cnn, verbose=0)\n\n # print results\n print(\"\\nMLP accuracy: %.1f%%. Training time: %.1fs. Parameters count: %d. Batch count: %d\" %\n (100.0 * accuracy_mlp, training_time_mlp, model_mlp.count_params(), batch_size_mlp))\n print(\"\\nCNN accuracy: %.1f%%. Training time: %.1fs. Parameters count: %d. Batch count: %d\" %\n (100.0 * accuracy_cnn, training_time_cnn, model_cnn.count_params(), batch_size_cnn))\n\n\nrun_comparison()\n","repo_name":"repcakk/mnist-mlp-vs-cnn","sub_path":"mnist-classifier.py","file_name":"mnist-classifier.py","file_ext":"py","file_size_in_byte":4392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"20640617886","text":"import asyncio\nimport nats\nimport time\nfrom nats.errors import ConnectionClosedError, TimeoutError, NoServersError\n\nimport blinkt\nimport json\n\nasync def run():\n # It is very likely that the demo server will see traffic from clients other than yours.\n # To avoid this, start your own locally and modify the example to use it.\n\n # Connect to NATS!\n nc = nats.NATS()\n await nc.connect(servers=\"nats://natstwinergy.etra-id.com:4223\",\n token=\"uBCdpRHUhuQsc4Q8Po\",\n max_reconnect_attempts=1)\n\n # Receive messages on 'foo'\n sub = await nc.subscribe(\"M5.data.energylight.bristol\")\n\n # Publish a message to 'foo'\n # await nc.publish(\"foo\", b'Hello from Python!')\n while 1:\n # Process a message\n try:\n msg = await sub.next_msg()\n print(\"Received:\", msg)\n data = json.loads(msg.data)\n\n if data['energy_light'] == 'green':\n blinkt.set_all(0,255,0)\n elif data['energy_light'] == 'yellow':\n blinkt.set_all(255,255,0)\n elif data['energy_light'] == 'red':\n blinkt.set_all(255,0,0)\n else:\n blinkt.set_all(0,0,255)\n\n blinkt.show()\n\n except Exception as e:\n print(e)\n time.sleep(60)\n\n\n # Close NATS connection\n await nc.close()\n\n\n\nif __name__ == '__main__':\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n try:\n asyncio.run(run())\n except KeyboardInterrupt:\n pass\n\n","repo_name":"samgunner/gridvis","sub_path":"twinergy_nat_LEDS.py","file_name":"twinergy_nat_LEDS.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"42005577131","text":"\"\"\"empty message\n\nRevision ID: 79c463336307\nRevises: 2fed03895153\nCreate Date: 2018-12-20 12:06:38.478060\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '79c463336307'\ndown_revision = '2fed03895153'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('organization',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=True),\n sa.Column('description', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('resource', sa.Column('organization_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'resource', 'organization', ['organization_id'], ['id'])\n op.drop_column('resource', 'organization')\n op.add_column('study', sa.Column('organization_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'study', 'organization', ['organization_id'], ['id'])\n op.add_column('training', sa.Column('organization_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'training', 'organization', ['organization_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'training', type_='foreignkey')\n op.drop_column('training', 'organization_id')\n op.drop_constraint(None, 'study', type_='foreignkey')\n op.drop_column('study', 'organization_id')\n op.add_column('resource', sa.Column('organization', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.drop_constraint(None, 'resource', type_='foreignkey')\n op.drop_column('resource', 'organization_id')\n op.drop_table('organization')\n # ### end Alembic commands ###\n","repo_name":"sartography/star-drive","sub_path":"backend/migrations/versions/79c463336307_.py","file_name":"79c463336307_.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"32622238348","text":"from reportlab.pdfbase import ttfonts\nfrom openerp.osv import fields, osv\nfrom openerp.report.render.rml2pdf import customfonts\n\nimport logging\n\n\"\"\"This module allows the mapping of some system-available TTF fonts to\nthe reportlab engine.\n\nThis file could be customized per distro (although most Linux/Unix ones)\nshould have the same filenames, only need the code below).\n\nDue to an awful configuration that ships with reportlab at many Linux\nand Ubuntu distros, we have to override the search path, too.\n\"\"\"\n_logger = logging.getLogger(__name__)\n\n\nclass res_font(osv.Model):\n _name = \"res.font\"\n _description = 'Fonts available'\n _order = 'name'\n\n _columns = {\n 'name': fields.char(\"Name\", required=True),\n }\n\n _sql_constraints = [\n ('name_font_uniq', 'unique(name)', 'You can not register two fonts with the same name'),\n ]\n\n def discover_fonts(self, cr, uid, ids, context=None):\n \"\"\"Scan fonts on the file system, add them to the list of known fonts\n and create font object for the new ones\"\"\"\n customfonts.CustomTTFonts = customfonts.BaseCustomTTFonts\n\n found_fonts = {}\n for font_path in customfonts.list_all_sysfonts():\n try:\n font = ttfonts.TTFontFile(font_path)\n _logger.debug(\"Found font %s at %s\", font.name, font_path)\n if not found_fonts.get(font.familyName):\n found_fonts[font.familyName] = {'name': font.familyName}\n\n mode = font.styleName.lower().replace(\" \", \"\")\n\n customfonts.CustomTTFonts.append((font.familyName, font.name, font_path, mode))\n except ttfonts.TTFError:\n _logger.warning(\"Could not register Font %s\", font_path)\n\n # add default PDF fonts\n for family in customfonts.BasePDFFonts:\n if not found_fonts.get(family):\n found_fonts[family] = {'name': family}\n\n # remove deleted fonts\n existing_font_ids = self.search(cr, uid, [], context=context)\n existing_font_names = []\n for font in self.browse(cr, uid, existing_font_ids):\n existing_font_names.append(font.name)\n if font.name not in found_fonts.keys():\n self.unlink(cr, uid, font.id, context=context)\n\n # add unknown fonts\n for family, vals in found_fonts.items():\n if family not in existing_font_names:\n self.create(cr, uid, vals, context=context)\n return True\n\n def init_no_scan(self, cr, uid, context=None):\n \"\"\"Add demo data for PDF fonts without scan (faster for db creation)\"\"\"\n for font in customfonts.BasePDFFonts:\n if not self.search(cr, uid, [('name', '=', font)], context=context):\n self.create(cr, uid, {'name':font}, context=context)\n return True","repo_name":"Ichag/openerp-server","sub_path":"openerp/addons/base/res/res_font.py","file_name":"res_font.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"72348006776","text":"import re\r\nimport argparse\r\n# from argparse import ArgumentParser\r\n\r\n\r\ndef main():\r\n parser=argparse.ArgumentParser()\r\n parser.add_argument(\"word\",help='Specify word to be searched ')\r\n parser.add_argument(\"fname\",help=\"Specify file name to search\")\r\n args = parser.parse_args()\r\n searchfile=open(args.fname,\"r\")\r\n linenum=0\r\n\r\n for line in searchfile.readlines():\r\n line=line.strip('\\n\\r')\r\n linenum+=1\r\n searchres=re.search(args.word,line,re.M|re.I)\r\n if searchres:\r\n print(str(linenum)+\" : \"+line)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"kunal097/Advance-python","sub_path":"lookup.py","file_name":"lookup.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"12081145403","text":"\nfrom gevent.server import StreamServer\nfrom config import *\n\ndef httpd(socket, addr):\n while True:\n line = socket.recv(1024)\n if EOL1 in line or EOL2 in line:\n break\n socket.sendall(response)\n \nser = StreamServer(('0.0.0.0', 8080), httpd)\nser.serve_forever()\n","repo_name":"xufinal/python-cocurrency","sub_path":"app/t_gevent.py","file_name":"t_gevent.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"13654241434","text":"'''\nPower Set: Write a method to return all subsets of a set.\n'''\n\nimport copy\n\ndef getPowerSet(set):\n\tif set is None:\n\t\treturn None\n\treturn getPowerSetHelper(set)\n\ndef getPowerSetHelper(set):\n\tif len(set) == 0:\n\t\treturn [[]]\n\tsubset = getPowerSetHelper(set[1:])\n\tmoreSubset = copy.deepcopy(subset)\n\tfor list in moreSubset:\n\t\tlist.append(set[0])\n\treturn subset + moreSubset\n\ndef getPowerSetTemplate(set):\n\tif set is None:\n\t\treturn None\n\tgetPowerSetTemplateHelper([], set, 0)\n\treturn\n\ndef getPowerSetTemplateHelper(path, set, pos):\n\tprint(path)\n\n\tfor index in range(pos, len(set)):\n\t\tpath.append(set[index])\n\t\tgetPowerSetTemplateHelper(path, set, index+1)\n\t\tpath.pop(len(path)-1)\n\n\treturn\n\ndef getUniquePowerSet(set):\n\tif set is None:\n\t\treturn None\n\tgetUniquePowerSetHelper([], set, 0)\n\treturn\n\ndef getUniquePowerSetHelper(path, set, pos):\n\tprint(path)\n\n\tfor index in range(pos, len(set)):\n\t\tif (index > 0) and (set[index -1] == set[index]):\n\t\t\tcontinue\n\t\tpath.append(set[index])\n\t\tgetUniquePowerSetHelper(path, set, index+1)\n\t\tpath.pop(len(path)-1)\n\n\treturn \n\n\nif __name__ == '__main__':\n\tset = [3,2]\n\t#my method\n\tprint(getPowerSet(set))\n\n\t#template method\n\tprint()\n\tgetPowerSetTemplate(set)\n\n\t#unique power set template\n\tprint()\n\tset = [1,1,2,2]\n\tgetUniquePowerSet(set)\n\n\n","repo_name":"oreoero/cc150-python","sub_path":"chapter8/power_set.py","file_name":"power_set.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"74115417016","text":"import json\n\nfrom pydantic import BaseModel\nfrom typing import Dict, List, Optional\n\nclass OrderGoodsOptionDto(BaseModel):\n delivery_type: str\n sno: int\n ea: int\n cart_sno: int\n cart_sno: Optional[int]\n text_option: Optional[str]\n\n class Config:\n validate_assignment = 'limited'\n\n def showMemo(self):\n print(f'memo: {self.memo}')\n\n\nclass OrderRequestDto(BaseModel):\n total_price: int\n receiver_name: str\n receiver_postcode: str\n pay_method: str\n receiver_tel: str\n receiver_addr_detail: str\n is_toss_transfer: bool\n receipt_type: str\n goods_options: List[OrderGoodsOptionDto]\n emoney: int\n receiver_addr: str\n delivery_fee: int\n memo: str\n\n\nrequest_body_dict = {\n\t\"total_price\": 15800,\n\t\"receiver_name\": \"easywaldo\",\n\t\"receiver_postcode\": \"06234\",\n\t\"pay_method\": \"card\",\n\t\"receiver_tel\": \"111-222-6789\",\n\t\"receiver_addr_detail\": \"155층\",\n\t\"is_toss_transfer\": True,\n\t\"receipt_type\": \"0\",\n\t\"goods_options\": [{\n\t\t\"delivery_type\": \"standard\",\n\t\t\"sno\": 9999999999,\n\t\t\"text_option\": None,\n\t\t\"ea\": 1,\n\t\t\"cart_sno\": None\n\t}],\n\t\"emoney\": 0,\n\t\"receiver_addr\": \"Seoul, Korea\",\n\t\"delivery_fee\": 0,\n\t\"memo\": \"\"\n}\njson_str = json.dumps(request_body_dict)\nreceived_json_data = json.loads(json_str)\norder_data: OrderRequestDto = OrderRequestDto.parse_obj(received_json_data)\n\nprint(type(order_data))\nprint(order_data.total_price)\nprint(order_data.receiver_name)","repo_name":"easywaldo/pydantic_playground","sub_path":"order_dto_sample/order_dto_test.py","file_name":"order_dto_test.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"28477268451","text":"from typing import List\nfrom pandas.core.frame import DataFrame\nimport telebot\nfrom config import TOKEN\nimport requests as rq\nfrom bs4 import BeautifulSoup as bs\nimport re\nimport pandas as pd\nimport sqlite3\nfrom collections import Counter\n\n\ndata = pd.read_csv('rec.csv')\n\nbot = telebot.TeleBot(TOKEN)\n\n\n@bot.message_handler(commands=['start', 'help'])\ndef send_welcome(message: str) -> None:\n connect = sqlite3.connect('users.db')\n cursor = connect.cursor()\n\n cursor.execute('''CREATE TABLE IF NOT EXISTS user_links(\n id INTEGER, link TEXT\n )''')\n connect.commit()\n\n user_id = message.from_user.id\n cursor.execute(f'SELECT id FROM user_links WHERE id = {user_id}')\n user_data = cursor.fetchone()\n if user_data is None:\n bot.send_message(message.from_user.id,\n f'Привет, {message.from_user.first_name}!\\n'\n f'Я бот, который знает много игр.'\n f'Пожалуйста, пришли ссылку на свой профиль в Steam, '\n f'а я тебе что-нибудь порекомендую.')\n else:\n bot.send_message(message.from_user.id,\n f'Привет, {message.from_user.first_name}!'\n f'Рад тебя видеть! Хочешь во что-нибудь поиграть?\\n'\n f'Выбирай:\\n'\n f'/free - если хочешь какую-нибудь бесплатную игру,\\n'\n f'/paid - если подумываешь купить что-нибудь новенькое.')\n\n\ndef get_link(message: str) -> bool:\n if re.search(r'https://steamcommunity', message.text):\n return True\n else:\n return False\n\n\n@bot.message_handler(func=get_link, content_types=['text'])\ndef write_link(message: str) -> None:\n connect = sqlite3.connect('users.db')\n cursor = connect.cursor()\n\n user_id = message.from_user.id\n cursor.execute(f'SELECT id FROM user_links WHERE id = {user_id}')\n user_data = cursor.fetchone()\n if user_data is None:\n url = f'{message.text}/games/?tab=all'\n cursor.execute(\n 'INSERT INTO user_links VALUES(?,?);', [user_id, url]\n )\n connect.commit()\n bot.send_message(message.from_user.id,\n 'Отлично! Будем знакомы :) Выбирай:\\n'\n '/free - если хочешь какую-нибудь бесплатную игру,\\n'\n '/paid - если подумываешь купить что-нибудь новенькое.')\n else:\n bot.send_message(message.from_user.id, 'Давно не виделись!')\n\n\n@bot.message_handler(commands=['delete'])\ndef delete(message: str) -> None:\n connect = sqlite3.connect('users.db')\n cursor = connect.cursor()\n\n user_id = message.from_user.id\n cursor.execute(f'DELETE FROM user_links WHERE id = {user_id}')\n connect.commit()\n\n\ndef get_games(link: str) -> List[str]:\n page = rq.get(link)\n soup = bs(page.content, 'html.parser')\n text = str(soup.find('script', {'language': 'javascript'}).prettify())\n games = re.findall(r'(?<=\"name\":\").+?(?=\")', text)\n # hours = re.findall(r'(?<=\"hours_forever\":\").+?(?=\")', text)\n games = [' '.join(re.findall('[A-z0-9]+', elem)) for elem in games]\n games = [re.sub(r'\\\\u\\w{4}|\\\\', '', i) for i in games]\n # games = list(zip(games, hours))\n # print(games)\n return games\n\n\ndef get_clusters(games: List[str], cluster: str, loc_data: DataFrame) -> List[int]:\n clusters = loc_data[\n [x in games[:100] for x in loc_data['Title_clean']]\n ][cluster]\n top_clusters = Counter(clusters).most_common(3)\n return top_clusters\n\n\ndef get_recs(games: list, cluster: str, top_cluster: int, loc_data: DataFrame) -> DataFrame:\n game = loc_data[\n ([x not in games for x in loc_data['Title_clean']]) &\n (loc_data[cluster] == top_cluster)\n ].sort_values(\n ['Scores Count', 'Mean score'],\n ascending=False)[\n ['Title', 'URL', 'Description']\n ].head(1)\n return game\n\n\n@bot.message_handler(commands=['free'])\ndef recommend_free(message: str) -> None:\n connect = sqlite3.connect('users.db')\n cursor = connect.cursor()\n\n user_id = message.from_user.id\n cursor.execute(f'SELECT link FROM user_links WHERE id = {user_id}')\n user_url = cursor.fetchone()[0]\n\n games = get_games(user_url)\n if len(games) == 0:\n bot.send_message(message.from_user.id,\n 'Кажется, у тебя приватный аккаунт. '\n 'Проверь, видны ли другим людям твои игры'\n 'и есть ли у теб игры, и попробуй снова.')\n else:\n loc_data = data\n use = get_clusters(games, 'use_cluster', loc_data)\n\n loc_data = loc_data[loc_data['isFree'] == 'Free']\n loc_data.reset_index(drop=True, inplace=True)\n\n recs_use1 = get_recs(games, 'use_cluster', use[0][0], loc_data)\n recs_use2 = get_recs(games, 'use_cluster', use[1][0], loc_data)\n recs_use3 = get_recs(games, 'use_cluster', use[2][0], loc_data)\n\n bot.send_message(message.from_user.id,\n f'Тебе может понравиться:\\n'\n f'1. [{recs_use1[\"Title\"].to_list()[0]}]'\n f'({recs_use1[\"URL\"].to_list()[0]})\\n'\n f'{recs_use1[\"Description\"].to_list()[0].strip()}\\n'\n f'2. [{recs_use2[\"Title\"].to_list()[0]}]'\n f'({recs_use2[\"URL\"].to_list()[0]})\\n'\n f'{recs_use2[\"Description\"].to_list()[0].strip()}\\n'\n f'3. [{recs_use3[\"Title\"].to_list()[0]}]'\n f'({recs_use3[\"URL\"].to_list()[0]})\\n'\n f'{recs_use3[\"Description\"].to_list()[0].strip()}\\n',\n parse_mode=\"markdown\"\n )\n\n\n@bot.message_handler(commands=['paid'])\ndef recommend_paid(message: str) -> None:\n connect = sqlite3.connect('users.db')\n cursor = connect.cursor()\n\n user_id = message.from_user.id\n cursor.execute(f'SELECT link FROM user_links WHERE id = {user_id}')\n user_url = cursor.fetchone()[0]\n\n games = get_games(user_url)\n if len(games) == 0:\n bot.send_message(message.from_user.id,\n 'Кажется, у тебя приватный аккаунт. '\n 'Проверь, видны ли другим людям твои игры'\n 'и есть ли у теб игры, и попробуй снова.')\n else:\n loc_data = data\n use = get_clusters(games, 'use_cluster', loc_data)\n\n loc_data = loc_data[loc_data['isFree'] == 'payed']\n loc_data.reset_index(drop=True, inplace=True)\n\n recs_use1 = get_recs(games, 'use_cluster', use[0][0], loc_data)\n recs_use2 = get_recs(games, 'use_cluster', use[1][0], loc_data)\n recs_use3 = get_recs(games, 'use_cluster', use[2][0], loc_data)\n\n bot.send_message(message.from_user.id,\n f'Тебе может понравиться:\\n'\n f'1. [{recs_use1[\"Title\"].to_list()[0]}]'\n f'({recs_use1[\"URL\"].to_list()[0]})\\n'\n f'{recs_use1[\"Description\"].to_list()[0].strip()}\\n'\n f'2. [{recs_use2[\"Title\"].to_list()[0]}]'\n f'({recs_use2[\"URL\"].to_list()[0]})\\n'\n f'{recs_use2[\"Description\"].to_list()[0].strip()}\\n'\n f'3. [{recs_use3[\"Title\"].to_list()[0]}]'\n f'({recs_use3[\"URL\"].to_list()[0]})\\n'\n f'{recs_use3[\"Description\"].to_list()[0].strip()}\\n',\n parse_mode=\"markdown\"\n )\n\n\nbot.polling(none_stop=True)\n","repo_name":"DPetrukhenko/Cl_2020","sub_path":"Final_project/bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":8196,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"729547239","text":"import re\r\nimport datetime\r\nimport os\r\nimport shutil\r\nimport win32com.client\r\nfrom pathlib import Path, PureWindowsPath\r\nimport win32wnet\r\nimport json\r\n\r\n\r\n#load configurations\r\nwith open(\"config.json\") as jsonFile:\r\n jsonObject = json.load(jsonFile)\r\n jsonFile.close()\r\n\r\nallowed_extensions = jsonObject['allowed_extensions']\r\nnumber_of_days_check = jsonObject['number_of_days_check']\r\nignore_emails_from_senders = jsonObject['ignore_emails_from_senders']\r\nonly_unread = jsonObject['only_unread']\r\ncurrent_employees = jsonObject['current_employees']\r\noverwrite_or_skip_or_rename = jsonObject['overwrite_or_skip_or_rename']\r\nlocalPath = jsonObject['localPath']\r\nnetworkPath = jsonObject['networkPath']\r\nnetworkHost = jsonObject['networkHost']\r\nnetworkUser = jsonObject['networkUser']\r\nnetworkPass = jsonObject['networkPass']\r\ncurrentEmployeesPath = jsonObject['currentEmployeesPath']\r\nnewEmployeesPath = jsonObject['newEmployeesPath']\r\n\r\n#manual configurations\r\n\r\n#allowed_extensions = ['.pdf', '.docx']\r\n#number_of_days_check = 15\r\n#ignore_emails_from_senders = ['noreply']\r\n#only_unread = False\r\n#current_employees = \"CURRENT EMPLOYEES 2023\"\r\n\r\n# 1=overwrite, 2=skip, 3=rename\r\n#overwrite_or_skip_or_rename = 3\r\n\r\n# example: r\"E:/scripts/py/email_downloader/HR/\"\r\n#localPath = r\"temp/\"\r\n\r\n# example1: r\"Z:/scripts/py/email_downloader/HR/\"\r\n# example2: \\\\192.168.1.30\\Shared\\HR\r\n#networkPath = r\"//192.168.1.30/Shared/HR/\"\r\n\r\n# example: r\"E:/scripts/py/email_downloader/HR/current/\"\r\n#currentEmployeesPath = r\"temp/\"+current_employees+\"/\"\r\n\r\n#example: r\"E:/scripts/py/email_downloader/HR/new/\"\r\n#newEmployeesPath = r\"temp/new/\"\r\n\r\noutlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")\r\ninbox = outlook.GetDefaultFolder(6)\r\nFilter = (\"@SQL=\" + chr(34) + \"urn:schemas:httpmail:hasattachment\" +\r\n chr(34) + \"=1\")\r\n\r\ndef ignore_sender(email):\r\n return email.lower().startswith(tuple(ignore_emails_from_senders))\r\n\r\ndef is_date_in_range(receivedDate):\r\n today = datetime.date.today()\r\n if number_of_days_check <= 1:\r\n return receivedDate == today\r\n else:\r\n daysCount = abs((today - receivedDate).days)\r\n return daysCount <= number_of_days_check\r\n\r\ndef is_valid_message(message):\r\n if (message.Class != 43):\r\n return False\r\n if (only_unread == True):\r\n if (message.Unread == False):\r\n return False\r\n print (\"Is valid message!\")\r\n return True\r\n\r\ndef is_message_older(message):\r\n if is_date_in_range(message.Senton.date()) == False:\r\n return True\r\n return False\r\n \r\ndef is_document(fileName):\r\n file = os.path.splitext(fileName)\r\n if file != None:\r\n print (\"File is not none.\")\r\n file_extension = file[1]\r\n print (\"File extension: \" + file_extension)\r\n if allowed_extensions.count(str(file_extension).lower()) > 0:\r\n print (\"Is Valid Extension\")\r\n return True\r\n else:\r\n print (\"File is none.\")\r\n if fileName.lower().endswith(tuple(allowed_extensions)):\r\n print (\"file has valid extensions\")\r\n return True\r\n print (\"\\nIs not valid document!\")\r\n return False\r\n \r\ndef copy_to_local_drive():\r\n host = networkHost\r\n dest_share_path = \"\\\\Shared\\\\HR\"\r\n username = networkUser\r\n password = networkPass\r\n toDir = localPath\r\n fromDir = networkPath\r\n print (\"Local Drive Copying...\")\r\n win32wnet.WNetAddConnection2(0, None, '\\\\\\\\'+host, None, username, password)\r\n #shutil.copy(source_file, '\\\\\\\\'+host+dest_share_path+'\\\\')\r\n destination = shutil.copytree('\\\\\\\\'+host+dest_share_path+'\\\\', toDir, dirs_exist_ok=True)\r\n win32wnet.WNetCancelConnection2('\\\\\\\\'+host, 0, 0) # optional disconnect\r\n print (\"Connection Disconnected.\")\r\n \r\n #if os.path.exists(toDir):\r\n # shutil.rmtree(toDir)\r\n #destination = shutil.copytree(fromDir, toDir, dirs_exist_ok=True)\r\n\r\ndef get_files_tree(src):\r\n print (\"Get Source Files Begin\")\r\n req_files = []\r\n for r, d, files in os.walk(src):\r\n for file in files:\r\n src_file = os.path.join(r, file)\r\n src_file = src_file.replace('\\\\', '/')\r\n print (\"Source File : \" + str(src_file))\r\n if src_file.lower().endswith(tuple(allowed_extensions)):\r\n req_files.append(src_file)\r\n return req_files\r\n\r\ndef copy_tree(src_path, dest_path):\r\n print (\"Copy Tree Begins\")\r\n print (\"src path : \" + src_path)\r\n print (\"dest path : \" +dest_path)\r\n for cf in get_files_tree(src_path):\r\n df= cf.replace(src_path, dest_path)\r\n print (\"dest file name : \" + df)\r\n dest_dir = os.path.dirname(df)\r\n print (\"dest directory: \" + dest_dir)\r\n if not os.path.exists(dest_dir):\r\n os.makedirs(dest_dir)\r\n print (\"directory created\")\r\n else:\r\n print (\"path exists\")\r\n \r\n print (\"Check Dest Dir : \" + df)\r\n if os.path.exists(df):\r\n print (\"File path exists.\")\r\n if overwrite_or_skip_or_rename == 1:\r\n print (\"File to be replaced.\")\r\n shutil.copy2(cf, df)\r\n elif overwrite_or_skip_or_rename == 2:\r\n print (\"File to be ignored.\")\r\n elif overwrite_or_skip_or_rename == 3:\r\n print (\"File to be renamed and copied.\")\r\n file = os.path.splitext(df)\r\n file_name = file[0]\r\n new_file_name = file_name + \"_\" + datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\r\n file_extension = file[1]\r\n new_df = new_file_name + file_extension\r\n print (\"new file path : \" + str(new_df))\r\n shutil.copy2(cf, new_df)\r\n else:\r\n shutil.copy2(cf, df)\r\n print (\"File Copied.\")\r\n \r\ndef copy_to_network_drive():\r\n destination = shutil.copytree(src, dest, dirs_exist_ok=True)\r\n\r\ndef is_current_employee_via_dirNme(sender_name, sender_email):\r\n names = [name for name in os.listdir(currentEmployeesPath) if os.path.isdir(os.path.join(currentEmployeesPath,name))]\r\n for name in names:\r\n formattedName = name.lower().strip()\r\n if (formattedName == sender_email.lower().strip() or formattedName == sender_name.lower().strip()):\r\n return [True, name]\r\n return [False, '']\r\n \r\ndef is_current_employee(sender_email):\r\n path = Path(\"current_employees_email_addresses.txt\")\r\n if (path.is_file()):\r\n namesFile = open(path, 'r')\r\n names = namesFile.readlines()\r\n for name in names:\r\n if (name.lower().strip() == sender_email.lower().strip()):\r\n return True\r\n return False\r\n \r\ntry:\r\n messages = inbox.Items.Restrict(Filter)\r\n messages.Sort('[ReceivedTime]', True)\r\n copied_to_local = False\r\n for message in messages:\r\n if (is_message_older(message)):\r\n print (\"Last Date to Ignore From : \")\r\n print (message.Senton.date())\r\n break\r\n if is_valid_message(message):\r\n if message.SenderEmailType=='EX':\r\n if message.Sender.GetExchangeUser() != None:\r\n current_sender = str(message.Sender.GetExchangeUser().PrimarySmtpAddress).lower()\r\n else:\r\n current_sender = str(message.Sender.GetExchangeDistributionList().PrimarySmtpAddress).lower()\r\n else:\r\n current_sender = str(message.SenderEmailAddress).lower()\r\n \r\n if ignore_sender(current_sender):\r\n print (\"Sender Ignored: \")\r\n print (current_sender)\r\n continue\r\n \r\n current_subject = str(message.Subject).lower()\r\n current_sender_name = str(message.Sender).lower()\r\n for attachment in message.Attachments:\r\n fileName = attachment.FileName\r\n if (is_document(fileName)):\r\n if (copied_to_local == False):\r\n copied_to_local = True\r\n copy_to_local_drive()\r\n \r\n checkSender = is_current_employee_via_dirNme(current_sender_name, current_sender)\r\n if (checkSender[0]):\r\n newPath = currentEmployeesPath + checkSender[1]\r\n else:\r\n print (\"New path to be created.\")\r\n newPath = newEmployeesPath + current_sender\r\n Path(newPath).mkdir(parents=True, exist_ok=True)\r\n fname = os.path.join(newPath, str(attachment))\r\n current_dir = os.getcwd()\r\n print (current_dir)\r\n filename = PureWindowsPath(current_dir + \"/\" + fname)\r\n correct_path = Path(filename)\r\n if (os.path.isfile(correct_path) == False):\r\n print (\"Saving File: \" + str(correct_path))\r\n attachment.SaveAsFile(correct_path)\r\n else:\r\n pass\r\n copy_tree(localPath, networkPath)\r\nexcept Exception as e:\r\n print('Error: '+ str(e))\r\n\r\n","repo_name":"tariqkhan051/email-downloader","sub_path":"read_email.py","file_name":"read_email.py","file_ext":"py","file_size_in_byte":9182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"29435196286","text":"import pygame\nimport numpy as np\nimport tkinter as tk\nfrom tkinter import filedialog\nfrom PIL import Image, ImageOps\nfrom PIL import ImageEnhance\n\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (200, 0, 0)\n\n# 5px squares\nwidth = 5\nheight = 5\n\n#1px margin\nmargin = 1\n\n#90x90 square matrix\nrows = 100\n\n#button height\nbtn_height = 50\n\nscreen_width = rows * (width + margin) + 2 * margin \nscreen_height = screen_width + btn_height\n\nbtn_width = screen_width // 3\n\nstart_build = False\n\nclass button:\n def __init__(self, x, y, width, height, title):\n self.height = height\n self.width = width\n self.title = title\n self.x = x\n self.y = y\n\n\n def isOver(self, pos):\n if ((pos[0] > self.x and pos[0] < self.x + self.width) and (pos[1] > self.y and pos[1] < self.y + self.height)):\n return True\n else:\n return False\n\n def draw(self, screen, color):\n pygame.draw.rect(screen, color, (self.x, self.y, self.width, self.height))\n if self.title != '':\n font = pygame.font.SysFont('arial', 20)\n title = font.render(self.title, 1, (0,0,0))\n screen.blit(title, (self.x + int(self.width/2 - title.get_width()/2), self.y + int(self.height/2 - title.get_height()/2)))\n\n\n \n\ndef create_grid(size):\n grid = []\n for i in range(size):\n grid.append([])\n for j in range(size):\n grid[i].append(0) \n return grid\n\n\n\nmain_grid = create_grid(rows) # our main grid\n\n\ndef generate(grid): # generation of next iteration grid\n row = len(grid)\n\n\n aux = create_grid(row) # create a separate grid\n\n \n # do not update the current main grid until all the cells are updated\n\n for i in range(row): # include boundaries, we use modulus arithmetic\n for j in range(row):\n alive_neighbours = 0\n for x in range(-1, 2):\n for y in range(-1, 2):\n if not (x == 0 and y == 0): #exclude same cell.\n r = (i + x + row) % row\n c = (j + y + row) % row\n if (grid[r][c] == 1): #only include alive neighbours\n alive_neighbours += 1\n\n #count neighbours\n if (grid[i][j] == 1):\n\n #first case: Any live cell with fewer than two live neighbours dies, as if by underpopulation.\n if (alive_neighbours < 2):\n aux[i][j] = 0\n \n #second case: Any live cell with two or three live neighbours lives on to the next generation.\n elif (alive_neighbours <= 3):\n aux[i][j] = 1\n \n #third case: Any live cell with more than three live neighbours dies, as if by overpopulation.\n elif (alive_neighbours > 3):\n aux[i][j] = 0\n \n #fourth case: Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n elif (grid[i][j] == 0 and alive_neighbours == 3):\n aux[i][j] = 1\n\n return aux\n\n \n\nstart_button = button(0, screen_width, btn_width, btn_height, \"start\")\nclear_button = button(btn_width + margin, screen_width, btn_width, btn_height, \"clear\")\nupload_button = button((btn_width + margin) * 2, screen_width, btn_width, btn_height, \"upload\")\n\n\ndef update_grid(grid, start_build):\n\n if start_build == True:\n grid = generate(grid)\n # Draw the grid\n for row in range(rows):\n for column in range(rows):\n color = WHITE\n if (grid[row][column] == 1):\n color = BLACK\n pygame.draw.rect(\n screen,\n color,\n [\n (margin + width) * column + margin,\n (margin + height) * row + margin,\n width,\n height\n ]\n )\n\n start_button.draw(screen, WHITE)\n clear_button.draw(screen, WHITE)\n upload_button.draw(screen, WHITE)\n return grid\n\n\n# Initialize pygame\npygame.init()\n \n# Set the HEIGHT and WIDTH of the screen\nscreen = pygame.display.set_mode((screen_width, screen_height))\n \n# Set title of screen\npygame.display.set_caption(\"Conway\")\n \n# Loop until the user clicks the close button.\ndone = False\n\n\n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\n \n# -------- Main Program Loop -----------\nwhile not done:\n\n for event in pygame.event.get(): # User did something\n\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n\n elif event.type == pygame.MOUSEBUTTONDOWN:\n # User clicks the mouse. Get the position\n pos = pygame.mouse.get_pos()\n if (pos[1] <= screen_width-1):\n # Change the x/y screen coordinates to grid coordinates\n column = pos[0] // (width + margin)\n row = pos[1] // (height + margin)\n # Set that location to one\n \n main_grid[row][column] = 1 if main_grid[row][column] == 0 else 0\n\n print(\"Click \", pos, \"Grid coordinates: \", row, column)\n\n elif (start_button.isOver(pos)): \n start_build = not start_build\n start_button.title = \"stop\" if start_button.title == \"start\" else \"start\" \n\n elif (clear_button.isOver(pos)):\n main_grid = create_grid(rows)\n\n start_build = False\n start_button.title = \"start\"\n \n elif (upload_button.isOver(pos)):\n # this part is gonna be a pain in the ass\n\n root = tk.Tk()\n root.withdraw()\n root.attributes(\"-topmost\", True)\n file_path = filedialog.askopenfilename(parent = root)\n if file_path:\n\n img = Image.open(file_path)\n \n ######################################################################################################\n # Kudos to this guy for the simple tutorial on converting images to pixel grid #\n # # \n # https://linux.ime.usp.br/~robotenique//computer%20science/python/2017/09/17/image-grid-python.html #\n ######################################################################################################\n \n size = (rows, rows)\n\n img = ImageOps.fit(img, size, Image.ANTIALIAS)\n img = ImageEnhance.Contrast(img).enhance(2.0).convert('1')\n pixel_arr = np.asarray(img)\n \n print(pixel_arr.shape)\n for i in range(rows):\n for j in range(rows):\n main_grid[i][j] = not pixel_arr[i][j]\n else:\n pass\n # Set the screen background\n screen.fill(BLACK)\n\n\n main_grid = update_grid(main_grid, start_build)\n\n # Go ahead and update the screen with what we've drawn.\n pygame.display.update()\n clock.tick()\n\n # Limit to 60 frames per second\n\n \n \n \n# Be IDLE friendly. If you forget this line, the program will 'hang'\n# on exit.\npygame.quit()","repo_name":"s-bose/game_of_life","sub_path":"conway.py","file_name":"conway.py","file_ext":"py","file_size_in_byte":7584,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"28693060339","text":"import time\nfrom functools import reduce\n\nfrom dijkstar import Graph, find_path\n\nimport ryan_scrapper\n\n\ndef find_shortest_path(routes, dep_code, dest_code):\n graph = Graph()\n for route in routes:\n departure, destination, length = route\n graph.add_edge(departure, destination, length)\n shortest_path = find_path(graph, dep_code, dest_code)\n return shortest_path\n\n\ndef find_all_cheepest_paths(flights, dep_code, dest_code):\n all_cheepest_paths = []\n graph = Graph()\n start_time = time.time()\n # building graph\n for flight1 in flights:\n if flight1.arrival_time == None or flight1.price_euro == \"\":\n continue\n for flight2 in flights:\n if flight1.dest_air_code != flight2.dep_air_code:\n continue\n if flight2.departure_time != None and flight1.arrival_time < flight2.departure_time:\n graph.add_edge(flight1, flight2, float(flight1.price_euro))\n\n # quering graph\n tickets_from_dep = ryan_scrapper.get_all_flights_by_departure_code(flights, dep_code)\n tickets_to_dest = ryan_scrapper.get_all_flights_by_destination_code(flights, dest_code)\n\n print(\"Building --- %s seconds ---\" % (time.time() - start_time))\n\n start_time = time.time()\n\n for ticket_from_dep in tickets_from_dep:\n for ticket_to_dest in tickets_to_dest:\n try:\n path = find_path(graph, ticket_from_dep, ticket_to_dest)\n all_cheepest_paths.append(path)\n except:\n path = \"No path\"\n min_total_cost = 10000000000\n optimal_route_tickets = []\n for c_path in all_cheepest_paths:\n route_tickets = c_path.nodes\n total = reduce(lambda a, t: a + t.price_euro, route_tickets, 0)\n if total < min_total_cost:\n min_total_cost = total\n optimal_route_tickets = route_tickets\n print(\"Finding --- %s seconds ---\" % (time.time() - start_time))\n print(optimal_route_tickets)\n print(min_total_cost)\n return all_cheepest_paths\n\n","repo_name":"NZ-code/ryanApiScrapper","sub_path":"path_finding/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"43185521251","text":"\"\"\"\n.. module:: filesystem\n :platform: Unix, Windows\n :synopsis: APIs related to file system\n\n.. moduleauthor:: Ajeet Singh \n\"\"\"\nimport os\nfrom goldfinch import validFileName\nimport pathlib\nimport zipfile\nimport io\nimport shutil\n\nclass File(object):\n\n \"\"\"Represents a file on file system. This class supports :meth:`copy` and :meth:`move` commands only and for all other operations use :mod:`os` or :mod:`pathlib` modules. There are two attributes :attr:`os` and :attr:`path` which provides access to both of the above mentioned modules respectively\n \"\"\"\n\n def __init__(self, file_name, create_if_not_exists=False, base_path=None):\n \"\"\"TODO: to be defined1. \"\"\"\n self._base_path = None\n self._ext = None\n\n if create_if_not_exists == False:\n if file_name is None:\n raise Exception('Filename can''t have blank')\n if base_path is None:\n if file_name.find('~') >= 0:\n src_file = pathlib.Path(file_name).expanduser()\n else:\n src_file = pathlib.Path(file_name).absolute()\n else:\n if base_path.find('~') >= 0:\n src_file = pathlib.Path(base_path).expanduser().joinpath(file_name).absolute()\n else:\n src_file = pathlib.Path(base_path).absolute().joinpath(file_name).absolute()\n if src_file.exists():\n self.name = src_file.name\n self.base_path = src_file.parent.absolute()\n self.content = src_file.read_bytes()\n self._exists = True\n self._size = src_file.stat().st_size\n self.path = src_file.absolute()\n else:\n raise Exception('Invalid file provided')\n else:\n self.name = file_name\n self.base_path = base_path\n self._exists = False\n self._size = 0\n self.path = pathlib.Path()\n self.content = None\n self.os = os\n\n def name():\n doc = \"Full name of file\"\n def fget(self):\n return self._name\n def fset(self, value):\n self._name = validFileName(value, initCap=False).decode() if type(validFileName(value, initCap=False)) != str else validFileName(value, initCap=False)\n self._base_name = value[0:value.rindex('.')]\n self._ext = value[(value.rindex('.')+1):]\n def fdel(self):\n del self._name\n return locals()\n name = property(**name())\n\n def base_name():\n doc = \"First part of filename which appears just before the last dot\"\n def fget(self):\n return self._base_name\n return locals()\n base_name = property(**base_name())\n\n def ext():\n doc = \"Second part of filename which appears after the last dot\"\n def fget(self):\n return self._ext\n return locals()\n ext = property(**ext())\n\n def base_path():\n doc = \"A valid directory location else None\"\n def fget(self):\n return self._base_path\n def fset(self, value):\n self._base_path = value if pathlib.os.path.exists(value) else None\n def fdel(self):\n del self._base_path\n return locals()\n base_path = property(**base_path())\n\n def size():\n doc = \"Size of the file on local file system\"\n def fget(self):\n return self._size \n return locals()\n size = property(**size())\n\n def content():\n doc = \"Content of the file in byte format\"\n def fget(self):\n return self._content\n def fset(self, value):\n self._content = value\n def fdel(self):\n del self._content\n return locals()\n content = property(**content())\n\n def exists():\n doc = \"Returns True if file exists else False\"\n def fget(self):\n return self._exists\n return locals()\n exists = property(**exists())\n\n def copy(self, destination, force=False, create_path=False):\n \"\"\"Copy file to new location passed as param. If file already exists and force param is True, it will overwrite the destination file else will return with no operation.\n\n Args:\n destination (str): The target location where file needs to be copied\n force (bool): If set to True, it will overwrite the file in destination\n create_path (bool): create the destination path if not exists\n Returns:\n file_path (pathlib.Path): Returns an instance of :class:`Path` if file copied else None\n \"\"\"\n if destination is not None and destination.find('~') >= 0:\n dest_path = pathlib.Path(destination).expanduser()\n elif destination is not None:\n dest_path = pathlib.Path(destination).absolute()\n else:\n raise Exception('Invalid path provided - {0}'.format(dest_path))\n\n if dest_path.exists():\n if dest_path.is_dir():\n dest_file = dest_path.joinpath(self.name)\n if dest_file.exists() and force == True:\n dest_file.unlink()\n dest_file.write_bytes(self.content)\n return dest_file\n elif dest_file.exists() and force == False:\n return None\n else:\n dest_file.write_bytes(self.content)\n return dest_file\n else:\n dest_file = pathlib.Path(dest_path)\n if force == True:\n dest_file.unlink()\n dest_file.write_bytes(self.content)\n return dest_file\n else:\n return None\n elif create_path == True:\n dest_path = dest_path.mkdir(parents=True)\n dest_file = dest_path.joinpath(self.name)\n dest_file.write_bytes(self.content)\n return dest_file\n else:\n raise Exception('Invalid destination path')\n\n def move(self, destination, force=False, create_path=False):\n \"\"\"Moves the current file to the destination. Please see :meth:`copy` for more information on arguments\n \"\"\"\n new_file = self.copy(destination, force, create_path)\n if new_file is not None:\n if new_file.exists():\n old_file = pathlib.Path(self.base_path).joinpath(self.name)\n self.base_path = new_file.parent.absolute()\n old_file.unlink()\n return new_file\n return None\n\nclass PackageFile(File):\n\n \"\"\"Represents a physical package file in the package management system. This class supports 4 commands...\n\n * copy\n * move\n * extract_to\n \"\"\"\n\n def __init__(self, file_name, create_if_not_exists=False, base_path=None):\n \"\"\"TODO: to be defined1. \"\"\"\n super(PackageFile, self).__init__(file_name, create_if_not_exists, base_path)\n if self.exists:\n if not zipfile.is_zipfile(self.path._str):\n raise Exception('Not a valid zip file')\n\n def extract_to(self, target_path, name_as_sub_folder=True, overwrite=False):\n \"\"\"Extract the contents of package to the specified path\n\n Args:\n target_path (str): path to the lication where package needs to be extracted\n name_as_sub_folder (bool): creates a sub folder under target_path with the same name as package file name before extracting contents. Default value is True\n overwrite (bool): Overwrites the contents if already exists in target location\n \"\"\"\n if target_path is not None and target_path.find('~') >= 0:\n dest_path = pathlib.Path(target_path).expanduser()\n elif target_path is not None:\n dest_path = pathlib.Path(target_path).absolute()\n else:\n raise Exception('Can''t accept blank for destination path')\n if dest_path.exists():\n if name_as_sub_folder==True:\n dest_path = dest_path.joinpath(self.base_name).absolute()\n if not dest_path.exists():\n dest_path.mkdir(parents=True)\n else:\n if overwrite == True:\n for f in dest_path.iterdir():\n if f.is_dir():\n shutil.rmtree(f)\n else:\n f.unlink()\n if len(self.content) > 0:\n file_bytes = io.BytesIO(self.content)\n zippedfile = zipfile.ZipFile(file_bytes)\n zippedfile.extractall(dest_path)\n return dest_path\n else:\n raise Exception('Invalid destination path specified')\n","repo_name":"singajeet/ui_builder","sub_path":"core/io/filesystem.py","file_name":"filesystem.py","file_ext":"py","file_size_in_byte":8802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"25154763374","text":"a, b = input().split()\n\nanswer = 0\nfor i in range(len(b)):\n cnt = 0\n if i + len(a) > len(b):\n break\n for j in range(len(a)):\n if b[i+j] == a[j]:\n cnt += 1\n if answer < cnt:\n answer = cnt\n\nprint(len(a)-answer)","repo_name":"moonsumhi/bj-algorithm","sub_path":"Backjoon/211201/1120.py","file_name":"1120.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"75071876535","text":"from glob import glob\nfrom subprocess import check_call \nimport os\nimport sys\nfrom pbr.base import _get_output\n\n\nrun_first_t1 = '/data/henry6/gina/henrylab_utils/first_t1_input.py'\n\n#import list with mseIDs\nmse_list = sys.argv[1:][0]\n\n\n# open the file passed as args.MSEID as f, strips off empty lines and /n in the txt file of mseids\nwith open(mse_list) as f:\n print(mse_list)\n mseid_list = list([x.strip() for x in f.readlines()])\n print(mseid_list)\n\n # iterate through each mseid in the file and run pbr first workflow\n for mseid in mseid_list:\n #mseid = 'mse{}'.format(mseid) #put \"mse\" if file does not contain mse<> in cell, because this is needed\n\n\n #check for each mseID if folder with bias field corrected images exists in PBR, if not, make a new folder\n #run N4 bias field correction algorithm from ants\n pbr_folder = glob('{0}/{1}/'.format(_get_output(mseid), mseid))\n N4corr = pbr_folder[0] + '/N4corr'\n nii = pbr_folder[0] + \"/nii\"\n if not (os.path.exists(N4corr)):\n\t os.mkdir(N4corr)\n\n t1_file = glob('{0}/{1}/nii/*BRAVO_IRSPGR_fa8_ti600.nii.gz'.format(_get_output(mseid), mseid))\n if t1_file:\n t1_N4corr = t1_file[0].replace('.nii','_N4corr.nii')\n cmd = ['N4BiasFieldCorrection', '-i', t1_file[0],'-o', t1_N4corr]\n check_call(cmd)\n else:\n print(\"missing {}\" .format(mseid))\n\n cmd = ['python', run_first_t1, '-i', t1_N4corr ]\n #cmd = ['pbr', mseid, '-w', 'first', '-R'] #needs [0] as check_call does not take a list, therefore now it takes the first img and T1\n print(cmd)\n check_call(cmd)\n\n\n\n\n\n\n\n\n \n\n\n","repo_name":"ginakirkish/henrylab_scripts","sub_path":"antje_transition/oppera_first_antje.py","file_name":"oppera_first_antje.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"33770101781","text":"# coding=utf-8\n\n\"\"\"\n Girdiğimiz bir sayıya kadar ki asal olan bütün sayıları listeleme\n\"\"\"\n\ndeger = int(input(\"Kaça kadar ki asal sayıları arıyorsunuz? : \"))\nasal = []\n\nfor i in range(2, deger):\n flag = False\n for j in range(2, i):\n if i % j == 0:\n flag = True\n break\n if not flag:\n asal.append(i)\n\nfor i in asal:\n print(i)\n\nprint(\"\\n0 - {} arasında toplam {} tane asal sayı vardır.\".format(deger, len(asal)))\n","repo_name":"aydinnyunus/Python-Kodlari","sub_path":"Asal Sayılar.py","file_name":"Asal Sayılar.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"tr","doc_type":"code","stars":18,"dataset":"github-code","pt":"22"} +{"seq_id":"7039875664","text":"import yfinance as yf\nimport numpy as np\nimport pandas as pd\nfrom . import utils\n\n\ndef ensureNormal ( df, **kwargs ):\n\tif kwargs.get('isLog',True):\n\t\t# print(\"transforming\")\n\t\tdx = np.diff(np.log(df))\n\telse:\n\t\t# print('skipping')\n\t\tdx = df\n\treturn dx\n\n\ndef basketVariance ( samples, weights, **kwargs ):\n\t\"\"\"Returns the variance a basket, weighted by 'weights'.\n\t\n\t'samples' should have shape (k,n) for k variables with n samples each.\n\t'weights' should be vector of shape (k,)\n\t\"\"\"\n\t# Covariance matrix\n\tc = np.cov ( ensureNormal(samples, **kwargs) )\n\t# Sum down to variance\n\tx = (weights.T @ c) @ weights.T\n\treturn x\n\t\n\t\n\t\n\t\ndef minimumVariance ( samples, **kwargs ):\n\t\"\"\"Returns the weights that minimize the variance among all baskets.\n\t\n\tLet samples have shape (k,n) as usual. K variables, n samples.\n\t\"\"\"\n\tdx = ensureNormal(samples,**kwargs)\n\tcov = np.cov(dx)\n\tx = np.linalg.inv (\n\t\tcov\n\t) @ np.ones ( samples.shape[0] )\n\treturn x / np.linalg.norm(x, ord=1)\n\n\n\n\ndef minVarHedgeRatio ( df1, df2, **kwargs ): \n\t\"\"\"Computes a simple minimum-variance hedge ratio.\n\t\n\tProvide 2 pandas series, df1 & df2,\n\t\tand I will provide the ratio units allocated in df2 to hedge each unit of df1\n\t\"\"\"\n\tdf1 = ensureNormal(df1, **kwargs)\n\tdf2 = ensureNormal(df2, **kwargs)\n\t\n#\t print(df1.shape, df2.shape)\n\t\n\ty = np.concatenate( [df1.reshape(-1,1),df2.reshape(-1,1)], axis=1 )\n#\t print(y.shape)\n\tx = minimumVariance ( y.T, isLog=False )\n#\t print(\"Min var allocs:\", x)\n\tr = x[1] / x[0]\n#\t print(\"Hedge ratio found:\",r)\n\treturn r\n\t\n\n\t\ndef singleHedgeAnalyze ( df1, df2, **kwargs ):\n\t\"\"\"Given two pd.Series objects,\n\tcompute the hedge ratio, and variance improvement information.\n\tReturns dictionary\n\t\"\"\"\n\t# Compute hedge ratio\n\tratio = minVarHedgeRatio( df1, df2, **kwargs )\n\tleverage = 1 + ratio\n\t\n\t# Simulated portfolio weights\n\twRaw = np.array([1.0, 0])\n\twHdg = np.array([1.0, ratio])\n\twHdgAdj = wHdg / np.abs(np.sum(wHdg))\n\t\n\t# Create portfolio universe, and test the variance\n\tdfx = np.concatenate([df1.reshape(-1,1),df2.reshape(-1,1)],axis=1).T\n\t\n\t# Variance of single-asset\n\tvarRaw = basketVariance(dfx, wRaw, **kwargs)\n\t# Variance of portfolio with single asset,\n\t# adding in the hedge asset\n\tvarHdg = basketVariance(dfx, wHdg, **kwargs)\n\t# Variance of varHdg, but adjusted\n\t# so position net size equals single-asset portfolio\n\tadjVarHdg = basketVariance(dfx, wHdgAdj, **kwargs)\n\t\n\tif kwargs.get('verbose',True):\n\t\tprint(\n\t\t\t'{:.1f}% variance improvement'.format(\n\t\t\t\t100*(varRaw - varHdg) / varRaw\n\t\t\t)\n\t\t)\n\t\tprint(\n\t\t\t'{:.1f}% variance improvement, for same-size portfolio'.format(\n\t\t\t\t100*(varRaw - adjVarHdg) / varRaw\n\t\t\t)\n\t\t)\n\treturn {\n\t\t'hedge ratio': ratio,\n\t\t'leverage': leverage,\n\t\t'net': 'short' if leverage < 0 else 'long',\n\t\t'hedge': {\n\t\t\t'weights': wHdg,\n\t\t\t'variance': varHdg,\n\t\t\t'adjusted variance': adjVarHdg,\n\t\t},\n\t\t'unhedged': {\n\t\t\t'weights': wRaw,\n\t\t\t'variance': varRaw,\n\t\t},\n\t}\n\n\n\n\ndef basketHedgeAnalyze ( df, positions, **kwargs):\n\t\"\"\"Construct some additional set of positions to hedge a given set of positions.\n\tdf -> pd.DataFrame, price timeseries\n\tpositions-> pd.Series, index is position, value is size in $$$\n\t\"\"\"\n\thdgSyms = [ x for x in df.columns if x not in positions.index ]\n\t\n\t# Stopping conditions\n\tif len(hdgSyms) == 0 or len(positions) == 0:\n\t\treturn positions\n\t\n\tdata = ensureNormal(df.values.T, **kwargs).T\n\t# index = df.index[:-1] if data.shape[1] != df.values.shape[1] else df.index\n\tdf = pd.DataFrame(\n\t\tdata = data,\n\t\tcolumns = df.columns,\n\t\tindex = df.index[:data.shape[0]]\n\t)\n\tk = {\n\t\t'isLog': False,\n\t\t'verbose': kwargs.get('verbose'),\n\t}\n\n\toldVar = basketVariance (\n\t\tdf[positions.index.tolist()].values.T,\n\t\tpositions.values,\n\t\t**k\n\t)\n\tprint( 'old variance:', oldVar )\n\t\n\tnetSize = np.abs(positions.sum())\n\n\t# Get the % allocation in each symbol\n\tnormalWeights = positions.values.reshape(-1,1) / netSize\n\t\n\tportfolio = (df[positions.index.tolist()].values @ normalWeights).flatten()\n\t\n\t# Portfolio net pct-change\n\tportfolio = pd.Series(\n\t\tportfolio,\n\t\tindex = df.index\n\t)\n\t\n\tres = []\n\tfor x in hdgSyms:\n\t\tj = singleHedgeAnalyze(\n\t\t\tportfolio.values,\n\t\t\tdf[x].values,\n\t\t\tisLog=False,\n\t\t\tverbose = kwargs.get('verbose',False)\n\t\t)\n\t\tj['symbol'] = x\n\t\tres.append(j)\n\t\n\t# Get the top value on top\n\tres.sort(key=lambda x: x['hedge']['adjusted variance'])\n\t# print(res[:2])\n\n\tp = positions.append(\n\t\tpd.Series(\n\t\t\t[res[0]['hedge ratio'] * netSize],\n\t\t\tindex=[res[0]['symbol']]\n\t\t)\n\t)\n\tprint(p)\n\tprint('net long: ${:.2f}'.format( p.sum() ))\n\tnewVar = basketVariance (\n\t\tdf[p.index.tolist()].values.T,\n\t\tp.values,\n\t\t**k\n\t)\n\tprint( 'new variance:', newVar )\n\t\n\t\n\tif oldVar > newVar:\n\t\tprint(\"We see improvement. Adding...\")\n\t\treturn basketHedgeAnalyze (df, p, **k)\n\telse:\n\t\tprint(\"No improvement. Terminating.\")\n\t\treturn positions\n\n\n\n\ndef allocSimulator ( sym, N=1000, period='1y', interval='1d', riskFree=0.01 ):\n\n\tdf = yf.download(\n\t\ttickers=sym,\n\t\tperiod=period,\n\t\tinterval=interval,\n\t\tauto_adjust=True\n\t)['Close'][sym]\n\n\tdx = ensureNormal ( df.values.T, isLog = True ).T\n\tdf = pd.DataFrame(\n\t\tdata = dx,\n\t\tcolumns = df.columns,\n\t\tindex = df.index[:dx.shape[0]]\n\t)\n\n\tshape = (len(sym), N)\n\tallocs = np.random.normal(size=shape)**2\n\tallocs = allocs / np.sum(allocs, axis=0)\n\n\tprint(allocs.shape)\n\n\tportfolio = (df.values @ allocs)\n\t# print(portfolio.shape)\n\t# print(df.values.shape)\n\t\n\tvariances = [\n\t\tutils.volAdjust (\n\t\t\tbasketVariance ( df.values.T, x, isLog = False )\n\t\t)\n\t\tfor x in allocs.T\n\t]\n\tmu = portfolio.mean(axis=0)\n\t# print(mu.shape)\n\t# print(mu)\n\tmu = (1 + mu)**252 - 1\n\n\tpriceDf = pd.DataFrame (\n\t\tdata = allocs.T,\n\t\tcolumns = sym\n\t)\n\tpriceDf['var'] = variances\n\tpriceDf['mu'] = mu\n\t\n\tpriceDf['sharpe'] = (priceDf['mu'] - riskFree) / priceDf['var'] **0.5\n\t\n\tpriceDf.sort_values(by=['sharpe'], ascending=False, inplace=True)\n\treturn priceDf\n","repo_name":"alienbrett/rraider","sub_path":"rraider/portfolio.py","file_name":"portfolio.py","file_ext":"py","file_size_in_byte":5793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"29772691758","text":"class Solution:\n def minCost(self, colors: str, neededTime: List[int]) -> int:\n total_time = 0\n streak_color = colors[0] # current color\n max_time = neededTime[0] # max time of the current color\n sum_time = neededTime[0] # sum of time of the current color\n streak = 1 # number of balloons from the current color\n for id_c in range(1, len(colors)):\n c = colors[id_c]\n if c != streak_color: # if color changes\n streak_color = c # new color\n if streak != 1: # if streak was k ballons>=2, remove k-1 ballons with min cost (so sum - max)\n streak = 1\n total_time += sum_time - max_time\n max_time = neededTime[id_c]\n sum_time = neededTime[id_c]\n else: # update the streak\n streak += 1\n max_time = max(max_time, neededTime[id_c])\n sum_time += neededTime[id_c]\n # check the last streak\n if streak != 1:\n streak = 1\n total_time += sum_time - max_time\n return total_time\n","repo_name":"AdrienC21/LeetCode","sub_path":"1578-minimum-time-to-make-rope-colorful/1578-minimum-time-to-make-rope-colorful.py","file_name":"1578-minimum-time-to-make-rope-colorful.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"4318862657","text":"from Crypto.Cipher import AES\nfrom Crypto.Util.Padding import pad, unpad\nfrom shlex import quote\nfrom base64 import b64decode, b64encode\nimport os\nfrom subprocess import Popen, PIPE, DEVNULL\n\n\ndef encrypt(key: bytes, ct: bytes) -> bytes:\n cipher = AES.new(key, AES.MODE_ECB)\n return cipher.encrypt(pad(ct, AES.block_size))\n\n\ndef decrypt(key: bytes, ct: bytes) -> bytes:\n cipher = AES.new(key, AES.MODE_ECB)\n return unpad(cipher.decrypt(ct), AES.block_size)\n\n\nif __name__ == \"__main__\":\n print(\"=\" * 40)\n print(\"Welcome to Encrypted Command Executor\")\n print(\"=\" * 40)\n key = os.urandom(AES.block_size)\n while True:\n print(\"1. Generate an echo command\")\n print(\"2. Generate a ls command\")\n print(\"3. Run an encrypted command\")\n print(\"4. Exit\")\n choice = input(\"> \")\n if choice == \"1\":\n msg = input(\"Message: \")\n cmd = \"echo %s\" % quote(msg)\n print(\"result:\", b64encode(encrypt(key, cmd.encode())).decode())\n elif choice == \"2\":\n directory = input(\"Directory: \")\n cmd = \"ls -- %s\" % quote(directory)\n print(\"result:\", b64encode(encrypt(key, cmd.encode())).decode())\n elif choice == \"3\":\n ct = input(\"Encrypted command: \")\n cmd = decrypt(key, b64decode(ct))\n proc = Popen(\n cmd.decode(), stdin=DEVNULL, stdout=PIPE, stderr=DEVNULL, shell=True\n )\n stdout, _ = proc.communicate()\n print(\"result:\", b64encode(encrypt(key, stdout)).decode())\n elif choice == \"4\":\n exit()\n","repo_name":"maple3142/My-CTF-Challenges","sub_path":"ImaginaryCTF/Round 35/Encrypted Command Executor/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"22"} +{"seq_id":"12807701034","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 11 01:03:27 2018\r\n\r\n@author: Ayberk Yaraneri\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\nclass Point(object):\r\n def __init__(self, x, y, z):\r\n self.x = x\r\n self.y = y\r\n self.z = z\r\n\r\n def __str__(self):\r\n return '(' + str(self.x) + ', ' + str(self.y) + ', ' + str(self.z) + ')'\r\n\r\n def getX(self):\r\n return self.x\r\n\r\n def getY(self):\r\n return self.y\r\n\r\n def getZ(self):\r\n return self.z\r\n\r\n def setX(self, x):\r\n self.x = x\r\n\r\n def setY(self, y):\r\n self.y = y\r\n\r\n def setZ(self, z):\r\n self.z = z\r\n\r\n def getCoord(self):\r\n return (self.x, self.y, self.z)\r\n\r\n def distance(self, other):\r\n return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2 + (self.z - other.z)**2)\r\n\r\n def move(self, deltaX=0, deltaY=0, deltaZ=0):\r\n self.x += deltaX\r\n self.y += deltaY\r\n self.z += deltaZ\r\n\r\nclass Airfoil(object):\r\n def __init__(self, filename):\r\n self.filename = filename\r\n self.airfoil_name = ''\r\n self.points = []\r\n self.midPoint = Point(0.5, 0, 0)\r\n self.twist = 0\r\n self.chord = 1\r\n\r\n try:\r\n origin = open(self.filename, 'r')\r\n except IOError:\r\n print(\"Couldn't open file or files.\")\r\n else:\r\n point_list = origin.read().split('\\n')\r\n\r\n self.airfoil_name = point_list[0]\r\n\r\n for point in point_list[1:]:\r\n coordinates = point.split()\r\n if len(coordinates):\r\n self.points.append(Point(float(coordinates[0]), float(coordinates[1]), 0.0))\r\n\r\n print('Airfoil imported successfully.')\r\n\r\n def set_airfoil_name(self, airfoil_name):\r\n self.airfoil_name = airfoil_name\r\n\r\n def addPoint(self, x, y, z, index):\r\n \"\"\"\r\n x, y, z = coordinates of point to be added\r\n index = index at which the new point will be\r\n \"\"\"\r\n point = Point(x, y, z)\r\n leftSplit = self.points[:index]\r\n rightSplit = self.points[(index + 1):]\r\n\r\n self.points = (leftSplit + [point] + rightSplit)\r\n\r\n def changeTwist(self, theta):\r\n \"\"\"\r\n Rotates airfoil around midPoint by theta degrees.\r\n theta: a float\r\n \"\"\"\r\n self.twist = theta\r\n\r\n for point in self.points:\r\n x = point.getX()\r\n y = point.getY()\r\n\r\n alpha = math.degrees(math.atan2((y - self.midPoint.getY()), (x - self.midPoint.getX())))\r\n hypotenuse_length = point.distance(self.midPoint)\r\n\r\n newY = math.sin(math.radians(alpha + self.twist)) * hypotenuse_length\r\n newX = math.cos(math.radians(alpha + self.twist)) * hypotenuse_length\r\n\r\n point.setX(newX + self.midPoint.getX())\r\n point.setY(newY + self.midPoint.getY())\r\n\r\n def moveAirfoil(self, deltaX=0, deltaY=0, deltaZ=0):\r\n self.midPoint.move(deltaX, deltaY, deltaZ)\r\n for point in self.points:\r\n point.move(deltaX, deltaY, deltaZ)\r\n\r\n def scaleAirfoil(self, scaleFactor):\r\n for point in self.points:\r\n x = point.getX()\r\n y = point.getY()\r\n\r\n point.setX(((x - self.midPoint.getX()) * scaleFactor) + self.midPoint.getX())\r\n point.setY(((y - self.midPoint.getY()) * scaleFactor) + self.midPoint.getY())\r\n\r\n def addSlot(self, xPos, yPos, r):\r\n \"\"\"\r\n ONLY WORKS WHEN TWIST = 0 !!!\r\n Adds a circular slot for a carbon fiber tube in the airfoil.\r\n xPos and yPos = coordinates of the center of the slot relative to the airfoil's midPoint\r\n r = radius of slot\r\n \"\"\"\r\n if self.twist != 0:\r\n print('Twist angle not zero! Cannot add slot.')\r\n else:\r\n slotPoints = []\r\n numPoints = len(self.points)\r\n\r\n for i in range(numPoints//2, numPoints):\r\n xVal = self.points[i].getX()\r\n if xVal > xPos:\r\n p2 = self.points[i]\r\n p2_index = i\r\n p1 = self.points[(i-1)]\r\n break\r\n\r\n x1, y1 = p1.getX(), p1.getY()\r\n x2, y2 = p2.getX(), p2.getY()\r\n\r\n p = xPos\r\n q = (y1 + y2)/2\r\n\r\n slotStart = Point(p, q, 0.0)\r\n slotPoints.append(slotStart)\r\n\r\n circleStart = Point(xPos, (yPos - r), 0.0)\r\n slotPoints.append(circleStart)\r\n\r\n theta = 270\r\n for i in range(60):\r\n theta -= 6\r\n theta_r = math.radians(theta)\r\n\r\n newY = (math.sin(theta_r) * r) + yPos\r\n newX = (math.cos(theta_r) * r) + xPos\r\n\r\n slotPoints.append(Point(newX, newY, 0.0))\r\n\r\n slotPoints.append(slotStart)\r\n\r\n leftSplit = self.points[:p2_index]\r\n rightSplit = self.points[(p2_index + 1):]\r\n\r\n self.points = (leftSplit + slotPoints + rightSplit)\r\n\r\n def plotAirfoil(self):\r\n xVals = []\r\n yVals = []\r\n\r\n for point in self.points:\r\n xVals.append(point.getX())\r\n yVals.append(point.getY())\r\n\r\n plt.figure('plot1')\r\n plt.plot(xVals, yVals, 'r-', label = self.airfoil_name + ' twist:' + str(self.twist), linewidth = 0.5)\r\n plt.legend(loc = 'upper left')\r\n plt.ylim(-1, 1)\r\n plt.xlim(-1, 1)\r\n plt.axvline(self.midPoint.getX(), color = 'r', linewidth = 0.2)\r\n plt.axhline(self.midPoint.getY(), color = 'r', linewidth = 0.2)\r\n plt.show()\r\n\r\n def exportAirfoil(self, newFileName):\r\n try:\r\n output = open(newFileName, 'w')\r\n except IOError:\r\n print(\"Couldn't open file or files.\")\r\n else:\r\n for point in self.points:\r\n output.write(str.format('{0:.6f}', float(point.getX())) + '\\t')\r\n output.write(str.format('{0:.6f}', float(point.getX())) + '\\t')\r\n output.write('0.000000\\n')\r\n\r\n print(\"Airofil exported successfully as: \" + newFileName)\r\n\r\n def __str__(self):\r\n return self.airfoil_name + ' twist:' + str(self.twist)\r\n\r\n\r\n\r\n\r\n###################################################################################################################################\r\n# INTERFACING #\r\n###################################################################################################################################\r\nprint(\"~Welcome to Airfoil_Converter_V2.0!~\")\r\n\r\nimported = False\r\n\r\nwhile True:\r\n\r\n command = input(\">\")\r\n\r\n if command == 'help' or command == 'h':\r\n print('\\n')\r\n print(\"Available Commands:\")\r\n print(\"import, move, scale, twist, plot, export, exit\")\r\n print('\\n')\r\n\r\n elif command == 'import':\r\n if imported:\r\n print('Airfoil already imported!')\r\n else:\r\n filename = input('enter filename:')\r\n imported = True\r\n airfoil1 = Airfoil(filename)\r\n\r\n elif command == 'move':\r\n if not imported:\r\n print('No airfoil avilable!')\r\n\r\n else:\r\n x = float(input(\"x:\"))\r\n y = float(input(\"y:\"))\r\n airfoil1.moveAirfoil(x, y)\r\n\r\n elif command == 'scale':\r\n if not imported:\r\n print('No airfoil available!')\r\n\r\n else:\r\n factor = float(input(\"factor:\"))\r\n airfoil1.scaleAirfoil(factor)\r\n\r\n elif command == 'twist':\r\n if not imported:\r\n print(\"No airfoil available!\")\r\n\r\n else:\r\n degrees = float(input('degrees:'))\r\n airfoil1.changeTwist(degrees)\r\n\r\n elif command == 'plot':\r\n if not imported:\r\n print('No airfoil available!')\r\n\r\n else:\r\n airfoil1.plotAirfoil()\r\n\r\n elif command == 'export':\r\n if not imported:\r\n print('No airfoil avaliable!')\r\n\r\n else:\r\n newFileName = input(\"File name to export as: \")\r\n airfoil1.exportAirfoil(newFileName)\r\n\r\n elif command == 'exit':\r\n break\r\n\r\n else:\r\n print(\"Invalid Command\")\r\n\r\n\r\n\r\n\r\n\"\"\"\r\nairfoil1 = Airfoil('clarky.dat')\r\n\r\nairfoil1.moveAirfoil(-0.5, 0.5)\r\n\r\n\r\nairfoil1.moveAirfoil(0, -0.5)\r\n\r\n# airfoil1.addPoint(0, 0, 0, 55)\r\n\r\nairfoil1.addSlot(-0.3, 0.03, 0.02)\r\nairfoil1.addSlot(-0.15, 0.03, 0.02)\r\n\r\nairfoil1.moveAirfoil(1.0, 0)\r\n\r\nairfoil1.addSlot(0.15, 0.03, 0.02)\r\n\r\n# airfoil1.changeTwist(25)\r\n\r\n\r\nairfoil1.plotAirfoil()\r\n\"\"\"\r\n","repo_name":"AyberkY/airfoil_converter_v2","sub_path":"airfoil_converter_v2.py","file_name":"airfoil_converter_v2.py","file_ext":"py","file_size_in_byte":8664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"42869443647","text":"import sys\nimport os\nimport SimpleITK as sitk\nimport numpy as np\nfrom tqdm import tqdm\n\n\n\ndef post_process(label,n):\n from skimage.morphology import remove_small_objects\n\n final= np.zeros_like(label,dtype=np.uint8)\n for i in range(1,n):\n roi = (label == i).astype(np.bool)\n roi = remove_small_objects(roi,min_size=64, connectivity=1,in_place=False)\n final[roi == 1] = i\n return final\n\n\n# part10_path = './result/Spine/v4.3-all/Part_10/fusion/'\n# part9_path = './result/Spine/v4.3-all/Part_9/fusion/'\n# save_folder = './result/Spine/v4.3-all/segmentation_results/'\n\n# part10_path = './result/Spine/v4.10-balance/Part_10/fusion/'\n# part9_path = './result/Spine/v4.10-balance/Part_9/fusion/'\n# save_folder = './result/Spine/v4.10-balance/segmentation_results/'\n\n# part10_path = './result/Spine/v4.3-balance/Part_10/fusion/'\n# part9_path = './result/Spine/v4.3-balance/Part_9/fusion/'\n# save_folder = './result/Spine/v4.3-balance/segmentation_results/'\n\nversion_list = ['v4.3-balance','v4.3-all','v4.10-balance','final']\n\nfor ver in version_list:\n part10_path = './post_result/Spine/{}/Part_10/weighted_fusion/'.format(ver)\n part9_path = './post_result/Spine/{}/Part_9/weighted_fusion/'.format(ver)\n save_folder = './post_result/Spine/{}/weighted_segmentation_results/'.format(ver)\n\n # part10_path = './result/Spine/{}/Part_10/fusion/'.format(ver)\n # part9_path = './result/Spine/{}/Part_9/fusion/'.format(ver)\n # save_folder = './result/Spine/{}/segmentation_results/'.format(ver)\n POST = True\n\n if not os.path.exists(save_folder):\n os.makedirs(save_folder)\n\n\n for part10_item in tqdm(os.scandir(part10_path)):\n part10_data = sitk.ReadImage(part10_item.path)\n part10_label = sitk.GetArrayFromImage(part10_data).astype(np.uint8)\n \n spacing = part10_data.GetSpacing()\n origin = part10_data.GetOrigin()\n direction = part10_data.GetDirection()\n\n final_label = np.zeros_like(part10_label,dtype=np.uint8)\n\n part9_item_path = os.path.join(part9_path,part10_item.name)\n part9_data = sitk.ReadImage(part9_item_path)\n part9_label = sitk.GetArrayFromImage(part9_data).astype(np.uint8)\n\n roi = 1\n for i in range(1,11):\n final_label[part10_label == i] = roi\n roi += 1\n \n for i in range(1,10):\n final_label[part9_label == i] = roi\n roi += 1\n \n if POST:\n for i in range(final_label.shape[0]):\n final_label[i] = post_process(final_label[i],20)\n\n sitk_data = sitk.GetImageFromArray(final_label)\n sitk_data.SetSpacing(spacing)\n sitk_data.SetOrigin(origin)\n sitk_data.SetDirection(direction)\n \n save_path = os.path.join(save_folder,part10_item.name)\n sitk.WriteImage(sitk_data, save_path)\n","repo_name":"shijun18/Spine_Seg","sub_path":"prepare_submission.py","file_name":"prepare_submission.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"34600265200","text":"def diamond(n):\n if n <= 0 or n % 2 == 0:\n return None\n counter = 1\n result = \"\"\n while counter <= n:\n n_spaces = (int((n-counter)/2))\n if counter != n:\n result += \" \" * n_spaces\n result += \"*\" * counter + \"\\n\"\n counter += 2\n counter -= 4\n while counter >= 1:\n n_spaces = (int((n-counter)/2))\n result += \" \" * n_spaces\n result += \"*\" * counter + \"\\n\"\n counter -= 2\n return result\n\nprint(diamond(5))","repo_name":"Stuart-McCafferty/Codewars","sub_path":"6kyu/give_me_a_diamond.py","file_name":"give_me_a_diamond.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"74916864056","text":"#!/usr/bin/python\n\nimport sys\nimport fnmatch\nimport os\nimport glob\nimport shutil\nimport argparse\nimport time\nimport pylab as pl\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\n\ncurrentdir = os.getcwd()\n\nparser = argparse.ArgumentParser(description='Visualizes already\\\ncomputed benchmarks from F4RT.')\nparser.add_argument('-d', '--directory', required=True,\n help='Directory where the benchmark file is included.')\n\nargs = parser.parse_args()\n\n# list of all methods\nmethods = ['Raw sequential','Open MP collapse(1)','Open MP collapse(2)',\n'Intel TBB 1D auto partitioner','Intel TBB 1D affinity partitioner',\n'Intel TBB 1D simple partitioner','Intel TBB 2D auto partitioner',\n'Intel TBB 2D affinity partitioner','Intel TBB 2D simple partitioner']\n\n# lists for all methods we have, those are lists of lists:\n# E.g. time_series[i] is a list of len(threads) elements of the timings\n# of methods[i]. \ntime_series = list()\ngflops_series = list()\n\nfor i in range(0,len(methods)):\n time_series.append(list())\n gflops_series.append(list())\n\n# go to directory\nos.chdir(args.directory)\n\nfile_name = ''\n# find bench file\nfor files in glob.glob(\"bench-*\"):\n file_name = files\n\n# read lines of the benchmark files\nf = open(file_name)\n\n# get threads for plot, stored in the first line of bench file\nplot_threads = f.readline().strip().replace(' ','').split(',')\n# for compatibility to the other scripts just store this again\nthreads = plot_threads\nthreads = list(map(lambda x: int(x) - 1, threads))\nlines = f.readlines()\nf.close()\n\n\nfor l in lines:\n for i in range(0,len(methods)): \n if l.find(methods[i]) != -1:\n tmp = i\n if l.find('Real time:') != -1:\n time_series[tmp].append(\\\n l.replace('Real time:','').replace('sec','').strip())\n if l.find('GFLOPS/sec:') != -1:\n # if the value is inf for infinity due to short computation time, we set\n # the GFLOPS value to be -1\n gflops_series[tmp].append(\\\n l.replace('GFLOPS/sec:','').replace('inf','-1').strip())\n\n#plot this data\n\n#line style\ncoloring = ['k^','b-','b--','g-','g--','g:','r-','r--','r:']\n\npl.rc('legend',**{'fontsize':5})\nfig = pl.figure()\nax = fig.add_subplot(111)\nfig.suptitle('Timings: '+file_name, fontsize=10)\nax.set_xlabel('Number of threads', fontsize=8)\nax.set_ylabel('Real time in seconds', fontsize=8)\n\n#pl.grid(True)\n\nax = pl.gca() \n\ngroup_labels = plot_threads\n\n#ax.set_xticklabels(group_labels)\nthreads_tmp = range(0,len(plot_threads))\n# get right scale for a4 paper size\nscale_tmp = 38 / (len(plot_threads)) \nthreads = range(0,38,scale_tmp)\ntick_lbs = plot_threads\nax.xaxis.set_ticks(threads)\nax.xaxis.set_ticklabels(tick_lbs)\n\np = [None]*len(methods)\nfor i in range(0,len(methods)):\n p[i], = ax.plot(threads[0:len(time_series[i])], time_series[i], coloring[i], label=i)\n# set 0 as min value for y and 1 as min value for x (threads)\n#pl.xlim(xmin=1)\npl.ylim(ymin=0)\nax.legend((methods),'upper right', shadow=True, fancybox=True)\n\n# take real time of sequential computation to figure out the \n# granularity of the yaxis\ntmp_ticks = ax.yaxis.get_majorticklocs()\ngranu = tmp_ticks[len(tmp_ticks)-1] / (len(tmp_ticks)-1) / 5\nax.yaxis.set_minor_locator(MultipleLocator(granu))\npl.tick_params(axis='both', which='major', labelsize=6)\npl.tick_params(axis='both', which='minor', labelsize=6)\n\npl.savefig('timings-plot.pdf',papertype='a4',orientation='landscape')\n\nfig = pl.figure()\nax = fig.add_subplot(111)\nfig.suptitle('GFLOPS/sec: '+file_name, fontsize=10)\nax.set_xlabel('Number of threads', fontsize=8)\nax.set_ylabel('GFLOPS per second', fontsize=8)\n\nax = pl.gca() \n\n#ax.set_xticklabels(group_labels)\nthreads_tmp = range(0,len(plot_threads))\n# get right scale for a4 paper size\nscale_tmp = 38 / (len(plot_threads)) \nthreads = range(0,38,scale_tmp)\ntick_lbs = plot_threads\nax.xaxis.set_ticks(threads)\nax.xaxis.set_ticklabels(tick_lbs)\n\np = [None]*len(methods)\nfor i in range(0,len(methods)):\n p[i], = ax.plot(threads[0:len(gflops_series[i])], gflops_series[i],coloring[i], label=i)\n# set 0 as min value for y and 1 as min value for x (threads)\n#pl.xlim(xmin=1)\npl.ylim(ymin=0)\nax.legend((methods),'upper left', shadow=True, fancybox=True)\n\n# take gflops of best computation to figure out the \n# granularity of the yaxis\ntmp_ticks = ax.yaxis.get_majorticklocs()\n# note that here \"abs()\" is needed since if computations are too fast we\n# set GFLOPS to -1 instead of infinity. Since the MultipleLocator must\n# be set to a positive integer value, we have to take care of this case.\ngranu = abs(tmp_ticks[len(tmp_ticks)-1]) / (len(tmp_ticks)-1) / 5\nax.yaxis.set_minor_locator(MultipleLocator(granu))\n\npl.tick_params(axis='both', which='major', labelsize=6)\npl.tick_params(axis='both', which='minor', labelsize=6)\n\npl.savefig('gflops-plot.pdf',papertype='a4',orientation='landscape')\n","repo_name":"ederc/LA-BENCHER","sub_path":"scripts/plot_old.py","file_name":"plot_old.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"22"} +{"seq_id":"23010311424","text":"from logging import INFO\r\nfrom search_engine import searcher\r\nfrom search_engine.search_engine import SearchEngine\r\nfrom utils.types import SearchResults\r\nfrom flask import Flask, render_template, jsonify\r\nimport logging\r\n\r\n\r\nlogging.basicConfig(level=INFO)\r\nse: SearchEngine = searcher\r\n\r\ncolumns = [\r\n {\r\n \"field\": \"id\", # which is the field's name of data key\r\n \"title\": \"id\", # display as the table header's name\r\n \"sortable\": True,\r\n },\r\n {\r\n \"field\": \"text\",\r\n \"title\": \"text\",\r\n \"sortable\": False,\r\n },\r\n]\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route(\"/search\")\r\n@app.route(\"/search/\")\r\ndef search(query=None):\r\n if not query:\r\n return render_template(\"search.html\", data=[], columns=columns)\r\n app.logger.info(f\"got query: {query}\")\r\n items: SearchResults = se.search(query)\r\n app.logger.info(f\"got data {items}\")\r\n return jsonify(items)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host=\"0.0.0.0\", debug=False)\r\n","repo_name":"helmanofer/semantic_search","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"32170041187","text":"from trytond.model import ModelSQL, ModelView, fields, DictSchemaMixin\nfrom trytond.pool import PoolMeta\nfrom trytond.pyson import Eval\n\n\nclass LotAttributeType(ModelSQL, ModelView):\n 'Lot Attribute Type'\n __name__ = 'stock.lot.attribute.type'\n\n name = fields.Char('Name', required=True)\n attributes = fields.One2Many('stock.lot.attribute', 'type',\n 'Attributes')\n\n\nclass LotAttribute(DictSchemaMixin, ModelSQL, ModelView):\n 'Lot Attribute'\n __name__ = 'stock.lot.attribute'\n _rec_name = 'name'\n\n type = fields.Many2One('stock.lot.attribute.type', 'Type',\n required=True, ondelete='CASCADE', select=True)\n\n @staticmethod\n def default_type_():\n return 'char'\n\n\nclass ProductCategory(metaclass=PoolMeta):\n __name__ = 'product.category'\n\n lot_attribute_types = fields.Many2Many(\n 'product.category-stock.lot.attribute.type',\n 'category', 'attribute_type', 'Lot Attribute Types')\n\n\nclass ProductCategoryLotAttributeType(ModelSQL):\n 'Product Category - Lot Attribute Type'\n __name__ = 'product.category-stock.lot.attribute.type'\n _table = 'product_category_stock_lot_attribute_type'\n\n category = fields.Many2One('product.category',\n 'Product Category', required=True, ondelete='CASCADE', select=True)\n attribute_type = fields.Many2One('stock.lot.attribute.type',\n 'Lot Attribute Type', required=True, ondelete='CASCADE', select=True)\n\n\nclass Lot(metaclass=PoolMeta):\n __name__ = 'stock.lot'\n\n attributes = fields.Dict('stock.lot.attribute', 'Attributes',\n domain=[('type', 'in', Eval('attribute_types_domain'))],\n depends=['attribute_types_domain'])\n attributes_string = attributes.translated('attributes')\n attribute_types_domain = fields.Function(fields.Many2Many(\n 'stock.lot.attribute.type', None, None, 'Attribute Types domain'),\n 'on_change_with_attribute_types_domain')\n\n @fields.depends('product', '_parent_product.template')\n def on_change_with_attribute_types_domain(self, name=None):\n a_types = []\n if self.product and self.product.template.categories:\n for cat in self.product.template.categories:\n for a_type in cat.lot_attribute_types:\n a_types.append(a_type.id)\n return a_types\n\n\nclass Move(metaclass=PoolMeta):\n __name__ = 'stock.move'\n\n @classmethod\n def _get_origin(cls):\n models = super()._get_origin()\n models.append('lims.analysis_sheet')\n return models\n","repo_name":"Kalenis/kalenislims","sub_path":"lims_analysis_sheet_stock/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"22"} +{"seq_id":"11111927636","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\n\nfrom .forms import (\n PessoaForm, \n VeiculoForm, \n MovRotativoForm, \n MensalistaForm,\n MovMensalistaForm,\n)\nfrom .models import (\n Pessoa, \n Veiculo, \n MovRotativo, \n Mensalista, \n MovMensalista, \n)\n\ndef home(request):\n context = {'mensagem': 'Ola novamente'}\n return render(request, 'core/index.html', context)\n\n# OS METODOS ABAIXO RETORNA PESSOA/ATUALIZA/DELETA\n\n@login_required\ndef lista_pessoas(request):\n pessoas = Pessoa.objects.all()\n forms = PessoaForm()\n data = {'pessoas': pessoas, 'forms': forms} \n return render(request, 'core/lista_pessoas.html', data)\n\n@login_required\ndef pessoas_novas(request):\n form = PessoaForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('core_lista_pessoas')\n\n@login_required\ndef pessoa_update(request, id):\n data = {}\n pessoa = Pessoa.objects.get(id=id)\n form = PessoaForm(request.POST or None, instance=pessoa)\n data['pessoa'] = pessoa\n data['form'] = form\n\n if request.method == 'POST' and form.is_valid():\n #if form.is_valid():\n form.save()\n return redirect('core_lista_pessoas')\n else:\n return render(request, 'core/pessoa_update.html', data)\n\n@login_required\ndef pessoa_delete(request, id):\n pessoa = Pessoa.objects.get(id=id)\n if request.method == 'POST':\n pessoa.delete()\n return redirect('core_lista_pessoas')\n else:\n return render(request, 'core/pessoaconfirme_delete.html', {'pessoa': pessoa})\n# OS METODOS ABAIXO RETORNA VEICULOS/ATUALIZA/DELETA\n\n@login_required\ndef lista_veiculos(request): \n veiculos = Veiculo.objects.all()\n forms = VeiculoForm()\n data = {'veiculo': veiculos, 'forms': forms}\n return render(request, 'core/lista_veiculos.html', data)\n\n@login_required\ndef novo_veiculo(request):\n form = VeiculoForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('core_lista_veiculos')\n\n@login_required\ndef veiculo_update(request, id):\n data = {}\n veiculo = Veiculo.objects.get(id=id)\n form = VeiculoForm(request.POST or None, instance=veiculo) \n data['veiculo'] = veiculo\n data['form'] = form\n\n if request.method == 'POST':\n form.save()\n return redirect('core_lista_veiculos') \n else:\n return render(request, 'core/veiculo_update.html', data)\n\n@login_required\ndef veiculo_delete(request, id):\n veiculo = Veiculo.objects.get(id=id)\n if request.method == 'POST':\n veiculo.delete()\n return redirect('core_lista_veiculos')\n else:\n return render(request, 'core/veiculoconfirme_delete.html', {'veiculo': veiculo})\n\n# OS METODOS ABAIXO RETORNA OS MOVIMENTOS ROTATIVOS/ATUALIZA/CADASTRA/DELETA\n\n@login_required\ndef lista_movrotativo(request):\n movimentos = MovRotativo.objects.all()\n forms = MovRotativoForm()\n data = {'movimentos': movimentos, 'forms': forms}\n return render(request, 'core/lista_movrotativo.html', data)\n\n@login_required\ndef novo_rotativo(request):\n form = MovRotativoForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('core_lista_movrotativos')\n\n@login_required\ndef movrotativo_update(request, id):\n data = {}\n movrotativo = MovRotativo.objects.get(id=id)\n form = MovRotativoForm(request.POST or None, instance=movrotativo) \n data['movrotativo'] = movrotativo\n data['form'] = form\n\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n return redirect('core_lista_movrotativos') \n else:\n return render(request, 'core/movrotativo_update.html', data)\n\n@login_required\ndef movrotativo_delete(request, id):\n movrotativo = MovRotativo.objects.get(id=id)\n if request.method == 'POST':\n movrotativo.delete()\n return redirect('core_lista_movrotativos')\n else:\n return render(request, 'core/mvrotconfirme_delete.html', {'movrotativo': movrotativo})\n\n\n# OS METODOS ABAIXO RETORNA OS MENSALISTAS/ATUALIZA/CADASTRA/DELETA\n\n@login_required\ndef lista_mensalistas(request):\n mensalistas = Mensalista.objects.all()\n forms = MensalistaForm()\n data = {'mensalistas': mensalistas, 'forms': forms}\n return render(request, 'core/lista_mensalistas.html', data)\n\n@login_required\ndef novo_mensalista(request):\n form = MensalistaForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('core_lista_mensalistas')\n\n@login_required\ndef mensalista_update(request, id):\n data = {}\n mensalista = Mensalista.objects.get(id=id)\n form = MensalistaForm(request.POST or None, instance=mensalista) \n data['mensalista'] = mensalista\n data['form'] = form\n\n if request.method == 'POST' and form.is_valid():\n form.save()\n return redirect('core_lista_mensalistas') \n else:\n return render(request, 'core/mensalista_update.html', data)\n\n@login_required\ndef mensalista_delete(request, id):\n mensalista = Mensalista.objects.get(id=id)\n if request.method == 'POST':\n mensalista.delete()\n return redirect('core_lista_mensalistas')\n else:\n return render(request, 'core/mensalistaconfirme_delete.html', {'mensalista': mensalista})\n\n\n# OS METODOS ABAIXO RETORNA OS MOVMENSALISTAS/ATUALIZA/CADASTRA/DELETA\n\n@login_required\ndef lista_movmensalistas(request):\n movmensalistas = MovMensalista.objects.all()\n forms = MovMensalistaForm()\n data = {'movmensalistas': movmensalistas, 'forms': forms}\n return render(\n request, 'core/lista_movmensalistas.html', data\n )\n\n@login_required\ndef novo_movmensalista(request):\n form = MovMensalistaForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('core_lista_movmensalistas')\n\n@login_required\ndef movmensalista_update(request, id):\n data = {}\n movmensalista = MovMensalista.objects.get(id=id)\n form = MovMensalistaForm(request.POST or None, instance=movmensalista)\n data['movmensalista'] = movmensalista\n data['form'] = form\n\n if request.method == 'POST' and form.is_valid():\n form.save()\n return redirect('core_lista_movmensalistas')\n else:\n return render(request, 'core/movmensalista_update.html', data)\n\n@login_required\ndef movmensalista_delete(request, id):\n movmensalista = MovMensalista.objects.get(id=id)\n if request.method == 'POST':\n movmensalista.delete()\n return redirect('core_lista_movmensalistas')\n else:\n return render(request, 'core/movmensalistaconfirme_delete.html', {'movmensalista': movmensalista})\n","repo_name":"juliobsilva/AppParking","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6731,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"34947175671","text":"import csv;\r\nimport json;\r\n\r\ndata = [];\r\n\r\nwith open(\"rewards.csv\", \"r\") as file:\r\n csvreader = csv.reader(file)\r\n\r\n header = next(csvreader);\r\n\r\n for row in csvreader:\r\n record = {};\r\n\r\n for i in range(len(header)):\r\n value = row[i].strip() if row[i] != \"\" else \"---\";\r\n record[header[i].strip()] = value;\r\n\r\n data.append(record)\r\n\r\nwith open(\"rewards.js\", 'w') as jsfile:\r\n jsfile.write(\"const data = \")\r\n json.dump(data, jsfile, indent=4)\r\n","repo_name":"SilverJolteon/SilverJolteon.github.io","sub_path":"MHP3rd/scripts/kelbi-horn/csv2js.py","file_name":"csv2js.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"71761234295","text":"from pandas import DataFrame\nfrom sklearn import svm, datasets\nfrom joblib import dump\nfrom sklearn.model_selection import train_test_split\n\n\nX, y = datasets.load_iris(return_X_y=True)\ndf = DataFrame(X, columns=[\n \"sepal_length\",\n \"sepal_width\",\n \"petal_length\",\n \"petal_width\",\n])\n\nX_train, X_test, y_train, y_test = train_test_split(\n df, y,\n test_size=0.2,\n stratify=y,\n random_state=42,\n)\nmodel = svm.SVC(\n class_weight='balanced',\n probability=True,\n random_state=42,\n)\nmodel.fit(X_train, y_train)\ndump(model, 'application/model.joblib')\n\nprint(f\"Training Accuracy: {model.score(X_train, y_train):.3%}\")\nprint(f\"Validation Accuracy: {model.score(X_test, y_test):.3%}\")\n","repo_name":"BrokenShell/DS-FastAPI-Template","sub_path":"builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"25100597447","text":"from scenariogeneration import xodr, prettyprint\nimport numpy as np\nimport os\n\n# create a road\nroad = xodr.create_road([xodr.Line(1000)], 0, 2, 2)\n\n## Create the OpenDrive class (Master class)\nodr = xodr.OpenDrive(\"myroad\")\n\n## Finally add roads to Opendrive\nodr.add_road(road)\n\n# Adjust initial positions of the roads looking at succ-pred logic\nodr.adjust_roads_and_lanes()\n\n# After adjustment, repeating objects on side of the road can be added automatically\nguardrail = xodr.Object(\n 0, 0, height=0.3, zOffset=0.4, Type=xodr.ObjectType.barrier, name=\"guardRail\"\n)\nroad.add_object_roadside(guardrail, 0, 0, tOffset=0.8)\n\ndelineator = xodr.Object(\n 0, 0, height=1, zOffset=0, Type=xodr.ObjectType.pole, name=\"delineator\"\n)\nroad.add_object_roadside(delineator, 50, sOffset=25, tOffset=0.85)\n\n## Add some other objects at specific positions\n# single emergency callbox\nemergencyCallbox = xodr.Object(\n 30, -6, Type=xodr.ObjectType.pole, name=\"emergencyCallBox\"\n)\nroad.add_object(emergencyCallbox)\n\n# repeating jersey barrier\njerseyBarrier = xodr.Object(\n 0, 0, height=0.75, zOffset=0, Type=xodr.ObjectType.barrier, name=\"jerseyBarrier\"\n)\njerseyBarrier.repeat(repeatLength=25, repeatDistance=0, sStart=240)\nroad.add_object(jerseyBarrier)\n\n# Print the .xodr file\nprettyprint(odr.get_element())\n\n# write the OpenDRIVE file as xodr using current script name\nodr.write_xml(os.path.basename(__file__).replace(\".py\", \".xodr\"))\n\n# uncomment the following lines to display the road using esmini\n# from scenariogeneration import esmini\n# esmini(odr,os.path.join('esmini'))\n","repo_name":"pyoscx/scenariogeneration","sub_path":"examples/xodr/simple_road_with_objects.py","file_name":"simple_road_with_objects.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":196,"dataset":"github-code","pt":"22"} +{"seq_id":"74323402617","text":"import tomograph\n\nimport sys\nimport time\n\n@tomograph.traced('test server', 'server response', port=80)\ndef server(latency):\n tomograph.annotate('this is an annotation')\n time.sleep(latency)\n tomograph.tag('this is double', 1.1)\n tomograph.tag('this is a string', 'foo')\n tomograph.tag('this is an int', 42)\n\n@tomograph.traced('test client', 'client request')\ndef client(client_overhead, server_latency):\n time.sleep(client_overhead)\n server(server_latency)\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n tomograph.config.set_backends(sys.argv[1:])\n client(0.1, 2.4)\n","repo_name":"timjr/tomograph","sub_path":"tests/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"22"} +{"seq_id":"11951807679","text":"from django.urls import path\nfrom . import views\n\napp_name = 'editors'\n\n\nurlpatterns = [\n path('',views.login,name='login'),\n path('registration/', views.reg, name='registration'),\n path('signup/',views.signup, name='signup'),\n path('signin/',views.signin, name='signin'),\n\n path('edit_corner/',views.edit_corner, name='edit_corner'),\n path('update_news//',views.news_update, name='news_update'),\n path('UpdateNewsHead//',views.news_head_update, name='news_head_update'),\n path('UpdateNewsContent//',views.news_content_update, name='news_content_update'),\n\n\n\n path('n_post/',views.post_news, name='n_post'),\n path('adv_page/',views.adv_page, name='adv_page'),\n path('ad_post/',views.ad_post,name='ad_post'),\n path('ad_view/',views.view_adv,name='view_adv'),\n path('ad_remove//',views.ad_remove,name='ad_remove'),\n path('my_record/',views.my_record,name='my_record'),\n path('all_members/',views.all_members,name='all_members'),\n path('allmembers_reject//',views.all_reject,name='all_reject'),\n path('update_user_type//',views.update_u_type,name='update_u_type'),\n path('pending_members/',views.pending_members,name='pending_members'),\n # path('view_profile/',views.view_profile,name='view_profile'),\n # path('update_profile/',views.update_profile,name='update_profile'),\n path('spl_img/',views.spl_img_page,name='spl_img_page'),\n path('upload_spl_img/',views.upload_spl_img,name='upload_spl_img'),\n path('wish_reject//',views.spl_img_delete,name='spl_img_delete'),\n path('edit_about/',views.editabout,name='editabout'),\n path('add_about_user/',views.add_user_about,name='add_user_about'),\n path('add_about_content/',views.add_about_content,name='add_about_content'),\n path('about_delete_content//',views.delete_about_content,name='delete_about_content'),\n path('about_delete_editors//',views.delete_about_editors,name='delete_about_editors'),\n path('u_approve//',views.u_approve,name='u_approve'),\n path('u_reject//',views.u_reject,name='u_reject'),\n path('n_reject//',views.n_reject,name='n_reject'),\n path('logout/',views.logout_view, name='logout'),\n]","repo_name":"naseef434/tsy_news","sub_path":"editors/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70320093497","text":"import random\r\nrock = '''\r\n _______\r\n---' ____)\r\n (_____)\r\n (_____)\r\n (____)\r\n---.__(___)\r\n'''\r\n\r\npaper = '''\r\n _______\r\n---' ____)____\r\n ______)\r\n _______)\r\n _______)\r\n---.__________)\r\n'''\r\n\r\nscissors = '''\r\n _______\r\n---' ____)____\r\n ______)\r\n __________)\r\n (____)\r\n---.__(___)\r\n'''\r\nimgs = [rock, paper, scissors]\r\n\r\ncomp_choice = random.randint(0, 2)\r\nusr_choice = int(input(\"What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\\n\"))\r\n\r\nif usr_choice < 0 or usr_choice >=3:\r\n print(\"You provided wrong value. Bye\")\r\nelif usr_choice >= 0 or usr_choice <=2:\r\n print(f\"You chose: {imgs[usr_choice]}\\nComputer chose: {imgs[comp_choice]}\")\r\n choices_matrix = [[\"It's a draw.\", \"You lose!\", \"You win!\"],[\"You win\", \"It's a draw.\", \"You lost\"],[\"You lost\", \"You win\", \"It's a draw\"]]\r\n print(choices_matrix[usr_choice][comp_choice])\r\nelse:\r\n print(\"How did you even get here?\")","repo_name":"IriW/rock_paper_scissors_v2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"2596705736","text":"from django.urls import path,include\nfrom . import views\n\napp_name = 'blog'\n\nurlpatterns = [\n path('', views.all_blogs, name='blog_list'),\n path('',views.detail, name='detail'),\n path('create',views.create_blog, name='create_blog'),\n]\n","repo_name":"NikhilP99/illicit","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"27002341364","text":"#!/bin/env python3\n\n# ----------------------------------\n# MySQL Bin Log SQL Extractor\n# Extract bin log for specific table\n# (c) 2022 Toha \n#\n# Last modified: April 22, 2022\n# ----------------------------------\n\nimport re\nimport sys\nfrom os.path import basename, exists, splitext\n\nclass BinlogExtractor:\n dbg = False\n handle = None\n filename = None\n outfilename = None\n tables = []\n\n def __init__(self, filename: str, tables: list) -> None:\n self.filename = filename\n self.tables = tables\n\n def extract(self) -> None:\n if not exists(self.filename):\n print('File not found %s!' % self.filename)\n return\n self.handle = None\n delimiter = '/*!*/;'\n binlog = None\n header = None\n headers = []\n prev = None\n collected = False\n fqtablename = None\n with open(self.filename, 'r') as f:\n for line in f:\n # parse for headers\n if header is None:\n # check for delimeter\n matches = re.search(r'^DELIMITER\\s+(?P.*)', line)\n if matches is not None:\n delimiter = matches.group('DELIM')\n self.log('DELIMITER set to %s...' % delimiter)\n # check for binlog\n if binlog is None and line.find('BINLOG') >= 0:\n binlog = True\n self.debug('Found BINLOG header...')\n # check for binlog end\n if binlog and line.find(delimiter) >= 0:\n header = True\n self.debug('BINLOG header completed...')\n headers.append(line)\n else:\n # find operation\n matches = re.search((\n r'^#(?P\\d{6})\\s+'\n r'(?P